Repository: fabric8io/kansible Branch: master Commit: 457ddca2ac23 Files: 3439 Total size: 22.4 MB Directory structure: gitextract_2u8aug_v/ ├── .dockerignore ├── .gitignore ├── BUILDING.md ├── Dockerfile ├── Dockerfile.scratch ├── Jenkinsfile ├── LICENSE ├── Makefile ├── README.md ├── add-headers.sh ├── ansible/ │ ├── ansible.go │ └── variables.go ├── circle.yml ├── cmd/ │ ├── kill.go │ ├── pod.go │ ├── rc.go │ ├── root.go │ ├── run.go │ └── version.go ├── glide.yaml ├── header.txt ├── headers.yml ├── k8s/ │ └── k8s.go ├── kansible.go ├── log/ │ └── log.go ├── ssh/ │ └── ssh.go ├── tools/ │ └── create-intellij-idea-golib.sh ├── vendor/ │ ├── bitbucket.org/ │ │ └── ww/ │ │ └── goautoneg/ │ │ ├── Makefile │ │ ├── README.txt │ │ ├── autoneg.go │ │ └── autoneg_test.go │ ├── github.com/ │ │ ├── Masterminds/ │ │ │ ├── semver/ │ │ │ │ ├── .travis.yml │ │ │ │ ├── CHANGELOG.md │ │ │ │ ├── LICENSE.txt │ │ │ │ ├── README.md │ │ │ │ ├── appveyor.yml │ │ │ │ ├── benchmark_test.go │ │ │ │ ├── collection.go │ │ │ │ ├── collection_test.go │ │ │ │ ├── constraints.go │ │ │ │ ├── constraints_test.go │ │ │ │ ├── doc.go │ │ │ │ ├── version.go │ │ │ │ └── version_test.go │ │ │ └── vcs/ │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── CHANGELOG.md │ │ │ ├── LICENSE.txt │ │ │ ├── README.md │ │ │ ├── bzr.go │ │ │ ├── bzr_test.go │ │ │ ├── git.go │ │ │ ├── git_test.go │ │ │ ├── hg.go │ │ │ ├── hg_test.go │ │ │ ├── repo.go │ │ │ ├── repo_test.go │ │ │ ├── svn.go │ │ │ ├── svn_test.go │ │ │ ├── vcs_local_lookup.go │ │ │ ├── vcs_remote_lookup.go │ │ │ └── vcs_remote_lookup_test.go │ │ ├── beorn7/ │ │ │ └── perks/ │ │ │ ├── .gitignore │ │ │ ├── README.md │ │ │ ├── histogram/ │ │ │ │ ├── bench_test.go │ │ │ │ ├── histogram.go │ │ │ │ └── histogram_test.go │ │ │ ├── quantile/ │ │ │ │ ├── bench_test.go │ │ │ │ ├── example_test.go │ │ │ │ ├── exampledata.txt │ │ │ │ ├── stream.go │ │ │ │ └── stream_test.go │ │ │ └── topk/ │ │ │ ├── topk.go │ │ │ └── topk_test.go │ │ ├── blang/ │ │ │ └── semver/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── examples/ │ │ │ │ └── main.go │ │ │ ├── json.go │ │ │ ├── json_test.go │ │ │ ├── semver.go │ │ │ ├── semver_test.go │ │ │ ├── sort.go │ │ │ ├── sort_test.go │ │ │ ├── sql.go │ │ │ └── sql_test.go │ │ ├── cloudfoundry-incubator/ │ │ │ └── candiedyaml/ │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── api.go │ │ │ ├── candiedyaml_suite_test.go │ │ │ ├── decode.go │ │ │ ├── decode_test.go │ │ │ ├── emitter.go │ │ │ ├── encode.go │ │ │ ├── encode_test.go │ │ │ ├── fixtures/ │ │ │ │ └── specification/ │ │ │ │ ├── example2_1.yaml │ │ │ │ ├── example2_10.yaml │ │ │ │ ├── example2_11.yaml │ │ │ │ ├── example2_12.yaml │ │ │ │ ├── example2_13.yaml │ │ │ │ ├── example2_14.yaml │ │ │ │ ├── example2_15.yaml │ │ │ │ ├── example2_15_dumped.yaml │ │ │ │ ├── example2_16.yaml │ │ │ │ ├── example2_17.yaml │ │ │ │ ├── example2_17_control.yaml │ │ │ │ ├── example2_17_hexesc.yaml │ │ │ │ ├── example2_17_quoted.yaml │ │ │ │ ├── example2_17_single.yaml │ │ │ │ ├── example2_17_tie_fighter.yaml │ │ │ │ ├── example2_17_unicode.yaml │ │ │ │ ├── example2_18.yaml │ │ │ │ ├── example2_19.yaml │ │ │ │ ├── example2_2.yaml │ │ │ │ ├── example2_20.yaml │ │ │ │ ├── example2_21.yaml │ │ │ │ ├── example2_22.yaml │ │ │ │ ├── example2_23.yaml │ │ │ │ ├── example2_23_application.yaml │ │ │ │ ├── example2_23_non_date.yaml │ │ │ │ ├── example2_23_picture.yaml │ │ │ │ ├── example2_24.yaml │ │ │ │ ├── example2_24_dumped.yaml │ │ │ │ ├── example2_25.yaml │ │ │ │ ├── example2_26.yaml │ │ │ │ ├── example2_27.yaml │ │ │ │ ├── example2_27_dumped.yaml │ │ │ │ ├── example2_28.yaml │ │ │ │ ├── example2_3.yaml │ │ │ │ ├── example2_4.yaml │ │ │ │ ├── example2_5.yaml │ │ │ │ ├── example2_6.yaml │ │ │ │ ├── example2_7.yaml │ │ │ │ ├── example2_8.yaml │ │ │ │ ├── example2_9.yaml │ │ │ │ ├── example_empty.yaml │ │ │ │ └── types/ │ │ │ │ ├── map.yaml │ │ │ │ ├── map_mixed_tags.yaml │ │ │ │ ├── merge.yaml │ │ │ │ ├── omap.yaml │ │ │ │ ├── pairs.yaml │ │ │ │ ├── seq.yaml │ │ │ │ ├── set.yaml │ │ │ │ ├── v.yaml │ │ │ │ └── value.yaml │ │ │ ├── libyaml-LICENSE │ │ │ ├── parser.go │ │ │ ├── parser_test.go │ │ │ ├── reader.go │ │ │ ├── reader_test.go │ │ │ ├── resolver.go │ │ │ ├── resolver_test.go │ │ │ ├── run_parser.go │ │ │ ├── scanner.go │ │ │ ├── scanner_test.go │ │ │ ├── tags.go │ │ │ ├── writer.go │ │ │ ├── yaml_definesh.go │ │ │ ├── yaml_privateh.go │ │ │ └── yamlh.go │ │ ├── davecgh/ │ │ │ └── go-spew/ │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── cov_report.sh │ │ │ ├── spew/ │ │ │ │ ├── common.go │ │ │ │ ├── common_test.go │ │ │ │ ├── config.go │ │ │ │ ├── doc.go │ │ │ │ ├── dump.go │ │ │ │ ├── dump_test.go │ │ │ │ ├── dumpcgo_test.go │ │ │ │ ├── dumpnocgo_test.go │ │ │ │ ├── example_test.go │ │ │ │ ├── format.go │ │ │ │ ├── format_test.go │ │ │ │ ├── internal_test.go │ │ │ │ ├── spew.go │ │ │ │ ├── spew_test.go │ │ │ │ └── testdata/ │ │ │ │ └── dumpcgo.go │ │ │ └── test_coverage.txt │ │ ├── docker/ │ │ │ ├── docker/ │ │ │ │ ├── .dockerignore │ │ │ │ ├── .gitignore │ │ │ │ ├── .mailmap │ │ │ │ ├── AUTHORS │ │ │ │ ├── CHANGELOG.md │ │ │ │ ├── CONTRIBUTING.md │ │ │ │ ├── Dockerfile │ │ │ │ ├── Dockerfile.simple │ │ │ │ ├── LICENSE │ │ │ │ ├── MAINTAINERS │ │ │ │ ├── Makefile │ │ │ │ ├── NOTICE │ │ │ │ ├── README.md │ │ │ │ ├── ROADMAP.md │ │ │ │ ├── VERSION │ │ │ │ ├── api/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── api_unit_test.go │ │ │ │ │ ├── client/ │ │ │ │ │ │ ├── attach.go │ │ │ │ │ │ ├── build.go │ │ │ │ │ │ ├── cli.go │ │ │ │ │ │ ├── client.go │ │ │ │ │ │ ├── commit.go │ │ │ │ │ │ ├── cp.go │ │ │ │ │ │ ├── create.go │ │ │ │ │ │ ├── diff.go │ │ │ │ │ │ ├── events.go │ │ │ │ │ │ ├── exec.go │ │ │ │ │ │ ├── export.go │ │ │ │ │ │ ├── help.go │ │ │ │ │ │ ├── hijack.go │ │ │ │ │ │ ├── history.go │ │ │ │ │ │ ├── images.go │ │ │ │ │ │ ├── import.go │ │ │ │ │ │ ├── info.go │ │ │ │ │ │ ├── inspect.go │ │ │ │ │ │ ├── kill.go │ │ │ │ │ │ ├── load.go │ │ │ │ │ │ ├── login.go │ │ │ │ │ │ ├── logout.go │ │ │ │ │ │ ├── logs.go │ │ │ │ │ │ ├── network.go │ │ │ │ │ │ ├── pause.go │ │ │ │ │ │ ├── port.go │ │ │ │ │ │ ├── ps.go │ │ │ │ │ │ ├── pull.go │ │ │ │ │ │ ├── push.go │ │ │ │ │ │ ├── rename.go │ │ │ │ │ │ ├── restart.go │ │ │ │ │ │ ├── rm.go │ │ │ │ │ │ ├── rmi.go │ │ │ │ │ │ ├── run.go │ │ │ │ │ │ ├── save.go │ │ │ │ │ │ ├── search.go │ │ │ │ │ │ ├── service.go │ │ │ │ │ │ ├── start.go │ │ │ │ │ │ ├── stats.go │ │ │ │ │ │ ├── stats_unit_test.go │ │ │ │ │ │ ├── stop.go │ │ │ │ │ │ ├── tag.go │ │ │ │ │ │ ├── top.go │ │ │ │ │ │ ├── unpause.go │ │ │ │ │ │ ├── utils.go │ │ │ │ │ │ ├── version.go │ │ │ │ │ │ └── wait.go │ │ │ │ │ ├── common.go │ │ │ │ │ ├── server/ │ │ │ │ │ │ ├── form.go │ │ │ │ │ │ ├── form_test.go │ │ │ │ │ │ ├── profiler.go │ │ │ │ │ │ ├── server.go │ │ │ │ │ │ ├── server_experimental.go │ │ │ │ │ │ ├── server_linux.go │ │ │ │ │ │ ├── server_linux_test.go │ │ │ │ │ │ ├── server_stub.go │ │ │ │ │ │ └── server_windows.go │ │ │ │ │ └── types/ │ │ │ │ │ ├── stats.go │ │ │ │ │ └── types.go │ │ │ │ ├── builder/ │ │ │ │ │ ├── bflag.go │ │ │ │ │ ├── bflag_test.go │ │ │ │ │ ├── command/ │ │ │ │ │ │ └── command.go │ │ │ │ │ ├── dispatchers.go │ │ │ │ │ ├── evaluator.go │ │ │ │ │ ├── internals.go │ │ │ │ │ ├── internals_linux.go │ │ │ │ │ ├── internals_windows.go │ │ │ │ │ ├── job.go │ │ │ │ │ ├── job_test.go │ │ │ │ │ ├── parser/ │ │ │ │ │ │ ├── dumper/ │ │ │ │ │ │ │ └── main.go │ │ │ │ │ │ ├── json_test.go │ │ │ │ │ │ ├── line_parsers.go │ │ │ │ │ │ ├── parser.go │ │ │ │ │ │ ├── parser_test.go │ │ │ │ │ │ ├── testfiles/ │ │ │ │ │ │ │ ├── ADD-COPY-with-JSON/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── brimstone-consuldock/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── brimstone-docker-consul/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── continueIndent/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── cpuguy83-nagios/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── docker/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── env/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── escapes/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── flags/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── influxdb/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── jeztah-invalid-json-json-inside-string/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── jeztah-invalid-json-json-inside-string-double/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── jeztah-invalid-json-single-quotes/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── jeztah-invalid-json-unterminated-bracket/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── jeztah-invalid-json-unterminated-string/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── json/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── kartar-entrypoint-oddities/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── lk4d4-the-edge-case-generator/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── mail/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── multiple-volumes/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── mumble/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── nginx/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── tf2/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ ├── weechat/ │ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ │ └── result │ │ │ │ │ │ │ └── znc/ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ └── result │ │ │ │ │ │ ├── testfiles-negative/ │ │ │ │ │ │ │ ├── env_no_value/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ └── shykes-nested-json/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ └── utils.go │ │ │ │ │ ├── shell_parser.go │ │ │ │ │ ├── shell_parser_test.go │ │ │ │ │ ├── support.go │ │ │ │ │ ├── support_test.go │ │ │ │ │ └── words │ │ │ │ ├── cliconfig/ │ │ │ │ │ ├── config.go │ │ │ │ │ └── config_test.go │ │ │ │ ├── contrib/ │ │ │ │ │ ├── README │ │ │ │ │ ├── REVIEWERS │ │ │ │ │ ├── apparmor/ │ │ │ │ │ │ └── docker │ │ │ │ │ ├── builder/ │ │ │ │ │ │ ├── deb/ │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ ├── build.sh │ │ │ │ │ │ │ ├── debian-jessie/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ ├── debian-stretch/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ ├── debian-wheezy/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ ├── generate.sh │ │ │ │ │ │ │ ├── ubuntu-debootstrap-precise/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ ├── ubuntu-debootstrap-trusty/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ ├── ubuntu-debootstrap-utopic/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ ├── ubuntu-debootstrap-vivid/ │ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ │ └── ubuntu-debootstrap-wily/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ └── rpm/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── build.sh │ │ │ │ │ │ ├── centos-7/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ ├── fedora-20/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ ├── fedora-21/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ ├── fedora-22/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ ├── generate.sh │ │ │ │ │ │ └── oraclelinux-7/ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ ├── check-config.sh │ │ │ │ │ ├── completion/ │ │ │ │ │ │ ├── REVIEWERS │ │ │ │ │ │ ├── bash/ │ │ │ │ │ │ │ └── docker │ │ │ │ │ │ ├── fish/ │ │ │ │ │ │ │ └── docker.fish │ │ │ │ │ │ └── zsh/ │ │ │ │ │ │ ├── REVIEWERS │ │ │ │ │ │ └── _docker │ │ │ │ │ ├── desktop-integration/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── chromium/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ └── gparted/ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ ├── docker-device-tool/ │ │ │ │ │ │ └── device_tool.go │ │ │ │ │ ├── dockerize-disk.sh │ │ │ │ │ ├── download-frozen-image.sh │ │ │ │ │ ├── host-integration/ │ │ │ │ │ │ ├── Dockerfile.dev │ │ │ │ │ │ ├── Dockerfile.min │ │ │ │ │ │ ├── manager/ │ │ │ │ │ │ │ ├── systemd │ │ │ │ │ │ │ └── upstart │ │ │ │ │ │ ├── manager.go │ │ │ │ │ │ └── manager.sh │ │ │ │ │ ├── httpserver/ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ └── server.go │ │ │ │ │ ├── init/ │ │ │ │ │ │ ├── openrc/ │ │ │ │ │ │ │ ├── docker.confd │ │ │ │ │ │ │ └── docker.initd │ │ │ │ │ │ ├── systemd/ │ │ │ │ │ │ │ ├── REVIEWERS │ │ │ │ │ │ │ ├── docker.service │ │ │ │ │ │ │ └── docker.socket │ │ │ │ │ │ ├── sysvinit-debian/ │ │ │ │ │ │ │ ├── docker │ │ │ │ │ │ │ └── docker.default │ │ │ │ │ │ ├── sysvinit-redhat/ │ │ │ │ │ │ │ ├── docker │ │ │ │ │ │ │ └── docker.sysconfig │ │ │ │ │ │ └── upstart/ │ │ │ │ │ │ ├── REVIEWERS │ │ │ │ │ │ └── docker.conf │ │ │ │ │ ├── mkimage/ │ │ │ │ │ │ ├── .febootstrap-minimize │ │ │ │ │ │ ├── busybox-static │ │ │ │ │ │ ├── debootstrap │ │ │ │ │ │ ├── mageia-urpmi │ │ │ │ │ │ └── rinse │ │ │ │ │ ├── mkimage-alpine.sh │ │ │ │ │ ├── mkimage-arch-pacman.conf │ │ │ │ │ ├── mkimage-arch.sh │ │ │ │ │ ├── mkimage-busybox.sh │ │ │ │ │ ├── mkimage-crux.sh │ │ │ │ │ ├── mkimage-debootstrap.sh │ │ │ │ │ ├── mkimage-rinse.sh │ │ │ │ │ ├── mkimage-yum.sh │ │ │ │ │ ├── mkimage.sh │ │ │ │ │ ├── mkseccomp.pl │ │ │ │ │ ├── mkseccomp.sample │ │ │ │ │ ├── nuke-graph-directory.sh │ │ │ │ │ ├── project-stats.sh │ │ │ │ │ ├── report-issue.sh │ │ │ │ │ ├── reprepro/ │ │ │ │ │ │ └── suites.sh │ │ │ │ │ ├── syntax/ │ │ │ │ │ │ ├── kate/ │ │ │ │ │ │ │ └── Dockerfile.xml │ │ │ │ │ │ ├── nano/ │ │ │ │ │ │ │ ├── Dockerfile.nanorc │ │ │ │ │ │ │ └── README.md │ │ │ │ │ │ ├── textmate/ │ │ │ │ │ │ │ ├── Docker.tmbundle/ │ │ │ │ │ │ │ │ ├── Preferences/ │ │ │ │ │ │ │ │ │ └── Dockerfile.tmPreferences │ │ │ │ │ │ │ │ ├── Syntaxes/ │ │ │ │ │ │ │ │ │ └── Dockerfile.tmLanguage │ │ │ │ │ │ │ │ └── info.plist │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ └── REVIEWERS │ │ │ │ │ │ └── vim/ │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── doc/ │ │ │ │ │ │ │ └── dockerfile.txt │ │ │ │ │ │ ├── ftdetect/ │ │ │ │ │ │ │ └── dockerfile.vim │ │ │ │ │ │ └── syntax/ │ │ │ │ │ │ └── dockerfile.vim │ │ │ │ │ ├── udev/ │ │ │ │ │ │ └── 80-docker.rules │ │ │ │ │ └── vagrant-docker/ │ │ │ │ │ └── README.md │ │ │ │ ├── daemon/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── archive.go │ │ │ │ │ ├── attach.go │ │ │ │ │ ├── changes.go │ │ │ │ │ ├── commit.go │ │ │ │ │ ├── config.go │ │ │ │ │ ├── config_experimental.go │ │ │ │ │ ├── config_linux.go │ │ │ │ │ ├── config_stub.go │ │ │ │ │ ├── config_windows.go │ │ │ │ │ ├── container.go │ │ │ │ │ ├── container_unit_test.go │ │ │ │ │ ├── container_unix.go │ │ │ │ │ ├── container_windows.go │ │ │ │ │ ├── create.go │ │ │ │ │ ├── daemon.go │ │ │ │ │ ├── daemon_aufs.go │ │ │ │ │ ├── daemon_btrfs.go │ │ │ │ │ ├── daemon_devicemapper.go │ │ │ │ │ ├── daemon_no_aufs.go │ │ │ │ │ ├── daemon_overlay.go │ │ │ │ │ ├── daemon_test.go │ │ │ │ │ ├── daemon_unit_test.go │ │ │ │ │ ├── daemon_unix.go │ │ │ │ │ ├── daemon_windows.go │ │ │ │ │ ├── daemon_zfs.go │ │ │ │ │ ├── debugtrap_unix.go │ │ │ │ │ ├── debugtrap_unsupported.go │ │ │ │ │ ├── debugtrap_windows.go │ │ │ │ │ ├── delete.go │ │ │ │ │ ├── events/ │ │ │ │ │ │ ├── events.go │ │ │ │ │ │ └── events_test.go │ │ │ │ │ ├── exec.go │ │ │ │ │ ├── exec_linux.go │ │ │ │ │ ├── exec_windows.go │ │ │ │ │ ├── execdriver/ │ │ │ │ │ │ ├── driver.go │ │ │ │ │ │ ├── driver_linux.go │ │ │ │ │ │ ├── execdrivers/ │ │ │ │ │ │ │ ├── execdrivers_linux.go │ │ │ │ │ │ │ └── execdrivers_windows.go │ │ │ │ │ │ ├── lxc/ │ │ │ │ │ │ │ ├── driver.go │ │ │ │ │ │ │ ├── info.go │ │ │ │ │ │ │ ├── info_test.go │ │ │ │ │ │ │ ├── init.go │ │ │ │ │ │ │ ├── lxc_init_linux.go │ │ │ │ │ │ │ ├── lxc_init_unsupported.go │ │ │ │ │ │ │ ├── lxc_template.go │ │ │ │ │ │ │ └── lxc_template_unit_test.go │ │ │ │ │ │ ├── native/ │ │ │ │ │ │ │ ├── create.go │ │ │ │ │ │ │ ├── driver.go │ │ │ │ │ │ │ ├── driver_unsupported.go │ │ │ │ │ │ │ ├── driver_unsupported_nocgo.go │ │ │ │ │ │ │ ├── exec.go │ │ │ │ │ │ │ ├── info.go │ │ │ │ │ │ │ ├── init.go │ │ │ │ │ │ │ └── template/ │ │ │ │ │ │ │ └── default_template.go │ │ │ │ │ │ ├── pipes.go │ │ │ │ │ │ ├── termconsole.go │ │ │ │ │ │ ├── utils.go │ │ │ │ │ │ └── windows/ │ │ │ │ │ │ ├── checkoptions.go │ │ │ │ │ │ ├── clean.go │ │ │ │ │ │ ├── exec.go │ │ │ │ │ │ ├── getpids.go │ │ │ │ │ │ ├── info.go │ │ │ │ │ │ ├── namedpipes.go │ │ │ │ │ │ ├── pauseunpause.go │ │ │ │ │ │ ├── run.go │ │ │ │ │ │ ├── stats.go │ │ │ │ │ │ ├── stdconsole.go │ │ │ │ │ │ ├── terminatekill.go │ │ │ │ │ │ ├── ttyconsole.go │ │ │ │ │ │ ├── unsupported.go │ │ │ │ │ │ └── windows.go │ │ │ │ │ ├── export.go │ │ │ │ │ ├── graphdriver/ │ │ │ │ │ │ ├── aufs/ │ │ │ │ │ │ │ ├── aufs.go │ │ │ │ │ │ │ ├── aufs_test.go │ │ │ │ │ │ │ ├── dirs.go │ │ │ │ │ │ │ ├── migrate.go │ │ │ │ │ │ │ ├── mount.go │ │ │ │ │ │ │ ├── mount_linux.go │ │ │ │ │ │ │ └── mount_unsupported.go │ │ │ │ │ │ ├── btrfs/ │ │ │ │ │ │ │ ├── btrfs.go │ │ │ │ │ │ │ ├── btrfs_test.go │ │ │ │ │ │ │ ├── dummy_unsupported.go │ │ │ │ │ │ │ ├── version.go │ │ │ │ │ │ │ ├── version_none.go │ │ │ │ │ │ │ └── version_test.go │ │ │ │ │ │ ├── devmapper/ │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ ├── deviceset.go │ │ │ │ │ │ │ ├── devmapper_doc.go │ │ │ │ │ │ │ ├── devmapper_test.go │ │ │ │ │ │ │ ├── driver.go │ │ │ │ │ │ │ └── mount.go │ │ │ │ │ │ ├── driver.go │ │ │ │ │ │ ├── driver_linux.go │ │ │ │ │ │ ├── driver_unsupported.go │ │ │ │ │ │ ├── driver_windows.go │ │ │ │ │ │ ├── fsdiff.go │ │ │ │ │ │ ├── graphtest/ │ │ │ │ │ │ │ └── graphtest.go │ │ │ │ │ │ ├── overlay/ │ │ │ │ │ │ │ ├── copy.go │ │ │ │ │ │ │ ├── overlay.go │ │ │ │ │ │ │ ├── overlay_test.go │ │ │ │ │ │ │ └── overlay_unsupported.go │ │ │ │ │ │ ├── vfs/ │ │ │ │ │ │ │ ├── driver.go │ │ │ │ │ │ │ ├── driver_unsupported.go │ │ │ │ │ │ │ └── vfs_test.go │ │ │ │ │ │ ├── windows/ │ │ │ │ │ │ │ └── windows.go │ │ │ │ │ │ └── zfs/ │ │ │ │ │ │ ├── MAINTAINERS │ │ │ │ │ │ ├── zfs.go │ │ │ │ │ │ ├── zfs_freebsd.go │ │ │ │ │ │ ├── zfs_linux.go │ │ │ │ │ │ ├── zfs_test.go │ │ │ │ │ │ └── zfs_unsupported.go │ │ │ │ │ ├── history.go │ │ │ │ │ ├── image_delete.go │ │ │ │ │ ├── info.go │ │ │ │ │ ├── inspect.go │ │ │ │ │ ├── kill.go │ │ │ │ │ ├── list.go │ │ │ │ │ ├── logdrivers_linux.go │ │ │ │ │ ├── logdrivers_windows.go │ │ │ │ │ ├── logger/ │ │ │ │ │ │ ├── copier.go │ │ │ │ │ │ ├── copier_test.go │ │ │ │ │ │ ├── factory.go │ │ │ │ │ │ ├── fluentd/ │ │ │ │ │ │ │ └── fluentd.go │ │ │ │ │ │ ├── gelf/ │ │ │ │ │ │ │ ├── gelf.go │ │ │ │ │ │ │ └── gelf_unsupported.go │ │ │ │ │ │ ├── journald/ │ │ │ │ │ │ │ ├── journald.go │ │ │ │ │ │ │ └── journald_unsupported.go │ │ │ │ │ │ ├── jsonfilelog/ │ │ │ │ │ │ │ ├── jsonfilelog.go │ │ │ │ │ │ │ └── jsonfilelog_test.go │ │ │ │ │ │ ├── logger.go │ │ │ │ │ │ └── syslog/ │ │ │ │ │ │ ├── syslog.go │ │ │ │ │ │ └── syslog_unsupported.go │ │ │ │ │ ├── logs.go │ │ │ │ │ ├── monitor.go │ │ │ │ │ ├── network/ │ │ │ │ │ │ └── settings.go │ │ │ │ │ ├── pause.go │ │ │ │ │ ├── rename.go │ │ │ │ │ ├── resize.go │ │ │ │ │ ├── restart.go │ │ │ │ │ ├── start.go │ │ │ │ │ ├── state.go │ │ │ │ │ ├── state_test.go │ │ │ │ │ ├── stats.go │ │ │ │ │ ├── stats_collector_unix.go │ │ │ │ │ ├── stats_collector_windows.go │ │ │ │ │ ├── stats_linux.go │ │ │ │ │ ├── stats_windows.go │ │ │ │ │ ├── stop.go │ │ │ │ │ ├── top.go │ │ │ │ │ ├── unpause.go │ │ │ │ │ ├── utils_nounix.go │ │ │ │ │ ├── utils_test.go │ │ │ │ │ ├── utils_unix.go │ │ │ │ │ ├── volumes.go │ │ │ │ │ ├── volumes_linux.go │ │ │ │ │ ├── volumes_linux_unit_test.go │ │ │ │ │ ├── volumes_unit_test.go │ │ │ │ │ ├── volumes_windows.go │ │ │ │ │ └── wait.go │ │ │ │ ├── docker/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── client.go │ │ │ │ │ ├── daemon.go │ │ │ │ │ ├── daemon_unix.go │ │ │ │ │ ├── daemon_windows.go │ │ │ │ │ ├── docker.go │ │ │ │ │ ├── docker_windows.go │ │ │ │ │ ├── flags.go │ │ │ │ │ └── log.go │ │ │ │ ├── dockerinit/ │ │ │ │ │ └── dockerinit.go │ │ │ │ ├── docs/ │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── Dockerfile │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── README.md │ │ │ │ │ ├── article-img/ │ │ │ │ │ │ ├── ipv6_basic_host_config.gliffy │ │ │ │ │ │ ├── ipv6_ndp_proxying.gliffy │ │ │ │ │ │ ├── ipv6_routed_network_example.gliffy │ │ │ │ │ │ ├── ipv6_slash64_subnet_config.gliffy │ │ │ │ │ │ └── ipv6_switched_network_example.gliffy │ │ │ │ │ ├── articles/ │ │ │ │ │ │ ├── ambassador_pattern_linking.md │ │ │ │ │ │ ├── b2d_volume_resize.md │ │ │ │ │ │ ├── baseimages.md │ │ │ │ │ │ ├── basics.md │ │ │ │ │ │ ├── certificates.md │ │ │ │ │ │ ├── cfengine_process_management.md │ │ │ │ │ │ ├── chef.md │ │ │ │ │ │ ├── configuring.md │ │ │ │ │ │ ├── dockerfile_best-practices.md │ │ │ │ │ │ ├── dsc.md │ │ │ │ │ │ ├── host_integration.md │ │ │ │ │ │ ├── https/ │ │ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ │ │ ├── Makefile │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ ├── make_certs.sh │ │ │ │ │ │ │ └── parsedocs.sh │ │ │ │ │ │ ├── https.md │ │ │ │ │ │ ├── networking.md │ │ │ │ │ │ ├── puppet.md │ │ │ │ │ │ ├── registry_mirror.md │ │ │ │ │ │ ├── runmetrics.md │ │ │ │ │ │ ├── security.md │ │ │ │ │ │ ├── systemd.md │ │ │ │ │ │ └── using_supervisord.md │ │ │ │ │ ├── docker-hub/ │ │ │ │ │ │ ├── accounts.md │ │ │ │ │ │ ├── builds.md │ │ │ │ │ │ ├── home.md │ │ │ │ │ │ ├── index.md │ │ │ │ │ │ ├── official_repos.md │ │ │ │ │ │ ├── repos.md │ │ │ │ │ │ └── userguide.md │ │ │ │ │ ├── examples/ │ │ │ │ │ │ ├── apt-cacher-ng.Dockerfile │ │ │ │ │ │ ├── apt-cacher-ng.md │ │ │ │ │ │ ├── couchdb_data_volumes.md │ │ │ │ │ │ ├── mongodb/ │ │ │ │ │ │ │ └── Dockerfile │ │ │ │ │ │ ├── mongodb.md │ │ │ │ │ │ ├── nodejs_web_app.md │ │ │ │ │ │ ├── postgresql_service.Dockerfile │ │ │ │ │ │ ├── postgresql_service.md │ │ │ │ │ │ ├── running_redis_service.md │ │ │ │ │ │ ├── running_riak_service.Dockerfile │ │ │ │ │ │ ├── running_riak_service.md │ │ │ │ │ │ ├── running_ssh_service.Dockerfile │ │ │ │ │ │ ├── running_ssh_service.md │ │ │ │ │ │ └── supervisord.conf │ │ │ │ │ ├── extend/ │ │ │ │ │ │ ├── index.md │ │ │ │ │ │ ├── plugin_api.md │ │ │ │ │ │ ├── plugins.md │ │ │ │ │ │ └── plugins_volume.md │ │ │ │ │ ├── installation/ │ │ │ │ │ │ ├── SUSE.md │ │ │ │ │ │ ├── amazon.md │ │ │ │ │ │ ├── archlinux.md │ │ │ │ │ │ ├── azure.md │ │ │ │ │ │ ├── binaries.md │ │ │ │ │ │ ├── centos.md │ │ │ │ │ │ ├── cruxlinux.md │ │ │ │ │ │ ├── debian.md │ │ │ │ │ │ ├── fedora.md │ │ │ │ │ │ ├── frugalware.md │ │ │ │ │ │ ├── gentoolinux.md │ │ │ │ │ │ ├── google.md │ │ │ │ │ │ ├── index.md │ │ │ │ │ │ ├── joyent.md │ │ │ │ │ │ ├── mac.md │ │ │ │ │ │ ├── oracle.md │ │ │ │ │ │ ├── rackspace.md │ │ │ │ │ │ ├── rhel.md │ │ │ │ │ │ ├── softlayer.md │ │ │ │ │ │ ├── ubuntulinux.md │ │ │ │ │ │ └── windows.md │ │ │ │ │ ├── introduction/ │ │ │ │ │ │ └── understanding-docker.md │ │ │ │ │ ├── misc/ │ │ │ │ │ │ ├── faq.md │ │ │ │ │ │ ├── index.md │ │ │ │ │ │ ├── release-notes.md │ │ │ │ │ │ └── search.md │ │ │ │ │ ├── project/ │ │ │ │ │ │ ├── advanced-contributing.md │ │ │ │ │ │ ├── coding-style.md │ │ │ │ │ │ ├── create-pr.md │ │ │ │ │ │ ├── doc-style.md │ │ │ │ │ │ ├── find-an-issue.md │ │ │ │ │ │ ├── get-help.md │ │ │ │ │ │ ├── images/ │ │ │ │ │ │ │ ├── existing_issue.snagproj │ │ │ │ │ │ │ └── proposal.snagproj │ │ │ │ │ │ ├── make-a-contribution.md │ │ │ │ │ │ ├── review-pr.md │ │ │ │ │ │ ├── set-up-dev-env.md │ │ │ │ │ │ ├── set-up-git.md │ │ │ │ │ │ ├── software-req-win.md │ │ │ │ │ │ ├── software-required.md │ │ │ │ │ │ ├── test-and-docs.md │ │ │ │ │ │ ├── who-written-for.md │ │ │ │ │ │ └── work-issue.md │ │ │ │ │ ├── reference/ │ │ │ │ │ │ ├── api/ │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ ├── docker-io_api.md │ │ │ │ │ │ │ ├── docker_io_accounts_api.md │ │ │ │ │ │ │ ├── docker_remote_api.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.0.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.1.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.10.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.11.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.12.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.13.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.14.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.15.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.16.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.17.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.18.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.19.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.2.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.20.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.3.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.4.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.5.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.6.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.7.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.8.md │ │ │ │ │ │ │ ├── docker_remote_api_v1.9.md │ │ │ │ │ │ │ ├── hub_registry_spec.md │ │ │ │ │ │ │ ├── images/ │ │ │ │ │ │ │ │ └── event_state.gliffy │ │ │ │ │ │ │ ├── registry_api.md │ │ │ │ │ │ │ ├── registry_api_client_libraries.md │ │ │ │ │ │ │ └── remote_api_client_libraries.md │ │ │ │ │ │ ├── builder.md │ │ │ │ │ │ ├── commandline/ │ │ │ │ │ │ │ ├── attach.md │ │ │ │ │ │ │ ├── build.md │ │ │ │ │ │ │ ├── cli.md │ │ │ │ │ │ │ ├── commit.md │ │ │ │ │ │ │ ├── cp.md │ │ │ │ │ │ │ ├── create.md │ │ │ │ │ │ │ ├── daemon.md │ │ │ │ │ │ │ ├── diff.md │ │ │ │ │ │ │ ├── events.md │ │ │ │ │ │ │ ├── exec.md │ │ │ │ │ │ │ ├── export.md │ │ │ │ │ │ │ ├── history.md │ │ │ │ │ │ │ ├── images.md │ │ │ │ │ │ │ ├── import.md │ │ │ │ │ │ │ ├── info.md │ │ │ │ │ │ │ ├── inspect.md │ │ │ │ │ │ │ ├── kill.md │ │ │ │ │ │ │ ├── load.md │ │ │ │ │ │ │ ├── login.md │ │ │ │ │ │ │ ├── logout.md │ │ │ │ │ │ │ ├── logs.md │ │ │ │ │ │ │ ├── pause.md │ │ │ │ │ │ │ ├── port.md │ │ │ │ │ │ │ ├── ps.md │ │ │ │ │ │ │ ├── pull.md │ │ │ │ │ │ │ ├── push.md │ │ │ │ │ │ │ ├── rename.md │ │ │ │ │ │ │ ├── restart.md │ │ │ │ │ │ │ ├── rm.md │ │ │ │ │ │ │ ├── rmi.md │ │ │ │ │ │ │ ├── run.md │ │ │ │ │ │ │ ├── save.md │ │ │ │ │ │ │ ├── search.md │ │ │ │ │ │ │ ├── start.md │ │ │ │ │ │ │ ├── stats.md │ │ │ │ │ │ │ ├── stop.md │ │ │ │ │ │ │ ├── tag.md │ │ │ │ │ │ │ ├── top.md │ │ │ │ │ │ │ ├── unpause.md │ │ │ │ │ │ │ ├── version.md │ │ │ │ │ │ │ └── wait.md │ │ │ │ │ │ ├── glossary.md │ │ │ │ │ │ ├── logging/ │ │ │ │ │ │ │ ├── fluentd.md │ │ │ │ │ │ │ ├── index.md │ │ │ │ │ │ │ └── journald.md │ │ │ │ │ │ └── run.md │ │ │ │ │ ├── static_files/ │ │ │ │ │ │ └── README.md │ │ │ │ │ ├── terms/ │ │ │ │ │ │ ├── container.md │ │ │ │ │ │ ├── filesystem.md │ │ │ │ │ │ ├── image.md │ │ │ │ │ │ ├── layer.md │ │ │ │ │ │ ├── registry.md │ │ │ │ │ │ └── repository.md │ │ │ │ │ ├── touch-up.sh │ │ │ │ │ └── userguide/ │ │ │ │ │ ├── dockerhub.md │ │ │ │ │ ├── dockerimages.md │ │ │ │ │ ├── dockerizing.md │ │ │ │ │ ├── dockerlinks.md │ │ │ │ │ ├── dockerrepos.md │ │ │ │ │ ├── dockervolumes.md │ │ │ │ │ ├── index.md │ │ │ │ │ ├── labels-custom-metadata.md │ │ │ │ │ ├── level1.md │ │ │ │ │ ├── level2.md │ │ │ │ │ └── usingdocker.md │ │ │ │ ├── experimental/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── compose_swarm_networking.md │ │ │ │ │ ├── networking.md │ │ │ │ │ ├── networking_api.md │ │ │ │ │ └── plugins_network.md │ │ │ │ ├── graph/ │ │ │ │ │ ├── export.go │ │ │ │ │ ├── graph.go │ │ │ │ │ ├── graph_test.go │ │ │ │ │ ├── graph_unix.go │ │ │ │ │ ├── graph_windows.go │ │ │ │ │ ├── history.go │ │ │ │ │ ├── import.go │ │ │ │ │ ├── list.go │ │ │ │ │ ├── load.go │ │ │ │ │ ├── load_unsupported.go │ │ │ │ │ ├── mutex.go │ │ │ │ │ ├── pools_test.go │ │ │ │ │ ├── pull.go │ │ │ │ │ ├── pull_v1.go │ │ │ │ │ ├── pull_v2.go │ │ │ │ │ ├── push.go │ │ │ │ │ ├── push_v1.go │ │ │ │ │ ├── push_v2.go │ │ │ │ │ ├── registry.go │ │ │ │ │ ├── service.go │ │ │ │ │ ├── tags/ │ │ │ │ │ │ ├── tags.go │ │ │ │ │ │ └── tags_unit_test.go │ │ │ │ │ ├── tags.go │ │ │ │ │ └── tags_unit_test.go │ │ │ │ ├── hack/ │ │ │ │ │ ├── .vendor-helpers.sh │ │ │ │ │ ├── dind │ │ │ │ │ ├── generate-authors.sh │ │ │ │ │ ├── install.sh │ │ │ │ │ ├── make/ │ │ │ │ │ │ ├── .build-deb/ │ │ │ │ │ │ │ ├── compat │ │ │ │ │ │ │ ├── control │ │ │ │ │ │ │ ├── docker-engine.bash-completion │ │ │ │ │ │ │ ├── docker-engine.install │ │ │ │ │ │ │ ├── docker-engine.manpages │ │ │ │ │ │ │ ├── docker-engine.postinst │ │ │ │ │ │ │ ├── docs │ │ │ │ │ │ │ └── rules │ │ │ │ │ │ ├── .build-rpm/ │ │ │ │ │ │ │ └── docker-engine.spec │ │ │ │ │ │ ├── .dockerinit │ │ │ │ │ │ ├── .dockerinit-gccgo │ │ │ │ │ │ ├── .ensure-emptyfs │ │ │ │ │ │ ├── .ensure-frozen-images │ │ │ │ │ │ ├── .ensure-httpserver │ │ │ │ │ │ ├── .go-autogen │ │ │ │ │ │ ├── .go-compile-test-dir │ │ │ │ │ │ ├── .integration-daemon-setup │ │ │ │ │ │ ├── .integration-daemon-start │ │ │ │ │ │ ├── .integration-daemon-stop │ │ │ │ │ │ ├── .resources-windows/ │ │ │ │ │ │ │ └── docker.exe.manifest │ │ │ │ │ │ ├── .validate │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── binary │ │ │ │ │ │ ├── build-deb │ │ │ │ │ │ ├── build-rpm │ │ │ │ │ │ ├── cover │ │ │ │ │ │ ├── cross │ │ │ │ │ │ ├── dynbinary │ │ │ │ │ │ ├── dyngccgo │ │ │ │ │ │ ├── gccgo │ │ │ │ │ │ ├── release-deb │ │ │ │ │ │ ├── release-rpm │ │ │ │ │ │ ├── sign-repos │ │ │ │ │ │ ├── test-docker-py │ │ │ │ │ │ ├── test-integration-cli │ │ │ │ │ │ ├── test-unit │ │ │ │ │ │ ├── tgz │ │ │ │ │ │ ├── ubuntu │ │ │ │ │ │ ├── validate-dco │ │ │ │ │ │ ├── validate-gofmt │ │ │ │ │ │ ├── validate-lint │ │ │ │ │ │ ├── validate-pkg │ │ │ │ │ │ ├── validate-test │ │ │ │ │ │ ├── validate-toml │ │ │ │ │ │ └── validate-vet │ │ │ │ │ ├── make.sh │ │ │ │ │ ├── release.sh │ │ │ │ │ └── vendor.sh │ │ │ │ ├── image/ │ │ │ │ │ ├── image.go │ │ │ │ │ └── spec/ │ │ │ │ │ └── v1.md │ │ │ │ ├── integration-cli/ │ │ │ │ │ ├── check_test.go │ │ │ │ │ ├── docker_api_attach_test.go │ │ │ │ │ ├── docker_api_containers_test.go │ │ │ │ │ ├── docker_api_events_test.go │ │ │ │ │ ├── docker_api_exec_resize_test.go │ │ │ │ │ ├── docker_api_exec_test.go │ │ │ │ │ ├── docker_api_images_test.go │ │ │ │ │ ├── docker_api_info_test.go │ │ │ │ │ ├── docker_api_inspect_test.go │ │ │ │ │ ├── docker_api_logs_test.go │ │ │ │ │ ├── docker_api_network_test.go │ │ │ │ │ ├── docker_api_resize_test.go │ │ │ │ │ ├── docker_api_service_test.go │ │ │ │ │ ├── docker_api_stats_test.go │ │ │ │ │ ├── docker_api_test.go │ │ │ │ │ ├── docker_api_version_test.go │ │ │ │ │ ├── docker_cli_attach_test.go │ │ │ │ │ ├── docker_cli_attach_unix_test.go │ │ │ │ │ ├── docker_cli_build_test.go │ │ │ │ │ ├── docker_cli_build_unix_test.go │ │ │ │ │ ├── docker_cli_by_digest_test.go │ │ │ │ │ ├── docker_cli_commit_test.go │ │ │ │ │ ├── docker_cli_config_test.go │ │ │ │ │ ├── docker_cli_cp_from_container_test.go │ │ │ │ │ ├── docker_cli_cp_test.go │ │ │ │ │ ├── docker_cli_cp_to_container_test.go │ │ │ │ │ ├── docker_cli_cp_utils.go │ │ │ │ │ ├── docker_cli_create_test.go │ │ │ │ │ ├── docker_cli_daemon_experimental_test.go │ │ │ │ │ ├── docker_cli_daemon_test.go │ │ │ │ │ ├── docker_cli_diff_test.go │ │ │ │ │ ├── docker_cli_events_test.go │ │ │ │ │ ├── docker_cli_events_unix_test.go │ │ │ │ │ ├── docker_cli_exec_test.go │ │ │ │ │ ├── docker_cli_exec_unix_test.go │ │ │ │ │ ├── docker_cli_experimental_test.go │ │ │ │ │ ├── docker_cli_export_import_test.go │ │ │ │ │ ├── docker_cli_help_test.go │ │ │ │ │ ├── docker_cli_history_test.go │ │ │ │ │ ├── docker_cli_images_test.go │ │ │ │ │ ├── docker_cli_import_test.go │ │ │ │ │ ├── docker_cli_info_test.go │ │ │ │ │ ├── docker_cli_inspect_experimental_test.go │ │ │ │ │ ├── docker_cli_inspect_test.go │ │ │ │ │ ├── docker_cli_kill_test.go │ │ │ │ │ ├── docker_cli_links_test.go │ │ │ │ │ ├── docker_cli_links_unix_test.go │ │ │ │ │ ├── docker_cli_login_test.go │ │ │ │ │ ├── docker_cli_logs_test.go │ │ │ │ │ ├── docker_cli_nat_test.go │ │ │ │ │ ├── docker_cli_network_test.go │ │ │ │ │ ├── docker_cli_pause_test.go │ │ │ │ │ ├── docker_cli_port_test.go │ │ │ │ │ ├── docker_cli_port_unix_test.go │ │ │ │ │ ├── docker_cli_proxy_test.go │ │ │ │ │ ├── docker_cli_ps_test.go │ │ │ │ │ ├── docker_cli_pull_test.go │ │ │ │ │ ├── docker_cli_push_test.go │ │ │ │ │ ├── docker_cli_rename_test.go │ │ │ │ │ ├── docker_cli_restart_test.go │ │ │ │ │ ├── docker_cli_rm_test.go │ │ │ │ │ ├── docker_cli_rmi_test.go │ │ │ │ │ ├── docker_cli_run_test.go │ │ │ │ │ ├── docker_cli_run_unix_test.go │ │ │ │ │ ├── docker_cli_save_load_test.go │ │ │ │ │ ├── docker_cli_save_load_unix_test.go │ │ │ │ │ ├── docker_cli_search_test.go │ │ │ │ │ ├── docker_cli_service_test.go │ │ │ │ │ ├── docker_cli_start_test.go │ │ │ │ │ ├── docker_cli_start_volume_driver_unix_test.go │ │ │ │ │ ├── docker_cli_stats_test.go │ │ │ │ │ ├── docker_cli_tag_test.go │ │ │ │ │ ├── docker_cli_top_test.go │ │ │ │ │ ├── docker_cli_version_test.go │ │ │ │ │ ├── docker_cli_wait_test.go │ │ │ │ │ ├── docker_test_vars.go │ │ │ │ │ ├── docker_test_vars_cli.go │ │ │ │ │ ├── docker_test_vars_daemon.go │ │ │ │ │ ├── docker_utils.go │ │ │ │ │ ├── fixtures/ │ │ │ │ │ │ └── https/ │ │ │ │ │ │ ├── ca.pem │ │ │ │ │ │ ├── client-cert.pem │ │ │ │ │ │ ├── client-key.pem │ │ │ │ │ │ ├── client-rogue-cert.pem │ │ │ │ │ │ ├── client-rogue-key.pem │ │ │ │ │ │ ├── server-cert.pem │ │ │ │ │ │ ├── server-key.pem │ │ │ │ │ │ ├── server-rogue-cert.pem │ │ │ │ │ │ └── server-rogue-key.pem │ │ │ │ │ ├── registry.go │ │ │ │ │ ├── requirements.go │ │ │ │ │ ├── requirements_unix.go │ │ │ │ │ ├── test_vars_exec.go │ │ │ │ │ ├── test_vars_noexec.go │ │ │ │ │ ├── test_vars_unix.go │ │ │ │ │ ├── test_vars_windows.go │ │ │ │ │ └── utils.go │ │ │ │ ├── links/ │ │ │ │ │ ├── links.go │ │ │ │ │ └── links_test.go │ │ │ │ ├── man/ │ │ │ │ │ ├── Dockerfile │ │ │ │ │ ├── Dockerfile.5.md │ │ │ │ │ ├── README.md │ │ │ │ │ ├── docker-attach.1.md │ │ │ │ │ ├── docker-build.1.md │ │ │ │ │ ├── docker-commit.1.md │ │ │ │ │ ├── docker-cp.1.md │ │ │ │ │ ├── docker-create.1.md │ │ │ │ │ ├── docker-diff.1.md │ │ │ │ │ ├── docker-events.1.md │ │ │ │ │ ├── docker-exec.1.md │ │ │ │ │ ├── docker-export.1.md │ │ │ │ │ ├── docker-history.1.md │ │ │ │ │ ├── docker-images.1.md │ │ │ │ │ ├── docker-import.1.md │ │ │ │ │ ├── docker-info.1.md │ │ │ │ │ ├── docker-inspect.1.md │ │ │ │ │ ├── docker-kill.1.md │ │ │ │ │ ├── docker-load.1.md │ │ │ │ │ ├── docker-login.1.md │ │ │ │ │ ├── docker-logout.1.md │ │ │ │ │ ├── docker-logs.1.md │ │ │ │ │ ├── docker-pause.1.md │ │ │ │ │ ├── docker-port.1.md │ │ │ │ │ ├── docker-ps.1.md │ │ │ │ │ ├── docker-pull.1.md │ │ │ │ │ ├── docker-push.1.md │ │ │ │ │ ├── docker-rename.1.md │ │ │ │ │ ├── docker-restart.1.md │ │ │ │ │ ├── docker-rm.1.md │ │ │ │ │ ├── docker-rmi.1.md │ │ │ │ │ ├── docker-run.1.md │ │ │ │ │ ├── docker-save.1.md │ │ │ │ │ ├── docker-search.1.md │ │ │ │ │ ├── docker-start.1.md │ │ │ │ │ ├── docker-stats.1.md │ │ │ │ │ ├── docker-stop.1.md │ │ │ │ │ ├── docker-tag.1.md │ │ │ │ │ ├── docker-top.1.md │ │ │ │ │ ├── docker-unpause.1.md │ │ │ │ │ ├── docker-version.1.md │ │ │ │ │ ├── docker-wait.1.md │ │ │ │ │ ├── docker.1.md │ │ │ │ │ └── md2man-all.sh │ │ │ │ ├── opts/ │ │ │ │ │ ├── envfile.go │ │ │ │ │ ├── envfile_test.go │ │ │ │ │ ├── ip.go │ │ │ │ │ ├── ip_test.go │ │ │ │ │ ├── opts.go │ │ │ │ │ ├── opts_test.go │ │ │ │ │ ├── ulimit.go │ │ │ │ │ └── ulimit_test.go │ │ │ │ ├── pkg/ │ │ │ │ │ ├── README.md │ │ │ │ │ ├── archive/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── archive.go │ │ │ │ │ │ ├── archive_test.go │ │ │ │ │ │ ├── archive_unix.go │ │ │ │ │ │ ├── archive_unix_test.go │ │ │ │ │ │ ├── archive_windows.go │ │ │ │ │ │ ├── archive_windows_test.go │ │ │ │ │ │ ├── changes.go │ │ │ │ │ │ ├── changes_linux.go │ │ │ │ │ │ ├── changes_other.go │ │ │ │ │ │ ├── changes_posix_test.go │ │ │ │ │ │ ├── changes_test.go │ │ │ │ │ │ ├── changes_unix.go │ │ │ │ │ │ ├── changes_windows.go │ │ │ │ │ │ ├── copy.go │ │ │ │ │ │ ├── copy_test.go │ │ │ │ │ │ ├── diff.go │ │ │ │ │ │ ├── diff_test.go │ │ │ │ │ │ ├── example_changes.go │ │ │ │ │ │ ├── time_linux.go │ │ │ │ │ │ ├── time_unsupported.go │ │ │ │ │ │ ├── utils_test.go │ │ │ │ │ │ ├── wrap.go │ │ │ │ │ │ └── wrap_test.go │ │ │ │ │ ├── broadcastwriter/ │ │ │ │ │ │ ├── broadcastwriter.go │ │ │ │ │ │ └── broadcastwriter_test.go │ │ │ │ │ ├── chrootarchive/ │ │ │ │ │ │ ├── archive.go │ │ │ │ │ │ ├── archive_test.go │ │ │ │ │ │ ├── archive_unix.go │ │ │ │ │ │ ├── archive_windows.go │ │ │ │ │ │ ├── diff_unix.go │ │ │ │ │ │ ├── diff_windows.go │ │ │ │ │ │ ├── init_unix.go │ │ │ │ │ │ └── init_windows.go │ │ │ │ │ ├── devicemapper/ │ │ │ │ │ │ ├── attach_loopback.go │ │ │ │ │ │ ├── devmapper.go │ │ │ │ │ │ ├── devmapper_log.go │ │ │ │ │ │ ├── devmapper_wrapper.go │ │ │ │ │ │ ├── devmapper_wrapper_deferred_remove.go │ │ │ │ │ │ ├── devmapper_wrapper_no_deferred_remove.go │ │ │ │ │ │ ├── ioctl.go │ │ │ │ │ │ └── log.go │ │ │ │ │ ├── directory/ │ │ │ │ │ │ ├── directory_linux.go │ │ │ │ │ │ ├── directory_test.go │ │ │ │ │ │ └── directory_windows.go │ │ │ │ │ ├── fileutils/ │ │ │ │ │ │ ├── fileutils.go │ │ │ │ │ │ └── fileutils_test.go │ │ │ │ │ ├── graphdb/ │ │ │ │ │ │ ├── conn_sqlite3.go │ │ │ │ │ │ ├── conn_sqlite3_unix.go │ │ │ │ │ │ ├── conn_sqlite3_windows.go │ │ │ │ │ │ ├── conn_unsupported.go │ │ │ │ │ │ ├── graphdb.go │ │ │ │ │ │ ├── graphdb_test.go │ │ │ │ │ │ ├── sort.go │ │ │ │ │ │ ├── sort_test.go │ │ │ │ │ │ └── utils.go │ │ │ │ │ ├── homedir/ │ │ │ │ │ │ ├── homedir.go │ │ │ │ │ │ └── homedir_test.go │ │ │ │ │ ├── httputils/ │ │ │ │ │ │ ├── httputils.go │ │ │ │ │ │ ├── mimetype.go │ │ │ │ │ │ ├── resumablerequestreader.go │ │ │ │ │ │ └── resumablerequestreader_test.go │ │ │ │ │ ├── ioutils/ │ │ │ │ │ │ ├── fmt.go │ │ │ │ │ │ ├── fmt_test.go │ │ │ │ │ │ ├── readers.go │ │ │ │ │ │ ├── readers_test.go │ │ │ │ │ │ ├── scheduler.go │ │ │ │ │ │ ├── scheduler_gccgo.go │ │ │ │ │ │ ├── writeflusher.go │ │ │ │ │ │ ├── writers.go │ │ │ │ │ │ └── writers_test.go │ │ │ │ │ ├── jsonlog/ │ │ │ │ │ │ ├── jsonlog.go │ │ │ │ │ │ ├── jsonlog_marshalling.go │ │ │ │ │ │ ├── jsonlog_marshalling_test.go │ │ │ │ │ │ ├── jsonlog_test.go │ │ │ │ │ │ ├── jsonlogbytes.go │ │ │ │ │ │ └── jsonlogbytes_test.go │ │ │ │ │ ├── jsonmessage/ │ │ │ │ │ │ ├── jsonmessage.go │ │ │ │ │ │ └── jsonmessage_test.go │ │ │ │ │ ├── listenbuffer/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── buffer.go │ │ │ │ │ │ └── listen_buffer_test.go │ │ │ │ │ ├── mflag/ │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── example/ │ │ │ │ │ │ │ └── example.go │ │ │ │ │ │ ├── flag.go │ │ │ │ │ │ └── flag_test.go │ │ │ │ │ ├── mount/ │ │ │ │ │ │ ├── flags.go │ │ │ │ │ │ ├── flags_freebsd.go │ │ │ │ │ │ ├── flags_linux.go │ │ │ │ │ │ ├── flags_unsupported.go │ │ │ │ │ │ ├── mount.go │ │ │ │ │ │ ├── mount_test.go │ │ │ │ │ │ ├── mounter_freebsd.go │ │ │ │ │ │ ├── mounter_linux.go │ │ │ │ │ │ ├── mounter_unsupported.go │ │ │ │ │ │ ├── mountinfo.go │ │ │ │ │ │ ├── mountinfo_freebsd.go │ │ │ │ │ │ ├── mountinfo_linux.go │ │ │ │ │ │ ├── mountinfo_linux_test.go │ │ │ │ │ │ ├── mountinfo_unsupported.go │ │ │ │ │ │ ├── sharedsubtree_linux.go │ │ │ │ │ │ └── sharedsubtree_linux_test.go │ │ │ │ │ ├── namesgenerator/ │ │ │ │ │ │ ├── names-generator.go │ │ │ │ │ │ └── names-generator_test.go │ │ │ │ │ ├── nat/ │ │ │ │ │ │ ├── nat.go │ │ │ │ │ │ ├── nat_test.go │ │ │ │ │ │ ├── sort.go │ │ │ │ │ │ └── sort_test.go │ │ │ │ │ ├── parsers/ │ │ │ │ │ │ ├── filters/ │ │ │ │ │ │ │ ├── parse.go │ │ │ │ │ │ │ └── parse_test.go │ │ │ │ │ │ ├── kernel/ │ │ │ │ │ │ │ ├── kernel.go │ │ │ │ │ │ │ ├── kernel_test.go │ │ │ │ │ │ │ ├── kernel_windows.go │ │ │ │ │ │ │ ├── uname_linux.go │ │ │ │ │ │ │ └── uname_unsupported.go │ │ │ │ │ │ ├── operatingsystem/ │ │ │ │ │ │ │ ├── operatingsystem_linux.go │ │ │ │ │ │ │ ├── operatingsystem_test.go │ │ │ │ │ │ │ └── operatingsystem_windows.go │ │ │ │ │ │ ├── parsers.go │ │ │ │ │ │ └── parsers_test.go │ │ │ │ │ ├── pidfile/ │ │ │ │ │ │ ├── pidfile.go │ │ │ │ │ │ └── pidfile_test.go │ │ │ │ │ ├── plugins/ │ │ │ │ │ │ ├── client.go │ │ │ │ │ │ ├── client_test.go │ │ │ │ │ │ ├── discovery.go │ │ │ │ │ │ ├── discovery_test.go │ │ │ │ │ │ ├── pluginrpc-gen/ │ │ │ │ │ │ │ ├── fixtures/ │ │ │ │ │ │ │ │ └── foo.go │ │ │ │ │ │ │ ├── main.go │ │ │ │ │ │ │ ├── parser.go │ │ │ │ │ │ │ ├── parser_test.go │ │ │ │ │ │ │ └── template.go │ │ │ │ │ │ └── plugins.go │ │ │ │ │ ├── pools/ │ │ │ │ │ │ ├── pools.go │ │ │ │ │ │ └── pools_test.go │ │ │ │ │ ├── progressreader/ │ │ │ │ │ │ ├── progressreader.go │ │ │ │ │ │ └── progressreader_test.go │ │ │ │ │ ├── promise/ │ │ │ │ │ │ └── promise.go │ │ │ │ │ ├── proxy/ │ │ │ │ │ │ ├── network_proxy_test.go │ │ │ │ │ │ ├── proxy.go │ │ │ │ │ │ ├── stub_proxy.go │ │ │ │ │ │ ├── tcp_proxy.go │ │ │ │ │ │ └── udp_proxy.go │ │ │ │ │ ├── pubsub/ │ │ │ │ │ │ ├── publisher.go │ │ │ │ │ │ └── publisher_test.go │ │ │ │ │ ├── random/ │ │ │ │ │ │ ├── random.go │ │ │ │ │ │ └── random_test.go │ │ │ │ │ ├── reexec/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── command_linux.go │ │ │ │ │ │ ├── command_unsupported.go │ │ │ │ │ │ ├── command_windows.go │ │ │ │ │ │ └── reexec.go │ │ │ │ │ ├── signal/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── signal.go │ │ │ │ │ │ ├── signal_darwin.go │ │ │ │ │ │ ├── signal_freebsd.go │ │ │ │ │ │ ├── signal_linux.go │ │ │ │ │ │ ├── signal_unix.go │ │ │ │ │ │ ├── signal_unsupported.go │ │ │ │ │ │ ├── signal_windows.go │ │ │ │ │ │ └── trap.go │ │ │ │ │ ├── sockets/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── tcp_socket.go │ │ │ │ │ │ └── unix_socket.go │ │ │ │ │ ├── stdcopy/ │ │ │ │ │ │ ├── stdcopy.go │ │ │ │ │ │ └── stdcopy_test.go │ │ │ │ │ ├── streamformatter/ │ │ │ │ │ │ ├── streamformatter.go │ │ │ │ │ │ └── streamformatter_test.go │ │ │ │ │ ├── stringid/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── stringid.go │ │ │ │ │ │ └── stringid_test.go │ │ │ │ │ ├── stringutils/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── stringutils.go │ │ │ │ │ │ └── stringutils_test.go │ │ │ │ │ ├── symlink/ │ │ │ │ │ │ ├── LICENSE.APACHE │ │ │ │ │ │ ├── LICENSE.BSD │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── fs.go │ │ │ │ │ │ └── fs_test.go │ │ │ │ │ ├── sysinfo/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── sysinfo.go │ │ │ │ │ │ ├── sysinfo_linux.go │ │ │ │ │ │ ├── sysinfo_linux_test.go │ │ │ │ │ │ └── sysinfo_windows.go │ │ │ │ │ ├── system/ │ │ │ │ │ │ ├── errors.go │ │ │ │ │ │ ├── events_windows.go │ │ │ │ │ │ ├── filesys.go │ │ │ │ │ │ ├── filesys_windows.go │ │ │ │ │ │ ├── lstat.go │ │ │ │ │ │ ├── lstat_test.go │ │ │ │ │ │ ├── lstat_windows.go │ │ │ │ │ │ ├── meminfo.go │ │ │ │ │ │ ├── meminfo_linux.go │ │ │ │ │ │ ├── meminfo_linux_test.go │ │ │ │ │ │ ├── meminfo_unsupported.go │ │ │ │ │ │ ├── meminfo_windows.go │ │ │ │ │ │ ├── mknod.go │ │ │ │ │ │ ├── mknod_windows.go │ │ │ │ │ │ ├── stat.go │ │ │ │ │ │ ├── stat_linux.go │ │ │ │ │ │ ├── stat_test.go │ │ │ │ │ │ ├── stat_unsupported.go │ │ │ │ │ │ ├── stat_windows.go │ │ │ │ │ │ ├── umask.go │ │ │ │ │ │ ├── umask_windows.go │ │ │ │ │ │ ├── utimes_darwin.go │ │ │ │ │ │ ├── utimes_freebsd.go │ │ │ │ │ │ ├── utimes_linux.go │ │ │ │ │ │ ├── utimes_test.go │ │ │ │ │ │ ├── utimes_unsupported.go │ │ │ │ │ │ ├── xattrs_linux.go │ │ │ │ │ │ └── xattrs_unsupported.go │ │ │ │ │ ├── systemd/ │ │ │ │ │ │ ├── booted.go │ │ │ │ │ │ ├── listendfd.go │ │ │ │ │ │ └── sd_notify.go │ │ │ │ │ ├── tailfile/ │ │ │ │ │ │ ├── tailfile.go │ │ │ │ │ │ └── tailfile_test.go │ │ │ │ │ ├── tarsum/ │ │ │ │ │ │ ├── builder_context.go │ │ │ │ │ │ ├── builder_context_test.go │ │ │ │ │ │ ├── fileinfosums.go │ │ │ │ │ │ ├── fileinfosums_test.go │ │ │ │ │ │ ├── tarsum.go │ │ │ │ │ │ ├── tarsum_spec.md │ │ │ │ │ │ ├── tarsum_test.go │ │ │ │ │ │ ├── testdata/ │ │ │ │ │ │ │ ├── 46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/ │ │ │ │ │ │ │ │ └── json │ │ │ │ │ │ │ ├── 511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158/ │ │ │ │ │ │ │ │ └── json │ │ │ │ │ │ │ └── xattr/ │ │ │ │ │ │ │ └── json │ │ │ │ │ │ ├── versioning.go │ │ │ │ │ │ ├── versioning_test.go │ │ │ │ │ │ └── writercloser.go │ │ │ │ │ ├── term/ │ │ │ │ │ │ ├── tc_linux_cgo.go │ │ │ │ │ │ ├── tc_other.go │ │ │ │ │ │ ├── term.go │ │ │ │ │ │ ├── term_windows.go │ │ │ │ │ │ ├── termios_darwin.go │ │ │ │ │ │ ├── termios_freebsd.go │ │ │ │ │ │ ├── termios_linux.go │ │ │ │ │ │ └── winconsole/ │ │ │ │ │ │ ├── console_windows.go │ │ │ │ │ │ ├── console_windows_test.go │ │ │ │ │ │ ├── term_emulator.go │ │ │ │ │ │ └── term_emulator_test.go │ │ │ │ │ ├── timeoutconn/ │ │ │ │ │ │ ├── timeoutconn.go │ │ │ │ │ │ └── timeoutconn_test.go │ │ │ │ │ ├── timeutils/ │ │ │ │ │ │ ├── json.go │ │ │ │ │ │ ├── json_test.go │ │ │ │ │ │ ├── utils.go │ │ │ │ │ │ └── utils_test.go │ │ │ │ │ ├── tlsconfig/ │ │ │ │ │ │ └── config.go │ │ │ │ │ ├── truncindex/ │ │ │ │ │ │ ├── truncindex.go │ │ │ │ │ │ └── truncindex_test.go │ │ │ │ │ ├── ulimit/ │ │ │ │ │ │ ├── ulimit.go │ │ │ │ │ │ └── ulimit_test.go │ │ │ │ │ ├── units/ │ │ │ │ │ │ ├── duration.go │ │ │ │ │ │ ├── duration_test.go │ │ │ │ │ │ ├── size.go │ │ │ │ │ │ └── size_test.go │ │ │ │ │ ├── urlutil/ │ │ │ │ │ │ ├── urlutil.go │ │ │ │ │ │ └── urlutil_test.go │ │ │ │ │ ├── useragent/ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── useragent.go │ │ │ │ │ │ └── useragent_test.go │ │ │ │ │ └── version/ │ │ │ │ │ ├── version.go │ │ │ │ │ └── version_test.go │ │ │ │ ├── project/ │ │ │ │ │ ├── GOVERNANCE.md │ │ │ │ │ ├── IRC-ADMINISTRATION.md │ │ │ │ │ ├── ISSUE-TRIAGE.md │ │ │ │ │ ├── PACKAGERS.md │ │ │ │ │ ├── PRINCIPLES.md │ │ │ │ │ ├── README.md │ │ │ │ │ ├── RELEASE-CHECKLIST.md │ │ │ │ │ ├── REVIEWING.md │ │ │ │ │ └── TOOLS.md │ │ │ │ ├── registry/ │ │ │ │ │ ├── auth.go │ │ │ │ │ ├── auth_test.go │ │ │ │ │ ├── authchallenge.go │ │ │ │ │ ├── config.go │ │ │ │ │ ├── config_test.go │ │ │ │ │ ├── endpoint.go │ │ │ │ │ ├── endpoint_test.go │ │ │ │ │ ├── registry.go │ │ │ │ │ ├── registry_mock_test.go │ │ │ │ │ ├── registry_test.go │ │ │ │ │ ├── service.go │ │ │ │ │ ├── session.go │ │ │ │ │ ├── token.go │ │ │ │ │ └── types.go │ │ │ │ ├── runconfig/ │ │ │ │ │ ├── compare.go │ │ │ │ │ ├── compare_test.go │ │ │ │ │ ├── config.go │ │ │ │ │ ├── config_test.go │ │ │ │ │ ├── exec.go │ │ │ │ │ ├── exec_test.go │ │ │ │ │ ├── fixtures/ │ │ │ │ │ │ ├── container_config_1_14.json │ │ │ │ │ │ ├── container_config_1_17.json │ │ │ │ │ │ ├── container_config_1_19.json │ │ │ │ │ │ ├── container_hostconfig_1_14.json │ │ │ │ │ │ ├── container_hostconfig_1_19.json │ │ │ │ │ │ ├── valid.env │ │ │ │ │ │ └── valid.label │ │ │ │ │ ├── hostconfig.go │ │ │ │ │ ├── hostconfig_test.go │ │ │ │ │ ├── hostconfig_unix.go │ │ │ │ │ ├── hostconfig_windows.go │ │ │ │ │ ├── merge.go │ │ │ │ │ ├── merge_test.go │ │ │ │ │ ├── parse.go │ │ │ │ │ ├── parse_experimental.go │ │ │ │ │ ├── parse_stub.go │ │ │ │ │ ├── parse_test.go │ │ │ │ │ ├── parse_unix.go │ │ │ │ │ └── parse_windows.go │ │ │ │ ├── trust/ │ │ │ │ │ ├── service.go │ │ │ │ │ └── trusts.go │ │ │ │ ├── utils/ │ │ │ │ │ ├── experimental.go │ │ │ │ │ ├── git.go │ │ │ │ │ ├── git_test.go │ │ │ │ │ ├── stubs.go │ │ │ │ │ ├── utils.go │ │ │ │ │ └── utils_test.go │ │ │ │ └── volume/ │ │ │ │ ├── drivers/ │ │ │ │ │ ├── adapter.go │ │ │ │ │ ├── api.go │ │ │ │ │ ├── extpoint.go │ │ │ │ │ ├── proxy.go │ │ │ │ │ └── proxy_test.go │ │ │ │ ├── local/ │ │ │ │ │ └── local.go │ │ │ │ └── volume.go │ │ │ ├── go-units/ │ │ │ │ ├── CONTRIBUTING.md │ │ │ │ ├── LICENSE.code │ │ │ │ ├── LICENSE.docs │ │ │ │ ├── MAINTAINERS │ │ │ │ ├── README.md │ │ │ │ ├── circle.yml │ │ │ │ ├── duration.go │ │ │ │ ├── duration_test.go │ │ │ │ ├── size.go │ │ │ │ ├── size_test.go │ │ │ │ ├── ulimit.go │ │ │ │ └── ulimit_test.go │ │ │ └── libcontainer/ │ │ │ ├── .gitignore │ │ │ ├── CONTRIBUTING.md │ │ │ ├── Dockerfile │ │ │ ├── LICENSE │ │ │ ├── MAINTAINERS │ │ │ ├── MAINTAINERS_GUIDE.md │ │ │ ├── Makefile │ │ │ ├── NOTICE │ │ │ ├── PRINCIPLES.md │ │ │ ├── README.md │ │ │ ├── ROADMAP.md │ │ │ ├── SPEC.md │ │ │ ├── apparmor/ │ │ │ │ ├── apparmor.go │ │ │ │ ├── apparmor_disabled.go │ │ │ │ ├── gen.go │ │ │ │ └── setup.go │ │ │ ├── capabilities_linux.go │ │ │ ├── cgroups/ │ │ │ │ ├── cgroups.go │ │ │ │ ├── cgroups_test.go │ │ │ │ ├── cgroups_unsupported.go │ │ │ │ ├── fs/ │ │ │ │ │ ├── apply_raw.go │ │ │ │ │ ├── blkio.go │ │ │ │ │ ├── blkio_test.go │ │ │ │ │ ├── cpu.go │ │ │ │ │ ├── cpu_test.go │ │ │ │ │ ├── cpuacct.go │ │ │ │ │ ├── cpuset.go │ │ │ │ │ ├── cpuset_test.go │ │ │ │ │ ├── devices.go │ │ │ │ │ ├── devices_test.go │ │ │ │ │ ├── freezer.go │ │ │ │ │ ├── freezer_test.go │ │ │ │ │ ├── fs_unsupported.go │ │ │ │ │ ├── hugetlb.go │ │ │ │ │ ├── hugetlb_test.go │ │ │ │ │ ├── memory.go │ │ │ │ │ ├── memory_test.go │ │ │ │ │ ├── net_cls.go │ │ │ │ │ ├── net_cls_test.go │ │ │ │ │ ├── net_prio.go │ │ │ │ │ ├── net_prio_test.go │ │ │ │ │ ├── perf_event.go │ │ │ │ │ ├── stats_util_test.go │ │ │ │ │ ├── util_test.go │ │ │ │ │ ├── utils.go │ │ │ │ │ └── utils_test.go │ │ │ │ ├── stats.go │ │ │ │ ├── systemd/ │ │ │ │ │ ├── apply_nosystemd.go │ │ │ │ │ └── apply_systemd.go │ │ │ │ └── utils.go │ │ │ ├── configs/ │ │ │ │ ├── cgroup.go │ │ │ │ ├── config.go │ │ │ │ ├── config_test.go │ │ │ │ ├── config_unix.go │ │ │ │ ├── device.go │ │ │ │ ├── device_defaults.go │ │ │ │ ├── hugepage_limit.go │ │ │ │ ├── interface_priority_map.go │ │ │ │ ├── mount.go │ │ │ │ ├── namespaces.go │ │ │ │ ├── namespaces_syscall.go │ │ │ │ ├── namespaces_syscall_unsupported.go │ │ │ │ ├── namespaces_unix.go │ │ │ │ ├── namespaces_windows.go │ │ │ │ ├── network.go │ │ │ │ └── validate/ │ │ │ │ └── config.go │ │ │ ├── console.go │ │ │ ├── console_freebsd.go │ │ │ ├── console_linux.go │ │ │ ├── console_windows.go │ │ │ ├── container.go │ │ │ ├── container_linux.go │ │ │ ├── container_linux_test.go │ │ │ ├── container_nouserns_linux.go │ │ │ ├── container_userns_linux.go │ │ │ ├── criu_opts.go │ │ │ ├── criurpc/ │ │ │ │ ├── Makefile │ │ │ │ ├── criurpc.pb.go │ │ │ │ └── criurpc.proto │ │ │ ├── devices/ │ │ │ │ ├── devices_test.go │ │ │ │ ├── devices_unix.go │ │ │ │ ├── devices_windows.go │ │ │ │ └── number.go │ │ │ ├── docs/ │ │ │ │ └── man/ │ │ │ │ └── nsinit.1.md │ │ │ ├── error.go │ │ │ ├── error_test.go │ │ │ ├── factory.go │ │ │ ├── factory_linux.go │ │ │ ├── factory_linux_test.go │ │ │ ├── generic_error.go │ │ │ ├── generic_error_test.go │ │ │ ├── hack/ │ │ │ │ └── validate.sh │ │ │ ├── init_linux.go │ │ │ ├── integration/ │ │ │ │ ├── checkpoint_test.go │ │ │ │ ├── doc.go │ │ │ │ ├── exec_test.go │ │ │ │ ├── execin_test.go │ │ │ │ ├── init_test.go │ │ │ │ ├── template_test.go │ │ │ │ └── utils_test.go │ │ │ ├── label/ │ │ │ │ ├── label.go │ │ │ │ ├── label_selinux.go │ │ │ │ └── label_selinux_test.go │ │ │ ├── netlink/ │ │ │ │ ├── MAINTAINERS │ │ │ │ ├── netlink.go │ │ │ │ ├── netlink_linux.go │ │ │ │ ├── netlink_linux_armppc64.go │ │ │ │ ├── netlink_linux_notarm.go │ │ │ │ ├── netlink_linux_test.go │ │ │ │ └── netlink_unsupported.go │ │ │ ├── network_linux.go │ │ │ ├── notify_linux.go │ │ │ ├── notify_linux_test.go │ │ │ ├── nsenter/ │ │ │ │ ├── README.md │ │ │ │ ├── nsenter.go │ │ │ │ ├── nsenter_gccgo.go │ │ │ │ ├── nsenter_test.go │ │ │ │ ├── nsenter_unsupported.go │ │ │ │ └── nsexec.c │ │ │ ├── nsinit/ │ │ │ │ ├── Makefile │ │ │ │ ├── README.md │ │ │ │ ├── checkpoint.go │ │ │ │ ├── config.go │ │ │ │ ├── exec.go │ │ │ │ ├── init.go │ │ │ │ ├── main.go │ │ │ │ ├── oom.go │ │ │ │ ├── pause.go │ │ │ │ ├── restore.go │ │ │ │ ├── security.go │ │ │ │ ├── state.go │ │ │ │ ├── stats.go │ │ │ │ ├── tty.go │ │ │ │ └── utils.go │ │ │ ├── process.go │ │ │ ├── process_linux.go │ │ │ ├── restored_process.go │ │ │ ├── rootfs_linux.go │ │ │ ├── rootfs_linux_test.go │ │ │ ├── sample_configs/ │ │ │ │ ├── README.md │ │ │ │ ├── apparmor.json │ │ │ │ ├── attach_to_bridge.json │ │ │ │ ├── host-pid.json │ │ │ │ ├── minimal.json │ │ │ │ ├── selinux.json │ │ │ │ └── userns.json │ │ │ ├── seccomp/ │ │ │ │ ├── bpf.go │ │ │ │ ├── context.go │ │ │ │ ├── filter.go │ │ │ │ ├── jump_amd64.go │ │ │ │ └── seccomp.go │ │ │ ├── selinux/ │ │ │ │ ├── selinux.go │ │ │ │ └── selinux_test.go │ │ │ ├── setns_init_linux.go │ │ │ ├── stacktrace/ │ │ │ │ ├── capture.go │ │ │ │ ├── capture_test.go │ │ │ │ ├── frame.go │ │ │ │ ├── frame_test.go │ │ │ │ └── stacktrace.go │ │ │ ├── standard_init_linux.go │ │ │ ├── stats.go │ │ │ ├── stats_freebsd.go │ │ │ ├── stats_linux.go │ │ │ ├── stats_windows.go │ │ │ ├── system/ │ │ │ │ ├── linux.go │ │ │ │ ├── proc.go │ │ │ │ ├── setns_linux.go │ │ │ │ ├── syscall_linux_386.go │ │ │ │ ├── syscall_linux_64.go │ │ │ │ ├── syscall_linux_arm.go │ │ │ │ ├── sysconfig.go │ │ │ │ ├── sysconfig_notcgo.go │ │ │ │ └── xattrs_linux.go │ │ │ ├── update-vendor.sh │ │ │ ├── user/ │ │ │ │ ├── MAINTAINERS │ │ │ │ ├── lookup.go │ │ │ │ ├── lookup_unix.go │ │ │ │ ├── lookup_unsupported.go │ │ │ │ ├── user.go │ │ │ │ └── user_test.go │ │ │ ├── utils/ │ │ │ │ ├── utils.go │ │ │ │ └── utils_test.go │ │ │ └── xattr/ │ │ │ ├── errors.go │ │ │ ├── xattr_linux.go │ │ │ ├── xattr_test.go │ │ │ └── xattr_unsupported.go │ │ ├── emicklei/ │ │ │ └── go-restful/ │ │ │ ├── .gitignore │ │ │ ├── CHANGES.md │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── Srcfile │ │ │ ├── bench_curly_test.go │ │ │ ├── bench_test.go │ │ │ ├── bench_test.sh │ │ │ ├── compress.go │ │ │ ├── compress_test.go │ │ │ ├── compressor_cache.go │ │ │ ├── compressor_pools.go │ │ │ ├── compressors.go │ │ │ ├── constants.go │ │ │ ├── container.go │ │ │ ├── container_test.go │ │ │ ├── cors_filter.go │ │ │ ├── cors_filter_test.go │ │ │ ├── coverage.sh │ │ │ ├── curly.go │ │ │ ├── curly_route.go │ │ │ ├── curly_test.go │ │ │ ├── doc.go │ │ │ ├── doc_examples_test.go │ │ │ ├── entity_accessors.go │ │ │ ├── entity_accessors_test.go │ │ │ ├── examples/ │ │ │ │ ├── .goconvey │ │ │ │ ├── google_app_engine/ │ │ │ │ │ ├── .goconvey │ │ │ │ │ ├── app.yaml │ │ │ │ │ ├── datastore/ │ │ │ │ │ │ ├── .goconvey │ │ │ │ │ │ ├── app.yaml │ │ │ │ │ │ └── main.go │ │ │ │ │ ├── restful-appstats-integration.go │ │ │ │ │ └── restful-user-service.go │ │ │ │ ├── home.html │ │ │ │ ├── restful-CORS-filter.go │ │ │ │ ├── restful-NCSA-logging.go │ │ │ │ ├── restful-basic-authentication.go │ │ │ │ ├── restful-cpuprofiler-service.go │ │ │ │ ├── restful-curly-router.go │ │ │ │ ├── restful-encoding-filter.go │ │ │ │ ├── restful-filters.go │ │ │ │ ├── restful-form-handling.go │ │ │ │ ├── restful-hello-world.go │ │ │ │ ├── restful-html-template.go │ │ │ │ ├── restful-multi-containers.go │ │ │ │ ├── restful-options-filter.go │ │ │ │ ├── restful-path-tail.go │ │ │ │ ├── restful-pre-post-filters.go │ │ │ │ ├── restful-resource-functions.go │ │ │ │ ├── restful-route_test.go │ │ │ │ ├── restful-routefunction_test.go │ │ │ │ ├── restful-serve-static.go │ │ │ │ ├── restful-swagger.go │ │ │ │ ├── restful-user-resource.go │ │ │ │ └── restful-user-service.go │ │ │ ├── filter.go │ │ │ ├── filter_test.go │ │ │ ├── install.sh │ │ │ ├── jsr311.go │ │ │ ├── jsr311_test.go │ │ │ ├── log/ │ │ │ │ └── log.go │ │ │ ├── logger.go │ │ │ ├── options_filter.go │ │ │ ├── options_filter_test.go │ │ │ ├── parameter.go │ │ │ ├── path_expression.go │ │ │ ├── path_expression_test.go │ │ │ ├── request.go │ │ │ ├── request_test.go │ │ │ ├── response.go │ │ │ ├── response_test.go │ │ │ ├── route.go │ │ │ ├── route_builder.go │ │ │ ├── route_builder_test.go │ │ │ ├── route_test.go │ │ │ ├── router.go │ │ │ ├── service_error.go │ │ │ ├── swagger/ │ │ │ │ ├── CHANGES.md │ │ │ │ ├── README.md │ │ │ │ ├── api_declaration_list.go │ │ │ │ ├── config.go │ │ │ │ ├── model_builder.go │ │ │ │ ├── model_builder_test.go │ │ │ │ ├── model_list.go │ │ │ │ ├── model_list_test.go │ │ │ │ ├── model_property_ext.go │ │ │ │ ├── model_property_ext_test.go │ │ │ │ ├── model_property_list.go │ │ │ │ ├── model_property_list_test.go │ │ │ │ ├── ordered_route_map.go │ │ │ │ ├── ordered_route_map_test.go │ │ │ │ ├── postbuild_model_test.go │ │ │ │ ├── swagger.go │ │ │ │ ├── swagger_builder.go │ │ │ │ ├── swagger_test.go │ │ │ │ ├── swagger_webservice.go │ │ │ │ ├── test_package/ │ │ │ │ │ └── struct.go │ │ │ │ └── utils_test.go │ │ │ ├── tracer_test.go │ │ │ ├── web_service.go │ │ │ ├── web_service_container.go │ │ │ └── web_service_test.go │ │ ├── evanphx/ │ │ │ └── json-patch/ │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── merge.go │ │ │ ├── merge_test.go │ │ │ ├── patch.go │ │ │ └── patch_test.go │ │ ├── fatih/ │ │ │ └── color/ │ │ │ ├── .travis.yml │ │ │ ├── LICENSE.md │ │ │ ├── README.md │ │ │ ├── color.go │ │ │ ├── color_test.go │ │ │ └── doc.go │ │ ├── fsouza/ │ │ │ └── go-dockerclient/ │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── AUTHORS │ │ │ ├── DOCKER-LICENSE │ │ │ ├── LICENSE │ │ │ ├── Makefile │ │ │ ├── README.markdown │ │ │ ├── auth.go │ │ │ ├── auth_test.go │ │ │ ├── build_test.go │ │ │ ├── change.go │ │ │ ├── change_test.go │ │ │ ├── client.go │ │ │ ├── client_test.go │ │ │ ├── container.go │ │ │ ├── container_test.go │ │ │ ├── env.go │ │ │ ├── env_test.go │ │ │ ├── event.go │ │ │ ├── event_test.go │ │ │ ├── example_test.go │ │ │ ├── exec.go │ │ │ ├── exec_test.go │ │ │ ├── external/ │ │ │ │ ├── github.com/ │ │ │ │ │ ├── Sirupsen/ │ │ │ │ │ │ └── logrus/ │ │ │ │ │ │ ├── CHANGELOG.md │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── doc.go │ │ │ │ │ │ ├── entry.go │ │ │ │ │ │ ├── entry_test.go │ │ │ │ │ │ ├── exported.go │ │ │ │ │ │ ├── formatter.go │ │ │ │ │ │ ├── formatter_bench_test.go │ │ │ │ │ │ ├── hook_test.go │ │ │ │ │ │ ├── hooks.go │ │ │ │ │ │ ├── json_formatter.go │ │ │ │ │ │ ├── json_formatter_test.go │ │ │ │ │ │ ├── logger.go │ │ │ │ │ │ ├── logrus.go │ │ │ │ │ │ ├── logrus_test.go │ │ │ │ │ │ ├── terminal_bsd.go │ │ │ │ │ │ ├── terminal_linux.go │ │ │ │ │ │ ├── terminal_notwindows.go │ │ │ │ │ │ ├── terminal_solaris.go │ │ │ │ │ │ ├── terminal_windows.go │ │ │ │ │ │ ├── text_formatter.go │ │ │ │ │ │ ├── text_formatter_test.go │ │ │ │ │ │ └── writer.go │ │ │ │ │ ├── docker/ │ │ │ │ │ │ ├── docker/ │ │ │ │ │ │ │ ├── opts/ │ │ │ │ │ │ │ │ ├── envfile.go │ │ │ │ │ │ │ │ ├── envfile_test.go │ │ │ │ │ │ │ │ ├── hosts.go │ │ │ │ │ │ │ │ ├── hosts_test.go │ │ │ │ │ │ │ │ ├── hosts_unix.go │ │ │ │ │ │ │ │ ├── hosts_windows.go │ │ │ │ │ │ │ │ ├── ip.go │ │ │ │ │ │ │ │ ├── ip_test.go │ │ │ │ │ │ │ │ ├── opts.go │ │ │ │ │ │ │ │ ├── opts_test.go │ │ │ │ │ │ │ │ ├── opts_unix.go │ │ │ │ │ │ │ │ └── opts_windows.go │ │ │ │ │ │ │ └── pkg/ │ │ │ │ │ │ │ ├── archive/ │ │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ │ ├── archive.go │ │ │ │ │ │ │ │ ├── archive_test.go │ │ │ │ │ │ │ │ ├── archive_unix.go │ │ │ │ │ │ │ │ ├── archive_unix_test.go │ │ │ │ │ │ │ │ ├── archive_windows.go │ │ │ │ │ │ │ │ ├── archive_windows_test.go │ │ │ │ │ │ │ │ ├── changes.go │ │ │ │ │ │ │ │ ├── changes_linux.go │ │ │ │ │ │ │ │ ├── changes_other.go │ │ │ │ │ │ │ │ ├── changes_posix_test.go │ │ │ │ │ │ │ │ ├── changes_test.go │ │ │ │ │ │ │ │ ├── changes_unix.go │ │ │ │ │ │ │ │ ├── changes_windows.go │ │ │ │ │ │ │ │ ├── copy.go │ │ │ │ │ │ │ │ ├── copy_test.go │ │ │ │ │ │ │ │ ├── copy_unix.go │ │ │ │ │ │ │ │ ├── copy_windows.go │ │ │ │ │ │ │ │ ├── diff.go │ │ │ │ │ │ │ │ ├── diff_test.go │ │ │ │ │ │ │ │ ├── example_changes.go │ │ │ │ │ │ │ │ ├── time_linux.go │ │ │ │ │ │ │ │ ├── time_unsupported.go │ │ │ │ │ │ │ │ ├── utils_test.go │ │ │ │ │ │ │ │ ├── whiteouts.go │ │ │ │ │ │ │ │ ├── wrap.go │ │ │ │ │ │ │ │ └── wrap_test.go │ │ │ │ │ │ │ ├── fileutils/ │ │ │ │ │ │ │ │ ├── fileutils.go │ │ │ │ │ │ │ │ ├── fileutils_test.go │ │ │ │ │ │ │ │ ├── fileutils_unix.go │ │ │ │ │ │ │ │ └── fileutils_windows.go │ │ │ │ │ │ │ ├── homedir/ │ │ │ │ │ │ │ │ ├── homedir.go │ │ │ │ │ │ │ │ └── homedir_test.go │ │ │ │ │ │ │ ├── idtools/ │ │ │ │ │ │ │ │ ├── idtools.go │ │ │ │ │ │ │ │ ├── idtools_unix.go │ │ │ │ │ │ │ │ ├── idtools_unix_test.go │ │ │ │ │ │ │ │ ├── idtools_windows.go │ │ │ │ │ │ │ │ ├── usergroupadd_linux.go │ │ │ │ │ │ │ │ └── usergroupadd_unsupported.go │ │ │ │ │ │ │ ├── ioutils/ │ │ │ │ │ │ │ │ ├── bytespipe.go │ │ │ │ │ │ │ │ ├── bytespipe_test.go │ │ │ │ │ │ │ │ ├── fmt.go │ │ │ │ │ │ │ │ ├── fmt_test.go │ │ │ │ │ │ │ │ ├── multireader.go │ │ │ │ │ │ │ │ ├── multireader_test.go │ │ │ │ │ │ │ │ ├── readers.go │ │ │ │ │ │ │ │ ├── readers_test.go │ │ │ │ │ │ │ │ ├── scheduler.go │ │ │ │ │ │ │ │ ├── scheduler_gccgo.go │ │ │ │ │ │ │ │ ├── temp_unix.go │ │ │ │ │ │ │ │ ├── temp_windows.go │ │ │ │ │ │ │ │ ├── writeflusher.go │ │ │ │ │ │ │ │ ├── writers.go │ │ │ │ │ │ │ │ └── writers_test.go │ │ │ │ │ │ │ ├── longpath/ │ │ │ │ │ │ │ │ ├── longpath.go │ │ │ │ │ │ │ │ └── longpath_test.go │ │ │ │ │ │ │ ├── pools/ │ │ │ │ │ │ │ │ ├── pools.go │ │ │ │ │ │ │ │ └── pools_test.go │ │ │ │ │ │ │ ├── promise/ │ │ │ │ │ │ │ │ └── promise.go │ │ │ │ │ │ │ ├── stdcopy/ │ │ │ │ │ │ │ │ ├── stdcopy.go │ │ │ │ │ │ │ │ └── stdcopy_test.go │ │ │ │ │ │ │ └── system/ │ │ │ │ │ │ │ ├── chtimes.go │ │ │ │ │ │ │ ├── chtimes_test.go │ │ │ │ │ │ │ ├── chtimes_unix_test.go │ │ │ │ │ │ │ ├── chtimes_windows_test.go │ │ │ │ │ │ │ ├── errors.go │ │ │ │ │ │ │ ├── events_windows.go │ │ │ │ │ │ │ ├── filesys.go │ │ │ │ │ │ │ ├── filesys_windows.go │ │ │ │ │ │ │ ├── lstat.go │ │ │ │ │ │ │ ├── lstat_unix_test.go │ │ │ │ │ │ │ ├── lstat_windows.go │ │ │ │ │ │ │ ├── meminfo.go │ │ │ │ │ │ │ ├── meminfo_linux.go │ │ │ │ │ │ │ ├── meminfo_unix_test.go │ │ │ │ │ │ │ ├── meminfo_unsupported.go │ │ │ │ │ │ │ ├── meminfo_windows.go │ │ │ │ │ │ │ ├── mknod.go │ │ │ │ │ │ │ ├── mknod_windows.go │ │ │ │ │ │ │ ├── path_unix.go │ │ │ │ │ │ │ ├── path_windows.go │ │ │ │ │ │ │ ├── stat.go │ │ │ │ │ │ │ ├── stat_freebsd.go │ │ │ │ │ │ │ ├── stat_linux.go │ │ │ │ │ │ │ ├── stat_solaris.go │ │ │ │ │ │ │ ├── stat_unix_test.go │ │ │ │ │ │ │ ├── stat_unsupported.go │ │ │ │ │ │ │ ├── stat_windows.go │ │ │ │ │ │ │ ├── syscall_unix.go │ │ │ │ │ │ │ ├── syscall_windows.go │ │ │ │ │ │ │ ├── umask.go │ │ │ │ │ │ │ ├── umask_windows.go │ │ │ │ │ │ │ ├── utimes_darwin.go │ │ │ │ │ │ │ ├── utimes_freebsd.go │ │ │ │ │ │ │ ├── utimes_linux.go │ │ │ │ │ │ │ ├── utimes_unix_test.go │ │ │ │ │ │ │ ├── utimes_unsupported.go │ │ │ │ │ │ │ ├── xattrs_linux.go │ │ │ │ │ │ │ └── xattrs_unsupported.go │ │ │ │ │ │ └── go-units/ │ │ │ │ │ │ ├── CONTRIBUTING.md │ │ │ │ │ │ ├── LICENSE.code │ │ │ │ │ │ ├── LICENSE.docs │ │ │ │ │ │ ├── MAINTAINERS │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── circle.yml │ │ │ │ │ │ ├── duration.go │ │ │ │ │ │ ├── duration_test.go │ │ │ │ │ │ ├── size.go │ │ │ │ │ │ ├── size_test.go │ │ │ │ │ │ ├── ulimit.go │ │ │ │ │ │ └── ulimit_test.go │ │ │ │ │ ├── gorilla/ │ │ │ │ │ │ ├── context/ │ │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ │ ├── context.go │ │ │ │ │ │ │ ├── context_test.go │ │ │ │ │ │ │ └── doc.go │ │ │ │ │ │ └── mux/ │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ ├── bench_test.go │ │ │ │ │ │ ├── doc.go │ │ │ │ │ │ ├── mux.go │ │ │ │ │ │ ├── mux_test.go │ │ │ │ │ │ ├── old_test.go │ │ │ │ │ │ ├── regexp.go │ │ │ │ │ │ └── route.go │ │ │ │ │ ├── hashicorp/ │ │ │ │ │ │ └── go-cleanhttp/ │ │ │ │ │ │ ├── LICENSE │ │ │ │ │ │ ├── README.md │ │ │ │ │ │ └── cleanhttp.go │ │ │ │ │ └── opencontainers/ │ │ │ │ │ └── runc/ │ │ │ │ │ └── libcontainer/ │ │ │ │ │ └── user/ │ │ │ │ │ ├── MAINTAINERS │ │ │ │ │ ├── lookup.go │ │ │ │ │ ├── lookup_unix.go │ │ │ │ │ ├── lookup_unsupported.go │ │ │ │ │ ├── user.go │ │ │ │ │ └── user_test.go │ │ │ │ └── golang.org/ │ │ │ │ └── x/ │ │ │ │ ├── net/ │ │ │ │ │ └── context/ │ │ │ │ │ ├── context.go │ │ │ │ │ ├── context_test.go │ │ │ │ │ └── withtimeout_test.go │ │ │ │ └── sys/ │ │ │ │ └── unix/ │ │ │ │ ├── asm.s │ │ │ │ ├── asm_darwin_386.s │ │ │ │ ├── asm_darwin_amd64.s │ │ │ │ ├── asm_darwin_arm.s │ │ │ │ ├── asm_darwin_arm64.s │ │ │ │ ├── asm_dragonfly_386.s │ │ │ │ ├── asm_dragonfly_amd64.s │ │ │ │ ├── asm_freebsd_386.s │ │ │ │ ├── asm_freebsd_amd64.s │ │ │ │ ├── asm_freebsd_arm.s │ │ │ │ ├── asm_linux_386.s │ │ │ │ ├── asm_linux_amd64.s │ │ │ │ ├── asm_linux_arm.s │ │ │ │ ├── asm_linux_arm64.s │ │ │ │ ├── asm_linux_ppc64x.s │ │ │ │ ├── asm_netbsd_386.s │ │ │ │ ├── asm_netbsd_amd64.s │ │ │ │ ├── asm_netbsd_arm.s │ │ │ │ ├── asm_openbsd_386.s │ │ │ │ ├── asm_openbsd_amd64.s │ │ │ │ ├── asm_solaris_amd64.s │ │ │ │ ├── constants.go │ │ │ │ ├── creds_test.go │ │ │ │ ├── env_unix.go │ │ │ │ ├── env_unset.go │ │ │ │ ├── export_test.go │ │ │ │ ├── flock.go │ │ │ │ ├── flock_linux_32bit.go │ │ │ │ ├── gccgo.go │ │ │ │ ├── gccgo_c.c │ │ │ │ ├── gccgo_linux_amd64.go │ │ │ │ ├── mkall.sh │ │ │ │ ├── mkerrors.sh │ │ │ │ ├── mksyscall.pl │ │ │ │ ├── mksyscall_solaris.pl │ │ │ │ ├── mksysctl_openbsd.pl │ │ │ │ ├── mksysnum_darwin.pl │ │ │ │ ├── mksysnum_dragonfly.pl │ │ │ │ ├── mksysnum_freebsd.pl │ │ │ │ ├── mksysnum_linux.pl │ │ │ │ ├── mksysnum_netbsd.pl │ │ │ │ ├── mksysnum_openbsd.pl │ │ │ │ ├── mmap_unix_test.go │ │ │ │ ├── race.go │ │ │ │ ├── race0.go │ │ │ │ ├── sockcmsg_linux.go │ │ │ │ ├── sockcmsg_unix.go │ │ │ │ ├── str.go │ │ │ │ ├── syscall.go │ │ │ │ ├── syscall_bsd.go │ │ │ │ ├── syscall_bsd_test.go │ │ │ │ ├── syscall_darwin.go │ │ │ │ ├── syscall_darwin_386.go │ │ │ │ ├── syscall_darwin_amd64.go │ │ │ │ ├── syscall_darwin_arm.go │ │ │ │ ├── syscall_darwin_arm64.go │ │ │ │ ├── syscall_dragonfly.go │ │ │ │ ├── syscall_dragonfly_386.go │ │ │ │ ├── syscall_dragonfly_amd64.go │ │ │ │ ├── syscall_freebsd.go │ │ │ │ ├── syscall_freebsd_386.go │ │ │ │ ├── syscall_freebsd_amd64.go │ │ │ │ ├── syscall_freebsd_arm.go │ │ │ │ ├── syscall_freebsd_test.go │ │ │ │ ├── syscall_linux.go │ │ │ │ ├── syscall_linux_386.go │ │ │ │ ├── syscall_linux_amd64.go │ │ │ │ ├── syscall_linux_arm.go │ │ │ │ ├── syscall_linux_arm64.go │ │ │ │ ├── syscall_linux_ppc64x.go │ │ │ │ ├── syscall_netbsd.go │ │ │ │ ├── syscall_netbsd_386.go │ │ │ │ ├── syscall_netbsd_amd64.go │ │ │ │ ├── syscall_netbsd_arm.go │ │ │ │ ├── syscall_no_getwd.go │ │ │ │ ├── syscall_openbsd.go │ │ │ │ ├── syscall_openbsd_386.go │ │ │ │ ├── syscall_openbsd_amd64.go │ │ │ │ ├── syscall_solaris.go │ │ │ │ ├── syscall_solaris_amd64.go │ │ │ │ ├── syscall_test.go │ │ │ │ ├── syscall_unix.go │ │ │ │ ├── syscall_unix_test.go │ │ │ │ ├── types_darwin.go │ │ │ │ ├── types_dragonfly.go │ │ │ │ ├── types_freebsd.go │ │ │ │ ├── types_linux.go │ │ │ │ ├── types_netbsd.go │ │ │ │ ├── types_openbsd.go │ │ │ │ ├── types_solaris.go │ │ │ │ ├── zerrors_darwin_386.go │ │ │ │ ├── zerrors_darwin_amd64.go │ │ │ │ ├── zerrors_darwin_arm.go │ │ │ │ ├── zerrors_darwin_arm64.go │ │ │ │ ├── zerrors_dragonfly_386.go │ │ │ │ ├── zerrors_dragonfly_amd64.go │ │ │ │ ├── zerrors_freebsd_386.go │ │ │ │ ├── zerrors_freebsd_amd64.go │ │ │ │ ├── zerrors_freebsd_arm.go │ │ │ │ ├── zerrors_linux_386.go │ │ │ │ ├── zerrors_linux_amd64.go │ │ │ │ ├── zerrors_linux_arm.go │ │ │ │ ├── zerrors_linux_arm64.go │ │ │ │ ├── zerrors_linux_ppc64.go │ │ │ │ ├── zerrors_linux_ppc64le.go │ │ │ │ ├── zerrors_netbsd_386.go │ │ │ │ ├── zerrors_netbsd_amd64.go │ │ │ │ ├── zerrors_netbsd_arm.go │ │ │ │ ├── zerrors_openbsd_386.go │ │ │ │ ├── zerrors_openbsd_amd64.go │ │ │ │ ├── zerrors_solaris_amd64.go │ │ │ │ ├── zsyscall_darwin_386.go │ │ │ │ ├── zsyscall_darwin_amd64.go │ │ │ │ ├── zsyscall_darwin_arm.go │ │ │ │ ├── zsyscall_darwin_arm64.go │ │ │ │ ├── zsyscall_dragonfly_386.go │ │ │ │ ├── zsyscall_dragonfly_amd64.go │ │ │ │ ├── zsyscall_freebsd_386.go │ │ │ │ ├── zsyscall_freebsd_amd64.go │ │ │ │ ├── zsyscall_freebsd_arm.go │ │ │ │ ├── zsyscall_linux_386.go │ │ │ │ ├── zsyscall_linux_amd64.go │ │ │ │ ├── zsyscall_linux_arm.go │ │ │ │ ├── zsyscall_linux_arm64.go │ │ │ │ ├── zsyscall_linux_ppc64.go │ │ │ │ ├── zsyscall_linux_ppc64le.go │ │ │ │ ├── zsyscall_netbsd_386.go │ │ │ │ ├── zsyscall_netbsd_amd64.go │ │ │ │ ├── zsyscall_netbsd_arm.go │ │ │ │ ├── zsyscall_openbsd_386.go │ │ │ │ ├── zsyscall_openbsd_amd64.go │ │ │ │ ├── zsyscall_solaris_amd64.go │ │ │ │ ├── zsysctl_openbsd.go │ │ │ │ ├── zsysnum_darwin_386.go │ │ │ │ ├── zsysnum_darwin_amd64.go │ │ │ │ ├── zsysnum_darwin_arm.go │ │ │ │ ├── zsysnum_darwin_arm64.go │ │ │ │ ├── zsysnum_dragonfly_386.go │ │ │ │ ├── zsysnum_dragonfly_amd64.go │ │ │ │ ├── zsysnum_freebsd_386.go │ │ │ │ ├── zsysnum_freebsd_amd64.go │ │ │ │ ├── zsysnum_freebsd_arm.go │ │ │ │ ├── zsysnum_linux_386.go │ │ │ │ ├── zsysnum_linux_amd64.go │ │ │ │ ├── zsysnum_linux_arm.go │ │ │ │ ├── zsysnum_linux_arm64.go │ │ │ │ ├── zsysnum_linux_ppc64.go │ │ │ │ ├── zsysnum_linux_ppc64le.go │ │ │ │ ├── zsysnum_netbsd_386.go │ │ │ │ ├── zsysnum_netbsd_amd64.go │ │ │ │ ├── zsysnum_netbsd_arm.go │ │ │ │ ├── zsysnum_openbsd_386.go │ │ │ │ ├── zsysnum_openbsd_amd64.go │ │ │ │ ├── zsysnum_solaris_amd64.go │ │ │ │ ├── ztypes_darwin_386.go │ │ │ │ ├── ztypes_darwin_amd64.go │ │ │ │ ├── ztypes_darwin_arm.go │ │ │ │ ├── ztypes_darwin_arm64.go │ │ │ │ ├── ztypes_dragonfly_386.go │ │ │ │ ├── ztypes_dragonfly_amd64.go │ │ │ │ ├── ztypes_freebsd_386.go │ │ │ │ ├── ztypes_freebsd_amd64.go │ │ │ │ ├── ztypes_freebsd_arm.go │ │ │ │ ├── ztypes_linux_386.go │ │ │ │ ├── ztypes_linux_amd64.go │ │ │ │ ├── ztypes_linux_arm.go │ │ │ │ ├── ztypes_linux_arm64.go │ │ │ │ ├── ztypes_linux_ppc64.go │ │ │ │ ├── ztypes_linux_ppc64le.go │ │ │ │ ├── ztypes_netbsd_386.go │ │ │ │ ├── ztypes_netbsd_amd64.go │ │ │ │ ├── ztypes_netbsd_arm.go │ │ │ │ ├── ztypes_openbsd_386.go │ │ │ │ ├── ztypes_openbsd_amd64.go │ │ │ │ └── ztypes_solaris_amd64.go │ │ │ ├── image.go │ │ │ ├── image_test.go │ │ │ ├── integration_test.go │ │ │ ├── misc.go │ │ │ ├── misc_test.go │ │ │ ├── network.go │ │ │ ├── network_test.go │ │ │ ├── signal.go │ │ │ ├── tar.go │ │ │ ├── testing/ │ │ │ │ ├── data/ │ │ │ │ │ ├── .dockerignore │ │ │ │ │ ├── Dockerfile │ │ │ │ │ ├── barfile │ │ │ │ │ ├── ca.pem │ │ │ │ │ ├── cert.pem │ │ │ │ │ ├── foofile │ │ │ │ │ ├── key.pem │ │ │ │ │ ├── server.pem │ │ │ │ │ └── serverkey.pem │ │ │ │ ├── server.go │ │ │ │ └── server_test.go │ │ │ ├── tls.go │ │ │ ├── volume.go │ │ │ └── volume_test.go │ │ ├── ghodss/ │ │ │ └── yaml/ │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── fields.go │ │ │ ├── yaml.go │ │ │ └── yaml_test.go │ │ ├── golang/ │ │ │ ├── glog/ │ │ │ │ ├── LICENSE │ │ │ │ ├── README │ │ │ │ ├── glog.go │ │ │ │ ├── glog_file.go │ │ │ │ └── glog_test.go │ │ │ ├── groupcache/ │ │ │ │ ├── .gitignore │ │ │ │ ├── LICENSE │ │ │ │ ├── README.md │ │ │ │ ├── byteview.go │ │ │ │ ├── byteview_test.go │ │ │ │ ├── consistenthash/ │ │ │ │ │ ├── consistenthash.go │ │ │ │ │ └── consistenthash_test.go │ │ │ │ ├── groupcache.go │ │ │ │ ├── groupcache_test.go │ │ │ │ ├── groupcachepb/ │ │ │ │ │ ├── groupcache.pb.go │ │ │ │ │ └── groupcache.proto │ │ │ │ ├── http.go │ │ │ │ ├── http_test.go │ │ │ │ ├── lru/ │ │ │ │ │ ├── lru.go │ │ │ │ │ └── lru_test.go │ │ │ │ ├── peers.go │ │ │ │ ├── singleflight/ │ │ │ │ │ ├── singleflight.go │ │ │ │ │ └── singleflight_test.go │ │ │ │ ├── sinks.go │ │ │ │ └── testpb/ │ │ │ │ ├── test.pb.go │ │ │ │ └── test.proto │ │ │ └── protobuf/ │ │ │ ├── .gitignore │ │ │ ├── AUTHORS │ │ │ ├── CONTRIBUTORS │ │ │ ├── LICENSE │ │ │ ├── Make.protobuf │ │ │ ├── Makefile │ │ │ ├── README.md │ │ │ ├── jsonpb/ │ │ │ │ ├── jsonpb.go │ │ │ │ ├── jsonpb_test.go │ │ │ │ └── jsonpb_test_proto/ │ │ │ │ ├── Makefile │ │ │ │ ├── more_test_objects.proto │ │ │ │ └── test_objects.proto │ │ │ ├── proto/ │ │ │ │ ├── Makefile │ │ │ │ ├── all_test.go │ │ │ │ ├── clone.go │ │ │ │ ├── clone_test.go │ │ │ │ ├── decode.go │ │ │ │ ├── encode.go │ │ │ │ ├── equal.go │ │ │ │ ├── equal_test.go │ │ │ │ ├── extensions.go │ │ │ │ ├── extensions_test.go │ │ │ │ ├── lib.go │ │ │ │ ├── message_set.go │ │ │ │ ├── message_set_test.go │ │ │ │ ├── pointer_reflect.go │ │ │ │ ├── pointer_unsafe.go │ │ │ │ ├── properties.go │ │ │ │ ├── proto3_proto/ │ │ │ │ │ └── proto3.proto │ │ │ │ ├── proto3_test.go │ │ │ │ ├── size2_test.go │ │ │ │ ├── size_test.go │ │ │ │ ├── testdata/ │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── golden_test.go │ │ │ │ │ └── test.proto │ │ │ │ ├── text.go │ │ │ │ ├── text_parser.go │ │ │ │ ├── text_parser_test.go │ │ │ │ └── text_test.go │ │ │ └── protoc-gen-go/ │ │ │ ├── Makefile │ │ │ ├── descriptor/ │ │ │ │ └── Makefile │ │ │ ├── doc.go │ │ │ ├── generator/ │ │ │ │ ├── Makefile │ │ │ │ ├── generator.go │ │ │ │ └── name_test.go │ │ │ ├── internal/ │ │ │ │ └── grpc/ │ │ │ │ └── grpc.go │ │ │ ├── link_grpc.go │ │ │ ├── main.go │ │ │ ├── plugin/ │ │ │ │ ├── Makefile │ │ │ │ └── plugin.pb.golden │ │ │ └── testdata/ │ │ │ ├── Makefile │ │ │ ├── extension_base.proto │ │ │ ├── extension_extra.proto │ │ │ ├── extension_test.go │ │ │ ├── extension_user.proto │ │ │ ├── grpc.proto │ │ │ ├── imp.pb.go.golden │ │ │ ├── imp.proto │ │ │ ├── imp2.proto │ │ │ ├── imp3.proto │ │ │ ├── main_test.go │ │ │ ├── multi/ │ │ │ │ ├── multi1.proto │ │ │ │ ├── multi2.proto │ │ │ │ └── multi3.proto │ │ │ ├── my_test/ │ │ │ │ ├── test.pb.go.golden │ │ │ │ └── test.proto │ │ │ └── proto3.proto │ │ ├── google/ │ │ │ └── gofuzz/ │ │ │ ├── .travis.yml │ │ │ ├── CONTRIBUTING.md │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── doc.go │ │ │ ├── example_test.go │ │ │ ├── fuzz.go │ │ │ └── fuzz_test.go │ │ ├── imdario/ │ │ │ └── mergo/ │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── doc.go │ │ │ ├── map.go │ │ │ ├── merge.go │ │ │ ├── mergo.go │ │ │ ├── mergo_test.go │ │ │ └── testdata/ │ │ │ ├── license.yml │ │ │ └── thing.yml │ │ ├── inconshreveable/ │ │ │ └── mousetrap/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── trap_others.go │ │ │ ├── trap_windows.go │ │ │ └── trap_windows_1.4.go │ │ ├── juju/ │ │ │ └── ratelimit/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── ratelimit.go │ │ │ ├── ratelimit_test.go │ │ │ └── reader.go │ │ ├── masterzen/ │ │ │ ├── simplexml/ │ │ │ │ ├── LICENSE │ │ │ │ ├── README.md │ │ │ │ └── dom/ │ │ │ │ ├── document.go │ │ │ │ ├── dom_test.go │ │ │ │ ├── element.go │ │ │ │ └── namespace.go │ │ │ ├── winrm/ │ │ │ │ ├── .gitignore │ │ │ │ ├── .travis.yml │ │ │ │ ├── LICENSE │ │ │ │ ├── Makefile │ │ │ │ ├── README.md │ │ │ │ ├── development/ │ │ │ │ │ ├── Vagrantfile │ │ │ │ │ ├── sample_requests.txt │ │ │ │ │ └── winrm-tests.sh │ │ │ │ ├── scripts/ │ │ │ │ │ └── test.sh │ │ │ │ ├── soap/ │ │ │ │ │ ├── header.go │ │ │ │ │ ├── header_test.go │ │ │ │ │ ├── message.go │ │ │ │ │ ├── namespaces.go │ │ │ │ │ └── namespaces_test.go │ │ │ │ ├── winrm/ │ │ │ │ │ ├── client.go │ │ │ │ │ ├── client_test.go │ │ │ │ │ ├── command.go │ │ │ │ │ ├── command_test.go │ │ │ │ │ ├── endpoint.go │ │ │ │ │ ├── endpoint_test.go │ │ │ │ │ ├── fixture_test.go │ │ │ │ │ ├── http.go │ │ │ │ │ ├── http_test.go │ │ │ │ │ ├── parameters.go │ │ │ │ │ ├── parameters_test.go │ │ │ │ │ ├── powershell.go │ │ │ │ │ ├── powershell_test.go │ │ │ │ │ ├── request.go │ │ │ │ │ ├── request_test.go │ │ │ │ │ ├── response.go │ │ │ │ │ ├── response_test.go │ │ │ │ │ ├── shell.go │ │ │ │ │ └── shell_test.go │ │ │ │ └── winrm.go │ │ │ └── xmlpath/ │ │ │ ├── LICENSE │ │ │ ├── all_test.go │ │ │ ├── doc.go │ │ │ ├── parser.go │ │ │ └── path.go │ │ ├── mattn/ │ │ │ ├── go-colorable/ │ │ │ │ ├── LICENSE │ │ │ │ ├── README.md │ │ │ │ ├── _example/ │ │ │ │ │ └── main.go │ │ │ │ ├── colorable_others.go │ │ │ │ └── colorable_windows.go │ │ │ └── go-isatty/ │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── _example/ │ │ │ │ └── example.go │ │ │ ├── doc.go │ │ │ ├── isatty_appengine.go │ │ │ ├── isatty_bsd.go │ │ │ ├── isatty_linux.go │ │ │ ├── isatty_solaris.go │ │ │ └── isatty_windows.go │ │ ├── matttproud/ │ │ │ └── golang_protobuf_extensions/ │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── ext/ │ │ │ │ └── moved.go │ │ │ ├── pbtest/ │ │ │ │ ├── doc.go │ │ │ │ ├── example_test.go │ │ │ │ └── quick.go │ │ │ └── pbutil/ │ │ │ ├── all_test.go │ │ │ ├── decode.go │ │ │ ├── doc.go │ │ │ ├── encode.go │ │ │ └── fixtures_test.go │ │ ├── nu7hatch/ │ │ │ └── gouuid/ │ │ │ ├── .gitignore │ │ │ ├── COPYING │ │ │ ├── README.md │ │ │ ├── example_test.go │ │ │ ├── uuid.go │ │ │ └── uuid_test.go │ │ ├── pborman/ │ │ │ └── uuid/ │ │ │ ├── CONTRIBUTORS │ │ │ ├── LICENSE │ │ │ ├── dce.go │ │ │ ├── doc.go │ │ │ ├── hash.go │ │ │ ├── json.go │ │ │ ├── json_test.go │ │ │ ├── node.go │ │ │ ├── seq_test.go │ │ │ ├── time.go │ │ │ ├── util.go │ │ │ ├── uuid.go │ │ │ ├── uuid_test.go │ │ │ ├── version1.go │ │ │ └── version4.go │ │ ├── prometheus/ │ │ │ ├── client_golang/ │ │ │ │ ├── .gitignore │ │ │ │ ├── .travis.yml │ │ │ │ ├── AUTHORS.md │ │ │ │ ├── CHANGELOG.md │ │ │ │ ├── CONTRIBUTING.md │ │ │ │ ├── LICENSE │ │ │ │ ├── NOTICE │ │ │ │ ├── README.md │ │ │ │ ├── VERSION │ │ │ │ ├── api/ │ │ │ │ │ └── prometheus/ │ │ │ │ │ ├── api.go │ │ │ │ │ └── api_test.go │ │ │ │ ├── examples/ │ │ │ │ │ ├── random/ │ │ │ │ │ │ └── main.go │ │ │ │ │ └── simple/ │ │ │ │ │ └── main.go │ │ │ │ └── prometheus/ │ │ │ │ ├── .gitignore │ │ │ │ ├── README.md │ │ │ │ ├── benchmark_test.go │ │ │ │ ├── collector.go │ │ │ │ ├── counter.go │ │ │ │ ├── counter_test.go │ │ │ │ ├── desc.go │ │ │ │ ├── doc.go │ │ │ │ ├── example_clustermanager_test.go │ │ │ │ ├── example_memstats_test.go │ │ │ │ ├── example_selfcollector_test.go │ │ │ │ ├── examples_test.go │ │ │ │ ├── expvar.go │ │ │ │ ├── expvar_test.go │ │ │ │ ├── gauge.go │ │ │ │ ├── gauge_test.go │ │ │ │ ├── go_collector.go │ │ │ │ ├── go_collector_test.go │ │ │ │ ├── histogram.go │ │ │ │ ├── histogram_test.go │ │ │ │ ├── http.go │ │ │ │ ├── http_test.go │ │ │ │ ├── metric.go │ │ │ │ ├── metric_test.go │ │ │ │ ├── process_collector.go │ │ │ │ ├── process_collector_test.go │ │ │ │ ├── push.go │ │ │ │ ├── registry.go │ │ │ │ ├── registry_test.go │ │ │ │ ├── summary.go │ │ │ │ ├── summary_test.go │ │ │ │ ├── untyped.go │ │ │ │ ├── value.go │ │ │ │ ├── vec.go │ │ │ │ └── vec_test.go │ │ │ ├── client_model/ │ │ │ │ ├── .gitignore │ │ │ │ ├── AUTHORS.md │ │ │ │ ├── CONTRIBUTING.md │ │ │ │ ├── LICENSE │ │ │ │ ├── Makefile │ │ │ │ ├── NOTICE │ │ │ │ ├── README.md │ │ │ │ ├── cpp/ │ │ │ │ │ ├── metrics.pb.cc │ │ │ │ │ └── metrics.pb.h │ │ │ │ ├── go/ │ │ │ │ │ └── metrics.pb.go │ │ │ │ ├── metrics.proto │ │ │ │ ├── pom.xml │ │ │ │ ├── python/ │ │ │ │ │ └── prometheus/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── client/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── model/ │ │ │ │ │ ├── __init__.py │ │ │ │ │ └── metrics_pb2.py │ │ │ │ ├── ruby/ │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── Gemfile │ │ │ │ │ ├── LICENSE │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── README.md │ │ │ │ │ ├── Rakefile │ │ │ │ │ ├── lib/ │ │ │ │ │ │ └── prometheus/ │ │ │ │ │ │ └── client/ │ │ │ │ │ │ ├── model/ │ │ │ │ │ │ │ ├── metrics.pb.rb │ │ │ │ │ │ │ └── version.rb │ │ │ │ │ │ └── model.rb │ │ │ │ │ └── prometheus-client-model.gemspec │ │ │ │ ├── setup.py │ │ │ │ └── src/ │ │ │ │ └── main/ │ │ │ │ └── java/ │ │ │ │ └── io/ │ │ │ │ └── prometheus/ │ │ │ │ └── client/ │ │ │ │ └── Metrics.java │ │ │ ├── common/ │ │ │ │ ├── README.md │ │ │ │ ├── expfmt/ │ │ │ │ │ ├── bench_test.go │ │ │ │ │ ├── decode.go │ │ │ │ │ ├── decode_test.go │ │ │ │ │ ├── encode.go │ │ │ │ │ ├── expfmt.go │ │ │ │ │ ├── fuzz/ │ │ │ │ │ │ └── corpus/ │ │ │ │ │ │ ├── from_test_parse_0 │ │ │ │ │ │ ├── from_test_parse_1 │ │ │ │ │ │ ├── from_test_parse_2 │ │ │ │ │ │ ├── from_test_parse_3 │ │ │ │ │ │ ├── from_test_parse_4 │ │ │ │ │ │ ├── from_test_parse_error_0 │ │ │ │ │ │ ├── from_test_parse_error_1 │ │ │ │ │ │ ├── from_test_parse_error_10 │ │ │ │ │ │ ├── from_test_parse_error_11 │ │ │ │ │ │ ├── from_test_parse_error_12 │ │ │ │ │ │ ├── from_test_parse_error_13 │ │ │ │ │ │ ├── from_test_parse_error_14 │ │ │ │ │ │ ├── from_test_parse_error_15 │ │ │ │ │ │ ├── from_test_parse_error_16 │ │ │ │ │ │ ├── from_test_parse_error_17 │ │ │ │ │ │ ├── from_test_parse_error_18 │ │ │ │ │ │ ├── from_test_parse_error_19 │ │ │ │ │ │ ├── from_test_parse_error_2 │ │ │ │ │ │ ├── from_test_parse_error_3 │ │ │ │ │ │ ├── from_test_parse_error_4 │ │ │ │ │ │ ├── from_test_parse_error_5 │ │ │ │ │ │ ├── from_test_parse_error_6 │ │ │ │ │ │ ├── from_test_parse_error_7 │ │ │ │ │ │ ├── from_test_parse_error_8 │ │ │ │ │ │ ├── from_test_parse_error_9 │ │ │ │ │ │ └── minimal │ │ │ │ │ ├── fuzz.go │ │ │ │ │ ├── json_decode.go │ │ │ │ │ ├── json_decode_test.go │ │ │ │ │ ├── testdata/ │ │ │ │ │ │ ├── json2 │ │ │ │ │ │ ├── protobuf │ │ │ │ │ │ └── text │ │ │ │ │ ├── text_create.go │ │ │ │ │ ├── text_create_test.go │ │ │ │ │ ├── text_parse.go │ │ │ │ │ └── text_parse_test.go │ │ │ │ ├── model/ │ │ │ │ │ ├── fingerprinting.go │ │ │ │ │ ├── labels.go │ │ │ │ │ ├── labels_test.go │ │ │ │ │ ├── labelset.go │ │ │ │ │ ├── metric.go │ │ │ │ │ ├── metric_test.go │ │ │ │ │ ├── model.go │ │ │ │ │ ├── signature.go │ │ │ │ │ ├── signature_test.go │ │ │ │ │ ├── time.go │ │ │ │ │ ├── time_test.go │ │ │ │ │ ├── value.go │ │ │ │ │ └── value_test.go │ │ │ │ └── route/ │ │ │ │ └── route.go │ │ │ └── procfs/ │ │ │ ├── .travis.yml │ │ │ ├── AUTHORS.md │ │ │ ├── CONTRIBUTING.md │ │ │ ├── LICENSE │ │ │ ├── NOTICE │ │ │ ├── README.md │ │ │ ├── doc.go │ │ │ ├── fixtures/ │ │ │ │ ├── 26231/ │ │ │ │ │ ├── cmdline │ │ │ │ │ ├── fd/ │ │ │ │ │ │ ├── 0 │ │ │ │ │ │ ├── 1 │ │ │ │ │ │ ├── 2 │ │ │ │ │ │ ├── 3 │ │ │ │ │ │ └── 4 │ │ │ │ │ ├── limits │ │ │ │ │ └── stat │ │ │ │ ├── 584/ │ │ │ │ │ └── stat │ │ │ │ └── stat │ │ │ ├── fs.go │ │ │ ├── fs_test.go │ │ │ ├── proc.go │ │ │ ├── proc_limits.go │ │ │ ├── proc_limits_test.go │ │ │ ├── proc_stat.go │ │ │ ├── proc_stat_test.go │ │ │ ├── proc_test.go │ │ │ ├── stat.go │ │ │ └── stat_test.go │ │ ├── russross/ │ │ │ └── blackfriday/ │ │ │ ├── .gitignore │ │ │ ├── .travis.yml │ │ │ ├── LICENSE.txt │ │ │ ├── README.md │ │ │ ├── block.go │ │ │ ├── block_test.go │ │ │ ├── html.go │ │ │ ├── inline.go │ │ │ ├── inline_test.go │ │ │ ├── latex.go │ │ │ ├── markdown.go │ │ │ ├── smartypants.go │ │ │ ├── upskirtref/ │ │ │ │ ├── Amps and angle encoding.html │ │ │ │ ├── Amps and angle encoding.text │ │ │ │ ├── Auto links.html │ │ │ │ ├── Auto links.text │ │ │ │ ├── Backslash escapes.html │ │ │ │ ├── Backslash escapes.text │ │ │ │ ├── Blockquotes with code blocks.html │ │ │ │ ├── Blockquotes with code blocks.text │ │ │ │ ├── Code Blocks.html │ │ │ │ ├── Code Blocks.text │ │ │ │ ├── Code Spans.html │ │ │ │ ├── Code Spans.text │ │ │ │ ├── Hard-wrapped paragraphs with list-like lines no empty line before block.html │ │ │ │ ├── Hard-wrapped paragraphs with list-like lines no empty line before block.text │ │ │ │ ├── Hard-wrapped paragraphs with list-like lines.html │ │ │ │ ├── Hard-wrapped paragraphs with list-like lines.text │ │ │ │ ├── Horizontal rules.html │ │ │ │ ├── Horizontal rules.text │ │ │ │ ├── Inline HTML (Advanced).html │ │ │ │ ├── Inline HTML (Advanced).text │ │ │ │ ├── Inline HTML (Simple).html │ │ │ │ ├── Inline HTML (Simple).text │ │ │ │ ├── Inline HTML comments.html │ │ │ │ ├── Inline HTML comments.text │ │ │ │ ├── Links, inline style.html │ │ │ │ ├── Links, inline style.text │ │ │ │ ├── Links, reference style.html │ │ │ │ ├── Links, reference style.text │ │ │ │ ├── Links, shortcut references.html │ │ │ │ ├── Links, shortcut references.text │ │ │ │ ├── Literal quotes in titles.html │ │ │ │ ├── Literal quotes in titles.text │ │ │ │ ├── Markdown Documentation - Basics.html │ │ │ │ ├── Markdown Documentation - Basics.text │ │ │ │ ├── Markdown Documentation - Syntax.html │ │ │ │ ├── Markdown Documentation - Syntax.text │ │ │ │ ├── Nested blockquotes.html │ │ │ │ ├── Nested blockquotes.text │ │ │ │ ├── Ordered and unordered lists.html │ │ │ │ ├── Ordered and unordered lists.text │ │ │ │ ├── Strong and em together.html │ │ │ │ ├── Strong and em together.text │ │ │ │ ├── Tabs.html │ │ │ │ ├── Tabs.text │ │ │ │ ├── Tidyness.html │ │ │ │ └── Tidyness.text │ │ │ └── upskirtref_test.go │ │ ├── shurcooL/ │ │ │ └── sanitized_anchor_name/ │ │ │ ├── .travis.yml │ │ │ ├── README.md │ │ │ ├── main.go │ │ │ └── main_test.go │ │ ├── spf13/ │ │ │ ├── cobra/ │ │ │ │ ├── .gitignore │ │ │ │ ├── .mailmap │ │ │ │ ├── .travis.yml │ │ │ │ ├── LICENSE.txt │ │ │ │ ├── README.md │ │ │ │ ├── bash_completions.go │ │ │ │ ├── bash_completions.md │ │ │ │ ├── bash_completions_test.go │ │ │ │ ├── cobra/ │ │ │ │ │ ├── cmd/ │ │ │ │ │ │ ├── add.go │ │ │ │ │ │ ├── helpers.go │ │ │ │ │ │ ├── helpers_test.go │ │ │ │ │ │ ├── init.go │ │ │ │ │ │ ├── licenses.go │ │ │ │ │ │ └── root.go │ │ │ │ │ └── main.go │ │ │ │ ├── cobra.go │ │ │ │ ├── cobra_test.go │ │ │ │ ├── command.go │ │ │ │ ├── command_test.go │ │ │ │ ├── doc_util.go │ │ │ │ ├── examples_test.go │ │ │ │ ├── man_docs.go │ │ │ │ ├── man_docs.md │ │ │ │ ├── man_docs_test.go │ │ │ │ ├── md_docs.go │ │ │ │ ├── md_docs.md │ │ │ │ └── md_docs_test.go │ │ │ └── pflag/ │ │ │ ├── .travis.yml │ │ │ ├── LICENSE │ │ │ ├── README.md │ │ │ ├── bool.go │ │ │ ├── bool_test.go │ │ │ ├── count.go │ │ │ ├── count_test.go │ │ │ ├── duration.go │ │ │ ├── example_test.go │ │ │ ├── export_test.go │ │ │ ├── flag.go │ │ │ ├── flag_test.go │ │ │ ├── float32.go │ │ │ ├── float64.go │ │ │ ├── golangflag.go │ │ │ ├── golangflag_test.go │ │ │ ├── int.go │ │ │ ├── int32.go │ │ │ ├── int64.go │ │ │ ├── int8.go │ │ │ ├── int_slice.go │ │ │ ├── int_slice_test.go │ │ │ ├── ip.go │ │ │ ├── ip_test.go │ │ │ ├── ipmask.go │ │ │ ├── ipnet.go │ │ │ ├── ipnet_test.go │ │ │ ├── string.go │ │ │ ├── string_slice.go │ │ │ ├── string_slice_test.go │ │ │ ├── uint.go │ │ │ ├── uint16.go │ │ │ ├── uint32.go │ │ │ ├── uint64.go │ │ │ ├── uint8.go │ │ │ └── verify/ │ │ │ ├── all.sh │ │ │ ├── gofmt.sh │ │ │ └── golint.sh │ │ └── ugorji/ │ │ └── go/ │ │ ├── LICENSE │ │ ├── README.md │ │ ├── codec/ │ │ │ ├── 0doc.go │ │ │ ├── README.md │ │ │ ├── binc.go │ │ │ ├── cbor.go │ │ │ ├── cbor_test.go │ │ │ ├── codec_test.go │ │ │ ├── codecgen/ │ │ │ │ ├── README.md │ │ │ │ ├── gen.go │ │ │ │ └── z.go │ │ │ ├── codecgen_test.go │ │ │ ├── decode.go │ │ │ ├── encode.go │ │ │ ├── fast-path.generated.go │ │ │ ├── fast-path.go.tmpl │ │ │ ├── fast-path.not.go │ │ │ ├── gen-dec-array.go.tmpl │ │ │ ├── gen-dec-map.go.tmpl │ │ │ ├── gen-helper.generated.go │ │ │ ├── gen-helper.go.tmpl │ │ │ ├── gen.generated.go │ │ │ ├── gen.go │ │ │ ├── helper.go │ │ │ ├── helper_internal.go │ │ │ ├── helper_not_unsafe.go │ │ │ ├── helper_test.go │ │ │ ├── helper_unsafe.go │ │ │ ├── json.go │ │ │ ├── msgpack.go │ │ │ ├── noop.go │ │ │ ├── prebuild.go │ │ │ ├── prebuild.sh │ │ │ ├── py_test.go │ │ │ ├── rpc.go │ │ │ ├── simple.go │ │ │ ├── test-cbor-goldens.json │ │ │ ├── test.py │ │ │ ├── tests.sh │ │ │ ├── time.go │ │ │ └── values_test.go │ │ └── msgpack.org.md │ ├── golang.org/ │ │ └── x/ │ │ ├── crypto/ │ │ │ ├── .gitattributes │ │ │ ├── .gitignore │ │ │ ├── AUTHORS │ │ │ ├── CONTRIBUTING.md │ │ │ ├── CONTRIBUTORS │ │ │ ├── LICENSE │ │ │ ├── PATENTS │ │ │ ├── README │ │ │ ├── bcrypt/ │ │ │ │ ├── base64.go │ │ │ │ ├── bcrypt.go │ │ │ │ └── bcrypt_test.go │ │ │ ├── blowfish/ │ │ │ │ ├── block.go │ │ │ │ ├── blowfish_test.go │ │ │ │ ├── cipher.go │ │ │ │ └── const.go │ │ │ ├── bn256/ │ │ │ │ ├── bn256.go │ │ │ │ ├── bn256_test.go │ │ │ │ ├── constants.go │ │ │ │ ├── curve.go │ │ │ │ ├── example_test.go │ │ │ │ ├── gfp12.go │ │ │ │ ├── gfp2.go │ │ │ │ ├── gfp6.go │ │ │ │ ├── optate.go │ │ │ │ └── twist.go │ │ │ ├── cast5/ │ │ │ │ ├── cast5.go │ │ │ │ └── cast5_test.go │ │ │ ├── codereview.cfg │ │ │ ├── curve25519/ │ │ │ │ ├── const_amd64.s │ │ │ │ ├── cswap_amd64.s │ │ │ │ ├── curve25519.go │ │ │ │ ├── curve25519_test.go │ │ │ │ ├── doc.go │ │ │ │ ├── freeze_amd64.s │ │ │ │ ├── ladderstep_amd64.s │ │ │ │ ├── mont25519_amd64.go │ │ │ │ ├── mul_amd64.s │ │ │ │ └── square_amd64.s │ │ │ ├── hkdf/ │ │ │ │ ├── example_test.go │ │ │ │ ├── hkdf.go │ │ │ │ └── hkdf_test.go │ │ │ ├── md4/ │ │ │ │ ├── md4.go │ │ │ │ ├── md4_test.go │ │ │ │ └── md4block.go │ │ │ ├── nacl/ │ │ │ │ ├── box/ │ │ │ │ │ ├── box.go │ │ │ │ │ └── box_test.go │ │ │ │ └── secretbox/ │ │ │ │ ├── secretbox.go │ │ │ │ └── secretbox_test.go │ │ │ ├── ocsp/ │ │ │ │ ├── ocsp.go │ │ │ │ └── ocsp_test.go │ │ │ ├── openpgp/ │ │ │ │ ├── armor/ │ │ │ │ │ ├── armor.go │ │ │ │ │ ├── armor_test.go │ │ │ │ │ └── encode.go │ │ │ │ ├── canonical_text.go │ │ │ │ ├── canonical_text_test.go │ │ │ │ ├── clearsign/ │ │ │ │ │ ├── clearsign.go │ │ │ │ │ └── clearsign_test.go │ │ │ │ ├── elgamal/ │ │ │ │ │ ├── elgamal.go │ │ │ │ │ └── elgamal_test.go │ │ │ │ ├── errors/ │ │ │ │ │ └── errors.go │ │ │ │ ├── keys.go │ │ │ │ ├── keys_test.go │ │ │ │ ├── packet/ │ │ │ │ │ ├── compressed.go │ │ │ │ │ ├── compressed_test.go │ │ │ │ │ ├── config.go │ │ │ │ │ ├── encrypted_key.go │ │ │ │ │ ├── encrypted_key_test.go │ │ │ │ │ ├── literal.go │ │ │ │ │ ├── ocfb.go │ │ │ │ │ ├── ocfb_test.go │ │ │ │ │ ├── one_pass_signature.go │ │ │ │ │ ├── opaque.go │ │ │ │ │ ├── opaque_test.go │ │ │ │ │ ├── packet.go │ │ │ │ │ ├── packet_test.go │ │ │ │ │ ├── private_key.go │ │ │ │ │ ├── private_key_test.go │ │ │ │ │ ├── public_key.go │ │ │ │ │ ├── public_key_test.go │ │ │ │ │ ├── public_key_v3.go │ │ │ │ │ ├── public_key_v3_test.go │ │ │ │ │ ├── reader.go │ │ │ │ │ ├── signature.go │ │ │ │ │ ├── signature_test.go │ │ │ │ │ ├── signature_v3.go │ │ │ │ │ ├── signature_v3_test.go │ │ │ │ │ ├── symmetric_key_encrypted.go │ │ │ │ │ ├── symmetric_key_encrypted_test.go │ │ │ │ │ ├── symmetrically_encrypted.go │ │ │ │ │ ├── symmetrically_encrypted_test.go │ │ │ │ │ ├── userattribute.go │ │ │ │ │ ├── userattribute_test.go │ │ │ │ │ ├── userid.go │ │ │ │ │ └── userid_test.go │ │ │ │ ├── read.go │ │ │ │ ├── read_test.go │ │ │ │ ├── s2k/ │ │ │ │ │ ├── s2k.go │ │ │ │ │ └── s2k_test.go │ │ │ │ ├── write.go │ │ │ │ └── write_test.go │ │ │ ├── otr/ │ │ │ │ ├── libotr_test_helper.c │ │ │ │ ├── otr.go │ │ │ │ ├── otr_test.go │ │ │ │ └── smp.go │ │ │ ├── pbkdf2/ │ │ │ │ ├── pbkdf2.go │ │ │ │ └── pbkdf2_test.go │ │ │ ├── poly1305/ │ │ │ │ ├── const_amd64.s │ │ │ │ ├── poly1305.go │ │ │ │ ├── poly1305_amd64.s │ │ │ │ ├── poly1305_test.go │ │ │ │ ├── sum_amd64.go │ │ │ │ └── sum_ref.go │ │ │ ├── ripemd160/ │ │ │ │ ├── ripemd160.go │ │ │ │ ├── ripemd160_test.go │ │ │ │ └── ripemd160block.go │ │ │ ├── salsa20/ │ │ │ │ ├── salsa/ │ │ │ │ │ ├── hsalsa20.go │ │ │ │ │ ├── salsa2020_amd64.s │ │ │ │ │ ├── salsa208.go │ │ │ │ │ ├── salsa20_amd64.go │ │ │ │ │ ├── salsa20_ref.go │ │ │ │ │ └── salsa_test.go │ │ │ │ ├── salsa20.go │ │ │ │ └── salsa20_test.go │ │ │ ├── scrypt/ │ │ │ │ ├── scrypt.go │ │ │ │ └── scrypt_test.go │ │ │ ├── sha3/ │ │ │ │ ├── doc.go │ │ │ │ ├── hashes.go │ │ │ │ ├── keccakf.go │ │ │ │ ├── register.go │ │ │ │ ├── sha3.go │ │ │ │ ├── sha3_test.go │ │ │ │ ├── shake.go │ │ │ │ ├── testdata/ │ │ │ │ │ └── keccakKats.json.deflate │ │ │ │ ├── xor.go │ │ │ │ ├── xor_generic.go │ │ │ │ └── xor_unaligned.go │ │ │ ├── ssh/ │ │ │ │ ├── agent/ │ │ │ │ │ ├── client.go │ │ │ │ │ ├── client_test.go │ │ │ │ │ ├── forward.go │ │ │ │ │ ├── keyring.go │ │ │ │ │ ├── server.go │ │ │ │ │ ├── server_test.go │ │ │ │ │ └── testdata_test.go │ │ │ │ ├── benchmark_test.go │ │ │ │ ├── buffer.go │ │ │ │ ├── buffer_test.go │ │ │ │ ├── certs.go │ │ │ │ ├── certs_test.go │ │ │ │ ├── channel.go │ │ │ │ ├── cipher.go │ │ │ │ ├── cipher_test.go │ │ │ │ ├── client.go │ │ │ │ ├── client_auth.go │ │ │ │ ├── client_auth_test.go │ │ │ │ ├── client_test.go │ │ │ │ ├── common.go │ │ │ │ ├── connection.go │ │ │ │ ├── doc.go │ │ │ │ ├── example_test.go │ │ │ │ ├── handshake.go │ │ │ │ ├── handshake_test.go │ │ │ │ ├── kex.go │ │ │ │ ├── kex_test.go │ │ │ │ ├── keys.go │ │ │ │ ├── keys_test.go │ │ │ │ ├── mac.go │ │ │ │ ├── mempipe_test.go │ │ │ │ ├── messages.go │ │ │ │ ├── messages_test.go │ │ │ │ ├── mux.go │ │ │ │ ├── mux_test.go │ │ │ │ ├── server.go │ │ │ │ ├── session.go │ │ │ │ ├── session_test.go │ │ │ │ ├── tcpip.go │ │ │ │ ├── tcpip_test.go │ │ │ │ ├── terminal/ │ │ │ │ │ ├── terminal.go │ │ │ │ │ ├── terminal_test.go │ │ │ │ │ ├── util.go │ │ │ │ │ ├── util_bsd.go │ │ │ │ │ ├── util_linux.go │ │ │ │ │ └── util_windows.go │ │ │ │ ├── test/ │ │ │ │ │ ├── agent_unix_test.go │ │ │ │ │ ├── cert_test.go │ │ │ │ │ ├── doc.go │ │ │ │ │ ├── forward_unix_test.go │ │ │ │ │ ├── session_test.go │ │ │ │ │ ├── tcpip_test.go │ │ │ │ │ ├── test_unix_test.go │ │ │ │ │ └── testdata_test.go │ │ │ │ ├── testdata/ │ │ │ │ │ ├── doc.go │ │ │ │ │ └── keys.go │ │ │ │ ├── testdata_test.go │ │ │ │ ├── transport.go │ │ │ │ └── transport_test.go │ │ │ ├── twofish/ │ │ │ │ ├── twofish.go │ │ │ │ └── twofish_test.go │ │ │ ├── xtea/ │ │ │ │ ├── block.go │ │ │ │ ├── cipher.go │ │ │ │ └── xtea_test.go │ │ │ └── xts/ │ │ │ ├── xts.go │ │ │ └── xts_test.go │ │ ├── net/ │ │ │ ├── .gitattributes │ │ │ ├── .gitignore │ │ │ ├── AUTHORS │ │ │ ├── CONTRIBUTING.md │ │ │ ├── CONTRIBUTORS │ │ │ ├── LICENSE │ │ │ ├── PATENTS │ │ │ ├── README │ │ │ ├── codereview.cfg │ │ │ ├── context/ │ │ │ │ ├── context.go │ │ │ │ ├── context_test.go │ │ │ │ ├── ctxhttp/ │ │ │ │ │ ├── cancelreq.go │ │ │ │ │ ├── cancelreq_go14.go │ │ │ │ │ ├── ctxhttp.go │ │ │ │ │ └── ctxhttp_test.go │ │ │ │ └── withtimeout_test.go │ │ │ ├── dict/ │ │ │ │ └── dict.go │ │ │ ├── html/ │ │ │ │ ├── atom/ │ │ │ │ │ ├── atom.go │ │ │ │ │ ├── atom_test.go │ │ │ │ │ ├── gen.go │ │ │ │ │ ├── table.go │ │ │ │ │ └── table_test.go │ │ │ │ ├── charset/ │ │ │ │ │ ├── charset.go │ │ │ │ │ ├── charset_test.go │ │ │ │ │ ├── gen.go │ │ │ │ │ ├── table.go │ │ │ │ │ └── testdata/ │ │ │ │ │ ├── HTTP-charset.html │ │ │ │ │ ├── HTTP-vs-UTF-8-BOM.html │ │ │ │ │ ├── HTTP-vs-meta-charset.html │ │ │ │ │ ├── HTTP-vs-meta-content.html │ │ │ │ │ ├── No-encoding-declaration.html │ │ │ │ │ ├── README │ │ │ │ │ ├── UTF-16BE-BOM.html │ │ │ │ │ ├── UTF-16LE-BOM.html │ │ │ │ │ ├── UTF-8-BOM-vs-meta-charset.html │ │ │ │ │ ├── UTF-8-BOM-vs-meta-content.html │ │ │ │ │ ├── meta-charset-attribute.html │ │ │ │ │ └── meta-content-attribute.html │ │ │ │ ├── const.go │ │ │ │ ├── doc.go │ │ │ │ ├── doctype.go │ │ │ │ ├── entity.go │ │ │ │ ├── entity_test.go │ │ │ │ ├── escape.go │ │ │ │ ├── escape_test.go │ │ │ │ ├── example_test.go │ │ │ │ ├── foreign.go │ │ │ │ ├── node.go │ │ │ │ ├── node_test.go │ │ │ │ ├── parse.go │ │ │ │ ├── parse_test.go │ │ │ │ ├── render.go │ │ │ │ ├── render_test.go │ │ │ │ ├── testdata/ │ │ │ │ │ ├── go1.html │ │ │ │ │ └── webkit/ │ │ │ │ │ └── README │ │ │ │ ├── token.go │ │ │ │ └── token_test.go │ │ │ ├── http2/ │ │ │ │ ├── .gitignore │ │ │ │ ├── Dockerfile │ │ │ │ ├── Makefile │ │ │ │ ├── README │ │ │ │ ├── buffer.go │ │ │ │ ├── buffer_test.go │ │ │ │ ├── errors.go │ │ │ │ ├── errors_test.go │ │ │ │ ├── flow.go │ │ │ │ ├── flow_test.go │ │ │ │ ├── frame.go │ │ │ │ ├── frame_test.go │ │ │ │ ├── gotrack.go │ │ │ │ ├── gotrack_test.go │ │ │ │ ├── h2i/ │ │ │ │ │ ├── README.md │ │ │ │ │ └── h2i.go │ │ │ │ ├── headermap.go │ │ │ │ ├── hpack/ │ │ │ │ │ ├── encode.go │ │ │ │ │ ├── encode_test.go │ │ │ │ │ ├── hpack.go │ │ │ │ │ ├── hpack_test.go │ │ │ │ │ ├── huffman.go │ │ │ │ │ └── tables.go │ │ │ │ ├── http2.go │ │ │ │ ├── http2_test.go │ │ │ │ ├── pipe.go │ │ │ │ ├── pipe_test.go │ │ │ │ ├── priority_test.go │ │ │ │ ├── server.go │ │ │ │ ├── server_test.go │ │ │ │ ├── testdata/ │ │ │ │ │ └── draft-ietf-httpbis-http2.xml │ │ │ │ ├── transport.go │ │ │ │ ├── transport_test.go │ │ │ │ ├── write.go │ │ │ │ ├── writesched.go │ │ │ │ └── z_spec_test.go │ │ │ ├── icmp/ │ │ │ │ ├── dstunreach.go │ │ │ │ ├── echo.go │ │ │ │ ├── endpoint.go │ │ │ │ ├── example_test.go │ │ │ │ ├── extension.go │ │ │ │ ├── extension_test.go │ │ │ │ ├── helper_posix.go │ │ │ │ ├── interface.go │ │ │ │ ├── ipv4.go │ │ │ │ ├── ipv4_test.go │ │ │ │ ├── ipv6.go │ │ │ │ ├── listen_posix.go │ │ │ │ ├── listen_stub.go │ │ │ │ ├── message.go │ │ │ │ ├── message_test.go │ │ │ │ ├── messagebody.go │ │ │ │ ├── mpls.go │ │ │ │ ├── multipart.go │ │ │ │ ├── multipart_test.go │ │ │ │ ├── packettoobig.go │ │ │ │ ├── paramprob.go │ │ │ │ ├── ping_test.go │ │ │ │ ├── sys_freebsd.go │ │ │ │ └── timeexceeded.go │ │ │ ├── idna/ │ │ │ │ ├── idna.go │ │ │ │ ├── idna_test.go │ │ │ │ ├── punycode.go │ │ │ │ └── punycode_test.go │ │ │ ├── internal/ │ │ │ │ ├── iana/ │ │ │ │ │ ├── const.go │ │ │ │ │ └── gen.go │ │ │ │ ├── nettest/ │ │ │ │ │ ├── error_posix.go │ │ │ │ │ ├── error_stub.go │ │ │ │ │ ├── interface.go │ │ │ │ │ ├── rlimit.go │ │ │ │ │ ├── rlimit_stub.go │ │ │ │ │ ├── rlimit_unix.go │ │ │ │ │ ├── rlimit_windows.go │ │ │ │ │ ├── stack.go │ │ │ │ │ ├── stack_stub.go │ │ │ │ │ ├── stack_unix.go │ │ │ │ │ └── stack_windows.go │ │ │ │ └── timeseries/ │ │ │ │ ├── timeseries.go │ │ │ │ └── timeseries_test.go │ │ │ ├── ipv4/ │ │ │ │ ├── control.go │ │ │ │ ├── control_bsd.go │ │ │ │ ├── control_pktinfo.go │ │ │ │ ├── control_stub.go │ │ │ │ ├── control_unix.go │ │ │ │ ├── control_windows.go │ │ │ │ ├── defs_darwin.go │ │ │ │ ├── defs_dragonfly.go │ │ │ │ ├── defs_freebsd.go │ │ │ │ ├── defs_linux.go │ │ │ │ ├── defs_netbsd.go │ │ │ │ ├── defs_openbsd.go │ │ │ │ ├── defs_solaris.go │ │ │ │ ├── dgramopt_posix.go │ │ │ │ ├── dgramopt_stub.go │ │ │ │ ├── doc.go │ │ │ │ ├── endpoint.go │ │ │ │ ├── example_test.go │ │ │ │ ├── gen.go │ │ │ │ ├── genericopt_posix.go │ │ │ │ ├── genericopt_stub.go │ │ │ │ ├── header.go │ │ │ │ ├── header_test.go │ │ │ │ ├── helper.go │ │ │ │ ├── helper_stub.go │ │ │ │ ├── helper_unix.go │ │ │ │ ├── helper_windows.go │ │ │ │ ├── iana.go │ │ │ │ ├── icmp.go │ │ │ │ ├── icmp_linux.go │ │ │ │ ├── icmp_stub.go │ │ │ │ ├── icmp_test.go │ │ │ │ ├── mocktransponder_test.go │ │ │ │ ├── multicast_test.go │ │ │ │ ├── multicastlistener_test.go │ │ │ │ ├── multicastsockopt_test.go │ │ │ │ ├── packet.go │ │ │ │ ├── payload.go │ │ │ │ ├── payload_cmsg.go │ │ │ │ ├── payload_nocmsg.go │ │ │ │ ├── readwrite_test.go │ │ │ │ ├── sockopt.go │ │ │ │ ├── sockopt_asmreq.go │ │ │ │ ├── sockopt_asmreq_stub.go │ │ │ │ ├── sockopt_asmreq_unix.go │ │ │ │ ├── sockopt_asmreq_windows.go │ │ │ │ ├── sockopt_asmreqn_stub.go │ │ │ │ ├── sockopt_asmreqn_unix.go │ │ │ │ ├── sockopt_ssmreq_stub.go │ │ │ │ ├── sockopt_ssmreq_unix.go │ │ │ │ ├── sockopt_stub.go │ │ │ │ ├── sockopt_unix.go │ │ │ │ ├── sockopt_windows.go │ │ │ │ ├── sys_bsd.go │ │ │ │ ├── sys_darwin.go │ │ │ │ ├── sys_freebsd.go │ │ │ │ ├── sys_linux.go │ │ │ │ ├── sys_openbsd.go │ │ │ │ ├── sys_stub.go │ │ │ │ ├── sys_windows.go │ │ │ │ ├── syscall_linux_386.go │ │ │ │ ├── syscall_unix.go │ │ │ │ ├── thunk_linux_386.s │ │ │ │ ├── unicast_test.go │ │ │ │ ├── unicastsockopt_test.go │ │ │ │ ├── zsys_darwin.go │ │ │ │ ├── zsys_dragonfly.go │ │ │ │ ├── zsys_freebsd_386.go │ │ │ │ ├── zsys_freebsd_amd64.go │ │ │ │ ├── zsys_freebsd_arm.go │ │ │ │ ├── zsys_linux_386.go │ │ │ │ ├── zsys_linux_amd64.go │ │ │ │ ├── zsys_linux_arm.go │ │ │ │ ├── zsys_linux_arm64.go │ │ │ │ ├── zsys_linux_ppc64.go │ │ │ │ ├── zsys_linux_ppc64le.go │ │ │ │ ├── zsys_netbsd.go │ │ │ │ ├── zsys_openbsd.go │ │ │ │ └── zsys_solaris.go │ │ │ ├── ipv6/ │ │ │ │ ├── control.go │ │ │ │ ├── control_rfc2292_unix.go │ │ │ │ ├── control_rfc3542_unix.go │ │ │ │ ├── control_stub.go │ │ │ │ ├── control_unix.go │ │ │ │ ├── control_windows.go │ │ │ │ ├── defs_darwin.go │ │ │ │ ├── defs_dragonfly.go │ │ │ │ ├── defs_freebsd.go │ │ │ │ ├── defs_linux.go │ │ │ │ ├── defs_netbsd.go │ │ │ │ ├── defs_openbsd.go │ │ │ │ ├── defs_solaris.go │ │ │ │ ├── dgramopt_posix.go │ │ │ │ ├── dgramopt_stub.go │ │ │ │ ├── doc.go │ │ │ │ ├── endpoint.go │ │ │ │ ├── example_test.go │ │ │ │ ├── gen.go │ │ │ │ ├── genericopt_posix.go │ │ │ │ ├── genericopt_stub.go │ │ │ │ ├── header.go │ │ │ │ ├── header_test.go │ │ │ │ ├── helper.go │ │ │ │ ├── helper_stub.go │ │ │ │ ├── helper_unix.go │ │ │ │ ├── helper_windows.go │ │ │ │ ├── iana.go │ │ │ │ ├── icmp.go │ │ │ │ ├── icmp_bsd.go │ │ │ │ ├── icmp_linux.go │ │ │ │ ├── icmp_solaris.go │ │ │ │ ├── icmp_stub.go │ │ │ │ ├── icmp_test.go │ │ │ │ ├── icmp_windows.go │ │ │ │ ├── mocktransponder_test.go │ │ │ │ ├── multicast_test.go │ │ │ │ ├── multicastlistener_test.go │ │ │ │ ├── multicastsockopt_test.go │ │ │ │ ├── payload.go │ │ │ │ ├── payload_cmsg.go │ │ │ │ ├── payload_nocmsg.go │ │ │ │ ├── readwrite_test.go │ │ │ │ ├── sockopt.go │ │ │ │ ├── sockopt_asmreq_unix.go │ │ │ │ ├── sockopt_asmreq_windows.go │ │ │ │ ├── sockopt_ssmreq_stub.go │ │ │ │ ├── sockopt_ssmreq_unix.go │ │ │ │ ├── sockopt_stub.go │ │ │ │ ├── sockopt_test.go │ │ │ │ ├── sockopt_unix.go │ │ │ │ ├── sockopt_windows.go │ │ │ │ ├── sys_bsd.go │ │ │ │ ├── sys_darwin.go │ │ │ │ ├── sys_freebsd.go │ │ │ │ ├── sys_linux.go │ │ │ │ ├── sys_stub.go │ │ │ │ ├── sys_windows.go │ │ │ │ ├── syscall_linux_386.go │ │ │ │ ├── syscall_unix.go │ │ │ │ ├── thunk_linux_386.s │ │ │ │ ├── unicast_test.go │ │ │ │ ├── unicastsockopt_test.go │ │ │ │ ├── zsys_darwin.go │ │ │ │ ├── zsys_dragonfly.go │ │ │ │ ├── zsys_freebsd_386.go │ │ │ │ ├── zsys_freebsd_amd64.go │ │ │ │ ├── zsys_freebsd_arm.go │ │ │ │ ├── zsys_linux_386.go │ │ │ │ ├── zsys_linux_amd64.go │ │ │ │ ├── zsys_linux_arm.go │ │ │ │ ├── zsys_linux_arm64.go │ │ │ │ ├── zsys_linux_ppc64.go │ │ │ │ ├── zsys_linux_ppc64le.go │ │ │ │ ├── zsys_netbsd.go │ │ │ │ ├── zsys_openbsd.go │ │ │ │ └── zsys_solaris.go │ │ │ ├── netutil/ │ │ │ │ ├── listen.go │ │ │ │ └── listen_test.go │ │ │ ├── proxy/ │ │ │ │ ├── direct.go │ │ │ │ ├── per_host.go │ │ │ │ ├── per_host_test.go │ │ │ │ ├── proxy.go │ │ │ │ ├── proxy_test.go │ │ │ │ └── socks5.go │ │ │ ├── publicsuffix/ │ │ │ │ ├── gen.go │ │ │ │ ├── list.go │ │ │ │ ├── list_test.go │ │ │ │ ├── table.go │ │ │ │ └── table_test.go │ │ │ ├── trace/ │ │ │ │ ├── events.go │ │ │ │ ├── histogram.go │ │ │ │ ├── histogram_test.go │ │ │ │ ├── trace.go │ │ │ │ └── trace_test.go │ │ │ ├── webdav/ │ │ │ │ ├── file.go │ │ │ │ ├── file_test.go │ │ │ │ ├── if.go │ │ │ │ ├── if_test.go │ │ │ │ ├── internal/ │ │ │ │ │ └── xml/ │ │ │ │ │ ├── README │ │ │ │ │ ├── atom_test.go │ │ │ │ │ ├── example_test.go │ │ │ │ │ ├── marshal.go │ │ │ │ │ ├── marshal_test.go │ │ │ │ │ ├── read.go │ │ │ │ │ ├── read_test.go │ │ │ │ │ ├── typeinfo.go │ │ │ │ │ ├── xml.go │ │ │ │ │ └── xml_test.go │ │ │ │ ├── litmus_test_server.go │ │ │ │ ├── lock.go │ │ │ │ ├── lock_test.go │ │ │ │ ├── prop.go │ │ │ │ ├── prop_test.go │ │ │ │ ├── webdav.go │ │ │ │ ├── webdav_test.go │ │ │ │ ├── xml.go │ │ │ │ └── xml_test.go │ │ │ └── websocket/ │ │ │ ├── client.go │ │ │ ├── exampledial_test.go │ │ │ ├── examplehandler_test.go │ │ │ ├── hybi.go │ │ │ ├── hybi_test.go │ │ │ ├── server.go │ │ │ ├── websocket.go │ │ │ └── websocket_test.go │ │ └── sys/ │ │ ├── .gitattributes │ │ ├── .gitignore │ │ ├── AUTHORS │ │ ├── CONTRIBUTING.md │ │ ├── CONTRIBUTORS │ │ ├── LICENSE │ │ ├── PATENTS │ │ ├── README │ │ ├── codereview.cfg │ │ ├── plan9/ │ │ │ ├── asm.s │ │ │ ├── asm_plan9_386.s │ │ │ ├── asm_plan9_amd64.s │ │ │ ├── const_plan9.go │ │ │ ├── dir_plan9.go │ │ │ ├── env_plan9.go │ │ │ ├── env_unset.go │ │ │ ├── errors_plan9.go │ │ │ ├── mkall.sh │ │ │ ├── mkerrors.sh │ │ │ ├── mksyscall.pl │ │ │ ├── mksysnum_plan9.sh │ │ │ ├── pwd_go15_plan9.go │ │ │ ├── pwd_plan9.go │ │ │ ├── race.go │ │ │ ├── race0.go │ │ │ ├── str.go │ │ │ ├── syscall.go │ │ │ ├── syscall_plan9.go │ │ │ ├── syscall_test.go │ │ │ ├── zsyscall_plan9_386.go │ │ │ ├── zsyscall_plan9_amd64.go │ │ │ └── zsysnum_plan9.go │ │ ├── unix/ │ │ │ ├── .gitignore │ │ │ ├── asm.s │ │ │ ├── asm_darwin_386.s │ │ │ ├── asm_darwin_amd64.s │ │ │ ├── asm_darwin_arm.s │ │ │ ├── asm_darwin_arm64.s │ │ │ ├── asm_dragonfly_386.s │ │ │ ├── asm_dragonfly_amd64.s │ │ │ ├── asm_freebsd_386.s │ │ │ ├── asm_freebsd_amd64.s │ │ │ ├── asm_freebsd_arm.s │ │ │ ├── asm_linux_386.s │ │ │ ├── asm_linux_amd64.s │ │ │ ├── asm_linux_arm.s │ │ │ ├── asm_linux_arm64.s │ │ │ ├── asm_linux_ppc64x.s │ │ │ ├── asm_netbsd_386.s │ │ │ ├── asm_netbsd_amd64.s │ │ │ ├── asm_netbsd_arm.s │ │ │ ├── asm_openbsd_386.s │ │ │ ├── asm_openbsd_amd64.s │ │ │ ├── asm_solaris_amd64.s │ │ │ ├── constants.go │ │ │ ├── creds_test.go │ │ │ ├── env_unix.go │ │ │ ├── env_unset.go │ │ │ ├── export_test.go │ │ │ ├── flock.go │ │ │ ├── flock_linux_32bit.go │ │ │ ├── gccgo.go │ │ │ ├── gccgo_c.c │ │ │ ├── gccgo_linux_amd64.go │ │ │ ├── mkall.sh │ │ │ ├── mkerrors.sh │ │ │ ├── mksyscall.pl │ │ │ ├── mksyscall_solaris.pl │ │ │ ├── mksysctl_openbsd.pl │ │ │ ├── mksysnum_darwin.pl │ │ │ ├── mksysnum_dragonfly.pl │ │ │ ├── mksysnum_freebsd.pl │ │ │ ├── mksysnum_linux.pl │ │ │ ├── mksysnum_netbsd.pl │ │ │ ├── mksysnum_openbsd.pl │ │ │ ├── mmap_unix_test.go │ │ │ ├── race.go │ │ │ ├── race0.go │ │ │ ├── sockcmsg_linux.go │ │ │ ├── sockcmsg_unix.go │ │ │ ├── str.go │ │ │ ├── syscall.go │ │ │ ├── syscall_bsd.go │ │ │ ├── syscall_bsd_test.go │ │ │ ├── syscall_darwin.go │ │ │ ├── syscall_darwin_386.go │ │ │ ├── syscall_darwin_amd64.go │ │ │ ├── syscall_darwin_arm.go │ │ │ ├── syscall_darwin_arm64.go │ │ │ ├── syscall_dragonfly.go │ │ │ ├── syscall_dragonfly_386.go │ │ │ ├── syscall_dragonfly_amd64.go │ │ │ ├── syscall_freebsd.go │ │ │ ├── syscall_freebsd_386.go │ │ │ ├── syscall_freebsd_amd64.go │ │ │ ├── syscall_freebsd_arm.go │ │ │ ├── syscall_freebsd_test.go │ │ │ ├── syscall_linux.go │ │ │ ├── syscall_linux_386.go │ │ │ ├── syscall_linux_amd64.go │ │ │ ├── syscall_linux_arm.go │ │ │ ├── syscall_linux_arm64.go │ │ │ ├── syscall_linux_ppc64x.go │ │ │ ├── syscall_netbsd.go │ │ │ ├── syscall_netbsd_386.go │ │ │ ├── syscall_netbsd_amd64.go │ │ │ ├── syscall_netbsd_arm.go │ │ │ ├── syscall_no_getwd.go │ │ │ ├── syscall_openbsd.go │ │ │ ├── syscall_openbsd_386.go │ │ │ ├── syscall_openbsd_amd64.go │ │ │ ├── syscall_solaris.go │ │ │ ├── syscall_solaris_amd64.go │ │ │ ├── syscall_test.go │ │ │ ├── syscall_unix.go │ │ │ ├── syscall_unix_test.go │ │ │ ├── types_darwin.go │ │ │ ├── types_dragonfly.go │ │ │ ├── types_freebsd.go │ │ │ ├── types_linux.go │ │ │ ├── types_netbsd.go │ │ │ ├── types_openbsd.go │ │ │ ├── types_solaris.go │ │ │ ├── zerrors_darwin_386.go │ │ │ ├── zerrors_darwin_amd64.go │ │ │ ├── zerrors_darwin_arm.go │ │ │ ├── zerrors_darwin_arm64.go │ │ │ ├── zerrors_dragonfly_386.go │ │ │ ├── zerrors_dragonfly_amd64.go │ │ │ ├── zerrors_freebsd_386.go │ │ │ ├── zerrors_freebsd_amd64.go │ │ │ ├── zerrors_freebsd_arm.go │ │ │ ├── zerrors_linux_386.go │ │ │ ├── zerrors_linux_amd64.go │ │ │ ├── zerrors_linux_arm.go │ │ │ ├── zerrors_linux_arm64.go │ │ │ ├── zerrors_linux_ppc64.go │ │ │ ├── zerrors_linux_ppc64le.go │ │ │ ├── zerrors_netbsd_386.go │ │ │ ├── zerrors_netbsd_amd64.go │ │ │ ├── zerrors_netbsd_arm.go │ │ │ ├── zerrors_openbsd_386.go │ │ │ ├── zerrors_openbsd_amd64.go │ │ │ ├── zerrors_solaris_amd64.go │ │ │ ├── zsyscall_darwin_386.go │ │ │ ├── zsyscall_darwin_amd64.go │ │ │ ├── zsyscall_darwin_arm.go │ │ │ ├── zsyscall_darwin_arm64.go │ │ │ ├── zsyscall_dragonfly_386.go │ │ │ ├── zsyscall_dragonfly_amd64.go │ │ │ ├── zsyscall_freebsd_386.go │ │ │ ├── zsyscall_freebsd_amd64.go │ │ │ ├── zsyscall_freebsd_arm.go │ │ │ ├── zsyscall_linux_386.go │ │ │ ├── zsyscall_linux_amd64.go │ │ │ ├── zsyscall_linux_arm.go │ │ │ ├── zsyscall_linux_arm64.go │ │ │ ├── zsyscall_linux_ppc64.go │ │ │ ├── zsyscall_linux_ppc64le.go │ │ │ ├── zsyscall_netbsd_386.go │ │ │ ├── zsyscall_netbsd_amd64.go │ │ │ ├── zsyscall_netbsd_arm.go │ │ │ ├── zsyscall_openbsd_386.go │ │ │ ├── zsyscall_openbsd_amd64.go │ │ │ ├── zsyscall_solaris_amd64.go │ │ │ ├── zsysctl_openbsd.go │ │ │ ├── zsysnum_darwin_386.go │ │ │ ├── zsysnum_darwin_amd64.go │ │ │ ├── zsysnum_darwin_arm.go │ │ │ ├── zsysnum_darwin_arm64.go │ │ │ ├── zsysnum_dragonfly_386.go │ │ │ ├── zsysnum_dragonfly_amd64.go │ │ │ ├── zsysnum_freebsd_386.go │ │ │ ├── zsysnum_freebsd_amd64.go │ │ │ ├── zsysnum_freebsd_arm.go │ │ │ ├── zsysnum_linux_386.go │ │ │ ├── zsysnum_linux_amd64.go │ │ │ ├── zsysnum_linux_arm.go │ │ │ ├── zsysnum_linux_arm64.go │ │ │ ├── zsysnum_linux_ppc64.go │ │ │ ├── zsysnum_linux_ppc64le.go │ │ │ ├── zsysnum_netbsd_386.go │ │ │ ├── zsysnum_netbsd_amd64.go │ │ │ ├── zsysnum_netbsd_arm.go │ │ │ ├── zsysnum_openbsd_386.go │ │ │ ├── zsysnum_openbsd_amd64.go │ │ │ ├── zsysnum_solaris_amd64.go │ │ │ ├── ztypes_darwin_386.go │ │ │ ├── ztypes_darwin_amd64.go │ │ │ ├── ztypes_darwin_arm.go │ │ │ ├── ztypes_darwin_arm64.go │ │ │ ├── ztypes_dragonfly_386.go │ │ │ ├── ztypes_dragonfly_amd64.go │ │ │ ├── ztypes_freebsd_386.go │ │ │ ├── ztypes_freebsd_amd64.go │ │ │ ├── ztypes_freebsd_arm.go │ │ │ ├── ztypes_linux_386.go │ │ │ ├── ztypes_linux_amd64.go │ │ │ ├── ztypes_linux_arm.go │ │ │ ├── ztypes_linux_arm64.go │ │ │ ├── ztypes_linux_ppc64.go │ │ │ ├── ztypes_linux_ppc64le.go │ │ │ ├── ztypes_netbsd_386.go │ │ │ ├── ztypes_netbsd_amd64.go │ │ │ ├── ztypes_netbsd_arm.go │ │ │ ├── ztypes_openbsd_386.go │ │ │ ├── ztypes_openbsd_amd64.go │ │ │ └── ztypes_solaris_amd64.go │ │ └── windows/ │ │ ├── asm.s │ │ ├── asm_windows_386.s │ │ ├── asm_windows_amd64.s │ │ ├── dll_windows.go │ │ ├── env_unset.go │ │ ├── env_windows.go │ │ ├── eventlog.go │ │ ├── exec_windows.go │ │ ├── race.go │ │ ├── race0.go │ │ ├── registry/ │ │ │ ├── export_test.go │ │ │ ├── key.go │ │ │ ├── registry_test.go │ │ │ ├── syscall.go │ │ │ ├── value.go │ │ │ └── zsyscall_windows.go │ │ ├── security_windows.go │ │ ├── service.go │ │ ├── str.go │ │ ├── svc/ │ │ │ ├── debug/ │ │ │ │ ├── log.go │ │ │ │ └── service.go │ │ │ ├── event.go │ │ │ ├── eventlog/ │ │ │ │ ├── install.go │ │ │ │ ├── log.go │ │ │ │ └── log_test.go │ │ │ ├── example/ │ │ │ │ ├── beep.go │ │ │ │ ├── install.go │ │ │ │ ├── main.go │ │ │ │ ├── manage.go │ │ │ │ └── service.go │ │ │ ├── go12.c │ │ │ ├── go12.go │ │ │ ├── go13.go │ │ │ ├── mgr/ │ │ │ │ ├── config.go │ │ │ │ ├── mgr.go │ │ │ │ ├── mgr_test.go │ │ │ │ └── service.go │ │ │ ├── security.go │ │ │ ├── service.go │ │ │ ├── svc_test.go │ │ │ ├── sys_386.s │ │ │ └── sys_amd64.s │ │ ├── syscall.go │ │ ├── syscall_test.go │ │ ├── syscall_windows.go │ │ ├── syscall_windows_test.go │ │ ├── zsyscall_windows.go │ │ ├── ztypes_windows.go │ │ ├── ztypes_windows_386.go │ │ └── ztypes_windows_amd64.go │ ├── gopkg.in/ │ │ └── yaml.v2/ │ │ ├── .travis.yml │ │ ├── LICENSE │ │ ├── LICENSE.libyaml │ │ ├── README.md │ │ ├── apic.go │ │ ├── decode.go │ │ ├── decode_test.go │ │ ├── emitterc.go │ │ ├── encode.go │ │ ├── encode_test.go │ │ ├── parserc.go │ │ ├── readerc.go │ │ ├── resolve.go │ │ ├── scannerc.go │ │ ├── sorter.go │ │ ├── suite_test.go │ │ ├── writerc.go │ │ ├── yaml.go │ │ ├── yamlh.go │ │ └── yamlprivateh.go │ └── speter.net/ │ └── go/ │ └── exp/ │ └── math/ │ └── dec/ │ └── inf/ │ ├── LICENSE │ ├── benchmark_test.go │ ├── dec.go │ ├── dec_go1_2_test.go │ ├── dec_internal_test.go │ ├── dec_test.go │ ├── example_test.go │ ├── rounder.go │ ├── rounder_example_test.go │ └── rounder_test.go ├── version/ │ ├── VERSION │ └── info.go └── winrm/ └── winrm.go ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ vendor golib ================================================ FILE: .gitignore ================================================ *.swp bin/ _dist/ .idea golib release ================================================ FILE: BUILDING.md ================================================ ## Building * install [go version 1.5.1 or later](https://golang.org/doc/install) * install [glide](https://github.com/Masterminds/glide#install) * type the following: ``` go get github.com/fabric8io/kansible cd $GOPATH/src/github.com/fabric8io/kansible make bootstrap ``` * then to build the binary make build * you can then run it via ./bin/kansible ### Running pods locally You can run `kansible rc ...` easily on a local build when working on the code. However to try out changes to the pod for `kansible pod ...` you can run that locally outside of docker with a small trick. You must set the `HOSTNAME` environment variable to a valid pod name you wish to use. ```bash export HOSTNAME=fabric8-znuj5 ``` e.g. the above uses the pod name for the current fabric8 console. This lets you pretend to be different pods from the command line when trying it out locally. e.g. run the `kansible pod ...` command in 2 shells as different pods, provided the `HOSTNAME` values are diferent. The pod name must be valid as `kansible pod ...` command will update the pod to annotate which host its chosen etc. So to run the [above examples](#running-kansible) type the following: for [fabric8-ansible-spring-boot](https://github.com/fabric8io/fabric8-ansible-spring-boot): kansible pod -rc hawtapp-demo appservers /opt/cdi-camel-2.2.98-SNAPSHOT-app/bin/run.sh for [fabric8-ansible-hawtapp](https://github.com/fabric8io/fabric8-ansible-hawtapp): kansible pod -rc springboot-demo appservers /opt/springboot-camel-2.2.98-SNAPSHOT ### Working with Windows If you're like me and have used a Mac for years, you might have forgotten how to work with Windows boxes ;). Here's some tips on how to test things out on the Windows VMs First install the [winrm binary](http://github.com/masterzen/winrm/) which you can do if you have golang installed via: go get github.com/masterzen/winrm Then to connect to one of the Windows VMs from an example, such as the [fabric8-ansible-hawtapp](https://github.com/fabric8io/fabric8-ansible-hawtapp) you can use: winrm -hostname 10.10.3.21 -username IEUser -password 'Passw0rd!' 'cmd' Then you can test if a java process is running via jps -l If you wish to kill a java process from its PID you can type: taskkill /PID 4308 /F Enjoy! ## Releasing Just run `make release`. This will cross-compile for all supported platforms, create tag & upload tarballs (zip file for Windows) to Github releases for download. Updating the version is done via `make bump` to bump minor version & `make bump-patch` to bump patch version. This is necessary as tags are created from the version specified when releasing. ================================================ FILE: Dockerfile ================================================ FROM centos:7 WORKDIR /playbook ENV PATH $PATH:/usr/local/kansible/ ADD ./bin/kansible /usr/local/kansible/ CMD kansible pod $KANSIBLE_HOSTS ================================================ FILE: Dockerfile.scratch ================================================ FROM scratch # Call 'make build-all' before building it ADD bin/kansible-docker /kansible # Variables are interpolated not by Docker but by kansible (they are transmitted literally) CMD [ "/kansible", "pod", "$KANSIBLE_HOSTS"] ================================================ FILE: Jenkinsfile ================================================ #!/usr/bin/groovy node{ stage 'canary release' git 'https://github.com/fabric8io/kansible.git' kubernetes.pod('buildpod').withImage('fabric8/go-builder').inside { retry(3){ sh 'make bootstrap' } retry(3){ sh "cd /go/src/workspace/${env.JOB_NAME} && make build test lint" } def imageName = 'kansible' def tag = 'latest' kubernetes.image().withName(imageName).build().fromPath(".") kubernetes.image().withName(imageName).tag().inRepository('docker.io/fabric8/'+imageName).force().withTag(tag) kubernetes.image().withName('docker.io/fabric8/'+imageName).push().withTag(tag).toRegistry() } } ================================================ FILE: LICENSE ================================================ Copyright 2016 Red Hat, 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. ================================================ FILE: Makefile ================================================ ifndef GOPATH $(error No GOPATH set) endif NAME := kansible VERSION := $(shell cat version/VERSION) REVISION=$(shell git rev-parse --short HEAD 2> /dev/null || echo 'unknown') BRANCH=$(shell git rev-parse --abbrev-ref HEAD 2> /dev/null || echo 'unknown') HOST=$(shell hostname -f) BUILD_DATE=$(shell date +%Y%m%d-%H:%M:%S) GO_VERSION=$(shell go version | sed -e 's/^[^0-9.]*\([0-9.]*\).*/\1/') ROOT_PACKAGE := $(shell go list .) BUILDFLAGS := -ldflags \ " -X $(ROOT_PACKAGE)/version.Version='$(VERSION)'\ -X $(ROOT_PACKAGE)/version.Revision='$(REVISION)'\ -X $(ROOT_PACKAGE)/version.Branch='$(BRANCH)'\ -X $(ROOT_PACKAGE)/version.BuildUser='${USER}@$(HOST)'\ -X $(ROOT_PACKAGE)/version.BuildDate='$(BUILD_DATE)'\ -X $(ROOT_PACKAGE)/version.GoVersion='$(GO_VERSION)'" BIN_DIR := bin DIST_DIR := _dist GO := GO15VENDOREXPERIMENT=1 go GO_PACKAGES := $(shell $(GO) list ./... | grep -v /vendor/) SRCS := $(shell find . -path ./vendor -prune -o -name '*.go') MAIN_GO := kansible.go KANSIBLE_BIN := $(BIN_DIR)/kansible LINTERS := --disable-all --enable=vet --enable=golint --enable=errcheck --enable=ineffassign --enable=interfacer --enable=goimports --enable=gofmt build: $(MAIN_GO) $(GO) build -o $(KANSIBLE_BIN) $(BUILDFLAGS) $< bootstrap: $(GO) get -u github.com/golang/lint/golint github.com/mitchellh/gox github.com/alecthomas/gometalinter github.com/fabric8io/gobump gometalinter --install --update update-vendor: GO15VENDOREXPERIMENT=1 glide up --update-vendored build-all: gox -verbose \ $(BUILDFLAGS) \ -os="linux darwin freebsd netbsd openbsd solaris windows" \ -arch="amd64 386" \ -output="$(DIST_DIR)/{{.OS}}-{{.Arch}}/{{.Dir}}" . clean: rm -rf $(DIST_DIR) $(BIN_DIR) release install: build install -d $(DESTDIR)/usr/local/bin/ install -m 755 $(KANSIBLE_BIN) $(DESTDIR)/usr/local/bin/kansible prep-bintray-json: # TRAVIS_TAG is set to the tag name if the build is a tag ifdef TRAVIS_TAG @jq '.version.name |= "$(VERSION)"' _scripts/ci/bintray-template.json | \ jq '.package.repo |= "kansible"' > _scripts/ci/bintray-ci.json else @jq '.version.name |= "$(VERSION)"' _scripts/ci/bintray-template.json \ > _scripts/ci/bintray-ci.json endif quicktest: $(GO) test -short $(GO_PACKAGES) test: $(GO) test -v $(GO_PACKAGES) lint: @echo "Linting does not currently fail the build but is likely to do so in future - fix stuff you see, when you see it please" @export TMP=$(shell mktemp -d) && cp -r vendor $${TMP}/src && GOPATH=$${TMP}:$${GOPATH} GO15VENDOREXPERIMENT=1 gometalinter --vendor --deadline=60s $(LINTERS) ./... || rm -rf $${TMP}} || true docker-scratch: gox -verbose $(BUILDFLAGS) -os="linux" -arch="amd64" \ -output="bin/kansible-docker" . docker build -f Dockerfile.scratch -t "fabric8/kansible:scratch" . release: build-all rm -rf release && mkdir release for os in linux darwin freebsd netbsd openbsd solaris ; do \ for arch in amd64 386 ; do \ if [ -f "$(DIST_DIR)/$$os-$$arch/$(NAME)" ] ; then \ tar --transform "s|^$(DIST_DIR)/$$os-$$arch/||" -czf release/$(NAME)-$(VERSION)-$$os-$$arch.tar.gz $(DIST_DIR)/$$os-$$arch/$(NAME) README.md LICENSE ; \ fi ; \ done ; \ done for arch in amd64 386 ; do \ zip -q --junk-paths release/$(NAME)-$(VERSION)-windows-$$arch.zip $(DIST_DIR)/windows-$$arch/$(NAME).exe README.md LICENSE ; \ done ; \ $(GO) get -u github.com/progrium/gh-release gh-release create fabric8io/$(NAME) $(VERSION) $(BRANCH) $(VERSION) bump: gobump minor -f version/VERSION bump-patch: gobump patch -f version/VERSION .PHONY: release clean .PHONY: bootstrap \ build \ build-all \ clean \ install \ prep-bintray-json \ quicktest \ release \ test \ test-charts \ lint \ bump \ bump-patch \ update-vendor ================================================ FILE: README.md ================================================ # Kansible Kansible lets you orchestrate operating system _processes_ on Windows or any Unix in the same way as you orchestrate your Docker _containers_ with [Kubernetes](http://kubernetes.io/) by using [Ansible](https://www.ansible.com/) to provision the software onto hosts and Kubernetes to orchestrate the processes and the containers in a single system.

kansible logo

Kansible uses: * [Ansible](https://www.ansible.com/) to install, configure and provision your software onto machines using [playbooks](http://docs.ansible.com/ansible/playbooks.html) * [Kubernetes](http://kubernetes.io/) to run and manage the processes and perform service discovery, scaling, load balancing together with centralised logging, metrics, alerts and management. Kansible provides a single pane of glass, CLI and REST API to all your processes whether they are inside docker containers or running as vanilla processes on Windows, AIX, Solaris or HP-UX or an old Linux distros that predate docker. Kansible lets you migrate to a pure container based Docker world at whatever pace suits you, while using Kubernetes to orchestrate all your containers and operating system processes for your entire journey. ## Features * All your processes appear as Pods inside Kubernetes namespaces so you can visualise, query and watch the status of your processes and containers in a canonical way * Each kind of process has its own [Replication Controller](http://kubernetes.io/v1.1/docs/user-guide/replication-controller.html) to ensure processes keep running and so you can [manually or automatically scale](http://kubernetes.io/v1.1/docs/user-guide/replication-controller.html#scaling) the number of processes up or down; up to the limit in the number of hosts in your [Ansible inventory](http://docs.ansible.com/ansible/intro_inventory.html) * Reuse Kubernetes [liveness checks](http://kubernetes.io/v1.1/docs/user-guide/liveness/README.html) so that Kubernetes can monitor the state of your process and restart if it goes bad * Reuse Kubernetes [readiness checks](http://kubernetes.io/v1.1/docs/user-guide/production-pods.html#liveness-and-readiness-probes-aka-health-checks) so that Kubernetes can know when your process can be included into the [internal or external service load balancer](http://kubernetes.io/v1.1/docs/user-guide/services.html) * You can view the logs of all your processes in the canonical kubernetes way via the CLI, REST API or web console * Port forwarding works from the pods to the remote processes so that you can reuse [Kubernetes Services](http://kubernetes.io/v1.1/docs/user-guide/services.html) to load balance across your processes automatically * [Centralised logging](http://fabric8.io/guide/logging.html) and [metrics and alerting](http://fabric8.io/guide/metrics.html) works equally across your containers and processes * You can open a shell into the remote process machine via the CLI, REST API or web console; which is either a unix bash or a windows cmd shell as shown in the fabric8 console screenshot below:

kansible logo

### Ansible perspective on Kansible If you already use Ansible; then one way to think about Kansible is that you continue to use Ansible however you have been doing; using reusable composable playbooks and so forth. The only change to your playbooks that Kansible introduces is that you don't run Unix or Windows services (e.g. like systemd / init.d). You install and configure the software via Ansible playbooks; setting up whatever directories, users and permissions you require. But you don't create services or run the software. Then we use Kubernetes (and kansible pods) as the alternative to Unix and Windows services. The reason we do this is that Kubernetes is a better distributed version of systemd/init.d/Windows services as it also includes features like: * service discovery and load balancing * health monitoring * centralised logging, metrics and alerts * manual and automatic scaling up or down * a consistent web console, CLI and REST API across processes running via kansible and Docker containers ### Kubernetes perspective on Kansible If you already use Kubernetes then you could look at Kansible as a way of extending the reach of Kubernetes to manage both Docker containers on a host that supports Docker plus remote processes on operating systems that don't support Docker. That then makes Kubernetes the orchestrator of all your software; whether its Dockerized or not! All your processes are belong to us! :) Longer term it would be great for Docker to be ported to more operating systems; along with the kubelet. So ideally more operating systems could use native Docker and kubelet; in which case there's less need for kansible. But at the time of writing, that goal is looking some way off for older versions of Windows along with AIX, Solaris and HPUX. Whats really compelling about using Kubernetes to manage Docker containers and operating system processes via Kansible is that you can mix and match on a per microservice basis - use the right tool for the job right now - but all the while use a single orchestrator platform, Kubernetes, a single REST API, CLI tools and web console - with standard service discovery, load balancing and management functions. Using Docker is more optimal; so we hope over time that you can use more Docker and less kansible; but its going to take our industry a while to Dockerize all the things and move everything to Linux; or to have fully working Docker + Kubernetes on Windows + all flavours of Unix. Until then, kansible can help! At least we can now pretend everything's Dockerized and running on Linux from an orchestration and management perspective ;) ## How to use Kansible You use kansible as follows: * create or reuse an existing [Ansible playbook](http://docs.ansible.com/ansible/playbooks.html) to _install and provision_ the software you wish to run on a number of machines defined by the [Ansible inventory](http://docs.ansible.com/ansible/intro_inventory.html) * if you reuse an existing playbook, make sure you disable running the unix / windows services; as you will run that command instead in the kansible pods. * run the [Ansible playbook](http://docs.ansible.com/ansible/playbooks.html) either as part of a [CI / CD build pipeline](http://fabric8.io/guide/cdelivery.html) when there's a change to the git repo of the Playbook, or using a command line tool, cron or [Ansible Tower](https://www.ansible.com/tower) * define a Replication Controller YAML file at `kubernetes/$HOSTS/rc.yml` for running the command for your process [like this example](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/kubernetes/appservers/rc.yml#L15-L16). * the RC YAML file contains the command you need to run remotely to execute your process via [`$KANSIBLE_COMMAND`](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/kubernetes/appservers/rc.yml#L15-L16) * you can think of the RC YAML file as like the systemd configuration file, describing the command to run to startup the application. Only its a single file for the entire cluster which is stored in Kubernetes. Plus it can include [readiness and liveness probes too](http://kubernetes.io/v1.1/docs/user-guide/production-pods.html#liveness-and-readiness-probes-aka-health-checks) . * You can use the `{{ foo_bar }}` Ansible variable expressions in the RC YAML to refer to variables from your [global Ansible variables file](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/group_vars/appservers) * to take advantage of Kubernetes services, you can also define any number of Service YAML files at `kubernetes/$HOSTS/service.yml` * they can be named anything you like so long as they are valid Kubernetes YAML or JSON and are in the same folder as the RC.yml * see the [Kubernetes Services example](#trying-out-kubernetes-services) and its [kubernetes/appservers/service.yml](https://github.com/fabric8io/fabric8-ansible-hawtapp/blob/master/kubernetes/appservers/service.yml) file for how to do this. * whenever the playbook git repo changes, run the **kansible rc** command inside a clone of the playbook git repository: kansible rc myhosts where `myhosts` is the name of the hosts you wish to use in the [Ansible inventory](http://docs.ansible.com/ansible/intro_inventory.html). Then **kansible** will then create/update [Secrets](http://kubernetes.io/v1.1/docs/user-guide/secrets.html) for any SSH private keys in your [Ansible inventory](http://docs.ansible.com/ansible/intro_inventory.html) and create or update a [Replication Controller](http://kubernetes.io/v1.1/docs/user-guide/replication-controller.html) of kansible pods which will start and supervise your processes, capture the logs and redirect ports to enable liveness checks, centralised metrics and Kubernetes services. So for each remote process on Windows, Linux, Solaris, AIX, HPUX kansible will create a kansible pod in Kubernetes which starts the command and tails the log to stdout/stderr. You can then use the [Replication Controller scaling](http://kubernetes.io/v1.1/docs/user-guide/replication-controller.html#scaling) to start/stop your remote processes! ### Working with kansible pods * As processes start and stop, you'll see the processes appear or disappear inside kubernetes, the CLI, REST API or the console as a kansible pod. * You can scale up and down the kansible Replication Controller via CLI, REST API or console. * You can then view the logs of any process in the usual kubernetes way via the command line, REST API or web console. * [Centralised logging](http://fabric8.io/guide/logging.html) then works great on all your processes (providing the command you run outputs logs to `stdout` / `stderr` ### Exposing ports Any ports defined in the Replication Controller YAML file will be automatically forwarded to the remote process. See [this example rc.yml file](https://github.com/fabric8io/fabric8-ansible-hawtapp/blob/master/kubernetes/appservers/rc.yml#L19-L21) to see how to expose ports. This means you can take advantage of things like [centralised metrics and alerting](http://fabric8.io/guide/metrics.html), liveness checks, Kubernetes Services along with the built in service discovery and load balancing inside Kubernetes! To see the use of Kubernetes Services and load balancing across remote processes with kansible check out the [fabric8-ansible-hawtapp demo](#fabric8-ansible-hawtapp). ### Opening a shell on the remote process You can open a shell directly on the remote machine via the web console or by running oc exec -it -p mypodname bash Then you'll get a remote shell on the Windows or Unix box! ## Examples Before you start with the kansible examples you'll need: * [Download a release](https://github.com/fabric8io/kansible/releases) and add `kansible` to your `$PATH` * Or [Build kansible](https://github.com/fabric8io/kansible/blob/master/BUILDING.md) then add the `$PWD/bin` folder to your `$PATH` so that you can type in `kansible` on the command line * Download and install [VirtualBox](https://www.virtualbox.org/wiki/Downloads) * Download and install [Vagrant](http://www.vagrantup.com/downloads.html) These examples assume you have a working [Kubernetes](http://kubernetes.io/) or [OpenShift](https://www.openshift.org/) cluster running. If you don't yet have a Kubernetes cluster to play with, try using the [Fabric8 Vagrant image that includes OpenShift Origin](http://fabric8.io/guide/getStarted/vagrant.html) as the Kubernetes cluster. ### [fabric8-ansible-spring-boot](https://github.com/fabric8io/fabric8-ansible-spring-boot) To run this example type the following to setup the VMs and provision things with Ansible: ```bash git clone https://github.com/fabric8io/fabric8-ansible-spring-boot.git cd fabric8-ansible-spring-boot vagrant up ansible-playbook -i inventory provisioning/site.yml -vv ``` You now should have 2 sample VMs (app1 and app2) with a Spring Boot based Java application provisioned onto the machines in the `/opt` folder, but with nothing actually running yet. Now to setup the kansible Replication Controller run the following, where `appservers` is the hosts from the [Ansible inventory](http://docs.ansible.com/ansible/intro_inventory.html) in [the inventory file](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/inventory#L1-L3) ```bash kansible rc appservers ``` This should now create a Replication Controller called `springboot-demo` along with 2 pods for each host in the `appservers` inventory file. You should be able to look at the logs of those 2 pods in the usual Kubernetes / OpenShift way; e.g. via the fabric8 or OpenShift console or via the CLI: e.g. ```bash oc get pods oc logs -f springboot-demo-81ryw ``` where `springboot-demo-81ryw` is the name of the pod you wish to view the logs. You can now scale down / up the number of pods using the web console or the command line: ```bash oc scale rc --replicas=2 springboot-demo ``` #### Important files The examples use the following files: * [inventory](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/inventory) is the Ansible inventory file to define the [hosts](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/inventory#L1-L3) to run the processes * [kubernetes/$HOSTS/rc.yml](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/kubernetes/appservers/rc.yml) is the Replication Controller configuration used to [define the command `$KANSIBLE_COMMAND`](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/kubernetes/appservers/rc.yml#L15-L16) which kansible uses to run the process remotely ### [fabric8-ansible-hawtapp](https://github.com/fabric8io/fabric8-ansible-hawtapp) This demonstration is similar to the above but it also demonstrates: * using both Windows and Linux boxes as the hosts * using Kubernetes Services to load balance across the processes To run this example type the following to setup the VMs and provision things with Ansible: ```bash git clone https://github.com/fabric8io/fabric8-ansible-hawtapp.git cd fabric8-ansible-hawtapp vagrant up ansible-playbook -i inventory provisioning/site.yml -vv ``` Now to setup the Replication Controller for the supervisors run the following, where `appservers` is the hosts from the inventory ``` kansible rc appservers ``` The pods should now start up for each host in the inventory. ### Using windows machines This example uses 1 windows box and 1 linux box in the inventory. The example shows that kansible can support both operating systems just fine; it does require the playbooks to handle the differences though. Also you typically will need to use different commands to run on Unix versus Windows which is configured in the [rc.yml file](https://github.com/fabric8io/fabric8-ansible-hawtapp/blob/master/kubernetes/appservers/rc.yml#L15-L18). For more details see the [documentation on the KANSIBLE_COMMAND_WINRM environment variable](#kansible_command_winrm) To use windows you may need to first make sure you've installed **pywinrm**: sudo pip install pywinrm If you try to open shells via the fabric8 console or `oc exec -it -p podName bash` for both pods running, you'll see that one runs on a Linux box and one runs on a Windows machine like this [example screenshot](https://raw.githubusercontent.com/fabric8io/kansible/master/docs/images/kansible-demo.png)! #### Trying out Kubernetes Services This example also creates a [Kubernetes Service](http://kubernetes.io/v1.1/docs/user-guide/services.html) which loads balances across the remote processes thanks to the [kubernetes/appservers/service.yml](https://github.com/fabric8io/fabric8-ansible-hawtapp/blob/master/kubernetes/appservers/service.yml) file which is then exposed via the [LoadBalancer type](https://github.com/fabric8io/fabric8-ansible-hawtapp/blob/master/kubernetes/appservers/service.yml#L16) (on OpenShift a Route is created for this). If you are using the fabric8 console you'll see the `hawtapp-demo` service in the Services tab. You can try out the service in your browser via: [http://hawtapp-demo-default.vagrant.f8/camel/hello?name=Kansible](http://hawtapp-demo-default.vagrant.f8/camel/hello?name=Kansible) Or using the CLI: curl http://hawtapp-demo-default.vagrant.f8/camel/hello?name=Kansible Each request load balances over the available processes. You can scale the Replication Controller down to 1 pod or up to 2 and each request should still work. ## Configuration To configure kansible you need to configure a [Replication Controller](http://kubernetes.io/v1.1/docs/user-guide/replication-controller.html) in a file called [kubernetes/$HOSTS/rc.yml](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/kubernetes/appservers/rc.yml). Specify a name and optionally some labels for the replication controller inside the `metadata` object. There's no need to specify the `spec.selector` or `spec.template.containers[0].metadata.labels` values as those are inherited by default from the `metadata.labels`. ### Environment variables You can specify the following environment variables in the `spec.template.spec.containers[0].env` array like the use of `KANSIBLE_COMMAND` below. These values can use Ansible variable expressions too. #### KANSIBLE_COMMAND Then you must specify a command to run via the [`$KANSIBLE_COMMAND`](https://github.com/fabric8io/fabric8-ansible-spring-boot/blob/master/kubernetes/appservers/rc.yml#L15-L16) environment variable: ```yaml apiVersion: "v1" kind: "ReplicationController" metadata: name: "myapp" labels: project: "myapp" version: "{{ app_version }}" spec: template: spec: containers: - env: - name: "KANSIBLE_COMMAND" value: "/opt/foo-{{ app_version }}/bin/run.sh" serviceAccountName: "fabric8" ``` #### KANSIBLE_COMMAND_WINRM This environment variable lets you provide a Windows specific command. It works the same as the `KANSIBLE_COMMAND` environment variable above, but this value is only used for Ansible connections of the form `winrm`. i.e. to supply a windows only command to execute. Its quite common to have a `foo.sh` script to run sh/bash scripts on unix and then a `foo.bat` or `foo.cmd` file for Windows. #### KANSIBLE_EXPORT_ENV_VARS Specify a space separated list of environment variable names which should be exported into the remote shell when running the remote command. Note that typically your [sshd_config](http://linux.die.net/man/5/sshd_config) will disable the use of most environment variables being exported that don't start with `LC_*` so you may need to [configure your sshd](http://linux.die.net/man/5/sshd_config) in `/etc/ssh/sshd_config` to enable this. #### KANSIBLE_BASH This defines the path where the bash script will be generated for running a remote bash shell. This allows running the command `bash` inside the kansible pod to remotely execute either `/bin/bash` or `cmd.exe` for Windows machines on the remote machine when you try to open a shell inside the Web Console or via: oc exec -p mypodname bash #### KANSIBLE_PORT_FORWARD Allows port forwarding to be disabled. export KANSIBLE_PORT_FORWARD=false This is mostly useful to allow the `bash` command within a pod to not also try to port forward as this will fail ;) ### SSH or WinRM The best way to configure if you want to connect via SSH for unix machines or WinRM for windows machines is via the Ansible Inventory. By default SSH is used on port 22 unless you specify `ansible_port` in the inventory or specify `--port` on the command line. You can configure Windows machines using the `ansible_connection=winrm` property in the inventory: ```ini [winboxes] windows1 ansible_host=localhost ansible_port=5985 ansible_user=foo ansible_pass=somepasswd! ansible_connection=winrm [unixes] app1 ansible_host=10.10.3.20 ansible_user=vagrant ansible_ssh_private_key_file=.vagrant/machines/app1/virtualbox/private_key app2 ansible_host=10.10.3.21 ansible_user=vagrant ansible_ssh_private_key_file=.vagrant/machines/app2/virtualbox/private_key ``` You can also enable WinRM via the `--winrm` command line flag: ```bash export KANSIBLE_WINRM=true kansible pod --winrm somehosts somecommand ``` or by setting the environment variable `KANSIBLE_WINRM` which is a little easier to configure on the RC YAML: ```bash export KANSIBLE_WINRM=true kansible pod somehosts somecommand ``` ### Checking the runtime status of the supervisors To see which pods own which hosts run the following command: oc export rc hawtapp-demo | grep ansible.fabric8 | sort Where `hawtapp-demo` is the name of the RC for the supervisors. The output is of the format: pod.kansible.fabric8.io/app1: supervisor-znuj5 pod.kansible.fabric8.io/app2: supervisor-1same Where the output is of the form ` pod.ansible.fabric8.io/$HOSTNAME: $PODNAME` ================================================ FILE: add-headers.sh ================================================ #!/bin/bash function join { local IFS="$1"; shift; echo "$*"; } copyright-header \ --copyright-software Kansible \ --copyright-holder 'Red Hat' \ --copyright-year 2016 \ --copyright-software-description 'Directly orchestrate operating system processes via Kubernetes' \ -o ./ \ --license-file header.txt \ -c headers.yml \ --add-path $(join : `find . -path ./vendor -prune -o -name '*.go' -print`) ================================================ FILE: ansible/ansible.go ================================================ /* * Copyright 2016 Red Hat * * 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 ansible import ( "bufio" "bytes" "fmt" "io" "io/ioutil" "math/rand" "net" "os" "os/exec" "path/filepath" "sort" "strconv" "strings" "time" "github.com/ghodss/yaml" "k8s.io/kubernetes/pkg/api" client "k8s.io/kubernetes/pkg/client/unversioned" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/fabric8io/kansible/k8s" "github.com/fabric8io/kansible/log" ) const ( // AnsibleHostPodAnnotationPrefix is the annotation prefix used on the RC to associate a host name with a pod name AnsibleHostPodAnnotationPrefix = "pod.kansible.fabric8.io/" // HostInventoryAnnotation is the list of hosts from the inventory HostInventoryAnnotation = "kansible.fabric8.io/host-inventory" // HostNameAnnotation is used to annotate a pod with the host name its processing HostNameAnnotation = "kansible.fabric8.io/host-name" // HostAddressAnnotation is used to annotate a pod with the host address its processing HostAddressAnnotation = "kansible.fabric8.io/host-address" // IconAnnotation is the annotation used to denote the icon on an RC or Service IconAnnotation = "fabric8.io/iconUrl" // IconURL is the kansible icon URL IconURL = "https://cdn.rawgit.com/fabric8io/kansible/master/docs/images/logo.png" // WinRMShellAnnotationPrefix stores the shell ID for the WinRM host name on the RC WinRMShellAnnotationPrefix = "winrm.shellid.kansible.fabric8.io/" // EnvHosts is the environment variable on a pod for specifying the Ansible hosts in the inventory EnvHosts = "KANSIBLE_HOSTS" // EnvCommand is the environment variable on a pod for specifying the command to run on each host EnvCommand = "KANSIBLE_COMMAND" // EnvRC is the environment variable on a pod for the name of the ReplicationController EnvRC = "KANSIBLE_RC" // EnvNamespace is the environment variable on a pod for the namespace to use EnvNamespace = "KANSIBLE_NAMESPACE" // EnvExportEnvVars is the space separated list of environment variables exported to the remote process EnvExportEnvVars = "KANSIBLE_EXPORT_ENV_VARS" // EnvPortForward allows port forwarding to be disabled EnvPortForward = "KANSIBLE_PORT_FORWARD" // EnvBash is the environment variable on a pod for the name of the bash script to generate on startup for // opening a remote shell EnvBash = "KANSIBLE_BASH" // EnvIsBashShell is used to indicate of the command running remotely on the machine is a bash shell in which case we // don't want to delete any previous WinRM shell EnvIsBashShell = "KANSIBLE_IS_BASH_SHELL" // PlaybookVolumeMount is the volume mount point where the playbook is assumed to be in the supervisor pod PlaybookVolumeMount = "/playbook" // AnsibleVariableHost is the Ansible inventory host variable for the remote host AnsibleVariableHost = "ansible_host" // AnsibleVariableUser is the Ansible inventory host variable for the remote user AnsibleVariableUser = "ansible_user" // AnsibleVariablePort is the Ansible inventory host variable for the reote port AnsibleVariablePort = "ansible_port" // AnsibleVariablePrivateKey is the Ansible inventory host variable for the SSH private key file AnsibleVariablePrivateKey = "ansible_ssh_private_key_file" // AnsibleVariableConnection is the Ansible inventory host variable for the kind of connection; e.g. 'winrm' for windows AnsibleVariableConnection = "ansible_connection" // AnsibleVariablePassword is the Ansible inventory host variable for the password AnsibleVariablePassword = "ansible_ssh_pass" // ConnectionWinRM is the value AnsibleVariableConnection of for using Windows with WinRM ConnectionWinRM = "winrm" // AppRunCommand is the Ansible inventory host variable for the run command that is executed on the remote host AppRunCommand = "app_run_command" gitURLPrefix = "url = " gitConfig = ".git/config" ) // HostEntry represents a single host entry in an Ansible inventory type HostEntry struct { Name string Host string Port string User string PrivateKey string Connection string Password string RunCommand string } // LoadHostEntries loads the Ansible inventory for a given hosts string value func LoadHostEntries(inventoryFile string, hosts string) ([]*HostEntry, error) { file, err := os.Open(inventoryFile) if err != nil { return nil, err } defer file.Close() hostEntries := []*HostEntry{} hostsLine := "[" + hosts + "]" foundHeader := false completed := false hostNames := []string{} scanner := bufio.NewScanner(file) for scanner.Scan() { text := strings.TrimSpace(scanner.Text()) if len(text) > 0 && !strings.HasPrefix(text, "#") { isHost := strings.HasPrefix(text, "[") && strings.HasSuffix(text, "]") if isHost { hostNames = append(hostNames, text[1:len(text)-1]) } if foundHeader { if isHost { completed = true } else if !completed { hostEntry := parseHostEntry(text) if hostEntry != nil { hostEntries = append(hostEntries, hostEntry) } } } else if text == hostsLine { foundHeader = true } } } if err := scanner.Err(); err != nil { return nil, err } if !foundHeader { sort.Strings(hostNames) return nil, fmt.Errorf("Could not find hosts `%s` in Ansible inventory file %s. Possible values are: %s", hosts, inventoryFile, strings.Join(hostNames, ", ")) } return hostEntries, nil } // LoadHostEntriesFromText loads the host entries from the given text which is typically taken from // an annotation on the ReplicationController func LoadHostEntriesFromText(text string) ([]*HostEntry, error) { hostEntries := []*HostEntry{} lines := strings.Split(text, "\n") for _, line := range lines { text := strings.TrimSpace(line) if len(text) > 0 && !strings.HasPrefix(text, "#") { hostEntry := parseHostEntry(text) if hostEntry != nil { hostEntries = append(hostEntries, hostEntry) } } } return hostEntries, nil } // ChooseHostAndPrivateKey parses the given Ansible inventory file for the hosts // and chooses a single host inside it, returning the host name and the private key func ChooseHostAndPrivateKey(thisPodName string, hosts string, c *client.Client, ns string, rcName string) (*HostEntry, *api.ReplicationController, map[string]string, error) { retryAttempts := 20 for i := 0; i < retryAttempts; i++ { if i > 0 { // lets sleep before retrying time.Sleep(time.Duration(random(1000, 20000)) * time.Millisecond) } if c == nil { return nil, nil, nil, fmt.Errorf("No Kubernetes Client specified!") } rc, err := c.ReplicationControllers(ns).Get(rcName) if err != nil { return nil, nil, nil, err } if rc == nil { return nil, nil, nil, fmt.Errorf("No ReplicationController found for name %s", rcName) } pods, err := c.Pods(ns).List(api.ListOptions{}) if err != nil { return nil, nil, nil, err } metadata := &rc.ObjectMeta resourceVersion := metadata.ResourceVersion if metadata.Annotations == nil { metadata.Annotations = make(map[string]string) } annotations := metadata.Annotations log.Info("Using ReplicationController with namespace %s name %s and version %s", ns, rcName, resourceVersion) hostsText := annotations[HostInventoryAnnotation] if len(hostsText) == 0 { return nil, nil, nil, fmt.Errorf("Could not find annotation %s on ReplicationController %s", HostInventoryAnnotation, rcName) } hostEntries, err := LoadHostEntriesFromText(hostsText) if err != nil { return nil, nil, nil, err } log.Info("Found %d host entries", len(hostEntries)) // lets pick a random entry if len(hostEntries) > 0 { filteredHostEntries := hostEntries for annKey, podName := range annotations { if strings.HasPrefix(annKey, AnsibleHostPodAnnotationPrefix) { hostName := annKey[len(AnsibleHostPodAnnotationPrefix):] if k8s.PodIsRunning(pods, podName) { if podName != thisPodName { log.Info("Pod %s podName has already claimed host %s", podName, hostName) filteredHostEntries = removeHostEntry(filteredHostEntries, hostName) } } else { // lets remove this annotation as the pod is no longer valid log.Info("Pod %s is no longer running so removing the annotation %s", podName, annKey) delete(metadata.Annotations, annKey) } } } count := len(filteredHostEntries) if count == 0 { log.Info("There are no more hosts available to be supervised by this pod!") return nil, nil, nil, fmt.Errorf("No more hosts available to be supervised!") } log.Info("After filtering out hosts owned by other pods we have %v host entries left", count) pickedEntry := filteredHostEntries[random(0, count)] hostName := pickedEntry.Name if len(pickedEntry.Host) == 0 { return nil, nil, nil, fmt.Errorf("Could not find host name for entry %s", pickedEntry.Name) } if len(pickedEntry.User) == 0 { return nil, nil, nil, fmt.Errorf("Could not find User for entry %s", pickedEntry.Name) } // lets try pick this pod annotations[AnsibleHostPodAnnotationPrefix+hostName] = thisPodName rc, err = c.ReplicationControllers(ns).Update(rc) if err != nil { log.Info("Failed to update the RC, could be concurrent update failure: %s", err) } else { log.Info("Picked host " + pickedEntry.Host) // lets update the Pod with the host name label podClient := c.Pods(ns) pod, err := podClient.Get(thisPodName) if err != nil { return pickedEntry, nil, nil, err } metadata := &pod.ObjectMeta if metadata.Annotations == nil { metadata.Annotations = make(map[string]string) } metadata.Annotations[HostNameAnnotation] = pickedEntry.Name metadata.Annotations[HostAddressAnnotation] = pickedEntry.Host //pod.Status = api.PodStatus{} pod, err = podClient.UpdateStatus(pod) if err != nil { return pickedEntry, nil, nil, err } // lets export required environment variables exportEnvVars := os.Getenv(EnvExportEnvVars) envVars := make(map[string]string) if len(exportEnvVars) > 0 { names := strings.Split(exportEnvVars, " ") for _, name := range names { name = strings.TrimSpace(name) if len(name) > 0 { value := os.Getenv(name) if len(value) > 0 { envVars[name] = value log.Debug("Exporting environment variable %s = %s", name, value) } } } } err = forwardPorts(pod, pickedEntry) return pickedEntry, rc, envVars, err } } } return nil, nil, nil, fmt.Errorf("Could not find any available hosts on the ReplicationController %s and hosts %s", rcName, hosts) } // forwardPorts forwards any ports that are defined in the PodSpec to the host func forwardPorts(pod *api.Pod, hostEntry *HostEntry) error { disableForwarding := os.Getenv(EnvPortForward) if len(disableForwarding) > 0 { if strings.ToLower(disableForwarding) == "false" { return nil } } podSpec := pod.Spec host := hostEntry.Host for _, container := range podSpec.Containers { for _, port := range container.Ports { name := port.Name portNum := port.ContainerPort if portNum > 0 { address := "0.0.0.0:" + strconv.Itoa(portNum) forwardAddress := host + ":" + strconv.Itoa(portNum) err := forwardPortLoop(name, address, forwardAddress) if err != nil { return err } } } } return nil } func forwardPortLoop(name string, address string, forwardAddress string) error { log.Info("forwarding port %s %s => %s", name, address, forwardAddress) listener, err := net.Listen("tcp", address) if err != nil { return err } log.Info("About to start the acceptor goroutine!") go func() { for { conn, err := listener.Accept() if err != nil { log.Err("Failed to accept listener: %v", err) } log.Info("Accepted connection %v\n", conn) go forwardPort(conn, forwardAddress) } }() return nil } func forwardPort(conn net.Conn, address string) { client, err := net.Dial("tcp", address) if err != nil { log.Err("Dial failed: %v", err) } log.Info("Connected to localhost %v\n", conn) go func() { defer client.Close() defer conn.Close() io.Copy(client, conn) }() go func() { defer client.Close() defer conn.Close() io.Copy(conn, client) }() } // UpdateKansibleRC reads the Ansible inventory and the RC YAML for the hosts and updates it in Kubernetes // along with removing any remaining pods which are running against old hosts that have been removed from the inventory func UpdateKansibleRC(hostEntries []*HostEntry, hosts string, f *cmdutil.Factory, c *client.Client, ns string, rcFile string, replicas int) (*api.ReplicationController, error) { variables, err := LoadAnsibleVariables(hosts) if err != nil { return nil, err } data, err := LoadFileAndReplaceVariables(rcFile, variables) if err != nil { return nil, err } rcConfig, err := k8s.ReadReplicationController(data) if err != nil { return nil, err } rcName := rcConfig.ObjectMeta.Name podSpec := k8s.GetOrCreatePodSpec(rcConfig) // lets default labels and selectors if they are missing rcLabels := rcConfig.ObjectMeta.Labels if len(rcLabels) > 0 { rcSpec := rcConfig.Spec if len(rcSpec.Selector) == 0 { rcSpec.Selector = rcLabels } template := rcSpec.Template if template != nil { if len(template.ObjectMeta.Labels) == 0 { template.ObjectMeta.Labels = rcLabels } } } container := k8s.GetFirstContainerOrCreate(rcConfig) if len(container.Image) == 0 { container.Image = "fabric8/kansible" } if len(container.Name) == 0 { container.Name = "kansible" } if len(container.ImagePullPolicy) == 0 { container.ImagePullPolicy = "IfNotPresent" } preStopCommands := []string{"kansible", "kill"} if len(podSpec.ServiceAccountName) == 0 { podSpec.ServiceAccountName = rcName } serviceAccountName := podSpec.ServiceAccountName k8s.EnsureContainerHasPreStopCommand(container, preStopCommands) k8s.EnsureContainerHasEnvVar(container, EnvHosts, hosts) k8s.EnsureContainerHasEnvVar(container, EnvRC, rcName) k8s.EnsureContainerHasEnvVar(container, EnvBash, "/usr/local/bin/bash") k8s.EnsureContainerHasEnvVarFromField(container, EnvNamespace, "metadata.namespace") command := k8s.GetContainerEnvVar(container, EnvCommand) if len(command) == 0 { return nil, fmt.Errorf("No environemnt variable value defined for %s in ReplicationController YAML file %s", EnvCommand, rcFile) } if len(serviceAccountName) > 0 { created, err := k8s.EnsureServiceAccountExists(c, ns, serviceAccountName) if err != nil { return nil, err } if created { err = ensureSCCExists(ns, serviceAccountName) if err != nil { return nil, err } } } isUpdate := true rc, err := c.ReplicationControllers(ns).Get(rcName) if err != nil { isUpdate = false rc = &api.ReplicationController{ ObjectMeta: api.ObjectMeta{ Namespace: ns, Name: rcName, }, } } pods, err := c.Pods(ns).List(api.ListOptions{}) if err != nil { return nil, err } // merge the RC configuration to allow configuration originalReplicas := rc.Spec.Replicas rc.Spec = rcConfig.Spec metadata := &rc.ObjectMeta resourceVersion := metadata.ResourceVersion rcSpec := &rc.Spec if replicas < 0 { replicas = originalReplicas } rcSpec.Replicas = replicas err = generatePrivateKeySecrets(c, ns, hostEntries, rc, podSpec, container) if err != nil { return rc, err } text := HostEntriesToString(hostEntries) if metadata.Annotations == nil { metadata.Annotations = make(map[string]string) } metadata.Annotations[HostInventoryAnnotation] = text metadata.Annotations[IconAnnotation] = IconURL log.Info("found RC with name %s and version %s and replicas %d", rcName, resourceVersion, rcSpec.Replicas) deletePodsForOldHosts(c, ns, metadata.Annotations, pods, hostEntries) replicationController := c.ReplicationControllers(ns) if isUpdate { _, err = replicationController.Update(rc) } else { _, err = replicationController.Create(rc) } if err != nil { log.Info("Failed to update the RC, could be concurrent update failure: %s", err) return nil, err } err = applyOtherKubernetesResources(f, c, ns, rcFile, variables) return rc, err } func applyOtherKubernetesResources(f *cmdutil.Factory, c *client.Client, ns string, rcFile string, variables map[string]string) error { dir := filepath.Dir(rcFile) if len(dir) == 0 { dir = "." } files, err := ioutil.ReadDir(dir) if err != nil { return err } for _, file := range files { name := file.Name() lower := strings.ToLower(name) ext := filepath.Ext(lower) if !file.IsDir() && lower != "rc.yml" { resource := false switch ext { case ".json": resource = true case ".js": resource = true case ".yml": resource = true case ".yaml": resource = true } if resource { fullpath := filepath.Join(dir, name) err = applyOtherKubernetesResource(f, c, ns, fullpath, variables) if err != nil { return err } } } } return nil } func applyOtherKubernetesResource(f *cmdutil.Factory, c *client.Client, ns string, file string, variables map[string]string) error { log.Info("applying kubernetes resource: %s", file) data, err := LoadFileAndReplaceVariables(file, variables) if err != nil { return err } // TODO the following should work ideally but something's wrong with the loading of versioned schemas... //return k8s.ApplyResource(f, c, ns, data, file) // lets use the `oc` binary instead isOc := true binary, err := exec.LookPath("oc") if err != nil { isOc = false var err2 error binary, err2 = exec.LookPath("kubectl") if err2 != nil { return err } } reader := bytes.NewReader(data) err = runCommand(binary, []string{"apply", "-f", "-"}, reader) if err != nil { return err } if isOc { // if we are a service lets try figure out the service name? service := api.Service{} if err := yaml.Unmarshal(data, &service); err != nil { log.Info("Probably not a service! %s", err) return nil } name := service.ObjectMeta.Name serviceType := service.Spec.Type if service.Kind == "Service" && len(name) > 0 && serviceType == "LoadBalancer" { log.Info("Checking the service %s is exposed in OpenShift", name) runCommand(binary, []string{"expose", "service", name}, os.Stdin) return nil } } return nil } func ensureSCCExists(ns string, serviceAccountName string) error { binary, err := exec.LookPath("oc") if err != nil { // no openshift so ignore return nil } text, err := getCommandOutputString(binary, []string{"export", "scc", serviceAccountName}, os.Stdin) if err != nil { log.Debug("Failed to get SecurityContextConstraints %s. %s", serviceAccountName, err) } if err != nil || len(text) == 0 { text = ` apiVersion: v1 kind: SecurityContextConstraints groups: - system:cluster-admins - system:nodes metadata: creationTimestamp: null name: ` + serviceAccountName + ` runAsUser: type: RunAsAny seLinuxContext: type: RunAsAny supplementalGroups: type: RunAsAny users: ` } // lets ensure there's a users section if !strings.Contains(text, "\nusers:") { text = text + "\nusers:\n" } line := "system:serviceaccount:" + ns + ":" + serviceAccountName if strings.Contains(text, line) { log.Info("No need to modify SecurityContextConstraints as it already contains line for namespace %s and service account %s", ns, serviceAccountName) return nil } text = text + "\n- " + line + "\n" log.Debug("created SecurityContextConstraints YAML: %s", text) log.Info("Applying changes for SecurityContextConstraints %s for namespace %s and ServiceAccount %s", serviceAccountName, ns, serviceAccountName) reader := bytes.NewReader([]byte(text)) err = runCommand(binary, []string{"apply", "-f", "-"}, reader) if err != nil { log.Err("Failed to update OpenShift SecurityContextConstraints named %s. %s", serviceAccountName, err) } return err } func getCommandOutputString(binary string, args []string, reader io.Reader) (string, error) { cmd := exec.Command(binary, args...) cmd.Stdin = reader var out bytes.Buffer cmd.Stdout = &out stderr, err := cmd.StderrPipe() if err != nil { return "", fmt.Errorf("Unable to setup stderr for command %s: %v", binary, err) } go io.Copy(os.Stderr, stderr) err = cmd.Start() if err != nil { return "", err } err = cmd.Wait() if err != nil { return "", err } return out.String(), err } func runCommand(binary string, args []string, reader io.Reader) error { cmd := exec.Command(binary, args...) cmd.Stdin = reader stdout, err := cmd.StdoutPipe() if err != nil { return fmt.Errorf("Unable to setup stdout for command %s: %v", binary, err) } go io.Copy(os.Stdout, stdout) stderr, err := cmd.StderrPipe() if err != nil { return fmt.Errorf("Unable to setup stderr for command %s: %v", binary, err) } go io.Copy(os.Stderr, stderr) err = cmd.Start() if err != nil { return err } err = cmd.Wait() if err != nil { return err } return err } func generatePrivateKeySecrets(c *client.Client, ns string, hostEntries []*HostEntry, rc *api.ReplicationController, podSpec *api.PodSpec, container *api.Container) error { secrets := map[string]string{} rcName := rc.ObjectMeta.Name for _, hostEntry := range hostEntries { privateKey := hostEntry.PrivateKey if len(privateKey) != 0 { volumeMount := secrets[privateKey] if len(volumeMount) == 0 { buffer, err := ioutil.ReadFile(privateKey) if err != nil { return err } hostName := hostEntry.Name secretName := rcName + "-" + hostName keyName := "sshkey" secret := &api.Secret{ ObjectMeta: api.ObjectMeta{ Name: secretName, Labels: rc.ObjectMeta.Labels, }, Data: map[string][]byte{ keyName: buffer, }, } // lets create or update the secret secretClient := c.Secrets(ns) current, err := secretClient.Get(secretName) if err != nil || current == nil { _, err = secretClient.Create(secret) } else { _, err = secretClient.Update(secret) } if err != nil { return err } volumeMount = "/secrets/" + hostName secrets[privateKey] = volumeMount hostEntry.PrivateKey = volumeMount + "/" + keyName // lets add the volume mapping to the container secretVolumeName := "secret-" + hostName k8s.EnsurePodSpecHasSecretVolume(podSpec, secretVolumeName, secretName) k8s.EnsureContainerHasVolumeMount(container, secretVolumeName, volumeMount) } } } return nil } func findGitURL() (string, error) { file, err := os.Open(gitConfig) if err != nil { return "", err } defer file.Close() scanner := bufio.NewScanner(file) for scanner.Scan() { text := strings.TrimSpace(scanner.Text()) if strings.HasPrefix(text, gitURLPrefix) { return text[len(gitURLPrefix):], nil } } if err := scanner.Err(); err != nil { return "", err } return "", nil } func removeHostEntry(hostEntries []*HostEntry, name string) []*HostEntry { for i, entry := range hostEntries { if entry.Name == name { if i < len(hostEntries)-1 { return append(hostEntries[:i], hostEntries[i+1:]...) } return hostEntries[:i] } } log.Warn("Did not find a host entry with name %s", name) return hostEntries } // GetHostEntryByName finds the HostEntry for the given host name or returns nil func GetHostEntryByName(hostEntries []*HostEntry, name string) *HostEntry { for _, entry := range hostEntries { if entry.Name == name { return entry } } return nil } func deletePodsForOldHosts(c *client.Client, ns string, annotations map[string]string, pods *api.PodList, hostEntries []*HostEntry) { for annKey, podName := range annotations { if strings.HasPrefix(annKey, AnsibleHostPodAnnotationPrefix) { hostName := annKey[len(AnsibleHostPodAnnotationPrefix):] if k8s.PodIsRunning(pods, podName) { hostEntry := GetHostEntryByName(hostEntries, hostName) if hostEntry == nil { log.Info("Deleting pod %s as there is no longer an Ansible inventory host called %s", podName, hostName) c.Pods(ns).Delete(podName, nil) } } } } } func random(min, max int) int { rand.Seed(time.Now().Unix()) return rand.Intn(max-min) + min } // HostEntriesToString generates the Ansible inventory text for the host entries func HostEntriesToString(hostEntries []*HostEntry) string { var buffer bytes.Buffer for _, hostEntry := range hostEntries { hostEntry.write(&buffer) buffer.WriteString("\n") } return buffer.String() } func (hostEntry HostEntry) write(buffer *bytes.Buffer) { buffer.WriteString(hostEntry.Name) host := hostEntry.Host if len(host) > 0 { buffer.WriteString(" ") buffer.WriteString(AnsibleVariableHost) buffer.WriteString("=") buffer.WriteString(host) } pk := hostEntry.PrivateKey if len(pk) > 0 { buffer.WriteString(" ") buffer.WriteString(AnsibleVariablePrivateKey) buffer.WriteString("=") buffer.WriteString(pk) } password := hostEntry.Password if len(password) > 0 { buffer.WriteString(" ") buffer.WriteString(AnsibleVariablePassword) buffer.WriteString("=") buffer.WriteString(password) } runCommand := hostEntry.RunCommand if len(runCommand) > 0 { buffer.WriteString(" ") buffer.WriteString(AppRunCommand) buffer.WriteString("=") buffer.WriteString(runCommand) } port := hostEntry.Port if len(port) > 0 { buffer.WriteString(" ") buffer.WriteString(AnsibleVariablePort) buffer.WriteString("=") buffer.WriteString(port) } user := hostEntry.User if len(user) > 0 { buffer.WriteString(" ") buffer.WriteString(AnsibleVariableUser) buffer.WriteString("=") buffer.WriteString(user) } connection := hostEntry.Connection if len(connection) > 0 { buffer.WriteString(" ") buffer.WriteString(AnsibleVariableConnection) buffer.WriteString("=") buffer.WriteString(connection) } } func parseHostEntry(text string) *HostEntry { values := strings.Split(text, " ") name := "" user := "" host := "" port := "" privateKey := "" connection := "" password := "" runCommand := "" count := len(values) if count > 0 { name = values[0] // lets parse the key value expressions for the host name for _, exp := range values[1:] { params := strings.Split(exp, "=") if len(params) == 2 { paramValue := params[1] switch params[0] { case AnsibleVariableHost: host = paramValue case AnsibleVariableUser: user = paramValue case AnsibleVariablePort: port = paramValue case AnsibleVariablePrivateKey: privateKey = paramValue case AnsibleVariableConnection: connection = paramValue case AnsibleVariablePassword: password = paramValue case AppRunCommand: runCommand = paramValue } } } // if there's no host defined yet, lets assume that the name is the host name if len(host) == 0 { host = name } } return &HostEntry{ Name: name, Host: host, Port: port, User: user, PrivateKey: privateKey, Connection: connection, Password: password, RunCommand: runCommand, } } ================================================ FILE: ansible/variables.go ================================================ /* * Copyright 2016 Red Hat * * 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 ansible import ( "io/ioutil" "os" "strings" "github.com/ghodss/yaml" ) const ( // AnsibleGlobalVariablesFile is the prefix file name for the Ansible global variables file AnsibleGlobalVariablesFile = "group_vars/" ) // LoadAnsibleVariables loads the global variables from the Ansible playbook // so that we can search and replace them inside other files like the RC.yml func LoadAnsibleVariables(hosts string) (map[string]string, error) { path := AnsibleGlobalVariablesFile + hosts if _, err := os.Stat(path); os.IsNotExist(err) { return map[string]string{}, nil } data, err := ioutil.ReadFile(path) if err != nil { return nil, err } variables := map[string]string{} err = yaml.Unmarshal(data, &variables) if err != nil { return variables, err } for k, v := range variables { variables[k] = ReplaceVariables(v, variables) } return variables, nil } // ReplaceVariables replaces variables in the given string using the Ansible variable syntax of // `{{ name }}` func ReplaceVariables(text string, variables map[string]string) string { for k, v := range variables { replace := "{{ " + k + " }}" text = strings.Replace(text, replace, v, -1) } return text } // LoadFileAndReplaceVariables loads the given file and replaces all the Ansible variable expressions // and then returns the data func LoadFileAndReplaceVariables(filename string, variables map[string]string) ([]byte, error) { data, err := ioutil.ReadFile(filename) if err != nil { return nil, err } // TODO replace the variables! text := ReplaceVariables(string(data), variables) return []byte(text), nil } ================================================ FILE: circle.yml ================================================ machine: environment: IMPORT_PATH: "github.com/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME" dependencies: pre: - echo $PATH - wget "https://github.com/Masterminds/glide/releases/download/0.8.2/glide-0.8.2-linux-amd64.tar.gz" - mkdir /home/ubuntu/.go_workspace/bin || true - tar -vxz -C /home/ubuntu/.go_workspace/bin --strip=1 -f glide-0.8.2-linux-amd64.tar.gz - mkdir -p "/home/ubuntu/.go_workspace/src/$IMPORT_PATH" || true - rsync -azC --delete ./ "/home/ubuntu/.go_workspace/src/$IMPORT_PATH/" override: - rm -rf vendor - make bootstrap build: pwd: "../.go_workspace/src/$IMPORT_PATH/" test: override: - make test lint: pwd: "../.go_workspace/src/$IMPORT_PATH/" # Disabled for now to avoid conflicts with the Jenkins builds: #deployment: # hub: # branch: master # owner: fabric8io # commands: # - docker build -t fabric8/kansible . # - docker login -e $DOCKER_EMAIL -u $DOCKER_USER -p $DOCKER_PASS # - docker push fabric8/kansible ================================================ FILE: cmd/kill.go ================================================ /* * Copyright 2016 Red Hat * * 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 cmd import ( "os" "github.com/spf13/cobra" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/fabric8io/kansible/ansible" "github.com/fabric8io/kansible/k8s" "github.com/fabric8io/kansible/log" "github.com/fabric8io/kansible/winrm" ) func init() { killCmd.Flags().StringVar(&rcName, "rc", "$KANSIBLE_RC", "the name of the ReplicationController for the supervisors") RootCmd.AddCommand(killCmd) } // killCmd kills the pending windows shell of the current pod if its still running var killCmd = &cobra.Command{ Use: "kill [command]", Short: "Kills any pending shells for this pod.", Long: `This commmand will find the shell thats associated with a pod and kill it.`, Run: func(cmd *cobra.Command, args []string) { f := cmdutil.NewFactory(clientConfig) if f == nil { log.Die("Failed to create Kubernetes client factory!") } kubeclient, err := f.Client() if err != nil || kubeclient == nil { log.Die(MessageFailedToCreateKubernetesClient, err) } ns, _, _ := f.DefaultNamespace() if len(ns) == 0 { ns = "default" } thisPodName, err := k8s.GetThisPodName() if err != nil { log.Die("Failed to get this pod name: %s", err) } pod, err := kubeclient.Pods(ns).Get(thisPodName) if err != nil { log.Die("Failed to get pod from API server: %s", err) } annotations := pod.ObjectMeta.Annotations if annotations == nil { log.Die("No annotations available on pod %s", thisPodName) } hostName := annotations[ansible.HostNameAnnotation] if len(hostName) == 0 { log.Info("No annotation `%s` available on pod %s", ansible.HostNameAnnotation, thisPodName) return } // now lets load the connection details from the RC annotations rcName = os.ExpandEnv(rcName) if rcName == "" { log.Die("Replication controller name is required") } rc, err := kubeclient.ReplicationControllers(ns).Get(rcName) if err != nil { log.Die("Failed to get replication controller from API server: %s", err) } if rc == nil { log.Die("No ReplicationController found for name %s", rcName) } metadata := &rc.ObjectMeta if metadata.Annotations == nil { metadata.Annotations = make(map[string]string) } rcAnnotations := metadata.Annotations hostsText := rcAnnotations[ansible.HostInventoryAnnotation] if len(hostsText) == 0 { log.Die("Could not find annotation %s on ReplicationController %s", ansible.HostInventoryAnnotation, rcName) } shellID := rcAnnotations[ansible.WinRMShellAnnotationPrefix+hostName] if len(shellID) == 0 { log.Info("No annotation `%s` available on pod %s", ansible.WinRMShellAnnotationPrefix, thisPodName) return } hostEntries, err := ansible.LoadHostEntriesFromText(hostsText) if err != nil { log.Die("Failed to load hosts: %s", err) } log.Info("Found %d host entries", len(hostEntries)) hostEntry := ansible.GetHostEntryByName(hostEntries, hostName) if hostEntry == nil { log.Die("Could not find a HostEntry called `%s` from %d host entries", hostName, len(hostEntries)) } err = winrm.CloseShell(hostEntry.User, hostEntry.Password, hostEntry.Host, hostEntry.Port, shellID) if err != nil { log.Die("Failed to close shell: %s", err) } log.Info("Shell %s has been closed", shellID) }, } ================================================ FILE: cmd/pod.go ================================================ /* * Copyright 2016 Red Hat * * 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 cmd import ( "io/ioutil" "os" "strconv" "strings" "github.com/spf13/cobra" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/fabric8io/kansible/ansible" "github.com/fabric8io/kansible/k8s" "github.com/fabric8io/kansible/log" "github.com/fabric8io/kansible/ssh" "github.com/fabric8io/kansible/winrm" ) var ( rcName, passwordFlag, connection, bash string ) func init() { podCmd.Flags().StringVar(&rcName, "rc", "$KANSIBLE_RC", "the name of the ReplicationController for the supervisors") podCmd.Flags().StringVar(&passwordFlag, "password", "$KANSIBLE_PASSWORD", "the password used for WinRM connections") podCmd.Flags().StringVar(&connection, "connection", "", "the Ansible connection type to use. Defaults to SSH unless 'winrm' is defined to use WinRM on Windows") podCmd.Flags().StringVar(&bash, "bash", "$KANSIBLE_BASH", "if specified a script is generated for running a bash like shell on the remote machine") RootCmd.AddCommand(podCmd) } // podCmd is the root command for the whole program. var podCmd = &cobra.Command{ Use: "pod [command]", Short: "Runs the kansible pod which owns a host from the Ansible inventory then runs a remote command on the host", Long: `This commmand will pick an available host from the Ansible inventory, then run a remote command on that host.`, Run: func(cmd *cobra.Command, args []string) { // Pod runs the kansible pod for a given group of hosts in an Ansible playbook // this grabs a specific host (using annotations on the RC) then runs a remote command // on that host binding stdin, stdout, stderr to the remote process if len(args) < 1 { log.Die("Expected arguments [command]") } hosts := os.ExpandEnv(args[0]) command := "" if len(args) > 1 { command = os.ExpandEnv(strings.Join(args[1:], " ")) } f := cmdutil.NewFactory(clientConfig) if f == nil { log.Die("Failed to create Kubernetes client factory!") } kubeclient, err := f.Client() if err != nil || kubeclient == nil { log.Die(MessageFailedToCreateKubernetesClient, err) } ns := os.Getenv(ansible.EnvNamespace) if len(ns) == 0 { ns, _, _ = f.DefaultNamespace() if len(ns) == 0 { ns = "default" } } rcName = os.ExpandEnv(rcName) if rcName == "" { log.Die("RC name is required") } thisPodName, err := k8s.GetThisPodName() if err != nil { log.Die("Couldn't get pod name: %s", err) } hostEntry, rc, envVars, err := ansible.ChooseHostAndPrivateKey(thisPodName, hosts, kubeclient, ns, rcName) if err != nil { log.Die("Couldn't find host: %s", err) } host := hostEntry.Host user := hostEntry.User port := hostEntry.Port if len(port) == 0 { port = strconv.Itoa(sshPort) } connection := hostEntry.Connection if len(connection) == 0 { connection = os.ExpandEnv(connection) } runCommand := hostEntry.RunCommand if len(runCommand) != 0 { command = runCommand } commandEnvVars := []string{} if len(command) == 0 { if len(connection) > 0 { envVarName := ansible.EnvCommand + "_" + strings.ToUpper(connection) commandEnvVars = append(commandEnvVars, envVarName) command = os.Getenv(envVarName) } } commandEnvVars = append(commandEnvVars, ansible.EnvCommand) if len(command) == 0 { command = os.Getenv(ansible.EnvCommand) } if len(command) == 0 { plural := "" if len(commandEnvVars) > 1 { plural = "s" } log.Die("Could not find a command to execute from the environment variable%s: %s", plural, strings.Join(commandEnvVars, ", ")) } bash := os.ExpandEnv(bash) if len(bash) > 0 { err = generateBashScript(bash, connection) if err != nil { log.Err("Failed to generate bash script at %s due to: %v", bash, err) return } } if connection == ansible.ConnectionWinRM { password := hostEntry.Password if len(password) == 0 { password = os.ExpandEnv(passwordFlag) if password == "" { log.Die("Cannot connect without a password") } } err = winrm.RemoteWinRmCommand(user, password, host, port, command, kubeclient, rc, hostEntry.Name) } else { privatekey := hostEntry.PrivateKey err = ssh.RemoteSSHCommand(user, privatekey, host, port, command, envVars) } if err != nil { log.Err("Failed: %v", err) } }, } func generateBashScript(file string, connection string) error { shellCommand := "bash" if connection == ansible.ConnectionWinRM { shellCommand = "cmd" } text := `#!/bin/sh echo "opening shell on remote machine..." export ` + ansible.EnvIsBashShell + `=true export ` + ansible.EnvPortForward + `=false kansible pod appservers ` + shellCommand + "\n" return ioutil.WriteFile(file, []byte(text), 0555) } ================================================ FILE: cmd/rc.go ================================================ /* * Copyright 2016 Red Hat * * 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 cmd import ( "os" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "github.com/fabric8io/kansible/ansible" "github.com/fabric8io/kansible/log" "github.com/spf13/cobra" ) const ( // MessageFailedToCreateKubernetesClient is the message to report if a kuberentes client cannot be created MessageFailedToCreateKubernetesClient = "Failed to create Kubernetes client. Maybe you need to run `oc login`?. Error: %s" ) var ( inventory string replicas int ) func init() { rcCmd.Flags().StringVar(&inventory, "inventory", "inventory", "the location of your Ansible inventory file") rcCmd.Flags().IntVar(&replicas, "replicas", -1, "specifies the number of replicas to create for the RC") RootCmd.AddCommand(rcCmd) } // RCCmd is the root command for the whole program. var rcCmd = &cobra.Command{ Use: "rc ", Short: "Creates or updates the kansible ReplicationController for some hosts in an Ansible inventory", Long: `This commmand will analyse the hosts in an Ansible inventory and creates or updates the ReplicationController for the kansible pods.`, Run: func(cmd *cobra.Command, args []string) { if len(args) != 1 { log.Die("Expected argument for the name of the hosts in the ansible inventory file") } hosts := args[0] f := cmdutil.NewFactory(clientConfig) if f == nil { log.Die("Failed to create Kubernetes client factory!") } kubeclient, err := f.Client() if err != nil || kubeclient == nil { log.Die(MessageFailedToCreateKubernetesClient, err) } ns, _, _ := f.DefaultNamespace() if len(ns) == 0 { ns = "default" } inventory = os.ExpandEnv(inventory) if inventory == "" { log.Die("Value for inventory flag is empty") } hostEntries, err := ansible.LoadHostEntries(inventory, hosts) if err != nil { log.Die("Cannot load host entries: %s", err) } log.Info("Found %d host entries in the Ansible inventory for %s", len(hostEntries), hosts) rcFile := "kubernetes/" + hosts + "/rc.yml" _, err = ansible.UpdateKansibleRC(hostEntries, hosts, f, kubeclient, ns, rcFile, replicas) if err != nil { log.Die("Failed to update Kansible RC: %s", err) } }, } ================================================ FILE: cmd/root.go ================================================ /* * Copyright 2016 Red Hat * * 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 cmd import ( "os" "github.com/spf13/cobra" "github.com/spf13/pflag" "k8s.io/kubernetes/pkg/client/unversioned/clientcmd" "github.com/fabric8io/kansible/log" ) var ( // RootCmd is the root command for the whole program. RootCmd = &cobra.Command{ Use: "kansible", Short: "Orchestrate processes in the same way as you orchestrate Docker containers with Kubernetes", Long: `Kansible Kansible orchestrates processes in the same way as you orchestrate Docker containers with Kubernetes. Once you have created an Ansible playbook to install and configure your software you can use Kansible to create a Kubernetes Replication Controller to run, scale and manage the processes providing a universal view in Kubernetes of all your containers and processes along with common scaling, high availability, service discovery and load balancing. More help is here: https://github.com/fabric8io/kansible/blob/master/README.md `, } sshPort int clientConfig clientcmd.ClientConfig ) func init() { RootCmd.PersistentFlags().IntVar(&sshPort, "port", 22, "the port for the remote SSH connection") RootCmd.PersistentFlags().BoolVar(&log.IsDebugging, "debug", false, "enable verbose debugging output") clientConfig = defaultClientConfig(RootCmd.PersistentFlags()) } func defaultClientConfig(flags *pflag.FlagSet) clientcmd.ClientConfig { loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() flags.StringVar(&loadingRules.ExplicitPath, "kubeconfig", "", "Path to the kubeconfig file to use for CLI requests.") overrides := &clientcmd.ConfigOverrides{} flagNames := clientcmd.RecommendedConfigOverrideFlags("") clientcmd.BindOverrideFlags(overrides, flags, flagNames) clientConfig := clientcmd.NewInteractiveDeferredLoadingClientConfig(loadingRules, overrides, os.Stdin) return clientConfig } ================================================ FILE: cmd/run.go ================================================ /* * Copyright 2016 Red Hat * * 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 cmd import ( "os" "strconv" "github.com/fabric8io/kansible/ansible" "github.com/fabric8io/kansible/log" "github.com/fabric8io/kansible/ssh" "github.com/fabric8io/kansible/winrm" "github.com/spf13/cobra" ) // cli.StringFlag{ // Name: "connection", // Usage: "The Ansible connection type to use. Defaults to SSH unless 'winrm' is defined to use WinRM on Windows", // }, // }, // }, var ( user, password, host, command, privatekey string ) func init() { runCmd.Flags().StringVar(&user, "user", "${KANSIBLE_USER}", "the user to use on the remote connection") runCmd.Flags().StringVar(&privatekey, "privatekey", "${KANSIBLE_PRIVATEKEY}", "the private key used for SSH") runCmd.Flags().StringVar(&host, "host", "${KANSIBLE_HOST}", "the host for the remote connection") runCmd.Flags().StringVar(&command, "command", "${KANSIBLE_COMMAND}", "the remote command to invoke on the host") runCmd.Flags().StringVar(&password, "password", "", "the password if using WinRM to execute the command") runCmd.Flags().StringVar(&connection, "connection", "", "the Ansible connection type to use. Defaults to SSH unless 'winrm' is defined to use WinRM on Windows") RootCmd.AddCommand(runCmd) } // runCmd runs a remote command on a given host to test out SSH / WinRM var runCmd = &cobra.Command{ Use: "run [command]", Short: "Runs a remote command on a given host to test out SSH / WinRM", Long: `This commmand will begin running the supervisor on an avaiable host.`, Run: func(cmd *cobra.Command, args []string) { command = os.ExpandEnv(command) if command == "" { log.Die("Command is required") } host = os.ExpandEnv(host) if host == "" { log.Die("Host is required") } user = os.ExpandEnv(user) if user == "" { log.Die("User is required") } if connection == ansible.ConnectionWinRM { password = os.ExpandEnv(password) if password == "" { log.Die("Password is required") } err := winrm.RemoteWinRmCommand(user, password, host, strconv.Itoa(sshPort), command, nil, nil, "") if err != nil { log.Err("Failed: %v", err) } } else { privatekey = os.ExpandEnv(privatekey) if privatekey == "" { log.Die("Private key is required") } err := ssh.RemoteSSHCommand(user, privatekey, host, strconv.Itoa(sshPort), command, nil) if err != nil { log.Err("Failed: %v", err) } } }, } ================================================ FILE: cmd/version.go ================================================ /* * Copyright 2016 Red Hat * * 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 cmd import ( "bytes" "fmt" "html/template" "os" "strings" "github.com/spf13/cobra" "github.com/fabric8io/kansible/version" ) var versionInfoTmpl = ` kansible, version {{.version}} (branch: {{.branch}}, revision: {{.revision}}) build user: {{.buildUser}} build date: {{.buildDate}} go version: {{.goVersion}} ` var versionCmd = &cobra.Command{ Use: "version", Short: "Output version information and exit", Long: `Output version information and exit.`, Run: func(cmd *cobra.Command, args []string) { t := template.Must(template.New("version").Parse(versionInfoTmpl)) var buf bytes.Buffer if err := t.ExecuteTemplate(&buf, "version", version.Map); err != nil { panic(err) } fmt.Fprintln(os.Stdout, strings.TrimSpace(buf.String())) }, } func init() { RootCmd.AddCommand(versionCmd) } ================================================ FILE: glide.yaml ================================================ package: github.com/fabric8io/gosupervise import: - package: github.com/Masterminds/vcs - package: github.com/Masterminds/semver version: ^1.0.0 - package: k8s.io/kubernetes version: v1.2.1 subpackages: - pkg/client - pkg/cmdutil - package: gopkg.in/yaml.v2 - package: github.com/nu7hatch/gouuid - package: github.com/masterzen/xmlpath version: 13f4951698adc0fa9c1dda3e275d489a24201161 - package: github.com/masterzen/simplexml subpackages: - dom - package: github.com/masterzen/winrm version: 71c963ed3718881facabea7cf61bc7b13911902e - package: github.com/fatih/color - package: github.com/cloudfoundry-incubator/candiedyaml ================================================ FILE: header.txt ================================================ Copyright <%=copyright_years.join(', ')%> <%=copyright_holders.join(', ')%> 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. ================================================ FILE: headers.yml ================================================ ruby: ext: ['.rb', '.rake'] after: ['^#!', '^#.*encoding:'] comment: open: '#\n' close: '#\n' prefix: '# ' perl: ext: ['.pl'] after: ['^#!', '^#.*encoding:'] comment: open: '#\n' close: '#\n' prefix: '# ' # Support PEP 0263 comments: # coding= # -*- coding: -*- # vim: set fileencoding= : python: ext: ['.py'] after: ['^#!', '^#.*coding:', '^#.*coding=', '^#.*fileencoding='] comment: open: '\n' close: '\n' prefix: '# ' html: ext: ['.html', '.htm', '.xhtml'] comment: open: '\n' prefix: ' ' php: ext: ['.php'] after: [ '^#!' ] comment: open: '\n' prefix: ' * ' javacript: ext: ['.js'] comment: open: '/*\n' close: ' */\n\n' prefix: ' * ' css: ext: ['.css'] comment: open: '/*\n' close: ' */\n\n' prefix: ' * ' c: ext: ['.c', '.h'] comment: open: '/*' close: ' */\n\n' prefix: ' * ' cpp: ext: ['.cpp', '.hpp', '.cc', '.hh'] comment: open: '//\n' close: '//\n\n' prefix: '// ' java: ext: ['.java'] comment: open: '/*\n' close: ' */\n\n' prefix: ' * ' groovy: ext: ['.groovy'] comment: open: '/*\n' close: ' */\n\n' prefix: ' * ' haml: ext: ['.haml', '.hamlc'] comment: open: '-#\n' close: '-#\n' prefix: '-# ' coffee: ext: ['.coffee'] comment: open: '###\n' close: '###\n' prefix: '' # M4 macro language, use #, not dnl m4: ext: ['.m4'] comment: open: '#\n' close: '#\n' prefix: '# ' # Most shells, really shell: ext: ['.sh'] after: ['^#!'] comment: open: '#\n' close: '#\n' prefix: '# ' # Use "-- " to make sure e.g. MySQL understands it sql: ext: ['.sql'] comment: open: '-- \n' close: '-- \n' prefix: '-- ' # XML is *not* the same as HTML, and the comments need to go after a # preprocessing directive, if present. # FIXME: only supports single line directives xml: ext: ['.xml', '.xsd', '.mxml'] after: ['^<\?'] comment: open: '\n' prefix: ' ' yaml: ext: ['.yml', '.yaml'] comment: open: '#\n' close: '#\n' prefix: '# ' action_script: ext: ['.as'] comment: open: '//\n' close: '//\n\n' prefix: '// ' sass: ext: ['.sass', '.scss'] comment: open: '/*\n' close: ' */\n\n' prefix: ' * ' go: ext: ['.go'] comment: open: '/*\n' close: ' */\n\n' prefix: ' * ' ================================================ FILE: k8s/k8s.go ================================================ /* * Copyright 2016 Red Hat * * 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 k8s import ( "bytes" "fmt" "io/ioutil" "os" "k8s.io/kubernetes/pkg/api" client "k8s.io/kubernetes/pkg/client/unversioned" "k8s.io/kubernetes/pkg/kubectl" cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" "k8s.io/kubernetes/pkg/kubectl/resource" "k8s.io/kubernetes/pkg/runtime" "k8s.io/kubernetes/pkg/util/strategicpatch" "github.com/ghodss/yaml" "github.com/fabric8io/kansible/log" ) // GetThisPodName returns this pod name via the `HOSTNAME` environment variable func GetThisPodName() (string, error) { var err error thisPodName := os.Getenv("HOSTNAME") if len(thisPodName) == 0 { thisPodName, err = os.Hostname() if err != nil { return "", err } } if len(thisPodName) == 0 { return "", fmt.Errorf("Could not find the pod name using $HOSTNAME!") } return thisPodName, nil } // ReadReplicationControllerFromFile reads the ReplicationController object from the given file name func ReadReplicationControllerFromFile(filename string) (*api.ReplicationController, error) { data, err := ioutil.ReadFile(filename) if err != nil { return nil, err } return ReadReplicationController(data) } // ReadReplicationController loads a ReplicationController from the given data func ReadReplicationController(data []byte) (*api.ReplicationController, error) { rc := api.ReplicationController{} if err := yaml.Unmarshal(data, &rc); err != nil { return nil, err } return &rc, nil } // PodIsRunning returns true if the given pod is running in the given list of all pods func PodIsRunning(pods *api.PodList, podName string) bool { for _, pod := range pods.Items { if pod.ObjectMeta.Name == podName { return true } } return false } // GetFirstContainerOrCreate returns the first Container in the PodSpec for this ReplicationController // lazily creating structures as required func GetFirstContainerOrCreate(rc *api.ReplicationController) *api.Container { podSpec := GetOrCreatePodSpec(rc) if len(podSpec.Containers) == 0 { podSpec.Containers[0] = api.Container{} } return &podSpec.Containers[0] } // GetOrCreatePodSpec returns the PodSpec for this ReplicationController // lazily creating structures as required func GetOrCreatePodSpec(rc *api.ReplicationController) *api.PodSpec { spec := &rc.Spec if spec == nil { rc.Spec = api.ReplicationControllerSpec{} spec = &rc.Spec } template := spec.Template if template == nil { spec.Template = &api.PodTemplateSpec{} template = spec.Template } podSpec := &template.Spec if podSpec == nil { template.Spec = api.PodSpec{} podSpec = &template.Spec } return podSpec } // GetContainerEnvVar returns the environment variable value for the given name in the Container func GetContainerEnvVar(container *api.Container, name string) string { if container != nil { for _, env := range container.Env { if env.Name == name { return env.Value } } } return "" } // EnsureContainerHasEnvVar if there is an existing EnvVar for the given name then lets update it // with the given value otherwise lets add a new entry. // Returns true if there was already an existing environment variable func EnsureContainerHasEnvVar(container *api.Container, name string, value string) bool { for _, env := range container.Env { if env.Name == name { env.Value = value return true } } container.Env = append(container.Env, api.EnvVar{ Name: name, Value: value, }) return false } // EnsureContainerHasEnvVarFromField if there is an existing EnvVar for the given name then lets update it // with the given fieldPath otherwise lets add a new entry. // Returns true if there was already an existing environment variable func EnsureContainerHasEnvVarFromField(container *api.Container, name string, fieldPath string) bool { from := &api.EnvVarSource{ FieldRef: &api.ObjectFieldSelector{ FieldPath: fieldPath, }, } for _, env := range container.Env { if env.Name == name { env.ValueFrom = from env.Value = "" return true } } container.Env = append(container.Env, api.EnvVar{ Name: name, ValueFrom: from, }) return false } // EnsureContainerHasPreStopCommand ensures that the given container has a `preStop` lifecycle hook // to invoke the given commands func EnsureContainerHasPreStopCommand(container *api.Container, commands []string) { if container.Lifecycle == nil { container.Lifecycle = &api.Lifecycle{} } lifecycle := container.Lifecycle if lifecycle.PreStop == nil { lifecycle.PreStop = &api.Handler{} } preStop := lifecycle.PreStop preStop.Exec = &api.ExecAction{ Command: commands, } } // EnsureContainerHasVolumeMount ensures that there is a volume mount of the given name with the given values // Returns true if there was already a volume mount func EnsureContainerHasVolumeMount(container *api.Container, name string, mountPath string) bool { for _, vm := range container.VolumeMounts { if vm.Name == name { vm.MountPath = mountPath return true } } container.VolumeMounts = append(container.VolumeMounts, api.VolumeMount{ Name: name, MountPath: mountPath, }) return false } // EnsurePodSpecHasGitVolume ensures that there is a volume with the given name and git repo and revision func EnsurePodSpecHasGitVolume(podSpec *api.PodSpec, name string, gitRepo string, gitRevision string) bool { for _, vm := range podSpec.Volumes { if vm.Name == name { vm.GitRepo = &api.GitRepoVolumeSource{ Repository: gitRepo, Revision: gitRevision, } return true } } podSpec.Volumes = append(podSpec.Volumes, api.Volume{ Name: name, VolumeSource: api.VolumeSource{ GitRepo: &api.GitRepoVolumeSource{ Repository: gitRepo, Revision: gitRevision, }, }, }) return false } // EnsurePodSpecHasSecretVolume ensures that there is a volume with the given name and secret func EnsurePodSpecHasSecretVolume(podSpec *api.PodSpec, name string, secretName string) bool { for _, vm := range podSpec.Volumes { if vm.Name == name { vm.Secret = &api.SecretVolumeSource{ SecretName: secretName, } return true } } podSpec.Volumes = append(podSpec.Volumes, api.Volume{ Name: name, VolumeSource: api.VolumeSource{ Secret: &api.SecretVolumeSource{ SecretName: secretName, }, }, }) return false } // EnsureServiceAccountExists ensures that there is a service account created for the given name func EnsureServiceAccountExists(c *client.Client, ns string, serviceAccountName string) (bool, error) { saClient := c.ServiceAccounts(ns) sa, err := saClient.Get(serviceAccountName) created := false if err != nil || sa == nil { // lets try create the SA sa = &api.ServiceAccount{ ObjectMeta: api.ObjectMeta{ Name: serviceAccountName, }, } log.Info("Creating ServiceAccount %s", serviceAccountName) _, err = saClient.Create(sa) if err == nil { created = true } } return created, err } // ApplyResource applies the given data as a kubernetes resource func ApplyResource(f *cmdutil.Factory, c *client.Client, ns string, data []byte, name string) error { schemaCacheDir := "/tmp/kubectl.schema" validate := true schema, err := f.Validator(validate, schemaCacheDir) if err != nil { log.Info("Failed to load kubernetes schema: %s", err) return err } mapper, typer := f.Object() r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)). Schema(schema). ContinueOnError(). NamespaceParam(ns).DefaultNamespace(). Stream(bytes.NewReader(data), name). Flatten(). Do() err = r.Err() if err != nil { log.Info("Failed to load mapper!") return err } count := 0 err = r.Visit(func(info *resource.Info, err error) error { // In this method, info.Object contains the object retrieved from the server // and info.VersionedObject contains the object decoded from the input source. if err != nil { return err } // Get the modified configuration of the object. Embed the result // as an annotation in the modified configuration, so that it will appear // in the patch sent to the server. modified, err := kubectl.GetModifiedConfiguration(info, true, f.JSONEncoder()) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving modified configuration from:\n%v\nfor:", info), info.Source, err) } if err := info.Get(); err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving current configuration of:\n%v\nfrom server for:", info), info.Source, err) } // Serialize the current configuration of the object from the server. current, err := runtime.Encode(f.JSONEncoder(), info.Object) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf("serializing current configuration from:\n%v\nfor:", info), info.Source, err) } // Retrieve the original configuration of the object from the annotation. original, err := kubectl.GetOriginalConfiguration(info) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf("retrieving original configuration from:\n%v\nfor:", info), info.Source, err) } // Compute a three way strategic merge patch to send to server. patch, err := strategicpatch.CreateThreeWayMergePatch(original, modified, current, info.VersionedObject, false) if err != nil { format := "creating patch with:\noriginal:\n%s\nmodified:\n%s\ncurrent:\n%s\nfrom:\n%v\nfor:" return cmdutil.AddSourceToErr(fmt.Sprintf(format, original, modified, current, info), info.Source, err) } helper := resource.NewHelper(info.Client, info.Mapping) _, err = helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patch) if err != nil { return cmdutil.AddSourceToErr(fmt.Sprintf("applying patch:\n%s\nto:\n%v\nfor:", patch, info), info.Source, err) } count++ cmdutil.PrintSuccess(mapper, false, os.Stdout, info.Mapping.Resource, info.Name, "configured") return nil }) if err != nil { return err } if count == 0 { return fmt.Errorf("no objects passed to apply") } return nil } ================================================ FILE: kansible.go ================================================ /* * Copyright 2016 Red Hat * * 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 main import ( "fmt" "os" "github.com/fabric8io/kansible/cmd" ) func main() { if err := cmd.RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } ================================================ FILE: log/log.go ================================================ /* * Copyright 2016 Red Hat * * 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 log import ( "fmt" "os" "github.com/fatih/color" ) var ( // IsDebugging toggles whether or not to enable debug output and behavior. IsDebugging = false // ErrorState denotes if application is in an error state. ErrorState = false ) // Msg passes through the formatter, but otherwise prints exactly as-is. // // No prettification. func Msg(format string, v ...interface{}) { fmt.Printf(appendNewLine(format), v...) } // Die prints an error and then call os.Exit(1). func Die(format string, v ...interface{}) { Err(format, v...) if IsDebugging { panic(fmt.Sprintf(format, v...)) } os.Exit(1) } // CleanExit prints a message and then exits with 0. func CleanExit(format string, v ...interface{}) { Info(format, v...) os.Exit(0) } // Err prints an error message. It does not cause an exit. func Err(format string, v ...interface{}) { fmt.Print(color.RedString("[ERROR] ")) fmt.Printf(appendNewLine(format), v...) ErrorState = true } // Info prints a green-tinted message. func Info(format string, v ...interface{}) { fmt.Print(color.GreenString("---> ")) fmt.Printf(appendNewLine(format), v...) } // Debug prints a cyan-tinted message if IsDebugging is true. func Debug(format string, v ...interface{}) { if IsDebugging { fmt.Print(color.CyanString("[DEBUG] ")) fmt.Printf(appendNewLine(format), v...) } } // Warn prints a yellow-tinted warning message. func Warn(format string, v ...interface{}) { fmt.Print(color.YellowString("[WARN] ")) fmt.Printf(appendNewLine(format), v...) } func appendNewLine(format string) string { return format + "\n" } ================================================ FILE: ssh/ssh.go ================================================ /* * Copyright 2016 Red Hat * * 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 ssh import ( "fmt" "io" "io/ioutil" "net" "os" "os/signal" "github.com/fabric8io/kansible/log" "golang.org/x/crypto/ssh" "syscall" ) // RemoteSSHCommand invokes the given command on a host and port func RemoteSSHCommand(user string, privateKey string, host string, port string, cmd string, envVars map[string]string) error { if len(privateKey) == 0 { return fmt.Errorf("Could not find PrivateKey for entry %s", host) } log.Info("Connecting to host over SSH on host %s and port %s with user %s with command `%s`", host, port, user, cmd) hostPort := net.JoinHostPort(host, port) sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{ PublicKeyFile(privateKey), }, } if sshConfig == nil { log.Warn("No sshConfig could be created!") } connection, err := ssh.Dial("tcp", hostPort, sshConfig) if err != nil { return fmt.Errorf("Failed to dial: %s", err) } session, err := connection.NewSession() if err != nil { return fmt.Errorf("Failed to create session: %s", err) } defer session.Close() modes := ssh.TerminalModes{ // ssh.ECHO: 0, // disable echoing ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud } if err := session.RequestPty("xterm", 80, 40, modes); err != nil { return fmt.Errorf("Request for pseudo terminal failed: %s", err) } stdin, err := session.StdinPipe() if err != nil { return fmt.Errorf("Unable to setup stdin for session: %v", err) } go io.Copy(stdin, os.Stdin) stdout, err := session.StdoutPipe() if err != nil { return fmt.Errorf("Unable to setup stdout for session: %v", err) } go io.Copy(os.Stdout, stdout) stderr, err := session.StderrPipe() if err != nil { return fmt.Errorf("Unable to setup stderr for session: %v", err) } go io.Copy(os.Stderr, stderr) for envName, envValue := range envVars { log.Info("Setting environment value %s = %s", envName, envValue) if err := session.Setenv(envName, envValue); err != nil { return fmt.Errorf("Could not set environment variable %s = %s over SSH. This could be disabled by the sshd configuration. See the `AcceptEnv` setting in your /etc/ssh/sshd_config more info: http://linux.die.net/man/5/sshd_config . Error: %s", envName, envValue, err) } } signals := make(chan os.Signal, 1) signal.Notify(signals, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) signaled := false go func() { <-signals log.Info("Shutting down SSH session.") signaled = true session.Close() }() log.Info("Running command %s", cmd) err = session.Run(cmd) if !signaled && err != nil { return fmt.Errorf("Failed to run command: " + cmd + ": %v", err) } return nil } // PublicKeyFile creates the auth method for the given private key file func PublicKeyFile(file string) ssh.AuthMethod { buffer, err := ioutil.ReadFile(file) if err != nil { return nil } key, err := ssh.ParsePrivateKey(buffer) if err != nil { return nil } return ssh.PublicKeys(key) } ================================================ FILE: tools/create-intellij-idea-golib.sh ================================================ #!/bin/bash # Build up a GOPATH directory for IntelliJ IDEA # which doesn't support GO15VENDOREXPERIMENT yet pushd `dirname $0`/.. > /dev/null base=`pwd` popd > /dev/null golib=${base}/golib rm -rf ${golib} # Link all from the vendor dirs pulled by glide: vendor_src=${golib}/vendor/src mkdir -p ${vendor_src} for f in ${base}/vendor/* do # echo "Symlinking vendor source dir: ${base}/${f}" ln -s "${f}" "${vendor_src}/" done # Link self into the golib dir self_src=${golib}/self/src/github.com/fabric8io mkdir -p ${self_src} ln -s "${base}" "${self_src}/kansible"; echo "Use the following dirs exclusively as go-libraries in IntelliJ IDEA:" echo "(Preferences -> Languages & Frameworks -> Go -> Go Libraries, Add to Project Libraries, uncheck 'use system defined GOPATH')" echo echo "${golib}/vendor" echo "${golib}/self" ================================================ FILE: vendor/bitbucket.org/ww/goautoneg/Makefile ================================================ include $(GOROOT)/src/Make.inc TARG=bitbucket.org/ww/goautoneg GOFILES=autoneg.go include $(GOROOT)/src/Make.pkg format: gofmt -w *.go docs: gomake clean godoc ${TARG} > README.txt ================================================ FILE: vendor/bitbucket.org/ww/goautoneg/README.txt ================================================ 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 ================================================ FILE: vendor/bitbucket.org/ww/goautoneg/autoneg.go ================================================ /* 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 } ================================================ FILE: vendor/bitbucket.org/ww/goautoneg/autoneg_test.go ================================================ package goautoneg import ( "testing" ) var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" func TestParseAccept(t *testing.T) { alternatives := []string{"text/html", "image/png"} content_type := Negotiate(chrome, alternatives) if content_type != "image/png" { t.Errorf("got %s expected image/png", content_type) } alternatives = []string{"text/html", "text/plain", "text/n3"} content_type = Negotiate(chrome, alternatives) if content_type != "text/html" { t.Errorf("got %s expected text/html", content_type) } alternatives = []string{"text/n3", "text/plain"} content_type = Negotiate(chrome, alternatives) if content_type != "text/plain" { t.Errorf("got %s expected text/plain", content_type) } alternatives = []string{"text/n3", "application/rdf+xml"} content_type = Negotiate(chrome, alternatives) if content_type != "text/n3" { t.Errorf("got %s expected text/n3", content_type) } } ================================================ FILE: vendor/github.com/Masterminds/semver/.travis.yml ================================================ language: go go: - 1.3 - 1.4 - 1.5 - tip # Setting sudo access to false will let Travis CI use containers rather than # VMs to run the tests. For more details see: # - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ # - http://docs.travis-ci.com/user/workers/standard-infrastructure/ sudo: false notifications: irc: "irc.freenode.net#masterminds" ================================================ FILE: vendor/github.com/Masterminds/semver/CHANGELOG.md ================================================ # Release 1.x.x (xxxx-xx-xx) - Issue #9: Speed up version comparison performance (thanks @sdboyer) - Issue #8: Added benchmarks (thanks @sdboyer) # Release 1.1.0 (2015-03-11) - Issue #2: Implemented validation to provide reasons a versions failed a constraint. # Release 1.0.1 (2015-12-31) - Fixed #1: * constraint failing on valid versions. # Release 1.0.0 (2015-10-20) - Initial release ================================================ FILE: vendor/github.com/Masterminds/semver/LICENSE.txt ================================================ The Masterminds Copyright (C) 2014-2015, Matt Butcher and Matt Farina 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. ================================================ FILE: vendor/github.com/Masterminds/semver/README.md ================================================ # SemVer The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to: * Parse semantic versions * Sort semantic versions * Check if a semantic version fits within a set of constraints * Optionally work with a `v` prefix [![Build Status](https://travis-ci.org/Masterminds/semver.svg)](https://travis-ci.org/Masterminds/semver) [![Build status](https://ci.appveyor.com/api/projects/status/jfk66lib7hb985k8/branch/master?svg=true&passingText=windows%20build%20passing&failingText=windows%20build%20failing)](https://ci.appveyor.com/project/mattfarina/semver/branch/master) [![GoDoc](https://godoc.org/github.com/Masterminds/semver?status.png)](https://godoc.org/github.com/Masterminds/semver) [![Go Report Card](http://goreportcard.com/badge/Masterminds/semver)](http://goreportcard.com/report/Masterminds/semver) ## Parsing Semantic Versions To parse a semantic version use the `NewVersion` function. For example, v, err := semver.NewVersion("1.2.3-beta.1+build345") If there is an error the version wasn't parseable. The version object has methods to get the parts of the version, compare it to other versions, convert the version back into a string, and get the original string. For more details please see the [documentation](https://godoc.org/github.com/Masterminds/semver). ## Sorting Semantic Versions A set of versions can be sorted using the [`sort`](https://golang.org/pkg/sort/) package from the standard library. For example, raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} vs := make([]*semver.Version, len(raw)) for i, r := range raw { v, err := semver.NewVersion(r) if err != nil { t.Errorf("Error parsing version: %s", err) } vs[i] = v } sort.Sort(semver.Collection(vs)) ## Checking Version Constraints Checking a version against version constraints is one of the most featureful parts of the package. c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parseable. } v, _ := semver.NewVersion("1.3") if err != nil { // Handle version not being parseable. } // Check if the version meets the constraints. The a variable will be true. a := c.Check(v) ## Basic Comparisons There are two elements to the comparisons. First, a comparison string is a list of comma separated and comparisons. These are then separated by || separated or comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a comparison that's greater than or equal to 1.2 and less than 3.0.0 or is greater than or equal to 4.2.3. The basic comparisons are: * `=`: equal (aliased to no operator) * `!=`: not equal * `>`: greater than * `<`: less than * `>=`: greater than or equal to * `<=`: less than or equal to ## Hyphen Range Comparisons There are multiple methods to handle ranges and the first is hyphens ranges. These look like: * `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` * `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` ## Wildcards In Comparisons The `x`, `X`, and `*` characters can be used as a wildcard character. This works for all comparison operators. When used on the `=` operator it falls back to the pack level comparison (see tilde below). For example, * `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` * `>= 1.2.x` is equivalent to `>= 1.2.0` * `<= 2.x` is equivalent to `<= 3` * `*` is equivalent to `>= 0.0.0` ## Tilde Range Comparisons (Patch) The tilde (`~`) comparison operator is for patch level ranges when a minor version is specified and major level changes when the minor number is missing. For example, * `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` * `~1` is equivalent to `>= 1, < 2` * `~2.3` is equivalent to `>= 2.3, < 2.4` * `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` * `~1.x` is equivalent to `>= 1, < 2` ## Caret Range Comparisons (Major) The caret (`^`) comparison operator is for major level changes. This is useful when comparisons of API versions as a major change is API breaking. For example, * `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` * `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` * `^2.3` is equivalent to `>= 2.3, < 3` * `^2.x` is equivalent to `>= 2.0.0, < 3` # Validation In addition to testing a version against a constraint, a version can be validated against a constraint. When validation fails a slice of errors containing why a version didn't meet the constraint is returned. For example, c, err := semver.NewConstraint("<= 1.2.3, >= 1.4") if err != nil { // Handle constraint not being parseable. } v, _ := semver.NewVersion("1.3") if err != nil { // Handle version not being parseable. } // Validate a version against a constraint. a, msgs := c.Validate(v) // a is false for _, m := range msgs { fmt.Println(m) // Loops over the errors which would read // "1.3 is greater than 1.2.3" // "1.3 is less than 1.4" } # Contribute If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues) or [create a pull request](https://github.com/Masterminds/semver/pulls). ================================================ FILE: vendor/github.com/Masterminds/semver/appveyor.yml ================================================ version: build-{build}.{branch} clone_folder: C:\gopath\src\github.com\Masterminds\semver shallow_clone: true environment: GOPATH: C:\gopath platform: - x64 install: - go version - go env build_script: - go install -v ./... test_script: - go test -v deploy: off ================================================ FILE: vendor/github.com/Masterminds/semver/benchmark_test.go ================================================ package semver_test import ( "testing" "github.com/Masterminds/semver" ) /* Constraint creation benchmarks */ func benchNewConstraint(c string, b *testing.B) { for i := 0; i < b.N; i++ { semver.NewConstraint(c) } } func BenchmarkNewConstraintUnary(b *testing.B) { benchNewConstraint("=2.0", b) } func BenchmarkNewConstraintTilde(b *testing.B) { benchNewConstraint("~2.0.0", b) } func BenchmarkNewConstraintCaret(b *testing.B) { benchNewConstraint("^2.0.0", b) } func BenchmarkNewConstraintWildcard(b *testing.B) { benchNewConstraint("1.x", b) } func BenchmarkNewConstraintRange(b *testing.B) { benchNewConstraint(">=2.1.x, <3.1.0", b) } func BenchmarkNewConstraintUnion(b *testing.B) { benchNewConstraint("~2.0.0 || =3.1.0", b) } /* Check benchmarks */ func benchCheckVersion(c, v string, b *testing.B) { version, _ := semver.NewVersion(v) constraint, _ := semver.NewConstraint(c) for i := 0; i < b.N; i++ { constraint.Check(version) } } func BenchmarkCheckVersionUnary(b *testing.B) { benchCheckVersion("=2.0", "2.0.0", b) } func BenchmarkCheckVersionTilde(b *testing.B) { benchCheckVersion("~2.0.0", "2.0.5", b) } func BenchmarkCheckVersionCaret(b *testing.B) { benchCheckVersion("^2.0.0", "2.1.0", b) } func BenchmarkCheckVersionWildcard(b *testing.B) { benchCheckVersion("1.x", "1.4.0", b) } func BenchmarkCheckVersionRange(b *testing.B) { benchCheckVersion(">=2.1.x, <3.1.0", "2.4.5", b) } func BenchmarkCheckVersionUnion(b *testing.B) { benchCheckVersion("~2.0.0 || =3.1.0", "3.1.0", b) } func benchValidateVersion(c, v string, b *testing.B) { version, _ := semver.NewVersion(v) constraint, _ := semver.NewConstraint(c) for i := 0; i < b.N; i++ { constraint.Validate(version) } } /* Validate benchmarks, including fails */ func BenchmarkValidateVersionUnary(b *testing.B) { benchValidateVersion("=2.0", "2.0.0", b) } func BenchmarkValidateVersionUnaryFail(b *testing.B) { benchValidateVersion("=2.0", "2.0.1", b) } func BenchmarkValidateVersionTilde(b *testing.B) { benchValidateVersion("~2.0.0", "2.0.5", b) } func BenchmarkValidateVersionTildeFail(b *testing.B) { benchValidateVersion("~2.0.0", "1.0.5", b) } func BenchmarkValidateVersionCaret(b *testing.B) { benchValidateVersion("^2.0.0", "2.1.0", b) } func BenchmarkValidateVersionCaretFail(b *testing.B) { benchValidateVersion("^2.0.0", "4.1.0", b) } func BenchmarkValidateVersionWildcard(b *testing.B) { benchValidateVersion("1.x", "1.4.0", b) } func BenchmarkValidateVersionWildcardFail(b *testing.B) { benchValidateVersion("1.x", "2.4.0", b) } func BenchmarkValidateVersionRange(b *testing.B) { benchValidateVersion(">=2.1.x, <3.1.0", "2.4.5", b) } func BenchmarkValidateVersionRangeFail(b *testing.B) { benchValidateVersion(">=2.1.x, <3.1.0", "1.4.5", b) } func BenchmarkValidateVersionUnion(b *testing.B) { benchValidateVersion("~2.0.0 || =3.1.0", "3.1.0", b) } func BenchmarkValidateVersionUnionFail(b *testing.B) { benchValidateVersion("~2.0.0 || =3.1.0", "3.1.1", b) } /* Version creation benchmarks */ func benchNewVersion(v string, b *testing.B) { for i := 0; i < b.N; i++ { semver.NewVersion(v) } } func BenchmarkNewVersionSimple(b *testing.B) { benchNewVersion("1.0.0", b) } func BenchmarkNewVersionPre(b *testing.B) { benchNewVersion("1.0.0-alpha", b) } func BenchmarkNewVersionMeta(b *testing.B) { benchNewVersion("1.0.0+metadata", b) } func BenchmarkNewVersionMetaDash(b *testing.B) { benchNewVersion("1.0.0+metadata-dash", b) } ================================================ FILE: vendor/github.com/Masterminds/semver/collection.go ================================================ package semver // Collection is a collection of Version instances and implements the sort // interface. See the sort package for more details. // https://golang.org/pkg/sort/ type Collection []*Version // Len returns the length of a collection. The number of Version instances // on the slice. func (c Collection) Len() int { return len(c) } // Less is needed for the sort interface to compare two Version objects on the // slice. If checks if one is less than the other. func (c Collection) Less(i, j int) bool { return c[i].LessThan(c[j]) } // Swap is needed for the sort interface to replace the Version objects // at two different positions in the slice. func (c Collection) Swap(i, j int) { c[i], c[j] = c[j], c[i] } ================================================ FILE: vendor/github.com/Masterminds/semver/collection_test.go ================================================ package semver import ( "reflect" "sort" "testing" ) func TestCollection(t *testing.T) { raw := []string{ "1.2.3", "1.0", "1.3", "2", "0.4.2", } vs := make([]*Version, len(raw)) for i, r := range raw { v, err := NewVersion(r) if err != nil { t.Errorf("Error parsing version: %s", err) } vs[i] = v } sort.Sort(Collection(vs)) e := []string{ "0.4.2", "1.0.0", "1.2.3", "1.3.0", "2.0.0", } a := make([]string, len(vs)) for i, v := range vs { a[i] = v.String() } if !reflect.DeepEqual(a, e) { t.Error("Sorting Collection failed") } } ================================================ FILE: vendor/github.com/Masterminds/semver/constraints.go ================================================ package semver import ( "errors" "fmt" "regexp" "strings" ) // Constraints is one or more constraint that a semantic version can be // checked against. type Constraints struct { constraints [][]*constraint } // NewConstraint returns a Constraints instance that a Version instance can // be checked against. If there is a parse error it will be returned. func NewConstraint(c string) (*Constraints, error) { // Rewrite - ranges into a comparison operation. c = rewriteRange(c) ors := strings.Split(c, "||") or := make([][]*constraint, len(ors)) for k, v := range ors { cs := strings.Split(v, ",") result := make([]*constraint, len(cs)) for i, s := range cs { pc, err := parseConstraint(s) if err != nil { return nil, err } result[i] = pc } or[k] = result } o := &Constraints{constraints: or} return o, nil } // Check tests if a version satisfies the constraints. func (cs Constraints) Check(v *Version) bool { // loop over the ORs and check the inner ANDs for _, o := range cs.constraints { joy := true for _, c := range o { if !c.check(v) { joy = false break } } if joy { return true } } return false } // Validate checks if a version satisfies a constraint. If not a slice of // reasons for the failure are returned in addition to a bool. func (cs Constraints) Validate(v *Version) (bool, []error) { // loop over the ORs and check the inner ANDs var e []error for _, o := range cs.constraints { joy := true for _, c := range o { if !c.check(v) { em := fmt.Errorf(c.msg, v, c.orig) e = append(e, em) joy = false } } if joy { return true, []error{} } } return false, e } var constraintOps map[string]cfunc var constraintMsg map[string]string var constraintRegex *regexp.Regexp func init() { constraintOps = map[string]cfunc{ "": constraintTildeOrEqual, "=": constraintTildeOrEqual, "!=": constraintNotEqual, ">": constraintGreaterThan, "<": constraintLessThan, ">=": constraintGreaterThanEqual, "=>": constraintGreaterThanEqual, "<=": constraintLessThanEqual, "=<": constraintLessThanEqual, "~": constraintTilde, "~>": constraintTilde, "^": constraintCaret, } constraintMsg = map[string]string{ "": "%s is not equal to %s", "=": "%s is not equal to %s", "!=": "%s is equal to %s", ">": "%s is less than or equal to %s", "<": "%s is greater than or equal to %s", ">=": "%s is less than %s", "=>": "%s is less than %s", "<=": "%s is greater than %s", "=<": "%s is greater than %s", "~": "%s does not have same major and minor version as %s", "~>": "%s does not have same major and minor version as %s", "^": "%s does not have same major version as %s", } ops := make([]string, 0, len(constraintOps)) for k := range constraintOps { ops = append(ops, regexp.QuoteMeta(k)) } constraintRegex = regexp.MustCompile(fmt.Sprintf( `^\s*(%s)\s*(%s)\s*$`, strings.Join(ops, "|"), cvRegex)) constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( `\s*(%s)\s*-\s*(%s)\s*`, cvRegex, cvRegex)) } // An individual constraint type constraint struct { // The callback function for the restraint. It performs the logic for // the constraint. function cfunc msg string // The version used in the constraint check. For example, if a constraint // is '<= 2.0.0' the con a version instance representing 2.0.0. con *Version // The original parsed version (e.g., 4.x from != 4.x) orig string // When an x is used as part of the version (e.g., 1.x) minorDirty bool dirty bool } // Check if a version meets the constraint func (c *constraint) check(v *Version) bool { return c.function(v, c) } type cfunc func(v *Version, c *constraint) bool func parseConstraint(c string) (*constraint, error) { m := constraintRegex.FindStringSubmatch(c) if m == nil { return nil, fmt.Errorf("improper constraint: %s", c) } ver := m[2] orig := ver minorDirty := false dirty := false if isX(m[3]) { ver = "0.0.0" dirty = true } else if isX(strings.TrimPrefix(m[4], ".")) { minorDirty = true dirty = true ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) } else if isX(strings.TrimPrefix(m[5], ".")) { dirty = true ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) } con, err := NewVersion(ver) if err != nil { // The constraintRegex should catch any regex parsing errors. So, // we should never get here. return nil, errors.New("constraint Parser Error") } cs := &constraint{ function: constraintOps[m[1]], msg: constraintMsg[m[1]], con: con, orig: orig, minorDirty: minorDirty, dirty: dirty, } return cs, nil } // Constraint functions func constraintNotEqual(v *Version, c *constraint) bool { if c.dirty { if c.con.Major() != v.Major() { return true } if c.con.Minor() != v.Minor() && !c.minorDirty { return true } else if c.minorDirty { return false } return false } return !v.Equal(c.con) } func constraintGreaterThan(v *Version, c *constraint) bool { return v.Compare(c.con) == 1 } func constraintLessThan(v *Version, c *constraint) bool { if !c.dirty { return v.Compare(c.con) < 0 } if v.Major() > c.con.Major() { return false } else if v.Minor() > c.con.Minor() && !c.minorDirty { return false } return true } func constraintGreaterThanEqual(v *Version, c *constraint) bool { return v.Compare(c.con) >= 0 } func constraintLessThanEqual(v *Version, c *constraint) bool { if !c.dirty { return v.Compare(c.con) <= 0 } if v.Major() > c.con.Major() { return false } else if v.Minor() > c.con.Minor() && !c.minorDirty { return false } return true } // ~*, ~>* --> >= 0.0.0 (any) // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 // ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 // ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 func constraintTilde(v *Version, c *constraint) bool { if v.LessThan(c.con) { return false } // ~0.0.0 is a special case where all constraints are accepted. It's // equivalent to >= 0.0.0. if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 { return true } if v.Major() != c.con.Major() { return false } if v.Minor() != c.con.Minor() && !c.minorDirty { return false } return true } // When there is a .x (dirty) status it automatically opts in to ~. Otherwise // it's a straight = func constraintTildeOrEqual(v *Version, c *constraint) bool { if c.dirty { c.msg = constraintMsg["~"] return constraintTilde(v, c) } return v.Equal(c.con) } // ^* --> (any) // ^2, ^2.x, ^2.x.x --> >=2.0.0, <3.0.0 // ^2.0, ^2.0.x --> >=2.0.0, <3.0.0 // ^1.2, ^1.2.x --> >=1.2.0, <2.0.0 // ^1.2.3 --> >=1.2.3, <2.0.0 // ^1.2.0 --> >=1.2.0, <2.0.0 func constraintCaret(v *Version, c *constraint) bool { if v.LessThan(c.con) { return false } if v.Major() != c.con.Major() { return false } return true } var constraintRangeRegex *regexp.Regexp const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` func isX(x string) bool { switch x { case "x", "*", "X": return true default: return false } } func rewriteRange(i string) string { m := constraintRangeRegex.FindAllStringSubmatch(i, -1) if m == nil { return i } o := i for _, v := range m { t := fmt.Sprintf(">= %s, <= %s", v[1], v[11]) o = strings.Replace(o, v[0], t, 1) } return o } ================================================ FILE: vendor/github.com/Masterminds/semver/constraints_test.go ================================================ package semver import ( "reflect" "testing" ) func TestParseConstraint(t *testing.T) { tests := []struct { in string f cfunc v string err bool }{ {">= 1.2", constraintGreaterThanEqual, "1.2.0", false}, {"1.0", constraintTildeOrEqual, "1.0.0", false}, {"foo", nil, "", true}, {"<= 1.2", constraintLessThanEqual, "1.2.0", false}, {"=< 1.2", constraintLessThanEqual, "1.2.0", false}, {"=> 1.2", constraintGreaterThanEqual, "1.2.0", false}, {"v1.2", constraintTildeOrEqual, "1.2.0", false}, {"=1.5", constraintTildeOrEqual, "1.5.0", false}, {"> 1.3", constraintGreaterThan, "1.3.0", false}, {"< 1.4.1", constraintLessThan, "1.4.1", false}, } for _, tc := range tests { c, err := parseConstraint(tc.in) if tc.err && err == nil { t.Errorf("Expected error for %s didn't occur", tc.in) } else if !tc.err && err != nil { t.Errorf("Unexpected error for %s", tc.in) } // If an error was expected continue the loop and don't try the other // tests as they will cause errors. if tc.err { continue } if tc.v != c.con.String() { t.Errorf("Incorrect version found on %s", tc.in) } f1 := reflect.ValueOf(tc.f) f2 := reflect.ValueOf(c.function) if f1 != f2 { t.Errorf("Wrong constraint found for %s", tc.in) } } } func TestConstraintCheck(t *testing.T) { tests := []struct { constraint string version string check bool }{ {"= 2.0", "1.2.3", false}, {"= 2.0", "2.0.0", true}, {"4.1", "4.1.0", true}, {"!=4.1", "4.1.0", false}, {"!=4.1", "5.1.0", true}, {">1.1", "4.1.0", true}, {">1.1", "1.1.0", false}, {"<1.1", "0.1.0", true}, {"<1.1", "1.1.0", false}, {"<1.1", "1.1.1", false}, {">=1.1", "4.1.0", true}, {">=1.1", "1.1.0", true}, {">=1.1", "0.0.9", false}, {"<=1.1", "0.1.0", true}, {"<=1.1", "1.1.0", true}, {"<=1.1", "1.1.1", false}, } for _, tc := range tests { c, err := parseConstraint(tc.constraint) if err != nil { t.Errorf("err: %s", err) continue } v, err := NewVersion(tc.version) if err != nil { t.Errorf("err: %s", err) continue } a := c.check(v) if a != tc.check { t.Errorf("Constraint '%s' failing", tc.constraint) } } } func TestNewConstraint(t *testing.T) { tests := []struct { input string ors int count int err bool }{ {">= 1.1", 1, 1, false}, {"2.0", 1, 1, false}, {">= bar", 0, 0, true}, {">= 1.2.3, < 2.0", 1, 2, false}, {">= 1.2.3, < 2.0 || => 3.0, < 4", 2, 2, false}, // The 3-4 should be broken into 2 by the range rewriting {"3-4 || => 3.0, < 4", 2, 2, false}, } for _, tc := range tests { v, err := NewConstraint(tc.input) if tc.err && err == nil { t.Errorf("expected but did not get error for: %s", tc.input) continue } else if !tc.err && err != nil { t.Errorf("unexpectederror for input %s: %s", tc.input, err) continue } if tc.err { continue } l := len(v.constraints) if tc.ors != l { t.Errorf("Expected %s to have %d ORs but got %d", tc.input, tc.ors, l) } l = len(v.constraints[0]) if tc.count != l { t.Errorf("Expected %s to have %d constraints but got %d", tc.input, tc.count, l) } } } func TestConstraintsCheck(t *testing.T) { tests := []struct { constraint string version string check bool }{ {"*", "1.2.3", true}, {"~0.0.0", "1.2.3", true}, {"= 2.0", "1.2.3", false}, {"= 2.0", "2.0.0", true}, {"4.1", "4.1.0", true}, {"4.1.x", "4.1.3", true}, {"1.x", "1.4", true}, {"!=4.1", "4.1.0", false}, {"!=4.1", "5.1.0", true}, {"!=4.x", "5.1.0", true}, {"!=4.x", "4.1.0", false}, {"!=4.1.x", "4.2.0", true}, {"!=4.2.x", "4.2.3", false}, {">1.1", "4.1.0", true}, {">1.1", "1.1.0", false}, {"<1.1", "0.1.0", true}, {"<1.1", "1.1.0", false}, {"<1.1", "1.1.1", false}, {"<1.x", "1.1.1", true}, {"<1.x", "2.1.1", false}, {"<1.1.x", "1.2.1", false}, {"<1.1.x", "1.1.500", true}, {"<1.2.x", "1.1.1", true}, {">=1.1", "4.1.0", true}, {">=1.1", "1.1.0", true}, {">=1.1", "0.0.9", false}, {"<=1.1", "0.1.0", true}, {"<=1.1", "1.1.0", true}, {"<=1.x", "1.1.0", true}, {"<=2.x", "3.1.0", false}, {"<=1.1", "1.1.1", false}, {"<=1.1.x", "1.2.500", false}, {">1.1, <2", "1.1.1", true}, {">1.1, <3", "4.3.2", false}, {">=1.1, <2, !=1.2.3", "1.2.3", false}, {">=1.1, <2, !=1.2.3 || > 3", "3.1.2", true}, {">=1.1, <2, !=1.2.3 || >= 3", "3.0.0", true}, {">=1.1, <2, !=1.2.3 || > 3", "3.0.0", false}, {">=1.1, <2, !=1.2.3 || > 3", "1.2.3", false}, {"1.1 - 2", "1.1.1", true}, {"1.1-3", "4.3.2", false}, {"^1.1", "1.1.1", true}, {"^1.1", "4.3.2", false}, {"^1.x", "1.1.1", true}, {"^2.x", "1.1.1", false}, {"^1.x", "2.1.1", false}, {"~*", "2.1.1", true}, {"~1.x", "2.1.1", false}, {"~1.x", "1.3.5", true}, {"~1.x", "1.4", true}, {"~1.1", "1.1.1", true}, {"~1.2.3", "1.2.5", true}, {"~1.2.3", "1.2.2", false}, {"~1.2.3", "1.3.2", false}, {"~1.1", "1.2.3", false}, {"~1.3", "2.4.5", false}, } for _, tc := range tests { c, err := NewConstraint(tc.constraint) if err != nil { t.Errorf("err: %s", err) continue } v, err := NewVersion(tc.version) if err != nil { t.Errorf("err: %s", err) continue } a := c.Check(v) if a != tc.check { t.Errorf("Constraint '%s' failing with '%s'", tc.constraint, tc.version) } } } func TestRewriteRange(t *testing.T) { tests := []struct { c string nc string }{ {"2-3", ">= 2, <= 3"}, {"2-3, 2-3", ">= 2, <= 3,>= 2, <= 3"}, {"2-3, 4.0.0-5.1", ">= 2, <= 3,>= 4.0.0, <= 5.1"}, } for _, tc := range tests { o := rewriteRange(tc.c) if o != tc.nc { t.Errorf("Range %s rewritten incorrectly as '%s'", tc.c, o) } } } func TestIsX(t *testing.T) { tests := []struct { t string c bool }{ {"A", false}, {"%", false}, {"X", true}, {"x", true}, {"*", true}, } for _, tc := range tests { a := isX(tc.t) if a != tc.c { t.Errorf("Function isX error on %s", tc.t) } } } func TestConstraintsValidate(t *testing.T) { tests := []struct { constraint string version string check bool }{ {"*", "1.2.3", true}, {"~0.0.0", "1.2.3", true}, {"= 2.0", "1.2.3", false}, {"= 2.0", "2.0.0", true}, {"4.1", "4.1.0", true}, {"4.1.x", "4.1.3", true}, {"1.x", "1.4", true}, {"!=4.1", "4.1.0", false}, {"!=4.1", "5.1.0", true}, {"!=4.x", "5.1.0", true}, {"!=4.x", "4.1.0", false}, {"!=4.1.x", "4.2.0", true}, {"!=4.2.x", "4.2.3", false}, {">1.1", "4.1.0", true}, {">1.1", "1.1.0", false}, {"<1.1", "0.1.0", true}, {"<1.1", "1.1.0", false}, {"<1.1", "1.1.1", false}, {"<1.x", "1.1.1", true}, {"<1.x", "2.1.1", false}, {"<1.1.x", "1.2.1", false}, {"<1.1.x", "1.1.500", true}, {"<1.2.x", "1.1.1", true}, {">=1.1", "4.1.0", true}, {">=1.1", "1.1.0", true}, {">=1.1", "0.0.9", false}, {"<=1.1", "0.1.0", true}, {"<=1.1", "1.1.0", true}, {"<=1.x", "1.1.0", true}, {"<=2.x", "3.1.0", false}, {"<=1.1", "1.1.1", false}, {"<=1.1.x", "1.2.500", false}, {">1.1, <2", "1.1.1", true}, {">1.1, <3", "4.3.2", false}, {">=1.1, <2, !=1.2.3", "1.2.3", false}, {">=1.1, <2, !=1.2.3 || > 3", "3.1.2", true}, {">=1.1, <2, !=1.2.3 || >= 3", "3.0.0", true}, {">=1.1, <2, !=1.2.3 || > 3", "3.0.0", false}, {">=1.1, <2, !=1.2.3 || > 3", "1.2.3", false}, {"1.1 - 2", "1.1.1", true}, {"1.1-3", "4.3.2", false}, {"^1.1", "1.1.1", true}, {"^1.1", "4.3.2", false}, {"^1.x", "1.1.1", true}, {"^2.x", "1.1.1", false}, {"^1.x", "2.1.1", false}, {"~*", "2.1.1", true}, {"~1.x", "2.1.1", false}, {"~1.x", "1.3.5", true}, {"~1.x", "1.4", true}, {"~1.1", "1.1.1", true}, {"~1.2.3", "1.2.5", true}, {"~1.2.3", "1.2.2", false}, {"~1.2.3", "1.3.2", false}, {"~1.1", "1.2.3", false}, {"~1.3", "2.4.5", false}, } for _, tc := range tests { c, err := NewConstraint(tc.constraint) if err != nil { t.Errorf("err: %s", err) continue } v, err := NewVersion(tc.version) if err != nil { t.Errorf("err: %s", err) continue } a, msgs := c.Validate(v) if a != tc.check { t.Errorf("Constraint '%s' failing with '%s'", tc.constraint, tc.version) } else if a == false && len(msgs) == 0 { t.Errorf("%q failed with %q but no errors returned", tc.constraint, tc.version) } // if a == false { // for _, m := range msgs { // t.Errorf("%s", m) // } // } } v, err := NewVersion("1.2.3") if err != nil { t.Errorf("err: %s", err) } c, err := NewConstraint("!= 1.2.5, ^2, <= 1.1.x") if err != nil { t.Errorf("err: %s", err) } _, msgs := c.Validate(v) if len(msgs) != 2 { t.Error("Invalid number of validations found") } e := msgs[0].Error() if e != "1.2.3 does not have same major version as 2" { t.Error("Did not get expected message: 1.2.3 does not have same major version as 2") } e = msgs[1].Error() if e != "1.2.3 is greater than 1.1.x" { t.Error("Did not get expected message: 1.2.3 is greater than 1.1.x") } tests2 := []struct { constraint, version, msg string }{ {"= 2.0", "1.2.3", "1.2.3 is not equal to 2.0"}, {"!=4.1", "4.1.0", "4.1.0 is equal to 4.1"}, {"!=4.x", "4.1.0", "4.1.0 is equal to 4.x"}, {"!=4.2.x", "4.2.3", "4.2.3 is equal to 4.2.x"}, {">1.1", "1.1.0", "1.1.0 is less than or equal to 1.1"}, {"<1.1", "1.1.0", "1.1.0 is greater than or equal to 1.1"}, {"<1.1", "1.1.1", "1.1.1 is greater than or equal to 1.1"}, {"<1.x", "2.1.1", "2.1.1 is greater than or equal to 1.x"}, {"<1.1.x", "1.2.1", "1.2.1 is greater than or equal to 1.1.x"}, {">=1.1", "0.0.9", "0.0.9 is less than 1.1"}, {"<=2.x", "3.1.0", "3.1.0 is greater than 2.x"}, {"<=1.1", "1.1.1", "1.1.1 is greater than 1.1"}, {"<=1.1.x", "1.2.500", "1.2.500 is greater than 1.1.x"}, {">1.1, <3", "4.3.2", "4.3.2 is greater than or equal to 3"}, {">=1.1, <2, !=1.2.3", "1.2.3", "1.2.3 is equal to 1.2.3"}, {">=1.1, <2, !=1.2.3 || > 3", "3.0.0", "3.0.0 is greater than or equal to 2"}, {">=1.1, <2, !=1.2.3 || > 3", "1.2.3", "1.2.3 is equal to 1.2.3"}, {"1.1-3", "4.3.2", "4.3.2 is greater than 3"}, {"^1.1", "4.3.2", "4.3.2 does not have same major version as 1.1"}, {"^2.x", "1.1.1", "1.1.1 does not have same major version as 2.x"}, {"^1.x", "2.1.1", "2.1.1 does not have same major version as 1.x"}, {"~1.x", "2.1.1", "2.1.1 does not have same major and minor version as 1.x"}, {"~1.2.3", "1.2.2", "1.2.2 does not have same major and minor version as 1.2.3"}, {"~1.2.3", "1.3.2", "1.3.2 does not have same major and minor version as 1.2.3"}, {"~1.1", "1.2.3", "1.2.3 does not have same major and minor version as 1.1"}, {"~1.3", "2.4.5", "2.4.5 does not have same major and minor version as 1.3"}, } for _, tc := range tests2 { c, err := NewConstraint(tc.constraint) if err != nil { t.Errorf("err: %s", err) continue } v, err := NewVersion(tc.version) if err != nil { t.Errorf("err: %s", err) continue } _, msgs := c.Validate(v) e := msgs[0].Error() if e != tc.msg { t.Errorf("Did not get expected message %q: %s", tc.msg, e) } } } ================================================ FILE: vendor/github.com/Masterminds/semver/doc.go ================================================ /* Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go. Specifically it provides the ability to: * Parse semantic versions * Sort semantic versions * Check if a semantic version fits within a set of constraints * Optionally work with a `v` prefix Parsing Semantic Versions To parse a semantic version use the `NewVersion` function. For example, v, err := semver.NewVersion("1.2.3-beta.1+build345") If there is an error the version wasn't parseable. The version object has methods to get the parts of the version, compare it to other versions, convert the version back into a string, and get the original string. For more details please see the documentation at https://godoc.org/github.com/Masterminds/semver. Sorting Semantic Versions A set of versions can be sorted using the `sort` package from the standard library. For example, raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} vs := make([]*semver.Version, len(raw)) for i, r := range raw { v, err := semver.NewVersion(r) if err != nil { t.Errorf("Error parsing version: %s", err) } vs[i] = v } sort.Sort(semver.Collection(vs)) Checking Version Constraints Checking a version against version constraints is one of the most featureful parts of the package. c, err := semver.NewConstraint(">= 1.2.3") if err != nil { // Handle constraint not being parseable. } v, _ := semver.NewVersion("1.3") if err != nil { // Handle version not being parseable. } // Check if the version meets the constraints. The a variable will be true. a := c.Check(v) Basic Comparisons There are two elements to the comparisons. First, a comparison string is a list of comma separated and comparisons. These are then separated by || separated or comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a comparison that's greater than or equal to 1.2 and less than 3.0.0 or is greater than or equal to 4.2.3. The basic comparisons are: * `=`: equal (aliased to no operator) * `!=`: not equal * `>`: greater than * `<`: less than * `>=`: greater than or equal to * `<=`: less than or equal to Hyphen Range Comparisons There are multiple methods to handle ranges and the first is hyphens ranges. These look like: * `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` * `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` Wildcards In Comparisons The `x`, `X`, and `*` characters can be used as a wildcard character. This works for all comparison operators. When used on the `=` operator it falls back to the pack level comparison (see tilde below). For example, * `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` * `>= 1.2.x` is equivalent to `>= 1.2.0` * `<= 2.x` is equivalent to `<= 3` * `*` is equivalent to `>= 0.0.0` Tilde Range Comparisons (Patch) The tilde (`~`) comparison operator is for patch level ranges when a minor version is specified and major level changes when the minor number is missing. For example, * `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` * `~1` is equivalent to `>= 1, < 2` * `~2.3` is equivalent to `>= 2.3, < 2.4` * `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` * `~1.x` is equivalent to `>= 1, < 2` Caret Range Comparisons (Major) The caret (`^`) comparison operator is for major level changes. This is useful when comparisons of API versions as a major change is API breaking. For example, * `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` * `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` * `^2.3` is equivalent to `>= 2.3, < 3` * `^2.x` is equivalent to `>= 2.0.0, < 3` */ package semver ================================================ FILE: vendor/github.com/Masterminds/semver/version.go ================================================ package semver import ( "bytes" "errors" "fmt" "regexp" "strconv" "strings" ) // The compiled version of the regex created at init() is cached here so it // only needs to be created once. var versionRegex *regexp.Regexp var ( // ErrInvalidSemVer is returned a version is found to be invalid when // being parsed. ErrInvalidSemVer = errors.New("Invalid Semantic Version") ) // SemVerRegex id the regular expression used to parse a semantic version. const SemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` // Version represents a single semantic version. type Version struct { major, minor, patch int64 pre string metadata string original string } func init() { versionRegex = regexp.MustCompile("^" + SemVerRegex + "$") } // NewVersion parses a given version and returns an instance of Version or // an error if unable to parse the version. func NewVersion(v string) (*Version, error) { m := versionRegex.FindStringSubmatch(v) if m == nil { return nil, ErrInvalidSemVer } sv := &Version{ metadata: m[8], pre: m[5], original: v, } var temp int64 temp, err := strconv.ParseInt(m[1], 10, 32) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } sv.major = temp if m[2] != "" { temp, err = strconv.ParseInt(strings.TrimPrefix(m[2], "."), 10, 32) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } sv.minor = temp } else { sv.minor = 0 } if m[3] != "" { temp, err = strconv.ParseInt(strings.TrimPrefix(m[3], "."), 10, 32) if err != nil { return nil, fmt.Errorf("Error parsing version segment: %s", err) } sv.patch = temp } else { sv.patch = 0 } return sv, nil } // String converts a Version object to a string. // Note, if the original version contained a leading v this version will not. // See the Original() method to retrieve the original value. Semantic Versions // don't contain a leading v per the spec. Instead it's optional on // impelementation. func (v *Version) String() string { var buf bytes.Buffer fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) if v.pre != "" { fmt.Fprintf(&buf, "-%s", v.pre) } if v.metadata != "" { fmt.Fprintf(&buf, "+%s", v.metadata) } return buf.String() } // Original returns the original value passed in to be parsed. func (v *Version) Original() string { return v.original } // Major returns the major version. func (v *Version) Major() int64 { return v.major } // Minor returns the minor version. func (v *Version) Minor() int64 { return v.minor } // Patch returns the patch version. func (v *Version) Patch() int64 { return v.patch } // Prerelease returns the pre-release version. func (v *Version) Prerelease() string { return v.pre } // Metadata returns the metadata on the version. func (v *Version) Metadata() string { return v.metadata } // LessThan tests if one version is less than another one. func (v *Version) LessThan(o *Version) bool { return v.Compare(o) < 0 } // GreaterThan tests if one version is greater than another one. func (v *Version) GreaterThan(o *Version) bool { return v.Compare(o) > 0 } // Equal tests if two versions are equal to each other. // Note, versions can be equal with different metadata since metadata // is not considered part of the comparable version. func (v *Version) Equal(o *Version) bool { return v.Compare(o) == 0 } // Compare compares this version to another one. It returns -1, 0, or 1 if // the version smaller, equal, or larger than the other version. // // Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is // lower than the version without a prerelease. func (v *Version) Compare(o *Version) int { // Compare the major, minor, and patch version for differences. If a // difference is found return the comparison. if d := compareSegment(v.Major(), o.Major()); d != 0 { return d } if d := compareSegment(v.Minor(), o.Minor()); d != 0 { return d } if d := compareSegment(v.Patch(), o.Patch()); d != 0 { return d } // At this point the major, minor, and patch versions are the same. ps := v.pre po := o.Prerelease() if ps == "" && po == "" { return 0 } if ps == "" { return 1 } if po == "" { return -1 } return comparePrerelease(ps, po) } func compareSegment(v, o int64) int { if v < o { return -1 } if v > o { return 1 } return 0 } func comparePrerelease(v, o string) int { // split the prelease versions by their part. The separator, per the spec, // is a . sparts := strings.Split(v, ".") oparts := strings.Split(o, ".") // Find the longer length of the parts to know how many loop iterations to // go through. slen := len(sparts) olen := len(oparts) l := slen if olen > slen { l = olen } // Iterate over each part of the prereleases to compare the differences. for i := 0; i < l; i++ { // Since the lentgh of the parts can be different we need to create // a placeholder. This is to avoid out of bounds issues. stemp := "" if i < slen { stemp = sparts[i] } otemp := "" if i < olen { otemp = oparts[i] } d := comparePrePart(stemp, otemp) if d != 0 { return d } } // Reaching here means two versions are of equal value but have different // metadata (the part following a +). They are not identical in string form // but the version comparison finds them to be equal. return 0 } func comparePrePart(s, o string) int { // Fastpath if they are equal if s == o { return 0 } // When s or o are empty we can use the other in an attempt to determine // the response. if o == "" { _, n := strconv.ParseInt(s, 10, 64) if n != nil { return -1 } return 1 } if s == "" { _, n := strconv.ParseInt(o, 10, 64) if n != nil { return 1 } return -1 } if s > o { return 1 } return -1 } ================================================ FILE: vendor/github.com/Masterminds/semver/version_test.go ================================================ package semver import ( "testing" ) func TestNewVersion(t *testing.T) { tests := []struct { version string err bool }{ {"1.2.3", false}, {"v1.2.3", false}, {"1.0", false}, {"v1.0", false}, {"1", false}, {"v1", false}, {"1.2.beta", true}, {"v1.2.beta", true}, {"foo", true}, {"1.2-5", false}, {"v1.2-5", false}, {"1.2-beta.5", false}, {"v1.2-beta.5", false}, {"\n1.2", true}, {"\nv1.2", true}, {"1.2.0-x.Y.0+metadata", false}, {"v1.2.0-x.Y.0+metadata", false}, {"1.2.0-x.Y.0+metadata-width-hypen", false}, {"v1.2.0-x.Y.0+metadata-width-hypen", false}, {"1.2.3-rc1-with-hypen", false}, {"v1.2.3-rc1-with-hypen", false}, {"1.2.3.4", true}, {"v1.2.3.4", true}, } for _, tc := range tests { _, err := NewVersion(tc.version) if tc.err && err == nil { t.Fatalf("expected error for version: %s", tc.version) } else if !tc.err && err != nil { t.Fatalf("error for version %s: %s", tc.version, err) } } } func TestOriginal(t *testing.T) { tests := []string{ "1.2.3", "v1.2.3", "1.0", "v1.0", "1", "v1", "1.2-5", "v1.2-5", "1.2-beta.5", "v1.2-beta.5", "1.2.0-x.Y.0+metadata", "v1.2.0-x.Y.0+metadata", "1.2.0-x.Y.0+metadata-width-hypen", "v1.2.0-x.Y.0+metadata-width-hypen", "1.2.3-rc1-with-hypen", "v1.2.3-rc1-with-hypen", } for _, tc := range tests { v, err := NewVersion(tc) if err != nil { t.Errorf("Error parsing version %s", tc) } o := v.Original() if o != tc { t.Errorf("Error retrieving originl. Expected '%s' but got '%s'", tc, v) } } } func TestParts(t *testing.T) { v, err := NewVersion("1.2.3-beta.1+build.123") if err != nil { t.Error("Error parsing version 1.2.3-beta.1+build.123") } if v.Major() != 1 { t.Error("Major() returning wrong value") } if v.Minor() != 2 { t.Error("Minor() returning wrong value") } if v.Patch() != 3 { t.Error("Patch() returning wrong value") } if v.Prerelease() != "beta.1" { t.Error("Prerelease() returning wrong value") } if v.Metadata() != "build.123" { t.Error("Metadata() returning wrong value") } } func TestString(t *testing.T) { tests := []struct { version string expected string }{ {"1.2.3", "1.2.3"}, {"v1.2.3", "1.2.3"}, {"1.0", "1.0.0"}, {"v1.0", "1.0.0"}, {"1", "1.0.0"}, {"v1", "1.0.0"}, {"1.2-5", "1.2.0-5"}, {"v1.2-5", "1.2.0-5"}, {"1.2-beta.5", "1.2.0-beta.5"}, {"v1.2-beta.5", "1.2.0-beta.5"}, {"1.2.0-x.Y.0+metadata", "1.2.0-x.Y.0+metadata"}, {"v1.2.0-x.Y.0+metadata", "1.2.0-x.Y.0+metadata"}, {"1.2.0-x.Y.0+metadata-width-hypen", "1.2.0-x.Y.0+metadata-width-hypen"}, {"v1.2.0-x.Y.0+metadata-width-hypen", "1.2.0-x.Y.0+metadata-width-hypen"}, {"1.2.3-rc1-with-hypen", "1.2.3-rc1-with-hypen"}, {"v1.2.3-rc1-with-hypen", "1.2.3-rc1-with-hypen"}, } for _, tc := range tests { v, err := NewVersion(tc.version) if err != nil { t.Errorf("Error parsing version %s", tc) } s := v.String() if s != tc.expected { t.Errorf("Error generating string. Expected '%s' but got '%s'", tc.expected, s) } } } func TestCompare(t *testing.T) { tests := []struct { v1 string v2 string expected int }{ {"1.2.3", "1.5.1", -1}, {"2.2.3", "1.5.1", 1}, {"2.2.3", "2.2.2", 1}, {"3.2-beta", "3.2-beta", 0}, {"1.3", "1.1.4", 1}, {"4.2", "4.2-beta", 1}, {"4.2-beta", "4.2", -1}, {"4.2-alpha", "4.2-beta", -1}, {"4.2-alpha", "4.2-alpha", 0}, {"4.2-beta.2", "4.2-beta.1", 1}, {"4.2-beta2", "4.2-beta1", 1}, {"4.2-beta", "4.2-beta.2", -1}, {"4.2-beta", "4.2-beta.foo", 1}, {"4.2-beta.2", "4.2-beta", 1}, {"4.2-beta.foo", "4.2-beta", -1}, {"1.2+bar", "1.2+baz", 0}, } for _, tc := range tests { v1, err := NewVersion(tc.v1) if err != nil { t.Errorf("Error parsing version: %s", err) } v2, err := NewVersion(tc.v2) if err != nil { t.Errorf("Error parsing version: %s", err) } a := v1.Compare(v2) e := tc.expected if a != e { t.Errorf( "Comparison of '%s' and '%s' failed. Expected '%d', got '%d'", tc.v1, tc.v2, e, a, ) } } } func TestLessThan(t *testing.T) { tests := []struct { v1 string v2 string expected bool }{ {"1.2.3", "1.5.1", true}, {"2.2.3", "1.5.1", false}, {"3.2-beta", "3.2-beta", false}, } for _, tc := range tests { v1, err := NewVersion(tc.v1) if err != nil { t.Errorf("Error parsing version: %s", err) } v2, err := NewVersion(tc.v2) if err != nil { t.Errorf("Error parsing version: %s", err) } a := v1.LessThan(v2) e := tc.expected if a != e { t.Errorf( "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", tc.v1, tc.v2, e, a, ) } } } func TestGreaterThan(t *testing.T) { tests := []struct { v1 string v2 string expected bool }{ {"1.2.3", "1.5.1", false}, {"2.2.3", "1.5.1", true}, {"3.2-beta", "3.2-beta", false}, } for _, tc := range tests { v1, err := NewVersion(tc.v1) if err != nil { t.Errorf("Error parsing version: %s", err) } v2, err := NewVersion(tc.v2) if err != nil { t.Errorf("Error parsing version: %s", err) } a := v1.GreaterThan(v2) e := tc.expected if a != e { t.Errorf( "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", tc.v1, tc.v2, e, a, ) } } } func TestEqual(t *testing.T) { tests := []struct { v1 string v2 string expected bool }{ {"1.2.3", "1.5.1", false}, {"2.2.3", "1.5.1", false}, {"3.2-beta", "3.2-beta", true}, {"3.2-beta+foo", "3.2-beta+bar", true}, } for _, tc := range tests { v1, err := NewVersion(tc.v1) if err != nil { t.Errorf("Error parsing version: %s", err) } v2, err := NewVersion(tc.v2) if err != nil { t.Errorf("Error parsing version: %s", err) } a := v1.Equal(v2) e := tc.expected if a != e { t.Errorf( "Comparison of '%s' and '%s' failed. Expected '%t', got '%t'", tc.v1, tc.v2, e, a, ) } } } ================================================ FILE: vendor/github.com/Masterminds/vcs/.gitignore ================================================ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof ================================================ FILE: vendor/github.com/Masterminds/vcs/.travis.yml ================================================ language: go go: - 1.3 - 1.4 - 1.5 - 1.6 - tip # Setting sudo access to false will let Travis CI use containers rather than # VMs to run the tests. For more details see: # - http://docs.travis-ci.com/user/workers/container-based-infrastructure/ # - http://docs.travis-ci.com/user/workers/standard-infrastructure/ sudo: false notifications: irc: "irc.freenode.net#masterminds" ================================================ FILE: vendor/github.com/Masterminds/vcs/CHANGELOG.md ================================================ # 1.5.1 (2016-03-23) - Fixing bug parsing some Git commit dates. # 1.5.0 (2016-03-22) - Add Travis CI testing for Go 1.6. - Issue #17: Add CommitInfo method allowing for a common way to get commit metadata from all VCS. - Autodetect types that have git@ or hg@ users. - Autodetect git+ssh, bzr+ssh, git, and svn+ssh scheme urls. - On Bitbucket for ssh style URLs retrieve the type from the URL. This allows for private repo type detection. - Issue #14: Autodetect ssh/scp style urls (thanks chonthu). # 1.4.1 (2016-03-07) - Fixes #16: some windows situations are unable to create parent directory. # 1.4.0 (2016-02-15) - Adding support for IBM JazzHub. # 1.3.1 (2016-01-27) - Issue #12: Failed to checkout Bzr repo when parent directory didn't exist (thanks cyrilleverrier). # 1.3.0 (2015-11-09) - Issue #9: Added Date method to get the date/time of latest commit (thanks kamilchm). # 1.2.0 (2015-10-29) - Adding IsDirty method to detect a checkout with uncommitted changes. # 1.1.4 (2015-10-28) - Fixed #8: Git IsReference not detecting branches that have not been checked out yet. # 1.1.3 (2015-10-21) - Fixing issue where there are multiple go-import statements for go redirects # 1.1.2 (2015-10-20) - Fixes #7: hg not checking out code when Get is called # 1.1.1 (2015-10-20) - Issue #6: Allow VCS commands to be run concurrently. # 1.1.0 (2015-10-19) - #5: Added output of failed command to returned errors. # 1.0.0 (2015-10-06) - Initial release. ================================================ FILE: vendor/github.com/Masterminds/vcs/LICENSE.txt ================================================ The Masterminds Copyright (C) 2014-2015, Matt Butcher and Matt Farina 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. ================================================ FILE: vendor/github.com/Masterminds/vcs/README.md ================================================ # VCS Repository Management for Go Manage repos in varying version control systems with ease through a common interface. [![Build Status](https://travis-ci.org/Masterminds/vcs.svg)](https://travis-ci.org/Masterminds/vcs) [![GoDoc](https://godoc.org/github.com/Masterminds/vcs?status.png)](https://godoc.org/github.com/Masterminds/vcs) [![Go Report Card](http://goreportcard.com/badge/Masterminds/vcs)](http://goreportcard.com/report/Masterminds/vcs) ## Quick Usage Quick usage: remote := "https://github.com/Masterminds/vcs" local, _ := ioutil.TempDir("", "go-vcs") repo, err := NewRepo(remote, local) In this case `NewRepo` will detect the VCS is Git and return a `GitRepo`. All of the repos implement the `Repo` interface with a common set of features between them. ## Supported VCS Git, SVN, Bazaar (Bzr), and Mercurial (Hg) are currently supported. They each have their own type (e.g., `GitRepo`) that follow a simple naming pattern. Each type implements the `Repo` interface and has a constructor (e.g., `NewGitRepo`). The constructors have the same signature as `NewRepo`. ## Features - Clone or checkout a repository depending on the version control system. - Pull updates to a repository. - Get the currently checked out commit id. - Checkout a commit id, branch, or tag (depending on the availability in the VCS). - Get a list of tags and branches in the VCS. - Check if a string value is a valid reference within the VCS. - More... For more details see [the documentation](https://godoc.org/github.com/Masterminds/vcs). ## Motivation The package `golang.org/x/tools/go/vcs` provides some valuable functionality for working with packages in repositories in varying source control management systems. That package, while useful and well tested, is designed with a specific purpose in mind. Our uses went beyond the scope of that package. To implement our scope we built a package that went beyond the functionality and scope of `golang.org/x/tools/go/vcs`. ================================================ FILE: vendor/github.com/Masterminds/vcs/bzr.go ================================================ package vcs import ( "os" "os/exec" "path/filepath" "regexp" "strings" "time" ) var bzrDetectURL = regexp.MustCompile("parent branch: (?P.+)\n") // NewBzrRepo creates a new instance of BzrRepo. The remote and local directories // need to be passed in. func NewBzrRepo(remote, local string) (*BzrRepo, error) { ltype, err := DetectVcsFromFS(local) // Found a VCS other than Bzr. Need to report an error. if err == nil && ltype != Bzr { return nil, ErrWrongVCS } r := &BzrRepo{} r.setRemote(remote) r.setLocalPath(local) r.Logger = Logger // With the other VCS we can check if the endpoint locally is different // from the one configured internally. But, with Bzr you can't. For example, // if you do `bzr branch https://launchpad.net/govcstestbzrrepo` and then // use `bzr info` to get the parent branch you'll find it set to // http://bazaar.launchpad.net/~mattfarina/govcstestbzrrepo/trunk/. Notice // the change from https to http and the path chance. // Here we set the remote to be the local one if none is passed in. if err == nil && r.CheckLocal() == true && remote == "" { c := exec.Command("bzr", "info") c.Dir = local c.Env = envForDir(c.Dir) out, err := c.CombinedOutput() if err != nil { return nil, err } m := bzrDetectURL.FindStringSubmatch(string(out)) // If no remote was passed in but one is configured for the locally // checked out Bzr repo use that one. if m[1] != "" { r.setRemote(m[1]) } } return r, nil } // BzrRepo implements the Repo interface for the Bzr source control. type BzrRepo struct { base } // Vcs retrieves the underlying VCS being implemented. func (s BzrRepo) Vcs() Type { return Bzr } // Get is used to perform an initial clone of a repository. func (s *BzrRepo) Get() error { basePath := filepath.Dir(filepath.FromSlash(s.LocalPath())) if _, err := os.Stat(basePath); os.IsNotExist(err) { err = os.MkdirAll(basePath, 0755) if err != nil { return err } } _, err := s.run("bzr", "branch", s.Remote(), s.LocalPath()) return err } // Update performs a Bzr pull and update to an existing checkout. func (s *BzrRepo) Update() error { _, err := s.runFromDir("bzr", "pull") if err != nil { return err } _, err = s.runFromDir("bzr", "update") return err } // UpdateVersion sets the version of a package currently checked out via Bzr. func (s *BzrRepo) UpdateVersion(version string) error { _, err := s.runFromDir("bzr", "update", "-r", version) return err } // Version retrieves the current version. func (s *BzrRepo) Version() (string, error) { out, err := s.runFromDir("bzr", "revno", "--tree") if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } // Date retrieves the date on the latest commit. func (s *BzrRepo) Date() (time.Time, error) { out, err := s.runFromDir("bzr", "version-info", "--custom", "--template={date}") if err != nil { return time.Time{}, err } t, err := time.Parse(longForm, string(out)) if err != nil { return time.Time{}, err } return t, nil } // CheckLocal verifies the local location is a Bzr repo. func (s *BzrRepo) CheckLocal() bool { if _, err := os.Stat(s.LocalPath() + "/.bzr"); err == nil { return true } return false } // Branches returns a list of available branches on the repository. // In Bazaar (Bzr) clones and branches are the same. A different branch will // have a different URL location which we cannot detect from the repo. This // is a little different from other VCS. func (s *BzrRepo) Branches() ([]string, error) { var branches []string return branches, nil } // Tags returns a list of available tags on the repository. func (s *BzrRepo) Tags() ([]string, error) { out, err := s.runFromDir("bzr", "tags") if err != nil { return []string{}, err } tags := s.referenceList(string(out), `(?m-s)^(\S+)`) return tags, nil } // IsReference returns if a string is a reference. A reference can be a // commit id or tag. func (s *BzrRepo) IsReference(r string) bool { _, err := s.runFromDir("bzr", "revno", "-r", r) if err == nil { return true } return false } // IsDirty returns if the checkout has been modified from the checked // out reference. func (s *BzrRepo) IsDirty() bool { out, err := s.runFromDir("bzr", "diff") return err != nil || len(out) != 0 } // CommitInfo retrieves metadata about a commit. func (s *BzrRepo) CommitInfo(id string) (*CommitInfo, error) { r := "-r" + id out, err := s.runFromDir("bzr", "log", r, "--log-format=long") if err != nil { return nil, ErrRevisionUnavailable } ci := &CommitInfo{ Commit: id, } lines := strings.Split(string(out), "\n") const format = "Mon 2006-01-02 15:04:05 -0700" var track int var trackOn bool // Note, bzr does not appear to use i18m. for i, l := range lines { if strings.HasPrefix(l, "committer:") { ci.Author = strings.TrimSpace(strings.TrimPrefix(l, "committer:")) } else if strings.HasPrefix(l, "timestamp:") { ts := strings.TrimSpace(strings.TrimPrefix(l, "timestamp:")) ci.Date, err = time.Parse(format, ts) if err != nil { return nil, err } } else if strings.TrimSpace(l) == "message:" { track = i trackOn = true } else if trackOn && i > track { ci.Message = ci.Message + l } } ci.Message = strings.TrimSpace(ci.Message) // Didn't find the revision if ci.Author == "" { return nil, ErrRevisionUnavailable } return ci, nil } ================================================ FILE: vendor/github.com/Masterminds/vcs/bzr_test.go ================================================ package vcs import ( "io/ioutil" "time" //"log" "os" "testing" ) // Canary test to ensure BzrRepo implements the Repo interface. var _ Repo = &BzrRepo{} // To verify bzr is working we perform integration testing // with a known bzr service. Due to the long time of repeatedly checking out // repos these tests are structured to work together. func TestBzr(t *testing.T) { tempDir, err := ioutil.TempDir("", "go-vcs-bzr-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, err := NewBzrRepo("https://launchpad.net/govcstestbzrrepo", tempDir+"/govcstestbzrrepo") if err != nil { t.Error(err) } if repo.Vcs() != Bzr { t.Error("Bzr is detecting the wrong type") } // Check the basic getters. if repo.Remote() != "https://launchpad.net/govcstestbzrrepo" { t.Error("Remote not set properly") } if repo.LocalPath() != tempDir+"/govcstestbzrrepo" { t.Error("Local disk location not set properly") } //Logger = log.New(os.Stdout, "", log.LstdFlags) // Do an initial clone. err = repo.Get() if err != nil { t.Errorf("Unable to clone Bzr repo. Err was %s", err) } // Verify Bzr repo is a Bzr repo if repo.CheckLocal() == false { t.Error("Problem checking out repo or Bzr CheckLocal is not working") } // Test internal lookup mechanism used outside of Bzr specific functionality. ltype, err := DetectVcsFromFS(tempDir + "/govcstestbzrrepo") if err != nil { t.Error("detectVcsFromFS unable to Bzr repo") } if ltype != Bzr { t.Errorf("detectVcsFromFS detected %s instead of Bzr type", ltype) } // Test NewRepo on existing checkout. This should simply provide a working // instance without error based on looking at the local directory. nrepo, nrerr := NewRepo("https://launchpad.net/govcstestbzrrepo", tempDir+"/govcstestbzrrepo") if nrerr != nil { t.Error(nrerr) } // Verify the right oject is returned. It will check the local repo type. if nrepo.CheckLocal() == false { t.Error("Wrong version returned from NewRepo") } err = repo.UpdateVersion("2") if err != nil { t.Errorf("Unable to update Bzr repo version. Err was %s", err) } // Use Version to verify we are on the right version. v, err := repo.Version() if v != "2" { t.Error("Error checking checked out Bzr version") } if err != nil { t.Error(err) } // Use Date to verify we are on the right commit. d, err := repo.Date() if d.Format(longForm) != "2015-07-31 09:50:42 -0400" { t.Error("Error checking checked out Bzr commit date") } if err != nil { t.Error(err) } // Perform an update. err = repo.Update() if err != nil { t.Error(err) } v, err = repo.Version() if v != "3" { t.Error("Error checking checked out Bzr version") } if err != nil { t.Error(err) } tags, err := repo.Tags() if err != nil { t.Error(err) } if tags[0] != "1.0.0" { t.Error("Bzr tags is not reporting the correct version") } branches, err := repo.Branches() if err != nil { t.Error(err) } if len(branches) != 0 { t.Error("Bzr is incorrectly returning branches") } if repo.IsReference("1.0.0") != true { t.Error("Bzr is reporting a reference is not one") } if repo.IsReference("foo") == true { t.Error("Bzr is reporting a non-existant reference is one") } if repo.IsDirty() == true { t.Error("Bzr incorrectly reporting dirty") } ci, err := repo.CommitInfo("3") if err != nil { t.Error(err) } if ci.Commit != "3" { t.Error("Bzr.CommitInfo wrong commit id") } if ci.Author != "Matt Farina " { t.Error("Bzr.CommitInfo wrong author") } if ci.Message != "Updated Readme with pointer." { t.Error("Bzr.CommitInfo wrong message") } ti, err := time.Parse(time.RFC1123Z, "Fri, 31 Jul 2015 09:51:37 -0400") if err != nil { t.Error(err) } if !ti.Equal(ci.Date) { t.Error("Bzr.CommitInfo wrong date") } _, err = repo.CommitInfo("asdfasdfasdf") if err != ErrRevisionUnavailable { t.Error("Bzr didn't return expected ErrRevisionUnavailable") } } func TestBzrCheckLocal(t *testing.T) { // Verify repo.CheckLocal fails for non-Bzr directories. // TestBzr is already checking on a valid repo tempDir, err := ioutil.TempDir("", "go-vcs-bzr-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, _ := NewBzrRepo("", tempDir) if repo.CheckLocal() == true { t.Error("Bzr CheckLocal does not identify non-Bzr location") } // Test NewRepo when there's no local. This should simply provide a working // instance without error based on looking at the remote localtion. _, nrerr := NewRepo("https://launchpad.net/govcstestbzrrepo", tempDir+"/govcstestbzrrepo") if nrerr != nil { t.Error(nrerr) } } ================================================ FILE: vendor/github.com/Masterminds/vcs/git.go ================================================ package vcs import ( "encoding/xml" "os" "os/exec" "path/filepath" "strings" "time" ) // NewGitRepo creates a new instance of GitRepo. The remote and local directories // need to be passed in. func NewGitRepo(remote, local string) (*GitRepo, error) { ltype, err := DetectVcsFromFS(local) // Found a VCS other than Git. Need to report an error. if err == nil && ltype != Git { return nil, ErrWrongVCS } r := &GitRepo{} r.setRemote(remote) r.setLocalPath(local) r.RemoteLocation = "origin" r.Logger = Logger // Make sure the local Git repo is configured the same as the remote when // A remote value was passed in. if err == nil && r.CheckLocal() == true { c := exec.Command("git", "config", "--get", "remote.origin.url") c.Dir = local c.Env = envForDir(c.Dir) out, err := c.CombinedOutput() if err != nil { return nil, err } localRemote := strings.TrimSpace(string(out)) if remote != "" && localRemote != remote { return nil, ErrWrongRemote } // If no remote was passed in but one is configured for the locally // checked out Git repo use that one. if remote == "" && localRemote != "" { r.setRemote(localRemote) } } return r, nil } // GitRepo implements the Repo interface for the Git source control. type GitRepo struct { base RemoteLocation string } // Vcs retrieves the underlying VCS being implemented. func (s GitRepo) Vcs() Type { return Git } // Get is used to perform an initial clone of a repository. func (s *GitRepo) Get() error { _, err := s.run("git", "clone", s.Remote(), s.LocalPath()) // There are some windows cases where Git cannot create the parent directory, // if it does not already exist, to the location it's trying to create the // repo. Catch that error and try to handle it. if err != nil && s.isUnableToCreateDir(err) { basePath := filepath.Dir(filepath.FromSlash(s.LocalPath())) if _, err := os.Stat(basePath); os.IsNotExist(err) { err = os.MkdirAll(basePath, 0755) if err != nil { return err } _, err = s.run("git", "clone", s.Remote(), s.LocalPath()) return err } } return err } // Update performs an Git fetch and pull to an existing checkout. func (s *GitRepo) Update() error { // Perform a fetch to make sure everything is up to date. _, err := s.runFromDir("git", "fetch", s.RemoteLocation) if err != nil { return err } // When in a detached head state, such as when an individual commit is checked // out do not attempt a pull. It will cause an error. detached, err := isDetachedHead(s.LocalPath()) if err != nil { return err } if detached == true { return nil } _, err = s.runFromDir("git", "pull") return err } // UpdateVersion sets the version of a package currently checked out via Git. func (s *GitRepo) UpdateVersion(version string) error { _, err := s.runFromDir("git", "checkout", version) return err } // Version retrieves the current version. func (s *GitRepo) Version() (string, error) { out, err := s.runFromDir("git", "rev-parse", "HEAD") if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } // Date retrieves the date on the latest commit. func (s *GitRepo) Date() (time.Time, error) { out, err := s.runFromDir("git", "log", "-1", "--date=iso", "--pretty=format:%cd") if err != nil { return time.Time{}, err } t, err := time.Parse(longForm, string(out)) if err != nil { return time.Time{}, err } return t, nil } // Branches returns a list of available branches on the RemoteLocation func (s *GitRepo) Branches() ([]string, error) { out, err := s.runFromDir("git", "show-ref") if err != nil { return []string{}, err } branches := s.referenceList(string(out), `(?m-s)(?:`+s.RemoteLocation+`)/(\S+)$`) return branches, nil } // Tags returns a list of available tags on the RemoteLocation func (s *GitRepo) Tags() ([]string, error) { out, err := s.runFromDir("git", "show-ref") if err != nil { return []string{}, err } tags := s.referenceList(string(out), `(?m-s)(?:tags)/(\S+)$`) return tags, nil } // CheckLocal verifies the local location is a Git repo. func (s *GitRepo) CheckLocal() bool { if _, err := os.Stat(s.LocalPath() + "/.git"); err == nil { return true } return false } // IsReference returns if a string is a reference. A reference can be a // commit id, branch, or tag. func (s *GitRepo) IsReference(r string) bool { _, err := s.runFromDir("git", "rev-parse", "--verify", r) if err == nil { return true } // Some refs will fail rev-parse. For example, a remote branch that has // not been checked out yet. This next step should pickup the other // possible references. _, err = s.runFromDir("git", "show-ref", r) if err == nil { return true } return false } // IsDirty returns if the checkout has been modified from the checked // out reference. func (s *GitRepo) IsDirty() bool { out, err := s.runFromDir("git", "diff") return err != nil || len(out) != 0 } // CommitInfo retrieves metadata about a commit. func (s *GitRepo) CommitInfo(id string) (*CommitInfo, error) { fm := `--pretty=format:"%H%an <%ae>%aD%s"` out, err := s.runFromDir("git", "log", id, fm, "-1") if err != nil { return nil, ErrRevisionUnavailable } cis := struct { Commit string `xml:"commit"` Author string `xml:"author"` Date string `xml:"date"` Message string `xml:"message"` }{} err = xml.Unmarshal(out, &cis) if err != nil { return nil, err } t, err := time.Parse("Mon, _2 Jan 2006 15:04:05 -0700", cis.Date) if err != nil { return nil, err } ci := &CommitInfo{ Commit: cis.Commit, Author: cis.Author, Date: t, Message: cis.Message, } return ci, nil } func isDetachedHead(dir string) (bool, error) { c := exec.Command("git", "status", "-uno") c.Dir = dir c.Env = envForDir(c.Dir) out, err := c.CombinedOutput() if err != nil { return false, err } detached := strings.Contains(string(out), "HEAD detached at") return detached, nil } // In a multi-langual manner check for the Git error that it couldn't create // the directory. func (s *GitRepo) isUnableToCreateDir(err error) bool { msg := err.Error() if strings.HasPrefix(msg, "could not create work tree dir") || strings.HasPrefix(msg, "不能创建工作区目录") || strings.HasPrefix(msg, "no s'ha pogut crear el directori d'arbre de treball") || strings.HasPrefix(msg, "impossible de créer le répertoire de la copie de travail") || strings.HasPrefix(msg, "kunde inte skapa arbetskatalogen") || (strings.HasPrefix(msg, "Konnte Arbeitsverzeichnis") && strings.Contains(msg, "nicht erstellen")) || (strings.HasPrefix(msg, "작업 디렉터리를") && strings.Contains(msg, "만들 수 없습니다")) { return true } return false } ================================================ FILE: vendor/github.com/Masterminds/vcs/git_test.go ================================================ package vcs import ( "io/ioutil" "time" //"log" "os" "testing" ) // Canary test to ensure GitRepo implements the Repo interface. var _ Repo = &GitRepo{} // To verify git is working we perform integration testing // with a known git service. func TestGit(t *testing.T) { tempDir, err := ioutil.TempDir("", "go-vcs-git-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, err := NewGitRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") if err != nil { t.Error(err) } if repo.Vcs() != Git { t.Error("Git is detecting the wrong type") } // Check the basic getters. if repo.Remote() != "https://github.com/Masterminds/VCSTestRepo" { t.Error("Remote not set properly") } if repo.LocalPath() != tempDir+"/VCSTestRepo" { t.Error("Local disk location not set properly") } //Logger = log.New(os.Stdout, "", log.LstdFlags) // Do an initial clone. err = repo.Get() if err != nil { t.Errorf("Unable to clone Git repo. Err was %s", err) } // Verify Git repo is a Git repo if repo.CheckLocal() == false { t.Error("Problem checking out repo or Git CheckLocal is not working") } // Test internal lookup mechanism used outside of Git specific functionality. ltype, err := DetectVcsFromFS(tempDir + "/VCSTestRepo") if err != nil { t.Error("detectVcsFromFS unable to Git repo") } if ltype != Git { t.Errorf("detectVcsFromFS detected %s instead of Git type", ltype) } // Test NewRepo on existing checkout. This should simply provide a working // instance without error based on looking at the local directory. nrepo, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") if nrerr != nil { t.Error(nrerr) } // Verify the right oject is returned. It will check the local repo type. if nrepo.CheckLocal() == false { t.Error("Wrong version returned from NewRepo") } // Perform an update. err = repo.Update() if err != nil { t.Error(err) } // Set the version using the short hash. err = repo.UpdateVersion("806b07b") if err != nil { t.Errorf("Unable to update Git repo version. Err was %s", err) } // Once a ref has been checked out the repo is in a detached head state. // Trying to pull in an update in this state will cause an error. Update // should cleanly handle this. Pulling on a branch (tested elsewhere) and // skipping that here. err = repo.Update() if err != nil { t.Error(err) } // Use Version to verify we are on the right version. v, err := repo.Version() if v != "806b07b08faa21cfbdae93027904f80174679402" { t.Error("Error checking checked out Git version") } if err != nil { t.Error(err) } // Use Date to verify we are on the right commit. d, err := repo.Date() if d.Format(longForm) != "2015-07-29 09:46:39 -0400" { t.Error("Error checking checked out Git commit date") } if err != nil { t.Error(err) } // Verify that we can set the version something other than short hash err = repo.UpdateVersion("master") if err != nil { t.Errorf("Unable to update Git repo version. Err was %s", err) } err = repo.UpdateVersion("806b07b08faa21cfbdae93027904f80174679402") if err != nil { t.Errorf("Unable to update Git repo version. Err was %s", err) } v, err = repo.Version() if v != "806b07b08faa21cfbdae93027904f80174679402" { t.Error("Error checking checked out Git version") } if err != nil { t.Error(err) } tags, err := repo.Tags() if err != nil { t.Error(err) } if tags[0] != "1.0.0" { t.Error("Git tags is not reporting the correct version") } branches, err := repo.Branches() if err != nil { t.Error(err) } // The branches should be HEAD, master, and test. if branches[2] != "test" { t.Error("Git is incorrectly returning branches") } if repo.IsReference("1.0.0") != true { t.Error("Git is reporting a reference is not one") } if repo.IsReference("foo") == true { t.Error("Git is reporting a non-existant reference is one") } if repo.IsDirty() == true { t.Error("Git incorrectly reporting dirty") } ci, err := repo.CommitInfo("806b07b08faa21cfbdae93027904f80174679402") if err != nil { t.Error(err) } if ci.Commit != "806b07b08faa21cfbdae93027904f80174679402" { t.Error("Git.CommitInfo wrong commit id") } if ci.Author != "Matt Farina " { t.Error("Git.CommitInfo wrong author") } if ci.Message != "Update README.md" { t.Error("Git.CommitInfo wrong message") } ti, err := time.Parse(time.RFC1123Z, "Wed, 29 Jul 2015 09:46:39 -0400") if err != nil { t.Error(err) } if !ti.Equal(ci.Date) { t.Error("Git.CommitInfo wrong date") } _, err = repo.CommitInfo("asdfasdfasdf") if err != ErrRevisionUnavailable { t.Error("Git didn't return expected ErrRevisionUnavailable") } } func TestGitCheckLocal(t *testing.T) { // Verify repo.CheckLocal fails for non-Git directories. // TestGit is already checking on a valid repo tempDir, err := ioutil.TempDir("", "go-vcs-git-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, _ := NewGitRepo("", tempDir) if repo.CheckLocal() == true { t.Error("Git CheckLocal does not identify non-Git location") } // Test NewRepo when there's no local. This should simply provide a working // instance without error based on looking at the remote localtion. _, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") if nrerr != nil { t.Error(nrerr) } } ================================================ FILE: vendor/github.com/Masterminds/vcs/hg.go ================================================ package vcs import ( "encoding/xml" "os" "os/exec" "regexp" "strings" "time" ) var hgDetectURL = regexp.MustCompile("default = (?P.+)\n") // NewHgRepo creates a new instance of HgRepo. The remote and local directories // need to be passed in. func NewHgRepo(remote, local string) (*HgRepo, error) { ltype, err := DetectVcsFromFS(local) // Found a VCS other than Hg. Need to report an error. if err == nil && ltype != Hg { return nil, ErrWrongVCS } r := &HgRepo{} r.setRemote(remote) r.setLocalPath(local) r.Logger = Logger // Make sure the local Hg repo is configured the same as the remote when // A remote value was passed in. if err == nil && r.CheckLocal() == true { // An Hg repo was found so test that the URL there matches // the repo passed in here. c := exec.Command("hg", "paths") c.Dir = local c.Env = envForDir(c.Dir) out, err := c.CombinedOutput() if err != nil { return nil, err } m := hgDetectURL.FindStringSubmatch(string(out)) if m[1] != "" && m[1] != remote { return nil, ErrWrongRemote } // If no remote was passed in but one is configured for the locally // checked out Hg repo use that one. if remote == "" && m[1] != "" { r.setRemote(m[1]) } } return r, nil } // HgRepo implements the Repo interface for the Mercurial source control. type HgRepo struct { base } // Vcs retrieves the underlying VCS being implemented. func (s HgRepo) Vcs() Type { return Hg } // Get is used to perform an initial clone of a repository. func (s *HgRepo) Get() error { _, err := s.run("hg", "clone", s.Remote(), s.LocalPath()) return err } // Update performs a Mercurial pull to an existing checkout. func (s *HgRepo) Update() error { _, err := s.runFromDir("hg", "update") return err } // UpdateVersion sets the version of a package currently checked out via Hg. func (s *HgRepo) UpdateVersion(version string) error { _, err := s.runFromDir("hg", "pull") if err != nil { return err } _, err = s.runFromDir("hg", "update", version) return err } // Version retrieves the current version. func (s *HgRepo) Version() (string, error) { out, err := s.runFromDir("hg", "identify") if err != nil { return "", err } parts := strings.SplitN(string(out), " ", 2) sha := parts[0] return strings.TrimSpace(sha), nil } // Date retrieves the date on the latest commit. func (s *HgRepo) Date() (time.Time, error) { version, err := s.Version() if err != nil { return time.Time{}, err } out, err := s.runFromDir("hg", "log", "-r", version, "--template", "{date|isodatesec}") if err != nil { return time.Time{}, err } t, err := time.Parse(longForm, string(out)) if err != nil { return time.Time{}, err } return t, nil } // CheckLocal verifies the local location is a Git repo. func (s *HgRepo) CheckLocal() bool { if _, err := os.Stat(s.LocalPath() + "/.hg"); err == nil { return true } return false } // Branches returns a list of available branches func (s *HgRepo) Branches() ([]string, error) { out, err := s.runFromDir("hg", "branches") if err != nil { return []string{}, err } branches := s.referenceList(string(out), `(?m-s)^(\S+)`) return branches, nil } // Tags returns a list of available tags func (s *HgRepo) Tags() ([]string, error) { out, err := s.runFromDir("hg", "tags") if err != nil { return []string{}, err } tags := s.referenceList(string(out), `(?m-s)^(\S+)`) return tags, nil } // IsReference returns if a string is a reference. A reference can be a // commit id, branch, or tag. func (s *HgRepo) IsReference(r string) bool { _, err := s.runFromDir("hg", "log", "-r", r) if err == nil { return true } return false } // IsDirty returns if the checkout has been modified from the checked // out reference. func (s *HgRepo) IsDirty() bool { out, err := s.runFromDir("hg", "diff") return err != nil || len(out) != 0 } // CommitInfo retrieves metadata about a commit. func (s *HgRepo) CommitInfo(id string) (*CommitInfo, error) { out, err := s.runFromDir("hg", "log", "-r", id, "--style=xml") if err != nil { return nil, ErrRevisionUnavailable } type Author struct { Name string `xml:",chardata"` Email string `xml:"email,attr"` } type Logentry struct { Node string `xml:"node,attr"` Author Author `xml:"author"` Date string `xml:"date"` Msg string `xml:"msg"` } type Log struct { XMLName xml.Name `xml:"log"` Logs []Logentry `xml:"logentry"` } logs := &Log{} err = xml.Unmarshal(out, &logs) if err != nil { return nil, err } if len(logs.Logs) == 0 { return nil, ErrRevisionUnavailable } ci := &CommitInfo{ Commit: logs.Logs[0].Node, Author: logs.Logs[0].Author.Name + " <" + logs.Logs[0].Author.Email + ">", Message: logs.Logs[0].Msg, } if logs.Logs[0].Date != "" { ci.Date, err = time.Parse(time.RFC3339, logs.Logs[0].Date) if err != nil { return nil, err } } return ci, nil } ================================================ FILE: vendor/github.com/Masterminds/vcs/hg_test.go ================================================ package vcs import ( "io/ioutil" "time" //"log" "os" "testing" ) // Canary test to ensure HgRepo implements the Repo interface. var _ Repo = &HgRepo{} // To verify hg is working we perform integration testing // with a known hg service. func TestHg(t *testing.T) { tempDir, err := ioutil.TempDir("", "go-vcs-hg-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, err := NewHgRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir+"/testhgrepo") if err != nil { t.Error(err) } if repo.Vcs() != Hg { t.Error("Hg is detecting the wrong type") } // Check the basic getters. if repo.Remote() != "https://bitbucket.org/mattfarina/testhgrepo" { t.Error("Remote not set properly") } if repo.LocalPath() != tempDir+"/testhgrepo" { t.Error("Local disk location not set properly") } //Logger = log.New(os.Stdout, "", log.LstdFlags) // Do an initial clone. err = repo.Get() if err != nil { t.Errorf("Unable to clone Hg repo. Err was %s", err) } // Verify Hg repo is a Hg repo if repo.CheckLocal() == false { t.Error("Problem checking out repo or Hg CheckLocal is not working") } // Test internal lookup mechanism used outside of Hg specific functionality. ltype, err := DetectVcsFromFS(tempDir + "/testhgrepo") if err != nil { t.Error("detectVcsFromFS unable to Hg repo") } if ltype != Hg { t.Errorf("detectVcsFromFS detected %s instead of Hg type", ltype) } // Test NewRepo on existing checkout. This should simply provide a working // instance without error based on looking at the local directory. nrepo, nrerr := NewRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir+"/testhgrepo") if nrerr != nil { t.Error(nrerr) } // Verify the right oject is returned. It will check the local repo type. if nrepo.CheckLocal() == false { t.Error("Wrong version returned from NewRepo") } // Set the version using the short hash. err = repo.UpdateVersion("a5494ba2177f") if err != nil { t.Errorf("Unable to update Hg repo version. Err was %s", err) } // Use Version to verify we are on the right version. v, err := repo.Version() if v != "a5494ba2177f" { t.Error("Error checking checked out Hg version") } if err != nil { t.Error(err) } // Use Date to verify we are on the right commit. d, err := repo.Date() if err != nil { t.Error(err) } if d.Format(longForm) != "2015-07-30 16:14:08 -0400" { t.Error("Error checking checked out Hg commit date. Got wrong date:", d) } // Perform an update. err = repo.Update() if err != nil { t.Error(err) } v, err = repo.Version() if v != "9c6ccbca73e8" { t.Error("Error checking checked out Hg version") } if err != nil { t.Error(err) } tags, err := repo.Tags() if err != nil { t.Error(err) } if tags[1] != "1.0.0" { t.Error("Hg tags is not reporting the correct version") } branches, err := repo.Branches() if err != nil { t.Error(err) } // The branches should be HEAD, master, and test. if branches[0] != "test" { t.Error("Hg is incorrectly returning branches") } if repo.IsReference("1.0.0") != true { t.Error("Hg is reporting a reference is not one") } if repo.IsReference("test") != true { t.Error("Hg is reporting a reference is not one") } if repo.IsReference("foo") == true { t.Error("Hg is reporting a non-existant reference is one") } if repo.IsDirty() == true { t.Error("Hg incorrectly reporting dirty") } ci, err := repo.CommitInfo("a5494ba2177f") if err != nil { t.Error(err) } if ci.Commit != "a5494ba2177ff9ef26feb3c155dfecc350b1a8ef" { t.Error("Hg.CommitInfo wrong commit id") } if ci.Author != "Matt Farina " { t.Error("Hg.CommitInfo wrong author") } if ci.Message != "A commit" { t.Error("Hg.CommitInfo wrong message") } ti := time.Unix(1438287248, 0) if !ti.Equal(ci.Date) { t.Error("Hg.CommitInfo wrong date") } _, err = repo.CommitInfo("asdfasdfasdf") if err != ErrRevisionUnavailable { t.Error("Hg didn't return expected ErrRevisionUnavailable") } } func TestHgCheckLocal(t *testing.T) { // Verify repo.CheckLocal fails for non-Hg directories. // TestHg is already checking on a valid repo tempDir, err := ioutil.TempDir("", "go-vcs-hg-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, _ := NewHgRepo("", tempDir) if repo.CheckLocal() == true { t.Error("Hg CheckLocal does not identify non-Hg location") } // Test NewRepo when there's no local. This should simply provide a working // instance without error based on looking at the remote localtion. _, nrerr := NewRepo("https://bitbucket.org/mattfarina/testhgrepo", tempDir+"/testhgrepo") if nrerr != nil { t.Error(nrerr) } } ================================================ FILE: vendor/github.com/Masterminds/vcs/repo.go ================================================ // Package vcs provides the ability to work with varying version control systems // (VCS), also known as source control systems (SCM) though the same interface. // // This package includes a function that attempts to detect the repo type from // the remote URL and return the proper type. For example, // // remote := "https://github.com/Masterminds/vcs" // local, _ := ioutil.TempDir("", "go-vcs") // repo, err := NewRepo(remote, local) // // In this case repo will be a GitRepo instance. NewRepo can detect the VCS for // numerous popular VCS and from the URL. For example, a URL ending in .git // that's not from one of the popular VCS will be detected as a Git repo and // the correct type will be returned. // // If you know the repository type and would like to create an instance of a // specific type you can use one of constructors for a type. They are NewGitRepo, // NewSvnRepo, NewBzrRepo, and NewHgRepo. The definition and usage is the same // as NewRepo. // // Once you have an object implementing the Repo interface the operations are // the same no matter which VCS you're using. There are some caveats. For // example, each VCS has its own version formats that need to be respected and // checkout out branches, if a branch is being worked with, is different in // each VCS. package vcs import ( "errors" "fmt" "io/ioutil" "log" "os" "os/exec" "regexp" "strings" "time" ) var ( // ErrWrongVCS is returned when an action is tried on the wrong VCS. ErrWrongVCS = errors.New("Wrong VCS detected") // ErrCannotDetectVCS is returned when VCS cannot be detected from URI string. ErrCannotDetectVCS = errors.New("Cannot detect VCS") // ErrWrongRemote occurs when the passed in remote does not match the VCS // configured endpoint. ErrWrongRemote = errors.New("The Remote does not match the VCS endpoint") // ErrRevisionUnavailable happens when commit revision information is // unavailable. ErrRevisionUnavailable = errors.New("Revision unavailable") ) // Logger is where you can provide a logger, implementing the log.Logger interface, // where verbose output from each VCS will be written. The default logger does // not log data. To log data supply your own logger or change the output location // of the provided logger. var Logger *log.Logger func init() { // Initialize the logger to one that does not actually log anywhere. This is // to be overridden by the package user by setting vcs.Logger to a different // logger. Logger = log.New(ioutil.Discard, "go-vcs", log.LstdFlags) } const longForm = "2006-01-02 15:04:05 -0700" // Type describes the type of VCS type Type string // VCS types const ( NoVCS Type = "" Git Type = "git" Svn Type = "svn" Bzr Type = "bzr" Hg Type = "hg" ) // Repo provides an interface to work with repositories using different source // control systems such as Git, Bzr, Mercurial, and SVN. For implementations // of this interface see BzrRepo, GitRepo, HgRepo, and SvnRepo. type Repo interface { // Vcs retrieves the underlying VCS being implemented. Vcs() Type // Remote retrieves the remote location for a repo. Remote() string // LocalPath retrieves the local file system location for a repo. LocalPath() string // Get is used to perform an initial clone/checkout of a repository. Get() error // Update performs an update to an existing checkout of a repository. Update() error // UpdateVersion sets the version of a package of a repository. UpdateVersion(string) error // Version retrieves the current version. Version() (string, error) // Date retrieves the date on the latest commit. Date() (time.Time, error) // CheckLocal verifies the local location is of the correct VCS type CheckLocal() bool // Branches returns a list of available branches on the repository. Branches() ([]string, error) // Tags returns a list of available tags on the repository. Tags() ([]string, error) // TODO: Provide a consistent manner to get reference information across // multiple VCS. // IsReference returns if a string is a reference. A reference can be a // commit id, branch, or tag. IsReference(string) bool // IsDirty returns if the checkout has been modified from the checked // out reference. IsDirty() bool // CommitInfo retrieves metadata about a commit. CommitInfo(string) (*CommitInfo, error) } // NewRepo returns a Repo based on trying to detect the source control from the // remote and local locations. The appropriate implementation will be returned // or an ErrCannotDetectVCS if the VCS type cannot be detected. // Note, this function may make calls to the Internet to determind help determine // the VCS. func NewRepo(remote, local string) (Repo, error) { vtype, remote, err := detectVcsFromRemote(remote) // From the remote URL the VCS could not be detected. See if the local // repo contains enough information to figure out the VCS. The reason the // local repo is not checked first is because of the potential for VCS type // switches which will be detected in each of the type builders. if err == ErrCannotDetectVCS { vtype, err = DetectVcsFromFS(local) } if err != nil { return nil, err } switch vtype { case Git: return NewGitRepo(remote, local) case Svn: return NewSvnRepo(remote, local) case Hg: return NewHgRepo(remote, local) case Bzr: return NewBzrRepo(remote, local) } // Should never fall through to here but just in case. return nil, ErrCannotDetectVCS } // CommitInfo contains metadata about a commit. type CommitInfo struct { // The commit id Commit string // Who authored the commit Author string // Date of the commit Date time.Time // Commit message Message string } type base struct { remote, local string Logger *log.Logger } func (b *base) log(v interface{}) { b.Logger.Printf("%s", v) } // Remote retrieves the remote location for a repo. func (b *base) Remote() string { return b.remote } // LocalPath retrieves the local file system location for a repo. func (b *base) LocalPath() string { return b.local } func (b *base) setRemote(remote string) { b.remote = remote } func (b *base) setLocalPath(local string) { b.local = local } func (b base) run(cmd string, args ...string) ([]byte, error) { out, err := exec.Command(cmd, args...).CombinedOutput() b.log(out) if err != nil { err = fmt.Errorf("%s: %s", out, err) } return out, err } func (b *base) runFromDir(cmd string, args ...string) ([]byte, error) { c := exec.Command(cmd, args...) c.Dir = b.local c.Env = envForDir(c.Dir) out, err := c.CombinedOutput() return out, err } func (b *base) referenceList(c, r string) []string { var out []string re := regexp.MustCompile(r) for _, m := range re.FindAllStringSubmatch(c, -1) { out = append(out, m[1]) } return out } func envForDir(dir string) []string { env := os.Environ() return mergeEnvLists([]string{"PWD=" + dir}, env) } func mergeEnvLists(in, out []string) []string { NextVar: for _, inkv := range in { k := strings.SplitAfterN(inkv, "=", 2)[0] for i, outkv := range out { if strings.HasPrefix(outkv, k) { out[i] = inkv continue NextVar } } out = append(out, inkv) } return out } ================================================ FILE: vendor/github.com/Masterminds/vcs/repo_test.go ================================================ package vcs import ( "fmt" "io/ioutil" "os" "testing" ) func ExampleNewRepo() { remote := "https://github.com/Masterminds/vcs" local, _ := ioutil.TempDir("", "go-vcs") repo, _ := NewRepo(remote, local) // Returns: instance of GitRepo repo.Vcs() // Returns Git as this is a Git repo err := repo.Get() // Pulls down a repo, or a checkout in the case of SVN, and returns an // error if that didn't happen successfully. if err != nil { fmt.Println(err) } err = repo.UpdateVersion("master") // Checkouts out a specific version. In most cases this can be a commit id, // branch, or tag. if err != nil { fmt.Println(err) } } func TestTypeSwitch(t *testing.T) { // To test repo type switching we checkout as SVN and then try to get it as // a git repo afterwards. tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, err := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+"/VCSTestRepo") if err != nil { t.Error(err) } err = repo.Get() if err != nil { t.Errorf("Unable to checkout SVN repo for repo switching tests. Err was %s", err) } _, err = NewRepo("https://github.com/Masterminds/VCSTestRepo", tempDir+"/VCSTestRepo") if err != ErrWrongVCS { t.Errorf("Not detecting repo switch from SVN to Git") } } ================================================ FILE: vendor/github.com/Masterminds/vcs/svn.go ================================================ package vcs import ( "encoding/xml" "os" "os/exec" "regexp" "strings" "time" ) var svnDetectURL = regexp.MustCompile("URL: (?P.+)\n") // NewSvnRepo creates a new instance of SvnRepo. The remote and local directories // need to be passed in. The remote location should include the branch for SVN. // For example, if the package is https://github.com/Masterminds/cookoo/ the remote // should be https://github.com/Masterminds/cookoo/trunk for the trunk branch. func NewSvnRepo(remote, local string) (*SvnRepo, error) { ltype, err := DetectVcsFromFS(local) // Found a VCS other than Svn. Need to report an error. if err == nil && ltype != Svn { return nil, ErrWrongVCS } r := &SvnRepo{} r.setRemote(remote) r.setLocalPath(local) r.Logger = Logger // Make sure the local SVN repo is configured the same as the remote when // A remote value was passed in. if err == nil && r.CheckLocal() == true { // An SVN repo was found so test that the URL there matches // the repo passed in here. out, err := exec.Command("svn", "info", local).CombinedOutput() if err != nil { return nil, err } m := svnDetectURL.FindStringSubmatch(string(out)) if m[1] != "" && m[1] != remote { return nil, ErrWrongRemote } // If no remote was passed in but one is configured for the locally // checked out Svn repo use that one. if remote == "" && m[1] != "" { r.setRemote(m[1]) } } return r, nil } // SvnRepo implements the Repo interface for the Svn source control. type SvnRepo struct { base } // Vcs retrieves the underlying VCS being implemented. func (s SvnRepo) Vcs() Type { return Svn } // Get is used to perform an initial checkout of a repository. // Note, because SVN isn't distributed this is a checkout without // a clone. func (s *SvnRepo) Get() error { _, err := s.run("svn", "checkout", s.Remote(), s.LocalPath()) return err } // Update performs an SVN update to an existing checkout. func (s *SvnRepo) Update() error { _, err := s.runFromDir("svn", "update") return err } // UpdateVersion sets the version of a package currently checked out via SVN. func (s *SvnRepo) UpdateVersion(version string) error { _, err := s.runFromDir("svn", "update", "-r", version) return err } // Version retrieves the current version. func (s *SvnRepo) Version() (string, error) { out, err := s.runFromDir("svnversion", ".") s.log(out) if err != nil { return "", err } return strings.TrimSpace(string(out)), nil } // Date retrieves the date on the latest commit. func (s *SvnRepo) Date() (time.Time, error) { version, err := s.Version() if err != nil { return time.Time{}, err } out, err := s.runFromDir("svn", "pget", "svn:date", "--revprop", "-r", version) if err != nil { return time.Time{}, err } const longForm = "2006-01-02T15:04:05.000000Z\n" t, err := time.Parse(longForm, string(out)) if err != nil { return time.Time{}, err } return t, nil } // CheckLocal verifies the local location is an SVN repo. func (s *SvnRepo) CheckLocal() bool { if _, err := os.Stat(s.LocalPath() + "/.svn"); err == nil { return true } return false } // Tags returns []string{} as there are no formal tags in SVN. Tags are a // convention in SVN. They are typically implemented as a copy of the trunk and // placed in the /tags/[tag name] directory. Since this is a convention the // expectation is to checkout a tag the correct subdirectory will be used // as the path. For more information see: // http://svnbook.red-bean.com/en/1.7/svn.branchmerge.tags.html func (s *SvnRepo) Tags() ([]string, error) { return []string{}, nil } // Branches returns []string{} as there are no formal branches in SVN. Branches // are a convention. They are typically implemented as a copy of the trunk and // placed in the /branches/[tag name] directory. Since this is a convention the // expectation is to checkout a branch the correct subdirectory will be used // as the path. For more information see: // http://svnbook.red-bean.com/en/1.7/svn.branchmerge.using.html func (s *SvnRepo) Branches() ([]string, error) { return []string{}, nil } // IsReference returns if a string is a reference. A reference is a commit id. // Branches and tags are part of the path. func (s *SvnRepo) IsReference(r string) bool { out, err := s.runFromDir("svn", "log", "-r", r) // This is a complete hack. There must be a better way to do this. Pull // requests welcome. When the reference isn't real you get a line of // repeated - followed by an empty line. If the reference is real there // is commit information in addition to those. So, we look for responses // over 2 lines long. lines := strings.Split(string(out), "\n") if err == nil && len(lines) > 2 { return true } return false } // IsDirty returns if the checkout has been modified from the checked // out reference. func (s *SvnRepo) IsDirty() bool { out, err := s.runFromDir("svn", "diff") return err != nil || len(out) != 0 } // CommitInfo retrieves metadata about a commit. func (s *SvnRepo) CommitInfo(id string) (*CommitInfo, error) { out, err := s.runFromDir("svn", "log", "-r", id, "--xml") if err != nil { return nil, err } type Logentry struct { Author string `xml:"author"` Date string `xml:"date"` Msg string `xml:"msg"` } type Log struct { XMLName xml.Name `xml:"log"` Logs []Logentry `xml:"logentry"` } logs := &Log{} err = xml.Unmarshal(out, &logs) if err != nil { return nil, err } if len(logs.Logs) == 0 { return nil, ErrRevisionUnavailable } ci := &CommitInfo{ Commit: id, Author: logs.Logs[0].Author, Message: logs.Logs[0].Msg, } if len(logs.Logs[0].Date) > 0 { ci.Date, err = time.Parse(time.RFC3339Nano, logs.Logs[0].Date) if err != nil { return nil, err } } return ci, nil } ================================================ FILE: vendor/github.com/Masterminds/vcs/svn_test.go ================================================ package vcs import ( "io/ioutil" "time" //"log" "os" "testing" ) // To verify svn is working we perform integration testing // with a known svn service. // Canary test to ensure SvnRepo implements the Repo interface. var _ Repo = &SvnRepo{} func TestSvn(t *testing.T) { tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, err := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+"/VCSTestRepo") if err != nil { t.Error(err) } if repo.Vcs() != Svn { t.Error("Svn is detecting the wrong type") } // Check the basic getters. if repo.Remote() != "https://github.com/Masterminds/VCSTestRepo/trunk" { t.Error("Remote not set properly") } if repo.LocalPath() != tempDir+"/VCSTestRepo" { t.Error("Local disk location not set properly") } //Logger = log.New(os.Stdout, "", log.LstdFlags) // Do an initial checkout. err = repo.Get() if err != nil { t.Errorf("Unable to checkout SVN repo. Err was %s", err) } // Verify SVN repo is a SVN repo if repo.CheckLocal() == false { t.Error("Problem checking out repo or SVN CheckLocal is not working") } // Verify an incorrect remote is caught when NewSvnRepo is used on an existing location _, nrerr := NewSvnRepo("https://github.com/Masterminds/VCSTestRepo/unknownbranch", tempDir+"/VCSTestRepo") if nrerr != ErrWrongRemote { t.Error("ErrWrongRemote was not triggered for SVN") } // Test internal lookup mechanism used outside of Hg specific functionality. ltype, err := DetectVcsFromFS(tempDir + "/VCSTestRepo") if err != nil { t.Error("detectVcsFromFS unable to Svn repo") } if ltype != Svn { t.Errorf("detectVcsFromFS detected %s instead of Svn type", ltype) } // Commenting out auto-detection tests for SVN. NewRepo automatically detects // GitHub to be a Git repo and that's an issue for this test. Need an // SVN host that can autodetect from before using this test again. // // Test NewRepo on existing checkout. This should simply provide a working // instance without error based on looking at the local directory. // nrepo, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+"/VCSTestRepo") // if nrerr != nil { // t.Error(nrerr) // } // // Verify the right oject is returned. It will check the local repo type. // if nrepo.CheckLocal() == false { // t.Error("Wrong version returned from NewRepo") // } // Update the version to a previous version. err = repo.UpdateVersion("r2") if err != nil { t.Errorf("Unable to update SVN repo version. Err was %s", err) } // Use Version to verify we are on the right version. v, err := repo.Version() if v != "2" { t.Error("Error checking checked SVN out version") } if err != nil { t.Error(err) } // Perform an update which should take up back to the latest version. err = repo.Update() if err != nil { t.Error(err) } // Make sure we are on a newer version because of the update. v, err = repo.Version() if v == "2" { t.Error("Error with version. Still on old version. Update failed") } if err != nil { t.Error(err) } // Use Date to verify we are on the right commit. d, err := repo.Date() if d.Format(longForm) != "2015-07-29 13:47:03 +0000" { t.Error("Error checking checked out Svn commit date") } if err != nil { t.Error(err) } tags, err := repo.Tags() if err != nil { t.Error(err) } if len(tags) != 0 { t.Error("Svn is incorrectly returning tags") } branches, err := repo.Branches() if err != nil { t.Error(err) } if len(branches) != 0 { t.Error("Svn is incorrectly returning branches") } if repo.IsReference("r4") != true { t.Error("Svn is reporting a reference is not one") } if repo.IsReference("55") == true { t.Error("Svn is reporting a non-existant reference is one") } if repo.IsDirty() == true { t.Error("Svn incorrectly reporting dirty") } ci, err := repo.CommitInfo("2") if err != nil { t.Error(err) } if ci.Commit != "2" { t.Error("Svn.CommitInfo wrong commit id") } if ci.Author != "matt.farina" { t.Error("Svn.CommitInfo wrong author") } if ci.Message != "Update README.md" { t.Error("Svn.CommitInfo wrong message") } ti, err := time.Parse(time.RFC3339Nano, "2015-07-29T13:46:20.000000Z") if err != nil { t.Error(err) } if !ti.Equal(ci.Date) { t.Error("Svn.CommitInfo wrong date") } _, err = repo.CommitInfo("555555555") if err != ErrRevisionUnavailable { t.Error("Svn didn't return expected ErrRevisionUnavailable") } } func TestSvnCheckLocal(t *testing.T) { // Verify repo.CheckLocal fails for non-SVN directories. // TestSvn is already checking on a valid repo tempDir, err := ioutil.TempDir("", "go-vcs-svn-tests") if err != nil { t.Error(err) } defer func() { err = os.RemoveAll(tempDir) if err != nil { t.Error(err) } }() repo, _ := NewSvnRepo("", tempDir) if repo.CheckLocal() == true { t.Error("SVN CheckLocal does not identify non-SVN location") } // Test NewRepo when there's no local. This should simply provide a working // instance without error based on looking at the remote localtion. _, nrerr := NewRepo("https://github.com/Masterminds/VCSTestRepo/trunk", tempDir+"/VCSTestRepo") if nrerr != nil { t.Error(nrerr) } } ================================================ FILE: vendor/github.com/Masterminds/vcs/vcs_local_lookup.go ================================================ package vcs import ( "os" ) // DetectVcsFromFS detects the type from the local path. // Is there a better way to do this? func DetectVcsFromFS(vcsPath string) (Type, error) { // When the local directory to the package doesn't exist // it's not yet downloaded so we can't detect the type // locally. if _, err := os.Stat(vcsPath); os.IsNotExist(err) { return "", ErrCannotDetectVCS } seperator := string(os.PathSeparator) // Walk through each of the different VCS types to see if // one can be detected. Do this is order of guessed popularity. if _, err := os.Stat(vcsPath + seperator + ".git"); err == nil { return Git, nil } if _, err := os.Stat(vcsPath + seperator + ".svn"); err == nil { return Svn, nil } if _, err := os.Stat(vcsPath + seperator + ".hg"); err == nil { return Hg, nil } if _, err := os.Stat(vcsPath + seperator + ".bzr"); err == nil { return Bzr, nil } // If one was not already detected than we default to not finding it. return "", ErrCannotDetectVCS } ================================================ FILE: vendor/github.com/Masterminds/vcs/vcs_remote_lookup.go ================================================ package vcs import ( "encoding/json" "encoding/xml" "fmt" "io" "io/ioutil" "net/http" "net/url" "regexp" "strings" ) type vcsInfo struct { host string pattern string vcs Type addCheck func(m map[string]string, u *url.URL) (Type, error) regex *regexp.Regexp } // scpSyntaxRe matches the SCP-like addresses used by Git to access // repositories by SSH. var scpSyntaxRe = regexp.MustCompile(`^([a-zA-Z0-9_]+)@([a-zA-Z0-9._-]+):(.*)$`) var vcsList = []*vcsInfo{ { host: "github.com", vcs: Git, pattern: `^(github\.com[/|:][A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`, }, { host: "bitbucket.org", pattern: `^(bitbucket\.org/(?P[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`, addCheck: checkBitbucket, }, { host: "launchpad.net", pattern: `^(launchpad\.net/(([A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)?|~[A-Za-z0-9_.\-]+/(\+junk|[A-Za-z0-9_.\-]+)/[A-Za-z0-9_.\-]+))(/[A-Za-z0-9_.\-]+)*$`, vcs: Bzr, }, { host: "git.launchpad.net", vcs: Git, pattern: `^(git\.launchpad\.net/(([A-Za-z0-9_.\-]+)|~[A-Za-z0-9_.\-]+/(\+git|[A-Za-z0-9_.\-]+)/[A-Za-z0-9_.\-]+))$`, }, { host: "hub.jazz.net", vcs: Git, pattern: `^(hub\.jazz\.net/git/[a-z0-9]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`, }, { host: "go.googlesource.com", vcs: Git, pattern: `^(go\.googlesource\.com/[A-Za-z0-9_.\-]+/?)$`, }, // TODO: Once Google Code becomes fully deprecated this can be removed. { host: "code.google.com", addCheck: checkGoogle, pattern: `^(code\.google\.com/[pr]/(?P[a-z0-9\-]+)(\.(?P[a-z0-9\-]+))?)(/[A-Za-z0-9_.\-]+)*$`, }, // Alternative Google setup. This is the previous structure but it still works... until Google Code goes away. { addCheck: checkURL, pattern: `^([a-z0-9_\-.]+)\.googlecode\.com/(?Pgit|hg|svn)(/.*)?$`, }, // If none of the previous detect the type they will fall to this looking for the type in a generic sense // by the extension to the path. { addCheck: checkURL, pattern: `\.(?Pgit|hg|svn|bzr)$`, }, } func init() { // Precompile the regular expressions used to check VCS locations. for _, v := range vcsList { v.regex = regexp.MustCompile(v.pattern) } } // This function is really a hack around Go redirects rather than around // something VCS related. Should this be moved to the glide project or a // helper function? func detectVcsFromRemote(vcsURL string) (Type, string, error) { t, e := detectVcsFromURL(vcsURL) if e == nil { return t, vcsURL, nil } // Need to test for vanity or paths like golang.org/x/ // TODO: Test for 3xx redirect codes and handle appropriately. // Pages like https://golang.org/x/net provide an html document with // meta tags containing a location to work with. The go tool uses // a meta tag with the name go-import which is what we use here. // godoc.org also has one call go-source that we do not need to use. // The value of go-import is in the form "prefix vcs repo". The prefix // should match the vcsURL and the repo is a location that can be // checked out. Note, to get the html document you you need to add // ?go-get=1 to the url. u, err := url.Parse(vcsURL) if err != nil { return NoVCS, "", err } if u.RawQuery == "" { u.RawQuery = "go-get=1" } else { u.RawQuery = u.RawQuery + "+go-get=1" } checkURL := u.String() resp, err := http.Get(checkURL) if err != nil { return NoVCS, "", ErrCannotDetectVCS } defer resp.Body.Close() t, nu, err := parseImportFromBody(u, resp.Body) if err != nil { return NoVCS, "", err } else if t == "" || nu == "" { return NoVCS, "", ErrCannotDetectVCS } return t, nu, nil } // From a remote vcs url attempt to detect the VCS. func detectVcsFromURL(vcsURL string) (Type, error) { var u *url.URL var err error if m := scpSyntaxRe.FindStringSubmatch(vcsURL); m != nil { // Match SCP-like syntax and convert it to a URL. // Eg, "git@github.com:user/repo" becomes // "ssh://git@github.com/user/repo". u = &url.URL{ Scheme: "ssh", User: url.User(m[1]), Host: m[2], Path: "/" + m[3], } } else { u, err = url.Parse(vcsURL) if err != nil { return "", err } } if u.Host == "" { return "", ErrCannotDetectVCS } // Try to detect from the scheme switch u.Scheme { case "git+ssh": return Git, nil case "git": return Git, nil case "bzr+ssh": return Bzr, nil case "svn+ssh": return Svn, nil } // Try to detect from known hosts, such as Github for _, v := range vcsList { if v.host != "" && v.host != u.Host { continue } // Make sure the pattern matches for an actual repo location. For example, // we should fail if the VCS listed is github.com/masterminds as that's // not actually a repo. uCheck := u.Host + u.Path m := v.regex.FindStringSubmatch(uCheck) if m == nil { if v.host != "" { return "", ErrCannotDetectVCS } continue } // If we are here the host matches. If the host has a singular // VCS type, such as Github, we can return the type right away. if v.vcs != "" { return v.vcs, nil } // Run additional checks to determine try and determine the repo // for the matched service. info := make(map[string]string) for i, name := range v.regex.SubexpNames() { if name != "" { info[name] = m[i] } } t, err := v.addCheck(info, u) if err != nil { return "", ErrCannotDetectVCS } return t, nil } // Attempt to ascertain from the username passed in. if u.User != nil { un := u.User.Username() if un == "git" { return Git, nil } else if un == "hg" { return Hg, nil } } // Unable to determine the vcs from the url. return "", ErrCannotDetectVCS } // Figure out the type for Bitbucket by the passed in information // or via the public API. func checkBitbucket(i map[string]string, ul *url.URL) (Type, error) { // Fast path for ssh urls where we may not even be able to // anonymously get details from the API. if ul.User != nil { un := ul.User.Username() if un == "git" { return Git, nil } else if un == "hg" { return Hg, nil } } // The part of the response we care about. var response struct { SCM Type `json:"scm"` } u := expand(i, "https://api.bitbucket.org/1.0/repositories/{name}") data, err := get(u) if err != nil { return "", err } if err := json.Unmarshal(data, &response); err != nil { return "", fmt.Errorf("Decoding error %s: %v", u, err) } return response.SCM, nil } // Google supports Git, Hg, and Svn. The SVN style is only // supported through their legacy setup at .googlecode.com. // I wonder if anyone is actually using SVN support. func checkGoogle(i map[string]string, u *url.URL) (Type, error) { // To figure out which of the VCS types is used in Google Code you need // to parse a web page and find it. Ugh. I mean... ugh. var hack = regexp.MustCompile(`id="checkoutcmd">(hg|git|svn)`) d, err := get(expand(i, "https://code.google.com/p/{project}/source/checkout?repo={repo}")) if err != nil { return "", err } if m := hack.FindSubmatch(d); m != nil { if vcs := string(m[1]); vcs != "" { if vcs == "svn" { // While Google supports SVN it can only be used with the legacy // urls of .googlecode.com. I considered creating a new // error for this problem but Google Code is going away and there // is support for the legacy structure. return "", ErrCannotDetectVCS } return Type(vcs), nil } } return "", ErrCannotDetectVCS } // Expect a type key on i with the exact type detected from the regex. func checkURL(i map[string]string, u *url.URL) (Type, error) { return Type(i["type"]), nil } func get(url string) ([]byte, error) { resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != 200 { return nil, fmt.Errorf("%s: %s", url, resp.Status) } b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("%s: %v", url, err) } return b, nil } func expand(match map[string]string, s string) string { for k, v := range match { s = strings.Replace(s, "{"+k+"}", v, -1) } return s } func parseImportFromBody(ur *url.URL, r io.ReadCloser) (tp Type, u string, err error) { d := xml.NewDecoder(r) d.CharsetReader = charsetReader d.Strict = false var t xml.Token for { t, err = d.Token() if err != nil { if err == io.EOF { // When the end is reached it could not detect a VCS if it // got here. err = ErrCannotDetectVCS } return } if e, ok := t.(xml.StartElement); ok && strings.EqualFold(e.Name.Local, "body") { return } if e, ok := t.(xml.EndElement); ok && strings.EqualFold(e.Name.Local, "head") { return } e, ok := t.(xml.StartElement) if !ok || !strings.EqualFold(e.Name.Local, "meta") { continue } if attrValue(e.Attr, "name") != "go-import" { continue } if f := strings.Fields(attrValue(e.Attr, "content")); len(f) == 3 { // If the prefix supplied by the remote system isn't a prefix to the // url we're fetching continue to look for other imports. // This will work for exact matches and prefixes. For example, // golang.org/x/net as a prefix will match for golang.org/x/net and // golang.org/x/net/context. vcsURL := ur.Host + ur.Path if !strings.HasPrefix(vcsURL, f[0]) { continue } else { switch Type(f[1]) { case Git: tp = Git case Svn: tp = Svn case Bzr: tp = Bzr case Hg: tp = Hg } u = f[2] return } } } } func charsetReader(charset string, input io.Reader) (io.Reader, error) { switch strings.ToLower(charset) { case "ascii": return input, nil default: return nil, fmt.Errorf("can't decode XML document using charset %q", charset) } } func attrValue(attrs []xml.Attr, name string) string { for _, a := range attrs { if strings.EqualFold(a.Name.Local, name) { return a.Value } } return "" } ================================================ FILE: vendor/github.com/Masterminds/vcs/vcs_remote_lookup_test.go ================================================ package vcs import ( "testing" ) func TestVCSLookup(t *testing.T) { // TODO: Expand to make sure it detected the right vcs. urlList := map[string]struct { work bool t Type }{ "https://github.com/masterminds": {work: false, t: Git}, "https://github.com/Masterminds/VCSTestRepo": {work: true, t: Git}, "https://bitbucket.org/mattfarina/testhgrepo": {work: true, t: Hg}, "https://launchpad.net/govcstestbzrrepo/trunk": {work: true, t: Bzr}, "https://launchpad.net/~mattfarina/+junk/mygovcstestbzrrepo": {work: true, t: Bzr}, "https://launchpad.net/~mattfarina/+junk/mygovcstestbzrrepo/trunk": {work: true, t: Bzr}, "https://git.launchpad.net/govcstestgitrepo": {work: true, t: Git}, "https://git.launchpad.net/~mattfarina/+git/mygovcstestgitrepo": {work: true, t: Git}, "https://hub.jazz.net/git/user1/pkgname": {work: true, t: Git}, "https://hub.jazz.net/git/user1/pkgname/subpkg/subpkg/subpkg": {work: true, t: Git}, "https://hubs.jazz.net/git/user1/pkgname": {work: false, t: Git}, "http://farbtastic.googlecode.com/svn/": {work: true, t: Svn}, "http://farbtastic.googlecode.com/svn/trunk": {work: true, t: Svn}, "https://example.com/foo/bar.git": {work: true, t: Git}, "https://example.com/foo/bar.svn": {work: true, t: Svn}, "https://example.com/foo/bar/baz.bzr": {work: true, t: Bzr}, "https://example.com/foo/bar/baz.hg": {work: true, t: Hg}, "https://gopkg.in/tomb.v1": {work: true, t: Git}, "https://golang.org/x/net": {work: true, t: Git}, "https://speter.net/go/exp/math/dec/inf": {work: true, t: Git}, "git@github.com:Masterminds/vcs.git": {work: true, t: Git}, "git@example.com:foo.git": {work: true, t: Git}, "ssh://hg@bitbucket.org/mattfarina/testhgrepo": {work: true, t: Hg}, "git@bitbucket.org:mattfarina/glide-bitbucket-example.git": {work: true, t: Git}, "git+ssh://example.com/foo/bar": {work: true, t: Git}, "git://example.com/foo/bar": {work: true, t: Git}, "bzr+ssh://example.com/foo/bar": {work: true, t: Bzr}, "svn+ssh://example.com/foo/bar": {work: true, t: Svn}, "git@example.com:foo/bar": {work: true, t: Git}, "hg@example.com:foo/bar": {work: true, t: Hg}, } for u, c := range urlList { ty, _, err := detectVcsFromRemote(u) if err == nil && c.work == false { t.Errorf("Error detecting VCS from URL(%s)", u) } if err == ErrCannotDetectVCS && c.work == true { t.Errorf("Error detecting VCS from URL(%s)", u) } if err != nil && c.work == true { t.Errorf("Error detecting VCS from URL(%s): %s", u, err) } if c.work == true && ty != c.t { t.Errorf("Incorrect VCS type returned(%s)", u) } } } ================================================ FILE: vendor/github.com/beorn7/perks/.gitignore ================================================ *.test *.prof ================================================ FILE: vendor/github.com/beorn7/perks/README.md ================================================ # 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. ================================================ FILE: vendor/github.com/beorn7/perks/histogram/bench_test.go ================================================ package histogram import ( "math/rand" "testing" ) func BenchmarkInsert10Bins(b *testing.B) { b.StopTimer() h := New(10) b.StartTimer() for i := 0; i < b.N; i++ { f := rand.ExpFloat64() h.Insert(f) } } func BenchmarkInsert100Bins(b *testing.B) { b.StopTimer() h := New(100) b.StartTimer() for i := 0; i < b.N; i++ { f := rand.ExpFloat64() h.Insert(f) } } ================================================ FILE: vendor/github.com/beorn7/perks/histogram/histogram.go ================================================ // Package histogram provides a Go implementation of BigML's histogram package // for Clojure/Java. It is currently experimental. package histogram import ( "container/heap" "math" "sort" ) type Bin struct { Count int Sum float64 } func (b *Bin) Update(x *Bin) { b.Count += x.Count b.Sum += x.Sum } func (b *Bin) Mean() float64 { return b.Sum / float64(b.Count) } type Bins []*Bin func (bs Bins) Len() int { return len(bs) } func (bs Bins) Less(i, j int) bool { return bs[i].Mean() < bs[j].Mean() } func (bs Bins) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] } func (bs *Bins) Push(x interface{}) { *bs = append(*bs, x.(*Bin)) } func (bs *Bins) Pop() interface{} { return bs.remove(len(*bs) - 1) } func (bs *Bins) remove(n int) *Bin { if n < 0 || len(*bs) < n { return nil } x := (*bs)[n] *bs = append((*bs)[:n], (*bs)[n+1:]...) return x } type Histogram struct { res *reservoir } func New(maxBins int) *Histogram { return &Histogram{res: newReservoir(maxBins)} } func (h *Histogram) Insert(f float64) { h.res.insert(&Bin{1, f}) h.res.compress() } func (h *Histogram) Bins() Bins { return h.res.bins } type reservoir struct { n int maxBins int bins Bins } func newReservoir(maxBins int) *reservoir { return &reservoir{maxBins: maxBins} } func (r *reservoir) insert(bin *Bin) { r.n += bin.Count i := sort.Search(len(r.bins), func(i int) bool { return r.bins[i].Mean() >= bin.Mean() }) if i < 0 || i == r.bins.Len() { // TODO(blake): Maybe use an .insert(i, bin) instead of // performing the extra work of a heap.Push. heap.Push(&r.bins, bin) return } r.bins[i].Update(bin) } func (r *reservoir) compress() { for r.bins.Len() > r.maxBins { minGapIndex := -1 minGap := math.MaxFloat64 for i := 0; i < r.bins.Len()-1; i++ { gap := gapWeight(r.bins[i], r.bins[i+1]) if minGap > gap { minGap = gap minGapIndex = i } } prev := r.bins[minGapIndex] next := r.bins.remove(minGapIndex + 1) prev.Update(next) } } func gapWeight(prev, next *Bin) float64 { return next.Mean() - prev.Mean() } ================================================ FILE: vendor/github.com/beorn7/perks/histogram/histogram_test.go ================================================ package histogram import ( "math/rand" "testing" ) func TestHistogram(t *testing.T) { const numPoints = 1e6 const maxBins = 3 h := New(maxBins) for i := 0; i < numPoints; i++ { f := rand.ExpFloat64() h.Insert(f) } bins := h.Bins() if g := len(bins); g > maxBins { t.Fatalf("got %d bins, wanted <= %d", g, maxBins) } for _, b := range bins { t.Logf("%+v", b) } if g := count(h.Bins()); g != numPoints { t.Fatalf("binned %d points, wanted %d", g, numPoints) } } func count(bins Bins) int { binCounts := 0 for _, b := range bins { binCounts += b.Count } return binCounts } ================================================ FILE: vendor/github.com/beorn7/perks/quantile/bench_test.go ================================================ package quantile import ( "testing" ) func BenchmarkInsertTargeted(b *testing.B) { b.ReportAllocs() s := NewTargeted(Targets) b.ResetTimer() for i := float64(0); i < float64(b.N); i++ { s.Insert(i) } } func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) { s := NewTargeted(TargetsSmallEpsilon) b.ResetTimer() for i := float64(0); i < float64(b.N); i++ { s.Insert(i) } } func BenchmarkInsertBiased(b *testing.B) { s := NewLowBiased(0.01) b.ResetTimer() for i := float64(0); i < float64(b.N); i++ { s.Insert(i) } } func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) { s := NewLowBiased(0.0001) b.ResetTimer() for i := float64(0); i < float64(b.N); i++ { s.Insert(i) } } func BenchmarkQuery(b *testing.B) { s := NewTargeted(Targets) for i := float64(0); i < 1e6; i++ { s.Insert(i) } b.ResetTimer() n := float64(b.N) for i := float64(0); i < n; i++ { s.Query(i / n) } } func BenchmarkQuerySmallEpsilon(b *testing.B) { s := NewTargeted(TargetsSmallEpsilon) for i := float64(0); i < 1e6; i++ { s.Insert(i) } b.ResetTimer() n := float64(b.N) for i := float64(0); i < n; i++ { s.Query(i / n) } } ================================================ FILE: vendor/github.com/beorn7/perks/quantile/example_test.go ================================================ // +build go1.1 package quantile_test import ( "bufio" "fmt" "log" "os" "strconv" "time" "github.com/beorn7/perks/quantile" ) func Example_simple() { ch := make(chan float64) go sendFloats(ch) // Compute the 50th, 90th, and 99th percentile. q := quantile.NewTargeted(map[float64]float64{ 0.50: 0.005, 0.90: 0.001, 0.99: 0.0001, }) for v := range ch { q.Insert(v) } fmt.Println("perc50:", q.Query(0.50)) fmt.Println("perc90:", q.Query(0.90)) fmt.Println("perc99:", q.Query(0.99)) fmt.Println("count:", q.Count()) // Output: // perc50: 5 // perc90: 16 // perc99: 223 // count: 2388 } func Example_mergeMultipleStreams() { // Scenario: // We have multiple database shards. On each shard, there is a process // collecting query response times from the database logs and inserting // them into a Stream (created via NewTargeted(0.90)), much like the // Simple example. These processes expose a network interface for us to // ask them to serialize and send us the results of their // Stream.Samples so we may Merge and Query them. // // NOTES: // * These sample sets are small, allowing us to get them // across the network much faster than sending the entire list of data // points. // // * For this to work correctly, we must supply the same quantiles // a priori the process collecting the samples supplied to NewTargeted, // even if we do not plan to query them all here. ch := make(chan quantile.Samples) getDBQuerySamples(ch) q := quantile.NewTargeted(map[float64]float64{0.90: 0.001}) for samples := range ch { q.Merge(samples) } fmt.Println("perc90:", q.Query(0.90)) } func Example_window() { // Scenario: We want the 90th, 95th, and 99th percentiles for each // minute. ch := make(chan float64) go sendStreamValues(ch) tick := time.NewTicker(1 * time.Minute) q := quantile.NewTargeted(map[float64]float64{ 0.90: 0.001, 0.95: 0.0005, 0.99: 0.0001, }) for { select { case t := <-tick.C: flushToDB(t, q.Samples()) q.Reset() case v := <-ch: q.Insert(v) } } } func sendStreamValues(ch chan float64) { // Use your imagination } func flushToDB(t time.Time, samples quantile.Samples) { // Use your imagination } // This is a stub for the above example. In reality this would hit the remote // servers via http or something like it. func getDBQuerySamples(ch chan quantile.Samples) {} func sendFloats(ch chan<- float64) { f, err := os.Open("exampledata.txt") if err != nil { log.Fatal(err) } sc := bufio.NewScanner(f) for sc.Scan() { b := sc.Bytes() v, err := strconv.ParseFloat(string(b), 64) if err != nil { log.Fatal(err) } ch <- v } if sc.Err() != nil { log.Fatal(sc.Err()) } close(ch) } ================================================ FILE: vendor/github.com/beorn7/perks/quantile/exampledata.txt ================================================ 8 5 26 12 5 235 13 6 28 30 3 3 3 3 5 2 33 7 2 4 7 12 14 5 8 3 10 4 5 3 6 6 209 20 3 10 14 3 4 6 8 5 11 7 3 2 3 3 212 5 222 4 10 10 5 6 3 8 3 10 254 220 2 3 5 24 5 4 222 7 3 3 223 8 15 12 14 14 3 2 2 3 13 3 11 4 4 6 5 7 13 5 3 5 2 5 3 5 2 7 15 17 14 3 6 6 3 17 5 4 7 6 4 4 8 6 8 3 9 3 6 3 4 5 3 3 660 4 6 10 3 6 3 2 5 13 2 4 4 10 4 8 4 3 7 9 9 3 10 37 3 13 4 12 3 6 10 8 5 21 2 3 8 3 2 3 3 4 12 2 4 8 8 4 3 2 20 1 6 32 2 11 6 18 3 8 11 3 212 3 4 2 6 7 12 11 3 2 16 10 6 4 6 3 2 7 3 2 2 2 2 5 6 4 3 10 3 4 6 5 3 4 4 5 6 4 3 4 4 5 7 5 5 3 2 7 2 4 12 4 5 6 2 4 4 8 4 15 13 7 16 5 3 23 5 5 7 3 2 9 8 7 5 8 11 4 10 76 4 47 4 3 2 7 4 2 3 37 10 4 2 20 5 4 4 10 10 4 3 7 23 240 7 13 5 5 3 3 2 5 4 2 8 7 19 2 23 8 7 2 5 3 8 3 8 13 5 5 5 2 3 23 4 9 8 4 3 3 5 220 2 3 4 6 14 3 53 6 2 5 18 6 3 219 6 5 2 5 3 6 5 15 4 3 17 3 2 4 7 2 3 3 4 4 3 2 664 6 3 23 5 5 16 5 8 2 4 2 24 12 3 2 3 5 8 3 5 4 3 14 3 5 8 2 3 7 9 4 2 3 6 8 4 3 4 6 5 3 3 6 3 19 4 4 6 3 6 3 5 22 5 4 4 3 8 11 4 9 7 6 13 4 4 4 6 17 9 3 3 3 4 3 221 5 11 3 4 2 12 6 3 5 7 5 7 4 9 7 14 37 19 217 16 3 5 2 2 7 19 7 6 7 4 24 5 11 4 7 7 9 13 3 4 3 6 28 4 4 5 5 2 5 6 4 4 6 10 5 4 3 2 3 3 6 5 5 4 3 2 3 7 4 6 18 16 8 16 4 5 8 6 9 13 1545 6 215 6 5 6 3 45 31 5 2 2 4 3 3 2 5 4 3 5 7 7 4 5 8 5 4 749 2 31 9 11 2 11 5 4 4 7 9 11 4 5 4 7 3 4 6 2 15 3 4 3 4 3 5 2 13 5 5 3 3 23 4 4 5 7 4 13 2 4 3 4 2 6 2 7 3 5 5 3 29 5 4 4 3 10 2 3 79 16 6 6 7 7 3 5 5 7 4 3 7 9 5 6 5 9 6 3 6 4 17 2 10 9 3 6 2 3 21 22 5 11 4 2 17 2 224 2 14 3 4 4 2 4 4 4 4 5 3 4 4 10 2 6 3 3 5 7 2 7 5 6 3 218 2 2 5 2 6 3 5 222 14 6 33 3 2 5 3 3 3 9 5 3 3 2 7 4 3 4 3 5 6 5 26 4 13 9 7 3 221 3 3 4 4 4 4 2 18 5 3 7 9 6 8 3 10 3 11 9 5 4 17 5 5 6 6 3 2 4 12 17 6 7 218 4 2 4 10 3 5 15 3 9 4 3 3 6 29 3 3 4 5 5 3 8 5 6 6 7 5 3 5 3 29 2 31 5 15 24 16 5 207 4 3 3 2 15 4 4 13 5 5 4 6 10 2 7 8 4 6 20 5 3 4 3 12 12 5 17 7 3 3 3 6 10 3 5 25 80 4 9 3 2 11 3 3 2 3 8 7 5 5 19 5 3 3 12 11 2 6 5 5 5 3 3 3 4 209 14 3 2 5 19 4 4 3 4 14 5 6 4 13 9 7 4 7 10 2 9 5 7 2 8 4 6 5 5 222 8 7 12 5 216 3 4 4 6 3 14 8 7 13 4 3 3 3 3 17 5 4 3 33 6 6 33 7 5 3 8 7 5 2 9 4 2 233 24 7 4 8 10 3 4 15 2 16 3 3 13 12 7 5 4 207 4 2 4 27 15 2 5 2 25 6 5 5 6 13 6 18 6 4 12 225 10 7 5 2 2 11 4 14 21 8 10 3 5 4 232 2 5 5 3 7 17 11 6 6 23 4 6 3 5 4 2 17 3 6 5 8 3 2 2 14 9 4 4 2 5 5 3 7 6 12 6 10 3 6 2 2 19 5 4 4 9 2 4 13 3 5 6 3 6 5 4 9 6 3 5 7 3 6 6 4 3 10 6 3 221 3 5 3 6 4 8 5 3 6 4 4 2 54 5 6 11 3 3 4 4 4 3 7 3 11 11 7 10 6 13 223 213 15 231 7 3 7 228 2 3 4 4 5 6 7 4 13 3 4 5 3 6 4 6 7 2 4 3 4 3 3 6 3 7 3 5 18 5 6 8 10 3 3 3 2 4 2 4 4 5 6 6 4 10 13 3 12 5 12 16 8 4 19 11 2 4 5 6 8 5 6 4 18 10 4 2 216 6 6 6 2 4 12 8 3 11 5 6 14 5 3 13 4 5 4 5 3 28 6 3 7 219 3 9 7 3 10 6 3 4 19 5 7 11 6 15 19 4 13 11 3 7 5 10 2 8 11 2 6 4 6 24 6 3 3 3 3 6 18 4 11 4 2 5 10 8 3 9 5 3 4 5 6 2 5 7 4 4 14 6 4 4 5 5 7 2 4 3 7 3 3 6 4 5 4 4 4 3 3 3 3 8 14 2 3 5 3 2 4 5 3 7 3 3 18 3 4 4 5 7 3 3 3 13 5 4 8 211 5 5 3 5 2 5 4 2 655 6 3 5 11 2 5 3 12 9 15 11 5 12 217 2 6 17 3 3 207 5 5 4 5 9 3 2 8 5 4 3 2 5 12 4 14 5 4 2 13 5 8 4 225 4 3 4 5 4 3 3 6 23 9 2 6 7 233 4 4 6 18 3 4 6 3 4 4 2 3 7 4 13 227 4 3 5 4 2 12 9 17 3 7 14 6 4 5 21 4 8 9 2 9 25 16 3 6 4 7 8 5 2 3 5 4 3 3 5 3 3 3 2 3 19 2 4 3 4 2 3 4 4 2 4 3 3 3 2 6 3 17 5 6 4 3 13 5 3 3 3 4 9 4 2 14 12 4 5 24 4 3 37 12 11 21 3 4 3 13 4 2 3 15 4 11 4 4 3 8 3 4 4 12 8 5 3 3 4 2 220 3 5 223 3 3 3 10 3 15 4 241 9 7 3 6 6 23 4 13 7 3 4 7 4 9 3 3 4 10 5 5 1 5 24 2 4 5 5 6 14 3 8 2 3 5 13 13 3 5 2 3 15 3 4 2 10 4 4 4 5 5 3 5 3 4 7 4 27 3 6 4 15 3 5 6 6 5 4 8 3 9 2 6 3 4 3 7 4 18 3 11 3 3 8 9 7 24 3 219 7 10 4 5 9 12 2 5 4 4 4 3 3 19 5 8 16 8 6 22 3 23 3 242 9 4 3 3 5 7 3 3 5 8 3 7 5 14 8 10 3 4 3 7 4 6 7 4 10 4 3 11 3 7 10 3 13 6 8 12 10 5 7 9 3 4 7 7 10 8 30 9 19 4 3 19 15 4 13 3 215 223 4 7 4 8 17 16 3 7 6 5 5 4 12 3 7 4 4 13 4 5 2 5 6 5 6 6 7 10 18 23 9 3 3 6 5 2 4 2 7 3 3 2 5 5 14 10 224 6 3 4 3 7 5 9 3 6 4 2 5 11 4 3 3 2 8 4 7 4 10 7 3 3 18 18 17 3 3 3 4 5 3 3 4 12 7 3 11 13 5 4 7 13 5 4 11 3 12 3 6 4 4 21 4 6 9 5 3 10 8 4 6 4 4 6 5 4 8 6 4 6 4 4 5 9 6 3 4 2 9 3 18 2 4 3 13 3 6 6 8 7 9 3 2 16 3 4 6 3 2 33 22 14 4 9 12 4 5 6 3 23 9 4 3 5 5 3 4 5 3 5 3 10 4 5 5 8 4 4 6 8 5 4 3 4 6 3 3 3 5 9 12 6 5 9 3 5 3 2 2 2 18 3 2 21 2 5 4 6 4 5 10 3 9 3 2 10 7 3 6 6 4 4 8 12 7 3 7 3 3 9 3 4 5 4 4 5 5 10 15 4 4 14 6 227 3 14 5 216 22 5 4 2 2 6 3 4 2 9 9 4 3 28 13 11 4 5 3 3 2 3 3 5 3 4 3 5 23 26 3 4 5 6 4 6 3 5 5 3 4 3 2 2 2 7 14 3 6 7 17 2 2 15 14 16 4 6 7 13 6 4 5 6 16 3 3 28 3 6 15 3 9 2 4 6 3 3 22 4 12 6 7 2 5 4 10 3 16 6 9 2 5 12 7 5 5 5 5 2 11 9 17 4 3 11 7 3 5 15 4 3 4 211 8 7 5 4 7 6 7 6 3 6 5 6 5 3 4 4 26 4 6 10 4 4 3 2 3 3 4 5 9 3 9 4 4 5 5 8 2 4 2 3 8 4 11 19 5 8 6 3 5 6 12 3 2 4 16 12 3 4 4 8 6 5 6 6 219 8 222 6 16 3 13 19 5 4 3 11 6 10 4 7 7 12 5 3 3 5 6 10 3 8 2 5 4 7 2 4 4 2 12 9 6 4 2 40 2 4 10 4 223 4 2 20 6 7 24 5 4 5 2 20 16 6 5 13 2 3 3 19 3 2 4 5 6 7 11 12 5 6 7 7 3 5 3 5 3 14 3 4 4 2 11 1 7 3 9 6 11 12 5 8 6 221 4 2 12 4 3 15 4 5 226 7 218 7 5 4 5 18 4 5 9 4 4 2 9 18 18 9 5 6 6 3 3 7 3 5 4 4 4 12 3 6 31 5 4 7 3 6 5 6 5 11 2 2 11 11 6 7 5 8 7 10 5 23 7 4 3 5 34 2 5 23 7 3 6 8 4 4 4 2 5 3 8 5 4 8 25 2 3 17 8 3 4 8 7 3 15 6 5 7 21 9 5 6 6 5 3 2 3 10 3 6 3 14 7 4 4 8 7 8 2 6 12 4 213 6 5 21 8 2 5 23 3 11 2 3 6 25 2 3 6 7 6 6 4 4 6 3 17 9 7 6 4 3 10 7 2 3 3 3 11 8 3 7 6 4 14 36 3 4 3 3 22 13 21 4 2 7 4 4 17 15 3 7 11 2 4 7 6 209 6 3 2 2 24 4 9 4 3 3 3 29 2 2 4 3 3 5 4 6 3 3 2 4 ================================================ FILE: vendor/github.com/beorn7/perks/quantile/stream.go ================================================ // 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(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 } ================================================ FILE: vendor/github.com/beorn7/perks/quantile/stream_test.go ================================================ package quantile import ( "math" "math/rand" "sort" "testing" ) var ( Targets = map[float64]float64{ 0.01: 0.001, 0.10: 0.01, 0.50: 0.05, 0.90: 0.01, 0.99: 0.001, } TargetsSmallEpsilon = map[float64]float64{ 0.01: 0.0001, 0.10: 0.001, 0.50: 0.005, 0.90: 0.001, 0.99: 0.0001, } LowQuantiles = []float64{0.01, 0.1, 0.5} HighQuantiles = []float64{0.99, 0.9, 0.5} ) const RelativeEpsilon = 0.01 func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) { sort.Float64s(a) for quantile, epsilon := range Targets { n := float64(len(a)) k := int(quantile * n) lower := int((quantile - epsilon) * n) if lower < 1 { lower = 1 } upper := int(math.Ceil((quantile + epsilon) * n)) if upper > len(a) { upper = len(a) } w, min, max := a[k-1], a[lower-1], a[upper-1] if g := s.Query(quantile); g < min || g > max { t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g) } } } func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { sort.Float64s(a) for _, qu := range LowQuantiles { n := float64(len(a)) k := int(qu * n) lowerRank := int((1 - RelativeEpsilon) * qu * n) upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n)) w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] if g := s.Query(qu); g < min || g > max { t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) } } } func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) { sort.Float64s(a) for _, qu := range HighQuantiles { n := float64(len(a)) k := int(qu * n) lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n) upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n)) w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1] if g := s.Query(qu); g < min || g > max { t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g) } } } func populateStream(s *Stream) []float64 { a := make([]float64, 0, 1e5+100) for i := 0; i < cap(a); i++ { v := rand.NormFloat64() // Add 5% asymmetric outliers. if i%20 == 0 { v = v*v + 1 } s.Insert(v) a = append(a, v) } return a } func TestTargetedQuery(t *testing.T) { rand.Seed(42) s := NewTargeted(Targets) a := populateStream(s) verifyPercsWithAbsoluteEpsilon(t, a, s) } func TestLowBiasedQuery(t *testing.T) { rand.Seed(42) s := NewLowBiased(RelativeEpsilon) a := populateStream(s) verifyLowPercsWithRelativeEpsilon(t, a, s) } func TestHighBiasedQuery(t *testing.T) { rand.Seed(42) s := NewHighBiased(RelativeEpsilon) a := populateStream(s) verifyHighPercsWithRelativeEpsilon(t, a, s) } // BrokenTestTargetedMerge is broken, see Merge doc comment. func BrokenTestTargetedMerge(t *testing.T) { rand.Seed(42) s1 := NewTargeted(Targets) s2 := NewTargeted(Targets) a := populateStream(s1) a = append(a, populateStream(s2)...) s1.Merge(s2.Samples()) verifyPercsWithAbsoluteEpsilon(t, a, s1) } // BrokenTestLowBiasedMerge is broken, see Merge doc comment. func BrokenTestLowBiasedMerge(t *testing.T) { rand.Seed(42) s1 := NewLowBiased(RelativeEpsilon) s2 := NewLowBiased(RelativeEpsilon) a := populateStream(s1) a = append(a, populateStream(s2)...) s1.Merge(s2.Samples()) verifyLowPercsWithRelativeEpsilon(t, a, s2) } // BrokenTestHighBiasedMerge is broken, see Merge doc comment. func BrokenTestHighBiasedMerge(t *testing.T) { rand.Seed(42) s1 := NewHighBiased(RelativeEpsilon) s2 := NewHighBiased(RelativeEpsilon) a := populateStream(s1) a = append(a, populateStream(s2)...) s1.Merge(s2.Samples()) verifyHighPercsWithRelativeEpsilon(t, a, s2) } func TestUncompressed(t *testing.T) { q := NewTargeted(Targets) for i := 100; i > 0; i-- { q.Insert(float64(i)) } if g := q.Count(); g != 100 { t.Errorf("want count 100, got %d", g) } // Before compression, Query should have 100% accuracy. for quantile := range Targets { w := quantile * 100 if g := q.Query(quantile); g != w { t.Errorf("want %f, got %f", w, g) } } } func TestUncompressedSamples(t *testing.T) { q := NewTargeted(map[float64]float64{0.99: 0.001}) for i := 1; i <= 100; i++ { q.Insert(float64(i)) } if g := q.Samples().Len(); g != 100 { t.Errorf("want count 100, got %d", g) } } func TestUncompressedOne(t *testing.T) { q := NewTargeted(map[float64]float64{0.99: 0.01}) q.Insert(3.14) if g := q.Query(0.90); g != 3.14 { t.Error("want PI, got", g) } } func TestDefaults(t *testing.T) { if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 { t.Errorf("want 0, got %f", g) } } ================================================ FILE: vendor/github.com/beorn7/perks/topk/topk.go ================================================ package topk import ( "sort" ) // http://www.cs.ucsb.edu/research/tech_reports/reports/2005-23.pdf type Element struct { Value string Count int } type Samples []*Element func (sm Samples) Len() int { return len(sm) } func (sm Samples) Less(i, j int) bool { return sm[i].Count < sm[j].Count } func (sm Samples) Swap(i, j int) { sm[i], sm[j] = sm[j], sm[i] } type Stream struct { k int mon map[string]*Element // the minimum Element min *Element } func New(k int) *Stream { s := new(Stream) s.k = k s.mon = make(map[string]*Element) s.min = &Element{} // Track k+1 so that less frequenet items contended for that spot, // resulting in k being more accurate. return s } func (s *Stream) Insert(x string) { s.insert(&Element{x, 1}) } func (s *Stream) Merge(sm Samples) { for _, e := range sm { s.insert(e) } } func (s *Stream) insert(in *Element) { e := s.mon[in.Value] if e != nil { e.Count++ } else { if len(s.mon) < s.k+1 { e = &Element{in.Value, in.Count} s.mon[in.Value] = e } else { e = s.min delete(s.mon, e.Value) e.Value = in.Value e.Count += in.Count s.min = e } } if e.Count < s.min.Count { s.min = e } } func (s *Stream) Query() Samples { var sm Samples for _, e := range s.mon { sm = append(sm, e) } sort.Sort(sort.Reverse(sm)) if len(sm) < s.k { return sm } return sm[:s.k] } ================================================ FILE: vendor/github.com/beorn7/perks/topk/topk_test.go ================================================ package topk import ( "fmt" "math/rand" "sort" "testing" ) func TestTopK(t *testing.T) { stream := New(10) ss := []*Stream{New(10), New(10), New(10)} m := make(map[string]int) for _, s := range ss { for i := 0; i < 1e6; i++ { v := fmt.Sprintf("%x", int8(rand.ExpFloat64())) s.Insert(v) m[v]++ } stream.Merge(s.Query()) } var sm Samples for x, s := range m { sm = append(sm, &Element{x, s}) } sort.Sort(sort.Reverse(sm)) g := stream.Query() if len(g) != 10 { t.Fatalf("got %d, want 10", len(g)) } for i, e := range g { if sm[i].Value != e.Value { t.Errorf("at %d: want %q, got %q", i, sm[i].Value, e.Value) } } } func TestQuery(t *testing.T) { queryTests := []struct { value string expected int }{ {"a", 1}, {"b", 2}, {"c", 2}, } stream := New(2) for _, tt := range queryTests { stream.Insert(tt.value) if n := len(stream.Query()); n != tt.expected { t.Errorf("want %d, got %d", tt.expected, n) } } } ================================================ FILE: vendor/github.com/blang/semver/LICENSE ================================================ The MIT License Copyright (c) 2014 Benedikt Lang 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. ================================================ FILE: vendor/github.com/blang/semver/README.md ================================================ semver for golang [![Build Status](https://drone.io/github.com/blang/semver/status.png)](https://drone.io/github.com/blang/semver/latest) [![GoDoc](https://godoc.org/github.com/blang/semver?status.png)](https://godoc.org/github.com/blang/semver) [![Coverage Status](https://img.shields.io/coveralls/blang/semver.svg)](https://coveralls.io/r/blang/semver?branch=master) ====== semver is a [Semantic Versioning](http://semver.org/) library written in golang. It fully covers spec version `2.0.0`. Usage ----- ```bash $ go get github.com/blang/semver ``` Note: Always vendor your dependencies or fix on a specific version tag. ```go import github.com/blang/semver v1, err := semver.Make("1.0.0-beta") v2, err := semver.Make("2.0.0-beta") v1.Compare(v2) ``` Also check the [GoDocs](http://godoc.org/github.com/blang/semver). Why should I use this lib? ----- - Fully spec compatible - No reflection - No regex - Fully tested (Coverage >99%) - Readable parsing/validation errors - Fast (See [Benchmarks](#benchmarks)) - Only Stdlib - Uses values instead of pointers - Many features, see below Features ----- - Parsing and validation at all levels - Comparator-like comparisons - Compare Helper Methods - InPlace manipulation - Sortable (implements sort.Interface) - database/sql compatible (sql.Scanner/Valuer) - encoding/json compatible (json.Marshaler/Unmarshaler) Example ----- Have a look at full examples in [examples/main.go](examples/main.go) ```go import github.com/blang/semver v, err := semver.Make("0.0.1-alpha.preview+123.github") fmt.Printf("Major: %d\n", v.Major) fmt.Printf("Minor: %d\n", v.Minor) fmt.Printf("Patch: %d\n", v.Patch) fmt.Printf("Pre: %s\n", v.Pre) fmt.Printf("Build: %s\n", v.Build) // Prerelease versions array if len(v.Pre) > 0 { fmt.Println("Prerelease versions:") for i, pre := range v.Pre { fmt.Printf("%d: %q\n", i, pre) } } // Build meta data array if len(v.Build) > 0 { fmt.Println("Build meta data:") for i, build := range v.Build { fmt.Printf("%d: %q\n", i, build) } } v001, err := semver.Make("0.0.1") // Compare using helpers: v.GT(v2), v.LT, v.GTE, v.LTE v001.GT(v) == true v.LT(v001) == true v.GTE(v) == true v.LTE(v) == true // Or use v.Compare(v2) for comparisons (-1, 0, 1): v001.Compare(v) == 1 v.Compare(v001) == -1 v.Compare(v) == 0 // Manipulate Version in place: v.Pre[0], err = semver.NewPRVersion("beta") if err != nil { fmt.Printf("Error parsing pre release version: %q", err) } fmt.Println("\nValidate versions:") v.Build[0] = "?" err = v.Validate() if err != nil { fmt.Printf("Validation failed: %s\n", err) } ``` Benchmarks ----- BenchmarkParseSimple 5000000 328 ns/op 49 B/op 1 allocs/op BenchmarkParseComplex 1000000 2105 ns/op 263 B/op 7 allocs/op BenchmarkParseAverage 1000000 1301 ns/op 168 B/op 4 allocs/op BenchmarkStringSimple 10000000 130 ns/op 5 B/op 1 allocs/op BenchmarkStringLarger 5000000 280 ns/op 32 B/op 2 allocs/op BenchmarkStringComplex 3000000 512 ns/op 80 B/op 3 allocs/op BenchmarkStringAverage 5000000 387 ns/op 47 B/op 2 allocs/op BenchmarkValidateSimple 500000000 7.92 ns/op 0 B/op 0 allocs/op BenchmarkValidateComplex 2000000 923 ns/op 0 B/op 0 allocs/op BenchmarkValidateAverage 5000000 452 ns/op 0 B/op 0 allocs/op BenchmarkCompareSimple 100000000 11.2 ns/op 0 B/op 0 allocs/op BenchmarkCompareComplex 50000000 40.9 ns/op 0 B/op 0 allocs/op BenchmarkCompareAverage 50000000 43.8 ns/op 0 B/op 0 allocs/op BenchmarkSort 5000000 436 ns/op 259 B/op 2 allocs/op See benchmark cases at [semver_test.go](semver_test.go) Motivation ----- I simply couldn't find any lib supporting the full spec. Others were just wrong or used reflection and regex which i don't like. Contribution ----- Feel free to make a pull request. For bigger changes create a issue first to discuss about it. License ----- See [LICENSE](LICENSE) file. ================================================ FILE: vendor/github.com/blang/semver/examples/main.go ================================================ package main import ( "fmt" "github.com/blang/semver" ) func main() { v, err := semver.Parse("0.0.1-alpha.preview.222+123.github") if err != nil { fmt.Printf("Error while parsing (not valid): %q", err) } fmt.Printf("Version to string: %q\n", v) fmt.Printf("Major: %d\n", v.Major) fmt.Printf("Minor: %d\n", v.Minor) fmt.Printf("Patch: %d\n", v.Patch) // Prerelease versions if len(v.Pre) > 0 { fmt.Println("Prerelease versions:") for i, pre := range v.Pre { fmt.Printf("%d: %q\n", i, pre) } } // Build meta data if len(v.Build) > 0 { fmt.Println("Build meta data:") for i, build := range v.Build { fmt.Printf("%d: %q\n", i, build) } } // Make == Parse (Value), New for Pointer v001, err := semver.Make("0.0.1") fmt.Println("\nUse Version.Compare for comparisons (-1, 0, 1):") fmt.Printf("%q is greater than %q: Compare == %d\n", v001, v, v001.Compare(v)) fmt.Printf("%q is less than %q: Compare == %d\n", v, v001, v.Compare(v001)) fmt.Printf("%q is equal to %q: Compare == %d\n", v, v, v.Compare(v)) fmt.Println("\nUse comparison helpers returning booleans:") fmt.Printf("%q is greater than %q: %t\n", v001, v, v001.GT(v)) fmt.Printf("%q is greater than equal %q: %t\n", v001, v, v001.GTE(v)) fmt.Printf("%q is greater than equal %q: %t\n", v, v, v.GTE(v)) fmt.Printf("%q is less than %q: %t\n", v, v001, v.LT(v001)) fmt.Printf("%q is less than equal %q: %t\n", v, v001, v.LTE(v001)) fmt.Printf("%q is less than equal %q: %t\n", v, v, v.LTE(v)) fmt.Println("\nManipulate Version in place:") v.Pre[0], err = semver.NewPRVersion("beta") if err != nil { fmt.Printf("Error parsing pre release version: %q", err) } fmt.Printf("Version to string: %q\n", v) fmt.Println("\nCompare Prerelease versions:") pre1, _ := semver.NewPRVersion("123") pre2, _ := semver.NewPRVersion("alpha") pre3, _ := semver.NewPRVersion("124") fmt.Printf("%q is less than %q: Compare == %d\n", pre1, pre2, pre1.Compare(pre2)) fmt.Printf("%q is greater than %q: Compare == %d\n", pre3, pre1, pre3.Compare(pre1)) fmt.Printf("%q is equal to %q: Compare == %d\n", pre1, pre1, pre1.Compare(pre1)) fmt.Println("\nValidate versions:") v.Build[0] = "?" err = v.Validate() if err != nil { fmt.Printf("Validation failed: %s\n", err) } fmt.Println("Create valid build meta data:") b1, _ := semver.NewBuildVersion("build123") v.Build[0] = b1 fmt.Printf("Version with new build version %q\n", v) _, err = semver.NewBuildVersion("build?123") if err != nil { fmt.Printf("Create build version failed: %s\n", err) } } ================================================ FILE: vendor/github.com/blang/semver/json.go ================================================ package semver import ( "encoding/json" ) // MarshalJSON implements the encoding/json.Marshaler interface. func (v Version) MarshalJSON() ([]byte, error) { return json.Marshal(v.String()) } // UnmarshalJSON implements the encoding/json.Unmarshaler interface. func (v *Version) UnmarshalJSON(data []byte) (err error) { var versionString string if err = json.Unmarshal(data, &versionString); err != nil { return } *v, err = Parse(versionString) return } ================================================ FILE: vendor/github.com/blang/semver/json_test.go ================================================ package semver import ( "encoding/json" "strconv" "testing" ) func TestJSONMarshal(t *testing.T) { versionString := "3.1.4-alpha.1.5.9+build.2.6.5" v, err := Parse(versionString) if err != nil { t.Fatal(err) } versionJSON, err := json.Marshal(v) if err != nil { t.Fatal(err) } quotedVersionString := strconv.Quote(versionString) if string(versionJSON) != quotedVersionString { t.Fatalf("JSON marshaled semantic version not equal: expected %q, got %q", quotedVersionString, string(versionJSON)) } } func TestJSONUnmarshal(t *testing.T) { versionString := "3.1.4-alpha.1.5.9+build.2.6.5" quotedVersionString := strconv.Quote(versionString) var v Version if err := json.Unmarshal([]byte(quotedVersionString), &v); err != nil { t.Fatal(err) } if v.String() != versionString { t.Fatalf("JSON unmarshaled semantic version not equal: expected %q, got %q", versionString, v.String()) } badVersionString := strconv.Quote("3.1.4.1.5.9.2.6.5-other-digits-of-pi") if err := json.Unmarshal([]byte(badVersionString), &v); err == nil { t.Fatal("expected JSON unmarshal error, got nil") } } ================================================ FILE: vendor/github.com/blang/semver/semver.go ================================================ package semver import ( "errors" "fmt" "strconv" "strings" ) const ( numbers string = "0123456789" alphas = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-" alphanum = alphas + numbers ) // SpecVersion is the latest fully supported spec version of semver var SpecVersion = Version{ Major: 2, Minor: 0, Patch: 0, } // Version represents a semver compatible version type Version struct { Major uint64 Minor uint64 Patch uint64 Pre []PRVersion Build []string //No Precendence } // Version to string func (v Version) String() string { b := make([]byte, 0, 5) b = strconv.AppendUint(b, v.Major, 10) b = append(b, '.') b = strconv.AppendUint(b, v.Minor, 10) b = append(b, '.') b = strconv.AppendUint(b, v.Patch, 10) if len(v.Pre) > 0 { b = append(b, '-') b = append(b, v.Pre[0].String()...) for _, pre := range v.Pre[1:] { b = append(b, '.') b = append(b, pre.String()...) } } if len(v.Build) > 0 { b = append(b, '+') b = append(b, v.Build[0]...) for _, build := range v.Build[1:] { b = append(b, '.') b = append(b, build...) } } return string(b) } // Equals checks if v is equal to o. func (v Version) Equals(o Version) bool { return (v.Compare(o) == 0) } // EQ checks if v is equal to o. func (v Version) EQ(o Version) bool { return (v.Compare(o) == 0) } // NE checks if v is not equal to o. func (v Version) NE(o Version) bool { return (v.Compare(o) != 0) } // GT checks if v is greater than o. func (v Version) GT(o Version) bool { return (v.Compare(o) == 1) } // GTE checks if v is greater than or equal to o. func (v Version) GTE(o Version) bool { return (v.Compare(o) >= 0) } // GE checks if v is greater than or equal to o. func (v Version) GE(o Version) bool { return (v.Compare(o) >= 0) } // LT checks if v is less than o. func (v Version) LT(o Version) bool { return (v.Compare(o) == -1) } // LTE checks if v is less than or equal to o. func (v Version) LTE(o Version) bool { return (v.Compare(o) <= 0) } // LE checks if v is less than or equal to o. func (v Version) LE(o Version) bool { return (v.Compare(o) <= 0) } // Compare compares Versions v to o: // -1 == v is less than o // 0 == v is equal to o // 1 == v is greater than o func (v Version) Compare(o Version) int { if v.Major != o.Major { if v.Major > o.Major { return 1 } return -1 } if v.Minor != o.Minor { if v.Minor > o.Minor { return 1 } return -1 } if v.Patch != o.Patch { if v.Patch > o.Patch { return 1 } return -1 } // Quick comparison if a version has no prerelease versions if len(v.Pre) == 0 && len(o.Pre) == 0 { return 0 } else if len(v.Pre) == 0 && len(o.Pre) > 0 { return 1 } else if len(v.Pre) > 0 && len(o.Pre) == 0 { return -1 } i := 0 for ; i < len(v.Pre) && i < len(o.Pre); i++ { if comp := v.Pre[i].Compare(o.Pre[i]); comp == 0 { continue } else if comp == 1 { return 1 } else { return -1 } } // If all pr versions are the equal but one has further prversion, this one greater if i == len(v.Pre) && i == len(o.Pre) { return 0 } else if i == len(v.Pre) && i < len(o.Pre) { return -1 } else { return 1 } } // Validate validates v and returns error in case func (v Version) Validate() error { // Major, Minor, Patch already validated using uint64 for _, pre := range v.Pre { if !pre.IsNum { //Numeric prerelease versions already uint64 if len(pre.VersionStr) == 0 { return fmt.Errorf("Prerelease can not be empty %q", pre.VersionStr) } if !containsOnly(pre.VersionStr, alphanum) { return fmt.Errorf("Invalid character(s) found in prerelease %q", pre.VersionStr) } } } for _, build := range v.Build { if len(build) == 0 { return fmt.Errorf("Build meta data can not be empty %q", build) } if !containsOnly(build, alphanum) { return fmt.Errorf("Invalid character(s) found in build meta data %q", build) } } return nil } // New is an alias for Parse and returns a pointer, parses version string and returns a validated Version or error func New(s string) (vp *Version, err error) { v, err := Parse(s) vp = &v return } // Make is an alias for Parse, parses version string and returns a validated Version or error func Make(s string) (Version, error) { return Parse(s) } // Parse parses version string and returns a validated Version or error func Parse(s string) (Version, error) { if len(s) == 0 { return Version{}, errors.New("Version string empty") } // Split into major.minor.(patch+pr+meta) parts := strings.SplitN(s, ".", 3) if len(parts) != 3 { return Version{}, errors.New("No Major.Minor.Patch elements found") } // Major if !containsOnly(parts[0], numbers) { return Version{}, fmt.Errorf("Invalid character(s) found in major number %q", parts[0]) } if hasLeadingZeroes(parts[0]) { return Version{}, fmt.Errorf("Major number must not contain leading zeroes %q", parts[0]) } major, err := strconv.ParseUint(parts[0], 10, 64) if err != nil { return Version{}, err } // Minor if !containsOnly(parts[1], numbers) { return Version{}, fmt.Errorf("Invalid character(s) found in minor number %q", parts[1]) } if hasLeadingZeroes(parts[1]) { return Version{}, fmt.Errorf("Minor number must not contain leading zeroes %q", parts[1]) } minor, err := strconv.ParseUint(parts[1], 10, 64) if err != nil { return Version{}, err } v := Version{} v.Major = major v.Minor = minor var build, prerelease []string patchStr := parts[2] if buildIndex := strings.IndexRune(patchStr, '+'); buildIndex != -1 { build = strings.Split(patchStr[buildIndex+1:], ".") patchStr = patchStr[:buildIndex] } if preIndex := strings.IndexRune(patchStr, '-'); preIndex != -1 { prerelease = strings.Split(patchStr[preIndex+1:], ".") patchStr = patchStr[:preIndex] } if !containsOnly(patchStr, numbers) { return Version{}, fmt.Errorf("Invalid character(s) found in patch number %q", patchStr) } if hasLeadingZeroes(patchStr) { return Version{}, fmt.Errorf("Patch number must not contain leading zeroes %q", patchStr) } patch, err := strconv.ParseUint(patchStr, 10, 64) if err != nil { return Version{}, err } v.Patch = patch // Prerelease for _, prstr := range prerelease { parsedPR, err := NewPRVersion(prstr) if err != nil { return Version{}, err } v.Pre = append(v.Pre, parsedPR) } // Build meta data for _, str := range build { if len(str) == 0 { return Version{}, errors.New("Build meta data is empty") } if !containsOnly(str, alphanum) { return Version{}, fmt.Errorf("Invalid character(s) found in build meta data %q", str) } v.Build = append(v.Build, str) } return v, nil } // MustParse is like Parse but panics if the version cannot be parsed. func MustParse(s string) Version { v, err := Parse(s) if err != nil { panic(`semver: Parse(` + s + `): ` + err.Error()) } return v } // PRVersion represents a PreRelease Version type PRVersion struct { VersionStr string VersionNum uint64 IsNum bool } // NewPRVersion creates a new valid prerelease version func NewPRVersion(s string) (PRVersion, error) { if len(s) == 0 { return PRVersion{}, errors.New("Prerelease is empty") } v := PRVersion{} if containsOnly(s, numbers) { if hasLeadingZeroes(s) { return PRVersion{}, fmt.Errorf("Numeric PreRelease version must not contain leading zeroes %q", s) } num, err := strconv.ParseUint(s, 10, 64) // Might never be hit, but just in case if err != nil { return PRVersion{}, err } v.VersionNum = num v.IsNum = true } else if containsOnly(s, alphanum) { v.VersionStr = s v.IsNum = false } else { return PRVersion{}, fmt.Errorf("Invalid character(s) found in prerelease %q", s) } return v, nil } // IsNumeric checks if prerelease-version is numeric func (v PRVersion) IsNumeric() bool { return v.IsNum } // Compare compares two PreRelease Versions v and o: // -1 == v is less than o // 0 == v is equal to o // 1 == v is greater than o func (v PRVersion) Compare(o PRVersion) int { if v.IsNum && !o.IsNum { return -1 } else if !v.IsNum && o.IsNum { return 1 } else if v.IsNum && o.IsNum { if v.VersionNum == o.VersionNum { return 0 } else if v.VersionNum > o.VersionNum { return 1 } else { return -1 } } else { // both are Alphas if v.VersionStr == o.VersionStr { return 0 } else if v.VersionStr > o.VersionStr { return 1 } else { return -1 } } } // PreRelease version to string func (v PRVersion) String() string { if v.IsNum { return strconv.FormatUint(v.VersionNum, 10) } return v.VersionStr } func containsOnly(s string, set string) bool { return strings.IndexFunc(s, func(r rune) bool { return !strings.ContainsRune(set, r) }) == -1 } func hasLeadingZeroes(s string) bool { return len(s) > 1 && s[0] == '0' } // NewBuildVersion creates a new valid build version func NewBuildVersion(s string) (string, error) { if len(s) == 0 { return "", errors.New("Buildversion is empty") } if !containsOnly(s, alphanum) { return "", fmt.Errorf("Invalid character(s) found in build meta data %q", s) } return s, nil } ================================================ FILE: vendor/github.com/blang/semver/semver_test.go ================================================ package semver import ( "testing" ) func prstr(s string) PRVersion { return PRVersion{s, 0, false} } func prnum(i uint64) PRVersion { return PRVersion{"", i, true} } type formatTest struct { v Version result string } var formatTests = []formatTest{ {Version{1, 2, 3, nil, nil}, "1.2.3"}, {Version{0, 0, 1, nil, nil}, "0.0.1"}, {Version{0, 0, 1, []PRVersion{prstr("alpha"), prstr("preview")}, []string{"123", "456"}}, "0.0.1-alpha.preview+123.456"}, {Version{1, 2, 3, []PRVersion{prstr("alpha"), prnum(1)}, []string{"123", "456"}}, "1.2.3-alpha.1+123.456"}, {Version{1, 2, 3, []PRVersion{prstr("alpha"), prnum(1)}, nil}, "1.2.3-alpha.1"}, {Version{1, 2, 3, nil, []string{"123", "456"}}, "1.2.3+123.456"}, // Prereleases and build metadata hyphens {Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, []string{"123", "b-uild"}}, "1.2.3-alpha.b-eta+123.b-uild"}, {Version{1, 2, 3, nil, []string{"123", "b-uild"}}, "1.2.3+123.b-uild"}, {Version{1, 2, 3, []PRVersion{prstr("alpha"), prstr("b-eta")}, nil}, "1.2.3-alpha.b-eta"}, } func TestStringer(t *testing.T) { for _, test := range formatTests { if res := test.v.String(); res != test.result { t.Errorf("Stringer, expected %q but got %q", test.result, res) } } } func TestParse(t *testing.T) { for _, test := range formatTests { if v, err := Parse(test.result); err != nil { t.Errorf("Error parsing %q: %q", test.result, err) } else if comp := v.Compare(test.v); comp != 0 { t.Errorf("Parsing, expected %q but got %q, comp: %d ", test.v, v, comp) } else if err := v.Validate(); err != nil { t.Errorf("Error validating parsed version %q: %q", test.v, err) } } } func TestMustParse(t *testing.T) { _ = MustParse("32.2.1-alpha") } func TestMustParse_panic(t *testing.T) { defer func() { if recover() == nil { t.Errorf("Should have panicked") } }() _ = MustParse("invalid version") } func TestValidate(t *testing.T) { for _, test := range formatTests { if err := test.v.Validate(); err != nil { t.Errorf("Error validating %q: %q", test.v, err) } } } type compareTest struct { v1 Version v2 Version result int } var compareTests = []compareTest{ {Version{1, 0, 0, nil, nil}, Version{1, 0, 0, nil, nil}, 0}, {Version{2, 0, 0, nil, nil}, Version{1, 0, 0, nil, nil}, 1}, {Version{0, 1, 0, nil, nil}, Version{0, 1, 0, nil, nil}, 0}, {Version{0, 2, 0, nil, nil}, Version{0, 1, 0, nil, nil}, 1}, {Version{0, 0, 1, nil, nil}, Version{0, 0, 1, nil, nil}, 0}, {Version{0, 0, 2, nil, nil}, Version{0, 0, 1, nil, nil}, 1}, {Version{1, 2, 3, nil, nil}, Version{1, 2, 3, nil, nil}, 0}, {Version{2, 2, 4, nil, nil}, Version{1, 2, 4, nil, nil}, 1}, {Version{1, 3, 3, nil, nil}, Version{1, 2, 3, nil, nil}, 1}, {Version{1, 2, 4, nil, nil}, Version{1, 2, 3, nil, nil}, 1}, // Spec Examples #11 {Version{1, 0, 0, nil, nil}, Version{2, 0, 0, nil, nil}, -1}, {Version{2, 0, 0, nil, nil}, Version{2, 1, 0, nil, nil}, -1}, {Version{2, 1, 0, nil, nil}, Version{2, 1, 1, nil, nil}, -1}, // Spec Examples #9 {Version{1, 0, 0, nil, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, 1}, {Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha"), prnum(1)}, nil}, -1}, {Version{1, 0, 0, []PRVersion{prstr("alpha"), prnum(1)}, nil}, Version{1, 0, 0, []PRVersion{prstr("alpha"), prstr("beta")}, nil}, -1}, {Version{1, 0, 0, []PRVersion{prstr("alpha"), prstr("beta")}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta")}, nil}, -1}, {Version{1, 0, 0, []PRVersion{prstr("beta")}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(2)}, nil}, -1}, {Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(2)}, nil}, Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(11)}, nil}, -1}, {Version{1, 0, 0, []PRVersion{prstr("beta"), prnum(11)}, nil}, Version{1, 0, 0, []PRVersion{prstr("rc"), prnum(1)}, nil}, -1}, {Version{1, 0, 0, []PRVersion{prstr("rc"), prnum(1)}, nil}, Version{1, 0, 0, nil, nil}, -1}, // Ignore Build metadata {Version{1, 0, 0, nil, []string{"1", "2", "3"}}, Version{1, 0, 0, nil, nil}, 0}, } func TestCompare(t *testing.T) { for _, test := range compareTests { if res := test.v1.Compare(test.v2); res != test.result { t.Errorf("Comparing %q : %q, expected %d but got %d", test.v1, test.v2, test.result, res) } //Test counterpart if res := test.v2.Compare(test.v1); res != -test.result { t.Errorf("Comparing %q : %q, expected %d but got %d", test.v2, test.v1, -test.result, res) } } } type wrongformatTest struct { v *Version str string } var wrongformatTests = []wrongformatTest{ {nil, ""}, {nil, "."}, {nil, "1."}, {nil, ".1"}, {nil, "a.b.c"}, {nil, "1.a.b"}, {nil, "1.1.a"}, {nil, "1.a.1"}, {nil, "a.1.1"}, {nil, ".."}, {nil, "1.."}, {nil, "1.1."}, {nil, "1..1"}, {nil, "1.1.+123"}, {nil, "1.1.-beta"}, {nil, "-1.1.1"}, {nil, "1.-1.1"}, {nil, "1.1.-1"}, // giant numbers {nil, "20000000000000000000.1.1"}, {nil, "1.20000000000000000000.1"}, {nil, "1.1.20000000000000000000"}, {nil, "1.1.1-20000000000000000000"}, // Leading zeroes {nil, "01.1.1"}, {nil, "001.1.1"}, {nil, "1.01.1"}, {nil, "1.001.1"}, {nil, "1.1.01"}, {nil, "1.1.001"}, {nil, "1.1.1-01"}, {nil, "1.1.1-001"}, {nil, "1.1.1-beta.01"}, {nil, "1.1.1-beta.001"}, {&Version{0, 0, 0, []PRVersion{prstr("!")}, nil}, "0.0.0-!"}, {&Version{0, 0, 0, nil, []string{"!"}}, "0.0.0+!"}, // empty prversion {&Version{0, 0, 0, []PRVersion{prstr(""), prstr("alpha")}, nil}, "0.0.0-.alpha"}, // empty build meta data {&Version{0, 0, 0, []PRVersion{prstr("alpha")}, []string{""}}, "0.0.0-alpha+"}, {&Version{0, 0, 0, []PRVersion{prstr("alpha")}, []string{"test", ""}}, "0.0.0-alpha+test."}, } func TestWrongFormat(t *testing.T) { for _, test := range wrongformatTests { if res, err := Parse(test.str); err == nil { t.Errorf("Parsing wrong format version %q, expected error but got %q", test.str, res) } if test.v != nil { if err := test.v.Validate(); err == nil { t.Errorf("Validating wrong format version %q (%q), expected error", test.v, test.str) } } } } func TestCompareHelper(t *testing.T) { v := Version{1, 0, 0, []PRVersion{prstr("alpha")}, nil} v1 := Version{1, 0, 0, nil, nil} if !v.EQ(v) { t.Errorf("%q should be equal to %q", v, v) } if !v.Equals(v) { t.Errorf("%q should be equal to %q", v, v) } if !v1.NE(v) { t.Errorf("%q should not be equal to %q", v1, v) } if !v.GTE(v) { t.Errorf("%q should be greater than or equal to %q", v, v) } if !v.LTE(v) { t.Errorf("%q should be less than or equal to %q", v, v) } if !v.LT(v1) { t.Errorf("%q should be less than %q", v, v1) } if !v.LTE(v1) { t.Errorf("%q should be less than or equal %q", v, v1) } if !v.LE(v1) { t.Errorf("%q should be less than or equal %q", v, v1) } if !v1.GT(v) { t.Errorf("%q should be greater than %q", v1, v) } if !v1.GTE(v) { t.Errorf("%q should be greater than or equal %q", v1, v) } if !v1.GE(v) { t.Errorf("%q should be greater than or equal %q", v1, v) } } func TestPreReleaseVersions(t *testing.T) { p1, err := NewPRVersion("123") if !p1.IsNumeric() { t.Errorf("Expected numeric prversion, got %q", p1) } if p1.VersionNum != 123 { t.Error("Wrong prversion number") } if err != nil { t.Errorf("Not expected error %q", err) } p2, err := NewPRVersion("alpha") if p2.IsNumeric() { t.Errorf("Expected non-numeric prversion, got %q", p2) } if p2.VersionStr != "alpha" { t.Error("Wrong prversion string") } if err != nil { t.Errorf("Not expected error %q", err) } } func TestBuildMetaDataVersions(t *testing.T) { _, err := NewBuildVersion("123") if err != nil { t.Errorf("Unexpected error %q", err) } _, err = NewBuildVersion("build") if err != nil { t.Errorf("Unexpected error %q", err) } _, err = NewBuildVersion("test?") if err == nil { t.Error("Expected error, got none") } _, err = NewBuildVersion("") if err == nil { t.Error("Expected error, got none") } } func TestNewHelper(t *testing.T) { v, err := New("1.2.3") if err != nil { t.Fatalf("Unexpected error %q", err) } // New returns pointer if v == nil { t.Fatal("Version is nil") } if v.Compare(Version{1, 2, 3, nil, nil}) != 0 { t.Fatal("Unexpected comparison problem") } } func TestMakeHelper(t *testing.T) { v, err := Make("1.2.3") if err != nil { t.Fatalf("Unexpected error %q", err) } if v.Compare(Version{1, 2, 3, nil, nil}) != 0 { t.Fatal("Unexpected comparison problem") } } func BenchmarkParseSimple(b *testing.B) { const VERSION = "0.0.1" b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { Parse(VERSION) } } func BenchmarkParseComplex(b *testing.B) { const VERSION = "0.0.1-alpha.preview+123.456" b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { Parse(VERSION) } } func BenchmarkParseAverage(b *testing.B) { l := len(formatTests) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { Parse(formatTests[n%l].result) } } func BenchmarkStringSimple(b *testing.B) { const VERSION = "0.0.1" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.String() } } func BenchmarkStringLarger(b *testing.B) { const VERSION = "11.15.2012" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.String() } } func BenchmarkStringComplex(b *testing.B) { const VERSION = "0.0.1-alpha.preview+123.456" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.String() } } func BenchmarkStringAverage(b *testing.B) { l := len(formatTests) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { formatTests[n%l].v.String() } } func BenchmarkValidateSimple(b *testing.B) { const VERSION = "0.0.1" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.Validate() } } func BenchmarkValidateComplex(b *testing.B) { const VERSION = "0.0.1-alpha.preview+123.456" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.Validate() } } func BenchmarkValidateAverage(b *testing.B) { l := len(formatTests) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { formatTests[n%l].v.Validate() } } func BenchmarkCompareSimple(b *testing.B) { const VERSION = "0.0.1" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.Compare(v) } } func BenchmarkCompareComplex(b *testing.B) { const VERSION = "0.0.1-alpha.preview+123.456" v, _ := Parse(VERSION) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { v.Compare(v) } } func BenchmarkCompareAverage(b *testing.B) { l := len(compareTests) b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { compareTests[n%l].v1.Compare((compareTests[n%l].v2)) } } ================================================ FILE: vendor/github.com/blang/semver/sort.go ================================================ package semver import ( "sort" ) // Versions represents multiple versions. type Versions []Version // Len returns length of version collection func (s Versions) Len() int { return len(s) } // Swap swaps two versions inside the collection by its indices func (s Versions) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // Less checks if version at index i is less than version at index j func (s Versions) Less(i, j int) bool { return s[i].LT(s[j]) } // Sort sorts a slice of versions func Sort(versions []Version) { sort.Sort(Versions(versions)) } ================================================ FILE: vendor/github.com/blang/semver/sort_test.go ================================================ package semver import ( "reflect" "testing" ) func TestSort(t *testing.T) { v100, _ := Parse("1.0.0") v010, _ := Parse("0.1.0") v001, _ := Parse("0.0.1") versions := []Version{v010, v100, v001} Sort(versions) correct := []Version{v001, v010, v100} if !reflect.DeepEqual(versions, correct) { t.Fatalf("Sort returned wrong order: %s", versions) } } func BenchmarkSort(b *testing.B) { v100, _ := Parse("1.0.0") v010, _ := Parse("0.1.0") v001, _ := Parse("0.0.1") b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { Sort([]Version{v010, v100, v001}) } } ================================================ FILE: vendor/github.com/blang/semver/sql.go ================================================ package semver import ( "database/sql/driver" "fmt" ) // Scan implements the database/sql.Scanner interface. func (v *Version) Scan(src interface{}) (err error) { var str string switch src := src.(type) { case string: str = src case []byte: str = string(src) default: return fmt.Errorf("Version.Scan: cannot convert %T to string.", src) } if t, err := Parse(str); err == nil { *v = t } return } // Value implements the database/sql/driver.Valuer interface. func (v Version) Value() (driver.Value, error) { return v.String(), nil } ================================================ FILE: vendor/github.com/blang/semver/sql_test.go ================================================ package semver import ( "testing" ) type scanTest struct { val interface{} shouldError bool expected string } var scanTests = []scanTest{ {"1.2.3", false, "1.2.3"}, {[]byte("1.2.3"), false, "1.2.3"}, {7, true, ""}, {7e4, true, ""}, {true, true, ""}, } func TestScanString(t *testing.T) { for _, tc := range scanTests { s := &Version{} err := s.Scan(tc.val) if tc.shouldError { if err == nil { t.Fatalf("Scan did not return an error on %v (%T)", tc.val, tc.val) } } else { if err != nil { t.Fatalf("Scan returned an unexpected error: %s (%T) on %v (%T)", tc.val, tc.val, tc.val, tc.val) } if val, _ := s.Value(); val != tc.expected { t.Errorf("Wrong Value returned, expected %q, got %q", tc.expected, val) } } } } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/.gitignore ================================================ *.coverprofile ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/.travis.yml ================================================ language: go go: - 1.4.1 install: - go get -t -v ./... - go install github.com/onsi/ginkgo/ginkgo script: - export PATH=$HOME/gopath/bin:$PATH - ginkgo -r -failOnPending -randomizeAllSpecs -race ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/LICENSE ================================================ 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 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/README.md ================================================ [![Build Status](https://travis-ci.org/cloudfoundry-incubator/candiedyaml.svg)](https://travis-ci.org/cloudfoundry-incubator/candiedyaml) candiedyaml =========== YAML for Go A YAML 1.1 parser with support for YAML 1.2 features Usage ----- ```go package myApp import ( "github.com/cloudfoundry-incubator/candiedyaml" "fmt" "os" ) func main() { file, err := os.Open("path/to/some/file.yml") if err != nil { println("File does not exist:", err.Error()) os.Exit(1) } defer file.Close() document := new(interface{}) decoder := candiedyaml.NewDecoder(file) err = decoder.Decode(document) if err != nil { println("Failed to decode document:", err.Error()) } println("parsed yml into interface:", fmt.Sprintf("%#v", document)) fileToWrite, err := os.Create("path/to/some/new/file.yml") if err != nil { println("Failed to open file for writing:", err.Error()) os.Exit(1) } defer fileToWrite.Close() encoder := candiedyaml.NewEncoder(fileToWrite) err = encoder.Encode(document) if err != nil { println("Failed to encode document:", err.Error()) os.Exit(1) } return } ``` ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/api.go ================================================ /* 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 candiedyaml import ( "io" ) /* * 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) (int, 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) (int, error) { return parser.input_reader.Read(buffer) } /* * Set a string input. */ func yaml_parser_set_input_string(parser *yaml_parser_t, input []byte) { if parser.read_handler != nil { panic("input already set") } parser.read_handler = yaml_string_read_handler parser.input = input parser.input_pos = 0 } /* * Set a reader input */ func yaml_parser_set_input_reader(parser *yaml_parser_t, reader io.Reader) { if parser.read_handler != nil { panic("input already set") } parser.read_handler = yaml_file_read_handler parser.input_reader = reader } /* * Set a generic input. */ func yaml_parser_set_input(parser *yaml_parser_t, handler yaml_read_handler_t) { if parser.read_handler != nil { panic("input already set") } parser.read_handler = handler } /* * Set the source encoding. */ func yaml_parser_set_encoding(parser *yaml_parser_t, encoding yaml_encoding_t) { if parser.encoding != yaml_ANY_ENCODING { panic("encoding already set") } parser.encoding = encoding } /* * Create a new emitter object. */ func yaml_emitter_initialize(emitter *yaml_emitter_t) { *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), } } 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_writer_write_handler(emitter *yaml_emitter_t, buffer []byte) error { _, err := emitter.output_writer.Write(buffer) return err } /* * Set a string output. */ func yaml_emitter_set_output_string(emitter *yaml_emitter_t, buffer *[]byte) { if emitter.write_handler != nil { panic("output already set") } emitter.write_handler = yaml_string_write_handler emitter.output_buffer = buffer } /* * Set a file output. */ func yaml_emitter_set_output_writer(emitter *yaml_emitter_t, w io.Writer) { if emitter.write_handler != nil { panic("output already set") } emitter.write_handler = yaml_writer_write_handler emitter.output_writer = w } /* * Set a generic output handler. */ func yaml_emitter_set_output(emitter *yaml_emitter_t, handler yaml_write_handler_t) { if emitter.write_handler != nil { panic("output already set") } emitter.write_handler = handler } /* * Set the output encoding. */ func yaml_emitter_set_encoding(emitter *yaml_emitter_t, encoding yaml_encoding_t) { if emitter.encoding != yaml_ANY_ENCODING { panic("encoding already set") } 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) { *event = yaml_event_t{ event_type: yaml_STREAM_START_EVENT, encoding: encoding, } } /* * Create STREAM-END. */ func yaml_stream_end_event_initialize(event *yaml_event_t) { *event = yaml_event_t{ event_type: yaml_STREAM_END_EVENT, } } /* * 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) { *event = yaml_event_t{ event_type: yaml_DOCUMENT_START_EVENT, version_directive: version_directive, tag_directives: tag_directives, implicit: implicit, } } /* * Create DOCUMENT-END. */ func yaml_document_end_event_initialize(event *yaml_event_t, implicit bool) { *event = yaml_event_t{ event_type: yaml_DOCUMENT_END_EVENT, implicit: implicit, } } /* * Create ALIAS. */ func yaml_alias_event_initialize(event *yaml_event_t, anchor []byte) { *event = yaml_event_t{ event_type: yaml_ALIAS_EVENT, anchor: anchor, } } /* * Create SCALAR. */ func yaml_scalar_event_initialize(event *yaml_event_t, anchor []byte, tag []byte, value []byte, plain_implicit bool, quoted_implicit bool, style yaml_scalar_style_t) { *event = yaml_event_t{ event_type: yaml_SCALAR_EVENT, anchor: anchor, tag: tag, value: value, implicit: plain_implicit, quoted_implicit: quoted_implicit, style: yaml_style_t(style), } } /* * Create SEQUENCE-START. */ func yaml_sequence_start_event_initialize(event *yaml_event_t, anchor []byte, tag []byte, implicit bool, style yaml_sequence_style_t) { *event = yaml_event_t{ event_type: yaml_SEQUENCE_START_EVENT, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(style), } } /* * Create SEQUENCE-END. */ func yaml_sequence_end_event_initialize(event *yaml_event_t) { *event = yaml_event_t{ event_type: yaml_SEQUENCE_END_EVENT, } } /* * Create MAPPING-START. */ func yaml_mapping_start_event_initialize(event *yaml_event_t, anchor []byte, tag []byte, implicit bool, style yaml_mapping_style_t) { *event = yaml_event_t{ event_type: yaml_MAPPING_START_EVENT, anchor: anchor, tag: tag, implicit: implicit, style: yaml_style_t(style), } } /* * Create MAPPING-END. */ func yaml_mapping_end_event_initialize(event *yaml_event_t) { *event = yaml_event_t{ event_type: yaml_MAPPING_END_EVENT, } } /* * Destroy an event object. */ func yaml_event_delete(event *yaml_event_t) { *event = yaml_event_t{} } // /* // * Create a document object. // */ // // func yaml_document_initialize(document *yaml_document_t, // version_directive *yaml_version_directive_t, // tag_directives []yaml_tag_directive_t, // start_implicit, end_implicit bool) bool { // // // { // struct { // YAML_error_type_t error; // } context; // struct { // yaml_node_t *start; // yaml_node_t *end; // yaml_node_t *top; // } nodes = { NULL, NULL, NULL }; // yaml_version_directive_t *version_directive_copy = NULL; // struct { // yaml_tag_directive_t *start; // yaml_tag_directive_t *end; // yaml_tag_directive_t *top; // } tag_directives_copy = { NULL, NULL, NULL }; // yaml_tag_directive_t value = { NULL, NULL }; // YAML_mark_t mark = { 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) { // yaml_tag_directive_t *tag_directive; // 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)) { // yaml_tag_directive_t value = 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 { // YAML_error_type_t error; // } context; // yaml_tag_directive_t *tag_directive; // // context.error = yaml_NO_ERROR; /* Eliminate a compliler warning. */ // // assert(document); /* Non-NULL document object is expected. */ // // while (!STACK_EMPTY(&context, document.nodes)) { // yaml_node_t node = 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, int index) // { // 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, // yaml_char_t *tag, yaml_char_t *value, int length, // yaml_scalar_style_t style) // { // struct { // YAML_error_type_t error; // } context; // YAML_mark_t mark = { 0, 0, 0 }; // yaml_char_t *tag_copy = NULL; // yaml_char_t *value_copy = NULL; // yaml_node_t node; // // 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, // yaml_char_t *tag, yaml_sequence_style_t style) // { // struct { // YAML_error_type_t error; // } context; // YAML_mark_t mark = { 0, 0, 0 }; // yaml_char_t *tag_copy = NULL; // struct { // yaml_node_item_t *start; // yaml_node_item_t *end; // yaml_node_item_t *top; // } items = { NULL, NULL, NULL }; // yaml_node_t node; // // 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, // yaml_char_t *tag, yaml_mapping_style_t style) // { // struct { // YAML_error_type_t error; // } context; // YAML_mark_t mark = { 0, 0, 0 }; // yaml_char_t *tag_copy = NULL; // struct { // yaml_node_pair_t *start; // yaml_node_pair_t *end; // yaml_node_pair_t *top; // } pairs = { NULL, NULL, NULL }; // yaml_node_t node; // // 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, // int sequence, int item) // { // struct { // YAML_error_type_t error; // } 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, // int mapping, int key, int value) // { // struct { // YAML_error_type_t error; // } context; // // yaml_node_pair_t pair; // // 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; // } // ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/candiedyaml_suite_test.go ================================================ /* 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 candiedyaml import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestCandiedyaml(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Candiedyaml Suite") } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/decode.go ================================================ /* 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 candiedyaml import ( "bytes" "errors" "fmt" "io" "reflect" "runtime" "strconv" "strings" ) type Unmarshaler interface { UnmarshalYAML(tag string, value interface{}) error } // 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) } type Decoder struct { parser yaml_parser_t event yaml_event_t replay_events []yaml_event_t useNumber bool anchors map[string][]yaml_event_t tracking_anchors [][]yaml_event_t } type ParserError struct { ErrorType YAML_error_type_t Context string ContextMark YAML_mark_t Problem string ProblemMark YAML_mark_t } func (e *ParserError) Error() string { return fmt.Sprintf("yaml: [%s] %s at line %d, column %d", e.Context, e.Problem, e.ProblemMark.line+1, e.ProblemMark.column+1) } type UnexpectedEventError struct { Value string EventType yaml_event_type_t At YAML_mark_t } func (e *UnexpectedEventError) Error() string { return fmt.Sprintf("yaml: Unexpect event [%d]: '%s' at line %d, column %d", e.EventType, e.Value, e.At.line+1, e.At.column+1) } func recovery(err *error) { if r := recover(); r != nil { if _, ok := r.(runtime.Error); ok { panic(r) } var tmpError error switch r := r.(type) { case error: tmpError = r case string: tmpError = errors.New(r) default: tmpError = errors.New("Unknown panic: " + reflect.ValueOf(r).String()) } *err = tmpError } } func Unmarshal(data []byte, v interface{}) error { d := NewDecoder(bytes.NewBuffer(data)) return d.Decode(v) } func NewDecoder(r io.Reader) *Decoder { d := &Decoder{ anchors: make(map[string][]yaml_event_t), tracking_anchors: make([][]yaml_event_t, 1), } yaml_parser_initialize(&d.parser) yaml_parser_set_input_reader(&d.parser, r) return d } func (d *Decoder) Decode(v interface{}) (err error) { defer recovery(&err) rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr || rv.IsNil() { return fmt.Errorf("Expected a pointer or nil but was a %s at %s", rv.String(), d.event.start_mark) } if d.event.event_type == yaml_NO_EVENT { d.nextEvent() if d.event.event_type != yaml_STREAM_START_EVENT { return errors.New("Invalid stream") } d.nextEvent() } d.document(rv) return nil } func (d *Decoder) UseNumber() { d.useNumber = true } func (d *Decoder) error(err error) { panic(err) } func (d *Decoder) nextEvent() { if d.event.event_type == yaml_STREAM_END_EVENT { d.error(errors.New("The stream is closed")) } if d.replay_events != nil { d.event = d.replay_events[0] if len(d.replay_events) == 1 { d.replay_events = nil } else { d.replay_events = d.replay_events[1:] } } else { if !yaml_parser_parse(&d.parser, &d.event) { yaml_event_delete(&d.event) d.error(&ParserError{ ErrorType: d.parser.error, Context: d.parser.context, ContextMark: d.parser.context_mark, Problem: d.parser.problem, ProblemMark: d.parser.problem_mark, }) } } last := len(d.tracking_anchors) // skip aliases when tracking an anchor if last > 0 && d.event.event_type != yaml_ALIAS_EVENT { d.tracking_anchors[last-1] = append(d.tracking_anchors[last-1], d.event) } } func (d *Decoder) document(rv reflect.Value) { if d.event.event_type != yaml_DOCUMENT_START_EVENT { d.error(fmt.Errorf("Expected document start at %s", d.event.start_mark)) } d.nextEvent() d.parse(rv) if d.event.event_type != yaml_DOCUMENT_END_EVENT { d.error(fmt.Errorf("Expected document end at %s", d.event.start_mark)) } d.nextEvent() } func (d *Decoder) parse(rv reflect.Value) { if !rv.IsValid() { // skip ahead since we cannot store d.valueInterface() return } anchor := string(d.event.anchor) switch d.event.event_type { case yaml_SEQUENCE_START_EVENT: d.begin_anchor(anchor) d.sequence(rv) d.end_anchor(anchor) case yaml_MAPPING_START_EVENT: d.begin_anchor(anchor) d.mapping(rv) d.end_anchor(anchor) case yaml_SCALAR_EVENT: d.begin_anchor(anchor) d.scalar(rv) d.end_anchor(anchor) case yaml_ALIAS_EVENT: d.alias(rv) case yaml_DOCUMENT_END_EVENT: default: d.error(&UnexpectedEventError{ Value: string(d.event.value), EventType: d.event.event_type, At: d.event.start_mark, }) } } func (d *Decoder) begin_anchor(anchor string) { if anchor != "" { events := []yaml_event_t{d.event} d.tracking_anchors = append(d.tracking_anchors, events) } } func (d *Decoder) end_anchor(anchor string) { if anchor != "" { events := d.tracking_anchors[len(d.tracking_anchors)-1] d.tracking_anchors = d.tracking_anchors[0 : len(d.tracking_anchors)-1] // remove the anchor, replaying events shouldn't have anchors events[0].anchor = nil // we went one too many, remove the extra event events = events[:len(events)-1] // if nested, append to all the other anchors for i, e := range d.tracking_anchors { d.tracking_anchors[i] = append(e, events...) } d.anchors[anchor] = events } } func (d *Decoder) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, 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 { var temp interface{} return u, reflect.ValueOf(&temp) } } v = v.Elem() } return nil, v } func (d *Decoder) sequence(v reflect.Value) { if d.event.event_type != yaml_SEQUENCE_START_EVENT { d.error(fmt.Errorf("Expected sequence start at %s", d.event.start_mark)) } u, pv := d.indirect(v, false) if u != nil { defer func() { if err := u.UnmarshalYAML(yaml_SEQ_TAG, pv.Interface()); err != nil { d.error(err) } }() _, pv = d.indirect(pv, false) } 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.sequenceInterface())) return } // Otherwise it's invalid. fallthrough default: d.error(fmt.Errorf("Expected an array, slice or interface{} but was a %s at %s", v, d.event.start_mark)) case reflect.Array: case reflect.Slice: break } d.nextEvent() i := 0 done: for { switch d.event.event_type { case yaml_SEQUENCE_END_EVENT, yaml_DOCUMENT_END_EVENT: break done } // 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.parse(v.Index(i)) } else { // Ran out of fixed array: skip. d.parse(reflect.Value{}) } i++ } 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)) } if d.event.event_type != yaml_DOCUMENT_END_EVENT { d.nextEvent() } } func (d *Decoder) mapping(v reflect.Value) { u, pv := d.indirect(v, false) if u != nil { defer func() { if err := u.UnmarshalYAML(yaml_MAP_TAG, pv.Interface()); err != nil { d.error(err) } }() _, pv = d.indirect(pv, false) } v = pv // Decoding into nil interface? Switch to non-reflect code. if v.Kind() == reflect.Interface && v.NumMethod() == 0 { v.Set(reflect.ValueOf(d.mappingInterface())) return } // Check type of target: struct or map[X]Y switch v.Kind() { case reflect.Struct: d.mappingStruct(v) return case reflect.Map: default: d.error(fmt.Errorf("Expected a struct or map but was a %s at %s ", v, d.event.start_mark)) } mapt := v.Type() if v.IsNil() { v.Set(reflect.MakeMap(mapt)) } d.nextEvent() keyt := mapt.Key() mapElemt := mapt.Elem() var mapElem reflect.Value done: for { switch d.event.event_type { case yaml_MAPPING_END_EVENT: break done case yaml_DOCUMENT_END_EVENT: return } key := reflect.New(keyt) d.parse(key.Elem()) if !mapElem.IsValid() { mapElem = reflect.New(mapElemt).Elem() } else { mapElem.Set(reflect.Zero(mapElemt)) } d.parse(mapElem) v.SetMapIndex(key.Elem(), mapElem) } d.nextEvent() } func (d *Decoder) mappingStruct(v reflect.Value) { structt := v.Type() fields := cachedTypeFields(structt) d.nextEvent() done: for { switch d.event.event_type { case yaml_MAPPING_END_EVENT: break done case yaml_DOCUMENT_END_EVENT: return } key := "" d.parse(reflect.ValueOf(&key)) // Figure out field corresponding to key. var subv reflect.Value var f *field 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 = v 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) } } d.parse(subv) } d.nextEvent() } func (d *Decoder) scalar(v reflect.Value) { val := string(d.event.value) wantptr := null_values[val] u, pv := d.indirect(v, wantptr) var tag string if u != nil { defer func() { if err := u.UnmarshalYAML(tag, pv.Interface()); err != nil { d.error(err) } }() _, pv = d.indirect(pv, wantptr) } v = pv var err error tag, err = resolve(d.event, v, d.useNumber) if err != nil { d.error(err) } d.nextEvent() } func (d *Decoder) alias(rv reflect.Value) { val, ok := d.anchors[string(d.event.anchor)] if !ok { d.error(fmt.Errorf("missing anchor: '%s' at %s", d.event.anchor, d.event.start_mark)) } d.replay_events = val d.nextEvent() d.parse(rv) } func (d *Decoder) valueInterface() interface{} { var v interface{} anchor := string(d.event.anchor) switch d.event.event_type { case yaml_SEQUENCE_START_EVENT: d.begin_anchor(anchor) v = d.sequenceInterface() case yaml_MAPPING_START_EVENT: d.begin_anchor(anchor) v = d.mappingInterface() case yaml_SCALAR_EVENT: d.begin_anchor(anchor) v = d.scalarInterface() case yaml_ALIAS_EVENT: rv := reflect.ValueOf(&v) d.alias(rv) return v case yaml_DOCUMENT_END_EVENT: d.error(&UnexpectedEventError{ Value: string(d.event.value), EventType: d.event.event_type, At: d.event.start_mark, }) } d.end_anchor(anchor) return v } func (d *Decoder) scalarInterface() interface{} { _, v := resolveInterface(d.event, d.useNumber) d.nextEvent() return v } // sequenceInterface is like sequence but returns []interface{}. func (d *Decoder) sequenceInterface() []interface{} { var v = make([]interface{}, 0) d.nextEvent() done: for { switch d.event.event_type { case yaml_SEQUENCE_END_EVENT, yaml_DOCUMENT_END_EVENT: break done } v = append(v, d.valueInterface()) } if d.event.event_type != yaml_DOCUMENT_END_EVENT { d.nextEvent() } return v } // mappingInterface is like mapping but returns map[interface{}]interface{}. func (d *Decoder) mappingInterface() map[interface{}]interface{} { m := make(map[interface{}]interface{}) d.nextEvent() done: for { switch d.event.event_type { case yaml_MAPPING_END_EVENT, yaml_DOCUMENT_END_EVENT: break done } key := d.valueInterface() // Read value. m[key] = d.valueInterface() } if d.event.event_type != yaml_DOCUMENT_END_EVENT { d.nextEvent() } return m } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/decode_test.go ================================================ /* 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 candiedyaml import ( "math" "os" "strconv" "strings" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Decode", func() { It("Decodes a file", func() { f, _ := os.Open("fixtures/specification/example2_1.yaml") d := NewDecoder(f) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) }) Context("strings", func() { It("Decodes an empty string", func() { d := NewDecoder(strings.NewReader(`"" `)) var v string err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal("")) }) It("Decodes an empty string to an interface", func() { d := NewDecoder(strings.NewReader(`"" `)) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal("")) }) It("Decodes a map containing empty strings to an interface", func() { d := NewDecoder(strings.NewReader(`"" : "" `)) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[interface{}]interface{}{"": ""})) }) It("Decodes strings starting with a colon", func() { d := NewDecoder(strings.NewReader(`:colon `)) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(":colon")) }) }) Context("Sequence", func() { It("Decodes to interface{}s", func() { f, _ := os.Open("fixtures/specification/example2_1.yaml") d := NewDecoder(f) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect((v).([]interface{})).To(Equal([]interface{}{"Mark McGwire", "Sammy Sosa", "Ken Griffey"})) }) It("Decodes to []string", func() { f, _ := os.Open("fixtures/specification/example2_1.yaml") d := NewDecoder(f) v := make([]string, 0, 3) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([]string{"Mark McGwire", "Sammy Sosa", "Ken Griffey"})) }) It("Decodes a sequence of maps", func() { f, _ := os.Open("fixtures/specification/example2_12.yaml") d := NewDecoder(f) v := make([]map[string]interface{}, 1) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([]map[string]interface{}{ {"item": "Super Hoop", "quantity": int64(1)}, {"item": "Basketball", "quantity": int64(4)}, {"item": "Big Shoes", "quantity": int64(1)}, })) }) Describe("As structs", func() { It("Simple struct", func() { f, _ := os.Open("fixtures/specification/example2_4.yaml") d := NewDecoder(f) type batter struct { Name string HR int64 AVG float64 } v := make([]batter, 0, 1) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([]batter{ batter{Name: "Mark McGwire", HR: 65, AVG: 0.278}, batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288}, })) }) It("Tagged struct", func() { f, _ := os.Open("fixtures/specification/example2_4.yaml") d := NewDecoder(f) type batter struct { N string `yaml:"name"` H int64 `yaml:"hr"` A float64 `yaml:"avg"` } v := make([]batter, 0, 1) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([]batter{ batter{N: "Mark McGwire", H: 65, A: 0.278}, batter{N: "Sammy Sosa", H: 63, A: 0.288}, })) }) It("handles null values", func() { type S struct { Default interface{} } d := NewDecoder(strings.NewReader(` --- default: `)) var s S err := d.Decode(&s) Expect(err).NotTo(HaveOccurred()) Expect(s).To(Equal(S{Default: nil})) }) It("ignores missing tags", func() { f, _ := os.Open("fixtures/specification/example2_4.yaml") d := NewDecoder(f) type batter struct { N string `yaml:"name"` HR int64 A float64 } v := make([]batter, 0, 1) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([]batter{ batter{N: "Mark McGwire", HR: 65}, batter{N: "Sammy Sosa", HR: 63}, })) }) }) It("Decodes a sequence of sequences", func() { f, _ := os.Open("fixtures/specification/example2_5.yaml") d := NewDecoder(f) v := make([][]interface{}, 1) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([][]interface{}{ {"name", "hr", "avg"}, {"Mark McGwire", int64(65), float64(0.278)}, {"Sammy Sosa", int64(63), float64(0.288)}, })) }) }) Context("Maps", func() { It("Decodes to interface{}s", func() { f, _ := os.Open("fixtures/specification/example2_2.yaml") d := NewDecoder(f) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect((v).(map[interface{}]interface{})).To(Equal(map[interface{}]interface{}{ "hr": int64(65), "avg": float64(0.278), "rbi": int64(147), })) }) It("Decodes to a struct", func() { f, _ := os.Open("fixtures/specification/example2_2.yaml") d := NewDecoder(f) type batter struct { HR int64 AVG float64 RBI int64 } v := batter{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(batter{HR: 65, AVG: 0.278, RBI: 147})) }) It("Decodes to a map of string arrays", func() { f, _ := os.Open("fixtures/specification/example2_9.yaml") d := NewDecoder(f) v := make(map[string][]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string][]string{"hr": []string{"Mark McGwire", "Sammy Sosa"}, "rbi": []string{"Sammy Sosa", "Ken Griffey"}})) }) }) Context("Sequence of Maps", func() { It("Decodes to interface{}s", func() { f, _ := os.Open("fixtures/specification/example2_4.yaml") d := NewDecoder(f) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect((v).([]interface{})).To(Equal([]interface{}{ map[interface{}]interface{}{"name": "Mark McGwire", "hr": int64(65), "avg": float64(0.278)}, map[interface{}]interface{}{"name": "Sammy Sosa", "hr": int64(63), "avg": float64(0.288)}, })) }) }) It("Decodes ascii art", func() { f, _ := os.Open("fixtures/specification/example2_13.yaml") d := NewDecoder(f) v := "" err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(`\//||\/|| // || ||__ `)) }) It("Decodes folded strings", func() { f, _ := os.Open("fixtures/specification/example2_15.yaml") d := NewDecoder(f) v := "" err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal("Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n")) }) It("Decodes literal and folded strings with indents", func() { f, _ := os.Open("fixtures/specification/example2_16.yaml") d := NewDecoder(f) v := make(map[string]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]string{ "name": "Mark McGwire", "accomplishment": `Mark set a major league home run record in 1998. `, "stats": `65 Home Runs 0.278 Batting Average `, })) }) It("Decodes single quoted", func() { f, _ := os.Open("fixtures/specification/example2_17_quoted.yaml") d := NewDecoder(f) v := make(map[string]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]string{ "quoted": ` # not a 'comment'.`, })) }) Context("ints", func() { It("Decodes into an interface{}", func() { f, _ := os.Open("fixtures/specification/example2_19.yaml") d := NewDecoder(f) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "canonical": int64(12345), "decimal": int64(12345), "octal": int64(12), "hexadecimal": int64(12), })) }) It("Decodes into int64", func() { f, _ := os.Open("fixtures/specification/example2_19.yaml") d := NewDecoder(f) v := make(map[string]int64) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]int64{ "canonical": int64(12345), "decimal": int64(12345), "octal": int64(12), "hexadecimal": int64(12), })) }) Context("boundary values", func() { intoInt64 := func(val int64) { It("Decodes into an int64 value", func() { var v int64 d := NewDecoder(strings.NewReader(strconv.FormatInt(val, 10))) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(val)) }) } intoInt := func(val int) { It("Decodes into an int value", func() { var v int d := NewDecoder(strings.NewReader(strconv.FormatInt(int64(val), 10))) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(val)) }) } intoInterface := func(val int64) { It("Decodes into an interface{}", func() { var v interface{} d := NewDecoder(strings.NewReader(strconv.FormatInt(val, 10))) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(val)) }) } intoInt64(math.MaxInt64) intoInterface(math.MaxInt64) intoInt64(math.MinInt64) intoInterface(math.MinInt64) intoInt(math.MaxInt32) intoInt(math.MinInt32) }) }) It("Decodes a variety of floats", func() { f, _ := os.Open("fixtures/specification/example2_20.yaml") d := NewDecoder(f) v := make(map[string]float64) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(math.IsNaN(v["not a number"])).To(BeTrue()) delete(v, "not a number") Expect(v).To(Equal(map[string]float64{ "canonical": float64(1230.15), "exponential": float64(1230.15), "fixed": float64(1230.15), "negative infinity": math.Inf(-1), })) }) It("Decodes booleans, nil and strings", func() { f, _ := os.Open("fixtures/specification/example2_21.yaml") d := NewDecoder(f) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "": interface{}(nil), "true": true, "false": false, "string": "12345", })) }) It("Decodes a null ptr", func() { d := NewDecoder(strings.NewReader(`null `)) var v *bool err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(BeNil()) }) It("Decodes dates/time", func() { f, _ := os.Open("fixtures/specification/example2_22.yaml") d := NewDecoder(f) v := make(map[string]time.Time) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]time.Time{ "canonical": time.Date(2001, time.December, 15, 2, 59, 43, int(1*time.Millisecond), time.UTC), "iso8601": time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)), "spaced": time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)), "date": time.Date(2002, time.December, 14, 0, 0, 0, 0, time.UTC), })) }) Context("Tags", func() { It("Respects tags", func() { f, _ := os.Open("fixtures/specification/example2_23_non_date.yaml") d := NewDecoder(f) v := make(map[string]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]string{ "not-date": "2002-04-28", })) }) It("handles non-specific tags", func() { d := NewDecoder(strings.NewReader(` --- not_parsed: ! 123 `)) v := make(map[string]int) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]int{"not_parsed": 123})) }) It("handles non-specific tags", func() { d := NewDecoder(strings.NewReader(` --- ? a complex key : ! "123" `)) v := make(map[string]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]string{"a complex key": "123"})) }) }) Context("Decodes binary/base64", func() { It("to []byte", func() { f, _ := os.Open("fixtures/specification/example2_23_picture.yaml") d := NewDecoder(f) v := make(map[string][]byte) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string][]byte{ "picture": []byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0c, 0x00, 0x0c, 0x00, 0x84, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xf5, 0xf5, 0xee, 0xe9, 0xe9, 0xe5, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0xe7, 0xe7, 0xe7, 0x5e, 0x5e, 0x5e, 0xf3, 0xf3, 0xed, 0x8e, 0x8e, 0x8e, 0xe0, 0xe0, 0xe0, 0x9f, 0x9f, 0x9f, 0x93, 0x93, 0x93, 0xa7, 0xa7, 0xa7, 0x9e, 0x9e, 0x9e, 0x69, 0x5e, 0x10, 0x27, 0x20, 0x82, 0x0a, 0x01, 0x00, 0x3b}, })) }) It("to string", func() { d := NewDecoder(strings.NewReader("!binary YWJjZGVmZw==")) var v string err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal("abcdefg")) }) It("to string via alternate form", func() { d := NewDecoder(strings.NewReader("!!binary YWJjZGVmZw==")) var v string err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal("abcdefg")) }) It("to interface", func() { d := NewDecoder(strings.NewReader("!binary YWJjZGVmZw==")) var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal([]byte("abcdefg"))) }) }) Context("Aliases", func() { Context("to known types", func() { It("aliases scalars", func() { f, _ := os.Open("fixtures/specification/example2_10.yaml") d := NewDecoder(f) v := make(map[string][]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string][]string{ "hr": {"Mark McGwire", "Sammy Sosa"}, "rbi": {"Sammy Sosa", "Ken Griffey"}, })) }) It("aliases sequences", func() { d := NewDecoder(strings.NewReader(` --- hr: &ss - MG - SS rbi: *ss `)) v := make(map[string][]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string][]string{ "hr": {"MG", "SS"}, "rbi": {"MG", "SS"}, })) }) It("aliases maps", func() { d := NewDecoder(strings.NewReader(` --- hr: &ss MG : SS rbi: *ss `)) v := make(map[string]map[string]string) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]map[string]string{ "hr": {"MG": "SS"}, "rbi": {"MG": "SS"}, })) }) }) It("aliases to different types", func() { type S struct { A map[string]int C map[string]string } d := NewDecoder(strings.NewReader(` --- a: &map b : 1 c: *map `)) var s S err := d.Decode(&s) Expect(err).NotTo(HaveOccurred()) Expect(s).To(Equal(S{ A: map[string]int{"b": 1}, C: map[string]string{"b": "1"}, })) }) It("fails if an anchor is undefined", func() { d := NewDecoder(strings.NewReader(` --- a: *missing `)) m := make(map[string]string) err := d.Decode(&m) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("missing anchor.*line.*column.*")) }) Context("to Interface", func() { It("aliases scalars", func() { f, _ := os.Open("fixtures/specification/example2_10.yaml") d := NewDecoder(f) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "hr": []interface{}{"Mark McGwire", "Sammy Sosa"}, "rbi": []interface{}{"Sammy Sosa", "Ken Griffey"}, })) }) It("aliases sequences", func() { d := NewDecoder(strings.NewReader(` --- hr: &ss - MG - SS rbi: *ss `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "hr": []interface{}{"MG", "SS"}, "rbi": []interface{}{"MG", "SS"}, })) }) It("aliases maps", func() { d := NewDecoder(strings.NewReader(` --- hr: &ss MG : SS rbi: *ss `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "hr": map[interface{}]interface{}{"MG": "SS"}, "rbi": map[interface{}]interface{}{"MG": "SS"}, })) }) It("supports duplicate aliases", func() { d := NewDecoder(strings.NewReader(` --- a: &a b: 1 x: *a y: *a `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "a": map[interface{}]interface{}{"b": int64(1)}, "x": map[interface{}]interface{}{"b": int64(1)}, "y": map[interface{}]interface{}{"b": int64(1)}, })) }) It("supports overriden anchors", func() { d := NewDecoder(strings.NewReader(` --- First occurrence: &anchor Foo Second occurrence: *anchor Override anchor: &anchor Bar Reuse anchor: *anchor `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "First occurrence": "Foo", "Second occurrence": "Foo", "Override anchor": "Bar", "Reuse anchor": "Bar", })) }) It("fails if an anchor is undefined", func() { d := NewDecoder(strings.NewReader(` --- a: *missing `)) var i interface{} err := d.Decode(&i) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("missing anchor.*line.*column.*")) }) }) It("supports composing aliases", func() { d := NewDecoder(strings.NewReader(` --- a: &a b x: &b d: *a z: *b `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "a": "b", "x": map[interface{}]interface{}{"d": "b"}, "z": map[interface{}]interface{}{"d": "b"}, })) }) It("redefinition while composing aliases", func() { d := NewDecoder(strings.NewReader(` --- a: &a b x: &c d : &a 1 y: *a `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(Equal(map[string]interface{}{ "a": "b", "x": map[interface{}]interface{}{"d": int64(1)}, "y": int64(1), })) }) It("can parse nested anchors", func() { d := NewDecoder(strings.NewReader(` --- a: aa: &x aaa: 1 ab: aba: &y abaa: abaaa: *x b: - ba: baa: *y `)) v := make(map[string]interface{}) err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) }) }) Context("When decoding fails", func() { It("returns an error", func() { f, _ := os.Open("fixtures/specification/example_empty.yaml") d := NewDecoder(f) var v interface{} err := d.Decode(&v) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Expected document start at line 0, column 0")) }) }) Context("Unmarshaler support", func() { Context("Receiver is a value", func() { It("the Marshaler interface is not used", func() { d := NewDecoder(strings.NewReader("abc\n")) v := hasMarshaler{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v.Value).To(BeNil()) }) }) Context("Receiver is a pointer", func() { It("uses the Marshaler interface when a pointer", func() { d := NewDecoder(strings.NewReader("abc\n")) v := hasPtrMarshaler{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) }) It("marshals a scalar", func() { d := NewDecoder(strings.NewReader("abc\n")) v := hasPtrMarshaler{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v.Tag).To(Equal(yaml_STR_TAG)) Expect(v.Value).To(Equal("abc")) }) It("marshals a sequence", func() { d := NewDecoder(strings.NewReader("[abc, def]\n")) v := hasPtrMarshaler{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v.Tag).To(Equal(yaml_SEQ_TAG)) Expect(v.Value).To(Equal([]interface{}{"abc", "def"})) }) It("marshals a map", func() { d := NewDecoder(strings.NewReader("{ a: bc}\n")) v := hasPtrMarshaler{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v.Tag).To(Equal(yaml_MAP_TAG)) Expect(v.Value).To(Equal(map[interface{}]interface{}{"a": "bc"})) }) }) }) Context("Marshals into a Number", func() { It("when the number is an int", func() { d := NewDecoder(strings.NewReader("123\n")) d.UseNumber() var v Number err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v.String()).To(Equal("123")) }) It("when the number is an float", func() { d := NewDecoder(strings.NewReader("1.23\n")) d.UseNumber() var v Number err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v.String()).To(Equal("1.23")) }) It("it fails when its a non-Number", func() { d := NewDecoder(strings.NewReader("on\n")) d.UseNumber() var v Number err := d.Decode(&v) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("Not a number: 'on' at line 0, column 0")) }) It("returns a Number", func() { d := NewDecoder(strings.NewReader("123\n")) d.UseNumber() var v interface{} err := d.Decode(&v) Expect(err).NotTo(HaveOccurred()) Expect(v).To(BeAssignableToTypeOf(Number(""))) n := v.(Number) Expect(n.String()).To(Equal("123")) }) }) Context("When there are special characters", func() { It("returns an error", func() { d := NewDecoder(strings.NewReader(` --- applications: - name: m services: - !@# `)) var v interface{} err := d.Decode(&v) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(MatchRegexp("yaml.*did not find.*line.*column.*")) }) }) }) ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/emitter.go ================================================ /* 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 candiedyaml import ( "bytes" ) var default_tag_directives = []yaml_tag_directive_t{ {[]byte("!"), []byte("!")}, {[]byte("!!"), []byte("tag:yaml.org,2002:")}, } /* * 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 !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 !flush(emitter) { return false } switch emitter.line_break { case yaml_CR_BREAK: emitter.buffer[emitter.buffer_pos] = '\r' emitter.buffer_pos++ case yaml_LN_BREAK: emitter.buffer[emitter.buffer_pos] = '\n' emitter.buffer_pos++ case yaml_CRLN_BREAK: emitter.buffer[emitter.buffer_pos] = '\r' emitter.buffer[emitter.buffer_pos] = '\n' emitter.buffer_pos += 2 default: return false } emitter.column = 0 emitter.line++ return true } /* * Copy a character from a string into buffer. */ func write(emitter *yaml_emitter_t, src []byte, src_pos *int) bool { if !flush(emitter) { return false } copy_bytes(emitter.buffer, &emitter.buffer_pos, src, src_pos) emitter.column++ return true } /* * Copy a line break character from a string into buffer. */ func write_break(emitter *yaml_emitter_t, src []byte, src_pos *int) bool { if src[*src_pos] == '\n' { if !put_break(emitter) { return false } *src_pos++ } else { if !write(emitter, src, src_pos) { return false } emitter.column = 0 emitter.line++ } return true } /* * Set an emitter error and return 0. */ 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 } accumulate := 0 switch emitter.events[emitter.events_head].event_type { case yaml_DOCUMENT_START_EVENT: accumulate = 1 case yaml_SEQUENCE_START_EVENT: accumulate = 2 case yaml_MAPPING_START_EVENT: accumulate = 3 default: return false } if len(emitter.events)-emitter.events_head > accumulate { return false } level := 0 for i := emitter.events_head; i < len(emitter.events); i++ { switch emitter.events[i].event_type { 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 := range emitter.tag_directives { if bytes.Equal(value.handle, emitter.tag_directives[i].handle) { if allow_duplicates { return true } return yaml_emitter_set_emitter_error(emitter, "duplicat %TAG directive") } } tag_copy := yaml_tag_directive_t{ handle: value.handle, 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 bool, 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 { 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 state") } /* * Expect STREAM-START. */ func yaml_emitter_emit_stream_start(emitter *yaml_emitter_t, event *yaml_event_t) bool { if event.event_type != 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.event_type == yaml_DOCUMENT_START_EVENT { if event.version_directive != nil { if !yaml_emitter_analyze_version_directive(emitter, *event.version_directive) { return false } } for i := range event.tag_directives { 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 := range default_tag_directives { if !yaml_emitter_append_tag_directive(emitter, &default_tag_directives[i], true) { return false } } implicit := event.implicit if !first || emitter.canonical { implicit = false } if (event.version_directive != nil || len(event.tag_directives) > 0) && emitter.open_ended { 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 := range event.tag_directives { 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 } else if event.event_type == 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.event_type != 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 { 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.event_type == 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.event_type == 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) } else { 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.event_type == 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.event_type == 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) } else { 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.event_type { 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.style == yaml_style_t(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.style == yaml_style_t(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 } /* * 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].event_type == yaml_SEQUENCE_START_EVENT && emitter.events[emitter.events_head+1].event_type == 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].event_type == yaml_MAPPING_START_EVENT && emitter.events[emitter.events_head+1].event_type == 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].event_type { 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 } if length > 128 { return false } return true } /* * 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 := yaml_scalar_style_t(event.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 } indicator := "*" if !emitter.anchor_data.alias { indicator = "&" } if !yaml_emitter_write_indicator(emitter, []byte(indicator), 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 { 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) default: panic("unknown scalar") } return false } /* * 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; 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 { errmsg := "alias value must not be empty" if !alias { errmsg = "anchor value must not be empty" } return yaml_emitter_set_emitter_error(emitter, errmsg) } for i := 0; i < len(anchor); i += width(anchor[i]) { if !is_alpha(anchor[i]) { errmsg := "alias value must contain alphanumerical characters only" if !alias { errmsg = "anchor value must contain alphanumerical characters only" } return yaml_emitter_set_emitter_error(emitter, errmsg) } } 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 := range emitter.tag_directives { 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 { 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_blankz_at(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_at(value, i) || (!is_ascii(value[i]) && !emitter.unicode) { special_characters = true } if is_break_at(value, i) { line_breaks = true } if is_space(value[i]) { if i == 0 { leading_space = true } if i+w == len(value) { trailing_space = true } if previous_break { break_space = true } previous_space = true previous_break = false } else if is_break_at(value, i) { 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 } preceeded_by_whitespace = is_blankz_at(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.event_type { 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] = '\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 bool, is_whitespace bool, is_indention bool) bool { if need_whitespace && !emitter.whitespace { if !put(emitter, ' ') { return false } } ind_pos := 0 for ind_pos < len(indicator) { if !write(emitter, indicator, &ind_pos) { 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 { pos := 0 for pos < len(value) { if !write(emitter, value, &pos) { 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 } } pos := 0 for pos < len(value) { if !write(emitter, value, &pos) { 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); { write_it := false switch value[i] { case ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '!', '~', '*', '\'', '(', ')', '[', ']': write_it = true default: write_it = is_alpha(value[i]) } if write_it { if !write(emitter, value, &i) { return false } } else { w := width(value[i]) for j := 0; j < w; j++ { val := value[i] i++ if !put(emitter, '%') { return false } c := val >> 4 if c < 10 { c += '0' } else { c += 'A' - 10 } if !put(emitter, c) { return false } c = val & 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 { spaces := false breaks := false if !emitter.whitespace { if !put(emitter, ' ') { return 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_at(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 { spaces := false breaks := false if !yaml_emitter_write_indicator(emitter, []byte("'"), true, false, false) { return 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_at(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_at(value, i) || (!emitter.unicode && !is_ascii(value[i])) || is_bom_at(value, i) || is_break_at(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 } switch v { case 0x00: if !put(emitter, '0') { return false } case 0x07: if !put(emitter, 'a') { return false } case 0x08: if !put(emitter, 'b') { return false } case 0x09: if !put(emitter, 't') { return false } case 0x0A: if !put(emitter, 'n') { return false } case 0x0B: if !put(emitter, 'v') { return false } case 0x0C: if !put(emitter, 'f') { return false } case 0x0D: if !put(emitter, 'r') { return false } case 0x1B: if !put(emitter, 'e') { return false } case 0x22: if !put(emitter, '"') { return false } case 0x5C: if !put(emitter, '\\') { return false } case 0x85: if !put(emitter, 'N') { return false } case 0xA0: if !put(emitter, '_') { return false } case 0x2028: if !put(emitter, 'L') { return false } case 0x2029: if !put(emitter, 'P') { return false } default: if v <= 0xFF { if !put(emitter, 'x') { return false } w = 2 } else if v <= 0xFFFF { if !put(emitter, 'u') { return false } w = 4 } else { if !put(emitter, 'U') { return false } w = 8 } for k := (w - 1) * 4; k >= 0; k -= 4 { digit := byte((v >> uint(k)) & 0x0F) c := digit + '0' if c > 9 { c = digit + 'A' - 10 } if !put(emitter, c) { 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_at(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_at(value, i) { chomp_hint[0] = '-' } else if i == 0 { chomp_hint[0] = '+' emitter.open_ended = true } else { for value[i]&0xC0 == 0x80 { i-- } if is_break_at(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 { breaks := true 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 for i := 0; i < len(value); { if is_break_at(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 { breaks := true leading_spaces := true 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 for i := 0; i < len(value); { if is_break_at(value, i) { if !breaks && !leading_spaces && value[i] == '\n' { k := i for is_break_at(value, k) { k += width(value[k]) } if !is_blankz_at(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 } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/encode.go ================================================ /* 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 candiedyaml import ( "bytes" "encoding/base64" "io" "math" "reflect" "regexp" "sort" "strconv" "time" ) var ( timeTimeType = reflect.TypeOf(time.Time{}) marshalerType = reflect.TypeOf(new(Marshaler)).Elem() numberType = reflect.TypeOf(Number("")) nonPrintable = regexp.MustCompile("[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFD]") multiline = regexp.MustCompile("\n|\u0085|\u2028|\u2029") shortTags = map[string]string{ yaml_NULL_TAG: "!!null", yaml_BOOL_TAG: "!!bool", yaml_STR_TAG: "!!str", yaml_INT_TAG: "!!int", yaml_FLOAT_TAG: "!!float", yaml_TIMESTAMP_TAG: "!!timestamp", yaml_SEQ_TAG: "!!seq", yaml_MAP_TAG: "!!map", yaml_BINARY_TAG: "!!binary", } ) type Marshaler interface { MarshalYAML() (tag string, value interface{}, err error) } // An Encoder writes JSON objects to an output stream. type Encoder struct { w io.Writer emitter yaml_emitter_t event yaml_event_t flow bool err error } func Marshal(v interface{}) ([]byte, error) { b := bytes.Buffer{} e := NewEncoder(&b) err := e.Encode(v) return b.Bytes(), err } // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { e := &Encoder{w: w} yaml_emitter_initialize(&e.emitter) yaml_emitter_set_output_writer(&e.emitter, e.w) yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING) e.emit() yaml_document_start_event_initialize(&e.event, nil, nil, true) e.emit() return e } func (e *Encoder) Encode(v interface{}) (err error) { defer recovery(&err) if e.err != nil { return e.err } e.marshal("", reflect.ValueOf(v), true) yaml_document_end_event_initialize(&e.event, true) e.emit() e.emitter.open_ended = false yaml_stream_end_event_initialize(&e.event) e.emit() return nil } func (e *Encoder) emit() { if !yaml_emitter_emit(&e.emitter, &e.event) { panic("bad emit") } } func (e *Encoder) marshal(tag string, v reflect.Value, allowAddr bool) { vt := v.Type() if vt.Implements(marshalerType) { e.emitMarshaler(tag, v) return } if vt.Kind() != reflect.Ptr && allowAddr { if reflect.PtrTo(vt).Implements(marshalerType) { e.emitAddrMarshaler(tag, v) return } } switch v.Kind() { case reflect.Interface: if v.IsNil() { e.emitNil() } else { e.marshal(tag, v.Elem(), allowAddr) } case reflect.Map: e.emitMap(tag, v) case reflect.Ptr: if v.IsNil() { e.emitNil() } else { e.marshal(tag, v.Elem(), true) } case reflect.Struct: e.emitStruct(tag, v) case reflect.Slice: e.emitSlice(tag, v) case reflect.String: e.emitString(tag, v) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: e.emitInt(tag, v) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: e.emitUint(tag, v) case reflect.Float32, reflect.Float64: e.emitFloat(tag, v) case reflect.Bool: e.emitBool(tag, v) default: panic("Can't marshal type yet: " + v.Type().String()) } } func (e *Encoder) emitMap(tag string, v reflect.Value) { e.mapping(tag, func() { var keys stringValues = v.MapKeys() sort.Sort(keys) for _, k := range keys { e.marshal("", k, true) e.marshal("", v.MapIndex(k), true) } }) } func (e *Encoder) emitStruct(tag string, v reflect.Value) { if v.Type() == timeTimeType { e.emitTime(tag, v) return } fields := cachedTypeFields(v.Type()) e.mapping(tag, func() { for _, f := range fields { fv := fieldByIndex(v, f.index) if !fv.IsValid() || f.omitEmpty && isEmptyValue(fv) { continue } e.marshal("", reflect.ValueOf(f.name), true) e.flow = f.flow e.marshal("", fv, true) } }) } func (e *Encoder) emitTime(tag string, v reflect.Value) { t := v.Interface().(time.Time) bytes, _ := t.MarshalText() e.emitScalar(string(bytes), "", tag, yaml_PLAIN_SCALAR_STYLE) } 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 *Encoder) mapping(tag string, f func()) { implicit := tag == "" style := yaml_BLOCK_MAPPING_STYLE if e.flow { e.flow = false style = yaml_FLOW_MAPPING_STYLE } yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) e.emit() f() yaml_mapping_end_event_initialize(&e.event) e.emit() } func (e *Encoder) emitSlice(tag string, v reflect.Value) { if v.Type() == byteSliceType { e.emitBase64(tag, v) return } implicit := tag == "" style := yaml_BLOCK_SEQUENCE_STYLE if e.flow { e.flow = false style = yaml_FLOW_SEQUENCE_STYLE } yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style) e.emit() n := v.Len() for i := 0; i < n; i++ { e.marshal("", v.Index(i), true) } yaml_sequence_end_event_initialize(&e.event) e.emit() } func (e *Encoder) emitBase64(tag string, v reflect.Value) { if v.IsNil() { e.emitNil() return } s := v.Bytes() dst := make([]byte, base64.StdEncoding.EncodedLen(len(s))) base64.StdEncoding.Encode(dst, s) e.emitScalar(string(dst), "", yaml_BINARY_TAG, yaml_DOUBLE_QUOTED_SCALAR_STYLE) } func (e *Encoder) emitString(tag string, v reflect.Value) { var style yaml_scalar_style_t s := v.String() if nonPrintable.MatchString(s) { e.emitBase64(tag, v) return } if v.Type() == numberType { style = yaml_PLAIN_SCALAR_STYLE } else { event := yaml_event_t{ implicit: true, value: []byte(s), } rtag, _ := resolveInterface(event, false) if tag == "" && rtag != yaml_STR_TAG { style = yaml_DOUBLE_QUOTED_SCALAR_STYLE } else if multiline.MatchString(s) { style = yaml_LITERAL_SCALAR_STYLE } else { style = yaml_PLAIN_SCALAR_STYLE } } e.emitScalar(s, "", tag, style) } func (e *Encoder) emitBool(tag string, v reflect.Value) { s := strconv.FormatBool(v.Bool()) e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *Encoder) emitInt(tag string, v reflect.Value) { s := strconv.FormatInt(v.Int(), 10) e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *Encoder) emitUint(tag string, v reflect.Value) { s := strconv.FormatUint(v.Uint(), 10) e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *Encoder) emitFloat(tag string, v reflect.Value) { f := v.Float() var s string switch { case math.IsNaN(f): s = ".nan" case math.IsInf(f, 1): s = "+.inf" case math.IsInf(f, -1): s = "-.inf" default: s = strconv.FormatFloat(f, 'g', -1, v.Type().Bits()) } e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE) } func (e *Encoder) emitNil() { e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE) } func (e *Encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) { implicit := tag == "" if !implicit { style = yaml_PLAIN_SCALAR_STYLE } stag := shortTags[tag] if stag == "" { stag = tag } yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(stag), []byte(value), implicit, implicit, style) e.emit() } func (e *Encoder) emitMarshaler(tag string, v reflect.Value) { if v.Kind() == reflect.Ptr && v.IsNil() { e.emitNil() return } m := v.Interface().(Marshaler) if m == nil { e.emitNil() return } t, val, err := m.MarshalYAML() if err != nil { panic(err) } if val == nil { e.emitNil() return } e.marshal(t, reflect.ValueOf(val), false) } func (e *Encoder) emitAddrMarshaler(tag string, v reflect.Value) { if !v.CanAddr() { e.marshal(tag, v, false) return } va := v.Addr() if va.IsNil() { e.emitNil() return } m := v.Interface().(Marshaler) t, val, err := m.MarshalYAML() if err != nil { panic(err) } if val == nil { e.emitNil() return } e.marshal(t, reflect.ValueOf(val), false) } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/encode_test.go ================================================ /* 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 candiedyaml import ( "bytes" "errors" "math" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Encode", func() { var buf *bytes.Buffer var enc *Encoder BeforeEach(func() { buf = &bytes.Buffer{} enc = NewEncoder(buf) }) Context("Scalars", func() { It("handles strings", func() { err := enc.Encode("abc") Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`abc `)) }) It("handles really short strings", func() { err := enc.Encode(".") Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`. `)) }) It("encodes strings with multilines", func() { err := enc.Encode("a\nc") Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`|- a c `)) }) It("handles strings that match known scalars", func() { err := enc.Encode("true") Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`"true" `)) }) It("handles strings that contain colons followed by whitespace", func() { err := enc.Encode("contains: colon") Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`'contains: colon' `)) }) Context("handles ints", func() { It("handles ints", func() { err := enc.Encode(13) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("13\n")) }) It("handles uints", func() { err := enc.Encode(uint64(1)) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("1\n")) }) }) Context("handles floats", func() { It("handles float32", func() { err := enc.Encode(float32(1.234)) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("1.234\n")) }) It("handles float64", func() { err := enc.Encode(float64(1.2e23)) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("1.2e+23\n")) }) It("handles NaN", func() { err := enc.Encode(math.NaN()) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(".nan\n")) }) It("handles infinity", func() { err := enc.Encode(math.Inf(-1)) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("-.inf\n")) }) }) It("handles bools", func() { err := enc.Encode(true) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("true\n")) }) It("handles time.Time", func() { t := time.Now() err := enc.Encode(t) Expect(err).NotTo(HaveOccurred()) bytes, _ := t.MarshalText() Expect(buf.String()).To(Equal(string(bytes) + "\n")) }) Context("Null", func() { It("fails on nil", func() { err := enc.Encode(nil) Expect(err).To(HaveOccurred()) }) }) It("handles []byte", func() { err := enc.Encode([]byte{'a', 'b', 'c'}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("!!binary YWJj\n")) }) Context("Ptrs", func() { It("handles ptr of a type", func() { p := new(int) *p = 10 err := enc.Encode(p) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("10\n")) }) It("handles nil ptr", func() { var p *int err := enc.Encode(p) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("null\n")) }) }) Context("Structs", func() { It("handles simple structs", func() { type batter struct { Name string HR int64 AVG float64 } batters := []batter{ batter{Name: "Mark McGwire", HR: 65, AVG: 0.278}, batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288}, } err := enc.Encode(batters) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`- Name: Mark McGwire HR: 65 AVG: 0.278 - Name: Sammy Sosa HR: 63 AVG: 0.288 `)) }) It("handles tagged structs", func() { type batter struct { Name string `yaml:"name"` HR int64 AVG float64 `yaml:"avg"` } batters := []batter{ batter{Name: "Mark McGwire", HR: 65, AVG: 0.278}, batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288}, } err := enc.Encode(batters) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`- name: Mark McGwire HR: 65 avg: 0.278 - name: Sammy Sosa HR: 63 avg: 0.288 `)) }) It("handles nested structs", func() { type nestedConfig struct { AString string `yaml:"str"` Integer int `yaml:"int"` } type config struct { TopString string Nested nestedConfig } cfg := config{ TopString: "def", Nested: nestedConfig{ AString: "abc", Integer: 123, }, } err := enc.Encode(cfg) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`TopString: def Nested: str: abc int: 123 `)) }) It("handles inline structs", func() { type NestedConfig struct { AString string `yaml:"str"` Integer int `yaml:"int"` } type config struct { TopString string NestedConfig } cfg := config{ TopString: "def", NestedConfig: NestedConfig{ AString: "abc", Integer: 123, }, } err := enc.Encode(cfg) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`TopString: def str: abc int: 123 `)) }) It("handles inline structs with conflicts", func() { type NestedConfig struct { AString string `yaml:"str"` Integer int `yaml:"int"` } type config struct { AString string `yaml:"str"` NestedConfig } cfg := config{ AString: "def", NestedConfig: NestedConfig{ AString: "abc", Integer: 123, }, } err := enc.Encode(cfg) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`str: def int: 123 `)) }) }) }) Context("Sequence", func() { It("handles slices", func() { val := []string{"a", "b", "c"} err := enc.Encode(val) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`- a - b - c `)) }) }) Context("Maps", func() { It("Encodes simple maps", func() { err := enc.Encode(&map[string]string{ "name": "Mark McGwire", "hr": "65", "avg": "0.278", }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`avg: "0.278" hr: "65" name: Mark McGwire `)) }) It("sorts by key when strings otherwise by kind", func() { err := enc.Encode(&map[interface{}]string{ 1.2: "float", 8: "integer", "name": "Mark McGwire", "hr": "65", "avg": "0.278", }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`8: integer 1.2: float avg: "0.278" hr: "65" name: Mark McGwire `)) }) It("encodes mix types", func() { err := enc.Encode(&map[string]interface{}{ "name": "Mark McGwire", "hr": 65, "avg": 0.278, }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`avg: 0.278 hr: 65 name: Mark McGwire `)) }) }) Context("Sequence of Maps", func() { It("encodes", func() { err := enc.Encode([]map[string]interface{}{ {"name": "Mark McGwire", "hr": 65, "avg": 0.278, }, {"name": "Sammy Sosa", "hr": 63, "avg": 0.288, }, }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`- avg: 0.278 hr: 65 name: Mark McGwire - avg: 0.288 hr: 63 name: Sammy Sosa `)) }) }) Context("Maps of Sequence", func() { It("encodes", func() { err := enc.Encode(map[string][]interface{}{ "name": []interface{}{"Mark McGwire", "Sammy Sosa"}, "hr": []interface{}{65, 63}, "avg": []interface{}{0.278, 0.288}, }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`avg: - 0.278 - 0.288 hr: - 65 - 63 name: - Mark McGwire - Sammy Sosa `)) }) }) Context("Flow", func() { It("flows structs", func() { type i struct { A string } type o struct { I i `yaml:"i,flow"` } err := enc.Encode(o{ I: i{A: "abc"}, }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`i: {A: abc} `)) }) It("flows sequences", func() { type i struct { A string } type o struct { I []i `yaml:"i,flow"` } err := enc.Encode(o{ I: []i{{A: "abc"}}, }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`i: [{A: abc}] `)) }) }) Context("Omit empty", func() { It("omits nil ptrs", func() { type i struct { A *string `yaml:"a,omitempty"` } type o struct { I []i `yaml:"i,flow"` } err := enc.Encode(o{ I: []i{{A: nil}}, }) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`i: [{}] `)) }) }) Context("Skip field", func() { It("does not include the field", func() { type a struct { B string `yaml:"-"` C string } err := enc.Encode(a{B: "b", C: "c"}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`C: c `)) }) }) Context("Marshaler support", func() { Context("Receiver is a value", func() { It("uses the Marshaler interface when a value", func() { err := enc.Encode(hasMarshaler{Value: 123}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("123\n")) }) It("uses the Marshaler interface when a pointer", func() { err := enc.Encode(&hasMarshaler{Value: "abc"}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`abc `)) }) Context("when it fails", func() { It("returns an error", func() { err := enc.Encode(&hasMarshaler{Value: "abc", Error: errors.New("fail")}) Expect(err).To(MatchError("fail")) }) }) }) Context("Receiver is a pointer", func() { It("uses the Marshaler interface when a pointer", func() { err := enc.Encode(&hasPtrMarshaler{Value: map[string]string{"a": "b"}}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`a: b `)) }) It("skips the Marshaler when its a value", func() { err := enc.Encode(hasPtrMarshaler{Value: map[string]string{"a": "b"}}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`Tag: "" Value: a: b Error: null `)) }) Context("the receiver is nil", func() { var ptr *hasPtrMarshaler Context("when it fails", func() { It("returns an error", func() { err := enc.Encode(&hasPtrMarshaler{Value: "abc", Error: errors.New("fail")}) Expect(err).To(MatchError("fail")) }) }) It("returns a null", func() { err := enc.Encode(ptr) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`null `)) }) It("returns a null value for ptr types", func() { err := enc.Encode(map[string]*hasPtrMarshaler{"a": ptr}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`a: null `)) }) It("panics when used as a nil interface", func() { Expect(func() { enc.Encode(map[string]Marshaler{"a": ptr}) }).To(Panic()) }) }) Context("the receiver has a nil value", func() { ptr := &hasPtrMarshaler{Value: nil} It("returns null", func() { err := enc.Encode(ptr) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`null `)) }) Context("in a map", func() { It("returns a null value for ptr types", func() { err := enc.Encode(map[string]*hasPtrMarshaler{"a": ptr}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`a: null `)) }) It("returns a null value for interface types", func() { err := enc.Encode(map[string]Marshaler{"a": ptr}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`a: null `)) }) }) Context("in a slice", func() { It("returns a null value for ptr types", func() { err := enc.Encode([]*hasPtrMarshaler{ptr}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`- null `)) }) It("returns a null value for interface types", func() { err := enc.Encode([]Marshaler{ptr}) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal(`- null `)) }) }) }) }) }) Context("Number type", func() { It("encodes as a number", func() { n := Number("12345") err := enc.Encode(n) Expect(err).NotTo(HaveOccurred()) Expect(buf.String()).To(Equal("12345\n")) }) }) }) type hasMarshaler struct { Value interface{} Error error } func (m hasMarshaler) MarshalYAML() (string, interface{}, error) { return "", m.Value, m.Error } func (m hasMarshaler) UnmarshalYAML(tag string, value interface{}) error { m.Value = value return nil } type hasPtrMarshaler struct { Tag string Value interface{} Error error } func (m *hasPtrMarshaler) MarshalYAML() (string, interface{}, error) { return "", m.Value, m.Error } func (m *hasPtrMarshaler) UnmarshalYAML(tag string, value interface{}) error { m.Tag = tag m.Value = value return nil } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_1.yaml ================================================ - Mark McGwire - Sammy Sosa - Ken Griffey ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_10.yaml ================================================ --- hr: - Mark McGwire # Following node labeled SS - &SS Sammy Sosa rbi: - *SS # Subsequent occurrence - Ken Griffey ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_11.yaml ================================================ ? - Detroit Tigers - Chicago cubs : - 2001-07-23 ? [ New York Yankees, Atlanta Braves ] : [ 2001-07-02, 2001-08-12, 2001-08-14 ] ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_12.yaml ================================================ --- # products purchased - item : Super Hoop quantity: 1 - item : Basketball quantity: 4 - item : Big Shoes quantity: 1 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_13.yaml ================================================ # ASCII Art --- | \//||\/|| // || ||__ ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_14.yaml ================================================ --- Mark McGwire's year was crippled by a knee injury. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_15.yaml ================================================ > Sammy Sosa completed another fine season with great stats. 63 Home Runs 0.288 Batting Average What a year! ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_15_dumped.yaml ================================================ > Sammy Sosa completed another fine season with great stats. 63 Home Runs 0.288 Batting Average What a year! ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_16.yaml ================================================ name: Mark McGwire accomplishment: > Mark set a major league home run record in 1998. stats: | 65 Home Runs 0.278 Batting Average ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17.yaml ================================================ unicode: "Sosa did fine.\u263A" control: "\b1998\t1999\t2000\n" hexesc: "\x0D\x0A is \r\n" single: '"Howdy!" he cried.' quoted: ' # not a ''comment''.' tie-fighter: '|\-*-/|' ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17_control.yaml ================================================ control: "\b1998\t1999\t2000\n" ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17_hexesc.yaml ================================================ hexesc: "\x0D\x0A is \r\n" ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17_quoted.yaml ================================================ quoted: ' # not a ''comment''.' ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17_single.yaml ================================================ single: '"Howdy!" he cried.' ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17_tie_fighter.yaml ================================================ tie-fighter: '|\-*-/|' ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_17_unicode.yaml ================================================ unicode: "Sosa did fine.\u263A" ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_18.yaml ================================================ plain: This unquoted scalar spans many lines. quoted: "So does this quoted scalar.\n" ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_19.yaml ================================================ canonical: 12345 decimal: +12_345 octal: 014 hexadecimal: 0xC ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_2.yaml ================================================ hr: 65 # Home runs avg: 0.278 # Batting average rbi: 147 # Runs Batted In ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_20.yaml ================================================ canonical: 1.23015e+3 exponential: 12.3015e+02 fixed: 1_230.15 negative infinity: -.inf not a number: .NaN ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_21.yaml ================================================ null: ~ true: yes false: no string: '12345' ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_22.yaml ================================================ canonical: 2001-12-15T02:59:43.1Z iso8601: 2001-12-14t21:59:43.10-05:00 spaced: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_23.yaml ================================================ --- not-date: !!str 2002-04-28 picture: !!binary "\ R0lGODlhDAAMAIQAAP//9/X\ 17unp5WZmZgAAAOfn515eXv\ Pz7Y6OjuDg4J+fn5OTk6enp\ 56enmleECcgggoBADs=" application specific tag: !something | The semantics of the tag above may be different for different documents. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_23_application.yaml ================================================ --- application specific tag: !something | The semantics of the tag above may be different for different documents. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_23_non_date.yaml ================================================ --- not-date: !!str 2002-04-28 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_23_picture.yaml ================================================ --- picture: !!binary "\ R0lGODlhDAAMAIQAAP//9/X\ 17unp5WZmZgAAAOfn515eXv\ Pz7Y6OjuDg4J+fn5OTk6enp\ 56enmleECcgggoBADs=" ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_24.yaml ================================================ %TAG ! tag:clarkevans.com,2002: --- !shape # Use the ! handle for presenting # tag:clarkevans.com,2002:circle - !circle center: &ORIGIN {x: 73, y: 129} radius: 7 - !line start: *ORIGIN finish: { x: 89, y: 102 } - !label start: *ORIGIN color: 0xFFEEBB text: Pretty vector drawing. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_24_dumped.yaml ================================================ !shape - !circle center: &id001 {x: 73, y: 129} radius: 7 - !line finish: {x: 89, y: 102} start: *id001 - !label color: 0xFFEEBB start: *id001 text: Pretty vector drawing. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_25.yaml ================================================ # sets are represented as a # mapping where each key is # associated with the empty string --- !!set ? Mark McGwire ? Sammy Sosa ? Ken Griff ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_26.yaml ================================================ # ordered maps are represented as # a sequence of mappings, with # each mapping having one key --- !!omap - Mark McGwire: 65 - Sammy Sosa: 63 - Ken Griffy: 58 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_27.yaml ================================================ --- ! invoice: 34843 date : 2001-01-23 billTo: &id001 given : Chris family : Dumars address: lines: | 458 Walkman Dr. Suite #292 city : Royal Oak state : MI postal : 48046 shipTo: *id001 product: - sku : BL394D quantity : 4 description : Basketball price : 450.00 - sku : BL4438H quantity : 1 description : Super Hoop price : 2392.00 tax : 251.42 total: 4443.52 comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_27_dumped.yaml ================================================ !!org.yaml.snakeyaml.Invoice billTo: &id001 address: city: Royal Oak lines: | 458 Walkman Dr. Suite #292 postal: '48046' state: MI family: Dumars given: Chris comments: Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338. date: '2001-01-23' invoice: 34843 product: - {description: Basketball, price: 450.0, quantity: 4, sku: BL394D} - {description: Super Hoop, price: 2392.0, quantity: 1, sku: BL4438H} shipTo: *id001 tax: 251.42 total: 4443.52 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_28.yaml ================================================ --- Time: 2001-11-23 15:01:42 -5 User: ed Warning: This is an error message for the log file --- Time: 2001-11-23 15:02:31 -5 User: ed Warning: A slightly different error message. --- Date: 2001-11-23 15:03:17 -5 User: ed Fatal: Unknown variable "bar" Stack: - file: TopClass.py line: 23 code: | x = MoreObject("345\n") - file: MoreClass.py line: 58 code: |- foo = bar ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_3.yaml ================================================ american: - Boston Red Sox - Detroit Tigers - New York Yankees national: - New York Mets - Chicago Cubs - Atlanta Braves ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_4.yaml ================================================ - name: Mark McGwire hr: 65 avg: 0.278 - name: Sammy Sosa hr: 63 avg: 0.288 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_5.yaml ================================================ - [name , hr, avg ] - [Mark McGwire, 65, 0.278] - [Sammy Sosa , 63, 0.288] ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_6.yaml ================================================ Mark McGwire: {hr: 65, avg: 0.278} Sammy Sosa: { hr: 63, avg: 0.288 } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_7.yaml ================================================ # Ranking of 1998 home runs --- - Mark McGwire - Sammy Sosa - Ken Griffey # Team ranking --- - Chicago Cubs - St Louis Cardinals ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_8.yaml ================================================ --- time: 20:03:20 player: Sammy Sosa action: strike (miss) ... --- time: 20:03:47 player: Sammy Sosa action: grand slam ... ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example2_9.yaml ================================================ --- hr: # 1998 hr ranking - Mark McGwire - Sammy Sosa rbi: # 1998 rbi ranking - Sammy Sosa - Ken Griffey ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/example_empty.yaml ================================================ ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/map.yaml ================================================ # Unordered set of key: value pairs. Block style: !!map Clark : Evans Brian : Ingerson Oren : Ben-Kiki Flow style: !!map { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/map_mixed_tags.yaml ================================================ # Unordered set of key: value pairs. Block style: ! Clark : Evans Brian : Ingerson Oren : Ben-Kiki Flow style: { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/merge.yaml ================================================ --- - &CENTER { x: 1, y: 2 } - &LEFT { x: 0, y: 2 } - &BIG { r: 10 } - &SMALL { r: 1 } # All the following maps are equal: - # Explicit keys x: 1 y: 2 r: 10 label: center/big - # Merge one map << : *CENTER r: 10 label: center/big - # Merge multiple maps << : [ *CENTER, *BIG ] label: center/big - # Override << : [ *BIG, *LEFT, *SMALL ] x: 1 label: center/big ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/omap.yaml ================================================ # Explicitly typed ordered map (dictionary). Bestiary: !!omap - aardvark: African pig-like ant eater. Ugly. - anteater: South-American ant eater. Two species. - anaconda: South-American constrictor snake. Scaly. # Etc. # Flow style Numbers: !!omap [ one: 1, two: 2, three : 3 ] ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/pairs.yaml ================================================ # Explicitly typed pairs. Block tasks: !!pairs - meeting: with team. - meeting: with boss. - break: lunch. - meeting: with client. Flow tasks: !!pairs [ meeting: with team, meeting: with boss ] ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/seq.yaml ================================================ # Ordered sequence of nodes Block style: !!seq - Mercury # Rotates - no light/dark sides. - Venus # Deadliest. Aptly named. - Earth # Mostly dirt. - Mars # Seems empty. - Jupiter # The king. - Saturn # Pretty. - Uranus # Where the sun hardly shines. - Neptune # Boring. No rings. - Pluto # You call this a planet? Flow style: !!seq [ Mercury, Venus, Earth, Mars, # Rocks Jupiter, Saturn, Uranus, Neptune, # Gas Pluto ] # Overrated ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/set.yaml ================================================ # Explicitly typed set. baseball players: !!set ? Mark McGwire ? Sammy Sosa ? Ken Griffey # Flow style baseball teams: !!set { Boston Red Sox, Detroit Tigers, New York Yankees } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/v.yaml ================================================ --- # New schema link with: - = : library1.dll version: 1.2 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/fixtures/specification/types/value.yaml ================================================ --- # Old schema link with: - library1.dll - library2.dll --- # New schema link with: - = : library1.dll version: 1.2 - = : library2.dll version: 2.3 ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/libyaml-LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/parser.go ================================================ /* 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 candiedyaml 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].token_type == 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 { 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) } panic("invalid parser state") } /* * 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.token_type != yaml_STREAM_START_TOKEN { return yaml_parser_set_parser_error(parser, "did not find expected ", token.start_mark) } parser.state = yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE *event = yaml_event_t{ event_type: 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.token_type == yaml_DOCUMENT_END_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } } } /* Parse an implicit document. */ if implicit && token.token_type != yaml_VERSION_DIRECTIVE_TOKEN && token.token_type != yaml_TAG_DIRECTIVE_TOKEN && token.token_type != yaml_DOCUMENT_START_TOKEN && token.token_type != yaml_STREAM_END_TOKEN { 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{ event_type: yaml_DOCUMENT_START_EVENT, implicit: true, start_mark: token.start_mark, end_mark: token.end_mark, } } else if token.token_type != 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.token_type != yaml_DOCUMENT_START_TOKEN { yaml_parser_set_parser_error(parser, "did not find expected ", 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{ event_type: 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{ event_type: 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.token_type == yaml_VERSION_DIRECTIVE_TOKEN || token.token_type == yaml_TAG_DIRECTIVE_TOKEN || token.token_type == yaml_DOCUMENT_START_TOKEN || token.token_type == yaml_DOCUMENT_END_TOKEN || token.token_type == 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) } else { 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 { implicit := true token := peek_token(parser) if token == nil { return false } start_mark, end_mark := token.start_mark, token.start_mark if token.token_type == 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{ event_type: 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 bool, indentless_sequence bool) bool { token := peek_token(parser) if token == nil { return false } if token.token_type == yaml_ALIAS_TOKEN { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] *event = yaml_event_t{ event_type: yaml_ALIAS_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, anchor: token.value, } skip_token(parser) return true } else { start_mark, end_mark := token.start_mark, token.start_mark var tag_handle []byte var tag_suffix, anchor []byte var tag_mark YAML_mark_t if token.token_type == 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.token_type == yaml_TAG_TOKEN { 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.token_type == yaml_TAG_TOKEN { tag_handle = token.value tag_suffix = token.suffix start_mark, tag_mark = token.start_mark, token.start_mark end_mark = token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type == 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_handle != nil { if len(tag_handle) == 0 { tag = tag_suffix tag_handle = nil tag_suffix = nil } else { for i := range parser.tag_directives { tag_directive := &parser.tag_directives[i] if bytes.Equal(tag_directive.handle, tag_handle) { tag = append([]byte(nil), tag_directive.prefix...) tag = append(tag, tag_suffix...) tag_handle = nil tag_suffix = nil 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.token_type == yaml_BLOCK_ENTRY_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE *event = yaml_event_t{ event_type: 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 } else { if token.token_type == yaml_SCALAR_TOKEN { plain_implicit := false quoted_implicit := false end_mark = token.end_mark if (token.style == yaml_PLAIN_SCALAR_STYLE && len(tag) == 0) || (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{ event_type: 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 } else if token.token_type == yaml_FLOW_SEQUENCE_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE *event = yaml_event_t{ event_type: 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 } else if token.token_type == yaml_FLOW_MAPPING_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE *event = yaml_event_t{ event_type: 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 } else if block && token.token_type == yaml_BLOCK_SEQUENCE_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE *event = yaml_event_t{ event_type: 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 } else if block && token.token_type == yaml_BLOCK_MAPPING_START_TOKEN { end_mark = token.end_mark parser.state = yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE *event = yaml_event_t{ event_type: 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 } else 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{ event_type: 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 } else { msg := "while parsing a block node" if !block { msg = "while parsing a flow node" } yaml_parser_set_parser_error_context(parser, msg, start_mark, "did not find expected node content", token.start_mark) return false } } } 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.token_type == yaml_BLOCK_ENTRY_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_BLOCK_ENTRY_TOKEN && token.token_type != 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) } } else if token.token_type == 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{ event_type: yaml_SEQUENCE_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) return true } else { 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", 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.token_type == yaml_BLOCK_ENTRY_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_BLOCK_ENTRY_TOKEN && token.token_type != yaml_KEY_TOKEN && token.token_type != yaml_VALUE_TOKEN && token.token_type != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE) return yaml_parser_parse_node(parser, event, true, false) } else { parser.state = yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } } else { parser.state = parser.states[len(parser.states)-1] parser.states = parser.states[:len(parser.states)-1] *event = yaml_event_t{ event_type: yaml_SEQUENCE_END_EVENT, start_mark: token.start_mark, end_mark: token.start_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.token_type == yaml_KEY_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_KEY_TOKEN && token.token_type != yaml_VALUE_TOKEN && token.token_type != 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.token_type == 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{ event_type: yaml_MAPPING_END_EVENT, start_mark: token.start_mark, end_mark: token.end_mark, } skip_token(parser) return true } else { 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", 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.token_type == yaml_VALUE_TOKEN { mark := token.end_mark skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_KEY_TOKEN && token.token_type != yaml_VALUE_TOKEN && token.token_type != yaml_BLOCK_END_TOKEN { parser.states = append(parser.states, yaml_PARSE_BLOCK_MAPPING_KEY_STATE) return yaml_parser_parse_node(parser, event, true, true) } else { parser.state = yaml_PARSE_BLOCK_MAPPING_KEY_STATE return yaml_parser_process_empty_scalar(parser, event, mark) } } else { 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.token_type != yaml_FLOW_SEQUENCE_END_TOKEN { if !first { if token.token_type == yaml_FLOW_ENTRY_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } } else { 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", mark, "did not find expected ',' or ']'", token.start_mark) } } if token.token_type == yaml_KEY_TOKEN { parser.state = yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE *event = yaml_event_t{ event_type: 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.token_type != 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{ event_type: 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.token_type != yaml_VALUE_TOKEN && token.token_type != yaml_FLOW_ENTRY_TOKEN && token.token_type != 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) } else { 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.token_type == yaml_VALUE_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_FLOW_ENTRY_TOKEN && token.token_type != 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{ event_type: yaml_MAPPING_END_EVENT, start_mark: token.start_mark, end_mark: token.start_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.token_type != yaml_FLOW_MAPPING_END_TOKEN { if !first { if token.token_type == yaml_FLOW_ENTRY_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } } else { 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", mark, "did not find expected ',' or '}'", token.start_mark) } } if token.token_type == yaml_KEY_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_VALUE_TOKEN && token.token_type != yaml_FLOW_ENTRY_TOKEN && token.token_type != 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.token_type != 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{ event_type: 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.token_type == yaml_VALUE_TOKEN { skip_token(parser) token = peek_token(parser) if token == nil { return false } if token.token_type != yaml_FLOW_ENTRY_TOKEN && token.token_type != 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{ event_type: yaml_SCALAR_EVENT, start_mark: mark, end_mark: mark, value: nil, implicit: true, style: yaml_style_t(yaml_PLAIN_SCALAR_STYLE), } return true } /* * 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 { token := peek_token(parser) if token == nil { return false } var version_directive *yaml_version_directive_t var tag_directives []yaml_tag_directive_t for token.token_type == yaml_VERSION_DIRECTIVE_TOKEN || token.token_type == yaml_TAG_DIRECTIVE_TOKEN { if token.token_type == 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.token_type == 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 { tag := &parser.tag_directives[i] if bytes.Equal(value.handle, tag.handle) { if allow_duplicates { return true } return yaml_parser_set_parser_error(parser, "found duplicate %TAG directive", mark) } } parser.tag_directives = append(parser.tag_directives, value) return true } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/parser_test.go ================================================ /* 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 candiedyaml import ( "io/ioutil" "os" "path/filepath" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var parses = func(filename string) { It("parses "+filename, func() { file, err := os.Open(filename) Expect(err).To(BeNil()) parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_reader(&parser, file) failed := false event := yaml_event_t{} for { if !yaml_parser_parse(&parser, &event) { failed = true println("---", parser.error, parser.problem, parser.context, "line", parser.problem_mark.line, "col", parser.problem_mark.column) break } if event.event_type == yaml_STREAM_END_EVENT { break } } file.Close() // msg := "SUCCESS" // if failed { // msg = "FAILED" // if parser.error != yaml_NO_ERROR { // m := parser.problem_mark // fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n", // parser.context, parser.problem, m.line, m.column) // } // } Expect(failed).To(BeFalse()) }) } var parseYamls = func(dirname string) { fileInfos, err := ioutil.ReadDir(dirname) if err != nil { panic(err.Error()) } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() { parses(filepath.Join(dirname, fileInfo.Name())) } } } var _ = Describe("Parser", func() { parseYamls("fixtures/specification") parseYamls("fixtures/specification/types") }) ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/reader.go ================================================ /* 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 candiedyaml 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. */ raw := parser.raw_buffer pos := parser.raw_buffer_pos remaining := len(raw) - pos if remaining >= 2 && raw[pos] == BOM_UTF16LE[0] && raw[pos+1] == BOM_UTF16LE[1] { parser.encoding = yaml_UTF16LE_ENCODING parser.raw_buffer_pos += 2 parser.offset += 2 } else if remaining >= 2 && raw[pos] == BOM_UTF16BE[0] && raw[pos+1] == BOM_UTF16BE[1] { parser.encoding = yaml_UTF16BE_ENCODING parser.raw_buffer_pos += 2 parser.offset += 2 } else if remaining >= 3 && raw[pos] == BOM_UTF8[0] && raw[pos+1] == BOM_UTF8[1] && raw[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 1 on success, 0 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 { /* Read handler must be set. */ 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_end := len(parser.buffer) if 0 < parser.buffer_pos && parser.buffer_pos < buffer_end { copy(parser.buffer, parser.buffer[parser.buffer_pos:]) buffer_end -= parser.buffer_pos parser.buffer_pos = 0 } else if parser.buffer_pos == buffer_end { buffer_end = 0 parser.buffer_pos = 0 } 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_end] return false } } first = false /* Decode the raw buffer. */ for parser.raw_buffer_pos != len(parser.raw_buffer) { var value rune var w int raw_unread := len(parser.raw_buffer) - parser.raw_buffer_pos incomplete := false /* 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] w = width(octet) /* Check if the leading octet is valid. */ if w == 0 { 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 w > raw_unread { if parser.eof { return yaml_parser_set_reader_error(parser, "incomplete UTF-8 octet sequence", parser.offset, -1) } incomplete = true break } /* 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 < w; 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 w == 1: case w == 2 && value >= 0x80: case w == 3 && value >= 0x800: case w == 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 { high, low = 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) } incomplete = true break } /* 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 { w = 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) } incomplete = true break } /* 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 { w = 2 } break default: panic("Impossible") /* Impossible. */ } /* Check if the raw buffer contains enough bytes to form a character. */ if incomplete { break } /* * 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) */ if !(value == 0x09 || value == 0x0A || value == 0x0D || (value >= 0x20 && value <= 0x7E) || (value == 0x85) || (value >= 0xA0 && value <= 0xD7FF) || (value >= 0xE000 && value <= 0xFFFD) || (value >= 0x10000 && value <= 0x10FFFF)) { return yaml_parser_set_reader_error(parser, "control characters are not allowed", parser.offset, int(value)) } /* Move the raw pointers. */ parser.raw_buffer_pos += w parser.offset += w /* Finally put the character into the buffer. */ /* 0000 0000-0000 007F . 0xxxxxxx */ if value <= 0x7F { parser.buffer[buffer_end] = byte(value) } else if value <= 0x7FF { /* 0000 0080-0000 07FF . 110xxxxx 10xxxxxx */ parser.buffer[buffer_end] = byte(0xC0 + (value >> 6)) parser.buffer[buffer_end+1] = byte(0x80 + (value & 0x3F)) } else if value <= 0xFFFF { /* 0000 0800-0000 FFFF . 1110xxxx 10xxxxxx 10xxxxxx */ parser.buffer[buffer_end] = byte(0xE0 + (value >> 12)) parser.buffer[buffer_end+1] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_end+2] = byte(0x80 + (value & 0x3F)) } else { /* 0001 0000-0010 FFFF . 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ parser.buffer[buffer_end] = byte(0xF0 + (value >> 18)) parser.buffer[buffer_end+1] = byte(0x80 + ((value >> 12) & 0x3F)) parser.buffer[buffer_end+2] = byte(0x80 + ((value >> 6) & 0x3F)) parser.buffer[buffer_end+3] = byte(0x80 + (value & 0x3F)) } buffer_end += w parser.unread++ } /* On EOF, put NUL into the buffer and return. */ if parser.eof { parser.buffer[buffer_end] = 0 buffer_end++ parser.buffer = parser.buffer[:buffer_end] parser.unread++ return true } } parser.buffer = parser.buffer[:buffer_end] return true } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/reader_test.go ================================================ /* 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 candiedyaml import ( // "fmt" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) /* * Test cases are stolen from * http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt */ type test_case struct { title string test string result bool } var _ = Describe("Reader", func() { LONG := 100000 Context("UTF8 Sequences", func() { utf8_sequences := []test_case{ /* {"title", "test 1|test 2|...|test N!", (0 or 1)}, */ {"a simple test", "'test' is '\xd0\xbf\xd1\x80\xd0\xbe\xd0\xb2\xd0\xb5\xd1\x80\xd0\xba\xd0\xb0' in Russian!", true}, {"an empty line", "!", true}, {"u-0 is a control character", "\x00!", false}, {"u-80 is a control character", "\xc2\x80!", false}, {"u-800 is valid", "\xe0\xa0\x80!", true}, {"u-10000 is valid", "\xf0\x90\x80\x80!", true}, {"5 bytes sequences are not allowed", "\xf8\x88\x80\x80\x80!", false}, {"6 bytes sequences are not allowed", "\xfc\x84\x80\x80\x80\x80!", false}, {"u-7f is a control character", "\x7f!", false}, {"u-7FF is valid", "\xdf\xbf!", true}, {"u-FFFF is a control character", "\xef\xbf\xbf!", false}, {"u-1FFFFF is too large", "\xf7\xbf\xbf\xbf!", false}, {"u-3FFFFFF is 5 bytes", "\xfb\xbf\xbf\xbf\xbf!", false}, {"u-7FFFFFFF is 6 bytes", "\xfd\xbf\xbf\xbf\xbf\xbf!", false}, {"u-D7FF", "\xed\x9f\xbf!", true}, {"u-E000", "\xee\x80\x80!", true}, {"u-FFFD", "\xef\xbf\xbd!", true}, {"u-10FFFF", "\xf4\x8f\xbf\xbf!", true}, {"u-110000", "\xf4\x90\x80\x80!", false}, {"first continuation byte", "\x80!", false}, {"last continuation byte", "\xbf!", false}, {"2 continuation bytes", "\x80\xbf!", false}, {"3 continuation bytes", "\x80\xbf\x80!", false}, {"4 continuation bytes", "\x80\xbf\x80\xbf!", false}, {"5 continuation bytes", "\x80\xbf\x80\xbf\x80!", false}, {"6 continuation bytes", "\x80\xbf\x80\xbf\x80\xbf!", false}, {"7 continuation bytes", "\x80\xbf\x80\xbf\x80\xbf\x80!", false}, {"sequence of all 64 possible continuation bytes", "\x80|\x81|\x82|\x83|\x84|\x85|\x86|\x87|\x88|\x89|\x8a|\x8b|\x8c|\x8d|\x8e|\x8f|" + "\x90|\x91|\x92|\x93|\x94|\x95|\x96|\x97|\x98|\x99|\x9a|\x9b|\x9c|\x9d|\x9e|\x9f|" + "\xa0|\xa1|\xa2|\xa3|\xa4|\xa5|\xa6|\xa7|\xa8|\xa9|\xaa|\xab|\xac|\xad|\xae|\xaf|" + "\xb0|\xb1|\xb2|\xb3|\xb4|\xb5|\xb6|\xb7|\xb8|\xb9|\xba|\xbb|\xbc|\xbd|\xbe|\xbf!", false}, {"32 first bytes of 2-byte sequences {0xc0-0xdf}", "\xc0 |\xc1 |\xc2 |\xc3 |\xc4 |\xc5 |\xc6 |\xc7 |\xc8 |\xc9 |\xca |\xcb |\xcc |\xcd |\xce |\xcf |" + "\xd0 |\xd1 |\xd2 |\xd3 |\xd4 |\xd5 |\xd6 |\xd7 |\xd8 |\xd9 |\xda |\xdb |\xdc |\xdd |\xde |\xdf !", false}, {"16 first bytes of 3-byte sequences {0xe0-0xef}", "\xe0 |\xe1 |\xe2 |\xe3 |\xe4 |\xe5 |\xe6 |\xe7 |\xe8 |\xe9 |\xea |\xeb |\xec |\xed |\xee |\xef !", false}, {"8 first bytes of 4-byte sequences {0xf0-0xf7}", "\xf0 |\xf1 |\xf2 |\xf3 |\xf4 |\xf5 |\xf6 |\xf7 !", false}, {"4 first bytes of 5-byte sequences {0xf8-0xfb}", "\xf8 |\xf9 |\xfa |\xfb !", false}, {"2 first bytes of 6-byte sequences {0xfc-0xfd}", "\xfc |\xfd !", false}, {"sequences with last byte missing {u-0}", "\xc0|\xe0\x80|\xf0\x80\x80|\xf8\x80\x80\x80|\xfc\x80\x80\x80\x80!", false}, {"sequences with last byte missing {u-...FF}", "\xdf|\xef\xbf|\xf7\xbf\xbf|\xfb\xbf\xbf\xbf|\xfd\xbf\xbf\xbf\xbf!", false}, {"impossible bytes", "\xfe|\xff|\xfe\xfe\xff\xff!", false}, {"overlong sequences {u-2f}", "\xc0\xaf|\xe0\x80\xaf|\xf0\x80\x80\xaf|\xf8\x80\x80\x80\xaf|\xfc\x80\x80\x80\x80\xaf!", false}, {"maximum overlong sequences", "\xc1\xbf|\xe0\x9f\xbf|\xf0\x8f\xbf\xbf|\xf8\x87\xbf\xbf\xbf|\xfc\x83\xbf\xbf\xbf\xbf!", false}, {"overlong representation of the NUL character", "\xc0\x80|\xe0\x80\x80|\xf0\x80\x80\x80|\xf8\x80\x80\x80\x80|\xfc\x80\x80\x80\x80\x80!", false}, {"single UTF-16 surrogates", "\xed\xa0\x80|\xed\xad\xbf|\xed\xae\x80|\xed\xaf\xbf|\xed\xb0\x80|\xed\xbe\x80|\xed\xbf\xbf!", false}, {"paired UTF-16 surrogates", "\xed\xa0\x80\xed\xb0\x80|\xed\xa0\x80\xed\xbf\xbf|\xed\xad\xbf\xed\xb0\x80|" + "\xed\xad\xbf\xed\xbf\xbf|\xed\xae\x80\xed\xb0\x80|\xed\xae\x80\xed\xbf\xbf|" + "\xed\xaf\xbf\xed\xb0\x80|\xed\xaf\xbf\xed\xbf\xbf!", false}, {"other illegal code positions", "\xef\xbf\xbe|\xef\xbf\xbf!", false}, } check_sequence := func(tc test_case) { It(tc.title, func() { start := 0 end := start bytes := []byte(tc.test) for { for bytes[end] != '|' && bytes[end] != '!' { end++ } parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_string(&parser, bytes) result := yaml_parser_update_buffer(&parser, end-start) Expect(result).To(Equal(tc.result)) // outcome := '+' // if result != tc.result { // outcome = '-' // } // fmt.Printf("\t\t %c %s", outcome, tc.title) // if parser.error == yaml_NO_ERROR { // fmt.Printf("(no error)\n") // } else if parser.error == yaml_READER_ERROR { // if parser.problem_value != -1 { // fmt.Printf("(reader error: %s: #%X at %d)\n", // parser.problem, parser.problem_value, parser.problem_offset) // } else { // fmt.Printf("(reader error: %s: at %d)\n", // parser.problem, parser.problem_offset) // } // } if bytes[end] == '!' { break } end++ start = end yaml_parser_delete(&parser) } }) } for _, test := range utf8_sequences { check_sequence(test) } }) Context("BOMs", func() { boms := []test_case{ /* {"title", "test!", lenth}, */ {"no bom (utf-8)", "Hi is \xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!", true}, {"bom (utf-8)", "\xef\xbb\xbfHi is \xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!", true}, {"bom (utf-16-le)", "\xff\xfeH\x00i\x00 \x00i\x00s\x00 \x00\x1f\x04@\x04" + "8\x04" + "2\x04" + "5\x04" + "B\x04!", true}, {"bom (utf-16-be)", "\xfe\xff\x00H\x00i\x00 \x00i\x00s\x00 \x04\x1f\x04@\x04" + "8\x04" + "2\x04" + "5\x04" + "B!", true}, } check_bom := func(tc test_case) { It(tc.title, func() { start := 0 end := start bytes := []byte(tc.test) for bytes[end] != '!' { end++ } parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_string(&parser, bytes[:end-start]) result := yaml_parser_update_buffer(&parser, end-start) Expect(result).To(Equal(tc.result)) yaml_parser_delete(&parser) }) } for _, test := range boms { check_bom(test) } }) Context("Long UTF8", func() { It("parses properly", func() { buffer := make([]byte, 0, 3+LONG*2) buffer = append(buffer, '\xef', '\xbb', '\xbf') for j := 0; j < LONG; j++ { if j%2 == 1 { buffer = append(buffer, '\xd0', '\x90') } else { buffer = append(buffer, '\xd0', '\xaf') } } parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_string(&parser, buffer) for k := 0; k < LONG; k++ { if parser.unread == 0 { updated := yaml_parser_update_buffer(&parser, 1) Expect(updated).To(BeTrue()) // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset); } Expect(parser.unread).NotTo(Equal(0)) // printf("\tnot enough characters at %d\n", k); var ch0, ch1 byte if k%2 == 1 { ch0 = '\xd0' ch1 = '\x90' } else { ch0 = '\xd0' ch1 = '\xaf' } Expect(parser.buffer[parser.buffer_pos]).To(Equal(ch0)) Expect(parser.buffer[parser.buffer_pos+1]).To(Equal(ch1)) // printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n", // (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1], // (int)ch0, (int)ch1); parser.buffer_pos += 2 parser.unread -= 1 } updated := yaml_parser_update_buffer(&parser, 1) Expect(updated).To(BeTrue()) // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset); yaml_parser_delete(&parser) }) }) Context("Long UTF16", func() { It("parses properly", func() { buffer := make([]byte, 0, 2+LONG*2) buffer = append(buffer, '\xff', '\xfe') for j := 0; j < LONG; j++ { if j%2 == 1 { buffer = append(buffer, '\x10', '\x04') } else { buffer = append(buffer, '/', '\x04') } } parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_string(&parser, buffer) for k := 0; k < LONG; k++ { if parser.unread == 0 { updated := yaml_parser_update_buffer(&parser, 1) Expect(updated).To(BeTrue()) // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset); } Expect(parser.unread).NotTo(Equal(0)) // printf("\tnot enough characters at %d\n", k); var ch0, ch1 byte if k%2 == 1 { ch0 = '\xd0' ch1 = '\x90' } else { ch0 = '\xd0' ch1 = '\xaf' } Expect(parser.buffer[parser.buffer_pos]).To(Equal(ch0)) Expect(parser.buffer[parser.buffer_pos+1]).To(Equal(ch1)) // printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n", // (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1], // (int)ch0, (int)ch1); parser.buffer_pos += 2 parser.unread -= 1 } updated := yaml_parser_update_buffer(&parser, 1) Expect(updated).To(BeTrue()) // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset); yaml_parser_delete(&parser) }) }) }) ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/resolver.go ================================================ /* 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 candiedyaml import ( "bytes" "encoding/base64" "fmt" "math" "reflect" "regexp" "strconv" "strings" "time" ) var byteSliceType = reflect.TypeOf([]byte(nil)) var binary_tags = [][]byte{[]byte("!binary"), []byte(yaml_BINARY_TAG)} var bool_values map[string]bool var null_values map[string]bool var signs = []byte{'-', '+'} var nulls = []byte{'~', 'n', 'N'} var bools = []byte{'t', 'T', 'f', 'F', 'y', 'Y', 'n', 'N', 'o', 'O'} var timestamp_regexp *regexp.Regexp var ymd_regexp *regexp.Regexp func init() { bool_values = make(map[string]bool) bool_values["y"] = true bool_values["yes"] = true bool_values["n"] = false bool_values["no"] = false bool_values["true"] = true bool_values["false"] = false bool_values["on"] = true bool_values["off"] = false null_values = make(map[string]bool) null_values["~"] = true null_values["null"] = true null_values["Null"] = true null_values["NULL"] = true timestamp_regexp = regexp.MustCompile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:(?:[Tt]|[ \t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \t]*(?:Z|([-+][0-9][0-9]?)(?::([0-9][0-9])?)?))?)?$") ymd_regexp = regexp.MustCompile("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)$") } func resolve(event yaml_event_t, v reflect.Value, useNumber bool) (string, error) { val := string(event.value) if null_values[val] { v.Set(reflect.Zero(v.Type())) return yaml_NULL_TAG, nil } switch v.Kind() { case reflect.String: if useNumber && v.Type() == numberType { tag, i := resolveInterface(event, useNumber) if n, ok := i.(Number); ok { v.Set(reflect.ValueOf(n)) return tag, nil } return "", fmt.Errorf("Not a number: '%s' at %s", event.value, event.start_mark) } return resolve_string(val, v, event) case reflect.Bool: return resolve_bool(val, v, event) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return resolve_int(val, v, useNumber, event) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return resolve_uint(val, v, useNumber, event) case reflect.Float32, reflect.Float64: return resolve_float(val, v, useNumber, event) case reflect.Interface: _, i := resolveInterface(event, useNumber) if i != nil { v.Set(reflect.ValueOf(i)) } else { v.Set(reflect.Zero(v.Type())) } case reflect.Struct: return resolve_time(val, v, event) case reflect.Slice: if v.Type() != byteSliceType { return "", fmt.Errorf("Cannot resolve %s into %s at %s", val, v.String(), event.start_mark) } b, err := decode_binary(event.value, event) if err != nil { return "", err } v.Set(reflect.ValueOf(b)) default: return "", fmt.Errorf("Unknown resolution for '%s' using %s at %s", val, v.String(), event.start_mark) } return yaml_STR_TAG, nil } func hasBinaryTag(event yaml_event_t) bool { for _, tag := range binary_tags { if bytes.Equal(event.tag, tag) { return true } } return false } func decode_binary(value []byte, event yaml_event_t) ([]byte, error) { b := make([]byte, base64.StdEncoding.DecodedLen(len(value))) n, err := base64.StdEncoding.Decode(b, value) if err != nil { return nil, fmt.Errorf("Invalid base64 text: '%s' at %s", string(b), event.start_mark) } return b[:n], nil } func resolve_string(val string, v reflect.Value, event yaml_event_t) (string, error) { if len(event.tag) > 0 { if hasBinaryTag(event) { b, err := decode_binary(event.value, event) if err != nil { return "", err } val = string(b) } } v.SetString(val) return yaml_STR_TAG, nil } func resolve_bool(val string, v reflect.Value, event yaml_event_t) (string, error) { b, found := bool_values[strings.ToLower(val)] if !found { return "", fmt.Errorf("Invalid boolean: '%s' at %s", val, event.start_mark) } v.SetBool(b) return yaml_BOOL_TAG, nil } func resolve_int(val string, v reflect.Value, useNumber bool, event yaml_event_t) (string, error) { original := val val = strings.Replace(val, "_", "", -1) var value uint64 isNumberValue := v.Type() == numberType sign := int64(1) if val[0] == '-' { sign = -1 val = val[1:] } else if val[0] == '+' { val = val[1:] } base := 0 if val == "0" { if isNumberValue { v.SetString("0") } else { v.Set(reflect.Zero(v.Type())) } return yaml_INT_TAG, nil } if strings.HasPrefix(val, "0o") { base = 8 val = val[2:] } value, err := strconv.ParseUint(val, base, 64) if err != nil { return "", fmt.Errorf("Invalid integer: '%s' at %s", original, event.start_mark) } var val64 int64 if value <= math.MaxInt64 { val64 = int64(value) if sign == -1 { val64 = -val64 } } else if sign == -1 && value == uint64(math.MaxInt64)+1 { val64 = math.MinInt64 } else { return "", fmt.Errorf("Invalid integer: '%s' at %s", original, event.start_mark) } if isNumberValue { v.SetString(strconv.FormatInt(val64, 10)) } else { if v.OverflowInt(val64) { return "", fmt.Errorf("Invalid integer: '%s' at %s", original, event.start_mark) } v.SetInt(val64) } return yaml_INT_TAG, nil } func resolve_uint(val string, v reflect.Value, useNumber bool, event yaml_event_t) (string, error) { original := val val = strings.Replace(val, "_", "", -1) var value uint64 isNumberValue := v.Type() == numberType if val[0] == '-' { return "", fmt.Errorf("Unsigned int with negative value: '%s' at %s", original, event.start_mark) } if val[0] == '+' { val = val[1:] } base := 0 if val == "0" { if isNumberValue { v.SetString("0") } else { v.Set(reflect.Zero(v.Type())) } return yaml_INT_TAG, nil } if strings.HasPrefix(val, "0o") { base = 8 val = val[2:] } value, err := strconv.ParseUint(val, base, 64) if err != nil { return "", fmt.Errorf("Invalid unsigned integer: '%s' at %s", val, event.start_mark) } if isNumberValue { v.SetString(strconv.FormatUint(value, 10)) } else { if v.OverflowUint(value) { return "", fmt.Errorf("Invalid unsigned integer: '%s' at %s", val, event.start_mark) } v.SetUint(value) } return yaml_INT_TAG, nil } func resolve_float(val string, v reflect.Value, useNumber bool, event yaml_event_t) (string, error) { val = strings.Replace(val, "_", "", -1) var value float64 isNumberValue := v.Type() == numberType typeBits := 64 if !isNumberValue { typeBits = v.Type().Bits() } sign := 1 if val[0] == '-' { sign = -1 val = val[1:] } else if val[0] == '+' { val = val[1:] } valLower := strings.ToLower(val) if valLower == ".inf" { value = math.Inf(sign) } else if valLower == ".nan" { value = math.NaN() } else { var err error value, err = strconv.ParseFloat(val, typeBits) value *= float64(sign) if err != nil { return "", fmt.Errorf("Invalid float: '%s' at %s", val, event.start_mark) } } if isNumberValue { v.SetString(strconv.FormatFloat(value, 'g', -1, typeBits)) } else { if v.OverflowFloat(value) { return "", fmt.Errorf("Invalid float: '%s' at %s", val, event.start_mark) } v.SetFloat(value) } return yaml_FLOAT_TAG, nil } func resolve_time(val string, v reflect.Value, event yaml_event_t) (string, error) { var parsedTime time.Time matches := ymd_regexp.FindStringSubmatch(val) if len(matches) > 0 { year, _ := strconv.Atoi(matches[1]) month, _ := strconv.Atoi(matches[2]) day, _ := strconv.Atoi(matches[3]) parsedTime = time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC) } else { matches = timestamp_regexp.FindStringSubmatch(val) if len(matches) == 0 { return "", fmt.Errorf("Invalid timestamp: '%s' at %s", val, event.start_mark) } year, _ := strconv.Atoi(matches[1]) month, _ := strconv.Atoi(matches[2]) day, _ := strconv.Atoi(matches[3]) hour, _ := strconv.Atoi(matches[4]) min, _ := strconv.Atoi(matches[5]) sec, _ := strconv.Atoi(matches[6]) nsec := 0 if matches[7] != "" { millis, _ := strconv.Atoi(matches[7]) nsec = int(time.Duration(millis) * time.Millisecond) } loc := time.UTC if matches[8] != "" { sign := matches[8][0] hr, _ := strconv.Atoi(matches[8][1:]) min := 0 if matches[9] != "" { min, _ = strconv.Atoi(matches[9]) } zoneOffset := (hr*60 + min) * 60 if sign == '-' { zoneOffset = -zoneOffset } loc = time.FixedZone("", zoneOffset) } parsedTime = time.Date(year, time.Month(month), day, hour, min, sec, nsec, loc) } v.Set(reflect.ValueOf(parsedTime)) return "", nil } func resolveInterface(event yaml_event_t, useNumber bool) (string, interface{}) { val := string(event.value) if len(event.tag) == 0 && !event.implicit { return "", val } if len(val) == 0 { return yaml_NULL_TAG, nil } var result interface{} sign := false c := val[0] switch { case bytes.IndexByte(signs, c) != -1: sign = true fallthrough case c >= '0' && c <= '9': i := int64(0) result = &i if useNumber { var n Number result = &n } v := reflect.ValueOf(result).Elem() if _, err := resolve_int(val, v, useNumber, event); err == nil { return yaml_INT_TAG, v.Interface() } f := float64(0) result = &f if useNumber { var n Number result = &n } v = reflect.ValueOf(result).Elem() if _, err := resolve_float(val, v, useNumber, event); err == nil { return yaml_FLOAT_TAG, v.Interface() } if !sign { t := time.Time{} if _, err := resolve_time(val, reflect.ValueOf(&t).Elem(), event); err == nil { return "", t } } case bytes.IndexByte(nulls, c) != -1: if null_values[val] { return yaml_NULL_TAG, nil } b := false if _, err := resolve_bool(val, reflect.ValueOf(&b).Elem(), event); err == nil { return yaml_BOOL_TAG, b } case c == '.': f := float64(0) result = &f if useNumber { var n Number result = &n } v := reflect.ValueOf(result).Elem() if _, err := resolve_float(val, v, useNumber, event); err == nil { return yaml_FLOAT_TAG, v.Interface() } case bytes.IndexByte(bools, c) != -1: b := false if _, err := resolve_bool(val, reflect.ValueOf(&b).Elem(), event); err == nil { return yaml_BOOL_TAG, b } } if hasBinaryTag(event) { bytes, err := decode_binary(event.value, event) if err == nil { return yaml_BINARY_TAG, bytes } } return yaml_STR_TAG, val } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/resolver_test.go ================================================ /* 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 candiedyaml import ( "math" "reflect" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Resolver", func() { var event yaml_event_t var nulls = []string{"~", "null", "Null", "NULL"} BeforeEach(func() { event = yaml_event_t{} }) Context("Resolve", func() { Context("Implicit events", func() { checkNulls := func(f func()) { for _, null := range nulls { event = yaml_event_t{implicit: true} event.value = []byte(null) f() } } BeforeEach(func() { event.implicit = true }) Context("String", func() { It("resolves a string", func() { aString := "" v := reflect.ValueOf(&aString) event.value = []byte("abc") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_STR_TAG)) Expect(aString).To(Equal("abc")) }) It("resolves the empty string", func() { aString := "abc" v := reflect.ValueOf(&aString) event.value = []byte("") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_STR_TAG)) Expect(aString).To(Equal("")) }) It("resolves null", func() { checkNulls(func() { aString := "abc" v := reflect.ValueOf(&aString) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(aString).To(Equal("")) }) }) It("resolves null pointers", func() { checkNulls(func() { aString := "abc" pString := &aString v := reflect.ValueOf(&pString) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(pString).To(BeNil()) }) }) }) Context("Booleans", func() { match_bool := func(val string, expected bool) { b := !expected v := reflect.ValueOf(&b) event.value = []byte(val) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_BOOL_TAG)) Expect(b).To(Equal(expected)) } It("resolves on", func() { match_bool("on", true) match_bool("ON", true) }) It("resolves off", func() { match_bool("off", false) match_bool("OFF", false) }) It("resolves true", func() { match_bool("true", true) match_bool("TRUE", true) }) It("resolves false", func() { match_bool("false", false) match_bool("FALSE", false) }) It("resolves yes", func() { match_bool("yes", true) match_bool("YES", true) }) It("resolves no", func() { match_bool("no", false) match_bool("NO", false) }) It("reports an error otherwise", func() { b := true v := reflect.ValueOf(&b) event.value = []byte("fail") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Invalid boolean: 'fail' at line 0, column 0")) }) It("resolves null", func() { checkNulls(func() { b := true v := reflect.ValueOf(&b) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(b).To(BeFalse()) }) }) It("resolves null pointers", func() { checkNulls(func() { b := true pb := &b v := reflect.ValueOf(&pb) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(pb).To(BeNil()) }) }) }) Context("Ints", func() { It("simple ints", func() { i := 0 v := reflect.ValueOf(&i) event.value = []byte("1234") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(1234)) }) It("positive ints", func() { i := int16(0) v := reflect.ValueOf(&i) event.value = []byte("+678") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(int16(678))) }) It("negative ints", func() { i := int32(0) v := reflect.ValueOf(&i) event.value = []byte("-2345") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(int32(-2345))) }) It("base 8", func() { i := 0 v := reflect.ValueOf(&i) event.value = []byte("0o12") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(10)) }) It("base 16", func() { i := 0 v := reflect.ValueOf(&i) event.value = []byte("0xff") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(255)) }) It("fails on overflow", func() { i := int8(0) v := reflect.ValueOf(&i) event.value = []byte("2345") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Invalid integer: '2345' at line 0, column 0")) }) It("fails on invalid int", func() { i := 0 v := reflect.ValueOf(&i) event.value = []byte("234f") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Invalid integer: '234f' at line 0, column 0")) }) It("resolves null", func() { checkNulls(func() { i := 1 v := reflect.ValueOf(&i) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(i).To(Equal(0)) }) }) It("resolves null pointers", func() { checkNulls(func() { i := 1 pi := &i v := reflect.ValueOf(&pi) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(pi).To(BeNil()) }) }) It("returns a Number", func() { var i Number v := reflect.ValueOf(&i) tag, err := resolve_int("12345", v.Elem(), true, event) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(Number("12345"))) Expect(i.Int64()).To(Equal(int64(12345))) event.value = []byte("1234") tag, err = resolve(event, v.Elem(), true) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(Number("1234"))) }) }) Context("UInts", func() { It("resolves simple uints", func() { i := uint(0) v := reflect.ValueOf(&i) event.value = []byte("1234") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(uint(1234))) }) It("resolves positive uints", func() { i := uint16(0) v := reflect.ValueOf(&i) event.value = []byte("+678") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(uint16(678))) }) It("base 8", func() { i := uint(0) v := reflect.ValueOf(&i) event.value = []byte("0o12") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(uint(10))) }) It("base 16", func() { i := uint(0) v := reflect.ValueOf(&i) event.value = []byte("0xff") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(uint(255))) }) It("fails with negative ints", func() { i := uint(0) v := reflect.ValueOf(&i) event.value = []byte("-2345") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Unsigned int with negative value: '-2345' at line 0, column 0")) }) It("fails on overflow", func() { i := uint8(0) v := reflect.ValueOf(&i) event.value = []byte("2345") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Invalid unsigned integer: '2345' at line 0, column 0")) }) It("resolves null", func() { checkNulls(func() { i := uint(1) v := reflect.ValueOf(&i) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(i).To(Equal(uint(0))) }) }) It("resolves null pointers", func() { checkNulls(func() { i := uint(1) pi := &i v := reflect.ValueOf(&pi) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(pi).To(BeNil()) }) }) It("returns a Number", func() { var i Number v := reflect.ValueOf(&i) tag, err := resolve_uint("12345", v.Elem(), true, event) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(Number("12345"))) event.value = []byte("1234") tag, err = resolve(event, v.Elem(), true) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_INT_TAG)) Expect(i).To(Equal(Number("1234"))) }) }) Context("Floats", func() { It("float32", func() { f := float32(0) v := reflect.ValueOf(&f) event.value = []byte("2345.01") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(f).To(Equal(float32(2345.01))) }) It("float64", func() { f := float64(0) v := reflect.ValueOf(&f) event.value = []byte("-456456.01") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(f).To(Equal(float64(-456456.01))) }) It("+inf", func() { f := float64(0) v := reflect.ValueOf(&f) event.value = []byte("+.inf") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(f).To(Equal(math.Inf(1))) }) It("-inf", func() { f := float32(0) v := reflect.ValueOf(&f) event.value = []byte("-.inf") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(f).To(Equal(float32(math.Inf(-1)))) }) It("nan", func() { f := float64(0) v := reflect.ValueOf(&f) event.value = []byte(".NaN") tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(math.IsNaN(f)).To(BeTrue()) }) It("fails on overflow", func() { i := float32(0) v := reflect.ValueOf(&i) event.value = []byte("123e10000") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Invalid float: '123e10000' at line 0, column 0")) }) It("fails on invalid float", func() { i := float32(0) v := reflect.ValueOf(&i) event.value = []byte("123e1a") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Invalid float: '123e1a' at line 0, column 0")) }) It("resolves null", func() { checkNulls(func() { f := float64(1) v := reflect.ValueOf(&f) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(f).To(Equal(0.0)) }) }) It("resolves null pointers", func() { checkNulls(func() { f := float64(1) pf := &f v := reflect.ValueOf(&pf) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(pf).To(BeNil()) }) }) It("returns a Number", func() { var i Number v := reflect.ValueOf(&i) tag, err := resolve_float("12.345", v.Elem(), true, event) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(i).To(Equal(Number("12.345"))) Expect(i.Float64()).To(Equal(12.345)) event.value = []byte("1.234") tag, err = resolve(event, v.Elem(), true) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_FLOAT_TAG)) Expect(i).To(Equal(Number("1.234"))) }) }) Context("Timestamps", func() { parse_date := func(val string, date time.Time) { d := time.Now() v := reflect.ValueOf(&d) event.value = []byte(val) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal("")) Expect(d).To(Equal(date)) } It("date", func() { parse_date("2002-12-14", time.Date(2002, time.December, 14, 0, 0, 0, 0, time.UTC)) }) It("canonical", func() { parse_date("2001-12-15T02:59:43.1Z", time.Date(2001, time.December, 15, 2, 59, 43, int(1*time.Millisecond), time.UTC)) }) It("iso8601", func() { parse_date("2001-12-14t21:59:43.10-05:00", time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600))) }) It("space separated", func() { parse_date("2001-12-14 21:59:43.10 -5", time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600))) }) It("no time zone", func() { parse_date("2001-12-15 2:59:43.10", time.Date(2001, time.December, 15, 2, 59, 43, int(10*time.Millisecond), time.UTC)) }) It("resolves null", func() { checkNulls(func() { d := time.Now() v := reflect.ValueOf(&d) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(d).To(Equal(time.Time{})) }) }) It("resolves null pointers", func() { checkNulls(func() { d := time.Now() pd := &d v := reflect.ValueOf(&pd) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_NULL_TAG)) Expect(pd).To(BeNil()) }) }) }) Context("Binary tag", func() { It("string", func() { checkNulls(func() { event.value = []byte("YWJjZGVmZw==") event.tag = []byte("!binary") aString := "" v := reflect.ValueOf(&aString) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_STR_TAG)) Expect(aString).To(Equal("abcdefg")) }) }) It("[]byte", func() { checkNulls(func() { event.value = []byte("YWJjZGVmZw==") event.tag = []byte("!binary") bytes := []byte(nil) v := reflect.ValueOf(&bytes) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_STR_TAG)) Expect(bytes).To(Equal([]byte("abcdefg"))) }) }) It("returns a []byte when provided no hints", func() { checkNulls(func() { event.value = []byte("YWJjZGVmZw==") event.tag = []byte("!binary") var intf interface{} v := reflect.ValueOf(&intf) tag, err := resolve(event, v.Elem(), false) Expect(err).NotTo(HaveOccurred()) Expect(tag).To(Equal(yaml_STR_TAG)) Expect(intf).To(Equal([]byte("abcdefg"))) }) }) }) It("fails to resolve a pointer", func() { aString := "" pString := &aString v := reflect.ValueOf(&pString) event.value = []byte("abc") _, err := resolve(event, v.Elem(), false) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(Equal("Unknown resolution for 'abc' using <*string Value> at line 0, column 0")) }) }) Context("Not an implicit event && no tag", func() { It("bool returns a string", func() { event.value = []byte("on") tag, result := resolveInterface(event, false) Expect(result).To(Equal("on")) Expect(tag).To(Equal("")) }) It("number returns a string", func() { event.value = []byte("1234") tag, result := resolveInterface(event, false) Expect(result).To(Equal("1234")) Expect(tag).To(Equal("")) }) It("returns the empty string", func() { event.value = []byte("") // event.implicit = true tag, result := resolveInterface(event, false) Expect(result).To(Equal("")) Expect(tag).To(Equal("")) }) }) }) }) ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/run_parser.go ================================================ /* 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 candiedyaml import ( "fmt" "os" ) func Run_parser(cmd string, args []string) { for i := 0; i < len(args); i++ { fmt.Printf("[%d] Scanning '%s'", i, args[i]) file, err := os.Open(args[i]) if err != nil { panic(fmt.Sprintf("Invalid file '%s': %s", args[i], err.Error())) } parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_reader(&parser, file) failed := false token := yaml_token_t{} count := 0 for { if !yaml_parser_scan(&parser, &token) { failed = true break } if token.token_type == yaml_STREAM_END_TOKEN { break } count++ } file.Close() msg := "SUCCESS" if failed { msg = "FAILED" if parser.error != yaml_NO_ERROR { m := parser.problem_mark fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n", parser.context, parser.problem, m.line, m.column) } } fmt.Printf("%s (%d tokens)\n", msg, count) } } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/scanner.go ================================================ /* 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 candiedyaml import ( "bytes" ) /* * 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 1 on success, 0 on failure (reader error or memory error). */ func cache(parser *yaml_parser_t, length int) bool { if parser.unread >= length { return true } return 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_at(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_at(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 if buf[pos] == '\r' && buf[pos+1] == '\n' { /* CR LF . LF */ s = append(s, '\n') parser.buffer_pos += 2 parser.mark.index++ parser.unread-- } else if buf[pos] == '\r' || buf[pos] == '\n' { /* CR|LF . LF */ s = append(s, '\n') parser.buffer_pos += 1 } else if buf[pos] == '\xC2' && buf[pos+1] == '\x85' { /* NEL . LF */ s = append(s, '\n') parser.buffer_pos += 2 } else if 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 } else { 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{} /* 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.token_available = false parser.tokens_parsed++ if token.token_type == yaml_STREAM_END_TOKEN { parser.stream_end_produced = true } return true } /* * Set the scanner error and return 0. */ 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 directive" if directive { context = "while parsing a tag" } return yaml_parser_set_scanner_error(parser, context, context_mark, "did not find URI escaped octet") } /* * 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 } } } if len(parser.simple_keys) > 0 { } /* 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 !cache(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 !cache(parser, 4) { return false } /* Is it the end of the stream? */ buf := parser.buffer pos := parser.buffer_pos if is_z(buf[pos]) { return yaml_parser_fetch_stream_end(parser) } /* Is it a directive? */ if parser.mark.column == 0 && buf[pos] == '%' { return yaml_parser_fetch_directive(parser) } /* Is it the document start indicator? */ if parser.mark.column == 0 && buf[pos] == '-' && buf[pos+1] == '-' && buf[pos+2] == '-' && is_blankz_at(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_at(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 buf[pos] == '{' { return yaml_parser_fetch_flow_collection_start(parser, yaml_FLOW_MAPPING_START_TOKEN) } /* Is it the flow sequence end indicator? */ if buf[pos] == ']' { return yaml_parser_fetch_flow_collection_end(parser, yaml_FLOW_SEQUENCE_END_TOKEN) } /* Is it the flow mapping end indicator? */ if buf[pos] == '}' { return yaml_parser_fetch_flow_collection_end(parser, yaml_FLOW_MAPPING_END_TOKEN) } /* Is it the flow entry indicator? */ if buf[pos] == ',' { return yaml_parser_fetch_flow_entry(parser) } /* Is it the block entry indicator? */ if buf[pos] == '-' && is_blankz_at(buf, pos+1) { return yaml_parser_fetch_block_entry(parser) } /* Is it the key indicator? */ if buf[pos] == '?' && (parser.flow_level > 0 || is_blankz_at(buf, pos+1)) { return yaml_parser_fetch_key(parser) } /* Is it the value indicator? */ if buf[pos] == ':' && (parser.flow_level > 0 || is_blankz_at(buf, pos+1)) { return yaml_parser_fetch_value(parser) } /* Is it an alias? */ if buf[pos] == '*' { return yaml_parser_fetch_anchor(parser, yaml_ALIAS_TOKEN) } /* Is it an anchor? */ if buf[pos] == '&' { return yaml_parser_fetch_anchor(parser, yaml_ANCHOR_TOKEN) } /* Is it a tag? */ if buf[pos] == '!' { return yaml_parser_fetch_tag(parser) } /* Is it a literal scalar? */ if buf[pos] == '|' && parser.flow_level == 0 { return yaml_parser_fetch_block_scalar(parser, true) } /* Is it a folded scalar? */ if buf[pos] == '>' && parser.flow_level == 0 { return yaml_parser_fetch_block_scalar(parser, false) } /* Is it a single-quoted scalar? */ if buf[pos] == '\'' { return yaml_parser_fetch_flow_scalar(parser, true) } /* Is it a double-quoted scalar? */ if buf[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. */ b := buf[pos] if !(is_blankz_at(buf, pos) || b == '-' || b == '?' || b == ':' || b == ',' || b == '[' || b == ']' || b == '{' || b == '}' || b == '#' || b == '&' || b == '*' || b == '!' || b == '|' || b == '>' || b == '\'' || b == '"' || b == '%' || b == '@' || b == '`') || (b == '-' && !is_blank(buf[pos+1])) || (parser.flow_level == 0 && (buf[pos] == '?' || buf[pos] == ':') && !is_blank(buf[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 { /* * The specification requires that a simple key * * - is limited to a single line, * - is shorter than 1024 characters. */ simple_key := &parser.simple_keys[i] 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("impossible") /* Impossible. */ } /* * 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 { simple_key := &parser.simple_keys[len(parser.simple_keys)-1] if simple_key.possible { /* If the key is required, it is an error. */ if simple_key.required { return yaml_parser_set_scanner_error(parser, "while scanning a simple key", simple_key.mark, "could not find expected ':'") } } /* Remove the key from the stack. */ simple_key.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 int, number int, token_type 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 == -1 || 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{ token_type: token_type, start_mark: mark, end_mark: mark, } // number == -1 -> enqueue otherwise insert if number > -1 { number -= parser.tokens_parsed } 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 } /* * column is unsigned and parser->indent is signed, so if * parser->indent is less than zero the conditional in the while * loop below is incorrect. Guard against that. */ if parser.indent < 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{ token_type: yaml_BLOCK_END_TOKEN, start_mark: parser.mark, end_mark: parser.mark, } 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 } /* * Pop indentation levels from the indents stack until the current * level resets to -1. For each indentation level, append the * BLOCK-END token. */ func yaml_parser_reset_indent(parser *yaml_parser_t) 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 > -1 { /* Create a token and append it to the queue. */ token := yaml_token_t{ token_type: yaml_BLOCK_END_TOKEN, start_mark: parser.mark, end_mark: parser.mark, } 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{ token_type: yaml_STREAM_START_TOKEN, start_mark: parser.mark, end_mark: parser.mark, encoding: parser.encoding, } 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_reset_indent(parser) { 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{ token_type: yaml_STREAM_END_TOKEN, start_mark: parser.mark, end_mark: parser.mark, } 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_reset_indent(parser) { 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. */ var token yaml_token_t if !yaml_parser_scan_directive(parser, &token) { return false } /* Append the token to the queue. */ 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, token_type yaml_token_type_t) bool { /* Reset the indentation level. */ if !yaml_parser_reset_indent(parser) { 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{ token_type: token_type, start_mark: start_mark, end_mark: end_mark, } /* Append the token to the queue. */ 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, token_type 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{ token_type: token_type, start_mark: start_mark, end_mark: end_mark, } /* Append the token to the queue. */ 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, token_type 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{ token_type: token_type, start_mark: start_mark, end_mark: end_mark, } /* Append the token to the queue. */ 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{ token_type: yaml_FLOW_ENTRY_TOKEN, start_mark: start_mark, end_mark: end_mark, } 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{ token_type: yaml_BLOCK_ENTRY_TOKEN, start_mark: start_mark, end_mark: end_mark, } 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{ token_type: yaml_KEY_TOKEN, start_mark: start_mark, end_mark: end_mark, } 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{ token_type: yaml_KEY_TOKEN, start_mark: simple_key.mark, end_mark: simple_key.mark, } 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{ token_type: yaml_VALUE_TOKEN, start_mark: start_mark, end_mark: end_mark, } insert_token(parser, -1, &token) return true } /* * Produce the ALIAS or ANCHOR token. */ func yaml_parser_fetch_anchor(parser *yaml_parser_t, token_type 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, token_type) { return false } 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 } 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 } 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 } 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 } 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 !cache(parser, 1) { return false } if parser.mark.column == 0 && is_bom_at(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 !cache(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 !cache(parser, 1) { return false } } /* Eat a comment until a line break. */ if parser.buffer[parser.buffer_pos] == '#' { for !is_breakz_at(parser.buffer, parser.buffer_pos) { skip(parser) if !cache(parser, 1) { return false } } } /* If it is a line break, eat it. */ if is_break_at(parser.buffer, parser.buffer_pos) { if !cache(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 { /* We have found a token. */ break } } 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? */ var major, minor int if bytes.Equal(name, []byte("YAML")) { /* Scan the VERSION directive value. */ 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{ token_type: yaml_VERSION_DIRECTIVE_TOKEN, start_mark: start_mark, end_mark: end_mark, major: major, minor: minor, } } else if bytes.Equal(name, []byte("TAG")) { /* Is it a TAG directive? */ /* 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{ token_type: yaml_TAG_DIRECTIVE_TOKEN, start_mark: start_mark, end_mark: end_mark, value: handle, prefix: prefix, } } else { /* Unknown directive. */ yaml_parser_set_scanner_error(parser, "while scanning a directive", start_mark, "found uknown directive name") return false } /* Eat the rest of the line including any comments. */ if !cache(parser, 1) { return false } for is_blank(parser.buffer[parser.buffer_pos]) { skip(parser) if !cache(parser, 1) { return false } } if parser.buffer[parser.buffer_pos] == '#' { for !is_breakz_at(parser.buffer, parser.buffer_pos) { skip(parser) if !cache(parser, 1) { return false } } } /* Check if we are at the end of the line. */ if !is_breakz_at(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_at(parser.buffer, parser.buffer_pos) { if !cache(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 !cache(parser, 1) { return false } var s []byte for is_alpha(parser.buffer[parser.buffer_pos]) { s = read(parser, s) if !cache(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_at(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 *int, minor *int) bool { /* Eat whitespaces. */ if !cache(parser, 1) { return false } for is_blank(parser.buffer[parser.buffer_pos]) { skip(parser) if !cache(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 = 9 /* * 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 *int) bool { /* Repeat while the next character is digit. */ if !cache(parser, 1) { return false } value := 0 length := 0 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 + as_digit(parser.buffer[parser.buffer_pos]) skip(parser) if !cache(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 { /* Eat whitespaces. */ if !cache(parser, 1) { return false } for is_blank(parser.buffer[parser.buffer_pos]) { skip(parser) if !cache(parser, 1) { return false } } /* Scan a handle. */ var handle_value []byte if !yaml_parser_scan_tag_handle(parser, true, start_mark, &handle_value) { return false } /* Expect a whitespace. */ if !cache(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 !cache(parser, 1) { return false } } /* Scan a prefix. */ var prefix_value []byte if !yaml_parser_scan_tag_uri(parser, true, nil, start_mark, &prefix_value) { return false } /* Expect a whitespace or line break. */ if !cache(parser, 1) { return false } if !is_blankz_at(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, token_type yaml_token_type_t) bool { /* Eat the indicator character. */ start_mark := parser.mark skip(parser) /* Consume the value. */ if !cache(parser, 1) { return false } var s []byte for is_alpha(parser.buffer[parser.buffer_pos]) { s = read(parser, s) if !cache(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: * * '?', ':', ',', ']', '}', '%', '@', '`'. */ b := parser.buffer[parser.buffer_pos] if len(s) == 0 || !(is_blankz_at(parser.buffer, parser.buffer_pos) || b == '?' || b == ':' || b == ',' || b == ']' || b == '}' || b == '%' || b == '@' || b == '`') { context := "while scanning an anchor" if token_type != yaml_ANCHOR_TOKEN { context = "while scanning an alias" } 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{ token_type: token_type, 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 { start_mark := parser.mark /* Check if the tag is in the canonical form. */ if !cache(parser, 2) { return false } var handle []byte var suffix []byte if parser.buffer[parser.buffer_pos+1] == '<' { /* Set the handle to '' */ /* 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 if is_blank(parser.buffer[parser.buffer_pos+1]) { // NON-SPECIFIED 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 !cache(parser, 1) { return false } if !is_blankz_at(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{ token_type: 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 !cache(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 } /* Copy the '!' character. */ var s []byte s = read(parser, s) /* Copy all subsequent alphabetical and numerical characters. */ if !cache(parser, 1) { return false } for is_alpha(parser.buffer[parser.buffer_pos]) { s = read(parser, s) if !cache(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] == '!' && len(s) == 1) { 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 { 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 !cache(parser, 1) { return false } /* * The set of characters that may appear in URI is as follows: * * '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', * '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', * '%'. */ b := parser.buffer[parser.buffer_pos] for is_alpha(b) || b == ';' || b == '/' || b == '?' || b == ':' || b == '@' || b == '&' || b == '=' || b == '+' || b == '$' || b == ',' || b == '.' || b == '!' || b == '~' || b == '*' || b == '\'' || b == '(' || b == ')' || b == '[' || b == ']' || b == '%' { /* Check if it is a URI-escape sequence. */ if b == '%' { if !yaml_parser_scan_uri_escapes(parser, directive, start_mark, &s) { return false } } else { s = read(parser, s) } if !cache(parser, 1) { return false } b = parser.buffer[parser.buffer_pos] } /* 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 := 10 for w > 0 { /* Check for a URI-escaped octet. */ if !cache(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 == 10 { 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 !cache(parser, 1) { return false } /* Check for a chomping indicator. */ chomping := 0 increment := 0 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 !cache(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 !cache(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 !cache(parser, 1) { return false } for is_blank(parser.buffer[parser.buffer_pos]) { skip(parser) if !cache(parser, 1) { return false } } if parser.buffer[parser.buffer_pos] == '#' { for !is_breakz_at(parser.buffer, parser.buffer_pos) { skip(parser) if !cache(parser, 1) { return false } } } /* Check if we are at the end of the line. */ if !is_breakz_at(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_at(parser.buffer, parser.buffer_pos) { if !cache(parser, 2) { return false } skip_line(parser) } end_mark := parser.mark /* Set the indentation level if it was specified. */ indent := 0 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 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 !cache(parser, 1) { return false } var s []byte var leading_break []byte leading_blank := false trailing_blank := false 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 && len(leading_break) > 0 && leading_break[0] == '\n' && !leading_blank && !trailing_blank { /* Do we need to join the lines by space? */ if len(trailing_breaks) == 0 { s = append(s, ' ') } leading_break = leading_break[:0] } 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_at(parser.buffer, parser.buffer_pos) { s = read(parser, s) if !cache(parser, 1) { return false } } /* Consume the line break. */ if !cache(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{ token_type: 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 !cache(parser, 1) { return false } for (*indent == 0 || parser.mark.column < *indent) && is_space(parser.buffer[parser.buffer_pos]) { skip(parser) if !cache(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_at(parser.buffer, parser.buffer_pos) { break } /* Consume the line break. */ if !cache(parser, 2) { return false } *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 []byte var leading_break []byte var trailing_breaks []byte var whitespaces []byte for { /* Check that there are no document indicators at the beginning of the line. */ if !cache(parser, 4) { return false } if parser.mark.column == 0 && ((parser.buffer[parser.buffer_pos] == '-' && parser.buffer[parser.buffer_pos+1] == '-' && parser.buffer[parser.buffer_pos+2] == '-') || (parser.buffer[parser.buffer_pos] == '.' && parser.buffer[parser.buffer_pos+1] == '.' && parser.buffer[parser.buffer_pos+2] == '.')) && is_blankz_at(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. */ if !cache(parser, 2) { return false } leading_blanks := false for !is_blankz_at(parser.buffer, parser.buffer_pos) { /* Check for an escaped single quote. */ 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] == '\'' { /* Check for the right quote. */ break } else if !single && parser.buffer[parser.buffer_pos] == '"' { /* Check for the right quote. */ break } else if !single && parser.buffer[parser.buffer_pos] == '\\' && is_break_at(parser.buffer, parser.buffer_pos+1) { /* Check for an escaped line break. */ if !cache(parser, 3) { return false } skip(parser) skip_line(parser) leading_blanks = true break } else if !single && parser.buffer[parser.buffer_pos] == '\\' { /* Check for 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 { value := 0 /* Scan the character value. */ if !cache(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 !cache(parser, 2) { return false } } /* Check if we are at the end of the scalar. */ b := parser.buffer[parser.buffer_pos] if single { if b == '\'' { break } } else if b == '"' { break } /* Consume blank characters. */ if !cache(parser, 1) { return false } for is_blank(parser.buffer[parser.buffer_pos]) || is_break_at(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 !cache(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 !cache(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...) trailing_breaks = trailing_breaks[:0] } leading_break = leading_break[:0] } else { s = append(s, leading_break...) s = append(s, trailing_breaks...) leading_break = leading_break[:0] trailing_breaks = trailing_breaks[: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{ token_type: 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 []byte var leading_break []byte var trailing_breaks []byte var whitespaces []byte leading_blanks := false 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 !cache(parser, 4) { return false } if parser.mark.column == 0 && ((parser.buffer[parser.buffer_pos] == '-' && parser.buffer[parser.buffer_pos+1] == '-' && parser.buffer[parser.buffer_pos+2] == '-') || (parser.buffer[parser.buffer_pos] == '.' && parser.buffer[parser.buffer_pos+1] == '.' && parser.buffer[parser.buffer_pos+2] == '.')) && is_blankz_at(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_at(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_at(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. */ b := parser.buffer[parser.buffer_pos] if (b == ':' && is_blankz_at(parser.buffer, parser.buffer_pos+1)) || (parser.flow_level > 0 && (b == ',' || b == ':' || b == '?' || b == '[' || b == ']' || b == '{' || b == '}')) { 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...) trailing_breaks = trailing_breaks[:0] } leading_break = leading_break[:0] } else { s = append(s, leading_break...) s = append(s, trailing_breaks...) leading_break = leading_break[:0] trailing_breaks = trailing_breaks[:0] } leading_blanks = false } else { s = append(s, whitespaces...) whitespaces = whitespaces[:0] } } /* Copy the character. */ s = read(parser, s) end_mark = parser.mark if !cache(parser, 2) { return false } } /* Is it the end? */ if !(is_blank(parser.buffer[parser.buffer_pos]) || is_break_at(parser.buffer, parser.buffer_pos)) { break } /* Consume blank characters. */ if !cache(parser, 1) { return false } for is_blank(parser.buffer[parser.buffer_pos]) || is_break_at(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 !cache(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 !cache(parser, 1) { return false } } /* Check indentation level. */ if parser.flow_level == 0 && parser.mark.column < indent { break } } /* Create a token. */ *token = yaml_token_t{ token_type: 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 } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/scanner_test.go ================================================ /* 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 candiedyaml import ( "io/ioutil" "os" "path/filepath" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var scan = func(filename string) { It("scan "+filename, func() { file, err := os.Open(filename) Expect(err).To(BeNil()) parser := yaml_parser_t{} yaml_parser_initialize(&parser) yaml_parser_set_input_reader(&parser, file) failed := false token := yaml_token_t{} for { if !yaml_parser_scan(&parser, &token) { failed = true break } if token.token_type == yaml_STREAM_END_TOKEN { break } } file.Close() // msg := "SUCCESS" // if failed { // msg = "FAILED" // if parser.error != yaml_NO_ERROR { // m := parser.problem_mark // fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n", // parser.context, parser.problem, m.line, m.column) // } // } Expect(failed).To(BeFalse()) }) } var scanYamls = func(dirname string) { fileInfos, err := ioutil.ReadDir(dirname) if err != nil { panic(err.Error()) } for _, fileInfo := range fileInfos { if !fileInfo.IsDir() { scan(filepath.Join(dirname, fileInfo.Name())) } } } var _ = Describe("Scanner", func() { scanYamls("fixtures/specification") scanYamls("fixtures/specification/types") }) ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/tags.go ================================================ /* 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 candiedyaml import ( "reflect" "sort" "strings" "sync" "unicode" ) // A field represents a single field found in a struct. type field struct { name string tag bool index []int typ reflect.Type omitEmpty bool flow bool } // 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 != "" { // unexported continue } tag := sf.Tag.Get("yaml") 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() } // 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, opts.Contains("omitempty"), opts.Contains("flow")}) 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, 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) } } 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 // 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 } 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 } // 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 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 { av, ak := getElem(sv[i]) bv, bk := getElem(sv[j]) if ak == reflect.String && bk == reflect.String { return av.String() < bv.String() } return ak < bk } func getElem(v reflect.Value) (reflect.Value, reflect.Kind) { k := v.Kind() for k == reflect.Interface || k == reflect.Ptr && !v.IsNil() { v = v.Elem() k = v.Kind() } return v, k } // 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 } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/writer.go ================================================ /* 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 candiedyaml /* * Set the writer error and return 0. */ 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 must be set") /* Write handler must be set. */ } if emitter.encoding == yaml_ANY_ENCODING { panic("Encoding must be set") /* Output encoding must be 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. */ // 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 } ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/yaml_definesh.go ================================================ /* 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 candiedyaml const ( yaml_VERSION_MAJOR = 0 yaml_VERSION_MINOR = 1 yaml_VERSION_PATCH = 6 yaml_VERSION_STRING = "0.1.6" ) ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/yaml_privateh.go ================================================ /* 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 candiedyaml const ( INPUT_RAW_BUFFER_SIZE = 1024 /* * 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 = 512 /* * 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) INITIAL_STACK_SIZE = 16 INITIAL_QUEUE_SIZE = 16 ) func width(b byte) int { if b&0x80 == 0 { return 1 } if b&0xE0 == 0xC0 { return 2 } if b&0xF0 == 0xE0 { return 3 } if b&0xF8 == 0xF0 { return 4 } return 0 } func copy_bytes(dest []byte, dest_pos *int, src []byte, src_pos *int) { w := width(src[*src_pos]) switch w { case 4: dest[*dest_pos+3] = src[*src_pos+3] fallthrough case 3: dest[*dest_pos+2] = src[*src_pos+2] fallthrough case 2: dest[*dest_pos+1] = src[*src_pos+1] fallthrough case 1: dest[*dest_pos] = src[*src_pos] default: panic("invalid width") } *dest_pos += w *src_pos += w } // /* // * Check if the character at the specified position is an alphabetical // * character, a digit, '_', or '-'. // */ func is_alpha(b byte) bool { return (b >= '0' && b <= '9') || (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || b == '_' || b == '-' } // /* // * Check if the character at the specified position is a digit. // */ // func is_digit(b byte) bool { return b >= '0' && b <= '9' } // /* // * Get the value of a digit. // */ // func as_digit(b byte) int { return int(b) - '0' } // /* // * Check if the character at the specified position is a hex-digit. // */ // func is_hex(b byte) bool { return (b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f') } // // /* // * Get the value of a hex-digit. // */ // func as_hex(b byte) int { if b >= 'A' && b <= 'F' { return int(b) - 'A' + 10 } else if b >= 'a' && b <= 'f' { return int(b) - 'a' + 10 } return int(b) - '0' } // #define AS_HEX_AT(string,offset) \ // (((string).pointer[offset] >= (yaml_char_t) 'A' && \ // (string).pointer[offset] <= (yaml_char_t) 'F') ? \ // ((string).pointer[offset] - (yaml_char_t) 'A' + 10) : \ // ((string).pointer[offset] >= (yaml_char_t) 'a' && \ // (string).pointer[offset] <= (yaml_char_t) 'f') ? \ // ((string).pointer[offset] - (yaml_char_t) 'a' + 10) : \ // ((string).pointer[offset] - (yaml_char_t) '0')) // /* // * Check if the character is a line break, space, tab, or NUL. // */ func is_blankz_at(b []byte, i int) bool { return is_blank(b[i]) || is_breakz_at(b, i) } // /* // * Check if the character at the specified position is a line break. // */ func is_break_at(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_breakz_at(b []byte, i int) bool { return is_break_at(b, i) || is_z(b[i]) } func is_crlf_at(b []byte, i int) bool { return b[i] == '\r' && b[i+1] == '\n' } // /* // * Check if the character at the specified position is NUL. // */ func is_z(b byte) bool { return b == 0x0 } // /* // * Check if the character at the specified position is space. // */ func is_space(b byte) bool { return b == ' ' } // // /* // * Check if the character at the specified position is tab. // */ func is_tab(b byte) bool { return b == '\t' } // /* // * Check if the character at the specified position is blank (space or tab). // */ func is_blank(b byte) bool { return is_space(b) || is_tab(b) } // /* // * Check if the character is ASCII. // */ func is_ascii(b byte) bool { return b <= '\x7f' } // /* // * Check if the character can be printed unescaped. // */ func is_printable_at(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 && /* && . != #xFEFF */ !(b[i+1] == 0xBB && b[i+2] == 0xBF) && !(b[i+1] == 0xBF && (b[i+2] == 0xBE || b[i+2] == 0xBF)))) } func insert_token(parser *yaml_parser_t, pos int, token *yaml_token_t) { // collapse the slice if parser.tokens_head > 0 && len(parser.tokens) == cap(parser.tokens) { if parser.tokens_head != len(parser.tokens) { // move the tokens down copy(parser.tokens, parser.tokens[parser.tokens_head:]) } // readjust the length 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 } // /* // * Check if the character at the specified position is BOM. // */ // func is_bom_at(b []byte, i int) bool { return b[i] == 0xEF && b[i+1] == 0xBB && b[i+2] == 0xBF } // // #ifdef HAVE_CONFIG_H // #include // #endif // // #include "./yaml.h" // // #include // #include // // /* // * Memory management. // */ // // yaml_DECLARE(void *) // yaml_malloc(size_t size); // // yaml_DECLARE(void *) // yaml_realloc(void *ptr, size_t size); // // yaml_DECLARE(void) // yaml_free(void *ptr); // // yaml_DECLARE(yaml_char_t *) // yaml_strdup(const yaml_char_t *); // // /* // * Reader: Ensure that the buffer contains at least `length` characters. // */ // // yaml_DECLARE(int) // yaml_parser_update_buffer(yaml_parser_t *parser, size_t length); // // /* // * Scanner: Ensure that the token stack contains at least one token ready. // */ // // yaml_DECLARE(int) // yaml_parser_fetch_more_tokens(yaml_parser_t *parser); // // /* // * The size of the input raw buffer. // */ // // #define INPUT_RAW_BUFFER_SIZE 16384 // // /* // * The size of the input buffer. // * // * It should be possible to decode the whole raw buffer. // */ // // #define INPUT_BUFFER_SIZE (INPUT_RAW_BUFFER_SIZE*3) // // /* // * The size of the output buffer. // */ // // #define OUTPUT_BUFFER_SIZE 16384 // // /* // * The size of the output raw buffer. // * // * It should be possible to encode the whole output buffer. // */ // // #define OUTPUT_RAW_BUFFER_SIZE (OUTPUT_BUFFER_SIZE*2+2) // // /* // * The size of other stacks and queues. // */ // // #define INITIAL_STACK_SIZE 16 // #define INITIAL_QUEUE_SIZE 16 // #define INITIAL_STRING_SIZE 16 // // /* // * Buffer management. // */ // // #define BUFFER_INIT(context,buffer,size) \ // (((buffer).start = yaml_malloc(size)) ? \ // ((buffer).last = (buffer).pointer = (buffer).start, \ // (buffer).end = (buffer).start+(size), \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // #define BUFFER_DEL(context,buffer) \ // (yaml_free((buffer).start), \ // (buffer).start = (buffer).pointer = (buffer).end = 0) // // /* // * String management. // */ // // typedef struct { // yaml_char_t *start; // yaml_char_t *end; // yaml_char_t *pointer; // } yaml_string_t; // // yaml_DECLARE(int) // yaml_string_extend(yaml_char_t **start, // yaml_char_t **pointer, yaml_char_t **end); // // yaml_DECLARE(int) // yaml_string_join( // yaml_char_t **a_start, yaml_char_t **a_pointer, yaml_char_t **a_end, // yaml_char_t **b_start, yaml_char_t **b_pointer, yaml_char_t **b_end); // // #define NULL_STRING { NULL, NULL, NULL } // // #define STRING(string,length) { (string), (string)+(length), (string) } // // #define STRING_ASSIGN(value,string,length) \ // ((value).start = (string), \ // (value).end = (string)+(length), \ // (value).pointer = (string)) // // #define STRING_INIT(context,string,size) \ // (((string).start = yaml_malloc(size)) ? \ // ((string).pointer = (string).start, \ // (string).end = (string).start+(size), \ // memset((string).start, 0, (size)), \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // #define STRING_DEL(context,string) \ // (yaml_free((string).start), \ // (string).start = (string).pointer = (string).end = 0) // // #define STRING_EXTEND(context,string) \ // (((string).pointer+5 < (string).end) \ // || yaml_string_extend(&(string).start, \ // &(string).pointer, &(string).end)) // // #define CLEAR(context,string) \ // ((string).pointer = (string).start, \ // memset((string).start, 0, (string).end-(string).start)) // // #define JOIN(context,string_a,string_b) \ // ((yaml_string_join(&(string_a).start, &(string_a).pointer, \ // &(string_a).end, &(string_b).start, \ // &(string_b).pointer, &(string_b).end)) ? \ // ((string_b).pointer = (string_b).start, \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // /* // * String check operations. // */ // // /* // * Check the octet at the specified position. // */ // // #define CHECK_AT(string,octet,offset) \ // ((string).pointer[offset] == (yaml_char_t)(octet)) // // /* // * Check the current octet in the buffer. // */ // // #define CHECK(string,octet) CHECK_AT((string),(octet),0) // // /* // * Check if the character at the specified position is an alphabetical // * character, a digit, '_', or '-'. // */ // // #define IS_ALPHA_AT(string,offset) \ // (((string).pointer[offset] >= (yaml_char_t) '0' && \ // (string).pointer[offset] <= (yaml_char_t) '9') || \ // ((string).pointer[offset] >= (yaml_char_t) 'A' && \ // (string).pointer[offset] <= (yaml_char_t) 'Z') || \ // ((string).pointer[offset] >= (yaml_char_t) 'a' && \ // (string).pointer[offset] <= (yaml_char_t) 'z') || \ // (string).pointer[offset] == '_' || \ // (string).pointer[offset] == '-') // // #define IS_ALPHA(string) IS_ALPHA_AT((string),0) // // /* // * Check if the character at the specified position is a digit. // */ // // #define IS_DIGIT_AT(string,offset) \ // (((string).pointer[offset] >= (yaml_char_t) '0' && \ // (string).pointer[offset] <= (yaml_char_t) '9')) // // #define IS_DIGIT(string) IS_DIGIT_AT((string),0) // // /* // * Get the value of a digit. // */ // // #define AS_DIGIT_AT(string,offset) \ // ((string).pointer[offset] - (yaml_char_t) '0') // // #define AS_DIGIT(string) AS_DIGIT_AT((string),0) // // /* // * Check if the character at the specified position is a hex-digit. // */ // // #define IS_HEX_AT(string,offset) \ // (((string).pointer[offset] >= (yaml_char_t) '0' && \ // (string).pointer[offset] <= (yaml_char_t) '9') || \ // ((string).pointer[offset] >= (yaml_char_t) 'A' && \ // (string).pointer[offset] <= (yaml_char_t) 'F') || \ // ((string).pointer[offset] >= (yaml_char_t) 'a' && \ // (string).pointer[offset] <= (yaml_char_t) 'f')) // // #define IS_HEX(string) IS_HEX_AT((string),0) // // /* // * Get the value of a hex-digit. // */ // // #define AS_HEX_AT(string,offset) \ // (((string).pointer[offset] >= (yaml_char_t) 'A' && \ // (string).pointer[offset] <= (yaml_char_t) 'F') ? \ // ((string).pointer[offset] - (yaml_char_t) 'A' + 10) : \ // ((string).pointer[offset] >= (yaml_char_t) 'a' && \ // (string).pointer[offset] <= (yaml_char_t) 'f') ? \ // ((string).pointer[offset] - (yaml_char_t) 'a' + 10) : \ // ((string).pointer[offset] - (yaml_char_t) '0')) // // #define AS_HEX(string) AS_HEX_AT((string),0) // // /* // * Check if the character is ASCII. // */ // // #define IS_ASCII_AT(string,offset) \ // ((string).pointer[offset] <= (yaml_char_t) '\x7F') // // #define IS_ASCII(string) IS_ASCII_AT((string),0) // // /* // * Check if the character can be printed unescaped. // */ // // #define IS_PRINTABLE_AT(string,offset) \ // (((string).pointer[offset] == 0x0A) /* . == #x0A */ \ // || ((string).pointer[offset] >= 0x20 /* #x20 <= . <= #x7E */ \ // && (string).pointer[offset] <= 0x7E) \ // || ((string).pointer[offset] == 0xC2 /* #0xA0 <= . <= #xD7FF */ \ // && (string).pointer[offset+1] >= 0xA0) \ // || ((string).pointer[offset] > 0xC2 \ // && (string).pointer[offset] < 0xED) \ // || ((string).pointer[offset] == 0xED \ // && (string).pointer[offset+1] < 0xA0) \ // || ((string).pointer[offset] == 0xEE) \ // || ((string).pointer[offset] == 0xEF /* #xE000 <= . <= #xFFFD */ \ // && !((string).pointer[offset+1] == 0xBB /* && . != #xFEFF */ \ // && (string).pointer[offset+2] == 0xBF) \ // && !((string).pointer[offset+1] == 0xBF \ // && ((string).pointer[offset+2] == 0xBE \ // || (string).pointer[offset+2] == 0xBF)))) // // #define IS_PRINTABLE(string) IS_PRINTABLE_AT((string),0) // // /* // * Check if the character at the specified position is NUL. // */ // // #define IS_Z_AT(string,offset) CHECK_AT((string),'\0',(offset)) // // #define IS_Z(string) IS_Z_AT((string),0) // // /* // * Check if the character at the specified position is BOM. // */ // // #define IS_BOM_AT(string,offset) \ // (CHECK_AT((string),'\xEF',(offset)) \ // && CHECK_AT((string),'\xBB',(offset)+1) \ // && CHECK_AT((string),'\xBF',(offset)+2)) /* BOM (#xFEFF) */ // // #define IS_BOM(string) IS_BOM_AT(string,0) // // /* // * Check if the character at the specified position is space. // */ // // #define IS_SPACE_AT(string,offset) CHECK_AT((string),' ',(offset)) // // #define IS_SPACE(string) IS_SPACE_AT((string),0) // // /* // * Check if the character at the specified position is tab. // */ // // #define IS_TAB_AT(string,offset) CHECK_AT((string),'\t',(offset)) // // #define IS_TAB(string) IS_TAB_AT((string),0) // // /* // * Check if the character at the specified position is blank (space or tab). // */ // // #define IS_BLANK_AT(string,offset) \ // (IS_SPACE_AT((string),(offset)) || IS_TAB_AT((string),(offset))) // // #define IS_BLANK(string) IS_BLANK_AT((string),0) // // /* // * Check if the character at the specified position is a line break. // */ // // #define IS_BREAK_AT(string,offset) \ // (CHECK_AT((string),'\r',(offset)) /* CR (#xD)*/ \ // || CHECK_AT((string),'\n',(offset)) /* LF (#xA) */ \ // || (CHECK_AT((string),'\xC2',(offset)) \ // && CHECK_AT((string),'\x85',(offset)+1)) /* NEL (#x85) */ \ // || (CHECK_AT((string),'\xE2',(offset)) \ // && CHECK_AT((string),'\x80',(offset)+1) \ // && CHECK_AT((string),'\xA8',(offset)+2)) /* LS (#x2028) */ \ // || (CHECK_AT((string),'\xE2',(offset)) \ // && CHECK_AT((string),'\x80',(offset)+1) \ // && CHECK_AT((string),'\xA9',(offset)+2))) /* PS (#x2029) */ // // #define IS_BREAK(string) IS_BREAK_AT((string),0) // // #define IS_CRLF_AT(string,offset) \ // (CHECK_AT((string),'\r',(offset)) && CHECK_AT((string),'\n',(offset)+1)) // // #define IS_CRLF(string) IS_CRLF_AT((string),0) // // /* // * Check if the character is a line break or NUL. // */ // // #define IS_BREAKZ_AT(string,offset) \ // (IS_BREAK_AT((string),(offset)) || IS_Z_AT((string),(offset))) // // #define IS_BREAKZ(string) IS_BREAKZ_AT((string),0) // // /* // * Check if the character is a line break, space, or NUL. // */ // // #define IS_SPACEZ_AT(string,offset) \ // (IS_SPACE_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset))) // // #define IS_SPACEZ(string) IS_SPACEZ_AT((string),0) // // /* // * Check if the character is a line break, space, tab, or NUL. // */ // // #define IS_BLANKZ_AT(string,offset) \ // (IS_BLANK_AT((string),(offset)) || IS_BREAKZ_AT((string),(offset))) // // #define IS_BLANKZ(string) IS_BLANKZ_AT((string),0) // // /* // * Determine the width of the character. // */ // // #define WIDTH_AT(string,offset) \ // (((string).pointer[offset] & 0x80) == 0x00 ? 1 : \ // ((string).pointer[offset] & 0xE0) == 0xC0 ? 2 : \ // ((string).pointer[offset] & 0xF0) == 0xE0 ? 3 : \ // ((string).pointer[offset] & 0xF8) == 0xF0 ? 4 : 0) // // #define WIDTH(string) WIDTH_AT((string),0) // // /* // * Move the string pointer to the next character. // */ // // #define MOVE(string) ((string).pointer += WIDTH((string))) // // /* // * Copy a character and move the pointers of both strings. // */ // // #define COPY(string_a,string_b) \ // ((*(string_b).pointer & 0x80) == 0x00 ? \ // (*((string_a).pointer++) = *((string_b).pointer++)) : \ // (*(string_b).pointer & 0xE0) == 0xC0 ? \ // (*((string_a).pointer++) = *((string_b).pointer++), \ // *((string_a).pointer++) = *((string_b).pointer++)) : \ // (*(string_b).pointer & 0xF0) == 0xE0 ? \ // (*((string_a).pointer++) = *((string_b).pointer++), \ // *((string_a).pointer++) = *((string_b).pointer++), \ // *((string_a).pointer++) = *((string_b).pointer++)) : \ // (*(string_b).pointer & 0xF8) == 0xF0 ? \ // (*((string_a).pointer++) = *((string_b).pointer++), \ // *((string_a).pointer++) = *((string_b).pointer++), \ // *((string_a).pointer++) = *((string_b).pointer++), \ // *((string_a).pointer++) = *((string_b).pointer++)) : 0) // // /* // * Stack and queue management. // */ // // yaml_DECLARE(int) // yaml_stack_extend(void **start, void **top, void **end); // // yaml_DECLARE(int) // yaml_queue_extend(void **start, void **head, void **tail, void **end); // // #define STACK_INIT(context,stack,size) \ // (((stack).start = yaml_malloc((size)*sizeof(*(stack).start))) ? \ // ((stack).top = (stack).start, \ // (stack).end = (stack).start+(size), \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // #define STACK_DEL(context,stack) \ // (yaml_free((stack).start), \ // (stack).start = (stack).top = (stack).end = 0) // // #define STACK_EMPTY(context,stack) \ // ((stack).start == (stack).top) // // #define PUSH(context,stack,value) \ // (((stack).top != (stack).end \ // || yaml_stack_extend((void **)&(stack).start, \ // (void **)&(stack).top, (void **)&(stack).end)) ? \ // (*((stack).top++) = value, \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // #define POP(context,stack) \ // (*(--(stack).top)) // // #define QUEUE_INIT(context,queue,size) \ // (((queue).start = yaml_malloc((size)*sizeof(*(queue).start))) ? \ // ((queue).head = (queue).tail = (queue).start, \ // (queue).end = (queue).start+(size), \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // #define QUEUE_DEL(context,queue) \ // (yaml_free((queue).start), \ // (queue).start = (queue).head = (queue).tail = (queue).end = 0) // // #define QUEUE_EMPTY(context,queue) \ // ((queue).head == (queue).tail) // // #define ENQUEUE(context,queue,value) \ // (((queue).tail != (queue).end \ // || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \ // (void **)&(queue).tail, (void **)&(queue).end)) ? \ // (*((queue).tail++) = value, \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // #define DEQUEUE(context,queue) \ // (*((queue).head++)) // // #define QUEUE_INSERT(context,queue,index,value) \ // (((queue).tail != (queue).end \ // || yaml_queue_extend((void **)&(queue).start, (void **)&(queue).head, \ // (void **)&(queue).tail, (void **)&(queue).end)) ? \ // (memmove((queue).head+(index)+1,(queue).head+(index), \ // ((queue).tail-(queue).head-(index))*sizeof(*(queue).start)), \ // *((queue).head+(index)) = value, \ // (queue).tail++, \ // 1) : \ // ((context)->error = yaml_MEMORY_ERROR, \ // 0)) // // /* // * Token initializers. // */ // // #define TOKEN_INIT(token,token_type,token_start_mark,token_end_mark) \ // (memset(&(token), 0, sizeof(yaml_token_t)), \ // (token).type = (token_type), \ // (token).start_mark = (token_start_mark), \ // (token).end_mark = (token_end_mark)) // // #define STREAM_START_TOKEN_INIT(token,token_encoding,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_STREAM_START_TOKEN,(start_mark),(end_mark)), \ // (token).data.stream_start.encoding = (token_encoding)) // // #define STREAM_END_TOKEN_INIT(token,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_STREAM_END_TOKEN,(start_mark),(end_mark))) // // #define ALIAS_TOKEN_INIT(token,token_value,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_ALIAS_TOKEN,(start_mark),(end_mark)), \ // (token).data.alias.value = (token_value)) // // #define ANCHOR_TOKEN_INIT(token,token_value,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_ANCHOR_TOKEN,(start_mark),(end_mark)), \ // (token).data.anchor.value = (token_value)) // // #define TAG_TOKEN_INIT(token,token_handle,token_suffix,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_TAG_TOKEN,(start_mark),(end_mark)), \ // (token).data.tag.handle = (token_handle), \ // (token).data.tag.suffix = (token_suffix)) // // #define SCALAR_TOKEN_INIT(token,token_value,token_length,token_style,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_SCALAR_TOKEN,(start_mark),(end_mark)), \ // (token).data.scalar.value = (token_value), \ // (token).data.scalar.length = (token_length), \ // (token).data.scalar.style = (token_style)) // // #define VERSION_DIRECTIVE_TOKEN_INIT(token,token_major,token_minor,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_VERSION_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \ // (token).data.version_directive.major = (token_major), \ // (token).data.version_directive.minor = (token_minor)) // // #define TAG_DIRECTIVE_TOKEN_INIT(token,token_handle,token_prefix,start_mark,end_mark) \ // (TOKEN_INIT((token),yaml_TAG_DIRECTIVE_TOKEN,(start_mark),(end_mark)), \ // (token).data.tag_directive.handle = (token_handle), \ // (token).data.tag_directive.prefix = (token_prefix)) // // /* // * Event initializers. // */ // // #define EVENT_INIT(event,event_type,event_start_mark,event_end_mark) \ // (memset(&(event), 0, sizeof(yaml_event_t)), \ // (event).type = (event_type), \ // (event).start_mark = (event_start_mark), \ // (event).end_mark = (event_end_mark)) // // #define STREAM_START_EVENT_INIT(event,event_encoding,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_STREAM_START_EVENT,(start_mark),(end_mark)), \ // (event).data.stream_start.encoding = (event_encoding)) // // #define STREAM_END_EVENT_INIT(event,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_STREAM_END_EVENT,(start_mark),(end_mark))) // // #define DOCUMENT_START_EVENT_INIT(event,event_version_directive, \ // event_tag_directives_start,event_tag_directives_end,event_implicit,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_DOCUMENT_START_EVENT,(start_mark),(end_mark)), \ // (event).data.document_start.version_directive = (event_version_directive), \ // (event).data.document_start.tag_directives.start = (event_tag_directives_start), \ // (event).data.document_start.tag_directives.end = (event_tag_directives_end), \ // (event).data.document_start.implicit = (event_implicit)) // // #define DOCUMENT_END_EVENT_INIT(event,event_implicit,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_DOCUMENT_END_EVENT,(start_mark),(end_mark)), \ // (event).data.document_end.implicit = (event_implicit)) // // #define ALIAS_EVENT_INIT(event,event_anchor,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_ALIAS_EVENT,(start_mark),(end_mark)), \ // (event).data.alias.anchor = (event_anchor)) // // #define SCALAR_EVENT_INIT(event,event_anchor,event_tag,event_value,event_length, \ // event_plain_implicit, event_quoted_implicit,event_style,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_SCALAR_EVENT,(start_mark),(end_mark)), \ // (event).data.scalar.anchor = (event_anchor), \ // (event).data.scalar.tag = (event_tag), \ // (event).data.scalar.value = (event_value), \ // (event).data.scalar.length = (event_length), \ // (event).data.scalar.plain_implicit = (event_plain_implicit), \ // (event).data.scalar.quoted_implicit = (event_quoted_implicit), \ // (event).data.scalar.style = (event_style)) // // #define SEQUENCE_START_EVENT_INIT(event,event_anchor,event_tag, \ // event_implicit,event_style,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_SEQUENCE_START_EVENT,(start_mark),(end_mark)), \ // (event).data.sequence_start.anchor = (event_anchor), \ // (event).data.sequence_start.tag = (event_tag), \ // (event).data.sequence_start.implicit = (event_implicit), \ // (event).data.sequence_start.style = (event_style)) // // #define SEQUENCE_END_EVENT_INIT(event,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_SEQUENCE_END_EVENT,(start_mark),(end_mark))) // // #define MAPPING_START_EVENT_INIT(event,event_anchor,event_tag, \ // event_implicit,event_style,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_MAPPING_START_EVENT,(start_mark),(end_mark)), \ // (event).data.mapping_start.anchor = (event_anchor), \ // (event).data.mapping_start.tag = (event_tag), \ // (event).data.mapping_start.implicit = (event_implicit), \ // (event).data.mapping_start.style = (event_style)) // // #define MAPPING_END_EVENT_INIT(event,start_mark,end_mark) \ // (EVENT_INIT((event),yaml_MAPPING_END_EVENT,(start_mark),(end_mark))) // // /* // * Document initializer. // */ // // #define DOCUMENT_INIT(document,document_nodes_start,document_nodes_end, \ // document_version_directive,document_tag_directives_start, \ // document_tag_directives_end,document_start_implicit, \ // document_end_implicit,document_start_mark,document_end_mark) \ // (memset(&(document), 0, sizeof(yaml_document_t)), \ // (document).nodes.start = (document_nodes_start), \ // (document).nodes.end = (document_nodes_end), \ // (document).nodes.top = (document_nodes_start), \ // (document).version_directive = (document_version_directive), \ // (document).tag_directives.start = (document_tag_directives_start), \ // (document).tag_directives.end = (document_tag_directives_end), \ // (document).start_implicit = (document_start_implicit), \ // (document).end_implicit = (document_end_implicit), \ // (document).start_mark = (document_start_mark), \ // (document).end_mark = (document_end_mark)) // // /* // * Node initializers. // */ // // #define NODE_INIT(node,node_type,node_tag,node_start_mark,node_end_mark) \ // (memset(&(node), 0, sizeof(yaml_node_t)), \ // (node).type = (node_type), \ // (node).tag = (node_tag), \ // (node).start_mark = (node_start_mark), \ // (node).end_mark = (node_end_mark)) // // #define SCALAR_NODE_INIT(node,node_tag,node_value,node_length, \ // node_style,start_mark,end_mark) \ // (NODE_INIT((node),yaml_SCALAR_NODE,(node_tag),(start_mark),(end_mark)), \ // (node).data.scalar.value = (node_value), \ // (node).data.scalar.length = (node_length), \ // (node).data.scalar.style = (node_style)) // // #define SEQUENCE_NODE_INIT(node,node_tag,node_items_start,node_items_end, \ // node_style,start_mark,end_mark) \ // (NODE_INIT((node),yaml_SEQUENCE_NODE,(node_tag),(start_mark),(end_mark)), \ // (node).data.sequence.items.start = (node_items_start), \ // (node).data.sequence.items.end = (node_items_end), \ // (node).data.sequence.items.top = (node_items_start), \ // (node).data.sequence.style = (node_style)) // // #define MAPPING_NODE_INIT(node,node_tag,node_pairs_start,node_pairs_end, \ // node_style,start_mark,end_mark) \ // (NODE_INIT((node),yaml_MAPPING_NODE,(node_tag),(start_mark),(end_mark)), \ // (node).data.mapping.pairs.start = (node_pairs_start), \ // (node).data.mapping.pairs.end = (node_pairs_end), \ // (node).data.mapping.pairs.top = (node_pairs_start), \ // (node).data.mapping.style = (node_style)) // ================================================ FILE: vendor/github.com/cloudfoundry-incubator/candiedyaml/yamlh.go ================================================ /* 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 candiedyaml import ( "fmt" "io" ) /** The version directive data. */ type yaml_version_directive_t struct { major int // The major version number minor int // The minor version number } /** The tag directive data. */ type yaml_tag_directive_t struct { handle []byte // The tag handle prefix []byte // The tag prefix } /** The stream encoding. */ type yaml_encoding_t int const ( /** Let the parser choose the encoding. */ yaml_ANY_ENCODING yaml_encoding_t = iota /** The defau lt UTF-8 encoding. */ yaml_UTF8_ENCODING /** The UTF-16-LE encoding with BOM. */ yaml_UTF16LE_ENCODING /** The UTF-16-BE encoding with BOM. */ yaml_UTF16BE_ENCODING ) /** Line break types. */ type yaml_break_t int const ( yaml_ANY_BREAK yaml_break_t = iota /** Let the parser choose the break type. */ 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). */ ) /** Many bad things could happen with the parser and emitter. */ type YAML_error_type_t int const ( /** No error is produced. */ yaml_NO_ERROR YAML_error_type_t = iota /** Cannot allocate or reallocate a block of memory. */ yaml_MEMORY_ERROR /** Cannot read or decode the input stream. */ yaml_READER_ERROR /** Cannot scan the input stream. */ yaml_SCANNER_ERROR /** Cannot parse the input stream. */ yaml_PARSER_ERROR /** Cannot compose a YAML document. */ yaml_COMPOSER_ERROR /** Cannot write to the output stream. */ yaml_WRITER_ERROR /** Cannot emit a YAML stream. */ yaml_EMITTER_ERROR ) /** The pointer position. */ type YAML_mark_t struct { /** The position index. */ index int /** The position line. */ line int /** The position column. */ column int } func (m YAML_mark_t) String() string { return fmt.Sprintf("line %d, column %d", m.line, m.column) } /** @} */ /** * @defgroup styles Node Styles * @{ */ type yaml_style_t int /** Scalar styles. */ type yaml_scalar_style_t yaml_style_t const ( /** Let the emitter choose the style. */ yaml_ANY_SCALAR_STYLE yaml_scalar_style_t = iota /** The plain scalar style. */ yaml_PLAIN_SCALAR_STYLE /** The single-quoted scalar style. */ yaml_SINGLE_QUOTED_SCALAR_STYLE /** The double-quoted scalar style. */ yaml_DOUBLE_QUOTED_SCALAR_STYLE /** The literal scalar style. */ yaml_LITERAL_SCALAR_STYLE /** The folded scalar style. */ yaml_FOLDED_SCALAR_STYLE ) /** Sequence styles. */ type yaml_sequence_style_t yaml_style_t const ( /** Let the emitter choose the style. */ yaml_ANY_SEQUENCE_STYLE yaml_sequence_style_t = iota /** The block sequence style. */ yaml_BLOCK_SEQUENCE_STYLE /** The flow sequence style. */ yaml_FLOW_SEQUENCE_STYLE ) /** Mapping styles. */ type yaml_mapping_style_t yaml_style_t const ( /** Let the emitter choose the style. */ yaml_ANY_MAPPING_STYLE yaml_mapping_style_t = iota /** The block mapping style. */ yaml_BLOCK_MAPPING_STYLE /** The flow mapping style. */ yaml_FLOW_MAPPING_STYLE /* yaml_FLOW_SET_MAPPING_STYLE */ ) /** @} */ /** * @defgroup tokens Tokens * @{ */ /** Token types. */ type yaml_token_type_t int const ( /** An empty token. */ yaml_NO_TOKEN yaml_token_type_t = iota /** A STREAM-START token. */ yaml_STREAM_START_TOKEN /** A STREAM-END token. */ yaml_STREAM_END_TOKEN /** A VERSION-DIRECTIVE token. */ yaml_VERSION_DIRECTIVE_TOKEN /** A TAG-DIRECTIVE token. */ yaml_TAG_DIRECTIVE_TOKEN /** A DOCUMENT-START token. */ yaml_DOCUMENT_START_TOKEN /** A DOCUMENT-END token. */ yaml_DOCUMENT_END_TOKEN /** A BLOCK-SEQUENCE-START token. */ yaml_BLOCK_SEQUENCE_START_TOKEN /** A BLOCK-SEQUENCE-END token. */ yaml_BLOCK_MAPPING_START_TOKEN /** A BLOCK-END token. */ yaml_BLOCK_END_TOKEN /** A FLOW-SEQUENCE-START token. */ yaml_FLOW_SEQUENCE_START_TOKEN /** A FLOW-SEQUENCE-END token. */ yaml_FLOW_SEQUENCE_END_TOKEN /** A FLOW-MAPPING-START token. */ yaml_FLOW_MAPPING_START_TOKEN /** A FLOW-MAPPING-END token. */ yaml_FLOW_MAPPING_END_TOKEN /** A BLOCK-ENTRY token. */ yaml_BLOCK_ENTRY_TOKEN /** A FLOW-ENTRY token. */ yaml_FLOW_ENTRY_TOKEN /** A KEY token. */ yaml_KEY_TOKEN /** A VALUE token. */ yaml_VALUE_TOKEN /** An ALIAS token. */ yaml_ALIAS_TOKEN /** An ANCHOR token. */ yaml_ANCHOR_TOKEN /** A TAG token. */ yaml_TAG_TOKEN /** A SCALAR token. */ yaml_SCALAR_TOKEN ) /** The token structure. */ type yaml_token_t struct { /** The token type. */ token_type yaml_token_type_t /** The token data. */ /** The stream start (for @c yaml_STREAM_START_TOKEN). */ encoding yaml_encoding_t /** The alias (for @c yaml_ALIAS_TOKEN, yaml_ANCHOR_TOKEN, yaml_SCALAR_TOKEN,yaml_TAG_TOKEN ). */ /** The anchor (for @c ). */ /** The scalar value (for @c ). */ value []byte /** The tag suffix. */ suffix []byte /** The scalar value (for @c yaml_SCALAR_TOKEN). */ /** The scalar style. */ style yaml_scalar_style_t /** The version directive (for @c yaml_VERSION_DIRECTIVE_TOKEN). */ version_directive yaml_version_directive_t /** The tag directive (for @c yaml_TAG_DIRECTIVE_TOKEN). */ prefix []byte /** The beginning of the token. */ start_mark YAML_mark_t /** The end of the token. */ end_mark YAML_mark_t major, minor int } /** * @defgroup events Events * @{ */ /** Event types. */ type yaml_event_type_t int const ( /** An empty event. */ yaml_NO_EVENT yaml_event_type_t = iota /** A STREAM-START event. */ yaml_STREAM_START_EVENT /** A STREAM-END event. */ yaml_STREAM_END_EVENT /** A DOCUMENT-START event. */ yaml_DOCUMENT_START_EVENT /** A DOCUMENT-END event. */ yaml_DOCUMENT_END_EVENT /** An ALIAS event. */ yaml_ALIAS_EVENT /** A SCALAR event. */ yaml_SCALAR_EVENT /** A SEQUENCE-START event. */ yaml_SEQUENCE_START_EVENT /** A SEQUENCE-END event. */ yaml_SEQUENCE_END_EVENT /** A MAPPING-START event. */ yaml_MAPPING_START_EVENT /** A MAPPING-END event. */ yaml_MAPPING_END_EVENT ) /** The event structure. */ type yaml_event_t struct { /** The event type. */ event_type yaml_event_type_t /** The stream parameters (for @c yaml_STREAM_START_EVENT). */ encoding yaml_encoding_t /** The document parameters (for @c yaml_DOCUMENT_START_EVENT). */ version_directive *yaml_version_directive_t /** The beginning and end of the tag directives list. */ tag_directives []yaml_tag_directive_t /** The document parameters (for @c yaml_DOCUMENT_START_EVENT, yaml_DOCUMENT_END_EVENT, yaml_SEQUENCE_START_EVENT,yaml_MAPPING_START_EVENT). */ /** Is the document indicator implicit? */ implicit bool /** The alias parameters (for @c yaml_ALIAS_EVENT,yaml_SCALAR_EVENT, yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). */ /** The anchor. */ anchor []byte /** The scalar parameters (for @c yaml_SCALAR_EVENT,yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). */ /** The tag. */ tag []byte /** The scalar value. */ value []byte /** Is the tag optional for the plain style? */ plain_implicit bool /** Is the tag optional for any non-plain style? */ quoted_implicit bool /** The sequence parameters (for @c yaml_SEQUENCE_START_EVENT, yaml_MAPPING_START_EVENT). */ /** The sequence style. */ /** The scalar style. */ style yaml_style_t /** The beginning of the event. */ start_mark, end_mark YAML_mark_t } /** * @defgroup nodes Nodes * @{ */ const ( /** The tag @c !!null with the only possible value: @c null. */ yaml_NULL_TAG = "tag:yaml.org,2002:null" /** The tag @c !!bool with the values: @c true and @c falce. */ yaml_BOOL_TAG = "tag:yaml.org,2002:bool" /** The tag @c !!str for string values. */ yaml_STR_TAG = "tag:yaml.org,2002:str" /** The tag @c !!int for integer values. */ yaml_INT_TAG = "tag:yaml.org,2002:int" /** The tag @c !!float for float values. */ yaml_FLOAT_TAG = "tag:yaml.org,2002:float" /** The tag @c !!timestamp for date and time values. */ yaml_TIMESTAMP_TAG = "tag:yaml.org,2002:timestamp" /** The tag @c !!seq is used to denote sequences. */ yaml_SEQ_TAG = "tag:yaml.org,2002:seq" /** The tag @c !!map is used to denote mapping. */ yaml_MAP_TAG = "tag:yaml.org,2002:map" /** The default scalar tag is @c !!str. */ yaml_DEFAULT_SCALAR_TAG = yaml_STR_TAG /** The default sequence tag is @c !!seq. */ yaml_DEFAULT_SEQUENCE_TAG = yaml_SEQ_TAG /** The default mapping tag is @c !!map. */ yaml_DEFAULT_MAPPING_TAG = yaml_MAP_TAG yaml_BINARY_TAG = "tag:yaml.org,2002:binary" ) /** Node types. */ type yaml_node_type_t int const ( /** An empty node. */ yaml_NO_NODE yaml_node_type_t = iota /** A scalar node. */ yaml_SCALAR_NODE /** A sequence node. */ yaml_SEQUENCE_NODE /** A mapping node. */ yaml_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 { /** The key of the element. */ key int /** The value of the element. */ value int } /** The node structure. */ type yaml_node_t struct { /** The node type. */ node_type yaml_node_type_t /** The node tag. */ tag []byte /** The scalar parameters (for @c yaml_SCALAR_NODE). */ scalar struct { /** The scalar value. */ value []byte /** The scalar style. */ style yaml_scalar_style_t } /** The sequence parameters (for @c yaml_SEQUENCE_NODE). */ sequence struct { /** The stack of sequence items. */ items []yaml_node_item_t /** The sequence style. */ style yaml_sequence_style_t } /** The mapping parameters (for @c yaml_MAPPING_NODE). */ mapping struct { /** The stack of mapping pairs (key, value). */ pairs []yaml_node_pair_t /** The mapping style. */ style yaml_mapping_style_t } /** The beginning of the node. */ start_mark YAML_mark_t /** The end of the node. */ end_mark YAML_mark_t } /** 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. */ tags []yaml_tag_directive_t /** Is the document start indicator implicit? */ start_implicit bool /** Is the document end indicator implicit? */ end_implicit bool /** The beginning of the document. */ start_mark YAML_mark_t /** The end of the document. */ 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 @a size bytes to the @a * buffer. The number of written bytes should be set to the @a length variable. * * @param[in,out] data A pointer to an application data specified by * yaml_parser_set_input(). * @param[out] buffer The buffer to write the data from the source. * @param[in] size The size of the buffer. * @param[out] size_read The actual number of bytes read from the source. * * @returns On success, the handler should return @c 1. If the handler failed, * the returned value should be @c 0. On EOF, the handler should set the * @a size_read to @c 0 and return @c 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 { /** Is a simple key possible? */ possible bool /** Is a simple key required? */ required bool /** The number of the token. */ token_number int /** The position mark. */ mark YAML_mark_t } /** * The states of the parser. */ type yaml_parser_state_t int const ( /** Expect STREAM-START. */ yaml_PARSE_STREAM_START_STATE yaml_parser_state_t = iota /** Expect the beginning of an implicit document. */ yaml_PARSE_IMPLICIT_DOCUMENT_START_STATE /** Expect DOCUMENT-START. */ yaml_PARSE_DOCUMENT_START_STATE /** Expect the content of a document. */ yaml_PARSE_DOCUMENT_CONTENT_STATE /** Expect DOCUMENT-END. */ yaml_PARSE_DOCUMENT_END_STATE /** Expect a block node. */ yaml_PARSE_BLOCK_NODE_STATE /** Expect a block node or indentless sequence. */ yaml_PARSE_BLOCK_NODE_OR_INDENTLESS_SEQUENCE_STATE /** Expect a flow node. */ yaml_PARSE_FLOW_NODE_STATE /** Expect the first entry of a block sequence. */ yaml_PARSE_BLOCK_SEQUENCE_FIRST_ENTRY_STATE /** Expect an entry of a block sequence. */ yaml_PARSE_BLOCK_SEQUENCE_ENTRY_STATE /** Expect an entry of an indentless sequence. */ yaml_PARSE_INDENTLESS_SEQUENCE_ENTRY_STATE /** Expect the first key of a block mapping. */ yaml_PARSE_BLOCK_MAPPING_FIRST_KEY_STATE /** Expect a block mapping key. */ yaml_PARSE_BLOCK_MAPPING_KEY_STATE /** Expect a block mapping value. */ yaml_PARSE_BLOCK_MAPPING_VALUE_STATE /** Expect the first entry of a flow sequence. */ yaml_PARSE_FLOW_SEQUENCE_FIRST_ENTRY_STATE /** Expect an entry of a flow sequence. */ yaml_PARSE_FLOW_SEQUENCE_ENTRY_STATE /** Expect a key of an ordered mapping. */ yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_KEY_STATE /** Expect a value of an ordered mapping. */ yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_VALUE_STATE /** Expect the and of an ordered mapping entry. */ yaml_PARSE_FLOW_SEQUENCE_ENTRY_MAPPING_END_STATE /** Expect the first key of a flow mapping. */ yaml_PARSE_FLOW_MAPPING_FIRST_KEY_STATE /** Expect a key of a flow mapping. */ yaml_PARSE_FLOW_MAPPING_KEY_STATE /** Expect a value of a flow mapping. */ yaml_PARSE_FLOW_MAPPING_VALUE_STATE /** Expect an empty value of a flow mapping. */ yaml_PARSE_FLOW_MAPPING_EMPTY_VALUE_STATE /** Expect nothing. */ yaml_PARSE_END_STATE ) /** * This structure holds aliases data. */ type yaml_alias_data_t struct { /** The anchor. */ anchor []byte /** The node id. */ index int /** The anchor mark. */ mark YAML_mark_t } /** * The parser structure. * * All members are internal. Manage the structure using the @c yaml_parser_ * family of functions. */ type yaml_parser_t struct { /** * @name Error handling * @{ */ /** Error type. */ error YAML_error_type_t /** Error description. */ problem string /** The byte about which the problem occured. */ problem_offset int /** The problematic value (@c -1 is none). */ problem_value int /** The problem position. */ problem_mark YAML_mark_t /** The error context. */ context string /** The context position. */ context_mark YAML_mark_t /** * @} */ /** * @name Reader stuff * @{ */ /** Read handler. */ read_handler yaml_read_handler_t /** Reader input data. */ input_reader io.Reader input []byte input_pos int /** EOF flag */ eof bool /** The working buffer. */ buffer []byte buffer_pos int /* The number of unread characters in the buffer. */ unread int /** The raw buffer. */ raw_buffer []byte raw_buffer_pos int /** The input encoding. */ encoding yaml_encoding_t /** The offset of the current position (in bytes). */ offset int /** The mark of the current position. */ mark YAML_mark_t /** * @} */ /** * @name Scanner stuff * @{ */ /** Have we started to scan the input stream? */ stream_start_produced bool /** Have we reached the end of the input stream? */ stream_end_produced bool /** The number of unclosed '[' and '{' indicators. */ flow_level int /** The tokens queue. */ tokens []yaml_token_t tokens_head int /** The number of tokens fetched from the queue. */ tokens_parsed int /* Does the tokens queue contain a token ready for dequeueing. */ token_available bool /** The indentation levels stack. */ indents []int /** The current indentation level. */ indent int /** May a simple key occur at the current position? */ simple_key_allowed bool /** The stack of simple keys. */ simple_keys []yaml_simple_key_t /** * @} */ /** * @name Parser stuff * @{ */ /** The parser states stack. */ states []yaml_parser_state_t /** The current parser state. */ state yaml_parser_state_t /** The stack of marks. */ marks []YAML_mark_t /** The list of TAG directives. */ tag_directives []yaml_tag_directive_t /** * @} */ /** * @name Dumper stuff * @{ */ /** The alias data. */ aliases []yaml_alias_data_t /** The currently parsed document. */ document *yaml_document_t /** * @} */ } /** * 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 /** The emitter states. */ type yaml_emitter_state_t int const ( /** Expect STREAM-START. */ yaml_EMIT_STREAM_START_STATE yaml_emitter_state_t = iota /** Expect the first DOCUMENT-START or STREAM-END. */ yaml_EMIT_FIRST_DOCUMENT_START_STATE /** Expect DOCUMENT-START or STREAM-END. */ yaml_EMIT_DOCUMENT_START_STATE /** Expect the content of a document. */ yaml_EMIT_DOCUMENT_CONTENT_STATE /** Expect DOCUMENT-END. */ yaml_EMIT_DOCUMENT_END_STATE /** Expect the first item of a flow sequence. */ yaml_EMIT_FLOW_SEQUENCE_FIRST_ITEM_STATE /** Expect an item of a flow sequence. */ yaml_EMIT_FLOW_SEQUENCE_ITEM_STATE /** Expect the first key of a flow mapping. */ yaml_EMIT_FLOW_MAPPING_FIRST_KEY_STATE /** Expect a key of a flow mapping. */ yaml_EMIT_FLOW_MAPPING_KEY_STATE /** Expect a value for a simple key of a flow mapping. */ yaml_EMIT_FLOW_MAPPING_SIMPLE_VALUE_STATE /** Expect a value of a flow mapping. */ yaml_EMIT_FLOW_MAPPING_VALUE_STATE /** Expect the first item of a block sequence. */ yaml_EMIT_BLOCK_SEQUENCE_FIRST_ITEM_STATE /** Expect an item of a block sequence. */ yaml_EMIT_BLOCK_SEQUENCE_ITEM_STATE /** Expect the first key of a block mapping. */ yaml_EMIT_BLOCK_MAPPING_FIRST_KEY_STATE /** Expect the key of a block mapping. */ yaml_EMIT_BLOCK_MAPPING_KEY_STATE /** Expect a value for a simple key of a block mapping. */ yaml_EMIT_BLOCK_MAPPING_SIMPLE_VALUE_STATE /** Expect a value of a block mapping. */ yaml_EMIT_BLOCK_MAPPING_VALUE_STATE /** Expect nothing. */ yaml_EMIT_END_STATE ) /** * The emitter structure. * * All members are internal. Manage the structure using the @c yaml_emitter_ * family of functions. */ type yaml_emitter_t struct { /** * @name Error handling * @{ */ /** Error type. */ error YAML_error_type_t /** Error description. */ problem string /** * @} */ /** * @name Writer stuff * @{ */ /** Write handler. */ write_handler yaml_write_handler_t /** Standard (string or file) output data. */ output_buffer *[]byte output_writer io.Writer /** The working buffer. */ buffer []byte buffer_pos int /** The raw buffer. */ raw_buffer []byte raw_buffer_pos int /** The stream encoding. */ encoding yaml_encoding_t /** * @} */ /** * @name Emitter stuff * @{ */ /** If the output is in the canonical style? */ canonical bool /** The number of indentation spaces. */ best_indent int /** The preferred width of the output lines. */ best_width int /** Allow unescaped non-ASCII characters? */ unicode bool /** The preferred line break. */ line_break yaml_break_t /** The stack of states. */ states []yaml_emitter_state_t /** The current emitter state. */ state yaml_emitter_state_t /** The event queue. */ events []yaml_event_t events_head int /** The stack of indentation levels. */ indents []int /** The list of tag directives. */ tag_directives []yaml_tag_directive_t /** The current indentation level. */ indent int /** The current flow level. */ flow_level int /** Is it the document root context? */ root_context bool /** Is it a sequence context? */ sequence_context bool /** Is it a mapping context? */ mapping_context bool /** Is it a simple mapping key context? */ simple_key_context bool /** The current line. */ line int /** The current column. */ column int /** If the last character was a whitespace? */ whitespace bool /** If the last character was an indentation character (' ', '-', '?', ':')? */ indention bool /** If an explicit document end is required? */ open_ended bool /** Anchor analysis. */ anchor_data struct { /** The anchor value. */ anchor []byte /** Is it an alias? */ alias bool } /** Tag analysis. */ tag_data struct { /** The tag handle. */ handle []byte /** The tag suffix. */ suffix []byte } /** Scalar analysis. */ scalar_data struct { /** The scalar value. */ value []byte /** Does the scalar contain line breaks? */ multiline bool /** Can the scalar be expessed in the flow plain style? */ flow_plain_allowed bool /** Can the scalar be expressed in the block plain style? */ block_plain_allowed bool /** Can the scalar be expressed in the single quoted style? */ single_quoted_allowed bool /** Can the scalar be expressed in the literal or folded styles? */ block_allowed bool /** The output style. */ style yaml_scalar_style_t } /** * @} */ /** * @name Dumper stuff * @{ */ /** If the stream was already opened? */ opened bool /** If the stream was already closed? */ closed bool /** The information associated with the document nodes. */ anchors *struct { /** The number of references. */ references int /** The anchor id. */ anchor int /** If the node has been emitted? */ serialized bool } /** The last assigned anchor id. */ last_anchor_id int /** The currently emitted document. */ document *yaml_document_t /** * @} */ } ================================================ FILE: vendor/github.com/davecgh/go-spew/.gitignore ================================================ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe ================================================ FILE: vendor/github.com/davecgh/go-spew/.travis.yml ================================================ language: go go: 1.2 install: - go get -v code.google.com/p/go.tools/cmd/cover script: - go test -v -tags=testcgo ./spew -covermode=count -coverprofile=profile.cov after_success: - go get -v github.com/mattn/goveralls - export PATH=$PATH:$HOME/gopath/bin - goveralls -coverprofile=profile.cov -service=travis-ci ================================================ FILE: vendor/github.com/davecgh/go-spew/LICENSE ================================================ Copyright (c) 2012-2013 Dave Collins 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. ================================================ FILE: vendor/github.com/davecgh/go-spew/README.md ================================================ go-spew ======= [![Build Status](https://travis-ci.org/davecgh/go-spew.png?branch=master)] (https://travis-ci.org/davecgh/go-spew) [![Coverage Status] (https://coveralls.io/repos/davecgh/go-spew/badge.png?branch=master)] (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://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). ## Documentation [![GoDoc](https://godoc.org/github.com/davecgh/go-spew/spew?status.png)] (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 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) ``` ## Sample Dump Output ``` (main.Foo) { unexportedField: (*main.Bar)(0xf84002e210)({ flag: (main.Flag) flagTwo, data: (uintptr) }), 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 <*>} %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} ``` ## 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. Pointer method invocation is enabled by default. * 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. ``` ## License Go-spew is licensed under the liberal ISC License. ================================================ FILE: vendor/github.com/davecgh/go-spew/cov_report.sh ================================================ #!/bin/sh # This script uses gocov to generate a test coverage report. # The gocov tool my be obtained with the following command: # go get github.com/axw/gocov/gocov # # It will be installed to $GOPATH/bin, so ensure that location is in your $PATH. # Check for gocov. if ! type gocov >/dev/null 2>&1; then echo >&2 "This script requires the gocov tool." echo >&2 "You may obtain it with the following command:" echo >&2 "go get github.com/axw/gocov/gocov" exit 1 fi # Only run the cgo tests if gcc is installed. if type gcc >/dev/null 2>&1; then (cd spew && gocov test -tags testcgo | gocov report) else (cd spew && gocov test | gocov report) fi ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/common.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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" "unsafe" ) const ( // 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<>flagKindShift != uintptr(reflect.Int) { flagKindShift = 0 flagRO = 1 << 5 flagIndir = 1 << 6 } } // 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 } // 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("") maxNewlineBytes = []byte("\n") maxShortBytes = []byte("") circularBytes = []byte("") circularShortBytes = []byte("") invalidAngleBytes = []byte("") 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 to bypass these restrictions // since this package does not mutate the values. if !v.CanInterface() { 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. var viface interface{} if !cs.DisablePointerMethods { if !v.CanAddr() { v = unsafeReflectValue(v) } viface = v.Addr().Interface() } else { if v.CanAddr() { v = v.Addr() } viface = v.Interface() } // Is it an error or Stringer? switch iface := viface.(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)) } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/common_test.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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_test import ( "fmt" "reflect" "testing" "github.com/davecgh/go-spew/spew" ) // custom type to test Stinger interface on non-pointer receiver. type stringer string // String implements the Stringer interface for testing invocation of custom // stringers on types with non-pointer receivers. func (s stringer) String() string { return "stringer " + string(s) } // custom type to test Stinger interface on pointer receiver. type pstringer string // String implements the Stringer interface for testing invocation of custom // stringers on types with only pointer receivers. func (s *pstringer) String() string { return "stringer " + string(*s) } // xref1 and xref2 are cross referencing structs for testing circular reference // detection. type xref1 struct { ps2 *xref2 } type xref2 struct { ps1 *xref1 } // indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular // reference for testing detection. type indirCir1 struct { ps2 *indirCir2 } type indirCir2 struct { ps3 *indirCir3 } type indirCir3 struct { ps1 *indirCir1 } // embed is used to test embedded structures. type embed struct { a string } // embedwrap is used to test embedded structures. type embedwrap struct { *embed e *embed } // panicer is used to intentionally cause a panic for testing spew properly // handles them type panicer int func (p panicer) String() string { panic("test panic") } // customError is used to test custom error interface invocation. type customError int func (e customError) Error() string { return fmt.Sprintf("error: %d", int(e)) } // stringizeWants converts a slice of wanted test output into a format suitable // for a test error message. func stringizeWants(wants []string) string { s := "" for i, want := range wants { if i > 0 { s += fmt.Sprintf("want%d: %s", i+1, want) } else { s += "want: " + want } } return s } // testFailed returns whether or not a test failed by checking if the result // of the test is in the slice of wanted strings. func testFailed(result string, wants []string) bool { for _, want := range wants { if result == want { return false } } return true } type sortableStruct struct { x int } func (ss sortableStruct) String() string { return fmt.Sprintf("ss.%d", ss.x) } type unsortableStruct struct { x int } type sortTestCase struct { input []reflect.Value expected []reflect.Value } func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) { getInterfaces := func(values []reflect.Value) []interface{} { interfaces := []interface{}{} for _, v := range values { interfaces = append(interfaces, v.Interface()) } return interfaces } for _, test := range tests { spew.SortValues(test.input, cs) // reflect.DeepEqual cannot really make sense of reflect.Value, // probably because of all the pointer tricks. For instance, // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{} // instead. input := getInterfaces(test.input) expected := getInterfaces(test.expected) if !reflect.DeepEqual(input, expected) { t.Errorf("Sort mismatch:\n %v != %v", input, expected) } } } // TestSortValues ensures the sort functionality for relect.Value based sorting // works as intended. func TestSortValues(t *testing.T) { v := reflect.ValueOf a := v("a") b := v("b") c := v("c") embedA := v(embed{"a"}) embedB := v(embed{"b"}) embedC := v(embed{"c"}) tests := []sortTestCase{ // No values. { []reflect.Value{}, []reflect.Value{}, }, // Bools. { []reflect.Value{v(false), v(true), v(false)}, []reflect.Value{v(false), v(false), v(true)}, }, // Ints. { []reflect.Value{v(2), v(1), v(3)}, []reflect.Value{v(1), v(2), v(3)}, }, // Uints. { []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))}, []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))}, }, // Floats. { []reflect.Value{v(2.0), v(1.0), v(3.0)}, []reflect.Value{v(1.0), v(2.0), v(3.0)}, }, // Strings. { []reflect.Value{b, a, c}, []reflect.Value{a, b, c}, }, // Array { []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})}, []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})}, }, // Uintptrs. { []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))}, []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))}, }, // SortableStructs. { // Note: not sorted - DisableMethods is set. []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, }, // UnsortableStructs. { // Note: not sorted - SpewKeys is false. []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, }, // Invalid. { []reflect.Value{embedB, embedA, embedC}, []reflect.Value{embedB, embedA, embedC}, }, } cs := spew.ConfigState{DisableMethods: true, SpewKeys: false} helpTestSortValues(tests, &cs, t) } // TestSortValuesWithMethods ensures the sort functionality for relect.Value // based sorting works as intended when using string methods. func TestSortValuesWithMethods(t *testing.T) { v := reflect.ValueOf a := v("a") b := v("b") c := v("c") tests := []sortTestCase{ // Ints. { []reflect.Value{v(2), v(1), v(3)}, []reflect.Value{v(1), v(2), v(3)}, }, // Strings. { []reflect.Value{b, a, c}, []reflect.Value{a, b, c}, }, // SortableStructs. { []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, }, // UnsortableStructs. { // Note: not sorted - SpewKeys is false. []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, }, } cs := spew.ConfigState{DisableMethods: false, SpewKeys: false} helpTestSortValues(tests, &cs, t) } // TestSortValuesWithSpew ensures the sort functionality for relect.Value // based sorting works as intended when using spew to stringify keys. func TestSortValuesWithSpew(t *testing.T) { v := reflect.ValueOf a := v("a") b := v("b") c := v("c") tests := []sortTestCase{ // Ints. { []reflect.Value{v(2), v(1), v(3)}, []reflect.Value{v(1), v(2), v(3)}, }, // Strings. { []reflect.Value{b, a, c}, []reflect.Value{a, b, c}, }, // SortableStructs. { []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})}, []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})}, }, // UnsortableStructs. { []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})}, []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})}, }, } cs := spew.ConfigState{DisableMethods: true, SpewKeys: true} helpTestSortValues(tests, &cs, t) } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/config.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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. DisablePointerMethods 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: " "} } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/doc.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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. * 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) }), 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 <*>} %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} 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 ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/dump.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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 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 back // into 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 // to bypass these restrictions since this package does not // mutate the values. vs := v if !vs.CanInterface() || !vs.CanAddr() { vs = unsafeReflectValue(vs) } 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 || valueCap != 0 { d.w.Write(openParenBytes) if valueLen != 0 { d.w.Write(lenEqualsBytes) printInt(d.w, int64(valueLen), 10) } if 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...) } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/dump_test.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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. */ /* Test Summary: NOTE: For each test, a nil pointer, a single pointer and double pointer to the base test element are also tested to ensure proper indirection across all types. - Max int8, int16, int32, int64, int - Max uint8, uint16, uint32, uint64, uint - Boolean true and false - Standard complex64 and complex128 - Array containing standard ints - Array containing type with custom formatter on pointer receiver only - Array containing interfaces - Array containing bytes - Slice containing standard float32 values - Slice containing type with custom formatter on pointer receiver only - Slice containing interfaces - Slice containing bytes - Nil slice - Standard string - Nil interface - Sub-interface - Map with string keys and int vals - Map with custom formatter type on pointer receiver only keys and vals - Map with interface keys and values - Map with nil interface value - Struct with primitives - Struct that contains another struct - Struct that contains custom type with Stringer pointer interface via both exported and unexported fields - Struct that contains embedded struct and field to same struct - Uintptr to 0 (null pointer) - Uintptr address of real variable - Unsafe.Pointer to 0 (null pointer) - Unsafe.Pointer to address of real variable - Nil channel - Standard int channel - Function with no params and no returns - Function with param and no returns - Function with multiple params and multiple returns - Struct that is circular through self referencing - Structs that are circular through cross referencing - Structs that are indirectly circular - Type that panics in its Stringer interface */ package spew_test import ( "bytes" "fmt" "testing" "unsafe" "github.com/davecgh/go-spew/spew" ) // dumpTest is used to describe a test to be perfomed against the Dump method. type dumpTest struct { in interface{} wants []string } // dumpTests houses all of the tests to be performed against the Dump method. var dumpTests = make([]dumpTest, 0) // addDumpTest is a helper method to append the passed input and desired result // to dumpTests func addDumpTest(in interface{}, wants ...string) { test := dumpTest{in, wants} dumpTests = append(dumpTests, test) } func addIntDumpTests() { // Max int8. v := int8(127) nv := (*int8)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "int8" vs := "127" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Max int16. v2 := int16(32767) nv2 := (*int16)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "int16" v2s := "32767" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") // Max int32. v3 := int32(2147483647) nv3 := (*int32)(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "int32" v3s := "2147483647" addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") addDumpTest(nv3, "(*"+v3t+")()\n") // Max int64. v4 := int64(9223372036854775807) nv4 := (*int64)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "int64" v4s := "9223372036854775807" addDumpTest(v4, "("+v4t+") "+v4s+"\n") addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") addDumpTest(nv4, "(*"+v4t+")()\n") // Max int. v5 := int(2147483647) nv5 := (*int)(nil) pv5 := &v5 v5Addr := fmt.Sprintf("%p", pv5) pv5Addr := fmt.Sprintf("%p", &pv5) v5t := "int" v5s := "2147483647" addDumpTest(v5, "("+v5t+") "+v5s+"\n") addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") addDumpTest(nv5, "(*"+v5t+")()\n") } func addUintDumpTests() { // Max uint8. v := uint8(255) nv := (*uint8)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "uint8" vs := "255" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Max uint16. v2 := uint16(65535) nv2 := (*uint16)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "uint16" v2s := "65535" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") // Max uint32. v3 := uint32(4294967295) nv3 := (*uint32)(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "uint32" v3s := "4294967295" addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") addDumpTest(nv3, "(*"+v3t+")()\n") // Max uint64. v4 := uint64(18446744073709551615) nv4 := (*uint64)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "uint64" v4s := "18446744073709551615" addDumpTest(v4, "("+v4t+") "+v4s+"\n") addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") addDumpTest(nv4, "(*"+v4t+")()\n") // Max uint. v5 := uint(4294967295) nv5 := (*uint)(nil) pv5 := &v5 v5Addr := fmt.Sprintf("%p", pv5) pv5Addr := fmt.Sprintf("%p", &pv5) v5t := "uint" v5s := "4294967295" addDumpTest(v5, "("+v5t+") "+v5s+"\n") addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") addDumpTest(nv5, "(*"+v5t+")()\n") } func addBoolDumpTests() { // Boolean true. v := bool(true) nv := (*bool)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "bool" vs := "true" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Boolean false. v2 := bool(false) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "bool" v2s := "false" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") } func addFloatDumpTests() { // Standard float32. v := float32(3.1415) nv := (*float32)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "float32" vs := "3.1415" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Standard float64. v2 := float64(3.1415926) nv2 := (*float64)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "float64" v2s := "3.1415926" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") } func addComplexDumpTests() { // Standard complex64. v := complex(float32(6), -2) nv := (*complex64)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "complex64" vs := "(6-2i)" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Standard complex128. v2 := complex(float64(-6), 2) nv2 := (*complex128)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "complex128" v2s := "(-6+2i)" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") } func addArrayDumpTests() { // Array containing standard ints. v := [3]int{1, 2, 3} vLen := fmt.Sprintf("%d", len(v)) vCap := fmt.Sprintf("%d", cap(v)) nv := (*[3]int)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "int" vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" + vt + ") 2,\n (" + vt + ") 3\n}" addDumpTest(v, "([3]"+vt+") "+vs+"\n") addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*[3]"+vt+")()\n") // Array containing type with custom formatter on pointer receiver only. v2i0 := pstringer("1") v2i1 := pstringer("2") v2i2 := pstringer("3") v2 := [3]pstringer{v2i0, v2i1, v2i2} v2i0Len := fmt.Sprintf("%d", len(v2i0)) v2i1Len := fmt.Sprintf("%d", len(v2i1)) v2i2Len := fmt.Sprintf("%d", len(v2i2)) v2Len := fmt.Sprintf("%d", len(v2)) v2Cap := fmt.Sprintf("%d", cap(v2)) nv2 := (*[3]pstringer)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "spew_test.pstringer" v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + "stringer 3\n}" addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*[3]"+v2t+")()\n") // Array containing interfaces. v3i0 := "one" v3 := [3]interface{}{v3i0, int(2), uint(3)} v3i0Len := fmt.Sprintf("%d", len(v3i0)) v3Len := fmt.Sprintf("%d", len(v3)) v3Cap := fmt.Sprintf("%d", cap(v3)) nv3 := (*[3]interface{})(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "[3]interface {}" v3t2 := "string" v3t3 := "int" v3t4 := "uint" v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + v3t4 + ") 3\n}" addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") addDumpTest(nv3, "(*"+v3t+")()\n") // Array containing bytes. v4 := [34]byte{ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, } v4Len := fmt.Sprintf("%d", len(v4)) v4Cap := fmt.Sprintf("%d", cap(v4)) nv4 := (*[34]byte)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "[34]uint8" v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + " |............... |\n" + " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + " |!\"#$%&'()*+,-./0|\n" + " 00000020 31 32 " + " |12|\n}" addDumpTest(v4, "("+v4t+") "+v4s+"\n") addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") addDumpTest(nv4, "(*"+v4t+")()\n") } func addSliceDumpTests() { // Slice containing standard float32 values. v := []float32{3.14, 6.28, 12.56} vLen := fmt.Sprintf("%d", len(v)) vCap := fmt.Sprintf("%d", cap(v)) nv := (*[]float32)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "float32" vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" + vt + ") 6.28,\n (" + vt + ") 12.56\n}" addDumpTest(v, "([]"+vt+") "+vs+"\n") addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*[]"+vt+")()\n") // Slice containing type with custom formatter on pointer receiver only. v2i0 := pstringer("1") v2i1 := pstringer("2") v2i2 := pstringer("3") v2 := []pstringer{v2i0, v2i1, v2i2} v2i0Len := fmt.Sprintf("%d", len(v2i0)) v2i1Len := fmt.Sprintf("%d", len(v2i1)) v2i2Len := fmt.Sprintf("%d", len(v2i2)) v2Len := fmt.Sprintf("%d", len(v2)) v2Cap := fmt.Sprintf("%d", cap(v2)) nv2 := (*[]pstringer)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "spew_test.pstringer" v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " + "stringer 3\n}" addDumpTest(v2, "([]"+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*[]"+v2t+")()\n") // Slice containing interfaces. v3i0 := "one" v3 := []interface{}{v3i0, int(2), uint(3), nil} v3i0Len := fmt.Sprintf("%d", len(v3i0)) v3Len := fmt.Sprintf("%d", len(v3)) v3Cap := fmt.Sprintf("%d", cap(v3)) nv3 := (*[]interface{})(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "[]interface {}" v3t2 := "string" v3t3 := "int" v3t4 := "uint" v3t5 := "interface {}" v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " + "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" + v3t4 + ") 3,\n (" + v3t5 + ") \n}" addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") addDumpTest(nv3, "(*"+v3t+")()\n") // Slice containing bytes. v4 := []byte{ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, } v4Len := fmt.Sprintf("%d", len(v4)) v4Cap := fmt.Sprintf("%d", cap(v4)) nv4 := (*[]byte)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "[]uint8" v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" + " |............... |\n" + " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" + " |!\"#$%&'()*+,-./0|\n" + " 00000020 31 32 " + " |12|\n}" addDumpTest(v4, "("+v4t+") "+v4s+"\n") addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") addDumpTest(nv4, "(*"+v4t+")()\n") // Nil slice. v5 := []int(nil) nv5 := (*[]int)(nil) pv5 := &v5 v5Addr := fmt.Sprintf("%p", pv5) pv5Addr := fmt.Sprintf("%p", &pv5) v5t := "[]int" v5s := "" addDumpTest(v5, "("+v5t+") "+v5s+"\n") addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n") addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n") addDumpTest(nv5, "(*"+v5t+")()\n") } func addStringDumpTests() { // Standard string. v := "test" vLen := fmt.Sprintf("%d", len(v)) nv := (*string)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "string" vs := "(len=" + vLen + ") \"test\"" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") } func addInterfaceDumpTests() { // Nil interface. var v interface{} nv := (*interface{})(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "interface {}" vs := "" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Sub-interface. v2 := interface{}(uint16(65535)) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "uint16" v2s := "65535" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") } func addMapDumpTests() { // Map with string keys and int vals. k := "one" kk := "two" m := map[string]int{k: 1, kk: 2} klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up kkLen := fmt.Sprintf("%d", len(kk)) mLen := fmt.Sprintf("%d", len(m)) nilMap := map[string]int(nil) nm := (*map[string]int)(nil) pm := &m mAddr := fmt.Sprintf("%p", pm) pmAddr := fmt.Sprintf("%p", &pm) mt := "map[string]int" mt1 := "string" mt2 := "int" ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " + "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen + ") \"two\": (" + mt2 + ") 2\n}" ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " + "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen + ") \"one\": (" + mt2 + ") 1\n}" addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n") addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n", "(*"+mt+")("+mAddr+")("+ms2+")\n") addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n", "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n") addDumpTest(nm, "(*"+mt+")()\n") addDumpTest(nilMap, "("+mt+") \n") // Map with custom formatter type on pointer receiver only keys and vals. k2 := pstringer("one") v2 := pstringer("1") m2 := map[pstringer]pstringer{k2: v2} k2Len := fmt.Sprintf("%d", len(k2)) v2Len := fmt.Sprintf("%d", len(v2)) m2Len := fmt.Sprintf("%d", len(m2)) nilMap2 := map[pstringer]pstringer(nil) nm2 := (*map[pstringer]pstringer)(nil) pm2 := &m2 m2Addr := fmt.Sprintf("%p", pm2) pm2Addr := fmt.Sprintf("%p", &pm2) m2t := "map[spew_test.pstringer]spew_test.pstringer" m2t1 := "spew_test.pstringer" m2t2 := "spew_test.pstringer" m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " + "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}" addDumpTest(m2, "("+m2t+") "+m2s+"\n") addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n") addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n") addDumpTest(nm2, "(*"+m2t+")()\n") addDumpTest(nilMap2, "("+m2t+") \n") // Map with interface keys and values. k3 := "one" k3Len := fmt.Sprintf("%d", len(k3)) m3 := map[interface{}]interface{}{k3: 1} m3Len := fmt.Sprintf("%d", len(m3)) nilMap3 := map[interface{}]interface{}(nil) nm3 := (*map[interface{}]interface{})(nil) pm3 := &m3 m3Addr := fmt.Sprintf("%p", pm3) pm3Addr := fmt.Sprintf("%p", &pm3) m3t := "map[interface {}]interface {}" m3t1 := "string" m3t2 := "int" m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " + "\"one\": (" + m3t2 + ") 1\n}" addDumpTest(m3, "("+m3t+") "+m3s+"\n") addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n") addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n") addDumpTest(nm3, "(*"+m3t+")()\n") addDumpTest(nilMap3, "("+m3t+") \n") // Map with nil interface value. k4 := "nil" k4Len := fmt.Sprintf("%d", len(k4)) m4 := map[string]interface{}{k4: nil} m4Len := fmt.Sprintf("%d", len(m4)) nilMap4 := map[string]interface{}(nil) nm4 := (*map[string]interface{})(nil) pm4 := &m4 m4Addr := fmt.Sprintf("%p", pm4) pm4Addr := fmt.Sprintf("%p", &pm4) m4t := "map[string]interface {}" m4t1 := "string" m4t2 := "interface {}" m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" + " \"nil\": (" + m4t2 + ") \n}" addDumpTest(m4, "("+m4t+") "+m4s+"\n") addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n") addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n") addDumpTest(nm4, "(*"+m4t+")()\n") addDumpTest(nilMap4, "("+m4t+") \n") } func addStructDumpTests() { // Struct with primitives. type s1 struct { a int8 b uint8 } v := s1{127, 255} nv := (*s1)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.s1" vt2 := "int8" vt3 := "uint8" vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Struct that contains another struct. type s2 struct { s1 s1 b bool } v2 := s2{s1{127, 255}, true} nv2 := (*s2)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "spew_test.s2" v2t2 := "spew_test.s1" v2t3 := "int8" v2t4 := "uint8" v2t5 := "bool" v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" + v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") // Struct that contains custom type with Stringer pointer interface via both // exported and unexported fields. type s3 struct { s pstringer S pstringer } v3 := s3{"test", "test2"} nv3 := (*s3)(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "spew_test.s3" v3t2 := "spew_test.pstringer" v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 + ") (len=5) stringer test2\n}" addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") addDumpTest(nv3, "(*"+v3t+")()\n") // Struct that contains embedded struct and field to same struct. e := embed{"embedstr"} eLen := fmt.Sprintf("%d", len("embedstr")) v4 := embedwrap{embed: &e, e: &e} nv4 := (*embedwrap)(nil) pv4 := &v4 eAddr := fmt.Sprintf("%p", &e) v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "spew_test.embedwrap" v4t2 := "spew_test.embed" v4t3 := "string" v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" + " \"embedstr\"\n })\n}" addDumpTest(v4, "("+v4t+") "+v4s+"\n") addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n") addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n") addDumpTest(nv4, "(*"+v4t+")()\n") } func addUintptrDumpTests() { // Null pointer. v := uintptr(0) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "uintptr" vs := "" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") // Address of real variable. i := 1 v2 := uintptr(unsafe.Pointer(&i)) nv2 := (*uintptr)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "uintptr" v2s := fmt.Sprintf("%p", &i) addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") } func addUnsafePointerDumpTests() { // Null pointer. v := unsafe.Pointer(uintptr(0)) nv := (*unsafe.Pointer)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "unsafe.Pointer" vs := "" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Address of real variable. i := 1 v2 := unsafe.Pointer(&i) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "unsafe.Pointer" v2s := fmt.Sprintf("%p", &i) addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv, "(*"+vt+")()\n") } func addChanDumpTests() { // Nil channel. var v chan int pv := &v nv := (*chan int)(nil) vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "chan int" vs := "" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Real channel. v2 := make(chan int) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "chan int" v2s := fmt.Sprintf("%p", v2) addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") } func addFuncDumpTests() { // Function with no params and no returns. v := addIntDumpTests nv := (*func())(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "func()" vs := fmt.Sprintf("%p", v) addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") // Function with param and no returns. v2 := TestDump nv2 := (*func(*testing.T))(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "func(*testing.T)" v2s := fmt.Sprintf("%p", v2) addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n") addDumpTest(nv2, "(*"+v2t+")()\n") // Function with multiple params and multiple returns. var v3 = func(i int, s string) (b bool, err error) { return true, nil } nv3 := (*func(int, string) (bool, error))(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "func(int, string) (bool, error)" v3s := fmt.Sprintf("%p", v3) addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n") addDumpTest(nv3, "(*"+v3t+")()\n") } func addCircularDumpTests() { // Struct that is circular through self referencing. type circular struct { c *circular } v := circular{nil} v.c = &v pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.circular" vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" + vAddr + ")()\n })\n}" vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n") // Structs that are circular through cross referencing. v2 := xref1{nil} ts2 := xref2{&v2} v2.ps2 = &ts2 pv2 := &v2 ts2Addr := fmt.Sprintf("%p", &ts2) v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "spew_test.xref1" v2t2 := "spew_test.xref2" v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")()\n })\n })\n}" v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t + ")(" + v2Addr + ")()\n })\n}" addDumpTest(v2, "("+v2t+") "+v2s+"\n") addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n") addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n") // Structs that are indirectly circular. v3 := indirCir1{nil} tic2 := indirCir2{nil} tic3 := indirCir3{&v3} tic2.ps3 = &tic3 v3.ps2 = &tic2 pv3 := &v3 tic2Addr := fmt.Sprintf("%p", &tic2) tic3Addr := fmt.Sprintf("%p", &tic3) v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "spew_test.indirCir1" v3t2 := "spew_test.indirCir2" v3t3 := "spew_test.indirCir3" v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")()\n })\n })\n })\n}" v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 + ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr + ")()\n })\n })\n}" addDumpTest(v3, "("+v3t+") "+v3s+"\n") addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n") addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n") } func addPanicDumpTests() { // Type that panics in its Stringer interface. v := panicer(127) nv := (*panicer)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.panicer" vs := "(PANIC=test panic)127" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") } func addErrorDumpTests() { // Type that has a custom Error interface. v := customError(127) nv := (*customError)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.customError" vs := "error: 127" addDumpTest(v, "("+vt+") "+vs+"\n") addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n") addDumpTest(nv, "(*"+vt+")()\n") } // TestDump executes all of the tests described by dumpTests. func TestDump(t *testing.T) { // Setup tests. addIntDumpTests() addUintDumpTests() addBoolDumpTests() addFloatDumpTests() addComplexDumpTests() addArrayDumpTests() addSliceDumpTests() addStringDumpTests() addInterfaceDumpTests() addMapDumpTests() addStructDumpTests() addUintptrDumpTests() addUnsafePointerDumpTests() addChanDumpTests() addFuncDumpTests() addCircularDumpTests() addPanicDumpTests() addErrorDumpTests() addCgoDumpTests() t.Logf("Running %d tests", len(dumpTests)) for i, test := range dumpTests { buf := new(bytes.Buffer) spew.Fdump(buf, test.in) s := buf.String() if testFailed(s, test.wants) { t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants)) continue } } } func TestDumpSortedKeys(t *testing.T) { cfg := spew.ConfigState{SortKeys: true} s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"}) expected := `(map[int]string) (len=3) { (int) 1: (string) (len=1) "1", (int) 2: (string) (len=1) "2", (int) 3: (string) (len=1) "3" } ` if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2}) expected = `(map[spew_test.stringer]int) (len=3) { (spew_test.stringer) (len=1) stringer 1: (int) 1, (spew_test.stringer) (len=1) stringer 2: (int) 2, (spew_test.stringer) (len=1) stringer 3: (int) 3 } ` if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) expected = `(map[spew_test.pstringer]int) (len=3) { (spew_test.pstringer) (len=1) stringer 1: (int) 1, (spew_test.pstringer) (len=1) stringer 2: (int) 2, (spew_test.pstringer) (len=1) stringer 3: (int) 3 } ` if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) expected = `(map[spew_test.customError]int) (len=3) { (spew_test.customError) error: 1: (int) 1, (spew_test.customError) error: 2: (int) 2, (spew_test.customError) error: 3: (int) 3 } ` if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go ================================================ // Copyright (c) 2013 Dave Collins // // 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 both cgo is supported and "-tags testcgo" is added to the go test // command line. This means the cgo tests are only added (and hence run) when // specifially requested. This configuration is used because spew itself // does not require cgo to run even though it does handle certain cgo types // specially. Rather than forcing all clients to require cgo and an external // C compiler just to run the tests, this scheme makes them optional. // +build cgo,testcgo package spew_test import ( "fmt" "github.com/davecgh/go-spew/spew/testdata" ) func addCgoDumpTests() { // C char pointer. v := testdata.GetCgoCharPointer() nv := testdata.GetCgoNullCharPointer() pv := &v vcAddr := fmt.Sprintf("%p", v) vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "*testdata._Ctype_char" vs := "116" addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n") addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n") addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n") addDumpTest(nv, "("+vt+")()\n") // C char array. v2, v2l, v2c := testdata.GetCgoCharArray() v2Len := fmt.Sprintf("%d", v2l) v2Cap := fmt.Sprintf("%d", v2c) v2t := "[6]testdata._Ctype_char" v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " + "{\n 00000000 74 65 73 74 32 00 " + " |test2.|\n}" addDumpTest(v2, "("+v2t+") "+v2s+"\n") // C unsigned char array. v3, v3l, v3c := testdata.GetCgoUnsignedCharArray() v3Len := fmt.Sprintf("%d", v3l) v3Cap := fmt.Sprintf("%d", v3c) v3t := "[6]testdata._Ctype_unsignedchar" v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " + "{\n 00000000 74 65 73 74 33 00 " + " |test3.|\n}" addDumpTest(v3, "("+v3t+") "+v3s+"\n") // C signed char array. v4, v4l, v4c := testdata.GetCgoSignedCharArray() v4Len := fmt.Sprintf("%d", v4l) v4Cap := fmt.Sprintf("%d", v4c) v4t := "[6]testdata._Ctype_schar" v4t2 := "testdata._Ctype_schar" v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " + "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 + ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 + ") 0\n}" addDumpTest(v4, "("+v4t+") "+v4s+"\n") // C uint8_t array. v5, v5l, v5c := testdata.GetCgoUint8tArray() v5Len := fmt.Sprintf("%d", v5l) v5Cap := fmt.Sprintf("%d", v5c) v5t := "[6]testdata._Ctype_uint8_t" v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " + "{\n 00000000 74 65 73 74 35 00 " + " |test5.|\n}" addDumpTest(v5, "("+v5t+") "+v5s+"\n") // C typedefed unsigned char array. v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray() v6Len := fmt.Sprintf("%d", v6l) v6Cap := fmt.Sprintf("%d", v6c) v6t := "[6]testdata._Ctype_custom_uchar_t" v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " + "{\n 00000000 74 65 73 74 36 00 " + " |test6.|\n}" addDumpTest(v6, "("+v6t+") "+v6s+"\n") } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go ================================================ // Copyright (c) 2013 Dave Collins // // 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 either cgo is not supported or "-tags testcgo" is not added to the go // test command line. This file intentionally does not setup any cgo tests in // this scenario. // +build !cgo !testcgo package spew_test func addCgoDumpTests() { // Don't add any tests for cgo since this file is only compiled when // there should not be any cgo tests. } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/example_test.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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_test import ( "fmt" "github.com/davecgh/go-spew/spew" ) type Flag int const ( flagOne Flag = iota flagTwo ) var flagStrings = map[Flag]string{ flagOne: "flagOne", flagTwo: "flagTwo", } func (f Flag) String() string { if s, ok := flagStrings[f]; ok { return s } return fmt.Sprintf("Unknown flag (%d)", int(f)) } type Bar struct { flag Flag data uintptr } type Foo struct { unexportedField Bar ExportedField map[interface{}]interface{} } // This example demonstrates how to use Dump to dump variables to stdout. func ExampleDump() { // The following package level declarations are assumed for this example: /* type Flag int const ( flagOne Flag = iota flagTwo ) var flagStrings = map[Flag]string{ flagOne: "flagOne", flagTwo: "flagTwo", } func (f Flag) String() string { if s, ok := flagStrings[f]; ok { return s } return fmt.Sprintf("Unknown flag (%d)", int(f)) } type Bar struct { flag Flag data uintptr } type Foo struct { unexportedField Bar ExportedField map[interface{}]interface{} } */ // Setup some sample data structures for the example. bar := Bar{Flag(flagTwo), uintptr(0)} s1 := Foo{bar, map[interface{}]interface{}{"one": true}} f := Flag(5) b := []byte{ 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, } // Dump! spew.Dump(s1, f, b) // Output: // (spew_test.Foo) { // unexportedField: (spew_test.Bar) { // flag: (spew_test.Flag) flagTwo, // data: (uintptr) // }, // ExportedField: (map[interface {}]interface {}) (len=1) { // (string) (len=3) "one": (bool) true // } // } // (spew_test.Flag) Unknown flag (5) // ([]uint8) (len=34 cap=34) { // 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| // } // } // This example demonstrates how to use Printf to display a variable with a // format string and inline formatting. func ExamplePrintf() { // Create a double pointer to a uint 8. ui8 := uint8(5) pui8 := &ui8 ppui8 := &pui8 // Create a circular data type. type circular struct { ui8 uint8 c *circular } c := circular{ui8: 1} c.c = &c // Print! spew.Printf("ppui8: %v\n", ppui8) spew.Printf("circular: %v\n", c) // Output: // ppui8: <**>5 // circular: {1 <*>{1 <*>}} } // This example demonstrates how to use a ConfigState. func ExampleConfigState() { // Modify the indent level of the ConfigState only. The global // configuration is not modified. scs := spew.ConfigState{Indent: "\t"} // Output using the ConfigState instance. v := map[string]int{"one": 1} scs.Printf("v: %v\n", v) scs.Dump(v) // Output: // v: map[one:1] // (map[string]int) (len=1) { // (string) (len=3) "one": (int) 1 // } } // This example demonstrates how to use ConfigState.Dump to dump variables to // stdout func ExampleConfigState_Dump() { // See the top-level Dump example for details on the types used in this // example. // Create two ConfigState instances with different indentation. scs := spew.ConfigState{Indent: "\t"} scs2 := spew.ConfigState{Indent: " "} // Setup some sample data structures for the example. bar := Bar{Flag(flagTwo), uintptr(0)} s1 := Foo{bar, map[interface{}]interface{}{"one": true}} // Dump using the ConfigState instances. scs.Dump(s1) scs2.Dump(s1) // Output: // (spew_test.Foo) { // unexportedField: (spew_test.Bar) { // flag: (spew_test.Flag) flagTwo, // data: (uintptr) // }, // ExportedField: (map[interface {}]interface {}) (len=1) { // (string) (len=3) "one": (bool) true // } // } // (spew_test.Foo) { // unexportedField: (spew_test.Bar) { // flag: (spew_test.Flag) flagTwo, // data: (uintptr) // }, // ExportedField: (map[interface {}]interface {}) (len=1) { // (string) (len=3) "one": (bool) true // } // } // } // This example demonstrates how to use ConfigState.Printf to display a variable // with a format string and inline formatting. func ExampleConfigState_Printf() { // See the top-level Dump example for details on the types used in this // example. // Create two ConfigState instances and modify the method handling of the // first ConfigState only. scs := spew.NewDefaultConfig() scs2 := spew.NewDefaultConfig() scs.DisableMethods = true // Alternatively // scs := spew.ConfigState{Indent: " ", DisableMethods: true} // scs2 := spew.ConfigState{Indent: " "} // This is of type Flag which implements a Stringer and has raw value 1. f := flagTwo // Dump using the ConfigState instances. scs.Printf("f: %v\n", f) scs2.Printf("f: %v\n", f) // Output: // f: 1 // f: flagTwo } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/format.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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) } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/format_test.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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. */ /* Test Summary: NOTE: For each test, a nil pointer, a single pointer and double pointer to the base test element are also tested to ensure proper indirection across all types. - Max int8, int16, int32, int64, int - Max uint8, uint16, uint32, uint64, uint - Boolean true and false - Standard complex64 and complex128 - Array containing standard ints - Array containing type with custom formatter on pointer receiver only - Array containing interfaces - Slice containing standard float32 values - Slice containing type with custom formatter on pointer receiver only - Slice containing interfaces - Nil slice - Standard string - Nil interface - Sub-interface - Map with string keys and int vals - Map with custom formatter type on pointer receiver only keys and vals - Map with interface keys and values - Map with nil interface value - Struct with primitives - Struct that contains another struct - Struct that contains custom type with Stringer pointer interface via both exported and unexported fields - Struct that contains embedded struct and field to same struct - Uintptr to 0 (null pointer) - Uintptr address of real variable - Unsafe.Pointer to 0 (null pointer) - Unsafe.Pointer to address of real variable - Nil channel - Standard int channel - Function with no params and no returns - Function with param and no returns - Function with multiple params and multiple returns - Struct that is circular through self referencing - Structs that are circular through cross referencing - Structs that are indirectly circular - Type that panics in its Stringer interface - Type that has a custom Error interface - %x passthrough with uint - %#x passthrough with uint - %f passthrough with precision - %f passthrough with width and precision - %d passthrough with width - %q passthrough with string */ package spew_test import ( "bytes" "fmt" "testing" "unsafe" "github.com/davecgh/go-spew/spew" ) // formatterTest is used to describe a test to be perfomed against NewFormatter. type formatterTest struct { format string in interface{} wants []string } // formatterTests houses all of the tests to be performed against NewFormatter. var formatterTests = make([]formatterTest, 0) // addFormatterTest is a helper method to append the passed input and desired // result to formatterTests. func addFormatterTest(format string, in interface{}, wants ...string) { test := formatterTest{format, in, wants} formatterTests = append(formatterTests, test) } func addIntFormatterTests() { // Max int8. v := int8(127) nv := (*int8)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "int8" vs := "127" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Max int16. v2 := int16(32767) nv2 := (*int16)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "int16" v2s := "32767" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Max int32. v3 := int32(2147483647) nv3 := (*int32)(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "int32" v3s := "2147483647" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%v", nv3, "") addFormatterTest("%+v", v3, v3s) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") // Max int64. v4 := int64(9223372036854775807) nv4 := (*int64)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "int64" v4s := "9223372036854775807" addFormatterTest("%v", v4, v4s) addFormatterTest("%v", pv4, "<*>"+v4s) addFormatterTest("%v", &pv4, "<**>"+v4s) addFormatterTest("%v", nv4, "") addFormatterTest("%+v", v4, v4s) addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%#v", v4, "("+v4t+")"+v4s) addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") // Max int. v5 := int(2147483647) nv5 := (*int)(nil) pv5 := &v5 v5Addr := fmt.Sprintf("%p", pv5) pv5Addr := fmt.Sprintf("%p", &pv5) v5t := "int" v5s := "2147483647" addFormatterTest("%v", v5, v5s) addFormatterTest("%v", pv5, "<*>"+v5s) addFormatterTest("%v", &pv5, "<**>"+v5s) addFormatterTest("%v", nv5, "") addFormatterTest("%+v", v5, v5s) addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) addFormatterTest("%+v", nv5, "") addFormatterTest("%#v", v5, "("+v5t+")"+v5s) addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"") } func addUintFormatterTests() { // Max uint8. v := uint8(255) nv := (*uint8)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "uint8" vs := "255" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Max uint16. v2 := uint16(65535) nv2 := (*uint16)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "uint16" v2s := "65535" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Max uint32. v3 := uint32(4294967295) nv3 := (*uint32)(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "uint32" v3s := "4294967295" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%v", nv3, "") addFormatterTest("%+v", v3, v3s) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") // Max uint64. v4 := uint64(18446744073709551615) nv4 := (*uint64)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "uint64" v4s := "18446744073709551615" addFormatterTest("%v", v4, v4s) addFormatterTest("%v", pv4, "<*>"+v4s) addFormatterTest("%v", &pv4, "<**>"+v4s) addFormatterTest("%v", nv4, "") addFormatterTest("%+v", v4, v4s) addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%#v", v4, "("+v4t+")"+v4s) addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") // Max uint. v5 := uint(4294967295) nv5 := (*uint)(nil) pv5 := &v5 v5Addr := fmt.Sprintf("%p", pv5) pv5Addr := fmt.Sprintf("%p", &pv5) v5t := "uint" v5s := "4294967295" addFormatterTest("%v", v5, v5s) addFormatterTest("%v", pv5, "<*>"+v5s) addFormatterTest("%v", &pv5, "<**>"+v5s) addFormatterTest("%v", nv5, "") addFormatterTest("%+v", v5, v5s) addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s) addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s) addFormatterTest("%+v", nv5, "") addFormatterTest("%#v", v5, "("+v5t+")"+v5s) addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s) addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s) addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") addFormatterTest("%#+v", v5, "("+v5t+")"+v5s) addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s) addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s) addFormatterTest("%#v", nv5, "(*"+v5t+")"+"") } func addBoolFormatterTests() { // Boolean true. v := bool(true) nv := (*bool)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "bool" vs := "true" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Boolean false. v2 := bool(false) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "bool" v2s := "false" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) } func addFloatFormatterTests() { // Standard float32. v := float32(3.1415) nv := (*float32)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "float32" vs := "3.1415" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Standard float64. v2 := float64(3.1415926) nv2 := (*float64)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "float64" v2s := "3.1415926" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") } func addComplexFormatterTests() { // Standard complex64. v := complex(float32(6), -2) nv := (*complex64)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "complex64" vs := "(6-2i)" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Standard complex128. v2 := complex(float64(-6), 2) nv2 := (*complex128)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "complex128" v2s := "(-6+2i)" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") } func addArrayFormatterTests() { // Array containing standard ints. v := [3]int{1, 2, 3} nv := (*[3]int)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "[3]int" vs := "[1 2 3]" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Array containing type with custom formatter on pointer receiver only. v2 := [3]pstringer{"1", "2", "3"} nv2 := (*[3]pstringer)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "[3]spew_test.pstringer" v2s := "[stringer 1 stringer 2 stringer 3]" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Array containing interfaces. v3 := [3]interface{}{"one", int(2), uint(3)} nv3 := (*[3]interface{})(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "[3]interface {}" v3t2 := "string" v3t3 := "int" v3t4 := "uint" v3s := "[one 2 3]" v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%+v", v3, v3s) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") } func addSliceFormatterTests() { // Slice containing standard float32 values. v := []float32{3.14, 6.28, 12.56} nv := (*[]float32)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "[]float32" vs := "[3.14 6.28 12.56]" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Slice containing type with custom formatter on pointer receiver only. v2 := []pstringer{"1", "2", "3"} nv2 := (*[]pstringer)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "[]spew_test.pstringer" v2s := "[stringer 1 stringer 2 stringer 3]" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Slice containing interfaces. v3 := []interface{}{"one", int(2), uint(3), nil} nv3 := (*[]interface{})(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "[]interface {}" v3t2 := "string" v3t3 := "int" v3t4 := "uint" v3t5 := "interface {}" v3s := "[one 2 3 ]" v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 + ")]" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%+v", v3, v3s) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") // Nil slice. var v4 []int nv4 := (*[]int)(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "[]int" v4s := "" addFormatterTest("%v", v4, v4s) addFormatterTest("%v", pv4, "<*>"+v4s) addFormatterTest("%v", &pv4, "<**>"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%+v", v4, v4s) addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%#v", v4, "("+v4t+")"+v4s) addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s) addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s) addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") addFormatterTest("%#+v", v4, "("+v4t+")"+v4s) addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s) addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") } func addStringFormatterTests() { // Standard string. v := "test" nv := (*string)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "string" vs := "test" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") } func addInterfaceFormatterTests() { // Nil interface. var v interface{} nv := (*interface{})(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "interface {}" vs := "" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Sub-interface. v2 := interface{}(uint16(65535)) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "uint16" v2s := "65535" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) } func addMapFormatterTests() { // Map with string keys and int vals. v := map[string]int{"one": 1, "two": 2} nilMap := map[string]int(nil) nv := (*map[string]int)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "map[string]int" vs := "map[one:1 two:2]" vs2 := "map[two:2 one:1]" addFormatterTest("%v", v, vs, vs2) addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2) addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2) addFormatterTest("%+v", nilMap, "") addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs, vs2) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs, "<**>("+pvAddr+"->"+vAddr+")"+vs2) addFormatterTest("%+v", nilMap, "") addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2) addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2) addFormatterTest("%#v", nilMap, "("+vt+")"+"") addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs, "(*"+vt+")("+vAddr+")"+vs2) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2) addFormatterTest("%#+v", nilMap, "("+vt+")"+"") addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Map with custom formatter type on pointer receiver only keys and vals. v2 := map[pstringer]pstringer{"one": "1"} nv2 := (*map[pstringer]pstringer)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "map[spew_test.pstringer]spew_test.pstringer" v2s := "map[stringer one:stringer 1]" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Map with interface keys and values. v3 := map[interface{}]interface{}{"one": 1} nv3 := (*map[interface{}]interface{})(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "map[interface {}]interface {}" v3t1 := "string" v3t2 := "int" v3s := "map[one:1]" v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%+v", v3, v3s) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s2) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2) addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") // Map with nil interface value v4 := map[string]interface{}{"nil": nil} nv4 := (*map[string]interface{})(nil) pv4 := &v4 v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "map[string]interface {}" v4t1 := "interface {}" v4s := "map[nil:]" v4s2 := "map[nil:(" + v4t1 + ")]" addFormatterTest("%v", v4, v4s) addFormatterTest("%v", pv4, "<*>"+v4s) addFormatterTest("%v", &pv4, "<**>"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%+v", v4, v4s) addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s) addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%#v", v4, "("+v4t+")"+v4s2) addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2) addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2) addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2) addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2) addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2) addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") } func addStructFormatterTests() { // Struct with primitives. type s1 struct { a int8 b uint8 } v := s1{127, 255} nv := (*s1)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.s1" vt2 := "int8" vt3 := "uint8" vs := "{127 255}" vs2 := "{a:127 b:255}" vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs2) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs3) addFormatterTest("%#v", pv, "(*"+vt+")"+vs3) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs3) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Struct that contains another struct. type s2 struct { s1 s1 b bool } v2 := s2{s1{127, 255}, true} nv2 := (*s2)(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "spew_test.s2" v2t2 := "spew_test.s1" v2t3 := "int8" v2t4 := "uint8" v2t5 := "bool" v2s := "{{127 255} true}" v2s2 := "{s1:{a:127 b:255} b:true}" v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" + v2t5 + ")true}" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s2) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s3) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Struct that contains custom type with Stringer pointer interface via both // exported and unexported fields. type s3 struct { s pstringer S pstringer } v3 := s3{"test", "test2"} nv3 := (*s3)(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "spew_test.s3" v3t2 := "spew_test.pstringer" v3s := "{stringer test stringer test2}" v3s2 := "{s:stringer test S:stringer test2}" v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%+v", v3, v3s2) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s3) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3) addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") // Struct that contains embedded struct and field to same struct. e := embed{"embedstr"} v4 := embedwrap{embed: &e, e: &e} nv4 := (*embedwrap)(nil) pv4 := &v4 eAddr := fmt.Sprintf("%p", &e) v4Addr := fmt.Sprintf("%p", pv4) pv4Addr := fmt.Sprintf("%p", &pv4) v4t := "spew_test.embedwrap" v4t2 := "spew_test.embed" v4t3 := "string" v4s := "{<*>{embedstr} <*>{embedstr}}" v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr + "){a:embedstr}}" v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr}}" v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}" addFormatterTest("%v", v4, v4s) addFormatterTest("%v", pv4, "<*>"+v4s) addFormatterTest("%v", &pv4, "<**>"+v4s) addFormatterTest("%+v", nv4, "") addFormatterTest("%+v", v4, v4s2) addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2) addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2) addFormatterTest("%+v", nv4, "") addFormatterTest("%#v", v4, "("+v4t+")"+v4s3) addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3) addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3) addFormatterTest("%#v", nv4, "(*"+v4t+")"+"") addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4) addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4) addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4) addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"") } func addUintptrFormatterTests() { // Null pointer. v := uintptr(0) nv := (*uintptr)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "uintptr" vs := "" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Address of real variable. i := 1 v2 := uintptr(unsafe.Pointer(&i)) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "uintptr" v2s := fmt.Sprintf("%p", &i) addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) } func addUnsafePointerFormatterTests() { // Null pointer. v := unsafe.Pointer(uintptr(0)) nv := (*unsafe.Pointer)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "unsafe.Pointer" vs := "" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Address of real variable. i := 1 v2 := unsafe.Pointer(&i) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "unsafe.Pointer" v2s := fmt.Sprintf("%p", &i) addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) } func addChanFormatterTests() { // Nil channel. var v chan int pv := &v nv := (*chan int)(nil) vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "chan int" vs := "" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Real channel. v2 := make(chan int) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "chan int" v2s := fmt.Sprintf("%p", v2) addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) } func addFuncFormatterTests() { // Function with no params and no returns. v := addIntFormatterTests nv := (*func())(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "func()" vs := fmt.Sprintf("%p", v) addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") // Function with param and no returns. v2 := TestFormatter nv2 := (*func(*testing.T))(nil) pv2 := &v2 v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "func(*testing.T)" v2s := fmt.Sprintf("%p", v2) addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s) addFormatterTest("%v", &pv2, "<**>"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%+v", v2, v2s) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%+v", nv2, "") addFormatterTest("%#v", v2, "("+v2t+")"+v2s) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s) addFormatterTest("%#v", nv2, "(*"+v2t+")"+"") addFormatterTest("%#+v", v2, "("+v2t+")"+v2s) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s) addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"") // Function with multiple params and multiple returns. var v3 = func(i int, s string) (b bool, err error) { return true, nil } nv3 := (*func(int, string) (bool, error))(nil) pv3 := &v3 v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "func(int, string) (bool, error)" v3s := fmt.Sprintf("%p", v3) addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s) addFormatterTest("%v", &pv3, "<**>"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%+v", v3, v3s) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%+v", nv3, "") addFormatterTest("%#v", v3, "("+v3t+")"+v3s) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s) addFormatterTest("%#v", nv3, "(*"+v3t+")"+"") addFormatterTest("%#+v", v3, "("+v3t+")"+v3s) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s) addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"") } func addCircularFormatterTests() { // Struct that is circular through self referencing. type circular struct { c *circular } v := circular{nil} v.c = &v pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.circular" vs := "{<*>{<*>}}" vs2 := "{<*>}" vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}" vs4 := "{c:<*>(" + vAddr + ")}" vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}" vs6 := "{c:(*" + vt + ")}" vs7 := "{c:(*" + vt + ")(" + vAddr + "){c:(*" + vt + ")(" + vAddr + ")}}" vs8 := "{c:(*" + vt + ")(" + vAddr + ")}" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs2) addFormatterTest("%v", &pv, "<**>"+vs2) addFormatterTest("%+v", v, vs3) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs4) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs4) addFormatterTest("%#v", v, "("+vt+")"+vs5) addFormatterTest("%#v", pv, "(*"+vt+")"+vs6) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs6) addFormatterTest("%#+v", v, "("+vt+")"+vs7) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs8) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs8) // Structs that are circular through cross referencing. v2 := xref1{nil} ts2 := xref2{&v2} v2.ps2 = &ts2 pv2 := &v2 ts2Addr := fmt.Sprintf("%p", &ts2) v2Addr := fmt.Sprintf("%p", pv2) pv2Addr := fmt.Sprintf("%p", &pv2) v2t := "spew_test.xref1" v2t2 := "spew_test.xref2" v2s := "{<*>{<*>{<*>}}}" v2s2 := "{<*>{<*>}}" v2s3 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + "){ps2:<*>(" + ts2Addr + ")}}}" v2s4 := "{ps2:<*>(" + ts2Addr + "){ps1:<*>(" + v2Addr + ")}}" v2s5 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + "){ps2:(*" + v2t2 + ")}}}" v2s6 := "{ps2:(*" + v2t2 + "){ps1:(*" + v2t + ")}}" v2s7 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + ")(" + v2Addr + "){ps2:(*" + v2t2 + ")(" + ts2Addr + ")}}}" v2s8 := "{ps2:(*" + v2t2 + ")(" + ts2Addr + "){ps1:(*" + v2t + ")(" + v2Addr + ")}}" addFormatterTest("%v", v2, v2s) addFormatterTest("%v", pv2, "<*>"+v2s2) addFormatterTest("%v", &pv2, "<**>"+v2s2) addFormatterTest("%+v", v2, v2s3) addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s4) addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s4) addFormatterTest("%#v", v2, "("+v2t+")"+v2s5) addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s6) addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s6) addFormatterTest("%#+v", v2, "("+v2t+")"+v2s7) addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s8) addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s8) // Structs that are indirectly circular. v3 := indirCir1{nil} tic2 := indirCir2{nil} tic3 := indirCir3{&v3} tic2.ps3 = &tic3 v3.ps2 = &tic2 pv3 := &v3 tic2Addr := fmt.Sprintf("%p", &tic2) tic3Addr := fmt.Sprintf("%p", &tic3) v3Addr := fmt.Sprintf("%p", pv3) pv3Addr := fmt.Sprintf("%p", &pv3) v3t := "spew_test.indirCir1" v3t2 := "spew_test.indirCir2" v3t3 := "spew_test.indirCir3" v3s := "{<*>{<*>{<*>{<*>}}}}" v3s2 := "{<*>{<*>{<*>}}}" v3s3 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + v3Addr + "){ps2:<*>(" + tic2Addr + ")}}}}" v3s4 := "{ps2:<*>(" + tic2Addr + "){ps3:<*>(" + tic3Addr + "){ps1:<*>(" + v3Addr + ")}}}" v3s5 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + "){ps2:(*" + v3t2 + ")}}}}" v3s6 := "{ps2:(*" + v3t2 + "){ps3:(*" + v3t3 + "){ps1:(*" + v3t + ")}}}" v3s7 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + "){ps2:(*" + v3t2 + ")(" + tic2Addr + ")}}}}" v3s8 := "{ps2:(*" + v3t2 + ")(" + tic2Addr + "){ps3:(*" + v3t3 + ")(" + tic3Addr + "){ps1:(*" + v3t + ")(" + v3Addr + ")}}}" addFormatterTest("%v", v3, v3s) addFormatterTest("%v", pv3, "<*>"+v3s2) addFormatterTest("%v", &pv3, "<**>"+v3s2) addFormatterTest("%+v", v3, v3s3) addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s4) addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s4) addFormatterTest("%#v", v3, "("+v3t+")"+v3s5) addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s6) addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s6) addFormatterTest("%#+v", v3, "("+v3t+")"+v3s7) addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s8) addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s8) } func addPanicFormatterTests() { // Type that panics in its Stringer interface. v := panicer(127) nv := (*panicer)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.panicer" vs := "(PANIC=test panic)127" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") } func addErrorFormatterTests() { // Type that has a custom Error interface. v := customError(127) nv := (*customError)(nil) pv := &v vAddr := fmt.Sprintf("%p", pv) pvAddr := fmt.Sprintf("%p", &pv) vt := "spew_test.customError" vs := "error: 127" addFormatterTest("%v", v, vs) addFormatterTest("%v", pv, "<*>"+vs) addFormatterTest("%v", &pv, "<**>"+vs) addFormatterTest("%v", nv, "") addFormatterTest("%+v", v, vs) addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs) addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%+v", nv, "") addFormatterTest("%#v", v, "("+vt+")"+vs) addFormatterTest("%#v", pv, "(*"+vt+")"+vs) addFormatterTest("%#v", &pv, "(**"+vt+")"+vs) addFormatterTest("%#v", nv, "(*"+vt+")"+"") addFormatterTest("%#+v", v, "("+vt+")"+vs) addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs) addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs) addFormatterTest("%#+v", nv, "(*"+vt+")"+"") } func addPassthroughFormatterTests() { // %x passthrough with uint. v := uint(4294967295) pv := &v vAddr := fmt.Sprintf("%x", pv) pvAddr := fmt.Sprintf("%x", &pv) vs := "ffffffff" addFormatterTest("%x", v, vs) addFormatterTest("%x", pv, vAddr) addFormatterTest("%x", &pv, pvAddr) // %#x passthrough with uint. v2 := int(2147483647) pv2 := &v2 v2Addr := fmt.Sprintf("%#x", pv2) pv2Addr := fmt.Sprintf("%#x", &pv2) v2s := "0x7fffffff" addFormatterTest("%#x", v2, v2s) addFormatterTest("%#x", pv2, v2Addr) addFormatterTest("%#x", &pv2, pv2Addr) // %f passthrough with precision. addFormatterTest("%.2f", 3.1415, "3.14") addFormatterTest("%.3f", 3.1415, "3.142") addFormatterTest("%.4f", 3.1415, "3.1415") // %f passthrough with width and precision. addFormatterTest("%5.2f", 3.1415, " 3.14") addFormatterTest("%6.3f", 3.1415, " 3.142") addFormatterTest("%7.4f", 3.1415, " 3.1415") // %d passthrough with width. addFormatterTest("%3d", 127, "127") addFormatterTest("%4d", 127, " 127") addFormatterTest("%5d", 127, " 127") // %q passthrough with string. addFormatterTest("%q", "test", "\"test\"") } // TestFormatter executes all of the tests described by formatterTests. func TestFormatter(t *testing.T) { // Setup tests. addIntFormatterTests() addUintFormatterTests() addBoolFormatterTests() addFloatFormatterTests() addComplexFormatterTests() addArrayFormatterTests() addSliceFormatterTests() addStringFormatterTests() addInterfaceFormatterTests() addMapFormatterTests() addStructFormatterTests() addUintptrFormatterTests() addUnsafePointerFormatterTests() addChanFormatterTests() addFuncFormatterTests() addCircularFormatterTests() addPanicFormatterTests() addErrorFormatterTests() addPassthroughFormatterTests() t.Logf("Running %d tests", len(formatterTests)) for i, test := range formatterTests { buf := new(bytes.Buffer) spew.Fprintf(buf, test.format, test.in) s := buf.String() if testFailed(s, test.wants) { t.Errorf("Formatter #%d format: %s got: %s %s", i, test.format, s, stringizeWants(test.wants)) continue } } } type testStruct struct { x int } func (ts testStruct) String() string { return fmt.Sprintf("ts.%d", ts.x) } type testStructP struct { x int } func (ts *testStructP) String() string { return fmt.Sprintf("ts.%d", ts.x) } func TestPrintSortedKeys(t *testing.T) { cfg := spew.ConfigState{SortKeys: true} s := cfg.Sprint(map[int]string{1: "1", 3: "3", 2: "2"}) expected := "map[1:1 2:2 3:3]" if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sprint(map[stringer]int{"1": 1, "3": 3, "2": 2}) expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sprint(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2}) expected = "map[stringer 1:1 stringer 2:2 stringer 3:3]" if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sprint(map[testStruct]int{testStruct{1}: 1, testStruct{3}: 3, testStruct{2}: 2}) expected = "map[ts.1:1 ts.2:2 ts.3:3]" if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sprint(map[testStructP]int{testStructP{1}: 1, testStructP{3}: 3, testStructP{2}: 2}) expected = "map[ts.1:1 ts.2:2 ts.3:3]" if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } s = cfg.Sprint(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2}) expected = "map[error: 1:1 error: 2:2 error: 3:3]" if s != expected { t.Errorf("Sorted keys mismatch:\n %v %v", s, expected) } } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/internal_test.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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. */ /* This test file is part of the spew package rather than than the spew_test package because it needs access to internals to properly test certain cases which are not possible via the public interface since they should never happen. */ package spew import ( "bytes" "reflect" "testing" "unsafe" ) // dummyFmtState implements a fake fmt.State to use for testing invalid // reflect.Value handling. This is necessary because the fmt package catches // invalid values before invoking the formatter on them. type dummyFmtState struct { bytes.Buffer } func (dfs *dummyFmtState) Flag(f int) bool { if f == int('+') { return true } return false } func (dfs *dummyFmtState) Precision() (int, bool) { return 0, false } func (dfs *dummyFmtState) Width() (int, bool) { return 0, false } // TestInvalidReflectValue ensures the dump and formatter code handles an // invalid reflect value properly. This needs access to internal state since it // should never happen in real code and therefore can't be tested via the public // API. func TestInvalidReflectValue(t *testing.T) { i := 1 // Dump invalid reflect value. v := new(reflect.Value) buf := new(bytes.Buffer) d := dumpState{w: buf, cs: &Config} d.dump(*v) s := buf.String() want := "" if s != want { t.Errorf("InvalidReflectValue #%d\n got: %s want: %s", i, s, want) } i++ // Formatter invalid reflect value. buf2 := new(dummyFmtState) f := formatState{value: *v, cs: &Config, fs: buf2} f.format(*v) s = buf2.String() want = "" if s != want { t.Errorf("InvalidReflectValue #%d got: %s want: %s", i, s, want) } } // changeKind uses unsafe to intentionally change the kind of a reflect.Value to // the maximum kind value which does not exist. This is needed to test the // fallback code which punts to the standard fmt library for new types that // might get added to the language. func changeKind(v *reflect.Value, readOnly bool) { rvf := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + offsetFlag)) *rvf = *rvf | ((1< * * 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 } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/spew_test.go ================================================ /* * Copyright (c) 2013 Dave Collins * * 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_test import ( "bytes" "fmt" "github.com/davecgh/go-spew/spew" "io/ioutil" "os" "testing" ) // spewFunc is used to identify which public function of the spew package or // ConfigState a test applies to. type spewFunc int const ( fCSFdump spewFunc = iota fCSFprint fCSFprintf fCSFprintln fCSPrint fCSPrintln fCSSdump fCSSprint fCSSprintf fCSSprintln fCSErrorf fCSNewFormatter fErrorf fFprint fFprintln fPrint fPrintln fSdump fSprint fSprintf fSprintln ) // Map of spewFunc values to names for pretty printing. var spewFuncStrings = map[spewFunc]string{ fCSFdump: "ConfigState.Fdump", fCSFprint: "ConfigState.Fprint", fCSFprintf: "ConfigState.Fprintf", fCSFprintln: "ConfigState.Fprintln", fCSSdump: "ConfigState.Sdump", fCSPrint: "ConfigState.Print", fCSPrintln: "ConfigState.Println", fCSSprint: "ConfigState.Sprint", fCSSprintf: "ConfigState.Sprintf", fCSSprintln: "ConfigState.Sprintln", fCSErrorf: "ConfigState.Errorf", fCSNewFormatter: "ConfigState.NewFormatter", fErrorf: "spew.Errorf", fFprint: "spew.Fprint", fFprintln: "spew.Fprintln", fPrint: "spew.Print", fPrintln: "spew.Println", fSdump: "spew.Sdump", fSprint: "spew.Sprint", fSprintf: "spew.Sprintf", fSprintln: "spew.Sprintln", } func (f spewFunc) String() string { if s, ok := spewFuncStrings[f]; ok { return s } return fmt.Sprintf("Unknown spewFunc (%d)", int(f)) } // spewTest is used to describe a test to be performed against the public // functions of the spew package or ConfigState. type spewTest struct { cs *spew.ConfigState f spewFunc format string in interface{} want string } // spewTests houses the tests to be performed against the public functions of // the spew package and ConfigState. // // These tests are only intended to ensure the public functions are exercised // and are intentionally not exhaustive of types. The exhaustive type // tests are handled in the dump and format tests. var spewTests []spewTest // redirStdout is a helper function to return the standard output from f as a // byte slice. func redirStdout(f func()) ([]byte, error) { tempFile, err := ioutil.TempFile("", "ss-test") if err != nil { return nil, err } fileName := tempFile.Name() defer os.Remove(fileName) // Ignore error origStdout := os.Stdout os.Stdout = tempFile f() os.Stdout = origStdout tempFile.Close() return ioutil.ReadFile(fileName) } func initSpewTests() { // Config states with various settings. scsDefault := spew.NewDefaultConfig() scsNoMethods := &spew.ConfigState{Indent: " ", DisableMethods: true} scsNoPmethods := &spew.ConfigState{Indent: " ", DisablePointerMethods: true} scsMaxDepth := &spew.ConfigState{Indent: " ", MaxDepth: 1} scsContinue := &spew.ConfigState{Indent: " ", ContinueOnMethod: true} // Variables for tests on types which implement Stringer interface with and // without a pointer receiver. ts := stringer("test") tps := pstringer("test") // depthTester is used to test max depth handling for structs, array, slices // and maps. type depthTester struct { ic indirCir1 arr [1]string slice []string m map[string]int } dt := depthTester{indirCir1{nil}, [1]string{"arr"}, []string{"slice"}, map[string]int{"one": 1}} // Variable for tests on types which implement error interface. te := customError(10) spewTests = []spewTest{ {scsDefault, fCSFdump, "", int8(127), "(int8) 127\n"}, {scsDefault, fCSFprint, "", int16(32767), "32767"}, {scsDefault, fCSFprintf, "%v", int32(2147483647), "2147483647"}, {scsDefault, fCSFprintln, "", int(2147483647), "2147483647\n"}, {scsDefault, fCSPrint, "", int64(9223372036854775807), "9223372036854775807"}, {scsDefault, fCSPrintln, "", uint8(255), "255\n"}, {scsDefault, fCSSdump, "", uint8(64), "(uint8) 64\n"}, {scsDefault, fCSSprint, "", complex(1, 2), "(1+2i)"}, {scsDefault, fCSSprintf, "%v", complex(float32(3), 4), "(3+4i)"}, {scsDefault, fCSSprintln, "", complex(float64(5), 6), "(5+6i)\n"}, {scsDefault, fCSErrorf, "%#v", uint16(65535), "(uint16)65535"}, {scsDefault, fCSNewFormatter, "%v", uint32(4294967295), "4294967295"}, {scsDefault, fErrorf, "%v", uint64(18446744073709551615), "18446744073709551615"}, {scsDefault, fFprint, "", float32(3.14), "3.14"}, {scsDefault, fFprintln, "", float64(6.28), "6.28\n"}, {scsDefault, fPrint, "", true, "true"}, {scsDefault, fPrintln, "", false, "false\n"}, {scsDefault, fSdump, "", complex(-10, -20), "(complex128) (-10-20i)\n"}, {scsDefault, fSprint, "", complex(-1, -2), "(-1-2i)"}, {scsDefault, fSprintf, "%v", complex(float32(-3), -4), "(-3-4i)"}, {scsDefault, fSprintln, "", complex(float64(-5), -6), "(-5-6i)\n"}, {scsNoMethods, fCSFprint, "", ts, "test"}, {scsNoMethods, fCSFprint, "", &ts, "<*>test"}, {scsNoMethods, fCSFprint, "", tps, "test"}, {scsNoMethods, fCSFprint, "", &tps, "<*>test"}, {scsNoPmethods, fCSFprint, "", ts, "stringer test"}, {scsNoPmethods, fCSFprint, "", &ts, "<*>stringer test"}, {scsNoPmethods, fCSFprint, "", tps, "test"}, {scsNoPmethods, fCSFprint, "", &tps, "<*>stringer test"}, {scsMaxDepth, fCSFprint, "", dt, "{{} [] [] map[]}"}, {scsMaxDepth, fCSFdump, "", dt, "(spew_test.depthTester) {\n" + " ic: (spew_test.indirCir1) {\n \n },\n" + " arr: ([1]string) (len=1 cap=1) {\n \n },\n" + " slice: ([]string) (len=1 cap=1) {\n \n },\n" + " m: (map[string]int) (len=1) {\n \n }\n}\n"}, {scsContinue, fCSFprint, "", ts, "(stringer test) test"}, {scsContinue, fCSFdump, "", ts, "(spew_test.stringer) " + "(len=4) (stringer test) \"test\"\n"}, {scsContinue, fCSFprint, "", te, "(error: 10) 10"}, {scsContinue, fCSFdump, "", te, "(spew_test.customError) " + "(error: 10) 10\n"}, } } // TestSpew executes all of the tests described by spewTests. func TestSpew(t *testing.T) { initSpewTests() t.Logf("Running %d tests", len(spewTests)) for i, test := range spewTests { buf := new(bytes.Buffer) switch test.f { case fCSFdump: test.cs.Fdump(buf, test.in) case fCSFprint: test.cs.Fprint(buf, test.in) case fCSFprintf: test.cs.Fprintf(buf, test.format, test.in) case fCSFprintln: test.cs.Fprintln(buf, test.in) case fCSPrint: b, err := redirStdout(func() { test.cs.Print(test.in) }) if err != nil { t.Errorf("%v #%d %v", test.f, i, err) continue } buf.Write(b) case fCSPrintln: b, err := redirStdout(func() { test.cs.Println(test.in) }) if err != nil { t.Errorf("%v #%d %v", test.f, i, err) continue } buf.Write(b) case fCSSdump: str := test.cs.Sdump(test.in) buf.WriteString(str) case fCSSprint: str := test.cs.Sprint(test.in) buf.WriteString(str) case fCSSprintf: str := test.cs.Sprintf(test.format, test.in) buf.WriteString(str) case fCSSprintln: str := test.cs.Sprintln(test.in) buf.WriteString(str) case fCSErrorf: err := test.cs.Errorf(test.format, test.in) buf.WriteString(err.Error()) case fCSNewFormatter: fmt.Fprintf(buf, test.format, test.cs.NewFormatter(test.in)) case fErrorf: err := spew.Errorf(test.format, test.in) buf.WriteString(err.Error()) case fFprint: spew.Fprint(buf, test.in) case fFprintln: spew.Fprintln(buf, test.in) case fPrint: b, err := redirStdout(func() { spew.Print(test.in) }) if err != nil { t.Errorf("%v #%d %v", test.f, i, err) continue } buf.Write(b) case fPrintln: b, err := redirStdout(func() { spew.Println(test.in) }) if err != nil { t.Errorf("%v #%d %v", test.f, i, err) continue } buf.Write(b) case fSdump: str := spew.Sdump(test.in) buf.WriteString(str) case fSprint: str := spew.Sprint(test.in) buf.WriteString(str) case fSprintf: str := spew.Sprintf(test.format, test.in) buf.WriteString(str) case fSprintln: str := spew.Sprintln(test.in) buf.WriteString(str) default: t.Errorf("%v #%d unrecognized function", test.f, i) continue } s := buf.String() if test.want != s { t.Errorf("ConfigState #%d\n got: %s want: %s", i, s, test.want) continue } } } ================================================ FILE: vendor/github.com/davecgh/go-spew/spew/testdata/dumpcgo.go ================================================ // Copyright (c) 2013 Dave Collins // // 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 both cgo is supported and "-tags testcgo" is added to the go test // command line. This code should really only be in the dumpcgo_test.go file, // but unfortunately Go will not allow cgo in test files, so this is a // workaround to allow cgo types to be tested. This configuration is used // because spew itself does not require cgo to run even though it does handle // certain cgo types specially. Rather than forcing all clients to require cgo // and an external C compiler just to run the tests, this scheme makes them // optional. // +build cgo,testcgo package testdata /* #include typedef unsigned char custom_uchar_t; char *ncp = 0; char *cp = "test"; char ca[6] = {'t', 'e', 's', 't', '2', '\0'}; unsigned char uca[6] = {'t', 'e', 's', 't', '3', '\0'}; signed char sca[6] = {'t', 'e', 's', 't', '4', '\0'}; uint8_t ui8ta[6] = {'t', 'e', 's', 't', '5', '\0'}; custom_uchar_t tuca[6] = {'t', 'e', 's', 't', '6', '\0'}; */ import "C" // GetCgoNullCharPointer returns a null char pointer via cgo. This is only // used for tests. func GetCgoNullCharPointer() interface{} { return C.ncp } // GetCgoCharPointer returns a char pointer via cgo. This is only used for // tests. func GetCgoCharPointer() interface{} { return C.cp } // GetCgoCharArray returns a char array via cgo and the array's len and cap. // This is only used for tests. func GetCgoCharArray() (interface{}, int, int) { return C.ca, len(C.ca), cap(C.ca) } // GetCgoUnsignedCharArray returns an unsigned char array via cgo and the // array's len and cap. This is only used for tests. func GetCgoUnsignedCharArray() (interface{}, int, int) { return C.uca, len(C.uca), cap(C.uca) } // GetCgoSignedCharArray returns a signed char array via cgo and the array's len // and cap. This is only used for tests. func GetCgoSignedCharArray() (interface{}, int, int) { return C.sca, len(C.sca), cap(C.sca) } // GetCgoUint8tArray returns a uint8_t array via cgo and the array's len and // cap. This is only used for tests. func GetCgoUint8tArray() (interface{}, int, int) { return C.ui8ta, len(C.ui8ta), cap(C.ui8ta) } // GetCgoTypdefedUnsignedCharArray returns a typedefed unsigned char array via // cgo and the array's len and cap. This is only used for tests. func GetCgoTypdefedUnsignedCharArray() (interface{}, int, int) { return C.tuca, len(C.tuca), cap(C.tuca) } ================================================ FILE: vendor/github.com/davecgh/go-spew/test_coverage.txt ================================================ github.com/davecgh/go-spew/spew/dump.go dumpState.dump 100.00% (88/88) github.com/davecgh/go-spew/spew/format.go formatState.format 100.00% (82/82) github.com/davecgh/go-spew/spew/format.go formatState.formatPtr 100.00% (52/52) github.com/davecgh/go-spew/spew/dump.go dumpState.dumpPtr 100.00% (44/44) github.com/davecgh/go-spew/spew/dump.go dumpState.dumpSlice 100.00% (39/39) github.com/davecgh/go-spew/spew/common.go handleMethods 100.00% (30/30) github.com/davecgh/go-spew/spew/common.go printHexPtr 100.00% (18/18) github.com/davecgh/go-spew/spew/common.go unsafeReflectValue 100.00% (13/13) github.com/davecgh/go-spew/spew/format.go formatState.constructOrigFormat 100.00% (12/12) github.com/davecgh/go-spew/spew/dump.go fdump 100.00% (11/11) github.com/davecgh/go-spew/spew/format.go formatState.Format 100.00% (11/11) github.com/davecgh/go-spew/spew/common.go init 100.00% (10/10) github.com/davecgh/go-spew/spew/common.go printComplex 100.00% (9/9) github.com/davecgh/go-spew/spew/common.go valuesSorter.Less 100.00% (8/8) github.com/davecgh/go-spew/spew/format.go formatState.buildDefaultFormat 100.00% (7/7) github.com/davecgh/go-spew/spew/format.go formatState.unpackValue 100.00% (5/5) github.com/davecgh/go-spew/spew/dump.go dumpState.indent 100.00% (4/4) github.com/davecgh/go-spew/spew/common.go catchPanic 100.00% (4/4) github.com/davecgh/go-spew/spew/config.go ConfigState.convertArgs 100.00% (4/4) github.com/davecgh/go-spew/spew/spew.go convertArgs 100.00% (4/4) github.com/davecgh/go-spew/spew/format.go newFormatter 100.00% (3/3) github.com/davecgh/go-spew/spew/dump.go Sdump 100.00% (3/3) github.com/davecgh/go-spew/spew/common.go printBool 100.00% (3/3) github.com/davecgh/go-spew/spew/common.go sortValues 100.00% (3/3) github.com/davecgh/go-spew/spew/config.go ConfigState.Sdump 100.00% (3/3) github.com/davecgh/go-spew/spew/dump.go dumpState.unpackValue 100.00% (3/3) github.com/davecgh/go-spew/spew/spew.go Printf 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Println 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Sprint 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Sprintf 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Sprintln 100.00% (1/1) github.com/davecgh/go-spew/spew/common.go printFloat 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go NewDefaultConfig 100.00% (1/1) github.com/davecgh/go-spew/spew/common.go printInt 100.00% (1/1) github.com/davecgh/go-spew/spew/common.go printUint 100.00% (1/1) github.com/davecgh/go-spew/spew/common.go valuesSorter.Len 100.00% (1/1) github.com/davecgh/go-spew/spew/common.go valuesSorter.Swap 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Errorf 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Fprint 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintf 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Fprintln 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Print 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Printf 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Println 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Sprint 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintf 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Sprintln 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.NewFormatter 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Fdump 100.00% (1/1) github.com/davecgh/go-spew/spew/config.go ConfigState.Dump 100.00% (1/1) github.com/davecgh/go-spew/spew/dump.go Fdump 100.00% (1/1) github.com/davecgh/go-spew/spew/dump.go Dump 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Fprintln 100.00% (1/1) github.com/davecgh/go-spew/spew/format.go NewFormatter 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Errorf 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Fprint 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Fprintf 100.00% (1/1) github.com/davecgh/go-spew/spew/spew.go Print 100.00% (1/1) github.com/davecgh/go-spew/spew ------------------------------- 100.00% (505/505) ================================================ FILE: vendor/github.com/docker/docker/.dockerignore ================================================ bundles .gopath ================================================ FILE: vendor/github.com/docker/docker/.gitignore ================================================ # Docker project generated files to ignore # if you want to ignore files created by your editor/tools, # please consider a global .gitignore https://help.github.com/articles/ignoring-files *.exe *.exe~ *.orig *.rej *.test .*.swp .DS_Store .bashrc .dotcloud .flymake* .git/ .gopath/ .hg/ .vagrant* Vagrantfile a.out autogen/ bin build_src bundles/ docker/docker docs/AWS_S3_BUCKET docs/GITCOMMIT docs/GIT_BRANCH docs/VERSION docs/_build docs/_static docs/_templates docs/changed-files # generated by man/man/md2man-all.sh man/man1 man/man5 pyenv vendor/pkg/ ================================================ FILE: vendor/github.com/docker/docker/.mailmap ================================================ # Generate AUTHORS: hack/generate-authors.sh # Tip for finding duplicates (besides scanning the output of AUTHORS for name # duplicates that aren't also email duplicates): scan the output of: # git log --format='%aE - %aN' | sort -uf # # For explanation on this file format: man git-shortlog Patrick Stapleton Shishir Mahajan Erwin van der Koogh Ahmed Kamal Tejesh Mehta Cristian Staretu Cristian Staretu Cristian Staretu Marcus Linke Aleksandrs Fadins Christopher Latham Hu Keping Wayne Chang Chen Chao Daehyeok Mun Guillaume J. Charmes Thatcher Peskens Thatcher Peskens Thatcher Peskens dhrp Jérôme Petazzoni jpetazzo Jérôme Petazzoni Joffrey F Joffrey F Joffrey F Tim Terhorst Andy Smith Walter Stanish Roberto Hashioka Konstantin Pelykh David Sissitka Nolan Darilek Benoit Chesneau Jordan Arentsen Daniel Garcia Miguel Angel Fernández Bhiraj Butala Faiz Khan Victor Lyuboslavsky Jean-Baptiste Barth Matthew Mueller Shih-Yuan Lee Daniel Mizyrycki root Jean-Baptiste Dalido Sven Dowideit Sven Dowideit Sven Dowideit Sven Dowideit <¨SvenDowideit@home.org.au¨> Sven Dowideit Sven Dowideit Alexandr Morozov O.S. Tezer Roberto G. Hashioka Sridhar Ratnakumar Sridhar Ratnakumar Liang-Chi Hsieh Aleksa Sarai Will Weaver Timothy Hobbs Nathan LeClaire Nathan LeClaire Matthew Heon Francisco Carriedo Brian Goff Hollie Teal Jessica Frazelle Jessie Frazelle Thomas LEVEIL Thomas LÉVEIL Antonio Murdaca Antonio Murdaca Antonio Murdaca Darren Shepherd Deshi Xiao Deshi Xiao Doug Davis Jacob Atzen Jeff Nickoloff John Howard (VM) John Howard Madhu Venugopal Mary Anthony Mary Anthony moxiegirl Mary Anthony mattyw resouer AJ Bowen soulshake AJ Bowen soulshake Tibor Vass Tibor Vass Vincent Bernat Yestin Sun bin liu John Howard (VM) jhowardmsft Ankush Agarwal Tangi COLIN tangicolin ================================================ FILE: vendor/github.com/docker/docker/AUTHORS ================================================ # This file lists all individuals having contributed content to the repository. # For how it is generated, see `hack/generate-authors.sh`. Aanand Prasad Aaron Davidson Aaron Feng Aaron Huslage Aaron Welch Abel Muiño Abhinav Ajgaonkar Abhishek Chanda Abin Shahab Adam Miller Adam Singer Aditya Adria Casas Adrian Mouat Adrien Folie Ahmed Kamal Ahmet Alp Balkan Aidan Hobson Sayers AJ Bowen Al Tobey alambike Alan Thompson Albert Callarisa Albert Zhang Aleksa Sarai Aleksandrs Fadins Alena Prokharchyk Alessandro Boch Alessio Biancalana Alex Gaynor Alex Warhawk Alexander Boyd Alexander Larsson Alexander Morozov Alexander Shopov Alexandr Morozov Alexey Guskov Alexey Kotlyarov Alexey Shamrin Alexis THOMAS Allen Madsen almoehi Alvin Richards amangoel Amit Bakshi Amy Lindburg Anand Patil AnandkumarPatel Anchal Agrawal Anders Janmyr Andre Dublin <81dublin@gmail.com> Andrea Luzzardi Andrea Turli Andreas Köhler Andreas Savvides Andreas Tiefenthaler Andrew C. Bodine Andrew Clay Shafer Andrew Duckworth Andrew France Andrew Kuklewicz Andrew Macgregor Andrew Martin Andrew Munsell Andrew Weiss Andrew Williams Andrews Medina Andrey Petrov Andrey Stolbovsky André Martins Andy Chambers andy diller Andy Goldstein Andy Kipp Andy Rothfusz Andy Smith Andy Wilson Anes Hasicic Ankush Agarwal Anthony Baire Anthony Bishopric Anton Löfgren Anton Nikitin Anton Tiurin Antonio Murdaca Antony Messerli apocas ArikaChen Arnaud Porterie Arthur Barr Arthur Gautier Asbjørn Enge averagehuman Avi Das Avi Miller Barnaby Gray Barry Allard Bartłomiej Piotrowski bdevloed Ben Firshman Ben Sargent Ben Severson Ben Toews Ben Wiklund Benjamin Atkin Benoit Chesneau Bernerd Schaefer Bert Goethals Bharath Thiruveedula Bhiraj Butala bin liu Blake Geno bobby abbott boucher Bouke Haarsma Boyd Hemphill Bradley Cicenas Bradley Wright Brandon Liu Brandon Philips Brandon Rhodes Brendan Dixon Brent Salisbury Brett Kochendorfer Brian (bex) Exelbierd Brian DeHamer Brian Dorsey Brian Flad Brian Goff Brian McCallister Brian Olsen Brian Shumate Brice Jaglin Briehan Lombaard Bruno Bigras Bruno Binet Bruno Gazzera Bruno Renié Bryan Bess Bryan Boreham Bryan Matsuo Bryan Murphy buddhamagnet Burke Libbey Byung Kang Caleb Spare Calen Pennington Cameron Boehmer Carl X. Su Cary Casey Bisson Charles Hooper Charles Lindsay Charles Merriam Charlie Lewis Chen Chao Chen Hanxiao cheney90 Chewey Chia-liang Kao chli Chris Alfonso Chris Armstrong Chris Khoo Chris Snow Chris St. Pierre Chris Stivers Chris Wahl chrismckinnel Christian Berendt Christian Simon Christian Stefanescu ChristoperBiscardi Christophe Troestler Christopher Currie Christopher Latham Christopher Rigor Christy Perez Chun Chen Ciro S. Costa Clayton Coleman Coenraad Loubser Colin Dunklau Colin Rice Colin Walters Colm Hally Cory Forsyth cressie176 Cristian Staretu Cruceru Calin-Cristian Cyril F Daan van Berkel Daehyeok Mun Dafydd Crosby dalanlan Damjan Georgievski Dan Anolik Dan Buch Dan Cotora Dan Griffin Dan Hirsch Dan Keder Dan McPherson Dan Stine Dan Walsh Dan Williams Daniel Antlinger Daniel Exner Daniel Farrell Daniel Garcia Daniel Gasienica Daniel Menet Daniel Mizyrycki Daniel Nephin Daniel Norberg Daniel Nordberg Daniel Robinson Daniel S Daniel Von Fange Daniel YC Lin Daniel Zhang Daniel, Dao Quang Minh Danny Berger Danny Yates Darren Coxall Darren Shepherd Dave Henderson David Anderson David Calavera David Corking David Davis David Gageot David Gebler David Mackey David Mat David Mcanulty David Pelaez David R. Jenni David Röthlisberger David Sissitka David Xia David Young Davide Ceretti Dawn Chen decadent Deng Guangxing Deni Bertovic Derek Derek Derek McGowan Deric Crago Deshi Xiao Dinesh Subhraveti DiuDiugirl Djibril Koné dkumor Dmitry Demeshchuk Dmitry Gusev Dmitry V. Krivenok Dolph Mathews Dominik Finkbeiner Dominik Honnef Don Kirkby Don Kjer Don Spaulding Doug Davis Doug MacEachern doug tangren Dr Nic Williams dragon788 Dražen Lučanin Dustin Sallings Ed Costello Edmund Wagner Eiichi Tsukata Eike Herzbach Eivind Uggedal Elias Probst Elijah Zupancic eluck Emil Hernvall Emily Maier Emily Rose Emir Ozer Enguerran Eohyung Lee Eric Hanchrow Eric Lee Eric Myhre Eric Paris Eric Rafaloff Eric Windisch Eric-Olivier Lamey Erik Dubbelboer Erik Hollensbe Erik Inge Bolsø Erik Kristensen Erno Hopearuoho Erwin van der Koogh Euan Eugene Yakubovich eugenkrizo Evan Carmi Evan Hazlett Evan Krall Evan Phoenix Evan Wies Evgeny Vereshchagin Eystein Måløy Stenberg ezbercih Fabiano Rosas Fabio Falci Fabio Rehm Fabrizio Regini Faiz Khan falmp Fareed Dudhia Felix Rabe Felix Schindler Ferenc Szabo Fernando Filipe Brandenburger Flavio Castelli FLGMwt Florian Weingarten Francisco Carriedo Francisco Souza Frank Herrmann Frank Macreery Frank Rosquin Fred Lifton Frederick F. Kautz IV Frederik Loeffert Freek Kalter Félix Baylac-Jacqué Gabe Rosenhouse Gabor Nagy Gabriel Monroy Galen Sampson Gareth Rushgrove Gaurav gautam, prasanna GennadySpb Geoffrey Bachelet George MacRorie George Xie Gereon Frey German DZ Gert van Valkenhoef Gianluca Borello Giuseppe Mazzotta Gleb Fotengauer-Malinovskiy Gleb M Borisov Glyn Normington Goffert van Gool golubbe Gosuke Miyashita Graydon Hoare Greg Fausak Greg Thornton grossws grunny Guilherme Salgado Guillaume Dufour Guillaume J. Charmes guoxiuyan Gurjeet Singh Guruprasad Günter Zöchbauer Hans Rødtang Harald Albers Harley Laue Harry Zhang He Simei Hector Castro Henning Sprang Hobofan Hollie Teal Hong Xu Hu Keping Hu Tao Huayi Zhang Hugo Duncan Hunter Blanks Huu Nguyen hyeongkyu.lee hyp3rdino Ian Babrou Ian Bishop Ian Bull Ian Calvert Ian Main Ian Truslove Iavael Igor Dolzhikov ILYA Khlopotov imre Fitos inglesp Isaac Dupree Isabel Jimenez Isao Jonas Ivan Fraixedes J Bruni J. Nunn Jack Danger Canty Jacob Atzen Jacob Edelman Jake Champlin Jake Moshenko jakedt James Allen James Carr James DeFelice James Harrison Fisher James Kyle James Lal James Mills James Turnbull Jamie Hannaford Jamshid Afshar Jan Keromnes Jan Koprowski Jan Pazdziora Jan Toebes Jan-Jaap Driessen Jana Radhakrishnan Jared Biel Jaroslaw Zabiello jaseg Jason Divock Jason Giedymin Jason Hall Jason Livesay Jason McVetta Jason Plum Jason Shepherd Jason Smith Jason Sommer Jason Stangroome Jay Jean-Baptiste Barth Jean-Baptiste Dalido Jean-Paul Calderone Jean-Tiare Le Bigot Jeff Anderson Jeff Lindsay Jeff Nickoloff Jeff Welch Jeffrey Bolle Jeffrey Morgan Jeffrey van Gogh Jeremy Grosser Jesse Dearing Jesse Dubay Jessica Frazelle Jezeniel Zapanta jianbosun Jilles Oldenbeuving Jim Alateras Jim Perrin Jimmy Cuadra Jimmy Puckett jimmyxian Jinsoo Park Jiri Popelka Jiří Župka jjy jmzwcn Joe Beda Joe Ferguson Joe Gordon Joe Shaw Joe Van Dyk Joel Friedly Joel Handwell Joey Gibson Joffrey F Johan Euphrosine Johan Rydberg Johannes 'fish' Ziemke John Costa John Feminella John Gardiner Myers John Gossman John Howard (VM) John OBrien III John Tims John Warwick John Willis Jon Wedaman Jonas Pfenniger Jonathan A. Sternberg Jonathan Boulle Jonathan Camp Jonathan Dowland Jonathan McCrohan Jonathan Mueller Jonathan Pares Jonathan Rudenberg Joost Cassee Jordan Arentsen Jordan Sissel Joseph Anthony Pasquale Holsten Joseph Hager Joseph Kern Josh Josh Hawn Josh Poimboeuf Josiah Kiehl José Tomás Albornoz JP Julian Taylor Julien Barbier Julien Bordellier Julien Dubois Jun-Ru Chang Justin Force Justin Plock Justin Simonelis Jyrki Puttonen Jérôme Petazzoni Jörg Thalheim Kamil Domanski Karan Lyons kargakis Karl Grzeszczak Katie McLaughlin Kato Kazuyoshi Katrina Owen Kawsar Saiyeed Keli Hu Ken Cochrane Ken ICHIKAWA Kent Johnson Kevin "qwazerty" Houdebert Kevin Clark Kevin J. Lynagh Kevin Menard Kevin Wallace Kevin Yap Keyvan Fatehi kies Kim BKC Carlbacker Kimbro Staken Kiran Gangadharan Kirill SIbirev knappe Kohei Tsuruta Konrad Kleine Konstantin Pelykh Krasimir Georgiev krrg Kyle Conroy kyu Lachlan Coote Lajos Papp Lakshan Perera lalyos Lance Chen Lance Kinley Lars Kellogg-Stedman Lars R. Damerow Laurie Voss leeplay Lei Jitang Len Weincier Leszek Kowalski Levi Gross Lewis Marshall Lewis Peckover Liana Lo Liang-Chi Hsieh limsy Liu Hua Lloyd Dewolf Lokesh Mandvekar Lorenz Leutgeb Lorenzo Fontana Louis Opter Luis Martínez de Bartolomé Izquierdo lukaspustina lukemarsden Lénaïc Huard Ma Shimiao Mabin Madhu Venugopal Mahesh Tiyyagura malnick Malte Janduda Manfred Touron Manfred Zabarauskas Manuel Meurer Manuel Woelker Marc Abramowitz Marc Kuo Marc Tamsky Marco Hennings Marcus Farkas Marcus Linke Marcus Ramberg Marek Goldmann Marian Marinov Marianna Marius Voila Mark Allen Mark McGranaghan Mark West Marko Mikulicic Marko Tibold Markus Fix Martijn Dwars Martijn van Oosterhout Martin Honermeyer Martin Redmond Mary Anthony Masahito Zembutsu Mason Malone Mateusz Sulima Mathias Monnerville Mathieu Le Marec - Pasquet Matt Apperson Matt Bachmann Matt Bentley Matt Haggard Matt McCormick Matthew Heon Matthew Mayer Matthew Mueller Matthew Riley Matthias Klumpp Matthias Kühnle mattymo mattyw mauriyouth Max Shytikov Maxim Kulkin Maxim Treskin Maxime Petazzoni Meaglith Ma meejah Megan Kostick Mehul Kar Mengdi Gao Mert Yazıcıoğlu Michael A. Smith Michael Brown Michael Chiang Michael Crosby Michael Gorsuch Michael Hudson-Doyle Michael Neale Michael Prokop Michael Scharf Michael Stapelberg Michael Steinert Michael Thies Michael West Michal Fojtik Michal Jemala Michal Minar Michaël Pailloncy Michiel@unhosted Miguel Angel Fernández Mihai Borobocea Mike Chelen Mike Dillon Mike Gaffney Mike Leone Mike MacCana Mike Naberezny Mike Snitzer Mikhail Sobolev Mingzhen Feng Mitch Capper Mohit Soni Morgante Pell Morten Siebuhr Moysés Borges Mrunal Patel mschurenko Mustafa Akın Médi-Rémi Hashim Nan Monnand Deng Naoki Orii Natalie Parker Nate Eagleson Nate Jones Nathan Hsieh Nathan Kleyn Nathan LeClaire Neal McBurnett Nelson Chen Nghia Tran Niall O'Higgins Nicholas E. Rabenau Nick Irvine Nick Parker Nick Payne Nick Stenning Nick Stinemates Nicolas De loof Nicolas Dudebout Nicolas Goy Nicolas Kaiser NikolaMandic nikolas noducks Nolan Darilek nponeccop Nuutti Kotivuori nzwsch O.S. Tezer OddBloke odk- Oguz Bilgic Oh Jinkyun Ole Reifschneider Olivier Gambier pandrew panticz Pascal Borreli Pascal Hartig Patrick Devine Patrick Hemmer Patrick Stapleton pattichen Paul paul Paul Annesley Paul Bellamy Paul Bowsher Paul Hammond Paul Jimenez Paul Lietar Paul Morie Paul Nasrat Paul Weaver Pavel Lobashov Pavel Tikhomirov Pavlos Ratis Peggy Li Peter Bourgon Peter Braden Peter Choi Peter Dave Hello Peter Ericson Peter Esbensen Peter Salvatore Peter Volpe Peter Waller Phil Phil Estes Phil Spitler Philipp Weissensteiner Phillip Alexander Piergiuliano Bossi Pierre Pierre Wacrenier Pierre-Alain RIVIERE Piotr Bogdan pixelistik Porjo Pradeep Chhetri Prasanna Gautam Przemek Hejman pysqz Qiang Huang Quentin Brossard r0n22 Rafal Jeczalik Rafe Colton Raghuram Devarakonda Rajat Pandit Rajdeep Dua Ralph Bean Ramkumar Ramachandra Ramon van Alteren Recursive Madman Remi Rampin Renato Riccieri Santos Zannon resouer rgstephens Rhys Hiltner Rich Seymour Richard Richard Burnison Richard Harvey Richard Metzler Richo Healey Rick Bradley Rick van de Loo Rick Wieman Rik Nijessen Robert Bachmann Robert Bittle Robert Obryk Roberto G. Hashioka Robin Speekenbrink robpc Rodrigo Vaz Roel Van Nyen Roger Peppe Rohit Jnagal Roland Huß Roland Moriz Ron Smits root Rovanion Luckey Rudolph Gottesheim Ryan Anderson Ryan Aslett Ryan Detzel Ryan Fowler Ryan O'Donnell Ryan Seto Ryan Thomas Rémy Greinhofer s. rannou s00318865 Sabin Basyal Sachin Joshi Sam Abed Sam Alba Sam Bailey Sam J Sharpe Sam Reis Sam Rijs Sami Wagiaalla Samuel Andaya Samuel PHAN Sankar சங்கர் Sanket Saurav sapphiredev Satnam Singh satoru Satoshi Amemiya Scott Bessler Scott Collier Scott Johnston Scott Stamp Scott Walls sdreyesg Sean Cronin Sean P. Kane Sebastiaan van Steenis Sebastiaan van Stijn Senthil Kumar Selvaraj SeongJae Park Seongyeol Lim Sergey Alekseev Sergey Evstifeev Shane Canon shaunol Shawn Landden Shawn Siefkas Shih-Yuan Lee Shijiang Wei Shishir Mahajan shuai-z sidharthamani Silas Sewell Simei He Simon Eskildsen Simon Leinen Simon Taranto Sindhu S Sjoerd Langkemper Solomon Hykes Song Gao Soulou Sridatta Thatipamala Sridhar Ratnakumar Srini Brahmaroutu Srini Brahmaroutu Steeve Morin Stefan Praszalowicz Stephen Crosby Stephen J Day Steve Francia Steve Koch Steven Burgess Steven Merrill Steven Richards Steven Taylor Sven Dowideit Swapnil Daingade Sylvain Baubeau Sylvain Bellemare Sébastien Sébastien Luttringer Sébastien Stormacq tang0th Tangi COLIN Tatsuki Sugiura Tatsushi Inagaki Ted M. Young Tehmasp Chaudhri Tejesh Mehta Thatcher Peskens theadactyl Thell 'Bo' Fowler Thermionix Thijs Terlouw Thomas Bikeev Thomas Frössman Thomas Hansen Thomas LEVEIL Thomas Orozco Thomas Schroeter Thomas Sjögren Thomas Texier Tianon Gravi Tibor Vass Tiffany Low Tim Bosse Tim Hockin Tim Ruffles Tim Smith Tim Terhorst Timothy Hobbs tjwebb123 tobe Tobias Bieniek Tobias Gesellchen Tobias Schmidt Tobias Schwab Todd Lunter Todd Whiteman Tom Fotherby Tom Hulihan Tom Maaswinkel Tomas Tomecek Tomasz Lipinski Tomasz Nurkiewicz Tommaso Visconti Tomáš Hrčka Tonis Tiigi Tonny Xu Tony Daws Tony Miller Torstein Husebø tpng Travis Cline Travis Thieman Trent Ogren Tristan Carel Tyler Brock Tzu-Jung Lee Ulysse Carion unknown vagrant Vaidas Jablonskis vgeta Victor Coisne Victor Lyuboslavsky Victor Marmol Victor Vieux Viktor Vojnovski Vincent Batts Vincent Bernat Vincent Bernat Vincent Demeester Vincent Giersch Vincent Mayers Vincent Woo Vinod Kulkarni Vishal Doshi Vishnu Kannan Vitor Monteiro Vivek Agarwal Vivek Dasgupta Vivek Goyal Vladimir Bulyga Vladimir Kirillov Vladimir Rutsky VladimirAus Vojtech Vitek (V-Teq) waitingkuo Walter Leibbrandt Walter Stanish Ward Vandewege WarheadsSE Wayne Chang Wei-Ting Kuo Wes Morgan Will Dietz Will Rouesnel Will Weaver willhf William Delanoue William Henry William Riancho William Thurston WiseTrem wlan0 Wolfgang Powisch wonderflow xamyzhao XiaoBing Jiang Xinzi Zhou Xiuming Chen xuzhaokui y00277921 Yahya YAMADA Tsuyoshi Yan Feng Yang Bai Yasunori Mahata Yestin Sun Yihang Ho Yohei Ueda Yongzhi Pan Yuan Sun Yurii Rashkovskii Zac Dover Zach Borboa Zain Memon Zaiste! Zane DeGraffenried Zefan Li Zen Lin(Zhinan Lin) Zhang Wei Zhang Wentao Zilin Du zimbatm Zoltan Tombol zqh Álex González Álvaro Lázaro 尹吉峰 ================================================ FILE: vendor/github.com/docker/docker/CHANGELOG.md ================================================ # Changelog ## 1.7.1 (2015-07-14) #### Runtime - Fix default user spawning exec process with `docker exec` - Make `--bridge=none` not to configure the network bridge - Publish networking stats properly - Fix implicit devicemapper selection with static binaries - Fix socket connections that hung intermittently - Fix bridge interface creation on CentOS/RHEL 6.6 - Fix local dns lookups added to resolv.conf - Fix copy command mounting volumes - Fix read/write privileges in volumes mounted with --volumes-from #### Remote API - Fix unmarshalling of Command and Entrypoint - Set limit for minimum client version supported - Validate port specification - Return proper errors when attach/reattach fail #### Distribution - Fix pulling private images - Fix fallback between registry V2 and V1 ## 1.7.0 (2015-06-16) #### Runtime + Experimental feature: support for out-of-process volume plugins * The userland proxy can be disabled in favor of hairpin NAT using the daemon’s `--userland-proxy=false` flag * The `exec` command supports the `-u|--user` flag to specify the new process owner + Default gateway for containers can be specified daemon-wide using the `--default-gateway` and `--default-gateway-v6` flags + The CPU CFS (Completely Fair Scheduler) quota can be set in `docker run` using `--cpu-quota` + Container block IO can be controlled in `docker run` using`--blkio-weight` + ZFS support + The `docker logs` command supports a `--since` argument + UTS namespace can be shared with the host with `docker run --uts=host` #### Quality * Networking stack was entirely rewritten as part of the libnetwork effort * Engine internals refactoring * Volumes code was entirely rewritten to support the plugins effort + Sending SIGUSR1 to a daemon will dump all goroutines stacks without exiting #### Build + Support ${variable:-value} and ${variable:+value} syntax for environment variables + Support resource management flags `--cgroup-parent`, `--cpu-period`, `--cpu-quota`, `--cpuset-cpus`, `--cpuset-mems` + git context changes with branches and directories * The .dockerignore file support exclusion rules #### Distribution + Client support for v2 mirroring support for the official registry #### Bugfixes * Firewalld is now supported and will automatically be used when available * mounting --device recursively ## 1.6.2 (2015-05-13) #### Runtime - Revert change prohibiting mounting into /sys ## 1.6.1 (2015-05-07) #### Security - Fix read/write /proc paths (CVE-2015-3630) - Prohibit VOLUME /proc and VOLUME / (CVE-2015-3631) - Fix opening of file-descriptor 1 (CVE-2015-3627) - Fix symlink traversal on container respawn allowing local privilege escalation (CVE-2015-3629) - Prohibit mount of /sys #### Runtime - Update AppArmor policy to not allow mounts ## 1.6.0 (2015-04-07) #### Builder + Building images from an image ID + Build containers with resource constraints, ie `docker build --cpu-shares=100 --memory=1024m...` + `commit --change` to apply specified Dockerfile instructions while committing the image + `import --change` to apply specified Dockerfile instructions while importing the image + Builds no longer continue in the background when canceled with CTRL-C #### Client + Windows Support #### Runtime + Container and image Labels + `--cgroup-parent` for specifying a parent cgroup to place container cgroup within + Logging drivers, `json-file`, `syslog`, or `none` + Pulling images by ID + `--ulimit` to set the ulimit on a container + `--default-ulimit` option on the daemon which applies to all created containers (and overwritten by `--ulimit` on run) ## 1.5.0 (2015-02-10) #### Builder + Dockerfile to use for a given `docker build` can be specified with the `-f` flag * Dockerfile and .dockerignore files can be themselves excluded as part of the .dockerignore file, thus preventing modifications to these files invalidating ADD or COPY instructions cache * ADD and COPY instructions accept relative paths * Dockerfile `FROM scratch` instruction is now interpreted as a no-base specifier * Improve performance when exposing a large number of ports #### Hack + Allow client-side only integration tests for Windows * Include docker-py integration tests against Docker daemon as part of our test suites #### Packaging + Support for the new version of the registry HTTP API * Speed up `docker push` for images with a majority of already existing layers - Fixed contacting a private registry through a proxy #### Remote API + A new endpoint will stream live container resource metrics and can be accessed with the `docker stats` command + Containers can be renamed using the new `rename` endpoint and the associated `docker rename` command * Container `inspect` endpoint show the ID of `exec` commands running in this container * Container `inspect` endpoint show the number of times Docker auto-restarted the container * New types of event can be streamed by the `events` endpoint: ‘OOM’ (container died with out of memory), ‘exec_create’, and ‘exec_start' - Fixed returned string fields which hold numeric characters incorrectly omitting surrounding double quotes #### Runtime + Docker daemon has full IPv6 support + The `docker run` command can take the `--pid=host` flag to use the host PID namespace, which makes it possible for example to debug host processes using containerized debugging tools + The `docker run` command can take the `--read-only` flag to make the container’s root filesystem mounted as readonly, which can be used in combination with volumes to force a container’s processes to only write to locations that will be persisted + Container total memory usage can be limited for `docker run` using the `—memory-swap` flag * Major stability improvements for devicemapper storage driver * Better integration with host system: containers will reflect changes to the host's `/etc/resolv.conf` file when restarted * Better integration with host system: per-container iptable rules are moved to the DOCKER chain - Fixed container exiting on out of memory to return an invalid exit code #### Other * The HTTP_PROXY, HTTPS_PROXY, and NO_PROXY environment variables are properly taken into account by the client when connecting to the Docker daemon ## 1.4.1 (2014-12-15) #### Runtime - Fix issue with volumes-from and bind mounts not being honored after create ## 1.4.0 (2014-12-11) #### Notable Features since 1.3.0 + Set key=value labels to the daemon (displayed in `docker info`), applied with new `-label` daemon flag + Add support for `ENV` in Dockerfile of the form: `ENV name=value name2=value2...` + New Overlayfs Storage Driver + `docker info` now returns an `ID` and `Name` field + Filter events by event name, container, or image + `docker cp` now supports copying from container volumes - Fixed `docker tag`, so it honors `--force` when overriding a tag for existing image. ## 1.3.3 (2014-12-11) #### Security - Fix path traversal vulnerability in processing of absolute symbolic links (CVE-2014-9356) - Fix decompression of xz image archives, preventing privilege escalation (CVE-2014-9357) - Validate image IDs (CVE-2014-9358) #### Runtime - Fix an issue when image archives are being read slowly #### Client - Fix a regression related to stdin redirection - Fix a regression with `docker cp` when destination is the current directory ## 1.3.2 (2014-11-20) #### Security - Fix tar breakout vulnerability * Extractions are now sandboxed chroot - Security options are no longer committed to images #### Runtime - Fix deadlock in `docker ps -f exited=1` - Fix a bug when `--volumes-from` references a container that failed to start #### Registry + `--insecure-registry` now accepts CIDR notation such as 10.1.0.0/16 * Private registries whose IPs fall in the 127.0.0.0/8 range do no need the `--insecure-registry` flag - Skip the experimental registry v2 API when mirroring is enabled ## 1.3.1 (2014-10-28) #### Security * Prevent fallback to SSL protocols < TLS 1.0 for client, daemon and registry + Secure HTTPS connection to registries with certificate verification and without HTTP fallback unless `--insecure-registry` is specified #### Runtime - Fix issue where volumes would not be shared #### Client - Fix issue with `--iptables=false` not automatically setting `--ip-masq=false` - Fix docker run output to non-TTY stdout #### Builder - Fix escaping `$` for environment variables - Fix issue with lowercase `onbuild` Dockerfile instruction - Restrict environment variable expansion to `ENV`, `ADD`, `COPY`, `WORKDIR`, `EXPOSE`, `VOLUME` and `USER` ## 1.3.0 (2014-10-14) #### Notable features since 1.2.0 + Docker `exec` allows you to run additional processes inside existing containers + Docker `create` gives you the ability to create a container via the CLI without executing a process + `--security-opts` options to allow user to customize container labels and apparmor profiles + Docker `ps` filters - Wildcard support to COPY/ADD + Move production URLs to get.docker.com from get.docker.io + Allocate IP address on the bridge inside a valid CIDR + Use drone.io for PR and CI testing + Ability to setup an official registry mirror + Ability to save multiple images with docker `save` ## 1.2.0 (2014-08-20) #### Runtime + Make /etc/hosts /etc/resolv.conf and /etc/hostname editable at runtime + Auto-restart containers using policies + Use /var/lib/docker/tmp for large temporary files + `--cap-add` and `--cap-drop` to tweak what linux capability you want + `--device` to use devices in containers #### Client + `docker search` on private registries + Add `exited` filter to `docker ps --filter` * `docker rm -f` now kills instead of stop + Support for IPv6 addresses in `--dns` flag #### Proxy + Proxy instances in separate processes * Small bug fix on UDP proxy ## 1.1.2 (2014-07-23) #### Runtime + Fix port allocation for existing containers + Fix containers restart on daemon restart #### Packaging + Fix /etc/init.d/docker issue on Debian ## 1.1.1 (2014-07-09) #### Builder * Fix issue with ADD ## 1.1.0 (2014-07-03) #### Notable features since 1.0.1 + Add `.dockerignore` support + Pause containers during `docker commit` + Add `--tail` to `docker logs` #### Builder + Allow a tar file as context for `docker build` * Fix issue with white-spaces and multi-lines in `Dockerfiles` #### Runtime * Overall performance improvements * Allow `/` as source of `docker run -v` * Fix port allocation * Fix bug in `docker save` * Add links information to `docker inspect` #### Client * Improve command line parsing for `docker commit` #### Remote API * Improve status code for the `start` and `stop` endpoints ## 1.0.1 (2014-06-19) #### Notable features since 1.0.0 * Enhance security for the LXC driver #### Builder * Fix `ONBUILD` instruction passed to grandchildren #### Runtime * Fix events subscription * Fix /etc/hostname file with host networking * Allow `-h` and `--net=none` * Fix issue with hotplug devices in `--privileged` #### Client * Fix artifacts with events * Fix a panic with empty flags * Fix `docker cp` on Mac OS X #### Miscellaneous * Fix compilation on Mac OS X * Fix several races ## 1.0.0 (2014-06-09) #### Notable features since 0.12.0 * Production support ## 0.12.0 (2014-06-05) #### Notable features since 0.11.0 * 40+ various improvements to stability, performance and usability * New `COPY` Dockerfile instruction to allow copying a local file from the context into the container without ever extracting if the file is a tar file * Inherit file permissions from the host on `ADD` * New `pause` and `unpause` commands to allow pausing and unpausing of containers using cgroup freezer * The `images` command has a `-f`/`--filter` option to filter the list of images * Add `--force-rm` to clean up after a failed build * Standardize JSON keys in Remote API to CamelCase * Pull from a docker run now assumes `latest` tag if not specified * Enhance security on Linux capabilities and device nodes ## 0.11.1 (2014-05-07) #### Registry - Fix push and pull to private registry ## 0.11.0 (2014-05-07) #### Notable features since 0.10.0 * SELinux support for mount and process labels * Linked containers can be accessed by hostname * Use the net `--net` flag to allow advanced network configuration such as host networking so that containers can use the host's network interfaces * Add a ping endpoint to the Remote API to do healthchecks of your docker daemon * Logs can now be returned with an optional timestamp * Docker now works with registries that support SHA-512 * Multiple registry endpoints are supported to allow registry mirrors ## 0.10.0 (2014-04-08) #### Builder - Fix printing multiple messages on a single line. Fixes broken output during builds. - Follow symlinks inside container's root for ADD build instructions. - Fix EXPOSE caching. #### Documentation - Add the new options of `docker ps` to the documentation. - Add the options of `docker restart` to the documentation. - Update daemon docs and help messages for --iptables and --ip-forward. - Updated apt-cacher-ng docs example. - Remove duplicate description of --mtu from docs. - Add missing -t and -v for `docker images` to the docs. - Add fixes to the cli docs. - Update libcontainer docs. - Update images in docs to remove references to AUFS and LXC. - Update the nodejs_web_app in the docs to use the new epel RPM address. - Fix external link on security of containers. - Update remote API docs. - Add image size to history docs. - Be explicit about binding to all interfaces in redis example. - Document DisableNetwork flag in the 1.10 remote api. - Document that `--lxc-conf` is lxc only. - Add chef usage documentation. - Add example for an image with multiple for `docker load`. - Explain what `docker run -a` does in the docs. #### Contrib - Add variable for DOCKER_LOGFILE to sysvinit and use append instead of overwrite in opening the logfile. - Fix init script cgroup mounting workarounds to be more similar to cgroupfs-mount and thus work properly. - Remove inotifywait hack from the upstart host-integration example because it's not necessary any more. - Add check-config script to contrib. - Fix fish shell completion. #### Hack * Clean up "go test" output from "make test" to be much more readable/scannable. * Exclude more "definitely not unit tested Go source code" directories from hack/make/test. + Generate md5 and sha256 hashes when building, and upload them via hack/release.sh. - Include contributed completions in Ubuntu PPA. + Add cli integration tests. * Add tweaks to the hack scripts to make them simpler. #### Remote API + Add TLS auth support for API. * Move git clone from daemon to client. - Fix content-type detection in docker cp. * Split API into 2 go packages. #### Runtime * Support hairpin NAT without going through Docker server. - devicemapper: succeed immediately when removing non-existing devices. - devicemapper: improve handling of devicemapper devices (add per device lock, increase sleep time and unlock while sleeping). - devicemapper: increase timeout in waitClose to 10 seconds. - devicemapper: ensure we shut down thin pool cleanly. - devicemapper: pass info, rather than hash to activateDeviceIfNeeded, deactivateDevice, setInitialized, deleteDevice. - devicemapper: avoid AB-BA deadlock. - devicemapper: make shutdown better/faster. - improve alpha sorting in mflag. - Remove manual http cookie management because the cookiejar is being used. - Use BSD raw mode on Darwin. Fixes nano, tmux and others. - Add FreeBSD support for the client. - Merge auth package into registry. - Add deprecation warning for -t on `docker pull`. - Remove goroutine leak on error. - Update parseLxcInfo to comply with new lxc1.0 format. - Fix attach exit on darwin. - Improve deprecation message. - Retry to retrieve the layer metadata up to 5 times for `docker pull`. - Only unshare the mount namespace for execin. - Merge existing config when committing. - Disable daemon startup timeout. - Fix issue #4681: add loopback interface when networking is disabled. - Add failing test case for issue #4681. - Send SIGTERM to child, instead of SIGKILL. - Show the driver and the kernel version in `docker info` even when not in debug mode. - Always symlink /dev/ptmx for libcontainer. This fixes console related problems. - Fix issue caused by the absence of /etc/apparmor.d. - Don't leave empty cidFile behind when failing to create the container. - Mount cgroups automatically if they're not mounted already. - Use mock for search tests. - Update to double-dash everywhere. - Move .dockerenv parsing to lxc driver. - Move all bind-mounts in the container inside the namespace. - Don't use separate bind mount for container. - Always symlink /dev/ptmx for libcontainer. - Don't kill by pid for other drivers. - Add initial logging to libcontainer. * Sort by port in `docker ps`. - Move networking drivers into runtime top level package. + Add --no-prune to `docker rmi`. + Add time since exit in `docker ps`. - graphdriver: add build tags. - Prevent allocation of previously allocated ports & prevent improve port allocation. * Add support for --since/--before in `docker ps`. - Clean up container stop. + Add support for configurable dns search domains. - Add support for relative WORKDIR instructions. - Add --output flag for docker save. - Remove duplication of DNS entries in config merging. - Add cpuset.cpus to cgroups and native driver options. - Remove docker-ci. - Promote btrfs. btrfs is no longer considered experimental. - Add --input flag to `docker load`. - Return error when existing bridge doesn't match IP address. - Strip comments before parsing line continuations to avoid interpreting instructions as comments. - Fix TestOnlyLoopbackExistsWhenUsingDisableNetworkOption to ignore "DOWN" interfaces. - Add systemd implementation of cgroups and make containers show up as systemd units. - Fix commit and import when no repository is specified. - Remount /var/lib/docker as --private to fix scaling issue. - Use the environment's proxy when pinging the remote registry. - Reduce error level from harmless errors. * Allow --volumes-from to be individual files. - Fix expanding buffer in StdCopy. - Set error regardless of attach or stdin. This fixes #3364. - Add support for --env-file to load environment variables from files. - Symlink /etc/mtab and /proc/mounts. - Allow pushing a single tag. - Shut down containers cleanly at shutdown and wait forever for the containers to shut down. This makes container shutdown on daemon shutdown work properly via SIGTERM. - Don't throw error when starting an already running container. - Fix dynamic port allocation limit. - remove setupDev from libcontainer. - Add API version to `docker version`. - Return correct exit code when receiving signal and make SIGQUIT quit without cleanup. - Fix --volumes-from mount failure. - Allow non-privileged containers to create device nodes. - Skip login tests because of external dependency on a hosted service. - Deprecate `docker images --tree` and `docker images --viz`. - Deprecate `docker insert`. - Include base abstraction for apparmor. This fixes some apparmor related problems on Ubuntu 14.04. - Add specific error message when hitting 401 over HTTP on push. - Fix absolute volume check. - Remove volumes-from from the config. - Move DNS options to hostconfig. - Update the apparmor profile for libcontainer. - Add deprecation notice for `docker commit -run`. ## 0.9.1 (2014-03-24) #### Builder - Fix printing multiple messages on a single line. Fixes broken output during builds. #### Documentation - Fix external link on security of containers. #### Contrib - Fix init script cgroup mounting workarounds to be more similar to cgroupfs-mount and thus work properly. - Add variable for DOCKER_LOGFILE to sysvinit and use append instead of overwrite in opening the logfile. #### Hack - Generate md5 and sha256 hashes when building, and upload them via hack/release.sh. #### Remote API - Fix content-type detection in `docker cp`. #### Runtime - Use BSD raw mode on Darwin. Fixes nano, tmux and others. - Only unshare the mount namespace for execin. - Retry to retrieve the layer metadata up to 5 times for `docker pull`. - Merge existing config when committing. - Fix panic in monitor. - Disable daemon startup timeout. - Fix issue #4681: add loopback interface when networking is disabled. - Add failing test case for issue #4681. - Send SIGTERM to child, instead of SIGKILL. - Show the driver and the kernel version in `docker info` even when not in debug mode. - Always symlink /dev/ptmx for libcontainer. This fixes console related problems. - Fix issue caused by the absence of /etc/apparmor.d. - Don't leave empty cidFile behind when failing to create the container. - Improve deprecation message. - Fix attach exit on darwin. - devicemapper: improve handling of devicemapper devices (add per device lock, increase sleep time, unlock while sleeping). - devicemapper: succeed immediately when removing non-existing devices. - devicemapper: increase timeout in waitClose to 10 seconds. - Remove goroutine leak on error. - Update parseLxcInfo to comply with new lxc1.0 format. ## 0.9.0 (2014-03-10) #### Builder - Avoid extra mount/unmount during build. This fixes mount/unmount related errors during build. - Add error to docker build --rm. This adds missing error handling. - Forbid chained onbuild, `onbuild from` and `onbuild maintainer` triggers. - Make `--rm` the default for `docker build`. #### Documentation - Download the docker client binary for Mac over https. - Update the titles of the install instructions & descriptions. * Add instructions for upgrading boot2docker. * Add port forwarding example in OS X install docs. - Attempt to disentangle repository and registry. - Update docs to explain more about `docker ps`. - Update sshd example to use a Dockerfile. - Rework some examples, including the Python examples. - Update docs to include instructions for a container's lifecycle. - Update docs documentation to discuss the docs branch. - Don't skip cert check for an example & use HTTPS. - Bring back the memory and swap accounting section which was lost when the kernel page was removed. - Explain DNS warnings and how to fix them on systems running and using a local nameserver. #### Contrib - Add Tanglu support for mkimage-debootstrap. - Add SteamOS support for mkimage-debootstrap. #### Hack - Get package coverage when running integration tests. - Remove the Vagrantfile. This is being replaced with boot2docker. - Fix tests on systems where aufs isn't available. - Update packaging instructions and remove the dependency on lxc. #### Remote API * Move code specific to the API to the api package. - Fix header content type for the API. Makes all endpoints use proper content type. - Fix registry auth & remove ping calls from CmdPush and CmdPull. - Add newlines to the JSON stream functions. #### Runtime * Do not ping the registry from the CLI. All requests to registries flow through the daemon. - Check for nil information return in the lxc driver. This fixes panics with older lxc versions. - Devicemapper: cleanups and fix for unmount. Fixes two problems which were causing unmount to fail intermittently. - Devicemapper: remove directory when removing device. Directories don't get left behind when removing the device. * Devicemapper: enable skip_block_zeroing. Improves performance by not zeroing blocks. - Devicemapper: fix shutdown warnings. Fixes shutdown warnings concerning pool device removal. - Ensure docker cp stream is closed properly. Fixes problems with files not being copied by `docker cp`. - Stop making `tcp://` default to `127.0.0.1:4243` and remove the default port for tcp. - Fix `--run` in `docker commit`. This makes `docker commit --run` work again. - Fix custom bridge related options. This makes custom bridges work again. + Mount-bind the PTY as container console. This allows tmux/screen to run. + Add the pure Go libcontainer library to make it possible to run containers using only features of the Linux kernel. + Add native exec driver which uses libcontainer and make it the default exec driver. - Add support for handling extended attributes in archives. * Set the container MTU to be the same as the host MTU. + Add simple sha256 checksums for layers to speed up `docker push`. * Improve kernel version parsing. * Allow flag grouping (`docker run -it`). - Remove chroot exec driver. - Fix divide by zero to fix panic. - Rewrite `docker rmi`. - Fix docker info with lxc 1.0.0. - Fix fedora tty with apparmor. * Don't always append env vars, replace defaults with vars from config. * Fix a goroutine leak. * Switch to Go 1.2.1. - Fix unique constraint error checks. * Handle symlinks for Docker's data directory and for TMPDIR. - Add deprecation warnings for flags (-flag is deprecated in favor of --flag) - Add apparmor profile for the native execution driver. * Move system specific code from archive to pkg/system. - Fix duplicate signal for `docker run -i -t` (issue #3336). - Return correct process pid for lxc. - Add a -G option to specify the group which unix sockets belong to. + Add `-f` flag to `docker rm` to force removal of running containers. + Kill ghost containers and restart all ghost containers when the docker daemon restarts. + Add `DOCKER_RAMDISK` environment variable to make Docker work when the root is on a ramdisk. ## 0.8.1 (2014-02-18) #### Builder - Avoid extra mount/unmount during build. This removes an unneeded mount/unmount operation which was causing problems with devicemapper - Fix regression with ADD of tar files. This stops Docker from decompressing tarballs added via ADD from the local file system - Add error to `docker build --rm`. This adds a missing error check to ensure failures to remove containers are detected and reported #### Documentation * Update issue filing instructions * Warn against the use of symlinks for Docker's storage folder * Replace the Firefox example with an IceWeasel example * Rewrite the PostgresSQL example using a Dockerfile and add more details to it * Improve the OS X documentation #### Remote API - Fix broken images API for version less than 1.7 - Use the right encoding for all API endpoints which return JSON - Move remote api client to api/ - Queue calls to the API using generic socket wait #### Runtime - Fix the use of custom settings for bridges and custom bridges - Refactor the devicemapper code to avoid many mount/unmount race conditions and failures - Remove two panics which could make Docker crash in some situations - Don't ping registry from the CLI client - Enable skip_block_zeroing for devicemapper. This stops devicemapper from always zeroing entire blocks - Fix --run in `docker commit`. This makes docker commit store `--run` in the image configuration - Remove directory when removing devicemapper device. This cleans up leftover mount directories - Drop NET_ADMIN capability for non-privileged containers. Unprivileged containers can't change their network configuration - Ensure `docker cp` stream is closed properly - Avoid extra mount/unmount during container registration. This removes an unneeded mount/unmount operation which was causing problems with devicemapper - Stop allowing tcp:// as a default tcp bin address which binds to 127.0.0.1:4243 and remove the default port + Mount-bind the PTY as container console. This allows tmux and screen to run in a container - Clean up archive closing. This fixes and improves archive handling - Fix engine tests on systems where temp directories are symlinked - Add test methods for save and load - Avoid temporarily unmounting the container when restarting it. This fixes a race for devicemapper during restart - Support submodules when building from a GitHub repository - Quote volume path to allow spaces - Fix remote tar ADD behavior. This fixes a regression which was causing Docker to extract tarballs ## 0.8.0 (2014-02-04) #### Notable features since 0.7.0 * Images and containers can be removed much faster * Building an image from source with docker build is now much faster * The Docker daemon starts and stops much faster * The memory footprint of many common operations has been reduced, by streaming files instead of buffering them in memory, fixing memory leaks, and fixing various suboptimal memory allocations * Several race conditions were fixed, making Docker more stable under very high concurrency load. This makes Docker more stable and less likely to crash and reduces the memory footprint of many common operations * All packaging operations are now built on the Go language’s standard tar implementation, which is bundled with Docker itself. This makes packaging more portable across host distributions, and solves several issues caused by quirks and incompatibilities between different distributions of tar * Docker can now create, remove and modify larger numbers of containers and images graciously thanks to more aggressive releasing of system resources. For example the storage driver API now allows Docker to do reference counting on mounts created by the drivers With the ongoing changes to the networking and execution subsystems of docker testing these areas have been a focus of the refactoring. By moving these subsystems into separate packages we can test, analyze, and monitor coverage and quality of these packages * Many components have been separated into smaller sub-packages, each with a dedicated test suite. As a result the code is better-tested, more readable and easier to change * The ADD instruction now supports caching, which avoids unnecessarily re-uploading the same source content again and again when it hasn’t changed * The new ONBUILD instruction adds to your image a “trigger” instruction to be executed at a later time, when the image is used as the base for another build * Docker now ships with an experimental storage driver which uses the BTRFS filesystem for copy-on-write * Docker is officially supported on Mac OS X * The Docker daemon supports systemd socket activation ## 0.7.6 (2014-01-14) #### Builder * Do not follow symlink outside of build context #### Runtime - Remount bind mounts when ro is specified * Use https for fetching docker version #### Other * Inline the test.docker.io fingerprint * Add ca-certificates to packaging documentation ## 0.7.5 (2014-01-09) #### Builder * Disable compression for build. More space usage but a much faster upload - Fix ADD caching for certain paths - Do not compress archive from git build #### Documentation - Fix error in GROUP add example * Make sure the GPG fingerprint is inline in the documentation * Give more specific advice on setting up signing of commits for DCO #### Runtime - Fix misspelled container names - Do not add hostname when networking is disabled * Return most recent image from the cache by date - Return all errors from docker wait * Add Content-Type Header "application/json" to GET /version and /info responses #### Other * Update DCO to version 1.1 + Update Makefile to use "docker:GIT_BRANCH" as the generated image name * Update Travis to check for new 1.1 DCO version ## 0.7.4 (2014-01-07) #### Builder - Fix ADD caching issue with . prefixed path - Fix docker build on devicemapper by reverting sparse file tar option - Fix issue with file caching and prevent wrong cache hit * Use same error handling while unmarshalling CMD and ENTRYPOINT #### Documentation * Simplify and streamline Amazon Quickstart * Install instructions use unprefixed Fedora image * Update instructions for mtu flag for Docker on GCE + Add Ubuntu Saucy to installation - Fix for wrong version warning on master instead of latest #### Runtime - Only get the image's rootfs when we need to calculate the image size - Correctly handle unmapping UDP ports * Make CopyFileWithTar use a pipe instead of a buffer to save memory on docker build - Fix login message to say pull instead of push - Fix "docker load" help by removing "SOURCE" prompt and mentioning STDIN * Make blank -H option default to the same as no -H was sent * Extract cgroups utilities to own submodule #### Other + Add Travis CI configuration to validate DCO and gofmt requirements + Add Developer Certificate of Origin Text * Upgrade VBox Guest Additions * Check standalone header when pinging a registry server ## 0.7.3 (2014-01-02) #### Builder + Update ADD to use the image cache, based on a hash of the added content * Add error message for empty Dockerfile #### Documentation - Fix outdated link to the "Introduction" on www.docker.io + Update the docs to get wider when the screen does - Add information about needing to install LXC when using raw binaries * Update Fedora documentation to disentangle the docker and docker.io conflict * Add a note about using the new `-mtu` flag in several GCE zones + Add FrugalWare installation instructions + Add a more complete example of `docker run` - Fix API documentation for creating and starting Privileged containers - Add missing "name" parameter documentation on "/containers/create" * Add a mention of `lxc-checkconfig` as a way to check for some of the necessary kernel configuration - Update the 1.8 API documentation with some additions that were added to the docs for 1.7 #### Hack - Add missing libdevmapper dependency to the packagers documentation * Update minimum Go requirement to a hard line at Go 1.2+ * Many minor improvements to the Vagrantfile + Add ability to customize dockerinit search locations when compiling (to be used very sparingly only by packagers of platforms who require a nonstandard location) + Add coverprofile generation reporting - Add `-a` to our Go build flags, removing the need for recompiling the stdlib manually * Update Dockerfile to be more canonical and have less spurious warnings during build - Fix some miscellaneous `docker pull` progress bar display issues * Migrate more miscellaneous packages under the "pkg" folder * Update TextMate highlighting to automatically be enabled for files named "Dockerfile" * Reorganize syntax highlighting files under a common "contrib/syntax" directory * Update install.sh script (https://get.docker.io/) to not fail if busybox fails to download or run at the end of the Ubuntu/Debian installation * Add support for container names in bash completion #### Packaging + Add an official Docker client binary for Darwin (Mac OS X) * Remove empty "Vendor" string and added "License" on deb package + Add a stubbed version of "/etc/default/docker" in the deb package #### Runtime * Update layer application to extract tars in place, avoiding file churn while handling whiteouts - Fix permissiveness of mtime comparisons in tar handling (since GNU tar and Go tar do not yet support sub-second mtime precision) * Reimplement `docker top` in pure Go to work more consistently, and even inside Docker-in-Docker (thus removing the shell injection vulnerability present in some versions of `lxc-ps`) + Update `-H unix://` to work similarly to `-H tcp://` by inserting the default values for missing portions - Fix more edge cases regarding dockerinit and deleted or replaced docker or dockerinit files * Update container name validation to include '.' - Fix use of a symlink or non-absolute path as the argument to `-g` to work as expected * Update to handle external mounts outside of LXC, fixing many small mounting quirks and making future execution backends and other features simpler * Update to use proper box-drawing characters everywhere in `docker images -tree` * Move MTU setting from LXC configuration to directly use netlink * Add `-S` option to external tar invocation for more efficient spare file handling + Add arch/os info to User-Agent string, especially for registry requests + Add `-mtu` option to Docker daemon for configuring MTU - Fix `docker build` to exit with a non-zero exit code on error + Add `DOCKER_HOST` environment variable to configure the client `-H` flag without specifying it manually for every invocation ## 0.7.2 (2013-12-16) #### Runtime + Validate container names on creation with standard regex * Increase maximum image depth to 127 from 42 * Continue to move api endpoints to the job api + Add -bip flag to allow specification of dynamic bridge IP via CIDR - Allow bridge creation when ipv6 is not enabled on certain systems * Set hostname and IP address from within dockerinit * Drop capabilities from within dockerinit - Fix volumes on host when symlink is present the image - Prevent deletion of image if ANY container is depending on it even if the container is not running * Update docker push to use new progress display * Use os.Lstat to allow mounting unix sockets when inspecting volumes - Adjust handling of inactive user login - Add missing defines in devicemapper for older kernels - Allow untag operations with no container validation - Add auth config to docker build #### Documentation * Add more information about Docker logging + Add RHEL documentation * Add a direct example for changing the CMD that is run in a container * Update Arch installation documentation + Add section on Trusted Builds + Add Network documentation page #### Other + Add new cover bundle for providing code coverage reporting * Separate integration tests in bundles * Make Tianon the hack maintainer * Update mkimage-debootstrap with more tweaks for keeping images small * Use https to get the install script * Remove vendored dotcloud/tar now that Go 1.2 has been released ## 0.7.1 (2013-12-05) #### Documentation + Add @SvenDowideit as documentation maintainer + Add links example + Add documentation regarding ambassador pattern + Add Google Cloud Platform docs + Add dockerfile best practices * Update doc for RHEL * Update doc for registry * Update Postgres examples * Update doc for Ubuntu install * Improve remote api doc #### Runtime + Add hostconfig to docker inspect + Implement `docker log -f` to stream logs + Add env variable to disable kernel version warning + Add -format to `docker inspect` + Support bind-mount for files - Fix bridge creation on RHEL - Fix image size calculation - Make sure iptables are called even if the bridge already exists - Fix issue with stderr only attach - Remove init layer when destroying a container - Fix same port binding on different interfaces - `docker build` now returns the correct exit code - Fix `docker port` to display correct port - `docker build` now check that the dockerfile exists client side - `docker attach` now returns the correct exit code - Remove the name entry when the container does not exist #### Registry * Improve progress bars, add ETA for downloads * Simultaneous pulls now waits for the first to finish instead of failing - Tag only the top-layer image when pushing to registry - Fix issue with offline image transfer - Fix issue preventing using ':' in password for registry #### Other + Add pprof handler for debug + Create a Makefile * Use stdlib tar that now includes fix * Improve make.sh test script * Handle SIGQUIT on the daemon * Disable verbose during tests * Upgrade to go1.2 for official build * Improve unit tests * The test suite now runs all tests even if one fails * Refactor C in Go (Devmapper) - Fix OS X compilation ## 0.7.0 (2013-11-25) #### Notable features since 0.6.0 * Storage drivers: choose from aufs, device-mapper, or vfs. * Standard Linux support: docker now runs on unmodified Linux kernels and all major distributions. * Links: compose complex software stacks by connecting containers to each other. * Container naming: organize your containers by giving them memorable names. * Advanced port redirects: specify port redirects per interface, or keep sensitive ports private. * Offline transfer: push and pull images to the filesystem without losing information. * Quality: numerous bugfixes and small usability improvements. Significant increase in test coverage. ## 0.6.7 (2013-11-21) #### Runtime * Improve stability, fixes some race conditions * Skip the volumes mounted when deleting the volumes of container. * Fix layer size computation: handle hard links correctly * Use the work Path for docker cp CONTAINER:PATH * Fix tmp dir never cleanup * Speedup docker ps * More informative error message on name collisions * Fix nameserver regex * Always return long id's * Fix container restart race condition * Keep published ports on docker stop;docker start * Fix container networking on Fedora * Correctly express "any address" to iptables * Fix network setup when reconnecting to ghost container * Prevent deletion if image is used by a running container * Lock around read operations in graph #### RemoteAPI * Return full ID on docker rmi #### Client + Add -tree option to images + Offline image transfer * Exit with status 2 on usage error and display usage on stderr * Do not forward SIGCHLD to container * Use string timestamp for docker events -since #### Other * Update to go 1.2rc5 + Add /etc/default/docker support to upstart ## 0.6.6 (2013-11-06) #### Runtime * Ensure container name on register * Fix regression in /etc/hosts + Add lock around write operations in graph * Check if port is valid * Fix restart runtime error with ghost container networking + Add some more colors and animals to increase the pool of generated names * Fix issues in docker inspect + Escape apparmor confinement + Set environment variables using a file. * Prevent docker insert to erase something + Prevent DNS server conflicts in CreateBridgeIface + Validate bind mounts on the server side + Use parent image config in docker build * Fix regression in /etc/hosts #### Client + Add -P flag to publish all exposed ports + Add -notrunc and -q flags to docker history * Fix docker commit, tag and import usage + Add stars, trusted builds and library flags in docker search * Fix docker logs with tty #### RemoteAPI * Make /events API send headers immediately * Do not split last column docker top + Add size to history #### Other + Contrib: Desktop integration. Firefox usecase. + Dockerfile: bump to go1.2rc3 ## 0.6.5 (2013-10-29) #### Runtime + Containers can now be named + Containers can now be linked together for service discovery + 'run -a', 'start -a' and 'attach' can forward signals to the container for better integration with process supervisors + Automatically start crashed containers after a reboot + Expose IP, port, and proto as separate environment vars for container links * Allow ports to be published to specific ips * Prohibit inter-container communication by default - Ignore ErrClosedPipe for stdin in Container.Attach - Remove unused field kernelVersion * Fix issue when mounting subdirectories of /mnt in container - Fix untag during removal of images * Check return value of syscall.Chdir when changing working directory inside dockerinit #### Client - Only pass stdin to hijack when needed to avoid closed pipe errors * Use less reflection in command-line method invocation - Monitor the tty size after starting the container, not prior - Remove useless os.Exit() calls after log.Fatal #### Hack + Add initial init scripts library and a safer Ubuntu packaging script that works for Debian * Add -p option to invoke debootstrap with http_proxy - Update install.sh with $sh_c to get sudo/su for modprobe * Update all the mkimage scripts to use --numeric-owner as a tar argument * Update hack/release.sh process to automatically invoke hack/make.sh and bail on build and test issues #### Other * Documentation: Fix the flags for nc in example * Testing: Remove warnings and prevent mount issues - Testing: Change logic for tty resize to avoid warning in tests - Builder: Fix race condition in docker build with verbose output - Registry: Fix content-type for PushImageJSONIndex method * Contrib: Improve helper tools to generate debian and Arch linux server images ## 0.6.4 (2013-10-16) #### Runtime - Add cleanup of container when Start() fails * Add better comments to utils/stdcopy.go * Add utils.Errorf for error logging + Add -rm to docker run for removing a container on exit - Remove error messages which are not actually errors - Fix `docker rm` with volumes - Fix some error cases where a HTTP body might not be closed - Fix panic with wrong dockercfg file - Fix the attach behavior with -i * Record termination time in state. - Use empty string so TempDir uses the OS's temp dir automatically - Make sure to close the network allocators + Autorestart containers by default * Bump vendor kr/pty to commit 3b1f6487b `(syscall.O_NOCTTY)` * lxc: Allow set_file_cap capability in container - Move run -rm to the cli only * Split stdout stderr * Always create a new session for the container #### Testing - Add aggregated docker-ci email report - Add cleanup to remove leftover containers * Add nightly release to docker-ci * Add more tests around auth.ResolveAuthConfig - Remove a few errors in tests - Catch errClosing error when TCP and UDP proxies are terminated * Only run certain tests with TESTFLAGS='-run TestName' make.sh * Prevent docker-ci to test closing PRs * Replace panic by log.Fatal in tests - Increase TestRunDetach timeout #### Documentation * Add initial draft of the Docker infrastructure doc * Add devenvironment link to CONTRIBUTING.md * Add `apt-get install curl` to Ubuntu docs * Add explanation for export restrictions * Add .dockercfg doc * Remove Gentoo install notes about #1422 workaround * Fix help text for -v option * Fix Ping endpoint documentation - Fix parameter names in docs for ADD command - Fix ironic typo in changelog * Various command fixes in postgres example * Document how to edit and release docs - Minor updates to `postgresql_service.rst` * Clarify LGTM process to contributors - Corrected error in the package name * Document what `vagrant up` is actually doing + improve doc search results * Cleanup whitespace in API 1.5 docs * use angle brackets in MAINTAINER example email * Update archlinux.rst + Changes to a new style for the docs. Includes version switcher. * Formatting, add information about multiline json * Improve registry and index REST API documentation - Replace deprecated upgrading reference to docker-latest.tgz, which hasn't been updated since 0.5.3 * Update Gentoo installation documentation now that we're in the portage tree proper * Cleanup and reorganize docs and tooling for contributors and maintainers - Minor spelling correction of protocoll -> protocol #### Contrib * Add vim syntax highlighting for Dockerfiles from @honza * Add mkimage-arch.sh * Reorganize contributed completion scripts to add zsh completion #### Hack * Add vagrant user to the docker group * Add proper bash completion for "docker push" * Add xz utils as a runtime dep * Add cleanup/refactor portion of #2010 for hack and Dockerfile updates + Add contrib/mkimage-centos.sh back (from #1621), and associated documentation link * Add several of the small make.sh fixes from #1920, and make the output more consistent and contributor-friendly + Add @tianon to hack/MAINTAINERS * Improve network performance for VirtualBox * Revamp install.sh to be usable by more people, and to use official install methods whenever possible (apt repo, portage tree, etc.) - Fix contrib/mkimage-debian.sh apt caching prevention + Add Dockerfile.tmLanguage to contrib * Configured FPM to make /etc/init/docker.conf a config file * Enable SSH Agent forwarding in Vagrant VM * Several small tweaks/fixes for contrib/mkimage-debian.sh #### Other - Builder: Abort build if mergeConfig returns an error and fix duplicate error message - Packaging: Remove deprecated packaging directory - Registry: Use correct auth config when logging in. - Registry: Fix the error message so it is the same as the regex ## 0.6.3 (2013-09-23) #### Packaging * Add 'docker' group on install for ubuntu package * Update tar vendor dependency * Download apt key over HTTPS #### Runtime - Only copy and change permissions on non-bindmount volumes * Allow multiple volumes-from - Fix HTTP imports from STDIN #### Documentation * Update section on extracting the docker binary after build * Update development environment docs for new build process * Remove 'base' image from documentation #### Other - Client: Fix detach issue - Registry: Update regular expression to match index ## 0.6.2 (2013-09-17) #### Runtime + Add domainname support + Implement image filtering with path.Match * Remove unnecessary warnings * Remove os/user dependency * Only mount the hostname file when the config exists * Handle signals within the `docker login` command - UID and GID are now also applied to volumes - `docker start` set error code upon error - `docker run` set the same error code as the process started #### Builder + Add -rm option in order to remove intermediate containers * Allow multiline for the RUN instruction #### Registry * Implement login with private registry - Fix push issues #### Other + Hack: Vendor all dependencies * Remote API: Bump to v1.5 * Packaging: Break down hack/make.sh into small scripts, one per 'bundle': test, binary, ubuntu etc. * Documentation: General improvements ## 0.6.1 (2013-08-23) #### Registry * Pass "meta" headers in API calls to the registry #### Packaging - Use correct upstart script with new build tool - Use libffi-dev, don`t build it from sources - Remove duplicate mercurial install command ## 0.6.0 (2013-08-22) #### Runtime + Add lxc-conf flag to allow custom lxc options + Add an option to set the working directory * Add Image name to LogEvent tests + Add -privileged flag and relevant tests, docs, and examples * Add websocket support to /container//attach/ws * Add warning when net.ipv4.ip_forwarding = 0 * Add hostname to environment * Add last stable version in `docker version` - Fix race conditions in parallel pull - Fix Graph ByParent() to generate list of child images per parent image. - Fix typo: fmt.Sprint -> fmt.Sprintf - Fix small \n error un docker build * Fix to "Inject dockerinit at /.dockerinit" * Fix #910. print user name to docker info output * Use Go 1.1.2 for dockerbuilder * Use ranged for loop on channels - Use utils.ParseRepositoryTag instead of strings.Split(name, ":") in server.ImageDelete - Improve CMD, ENTRYPOINT, and attach docs. - Improve connect message with socket error - Load authConfig only when needed and fix useless WARNING - Show tag used when image is missing * Apply volumes-from before creating volumes - Make docker run handle SIGINT/SIGTERM - Prevent crash when .dockercfg not readable - Install script should be fetched over https, not http. * API, issue 1471: Use groups for socket permissions - Correctly detect IPv4 forwarding * Mount /dev/shm as a tmpfs - Switch from http to https for get.docker.io * Let userland proxy handle container-bound traffic * Update the Docker CLI to specify a value for the "Host" header. - Change network range to avoid conflict with EC2 DNS - Reduce connect and read timeout when pinging the registry * Parallel pull - Handle ip route showing mask-less IP addresses * Allow ENTRYPOINT without CMD - Always consider localhost as a domain name when parsing the FQN repos name * Refactor checksum #### Documentation * Add MongoDB image example * Add instructions for creating and using the docker group * Add sudo to examples and installation to documentation * Add ufw doc * Add a reference to ps -a * Add information about Docker`s high level tools over LXC. * Fix typo in docs for docker run -dns * Fix a typo in the ubuntu installation guide * Fix to docs regarding adding docker groups * Update default -H docs * Update readme with dependencies for building * Update amazon.rst to explain that Vagrant is not necessary for running Docker on ec2 * PostgreSQL service example in documentation * Suggest installing linux-headers by default. * Change the twitter handle * Clarify Amazon EC2 installation * 'Base' image is deprecated and should no longer be referenced in the docs. * Move note about officially supported kernel - Solved the logo being squished in Safari #### Builder + Add USER instruction do Dockerfile + Add workdir support for the Buildfile * Add no cache for docker build - Fix docker build and docker events output - Only count known instructions as build steps - Make sure ENV instruction within build perform a commit each time - Forbid certain paths within docker build ADD - Repository name (and optionally a tag) in build usage - Make sure ADD will create everything in 0755 #### Remote API * Sort Images by most recent creation date. * Reworking opaque requests in registry module * Add image name in /events * Use mime pkg to parse Content-Type * 650 http utils and user agent field #### Hack + Bash Completion: Limit commands to containers of a relevant state * Add docker dependencies coverage testing into docker-ci #### Packaging + Docker-brew 0.5.2 support and memory footprint reduction * Add new docker dependencies into docker-ci - Revert "docker.upstart: avoid spawning a `sh` process" + Docker-brew and Docker standard library + Release docker with docker * Fix the upstart script generated by get.docker.io * Enabled the docs to generate manpages. * Revert Bind daemon to 0.0.0.0 in Vagrant. #### Register * Improve auth push * Registry unit tests + mock registry #### Tests * Improve TestKillDifferentUser to prevent timeout on buildbot - Fix typo in TestBindMounts (runContainer called without image) * Improve TestGetContainersTop so it does not rely on sleep * Relax the lo interface test to allow iface index != 1 * Add registry functional test to docker-ci * Add some tests in server and utils #### Other * Contrib: bash completion script * Client: Add docker cp command and copy api endpoint to copy container files/folders to the host * Don`t read from stdout when only attached to stdin ## 0.5.3 (2013-08-13) #### Runtime * Use docker group for socket permissions - Spawn shell within upstart script - Handle ip route showing mask-less IP addresses - Add hostname to environment #### Builder - Make sure ENV instruction within build perform a commit each time ## 0.5.2 (2013-08-08) * Builder: Forbid certain paths within docker build ADD - Runtime: Change network range to avoid conflict with EC2 DNS * API: Change daemon to listen on unix socket by default ## 0.5.1 (2013-07-30) #### Runtime + Add `ps` args to `docker top` + Add support for container ID files (pidfile like) + Add container=lxc in default env + Support networkless containers with `docker run -n` and `docker -d -b=none` * Stdout/stderr logs are now stored in the same file as JSON * Allocate a /16 IP range by default, with fallback to /24. Try 12 ranges instead of 3. * Change .dockercfg format to json and support multiple auth remote - Do not override volumes from config - Fix issue with EXPOSE override #### API + Docker client now sets useragent (RFC 2616) + Add /events endpoint #### Builder + ADD command now understands URLs + CmdAdd and CmdEnv now respect Dockerfile-set ENV variables - Create directories with 755 instead of 700 within ADD instruction #### Hack * Simplify unit tests with helpers * Improve docker.upstart event * Add coverage testing into docker-ci ## 0.5.0 (2013-07-17) #### Runtime + List all processes running inside a container with 'docker top' + Host directories can be mounted as volumes with 'docker run -v' + Containers can expose public UDP ports (eg, '-p 123/udp') + Optionally specify an exact public port (eg. '-p 80:4500') * 'docker login' supports additional options - Dont save a container`s hostname when committing an image. #### Registry + New image naming scheme inspired by Go packaging convention allows arbitrary combinations of registries - Fix issues when uploading images to a private registry #### Builder + ENTRYPOINT instruction sets a default binary entry point to a container + VOLUME instruction marks a part of the container as persistent data * 'docker build' displays the full output of a build by default ## 0.4.8 (2013-07-01) + Builder: New build operation ENTRYPOINT adds an executable entry point to the container. - Runtime: Fix a bug which caused 'docker run -d' to no longer print the container ID. - Tests: Fix issues in the test suite ## 0.4.7 (2013-06-28) #### Remote API * The progress bar updates faster when downloading and uploading large files - Fix a bug in the optional unix socket transport #### Runtime * Improve detection of kernel version + Host directories can be mounted as volumes with 'docker run -b' - fix an issue when only attaching to stdin * Use 'tar --numeric-owner' to avoid uid mismatch across multiple hosts #### Hack * Improve test suite and dev environment * Remove dependency on unit tests on 'os/user' #### Other * Registry: easier push/pull to a custom registry + Documentation: add terminology section ## 0.4.6 (2013-06-22) - Runtime: fix a bug which caused creation of empty images (and volumes) to crash. ## 0.4.5 (2013-06-21) + Builder: 'docker build git://URL' fetches and builds a remote git repository * Runtime: 'docker ps -s' optionally prints container size * Tests: improved and simplified - Runtime: fix a regression introduced in 0.4.3 which caused the logs command to fail. - Builder: fix a regression when using ADD with single regular file. ## 0.4.4 (2013-06-19) - Builder: fix a regression introduced in 0.4.3 which caused builds to fail on new clients. ## 0.4.3 (2013-06-19) #### Builder + ADD of a local file will detect tar archives and unpack them * ADD improvements: use tar for copy + automatically unpack local archives * ADD uses tar/untar for copies instead of calling 'cp -ar' * Fix the behavior of ADD to be (mostly) reverse-compatible, predictable and well-documented. - Fix a bug which caused builds to fail if ADD was the first command * Nicer output for 'docker build' #### Runtime * Remove bsdtar dependency * Add unix socket and multiple -H support * Prevent rm of running containers * Use go1.1 cookiejar - Fix issue detaching from running TTY container - Forbid parallel push/pull for a single image/repo. Fixes #311 - Fix race condition within Run command when attaching. #### Client * HumanReadable ProgressBar sizes in pull * Fix docker version`s git commit output #### API * Send all tags on History API call * Add tag lookup to history command. Fixes #882 #### Documentation - Fix missing command in irc bouncer example ## 0.4.2 (2013-06-17) - Packaging: Bumped version to work around an Ubuntu bug ## 0.4.1 (2013-06-17) #### Remote Api + Add flag to enable cross domain requests + Add images and containers sizes in docker ps and docker images #### Runtime + Configure dns configuration host-wide with 'docker -d -dns' + Detect faulty DNS configuration and replace it with a public default + Allow docker run : + You can now specify public port (ex: -p 80:4500) * Improve image removal to garbage-collect unreferenced parents #### Client * Allow multiple params in inspect * Print the container id before the hijack in `docker run` #### Registry * Add regexp check on repo`s name * Move auth to the client - Remove login check on pull #### Other * Vagrantfile: Add the rest api port to vagrantfile`s port_forward * Upgrade to Go 1.1 - Builder: don`t ignore last line in Dockerfile when it doesn`t end with \n ## 0.4.0 (2013-06-03) #### Builder + Introducing Builder + 'docker build' builds a container, layer by layer, from a source repository containing a Dockerfile #### Remote API + Introducing Remote API + control Docker programmatically using a simple HTTP/json API #### Runtime * Various reliability and usability improvements ## 0.3.4 (2013-05-30) #### Builder + 'docker build' builds a container, layer by layer, from a source repository containing a Dockerfile + 'docker build -t FOO' applies the tag FOO to the newly built container. #### Runtime + Interactive TTYs correctly handle window resize * Fix how configuration is merged between layers #### Remote API + Split stdout and stderr on 'docker run' + Optionally listen on a different IP and port (use at your own risk) #### Documentation * Improve install instructions. ## 0.3.3 (2013-05-23) - Registry: Fix push regression - Various bugfixes ## 0.3.2 (2013-05-09) #### Registry * Improve the checksum process * Use the size to have a good progress bar while pushing * Use the actual archive if it exists in order to speed up the push - Fix error 400 on push #### Runtime * Store the actual archive on commit ## 0.3.1 (2013-05-08) #### Builder + Implement the autorun capability within docker builder + Add caching to docker builder + Add support for docker builder with native API as top level command + Implement ENV within docker builder - Check the command existence prior create and add Unit tests for the case * use any whitespaces instead of tabs #### Runtime + Add go version to debug infos * Kernel version - don`t show the dash if flavor is empty #### Registry + Add docker search top level command in order to search a repository - Fix pull for official images with specific tag - Fix issue when login in with a different user and trying to push * Improve checksum - async calculation #### Images + Output graph of images to dot (graphviz) - Fix ByParent function #### Documentation + New introduction and high-level overview + Add the documentation for docker builder - CSS fix for docker documentation to make REST API docs look better. - Fix CouchDB example page header mistake - Fix README formatting * Update www.docker.io website. #### Other + Website: new high-level overview - Makefile: Swap "go get" for "go get -d", especially to compile on go1.1rc * Packaging: packaging ubuntu; issue #510: Use goland-stable PPA package to build docker ## 0.3.0 (2013-05-06) #### Runtime - Fix the command existence check - strings.Split may return an empty string on no match - Fix an index out of range crash if cgroup memory is not #### Documentation * Various improvements + New example: sharing data between 2 couchdb databases #### Other * Vagrant: Use only one deb line in /etc/apt + Registry: Implement the new registry ## 0.2.2 (2013-05-03) + Support for data volumes ('docker run -v=PATH') + Share data volumes between containers ('docker run -volumes-from') + Improve documentation * Upgrade to Go 1.0.3 * Various upgrades to the dev environment for contributors ## 0.2.1 (2013-05-01) + 'docker commit -run' bundles a layer with default runtime options: command, ports etc. * Improve install process on Vagrant + New Dockerfile operation: "maintainer" + New Dockerfile operation: "expose" + New Dockerfile operation: "cmd" + Contrib script to build a Debian base layer + 'docker -d -r': restart crashed containers at daemon startup * Runtime: improve test coverage ## 0.2.0 (2013-04-23) - Runtime: ghost containers can be killed and waited for * Documentation: update install instructions - Packaging: fix Vagrantfile - Development: automate releasing binaries and ubuntu packages + Add a changelog - Various bugfixes ## 0.1.8 (2013-04-22) - Dynamically detect cgroup capabilities - Issue stability warning on kernels <3.8 - 'docker push' buffers on disk instead of memory - Fix 'docker diff' for removed files - Fix 'docker stop' for ghost containers - Fix handling of pidfile - Various bugfixes and stability improvements ## 0.1.7 (2013-04-18) - Container ports are available on localhost - 'docker ps' shows allocated TCP ports - Contributors can run 'make hack' to start a continuous integration VM - Streamline ubuntu packaging & uploading - Various bugfixes and stability improvements ## 0.1.6 (2013-04-17) - Record the author an image with 'docker commit -author' ## 0.1.5 (2013-04-17) - Disable standalone mode - Use a custom DNS resolver with 'docker -d -dns' - Detect ghost containers - Improve diagnosis of missing system capabilities - Allow disabling memory limits at compile time - Add debian packaging - Documentation: installing on Arch Linux - Documentation: running Redis on docker - Fix lxc 0.9 compatibility - Automatically load aufs module - Various bugfixes and stability improvements ## 0.1.4 (2013-04-09) - Full support for TTY emulation - Detach from a TTY session with the escape sequence `C-p C-q` - Various bugfixes and stability improvements - Minor UI improvements - Automatically create our own bridge interface 'docker0' ## 0.1.3 (2013-04-04) - Choose TCP frontend port with '-p :PORT' - Layer format is versioned - Major reliability improvements to the process manager - Various bugfixes and stability improvements ## 0.1.2 (2013-04-03) - Set container hostname with 'docker run -h' - Selective attach at run with 'docker run -a [stdin[,stdout[,stderr]]]' - Various bugfixes and stability improvements - UI polish - Progress bar on push/pull - Use XZ compression by default - Make IP allocator lazy ## 0.1.1 (2013-03-31) - Display shorthand IDs for convenience - Stabilize process management - Layers can include a commit message - Simplified 'docker attach' - Fix support for re-attaching - Various bugfixes and stability improvements - Auto-download at run - Auto-login on push - Beefed up documentation ## 0.1.0 (2013-03-23) Initial public release - Implement registry in order to push/pull images - TCP port allocation - Fix termcaps on Linux - Add documentation - Add Vagrant support with Vagrantfile - Add unit tests - Add repository/tags to ease image management - Improve the layer implementation ================================================ FILE: vendor/github.com/docker/docker/CONTRIBUTING.md ================================================ # Contributing to Docker Want to hack on Docker? Awesome! We have a contributor's guide that explains [setting up a Docker development environment and the contribution process](https://docs.docker.com/project/who-written-for/). ![Contributors guide](docs/static_files/contributors.png) This page contains information about reporting issues as well as some tips and guidelines useful to experienced open source contributors. Finally, make sure you read our [community guidelines](#docker-community-guidelines) before you start participating. ## Topics * [Reporting Security Issues](#reporting-security-issues) * [Design and Cleanup Proposals](#design-and-cleanup-proposals) * [Reporting Issues](#reporting-other-issues) * [Quick Contribution Tips and Guidelines](#quick-contribution-tips-and-guidelines) * [Community Guidelines](#docker-community-guidelines) ## Reporting security issues The Docker 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](mailto: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. ## Reporting other issues A great way to contribute to the project is to send a detailed report when you encounter an issue. We always appreciate a well-written, thorough bug report, and will thank you for it! Check that [our issue database](https://github.com/docker/docker/issues) doesn't already include that problem or suggestion before submitting an issue. If you find a match, add a quick "+1" or "I have this problem too." Doing this helps prioritize the most common problems and requests. When reporting issues, please include your host OS (Ubuntu 12.04, Fedora 19, etc). Please include: * The output of `uname -a`. * The output of `docker version`. * The output of `docker -D info`. Please also include the steps required to reproduce the problem if possible and applicable. This information will help us review and fix your issue faster. **Issue Report Template**: ``` Description of problem: `docker version`: `docker info`: `uname -a`: Environment details (AWS, VirtualBox, physical, etc.): How reproducible: Steps to Reproduce: 1. 2. 3. Actual Results: Expected Results: Additional info: ``` ##Quick contribution tips and guidelines This section gives the experienced contributor some tips and guidelines. ###Pull requests are always welcome Not sure if that typo is worth a pull request? Found a bug and know how to fix it? Do it! We will appreciate it. Any significant improvement should be documented as [a GitHub issue](https://github.com/docker/docker/issues) before anybody starts working on it. We are always thrilled to receive pull requests. We do our best to process them quickly. If your pull request is not accepted on the first try, don't get discouraged! Our contributor's guide explains [the review process we use for simple changes](https://docs.docker.com/project/make-a-contribution/). ### Design and cleanup proposals You can propose new designs for existing Docker features. You can also design entirely new features. We really appreciate contributors who want to refactor or otherwise cleanup our project. For information on making these types of contributions, see [the advanced contribution section](https://docs.docker.com/project/advanced-contributing/) in the contributors guide. We try hard to keep Docker lean and focused. Docker can't do everything for everybody. This means that we might decide against incorporating a new feature. However, there might be a way to implement that feature *on top of* Docker. ### Talking to other Docker users and contributors
Internet Relay Chat (IRC)

IRC a direct line to our most knowledgeable Docker users; we have both the #docker and #docker-dev group on irc.freenode.net. IRC is a rich chat protocol but it can overwhelm new users. You can search our chat archives.

Read our IRC quickstart guide for an easy way to get started.
Google Groups There are two groups. Docker-user is for people using Docker containers. The docker-dev group is for contributors and other people contributing to the Docker project.
Twitter You can follow Docker's Twitter feed to get updates on our products. You can also tweet us questions or just share blogs or stories.
Stack Overflow Stack Overflow has over 7000K Docker questions listed. We regularly monitor Docker questions and so do many other knowledgeable Docker users.
### Conventions Fork the repository and make changes on your fork in a feature branch: - If it's a bug fix branch, name it XXXX-something where XXXX is the number of the issue. - If it's a feature branch, create an enhancement issue to announce your intentions, and name it XXXX-something where XXXX is the number of the issue. Submit unit tests for your changes. Go has a great test framework built in; use it! Take a look at existing tests for inspiration. [Run the full test suite](https://docs.docker.com/project/test-and-docs/) on your branch before submitting a pull request. Update the documentation when creating or modifying features. Test your documentation changes for clarity, concision, and correctness, as well as a clean documentation build. See our contributors guide for [our style guide](https://docs.docker.com/project/doc-style) and instructions on [building the documentation](https://docs.docker.com/project/test-and-docs/#build-and-test-the-documentation). Write clean code. Universally formatted code promotes ease of writing, reading, and maintenance. Always run `gofmt -s -w file.go` on each changed file before committing your changes. Most editors have plug-ins that do this automatically. Pull request descriptions should be as clear as possible and include a reference to all the issues that they address. Commit messages must start with a capitalized and short summary (max. 50 chars) written in the imperative, followed by an optional, more detailed explanatory text which is separated from the summary by an empty line. Code review comments may be added to your pull request. Discuss, then make the suggested modifications and push additional commits to your feature branch. Post a comment after pushing. New commits show up in the pull request automatically, but the reviewers are notified only when you comment. Pull requests must be cleanly rebased on top of master without multiple branches mixed into the PR. **Git tip**: If your PR no longer merges cleanly, use `rebase master` in your feature branch to update your pull request rather than `merge master`. Before you make a pull request, squash your commits into logical units of work using `git rebase -i` and `git push -f`. A logical unit of work is a consistent set of patches that should be reviewed together: for example, upgrading the version of a vendored dependency and taking advantage of its now available new feature constitute two separate units of work. Implementing a new function and calling it in another file constitute a single logical unit of work. The very high majority of submissions should have a single commit, so if in doubt: squash down to one. After every commit, [make sure the test suite passes] ((https://docs.docker.com/project/test-and-docs/)). Include documentation changes in the same pull request so that a revert would remove all traces of the feature or fix. Include an issue reference like `Closes #XXXX` or `Fixes #XXXX` in commits that close an issue. Including references automatically closes the issue on a merge. Please do not add yourself to the `AUTHORS` file, as it is regenerated regularly from the Git history. Please see the [Coding Style](#coding-style) for further guidelines. ### Merge approval Docker maintainers use LGTM (Looks Good To Me) in comments on the code review to indicate acceptance. A change requires LGTMs from an absolute majority of the maintainers of each component affected. For example, if a change affects `docs/` and `registry/`, it needs an absolute majority from the maintainers of `docs/` AND, separately, an absolute majority of the maintainers of `registry/`. For more details, see the [MAINTAINERS](MAINTAINERS) page. ### Sign your work The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch 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 Use your real name (sorry, no pseudonyms or anonymous contributions.) If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. Note that the old-style `Docker-DCO-1.1-Signed-off-by: ...` format is still accepted, so there is no need to update outstanding pull requests to the new format right away, but please do adjust your processes for future contributions. ### How can I become a maintainer? * Step 1: Learn the component inside out * Step 2: Make yourself useful by contributing code, bug fixes, support etc. * Step 3: Volunteer on the IRC channel (#docker at Freenode) * Step 4: Propose yourself at a scheduled docker meeting in #docker-dev Don't forget: being a maintainer is a time investment. Make sure you will have time to make yourself available. You don't have to be a maintainer to make a difference on the project! ### IRC meetings There are two monthly meetings taking place on #docker-dev IRC to accommodate all timezones. Anybody can propose a topic for discussion prior to the meeting. If you feel the conversation is going off-topic, feel free to point it out. For the exact dates and times, have a look at [the irc-minutes repo](https://github.com/docker/irc-minutes). The minutes also contain all the notes from previous meetings. ## Docker community guidelines We want to keep the Docker community awesome, growing and collaborative. We need your help to keep it that way. To help with this we've come up with some general guidelines for the community as a whole: * Be nice: Be courteous, respectful and polite to fellow community members: no regional, racial, gender, or other abuse will be tolerated. We like nice people way better than mean ones! * Encourage diversity and participation: Make everyone in our community feel welcome, regardless of their background and the extent of their contributions, and do everything possible to encourage participation in our community. * Keep it legal: Basically, don't get us in trouble. Share only content that you own, do not share private or sensitive information, and don't break the law. * Stay on topic: Make sure that you are posting to the correct channel and avoid off-topic discussions. Remember when you update an issue or respond to an email you are potentially sending to a large number of people. Please consider this before you update. Also remember that nobody likes spam. ### Guideline violations — 3 strikes method The point of this section is not to find opportunities to punish people, but we do need a fair way to deal with people who are making our community suck. 1. First occurrence: We'll give you a friendly, but public reminder that the behavior is inappropriate according to our guidelines. 2. Second occurrence: We will send you a private message with a warning that any additional violations will result in removal from the community. 3. Third occurrence: Depending on the violation, we may need to delete or ban your account. **Notes:** * Obvious spammers are banned on first occurrence. If we don't do this, we'll have spam all over the place. * Violations are forgiven after 6 months of good behavior, and we won't hold a grudge. * People who commit minor infractions will get some education, rather than hammering them in the 3 strikes process. * The rules apply equally to everyone in the community, no matter how much you've contributed. * Extreme violations of a threatening, abusive, destructive or illegal nature will be addressed immediately and are not subject to 3 strikes or forgiveness. * Contact abuse@docker.com to report abuse or appeal violations. In the case of appeals, we know that mistakes happen, and we'll work with you to come up with a fair solution if there has been a misunderstanding. ## Coding Style Unless explicitly stated, we follow all coding guidelines from the Go community. While some of these standards may seem arbitrary, they somehow seem to result in a solid, consistent codebase. It is possible that the code base does not currently comply with these guidelines. We are not looking for a massive PR that fixes this, since that goes against the spirit of the guidelines. All new contributions should make a best effort to clean up and make the code base better than they left it. Obviously, apply your best judgement. Remember, the goal here is to make the code base easier for humans to navigate and understand. Always keep that in mind when nudging others to comply. The rules: 1. All code should be formatted with `gofmt -s`. 2. All code should pass the default levels of [`golint`](https://github.com/golang/lint). 3. All code should follow the guidelines covered in [Effective Go](http://golang.org/doc/effective_go.html) and [Go Code Review Comments](https://github.com/golang/go/wiki/CodeReviewComments). 4. Comment the code. Tell us the why, the history and the context. 5. Document _all_ declarations and methods, even private ones. Declare expectations, caveats and anything else that may be important. If a type gets exported, having the comments already there will ensure it's ready. 6. Variable name length should be proportional to it's context and no longer. `noCommaALongVariableNameLikeThisIsNotMoreClearWhenASimpleCommentWouldDo`. In practice, short methods will have short variable names and globals will have longer names. 7. No underscores in package names. If you need a compound name, step back, and re-examine why you need a compound name. If you still think you need a compound name, lose the underscore. 8. No utils or helpers packages. If a function is not general enough to warrant it's own package, it has not been written generally enough to be a part of a util package. Just leave it unexported and well-documented. 9. All tests should run with `go test` and outside tooling should not be required. No, we don't need another unit testing framework. Assertion packages are acceptable if they provide _real_ incremental value. 10. Even though we call these "rules" above, they are actually just guidelines. Since you've read all the rules, you now know that. If you are having trouble getting into the mood of idiomatic Go, we recommend reading through [Effective Go](http://golang.org/doc/effective_go.html). The [Go Blog](http://blog.golang.org/) is also a great resource. Drinking the kool-aid is a lot easier than going thirsty. ================================================ FILE: vendor/github.com/docker/docker/Dockerfile ================================================ # This file describes the standard way to build Docker, using docker # # Usage: # # # Assemble the full dev environment. This is slow the first time. # docker build -t docker . # # # Mount your source in an interactive container for quick testing: # docker run -v `pwd`:/go/src/github.com/docker/docker --privileged -i -t docker bash # # # Run the test suite: # docker run --privileged docker hack/make.sh test # # # Publish a release: # docker run --privileged \ # -e AWS_S3_BUCKET=baz \ # -e AWS_ACCESS_KEY=foo \ # -e AWS_SECRET_KEY=bar \ # -e GPG_PASSPHRASE=gloubiboulga \ # docker hack/release.sh # # Note: AppArmor used to mess with privileged mode, but this is no longer # the case. Therefore, you don't have to disable it anymore. # FROM ubuntu:14.04 MAINTAINER Tianon Gravi (@tianon) RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys E871F18B51E0147C77796AC81196BA81F6B0FC61 RUN echo deb http://ppa.launchpad.net/zfs-native/stable/ubuntu trusty main > /etc/apt/sources.list.d/zfs.list # Packaged dependencies RUN apt-get update && apt-get install -y \ apparmor \ aufs-tools \ automake \ bash-completion \ btrfs-tools \ build-essential \ createrepo \ curl \ dpkg-sig \ git \ iptables \ libapparmor-dev \ libcap-dev \ libsqlite3-dev \ mercurial \ parallel \ python-mock \ python-pip \ python-websocket \ reprepro \ ruby1.9.1 \ ruby1.9.1-dev \ s3cmd=1.1.0* \ ubuntu-zfs \ libzfs-dev \ --no-install-recommends # Get lvm2 source for compiling statically RUN git clone -b v2_02_103 https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 # see https://git.fedorahosted.org/cgit/lvm2.git/refs/tags for release tags # Compile and install lvm2 RUN cd /usr/local/lvm2 \ && ./configure --enable-static_link \ && make device-mapper \ && make install_device-mapper # see https://git.fedorahosted.org/cgit/lvm2.git/tree/INSTALL # Install lxc ENV LXC_VERSION 1.1.2 RUN mkdir -p /usr/src/lxc \ && curl -sSL https://linuxcontainers.org/downloads/lxc/lxc-${LXC_VERSION}.tar.gz | tar -v -C /usr/src/lxc/ -xz --strip-components=1 RUN cd /usr/src/lxc \ && ./configure \ && make \ && make install \ && ldconfig # Install Go ENV GO_VERSION 1.4.2 RUN curl -sSL https://golang.org/dl/go${GO_VERSION}.src.tar.gz | tar -v -C /usr/local -xz \ && mkdir -p /go/bin ENV PATH /go/bin:/usr/local/go/bin:$PATH ENV GOPATH /go:/go/src/github.com/docker/docker/vendor RUN cd /usr/local/go/src && ./make.bash --no-clean 2>&1 # Compile Go for cross compilation ENV DOCKER_CROSSPLATFORMS \ linux/386 linux/arm \ darwin/amd64 darwin/386 \ freebsd/amd64 freebsd/386 freebsd/arm \ windows/amd64 windows/386 # (set an explicit GOARM of 5 for maximum compatibility) ENV GOARM 5 RUN cd /usr/local/go/src \ && set -x \ && for platform in $DOCKER_CROSSPLATFORMS; do \ GOOS=${platform%/*} \ GOARCH=${platform##*/} \ ./make.bash --no-clean 2>&1; \ done # This has been commented out and kept as reference because we don't support compiling with older Go anymore. # ENV GOFMT_VERSION 1.3.3 # RUN curl -sSL https://storage.googleapis.com/golang/go${GOFMT_VERSION}.$(go env GOOS)-$(go env GOARCH).tar.gz | tar -C /go/bin -xz --strip-components=2 go/bin/gofmt # Update this sha when we upgrade to go 1.5.0 ENV GO_TOOLS_COMMIT 069d2f3bcb68257b627205f0486d6cc69a231ff9 # Grab Go's cover tool for dead-simple code coverage testing # Grab Go's vet tool for examining go code to find suspicious constructs # and help prevent errors that the compiler might not catch RUN git clone https://github.com/golang/tools.git /go/src/golang.org/x/tools \ && (cd /go/src/golang.org/x/tools && git checkout -q $GO_TOOLS_COMMIT) \ && go install -v golang.org/x/tools/cmd/cover \ && go install -v golang.org/x/tools/cmd/vet # Grab Go's lint tool ENV GO_LINT_COMMIT f42f5c1c440621302702cb0741e9d2ca547ae80f RUN git clone https://github.com/golang/lint.git /go/src/github.com/golang/lint \ && (cd /go/src/github.com/golang/lint && git checkout -q $GO_LINT_COMMIT) \ && go install -v github.com/golang/lint/golint # TODO replace FPM with some very minimal debhelper stuff RUN gem install --no-rdoc --no-ri fpm --version 1.3.2 # Install registry ENV REGISTRY_COMMIT 2317f721a3d8428215a2b65da4ae85212ed473b4 RUN set -x \ && export GOPATH="$(mktemp -d)" \ && git clone https://github.com/docker/distribution.git "$GOPATH/src/github.com/docker/distribution" \ && (cd "$GOPATH/src/github.com/docker/distribution" && git checkout -q "$REGISTRY_COMMIT") \ && GOPATH="$GOPATH/src/github.com/docker/distribution/Godeps/_workspace:$GOPATH" \ go build -o /usr/local/bin/registry-v2 github.com/docker/distribution/cmd/registry \ && rm -rf "$GOPATH" # Get the "docker-py" source so we can run their integration tests ENV DOCKER_PY_COMMIT 91985b239764fe54714fa0a93d52aa362357d251 RUN git clone https://github.com/docker/docker-py.git /docker-py \ && cd /docker-py \ && git checkout -q $DOCKER_PY_COMMIT # Setup s3cmd config RUN { \ echo '[default]'; \ echo 'access_key=$AWS_ACCESS_KEY'; \ echo 'secret_key=$AWS_SECRET_KEY'; \ } > ~/.s3cfg # Set user.email so crosbymichael's in-container merge commits go smoothly RUN git config --global user.email 'docker-dummy@example.com' # Add an unprivileged user to be used for tests which need it RUN groupadd -r docker RUN useradd --create-home --gid docker unprivilegeduser VOLUME /var/lib/docker WORKDIR /go/src/github.com/docker/docker ENV DOCKER_BUILDTAGS apparmor selinux # Let us use a .bashrc file RUN ln -sfv $PWD/.bashrc ~/.bashrc # Register Docker's bash completion. RUN ln -sv $PWD/contrib/completion/bash/docker /etc/bash_completion.d/docker # Get useful and necessary Hub images so we can "docker load" locally instead of pulling COPY contrib/download-frozen-image.sh /go/src/github.com/docker/docker/contrib/ RUN ./contrib/download-frozen-image.sh /docker-frozen-images \ busybox:latest@8c2e06607696bd4afb3d03b687e361cc43cf8ec1a4a725bc96e39f05ba97dd55 \ hello-world:frozen@91c95931e552b11604fea91c2f537284149ec32fff0f700a4769cfd31d7696ae \ jess/unshare@5c9f6ea50341a2a8eb6677527f2bdedbf331ae894a41714fda770fb130f3314d # see also "hack/make/.ensure-frozen-images" (which needs to be updated any time this list is) # Download man page generator RUN set -x \ && export GOPATH="$(mktemp -d)" \ && git clone -b v1.0.3 https://github.com/cpuguy83/go-md2man.git "$GOPATH/src/github.com/cpuguy83/go-md2man" \ && git clone -b v1.2 https://github.com/russross/blackfriday.git "$GOPATH/src/github.com/russross/blackfriday" \ && go get -v -d github.com/cpuguy83/go-md2man \ && go build -v -o /usr/local/bin/go-md2man github.com/cpuguy83/go-md2man \ && rm -rf "$GOPATH" # Download toml validator ENV TOMLV_COMMIT 9baf8a8a9f2ed20a8e54160840c492f937eeaf9a RUN set -x \ && export GOPATH="$(mktemp -d)" \ && git clone https://github.com/BurntSushi/toml.git "$GOPATH/src/github.com/BurntSushi/toml" \ && (cd "$GOPATH/src/github.com/BurntSushi/toml" && git checkout -q "$TOMLV_COMMIT") \ && go build -v -o /usr/local/bin/tomlv github.com/BurntSushi/toml/cmd/tomlv \ && rm -rf "$GOPATH" # Build/install the tool for embedding resources in Windows binaries ENV RSRC_COMMIT e48dbf1b7fc464a9e85fcec450dddf80816b76e0 RUN set -x \ && git clone https://github.com/akavel/rsrc.git /go/src/github.com/akavel/rsrc \ && cd /go/src/github.com/akavel/rsrc \ && git checkout -q $RSRC_COMMIT \ && go install -v # Wrap all commands in the "docker-in-docker" script to allow nested containers ENTRYPOINT ["hack/dind"] # Upload docker source COPY . /go/src/github.com/docker/docker ================================================ FILE: vendor/github.com/docker/docker/Dockerfile.simple ================================================ # docker build -t docker:simple -f Dockerfile.simple . # docker run --rm docker:simple hack/make.sh dynbinary # docker run --rm --privileged docker:simple hack/dind hack/make.sh test-unit # docker run --rm --privileged -v /var/lib/docker docker:simple hack/dind hack/make.sh dynbinary test-integration-cli # This represents the bare minimum required to build and test Docker. FROM debian:jessie # compile and runtime deps # https://github.com/docker/docker/blob/master/project/PACKAGERS.md#build-dependencies # https://github.com/docker/docker/blob/master/project/PACKAGERS.md#runtime-dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ btrfs-tools \ curl \ gcc \ git \ golang \ libdevmapper-dev \ libsqlite3-dev \ \ ca-certificates \ e2fsprogs \ iptables \ procps \ xz-utils \ \ aufs-tools \ lxc \ && rm -rf /var/lib/apt/lists/* ENV AUTO_GOPATH 1 WORKDIR /usr/src/docker COPY . /usr/src/docker ================================================ FILE: vendor/github.com/docker/docker/LICENSE ================================================ 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-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. ================================================ FILE: vendor/github.com/docker/docker/MAINTAINERS ================================================ # Docker maintainers file # # This file describes who runs the Docker project and how. # This is a living document - if you see something out of date or missing, # speak up! # # It is structured to be consumable by both humans and programs. # To extract its contents programmatically, use any TOML-compliant # parser. [Rules] [Rules.maintainers] title = "What is a maintainer?" text = """ There are different types of maintainers, with different responsibilities, but all maintainers have 3 things in common: 1) They share responsibility in the project's success. 2) They have made a long-term, recurring time investment to improve the project. 3) They spend that time doing whatever needs to be done, not necessarily what is the most interesting or fun. Maintainers are often under-appreciated, because their work is harder to appreciate. It's easy to appreciate a really cool and technically advanced feature. It's harder to appreciate the absence of bugs, the slow but steady improvement in stability, or the reliability of a release process. But those things distinguish a good project from a great one. """ [Rules.bdfl] title = "The Benevolent dictator for life (BDFL)" text = """ Docker follows the timeless, highly efficient and totally unfair system known as [Benevolent dictator for life](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), with yours truly, Solomon Hykes, in the role of BDFL. This means that all decisions are made, by default, by Solomon. Since making every decision myself would be highly un-scalable, in practice decisions are spread across multiple maintainers. Ideally, the BDFL role is like the Queen of England: awesome crown, but not an actual operational role day-to-day. The real job of a BDFL is to NEVER GO AWAY. Every other rule can change, perhaps drastically so, but the BDFL will always be there, preserving the philosophy and principles of the project, and keeping ultimate authority over its fate. This gives us great flexibility in experimenting with various governance models, knowing that we can always press the "reset" button without fear of fragmentation or deadlock. See the US congress for a counter-example. BDFL daily routine: * Is the project governance stuck in a deadlock or irreversibly fragmented? * If yes: refactor the project governance * Are there issues or conflicts escalated by core? * If yes: resolve them * Go back to polishing that crown. """ [Rules.decisions] title = "How are decisions made?" text = """ Short answer: EVERYTHING IS A PULL REQUEST. Docker is an open-source project with an open design philosophy. This means that the repository is the source of truth for EVERY aspect of the project, including its philosophy, design, road map, and APIs. *If it's part of the project, it's in the repo. If it's in the repo, it's part of the project.* As a result, all decisions can be expressed as changes to the repository. An implementation change is a change to the source code. An API change is a change to the API specification. A philosophy change is a change to the philosophy manifesto, and so on. All decisions affecting Docker, big and small, follow the same 3 steps: * Step 1: Open a pull request. Anyone can do this. * Step 2: Discuss the pull request. Anyone can do this. * Step 3: Merge or refuse the pull request. Who does this depends on the nature of the pull request and which areas of the project it affects. See *review flow* for details. Because Docker is such a large and active project, it's important for everyone to know who is responsible for deciding what. That is determined by a precise set of rules. * For every *decision* in the project, the rules should designate, in a deterministic way, who should *decide*. * For every *problem* in the project, the rules should designate, in a deterministic way, who should be responsible for *fixing* it. * For every *question* in the project, the rules should designate, in a deterministic way, who should be expected to have the *answer*. """ [Rules.review] title = "Review flow" text = """ Pull requests should be processed according to the following flow: * For each subsystem affected by the change, the maintainers of the subsystem must approve or refuse it. It is the responsibility of the subsystem maintainers to process patches affecting them in a timely manner. * If the change affects areas of the code which are not part of a subsystem, or if subsystem maintainers are unable to reach a timely decision, it must be approved by the core maintainers. * If the change affects the UI or public APIs, or if it represents a major change in architecture, the architects must approve or refuse it. * If the change affects the operations of the project, it must be approved or rejected by the relevant operators. * If the change affects the governance, philosophy, goals or principles of the project, it must be approved by BDFL. """ [Rules.DCO] title = "Helping contributors with the DCO" text = """ The [DCO or `Sign your work`]( https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work) requirement is not intended as a roadblock or speed bump. Some Docker contributors are not as familiar with `git`, or have used a web based editor, and thus asking them to `git commit --amend -s` is not the best way forward. In this case, maintainers can update the commits based on clause (c) of the DCO. The most trivial way for a contributor to allow the maintainer to do this, is to add a DCO signature in a Pull Requests's comment, or a maintainer can simply note that the change is sufficiently trivial that it does not substantivly change the existing contribution - i.e., a spelling change. When you add someone's DCO, please also add your own to keep a log. """ [Rules.holiday] title = "I'm a maintainer, and I'm going on holiday" text = """ Please let your co-maintainers and other contributors know by raising a pull request that comments out your `MAINTAINERS` file entry using a `#`. """ [Rules."no direct push"] title = "I'm a maintainer. Should I make pull requests too?" text = """ Yes. Nobody should ever push to master directly. All changes should be made through a pull request. """ [Rules.meta] title = "How is this process changed?" text = "Just like everything else: by making a pull request :)" # Current project organization [Org] bdfl = "shykes" # The chief architect is responsible for the overall integrity of the technical architecture # across all subsystems, and the consistency of APIs and UI. # # Changes to UI, public APIs and overall architecture (for example a plugin system) must # be approved by the chief architect. "Chief Architect" = "shykes" # The Chief Operator is responsible for the day-to-day operations of the project including: # - facilitating communications amongst all the contributors; # - tracking release schedules; # - managing the relationship with downstream distributions and upstream dependencies; # - helping new contributors to get involved and become successful contributors and maintainers # # The role is also responsible for managing and measuring the success of the overall project # and ensuring it is governed properly working in concert with the Docker Governance Advisory Board (DGAB). "Chief Operator" = "spf13" [Org.Operators] # The operators make sure the trains run on time. They are responsible for overall operations # of the project. This includes facilitating communication between all the participants; helping # newcomers get involved and become successful contributors and maintainers; tracking the schedule # of releases; managing the relationship with downstream distributions and upstream dependencies; # define measures of success for the project and measure progress; Devise and implement tools and # processes which make contributors and maintainers happier and more efficient. [Org.Operators.security] people = [ "erw", "diogomonica", "nathanmccauley" ] [Org.Operators."monthly meetings"] people = [ "sven", "tianon" ] [Org.Operators.infrastructure] people = [ "jfrazelle", "crosbymichael" ] [Org.Operators.community] people = [ "theadactyl" ] # The chief maintainer is responsible for all aspects of quality for the project including # code reviews, usability, stability, security, performance, etc. # The most important function of the chief maintainer is to lead by example. On the first # day of a new maintainer, the best advice should be "follow the C.M.'s example and you'll # be fine". "Chief Maintainer" = "crosbymichael" # The community manager is responsible for serving the project community, including users, # contributors and partners. This involves: # - facilitating communication between maintainers, contributors and users # - organizing contributor and maintainer events # - helping new contributors get involved # - anything the project community needs to be successful # # The community manager is a point of contact for any contributor who has questions, concerns # or feedback about project operations. "Community Manager" = "theadactyl" [Org."Core maintainers"] # The Core maintainers are the ghostbusters of the project: when there's a problem others # can't solve, they show up and fix it with bizarre devices and weaponry. # They have final say on technical implementation and coding style. # They are ultimately responsible for quality in all its forms: usability polish, # bugfixes, performance, stability, etc. When ownership can cleanly be passed to # a subsystem, they are responsible for doing so and holding the # subsystem maintainers accountable. If ownership is unclear, they are the de facto owners. # For each release (including minor releases), a "release captain" is assigned from the # pool of core maintainers. Rotation is encouraged across all maintainers, to ensure # the release process is clear and up-to-date. # # It is common for core maintainers to "branch out" to join or start a subsystem. people = [ "calavera", "crosbymichael", "erikh", "estesp", "icecrime", "jfrazelle", "lk4d4", "runcom", "tibor", "unclejack", "vbatts", "vieux", "vishh" ] [Org.Subsystems] # As the project grows, it gets separated into well-defined subsystems. Each subsystem # has a dedicated group of maintainers, which are dedicated to that subsytem and responsible # for its quality. # This "cellular division" is the primary mechanism for scaling maintenance of the project as it grows. # # The maintainers of each subsytem are responsible for: # # 1. Exposing a clear road map for improving their subsystem. # 2. Deliver prompt feedback and decisions on pull requests affecting their subsystem. # 3. Be available to anyone with questions, bug reports, criticism etc. # on their component. This includes IRC, GitHub requests and the mailing # list. # 4. Make sure their subsystem respects the philosophy, design and # road map of the project. # # #### How to review patches to your subsystem # # Accepting pull requests: # # - If the pull request appears to be ready to merge, give it a `LGTM`, which # stands for "Looks Good To Me". # - If the pull request has some small problems that need to be changed, make # a comment adressing the issues. # - If the changes needed to a PR are small, you can add a "LGTM once the # following comments are adressed..." this will reduce needless back and # forth. # - If the PR only needs a few changes before being merged, any MAINTAINER can # make a replacement PR that incorporates the existing commits and fixes the # problems before a fast track merge. # # Closing pull requests: # # - If a PR appears to be abandoned, after having attempted to contact the # original contributor, then a replacement PR may be made. Once the # replacement PR is made, any contributor may close the original one. # - If you are not sure if the pull request implements a good feature or you # do not understand the purpose of the PR, ask the contributor to provide # more documentation. If the contributor is not able to adequately explain # the purpose of the PR, the PR may be closed by any MAINTAINER. # - If a MAINTAINER feels that the pull request is sufficiently architecturally # flawed, or if the pull request needs significantly more design discussion # before being considered, the MAINTAINER should close the pull request with # a short explanation of what discussion still needs to be had. It is # important not to leave such pull requests open, as this will waste both the # MAINTAINER's time and the contributor's time. It is not good to string a # contributor on for weeks or months, having them make many changes to a PR # that will eventually be rejected. [Org.Subsystems.Documentation] people = [ "fredlf", "james", "moxiegirl", "thaJeztah", "jamtur01", "spf13", "sven" ] [Org.Subsystems.libcontainer] people = [ "crosbymichael", "jnagal", "lk4d4", "mpatel", "vmarmol" ] [Org.Subsystems.registry] people = [ "dmcg", "dmp42", "jlhawn", "samalba", "sday", "vbatts" ] [Org.Subsystems."build tools"] people = [ "shykes", "tianon" ] [Org.Subsystem."remote api"] people = [ "vieux" ] [Org.Subsystem.swarm] people = [ "aluzzardi", "vieux" ] [Org.Subsystem.machine] people = [ "bfirsh", "ehazlett" ] [Org.Subsystem.compose] people = [ "aanand" ] [Org.Subsystem.builder] people = [ "duglin", "erikh", "tibor" ] [Org.Curators] # The curators help ensure that incoming issues and pull requests are properly triaged and # that our various contribution and reviewing processes are respected. With their knowledge of # the repository activity, they can also guide contributors to relevant material or # discussions. # # They are neither code nor docs reviewers, so they are never expected to merge. They can # however: # - close an issue or pull request when it's an exact duplicate # - close an issue or pull request when it's inappropriate or off-topic people = [ "thajeztah" ] [people] # A reference list of all people associated with the project. # All other sections should refer to people by their canonical key # in the people section. # ADD YOURSELF HERE IN ALPHABETICAL ORDER [people.aanand] Name = "Aanand Prasad" Email = "aanand@docker.com" GitHub = "aanand" [people.aluzzardi] Name = "Andrea Luzzardi" Email = "aluzzardi@docker.com" GitHub = "aluzzardi" [people.bfirsh] Name = "Ben Firshman" Email = "ben@firshman.co.uk" GitHub = "bfirsh" [people.calavera] Name = "David Calavera" Email = "david.calavera@gmail.com" GitHub = "calavera" [people.cpuguy83] Name = "Brian Goff" Email = "cpuguy83@gmail.com" Github = "cpuguy83" [people.crosbymichael] Name = "Michael Crosby" Email = "crosbymichael@gmail.com" GitHub = "crosbymichael" [people.diogomonica] Name = "Diogo Monica" Email = "diogo@docker.com" GitHub = "diogomonica" [people.duglin] Name = "Doug Davis" Email = "dug@us.ibm.com" GitHub = "duglin" [people.dmcg] Name = "Derek McGowan" Email = "derek@docker.com" Github = "dmcgowan" [people.dmp42] Name = "Olivier Gambier" Email = "olivier@docker.com" Github = "dmp42" [people.ehazlett] Name = "Evan Hazlett" Email = "ejhazlett@gmail.com" GitHub = "ehazlett" [people.erikh] Name = "Erik Hollensbe" Email = "erik@docker.com" GitHub = "erikh" [people.erw] Name = "Eric Windisch" Email = "eric@windisch.us" GitHub = "ewindisch" [people.estesp] Name = "Phil Estes" Email = "estesp@linux.vnet.ibm.com" GitHub = "estesp" [people.fredlf] Name = "Fred Lifton" Email = "fred.lifton@docker.com" GitHub = "fredlf" [people.icecrime] Name = "Arnaud Porterie" Email = "arnaud@docker.com" GitHub = "icecrime" [people.jfrazelle] Name = "Jessie Frazelle" Email = "j@docker.com" GitHub = "jfrazelle" [people.jlhawn] Name = "Josh Hawn" Email = "josh.hawn@docker.com" Github = "jlhawn" [people.lk4d4] Name = "Alexander Morozov" Email = "lk4d4@docker.com" GitHub = "lk4d4" [people.moxiegirl] Name = "Mary Anthony" Email = "mary.anthony@docker.com" GitHub = "moxiegirl" [people.nathanmccauley] Name = "Nathan McCauley" Email = "nathan.mccauley@docker.com" GitHub = "nathanmccauley" [people.runcom] Name = "Antonio Murdaca" Email = "me@runcom.ninja" GitHub = "runcom" [people.sday] Name = "Stephen Day" Email = "stephen.day@docker.com" Github = "stevvooe" [people.shykes] Name = "Solomon Hykes" Email = "solomon@docker.com" GitHub = "shykes" [people.spf13] Name = "Steve Francia" Email = "steve.francia@gmail.com" GitHub = "spf13" [people.sven] Name = "Sven Dowideit" Email = "SvenDowideit@home.org.au" GitHub = "SvenDowideit" [people.thajeztah] Name = "Sebastiaan van Stijn" Email = "github@gone.nl" GitHub = "thaJeztah" [people.theadactyl] Name = "Thea Lamkin" Email = "thea@docker.com" GitHub = "theadactyl" [people.tianon] Name = "Tianon Gravi" Email = "admwiggin@gmail.com" GitHub = "tianon" [people.tibor] Name = "Tibor Vass" Email = "tibor@docker.com" GitHub = "tiborvass" [people.vbatts] Name = "Vincent Batts" Email = "vbatts@redhat.com" GitHub = "vbatts" [people.vieux] Name = "Victor Vieux" Email = "vieux@docker.com" GitHub = "vieux" [people.vmarmol] Name = "Victor Marmol" Email = "vmarmol@google.com" GitHub = "vmarmol" [people.jnagal] Name = "Rohit Jnagal" Email = "jnagal@google.com" GitHub = "rjnagal" [people.mpatel] Name = "Mrunal Patel" Email = "mpatel@redhat.com" GitHub = "mrunalp" [people.unclejack] Name = "Cristian Staretu" Email = "cristian.staretu@gmail.com" GitHub = "unclejack" [people.vishh] Name = "Vishnu Kannan" Email = "vishnuk@google.com" GitHub = "vishh" ================================================ FILE: vendor/github.com/docker/docker/Makefile ================================================ .PHONY: all binary build cross default docs docs-build docs-shell shell test test-unit test-integration-cli test-docker-py validate # env vars passed through directly to Docker's build scripts # to allow things like `make DOCKER_CLIENTONLY=1 binary` easily # `docs/sources/contributing/devenvironment.md ` and `project/PACKAGERS.md` have some limited documentation of some of these DOCKER_ENVS := \ -e BUILDFLAGS \ -e DOCKER_CLIENTONLY \ -e DOCKER_DEBUG \ -e DOCKER_EXECDRIVER \ -e DOCKER_EXPERIMENTAL \ -e DOCKER_GRAPHDRIVER \ -e DOCKER_STORAGE_OPTS \ -e DOCKER_USERLANDPROXY \ -e TESTDIRS \ -e TESTFLAGS \ -e TIMEOUT # note: we _cannot_ add "-e DOCKER_BUILDTAGS" here because even if it's unset in the shell, that would shadow the "ENV DOCKER_BUILDTAGS" set in our Dockerfile, which is very important for our official builds # to allow `make BIND_DIR=. shell` or `make BIND_DIR= test` # (default to no bind mount if DOCKER_HOST is set) # note: BINDDIR is supported for backwards-compatibility here BIND_DIR := $(if $(BINDDIR),$(BINDDIR),$(if $(DOCKER_HOST),,bundles)) DOCKER_MOUNT := $(if $(BIND_DIR),-v "$(CURDIR)/$(BIND_DIR):/go/src/github.com/docker/docker/$(BIND_DIR)") GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null) DOCKER_IMAGE := docker-dev$(if $(GIT_BRANCH),:$(GIT_BRANCH)) DOCKER_DOCS_IMAGE := docker-docs$(if $(GIT_BRANCH),:$(GIT_BRANCH)) DOCKER_RUN_DOCKER := docker run --rm -it --privileged $(DOCKER_ENVS) $(DOCKER_MOUNT) "$(DOCKER_IMAGE)" DOCKER_RUN_DOCS := docker run --rm -it $(DOCS_MOUNT) -e AWS_S3_BUCKET -e NOCACHE # for some docs workarounds (see below in "docs-build" target) GITCOMMIT := $(shell git rev-parse --short HEAD 2>/dev/null) default: binary all: build $(DOCKER_RUN_DOCKER) hack/make.sh binary: build $(DOCKER_RUN_DOCKER) hack/make.sh binary cross: build $(DOCKER_RUN_DOCKER) hack/make.sh binary cross deb: build $(DOCKER_RUN_DOCKER) hack/make.sh binary build-deb rpm: build $(DOCKER_RUN_DOCKER) hack/make.sh binary build-rpm test: build $(DOCKER_RUN_DOCKER) hack/make.sh binary cross test-unit test-integration-cli test-docker-py test-unit: build $(DOCKER_RUN_DOCKER) hack/make.sh test-unit test-integration-cli: build $(DOCKER_RUN_DOCKER) hack/make.sh binary test-integration-cli test-docker-py: build $(DOCKER_RUN_DOCKER) hack/make.sh binary test-docker-py validate: build $(DOCKER_RUN_DOCKER) hack/make.sh validate-dco validate-gofmt validate-pkg validate-lint validate-test validate-toml validate-vet shell: build $(DOCKER_RUN_DOCKER) bash build: bundles docker build -t "$(DOCKER_IMAGE)" . bundles: mkdir bundles docs: $(MAKE) -C docs docs ================================================ FILE: vendor/github.com/docker/docker/NOTICE ================================================ Docker Copyright 2012-2015 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. ================================================ FILE: vendor/github.com/docker/docker/README.md ================================================ Docker: the Linux container engine ================================== Docker is an open source project to pack, ship and run any application as a lightweight container. Docker containers are both *hardware-agnostic* and *platform-agnostic*. This means they can run anywhere, from your laptop to the largest EC2 compute instance and everything in between - and they don't require you to use a particular language, framework or packaging system. That makes them great building blocks for deploying and scaling web apps, databases, and backend services without depending on a particular stack or provider. Docker began as an open-source implementation of the deployment engine which powers [dotCloud](https://dotcloud.com), a popular Platform-as-a-Service. It benefits directly from the experience accumulated over several years of large-scale operation and support of hundreds of thousands of applications and databases. ![Docker L](docs/static_files/docker-logo-compressed.png "Docker") ## Security Disclosure Security is very important to us. If you have any issue regarding security, please disclose the information responsibly by sending an email to security@docker.com and not by creating a github issue. ## Better than VMs A common method for distributing applications and sandboxing their execution is to use virtual machines, or VMs. Typical VM formats are VMware's vmdk, Oracle VirtualBox's vdi, and Amazon EC2's ami. In theory these formats should allow every developer to automatically package their application into a "machine" for easy distribution and deployment. In practice, that almost never happens, for a few reasons: * *Size*: VMs are very large which makes them impractical to store and transfer. * *Performance*: running VMs consumes significant CPU and memory, which makes them impractical in many scenarios, for example local development of multi-tier applications, and large-scale deployment of cpu and memory-intensive applications on large numbers of machines. * *Portability*: competing VM environments don't play well with each other. Although conversion tools do exist, they are limited and add even more overhead. * *Hardware-centric*: VMs were designed with machine operators in mind, not software developers. As a result, they offer very limited tooling for what developers need most: building, testing and running their software. For example, VMs offer no facilities for application versioning, monitoring, configuration, logging or service discovery. By contrast, Docker relies on a different sandboxing method known as *containerization*. Unlike traditional virtualization, containerization takes place at the kernel level. Most modern operating system kernels now support the primitives necessary for containerization, including Linux with [openvz](https://openvz.org), [vserver](http://linux-vserver.org) and more recently [lxc](https://linuxcontainers.org/), Solaris with [zones](https://docs.oracle.com/cd/E26502_01/html/E29024/preface-1.html#scrolltoc), and FreeBSD with [Jails](https://www.freebsd.org/doc/handbook/jails.html). Docker builds on top of these low-level primitives to offer developers a portable format and runtime environment that solves all four problems. Docker containers are small (and their transfer can be optimized with layers), they have basically zero memory and cpu overhead, they are completely portable, and are designed from the ground up with an application-centric design. Perhaps best of all, because Docker operates at the OS level, it can still be run inside a VM! ## Plays well with others Docker does not require you to buy into a particular programming language, framework, packaging system, or configuration language. Is your application a Unix process? Does it use files, tcp connections, environment variables, standard Unix streams and command-line arguments as inputs and outputs? Then Docker can run it. Can your application's build be expressed as a sequence of such commands? Then Docker can build it. ## Escape dependency hell A common problem for developers is the difficulty of managing all their application's dependencies in a simple and automated way. This is usually difficult for several reasons: * *Cross-platform dependencies*. Modern applications often depend on a combination of system libraries and binaries, language-specific packages, framework-specific modules, internal components developed for another project, etc. These dependencies live in different "worlds" and require different tools - these tools typically don't work well with each other, requiring awkward custom integrations. * *Conflicting dependencies*. Different applications may depend on different versions of the same dependency. Packaging tools handle these situations with various degrees of ease - but they all handle them in different and incompatible ways, which again forces the developer to do extra work. * *Custom dependencies*. A developer may need to prepare a custom version of their application's dependency. Some packaging systems can handle custom versions of a dependency, others can't - and all of them handle it differently. Docker solves the problem of dependency hell by giving the developer a simple way to express *all* their application's dependencies in one place, while streamlining the process of assembling them. If this makes you think of [XKCD 927](https://xkcd.com/927/), don't worry. Docker doesn't *replace* your favorite packaging systems. It simply orchestrates their use in a simple and repeatable way. How does it do that? With layers. Docker defines a build as running a sequence of Unix commands, one after the other, in the same container. Build commands modify the contents of the container (usually by installing new files on the filesystem), the next command modifies it some more, etc. Since each build command inherits the result of the previous commands, the *order* in which the commands are executed expresses *dependencies*. Here's a typical Docker build process: ```bash FROM ubuntu:12.04 RUN apt-get update && apt-get install -y python python-pip curl RUN curl -sSL https://github.com/shykes/helloflask/archive/master.tar.gz | tar -xzv RUN cd helloflask-master && pip install -r requirements.txt ``` Note that Docker doesn't care *how* dependencies are built - as long as they can be built by running a Unix command in a container. Getting started =============== Docker can be installed on your local machine as well as servers - both bare metal and virtualized. It is available as a binary on most modern Linux systems, or as a VM on Windows, Mac and other systems. We also offer an [interactive tutorial](https://www.docker.com/tryit/) for quickly learning the basics of using Docker. For up-to-date install instructions, see the [Docs](https://docs.docker.com). Usage examples ============== Docker can be used to run short-lived commands, long-running daemons (app servers, databases, etc.), interactive shell sessions, etc. You can find a [list of real-world examples](https://docs.docker.com/examples/) in the documentation. Under the hood -------------- Under the hood, Docker is built on the following components: * The [cgroups](https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt) and [namespaces](http://man7.org/linux/man-pages/man7/namespaces.7.html) capabilities of the Linux kernel * The [Go](https://golang.org) programming language * The [Docker Image Specification](https://github.com/docker/docker/blob/master/image/spec/v1.md) * The [Libcontainer Specification](https://github.com/docker/libcontainer/blob/master/SPEC.md) Contributing to Docker ====================== [![GoDoc](https://godoc.org/github.com/docker/docker?status.svg)](https://godoc.org/github.com/docker/docker) [![Jenkins Build Status](https://jenkins.dockerproject.org/job/Docker%20Master/badge/icon)](https://jenkins.dockerproject.org/job/Docker%20Master/) Want to hack on Docker? Awesome! We have [instructions to help you get started contributing code or documentation](https://docs.docker.com/project/who-written-for/). These instructions are probably not perfect, please let us know if anything feels wrong or incomplete. Better yet, submit a PR and improve them yourself. Getting the development builds ============================== Want to run Docker from a master build? You can download master builds at [master.dockerproject.org](https://master.dockerproject.org). They are updated with each commit merged into the master branch. Don't know how to use that super cool new feature in the master build? Check out the master docs at [docs.master.dockerproject.org](http://docs.master.dockerproject.org). How the project is run ====================== Docker is a very, very active project. If you want to learn more about how it is run, or want to get more involved, the best place to start is [the project directory](https://github.com/docker/docker/tree/master/project). We are always open to suggestions on process improvements, and are always looking for more maintainers. ### Talking to other Docker users and contributors
Internet Relay Chat (IRC)

IRC a direct line to our most knowledgeable Docker users; we have both the #docker and #docker-dev group on irc.freenode.net. IRC is a rich chat protocol but it can overwhelm new users. You can search our chat archives.

Read our IRC quickstart guide for an easy way to get started.
Google Groups There are two groups. Docker-user is for people using Docker containers. The docker-dev group is for contributors and other people contributing to the Docker project.
Twitter You can follow Docker's Twitter feed to get updates on our products. You can also tweet us questions or just share blogs or stories.
Stack Overflow Stack Overflow has over 7000K Docker questions listed. We regularly monitor Docker questions and so do many other knowledgeable Docker users.
### Legal *Brought to you courtesy of our legal counsel. For more context, please see the [NOTICE](https://github.com/docker/docker/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 is licensed under the Apache License, Version 2.0. See [LICENSE](https://github.com/docker/docker/blob/master/LICENSE) for the full license text. Other Docker Related Projects ============================= There are a number of projects under development that are based on Docker's core technology. These projects expand the tooling built around the Docker platform to broaden its application and utility. * [Docker Registry](https://github.com/docker/distribution): Registry server for Docker (hosting/delivery of repositories and images) * [Docker Machine](https://github.com/docker/machine): Machine management for a container-centric world * [Docker Swarm](https://github.com/docker/swarm): A Docker-native clustering system * [Docker Compose](https://github.com/docker/compose) (formerly Fig): Define and run multi-container apps * [Kitematic](https://github.com/kitematic/kitematic): The easiest way to use Docker on Mac and Windows If you know of another project underway that should be listed here, please help us keep this list up-to-date by submitting a PR. ================================================ FILE: vendor/github.com/docker/docker/ROADMAP.md ================================================ Docker Engine Roadmap ===================== ### How should I use this document? This document provides description of items that the project decided to prioritize. This should serve as a reference point for Docker contributors to understand where the project is going, and help determine if a contribution could be conflicting with some longer terms plans. The fact that a feature isn't listed here doesn't mean that a patch for it will automatically be refused (except for those mentioned as "frozen features" below)! We are always happy to receive patches for new cool features we haven't thought about, or didn't judge priority. Please however understand that such patches might take longer for us to review. ### How can I help? Short term objectives are listed in the [wiki](https://github.com/docker/docker/wiki) and described in [Issues](https://github.com/docker/docker/issues?q=is%3Aopen+is%3Aissue+label%3Aroadmap). Our goal is to split down the workload in such way that anybody can jump in and help. Please comment on issues if you want to take it to avoid duplicating effort! Similarly, if a maintainer is already assigned on an issue you'd like to participate in, pinging him on IRC or GitHub to offer your help is the best way to go. ### How can I add something to the roadmap? The roadmap process is new to the Docker Engine: we are only beginning to structure and document the project objectives. Our immediate goal is to be more transparent, and work with our community to focus our efforts on fewer prioritized topics. We hope to offer in the near future a process allowing anyone to propose a topic to the roadmap, but we are not quite there yet. For the time being, the BDFL remains the keeper of the roadmap, and we won't be accepting pull requests adding or removing items from this file. # 1. Features and refactoring ## 1.1 Security Security is a top objective for the Docker Engine. The most notable items we intend to provide in the near future are: - Trusted distribution of images: the effort is driven by the [distribution](https://github.com/docker/distribution) group but will have significant impact on the Engine - [User namespaces](https://github.com/docker/docker/pull/12648) - [Seccomp support](https://github.com/docker/libcontainer/pull/613) ## 1.2 Plumbing project We define a plumbing tool as a standalone piece of software usable and meaningful on its own. In the current state of the Docker Engine, most subsystems provide independent functionalities (such the builder, pushing and pulling images, running applications in a containerized environment, etc) but all are coupled in a single binary. We want to offer the users to flexibility to use only the pieces they need, and we will also gain in maintainability by splitting the project among multiple repositories. As it currently stands, the rough design outlines is to have: - Low level plumbing tools, each dealing with one responsibility (e.g., [runC](https://runc.io)) - Docker subsystems services, each exposing an elementary concept over an API, and relying on one or multiple lower level plumbing tools for their implementation (e.g., network management) - Docker Engine to expose higher level actions (e.g., create a container with volume `V` and network `N`), while still providing pass-through access to the individual subsystems. The architectural details are still being worked on, but one thing we know for sure is that we need to technically decouple the pieces. ### 1.2.1 Runtime A Runtime tool already exists today in the form of [runC](https://github.com/opencontainers/runc). We intend to modify the Engine to directly call out to a binary implementing the Open Containers Specification such as runC rather than relying on libcontainer to set the container runtime up. This plan will deprecate the existing [`execdriver`](https://github.com/docker/docker/tree/master/daemon/execdriver) as different runtime backends will be implemented as separated binaries instead of being compiled into the Engine. ### 1.2.2 Builder The Builder (i.e., the ability to build an image from a Dockerfile) is already nicely decoupled, but would benefit from being entirely separated from the Engine, and rely on the standard Engine API for its operations. ### 1.2.3 Distribution Distribution already has a [dedicated repository](https://github.com/docker/distribution) which holds the implementation for Registry v2 and client libraries. We could imagine going further by having the Engine call out to a binary providing image distribution related functionalities. There are two short term goals related to image distribution. The first is stabilize and simplify the push/pull code. Following that is the conversion to the more secure Registry V2 protocol. ### 1.2.4 Networking Most of networking related code was already decoupled today in [libnetwork](https://github.com/docker/libnetwork). As with other ingredients, we might want to take it a step further and make it a meaningful utility that the Engine would call out to instead of a library. ## 1.3 Plugins An initiative around plugins started with Docker 1.7.0, with the goal of allowing for out of process extensibility of some Docker functionalities, starting with volumes and networking. The approach is to provide specific extension points rather than generic hooking facilities. We also deliberately keep the extensions API the simplest possible, expanding as we discover valid use cases that cannot be implemented. At the time of writing: - Plugin support is merged as an experimental feature: real world use cases and user feedback will help us refine the UX to make the feature more user friendly. - There are no immediate plans to expand on the number of pluggable subsystems. - Golang 1.5 might add language support for [plugins](https://docs.google.com/document/d/1nr-TQHw_er6GOQRsF6T43GGhFDelrAP0NqSS_00RgZQ) which we consider supporting as an alternative to JSON/HTTP. ## 1.4 Volume management Volumes are not a first class citizen in the Engine today: we would like better volume management, similar to the way network are managed in the new [CNM](https://github.com/docker/docker/issues/9983). ## 1.5 Better API implementation The current Engine API is insufficiently typed, versioned, and ultimately hard to maintain. We also suffer from the lack of a common implementation with [Swarm](https://github.com/docker/swarm). ## 1.6 Checkpoint/restore Support for checkpoint/restore was [merged](https://github.com/docker/libcontainer/pull/479) in [libcontainer](https://github.com/docker/libcontainer) and made available through [runC](https://runc.io): we intend to take advantage of it in the Engine. # 2 Frozen features ## 2.1 Docker exec We won't accept patches expanding the surface of `docker exec`, which we intend to keep as a *debugging* feature, as well as being strongly dependent on the the Runtime ingredient effort. ## 2.2 Dockerfile syntax The Dockerfile syntax as we know it is simple, and has proven succesful in supporting all our [official images](https://github.com/docker-library/official-images). Although this is *not* a definitive move, we temporarily won't accept more patches to the Dockerfile syntax for several reasons: - Long term impact of syntax changes is a sensitive matter that require an amount of attention the volume of Engine codebase and activity today doesn't allow us to provide. - Allowing the Builder to be implemented as a separate utility consuming the Engine's API will open the door for many possibilities, such as offering alternate syntaxes or DSL for existing languages without cluttering the Engine's codebase. - A standalone Builder will also offer the opportunity for a better dedicated group of maintainers to own the Dockerfile syntax and decide collectively on the direction to give it. - Our experience with official images tend to show that no new instruction or syntax expansion is *strictly* necessary for the majority of use cases, and although we are aware many things are still lacking for many, we cannot make it a priority yet for the above reasons. Again, this is not about saying that the Dockerfile syntax is done, it's about making choices about what we want to do first! ================================================ FILE: vendor/github.com/docker/docker/VERSION ================================================ 1.8.0-dev ================================================ FILE: vendor/github.com/docker/docker/api/README.md ================================================ This directory contains code pertaining to the Docker API: - Used by the docker client when communicating with the docker daemon - Used by third party tools wishing to interface with the docker daemon ================================================ FILE: vendor/github.com/docker/docker/api/api_unit_test.go ================================================ package api import ( "testing" ) func TestJsonContentType(t *testing.T) { if !MatchesContentType("application/json", "application/json") { t.Fail() } if !MatchesContentType("application/json; charset=utf-8", "application/json") { t.Fail() } if MatchesContentType("dockerapplication/json", "application/json") { t.Fail() } } ================================================ FILE: vendor/github.com/docker/docker/api/client/attach.go ================================================ package client import ( "encoding/json" "fmt" "io" "net/url" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/signal" ) // CmdAttach attaches to a running container. // // Usage: docker attach [OPTIONS] CONTAINER func (cli *DockerCli) CmdAttach(args ...string) error { cmd := cli.Subcmd("attach", []string{"CONTAINER"}, "Attach to a running container", true) noStdin := cmd.Bool([]string{"#nostdin", "-no-stdin"}, false, "Do not attach STDIN") proxy := cmd.Bool([]string{"#sig-proxy", "-sig-proxy"}, true, "Proxy all received signals to the process") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) if err != nil { return err } defer serverResp.body.Close() var c types.ContainerJSON if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { return err } if !c.State.Running { return fmt.Errorf("You cannot attach to a stopped container, start it first") } if err := cli.CheckTtyInput(!*noStdin, c.Config.Tty); err != nil { return err } if c.Config.Tty && cli.isTerminalOut { if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil { logrus.Debugf("Error monitoring TTY size: %s", err) } } var in io.ReadCloser v := url.Values{} v.Set("stream", "1") if !*noStdin && c.Config.OpenStdin { v.Set("stdin", "1") in = cli.in } v.Set("stdout", "1") v.Set("stderr", "1") if *proxy && !c.Config.Tty { sigc := cli.forwardAllSignals(cmd.Arg(0)) defer signal.StopCatch(sigc) } if err := cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), c.Config.Tty, in, cli.out, cli.err, nil, nil); err != nil { return err } _, status, err := getExitCode(cli, cmd.Arg(0)) if err != nil { return err } if status != 0 { return StatusError{StatusCode: status} } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/build.go ================================================ package client import ( "bufio" "encoding/base64" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "os/exec" "path" "path/filepath" "runtime" "strconv" "strings" "github.com/docker/docker/api" "github.com/docker/docker/graph/tags" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/httputils" "github.com/docker/docker/pkg/jsonmessage" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/symlink" "github.com/docker/docker/pkg/units" "github.com/docker/docker/pkg/urlutil" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) const ( tarHeaderSize = 512 ) // CmdBuild builds a new image from the source code at a given path. // // If '-' is provided instead of a path or URL, Docker will build an image from either a Dockerfile or tar archive read from STDIN. // // Usage: docker build [OPTIONS] PATH | URL | - func (cli *DockerCli) CmdBuild(args ...string) error { cmd := cli.Subcmd("build", []string{"PATH | URL | -"}, "Build a new image from the source code at PATH", true) tag := cmd.String([]string{"t", "-tag"}, "", "Repository name (and optionally a tag) for the image") suppressOutput := cmd.Bool([]string{"q", "-quiet"}, false, "Suppress the verbose output generated by the containers") noCache := cmd.Bool([]string{"#no-cache", "-no-cache"}, false, "Do not use cache when building the image") rm := cmd.Bool([]string{"#rm", "-rm"}, true, "Remove intermediate containers after a successful build") forceRm := cmd.Bool([]string{"-force-rm"}, false, "Always remove intermediate containers") pull := cmd.Bool([]string{"-pull"}, false, "Always attempt to pull a newer version of the image") dockerfileName := cmd.String([]string{"f", "-file"}, "", "Name of the Dockerfile (Default is 'PATH/Dockerfile')") flMemoryString := cmd.String([]string{"m", "-memory"}, "", "Memory limit") flMemorySwap := cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap") flCPUShares := cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") flCpuPeriod := cmd.Int64([]string{"-cpu-period"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) period") flCpuQuota := cmd.Int64([]string{"-cpu-quota"}, 0, "Limit the CPU CFS (Completely Fair Scheduler) quota") flCPUSetCpus := cmd.String([]string{"-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") flCPUSetMems := cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)") flCgroupParent := cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) var ( context archive.Archive isRemote bool err error ) _, err = exec.LookPath("git") hasGit := err == nil if cmd.Arg(0) == "-" { // As a special case, 'docker build -' will build from either an empty context with the // contents of stdin as a Dockerfile, or a tar-ed context from stdin. buf := bufio.NewReader(cli.in) magic, err := buf.Peek(tarHeaderSize) if err != nil && err != io.EOF { return fmt.Errorf("failed to peek context header from STDIN: %v", err) } if !archive.IsArchive(magic) { dockerfile, err := ioutil.ReadAll(buf) if err != nil { return fmt.Errorf("failed to read Dockerfile from STDIN: %v", err) } // -f option has no meaning when we're reading it from stdin, // so just use our default Dockerfile name *dockerfileName = api.DefaultDockerfileName context, err = archive.Generate(*dockerfileName, string(dockerfile)) } else { context = ioutil.NopCloser(buf) } } else if urlutil.IsURL(cmd.Arg(0)) && (!urlutil.IsGitURL(cmd.Arg(0)) || !hasGit) { isRemote = true } else { root := cmd.Arg(0) if urlutil.IsGitURL(root) { root, err = utils.GitClone(root) if err != nil { return err } defer os.RemoveAll(root) } if _, err := os.Stat(root); err != nil { return err } absRoot, err := filepath.Abs(root) if err != nil { return err } filename := *dockerfileName // path to Dockerfile if *dockerfileName == "" { // No -f/--file was specified so use the default *dockerfileName = api.DefaultDockerfileName filename = filepath.Join(absRoot, *dockerfileName) // Just to be nice ;-) look for 'dockerfile' too but only // use it if we found it, otherwise ignore this check if _, err = os.Lstat(filename); os.IsNotExist(err) { tmpFN := path.Join(absRoot, strings.ToLower(*dockerfileName)) if _, err = os.Lstat(tmpFN); err == nil { *dockerfileName = strings.ToLower(*dockerfileName) filename = tmpFN } } } origDockerfile := *dockerfileName // used for error msg if filename, err = filepath.Abs(filename); err != nil { return err } // Verify that 'filename' is within the build context filename, err = symlink.FollowSymlinkInScope(filename, absRoot) if err != nil { return fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", origDockerfile, root) } // Now reset the dockerfileName to be relative to the build context *dockerfileName, err = filepath.Rel(absRoot, filename) if err != nil { return err } // And canonicalize dockerfile name to a platform-independent one *dockerfileName, err = archive.CanonicalTarNameForPath(*dockerfileName) if err != nil { return fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", *dockerfileName, err) } if _, err = os.Lstat(filename); os.IsNotExist(err) { return fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile) } var includes = []string{"."} excludes, err := utils.ReadDockerIgnore(path.Join(root, ".dockerignore")) if err != nil { return err } // If .dockerignore mentions .dockerignore or the Dockerfile // then make sure we send both files over to the daemon // because Dockerfile is, obviously, needed no matter what, and // .dockerignore is needed to know if either one needs to be // removed. The deamon will remove them for us, if needed, after it // parses the Dockerfile. keepThem1, _ := fileutils.Matches(".dockerignore", excludes) keepThem2, _ := fileutils.Matches(*dockerfileName, excludes) if keepThem1 || keepThem2 { includes = append(includes, ".dockerignore", *dockerfileName) } if err := utils.ValidateContextDirectory(root, excludes); err != nil { return fmt.Errorf("Error checking context: '%s'.", err) } options := &archive.TarOptions{ Compression: archive.Uncompressed, ExcludePatterns: excludes, IncludeFiles: includes, } context, err = archive.TarWithOptions(root, options) if err != nil { return err } } var body io.Reader // Setup an upload progress bar // FIXME: ProgressReader shouldn't be this annoying to use if context != nil { sf := streamformatter.NewStreamFormatter() body = progressreader.New(progressreader.Config{ In: context, Out: cli.out, Formatter: sf, NewLines: true, ID: "", Action: "Sending build context to Docker daemon", }) } var memory int64 if *flMemoryString != "" { parsedMemory, err := units.RAMInBytes(*flMemoryString) if err != nil { return err } memory = parsedMemory } var memorySwap int64 if *flMemorySwap != "" { if *flMemorySwap == "-1" { memorySwap = -1 } else { parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap) if err != nil { return err } memorySwap = parsedMemorySwap } } // Send the build context v := &url.Values{} //Check if the given image name can be resolved if *tag != "" { repository, tag := parsers.ParseRepositoryTag(*tag) if err := registry.ValidateRepositoryName(repository); err != nil { return err } if len(tag) > 0 { if err := tags.ValidateTagName(tag); err != nil { return err } } } v.Set("t", *tag) if *suppressOutput { v.Set("q", "1") } if isRemote { v.Set("remote", cmd.Arg(0)) } if *noCache { v.Set("nocache", "1") } if *rm { v.Set("rm", "1") } else { v.Set("rm", "0") } if *forceRm { v.Set("forcerm", "1") } if *pull { v.Set("pull", "1") } v.Set("cpusetcpus", *flCPUSetCpus) v.Set("cpusetmems", *flCPUSetMems) v.Set("cpushares", strconv.FormatInt(*flCPUShares, 10)) v.Set("cpuquota", strconv.FormatInt(*flCpuQuota, 10)) v.Set("cpuperiod", strconv.FormatInt(*flCpuPeriod, 10)) v.Set("memory", strconv.FormatInt(memory, 10)) v.Set("memswap", strconv.FormatInt(memorySwap, 10)) v.Set("cgroupparent", *flCgroupParent) v.Set("dockerfile", *dockerfileName) headers := http.Header(make(map[string][]string)) buf, err := json.Marshal(cli.configFile.AuthConfigs) if err != nil { return err } headers.Add("X-Registry-Config", base64.URLEncoding.EncodeToString(buf)) if context != nil { headers.Set("Content-Type", "application/tar") } sopts := &streamOpts{ rawTerminal: true, in: body, out: cli.out, headers: headers, } serverResp, err := cli.stream("POST", fmt.Sprintf("/build?%s", v.Encode()), sopts) // Windows: show error message about modified file permissions. if runtime.GOOS == "windows" { h, err := httputils.ParseServerHeader(serverResp.header.Get("Server")) if err == nil { if h.OS != "windows" { fmt.Fprintln(cli.err, `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.`) } } } if jerr, ok := err.(*jsonmessage.JSONError); ok { // If no error code is set, default to 1 if jerr.Code == 0 { jerr.Code = 1 } return StatusError{Status: jerr.Message, StatusCode: jerr.Code} } return err } ================================================ FILE: vendor/github.com/docker/docker/api/client/cli.go ================================================ package client import ( "crypto/tls" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "reflect" "strings" "text/template" "github.com/docker/docker/cliconfig" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/sockets" "github.com/docker/docker/pkg/term" ) // DockerCli represents the docker command line client. // Instances of the client can be returned from NewDockerCli. type DockerCli struct { // proto holds the client protocol i.e. unix. proto string // addr holds the client address. addr string // basePath holds the path to prepend to the requests basePath string // configFile has the client configuration file configFile *cliconfig.ConfigFile // in holds the input stream and closer (io.ReadCloser) for the client. in io.ReadCloser // out holds the output stream (io.Writer) for the client. out io.Writer // err holds the error stream (io.Writer) for the client. err io.Writer // keyFile holds the key file as a string. keyFile string // tlsConfig holds the TLS configuration for the client, and will // set the scheme to https in NewDockerCli if present. tlsConfig *tls.Config // scheme holds the scheme of the client i.e. https. scheme string // inFd holds the file descriptor of the client's STDIN (if valid). inFd uintptr // outFd holds file descriptor of the client's STDOUT (if valid). outFd uintptr // isTerminalIn indicates whether the client's STDIN is a TTY isTerminalIn bool // isTerminalOut dindicates whether the client's STDOUT is a TTY isTerminalOut bool // transport holds the client transport instance. transport *http.Transport } var funcMap = template.FuncMap{ "json": func(v interface{}) string { a, _ := json.Marshal(v) return string(a) }, } func (cli *DockerCli) Out() io.Writer { return cli.out } func (cli *DockerCli) Err() io.Writer { return cli.err } func (cli *DockerCli) getMethod(args ...string) (func(...string) error, bool) { camelArgs := make([]string, len(args)) for i, s := range args { if len(s) == 0 { return nil, false } camelArgs[i] = strings.ToUpper(s[:1]) + strings.ToLower(s[1:]) } methodName := "Cmd" + strings.Join(camelArgs, "") method := reflect.ValueOf(cli).MethodByName(methodName) if !method.IsValid() { return nil, false } return method.Interface().(func(...string) error), true } // Cmd executes the specified command. func (cli *DockerCli) Cmd(args ...string) error { if len(args) > 1 { method, exists := cli.getMethod(args[:2]...) if exists { return method(args[2:]...) } } if len(args) > 0 { method, exists := cli.getMethod(args[0]) if !exists { return fmt.Errorf("docker: '%s' is not a docker command.\nSee 'docker --help'.", args[0]) } return method(args[1:]...) } return cli.CmdHelp() } // Subcmd is a subcommand of the main "docker" command. // A subcommand represents an action that can be performed // from the Docker command line client. // // Multiple subcommand synopses may be provided with one 'Usage' line being // printed for each in the following way: // // Usage: docker [OPTIONS] // docker [OPTIONS] // ... // // If no undeprecated flags are added to the returned FlagSet, "[OPTIONS]" will // not be included on the usage synopsis lines. If no synopses are given, only // one usage synopsis line will be printed with nothing following the // "[OPTIONS]" section // // To see all available subcommands, run "docker --help". func (cli *DockerCli) Subcmd(name string, synopses []string, description string, exitOnError bool) *flag.FlagSet { var errorHandling flag.ErrorHandling if exitOnError { errorHandling = flag.ExitOnError } else { errorHandling = flag.ContinueOnError } flags := flag.NewFlagSet(name, errorHandling) flags.Usage = func() { flags.ShortUsage() flags.PrintDefaults() } flags.ShortUsage = func() { options := "" if flags.FlagCountUndeprecated() > 0 { options = " [OPTIONS]" } if len(synopses) == 0 { synopses = []string{""} } // Allow for multiple command usage synopses. for i, synopsis := range synopses { lead := "\t" if i == 0 { // First line needs the word 'Usage'. lead = "Usage:\t" } if synopsis != "" { synopsis = " " + synopsis } fmt.Fprintf(flags.Out(), "\n%sdocker %s%s%s", lead, name, options, synopsis) } fmt.Fprintf(flags.Out(), "\n\n%s\n", description) } return flags } // CheckTtyInput 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 (cli *DockerCli) CheckTtyInput(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 && !cli.isTerminalIn { return errors.New("cannot enable tty mode on non tty input") } return nil } // NewDockerCli returns a DockerCli instance with IO output and error streams set by in, out and err. // The key file, protocol (i.e. unix) and address are passed in as strings, along with the tls.Config. If the tls.Config // is set the client scheme will be set to https. // The client will be given a 32-second timeout (see https://github.com/docker/docker/pull/8035). func NewDockerCli(in io.ReadCloser, out, err io.Writer, keyFile string, proto, addr string, tlsConfig *tls.Config) *DockerCli { var ( inFd uintptr outFd uintptr isTerminalIn = false isTerminalOut = false scheme = "http" basePath = "" ) if tlsConfig != nil { scheme = "https" } if in != nil { inFd, isTerminalIn = term.GetFdInfo(in) } if out != nil { outFd, isTerminalOut = term.GetFdInfo(out) } if err == nil { err = out } // The transport is created here for reuse during the client session. tr := &http.Transport{ TLSClientConfig: tlsConfig, } sockets.ConfigureTCPTransport(tr, proto, addr) configFile, e := cliconfig.Load(cliconfig.ConfigDir()) if e != nil { fmt.Fprintf(err, "WARNING: Error loading config file:%v\n", e) } if proto == "tcp" { // error is checked in pkg/parsers already parsed, _ := url.Parse("tcp://" + addr) addr = parsed.Host basePath = parsed.Path } return &DockerCli{ proto: proto, addr: addr, basePath: basePath, configFile: configFile, in: in, out: out, err: err, keyFile: keyFile, inFd: inFd, outFd: outFd, isTerminalIn: isTerminalIn, isTerminalOut: isTerminalOut, tlsConfig: tlsConfig, scheme: scheme, transport: tr, } } ================================================ FILE: vendor/github.com/docker/docker/api/client/client.go ================================================ // Package client provides a command-line interface for Docker. // // Run "docker help SUBCOMMAND" or "docker SUBCOMMAND --help" to see more information on any Docker subcommand, including the full list of options supported for the subcommand. // See https://docs.docker.com/installation/ for instructions on installing Docker. package client import "fmt" // An 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) } ================================================ FILE: vendor/github.com/docker/docker/api/client/commit.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "github.com/docker/docker/api/types" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" ) // CmdCommit creates a new image from a container's changes. // // Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] func (cli *DockerCli) CmdCommit(args ...string) error { cmd := cli.Subcmd("commit", []string{"CONTAINER [REPOSITORY[:TAG]]"}, "Create a new image from a container's changes", true) flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit") flComment := cmd.String([]string{"m", "-message"}, "", "Commit message") flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith \")") flChanges := opts.NewListOpts(nil) cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image") // FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands. flConfig := cmd.String([]string{"#run", "#-run"}, "", "This option is deprecated and will be removed in a future version in favor of inline Dockerfile-compatible commands") cmd.Require(flag.Max, 2) cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var ( name = cmd.Arg(0) repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1)) ) //Check if the given image name can be resolved if repository != "" { if err := registry.ValidateRepositoryName(repository); err != nil { return err } } v := url.Values{} v.Set("container", name) v.Set("repo", repository) v.Set("tag", tag) v.Set("comment", *flComment) v.Set("author", *flAuthor) for _, change := range flChanges.GetAll() { v.Add("changes", change) } if *flPause != true { v.Set("pause", "0") } var ( config *runconfig.Config response types.ContainerCommitResponse ) if *flConfig != "" { config = &runconfig.Config{} if err := json.Unmarshal([]byte(*flConfig), config); err != nil { return err } } serverResp, err := cli.call("POST", "/commit?"+v.Encode(), config, nil) if err != nil { return err } defer serverResp.body.Close() if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { return err } fmt.Fprintln(cli.out, response.ID) return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/cp.go ================================================ package client import ( "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/url" "os" "path/filepath" "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/archive" flag "github.com/docker/docker/pkg/mflag" ) type copyDirection int const ( fromContainer copyDirection = (1 << iota) toContainer acrossContainers = fromContainer | toContainer ) // CmdCp copies files/folders to or from a path in a container. // // When copying from a container, if LOCALPATH is '-' the data is written as a // tar archive file to STDOUT. // // When copying to a container, if LOCALPATH is '-' the data is read as a tar // archive file from STDIN, and the destination CONTAINER:PATH, must specify // a directory. // // Usage: // docker cp CONTAINER:PATH LOCALPATH|- // docker cp LOCALPATH|- CONTAINER:PATH func (cli *DockerCli) CmdCp(args ...string) error { cmd := cli.Subcmd( "cp", []string{"CONTAINER:PATH LOCALPATH|-", "LOCALPATH|- CONTAINER:PATH"}, strings.Join([]string{ "Copy files/folders between a container and your host.\n", "Use '-' 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.", }, ""), true, ) cmd.Require(flag.Exact, 2) cmd.ParseFlags(args, true) if cmd.Arg(0) == "" { return fmt.Errorf("source can not be empty") } if cmd.Arg(1) == "" { return fmt.Errorf("destination can not be empty") } srcContainer, srcPath := splitCpArg(cmd.Arg(0)) dstContainer, dstPath := splitCpArg(cmd.Arg(1)) var direction copyDirection if srcContainer != "" { direction |= fromContainer } if dstContainer != "" { direction |= toContainer } switch direction { case fromContainer: return cli.copyFromContainer(srcContainer, srcPath, dstPath) case toContainer: return cli.copyToContainer(srcPath, dstContainer, dstPath) case acrossContainers: // Copying between containers isn't supported. return fmt.Errorf("copying between containers is not supported") default: // User didn't specify any container. return fmt.Errorf("must specify at least one container source") } } // 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 filepath.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] } func (cli *DockerCli) statContainerPath(containerName, path string) (types.ContainerPathStat, error) { var stat types.ContainerPathStat query := make(url.Values, 1) query.Set("path", filepath.ToSlash(path)) // Normalize the paths used in the API. urlStr := fmt.Sprintf("/containers/%s/archive?%s", containerName, query.Encode()) response, err := cli.call("HEAD", urlStr, nil, nil) if err != nil { return stat, err } defer response.body.Close() if response.statusCode != http.StatusOK { return stat, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) } return getContainerPathStatFromHeader(response.header) } func getContainerPathStatFromHeader(header http.Header) (types.ContainerPathStat, error) { var stat types.ContainerPathStat encodedStat := header.Get("X-Docker-Container-Path-Stat") statDecoder := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encodedStat)) err := json.NewDecoder(statDecoder).Decode(&stat) if err != nil { err = fmt.Errorf("unable to decode container path stat header: %s", err) } return stat, err } func resolveLocalPath(localPath string) (absPath string, err error) { if absPath, err = filepath.Abs(localPath); err != nil { return } return archive.PreserveTrailingDotOrSeparator(absPath, localPath), nil } func (cli *DockerCli) copyFromContainer(srcContainer, srcPath, dstPath string) (err error) { if dstPath != "-" { // Get an absolute destination path. dstPath, err = resolveLocalPath(dstPath) if err != nil { return err } } query := make(url.Values, 1) query.Set("path", filepath.ToSlash(srcPath)) // Normalize the paths used in the API. urlStr := fmt.Sprintf("/containers/%s/archive?%s", srcContainer, query.Encode()) response, err := cli.call("GET", urlStr, nil, nil) if err != nil { return err } defer response.body.Close() if response.statusCode != http.StatusOK { return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) } if dstPath == "-" { // Send the response to STDOUT. _, err = io.Copy(os.Stdout, response.body) return err } // In order to get the copy behavior right, we need to know information // about both the source and the destination. The response headers include // stat info about the source that we can use in deciding exactly how to // copy it locally. Along with the stat info about the local destination, // we have everything we need to handle the multiple possibilities there // can be when copying a file/dir from one location to another file/dir. stat, err := getContainerPathStatFromHeader(response.header) if err != nil { return fmt.Errorf("unable to get resource stat from response: %s", err) } // Prepare source copy info. srcInfo := archive.CopyInfo{ Path: srcPath, Exists: true, IsDir: stat.Mode.IsDir(), } // 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(response.body, srcInfo, dstPath) } func (cli *DockerCli) copyToContainer(srcPath, dstContainer, dstPath string) (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 := cli.statContainerPath(dstContainer, dstPath) // 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 versia) 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 if srcPath == "-" { // Use STDIN. content = os.Stdin if !dstInfo.IsDir { return fmt.Errorf("destination %q must be a directory", fmt.Sprintf("%s:%s", dstContainer, dstPath)) } } else { srcArchive, err := archive.TarResource(srcPath) 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 disired // copy behavior. // Prepare source copy info. srcInfo, err := archive.CopyInfoStatPath(srcPath, true) if err != nil { return err } // 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() dstPath = dstDir content = preparedArchive } query := make(url.Values, 2) query.Set("path", filepath.ToSlash(dstPath)) // Normalize the paths used in the API. // Do not allow for an existing directory to be overwritten by a non-directory and vice versa. query.Set("noOverwriteDirNonDir", "true") urlStr := fmt.Sprintf("/containers/%s/archive?%s", dstContainer, query.Encode()) response, err := cli.stream("PUT", urlStr, &streamOpts{in: content}) if err != nil { return err } defer response.body.Close() if response.statusCode != http.StatusOK { return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/create.go ================================================ package client import ( "encoding/base64" "encoding/json" "fmt" "io" "net/url" "os" "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/graph/tags" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) func (cli *DockerCli) pullImage(image string) error { return cli.pullImageCustomOut(image, cli.out) } func (cli *DockerCli) pullImageCustomOut(image string, out io.Writer) error { v := url.Values{} repos, tag := parsers.ParseRepositoryTag(image) // pull only the image tagged 'latest' if no tag was specified if tag == "" { tag = tags.DEFAULTTAG } v.Set("fromImage", repos) v.Set("tag", tag) // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := registry.ParseRepositoryInfo(repos) if err != nil { return err } // Resolve the Auth config relevant for this server authConfig := registry.ResolveAuthConfig(cli.configFile, repoInfo.Index) buf, err := json.Marshal(authConfig) if err != nil { return err } registryAuthHeader := []string{ base64.URLEncoding.EncodeToString(buf), } sopts := &streamOpts{ rawTerminal: true, out: out, headers: map[string][]string{"X-Registry-Auth": registryAuthHeader}, } if _, err := cli.stream("POST", "/images/create?"+v.Encode(), sopts); err != nil { return err } return nil } type cidFile struct { path string file *os.File written bool } func newCIDFile(path string) (*cidFile, error) { if _, err := os.Stat(path); err == nil { return nil, fmt.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, fmt.Errorf("Failed to create the container ID file: %s", err) } return &cidFile{path: path, file: f}, nil } func (cli *DockerCli) createContainer(config *runconfig.Config, hostConfig *runconfig.HostConfig, cidfile, name string) (*types.ContainerCreateResponse, error) { containerValues := url.Values{} if name != "" { containerValues.Set("name", name) } mergedConfig := runconfig.MergeConfigs(config, hostConfig) var containerIDFile *cidFile if cidfile != "" { var err error if containerIDFile, err = newCIDFile(cidfile); err != nil { return nil, err } defer containerIDFile.Close() } //create the container serverResp, err := cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil) //if image not found try to pull it if serverResp.statusCode == 404 && strings.Contains(err.Error(), config.Image) { repo, tag := parsers.ParseRepositoryTag(config.Image) if tag == "" { tag = tags.DEFAULTTAG } fmt.Fprintf(cli.err, "Unable to find image '%s' locally\n", utils.ImageReference(repo, tag)) // we don't want to write to stdout anything apart from container.ID if err = cli.pullImageCustomOut(config.Image, cli.err); err != nil { return nil, err } // Retry if serverResp, err = cli.call("POST", "/containers/create?"+containerValues.Encode(), mergedConfig, nil); err != nil { return nil, err } } else if err != nil { return nil, err } defer serverResp.body.Close() var response types.ContainerCreateResponse if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { return nil, err } for _, warning := range response.Warnings { fmt.Fprintf(cli.err, "WARNING: %s\n", warning) } if containerIDFile != nil { if err = containerIDFile.Write(response.ID); err != nil { return nil, err } } return &response, nil } // CmdCreate creates a new container from a given image. // // Usage: docker create [OPTIONS] IMAGE [COMMAND] [ARG...] func (cli *DockerCli) CmdCreate(args ...string) error { cmd := cli.Subcmd("create", []string{"IMAGE [COMMAND] [ARG...]"}, "Create a new container", true) // These are flags not stored in Config/HostConfig var ( flName = cmd.String([]string{"-name"}, "", "Assign a name to the container") ) config, hostConfig, cmd, err := runconfig.Parse(cmd, args) if err != nil { cmd.ReportError(err.Error(), true) os.Exit(1) } if config.Image == "" { cmd.Usage() return nil } response, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName) if err != nil { return err } fmt.Fprintf(cli.out, "%s\n", response.ID) return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/diff.go ================================================ package client import ( "encoding/json" "fmt" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/archive" flag "github.com/docker/docker/pkg/mflag" ) // CmdDiff shows changes on a container's filesystem. // // Each changed file is printed on a separate line, prefixed with a single // character that indicates the status of the file: C (modified), A (added), // or D (deleted). // // Usage: docker diff CONTAINER func (cli *DockerCli) CmdDiff(args ...string) error { cmd := cli.Subcmd("diff", []string{"CONTAINER"}, "Inspect changes on a container's filesystem", true) cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) if cmd.Arg(0) == "" { return fmt.Errorf("Container name cannot be empty") } serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/changes", nil, nil) if err != nil { return err } defer serverResp.body.Close() changes := []types.ContainerChange{} if err := json.NewDecoder(serverResp.body).Decode(&changes); err != nil { return err } for _, change := range changes { var kind string switch change.Kind { case archive.ChangeModify: kind = "C" case archive.ChangeAdd: kind = "A" case archive.ChangeDelete: kind = "D" } fmt.Fprintf(cli.out, "%s %s\n", kind, change.Path) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/events.go ================================================ package client import ( "net/url" "time" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/pkg/timeutils" ) // CmdEvents prints a live stream of real time events from the server. // // Usage: docker events [OPTIONS] func (cli *DockerCli) CmdEvents(args ...string) error { cmd := cli.Subcmd("events", nil, "Get real time events from the server", true) since := cmd.String([]string{"#since", "-since"}, "", "Show all events created since timestamp") until := cmd.String([]string{"-until"}, "", "Stream events until this timestamp") flFilter := opts.NewListOpts(nil) cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") cmd.Require(flag.Exact, 0) cmd.ParseFlags(args, true) var ( v = url.Values{} eventFilterArgs = filters.Args{} ) // Consolidate all filter flags, and sanity check them early. // They'll get process in the daemon/server. for _, f := range flFilter.GetAll() { var err error eventFilterArgs, err = filters.ParseFlag(f, eventFilterArgs) if err != nil { return err } } ref := time.Now() if *since != "" { v.Set("since", timeutils.GetTimestamp(*since, ref)) } if *until != "" { v.Set("until", timeutils.GetTimestamp(*until, ref)) } if len(eventFilterArgs) > 0 { filterJSON, err := filters.ToParam(eventFilterArgs) if err != nil { return err } v.Set("filters", filterJSON) } sopts := &streamOpts{ rawTerminal: true, out: cli.out, } if _, err := cli.stream("GET", "/events?"+v.Encode(), sopts); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/exec.go ================================================ package client import ( "encoding/json" "fmt" "io" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/runconfig" ) // CmdExec runs a command in a running container. // // Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...] func (cli *DockerCli) CmdExec(args ...string) error { cmd := cli.Subcmd("exec", []string{"CONTAINER COMMAND [ARG...]"}, "Run a command in a running container", true) execConfig, err := runconfig.ParseExec(cmd, args) // just in case the ParseExec does not exit if execConfig.Container == "" || err != nil { return StatusError{StatusCode: 1} } serverResp, err := cli.call("POST", "/containers/"+execConfig.Container+"/exec", execConfig, nil) if err != nil { return err } defer serverResp.body.Close() var response types.ContainerExecCreateResponse if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { return err } execID := response.ID if execID == "" { fmt.Fprintf(cli.out, "exec ID empty") return nil } //Temp struct for execStart so that we don't need to transfer all the execConfig execStartCheck := &types.ExecStartCheck{ Detach: execConfig.Detach, Tty: execConfig.Tty, } if !execConfig.Detach { if err := cli.CheckTtyInput(execConfig.AttachStdin, execConfig.Tty); err != nil { return err } } else { if _, _, err := readBody(cli.call("POST", "/exec/"+execID+"/start", execStartCheck, nil)); err != nil { return err } // For now don't print this - wait for when we support exec wait() // fmt.Fprintf(cli.out, "%s\n", execID) return nil } // Interactive exec requested. var ( out, stderr io.Writer in io.ReadCloser hijacked = make(chan io.Closer) errCh chan error ) // Block the return until the chan gets closed defer func() { logrus.Debugf("End of CmdExec(), Waiting for hijack to finish.") if _, ok := <-hijacked; ok { fmt.Fprintln(cli.err, "Hijack did not finish (chan still open)") } }() if execConfig.AttachStdin { in = cli.in } if execConfig.AttachStdout { out = cli.out } if execConfig.AttachStderr { if execConfig.Tty { stderr = cli.out } else { stderr = cli.err } } errCh = promise.Go(func() error { return cli.hijack("POST", "/exec/"+execID+"/start", execConfig.Tty, in, out, stderr, hijacked, execConfig) }) // Acknowledge the hijack before starting select { case closer := <-hijacked: // Make sure that hijack gets closed when returning. (result // in closing hijack chan and freeing server's goroutines. if closer != nil { defer closer.Close() } case err := <-errCh: if err != nil { logrus.Debugf("Error hijack: %s", err) return err } } if execConfig.Tty && cli.isTerminalIn { if err := cli.monitorTtySize(execID, true); err != nil { fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err) } } if err := <-errCh; err != nil { logrus.Debugf("Error hijack: %s", err) return err } var status int if _, status, err = getExecExitCode(cli, execID); err != nil { return err } if status != 0 { return StatusError{StatusCode: status} } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/export.go ================================================ package client import ( "errors" "io" "os" flag "github.com/docker/docker/pkg/mflag" ) // CmdExport exports a filesystem as a tar archive. // // The tar archive is streamed to STDOUT by default or written to a file. // // Usage: docker export [OPTIONS] CONTAINER func (cli *DockerCli) CmdExport(args ...string) error { cmd := cli.Subcmd("export", []string{"CONTAINER"}, "Export the contents of a container's filesystem as a tar archive", true) outfile := cmd.String([]string{"o", "-output"}, "", "Write to a file, instead of STDOUT") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) var ( output io.Writer = cli.out err error ) if *outfile != "" { output, err = os.Create(*outfile) if err != nil { return err } } else if cli.isTerminalOut { return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.") } image := cmd.Arg(0) sopts := &streamOpts{ rawTerminal: true, out: output, } if _, err := cli.stream("GET", "/containers/"+image+"/export", sopts); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/help.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) // CmdHelp displays information on a Docker command. // // If more than one command is specified, information is only shown for the first command. // // Usage: docker help COMMAND or docker COMMAND --help func (cli *DockerCli) CmdHelp(args ...string) error { if len(args) > 1 { method, exists := cli.getMethod(args[:2]...) if exists { method("--help") return nil } } if len(args) > 0 { method, exists := cli.getMethod(args[0]) if !exists { return fmt.Errorf("docker: '%s' is not a docker command. See 'docker --help'.", args[0]) } method("--help") return nil } flag.Usage() return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/hijack.go ================================================ package client import ( "crypto/tls" "errors" "fmt" "io" "net" "net/http" "net/http/httputil" "os" "runtime" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/api" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/term" ) type tlsClientCon struct { *tls.Conn rawConn net.Conn } func (c *tlsClientCon) CloseWrite() error { // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it // on its underlying connection. if cwc, ok := c.rawConn.(interface { CloseWrite() error }); ok { return cwc.CloseWrite() } return nil } func tlsDial(network, addr string, config *tls.Config) (net.Conn, error) { return tlsDialWithDialer(new(net.Dialer), network, addr, config) } // We need to copy Go's implementation of tls.Dial (pkg/cryptor/tls/tls.go) in // order to return our custom tlsClientCon struct which holds both the tls.Conn // object _and_ its underlying raw connection. The rationale for this is that // we need to be able to close the write end of the connection when attaching, // which tls.Conn does not provide. func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { // We want the Timeout and Deadline values from dialer to cover the // whole process: TCP connection and TLS handshake. This means that we // also need to start our own timers now. timeout := dialer.Timeout if !dialer.Deadline.IsZero() { deadlineTimeout := dialer.Deadline.Sub(time.Now()) if timeout == 0 || deadlineTimeout < timeout { timeout = deadlineTimeout } } var errChannel chan error if timeout != 0 { errChannel = make(chan error, 2) time.AfterFunc(timeout, func() { errChannel <- errors.New("") }) } rawConn, err := dialer.Dial(network, addr) if err != nil { return nil, err } // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain // network setups may cause ECONNTIMEOUT, leaving the client in an unknown // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := rawConn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(30 * time.Second) } colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } hostname := addr[:colonPos] // If no ServerName is set, infer the ServerName // from the hostname we're connecting to. if config.ServerName == "" { // Make a copy to avoid polluting argument or default. c := *config c.ServerName = hostname config = &c } conn := tls.Client(rawConn, config) if timeout == 0 { err = conn.Handshake() } else { go func() { errChannel <- conn.Handshake() }() err = <-errChannel } if err != nil { rawConn.Close() return nil, err } // This is Docker difference with standard's crypto/tls package: returned a // wrapper which holds both the TLS and raw connections. return &tlsClientCon{conn, rawConn}, nil } func (cli *DockerCli) dial() (net.Conn, error) { if cli.tlsConfig != nil && cli.proto != "unix" { // Notice this isn't Go standard's tls.Dial function return tlsDial(cli.proto, cli.addr, cli.tlsConfig) } return net.Dial(cli.proto, cli.addr) } func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.ReadCloser, stdout, stderr io.Writer, started chan io.Closer, data interface{}) error { defer func() { if started != nil { close(started) } }() params, err := cli.encodeData(data) if err != nil { return err } req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), params) if err != nil { return err } // Add CLI Config's HTTP Headers BEFORE we set the Docker headers // then the user can't change OUR headers for k, v := range cli.configFile.HTTPHeaders { req.Header.Set(k, v) } req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")") req.Header.Set("Content-Type", "text/plain") req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", "tcp") req.Host = cli.addr dial, err := cli.dial() // When we set up a TCP connection for hijack, there could be long periods // of inactivity (a long running command with no output) that in certain // network setups may cause ECONNTIMEOUT, leaving the client in an unknown // state. Setting TCP KeepAlive on the socket connection will prohibit // ECONNTIMEOUT unless the socket connection truly is broken if tcpConn, ok := dial.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(30 * time.Second) } if err != nil { if strings.Contains(err.Error(), "connection refused") { return fmt.Errorf("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?") } return err } clientconn := httputil.NewClientConn(dial, nil) defer clientconn.Close() // Server hijacks the connection, error 'connection closed' expected clientconn.Do(req) rwc, br := clientconn.Hijack() defer rwc.Close() if started != nil { started <- rwc } var receiveStdout chan error var oldState *term.State if in != nil && setRawTerminal && cli.isTerminalIn && os.Getenv("NORAW") == "" { oldState, err = term.SetRawTerminal(cli.inFd) if err != nil { return err } defer term.RestoreTerminal(cli.inFd, oldState) } if stdout != nil || stderr != nil { receiveStdout = promise.Go(func() (err error) { defer func() { if in != nil { if setRawTerminal && cli.isTerminalIn { term.RestoreTerminal(cli.inFd, oldState) } // For some reason this Close call blocks on darwin.. // As the client exists right after, simply discard the close // until we find a better solution. if runtime.GOOS != "darwin" { in.Close() } } }() // When TTY is ON, use regular copy if setRawTerminal && stdout != nil { _, err = io.Copy(stdout, br) } else { _, err = stdcopy.StdCopy(stdout, stderr, br) } logrus.Debugf("[hijack] End of stdout") return err }) } sendStdin := promise.Go(func() error { if in != nil { io.Copy(rwc, in) logrus.Debugf("[hijack] End of stdin") } if conn, ok := rwc.(interface { CloseWrite() error }); ok { if err := conn.CloseWrite(); err != nil { logrus.Debugf("Couldn't send EOF: %s", err) } } // Discard errors due to pipe interruption return nil }) if stdout != nil || stderr != nil { if err := <-receiveStdout; err != nil { logrus.Debugf("Error receiveStdout: %s", err) return err } } if !cli.isTerminalIn { if err := <-sendStdin; err != nil { logrus.Debugf("Error sendStdin: %s", err) return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/history.go ================================================ package client import ( "encoding/json" "fmt" "text/tabwriter" "time" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/pkg/units" ) // CmdHistory shows the history of an image. // // Usage: docker history [OPTIONS] IMAGE func (cli *DockerCli) CmdHistory(args ...string) error { cmd := cli.Subcmd("history", []string{"IMAGE"}, "Show the history of an image", true) human := cmd.Bool([]string{"H", "-human"}, true, "Print sizes and dates in human readable format") quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs") noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) serverResp, err := cli.call("GET", "/images/"+cmd.Arg(0)+"/history", nil, nil) if err != nil { return err } defer serverResp.body.Close() history := []types.ImageHistory{} if err := json.NewDecoder(serverResp.body).Decode(&history); err != nil { return err } w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) if !*quiet { fmt.Fprintln(w, "IMAGE\tCREATED\tCREATED BY\tSIZE\tCOMMENT") } for _, entry := range history { if *noTrunc { fmt.Fprintf(w, entry.ID) } else { fmt.Fprintf(w, stringid.TruncateID(entry.ID)) } if !*quiet { if *human { fmt.Fprintf(w, "\t%s ago\t", units.HumanDuration(time.Now().UTC().Sub(time.Unix(entry.Created, 0)))) } else { fmt.Fprintf(w, "\t%s\t", time.Unix(entry.Created, 0).Format(time.RFC3339)) } if *noTrunc { fmt.Fprintf(w, "%s\t", entry.CreatedBy) } else { fmt.Fprintf(w, "%s\t", stringutils.Truncate(entry.CreatedBy, 45)) } if *human { fmt.Fprintf(w, "%s\t", units.HumanSize(float64(entry.Size))) } else { fmt.Fprintf(w, "%d\t", entry.Size) } fmt.Fprintf(w, "%s", entry.Comment) } fmt.Fprintf(w, "\n") } w.Flush() return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/images.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "text/tabwriter" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/units" "github.com/docker/docker/utils" ) // CmdImages lists the images in a specified repository, or all top-level images if no repository is specified. // // Usage: docker images [OPTIONS] [REPOSITORY] func (cli *DockerCli) CmdImages(args ...string) error { cmd := cli.Subcmd("images", []string{"[REPOSITORY]"}, "List images", true) quiet := cmd.Bool([]string{"q", "-quiet"}, false, "Only show numeric IDs") all := cmd.Bool([]string{"a", "-all"}, false, "Show all images (default hides intermediate images)") noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") showDigests := cmd.Bool([]string{"-digests"}, false, "Show digests") flFilter := opts.NewListOpts(nil) cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") cmd.Require(flag.Max, 1) cmd.ParseFlags(args, true) // Consolidate all filter flags, and sanity check them early. // They'll get process in the daemon/server. imageFilterArgs := filters.Args{} for _, f := range flFilter.GetAll() { var err error imageFilterArgs, err = filters.ParseFlag(f, imageFilterArgs) if err != nil { return err } } matchName := cmd.Arg(0) v := url.Values{} if len(imageFilterArgs) > 0 { filterJSON, err := filters.ToParam(imageFilterArgs) if err != nil { return err } v.Set("filters", filterJSON) } if cmd.NArg() == 1 { // FIXME rename this parameter, to not be confused with the filters flag v.Set("filter", matchName) } if *all { v.Set("all", "1") } serverResp, err := cli.call("GET", "/images/json?"+v.Encode(), nil, nil) if err != nil { return err } defer serverResp.body.Close() images := []types.Image{} if err := json.NewDecoder(serverResp.body).Decode(&images); err != nil { return err } w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) if !*quiet { if *showDigests { fmt.Fprintln(w, "REPOSITORY\tTAG\tDIGEST\tIMAGE ID\tCREATED\tVIRTUAL SIZE") } else { fmt.Fprintln(w, "REPOSITORY\tTAG\tIMAGE ID\tCREATED\tVIRTUAL SIZE") } } for _, image := range images { ID := image.ID if !*noTrunc { ID = stringid.TruncateID(ID) } repoTags := image.RepoTags repoDigests := image.RepoDigests if len(repoTags) == 1 && repoTags[0] == ":" && len(repoDigests) == 1 && repoDigests[0] == "@" { // dangling image - clear out either repoTags or repoDigsts so we only show it once below repoDigests = []string{} } // combine the tags and digests lists tagsAndDigests := append(repoTags, repoDigests...) for _, repoAndRef := range tagsAndDigests { repo, ref := parsers.ParseRepositoryTag(repoAndRef) // default tag and digest to none - if there's a value, it'll be set below tag := "" digest := "" if utils.DigestReference(ref) { digest = ref } else { tag = ref } if !*quiet { if *showDigests { fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s ago\t%s\n", repo, tag, digest, ID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(int64(image.Created), 0))), units.HumanSize(float64(image.VirtualSize))) } else { fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\n", repo, tag, ID, units.HumanDuration(time.Now().UTC().Sub(time.Unix(int64(image.Created), 0))), units.HumanSize(float64(image.VirtualSize))) } } else { fmt.Fprintln(w, ID) } } } if !*quiet { w.Flush() } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/import.go ================================================ package client import ( "fmt" "io" "net/url" "os" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/urlutil" "github.com/docker/docker/registry" ) // CmdImport creates an empty filesystem image, imports the contents of the tarball into the image, and optionally tags the image. // // The URL argument is the address of a tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) file or a path to local file relative to docker client. If the URL is '-', then the tar file is read from STDIN. // // Usage: docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]] func (cli *DockerCli) CmdImport(args ...string) error { cmd := cli.Subcmd("import", []string{"file|URL|- [REPOSITORY[:TAG]]"}, "Create an empty filesystem image and import the contents of the\ntarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) into it, then\noptionally tag it.", true) flChanges := opts.NewListOpts(nil) cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var ( v = url.Values{} src = cmd.Arg(0) repository = cmd.Arg(1) ) v.Set("fromSrc", src) v.Set("repo", repository) for _, change := range flChanges.GetAll() { v.Add("changes", change) } if cmd.NArg() == 3 { fmt.Fprintf(cli.err, "[DEPRECATED] The format 'file|URL|- [REPOSITORY [TAG]]' has been deprecated. Please use file|URL|- [REPOSITORY[:TAG]]\n") v.Set("tag", cmd.Arg(2)) } if repository != "" { //Check if the given image name can be resolved repo, _ := parsers.ParseRepositoryTag(repository) if err := registry.ValidateRepositoryName(repo); err != nil { return err } } var in io.Reader if src == "-" { in = cli.in } else if !urlutil.IsURL(src) { v.Set("fromSrc", "-") file, err := os.Open(src) if err != nil { return err } defer file.Close() in = file } sopts := &streamOpts{ rawTerminal: true, in: in, out: cli.out, } _, err := cli.stream("POST", "/images/create?"+v.Encode(), sopts) return err } ================================================ FILE: vendor/github.com/docker/docker/api/client/info.go ================================================ package client import ( "encoding/json" "fmt" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/httputils" "github.com/docker/docker/pkg/ioutils" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/units" ) // CmdInfo displays system-wide information. // // Usage: docker info func (cli *DockerCli) CmdInfo(args ...string) error { cmd := cli.Subcmd("info", nil, "Display system-wide information", true) cmd.Require(flag.Exact, 0) cmd.ParseFlags(args, true) serverResp, err := cli.call("GET", "/info", nil, nil) if err != nil { return err } defer serverResp.body.Close() info := &types.Info{} if err := json.NewDecoder(serverResp.body).Decode(info); err != nil { return fmt.Errorf("Error reading remote info: %v", err) } fmt.Fprintf(cli.out, "Containers: %d\n", info.Containers) fmt.Fprintf(cli.out, "Images: %d\n", info.Images) ioutils.FprintfIfNotEmpty(cli.out, "Storage Driver: %s\n", info.Driver) if info.DriverStatus != nil { for _, pair := range info.DriverStatus { fmt.Fprintf(cli.out, " %s: %s\n", pair[0], pair[1]) } } ioutils.FprintfIfNotEmpty(cli.out, "Execution Driver: %s\n", info.ExecutionDriver) ioutils.FprintfIfNotEmpty(cli.out, "Logging Driver: %s\n", info.LoggingDriver) ioutils.FprintfIfNotEmpty(cli.out, "Kernel Version: %s\n", info.KernelVersion) ioutils.FprintfIfNotEmpty(cli.out, "Operating System: %s\n", info.OperatingSystem) fmt.Fprintf(cli.out, "CPUs: %d\n", info.NCPU) fmt.Fprintf(cli.out, "Total Memory: %s\n", units.BytesSize(float64(info.MemTotal))) ioutils.FprintfIfNotEmpty(cli.out, "Name: %s\n", info.Name) ioutils.FprintfIfNotEmpty(cli.out, "ID: %s\n", info.ID) if info.Debug { fmt.Fprintf(cli.out, "Debug mode (server): %v\n", info.Debug) fmt.Fprintf(cli.out, "File Descriptors: %d\n", info.NFd) fmt.Fprintf(cli.out, "Goroutines: %d\n", info.NGoroutines) fmt.Fprintf(cli.out, "System Time: %s\n", info.SystemTime) fmt.Fprintf(cli.out, "EventsListeners: %d\n", info.NEventsListener) fmt.Fprintf(cli.out, "Init SHA1: %s\n", info.InitSha1) fmt.Fprintf(cli.out, "Init Path: %s\n", info.InitPath) fmt.Fprintf(cli.out, "Docker Root Dir: %s\n", info.DockerRootDir) } ioutils.FprintfIfNotEmpty(cli.out, "Http Proxy: %s\n", info.HttpProxy) ioutils.FprintfIfNotEmpty(cli.out, "Https Proxy: %s\n", info.HttpsProxy) ioutils.FprintfIfNotEmpty(cli.out, "No Proxy: %s\n", info.NoProxy) if info.IndexServerAddress != "" { u := cli.configFile.AuthConfigs[info.IndexServerAddress].Username if len(u) > 0 { fmt.Fprintf(cli.out, "Username: %v\n", u) fmt.Fprintf(cli.out, "Registry: %v\n", info.IndexServerAddress) } } // Only output these warnings if the server supports these features if h, err := httputils.ParseServerHeader(serverResp.header.Get("Server")); err == nil { if h.OS != "windows" { if !info.MemoryLimit { fmt.Fprintf(cli.err, "WARNING: No memory limit support\n") } if !info.SwapLimit { fmt.Fprintf(cli.err, "WARNING: No swap limit support\n") } if !info.IPv4Forwarding { fmt.Fprintf(cli.err, "WARNING: IPv4 forwarding is disabled.\n") } if !info.BridgeNfIptables { fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-iptables is disabled\n") } if !info.BridgeNfIp6tables { fmt.Fprintf(cli.err, "WARNING: bridge-nf-call-ip6tables is disabled\n") } } } if info.Labels != nil { fmt.Fprintln(cli.out, "Labels:") for _, attribute := range info.Labels { fmt.Fprintf(cli.out, " %s\n", attribute) } } if info.ExperimentalBuild { fmt.Fprintf(cli.out, "Experimental: true\n") } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/inspect.go ================================================ package client import ( "bytes" "encoding/json" "fmt" "io" "strings" "text/template" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" ) // CmdInspect displays low-level information on one or more containers or images. // // Usage: docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...] func (cli *DockerCli) CmdInspect(args ...string) error { cmd := cli.Subcmd("inspect", []string{"CONTAINER|IMAGE [CONTAINER|IMAGE...]"}, "Return low-level information on a container or image", true) tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template") inspectType := cmd.String([]string{"-type"}, "", "Return JSON for specified type, (e.g image or container)") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var tmpl *template.Template var err error var obj []byte if *tmplStr != "" { if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil { return StatusError{StatusCode: 64, Status: "Template parsing error: " + err.Error()} } } if *inspectType != "" && *inspectType != "container" && *inspectType != "image" { return fmt.Errorf("%q is not a valid value for --type", *inspectType) } indented := new(bytes.Buffer) indented.WriteString("[\n") status := 0 isImage := false for _, name := range cmd.Args() { if *inspectType == "" || *inspectType == "container" { obj, _, err = readBody(cli.call("GET", "/containers/"+name+"/json", nil, nil)) if err != nil && *inspectType == "container" { if strings.Contains(err.Error(), "No such") { fmt.Fprintf(cli.err, "Error: No such container: %s\n", name) } else { fmt.Fprintf(cli.err, "%s", err) } status = 1 continue } } if obj == nil && (*inspectType == "" || *inspectType == "image") { obj, _, err = readBody(cli.call("GET", "/images/"+name+"/json", nil, nil)) isImage = true if err != nil { if strings.Contains(err.Error(), "No such") { if *inspectType == "" { fmt.Fprintf(cli.err, "Error: No such image or container: %s\n", name) } else { fmt.Fprintf(cli.err, "Error: No such image: %s\n", name) } } else { fmt.Fprintf(cli.err, "%s", err) } status = 1 continue } } if tmpl == nil { if err := json.Indent(indented, obj, "", " "); err != nil { fmt.Fprintf(cli.err, "%s\n", err) status = 1 continue } } else { rdr := bytes.NewReader(obj) dec := json.NewDecoder(rdr) if isImage { inspPtr := types.ImageInspect{} if err := dec.Decode(&inspPtr); err != nil { fmt.Fprintf(cli.err, "%s\n", err) status = 1 continue } if err := tmpl.Execute(cli.out, inspPtr); err != nil { rdr.Seek(0, 0) var raw interface{} if err := dec.Decode(&raw); err != nil { return err } if err = tmpl.Execute(cli.out, raw); err != nil { return err } } } else { inspPtr := types.ContainerJSON{} if err := dec.Decode(&inspPtr); err != nil { fmt.Fprintf(cli.err, "%s\n", err) status = 1 continue } if err := tmpl.Execute(cli.out, inspPtr); err != nil { rdr.Seek(0, 0) var raw interface{} if err := dec.Decode(&raw); err != nil { return err } if err = tmpl.Execute(cli.out, raw); err != nil { return err } } } cli.out.Write([]byte{'\n'}) } indented.WriteString(",") } if indented.Len() > 1 { // Remove trailing ',' indented.Truncate(indented.Len() - 1) } indented.WriteString("]\n") if tmpl == nil { // Note that we will always write "[]" when "-f" isn't specified, // to make sure the output would always be array, see // https://github.com/docker/docker/pull/9500#issuecomment-65846734 if _, err := io.Copy(cli.out, indented); err != nil { return err } } if status != 0 { return StatusError{StatusCode: status} } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/kill.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) // CmdKill kills one or more running container using SIGKILL or a specified signal. // // Usage: docker kill [OPTIONS] CONTAINER [CONTAINER...] func (cli *DockerCli) CmdKill(args ...string) error { cmd := cli.Subcmd("kill", []string{"CONTAINER [CONTAINER...]"}, "Kill a running container using SIGKILL or a specified signal", true) signal := cmd.String([]string{"s", "-signal"}, "KILL", "Signal to send to the container") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var errNames []string for _, name := range cmd.Args() { if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", name, *signal), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to kill containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/load.go ================================================ package client import ( "io" "os" flag "github.com/docker/docker/pkg/mflag" ) // CmdLoad loads an image from a tar archive. // // The tar archive is read from STDIN by default, or from a tar archive file. // // Usage: docker load [OPTIONS] func (cli *DockerCli) CmdLoad(args ...string) error { cmd := cli.Subcmd("load", nil, "Load an image from a tar archive or STDIN", true) infile := cmd.String([]string{"i", "-input"}, "", "Read from a tar archive file, instead of STDIN") cmd.Require(flag.Exact, 0) cmd.ParseFlags(args, true) var ( input io.Reader = cli.in err error ) if *infile != "" { input, err = os.Open(*infile) if err != nil { return err } } sopts := &streamOpts{ rawTerminal: true, in: input, out: cli.out, } if _, err := cli.stream("POST", "/images/load", sopts); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/login.go ================================================ package client import ( "bufio" "encoding/json" "fmt" "io" "os" "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/cliconfig" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/term" "github.com/docker/docker/registry" ) // CmdLogin logs in or registers a user to a Docker registry service. // // If no server is specified, the user will be logged into or registered to the registry's index server. // // Usage: docker login SERVER func (cli *DockerCli) CmdLogin(args ...string) error { cmd := cli.Subcmd("login", []string{"[SERVER]"}, "Register or log in to a Docker registry server, if no server is\nspecified \""+registry.INDEXSERVER+"\" is the default.", true) cmd.Require(flag.Max, 1) var username, password, email string cmd.StringVar(&username, []string{"u", "-username"}, "", "Username") cmd.StringVar(&password, []string{"p", "-password"}, "", "Password") cmd.StringVar(&email, []string{"e", "-email"}, "", "Email") cmd.ParseFlags(args, true) serverAddress := registry.INDEXSERVER if len(cmd.Args()) > 0 { serverAddress = cmd.Arg(0) } promptDefault := func(prompt string, configDefault string) { if configDefault == "" { fmt.Fprintf(cli.out, "%s: ", prompt) } else { fmt.Fprintf(cli.out, "%s (%s): ", prompt, configDefault) } } readInput := func(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) } authconfig, ok := cli.configFile.AuthConfigs[serverAddress] if !ok { authconfig = cliconfig.AuthConfig{} } if username == "" { promptDefault("Username", authconfig.Username) username = readInput(cli.in, cli.out) username = strings.Trim(username, " ") if username == "" { username = authconfig.Username } } // Assume that a different username means they may not want to use // the password or email from the config file, so prompt them if username != authconfig.Username { if password == "" { oldState, err := term.SaveState(cli.inFd) if err != nil { return err } fmt.Fprintf(cli.out, "Password: ") term.DisableEcho(cli.inFd, oldState) password = readInput(cli.in, cli.out) fmt.Fprint(cli.out, "\n") term.RestoreTerminal(cli.inFd, oldState) if password == "" { return fmt.Errorf("Error : Password Required") } } if email == "" { promptDefault("Email", authconfig.Email) email = readInput(cli.in, cli.out) if email == "" { email = authconfig.Email } } } else { // However, if they don't override the username use the // password or email from the cmd line if specified. IOW, allow // then to change/override them. And if not specified, just // use what's in the config file if password == "" { password = authconfig.Password } if email == "" { email = authconfig.Email } } authconfig.Username = username authconfig.Password = password authconfig.Email = email authconfig.ServerAddress = serverAddress cli.configFile.AuthConfigs[serverAddress] = authconfig serverResp, err := cli.call("POST", "/auth", cli.configFile.AuthConfigs[serverAddress], nil) if serverResp.statusCode == 401 { delete(cli.configFile.AuthConfigs, serverAddress) if err2 := cli.configFile.Save(); err2 != nil { fmt.Fprintf(cli.out, "WARNING: could not save config file: %v\n", err2) } return err } if err != nil { return err } defer serverResp.body.Close() var response types.AuthResponse if err := json.NewDecoder(serverResp.body).Decode(&response); err != nil { // Upon error, remove entry delete(cli.configFile.AuthConfigs, serverAddress) return err } if err := cli.configFile.Save(); err != nil { return fmt.Errorf("Error saving config file: %v", err) } fmt.Fprintf(cli.out, "WARNING: login credentials saved in %s\n", cli.configFile.Filename()) if response.Status != "" { fmt.Fprintf(cli.out, "%s\n", response.Status) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/logout.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/registry" ) // CmdLogout logs a user out from a Docker registry. // // If no server is specified, the user will be logged out from the registry's index server. // // Usage: docker logout [SERVER] func (cli *DockerCli) CmdLogout(args ...string) error { cmd := cli.Subcmd("logout", []string{"[SERVER]"}, "Log out from a Docker registry, if no server is\nspecified \""+registry.INDEXSERVER+"\" is the default.", true) cmd.Require(flag.Max, 1) cmd.ParseFlags(args, true) serverAddress := registry.INDEXSERVER if len(cmd.Args()) > 0 { serverAddress = cmd.Arg(0) } if _, ok := cli.configFile.AuthConfigs[serverAddress]; !ok { fmt.Fprintf(cli.out, "Not logged in to %s\n", serverAddress) } else { fmt.Fprintf(cli.out, "Remove login credentials for %s\n", serverAddress) delete(cli.configFile.AuthConfigs, serverAddress) if err := cli.configFile.Save(); err != nil { return fmt.Errorf("Failed to save docker config: %v", err) } } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/logs.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "time" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/timeutils" ) // CmdLogs fetches the logs of a given container. // // docker logs [OPTIONS] CONTAINER func (cli *DockerCli) CmdLogs(args ...string) error { cmd := cli.Subcmd("logs", []string{"CONTAINER"}, "Fetch the logs of a container", true) follow := cmd.Bool([]string{"f", "-follow"}, false, "Follow log output") since := cmd.String([]string{"-since"}, "", "Show logs since timestamp") times := cmd.Bool([]string{"t", "-timestamps"}, false, "Show timestamps") tail := cmd.String([]string{"-tail"}, "latest", "Number of lines to show from the end of the logs") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) name := cmd.Arg(0) serverResp, err := cli.call("GET", "/containers/"+name+"/json", nil, nil) if err != nil { return err } var c types.ContainerJSON if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { return err } if logType := c.HostConfig.LogConfig.Type; logType != "json-file" { return fmt.Errorf("\"logs\" command is supported only for \"json-file\" logging driver (got: %s)", logType) } v := url.Values{} v.Set("stdout", "1") v.Set("stderr", "1") if *since != "" { v.Set("since", timeutils.GetTimestamp(*since, time.Now())) } if *times { v.Set("timestamps", "1") } if *follow { v.Set("follow", "1") } v.Set("tail", *tail) sopts := &streamOpts{ rawTerminal: c.Config.Tty, out: cli.out, err: cli.err, } _, err = cli.stream("GET", "/containers/"+name+"/logs?"+v.Encode(), sopts) return err } ================================================ FILE: vendor/github.com/docker/docker/api/client/network.go ================================================ // +build experimental package client import ( "os" nwclient "github.com/docker/libnetwork/client" ) func (cli *DockerCli) CmdNetwork(args ...string) error { nCli := nwclient.NewNetworkCli(cli.out, cli.err, nwclient.CallFunc(cli.callWrapper)) args = append([]string{"network"}, args...) return nCli.Cmd(os.Args[0], args...) } ================================================ FILE: vendor/github.com/docker/docker/api/client/pause.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) // CmdPause pauses all processes within one or more containers. // // Usage: docker pause CONTAINER [CONTAINER...] func (cli *DockerCli) CmdPause(args ...string) error { cmd := cli.Subcmd("pause", []string{"CONTAINER [CONTAINER...]"}, "Pause all processes within a container", true) cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var errNames []string for _, name := range cmd.Args() { if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/pause", name), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to pause containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/port.go ================================================ package client import ( "encoding/json" "fmt" "strings" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/nat" ) // CmdPort lists port mappings for a container. // If a private port is specified, it also shows the public-facing port that is NATed to the private port. // // Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]] func (cli *DockerCli) CmdPort(args ...string) error { cmd := cli.Subcmd("port", []string{"CONTAINER [PRIVATE_PORT[/PROTO]]"}, "List port mappings for the CONTAINER, or lookup the public-facing port that\nis NAT-ed to the PRIVATE_PORT", true) cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) if err != nil { return err } defer serverResp.body.Close() var c struct { NetworkSettings struct { Ports nat.PortMap } } if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { return err } if cmd.NArg() == 2 { var ( port = cmd.Arg(1) 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(cli.out, "%s:%s\n", frontend.HostIP, frontend.HostPort) } return nil } return fmt.Errorf("Error: No public port '%s' published for %s", natPort, cmd.Arg(0)) } for from, frontends := range c.NetworkSettings.Ports { for _, frontend := range frontends { fmt.Fprintf(cli.out, "%s -> %s:%s\n", from, frontend.HostIP, frontend.HostPort) } } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/ps.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "strconv" "strings" "text/tabwriter" "time" "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/pkg/units" ) // CmdPs outputs a list of Docker containers. // // Usage: docker ps [OPTIONS] func (cli *DockerCli) CmdPs(args ...string) error { var ( err error psFilterArgs = filters.Args{} v = url.Values{} cmd = cli.Subcmd("ps", nil, "List containers", true) quiet = cmd.Bool([]string{"q", "-quiet"}, false, "Only display numeric IDs") size = cmd.Bool([]string{"s", "-size"}, false, "Display total file sizes") all = cmd.Bool([]string{"a", "-all"}, false, "Show all containers (default shows just running)") noTrunc = cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") nLatest = cmd.Bool([]string{"l", "-latest"}, false, "Show the latest created container, include non-running") since = cmd.String([]string{"#sinceId", "#-since-id", "-since"}, "", "Show created since Id or Name, include non-running") before = cmd.String([]string{"#beforeId", "#-before-id", "-before"}, "", "Show only container created before Id or Name") last = cmd.Int([]string{"n"}, -1, "Show n last created containers, include non-running") flFilter = opts.NewListOpts(nil) ) cmd.Require(flag.Exact, 0) cmd.Var(&flFilter, []string{"f", "-filter"}, "Filter output based on conditions provided") cmd.ParseFlags(args, true) if *last == -1 && *nLatest { *last = 1 } if *all { v.Set("all", "1") } if *last != -1 { v.Set("limit", strconv.Itoa(*last)) } if *since != "" { v.Set("since", *since) } if *before != "" { v.Set("before", *before) } if *size { v.Set("size", "1") } // Consolidate all filter flags, and sanity check them. // They'll get processed in the daemon/server. for _, f := range flFilter.GetAll() { if psFilterArgs, err = filters.ParseFlag(f, psFilterArgs); err != nil { return err } } if len(psFilterArgs) > 0 { filterJSON, err := filters.ToParam(psFilterArgs) if err != nil { return err } v.Set("filters", filterJSON) } serverResp, err := cli.call("GET", "/containers/json?"+v.Encode(), nil, nil) if err != nil { return err } defer serverResp.body.Close() containers := []types.Container{} if err := json.NewDecoder(serverResp.body).Decode(&containers); err != nil { return err } w := tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) if !*quiet { fmt.Fprint(w, "CONTAINER ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tNAMES") if *size { fmt.Fprintln(w, "\tSIZE") } else { fmt.Fprint(w, "\n") } } stripNamePrefix := func(ss []string) []string { for i, s := range ss { ss[i] = s[1:] } return ss } for _, container := range containers { ID := container.ID if !*noTrunc { ID = stringid.TruncateID(ID) } if *quiet { fmt.Fprintln(w, ID) continue } var ( names = stripNamePrefix(container.Names) command = strconv.Quote(container.Command) displayPort string ) if !*noTrunc { command = stringutils.Truncate(command, 20) // only display the default name for the container with notrunc is passed for _, name := range names { if len(strings.Split(name, "/")) == 1 { names = []string{name} break } } } image := container.Image if image == "" { image = "" } if container.HostConfig.NetworkMode == "host" { displayPort = "*/tcp, */udp" } else { displayPort = api.DisplayablePorts(container.Ports) } fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t%s\t", ID, image, command, units.HumanDuration(time.Now().UTC().Sub(time.Unix(int64(container.Created), 0))), container.Status, displayPort, strings.Join(names, ",")) if *size { if container.SizeRootFs > 0 { fmt.Fprintf(w, "%s (virtual %s)\n", units.HumanSize(float64(container.SizeRw)), units.HumanSize(float64(container.SizeRootFs))) } else { fmt.Fprintf(w, "%s\n", units.HumanSize(float64(container.SizeRw))) } continue } fmt.Fprint(w, "\n") } if !*quiet { w.Flush() } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/pull.go ================================================ package client import ( "fmt" "net/url" "github.com/docker/docker/graph/tags" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) // CmdPull pulls an image or a repository from the registry. // // Usage: docker pull [OPTIONS] IMAGENAME[:TAG|@DIGEST] func (cli *DockerCli) CmdPull(args ...string) error { cmd := cli.Subcmd("pull", []string{"NAME[:TAG|@DIGEST]"}, "Pull an image or a repository from a registry", true) allTags := cmd.Bool([]string{"a", "-all-tags"}, false, "Download all tagged images in the repository") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) var ( v = url.Values{} remote = cmd.Arg(0) newRemote = remote ) taglessRemote, tag := parsers.ParseRepositoryTag(remote) if tag == "" && !*allTags { newRemote = utils.ImageReference(taglessRemote, tags.DEFAULTTAG) } if tag != "" && *allTags { return fmt.Errorf("tag can't be used with --all-tags/-a") } v.Set("fromImage", newRemote) // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := registry.ParseRepositoryInfo(taglessRemote) if err != nil { return err } _, _, err = cli.clientRequestAttemptLogin("POST", "/images/create?"+v.Encode(), nil, cli.out, repoInfo.Index, "pull") return err } ================================================ FILE: vendor/github.com/docker/docker/api/client/push.go ================================================ package client import ( "fmt" "net/url" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/registry" ) // CmdPush pushes an image or repository to the registry. // // Usage: docker push NAME[:TAG] func (cli *DockerCli) CmdPush(args ...string) error { cmd := cli.Subcmd("push", []string{"NAME[:TAG]"}, "Push an image or a repository to a registry", true) cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) remote, tag := parsers.ParseRepositoryTag(cmd.Arg(0)) // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := registry.ParseRepositoryInfo(remote) if err != nil { return err } // Resolve the Auth config relevant for this server authConfig := registry.ResolveAuthConfig(cli.configFile, repoInfo.Index) // If we're not using a custom registry, we know the restrictions // applied to repository names and can warn the user in advance. // Custom repositories can have different rules, and we must also // allow pushing by image ID. if repoInfo.Official { username := authConfig.Username if username == "" { username = "" } return fmt.Errorf("You cannot push a \"root\" repository. Please rename your repository to / (ex: %s/%s)", username, repoInfo.LocalName) } v := url.Values{} v.Set("tag", tag) _, _, err = cli.clientRequestAttemptLogin("POST", "/images/"+remote+"/push?"+v.Encode(), nil, cli.out, repoInfo.Index, "push") return err } ================================================ FILE: vendor/github.com/docker/docker/api/client/rename.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) // CmdRename renames a container. // // Usage: docker rename OLD_NAME NEW_NAME func (cli *DockerCli) CmdRename(args ...string) error { cmd := cli.Subcmd("rename", []string{"OLD_NAME NEW_NAME"}, "Rename a container", true) cmd.Require(flag.Exact, 2) cmd.ParseFlags(args, true) oldName := cmd.Arg(0) newName := cmd.Arg(1) if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/rename?name=%s", oldName, newName), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) return fmt.Errorf("Error: failed to rename container named %s", oldName) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/restart.go ================================================ package client import ( "fmt" "net/url" "strconv" flag "github.com/docker/docker/pkg/mflag" ) // CmdRestart restarts one or more running containers. // // Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...] func (cli *DockerCli) CmdRestart(args ...string) error { cmd := cli.Subcmd("restart", []string{"CONTAINER [CONTAINER...]"}, "Restart a running container", true) nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing the container") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) v := url.Values{} v.Set("t", strconv.Itoa(*nSeconds)) var errNames []string for _, name := range cmd.Args() { _, _, err := readBody(cli.call("POST", "/containers/"+name+"/restart?"+v.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to restart containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/rm.go ================================================ package client import ( "fmt" "net/url" "strings" flag "github.com/docker/docker/pkg/mflag" ) // CmdRm removes one or more containers. // // Usage: docker rm [OPTIONS] CONTAINER [CONTAINER...] func (cli *DockerCli) CmdRm(args ...string) error { cmd := cli.Subcmd("rm", []string{"CONTAINER [CONTAINER...]"}, "Remove one or more containers", true) v := cmd.Bool([]string{"v", "-volumes"}, false, "Remove the volumes associated with the container") link := cmd.Bool([]string{"l", "#link", "-link"}, false, "Remove the specified link") force := cmd.Bool([]string{"f", "-force"}, false, "Force the removal of a running container (uses SIGKILL)") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) val := url.Values{} if *v { val.Set("v", "1") } if *link { val.Set("link", "1") } if *force { val.Set("force", "1") } var errNames []string for _, name := range cmd.Args() { if name == "" { return fmt.Errorf("Container name cannot be empty") } name = strings.Trim(name, "/") _, _, err := readBody(cli.call("DELETE", "/containers/"+name+"?"+val.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to remove containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/rmi.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" ) // CmdRmi removes all images with the specified name(s). // // Usage: docker rmi [OPTIONS] IMAGE [IMAGE...] func (cli *DockerCli) CmdRmi(args ...string) error { cmd := cli.Subcmd("rmi", []string{"IMAGE [IMAGE...]"}, "Remove one or more images", true) force := cmd.Bool([]string{"f", "-force"}, false, "Force removal of the image") noprune := cmd.Bool([]string{"-no-prune"}, false, "Do not delete untagged parents") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) v := url.Values{} if *force { v.Set("force", "1") } if *noprune { v.Set("noprune", "1") } var errNames []string for _, name := range cmd.Args() { serverResp, err := cli.call("DELETE", "/images/"+name+"?"+v.Encode(), nil, nil) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { defer serverResp.body.Close() dels := []types.ImageDelete{} if err := json.NewDecoder(serverResp.body).Decode(&dels); err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) continue } for _, del := range dels { if del.Deleted != "" { fmt.Fprintf(cli.out, "Deleted: %s\n", del.Deleted) } else { fmt.Fprintf(cli.out, "Untagged: %s\n", del.Untagged) } } } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to remove images: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/run.go ================================================ package client import ( "fmt" "io" "net/url" "os" "runtime" "github.com/Sirupsen/logrus" "github.com/docker/docker/opts" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/runconfig" "github.com/docker/libnetwork/resolvconf/dns" ) func (cid *cidFile) Close() error { cid.file.Close() if !cid.written { if err := os.Remove(cid.path); err != nil { return fmt.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 fmt.Errorf("Failed to write the container ID to the file: %s", err) } cid.written = true return nil } // CmdRun runs a command in a new container. // // Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] func (cli *DockerCli) CmdRun(args ...string) error { cmd := cli.Subcmd("run", []string{"IMAGE [COMMAND] [ARG...]"}, "Run a command in a new container", true) // These are flags not stored in Config/HostConfig var ( flAutoRemove = cmd.Bool([]string{"-rm"}, false, "Automatically remove the container when it exits") flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Run container in background and print container ID") flSigProxy = cmd.Bool([]string{"-sig-proxy"}, true, "Proxy received signals to the process") flName = cmd.String([]string{"-name"}, "", "Assign a name to the container") flAttach *opts.ListOpts ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d") ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm") ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d") ) config, hostConfig, cmd, err := runconfig.Parse(cmd, args) // just in case the Parse does not exit if err != nil { cmd.ReportError(err.Error(), true) os.Exit(1) } if len(hostConfig.Dns) > 0 { // check the DNS settings passed via --dns against // localhost regexp to warn if they are trying to // set a DNS to a localhost address for _, dnsIP := range hostConfig.Dns { if dns.IsLocalhost(dnsIP) { fmt.Fprintf(cli.err, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP) break } } } if config.Image == "" { cmd.Usage() return nil } if !*flDetach { if err := cli.CheckTtyInput(config.AttachStdin, config.Tty); err != nil { return err } } else { if fl := cmd.Lookup("-attach"); fl != nil { flAttach = fl.Value.(*opts.ListOpts) if flAttach.Len() != 0 { return ErrConflictAttachDetach } } if *flAutoRemove { return ErrConflictDetachAutoRemove } config.AttachStdin = false config.AttachStdout = false config.AttachStderr = false config.StdinOnce = false } // Disable flSigProxy when in TTY mode sigProxy := *flSigProxy if config.Tty { 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] = cli.getTtySize() } createResponse, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName) if err != nil { return err } if sigProxy { sigc := cli.forwardAllSignals(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.Fprintf(cli.out, "%s\n", createResponse.ID) }() } if *flAutoRemove && (hostConfig.RestartPolicy.IsAlways() || hostConfig.RestartPolicy.IsOnFailure()) { return ErrConflictRestartPolicyAndAutoRemove } // We need to instantiate the chan because the select needs it. It can // be closed but can't be uninitialized. hijacked := make(chan io.Closer) // Block the return until the chan gets closed defer func() { logrus.Debugf("End of CmdRun(), Waiting for hijack to finish.") if _, ok := <-hijacked; ok { fmt.Fprintln(cli.err, "Hijack did not finish (chan still open)") } }() if config.AttachStdin || config.AttachStdout || config.AttachStderr { var ( out, stderr io.Writer in io.ReadCloser v = url.Values{} ) v.Set("stream", "1") if config.AttachStdin { v.Set("stdin", "1") in = cli.in } if config.AttachStdout { v.Set("stdout", "1") out = cli.out } if config.AttachStderr { v.Set("stderr", "1") if config.Tty { stderr = cli.out } else { stderr = cli.err } } errCh = promise.Go(func() error { return cli.hijack("POST", "/containers/"+createResponse.ID+"/attach?"+v.Encode(), config.Tty, in, out, stderr, hijacked, nil) }) } else { close(hijacked) } // Acknowledge the hijack before starting select { case closer := <-hijacked: // Make sure that the hijack gets closed when returning (results // in closing the hijack chan and freeing server's goroutines) if closer != nil { defer closer.Close() } case err := <-errCh: if err != nil { logrus.Debugf("Error hijack: %s", err) return err } } defer func() { if *flAutoRemove { if _, _, err = readBody(cli.call("DELETE", "/containers/"+createResponse.ID+"?v=1", nil, nil)); err != nil { fmt.Fprintf(cli.err, "Error deleting container: %s\n", err) } } }() //start the container if _, _, err = readBody(cli.call("POST", "/containers/"+createResponse.ID+"/start", nil, nil)); err != nil { return err } if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut { if err := cli.monitorTtySize(createResponse.ID, false); err != nil { fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err) } } if errCh != nil { if err := <-errCh; err != 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 } var status int // Attached mode if *flAutoRemove { // Autoremove: wait for the container to finish, retrieve // the exit code and remove the container if _, _, err := readBody(cli.call("POST", "/containers/"+createResponse.ID+"/wait", nil, nil)); err != nil { return err } if _, status, err = getExitCode(cli, createResponse.ID); err != nil { return err } } else { // No Autoremove: Simply retrieve the exit code if !config.Tty { // In non-TTY mode, we can't detach, so we must wait for container exit if status, err = waitForExit(cli, createResponse.ID); err != nil { return err } } else { // In TTY mode, there is a race: if the process dies too slowly, the state could // be updated after the getExitCode call and result in the wrong exit code being reported if _, status, err = getExitCode(cli, createResponse.ID); err != nil { return err } } } if status != 0 { return StatusError{StatusCode: status} } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/save.go ================================================ package client import ( "errors" "io" "net/url" "os" flag "github.com/docker/docker/pkg/mflag" ) // CmdSave saves one or more images to a tar archive. // // The tar archive is written to STDOUT by default, or written to a file. // // Usage: docker save [OPTIONS] IMAGE [IMAGE...] func (cli *DockerCli) CmdSave(args ...string) error { cmd := cli.Subcmd("save", []string{"IMAGE [IMAGE...]"}, "Save an image(s) to a tar archive (streamed to STDOUT by default)", true) outfile := cmd.String([]string{"o", "-output"}, "", "Write to an file, instead of STDOUT") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var ( output io.Writer = cli.out err error ) if *outfile != "" { output, err = os.Create(*outfile) if err != nil { return err } } else if cli.isTerminalOut { return errors.New("Cowardly refusing to save to a terminal. Use the -o flag or redirect.") } sopts := &streamOpts{ rawTerminal: true, out: output, } if len(cmd.Args()) == 1 { image := cmd.Arg(0) if _, err := cli.stream("GET", "/images/"+image+"/get", sopts); err != nil { return err } } else { v := url.Values{} for _, arg := range cmd.Args() { v.Add("names", arg) } if _, err := cli.stream("GET", "/images/get?"+v.Encode(), sopts); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/search.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "sort" "strings" "text/tabwriter" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/stringutils" "github.com/docker/docker/registry" ) // ByStars sorts search results in ascending order by number of stars. type ByStars []registry.SearchResult func (r ByStars) Len() int { return len(r) } func (r ByStars) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r ByStars) Less(i, j int) bool { return r[i].StarCount < r[j].StarCount } // CmdSearch searches the Docker Hub for images. // // Usage: docker search [OPTIONS] TERM func (cli *DockerCli) CmdSearch(args ...string) error { cmd := cli.Subcmd("search", []string{"TERM"}, "Search the Docker Hub for images", true) noTrunc := cmd.Bool([]string{"#notrunc", "-no-trunc"}, false, "Don't truncate output") trusted := cmd.Bool([]string{"#t", "#trusted", "#-trusted"}, false, "Only show trusted builds") automated := cmd.Bool([]string{"-automated"}, false, "Only show automated builds") stars := cmd.Uint([]string{"s", "#stars", "-stars"}, 0, "Only displays with at least x stars") cmd.Require(flag.Exact, 1) cmd.ParseFlags(args, true) name := cmd.Arg(0) v := url.Values{} v.Set("term", name) // Resolve the Repository name from fqn to hostname + name taglessRemote, _ := parsers.ParseRepositoryTag(name) repoInfo, err := registry.ParseRepositoryInfo(taglessRemote) if err != nil { return err } rdr, _, err := cli.clientRequestAttemptLogin("GET", "/images/search?"+v.Encode(), nil, nil, repoInfo.Index, "search") if err != nil { return err } defer rdr.Close() results := ByStars{} if err := json.NewDecoder(rdr).Decode(&results); err != nil { return err } sort.Sort(sort.Reverse(results)) w := tabwriter.NewWriter(cli.out, 10, 1, 3, ' ', 0) fmt.Fprintf(w, "NAME\tDESCRIPTION\tSTARS\tOFFICIAL\tAUTOMATED\n") for _, res := range results { if ((*automated || *trusted) && (!res.IsTrusted && !res.IsAutomated)) || (int(*stars) > res.StarCount) { continue } desc := strings.Replace(res.Description, "\n", " ", -1) desc = strings.Replace(desc, "\r", " ", -1) if !*noTrunc && len(desc) > 45 { desc = stringutils.Truncate(desc, 42) + "..." } 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 || res.IsTrusted { fmt.Fprint(w, "[OK]") } fmt.Fprint(w, "\n") } w.Flush() return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/service.go ================================================ // +build experimental package client import ( "os" nwclient "github.com/docker/libnetwork/client" ) func (cli *DockerCli) CmdService(args ...string) error { nCli := nwclient.NewNetworkCli(cli.out, cli.err, nwclient.CallFunc(cli.callWrapper)) args = append([]string{"service"}, args...) return nCli.Cmd(os.Args[0], args...) } ================================================ FILE: vendor/github.com/docker/docker/api/client/start.go ================================================ package client import ( "encoding/json" "fmt" "io" "net/url" "os" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/signal" ) func (cli *DockerCli) forwardAllSignals(cid string) chan os.Signal { sigc := make(chan os.Signal, 128) signal.CatchAll(sigc) go func() { for s := range sigc { if s == signal.SIGCHLD { 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) } if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/kill?signal=%s", cid, sig), nil, nil)); err != nil { logrus.Debugf("Error sending signal: %s", err) } } }() return sigc } // CmdStart starts one or more stopped containers. // // Usage: docker start [OPTIONS] CONTAINER [CONTAINER...] func (cli *DockerCli) CmdStart(args ...string) error { cmd := cli.Subcmd("start", []string{"CONTAINER [CONTAINER...]"}, "Start one or more stopped containers", true) attach := cmd.Bool([]string{"a", "-attach"}, false, "Attach STDOUT/STDERR and forward signals") openStdin := cmd.Bool([]string{"i", "-interactive"}, false, "Attach container's STDIN") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var ( cErr chan error tty bool ) if *attach || *openStdin { if cmd.NArg() > 1 { return fmt.Errorf("You cannot start and attach multiple containers at once.") } serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/json", nil, nil) if err != nil { return err } defer serverResp.body.Close() var c types.ContainerJSON if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { return err } tty = c.Config.Tty if !tty { sigc := cli.forwardAllSignals(cmd.Arg(0)) defer signal.StopCatch(sigc) } var in io.ReadCloser v := url.Values{} v.Set("stream", "1") if *openStdin && c.Config.OpenStdin { v.Set("stdin", "1") in = cli.in } v.Set("stdout", "1") v.Set("stderr", "1") hijacked := make(chan io.Closer) // Block the return until the chan gets closed defer func() { logrus.Debugf("CmdStart() returned, defer waiting for hijack to finish.") if _, ok := <-hijacked; ok { fmt.Fprintln(cli.err, "Hijack did not finish (chan still open)") } cli.in.Close() }() cErr = promise.Go(func() error { return cli.hijack("POST", "/containers/"+cmd.Arg(0)+"/attach?"+v.Encode(), tty, in, cli.out, cli.err, hijacked, nil) }) // Acknowledge the hijack before starting select { case closer := <-hijacked: // Make sure that the hijack gets closed when returning (results // in closing the hijack chan and freeing server's goroutines) if closer != nil { defer closer.Close() } case err := <-cErr: if err != nil { return err } } } var encounteredError error var errNames []string for _, name := range cmd.Args() { _, _, err := readBody(cli.call("POST", "/containers/"+name+"/start", nil, nil)) if err != nil { if !*attach && !*openStdin { // attach and openStdin is false means it could be starting multiple containers // when a container start failed, show the error message and start next fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { encounteredError = err } } else { if !*attach && !*openStdin { fmt.Fprintf(cli.out, "%s\n", name) } } } if len(errNames) > 0 { encounteredError = fmt.Errorf("Error: failed to start containers: %v", errNames) } if encounteredError != nil { return encounteredError } if *openStdin || *attach { if tty && cli.isTerminalOut { if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil { fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err) } } if attchErr := <-cErr; attchErr != nil { return attchErr } _, status, err := getExitCode(cli, cmd.Arg(0)) if err != nil { return err } if status != 0 { return StatusError{StatusCode: status} } } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/stats.go ================================================ package client import ( "encoding/json" "fmt" "io" "net/url" "sort" "strings" "sync" "text/tabwriter" "time" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/units" ) type containerStats struct { Name string CPUPercentage float64 Memory float64 MemoryLimit float64 MemoryPercentage float64 NetworkRx float64 NetworkTx float64 mu sync.RWMutex err error } func (s *containerStats) Collect(cli *DockerCli, streamStats bool) { v := url.Values{} if streamStats { v.Set("stream", "1") } else { v.Set("stream", "0") } serverResp, err := cli.call("GET", "/containers/"+s.Name+"/stats?"+v.Encode(), nil, nil) if err != nil { s.mu.Lock() s.err = err s.mu.Unlock() return } defer serverResp.body.Close() var ( previousCPU uint64 previousSystem uint64 dec = json.NewDecoder(serverResp.body) u = make(chan error, 1) ) go func() { for { var v *types.Stats if err := dec.Decode(&v); err != nil { u <- err return } var ( memPercent = float64(v.MemoryStats.Usage) / float64(v.MemoryStats.Limit) * 100.0 cpuPercent = 0.0 ) previousCPU = v.PreCpuStats.CpuUsage.TotalUsage previousSystem = v.PreCpuStats.SystemUsage cpuPercent = calculateCPUPercent(previousCPU, previousSystem, v) s.mu.Lock() s.CPUPercentage = cpuPercent s.Memory = float64(v.MemoryStats.Usage) s.MemoryLimit = float64(v.MemoryStats.Limit) s.MemoryPercentage = memPercent s.NetworkRx = float64(v.Network.RxBytes) s.NetworkTx = float64(v.Network.TxBytes) s.mu.Unlock() 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.mu.Lock() s.CPUPercentage = 0 s.Memory = 0 s.MemoryPercentage = 0 s.mu.Unlock() case err := <-u: if err != nil { s.mu.Lock() s.err = err s.mu.Unlock() return } } if !streamStats { return } } } func (s *containerStats) Display(w io.Writer) error { s.mu.RLock() defer s.mu.RUnlock() if s.err != nil { return s.err } fmt.Fprintf(w, "%s\t%.2f%%\t%s/%s\t%.2f%%\t%s/%s\n", s.Name, s.CPUPercentage, units.HumanSize(s.Memory), units.HumanSize(s.MemoryLimit), s.MemoryPercentage, units.HumanSize(s.NetworkRx), units.HumanSize(s.NetworkTx)) return nil } // CmdStats 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. // // Usage: docker stats CONTAINER [CONTAINER...] func (cli *DockerCli) CmdStats(args ...string) error { cmd := cli.Subcmd("stats", []string{"CONTAINER [CONTAINER...]"}, "Display a live stream of one or more containers' resource usage statistics", true) noStream := cmd.Bool([]string{"-no-stream"}, false, "Disable streaming stats and only pull the first result") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) names := cmd.Args() sort.Strings(names) var ( cStats []*containerStats w = tabwriter.NewWriter(cli.out, 20, 1, 3, ' ', 0) ) printHeader := func() { if !*noStream { fmt.Fprint(cli.out, "\033[2J") fmt.Fprint(cli.out, "\033[H") } io.WriteString(w, "CONTAINER\tCPU %\tMEM USAGE/LIMIT\tMEM %\tNET I/O\n") } for _, n := range names { s := &containerStats{Name: n} cStats = append(cStats, s) go s.Collect(cli, !*noStream) } // do a quick pause so that any failed connections for containers that do not exist are able to be // evicted before we display the initial or default values. time.Sleep(1500 * time.Millisecond) var errs []string for _, c := range cStats { c.mu.Lock() if c.err != nil { errs = append(errs, fmt.Sprintf("%s: %v", c.Name, c.err)) } c.mu.Unlock() } if len(errs) > 0 { return fmt.Errorf("%s", strings.Join(errs, ", ")) } for range time.Tick(500 * time.Millisecond) { printHeader() toRemove := []int{} for i, s := range cStats { if err := s.Display(w); err != nil && !*noStream { toRemove = append(toRemove, i) } } for j := len(toRemove) - 1; j >= 0; j-- { i := toRemove[j] cStats = append(cStats[:i], cStats[i+1:]...) } if len(cStats) == 0 { return nil } w.Flush() if *noStream { break } } return nil } func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.Stats) float64 { var ( cpuPercent = 0.0 // calculate the change for the cpu usage of the container in between readings cpuDelta = float64(v.CpuStats.CpuUsage.TotalUsage - previousCPU) // calculate the change for the entire system between readings systemDelta = float64(v.CpuStats.SystemUsage - previousSystem) ) if systemDelta > 0.0 && cpuDelta > 0.0 { cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CpuStats.CpuUsage.PercpuUsage)) * 100.0 } return cpuPercent } ================================================ FILE: vendor/github.com/docker/docker/api/client/stats_unit_test.go ================================================ package client import ( "bytes" "sync" "testing" ) func TestDisplay(t *testing.T) { c := &containerStats{ Name: "app", CPUPercentage: 30.0, Memory: 100 * 1024 * 1024.0, MemoryLimit: 2048 * 1024 * 1024.0, MemoryPercentage: 100.0 / 2048.0 * 100.0, NetworkRx: 100 * 1024 * 1024, NetworkTx: 800 * 1024 * 1024, mu: sync.RWMutex{}, } var b bytes.Buffer if err := c.Display(&b); err != nil { t.Fatalf("c.Display() gave error: %s", err) } got := b.String() want := "app\t30.00%\t104.9 MB/2.147 GB\t4.88%\t104.9 MB/838.9 MB\n" if got != want { t.Fatalf("c.Display() = %q, want %q", got, want) } } ================================================ FILE: vendor/github.com/docker/docker/api/client/stop.go ================================================ package client import ( "fmt" "net/url" "strconv" flag "github.com/docker/docker/pkg/mflag" ) // CmdStop stops one or more running containers. // // A running container is stopped by first sending SIGTERM and then SIGKILL if the container fails to stop within a grace period (the default is 10 seconds). // // Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...] func (cli *DockerCli) CmdStop(args ...string) error { cmd := cli.Subcmd("stop", []string{"CONTAINER [CONTAINER...]"}, "Stop a running container by sending SIGTERM and then SIGKILL after a\ngrace period", true) nSeconds := cmd.Int([]string{"t", "-time"}, 10, "Seconds to wait for stop before killing it") cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) v := url.Values{} v.Set("t", strconv.Itoa(*nSeconds)) var errNames []string for _, name := range cmd.Args() { _, _, err := readBody(cli.call("POST", "/containers/"+name+"/stop?"+v.Encode(), nil, nil)) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to stop containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/tag.go ================================================ package client import ( "net/url" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/registry" ) // CmdTag tags an image into a repository. // // Usage: docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG] func (cli *DockerCli) CmdTag(args ...string) error { cmd := cli.Subcmd("tag", []string{"IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]"}, "Tag an image into a repository", true) force := cmd.Bool([]string{"f", "#force", "-force"}, false, "Force") cmd.Require(flag.Exact, 2) cmd.ParseFlags(args, true) var ( repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1)) v = url.Values{} ) //Check if the given image name can be resolved if err := registry.ValidateRepositoryName(repository); err != nil { return err } v.Set("repo", repository) v.Set("tag", tag) if *force { v.Set("force", "1") } if _, _, err := readBody(cli.call("POST", "/images/"+cmd.Arg(0)+"/tag?"+v.Encode(), nil, nil)); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/top.go ================================================ package client import ( "encoding/json" "fmt" "net/url" "strings" "text/tabwriter" "github.com/docker/docker/api/types" flag "github.com/docker/docker/pkg/mflag" ) // CmdTop displays the running processes of a container. // // Usage: docker top CONTAINER func (cli *DockerCli) CmdTop(args ...string) error { cmd := cli.Subcmd("top", []string{"CONTAINER [ps OPTIONS]"}, "Display the running processes of a container", true) cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) val := url.Values{} if cmd.NArg() > 1 { val.Set("ps_args", strings.Join(cmd.Args()[1:], " ")) } serverResp, err := cli.call("GET", "/containers/"+cmd.Arg(0)+"/top?"+val.Encode(), nil, nil) if err != nil { return err } defer serverResp.body.Close() procList := types.ContainerProcessList{} if err := json.NewDecoder(serverResp.body).Decode(&procList); err != nil { return err } w := tabwriter.NewWriter(cli.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 } ================================================ FILE: vendor/github.com/docker/docker/api/client/unpause.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) // CmdUnpause unpauses all processes within a container, for one or more containers. // // Usage: docker unpause CONTAINER [CONTAINER...] func (cli *DockerCli) CmdUnpause(args ...string) error { cmd := cli.Subcmd("unpause", []string{"CONTAINER [CONTAINER...]"}, "Unpause all processes within a container", true) cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var errNames []string for _, name := range cmd.Args() { if _, _, err := readBody(cli.call("POST", fmt.Sprintf("/containers/%s/unpause", name), nil, nil)); err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%s\n", name) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to unpause containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/utils.go ================================================ package client import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" gosignal "os/signal" "runtime" "strconv" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/cliconfig" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/term" "github.com/docker/docker/registry" ) var ( errConnectionRefused = errors.New("Cannot connect to the Docker daemon. Is 'docker -d' running on this host?") ) type serverResponse struct { body io.ReadCloser header http.Header statusCode int } // HTTPClient creates a new HTTP client with the cli's client transport instance. func (cli *DockerCli) HTTPClient() *http.Client { return &http.Client{Transport: cli.transport} } func (cli *DockerCli) encodeData(data interface{}) (*bytes.Buffer, error) { params := bytes.NewBuffer(nil) if data != nil { if err := json.NewEncoder(params).Encode(data); err != nil { return nil, err } } return params, nil } func (cli *DockerCli) clientRequest(method, path string, in io.Reader, headers map[string][]string) (*serverResponse, error) { serverResp := &serverResponse{ body: nil, statusCode: -1, } expectedPayload := (method == "POST" || method == "PUT") if expectedPayload && in == nil { in = bytes.NewReader([]byte{}) } req, err := http.NewRequest(method, fmt.Sprintf("%s/v%s%s", cli.basePath, api.Version, path), in) if err != nil { return serverResp, err } // Add CLI Config's HTTP Headers BEFORE we set the Docker headers // then the user can't change OUR headers for k, v := range cli.configFile.HTTPHeaders { req.Header.Set(k, v) } req.Header.Set("User-Agent", "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")") req.URL.Host = cli.addr req.URL.Scheme = cli.scheme if headers != nil { for k, v := range headers { req.Header[k] = v } } if expectedPayload && req.Header.Get("Content-Type") == "" { req.Header.Set("Content-Type", "text/plain") } resp, err := cli.HTTPClient().Do(req) if resp != nil { serverResp.statusCode = resp.StatusCode } if err != nil { if strings.Contains(err.Error(), "connection refused") { return serverResp, errConnectionRefused } if cli.tlsConfig == nil { return serverResp, fmt.Errorf("%v.\n* Are you trying to connect to a TLS-enabled daemon without TLS?\n* Is your docker daemon up and running?", err) } if cli.tlsConfig != nil && strings.Contains(err.Error(), "remote error: bad certificate") { return serverResp, fmt.Errorf("The server probably has client authentication (--tlsverify) enabled. Please check your TLS client certification settings: %v", err) } return serverResp, fmt.Errorf("An error occurred trying to connect: %v", err) } if serverResp.statusCode < 200 || serverResp.statusCode >= 400 { body, err := ioutil.ReadAll(resp.Body) if err != nil { return serverResp, err } if len(body) == 0 { return serverResp, fmt.Errorf("Error: request returned %s for API route and version %s, check if the server supports the requested API version", http.StatusText(serverResp.statusCode), req.URL) } return serverResp, fmt.Errorf("Error response from daemon: %s", bytes.TrimSpace(body)) } serverResp.body = resp.Body serverResp.header = resp.Header return serverResp, nil } func (cli *DockerCli) clientRequestAttemptLogin(method, path string, in io.Reader, out io.Writer, index *registry.IndexInfo, cmdName string) (io.ReadCloser, int, error) { cmdAttempt := func(authConfig cliconfig.AuthConfig) (io.ReadCloser, int, error) { buf, err := json.Marshal(authConfig) if err != nil { return nil, -1, err } registryAuthHeader := []string{ base64.URLEncoding.EncodeToString(buf), } // begin the request serverResp, err := cli.clientRequest(method, path, in, map[string][]string{ "X-Registry-Auth": registryAuthHeader, }) if err == nil && out != nil { // If we are streaming output, complete the stream since // errors may not appear until later. err = cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), true, out, nil) } if err != nil { // Since errors in a stream appear after status 200 has been written, // we may need to change the status code. if strings.Contains(err.Error(), "Authentication is required") || strings.Contains(err.Error(), "Status 401") || strings.Contains(err.Error(), "401 Unauthorized") || strings.Contains(err.Error(), "status code 401") { serverResp.statusCode = http.StatusUnauthorized } } return serverResp.body, serverResp.statusCode, err } // Resolve the Auth config relevant for this server authConfig := registry.ResolveAuthConfig(cli.configFile, index) body, statusCode, err := cmdAttempt(authConfig) if statusCode == http.StatusUnauthorized { fmt.Fprintf(cli.out, "\nPlease login prior to %s:\n", cmdName) if err = cli.CmdLogin(index.GetAuthConfigKey()); err != nil { return nil, -1, err } authConfig = registry.ResolveAuthConfig(cli.configFile, index) return cmdAttempt(authConfig) } return body, statusCode, err } func (cli *DockerCli) callWrapper(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, http.Header, int, error) { sr, err := cli.call(method, path, data, headers) return sr.body, sr.header, sr.statusCode, err } func (cli *DockerCli) call(method, path string, data interface{}, headers map[string][]string) (*serverResponse, error) { params, err := cli.encodeData(data) if err != nil { sr := &serverResponse{ body: nil, header: nil, statusCode: -1, } return sr, nil } if data != nil { if headers == nil { headers = make(map[string][]string) } headers["Content-Type"] = []string{"application/json"} } serverResp, err := cli.clientRequest(method, path, params, headers) return serverResp, err } type streamOpts struct { rawTerminal bool in io.Reader out io.Writer err io.Writer headers map[string][]string } func (cli *DockerCli) stream(method, path string, opts *streamOpts) (*serverResponse, error) { serverResp, err := cli.clientRequest(method, path, opts.in, opts.headers) if err != nil { return serverResp, err } return serverResp, cli.streamBody(serverResp.body, serverResp.header.Get("Content-Type"), opts.rawTerminal, opts.out, opts.err) } func (cli *DockerCli) streamBody(body io.ReadCloser, contentType string, rawTerminal bool, stdout, stderr io.Writer) error { defer body.Close() if api.MatchesContentType(contentType, "application/json") { return jsonmessage.DisplayJSONMessagesStream(body, stdout, cli.outFd, cli.isTerminalOut) } if stdout != nil || stderr != nil { // When TTY is ON, use regular copy var err error if rawTerminal { _, err = io.Copy(stdout, body) } else { _, err = stdcopy.StdCopy(stdout, stderr, body) } logrus.Debugf("[stream] End of stdout") return err } return nil } func (cli *DockerCli) resizeTty(id string, isExec bool) { height, width := cli.getTtySize() if height == 0 && width == 0 { return } v := url.Values{} v.Set("h", strconv.Itoa(height)) v.Set("w", strconv.Itoa(width)) path := "" if !isExec { path = "/containers/" + id + "/resize?" } else { path = "/exec/" + id + "/resize?" } if _, _, err := readBody(cli.call("POST", path+v.Encode(), nil, nil)); err != nil { logrus.Debugf("Error resize: %s", err) } } func waitForExit(cli *DockerCli, containerID string) (int, error) { serverResp, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil) if err != nil { return -1, err } defer serverResp.body.Close() var res types.ContainerWaitResponse if err := json.NewDecoder(serverResp.body).Decode(&res); err != nil { return -1, err } return res.StatusCode, nil } // getExitCode perform an inspect on the container. It returns // the running state and the exit code. func getExitCode(cli *DockerCli, containerID string) (bool, int, error) { serverResp, err := cli.call("GET", "/containers/"+containerID+"/json", nil, nil) if err != nil { // If we can't connect, then the daemon probably died. if err != errConnectionRefused { return false, -1, err } return false, -1, nil } defer serverResp.body.Close() var c types.ContainerJSON if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { return false, -1, err } return c.State.Running, c.State.ExitCode, nil } // getExecExitCode perform an inspect on the exec command. It returns // the running state and the exit code. func getExecExitCode(cli *DockerCli, execID string) (bool, int, error) { serverResp, err := cli.call("GET", "/exec/"+execID+"/json", nil, nil) if err != nil { // If we can't connect, then the daemon probably died. if err != errConnectionRefused { return false, -1, err } return false, -1, nil } defer serverResp.body.Close() //TODO: Should we reconsider having a type in api/types? //this is a response to exex/id/json not container var c struct { Running bool ExitCode int } if err := json.NewDecoder(serverResp.body).Decode(&c); err != nil { return false, -1, err } return c.Running, c.ExitCode, nil } func (cli *DockerCli) monitorTtySize(id string, isExec bool) error { cli.resizeTty(id, isExec) if runtime.GOOS == "windows" { go func() { prevH, prevW := cli.getTtySize() for { time.Sleep(time.Millisecond * 250) h, w := cli.getTtySize() if prevW != w || prevH != h { cli.resizeTty(id, isExec) } prevH = h prevW = w } }() } else { sigchan := make(chan os.Signal, 1) gosignal.Notify(sigchan, signal.SIGWINCH) go func() { for range sigchan { cli.resizeTty(id, isExec) } }() } return nil } func (cli *DockerCli) getTtySize() (int, int) { if !cli.isTerminalOut { return 0, 0 } ws, err := term.GetWinsize(cli.outFd) if err != nil { logrus.Debugf("Error getting size: %s", err) if ws == nil { return 0, 0 } } return int(ws.Height), int(ws.Width) } func readBody(serverResp *serverResponse, err error) ([]byte, int, error) { if serverResp.body != nil { defer serverResp.body.Close() } if err != nil { return nil, serverResp.statusCode, err } body, err := ioutil.ReadAll(serverResp.body) if err != nil { return nil, -1, err } return body, serverResp.statusCode, nil } ================================================ FILE: vendor/github.com/docker/docker/api/client/version.go ================================================ package client import ( "encoding/json" "runtime" "text/template" "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/autogen/dockerversion" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/utils" ) var VersionTemplate = `Client: Version: {{.Client.Version}} API version: {{.Client.ApiVersion}} Go version: {{.Client.GoVersion}} Git commit: {{.Client.GitCommit}} Built: {{.Client.BuildTime}} OS/Arch: {{.Client.Os}}/{{.Client.Arch}}{{if .Client.Experimental}} Experimental: {{.Client.Experimental}}{{end}}{{if .ServerOK}} Server: Version: {{.Server.Version}} API version: {{.Server.ApiVersion}} Go version: {{.Server.GoVersion}} Git commit: {{.Server.GitCommit}} Built: {{.Server.BuildTime}} OS/Arch: {{.Server.Os}}/{{.Server.Arch}}{{if .Server.Experimental}} Experimental: {{.Server.Experimental}}{{end}}{{end}}` type VersionData struct { Client types.Version ServerOK bool Server types.Version } // CmdVersion shows Docker version information. // // Available version information is shown for: client Docker version, client API version, client Go version, client Git commit, client OS/Arch, server Docker version, server API version, server Go version, server Git commit, and server OS/Arch. // // Usage: docker version func (cli *DockerCli) CmdVersion(args ...string) (err error) { cmd := cli.Subcmd("version", nil, "Show the Docker version information.", true) tmplStr := cmd.String([]string{"f", "#format", "-format"}, "", "Format the output using the given go template") cmd.Require(flag.Exact, 0) cmd.ParseFlags(args, true) if *tmplStr == "" { *tmplStr = VersionTemplate } var tmpl *template.Template if tmpl, err = template.New("").Funcs(funcMap).Parse(*tmplStr); err != nil { return StatusError{StatusCode: 64, Status: "Template parsing error: " + err.Error()} } vd := VersionData{ Client: types.Version{ Version: dockerversion.VERSION, ApiVersion: api.Version, GoVersion: runtime.Version(), GitCommit: dockerversion.GITCOMMIT, BuildTime: dockerversion.BUILDTIME, Os: runtime.GOOS, Arch: runtime.GOARCH, Experimental: utils.ExperimentalBuild(), }, } defer func() { if err2 := tmpl.Execute(cli.out, vd); err2 != nil && err == nil { err = err2 } cli.out.Write([]byte{'\n'}) }() serverResp, err := cli.call("GET", "/version", nil, nil) if err != nil { return err } defer serverResp.body.Close() if err = json.NewDecoder(serverResp.body).Decode(&vd.Server); err != nil { return StatusError{StatusCode: 1, Status: "Error reading remote version: " + err.Error()} } vd.ServerOK = true return } ================================================ FILE: vendor/github.com/docker/docker/api/client/wait.go ================================================ package client import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) // CmdWait blocks until a container stops, then prints its exit code. // // If more than one container is specified, this will wait synchronously on each container. // // Usage: docker wait CONTAINER [CONTAINER...] func (cli *DockerCli) CmdWait(args ...string) error { cmd := cli.Subcmd("wait", []string{"CONTAINER [CONTAINER...]"}, "Block until a container stops, then print its exit code.", true) cmd.Require(flag.Min, 1) cmd.ParseFlags(args, true) var errNames []string for _, name := range cmd.Args() { status, err := waitForExit(cli, name) if err != nil { fmt.Fprintf(cli.err, "%s\n", err) errNames = append(errNames, name) } else { fmt.Fprintf(cli.out, "%d\n", status) } } if len(errNames) > 0 { return fmt.Errorf("Error: failed to wait containers: %v", errNames) } return nil } ================================================ FILE: vendor/github.com/docker/docker/api/common.go ================================================ package api import ( "fmt" "mime" "path/filepath" "sort" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/version" "github.com/docker/libtrust" ) // Common constants for daemon and client. const ( // Current REST API version Version version.Version = "1.20" // Minimun REST API version supported MinVersion version.Version = "1.12" // Default filename with Docker commands, read by docker build DefaultDockerfileName string = "Dockerfile" ) type ByPrivatePort []types.Port func (r ByPrivatePort) Len() int { return len(r) } func (r ByPrivatePort) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r ByPrivatePort) Less(i, j int) bool { return r[i].PrivatePort < r[j].PrivatePort } func DisplayablePorts(ports []types.Port) string { var ( result = []string{} hostMappings = []string{} firstInGroupMap map[string]int lastInGroupMap map[string]int ) firstInGroupMap = make(map[string]int) lastInGroupMap = make(map[string]int) sort.Sort(ByPrivatePort(ports)) for _, port := range ports { var ( current = port.PrivatePort portKey = port.Type firstInGroup int lastInGroup int ) 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) } firstInGroup = firstInGroupMap[portKey] lastInGroup = lastInGroupMap[portKey] if firstInGroup == 0 { firstInGroupMap[portKey] = current lastInGroupMap[portKey] = current continue } if current == (lastInGroup + 1) { lastInGroupMap[portKey] = current continue } result = append(result, FormGroup(portKey, firstInGroup, lastInGroup)) firstInGroupMap[portKey] = current lastInGroupMap[portKey] = current } for portKey, firstInGroup := range firstInGroupMap { result = append(result, FormGroup(portKey, firstInGroup, lastInGroupMap[portKey])) } result = append(result, hostMappings...) return strings.Join(result, ", ") } func FormGroup(key string, start, last int) string { var ( group string parts = strings.Split(key, "/") groupType = parts[0] ip = "" ) if len(parts) > 1 { ip = parts[0] groupType = parts[1] } if start == last { group = fmt.Sprintf("%d", start) } else { group = fmt.Sprintf("%d-%d", start, last) } if ip != "" { group = fmt.Sprintf("%s:%s->%s", ip, group, group) } return fmt.Sprintf("%s/%s", group, groupType) } func MatchesContentType(contentType, expectedType string) bool { mimetype, _, err := mime.ParseMediaType(contentType) if err != nil { logrus.Errorf("Error parsing media type: %s error: %v", contentType, err) } return err == nil && mimetype == expectedType } // LoadOrCreateTrustKey attempts to load the libtrust key at the given path, // otherwise generates a new one func LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) { err := system.MkdirAll(filepath.Dir(trustKeyPath), 0700) if err != nil { return nil, err } trustKey, err := libtrust.LoadKeyFile(trustKeyPath) if err == libtrust.ErrKeyFileDoesNotExist { trustKey, err = libtrust.GenerateECP256PrivateKey() if err != nil { return nil, fmt.Errorf("Error generating key: %s", err) } if err := libtrust.SaveKey(trustKeyPath, trustKey); err != nil { return nil, fmt.Errorf("Error saving key file: %s", err) } } else if err != nil { return nil, fmt.Errorf("Error loading key file %s: %s", trustKeyPath, err) } return trustKey, nil } ================================================ FILE: vendor/github.com/docker/docker/api/server/form.go ================================================ package server import ( "net/http" "strconv" "strings" ) func boolValue(r *http.Request, k string) bool { s := strings.ToLower(strings.TrimSpace(r.FormValue(k))) return !(s == "" || s == "0" || s == "no" || s == "false" || s == "none") } // boolValueOrDefault returns the default bool passed if the query param is // missing, otherwise it's just a proxy to boolValue above func boolValueOrDefault(r *http.Request, k string, d bool) bool { if _, ok := r.Form[k]; !ok { return d } return boolValue(r, k) } func int64ValueOrZero(r *http.Request, k string) int64 { val, err := strconv.ParseInt(r.FormValue(k), 10, 64) if err != nil { return 0 } return val } ================================================ FILE: vendor/github.com/docker/docker/api/server/form_test.go ================================================ package server import ( "net/http" "net/url" "testing" ) func TestBoolValue(t *testing.T) { cases := map[string]bool{ "": false, "0": false, "no": false, "false": false, "none": false, "1": true, "yes": true, "true": true, "one": true, "100": true, } for c, e := range cases { v := url.Values{} v.Set("test", c) r, _ := http.NewRequest("POST", "", nil) r.Form = v a := boolValue(r, "test") if a != e { t.Fatalf("Value: %s, expected: %v, actual: %v", c, e, a) } } } func TestBoolValueOrDefault(t *testing.T) { r, _ := http.NewRequest("GET", "", nil) if !boolValueOrDefault(r, "queryparam", true) { t.Fatal("Expected to get true default value, got false") } v := url.Values{} v.Set("param", "") r, _ = http.NewRequest("GET", "", nil) r.Form = v if boolValueOrDefault(r, "param", true) { t.Fatal("Expected not to get true") } } func TestInt64ValueOrZero(t *testing.T) { cases := map[string]int64{ "": 0, "asdf": 0, "0": 0, "1": 1, } for c, e := range cases { v := url.Values{} v.Set("test", c) r, _ := http.NewRequest("POST", "", nil) r.Form = v a := int64ValueOrZero(r, "test") if a != e { t.Fatalf("Value: %s, expected: %v, actual: %v", c, e, a) } } } ================================================ FILE: vendor/github.com/docker/docker/api/server/profiler.go ================================================ package server import ( "expvar" "fmt" "net/http" "net/http/pprof" "github.com/gorilla/mux" ) func ProfilerSetup(mainRouter *mux.Router, path string) { var r = mainRouter.PathPrefix(path).Subrouter() r.HandleFunc("/vars", expVars) r.HandleFunc("/pprof/", pprof.Index) r.HandleFunc("/pprof/cmdline", pprof.Cmdline) r.HandleFunc("/pprof/profile", pprof.Profile) r.HandleFunc("/pprof/symbol", pprof.Symbol) r.HandleFunc("/pprof/block", pprof.Handler("block").ServeHTTP) r.HandleFunc("/pprof/heap", pprof.Handler("heap").ServeHTTP) r.HandleFunc("/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP) r.HandleFunc("/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP) } // Replicated from expvar.go as not public. func expVars(w http.ResponseWriter, r *http.Request) { first := true w.Header().Set("Content-Type", "application/json; charset=utf-8") fmt.Fprintf(w, "{\n") expvar.Do(func(kv expvar.KeyValue) { if !first { fmt.Fprintf(w, ",\n") } first = false fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value) }) fmt.Fprintf(w, "\n}\n") } ================================================ FILE: vendor/github.com/docker/docker/api/server/server.go ================================================ package server import ( "crypto/tls" "encoding/base64" "encoding/json" "fmt" "io" "net" "net/http" "os" "runtime" "strconv" "strings" "time" "github.com/gorilla/mux" "golang.org/x/net/websocket" "github.com/Sirupsen/logrus" "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/builder" "github.com/docker/docker/cliconfig" "github.com/docker/docker/daemon" "github.com/docker/docker/graph" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/sockets" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/version" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) type ServerConfig struct { Logging bool EnableCors bool CorsHeaders string Version string SocketGroup string TLSConfig *tls.Config } type Server struct { daemon *daemon.Daemon cfg *ServerConfig router *mux.Router start chan struct{} servers []serverCloser } func New(cfg *ServerConfig) *Server { srv := &Server{ cfg: cfg, start: make(chan struct{}), } r := createRouter(srv) srv.router = r return srv } func (s *Server) Close() { for _, srv := range s.servers { if err := srv.Close(); err != nil { logrus.Error(err) } } } type serverCloser interface { Serve() error Close() error } // ServeApi loops through all of the protocols sent in to docker and spawns // off a go routine to setup a serving http.Server for each. func (s *Server) ServeApi(protoAddrs []string) error { var chErrors = make(chan error, len(protoAddrs)) for _, protoAddr := range protoAddrs { protoAddrParts := strings.SplitN(protoAddr, "://", 2) if len(protoAddrParts) != 2 { return fmt.Errorf("bad format, expected PROTO://ADDR") } srv, err := s.newServer(protoAddrParts[0], protoAddrParts[1]) if err != nil { return err } s.servers = append(s.servers, srv...) for _, s := range srv { logrus.Infof("Listening for HTTP on %s (%s)", protoAddrParts[0], protoAddrParts[1]) go func(s serverCloser) { if err := s.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") { err = nil } chErrors <- err }(s) } } for i := 0; i < len(protoAddrs); i++ { err := <-chErrors if err != nil { return err } } return nil } type HttpServer struct { srv *http.Server l net.Listener } func (s *HttpServer) Serve() error { return s.srv.Serve(s.l) } func (s *HttpServer) Close() error { return s.l.Close() } type HttpApiFunc func(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error func hijackServer(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) { conn, _, err := w.(http.Hijacker).Hijack() if err != nil { return nil, nil, err } // Flush the options to make sure the client sets the raw mode conn.Write([]byte{}) return conn, conn, nil } func closeStreams(streams ...interface{}) { for _, stream := range streams { if tcpc, ok := stream.(interface { CloseWrite() error }); ok { tcpc.CloseWrite() } else if closer, ok := stream.(io.Closer); ok { closer.Close() } } } // Check to make sure request's Content-Type is application/json func checkForJson(r *http.Request) error { ct := r.Header.Get("Content-Type") // No Content-Type header is ok as long as there's no Body if ct == "" { if r.Body == nil || r.ContentLength == 0 { return nil } } // Otherwise it better be json if api.MatchesContentType(ct, "application/json") { return nil } return fmt.Errorf("Content-Type specified (%s) must be 'application/json'", ct) } //If we don't do this, POST method without Content-type (even with empty body) will fail func parseForm(r *http.Request) error { if r == nil { return nil } if err := r.ParseForm(); err != nil && !strings.HasPrefix(err.Error(), "mime:") { return err } return nil } func parseMultipartForm(r *http.Request) error { if err := r.ParseMultipartForm(4096); err != nil && !strings.HasPrefix(err.Error(), "mime:") { return err } return nil } func httpError(w http.ResponseWriter, err error) { if err == nil || w == nil { logrus.WithFields(logrus.Fields{"error": err, "writer": w}).Error("unexpected HTTP error handling") return } statusCode := http.StatusInternalServerError // FIXME: this is brittle and should not be necessary. // If we need to differentiate between different possible error types, we should // create appropriate error types with clearly defined meaning. errStr := strings.ToLower(err.Error()) for keyword, status := range map[string]int{ "not found": http.StatusNotFound, "no such": http.StatusNotFound, "bad parameter": http.StatusBadRequest, "conflict": http.StatusConflict, "impossible": http.StatusNotAcceptable, "wrong login/password": http.StatusUnauthorized, "hasn't been activated": http.StatusForbidden, } { if strings.Contains(errStr, keyword) { statusCode = status break } } logrus.WithFields(logrus.Fields{"statusCode": statusCode, "err": err}).Error("HTTP Error") http.Error(w, err.Error(), statusCode) } // writeJSON writes the value v to the http response stream as json with standard // json encoding. func writeJSON(w http.ResponseWriter, code int, v interface{}) error { w.Header().Set("Content-Type", "application/json") w.WriteHeader(code) return json.NewEncoder(w).Encode(v) } func (s *Server) postAuth(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { var config *cliconfig.AuthConfig err := json.NewDecoder(r.Body).Decode(&config) r.Body.Close() if err != nil { return err } status, err := s.daemon.RegistryService.Auth(config) if err != nil { return err } return writeJSON(w, http.StatusOK, &types.AuthResponse{ Status: status, }) } func (s *Server) getVersion(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { v := &types.Version{ Version: dockerversion.VERSION, ApiVersion: api.Version, GitCommit: dockerversion.GITCOMMIT, GoVersion: runtime.Version(), Os: runtime.GOOS, Arch: runtime.GOARCH, BuildTime: dockerversion.BUILDTIME, } if version.GreaterThanOrEqualTo("1.19") { v.Experimental = utils.ExperimentalBuild() } if kernelVersion, err := kernel.GetKernelVersion(); err == nil { v.KernelVersion = kernelVersion.String() } return writeJSON(w, http.StatusOK, v) } func (s *Server) postContainersKill(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } var sig uint64 name := vars["name"] // If we have a signal, look at it. Otherwise, do nothing if sigStr := r.Form.Get("signal"); sigStr != "" { // Check if we passed the signal as a number: // The largest legal signal is 31, so let's parse on 5 bits sigN, err := strconv.ParseUint(sigStr, 10, 5) if err != nil { // The signal is not a number, treat it as a string (either like // "KILL" or like "SIGKILL") syscallSig, ok := signal.SignalMap[strings.TrimPrefix(sigStr, "SIG")] if !ok { return fmt.Errorf("Invalid signal: %s", sigStr) } sig = uint64(syscallSig) } else { sig = sigN } if sig == 0 { return fmt.Errorf("Invalid signal: %s", sigStr) } } if err := s.daemon.ContainerKill(name, sig); err != nil { return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) postContainersPause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } if err := s.daemon.ContainerPause(vars["name"]); err != nil { return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) postContainersUnpause(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } if err := s.daemon.ContainerUnpause(vars["name"]); err != nil { return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) getContainersExport(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } return s.daemon.ContainerExport(vars["name"], w) } func (s *Server) getImagesJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } imagesConfig := graph.ImagesConfig{ Filters: r.Form.Get("filters"), // FIXME this parameter could just be a match filter Filter: r.Form.Get("filter"), All: boolValue(r, "all"), } images, err := s.daemon.Repositories().Images(&imagesConfig) if err != nil { return err } return writeJSON(w, http.StatusOK, images) } func (s *Server) getInfo(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { info, err := s.daemon.SystemInfo() if err != nil { return err } return writeJSON(w, http.StatusOK, info) } func (s *Server) getEvents(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } var since int64 = -1 if r.Form.Get("since") != "" { s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64) if err != nil { return err } since = s } var until int64 = -1 if r.Form.Get("until") != "" { u, err := strconv.ParseInt(r.Form.Get("until"), 10, 64) if err != nil { return err } until = u } timer := time.NewTimer(0) timer.Stop() if until > 0 { dur := time.Unix(until, 0).Sub(time.Now()) timer = time.NewTimer(dur) } ef, err := filters.FromParam(r.Form.Get("filters")) if err != nil { return err } isFiltered := func(field string, filter []string) bool { if len(field) == 0 { return false } if len(filter) == 0 { return false } for _, v := range filter { if v == field { return false } if strings.Contains(field, ":") { image := strings.Split(field, ":") if image[0] == v { return false } } } return true } d := s.daemon es := d.EventsService w.Header().Set("Content-Type", "application/json") outStream := ioutils.NewWriteFlusher(w) outStream.Write(nil) // make sure response is sent immediately enc := json.NewEncoder(outStream) getContainerId := func(cn string) string { c, err := d.Get(cn) if err != nil { return "" } return c.ID } sendEvent := func(ev *jsonmessage.JSONMessage) error { //incoming container filter can be name,id or partial id, convert and replace as a full container id for i, cn := range ef["container"] { ef["container"][i] = getContainerId(cn) } if isFiltered(ev.Status, ef["event"]) || (isFiltered(ev.ID, ef["image"]) && isFiltered(ev.From, ef["image"])) || isFiltered(ev.ID, ef["container"]) { return nil } return enc.Encode(ev) } current, l := es.Subscribe() if since == -1 { current = nil } defer es.Evict(l) for _, ev := range current { if ev.Time < since { continue } if err := sendEvent(ev); err != nil { return err } } var closeNotify <-chan bool if closeNotifier, ok := w.(http.CloseNotifier); ok { closeNotify = closeNotifier.CloseNotify() } for { select { case ev := <-l: jev, ok := ev.(*jsonmessage.JSONMessage) if !ok { continue } if err := sendEvent(jev); err != nil { return err } case <-timer.C: return nil case <-closeNotify: logrus.Debug("Client disconnected, stop sending events") return nil } } } func (s *Server) getImagesHistory(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } name := vars["name"] history, err := s.daemon.Repositories().History(name) if err != nil { return err } return writeJSON(w, http.StatusOK, history) } func (s *Server) getContainersChanges(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } changes, err := s.daemon.ContainerChanges(vars["name"]) if err != nil { return err } return writeJSON(w, http.StatusOK, changes) } func (s *Server) getContainersTop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } procList, err := s.daemon.ContainerTop(vars["name"], r.Form.Get("ps_args")) if err != nil { return err } return writeJSON(w, http.StatusOK, procList) } func (s *Server) getContainersJSON(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } config := &daemon.ContainersConfig{ All: boolValue(r, "all"), Size: boolValue(r, "size"), Since: r.Form.Get("since"), Before: r.Form.Get("before"), Filters: r.Form.Get("filters"), } if tmpLimit := r.Form.Get("limit"); tmpLimit != "" { limit, err := strconv.Atoi(tmpLimit) if err != nil { return err } config.Limit = limit } containers, err := s.daemon.Containers(config) if err != nil { return err } return writeJSON(w, http.StatusOK, containers) } func (s *Server) getContainersStats(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } stream := boolValueOrDefault(r, "stream", true) var out io.Writer if !stream { w.Header().Set("Content-Type", "application/json") out = w } else { out = ioutils.NewWriteFlusher(w) } var closeNotifier <-chan bool if notifier, ok := w.(http.CloseNotifier); ok { closeNotifier = notifier.CloseNotify() } config := &daemon.ContainerStatsConfig{ Stream: stream, OutStream: out, Stop: closeNotifier, } return s.daemon.ContainerStats(vars["name"], config) } func (s *Server) getContainersLogs(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } // Validate args here, because we can't return not StatusOK after job.Run() call stdout, stderr := boolValue(r, "stdout"), boolValue(r, "stderr") if !(stdout || stderr) { return fmt.Errorf("Bad parameters: you must choose at least one stream") } var since time.Time if r.Form.Get("since") != "" { s, err := strconv.ParseInt(r.Form.Get("since"), 10, 64) if err != nil { return err } since = time.Unix(s, 0) } var closeNotifier <-chan bool if notifier, ok := w.(http.CloseNotifier); ok { closeNotifier = notifier.CloseNotify() } logsConfig := &daemon.ContainerLogsConfig{ Follow: boolValue(r, "follow"), Timestamps: boolValue(r, "timestamps"), Since: since, Tail: r.Form.Get("tail"), UseStdout: stdout, UseStderr: stderr, OutStream: ioutils.NewWriteFlusher(w), Stop: closeNotifier, } if err := s.daemon.ContainerLogs(vars["name"], logsConfig); err != nil { fmt.Fprintf(w, "Error running logs job: %s\n", err) } return nil } func (s *Server) postImagesTag(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } repo := r.Form.Get("repo") tag := r.Form.Get("tag") force := boolValue(r, "force") name := vars["name"] if err := s.daemon.Repositories().Tag(repo, tag, name, force); err != nil { return err } s.daemon.EventsService.Log("tag", utils.ImageReference(repo, tag), "") w.WriteHeader(http.StatusCreated) return nil } func (s *Server) postCommit(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if err := checkForJson(r); err != nil { return err } cname := r.Form.Get("container") pause := boolValue(r, "pause") if r.FormValue("pause") == "" && version.GreaterThanOrEqualTo("1.13") { pause = true } c, _, err := runconfig.DecodeContainerConfig(r.Body) if err != nil && err != io.EOF { //Do not fail if body is empty. return err } commitCfg := &builder.BuilderCommitConfig{ Pause: pause, Repo: r.Form.Get("repo"), Tag: r.Form.Get("tag"), Author: r.Form.Get("author"), Comment: r.Form.Get("comment"), Changes: r.Form["changes"], Config: c, } imgID, err := builder.Commit(cname, s.daemon, commitCfg) if err != nil { return err } return writeJSON(w, http.StatusCreated, &types.ContainerCommitResponse{ ID: imgID, }) } // Creates an image from Pull or from Import func (s *Server) postImagesCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } var ( image = r.Form.Get("fromImage") repo = r.Form.Get("repo") tag = r.Form.Get("tag") ) authEncoded := r.Header.Get("X-Registry-Auth") authConfig := &cliconfig.AuthConfig{} if authEncoded != "" { authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) if err := json.NewDecoder(authJson).Decode(authConfig); err != nil { // for a pull it is not an error if no auth was given // to increase compatibility with the existing api it is defaulting to be empty authConfig = &cliconfig.AuthConfig{} } } var ( err error output = ioutils.NewWriteFlusher(w) ) w.Header().Set("Content-Type", "application/json") if image != "" { //pull if tag == "" { image, tag = parsers.ParseRepositoryTag(image) } metaHeaders := map[string][]string{} for k, v := range r.Header { if strings.HasPrefix(k, "X-Meta-") { metaHeaders[k] = v } } imagePullConfig := &graph.ImagePullConfig{ MetaHeaders: metaHeaders, AuthConfig: authConfig, OutStream: output, } err = s.daemon.Repositories().Pull(image, tag, imagePullConfig) } else { //import if tag == "" { repo, tag = parsers.ParseRepositoryTag(repo) } src := r.Form.Get("fromSrc") imageImportConfig := &graph.ImageImportConfig{ Changes: r.Form["changes"], InConfig: r.Body, OutStream: output, } // 'err' MUST NOT be defined within this block, we need any error // generated from the download to be available to the output // stream processing below var newConfig *runconfig.Config newConfig, err = builder.BuildFromConfig(s.daemon, &runconfig.Config{}, imageImportConfig.Changes) if err != nil { return err } imageImportConfig.ContainerConfig = newConfig err = s.daemon.Repositories().Import(src, repo, tag, imageImportConfig) } if err != nil { if !output.Flushed() { return err } sf := streamformatter.NewJSONStreamFormatter() output.Write(sf.FormatError(err)) } return nil } func (s *Server) getImagesSearch(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } var ( config *cliconfig.AuthConfig authEncoded = r.Header.Get("X-Registry-Auth") headers = map[string][]string{} ) if authEncoded != "" { authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) if err := json.NewDecoder(authJson).Decode(&config); err != nil { // for a search it is not an error if no auth was given // to increase compatibility with the existing api it is defaulting to be empty config = &cliconfig.AuthConfig{} } } for k, v := range r.Header { if strings.HasPrefix(k, "X-Meta-") { headers[k] = v } } query, err := s.daemon.RegistryService.Search(r.Form.Get("term"), config, headers) if err != nil { return err } return json.NewEncoder(w).Encode(query.Results) } func (s *Server) postImagesPush(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } metaHeaders := map[string][]string{} for k, v := range r.Header { if strings.HasPrefix(k, "X-Meta-") { metaHeaders[k] = v } } if err := parseForm(r); err != nil { return err } authConfig := &cliconfig.AuthConfig{} authEncoded := r.Header.Get("X-Registry-Auth") if authEncoded != "" { // the new format is to handle the authConfig as a header authJson := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authEncoded)) if err := json.NewDecoder(authJson).Decode(authConfig); err != nil { // to increase compatibility to existing api it is defaulting to be empty authConfig = &cliconfig.AuthConfig{} } } else { // the old format is supported for compatibility if there was no authConfig header if err := json.NewDecoder(r.Body).Decode(authConfig); err != nil { return fmt.Errorf("Bad parameters and missing X-Registry-Auth: %v", err) } } name := vars["name"] output := ioutils.NewWriteFlusher(w) imagePushConfig := &graph.ImagePushConfig{ MetaHeaders: metaHeaders, AuthConfig: authConfig, Tag: r.Form.Get("tag"), OutStream: output, } w.Header().Set("Content-Type", "application/json") if err := s.daemon.Repositories().Push(name, imagePushConfig); err != nil { if !output.Flushed() { return err } sf := streamformatter.NewJSONStreamFormatter() output.Write(sf.FormatError(err)) } return nil } func (s *Server) getImagesGet(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } w.Header().Set("Content-Type", "application/x-tar") output := ioutils.NewWriteFlusher(w) imageExportConfig := &graph.ImageExportConfig{Outstream: output} if name, ok := vars["name"]; ok { imageExportConfig.Names = []string{name} } else { imageExportConfig.Names = r.Form["names"] } if err := s.daemon.Repositories().ImageExport(imageExportConfig); err != nil { if !output.Flushed() { return err } sf := streamformatter.NewJSONStreamFormatter() output.Write(sf.FormatError(err)) } return nil } func (s *Server) postImagesLoad(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { return s.daemon.Repositories().Load(r.Body, w) } func (s *Server) postContainersCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if err := checkForJson(r); err != nil { return err } var ( warnings []string name = r.Form.Get("name") ) config, hostConfig, err := runconfig.DecodeContainerConfig(r.Body) if err != nil { return err } adjustCpuShares(version, hostConfig) containerId, warnings, err := s.daemon.ContainerCreate(name, config, hostConfig) if err != nil { return err } return writeJSON(w, http.StatusCreated, &types.ContainerCreateResponse{ ID: containerId, Warnings: warnings, }) } func (s *Server) postContainersRestart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } timeout, _ := strconv.Atoi(r.Form.Get("t")) if err := s.daemon.ContainerRestart(vars["name"], timeout); err != nil { return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) postContainerRename(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } name := vars["name"] newName := r.Form.Get("name") if err := s.daemon.ContainerRename(name, newName); err != nil { return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) deleteContainers(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } name := vars["name"] config := &daemon.ContainerRmConfig{ ForceRemove: boolValue(r, "force"), RemoveVolume: boolValue(r, "v"), RemoveLink: boolValue(r, "link"), } if err := s.daemon.ContainerRm(name, config); err != nil { // Force a 404 for the empty string if strings.Contains(strings.ToLower(err.Error()), "prefix can't be empty") { return fmt.Errorf("no such id: \"\"") } return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) deleteImages(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } name := vars["name"] force := boolValue(r, "force") noprune := boolValue(r, "noprune") list, err := s.daemon.ImageDelete(name, force, noprune) if err != nil { return err } return writeJSON(w, http.StatusOK, list) } func (s *Server) postContainersStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } // If contentLength is -1, we can assumed chunked encoding // or more technically that the length is unknown // https://golang.org/src/pkg/net/http/request.go#L139 // net/http otherwise seems to swallow any headers related to chunked encoding // including r.TransferEncoding // allow a nil body for backwards compatibility var hostConfig *runconfig.HostConfig if r.Body != nil && (r.ContentLength > 0 || r.ContentLength == -1) { if err := checkForJson(r); err != nil { return err } c, err := runconfig.DecodeHostConfig(r.Body) if err != nil { return err } hostConfig = c } if err := s.daemon.ContainerStart(vars["name"], hostConfig); err != nil { if err.Error() == "Container already started" { w.WriteHeader(http.StatusNotModified) return nil } return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) postContainersStop(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } seconds, _ := strconv.Atoi(r.Form.Get("t")) if err := s.daemon.ContainerStop(vars["name"], seconds); err != nil { if err.Error() == "Container already stopped" { w.WriteHeader(http.StatusNotModified) return nil } return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) postContainersWait(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } status, err := s.daemon.ContainerWait(vars["name"], -1*time.Second) if err != nil { return err } return writeJSON(w, http.StatusOK, &types.ContainerWaitResponse{ StatusCode: status, }) } func (s *Server) postContainersResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } height, err := strconv.Atoi(r.Form.Get("h")) if err != nil { return err } width, err := strconv.Atoi(r.Form.Get("w")) if err != nil { return err } return s.daemon.ContainerResize(vars["name"], height, width) } func (s *Server) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } cont, err := s.daemon.Get(vars["name"]) if err != nil { return err } inStream, outStream, err := hijackServer(w) if err != nil { return err } defer closeStreams(inStream, outStream) if _, ok := r.Header["Upgrade"]; ok { fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n") } else { fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") } attachWithLogsConfig := &daemon.ContainerAttachWithLogsConfig{ InStream: inStream, OutStream: outStream, UseStdin: boolValue(r, "stdin"), UseStdout: boolValue(r, "stdout"), UseStderr: boolValue(r, "stderr"), Logs: boolValue(r, "logs"), Stream: boolValue(r, "stream"), } if err := s.daemon.ContainerAttachWithLogs(cont, attachWithLogsConfig); err != nil { fmt.Fprintf(outStream, "Error attaching: %s\n", err) } return nil } func (s *Server) wsContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } cont, err := s.daemon.Get(vars["name"]) if err != nil { return err } h := websocket.Handler(func(ws *websocket.Conn) { defer ws.Close() wsAttachWithLogsConfig := &daemon.ContainerWsAttachWithLogsConfig{ InStream: ws, OutStream: ws, ErrStream: ws, Logs: boolValue(r, "logs"), Stream: boolValue(r, "stream"), } if err := s.daemon.ContainerWsAttachWithLogs(cont, wsAttachWithLogsConfig); err != nil { logrus.Errorf("Error attaching websocket: %s", err) } }) h.ServeHTTP(w, r) return nil } func (s *Server) getContainersByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if version.LessThan("1.20") { containerJSONRaw, err := s.daemon.ContainerInspectPre120(vars["name"]) if err != nil { return err } return writeJSON(w, http.StatusOK, containerJSONRaw) } containerJSON, err := s.daemon.ContainerInspect(vars["name"]) if err != nil { return err } return writeJSON(w, http.StatusOK, containerJSON) } func (s *Server) getExecByID(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter 'id'") } eConfig, err := s.daemon.ContainerExecInspect(vars["id"]) if err != nil { return err } return writeJSON(w, http.StatusOK, eConfig) } func (s *Server) getImagesByName(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } imageInspect, err := s.daemon.Repositories().Lookup(vars["name"]) if err != nil { return err } return writeJSON(w, http.StatusOK, imageInspect) } func (s *Server) postBuild(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { var ( authConfigs = map[string]cliconfig.AuthConfig{} authConfigsEncoded = r.Header.Get("X-Registry-Config") buildConfig = builder.NewBuildConfig() ) if authConfigsEncoded != "" { authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded)) if err := json.NewDecoder(authConfigsJSON).Decode(&authConfigs); err != nil { // for a pull it is not an error if no auth was given // to increase compatibility with the existing api it is defaulting // to be empty. } } w.Header().Set("Content-Type", "application/json") if boolValue(r, "forcerm") && version.GreaterThanOrEqualTo("1.12") { buildConfig.Remove = true } else if r.FormValue("rm") == "" && version.GreaterThanOrEqualTo("1.12") { buildConfig.Remove = true } else { buildConfig.Remove = boolValue(r, "rm") } if boolValue(r, "pull") && version.GreaterThanOrEqualTo("1.16") { buildConfig.Pull = true } output := ioutils.NewWriteFlusher(w) buildConfig.Stdout = output buildConfig.Context = r.Body buildConfig.RemoteURL = r.FormValue("remote") buildConfig.DockerfileName = r.FormValue("dockerfile") buildConfig.RepoName = r.FormValue("t") buildConfig.SuppressOutput = boolValue(r, "q") buildConfig.NoCache = boolValue(r, "nocache") buildConfig.ForceRemove = boolValue(r, "forcerm") buildConfig.AuthConfigs = authConfigs buildConfig.MemorySwap = int64ValueOrZero(r, "memswap") buildConfig.Memory = int64ValueOrZero(r, "memory") buildConfig.CpuShares = int64ValueOrZero(r, "cpushares") buildConfig.CpuPeriod = int64ValueOrZero(r, "cpuperiod") buildConfig.CpuQuota = int64ValueOrZero(r, "cpuquota") buildConfig.CpuSetCpus = r.FormValue("cpusetcpus") buildConfig.CpuSetMems = r.FormValue("cpusetmems") buildConfig.CgroupParent = r.FormValue("cgroupparent") // Job cancellation. Note: not all job types support this. if closeNotifier, ok := w.(http.CloseNotifier); ok { finished := make(chan struct{}) defer close(finished) go func() { select { case <-finished: case <-closeNotifier.CloseNotify(): logrus.Infof("Client disconnected, cancelling job: build") buildConfig.Cancel() } }() } if err := builder.Build(s.daemon, buildConfig); err != nil { // Do not write the error in the http output if it's still empty. // This prevents from writing a 200(OK) when there is an interal error. if !output.Flushed() { return err } sf := streamformatter.NewJSONStreamFormatter() w.Write(sf.FormatError(err)) } return nil } // postContainersCopy is deprecated in favor of getContainersArchivePath. func (s *Server) postContainersCopy(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := checkForJson(r); err != nil { return err } cfg := types.CopyConfig{} if err := json.NewDecoder(r.Body).Decode(&cfg); err != nil { return err } if cfg.Resource == "" { return fmt.Errorf("Path cannot be empty") } data, err := s.daemon.ContainerCopy(vars["name"], cfg.Resource) if err != nil { if strings.Contains(strings.ToLower(err.Error()), "no such id") { w.WriteHeader(http.StatusNotFound) return nil } if os.IsNotExist(err) { return fmt.Errorf("Could not find the file %s in container %s", cfg.Resource, vars["name"]) } return err } defer data.Close() w.Header().Set("Content-Type", "application/x-tar") if _, err := io.Copy(w, data); err != nil { return err } return nil } // // Encode the stat to JSON, base64 encode, and place in a header. func setContainerPathStatHeader(stat *types.ContainerPathStat, header http.Header) error { statJSON, err := json.Marshal(stat) if err != nil { return err } header.Set( "X-Docker-Container-Path-Stat", base64.StdEncoding.EncodeToString(statJSON), ) return nil } func (s *Server) headContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } name := vars["name"] path := r.Form.Get("path") switch { case name == "": return fmt.Errorf("bad parameter: 'name' cannot be empty") case path == "": return fmt.Errorf("bad parameter: 'path' cannot be empty") } stat, err := s.daemon.ContainerStatPath(name, path) if err != nil { return err } return setContainerPathStatHeader(stat, w.Header()) } func (s *Server) getContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } name := vars["name"] path := r.Form.Get("path") switch { case name == "": return fmt.Errorf("bad parameter: 'name' cannot be empty") case path == "": return fmt.Errorf("bad parameter: 'path' cannot be empty") } tarArchive, stat, err := s.daemon.ContainerArchivePath(name, path) if err != nil { return err } defer tarArchive.Close() if err := setContainerPathStatHeader(stat, w.Header()); err != nil { return err } w.Header().Set("Content-Type", "application/x-tar") _, err = io.Copy(w, tarArchive) return err } func (s *Server) putContainersArchive(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if vars == nil { return fmt.Errorf("Missing parameter") } if err := parseForm(r); err != nil { return err } name := vars["name"] path := r.Form.Get("path") noOverwriteDirNonDir := boolValue(r, "noOverwriteDirNonDir") switch { case name == "": return fmt.Errorf("bad parameter: 'name' cannot be empty") case path == "": return fmt.Errorf("bad parameter: 'path' cannot be empty") } return s.daemon.ContainerExtractToDir(name, path, noOverwriteDirNonDir, r.Body) } func (s *Server) postContainerExecCreate(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if err := checkForJson(r); err != nil { return err } name := vars["name"] execConfig := &runconfig.ExecConfig{} if err := json.NewDecoder(r.Body).Decode(execConfig); err != nil { return err } execConfig.Container = name if len(execConfig.Cmd) == 0 { return fmt.Errorf("No exec command specified") } // Register an instance of Exec in container. id, err := s.daemon.ContainerExecCreate(execConfig) if err != nil { logrus.Errorf("Error setting up exec command in container %s: %s", name, err) return err } return writeJSON(w, http.StatusCreated, &types.ContainerExecCreateResponse{ ID: id, }) } // TODO(vishh): Refactor the code to avoid having to specify stream config as part of both create and start. func (s *Server) postContainerExecStart(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } var ( execName = vars["name"] stdin io.ReadCloser stdout io.Writer stderr io.Writer ) execStartCheck := &types.ExecStartCheck{} if err := json.NewDecoder(r.Body).Decode(execStartCheck); err != nil { return err } if !execStartCheck.Detach { // Setting up the streaming http interface. inStream, outStream, err := hijackServer(w) if err != nil { return err } defer closeStreams(inStream, outStream) var errStream io.Writer if _, ok := r.Header["Upgrade"]; ok { fmt.Fprintf(outStream, "HTTP/1.1 101 UPGRADED\r\nContent-Type: application/vnd.docker.raw-stream\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n") } else { fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") } if !execStartCheck.Tty { errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr) outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout) } stdin = inStream stdout = outStream stderr = errStream } // Now run the user process in container. if err := s.daemon.ContainerExecStart(execName, stdin, stdout, stderr); err != nil { logrus.Errorf("Error starting exec command in container %s: %s", execName, err) return err } w.WriteHeader(http.StatusNoContent) return nil } func (s *Server) postContainerExecResize(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { if err := parseForm(r); err != nil { return err } if vars == nil { return fmt.Errorf("Missing parameter") } height, err := strconv.Atoi(r.Form.Get("h")) if err != nil { return err } width, err := strconv.Atoi(r.Form.Get("w")) if err != nil { return err } return s.daemon.ContainerExecResize(vars["name"], height, width) } func (s *Server) optionsHandler(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { w.WriteHeader(http.StatusOK) return nil } func writeCorsHeaders(w http.ResponseWriter, r *http.Request, corsHeaders string) { logrus.Debugf("CORS header is enabled and set to: %s", corsHeaders) w.Header().Add("Access-Control-Allow-Origin", corsHeaders) w.Header().Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth") w.Header().Add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS") } func (s *Server) ping(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error { _, err := w.Write([]byte{'O', 'K'}) return err } func (s *Server) initTcpSocket(addr string) (l net.Listener, err error) { if s.cfg.TLSConfig == nil || s.cfg.TLSConfig.ClientAuth != tls.RequireAndVerifyClientCert { logrus.Warn("/!\\ DON'T BIND ON ANY IP ADDRESS WITHOUT setting -tlsverify IF YOU DON'T KNOW WHAT YOU'RE DOING /!\\") } if l, err = sockets.NewTcpSocket(addr, s.cfg.TLSConfig, s.start); err != nil { return nil, err } if err := allocateDaemonPort(addr); err != nil { return nil, err } return } func makeHttpHandler(logging bool, localMethod string, localRoute string, handlerFunc HttpApiFunc, corsHeaders string, dockerVersion version.Version) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // log the request logrus.Debugf("Calling %s %s", localMethod, localRoute) if logging { logrus.Infof("%s %s", r.Method, r.RequestURI) } if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") { userAgent := strings.Split(r.Header.Get("User-Agent"), "/") // v1.20 onwards includes the GOOS of the client after the version // such as Docker/1.7.0 (linux) if len(userAgent) == 2 && strings.Contains(userAgent[1], " ") { userAgent[1] = strings.Split(userAgent[1], " ")[0] } if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) { logrus.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion) } } version := version.Version(mux.Vars(r)["version"]) if version == "" { version = api.Version } if corsHeaders != "" { writeCorsHeaders(w, r, corsHeaders) } if version.GreaterThan(api.Version) { http.Error(w, fmt.Errorf("client is newer than server (client API version: %s, server API version: %s)", version, api.Version).Error(), http.StatusBadRequest) return } if version.LessThan(api.MinVersion) { http.Error(w, fmt.Errorf("client is too old, minimum supported API version is %s, please upgrade your client to a newer version", api.MinVersion).Error(), http.StatusBadRequest) return } w.Header().Set("Server", "Docker/"+dockerversion.VERSION+" ("+runtime.GOOS+")") if err := handlerFunc(version, w, r, mux.Vars(r)); err != nil { logrus.Errorf("Handler for %s %s returned error: %s", localMethod, localRoute, err) httpError(w, err) } } } // we keep enableCors just for legacy usage, need to be removed in the future func createRouter(s *Server) *mux.Router { r := mux.NewRouter() if os.Getenv("DEBUG") != "" { ProfilerSetup(r, "/debug/") } m := map[string]map[string]HttpApiFunc{ "HEAD": { "/containers/{name:.*}/archive": s.headContainersArchive, }, "GET": { "/_ping": s.ping, "/events": s.getEvents, "/info": s.getInfo, "/version": s.getVersion, "/images/json": s.getImagesJSON, "/images/search": s.getImagesSearch, "/images/get": s.getImagesGet, "/images/{name:.*}/get": s.getImagesGet, "/images/{name:.*}/history": s.getImagesHistory, "/images/{name:.*}/json": s.getImagesByName, "/containers/ps": s.getContainersJSON, "/containers/json": s.getContainersJSON, "/containers/{name:.*}/export": s.getContainersExport, "/containers/{name:.*}/changes": s.getContainersChanges, "/containers/{name:.*}/json": s.getContainersByName, "/containers/{name:.*}/top": s.getContainersTop, "/containers/{name:.*}/logs": s.getContainersLogs, "/containers/{name:.*}/stats": s.getContainersStats, "/containers/{name:.*}/attach/ws": s.wsContainersAttach, "/exec/{id:.*}/json": s.getExecByID, "/containers/{name:.*}/archive": s.getContainersArchive, }, "POST": { "/auth": s.postAuth, "/commit": s.postCommit, "/build": s.postBuild, "/images/create": s.postImagesCreate, "/images/load": s.postImagesLoad, "/images/{name:.*}/push": s.postImagesPush, "/images/{name:.*}/tag": s.postImagesTag, "/containers/create": s.postContainersCreate, "/containers/{name:.*}/kill": s.postContainersKill, "/containers/{name:.*}/pause": s.postContainersPause, "/containers/{name:.*}/unpause": s.postContainersUnpause, "/containers/{name:.*}/restart": s.postContainersRestart, "/containers/{name:.*}/start": s.postContainersStart, "/containers/{name:.*}/stop": s.postContainersStop, "/containers/{name:.*}/wait": s.postContainersWait, "/containers/{name:.*}/resize": s.postContainersResize, "/containers/{name:.*}/attach": s.postContainersAttach, "/containers/{name:.*}/copy": s.postContainersCopy, "/containers/{name:.*}/exec": s.postContainerExecCreate, "/exec/{name:.*}/start": s.postContainerExecStart, "/exec/{name:.*}/resize": s.postContainerExecResize, "/containers/{name:.*}/rename": s.postContainerRename, }, "PUT": { "/containers/{name:.*}/archive": s.putContainersArchive, }, "DELETE": { "/containers/{name:.*}": s.deleteContainers, "/images/{name:.*}": s.deleteImages, }, "OPTIONS": { "": s.optionsHandler, }, } // If "api-cors-header" is not given, but "api-enable-cors" is true, we set cors to "*" // otherwise, all head values will be passed to HTTP handler corsHeaders := s.cfg.CorsHeaders if corsHeaders == "" && s.cfg.EnableCors { corsHeaders = "*" } for method, routes := range m { for route, fct := range routes { logrus.Debugf("Registering %s, %s", method, route) // NOTE: scope issue, make sure the variables are local and won't be changed localRoute := route localFct := fct localMethod := method // build the handler function f := makeHttpHandler(s.cfg.Logging, localMethod, localRoute, localFct, corsHeaders, version.Version(s.cfg.Version)) // add the new route if localRoute == "" { r.Methods(localMethod).HandlerFunc(f) } else { r.Path("/v{version:[0-9.]+}" + localRoute).Methods(localMethod).HandlerFunc(f) r.Path(localRoute).Methods(localMethod).HandlerFunc(f) } } } return r } ================================================ FILE: vendor/github.com/docker/docker/api/server/server_experimental.go ================================================ // +build experimental package server func (s *Server) registerSubRouter() { httpHandler := s.daemon.NetworkApiRouter() subrouter := s.router.PathPrefix("/v{version:[0-9.]+}/networks").Subrouter() subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler) subrouter = s.router.PathPrefix("/networks").Subrouter() subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler) subrouter = s.router.PathPrefix("/v{version:[0-9.]+}/services").Subrouter() subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler) subrouter = s.router.PathPrefix("/services").Subrouter() subrouter.Methods("GET", "POST", "PUT", "DELETE").HandlerFunc(httpHandler) } ================================================ FILE: vendor/github.com/docker/docker/api/server/server_linux.go ================================================ // +build linux package server import ( "fmt" "net" "net/http" "strconv" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon" "github.com/docker/docker/pkg/sockets" "github.com/docker/docker/pkg/systemd" "github.com/docker/docker/pkg/version" "github.com/docker/docker/runconfig" "github.com/docker/libnetwork/portallocator" ) const ( // See http://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269 linuxMinCpuShares = 2 linuxMaxCpuShares = 262144 ) // newServer sets up the required serverClosers and does protocol specific checking. func (s *Server) newServer(proto, addr string) ([]serverCloser, error) { var ( err error ls []net.Listener ) switch proto { case "fd": ls, err = systemd.ListenFD(addr) if err != nil { return nil, err } // We don't want to start serving on these sockets until the // daemon is initialized and installed. Otherwise required handlers // won't be ready. <-s.start case "tcp": l, err := s.initTcpSocket(addr) if err != nil { return nil, err } ls = append(ls, l) case "unix": l, err := sockets.NewUnixSocket(addr, s.cfg.SocketGroup, s.start) if err != nil { return nil, err } ls = append(ls, l) default: return nil, fmt.Errorf("Invalid protocol format: %q", proto) } var res []serverCloser for _, l := range ls { res = append(res, &HttpServer{ &http.Server{ Addr: addr, Handler: s.router, }, l, }) } return res, nil } func (s *Server) AcceptConnections(d *daemon.Daemon) { // Tell the init daemon we are accepting requests s.daemon = d s.registerSubRouter() go systemd.SdNotify("READY=1") // close the lock so the listeners start accepting connections select { case <-s.start: default: close(s.start) } } func allocateDaemonPort(addr string) error { host, port, err := net.SplitHostPort(addr) if err != nil { return err } intPort, err := strconv.Atoi(port) if err != nil { return err } var hostIPs []net.IP if parsedIP := net.ParseIP(host); parsedIP != nil { hostIPs = append(hostIPs, parsedIP) } else if hostIPs, err = net.LookupIP(host); err != nil { return fmt.Errorf("failed to lookup %s address in host specification", host) } pa := portallocator.Get() for _, hostIP := range hostIPs { if _, err := pa.RequestPort(hostIP, "tcp", intPort); err != nil { return fmt.Errorf("failed to allocate daemon listening port %d (err: %v)", intPort, err) } } return nil } func adjustCpuShares(version version.Version, hostConfig *runconfig.HostConfig) { if version.LessThan("1.19") { if hostConfig.CpuShares > 0 { // Handle unsupported CpuShares if hostConfig.CpuShares < linuxMinCpuShares { logrus.Warnf("Changing requested CpuShares of %d to minimum allowed of %d", hostConfig.CpuShares, linuxMinCpuShares) hostConfig.CpuShares = linuxMinCpuShares } else if hostConfig.CpuShares > linuxMaxCpuShares { logrus.Warnf("Changing requested CpuShares of %d to maximum allowed of %d", hostConfig.CpuShares, linuxMaxCpuShares) hostConfig.CpuShares = linuxMaxCpuShares } } } } ================================================ FILE: vendor/github.com/docker/docker/api/server/server_linux_test.go ================================================ // +build linux package server import ( "testing" "github.com/docker/docker/pkg/version" "github.com/docker/docker/runconfig" ) func TestAdjustCpuSharesOldApi(t *testing.T) { apiVersion := version.Version("1.18") hostConfig := &runconfig.HostConfig{ CpuShares: linuxMinCpuShares - 1, } adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != linuxMinCpuShares { t.Errorf("Expected CpuShares to be %d", linuxMinCpuShares) } hostConfig.CpuShares = linuxMaxCpuShares + 1 adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != linuxMaxCpuShares { t.Errorf("Expected CpuShares to be %d", linuxMaxCpuShares) } hostConfig.CpuShares = 0 adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != 0 { t.Error("Expected CpuShares to be unchanged") } hostConfig.CpuShares = 1024 adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != 1024 { t.Error("Expected CpuShares to be unchanged") } } func TestAdjustCpuSharesNoAdjustment(t *testing.T) { apiVersion := version.Version("1.19") hostConfig := &runconfig.HostConfig{ CpuShares: linuxMinCpuShares - 1, } adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != linuxMinCpuShares-1 { t.Errorf("Expected CpuShares to be %d", linuxMinCpuShares-1) } hostConfig.CpuShares = linuxMaxCpuShares + 1 adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != linuxMaxCpuShares+1 { t.Errorf("Expected CpuShares to be %d", linuxMaxCpuShares+1) } hostConfig.CpuShares = 0 adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != 0 { t.Error("Expected CpuShares to be unchanged") } hostConfig.CpuShares = 1024 adjustCpuShares(apiVersion, hostConfig) if hostConfig.CpuShares != 1024 { t.Error("Expected CpuShares to be unchanged") } } ================================================ FILE: vendor/github.com/docker/docker/api/server/server_stub.go ================================================ // +build !experimental package server func (s *Server) registerSubRouter() { } ================================================ FILE: vendor/github.com/docker/docker/api/server/server_windows.go ================================================ // +build windows package server import ( "errors" "net" "net/http" "github.com/docker/docker/daemon" "github.com/docker/docker/pkg/version" "github.com/docker/docker/runconfig" ) // NewServer sets up the required Server and does protocol specific checking. func (s *Server) newServer(proto, addr string) ([]serverCloser, error) { var ( ls []net.Listener ) switch proto { case "tcp": l, err := s.initTcpSocket(addr) if err != nil { return nil, err } ls = append(ls, l) default: return nil, errors.New("Invalid protocol format. Windows only supports tcp.") } var res []serverCloser for _, l := range ls { res = append(res, &HttpServer{ &http.Server{ Addr: addr, Handler: s.router, }, l, }) } return res, nil } func (s *Server) AcceptConnections(d *daemon.Daemon) { s.daemon = d s.registerSubRouter() // close the lock so the listeners start accepting connections select { case <-s.start: default: close(s.start) } } func allocateDaemonPort(addr string) error { return nil } func adjustCpuShares(version version.Version, hostConfig *runconfig.HostConfig) { } ================================================ FILE: vendor/github.com/docker/docker/api/types/stats.go ================================================ // This package is used for API stability in the types and response to the // consumers of the API stats endpoint. package types import "time" type ThrottlingData struct { // Number of periods with throttling active Periods uint64 `json:"periods"` // Number of periods when the container hit its throttling limit. ThrottledPeriods uint64 `json:"throttled_periods"` // Aggregate time the container was throttled for in nanoseconds. ThrottledTime uint64 `json:"throttled_time"` } // All CPU stats are aggregated since container inception. type CpuUsage struct { // Total CPU time consumed. // Units: nanoseconds. TotalUsage uint64 `json:"total_usage"` // Total CPU time consumed per core. // Units: nanoseconds. PercpuUsage []uint64 `json:"percpu_usage"` // 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"` SystemUsage uint64 `json:"system_cpu_usage"` ThrottlingData ThrottlingData `json:"throttling_data,omitempty"` } type MemoryStats struct { // current res_counter usage for memory Usage uint64 `json:"usage"` // maximum usage ever recorded. MaxUsage uint64 `json:"max_usage"` // TODO(vishh): Export these as stronger types. // all the stats exported via memory.stat. Stats map[string]uint64 `json:"stats"` // number of times memory usage hits limits. Failcnt uint64 `json:"failcnt"` Limit uint64 `json:"limit"` } // TODO Windows: This can be factored out type BlkioStatEntry struct { Major uint64 `json:"major"` Minor uint64 `json:"minor"` Op string `json:"op"` Value uint64 `json:"value"` } // TODO Windows: This can be factored out type BlkioStats struct { // number of bytes tranferred to and from the block device IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"` IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive"` IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive"` IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive"` IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive"` IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive"` IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive"` SectorsRecursive []BlkioStatEntry `json:"sectors_recursive"` } // TODO Windows: This will require refactoring type Network struct { RxBytes uint64 `json:"rx_bytes"` RxPackets uint64 `json:"rx_packets"` RxErrors uint64 `json:"rx_errors"` RxDropped uint64 `json:"rx_dropped"` TxBytes uint64 `json:"tx_bytes"` TxPackets uint64 `json:"tx_packets"` TxErrors uint64 `json:"tx_errors"` TxDropped uint64 `json:"tx_dropped"` } type Stats struct { Read time.Time `json:"read"` Network Network `json:"network,omitempty"` PreCpuStats CpuStats `json:"precpu_stats,omitempty"` CpuStats CpuStats `json:"cpu_stats,omitempty"` MemoryStats MemoryStats `json:"memory_stats,omitempty"` BlkioStats BlkioStats `json:"blkio_stats,omitempty"` } ================================================ FILE: vendor/github.com/docker/docker/api/types/types.go ================================================ package types import ( "os" "time" "github.com/docker/docker/daemon/network" "github.com/docker/docker/pkg/version" "github.com/docker/docker/runconfig" ) // ContainerCreateResponse contains the information returned to a client on the // creation of a new container. type ContainerCreateResponse struct { // ID is the ID of the created container. ID string `json:"Id"` // Warnings are any warnings encountered during the creation of the container. Warnings []string `json:"Warnings"` } // POST /containers/{name:.*}/exec type ContainerExecCreateResponse struct { // ID is the exec ID. ID string `json:"Id"` } // POST /auth type AuthResponse struct { // Status is the authentication status Status string `json:"Status"` } // POST "/containers/"+containerID+"/wait" type ContainerWaitResponse struct { // StatusCode is the status code of the wait job StatusCode int `json:"StatusCode"` } // POST "/commit?container="+containerID type ContainerCommitResponse struct { ID string `json:"Id"` } // GET "/containers/{name:.*}/changes" type ContainerChange struct { Kind int Path string } // GET "/images/{name:.*}/history" type ImageHistory struct { ID string `json:"Id"` Created int64 CreatedBy string Tags []string Size int64 Comment string } // DELETE "/images/{name:.*}" type ImageDelete struct { Untagged string `json:",omitempty"` Deleted string `json:",omitempty"` } // GET "/images/json" type Image struct { ID string `json:"Id"` ParentId string RepoTags []string RepoDigests []string Created int Size int VirtualSize int Labels map[string]string } type GraphDriverData struct { Name string Data map[string]string } // GET "/images/{name:.*}/json" type ImageInspect struct { Id string Parent string Comment string Created time.Time Container string ContainerConfig *runconfig.Config DockerVersion string Author string Config *runconfig.Config Architecture string Os string Size int64 VirtualSize int64 GraphDriver GraphDriverData } // GET "/containers/json" type Port struct { IP string `json:",omitempty"` PrivatePort int PublicPort int `json:",omitempty"` Type string } type Container struct { ID string `json:"Id"` Names []string Image string Command string Created int Ports []Port SizeRw int `json:",omitempty"` SizeRootFs int `json:",omitempty"` Labels map[string]string Status string HostConfig struct { NetworkMode string `json:",omitempty"` } } // POST "/containers/"+containerID+"/copy" type CopyConfig struct { Resource string } // ContainerPathStat is used to encode the header from // GET /containers/{name:.*}/archive // "name" is the file or directory name. // "path" is the absolute path to the resource in the container. type ContainerPathStat struct { Name string `json:"name"` Path string `json:"path"` Size int64 `json:"size"` Mode os.FileMode `json:"mode"` Mtime time.Time `json:"mtime"` } // GET "/containers/{name:.*}/top" type ContainerProcessList struct { Processes [][]string Titles []string } type Version struct { Version string ApiVersion version.Version GitCommit string GoVersion string Os string Arch string KernelVersion string `json:",omitempty"` Experimental bool `json:",omitempty"` BuildTime string `json:",omitempty"` } // GET "/info" type Info struct { ID string Containers int Images int Driver string DriverStatus [][2]string MemoryLimit bool SwapLimit bool CpuCfsPeriod bool CpuCfsQuota bool IPv4Forwarding bool BridgeNfIptables bool BridgeNfIp6tables bool Debug bool NFd int OomKillDisable bool NGoroutines int SystemTime string ExecutionDriver string LoggingDriver string NEventsListener int KernelVersion string OperatingSystem string IndexServerAddress string RegistryConfig interface{} InitSha1 string InitPath string NCPU int MemTotal int64 DockerRootDir string HttpProxy string HttpsProxy string NoProxy string Name string Labels []string ExperimentalBuild bool } // This struct is a temp struct used by execStart // Config fields is part of ExecConfig in runconfig package type ExecStartCheck struct { // ExecStart will first check if it's detached Detach bool // Check if there's a tty Tty bool } type ContainerState struct { Running bool Paused bool Restarting bool OOMKilled bool Dead bool Pid int ExitCode int Error string StartedAt time.Time FinishedAt time.Time } // GET "/containers/{name:.*}/json" type ContainerJSONBase struct { Id string Created time.Time Path string Args []string State *ContainerState Image string NetworkSettings *network.Settings ResolvConfPath string HostnamePath string HostsPath string LogPath string Name string RestartCount int Driver string ExecDriver string MountLabel string ProcessLabel string AppArmorProfile string ExecIDs []string HostConfig *runconfig.HostConfig GraphDriver GraphDriverData } type ContainerJSON struct { *ContainerJSONBase Mounts []MountPoint Config *runconfig.Config } // backcompatibility struct along with ContainerConfig type ContainerJSONPre120 struct { *ContainerJSONBase Volumes map[string]string VolumesRW map[string]bool Config *ContainerConfig } type ContainerConfig struct { *runconfig.Config // backward compatibility, they now live in HostConfig Memory int64 MemorySwap int64 CpuShares int64 Cpuset string } // MountPoint represents a mount point configuration inside the container. type MountPoint struct { Name string `json:",omitempty"` Source string Destination string Driver string `json:",omitempty"` Mode string // this is internally named `Relabel` RW bool } ================================================ FILE: vendor/github.com/docker/docker/builder/bflag.go ================================================ package builder import ( "fmt" "strings" ) type FlagType int const ( boolType FlagType = iota stringType ) type BuilderFlags struct { Args []string // actual flags/args from cmd line flags map[string]*Flag used map[string]*Flag Err error } type Flag struct { bf *BuilderFlags name string flagType FlagType Value string } func NewBuilderFlags() *BuilderFlags { return &BuilderFlags{ flags: make(map[string]*Flag), used: make(map[string]*Flag), } } func (bf *BuilderFlags) AddBool(name string, def bool) *Flag { flag := bf.addFlag(name, boolType) if flag == nil { return nil } if def { flag.Value = "true" } else { flag.Value = "false" } return flag } func (bf *BuilderFlags) AddString(name string, def string) *Flag { flag := bf.addFlag(name, stringType) if flag == nil { return nil } flag.Value = def return flag } func (bf *BuilderFlags) addFlag(name string, flagType FlagType) *Flag { if _, ok := bf.flags[name]; ok { bf.Err = fmt.Errorf("Duplicate flag defined: %s", name) return nil } newFlag := &Flag{ bf: bf, name: name, flagType: flagType, } bf.flags[name] = newFlag return newFlag } func (fl *Flag) IsUsed() bool { if _, ok := fl.bf.used[fl.name]; ok { return true } return false } func (fl *Flag) IsTrue() bool { if fl.flagType != boolType { // Should never get here panic(fmt.Errorf("Trying to use IsTrue on a non-boolean: %s", fl.name)) } return fl.Value == "true" } func (bf *BuilderFlags) Parse() error { // If there was an error while defining the possible flags // go ahead and bubble it back up here since we didn't do it // earlier in the processing if bf.Err != nil { return fmt.Errorf("Error setting up flags: %s", bf.Err) } for _, arg := range bf.Args { if !strings.HasPrefix(arg, "--") { return fmt.Errorf("Arg should start with -- : %s", arg) } if arg == "--" { return nil } arg = arg[2:] value := "" index := strings.Index(arg, "=") if index >= 0 { value = arg[index+1:] arg = arg[:index] } flag, ok := bf.flags[arg] if !ok { return fmt.Errorf("Unknown flag: %s", arg) } if _, ok = bf.used[arg]; ok { return fmt.Errorf("Duplicate flag specified: %s", arg) } bf.used[arg] = flag switch flag.flagType { case boolType: // value == "" is only ok if no "=" was specified if index >= 0 && value == "" { return fmt.Errorf("Missing a value on flag: %s", arg) } lower := strings.ToLower(value) if lower == "" { flag.Value = "true" } else if lower == "true" || lower == "false" { flag.Value = lower } else { return fmt.Errorf("Expecting boolean value for flag %s, not: %s", arg, value) } case stringType: if index < 0 { return fmt.Errorf("Missing a value on flag: %s", arg) } flag.Value = value default: panic(fmt.Errorf("No idea what kind of flag we have! Should never get here!")) } } return nil } ================================================ FILE: vendor/github.com/docker/docker/builder/bflag_test.go ================================================ package builder import ( "testing" ) func TestBuilderFlags(t *testing.T) { var expected string var err error // --- bf := NewBuilderFlags() bf.Args = []string{} if err := bf.Parse(); err != nil { t.Fatalf("Test1 of %q was supposed to work: %s", bf.Args, err) } // --- bf = NewBuilderFlags() bf.Args = []string{"--"} if err := bf.Parse(); err != nil { t.Fatalf("Test2 of %q was supposed to work: %s", bf.Args, err) } // --- bf = NewBuilderFlags() flStr1 := bf.AddString("str1", "") flBool1 := bf.AddBool("bool1", false) bf.Args = []string{} if err = bf.Parse(); err != nil { t.Fatalf("Test3 of %q was supposed to work: %s", bf.Args, err) } if flStr1.IsUsed() == true { t.Fatalf("Test3 - str1 was not used!") } if flBool1.IsUsed() == true { t.Fatalf("Test3 - bool1 was not used!") } // --- bf = NewBuilderFlags() flStr1 = bf.AddString("str1", "HI") flBool1 = bf.AddBool("bool1", false) bf.Args = []string{} if err = bf.Parse(); err != nil { t.Fatalf("Test4 of %q was supposed to work: %s", bf.Args, err) } if flStr1.Value != "HI" { t.Fatalf("Str1 was supposed to default to: HI") } if flBool1.IsTrue() { t.Fatalf("Bool1 was supposed to default to: false") } if flStr1.IsUsed() == true { t.Fatalf("Str1 was not used!") } if flBool1.IsUsed() == true { t.Fatalf("Bool1 was not used!") } // --- bf = NewBuilderFlags() flStr1 = bf.AddString("str1", "HI") bf.Args = []string{"--str1"} if err = bf.Parse(); err == nil { t.Fatalf("Test %q was supposed to fail", bf.Args) } // --- bf = NewBuilderFlags() flStr1 = bf.AddString("str1", "HI") bf.Args = []string{"--str1="} if err = bf.Parse(); err != nil { t.Fatalf("Test %q was supposed to work: %s", bf.Args, err) } expected = "" if flStr1.Value != expected { t.Fatalf("Str1 (%q) should be: %q", flStr1.Value, expected) } // --- bf = NewBuilderFlags() flStr1 = bf.AddString("str1", "HI") bf.Args = []string{"--str1=BYE"} if err = bf.Parse(); err != nil { t.Fatalf("Test %q was supposed to work: %s", bf.Args, err) } expected = "BYE" if flStr1.Value != expected { t.Fatalf("Str1 (%q) should be: %q", flStr1.Value, expected) } // --- bf = NewBuilderFlags() flBool1 = bf.AddBool("bool1", false) bf.Args = []string{"--bool1"} if err = bf.Parse(); err != nil { t.Fatalf("Test %q was supposed to work: %s", bf.Args, err) } if !flBool1.IsTrue() { t.Fatalf("Test-b1 Bool1 was supposed to be true") } // --- bf = NewBuilderFlags() flBool1 = bf.AddBool("bool1", false) bf.Args = []string{"--bool1=true"} if err = bf.Parse(); err != nil { t.Fatalf("Test %q was supposed to work: %s", bf.Args, err) } if !flBool1.IsTrue() { t.Fatalf("Test-b2 Bool1 was supposed to be true") } // --- bf = NewBuilderFlags() flBool1 = bf.AddBool("bool1", false) bf.Args = []string{"--bool1=false"} if err = bf.Parse(); err != nil { t.Fatalf("Test %q was supposed to work: %s", bf.Args, err) } if flBool1.IsTrue() { t.Fatalf("Test-b3 Bool1 was supposed to be false") } // --- bf = NewBuilderFlags() flBool1 = bf.AddBool("bool1", false) bf.Args = []string{"--bool1=false1"} if err = bf.Parse(); err == nil { t.Fatalf("Test %q was supposed to fail", bf.Args) } // --- bf = NewBuilderFlags() flBool1 = bf.AddBool("bool1", false) bf.Args = []string{"--bool2"} if err = bf.Parse(); err == nil { t.Fatalf("Test %q was supposed to fail", bf.Args) } // --- bf = NewBuilderFlags() flStr1 = bf.AddString("str1", "HI") flBool1 = bf.AddBool("bool1", false) bf.Args = []string{"--bool1", "--str1=BYE"} if err = bf.Parse(); err != nil { t.Fatalf("Test %q was supposed to work: %s", bf.Args, err) } if flStr1.Value != "BYE" { t.Fatalf("Teset %s, str1 should be BYE", bf.Args) } if !flBool1.IsTrue() { t.Fatalf("Teset %s, bool1 should be true", bf.Args) } } ================================================ FILE: vendor/github.com/docker/docker/builder/command/command.go ================================================ // This package contains the set of Dockerfile commands. package command const ( Env = "env" Label = "label" Maintainer = "maintainer" Add = "add" Copy = "copy" From = "from" Onbuild = "onbuild" Workdir = "workdir" Run = "run" Cmd = "cmd" Entrypoint = "entrypoint" Expose = "expose" Volume = "volume" User = "user" ) // Commands is list of all Dockerfile commands var Commands = map[string]struct{}{ Env: {}, Label: {}, Maintainer: {}, Add: {}, Copy: {}, From: {}, Onbuild: {}, Workdir: {}, Run: {}, Cmd: {}, Entrypoint: {}, Expose: {}, Volume: {}, User: {}, } ================================================ FILE: vendor/github.com/docker/docker/builder/dispatchers.go ================================================ package builder // This file contains the dispatchers for each command. Note that // `nullDispatch` is not actually a command, but support for commands we parse // but do nothing with. // // See evaluator.go for a higher level discussion of the whole evaluator // package. import ( "fmt" "io/ioutil" "path" "path/filepath" "regexp" "runtime" "sort" "strings" "github.com/Sirupsen/logrus" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/runconfig" ) const ( // NoBaseImageSpecifier is the symbol used by the FROM // command to specify that no base image is to be used. NoBaseImageSpecifier string = "scratch" ) // dispatch with no layer / parsing. This is effectively not a command. func nullDispatch(b *Builder, args []string, attributes map[string]bool, original string) error { return nil } // ENV foo bar // // Sets the environment variable foo to bar, also makes interpolation // in the dockerfile available from the next statement on via ${foo}. // func env(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) == 0 { return fmt.Errorf("ENV requires at least one argument") } if len(args)%2 != 0 { // should never get here, but just in case return fmt.Errorf("Bad input to ENV, too many args") } if err := b.BuilderFlags.Parse(); err != nil { return err } // TODO/FIXME/NOT USED // Just here to show how to use the builder flags stuff within the // context of a builder command. Will remove once we actually add // a builder command to something! /* flBool1 := b.BuilderFlags.AddBool("bool1", false) flStr1 := b.BuilderFlags.AddString("str1", "HI") if err := b.BuilderFlags.Parse(); err != nil { return err } fmt.Printf("Bool1:%v\n", flBool1) fmt.Printf("Str1:%v\n", flStr1) */ commitStr := "ENV" for j := 0; j < len(args); j++ { // name ==> args[j] // value ==> args[j+1] newVar := args[j] + "=" + args[j+1] + "" commitStr += " " + newVar gotOne := false for i, envVar := range b.Config.Env { envParts := strings.SplitN(envVar, "=", 2) if envParts[0] == args[j] { b.Config.Env[i] = newVar gotOne = true break } } if !gotOne { b.Config.Env = append(b.Config.Env, newVar) } j++ } return b.commit("", b.Config.Cmd, commitStr) } // MAINTAINER some text // // Sets the maintainer metadata. func maintainer(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) != 1 { return fmt.Errorf("MAINTAINER requires exactly one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } b.maintainer = args[0] return b.commit("", b.Config.Cmd, fmt.Sprintf("MAINTAINER %s", b.maintainer)) } // LABEL some json data describing the image // // Sets the Label variable foo to bar, // func label(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) == 0 { return fmt.Errorf("LABEL requires at least one argument") } if len(args)%2 != 0 { // should never get here, but just in case return fmt.Errorf("Bad input to LABEL, too many args") } if err := b.BuilderFlags.Parse(); err != nil { return err } commitStr := "LABEL" if b.Config.Labels == nil { b.Config.Labels = map[string]string{} } for j := 0; j < len(args); j++ { // name ==> args[j] // value ==> args[j+1] newVar := args[j] + "=" + args[j+1] + "" commitStr += " " + newVar b.Config.Labels[args[j]] = args[j+1] j++ } return b.commit("", b.Config.Cmd, commitStr) } // ADD foo /path // // Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling // exist here. If you do not wish to have this automatic handling, use COPY. // func add(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) < 2 { return fmt.Errorf("ADD requires at least two arguments") } if err := b.BuilderFlags.Parse(); err != nil { return err } return b.runContextCommand(args, true, true, "ADD") } // COPY foo /path // // Same as 'ADD' but without the tar and remote url handling. // func dispatchCopy(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) < 2 { return fmt.Errorf("COPY requires at least two arguments") } if err := b.BuilderFlags.Parse(); err != nil { return err } return b.runContextCommand(args, false, false, "COPY") } // FROM imagename // // This sets the image the dockerfile will build on top of. // func from(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) != 1 { return fmt.Errorf("FROM requires one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } name := args[0] if name == NoBaseImageSpecifier { b.image = "" b.noBaseImage = true return nil } image, err := b.Daemon.Repositories().LookupImage(name) if b.Pull { image, err = b.pullImage(name) if err != nil { return err } } if err != nil { if b.Daemon.Graph().IsNotExist(err, name) { image, err = b.pullImage(name) } // note that the top level err will still be !nil here if IsNotExist is // not the error. This approach just simplifies the logic a bit. if err != nil { return err } } return b.processImageFrom(image) } // ONBUILD RUN echo yo // // ONBUILD triggers run when the image is used in a FROM statement. // // ONBUILD handling has a lot of special-case functionality, the heading in // evaluator.go and comments around dispatch() in the same file explain the // special cases. search for 'OnBuild' in internals.go for additional special // cases. // func onbuild(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) == 0 { return fmt.Errorf("ONBUILD requires at least one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0])) switch triggerInstruction { case "ONBUILD": return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") case "MAINTAINER", "FROM": return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction) } original = regexp.MustCompile(`(?i)^\s*ONBUILD\s*`).ReplaceAllString(original, "") b.Config.OnBuild = append(b.Config.OnBuild, original) return b.commit("", b.Config.Cmd, fmt.Sprintf("ONBUILD %s", original)) } // WORKDIR /tmp // // Set the working directory for future RUN/CMD/etc statements. // func workdir(b *Builder, args []string, attributes map[string]bool, original string) error { if len(args) != 1 { return fmt.Errorf("WORKDIR requires exactly one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } // Note that workdir passed comes from the Dockerfile. Hence it is in // Linux format using forward-slashes, even on Windows. However, // b.Config.WorkingDir is in platform-specific notation (in other words // on Windows will use `\` workdir := args[0] isAbs := false if runtime.GOOS == "windows" { // Alternate processing for Windows here is necessary as we can't call // filepath.IsAbs(workDir) as that would verify Windows style paths, // along with drive-letters (eg c:\pathto\file.txt). We (arguably // correctly or not) check for both forward and back slashes as this // is what the 1.4.2 GoLang implementation of IsAbs() does in the // isSlash() function. isAbs = workdir[0] == '\\' || workdir[0] == '/' } else { isAbs = filepath.IsAbs(workdir) } if !isAbs { current := b.Config.WorkingDir if runtime.GOOS == "windows" { // Convert to Linux format before join current = strings.Replace(current, "\\", "/", -1) } // Must use path.Join so works correctly on Windows, not filepath workdir = path.Join("/", current, workdir) } // Convert to platform specific format if runtime.GOOS == "windows" { workdir = strings.Replace(workdir, "/", "\\", -1) } b.Config.WorkingDir = workdir return b.commit("", b.Config.Cmd, fmt.Sprintf("WORKDIR %v", workdir)) } // RUN some command yo // // run a command and commit the image. Args are automatically prepended with // 'sh -c' under linux or 'cmd /S /C' under Windows, in the event there is // only one argument. The difference in processing: // // RUN echo hi # sh -c echo hi (Linux) // RUN echo hi # cmd /S /C echo hi (Windows) // RUN [ "echo", "hi" ] # echo hi // func run(b *Builder, args []string, attributes map[string]bool, original string) error { if b.image == "" && !b.noBaseImage { return fmt.Errorf("Please provide a source image with `from` prior to run") } if err := b.BuilderFlags.Parse(); err != nil { return err } args = handleJsonArgs(args, attributes) if !attributes["json"] { if runtime.GOOS != "windows" { args = append([]string{"/bin/sh", "-c"}, args...) } else { args = append([]string{"cmd", "/S /C"}, args...) } } runCmd := flag.NewFlagSet("run", flag.ContinueOnError) runCmd.SetOutput(ioutil.Discard) runCmd.Usage = nil config, _, _, err := runconfig.Parse(runCmd, append([]string{b.image}, args...)) if err != nil { return err } cmd := b.Config.Cmd // set Cmd manually, this is special case only for Dockerfiles b.Config.Cmd = config.Cmd runconfig.Merge(b.Config, config) defer func(cmd *runconfig.Command) { b.Config.Cmd = cmd }(cmd) logrus.Debugf("[BUILDER] Command to be executed: %v", b.Config.Cmd) hit, err := b.probeCache() if err != nil { return err } if hit { return nil } c, err := b.create() if err != nil { return err } // Ensure that we keep the container mounted until the commit // to avoid unmounting and then mounting directly again c.Mount() defer c.Unmount() err = b.run(c) if err != nil { return err } if err := b.commit(c.ID, cmd, "run"); err != nil { return err } return nil } // CMD foo // // Set the default command to run in the container (which may be empty). // Argument handling is the same as RUN. // func cmd(b *Builder, args []string, attributes map[string]bool, original string) error { if err := b.BuilderFlags.Parse(); err != nil { return err } cmdSlice := handleJsonArgs(args, attributes) if !attributes["json"] { if runtime.GOOS != "windows" { cmdSlice = append([]string{"/bin/sh", "-c"}, cmdSlice...) } else { cmdSlice = append([]string{"cmd", "/S /C"}, cmdSlice...) } } b.Config.Cmd = runconfig.NewCommand(cmdSlice...) if err := b.commit("", b.Config.Cmd, fmt.Sprintf("CMD %q", cmdSlice)); err != nil { return err } if len(args) != 0 { b.cmdSet = true } return nil } // ENTRYPOINT /usr/sbin/nginx // // Set the entrypoint (which defaults to sh -c on linux, or cmd /S /C on Windows) to // /usr/sbin/nginx. Will accept the CMD as the arguments to /usr/sbin/nginx. // // Handles command processing similar to CMD and RUN, only b.Config.Entrypoint // is initialized at NewBuilder time instead of through argument parsing. // func entrypoint(b *Builder, args []string, attributes map[string]bool, original string) error { if err := b.BuilderFlags.Parse(); err != nil { return err } parsed := handleJsonArgs(args, attributes) switch { case attributes["json"]: // ENTRYPOINT ["echo", "hi"] b.Config.Entrypoint = runconfig.NewEntrypoint(parsed...) case len(parsed) == 0: // ENTRYPOINT [] b.Config.Entrypoint = nil default: // ENTRYPOINT echo hi if runtime.GOOS != "windows" { b.Config.Entrypoint = runconfig.NewEntrypoint("/bin/sh", "-c", parsed[0]) } else { b.Config.Entrypoint = runconfig.NewEntrypoint("cmd", "/S /C", parsed[0]) } } // when setting the entrypoint if a CMD was not explicitly set then // set the command to nil if !b.cmdSet { b.Config.Cmd = nil } if err := b.commit("", b.Config.Cmd, fmt.Sprintf("ENTRYPOINT %q", b.Config.Entrypoint)); err != nil { return err } return nil } // EXPOSE 6667/tcp 7000/tcp // // Expose ports for links and port mappings. This all ends up in // b.Config.ExposedPorts for runconfig. // func expose(b *Builder, args []string, attributes map[string]bool, original string) error { portsTab := args if len(args) == 0 { return fmt.Errorf("EXPOSE requires at least one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } if b.Config.ExposedPorts == nil { b.Config.ExposedPorts = make(nat.PortSet) } ports, _, err := nat.ParsePortSpecs(portsTab) if err != nil { return err } // instead of using ports directly, we build a list of ports and sort it so // the order is consistent. This prevents cache burst where map ordering // changes between builds portList := make([]string, len(ports)) var i int for port := range ports { if _, exists := b.Config.ExposedPorts[port]; !exists { b.Config.ExposedPorts[port] = struct{}{} } portList[i] = string(port) i++ } sort.Strings(portList) return b.commit("", b.Config.Cmd, fmt.Sprintf("EXPOSE %s", strings.Join(portList, " "))) } // USER foo // // Set the user to 'foo' for future commands and when running the // ENTRYPOINT/CMD at container run time. // func user(b *Builder, args []string, attributes map[string]bool, original string) error { if runtime.GOOS == "windows" { return fmt.Errorf("USER is not supported on Windows.") } if len(args) != 1 { return fmt.Errorf("USER requires exactly one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } b.Config.User = args[0] return b.commit("", b.Config.Cmd, fmt.Sprintf("USER %v", args)) } // VOLUME /foo // // Expose the volume /foo for use. Will also accept the JSON array form. // func volume(b *Builder, args []string, attributes map[string]bool, original string) error { if runtime.GOOS == "windows" { return fmt.Errorf("VOLUME is not supported on Windows.") } if len(args) == 0 { return fmt.Errorf("VOLUME requires at least one argument") } if err := b.BuilderFlags.Parse(); err != nil { return err } if b.Config.Volumes == nil { b.Config.Volumes = map[string]struct{}{} } for _, v := range args { v = strings.TrimSpace(v) if v == "" { return fmt.Errorf("Volume specified can not be an empty string") } b.Config.Volumes[v] = struct{}{} } if err := b.commit("", b.Config.Cmd, fmt.Sprintf("VOLUME %v", args)); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/builder/evaluator.go ================================================ // Package builder is the evaluation step in the Dockerfile parse/evaluate pipeline. // // It incorporates a dispatch table based on the parser.Node values (see the // parser package for more information) that are yielded from the parser itself. // Calling NewBuilder with the BuildOpts struct can be used to customize the // experience for execution purposes only. Parsing is controlled in the parser // package, and this division of resposibility should be respected. // // Please see the jump table targets for the actual invocations, most of which // will call out to the functions in internals.go to deal with their tasks. // // ONBUILD is a special case, which is covered in the onbuild() func in // dispatchers.go. // // The evaluator uses the concept of "steps", which are usually each processable // line in the Dockerfile. Each step is numbered and certain actions are taken // before and after each step, such as creating an image ID and removing temporary // containers and images. Note that ONBUILD creates a kinda-sorta "sub run" which // includes its own set of steps (usually only one of them). package builder import ( "fmt" "io" "os" "path/filepath" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/api" "github.com/docker/docker/builder/command" "github.com/docker/docker/builder/parser" "github.com/docker/docker/cliconfig" "github.com/docker/docker/daemon" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/symlink" "github.com/docker/docker/pkg/tarsum" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) // Environment variable interpolation will happen on these statements only. var replaceEnvAllowed = map[string]struct{}{ command.Env: {}, command.Label: {}, command.Add: {}, command.Copy: {}, command.Workdir: {}, command.Expose: {}, command.Volume: {}, command.User: {}, } var evaluateTable map[string]func(*Builder, []string, map[string]bool, string) error func init() { evaluateTable = map[string]func(*Builder, []string, map[string]bool, string) error{ command.Env: env, command.Label: label, command.Maintainer: maintainer, command.Add: add, command.Copy: dispatchCopy, // copy() is a go builtin command.From: from, command.Onbuild: onbuild, command.Workdir: workdir, command.Run: run, command.Cmd: cmd, command.Entrypoint: entrypoint, command.Expose: expose, command.Volume: volume, command.User: user, } } // internal struct, used to maintain configuration of the Dockerfile's // processing as it evaluates the parsing result. type Builder struct { Daemon *daemon.Daemon // effectively stdio for the run. Because it is not stdio, I said // "Effectively". Do not use stdio anywhere in this package for any reason. OutStream io.Writer ErrStream io.Writer Verbose bool UtilizeCache bool cacheBusted bool // controls how images and containers are handled between steps. Remove bool ForceRemove bool Pull bool // set this to true if we want the builder to not commit between steps. // This is useful when we only want to use the evaluator table to generate // the final configs of the Dockerfile but dont want the layers disableCommit bool // Registry server auth configs used to pull images when handling `FROM`. AuthConfigs map[string]cliconfig.AuthConfig // Deprecated, original writer used for ImagePull. To be removed. OutOld io.Writer StreamFormatter *streamformatter.StreamFormatter Config *runconfig.Config // runconfig for cmd, run, entrypoint etc. // both of these are controlled by the Remove and ForceRemove options in BuildOpts TmpContainers map[string]struct{} // a map of containers used for removes dockerfileName string // name of Dockerfile dockerfile *parser.Node // the syntax tree of the dockerfile image string // image name for commit processing maintainer string // maintainer name. could probably be removed. cmdSet bool // indicates is CMD was set in current Dockerfile BuilderFlags *BuilderFlags // current cmd's BuilderFlags - temporary context tarsum.TarSum // the context is a tarball that is uploaded by the client contextPath string // the path of the temporary directory the local context is unpacked to (server side) noBaseImage bool // indicates that this build does not start from any base image, but is being built from an empty file system. // Set resource restrictions for build containers cpuSetCpus string cpuSetMems string cpuShares int64 cpuPeriod int64 cpuQuota int64 cgroupParent string memory int64 memorySwap int64 cancelled <-chan struct{} // When closed, job was cancelled. activeImages []string id string // Used to hold reference images } // Run the builder with the context. This is the lynchpin of this package. This // will (barring errors): // // * call readContext() which will set up the temporary directory and unpack // the context into it. // * read the dockerfile // * parse the dockerfile // * walk the parse tree and execute it by dispatching to handlers. If Remove // or ForceRemove is set, additional cleanup around containers happens after // processing. // * Print a happy message and return the image ID. // func (b *Builder) Run(context io.Reader) (string, error) { if err := b.readContext(context); err != nil { return "", err } defer func() { if err := os.RemoveAll(b.contextPath); err != nil { logrus.Debugf("[BUILDER] failed to remove temporary context: %s", err) } }() if err := b.readDockerfile(); err != nil { return "", err } // some initializations that would not have been supplied by the caller. b.Config = &runconfig.Config{} b.TmpContainers = map[string]struct{}{} for i, n := range b.dockerfile.Children { select { case <-b.cancelled: logrus.Debug("Builder: build cancelled!") fmt.Fprintf(b.OutStream, "Build cancelled") return "", fmt.Errorf("Build cancelled") default: // Not cancelled yet, keep going... } if err := b.dispatch(i, n); err != nil { if b.ForceRemove { b.clearTmp() } return "", err } fmt.Fprintf(b.OutStream, " ---> %s\n", stringid.TruncateID(b.image)) if b.Remove { b.clearTmp() } } if b.image == "" { return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?") } fmt.Fprintf(b.OutStream, "Successfully built %s\n", stringid.TruncateID(b.image)) return b.image, nil } // Reads a Dockerfile from the current context. It assumes that the // 'filename' is a relative path from the root of the context func (b *Builder) readDockerfile() error { // If no -f was specified then look for 'Dockerfile'. If we can't find // that then look for 'dockerfile'. If neither are found then default // back to 'Dockerfile' and use that in the error message. if b.dockerfileName == "" { b.dockerfileName = api.DefaultDockerfileName tmpFN := filepath.Join(b.contextPath, api.DefaultDockerfileName) if _, err := os.Lstat(tmpFN); err != nil { tmpFN = filepath.Join(b.contextPath, strings.ToLower(api.DefaultDockerfileName)) if _, err := os.Lstat(tmpFN); err == nil { b.dockerfileName = strings.ToLower(api.DefaultDockerfileName) } } } origFile := b.dockerfileName filename, err := symlink.FollowSymlinkInScope(filepath.Join(b.contextPath, origFile), b.contextPath) if err != nil { return fmt.Errorf("The Dockerfile (%s) must be within the build context", origFile) } fi, err := os.Lstat(filename) if os.IsNotExist(err) { return fmt.Errorf("Cannot locate specified Dockerfile: %s", origFile) } if fi.Size() == 0 { return fmt.Errorf("The Dockerfile (%s) cannot be empty", origFile) } f, err := os.Open(filename) if err != nil { return err } b.dockerfile, err = parser.Parse(f) f.Close() if err != nil { return err } // After the Dockerfile has been parsed, we need to check the .dockerignore // file for either "Dockerfile" or ".dockerignore", and if either are // present then erase them from the build context. These files should never // have been sent from the client but we did send them to make sure that // we had the Dockerfile to actually parse, and then we also need the // .dockerignore file to know whether either file should be removed. // Note that this assumes the Dockerfile has been read into memory and // is now safe to be removed. excludes, _ := utils.ReadDockerIgnore(filepath.Join(b.contextPath, ".dockerignore")) if rm, _ := fileutils.Matches(".dockerignore", excludes); rm == true { os.Remove(filepath.Join(b.contextPath, ".dockerignore")) b.context.(tarsum.BuilderContext).Remove(".dockerignore") } if rm, _ := fileutils.Matches(b.dockerfileName, excludes); rm == true { os.Remove(filepath.Join(b.contextPath, b.dockerfileName)) b.context.(tarsum.BuilderContext).Remove(b.dockerfileName) } return nil } // This method is the entrypoint to all statement handling routines. // // Almost all nodes will have this structure: // Child[Node, Node, Node] where Child is from parser.Node.Children and each // node comes from parser.Node.Next. This forms a "line" with a statement and // arguments and we process them in this normalized form by hitting // evaluateTable with the leaf nodes of the command and the Builder object. // // ONBUILD is a special case; in this case the parser will emit: // Child[Node, Child[Node, Node...]] where the first node is the literal // "onbuild" and the child entrypoint is the command of the ONBUILD statmeent, // such as `RUN` in ONBUILD RUN foo. There is special case logic in here to // deal with that, at least until it becomes more of a general concern with new // features. func (b *Builder) dispatch(stepN int, ast *parser.Node) error { cmd := ast.Value attrs := ast.Attributes original := ast.Original flags := ast.Flags strs := []string{} msg := fmt.Sprintf("Step %d : %s", stepN, strings.ToUpper(cmd)) if len(ast.Flags) > 0 { msg += " " + strings.Join(ast.Flags, " ") } if cmd == "onbuild" { if ast.Next == nil { return fmt.Errorf("ONBUILD requires at least one argument") } ast = ast.Next.Children[0] strs = append(strs, ast.Value) msg += " " + ast.Value if len(ast.Flags) > 0 { msg += " " + strings.Join(ast.Flags, " ") } } // count the number of nodes that we are going to traverse first // so we can pre-create the argument and message array. This speeds up the // allocation of those list a lot when they have a lot of arguments cursor := ast var n int for cursor.Next != nil { cursor = cursor.Next n++ } l := len(strs) strList := make([]string, n+l) copy(strList, strs) msgList := make([]string, n) var i int for ast.Next != nil { ast = ast.Next var str string str = ast.Value if _, ok := replaceEnvAllowed[cmd]; ok { var err error str, err = ProcessWord(ast.Value, b.Config.Env) if err != nil { return err } } strList[i+l] = str msgList[i] = ast.Value i++ } msg += " " + strings.Join(msgList, " ") fmt.Fprintln(b.OutStream, msg) // XXX yes, we skip any cmds that are not valid; the parser should have // picked these out already. if f, ok := evaluateTable[cmd]; ok { b.BuilderFlags = NewBuilderFlags() b.BuilderFlags.Args = flags return f(b, strList, attrs, original) } return fmt.Errorf("Unknown instruction: %s", strings.ToUpper(cmd)) } ================================================ FILE: vendor/github.com/docker/docker/builder/internals.go ================================================ package builder // internals for handling commands. Covers many areas and a lot of // non-contiguous functionality. Please read the comments. import ( "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "runtime" "sort" "strings" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/builder/parser" "github.com/docker/docker/cliconfig" "github.com/docker/docker/daemon" "github.com/docker/docker/graph" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/httputils" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/tarsum" "github.com/docker/docker/pkg/urlutil" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" ) func (b *Builder) readContext(context io.Reader) (err error) { tmpdirPath, err := ioutil.TempDir("", "docker-build") if err != nil { return } // Make sure we clean-up upon error. In the happy case the caller // is expected to manage the clean-up defer func() { if err != nil { if e := os.RemoveAll(tmpdirPath); e != nil { logrus.Debugf("[BUILDER] failed to remove temporary context: %s", e) } } }() decompressedStream, err := archive.DecompressStream(context) if err != nil { return } if b.context, err = tarsum.NewTarSum(decompressedStream, true, tarsum.Version1); err != nil { return } if err = chrootarchive.Untar(b.context, tmpdirPath, nil); err != nil { return } b.contextPath = tmpdirPath return } func (b *Builder) commit(id string, autoCmd *runconfig.Command, comment string) error { if b.disableCommit { return nil } if b.image == "" && !b.noBaseImage { return fmt.Errorf("Please provide a source image with `from` prior to commit") } b.Config.Image = b.image if id == "" { cmd := b.Config.Cmd if runtime.GOOS != "windows" { b.Config.Cmd = runconfig.NewCommand("/bin/sh", "-c", "#(nop) "+comment) } else { b.Config.Cmd = runconfig.NewCommand("cmd", "/S /C", "REM (nop) "+comment) } defer func(cmd *runconfig.Command) { b.Config.Cmd = cmd }(cmd) hit, err := b.probeCache() if err != nil { return err } if hit { return nil } container, err := b.create() if err != nil { return err } id = container.ID if err := container.Mount(); err != nil { return err } defer container.Unmount() } container, err := b.Daemon.Get(id) if err != nil { return err } // Note: Actually copy the struct autoConfig := *b.Config autoConfig.Cmd = autoCmd commitCfg := &daemon.ContainerCommitConfig{ Author: b.maintainer, Pause: true, Config: &autoConfig, } // Commit the container image, err := b.Daemon.Commit(container, commitCfg) if err != nil { return err } b.Daemon.Graph().Retain(b.id, image.ID) b.activeImages = append(b.activeImages, image.ID) b.image = image.ID return nil } type copyInfo struct { origPath string destPath string hash string decompress bool tmpDir string } func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecompression bool, cmdName string) error { if b.context == nil { return fmt.Errorf("No context given. Impossible to use %s", cmdName) } if len(args) < 2 { return fmt.Errorf("Invalid %s format - at least two arguments required", cmdName) } // Work in daemon-specific filepath semantics dest := filepath.FromSlash(args[len(args)-1]) // last one is always the dest copyInfos := []*copyInfo{} b.Config.Image = b.image defer func() { for _, ci := range copyInfos { if ci.tmpDir != "" { os.RemoveAll(ci.tmpDir) } } }() // Loop through each src file and calculate the info we need to // do the copy (e.g. hash value if cached). Don't actually do // the copy until we've looked at all src files for _, orig := range args[0 : len(args)-1] { if err := calcCopyInfo( b, cmdName, ©Infos, orig, dest, allowRemote, allowDecompression, true, ); err != nil { return err } } if len(copyInfos) == 0 { return fmt.Errorf("No source files were specified") } if len(copyInfos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) { return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName) } // For backwards compat, if there's just one CI then use it as the // cache look-up string, otherwise hash 'em all into one var srcHash string var origPaths string if len(copyInfos) == 1 { srcHash = copyInfos[0].hash origPaths = copyInfos[0].origPath } else { var hashs []string var origs []string for _, ci := range copyInfos { hashs = append(hashs, ci.hash) origs = append(origs, ci.origPath) } hasher := sha256.New() hasher.Write([]byte(strings.Join(hashs, ","))) srcHash = "multi:" + hex.EncodeToString(hasher.Sum(nil)) origPaths = strings.Join(origs, " ") } cmd := b.Config.Cmd if runtime.GOOS != "windows" { b.Config.Cmd = runconfig.NewCommand("/bin/sh", "-c", fmt.Sprintf("#(nop) %s %s in %s", cmdName, srcHash, dest)) } else { b.Config.Cmd = runconfig.NewCommand("cmd", "/S /C", fmt.Sprintf("REM (nop) %s %s in %s", cmdName, srcHash, dest)) } defer func(cmd *runconfig.Command) { b.Config.Cmd = cmd }(cmd) hit, err := b.probeCache() if err != nil { return err } if hit { return nil } container, _, err := b.Daemon.Create(b.Config, nil, "") if err != nil { return err } b.TmpContainers[container.ID] = struct{}{} if err := container.Mount(); err != nil { return err } defer container.Unmount() if err := container.PrepareStorage(); err != nil { return err } for _, ci := range copyInfos { if err := b.addContext(container, ci.origPath, ci.destPath, ci.decompress); err != nil { return err } } if err := container.CleanupStorage(); err != nil { return err } if err := b.commit(container.ID, cmd, fmt.Sprintf("%s %s in %s", cmdName, origPaths, dest)); err != nil { return err } return nil } func calcCopyInfo(b *Builder, cmdName string, cInfos *[]*copyInfo, origPath string, destPath string, allowRemote bool, allowDecompression bool, allowWildcards bool) error { // Work in daemon-specific OS filepath semantics. However, we save // the the origPath passed in here, as it might also be a URL which // we need to check for in this function. passedInOrigPath := origPath origPath = filepath.FromSlash(origPath) destPath = filepath.FromSlash(destPath) if origPath != "" && origPath[0] == os.PathSeparator && len(origPath) > 1 { origPath = origPath[1:] } origPath = strings.TrimPrefix(origPath, "."+string(os.PathSeparator)) // Twiddle the destPath when its a relative path - meaning, make it // relative to the WORKINGDIR if !filepath.IsAbs(destPath) { hasSlash := strings.HasSuffix(destPath, string(os.PathSeparator)) destPath = filepath.Join(string(os.PathSeparator), filepath.FromSlash(b.Config.WorkingDir), destPath) // Make sure we preserve any trailing slash if hasSlash { destPath += string(os.PathSeparator) } } // In the remote/URL case, download it and gen its hashcode if urlutil.IsURL(passedInOrigPath) { // As it's a URL, we go back to processing on what was passed in // to this function origPath = passedInOrigPath if !allowRemote { return fmt.Errorf("Source can't be a URL for %s", cmdName) } ci := copyInfo{} ci.origPath = origPath ci.hash = origPath // default to this but can change ci.destPath = destPath ci.decompress = false *cInfos = append(*cInfos, &ci) // Initiate the download resp, err := httputils.Download(ci.origPath) if err != nil { return err } // Create a tmp dir tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote") if err != nil { return err } ci.tmpDir = tmpDirName // Create a tmp file within our tmp dir tmpFileName := filepath.Join(tmpDirName, "tmp") tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) if err != nil { return err } // Download and dump result to tmp file if _, err := io.Copy(tmpFile, progressreader.New(progressreader.Config{ In: resp.Body, Out: b.OutOld, Formatter: b.StreamFormatter, Size: int(resp.ContentLength), NewLines: true, ID: "", Action: "Downloading", })); err != nil { tmpFile.Close() return err } fmt.Fprintf(b.OutStream, "\n") tmpFile.Close() // Set the mtime to the Last-Modified header value if present // Otherwise just remove atime and mtime times := make([]syscall.Timespec, 2) lastMod := resp.Header.Get("Last-Modified") if lastMod != "" { mTime, err := http.ParseTime(lastMod) // If we can't parse it then just let it default to 'zero' // otherwise use the parsed time value if err == nil { times[1] = syscall.NsecToTimespec(mTime.UnixNano()) } } if err := system.UtimesNano(tmpFileName, times); err != nil { return err } ci.origPath = filepath.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName)) // If the destination is a directory, figure out the filename. if strings.HasSuffix(ci.destPath, string(os.PathSeparator)) { u, err := url.Parse(origPath) if err != nil { return err } path := u.Path if strings.HasSuffix(path, string(os.PathSeparator)) { path = path[:len(path)-1] } parts := strings.Split(path, string(os.PathSeparator)) filename := parts[len(parts)-1] if filename == "" { return fmt.Errorf("cannot determine filename from url: %s", u) } ci.destPath = ci.destPath + filename } // Calc the checksum, even if we're using the cache r, err := archive.Tar(tmpFileName, archive.Uncompressed) if err != nil { return err } tarSum, err := tarsum.NewTarSum(r, true, tarsum.Version1) if err != nil { return err } if _, err := io.Copy(ioutil.Discard, tarSum); err != nil { return err } ci.hash = tarSum.Sum(nil) r.Close() return nil } // Deal with wildcards if allowWildcards && ContainsWildcards(origPath) { for _, fileInfo := range b.context.GetSums() { if fileInfo.Name() == "" { continue } match, _ := filepath.Match(origPath, fileInfo.Name()) if !match { continue } // Note we set allowWildcards to false in case the name has // a * in it calcCopyInfo(b, cmdName, cInfos, fileInfo.Name(), destPath, allowRemote, allowDecompression, false) } return nil } // Must be a dir or a file if err := b.checkPathForAddition(origPath); err != nil { return err } fi, _ := os.Stat(filepath.Join(b.contextPath, origPath)) ci := copyInfo{} ci.origPath = origPath ci.hash = origPath ci.destPath = destPath ci.decompress = allowDecompression *cInfos = append(*cInfos, &ci) // Deal with the single file case if !fi.IsDir() { // This will match first file in sums of the archive fis := b.context.GetSums().GetFile(ci.origPath) if fis != nil { ci.hash = "file:" + fis.Sum() } return nil } // Must be a dir var subfiles []string absOrigPath := filepath.Join(b.contextPath, ci.origPath) // Add a trailing / to make sure we only pick up nested files under // the dir and not sibling files of the dir that just happen to // start with the same chars if !strings.HasSuffix(absOrigPath, string(os.PathSeparator)) { absOrigPath += string(os.PathSeparator) } // Need path w/o slash too to find matching dir w/o trailing slash absOrigPathNoSlash := absOrigPath[:len(absOrigPath)-1] for _, fileInfo := range b.context.GetSums() { absFile := filepath.Join(b.contextPath, fileInfo.Name()) // Any file in the context that starts with the given path will be // picked up and its hashcode used. However, we'll exclude the // root dir itself. We do this for a coupel of reasons: // 1 - ADD/COPY will not copy the dir itself, just its children // so there's no reason to include it in the hash calc // 2 - the metadata on the dir will change when any child file // changes. This will lead to a miss in the cache check if that // child file is in the .dockerignore list. if strings.HasPrefix(absFile, absOrigPath) && absFile != absOrigPathNoSlash { subfiles = append(subfiles, fileInfo.Sum()) } } sort.Strings(subfiles) hasher := sha256.New() hasher.Write([]byte(strings.Join(subfiles, ","))) ci.hash = "dir:" + hex.EncodeToString(hasher.Sum(nil)) return nil } func ContainsWildcards(name string) bool { for i := 0; i < len(name); i++ { ch := name[i] if ch == '\\' { i++ } else if ch == '*' || ch == '?' || ch == '[' { return true } } return false } func (b *Builder) pullImage(name string) (*image.Image, error) { remote, tag := parsers.ParseRepositoryTag(name) if tag == "" { tag = "latest" } pullRegistryAuth := &cliconfig.AuthConfig{} if len(b.AuthConfigs) > 0 { // The request came with a full auth config file, we prefer to use that repoInfo, err := b.Daemon.RegistryService.ResolveRepository(remote) if err != nil { return nil, err } resolvedConfig := registry.ResolveAuthConfig( &cliconfig.ConfigFile{AuthConfigs: b.AuthConfigs}, repoInfo.Index, ) pullRegistryAuth = &resolvedConfig } imagePullConfig := &graph.ImagePullConfig{ AuthConfig: pullRegistryAuth, OutStream: ioutils.NopWriteCloser(b.OutOld), } if err := b.Daemon.Repositories().Pull(remote, tag, imagePullConfig); err != nil { return nil, err } image, err := b.Daemon.Repositories().LookupImage(name) if err != nil { return nil, err } return image, nil } func (b *Builder) processImageFrom(img *image.Image) error { b.image = img.ID if img.Config != nil { b.Config = img.Config } // The default path will be blank on Windows (set by HCS) if len(b.Config.Env) == 0 && daemon.DefaultPathEnv != "" { b.Config.Env = append(b.Config.Env, "PATH="+daemon.DefaultPathEnv) } // Process ONBUILD triggers if they exist if nTriggers := len(b.Config.OnBuild); nTriggers != 0 { fmt.Fprintf(b.ErrStream, "# Executing %d build triggers\n", nTriggers) } // Copy the ONBUILD triggers, and remove them from the config, since the config will be committed. onBuildTriggers := b.Config.OnBuild b.Config.OnBuild = []string{} // parse the ONBUILD triggers by invoking the parser for stepN, step := range onBuildTriggers { ast, err := parser.Parse(strings.NewReader(step)) if err != nil { return err } for i, n := range ast.Children { switch strings.ToUpper(n.Value) { case "ONBUILD": return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") case "MAINTAINER", "FROM": return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", n.Value) } fmt.Fprintf(b.OutStream, "Trigger %d, %s\n", stepN, step) if err := b.dispatch(i, n); err != nil { return err } } } return nil } // probeCache checks to see if image-caching is enabled (`b.UtilizeCache`) // and if so attempts to look up the current `b.image` and `b.Config` pair // in the current server `b.Daemon`. If an image is found, probeCache returns // `(true, nil)`. If no image is found, it returns `(false, nil)`. If there // is any error, it returns `(false, err)`. func (b *Builder) probeCache() (bool, error) { if !b.UtilizeCache || b.cacheBusted { return false, nil } cache, err := b.Daemon.ImageGetCached(b.image, b.Config) if err != nil { return false, err } if cache == nil { logrus.Debugf("[BUILDER] Cache miss") b.cacheBusted = true return false, nil } fmt.Fprintf(b.OutStream, " ---> Using cache\n") logrus.Debugf("[BUILDER] Use cached version") b.image = cache.ID b.Daemon.Graph().Retain(b.id, cache.ID) b.activeImages = append(b.activeImages, cache.ID) return true, nil } func (b *Builder) create() (*daemon.Container, error) { if b.image == "" && !b.noBaseImage { return nil, fmt.Errorf("Please provide a source image with `from` prior to run") } b.Config.Image = b.image hostConfig := &runconfig.HostConfig{ CpuShares: b.cpuShares, CpuPeriod: b.cpuPeriod, CpuQuota: b.cpuQuota, CpusetCpus: b.cpuSetCpus, CpusetMems: b.cpuSetMems, CgroupParent: b.cgroupParent, Memory: b.memory, MemorySwap: b.memorySwap, } config := *b.Config // Create the container c, warnings, err := b.Daemon.Create(b.Config, hostConfig, "") if err != nil { return nil, err } for _, warning := range warnings { fmt.Fprintf(b.OutStream, " ---> [Warning] %s\n", warning) } b.TmpContainers[c.ID] = struct{}{} fmt.Fprintf(b.OutStream, " ---> Running in %s\n", stringid.TruncateID(c.ID)) if config.Cmd.Len() > 0 { // override the entry point that may have been picked up from the base image s := config.Cmd.Slice() c.Path = s[0] c.Args = s[1:] } else { config.Cmd = runconfig.NewCommand() } return c, nil } func (b *Builder) run(c *daemon.Container) error { var errCh chan error if b.Verbose { errCh = c.Attach(nil, b.OutStream, b.ErrStream) } //start the container if err := c.Start(); err != nil { return err } finished := make(chan struct{}) defer close(finished) go func() { select { case <-b.cancelled: logrus.Debugln("Build cancelled, killing container:", c.ID) c.Kill() case <-finished: } }() if b.Verbose { // Block on reading output from container, stop on err or chan closed if err := <-errCh; err != nil { return err } } // Wait for it to finish if ret, _ := c.WaitStop(-1 * time.Second); ret != 0 { return &jsonmessage.JSONError{ Message: fmt.Sprintf("The command '%s' returned a non-zero code: %d", b.Config.Cmd.ToString(), ret), Code: ret, } } return nil } func (b *Builder) checkPathForAddition(orig string) error { origPath := filepath.Join(b.contextPath, orig) origPath, err := filepath.EvalSymlinks(origPath) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("%s: no such file or directory", orig) } return err } contextPath, err := filepath.EvalSymlinks(b.contextPath) if err != nil { return err } if !strings.HasPrefix(origPath, contextPath) { return fmt.Errorf("Forbidden path outside the build context: %s (%s)", orig, origPath) } if _, err := os.Stat(origPath); err != nil { if os.IsNotExist(err) { return fmt.Errorf("%s: no such file or directory", orig) } return err } return nil } func (b *Builder) addContext(container *daemon.Container, orig, dest string, decompress bool) error { var ( err error destExists = true origPath = filepath.Join(b.contextPath, orig) destPath string ) // Work in daemon-local OS specific file paths dest = filepath.FromSlash(dest) destPath, err = container.GetResourcePath(dest) if err != nil { return err } // Preserve the trailing slash if strings.HasSuffix(dest, string(os.PathSeparator)) || dest == "." { destPath = destPath + string(os.PathSeparator) } destStat, err := os.Stat(destPath) if err != nil { if !os.IsNotExist(err) { logrus.Errorf("Error performing os.Stat on %s. %s", destPath, err) return err } destExists = false } fi, err := os.Stat(origPath) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("%s: no such file or directory", orig) } return err } if fi.IsDir() { return copyAsDirectory(origPath, destPath, destExists) } // If we are adding a remote file (or we've been told not to decompress), do not try to untar it if decompress { // First try to unpack the source as an archive // to support the untar feature we need to clean up the path a little bit // because tar is very forgiving. First we need to strip off the archive's // filename from the path but this is only added if it does not end in slash tarDest := destPath if strings.HasSuffix(tarDest, string(os.PathSeparator)) { tarDest = filepath.Dir(destPath) } // try to successfully untar the orig if err := chrootarchive.UntarPath(origPath, tarDest); err == nil { return nil } else if err != io.EOF { logrus.Debugf("Couldn't untar %s to %s: %s", origPath, tarDest, err) } } if err := system.MkdirAll(filepath.Dir(destPath), 0755); err != nil { return err } if err := chrootarchive.CopyWithTar(origPath, destPath); err != nil { return err } resPath := destPath if destExists && destStat.IsDir() { resPath = filepath.Join(destPath, filepath.Base(origPath)) } return fixPermissions(origPath, resPath, 0, 0, destExists) } func copyAsDirectory(source, destination string, destExisted bool) error { if err := chrootarchive.CopyWithTar(source, destination); err != nil { return err } return fixPermissions(source, destination, 0, 0, destExisted) } func (b *Builder) clearTmp() { for c := range b.TmpContainers { rmConfig := &daemon.ContainerRmConfig{ ForceRemove: true, RemoveVolume: true, } if err := b.Daemon.ContainerRm(c, rmConfig); err != nil { fmt.Fprintf(b.OutStream, "Error removing intermediate container %s: %v\n", stringid.TruncateID(c), err) return } delete(b.TmpContainers, c) fmt.Fprintf(b.OutStream, "Removing intermediate container %s\n", stringid.TruncateID(c)) } } ================================================ FILE: vendor/github.com/docker/docker/builder/internals_linux.go ================================================ // +build linux package builder import ( "os" "path/filepath" ) func fixPermissions(source, destination string, uid, gid int, destExisted bool) error { // If the destination didn't already exist, or the destination isn't a // directory, then we should Lchown the destination. Otherwise, we shouldn't // Lchown the destination. destStat, err := os.Stat(destination) if err != nil { // This should *never* be reached, because the destination must've already // been created while untar-ing the context. return err } doChownDestination := !destExisted || !destStat.IsDir() // We Walk on the source rather than on the destination because we don't // want to change permissions on things we haven't created or modified. return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error { // Do not alter the walk root iff. it existed before, as it doesn't fall under // the domain of "things we should chown". if !doChownDestination && (source == fullpath) { return nil } // Path is prefixed by source: substitute with destination instead. cleaned, err := filepath.Rel(source, fullpath) if err != nil { return err } fullpath = filepath.Join(destination, cleaned) return os.Lchown(fullpath, uid, gid) }) } ================================================ FILE: vendor/github.com/docker/docker/builder/internals_windows.go ================================================ // +build windows package builder func fixPermissions(source, destination string, uid, gid int, destExisted bool) error { // chown is not supported on Windows return nil } ================================================ FILE: vendor/github.com/docker/docker/builder/job.go ================================================ package builder import ( "bytes" "errors" "fmt" "io" "io/ioutil" "os" "strings" "sync" "github.com/docker/docker/api" "github.com/docker/docker/builder/parser" "github.com/docker/docker/cliconfig" "github.com/docker/docker/daemon" "github.com/docker/docker/graph/tags" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/httputils" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/urlutil" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) // When downloading remote contexts, limit the amount (in bytes) // to be read from the response body in order to detect its Content-Type const maxPreambleLength = 100 // whitelist of commands allowed for a commit/import var validCommitCommands = map[string]bool{ "cmd": true, "entrypoint": true, "env": true, "expose": true, "label": true, "onbuild": true, "user": true, "volume": true, "workdir": true, } type Config struct { DockerfileName string RemoteURL string RepoName string SuppressOutput bool NoCache bool Remove bool ForceRemove bool Pull bool Memory int64 MemorySwap int64 CpuShares int64 CpuPeriod int64 CpuQuota int64 CpuSetCpus string CpuSetMems string CgroupParent string AuthConfigs map[string]cliconfig.AuthConfig Stdout io.Writer Context io.ReadCloser // When closed, the job has been cancelled. // Note: not all jobs implement cancellation. // See Job.Cancel() and Job.WaitCancelled() cancelled chan struct{} cancelOnce sync.Once } // When called, causes the Job.WaitCancelled channel to unblock. func (b *Config) Cancel() { b.cancelOnce.Do(func() { close(b.cancelled) }) } // Returns a channel which is closed ("never blocks") when the job is cancelled. func (b *Config) WaitCancelled() <-chan struct{} { return b.cancelled } func NewBuildConfig() *Config { return &Config{ AuthConfigs: map[string]cliconfig.AuthConfig{}, cancelled: make(chan struct{}), } } func Build(d *daemon.Daemon, buildConfig *Config) error { var ( repoName string tag string context io.ReadCloser ) sf := streamformatter.NewJSONStreamFormatter() repoName, tag = parsers.ParseRepositoryTag(buildConfig.RepoName) if repoName != "" { if err := registry.ValidateRepositoryName(repoName); err != nil { return err } if len(tag) > 0 { if err := tags.ValidateTagName(tag); err != nil { return err } } } if buildConfig.RemoteURL == "" { context = ioutil.NopCloser(buildConfig.Context) } else if urlutil.IsGitURL(buildConfig.RemoteURL) { root, err := utils.GitClone(buildConfig.RemoteURL) if err != nil { return err } defer os.RemoveAll(root) c, err := archive.Tar(root, archive.Uncompressed) if err != nil { return err } context = c } else if urlutil.IsURL(buildConfig.RemoteURL) { f, err := httputils.Download(buildConfig.RemoteURL) if err != nil { return fmt.Errorf("Error downloading remote context %s: %v", buildConfig.RemoteURL, err) } defer f.Body.Close() ct := f.Header.Get("Content-Type") clen := int(f.ContentLength) contentType, bodyReader, err := inspectResponse(ct, f.Body, clen) defer bodyReader.Close() if err != nil { return fmt.Errorf("Error detecting content type for remote %s: %v", buildConfig.RemoteURL, err) } if contentType == httputils.MimeTypes.TextPlain { dockerFile, err := ioutil.ReadAll(bodyReader) if err != nil { return err } // When we're downloading just a Dockerfile put it in // the default name - don't allow the client to move/specify it buildConfig.DockerfileName = api.DefaultDockerfileName c, err := archive.Generate(buildConfig.DockerfileName, string(dockerFile)) if err != nil { return err } context = c } else { // Pass through - this is a pre-packaged context, presumably // with a Dockerfile with the right name inside it. prCfg := progressreader.Config{ In: bodyReader, Out: buildConfig.Stdout, Formatter: sf, Size: clen, NewLines: true, ID: "Downloading context", Action: buildConfig.RemoteURL, } context = progressreader.New(prCfg) } } defer context.Close() builder := &Builder{ Daemon: d, OutStream: &streamformatter.StdoutFormater{ Writer: buildConfig.Stdout, StreamFormatter: sf, }, ErrStream: &streamformatter.StderrFormater{ Writer: buildConfig.Stdout, StreamFormatter: sf, }, Verbose: !buildConfig.SuppressOutput, UtilizeCache: !buildConfig.NoCache, Remove: buildConfig.Remove, ForceRemove: buildConfig.ForceRemove, Pull: buildConfig.Pull, OutOld: buildConfig.Stdout, StreamFormatter: sf, AuthConfigs: buildConfig.AuthConfigs, dockerfileName: buildConfig.DockerfileName, cpuShares: buildConfig.CpuShares, cpuPeriod: buildConfig.CpuPeriod, cpuQuota: buildConfig.CpuQuota, cpuSetCpus: buildConfig.CpuSetCpus, cpuSetMems: buildConfig.CpuSetMems, cgroupParent: buildConfig.CgroupParent, memory: buildConfig.Memory, memorySwap: buildConfig.MemorySwap, cancelled: buildConfig.WaitCancelled(), id: stringid.GenerateRandomID(), } defer func() { builder.Daemon.Graph().Release(builder.id, builder.activeImages...) }() id, err := builder.Run(context) if err != nil { return err } if repoName != "" { return d.Repositories().Tag(repoName, tag, id, true) } return nil } func BuildFromConfig(d *daemon.Daemon, c *runconfig.Config, changes []string) (*runconfig.Config, error) { ast, err := parser.Parse(bytes.NewBufferString(strings.Join(changes, "\n"))) if err != nil { return nil, err } // ensure that the commands are valid for _, n := range ast.Children { if !validCommitCommands[n.Value] { return nil, fmt.Errorf("%s is not a valid change command", n.Value) } } builder := &Builder{ Daemon: d, Config: c, OutStream: ioutil.Discard, ErrStream: ioutil.Discard, disableCommit: true, } for i, n := range ast.Children { if err := builder.dispatch(i, n); err != nil { return nil, err } } return builder.Config, nil } type BuilderCommitConfig struct { Pause bool Repo string Tag string Author string Comment string Changes []string Config *runconfig.Config } func Commit(name string, d *daemon.Daemon, c *BuilderCommitConfig) (string, error) { container, err := d.Get(name) if err != nil { return "", err } if c.Config == nil { c.Config = &runconfig.Config{} } newConfig, err := BuildFromConfig(d, c.Config, c.Changes) if err != nil { return "", err } if err := runconfig.Merge(newConfig, container.Config); err != nil { return "", err } commitCfg := &daemon.ContainerCommitConfig{ Pause: c.Pause, Repo: c.Repo, Tag: c.Tag, Author: c.Author, Comment: c.Comment, Config: newConfig, } img, err := d.Commit(container, commitCfg) if err != nil { return "", err } return img.ID, nil } // inspectResponse looks into the http response data at r to determine whether its // content-type is on the list of acceptable content types for remote build contexts. // This function returns: // - a string representation of the detected content-type // - an io.Reader for the response body // - an error value which will be non-nil either when something goes wrong while // reading bytes from r or when the detected content-type is not acceptable. func inspectResponse(ct string, r io.ReadCloser, clen int) (string, io.ReadCloser, error) { plen := clen if plen <= 0 || plen > maxPreambleLength { plen = maxPreambleLength } preamble := make([]byte, plen, plen) rlen, err := r.Read(preamble) if rlen == 0 { return ct, r, errors.New("Empty response") } if err != nil && err != io.EOF { return ct, r, err } preambleR := bytes.NewReader(preamble) bodyReader := ioutil.NopCloser(io.MultiReader(preambleR, r)) // Some web servers will use application/octet-stream as the default // content type for files without an extension (e.g. 'Dockerfile') // so if we receive this value we better check for text content contentType := ct if len(ct) == 0 || ct == httputils.MimeTypes.OctetStream { contentType, _, err = httputils.DetectContentType(preamble) if err != nil { return contentType, bodyReader, err } } contentType = selectAcceptableMIME(contentType) var cterr error if len(contentType) == 0 { cterr = fmt.Errorf("unsupported Content-Type %q", ct) contentType = ct } return contentType, bodyReader, cterr } ================================================ FILE: vendor/github.com/docker/docker/builder/job_test.go ================================================ package builder import ( "bytes" "io/ioutil" "testing" ) var textPlainDockerfile = "FROM busybox" var binaryContext = []byte{0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00} //xz magic func TestInspectEmptyResponse(t *testing.T) { ct := "application/octet-stream" br := ioutil.NopCloser(bytes.NewReader([]byte(""))) contentType, bReader, err := inspectResponse(ct, br, 0) if err == nil { t.Fatalf("Should have generated an error for an empty response") } if contentType != "application/octet-stream" { t.Fatalf("Content type should be 'application/octet-stream' but is %q", contentType) } body, err := ioutil.ReadAll(bReader) if err != nil { t.Fatal(err) } if len(body) != 0 { t.Fatal("response body should remain empty") } } func TestInspectResponseBinary(t *testing.T) { ct := "application/octet-stream" br := ioutil.NopCloser(bytes.NewReader(binaryContext)) contentType, bReader, err := inspectResponse(ct, br, len(binaryContext)) if err != nil { t.Fatal(err) } if contentType != "application/octet-stream" { t.Fatalf("Content type should be 'application/octet-stream' but is %q", contentType) } body, err := ioutil.ReadAll(bReader) if err != nil { t.Fatal(err) } if len(body) != len(binaryContext) { t.Fatalf("Wrong response size %d, should be == len(binaryContext)", len(body)) } for i := range body { if body[i] != binaryContext[i] { t.Fatalf("Corrupted response body at byte index %d", i) } } } func TestResponseUnsupportedContentType(t *testing.T) { content := []byte(textPlainDockerfile) ct := "application/json" br := ioutil.NopCloser(bytes.NewReader(content)) contentType, bReader, err := inspectResponse(ct, br, len(textPlainDockerfile)) if err == nil { t.Fatal("Should have returned an error on content-type 'application/json'") } if contentType != ct { t.Fatalf("Should not have altered content-type: orig: %s, altered: %s", ct, contentType) } body, err := ioutil.ReadAll(bReader) if err != nil { t.Fatal(err) } if string(body) != textPlainDockerfile { t.Fatalf("Corrupted response body %s", body) } } func TestInspectResponseTextSimple(t *testing.T) { content := []byte(textPlainDockerfile) ct := "text/plain" br := ioutil.NopCloser(bytes.NewReader(content)) contentType, bReader, err := inspectResponse(ct, br, len(content)) if err != nil { t.Fatal(err) } if contentType != "text/plain" { t.Fatalf("Content type should be 'text/plain' but is %q", contentType) } body, err := ioutil.ReadAll(bReader) if err != nil { t.Fatal(err) } if string(body) != textPlainDockerfile { t.Fatalf("Corrupted response body %s", body) } } func TestInspectResponseEmptyContentType(t *testing.T) { content := []byte(textPlainDockerfile) br := ioutil.NopCloser(bytes.NewReader(content)) contentType, bodyReader, err := inspectResponse("", br, len(content)) if err != nil { t.Fatal(err) } if contentType != "text/plain" { t.Fatalf("Content type should be 'text/plain' but is %q", contentType) } body, err := ioutil.ReadAll(bodyReader) if err != nil { t.Fatal(err) } if string(body) != textPlainDockerfile { t.Fatalf("Corrupted response body %s", body) } } ================================================ FILE: vendor/github.com/docker/docker/builder/parser/dumper/main.go ================================================ package main import ( "fmt" "os" "github.com/docker/docker/builder/parser" ) func main() { var f *os.File var err error if len(os.Args) < 2 { fmt.Println("please supply filename(s)") os.Exit(1) } for _, fn := range os.Args[1:] { f, err = os.Open(fn) if err != nil { panic(err) } ast, err := parser.Parse(f) if err != nil { panic(err) } else { fmt.Println(ast.Dump()) } } } ================================================ FILE: vendor/github.com/docker/docker/builder/parser/json_test.go ================================================ package parser import ( "testing" ) var invalidJSONArraysOfStrings = []string{ `["a",42,"b"]`, `["a",123.456,"b"]`, `["a",{},"b"]`, `["a",{"c": "d"},"b"]`, `["a",["c"],"b"]`, `["a",true,"b"]`, `["a",false,"b"]`, `["a",null,"b"]`, } var validJSONArraysOfStrings = map[string][]string{ `[]`: {}, `[""]`: {""}, `["a"]`: {"a"}, `["a","b"]`: {"a", "b"}, `[ "a", "b" ]`: {"a", "b"}, `[ "a", "b" ]`: {"a", "b"}, ` [ "a", "b" ] `: {"a", "b"}, `["abc 123", "♥", "☃", "\" \\ \/ \b \f \n \r \t \u0000"]`: {"abc 123", "♥", "☃", "\" \\ / \b \f \n \r \t \u0000"}, } func TestJSONArraysOfStrings(t *testing.T) { for json, expected := range validJSONArraysOfStrings { if node, _, err := parseJSON(json); err != nil { t.Fatalf("%q should be a valid JSON array of strings, but wasn't! (err: %q)", json, err) } else { i := 0 for node != nil { if i >= len(expected) { t.Fatalf("expected result is shorter than parsed result (%d vs %d+) in %q", len(expected), i+1, json) } if node.Value != expected[i] { t.Fatalf("expected %q (not %q) in %q at pos %d", expected[i], node.Value, json, i) } node = node.Next i++ } if i != len(expected) { t.Fatalf("expected result is longer than parsed result (%d vs %d) in %q", len(expected), i+1, json) } } } for _, json := range invalidJSONArraysOfStrings { if _, _, err := parseJSON(json); err != errDockerfileNotStringArray { t.Fatalf("%q should be an invalid JSON array of strings, but wasn't!", json) } } } ================================================ FILE: vendor/github.com/docker/docker/builder/parser/line_parsers.go ================================================ package parser // line parsers are dispatch calls that parse a single unit of text into a // Node object which contains the whole statement. Dockerfiles have varied // (but not usually unique, see ONBUILD for a unique example) parsing rules // per-command, and these unify the processing in a way that makes it // manageable. import ( "encoding/json" "errors" "fmt" "strings" "unicode" ) var ( errDockerfileNotStringArray = errors.New("When using JSON array syntax, arrays must be comprised of strings only.") ) // ignore the current argument. This will still leave a command parsed, but // will not incorporate the arguments into the ast. func parseIgnore(rest string) (*Node, map[string]bool, error) { return &Node{}, nil, nil } // used for onbuild. Could potentially be used for anything that represents a // statement with sub-statements. // // ONBUILD RUN foo bar -> (onbuild (run foo bar)) // func parseSubCommand(rest string) (*Node, map[string]bool, error) { if rest == "" { return nil, nil, nil } _, child, err := parseLine(rest) if err != nil { return nil, nil, err } return &Node{Children: []*Node{child}}, nil, nil } // parse environment like statements. Note that this does *not* handle // variable interpolation, which will be handled in the evaluator. func parseNameVal(rest string, key string) (*Node, map[string]bool, error) { // This is kind of tricky because we need to support the old // variant: KEY name value // as well as the new one: KEY name=value ... // The trigger to know which one is being used will be whether we hit // a space or = first. space ==> old, "=" ==> new const ( inSpaces = iota // looking for start of a word inWord inQuote ) words := []string{} phase := inSpaces word := "" quote := '\000' blankOK := false var ch rune for pos := 0; pos <= len(rest); pos++ { if pos != len(rest) { ch = rune(rest[pos]) } if phase == inSpaces { // Looking for start of word if pos == len(rest) { // end of input break } if unicode.IsSpace(ch) { // skip spaces continue } phase = inWord // found it, fall thru } if (phase == inWord || phase == inQuote) && (pos == len(rest)) { if blankOK || len(word) > 0 { words = append(words, word) } break } if phase == inWord { if unicode.IsSpace(ch) { phase = inSpaces if blankOK || len(word) > 0 { words = append(words, word) // Look for = and if not there assume // we're doing the old stuff and // just read the rest of the line if !strings.Contains(word, "=") { word = strings.TrimSpace(rest[pos:]) words = append(words, word) break } } word = "" blankOK = false continue } if ch == '\'' || ch == '"' { quote = ch blankOK = true phase = inQuote } if ch == '\\' { if pos+1 == len(rest) { continue // just skip \ at end } // If we're not quoted and we see a \, then always just // add \ plus the char to the word, even if the char // is a quote. word += string(ch) pos++ ch = rune(rest[pos]) } word += string(ch) continue } if phase == inQuote { if ch == quote { phase = inWord } // \ is special except for ' quotes - can't escape anything for ' if ch == '\\' && quote != '\'' { if pos+1 == len(rest) { phase = inWord continue // just skip \ at end } pos++ nextCh := rune(rest[pos]) word += string(ch) ch = nextCh } word += string(ch) } } if len(words) == 0 { return nil, nil, nil } // Old format (KEY name value) var rootnode *Node if !strings.Contains(words[0], "=") { node := &Node{} rootnode = node strs := TOKEN_WHITESPACE.Split(rest, 2) if len(strs) < 2 { return nil, nil, fmt.Errorf(key + " must have two arguments") } node.Value = strs[0] node.Next = &Node{} node.Next.Value = strs[1] } else { var prevNode *Node for i, word := range words { if !strings.Contains(word, "=") { return nil, nil, fmt.Errorf("Syntax error - can't find = in %q. Must be of the form: name=value", word) } parts := strings.SplitN(word, "=", 2) name := &Node{} value := &Node{} name.Next = value name.Value = parts[0] value.Value = parts[1] if i == 0 { rootnode = name } else { prevNode.Next = name } prevNode = value } } return rootnode, nil, nil } func parseEnv(rest string) (*Node, map[string]bool, error) { return parseNameVal(rest, "ENV") } func parseLabel(rest string) (*Node, map[string]bool, error) { return parseNameVal(rest, "LABEL") } // parses a whitespace-delimited set of arguments. The result is effectively a // linked list of string arguments. func parseStringsWhitespaceDelimited(rest string) (*Node, map[string]bool, error) { if rest == "" { return nil, nil, nil } node := &Node{} rootnode := node prevnode := node for _, str := range TOKEN_WHITESPACE.Split(rest, -1) { // use regexp prevnode = node node.Value = str node.Next = &Node{} node = node.Next } // XXX to get around regexp.Split *always* providing an empty string at the // end due to how our loop is constructed, nil out the last node in the // chain. prevnode.Next = nil return rootnode, nil, nil } // parsestring just wraps the string in quotes and returns a working node. func parseString(rest string) (*Node, map[string]bool, error) { if rest == "" { return nil, nil, nil } n := &Node{} n.Value = rest return n, nil, nil } // parseJSON converts JSON arrays to an AST. func parseJSON(rest string) (*Node, map[string]bool, error) { var myJson []interface{} if err := json.NewDecoder(strings.NewReader(rest)).Decode(&myJson); err != nil { return nil, nil, err } var top, prev *Node for _, str := range myJson { s, ok := str.(string) if !ok { return nil, nil, errDockerfileNotStringArray } node := &Node{Value: s} if prev == nil { top = node } else { prev.Next = node } prev = node } return top, map[string]bool{"json": true}, nil } // parseMaybeJSON determines if the argument appears to be a JSON array. If // so, passes to parseJSON; if not, quotes the result and returns a single // node. func parseMaybeJSON(rest string) (*Node, map[string]bool, error) { if rest == "" { return nil, nil, nil } node, attrs, err := parseJSON(rest) if err == nil { return node, attrs, nil } if err == errDockerfileNotStringArray { return nil, nil, err } node = &Node{} node.Value = rest return node, nil, nil } // parseMaybeJSONToList determines if the argument appears to be a JSON array. If // so, passes to parseJSON; if not, attempts to parse it as a whitespace // delimited string. func parseMaybeJSONToList(rest string) (*Node, map[string]bool, error) { node, attrs, err := parseJSON(rest) if err == nil { return node, attrs, nil } if err == errDockerfileNotStringArray { return nil, nil, err } return parseStringsWhitespaceDelimited(rest) } ================================================ FILE: vendor/github.com/docker/docker/builder/parser/parser.go ================================================ // This package implements a parser and parse tree dumper for Dockerfiles. package parser import ( "bufio" "io" "regexp" "strings" "unicode" "github.com/docker/docker/builder/command" ) // Node is a structure used to represent a parse tree. // // In the node there are three fields, Value, Next, and Children. Value is the // current token's string value. Next is always the next non-child token, and // children contains all the children. Here's an example: // // (value next (child child-next child-next-next) next-next) // // This data structure is frankly pretty lousy for handling complex languages, // but lucky for us the Dockerfile isn't very complicated. This structure // works a little more effectively than a "proper" parse tree for our needs. // type Node struct { Value string // actual content Next *Node // the next item in the current sexp Children []*Node // the children of this sexp Attributes map[string]bool // special attributes for this node Original string // original line used before parsing Flags []string // only top Node should have this set } var ( dispatch map[string]func(string) (*Node, map[string]bool, error) TOKEN_WHITESPACE = regexp.MustCompile(`[\t\v\f\r ]+`) TOKEN_LINE_CONTINUATION = regexp.MustCompile(`\\[ \t]*$`) TOKEN_COMMENT = regexp.MustCompile(`^#.*$`) ) func init() { // Dispatch Table. see line_parsers.go for the parse functions. // The command is parsed and mapped to the line parser. The line parser // recieves the arguments but not the command, and returns an AST after // reformulating the arguments according to the rules in the parser // functions. Errors are propagated up by Parse() and the resulting AST can // be incorporated directly into the existing AST as a next. dispatch = map[string]func(string) (*Node, map[string]bool, error){ command.User: parseString, command.Onbuild: parseSubCommand, command.Workdir: parseString, command.Env: parseEnv, command.Label: parseLabel, command.Maintainer: parseString, command.From: parseString, command.Add: parseMaybeJSONToList, command.Copy: parseMaybeJSONToList, command.Run: parseMaybeJSON, command.Cmd: parseMaybeJSON, command.Entrypoint: parseMaybeJSON, command.Expose: parseStringsWhitespaceDelimited, command.Volume: parseMaybeJSONToList, } } // parse a line and return the remainder. func parseLine(line string) (string, *Node, error) { if line = stripComments(line); line == "" { return "", nil, nil } if TOKEN_LINE_CONTINUATION.MatchString(line) { line = TOKEN_LINE_CONTINUATION.ReplaceAllString(line, "") return line, nil, nil } cmd, flags, args, err := splitCommand(line) if err != nil { return "", nil, err } node := &Node{} node.Value = cmd sexp, attrs, err := fullDispatch(cmd, args) if err != nil { return "", nil, err } node.Next = sexp node.Attributes = attrs node.Original = line node.Flags = flags return "", node, nil } // The main parse routine. Handles an io.ReadWriteCloser and returns the root // of the AST. func Parse(rwc io.Reader) (*Node, error) { root := &Node{} scanner := bufio.NewScanner(rwc) for scanner.Scan() { scannedLine := strings.TrimLeftFunc(scanner.Text(), unicode.IsSpace) line, child, err := parseLine(scannedLine) if err != nil { return nil, err } if line != "" && child == nil { for scanner.Scan() { newline := scanner.Text() if stripComments(strings.TrimSpace(newline)) == "" { continue } line, child, err = parseLine(line + newline) if err != nil { return nil, err } if child != nil { break } } if child == nil && line != "" { line, child, err = parseLine(line) if err != nil { return nil, err } } } if child != nil { root.Children = append(root.Children, child) } } return root, nil } ================================================ FILE: vendor/github.com/docker/docker/builder/parser/parser_test.go ================================================ package parser import ( "fmt" "io/ioutil" "os" "path/filepath" "testing" ) const testDir = "testfiles" const negativeTestDir = "testfiles-negative" func getDirs(t *testing.T, dir string) []string { f, err := os.Open(dir) if err != nil { t.Fatal(err) } defer f.Close() dirs, err := f.Readdirnames(0) if err != nil { t.Fatal(err) } return dirs } func TestTestNegative(t *testing.T) { for _, dir := range getDirs(t, negativeTestDir) { dockerfile := filepath.Join(negativeTestDir, dir, "Dockerfile") df, err := os.Open(dockerfile) if err != nil { t.Fatalf("Dockerfile missing for %s: %v", dir, err) } _, err = Parse(df) if err == nil { t.Fatalf("No error parsing broken dockerfile for %s", dir) } df.Close() } } func TestTestData(t *testing.T) { for _, dir := range getDirs(t, testDir) { dockerfile := filepath.Join(testDir, dir, "Dockerfile") resultfile := filepath.Join(testDir, dir, "result") df, err := os.Open(dockerfile) if err != nil { t.Fatalf("Dockerfile missing for %s: %v", dir, err) } defer df.Close() ast, err := Parse(df) if err != nil { t.Fatalf("Error parsing %s's dockerfile: %v", dir, err) } content, err := ioutil.ReadFile(resultfile) if err != nil { t.Fatalf("Error reading %s's result file: %v", dir, err) } if ast.Dump()+"\n" != string(content) { fmt.Fprintln(os.Stderr, "Result:\n"+ast.Dump()) fmt.Fprintln(os.Stderr, "Expected:\n"+string(content)) t.Fatalf("%s: AST dump of dockerfile does not match result", dir) } } } ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/ADD-COPY-with-JSON/Dockerfile ================================================ FROM ubuntu:14.04 MAINTAINER Seongyeol Lim COPY . /go/src/github.com/docker/docker ADD . / ADD [ "vimrc", "/tmp" ] COPY [ "bashrc", "/tmp" ] COPY [ "test file", "/tmp" ] ADD [ "test file", "/tmp/test file" ] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/ADD-COPY-with-JSON/result ================================================ (from "ubuntu:14.04") (maintainer "Seongyeol Lim ") (copy "." "/go/src/github.com/docker/docker") (add "." "/") (add "vimrc" "/tmp") (copy "bashrc" "/tmp") (copy "test file" "/tmp") (add "test file" "/tmp/test file") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/brimstone-consuldock/Dockerfile ================================================ FROM brimstone/ubuntu:14.04 MAINTAINER brimstone@the.narro.ws # TORUN -v /var/run/docker.sock:/var/run/docker.sock ENV GOPATH /go # Set our command ENTRYPOINT ["/usr/local/bin/consuldock"] # Install the packages we need, clean up after them and us RUN apt-get update \ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \ && apt-get install -y --no-install-recommends git golang ca-certificates \ && apt-get clean \ && rm -rf /var/lib/apt/lists \ && go get -v github.com/brimstone/consuldock \ && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \ && rm /tmp/dpkg.* \ && rm -rf $GOPATH ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/brimstone-consuldock/result ================================================ (from "brimstone/ubuntu:14.04") (maintainer "brimstone@the.narro.ws") (env "GOPATH" "/go") (entrypoint "/usr/local/bin/consuldock") (run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get install -y --no-install-recommends git golang ca-certificates && apt-get clean && rm -rf /var/lib/apt/lists \t&& go get -v github.com/brimstone/consuldock && mv $GOPATH/bin/consuldock /usr/local/bin/consuldock \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.* \t&& rm -rf $GOPATH") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/brimstone-docker-consul/Dockerfile ================================================ FROM brimstone/ubuntu:14.04 CMD [] ENTRYPOINT ["/usr/bin/consul", "agent", "-server", "-data-dir=/consul", "-client=0.0.0.0", "-ui-dir=/webui"] EXPOSE 8500 8600 8400 8301 8302 RUN apt-get update \ && apt-get install -y unzip wget \ && apt-get clean \ && rm -rf /var/lib/apt/lists RUN cd /tmp \ && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip \ -O web_ui.zip \ && unzip web_ui.zip \ && mv dist /webui \ && rm web_ui.zip RUN apt-get update \ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \ && apt-get install -y --no-install-recommends unzip wget \ && apt-get clean \ && rm -rf /var/lib/apt/lists \ && cd /tmp \ && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip \ -O web_ui.zip \ && unzip web_ui.zip \ && mv dist /webui \ && rm web_ui.zip \ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \ && rm /tmp/dpkg.* ENV GOPATH /go RUN apt-get update \ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean \ && apt-get install -y --no-install-recommends git golang ca-certificates build-essential \ && apt-get clean \ && rm -rf /var/lib/apt/lists \ && go get -v github.com/hashicorp/consul \ && mv $GOPATH/bin/consul /usr/bin/consul \ && dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \ && apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \ && rm /tmp/dpkg.* \ && rm -rf $GOPATH ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/brimstone-docker-consul/result ================================================ (from "brimstone/ubuntu:14.04") (cmd) (entrypoint "/usr/bin/consul" "agent" "-server" "-data-dir=/consul" "-client=0.0.0.0" "-ui-dir=/webui") (expose "8500" "8600" "8400" "8301" "8302") (run "apt-get update && apt-get install -y unzip wget \t&& apt-get clean \t&& rm -rf /var/lib/apt/lists") (run "cd /tmp && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip -O web_ui.zip && unzip web_ui.zip && mv dist /webui && rm web_ui.zip") (run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get install -y --no-install-recommends unzip wget && apt-get clean && rm -rf /var/lib/apt/lists && cd /tmp && wget https://dl.bintray.com/mitchellh/consul/0.3.1_web_ui.zip -O web_ui.zip && unzip web_ui.zip && mv dist /webui && rm web_ui.zip \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.*") (env "GOPATH" "/go") (run "apt-get update \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.clean && apt-get install -y --no-install-recommends git golang ca-certificates build-essential && apt-get clean && rm -rf /var/lib/apt/lists \t&& go get -v github.com/hashicorp/consul \t&& mv $GOPATH/bin/consul /usr/bin/consul \t&& dpkg -l | awk '/^ii/ {print $2}' > /tmp/dpkg.dirty \t&& apt-get remove --purge -y $(diff /tmp/dpkg.clean /tmp/dpkg.dirty | awk '/^>/ {print $2}') \t&& rm /tmp/dpkg.* \t&& rm -rf $GOPATH") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/continueIndent/Dockerfile ================================================ FROM ubuntu:14.04 RUN echo hello\ world\ goodnight \ moon\ light\ ning RUN echo hello \ world RUN echo hello \ world RUN echo hello \ goodbye\ frog RUN echo hello \ world RUN echo hi \ \ world \ \ good\ \ night RUN echo goodbye\ frog RUN echo good\ bye\ frog RUN echo hello \ # this is a comment # this is a comment with a blank line surrounding it this is some more useful stuff ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/continueIndent/result ================================================ (from "ubuntu:14.04") (run "echo hello world goodnight moon lightning") (run "echo hello world") (run "echo hello world") (run "echo hello goodbyefrog") (run "echo hello world") (run "echo hi world goodnight") (run "echo goodbyefrog") (run "echo goodbyefrog") (run "echo hello this is some more useful stuff") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/cpuguy83-nagios/Dockerfile ================================================ FROM cpuguy83/ubuntu ENV NAGIOS_HOME /opt/nagios ENV NAGIOS_USER nagios ENV NAGIOS_GROUP nagios ENV NAGIOS_CMDUSER nagios ENV NAGIOS_CMDGROUP nagios ENV NAGIOSADMIN_USER nagiosadmin ENV NAGIOSADMIN_PASS nagios ENV APACHE_RUN_USER nagios ENV APACHE_RUN_GROUP nagios ENV NAGIOS_TIMEZONE UTC RUN sed -i 's/universe/universe multiverse/' /etc/apt/sources.list RUN apt-get update && apt-get install -y iputils-ping netcat build-essential snmp snmpd snmp-mibs-downloader php5-cli apache2 libapache2-mod-php5 runit bc postfix bsd-mailx RUN ( egrep -i "^${NAGIOS_GROUP}" /etc/group || groupadd $NAGIOS_GROUP ) && ( egrep -i "^${NAGIOS_CMDGROUP}" /etc/group || groupadd $NAGIOS_CMDGROUP ) RUN ( id -u $NAGIOS_USER || useradd --system $NAGIOS_USER -g $NAGIOS_GROUP -d $NAGIOS_HOME ) && ( id -u $NAGIOS_CMDUSER || useradd --system -d $NAGIOS_HOME -g $NAGIOS_CMDGROUP $NAGIOS_CMDUSER ) ADD http://downloads.sourceforge.net/project/nagios/nagios-3.x/nagios-3.5.1/nagios-3.5.1.tar.gz?r=http%3A%2F%2Fwww.nagios.org%2Fdownload%2Fcore%2Fthanks%2F%3Ft%3D1398863696&ts=1398863718&use_mirror=superb-dca3 /tmp/nagios.tar.gz RUN cd /tmp && tar -zxvf nagios.tar.gz && cd nagios && ./configure --prefix=${NAGIOS_HOME} --exec-prefix=${NAGIOS_HOME} --enable-event-broker --with-nagios-command-user=${NAGIOS_CMDUSER} --with-command-group=${NAGIOS_CMDGROUP} --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} && make all && make install && make install-config && make install-commandmode && cp sample-config/httpd.conf /etc/apache2/conf.d/nagios.conf ADD http://www.nagios-plugins.org/download/nagios-plugins-1.5.tar.gz /tmp/ RUN cd /tmp && tar -zxvf nagios-plugins-1.5.tar.gz && cd nagios-plugins-1.5 && ./configure --prefix=${NAGIOS_HOME} && make && make install RUN sed -i.bak 's/.*\=www\-data//g' /etc/apache2/envvars RUN export DOC_ROOT="DocumentRoot $(echo $NAGIOS_HOME/share)"; sed -i "s,DocumentRoot.*,$DOC_ROOT," /etc/apache2/sites-enabled/000-default RUN ln -s ${NAGIOS_HOME}/bin/nagios /usr/local/bin/nagios && mkdir -p /usr/share/snmp/mibs && chmod 0755 /usr/share/snmp/mibs && touch /usr/share/snmp/mibs/.foo RUN echo "use_timezone=$NAGIOS_TIMEZONE" >> ${NAGIOS_HOME}/etc/nagios.cfg && echo "SetEnv TZ \"${NAGIOS_TIMEZONE}\"" >> /etc/apache2/conf.d/nagios.conf RUN mkdir -p ${NAGIOS_HOME}/etc/conf.d && mkdir -p ${NAGIOS_HOME}/etc/monitor && ln -s /usr/share/snmp/mibs ${NAGIOS_HOME}/libexec/mibs RUN echo "cfg_dir=${NAGIOS_HOME}/etc/conf.d" >> ${NAGIOS_HOME}/etc/nagios.cfg RUN echo "cfg_dir=${NAGIOS_HOME}/etc/monitor" >> ${NAGIOS_HOME}/etc/nagios.cfg RUN download-mibs && echo "mibs +ALL" > /etc/snmp/snmp.conf RUN sed -i 's,/bin/mail,/usr/bin/mail,' /opt/nagios/etc/objects/commands.cfg && \ sed -i 's,/usr/usr,/usr,' /opt/nagios/etc/objects/commands.cfg RUN cp /etc/services /var/spool/postfix/etc/ RUN mkdir -p /etc/sv/nagios && mkdir -p /etc/sv/apache && rm -rf /etc/sv/getty-5 && mkdir -p /etc/sv/postfix ADD nagios.init /etc/sv/nagios/run ADD apache.init /etc/sv/apache/run ADD postfix.init /etc/sv/postfix/run ADD postfix.stop /etc/sv/postfix/finish ADD start.sh /usr/local/bin/start_nagios ENV APACHE_LOCK_DIR /var/run ENV APACHE_LOG_DIR /var/log/apache2 EXPOSE 80 VOLUME ["/opt/nagios/var", "/opt/nagios/etc", "/opt/nagios/libexec", "/var/log/apache2", "/usr/share/snmp/mibs"] CMD ["/usr/local/bin/start_nagios"] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/cpuguy83-nagios/result ================================================ (from "cpuguy83/ubuntu") (env "NAGIOS_HOME" "/opt/nagios") (env "NAGIOS_USER" "nagios") (env "NAGIOS_GROUP" "nagios") (env "NAGIOS_CMDUSER" "nagios") (env "NAGIOS_CMDGROUP" "nagios") (env "NAGIOSADMIN_USER" "nagiosadmin") (env "NAGIOSADMIN_PASS" "nagios") (env "APACHE_RUN_USER" "nagios") (env "APACHE_RUN_GROUP" "nagios") (env "NAGIOS_TIMEZONE" "UTC") (run "sed -i 's/universe/universe multiverse/' /etc/apt/sources.list") (run "apt-get update && apt-get install -y iputils-ping netcat build-essential snmp snmpd snmp-mibs-downloader php5-cli apache2 libapache2-mod-php5 runit bc postfix bsd-mailx") (run "( egrep -i \"^${NAGIOS_GROUP}\" /etc/group || groupadd $NAGIOS_GROUP ) && ( egrep -i \"^${NAGIOS_CMDGROUP}\" /etc/group || groupadd $NAGIOS_CMDGROUP )") (run "( id -u $NAGIOS_USER || useradd --system $NAGIOS_USER -g $NAGIOS_GROUP -d $NAGIOS_HOME ) && ( id -u $NAGIOS_CMDUSER || useradd --system -d $NAGIOS_HOME -g $NAGIOS_CMDGROUP $NAGIOS_CMDUSER )") (add "http://downloads.sourceforge.net/project/nagios/nagios-3.x/nagios-3.5.1/nagios-3.5.1.tar.gz?r=http%3A%2F%2Fwww.nagios.org%2Fdownload%2Fcore%2Fthanks%2F%3Ft%3D1398863696&ts=1398863718&use_mirror=superb-dca3" "/tmp/nagios.tar.gz") (run "cd /tmp && tar -zxvf nagios.tar.gz && cd nagios && ./configure --prefix=${NAGIOS_HOME} --exec-prefix=${NAGIOS_HOME} --enable-event-broker --with-nagios-command-user=${NAGIOS_CMDUSER} --with-command-group=${NAGIOS_CMDGROUP} --with-nagios-user=${NAGIOS_USER} --with-nagios-group=${NAGIOS_GROUP} && make all && make install && make install-config && make install-commandmode && cp sample-config/httpd.conf /etc/apache2/conf.d/nagios.conf") (add "http://www.nagios-plugins.org/download/nagios-plugins-1.5.tar.gz" "/tmp/") (run "cd /tmp && tar -zxvf nagios-plugins-1.5.tar.gz && cd nagios-plugins-1.5 && ./configure --prefix=${NAGIOS_HOME} && make && make install") (run "sed -i.bak 's/.*\\=www\\-data//g' /etc/apache2/envvars") (run "export DOC_ROOT=\"DocumentRoot $(echo $NAGIOS_HOME/share)\"; sed -i \"s,DocumentRoot.*,$DOC_ROOT,\" /etc/apache2/sites-enabled/000-default") (run "ln -s ${NAGIOS_HOME}/bin/nagios /usr/local/bin/nagios && mkdir -p /usr/share/snmp/mibs && chmod 0755 /usr/share/snmp/mibs && touch /usr/share/snmp/mibs/.foo") (run "echo \"use_timezone=$NAGIOS_TIMEZONE\" >> ${NAGIOS_HOME}/etc/nagios.cfg && echo \"SetEnv TZ \\\"${NAGIOS_TIMEZONE}\\\"\" >> /etc/apache2/conf.d/nagios.conf") (run "mkdir -p ${NAGIOS_HOME}/etc/conf.d && mkdir -p ${NAGIOS_HOME}/etc/monitor && ln -s /usr/share/snmp/mibs ${NAGIOS_HOME}/libexec/mibs") (run "echo \"cfg_dir=${NAGIOS_HOME}/etc/conf.d\" >> ${NAGIOS_HOME}/etc/nagios.cfg") (run "echo \"cfg_dir=${NAGIOS_HOME}/etc/monitor\" >> ${NAGIOS_HOME}/etc/nagios.cfg") (run "download-mibs && echo \"mibs +ALL\" > /etc/snmp/snmp.conf") (run "sed -i 's,/bin/mail,/usr/bin/mail,' /opt/nagios/etc/objects/commands.cfg && sed -i 's,/usr/usr,/usr,' /opt/nagios/etc/objects/commands.cfg") (run "cp /etc/services /var/spool/postfix/etc/") (run "mkdir -p /etc/sv/nagios && mkdir -p /etc/sv/apache && rm -rf /etc/sv/getty-5 && mkdir -p /etc/sv/postfix") (add "nagios.init" "/etc/sv/nagios/run") (add "apache.init" "/etc/sv/apache/run") (add "postfix.init" "/etc/sv/postfix/run") (add "postfix.stop" "/etc/sv/postfix/finish") (add "start.sh" "/usr/local/bin/start_nagios") (env "APACHE_LOCK_DIR" "/var/run") (env "APACHE_LOG_DIR" "/var/log/apache2") (expose "80") (volume "/opt/nagios/var" "/opt/nagios/etc" "/opt/nagios/libexec" "/var/log/apache2" "/usr/share/snmp/mibs") (cmd "/usr/local/bin/start_nagios") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/docker/Dockerfile ================================================ # This file describes the standard way to build Docker, using docker # # Usage: # # # Assemble the full dev environment. This is slow the first time. # docker build -t docker . # # # Mount your source in an interactive container for quick testing: # docker run -v `pwd`:/go/src/github.com/docker/docker --privileged -i -t docker bash # # # Run the test suite: # docker run --privileged docker hack/make.sh test # # # Publish a release: # docker run --privileged \ # -e AWS_S3_BUCKET=baz \ # -e AWS_ACCESS_KEY=foo \ # -e AWS_SECRET_KEY=bar \ # -e GPG_PASSPHRASE=gloubiboulga \ # docker hack/release.sh # # Note: AppArmor used to mess with privileged mode, but this is no longer # the case. Therefore, you don't have to disable it anymore. # FROM ubuntu:14.04 MAINTAINER Tianon Gravi (@tianon) # Packaged dependencies RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -yq \ apt-utils \ aufs-tools \ automake \ btrfs-tools \ build-essential \ curl \ dpkg-sig \ git \ iptables \ libapparmor-dev \ libcap-dev \ libsqlite3-dev \ lxc=1.0* \ mercurial \ pandoc \ parallel \ reprepro \ ruby1.9.1 \ ruby1.9.1-dev \ s3cmd=1.1.0* \ --no-install-recommends # Get lvm2 source for compiling statically RUN git clone --no-checkout https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 && cd /usr/local/lvm2 && git checkout -q v2_02_103 # see https://git.fedorahosted.org/cgit/lvm2.git/refs/tags for release tags # note: we don't use "git clone -b" above because it then spews big nasty warnings about 'detached HEAD' state that we can't silence as easily as we can silence them using "git checkout" directly # Compile and install lvm2 RUN cd /usr/local/lvm2 && ./configure --enable-static_link && make device-mapper && make install_device-mapper # see https://git.fedorahosted.org/cgit/lvm2.git/tree/INSTALL # Install Go RUN curl -sSL https://golang.org/dl/go1.3.src.tar.gz | tar -v -C /usr/local -xz ENV PATH /usr/local/go/bin:$PATH ENV GOPATH /go:/go/src/github.com/docker/docker/vendor RUN cd /usr/local/go/src && ./make.bash --no-clean 2>&1 # Compile Go for cross compilation ENV DOCKER_CROSSPLATFORMS \ linux/386 linux/arm \ darwin/amd64 darwin/386 \ freebsd/amd64 freebsd/386 freebsd/arm # (set an explicit GOARM of 5 for maximum compatibility) ENV GOARM 5 RUN cd /usr/local/go/src && bash -xc 'for platform in $DOCKER_CROSSPLATFORMS; do GOOS=${platform%/*} GOARCH=${platform##*/} ./make.bash --no-clean 2>&1; done' # Grab Go's cover tool for dead-simple code coverage testing RUN go get golang.org/x/tools/cmd/cover # TODO replace FPM with some very minimal debhelper stuff RUN gem install --no-rdoc --no-ri fpm --version 1.0.2 # Get the "busybox" image source so we can build locally instead of pulling RUN git clone -b buildroot-2014.02 https://github.com/jpetazzo/docker-busybox.git /docker-busybox # Setup s3cmd config RUN /bin/echo -e '[default]\naccess_key=$AWS_ACCESS_KEY\nsecret_key=$AWS_SECRET_KEY' > /.s3cfg # Set user.email so crosbymichael's in-container merge commits go smoothly RUN git config --global user.email 'docker-dummy@example.com' # Add an unprivileged user to be used for tests which need it RUN groupadd -r docker RUN useradd --create-home --gid docker unprivilegeduser VOLUME /var/lib/docker WORKDIR /go/src/github.com/docker/docker ENV DOCKER_BUILDTAGS apparmor selinux # Wrap all commands in the "docker-in-docker" script to allow nested containers ENTRYPOINT ["hack/dind"] # Upload docker source COPY . /go/src/github.com/docker/docker ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/docker/result ================================================ (from "ubuntu:14.04") (maintainer "Tianon Gravi (@tianon)") (run "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -yq \tapt-utils \taufs-tools \tautomake \tbtrfs-tools \tbuild-essential \tcurl \tdpkg-sig \tgit \tiptables \tlibapparmor-dev \tlibcap-dev \tlibsqlite3-dev \tlxc=1.0* \tmercurial \tpandoc \tparallel \treprepro \truby1.9.1 \truby1.9.1-dev \ts3cmd=1.1.0* \t--no-install-recommends") (run "git clone --no-checkout https://git.fedorahosted.org/git/lvm2.git /usr/local/lvm2 && cd /usr/local/lvm2 && git checkout -q v2_02_103") (run "cd /usr/local/lvm2 && ./configure --enable-static_link && make device-mapper && make install_device-mapper") (run "curl -sSL https://golang.org/dl/go1.3.src.tar.gz | tar -v -C /usr/local -xz") (env "PATH" "/usr/local/go/bin:$PATH") (env "GOPATH" "/go:/go/src/github.com/docker/docker/vendor") (run "cd /usr/local/go/src && ./make.bash --no-clean 2>&1") (env "DOCKER_CROSSPLATFORMS" "linux/386 linux/arm \tdarwin/amd64 darwin/386 \tfreebsd/amd64 freebsd/386 freebsd/arm") (env "GOARM" "5") (run "cd /usr/local/go/src && bash -xc 'for platform in $DOCKER_CROSSPLATFORMS; do GOOS=${platform%/*} GOARCH=${platform##*/} ./make.bash --no-clean 2>&1; done'") (run "go get golang.org/x/tools/cmd/cover") (run "gem install --no-rdoc --no-ri fpm --version 1.0.2") (run "git clone -b buildroot-2014.02 https://github.com/jpetazzo/docker-busybox.git /docker-busybox") (run "/bin/echo -e '[default]\\naccess_key=$AWS_ACCESS_KEY\\nsecret_key=$AWS_SECRET_KEY' > /.s3cfg") (run "git config --global user.email 'docker-dummy@example.com'") (run "groupadd -r docker") (run "useradd --create-home --gid docker unprivilegeduser") (volume "/var/lib/docker") (workdir "/go/src/github.com/docker/docker") (env "DOCKER_BUILDTAGS" "apparmor selinux") (entrypoint "hack/dind") (copy "." "/go/src/github.com/docker/docker") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/env/Dockerfile ================================================ FROM ubuntu ENV name value ENV name=value ENV name=value name2=value2 ENV name="value value1" ENV name=value\ value2 ENV name="value'quote space'value2" ENV name='value"double quote"value2' ENV name=value\ value2 name2=value2\ value3 ENV name="a\"b" ENV name="a\'b" ENV name='a\'b' ENV name='a\'b'' ENV name='a\"b' ENV name="''" # don't put anything after the next line - it must be the last line of the # Dockerfile and it must end with \ ENV name=value \ name1=value1 \ name2="value2a \ value2b" \ name3="value3a\n\"value3b\"" \ name4="value4a\\nvalue4b" \ ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/env/result ================================================ (from "ubuntu") (env "name" "value") (env "name" "value") (env "name" "value" "name2" "value2") (env "name" "\"value value1\"") (env "name" "value\\ value2") (env "name" "\"value'quote space'value2\"") (env "name" "'value\"double quote\"value2'") (env "name" "value\\ value2" "name2" "value2\\ value3") (env "name" "\"a\\\"b\"") (env "name" "\"a\\'b\"") (env "name" "'a\\'b'") (env "name" "'a\\'b''") (env "name" "'a\\\"b'") (env "name" "\"''\"") (env "name" "value" "name1" "value1" "name2" "\"value2a value2b\"" "name3" "\"value3a\\n\\\"value3b\\\"\"" "name4" "\"value4a\\\\nvalue4b\"") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/escapes/Dockerfile ================================================ FROM ubuntu:14.04 MAINTAINER Erik \\Hollensbe \" RUN apt-get \update && \ apt-get \"install znc -y ADD \conf\\" /.znc RUN foo \ bar \ baz CMD [ "\/usr\\\"/bin/znc", "-f", "-r" ] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/escapes/result ================================================ (from "ubuntu:14.04") (maintainer "Erik \\\\Hollensbe \\\"") (run "apt-get \\update && apt-get \\\"install znc -y") (add "\\conf\\\\\"" "/.znc") (run "foo bar baz") (cmd "/usr\\\"/bin/znc" "-f" "-r") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/flags/Dockerfile ================================================ FROM scratch COPY foo /tmp/ COPY --user=me foo /tmp/ COPY --doit=true foo /tmp/ COPY --user=me --doit=true foo /tmp/ COPY --doit=true -- foo /tmp/ COPY -- foo /tmp/ CMD --doit [ "a", "b" ] CMD --doit=true -- [ "a", "b" ] CMD --doit -- [ ] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/flags/result ================================================ (from "scratch") (copy "foo" "/tmp/") (copy ["--user=me"] "foo" "/tmp/") (copy ["--doit=true"] "foo" "/tmp/") (copy ["--user=me" "--doit=true"] "foo" "/tmp/") (copy ["--doit=true"] "foo" "/tmp/") (copy "foo" "/tmp/") (cmd ["--doit"] "a" "b") (cmd ["--doit=true"] "a" "b") (cmd ["--doit"]) ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/influxdb/Dockerfile ================================================ FROM ubuntu:14.04 RUN apt-get update && apt-get install wget -y RUN wget http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb RUN dpkg -i influxdb_latest_amd64.deb RUN rm -r /opt/influxdb/shared VOLUME /opt/influxdb/shared CMD /usr/bin/influxdb --pidfile /var/run/influxdb.pid -config /opt/influxdb/shared/config.toml EXPOSE 8083 EXPOSE 8086 EXPOSE 8090 EXPOSE 8099 ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/influxdb/result ================================================ (from "ubuntu:14.04") (run "apt-get update && apt-get install wget -y") (run "wget http://s3.amazonaws.com/influxdb/influxdb_latest_amd64.deb") (run "dpkg -i influxdb_latest_amd64.deb") (run "rm -r /opt/influxdb/shared") (volume "/opt/influxdb/shared") (cmd "/usr/bin/influxdb --pidfile /var/run/influxdb.pid -config /opt/influxdb/shared/config.toml") (expose "8083") (expose "8086") (expose "8090") (expose "8099") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-json-inside-string/Dockerfile ================================================ CMD '["echo", "Well, JSON in a string is JSON too?"]' ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-json-inside-string/result ================================================ (cmd "'[\"echo\", \"Well, JSON in a string is JSON too?\"]'") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-json-inside-string-double/Dockerfile ================================================ CMD "[\"echo\", \"Phew, I just managed to escaped those double quotes\"]" ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-json-inside-string-double/result ================================================ (cmd "\"[\\\"echo\\\", \\\"Phew, I just managed to escaped those double quotes\\\"]\"") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-single-quotes/Dockerfile ================================================ CMD ['echo','single quotes are invalid JSON'] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-single-quotes/result ================================================ (cmd "['echo','single quotes are invalid JSON']") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-unterminated-bracket/Dockerfile ================================================ CMD ["echo", "Please, close the brackets when you're done" ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-unterminated-bracket/result ================================================ (cmd "[\"echo\", \"Please, close the brackets when you're done\"") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-unterminated-string/Dockerfile ================================================ CMD ["echo", "look ma, no quote!] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/jeztah-invalid-json-unterminated-string/result ================================================ (cmd "[\"echo\", \"look ma, no quote!]") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/json/Dockerfile ================================================ CMD [] CMD [""] CMD ["a"] CMD ["a","b"] CMD [ "a", "b" ] CMD [ "a", "b" ] CMD [ "a", "b" ] CMD ["abc 123", "♥", "☃", "\" \\ \/ \b \f \n \r \t \u0000"] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/json/result ================================================ (cmd) (cmd "") (cmd "a") (cmd "a" "b") (cmd "a" "b") (cmd "a" "b") (cmd "a" "b") (cmd "abc 123" "♥" "☃" "\" \\ / \b \f \n \r \t \x00") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/kartar-entrypoint-oddities/Dockerfile ================================================ FROM ubuntu:14.04 MAINTAINER James Turnbull "james@example.com" ENV REFRESHED_AT 2014-06-01 RUN apt-get update RUN apt-get -y install redis-server redis-tools EXPOSE 6379 ENTRYPOINT [ "/usr/bin/redis-server" ] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/kartar-entrypoint-oddities/result ================================================ (from "ubuntu:14.04") (maintainer "James Turnbull \"james@example.com\"") (env "REFRESHED_AT" "2014-06-01") (run "apt-get update") (run "apt-get -y install redis-server redis-tools") (expose "6379") (entrypoint "/usr/bin/redis-server") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/lk4d4-the-edge-case-generator/Dockerfile ================================================ FROM busybox:buildroot-2014.02 MAINTAINER docker ONBUILD RUN ["echo", "test"] ONBUILD RUN echo test ONBUILD COPY . / # RUN Commands \ # linebreak in comment \ RUN ["ls", "-la"] RUN ["echo", "'1234'"] RUN echo "1234" RUN echo 1234 RUN echo '1234' && \ echo "456" && \ echo 789 RUN sh -c 'echo root:testpass \ > /tmp/passwd' RUN mkdir -p /test /test2 /test3/test # ENV \ ENV SCUBA 1 DUBA 3 ENV SCUBA "1 DUBA 3" # CMD \ CMD ["echo", "test"] CMD echo test CMD echo "test" CMD echo 'test' CMD echo 'test' | wc - #EXPOSE\ EXPOSE 3000 EXPOSE 9000 5000 6000 USER docker USER docker:root VOLUME ["/test"] VOLUME ["/test", "/test2"] VOLUME /test3 WORKDIR /test ADD . / COPY . copy ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/lk4d4-the-edge-case-generator/result ================================================ (from "busybox:buildroot-2014.02") (maintainer "docker ") (onbuild (run "echo" "test")) (onbuild (run "echo test")) (onbuild (copy "." "/")) (run "ls" "-la") (run "echo" "'1234'") (run "echo \"1234\"") (run "echo 1234") (run "echo '1234' && echo \"456\" && echo 789") (run "sh -c 'echo root:testpass > /tmp/passwd'") (run "mkdir -p /test /test2 /test3/test") (env "SCUBA" "1 DUBA 3") (env "SCUBA" "\"1 DUBA 3\"") (cmd "echo" "test") (cmd "echo test") (cmd "echo \"test\"") (cmd "echo 'test'") (cmd "echo 'test' | wc -") (expose "3000") (expose "9000" "5000" "6000") (user "docker") (user "docker:root") (volume "/test") (volume "/test" "/test2") (volume "/test3") (workdir "/test") (add "." "/") (copy "." "copy") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/mail/Dockerfile ================================================ FROM ubuntu:14.04 RUN apt-get update -qy && apt-get install mutt offlineimap vim-nox abook elinks curl tmux cron zsh -y ADD .muttrc / ADD .offlineimaprc / ADD .tmux.conf / ADD mutt /.mutt ADD vim /.vim ADD vimrc /.vimrc ADD crontab /etc/crontab RUN chmod 644 /etc/crontab RUN mkdir /Mail RUN mkdir /.offlineimap RUN echo "export TERM=screen-256color" >/.zshenv CMD setsid cron; tmux -2 ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/mail/result ================================================ (from "ubuntu:14.04") (run "apt-get update -qy && apt-get install mutt offlineimap vim-nox abook elinks curl tmux cron zsh -y") (add ".muttrc" "/") (add ".offlineimaprc" "/") (add ".tmux.conf" "/") (add "mutt" "/.mutt") (add "vim" "/.vim") (add "vimrc" "/.vimrc") (add "crontab" "/etc/crontab") (run "chmod 644 /etc/crontab") (run "mkdir /Mail") (run "mkdir /.offlineimap") (run "echo \"export TERM=screen-256color\" >/.zshenv") (cmd "setsid cron; tmux -2") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/multiple-volumes/Dockerfile ================================================ FROM foo VOLUME /opt/nagios/var /opt/nagios/etc /opt/nagios/libexec /var/log/apache2 /usr/share/snmp/mibs ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/multiple-volumes/result ================================================ (from "foo") (volume "/opt/nagios/var" "/opt/nagios/etc" "/opt/nagios/libexec" "/var/log/apache2" "/usr/share/snmp/mibs") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/mumble/Dockerfile ================================================ FROM ubuntu:14.04 RUN apt-get update && apt-get install libcap2-bin mumble-server -y ADD ./mumble-server.ini /etc/mumble-server.ini CMD /usr/sbin/murmurd ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/mumble/result ================================================ (from "ubuntu:14.04") (run "apt-get update && apt-get install libcap2-bin mumble-server -y") (add "./mumble-server.ini" "/etc/mumble-server.ini") (cmd "/usr/sbin/murmurd") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/nginx/Dockerfile ================================================ FROM ubuntu:14.04 MAINTAINER Erik Hollensbe RUN apt-get update && apt-get install nginx-full -y RUN rm -rf /etc/nginx ADD etc /etc/nginx RUN chown -R root:root /etc/nginx RUN /usr/sbin/nginx -qt RUN mkdir /www CMD ["/usr/sbin/nginx"] VOLUME /www EXPOSE 80 ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/nginx/result ================================================ (from "ubuntu:14.04") (maintainer "Erik Hollensbe ") (run "apt-get update && apt-get install nginx-full -y") (run "rm -rf /etc/nginx") (add "etc" "/etc/nginx") (run "chown -R root:root /etc/nginx") (run "/usr/sbin/nginx -qt") (run "mkdir /www") (cmd "/usr/sbin/nginx") (volume "/www") (expose "80") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/tf2/Dockerfile ================================================ FROM ubuntu:12.04 EXPOSE 27015 EXPOSE 27005 EXPOSE 26901 EXPOSE 27020 RUN apt-get update && apt-get install libc6-dev-i386 curl unzip -y RUN mkdir -p /steam RUN curl http://media.steampowered.com/client/steamcmd_linux.tar.gz | tar vxz -C /steam ADD ./script /steam/script RUN /steam/steamcmd.sh +runscript /steam/script RUN curl http://mirror.pointysoftware.net/alliedmodders/mmsource-1.10.0-linux.tar.gz | tar vxz -C /steam/tf2/tf RUN curl http://mirror.pointysoftware.net/alliedmodders/sourcemod-1.5.3-linux.tar.gz | tar vxz -C /steam/tf2/tf ADD ./server.cfg /steam/tf2/tf/cfg/server.cfg ADD ./ctf_2fort.cfg /steam/tf2/tf/cfg/ctf_2fort.cfg ADD ./sourcemod.cfg /steam/tf2/tf/cfg/sourcemod/sourcemod.cfg RUN rm -r /steam/tf2/tf/addons/sourcemod/configs ADD ./configs /steam/tf2/tf/addons/sourcemod/configs RUN mkdir -p /steam/tf2/tf/addons/sourcemod/translations/en RUN cp /steam/tf2/tf/addons/sourcemod/translations/*.txt /steam/tf2/tf/addons/sourcemod/translations/en CMD cd /steam/tf2 && ./srcds_run -port 27015 +ip 0.0.0.0 +map ctf_2fort -autoupdate -steam_dir /steam -steamcmd_script /steam/script +tf_bot_quota 12 +tf_bot_quota_mode fill ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/tf2/result ================================================ (from "ubuntu:12.04") (expose "27015") (expose "27005") (expose "26901") (expose "27020") (run "apt-get update && apt-get install libc6-dev-i386 curl unzip -y") (run "mkdir -p /steam") (run "curl http://media.steampowered.com/client/steamcmd_linux.tar.gz | tar vxz -C /steam") (add "./script" "/steam/script") (run "/steam/steamcmd.sh +runscript /steam/script") (run "curl http://mirror.pointysoftware.net/alliedmodders/mmsource-1.10.0-linux.tar.gz | tar vxz -C /steam/tf2/tf") (run "curl http://mirror.pointysoftware.net/alliedmodders/sourcemod-1.5.3-linux.tar.gz | tar vxz -C /steam/tf2/tf") (add "./server.cfg" "/steam/tf2/tf/cfg/server.cfg") (add "./ctf_2fort.cfg" "/steam/tf2/tf/cfg/ctf_2fort.cfg") (add "./sourcemod.cfg" "/steam/tf2/tf/cfg/sourcemod/sourcemod.cfg") (run "rm -r /steam/tf2/tf/addons/sourcemod/configs") (add "./configs" "/steam/tf2/tf/addons/sourcemod/configs") (run "mkdir -p /steam/tf2/tf/addons/sourcemod/translations/en") (run "cp /steam/tf2/tf/addons/sourcemod/translations/*.txt /steam/tf2/tf/addons/sourcemod/translations/en") (cmd "cd /steam/tf2 && ./srcds_run -port 27015 +ip 0.0.0.0 +map ctf_2fort -autoupdate -steam_dir /steam -steamcmd_script /steam/script +tf_bot_quota 12 +tf_bot_quota_mode fill") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/weechat/Dockerfile ================================================ FROM ubuntu:14.04 RUN apt-get update -qy && apt-get install tmux zsh weechat-curses -y ADD .weechat /.weechat ADD .tmux.conf / RUN echo "export TERM=screen-256color" >/.zshenv CMD zsh -c weechat ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/weechat/result ================================================ (from "ubuntu:14.04") (run "apt-get update -qy && apt-get install tmux zsh weechat-curses -y") (add ".weechat" "/.weechat") (add ".tmux.conf" "/") (run "echo \"export TERM=screen-256color\" >/.zshenv") (cmd "zsh -c weechat") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/znc/Dockerfile ================================================ FROM ubuntu:14.04 MAINTAINER Erik Hollensbe RUN apt-get update && apt-get install znc -y ADD conf /.znc CMD [ "/usr/bin/znc", "-f", "-r" ] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles/znc/result ================================================ (from "ubuntu:14.04") (maintainer "Erik Hollensbe ") (run "apt-get update && apt-get install znc -y") (add "conf" "/.znc") (cmd "/usr/bin/znc" "-f" "-r") ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles-negative/env_no_value/Dockerfile ================================================ FROM busybox ENV PATH ================================================ FILE: vendor/github.com/docker/docker/builder/parser/testfiles-negative/shykes-nested-json/Dockerfile ================================================ CMD [ "echo", [ "nested json" ] ] ================================================ FILE: vendor/github.com/docker/docker/builder/parser/utils.go ================================================ package parser import ( "fmt" "strconv" "strings" "unicode" ) // dumps the AST defined by `node` as a list of sexps. Returns a string // suitable for printing. func (node *Node) Dump() string { str := "" str += node.Value if len(node.Flags) > 0 { str += fmt.Sprintf(" %q", node.Flags) } for _, n := range node.Children { str += "(" + n.Dump() + ")\n" } if node.Next != nil { for n := node.Next; n != nil; n = n.Next { if len(n.Children) > 0 { str += " " + n.Dump() } else { str += " " + strconv.Quote(n.Value) } } } return strings.TrimSpace(str) } // performs the dispatch based on the two primal strings, cmd and args. Please // look at the dispatch table in parser.go to see how these dispatchers work. func fullDispatch(cmd, args string) (*Node, map[string]bool, error) { fn := dispatch[cmd] // Ignore invalid Dockerfile instructions if fn == nil { fn = parseIgnore } sexp, attrs, err := fn(args) if err != nil { return nil, nil, err } return sexp, attrs, nil } // splitCommand takes a single line of text and parses out the cmd and args, // which are used for dispatching to more exact parsing functions. func splitCommand(line string) (string, []string, string, error) { var args string var flags []string // Make sure we get the same results irrespective of leading/trailing spaces cmdline := TOKEN_WHITESPACE.Split(strings.TrimSpace(line), 2) cmd := strings.ToLower(cmdline[0]) if len(cmdline) == 2 { var err error args, flags, err = extractBuilderFlags(cmdline[1]) if err != nil { return "", nil, "", err } } return cmd, flags, strings.TrimSpace(args), nil } // covers comments and empty lines. Lines should be trimmed before passing to // this function. func stripComments(line string) string { // string is already trimmed at this point if TOKEN_COMMENT.MatchString(line) { return TOKEN_COMMENT.ReplaceAllString(line, "") } return line } func extractBuilderFlags(line string) (string, []string, error) { // Parses the BuilderFlags and returns the remaining part of the line const ( inSpaces = iota // looking for start of a word inWord inQuote ) words := []string{} phase := inSpaces word := "" quote := '\000' blankOK := false var ch rune for pos := 0; pos <= len(line); pos++ { if pos != len(line) { ch = rune(line[pos]) } if phase == inSpaces { // Looking for start of word if pos == len(line) { // end of input break } if unicode.IsSpace(ch) { // skip spaces continue } // Only keep going if the next word starts with -- if ch != '-' || pos+1 == len(line) || rune(line[pos+1]) != '-' { return line[pos:], words, nil } phase = inWord // found someting with "--", fall thru } if (phase == inWord || phase == inQuote) && (pos == len(line)) { if word != "--" && (blankOK || len(word) > 0) { words = append(words, word) } break } if phase == inWord { if unicode.IsSpace(ch) { phase = inSpaces if word == "--" { return line[pos:], words, nil } if blankOK || len(word) > 0 { words = append(words, word) } word = "" blankOK = false continue } if ch == '\'' || ch == '"' { quote = ch blankOK = true phase = inQuote continue } if ch == '\\' { if pos+1 == len(line) { continue // just skip \ at end } pos++ ch = rune(line[pos]) } word += string(ch) continue } if phase == inQuote { if ch == quote { phase = inWord continue } if ch == '\\' { if pos+1 == len(line) { phase = inWord continue // just skip \ at end } pos++ ch = rune(line[pos]) } word += string(ch) } } return "", words, nil } ================================================ FILE: vendor/github.com/docker/docker/builder/shell_parser.go ================================================ package builder // This will take a single word and an array of env variables and // process all quotes (" and ') as well as $xxx and ${xxx} env variable // tokens. Tries to mimic bash shell process. // It doesn't support all flavors of ${xx:...} formats but new ones can // be added by adding code to the "special ${} format processing" section import ( "fmt" "strings" "unicode" ) type shellWord struct { word string envs []string pos int } func ProcessWord(word string, env []string) (string, error) { sw := &shellWord{ word: word, envs: env, pos: 0, } return sw.process() } func (sw *shellWord) process() (string, error) { return sw.processStopOn('\000') } // Process the word, starting at 'pos', and stop when we get to the // end of the word or the 'stopChar' character func (sw *shellWord) processStopOn(stopChar rune) (string, error) { var result string var charFuncMapping = map[rune]func() (string, error){ '\'': sw.processSingleQuote, '"': sw.processDoubleQuote, '$': sw.processDollar, } for sw.pos < len(sw.word) { ch := sw.peek() if stopChar != '\000' && ch == stopChar { sw.next() break } if fn, ok := charFuncMapping[ch]; ok { // Call special processing func for certain chars tmp, err := fn() if err != nil { return "", err } result += tmp } else { // Not special, just add it to the result ch = sw.next() if ch == '\\' { // '\' escapes, except end of line ch = sw.next() if ch == '\000' { continue } } result += string(ch) } } return result, nil } func (sw *shellWord) peek() rune { if sw.pos == len(sw.word) { return '\000' } return rune(sw.word[sw.pos]) } func (sw *shellWord) next() rune { if sw.pos == len(sw.word) { return '\000' } ch := rune(sw.word[sw.pos]) sw.pos++ return ch } func (sw *shellWord) processSingleQuote() (string, error) { // All chars between single quotes are taken as-is // Note, you can't escape ' var result string sw.next() for { ch := sw.next() if ch == '\000' || ch == '\'' { break } result += string(ch) } return result, nil } func (sw *shellWord) processDoubleQuote() (string, error) { // All chars up to the next " are taken as-is, even ', except any $ chars // But you can escape " with a \ var result string sw.next() for sw.pos < len(sw.word) { ch := sw.peek() if ch == '"' { sw.next() break } if ch == '$' { tmp, err := sw.processDollar() if err != nil { return "", err } result += tmp } else { ch = sw.next() if ch == '\\' { chNext := sw.peek() if chNext == '\000' { // Ignore \ at end of word continue } if chNext == '"' || chNext == '$' { // \" and \$ can be escaped, all other \'s are left as-is ch = sw.next() } } result += string(ch) } } return result, nil } func (sw *shellWord) processDollar() (string, error) { sw.next() ch := sw.peek() if ch == '{' { sw.next() name := sw.processName() ch = sw.peek() if ch == '}' { // Normal ${xx} case sw.next() return sw.getEnv(name), nil } if ch == ':' { // Special ${xx:...} format processing // Yes it allows for recursive $'s in the ... spot sw.next() // skip over : modifier := sw.next() word, err := sw.processStopOn('}') if err != nil { return "", err } // Grab the current value of the variable in question so we // can use to to determine what to do based on the modifier newValue := sw.getEnv(name) switch modifier { case '+': if newValue != "" { newValue = word } return newValue, nil case '-': if newValue == "" { newValue = word } return newValue, nil default: return "", fmt.Errorf("Unsupported modifier (%c) in substitution: %s", modifier, sw.word) } } return "", fmt.Errorf("Missing ':' in substitution: %s", sw.word) } // $xxx case name := sw.processName() if name == "" { return "$", nil } return sw.getEnv(name), nil } func (sw *shellWord) processName() string { // Read in a name (alphanumeric or _) // If it starts with a numeric then just return $# var name string for sw.pos < len(sw.word) { ch := sw.peek() if len(name) == 0 && unicode.IsDigit(ch) { ch = sw.next() return string(ch) } if !unicode.IsLetter(ch) && !unicode.IsDigit(ch) && ch != '_' { break } ch = sw.next() name += string(ch) } return name } func (sw *shellWord) getEnv(name string) string { for _, env := range sw.envs { i := strings.Index(env, "=") if i < 0 { if name == env { // Should probably never get here, but just in case treat // it like "var" and "var=" are the same return "" } continue } if name != env[:i] { continue } return env[i+1:] } return "" } ================================================ FILE: vendor/github.com/docker/docker/builder/shell_parser_test.go ================================================ package builder import ( "bufio" "os" "strings" "testing" ) func TestShellParser(t *testing.T) { file, err := os.Open("words") if err != nil { t.Fatalf("Can't open 'words': %s", err) } defer file.Close() scanner := bufio.NewScanner(file) envs := []string{"PWD=/home", "SHELL=bash"} for scanner.Scan() { line := scanner.Text() // Trim comments and blank lines i := strings.Index(line, "#") if i >= 0 { line = line[:i] } line = strings.TrimSpace(line) if line == "" { continue } words := strings.Split(line, "|") if len(words) != 2 { t.Fatalf("Error in 'words' - should be 2 words:%q", words) } words[0] = strings.TrimSpace(words[0]) words[1] = strings.TrimSpace(words[1]) newWord, err := ProcessWord(words[0], envs) if err != nil { newWord = "error" } if newWord != words[1] { t.Fatalf("Error. Src: %s Calc: %s Expected: %s", words[0], newWord, words[1]) } } } ================================================ FILE: vendor/github.com/docker/docker/builder/support.go ================================================ package builder import ( "regexp" "strings" ) const acceptableRemoteMIME = `(?:application/(?:(?:x\-)?tar|octet\-stream|((?:x\-)?(?:gzip|bzip2?|xz)))|(?:text/plain))` var mimeRe = regexp.MustCompile(acceptableRemoteMIME) func selectAcceptableMIME(ct string) string { return mimeRe.FindString(ct) } func handleJsonArgs(args []string, attributes map[string]bool) []string { if len(args) == 0 { return []string{} } if attributes != nil && attributes["json"] { return args } // literal string command, not an exec array return []string{strings.Join(args, " ")} } ================================================ FILE: vendor/github.com/docker/docker/builder/support_test.go ================================================ package builder import ( "fmt" "testing" ) func TestSelectAcceptableMIME(t *testing.T) { validMimeStrings := []string{ "application/x-bzip2", "application/bzip2", "application/gzip", "application/x-gzip", "application/x-xz", "application/xz", "application/tar", "application/x-tar", "application/octet-stream", "text/plain", } invalidMimeStrings := []string{ "", "application/octet", "application/json", } for _, m := range invalidMimeStrings { if len(selectAcceptableMIME(m)) > 0 { err := fmt.Errorf("Should not have accepted %q", m) t.Fatal(err) } } for _, m := range validMimeStrings { if str := selectAcceptableMIME(m); str == "" { err := fmt.Errorf("Should have accepted %q", m) t.Fatal(err) } } } ================================================ FILE: vendor/github.com/docker/docker/builder/words ================================================ hello | hello he'll'o | hello he'llo | hello he\'llo | he'llo he\\'llo | he\llo abc\tdef | abctdef "abc\tdef" | abc\tdef 'abc\tdef' | abc\tdef hello\ | hello hello\\ | hello\ "hello | hello "hello\" | hello" "hel'lo" | hel'lo 'hello | hello 'hello\' | hello\ "''" | '' $. | $. $1 | he$1x | hex he$.x | he$.x he$pwd. | he. he$PWD | he/home he\$PWD | he$PWD he\\$PWD | he\/home he\${} | he${} he\${}xx | he${}xx he${} | he he${}xx | hexx he${hi} | he he${hi}xx | hexx he${PWD} | he/home he${.} | error he${XXX:-000}xx | he000xx he${PWD:-000}xx | he/homexx he${XXX:-$PWD}xx | he/homexx he${XXX:-${PWD:-yyy}}xx | he/homexx he${XXX:-${YYY:-yyy}}xx | heyyyxx he${XXX:YYY} | error he${XXX:+${PWD}}xx | hexx he${PWD:+${XXX}}xx | hexx he${PWD:+${SHELL}}xx | hebashxx he${XXX:+000}xx | hexx he${PWD:+000}xx | he000xx 'he${XX}' | he${XX} "he${PWD}" | he/home "he'$PWD'" | he'/home' "$PWD" | /home '$PWD' | $PWD '\$PWD' | \$PWD '"hello"' | "hello" he\$PWD | he$PWD "he\$PWD" | he$PWD 'he\$PWD' | he\$PWD he${PWD | error he${PWD:=000}xx | error he${PWD:+${PWD}:}xx | he/home:xx he${XXX:-\$PWD:}xx | he$PWD:xx he${XXX:-\${PWD}z}xx | he${PWDz}xx ================================================ FILE: vendor/github.com/docker/docker/cliconfig/config.go ================================================ package cliconfig import ( "encoding/base64" "encoding/json" "fmt" "io/ioutil" "os" "path/filepath" "strings" "github.com/docker/docker/pkg/homedir" "github.com/docker/docker/pkg/system" ) const ( // ConfigFile is the name of config file ConfigFileName = "config.json" oldConfigfile = ".dockercfg" // 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/" ) var ( configDir = os.Getenv("DOCKER_CONFIG") ) func init() { if configDir == "" { configDir = filepath.Join(homedir.Get(), ".docker") } } // ConfigDir returns the directory the configuration file is stored in func ConfigDir() string { return configDir } // SetConfigDir sets the directory the configuration file is stored in func SetConfigDir(dir string) { configDir = dir } // AuthConfig contains authorization information for connecting to a Registry type AuthConfig struct { Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` Auth string `json:"auth"` Email string `json:"email"` ServerAddress string `json:"serveraddress,omitempty"` } // ConfigFile ~/.docker/config.json file info type ConfigFile struct { AuthConfigs map[string]AuthConfig `json:"auths"` HTTPHeaders map[string]string `json:"HttpHeaders,omitempty"` filename string // Note: not serialized - for internal use only } // NewConfigFile initilizes an empty configuration file for the given filename 'fn' func NewConfigFile(fn string) *ConfigFile { return &ConfigFile{ AuthConfigs: make(map[string]AuthConfig), HTTPHeaders: make(map[string]string), filename: fn, } } // Load reads the configuration files in the given directory, and sets up // the auth config information and return values. // FIXME: use the internal golang config parser func Load(configDir string) (*ConfigFile, error) { if configDir == "" { configDir = ConfigDir() } configFile := ConfigFile{ AuthConfigs: make(map[string]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, err } defer file.Close() if err := json.NewDecoder(file).Decode(&configFile); err != nil { return &configFile, err } for addr, ac := range configFile.AuthConfigs { ac.Username, ac.Password, err = DecodeAuth(ac.Auth) if err != nil { return &configFile, err } ac.Auth = "" ac.ServerAddress = addr configFile.AuthConfigs[addr] = ac } return &configFile, nil } 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, 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 } b, err := ioutil.ReadFile(confFile) if err != nil { return &configFile, err } if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil { arr := strings.Split(string(b), "\n") if len(arr) < 2 { return &configFile, fmt.Errorf("The Auth config file is empty") } authConfig := AuthConfig{} origAuth := strings.Split(arr[0], " = ") if len(origAuth) != 2 { return &configFile, fmt.Errorf("Invalid Auth config file") } authConfig.Username, authConfig.Password, err = DecodeAuth(origAuth[1]) if err != nil { return &configFile, err } origEmail := strings.Split(arr[1], " = ") if len(origEmail) != 2 { return &configFile, fmt.Errorf("Invalid Auth config file") } authConfig.Email = origEmail[1] 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 &configFile, err } authConfig.Auth = "" authConfig.ServerAddress = k configFile.AuthConfigs[k] = authConfig } } return &configFile, nil } // Save encodes and writes out all the authorization information func (configFile *ConfigFile) Save() error { // Encode sensitive data into a new/temp struct tmpAuthConfigs := make(map[string]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 } if err := system.MkdirAll(filepath.Dir(configFile.filename), 0700); err != nil { return err } if err := ioutil.WriteFile(configFile.filename, data, 0600); err != nil { return err } return nil } // Filename returns the name of the configuration file func (configFile *ConfigFile) Filename() string { return configFile.filename } // EncodeAuth creates a base64 encoded string to containing authorization information func EncodeAuth(authConfig *AuthConfig) string { 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) { 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 "", "", fmt.Errorf("Something went wrong decoding auth config") } arr := strings.SplitN(string(decoded), ":", 2) if len(arr) != 2 { return "", "", fmt.Errorf("Invalid auth configuration file") } password := strings.Trim(arr[1], "\x00") return arr[0], password, nil } ================================================ FILE: vendor/github.com/docker/docker/cliconfig/config_test.go ================================================ package cliconfig import ( "io/ioutil" "os" "path/filepath" "runtime" "strings" "testing" "github.com/docker/docker/pkg/homedir" ) func TestMissingFile(t *testing.T) { tmpHome, _ := ioutil.TempDir("", "config-test") config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on missing file: %q", err) } // Now save it and make sure it shows up in new form err = config.Save() if err != nil { t.Fatalf("Failed to save: %q", err) } buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) if !strings.Contains(string(buf), `"auths":`) { t.Fatalf("Should have save in new form: %s", string(buf)) } } func TestSaveFileToDirs(t *testing.T) { tmpHome, _ := ioutil.TempDir("", "config-test") tmpHome += "/.docker" config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on missing file: %q", err) } // Now save it and make sure it shows up in new form err = config.Save() if err != nil { t.Fatalf("Failed to save: %q", err) } buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) if !strings.Contains(string(buf), `"auths":`) { t.Fatalf("Should have save in new form: %s", string(buf)) } } func TestEmptyFile(t *testing.T) { tmpHome, _ := ioutil.TempDir("", "config-test") fn := filepath.Join(tmpHome, ConfigFileName) ioutil.WriteFile(fn, []byte(""), 0600) _, err := Load(tmpHome) if err == nil { t.Fatalf("Was supposed to fail") } } func TestEmptyJson(t *testing.T) { tmpHome, _ := ioutil.TempDir("", "config-test") fn := filepath.Join(tmpHome, ConfigFileName) ioutil.WriteFile(fn, []byte("{}"), 0600) config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on empty json file: %q", err) } // Now save it and make sure it shows up in new form err = config.Save() if err != nil { t.Fatalf("Failed to save: %q", err) } buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) if !strings.Contains(string(buf), `"auths":`) { t.Fatalf("Should have save in new form: %s", string(buf)) } } func TestOldJson(t *testing.T) { if runtime.GOOS == "windows" { return } tmpHome, _ := ioutil.TempDir("", "config-test") defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) fn := filepath.Join(tmpHome, oldConfigfile) js := `{"https://index.docker.io/v1/":{"auth":"am9lam9lOmhlbGxv","email":"user@example.com"}}` ioutil.WriteFile(fn, []byte(js), 0600) config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on empty json file: %q", err) } ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Email != "user@example.com" || ac.Username != "joejoe" || ac.Password != "hello" { t.Fatalf("Missing data from parsing:\n%q", config) } // Now save it and make sure it shows up in new form err = config.Save() if err != nil { t.Fatalf("Failed to save: %q", err) } buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) if !strings.Contains(string(buf), `"auths":`) || !strings.Contains(string(buf), "user@example.com") { t.Fatalf("Should have save in new form: %s", string(buf)) } } func TestNewJson(t *testing.T) { tmpHome, _ := ioutil.TempDir("", "config-test") fn := filepath.Join(tmpHome, ConfigFileName) js := ` { "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv", "email": "user@example.com" } } }` ioutil.WriteFile(fn, []byte(js), 0600) config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on empty json file: %q", err) } ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Email != "user@example.com" || ac.Username != "joejoe" || ac.Password != "hello" { t.Fatalf("Missing data from parsing:\n%q", config) } // Now save it and make sure it shows up in new form err = config.Save() if err != nil { t.Fatalf("Failed to save: %q", err) } buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) if !strings.Contains(string(buf), `"auths":`) || !strings.Contains(string(buf), "user@example.com") { t.Fatalf("Should have save in new form: %s", string(buf)) } } ================================================ FILE: vendor/github.com/docker/docker/contrib/README ================================================ The `contrib` directory contains scripts, images, and other helpful things which are not part of the core docker distribution. Please note that they could be out of date, since they do not receive the same attention as the rest of the repository. ================================================ FILE: vendor/github.com/docker/docker/contrib/REVIEWERS ================================================ Tianon Gravi (@tianon) ================================================ FILE: vendor/github.com/docker/docker/contrib/apparmor/docker ================================================ #include profile docker-default flags=(attach_disconnected,mediate_deleted) { #include network, capability, file, umount, deny @{PROC}/sys/fs/** wklx, deny @{PROC}/sysrq-trigger rwklx, deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx, deny @{PROC}/sys/kernel/*/** wklx, deny mount, deny /sys/[^f]*/** wklx, deny /sys/f[^s]*/** wklx, deny /sys/fs/[^c]*/** wklx, deny /sys/fs/c[^g]*/** wklx, deny /sys/fs/cg[^r]*/** wklx, deny /sys/firmware/efi/efivars/** rwklx, deny /sys/kernel/security/** rwklx, } ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/README.md ================================================ # `dockercore/builder-deb` This image's tags contain the dependencies for building Docker `.deb`s for each of the Debian-based platforms Docker targets. To add new tags, see [`contrib/builder/deb` in https://github.com/docker/docker](https://github.com/docker/docker/tree/master/contrib/builder/deb), specifically the `generate.sh` script, whose usage is described in a comment at the top of the file. ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/build.sh ================================================ #!/bin/bash set -e cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" set -x ./generate.sh for d in */; do docker build -t "dockercore/builder-deb:$(basename "$d")" "$d" done ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/debian-jessie/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM debian:jessie RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/debian-stretch/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM debian:stretch RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/debian-wheezy/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM debian:wheezy RUN echo deb http://http.debian.net/debian wheezy-backports main > /etc/apt/sources.list.d/wheezy-backports.list RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/generate.sh ================================================ #!/bin/bash set -e # usage: ./generate.sh [versions] # ie: ./generate.sh # to update all Dockerfiles in this directory # or: ./generate.sh debian-jessie # to only update debian-jessie/Dockerfile # or: ./generate.sh debian-newversion # to create a new folder and a Dockerfile within it cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" versions=( "$@" ) if [ ${#versions[@]} -eq 0 ]; then versions=( */ ) fi versions=( "${versions[@]%/}" ) for version in "${versions[@]}"; do distro="${version%-*}" suite="${version##*-}" from="${distro}:${suite}" mkdir -p "$version" echo "$version -> FROM $from" cat > "$version/Dockerfile" <<-EOF # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM $from EOF case "$from" in debian:wheezy) # add -backports, like our users have to echo "RUN echo deb http://http.debian.net/debian $suite-backports main > /etc/apt/sources.list.d/$suite-backports.list" >> "$version/Dockerfile" ;; esac echo >> "$version/Dockerfile" extraBuildTags= # this list is sorted alphabetically; please keep it that way packages=( bash-completion # for bash-completion debhelper integration btrfs-tools # for "btrfs/ioctl.h" (and "version.h" if possible) build-essential # "essential for building Debian packages" curl ca-certificates # for downloading Go debhelper # for easy ".deb" building dh-apparmor # for apparmor debhelper dh-systemd # for systemd debhelper integration git # for "git commit" info in "docker -v" libapparmor-dev # for "sys/apparmor.h" libdevmapper-dev # for "libdevmapper.h" libsqlite3-dev # for "sqlite3.h" ) if [ "$suite" = 'precise' ]; then # precise has a few package issues # - dh-systemd doesn't exist at all packages=( "${packages[@]/dh-systemd}" ) # - libdevmapper-dev is missing critical structs (too old) packages=( "${packages[@]/libdevmapper-dev}" ) extraBuildTags+=' exclude_graphdriver_devicemapper' # - btrfs-tools is missing "ioctl.h" (too old), so it's useless # (since kernels on precise are old too, just skip btrfs entirely) packages=( "${packages[@]/btrfs-tools}" ) extraBuildTags+=' exclude_graphdriver_btrfs' fi echo "RUN apt-get update && apt-get install -y ${packages[*]} --no-install-recommends && rm -rf /var/lib/apt/lists/*" >> "$version/Dockerfile" echo >> "$version/Dockerfile" awk '$1 == "ENV" && $2 == "GO_VERSION" { print; exit }' ../../../Dockerfile >> "$version/Dockerfile" echo 'RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local' >> "$version/Dockerfile" echo 'ENV PATH $PATH:/usr/local/go/bin' >> "$version/Dockerfile" echo >> "$version/Dockerfile" echo 'ENV AUTO_GOPATH 1' >> "$version/Dockerfile" awk '$1 == "ENV" && $2 == "DOCKER_BUILDTAGS" { print $0 "'"$extraBuildTags"'"; exit }' ../../../Dockerfile >> "$version/Dockerfile" done ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/ubuntu-debootstrap-precise/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM ubuntu-debootstrap:precise RUN apt-get update && apt-get install -y bash-completion build-essential curl ca-certificates debhelper git libapparmor-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux exclude_graphdriver_devicemapper exclude_graphdriver_btrfs ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/ubuntu-debootstrap-trusty/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM ubuntu-debootstrap:trusty RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/ubuntu-debootstrap-utopic/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM ubuntu-debootstrap:utopic RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/ubuntu-debootstrap-vivid/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM ubuntu-debootstrap:vivid RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/deb/ubuntu-debootstrap-wily/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/deb/generate.sh"! # FROM ubuntu-debootstrap:wily RUN apt-get update && apt-get install -y bash-completion btrfs-tools build-essential curl ca-certificates debhelper dh-systemd git libapparmor-dev libdevmapper-dev libsqlite3-dev --no-install-recommends && rm -rf /var/lib/apt/lists/* ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS apparmor selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/README.md ================================================ # `dockercore/builder-rpm` This image's tags contain the dependencies for building Docker `.rpm`s for each of the RPM-based platforms Docker targets. To add new tags, see [`contrib/builder/rpm` in https://github.com/docker/docker](https://github.com/docker/docker/tree/master/contrib/builder/rpm), specifically the `generate.sh` script, whose usage is described in a comment at the top of the file. ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/build.sh ================================================ #!/bin/bash set -e cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" set -x ./generate.sh for d in */; do docker build -t "dockercore/builder-rpm:$(basename "$d")" "$d" done ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/centos-7/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/rpm/generate.sh"! # FROM centos:7 RUN yum groupinstall -y "Development Tools" RUN yum -y swap -- remove systemd-container systemd-container-libs -- install systemd systemd-libs RUN yum install -y btrfs-progs-devel device-mapper-devel glibc-static libselinux-devel sqlite-devel tar ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/fedora-20/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/rpm/generate.sh"! # FROM fedora:20 RUN yum install -y @development-tools fedora-packager RUN yum install -y btrfs-progs-devel device-mapper-devel glibc-static libselinux-devel sqlite-devel tar ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/fedora-21/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/rpm/generate.sh"! # FROM fedora:21 RUN yum install -y @development-tools fedora-packager RUN yum install -y btrfs-progs-devel device-mapper-devel glibc-static libselinux-devel sqlite-devel tar ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/fedora-22/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/rpm/generate.sh"! # FROM fedora:22 RUN yum install -y @development-tools fedora-packager RUN yum install -y btrfs-progs-devel device-mapper-devel glibc-static libselinux-devel sqlite-devel tar ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/generate.sh ================================================ #!/bin/bash set -e # usage: ./generate.sh [versions] # ie: ./generate.sh # to update all Dockerfiles in this directory # or: ./generate.sh # to only update fedora-20/Dockerfile # or: ./generate.sh fedora-newversion # to create a new folder and a Dockerfile within it cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" versions=( "$@" ) if [ ${#versions[@]} -eq 0 ]; then versions=( */ ) fi versions=( "${versions[@]%/}" ) for version in "${versions[@]}"; do distro="${version%-*}" suite="${version##*-}" from="${distro}:${suite}" mkdir -p "$version" echo "$version -> FROM $from" cat > "$version/Dockerfile" <<-EOF # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/rpm/generate.sh"! # FROM $from EOF echo >> "$version/Dockerfile" case "$from" in centos:*) # get "Development Tools" packages dependencies echo 'RUN yum groupinstall -y "Development Tools"' >> "$version/Dockerfile" if [[ "$version" == "centos-7" ]]; then echo 'RUN yum -y swap -- remove systemd-container systemd-container-libs -- install systemd systemd-libs' >> "$version/Dockerfile" fi ;; oraclelinux:*) # get "Development Tools" packages and dependencies echo 'RUN yum groupinstall -y "Development Tools"' >> "$version/Dockerfile" ;; *) echo 'RUN yum install -y @development-tools fedora-packager' >> "$version/Dockerfile" ;; esac # this list is sorted alphabetically; please keep it that way packages=( btrfs-progs-devel # for "btrfs/ioctl.h" (and "version.h" if possible) device-mapper-devel # for "libdevmapper.h" glibc-static libselinux-devel # for "libselinux.so" sqlite-devel # for "sqlite3.h" tar # older versions of dev-tools do not have tar ) case "$from" in oraclelinux:7) # Enable the optional repository packages=( --enablerepo=ol7_optional_latest "${packages[*]}" ) ;; esac echo "RUN yum install -y ${packages[*]}" >> "$version/Dockerfile" echo >> "$version/Dockerfile" awk '$1 == "ENV" && $2 == "GO_VERSION" { print; exit }' ../../../Dockerfile >> "$version/Dockerfile" echo 'RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local' >> "$version/Dockerfile" echo 'ENV PATH $PATH:/usr/local/go/bin' >> "$version/Dockerfile" echo >> "$version/Dockerfile" echo 'ENV AUTO_GOPATH 1' >> "$version/Dockerfile" echo 'ENV DOCKER_BUILDTAGS selinux' >> "$version/Dockerfile" done ================================================ FILE: vendor/github.com/docker/docker/contrib/builder/rpm/oraclelinux-7/Dockerfile ================================================ # # THIS FILE IS AUTOGENERATED; SEE "contrib/builder/rpm/generate.sh"! # FROM oraclelinux:7 RUN yum groupinstall -y "Development Tools" RUN yum install -y --enablerepo=ol7_optional_latest btrfs-progs-devel device-mapper-devel glibc-static libselinux-devel sqlite-devel tar ENV GO_VERSION 1.4.2 RUN curl -fSL "https://storage.googleapis.com/golang/go${GO_VERSION}.linux-amd64.tar.gz" | tar xzC /usr/local ENV PATH $PATH:/usr/local/go/bin ENV AUTO_GOPATH 1 ENV DOCKER_BUILDTAGS selinux ================================================ FILE: vendor/github.com/docker/docker/contrib/check-config.sh ================================================ #!/usr/bin/env bash set -e # bits of this were adapted from lxc-checkconfig # see also https://github.com/lxc/lxc/blob/lxc-1.0.2/src/lxc/lxc-checkconfig.in possibleConfigs=( '/proc/config.gz' "/boot/config-$(uname -r)" "/usr/src/linux-$(uname -r)/.config" '/usr/src/linux/.config' ) if [ $# -gt 0 ]; then CONFIG="$1" else : ${CONFIG:="${possibleConfigs[0]}"} fi if ! command -v zgrep &> /dev/null; then zgrep() { zcat "$2" | grep "$1" } fi kernelVersion="$(uname -r)" kernelMajor="${kernelVersion%%.*}" kernelMinor="${kernelVersion#$kernelMajor.}" kernelMinor="${kernelMinor%%.*}" is_set() { zgrep "CONFIG_$1=[y|m]" "$CONFIG" > /dev/null } is_set_in_kernel() { zgrep "CONFIG_$1=y" "$CONFIG" > /dev/null } is_set_as_module() { zgrep "CONFIG_$1=m" "$CONFIG" > /dev/null } # see https://en.wikipedia.org/wiki/ANSI_escape_code#Colors declare -A colors=( [black]=30 [red]=31 [green]=32 [yellow]=33 [blue]=34 [magenta]=35 [cyan]=36 [white]=37 ) color() { color=() if [ "$1" = 'bold' ]; then color+=( '1' ) shift fi if [ $# -gt 0 ] && [ "${colors[$1]}" ]; then color+=( "${colors[$1]}" ) fi local IFS=';' echo -en '\033['"${color[*]}"m } wrap_color() { text="$1" shift color "$@" echo -n "$text" color reset echo } wrap_good() { echo "$(wrap_color "$1" white): $(wrap_color "$2" green)" } wrap_bad() { echo "$(wrap_color "$1" bold): $(wrap_color "$2" bold red)" } wrap_warning() { wrap_color >&2 "$*" red } check_flag() { if is_set_in_kernel "$1"; then wrap_good "CONFIG_$1" 'enabled' elif is_set_as_module "$1"; then wrap_good "CONFIG_$1" 'enabled (as module)' else wrap_bad "CONFIG_$1" 'missing' fi } check_flags() { for flag in "$@"; do echo "- $(check_flag "$flag")" done } check_command() { if command -v "$1" >/dev/null 2>&1; then wrap_good "$1 command" 'available' else wrap_bad "$1 command" 'missing' fi } check_device() { if [ -c "$1" ]; then wrap_good "$1" 'present' else wrap_bad "$1" 'missing' fi } if [ ! -e "$CONFIG" ]; then wrap_warning "warning: $CONFIG does not exist, searching other paths for kernel config..." for tryConfig in "${possibleConfigs[@]}"; do if [ -e "$tryConfig" ]; then CONFIG="$tryConfig" break fi done if [ ! -e "$CONFIG" ]; then wrap_warning "error: cannot find kernel config" wrap_warning " try running this script again, specifying the kernel config:" wrap_warning " CONFIG=/path/to/kernel/.config $0 or $0 /path/to/kernel/.config" exit 1 fi fi wrap_color "info: reading kernel config from $CONFIG ..." white echo echo 'Generally Necessary:' echo -n '- ' cgroupSubsystemDir="$(awk '/[, ](cpu|cpuacct|cpuset|devices|freezer|memory)[, ]/ && $3 == "cgroup" { print $2 }' /proc/mounts | head -n1)" cgroupDir="$(dirname "$cgroupSubsystemDir")" if [ -d "$cgroupDir/cpu" -o -d "$cgroupDir/cpuacct" -o -d "$cgroupDir/cpuset" -o -d "$cgroupDir/devices" -o -d "$cgroupDir/freezer" -o -d "$cgroupDir/memory" ]; then echo "$(wrap_good 'cgroup hierarchy' 'properly mounted') [$cgroupDir]" else if [ "$cgroupSubsystemDir" ]; then echo "$(wrap_bad 'cgroup hierarchy' 'single mountpoint!') [$cgroupSubsystemDir]" else echo "$(wrap_bad 'cgroup hierarchy' 'nonexistent??')" fi echo " $(wrap_color '(see https://github.com/tianon/cgroupfs-mount)' yellow)" fi if [ "$(cat /sys/module/apparmor/parameters/enabled 2>/dev/null)" = 'Y' ]; then echo -n '- ' if command -v apparmor_parser &> /dev/null; then echo "$(wrap_good 'apparmor' 'enabled and tools installed')" else echo "$(wrap_bad 'apparmor' 'enabled, but apparmor_parser missing')" echo -n ' ' if command -v apt-get &> /dev/null; then echo "$(wrap_color '(use "apt-get install apparmor" to fix this)')" elif command -v yum &> /dev/null; then echo "$(wrap_color '(your best bet is "yum install apparmor-parser")')" else echo "$(wrap_color '(look for an "apparmor" package for your distribution)')" fi fi fi flags=( NAMESPACES {NET,PID,IPC,UTS}_NS DEVPTS_MULTIPLE_INSTANCES CGROUPS CGROUP_CPUACCT CGROUP_DEVICE CGROUP_FREEZER CGROUP_SCHED CPUSETS MACVLAN VETH BRIDGE BRIDGE_NETFILTER NF_NAT_IPV4 IP_NF_FILTER IP_NF_TARGET_MASQUERADE NETFILTER_XT_MATCH_{ADDRTYPE,CONNTRACK} NF_NAT NF_NAT_NEEDED # required for bind-mounting /dev/mqueue into containers POSIX_MQUEUE ) check_flags "${flags[@]}" echo echo 'Optional Features:' { check_flags MEMCG_SWAP check_flags MEMCG_SWAP_ENABLED if is_set MEMCG_SWAP && ! is_set MEMCG_SWAP_ENABLED; then echo " $(wrap_color '(note that cgroup swap accounting is not enabled in your kernel config, you can enable it by setting boot option "swapaccount=1")' bold black)" fi } if [ "$kernelMajor" -lt 3 ] || [ "$kernelMajor" -eq 3 -a "$kernelMinor" -le 18 ]; then check_flags RESOURCE_COUNTERS fi flags=( BLK_CGROUP IOSCHED_CFQ CGROUP_PERF CFS_BANDWIDTH ) check_flags "${flags[@]}" echo '- Storage Drivers:' { echo '- "'$(wrap_color 'aufs' blue)'":' check_flags AUFS_FS | sed 's/^/ /' if ! is_set AUFS_FS && grep -q aufs /proc/filesystems; then echo " $(wrap_color '(note that some kernels include AUFS patches but not the AUFS_FS flag)' bold black)" fi check_flags EXT4_FS_POSIX_ACL EXT4_FS_SECURITY | sed 's/^/ /' echo '- "'$(wrap_color 'btrfs' blue)'":' check_flags BTRFS_FS | sed 's/^/ /' echo '- "'$(wrap_color 'devicemapper' blue)'":' check_flags BLK_DEV_DM DM_THIN_PROVISIONING EXT4_FS EXT4_FS_POSIX_ACL EXT4_FS_SECURITY | sed 's/^/ /' echo '- "'$(wrap_color 'overlay' blue)'":' check_flags OVERLAY_FS EXT4_FS_SECURITY EXT4_FS_POSIX_ACL | sed 's/^/ /' echo '- "'$(wrap_color 'zfs' blue)'":' echo " - $(check_device /dev/zfs)" echo " - $(check_command zfs)" echo " - $(check_command zpool)" } | sed 's/^/ /' echo #echo 'Potential Future Features:' #check_flags USER_NS #echo ================================================ FILE: vendor/github.com/docker/docker/contrib/completion/REVIEWERS ================================================ Tianon Gravi (@tianon) Jessie Frazelle (@jfrazelle) ================================================ FILE: vendor/github.com/docker/docker/contrib/completion/bash/docker ================================================ #!/bin/bash # # bash completion file for core docker commands # # This script provides completion of: # - commands and their options # - container ids and names # - image repos and tags # - filepaths # # To enable the completions either: # - place this file in /etc/bash_completion.d # or # - copy this file to e.g. ~/.docker-completion.sh and add the line # below to your .bashrc after bash completion features are loaded # . ~/.docker-completion.sh # # Note: # Currently, the completions will not work if the docker daemon is not # bound to the default communication port/socket # If the docker daemon is using a unix socket for communication your user # must have access to the socket for the completions to function correctly # # Note for developers: # Please arrange options sorted alphabetically by long name with the short # options immediately following their corresponding long form. # This order should be applied to lists, alternatives and code blocks. __docker_q() { docker ${host:+-H "$host"} 2>/dev/null "$@" } __docker_containers_all() { local IFS=$'\n' local containers=( $(__docker_q ps -aq --no-trunc) ) if [ "$1" ]; then containers=( $(__docker_q inspect --format "{{if $1}}{{.Id}}{{end}}" "${containers[@]}") ) fi local names=( $(__docker_q inspect --format '{{.Name}}' "${containers[@]}") ) names=( "${names[@]#/}" ) # trim off the leading "/" from the container names unset IFS COMPREPLY=( $(compgen -W "${names[*]} ${containers[*]}" -- "$cur") ) } __docker_containers_running() { __docker_containers_all '.State.Running' } __docker_containers_stopped() { __docker_containers_all 'not .State.Running' } __docker_containers_pauseable() { __docker_containers_all 'and .State.Running (not .State.Paused)' } __docker_containers_unpauseable() { __docker_containers_all '.State.Paused' } __docker_container_names() { local containers=( $(__docker_q ps -aq --no-trunc) ) local names=( $(__docker_q inspect --format '{{.Name}}' "${containers[@]}") ) names=( "${names[@]#/}" ) # trim off the leading "/" from the container names COMPREPLY=( $(compgen -W "${names[*]}" -- "$cur") ) } __docker_container_ids() { local containers=( $(__docker_q ps -aq) ) COMPREPLY=( $(compgen -W "${containers[*]}" -- "$cur") ) } __docker_image_repos() { local repos="$(__docker_q images | awk 'NR>1 && $1 != "" { print $1 }')" COMPREPLY=( $(compgen -W "$repos" -- "$cur") ) } __docker_image_repos_and_tags() { local reposAndTags="$(__docker_q images | awk 'NR>1 && $1 != "" { print $1; print $1":"$2 }')" COMPREPLY=( $(compgen -W "$reposAndTags" -- "$cur") ) __ltrim_colon_completions "$cur" } __docker_image_repos_and_tags_and_ids() { local images="$(__docker_q images -a --no-trunc | awk 'NR>1 { print $3; if ($1 != "") { print $1; print $1":"$2 } }')" COMPREPLY=( $(compgen -W "$images" -- "$cur") ) __ltrim_colon_completions "$cur" } __docker_containers_and_images() { __docker_containers_all local containers=( "${COMPREPLY[@]}" ) __docker_image_repos_and_tags_and_ids COMPREPLY+=( "${containers[@]}" ) } # Finds the position of the first word that is neither option nor an option's argument. # If there are options that require arguments, you should pass a glob describing those # options, e.g. "--option1|-o|--option2" # Use this function to restrict completions to exact positions after the argument list. __docker_pos_first_nonflag() { local argument_flags=$1 local counter=$((command_pos + 1)) while [ $counter -le $cword ]; do if [ -n "$argument_flags" ] && eval "case '${words[$counter]}' in $argument_flags) true ;; *) false ;; esac"; then (( counter++ )) # eat "=" in case of --option=arg syntax [ "${words[$counter]}" = "=" ] && (( counter++ )) else case "${words[$counter]}" in -*) ;; *) break ;; esac fi # Bash splits words at "=", retaining "=" as a word, examples: # "--debug=false" => 3 words, "--log-opt syslog-facility=daemon" => 4 words while [ "${words[$counter + 1]}" = "=" ] ; do counter=$(( counter + 2)) done (( counter++ )) done echo $counter } # Returns the value of the first option matching option_glob. # Valid values for option_glob are option names like '--log-level' and # globs like '--log-level|-l' # Only positions between the command and the current word are considered. __docker_value_of_option() { local option_glob=$1 local counter=$((command_pos + 1)) while [ $counter -lt $cword ]; do case ${words[$counter]} in $option_glob ) echo ${words[$counter + 1]} break ;; esac (( counter++ )) done } # Transforms a multiline list of strings into a single line string # with the words separated by "|". # This is used to prepare arguments to __docker_pos_first_nonflag(). __docker_to_alternatives() { local parts=( $1 ) local IFS='|' echo "${parts[*]}" } # Transforms a multiline list of options into an extglob pattern # suitable for use in case statements. __docker_to_extglob() { local extglob=$( __docker_to_alternatives "$1" ) echo "@($extglob)" } __docker_resolve_hostname() { command -v host >/dev/null 2>&1 || return COMPREPLY=( $(host 2>/dev/null "${cur%:}" | awk '/has address/ {print $4}') ) } __docker_capabilities() { # The list of capabilities is defined in types.go, ALL was added manually. COMPREPLY=( $( compgen -W " ALL AUDIT_CONTROL AUDIT_WRITE AUDIT_READ BLOCK_SUSPEND CHOWN DAC_OVERRIDE DAC_READ_SEARCH FOWNER FSETID IPC_LOCK IPC_OWNER KILL LEASE LINUX_IMMUTABLE MAC_ADMIN MAC_OVERRIDE MKNOD NET_ADMIN NET_BIND_SERVICE NET_BROADCAST NET_RAW SETFCAP SETGID SETPCAP SETUID SYS_ADMIN SYS_BOOT SYS_CHROOT SYSLOG SYS_MODULE SYS_NICE SYS_PACCT SYS_PTRACE SYS_RAWIO SYS_RESOURCE SYS_TIME SYS_TTY_CONFIG WAKE_ALARM " -- "$cur" ) ) } __docker_log_drivers() { COMPREPLY=( $( compgen -W " fluentd gelf journald json-file none syslog " -- "$cur" ) ) } __docker_log_driver_options() { # see docs/reference/logging/index.md case $(__docker_value_of_option --log-driver) in fluentd) COMPREPLY=( $( compgen -W "fluentd-address fluentd-tag" -S = -- "$cur" ) ) ;; gelf) COMPREPLY=( $( compgen -W "gelf-address gelf-tag" -S = -- "$cur" ) ) ;; syslog) COMPREPLY=( $( compgen -W "syslog-address syslog-facility syslog-tag" -S = -- "$cur" ) ) ;; *) return ;; esac compopt -o nospace } __docker_complete_log_driver_options() { # "=" gets parsed to a word and assigned to either $cur or $prev depending on whether # it is the last character or not. So we search for "xxx=" in the the last two words. case "${words[$cword-2]}$prev=" in *gelf-address=*) COMPREPLY=( $( compgen -W "udp" -S "://" -- "${cur#=}" ) ) compopt -o nospace return ;; *syslog-address=*) COMPREPLY=( $( compgen -W "tcp udp unix" -S "://" -- "${cur#=}" ) ) compopt -o nospace return ;; *syslog-facility=*) COMPREPLY=( $( compgen -W " auth authpriv cron daemon ftp kern local0 local1 local2 local3 local4 local5 local6 local7 lpr mail news syslog user uucp " -- "${cur#=}" ) ) return ;; esac return 1 } # a selection of the available signals that is most likely of interest in the # context of docker containers. __docker_signals() { local signals=( SIGCONT SIGHUP SIGINT SIGKILL SIGQUIT SIGSTOP SIGTERM SIGUSR1 SIGUSR2 ) COMPREPLY=( $( compgen -W "${signals[*]} ${signals[*]#SIG}" -- "$( echo $cur | tr '[:lower:]' '[:upper:]')" ) ) } _docker_docker() { local boolean_options=" --daemon -d --debug -D --help -h --icc --ip-forward --ip-masq --iptables --ipv6 --selinux-enabled --tls --tlsverify --userland-proxy=false --version -v " case "$prev" in --exec-root|--graph|-g) _filedir -d return ;; --log-driver) __docker_log_drivers return ;; --log-level|-l) COMPREPLY=( $( compgen -W "debug info warn error fatal" -- "$cur" ) ) return ;; --log-opt) __docker_log_driver_options return ;; --pidfile|-p|--tlscacert|--tlscert|--tlskey) _filedir return ;; --storage-driver|-s) COMPREPLY=( $( compgen -W "aufs devicemapper btrfs overlay" -- "$(echo $cur | tr '[:upper:]' '[:lower:]')" ) ) return ;; $main_options_with_args_glob ) return ;; esac __docker_complete_log_driver_options && return case "$cur" in -*) COMPREPLY=( $( compgen -W "$boolean_options $main_options_with_args" -- "$cur" ) ) ;; *) COMPREPLY=( $( compgen -W "${commands[*]} help" -- "$cur" ) ) ;; esac } _docker_attach() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --no-stdin --sig-proxy" -- "$cur" ) ) ;; *) local counter="$(__docker_pos_first_nonflag)" if [ $cword -eq $counter ]; then __docker_containers_running fi ;; esac } _docker_build() { case "$prev" in --cgroup-parent|--cpuset-cpus|--cpuset-mems|--cpu-shares|-c|--cpu-period|--cpu-quota|--memory|-m|--memory-swap) return ;; --file|-f) _filedir return ;; --tag|-t) __docker_image_repos_and_tags return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--cgroup-parent --cpuset-cpus --cpuset-mems --cpu-shares -c --cpu-period --cpu-quota --file -f --force-rm --help --memory -m --memory-swap --no-cache --pull --quiet -q --rm --tag -t" -- "$cur" ) ) ;; *) local counter="$(__docker_pos_first_nonflag '--cgroup-parent|--cpuset-cpus|--cpuset-mems|--cpu-shares|-c|--cpu-period|--cpu-quota|--file|-f|--memory|-m|--memory-swap|--tag|-t')" if [ $cword -eq $counter ]; then _filedir -d fi ;; esac } _docker_commit() { case "$prev" in --author|-a|--change|-c|--message|-m) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--author -a --change -c --help --message -m --pause -p" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag '--author|-a|--change|-c|--message|-m') if [ $cword -eq $counter ]; then __docker_containers_all return fi (( counter++ )) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags return fi ;; esac } _docker_cp() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then case "$cur" in *:) return ;; *) __docker_containers_all COMPREPLY=( $( compgen -W "${COMPREPLY[*]}" -S ':' ) ) compopt -o nospace return ;; esac fi (( counter++ )) if [ $cword -eq $counter ]; then _filedir -d return fi ;; esac } _docker_create() { _docker_run } _docker_diff() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_all fi ;; esac } _docker_events() { case "$prev" in --filter|-f) COMPREPLY=( $( compgen -S = -W "container event image" -- "$cur" ) ) compopt -o nospace return ;; --since|--until) return ;; esac case "${words[$cword-2]}$prev=" in *container=*) cur="${cur#=}" __docker_containers_all return ;; *event=*) COMPREPLY=( $( compgen -W " attach commit copy create delete destroy die exec_create exec_start export import kill oom pause pull push rename resize restart start stop tag top unpause untag " -- "${cur#=}" ) ) return ;; *image=*) cur="${cur#=}" __docker_image_repos_and_tags_and_ids return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--filter -f --help --since --until" -- "$cur" ) ) ;; esac } _docker_exec() { case "$prev" in --user|-u) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--detach -d --help --interactive -i -t --tty -u --user" -- "$cur" ) ) ;; *) __docker_containers_running ;; esac } _docker_export() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_all fi ;; esac } _docker_help() { local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then COMPREPLY=( $( compgen -W "${commands[*]}" -- "$cur" ) ) fi } _docker_history() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --no-trunc --quiet -q" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags_and_ids fi ;; esac } _docker_images() { case "$prev" in --filter|-f) COMPREPLY=( $( compgen -W "dangling=true label=" -- "$cur" ) ) if [ "$COMPREPLY" = "label=" ]; then compopt -o nospace fi return ;; esac case "${words[$cword-2]}$prev=" in *dangling=*) COMPREPLY=( $( compgen -W "true false" -- "${cur#=}" ) ) return ;; *label=*) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--all -a --digests --filter -f --help --no-trunc --quiet -q" -- "$cur" ) ) ;; =) return ;; *) __docker_image_repos ;; esac } _docker_import() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then return fi (( counter++ )) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags return fi ;; esac } _docker_info() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; esac } _docker_inspect() { case "$prev" in --format|-f) return ;; --type) COMPREPLY=( $( compgen -W "image container" -- "$cur" ) ) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--format -f --type --help" -- "$cur" ) ) ;; *) __docker_containers_and_images ;; esac } _docker_kill() { case "$prev" in --signal|-s) __docker_signals return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --signal -s" -- "$cur" ) ) ;; *) __docker_containers_running ;; esac } _docker_load() { case "$prev" in --input|-i) _filedir return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --input -i" -- "$cur" ) ) ;; esac } _docker_login() { case "$prev" in --email|-e|--password|-p|--username|-u) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--email -e --help --password -p --username -u" -- "$cur" ) ) ;; esac } _docker_logout() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; esac } _docker_logs() { case "$prev" in --since|--tail) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--follow -f --help --since --tail --timestamps -t" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag '--tail') if [ $cword -eq $counter ]; then __docker_containers_all fi ;; esac } _docker_pause() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_pauseable fi ;; esac } _docker_port() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_all fi ;; esac } _docker_ps() { case "$prev" in --before|--since) __docker_containers_all ;; --filter|-f) COMPREPLY=( $( compgen -S = -W "exited id label name status" -- "$cur" ) ) compopt -o nospace return ;; -n) return ;; esac case "${words[$cword-2]}$prev=" in *id=*) cur="${cur#=}" __docker_container_ids return ;; *name=*) cur="${cur#=}" __docker_container_names return ;; *status=*) COMPREPLY=( $( compgen -W "exited paused restarting running" -- "${cur#=}" ) ) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--all -a --before --filter -f --help --latest -l -n --no-trunc --quiet -q --size -s --since" -- "$cur" ) ) ;; esac } _docker_pull() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--all-tags -a --help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then for arg in "${COMP_WORDS[@]}"; do case "$arg" in --all-tags|-a) __docker_image_repos return ;; esac done __docker_image_repos_and_tags fi ;; esac } _docker_push() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags fi ;; esac } _docker_rename() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_all fi ;; esac } _docker_restart() { case "$prev" in --time|-t) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --time -t" -- "$cur" ) ) ;; *) __docker_containers_all ;; esac } _docker_rm() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--force -f --help --link -l --volumes -v" -- "$cur" ) ) ;; *) for arg in "${COMP_WORDS[@]}"; do case "$arg" in --force|-f) __docker_containers_all return ;; esac done __docker_containers_stopped ;; esac } _docker_rmi() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--force -f --help --no-prune" -- "$cur" ) ) ;; *) __docker_image_repos_and_tags_and_ids ;; esac } _docker_run() { local options_with_args=" --add-host --blkio-weight --attach -a --cap-add --cap-drop --cgroup-parent --cidfile --cpuset --cpu-period --cpu-quota --cpu-shares -c --device --dns --dns-search --entrypoint --env -e --env-file --expose --group-add --hostname -h --ipc --label -l --label-file --link --log-driver --log-opt --lxc-conf --mac-address --memory -m --memory-swap --name --net --pid --publish -p --restart --security-opt --user -u --ulimit --uts --volumes-from --volume -v --workdir -w " local all_options="$options_with_args --help --interactive -i --privileged --publish-all -P --read-only --tty -t " [ "$command" = "run" ] && all_options="$all_options --detach -d --rm --sig-proxy " local options_with_args_glob=$(__docker_to_extglob "$options_with_args") case "$prev" in --add-host) case "$cur" in *:) __docker_resolve_hostname return ;; esac ;; --attach|-a) COMPREPLY=( $( compgen -W 'stdin stdout stderr' -- "$cur" ) ) return ;; --cap-add|--cap-drop) __docker_capabilities return ;; --cidfile|--env-file|--label-file) _filedir return ;; --device|--volume|-v) case "$cur" in *:*) # TODO somehow do _filedir for stuff inside the image, if it's already specified (which is also somewhat difficult to determine) ;; '') COMPREPLY=( $( compgen -W '/' -- "$cur" ) ) compopt -o nospace ;; /*) _filedir compopt -o nospace ;; esac return ;; --env|-e) COMPREPLY=( $( compgen -e -- "$cur" ) ) compopt -o nospace return ;; --ipc) case "$cur" in *:*) cur="${cur#*:}" __docker_containers_running ;; *) COMPREPLY=( $( compgen -W 'host container:' -- "$cur" ) ) if [ "$COMPREPLY" = "container:" ]; then compopt -o nospace fi ;; esac return ;; --link) case "$cur" in *:*) ;; *) __docker_containers_running COMPREPLY=( $( compgen -W "${COMPREPLY[*]}" -S ':' ) ) compopt -o nospace ;; esac return ;; --log-driver) __docker_log_drivers return ;; --log-opt) __docker_log_driver_options return ;; --net) case "$cur" in container:*) local cur=${cur#*:} __docker_containers_all ;; *) COMPREPLY=( $( compgen -W "bridge none container: host" -- "$cur") ) if [ "${COMPREPLY[*]}" = "container:" ] ; then compopt -o nospace fi ;; esac return ;; --restart) case "$cur" in on-failure:*) ;; *) COMPREPLY=( $( compgen -W "no on-failure on-failure: always" -- "$cur") ) ;; esac return ;; --security-opt) case "$cur" in label:*:*) ;; label:*) local cur=${cur##*:} COMPREPLY=( $( compgen -W "user: role: type: level: disable" -- "$cur") ) if [ "${COMPREPLY[*]}" != "disable" ] ; then compopt -o nospace fi ;; *) COMPREPLY=( $( compgen -W "label apparmor" -S ":" -- "$cur") ) compopt -o nospace ;; esac return ;; --volumes-from) __docker_containers_all return ;; $options_with_args_glob ) return ;; esac __docker_complete_log_driver_options && return case "$cur" in -*) COMPREPLY=( $( compgen -W "$all_options" -- "$cur" ) ) ;; *) local counter=$( __docker_pos_first_nonflag $( __docker_to_alternatives "$options_with_args" ) ) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags_and_ids fi ;; esac } _docker_save() { case "$prev" in --output|-o) _filedir return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --output -o" -- "$cur" ) ) ;; *) __docker_image_repos_and_tags_and_ids ;; esac } _docker_search() { case "$prev" in --stars|-s) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--automated --help --no-trunc --stars -s" -- "$cur" ) ) ;; esac } _docker_start() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--attach -a --help --interactive -i" -- "$cur" ) ) ;; *) __docker_containers_stopped ;; esac } _docker_stats() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--no-stream --help" -- "$cur" ) ) ;; *) __docker_containers_running ;; esac } _docker_stop() { case "$prev" in --time|-t) return ;; esac case "$cur" in -*) COMPREPLY=( $( compgen -W "--help --time -t" -- "$cur" ) ) ;; *) __docker_containers_running ;; esac } _docker_tag() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--force -f --help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags return fi (( counter++ )) if [ $cword -eq $counter ]; then __docker_image_repos_and_tags return fi ;; esac } _docker_unpause() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_unpauseable fi ;; esac } _docker_top() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) local counter=$(__docker_pos_first_nonflag) if [ $cword -eq $counter ]; then __docker_containers_running fi ;; esac } _docker_version() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; esac } _docker_wait() { case "$cur" in -*) COMPREPLY=( $( compgen -W "--help" -- "$cur" ) ) ;; *) __docker_containers_all ;; esac } _docker() { local previous_extglob_setting=$(shopt -p extglob) shopt -s extglob local commands=( attach build commit cp create diff events exec export history images import info inspect kill load login logout logs pause port ps pull push rename restart rm rmi run save search start stats stop tag top unpause version wait ) local main_options_with_args=" --api-cors-header --bip --bridge -b --default-gateway --default-gateway-v6 --default-ulimit --dns --dns-search --exec-driver -e --exec-opt --exec-root --fixed-cidr --fixed-cidr-v6 --graph -g --group -G --host -H --insecure-registry --ip --label --log-driver --log-level -l --log-opt --mtu --pidfile -p --registry-mirror --storage-driver -s --storage-opt --tlscacert --tlscert --tlskey " local main_options_with_args_glob=$(__docker_to_extglob "$main_options_with_args") local host COMPREPLY=() local cur prev words cword _get_comp_words_by_ref -n : cur prev words cword local command='docker' command_pos=0 local counter=1 while [ $counter -lt $cword ]; do case "${words[$counter]}" in # save host so that completion can use custom daemon --host|-H) (( counter++ )) host="${words[$counter]}" ;; $main_options_with_args_glob ) (( counter++ )) ;; -*) ;; =) (( counter++ )) ;; *) command="${words[$counter]}" command_pos=$counter break ;; esac (( counter++ )) done local completions_func=_docker_${command} declare -F $completions_func >/dev/null && $completions_func eval "$previous_extglob_setting" return 0 } complete -F _docker docker ================================================ FILE: vendor/github.com/docker/docker/contrib/completion/fish/docker.fish ================================================ # docker.fish - docker completions for fish shell # # This file is generated by gen_docker_fish_completions.py from: # https://github.com/barnybug/docker-fish-completion # # To install the completions: # mkdir -p ~/.config/fish/completions # cp docker.fish ~/.config/fish/completions # # Completion supported: # - parameters # - commands # - containers # - images # - repositories function __fish_docker_no_subcommand --description 'Test if docker has yet to be given the subcommand' for i in (commandline -opc) if contains -- $i attach build commit cp create diff events exec export history images import info inspect kill load login logout logs pause port ps pull push rename restart rm rmi run save search start stop tag top unpause version wait stats return 1 end end return 0 end function __fish_print_docker_containers --description 'Print a list of docker containers' -a select switch $select case running docker ps -a --no-trunc | command awk 'NR>1' | command awk 'BEGIN {FS=" +"}; $5 ~ "^Up" {print $1 "\n" $(NF-1)}' | tr ',' '\n' case stopped docker ps -a --no-trunc | command awk 'NR>1' | command awk 'BEGIN {FS=" +"}; $5 ~ "^Exit" {print $1 "\n" $(NF-1)}' | tr ',' '\n' case all docker ps -a --no-trunc | command awk 'NR>1' | command awk 'BEGIN {FS=" +"}; {print $1 "\n" $(NF-1)}' | tr ',' '\n' end end function __fish_print_docker_images --description 'Print a list of docker images' docker images | command awk 'NR>1' | command grep -v '' | command awk '{print $1":"$2}' end function __fish_print_docker_repositories --description 'Print a list of docker repositories' docker images | command awk 'NR>1' | command grep -v '' | command awk '{print $1}' | command sort | command uniq end # common options complete -c docker -f -n '__fish_docker_no_subcommand' -l api-cors-header -d "Set CORS headers in the remote API. Default is cors disabled" complete -c docker -f -n '__fish_docker_no_subcommand' -s b -l bridge -d 'Attach containers to a pre-existing network bridge' complete -c docker -f -n '__fish_docker_no_subcommand' -l bip -d "Use this CIDR notation address for the network bridge's IP, not compatible with -b" complete -c docker -f -n '__fish_docker_no_subcommand' -s D -l debug -d 'Enable debug mode' complete -c docker -f -n '__fish_docker_no_subcommand' -s d -l daemon -d 'Enable daemon mode' complete -c docker -f -n '__fish_docker_no_subcommand' -l dns -d 'Force Docker to use specific DNS servers' complete -c docker -f -n '__fish_docker_no_subcommand' -l dns-search -d 'Force Docker to use specific DNS search domains' complete -c docker -f -n '__fish_docker_no_subcommand' -s e -l exec-driver -d 'Force the Docker runtime to use a specific exec driver' complete -c docker -f -n '__fish_docker_no_subcommand' -l exec-opt -d 'Set exec driver options' complete -c docker -f -n '__fish_docker_no_subcommand' -l fixed-cidr -d 'IPv4 subnet for fixed IPs (e.g. 10.20.0.0/16)' complete -c docker -f -n '__fish_docker_no_subcommand' -l fixed-cidr-v6 -d 'IPv6 subnet for fixed IPs (e.g.: 2001:a02b/48)' complete -c docker -f -n '__fish_docker_no_subcommand' -s G -l group -d 'Group to assign the unix socket specified by -H when running in daemon mode' complete -c docker -f -n '__fish_docker_no_subcommand' -s g -l graph -d 'Path to use as the root of the Docker runtime' complete -c docker -f -n '__fish_docker_no_subcommand' -s H -l host -d 'The socket(s) to bind to in daemon mode or connect to in client mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd.' complete -c docker -f -n '__fish_docker_no_subcommand' -s h -l help -d 'Print usage' complete -c docker -f -n '__fish_docker_no_subcommand' -l icc -d 'Allow unrestricted inter-container and Docker daemon host communication' complete -c docker -f -n '__fish_docker_no_subcommand' -l insecure-registry -d 'Enable insecure communication with specified registries (no certificate verification for HTTPS and enable HTTP fallback) (e.g., localhost:5000 or 10.20.0.0/16)' complete -c docker -f -n '__fish_docker_no_subcommand' -l ip -d 'Default IP address to use when binding container ports' complete -c docker -f -n '__fish_docker_no_subcommand' -l ip-forward -d 'Enable net.ipv4.ip_forward and IPv6 forwarding if --fixed-cidr-v6 is defined. IPv6 forwarding may interfere with your existing IPv6 configuration when using Router Advertisement.' complete -c docker -f -n '__fish_docker_no_subcommand' -l ip-masq -d "Enable IP masquerading for bridge's IP range" complete -c docker -f -n '__fish_docker_no_subcommand' -l iptables -d "Enable Docker's addition of iptables rules" complete -c docker -f -n '__fish_docker_no_subcommand' -l ipv6 -d 'Enable IPv6 networking' complete -c docker -f -n '__fish_docker_no_subcommand' -s l -l log-level -d 'Set the logging level (debug, info, warn, error, fatal)' complete -c docker -f -n '__fish_docker_no_subcommand' -l label -d 'Set key=value labels to the daemon (displayed in `docker info`)' complete -c docker -f -n '__fish_docker_no_subcommand' -l mtu -d 'Set the containers network MTU' complete -c docker -f -n '__fish_docker_no_subcommand' -s p -l pidfile -d 'Path to use for daemon PID file' complete -c docker -f -n '__fish_docker_no_subcommand' -l registry-mirror -d 'Specify a preferred Docker registry mirror' complete -c docker -f -n '__fish_docker_no_subcommand' -s s -l storage-driver -d 'Force the Docker runtime to use a specific storage driver' complete -c docker -f -n '__fish_docker_no_subcommand' -l selinux-enabled -d 'Enable selinux support. SELinux does not presently support the BTRFS storage driver' complete -c docker -f -n '__fish_docker_no_subcommand' -l storage-opt -d 'Set storage driver options' complete -c docker -f -n '__fish_docker_no_subcommand' -l tls -d 'Use TLS; implied by --tlsverify' complete -c docker -f -n '__fish_docker_no_subcommand' -l tlscacert -d 'Trust only remotes providing a certificate signed by the CA given here' complete -c docker -f -n '__fish_docker_no_subcommand' -l tlscert -d 'Path to TLS certificate file' complete -c docker -f -n '__fish_docker_no_subcommand' -l tlskey -d 'Path to TLS key file' complete -c docker -f -n '__fish_docker_no_subcommand' -l tlsverify -d 'Use TLS and verify the remote (daemon: verify client, client: verify daemon)' complete -c docker -f -n '__fish_docker_no_subcommand' -s v -l version -d 'Print version information and quit' # subcommands # attach complete -c docker -f -n '__fish_docker_no_subcommand' -a attach -d 'Attach to a running container' complete -c docker -A -f -n '__fish_seen_subcommand_from attach' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from attach' -l no-stdin -d 'Do not attach STDIN' complete -c docker -A -f -n '__fish_seen_subcommand_from attach' -l sig-proxy -d 'Proxy all received signals to the process (non-TTY mode only). SIGCHLD, SIGKILL, and SIGSTOP are not proxied.' complete -c docker -A -f -n '__fish_seen_subcommand_from attach' -a '(__fish_print_docker_containers running)' -d "Container" # build complete -c docker -f -n '__fish_docker_no_subcommand' -a build -d 'Build an image from a Dockerfile' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -s f -l file -d "Name of the Dockerfile(Default is 'Dockerfile' at context root)" complete -c docker -A -f -n '__fish_seen_subcommand_from build' -l force-rm -d 'Always remove intermediate containers, even after unsuccessful builds' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -l no-cache -d 'Do not use cache when building the image' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -l pull -d 'Always attempt to pull a newer version of the image' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -s q -l quiet -d 'Suppress the verbose output generated by the containers' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -l rm -d 'Remove intermediate containers after a successful build' complete -c docker -A -f -n '__fish_seen_subcommand_from build' -s t -l tag -d 'Repository name (and optionally a tag) to be applied to the resulting image in case of success' # commit complete -c docker -f -n '__fish_docker_no_subcommand' -a commit -d "Create a new image from a container's changes" complete -c docker -A -f -n '__fish_seen_subcommand_from commit' -s a -l author -d 'Author (e.g., "John Hannibal Smith ")' complete -c docker -A -f -n '__fish_seen_subcommand_from commit' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from commit' -s m -l message -d 'Commit message' complete -c docker -A -f -n '__fish_seen_subcommand_from commit' -s p -l pause -d 'Pause container during commit' complete -c docker -A -f -n '__fish_seen_subcommand_from commit' -a '(__fish_print_docker_containers all)' -d "Container" # cp complete -c docker -f -n '__fish_docker_no_subcommand' -a cp -d "Copy files/folders from a container's filesystem to the host path" complete -c docker -A -f -n '__fish_seen_subcommand_from cp' -l help -d 'Print usage' # create complete -c docker -f -n '__fish_docker_no_subcommand' -a create -d 'Create a new container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s a -l attach -d 'Attach to STDIN, STDOUT or STDERR.' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l add-host -d 'Add a custom host-to-IP mapping (host:ip)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s c -l cpu-shares -d 'CPU shares (relative weight)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l cap-add -d 'Add Linux capabilities' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l cap-drop -d 'Drop Linux capabilities' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l cidfile -d 'Write the container ID to the file' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l cpuset -d 'CPUs in which to allow execution (0-3, 0,1)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l device -d 'Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l dns -d 'Set custom DNS servers' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l dns-search -d "Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)" complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s e -l env -d 'Set environment variables' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l entrypoint -d 'Overwrite the default ENTRYPOINT of the image' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l env-file -d 'Read in a line delimited file of environment variables' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l expose -d 'Expose a port or a range of ports (e.g. --expose=3300-3310) from the container without publishing it to your host' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l group-add -d 'Add additional groups to run as' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s h -l hostname -d 'Container host name' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s i -l interactive -d 'Keep STDIN open even if not attached' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l ipc -d 'Default is to create a private IPC namespace (POSIX SysV IPC) for the container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l link -d 'Add link to another container in the form of :alias' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l lxc-conf -d '(lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s m -l memory -d 'Memory limit (format: , where unit = b, k, m or g)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l mac-address -d 'Container MAC address (e.g. 92:d0:c6:0a:29:33)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l memory-swap -d "Total memory usage (memory + swap), set '-1' to disable swap (format: , where unit = b, k, m or g)" complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l name -d 'Assign a name to the container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l net -d 'Set the Network mode for the container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s P -l publish-all -d 'Publish all exposed ports to random ports on the host interfaces' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s p -l publish -d "Publish a container's port to the host" complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l pid -d 'Default is to create a private PID namespace for the container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l privileged -d 'Give extended privileges to this container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l read-only -d "Mount the container's root filesystem as read only" complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l restart -d 'Restart policy to apply when a container exits (no, on-failure[:max-retry], always)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l security-opt -d 'Security Options' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s t -l tty -d 'Allocate a pseudo-TTY' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s u -l user -d 'Username or UID' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s v -l volume -d 'Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l volumes-from -d 'Mount volumes from the specified container(s)' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -s w -l workdir -d 'Working directory inside the container' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -a '(__fish_print_docker_images)' -d "Image" # diff complete -c docker -f -n '__fish_docker_no_subcommand' -a diff -d "Inspect changes on a container's filesystem" complete -c docker -A -f -n '__fish_seen_subcommand_from diff' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from diff' -a '(__fish_print_docker_containers all)' -d "Container" # events complete -c docker -f -n '__fish_docker_no_subcommand' -a events -d 'Get real time events from the server' complete -c docker -A -f -n '__fish_seen_subcommand_from events' -s f -l filter -d "Provide filter values (i.e., 'event=stop')" complete -c docker -A -f -n '__fish_seen_subcommand_from events' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from events' -l since -d 'Show all events created since timestamp' complete -c docker -A -f -n '__fish_seen_subcommand_from events' -l until -d 'Stream events until this timestamp' # exec complete -c docker -f -n '__fish_docker_no_subcommand' -a exec -d 'Run a command in a running container' complete -c docker -A -f -n '__fish_seen_subcommand_from exec' -s d -l detach -d 'Detached mode: run command in the background' complete -c docker -A -f -n '__fish_seen_subcommand_from exec' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from exec' -s i -l interactive -d 'Keep STDIN open even if not attached' complete -c docker -A -f -n '__fish_seen_subcommand_from exec' -s t -l tty -d 'Allocate a pseudo-TTY' complete -c docker -A -f -n '__fish_seen_subcommand_from exec' -a '(__fish_print_docker_containers running)' -d "Container" # export complete -c docker -f -n '__fish_docker_no_subcommand' -a export -d 'Stream the contents of a container as a tar archive' complete -c docker -A -f -n '__fish_seen_subcommand_from export' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from export' -a '(__fish_print_docker_containers all)' -d "Container" # history complete -c docker -f -n '__fish_docker_no_subcommand' -a history -d 'Show the history of an image' complete -c docker -A -f -n '__fish_seen_subcommand_from history' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from history' -l no-trunc -d "Don't truncate output" complete -c docker -A -f -n '__fish_seen_subcommand_from history' -s q -l quiet -d 'Only show numeric IDs' complete -c docker -A -f -n '__fish_seen_subcommand_from history' -a '(__fish_print_docker_images)' -d "Image" # images complete -c docker -f -n '__fish_docker_no_subcommand' -a images -d 'List images' complete -c docker -A -f -n '__fish_seen_subcommand_from images' -s a -l all -d 'Show all images (by default filter out the intermediate image layers)' complete -c docker -A -f -n '__fish_seen_subcommand_from images' -s f -l filter -d "Provide filter values (i.e., 'dangling=true')" complete -c docker -A -f -n '__fish_seen_subcommand_from images' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from images' -l no-trunc -d "Don't truncate output" complete -c docker -A -f -n '__fish_seen_subcommand_from images' -s q -l quiet -d 'Only show numeric IDs' complete -c docker -A -f -n '__fish_seen_subcommand_from images' -a '(__fish_print_docker_repositories)' -d "Repository" # import complete -c docker -f -n '__fish_docker_no_subcommand' -a import -d 'Create a new filesystem image from the contents of a tarball' complete -c docker -A -f -n '__fish_seen_subcommand_from import' -l help -d 'Print usage' # info complete -c docker -f -n '__fish_docker_no_subcommand' -a info -d 'Display system-wide information' # inspect complete -c docker -f -n '__fish_docker_no_subcommand' -a inspect -d 'Return low-level information on a container or image' complete -c docker -A -f -n '__fish_seen_subcommand_from inspect' -s f -l format -d 'Format the output using the given go template.' complete -c docker -A -f -n '__fish_seen_subcommand_from inspect' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from inspect' -a '(__fish_print_docker_images)' -d "Image" complete -c docker -A -f -n '__fish_seen_subcommand_from inspect' -a '(__fish_print_docker_containers all)' -d "Container" # kill complete -c docker -f -n '__fish_docker_no_subcommand' -a kill -d 'Kill a running container' complete -c docker -A -f -n '__fish_seen_subcommand_from kill' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from kill' -s s -l signal -d 'Signal to send to the container' complete -c docker -A -f -n '__fish_seen_subcommand_from kill' -a '(__fish_print_docker_containers running)' -d "Container" # load complete -c docker -f -n '__fish_docker_no_subcommand' -a load -d 'Load an image from a tar archive' complete -c docker -A -f -n '__fish_seen_subcommand_from load' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from load' -s i -l input -d 'Read from a tar archive file, instead of STDIN' # login complete -c docker -f -n '__fish_docker_no_subcommand' -a login -d 'Register or log in to a Docker registry server' complete -c docker -A -f -n '__fish_seen_subcommand_from login' -s e -l email -d 'Email' complete -c docker -A -f -n '__fish_seen_subcommand_from login' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from login' -s p -l password -d 'Password' complete -c docker -A -f -n '__fish_seen_subcommand_from login' -s u -l username -d 'Username' # logout complete -c docker -f -n '__fish_docker_no_subcommand' -a logout -d 'Log out from a Docker registry server' # logs complete -c docker -f -n '__fish_docker_no_subcommand' -a logs -d 'Fetch the logs of a container' complete -c docker -A -f -n '__fish_seen_subcommand_from logs' -s f -l follow -d 'Follow log output' complete -c docker -A -f -n '__fish_seen_subcommand_from logs' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from logs' -s t -l timestamps -d 'Show timestamps' complete -c docker -A -f -n '__fish_seen_subcommand_from logs' -l since -d 'Show logs since timestamp' complete -c docker -A -f -n '__fish_seen_subcommand_from logs' -l tail -d 'Output the specified number of lines at the end of logs (defaults to all logs)' complete -c docker -A -f -n '__fish_seen_subcommand_from logs' -a '(__fish_print_docker_containers running)' -d "Container" # port complete -c docker -f -n '__fish_docker_no_subcommand' -a port -d 'Lookup the public-facing port that is NAT-ed to PRIVATE_PORT' complete -c docker -A -f -n '__fish_seen_subcommand_from port' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from port' -a '(__fish_print_docker_containers running)' -d "Container" # pause complete -c docker -f -n '__fish_docker_no_subcommand' -a pause -d 'Pause all processes within a container' complete -c docker -A -f -n '__fish_seen_subcommand_from pause' -a '(__fish_print_docker_containers running)' -d "Container" # ps complete -c docker -f -n '__fish_docker_no_subcommand' -a ps -d 'List containers' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -s a -l all -d 'Show all containers. Only running containers are shown by default.' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -l before -d 'Show only container created before Id or Name, include non-running ones.' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -s f -l filter -d 'Provide filter values. Valid filters:' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -s l -l latest -d 'Show only the latest created container, include non-running ones.' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -s n -d 'Show n last created containers, include non-running ones.' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -l no-trunc -d "Don't truncate output" complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -s q -l quiet -d 'Only display numeric IDs' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -s s -l size -d 'Display total file sizes' complete -c docker -A -f -n '__fish_seen_subcommand_from ps' -l since -d 'Show only containers created since Id or Name, include non-running ones.' # pull complete -c docker -f -n '__fish_docker_no_subcommand' -a pull -d 'Pull an image or a repository from a Docker registry server' complete -c docker -A -f -n '__fish_seen_subcommand_from pull' -s a -l all-tags -d 'Download all tagged images in the repository' complete -c docker -A -f -n '__fish_seen_subcommand_from pull' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from pull' -a '(__fish_print_docker_images)' -d "Image" complete -c docker -A -f -n '__fish_seen_subcommand_from pull' -a '(__fish_print_docker_repositories)' -d "Repository" # push complete -c docker -f -n '__fish_docker_no_subcommand' -a push -d 'Push an image or a repository to a Docker registry server' complete -c docker -A -f -n '__fish_seen_subcommand_from push' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from push' -a '(__fish_print_docker_images)' -d "Image" complete -c docker -A -f -n '__fish_seen_subcommand_from push' -a '(__fish_print_docker_repositories)' -d "Repository" # rename complete -c docker -f -n '__fish_docker_no_subcommand' -a rename -d 'Rename an existing container' # restart complete -c docker -f -n '__fish_docker_no_subcommand' -a restart -d 'Restart a running container' complete -c docker -A -f -n '__fish_seen_subcommand_from restart' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from restart' -s t -l time -d 'Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds.' complete -c docker -A -f -n '__fish_seen_subcommand_from restart' -a '(__fish_print_docker_containers running)' -d "Container" # rm complete -c docker -f -n '__fish_docker_no_subcommand' -a rm -d 'Remove one or more containers' complete -c docker -A -f -n '__fish_seen_subcommand_from rm' -s f -l force -d 'Force the removal of a running container (uses SIGKILL)' complete -c docker -A -f -n '__fish_seen_subcommand_from rm' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from rm' -s l -l link -d 'Remove the specified link and not the underlying container' complete -c docker -A -f -n '__fish_seen_subcommand_from rm' -s v -l volumes -d 'Remove the volumes associated with the container' complete -c docker -A -f -n '__fish_seen_subcommand_from rm' -a '(__fish_print_docker_containers stopped)' -d "Container" # rmi complete -c docker -f -n '__fish_docker_no_subcommand' -a rmi -d 'Remove one or more images' complete -c docker -A -f -n '__fish_seen_subcommand_from rmi' -s f -l force -d 'Force removal of the image' complete -c docker -A -f -n '__fish_seen_subcommand_from rmi' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from rmi' -l no-prune -d 'Do not delete untagged parents' complete -c docker -A -f -n '__fish_seen_subcommand_from rmi' -a '(__fish_print_docker_images)' -d "Image" # run complete -c docker -f -n '__fish_docker_no_subcommand' -a run -d 'Run a command in a new container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s a -l attach -d 'Attach to STDIN, STDOUT or STDERR.' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l add-host -d 'Add a custom host-to-IP mapping (host:ip)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s c -l cpu-shares -d 'CPU shares (relative weight)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l cap-add -d 'Add Linux capabilities' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l cap-drop -d 'Drop Linux capabilities' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l cidfile -d 'Write the container ID to the file' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l cpuset -d 'CPUs in which to allow execution (0-3, 0,1)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s d -l detach -d 'Detached mode: run the container in the background and print the new container ID' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l device -d 'Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l dns -d 'Set custom DNS servers' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l dns-search -d "Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain)" complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s e -l env -d 'Set environment variables' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l entrypoint -d 'Overwrite the default ENTRYPOINT of the image' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l env-file -d 'Read in a line delimited file of environment variables' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l expose -d 'Expose a port or a range of ports (e.g. --expose=3300-3310) from the container without publishing it to your host' complete -c docker -A -f -n '__fish_seen_subcommand_from create' -l group-add -d 'Add additional groups to run as' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s h -l hostname -d 'Container host name' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s i -l interactive -d 'Keep STDIN open even if not attached' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l ipc -d 'Default is to create a private IPC namespace (POSIX SysV IPC) for the container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l link -d 'Add link to another container in the form of :alias' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l lxc-conf -d '(lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1"' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s m -l memory -d 'Memory limit (format: , where unit = b, k, m or g)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l mac-address -d 'Container MAC address (e.g. 92:d0:c6:0a:29:33)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l memory-swap -d "Total memory usage (memory + swap), set '-1' to disable swap (format: , where unit = b, k, m or g)" complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l name -d 'Assign a name to the container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l net -d 'Set the Network mode for the container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s P -l publish-all -d 'Publish all exposed ports to random ports on the host interfaces' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s p -l publish -d "Publish a container's port to the host" complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l pid -d 'Default is to create a private PID namespace for the container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l privileged -d 'Give extended privileges to this container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l read-only -d "Mount the container's root filesystem as read only" complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l restart -d 'Restart policy to apply when a container exits (no, on-failure[:max-retry], always)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l rm -d 'Automatically remove the container when it exits (incompatible with -d)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l security-opt -d 'Security Options' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l sig-proxy -d 'Proxy received signals to the process (non-TTY mode only). SIGCHLD, SIGSTOP, and SIGKILL are not proxied.' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s t -l tty -d 'Allocate a pseudo-TTY' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s u -l user -d 'Username or UID' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s v -l volume -d 'Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -l volumes-from -d 'Mount volumes from the specified container(s)' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -s w -l workdir -d 'Working directory inside the container' complete -c docker -A -f -n '__fish_seen_subcommand_from run' -a '(__fish_print_docker_images)' -d "Image" # save complete -c docker -f -n '__fish_docker_no_subcommand' -a save -d 'Save an image to a tar archive' complete -c docker -A -f -n '__fish_seen_subcommand_from save' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from save' -s o -l output -d 'Write to an file, instead of STDOUT' complete -c docker -A -f -n '__fish_seen_subcommand_from save' -a '(__fish_print_docker_images)' -d "Image" # search complete -c docker -f -n '__fish_docker_no_subcommand' -a search -d 'Search for an image on the registry (defaults to the Docker Hub)' complete -c docker -A -f -n '__fish_seen_subcommand_from search' -l automated -d 'Only show automated builds' complete -c docker -A -f -n '__fish_seen_subcommand_from search' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from search' -l no-trunc -d "Don't truncate output" complete -c docker -A -f -n '__fish_seen_subcommand_from search' -s s -l stars -d 'Only displays with at least x stars' # start complete -c docker -f -n '__fish_docker_no_subcommand' -a start -d 'Start a stopped container' complete -c docker -A -f -n '__fish_seen_subcommand_from start' -s a -l attach -d "Attach container's STDOUT and STDERR and forward all signals to the process" complete -c docker -A -f -n '__fish_seen_subcommand_from start' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from start' -s i -l interactive -d "Attach container's STDIN" complete -c docker -A -f -n '__fish_seen_subcommand_from start' -a '(__fish_print_docker_containers stopped)' -d "Container" # stats complete -c docker -f -n '__fish_docker_no_subcommand' -a stats -d "Display a live stream of one or more containers' resource usage statistics" complete -c docker -A -f -n '__fish_seen_subcommand_from stats' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from stats' -l no-stream -d 'Disable streaming stats and only pull the first result' complete -c docker -A -f -n '__fish_seen_subcommand_from stats' -a '(__fish_print_docker_containers running)' -d "Container" # stop complete -c docker -f -n '__fish_docker_no_subcommand' -a stop -d 'Stop a running container' complete -c docker -A -f -n '__fish_seen_subcommand_from stop' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from stop' -s t -l time -d 'Number of seconds to wait for the container to stop before killing it. Default is 10 seconds.' complete -c docker -A -f -n '__fish_seen_subcommand_from stop' -a '(__fish_print_docker_containers running)' -d "Container" # tag complete -c docker -f -n '__fish_docker_no_subcommand' -a tag -d 'Tag an image into a repository' complete -c docker -A -f -n '__fish_seen_subcommand_from tag' -s f -l force -d 'Force' complete -c docker -A -f -n '__fish_seen_subcommand_from tag' -l help -d 'Print usage' # top complete -c docker -f -n '__fish_docker_no_subcommand' -a top -d 'Lookup the running processes of a container' complete -c docker -A -f -n '__fish_seen_subcommand_from top' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from top' -a '(__fish_print_docker_containers running)' -d "Container" # unpause complete -c docker -f -n '__fish_docker_no_subcommand' -a unpause -d 'Unpause a paused container' complete -c docker -A -f -n '__fish_seen_subcommand_from unpause' -a '(__fish_print_docker_containers running)' -d "Container" # version complete -c docker -f -n '__fish_docker_no_subcommand' -a version -d 'Show the Docker version information' # wait complete -c docker -f -n '__fish_docker_no_subcommand' -a wait -d 'Block until a container stops, then print its exit code' complete -c docker -A -f -n '__fish_seen_subcommand_from wait' -l help -d 'Print usage' complete -c docker -A -f -n '__fish_seen_subcommand_from wait' -a '(__fish_print_docker_containers running)' -d "Container" ================================================ FILE: vendor/github.com/docker/docker/contrib/completion/zsh/REVIEWERS ================================================ Tianon Gravi (@tianon) Jessie Frazelle (@jfrazelle) ================================================ FILE: vendor/github.com/docker/docker/contrib/completion/zsh/_docker ================================================ #compdef docker # # zsh completion for docker (http://docker.com) # # version: 0.3.0 # github: https://github.com/felixr/docker-zsh-completion # # contributors: # - Felix Riedel # - Steve Durrheimer # - Vincent Bernat # # license: # # Copyright (c) 2013, Felix Riedel # 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 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 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. # __docker_get_containers() { [[ $PREFIX = -* ]] && return 1 integer ret=1 local kind declare -a running stopped lines args kind=$1 shift [[ $kind = (stopped|all) ]] && args=($args -a) lines=(${(f)"$(_call_program commands docker $docker_options ps $args)"}) # Parse header line to find columns local i=1 j=1 k header=${lines[1]} declare -A begin end while (( j < ${#header} - 1 )); do i=$(( j + ${${header[$j,-1]}[(i)[^ ]]} - 1 )) j=$(( i + ${${header[$i,-1]}[(i) ]} - 1 )) k=$(( j + ${${header[$j,-1]}[(i)[^ ]]} - 2 )) begin[${header[$i,$((j-1))]}]=$i end[${header[$i,$((j-1))]}]=$k done lines=(${lines[2,-1]}) # Container ID local line local s for line in $lines; do s="${line[${begin[CONTAINER ID]},${end[CONTAINER ID]}]%% ##}" s="$s:${(l:15:: :::)${${line[${begin[CREATED]},${end[CREATED]}]/ ago/}%% ##}}" s="$s, ${${${line[${begin[IMAGE]},${end[IMAGE]}]}/:/\\:}%% ##}" if [[ ${line[${begin[STATUS]},${end[STATUS]}]} = Exit* ]]; then stopped=($stopped $s) else running=($running $s) fi done # Names local name local -a names for line in $lines; do names=(${(ps:,:)${${line[${begin[NAMES]},-1]}%% *}}) for name in $names; do s="${name}:${(l:15:: :::)${${line[${begin[CREATED]},${end[CREATED]}]/ ago/}%% ##}}" s="$s, ${${${line[${begin[IMAGE]},${end[IMAGE]}]}/:/\\:}%% ##}" if [[ ${line[${begin[STATUS]},${end[STATUS]}]} = Exit* ]]; then stopped=($stopped ${s#*/}) else running=($running ${s#*/}) fi done done [[ $kind = (running|all) ]] && _describe -t containers-running "running containers" running "$@" && ret=0 [[ $kind = (stopped|all) ]] && _describe -t containers-stopped "stopped containers" stopped "$@" && ret=0 return ret } __docker_stoppedcontainers() { [[ $PREFIX = -* ]] && return 1 __docker_get_containers stopped "$@" } __docker_runningcontainers() { [[ $PREFIX = -* ]] && return 1 __docker_get_containers running "$@" } __docker_containers() { [[ $PREFIX = -* ]] && return 1 __docker_get_containers all "$@" } __docker_images() { [[ $PREFIX = -* ]] && return 1 integer ret=1 declare -a images images=(${${${(f)"$(_call_program commands docker $docker_options images)"}[2,-1]}/(#b)([^ ]##) ##([^ ]##) ##([^ ]##)*/${match[3]}:${(r:15:: :::)match[2]} in ${match[1]}}) _describe -t docker-images "images" images && ret=0 __docker_repositories_with_tags && ret=0 return ret } __docker_repositories() { [[ $PREFIX = -* ]] && return 1 declare -a repos repos=(${${${(f)"$(_call_program commands docker $docker_options images)"}%% *}[2,-1]}) repos=(${repos#}) _describe -t docker-repos "repositories" repos } __docker_repositories_with_tags() { [[ $PREFIX = -* ]] && return 1 integer ret=1 declare -a repos onlyrepos matched declare m repos=(${${${${(f)"$(_call_program commands docker $docker_options images)"}[2,-1]}/ ##/:::}%% *}) repos=(${${repos%:::}#}) # Check if we have a prefix-match for the current prefix. onlyrepos=(${repos%::*}) for m in $onlyrepos; do [[ ${PREFIX##${~~m}} != ${PREFIX} ]] && { # Yes, complete with tags repos=(${${repos/:::/:}/:/\\:}) _describe -t docker-repos-with-tags "repositories with tags" repos && ret=0 return ret } done # No, only complete repositories onlyrepos=(${${repos%:::*}/:/\\:}) _describe -t docker-repos "repositories" onlyrepos -qS : && ret=0 return ret } __docker_search() { [[ $PREFIX = -* ]] && return 1 local cache_policy zstyle -s ":completion:${curcontext}:" cache-policy cache_policy if [[ -z "$cache_policy" ]]; then zstyle ":completion:${curcontext}:" cache-policy __docker_caching_policy fi local searchterm cachename searchterm="${words[$CURRENT]%/}" cachename=_docker-search-$searchterm local expl local -a result if ( [[ ${(P)+cachename} -eq 0 ]] || _cache_invalid ${cachename#_} ) \ && ! _retrieve_cache ${cachename#_}; then _message "Searching for ${searchterm}..." result=(${${${(f)"$(_call_program commands docker $docker_options search $searchterm)"}%% *}[2,-1]}) _store_cache ${cachename#_} result fi _wanted dockersearch expl 'available images' compadd -a result } __docker_caching_policy() { oldp=( "$1"(Nmh+1) ) # 1 hour (( $#oldp )) } __docker_commands() { local cache_policy zstyle -s ":completion:${curcontext}:" cache-policy cache_policy if [[ -z "$cache_policy" ]]; then zstyle ":completion:${curcontext}:" cache-policy __docker_caching_policy fi if ( [[ ${+_docker_subcommands} -eq 0 ]] || _cache_invalid docker_subcommands) \ && ! _retrieve_cache docker_subcommands; then local -a lines lines=(${(f)"$(_call_program commands docker 2>&1)"}) _docker_subcommands=(${${${lines[$((${lines[(i)Commands:]} + 1)),${lines[(I) *]}]}## #}/ ##/:}) _docker_subcommands=($_docker_subcommands 'help:Show help for a command') _store_cache docker_subcommands _docker_subcommands fi _describe -t docker-commands "docker command" _docker_subcommands } __docker_subcommand() { local -a _command_args opts_help opts_cpumem opts_create local expl help="-h --help" integer ret=1 opts_help=("(: -)"{-h,--help}"[Print usage]") opts_cpumem=( "($help -c --cpu-shares)"{-c,--cpu-shares=-}"[CPU shares (relative weight)]:CPU shares:(0 10 100 200 500 800 1000)" "($help)--cgroup-parent=-[Parent cgroup for the container]:cgroup: " "($help)--cpu-period=-[Limit the CPU CFS (Completely Fair Scheduler) period]:CPU period: " "($help)--cpu-quota=-[Limit the CPU CFS (Completely Fair Scheduler) quota]:CPU quota: " "($help)--cpuset-cpus=-[CPUs in which to allow execution]:CPUs: " "($help)--cpuset-mems=-[MEMs in which to allow execution]:MEMs: " "($help -m --memory)"{-m,--memory=-}"[Memory limit]:Memory limit: " "($help)--memory-swap=-[Total memory limit with swap]:Memory limit: " ) opts_create=( "($help -a --attach)"{-a,--attach=-}"[Attach to stdin, stdout or stderr]:device:(STDIN STDOUT STDERR)" "($help)*--add-host=-[Add a custom host-to-IP mapping]:host\:ip mapping: " "($help)--blkio-weight=-[Block IO (relative weight), between 10 and 1000]:Block IO weight:(10 100 500 1000)" "($help)*--cap-add=-[Add Linux capabilities]:capability: " "($help)*--cap-drop=-[Drop Linux capabilities]:capability: " "($help)--cidfile=-[Write the container ID to the file]:CID file:_files" "($help)*--device=-[Add a host device to the container]:device:_files" "($help)*--dns=-[Set custom dns servers]:dns server: " "($help)*--dns-search=-[Set custom DNS search domains]:dns domains: " "($help)*"{-e,--env=-}"[Set environment variables]:environment variable: " "($help)--entrypoint=-[Overwrite the default entrypoint of the image]:entry point: " "($help)*--env-file=-[Read environment variables from a file]:environment file:_files" "($help)*--expose=-[Expose a port from the container without publishing it]: " "($help)*--group-add=-[Add additional groups to run as]:group:_groups" "($help -h --hostname)"{-h,--hostname=-}"[Container host name]:hostname:_hosts" "($help -i --interactive)"{-i,--interactive}"[Keep stdin open even if not attached]" "($help)--ipc=-[IPC namespace to use]:IPC namespace: " "($help)*--link=-[Add link to another container]:link:->link" "($help)*"{-l,--label=-}"[Set meta data on a container]:label: " "($help)--log-driver=-[Default driver for container logs]:Logging driver:(json-file syslog journald gelf fluentd none)" "($help)*--log-opt=-[Log driver specific options]:log driver options: " "($help)*--lxc-conf=-[Add custom lxc options]:lxc options: " "($help)--mac-address=-[Container MAC address]:MAC address: " "($help)--name=-[Container name]:name: " "($help)--net=-[Network mode]:network mode:(bridge none container host)" "($help)--oom-kill-disable[Disable OOM Killer]" "($help -P --publish-all)"{-P,--publish-all}"[Publish all exposed ports]" "($help)*"{-p,--publish=-}"[Expose a container's port to the host]:port:_ports" "($help)--pid=-[PID namespace to use]:PID: " "($help)--privileged[Give extended privileges to this container]" "($help)--read-only[Mount the container's root filesystem as read only]" "($help)--restart=-[Restart policy]:restart policy:(no on-failure always)" "($help)*--security-opt=-[Security options]:security option: " "($help -t --tty)"{-t,--tty}"[Allocate a pseudo-tty]" "($help -u --user)"{-u,--user=-}"[Username or UID]:user:_users" "($help)*--ulimit=-[ulimit options]:ulimit: " "($help)*-v[Bind mount a volume]:volume: " "($help)*--volumes-from=-[Mount volumes from the specified container]:volume: " "($help -w --workdir)"{-w,--workdir=-}"[Working directory inside the container]:directory:_directories" ) case "$words[1]" in (attach) _arguments \ $opts_help \ "($help)--no-stdin[Do not attach stdin]" \ "($help)--sig-proxy[Proxy all received signals to the process (non-TTY mode only)]" \ "($help -):containers:__docker_runningcontainers" && ret=0 ;; (build) _arguments \ $opts_help \ $opts_cpumem \ "($help -f --file)"{-f,--file=-}"[Name of the Dockerfile]:Dockerfile:_files" \ "($help)--force-rm[Always remove intermediate containers]" \ "($help)--no-cache[Do not use cache when building the image]" \ "($help)--pull[Attempt to pull a newer version of the image]" \ "($help -q --quiet)"{-q,--quiet}"[Suppress verbose build output]" \ "($help)--rm[Remove intermediate containers after a successful build]" \ "($help -t --tag)"{-t,--tag=-}"[Repository, name and tag for the image]: :__docker_repositories_with_tags" \ "($help -):path or URL:_directories" && ret=0 ;; (commit) _arguments \ $opts_help \ "($help -a --author)"{-a,--author=-}"[Author]:author: " \ "($help -c --change)*"{-c,--change=-}"[Apply Dockerfile instruction to the created image]:Dockerfile:_files" \ "($help -m --message)"{-m,--message=-}"[Commit message]:message: " \ "($help -p --pause)"{-p,--pause}"[Pause container during commit]" \ "($help -):container:__docker_containers" \ "($help -): :__docker_repositories_with_tags" && ret=0 ;; (cp) _arguments \ $opts_help \ "($help -)1:container:->container" \ "($help -)2:hostpath:_files" && ret=0 case $state in (container) if compset -P "*:"; then _files && ret=0 else __docker_containers -qS ":" && ret=0 fi ;; esac ;; (create) _arguments \ $opts_help \ $opts_cpumem \ $opts_create \ "($help -): :__docker_images" \ "($help -):command: _command_names -e" \ "($help -)*::arguments: _normal" && ret=0 case $state in (link) if compset -P "*:"; then _wanted alias expl "Alias" compadd -E "" && ret=0 else __docker_runningcontainers -qS ":" && ret=0 fi ;; esac ;; (diff) _arguments \ $opts_help \ "($help -)*:containers:__docker_containers" && ret=0 ;; (events) _arguments \ $opts_help \ "($help)*"{-f,--filter=-}"[Filter values]:filter: " \ "($help)--since=-[Events created since this timestamp]:timestamp: " \ "($help)--until=-[Events created until this timestamp]:timestamp: " && ret=0 ;; (exec) local state _arguments \ $opts_help \ "($help -d --detach)"{-d,--detach}"[Detached mode: leave the container running in the background]" \ "($help -i --interactive)"{-i,--interactive}"[Keep stdin open even if not attached]" \ "($help -t --tty)"{-t,--tty}"[Allocate a pseudo-tty]" \ "($help -u --user)"{-u,--user=-}"[Username or UID]:user:_users" \ "($help -):containers:__docker_runningcontainers" \ "($help -)*::command:->anycommand" && ret=0 case $state in (anycommand) shift 1 words (( CURRENT-- )) _normal && ret=0 ;; esac ;; (export) _arguments \ $opts_help \ "($help -o --output)"{-o,--output=-}"[Write to a file, instead of stdout]:output file:_files" \ "($help -)*:containers:__docker_containers" && ret=0 ;; (history) _arguments \ $opts_help \ "($help -H --human)"{-H,--human}"[Print sizes and dates in human readable format]" \ "($help)--no-trunc[Do not truncate output]" \ "($help -q --quiet)"{-q,--quiet}"[Only show numeric IDs]" \ "($help -)*: :__docker_images" && ret=0 ;; (images) _arguments \ $opts_help \ "($help -a --all)"{-a,--all}"[Show all images]" \ "($help)--digest[Show digests]" \ "($help)*"{-f,--filter=-}"[Filter values]:filter: " \ "($help)--no-trunc[Do not truncate output]" \ "($help -q --quiet)"{-q,--quiet}"[Only show numeric IDs]" \ "($help -): :__docker_repositories" && ret=0 ;; (import) _arguments \ $opts_help \ "($help -c --change)*"{-c,--change=-}"[Apply Dockerfile instruction to the created image]:Dockerfile:_files" \ "($help -):URL:(- http:// file://)" \ "($help -): :__docker_repositories_with_tags" && ret=0 ;; (info|version) _arguments \ $opts_help && ret=0 ;; (inspect) _arguments \ $opts_help \ "($help -f --format=-)"{-f,--format=-}"[Format the output using the given go template]:template: " \ "($help)--type=-[Return JSON for specified type]:type:(image container)" \ "($help -)*:containers:__docker_containers" && ret=0 ;; (kill) _arguments \ $opts_help \ "($help -s --signal)"{-s,--signal=-}"[Signal to send]:signal:_signals" \ "($help -)*:containers:__docker_runningcontainers" && ret=0 ;; (load) _arguments \ $opts_help \ "($help -i --input)"{-i,--input=-}"[Read from tar archive file]:archive file:_files -g "*.((tar|TAR)(.gz|.GZ|.Z|.bz2|.lzma|.xz|)|(tbz|tgz|txz))(-.)"" && ret=0 ;; (login) _arguments \ $opts_help \ "($help -e --email)"{-e,--email=-}"[Email]:email: " \ "($help -p --password)"{-p,--password=-}"[Password]:password: " \ "($help -u --user)"{-u,--user=-}"[Username]:username: " \ "($help -)1:server: " && ret=0 ;; (logout) _arguments \ $opts_help \ "($help -)1:server: " && ret=0 ;; (logs) _arguments \ $opts_help \ "($help -f --follow)"{-f,--follow}"[Follow log output]" \ "($help -s --since)"{-s,--since=-}"[Show logs since this timestamp]:timestamp: " \ "($help -t --timestamps)"{-t,--timestamps}"[Show timestamps]" \ "($help)--tail=-[Output the last K lines]:lines:(1 10 20 50 all)" \ "($help -)*:containers:__docker_containers" && ret=0 ;; (pause|unpause) _arguments \ $opts_help \ "($help -)*:containers:__docker_runningcontainers" && ret=0 ;; (port) _arguments \ $opts_help \ "($help -)1:containers:__docker_runningcontainers" \ "($help -)2:port:_ports" && ret=0 ;; (ps) _arguments \ $opts_help \ "($help -a --all)"{-a,--all}"[Show all containers]" \ "($help)--before=-[Show only container created before...]:containers:__docker_containers" \ "($help)*"{-f,--filter=-}"[Filter values]:filter: " \ "($help -l --latest)"{-l,--latest}"[Show only the latest created container]" \ "($help)-n[Show n last created containers, include non-running one]:n:(1 5 10 25 50)" \ "($help)--no-trunc[Do not truncate output]" \ "($help -q --quiet)"{-q,--quiet}"[Only show numeric IDs]" \ "($help -s --size)"{-s,--size}"[Display total file sizes]" \ "($help)--since=-[Show only containers created since...]:containers:__docker_containers" && ret=0 ;; (pull) _arguments \ $opts_help \ "($help -a --all-tags)"{-a,--all-tags}"[Download all tagged images]" \ "($help -):name:__docker_search" && ret=0 ;; (push) _arguments \ $opts_help \ "($help -): :__docker_images" && ret=0 ;; (rename) _arguments \ $opts_help \ "($help -):old name:__docker_containers" \ "($help -):new name: " && ret=0 ;; (restart|stop) _arguments \ $opts_help \ "($help -t --time=-)"{-t,--time=-}"[Number of seconds to try to stop for before killing the container]:seconds to before killing:(1 5 10 30 60)" \ "($help -)*:containers:__docker_runningcontainers" && ret=0 ;; (rm) _arguments \ $opts_help \ "($help -f --force)"{-f,--force}"[Force removal]" \ "($help -l --link)"{-l,--link}"[Remove the specified link and not the underlying container]" \ "($help -v --volumes)"{-v,--volumes}"[Remove the volumes associated to the container]" \ "($help -)*:containers:__docker_stoppedcontainers" && ret=0 ;; (rmi) _arguments \ $opts_help \ "($help -f --force)"{-f,--force}"[Force removal]" \ "($help)--no-prune[Do not delete untagged parents]" \ "($help -)*: :__docker_images" && ret=0 ;; (run) _arguments \ $opts_help \ $opts_cpumem \ $opts_create \ "($help -d --detach)"{-d,--detach}"[Detached mode: leave the container running in the background]" \ "($help)--rm[Remove intermediate containers when it exits]" \ "($help)--sig-proxy[Proxy all received signals to the process (non-TTY mode only)]" \ "($help -): :__docker_images" \ "($help -):command: _command_names -e" \ "($help -)*::arguments: _normal" && ret=0 case $state in (link) if compset -P "*:"; then _wanted alias expl "Alias" compadd -E "" && ret=0 else __docker_runningcontainers -qS ":" && ret=0 fi ;; esac ;; (save) _arguments \ $opts_help \ "($help -o --output)"{-o,--output=-}"[Write to file]:file:_files" \ "($help -)*: :__docker_images" && ret=0 ;; (search) _arguments \ $opts_help \ "($help)--automated[Only show automated builds]" \ "($help)--no-trunc[Do not truncate output]" \ "($help -s --stars)"{-s,--stars=-}"[Only display with at least X stars]:stars:(0 10 100 1000)" \ "($help -):term: " && ret=0 ;; (start) _arguments \ $opts_help \ "($help -a --attach)"{-a,--attach}"[Attach container's stdout/stderr and forward all signals]" \ "($help -i --interactive)"{-i,--interactive}"[Attach container's stding]" \ "($help -)*:containers:__docker_stoppedcontainers" && ret=0 ;; (stats) _arguments \ $opts_help \ "($help)--no-stream[Disable streaming stats and only pull the first result]" \ "($help -)*:containers:__docker_runningcontainers" && ret=0 ;; (tag) _arguments \ $opts_help \ "($help -f --force)"{-f,--force}"[force]"\ "($help -):source:__docker_images"\ "($help -):destination:__docker_repositories_with_tags" && ret=0 ;; (top) _arguments \ $opts_help \ "($help -)1:containers:__docker_runningcontainers" \ "($help -)*:: :->ps-arguments" && ret=0 case $state in (ps-arguments) _ps && ret=0 ;; esac ;; (wait) _arguments \ $opts_help \ "($help -)*:containers:__docker_runningcontainers" && ret=0 ;; (help) _arguments ":subcommand:__docker_commands" && ret=0 ;; esac return ret } _docker() { # Support for subservices, which allows for `compdef _docker docker-shell=_docker_containers`. # Based on /usr/share/zsh/functions/Completion/Unix/_git without support for `ret`. if [[ $service != docker ]]; then _call_function - _$service return fi local curcontext="$curcontext" state line help="-h --help" integer ret=1 typeset -A opt_args _arguments -C \ "(: -)"{-h,--help}"[Print usage]" \ "($help)--api-cors-header=-[Set CORS headers in the remote API]:CORS headers: " \ "($help -b --bridge)"{-b,--bridge=-}"[Attach containers to a network bridge]:bridge:_net_interfaces" \ "($help)--bip=-[Specify network bridge IP]" \ "($help -D --debug)"{-D,--debug}"[Enable debug mode]" \ "($help -d --daeamon)"{-d,--daemon}"[Enable daemon mode]" \ "($help)--default-gateway[Container default gateway IPv4 address]:IPv4 address: " \ "($help)--default-gateway-v6[Container default gateway IPv6 address]:IPv6 address: " \ "($help)*--dns=-[DNS server to use]:DNS: " \ "($help)*--dns-search=-[DNS search domains to use]" \ "($help)*--default-ulimit=-[Set default ulimit settings for containers]:ulimit: " \ "($help -e --exec-driver)"{-e,--exec-driver=-}"[Exec driver to use]:driver:(native lxc windows)" \ "($help)*--exec-opt=-[Set exec driver options]:exec driver options: " \ "($help)--exec-root=-[Root of the Docker execdriver]:path:_directories" \ "($help)--fixed-cidr=-[IPv4 subnet for fixed IPs]:IPv4 subnet: " \ "($help)--fixed-cidr-v6=-[IPv6 subnet for fixed IPs]:IPv6 subnet: " \ "($help -G --group)"{-G,--group=-}"[Group for the unix socket]:group:_groups" \ "($help -g --graph)"{-g,--graph=-}"[Root of the Docker runtime]:path:_directories" \ "($help -H --host)"{-H,--host=-}"[tcp://host:port to bind/connect to]:host: " \ "($help)--icc[Enable inter-container communication]" \ "($help)*--insecure-registry=-[Enable insecure registry communication]:registry: " \ "($help)--ip=-[Default IP when binding container ports]" \ "($help)--ip-forward[Enable net.ipv4.ip_forward]" \ "($help)--ip-masq[Enable IP masquerading]" \ "($help)--iptables[Enable addition of iptables rules]" \ "($help)--ipv6[Enable IPv6 networking]" \ "($help -l --log-level)"{-l,--log-level=-}"[Set the logging level]:level:(debug info warn error fatal)" \ "($help)*--label=-[Set key=value labels to the daemon]:label: " \ "($help)--log-driver=-[Default driver for container logs]:Logging driver:(json-file syslog journald gelf fluentd none)" \ "($help)*--log-opt=-[Log driver specific options]:log driver options: " \ "($help)--mtu=-[Set the containers network MTU]:mtu:(0 576 1420 1500 9000)" \ "($help -p --pidfile)"{-p,--pidfile=-}"[Path to use for daemon PID file]:PID file:_files" \ "($help)*--registry-mirror=-[Preferred Docker registry mirror]:registry mirror: " \ "($help -s --storage-driver)"{-s,--storage-driver=-}"[Storage driver to use]:driver:(aufs devicemapper btrfs zfs overlay)" \ "($help)--selinux-enabled[Enable selinux support]" \ "($help)*--storage-opt=-[Set storage driver options]:storage driver options: " \ "($help)--tls[Use TLS]" \ "($help)--tlscacert=-[Trust certs signed only by this CA]:PEM file:_files -g "*.(pem|crt)"" \ "($help)--tlscert=-[Path to TLS certificate file]:PEM file:_files -g "*.(pem|crt)"" \ "($help)--tlskey=-[Path to TLS key file]:Key file:_files -g "*.(pem|key)"" \ "($help)--tlsverify[Use TLS and verify the remote]" \ "($help)--userland-proxy[Use userland proxy for loopback traffic]" \ "($help -v --version)"{-v,--version}"[Print version information and quit]" \ "($help -): :->command" \ "($help -)*:: :->option-or-argument" && ret=0 local host=${opt_args[-H]}${opt_args[--host]} local docker_options=${host:+--host $host} case $state in (command) __docker_commands && ret=0 ;; (option-or-argument) curcontext=${curcontext%:*:*}:docker-$words[1]: __docker_subcommand && ret=0 ;; esac return ret } _docker "$@" # Local Variables: # mode: Shell-Script # sh-indentation: 4 # indent-tabs-mode: nil # sh-basic-offset: 4 # End: # vim: ft=zsh sw=4 ts=4 et ================================================ FILE: vendor/github.com/docker/docker/contrib/desktop-integration/README.md ================================================ Desktop Integration =================== The ./contrib/desktop-integration contains examples of typical dockerized desktop applications. Examples ======== * Chromium: ./chromium/Dockerfile shows a way to dockerize a common application * Gparted: ./gparted/Dockerfile shows a way to dockerize a common application w devices ================================================ FILE: vendor/github.com/docker/docker/contrib/desktop-integration/chromium/Dockerfile ================================================ # VERSION: 0.1 # DESCRIPTION: Create chromium container with its dependencies # AUTHOR: Jessica Frazelle # COMMENTS: # This file describes how to build a Chromium container with all # dependencies installed. It uses native X11 unix socket. # Tested on Debian Jessie # USAGE: # # Download Chromium Dockerfile # wget http://raw.githubusercontent.com/docker/docker/master/contrib/desktop-integration/chromium/Dockerfile # # # Build chromium image # docker build -t chromium . # # # Run stateful data-on-host chromium. For ephemeral, remove -v /data/chromium:/data # docker run -v /data/chromium:/data -v /tmp/.X11-unix:/tmp/.X11-unix \ # -e DISPLAY=unix$DISPLAY chromium # # To run stateful dockerized data containers # docker run --volumes-from chromium-data -v /tmp/.X11-unix:/tmp/.X11-unix \ # -e DISPLAY=unix$DISPLAY chromium # Base docker image FROM debian:jessie MAINTAINER Jessica Frazelle # Install Chromium RUN apt-get update && apt-get install -y \ chromium \ chromium-l10n \ libcanberra-gtk-module \ libexif-dev \ --no-install-recommends # Autorun chromium CMD ["/usr/bin/chromium", "--no-sandbox", "--user-data-dir=/data"] ================================================ FILE: vendor/github.com/docker/docker/contrib/desktop-integration/gparted/Dockerfile ================================================ # VERSION: 0.1 # DESCRIPTION: Create gparted container with its dependencies # AUTHOR: Jessica Frazelle # COMMENTS: # This file describes how to build a gparted container with all # dependencies installed. It uses native X11 unix socket. # Tested on Debian Jessie # USAGE: # # Download gparted Dockerfile # wget http://raw.githubusercontent.com/docker/docker/master/contrib/desktop-integration/gparted/Dockerfile # # # Build gparted image # docker build -t gparted . # # docker run -v /tmp/.X11-unix:/tmp/.X11-unix \ # --device=/dev/sda:/dev/sda \ # -e DISPLAY=unix$DISPLAY gparted # # Base docker image FROM debian:jessie MAINTAINER Jessica Frazelle # Install Gparted and its dependencies RUN apt-get update && apt-get install -y \ gparted \ libcanberra-gtk-module \ --no-install-recommends # Autorun gparted CMD ["/usr/sbin/gparted"] ================================================ FILE: vendor/github.com/docker/docker/contrib/docker-device-tool/device_tool.go ================================================ package main import ( "flag" "fmt" "os" "path" "sort" "strconv" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver/devmapper" "github.com/docker/docker/pkg/devicemapper" ) func usage() { fmt.Fprintf(os.Stderr, "Usage: %s [status] | [list] | [device id] | [resize new-pool-size] | [snap new-id base-id] | [remove id] | [mount id mountpoint]\n", os.Args[0]) flag.PrintDefaults() os.Exit(1) } func byteSizeFromString(arg string) (int64, error) { digits := "" rest := "" last := strings.LastIndexAny(arg, "0123456789") if last >= 0 { digits = arg[:last+1] rest = arg[last+1:] } val, err := strconv.ParseInt(digits, 10, 64) if err != nil { return val, err } rest = strings.ToLower(strings.TrimSpace(rest)) var multiplier int64 = 1 switch rest { case "": multiplier = 1 case "k", "kb": multiplier = 1024 case "m", "mb": multiplier = 1024 * 1024 case "g", "gb": multiplier = 1024 * 1024 * 1024 case "t", "tb": multiplier = 1024 * 1024 * 1024 * 1024 default: return 0, fmt.Errorf("Unknown size unit: %s", rest) } return val * multiplier, nil } func main() { root := flag.String("r", "/var/lib/docker", "Docker root dir") flDebug := flag.Bool("D", false, "Debug mode") flag.Parse() if *flDebug { os.Setenv("DEBUG", "1") logrus.SetLevel(logrus.DebugLevel) } if flag.NArg() < 1 { usage() } args := flag.Args() home := path.Join(*root, "devicemapper") devices, err := devmapper.NewDeviceSet(home, false, nil) if err != nil { fmt.Println("Can't initialize device mapper: ", err) os.Exit(1) } switch args[0] { case "status": status := devices.Status() fmt.Printf("Pool name: %s\n", status.PoolName) fmt.Printf("Data Loopback file: %s\n", status.DataLoopback) fmt.Printf("Metadata Loopback file: %s\n", status.MetadataLoopback) fmt.Printf("Sector size: %d\n", status.SectorSize) fmt.Printf("Data use: %d of %d (%.1f %%)\n", status.Data.Used, status.Data.Total, 100.0*float64(status.Data.Used)/float64(status.Data.Total)) fmt.Printf("Metadata use: %d of %d (%.1f %%)\n", status.Metadata.Used, status.Metadata.Total, 100.0*float64(status.Metadata.Used)/float64(status.Metadata.Total)) break case "list": ids := devices.List() sort.Strings(ids) for _, id := range ids { fmt.Println(id) } break case "device": if flag.NArg() < 2 { usage() } status, err := devices.GetDeviceStatus(args[1]) if err != nil { fmt.Println("Can't get device info: ", err) os.Exit(1) } fmt.Printf("Id: %d\n", status.DeviceId) fmt.Printf("Size: %d\n", status.Size) fmt.Printf("Transaction Id: %d\n", status.TransactionId) fmt.Printf("Size in Sectors: %d\n", status.SizeInSectors) fmt.Printf("Mapped Sectors: %d\n", status.MappedSectors) fmt.Printf("Highest Mapped Sector: %d\n", status.HighestMappedSector) break case "resize": if flag.NArg() < 2 { usage() } size, err := byteSizeFromString(args[1]) if err != nil { fmt.Println("Invalid size: ", err) os.Exit(1) } err = devices.ResizePool(size) if err != nil { fmt.Println("Error resizing pool: ", err) os.Exit(1) } break case "snap": if flag.NArg() < 3 { usage() } err := devices.AddDevice(args[1], args[2]) if err != nil { fmt.Println("Can't create snap device: ", err) os.Exit(1) } break case "remove": if flag.NArg() < 2 { usage() } err := devicemapper.RemoveDevice(args[1]) if err != nil { fmt.Println("Can't remove device: ", err) os.Exit(1) } break case "mount": if flag.NArg() < 3 { usage() } err := devices.MountDevice(args[1], args[2], "") if err != nil { fmt.Println("Can't create snap device: ", err) os.Exit(1) } break default: fmt.Printf("Unknown command %s\n", args[0]) usage() os.Exit(1) } return } ================================================ FILE: vendor/github.com/docker/docker/contrib/dockerize-disk.sh ================================================ #!/usr/bin/env bash set -e if ! command -v qemu-nbd &> /dev/null; then echo >&2 'error: "qemu-nbd" not found!' exit 1 fi usage() { echo "Convert disk image to docker image" echo "" echo "usage: $0 image-name disk-image-file [ base-image ]" echo " ie: $0 cirros:0.3.3 cirros-0.3.3-x86_64-disk.img" echo " $0 ubuntu:cloud ubuntu-14.04-server-cloudimg-amd64-disk1.img ubuntu:14.04" } if [ "$#" -lt 2 ]; then usage exit 1 fi CURDIR=$(pwd) image_name="${1%:*}" image_tag="${1#*:}" if [ "$image_tag" == "$1" ]; then image_tag="latest" fi disk_image_file="$2" docker_base_image="$3" block_device=/dev/nbd0 builddir=$(mktemp -d) cleanup() { umount "$builddir/disk_image" || true umount "$builddir/workdir" || true qemu-nbd -d $block_device &> /dev/null || true rm -rf $builddir } trap cleanup EXIT # Mount disk image modprobe nbd max_part=63 qemu-nbd -rc ${block_device} -P 1 "$disk_image_file" mkdir "$builddir/disk_image" mount -o ro ${block_device} "$builddir/disk_image" mkdir "$builddir/workdir" mkdir "$builddir/diff" base_image_mounts="" # Unpack base image if [ -n "$docker_base_image" ]; then mkdir -p "$builddir/base" docker pull "$docker_base_image" docker save "$docker_base_image" | tar -xC "$builddir/base" image_id=$(docker inspect -f "{{.Id}}" "$docker_base_image") while [ -n "$image_id" ]; do mkdir -p "$builddir/base/$image_id/layer" tar -xf "$builddir/base/$image_id/layer.tar" -C "$builddir/base/$image_id/layer" base_image_mounts="${base_image_mounts}:$builddir/base/$image_id/layer=ro+wh" image_id=$(docker inspect -f "{{.Parent}}" "$image_id") done fi # Mount work directory mount -t aufs -o "br=$builddir/diff=rw${base_image_mounts},dio,xino=/dev/shm/aufs.xino" none "$builddir/workdir" # Update files cd $builddir LC_ALL=C diff -rq disk_image workdir \ | sed -re "s|Only in workdir(.*?): |DEL \1/|g;s|Only in disk_image(.*?): |ADD \1/|g;s|Files disk_image/(.+) and workdir/(.+) differ|UPDATE /\1|g" \ | while read action entry; do case "$action" in ADD|UPDATE) cp -a "disk_image$entry" "workdir$entry" ;; DEL) rm -rf "workdir$entry" ;; *) echo "Error: unknown diff line: $action $entry" >&2 ;; esac done # Pack new image new_image_id="$(for i in $(seq 1 32); do printf "%02x" $(($RANDOM % 256)); done)" mkdir -p $builddir/result/$new_image_id cd diff tar -cf $builddir/result/$new_image_id/layer.tar * echo "1.0" > $builddir/result/$new_image_id/VERSION cat > $builddir/result/$new_image_id/json <<-EOS { "docker_version": "1.4.1" , "id": "$new_image_id" , "created": "$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)" EOS if [ -n "$docker_base_image" ]; then image_id=$(docker inspect -f "{{.Id}}" "$docker_base_image") echo ", \"parent\": \"$image_id\"" >> $builddir/result/$new_image_id/json fi echo "}" >> $builddir/result/$new_image_id/json echo "{\"$image_name\":{\"$image_tag\":\"$new_image_id\"}}" > $builddir/result/repositories cd $builddir/result # mkdir -p $CURDIR/$image_name # cp -r * $CURDIR/$image_name tar -c * | docker load ================================================ FILE: vendor/github.com/docker/docker/contrib/download-frozen-image.sh ================================================ #!/bin/bash set -e # hello-world latest ef872312fe1b 3 months ago 910 B # hello-world latest ef872312fe1bbc5e05aae626791a47ee9b032efa8f3bda39cc0be7b56bfe59b9 3 months ago 910 B # debian latest f6fab3b798be 10 weeks ago 85.1 MB # debian latest f6fab3b798be3174f45aa1eb731f8182705555f89c9026d8c1ef230cbf8301dd 10 weeks ago 85.1 MB if ! command -v curl &> /dev/null; then echo >&2 'error: "curl" not found!' exit 1 fi usage() { echo "usage: $0 dir image[:tag][@image-id] ..." echo " ie: $0 /tmp/hello-world hello-world" echo " $0 /tmp/debian-jessie debian:jessie" echo " $0 /tmp/old-hello-world hello-world@ef872312fe1bbc5e05aae626791a47ee9b032efa8f3bda39cc0be7b56bfe59b9" echo " $0 /tmp/old-debian debian:latest@f6fab3b798be3174f45aa1eb731f8182705555f89c9026d8c1ef230cbf8301dd" [ -z "$1" ] || exit "$1" } dir="$1" # dir for building tar in shift || usage 1 >&2 [ $# -gt 0 -a "$dir" ] || usage 2 >&2 mkdir -p "$dir" # hacky workarounds for Bash 3 support (no associative arrays) images=() rm -f "$dir"/tags-*.tmp # repositories[busybox]='"latest": "...", "ubuntu-14.04": "..."' while [ $# -gt 0 ]; do imageTag="$1" shift image="${imageTag%%[:@]*}" tag="${imageTag#*:}" imageId="${tag##*@}" [ "$imageId" != "$tag" ] || imageId= [ "$tag" != "$imageTag" ] || tag='latest' tag="${tag%@*}" imageFile="${image//\//_}" # "/" can't be in filenames :) token="$(curl -sSL -o /dev/null -D- -H 'X-Docker-Token: true' "https://index.docker.io/v1/repositories/$image/images" | tr -d '\r' | awk -F ': *' '$1 == "X-Docker-Token" { print $2 }')" if [ -z "$imageId" ]; then imageId="$(curl -sSL -H "Authorization: Token $token" "https://registry-1.docker.io/v1/repositories/$image/tags/$tag")" imageId="${imageId//\"/}" fi ancestryJson="$(curl -sSL -H "Authorization: Token $token" "https://registry-1.docker.io/v1/images/$imageId/ancestry")" if [ "${ancestryJson:0:1}" != '[' ]; then echo >&2 "error: /v1/images/$imageId/ancestry returned something unexpected:" echo >&2 " $ancestryJson" exit 1 fi IFS=',' ancestry=( ${ancestryJson//[\[\] \"]/} ) unset IFS if [ -s "$dir/tags-$imageFile.tmp" ]; then echo -n ', ' >> "$dir/tags-$imageFile.tmp" else images=( "${images[@]}" "$image" ) fi echo -n '"'"$tag"'": "'"$imageId"'"' >> "$dir/tags-$imageFile.tmp" echo "Downloading '$imageTag' (${#ancestry[@]} layers)..." for imageId in "${ancestry[@]}"; do mkdir -p "$dir/$imageId" echo '1.0' > "$dir/$imageId/VERSION" curl -sSL -H "Authorization: Token $token" "https://registry-1.docker.io/v1/images/$imageId/json" -o "$dir/$imageId/json" # TODO figure out why "-C -" doesn't work here # "curl: (33) HTTP server doesn't seem to support byte ranges. Cannot resume." # "HTTP/1.1 416 Requested Range Not Satisfiable" if [ -f "$dir/$imageId/layer.tar" ]; then # TODO hackpatch for no -C support :'( echo "skipping existing ${imageId:0:12}" continue fi curl -SL --progress -H "Authorization: Token $token" "https://registry-1.docker.io/v1/images/$imageId/layer" -o "$dir/$imageId/layer.tar" # -C - done echo done echo -n '{' > "$dir/repositories" firstImage=1 for image in "${images[@]}"; do imageFile="${image//\//_}" # "/" can't be in filenames :) [ "$firstImage" ] || echo -n ',' >> "$dir/repositories" firstImage= echo -n $'\n\t' >> "$dir/repositories" echo -n '"'"$image"'": { '"$(cat "$dir/tags-$imageFile.tmp")"' }' >> "$dir/repositories" done echo -n $'\n}\n' >> "$dir/repositories" rm -f "$dir"/tags-*.tmp echo "Download of images into '$dir' complete." echo "Use something like the following to load the result into a Docker daemon:" echo " tar -cC '$dir' . | docker load" ================================================ FILE: vendor/github.com/docker/docker/contrib/host-integration/Dockerfile.dev ================================================ # # This Dockerfile will create an image that allows to generate upstart and # systemd scripts (more to come) # FROM ubuntu:12.10 MAINTAINER Guillaume J. Charmes RUN apt-get update && apt-get install -y wget git mercurial # Install Go RUN wget --no-check-certificate https://go.googlecode.com/files/go1.1.2.linux-amd64.tar.gz -O go-1.1.2.tar.gz RUN tar -xzvf go-1.1.2.tar.gz && mv /go /goroot RUN mkdir /go ENV GOROOT /goroot ENV GOPATH /go ENV PATH $GOROOT/bin:$PATH RUN go get github.com/docker/docker && cd /go/src/github.com/docker/docker && git checkout v0.6.3 ADD manager.go /manager/ RUN cd /manager && go build -o /usr/bin/manager ENTRYPOINT ["/usr/bin/manager"] ================================================ FILE: vendor/github.com/docker/docker/contrib/host-integration/Dockerfile.min ================================================ FROM busybox MAINTAINER Guillaume J. Charmes ADD manager /usr/bin/ ENTRYPOINT ["/usr/bin/manager"] ================================================ FILE: vendor/github.com/docker/docker/contrib/host-integration/manager/systemd ================================================ #!/bin/sh set -e cid="$1" auth="$2" desc="$3" cat <<-EOF [Unit] Description=$desc Author=$auth After=docker.service [Service] ExecStart=/usr/bin/docker start -a $cid ExecStop=/usr/bin/docker stop -t 2 $cid [Install] WantedBy=local.target EOF ================================================ FILE: vendor/github.com/docker/docker/contrib/host-integration/manager/upstart ================================================ #!/bin/sh set -e cid="$1" auth="$2" desc="$3" cat <<-EOF description "$(echo "$desc" | sed 's/"/\\"/g')" author "$(echo "$auth" | sed 's/"/\\"/g')" start on filesystem and started lxc-net and started docker stop on runlevel [!2345] respawn exec /usr/bin/docker start -a "$cid" EOF ================================================ FILE: vendor/github.com/docker/docker/contrib/host-integration/manager.go ================================================ package main import ( "bytes" "encoding/json" "flag" "fmt" "github.com/docker/docker" "os" "strings" "text/template" ) var templates = map[string]string{ "upstart": `description "{{.description}}" author "{{.author}}" start on filesystem and started lxc-net and started docker stop on runlevel [!2345] respawn exec /home/vagrant/goroot/bin/docker start -a {{.container_id}} `, "systemd": `[Unit] Description={{.description}} Author={{.author}} After=docker.service [Service] Restart=always ExecStart=/usr/bin/docker start -a {{.container_id}} ExecStop=/usr/bin/docker stop -t 2 {{.container_id}} [Install] WantedBy=local.target `, } func main() { // Parse command line for custom options kind := flag.String("t", "upstart", "Type of manager requested") author := flag.String("a", "", "Author of the image") description := flag.String("d", "", "Description of the image") flag.Usage = func() { fmt.Fprintf(os.Stderr, "\nUsage: manager \n\n") flag.PrintDefaults() } flag.Parse() // We require at least the container ID if flag.NArg() != 1 { println(flag.NArg()) flag.Usage() return } // Check that the requested process manager is supported if _, exists := templates[*kind]; !exists { panic("Unknown script template") } // Load the requested template tpl, err := template.New("processManager").Parse(templates[*kind]) if err != nil { panic(err) } // Create stdout/stderr buffers bufOut := bytes.NewBuffer(nil) bufErr := bytes.NewBuffer(nil) // Instanciate the Docker CLI cli := docker.NewDockerCli(nil, bufOut, bufErr, "unix", "/var/run/docker.sock", false, nil) // Retrieve the container info if err := cli.CmdInspect(flag.Arg(0)); err != nil { // As of docker v0.6.3, CmdInspect always returns nil panic(err) } // If there is nothing in the error buffer, then the Docker daemon is there and the container has been found if bufErr.Len() == 0 { // Unmarshall the resulting container data c := []*docker.Container{{}} if err := json.Unmarshal(bufOut.Bytes(), &c); err != nil { panic(err) } // Reset the buffers bufOut.Reset() bufErr.Reset() // Retrieve the info of the linked image if err := cli.CmdInspect(c[0].Image); err != nil { panic(err) } // If there is nothing in the error buffer, then the image has been found. if bufErr.Len() == 0 { // Unmarshall the resulting image data img := []*docker.Image{{}} if err := json.Unmarshal(bufOut.Bytes(), &img); err != nil { panic(err) } // If no author has been set, use the one from the image if *author == "" && img[0].Author != "" { *author = strings.Replace(img[0].Author, "\"", "", -1) } // If no description has been set, use the comment from the image if *description == "" && img[0].Comment != "" { *description = strings.Replace(img[0].Comment, "\"", "", -1) } } } /// Old version: Wrtie the resulting script to file // f, err := os.OpenFile(kind, os.O_CREATE|os.O_WRONLY, 0755) // if err != nil { // panic(err) // } // defer f.Close() // Create a map with needed data data := map[string]string{ "author": *author, "description": *description, "container_id": flag.Arg(0), } // Process the template and output it on Stdout if err := tpl.Execute(os.Stdout, data); err != nil { panic(err) } } ================================================ FILE: vendor/github.com/docker/docker/contrib/host-integration/manager.sh ================================================ #!/bin/sh set -e usage() { echo >&2 "usage: $0 [-a author] [-d description] container [manager]" echo >&2 " ie: $0 -a 'John Smith' 4ec9612a37cd systemd" echo >&2 " ie: $0 -d 'Super Cool System' 4ec9612a37cd # defaults to upstart" exit 1 } auth='' desc='' have_auth= have_desc= while getopts a:d: opt; do case "$opt" in a) auth="$OPTARG" have_auth=1 ;; d) desc="$OPTARG" have_desc=1 ;; esac done shift $(($OPTIND - 1)) [ $# -ge 1 -a $# -le 2 ] || usage cid="$1" script="${2:-upstart}" if [ ! -e "manager/$script" ]; then echo >&2 "Error: manager type '$script' is unknown (PRs always welcome!)." echo >&2 'The currently supported types are:' echo >&2 " $(cd manager && echo *)" exit 1 fi # TODO https://github.com/docker/docker/issues/734 (docker inspect formatting) #if command -v docker > /dev/null 2>&1; then # image="$(docker inspect -f '{{.Image}}' "$cid")" # if [ "$image" ]; then # if [ -z "$have_auth" ]; then # auth="$(docker inspect -f '{{.Author}}' "$image")" # fi # if [ -z "$have_desc" ]; then # desc="$(docker inspect -f '{{.Comment}}' "$image")" # fi # fi #fi exec "manager/$script" "$cid" "$auth" "$desc" ================================================ FILE: vendor/github.com/docker/docker/contrib/httpserver/Dockerfile ================================================ FROM busybox EXPOSE 80/tcp COPY httpserver . CMD ["./httpserver"] ================================================ FILE: vendor/github.com/docker/docker/contrib/httpserver/server.go ================================================ package main import ( "log" "net/http" ) func main() { fs := http.FileServer(http.Dir("/static")) http.Handle("/", fs) log.Panic(http.ListenAndServe(":80", nil)) } ================================================ FILE: vendor/github.com/docker/docker/contrib/init/openrc/docker.confd ================================================ # /etc/conf.d/docker: config file for /etc/init.d/docker # where the docker daemon output gets piped #DOCKER_LOGFILE="/var/log/docker.log" # where docker's pid get stored #DOCKER_PIDFILE="/run/docker.pid" # where the docker daemon itself is run from #DOCKER_BINARY="/usr/bin/docker" # any other random options you want to pass to docker DOCKER_OPTS="" ================================================ FILE: vendor/github.com/docker/docker/contrib/init/openrc/docker.initd ================================================ #!/sbin/runscript # Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # $Header: $ DOCKER_LOGFILE=${DOCKER_LOGFILE:-/var/log/${SVCNAME}.log} DOCKER_PIDFILE=${DOCKER_PIDFILE:-/run/${SVCNAME}.pid} DOCKER_BINARY=${DOCKER_BINARY:-/usr/bin/docker} DOCKER_OPTS=${DOCKER_OPTS:-} start() { checkpath -f -m 0644 -o root:docker "$DOCKER_LOGFILE" ulimit -n 1048576 ulimit -u 1048576 ebegin "Starting docker daemon" start-stop-daemon --start --background \ --exec "$DOCKER_BINARY" \ --pidfile "$DOCKER_PIDFILE" \ --stdout "$DOCKER_LOGFILE" \ --stderr "$DOCKER_LOGFILE" \ -- -d -p "$DOCKER_PIDFILE" \ $DOCKER_OPTS eend $? } stop() { ebegin "Stopping docker daemon" start-stop-daemon --stop \ --exec "$DOCKER_BINARY" \ --pidfile "$DOCKER_PIDFILE" eend $? } ================================================ FILE: vendor/github.com/docker/docker/contrib/init/systemd/REVIEWERS ================================================ Lokesh Mandvekar (@lsm5) Brandon Philips (@philips) Jessie Frazelle (@jfrazelle) ================================================ FILE: vendor/github.com/docker/docker/contrib/init/systemd/docker.service ================================================ [Unit] Description=Docker Application Container Engine Documentation=https://docs.docker.com After=network.target docker.socket Requires=docker.socket [Service] ExecStart=/usr/bin/docker -d -H fd:// MountFlags=slave LimitNOFILE=1048576 LimitNPROC=1048576 LimitCORE=infinity [Install] WantedBy=multi-user.target ================================================ FILE: vendor/github.com/docker/docker/contrib/init/systemd/docker.socket ================================================ [Unit] Description=Docker Socket for the API PartOf=docker.service [Socket] ListenStream=/var/run/docker.sock SocketMode=0660 SocketUser=root SocketGroup=docker [Install] WantedBy=sockets.target ================================================ FILE: vendor/github.com/docker/docker/contrib/init/sysvinit-debian/docker ================================================ #!/bin/sh set -e ### BEGIN INIT INFO # Provides: docker # Required-Start: $syslog $remote_fs # Required-Stop: $syslog $remote_fs # Should-Start: cgroupfs-mount cgroup-lite # Should-Stop: cgroupfs-mount cgroup-lite # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Create lightweight, portable, self-sufficient containers. # Description: # Docker is an open-source project to easily create lightweight, portable, # self-sufficient containers from any application. The same container that a # developer builds and tests on a laptop can run at scale, in production, on # VMs, bare metal, OpenStack clusters, public clouds and more. ### END INIT INFO export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin BASE=$(basename $0) # modify these in /etc/default/$BASE (/etc/default/docker) DOCKER=/usr/bin/$BASE # This is the pid file managed by docker itself DOCKER_PIDFILE=/var/run/$BASE.pid # This is the pid file created/managed by start-stop-daemon DOCKER_SSD_PIDFILE=/var/run/$BASE-ssd.pid DOCKER_LOGFILE=/var/log/$BASE.log DOCKER_OPTS= DOCKER_DESC="Docker" # Get lsb functions . /lib/lsb/init-functions if [ -f /etc/default/$BASE ]; then . /etc/default/$BASE fi # Check docker is present if [ ! -x $DOCKER ]; then log_failure_msg "$DOCKER not present or not executable" exit 1 fi check_init() { # see also init_is_upstart in /lib/lsb/init-functions (which isn't available in Ubuntu 12.04, or we'd use it directly) if [ -x /sbin/initctl ] && /sbin/initctl version 2>/dev/null | grep -q upstart; then log_failure_msg "$DOCKER_DESC is managed via upstart, try using service $BASE $1" exit 1 fi } fail_unless_root() { if [ "$(id -u)" != '0' ]; then log_failure_msg "$DOCKER_DESC must be run as root" exit 1 fi } cgroupfs_mount() { # see also https://github.com/tianon/cgroupfs-mount/blob/master/cgroupfs-mount if grep -v '^#' /etc/fstab | grep -q cgroup \ || [ ! -e /proc/cgroups ] \ || [ ! -d /sys/fs/cgroup ]; then return fi if ! mountpoint -q /sys/fs/cgroup; then mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup fi ( cd /sys/fs/cgroup for sys in $(awk '!/^#/ { if ($4 == 1) print $1 }' /proc/cgroups); do mkdir -p $sys if ! mountpoint -q $sys; then if ! mount -n -t cgroup -o $sys cgroup $sys; then rmdir $sys || true fi fi done ) } case "$1" in start) check_init fail_unless_root cgroupfs_mount touch "$DOCKER_LOGFILE" chgrp docker "$DOCKER_LOGFILE" ulimit -n 1048576 if [ "$BASH" ]; then ulimit -u 1048576 else ulimit -p 1048576 fi log_begin_msg "Starting $DOCKER_DESC: $BASE" start-stop-daemon --start --background \ --no-close \ --exec "$DOCKER" \ --pidfile "$DOCKER_SSD_PIDFILE" \ --make-pidfile \ -- \ -d -p "$DOCKER_PIDFILE" \ $DOCKER_OPTS \ >> "$DOCKER_LOGFILE" 2>&1 log_end_msg $? ;; stop) check_init fail_unless_root log_begin_msg "Stopping $DOCKER_DESC: $BASE" start-stop-daemon --stop --pidfile "$DOCKER_SSD_PIDFILE" log_end_msg $? ;; restart) check_init fail_unless_root docker_pid=`cat "$DOCKER_SSD_PIDFILE" 2>/dev/null` [ -n "$docker_pid" ] \ && ps -p $docker_pid > /dev/null 2>&1 \ && $0 stop $0 start ;; force-reload) check_init fail_unless_root $0 restart ;; status) check_init status_of_proc -p "$DOCKER_SSD_PIDFILE" "$DOCKER" "$DOCKER_DESC" ;; *) echo "Usage: service docker {start|stop|restart|status}" exit 1 ;; esac ================================================ FILE: vendor/github.com/docker/docker/contrib/init/sysvinit-debian/docker.default ================================================ # Docker Upstart and SysVinit configuration file # Customize location of Docker binary (especially for development testing). #DOCKER="/usr/local/bin/docker" # Use DOCKER_OPTS to modify the daemon startup options. #DOCKER_OPTS="--dns 8.8.8.8 --dns 8.8.4.4" # If you need Docker to use an HTTP proxy, it can also be specified here. #export http_proxy="http://127.0.0.1:3128/" # This is also a handy place to tweak where Docker's temporary files go. #export TMPDIR="/mnt/bigdrive/docker-tmp" ================================================ FILE: vendor/github.com/docker/docker/contrib/init/sysvinit-redhat/docker ================================================ #!/bin/sh # # /etc/rc.d/init.d/docker # # Daemon for docker.com # # chkconfig: 2345 95 95 # description: Daemon for docker.com ### BEGIN INIT INFO # Provides: docker # Required-Start: $network cgconfig # Required-Stop: # Should-Start: # Should-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: start and stop docker # Description: Daemon for docker.com ### END INIT INFO # Source function library. . /etc/rc.d/init.d/functions prog="docker" unshare=/usr/bin/unshare exec="/usr/bin/$prog" pidfile="/var/run/$prog.pid" lockfile="/var/lock/subsys/$prog" logfile="/var/log/$prog" [ -e /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog prestart() { service cgconfig status > /dev/null if [[ $? != 0 ]]; then service cgconfig start fi } start() { [ -x $exec ] || exit 5 check_for_cleanup if ! [ -f $pidfile ]; then prestart printf "Starting $prog:\t" echo "\n$(date)\n" >> $logfile "$unshare" -m -- $exec -d $other_args &>> $logfile & pid=$! touch $lockfile # wait up to 10 seconds for the pidfile to exist. see # https://github.com/docker/docker/issues/5359 tries=0 while [ ! -f $pidfile -a $tries -lt 10 ]; do sleep 1 tries=$((tries + 1)) done success echo else failure echo printf "$pidfile still exists...\n" exit 7 fi } stop() { echo -n $"Stopping $prog: " killproc -p $pidfile -d 300 $prog retval=$? echo [ $retval -eq 0 ] && rm -f $lockfile return $retval } restart() { stop start } reload() { restart } force_reload() { restart } rh_status() { status -p $pidfile $prog } rh_status_q() { rh_status >/dev/null 2>&1 } check_for_cleanup() { if [ -f ${pidfile} ]; then /bin/ps -fp $(cat ${pidfile}) > /dev/null || rm ${pidfile} fi } case "$1" in start) rh_status_q && exit 0 $1 ;; stop) rh_status_q || exit 0 $1 ;; restart) $1 ;; reload) rh_status_q || exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q || exit 0 restart ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload}" exit 2 esac exit $? ================================================ FILE: vendor/github.com/docker/docker/contrib/init/sysvinit-redhat/docker.sysconfig ================================================ # /etc/sysconfig/docker # # Other arguments to pass to the docker daemon process # These will be parsed by the sysv initscript and appended # to the arguments list passed to docker -d other_args="" ================================================ FILE: vendor/github.com/docker/docker/contrib/init/upstart/REVIEWERS ================================================ Tianon Gravi (@tianon) Jessie Frazelle (@jfrazelle) ================================================ FILE: vendor/github.com/docker/docker/contrib/init/upstart/docker.conf ================================================ description "Docker daemon" start on (local-filesystems and net-device-up IFACE!=lo) stop on runlevel [!2345] limit nofile 524288 1048576 limit nproc 524288 1048576 respawn kill timeout 20 pre-start script # see also https://github.com/tianon/cgroupfs-mount/blob/master/cgroupfs-mount if grep -v '^#' /etc/fstab | grep -q cgroup \ || [ ! -e /proc/cgroups ] \ || [ ! -d /sys/fs/cgroup ]; then exit 0 fi if ! mountpoint -q /sys/fs/cgroup; then mount -t tmpfs -o uid=0,gid=0,mode=0755 cgroup /sys/fs/cgroup fi ( cd /sys/fs/cgroup for sys in $(awk '!/^#/ { if ($4 == 1) print $1 }' /proc/cgroups); do mkdir -p $sys if ! mountpoint -q $sys; then if ! mount -n -t cgroup -o $sys cgroup $sys; then rmdir $sys || true fi fi done ) end script script # modify these in /etc/default/$UPSTART_JOB (/etc/default/docker) DOCKER=/usr/bin/$UPSTART_JOB DOCKER_OPTS= if [ -f /etc/default/$UPSTART_JOB ]; then . /etc/default/$UPSTART_JOB fi exec "$DOCKER" -d $DOCKER_OPTS end script # Don't emit "started" event until docker.sock is ready. # See https://github.com/docker/docker/issues/6647 post-start script DOCKER_OPTS= if [ -f /etc/default/$UPSTART_JOB ]; then . /etc/default/$UPSTART_JOB fi if ! printf "%s" "$DOCKER_OPTS" | grep -qE -e '-H|--host'; then while ! [ -e /var/run/docker.sock ]; do initctl status $UPSTART_JOB | grep -qE "(stop|respawn)/" && exit 1 echo "Waiting for /var/run/docker.sock" sleep 0.1 done echo "/var/run/docker.sock is up" fi end script ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage/.febootstrap-minimize ================================================ #!/usr/bin/env bash set -e rootfsDir="$1" shift ( cd "$rootfsDir" # effectively: febootstrap-minimize --keep-zoneinfo --keep-rpmdb --keep-services "$target" # locales rm -rf usr/{{lib,share}/locale,{lib,lib64}/gconv,bin/localedef,sbin/build-locale-archive} # docs and man pages rm -rf usr/share/{man,doc,info,gnome/help} # cracklib rm -rf usr/share/cracklib # i18n rm -rf usr/share/i18n # yum cache rm -rf var/cache/yum mkdir -p --mode=0755 var/cache/yum # sln rm -rf sbin/sln # ldconfig #rm -rf sbin/ldconfig rm -rf etc/ld.so.cache var/cache/ldconfig mkdir -p --mode=0755 var/cache/ldconfig ) ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage/busybox-static ================================================ #!/usr/bin/env bash set -e rootfsDir="$1" shift busybox="$(which busybox 2>/dev/null || true)" if [ -z "$busybox" ]; then echo >&2 'error: busybox: not found' echo >&2 ' install it with your distribution "busybox-static" package' exit 1 fi if ! ldd "$busybox" 2>&1 | grep -q 'not a dynamic executable'; then echo >&2 "error: '$busybox' appears to be a dynamic executable" echo >&2 ' you should install your distribution "busybox-static" package instead' exit 1 fi mkdir -p "$rootfsDir/bin" rm -f "$rootfsDir/bin/busybox" # just in case cp "$busybox" "$rootfsDir/bin/busybox" ( cd "$rootfsDir" IFS=$'\n' modules=( $(bin/busybox --list-modules) ) unset IFS for module in "${modules[@]}"; do mkdir -p "$(dirname "$module")" ln -sf /bin/busybox "$module" done ) ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage/debootstrap ================================================ #!/usr/bin/env bash set -e rootfsDir="$1" shift # we have to do a little fancy footwork to make sure "rootfsDir" becomes the second non-option argument to debootstrap before=() while [ $# -gt 0 ] && [[ "$1" == -* ]]; do before+=( "$1" ) shift done suite="$1" shift # get path to "chroot" in our current PATH chrootPath="$(type -P chroot)" rootfs_chroot() { # "chroot" doesn't set PATH, so we need to set it explicitly to something our new debootstrap chroot can use appropriately! # set PATH and chroot away! PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' \ "$chrootPath" "$rootfsDir" "$@" } # allow for DEBOOTSTRAP=qemu-debootstrap ./mkimage.sh ... : ${DEBOOTSTRAP:=debootstrap} ( set -x $DEBOOTSTRAP "${before[@]}" "$suite" "$rootfsDir" "$@" ) # now for some Docker-specific tweaks # prevent init scripts from running during install/update echo >&2 "+ echo exit 101 > '$rootfsDir/usr/sbin/policy-rc.d'" cat > "$rootfsDir/usr/sbin/policy-rc.d" <<-'EOF' #!/bin/sh # For most Docker users, "apt-get install" only happens during "docker build", # where starting services doesn't work and often fails in humorous ways. This # prevents those failures by stopping the services from attempting to start. exit 101 EOF chmod +x "$rootfsDir/usr/sbin/policy-rc.d" # prevent upstart scripts from running during install/update ( set -x rootfs_chroot dpkg-divert --local --rename --add /sbin/initctl cp -a "$rootfsDir/usr/sbin/policy-rc.d" "$rootfsDir/sbin/initctl" sed -i 's/^exit.*/exit 0/' "$rootfsDir/sbin/initctl" ) # shrink a little, since apt makes us cache-fat (wheezy: ~157.5MB vs ~120MB) ( set -x; rootfs_chroot apt-get clean ) # this file is one APT creates to make sure we don't "autoremove" our currently # in-use kernel, which doesn't really apply to debootstraps/Docker images that # don't even have kernels installed rm -f "$rootfsDir/etc/apt/apt.conf.d/01autoremove-kernels" # Ubuntu 10.04 sucks... :) if strings "$rootfsDir/usr/bin/dpkg" | grep -q unsafe-io; then # force dpkg not to call sync() after package extraction (speeding up installs) echo >&2 "+ echo force-unsafe-io > '$rootfsDir/etc/dpkg/dpkg.cfg.d/docker-apt-speedup'" cat > "$rootfsDir/etc/dpkg/dpkg.cfg.d/docker-apt-speedup" <<-'EOF' # For most Docker users, package installs happen during "docker build", which # doesn't survive power loss and gets restarted clean afterwards anyhow, so # this minor tweak gives us a nice speedup (much nicer on spinning disks, # obviously). force-unsafe-io EOF fi if [ -d "$rootfsDir/etc/apt/apt.conf.d" ]; then # _keep_ us lean by effectively running "apt-get clean" after every install aptGetClean='"rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true";' echo >&2 "+ cat > '$rootfsDir/etc/apt/apt.conf.d/docker-clean'" cat > "$rootfsDir/etc/apt/apt.conf.d/docker-clean" <<-EOF # Since for most Docker users, package installs happen in "docker build" steps, # they essentially become individual layers due to the way Docker handles # layering, especially using CoW filesystems. What this means for us is that # the caches that APT keeps end up just wasting space in those layers, making # our layers unnecessarily large (especially since we'll normally never use # these caches again and will instead just "docker build" again and make a brand # new image). # Ideally, these would just be invoking "apt-get clean", but in our testing, # that ended up being cyclic and we got stuck on APT's lock, so we get this fun # creation that's essentially just "apt-get clean". DPkg::Post-Invoke { ${aptGetClean} }; APT::Update::Post-Invoke { ${aptGetClean} }; Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache ""; # Note that we do realize this isn't the ideal way to do this, and are always # open to better suggestions (https://github.com/docker/docker/issues). EOF # remove apt-cache translations for fast "apt-get update" echo >&2 "+ echo Acquire::Languages 'none' > '$rootfsDir/etc/apt/apt.conf.d/docker-no-languages'" cat > "$rootfsDir/etc/apt/apt.conf.d/docker-no-languages" <<-'EOF' # In Docker, we don't often need the "Translations" files, so we're just wasting # time and space by downloading them, and this inhibits that. For users that do # need them, it's a simple matter to delete this file and "apt-get update". :) Acquire::Languages "none"; EOF echo >&2 "+ echo Acquire::GzipIndexes 'true' > '$rootfsDir/etc/apt/apt.conf.d/docker-gzip-indexes'" cat > "$rootfsDir/etc/apt/apt.conf.d/docker-gzip-indexes" <<-'EOF' # Since Docker users using "RUN apt-get update && apt-get install -y ..." in # their Dockerfiles don't go delete the lists files afterwards, we want them to # be as small as possible on-disk, so we explicitly request "gz" versions and # tell Apt to keep them gzipped on-disk. # For comparison, an "apt-get update" layer without this on a pristine # "debian:wheezy" base image was "29.88 MB", where with this it was only # "8.273 MB". Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz"; EOF # update "autoremove" configuration to be aggressive about removing suggests deps that weren't manually installed echo >&2 "+ echo Apt::AutoRemove::SuggestsImportant 'false' > '$rootfsDir/etc/apt/apt.conf.d/docker-autoremove-suggests'" cat > "$rootfsDir/etc/apt/apt.conf.d/docker-autoremove-suggests" <<-'EOF' # Since Docker users are looking for the smallest possible final images, the # following emerges as a very common pattern: # RUN apt-get update \ # && apt-get install -y \ # && \ # && apt-get purge -y --auto-remove # By default, APT will actually _keep_ packages installed via Recommends or # Depends if another package Suggests them, even and including if the package # that originally caused them to be installed is removed. Setting this to # "false" ensures that APT is appropriately aggressive about removing the # packages it added. # https://aptitude.alioth.debian.org/doc/en/ch02s05s05.html#configApt-AutoRemove-SuggestsImportant Apt::AutoRemove::SuggestsImportant "false"; EOF fi if [ -z "$DONT_TOUCH_SOURCES_LIST" ]; then # tweak sources.list, where appropriate lsbDist= if [ -z "$lsbDist" -a -r "$rootfsDir/etc/os-release" ]; then lsbDist="$(. "$rootfsDir/etc/os-release" && echo "$ID")" fi if [ -z "$lsbDist" -a -r "$rootfsDir/etc/lsb-release" ]; then lsbDist="$(. "$rootfsDir/etc/lsb-release" && echo "$DISTRIB_ID")" fi if [ -z "$lsbDist" -a -r "$rootfsDir/etc/debian_version" ]; then lsbDist='Debian' fi # normalize to lowercase for easier matching lsbDist="$(echo "$lsbDist" | tr '[:upper:]' '[:lower:]')" case "$lsbDist" in debian) # updates and security! if [ "$suite" != 'sid' -a "$suite" != 'unstable' ]; then ( set -x sed -i " p; s/ $suite / ${suite}-updates / " "$rootfsDir/etc/apt/sources.list" echo "deb http://security.debian.org $suite/updates main" >> "$rootfsDir/etc/apt/sources.list" # squeeze-lts if [ -f "$rootfsDir/etc/debian_version" ]; then ltsSuite= case "$(cat "$rootfsDir/etc/debian_version")" in 6.*) ltsSuite='squeeze-lts' ;; #7.*) ltsSuite='wheezy-lts' ;; #8.*) ltsSuite='jessie-lts' ;; esac if [ "$ltsSuite" ]; then head -1 "$rootfsDir/etc/apt/sources.list" \ | sed "s/ $suite / $ltsSuite /" \ >> "$rootfsDir/etc/apt/sources.list" fi fi ) fi ;; ubuntu) # add the updates and security repositories ( set -x sed -i " p; s/ $suite / ${suite}-updates /; p; s/ $suite-updates / ${suite}-security / " "$rootfsDir/etc/apt/sources.list" ) ;; tanglu) # add the updates repository if [ "$suite" != 'devel' ]; then ( set -x sed -i " p; s/ $suite / ${suite}-updates / " "$rootfsDir/etc/apt/sources.list" ) fi ;; steamos) # add contrib and non-free if "main" is the only component ( set -x sed -i "s/ $suite main$/ $suite main contrib non-free/" "$rootfsDir/etc/apt/sources.list" ) ;; esac fi ( set -x # make sure we're fully up-to-date rootfs_chroot sh -xc 'apt-get update && apt-get dist-upgrade -y' # delete all the apt list files since they're big and get stale quickly rm -rf "$rootfsDir/var/lib/apt/lists"/* # this forces "apt-get update" in dependent images, which is also good mkdir "$rootfsDir/var/lib/apt/lists/partial" # Lucid... "E: Lists directory /var/lib/apt/lists/partial is missing." ) ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage/mageia-urpmi ================================================ #!/usr/bin/env bash # # Needs to be run from Mageia 4 or greater for kernel support for docker. # # Mageia 4 does not have docker available in official repos, so please # install and run the docker binary manually. # # Tested working versions are for Mageia 2 onwards (inc. cauldron). # set -e rootfsDir="$1" shift optTemp=$(getopt --options '+v:,m:' --longoptions 'version:,mirror:' --name mageia-urpmi -- "$@") eval set -- "$optTemp" unset optTemp installversion= mirror= while true; do case "$1" in -v|--version) installversion="$2" ; shift 2 ;; -m|--mirror) mirror="$2" ; shift 2 ;; --) shift ; break ;; esac done if [ -z $installversion ]; then # Attempt to match host version if [ -r /etc/mageia-release ]; then installversion="$(sed 's/^[^0-9\]*\([0-9.]\+\).*$/\1/' /etc/mageia-release)" else echo "Error: no version supplied and unable to detect host mageia version" exit 1 fi fi if [ -z $mirror ]; then # No mirror provided, default to mirrorlist mirror="--mirrorlist https://mirrors.mageia.org/api/mageia.$installversion.x86_64.list" fi ( set -x urpmi.addmedia --distrib \ $mirror \ --urpmi-root "$rootfsDir" urpmi basesystem-minimal urpmi \ --auto \ --no-suggests \ --urpmi-root "$rootfsDir" \ --root "$rootfsDir" ) "$(dirname "$BASH_SOURCE")/.febootstrap-minimize" "$rootfsDir" if [ -d "$rootfsDir/etc/sysconfig" ]; then # allow networking init scripts inside the container to work without extra steps echo 'NETWORKING=yes' > "$rootfsDir/etc/sysconfig/network" fi ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage/rinse ================================================ #!/usr/bin/env bash set -e rootfsDir="$1" shift # specifying --arch below is safe because "$@" can override it and the "latest" one wins :) ( set -x rinse --directory "$rootfsDir" --arch amd64 "$@" ) "$(dirname "$BASH_SOURCE")/.febootstrap-minimize" "$rootfsDir" if [ -d "$rootfsDir/etc/sysconfig" ]; then # allow networking init scripts inside the container to work without extra steps echo 'NETWORKING=yes' > "$rootfsDir/etc/sysconfig/network" fi # make sure we're fully up-to-date, too ( set -x chroot "$rootfsDir" yum update -y ) ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-alpine.sh ================================================ #!/bin/sh set -e [ $(id -u) -eq 0 ] || { printf >&2 '%s requires root\n' "$0" exit 1 } usage() { printf >&2 '%s: [-r release] [-m mirror] [-s]\n' "$0" exit 1 } tmp() { TMP=$(mktemp -d ${TMPDIR:-/var/tmp}/alpine-docker-XXXXXXXXXX) ROOTFS=$(mktemp -d ${TMPDIR:-/var/tmp}/alpine-docker-rootfs-XXXXXXXXXX) trap "rm -rf $TMP $ROOTFS" EXIT TERM INT } apkv() { curl -sSL $REPO/$ARCH/APKINDEX.tar.gz | tar -Oxz | grep '^P:apk-tools-static$' -A1 | tail -n1 | cut -d: -f2 } getapk() { curl -sSL $REPO/$ARCH/apk-tools-static-$(apkv).apk | tar -xz -C $TMP sbin/apk.static } mkbase() { $TMP/sbin/apk.static --repository $REPO --update-cache --allow-untrusted \ --root $ROOTFS --initdb add alpine-base } conf() { printf '%s\n' $REPO > $ROOTFS/etc/apk/repositories } pack() { local id id=$(tar --numeric-owner -C $ROOTFS -c . | docker import - alpine:$REL) docker tag $id alpine:latest docker run -i -t alpine printf 'alpine:%s with id=%s created!\n' $REL $id } save() { [ $SAVE -eq 1 ] || return tar --numeric-owner -C $ROOTFS -c . | xz > rootfs.tar.xz } while getopts "hr:m:s" opt; do case $opt in r) REL=$OPTARG ;; m) MIRROR=$OPTARG ;; s) SAVE=1 ;; *) usage ;; esac done REL=${REL:-edge} MIRROR=${MIRROR:-http://nl.alpinelinux.org/alpine} SAVE=${SAVE:-0} REPO=$MIRROR/$REL/main ARCH=${ARCH:-$(uname -m)} tmp getapk mkbase conf pack save ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-arch-pacman.conf ================================================ # # /etc/pacman.conf # # See the pacman.conf(5) manpage for option and repository directives # # GENERAL OPTIONS # [options] # The following paths are commented out with their default values listed. # If you wish to use different paths, uncomment and update the paths. #RootDir = / #DBPath = /var/lib/pacman/ #CacheDir = /var/cache/pacman/pkg/ #LogFile = /var/log/pacman.log #GPGDir = /etc/pacman.d/gnupg/ HoldPkg = pacman glibc #XferCommand = /usr/bin/curl -C - -f %u > %o #XferCommand = /usr/bin/wget --passive-ftp -c -O %o %u #CleanMethod = KeepInstalled #UseDelta = 0.7 Architecture = auto # Pacman won't upgrade packages listed in IgnorePkg and members of IgnoreGroup #IgnorePkg = #IgnoreGroup = #NoUpgrade = #NoExtract = # Misc options #UseSyslog #Color #TotalDownload # We cannot check disk space from within a chroot environment #CheckSpace #VerbosePkgLists # By default, pacman accepts packages signed by keys that its local keyring # trusts (see pacman-key and its man page), as well as unsigned packages. SigLevel = Required DatabaseOptional LocalFileSigLevel = Optional #RemoteFileSigLevel = Required # NOTE: You must run `pacman-key --init` before first using pacman; the local # keyring can then be populated with the keys of all official Arch Linux # packagers with `pacman-key --populate archlinux`. # # REPOSITORIES # - can be defined here or included from another file # - pacman will search repositories in the order defined here # - local/custom mirrors can be added here or in separate files # - repositories listed first will take precedence when packages # have identical names, regardless of version number # - URLs will have $repo replaced by the name of the current repo # - URLs will have $arch replaced by the name of the architecture # # Repository entries are of the format: # [repo-name] # Server = ServerName # Include = IncludePath # # The header [repo-name] is crucial - it must be present and # uncommented to enable the repo. # # The testing repositories are disabled by default. To enable, uncomment the # repo name header and Include lines. You can add preferred servers immediately # after the header, and they will be used before the default mirrors. #[testing] #Include = /etc/pacman.d/mirrorlist [core] Include = /etc/pacman.d/mirrorlist [extra] Include = /etc/pacman.d/mirrorlist #[community-testing] #Include = /etc/pacman.d/mirrorlist [community] Include = /etc/pacman.d/mirrorlist # An example of a custom package repository. See the pacman manpage for # tips on creating your own repositories. #[custom] #SigLevel = Optional TrustAll #Server = file:///home/custompkgs ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-arch.sh ================================================ #!/usr/bin/env bash # Generate a minimal filesystem for archlinux and load it into the local # docker as "archlinux" # requires root set -e hash pacstrap &>/dev/null || { echo "Could not find pacstrap. Run pacman -S arch-install-scripts" exit 1 } hash expect &>/dev/null || { echo "Could not find expect. Run pacman -S expect" exit 1 } export LANG="C.UTF-8" ROOTFS=$(mktemp -d ${TMPDIR:-/var/tmp}/rootfs-archlinux-XXXXXXXXXX) chmod 755 $ROOTFS # packages to ignore for space savings PKGIGNORE=( cryptsetup device-mapper dhcpcd iproute2 jfsutils linux lvm2 man-db man-pages mdadm nano netctl openresolv pciutils pcmciautils reiserfsprogs s-nail systemd-sysvcompat usbutils vi xfsprogs ) IFS=',' PKGIGNORE="${PKGIGNORE[*]}" unset IFS expect < $ROOTFS/etc/locale.gen arch-chroot $ROOTFS locale-gen arch-chroot $ROOTFS /bin/sh -c 'echo "Server = https://mirrors.kernel.org/archlinux/\$repo/os/\$arch" > /etc/pacman.d/mirrorlist' # udev doesn't work in containers, rebuild /dev DEV=$ROOTFS/dev rm -rf $DEV mkdir -p $DEV mknod -m 666 $DEV/null c 1 3 mknod -m 666 $DEV/zero c 1 5 mknod -m 666 $DEV/random c 1 8 mknod -m 666 $DEV/urandom c 1 9 mkdir -m 755 $DEV/pts mkdir -m 1777 $DEV/shm mknod -m 666 $DEV/tty c 5 0 mknod -m 600 $DEV/console c 5 1 mknod -m 666 $DEV/tty0 c 4 0 mknod -m 666 $DEV/full c 1 7 mknod -m 600 $DEV/initctl p mknod -m 666 $DEV/ptmx c 5 2 ln -sf /proc/self/fd $DEV/fd tar --numeric-owner --xattrs --acls -C $ROOTFS -c . | docker import - archlinux docker run -t archlinux echo Success. rm -rf $ROOTFS ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-busybox.sh ================================================ #!/usr/bin/env bash # Generate a very minimal filesystem based on busybox-static, # and load it into the local docker under the name "busybox". echo >&2 echo >&2 'warning: this script is deprecated - see mkimage.sh and mkimage/busybox-static' echo >&2 BUSYBOX=$(which busybox) [ "$BUSYBOX" ] || { echo "Sorry, I could not locate busybox." echo "Try 'apt-get install busybox-static'?" exit 1 } set -e ROOTFS=${TMPDIR:-/var/tmp}/rootfs-busybox-$$-$RANDOM mkdir $ROOTFS cd $ROOTFS mkdir bin etc dev dev/pts lib proc sys tmp touch etc/resolv.conf cp /etc/nsswitch.conf etc/nsswitch.conf echo root:x:0:0:root:/:/bin/sh > etc/passwd echo root:x:0: > etc/group ln -s lib lib64 ln -s bin sbin cp $BUSYBOX bin for X in $(busybox --list) do ln -s busybox bin/$X done rm bin/init ln bin/busybox bin/init cp /lib/x86_64-linux-gnu/lib{pthread,c,dl,nsl,nss_*}.so.* lib cp /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 lib for X in console null ptmx random stdin stdout stderr tty urandom zero do cp -a /dev/$X dev done tar --numeric-owner -cf- . | docker import - busybox docker run -i -u root busybox /bin/echo Success. ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-crux.sh ================================================ #!/usr/bin/env bash # Generate a minimal filesystem for CRUX/Linux and load it into the local # docker as "cruxlinux" # requires root and the crux iso (http://crux.nu) set -e die () { echo >&2 "$@" exit 1 } [ "$#" -eq 1 ] || die "1 argument(s) required, $# provided. Usage: ./mkimage-crux.sh /path/to/iso" ISO=${1} ROOTFS=$(mktemp -d ${TMPDIR:-/var/tmp}/rootfs-crux-XXXXXXXXXX) CRUX=$(mktemp -d ${TMPDIR:-/var/tmp}/crux-XXXXXXXXXX) TMP=$(mktemp -d ${TMPDIR:-/var/tmp}/XXXXXXXXXX) VERSION=$(basename --suffix=.iso $ISO | sed 's/[^0-9.]*\([0-9.]*\).*/\1/') # Mount the ISO mount -o ro,loop $ISO $CRUX # Extract pkgutils tar -C $TMP -xf $CRUX/tools/pkgutils#*.pkg.tar.gz # Put pkgadd in the $PATH export PATH="$TMP/usr/bin:$PATH" # Install core packages mkdir -p $ROOTFS/var/lib/pkg touch $ROOTFS/var/lib/pkg/db for pkg in $CRUX/crux/core/*; do pkgadd -r $ROOTFS $pkg done # Remove agetty and inittab config if (grep agetty ${ROOTFS}/etc/inittab 2>&1 > /dev/null); then echo "Removing agetty from /etc/inittab ..." chroot ${ROOTFS} sed -i -e "/agetty/d" /etc/inittab chroot ${ROOTFS} sed -i -e "/shutdown/d" /etc/inittab chroot ${ROOTFS} sed -i -e "/^$/N;/^\n$/d" /etc/inittab fi # Remove kernel source rm -rf $ROOTFS/usr/src/* # udev doesn't work in containers, rebuild /dev DEV=$ROOTFS/dev rm -rf $DEV mkdir -p $DEV mknod -m 666 $DEV/null c 1 3 mknod -m 666 $DEV/zero c 1 5 mknod -m 666 $DEV/random c 1 8 mknod -m 666 $DEV/urandom c 1 9 mkdir -m 755 $DEV/pts mkdir -m 1777 $DEV/shm mknod -m 666 $DEV/tty c 5 0 mknod -m 600 $DEV/console c 5 1 mknod -m 666 $DEV/tty0 c 4 0 mknod -m 666 $DEV/full c 1 7 mknod -m 600 $DEV/initctl p mknod -m 666 $DEV/ptmx c 5 2 IMAGE_ID=$(tar --numeric-owner -C $ROOTFS -c . | docker import - crux:$VERSION) docker tag $IMAGE_ID crux:latest docker run -i -t crux echo Success. # Cleanup umount $CRUX rm -rf $ROOTFS rm -rf $CRUX rm -rf $TMP ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-debootstrap.sh ================================================ #!/usr/bin/env bash set -e echo >&2 echo >&2 'warning: this script is deprecated - see mkimage.sh and mkimage/debootstrap' echo >&2 variant='minbase' include='iproute,iputils-ping' arch='amd64' # intentionally undocumented for now skipDetection= strictDebootstrap= justTar= usage() { echo >&2 echo >&2 "usage: $0 [options] repo suite [mirror]" echo >&2 echo >&2 'options: (not recommended)' echo >&2 " -p set an http_proxy for debootstrap" echo >&2 " -v $variant # change default debootstrap variant" echo >&2 " -i $include # change default package includes" echo >&2 " -d # strict debootstrap (do not apply any docker-specific tweaks)" echo >&2 " -s # skip version detection and tagging (ie, precise also tagged as 12.04)" echo >&2 " # note that this will also skip adding universe and/or security/updates to sources.list" echo >&2 " -t # just create a tarball, especially for dockerbrew (uses repo as tarball name)" echo >&2 echo >&2 " ie: $0 username/debian squeeze" echo >&2 " $0 username/debian squeeze http://ftp.uk.debian.org/debian/" echo >&2 echo >&2 " ie: $0 username/ubuntu precise" echo >&2 " $0 username/ubuntu precise http://mirrors.melbourne.co.uk/ubuntu/" echo >&2 echo >&2 " ie: $0 -t precise.tar.bz2 precise" echo >&2 " $0 -t wheezy.tgz wheezy" echo >&2 " $0 -t wheezy-uk.tar.xz wheezy http://ftp.uk.debian.org/debian/" echo >&2 } # these should match the names found at http://www.debian.org/releases/ debianStable=wheezy debianUnstable=sid # this should match the name found at http://releases.ubuntu.com/ ubuntuLatestLTS=trusty # this should match the name found at http://releases.tanglu.org/ tangluLatest=aequorea while getopts v:i:a:p:dst name; do case "$name" in p) http_proxy="$OPTARG" ;; v) variant="$OPTARG" ;; i) include="$OPTARG" ;; a) arch="$OPTARG" ;; d) strictDebootstrap=1 ;; s) skipDetection=1 ;; t) justTar=1 ;; ?) usage exit 0 ;; esac done shift $(($OPTIND - 1)) repo="$1" suite="$2" mirror="${3:-}" # stick to the default debootstrap mirror if one is not provided if [ ! "$repo" ] || [ ! "$suite" ]; then usage exit 1 fi # some rudimentary detection for whether we need to "sudo" our docker calls docker='' if docker version > /dev/null 2>&1; then docker='docker' elif sudo docker version > /dev/null 2>&1; then docker='sudo docker' elif command -v docker > /dev/null 2>&1; then docker='docker' else echo >&2 "warning: either docker isn't installed, or your current user cannot run it;" echo >&2 " this script is not likely to work as expected" sleep 3 docker='docker' # give us a command-not-found later fi # make sure we have an absolute path to our final tarball so we can still reference it properly after we change directory if [ "$justTar" ]; then if [ ! -d "$(dirname "$repo")" ]; then echo >&2 "error: $(dirname "$repo") does not exist" exit 1 fi repo="$(cd "$(dirname "$repo")" && pwd -P)/$(basename "$repo")" fi # will be filled in later, if [ -z "$skipDetection" ] lsbDist='' target="${TMPDIR:-/var/tmp}/docker-rootfs-debootstrap-$suite-$$-$RANDOM" cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" returnTo="$(pwd -P)" if [ "$suite" = 'lucid' ]; then # lucid fails and doesn't include gpgv in minbase; "apt-get update" fails include+=',gpgv' fi set -x # bootstrap mkdir -p "$target" sudo http_proxy=$http_proxy debootstrap --verbose --variant="$variant" --include="$include" --arch="$arch" "$suite" "$target" "$mirror" cd "$target" if [ -z "$strictDebootstrap" ]; then # prevent init scripts from running during install/update # policy-rc.d (for most scripts) echo $'#!/bin/sh\nexit 101' | sudo tee usr/sbin/policy-rc.d > /dev/null sudo chmod +x usr/sbin/policy-rc.d # initctl (for some pesky upstart scripts) sudo chroot . dpkg-divert --local --rename --add /sbin/initctl sudo ln -sf /bin/true sbin/initctl # see https://github.com/docker/docker/issues/446#issuecomment-16953173 # shrink the image, since apt makes us fat (wheezy: ~157.5MB vs ~120MB) sudo chroot . apt-get clean if strings usr/bin/dpkg | grep -q unsafe-io; then # while we're at it, apt is unnecessarily slow inside containers # this forces dpkg not to call sync() after package extraction and speeds up install # the benefit is huge on spinning disks, and the penalty is nonexistent on SSD or decent server virtualization echo 'force-unsafe-io' | sudo tee etc/dpkg/dpkg.cfg.d/02apt-speedup > /dev/null # we have this wrapped up in an "if" because the "force-unsafe-io" # option was added in dpkg 1.15.8.6 # (see http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=584254#82), # and ubuntu lucid/10.04 only has 1.15.5.6 fi # we want to effectively run "apt-get clean" after every install to keep images small (see output of "apt-get clean -s" for context) { aptGetClean='"rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true";' echo "DPkg::Post-Invoke { ${aptGetClean} };" echo "APT::Update::Post-Invoke { ${aptGetClean} };" echo 'Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";' } | sudo tee etc/apt/apt.conf.d/no-cache > /dev/null # and remove the translations, too echo 'Acquire::Languages "none";' | sudo tee etc/apt/apt.conf.d/no-languages > /dev/null # helpful undo lines for each the above tweaks (for lack of a better home to keep track of them): # rm /usr/sbin/policy-rc.d # rm /sbin/initctl; dpkg-divert --rename --remove /sbin/initctl # rm /etc/dpkg/dpkg.cfg.d/02apt-speedup # rm /etc/apt/apt.conf.d/no-cache # rm /etc/apt/apt.conf.d/no-languages if [ -z "$skipDetection" ]; then # see also rudimentary platform detection in hack/install.sh lsbDist='' if [ -r etc/lsb-release ]; then lsbDist="$(. etc/lsb-release && echo "$DISTRIB_ID")" fi if [ -z "$lsbDist" ] && [ -r etc/debian_version ]; then lsbDist='Debian' fi case "$lsbDist" in Debian) # add the updates and security repositories if [ "$suite" != "$debianUnstable" -a "$suite" != 'unstable' ]; then # ${suite}-updates only applies to non-unstable sudo sed -i "p; s/ $suite main$/ ${suite}-updates main/" etc/apt/sources.list # same for security updates echo "deb http://security.debian.org/ $suite/updates main" | sudo tee -a etc/apt/sources.list > /dev/null fi ;; Ubuntu) # add the universe, updates, and security repositories sudo sed -i " s/ $suite main$/ $suite main universe/; p; s/ $suite main/ ${suite}-updates main/; p; s/ $suite-updates main/ ${suite}-security main/ " etc/apt/sources.list ;; Tanglu) # add the updates repository if [ "$suite" = "$tangluLatest" ]; then # ${suite}-updates only applies to stable Tanglu versions sudo sed -i "p; s/ $suite main$/ ${suite}-updates main/" etc/apt/sources.list fi ;; SteamOS) # add contrib and non-free sudo sed -i "s/ $suite main$/ $suite main contrib non-free/" etc/apt/sources.list ;; esac fi # make sure our packages lists are as up to date as we can get them sudo chroot . apt-get update sudo chroot . apt-get dist-upgrade -y fi if [ "$justTar" ]; then # create the tarball file so it has the right permissions (ie, not root) touch "$repo" # fill the tarball sudo tar --numeric-owner -caf "$repo" . else # create the image (and tag $repo:$suite) sudo tar --numeric-owner -c . | $docker import - $repo:$suite # test the image $docker run -i -t $repo:$suite echo success if [ -z "$skipDetection" ]; then case "$lsbDist" in Debian) if [ "$suite" = "$debianStable" -o "$suite" = 'stable' ] && [ -r etc/debian_version ]; then # tag latest $docker tag $repo:$suite $repo:latest if [ -r etc/debian_version ]; then # tag the specific debian release version (which is only reasonable to tag on debian stable) ver=$(cat etc/debian_version) $docker tag $repo:$suite $repo:$ver fi fi ;; Ubuntu) if [ "$suite" = "$ubuntuLatestLTS" ]; then # tag latest $docker tag $repo:$suite $repo:latest fi if [ -r etc/lsb-release ]; then lsbRelease="$(. etc/lsb-release && echo "$DISTRIB_RELEASE")" if [ "$lsbRelease" ]; then # tag specific Ubuntu version number, if available (12.04, etc.) $docker tag $repo:$suite $repo:$lsbRelease fi fi ;; Tanglu) if [ "$suite" = "$tangluLatest" ]; then # tag latest $docker tag $repo:$suite $repo:latest fi if [ -r etc/lsb-release ]; then lsbRelease="$(. etc/lsb-release && echo "$DISTRIB_RELEASE")" if [ "$lsbRelease" ]; then # tag specific Tanglu version number, if available (1.0, 2.0, etc.) $docker tag $repo:$suite $repo:$lsbRelease fi fi ;; SteamOS) if [ -r etc/lsb-release ]; then lsbRelease="$(. etc/lsb-release && echo "$DISTRIB_RELEASE")" if [ "$lsbRelease" ]; then # tag specific SteamOS version number, if available (1.0, 2.0, etc.) $docker tag $repo:$suite $repo:$lsbRelease fi fi ;; esac fi fi # cleanup cd "$returnTo" sudo rm -rf "$target" ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-rinse.sh ================================================ #!/usr/bin/env bash # # Create a base CentOS Docker image. # This script is useful on systems with rinse available (e.g., # building a CentOS image on Debian). See contrib/mkimage-yum.sh for # a way to build CentOS images on systems with yum installed. set -e echo >&2 echo >&2 'warning: this script is deprecated - see mkimage.sh and mkimage/rinse' echo >&2 repo="$1" distro="$2" mirror="$3" if [ ! "$repo" ] || [ ! "$distro" ]; then self="$(basename $0)" echo >&2 "usage: $self repo distro [mirror]" echo >&2 echo >&2 " ie: $self username/centos centos-5" echo >&2 " $self username/centos centos-6" echo >&2 echo >&2 " ie: $self username/slc slc-5" echo >&2 " $self username/slc slc-6" echo >&2 echo >&2 " ie: $self username/centos centos-5 http://vault.centos.org/5.8/os/x86_64/CentOS/" echo >&2 " $self username/centos centos-6 http://vault.centos.org/6.3/os/x86_64/Packages/" echo >&2 echo >&2 'See /etc/rinse for supported values of "distro" and for examples of' echo >&2 ' expected values of "mirror".' echo >&2 echo >&2 'This script is tested to work with the original upstream version of rinse,' echo >&2 ' found at http://www.steve.org.uk/Software/rinse/ and also in Debian at' echo >&2 ' http://packages.debian.org/wheezy/rinse -- as always, YMMV.' echo >&2 exit 1 fi target="${TMPDIR:-/var/tmp}/docker-rootfs-rinse-$distro-$$-$RANDOM" cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" returnTo="$(pwd -P)" rinseArgs=( --arch amd64 --distribution "$distro" --directory "$target" ) if [ "$mirror" ]; then rinseArgs+=( --mirror "$mirror" ) fi set -x mkdir -p "$target" sudo rinse "${rinseArgs[@]}" cd "$target" # rinse fails a little at setting up /dev, so we'll just wipe it out and create our own sudo rm -rf dev sudo mkdir -m 755 dev ( cd dev sudo ln -sf /proc/self/fd ./ sudo mkdir -m 755 pts sudo mkdir -m 1777 shm sudo mknod -m 600 console c 5 1 sudo mknod -m 600 initctl p sudo mknod -m 666 full c 1 7 sudo mknod -m 666 null c 1 3 sudo mknod -m 666 ptmx c 5 2 sudo mknod -m 666 random c 1 8 sudo mknod -m 666 tty c 5 0 sudo mknod -m 666 tty0 c 4 0 sudo mknod -m 666 urandom c 1 9 sudo mknod -m 666 zero c 1 5 ) # effectively: febootstrap-minimize --keep-zoneinfo --keep-rpmdb --keep-services "$target" # locales sudo rm -rf usr/{{lib,share}/locale,{lib,lib64}/gconv,bin/localedef,sbin/build-locale-archive} # docs and man pages sudo rm -rf usr/share/{man,doc,info,gnome/help} # cracklib sudo rm -rf usr/share/cracklib # i18n sudo rm -rf usr/share/i18n # yum cache sudo rm -rf var/cache/yum sudo mkdir -p --mode=0755 var/cache/yum # sln sudo rm -rf sbin/sln # ldconfig #sudo rm -rf sbin/ldconfig sudo rm -rf etc/ld.so.cache var/cache/ldconfig sudo mkdir -p --mode=0755 var/cache/ldconfig # allow networking init scripts inside the container to work without extra steps echo 'NETWORKING=yes' | sudo tee etc/sysconfig/network > /dev/null # to restore locales later: # yum reinstall glibc-common version= if [ -r etc/redhat-release ]; then version="$(sed -E 's/^[^0-9.]*([0-9.]+).*$/\1/' etc/redhat-release)" elif [ -r etc/SuSE-release ]; then version="$(awk '/^VERSION/ { print $3 }' etc/SuSE-release)" fi if [ -z "$version" ]; then echo >&2 "warning: cannot autodetect OS version, using $distro as tag" sleep 20 version="$distro" fi sudo tar --numeric-owner -c . | docker import - $repo:$version docker run -i -t $repo:$version echo success cd "$returnTo" sudo rm -rf "$target" ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage-yum.sh ================================================ #!/usr/bin/env bash # # Create a base CentOS Docker image. # # This script is useful on systems with yum installed (e.g., building # a CentOS image on CentOS). See contrib/mkimage-rinse.sh for a way # to build CentOS images on other systems. usage() { cat < OPTIONS: -y The path to the yum config to install packages from. The default is /etc/yum.conf. EOOPTS exit 1 } # option defaults yum_config=/etc/yum.conf while getopts ":y:h" opt; do case $opt in y) yum_config=$OPTARG ;; h) usage ;; \?) echo "Invalid option: -$OPTARG" usage ;; esac done shift $((OPTIND - 1)) name=$1 if [[ -z $name ]]; then usage fi #-------------------- target=$(mktemp -d --tmpdir $(basename $0).XXXXXX) set -x mkdir -m 755 "$target"/dev mknod -m 600 "$target"/dev/console c 5 1 mknod -m 600 "$target"/dev/initctl p mknod -m 666 "$target"/dev/full c 1 7 mknod -m 666 "$target"/dev/null c 1 3 mknod -m 666 "$target"/dev/ptmx c 5 2 mknod -m 666 "$target"/dev/random c 1 8 mknod -m 666 "$target"/dev/tty c 5 0 mknod -m 666 "$target"/dev/tty0 c 4 0 mknod -m 666 "$target"/dev/urandom c 1 9 mknod -m 666 "$target"/dev/zero c 1 5 # amazon linux yum will fail without vars set if [ -d /etc/yum/vars ]; then mkdir -p -m 755 "$target"/etc/yum cp -a /etc/yum/vars "$target"/etc/yum/ fi yum -c "$yum_config" --installroot="$target" --releasever=/ --setopt=tsflags=nodocs \ --setopt=group_package_types=mandatory -y groupinstall Core yum -c "$yum_config" --installroot="$target" -y clean all cat > "$target"/etc/sysconfig/network <&2 "warning: cannot autodetect OS version, using '$name' as tag" version=$name fi tar --numeric-owner -c -C "$target" . | docker import - $name:$version docker run -i -t $name:$version echo success rm -rf "$target" ================================================ FILE: vendor/github.com/docker/docker/contrib/mkimage.sh ================================================ #!/usr/bin/env bash set -e mkimg="$(basename "$0")" usage() { echo >&2 "usage: $mkimg [-d dir] [-t tag] script [script-args]" echo >&2 " ie: $mkimg -t someuser/debian debootstrap --variant=minbase jessie" echo >&2 " $mkimg -t someuser/ubuntu debootstrap --include=ubuntu-minimal --components=main,universe trusty" echo >&2 " $mkimg -t someuser/busybox busybox-static" echo >&2 " $mkimg -t someuser/centos:5 rinse --distribution centos-5" echo >&2 " $mkimg -t someuser/mageia:4 mageia-urpmi --version=4" echo >&2 " $mkimg -t someuser/mageia:4 mageia-urpmi --version=4 --mirror=http://somemirror/" exit 1 } scriptDir="$(dirname "$(readlink -f "$BASH_SOURCE")")/mkimage" optTemp=$(getopt --options '+d:t:h' --longoptions 'dir:,tag:,help' --name "$mkimg" -- "$@") eval set -- "$optTemp" unset optTemp dir= tag= while true; do case "$1" in -d|--dir) dir="$2" ; shift 2 ;; -t|--tag) tag="$2" ; shift 2 ;; -h|--help) usage ;; --) shift ; break ;; esac done script="$1" [ "$script" ] || usage shift if [ ! -x "$scriptDir/$script" ]; then echo >&2 "error: $script does not exist or is not executable" echo >&2 " see $scriptDir for possible scripts" exit 1 fi # don't mistake common scripts like .febootstrap-minimize as image-creators if [[ "$script" == .* ]]; then echo >&2 "error: $script is a script helper, not a script" echo >&2 " see $scriptDir for possible scripts" exit 1 fi delDir= if [ -z "$dir" ]; then dir="$(mktemp -d ${TMPDIR:-/var/tmp}/docker-mkimage.XXXXXXXXXX)" delDir=1 fi rootfsDir="$dir/rootfs" ( set -x; mkdir -p "$rootfsDir" ) # pass all remaining arguments to $script "$scriptDir/$script" "$rootfsDir" "$@" # Docker mounts tmpfs at /dev and procfs at /proc so we can remove them rm -rf "$rootfsDir/dev" "$rootfsDir/proc" mkdir -p "$rootfsDir/dev" "$rootfsDir/proc" # make sure /etc/resolv.conf has something useful in it mkdir -p "$rootfsDir/etc" cat > "$rootfsDir/etc/resolv.conf" <<'EOF' nameserver 8.8.8.8 nameserver 8.8.4.4 EOF tarFile="$dir/rootfs.tar.xz" touch "$tarFile" ( set -x tar --numeric-owner -caf "$tarFile" -C "$rootfsDir" --transform='s,^./,,' . ) echo >&2 "+ cat > '$dir/Dockerfile'" cat > "$dir/Dockerfile" <<'EOF' FROM scratch ADD rootfs.tar.xz / EOF # if our generated image has a decent shell, let's set a default command for shell in /bin/bash /usr/bin/fish /usr/bin/zsh /bin/sh; do if [ -x "$rootfsDir/$shell" ]; then ( set -x; echo 'CMD ["'"$shell"'"]' >> "$dir/Dockerfile" ) break fi done ( set -x; rm -rf "$rootfsDir" ) if [ "$tag" ]; then ( set -x; docker build -t "$tag" "$dir" ) elif [ "$delDir" ]; then # if we didn't specify a tag and we're going to delete our dir, let's just build an untagged image so that we did _something_ ( set -x; docker build "$dir" ) fi if [ "$delDir" ]; then ( set -x; rm -rf "$dir" ) fi ================================================ FILE: vendor/github.com/docker/docker/contrib/mkseccomp.pl ================================================ #!/usr/bin/perl # # A simple helper script to help people build seccomp profiles for # Docker/LXC. The goal is mostly to reduce the attack surface to the # kernel, by restricting access to rarely used, recently added or not used # syscalls. # # This script processes one or more files which contain the list of system # calls to be allowed. See mkseccomp.sample for more information how you # can configure the list of syscalls. When run, this script produces output # which, when stored in a file, can be passed to docker as follows: # # docker run --lxc-conf="lxc.seccomp=$file" # # The included sample file shows how to cut about a quarter of all syscalls, # which affecting most applications. # # For specific situations it is possible to reduce the list further. By # reducing the list to just those syscalls required by a certain application # you can make it difficult for unknown/unexpected code to run. # # Run this script as follows: # # ./mkseccomp.pl < mkseccomp.sample >syscalls.list # or # ./mkseccomp.pl mkseccomp.sample >syscalls.list # # Multiple files can be specified, in which case the lists of syscalls are # combined. # # By Martijn van Oosterhout Nov 2013 # How it works: # # This program basically spawns two processes to form a chain like: # # | cpp | use strict; use warnings; if( -t ) { print STDERR "Helper script to make seccomp filters for Docker/LXC.\n"; print STDERR "Usage: mkseccomp.pl < [files...]\n"; exit 1; } my $pid = open(my $in, "-|") // die "Couldn't fork1 ($!)\n"; if($pid == 0) { # Child $pid = open(my $out, "|-") // die "Couldn't fork2 ($!)\n"; if($pid == 0) { # Child, which execs cpp exec "cpp" or die "Couldn't exec cpp ($!)\n"; exit 1; } # Process the DATA section and output to cpp print $out "#include \n"; while(<>) { if(/^\w/) { print $out "__NR_$_"; } } close $out; exit 0; } # Print header and then process output from cpp. print "1\n"; print "whitelist\n"; while(<$in>) { print if( /^[0-9]/ ); } ================================================ FILE: vendor/github.com/docker/docker/contrib/mkseccomp.sample ================================================ /* This sample file is an example for mkseccomp.pl to produce a seccomp file * which restricts syscalls that are only useful for an admin but allows the * vast majority of normal userspace programs to run normally. * * The format of this file is one line per syscall. This is then processed * and passed to 'cpp' to convert the names to numbers using whatever is * correct for your platform. As such C-style comments are permitted. Note * this also means that C preprocessor macros are also allowed. So it is * possible to create groups surrounded by #ifdef/#endif and control their * inclusion via #define (not #include). * * Syscalls that don't exist on your architecture are silently filtered out. * Syscalls marked with (*) are required for a container to spawn a bash * shell successfully (not necessarily full featured). Listing the same * syscall multiple times is no problem. * * If you want to make a list specifically for one application the easiest * way is to run the application under strace, like so: * * $ strace -f -q -c -o strace.out application args... * * Once you have a reasonable sample of the execution of the program, exit * it. The file strace.out will have a summary of the syscalls used. Copy * that list into this file, comment out everything else except the starred * syscalls (which you need for the container to start) and you're done. * * To get the list of syscalls from the strace output this works well for * me * * $ cut -c52 < strace.out * * This sample list was compiled as a combination of all the syscalls * available on i386 and amd64 on Ubuntu Precise, as such it may not contain * everything and not everything may be relevent for your system. This * shouldn't be a problem. */ // Filesystem/File descriptor related access // (*) chdir // (*) chmod chown chown32 close // (*) creat dup // (*) dup2 // (*) dup3 epoll_create epoll_create1 epoll_ctl epoll_ctl_old epoll_pwait epoll_wait epoll_wait_old eventfd eventfd2 faccessat // (*) fadvise64 fadvise64_64 fallocate fanotify_init fanotify_mark ioctl // (*) fchdir fchmod fchmodat fchown fchown32 fchownat fcntl // (*) fcntl64 fdatasync fgetxattr flistxattr flock fremovexattr fsetxattr fstat // (*) fstat64 fstatat64 fstatfs fstatfs64 fsync ftruncate ftruncate64 getcwd // (*) getdents // (*) getdents64 getxattr inotify_add_watch inotify_init inotify_init1 inotify_rm_watch io_cancel io_destroy io_getevents io_setup io_submit lchown lchown32 lgetxattr link linkat listxattr llistxattr llseek _llseek lremovexattr lseek // (*) lsetxattr lstat lstat64 mkdir mkdirat mknod mknodat newfstatat _newselect oldfstat oldlstat oldolduname oldstat olduname oldwait4 open // (*) openat // (*) pipe // (*) pipe2 poll ppoll pread64 preadv futimesat pselect6 pwrite64 pwritev read // (*) readahead readdir readlink readlinkat readv removexattr rename renameat rmdir select sendfile sendfile64 setxattr splice stat // (*) stat64 statfs // (*) statfs64 symlink symlinkat sync sync_file_range sync_file_range2 syncfs tee truncate truncate64 umask unlink unlinkat ustat utime utimensat utimes write // (*) writev // Network related accept accept4 bind // (*) connect // (*) getpeername getsockname // (*) getsockopt listen recv recvfrom // (*) recvmmsg recvmsg send sendmmsg sendmsg sendto // (*) setsockopt shutdown socket // (*) socketcall socketpair sethostname // (*) // Signal related pause rt_sigaction // (*) rt_sigpending rt_sigprocmask // (*) rt_sigqueueinfo rt_sigreturn // (*) rt_sigsuspend rt_sigtimedwait rt_tgsigqueueinfo sigaction sigaltstack // (*) signal signalfd signalfd4 sigpending sigprocmask sigreturn sigsuspend // Other needed POSIX alarm brk // (*) clock_adjtime clock_getres clock_gettime clock_nanosleep //clock_settime gettimeofday nanosleep nice sysinfo syslog time timer_create timer_delete timerfd_create timerfd_gettime timerfd_settime timer_getoverrun timer_gettime timer_settime times uname // (*) // Memory control madvise mbind mincore mlock mlockall mmap // (*) mmap2 mprotect // (*) mremap msync munlock munlockall munmap // (*) remap_file_pages set_mempolicy vmsplice // Process control capget capset // (*) clone // (*) execve // (*) exit // (*) exit_group // (*) fork getcpu getpgid getpgrp // (*) getpid // (*) getppid // (*) getpriority getresgid getresgid32 getresuid getresuid32 getrlimit // (*) getrusage getsid getuid // (*) getuid32 getegid // (*) getegid32 geteuid // (*) geteuid32 getgid // (*) getgid32 getgroups getgroups32 getitimer get_mempolicy kill //personality prctl prlimit64 sched_getaffinity sched_getparam sched_get_priority_max sched_get_priority_min sched_getscheduler sched_rr_get_interval //sched_setaffinity //sched_setparam //sched_setscheduler sched_yield setfsgid setfsgid32 setfsuid setfsuid32 setgid setgid32 setgroups setgroups32 setitimer setpgid // (*) setpriority setregid setregid32 setresgid setresgid32 setresuid setresuid32 setreuid setreuid32 setrlimit setsid setuid setuid32 ugetrlimit vfork wait4 // (*) waitid waitpid // IPC ipc mq_getsetattr mq_notify mq_open mq_timedreceive mq_timedsend mq_unlink msgctl msgget msgrcv msgsnd semctl semget semop semtimedop shmat shmctl shmdt shmget // Linux specific, mostly needed for thread-related stuff arch_prctl // (*) get_robust_list get_thread_area gettid futex // (*) restart_syscall // (*) set_robust_list // (*) set_thread_area set_tid_address // (*) tgkill tkill // Admin syscalls, these are blocked //acct //adjtimex //bdflush //chroot //create_module //delete_module //get_kernel_syms // Obsolete //idle // Obsolete //init_module //ioperm //iopl //ioprio_get //ioprio_set //kexec_load //lookup_dcookie // oprofile only? //migrate_pages // NUMA //modify_ldt //mount //move_pages // NUMA //name_to_handle_at // NFS server //nfsservctl // NFS server //open_by_handle_at // NFS server //perf_event_open //pivot_root //process_vm_readv // For debugger //process_vm_writev // For debugger //ptrace // For debugger //query_module //quotactl //reboot //setdomainname //setns //settimeofday //sgetmask // Obsolete //ssetmask // Obsolete //stime //swapoff //swapon //_sysctl //sysfs //sys_setaltroot //umount //umount2 //unshare //uselib //vhangup //vm86 //vm86old // Kernel key management //add_key //keyctl //request_key // Unimplemented //afs_syscall //break //ftime //getpmsg //gtty //lock //madvise1 //mpx //prof //profil //putpmsg //security //stty //tuxcall //ulimit //vserver ================================================ FILE: vendor/github.com/docker/docker/contrib/nuke-graph-directory.sh ================================================ #!/bin/sh set -e dir="$1" if [ -z "$dir" ]; then { echo 'This script is for destroying old /var/lib/docker directories more safely than' echo ' "rm -rf", which can cause data loss or other serious issues.' echo echo "usage: $0 directory" echo " ie: $0 /var/lib/docker" } >&2 exit 1 fi if [ "$(id -u)" != 0 ]; then echo >&2 "error: $0 must be run as root" exit 1 fi if [ ! -d "$dir" ]; then echo >&2 "error: $dir is not a directory" exit 1 fi dir="$(readlink -f "$dir")" echo echo "Nuking $dir ..." echo ' (if this is wrong, press Ctrl+C NOW!)' echo ( set -x; sleep 10 ) echo dir_in_dir() { inner="$1" outer="$2" [ "${inner#$outer}" != "$inner" ] } # let's start by unmounting any submounts in $dir # (like -v /home:... for example - DON'T DELETE MY HOME DIRECTORY BRU!) for mount in $(awk '{ print $5 }' /proc/self/mountinfo); do mount="$(readlink -f "$mount" || true)" if dir_in_dir "$mount" "$dir"; then ( set -x; umount -f "$mount" ) fi done # now, let's go destroy individual btrfs subvolumes, if any exist if command -v btrfs > /dev/null 2>&1; then root="$(df "$dir" | awk 'NR>1 { print $NF }')" root="${root#/}" # if root is "/", we want it to become "" for subvol in $(btrfs subvolume list -o "$root/" 2>/dev/null | awk -F' path ' '{ print $2 }' | sort -r); do subvolDir="$root/$subvol" if dir_in_dir "$subvolDir" "$dir"; then ( set -x; btrfs subvolume delete "$subvolDir" ) fi done fi # finally, DESTROY ALL THINGS ( set -x; rm -rf "$dir" ) ================================================ FILE: vendor/github.com/docker/docker/contrib/project-stats.sh ================================================ #!/usr/bin/env bash ## Run this script from the root of the docker repository ## to query project stats useful to the maintainers. ## You will need to install `pulls` and `issues` from ## https://github.com/crosbymichael/pulls set -e echo -n "Open pulls: " PULLS=$(pulls | wc -l); let PULLS=$PULLS-1 echo $PULLS echo -n "Pulls alru: " pulls alru echo -n "Open issues: " ISSUES=$(issues list | wc -l); let ISSUES=$ISSUES-1 echo $ISSUES echo -n "Issues alru: " issues alru ================================================ FILE: vendor/github.com/docker/docker/contrib/report-issue.sh ================================================ #!/bin/sh # This is a convenience script for reporting issues that include a base # template of information. See https://github.com/docker/docker/pull/8845 set -e DOCKER_ISSUE_URL=${DOCKER_ISSUE_URL:-"https://github.com/docker/docker/issues/new"} DOCKER_ISSUE_NAME_PREFIX=${DOCKER_ISSUE_NAME_PREFIX:-"Report: "} DOCKER=${DOCKER:-"docker"} DOCKER_COMMAND="${DOCKER}" export DOCKER_COMMAND # pulled from https://gist.github.com/cdown/1163649 function urlencode() { # urlencode local length="${#1}" for (( i = 0; i < length; i++ )); do local c="${1:i:1}" case $c in [a-zA-Z0-9.~_-]) printf "$c" ;; *) printf '%%%02X' "'$c" esac done } function template() { # this should always match the template from CONTRIBUTING.md cat <<- EOM Description of problem: \`docker version\`: `${DOCKER_COMMAND} -D version` \`docker info\`: `${DOCKER_COMMAND} -D info` \`uname -a\`: `uname -a` Environment details (AWS, VirtualBox, physical, etc.): How reproducible: Steps to Reproduce: 1. 2. 3. Actual Results: Expected Results: Additional info: EOM } function format_issue_url() { if [ ${#@} -ne 2 ] ; then return 1 fi local issue_name=$(urlencode "${DOCKER_ISSUE_NAME_PREFIX}${1}") local issue_body=$(urlencode "${2}") echo "${DOCKER_ISSUE_URL}?title=${issue_name}&body=${issue_body}" } echo -ne "Do you use \`sudo\` to call docker? [y|N]: " read -r -n 1 use_sudo echo "" if [ "x${use_sudo}" = "xy" -o "x${use_sudo}" = "xY" ]; then export DOCKER_COMMAND="sudo ${DOCKER}" fi echo -ne "Title of new issue?: " read -r issue_title echo "" issue_url=$(format_issue_url "${issue_title}" "$(template)") if which xdg-open 2>/dev/null >/dev/null ; then echo -ne "Would like to launch this report in your browser? [Y|n]: " read -r -n 1 launch_now echo "" if [ "${launch_now}" != "n" -a "${launch_now}" != "N" ]; then xdg-open "${issue_url}" fi fi echo "If you would like to manually open the url, you can open this link if your browser: ${issue_url}" ================================================ FILE: vendor/github.com/docker/docker/contrib/reprepro/suites.sh ================================================ #!/bin/bash set -e cd "$(dirname "$BASH_SOURCE")/../.." targets_from() { git fetch -q https://github.com/docker/docker.git "$1" git ls-tree -r --name-only origin/master contrib/builder/deb | grep '/Dockerfile$' | sed -r 's!^contrib/builder/deb/|-debootstrap|/Dockerfile$!!g' } { targets_from master; targets_from release; } | sort -u ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/kate/Dockerfile.xml ================================================ FROM MAINTAINER ENV RUN ONBUILD COPY ADD VOLUME EXPOSE ENTRYPOINT CMD WORKDIR USER LABEL ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/nano/Dockerfile.nanorc ================================================ ## Syntax highlighting for Dockerfiles syntax "Dockerfile" "Dockerfile[^/]*$" ## Keywords icolor red "^(FROM|MAINTAINER|RUN|CMD|LABEL|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ONBUILD)[[:space:]]" ## Brackets & parenthesis color brightgreen "(\(|\)|\[|\])" ## Double ampersand color brightmagenta "&&" ## Comments icolor cyan "^[[:space:]]*#.*$" ## Blank space at EOL color ,green "[[:space:]]+$" ## Strings, single-quoted color brightwhite "'([^']|(\\'))*'" "%[qw]\{[^}]*\}" "%[qw]\([^)]*\)" "%[qw]<[^>]*>" "%[qw]\[[^]]*\]" "%[qw]\$[^$]*\$" "%[qw]\^[^^]*\^" "%[qw]![^!]*!" ## Strings, double-quoted color brightwhite ""([^"]|(\\"))*"" "%[QW]?\{[^}]*\}" "%[QW]?\([^)]*\)" "%[QW]?<[^>]*>" "%[QW]?\[[^]]*\]" "%[QW]?\$[^$]*\$" "%[QW]?\^[^^]*\^" "%[QW]?![^!]*!" ## Single and double quotes color brightyellow "('|\")" ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/nano/README.md ================================================ Dockerfile.nanorc ================= Dockerfile syntax highlighting for nano Single User Installation ------------------------ 1. Create a nano syntax directory in your home directory: * `mkdir -p ~/.nano/syntax` 2. Copy `Dockerfile.nanorc` to` ~/.nano/syntax/` * `cp Dockerfile.nanorc ~/.nano/syntax/` 3. Add the following to your `~/.nanorc` to tell nano where to find the `Dockerfile.nanorc` file ``` ## Dockerfile files include "~/.nano/syntax/Dockerfile.nanorc" ``` System Wide Installation ------------------------ 1. Create a nano syntax directory: * `mkdir /usr/local/share/nano` 2. Copy `Dockerfile.nanorc` to `/usr/local/share/nano` * `cp Dockerfile.nanorc /usr/local/share/nano/` 3. Add the following to your `/etc/nanorc`: ``` ## Dockerfile files include "/usr/local/share/nano/Dockerfile.nanorc" ``` ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/textmate/Docker.tmbundle/Preferences/Dockerfile.tmPreferences ================================================ name Comments scope source.dockerfile settings shellVariables name TM_COMMENT_START value # uuid 2B215AC0-A7F3-4090-9FF6-F4842BD56CA7 ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/textmate/Docker.tmbundle/Syntaxes/Dockerfile.tmLanguage ================================================ fileTypes Dockerfile name Dockerfile patterns captures 1 name keyword.control.dockerfile 2 name keyword.other.special-method.dockerfile match ^\s*(?:(ONBUILD)\s+)?(FROM|MAINTAINER|RUN|EXPOSE|ENV|ADD|VOLUME|USER|WORKDIR|COPY|LABEL)\s captures 1 name keyword.operator.dockerfile 2 name keyword.other.special-method.dockerfile match ^\s*(?:(ONBUILD)\s+)?(CMD|ENTRYPOINT)\s begin " beginCaptures 1 name punctuation.definition.string.begin.dockerfile end " endCaptures 1 name punctuation.definition.string.end.dockerfile name string.quoted.double.dockerfile patterns match \\. name constant.character.escaped.dockerfile begin ' beginCaptures 1 name punctuation.definition.string.begin.dockerfile end ' endCaptures 1 name punctuation.definition.string.end.dockerfile name string.quoted.single.dockerfile patterns match \\. name constant.character.escaped.dockerfile captures 1 name punctuation.whitespace.comment.leading.dockerfile 2 name comment.line.number-sign.dockerfile 3 name punctuation.definition.comment.dockerfile comment comment.line match ^(\s*)((#).*$\n?) scopeName source.dockerfile uuid a39d8795-59d2-49af-aa00-fe74ee29576e ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/textmate/Docker.tmbundle/info.plist ================================================ contactEmailRot13 germ@andz.com.ar contactName GermanDZ description Helpers for Docker. name Docker uuid 8B9DDBAF-E65C-4E12-FFA7-467D4AA535B1 ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/textmate/README.md ================================================ # Docker.tmbundle Dockerfile syntax highlighting for TextMate and Sublime Text. ## Install ### Sublime Text Available for Sublime Text under [package control](https://sublime.wbond.net/packages/Dockerfile%20Syntax%20Highlighting). Search for *Dockerfile Syntax Highlighting* ### TextMate 2 You can install this bundle in TextMate by opening the preferences and going to the bundles tab. After installation it will be automatically updated for you. enjoy. ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/textmate/REVIEWERS ================================================ Asbjorn Enge (@asbjornenge) ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/vim/LICENSE ================================================ Copyright (c) 2013 Honza Pokorny 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. ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/vim/README.md ================================================ dockerfile.vim ============== Syntax highlighting for Dockerfiles Installation ------------ With [pathogen](https://github.com/tpope/vim-pathogen), the usual way... With [Vundle](https://github.com/gmarik/Vundle.vim) Plugin 'docker/docker' , {'rtp': '/contrib/syntax/vim/'} Features -------- The syntax highlighting includes: * The directives (e.g. `FROM`) * Strings * Comments License ------- BSD, short and sweet ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/vim/doc/dockerfile.txt ================================================ *dockerfile.txt* Syntax highlighting for Dockerfiles Author: Honza Pokorny License: BSD INSTALLATION *installation* Drop it on your Pathogen path and you're all set. FEATURES *features* The syntax highlighting includes: * The directives (e.g. FROM) * Strings * Comments vim:tw=78:et:ft=help:norl: ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/vim/ftdetect/dockerfile.vim ================================================ au BufNewFile,BufRead [Dd]ockerfile,Dockerfile.* set filetype=dockerfile ================================================ FILE: vendor/github.com/docker/docker/contrib/syntax/vim/syntax/dockerfile.vim ================================================ " dockerfile.vim - Syntax highlighting for Dockerfiles " Maintainer: Honza Pokorny " Version: 0.5 if exists("b:current_syntax") finish endif let b:current_syntax = "dockerfile" syntax case ignore syntax match dockerfileKeyword /\v^\s*(ONBUILD\s+)?(ADD|CMD|ENTRYPOINT|ENV|EXPOSE|FROM|MAINTAINER|RUN|USER|LABEL|VOLUME|WORKDIR|COPY)\s/ highlight link dockerfileKeyword Keyword syntax region dockerfileString start=/\v"/ skip=/\v\\./ end=/\v"/ highlight link dockerfileString String syntax match dockerfileComment "\v^\s*#.*$" highlight link dockerfileComment Comment set commentstring=#\ %s " match "RUN", "CMD", and "ENTRYPOINT" lines, and parse them as shell let s:current_syntax = b:current_syntax unlet b:current_syntax syntax include @SH syntax/sh.vim let b:current_syntax = s:current_syntax syntax region shLine matchgroup=dockerfileKeyword start=/\v^\s*(RUN|CMD|ENTRYPOINT)\s/ end=/\v$/ contains=@SH " since @SH will handle "\" as part of the same line automatically, this "just works" for line continuation too, but with the caveat that it will highlight "RUN echo '" followed by a newline as if it were a block because the "'" is shell line continuation... not sure how to fix that just yet (TODO) ================================================ FILE: vendor/github.com/docker/docker/contrib/udev/80-docker.rules ================================================ # hide docker's loopback devices from udisks, and thus from user desktops SUBSYSTEM=="block", ENV{DM_NAME}=="docker-*", ENV{UDISKS_PRESENTATION_HIDE}="1", ENV{UDISKS_IGNORE}="1" SUBSYSTEM=="block", DEVPATH=="/devices/virtual/block/loop*", ATTR{loop/backing_file}=="/var/lib/docker/*", ENV{UDISKS_PRESENTATION_HIDE}="1", ENV{UDISKS_IGNORE}="1" ================================================ FILE: vendor/github.com/docker/docker/contrib/vagrant-docker/README.md ================================================ # Vagrant integration Currently there are at least 4 different projects that we are aware of that deals with integration with [Vagrant](http://vagrantup.com/) at different levels. One approach is to use Docker as a [provisioner](http://docs.vagrantup.com/v2/provisioning/index.html) which means you can create containers and pull base images on VMs using Docker's CLI and the other is to use Docker as a [provider](http://docs.vagrantup.com/v2/providers/index.html), meaning you can use Vagrant to control Docker containers. ### Provisioners * [Vocker](https://github.com/fgrehm/vocker) * [Ventriloquist](https://github.com/fgrehm/ventriloquist) ### Providers * [docker-provider](https://github.com/fgrehm/docker-provider) * [vagrant-shell](https://github.com/destructuring/vagrant-shell) ## Setting up Vagrant-docker with the Remote API The initial Docker upstart script will not work because it runs on `127.0.0.1`, which is not accessible to the host machine. Instead, we need to change the script to connect to `0.0.0.0`. To do this, modify `/etc/init/docker.conf` to look like this: ``` description "Docker daemon" start on filesystem and started lxc-net stop on runlevel [!2345] respawn script /usr/bin/docker -d -H=tcp://0.0.0.0:2375 end script ``` Once that's done, you need to set up a SSH tunnel between your host machine and the vagrant machine that's running Docker. This can be done by running the following command in a host terminal: ``` ssh -L 2375:localhost:2375 -p 2222 vagrant@localhost ``` (The first 2375 is what your host can connect to, the second 2375 is what port Docker is running on in the vagrant machine, and the 2222 is the port Vagrant is providing for SSH. If VirtualBox is the VM you're using, you can see what value "2222" should be by going to: Network > Adapter 1 > Advanced > Port Forwarding in the VirtualBox GUI.) Note that because the port has been changed, to run docker commands from within the command line you must run them like this: ``` sudo docker -H 0.0.0.0:2375 < commands for docker > ``` ================================================ FILE: vendor/github.com/docker/docker/daemon/README.md ================================================ This directory contains code pertaining to running containers and storing images Code pertaining to running containers: - execdriver - networkdriver Code pertaining to storing images: - graphdriver ================================================ FILE: vendor/github.com/docker/docker/daemon/archive.go ================================================ package daemon import ( "errors" "io" "os" "path/filepath" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/ioutils" ) // ErrExtractPointNotDirectory is used to convey that the operation to extract // a tar archive to a directory in a container has failed because the specified // path does not refer to a directory. var ErrExtractPointNotDirectory = errors.New("extraction point is not a directory") // ContainerCopy performs a depracated operation of archiving the resource at // the specified path in the conatiner identified by the given name. func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, error) { container, err := daemon.Get(name) if err != nil { return nil, err } if res[0] == '/' { res = res[1:] } return container.Copy(res) } // ContainerStatPath stats the filesystem resource at the specified path in the // container identified by the given name. func (daemon *Daemon) ContainerStatPath(name string, path string) (stat *types.ContainerPathStat, err error) { container, err := daemon.Get(name) if err != nil { return nil, err } return container.StatPath(path) } // ContainerArchivePath creates an archive of the filesystem resource at the // specified path in the container identified by the given name. Returns a // tar archive of the resource and whether it was a directory or a single file. func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) { container, err := daemon.Get(name) if err != nil { return nil, nil, err } return container.ArchivePath(path) } // ContainerExtractToDir extracts the given archive to the specified location // in the filesystem of the container identified by the given name. The given // path must be of a directory in the container. If it is not, the error will // be ErrExtractPointNotDirectory. If noOverwriteDirNonDir is true then it will // be an error if unpacking the given content would cause an existing directory // to be replaced with a non-directory and vice versa. func (daemon *Daemon) ContainerExtractToDir(name, path string, noOverwriteDirNonDir bool, content io.Reader) error { container, err := daemon.Get(name) if err != nil { return err } return container.ExtractToDir(path, noOverwriteDirNonDir, content) } // StatPath stats the filesystem resource at the specified path in this // container. Returns stat info about the resource. func (container *Container) StatPath(path string) (stat *types.ContainerPathStat, err error) { container.Lock() defer container.Unlock() if err = container.Mount(); err != nil { return nil, err } defer container.Unmount() err = container.mountVolumes() defer container.UnmountVolumes(true) if err != nil { return nil, err } // Consider the given path as an absolute path in the container. absPath := path if !filepath.IsAbs(absPath) { absPath = archive.PreserveTrailingDotOrSeparator(filepath.Join("/", path), path) } resolvedPath, err := container.GetResourcePath(absPath) if err != nil { return nil, err } // A trailing "." or separator has important meaning. For example, if // `"foo"` is a symlink to some directory `"dir"`, then `os.Lstat("foo")` // will stat the link itself, while `os.Lstat("foo/")` will stat the link // target. If the basename of the path is ".", it means to archive the // contents of the directory with "." as the first path component rather // than the name of the directory. This would cause extraction of the // archive to *not* make another directory, but instead use the current // directory. resolvedPath = archive.PreserveTrailingDotOrSeparator(resolvedPath, absPath) lstat, err := os.Lstat(resolvedPath) if err != nil { return nil, err } return &types.ContainerPathStat{ Name: lstat.Name(), Path: absPath, Size: lstat.Size(), Mode: lstat.Mode(), Mtime: lstat.ModTime(), }, nil } // ArchivePath creates an archive of the filesystem resource at the specified // path in this container. Returns a tar archive of the resource and stat info // about the resource. func (container *Container) ArchivePath(path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error) { container.Lock() defer func() { if err != nil { // Wait to unlock the container until the archive is fully read // (see the ReadCloseWrapper func below) or if there is an error // before that occurs. container.Unlock() } }() if err = container.Mount(); err != nil { return nil, nil, err } defer func() { if err != nil { // unmount any volumes container.UnmountVolumes(true) // unmount the container's rootfs container.Unmount() } }() if err = container.mountVolumes(); err != nil { return nil, nil, err } // Consider the given path as an absolute path in the container. absPath := path if !filepath.IsAbs(absPath) { absPath = archive.PreserveTrailingDotOrSeparator(filepath.Join("/", path), path) } resolvedPath, err := container.GetResourcePath(absPath) if err != nil { return nil, nil, err } // A trailing "." or separator has important meaning. For example, if // `"foo"` is a symlink to some directory `"dir"`, then `os.Lstat("foo")` // will stat the link itself, while `os.Lstat("foo/")` will stat the link // target. If the basename of the path is ".", it means to archive the // contents of the directory with "." as the first path component rather // than the name of the directory. This would cause extraction of the // archive to *not* make another directory, but instead use the current // directory. resolvedPath = archive.PreserveTrailingDotOrSeparator(resolvedPath, absPath) lstat, err := os.Lstat(resolvedPath) if err != nil { return nil, nil, err } stat = &types.ContainerPathStat{ Name: lstat.Name(), Path: absPath, Size: lstat.Size(), Mode: lstat.Mode(), Mtime: lstat.ModTime(), } data, err := archive.TarResource(resolvedPath) if err != nil { return nil, nil, err } content = ioutils.NewReadCloserWrapper(data, func() error { err := data.Close() container.UnmountVolumes(true) container.Unmount() container.Unlock() return err }) container.LogEvent("archive-path") return content, stat, nil } // ExtractToDir extracts the given tar archive to the specified location in the // filesystem of this container. The given path must be of a directory in the // container. If it is not, the error will be ErrExtractPointNotDirectory. If // noOverwriteDirNonDir is true then it will be an error if unpacking the // given content would cause an existing directory to be replaced with a non- // directory and vice versa. func (container *Container) ExtractToDir(path string, noOverwriteDirNonDir bool, content io.Reader) (err error) { container.Lock() defer container.Unlock() if err = container.Mount(); err != nil { return err } defer container.Unmount() err = container.mountVolumes() defer container.UnmountVolumes(true) if err != nil { return err } // Consider the given path as an absolute path in the container. absPath := path if !filepath.IsAbs(absPath) { absPath = archive.PreserveTrailingDotOrSeparator(filepath.Join("/", path), path) } resolvedPath, err := container.GetResourcePath(absPath) if err != nil { return err } // A trailing "." or separator has important meaning. For example, if // `"foo"` is a symlink to some directory `"dir"`, then `os.Lstat("foo")` // will stat the link itself, while `os.Lstat("foo/")` will stat the link // target. If the basename of the path is ".", it means to archive the // contents of the directory with "." as the first path component rather // than the name of the directory. This would cause extraction of the // archive to *not* make another directory, but instead use the current // directory. resolvedPath = archive.PreserveTrailingDotOrSeparator(resolvedPath, absPath) stat, err := os.Lstat(resolvedPath) if err != nil { return err } if !stat.IsDir() { return ErrExtractPointNotDirectory } baseRel, err := filepath.Rel(container.basefs, resolvedPath) if err != nil { return err } absPath = filepath.Join("/", baseRel) // Need to check if the path is in a volume. If it is, it cannot be in a // read-only volume. If it is not in a volume, the container cannot be // configured with a read-only rootfs. var toVolume bool for _, mnt := range container.MountPoints { if toVolume = mnt.hasResource(absPath); toVolume { if mnt.RW { break } return ErrVolumeReadonly } } if !toVolume && container.hostConfig.ReadonlyRootfs { return ErrContainerRootfsReadonly } options := &archive.TarOptions{ ChownOpts: &archive.TarChownOptions{ UID: 0, GID: 0, // TODO: use config.User? Remap to userns root? }, NoOverwriteDirNonDir: noOverwriteDirNonDir, } if err := chrootarchive.Untar(content, resolvedPath, options); err != nil { return err } container.LogEvent("extract-to-dir") return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/attach.go ================================================ package daemon import ( "io" "github.com/docker/docker/pkg/stdcopy" ) type ContainerAttachWithLogsConfig struct { InStream io.ReadCloser OutStream io.Writer UseStdin, UseStdout, UseStderr bool Logs, Stream bool } func (daemon *Daemon) ContainerAttachWithLogs(container *Container, c *ContainerAttachWithLogsConfig) error { var errStream io.Writer if !container.Config.Tty { errStream = stdcopy.NewStdWriter(c.OutStream, stdcopy.Stderr) c.OutStream = stdcopy.NewStdWriter(c.OutStream, stdcopy.Stdout) } else { errStream = c.OutStream } var stdin io.ReadCloser var stdout, stderr io.Writer if c.UseStdin { stdin = c.InStream } if c.UseStdout { stdout = c.OutStream } if c.UseStderr { stderr = errStream } return container.AttachWithLogs(stdin, stdout, stderr, c.Logs, c.Stream) } type ContainerWsAttachWithLogsConfig struct { InStream io.ReadCloser OutStream, ErrStream io.Writer Logs, Stream bool } func (daemon *Daemon) ContainerWsAttachWithLogs(container *Container, c *ContainerWsAttachWithLogsConfig) error { return container.AttachWithLogs(c.InStream, c.OutStream, c.ErrStream, c.Logs, c.Stream) } ================================================ FILE: vendor/github.com/docker/docker/daemon/changes.go ================================================ package daemon import "github.com/docker/docker/pkg/archive" // ContainerChanges returns a list of container fs changes func (daemon *Daemon) ContainerChanges(name string) ([]archive.Change, error) { container, err := daemon.Get(name) if err != nil { return nil, err } return container.Changes() } ================================================ FILE: vendor/github.com/docker/docker/daemon/commit.go ================================================ package daemon import ( "github.com/docker/docker/image" "github.com/docker/docker/runconfig" ) type ContainerCommitConfig struct { Pause bool Repo string Tag string Author string Comment string Config *runconfig.Config } // Commit creates a new filesystem image from the current state of a container. // The image can optionally be tagged into a repository func (daemon *Daemon) Commit(container *Container, c *ContainerCommitConfig) (*image.Image, error) { if c.Pause && !container.IsPaused() { container.Pause() defer container.Unpause() } rwTar, err := container.ExportRw() if err != nil { return nil, err } defer func() { if rwTar != nil { rwTar.Close() } }() // Create a new image from the container's base layers + a new layer from container changes var ( containerID, parentImageID string containerConfig *runconfig.Config ) if container != nil { containerID = container.ID parentImageID = container.ImageID containerConfig = container.Config } img, err := daemon.graph.Create(rwTar, containerID, parentImageID, c.Comment, c.Author, containerConfig, c.Config) if err != nil { return nil, err } // Register the image if needed if c.Repo != "" { if err := daemon.repositories.Tag(c.Repo, c.Tag, img.ID, true); err != nil { return img, err } } container.LogEvent("commit") return img, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/config.go ================================================ package daemon import ( "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/runconfig" ) const ( defaultNetworkMtu = 1500 disableNetworkBridge = "none" ) // CommonConfig defines the configuration of a docker daemon which are // common across platforms. type CommonConfig struct { AutoRestart bool Bridge bridgeConfig // Bridge holds bridge network specific configuration. Context map[string][]string CorsHeaders string DisableBridge bool Dns []string DnsSearch []string EnableCors bool ExecDriver string ExecOptions []string ExecRoot string GraphDriver string GraphOptions []string Labels []string LogConfig runconfig.LogConfig Mtu int Pidfile string Root string TrustKeyPath string DefaultNetwork string NetworkKVStore string } // InstallCommonFlags adds command-line options to the top-level flag parser for // the current process. // Subsequent calls to `flag.Parse` will populate config with values parsed // from the command-line. func (config *Config) InstallCommonFlags() { opts.ListVar(&config.GraphOptions, []string{"-storage-opt"}, "Set storage driver options") opts.ListVar(&config.ExecOptions, []string{"-exec-opt"}, "Set exec driver options") flag.StringVar(&config.Pidfile, []string{"p", "-pidfile"}, defaultPidFile, "Path to use for daemon PID file") flag.StringVar(&config.Root, []string{"g", "-graph"}, defaultGraph, "Root of the Docker runtime") flag.StringVar(&config.ExecRoot, []string{"-exec-root"}, "/var/run/docker", "Root of the Docker execdriver") flag.BoolVar(&config.AutoRestart, []string{"#r", "#-restart"}, true, "--restart on the daemon has been deprecated in favor of --restart policies on docker run") flag.StringVar(&config.GraphDriver, []string{"s", "-storage-driver"}, "", "Storage driver to use") flag.StringVar(&config.ExecDriver, []string{"e", "-exec-driver"}, defaultExec, "Exec driver to use") flag.IntVar(&config.Mtu, []string{"#mtu", "-mtu"}, 0, "Set the containers network MTU") flag.BoolVar(&config.EnableCors, []string{"#api-enable-cors", "#-api-enable-cors"}, false, "Enable CORS headers in the remote API, this is deprecated by --api-cors-header") flag.StringVar(&config.CorsHeaders, []string{"-api-cors-header"}, "", "Set CORS headers in the remote API") // FIXME: why the inconsistency between "hosts" and "sockets"? opts.IPListVar(&config.Dns, []string{"#dns", "-dns"}, "DNS server to use") opts.DNSSearchListVar(&config.DnsSearch, []string{"-dns-search"}, "DNS search domains to use") opts.LabelListVar(&config.Labels, []string{"-label"}, "Set key=value labels to the daemon") flag.StringVar(&config.LogConfig.Type, []string{"-log-driver"}, "json-file", "Default driver for container logs") opts.LogOptsVar(config.LogConfig.Config, []string{"-log-opt"}, "Set log driver options") } ================================================ FILE: vendor/github.com/docker/docker/daemon/config_experimental.go ================================================ // +build experimental package daemon import flag "github.com/docker/docker/pkg/mflag" func (config *Config) attachExperimentalFlags() { flag.StringVar(&config.DefaultNetwork, []string{"-default-network"}, "", "Set default network") flag.StringVar(&config.NetworkKVStore, []string{"-kv-store"}, "", "Set KV Store configuration") } ================================================ FILE: vendor/github.com/docker/docker/daemon/config_linux.go ================================================ package daemon import ( "net" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/ulimit" ) var ( defaultPidFile = "/var/run/docker.pid" defaultGraph = "/var/lib/docker" defaultExec = "native" ) // Config defines the configuration of a docker daemon. // These are the configuration settings that you pass // to the docker daemon when you launch it with say: `docker -d -e lxc` type Config struct { CommonConfig // Fields below here are platform specific. EnableSelinuxSupport bool SocketGroup string Ulimits map[string]*ulimit.Ulimit } // bridgeConfig stores all the bridge driver specific // configuration. type bridgeConfig struct { EnableIPv6 bool EnableIPTables bool EnableIPForward bool EnableIPMasq bool EnableUserlandProxy bool DefaultIP net.IP Iface string IP string FixedCIDR string FixedCIDRv6 string DefaultGatewayIPv4 net.IP DefaultGatewayIPv6 net.IP InterContainerCommunication bool } // InstallFlags adds command-line options to the top-level flag parser for // the current process. // Subsequent calls to `flag.Parse` will populate config with values parsed // from the command-line. func (config *Config) InstallFlags() { // First handle install flags which are consistent cross-platform config.InstallCommonFlags() // Then platform-specific install flags flag.BoolVar(&config.EnableSelinuxSupport, []string{"-selinux-enabled"}, false, "Enable selinux support") flag.StringVar(&config.SocketGroup, []string{"G", "-group"}, "docker", "Group for the unix socket") config.Ulimits = make(map[string]*ulimit.Ulimit) opts.UlimitMapVar(config.Ulimits, []string{"-default-ulimit"}, "Set default ulimits for containers") flag.BoolVar(&config.Bridge.EnableIPTables, []string{"#iptables", "-iptables"}, true, "Enable addition of iptables rules") flag.BoolVar(&config.Bridge.EnableIPForward, []string{"#ip-forward", "-ip-forward"}, true, "Enable net.ipv4.ip_forward") flag.BoolVar(&config.Bridge.EnableIPMasq, []string{"-ip-masq"}, true, "Enable IP masquerading") flag.BoolVar(&config.Bridge.EnableIPv6, []string{"-ipv6"}, false, "Enable IPv6 networking") flag.StringVar(&config.Bridge.IP, []string{"#bip", "-bip"}, "", "Specify network bridge IP") flag.StringVar(&config.Bridge.Iface, []string{"b", "-bridge"}, "", "Attach containers to a network bridge") flag.StringVar(&config.Bridge.FixedCIDR, []string{"-fixed-cidr"}, "", "IPv4 subnet for fixed IPs") flag.StringVar(&config.Bridge.FixedCIDRv6, []string{"-fixed-cidr-v6"}, "", "IPv6 subnet for fixed IPs") opts.IPVar(&config.Bridge.DefaultGatewayIPv4, []string{"-default-gateway"}, "", "Container default gateway IPv4 address") opts.IPVar(&config.Bridge.DefaultGatewayIPv6, []string{"-default-gateway-v6"}, "", "Container default gateway IPv6 address") flag.BoolVar(&config.Bridge.InterContainerCommunication, []string{"#icc", "-icc"}, true, "Enable inter-container communication") opts.IPVar(&config.Bridge.DefaultIP, []string{"#ip", "-ip"}, "0.0.0.0", "Default IP when binding container ports") flag.BoolVar(&config.Bridge.EnableUserlandProxy, []string{"-userland-proxy"}, true, "Use userland proxy for loopback traffic") config.attachExperimentalFlags() } ================================================ FILE: vendor/github.com/docker/docker/daemon/config_stub.go ================================================ // +build !experimental package daemon func (config *Config) attachExperimentalFlags() { } ================================================ FILE: vendor/github.com/docker/docker/daemon/config_windows.go ================================================ package daemon import ( "os" flag "github.com/docker/docker/pkg/mflag" ) var ( defaultPidFile = os.Getenv("programdata") + string(os.PathSeparator) + "docker.pid" defaultGraph = os.Getenv("programdata") + string(os.PathSeparator) + "docker" defaultExec = "windows" ) // bridgeConfig stores all the bridge driver specific // configuration. type bridgeConfig struct { VirtualSwitchName string } // Config defines the configuration of a docker daemon. // These are the configuration settings that you pass // to the docker daemon when you launch it with say: `docker -d -e windows` type Config struct { CommonConfig // Fields below here are platform specific. (There are none presently // for the Windows daemon.) } // InstallFlags adds command-line options to the top-level flag parser for // the current process. // Subsequent calls to `flag.Parse` will populate config with values parsed // from the command-line. func (config *Config) InstallFlags() { // First handle install flags which are consistent cross-platform config.InstallCommonFlags() // Then platform-specific install flags. flag.StringVar(&config.Bridge.VirtualSwitchName, []string{"b", "-bridge"}, "", "Attach containers to a virtual switch") } ================================================ FILE: vendor/github.com/docker/docker/daemon/container.go ================================================ package daemon import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "sync" "syscall" "time" "github.com/opencontainers/runc/libcontainer/label" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/jsonfilelog" "github.com/docker/docker/daemon/network" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/broadcastwriter" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/jsonlog" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/symlink" "github.com/docker/docker/runconfig" "github.com/docker/docker/volume" ) var ( ErrNotATTY = errors.New("The PTY is not a file") ErrNoTTY = errors.New("No PTY found") ErrContainerStart = errors.New("The container failed to start. Unknown error") ErrContainerStartTimeout = errors.New("The container failed to start due to timed out.") ErrContainerRootfsReadonly = errors.New("container rootfs is marked read-only") ) type StreamConfig struct { stdout *broadcastwriter.BroadcastWriter stderr *broadcastwriter.BroadcastWriter stdin io.ReadCloser stdinPipe io.WriteCloser } // CommonContainer holds the settings for a container which are applicable // across all platforms supported by the daemon. type CommonContainer struct { StreamConfig *State `json:"State"` // Needed for remote api version <= 1.11 root string // Path to the "home" of the container, including metadata. basefs string // Path to the graphdriver mountpoint ID string Created time.Time Path string Args []string Config *runconfig.Config ImageID string `json:"Image"` NetworkSettings *network.Settings ResolvConfPath string HostnamePath string HostsPath string LogPath string Name string Driver string ExecDriver string MountLabel, ProcessLabel string RestartCount int UpdateDns bool HasBeenStartedBefore bool MountPoints map[string]*mountPoint Volumes map[string]string // Deprecated since 1.7, kept for backwards compatibility VolumesRW map[string]bool // Deprecated since 1.7, kept for backwards compatibility hostConfig *runconfig.HostConfig command *execdriver.Command monitor *containerMonitor execCommands *execStore daemon *Daemon // logDriver for closing logDriver logger.Logger logCopier *logger.Copier } func (container *Container) FromDisk() error { pth, err := container.jsonPath() if err != nil { return err } jsonSource, err := os.Open(pth) if err != nil { return err } defer jsonSource.Close() dec := json.NewDecoder(jsonSource) // Load container settings // udp broke compat of docker.PortMapping, but it's not used when loading a container, we can skip it if err := dec.Decode(container); err != nil && !strings.Contains(err.Error(), "docker.PortMapping") { return err } if err := label.ReserveLabel(container.ProcessLabel); err != nil { return err } return container.readHostConfig() } func (container *Container) toDisk() error { data, err := json.Marshal(container) if err != nil { return err } pth, err := container.jsonPath() if err != nil { return err } if err := ioutil.WriteFile(pth, data, 0666); err != nil { return err } return container.WriteHostConfig() } func (container *Container) ToDisk() error { container.Lock() err := container.toDisk() container.Unlock() return err } func (container *Container) readHostConfig() error { container.hostConfig = &runconfig.HostConfig{} // If the hostconfig file does not exist, do not read it. // (We still have to initialize container.hostConfig, // but that's OK, since we just did that above.) pth, err := container.hostConfigPath() if err != nil { return err } _, err = os.Stat(pth) if os.IsNotExist(err) { return nil } f, err := os.Open(pth) if err != nil { return err } defer f.Close() return json.NewDecoder(f).Decode(&container.hostConfig) } func (container *Container) WriteHostConfig() error { data, err := json.Marshal(container.hostConfig) if err != nil { return err } pth, err := container.hostConfigPath() if err != nil { return err } return ioutil.WriteFile(pth, data, 0666) } func (container *Container) LogEvent(action string) { d := container.daemon d.EventsService.Log( action, container.ID, container.Config.Image, ) } // Evaluates `path` in the scope of the container's basefs, with proper path // sanitisation. Symlinks are all scoped to the basefs of the container, as // though the container's basefs was `/`. // // The basefs of a container is the host-facing path which is bind-mounted as // `/` inside the container. This method is essentially used to access a // particular path inside the container as though you were a process in that // container. // // NOTE: The returned path is *only* safely scoped inside the container's basefs // if no component of the returned path changes (such as a component // symlinking to a different path) between using this method and using the // path. See symlink.FollowSymlinkInScope for more details. func (container *Container) GetResourcePath(path string) (string, error) { // IMPORTANT - These are paths on the OS where the daemon is running, hence // any filepath operations must be done in an OS agnostic way. cleanPath := filepath.Join(string(os.PathSeparator), path) r, e := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, cleanPath), container.basefs) return r, e } // Evaluates `path` in the scope of the container's root, with proper path // sanitisation. Symlinks are all scoped to the root of the container, as // though the container's root was `/`. // // The root of a container is the host-facing configuration metadata directory. // Only use this method to safely access the container's `container.json` or // other metadata files. If in doubt, use container.GetResourcePath. // // NOTE: The returned path is *only* safely scoped inside the container's root // if no component of the returned path changes (such as a component // symlinking to a different path) between using this method and using the // path. See symlink.FollowSymlinkInScope for more details. func (container *Container) GetRootResourcePath(path string) (string, error) { // IMPORTANT - These are paths on the OS where the daemon is running, hence // any filepath operations must be done in an OS agnostic way. cleanPath := filepath.Join(string(os.PathSeparator), path) return symlink.FollowSymlinkInScope(filepath.Join(container.root, cleanPath), container.root) } func (container *Container) Start() (err error) { container.Lock() defer container.Unlock() if container.Running { return nil } if container.removalInProgress || container.Dead { return fmt.Errorf("Container is marked for removal and cannot be started.") } // if we encounter an error during start we need to ensure that any other // setup has been cleaned up properly defer func() { if err != nil { container.setError(err) // if no one else has set it, make sure we don't leave it at zero if container.ExitCode == 0 { container.ExitCode = 128 } container.toDisk() container.cleanup() container.LogEvent("die") } }() if err := container.Mount(); err != nil { return err } // No-op if non-Windows. Once the container filesystem is mounted, // prepare the layer to boot using the Windows driver. if err := container.PrepareStorage(); err != nil { return err } if err := container.initializeNetworking(); err != nil { return err } linkedEnv, err := container.setupLinkedContainers() if err != nil { return err } if err := container.setupWorkingDirectory(); err != nil { return err } env := container.createDaemonEnvironment(linkedEnv) if err := populateCommand(container, env); err != nil { return err } mounts, err := container.setupMounts() if err != nil { return err } container.command.Mounts = mounts return container.waitForStart() } func (container *Container) Run() error { if err := container.Start(); err != nil { return err } container.HasBeenStartedBefore = true container.WaitStop(-1 * time.Second) return nil } func (container *Container) Output() (output []byte, err error) { pipe := container.StdoutPipe() defer pipe.Close() if err := container.Start(); err != nil { return nil, err } output, err = ioutil.ReadAll(pipe) container.WaitStop(-1 * time.Second) return output, err } // StreamConfig.StdinPipe returns a WriteCloser which can be used to feed data // to the standard input of the container's active process. // Container.StdoutPipe and Container.StderrPipe each return a ReadCloser // which can be used to retrieve the standard output (and error) generated // by the container's active process. The output (and error) are actually // copied and delivered to all StdoutPipe and StderrPipe consumers, using // a kind of "broadcaster". func (streamConfig *StreamConfig) StdinPipe() io.WriteCloser { return streamConfig.stdinPipe } func (streamConfig *StreamConfig) StdoutPipe() io.ReadCloser { reader, writer := io.Pipe() streamConfig.stdout.AddWriter(writer, "") return ioutils.NewBufReader(reader) } func (streamConfig *StreamConfig) StderrPipe() io.ReadCloser { reader, writer := io.Pipe() streamConfig.stderr.AddWriter(writer, "") return ioutils.NewBufReader(reader) } func (streamConfig *StreamConfig) StdoutLogPipe() io.ReadCloser { reader, writer := io.Pipe() streamConfig.stdout.AddWriter(writer, "stdout") return ioutils.NewBufReader(reader) } func (streamConfig *StreamConfig) StderrLogPipe() io.ReadCloser { reader, writer := io.Pipe() streamConfig.stderr.AddWriter(writer, "stderr") return ioutils.NewBufReader(reader) } func (container *Container) isNetworkAllocated() bool { return container.NetworkSettings.IPAddress != "" } // cleanup releases any network resources allocated to the container along with any rules // around how containers are linked together. It also unmounts the container's root filesystem. func (container *Container) cleanup() { container.ReleaseNetwork() disableAllActiveLinks(container) if err := container.CleanupStorage(); err != nil { logrus.Errorf("%v: Failed to cleanup storage: %v", container.ID, err) } if err := container.Unmount(); err != nil { logrus.Errorf("%v: Failed to umount filesystem: %v", container.ID, err) } for _, eConfig := range container.execCommands.s { container.daemon.unregisterExecCommand(eConfig) } container.UnmountVolumes(false) } func (container *Container) KillSig(sig int) error { logrus.Debugf("Sending %d to %s", sig, container.ID) container.Lock() defer container.Unlock() // We could unpause the container for them rather than returning this error if container.Paused { return fmt.Errorf("Container %s is paused. Unpause the container before stopping", container.ID) } if !container.Running { return fmt.Errorf("Container %s is not running", container.ID) } // signal to the monitor that it should not restart the container // after we send the kill signal container.monitor.ExitOnNext() // if the container is currently restarting we do not need to send the signal // to the process. Telling the monitor that it should exit on it's next event // loop is enough if container.Restarting { return nil } if err := container.daemon.Kill(container, sig); err != nil { return err } container.LogEvent("kill") return nil } // Wrapper aroung KillSig() suppressing "no such process" error. func (container *Container) killPossiblyDeadProcess(sig int) error { err := container.KillSig(sig) if err == syscall.ESRCH { logrus.Debugf("Cannot kill process (pid=%d) with signal %d: no such process.", container.GetPid(), sig) return nil } return err } func (container *Container) Pause() error { container.Lock() defer container.Unlock() // We cannot Pause the container which is not running if !container.Running { return fmt.Errorf("Container %s is not running, cannot pause a non-running container", container.ID) } // We cannot Pause the container which is already paused if container.Paused { return fmt.Errorf("Container %s is already paused", container.ID) } if err := container.daemon.execDriver.Pause(container.command); err != nil { return err } container.Paused = true container.LogEvent("pause") return nil } func (container *Container) Unpause() error { container.Lock() defer container.Unlock() // We cannot unpause the container which is not running if !container.Running { return fmt.Errorf("Container %s is not running, cannot unpause a non-running container", container.ID) } // We cannot unpause the container which is not paused if !container.Paused { return fmt.Errorf("Container %s is not paused", container.ID) } if err := container.daemon.execDriver.Unpause(container.command); err != nil { return err } container.Paused = false container.LogEvent("unpause") return nil } func (container *Container) Kill() error { if !container.IsRunning() { return fmt.Errorf("Container %s is not running", container.ID) } // 1. Send SIGKILL if err := container.killPossiblyDeadProcess(9); err != nil { // While normally we might "return err" here we're not going to // because if we can't stop the container by this point then // its probably because its already stopped. Meaning, between // the time of the IsRunning() call above and now it stopped. // Also, since the err return will be exec driver specific we can't // look for any particular (common) error that would indicate // that the process is already dead vs something else going wrong. // So, instead we'll give it up to 2 more seconds to complete and if // by that time the container is still running, then the error // we got is probably valid and so we return it to the caller. if container.IsRunning() { container.WaitStop(2 * time.Second) if container.IsRunning() { return err } } } // 2. Wait for the process to die, in last resort, try to kill the process directly if err := killProcessDirectly(container); err != nil { return err } container.WaitStop(-1 * time.Second) return nil } func (container *Container) Stop(seconds int) error { if !container.IsRunning() { return nil } // 1. Send a SIGTERM if err := container.killPossiblyDeadProcess(15); err != nil { logrus.Infof("Failed to send SIGTERM to the process, force killing") if err := container.killPossiblyDeadProcess(9); err != nil { return err } } // 2. Wait for the process to exit on its own if _, err := container.WaitStop(time.Duration(seconds) * time.Second); err != nil { logrus.Infof("Container %v failed to exit within %d seconds of SIGTERM - using the force", container.ID, seconds) // 3. If it doesn't, then send SIGKILL if err := container.Kill(); err != nil { container.WaitStop(-1 * time.Second) return err } } container.LogEvent("stop") return nil } func (container *Container) Restart(seconds int) error { // Avoid unnecessarily unmounting and then directly mounting // the container when the container stops and then starts // again if err := container.Mount(); err == nil { defer container.Unmount() } if err := container.Stop(seconds); err != nil { return err } if err := container.Start(); err != nil { return err } container.LogEvent("restart") return nil } func (container *Container) Resize(h, w int) error { if !container.IsRunning() { return fmt.Errorf("Cannot resize container %s, container is not running", container.ID) } if err := container.command.ProcessConfig.Terminal.Resize(h, w); err != nil { return err } container.LogEvent("resize") return nil } func (container *Container) Export() (archive.Archive, error) { if err := container.Mount(); err != nil { return nil, err } archive, err := archive.Tar(container.basefs, archive.Uncompressed) if err != nil { container.Unmount() return nil, err } arch := ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() container.Unmount() return err }) container.LogEvent("export") return arch, err } func (container *Container) Mount() error { return container.daemon.Mount(container) } func (container *Container) changes() ([]archive.Change, error) { return container.daemon.Changes(container) } func (container *Container) Changes() ([]archive.Change, error) { container.Lock() defer container.Unlock() return container.changes() } func (container *Container) GetImage() (*image.Image, error) { if container.daemon == nil { return nil, fmt.Errorf("Can't get image of unregistered container") } return container.daemon.graph.Get(container.ImageID) } func (container *Container) Unmount() error { return container.daemon.Unmount(container) } func (container *Container) hostConfigPath() (string, error) { return container.GetRootResourcePath("hostconfig.json") } func (container *Container) jsonPath() (string, error) { return container.GetRootResourcePath("config.json") } // This method must be exported to be used from the lxc template // This directory is only usable when the container is running func (container *Container) RootfsPath() string { return container.basefs } func validateID(id string) error { if id == "" { return fmt.Errorf("Invalid empty id") } return nil } func (container *Container) Copy(resource string) (rc io.ReadCloser, err error) { container.Lock() defer func() { if err != nil { // Wait to unlock the container until the archive is fully read // (see the ReadCloseWrapper func below) or if there is an error // before that occurs. container.Unlock() } }() if err := container.Mount(); err != nil { return nil, err } defer func() { if err != nil { // unmount any volumes container.UnmountVolumes(true) // unmount the container's rootfs container.Unmount() } }() if err := container.mountVolumes(); err != nil { return nil, err } basePath, err := container.GetResourcePath(resource) if err != nil { return nil, err } stat, err := os.Stat(basePath) if err != nil { return nil, err } var filter []string if !stat.IsDir() { d, f := filepath.Split(basePath) basePath = d filter = []string{f} } else { filter = []string{filepath.Base(basePath)} basePath = filepath.Dir(basePath) } archive, err := archive.TarWithOptions(basePath, &archive.TarOptions{ Compression: archive.Uncompressed, IncludeFiles: filter, }) if err != nil { return nil, err } if err := container.PrepareStorage(); err != nil { container.Unmount() return nil, err } reader := ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() container.CleanupStorage() container.UnmountVolumes(true) container.Unmount() container.Unlock() return err }) container.LogEvent("copy") return reader, nil } // Returns true if the container exposes a certain port func (container *Container) Exposes(p nat.Port) bool { _, exists := container.Config.ExposedPorts[p] return exists } func (container *Container) HostConfig() *runconfig.HostConfig { return container.hostConfig } func (container *Container) SetHostConfig(hostConfig *runconfig.HostConfig) { container.hostConfig = hostConfig } func (container *Container) getLogConfig() runconfig.LogConfig { cfg := container.hostConfig.LogConfig if cfg.Type != "" || len(cfg.Config) > 0 { // container has log driver configured if cfg.Type == "" { cfg.Type = jsonfilelog.Name } return cfg } // Use daemon's default log config for containers return container.daemon.defaultLogConfig } func (container *Container) getLogger() (logger.Logger, error) { cfg := container.getLogConfig() if err := logger.ValidateLogOpts(cfg.Type, cfg.Config); err != nil { return nil, err } c, err := logger.GetLogDriver(cfg.Type) if err != nil { return nil, fmt.Errorf("Failed to get logging factory: %v", err) } ctx := logger.Context{ Config: cfg.Config, ContainerID: container.ID, ContainerName: container.Name, ContainerEntrypoint: container.Path, ContainerArgs: container.Args, ContainerImageID: container.ImageID, ContainerImageName: container.Config.Image, ContainerCreated: container.Created, } // Set logging file for "json-logger" if cfg.Type == jsonfilelog.Name { ctx.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID)) if err != nil { return nil, err } } return c(ctx) } func (container *Container) startLogging() error { cfg := container.getLogConfig() if cfg.Type == "none" { return nil // do not start logging routines } l, err := container.getLogger() if err != nil { return fmt.Errorf("Failed to initialize logging driver: %v", err) } copier, err := logger.NewCopier(container.ID, map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l) if err != nil { return err } container.logCopier = copier copier.Run() container.logDriver = l // set LogPath field only for json-file logdriver if jl, ok := l.(*jsonfilelog.JSONFileLogger); ok { container.LogPath = jl.LogPath() } return nil } func (container *Container) waitForStart() error { container.monitor = newContainerMonitor(container, container.hostConfig.RestartPolicy) // block until we either receive an error from the initial start of the container's // process or until the process is running in the container select { case <-container.monitor.startSignal: case err := <-promise.Go(container.monitor.Start): return err } return nil } func (container *Container) GetProcessLabel() string { // even if we have a process label return "" if we are running // in privileged mode if container.hostConfig.Privileged { return "" } return container.ProcessLabel } func (container *Container) GetMountLabel() string { if container.hostConfig.Privileged { return "" } return container.MountLabel } func (container *Container) Stats() (*execdriver.ResourceStats, error) { return container.daemon.Stats(container) } func (c *Container) LogDriverType() string { c.Lock() defer c.Unlock() if c.hostConfig.LogConfig.Type == "" { return c.daemon.defaultLogConfig.Type } return c.hostConfig.LogConfig.Type } func (container *Container) GetExecIDs() []string { return container.execCommands.List() } func (container *Container) Exec(execConfig *execConfig) error { container.Lock() defer container.Unlock() waitStart := make(chan struct{}) callback := func(processConfig *execdriver.ProcessConfig, pid int) { if processConfig.Tty { // The callback is called after the process Start() // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave // which we close here. if c, ok := processConfig.Stdout.(io.Closer); ok { c.Close() } } close(waitStart) } // We use a callback here instead of a goroutine and an chan for // syncronization purposes cErr := promise.Go(func() error { return container.monitorExec(execConfig, callback) }) // Exec should not return until the process is actually running select { case <-waitStart: case err := <-cErr: return err } return nil } func (container *Container) monitorExec(execConfig *execConfig, callback execdriver.StartCallback) error { var ( err error exitCode int ) pipes := execdriver.NewPipes(execConfig.StreamConfig.stdin, execConfig.StreamConfig.stdout, execConfig.StreamConfig.stderr, execConfig.OpenStdin) exitCode, err = container.daemon.Exec(container, execConfig, pipes, callback) if err != nil { logrus.Errorf("Error running command in existing container %s: %s", container.ID, err) } logrus.Debugf("Exec task in container %s exited with code %d", container.ID, exitCode) if execConfig.OpenStdin { if err := execConfig.StreamConfig.stdin.Close(); err != nil { logrus.Errorf("Error closing stdin while running in %s: %s", container.ID, err) } } if err := execConfig.StreamConfig.stdout.Clean(); err != nil { logrus.Errorf("Error closing stdout while running in %s: %s", container.ID, err) } if err := execConfig.StreamConfig.stderr.Clean(); err != nil { logrus.Errorf("Error closing stderr while running in %s: %s", container.ID, err) } if execConfig.ProcessConfig.Terminal != nil { if err := execConfig.ProcessConfig.Terminal.Close(); err != nil { logrus.Errorf("Error closing terminal while running in container %s: %s", container.ID, err) } } // remove the exec command from the container's store only and not the // daemon's store so that the exec command can be inspected. container.execCommands.Delete(execConfig.ID) return err } func (c *Container) Attach(stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error { return attach(&c.StreamConfig, c.Config.OpenStdin, c.Config.StdinOnce, c.Config.Tty, stdin, stdout, stderr) } func (c *Container) AttachWithLogs(stdin io.ReadCloser, stdout, stderr io.Writer, logs, stream bool) error { if logs { logDriver, err := c.getLogger() if err != nil { logrus.Errorf("Error obtaining the logger %v", err) return err } if _, ok := logDriver.(logger.Reader); !ok { logrus.Errorf("cannot read logs for [%s] driver", logDriver.Name()) } else { if cLog, err := logDriver.(logger.Reader).ReadLog(); err != nil { logrus.Errorf("Error reading logs %v", err) } else { dec := json.NewDecoder(cLog) for { l := &jsonlog.JSONLog{} if err := dec.Decode(l); err == io.EOF { break } else if err != nil { logrus.Errorf("Error streaming logs: %s", err) break } if l.Stream == "stdout" && stdout != nil { io.WriteString(stdout, l.Log) } if l.Stream == "stderr" && stderr != nil { io.WriteString(stderr, l.Log) } } } } } c.LogEvent("attach") //stream if stream { var stdinPipe io.ReadCloser if stdin != nil { r, w := io.Pipe() go func() { defer w.Close() defer logrus.Debugf("Closing buffered stdin pipe") io.Copy(w, stdin) }() stdinPipe = r } <-c.Attach(stdinPipe, stdout, stderr) // If we are in stdinonce mode, wait for the process to end // otherwise, simply return if c.Config.StdinOnce && !c.Config.Tty { c.WaitStop(-1 * time.Second) } } return nil } func attach(streamConfig *StreamConfig, openStdin, stdinOnce, tty bool, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) chan error { var ( cStdout, cStderr io.ReadCloser cStdin io.WriteCloser wg sync.WaitGroup errors = make(chan error, 3) ) if stdin != nil && openStdin { cStdin = streamConfig.StdinPipe() wg.Add(1) } if stdout != nil { cStdout = streamConfig.StdoutPipe() wg.Add(1) } if stderr != nil { cStderr = streamConfig.StderrPipe() wg.Add(1) } // Connect stdin of container to the http conn. go func() { if stdin == nil || !openStdin { return } logrus.Debugf("attach: stdin: begin") defer func() { if stdinOnce && !tty { cStdin.Close() } else { // No matter what, when stdin is closed (io.Copy unblock), close stdout and stderr if cStdout != nil { cStdout.Close() } if cStderr != nil { cStderr.Close() } } wg.Done() logrus.Debugf("attach: stdin: end") }() var err error if tty { _, err = copyEscapable(cStdin, stdin) } else { _, err = io.Copy(cStdin, stdin) } if err == io.ErrClosedPipe { err = nil } if err != nil { logrus.Errorf("attach: stdin: %s", err) errors <- err return } }() attachStream := func(name string, stream io.Writer, streamPipe io.ReadCloser) { if stream == nil { return } defer func() { // Make sure stdin gets closed if stdin != nil { stdin.Close() } streamPipe.Close() wg.Done() logrus.Debugf("attach: %s: end", name) }() logrus.Debugf("attach: %s: begin", name) _, err := io.Copy(stream, streamPipe) if err == io.ErrClosedPipe { err = nil } if err != nil { logrus.Errorf("attach: %s: %v", name, err) errors <- err } } go attachStream("stdout", stdout, cStdout) go attachStream("stderr", stderr, cStderr) return promise.Go(func() error { wg.Wait() close(errors) for err := range errors { if err != nil { return err } } return nil }) } // Code c/c from io.Copy() modified to handle escape sequence func copyEscapable(dst io.Writer, src io.ReadCloser) (written int64, err error) { buf := make([]byte, 32*1024) for { nr, er := src.Read(buf) if nr > 0 { // ---- Docker addition // char 16 is C-p if nr == 1 && buf[0] == 16 { nr, er = src.Read(buf) // char 17 is C-q if nr == 1 && buf[0] == 17 { if err := src.Close(); err != nil { return 0, err } return 0, nil } } // ---- End of docker 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 } func (container *Container) networkMounts() []execdriver.Mount { var mounts []execdriver.Mount if container.ResolvConfPath != "" { label.SetFileLabel(container.ResolvConfPath, container.MountLabel) mounts = append(mounts, execdriver.Mount{ Source: container.ResolvConfPath, Destination: "/etc/resolv.conf", Writable: !container.hostConfig.ReadonlyRootfs, Private: true, }) } if container.HostnamePath != "" { label.SetFileLabel(container.HostnamePath, container.MountLabel) mounts = append(mounts, execdriver.Mount{ Source: container.HostnamePath, Destination: "/etc/hostname", Writable: !container.hostConfig.ReadonlyRootfs, Private: true, }) } if container.HostsPath != "" { label.SetFileLabel(container.HostsPath, container.MountLabel) mounts = append(mounts, execdriver.Mount{ Source: container.HostsPath, Destination: "/etc/hosts", Writable: !container.hostConfig.ReadonlyRootfs, Private: true, }) } return mounts } func (container *Container) addBindMountPoint(name, source, destination string, rw bool) { container.MountPoints[destination] = &mountPoint{ Name: name, Source: source, Destination: destination, RW: rw, } } func (container *Container) addLocalMountPoint(name, destination string, rw bool) { container.MountPoints[destination] = &mountPoint{ Name: name, Driver: volume.DefaultDriverName, Destination: destination, RW: rw, } } func (container *Container) addMountPointWithVolume(destination string, vol volume.Volume, rw bool) { container.MountPoints[destination] = &mountPoint{ Name: vol.Name(), Driver: vol.DriverName(), Destination: destination, RW: rw, Volume: vol, } } func (container *Container) isDestinationMounted(destination string) bool { return container.MountPoints[destination] != nil } func (container *Container) prepareMountPoints() error { for _, config := range container.MountPoints { if len(config.Driver) > 0 { v, err := createVolume(config.Name, config.Driver) if err != nil { return err } config.Volume = v } } return nil } func (container *Container) removeMountPoints() error { for _, m := range container.MountPoints { if m.Volume != nil { if err := removeVolume(m.Volume); err != nil { return err } } } return nil } func (container *Container) shouldRestart() bool { return container.hostConfig.RestartPolicy.Name == "always" || (container.hostConfig.RestartPolicy.Name == "on-failure" && container.ExitCode != 0) } func (container *Container) mountVolumes() error { mounts, err := container.setupMounts() if err != nil { return err } for _, m := range mounts { dest, err := container.GetResourcePath(m.Destination) if err != nil { return err } var stat os.FileInfo stat, err = os.Stat(m.Source) if err != nil { return err } if err = fileutils.CreateIfNotExists(dest, stat.IsDir()); err != nil { return err } opts := "rbind,ro" if m.Writable { opts = "rbind,rw" } if err := mount.Mount(m.Source, dest, "bind", opts); err != nil { return err } } return nil } func (container *Container) copyImagePathContent(v volume.Volume, destination string) error { rootfs, err := symlink.FollowSymlinkInScope(filepath.Join(container.basefs, destination), container.basefs) if err != nil { return err } if _, err = ioutil.ReadDir(rootfs); err != nil { if os.IsNotExist(err) { return nil } return err } path, err := v.Mount() if err != nil { return err } if err := copyExistingContents(rootfs, path); err != nil { return err } return v.Unmount() } ================================================ FILE: vendor/github.com/docker/docker/daemon/container_unit_test.go ================================================ package daemon import "testing" func TestGetFullName(t *testing.T) { name, err := GetFullContainerName("testing") if err != nil { t.Fatal(err) } if name != "/testing" { t.Fatalf("Expected /testing got %s", name) } if _, err := GetFullContainerName(""); err == nil { t.Fatal("Error should not be nil") } } func TestValidContainerNames(t *testing.T) { invalidNames := []string{"-rm", "&sdfsfd", "safd%sd"} validNames := []string{"word-word", "word_word", "1weoid"} for _, name := range invalidNames { if validContainerNamePattern.MatchString(name) { t.Fatalf("%q is not a valid container name and was returned as valid.", name) } } for _, name := range validNames { if !validContainerNamePattern.MatchString(name) { t.Fatalf("%q is a valid container name and was returned as invalid.", name) } } } ================================================ FILE: vendor/github.com/docker/docker/daemon/container_unix.go ================================================ // +build !windows package daemon import ( "fmt" "io/ioutil" "net" "os" "path" "path/filepath" "strconv" "strings" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/network" "github.com/docker/docker/links" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/directory" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/ulimit" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" "github.com/docker/libnetwork" "github.com/docker/libnetwork/netlabel" "github.com/docker/libnetwork/options" "github.com/docker/libnetwork/types" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/devices" ) const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" type Container struct { CommonContainer // Fields below here are platform specific. AppArmorProfile string activeLinks map[string]*links.Link } func killProcessDirectly(container *Container) error { if _, err := container.WaitStop(10 * time.Second); err != nil { // Ensure that we don't kill ourselves if pid := container.GetPid(); pid != 0 { logrus.Infof("Container %s failed to exit within 10 seconds of kill - trying direct SIGKILL", stringid.TruncateID(container.ID)) if err := syscall.Kill(pid, 9); err != nil { if err != syscall.ESRCH { return err } logrus.Debugf("Cannot kill process (pid=%d) with signal 9: no such process.", pid) } } } return nil } func (container *Container) setupLinkedContainers() ([]string, error) { var ( env []string daemon = container.daemon ) children, err := daemon.Children(container.Name) if err != nil { return nil, err } if len(children) > 0 { container.activeLinks = make(map[string]*links.Link, len(children)) // If we encounter an error make sure that we rollback any network // config and iptables changes rollback := func() { for _, link := range container.activeLinks { link.Disable() } container.activeLinks = nil } for linkAlias, child := range children { if !child.IsRunning() { return nil, fmt.Errorf("Cannot link to a non running container: %s AS %s", child.Name, linkAlias) } link, err := links.NewLink( container.NetworkSettings.IPAddress, child.NetworkSettings.IPAddress, linkAlias, child.Config.Env, child.Config.ExposedPorts, ) if err != nil { rollback() return nil, err } container.activeLinks[link.Alias()] = link if err := link.Enable(); err != nil { rollback() return nil, err } for _, envVar := range link.ToEnv() { env = append(env, envVar) } } } return env, nil } func (container *Container) createDaemonEnvironment(linkedEnv []string) []string { // if a domain name was specified, append it to the hostname (see #7851) fullHostname := container.Config.Hostname if container.Config.Domainname != "" { fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname) } // Setup environment env := []string{ "PATH=" + DefaultPathEnv, "HOSTNAME=" + fullHostname, // Note: we don't set HOME here because it'll get autoset intelligently // based on the value of USER inside dockerinit, but only if it isn't // set already (ie, that can be overridden by setting HOME via -e or ENV // in a Dockerfile). } if container.Config.Tty { env = append(env, "TERM=xterm") } env = append(env, linkedEnv...) // because the env on the container can override certain default values // we need to replace the 'env' keys where they match and append anything // else. env = utils.ReplaceOrAppendEnvValues(env, container.Config.Env) return env } func getDevicesFromPath(deviceMapping runconfig.DeviceMapping) (devs []*configs.Device, err error) { device, err := devices.DeviceFromPath(deviceMapping.PathOnHost, deviceMapping.CgroupPermissions) // if there was no error, return the device if err == nil { device.Path = deviceMapping.PathInContainer return append(devs, device), nil } // if the device is not a device node // try to see if it's a directory holding many devices if err == devices.ErrNotADevice { // check if it is a directory if src, e := os.Stat(deviceMapping.PathOnHost); e == nil && src.IsDir() { // mount the internal devices recursively filepath.Walk(deviceMapping.PathOnHost, func(dpath string, f os.FileInfo, e error) error { childDevice, e := devices.DeviceFromPath(dpath, deviceMapping.CgroupPermissions) if e != nil { // ignore the device return nil } // add the device to userSpecified devices childDevice.Path = strings.Replace(dpath, deviceMapping.PathOnHost, deviceMapping.PathInContainer, 1) devs = append(devs, childDevice) return nil }) } } if len(devs) > 0 { return devs, nil } return devs, fmt.Errorf("error gathering device information while adding custom device %q: %s", deviceMapping.PathOnHost, err) } func populateCommand(c *Container, env []string) error { var en *execdriver.Network if !c.Config.NetworkDisabled { en = &execdriver.Network{ NamespacePath: c.NetworkSettings.SandboxKey, } parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2) if parts[0] == "container" { nc, err := c.getNetworkedContainer() if err != nil { return err } en.ContainerID = nc.ID } } ipc := &execdriver.Ipc{} if c.hostConfig.IpcMode.IsContainer() { ic, err := c.getIpcContainer() if err != nil { return err } ipc.ContainerID = ic.ID } else { ipc.HostIpc = c.hostConfig.IpcMode.IsHost() } pid := &execdriver.Pid{} pid.HostPid = c.hostConfig.PidMode.IsHost() uts := &execdriver.UTS{ HostUTS: c.hostConfig.UTSMode.IsHost(), } // Build lists of devices allowed and created within the container. var userSpecifiedDevices []*configs.Device for _, deviceMapping := range c.hostConfig.Devices { devs, err := getDevicesFromPath(deviceMapping) if err != nil { return err } userSpecifiedDevices = append(userSpecifiedDevices, devs...) } allowedDevices := mergeDevices(configs.DefaultAllowedDevices, userSpecifiedDevices) autoCreatedDevices := mergeDevices(configs.DefaultAutoCreatedDevices, userSpecifiedDevices) // TODO: this can be removed after lxc-conf is fully deprecated lxcConfig, err := mergeLxcConfIntoOptions(c.hostConfig) if err != nil { return err } var rlimits []*ulimit.Rlimit ulimits := c.hostConfig.Ulimits // Merge ulimits with daemon defaults ulIdx := make(map[string]*ulimit.Ulimit) for _, ul := range ulimits { ulIdx[ul.Name] = ul } for name, ul := range c.daemon.config.Ulimits { if _, exists := ulIdx[name]; !exists { ulimits = append(ulimits, ul) } } for _, limit := range ulimits { rl, err := limit.GetRlimit() if err != nil { return err } rlimits = append(rlimits, rl) } resources := &execdriver.Resources{ Memory: c.hostConfig.Memory, MemorySwap: c.hostConfig.MemorySwap, CpuShares: c.hostConfig.CpuShares, CpusetCpus: c.hostConfig.CpusetCpus, CpusetMems: c.hostConfig.CpusetMems, CpuPeriod: c.hostConfig.CpuPeriod, CpuQuota: c.hostConfig.CpuQuota, BlkioWeight: c.hostConfig.BlkioWeight, Rlimits: rlimits, OomKillDisable: c.hostConfig.OomKillDisable, MemorySwappiness: c.hostConfig.MemorySwappiness, } processConfig := execdriver.ProcessConfig{ Privileged: c.hostConfig.Privileged, Entrypoint: c.Path, Arguments: c.Args, Tty: c.Config.Tty, User: c.Config.User, } processConfig.SysProcAttr = &syscall.SysProcAttr{Setsid: true} processConfig.Env = env c.command = &execdriver.Command{ ID: c.ID, Rootfs: c.RootfsPath(), ReadonlyRootfs: c.hostConfig.ReadonlyRootfs, InitPath: "/.dockerinit", WorkingDir: c.Config.WorkingDir, Network: en, Ipc: ipc, Pid: pid, UTS: uts, Resources: resources, AllowedDevices: allowedDevices, AutoCreatedDevices: autoCreatedDevices, CapAdd: c.hostConfig.CapAdd.Slice(), CapDrop: c.hostConfig.CapDrop.Slice(), GroupAdd: c.hostConfig.GroupAdd, ProcessConfig: processConfig, ProcessLabel: c.GetProcessLabel(), MountLabel: c.GetMountLabel(), LxcConfig: lxcConfig, AppArmorProfile: c.AppArmorProfile, CgroupParent: c.hostConfig.CgroupParent, } return nil } func mergeDevices(defaultDevices, userDevices []*configs.Device) []*configs.Device { if len(userDevices) == 0 { return defaultDevices } paths := map[string]*configs.Device{} for _, d := range userDevices { paths[d.Path] = d } var devs []*configs.Device for _, d := range defaultDevices { if _, defined := paths[d.Path]; !defined { devs = append(devs, d) } } return append(devs, userDevices...) } // GetSize, return real size, virtual size func (container *Container) GetSize() (int64, int64) { var ( sizeRw, sizeRootfs int64 err error driver = container.daemon.driver ) if err := container.Mount(); err != nil { logrus.Errorf("Failed to compute size of container rootfs %s: %s", container.ID, err) return sizeRw, sizeRootfs } defer container.Unmount() initID := fmt.Sprintf("%s-init", container.ID) sizeRw, err = driver.DiffSize(container.ID, initID) if err != nil { logrus.Errorf("Driver %s couldn't return diff size of container %s: %s", driver, container.ID, err) // FIXME: GetSize should return an error. Not changing it now in case // there is a side-effect. sizeRw = -1 } if _, err = os.Stat(container.basefs); err == nil { if sizeRootfs, err = directory.Size(container.basefs); err != nil { sizeRootfs = -1 } } return sizeRw, sizeRootfs } func (container *Container) buildHostnameFile() error { hostnamePath, err := container.GetRootResourcePath("hostname") if err != nil { return err } container.HostnamePath = hostnamePath if container.Config.Domainname != "" { return ioutil.WriteFile(container.HostnamePath, []byte(fmt.Sprintf("%s.%s\n", container.Config.Hostname, container.Config.Domainname)), 0644) } return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644) } func (container *Container) buildJoinOptions() ([]libnetwork.EndpointOption, error) { var ( joinOptions []libnetwork.EndpointOption err error dns []string dnsSearch []string ) joinOptions = append(joinOptions, libnetwork.JoinOptionHostname(container.Config.Hostname), libnetwork.JoinOptionDomainname(container.Config.Domainname)) if container.hostConfig.NetworkMode.IsHost() { joinOptions = append(joinOptions, libnetwork.JoinOptionUseDefaultSandbox()) } container.HostsPath, err = container.GetRootResourcePath("hosts") if err != nil { return nil, err } joinOptions = append(joinOptions, libnetwork.JoinOptionHostsPath(container.HostsPath)) container.ResolvConfPath, err = container.GetRootResourcePath("resolv.conf") if err != nil { return nil, err } joinOptions = append(joinOptions, libnetwork.JoinOptionResolvConfPath(container.ResolvConfPath)) if len(container.hostConfig.Dns) > 0 { dns = container.hostConfig.Dns } else if len(container.daemon.config.Dns) > 0 { dns = container.daemon.config.Dns } for _, d := range dns { joinOptions = append(joinOptions, libnetwork.JoinOptionDNS(d)) } if len(container.hostConfig.DnsSearch) > 0 { dnsSearch = container.hostConfig.DnsSearch } else if len(container.daemon.config.DnsSearch) > 0 { dnsSearch = container.daemon.config.DnsSearch } for _, ds := range dnsSearch { joinOptions = append(joinOptions, libnetwork.JoinOptionDNSSearch(ds)) } if container.NetworkSettings.SecondaryIPAddresses != nil { name := container.Config.Hostname if container.Config.Domainname != "" { name = name + "." + container.Config.Domainname } for _, a := range container.NetworkSettings.SecondaryIPAddresses { joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(name, a.Addr)) } } var childEndpoints, parentEndpoints []string children, err := container.daemon.Children(container.Name) if err != nil { return nil, err } for linkAlias, child := range children { _, alias := path.Split(linkAlias) // allow access to the linked container via the alias, real name, and container hostname aliasList := alias + " " + child.Config.Hostname // only add the name if alias isn't equal to the name if alias != child.Name[1:] { aliasList = aliasList + " " + child.Name[1:] } joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(aliasList, child.NetworkSettings.IPAddress)) if child.NetworkSettings.EndpointID != "" { childEndpoints = append(childEndpoints, child.NetworkSettings.EndpointID) } } for _, extraHost := range container.hostConfig.ExtraHosts { // allow IPv6 addresses in extra hosts; only split on first ":" parts := strings.SplitN(extraHost, ":", 2) joinOptions = append(joinOptions, libnetwork.JoinOptionExtraHost(parts[0], parts[1])) } refs := container.daemon.ContainerGraph().RefPaths(container.ID) for _, ref := range refs { if ref.ParentID == "0" { continue } c, err := container.daemon.Get(ref.ParentID) if err != nil { logrus.Error(err) } if c != nil && !container.daemon.config.DisableBridge && container.hostConfig.NetworkMode.IsPrivate() { logrus.Debugf("Update /etc/hosts of %s for alias %s with ip %s", c.ID, ref.Name, container.NetworkSettings.IPAddress) joinOptions = append(joinOptions, libnetwork.JoinOptionParentUpdate(c.NetworkSettings.EndpointID, ref.Name, container.NetworkSettings.IPAddress)) if c.NetworkSettings.EndpointID != "" { parentEndpoints = append(parentEndpoints, c.NetworkSettings.EndpointID) } } } linkOptions := options.Generic{ netlabel.GenericData: options.Generic{ "ParentEndpoints": parentEndpoints, "ChildEndpoints": childEndpoints, }, } joinOptions = append(joinOptions, libnetwork.JoinOptionGeneric(linkOptions)) return joinOptions, nil } func (container *Container) buildPortMapInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) { if ep == nil { return nil, fmt.Errorf("invalid endpoint while building port map info") } if networkSettings == nil { return nil, fmt.Errorf("invalid networksettings while building port map info") } driverInfo, err := ep.DriverInfo() if err != nil { return nil, err } if driverInfo == nil { // It is not an error for epInfo to be nil return networkSettings, nil } if mac, ok := driverInfo[netlabel.MacAddress]; ok { networkSettings.MacAddress = mac.(net.HardwareAddr).String() } networkSettings.Ports = nat.PortMap{} if expData, ok := driverInfo[netlabel.ExposedPorts]; ok { if exposedPorts, ok := expData.([]types.TransportPort); ok { for _, tp := range exposedPorts { natPort, err := nat.NewPort(tp.Proto.String(), strconv.Itoa(int(tp.Port))) if err != nil { return nil, fmt.Errorf("Error parsing Port value(%s):%v", tp.Port, err) } networkSettings.Ports[natPort] = nil } } } mapData, ok := driverInfo[netlabel.PortMap] if !ok { return networkSettings, nil } if portMapping, ok := mapData.([]types.PortBinding); ok { for _, pp := range portMapping { natPort, err := nat.NewPort(pp.Proto.String(), strconv.Itoa(int(pp.Port))) if err != nil { return nil, err } natBndg := nat.PortBinding{HostIP: pp.HostIP.String(), HostPort: strconv.Itoa(int(pp.HostPort))} networkSettings.Ports[natPort] = append(networkSettings.Ports[natPort], natBndg) } } return networkSettings, nil } func (container *Container) buildEndpointInfo(n libnetwork.Network, ep libnetwork.Endpoint, networkSettings *network.Settings) (*network.Settings, error) { if ep == nil { return nil, fmt.Errorf("invalid endpoint while building port map info") } if networkSettings == nil { return nil, fmt.Errorf("invalid networksettings while building port map info") } epInfo := ep.Info() if epInfo == nil { // It is not an error to get an empty endpoint info return networkSettings, nil } ifaceList := epInfo.InterfaceList() if len(ifaceList) == 0 { return networkSettings, nil } iface := ifaceList[0] ones, _ := iface.Address().Mask.Size() networkSettings.IPAddress = iface.Address().IP.String() networkSettings.IPPrefixLen = ones if iface.AddressIPv6().IP.To16() != nil { onesv6, _ := iface.AddressIPv6().Mask.Size() networkSettings.GlobalIPv6Address = iface.AddressIPv6().IP.String() networkSettings.GlobalIPv6PrefixLen = onesv6 } if len(ifaceList) == 1 { return networkSettings, nil } networkSettings.SecondaryIPAddresses = make([]network.Address, 0, len(ifaceList)-1) networkSettings.SecondaryIPv6Addresses = make([]network.Address, 0, len(ifaceList)-1) for _, iface := range ifaceList[1:] { ones, _ := iface.Address().Mask.Size() addr := network.Address{Addr: iface.Address().IP.String(), PrefixLen: ones} networkSettings.SecondaryIPAddresses = append(networkSettings.SecondaryIPAddresses, addr) if iface.AddressIPv6().IP.To16() != nil { onesv6, _ := iface.AddressIPv6().Mask.Size() addrv6 := network.Address{Addr: iface.AddressIPv6().IP.String(), PrefixLen: onesv6} networkSettings.SecondaryIPv6Addresses = append(networkSettings.SecondaryIPv6Addresses, addrv6) } } return networkSettings, nil } func (container *Container) updateJoinInfo(ep libnetwork.Endpoint) error { epInfo := ep.Info() if epInfo == nil { // It is not an error to get an empty endpoint info return nil } container.NetworkSettings.Gateway = epInfo.Gateway().String() if epInfo.GatewayIPv6().To16() != nil { container.NetworkSettings.IPv6Gateway = epInfo.GatewayIPv6().String() } container.NetworkSettings.SandboxKey = epInfo.SandboxKey() return nil } func (container *Container) updateNetworkSettings(n libnetwork.Network, ep libnetwork.Endpoint) error { networkSettings := &network.Settings{NetworkID: n.ID(), EndpointID: ep.ID()} networkSettings, err := container.buildPortMapInfo(n, ep, networkSettings) if err != nil { return err } networkSettings, err = container.buildEndpointInfo(n, ep, networkSettings) if err != nil { return err } if container.hostConfig.NetworkMode == runconfig.NetworkMode("bridge") { networkSettings.Bridge = container.daemon.config.Bridge.Iface } container.NetworkSettings = networkSettings return nil } func (container *Container) UpdateNetwork() error { n, err := container.daemon.netController.NetworkByID(container.NetworkSettings.NetworkID) if err != nil { return fmt.Errorf("error locating network id %s: %v", container.NetworkSettings.NetworkID, err) } ep, err := n.EndpointByID(container.NetworkSettings.EndpointID) if err != nil { return fmt.Errorf("error locating endpoint id %s: %v", container.NetworkSettings.EndpointID, err) } if err := ep.Leave(container.ID); err != nil { return fmt.Errorf("endpoint leave failed: %v", err) } joinOptions, err := container.buildJoinOptions() if err != nil { return fmt.Errorf("Update network failed: %v", err) } if err := ep.Join(container.ID, joinOptions...); err != nil { return fmt.Errorf("endpoint join failed: %v", err) } if err := container.updateJoinInfo(ep); err != nil { return fmt.Errorf("Updating join info failed: %v", err) } return nil } func (container *Container) buildCreateEndpointOptions() ([]libnetwork.EndpointOption, error) { var ( portSpecs = make(nat.PortSet) bindings = make(nat.PortMap) pbList []types.PortBinding exposeList []types.TransportPort createOptions []libnetwork.EndpointOption ) if container.Config.ExposedPorts != nil { portSpecs = container.Config.ExposedPorts } if container.hostConfig.PortBindings != nil { for p, b := range container.hostConfig.PortBindings { bindings[p] = []nat.PortBinding{} for _, bb := range b { bindings[p] = append(bindings[p], nat.PortBinding{ HostIP: bb.HostIP, HostPort: bb.HostPort, }) } } } container.NetworkSettings.PortMapping = nil ports := make([]nat.Port, len(portSpecs)) var i int for p := range portSpecs { ports[i] = p i++ } nat.SortPortMap(ports, bindings) for _, port := range ports { expose := types.TransportPort{} expose.Proto = types.ParseProtocol(port.Proto()) expose.Port = uint16(port.Int()) exposeList = append(exposeList, expose) pb := types.PortBinding{Port: expose.Port, Proto: expose.Proto} binding := bindings[port] for i := 0; i < len(binding); i++ { pbCopy := pb.GetCopy() newP, err := nat.NewPort(nat.SplitProtoPort(binding[i].HostPort)) if err != nil { return nil, fmt.Errorf("Error parsing HostPort value(%s):%v", binding[i].HostPort, err) } pbCopy.HostPort = uint16(newP.Int()) pbCopy.HostIP = net.ParseIP(binding[i].HostIP) pbList = append(pbList, pbCopy) } if container.hostConfig.PublishAllPorts && len(binding) == 0 { pbList = append(pbList, pb) } } createOptions = append(createOptions, libnetwork.CreateOptionPortMapping(pbList), libnetwork.CreateOptionExposedPorts(exposeList)) if container.Config.MacAddress != "" { mac, err := net.ParseMAC(container.Config.MacAddress) if err != nil { return nil, err } genericOption := options.Generic{ netlabel.MacAddress: mac, } createOptions = append(createOptions, libnetwork.EndpointOptionGeneric(genericOption)) } return createOptions, nil } func parseService(controller libnetwork.NetworkController, service string) (string, string, string) { dn := controller.Config().Daemon.DefaultNetwork dd := controller.Config().Daemon.DefaultDriver snd := strings.Split(service, ".") if len(snd) > 2 { return strings.Join(snd[:len(snd)-2], "."), snd[len(snd)-2], snd[len(snd)-1] } if len(snd) > 1 { return snd[0], snd[1], dd } return snd[0], dn, dd } func createNetwork(controller libnetwork.NetworkController, dnet string, driver string) (libnetwork.Network, error) { createOptions := []libnetwork.NetworkOption{} genericOption := options.Generic{} // Bridge driver is special due to legacy reasons if runconfig.NetworkMode(driver).IsBridge() { genericOption[netlabel.GenericData] = map[string]interface{}{ "BridgeName": dnet, "AllowNonDefaultBridge": "true", } networkOption := libnetwork.NetworkOptionGeneric(genericOption) createOptions = append(createOptions, networkOption) } return controller.NewNetwork(driver, dnet, createOptions...) } func (container *Container) secondaryNetworkRequired(primaryNetworkType string) bool { switch primaryNetworkType { case "bridge", "none", "host", "container": return false } if container.daemon.config.DisableBridge { return false } if container.Config.ExposedPorts != nil && len(container.Config.ExposedPorts) > 0 { return true } if container.hostConfig.PortBindings != nil && len(container.hostConfig.PortBindings) > 0 { return true } return false } func (container *Container) AllocateNetwork() error { mode := container.hostConfig.NetworkMode controller := container.daemon.netController if container.Config.NetworkDisabled || mode.IsContainer() { return nil } networkDriver := string(mode) service := container.Config.PublishService networkName := mode.NetworkName() if mode.IsDefault() { if service != "" { service, networkName, networkDriver = parseService(controller, service) } else { networkName = controller.Config().Daemon.DefaultNetwork networkDriver = controller.Config().Daemon.DefaultDriver } } else if service != "" { return fmt.Errorf("conflicting options: publishing a service and network mode") } if runconfig.NetworkMode(networkDriver).IsBridge() && container.daemon.config.DisableBridge { container.Config.NetworkDisabled = true return nil } if service == "" { // dot character "." has a special meaning to support SERVICE[.NETWORK] format. // For backward compatiblity, replacing "." with "-", instead of failing service = strings.Replace(container.Name, ".", "-", -1) // Service names dont like "/" in them. removing it instead of failing for backward compatibility service = strings.Replace(service, "/", "", -1) } if container.secondaryNetworkRequired(networkDriver) { // Configure Bridge as secondary network for port binding purposes if err := container.configureNetwork("bridge", service, "bridge", false); err != nil { return err } } if err := container.configureNetwork(networkName, service, networkDriver, mode.IsDefault()); err != nil { return err } return container.WriteHostConfig() } func (container *Container) configureNetwork(networkName, service, networkDriver string, canCreateNetwork bool) error { controller := container.daemon.netController n, err := controller.NetworkByName(networkName) if err != nil { if _, ok := err.(libnetwork.ErrNoSuchNetwork); !ok || !canCreateNetwork { return err } if n, err = createNetwork(controller, networkName, networkDriver); err != nil { return err } } ep, err := n.EndpointByName(service) if err != nil { if _, ok := err.(libnetwork.ErrNoSuchEndpoint); !ok { return err } createOptions, err := container.buildCreateEndpointOptions() if err != nil { return err } ep, err = n.CreateEndpoint(service, createOptions...) if err != nil { return err } } if err := container.updateNetworkSettings(n, ep); err != nil { return err } joinOptions, err := container.buildJoinOptions() if err != nil { return err } if err := ep.Join(container.ID, joinOptions...); err != nil { return err } if err := container.updateJoinInfo(ep); err != nil { return fmt.Errorf("Updating join info failed: %v", err) } return nil } func (container *Container) initializeNetworking() error { var err error // Make sure NetworkMode has an acceptable value before // initializing networking. if container.hostConfig.NetworkMode == runconfig.NetworkMode("") { container.hostConfig.NetworkMode = runconfig.NetworkMode("default") } if container.hostConfig.NetworkMode.IsContainer() { // we need to get the hosts files from the container to join nc, err := container.getNetworkedContainer() if err != nil { return err } container.HostnamePath = nc.HostnamePath container.HostsPath = nc.HostsPath container.ResolvConfPath = nc.ResolvConfPath container.Config.Hostname = nc.Config.Hostname container.Config.Domainname = nc.Config.Domainname return nil } if container.hostConfig.NetworkMode.IsHost() { container.Config.Hostname, err = os.Hostname() if err != nil { return err } parts := strings.SplitN(container.Config.Hostname, ".", 2) if len(parts) > 1 { container.Config.Hostname = parts[0] container.Config.Domainname = parts[1] } } if err := container.AllocateNetwork(); err != nil { return err } return container.buildHostnameFile() } func (container *Container) ExportRw() (archive.Archive, error) { if container.daemon == nil { return nil, fmt.Errorf("Can't load storage driver for unregistered container %s", container.ID) } archive, err := container.daemon.Diff(container) if err != nil { return nil, err } return ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() return err }), nil } func (container *Container) getIpcContainer() (*Container, error) { containerID := container.hostConfig.IpcMode.Container() c, err := container.daemon.Get(containerID) if err != nil { return nil, err } if !c.IsRunning() { return nil, fmt.Errorf("cannot join IPC of a non running container: %s", containerID) } return c, nil } func (container *Container) setupWorkingDirectory() error { if container.Config.WorkingDir != "" { container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir) pth, err := container.GetResourcePath(container.Config.WorkingDir) if err != nil { return err } pthInfo, err := os.Stat(pth) if err != nil { if !os.IsNotExist(err) { return err } if err := system.MkdirAll(pth, 0755); err != nil { return err } } if pthInfo != nil && !pthInfo.IsDir() { return fmt.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir) } } return nil } func (container *Container) getNetworkedContainer() (*Container, error) { parts := strings.SplitN(string(container.hostConfig.NetworkMode), ":", 2) switch parts[0] { case "container": if len(parts) != 2 { return nil, fmt.Errorf("no container specified to join network") } nc, err := container.daemon.Get(parts[1]) if err != nil { return nil, err } if container == nc { return nil, fmt.Errorf("cannot join own network") } if !nc.IsRunning() { return nil, fmt.Errorf("cannot join network of a non running container: %s", parts[1]) } return nc, nil default: return nil, fmt.Errorf("network mode not set to container") } } func (container *Container) ReleaseNetwork() { if container.hostConfig.NetworkMode.IsContainer() || container.Config.NetworkDisabled { return } eid := container.NetworkSettings.EndpointID nid := container.NetworkSettings.NetworkID container.NetworkSettings = &network.Settings{} if nid == "" || eid == "" { return } n, err := container.daemon.netController.NetworkByID(nid) if err != nil { logrus.Errorf("error locating network id %s: %v", nid, err) return } ep, err := n.EndpointByID(eid) if err != nil { logrus.Errorf("error locating endpoint id %s: %v", eid, err) return } switch { case container.hostConfig.NetworkMode.IsHost(): if err := ep.Leave(container.ID); err != nil { logrus.Errorf("Error leaving endpoint id %s for container %s: %v", eid, container.ID, err) return } default: if err := container.daemon.netController.LeaveAll(container.ID); err != nil { logrus.Errorf("Leave all failed for %s: %v", container.ID, err) return } } // In addition to leaving all endpoints, delete implicitly created endpoint if container.Config.PublishService == "" { if err := ep.Delete(); err != nil { logrus.Errorf("deleting endpoint failed: %v", err) } } } func disableAllActiveLinks(container *Container) { if container.activeLinks != nil { for _, link := range container.activeLinks { link.Disable() } } } func (container *Container) DisableLink(name string) { if container.activeLinks != nil { if link, exists := container.activeLinks[name]; exists { link.Disable() delete(container.activeLinks, name) if err := container.UpdateNetwork(); err != nil { logrus.Debugf("Could not update network to remove link: %v", err) } } else { logrus.Debugf("Could not find active link for %s", name) } } } func (container *Container) UnmountVolumes(forceSyscall bool) error { var volumeMounts []mountPoint for _, mntPoint := range container.MountPoints { dest, err := container.GetResourcePath(mntPoint.Destination) if err != nil { return err } volumeMounts = append(volumeMounts, mountPoint{Destination: dest, Volume: mntPoint.Volume}) } for _, mnt := range container.networkMounts() { dest, err := container.GetResourcePath(mnt.Destination) if err != nil { return err } volumeMounts = append(volumeMounts, mountPoint{Destination: dest}) } for _, volumeMount := range volumeMounts { if forceSyscall { syscall.Unmount(volumeMount.Destination, 0) } if volumeMount.Volume != nil { if err := volumeMount.Volume.Unmount(); err != nil { return err } } } return nil } func (container *Container) PrepareStorage() error { return nil } func (container *Container) CleanupStorage() error { return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/container_windows.go ================================================ // +build windows package daemon import ( "fmt" "path/filepath" "strings" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/graphdriver/windows" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/microsoft/hcsshim" ) // This is deliberately empty on Windows as the default path will be set by // the container. Docker has no context of what the default path should be. const DefaultPathEnv = "" type Container struct { CommonContainer // Fields below here are platform specific. // TODO Windows. Further factoring out of unused fields will be necessary. // ---- START OF TEMPORARY DECLARATION ---- // TODO Windows. Temporarily keeping fields in to assist in compilation // of the daemon on Windows without affecting many other files in a single // PR, thus making code review significantly harder. These lines will be // removed in subsequent PRs. AppArmorProfile string // ---- END OF TEMPORARY DECLARATION ---- } func killProcessDirectly(container *Container) error { return nil } func (container *Container) setupContainerDns() error { return nil } func (container *Container) updateParentsHosts() error { return nil } func (container *Container) setupLinkedContainers() ([]string, error) { return nil, nil } func (container *Container) createDaemonEnvironment(linkedEnv []string) []string { // On Windows, nothing to link. Just return the container environment. return container.Config.Env } func (container *Container) initializeNetworking() error { return nil } func (container *Container) setupWorkingDirectory() error { return nil } func populateCommand(c *Container, env []string) error { en := &execdriver.Network{ Mtu: c.daemon.config.Mtu, Interface: nil, } parts := strings.SplitN(string(c.hostConfig.NetworkMode), ":", 2) switch parts[0] { case "none": case "default", "": // empty string to support existing containers if !c.Config.NetworkDisabled { en.Interface = &execdriver.NetworkInterface{ MacAddress: c.Config.MacAddress, Bridge: c.daemon.config.Bridge.VirtualSwitchName, } } default: return fmt.Errorf("invalid network mode: %s", c.hostConfig.NetworkMode) } pid := &execdriver.Pid{} // TODO Windows. This can probably be factored out. pid.HostPid = c.hostConfig.PidMode.IsHost() // TODO Windows. Resource controls to be implemented later. resources := &execdriver.Resources{} // TODO Windows. Further refactoring required (privileged/user) processConfig := execdriver.ProcessConfig{ Privileged: c.hostConfig.Privileged, Entrypoint: c.Path, Arguments: c.Args, Tty: c.Config.Tty, User: c.Config.User, ConsoleSize: c.hostConfig.ConsoleSize, } processConfig.Env = env var layerFolder string var layerPaths []string // The following is specific to the Windows driver. We do this to // enable VFS to continue operating for development purposes. if wd, ok := c.daemon.driver.(*windows.WindowsGraphDriver); ok { var err error var img *image.Image var ids []string if img, err = c.daemon.graph.Get(c.ImageID); err != nil { return fmt.Errorf("Failed to graph.Get on ImageID %s - %s", c.ImageID, err) } if ids, err = c.daemon.graph.ParentLayerIds(img); err != nil { return fmt.Errorf("Failed to get parentlayer ids %s", img.ID) } layerPaths = wd.LayerIdsToPaths(ids) layerFolder = filepath.Join(wd.Info().HomeDir, filepath.Base(c.ID)) } // TODO Windows: Factor out remainder of unused fields. c.command = &execdriver.Command{ ID: c.ID, Rootfs: c.RootfsPath(), ReadonlyRootfs: c.hostConfig.ReadonlyRootfs, InitPath: "/.dockerinit", WorkingDir: c.Config.WorkingDir, Network: en, Pid: pid, Resources: resources, CapAdd: c.hostConfig.CapAdd.Slice(), CapDrop: c.hostConfig.CapDrop.Slice(), ProcessConfig: processConfig, ProcessLabel: c.GetProcessLabel(), MountLabel: c.GetMountLabel(), FirstStart: !c.HasBeenStartedBefore, LayerFolder: layerFolder, LayerPaths: layerPaths, } return nil } // GetSize, return real size, virtual size func (container *Container) GetSize() (int64, int64) { // TODO Windows return 0, 0 } func (container *Container) AllocateNetwork() error { return nil } func (container *Container) ExportRw() (archive.Archive, error) { if container.IsRunning() { return nil, fmt.Errorf("Cannot export a running container.") } // TODO Windows. Implementation (different to Linux) return nil, nil } func (container *Container) ReleaseNetwork() { } func (container *Container) RestoreNetwork() error { return nil } func disableAllActiveLinks(container *Container) { } func (container *Container) DisableLink(name string) { } func (container *Container) UnmountVolumes(forceSyscall bool) error { return nil } func (container *Container) PrepareStorage() error { if wd, ok := container.daemon.driver.(*windows.WindowsGraphDriver); ok { // Get list of paths to parent layers. var ids []string if container.ImageID != "" { img, err := container.daemon.graph.Get(container.ImageID) if err != nil { return err } ids, err = container.daemon.graph.ParentLayerIds(img) if err != nil { return err } } if err := hcsshim.PrepareLayer(wd.Info(), container.ID, wd.LayerIdsToPaths(ids)); err != nil { return err } } return nil } func (container *Container) CleanupStorage() error { if wd, ok := container.daemon.driver.(*windows.WindowsGraphDriver); ok { return hcsshim.UnprepareLayer(wd.Info(), container.ID) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/create.go ================================================ package daemon import ( "fmt" "os" "path/filepath" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/graph" "github.com/docker/docker/image" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/runconfig" "github.com/opencontainers/runc/libcontainer/label" ) func (daemon *Daemon) ContainerCreate(name string, config *runconfig.Config, hostConfig *runconfig.HostConfig) (string, []string, error) { if config == nil { return "", nil, fmt.Errorf("Config cannot be empty in order to create a container") } warnings, err := daemon.verifyContainerSettings(hostConfig, config) if err != nil { return "", warnings, err } container, buildWarnings, err := daemon.Create(config, hostConfig, name) if err != nil { if daemon.Graph().IsNotExist(err, config.Image) { _, tag := parsers.ParseRepositoryTag(config.Image) if tag == "" { tag = graph.DEFAULTTAG } return "", warnings, fmt.Errorf("No such image: %s (tag: %s)", config.Image, tag) } return "", warnings, err } warnings = append(warnings, buildWarnings...) return container.ID, warnings, nil } // Create creates a new container from the given configuration with a given name. func (daemon *Daemon) Create(config *runconfig.Config, hostConfig *runconfig.HostConfig, name string) (*Container, []string, error) { var ( container *Container warnings []string img *image.Image imgID string err error ) if config.Image != "" { img, err = daemon.repositories.LookupImage(config.Image) if err != nil { return nil, nil, err } if err = daemon.graph.CheckDepth(img); err != nil { return nil, nil, err } imgID = img.ID } if err := daemon.mergeAndVerifyConfig(config, img); err != nil { return nil, nil, err } if !config.NetworkDisabled && daemon.SystemConfig().IPv4ForwardingDisabled { warnings = append(warnings, "IPv4 forwarding is disabled.") } if hostConfig == nil { hostConfig = &runconfig.HostConfig{} } if hostConfig.SecurityOpt == nil { hostConfig.SecurityOpt, err = daemon.GenerateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode) if err != nil { return nil, nil, err } } if container, err = daemon.newContainer(name, config, imgID); err != nil { return nil, nil, err } if err := daemon.Register(container); err != nil { return nil, nil, err } if err := daemon.createRootfs(container); err != nil { return nil, nil, err } if err := daemon.setHostConfig(container, hostConfig); err != nil { return nil, nil, err } if err := container.Mount(); err != nil { return nil, nil, err } defer container.Unmount() for spec := range config.Volumes { var ( name, destination string parts = strings.Split(spec, ":") ) switch len(parts) { case 2: name, destination = parts[0], filepath.Clean(parts[1]) default: name = stringid.GenerateRandomID() destination = filepath.Clean(parts[0]) } // Skip volumes for which we already have something mounted on that // destination because of a --volume-from. if container.isDestinationMounted(destination) { continue } path, err := container.GetResourcePath(destination) if err != nil { return nil, nil, err } stat, err := os.Stat(path) if err == nil && !stat.IsDir() { return nil, nil, fmt.Errorf("cannot mount volume over existing file, file exists %s", path) } v, err := createVolume(name, config.VolumeDriver) if err != nil { return nil, nil, err } if err := label.Relabel(v.Path(), container.MountLabel, "z"); err != nil { return nil, nil, err } if err := container.copyImagePathContent(v, destination); err != nil { return nil, nil, err } container.addMountPointWithVolume(destination, v, true) } if err := container.ToDisk(); err != nil { logrus.Errorf("Error saving new container to disk: %v", err) return nil, nil, err } container.LogEvent("create") return container, warnings, nil } func (daemon *Daemon) GenerateSecurityOpt(ipcMode runconfig.IpcMode, pidMode runconfig.PidMode) ([]string, error) { if ipcMode.IsHost() || pidMode.IsHost() { return label.DisableSecOpt(), nil } if ipcContainer := ipcMode.Container(); ipcContainer != "" { c, err := daemon.Get(ipcContainer) if err != nil { return nil, err } return label.DupSecOpt(c.ProcessLabel), nil } return nil, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon.go ================================================ package daemon import ( "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "regexp" "runtime" "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/api" "github.com/docker/docker/daemon/events" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/execdriver/execdrivers" "github.com/docker/docker/daemon/graphdriver" _ "github.com/docker/docker/daemon/graphdriver/vfs" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/network" "github.com/docker/docker/graph" "github.com/docker/docker/image" "github.com/docker/docker/pkg/broadcastwriter" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/graphdb" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/namesgenerator" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/sysinfo" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/truncindex" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" "github.com/docker/docker/trust" "github.com/docker/libnetwork" "github.com/opencontainers/runc/libcontainer/netlink" ) var ( validContainerNameChars = `[a-zA-Z0-9][a-zA-Z0-9_.-]` validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`) ErrSystemNotSupported = errors.New("The Docker daemon is not supported on this platform.") ) type contStore struct { s map[string]*Container sync.Mutex } func (c *contStore) Add(id string, cont *Container) { c.Lock() c.s[id] = cont c.Unlock() } func (c *contStore) Get(id string) *Container { c.Lock() res := c.s[id] c.Unlock() return res } func (c *contStore) Delete(id string) { c.Lock() delete(c.s, id) c.Unlock() } func (c *contStore) List() []*Container { containers := new(History) c.Lock() for _, cont := range c.s { containers.Add(cont) } c.Unlock() containers.Sort() return *containers } type Daemon struct { ID string repository string sysInitPath string containers *contStore execCommands *execStore graph *graph.Graph repositories *graph.TagStore idIndex *truncindex.TruncIndex sysInfo *sysinfo.SysInfo config *Config containerGraph *graphdb.Database driver graphdriver.Driver execDriver execdriver.Driver statsCollector *statsCollector defaultLogConfig runconfig.LogConfig RegistryService *registry.Service EventsService *events.Events netController libnetwork.NetworkController root string } // Get looks for a container using the provided information, which could be // one of the following inputs from the caller: // - A full container ID, which will exact match a container in daemon's list // - A container name, which will only exact match via the GetByName() function // - A partial container ID prefix (e.g. short ID) of any length that is // unique enough to only return a single container object // If none of these searches succeed, an error is returned func (daemon *Daemon) Get(prefixOrName string) (*Container, error) { if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil { // prefix is an exact match to a full container ID return containerByID, nil } // GetByName will match only an exact name provided; we ignore errors if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil { // prefix is an exact match to a full container Name return containerByName, nil } containerId, indexError := daemon.idIndex.Get(prefixOrName) if indexError != nil { return nil, indexError } return daemon.containers.Get(containerId), nil } // Exists returns a true if a container of the specified ID or name exists, // false otherwise. func (daemon *Daemon) Exists(id string) bool { c, _ := daemon.Get(id) return c != nil } func (daemon *Daemon) containerRoot(id string) string { return filepath.Join(daemon.repository, id) } // Load reads the contents of a container from disk // This is typically done at startup. func (daemon *Daemon) load(id string) (*Container, error) { container := &Container{ CommonContainer: daemon.newBaseContainer(id), } if err := container.FromDisk(); err != nil { return nil, err } if container.ID != id { return container, fmt.Errorf("Container %s is stored at %s", container.ID, id) } return container, nil } // Register makes a container object usable by the daemon as // This is a wrapper for register func (daemon *Daemon) Register(container *Container) error { return daemon.register(container, true) } // register makes a container object usable by the daemon as func (daemon *Daemon) register(container *Container, updateSuffixarray bool) error { if container.daemon != nil || daemon.Exists(container.ID) { return fmt.Errorf("Container is already loaded") } if err := validateID(container.ID); err != nil { return err } if err := daemon.ensureName(container); err != nil { return err } container.daemon = daemon // Attach to stdout and stderr container.stderr = broadcastwriter.New() container.stdout = broadcastwriter.New() // Attach to stdin if container.Config.OpenStdin { container.stdin, container.stdinPipe = io.Pipe() } else { container.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin } // done daemon.containers.Add(container.ID, container) // don't update the Suffixarray if we're starting up // we'll waste time if we update it for every container daemon.idIndex.Add(container.ID) if err := daemon.verifyVolumesInfo(container); err != nil { return err } if err := container.prepareMountPoints(); err != nil { return err } if container.IsRunning() { logrus.Debugf("killing old running container %s", container.ID) // Set exit code to 128 + SIGKILL (9) to properly represent unsuccessful exit container.SetStopped(&execdriver.ExitStatus{ExitCode: 137}) // use the current driver and ensure that the container is dead x.x cmd := &execdriver.Command{ ID: container.ID, } daemon.execDriver.Terminate(cmd) if err := container.Unmount(); err != nil { logrus.Debugf("unmount error %s", err) } if err := container.ToDisk(); err != nil { logrus.Errorf("Error saving stopped state to disk: %v", err) } } return nil } func (daemon *Daemon) ensureName(container *Container) error { if container.Name == "" { name, err := daemon.generateNewName(container.ID) if err != nil { return err } container.Name = name if err := container.ToDisk(); err != nil { logrus.Errorf("Error saving container name to disk: %v", err) } } return nil } func (daemon *Daemon) restore() error { type cr struct { container *Container registered bool } var ( debug = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "") currentDriver = daemon.driver.String() containers = make(map[string]*cr) ) if !debug { logrus.Info("Loading containers: start.") } dir, err := ioutil.ReadDir(daemon.repository) if err != nil { return err } for _, v := range dir { id := v.Name() container, err := daemon.load(id) if !debug && logrus.GetLevel() == logrus.InfoLevel { fmt.Print(".") } if err != nil { logrus.Errorf("Failed to load container %v: %v", id, err) continue } // Ignore the container if it does not support the current driver being used by the graph if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver { logrus.Debugf("Loaded container %v", container.ID) containers[container.ID] = &cr{container: container} } else { logrus.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID) } } if entities := daemon.containerGraph.List("/", -1); entities != nil { for _, p := range entities.Paths() { if !debug && logrus.GetLevel() == logrus.InfoLevel { fmt.Print(".") } e := entities[p] if c, ok := containers[e.ID()]; ok { c.registered = true } } } group := sync.WaitGroup{} for _, c := range containers { group.Add(1) go func(container *Container, registered bool) { defer group.Done() if !registered { // Try to set the default name for a container if it exists prior to links container.Name, err = daemon.generateNewName(container.ID) if err != nil { logrus.Debugf("Setting default id - %s", err) } } if err := daemon.register(container, false); err != nil { logrus.Debugf("Failed to register container %s: %s", container.ID, err) } // check the restart policy on the containers and restart any container with // the restart policy of "always" if daemon.config.AutoRestart && container.shouldRestart() { logrus.Debugf("Starting container %s", container.ID) if err := container.Start(); err != nil { logrus.Debugf("Failed to start container %s: %s", container.ID, err) } } }(c.container, c.registered) } group.Wait() if !debug { if logrus.GetLevel() == logrus.InfoLevel { fmt.Println() } logrus.Info("Loading containers: done.") } return nil } func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) error { if img != nil && img.Config != nil { if err := runconfig.Merge(config, img.Config); err != nil { return err } } if config.Entrypoint.Len() == 0 && config.Cmd.Len() == 0 { return fmt.Errorf("No command specified") } return nil } func (daemon *Daemon) generateIdAndName(name string) (string, string, error) { var ( err error id = stringid.GenerateRandomID() ) if name == "" { if name, err = daemon.generateNewName(id); err != nil { return "", "", err } return id, name, nil } if name, err = daemon.reserveName(id, name); err != nil { return "", "", err } return id, name, nil } func (daemon *Daemon) reserveName(id, name string) (string, error) { if !validContainerNamePattern.MatchString(name) { return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars) } if name[0] != '/' { name = "/" + name } if _, err := daemon.containerGraph.Set(name, id); err != nil { if !graphdb.IsNonUniqueNameError(err) { return "", err } conflictingContainer, err := daemon.GetByName(name) if err != nil { if strings.Contains(err.Error(), "Could not find entity") { return "", err } // Remove name and continue starting the container if err := daemon.containerGraph.Delete(name); err != nil { return "", err } } else { nameAsKnownByUser := strings.TrimPrefix(name, "/") return "", fmt.Errorf( "Conflict. The name %q is already in use by container %s. You have to delete (or rename) that container to be able to reuse that name.", nameAsKnownByUser, stringid.TruncateID(conflictingContainer.ID)) } } return name, nil } func (daemon *Daemon) generateNewName(id string) (string, error) { var name string for i := 0; i < 6; i++ { name = namesgenerator.GetRandomName(i) if name[0] != '/' { name = "/" + name } if _, err := daemon.containerGraph.Set(name, id); err != nil { if !graphdb.IsNonUniqueNameError(err) { return "", err } continue } return name, nil } name = "/" + stringid.TruncateID(id) if _, err := daemon.containerGraph.Set(name, id); err != nil { return "", err } return name, nil } func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) { // Generate default hostname // FIXME: the lxc template no longer needs to set a default hostname if config.Hostname == "" { config.Hostname = id[:12] } } func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint *runconfig.Entrypoint, configCmd *runconfig.Command) (string, []string) { var ( entrypoint string args []string ) cmdSlice := configCmd.Slice() if configEntrypoint.Len() != 0 { eSlice := configEntrypoint.Slice() entrypoint = eSlice[0] args = append(eSlice[1:], cmdSlice...) } else { entrypoint = cmdSlice[0] args = cmdSlice[1:] } return entrypoint, args } func (daemon *Daemon) newContainer(name string, config *runconfig.Config, imgID string) (*Container, error) { var ( id string err error ) id, name, err = daemon.generateIdAndName(name) if err != nil { return nil, err } daemon.generateHostname(id, config) entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd) base := daemon.newBaseContainer(id) base.Created = time.Now().UTC() base.Path = entrypoint base.Args = args //FIXME: de-duplicate from config base.Config = config base.hostConfig = &runconfig.HostConfig{} base.ImageID = imgID base.NetworkSettings = &network.Settings{} base.Name = name base.Driver = daemon.driver.String() base.ExecDriver = daemon.execDriver.Name() container := &Container{ CommonContainer: base, } return container, err } func GetFullContainerName(name string) (string, error) { if name == "" { return "", fmt.Errorf("Container name cannot be empty") } if name[0] != '/' { name = "/" + name } return name, nil } func (daemon *Daemon) GetByName(name string) (*Container, error) { fullName, err := GetFullContainerName(name) if err != nil { return nil, err } entity := daemon.containerGraph.Get(fullName) if entity == nil { return nil, fmt.Errorf("Could not find entity for %s", name) } e := daemon.containers.Get(entity.ID()) if e == nil { return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID()) } return e, nil } func (daemon *Daemon) Children(name string) (map[string]*Container, error) { name, err := GetFullContainerName(name) if err != nil { return nil, err } children := make(map[string]*Container) err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error { c, err := daemon.Get(e.ID()) if err != nil { return err } children[p] = c return nil }, 0) if err != nil { return nil, err } return children, nil } func (daemon *Daemon) Parents(name string) ([]string, error) { name, err := GetFullContainerName(name) if err != nil { return nil, err } return daemon.containerGraph.Parents(name) } func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error { fullName := filepath.Join(parent.Name, alias) if !daemon.containerGraph.Exists(fullName) { _, err := daemon.containerGraph.Set(fullName, child.ID) return err } return nil } func NewDaemon(config *Config, registryService *registry.Service) (daemon *Daemon, err error) { setDefaultMtu(config) // Ensure we have compatible configuration options if err := checkConfigOptions(config); err != nil { return nil, err } // Do we have a disabled network? config.DisableBridge = isBridgeNetworkDisabled(config) // Verify the platform is supported as a daemon if runtime.GOOS != "linux" && runtime.GOOS != "windows" { return nil, ErrSystemNotSupported } // Validate platform-specific requirements if err := checkSystem(); err != nil { return nil, err } // set up SIGUSR1 handler on Unix-like systems, or a Win32 global event // on Windows to dump Go routine stacks setupDumpStackTrap() // get the canonical path to the Docker root directory var realRoot string if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) { realRoot = config.Root } else { realRoot, err = fileutils.ReadSymlinkedDirectory(config.Root) if err != nil { return nil, fmt.Errorf("Unable to get the full path to root (%s): %s", config.Root, err) } } config.Root = realRoot // Create the root directory if it doesn't exists if err := system.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) { return nil, err } // set up the tmpDir to use a canonical path tmp, err := tempDir(config.Root) if err != nil { return nil, fmt.Errorf("Unable to get the TempDir under %s: %s", config.Root, err) } realTmp, err := fileutils.ReadSymlinkedDirectory(tmp) if err != nil { return nil, fmt.Errorf("Unable to get the full path to the TempDir (%s): %s", tmp, err) } os.Setenv("TMPDIR", realTmp) // Set the default driver graphdriver.DefaultDriver = config.GraphDriver // Load storage driver driver, err := graphdriver.New(config.Root, config.GraphOptions) if err != nil { return nil, fmt.Errorf("error initializing graphdriver: %v", err) } logrus.Debugf("Using graph driver %s", driver) d := &Daemon{} d.driver = driver // Ensure the graph driver is shutdown at a later point defer func() { if err != nil { if err := d.Shutdown(); err != nil { logrus.Error(err) } } }() // Verify logging driver type if config.LogConfig.Type != "none" { if _, err := logger.GetLogDriver(config.LogConfig.Type); err != nil { return nil, fmt.Errorf("error finding the logging driver: %v", err) } } logrus.Debugf("Using default logging driver %s", config.LogConfig.Type) // Configure and validate the kernels security support if err := configureKernelSecuritySupport(config, d.driver.String()); err != nil { return nil, err } daemonRepo := filepath.Join(config.Root, "containers") if err := system.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) { return nil, err } // Migrate the container if it is aufs and aufs is enabled if err := migrateIfDownlevel(d.driver, config.Root); err != nil { return nil, err } logrus.Debug("Creating images graph") g, err := graph.NewGraph(filepath.Join(config.Root, "graph"), d.driver) if err != nil { return nil, err } // Configure the volumes driver if err := configureVolumes(config); err != nil { return nil, err } trustKey, err := api.LoadOrCreateTrustKey(config.TrustKeyPath) if err != nil { return nil, err } trustDir := filepath.Join(config.Root, "trust") if err := system.MkdirAll(trustDir, 0700); err != nil && !os.IsExist(err) { return nil, err } trustService, err := trust.NewTrustStore(trustDir) if err != nil { return nil, fmt.Errorf("could not create trust store: %s", err) } eventsService := events.New() logrus.Debug("Creating repository list") tagCfg := &graph.TagStoreConfig{ Graph: g, Key: trustKey, Registry: registryService, Events: eventsService, Trust: trustService, } repositories, err := graph.NewTagStore(filepath.Join(config.Root, "repositories-"+d.driver.String()), tagCfg) if err != nil { return nil, fmt.Errorf("Couldn't create Tag store: %s", err) } d.netController, err = initNetworkController(config) if err != nil { return nil, fmt.Errorf("Error initializing network controller: %v", err) } graphdbPath := filepath.Join(config.Root, "linkgraph.db") graph, err := graphdb.NewSqliteConn(graphdbPath) if err != nil { return nil, err } d.containerGraph = graph var sysInitPath string if config.ExecDriver == "lxc" { initPath, err := configureSysInit(config) if err != nil { return nil, err } sysInitPath = initPath } sysInfo := sysinfo.New(false) // Check if Devices cgroup is mounted, it is hard requirement for container security, // on Linux/FreeBSD. if runtime.GOOS != "windows" && !sysInfo.CgroupDevicesEnabled { return nil, fmt.Errorf("Devices cgroup isn't mounted") } ed, err := execdrivers.NewDriver(config.ExecDriver, config.ExecOptions, config.ExecRoot, config.Root, sysInitPath, sysInfo) if err != nil { return nil, err } d.ID = trustKey.PublicKey().KeyID() d.repository = daemonRepo d.containers = &contStore{s: make(map[string]*Container)} d.execCommands = newExecStore() d.graph = g d.repositories = repositories d.idIndex = truncindex.NewTruncIndex([]string{}) d.sysInfo = sysInfo d.config = config d.sysInitPath = sysInitPath d.execDriver = ed d.statsCollector = newStatsCollector(1 * time.Second) d.defaultLogConfig = config.LogConfig d.RegistryService = registryService d.EventsService = eventsService d.root = config.Root go d.execCommandGC() if err := d.restore(); err != nil { return nil, err } return d, nil } func (daemon *Daemon) Shutdown() error { if daemon.containers != nil { group := sync.WaitGroup{} logrus.Debug("starting clean shutdown of all containers...") for _, container := range daemon.List() { c := container if c.IsRunning() { logrus.Debugf("stopping %s", c.ID) group.Add(1) go func() { defer group.Done() // If container failed to exit in 10 seconds of SIGTERM, then using the force if err := c.Stop(10); err != nil { logrus.Errorf("Stop container %s with error: %v", c.ID, err) } c.WaitStop(-1 * time.Second) logrus.Debugf("container stopped %s", c.ID) }() } } group.Wait() // trigger libnetwork GC only if it's initialized if daemon.netController != nil { daemon.netController.GC() } } if daemon.containerGraph != nil { if err := daemon.containerGraph.Close(); err != nil { logrus.Errorf("Error during container graph.Close(): %v", err) } } if daemon.driver != nil { if err := daemon.driver.Cleanup(); err != nil { logrus.Errorf("Error during graph storage driver.Cleanup(): %v", err) } } return nil } func (daemon *Daemon) Mount(container *Container) error { dir, err := daemon.driver.Get(container.ID, container.GetMountLabel()) if err != nil { return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err) } if container.basefs != dir { // The mount path reported by the graph driver should always be trusted on Windows, since the // volume path for a given mounted layer may change over time. This should only be an error // on non-Windows operating systems. if container.basefs != "" && runtime.GOOS != "windows" { daemon.driver.Put(container.ID) return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')", daemon.driver, container.ID, container.basefs, dir) } } container.basefs = dir return nil } func (daemon *Daemon) Unmount(container *Container) error { daemon.driver.Put(container.ID) return nil } func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { return daemon.execDriver.Run(c.command, pipes, startCallback) } func (daemon *Daemon) Kill(c *Container, sig int) error { return daemon.execDriver.Kill(c.command, sig) } func (daemon *Daemon) Stats(c *Container) (*execdriver.ResourceStats, error) { return daemon.execDriver.Stats(c.ID) } func (daemon *Daemon) SubscribeToContainerStats(name string) (chan interface{}, error) { c, err := daemon.Get(name) if err != nil { return nil, err } ch := daemon.statsCollector.collect(c) return ch, nil } func (daemon *Daemon) UnsubscribeToContainerStats(name string, ch chan interface{}) error { c, err := daemon.Get(name) if err != nil { return err } daemon.statsCollector.unsubscribe(c, ch) return nil } // FIXME: this is a convenience function for integration tests // which need direct access to daemon.graph. // Once the tests switch to using engine and jobs, this method // can go away. func (daemon *Daemon) Graph() *graph.Graph { return daemon.graph } func (daemon *Daemon) Repositories() *graph.TagStore { return daemon.repositories } func (daemon *Daemon) Config() *Config { return daemon.config } func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo { return daemon.sysInfo } func (daemon *Daemon) SystemInitPath() string { return daemon.sysInitPath } func (daemon *Daemon) GraphDriver() graphdriver.Driver { return daemon.driver } func (daemon *Daemon) ExecutionDriver() execdriver.Driver { return daemon.execDriver } func (daemon *Daemon) ContainerGraph() *graphdb.Database { return daemon.containerGraph } func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) { // Retrieve all images images := daemon.Graph().Map() // Store the tree in a map of map (map[parentId][childId]) imageMap := make(map[string]map[string]struct{}) for _, img := range images { if _, exists := imageMap[img.Parent]; !exists { imageMap[img.Parent] = make(map[string]struct{}) } imageMap[img.Parent][img.ID] = struct{}{} } // Loop on the children of the given image and check the config var match *image.Image for elem := range imageMap[imgID] { img, ok := images[elem] if !ok { return nil, fmt.Errorf("unable to find image %q", elem) } if runconfig.Compare(&img.ContainerConfig, config) { if match == nil || match.Created.Before(img.Created) { match = img } } } return match, nil } // tempDir returns the default directory to use for temporary files. func tempDir(rootDir string) (string, error) { var tmpDir string if tmpDir = os.Getenv("DOCKER_TMPDIR"); tmpDir == "" { tmpDir = filepath.Join(rootDir, "tmp") } return tmpDir, system.MkdirAll(tmpDir, 0700) } func (daemon *Daemon) setHostConfig(container *Container, hostConfig *runconfig.HostConfig) error { container.Lock() if err := parseSecurityOpt(container, hostConfig); err != nil { container.Unlock() return err } container.Unlock() // Do not lock while creating volumes since this could be calling out to external plugins // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin if err := daemon.registerMountPoints(container, hostConfig); err != nil { return err } container.Lock() defer container.Unlock() // Register any links from the host config before starting the container if err := daemon.RegisterLinks(container, hostConfig); err != nil { return err } container.hostConfig = hostConfig container.toDisk() return nil } func (daemon *Daemon) newBaseContainer(id string) CommonContainer { return CommonContainer{ ID: id, State: NewState(), MountPoints: make(map[string]*mountPoint), Volumes: make(map[string]string), VolumesRW: make(map[string]bool), execCommands: newExecStore(), root: daemon.containerRoot(id), } } func setDefaultMtu(config *Config) { // do nothing if the config does not have the default 0 value. if config.Mtu != 0 { return } config.Mtu = defaultNetworkMtu if routeMtu, err := getDefaultRouteMtu(); err == nil { config.Mtu = routeMtu } } var errNoDefaultRoute = errors.New("no default route was found") // getDefaultRouteMtu returns the MTU for the default route's interface. func getDefaultRouteMtu() (int, error) { routes, err := netlink.NetworkGetRoutes() if err != nil { return 0, err } for _, r := range routes { if r.Default { return r.Iface.MTU, nil } } return 0, errNoDefaultRoute } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_aufs.go ================================================ // +build !exclude_graphdriver_aufs,linux package daemon import ( "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/daemon/graphdriver/aufs" ) // Given the graphdriver ad, if it is aufs, then migrate it. // If aufs driver is not built, this func is a noop. func migrateIfAufs(driver graphdriver.Driver, root string) error { if ad, ok := driver.(*aufs.Driver); ok { logrus.Debugf("Migrating existing containers") if err := ad.Migrate(root, setupInitLayer); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_btrfs.go ================================================ // +build !exclude_graphdriver_btrfs,linux package daemon import ( _ "github.com/docker/docker/daemon/graphdriver/btrfs" ) ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_devicemapper.go ================================================ // +build !exclude_graphdriver_devicemapper,linux package daemon import ( _ "github.com/docker/docker/daemon/graphdriver/devmapper" ) ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_no_aufs.go ================================================ // +build exclude_graphdriver_aufs,linux package daemon import ( "github.com/docker/docker/daemon/graphdriver" ) func migrateIfAufs(driver graphdriver.Driver, root string) error { return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_overlay.go ================================================ // +build !exclude_graphdriver_overlay,linux package daemon import ( _ "github.com/docker/docker/daemon/graphdriver/overlay" ) ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_test.go ================================================ package daemon import ( "fmt" "io/ioutil" "os" "path" "path/filepath" "testing" "github.com/docker/docker/pkg/graphdb" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/truncindex" "github.com/docker/docker/volume" "github.com/docker/docker/volume/drivers" "github.com/docker/docker/volume/local" ) // // https://github.com/docker/docker/issues/8069 // func TestGet(t *testing.T) { c1 := &Container{ CommonContainer: CommonContainer{ ID: "5a4ff6a163ad4533d22d69a2b8960bf7fafdcba06e72d2febdba229008b0bf57", Name: "tender_bardeen", }, } c2 := &Container{ CommonContainer: CommonContainer{ ID: "3cdbd1aa394fd68559fd1441d6eff2ab7c1e6363582c82febfaa8045df3bd8de", Name: "drunk_hawking", }, } c3 := &Container{ CommonContainer: CommonContainer{ ID: "3cdbd1aa394fd68559fd1441d6eff2abfafdcba06e72d2febdba229008b0bf57", Name: "3cdbd1aa", }, } c4 := &Container{ CommonContainer: CommonContainer{ ID: "75fb0b800922abdbef2d27e60abcdfaf7fb0698b2a96d22d3354da361a6ff4a5", Name: "5a4ff6a163ad4533d22d69a2b8960bf7fafdcba06e72d2febdba229008b0bf57", }, } c5 := &Container{ CommonContainer: CommonContainer{ ID: "d22d69a2b8960bf7fafdcba06e72d2febdba960bf7fafdcba06e72d2f9008b060b", Name: "d22d69a2b896", }, } store := &contStore{ s: map[string]*Container{ c1.ID: c1, c2.ID: c2, c3.ID: c3, c4.ID: c4, c5.ID: c5, }, } index := truncindex.NewTruncIndex([]string{}) index.Add(c1.ID) index.Add(c2.ID) index.Add(c3.ID) index.Add(c4.ID) index.Add(c5.ID) daemonTestDbPath := path.Join(os.TempDir(), "daemon_test.db") graph, err := graphdb.NewSqliteConn(daemonTestDbPath) if err != nil { t.Fatalf("Failed to create daemon test sqlite database at %s", daemonTestDbPath) } graph.Set(c1.Name, c1.ID) graph.Set(c2.Name, c2.ID) graph.Set(c3.Name, c3.ID) graph.Set(c4.Name, c4.ID) graph.Set(c5.Name, c5.ID) daemon := &Daemon{ containers: store, idIndex: index, containerGraph: graph, } if container, _ := daemon.Get("3cdbd1aa394fd68559fd1441d6eff2ab7c1e6363582c82febfaa8045df3bd8de"); container != c2 { t.Fatal("Should explicitly match full container IDs") } if container, _ := daemon.Get("75fb0b8009"); container != c4 { t.Fatal("Should match a partial ID") } if container, _ := daemon.Get("drunk_hawking"); container != c2 { t.Fatal("Should match a full name") } // c3.Name is a partial match for both c3.ID and c2.ID if c, _ := daemon.Get("3cdbd1aa"); c != c3 { t.Fatal("Should match a full name even though it collides with another container's ID") } if container, _ := daemon.Get("d22d69a2b896"); container != c5 { t.Fatal("Should match a container where the provided prefix is an exact match to the it's name, and is also a prefix for it's ID") } if _, err := daemon.Get("3cdbd1"); err == nil { t.Fatal("Should return an error when provided a prefix that partially matches multiple container ID's") } if _, err := daemon.Get("nothing"); err == nil { t.Fatal("Should return an error when provided a prefix that is neither a name or a partial match to an ID") } os.Remove(daemonTestDbPath) } func TestLoadWithVolume(t *testing.T) { tmp, err := ioutil.TempDir("", "docker-daemon-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) containerId := "d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e" containerPath := filepath.Join(tmp, containerId) if err := os.MkdirAll(containerPath, 0755); err != nil { t.Fatal(err) } hostVolumeId := stringid.GenerateRandomID() vfsPath := filepath.Join(tmp, "vfs", "dir", hostVolumeId) volumePath := filepath.Join(tmp, "volumes", hostVolumeId) if err := os.MkdirAll(vfsPath, 0755); err != nil { t.Fatal(err) } if err := os.MkdirAll(volumePath, 0755); err != nil { t.Fatal(err) } content := filepath.Join(vfsPath, "helo") if err := ioutil.WriteFile(content, []byte("HELO"), 0644); err != nil { t.Fatal(err) } config := `{"State":{"Running":true,"Paused":false,"Restarting":false,"OOMKilled":false,"Dead":false,"Pid":2464,"ExitCode":0, "Error":"","StartedAt":"2015-05-26T16:48:53.869308965Z","FinishedAt":"0001-01-01T00:00:00Z"}, "ID":"d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e","Created":"2015-05-26T16:48:53.7987917Z","Path":"top", "Args":[],"Config":{"Hostname":"d59df5276e7b","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"Cpuset":"", "AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"PortSpecs":null,"ExposedPorts":null,"Tty":true,"OpenStdin":true, "StdinOnce":false,"Env":null,"Cmd":["top"],"Image":"ubuntu:latest","Volumes":null,"WorkingDir":"","Entrypoint":null, "NetworkDisabled":false,"MacAddress":"","OnBuild":null,"Labels":{}},"Image":"07f8e8c5e66084bef8f848877857537ffe1c47edd01a93af27e7161672ad0e95", "NetworkSettings":{"IPAddress":"172.17.0.1","IPPrefixLen":16,"MacAddress":"02:42:ac:11:00:01","LinkLocalIPv6Address":"fe80::42:acff:fe11:1", "LinkLocalIPv6PrefixLen":64,"GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"Gateway":"172.17.42.1","IPv6Gateway":"","Bridge":"docker0","PortMapping":null,"Ports":{}}, "ResolvConfPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/resolv.conf", "HostnamePath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hostname", "HostsPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hosts", "LogPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e-json.log", "Name":"/ubuntu","Driver":"aufs","ExecDriver":"native-0.2","MountLabel":"","ProcessLabel":"","AppArmorProfile":"","RestartCount":0, "UpdateDns":false,"Volumes":{"/vol1":"%s"},"VolumesRW":{"/vol1":true},"AppliedVolumesFrom":null}` cfg := fmt.Sprintf(config, vfsPath) if err = ioutil.WriteFile(filepath.Join(containerPath, "config.json"), []byte(cfg), 0644); err != nil { t.Fatal(err) } hostConfig := `{"Binds":[],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` if err = ioutil.WriteFile(filepath.Join(containerPath, "hostconfig.json"), []byte(hostConfig), 0644); err != nil { t.Fatal(err) } daemon, err := initDaemonForVolumesTest(tmp) if err != nil { t.Fatal(err) } defer volumedrivers.Unregister(volume.DefaultDriverName) c, err := daemon.load(containerId) if err != nil { t.Fatal(err) } err = daemon.verifyVolumesInfo(c) if err != nil { t.Fatal(err) } if len(c.MountPoints) != 1 { t.Fatalf("Expected 1 volume mounted, was 0\n") } m := c.MountPoints["/vol1"] if m.Name != hostVolumeId { t.Fatalf("Expected mount name to be %s, was %s\n", hostVolumeId, m.Name) } if m.Destination != "/vol1" { t.Fatalf("Expected mount destination /vol1, was %s\n", m.Destination) } if !m.RW { t.Fatalf("Expected mount point to be RW but it was not\n") } if m.Driver != volume.DefaultDriverName { t.Fatalf("Expected mount driver local, was %s\n", m.Driver) } newVolumeContent := filepath.Join(volumePath, local.VolumeDataPathName, "helo") b, err := ioutil.ReadFile(newVolumeContent) if err != nil { t.Fatal(err) } if string(b) != "HELO" { t.Fatalf("Expected HELO, was %s\n", string(b)) } } func TestLoadWithBindMount(t *testing.T) { tmp, err := ioutil.TempDir("", "docker-daemon-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) containerId := "d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e" containerPath := filepath.Join(tmp, containerId) if err = os.MkdirAll(containerPath, 0755); err != nil { t.Fatal(err) } config := `{"State":{"Running":true,"Paused":false,"Restarting":false,"OOMKilled":false,"Dead":false,"Pid":2464,"ExitCode":0, "Error":"","StartedAt":"2015-05-26T16:48:53.869308965Z","FinishedAt":"0001-01-01T00:00:00Z"}, "ID":"d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e","Created":"2015-05-26T16:48:53.7987917Z","Path":"top", "Args":[],"Config":{"Hostname":"d59df5276e7b","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"Cpuset":"", "AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"PortSpecs":null,"ExposedPorts":null,"Tty":true,"OpenStdin":true, "StdinOnce":false,"Env":null,"Cmd":["top"],"Image":"ubuntu:latest","Volumes":null,"WorkingDir":"","Entrypoint":null, "NetworkDisabled":false,"MacAddress":"","OnBuild":null,"Labels":{}},"Image":"07f8e8c5e66084bef8f848877857537ffe1c47edd01a93af27e7161672ad0e95", "NetworkSettings":{"IPAddress":"172.17.0.1","IPPrefixLen":16,"MacAddress":"02:42:ac:11:00:01","LinkLocalIPv6Address":"fe80::42:acff:fe11:1", "LinkLocalIPv6PrefixLen":64,"GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"Gateway":"172.17.42.1","IPv6Gateway":"","Bridge":"docker0","PortMapping":null,"Ports":{}}, "ResolvConfPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/resolv.conf", "HostnamePath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hostname", "HostsPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hosts", "LogPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e-json.log", "Name":"/ubuntu","Driver":"aufs","ExecDriver":"native-0.2","MountLabel":"","ProcessLabel":"","AppArmorProfile":"","RestartCount":0, "UpdateDns":false,"Volumes":{"/vol1": "/vol1"},"VolumesRW":{"/vol1":true},"AppliedVolumesFrom":null}` if err = ioutil.WriteFile(filepath.Join(containerPath, "config.json"), []byte(config), 0644); err != nil { t.Fatal(err) } hostConfig := `{"Binds":["/vol1:/vol1"],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` if err = ioutil.WriteFile(filepath.Join(containerPath, "hostconfig.json"), []byte(hostConfig), 0644); err != nil { t.Fatal(err) } daemon, err := initDaemonForVolumesTest(tmp) if err != nil { t.Fatal(err) } defer volumedrivers.Unregister(volume.DefaultDriverName) c, err := daemon.load(containerId) if err != nil { t.Fatal(err) } err = daemon.verifyVolumesInfo(c) if err != nil { t.Fatal(err) } if len(c.MountPoints) != 1 { t.Fatalf("Expected 1 volume mounted, was 0\n") } m := c.MountPoints["/vol1"] if m.Name != "" { t.Fatalf("Expected empty mount name, was %s\n", m.Name) } if m.Source != "/vol1" { t.Fatalf("Expected mount source /vol1, was %s\n", m.Source) } if m.Destination != "/vol1" { t.Fatalf("Expected mount destination /vol1, was %s\n", m.Destination) } if !m.RW { t.Fatalf("Expected mount point to be RW but it was not\n") } } func TestLoadWithVolume17RC(t *testing.T) { tmp, err := ioutil.TempDir("", "docker-daemon-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) containerId := "d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e" containerPath := filepath.Join(tmp, containerId) if err := os.MkdirAll(containerPath, 0755); err != nil { t.Fatal(err) } hostVolumeId := "6a3c03fc4a4e588561a543cc3bdd50089e27bd11bbb0e551e19bf735e2514101" volumePath := filepath.Join(tmp, "volumes", hostVolumeId) if err := os.MkdirAll(volumePath, 0755); err != nil { t.Fatal(err) } content := filepath.Join(volumePath, "helo") if err := ioutil.WriteFile(content, []byte("HELO"), 0644); err != nil { t.Fatal(err) } config := `{"State":{"Running":true,"Paused":false,"Restarting":false,"OOMKilled":false,"Dead":false,"Pid":2464,"ExitCode":0, "Error":"","StartedAt":"2015-05-26T16:48:53.869308965Z","FinishedAt":"0001-01-01T00:00:00Z"}, "ID":"d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e","Created":"2015-05-26T16:48:53.7987917Z","Path":"top", "Args":[],"Config":{"Hostname":"d59df5276e7b","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"Cpuset":"", "AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"PortSpecs":null,"ExposedPorts":null,"Tty":true,"OpenStdin":true, "StdinOnce":false,"Env":null,"Cmd":["top"],"Image":"ubuntu:latest","Volumes":null,"WorkingDir":"","Entrypoint":null, "NetworkDisabled":false,"MacAddress":"","OnBuild":null,"Labels":{}},"Image":"07f8e8c5e66084bef8f848877857537ffe1c47edd01a93af27e7161672ad0e95", "NetworkSettings":{"IPAddress":"172.17.0.1","IPPrefixLen":16,"MacAddress":"02:42:ac:11:00:01","LinkLocalIPv6Address":"fe80::42:acff:fe11:1", "LinkLocalIPv6PrefixLen":64,"GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"Gateway":"172.17.42.1","IPv6Gateway":"","Bridge":"docker0","PortMapping":null,"Ports":{}}, "ResolvConfPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/resolv.conf", "HostnamePath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hostname", "HostsPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hosts", "LogPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e-json.log", "Name":"/ubuntu","Driver":"aufs","ExecDriver":"native-0.2","MountLabel":"","ProcessLabel":"","AppArmorProfile":"","RestartCount":0, "UpdateDns":false,"MountPoints":{"/vol1":{"Name":"6a3c03fc4a4e588561a543cc3bdd50089e27bd11bbb0e551e19bf735e2514101","Destination":"/vol1","Driver":"local","RW":true,"Source":"","Relabel":""}},"AppliedVolumesFrom":null}` if err = ioutil.WriteFile(filepath.Join(containerPath, "config.json"), []byte(config), 0644); err != nil { t.Fatal(err) } hostConfig := `{"Binds":[],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` if err = ioutil.WriteFile(filepath.Join(containerPath, "hostconfig.json"), []byte(hostConfig), 0644); err != nil { t.Fatal(err) } daemon, err := initDaemonForVolumesTest(tmp) if err != nil { t.Fatal(err) } defer volumedrivers.Unregister(volume.DefaultDriverName) c, err := daemon.load(containerId) if err != nil { t.Fatal(err) } err = daemon.verifyVolumesInfo(c) if err != nil { t.Fatal(err) } if len(c.MountPoints) != 1 { t.Fatalf("Expected 1 volume mounted, was 0\n") } m := c.MountPoints["/vol1"] if m.Name != hostVolumeId { t.Fatalf("Expected mount name to be %s, was %s\n", hostVolumeId, m.Name) } if m.Destination != "/vol1" { t.Fatalf("Expected mount destination /vol1, was %s\n", m.Destination) } if !m.RW { t.Fatalf("Expected mount point to be RW but it was not\n") } if m.Driver != volume.DefaultDriverName { t.Fatalf("Expected mount driver local, was %s\n", m.Driver) } newVolumeContent := filepath.Join(volumePath, local.VolumeDataPathName, "helo") b, err := ioutil.ReadFile(newVolumeContent) if err != nil { t.Fatal(err) } if string(b) != "HELO" { t.Fatalf("Expected HELO, was %s\n", string(b)) } } func TestRemoveLocalVolumesFollowingSymlinks(t *testing.T) { tmp, err := ioutil.TempDir("", "docker-daemon-test-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) containerId := "d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e" containerPath := filepath.Join(tmp, containerId) if err := os.MkdirAll(containerPath, 0755); err != nil { t.Fatal(err) } hostVolumeId := stringid.GenerateRandomID() vfsPath := filepath.Join(tmp, "vfs", "dir", hostVolumeId) volumePath := filepath.Join(tmp, "volumes", hostVolumeId) if err := os.MkdirAll(vfsPath, 0755); err != nil { t.Fatal(err) } if err := os.MkdirAll(volumePath, 0755); err != nil { t.Fatal(err) } content := filepath.Join(vfsPath, "helo") if err := ioutil.WriteFile(content, []byte("HELO"), 0644); err != nil { t.Fatal(err) } config := `{"State":{"Running":true,"Paused":false,"Restarting":false,"OOMKilled":false,"Dead":false,"Pid":2464,"ExitCode":0, "Error":"","StartedAt":"2015-05-26T16:48:53.869308965Z","FinishedAt":"0001-01-01T00:00:00Z"}, "ID":"d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e","Created":"2015-05-26T16:48:53.7987917Z","Path":"top", "Args":[],"Config":{"Hostname":"d59df5276e7b","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"Cpuset":"", "AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"PortSpecs":null,"ExposedPorts":null,"Tty":true,"OpenStdin":true, "StdinOnce":false,"Env":null,"Cmd":["top"],"Image":"ubuntu:latest","Volumes":null,"WorkingDir":"","Entrypoint":null, "NetworkDisabled":false,"MacAddress":"","OnBuild":null,"Labels":{}},"Image":"07f8e8c5e66084bef8f848877857537ffe1c47edd01a93af27e7161672ad0e95", "NetworkSettings":{"IPAddress":"172.17.0.1","IPPrefixLen":16,"MacAddress":"02:42:ac:11:00:01","LinkLocalIPv6Address":"fe80::42:acff:fe11:1", "LinkLocalIPv6PrefixLen":64,"GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"Gateway":"172.17.42.1","IPv6Gateway":"","Bridge":"docker0","PortMapping":null,"Ports":{}}, "ResolvConfPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/resolv.conf", "HostnamePath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hostname", "HostsPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/hosts", "LogPath":"/var/lib/docker/containers/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e/d59df5276e7b219d510fe70565e0404bc06350e0d4b43fe961f22f339980170e-json.log", "Name":"/ubuntu","Driver":"aufs","ExecDriver":"native-0.2","MountLabel":"","ProcessLabel":"","AppArmorProfile":"","RestartCount":0, "UpdateDns":false,"Volumes":{"/vol1":"%s"},"VolumesRW":{"/vol1":true},"AppliedVolumesFrom":null}` cfg := fmt.Sprintf(config, vfsPath) if err = ioutil.WriteFile(filepath.Join(containerPath, "config.json"), []byte(cfg), 0644); err != nil { t.Fatal(err) } hostConfig := `{"Binds":[],"ContainerIDFile":"","LxcConf":[],"Memory":0,"MemorySwap":0,"CpuShares":0,"CpusetCpus":"", "Privileged":false,"PortBindings":{},"Links":null,"PublishAllPorts":false,"Dns":null,"DnsSearch":null,"ExtraHosts":null,"VolumesFrom":null, "Devices":[],"NetworkMode":"bridge","IpcMode":"","PidMode":"","CapAdd":null,"CapDrop":null,"RestartPolicy":{"Name":"no","MaximumRetryCount":0}, "SecurityOpt":null,"ReadonlyRootfs":false,"Ulimits":null,"LogConfig":{"Type":"","Config":null},"CgroupParent":""}` if err = ioutil.WriteFile(filepath.Join(containerPath, "hostconfig.json"), []byte(hostConfig), 0644); err != nil { t.Fatal(err) } daemon, err := initDaemonForVolumesTest(tmp) if err != nil { t.Fatal(err) } defer volumedrivers.Unregister(volume.DefaultDriverName) c, err := daemon.load(containerId) if err != nil { t.Fatal(err) } err = daemon.verifyVolumesInfo(c) if err != nil { t.Fatal(err) } if len(c.MountPoints) != 1 { t.Fatalf("Expected 1 volume mounted, was 0\n") } m := c.MountPoints["/vol1"] v, err := createVolume(m.Name, m.Driver) if err != nil { t.Fatal(err) } if err := removeVolume(v); err != nil { t.Fatal(err) } fi, err := os.Stat(vfsPath) if err == nil || !os.IsNotExist(err) { t.Fatalf("Expected vfs path to not exist: %v - %v\n", fi, err) } } func initDaemonForVolumesTest(tmp string) (*Daemon, error) { daemon := &Daemon{ repository: tmp, root: tmp, } volumesDriver, err := local.New(tmp) if err != nil { return nil, err } volumedrivers.Register(volumesDriver, volumesDriver.Name()) return daemon, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_unit_test.go ================================================ package daemon import ( "testing" "github.com/docker/docker/runconfig" ) func TestParseSecurityOpt(t *testing.T) { container := &Container{} config := &runconfig.HostConfig{} // test apparmor config.SecurityOpt = []string{"apparmor:test_profile"} if err := parseSecurityOpt(container, config); err != nil { t.Fatalf("Unexpected parseSecurityOpt error: %v", err) } if container.AppArmorProfile != "test_profile" { t.Fatalf("Unexpected AppArmorProfile, expected: \"test_profile\", got %q", container.AppArmorProfile) } // test valid label config.SecurityOpt = []string{"label:user:USER"} if err := parseSecurityOpt(container, config); err != nil { t.Fatalf("Unexpected parseSecurityOpt error: %v", err) } // test invalid label config.SecurityOpt = []string{"label"} if err := parseSecurityOpt(container, config); err == nil { t.Fatal("Expected parseSecurityOpt error, got nil") } // test invalid opt config.SecurityOpt = []string{"test"} if err := parseSecurityOpt(container, config); err == nil { t.Fatal("Expected parseSecurityOpt error, got nil") } } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_unix.go ================================================ // +build !windows package daemon import ( "fmt" "net" "net/http" "os" "path/filepath" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/system" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" volumedrivers "github.com/docker/docker/volume/drivers" "github.com/docker/docker/volume/local" "github.com/docker/libnetwork" nwapi "github.com/docker/libnetwork/api" nwconfig "github.com/docker/libnetwork/config" "github.com/docker/libnetwork/netlabel" "github.com/docker/libnetwork/options" "github.com/opencontainers/runc/libcontainer/label" ) func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) { initID := fmt.Sprintf("%s-init", container.ID) return daemon.driver.Changes(container.ID, initID) } func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) { initID := fmt.Sprintf("%s-init", container.ID) return daemon.driver.Diff(container.ID, initID) } func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error { var ( labelOpts []string err error ) for _, opt := range config.SecurityOpt { con := strings.SplitN(opt, ":", 2) if len(con) == 1 { return fmt.Errorf("Invalid --security-opt: %q", opt) } switch con[0] { case "label": labelOpts = append(labelOpts, con[1]) case "apparmor": container.AppArmorProfile = con[1] default: return fmt.Errorf("Invalid --security-opt: %q", opt) } } container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts) return err } func (daemon *Daemon) createRootfs(container *Container) error { // Step 1: create the container directory. // This doubles as a barrier to avoid race conditions. if err := os.Mkdir(container.root, 0700); err != nil { return err } initID := fmt.Sprintf("%s-init", container.ID) if err := daemon.driver.Create(initID, container.ImageID); err != nil { return err } initPath, err := daemon.driver.Get(initID, "") if err != nil { return err } defer daemon.driver.Put(initID) if err := setupInitLayer(initPath); err != nil { return err } if err := daemon.driver.Create(container.ID, initID); err != nil { return err } return nil } func checkKernel() error { // Check for unsupported kernel versions // FIXME: it would be cleaner to not test for specific versions, but rather // test for specific functionalities. // Unfortunately we can't test for the feature "does not cause a kernel panic" // without actually causing a kernel panic, so we need this workaround until // the circumstances of pre-3.10 crashes are clearer. // For details see https://github.com/docker/docker/issues/407 if k, err := kernel.GetKernelVersion(); err != nil { logrus.Warnf("%s", err) } else { if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 10, Minor: 0}) < 0 { if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" { logrus.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.10.0.", k.String()) } } } return nil } func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { var warnings []string if config != nil { // The check for a valid workdir path is made on the server rather than in the // client. This is because we don't know the type of path (Linux or Windows) // to validate on the client. if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) { return warnings, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir) } } if hostConfig == nil { return warnings, nil } for port := range hostConfig.PortBindings { _, portStr := nat.SplitProtoPort(string(port)) if _, err := nat.ParsePort(portStr); err != nil { return warnings, fmt.Errorf("Invalid port specification: %q", portStr) } for _, pb := range hostConfig.PortBindings[port] { _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort)) if err != nil { return warnings, fmt.Errorf("Invalid port specification: %q", pb.HostPort) } } } if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") { return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name()) } if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 { return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB") } if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit { warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.") logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.") hostConfig.Memory = 0 } if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit { warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.") logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.") hostConfig.MemorySwap = -1 } if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory { return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.") } if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 { return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.") } if hostConfig.MemorySwappiness != -1 && !daemon.SystemConfig().MemorySwappiness { warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.") logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.") hostConfig.MemorySwappiness = -1 } if hostConfig.MemorySwappiness != -1 && (hostConfig.MemorySwappiness < 0 || hostConfig.MemorySwappiness > 100) { return warnings, fmt.Errorf("Invalid value: %d, valid memory swappiness range is 0-100.", hostConfig.MemorySwappiness) } if hostConfig.CpuPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod { warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.") logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.") hostConfig.CpuPeriod = 0 } if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota { warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.") logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.") hostConfig.CpuQuota = 0 } if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) { return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.") } if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable { hostConfig.OomKillDisable = false return warnings, fmt.Errorf("Your kernel does not support oom kill disable.") } if daemon.SystemConfig().IPv4ForwardingDisabled { warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.") logrus.Warnf("IPv4 forwarding is disabled. Networking will not work") } return warnings, nil } // checkConfigOptions checks for mutually incompatible config options func checkConfigOptions(config *Config) error { // Check for mutually incompatible config options if config.Bridge.Iface != "" && config.Bridge.IP != "" { return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.") } if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication { return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.") } if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq { config.Bridge.EnableIPMasq = false } return nil } // checkSystem validates platform-specific requirements func checkSystem() error { if os.Geteuid() != 0 { return fmt.Errorf("The Docker daemon needs to be run as root") } if err := checkKernel(); err != nil { return err } return nil } // configureKernelSecuritySupport configures and validate security support for the kernel func configureKernelSecuritySupport(config *Config, driverName string) error { if config.EnableSelinuxSupport { if selinuxEnabled() { // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled if driverName == "btrfs" { return fmt.Errorf("SELinux is not supported with the BTRFS graph driver") } logrus.Debug("SELinux enabled successfully") } else { logrus.Warn("Docker could not enable SELinux on the host system") } } else { selinuxSetDisabled() } return nil } // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel func migrateIfDownlevel(driver graphdriver.Driver, root string) error { return migrateIfAufs(driver, root) } func configureVolumes(config *Config) error { volumesDriver, err := local.New(config.Root) if err != nil { return err } volumedrivers.Register(volumesDriver, volumesDriver.Name()) return nil } func configureSysInit(config *Config) (string, error) { localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION)) sysInitPath := utils.DockerInitPath(localCopy) if sysInitPath == "" { return "", fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See https://docs.docker.com/contributing/devenvironment for official build instructions.") } if sysInitPath != localCopy { // When we find a suitable dockerinit binary (even if it's our local binary), we copy it into config.Root at localCopy for future use (so that the original can go away without that being a problem, for example during a package upgrade). if err := os.Mkdir(filepath.Dir(localCopy), 0700); err != nil && !os.IsExist(err) { return "", err } if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil { return "", err } if err := os.Chmod(localCopy, 0700); err != nil { return "", err } sysInitPath = localCopy } return sysInitPath, nil } func isBridgeNetworkDisabled(config *Config) bool { return config.Bridge.Iface == disableNetworkBridge } func networkOptions(dconfig *Config) ([]nwconfig.Option, error) { options := []nwconfig.Option{} if dconfig == nil { return options, nil } if strings.TrimSpace(dconfig.DefaultNetwork) != "" { dn := strings.Split(dconfig.DefaultNetwork, ":") if len(dn) < 2 { return nil, fmt.Errorf("default network daemon config must be of the form NETWORKDRIVER:NETWORKNAME") } options = append(options, nwconfig.OptionDefaultDriver(dn[0])) options = append(options, nwconfig.OptionDefaultNetwork(strings.Join(dn[1:], ":"))) } else { dd := runconfig.DefaultDaemonNetworkMode() dn := runconfig.DefaultDaemonNetworkMode().NetworkName() options = append(options, nwconfig.OptionDefaultDriver(string(dd))) options = append(options, nwconfig.OptionDefaultNetwork(dn)) } if strings.TrimSpace(dconfig.NetworkKVStore) != "" { kv := strings.Split(dconfig.NetworkKVStore, ":") if len(kv) < 2 { return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER:KV-URL") } options = append(options, nwconfig.OptionKVProvider(kv[0])) options = append(options, nwconfig.OptionKVProviderURL(strings.Join(kv[1:], ":"))) } options = append(options, nwconfig.OptionLabels(dconfig.Labels)) return options, nil } func initNetworkController(config *Config) (libnetwork.NetworkController, error) { netOptions, err := networkOptions(config) if err != nil { return nil, err } controller, err := libnetwork.New(netOptions...) if err != nil { return nil, fmt.Errorf("error obtaining controller instance: %v", err) } // Initialize default driver "null" if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil { return nil, fmt.Errorf("Error initializing null driver: %v", err) } // Initialize default network on "null" if _, err := controller.NewNetwork("null", "none"); err != nil { return nil, fmt.Errorf("Error creating default \"null\" network: %v", err) } // Initialize default driver "host" if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil { return nil, fmt.Errorf("Error initializing host driver: %v", err) } // Initialize default network on "host" if _, err := controller.NewNetwork("host", "host"); err != nil { return nil, fmt.Errorf("Error creating default \"host\" network: %v", err) } if !config.DisableBridge { // Initialize default driver "bridge" if err := initBridgeDriver(controller, config); err != nil { return nil, err } } return controller, nil } func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error { option := options.Generic{ "EnableIPForwarding": config.Bridge.EnableIPForward} if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil { return fmt.Errorf("Error initializing bridge driver: %v", err) } netOption := options.Generic{ "BridgeName": config.Bridge.Iface, "Mtu": config.Mtu, "EnableIPTables": config.Bridge.EnableIPTables, "EnableIPMasquerade": config.Bridge.EnableIPMasq, "EnableICC": config.Bridge.InterContainerCommunication, "EnableUserlandProxy": config.Bridge.EnableUserlandProxy, } if config.Bridge.IP != "" { ip, bipNet, err := net.ParseCIDR(config.Bridge.IP) if err != nil { return err } bipNet.IP = ip netOption["AddressIPv4"] = bipNet } if config.Bridge.FixedCIDR != "" { _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR) if err != nil { return err } netOption["FixedCIDR"] = fCIDR } if config.Bridge.FixedCIDRv6 != "" { _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6) if err != nil { return err } netOption["FixedCIDRv6"] = fCIDRv6 } if config.Bridge.DefaultGatewayIPv4 != nil { netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4 } if config.Bridge.DefaultGatewayIPv6 != nil { netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6 } // --ip processing if config.Bridge.DefaultIP != nil { netOption["DefaultBindingIP"] = config.Bridge.DefaultIP } // Initialize default network on "bridge" with the same name _, err := controller.NewNetwork("bridge", "bridge", libnetwork.NetworkOptionGeneric(options.Generic{ netlabel.GenericData: netOption, netlabel.EnableIPv6: config.Bridge.EnableIPv6, })) if err != nil { return fmt.Errorf("Error creating default \"bridge\" network: %v", err) } return nil } // setupInitLayer populates a directory with mountpoints suitable // for bind-mounting dockerinit into the container. The mountpoint is simply an // empty file at /.dockerinit // // This extra layer is used by all containers as the top-most ro layer. It protects // the container from unwanted side-effects on the rw layer. func setupInitLayer(initLayer string) error { for pth, typ := range map[string]string{ "/dev/pts": "dir", "/dev/shm": "dir", "/proc": "dir", "/sys": "dir", "/.dockerinit": "file", "/.dockerenv": "file", "/etc/resolv.conf": "file", "/etc/hosts": "file", "/etc/hostname": "file", "/dev/console": "file", "/etc/mtab": "/proc/mounts", } { parts := strings.Split(pth, "/") prev := "/" for _, p := range parts[1:] { prev = filepath.Join(prev, p) syscall.Unlink(filepath.Join(initLayer, prev)) } if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil { if os.IsNotExist(err) { if err := system.MkdirAll(filepath.Join(initLayer, filepath.Dir(pth)), 0755); err != nil { return err } switch typ { case "dir": if err := system.MkdirAll(filepath.Join(initLayer, pth), 0755); err != nil { return err } case "file": f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755) if err != nil { return err } f.Close() default: if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil { return err } } } else { return err } } } // Layer is ready to use, if it wasn't before. return nil } func (daemon *Daemon) NetworkApiRouter() func(w http.ResponseWriter, req *http.Request) { return nwapi.NewHTTPHandler(daemon.netController) } func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error { if hostConfig == nil || hostConfig.Links == nil { return nil } for _, l := range hostConfig.Links { name, alias, err := parsers.ParseLink(l) if err != nil { return err } child, err := daemon.Get(name) if err != nil { //An error from daemon.Get() means this name could not be found return fmt.Errorf("Could not get container for %s", name) } for child.hostConfig.NetworkMode.IsContainer() { parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2) child, err = daemon.Get(parts[1]) if err != nil { return fmt.Errorf("Could not get container for %s", parts[1]) } } if child.hostConfig.NetworkMode.IsHost() { return runconfig.ErrConflictHostNetworkAndLinks } if err := daemon.RegisterLink(container, child, alias); err != nil { return err } } // After we load all the links into the daemon // set them to nil on the hostconfig hostConfig.Links = nil if err := container.WriteHostConfig(); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_windows.go ================================================ package daemon import ( "fmt" "os" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/daemon/graphdriver/windows" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/runconfig" "github.com/docker/libnetwork" "github.com/microsoft/hcsshim" ) const DefaultVirtualSwitch = "Virtual Switch" func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) { return daemon.driver.Changes(container.ID, container.ImageID) } func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) { return daemon.driver.Diff(container.ID, container.ImageID) } func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error { return nil } func (daemon *Daemon) createRootfs(container *Container) error { // Step 1: create the container directory. // This doubles as a barrier to avoid race conditions. if err := os.Mkdir(container.root, 0700); err != nil { return err } if wd, ok := daemon.driver.(*windows.WindowsGraphDriver); ok { if container.ImageID != "" { // Get list of paths to parent layers. logrus.Debugln("createRootfs: Container has parent image:", container.ImageID) img, err := daemon.graph.Get(container.ImageID) if err != nil { return err } ids, err := daemon.graph.ParentLayerIds(img) if err != nil { return err } logrus.Debugf("Got image ids: %d", len(ids)) if err := hcsshim.CreateSandboxLayer(wd.Info(), container.ID, container.ImageID, wd.LayerIdsToPaths(ids)); err != nil { return err } } else { if err := daemon.driver.Create(container.ID, container.ImageID); err != nil { return err } } } else { // Fall-back code path to allow the use of the VFS driver for development if err := daemon.driver.Create(container.ID, container.ImageID); err != nil { return err } } return nil } func checkKernel() error { return nil } func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) { // TODO Windows. Verifications TBC return nil, nil } // checkConfigOptions checks for mutually incompatible config options func checkConfigOptions(config *Config) error { return nil } // checkSystem validates platform-specific requirements func checkSystem() error { var dwVersion uint32 // TODO Windows. May need at some point to ensure have elevation and // possibly LocalSystem. // Validate the OS version. Note that docker.exe must be manifested for this // call to return the correct version. dwVersion, err := syscall.GetVersion() if err != nil { return fmt.Errorf("Failed to call GetVersion()") } if int(dwVersion&0xFF) < 10 { return fmt.Errorf("This version of Windows does not support the docker daemon") } return nil } // configureKernelSecuritySupport configures and validate security support for the kernel func configureKernelSecuritySupport(config *Config, driverName string) error { return nil } func migrateIfDownlevel(driver graphdriver.Driver, root string) error { return nil } func configureVolumes(config *Config) error { // Windows does not support volumes at this time return nil } func configureSysInit(config *Config) (string, error) { // TODO Windows. return os.Getenv("TEMP"), nil } func isBridgeNetworkDisabled(config *Config) bool { return false } func initNetworkController(config *Config) (libnetwork.NetworkController, error) { // Set the name of the virtual switch if not specified by -b on daemon start if config.Bridge.VirtualSwitchName == "" { config.Bridge.VirtualSwitchName = DefaultVirtualSwitch } return nil, nil } func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error { // TODO Windows. Factored out for network modes. There may be more // refactoring required here. if hostConfig == nil || hostConfig.Links == nil { return nil } for _, l := range hostConfig.Links { name, alias, err := parsers.ParseLink(l) if err != nil { return err } child, err := daemon.Get(name) if err != nil { //An error from daemon.Get() means this name could not be found return fmt.Errorf("Could not get container for %s", name) } if err := daemon.RegisterLink(container, child, alias); err != nil { return err } } // After we load all the links into the daemon // set them to nil on the hostconfig hostConfig.Links = nil if err := container.WriteHostConfig(); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/daemon_zfs.go ================================================ // +build !exclude_graphdriver_zfs,linux package daemon import ( _ "github.com/docker/docker/daemon/graphdriver/zfs" ) ================================================ FILE: vendor/github.com/docker/docker/daemon/debugtrap_unix.go ================================================ // +build !windows package daemon import ( "os" "os/signal" "syscall" psignal "github.com/docker/docker/pkg/signal" ) func setupDumpStackTrap() { c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGUSR1) go func() { for range c { psignal.DumpStacks() } }() } ================================================ FILE: vendor/github.com/docker/docker/daemon/debugtrap_unsupported.go ================================================ // +build !linux,!darwin,!freebsd,!windows package daemon func setupDumpStackTrap() { return } ================================================ FILE: vendor/github.com/docker/docker/daemon/debugtrap_windows.go ================================================ package daemon import ( "fmt" "os" "syscall" "github.com/Sirupsen/logrus" psignal "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/system" ) func setupDumpStackTrap() { // Windows does not support signals like *nix systems. So instead of // trapping on SIGUSR1 to dump stacks, we wait on a Win32 event to be // signalled. go func() { sa := syscall.SecurityAttributes{ Length: 0, } ev := "Global\\docker-daemon-" + fmt.Sprint(os.Getpid()) if h, _ := system.CreateEvent(&sa, false, false, ev); h != 0 { logrus.Debugf("Stackdump - waiting signal at %s", ev) for { syscall.WaitForSingleObject(h, syscall.INFINITE) psignal.DumpStacks() } } }() } ================================================ FILE: vendor/github.com/docker/docker/daemon/delete.go ================================================ package daemon import ( "fmt" "os" "path" "runtime" "github.com/Sirupsen/logrus" ) type ContainerRmConfig struct { ForceRemove, RemoveVolume, RemoveLink bool } func (daemon *Daemon) ContainerRm(name string, config *ContainerRmConfig) error { container, err := daemon.Get(name) if err != nil { return err } if config.RemoveLink { name, err := GetFullContainerName(name) if err != nil { return err } parent, n := path.Split(name) if parent == "/" { return fmt.Errorf("Conflict, cannot remove the default name of the container") } pe := daemon.ContainerGraph().Get(parent) if pe == nil { return fmt.Errorf("Cannot get parent %s for name %s", parent, name) } parentContainer, _ := daemon.Get(pe.ID()) if err := daemon.ContainerGraph().Delete(name); err != nil { return err } if parentContainer != nil { parentContainer.DisableLink(n) } return nil } if err := daemon.rm(container, config.ForceRemove); err != nil { return fmt.Errorf("Cannot destroy container %s: %v", name, err) } if config.RemoveVolume { container.removeMountPoints() } return nil } // Destroy unregisters a container from the daemon and cleanly removes its contents from the filesystem. func (daemon *Daemon) rm(container *Container, forceRemove bool) (err error) { if container.IsRunning() { if !forceRemove { return fmt.Errorf("Conflict, You cannot remove a running container. Stop the container before attempting removal or use -f") } if err := container.Kill(); err != nil { return fmt.Errorf("Could not kill running container, cannot remove - %v", err) } } // stop collection of stats for the container regardless // if stats are currently getting collected. daemon.statsCollector.stopCollection(container) element := daemon.containers.Get(container.ID) if element == nil { return fmt.Errorf("Container %v not found - maybe it was already destroyed?", container.ID) } // Container state RemovalInProgress should be used to avoid races. if err = container.SetRemovalInProgress(); err != nil { return fmt.Errorf("Failed to set container state to RemovalInProgress: %s", err) } defer container.ResetRemovalInProgress() if err = container.Stop(3); err != nil { return err } // Mark container dead. We don't want anybody to be restarting it. container.SetDead() // Save container state to disk. So that if error happens before // container meta file got removed from disk, then a restart of // docker should not make a dead container alive. if err := container.ToDisk(); err != nil { logrus.Errorf("Error saving dying container to disk: %v", err) } // If force removal is required, delete container from various // indexes even if removal failed. defer func() { if err != nil && forceRemove { daemon.idIndex.Delete(container.ID) daemon.containers.Delete(container.ID) os.RemoveAll(container.root) container.LogEvent("destroy") } }() if _, err := daemon.containerGraph.Purge(container.ID); err != nil { logrus.Debugf("Unable to remove container from link graph: %s", err) } if err = daemon.driver.Remove(container.ID); err != nil { return fmt.Errorf("Driver %s failed to remove root filesystem %s: %s", daemon.driver, container.ID, err) } // There will not be an -init on Windows, so don't fail by not attempting to delete it if runtime.GOOS != "windows" { initID := fmt.Sprintf("%s-init", container.ID) if err := daemon.driver.Remove(initID); err != nil { return fmt.Errorf("Driver %s failed to remove init filesystem %s: %s", daemon.driver, initID, err) } } if err = os.RemoveAll(container.root); err != nil { return fmt.Errorf("Unable to remove filesystem for %v: %v", container.ID, err) } if err = daemon.execDriver.Clean(container.ID); err != nil { return fmt.Errorf("Unable to remove execdriver data for %s: %s", container.ID, err) } selinuxFreeLxcContexts(container.ProcessLabel) daemon.idIndex.Delete(container.ID) daemon.containers.Delete(container.ID) container.LogEvent("destroy") return nil } func (daemon *Daemon) DeleteVolumes(c *Container) error { return c.removeMountPoints() } ================================================ FILE: vendor/github.com/docker/docker/daemon/events/events.go ================================================ package events import ( "sync" "time" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/pubsub" ) const eventsLimit = 64 // Events is pubsub channel for *jsonmessage.JSONMessage type Events struct { mu sync.Mutex events []*jsonmessage.JSONMessage pub *pubsub.Publisher } // New returns new *Events instance func New() *Events { return &Events{ events: make([]*jsonmessage.JSONMessage, 0, eventsLimit), pub: pubsub.NewPublisher(100*time.Millisecond, 1024), } } // Subscribe adds new listener to events, returns slice of 64 stored last events // channel in which you can expect new events in form of interface{}, so you // need type assertion. func (e *Events) Subscribe() ([]*jsonmessage.JSONMessage, chan interface{}) { e.mu.Lock() current := make([]*jsonmessage.JSONMessage, len(e.events)) copy(current, e.events) l := e.pub.Subscribe() e.mu.Unlock() return current, l } // Evict evicts listener from pubsub func (e *Events) Evict(l chan interface{}) { e.pub.Evict(l) } // Log broadcasts event to listeners. Each listener has 100 millisecond for // receiving event or it will be skipped. func (e *Events) Log(action, id, from string) { go func() { e.mu.Lock() jm := &jsonmessage.JSONMessage{Status: action, ID: id, From: from, Time: time.Now().UTC().Unix()} if len(e.events) == cap(e.events) { // discard oldest event copy(e.events, e.events[1:]) e.events[len(e.events)-1] = jm } else { e.events = append(e.events, jm) } e.mu.Unlock() e.pub.Publish(jm) }() } // SubscribersCount returns number of event listeners func (e *Events) SubscribersCount() int { return e.pub.Len() } ================================================ FILE: vendor/github.com/docker/docker/daemon/events/events_test.go ================================================ package events import ( "fmt" "testing" "time" "github.com/docker/docker/pkg/jsonmessage" ) func TestEventsLog(t *testing.T) { e := New() _, l1 := e.Subscribe() _, l2 := e.Subscribe() defer e.Evict(l1) defer e.Evict(l2) count := e.SubscribersCount() if count != 2 { t.Fatalf("Must be 2 subscribers, got %d", count) } e.Log("test", "cont", "image") select { case msg := <-l1: jmsg, ok := msg.(*jsonmessage.JSONMessage) if !ok { t.Fatalf("Unexpected type %T", msg) } if len(e.events) != 1 { t.Fatalf("Must be only one event, got %d", len(e.events)) } if jmsg.Status != "test" { t.Fatalf("Status should be test, got %s", jmsg.Status) } if jmsg.ID != "cont" { t.Fatalf("ID should be cont, got %s", jmsg.ID) } if jmsg.From != "image" { t.Fatalf("From should be image, got %s", jmsg.From) } case <-time.After(1 * time.Second): t.Fatal("Timeout waiting for broadcasted message") } select { case msg := <-l2: jmsg, ok := msg.(*jsonmessage.JSONMessage) if !ok { t.Fatalf("Unexpected type %T", msg) } if len(e.events) != 1 { t.Fatalf("Must be only one event, got %d", len(e.events)) } if jmsg.Status != "test" { t.Fatalf("Status should be test, got %s", jmsg.Status) } if jmsg.ID != "cont" { t.Fatalf("ID should be cont, got %s", jmsg.ID) } if jmsg.From != "image" { t.Fatalf("From should be image, got %s", jmsg.From) } case <-time.After(1 * time.Second): t.Fatal("Timeout waiting for broadcasted message") } } func TestEventsLogTimeout(t *testing.T) { e := New() _, l := e.Subscribe() defer e.Evict(l) c := make(chan struct{}) go func() { e.Log("test", "cont", "image") close(c) }() select { case <-c: case <-time.After(time.Second): t.Fatal("Timeout publishing message") } } func TestLogEvents(t *testing.T) { e := New() for i := 0; i < eventsLimit+16; i++ { action := fmt.Sprintf("action_%d", i) id := fmt.Sprintf("cont_%d", i) from := fmt.Sprintf("image_%d", i) e.Log(action, id, from) } time.Sleep(50 * time.Millisecond) current, l := e.Subscribe() for i := 0; i < 10; i++ { num := i + eventsLimit + 16 action := fmt.Sprintf("action_%d", num) id := fmt.Sprintf("cont_%d", num) from := fmt.Sprintf("image_%d", num) e.Log(action, id, from) } if len(e.events) != eventsLimit { t.Fatalf("Must be %d events, got %d", eventsLimit, len(e.events)) } var msgs []*jsonmessage.JSONMessage for len(msgs) < 10 { m := <-l jm, ok := (m).(*jsonmessage.JSONMessage) if !ok { t.Fatalf("Unexpected type %T", m) } msgs = append(msgs, jm) } if len(current) != eventsLimit { t.Fatalf("Must be %d events, got %d", eventsLimit, len(current)) } first := current[0] if first.Status != "action_16" { t.Fatalf("First action is %s, must be action_16", first.Status) } last := current[len(current)-1] if last.Status != "action_79" { t.Fatalf("Last action is %s, must be action_79", last.Status) } firstC := msgs[0] if firstC.Status != "action_80" { t.Fatalf("First action is %s, must be action_80", firstC.Status) } lastC := msgs[len(msgs)-1] if lastC.Status != "action_89" { t.Fatalf("Last action is %s, must be action_89", lastC.Status) } } ================================================ FILE: vendor/github.com/docker/docker/daemon/exec.go ================================================ package daemon import ( "fmt" "io" "io/ioutil" "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/broadcastwriter" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/runconfig" ) type execConfig struct { sync.Mutex ID string Running bool ExitCode int ProcessConfig *execdriver.ProcessConfig StreamConfig OpenStdin bool OpenStderr bool OpenStdout bool Container *Container canRemove bool } type execStore struct { s map[string]*execConfig sync.RWMutex } func newExecStore() *execStore { return &execStore{s: make(map[string]*execConfig, 0)} } func (e *execStore) Add(id string, execConfig *execConfig) { e.Lock() e.s[id] = execConfig e.Unlock() } func (e *execStore) Get(id string) *execConfig { e.RLock() res := e.s[id] e.RUnlock() return res } func (e *execStore) Delete(id string) { e.Lock() delete(e.s, id) e.Unlock() } func (e *execStore) List() []string { var IDs []string e.RLock() for id := range e.s { IDs = append(IDs, id) } e.RUnlock() return IDs } func (execConfig *execConfig) Resize(h, w int) error { return execConfig.ProcessConfig.Terminal.Resize(h, w) } func (d *Daemon) registerExecCommand(execConfig *execConfig) { // Storing execs in container in order to kill them gracefully whenever the container is stopped or removed. execConfig.Container.execCommands.Add(execConfig.ID, execConfig) // Storing execs in daemon for easy access via remote API. d.execCommands.Add(execConfig.ID, execConfig) } func (d *Daemon) getExecConfig(name string) (*execConfig, error) { if execConfig := d.execCommands.Get(name); execConfig != nil { if !execConfig.Container.IsRunning() { return nil, fmt.Errorf("Container %s is not running", execConfig.Container.ID) } return execConfig, nil } return nil, fmt.Errorf("No such exec instance '%s' found in daemon", name) } func (d *Daemon) unregisterExecCommand(execConfig *execConfig) { execConfig.Container.execCommands.Delete(execConfig.ID) d.execCommands.Delete(execConfig.ID) } func (d *Daemon) getActiveContainer(name string) (*Container, error) { container, err := d.Get(name) if err != nil { return nil, err } if !container.IsRunning() { return nil, fmt.Errorf("Container %s is not running", name) } if container.IsPaused() { return nil, fmt.Errorf("Container %s is paused, unpause the container before exec", name) } return container, nil } func (d *Daemon) ContainerExecCreate(config *runconfig.ExecConfig) (string, error) { // Not all drivers support Exec (LXC for example) if err := checkExecSupport(d.execDriver.Name()); err != nil { return "", err } container, err := d.getActiveContainer(config.Container) if err != nil { return "", err } cmd := runconfig.NewCommand(config.Cmd...) entrypoint, args := d.getEntrypointAndArgs(runconfig.NewEntrypoint(), cmd) user := config.User if len(user) == 0 { user = container.Config.User } processConfig := &execdriver.ProcessConfig{ Tty: config.Tty, Entrypoint: entrypoint, Arguments: args, User: user, } execConfig := &execConfig{ ID: stringid.GenerateRandomID(), OpenStdin: config.AttachStdin, OpenStdout: config.AttachStdout, OpenStderr: config.AttachStderr, StreamConfig: StreamConfig{}, ProcessConfig: processConfig, Container: container, Running: false, } d.registerExecCommand(execConfig) container.LogEvent("exec_create: " + execConfig.ProcessConfig.Entrypoint + " " + strings.Join(execConfig.ProcessConfig.Arguments, " ")) return execConfig.ID, nil } func (d *Daemon) ContainerExecStart(execName string, stdin io.ReadCloser, stdout io.Writer, stderr io.Writer) error { var ( cStdin io.ReadCloser cStdout, cStderr io.Writer ) execConfig, err := d.getExecConfig(execName) if err != nil { return err } func() { execConfig.Lock() defer execConfig.Unlock() if execConfig.Running { err = fmt.Errorf("Error: Exec command %s is already running", execName) } execConfig.Running = true }() if err != nil { return err } logrus.Debugf("starting exec command %s in container %s", execConfig.ID, execConfig.Container.ID) container := execConfig.Container container.LogEvent("exec_start: " + execConfig.ProcessConfig.Entrypoint + " " + strings.Join(execConfig.ProcessConfig.Arguments, " ")) if execConfig.OpenStdin { r, w := io.Pipe() go func() { defer w.Close() defer logrus.Debugf("Closing buffered stdin pipe") pools.Copy(w, stdin) }() cStdin = r } if execConfig.OpenStdout { cStdout = stdout } if execConfig.OpenStderr { cStderr = stderr } execConfig.StreamConfig.stderr = broadcastwriter.New() execConfig.StreamConfig.stdout = broadcastwriter.New() // Attach to stdin if execConfig.OpenStdin { execConfig.StreamConfig.stdin, execConfig.StreamConfig.stdinPipe = io.Pipe() } else { execConfig.StreamConfig.stdinPipe = ioutils.NopWriteCloser(ioutil.Discard) // Silently drop stdin } attachErr := attach(&execConfig.StreamConfig, execConfig.OpenStdin, true, execConfig.ProcessConfig.Tty, cStdin, cStdout, cStderr) execErr := make(chan error) // Note, the execConfig data will be removed when the container // itself is deleted. This allows us to query it (for things like // the exitStatus) even after the cmd is done running. go func() { if err := container.Exec(execConfig); err != nil { execErr <- fmt.Errorf("Cannot run exec command %s in container %s: %s", execName, container.ID, err) } }() select { case err := <-attachErr: if err != nil { return fmt.Errorf("attach failed with error: %s", err) } break case err := <-execErr: return err } return nil } func (d *Daemon) Exec(c *Container, execConfig *execConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { exitStatus, err := d.execDriver.Exec(c.command, execConfig.ProcessConfig, pipes, startCallback) // On err, make sure we don't leave ExitCode at zero if err != nil && exitStatus == 0 { exitStatus = 128 } execConfig.ExitCode = exitStatus execConfig.Running = false return exitStatus, err } // execCommandGC runs a ticker to clean up the daemon references // of exec configs that are no longer part of the container. func (d *Daemon) execCommandGC() { for range time.Tick(5 * time.Minute) { var ( cleaned int liveExecCommands = d.containerExecIds() ) for id, config := range d.execCommands.s { if config.canRemove { cleaned++ d.execCommands.Delete(id) } else { if _, exists := liveExecCommands[id]; !exists { config.canRemove = true } } } if cleaned > 0 { logrus.Debugf("clean %d unused exec commands", cleaned) } } } // containerExecIds returns a list of all the current exec ids that are in use // and running inside a container. func (d *Daemon) containerExecIds() map[string]struct{} { ids := map[string]struct{}{} for _, c := range d.containers.List() { for _, id := range c.execCommands.List() { ids[id] = struct{}{} } } return ids } ================================================ FILE: vendor/github.com/docker/docker/daemon/exec_linux.go ================================================ // +build linux package daemon import ( "strings" "github.com/docker/docker/daemon/execdriver/lxc" ) // checkExecSupport returns an error if the exec driver does not support exec, // or nil if it is supported. func checkExecSupport(drivername string) error { if strings.HasPrefix(drivername, lxc.DriverName) { return lxc.ErrExec } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/exec_windows.go ================================================ // +build windows package daemon // checkExecSupport returns an error if the exec driver does not support exec, // or nil if it is supported. func checkExecSupport(DriverName string) error { return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/driver.go ================================================ package execdriver import ( "errors" "io" "os/exec" "time" // TODO Windows: Factor out ulimit "github.com/docker/docker/pkg/ulimit" "github.com/opencontainers/runc/libcontainer" "github.com/opencontainers/runc/libcontainer/configs" ) // Context is a generic key value pair that allows // arbatrary data to be sent type Context map[string]string var ( ErrNotRunning = errors.New("Container is not running") ErrWaitTimeoutReached = errors.New("Wait timeout reached") ErrDriverAlreadyRegistered = errors.New("A driver already registered this docker init function") ErrDriverNotFound = errors.New("The requested docker init has not been found") ) type StartCallback func(*ProcessConfig, int) // Driver specific information based on // processes registered with the driver type Info interface { IsRunning() bool } // Terminal in an interface for drivers to implement // if they want to support Close and Resize calls from // the core type Terminal interface { io.Closer Resize(height, width int) error } // ExitStatus provides exit reasons for a container. type ExitStatus struct { // The exit code with which the container exited. ExitCode int // Whether the container encountered an OOM. OOMKilled bool } type Driver interface { Run(c *Command, pipes *Pipes, startCallback StartCallback) (ExitStatus, error) // Run executes the process and blocks until the process exits and returns the exit code // Exec executes the process in an existing container, blocks until the process exits and returns the exit code Exec(c *Command, processConfig *ProcessConfig, pipes *Pipes, startCallback StartCallback) (int, error) Kill(c *Command, sig int) error Pause(c *Command) error Unpause(c *Command) error Name() string // Driver name Info(id string) Info // "temporary" hack (until we move state from core to plugins) GetPidsForContainer(id string) ([]int, error) // Returns a list of pids for the given container. Terminate(c *Command) error // kill it with fire Clean(id string) error // clean all traces of container exec Stats(id string) (*ResourceStats, error) // Get resource stats for a running container } // Network settings of the container type Network struct { Interface *NetworkInterface `json:"interface"` // if interface is nil then networking is disabled Mtu int `json:"mtu"` ContainerID string `json:"container_id"` // id of the container to join network. NamespacePath string `json:"namespace_path"` HostNetworking bool `json:"host_networking"` } // IPC settings of the container type Ipc struct { ContainerID string `json:"container_id"` // id of the container to join ipc. HostIpc bool `json:"host_ipc"` } // PID settings of the container type Pid struct { HostPid bool `json:"host_pid"` } // UTS settings of the container type UTS struct { HostUTS bool `json:"host_uts"` } type NetworkInterface struct { Gateway string `json:"gateway"` IPAddress string `json:"ip"` IPPrefixLen int `json:"ip_prefix_len"` MacAddress string `json:"mac"` Bridge string `json:"bridge"` GlobalIPv6Address string `json:"global_ipv6"` LinkLocalIPv6Address string `json:"link_local_ipv6"` GlobalIPv6PrefixLen int `json:"global_ipv6_prefix_len"` IPv6Gateway string `json:"ipv6_gateway"` HairpinMode bool `json:"hairpin_mode"` } // TODO Windows: Factor out ulimit.Rlimit type Resources struct { Memory int64 `json:"memory"` MemorySwap int64 `json:"memory_swap"` CpuShares int64 `json:"cpu_shares"` CpusetCpus string `json:"cpuset_cpus"` CpusetMems string `json:"cpuset_mems"` CpuPeriod int64 `json:"cpu_period"` CpuQuota int64 `json:"cpu_quota"` BlkioWeight int64 `json:"blkio_weight"` Rlimits []*ulimit.Rlimit `json:"rlimits"` OomKillDisable bool `json:"oom_kill_disable"` MemorySwappiness int64 `json:"memory_swappiness"` } type ResourceStats struct { *libcontainer.Stats Read time.Time `json:"read"` MemoryLimit int64 `json:"memory_limit"` SystemUsage uint64 `json:"system_usage"` } type Mount struct { Source string `json:"source"` Destination string `json:"destination"` Writable bool `json:"writable"` Private bool `json:"private"` Slave bool `json:"slave"` } // Describes a process that will be run inside a container. type ProcessConfig struct { exec.Cmd `json:"-"` Privileged bool `json:"privileged"` User string `json:"user"` Tty bool `json:"tty"` Entrypoint string `json:"entrypoint"` Arguments []string `json:"arguments"` Terminal Terminal `json:"-"` // standard or tty terminal Console string `json:"-"` // dev/console path ConsoleSize [2]int `json:"-"` // h,w of initial console size } // TODO Windows: Factor out unused fields such as LxcConfig, AppArmorProfile, // and CgroupParent. // // Process wrapps an os/exec.Cmd to add more metadata type Command struct { ID string `json:"id"` Rootfs string `json:"rootfs"` // root fs of the container ReadonlyRootfs bool `json:"readonly_rootfs"` InitPath string `json:"initpath"` // dockerinit WorkingDir string `json:"working_dir"` ConfigPath string `json:"config_path"` // this should be able to be removed when the lxc template is moved into the driver Network *Network `json:"network"` Ipc *Ipc `json:"ipc"` Pid *Pid `json:"pid"` UTS *UTS `json:"uts"` Resources *Resources `json:"resources"` Mounts []Mount `json:"mounts"` AllowedDevices []*configs.Device `json:"allowed_devices"` AutoCreatedDevices []*configs.Device `json:"autocreated_devices"` CapAdd []string `json:"cap_add"` CapDrop []string `json:"cap_drop"` GroupAdd []string `json:"group_add"` ContainerPid int `json:"container_pid"` // the pid for the process inside a container ProcessConfig ProcessConfig `json:"process_config"` // Describes the init process of the container. ProcessLabel string `json:"process_label"` MountLabel string `json:"mount_label"` LxcConfig []string `json:"lxc_config"` AppArmorProfile string `json:"apparmor_profile"` CgroupParent string `json:"cgroup_parent"` // The parent cgroup for this command. FirstStart bool `json:"first_start"` LayerPaths []string `json:"layer_paths"` // Windows needs to know the layer paths and folder for a command LayerFolder string `json:"layer_folder"` } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/driver_linux.go ================================================ package execdriver import ( "encoding/json" "io/ioutil" "os" "path/filepath" "strconv" "strings" "time" "github.com/docker/docker/daemon/execdriver/native/template" "github.com/opencontainers/runc/libcontainer" "github.com/opencontainers/runc/libcontainer/cgroups/fs" "github.com/opencontainers/runc/libcontainer/configs" ) func InitContainer(c *Command) *configs.Config { container := template.New() container.Hostname = getEnv("HOSTNAME", c.ProcessConfig.Env) container.Cgroups.Name = c.ID container.Cgroups.AllowedDevices = c.AllowedDevices container.Devices = c.AutoCreatedDevices container.Rootfs = c.Rootfs container.Readonlyfs = c.ReadonlyRootfs container.Privatefs = true // check to see if we are running in ramdisk to disable pivot root container.NoPivotRoot = os.Getenv("DOCKER_RAMDISK") != "" // Default parent cgroup is "docker". Override if required. if c.CgroupParent != "" { container.Cgroups.Parent = c.CgroupParent } return container } func getEnv(key string, env []string) string { for _, pair := range env { parts := strings.SplitN(pair, "=", 2) if parts[0] == key { return parts[1] } } return "" } func SetupCgroups(container *configs.Config, c *Command) error { if c.Resources != nil { container.Cgroups.CpuShares = c.Resources.CpuShares container.Cgroups.Memory = c.Resources.Memory container.Cgroups.MemoryReservation = c.Resources.Memory container.Cgroups.MemorySwap = c.Resources.MemorySwap container.Cgroups.CpusetCpus = c.Resources.CpusetCpus container.Cgroups.CpusetMems = c.Resources.CpusetMems container.Cgroups.CpuPeriod = c.Resources.CpuPeriod container.Cgroups.CpuQuota = c.Resources.CpuQuota container.Cgroups.BlkioWeight = c.Resources.BlkioWeight container.Cgroups.OomKillDisable = c.Resources.OomKillDisable container.Cgroups.MemorySwappiness = c.Resources.MemorySwappiness } return nil } // Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo. func getNetworkInterfaceStats(interfaceName string) (*libcontainer.NetworkInterface, error) { out := &libcontainer.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//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) } func Stats(containerDir string, containerMemoryLimit int64, machineMemory int64) (*ResourceStats, error) { f, err := os.Open(filepath.Join(containerDir, "state.json")) if err != nil { return nil, err } defer f.Close() type network struct { Type string HostInterfaceName string } state := struct { CgroupPaths map[string]string `json:"cgroup_paths"` Networks []network }{} if err := json.NewDecoder(f).Decode(&state); err != nil { return nil, err } now := time.Now() mgr := fs.Manager{Paths: state.CgroupPaths} cstats, err := mgr.GetStats() if err != nil { return nil, err } stats := &libcontainer.Stats{CgroupStats: cstats} // if the container does not have any memory limit specified set the // limit to the machines memory memoryLimit := containerMemoryLimit if memoryLimit == 0 { memoryLimit = machineMemory } for _, iface := range state.Networks { switch iface.Type { case "veth": istats, err := getNetworkInterfaceStats(iface.HostInterfaceName) if err != nil { return nil, err } stats.Interfaces = append(stats.Interfaces, istats) } } return &ResourceStats{ Stats: stats, Read: now, MemoryLimit: memoryLimit, }, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/execdrivers/execdrivers_linux.go ================================================ // +build linux package execdrivers import ( "fmt" "path" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/execdriver/lxc" "github.com/docker/docker/daemon/execdriver/native" "github.com/docker/docker/pkg/sysinfo" ) func NewDriver(name string, options []string, root, libPath, initPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) { switch name { case "lxc": // we want to give the lxc driver the full docker root because it needs // to access and write config and template files in /var/lib/docker/containers/* // to be backwards compatible return lxc.NewDriver(root, libPath, initPath, sysInfo.AppArmor) case "native": return native.NewDriver(path.Join(root, "execdriver", "native"), initPath, options) } return nil, fmt.Errorf("unknown exec driver %s", name) } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/execdrivers/execdrivers_windows.go ================================================ // +build windows package execdrivers import ( "fmt" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/daemon/execdriver/windows" "github.com/docker/docker/pkg/sysinfo" ) func NewDriver(name string, options []string, root, libPath, initPath string, sysInfo *sysinfo.SysInfo) (execdriver.Driver, error) { switch name { case "windows": return windows.NewDriver(root, initPath, options) } return nil, fmt.Errorf("unknown exec driver %s", name) } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/driver.go ================================================ // +build linux package lxc import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "runtime" "strconv" "strings" "sync" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/stringutils" sysinfo "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/term" "github.com/docker/docker/pkg/version" "github.com/kr/pty" "github.com/opencontainers/runc/libcontainer" "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/vishvananda/netns" ) const DriverName = "lxc" var ErrExec = errors.New("Unsupported: Exec is not supported by the lxc driver") type driver struct { root string // root path for the driver to use libPath string initPath string apparmor bool sharedRoot bool activeContainers map[string]*activeContainer machineMemory int64 sync.Mutex } type activeContainer struct { container *configs.Config cmd *exec.Cmd } func NewDriver(root, libPath, initPath string, apparmor bool) (*driver, error) { if err := os.MkdirAll(root, 0700); err != nil { return nil, err } // setup unconfined symlink if err := linkLxcStart(root); err != nil { return nil, err } meminfo, err := sysinfo.ReadMemInfo() if err != nil { return nil, err } return &driver{ apparmor: apparmor, root: root, libPath: libPath, initPath: initPath, sharedRoot: rootIsShared(), activeContainers: make(map[string]*activeContainer), machineMemory: meminfo.MemTotal, }, nil } func (d *driver) Name() string { version := d.version() return fmt.Sprintf("%s-%s", DriverName, version) } func setupNetNs(nsPath string) (*os.Process, error) { runtime.LockOSThread() defer runtime.UnlockOSThread() origns, err := netns.Get() if err != nil { return nil, err } defer origns.Close() f, err := os.OpenFile(nsPath, os.O_RDONLY, 0) if err != nil { return nil, fmt.Errorf("failed to get network namespace %q: %v", nsPath, err) } defer f.Close() nsFD := f.Fd() if err := netns.Set(netns.NsHandle(nsFD)); err != nil { return nil, fmt.Errorf("failed to set network namespace %q: %v", nsPath, err) } defer netns.Set(origns) cmd := exec.Command("/bin/sh", "-c", "while true; do sleep 1; done") if err := cmd.Start(); err != nil { return nil, fmt.Errorf("failed to start netns process: %v", err) } return cmd.Process, nil } func killNetNsProc(proc *os.Process) { proc.Kill() proc.Wait() } func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { var ( term execdriver.Terminal err error dataPath = d.containerDir(c.ID) ) if c.Network == nil || (c.Network.NamespacePath == "" && c.Network.ContainerID == "") { return execdriver.ExitStatus{ExitCode: -1}, fmt.Errorf("empty namespace path for non-container network") } container, err := d.createContainer(c) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } if c.ProcessConfig.Tty { term, err = NewTtyConsole(&c.ProcessConfig, pipes) } else { term, err = execdriver.NewStdConsole(&c.ProcessConfig, pipes) } if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } c.ProcessConfig.Terminal = term d.Lock() d.activeContainers[c.ID] = &activeContainer{ container: container, cmd: &c.ProcessConfig.Cmd, } d.Unlock() c.Mounts = append(c.Mounts, execdriver.Mount{ Source: d.initPath, Destination: c.InitPath, Writable: false, Private: true, }) if err := d.generateEnvConfig(c); err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } configPath, err := d.generateLXCConfig(c) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } params := []string{ "lxc-start", "-n", c.ID, "-f", configPath, "-q", } // From lxc>=1.1 the default behavior is to daemonize containers after start lxcVersion := version.Version(d.version()) if lxcVersion.GreaterThanOrEqualTo(version.Version("1.1")) { params = append(params, "-F") } proc := &os.Process{} if c.Network.ContainerID != "" { params = append(params, "--share-net", c.Network.ContainerID, ) } else { proc, err = setupNetNs(c.Network.NamespacePath) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } pidStr := fmt.Sprintf("%d", proc.Pid) params = append(params, "--share-net", pidStr) } if c.Ipc != nil { if c.Ipc.ContainerID != "" { params = append(params, "--share-ipc", c.Ipc.ContainerID, ) } else if c.Ipc.HostIpc { params = append(params, "--share-ipc", "1", ) } } params = append(params, "--", c.InitPath, ) if c.ProcessConfig.User != "" { params = append(params, "-u", c.ProcessConfig.User) } if c.ProcessConfig.Privileged { if d.apparmor { params[0] = path.Join(d.root, "lxc-start-unconfined") } params = append(params, "-privileged") } if c.WorkingDir != "" { params = append(params, "-w", c.WorkingDir) } params = append(params, "--", c.ProcessConfig.Entrypoint) params = append(params, c.ProcessConfig.Arguments...) if d.sharedRoot { // lxc-start really needs / to be non-shared, or all kinds of stuff break // when lxc-start unmount things and those unmounts propagate to the main // mount namespace. // What we really want is to clone into a new namespace and then // mount / MS_REC|MS_SLAVE, but since we can't really clone or fork // without exec in go we have to do this horrible shell hack... shellString := "mount --make-rslave /; exec " + stringutils.ShellQuoteArguments(params) params = []string{ "unshare", "-m", "--", "/bin/sh", "-c", shellString, } } logrus.Debugf("lxc params %s", params) var ( name = params[0] arg = params[1:] ) aname, err := exec.LookPath(name) if err != nil { aname = name } c.ProcessConfig.Path = aname c.ProcessConfig.Args = append([]string{name}, arg...) if err := createDeviceNodes(c.Rootfs, c.AutoCreatedDevices); err != nil { killNetNsProc(proc) return execdriver.ExitStatus{ExitCode: -1}, err } if err := c.ProcessConfig.Start(); err != nil { killNetNsProc(proc) return execdriver.ExitStatus{ExitCode: -1}, err } var ( waitErr error waitLock = make(chan struct{}) ) go func() { if err := c.ProcessConfig.Wait(); err != nil { if _, ok := err.(*exec.ExitError); !ok { // Do not propagate the error if it's simply a status code != 0 waitErr = err } } close(waitLock) }() terminate := func(terr error) (execdriver.ExitStatus, error) { if c.ProcessConfig.Process != nil { c.ProcessConfig.Process.Kill() c.ProcessConfig.Wait() } return execdriver.ExitStatus{ExitCode: -1}, terr } // Poll lxc for RUNNING status pid, err := d.waitForStart(c, waitLock) if err != nil { killNetNsProc(proc) return terminate(err) } killNetNsProc(proc) cgroupPaths, err := cgroupPaths(c.ID) if err != nil { return terminate(err) } state := &libcontainer.State{ InitProcessPid: pid, CgroupPaths: cgroupPaths, } f, err := os.Create(filepath.Join(dataPath, "state.json")) if err != nil { return terminate(err) } defer f.Close() if err := json.NewEncoder(f).Encode(state); err != nil { return terminate(err) } c.ContainerPid = pid if startCallback != nil { logrus.Debugf("Invoking startCallback") startCallback(&c.ProcessConfig, pid) } oomKill := false oomKillNotification, err := notifyOnOOM(cgroupPaths) <-waitLock exitCode := getExitCode(c) if err == nil { _, oomKill = <-oomKillNotification logrus.Debugf("oomKill error: %v, waitErr: %v", oomKill, waitErr) } else { logrus.Warnf("Your kernel does not support OOM notifications: %s", err) } // check oom error if oomKill { exitCode = 137 } return execdriver.ExitStatus{ExitCode: exitCode, OOMKilled: oomKill}, waitErr } // copy from libcontainer func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) { dir := paths["memory"] if dir == "" { return nil, fmt.Errorf("There is no path for %q in state", "memory") } oomControl, err := os.Open(filepath.Join(dir, "memory.oom_control")) if err != nil { return nil, err } fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0) if syserr != 0 { oomControl.Close() return nil, syserr } eventfd := os.NewFile(fd, "eventfd") eventControlPath := filepath.Join(dir, "cgroup.event_control") data := fmt.Sprintf("%d %d", eventfd.Fd(), oomControl.Fd()) if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil { eventfd.Close() oomControl.Close() return nil, err } ch := make(chan struct{}) go func() { defer func() { close(ch) eventfd.Close() oomControl.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 } // createContainer populates and configures the container type with the // data provided by the execdriver.Command func (d *driver) createContainer(c *execdriver.Command) (*configs.Config, error) { container := execdriver.InitContainer(c) if err := execdriver.SetupCgroups(container, c); err != nil { return nil, err } return container, nil } // Return an map of susbystem -> container cgroup func cgroupPaths(containerId string) (map[string]string, error) { subsystems, err := cgroups.GetAllSubsystems() if err != nil { return nil, err } logrus.Debugf("subsystems: %s", subsystems) paths := make(map[string]string) for _, subsystem := range subsystems { cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem) logrus.Debugf("cgroup path %s %s", cgroupRoot, cgroupDir) if err != nil { //unsupported subystem continue } path := filepath.Join(cgroupRoot, cgroupDir, "lxc", containerId) paths[subsystem] = path } return paths, nil } // this is copy from old libcontainer nodes.go func createDeviceNodes(rootfs string, nodesToCreate []*configs.Device) error { oldMask := syscall.Umask(0000) defer syscall.Umask(oldMask) for _, node := range nodesToCreate { if err := createDeviceNode(rootfs, node); err != nil { return err } } return nil } // Creates the device node in the rootfs of the container. func createDeviceNode(rootfs string, node *configs.Device) error { var ( dest = filepath.Join(rootfs, node.Path) parent = filepath.Dir(dest) ) if err := os.MkdirAll(parent, 0755); err != nil { return err } fileMode := node.FileMode switch node.Type { case 'c': fileMode |= syscall.S_IFCHR case 'b': fileMode |= syscall.S_IFBLK 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 && !os.IsExist(err) { return fmt.Errorf("mknod %s %s", node.Path, err) } if err := syscall.Chown(dest, int(node.Uid), int(node.Gid)); err != nil { return fmt.Errorf("chown %s to %d:%d", node.Path, node.Uid, node.Gid) } return nil } // setupUser changes the groups, gid, and uid for the user inside the container // copy from libcontainer, cause not it's private func setupUser(userSpec string) error { // Set up defaults. defaultExecUser := user.ExecUser{ Uid: syscall.Getuid(), Gid: syscall.Getgid(), Home: "/", } passwdPath, err := user.GetPasswdPath() if err != nil { return err } groupPath, err := user.GetGroupPath() if err != nil { return err } execUser, err := user.GetExecUserPath(userSpec, &defaultExecUser, passwdPath, groupPath) if err != nil { return err } if err := syscall.Setgroups(execUser.Sgids); 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 } /// Return the exit code of the process // if the process has not exited -1 will be returned func getExitCode(c *execdriver.Command) int { if c.ProcessConfig.ProcessState == nil { return -1 } return c.ProcessConfig.ProcessState.Sys().(syscall.WaitStatus).ExitStatus() } func (d *driver) Kill(c *execdriver.Command, sig int) error { if sig == 9 || c.ProcessConfig.Process == nil { return KillLxc(c.ID, sig) } return c.ProcessConfig.Process.Signal(syscall.Signal(sig)) } func (d *driver) Pause(c *execdriver.Command) error { _, err := exec.LookPath("lxc-freeze") if err == nil { output, errExec := exec.Command("lxc-freeze", "-n", c.ID).CombinedOutput() if errExec != nil { return fmt.Errorf("Err: %s Output: %s", errExec, output) } } return err } func (d *driver) Unpause(c *execdriver.Command) error { _, err := exec.LookPath("lxc-unfreeze") if err == nil { output, errExec := exec.Command("lxc-unfreeze", "-n", c.ID).CombinedOutput() if errExec != nil { return fmt.Errorf("Err: %s Output: %s", errExec, output) } } return err } func (d *driver) Terminate(c *execdriver.Command) error { return KillLxc(c.ID, 9) } func (d *driver) version() string { var ( version string output []byte err error ) if _, errPath := exec.LookPath("lxc-version"); errPath == nil { output, err = exec.Command("lxc-version").CombinedOutput() } else { output, err = exec.Command("lxc-start", "--version").CombinedOutput() } if err == nil { version = strings.TrimSpace(string(output)) if parts := strings.SplitN(version, ":", 2); len(parts) == 2 { version = strings.TrimSpace(parts[1]) } } return version } func KillLxc(id string, sig int) error { var ( err error output []byte ) _, err = exec.LookPath("lxc-kill") if err == nil { output, err = exec.Command("lxc-kill", "-n", id, strconv.Itoa(sig)).CombinedOutput() } else { // lxc-stop does not take arbitrary signals like lxc-kill does output, err = exec.Command("lxc-stop", "-k", "-n", id).CombinedOutput() } if err != nil { return fmt.Errorf("Err: %s Output: %s", err, output) } return nil } // wait for the process to start and return the pid for the process func (d *driver) waitForStart(c *execdriver.Command, waitLock chan struct{}) (int, error) { var ( err error output []byte ) // We wait for the container to be fully running. // Timeout after 5 seconds. In case of broken pipe, just retry. // Note: The container can run and finish correctly before // the end of this loop for now := time.Now(); time.Since(now) < 5*time.Second; { select { case <-waitLock: // If the process dies while waiting for it, just return return -1, nil default: } output, err = d.getInfo(c.ID) if err == nil { info, err := parseLxcInfo(string(output)) if err != nil { return -1, err } if info.Running { return info.Pid, nil } } time.Sleep(50 * time.Millisecond) } return -1, execdriver.ErrNotRunning } func (d *driver) getInfo(id string) ([]byte, error) { return exec.Command("lxc-info", "-n", id).CombinedOutput() } type info struct { ID string driver *driver } func (i *info) IsRunning() bool { var running bool output, err := i.driver.getInfo(i.ID) if err != nil { logrus.Errorf("Error getting info for lxc container %s: %s (%s)", i.ID, err, output) return false } if strings.Contains(string(output), "RUNNING") { running = true } return running } func (d *driver) Info(id string) execdriver.Info { return &info{ ID: id, driver: d, } } func findCgroupRootAndDir(subsystem string) (string, string, error) { cgroupRoot, err := cgroups.FindCgroupMountpoint(subsystem) if err != nil { return "", "", err } cgroupDir, err := cgroups.GetThisCgroupDir(subsystem) if err != nil { return "", "", err } return cgroupRoot, cgroupDir, nil } func (d *driver) GetPidsForContainer(id string) ([]int, error) { pids := []int{} // cpu is chosen because it is the only non optional subsystem in cgroups subsystem := "cpu" cgroupRoot, cgroupDir, err := findCgroupRootAndDir(subsystem) if err != nil { return pids, err } filename := filepath.Join(cgroupRoot, cgroupDir, id, "tasks") if _, err := os.Stat(filename); os.IsNotExist(err) { // With more recent lxc versions use, cgroup will be in lxc/ filename = filepath.Join(cgroupRoot, cgroupDir, "lxc", id, "tasks") } output, err := ioutil.ReadFile(filename) if err != nil { return pids, err } for _, p := range strings.Split(string(output), "\n") { if len(p) == 0 { continue } pid, err := strconv.Atoi(p) if err != nil { return pids, fmt.Errorf("Invalid pid '%s': %s", p, err) } pids = append(pids, pid) } return pids, nil } func linkLxcStart(root string) error { sourcePath, err := exec.LookPath("lxc-start") if err != nil { return err } targetPath := path.Join(root, "lxc-start-unconfined") if _, err := os.Lstat(targetPath); err != nil && !os.IsNotExist(err) { return err } else if err == nil { if err := os.Remove(targetPath); err != nil { return err } } return os.Symlink(sourcePath, targetPath) } // TODO: This can be moved to the mountinfo reader in the mount pkg func rootIsShared() bool { if data, err := ioutil.ReadFile("/proc/self/mountinfo"); err == nil { for _, line := range strings.Split(string(data), "\n") { cols := strings.Split(line, " ") if len(cols) >= 6 && cols[4] == "/" { return strings.HasPrefix(cols[6], "shared") } } } // No idea, probably safe to assume so return true } func (d *driver) containerDir(containerId string) string { return path.Join(d.libPath, "containers", containerId) } func (d *driver) generateLXCConfig(c *execdriver.Command) (string, error) { root := path.Join(d.containerDir(c.ID), "config.lxc") fo, err := os.Create(root) if err != nil { return "", err } defer fo.Close() if err := LxcTemplateCompiled.Execute(fo, struct { *execdriver.Command AppArmor bool }{ Command: c, AppArmor: d.apparmor, }); err != nil { return "", err } return root, nil } func (d *driver) generateEnvConfig(c *execdriver.Command) error { data, err := json.Marshal(c.ProcessConfig.Env) if err != nil { return err } p := path.Join(d.libPath, "containers", c.ID, "config.env") c.Mounts = append(c.Mounts, execdriver.Mount{ Source: p, Destination: "/.dockerenv", Writable: false, Private: true, }) return ioutil.WriteFile(p, data, 0600) } // Clean not implemented for lxc func (d *driver) Clean(id string) error { return nil } type TtyConsole struct { MasterPty *os.File SlavePty *os.File } func NewTtyConsole(processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes) (*TtyConsole, error) { // lxc is special in that we cannot create the master outside of the container without // opening the slave because we have nothing to provide to the cmd. We have to open both then do // the crazy setup on command right now instead of passing the console path to lxc and telling it // to open up that console. we save a couple of openfiles in the native driver because we can do // this. ptyMaster, ptySlave, err := pty.Open() if err != nil { return nil, err } tty := &TtyConsole{ MasterPty: ptyMaster, SlavePty: ptySlave, } if err := tty.AttachPipes(&processConfig.Cmd, pipes); err != nil { tty.Close() return nil, err } processConfig.Console = tty.SlavePty.Name() return tty, nil } func (t *TtyConsole) Resize(h, w int) error { return term.SetWinsize(t.MasterPty.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) } func (t *TtyConsole) AttachPipes(command *exec.Cmd, pipes *execdriver.Pipes) error { command.Stdout = t.SlavePty command.Stderr = t.SlavePty go func() { if wb, ok := pipes.Stdout.(interface { CloseWriters() error }); ok { defer wb.CloseWriters() } io.Copy(pipes.Stdout, t.MasterPty) }() if pipes.Stdin != nil { command.Stdin = t.SlavePty command.SysProcAttr.Setctty = true go func() { io.Copy(t.MasterPty, pipes.Stdin) pipes.Stdin.Close() }() } return nil } func (t *TtyConsole) Close() error { t.SlavePty.Close() return t.MasterPty.Close() } func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { return -1, ErrExec } func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) { if _, ok := d.activeContainers[id]; !ok { return nil, fmt.Errorf("%s is not a key in active containers", id) } return execdriver.Stats(d.containerDir(id), d.activeContainers[id].container.Cgroups.Memory, d.machineMemory) } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/info.go ================================================ // +build linux package lxc import ( "bufio" "errors" "strconv" "strings" ) var ( ErrCannotParse = errors.New("cannot parse raw input") ) type lxcInfo struct { Running bool Pid int } func parseLxcInfo(raw string) (*lxcInfo, error) { if raw == "" { return nil, ErrCannotParse } var ( err error s = bufio.NewScanner(strings.NewReader(raw)) info = &lxcInfo{} ) for s.Scan() { text := s.Text() if s.Err() != nil { return nil, s.Err() } parts := strings.Split(text, ":") if len(parts) < 2 { continue } switch strings.ToLower(strings.TrimSpace(parts[0])) { case "state": info.Running = strings.TrimSpace(parts[1]) == "RUNNING" case "pid": info.Pid, err = strconv.Atoi(strings.TrimSpace(parts[1])) if err != nil { return nil, err } } } return info, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/info_test.go ================================================ // +build linux package lxc import ( "testing" ) func TestParseRunningInfo(t *testing.T) { raw := ` state: RUNNING pid: 50` info, err := parseLxcInfo(raw) if err != nil { t.Fatal(err) } if !info.Running { t.Fatal("info should return a running state") } if info.Pid != 50 { t.Fatalf("info should have pid 50 got %d", info.Pid) } } func TestEmptyInfo(t *testing.T) { _, err := parseLxcInfo("") if err == nil { t.Fatal("error should not be nil") } } func TestBadInfo(t *testing.T) { _, err := parseLxcInfo("state") if err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/init.go ================================================ // +build linux package lxc import ( "encoding/json" "flag" "fmt" "os" "os/exec" "runtime" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/reexec" ) // Args provided to the init function for a driver type InitArgs struct { User string Gateway string Ip string WorkDir string Privileged bool Env []string Args []string Mtu int Console string Pipe int Root string CapAdd string CapDrop string } func init() { // like always lxc requires a hack to get this to work reexec.Register("/.dockerinit", dockerInititalizer) } func dockerInititalizer() { initializer() } // initializer is the lxc driver's init function that is run inside the namespace to setup // additional configurations func initializer() { runtime.LockOSThread() args := getArgs() if err := setupNamespace(args); err != nil { logrus.Fatal(err) } } func setupNamespace(args *InitArgs) error { if err := setupEnv(args); err != nil { return err } if err := finalizeNamespace(args); err != nil { return err } path, err := exec.LookPath(args.Args[0]) if err != nil { logrus.Infof("Unable to locate %v", args.Args[0]) os.Exit(127) } if err := syscall.Exec(path, args.Args, os.Environ()); err != nil { return fmt.Errorf("dockerinit unable to execute %s - %s", path, err) } return nil } func getArgs() *InitArgs { var ( // Get cmdline arguments user = flag.String("u", "", "username or uid") gateway = flag.String("g", "", "gateway address") ip = flag.String("i", "", "ip address") workDir = flag.String("w", "", "workdir") privileged = flag.Bool("privileged", false, "privileged mode") mtu = flag.Int("mtu", 1500, "interface mtu") capAdd = flag.String("cap-add", "", "capabilities to add") capDrop = flag.String("cap-drop", "", "capabilities to drop") ) flag.Parse() return &InitArgs{ User: *user, Gateway: *gateway, Ip: *ip, WorkDir: *workDir, Privileged: *privileged, Args: flag.Args(), Mtu: *mtu, CapAdd: *capAdd, CapDrop: *capDrop, } } // Clear environment pollution introduced by lxc-start func setupEnv(args *InitArgs) error { // Get env var env []string dockerenv, err := os.Open(".dockerenv") if err != nil { return fmt.Errorf("Unable to load environment variables: %v", err) } defer dockerenv.Close() if err := json.NewDecoder(dockerenv).Decode(&env); err != nil { return fmt.Errorf("Unable to decode environment variables: %v", err) } // Propagate the plugin-specific container env variable env = append(env, "container="+os.Getenv("container")) args.Env = env os.Clearenv() for _, kv := range args.Env { parts := strings.SplitN(kv, "=", 2) if len(parts) == 1 { parts = append(parts, "") } os.Setenv(parts[0], parts[1]) } return nil } // Setup working directory func setupWorkingDirectory(args *InitArgs) error { if args.WorkDir == "" { return nil } if err := syscall.Chdir(args.WorkDir); err != nil { return fmt.Errorf("Unable to change dir to %v: %v", args.WorkDir, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/lxc_init_linux.go ================================================ // +build linux package lxc import ( "fmt" "github.com/opencontainers/runc/libcontainer/utils" ) func finalizeNamespace(args *InitArgs) error { if err := utils.CloseExecFrom(3); err != nil { return err } if err := setupUser(args.User); err != nil { return fmt.Errorf("setup user %s", err) } if err := setupWorkingDirectory(args); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/lxc_init_unsupported.go ================================================ // +build !linux package lxc func finalizeNamespace(args *InitArgs) error { panic("Not supported on this platform") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/lxc_template.go ================================================ // +build linux package lxc import ( "fmt" "os" "strings" "text/template" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" nativeTemplate "github.com/docker/docker/daemon/execdriver/native/template" "github.com/docker/docker/pkg/stringutils" "github.com/opencontainers/runc/libcontainer/label" ) const LxcTemplate = ` lxc.network.type = none # root filesystem {{$ROOTFS := .Rootfs}} lxc.rootfs = {{$ROOTFS}} # use a dedicated pts for the container (and limit the number of pseudo terminal # available) lxc.pts = 1024 # disable the main console lxc.console = none # no controlling tty at all lxc.tty = 1 {{if .ProcessConfig.Privileged}} lxc.cgroup.devices.allow = a {{else}} # no implicit access to devices lxc.cgroup.devices.deny = a #Allow the devices passed to us in the AllowedDevices list. {{range $allowedDevice := .AllowedDevices}} lxc.cgroup.devices.allow = {{$allowedDevice.CgroupString}} {{end}} {{end}} # standard mount point # Use mnt.putold as per https://bugs.launchpad.net/ubuntu/+source/lxc/+bug/986385 lxc.pivotdir = lxc_putold # lxc.autodev is not compatible with lxc --device switch lxc.autodev = 0 # NOTICE: These mounts must be applied within the namespace {{if .ProcessConfig.Privileged}} # WARNING: mounting procfs and/or sysfs read-write is a known attack vector. # See e.g. http://blog.zx2c4.com/749 and https://bit.ly/T9CkqJ # We mount them read-write here, but later, dockerinit will call the Restrict() function to remount them read-only. # We cannot mount them directly read-only, because that would prevent loading AppArmor profiles. lxc.mount.entry = proc {{escapeFstabSpaces $ROOTFS}}/proc proc nosuid,nodev,noexec 0 0 lxc.mount.entry = sysfs {{escapeFstabSpaces $ROOTFS}}/sys sysfs nosuid,nodev,noexec 0 0 {{if .AppArmor}} lxc.aa_profile = unconfined {{end}} {{else}} # In non-privileged mode, lxc will automatically mount /proc and /sys in readonly mode # for security. See: http://man7.org/linux/man-pages/man5/lxc.container.conf.5.html lxc.mount.auto = proc sys {{if .AppArmorProfile}} lxc.aa_profile = {{.AppArmorProfile}} {{end}} {{end}} {{if .ProcessConfig.Tty}} lxc.mount.entry = {{.ProcessConfig.Console}} {{escapeFstabSpaces $ROOTFS}}/dev/console none bind,rw,create=file 0 0 {{end}} lxc.mount.entry = devpts {{escapeFstabSpaces $ROOTFS}}/dev/pts devpts {{formatMountLabel "newinstance,ptmxmode=0666,nosuid,noexec,create=dir" ""}} 0 0 lxc.mount.entry = shm {{escapeFstabSpaces $ROOTFS}}/dev/shm tmpfs {{formatMountLabel "size=65536k,nosuid,nodev,noexec,create=dir" ""}} 0 0 {{range $value := .Mounts}} {{$createVal := isDirectory $value.Source}} {{if $value.Writable}} lxc.mount.entry = {{$value.Source}} {{escapeFstabSpaces $ROOTFS}}/{{escapeFstabSpaces $value.Destination}} none rbind,rw,create={{$createVal}} 0 0 {{else}} lxc.mount.entry = {{$value.Source}} {{escapeFstabSpaces $ROOTFS}}/{{escapeFstabSpaces $value.Destination}} none rbind,ro,create={{$createVal}} 0 0 {{end}} {{end}} # limits {{if .Resources}} {{if .Resources.Memory}} lxc.cgroup.memory.limit_in_bytes = {{.Resources.Memory}} lxc.cgroup.memory.soft_limit_in_bytes = {{.Resources.Memory}} {{with $memSwap := getMemorySwap .Resources}} lxc.cgroup.memory.memsw.limit_in_bytes = {{$memSwap}} {{end}} {{end}} {{if .Resources.CpuShares}} lxc.cgroup.cpu.shares = {{.Resources.CpuShares}} {{end}} {{if .Resources.CpuPeriod}} lxc.cgroup.cpu.cfs_period_us = {{.Resources.CpuPeriod}} {{end}} {{if .Resources.CpusetCpus}} lxc.cgroup.cpuset.cpus = {{.Resources.CpusetCpus}} {{end}} {{if .Resources.CpusetMems}} lxc.cgroup.cpuset.mems = {{.Resources.CpusetMems}} {{end}} {{if .Resources.CpuQuota}} lxc.cgroup.cpu.cfs_quota_us = {{.Resources.CpuQuota}} {{end}} {{if .Resources.BlkioWeight}} lxc.cgroup.blkio.weight = {{.Resources.BlkioWeight}} {{end}} {{if .Resources.OomKillDisable}} lxc.cgroup.memory.oom_control = {{.Resources.OomKillDisable}} {{end}} {{if .Resources.MemorySwappiness}} lxc.cgroup.memory.swappiness = {{.Resources.MemorySwappiness}} {{end}} {{end}} {{if .LxcConfig}} {{range $value := .LxcConfig}} lxc.{{$value}} {{end}} {{end}} {{if .Network.Interface}} {{if .Network.Interface.IPAddress}} lxc.network.ipv4 = {{.Network.Interface.IPAddress}}/{{.Network.Interface.IPPrefixLen}} {{end}} {{if .Network.Interface.Gateway}} lxc.network.ipv4.gateway = {{.Network.Interface.Gateway}} {{end}} {{if .Network.Interface.MacAddress}} lxc.network.hwaddr = {{.Network.Interface.MacAddress}} {{end}} {{end}} {{if .ProcessConfig.Env}} lxc.utsname = {{getHostname .ProcessConfig.Env}} {{end}} {{if .ProcessConfig.Privileged}} # No cap values are needed, as lxc is starting in privileged mode {{else}} {{ with keepCapabilities .CapAdd .CapDrop }} {{range .}} lxc.cap.keep = {{.}} {{end}} {{else}} {{ with dropList .CapDrop }} {{range .}} lxc.cap.drop = {{.}} {{end}} {{end}} {{end}} {{end}} ` var LxcTemplateCompiled *template.Template // Escape spaces in strings according to the fstab documentation, which is the // format for "lxc.mount.entry" lines in lxc.conf. See also "man 5 fstab". func escapeFstabSpaces(field string) string { return strings.Replace(field, " ", "\\040", -1) } func keepCapabilities(adds []string, drops []string) ([]string, error) { container := nativeTemplate.New() logrus.Debugf("adds %s drops %s\n", adds, drops) caps, err := execdriver.TweakCapabilities(container.Capabilities, adds, drops) if err != nil { return nil, err } var newCaps []string for _, cap := range caps { logrus.Debugf("cap %s\n", cap) realCap := execdriver.GetCapability(cap) numCap := fmt.Sprintf("%d", realCap.Value) newCaps = append(newCaps, numCap) } return newCaps, nil } func dropList(drops []string) ([]string, error) { if stringutils.InSlice(drops, "all") { var newCaps []string for _, capName := range execdriver.GetAllCapabilities() { cap := execdriver.GetCapability(capName) logrus.Debugf("drop cap %s\n", cap.Key) numCap := fmt.Sprintf("%d", cap.Value) newCaps = append(newCaps, numCap) } return newCaps, nil } return []string{}, nil } func isDirectory(source string) string { f, err := os.Stat(source) logrus.Debugf("dir: %s\n", source) if err != nil { if os.IsNotExist(err) { return "dir" } return "" } if f.IsDir() { return "dir" } return "file" } func getMemorySwap(v *execdriver.Resources) int64 { // By default, MemorySwap is set to twice the size of RAM. // If you want to omit MemorySwap, set it to `-1'. if v.MemorySwap < 0 { return 0 } return v.Memory * 2 } func getLabel(c map[string][]string, name string) string { label := c["label"] for _, l := range label { parts := strings.SplitN(l, "=", 2) if strings.TrimSpace(parts[0]) == name { return strings.TrimSpace(parts[1]) } } return "" } func getHostname(env []string) string { for _, kv := range env { parts := strings.SplitN(kv, "=", 2) if parts[0] == "HOSTNAME" && len(parts) == 2 { return parts[1] } } return "" } func init() { var err error funcMap := template.FuncMap{ "getMemorySwap": getMemorySwap, "escapeFstabSpaces": escapeFstabSpaces, "formatMountLabel": label.FormatMountLabel, "isDirectory": isDirectory, "keepCapabilities": keepCapabilities, "dropList": dropList, "getHostname": getHostname, } LxcTemplateCompiled, err = template.New("lxc").Funcs(funcMap).Parse(LxcTemplate) if err != nil { panic(err) } } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/lxc/lxc_template_unit_test.go ================================================ // +build linux package lxc import ( "bufio" "fmt" "io/ioutil" "math/rand" "os" "path" "strings" "testing" "time" "github.com/docker/docker/daemon/execdriver" nativeTemplate "github.com/docker/docker/daemon/execdriver/native/template" "github.com/opencontainers/runc/libcontainer/configs" "github.com/syndtr/gocapability/capability" ) func TestLXCConfig(t *testing.T) { root, err := ioutil.TempDir("", "TestLXCConfig") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) os.MkdirAll(path.Join(root, "containers", "1"), 0777) // Memory is allocated randomly for testing r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) var ( memMin = 33554432 memMax = 536870912 mem = memMin + r.Intn(memMax-memMin) cpuMin = 100 cpuMax = 10000 cpu = cpuMin + r.Intn(cpuMax-cpuMin) ) driver, err := NewDriver(root, root, "", false) if err != nil { t.Fatal(err) } command := &execdriver.Command{ ID: "1", Resources: &execdriver.Resources{ Memory: int64(mem), CpuShares: int64(cpu), }, Network: &execdriver.Network{ Mtu: 1500, Interface: nil, }, AllowedDevices: make([]*configs.Device, 0), ProcessConfig: execdriver.ProcessConfig{}, } p, err := driver.generateLXCConfig(command) if err != nil { t.Fatal(err) } grepFile(t, p, fmt.Sprintf("lxc.cgroup.memory.limit_in_bytes = %d", mem)) grepFile(t, p, fmt.Sprintf("lxc.cgroup.memory.memsw.limit_in_bytes = %d", mem*2)) } func TestCustomLxcConfig(t *testing.T) { root, err := ioutil.TempDir("", "TestCustomLxcConfig") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) os.MkdirAll(path.Join(root, "containers", "1"), 0777) driver, err := NewDriver(root, root, "", false) if err != nil { t.Fatal(err) } processConfig := execdriver.ProcessConfig{ Privileged: false, } command := &execdriver.Command{ ID: "1", LxcConfig: []string{ "lxc.utsname = docker", "lxc.cgroup.cpuset.cpus = 0,1", }, Network: &execdriver.Network{ Mtu: 1500, Interface: nil, }, ProcessConfig: processConfig, } p, err := driver.generateLXCConfig(command) if err != nil { t.Fatal(err) } grepFile(t, p, "lxc.utsname = docker") grepFile(t, p, "lxc.cgroup.cpuset.cpus = 0,1") } func grepFile(t *testing.T, path string, pattern string) { grepFileWithReverse(t, path, pattern, false) } func grepFileWithReverse(t *testing.T, path string, pattern string, inverseGrep bool) { f, err := os.Open(path) if err != nil { t.Fatal(err) } defer f.Close() r := bufio.NewReader(f) var ( line string ) err = nil for err == nil { line, err = r.ReadString('\n') if strings.Contains(line, pattern) == true { if inverseGrep { t.Fatalf("grepFile: pattern \"%s\" found in \"%s\"", pattern, path) } return } } if inverseGrep { return } t.Fatalf("grepFile: pattern \"%s\" not found in \"%s\"", pattern, path) } func TestEscapeFstabSpaces(t *testing.T) { var testInputs = map[string]string{ " ": "\\040", "": "", "/double space": "/double\\040\\040space", "/some long test string": "/some\\040long\\040test\\040string", "/var/lib/docker": "/var/lib/docker", " leading": "\\040leading", "trailing ": "trailing\\040", } for in, exp := range testInputs { if out := escapeFstabSpaces(in); exp != out { t.Logf("Expected %s got %s", exp, out) t.Fail() } } } func TestIsDirectory(t *testing.T) { tempDir, err := ioutil.TempDir("", "TestIsDir") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) tempFile, err := ioutil.TempFile(tempDir, "TestIsDirFile") if err != nil { t.Fatal(err) } if isDirectory(tempDir) != "dir" { t.Logf("Could not identify %s as a directory", tempDir) t.Fail() } if isDirectory(tempFile.Name()) != "file" { t.Logf("Could not identify %s as a file", tempFile.Name()) t.Fail() } } func TestCustomLxcConfigMounts(t *testing.T) { root, err := ioutil.TempDir("", "TestCustomLxcConfig") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) tempDir, err := ioutil.TempDir("", "TestIsDir") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) tempFile, err := ioutil.TempFile(tempDir, "TestIsDirFile") if err != nil { t.Fatal(err) } os.MkdirAll(path.Join(root, "containers", "1"), 0777) driver, err := NewDriver(root, root, "", false) if err != nil { t.Fatal(err) } processConfig := execdriver.ProcessConfig{ Privileged: false, } mounts := []execdriver.Mount{ { Source: tempDir, Destination: tempDir, Writable: false, Private: true, }, { Source: tempFile.Name(), Destination: tempFile.Name(), Writable: true, Private: true, }, } command := &execdriver.Command{ ID: "1", LxcConfig: []string{ "lxc.utsname = docker", "lxc.cgroup.cpuset.cpus = 0,1", }, Network: &execdriver.Network{ Mtu: 1500, Interface: nil, }, Mounts: mounts, ProcessConfig: processConfig, } p, err := driver.generateLXCConfig(command) if err != nil { t.Fatal(err) } grepFile(t, p, "lxc.utsname = docker") grepFile(t, p, "lxc.cgroup.cpuset.cpus = 0,1") grepFile(t, p, fmt.Sprintf("lxc.mount.entry = %s %s none rbind,ro,create=%s 0 0", tempDir, "/"+tempDir, "dir")) grepFile(t, p, fmt.Sprintf("lxc.mount.entry = %s %s none rbind,rw,create=%s 0 0", tempFile.Name(), "/"+tempFile.Name(), "file")) } func TestCustomLxcConfigMisc(t *testing.T) { root, err := ioutil.TempDir("", "TestCustomLxcConfig") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) os.MkdirAll(path.Join(root, "containers", "1"), 0777) driver, err := NewDriver(root, root, "", true) if err != nil { t.Fatal(err) } processConfig := execdriver.ProcessConfig{ Privileged: false, } processConfig.Env = []string{"HOSTNAME=testhost"} command := &execdriver.Command{ ID: "1", LxcConfig: []string{ "lxc.cgroup.cpuset.cpus = 0,1", }, Network: &execdriver.Network{ Mtu: 1500, Interface: nil, }, ProcessConfig: processConfig, CapAdd: []string{"net_admin", "syslog"}, CapDrop: []string{"kill", "mknod"}, AppArmorProfile: "lxc-container-default-with-nesting", } p, err := driver.generateLXCConfig(command) if err != nil { t.Fatal(err) } grepFile(t, p, "lxc.aa_profile = lxc-container-default-with-nesting") // hostname grepFile(t, p, "lxc.utsname = testhost") grepFile(t, p, "lxc.cgroup.cpuset.cpus = 0,1") container := nativeTemplate.New() for _, cap := range container.Capabilities { realCap := execdriver.GetCapability(cap) numCap := fmt.Sprintf("%d", realCap.Value) if cap != "MKNOD" && cap != "KILL" { grepFile(t, p, fmt.Sprintf("lxc.cap.keep = %s", numCap)) } } grepFileWithReverse(t, p, fmt.Sprintf("lxc.cap.keep = %d", capability.CAP_KILL), true) grepFileWithReverse(t, p, fmt.Sprintf("lxc.cap.keep = %d", capability.CAP_MKNOD), true) } func TestCustomLxcConfigMiscOverride(t *testing.T) { root, err := ioutil.TempDir("", "TestCustomLxcConfig") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) os.MkdirAll(path.Join(root, "containers", "1"), 0777) driver, err := NewDriver(root, root, "", false) if err != nil { t.Fatal(err) } processConfig := execdriver.ProcessConfig{ Privileged: false, } processConfig.Env = []string{"HOSTNAME=testhost"} command := &execdriver.Command{ ID: "1", LxcConfig: []string{ "lxc.cgroup.cpuset.cpus = 0,1", "lxc.network.ipv4 = 172.0.0.1", }, Network: &execdriver.Network{ Mtu: 1500, Interface: nil, }, ProcessConfig: processConfig, CapAdd: []string{"NET_ADMIN", "SYSLOG"}, CapDrop: []string{"KILL", "MKNOD"}, } p, err := driver.generateLXCConfig(command) if err != nil { t.Fatal(err) } // hostname grepFile(t, p, "lxc.utsname = testhost") grepFile(t, p, "lxc.cgroup.cpuset.cpus = 0,1") container := nativeTemplate.New() for _, cap := range container.Capabilities { realCap := execdriver.GetCapability(cap) numCap := fmt.Sprintf("%d", realCap.Value) if cap != "MKNOD" && cap != "KILL" { grepFile(t, p, fmt.Sprintf("lxc.cap.keep = %s", numCap)) } } grepFileWithReverse(t, p, fmt.Sprintf("lxc.cap.keep = %d", capability.CAP_KILL), true) grepFileWithReverse(t, p, fmt.Sprintf("lxc.cap.keep = %d", capability.CAP_MKNOD), true) } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/create.go ================================================ // +build linux,cgo package native import ( "errors" "fmt" "net" "strings" "syscall" "github.com/docker/docker/daemon/execdriver" "github.com/opencontainers/runc/libcontainer/apparmor" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/devices" "github.com/opencontainers/runc/libcontainer/utils" ) // createContainer populates and configures the container type with the // data provided by the execdriver.Command func (d *driver) createContainer(c *execdriver.Command) (*configs.Config, error) { container := execdriver.InitContainer(c) if err := d.createIpc(container, c); err != nil { return nil, err } if err := d.createPid(container, c); err != nil { return nil, err } if err := d.createUTS(container, c); err != nil { return nil, err } if err := d.createNetwork(container, c); err != nil { return nil, err } if c.ProcessConfig.Privileged { if !container.Readonlyfs { // clear readonly for /sys for i := range container.Mounts { if container.Mounts[i].Destination == "/sys" { container.Mounts[i].Flags &= ^syscall.MS_RDONLY } } container.ReadonlyPaths = nil } // clear readonly for cgroup for i := range container.Mounts { if container.Mounts[i].Device == "cgroup" { container.Mounts[i].Flags &= ^syscall.MS_RDONLY } } container.MaskPaths = nil if err := d.setPrivileged(container); err != nil { return nil, err } } else { if err := d.setCapabilities(container, c); err != nil { return nil, err } } container.AdditionalGroups = c.GroupAdd if c.AppArmorProfile != "" { container.AppArmorProfile = c.AppArmorProfile } if err := execdriver.SetupCgroups(container, c); err != nil { return nil, err } if container.Readonlyfs { for i := range container.Mounts { switch container.Mounts[i].Destination { case "/proc", "/dev", "/dev/pts": continue } container.Mounts[i].Flags |= syscall.MS_RDONLY } /* These paths must be remounted as r/o */ container.ReadonlyPaths = append(container.ReadonlyPaths, "/proc", "/dev") } if err := d.setupMounts(container, c); err != nil { return nil, err } d.setupLabels(container, c) d.setupRlimits(container, c) return container, nil } func generateIfaceName() (string, error) { for i := 0; i < 10; i++ { name, err := utils.GenerateRandomName("veth", 7) if err != nil { continue } if _, err := net.InterfaceByName(name); err != nil { if strings.Contains(err.Error(), "no such") { return name, nil } return "", err } } return "", errors.New("Failed to find name for new interface") } func (d *driver) createNetwork(container *configs.Config, c *execdriver.Command) error { if c.Network == nil { return nil } if c.Network.ContainerID != "" { d.Lock() active := d.activeContainers[c.Network.ContainerID] d.Unlock() if active == nil { return fmt.Errorf("%s is not a valid running container to join", c.Network.ContainerID) } state, err := active.State() if err != nil { return err } container.Namespaces.Add(configs.NEWNET, state.NamespacePaths[configs.NEWNET]) return nil } if c.Network.NamespacePath == "" { return fmt.Errorf("network namespace path is empty") } container.Namespaces.Add(configs.NEWNET, c.Network.NamespacePath) return nil } func (d *driver) createIpc(container *configs.Config, c *execdriver.Command) error { if c.Ipc.HostIpc { container.Namespaces.Remove(configs.NEWIPC) return nil } if c.Ipc.ContainerID != "" { d.Lock() active := d.activeContainers[c.Ipc.ContainerID] d.Unlock() if active == nil { return fmt.Errorf("%s is not a valid running container to join", c.Ipc.ContainerID) } state, err := active.State() if err != nil { return err } container.Namespaces.Add(configs.NEWIPC, state.NamespacePaths[configs.NEWIPC]) } return nil } func (d *driver) createPid(container *configs.Config, c *execdriver.Command) error { if c.Pid.HostPid { container.Namespaces.Remove(configs.NEWPID) return nil } return nil } func (d *driver) createUTS(container *configs.Config, c *execdriver.Command) error { if c.UTS.HostUTS { container.Namespaces.Remove(configs.NEWUTS) container.Hostname = "" return nil } return nil } func (d *driver) setPrivileged(container *configs.Config) (err error) { container.Capabilities = execdriver.GetAllCapabilities() container.Cgroups.AllowAllDevices = true hostDevices, err := devices.HostDevices() if err != nil { return err } container.Devices = hostDevices if apparmor.IsEnabled() { container.AppArmorProfile = "unconfined" } return nil } func (d *driver) setCapabilities(container *configs.Config, c *execdriver.Command) (err error) { container.Capabilities, err = execdriver.TweakCapabilities(container.Capabilities, c.CapAdd, c.CapDrop) return err } func (d *driver) setupRlimits(container *configs.Config, c *execdriver.Command) { if c.Resources == nil { return } for _, rlimit := range c.Resources.Rlimits { container.Rlimits = append(container.Rlimits, configs.Rlimit{ Type: rlimit.Type, Hard: rlimit.Hard, Soft: rlimit.Soft, }) } } func (d *driver) setupMounts(container *configs.Config, c *execdriver.Command) error { userMounts := make(map[string]struct{}) for _, m := range c.Mounts { userMounts[m.Destination] = struct{}{} } // Filter out mounts that are overriden by user supplied mounts var defaultMounts []*configs.Mount _, mountDev := userMounts["/dev"] for _, m := range container.Mounts { if _, ok := userMounts[m.Destination]; !ok { if mountDev && strings.HasPrefix(m.Destination, "/dev/") { continue } defaultMounts = append(defaultMounts, m) } } container.Mounts = defaultMounts for _, m := range c.Mounts { flags := syscall.MS_BIND | syscall.MS_REC if !m.Writable { flags |= syscall.MS_RDONLY } if m.Slave { flags |= syscall.MS_SLAVE } container.Mounts = append(container.Mounts, &configs.Mount{ Source: m.Source, Destination: m.Destination, Device: "bind", Flags: flags, }) } return nil } func (d *driver) setupLabels(container *configs.Config, c *execdriver.Command) { container.ProcessLabel = c.ProcessLabel container.MountLabel = c.MountLabel } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/driver.go ================================================ // +build linux,cgo package native import ( "fmt" "io" "os" "os/exec" "path/filepath" "strings" "sync" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/reexec" sysinfo "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/term" "github.com/opencontainers/runc/libcontainer" "github.com/opencontainers/runc/libcontainer/cgroups/systemd" "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/system" "github.com/opencontainers/runc/libcontainer/utils" ) const ( DriverName = "native" Version = "0.2" ) type driver struct { root string initPath string activeContainers map[string]libcontainer.Container machineMemory int64 factory libcontainer.Factory sync.Mutex } func NewDriver(root, initPath string, options []string) (*driver, error) { meminfo, err := sysinfo.ReadMemInfo() if err != nil { return nil, err } if err := sysinfo.MkdirAll(root, 0700); err != nil { return nil, err } // choose cgroup manager // this makes sure there are no breaking changes to people // who upgrade from versions without native.cgroupdriver opt cgm := libcontainer.Cgroupfs if systemd.UseSystemd() { cgm = libcontainer.SystemdCgroups } // parse the options for _, option := range options { key, val, err := parsers.ParseKeyValueOpt(option) if err != nil { return nil, err } key = strings.ToLower(key) switch key { case "native.cgroupdriver": // override the default if they set options switch val { case "systemd": if systemd.UseSystemd() { cgm = libcontainer.SystemdCgroups } else { // warn them that they chose the wrong driver logrus.Warn("You cannot use systemd as native.cgroupdriver, using cgroupfs instead") } case "cgroupfs": cgm = libcontainer.Cgroupfs default: return nil, fmt.Errorf("Unknown native.cgroupdriver given %q. try cgroupfs or systemd", val) } default: return nil, fmt.Errorf("Unknown option %s\n", key) } } f, err := libcontainer.New( root, cgm, libcontainer.InitPath(reexec.Self(), DriverName), ) if err != nil { return nil, err } return &driver{ root: root, initPath: initPath, activeContainers: make(map[string]libcontainer.Container), machineMemory: meminfo.MemTotal, factory: f, }, nil } type execOutput struct { exitCode int err error } func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { // take the Command and populate the libcontainer.Config from it container, err := d.createContainer(c) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } p := &libcontainer.Process{ Args: append([]string{c.ProcessConfig.Entrypoint}, c.ProcessConfig.Arguments...), Env: c.ProcessConfig.Env, Cwd: c.WorkingDir, User: c.ProcessConfig.User, } if err := setupPipes(container, &c.ProcessConfig, p, pipes); err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } cont, err := d.factory.Create(c.ID, container) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } d.Lock() d.activeContainers[c.ID] = cont d.Unlock() defer func() { cont.Destroy() d.cleanContainer(c.ID) }() if err := cont.Start(p); err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } if startCallback != nil { pid, err := p.Pid() if err != nil { p.Signal(os.Kill) p.Wait() return execdriver.ExitStatus{ExitCode: -1}, err } startCallback(&c.ProcessConfig, pid) } oom := notifyOnOOM(cont) waitF := p.Wait if nss := cont.Config().Namespaces; !nss.Contains(configs.NEWPID) { // we need such hack for tracking processes with inherited fds, // because cmd.Wait() waiting for all streams to be copied waitF = waitInPIDHost(p, cont) } ps, err := waitF() if err != nil { execErr, ok := err.(*exec.ExitError) if !ok { return execdriver.ExitStatus{ExitCode: -1}, err } ps = execErr.ProcessState } cont.Destroy() _, oomKill := <-oom return execdriver.ExitStatus{ExitCode: utils.ExitStatus(ps.Sys().(syscall.WaitStatus)), OOMKilled: oomKill}, nil } // notifyOnOOM returns a channel that signals if the container received an OOM notification // for any process. If it is unable to subscribe to OOM notifications then a closed // channel is returned as it will be non-blocking and return the correct result when read. func notifyOnOOM(container libcontainer.Container) <-chan struct{} { oom, err := container.NotifyOOM() if err != nil { logrus.Warnf("Your kernel does not support OOM notifications: %s", err) c := make(chan struct{}) close(c) return c } return oom } func killCgroupProcs(c libcontainer.Container) { var procs []*os.Process if err := c.Pause(); err != nil { logrus.Warn(err) } pids, err := c.Processes() if err != nil { // don't care about childs if we can't get them, this is mostly because cgroup already deleted logrus.Warnf("Failed to get processes from container %s: %v", c.ID(), err) } for _, pid := range pids { if p, err := os.FindProcess(pid); err == nil { procs = append(procs, p) if err := p.Kill(); err != nil { logrus.Warn(err) } } } if err := c.Resume(); err != nil { logrus.Warn(err) } for _, p := range procs { if _, err := p.Wait(); err != nil { logrus.Warn(err) } } } func waitInPIDHost(p *libcontainer.Process, c libcontainer.Container) func() (*os.ProcessState, error) { return func() (*os.ProcessState, error) { pid, err := p.Pid() if err != nil { return nil, err } process, err := os.FindProcess(pid) s, err := process.Wait() if err != nil { execErr, ok := err.(*exec.ExitError) if !ok { return s, err } s = execErr.ProcessState } killCgroupProcs(c) p.Wait() return s, err } } func (d *driver) Kill(c *execdriver.Command, sig int) error { d.Lock() active := d.activeContainers[c.ID] d.Unlock() if active == nil { return fmt.Errorf("active container for %s does not exist", c.ID) } state, err := active.State() if err != nil { return err } return syscall.Kill(state.InitProcessPid, syscall.Signal(sig)) } func (d *driver) Pause(c *execdriver.Command) error { d.Lock() active := d.activeContainers[c.ID] d.Unlock() if active == nil { return fmt.Errorf("active container for %s does not exist", c.ID) } return active.Pause() } func (d *driver) Unpause(c *execdriver.Command) error { d.Lock() active := d.activeContainers[c.ID] d.Unlock() if active == nil { return fmt.Errorf("active container for %s does not exist", c.ID) } return active.Resume() } func (d *driver) Terminate(c *execdriver.Command) error { defer d.cleanContainer(c.ID) container, err := d.factory.Load(c.ID) if err != nil { return err } defer container.Destroy() state, err := container.State() if err != nil { return err } pid := state.InitProcessPid currentStartTime, err := system.GetProcessStartTime(pid) if err != nil { return err } if state.InitProcessStartTime == currentStartTime { err = syscall.Kill(pid, 9) syscall.Wait4(pid, nil, 0, nil) } return err } func (d *driver) Info(id string) execdriver.Info { return &info{ ID: id, driver: d, } } func (d *driver) Name() string { return fmt.Sprintf("%s-%s", DriverName, Version) } func (d *driver) GetPidsForContainer(id string) ([]int, error) { d.Lock() active := d.activeContainers[id] d.Unlock() if active == nil { return nil, fmt.Errorf("active container for %s does not exist", id) } return active.Processes() } func (d *driver) cleanContainer(id string) error { d.Lock() delete(d.activeContainers, id) d.Unlock() return os.RemoveAll(filepath.Join(d.root, id)) } func (d *driver) createContainerRoot(id string) error { return os.MkdirAll(filepath.Join(d.root, id), 0655) } func (d *driver) Clean(id string) error { return os.RemoveAll(filepath.Join(d.root, id)) } func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) { d.Lock() c := d.activeContainers[id] d.Unlock() if c == nil { return nil, execdriver.ErrNotRunning } now := time.Now() stats, err := c.Stats() if err != nil { return nil, err } memoryLimit := c.Config().Cgroups.Memory // if the container does not have any memory limit specified set the // limit to the machines memory if memoryLimit == 0 { memoryLimit = d.machineMemory } return &execdriver.ResourceStats{ Stats: stats, Read: now, MemoryLimit: memoryLimit, }, nil } type TtyConsole struct { console libcontainer.Console } func NewTtyConsole(console libcontainer.Console, pipes *execdriver.Pipes) (*TtyConsole, error) { tty := &TtyConsole{ console: console, } if err := tty.AttachPipes(pipes); err != nil { tty.Close() return nil, err } return tty, nil } func (t *TtyConsole) Resize(h, w int) error { return term.SetWinsize(t.console.Fd(), &term.Winsize{Height: uint16(h), Width: uint16(w)}) } func (t *TtyConsole) AttachPipes(pipes *execdriver.Pipes) error { go func() { if wb, ok := pipes.Stdout.(interface { CloseWriters() error }); ok { defer wb.CloseWriters() } pools.Copy(pipes.Stdout, t.console) }() if pipes.Stdin != nil { go func() { pools.Copy(t.console, pipes.Stdin) pipes.Stdin.Close() }() } return nil } func (t *TtyConsole) Close() error { return t.console.Close() } func setupPipes(container *configs.Config, processConfig *execdriver.ProcessConfig, p *libcontainer.Process, pipes *execdriver.Pipes) error { var term execdriver.Terminal var err error if processConfig.Tty { rootuid, err := container.HostUID() if err != nil { return err } cons, err := p.NewConsole(rootuid) if err != nil { return err } term, err = NewTtyConsole(cons, pipes) } else { p.Stdout = pipes.Stdout p.Stderr = pipes.Stderr r, w, err := os.Pipe() if err != nil { return err } if pipes.Stdin != nil { go func() { io.Copy(w, pipes.Stdin) w.Close() }() p.Stdin = r } term = &execdriver.StdConsole{} } if err != nil { return err } processConfig.Terminal = term return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/driver_unsupported.go ================================================ // +build !linux package native import ( "fmt" "github.com/docker/docker/daemon/execdriver" ) func NewDriver(root, initPath string) (execdriver.Driver, error) { return nil, fmt.Errorf("native driver not supported on non-linux") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/driver_unsupported_nocgo.go ================================================ // +build linux,!cgo package native import ( "fmt" "github.com/docker/docker/daemon/execdriver" ) func NewDriver(root, initPath string) (execdriver.Driver, error) { return nil, fmt.Errorf("native driver not supported on non-linux") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/exec.go ================================================ // +build linux package native import ( "fmt" "os" "os/exec" "syscall" "github.com/docker/docker/daemon/execdriver" "github.com/opencontainers/runc/libcontainer" _ "github.com/opencontainers/runc/libcontainer/nsenter" "github.com/opencontainers/runc/libcontainer/utils" ) // TODO(vishh): Add support for running in privileged mode. func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { active := d.activeContainers[c.ID] if active == nil { return -1, fmt.Errorf("No active container exists with ID %s", c.ID) } p := &libcontainer.Process{ Args: append([]string{processConfig.Entrypoint}, processConfig.Arguments...), Env: c.ProcessConfig.Env, Cwd: c.WorkingDir, User: processConfig.User, } config := active.Config() if err := setupPipes(&config, processConfig, p, pipes); err != nil { return -1, err } if err := active.Start(p); err != nil { return -1, err } if startCallback != nil { pid, err := p.Pid() if err != nil { p.Signal(os.Kill) p.Wait() return -1, err } startCallback(&c.ProcessConfig, pid) } ps, err := p.Wait() if err != nil { exitErr, ok := err.(*exec.ExitError) if !ok { return -1, err } ps = exitErr.ProcessState } return utils.ExitStatus(ps.Sys().(syscall.WaitStatus)), nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/info.go ================================================ // +build linux,cgo package native type info struct { ID string driver *driver } // IsRunning is determined by looking for the // pid file for a container. If the file exists then the // container is currently running func (i *info) IsRunning() bool { _, ok := i.driver.activeContainers[i.ID] return ok } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/init.go ================================================ // +build linux package native import ( "fmt" "os" "runtime" "github.com/docker/docker/pkg/reexec" "github.com/opencontainers/runc/libcontainer" ) func init() { reexec.Register(DriverName, initializer) } func fatal(err error) { if lerr, ok := err.(libcontainer.Error); ok { lerr.Detail(os.Stderr) os.Exit(1) } fmt.Fprintln(os.Stderr, err) os.Exit(1) } func initializer() { runtime.GOMAXPROCS(1) runtime.LockOSThread() factory, err := libcontainer.New("") if err != nil { fatal(err) } if err := factory.StartInitialization(); err != nil { fatal(err) } panic("unreachable") } func writeError(err error) { fmt.Fprint(os.Stderr, err) os.Exit(1) } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/native/template/default_template.go ================================================ package template import ( "syscall" "github.com/opencontainers/runc/libcontainer/apparmor" "github.com/opencontainers/runc/libcontainer/configs" ) const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV // New returns the docker default configuration for libcontainer func New() *configs.Config { container := &configs.Config{ Capabilities: []string{ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE", }, Namespaces: configs.Namespaces([]configs.Namespace{ {Type: "NEWNS"}, {Type: "NEWUTS"}, {Type: "NEWIPC"}, {Type: "NEWPID"}, {Type: "NEWNET"}, }), Cgroups: &configs.Cgroup{ Parent: "docker", AllowAllDevices: false, MemorySwappiness: -1, }, 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, }, { Source: "cgroup", Destination: "/sys/fs/cgroup", Device: "cgroup", Flags: defaultMountFlags | syscall.MS_RDONLY, }, }, MaskPaths: []string{ "/proc/kcore", "/proc/latency_stats", "/proc/timer_stats", }, ReadonlyPaths: []string{ "/proc/asound", "/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger", }, } if apparmor.IsEnabled() { container.AppArmorProfile = "docker-default" } return container } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/pipes.go ================================================ package execdriver import ( "io" ) // Pipes is a wrapper around a containers output for // stdin, stdout, stderr type Pipes struct { Stdin io.ReadCloser Stdout, Stderr io.Writer } func NewPipes(stdin io.ReadCloser, stdout, stderr io.Writer, useStdin bool) *Pipes { p := &Pipes{ Stdout: stdout, Stderr: stderr, } if useStdin { p.Stdin = stdin } return p } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/termconsole.go ================================================ package execdriver import ( "io" "os/exec" ) type StdConsole struct { } func NewStdConsole(processConfig *ProcessConfig, pipes *Pipes) (*StdConsole, error) { std := &StdConsole{} if err := std.AttachPipes(&processConfig.Cmd, pipes); err != nil { return nil, err } return std, nil } func (s *StdConsole) AttachPipes(command *exec.Cmd, pipes *Pipes) error { command.Stdout = pipes.Stdout command.Stderr = pipes.Stderr if pipes.Stdin != nil { stdin, err := command.StdinPipe() if err != nil { return err } go func() { defer stdin.Close() io.Copy(stdin, pipes.Stdin) }() } return nil } func (s *StdConsole) Resize(h, w int) error { // we do not need to reside a non tty return nil } func (s *StdConsole) Close() error { // nothing to close here return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/utils.go ================================================ package execdriver import ( "fmt" "strings" "github.com/docker/docker/pkg/stringutils" "github.com/syndtr/gocapability/capability" ) var capabilityList Capabilities func init() { last := capability.CAP_LAST_CAP // hack 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 } capabilityList = append(capabilityList, &CapabilityMapping{ Key: strings.ToUpper(cap.String()), Value: cap, }, ) } } type ( CapabilityMapping struct { Key string `json:"key,omitempty"` Value capability.Cap `json:"value,omitempty"` } Capabilities []*CapabilityMapping ) func (c *CapabilityMapping) String() string { return c.Key } func GetCapability(key string) *CapabilityMapping { for _, capp := range capabilityList { if capp.Key == key { cpy := *capp return &cpy } } return nil } func GetAllCapabilities() []string { output := make([]string, len(capabilityList)) for i, capability := range capabilityList { output[i] = capability.String() } return output } func TweakCapabilities(basics, adds, drops []string) ([]string, error) { var ( newCaps []string allCaps = GetAllCapabilities() ) // look for invalid cap in the drop list for _, cap := range drops { if strings.ToLower(cap) == "all" { continue } if !stringutils.InSlice(allCaps, cap) { return nil, fmt.Errorf("Unknown capability drop: %q", cap) } } // handle --cap-add=all if stringutils.InSlice(adds, "all") { basics = allCaps } if !stringutils.InSlice(drops, "all") { for _, cap := range basics { // skip `all` aready handled above if strings.ToLower(cap) == "all" { continue } // if we don't drop `all`, add back all the non-dropped caps if !stringutils.InSlice(drops, cap) { newCaps = append(newCaps, strings.ToUpper(cap)) } } } for _, cap := range adds { // skip `all` aready handled above if strings.ToLower(cap) == "all" { continue } if !stringutils.InSlice(allCaps, cap) { return nil, fmt.Errorf("Unknown capability to add: %q", cap) } // add cap if not already in the list if !stringutils.InSlice(newCaps, cap) { newCaps = append(newCaps, strings.ToUpper(cap)) } } return newCaps, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/checkoptions.go ================================================ // +build windows package windows import ( "errors" "github.com/docker/docker/daemon/execdriver" ) func checkSupportedOptions(c *execdriver.Command) error { // Windows doesn't support read-only root filesystem if c.ReadonlyRootfs { return errors.New("Windows does not support the read-only root filesystem option") } // Windows doesn't support username if c.ProcessConfig.User != "" { return errors.New("Windows does not support the username option") } // Windows doesn't support custom lxc options if c.LxcConfig != nil { return errors.New("Windows does not support lxc options") } // Windows doesn't support ulimit if c.Resources.Rlimits != nil { return errors.New("Windows does not support ulimit options") } // TODO Windows: Validate other fields which Windows doesn't support, factor // out where applicable per platform. return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/clean.go ================================================ // +build windows package windows func (d *driver) Clean(id string) error { return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/exec.go ================================================ // +build windows package windows import ( "errors" "fmt" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/stringid" "github.com/microsoft/hcsshim" "github.com/natefinch/npipe" ) func (d *driver) Exec(c *execdriver.Command, processConfig *execdriver.ProcessConfig, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) { var ( inListen, outListen, errListen *npipe.PipeListener term execdriver.Terminal err error randomID string = stringid.GenerateRandomID() serverPipeFormat, clientPipeFormat string pid uint32 exitCode int32 ) active := d.activeContainers[c.ID] if active == nil { return -1, fmt.Errorf("Exec - No active container exists with ID %s", c.ID) } createProcessParms := hcsshim.CreateProcessParams{ EmulateConsole: processConfig.Tty, // Note NOT c.ProcessConfig.Tty WorkingDirectory: c.WorkingDir, } // Configure the environment for the process // Note NOT c.ProcessConfig.Tty createProcessParms.Environment = setupEnvironmentVariables(processConfig.Env) // We use another unique ID here for each exec instance otherwise it // may conflict with the pipe name being used by RUN. // We use a different pipe name between real and dummy mode in the HCS if dummyMode { clientPipeFormat = `\\.\pipe\docker-exec-%[1]s-%[2]s-%[3]s` serverPipeFormat = clientPipeFormat } else { clientPipeFormat = `\\.\pipe\docker-exec-%[2]s-%[3]s` serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-exec-%[2]s-%[3]s` } // Connect stdin if pipes.Stdin != nil { stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stdin") createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stdin") // Listen on the named pipe inListen, err = npipe.Listen(stdInPipe) if err != nil { logrus.Errorf("stdin failed to listen on %s %s ", stdInPipe, err) return -1, err } defer inListen.Close() // Launch a goroutine to do the accept. We do this so that we can // cause an otherwise blocking goroutine to gracefully close when // the caller (us) closes the listener go stdinAccept(inListen, stdInPipe, pipes.Stdin) } // Connect stdout stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stdout") createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stdout") outListen, err = npipe.Listen(stdOutPipe) if err != nil { logrus.Errorf("stdout failed to listen on %s %s", stdOutPipe, err) return -1, err } defer outListen.Close() go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout) // No stderr on TTY. Note NOT c.ProcessConfig.Tty if !processConfig.Tty { // Connect stderr stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, randomID, "stderr") createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, randomID, "stderr") errListen, err = npipe.Listen(stdErrPipe) if err != nil { logrus.Errorf("Stderr failed to listen on %s %s", stdErrPipe, err) return -1, err } defer errListen.Close() go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr) } // While this should get caught earlier, just in case, validate that we // have something to run. if processConfig.Entrypoint == "" { err = errors.New("No entrypoint specified") logrus.Error(err) return -1, err } // Build the command line of the process createProcessParms.CommandLine = processConfig.Entrypoint for _, arg := range processConfig.Arguments { logrus.Debugln("appending ", arg) createProcessParms.CommandLine += " " + arg } logrus.Debugln("commandLine: ", createProcessParms.CommandLine) // Start the command running in the container. pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms) if err != nil { logrus.Errorf("CreateProcessInComputeSystem() failed %s", err) return -1, err } // Note NOT c.ProcessConfig.Tty if processConfig.Tty { term = NewTtyConsole(c.ID, pid) } else { term = NewStdConsole() } processConfig.Terminal = term // Invoke the start callback if startCallback != nil { startCallback(&c.ProcessConfig, int(pid)) } if exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid); err != nil { logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err) return -1, err } // TODO Windows - Do something with this exit code logrus.Debugln("Exiting Run() with ExitCode 0", c.ID) return int(exitCode), nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/getpids.go ================================================ // +build windows package windows import "fmt" func (d *driver) GetPidsForContainer(id string) ([]int, error) { // TODO Windows: Implementation required. return nil, fmt.Errorf("GetPidsForContainer: GetPidsForContainer() not implemented") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/info.go ================================================ // +build windows package windows import "github.com/docker/docker/daemon/execdriver" type info struct { ID string driver *driver } func (d *driver) Info(id string) execdriver.Info { return &info{ ID: id, driver: d, } } func (i *info) IsRunning() bool { var running bool running = true // TODO Need an HCS API return running } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/namedpipes.go ================================================ // +build windows package windows import ( "io" "github.com/Sirupsen/logrus" "github.com/natefinch/npipe" ) // stdinAccept runs as a go function. It waits for the container system // to accept our offer of a named pipe for stdin. Once accepted, if we are // running "attached" to the container (eg docker run -i), then we spin up // a further thread to copy anything from the client into the container. // // Important design note. This function is run as a go function for a very // good reason. The named pipe Accept call is blocking until one of two things // happen. Either someone connects to it, or it is forcibly closed. Let's // assume that no-one connects to it, the only way otherwise the Run() // method would continue is by closing it. However, as that would be the same // thread, it can't close it. Hence we run as another thread allowing Run() // to close the named pipe. func stdinAccept(inListen *npipe.PipeListener, pipeName string, copyfrom io.ReadCloser) { // Wait for the pipe to be connected to by the shim logrus.Debugln("stdinAccept: Waiting on ", pipeName) stdinConn, err := inListen.Accept() if err != nil { logrus.Errorf("Failed to accept on pipe %s %s", pipeName, err) return } logrus.Debugln("Connected to ", stdinConn.RemoteAddr()) // Anything that comes from the client stdin should be copied // across to the stdin named pipe of the container. if copyfrom != nil { go func() { defer stdinConn.Close() logrus.Debugln("Calling io.Copy on stdin") bytes, err := io.Copy(stdinConn, copyfrom) logrus.Debugf("Finished io.Copy on stdin bytes=%d err=%s pipe=%s", bytes, err, stdinConn.RemoteAddr()) }() } else { defer stdinConn.Close() } } // stdouterrAccept runs as a go function. It waits for the container system to // accept our offer of a named pipe - in fact two of them - one for stdout // and one for stderr (we are called twice). Once the named pipe is accepted, // if we are running "attached" to the container (eg docker run -i), then we // spin up a further thread to copy anything from the containers output channels // to the client. func stdouterrAccept(outerrListen *npipe.PipeListener, pipeName string, copyto io.Writer) { // Wait for the pipe to be connected to by the shim logrus.Debugln("out/err: Waiting on ", pipeName) outerrConn, err := outerrListen.Accept() if err != nil { logrus.Errorf("Failed to accept on pipe %s %s", pipeName, err) return } logrus.Debugln("Connected to ", outerrConn.RemoteAddr()) // Anything that comes from the container named pipe stdout/err should be copied // across to the stdout/err of the client if copyto != nil { go func() { defer outerrConn.Close() logrus.Debugln("Calling io.Copy on ", pipeName) bytes, err := io.Copy(copyto, outerrConn) logrus.Debugf("Copied %d bytes from pipe=%s", bytes, outerrConn.RemoteAddr()) if err != nil { // Not fatal, just debug log it logrus.Debugf("Error hit during copy %s", err) } }() } else { defer outerrConn.Close() } } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/pauseunpause.go ================================================ // +build windows package windows import ( "fmt" "github.com/docker/docker/daemon/execdriver" ) func (d *driver) Pause(c *execdriver.Command) error { return fmt.Errorf("Windows: Containers cannot be paused") } func (d *driver) Unpause(c *execdriver.Command) error { return fmt.Errorf("Windows: Containers cannot be paused") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/run.go ================================================ // +build windows package windows // Note this is alpha code for the bring up of containers on Windows. import ( "encoding/json" "errors" "fmt" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/microsoft/hcsshim" "github.com/natefinch/npipe" ) type layer struct { Id string Path string } type defConfig struct { DefFile string } type networkConnection struct { NetworkName string EnableNat bool } type networkSettings struct { MacAddress string } type device struct { DeviceType string Connection interface{} Settings interface{} } type containerInit struct { SystemType string Name string IsDummy bool VolumePath string Devices []device IgnoreFlushesDuringBoot bool LayerFolderPath string Layers []layer } func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (execdriver.ExitStatus, error) { var ( term execdriver.Terminal err error inListen, outListen, errListen *npipe.PipeListener ) // Make sure the client isn't asking for options which aren't supported err = checkSupportedOptions(c) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } cu := &containerInit{ SystemType: "Container", Name: c.ID, IsDummy: dummyMode, VolumePath: c.Rootfs, IgnoreFlushesDuringBoot: c.FirstStart, LayerFolderPath: c.LayerFolder, } for i := 0; i < len(c.LayerPaths); i++ { cu.Layers = append(cu.Layers, layer{ Id: hcsshim.NewGUID(c.LayerPaths[i]).ToString(), Path: c.LayerPaths[i], }) } if c.Network.Interface != nil { dev := device{ DeviceType: "Network", Connection: &networkConnection{ NetworkName: c.Network.Interface.Bridge, EnableNat: false, }, } if c.Network.Interface.MacAddress != "" { windowsStyleMAC := strings.Replace( c.Network.Interface.MacAddress, ":", "-", -1) dev.Settings = networkSettings{ MacAddress: windowsStyleMAC, } } logrus.Debugf("Virtual switch '%s', mac='%s'", c.Network.Interface.Bridge, c.Network.Interface.MacAddress) cu.Devices = append(cu.Devices, dev) } else { logrus.Debugln("No network interface") } configurationb, err := json.Marshal(cu) if err != nil { return execdriver.ExitStatus{ExitCode: -1}, err } configuration := string(configurationb) err = hcsshim.CreateComputeSystem(c.ID, configuration) if err != nil { logrus.Debugln("Failed to create temporary container ", err) return execdriver.ExitStatus{ExitCode: -1}, err } // Start the container logrus.Debugln("Starting container ", c.ID) err = hcsshim.StartComputeSystem(c.ID) if err != nil { logrus.Errorf("Failed to start compute system: %s", err) return execdriver.ExitStatus{ExitCode: -1}, err } defer func() { // Stop the container if terminateMode { logrus.Debugf("Terminating container %s", c.ID) if err := hcsshim.TerminateComputeSystem(c.ID); err != nil { // IMPORTANT: Don't fail if fails to change state. It could already // have been stopped through kill(). // Otherwise, the docker daemon will hang in job wait() logrus.Warnf("Ignoring error from TerminateComputeSystem %s", err) } } else { logrus.Debugf("Shutting down container %s", c.ID) if err := hcsshim.ShutdownComputeSystem(c.ID); err != nil { // IMPORTANT: Don't fail if fails to change state. It could already // have been stopped through kill(). // Otherwise, the docker daemon will hang in job wait() logrus.Warnf("Ignoring error from ShutdownComputeSystem %s", err) } } }() // We use a different pipe name between real and dummy mode in the HCS var serverPipeFormat, clientPipeFormat string if dummyMode { clientPipeFormat = `\\.\pipe\docker-run-%[1]s-%[2]s` serverPipeFormat = clientPipeFormat } else { clientPipeFormat = `\\.\pipe\docker-run-%[2]s` serverPipeFormat = `\\.\Containers\%[1]s\Device\NamedPipe\docker-run-%[2]s` } createProcessParms := hcsshim.CreateProcessParams{ EmulateConsole: c.ProcessConfig.Tty, WorkingDirectory: c.WorkingDir, ConsoleSize: c.ProcessConfig.ConsoleSize, } // Configure the environment for the process createProcessParms.Environment = setupEnvironmentVariables(c.ProcessConfig.Env) // Connect stdin if pipes.Stdin != nil { stdInPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdin") createProcessParms.StdInPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdin") // Listen on the named pipe inListen, err = npipe.Listen(stdInPipe) if err != nil { logrus.Errorf("stdin failed to listen on %s err=%s", stdInPipe, err) return execdriver.ExitStatus{ExitCode: -1}, err } defer inListen.Close() // Launch a goroutine to do the accept. We do this so that we can // cause an otherwise blocking goroutine to gracefully close when // the caller (us) closes the listener go stdinAccept(inListen, stdInPipe, pipes.Stdin) } // Connect stdout stdOutPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stdout") createProcessParms.StdOutPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stdout") outListen, err = npipe.Listen(stdOutPipe) if err != nil { logrus.Errorf("stdout failed to listen on %s err=%s", stdOutPipe, err) return execdriver.ExitStatus{ExitCode: -1}, err } defer outListen.Close() go stdouterrAccept(outListen, stdOutPipe, pipes.Stdout) // No stderr on TTY. if !c.ProcessConfig.Tty { // Connect stderr stdErrPipe := fmt.Sprintf(serverPipeFormat, c.ID, "stderr") createProcessParms.StdErrPipe = fmt.Sprintf(clientPipeFormat, c.ID, "stderr") errListen, err = npipe.Listen(stdErrPipe) if err != nil { logrus.Errorf("stderr failed to listen on %s err=%s", stdErrPipe, err) return execdriver.ExitStatus{ExitCode: -1}, err } defer errListen.Close() go stdouterrAccept(errListen, stdErrPipe, pipes.Stderr) } // This should get caught earlier, but just in case - validate that we // have something to run if c.ProcessConfig.Entrypoint == "" { err = errors.New("No entrypoint specified") logrus.Error(err) return execdriver.ExitStatus{ExitCode: -1}, err } // Build the command line of the process createProcessParms.CommandLine = c.ProcessConfig.Entrypoint for _, arg := range c.ProcessConfig.Arguments { logrus.Debugln("appending ", arg) createProcessParms.CommandLine += " " + arg } logrus.Debugf("CommandLine: %s", createProcessParms.CommandLine) // Start the command running in the container. var pid uint32 pid, err = hcsshim.CreateProcessInComputeSystem(c.ID, createProcessParms) if err != nil { logrus.Errorf("CreateProcessInComputeSystem() failed %s", err) return execdriver.ExitStatus{ExitCode: -1}, err } //Save the PID as we'll need this in Kill() logrus.Debugf("PID %d", pid) c.ContainerPid = int(pid) if c.ProcessConfig.Tty { term = NewTtyConsole(c.ID, pid) } else { term = NewStdConsole() } c.ProcessConfig.Terminal = term // Maintain our list of active containers. We'll need this later for exec // and other commands. d.Lock() d.activeContainers[c.ID] = &activeContainer{ command: c, } d.Unlock() // Invoke the start callback if startCallback != nil { startCallback(&c.ProcessConfig, int(pid)) } var exitCode int32 exitCode, err = hcsshim.WaitForProcessInComputeSystem(c.ID, pid) if err != nil { logrus.Errorf("Failed to WaitForProcessInComputeSystem %s", err) return execdriver.ExitStatus{ExitCode: -1}, err } logrus.Debugf("Exiting Run() exitCode %d id=%s", exitCode, c.ID) return execdriver.ExitStatus{ExitCode: int(exitCode)}, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/stats.go ================================================ // +build windows package windows import ( "fmt" "github.com/docker/docker/daemon/execdriver" ) func (d *driver) Stats(id string) (*execdriver.ResourceStats, error) { return nil, fmt.Errorf("Windows: Stats not implemented") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/stdconsole.go ================================================ // +build windows package windows // StdConsole is for when using a container non-interactively type StdConsole struct { } func NewStdConsole() *StdConsole { return &StdConsole{} } func (s *StdConsole) Resize(h, w int) error { // we do not need to resize a non tty return nil } func (s *StdConsole) Close() error { // nothing to close here return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/terminatekill.go ================================================ // +build windows package windows import ( "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/microsoft/hcsshim" ) func (d *driver) Terminate(p *execdriver.Command) error { logrus.Debugf("WindowsExec: Terminate() id=%s", p.ID) return kill(p.ID, p.ContainerPid) } func (d *driver) Kill(p *execdriver.Command, sig int) error { logrus.Debugf("WindowsExec: Kill() id=%s sig=%d", p.ID, sig) return kill(p.ID, p.ContainerPid) } func kill(id string, pid int) error { logrus.Debugln("kill() ", id, pid) var err error // Terminate Process if err = hcsshim.TerminateProcessInComputeSystem(id, uint32(pid)); err != nil { logrus.Warnf("Failed to terminate pid %d in %s", id, pid, err) // Ignore errors err = nil } if terminateMode { // Terminate the compute system if err = hcsshim.TerminateComputeSystem(id); err != nil { logrus.Errorf("Failed to terminate %s - %s", id, err) } } else { // Shutdown the compute system if err = hcsshim.TerminateComputeSystem(id); err != nil { logrus.Errorf("Failed to shutdown %s - %s", id, err) } } return err } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/ttyconsole.go ================================================ // +build windows package windows import ( "github.com/microsoft/hcsshim" ) // TtyConsole is for when using a container interactively type TtyConsole struct { id string processid uint32 } func NewTtyConsole(id string, processid uint32) *TtyConsole { tty := &TtyConsole{ id: id, processid: processid, } return tty } func (t *TtyConsole) Resize(h, w int) error { return hcsshim.ResizeConsoleInComputeSystem(t.id, t.processid, h, w) } func (t *TtyConsole) Close() error { return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/unsupported.go ================================================ // +build !windows package windows import ( "fmt" "github.com/docker/docker/daemon/execdriver" ) func NewDriver(root, initPath string) (execdriver.Driver, error) { return nil, fmt.Errorf("Windows driver not supported on non-Windows") } ================================================ FILE: vendor/github.com/docker/docker/daemon/execdriver/windows/windows.go ================================================ // +build windows package windows import ( "fmt" "strings" "sync" "github.com/Sirupsen/logrus" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/parsers" ) // This is a daemon development variable only and should not be // used for running production containers on Windows. var dummyMode bool // This allows the daemon to terminate containers rather than shutdown var terminateMode bool var ( DriverName = "Windows 1854" Version = dockerversion.VERSION + " " + dockerversion.GITCOMMIT ) type activeContainer struct { command *execdriver.Command } type driver struct { root string initPath string activeContainers map[string]*activeContainer sync.Mutex } func (d *driver) Name() string { return fmt.Sprintf("%s %s", DriverName, Version) } func NewDriver(root, initPath string, options []string) (*driver, error) { for _, option := range options { key, val, err := parsers.ParseKeyValueOpt(option) if err != nil { return nil, err } key = strings.ToLower(key) switch key { case "dummy": switch val { case "1": dummyMode = true logrus.Warn("Using dummy mode in Windows exec driver. This is for development use only!") } case "terminate": switch val { case "1": terminateMode = true logrus.Warn("Using terminate mode in Windows exec driver. This is for testing purposes only.") } default: return nil, fmt.Errorf("Unrecognised exec driver option %s\n", key) } } return &driver{ root: root, initPath: initPath, activeContainers: make(map[string]*activeContainer), }, nil } // setupEnvironmentVariables convert a string array of environment variables // into a map as required by the HCS. Source array is in format [v1=k1] [v2=k2] etc. func setupEnvironmentVariables(a []string) map[string]string { r := make(map[string]string) for _, s := range a { arr := strings.Split(s, "=") if len(arr) == 2 { r[arr[0]] = arr[1] } } return r } ================================================ FILE: vendor/github.com/docker/docker/daemon/export.go ================================================ package daemon import ( "fmt" "io" ) func (daemon *Daemon) ContainerExport(name string, out io.Writer) error { container, err := daemon.Get(name) if err != nil { return err } data, err := container.Export() if err != nil { return fmt.Errorf("%s: %s", name, err) } defer data.Close() // Stream the entire contents of the container (basically a volatile snapshot) if _, err := io.Copy(out, data); err != nil { return fmt.Errorf("%s: %s", name, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/aufs.go ================================================ // +build linux /* aufs driver directory structure . ├── layers // Metadata of layers │ ├── 1 │ ├── 2 │ └── 3 ├── diff // Content of the layer │ ├── 1 // Contains layers that need to be mounted for the id │ ├── 2 │ └── 3 └── mnt // Mount points for the rw layers to be mounted ├── 1 ├── 2 └── 3 */ package aufs import ( "bufio" "fmt" "io/ioutil" "os" "os/exec" "path" "strings" "sync" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/directory" mountpk "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/stringid" "github.com/opencontainers/runc/libcontainer/label" ) var ( ErrAufsNotSupported = fmt.Errorf("AUFS was not found in /proc/filesystems") incompatibleFsMagic = []graphdriver.FsMagic{ graphdriver.FsMagicBtrfs, graphdriver.FsMagicAufs, } backingFs = "" enableDirpermLock sync.Once enableDirperm bool ) func init() { graphdriver.Register("aufs", Init) } type Driver struct { root string sync.Mutex // Protects concurrent modification to active active map[string]int } // New returns a new AUFS driver. // An error is returned if AUFS is not supported. func Init(root string, options []string) (graphdriver.Driver, error) { // Try to load the aufs kernel module if err := supportsAufs(); err != nil { return nil, graphdriver.ErrNotSupported } fsMagic, err := graphdriver.GetFSMagic(root) if err != nil { return nil, err } if fsName, ok := graphdriver.FsNames[fsMagic]; ok { backingFs = fsName } for _, magic := range incompatibleFsMagic { if fsMagic == magic { return nil, graphdriver.ErrIncompatibleFS } } paths := []string{ "mnt", "diff", "layers", } a := &Driver{ root: root, active: make(map[string]int), } // Create the root aufs driver dir and return // if it already exists // If not populate the dir structure if err := os.MkdirAll(root, 0755); err != nil { if os.IsExist(err) { return a, nil } return nil, err } if err := mountpk.MakePrivate(root); err != nil { return nil, err } for _, p := range paths { if err := os.MkdirAll(path.Join(root, p), 0755); err != nil { return nil, err } } return a, nil } // Return a nil error if the kernel supports aufs // We cannot modprobe because inside dind modprobe fails // to run func supportsAufs() error { // We can try to modprobe aufs first before looking at // proc/filesystems for when aufs is supported exec.Command("modprobe", "aufs").Run() f, err := os.Open("/proc/filesystems") if err != nil { return err } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { if strings.Contains(s.Text(), "aufs") { return nil } } return ErrAufsNotSupported } func (a *Driver) rootPath() string { return a.root } func (*Driver) String() string { return "aufs" } func (a *Driver) Status() [][2]string { ids, _ := loadIds(path.Join(a.rootPath(), "layers")) return [][2]string{ {"Root Dir", a.rootPath()}, {"Backing Filesystem", backingFs}, {"Dirs", fmt.Sprintf("%d", len(ids))}, {"Dirperm1 Supported", fmt.Sprintf("%v", useDirperm())}, } } func (a *Driver) GetMetadata(id string) (map[string]string, error) { return nil, nil } // Exists returns true if the given id is registered with // this driver func (a *Driver) Exists(id string) bool { if _, err := os.Lstat(path.Join(a.rootPath(), "layers", id)); err != nil { return false } return true } // Three folders are created for each id // mnt, layers, and diff func (a *Driver) Create(id, parent string) error { if err := a.createDirsFor(id); err != nil { return err } // Write the layers metadata f, err := os.Create(path.Join(a.rootPath(), "layers", id)) if err != nil { return err } defer f.Close() if parent != "" { ids, err := getParentIds(a.rootPath(), parent) if err != nil { return err } if _, err := fmt.Fprintln(f, parent); err != nil { return err } for _, i := range ids { if _, err := fmt.Fprintln(f, i); err != nil { return err } } } return nil } func (a *Driver) createDirsFor(id string) error { paths := []string{ "mnt", "diff", } for _, p := range paths { if err := os.MkdirAll(path.Join(a.rootPath(), p, id), 0755); err != nil { return err } } return nil } // Unmount and remove the dir information func (a *Driver) Remove(id string) error { // Protect the a.active from concurrent access a.Lock() defer a.Unlock() if a.active[id] != 0 { logrus.Errorf("Removing active id %s", id) } // Make sure the dir is umounted first if err := a.unmount(id); err != nil { return err } tmpDirs := []string{ "mnt", "diff", } // Atomically remove each directory in turn by first moving it out of the // way (so that docker doesn't find it anymore) before doing removal of // the whole tree. for _, p := range tmpDirs { realPath := path.Join(a.rootPath(), p, id) tmpPath := path.Join(a.rootPath(), p, fmt.Sprintf("%s-removing", id)) if err := os.Rename(realPath, tmpPath); err != nil && !os.IsNotExist(err) { return err } defer os.RemoveAll(tmpPath) } // Remove the layers file for the id if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) { return err } return nil } // Return the rootfs path for the id // This will mount the dir at it's given path func (a *Driver) Get(id, mountLabel string) (string, error) { ids, err := getParentIds(a.rootPath(), id) if err != nil { if !os.IsNotExist(err) { return "", err } ids = []string{} } // Protect the a.active from concurrent access a.Lock() defer a.Unlock() count := a.active[id] // If a dir does not have a parent ( no layers )do not try to mount // just return the diff path to the data out := path.Join(a.rootPath(), "diff", id) if len(ids) > 0 { out = path.Join(a.rootPath(), "mnt", id) if count == 0 { if err := a.mount(id, mountLabel); err != nil { return "", err } } } a.active[id] = count + 1 return out, nil } func (a *Driver) Put(id string) error { // Protect the a.active from concurrent access a.Lock() defer a.Unlock() if count := a.active[id]; count > 1 { a.active[id] = count - 1 } else { ids, _ := getParentIds(a.rootPath(), id) // We only mounted if there are any parents if ids != nil && len(ids) > 0 { a.unmount(id) } delete(a.active, id) } return nil } // Diff produces an archive of the changes between the specified // layer and its parent layer which may be "". func (a *Driver) Diff(id, parent string) (archive.Archive, error) { // AUFS doesn't need the parent layer to produce a diff. return archive.TarWithOptions(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{ Compression: archive.Uncompressed, ExcludePatterns: []string{".wh..wh.*"}, }) } func (a *Driver) applyDiff(id string, diff archive.ArchiveReader) error { return chrootarchive.Untar(diff, path.Join(a.rootPath(), "diff", id), nil) } // DiffSize calculates the changes between the specified id // and its parent and returns the size in bytes of the changes // relative to its base filesystem directory. func (a *Driver) DiffSize(id, parent string) (size int64, err error) { // AUFS doesn't need the parent layer to calculate the diff size. return directory.Size(path.Join(a.rootPath(), "diff", id)) } // ApplyDiff extracts the changeset from the given diff into the // layer with the specified id and parent, returning the size of the // new layer in bytes. func (a *Driver) ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error) { // AUFS doesn't need the parent id to apply the diff. if err = a.applyDiff(id, diff); err != nil { return } return a.DiffSize(id, parent) } // Changes produces a list of changes between the specified layer // and its parent layer. If parent is "", then all changes will be ADD changes. func (a *Driver) Changes(id, parent string) ([]archive.Change, error) { // AUFS doesn't have snapshots, so we need to get changes from all parent // layers. layers, err := a.getParentLayerPaths(id) if err != nil { return nil, err } return archive.Changes(layers, path.Join(a.rootPath(), "diff", id)) } func (a *Driver) getParentLayerPaths(id string) ([]string, error) { parentIds, err := getParentIds(a.rootPath(), id) if err != nil { return nil, err } layers := make([]string, len(parentIds)) // Get the diff paths for all the parent ids for i, p := range parentIds { layers[i] = path.Join(a.rootPath(), "diff", p) } return layers, nil } func (a *Driver) mount(id, mountLabel string) error { // If the id is mounted or we get an error return if mounted, err := a.mounted(id); err != nil || mounted { return err } var ( target = path.Join(a.rootPath(), "mnt", id) rw = path.Join(a.rootPath(), "diff", id) ) layers, err := a.getParentLayerPaths(id) if err != nil { return err } if err := a.aufsMount(layers, rw, target, mountLabel); err != nil { return fmt.Errorf("error creating aufs mount to %s: %v", target, err) } return nil } func (a *Driver) unmount(id string) error { if mounted, err := a.mounted(id); err != nil || !mounted { return err } target := path.Join(a.rootPath(), "mnt", id) return Unmount(target) } func (a *Driver) mounted(id string) (bool, error) { target := path.Join(a.rootPath(), "mnt", id) return mountpk.Mounted(target) } // During cleanup aufs needs to unmount all mountpoints func (a *Driver) Cleanup() error { ids, err := loadIds(path.Join(a.rootPath(), "layers")) if err != nil { return err } for _, id := range ids { if err := a.unmount(id); err != nil { logrus.Errorf("Unmounting %s: %s", stringid.TruncateID(id), err) } } return mountpk.Unmount(a.root) } func (a *Driver) aufsMount(ro []string, rw, target, mountLabel string) (err error) { defer func() { if err != nil { Unmount(target) } }() // Mount options are clipped to page size(4096 bytes). If there are more // layers then these are remounted individually using append. offset := 54 if useDirperm() { offset += len("dirperm1") } b := make([]byte, syscall.Getpagesize()-len(mountLabel)-offset) // room for xino & mountLabel bp := copy(b, fmt.Sprintf("br:%s=rw", rw)) firstMount := true i := 0 for { for ; i < len(ro); i++ { layer := fmt.Sprintf(":%s=ro+wh", ro[i]) if firstMount { if bp+len(layer) > len(b) { break } bp += copy(b[bp:], layer) } else { data := label.FormatMountLabel(fmt.Sprintf("append%s", layer), mountLabel) if err = mount("none", target, "aufs", MsRemount, data); err != nil { return } } } if firstMount { opts := "dio,xino=/dev/shm/aufs.xino" if useDirperm() { opts += ",dirperm1" } data := label.FormatMountLabel(fmt.Sprintf("%s,%s", string(b[:bp]), opts), mountLabel) if err = mount("none", target, "aufs", 0, data); err != nil { return } firstMount = false } if i == len(ro) { break } } return } // useDirperm checks dirperm1 mount option can be used with the current // version of aufs. func useDirperm() bool { enableDirpermLock.Do(func() { base, err := ioutil.TempDir("", "docker-aufs-base") if err != nil { logrus.Errorf("error checking dirperm1: %v", err) return } defer os.RemoveAll(base) union, err := ioutil.TempDir("", "docker-aufs-union") if err != nil { logrus.Errorf("error checking dirperm1: %v", err) return } defer os.RemoveAll(union) opts := fmt.Sprintf("br:%s,dirperm1,xino=/dev/shm/aufs.xino", base) if err := mount("none", union, "aufs", 0, opts); err != nil { return } enableDirperm = true if err := Unmount(union); err != nil { logrus.Errorf("error checking dirperm1: failed to unmount %v", err) } }) return enableDirperm } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/aufs_test.go ================================================ // +build linux package aufs import ( "crypto/sha256" "encoding/hex" "fmt" "io/ioutil" "os" "path" "testing" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/reexec" ) var ( tmpOuter = path.Join(os.TempDir(), "aufs-tests") tmp = path.Join(tmpOuter, "aufs") ) func init() { reexec.Init() } func testInit(dir string, t *testing.T) graphdriver.Driver { d, err := Init(dir, nil) if err != nil { if err == graphdriver.ErrNotSupported { t.Skip(err) } else { t.Fatal(err) } } return d } func newDriver(t *testing.T) *Driver { if err := os.MkdirAll(tmp, 0755); err != nil { t.Fatal(err) } d := testInit(tmp, t) return d.(*Driver) } func TestNewDriver(t *testing.T) { if err := os.MkdirAll(tmp, 0755); err != nil { t.Fatal(err) } d := testInit(tmp, t) defer os.RemoveAll(tmp) if d == nil { t.Fatalf("Driver should not be nil") } } func TestAufsString(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if d.String() != "aufs" { t.Fatalf("Expected aufs got %s", d.String()) } } func TestCreateDirStructure(t *testing.T) { newDriver(t) defer os.RemoveAll(tmp) paths := []string{ "mnt", "layers", "diff", } for _, p := range paths { if _, err := os.Stat(path.Join(tmp, p)); err != nil { t.Fatal(err) } } } // We should be able to create two drivers with the same dir structure func TestNewDriverFromExistingDir(t *testing.T) { if err := os.MkdirAll(tmp, 0755); err != nil { t.Fatal(err) } testInit(tmp, t) testInit(tmp, t) os.RemoveAll(tmp) } func TestCreateNewDir(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } } func TestCreateNewDirStructure(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } paths := []string{ "mnt", "diff", "layers", } for _, p := range paths { if _, err := os.Stat(path.Join(tmp, p, "1")); err != nil { t.Fatal(err) } } } func TestRemoveImage(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Remove("1"); err != nil { t.Fatal(err) } paths := []string{ "mnt", "diff", "layers", } for _, p := range paths { if _, err := os.Stat(path.Join(tmp, p, "1")); err == nil { t.Fatalf("Error should not be nil because dirs with id 1 should be delted: %s", p) } } } func TestGetWithoutParent(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } diffPath, err := d.Get("1", "") if err != nil { t.Fatal(err) } expected := path.Join(tmp, "diff", "1") if diffPath != expected { t.Fatalf("Expected path %s got %s", expected, diffPath) } } func TestCleanupWithNoDirs(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Cleanup(); err != nil { t.Fatal(err) } } func TestCleanupWithDir(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Cleanup(); err != nil { t.Fatal(err) } } func TestMountedFalseResponse(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } response, err := d.mounted("1") if err != nil { t.Fatal(err) } if response != false { t.Fatalf("Response if dir id 1 is mounted should be false") } } func TestMountedTrueReponse(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } _, err := d.Get("2", "") if err != nil { t.Fatal(err) } response, err := d.mounted("2") if err != nil { t.Fatal(err) } if response != true { t.Fatalf("Response if dir id 2 is mounted should be true") } } func TestMountWithParent(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } defer func() { if err := d.Cleanup(); err != nil { t.Fatal(err) } }() mntPath, err := d.Get("2", "") if err != nil { t.Fatal(err) } if mntPath == "" { t.Fatal("mntPath should not be empty string") } expected := path.Join(tmp, "mnt", "2") if mntPath != expected { t.Fatalf("Expected %s got %s", expected, mntPath) } } func TestRemoveMountedDir(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } defer func() { if err := d.Cleanup(); err != nil { t.Fatal(err) } }() mntPath, err := d.Get("2", "") if err != nil { t.Fatal(err) } if mntPath == "" { t.Fatal("mntPath should not be empty string") } mounted, err := d.mounted("2") if err != nil { t.Fatal(err) } if !mounted { t.Fatalf("Dir id 2 should be mounted") } if err := d.Remove("2"); err != nil { t.Fatal(err) } } func TestCreateWithInvalidParent(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", "docker"); err == nil { t.Fatalf("Error should not be nil with parent does not exist") } } func TestGetDiff(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } diffPath, err := d.Get("1", "") if err != nil { t.Fatal(err) } // Add a file to the diff path with a fixed size size := int64(1024) f, err := os.Create(path.Join(diffPath, "test_file")) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } f.Close() a, err := d.Diff("1", "") if err != nil { t.Fatal(err) } if a == nil { t.Fatalf("Archive should not be nil") } } func TestChanges(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } defer func() { if err := d.Cleanup(); err != nil { t.Fatal(err) } }() mntPoint, err := d.Get("2", "") if err != nil { t.Fatal(err) } // Create a file to save in the mountpoint f, err := os.Create(path.Join(mntPoint, "test.txt")) if err != nil { t.Fatal(err) } if _, err := f.WriteString("testline"); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } changes, err := d.Changes("2", "") if err != nil { t.Fatal(err) } if len(changes) != 1 { t.Fatalf("Dir 2 should have one change from parent got %d", len(changes)) } change := changes[0] expectedPath := "/test.txt" if change.Path != expectedPath { t.Fatalf("Expected path %s got %s", expectedPath, change.Path) } if change.Kind != archive.ChangeAdd { t.Fatalf("Change kind should be ChangeAdd got %s", change.Kind) } if err := d.Create("3", "2"); err != nil { t.Fatal(err) } mntPoint, err = d.Get("3", "") if err != nil { t.Fatal(err) } // Create a file to save in the mountpoint f, err = os.Create(path.Join(mntPoint, "test2.txt")) if err != nil { t.Fatal(err) } if _, err := f.WriteString("testline"); err != nil { t.Fatal(err) } if err := f.Close(); err != nil { t.Fatal(err) } changes, err = d.Changes("3", "") if err != nil { t.Fatal(err) } if len(changes) != 1 { t.Fatalf("Dir 2 should have one change from parent got %d", len(changes)) } change = changes[0] expectedPath = "/test2.txt" if change.Path != expectedPath { t.Fatalf("Expected path %s got %s", expectedPath, change.Path) } if change.Kind != archive.ChangeAdd { t.Fatalf("Change kind should be ChangeAdd got %s", change.Kind) } } func TestDiffSize(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) if err := d.Create("1", ""); err != nil { t.Fatal(err) } diffPath, err := d.Get("1", "") if err != nil { t.Fatal(err) } // Add a file to the diff path with a fixed size size := int64(1024) f, err := os.Create(path.Join(diffPath, "test_file")) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } s, err := f.Stat() if err != nil { t.Fatal(err) } size = s.Size() if err := f.Close(); err != nil { t.Fatal(err) } diffSize, err := d.DiffSize("1", "") if err != nil { t.Fatal(err) } if diffSize != size { t.Fatalf("Expected size to be %d got %d", size, diffSize) } } func TestChildDiffSize(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() if err := d.Create("1", ""); err != nil { t.Fatal(err) } diffPath, err := d.Get("1", "") if err != nil { t.Fatal(err) } // Add a file to the diff path with a fixed size size := int64(1024) f, err := os.Create(path.Join(diffPath, "test_file")) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } s, err := f.Stat() if err != nil { t.Fatal(err) } size = s.Size() if err := f.Close(); err != nil { t.Fatal(err) } diffSize, err := d.DiffSize("1", "") if err != nil { t.Fatal(err) } if diffSize != size { t.Fatalf("Expected size to be %d got %d", size, diffSize) } if err := d.Create("2", "1"); err != nil { t.Fatal(err) } diffSize, err = d.DiffSize("2", "") if err != nil { t.Fatal(err) } // The diff size for the child should be zero if diffSize != 0 { t.Fatalf("Expected size to be %d got %d", 0, diffSize) } } func TestExists(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() if err := d.Create("1", ""); err != nil { t.Fatal(err) } if d.Exists("none") { t.Fatal("id name should not exist in the driver") } if !d.Exists("1") { t.Fatal("id 1 should exist in the driver") } } func TestStatus(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() if err := d.Create("1", ""); err != nil { t.Fatal(err) } status := d.Status() if status == nil || len(status) == 0 { t.Fatal("Status should not be nil or empty") } rootDir := status[0] dirs := status[2] if rootDir[0] != "Root Dir" { t.Fatalf("Expected Root Dir got %s", rootDir[0]) } if rootDir[1] != d.rootPath() { t.Fatalf("Expected %s got %s", d.rootPath(), rootDir[1]) } if dirs[0] != "Dirs" { t.Fatalf("Expected Dirs got %s", dirs[0]) } if dirs[1] != "1" { t.Fatalf("Expected 1 got %s", dirs[1]) } } func TestApplyDiff(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) defer d.Cleanup() if err := d.Create("1", ""); err != nil { t.Fatal(err) } diffPath, err := d.Get("1", "") if err != nil { t.Fatal(err) } // Add a file to the diff path with a fixed size size := int64(1024) f, err := os.Create(path.Join(diffPath, "test_file")) if err != nil { t.Fatal(err) } if err := f.Truncate(size); err != nil { t.Fatal(err) } f.Close() diff, err := d.Diff("1", "") if err != nil { t.Fatal(err) } if err := d.Create("2", ""); err != nil { t.Fatal(err) } if err := d.Create("3", "2"); err != nil { t.Fatal(err) } if err := d.applyDiff("3", diff); err != nil { t.Fatal(err) } // Ensure that the file is in the mount point for id 3 mountPoint, err := d.Get("3", "") if err != nil { t.Fatal(err) } if _, err := os.Stat(path.Join(mountPoint, "test_file")); err != nil { t.Fatal(err) } } func hash(c string) string { h := sha256.New() fmt.Fprint(h, c) return hex.EncodeToString(h.Sum(nil)) } func testMountMoreThan42Layers(t *testing.T, mountPath string) { if err := os.MkdirAll(mountPath, 0755); err != nil { t.Fatal(err) } defer os.RemoveAll(mountPath) d := testInit(mountPath, t).(*Driver) defer d.Cleanup() var last string var expected int for i := 1; i < 127; i++ { expected++ var ( parent = fmt.Sprintf("%d", i-1) current = fmt.Sprintf("%d", i) ) if parent == "0" { parent = "" } else { parent = hash(parent) } current = hash(current) if err := d.Create(current, parent); err != nil { t.Logf("Current layer %d", i) t.Error(err) } point, err := d.Get(current, "") if err != nil { t.Logf("Current layer %d", i) t.Error(err) } f, err := os.Create(path.Join(point, current)) if err != nil { t.Logf("Current layer %d", i) t.Error(err) } f.Close() if i%10 == 0 { if err := os.Remove(path.Join(point, parent)); err != nil { t.Logf("Current layer %d", i) t.Error(err) } expected-- } last = current } // Perform the actual mount for the top most image point, err := d.Get(last, "") if err != nil { t.Error(err) } files, err := ioutil.ReadDir(point) if err != nil { t.Error(err) } if len(files) != expected { t.Errorf("Expected %d got %d", expected, len(files)) } } func TestMountMoreThan42Layers(t *testing.T) { os.RemoveAll(tmpOuter) testMountMoreThan42Layers(t, tmp) } func TestMountMoreThan42LayersMatchingPathLength(t *testing.T) { defer os.RemoveAll(tmpOuter) zeroes := "0" for { // This finds a mount path so that when combined into aufs mount options // 4096 byte boundary would be in between the paths or in permission // section. For '/tmp' it will use '/tmp/aufs-tests/00000000/aufs' mountPath := path.Join(tmpOuter, zeroes, "aufs") pathLength := 77 + len(mountPath) if mod := 4095 % pathLength; mod == 0 || mod > pathLength-2 { t.Logf("Using path: %s", mountPath) testMountMoreThan42Layers(t, mountPath) return } zeroes += "0" } } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/dirs.go ================================================ // +build linux package aufs import ( "bufio" "io/ioutil" "os" "path" ) // Return all the directories func loadIds(root string) ([]string, error) { dirs, err := ioutil.ReadDir(root) if err != nil { return nil, err } out := []string{} for _, d := range dirs { if !d.IsDir() { out = append(out, d.Name()) } } return out, nil } // Read the layers file for the current id and return all the // layers represented by new lines in the file // // If there are no lines in the file then the id has no parent // and an empty slice is returned. func getParentIds(root, id string) ([]string, error) { f, err := os.Open(path.Join(root, "layers", id)) if err != nil { return nil, err } defer f.Close() out := []string{} s := bufio.NewScanner(f) for s.Scan() { if t := s.Text(); t != "" { out = append(out, s.Text()) } } return out, s.Err() } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/migrate.go ================================================ // +build linux package aufs import ( "encoding/json" "fmt" "io/ioutil" "os" "path" ) type metadata struct { ID string `json:"id"` ParentID string `json:"parent,omitempty"` Image string `json:"Image,omitempty"` parent *metadata } func pathExists(pth string) bool { if _, err := os.Stat(pth); err != nil { return false } return true } // Migrate existing images and containers from docker < 0.7.x // // The format pre 0.7 is for docker to store the metadata and filesystem // content in the same directory. For the migration to work we need to move Image layer // data from /var/lib/docker/graph//layers to the diff of the registered id. // // Next we need to migrate the container's rw layer to diff of the driver. After the // contents are migrated we need to register the image and container ids with the // driver. // // For the migration we try to move the folder containing the layer files, if that // fails because the data is currently mounted we will fallback to creating a // symlink. func (a *Driver) Migrate(pth string, setupInit func(p string) error) error { if pathExists(path.Join(pth, "graph")) { if err := a.migrateRepositories(pth); err != nil { return err } if err := a.migrateImages(path.Join(pth, "graph")); err != nil { return err } return a.migrateContainers(path.Join(pth, "containers"), setupInit) } return nil } func (a *Driver) migrateRepositories(pth string) error { name := path.Join(pth, "repositories") if err := os.Rename(name, name+"-aufs"); err != nil && !os.IsNotExist(err) { return err } return nil } func (a *Driver) migrateContainers(pth string, setupInit func(p string) error) error { fis, err := ioutil.ReadDir(pth) if err != nil { return err } for _, fi := range fis { if id := fi.Name(); fi.IsDir() && pathExists(path.Join(pth, id, "rw")) { if err := tryRelocate(path.Join(pth, id, "rw"), path.Join(a.rootPath(), "diff", id)); err != nil { return err } if !a.Exists(id) { metadata, err := loadMetadata(path.Join(pth, id, "config.json")) if err != nil { return err } initID := fmt.Sprintf("%s-init", id) if err := a.Create(initID, metadata.Image); err != nil { return err } initPath, err := a.Get(initID, "") if err != nil { return err } // setup init layer if err := setupInit(initPath); err != nil { return err } if err := a.Create(id, initID); err != nil { return err } } } } return nil } func (a *Driver) migrateImages(pth string) error { fis, err := ioutil.ReadDir(pth) if err != nil { return err } var ( m = make(map[string]*metadata) current *metadata exists bool ) for _, fi := range fis { if id := fi.Name(); fi.IsDir() && pathExists(path.Join(pth, id, "layer")) { if current, exists = m[id]; !exists { current, err = loadMetadata(path.Join(pth, id, "json")) if err != nil { return err } m[id] = current } } } for _, v := range m { v.parent = m[v.ParentID] } migrated := make(map[string]bool) for _, v := range m { if err := a.migrateImage(v, pth, migrated); err != nil { return err } } return nil } func (a *Driver) migrateImage(m *metadata, pth string, migrated map[string]bool) error { if !migrated[m.ID] { if m.parent != nil { a.migrateImage(m.parent, pth, migrated) } if err := tryRelocate(path.Join(pth, m.ID, "layer"), path.Join(a.rootPath(), "diff", m.ID)); err != nil { return err } if !a.Exists(m.ID) { if err := a.Create(m.ID, m.ParentID); err != nil { return err } } migrated[m.ID] = true } return nil } // tryRelocate will try to rename the old path to the new pack and if // the operation fails, it will fallback to a symlink func tryRelocate(oldPath, newPath string) error { s, err := os.Lstat(newPath) if err != nil && !os.IsNotExist(err) { return err } // If the destination is a symlink then we already tried to relocate once before // and it failed so we delete it and try to remove if s != nil && s.Mode()&os.ModeSymlink != 0 { if err := os.RemoveAll(newPath); err != nil { return err } } if err := os.Rename(oldPath, newPath); err != nil { if sErr := os.Symlink(oldPath, newPath); sErr != nil { return fmt.Errorf("Unable to relocate %s to %s: Rename err %s Symlink err %s", oldPath, newPath, err, sErr) } } return nil } func loadMetadata(pth string) (*metadata, error) { f, err := os.Open(pth) if err != nil { return nil, err } defer f.Close() var ( out = &metadata{} dec = json.NewDecoder(f) ) if err := dec.Decode(out); err != nil { return nil, err } return out, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/mount.go ================================================ // +build linux package aufs import ( "os/exec" "syscall" "github.com/Sirupsen/logrus" ) func Unmount(target string) error { if err := exec.Command("auplink", target, "flush").Run(); err != nil { logrus.Errorf("Couldn't run auplink before unmount: %s", err) } if err := syscall.Unmount(target, 0); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/mount_linux.go ================================================ package aufs import "syscall" const MsRemount = syscall.MS_REMOUNT func mount(source string, target string, fstype string, flags uintptr, data string) error { return syscall.Mount(source, target, fstype, flags, data) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/aufs/mount_unsupported.go ================================================ // +build !linux package aufs import "errors" const MsRemount = 0 func mount(source string, target string, fstype string, flags uintptr, data string) (err error) { return errors.New("mount is not implemented on this platform") } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/btrfs/btrfs.go ================================================ // +build linux package btrfs /* #include #include #include */ import "C" import ( "fmt" "os" "path" "syscall" "unsafe" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/mount" ) func init() { graphdriver.Register("btrfs", Init) } func Init(home string, options []string) (graphdriver.Driver, error) { rootdir := path.Dir(home) var buf syscall.Statfs_t if err := syscall.Statfs(rootdir, &buf); err != nil { return nil, err } if graphdriver.FsMagic(buf.Type) != graphdriver.FsMagicBtrfs { return nil, graphdriver.ErrPrerequisites } if err := os.MkdirAll(home, 0700); err != nil { return nil, err } if err := mount.MakePrivate(home); err != nil { return nil, err } driver := &Driver{ home: home, } return graphdriver.NaiveDiffDriver(driver), nil } type Driver struct { home string } func (d *Driver) String() string { return "btrfs" } func (d *Driver) Status() [][2]string { status := [][2]string{} if bv := BtrfsBuildVersion(); bv != "-" { status = append(status, [2]string{"Build Version", bv}) } if lv := BtrfsLibVersion(); lv != -1 { status = append(status, [2]string{"Library Version", fmt.Sprintf("%d", lv)}) } return status } func (d *Driver) GetMetadata(id string) (map[string]string, error) { return nil, nil } func (d *Driver) Cleanup() error { return mount.Unmount(d.home) } func free(p *C.char) { C.free(unsafe.Pointer(p)) } func openDir(path string) (*C.DIR, error) { Cpath := C.CString(path) defer free(Cpath) dir := C.opendir(Cpath) if dir == nil { return nil, fmt.Errorf("Can't open dir") } return dir, nil } func closeDir(dir *C.DIR) { if dir != nil { C.closedir(dir) } } func getDirFd(dir *C.DIR) uintptr { return uintptr(C.dirfd(dir)) } func subvolCreate(path, name string) error { dir, err := openDir(path) if err != nil { return err } defer closeDir(dir) var args C.struct_btrfs_ioctl_vol_args for i, c := range []byte(name) { args.name[i] = C.char(c) } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, getDirFd(dir), C.BTRFS_IOC_SUBVOL_CREATE, uintptr(unsafe.Pointer(&args))) if errno != 0 { return fmt.Errorf("Failed to create btrfs subvolume: %v", errno.Error()) } return nil } func subvolSnapshot(src, dest, name string) error { srcDir, err := openDir(src) if err != nil { return err } defer closeDir(srcDir) destDir, err := openDir(dest) if err != nil { return err } defer closeDir(destDir) var args C.struct_btrfs_ioctl_vol_args_v2 args.fd = C.__s64(getDirFd(srcDir)) for i, c := range []byte(name) { args.name[i] = C.char(c) } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, getDirFd(destDir), C.BTRFS_IOC_SNAP_CREATE_V2, uintptr(unsafe.Pointer(&args))) if errno != 0 { return fmt.Errorf("Failed to create btrfs snapshot: %v", errno.Error()) } return nil } func subvolDelete(path, name string) error { dir, err := openDir(path) if err != nil { return err } defer closeDir(dir) var args C.struct_btrfs_ioctl_vol_args for i, c := range []byte(name) { args.name[i] = C.char(c) } _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, getDirFd(dir), C.BTRFS_IOC_SNAP_DESTROY, uintptr(unsafe.Pointer(&args))) if errno != 0 { return fmt.Errorf("Failed to destroy btrfs snapshot: %v", errno.Error()) } return nil } func (d *Driver) subvolumesDir() string { return path.Join(d.home, "subvolumes") } func (d *Driver) subvolumesDirId(id string) string { return path.Join(d.subvolumesDir(), id) } func (d *Driver) Create(id string, parent string) error { subvolumes := path.Join(d.home, "subvolumes") if err := os.MkdirAll(subvolumes, 0700); err != nil { return err } if parent == "" { if err := subvolCreate(subvolumes, id); err != nil { return err } } else { parentDir, err := d.Get(parent, "") if err != nil { return err } if err := subvolSnapshot(parentDir, subvolumes, id); err != nil { return err } } return nil } func (d *Driver) Remove(id string) error { dir := d.subvolumesDirId(id) if _, err := os.Stat(dir); err != nil { return err } if err := subvolDelete(d.subvolumesDir(), id); err != nil { return err } return os.RemoveAll(dir) } func (d *Driver) Get(id, mountLabel string) (string, error) { dir := d.subvolumesDirId(id) st, err := os.Stat(dir) if err != nil { return "", err } if !st.IsDir() { return "", fmt.Errorf("%s: not a directory", dir) } return dir, nil } func (d *Driver) Put(id string) error { // Get() creates no runtime resources (like e.g. mounts) // so this doesn't need to do anything. return nil } func (d *Driver) Exists(id string) bool { dir := d.subvolumesDirId(id) _, err := os.Stat(dir) return err == nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/btrfs/btrfs_test.go ================================================ // +build linux package btrfs import ( "github.com/docker/docker/daemon/graphdriver/graphtest" "testing" ) // This avoids creating a new driver for each test if all tests are run // Make sure to put new tests between TestBtrfsSetup and TestBtrfsTeardown func TestBtrfsSetup(t *testing.T) { graphtest.GetDriver(t, "btrfs") } func TestBtrfsCreateEmpty(t *testing.T) { graphtest.DriverTestCreateEmpty(t, "btrfs") } func TestBtrfsCreateBase(t *testing.T) { graphtest.DriverTestCreateBase(t, "btrfs") } func TestBtrfsCreateSnap(t *testing.T) { graphtest.DriverTestCreateSnap(t, "btrfs") } func TestBtrfsTeardown(t *testing.T) { graphtest.PutDriver(t) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/btrfs/dummy_unsupported.go ================================================ // +build !linux !cgo package btrfs ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/btrfs/version.go ================================================ // +build linux,!btrfs_noversion package btrfs /* #include // around version 3.16, they did not define lib version yet #ifndef BTRFS_LIB_VERSION #define BTRFS_LIB_VERSION -1 #endif // upstream had removed it, but now it will be coming back #ifndef BTRFS_BUILD_VERSION #define BTRFS_BUILD_VERSION "-" #endif */ import "C" func BtrfsBuildVersion() string { return string(C.BTRFS_BUILD_VERSION) } func BtrfsLibVersion() int { return int(C.BTRFS_LIB_VERSION) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/btrfs/version_none.go ================================================ // +build linux,btrfs_noversion package btrfs // TODO(vbatts) remove this work-around once supported linux distros are on // btrfs utililties of >= 3.16.1 func BtrfsBuildVersion() string { return "-" } func BtrfsLibVersion() int { return -1 } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/btrfs/version_test.go ================================================ // +build linux,!btrfs_noversion package btrfs import ( "testing" ) func TestLibVersion(t *testing.T) { if BtrfsLibVersion() <= 0 { t.Errorf("expected output from btrfs lib version > 0") } } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/devmapper/README.md ================================================ ## devicemapper - a storage backend based on Device Mapper ### Theory of operation The device mapper graphdriver uses the device mapper thin provisioning module (dm-thinp) to implement CoW snapshots. For each devicemapper graph location (typically `/var/lib/docker/devicemapper`, $graph below) a thin pool is created based on two block devices, one for data and one for metadata. By default these block devices are created automatically by using loopback mounts of automatically created sparse files. The default loopback files used are `$graph/devicemapper/data` and `$graph/devicemapper/metadata`. Additional metadata required to map from docker entities to the corresponding devicemapper volumes is stored in the `$graph/devicemapper/json` file (encoded as Json). In order to support multiple devicemapper graphs on a system, the thin pool will be named something like: `docker-0:33-19478248-pool`, where the `0:33` part is the minor/major device nr and `19478248` is the inode number of the $graph directory. On the thin pool, docker automatically creates a base thin device, called something like `docker-0:33-19478248-base` of a fixed size. This is automatically formatted with an empty filesystem on creation. This device is the base of all docker images and containers. All base images are snapshots of this device and those images are then in turn used as snapshots for other images and eventually containers. ### Information on `docker info` As of docker-1.4.1, `docker info` when using the `devicemapper` storage driver will display something like: $ sudo docker info [...] Storage Driver: devicemapper Pool Name: docker-253:1-17538953-pool Pool Blocksize: 65.54 kB Data file: /dev/loop4 Metadata file: /dev/loop4 Data Space Used: 2.536 GB Data Space Total: 107.4 GB Data Space Available: 104.8 GB Metadata Space Used: 7.93 MB Metadata Space Total: 2.147 GB Metadata Space Available: 2.14 GB Udev Sync Supported: true Data loop file: /home/docker/devicemapper/devicemapper/data Metadata loop file: /home/docker/devicemapper/devicemapper/metadata Library Version: 1.02.82-git (2013-10-04) [...] #### status items Each item in the indented section under `Storage Driver: devicemapper` are status information about the driver. * `Pool Name` name of the devicemapper pool for this driver. * `Pool Blocksize` tells the blocksize the thin pool was initialized with. This only changes on creation. * `Data file` blockdevice file used for the devicemapper data * `Metadata file` blockdevice file used for the devicemapper metadata * `Data Space Used` tells how much of `Data file` is currently used * `Data Space Total` tells max size the `Data file` * `Data Space Available` tells how much free space there is in the `Data file`. If you are using a loop device this will report the actual space available to the loop device on the underlying filesystem. * `Metadata Space Used` tells how much of `Metadata file` is currently used * `Metadata Space Total` tells max size the `Metadata file` * `Metadata Space Available` tells how much free space there is in the `Metadata file`. If you are using a loop device this will report the actual space available to the loop device on the underlying filesystem. * `Udev Sync Supported` tells whether devicemapper is able to sync with Udev. Should be `true`. * `Data loop file` file attached to `Data file`, if loopback device is used * `Metadata loop file` file attached to `Metadata file`, if loopback device is used * `Library Version` from the libdevmapper used ### About the devicemapper options The devicemapper backend supports some options that you can specify when starting the docker daemon using the `--storage-opt` flags. This uses the `dm` prefix and would be used something like `docker -d --storage-opt dm.foo=bar`. These options are currently documented both in [the man page](../../../man/docker.1.md) and in [the online documentation](https://docs.docker.com/reference/commandline/daemon/#docker- execdriver-option). If you add an options, update both the `man` page and the documentation. ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/devmapper/deviceset.go ================================================ // +build linux package devmapper import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "sync" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/devicemapper" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/units" "github.com/opencontainers/runc/libcontainer/label" ) var ( DefaultDataLoopbackSize int64 = 100 * 1024 * 1024 * 1024 DefaultMetaDataLoopbackSize int64 = 2 * 1024 * 1024 * 1024 DefaultBaseFsSize uint64 = 100 * 1024 * 1024 * 1024 DefaultThinpBlockSize uint32 = 128 // 64K = 128 512b sectors DefaultUdevSyncOverride bool = false MaxDeviceId int = 0xffffff // 24 bit, pool limit DeviceIdMapSz int = (MaxDeviceId + 1) / 8 // We retry device removal so many a times that even error messages // will fill up console during normal operation. So only log Fatal // messages by default. DMLogLevel int = devicemapper.LogLevelFatal DriverDeferredRemovalSupport bool = false EnableDeferredRemoval bool = false ) const deviceSetMetaFile string = "deviceset-metadata" const transactionMetaFile string = "transaction-metadata" type Transaction struct { OpenTransactionId uint64 `json:"open_transaction_id"` DeviceIdHash string `json:"device_hash"` DeviceId int `json:"device_id"` } type DevInfo struct { Hash string `json:"-"` DeviceId int `json:"device_id"` Size uint64 `json:"size"` TransactionId uint64 `json:"transaction_id"` Initialized bool `json:"initialized"` devices *DeviceSet mountCount int mountPath string // The global DeviceSet lock guarantees that we serialize all // the calls to libdevmapper (which is not threadsafe), but we // sometimes release that lock while sleeping. In that case // this per-device lock is still held, protecting against // other accesses to the device that we're doing the wait on. // // WARNING: In order to avoid AB-BA deadlocks when releasing // the global lock while holding the per-device locks all // device locks must be aquired *before* the device lock, and // multiple device locks should be aquired parent before child. lock sync.Mutex } type MetaData struct { Devices map[string]*DevInfo `json:"Devices"` devicesLock sync.Mutex // Protects all read/writes to Devices map } type DeviceSet struct { MetaData `json:"-"` sync.Mutex `json:"-"` // Protects Devices map and serializes calls into libdevmapper root string devicePrefix string TransactionId uint64 `json:"-"` NextDeviceId int `json:"next_device_id"` deviceIdMap []byte // Options dataLoopbackSize int64 metaDataLoopbackSize int64 baseFsSize uint64 filesystem string mountOptions string mkfsArgs []string dataDevice string // block or loop dev dataLoopFile string // loopback file, if used metadataDevice string // block or loop dev metadataLoopFile string // loopback file, if used doBlkDiscard bool thinpBlockSize uint32 thinPoolDevice string Transaction `json:"-"` overrideUdevSyncCheck bool deferredRemove bool // use deferred removal BaseDeviceUUID string //save UUID of base device } type DiskUsage struct { Used uint64 Total uint64 Available uint64 } type Status struct { PoolName string DataFile string // actual block device for data DataLoopback string // loopback file, if used MetadataFile string // actual block device for metadata MetadataLoopback string // loopback file, if used Data DiskUsage Metadata DiskUsage SectorSize uint64 UdevSyncSupported bool DeferredRemoveEnabled bool } // Structure used to export image/container metadata in docker inspect. type DeviceMetadata struct { deviceId int deviceSize uint64 // size in bytes deviceName string // Device name as used during activation } type DevStatus struct { DeviceId int Size uint64 TransactionId uint64 SizeInSectors uint64 MappedSectors uint64 HighestMappedSector uint64 } func getDevName(name string) string { return "/dev/mapper/" + name } func (info *DevInfo) Name() string { hash := info.Hash if hash == "" { hash = "base" } return fmt.Sprintf("%s-%s", info.devices.devicePrefix, hash) } func (info *DevInfo) DevName() string { return getDevName(info.Name()) } func (devices *DeviceSet) loopbackDir() string { return path.Join(devices.root, "devicemapper") } func (devices *DeviceSet) metadataDir() string { return path.Join(devices.root, "metadata") } func (devices *DeviceSet) metadataFile(info *DevInfo) string { file := info.Hash if file == "" { file = "base" } return path.Join(devices.metadataDir(), file) } func (devices *DeviceSet) transactionMetaFile() string { return path.Join(devices.metadataDir(), transactionMetaFile) } func (devices *DeviceSet) deviceSetMetaFile() string { return path.Join(devices.metadataDir(), deviceSetMetaFile) } func (devices *DeviceSet) oldMetadataFile() string { return path.Join(devices.loopbackDir(), "json") } func (devices *DeviceSet) getPoolName() string { if devices.thinPoolDevice == "" { return devices.devicePrefix + "-pool" } return devices.thinPoolDevice } func (devices *DeviceSet) getPoolDevName() string { return getDevName(devices.getPoolName()) } func (devices *DeviceSet) hasImage(name string) bool { dirname := devices.loopbackDir() filename := path.Join(dirname, name) _, err := os.Stat(filename) return err == nil } // ensureImage creates a sparse file of bytes at the path // /devicemapper/. // If the file already exists, it does nothing. // Either way it returns the full path. func (devices *DeviceSet) ensureImage(name string, size int64) (string, error) { dirname := devices.loopbackDir() filename := path.Join(dirname, name) if err := os.MkdirAll(dirname, 0700); err != nil && !os.IsExist(err) { return "", err } if _, err := os.Stat(filename); err != nil { if !os.IsNotExist(err) { return "", err } logrus.Debugf("Creating loopback file %s for device-manage use", filename) file, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0600) if err != nil { return "", err } defer file.Close() if err := file.Truncate(size); err != nil { return "", err } } return filename, nil } func (devices *DeviceSet) allocateTransactionId() uint64 { devices.OpenTransactionId = devices.TransactionId + 1 return devices.OpenTransactionId } func (devices *DeviceSet) updatePoolTransactionId() error { if err := devicemapper.SetTransactionId(devices.getPoolDevName(), devices.TransactionId, devices.OpenTransactionId); err != nil { return fmt.Errorf("Error setting devmapper transaction ID: %s", err) } devices.TransactionId = devices.OpenTransactionId return nil } func (devices *DeviceSet) removeMetadata(info *DevInfo) error { if err := os.RemoveAll(devices.metadataFile(info)); err != nil { return fmt.Errorf("Error removing metadata file %s: %s", devices.metadataFile(info), err) } return nil } // Given json data and file path, write it to disk func (devices *DeviceSet) writeMetaFile(jsonData []byte, filePath string) error { tmpFile, err := ioutil.TempFile(devices.metadataDir(), ".tmp") if err != nil { return fmt.Errorf("Error creating metadata file: %s", err) } n, err := tmpFile.Write(jsonData) if err != nil { return fmt.Errorf("Error writing metadata to %s: %s", tmpFile.Name(), err) } if n < len(jsonData) { return io.ErrShortWrite } if err := tmpFile.Sync(); err != nil { return fmt.Errorf("Error syncing metadata file %s: %s", tmpFile.Name(), err) } if err := tmpFile.Close(); err != nil { return fmt.Errorf("Error closing metadata file %s: %s", tmpFile.Name(), err) } if err := os.Rename(tmpFile.Name(), filePath); err != nil { return fmt.Errorf("Error committing metadata file %s: %s", tmpFile.Name(), err) } return nil } func (devices *DeviceSet) saveMetadata(info *DevInfo) error { jsonData, err := json.Marshal(info) if err != nil { return fmt.Errorf("Error encoding metadata to json: %s", err) } if err := devices.writeMetaFile(jsonData, devices.metadataFile(info)); err != nil { return err } return nil } func (devices *DeviceSet) markDeviceIdUsed(deviceId int) { var mask byte i := deviceId % 8 mask = 1 << uint(i) devices.deviceIdMap[deviceId/8] = devices.deviceIdMap[deviceId/8] | mask } func (devices *DeviceSet) markDeviceIdFree(deviceId int) { var mask byte i := deviceId % 8 mask = ^(1 << uint(i)) devices.deviceIdMap[deviceId/8] = devices.deviceIdMap[deviceId/8] & mask } func (devices *DeviceSet) isDeviceIdFree(deviceId int) bool { var mask byte i := deviceId % 8 mask = (1 << uint(i)) if (devices.deviceIdMap[deviceId/8] & mask) != 0 { return false } return true } func (devices *DeviceSet) lookupDevice(hash string) (*DevInfo, error) { devices.devicesLock.Lock() defer devices.devicesLock.Unlock() info := devices.Devices[hash] if info == nil { info = devices.loadMetadata(hash) if info == nil { return nil, fmt.Errorf("Unknown device %s", hash) } devices.Devices[hash] = info } return info, nil } func (devices *DeviceSet) deviceFileWalkFunction(path string, finfo os.FileInfo) error { // Skip some of the meta files which are not device files. if strings.HasSuffix(finfo.Name(), ".migrated") { logrus.Debugf("Skipping file %s", path) return nil } if strings.HasPrefix(finfo.Name(), ".") { logrus.Debugf("Skipping file %s", path) return nil } if finfo.Name() == deviceSetMetaFile { logrus.Debugf("Skipping file %s", path) return nil } logrus.Debugf("Loading data for file %s", path) hash := finfo.Name() if hash == "base" { hash = "" } dinfo := devices.loadMetadata(hash) if dinfo == nil { return fmt.Errorf("Error loading device metadata file %s", hash) } if dinfo.DeviceId > MaxDeviceId { logrus.Errorf("Ignoring Invalid DeviceId=%d", dinfo.DeviceId) return nil } devices.Lock() devices.markDeviceIdUsed(dinfo.DeviceId) devices.Unlock() logrus.Debugf("Added deviceId=%d to DeviceIdMap", dinfo.DeviceId) return nil } func (devices *DeviceSet) constructDeviceIdMap() error { logrus.Debugf("[deviceset] constructDeviceIdMap()") defer logrus.Debugf("[deviceset] constructDeviceIdMap() END") var scan = func(path string, info os.FileInfo, err error) error { if err != nil { logrus.Debugf("Can't walk the file %s", path) return nil } // Skip any directories if info.IsDir() { return nil } return devices.deviceFileWalkFunction(path, info) } return filepath.Walk(devices.metadataDir(), scan) } func (devices *DeviceSet) unregisterDevice(id int, hash string) error { logrus.Debugf("unregisterDevice(%v, %v)", id, hash) info := &DevInfo{ Hash: hash, DeviceId: id, } devices.devicesLock.Lock() delete(devices.Devices, hash) devices.devicesLock.Unlock() if err := devices.removeMetadata(info); err != nil { logrus.Debugf("Error removing metadata: %s", err) return err } return nil } func (devices *DeviceSet) registerDevice(id int, hash string, size uint64, transactionId uint64) (*DevInfo, error) { logrus.Debugf("registerDevice(%v, %v)", id, hash) info := &DevInfo{ Hash: hash, DeviceId: id, Size: size, TransactionId: transactionId, Initialized: false, devices: devices, } devices.devicesLock.Lock() devices.Devices[hash] = info devices.devicesLock.Unlock() if err := devices.saveMetadata(info); err != nil { // Try to remove unused device devices.devicesLock.Lock() delete(devices.Devices, hash) devices.devicesLock.Unlock() return nil, err } return info, nil } func (devices *DeviceSet) activateDeviceIfNeeded(info *DevInfo) error { logrus.Debugf("activateDeviceIfNeeded(%v)", info.Hash) // Make sure deferred removal on device is canceled, if one was // scheduled. if err := devices.cancelDeferredRemoval(info); err != nil { return fmt.Errorf("Deivce Deferred Removal Cancellation Failed: %s", err) } if devinfo, _ := devicemapper.GetInfo(info.Name()); devinfo != nil && devinfo.Exists != 0 { return nil } return devicemapper.ActivateDevice(devices.getPoolDevName(), info.Name(), info.DeviceId, info.Size) } func (devices *DeviceSet) createFilesystem(info *DevInfo) error { devname := info.DevName() args := []string{} for _, arg := range devices.mkfsArgs { args = append(args, arg) } args = append(args, devname) var err error switch devices.filesystem { case "xfs": err = exec.Command("mkfs.xfs", args...).Run() case "ext4": err = exec.Command("mkfs.ext4", append([]string{"-E", "nodiscard,lazy_itable_init=0,lazy_journal_init=0"}, args...)...).Run() if err != nil { err = exec.Command("mkfs.ext4", append([]string{"-E", "nodiscard,lazy_itable_init=0"}, args...)...).Run() } if err != nil { return err } err = exec.Command("tune2fs", append([]string{"-c", "-1", "-i", "0"}, devname)...).Run() default: err = fmt.Errorf("Unsupported filesystem type %s", devices.filesystem) } if err != nil { return err } return nil } func (devices *DeviceSet) migrateOldMetaData() error { // Migrate old metadata file jsonData, err := ioutil.ReadFile(devices.oldMetadataFile()) if err != nil && !os.IsNotExist(err) { return err } if jsonData != nil { m := MetaData{Devices: make(map[string]*DevInfo)} if err := json.Unmarshal(jsonData, &m); err != nil { return err } for hash, info := range m.Devices { info.Hash = hash devices.saveMetadata(info) } if err := os.Rename(devices.oldMetadataFile(), devices.oldMetadataFile()+".migrated"); err != nil { return err } } return nil } func (devices *DeviceSet) initMetaData() error { if err := devices.migrateOldMetaData(); err != nil { return err } _, transactionId, _, _, _, _, err := devices.poolStatus() if err != nil { return err } devices.TransactionId = transactionId if err := devices.constructDeviceIdMap(); err != nil { return err } if err := devices.processPendingTransaction(); err != nil { return err } return nil } func (devices *DeviceSet) incNextDeviceId() { // Ids are 24bit, so wrap around devices.NextDeviceId = (devices.NextDeviceId + 1) & MaxDeviceId } func (devices *DeviceSet) getNextFreeDeviceId() (int, error) { devices.incNextDeviceId() for i := 0; i <= MaxDeviceId; i++ { if devices.isDeviceIdFree(devices.NextDeviceId) { devices.markDeviceIdUsed(devices.NextDeviceId) return devices.NextDeviceId, nil } devices.incNextDeviceId() } return 0, fmt.Errorf("Unable to find a free device Id") } func (devices *DeviceSet) createRegisterDevice(hash string) (*DevInfo, error) { deviceId, err := devices.getNextFreeDeviceId() if err != nil { return nil, err } if err := devices.openTransaction(hash, deviceId); err != nil { logrus.Debugf("Error opening transaction hash = %s deviceId = %d", hash, deviceId) devices.markDeviceIdFree(deviceId) return nil, err } for { if err := devicemapper.CreateDevice(devices.getPoolDevName(), deviceId); err != nil { if devicemapper.DeviceIdExists(err) { // Device Id already exists. This should not // happen. Now we have a mechianism to find // a free device Id. So something is not right. // Give a warning and continue. logrus.Errorf("Device Id %d exists in pool but it is supposed to be unused", deviceId) deviceId, err = devices.getNextFreeDeviceId() if err != nil { return nil, err } // Save new device id into transaction devices.refreshTransaction(deviceId) continue } logrus.Debugf("Error creating device: %s", err) devices.markDeviceIdFree(deviceId) return nil, err } break } logrus.Debugf("Registering device (id %v) with FS size %v", deviceId, devices.baseFsSize) info, err := devices.registerDevice(deviceId, hash, devices.baseFsSize, devices.OpenTransactionId) if err != nil { _ = devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) devices.markDeviceIdFree(deviceId) return nil, err } if err := devices.closeTransaction(); err != nil { devices.unregisterDevice(deviceId, hash) devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) devices.markDeviceIdFree(deviceId) return nil, err } return info, nil } func (devices *DeviceSet) createRegisterSnapDevice(hash string, baseInfo *DevInfo) error { deviceId, err := devices.getNextFreeDeviceId() if err != nil { return err } if err := devices.openTransaction(hash, deviceId); err != nil { logrus.Debugf("Error opening transaction hash = %s deviceId = %d", hash, deviceId) devices.markDeviceIdFree(deviceId) return err } for { if err := devicemapper.CreateSnapDevice(devices.getPoolDevName(), deviceId, baseInfo.Name(), baseInfo.DeviceId); err != nil { if devicemapper.DeviceIdExists(err) { // Device Id already exists. This should not // happen. Now we have a mechianism to find // a free device Id. So something is not right. // Give a warning and continue. logrus.Errorf("Device Id %d exists in pool but it is supposed to be unused", deviceId) deviceId, err = devices.getNextFreeDeviceId() if err != nil { return err } // Save new device id into transaction devices.refreshTransaction(deviceId) continue } logrus.Debugf("Error creating snap device: %s", err) devices.markDeviceIdFree(deviceId) return err } break } if _, err := devices.registerDevice(deviceId, hash, baseInfo.Size, devices.OpenTransactionId); err != nil { devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) devices.markDeviceIdFree(deviceId) logrus.Debugf("Error registering device: %s", err) return err } if err := devices.closeTransaction(); err != nil { devices.unregisterDevice(deviceId, hash) devicemapper.DeleteDevice(devices.getPoolDevName(), deviceId) devices.markDeviceIdFree(deviceId) return err } return nil } func (devices *DeviceSet) loadMetadata(hash string) *DevInfo { info := &DevInfo{Hash: hash, devices: devices} jsonData, err := ioutil.ReadFile(devices.metadataFile(info)) if err != nil { return nil } if err := json.Unmarshal(jsonData, &info); err != nil { return nil } return info } func getDeviceUUID(device string) (string, error) { out, err := exec.Command("blkid", "-s", "UUID", "-o", "value", device).Output() if err != nil { logrus.Debugf("Failed to find uuid for device %s:%v", device, err) return "", err } uuid := strings.TrimSuffix(string(out), "\n") uuid = strings.TrimSpace(uuid) logrus.Debugf("UUID for device: %s is:%s", device, uuid) return uuid, nil } func (devices *DeviceSet) verifyBaseDeviceUUID(baseInfo *DevInfo) error { devices.Lock() defer devices.Unlock() if err := devices.activateDeviceIfNeeded(baseInfo); err != nil { return err } defer devices.deactivateDevice(baseInfo) uuid, err := getDeviceUUID(baseInfo.DevName()) if err != nil { return err } if devices.BaseDeviceUUID != uuid { return fmt.Errorf("Current Base Device UUID:%s does not match with stored UUID:%s", uuid, devices.BaseDeviceUUID) } return nil } func (devices *DeviceSet) saveBaseDeviceUUID(baseInfo *DevInfo) error { devices.Lock() defer devices.Unlock() if err := devices.activateDeviceIfNeeded(baseInfo); err != nil { return err } defer devices.deactivateDevice(baseInfo) uuid, err := getDeviceUUID(baseInfo.DevName()) if err != nil { return err } devices.BaseDeviceUUID = uuid devices.saveDeviceSetMetaData() return nil } func (devices *DeviceSet) setupBaseImage() error { oldInfo, _ := devices.lookupDevice("") if oldInfo != nil && oldInfo.Initialized { // If BaseDeviceUUID is nil (upgrade case), save it and // return success. if devices.BaseDeviceUUID == "" { if err := devices.saveBaseDeviceUUID(oldInfo); err != nil { return fmt.Errorf("Could not query and save base device UUID:%v", err) } return nil } if err := devices.verifyBaseDeviceUUID(oldInfo); err != nil { return fmt.Errorf("Base Device UUID verification failed. Possibly using a different thin pool then last invocation:%v", err) } return nil } if oldInfo != nil && !oldInfo.Initialized { logrus.Debugf("Removing uninitialized base image") if err := devices.DeleteDevice(""); err != nil { return err } } if devices.thinPoolDevice != "" && oldInfo == nil { _, transactionId, dataUsed, _, _, _, err := devices.poolStatus() if err != nil { return err } if dataUsed != 0 { return fmt.Errorf("Unable to take ownership of thin-pool (%s) that already has used data blocks", devices.thinPoolDevice) } if transactionId != 0 { return fmt.Errorf("Unable to take ownership of thin-pool (%s) with non-zero transaction Id", devices.thinPoolDevice) } } logrus.Debugf("Initializing base device-mapper thin volume") // Create initial device info, err := devices.createRegisterDevice("") if err != nil { return err } logrus.Debugf("Creating filesystem on base device-mapper thin volume") if err := devices.activateDeviceIfNeeded(info); err != nil { return err } if err := devices.createFilesystem(info); err != nil { return err } info.Initialized = true if err := devices.saveMetadata(info); err != nil { info.Initialized = false return err } if err := devices.saveBaseDeviceUUID(info); err != nil { return fmt.Errorf("Could not query and save base device UUID:%v", err) } return nil } func setCloseOnExec(name string) { if fileInfos, _ := ioutil.ReadDir("/proc/self/fd"); fileInfos != nil { for _, i := range fileInfos { link, _ := os.Readlink(filepath.Join("/proc/self/fd", i.Name())) if link == name { fd, err := strconv.Atoi(i.Name()) if err == nil { syscall.CloseOnExec(fd) } } } } } func (devices *DeviceSet) DMLog(level int, file string, line int, dmError int, message string) { // By default libdm sends us all the messages including debug ones. // We need to filter out messages here and figure out which one // should be printed. if level > DMLogLevel { return } // FIXME(vbatts) push this back into ./pkg/devicemapper/ if level <= devicemapper.LogLevelErr { logrus.Errorf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message) } else if level <= devicemapper.LogLevelInfo { logrus.Infof("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message) } else { // FIXME(vbatts) push this back into ./pkg/devicemapper/ logrus.Debugf("libdevmapper(%d): %s:%d (%d) %s", level, file, line, dmError, message) } } func major(device uint64) uint64 { return (device >> 8) & 0xfff } func minor(device uint64) uint64 { return (device & 0xff) | ((device >> 12) & 0xfff00) } func (devices *DeviceSet) ResizePool(size int64) error { dirname := devices.loopbackDir() datafilename := path.Join(dirname, "data") if len(devices.dataDevice) > 0 { datafilename = devices.dataDevice } metadatafilename := path.Join(dirname, "metadata") if len(devices.metadataDevice) > 0 { metadatafilename = devices.metadataDevice } datafile, err := os.OpenFile(datafilename, os.O_RDWR, 0) if datafile == nil { return err } defer datafile.Close() fi, err := datafile.Stat() if fi == nil { return err } if fi.Size() > size { return fmt.Errorf("Can't shrink file") } dataloopback := devicemapper.FindLoopDeviceFor(datafile) if dataloopback == nil { return fmt.Errorf("Unable to find loopback mount for: %s", datafilename) } defer dataloopback.Close() metadatafile, err := os.OpenFile(metadatafilename, os.O_RDWR, 0) if metadatafile == nil { return err } defer metadatafile.Close() metadataloopback := devicemapper.FindLoopDeviceFor(metadatafile) if metadataloopback == nil { return fmt.Errorf("Unable to find loopback mount for: %s", metadatafilename) } defer metadataloopback.Close() // Grow loopback file if err := datafile.Truncate(size); err != nil { return fmt.Errorf("Unable to grow loopback file: %s", err) } // Reload size for loopback device if err := devicemapper.LoopbackSetCapacity(dataloopback); err != nil { return fmt.Errorf("Unable to update loopback capacity: %s", err) } // Suspend the pool if err := devicemapper.SuspendDevice(devices.getPoolName()); err != nil { return fmt.Errorf("Unable to suspend pool: %s", err) } // Reload with the new block sizes if err := devicemapper.ReloadPool(devices.getPoolName(), dataloopback, metadataloopback, devices.thinpBlockSize); err != nil { return fmt.Errorf("Unable to reload pool: %s", err) } // Resume the pool if err := devicemapper.ResumeDevice(devices.getPoolName()); err != nil { return fmt.Errorf("Unable to resume pool: %s", err) } return nil } func (devices *DeviceSet) loadTransactionMetaData() error { jsonData, err := ioutil.ReadFile(devices.transactionMetaFile()) if err != nil { // There is no active transaction. This will be the case // during upgrade. if os.IsNotExist(err) { devices.OpenTransactionId = devices.TransactionId return nil } return err } json.Unmarshal(jsonData, &devices.Transaction) return nil } func (devices *DeviceSet) saveTransactionMetaData() error { jsonData, err := json.Marshal(&devices.Transaction) if err != nil { return fmt.Errorf("Error encoding metadata to json: %s", err) } return devices.writeMetaFile(jsonData, devices.transactionMetaFile()) } func (devices *DeviceSet) removeTransactionMetaData() error { if err := os.RemoveAll(devices.transactionMetaFile()); err != nil { return err } return nil } func (devices *DeviceSet) rollbackTransaction() error { logrus.Debugf("Rolling back open transaction: TransactionId=%d hash=%s device_id=%d", devices.OpenTransactionId, devices.DeviceIdHash, devices.DeviceId) // A device id might have already been deleted before transaction // closed. In that case this call will fail. Just leave a message // in case of failure. if err := devicemapper.DeleteDevice(devices.getPoolDevName(), devices.DeviceId); err != nil { logrus.Errorf("Unable to delete device: %s", err) } dinfo := &DevInfo{Hash: devices.DeviceIdHash} if err := devices.removeMetadata(dinfo); err != nil { logrus.Errorf("Unable to remove metadata: %s", err) } else { devices.markDeviceIdFree(devices.DeviceId) } if err := devices.removeTransactionMetaData(); err != nil { logrus.Errorf("Unable to remove transaction meta file %s: %s", devices.transactionMetaFile(), err) } return nil } func (devices *DeviceSet) processPendingTransaction() error { if err := devices.loadTransactionMetaData(); err != nil { return err } // If there was open transaction but pool transaction Id is same // as open transaction Id, nothing to roll back. if devices.TransactionId == devices.OpenTransactionId { return nil } // If open transaction Id is less than pool transaction Id, something // is wrong. Bail out. if devices.OpenTransactionId < devices.TransactionId { logrus.Errorf("Open Transaction id %d is less than pool transaction id %d", devices.OpenTransactionId, devices.TransactionId) return nil } // Pool transaction Id is not same as open transaction. There is // a transaction which was not completed. if err := devices.rollbackTransaction(); err != nil { return fmt.Errorf("Rolling back open transaction failed: %s", err) } devices.OpenTransactionId = devices.TransactionId return nil } func (devices *DeviceSet) loadDeviceSetMetaData() error { jsonData, err := ioutil.ReadFile(devices.deviceSetMetaFile()) if err != nil { // For backward compatibility return success if file does // not exist. if os.IsNotExist(err) { return nil } return err } return json.Unmarshal(jsonData, devices) } func (devices *DeviceSet) saveDeviceSetMetaData() error { jsonData, err := json.Marshal(devices) if err != nil { return fmt.Errorf("Error encoding metadata to json: %s", err) } return devices.writeMetaFile(jsonData, devices.deviceSetMetaFile()) } func (devices *DeviceSet) openTransaction(hash string, DeviceId int) error { devices.allocateTransactionId() devices.DeviceIdHash = hash devices.DeviceId = DeviceId if err := devices.saveTransactionMetaData(); err != nil { return fmt.Errorf("Error saving transaction metadata: %s", err) } return nil } func (devices *DeviceSet) refreshTransaction(DeviceId int) error { devices.DeviceId = DeviceId if err := devices.saveTransactionMetaData(); err != nil { return fmt.Errorf("Error saving transaction metadata: %s", err) } return nil } func (devices *DeviceSet) closeTransaction() error { if err := devices.updatePoolTransactionId(); err != nil { logrus.Debugf("Failed to close Transaction") return err } return nil } func determineDriverCapabilities(version string) error { /* * Driver version 4.27.0 and greater support deferred activation * feature. */ logrus.Debugf("devicemapper: driver version is %s", version) versionSplit := strings.Split(version, ".") major, err := strconv.Atoi(versionSplit[0]) if err != nil { return graphdriver.ErrNotSupported } if major > 4 { DriverDeferredRemovalSupport = true return nil } if major < 4 { return nil } minor, err := strconv.Atoi(versionSplit[1]) if err != nil { return graphdriver.ErrNotSupported } /* * If major is 4 and minor is 27, then there is no need to * check for patch level as it can not be less than 0. */ if minor >= 27 { DriverDeferredRemovalSupport = true return nil } return nil } // Determine the major and minor number of loopback device func getDeviceMajorMinor(file *os.File) (uint64, uint64, error) { stat, err := file.Stat() if err != nil { return 0, 0, err } dev := stat.Sys().(*syscall.Stat_t).Rdev majorNum := major(dev) minorNum := minor(dev) logrus.Debugf("[devmapper]: Major:Minor for device: %s is:%v:%v", file.Name(), majorNum, minorNum) return majorNum, minorNum, nil } // Given a file which is backing file of a loop back device, find the // loopback device name and its major/minor number. func getLoopFileDeviceMajMin(filename string) (string, uint64, uint64, error) { file, err := os.Open(filename) if err != nil { logrus.Debugf("[devmapper]: Failed to open file %s", filename) return "", 0, 0, err } defer file.Close() loopbackDevice := devicemapper.FindLoopDeviceFor(file) if loopbackDevice == nil { return "", 0, 0, fmt.Errorf("[devmapper]: Unable to find loopback mount for: %s", filename) } defer loopbackDevice.Close() Major, Minor, err := getDeviceMajorMinor(loopbackDevice) if err != nil { return "", 0, 0, err } return loopbackDevice.Name(), Major, Minor, nil } // Get the major/minor numbers of thin pool data and metadata devices func (devices *DeviceSet) getThinPoolDataMetaMajMin() (uint64, uint64, uint64, uint64, error) { var params, poolDataMajMin, poolMetadataMajMin string _, _, _, params, err := devicemapper.GetTable(devices.getPoolName()) if err != nil { return 0, 0, 0, 0, err } if _, err = fmt.Sscanf(params, "%s %s", &poolMetadataMajMin, &poolDataMajMin); err != nil { return 0, 0, 0, 0, err } logrus.Debugf("[devmapper]: poolDataMajMin=%s poolMetaMajMin=%s\n", poolDataMajMin, poolMetadataMajMin) poolDataMajMinorSplit := strings.Split(poolDataMajMin, ":") poolDataMajor, err := strconv.ParseUint(poolDataMajMinorSplit[0], 10, 32) if err != nil { return 0, 0, 0, 0, err } poolDataMinor, err := strconv.ParseUint(poolDataMajMinorSplit[1], 10, 32) if err != nil { return 0, 0, 0, 0, err } poolMetadataMajMinorSplit := strings.Split(poolMetadataMajMin, ":") poolMetadataMajor, err := strconv.ParseUint(poolMetadataMajMinorSplit[0], 10, 32) if err != nil { return 0, 0, 0, 0, err } poolMetadataMinor, err := strconv.ParseUint(poolMetadataMajMinorSplit[1], 10, 32) if err != nil { return 0, 0, 0, 0, err } return poolDataMajor, poolDataMinor, poolMetadataMajor, poolMetadataMinor, nil } func (devices *DeviceSet) loadThinPoolLoopBackInfo() error { poolDataMajor, poolDataMinor, poolMetadataMajor, poolMetadataMinor, err := devices.getThinPoolDataMetaMajMin() if err != nil { return err } dirname := devices.loopbackDir() // data device has not been passed in. So there should be a data file // which is being mounted as loop device. if devices.dataDevice == "" { datafilename := path.Join(dirname, "data") dataLoopDevice, dataMajor, dataMinor, err := getLoopFileDeviceMajMin(datafilename) if err != nil { return err } // Compare the two if poolDataMajor == dataMajor && poolDataMinor == dataMinor { devices.dataDevice = dataLoopDevice devices.dataLoopFile = datafilename } } // metadata device has not been passed in. So there should be a // metadata file which is being mounted as loop device. if devices.metadataDevice == "" { metadatafilename := path.Join(dirname, "metadata") metadataLoopDevice, metadataMajor, metadataMinor, err := getLoopFileDeviceMajMin(metadatafilename) if err != nil { return err } if poolMetadataMajor == metadataMajor && poolMetadataMinor == metadataMinor { devices.metadataDevice = metadataLoopDevice devices.metadataLoopFile = metadatafilename } } return nil } func (devices *DeviceSet) initDevmapper(doInit bool) error { // give ourselves to libdm as a log handler devicemapper.LogInit(devices) version, err := devicemapper.GetDriverVersion() if err != nil { // Can't even get driver version, assume not supported return graphdriver.ErrNotSupported } if err := determineDriverCapabilities(version); err != nil { return graphdriver.ErrNotSupported } // If user asked for deferred removal and both library and driver // supports deferred removal use it. if EnableDeferredRemoval && DriverDeferredRemovalSupport && devicemapper.LibraryDeferredRemovalSupport == true { logrus.Debugf("devmapper: Deferred removal support enabled.") devices.deferredRemove = true } // https://github.com/docker/docker/issues/4036 if supported := devicemapper.UdevSetSyncSupport(true); !supported { logrus.Warn("Udev sync is not supported. This will lead to unexpected behavior, data loss and errors. For more information, see https://docs.docker.com/reference/commandline/cli/#daemon-storage-driver-option") } if err := os.MkdirAll(devices.metadataDir(), 0700); err != nil && !os.IsExist(err) { return err } // Set the device prefix from the device id and inode of the docker root dir st, err := os.Stat(devices.root) if err != nil { return fmt.Errorf("Error looking up dir %s: %s", devices.root, err) } sysSt := st.Sys().(*syscall.Stat_t) // "reg-" stands for "regular file". // In the future we might use "dev-" for "device file", etc. // docker-maj,min[-inode] stands for: // - Managed by docker // - The target of this device is at major and minor // - If is defined, use that file inside the device as a loopback image. Otherwise use the device itself. devices.devicePrefix = fmt.Sprintf("docker-%d:%d-%d", major(sysSt.Dev), minor(sysSt.Dev), sysSt.Ino) logrus.Debugf("Generated prefix: %s", devices.devicePrefix) // Check for the existence of the thin-pool device logrus.Debugf("Checking for existence of the pool '%s'", devices.getPoolName()) info, err := devicemapper.GetInfo(devices.getPoolName()) if info == nil { logrus.Debugf("Error device devicemapper.GetInfo: %s", err) return err } // It seems libdevmapper opens this without O_CLOEXEC, and go exec will not close files // that are not Close-on-exec, and lxc-start will die if it inherits any unexpected files, // so we add this badhack to make sure it closes itself setCloseOnExec("/dev/mapper/control") // Make sure the sparse images exist in /devicemapper/data and // /devicemapper/metadata createdLoopback := false // If the pool doesn't exist, create it if info.Exists == 0 && devices.thinPoolDevice == "" { logrus.Debugf("Pool doesn't exist. Creating it.") var ( dataFile *os.File metadataFile *os.File ) if devices.dataDevice == "" { // Make sure the sparse images exist in /devicemapper/data hasData := devices.hasImage("data") if !doInit && !hasData { return errors.New("Loopback data file not found") } if !hasData { createdLoopback = true } data, err := devices.ensureImage("data", devices.dataLoopbackSize) if err != nil { logrus.Debugf("Error device ensureImage (data): %s", err) return err } dataFile, err = devicemapper.AttachLoopDevice(data) if err != nil { return err } devices.dataLoopFile = data devices.dataDevice = dataFile.Name() } else { dataFile, err = os.OpenFile(devices.dataDevice, os.O_RDWR, 0600) if err != nil { return err } } defer dataFile.Close() if devices.metadataDevice == "" { // Make sure the sparse images exist in /devicemapper/metadata hasMetadata := devices.hasImage("metadata") if !doInit && !hasMetadata { return errors.New("Loopback metadata file not found") } if !hasMetadata { createdLoopback = true } metadata, err := devices.ensureImage("metadata", devices.metaDataLoopbackSize) if err != nil { logrus.Debugf("Error device ensureImage (metadata): %s", err) return err } metadataFile, err = devicemapper.AttachLoopDevice(metadata) if err != nil { return err } devices.metadataLoopFile = metadata devices.metadataDevice = metadataFile.Name() } else { metadataFile, err = os.OpenFile(devices.metadataDevice, os.O_RDWR, 0600) if err != nil { return err } } defer metadataFile.Close() if err := devicemapper.CreatePool(devices.getPoolName(), dataFile, metadataFile, devices.thinpBlockSize); err != nil { return err } } // Pool already exists and caller did not pass us a pool. That means // we probably created pool earlier and could not remove it as some // containers were still using it. Detect some of the properties of // pool, like is it using loop devices. if info.Exists != 0 && devices.thinPoolDevice == "" { if err := devices.loadThinPoolLoopBackInfo(); err != nil { logrus.Debugf("Failed to load thin pool loopback device information:%v", err) return err } } // If we didn't just create the data or metadata image, we need to // load the transaction id and migrate old metadata if !createdLoopback { if err := devices.initMetaData(); err != nil { return err } } // Right now this loads only NextDeviceId. If there is more metadata // down the line, we might have to move it earlier. if err := devices.loadDeviceSetMetaData(); err != nil { return err } // Setup the base image if doInit { if err := devices.setupBaseImage(); err != nil { logrus.Debugf("Error device setupBaseImage: %s", err) return err } } return nil } func (devices *DeviceSet) AddDevice(hash, baseHash string) error { logrus.Debugf("[deviceset] AddDevice(hash=%s basehash=%s)", hash, baseHash) defer logrus.Debugf("[deviceset] AddDevice(hash=%s basehash=%s) END", hash, baseHash) baseInfo, err := devices.lookupDevice(baseHash) if err != nil { return err } baseInfo.lock.Lock() defer baseInfo.lock.Unlock() devices.Lock() defer devices.Unlock() if info, _ := devices.lookupDevice(hash); info != nil { return fmt.Errorf("device %s already exists", hash) } if err := devices.createRegisterSnapDevice(hash, baseInfo); err != nil { return err } return nil } func (devices *DeviceSet) deleteDevice(info *DevInfo) error { if devices.doBlkDiscard { // This is a workaround for the kernel not discarding block so // on the thin pool when we remove a thinp device, so we do it // manually if err := devices.activateDeviceIfNeeded(info); err == nil { if err := devicemapper.BlockDeviceDiscard(info.DevName()); err != nil { logrus.Debugf("Error discarding block on device: %s (ignoring)", err) } } } devinfo, _ := devicemapper.GetInfo(info.Name()) if devinfo != nil && devinfo.Exists != 0 { if err := devices.removeDevice(info.Name()); err != nil { logrus.Debugf("Error removing device: %s", err) return err } } if err := devices.openTransaction(info.Hash, info.DeviceId); err != nil { logrus.Debugf("Error opening transaction hash = %s deviceId = %d", "", info.DeviceId) return err } if err := devicemapper.DeleteDevice(devices.getPoolDevName(), info.DeviceId); err != nil { logrus.Debugf("Error deleting device: %s", err) return err } if err := devices.unregisterDevice(info.DeviceId, info.Hash); err != nil { return err } if err := devices.closeTransaction(); err != nil { return err } devices.markDeviceIdFree(info.DeviceId) return nil } func (devices *DeviceSet) DeleteDevice(hash string) error { info, err := devices.lookupDevice(hash) if err != nil { return err } info.lock.Lock() defer info.lock.Unlock() devices.Lock() defer devices.Unlock() return devices.deleteDevice(info) } func (devices *DeviceSet) deactivatePool() error { logrus.Debugf("[devmapper] deactivatePool()") defer logrus.Debugf("[devmapper] deactivatePool END") devname := devices.getPoolDevName() devinfo, err := devicemapper.GetInfo(devname) if err != nil { return err } if d, err := devicemapper.GetDeps(devname); err == nil { // Access to more Debug output logrus.Debugf("[devmapper] devicemapper.GetDeps() %s: %#v", devname, d) } if devinfo.Exists != 0 { return devicemapper.RemoveDevice(devname) } return nil } func (devices *DeviceSet) deactivateDevice(info *DevInfo) error { logrus.Debugf("[devmapper] deactivateDevice(%s)", info.Hash) defer logrus.Debugf("[devmapper] deactivateDevice END(%s)", info.Hash) devinfo, err := devicemapper.GetInfo(info.Name()) if err != nil { return err } if devinfo.Exists == 0 { return nil } if devices.deferredRemove { if err := devicemapper.RemoveDeviceDeferred(info.Name()); err != nil { return err } } else { if err := devices.removeDevice(info.Name()); err != nil { return err } } return nil } // Issues the underlying dm remove operation. func (devices *DeviceSet) removeDevice(devname string) error { var err error logrus.Debugf("[devmapper] removeDevice START(%s)", devname) defer logrus.Debugf("[devmapper] removeDevice END(%s)", devname) for i := 0; i < 200; i++ { err = devicemapper.RemoveDevice(devname) if err == nil { break } if err != devicemapper.ErrBusy { return err } // If we see EBUSY it may be a transient error, // sleep a bit a retry a few times. devices.Unlock() time.Sleep(100 * time.Millisecond) devices.Lock() } return err } func (devices *DeviceSet) cancelDeferredRemoval(info *DevInfo) error { if !devices.deferredRemove { return nil } logrus.Debugf("[devmapper] cancelDeferredRemoval START(%s)", info.Name()) defer logrus.Debugf("[devmapper] cancelDeferredRemoval END(%s)", info.Name()) devinfo, err := devicemapper.GetInfoWithDeferred(info.Name()) if devinfo != nil && devinfo.DeferredRemove == 0 { return nil } // Cancel deferred remove for i := 0; i < 100; i++ { err = devicemapper.CancelDeferredRemove(info.Name()) if err == nil { break } if err == devicemapper.ErrEnxio { // Device is probably already gone. Return success. return nil } if err != devicemapper.ErrBusy { return err } // If we see EBUSY it may be a transient error, // sleep a bit a retry a few times. devices.Unlock() time.Sleep(100 * time.Millisecond) devices.Lock() } return err } func (devices *DeviceSet) Shutdown() error { logrus.Debugf("[deviceset %s] Shutdown()", devices.devicePrefix) logrus.Debugf("[devmapper] Shutting down DeviceSet: %s", devices.root) defer logrus.Debugf("[deviceset %s] Shutdown() END", devices.devicePrefix) var devs []*DevInfo devices.devicesLock.Lock() for _, info := range devices.Devices { devs = append(devs, info) } devices.devicesLock.Unlock() for _, info := range devs { info.lock.Lock() if info.mountCount > 0 { // We use MNT_DETACH here in case it is still busy in some running // container. This means it'll go away from the global scope directly, // and the device will be released when that container dies. if err := syscall.Unmount(info.mountPath, syscall.MNT_DETACH); err != nil { logrus.Debugf("Shutdown unmounting %s, error: %s", info.mountPath, err) } devices.Lock() if err := devices.deactivateDevice(info); err != nil { logrus.Debugf("Shutdown deactivate %s , error: %s", info.Hash, err) } devices.Unlock() } info.lock.Unlock() } info, _ := devices.lookupDevice("") if info != nil { info.lock.Lock() devices.Lock() if err := devices.deactivateDevice(info); err != nil { logrus.Debugf("Shutdown deactivate base , error: %s", err) } devices.Unlock() info.lock.Unlock() } devices.Lock() if devices.thinPoolDevice == "" { if err := devices.deactivatePool(); err != nil { logrus.Debugf("Shutdown deactivate pool , error: %s", err) } } devices.saveDeviceSetMetaData() devices.Unlock() return nil } func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { info, err := devices.lookupDevice(hash) if err != nil { return err } info.lock.Lock() defer info.lock.Unlock() devices.Lock() defer devices.Unlock() if info.mountCount > 0 { if path != info.mountPath { return fmt.Errorf("Trying to mount devmapper device in multiple places (%s, %s)", info.mountPath, path) } info.mountCount++ return nil } if err := devices.activateDeviceIfNeeded(info); err != nil { return fmt.Errorf("Error activating devmapper device for '%s': %s", hash, err) } var flags uintptr = syscall.MS_MGC_VAL fstype, err := ProbeFsType(info.DevName()) if err != nil { return err } options := "" if fstype == "xfs" { // XFS needs nouuid or it can't mount filesystems with the same fs options = joinMountOptions(options, "nouuid") } options = joinMountOptions(options, devices.mountOptions) options = joinMountOptions(options, label.FormatMountLabel("", mountLabel)) if err := syscall.Mount(info.DevName(), path, fstype, flags, options); err != nil { return fmt.Errorf("Error mounting '%s' on '%s': %s", info.DevName(), path, err) } info.mountCount = 1 info.mountPath = path return nil } func (devices *DeviceSet) UnmountDevice(hash string) error { logrus.Debugf("[devmapper] UnmountDevice(hash=%s)", hash) defer logrus.Debugf("[devmapper] UnmountDevice(hash=%s) END", hash) info, err := devices.lookupDevice(hash) if err != nil { return err } info.lock.Lock() defer info.lock.Unlock() devices.Lock() defer devices.Unlock() if info.mountCount == 0 { return fmt.Errorf("UnmountDevice: device not-mounted id %s", hash) } info.mountCount-- if info.mountCount > 0 { return nil } logrus.Debugf("[devmapper] Unmount(%s)", info.mountPath) if err := syscall.Unmount(info.mountPath, syscall.MNT_DETACH); err != nil { return err } logrus.Debugf("[devmapper] Unmount done") if err := devices.deactivateDevice(info); err != nil { return err } info.mountPath = "" return nil } func (devices *DeviceSet) HasDevice(hash string) bool { devices.Lock() defer devices.Unlock() info, _ := devices.lookupDevice(hash) return info != nil } func (devices *DeviceSet) HasActivatedDevice(hash string) bool { info, _ := devices.lookupDevice(hash) if info == nil { return false } info.lock.Lock() defer info.lock.Unlock() devices.Lock() defer devices.Unlock() devinfo, _ := devicemapper.GetInfo(info.Name()) return devinfo != nil && devinfo.Exists != 0 } func (devices *DeviceSet) List() []string { devices.Lock() defer devices.Unlock() devices.devicesLock.Lock() ids := make([]string, len(devices.Devices)) i := 0 for k := range devices.Devices { ids[i] = k i++ } devices.devicesLock.Unlock() return ids } func (devices *DeviceSet) deviceStatus(devName string) (sizeInSectors, mappedSectors, highestMappedSector uint64, err error) { var params string _, sizeInSectors, _, params, err = devicemapper.GetStatus(devName) if err != nil { return } if _, err = fmt.Sscanf(params, "%d %d", &mappedSectors, &highestMappedSector); err == nil { return } return } func (devices *DeviceSet) GetDeviceStatus(hash string) (*DevStatus, error) { info, err := devices.lookupDevice(hash) if err != nil { return nil, err } info.lock.Lock() defer info.lock.Unlock() devices.Lock() defer devices.Unlock() status := &DevStatus{ DeviceId: info.DeviceId, Size: info.Size, TransactionId: info.TransactionId, } if err := devices.activateDeviceIfNeeded(info); err != nil { return nil, fmt.Errorf("Error activating devmapper device for '%s': %s", hash, err) } sizeInSectors, mappedSectors, highestMappedSector, err := devices.deviceStatus(info.DevName()) if err != nil { return nil, err } status.SizeInSectors = sizeInSectors status.MappedSectors = mappedSectors status.HighestMappedSector = highestMappedSector return status, nil } func (devices *DeviceSet) poolStatus() (totalSizeInSectors, transactionId, dataUsed, dataTotal, metadataUsed, metadataTotal uint64, err error) { var params string if _, totalSizeInSectors, _, params, err = devicemapper.GetStatus(devices.getPoolName()); err == nil { _, err = fmt.Sscanf(params, "%d %d/%d %d/%d", &transactionId, &metadataUsed, &metadataTotal, &dataUsed, &dataTotal) } return } // DataDevicePath returns the path to the data storage for this deviceset, // regardless of loopback or block device func (devices *DeviceSet) DataDevicePath() string { return devices.dataDevice } // MetadataDevicePath returns the path to the metadata storage for this deviceset, // regardless of loopback or block device func (devices *DeviceSet) MetadataDevicePath() string { return devices.metadataDevice } func (devices *DeviceSet) getUnderlyingAvailableSpace(loopFile string) (uint64, error) { buf := new(syscall.Statfs_t) if err := syscall.Statfs(loopFile, buf); err != nil { logrus.Warnf("Couldn't stat loopfile filesystem %v: %v", loopFile, err) return 0, err } return buf.Bfree * uint64(buf.Bsize), nil } func (devices *DeviceSet) isRealFile(loopFile string) (bool, error) { if loopFile != "" { fi, err := os.Stat(loopFile) if err != nil { logrus.Warnf("Couldn't stat loopfile %v: %v", loopFile, err) return false, err } return fi.Mode().IsRegular(), nil } return false, nil } // Status returns the current status of this deviceset func (devices *DeviceSet) Status() *Status { devices.Lock() defer devices.Unlock() status := &Status{} status.PoolName = devices.getPoolName() status.DataFile = devices.DataDevicePath() status.DataLoopback = devices.dataLoopFile status.MetadataFile = devices.MetadataDevicePath() status.MetadataLoopback = devices.metadataLoopFile status.UdevSyncSupported = devicemapper.UdevSyncSupported() status.DeferredRemoveEnabled = devices.deferredRemove totalSizeInSectors, _, dataUsed, dataTotal, metadataUsed, metadataTotal, err := devices.poolStatus() if err == nil { // Convert from blocks to bytes blockSizeInSectors := totalSizeInSectors / dataTotal status.Data.Used = dataUsed * blockSizeInSectors * 512 status.Data.Total = dataTotal * blockSizeInSectors * 512 status.Data.Available = status.Data.Total - status.Data.Used // metadata blocks are always 4k status.Metadata.Used = metadataUsed * 4096 status.Metadata.Total = metadataTotal * 4096 status.Metadata.Available = status.Metadata.Total - status.Metadata.Used status.SectorSize = blockSizeInSectors * 512 if check, _ := devices.isRealFile(devices.dataLoopFile); check { actualSpace, err := devices.getUnderlyingAvailableSpace(devices.dataLoopFile) if err == nil && actualSpace < status.Data.Available { status.Data.Available = actualSpace } } if check, _ := devices.isRealFile(devices.metadataLoopFile); check { actualSpace, err := devices.getUnderlyingAvailableSpace(devices.metadataLoopFile) if err == nil && actualSpace < status.Metadata.Available { status.Metadata.Available = actualSpace } } } return status } // Status returns the current status of this deviceset func (devices *DeviceSet) ExportDeviceMetadata(hash string) (*DeviceMetadata, error) { info, err := devices.lookupDevice(hash) if err != nil { return nil, err } info.lock.Lock() defer info.lock.Unlock() metadata := &DeviceMetadata{info.DeviceId, info.Size, info.Name()} return metadata, nil } func NewDeviceSet(root string, doInit bool, options []string) (*DeviceSet, error) { devicemapper.SetDevDir("/dev") devices := &DeviceSet{ root: root, MetaData: MetaData{Devices: make(map[string]*DevInfo)}, dataLoopbackSize: DefaultDataLoopbackSize, metaDataLoopbackSize: DefaultMetaDataLoopbackSize, baseFsSize: DefaultBaseFsSize, overrideUdevSyncCheck: DefaultUdevSyncOverride, filesystem: "ext4", doBlkDiscard: true, thinpBlockSize: DefaultThinpBlockSize, deviceIdMap: make([]byte, DeviceIdMapSz), } foundBlkDiscard := false for _, option := range options { key, val, err := parsers.ParseKeyValueOpt(option) if err != nil { return nil, err } key = strings.ToLower(key) switch key { case "dm.basesize": size, err := units.RAMInBytes(val) if err != nil { return nil, err } devices.baseFsSize = uint64(size) case "dm.loopdatasize": size, err := units.RAMInBytes(val) if err != nil { return nil, err } devices.dataLoopbackSize = size case "dm.loopmetadatasize": size, err := units.RAMInBytes(val) if err != nil { return nil, err } devices.metaDataLoopbackSize = size case "dm.fs": if val != "ext4" && val != "xfs" { return nil, fmt.Errorf("Unsupported filesystem %s\n", val) } devices.filesystem = val case "dm.mkfsarg": devices.mkfsArgs = append(devices.mkfsArgs, val) case "dm.mountopt": devices.mountOptions = joinMountOptions(devices.mountOptions, val) case "dm.metadatadev": devices.metadataDevice = val case "dm.datadev": devices.dataDevice = val case "dm.thinpooldev": devices.thinPoolDevice = strings.TrimPrefix(val, "/dev/mapper/") case "dm.blkdiscard": foundBlkDiscard = true devices.doBlkDiscard, err = strconv.ParseBool(val) if err != nil { return nil, err } case "dm.blocksize": size, err := units.RAMInBytes(val) if err != nil { return nil, err } // convert to 512b sectors devices.thinpBlockSize = uint32(size) >> 9 case "dm.override_udev_sync_check": devices.overrideUdevSyncCheck, err = strconv.ParseBool(val) if err != nil { return nil, err } case "dm.use_deferred_removal": EnableDeferredRemoval, err = strconv.ParseBool(val) if err != nil { return nil, err } default: return nil, fmt.Errorf("Unknown option %s\n", key) } } // By default, don't do blk discard hack on raw devices, its rarely useful and is expensive if !foundBlkDiscard && (devices.dataDevice != "" || devices.thinPoolDevice != "") { devices.doBlkDiscard = false } if err := devices.initDevmapper(doInit); err != nil { return nil, err } return devices, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/devmapper/devmapper_doc.go ================================================ package devmapper // Definition of struct dm_task and sub structures (from lvm2) // // struct dm_ioctl { // /* // * The version number is made up of three parts: // * major - no backward or forward compatibility, // * minor - only backwards compatible, // * patch - both backwards and forwards compatible. // * // * All clients of the ioctl interface should fill in the // * version number of the interface that they were // * compiled with. // * // * All recognised ioctl commands (ie. those that don't // * return -ENOTTY) fill out this field, even if the // * command failed. // */ // uint32_t version[3]; /* in/out */ // uint32_t data_size; /* total size of data passed in // * including this struct */ // uint32_t data_start; /* offset to start of data // * relative to start of this struct */ // uint32_t target_count; /* in/out */ // int32_t open_count; /* out */ // uint32_t flags; /* in/out */ // /* // * event_nr holds either the event number (input and output) or the // * udev cookie value (input only). // * The DM_DEV_WAIT ioctl takes an event number as input. // * The DM_SUSPEND, DM_DEV_REMOVE and DM_DEV_RENAME ioctls // * use the field as a cookie to return in the DM_COOKIE // * variable with the uevents they issue. // * For output, the ioctls return the event number, not the cookie. // */ // uint32_t event_nr; /* in/out */ // uint32_t padding; // uint64_t dev; /* in/out */ // char name[DM_NAME_LEN]; /* device name */ // char uuid[DM_UUID_LEN]; /* unique identifier for // * the block device */ // char data[7]; /* padding or data */ // }; // struct target { // uint64_t start; // uint64_t length; // char *type; // char *params; // struct target *next; // }; // typedef enum { // DM_ADD_NODE_ON_RESUME, /* add /dev/mapper node with dmsetup resume */ // DM_ADD_NODE_ON_CREATE /* add /dev/mapper node with dmsetup create */ // } dm_add_node_t; // struct dm_task { // int type; // char *dev_name; // char *mangled_dev_name; // struct target *head, *tail; // int read_only; // uint32_t event_nr; // int major; // int minor; // int allow_default_major_fallback; // uid_t uid; // gid_t gid; // mode_t mode; // uint32_t read_ahead; // uint32_t read_ahead_flags; // union { // struct dm_ioctl *v4; // } dmi; // char *newname; // char *message; // char *geometry; // uint64_t sector; // int no_flush; // int no_open_count; // int skip_lockfs; // int query_inactive_table; // int suppress_identical_reload; // dm_add_node_t add_node; // uint64_t existing_table_size; // int cookie_set; // int new_uuid; // int secure_data; // int retry_remove; // int enable_checks; // int expected_errno; // char *uuid; // char *mangled_uuid; // }; // ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/devmapper/devmapper_test.go ================================================ // +build linux package devmapper import ( "testing" "github.com/docker/docker/daemon/graphdriver/graphtest" ) func init() { // Reduce the size the the base fs and loopback for the tests DefaultDataLoopbackSize = 300 * 1024 * 1024 DefaultMetaDataLoopbackSize = 200 * 1024 * 1024 DefaultBaseFsSize = 300 * 1024 * 1024 DefaultUdevSyncOverride = true if err := graphtest.InitLoopbacks(); err != nil { panic(err) } } // This avoids creating a new driver for each test if all tests are run // Make sure to put new tests between TestDevmapperSetup and TestDevmapperTeardown func TestDevmapperSetup(t *testing.T) { graphtest.GetDriver(t, "devicemapper") } func TestDevmapperCreateEmpty(t *testing.T) { graphtest.DriverTestCreateEmpty(t, "devicemapper") } func TestDevmapperCreateBase(t *testing.T) { graphtest.DriverTestCreateBase(t, "devicemapper") } func TestDevmapperCreateSnap(t *testing.T) { graphtest.DriverTestCreateSnap(t, "devicemapper") } func TestDevmapperTeardown(t *testing.T) { graphtest.PutDriver(t) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/devmapper/driver.go ================================================ // +build linux package devmapper import ( "fmt" "io/ioutil" "os" "path" "strconv" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/devicemapper" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/units" ) func init() { graphdriver.Register("devicemapper", Init) } // Placeholder interfaces, to be replaced // at integration. // End of placeholder interfaces. type Driver struct { *DeviceSet home string } var backingFs = "" func Init(home string, options []string) (graphdriver.Driver, error) { fsMagic, err := graphdriver.GetFSMagic(home) if err != nil { return nil, err } if fsName, ok := graphdriver.FsNames[fsMagic]; ok { backingFs = fsName } deviceSet, err := NewDeviceSet(home, true, options) if err != nil { return nil, err } if err := mount.MakePrivate(home); err != nil { return nil, err } d := &Driver{ DeviceSet: deviceSet, home: home, } return graphdriver.NaiveDiffDriver(d), nil } func (d *Driver) String() string { return "devicemapper" } func (d *Driver) Status() [][2]string { s := d.DeviceSet.Status() status := [][2]string{ {"Pool Name", s.PoolName}, {"Pool Blocksize", fmt.Sprintf("%s", units.HumanSize(float64(s.SectorSize)))}, {"Backing Filesystem", backingFs}, {"Data file", s.DataFile}, {"Metadata file", s.MetadataFile}, {"Data Space Used", fmt.Sprintf("%s", units.HumanSize(float64(s.Data.Used)))}, {"Data Space Total", fmt.Sprintf("%s", units.HumanSize(float64(s.Data.Total)))}, {"Data Space Available", fmt.Sprintf("%s", units.HumanSize(float64(s.Data.Available)))}, {"Metadata Space Used", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Used)))}, {"Metadata Space Total", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Total)))}, {"Metadata Space Available", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Available)))}, {"Udev Sync Supported", fmt.Sprintf("%v", s.UdevSyncSupported)}, {"Deferred Removal Enabled", fmt.Sprintf("%v", s.DeferredRemoveEnabled)}, } if len(s.DataLoopback) > 0 { status = append(status, [2]string{"Data loop file", s.DataLoopback}) } if len(s.MetadataLoopback) > 0 { status = append(status, [2]string{"Metadata loop file", s.MetadataLoopback}) } if vStr, err := devicemapper.GetLibraryVersion(); err == nil { status = append(status, [2]string{"Library Version", vStr}) } return status } func (d *Driver) GetMetadata(id string) (map[string]string, error) { m, err := d.DeviceSet.ExportDeviceMetadata(id) if err != nil { return nil, err } metadata := make(map[string]string) metadata["DeviceId"] = strconv.Itoa(m.deviceId) metadata["DeviceSize"] = strconv.FormatUint(m.deviceSize, 10) metadata["DeviceName"] = m.deviceName return metadata, nil } func (d *Driver) Cleanup() error { err := d.DeviceSet.Shutdown() if err2 := mount.Unmount(d.home); err == nil { err = err2 } return err } func (d *Driver) Create(id, parent string) error { if err := d.DeviceSet.AddDevice(id, parent); err != nil { return err } return nil } func (d *Driver) Remove(id string) error { if !d.DeviceSet.HasDevice(id) { // Consider removing a non-existing device a no-op // This is useful to be able to progress on container removal // if the underlying device has gone away due to earlier errors return nil } // This assumes the device has been properly Get/Put:ed and thus is unmounted if err := d.DeviceSet.DeleteDevice(id); err != nil { return err } mp := path.Join(d.home, "mnt", id) if err := os.RemoveAll(mp); err != nil && !os.IsNotExist(err) { return err } return nil } func (d *Driver) Get(id, mountLabel string) (string, error) { mp := path.Join(d.home, "mnt", id) // Create the target directories if they don't exist if err := os.MkdirAll(mp, 0755); err != nil && !os.IsExist(err) { return "", err } // Mount the device if err := d.DeviceSet.MountDevice(id, mp, mountLabel); err != nil { return "", err } rootFs := path.Join(mp, "rootfs") if err := os.MkdirAll(rootFs, 0755); err != nil && !os.IsExist(err) { d.DeviceSet.UnmountDevice(id) return "", err } idFile := path.Join(mp, "id") if _, err := os.Stat(idFile); err != nil && os.IsNotExist(err) { // Create an "id" file with the container/image id in it to help reconscruct this in case // of later problems if err := ioutil.WriteFile(idFile, []byte(id), 0600); err != nil { d.DeviceSet.UnmountDevice(id) return "", err } } return rootFs, nil } func (d *Driver) Put(id string) error { err := d.DeviceSet.UnmountDevice(id) if err != nil { logrus.Errorf("Error unmounting device %s: %s", id, err) } return err } func (d *Driver) Exists(id string) bool { return d.DeviceSet.HasDevice(id) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/devmapper/mount.go ================================================ // +build linux package devmapper import ( "bytes" "fmt" "os" "path/filepath" "syscall" ) // FIXME: this is copy-pasted from the aufs driver. // It should be moved into the core. func Mounted(mountpoint string) (bool, error) { mntpoint, err := os.Stat(mountpoint) if err != nil { if os.IsNotExist(err) { return false, nil } return false, err } parent, err := os.Stat(filepath.Join(mountpoint, "..")) if err != nil { return false, err } mntpointSt := mntpoint.Sys().(*syscall.Stat_t) parentSt := parent.Sys().(*syscall.Stat_t) return mntpointSt.Dev != parentSt.Dev, nil } type probeData struct { fsName string magic string offset uint64 } func ProbeFsType(device string) (string, error) { probes := []probeData{ {"btrfs", "_BHRfS_M", 0x10040}, {"ext4", "\123\357", 0x438}, {"xfs", "XFSB", 0}, } maxLen := uint64(0) for _, p := range probes { l := p.offset + uint64(len(p.magic)) if l > maxLen { maxLen = l } } file, err := os.Open(device) if err != nil { return "", err } defer file.Close() buffer := make([]byte, maxLen) l, err := file.Read(buffer) if err != nil { return "", err } if uint64(l) != maxLen { return "", fmt.Errorf("unable to detect filesystem type of %s, short read", device) } for _, p := range probes { if bytes.Equal([]byte(p.magic), buffer[p.offset:p.offset+uint64(len(p.magic))]) { return p.fsName, nil } } return "", fmt.Errorf("Unknown filesystem type on %s", device) } func joinMountOptions(a, b string) string { if a == "" { return b } if b == "" { return a } return a + "," + b } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/driver.go ================================================ package graphdriver import ( "errors" "fmt" "os" "path/filepath" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/archive" ) type FsMagic uint32 const ( FsMagicUnsupported = FsMagic(0x00000000) ) var ( DefaultDriver string // All registred drivers drivers map[string]InitFunc ErrNotSupported = errors.New("driver not supported") ErrPrerequisites = errors.New("prerequisites for driver not satisfied (wrong filesystem?)") ErrIncompatibleFS = fmt.Errorf("backing file system is unsupported for this graph driver") ) type InitFunc func(root string, options []string) (Driver, error) // ProtoDriver defines the basic capabilities of a driver. // This interface exists solely to be a minimum set of methods // for client code which choose not to implement the entire Driver // interface and use the NaiveDiffDriver wrapper constructor. // // Use of ProtoDriver directly by client code is not recommended. type ProtoDriver interface { // String returns a string representation of this driver. String() string // Create creates a new, empty, filesystem layer with the // specified id and parent. Parent may be "". Create(id, parent string) error // Remove attempts to remove the filesystem layer with this id. Remove(id string) error // Get returns the mountpoint for the layered filesystem referred // to by this id. You can optionally specify a mountLabel or "". // Returns the absolute path to the mounted layered filesystem. Get(id, mountLabel string) (dir string, err error) // Put releases the system resources for the specified id, // e.g, unmounting layered filesystem. Put(id string) error // Exists returns whether a filesystem layer with the specified // ID exists on this driver. Exists(id string) bool // Status returns a set of key-value pairs which give low // level diagnostic status about this driver. Status() [][2]string // Returns a set of key-value pairs which give low level information // about the image/container driver is managing. GetMetadata(id string) (map[string]string, error) // Cleanup performs necessary tasks to release resources // held by the driver, e.g., unmounting all layered filesystems // known to this driver. Cleanup() error } // Driver is the interface for layered/snapshot file system drivers. type Driver interface { ProtoDriver // Diff produces an archive of the changes between the specified // layer and its parent layer which may be "". Diff(id, parent string) (archive.Archive, error) // Changes produces a list of changes between the specified layer // and its parent layer. If parent is "", then all changes will be ADD changes. Changes(id, parent string) ([]archive.Change, error) // ApplyDiff extracts the changeset from the given diff into the // layer with the specified id and parent, returning the size of the // new layer in bytes. ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error) // DiffSize calculates the changes between the specified id // and its parent and returns the size in bytes of the changes // relative to its base filesystem directory. DiffSize(id, parent string) (size int64, err error) } func init() { drivers = make(map[string]InitFunc) } func Register(name string, initFunc InitFunc) error { if _, exists := drivers[name]; exists { return fmt.Errorf("Name already registered %s", name) } drivers[name] = initFunc return nil } func GetDriver(name, home string, options []string) (Driver, error) { if initFunc, exists := drivers[name]; exists { return initFunc(filepath.Join(home, name), options) } logrus.Errorf("Failed to GetDriver graph %s %s", name, home) return nil, ErrNotSupported } func New(root string, options []string) (driver Driver, err error) { for _, name := range []string{os.Getenv("DOCKER_DRIVER"), DefaultDriver} { if name != "" { logrus.Debugf("[graphdriver] trying provided driver %q", name) // so the logs show specified driver return GetDriver(name, root, options) } } // Guess for prior driver priorDrivers := scanPriorDrivers(root) for _, name := range priority { if name == "vfs" { // don't use vfs even if there is state present. continue } for _, prior := range priorDrivers { // of the state found from prior drivers, check in order of our priority // which we would prefer if prior == name { driver, err = GetDriver(name, root, options) if err != nil { // unlike below, we will return error here, because there is prior // state, and now it is no longer supported/prereq/compatible, so // something changed and needs attention. Otherwise the daemon's // images would just "disappear". logrus.Errorf("[graphdriver] prior storage driver %q failed: %s", name, err) return nil, err } if err := checkPriorDriver(name, root); err != nil { return nil, err } logrus.Infof("[graphdriver] using prior storage driver %q", name) return driver, nil } } } // Check for priority drivers first for _, name := range priority { driver, err = GetDriver(name, root, options) if err != nil { if err == ErrNotSupported || err == ErrPrerequisites || err == ErrIncompatibleFS { continue } return nil, err } return driver, nil } // Check all registered drivers if no priority driver is found for _, initFunc := range drivers { if driver, err = initFunc(root, options); err != nil { if err == ErrNotSupported || err == ErrPrerequisites || err == ErrIncompatibleFS { continue } return nil, err } return driver, nil } return nil, fmt.Errorf("No supported storage backend found") } // scanPriorDrivers returns an un-ordered scan of directories of prior storage drivers func scanPriorDrivers(root string) []string { priorDrivers := []string{} for driver := range drivers { p := filepath.Join(root, driver) if _, err := os.Stat(p); err == nil && driver != "vfs" { priorDrivers = append(priorDrivers, driver) } } return priorDrivers } func checkPriorDriver(name, root string) error { priorDrivers := []string{} for _, prior := range scanPriorDrivers(root) { if prior != name && prior != "vfs" { if _, err := os.Stat(filepath.Join(root, prior)); err == nil { priorDrivers = append(priorDrivers, prior) } } } if len(priorDrivers) > 0 { return errors.New(fmt.Sprintf("%q contains other graphdrivers: %s; Please cleanup or explicitly choose storage driver (-s )", root, strings.Join(priorDrivers, ","))) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/driver_linux.go ================================================ // +build linux package graphdriver import ( "path/filepath" "syscall" ) const ( FsMagicAufs = FsMagic(0x61756673) FsMagicBtrfs = FsMagic(0x9123683E) FsMagicCramfs = FsMagic(0x28cd3d45) FsMagicExtfs = FsMagic(0x0000EF53) FsMagicF2fs = FsMagic(0xF2F52010) FsMagicJffs2Fs = FsMagic(0x000072b6) FsMagicJfs = FsMagic(0x3153464a) FsMagicNfsFs = FsMagic(0x00006969) FsMagicRamFs = FsMagic(0x858458f6) FsMagicReiserFs = FsMagic(0x52654973) FsMagicSmbFs = FsMagic(0x0000517B) FsMagicSquashFs = FsMagic(0x73717368) FsMagicTmpFs = FsMagic(0x01021994) FsMagicXfs = FsMagic(0x58465342) FsMagicZfs = FsMagic(0x2fc12fc1) ) var ( // Slice of drivers that should be used in an order priority = []string{ "aufs", "btrfs", "zfs", "devicemapper", "overlay", "vfs", } FsNames = map[FsMagic]string{ FsMagicAufs: "aufs", FsMagicBtrfs: "btrfs", FsMagicCramfs: "cramfs", FsMagicExtfs: "extfs", FsMagicF2fs: "f2fs", FsMagicJffs2Fs: "jffs2", FsMagicJfs: "jfs", FsMagicNfsFs: "nfs", FsMagicRamFs: "ramfs", FsMagicReiserFs: "reiserfs", FsMagicSmbFs: "smb", FsMagicSquashFs: "squashfs", FsMagicTmpFs: "tmpfs", FsMagicUnsupported: "unsupported", FsMagicXfs: "xfs", FsMagicZfs: "zfs", } ) func GetFSMagic(rootpath string) (FsMagic, error) { var buf syscall.Statfs_t if err := syscall.Statfs(filepath.Dir(rootpath), &buf); err != nil { return 0, err } return FsMagic(buf.Type), nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/driver_unsupported.go ================================================ // +build !linux,!windows package graphdriver var ( // Slice of drivers that should be used in an order priority = []string{ "unsupported", } ) func GetFSMagic(rootpath string) (FsMagic, error) { return FsMagicUnsupported, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/driver_windows.go ================================================ package graphdriver import ( "github.com/docker/docker/pkg/archive" "github.com/microsoft/hcsshim" ) type WindowsGraphDriver interface { Driver CopyDiff(id, sourceId string, parentLayerPaths []string) error LayerIdsToPaths(ids []string) []string Info() hcsshim.DriverInfo Export(id string, parentLayerPaths []string) (archive.Archive, error) Import(id string, layerData archive.ArchiveReader, parentLayerPaths []string) (int64, error) } var ( // Slice of drivers that should be used in order priority = []string{ "windowsfilter", "windowsdiff", "vfs", } ) func GetFSMagic(rootpath string) (FsMagic, error) { // Note it is OK to return FsMagicUnsupported on Windows. return FsMagicUnsupported, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/fsdiff.go ================================================ // +build daemon package graphdriver import ( "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/ioutils" ) // naiveDiffDriver takes a ProtoDriver and adds the // capability of the Diffing methods which it may or may not // support on its own. See the comment on the exported // NaiveDiffDriver function below. // Notably, the AUFS driver doesn't need to be wrapped like this. type naiveDiffDriver struct { ProtoDriver } // NaiveDiffDriver returns a fully functional driver that wraps the // given ProtoDriver and adds the capability of the following methods which // it may or may not support on its own: // Diff(id, parent string) (archive.Archive, error) // Changes(id, parent string) ([]archive.Change, error) // ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error) // DiffSize(id, parent string) (size int64, err error) func NaiveDiffDriver(driver ProtoDriver) Driver { return &naiveDiffDriver{ProtoDriver: driver} } // Diff produces an archive of the changes between the specified // layer and its parent layer which may be "". func (gdw *naiveDiffDriver) Diff(id, parent string) (arch archive.Archive, err error) { driver := gdw.ProtoDriver layerFs, err := driver.Get(id, "") if err != nil { return nil, err } defer func() { if err != nil { driver.Put(id) } }() if parent == "" { archive, err := archive.Tar(layerFs, archive.Uncompressed) if err != nil { return nil, err } return ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() driver.Put(id) return err }), nil } parentFs, err := driver.Get(parent, "") if err != nil { return nil, err } defer driver.Put(parent) changes, err := archive.ChangesDirs(layerFs, parentFs) if err != nil { return nil, err } archive, err := archive.ExportChanges(layerFs, changes) if err != nil { return nil, err } return ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() driver.Put(id) return err }), nil } // Changes produces a list of changes between the specified layer // and its parent layer. If parent is "", then all changes will be ADD changes. func (gdw *naiveDiffDriver) Changes(id, parent string) ([]archive.Change, error) { driver := gdw.ProtoDriver layerFs, err := driver.Get(id, "") if err != nil { return nil, err } defer driver.Put(id) parentFs := "" if parent != "" { parentFs, err = driver.Get(parent, "") if err != nil { return nil, err } defer driver.Put(parent) } return archive.ChangesDirs(layerFs, parentFs) } // ApplyDiff extracts the changeset from the given diff into the // layer with the specified id and parent, returning the size of the // new layer in bytes. func (gdw *naiveDiffDriver) ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error) { driver := gdw.ProtoDriver // Mount the root filesystem so we can apply the diff/layer. layerFs, err := driver.Get(id, "") if err != nil { return } defer driver.Put(id) start := time.Now().UTC() logrus.Debugf("Start untar layer") if size, err = chrootarchive.ApplyLayer(layerFs, diff); err != nil { return } logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds()) return } // DiffSize calculates the changes between the specified layer // and its parent and returns the size in bytes of the changes // relative to its base filesystem directory. func (gdw *naiveDiffDriver) DiffSize(id, parent string) (size int64, err error) { driver := gdw.ProtoDriver changes, err := gdw.Changes(id, parent) if err != nil { return } layerFs, err := driver.Get(id, "") if err != nil { return } defer driver.Put(id) return archive.ChangesSize(layerFs, changes), nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/graphtest/graphtest.go ================================================ package graphtest import ( "fmt" "io/ioutil" "os" "path" "syscall" "testing" "github.com/docker/docker/daemon/graphdriver" ) var ( drv *Driver ) type Driver struct { graphdriver.Driver root string refCount int } // InitLoopbacks ensures that the loopback devices are properly created within // the system running the device mapper tests. func InitLoopbacks() error { statT, err := getBaseLoopStats() if err != nil { return err } // create atleast 8 loopback files, ya, that is a good number for i := 0; i < 8; i++ { loopPath := fmt.Sprintf("/dev/loop%d", i) // only create new loopback files if they don't exist if _, err := os.Stat(loopPath); err != nil { if mkerr := syscall.Mknod(loopPath, uint32(statT.Mode|syscall.S_IFBLK), int((7<<8)|(i&0xff)|((i&0xfff00)<<12))); mkerr != nil { return mkerr } os.Chown(loopPath, int(statT.Uid), int(statT.Gid)) } } return nil } // getBaseLoopStats inspects /dev/loop0 to collect uid,gid, and mode for the // loop0 device on the system. If it does not exist we assume 0,0,0660 for the // stat data func getBaseLoopStats() (*syscall.Stat_t, error) { loop0, err := os.Stat("/dev/loop0") if err != nil { if os.IsNotExist(err) { return &syscall.Stat_t{ Uid: 0, Gid: 0, Mode: 0660, }, nil } return nil, err } return loop0.Sys().(*syscall.Stat_t), nil } func newDriver(t *testing.T, name string) *Driver { root, err := ioutil.TempDir("/var/tmp", "docker-graphtest-") if err != nil { t.Fatal(err) } if err := os.MkdirAll(root, 0755); err != nil { t.Fatal(err) } d, err := graphdriver.GetDriver(name, root, nil) if err != nil { t.Logf("graphdriver: %v\n", err) if err == graphdriver.ErrNotSupported || err == graphdriver.ErrPrerequisites || err == graphdriver.ErrIncompatibleFS { t.Skipf("Driver %s not supported", name) } t.Fatal(err) } return &Driver{d, root, 1} } func cleanup(t *testing.T, d *Driver) { if err := drv.Cleanup(); err != nil { t.Fatal(err) } os.RemoveAll(d.root) } func GetDriver(t *testing.T, name string) graphdriver.Driver { if drv == nil { drv = newDriver(t, name) } else { drv.refCount++ } return drv } func PutDriver(t *testing.T) { if drv == nil { t.Skip("No driver to put!") } drv.refCount-- if drv.refCount == 0 { cleanup(t, drv) drv = nil } } func verifyFile(t *testing.T, path string, mode os.FileMode, uid, gid uint32) { fi, err := os.Stat(path) if err != nil { t.Fatal(err) } if fi.Mode()&os.ModeType != mode&os.ModeType { t.Fatalf("Expected %s type 0x%x, got 0x%x", path, mode&os.ModeType, fi.Mode()&os.ModeType) } if fi.Mode()&os.ModePerm != mode&os.ModePerm { t.Fatalf("Expected %s mode %o, got %o", path, mode&os.ModePerm, fi.Mode()&os.ModePerm) } if fi.Mode()&os.ModeSticky != mode&os.ModeSticky { t.Fatalf("Expected %s sticky 0x%x, got 0x%x", path, mode&os.ModeSticky, fi.Mode()&os.ModeSticky) } if fi.Mode()&os.ModeSetuid != mode&os.ModeSetuid { t.Fatalf("Expected %s setuid 0x%x, got 0x%x", path, mode&os.ModeSetuid, fi.Mode()&os.ModeSetuid) } if fi.Mode()&os.ModeSetgid != mode&os.ModeSetgid { t.Fatalf("Expected %s setgid 0x%x, got 0x%x", path, mode&os.ModeSetgid, fi.Mode()&os.ModeSetgid) } if stat, ok := fi.Sys().(*syscall.Stat_t); ok { if stat.Uid != uid { t.Fatalf("%s no owned by uid %d", path, uid) } if stat.Gid != gid { t.Fatalf("%s not owned by gid %d", path, gid) } } } // Creates an new image and verifies it is empty and the right metadata func DriverTestCreateEmpty(t *testing.T, drivername string) { driver := GetDriver(t, drivername) defer PutDriver(t) if err := driver.Create("empty", ""); err != nil { t.Fatal(err) } if !driver.Exists("empty") { t.Fatal("Newly created image doesn't exist") } dir, err := driver.Get("empty", "") if err != nil { t.Fatal(err) } verifyFile(t, dir, 0755|os.ModeDir, 0, 0) // Verify that the directory is empty fis, err := ioutil.ReadDir(dir) if err != nil { t.Fatal(err) } if len(fis) != 0 { t.Fatal("New directory not empty") } driver.Put("empty") if err := driver.Remove("empty"); err != nil { t.Fatal(err) } } func createBase(t *testing.T, driver graphdriver.Driver, name string) { // We need to be able to set any perms oldmask := syscall.Umask(0) defer syscall.Umask(oldmask) if err := driver.Create(name, ""); err != nil { t.Fatal(err) } dir, err := driver.Get(name, "") if err != nil { t.Fatal(err) } defer driver.Put(name) subdir := path.Join(dir, "a subdir") if err := os.Mkdir(subdir, 0705|os.ModeSticky); err != nil { t.Fatal(err) } if err := os.Chown(subdir, 1, 2); err != nil { t.Fatal(err) } file := path.Join(dir, "a file") if err := ioutil.WriteFile(file, []byte("Some data"), 0222|os.ModeSetuid); err != nil { t.Fatal(err) } } func verifyBase(t *testing.T, driver graphdriver.Driver, name string) { dir, err := driver.Get(name, "") if err != nil { t.Fatal(err) } defer driver.Put(name) subdir := path.Join(dir, "a subdir") verifyFile(t, subdir, 0705|os.ModeDir|os.ModeSticky, 1, 2) file := path.Join(dir, "a file") verifyFile(t, file, 0222|os.ModeSetuid, 0, 0) fis, err := ioutil.ReadDir(dir) if err != nil { t.Fatal(err) } if len(fis) != 2 { t.Fatal("Unexpected files in base image") } } func DriverTestCreateBase(t *testing.T, drivername string) { driver := GetDriver(t, drivername) defer PutDriver(t) createBase(t, driver, "Base") verifyBase(t, driver, "Base") if err := driver.Remove("Base"); err != nil { t.Fatal(err) } } func DriverTestCreateSnap(t *testing.T, drivername string) { driver := GetDriver(t, drivername) defer PutDriver(t) createBase(t, driver, "Base") if err := driver.Create("Snap", "Base"); err != nil { t.Fatal(err) } verifyBase(t, driver, "Snap") if err := driver.Remove("Snap"); err != nil { t.Fatal(err) } if err := driver.Remove("Base"); err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/overlay/copy.go ================================================ // +build linux package overlay import ( "fmt" "io" "os" "path/filepath" "syscall" "github.com/docker/docker/pkg/system" ) type CopyFlags int const ( CopyHardlink CopyFlags = 1 << iota ) func copyRegular(srcPath, dstPath string, mode os.FileMode) error { srcFile, err := os.Open(srcPath) if err != nil { return err } defer srcFile.Close() dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE, mode) if err != nil { return err } defer dstFile.Close() _, err = io.Copy(dstFile, srcFile) return err } func copyXattr(srcPath, dstPath, attr string) error { data, err := system.Lgetxattr(srcPath, attr) if err != nil { return err } if data != nil { if err := system.Lsetxattr(dstPath, attr, data, 0); err != nil { return err } } return nil } func copyDir(srcDir, dstDir string, flags CopyFlags) error { err := filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path relPath, err := filepath.Rel(srcDir, srcPath) if err != nil { return err } dstPath := filepath.Join(dstDir, relPath) if err != nil { return err } stat, ok := f.Sys().(*syscall.Stat_t) if !ok { return fmt.Errorf("Unable to get raw syscall.Stat_t data for %s", srcPath) } isHardlink := false switch f.Mode() & os.ModeType { case 0: // Regular file if flags&CopyHardlink != 0 { isHardlink = true if err := os.Link(srcPath, dstPath); err != nil { return err } } else { if err := copyRegular(srcPath, dstPath, f.Mode()); err != nil { return err } } case os.ModeDir: if err := os.Mkdir(dstPath, f.Mode()); err != nil && !os.IsExist(err) { return err } case os.ModeSymlink: link, err := os.Readlink(srcPath) if err != nil { return err } if err := os.Symlink(link, dstPath); err != nil { return err } case os.ModeNamedPipe: fallthrough case os.ModeSocket: if err := syscall.Mkfifo(dstPath, stat.Mode); err != nil { return err } case os.ModeDevice: if err := syscall.Mknod(dstPath, stat.Mode, int(stat.Rdev)); err != nil { return err } default: return fmt.Errorf("Unknown file type for %s\n", srcPath) } // Everything below is copying metadata from src to dst. All this metadata // already shares an inode for hardlinks. if isHardlink { return nil } if err := os.Lchown(dstPath, int(stat.Uid), int(stat.Gid)); err != nil { return err } if err := copyXattr(srcPath, dstPath, "security.capability"); err != nil { return err } // We need to copy this attribute if it appears in an overlay upper layer, as // this function is used to copy those. It is set by overlay if a directory // is removed and then re-created and should not inherit anything from the // same dir in the lower dir. if err := copyXattr(srcPath, dstPath, "trusted.overlay.opaque"); err != nil { return err } isSymlink := f.Mode()&os.ModeSymlink != 0 // There is no LChmod, so ignore mode for symlink. Also, this // must happen after chown, as that can modify the file mode if !isSymlink { if err := os.Chmod(dstPath, f.Mode()); err != nil { return err } } ts := []syscall.Timespec{stat.Atim, stat.Mtim} // syscall.UtimesNano doesn't support a NOFOLLOW flag atm, and if !isSymlink { if err := system.UtimesNano(dstPath, ts); err != nil { return err } } else { if err := system.LUtimesNano(dstPath, ts); err != nil { return err } } return nil }) return err } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/overlay/overlay.go ================================================ // +build linux package overlay import ( "bufio" "fmt" "io/ioutil" "os" "os/exec" "path" "sync" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/opencontainers/runc/libcontainer/label" ) // This is a small wrapper over the NaiveDiffWriter that lets us have a custom // implementation of ApplyDiff() var ( ErrApplyDiffFallback = fmt.Errorf("Fall back to normal ApplyDiff") ) type ApplyDiffProtoDriver interface { graphdriver.ProtoDriver ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error) } type naiveDiffDriverWithApply struct { graphdriver.Driver applyDiff ApplyDiffProtoDriver } func NaiveDiffDriverWithApply(driver ApplyDiffProtoDriver) graphdriver.Driver { return &naiveDiffDriverWithApply{ Driver: graphdriver.NaiveDiffDriver(driver), applyDiff: driver, } } func (d *naiveDiffDriverWithApply) ApplyDiff(id, parent string, diff archive.ArchiveReader) (int64, error) { b, err := d.applyDiff.ApplyDiff(id, parent, diff) if err == ErrApplyDiffFallback { return d.Driver.ApplyDiff(id, parent, diff) } return b, err } // This backend uses the overlay union filesystem for containers // plus hard link file sharing for images. // Each container/image can have a "root" subdirectory which is a plain // filesystem hierarchy, or they can use overlay. // If they use overlay there is a "upper" directory and a "lower-id" // file, as well as "merged" and "work" directories. The "upper" // directory has the upper layer of the overlay, and "lower-id" contains // the id of the parent whose "root" directory shall be used as the lower // layer in the overlay. The overlay itself is mounted in the "merged" // directory, and the "work" dir is needed for overlay to work. // When a overlay layer is created there are two cases, either the // parent has a "root" dir, then we start out with a empty "upper" // directory overlaid on the parents root. This is typically the // case with the init layer of a container which is based on an image. // If there is no "root" in the parent, we inherit the lower-id from // the parent and start by making a copy if the parents "upper" dir. // This is typically the case for a container layer which copies // its parent -init upper layer. // Additionally we also have a custom implementation of ApplyLayer // which makes a recursive copy of the parent "root" layer using // hardlinks to share file data, and then applies the layer on top // of that. This means all child images share file (but not directory) // data with the parent. type ActiveMount struct { count int path string mounted bool } type Driver struct { home string sync.Mutex // Protects concurrent modification to active active map[string]*ActiveMount } var backingFs = "" func init() { graphdriver.Register("overlay", Init) } func Init(home string, options []string) (graphdriver.Driver, error) { if err := supportsOverlay(); err != nil { return nil, graphdriver.ErrNotSupported } fsMagic, err := graphdriver.GetFSMagic(home) if err != nil { return nil, err } if fsName, ok := graphdriver.FsNames[fsMagic]; ok { backingFs = fsName } // check if they are running over btrfs or aufs switch fsMagic { case graphdriver.FsMagicBtrfs: logrus.Error("'overlay' is not supported over btrfs.") return nil, graphdriver.ErrIncompatibleFS case graphdriver.FsMagicAufs: logrus.Error("'overlay' is not supported over aufs.") return nil, graphdriver.ErrIncompatibleFS case graphdriver.FsMagicZfs: logrus.Error("'overlay' is not supported over zfs.") return nil, graphdriver.ErrIncompatibleFS } // Create the driver home dir if err := os.MkdirAll(home, 0755); err != nil && !os.IsExist(err) { return nil, err } d := &Driver{ home: home, active: make(map[string]*ActiveMount), } return NaiveDiffDriverWithApply(d), nil } func supportsOverlay() error { // We can try to modprobe overlay first before looking at // proc/filesystems for when overlay is supported exec.Command("modprobe", "overlay").Run() f, err := os.Open("/proc/filesystems") if err != nil { return err } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { if s.Text() == "nodev\toverlay" { return nil } } logrus.Error("'overlay' not found as a supported filesystem on this host. Please ensure kernel is new enough and has overlay support loaded.") return graphdriver.ErrNotSupported } func (d *Driver) String() string { return "overlay" } func (d *Driver) Status() [][2]string { return [][2]string{ {"Backing Filesystem", backingFs}, } } func (d *Driver) GetMetadata(id string) (map[string]string, error) { dir := d.dir(id) if _, err := os.Stat(dir); err != nil { return nil, err } metadata := make(map[string]string) // If id has a root, it is an image rootDir := path.Join(dir, "root") if _, err := os.Stat(rootDir); err == nil { metadata["RootDir"] = rootDir return metadata, nil } lowerId, err := ioutil.ReadFile(path.Join(dir, "lower-id")) if err != nil { return nil, err } metadata["LowerDir"] = path.Join(d.dir(string(lowerId)), "root") metadata["UpperDir"] = path.Join(dir, "upper") metadata["WorkDir"] = path.Join(dir, "work") metadata["MergedDir"] = path.Join(dir, "merged") return metadata, nil } func (d *Driver) Cleanup() error { return nil } func (d *Driver) Create(id string, parent string) (retErr error) { dir := d.dir(id) if err := os.MkdirAll(path.Dir(dir), 0700); err != nil { return err } if err := os.Mkdir(dir, 0700); err != nil { return err } defer func() { // Clean up on failure if retErr != nil { os.RemoveAll(dir) } }() // Toplevel images are just a "root" dir if parent == "" { if err := os.Mkdir(path.Join(dir, "root"), 0755); err != nil { return err } return nil } parentDir := d.dir(parent) // Ensure parent exists if _, err := os.Lstat(parentDir); err != nil { return err } // If parent has a root, just do a overlay to it parentRoot := path.Join(parentDir, "root") if s, err := os.Lstat(parentRoot); err == nil { if err := os.Mkdir(path.Join(dir, "upper"), s.Mode()); err != nil { return err } if err := os.Mkdir(path.Join(dir, "work"), 0700); err != nil { return err } if err := os.Mkdir(path.Join(dir, "merged"), 0700); err != nil { return err } if err := ioutil.WriteFile(path.Join(dir, "lower-id"), []byte(parent), 0666); err != nil { return err } return nil } // Otherwise, copy the upper and the lower-id from the parent lowerId, err := ioutil.ReadFile(path.Join(parentDir, "lower-id")) if err != nil { return err } if err := ioutil.WriteFile(path.Join(dir, "lower-id"), lowerId, 0666); err != nil { return err } parentUpperDir := path.Join(parentDir, "upper") s, err := os.Lstat(parentUpperDir) if err != nil { return err } upperDir := path.Join(dir, "upper") if err := os.Mkdir(upperDir, s.Mode()); err != nil { return err } if err := os.Mkdir(path.Join(dir, "work"), 0700); err != nil { return err } if err := os.Mkdir(path.Join(dir, "merged"), 0700); err != nil { return err } return copyDir(parentUpperDir, upperDir, 0) } func (d *Driver) dir(id string) string { return path.Join(d.home, id) } func (d *Driver) Remove(id string) error { dir := d.dir(id) if _, err := os.Stat(dir); err != nil { return err } return os.RemoveAll(dir) } func (d *Driver) Get(id string, mountLabel string) (string, error) { // Protect the d.active from concurrent access d.Lock() defer d.Unlock() mount := d.active[id] if mount != nil { mount.count++ return mount.path, nil } mount = &ActiveMount{count: 1} dir := d.dir(id) if _, err := os.Stat(dir); err != nil { return "", err } // If id has a root, just return it rootDir := path.Join(dir, "root") if _, err := os.Stat(rootDir); err == nil { mount.path = rootDir d.active[id] = mount return mount.path, nil } lowerId, err := ioutil.ReadFile(path.Join(dir, "lower-id")) if err != nil { return "", err } lowerDir := path.Join(d.dir(string(lowerId)), "root") upperDir := path.Join(dir, "upper") workDir := path.Join(dir, "work") mergedDir := path.Join(dir, "merged") opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lowerDir, upperDir, workDir) if err := syscall.Mount("overlay", mergedDir, "overlay", 0, label.FormatMountLabel(opts, mountLabel)); err != nil { return "", fmt.Errorf("error creating overlay mount to %s: %v", mergedDir, err) } mount.path = mergedDir mount.mounted = true d.active[id] = mount return mount.path, nil } func (d *Driver) Put(id string) error { // Protect the d.active from concurrent access d.Lock() defer d.Unlock() mount := d.active[id] if mount == nil { logrus.Debugf("Put on a non-mounted device %s", id) // but it might be still here if d.Exists(id) { mergedDir := path.Join(d.dir(id), "merged") err := syscall.Unmount(mergedDir, 0) if err != nil { logrus.Debugf("Failed to unmount %s overlay: %v", id, err) } } return nil } mount.count-- if mount.count > 0 { return nil } defer delete(d.active, id) if mount.mounted { err := syscall.Unmount(mount.path, 0) if err != nil { logrus.Debugf("Failed to unmount %s overlay: %v", id, err) } return err } return nil } func (d *Driver) ApplyDiff(id string, parent string, diff archive.ArchiveReader) (size int64, err error) { dir := d.dir(id) if parent == "" { return 0, ErrApplyDiffFallback } parentRootDir := path.Join(d.dir(parent), "root") if _, err := os.Stat(parentRootDir); err != nil { return 0, ErrApplyDiffFallback } // We now know there is a parent, and it has a "root" directory containing // the full root filesystem. We can just hardlink it and apply the // layer. This relies on two things: // 1) ApplyDiff is only run once on a clean (no writes to upper layer) container // 2) ApplyDiff doesn't do any in-place writes to files (would break hardlinks) // These are all currently true and are not expected to break tmpRootDir, err := ioutil.TempDir(dir, "tmproot") if err != nil { return 0, err } defer func() { if err != nil { os.RemoveAll(tmpRootDir) } else { os.RemoveAll(path.Join(dir, "upper")) os.RemoveAll(path.Join(dir, "work")) os.RemoveAll(path.Join(dir, "merged")) os.RemoveAll(path.Join(dir, "lower-id")) } }() if err = copyDir(parentRootDir, tmpRootDir, CopyHardlink); err != nil { return 0, err } if size, err = chrootarchive.ApplyLayer(tmpRootDir, diff); err != nil { return 0, err } rootDir := path.Join(dir, "root") if err := os.Rename(tmpRootDir, rootDir); err != nil { return 0, err } return } func (d *Driver) Exists(id string) bool { _, err := os.Stat(d.dir(id)) return err == nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/overlay/overlay_test.go ================================================ // +build linux package overlay import ( "github.com/docker/docker/daemon/graphdriver/graphtest" "testing" ) // This avoids creating a new driver for each test if all tests are run // Make sure to put new tests between TestOverlaySetup and TestOverlayTeardown func TestOverlaySetup(t *testing.T) { graphtest.GetDriver(t, "overlay") } func TestOverlayCreateEmpty(t *testing.T) { graphtest.DriverTestCreateEmpty(t, "overlay") } func TestOverlayCreateBase(t *testing.T) { graphtest.DriverTestCreateBase(t, "overlay") } func TestOverlayCreateSnap(t *testing.T) { graphtest.DriverTestCreateSnap(t, "overlay") } func TestOverlayTeardown(t *testing.T) { graphtest.PutDriver(t) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/overlay/overlay_unsupported.go ================================================ // +build !linux package overlay ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/vfs/driver.go ================================================ // +build linux windows package vfs import ( "fmt" "os" "path/filepath" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/system" "github.com/opencontainers/runc/libcontainer/label" ) func init() { graphdriver.Register("vfs", Init) } func Init(home string, options []string) (graphdriver.Driver, error) { d := &Driver{ home: home, } return graphdriver.NaiveDiffDriver(d), nil } type Driver struct { home string } func (d *Driver) String() string { return "vfs" } func (d *Driver) Status() [][2]string { return nil } func (d *Driver) GetMetadata(id string) (map[string]string, error) { return nil, nil } func (d *Driver) Cleanup() error { return nil } func (d *Driver) Create(id, parent string) error { dir := d.dir(id) if err := system.MkdirAll(filepath.Dir(dir), 0700); err != nil { return err } if err := os.Mkdir(dir, 0755); err != nil { return err } opts := []string{"level:s0"} if _, mountLabel, err := label.InitLabels(opts); err == nil { label.SetFileLabel(dir, mountLabel) } if parent == "" { return nil } parentDir, err := d.Get(parent, "") if err != nil { return fmt.Errorf("%s: %s", parent, err) } if err := chrootarchive.CopyWithTar(parentDir, dir); err != nil { return err } return nil } func (d *Driver) dir(id string) string { return filepath.Join(d.home, "dir", filepath.Base(id)) } func (d *Driver) Remove(id string) error { if _, err := os.Stat(d.dir(id)); err != nil { return err } return os.RemoveAll(d.dir(id)) } func (d *Driver) Get(id, mountLabel string) (string, error) { dir := d.dir(id) if st, err := os.Stat(dir); err != nil { return "", err } else if !st.IsDir() { return "", fmt.Errorf("%s: not a directory", dir) } return dir, nil } func (d *Driver) Put(id string) error { // The vfs driver has no runtime resources (e.g. mounts) // to clean up, so we don't need anything here return nil } func (d *Driver) Exists(id string) bool { _, err := os.Stat(d.dir(id)) return err == nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/vfs/driver_unsupported.go ================================================ // +build !linux,!windows package vfs ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/vfs/vfs_test.go ================================================ // +build linux package vfs import ( "testing" "github.com/docker/docker/daemon/graphdriver/graphtest" "github.com/docker/docker/pkg/reexec" ) func init() { reexec.Init() } // This avoids creating a new driver for each test if all tests are run // Make sure to put new tests between TestVfsSetup and TestVfsTeardown func TestVfsSetup(t *testing.T) { graphtest.GetDriver(t, "vfs") } func TestVfsCreateEmpty(t *testing.T) { graphtest.DriverTestCreateEmpty(t, "vfs") } func TestVfsCreateBase(t *testing.T) { graphtest.DriverTestCreateBase(t, "vfs") } func TestVfsCreateSnap(t *testing.T) { graphtest.DriverTestCreateSnap(t, "vfs") } func TestVfsTeardown(t *testing.T) { graphtest.PutDriver(t) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/windows/windows.go ================================================ //+build windows package windows import ( "fmt" "os" "path/filepath" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/ioutils" "github.com/microsoft/hcsshim" ) func init() { graphdriver.Register("windowsfilter", InitFilter) graphdriver.Register("windowsdiff", InitDiff) } const ( diffDriver = iota filterDriver ) type WindowsGraphDriver struct { info hcsshim.DriverInfo sync.Mutex // Protects concurrent modification to active active map[string]int } // New returns a new Windows storage filter driver. func InitFilter(home string, options []string) (graphdriver.Driver, error) { logrus.Debugf("WindowsGraphDriver InitFilter at %s", home) d := &WindowsGraphDriver{ info: hcsshim.DriverInfo{ HomeDir: home, Flavour: filterDriver, }, active: make(map[string]int), } return d, nil } // New returns a new Windows differencing disk driver. func InitDiff(home string, options []string) (graphdriver.Driver, error) { logrus.Debugf("WindowsGraphDriver InitDiff at %s", home) d := &WindowsGraphDriver{ info: hcsshim.DriverInfo{ HomeDir: home, Flavour: diffDriver, }, active: make(map[string]int), } return d, nil } func (d *WindowsGraphDriver) Info() hcsshim.DriverInfo { return d.info } func (d *WindowsGraphDriver) String() string { switch d.info.Flavour { case diffDriver: return "windowsdiff" case filterDriver: return "windowsfilter" default: return "Unknown driver flavour" } } func (d *WindowsGraphDriver) Status() [][2]string { return [][2]string{ {"Windows", ""}, } } // Exists returns true if the given id is registered with // this driver func (d *WindowsGraphDriver) Exists(id string) bool { result, err := hcsshim.LayerExists(d.info, id) if err != nil { return false } return result } func (d *WindowsGraphDriver) Create(id, parent string) error { return hcsshim.CreateLayer(d.info, id, parent) } func (d *WindowsGraphDriver) dir(id string) string { return filepath.Join(d.info.HomeDir, filepath.Base(id)) } // Remove unmounts and removes the dir information func (d *WindowsGraphDriver) Remove(id string) error { return hcsshim.DestroyLayer(d.info, id) } // Get returns the rootfs path for the id. This will mount the dir at it's given path func (d *WindowsGraphDriver) Get(id, mountLabel string) (string, error) { var dir string d.Lock() defer d.Unlock() if d.active[id] == 0 { if err := hcsshim.ActivateLayer(d.info, id); err != nil { return "", err } } mountPath, err := hcsshim.GetLayerMountPath(d.info, id) if err != nil { return "", err } // If the layer has a mount path, use that. Otherwise, use the // folder path. if mountPath != "" { dir = mountPath } else { dir = d.dir(id) } d.active[id]++ return dir, nil } func (d *WindowsGraphDriver) Put(id string) error { logrus.Debugf("WindowsGraphDriver Put() id %s", id) d.Lock() defer d.Unlock() if d.active[id] > 1 { d.active[id]-- } else if d.active[id] == 1 { if err := hcsshim.DeactivateLayer(d.info, id); err != nil { return err } delete(d.active, id) } return nil } func (d *WindowsGraphDriver) Cleanup() error { return nil } // Diff produces an archive of the changes between the specified // layer and its parent layer which may be "". func (d *WindowsGraphDriver) Diff(id, parent string) (arch archive.Archive, err error) { return nil, fmt.Errorf("The Windows graphdriver does not support Diff()") } // Changes produces a list of changes between the specified layer // and its parent layer. If parent is "", then all changes will be ADD changes. func (d *WindowsGraphDriver) Changes(id, parent string) ([]archive.Change, error) { return nil, fmt.Errorf("The Windows graphdriver does not support Changes()") } // ApplyDiff extracts the changeset from the given diff into the // layer with the specified id and parent, returning the size of the // new layer in bytes. func (d *WindowsGraphDriver) ApplyDiff(id, parent string, diff archive.ArchiveReader) (size int64, err error) { start := time.Now().UTC() logrus.Debugf("WindowsGraphDriver ApplyDiff: Start untar layer") destination := d.dir(id) if d.info.Flavour == diffDriver { destination = filepath.Dir(destination) } if size, err = chrootarchive.ApplyLayer(destination, diff); err != nil { return } logrus.Debugf("WindowsGraphDriver ApplyDiff: Untar time: %vs", time.Now().UTC().Sub(start).Seconds()) return } // DiffSize calculates the changes between the specified layer // and its parent and returns the size in bytes of the changes // relative to its base filesystem directory. func (d *WindowsGraphDriver) DiffSize(id, parent string) (size int64, err error) { changes, err := d.Changes(id, parent) if err != nil { return } layerFs, err := d.Get(id, "") if err != nil { return } defer d.Put(id) return archive.ChangesSize(layerFs, changes), nil } func (d *WindowsGraphDriver) CopyDiff(sourceId, id string, parentLayerPaths []string) error { d.Lock() defer d.Unlock() if d.info.Flavour == filterDriver && d.active[sourceId] == 0 { if err := hcsshim.ActivateLayer(d.info, sourceId); err != nil { return err } defer func() { err := hcsshim.DeactivateLayer(d.info, sourceId) if err != nil { logrus.Warnf("Failed to Deactivate %s: %s", sourceId, err) } }() } return hcsshim.CopyLayer(d.info, sourceId, id, parentLayerPaths) } func (d *WindowsGraphDriver) LayerIdsToPaths(ids []string) []string { var paths []string for _, id := range ids { path, err := d.Get(id, "") if err != nil { logrus.Debug("LayerIdsToPaths: Error getting mount path for id", id, ":", err.Error()) return nil } if d.Put(id) != nil { logrus.Debug("LayerIdsToPaths: Error putting mount path for id", id, ":", err.Error()) return nil } paths = append(paths, path) } return paths } func (d *WindowsGraphDriver) GetMetadata(id string) (map[string]string, error) { return nil, nil } func (d *WindowsGraphDriver) Export(id string, parentLayerPaths []string) (arch archive.Archive, err error) { layerFs, err := d.Get(id, "") if err != nil { return } defer func() { if err != nil { d.Put(id) } }() tempFolder := layerFs + "-temp" if err = os.MkdirAll(tempFolder, 0755); err != nil { logrus.Errorf("Could not create %s %s", tempFolder, err) return } defer func() { if err != nil { if err2 := os.RemoveAll(tempFolder); err2 != nil { logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2) } } }() if err = hcsshim.ExportLayer(d.info, id, tempFolder, parentLayerPaths); err != nil { return } archive, err := archive.Tar(tempFolder, archive.Uncompressed) if err != nil { return } return ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() d.Put(id) if err2 := os.RemoveAll(tempFolder); err2 != nil { logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2) } return err }), nil } func (d *WindowsGraphDriver) Import(id string, layerData archive.ArchiveReader, parentLayerPaths []string) (size int64, err error) { layerFs, err := d.Get(id, "") if err != nil { return } defer func() { if err != nil { d.Put(id) } }() tempFolder := layerFs + "-temp" if err = os.MkdirAll(tempFolder, 0755); err != nil { logrus.Errorf("Could not create %s %s", tempFolder, err) return } defer func() { if err2 := os.RemoveAll(tempFolder); err2 != nil { logrus.Warnf("Couldn't clean-up tempFolder: %s %s", tempFolder, err2) } }() start := time.Now().UTC() logrus.Debugf("Start untar layer") if size, err = chrootarchive.ApplyLayer(tempFolder, layerData); err != nil { return } logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds()) if err = hcsshim.ImportLayer(d.info, id, tempFolder, parentLayerPaths); err != nil { return } return } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/zfs/MAINTAINERS ================================================ Jörg Thalheim (@Mic92) Arthur Gautier (@baloose) ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/zfs/zfs.go ================================================ // +build linux package zfs import ( "fmt" "os" "os/exec" "path" "strconv" "strings" "sync" "syscall" "time" log "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/parsers" zfs "github.com/mistifyio/go-zfs" "github.com/opencontainers/runc/libcontainer/label" ) type ZfsOptions struct { fsName string mountPath string } func init() { graphdriver.Register("zfs", Init) } type Logger struct{} func (*Logger) Log(cmd []string) { log.Debugf("[zfs] %s", strings.Join(cmd, " ")) } func Init(base string, opt []string) (graphdriver.Driver, error) { var err error options, err := parseOptions(opt) if err != nil { return nil, err } options.mountPath = base rootdir := path.Dir(base) if options.fsName == "" { err = checkRootdirFs(rootdir) if err != nil { return nil, err } } if _, err := exec.LookPath("zfs"); err != nil { return nil, fmt.Errorf("zfs command is not available: %v", err) } file, err := os.OpenFile("/dev/zfs", os.O_RDWR, 600) if err != nil { return nil, fmt.Errorf("cannot open /dev/zfs: %v", err) } defer file.Close() if options.fsName == "" { options.fsName, err = lookupZfsDataset(rootdir) if err != nil { return nil, err } } zfs.SetLogger(new(Logger)) filesystems, err := zfs.Filesystems(options.fsName) if err != nil { return nil, fmt.Errorf("Cannot find root filesystem %s: %v", options.fsName, err) } filesystemsCache := make(map[string]bool, len(filesystems)) var rootDataset *zfs.Dataset for _, fs := range filesystems { if fs.Name == options.fsName { rootDataset = fs } filesystemsCache[fs.Name] = true } if rootDataset == nil { return nil, fmt.Errorf("BUG: zfs get all -t filesystem -rHp '%s' should contain '%s'", options.fsName, options.fsName) } d := &Driver{ dataset: rootDataset, options: options, filesystemsCache: filesystemsCache, } return graphdriver.NaiveDiffDriver(d), nil } func parseOptions(opt []string) (ZfsOptions, error) { var options ZfsOptions options.fsName = "" for _, option := range opt { key, val, err := parsers.ParseKeyValueOpt(option) if err != nil { return options, err } key = strings.ToLower(key) switch key { case "zfs.fsname": options.fsName = val default: return options, fmt.Errorf("Unknown option %s", key) } } return options, nil } func lookupZfsDataset(rootdir string) (string, error) { var stat syscall.Stat_t if err := syscall.Stat(rootdir, &stat); err != nil { return "", fmt.Errorf("Failed to access '%s': %s", rootdir, err) } wantedDev := stat.Dev mounts, err := mount.GetMounts() if err != nil { return "", err } for _, m := range mounts { if err := syscall.Stat(m.Mountpoint, &stat); err != nil { log.Debugf("[zfs] failed to stat '%s' while scanning for zfs mount: %v", m.Mountpoint, err) continue // may fail on fuse file systems } if stat.Dev == wantedDev && m.Fstype == "zfs" { return m.Source, nil } } return "", fmt.Errorf("Failed to find zfs dataset mounted on '%s' in /proc/mounts", rootdir) } type Driver struct { dataset *zfs.Dataset options ZfsOptions sync.Mutex // protects filesystem cache against concurrent access filesystemsCache map[string]bool } func (d *Driver) String() string { return "zfs" } func (d *Driver) Cleanup() error { return nil } func (d *Driver) Status() [][2]string { parts := strings.Split(d.dataset.Name, "/") pool, err := zfs.GetZpool(parts[0]) var poolName, poolHealth string if err == nil { poolName = pool.Name poolHealth = pool.Health } else { poolName = fmt.Sprintf("error while getting pool information %v", err) poolHealth = "not available" } quota := "no" if d.dataset.Quota != 0 { quota = strconv.FormatUint(d.dataset.Quota, 10) } return [][2]string{ {"Zpool", poolName}, {"Zpool Health", poolHealth}, {"Parent Dataset", d.dataset.Name}, {"Space Used By Parent", strconv.FormatUint(d.dataset.Used, 10)}, {"Space Available", strconv.FormatUint(d.dataset.Avail, 10)}, {"Parent Quota", quota}, {"Compression", d.dataset.Compression}, } } func (d *Driver) GetMetadata(id string) (map[string]string, error) { return nil, nil } func (d *Driver) cloneFilesystem(name, parentName string) error { snapshotName := fmt.Sprintf("%d", time.Now().Nanosecond()) parentDataset := zfs.Dataset{Name: parentName} snapshot, err := parentDataset.Snapshot(snapshotName /*recursive */, false) if err != nil { return err } _, err = snapshot.Clone(name, map[string]string{"mountpoint": "legacy"}) if err == nil { d.Lock() d.filesystemsCache[name] = true d.Unlock() } if err != nil { snapshot.Destroy(zfs.DestroyDeferDeletion) return err } return snapshot.Destroy(zfs.DestroyDeferDeletion) } func (d *Driver) ZfsPath(id string) string { return d.options.fsName + "/" + id } func (d *Driver) MountPath(id string) string { return path.Join(d.options.mountPath, "graph", getMountpoint(id)) } func (d *Driver) Create(id string, parent string) error { err := d.create(id, parent) if err == nil { return nil } if zfsError, ok := err.(*zfs.Error); ok { if !strings.HasSuffix(zfsError.Stderr, "dataset already exists\n") { return err } // aborted build -> cleanup } else { return err } dataset := zfs.Dataset{Name: d.ZfsPath(id)} if err := dataset.Destroy(zfs.DestroyRecursiveClones); err != nil { return err } // retry return d.create(id, parent) } func (d *Driver) create(id, parent string) error { name := d.ZfsPath(id) if parent == "" { mountoptions := map[string]string{"mountpoint": "legacy"} fs, err := zfs.CreateFilesystem(name, mountoptions) if err == nil { d.Lock() d.filesystemsCache[fs.Name] = true d.Unlock() } return err } return d.cloneFilesystem(name, d.ZfsPath(parent)) } func (d *Driver) Remove(id string) error { name := d.ZfsPath(id) dataset := zfs.Dataset{Name: name} err := dataset.Destroy(zfs.DestroyRecursive) if err == nil { d.Lock() delete(d.filesystemsCache, name) d.Unlock() } return err } func (d *Driver) Get(id, mountLabel string) (string, error) { mountpoint := d.MountPath(id) filesystem := d.ZfsPath(id) options := label.FormatMountLabel("", mountLabel) log.Debugf(`[zfs] mount("%s", "%s", "%s")`, filesystem, mountpoint, options) // Create the target directories if they don't exist if err := os.MkdirAll(mountpoint, 0755); err != nil && !os.IsExist(err) { return "", err } err := mount.Mount(filesystem, mountpoint, "zfs", options) if err != nil { return "", fmt.Errorf("error creating zfs mount of %s to %s: %v", filesystem, mountpoint, err) } return mountpoint, nil } func (d *Driver) Put(id string) error { mountpoint := d.MountPath(id) log.Debugf(`[zfs] unmount("%s")`, mountpoint) if err := mount.Unmount(mountpoint); err != nil { return fmt.Errorf("error unmounting to %s: %v", mountpoint, err) } return nil } func (d *Driver) Exists(id string) bool { return d.filesystemsCache[d.ZfsPath(id)] == true } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/zfs/zfs_freebsd.go ================================================ package zfs import ( "fmt" "strings" "syscall" log "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" ) func checkRootdirFs(rootdir string) error { var buf syscall.Statfs_t if err := syscall.Statfs(rootdir, &buf); err != nil { return fmt.Errorf("Failed to access '%s': %s", rootdir, err) } // on FreeBSD buf.Fstypename contains ['z', 'f', 's', 0 ... ] if (buf.Fstypename[0] != 122) || (buf.Fstypename[1] != 102) || (buf.Fstypename[2] != 115) || (buf.Fstypename[3] != 0) { log.Debugf("[zfs] no zfs dataset found for rootdir '%s'", rootdir) return graphdriver.ErrPrerequisites } return nil } func getMountpoint(id string) string { maxlen := 12 // we need to preserve filesystem suffix suffix := strings.SplitN(id, "-", 2) if len(suffix) > 1 { return id[:maxlen] + "-" + suffix[1] } return id[:maxlen] } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/zfs/zfs_linux.go ================================================ package zfs import ( "fmt" "syscall" log "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver" ) func checkRootdirFs(rootdir string) error { var buf syscall.Statfs_t if err := syscall.Statfs(rootdir, &buf); err != nil { return fmt.Errorf("Failed to access '%s': %s", rootdir, err) } if graphdriver.FsMagic(buf.Type) != graphdriver.FsMagicZfs { log.Debugf("[zfs] no zfs dataset found for rootdir '%s'", rootdir) return graphdriver.ErrPrerequisites } return nil } func getMountpoint(id string) string { return id } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/zfs/zfs_test.go ================================================ // +build linux package zfs import ( "github.com/docker/docker/daemon/graphdriver/graphtest" "testing" ) // This avoids creating a new driver for each test if all tests are run // Make sure to put new tests between TestZfsSetup and TestZfsTeardown func TestZfsSetup(t *testing.T) { graphtest.GetDriver(t, "zfs") } func TestZfsCreateEmpty(t *testing.T) { graphtest.DriverTestCreateEmpty(t, "zfs") } func TestZfsCreateBase(t *testing.T) { graphtest.DriverTestCreateBase(t, "zfs") } func TestZfsCreateSnap(t *testing.T) { graphtest.DriverTestCreateSnap(t, "zfs") } func TestZfsTeardown(t *testing.T) { graphtest.PutDriver(t) } ================================================ FILE: vendor/github.com/docker/docker/daemon/graphdriver/zfs/zfs_unsupported.go ================================================ // +build !linux,!freebsd package zfs func checkRootdirFs(rootdir string) error { return nil } func getMountpoint(id string) string { return id } ================================================ FILE: vendor/github.com/docker/docker/daemon/history.go ================================================ package daemon import ( "sort" ) // History is a convenience type for storing a list of containers, // ordered by creation date. type History []*Container func (history *History) Len() int { return len(*history) } func (history *History) Less(i, j int) bool { containers := *history return containers[j].Created.Before(containers[i].Created) } func (history *History) Swap(i, j int) { containers := *history containers[i], containers[j] = containers[j], containers[i] } func (history *History) Add(container *Container) { *history = append(*history, container) } func (history *History) Sort() { sort.Sort(history) } ================================================ FILE: vendor/github.com/docker/docker/daemon/image_delete.go ================================================ package daemon import ( "fmt" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" "github.com/docker/docker/graph" "github.com/docker/docker/image" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/utils" ) // FIXME: remove ImageDelete's dependency on Daemon, then move to graph/ func (daemon *Daemon) ImageDelete(name string, force, noprune bool) ([]types.ImageDelete, error) { list := []types.ImageDelete{} if err := daemon.imgDeleteHelper(name, &list, true, force, noprune); err != nil { return nil, err } if len(list) == 0 { return nil, fmt.Errorf("Conflict, %s wasn't deleted", name) } return list, nil } func (daemon *Daemon) imgDeleteHelper(name string, list *[]types.ImageDelete, first, force, noprune bool) error { var ( repoName, tag string tags = []string{} ) repoAndTags := make(map[string][]string) // FIXME: please respect DRY and centralize repo+tag parsing in a single central place! -- shykes repoName, tag = parsers.ParseRepositoryTag(name) if tag == "" { tag = graph.DEFAULTTAG } if name == "" { return fmt.Errorf("Image name can not be blank") } img, err := daemon.Repositories().LookupImage(name) if err != nil { if r, _ := daemon.Repositories().Get(repoName); r != nil { return fmt.Errorf("No such image: %s", utils.ImageReference(repoName, tag)) } return fmt.Errorf("No such image: %s", name) } if strings.Contains(img.ID, name) { repoName = "" tag = "" } byParents := daemon.Graph().ByParent() repos := daemon.Repositories().ByID()[img.ID] //If delete by id, see if the id belong only to one repository deleteByID := repoName == "" if deleteByID { for _, repoAndTag := range repos { parsedRepo, parsedTag := parsers.ParseRepositoryTag(repoAndTag) if repoName == "" || repoName == parsedRepo { repoName = parsedRepo if parsedTag != "" { repoAndTags[repoName] = append(repoAndTags[repoName], parsedTag) } } else if repoName != parsedRepo && !force && first { // the id belongs to multiple repos, like base:latest and user:test, // in that case return conflict return fmt.Errorf("Conflict, cannot delete image %s because it is tagged in multiple repositories, use -f to force", name) } else { //the id belongs to multiple repos, with -f just delete all repoName = parsedRepo if parsedTag != "" { repoAndTags[repoName] = append(repoAndTags[repoName], parsedTag) } } } } else { repoAndTags[repoName] = append(repoAndTags[repoName], tag) } if !first && len(repoAndTags) > 0 { return nil } if len(repos) <= 1 || (len(repoAndTags) <= 1 && deleteByID) { if err := daemon.canDeleteImage(img.ID, force); err != nil { return err } } // Untag the current image for repoName, tags := range repoAndTags { for _, tag := range tags { tagDeleted, err := daemon.Repositories().Delete(repoName, tag) if err != nil { return err } if tagDeleted { *list = append(*list, types.ImageDelete{ Untagged: utils.ImageReference(repoName, tag), }) daemon.EventsService.Log("untag", img.ID, "") } } } tags = daemon.Repositories().ByID()[img.ID] if (len(tags) <= 1 && repoName == "") || len(tags) == 0 { if len(byParents[img.ID]) == 0 { if err := daemon.Repositories().DeleteAll(img.ID); err != nil { return err } if err := daemon.Graph().Delete(img.ID); err != nil { return err } *list = append(*list, types.ImageDelete{ Deleted: img.ID, }) daemon.EventsService.Log("delete", img.ID, "") if img.Parent != "" && !noprune { err := daemon.imgDeleteHelper(img.Parent, list, false, force, noprune) if first { return err } } } } return nil } func (daemon *Daemon) canDeleteImage(imgID string, force bool) error { if daemon.Graph().IsHeld(imgID) { return fmt.Errorf("Conflict, cannot delete because %s is held by an ongoing pull or build", stringid.TruncateID(imgID)) } for _, container := range daemon.List() { if container.ImageID == "" { // This technically should never happen, but if the container // has no ImageID then log the situation and move on. // If we allowed processing to continue then the code later // on would fail with a "Prefix can't be empty" error even // though the bad container has nothing to do with the image // we're trying to delete. logrus.Errorf("Container %q has no image associated with it!", container.ID) continue } parent, err := daemon.Repositories().LookupImage(container.ImageID) if err != nil { if daemon.Graph().IsNotExist(err, container.ImageID) { continue } return err } if err := daemon.graph.WalkHistory(parent, func(p image.Image) error { if imgID == p.ID { if container.IsRunning() { if force { return fmt.Errorf("Conflict, cannot force delete %s because the running container %s is using it, stop it and retry", stringid.TruncateID(imgID), stringid.TruncateID(container.ID)) } return fmt.Errorf("Conflict, cannot delete %s because the running container %s is using it, stop it and use -f to force", stringid.TruncateID(imgID), stringid.TruncateID(container.ID)) } else if !force { return fmt.Errorf("Conflict, cannot delete %s because the container %s is using it, use -f to force", stringid.TruncateID(imgID), stringid.TruncateID(container.ID)) } } return nil }); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/info.go ================================================ package daemon import ( "os" "runtime" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/parsers/operatingsystem" "github.com/docker/docker/pkg/system" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) func (daemon *Daemon) SystemInfo() (*types.Info, error) { images := daemon.Graph().Map() var imgcount int if images == nil { imgcount = 0 } else { imgcount = len(images) } kernelVersion := "" if kv, err := kernel.GetKernelVersion(); err == nil { kernelVersion = kv.String() } operatingSystem := "" if s, err := operatingsystem.GetOperatingSystem(); err == nil { operatingSystem = s } // Don't do containerized check on Windows if runtime.GOOS != "windows" { if inContainer, err := operatingsystem.IsContainerized(); err != nil { logrus.Errorf("Could not determine if daemon is containerized: %v", err) operatingSystem += " (error determining if containerized)" } else if inContainer { operatingSystem += " (containerized)" } } meminfo, err := system.ReadMemInfo() if err != nil { logrus.Errorf("Could not read system memory info: %v", err) } // if we still have the original dockerinit binary from before we copied it locally, let's return the path to that, since that's more intuitive (the copied path is trivial to derive by hand given VERSION) initPath := utils.DockerInitPath("") if initPath == "" { // if that fails, we'll just return the path from the daemon initPath = daemon.SystemInitPath() } v := &types.Info{ ID: daemon.ID, Containers: len(daemon.List()), Images: imgcount, Driver: daemon.GraphDriver().String(), DriverStatus: daemon.GraphDriver().Status(), IPv4Forwarding: !daemon.SystemConfig().IPv4ForwardingDisabled, BridgeNfIptables: !daemon.SystemConfig().BridgeNfCallIptablesDisabled, BridgeNfIp6tables: !daemon.SystemConfig().BridgeNfCallIp6tablesDisabled, Debug: os.Getenv("DEBUG") != "", NFd: fileutils.GetTotalUsedFds(), NGoroutines: runtime.NumGoroutine(), SystemTime: time.Now().Format(time.RFC3339Nano), ExecutionDriver: daemon.ExecutionDriver().Name(), LoggingDriver: daemon.defaultLogConfig.Type, NEventsListener: daemon.EventsService.SubscribersCount(), KernelVersion: kernelVersion, OperatingSystem: operatingSystem, IndexServerAddress: registry.INDEXSERVER, RegistryConfig: daemon.RegistryService.Config, InitSha1: dockerversion.INITSHA1, InitPath: initPath, NCPU: runtime.NumCPU(), MemTotal: meminfo.MemTotal, DockerRootDir: daemon.Config().Root, Labels: daemon.Config().Labels, ExperimentalBuild: utils.ExperimentalBuild(), } // TODO Windows. Refactor this more once sysinfo is refactored into // platform specific code. On Windows, sysinfo.cgroupMemInfo and // sysinfo.cgroupCpuInfo will be nil otherwise and cause a SIGSEGV if // an attempt is made to access through them. if runtime.GOOS != "windows" { v.MemoryLimit = daemon.SystemConfig().MemoryLimit v.SwapLimit = daemon.SystemConfig().SwapLimit v.OomKillDisable = daemon.SystemConfig().OomKillDisable v.CpuCfsPeriod = daemon.SystemConfig().CpuCfsPeriod v.CpuCfsQuota = daemon.SystemConfig().CpuCfsQuota } if httpProxy := os.Getenv("http_proxy"); httpProxy != "" { v.HttpProxy = httpProxy } if httpsProxy := os.Getenv("https_proxy"); httpsProxy != "" { v.HttpsProxy = httpsProxy } if noProxy := os.Getenv("no_proxy"); noProxy != "" { v.NoProxy = noProxy } if hostname, err := os.Hostname(); err == nil { v.Name = hostname } return v, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/inspect.go ================================================ package daemon import ( "fmt" "github.com/docker/docker/api/types" ) func (daemon *Daemon) ContainerInspect(name string) (*types.ContainerJSON, error) { container, err := daemon.Get(name) if err != nil { return nil, err } container.Lock() defer container.Unlock() base, err := daemon.getInspectData(container) if err != nil { return nil, err } mountPoints := make([]types.MountPoint, 0, len(container.MountPoints)) for _, m := range container.MountPoints { mountPoints = append(mountPoints, types.MountPoint{ Name: m.Name, Source: m.Path(), Destination: m.Destination, Driver: m.Driver, Mode: m.Relabel, RW: m.RW, }) } return &types.ContainerJSON{base, mountPoints, container.Config}, nil } func (daemon *Daemon) ContainerInspectPre120(name string) (*types.ContainerJSONPre120, error) { container, err := daemon.Get(name) if err != nil { return nil, err } container.Lock() defer container.Unlock() base, err := daemon.getInspectData(container) if err != nil { return nil, err } volumes := make(map[string]string) volumesRW := make(map[string]bool) for _, m := range container.MountPoints { volumes[m.Destination] = m.Path() volumesRW[m.Destination] = m.RW } config := &types.ContainerConfig{ container.Config, container.hostConfig.Memory, container.hostConfig.MemorySwap, container.hostConfig.CpuShares, container.hostConfig.CpusetCpus, } return &types.ContainerJSONPre120{base, volumes, volumesRW, config}, nil } func (daemon *Daemon) getInspectData(container *Container) (*types.ContainerJSONBase, error) { // make a copy to play with hostConfig := *container.hostConfig if children, err := daemon.Children(container.Name); err == nil { for linkAlias, child := range children { hostConfig.Links = append(hostConfig.Links, fmt.Sprintf("%s:%s", child.Name, linkAlias)) } } // we need this trick to preserve empty log driver, so // container will use daemon defaults even if daemon change them if hostConfig.LogConfig.Type == "" { hostConfig.LogConfig = daemon.defaultLogConfig } containerState := &types.ContainerState{ Running: container.State.Running, Paused: container.State.Paused, Restarting: container.State.Restarting, OOMKilled: container.State.OOMKilled, Dead: container.State.Dead, Pid: container.State.Pid, ExitCode: container.State.ExitCode, Error: container.State.Error, StartedAt: container.State.StartedAt, FinishedAt: container.State.FinishedAt, } contJSONBase := &types.ContainerJSONBase{ Id: container.ID, Created: container.Created, Path: container.Path, Args: container.Args, State: containerState, Image: container.ImageID, NetworkSettings: container.NetworkSettings, ResolvConfPath: container.ResolvConfPath, HostnamePath: container.HostnamePath, HostsPath: container.HostsPath, LogPath: container.LogPath, Name: container.Name, RestartCount: container.RestartCount, Driver: container.Driver, ExecDriver: container.ExecDriver, MountLabel: container.MountLabel, ProcessLabel: container.ProcessLabel, AppArmorProfile: container.AppArmorProfile, ExecIDs: container.GetExecIDs(), HostConfig: &hostConfig, } contJSONBase.GraphDriver.Name = container.Driver graphDriverData, err := daemon.driver.GetMetadata(container.ID) if err != nil { return nil, err } contJSONBase.GraphDriver.Data = graphDriverData return contJSONBase, nil } func (daemon *Daemon) ContainerExecInspect(id string) (*execConfig, error) { eConfig, err := daemon.getExecConfig(id) if err != nil { return nil, err } return eConfig, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/kill.go ================================================ package daemon import ( "fmt" "syscall" ) // ContainerKill send signal to the container // If no signal is given (sig 0), then Kill with SIGKILL and wait // for the container to exit. // If a signal is given, then just send it to the container and return. func (daemon *Daemon) ContainerKill(name string, sig uint64) error { container, err := daemon.Get(name) if err != nil { return err } // If no signal is passed, or SIGKILL, perform regular Kill (SIGKILL + wait()) if sig == 0 || syscall.Signal(sig) == syscall.SIGKILL { if err := container.Kill(); err != nil { return fmt.Errorf("Cannot kill container %s: %s", name, err) } } else { // Otherwise, just send the requested signal if err := container.KillSig(int(sig)); err != nil { return fmt.Errorf("Cannot kill container %s: %s", name, err) } } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/list.go ================================================ package daemon import ( "errors" "fmt" "strconv" "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/graphdb" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/parsers/filters" ) // List returns an array of all containers registered in the daemon. func (daemon *Daemon) List() []*Container { return daemon.containers.List() } type ContainersConfig struct { All bool Since string Before string Limit int Size bool Filters string } func (daemon *Daemon) Containers(config *ContainersConfig) ([]*types.Container, error) { var ( foundBefore bool displayed int all = config.All n = config.Limit psFilters filters.Args filtExited []int ) containers := []*types.Container{} psFilters, err := filters.FromParam(config.Filters) if err != nil { return nil, err } if i, ok := psFilters["exited"]; ok { for _, value := range i { code, err := strconv.Atoi(value) if err != nil { return nil, err } filtExited = append(filtExited, code) } } if i, ok := psFilters["status"]; ok { for _, value := range i { if !isValidStateString(value) { return nil, errors.New("Unrecognised filter value for status") } if value == "exited" || value == "created" { all = true } } } names := map[string][]string{} daemon.ContainerGraph().Walk("/", func(p string, e *graphdb.Entity) error { names[e.ID()] = append(names[e.ID()], p) return nil }, 1) var beforeCont, sinceCont *Container if config.Before != "" { beforeCont, err = daemon.Get(config.Before) if err != nil { return nil, err } } if config.Since != "" { sinceCont, err = daemon.Get(config.Since) if err != nil { return nil, err } } errLast := errors.New("last container") writeCont := func(container *Container) error { container.Lock() defer container.Unlock() if !container.Running && !all && n <= 0 && config.Since == "" && config.Before == "" { return nil } if !psFilters.Match("name", container.Name) { return nil } if !psFilters.Match("id", container.ID) { return nil } if !psFilters.MatchKVList("label", container.Config.Labels) { return nil } if config.Before != "" && !foundBefore { if container.ID == beforeCont.ID { foundBefore = true } return nil } if n > 0 && displayed == n { return errLast } if config.Since != "" { if container.ID == sinceCont.ID { return errLast } } if len(filtExited) > 0 { shouldSkip := true for _, code := range filtExited { if code == container.ExitCode && !container.Running { shouldSkip = false break } } if shouldSkip { return nil } } if !psFilters.Match("status", container.State.StateString()) { return nil } displayed++ newC := &types.Container{ ID: container.ID, Names: names[container.ID], } newC.Image = container.Config.Image if len(container.Args) > 0 { args := []string{} for _, arg := range container.Args { if strings.Contains(arg, " ") { args = append(args, fmt.Sprintf("'%s'", arg)) } else { args = append(args, arg) } } argsAsString := strings.Join(args, " ") newC.Command = fmt.Sprintf("%s %s", container.Path, argsAsString) } else { newC.Command = fmt.Sprintf("%s", container.Path) } newC.Created = int(container.Created.Unix()) newC.Status = container.State.String() newC.HostConfig.NetworkMode = string(container.HostConfig().NetworkMode) newC.Ports = []types.Port{} for port, bindings := range container.NetworkSettings.Ports { p, err := nat.ParsePort(port.Port()) if err != nil { return err } if len(bindings) == 0 { newC.Ports = append(newC.Ports, types.Port{ PrivatePort: p, Type: port.Proto(), }) continue } for _, binding := range bindings { h, err := nat.ParsePort(binding.HostPort) if err != nil { return err } newC.Ports = append(newC.Ports, types.Port{ PrivatePort: p, PublicPort: h, Type: port.Proto(), IP: binding.HostIP, }) } } if config.Size { sizeRw, sizeRootFs := container.GetSize() newC.SizeRw = int(sizeRw) newC.SizeRootFs = int(sizeRootFs) } newC.Labels = container.Config.Labels containers = append(containers, newC) return nil } for _, container := range daemon.List() { if err := writeCont(container); err != nil { if err != errLast { return nil, err } break } } return containers, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/logdrivers_linux.go ================================================ package daemon // Importing packages here only to make sure their init gets called and // therefore they register themselves to the logdriver factory. import ( _ "github.com/docker/docker/daemon/logger/fluentd" _ "github.com/docker/docker/daemon/logger/gelf" _ "github.com/docker/docker/daemon/logger/journald" _ "github.com/docker/docker/daemon/logger/jsonfilelog" _ "github.com/docker/docker/daemon/logger/syslog" ) ================================================ FILE: vendor/github.com/docker/docker/daemon/logdrivers_windows.go ================================================ package daemon // Importing packages here only to make sure their init gets called and // therefore they register themselves to the logdriver factory. import ( _ "github.com/docker/docker/daemon/logger/jsonfilelog" ) ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/copier.go ================================================ package logger import ( "bufio" "bytes" "io" "sync" "time" "github.com/Sirupsen/logrus" ) // Copier can copy logs from specified sources to Logger and attach // ContainerID and Timestamp. // Writes are concurrent, so you need implement some sync in your logger type Copier struct { // cid is container id for which we copying logs cid string // srcs is map of name -> reader pairs, for example "stdout", "stderr" srcs map[string]io.Reader dst Logger copyJobs sync.WaitGroup } // NewCopier creates new Copier func NewCopier(cid string, srcs map[string]io.Reader, dst Logger) (*Copier, error) { return &Copier{ cid: cid, srcs: srcs, dst: dst, }, nil } // Run starts logs copying func (c *Copier) Run() { for src, w := range c.srcs { c.copyJobs.Add(1) go c.copySrc(src, w) } } func (c *Copier) copySrc(name string, src io.Reader) { defer c.copyJobs.Done() reader := bufio.NewReader(src) for { line, err := reader.ReadBytes('\n') line = bytes.TrimSuffix(line, []byte{'\n'}) // ReadBytes can return full or partial output even when it failed. // e.g. it can return a full entry and EOF. if err == nil || len(line) > 0 { if logErr := c.dst.Log(&Message{ContainerID: c.cid, Line: line, Source: name, Timestamp: time.Now().UTC()}); logErr != nil { logrus.Errorf("Failed to log msg %q for logger %s: %s", line, c.dst.Name(), logErr) } } if err != nil { if err != io.EOF { logrus.Errorf("Error scanning log stream: %s", err) } return } } } // Wait waits until all copying is done func (c *Copier) Wait() { c.copyJobs.Wait() } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/copier_test.go ================================================ package logger import ( "bytes" "encoding/json" "io" "testing" "time" ) type TestLoggerJSON struct { *json.Encoder } func (l *TestLoggerJSON) Log(m *Message) error { return l.Encode(m) } func (l *TestLoggerJSON) Close() error { return nil } func (l *TestLoggerJSON) Name() string { return "json" } type TestLoggerText struct { *bytes.Buffer } func (l *TestLoggerText) Log(m *Message) error { _, err := l.WriteString(m.ContainerID + " " + m.Source + " " + string(m.Line) + "\n") return err } func (l *TestLoggerText) Close() error { return nil } func (l *TestLoggerText) Name() string { return "text" } func TestCopier(t *testing.T) { stdoutLine := "Line that thinks that it is log line from docker stdout" stderrLine := "Line that thinks that it is log line from docker stderr" var stdout bytes.Buffer var stderr bytes.Buffer for i := 0; i < 30; i++ { if _, err := stdout.WriteString(stdoutLine + "\n"); err != nil { t.Fatal(err) } if _, err := stderr.WriteString(stderrLine + "\n"); err != nil { t.Fatal(err) } } var jsonBuf bytes.Buffer jsonLog := &TestLoggerJSON{Encoder: json.NewEncoder(&jsonBuf)} cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" c, err := NewCopier(cid, map[string]io.Reader{ "stdout": &stdout, "stderr": &stderr, }, jsonLog) if err != nil { t.Fatal(err) } c.Run() wait := make(chan struct{}) go func() { c.Wait() close(wait) }() select { case <-time.After(1 * time.Second): t.Fatal("Copier failed to do its work in 1 second") case <-wait: } dec := json.NewDecoder(&jsonBuf) for { var msg Message if err := dec.Decode(&msg); err != nil { if err == io.EOF { break } t.Fatal(err) } if msg.Source != "stdout" && msg.Source != "stderr" { t.Fatalf("Wrong Source: %q, should be %q or %q", msg.Source, "stdout", "stderr") } if msg.ContainerID != cid { t.Fatalf("Wrong ContainerID: %q, expected %q", msg.ContainerID, cid) } if msg.Source == "stdout" { if string(msg.Line) != stdoutLine { t.Fatalf("Wrong Line: %q, expected %q", msg.Line, stdoutLine) } } if msg.Source == "stderr" { if string(msg.Line) != stderrLine { t.Fatalf("Wrong Line: %q, expected %q", msg.Line, stderrLine) } } } } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/factory.go ================================================ package logger import ( "fmt" "os" "strings" "sync" "time" ) // Creator is a method that builds a logging driver instance with given context type Creator func(Context) (Logger, error) //LogOptValidator is a method that validates the log opts provided type LogOptValidator func(cfg map[string]string) error // Context provides enough information for a logging driver to do its function type Context struct { Config map[string]string ContainerID string ContainerName string ContainerEntrypoint string ContainerArgs []string ContainerImageID string ContainerImageName string ContainerCreated time.Time LogPath string } func (ctx *Context) Hostname() (string, error) { hostname, err := os.Hostname() if err != nil { return "", fmt.Errorf("logger: can not resolve hostname: %v", err) } return hostname, nil } func (ctx *Context) Command() string { terms := []string{ctx.ContainerEntrypoint} for _, arg := range ctx.ContainerArgs { terms = append(terms, arg) } command := strings.Join(terms, " ") return command } type logdriverFactory struct { registry map[string]Creator optValidator map[string]LogOptValidator m sync.Mutex } func (lf *logdriverFactory) register(name string, c Creator) error { lf.m.Lock() defer lf.m.Unlock() if _, ok := lf.registry[name]; ok { return fmt.Errorf("logger: log driver named '%s' is already registered", name) } lf.registry[name] = c return nil } func (lf *logdriverFactory) registerLogOptValidator(name string, l LogOptValidator) error { lf.m.Lock() defer lf.m.Unlock() if _, ok := lf.optValidator[name]; ok { return fmt.Errorf("logger: log driver named '%s' is already registered", name) } lf.optValidator[name] = l return nil } func (lf *logdriverFactory) get(name string) (Creator, error) { lf.m.Lock() defer lf.m.Unlock() c, ok := lf.registry[name] if !ok { return c, fmt.Errorf("logger: no log driver named '%s' is registered", name) } return c, nil } func (lf *logdriverFactory) getLogOptValidator(name string) LogOptValidator { lf.m.Lock() defer lf.m.Unlock() c, _ := lf.optValidator[name] return c } var factory = &logdriverFactory{registry: make(map[string]Creator), optValidator: make(map[string]LogOptValidator)} // global factory instance // RegisterLogDriver registers the given logging driver builder with given logging // driver name. func RegisterLogDriver(name string, c Creator) error { return factory.register(name, c) } func RegisterLogOptValidator(name string, l LogOptValidator) error { return factory.registerLogOptValidator(name, l) } // GetLogDriver provides the logging driver builder for a logging driver name. func GetLogDriver(name string) (Creator, error) { return factory.get(name) } func ValidateLogOpts(name string, cfg map[string]string) error { l := factory.getLogOptValidator(name) if l != nil { return l(cfg) } return fmt.Errorf("Log Opts are not valid for [%s] driver", name) } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/fluentd/fluentd.go ================================================ package fluentd import ( "bytes" "fmt" "math" "net" "strconv" "strings" "text/template" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/logger" "github.com/fluent/fluent-logger-golang/fluent" ) type Fluentd struct { tag string containerID string containerName string writer *fluent.Fluent } type Receiver struct { ID string FullID string Name string } const ( name = "fluentd" defaultHostName = "localhost" defaultPort = 24224 defaultTagPrefix = "docker" ) func init() { if err := logger.RegisterLogDriver(name, New); err != nil { logrus.Fatal(err) } if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil { logrus.Fatal(err) } } func parseConfig(ctx logger.Context) (string, int, string, error) { host := defaultHostName port := defaultPort tag := "docker." + ctx.ContainerID[:12] config := ctx.Config if address := config["fluentd-address"]; address != "" { if h, p, err := net.SplitHostPort(address); err != nil { if !strings.Contains(err.Error(), "missing port in address") { return "", 0, "", err } host = h } else { portnum, err := strconv.Atoi(p) if err != nil { return "", 0, "", err } host = h port = portnum } } if config["fluentd-tag"] != "" { receiver := &Receiver{ ID: ctx.ContainerID[:12], FullID: ctx.ContainerID, Name: ctx.ContainerName, } tmpl, err := template.New("tag").Parse(config["fluentd-tag"]) if err != nil { return "", 0, "", err } buf := new(bytes.Buffer) if err := tmpl.Execute(buf, receiver); err != nil { return "", 0, "", err } tag = buf.String() } return host, port, tag, nil } func New(ctx logger.Context) (logger.Logger, error) { host, port, tag, err := parseConfig(ctx) if err != nil { return nil, err } logrus.Debugf("logging driver fluentd configured for container:%s, host:%s, port:%d, tag:%s.", ctx.ContainerID, host, port, tag) // logger tries to recoonect 2**64 - 1 times // failed (and panic) after 204 years [ 1.5 ** (2**32 - 1) - 1 seconds] log, err := fluent.New(fluent.Config{FluentPort: port, FluentHost: host, RetryWait: 1000, MaxRetry: math.MaxUint32}) if err != nil { return nil, err } return &Fluentd{ tag: tag, containerID: ctx.ContainerID, containerName: ctx.ContainerName, writer: log, }, nil } func (f *Fluentd) Log(msg *logger.Message) error { data := map[string]string{ "container_id": f.containerID, "container_name": f.containerName, "source": msg.Source, "log": string(msg.Line), } // fluent-logger-golang buffers logs from failures and disconnections, // and these are transferred again automatically. return f.writer.PostWithTime(f.tag, msg.Timestamp, data) } func ValidateLogOpt(cfg map[string]string) error { for key := range cfg { switch key { case "fluentd-address": case "fluentd-tag": default: return fmt.Errorf("unknown log opt '%s' for fluentd log driver", key) } } return nil } func (f *Fluentd) Close() error { return f.writer.Close() } func (f *Fluentd) Name() string { return name } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/gelf/gelf.go ================================================ // +build linux package gelf import ( "bytes" "fmt" "net" "net/url" "time" "github.com/Graylog2/go-gelf/gelf" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/pkg/urlutil" ) const name = "gelf" type GelfLogger struct { writer *gelf.Writer ctx logger.Context fields GelfFields } type GelfFields struct { hostname string containerId string containerName string imageId string imageName string command string tag string created time.Time } func init() { if err := logger.RegisterLogDriver(name, New); err != nil { logrus.Fatal(err) } if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil { logrus.Fatal(err) } } func New(ctx logger.Context) (logger.Logger, error) { // parse gelf address address, err := parseAddress(ctx.Config["gelf-address"]) if err != nil { return nil, err } // collect extra data for GELF message hostname, err := ctx.Hostname() if err != nil { return nil, fmt.Errorf("gelf: cannot access hostname to set source field") } // remove trailing slash from container name containerName := bytes.TrimLeft([]byte(ctx.ContainerName), "/") fields := GelfFields{ hostname: hostname, containerId: ctx.ContainerID, containerName: string(containerName), imageId: ctx.ContainerImageID, imageName: ctx.ContainerImageName, command: ctx.Command(), tag: ctx.Config["gelf-tag"], created: ctx.ContainerCreated, } // create new gelfWriter gelfWriter, err := gelf.NewWriter(address) if err != nil { return nil, fmt.Errorf("gelf: cannot connect to GELF endpoint: %s %v", address, err) } return &GelfLogger{ writer: gelfWriter, ctx: ctx, fields: fields, }, nil } func (s *GelfLogger) Log(msg *logger.Message) error { // remove trailing and leading whitespace short := bytes.TrimSpace([]byte(msg.Line)) level := gelf.LOG_INFO if msg.Source == "stderr" { level = gelf.LOG_ERR } m := gelf.Message{ Version: "1.1", Host: s.fields.hostname, Short: string(short), TimeUnix: float64(msg.Timestamp.UnixNano()/int64(time.Millisecond)) / 1000.0, Level: level, Extra: map[string]interface{}{ "_container_id": s.fields.containerId, "_container_name": s.fields.containerName, "_image_id": s.fields.imageId, "_image_name": s.fields.imageName, "_command": s.fields.command, "_tag": s.fields.tag, "_created": s.fields.created, }, } if err := s.writer.WriteMessage(&m); err != nil { return fmt.Errorf("gelf: cannot send GELF message: %v", err) } return nil } func (s *GelfLogger) Close() error { return s.writer.Close() } func (s *GelfLogger) Name() string { return name } func ValidateLogOpt(cfg map[string]string) error { for key := range cfg { switch key { case "gelf-address": case "gelf-tag": default: return fmt.Errorf("unknown log opt '%s' for gelf log driver", key) } } return nil } func parseAddress(address string) (string, error) { if urlutil.IsTransportURL(address) { url, err := url.Parse(address) if err != nil { return "", err } // we support only udp if url.Scheme != "udp" { return "", fmt.Errorf("gelf: endpoint needs to be UDP") } // get host and port if _, _, err = net.SplitHostPort(url.Host); err != nil { return "", fmt.Errorf("gelf: please provide gelf-address as udp://host:port") } return url.Host, nil } return "", nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/gelf/gelf_unsupported.go ================================================ // +build !linux package gelf ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/journald/journald.go ================================================ // +build linux package journald import ( "fmt" "github.com/Sirupsen/logrus" "github.com/coreos/go-systemd/journal" "github.com/docker/docker/daemon/logger" ) const name = "journald" type Journald struct { Jmap map[string]string } func init() { if err := logger.RegisterLogDriver(name, New); err != nil { logrus.Fatal(err) } } func New(ctx logger.Context) (logger.Logger, error) { if !journal.Enabled() { return nil, fmt.Errorf("journald is not enabled on this host") } // Strip a leading slash so that people can search for // CONTAINER_NAME=foo rather than CONTAINER_NAME=/foo. name := ctx.ContainerName if name[0] == '/' { name = name[1:] } jmap := map[string]string{ "CONTAINER_ID": ctx.ContainerID[:12], "CONTAINER_ID_FULL": ctx.ContainerID, "CONTAINER_NAME": name} return &Journald{Jmap: jmap}, nil } func (s *Journald) Log(msg *logger.Message) error { if msg.Source == "stderr" { return journal.Send(string(msg.Line), journal.PriErr, s.Jmap) } return journal.Send(string(msg.Line), journal.PriInfo, s.Jmap) } func (s *Journald) Close() error { return nil } func (s *Journald) Name() string { return name } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/journald/journald_unsupported.go ================================================ // +build !linux package journald ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/jsonfilelog/jsonfilelog.go ================================================ package jsonfilelog import ( "bytes" "fmt" "io" "os" "strconv" "sync" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/pkg/jsonlog" "github.com/docker/docker/pkg/timeutils" "github.com/docker/docker/pkg/units" ) const ( Name = "json-file" ) // JSONFileLogger is Logger implementation for default docker logging: // JSON objects to file type JSONFileLogger struct { buf *bytes.Buffer f *os.File // store for closing mu sync.Mutex // protects buffer capacity int64 //maximum size of each file n int //maximum number of files ctx logger.Context } func init() { if err := logger.RegisterLogDriver(Name, New); err != nil { logrus.Fatal(err) } if err := logger.RegisterLogOptValidator(Name, ValidateLogOpt); err != nil { logrus.Fatal(err) } } // New creates new JSONFileLogger which writes to filename func New(ctx logger.Context) (logger.Logger, error) { log, err := os.OpenFile(ctx.LogPath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600) if err != nil { return nil, err } var capval int64 = -1 if capacity, ok := ctx.Config["max-size"]; ok { var err error capval, err = units.FromHumanSize(capacity) if err != nil { return nil, err } } var maxFiles int = 1 if maxFileString, ok := ctx.Config["max-file"]; ok { maxFiles, err = strconv.Atoi(maxFileString) if err != nil { return nil, err } if maxFiles < 1 { return nil, fmt.Errorf("max-files cannot be less than 1.") } } return &JSONFileLogger{ f: log, buf: bytes.NewBuffer(nil), ctx: ctx, capacity: capval, n: maxFiles, }, nil } // Log converts logger.Message to jsonlog.JSONLog and serializes it to file func (l *JSONFileLogger) Log(msg *logger.Message) error { l.mu.Lock() defer l.mu.Unlock() timestamp, err := timeutils.FastMarshalJSON(msg.Timestamp) if err != nil { return err } err = (&jsonlog.JSONLogBytes{Log: append(msg.Line, '\n'), Stream: msg.Source, Created: timestamp}).MarshalJSONBuf(l.buf) if err != nil { return err } l.buf.WriteByte('\n') _, err = writeLog(l) return err } func writeLog(l *JSONFileLogger) (int64, error) { if l.capacity == -1 { return writeToBuf(l) } meta, err := l.f.Stat() if err != nil { return -1, err } if meta.Size() >= l.capacity { name := l.f.Name() if err := l.f.Close(); err != nil { return -1, err } if err := rotate(name, l.n); err != nil { return -1, err } file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) if err != nil { return -1, err } l.f = file } return writeToBuf(l) } func writeToBuf(l *JSONFileLogger) (int64, error) { i, err := l.buf.WriteTo(l.f) if err != nil { l.buf = bytes.NewBuffer(nil) } return i, err } func rotate(name string, n int) error { if n < 2 { return nil } for i := n - 1; i > 1; i-- { oldFile := name + "." + strconv.Itoa(i) replacingFile := name + "." + strconv.Itoa(i-1) if err := backup(oldFile, replacingFile); err != nil { return err } } if err := backup(name+".1", name); err != nil { return err } return nil } func backup(old, curr string) error { if _, err := os.Stat(old); !os.IsNotExist(err) { err := os.Remove(old) if err != nil { return err } } if _, err := os.Stat(curr); os.IsNotExist(err) { if f, err := os.Create(curr); err != nil { return err } else { f.Close() } } return os.Rename(curr, old) } func ValidateLogOpt(cfg map[string]string) error { for key := range cfg { switch key { case "max-file": case "max-size": default: return fmt.Errorf("unknown log opt '%s' for json-file log driver", key) } } return nil } func (l *JSONFileLogger) ReadLog(args ...string) (io.Reader, error) { pth := l.ctx.LogPath if len(args) > 0 { //check if args[0] is an integer index index, err := strconv.ParseInt(args[0], 0, 0) if err != nil { return nil, err } if index > 0 { pth = pth + "." + args[0] } } return os.Open(pth) } func (l *JSONFileLogger) LogPath() string { return l.ctx.LogPath } // Close closes underlying file func (l *JSONFileLogger) Close() error { return l.f.Close() } // Name returns name of this logger func (l *JSONFileLogger) Name() string { return Name } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/jsonfilelog/jsonfilelog_test.go ================================================ package jsonfilelog import ( "io/ioutil" "os" "path/filepath" "strconv" "testing" "time" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/pkg/jsonlog" ) func TestJSONFileLogger(t *testing.T) { cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" tmp, err := ioutil.TempDir("", "docker-logger-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) filename := filepath.Join(tmp, "container.log") l, err := New(logger.Context{ ContainerID: cid, LogPath: filename, }) if err != nil { t.Fatal(err) } defer l.Close() if err := l.Log(&logger.Message{ContainerID: cid, Line: []byte("line1"), Source: "src1"}); err != nil { t.Fatal(err) } if err := l.Log(&logger.Message{ContainerID: cid, Line: []byte("line2"), Source: "src2"}); err != nil { t.Fatal(err) } if err := l.Log(&logger.Message{ContainerID: cid, Line: []byte("line3"), Source: "src3"}); err != nil { t.Fatal(err) } res, err := ioutil.ReadFile(filename) if err != nil { t.Fatal(err) } expected := `{"log":"line1\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line2\n","stream":"src2","time":"0001-01-01T00:00:00Z"} {"log":"line3\n","stream":"src3","time":"0001-01-01T00:00:00Z"} ` if string(res) != expected { t.Fatalf("Wrong log content: %q, expected %q", res, expected) } } func BenchmarkJSONFileLogger(b *testing.B) { cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" tmp, err := ioutil.TempDir("", "docker-logger-") if err != nil { b.Fatal(err) } defer os.RemoveAll(tmp) filename := filepath.Join(tmp, "container.log") l, err := New(logger.Context{ ContainerID: cid, LogPath: filename, }) if err != nil { b.Fatal(err) } defer l.Close() testLine := "Line that thinks that it is log line from docker\n" msg := &logger.Message{ContainerID: cid, Line: []byte(testLine), Source: "stderr", Timestamp: time.Now().UTC()} jsonlog, err := (&jsonlog.JSONLog{Log: string(msg.Line) + "\n", Stream: msg.Source, Created: msg.Timestamp}).MarshalJSON() if err != nil { b.Fatal(err) } b.SetBytes(int64(len(jsonlog)+1) * 30) b.ResetTimer() for i := 0; i < b.N; i++ { for j := 0; j < 30; j++ { if err := l.Log(msg); err != nil { b.Fatal(err) } } } } func TestJSONFileLoggerWithOpts(t *testing.T) { cid := "a7317399f3f857173c6179d44823594f8294678dea9999662e5c625b5a1c7657" tmp, err := ioutil.TempDir("", "docker-logger-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) filename := filepath.Join(tmp, "container.log") config := map[string]string{"max-file": "2", "max-size": "1k"} l, err := New(logger.Context{ ContainerID: cid, LogPath: filename, Config: config, }) if err != nil { t.Fatal(err) } defer l.Close() for i := 0; i < 20; i++ { if err := l.Log(&logger.Message{ContainerID: cid, Line: []byte("line" + strconv.Itoa(i)), Source: "src1"}); err != nil { t.Fatal(err) } } res, err := ioutil.ReadFile(filename) if err != nil { t.Fatal(err) } penUlt, err := ioutil.ReadFile(filename + ".1") if err != nil { t.Fatal(err) } expectedPenultimate := `{"log":"line0\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line1\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line2\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line3\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line4\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line5\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line6\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line7\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line8\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line9\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line10\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line11\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line12\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line13\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line14\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line15\n","stream":"src1","time":"0001-01-01T00:00:00Z"} ` expected := `{"log":"line16\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line17\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line18\n","stream":"src1","time":"0001-01-01T00:00:00Z"} {"log":"line19\n","stream":"src1","time":"0001-01-01T00:00:00Z"} ` if string(res) != expected { t.Fatalf("Wrong log content: %q, expected %q", res, expected) } if string(penUlt) != expectedPenultimate { t.Fatalf("Wrong log content: %q, expected %q", penUlt, expectedPenultimate) } } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/logger.go ================================================ package logger import ( "errors" "io" "time" ) var ReadLogsNotSupported = errors.New("configured logging reader does not support reading") // Message is datastructure that represents record from some container type Message struct { ContainerID string Line []byte Source string Timestamp time.Time } // Logger is interface for docker logging drivers type Logger interface { Log(*Message) error Name() string Close() error } //Reader is an interface for docker logging drivers that support reading type Reader interface { ReadLog(args ...string) (io.Reader, error) } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/syslog/syslog.go ================================================ // +build linux package syslog import ( "errors" "fmt" "log/syslog" "net" "net/url" "os" "path" "strconv" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/pkg/urlutil" ) const name = "syslog" var facilities = map[string]syslog.Priority{ "kern": syslog.LOG_KERN, "user": syslog.LOG_USER, "mail": syslog.LOG_MAIL, "daemon": syslog.LOG_DAEMON, "auth": syslog.LOG_AUTH, "syslog": syslog.LOG_SYSLOG, "lpr": syslog.LOG_LPR, "news": syslog.LOG_NEWS, "uucp": syslog.LOG_UUCP, "cron": syslog.LOG_CRON, "authpriv": syslog.LOG_AUTHPRIV, "ftp": syslog.LOG_FTP, "local0": syslog.LOG_LOCAL0, "local1": syslog.LOG_LOCAL1, "local2": syslog.LOG_LOCAL2, "local3": syslog.LOG_LOCAL3, "local4": syslog.LOG_LOCAL4, "local5": syslog.LOG_LOCAL5, "local6": syslog.LOG_LOCAL6, "local7": syslog.LOG_LOCAL7, } type Syslog struct { writer *syslog.Writer } func init() { if err := logger.RegisterLogDriver(name, New); err != nil { logrus.Fatal(err) } if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil { logrus.Fatal(err) } } func New(ctx logger.Context) (logger.Logger, error) { tag := ctx.Config["syslog-tag"] if tag == "" { tag = ctx.ContainerID[:12] } proto, address, err := parseAddress(ctx.Config["syslog-address"]) if err != nil { return nil, err } facility, err := parseFacility(ctx.Config["syslog-facility"]) if err != nil { return nil, err } log, err := syslog.Dial( proto, address, facility, path.Base(os.Args[0])+"/"+tag, ) if err != nil { return nil, err } return &Syslog{ writer: log, }, nil } func (s *Syslog) Log(msg *logger.Message) error { if msg.Source == "stderr" { return s.writer.Err(string(msg.Line)) } return s.writer.Info(string(msg.Line)) } func (s *Syslog) Close() error { return s.writer.Close() } func (s *Syslog) Name() string { return name } func parseAddress(address string) (string, string, error) { if urlutil.IsTransportURL(address) { url, err := url.Parse(address) if err != nil { return "", "", err } // unix socket validation if url.Scheme == "unix" { if _, err := os.Stat(url.Path); err != nil { return "", "", err } return url.Scheme, url.Path, nil } // here we process tcp|udp host := url.Host if _, _, err := net.SplitHostPort(host); err != nil { if !strings.Contains(err.Error(), "missing port in address") { return "", "", err } host = host + ":514" } return url.Scheme, host, nil } return "", "", nil } func ValidateLogOpt(cfg map[string]string) error { for key := range cfg { switch key { case "syslog-address": case "syslog-tag": case "syslog-facility": default: return fmt.Errorf("unknown log opt '%s' for syslog log driver", key) } } return nil } func parseFacility(facility string) (syslog.Priority, error) { if facility == "" { return syslog.LOG_DAEMON, nil } if syslogFacility, valid := facilities[facility]; valid { return syslogFacility, nil } fInt, err := strconv.Atoi(facility) if err == nil && 0 <= fInt && fInt <= 23 { return syslog.Priority(fInt << 3), nil } return syslog.Priority(0), errors.New("invalid syslog facility") } ================================================ FILE: vendor/github.com/docker/docker/daemon/logger/syslog/syslog_unsupported.go ================================================ // +build !linux package syslog ================================================ FILE: vendor/github.com/docker/docker/daemon/logs.go ================================================ package daemon import ( "bytes" "encoding/json" "fmt" "io" "net" "os" "strconv" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/jsonfilelog" "github.com/docker/docker/pkg/jsonlog" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/pkg/tailfile" "github.com/docker/docker/pkg/timeutils" ) type ContainerLogsConfig struct { Follow, Timestamps bool Tail string Since time.Time UseStdout, UseStderr bool OutStream io.Writer Stop <-chan bool } func (daemon *Daemon) ContainerLogs(name string, config *ContainerLogsConfig) error { var ( lines = -1 format string ) if !(config.UseStdout || config.UseStderr) { return fmt.Errorf("You must choose at least one stream") } if config.Timestamps { format = timeutils.RFC3339NanoFixed } if config.Tail == "" { config.Tail = "latest" } container, err := daemon.Get(name) if err != nil { return err } var ( outStream = config.OutStream errStream io.Writer ) if !container.Config.Tty { errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr) outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout) } else { errStream = outStream } if container.LogDriverType() != jsonfilelog.Name { return fmt.Errorf("\"logs\" endpoint is supported only for \"json-file\" logging driver") } maxFile := 1 container.readHostConfig() cfg := container.getLogConfig() conf := cfg.Config if val, ok := conf["max-file"]; ok { var err error maxFile, err = strconv.Atoi(val) if err != nil { return fmt.Errorf("Error reading max-file value: %s", err) } } logDriver, err := container.getLogger() if err != nil { return err } _, ok := logDriver.(logger.Reader) if !ok { logrus.Errorf("Cannot read logs of the [%s] driver", logDriver.Name()) } else { // json-file driver if config.Tail != "all" && config.Tail != "latest" { var err error lines, err = strconv.Atoi(config.Tail) if err != nil { logrus.Errorf("Failed to parse tail %s, error: %v, show all logs", config.Tail, err) lines = -1 } } if lines != 0 { n := maxFile if config.Tail == "latest" && config.Since.IsZero() { n = 1 } before := false for i := n; i > 0; i-- { if before { break } cLog, err := getReader(logDriver, i, n, lines) if err != nil { logrus.Debugf("Error reading %d log file: %v", i-1, err) continue } //if lines are specified, then iterate only once if lines > 0 { i = 1 } else { // if lines are not specified, cLog is a file, It needs to be closed defer cLog.(*os.File).Close() } dec := json.NewDecoder(cLog) l := &jsonlog.JSONLog{} for { l.Reset() if err := dec.Decode(l); err == io.EOF { break } else if err != nil { logrus.Errorf("Error streaming logs: %s", err) break } logLine := l.Log if !config.Since.IsZero() && l.Created.Before(config.Since) { continue } if config.Timestamps { // format can be "" or time format, so here can't be error logLine, _ = l.Format(format) } if l.Stream == "stdout" && config.UseStdout { io.WriteString(outStream, logLine) } if l.Stream == "stderr" && config.UseStderr { io.WriteString(errStream, logLine) } } } } } if config.Follow && container.IsRunning() { chErrStderr := make(chan error) chErrStdout := make(chan error) var stdoutPipe, stderrPipe io.ReadCloser // write an empty chunk of data (this is to ensure that the // HTTP Response is sent immediatly, even if the container has // not yet produced any data) outStream.Write(nil) if config.UseStdout { stdoutPipe = container.StdoutLogPipe() go func() { logrus.Debug("logs: stdout stream begin") chErrStdout <- jsonlog.WriteLog(stdoutPipe, outStream, format, config.Since) logrus.Debug("logs: stdout stream end") }() } if config.UseStderr { stderrPipe = container.StderrLogPipe() go func() { logrus.Debug("logs: stderr stream begin") chErrStderr <- jsonlog.WriteLog(stderrPipe, errStream, format, config.Since) logrus.Debug("logs: stderr stream end") }() } select { case err = <-chErrStderr: if stdoutPipe != nil { stdoutPipe.Close() <-chErrStdout } case err = <-chErrStdout: if stderrPipe != nil { stderrPipe.Close() <-chErrStderr } case <-config.Stop: if stdoutPipe != nil { stdoutPipe.Close() <-chErrStdout } if stderrPipe != nil { stderrPipe.Close() <-chErrStderr } return nil } if err != nil && err != io.EOF && err != io.ErrClosedPipe { if e, ok := err.(*net.OpError); ok && e.Err != syscall.EPIPE { logrus.Errorf("error streaming logs: %v", err) } } } return nil } func getReader(logDriver logger.Logger, fileIndex, maxFiles, lines int) (io.Reader, error) { if lines <= 0 { index := strconv.Itoa(fileIndex - 1) cLog, err := logDriver.(logger.Reader).ReadLog(index) return cLog, err } buf := bytes.NewBuffer([]byte{}) remaining := lines for i := 0; i < maxFiles; i++ { index := strconv.Itoa(i) cLog, err := logDriver.(logger.Reader).ReadLog(index) if err != nil { return buf, err } f := cLog.(*os.File) ls, err := tailfile.TailFile(f, remaining) if err != nil { return buf, err } tmp := bytes.NewBuffer([]byte{}) for _, l := range ls { fmt.Fprintf(tmp, "%s\n", l) } tmp.ReadFrom(buf) buf = tmp if len(ls) == remaining { return buf, nil } remaining = remaining - len(ls) } return buf, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/monitor.go ================================================ package daemon import ( "io" "os/exec" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/runconfig" ) const defaultTimeIncrement = 100 // containerMonitor monitors the execution of a container's main process. // If a restart policy is specified for the container the monitor will ensure that the // process is restarted based on the rules of the policy. When the container is finally stopped // the monitor will reset and cleanup any of the container resources such as networking allocations // and the rootfs type containerMonitor struct { mux sync.Mutex // container is the container being monitored container *Container // restartPolicy is the current policy being applied to the container monitor restartPolicy runconfig.RestartPolicy // failureCount is the number of times the container has failed to // start in a row failureCount int // shouldStop signals the monitor that the next time the container exits it is // either because docker or the user asked for the container to be stopped shouldStop bool // startSignal is a channel that is closes after the container initially starts startSignal chan struct{} // stopChan is used to signal to the monitor whenever there is a wait for the // next restart so that the timeIncrement is not honored and the user is not // left waiting for nothing to happen during this time stopChan chan struct{} // timeIncrement is the amount of time to wait between restarts // this is in milliseconds timeIncrement int // lastStartTime is the time which the monitor last exec'd the container's process lastStartTime time.Time } // newContainerMonitor returns an initialized containerMonitor for the provided container // honoring the provided restart policy func newContainerMonitor(container *Container, policy runconfig.RestartPolicy) *containerMonitor { return &containerMonitor{ container: container, restartPolicy: policy, timeIncrement: defaultTimeIncrement, stopChan: make(chan struct{}), startSignal: make(chan struct{}), } } // Stop signals to the container monitor that it should stop monitoring the container // for exits the next time the process dies func (m *containerMonitor) ExitOnNext() { m.mux.Lock() // we need to protect having a double close of the channel when stop is called // twice or else we will get a panic if !m.shouldStop { m.shouldStop = true close(m.stopChan) } m.mux.Unlock() } // Close closes the container's resources such as networking allocations and // unmounts the contatiner's root filesystem func (m *containerMonitor) Close() error { // Cleanup networking and mounts m.container.cleanup() // FIXME: here is race condition between two RUN instructions in Dockerfile // because they share same runconfig and change image. Must be fixed // in builder/builder.go if err := m.container.toDisk(); err != nil { logrus.Errorf("Error dumping container %s state to disk: %s", m.container.ID, err) return err } return nil } // Start starts the containers process and monitors it according to the restart policy func (m *containerMonitor) Start() error { var ( err error exitStatus execdriver.ExitStatus // this variable indicates where we in execution flow: // before Run or after afterRun bool ) // ensure that when the monitor finally exits we release the networking and unmount the rootfs defer func() { if afterRun { m.container.Lock() m.container.setStopped(&exitStatus) defer m.container.Unlock() } m.Close() }() // reset the restart count m.container.RestartCount = -1 for { m.container.RestartCount++ if err := m.container.startLogging(); err != nil { m.resetContainer(false) return err } pipes := execdriver.NewPipes(m.container.stdin, m.container.stdout, m.container.stderr, m.container.Config.OpenStdin) m.container.LogEvent("start") m.lastStartTime = time.Now() if exitStatus, err = m.container.daemon.Run(m.container, pipes, m.callback); err != nil { // if we receive an internal error from the initial start of a container then lets // return it instead of entering the restart loop if m.container.RestartCount == 0 { m.container.ExitCode = -1 m.resetContainer(false) return err } logrus.Errorf("Error running container: %s", err) } // here container.Lock is already lost afterRun = true m.resetMonitor(err == nil && exitStatus.ExitCode == 0) if m.shouldRestart(exitStatus.ExitCode) { m.container.SetRestarting(&exitStatus) if exitStatus.OOMKilled { m.container.LogEvent("oom") } m.container.LogEvent("die") m.resetContainer(true) // sleep with a small time increment between each restart to help avoid issues cased by quickly // restarting the container because of some types of errors ( networking cut out, etc... ) m.waitForNextRestart() // we need to check this before reentering the loop because the waitForNextRestart could have // been terminated by a request from a user if m.shouldStop { return err } continue } if exitStatus.OOMKilled { m.container.LogEvent("oom") } m.container.LogEvent("die") m.resetContainer(true) return err } } // resetMonitor resets the stateful fields on the containerMonitor based on the // previous runs success or failure. Regardless of success, if the container had // an execution time of more than 10s then reset the timer back to the default func (m *containerMonitor) resetMonitor(successful bool) { executionTime := time.Now().Sub(m.lastStartTime).Seconds() if executionTime > 10 { m.timeIncrement = defaultTimeIncrement } else { // otherwise we need to increment the amount of time we wait before restarting // the process. We will build up by multiplying the increment by 2 m.timeIncrement *= 2 } // the container exited successfully so we need to reset the failure counter if successful { m.failureCount = 0 } else { m.failureCount++ } } // waitForNextRestart waits with the default time increment to restart the container unless // a user or docker asks for the container to be stopped func (m *containerMonitor) waitForNextRestart() { select { case <-time.After(time.Duration(m.timeIncrement) * time.Millisecond): case <-m.stopChan: } } // shouldRestart checks the restart policy and applies the rules to determine if // the container's process should be restarted func (m *containerMonitor) shouldRestart(exitCode int) bool { m.mux.Lock() defer m.mux.Unlock() // do not restart if the user or docker has requested that this container be stopped if m.shouldStop { return false } switch { case m.restartPolicy.IsAlways(): return true case m.restartPolicy.IsOnFailure(): // the default value of 0 for MaximumRetryCount means that we will not enforce a maximum count if max := m.restartPolicy.MaximumRetryCount; max != 0 && m.failureCount > max { logrus.Debugf("stopping restart of container %s because maximum failure could of %d has been reached", stringid.TruncateID(m.container.ID), max) return false } return exitCode != 0 } return false } // callback ensures that the container's state is properly updated after we // received ack from the execution drivers func (m *containerMonitor) callback(processConfig *execdriver.ProcessConfig, pid int) { if processConfig.Tty { // The callback is called after the process Start() // so we are in the parent process. In TTY mode, stdin/out/err is the PtySlave // which we close here. if c, ok := processConfig.Stdout.(io.Closer); ok { c.Close() } } m.container.setRunning(pid) // signal that the process has started // close channel only if not closed select { case <-m.startSignal: default: close(m.startSignal) } if err := m.container.ToDisk(); err != nil { logrus.Errorf("Error saving container to disk: %v", err) } } // resetContainer resets the container's IO and ensures that the command is able to be executed again // by copying the data into a new struct // if lock is true, then container locked during reset func (m *containerMonitor) resetContainer(lock bool) { container := m.container if lock { container.Lock() defer container.Unlock() } if container.Config.OpenStdin { if err := container.stdin.Close(); err != nil { logrus.Errorf("%s: Error close stdin: %s", container.ID, err) } } if err := container.stdout.Clean(); err != nil { logrus.Errorf("%s: Error close stdout: %s", container.ID, err) } if err := container.stderr.Clean(); err != nil { logrus.Errorf("%s: Error close stderr: %s", container.ID, err) } if container.command != nil && container.command.ProcessConfig.Terminal != nil { if err := container.command.ProcessConfig.Terminal.Close(); err != nil { logrus.Errorf("%s: Error closing terminal: %s", container.ID, err) } } // Re-create a brand new stdin pipe once the container exited if container.Config.OpenStdin { container.stdin, container.stdinPipe = io.Pipe() } if container.logDriver != nil { if container.logCopier != nil { exit := make(chan struct{}) go func() { container.logCopier.Wait() close(exit) }() select { case <-time.After(1 * time.Second): logrus.Warnf("Logger didn't exit in time: logs may be truncated") case <-exit: } } container.logDriver.Close() container.logCopier = nil container.logDriver = nil } c := container.command.ProcessConfig.Cmd container.command.ProcessConfig.Cmd = exec.Cmd{ Stdin: c.Stdin, Stdout: c.Stdout, Stderr: c.Stderr, Path: c.Path, Env: c.Env, ExtraFiles: c.ExtraFiles, Args: c.Args, Dir: c.Dir, SysProcAttr: c.SysProcAttr, } } ================================================ FILE: vendor/github.com/docker/docker/daemon/network/settings.go ================================================ package network import "github.com/docker/docker/pkg/nat" // Address represents an IP address type Address struct { Addr string PrefixLen int } // Settings stores configuration details about the daemon network config type Settings struct { Bridge string EndpointID string Gateway string GlobalIPv6Address string GlobalIPv6PrefixLen int HairpinMode bool IPAddress string IPPrefixLen int IPv6Gateway string LinkLocalIPv6Address string LinkLocalIPv6PrefixLen int MacAddress string NetworkID string PortMapping map[string]map[string]string // Deprecated Ports nat.PortMap SandboxKey string SecondaryIPAddresses []Address SecondaryIPv6Addresses []Address } ================================================ FILE: vendor/github.com/docker/docker/daemon/pause.go ================================================ package daemon import "fmt" // ContainerPause pauses a container func (daemon *Daemon) ContainerPause(name string) error { container, err := daemon.Get(name) if err != nil { return err } if err := container.Pause(); err != nil { return fmt.Errorf("Cannot pause container %s: %s", name, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/rename.go ================================================ package daemon import ( "fmt" ) func (daemon *Daemon) ContainerRename(oldName, newName string) error { if oldName == "" || newName == "" { return fmt.Errorf("usage: docker rename OLD_NAME NEW_NAME") } container, err := daemon.Get(oldName) if err != nil { return err } oldName = container.Name container.Lock() defer container.Unlock() if newName, err = daemon.reserveName(container.ID, newName); err != nil { return fmt.Errorf("Error when allocating new name: %s", err) } container.Name = newName undo := func() { container.Name = oldName daemon.reserveName(container.ID, oldName) daemon.containerGraph.Delete(newName) } if err := daemon.containerGraph.Delete(oldName); err != nil { undo() return fmt.Errorf("Failed to delete container %q: %v", oldName, err) } if err := container.toDisk(); err != nil { undo() return err } container.LogEvent("rename") return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/resize.go ================================================ package daemon func (daemon *Daemon) ContainerResize(name string, height, width int) error { container, err := daemon.Get(name) if err != nil { return err } return container.Resize(height, width) } func (daemon *Daemon) ContainerExecResize(name string, height, width int) error { execConfig, err := daemon.getExecConfig(name) if err != nil { return err } return execConfig.Resize(height, width) } ================================================ FILE: vendor/github.com/docker/docker/daemon/restart.go ================================================ package daemon import "fmt" func (daemon *Daemon) ContainerRestart(name string, seconds int) error { container, err := daemon.Get(name) if err != nil { return err } if err := container.Restart(seconds); err != nil { return fmt.Errorf("Cannot restart container %s: %s\n", name, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/start.go ================================================ package daemon import ( "fmt" "runtime" "github.com/docker/docker/runconfig" ) func (daemon *Daemon) ContainerStart(name string, hostConfig *runconfig.HostConfig) error { container, err := daemon.Get(name) if err != nil { return err } if container.IsPaused() { return fmt.Errorf("Cannot start a paused container, try unpause instead.") } if container.IsRunning() { return fmt.Errorf("Container already started") } if _, err = daemon.verifyContainerSettings(hostConfig, nil); err != nil { return err } // Windows does not have the backwards compatibilty issue here. if runtime.GOOS != "windows" { // This is kept for backward compatibility - hostconfig should be passed when // creating a container, not during start. if hostConfig != nil { if err := daemon.setHostConfig(container, hostConfig); err != nil { return err } } } else { if hostConfig != nil { return fmt.Errorf("Supplying a hostconfig on start is not supported. It should be supplied on create") } } if err := container.Start(); err != nil { return fmt.Errorf("Cannot start container %s: %s", name, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/state.go ================================================ package daemon import ( "fmt" "sync" "time" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/units" ) type State struct { sync.Mutex Running bool Paused bool Restarting bool OOMKilled bool removalInProgress bool // Not need for this to be persistent on disk. Dead bool Pid int ExitCode int Error string // contains last known error when starting the container StartedAt time.Time FinishedAt time.Time waitChan chan struct{} } func NewState() *State { return &State{ waitChan: make(chan struct{}), } } // String returns a human-readable description of the state func (s *State) String() string { if s.Running { if s.Paused { return fmt.Sprintf("Up %s (Paused)", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) } if s.Restarting { return fmt.Sprintf("Restarting (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) } return fmt.Sprintf("Up %s", units.HumanDuration(time.Now().UTC().Sub(s.StartedAt))) } if s.removalInProgress { return "Removal In Progress" } if s.Dead { return "Dead" } if s.StartedAt.IsZero() { return "Created" } if s.FinishedAt.IsZero() { return "" } return fmt.Sprintf("Exited (%d) %s ago", s.ExitCode, units.HumanDuration(time.Now().UTC().Sub(s.FinishedAt))) } // StateString returns a single string to describe state func (s *State) StateString() string { if s.Running { if s.Paused { return "paused" } if s.Restarting { return "restarting" } return "running" } if s.Dead { return "dead" } if s.StartedAt.IsZero() { return "created" } return "exited" } func isValidStateString(s string) bool { if s != "paused" && s != "restarting" && s != "running" && s != "dead" && s != "created" && s != "exited" { return false } return true } func wait(waitChan <-chan struct{}, timeout time.Duration) error { if timeout < 0 { <-waitChan return nil } select { case <-time.After(timeout): return fmt.Errorf("Timed out: %v", timeout) case <-waitChan: return nil } } // WaitRunning waits until state is running. If state already running it returns // immediately. If you want wait forever you must supply negative timeout. // Returns pid, that was passed to SetRunning func (s *State) WaitRunning(timeout time.Duration) (int, error) { s.Lock() if s.Running { pid := s.Pid s.Unlock() return pid, nil } waitChan := s.waitChan s.Unlock() if err := wait(waitChan, timeout); err != nil { return -1, err } return s.GetPid(), nil } // WaitStop waits until state is stopped. If state already stopped it returns // immediately. If you want wait forever you must supply negative timeout. // Returns exit code, that was passed to SetStopped func (s *State) WaitStop(timeout time.Duration) (int, error) { s.Lock() if !s.Running { exitCode := s.ExitCode s.Unlock() return exitCode, nil } waitChan := s.waitChan s.Unlock() if err := wait(waitChan, timeout); err != nil { return -1, err } return s.GetExitCode(), nil } func (s *State) IsRunning() bool { s.Lock() res := s.Running s.Unlock() return res } func (s *State) GetPid() int { s.Lock() res := s.Pid s.Unlock() return res } func (s *State) GetExitCode() int { s.Lock() res := s.ExitCode s.Unlock() return res } func (s *State) SetRunning(pid int) { s.Lock() s.setRunning(pid) s.Unlock() } func (s *State) setRunning(pid int) { s.Error = "" s.Running = true s.Paused = false s.Restarting = false s.ExitCode = 0 s.Pid = pid s.StartedAt = time.Now().UTC() close(s.waitChan) // fire waiters for start s.waitChan = make(chan struct{}) } func (s *State) SetStopped(exitStatus *execdriver.ExitStatus) { s.Lock() s.setStopped(exitStatus) s.Unlock() } func (s *State) setStopped(exitStatus *execdriver.ExitStatus) { s.Running = false s.Restarting = false s.Pid = 0 s.FinishedAt = time.Now().UTC() s.ExitCode = exitStatus.ExitCode s.OOMKilled = exitStatus.OOMKilled close(s.waitChan) // fire waiters for stop s.waitChan = make(chan struct{}) } // SetRestarting is when docker handles the auto restart of containers when they are // in the middle of a stop and being restarted again func (s *State) SetRestarting(exitStatus *execdriver.ExitStatus) { s.Lock() // we should consider the container running when it is restarting because of // all the checks in docker around rm/stop/etc s.Running = true s.Restarting = true s.Pid = 0 s.FinishedAt = time.Now().UTC() s.ExitCode = exitStatus.ExitCode s.OOMKilled = exitStatus.OOMKilled close(s.waitChan) // fire waiters for stop s.waitChan = make(chan struct{}) s.Unlock() } // setError sets the container's error state. This is useful when we want to // know the error that occurred when container transits to another state // when inspecting it func (s *State) setError(err error) { s.Error = err.Error() } func (s *State) IsRestarting() bool { s.Lock() res := s.Restarting s.Unlock() return res } func (s *State) SetPaused() { s.Lock() s.Paused = true s.Unlock() } func (s *State) SetUnpaused() { s.Lock() s.Paused = false s.Unlock() } func (s *State) IsPaused() bool { s.Lock() res := s.Paused s.Unlock() return res } func (s *State) SetRemovalInProgress() error { s.Lock() defer s.Unlock() if s.removalInProgress { return fmt.Errorf("Status is already RemovalInProgress") } s.removalInProgress = true return nil } func (s *State) ResetRemovalInProgress() { s.Lock() s.removalInProgress = false s.Unlock() } func (s *State) SetDead() { s.Lock() s.Dead = true s.Unlock() } ================================================ FILE: vendor/github.com/docker/docker/daemon/state_test.go ================================================ package daemon import ( "sync/atomic" "testing" "time" "github.com/docker/docker/daemon/execdriver" ) func TestStateRunStop(t *testing.T) { s := NewState() for i := 1; i < 3; i++ { // full lifecycle two times started := make(chan struct{}) var pid int64 go func() { runPid, _ := s.WaitRunning(-1 * time.Second) atomic.StoreInt64(&pid, int64(runPid)) close(started) }() s.SetRunning(i + 100) if !s.IsRunning() { t.Fatal("State not running") } if s.Pid != i+100 { t.Fatalf("Pid %v, expected %v", s.Pid, i+100) } if s.ExitCode != 0 { t.Fatalf("ExitCode %v, expected 0", s.ExitCode) } select { case <-time.After(100 * time.Millisecond): t.Fatal("Start callback doesn't fire in 100 milliseconds") case <-started: t.Log("Start callback fired") } runPid := int(atomic.LoadInt64(&pid)) if runPid != i+100 { t.Fatalf("Pid %v, expected %v", runPid, i+100) } if pid, err := s.WaitRunning(-1 * time.Second); err != nil || pid != i+100 { t.Fatalf("WaitRunning returned pid: %v, err: %v, expected pid: %v, err: %v", pid, err, i+100, nil) } stopped := make(chan struct{}) var exit int64 go func() { exitCode, _ := s.WaitStop(-1 * time.Second) atomic.StoreInt64(&exit, int64(exitCode)) close(stopped) }() s.SetStopped(&execdriver.ExitStatus{ExitCode: i}) if s.IsRunning() { t.Fatal("State is running") } if s.ExitCode != i { t.Fatalf("ExitCode %v, expected %v", s.ExitCode, i) } if s.Pid != 0 { t.Fatalf("Pid %v, expected 0", s.Pid) } select { case <-time.After(100 * time.Millisecond): t.Fatal("Stop callback doesn't fire in 100 milliseconds") case <-stopped: t.Log("Stop callback fired") } exitCode := int(atomic.LoadInt64(&exit)) if exitCode != i { t.Fatalf("ExitCode %v, expected %v", exitCode, i) } if exitCode, err := s.WaitStop(-1 * time.Second); err != nil || exitCode != i { t.Fatalf("WaitStop returned exitCode: %v, err: %v, expected exitCode: %v, err: %v", exitCode, err, i, nil) } } } func TestStateTimeoutWait(t *testing.T) { s := NewState() started := make(chan struct{}) go func() { s.WaitRunning(100 * time.Millisecond) close(started) }() select { case <-time.After(200 * time.Millisecond): t.Fatal("Start callback doesn't fire in 100 milliseconds") case <-started: t.Log("Start callback fired") } s.SetRunning(42) stopped := make(chan struct{}) go func() { s.WaitRunning(100 * time.Millisecond) close(stopped) }() select { case <-time.After(200 * time.Millisecond): t.Fatal("Start callback doesn't fire in 100 milliseconds") case <-stopped: t.Log("Start callback fired") } } ================================================ FILE: vendor/github.com/docker/docker/daemon/stats.go ================================================ package daemon import ( "encoding/json" "io" "github.com/docker/docker/api/types" "github.com/docker/docker/daemon/execdriver" "github.com/docker/libnetwork/sandbox" "github.com/opencontainers/runc/libcontainer" ) type ContainerStatsConfig struct { Stream bool OutStream io.Writer Stop <-chan bool } func (daemon *Daemon) ContainerStats(name string, config *ContainerStatsConfig) error { updates, err := daemon.SubscribeToContainerStats(name) if err != nil { return err } if config.Stream { config.OutStream.Write(nil) } var preCpuStats types.CpuStats getStat := func(v interface{}) *types.Stats { update := v.(*execdriver.ResourceStats) // Retrieve the nw statistics from libnetwork and inject them in the Stats if nwStats, err := daemon.getNetworkStats(name); err == nil { update.Stats.Interfaces = nwStats } ss := convertStatsToAPITypes(update.Stats) ss.PreCpuStats = preCpuStats ss.MemoryStats.Limit = uint64(update.MemoryLimit) ss.Read = update.Read ss.CpuStats.SystemUsage = update.SystemUsage preCpuStats = ss.CpuStats return ss } enc := json.NewEncoder(config.OutStream) defer daemon.UnsubscribeToContainerStats(name, updates) noStreamFirstFrame := true for { select { case v, ok := <-updates: if !ok { return nil } s := getStat(v) if !config.Stream && noStreamFirstFrame { // prime the cpu stats so they aren't 0 in the final output noStreamFirstFrame = false continue } if err := enc.Encode(s); err != nil { return err } if !config.Stream { return nil } case <-config.Stop: return nil } } } func (daemon *Daemon) getNetworkStats(name string) ([]*libcontainer.NetworkInterface, error) { var list []*libcontainer.NetworkInterface c, err := daemon.Get(name) if err != nil { return list, err } nw, err := daemon.netController.NetworkByID(c.NetworkSettings.NetworkID) if err != nil { return list, err } ep, err := nw.EndpointByID(c.NetworkSettings.EndpointID) if err != nil { return list, err } stats, err := ep.Statistics() if err != nil { return list, err } // Convert libnetwork nw stats into libcontainer nw stats for ifName, ifStats := range stats { list = append(list, convertLnNetworkStats(ifName, ifStats)) } return list, nil } func convertLnNetworkStats(name string, stats *sandbox.InterfaceStatistics) *libcontainer.NetworkInterface { n := &libcontainer.NetworkInterface{Name: name} n.RxBytes = stats.RxBytes n.RxPackets = stats.RxPackets n.RxErrors = stats.RxErrors n.RxDropped = stats.RxDropped n.TxBytes = stats.TxBytes n.TxPackets = stats.TxPackets n.TxErrors = stats.TxErrors n.TxDropped = stats.TxDropped return n } ================================================ FILE: vendor/github.com/docker/docker/daemon/stats_collector_unix.go ================================================ // +build !windows package daemon import ( "bufio" "fmt" "os" "strconv" "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/pubsub" "github.com/opencontainers/runc/libcontainer/system" ) // newStatsCollector returns a new statsCollector that collections // network and cgroup stats for a registered container at the specified // interval. The collector allows non-running containers to be added // and will start processing stats when they are started. func newStatsCollector(interval time.Duration) *statsCollector { s := &statsCollector{ interval: interval, publishers: make(map[*Container]*pubsub.Publisher), clockTicks: uint64(system.GetClockTicks()), bufReader: bufio.NewReaderSize(nil, 128), } go s.run() return s } // statsCollector manages and provides container resource stats type statsCollector struct { m sync.Mutex interval time.Duration clockTicks uint64 publishers map[*Container]*pubsub.Publisher bufReader *bufio.Reader } // collect registers the container with the collector and adds it to // the event loop for collection on the specified interval returning // a channel for the subscriber to receive on. func (s *statsCollector) collect(c *Container) chan interface{} { s.m.Lock() defer s.m.Unlock() publisher, exists := s.publishers[c] if !exists { publisher = pubsub.NewPublisher(100*time.Millisecond, 1024) s.publishers[c] = publisher } return publisher.Subscribe() } // stopCollection closes the channels for all subscribers and removes // the container from metrics collection. func (s *statsCollector) stopCollection(c *Container) { s.m.Lock() if publisher, exists := s.publishers[c]; exists { publisher.Close() delete(s.publishers, c) } s.m.Unlock() } // unsubscribe removes a specific subscriber from receiving updates for a container's stats. func (s *statsCollector) unsubscribe(c *Container, ch chan interface{}) { s.m.Lock() publisher := s.publishers[c] if publisher != nil { publisher.Evict(ch) if publisher.Len() == 0 { delete(s.publishers, c) } } s.m.Unlock() } func (s *statsCollector) run() { type publishersPair struct { container *Container publisher *pubsub.Publisher } // we cannot determine the capacity here. // it will grow enough in first iteration var pairs []publishersPair for range time.Tick(s.interval) { systemUsage, err := s.getSystemCpuUsage() if err != nil { logrus.Errorf("collecting system cpu usage: %v", err) continue } // it does not make sense in the first iteration, // but saves allocations in further iterations pairs = pairs[:0] s.m.Lock() for container, publisher := range s.publishers { // copy pointers here to release the lock ASAP pairs = append(pairs, publishersPair{container, publisher}) } s.m.Unlock() for _, pair := range pairs { stats, err := pair.container.Stats() if err != nil { if err != execdriver.ErrNotRunning { logrus.Errorf("collecting stats for %s: %v", pair.container.ID, err) } continue } stats.SystemUsage = systemUsage pair.publisher.Publish(stats) } } } const nanoSeconds = 1e9 // getSystemCpuUSage returns the host system's cpu usage in nanoseconds // for the system to match the cgroup readings are returned in the same format. func (s *statsCollector) getSystemCpuUsage() (uint64, error) { var line string f, err := os.Open("/proc/stat") if err != nil { return 0, err } defer func() { s.bufReader.Reset(nil) f.Close() }() s.bufReader.Reset(f) err = nil for err == nil { line, err = s.bufReader.ReadString('\n') if err != nil { break } parts := strings.Fields(line) switch parts[0] { case "cpu": if len(parts) < 8 { return 0, fmt.Errorf("invalid number of cpu fields") } var sum uint64 for _, i := range parts[1:8] { v, err := strconv.ParseUint(i, 10, 64) if err != nil { return 0, fmt.Errorf("Unable to convert value %s to int: %s", i, err) } sum += v } return (sum * nanoSeconds) / s.clockTicks, nil } } return 0, fmt.Errorf("invalid stat format") } ================================================ FILE: vendor/github.com/docker/docker/daemon/stats_collector_windows.go ================================================ package daemon import "time" // newStatsCollector returns a new statsCollector for collection stats // for a registered container at the specified interval. The collector allows // non-running containers to be added and will start processing stats when // they are started. func newStatsCollector(interval time.Duration) *statsCollector { return &statsCollector{} } // statsCollector manages and provides container resource stats type statsCollector struct { } // collect registers the container with the collector and adds it to // the event loop for collection on the specified interval returning // a channel for the subscriber to receive on. func (s *statsCollector) collect(c *Container) chan interface{} { return nil } // stopCollection closes the channels for all subscribers and removes // the container from metrics collection. func (s *statsCollector) stopCollection(c *Container) { } // unsubscribe removes a specific subscriber from receiving updates for a container's stats. func (s *statsCollector) unsubscribe(c *Container, ch chan interface{}) { } ================================================ FILE: vendor/github.com/docker/docker/daemon/stats_linux.go ================================================ package daemon import ( "github.com/docker/docker/api/types" "github.com/opencontainers/runc/libcontainer" "github.com/opencontainers/runc/libcontainer/cgroups" ) // convertStatsToAPITypes converts the libcontainer.Stats to the api specific // structs. This is done to preserve API compatibility and versioning. func convertStatsToAPITypes(ls *libcontainer.Stats) *types.Stats { s := &types.Stats{} if ls.Interfaces != nil { s.Network = types.Network{} for _, iface := range ls.Interfaces { s.Network.RxBytes += iface.RxBytes s.Network.RxPackets += iface.RxPackets s.Network.RxErrors += iface.RxErrors s.Network.RxDropped += iface.RxDropped s.Network.TxBytes += iface.TxBytes s.Network.TxPackets += iface.TxPackets s.Network.TxErrors += iface.TxErrors s.Network.TxDropped += iface.TxDropped } } cs := ls.CgroupStats if cs != nil { s.BlkioStats = types.BlkioStats{ IoServiceBytesRecursive: copyBlkioEntry(cs.BlkioStats.IoServiceBytesRecursive), IoServicedRecursive: copyBlkioEntry(cs.BlkioStats.IoServicedRecursive), IoQueuedRecursive: copyBlkioEntry(cs.BlkioStats.IoQueuedRecursive), IoServiceTimeRecursive: copyBlkioEntry(cs.BlkioStats.IoServiceTimeRecursive), IoWaitTimeRecursive: copyBlkioEntry(cs.BlkioStats.IoWaitTimeRecursive), IoMergedRecursive: copyBlkioEntry(cs.BlkioStats.IoMergedRecursive), IoTimeRecursive: copyBlkioEntry(cs.BlkioStats.IoTimeRecursive), SectorsRecursive: copyBlkioEntry(cs.BlkioStats.SectorsRecursive), } cpu := cs.CpuStats s.CpuStats = types.CpuStats{ CpuUsage: types.CpuUsage{ TotalUsage: cpu.CpuUsage.TotalUsage, PercpuUsage: cpu.CpuUsage.PercpuUsage, UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode, UsageInUsermode: cpu.CpuUsage.UsageInUsermode, }, ThrottlingData: types.ThrottlingData{ Periods: cpu.ThrottlingData.Periods, ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods, ThrottledTime: cpu.ThrottlingData.ThrottledTime, }, } mem := cs.MemoryStats s.MemoryStats = types.MemoryStats{ Usage: mem.Usage.Usage, MaxUsage: mem.Usage.MaxUsage, Stats: mem.Stats, Failcnt: mem.Usage.Failcnt, } } return s } func copyBlkioEntry(entries []cgroups.BlkioStatEntry) []types.BlkioStatEntry { out := make([]types.BlkioStatEntry, len(entries)) for i, re := range entries { out[i] = types.BlkioStatEntry{ Major: re.Major, Minor: re.Minor, Op: re.Op, Value: re.Value, } } return out } ================================================ FILE: vendor/github.com/docker/docker/daemon/stats_windows.go ================================================ package daemon import ( "github.com/docker/docker/api/types" "github.com/opencontainers/runc/libcontainer" ) // convertStatsToAPITypes converts the libcontainer.Stats to the api specific // structs. This is done to preserve API compatibility and versioning. func convertStatsToAPITypes(ls *libcontainer.Stats) *types.Stats { // TODO Windows. Refactor accordingly to fill in stats. s := &types.Stats{} return s } ================================================ FILE: vendor/github.com/docker/docker/daemon/stop.go ================================================ package daemon import "fmt" func (daemon *Daemon) ContainerStop(name string, seconds int) error { container, err := daemon.Get(name) if err != nil { return err } if !container.IsRunning() { return fmt.Errorf("Container already stopped") } if err := container.Stop(seconds); err != nil { return fmt.Errorf("Cannot stop container %s: %s\n", name, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/top.go ================================================ package daemon import ( "fmt" "os/exec" "strconv" "strings" "github.com/docker/docker/api/types" ) func (daemon *Daemon) ContainerTop(name string, psArgs string) (*types.ContainerProcessList, error) { if psArgs == "" { psArgs = "-ef" } container, err := daemon.Get(name) if err != nil { return nil, err } if !container.IsRunning() { return nil, fmt.Errorf("Container %s is not running", name) } pids, err := daemon.ExecutionDriver().GetPidsForContainer(container.ID) if err != nil { return nil, err } output, err := exec.Command("ps", strings.Split(psArgs, " ")...).Output() if err != nil { return nil, fmt.Errorf("Error running ps: %s", err) } procList := &types.ContainerProcessList{} lines := strings.Split(string(output), "\n") procList.Titles = strings.Fields(lines[0]) pidIndex := -1 for i, name := range procList.Titles { if name == "PID" { pidIndex = i } } if pidIndex == -1 { return nil, fmt.Errorf("Couldn't find PID field in ps output") } for _, line := range lines[1:] { if len(line) == 0 { continue } fields := strings.Fields(line) p, err := strconv.Atoi(fields[pidIndex]) if err != nil { return nil, fmt.Errorf("Unexpected pid '%s': %s", fields[pidIndex], err) } for _, pid := range pids { if pid == p { // Make sure number of fields equals number of header titles // merging "overhanging" fields process := fields[:len(procList.Titles)-1] process = append(process, strings.Join(fields[len(procList.Titles)-1:], " ")) procList.Processes = append(procList.Processes, process) } } } container.LogEvent("top") return procList, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/unpause.go ================================================ package daemon import "fmt" // ContainerUnpause unpauses a container func (daemon *Daemon) ContainerUnpause(name string) error { container, err := daemon.Get(name) if err != nil { return err } if err := container.Unpause(); err != nil { return fmt.Errorf("Cannot unpause container %s: %s", name, err) } return nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/utils_nounix.go ================================================ // +build !linux package daemon func selinuxSetDisabled() { } func selinuxFreeLxcContexts(label string) { } func selinuxEnabled() bool { return false } ================================================ FILE: vendor/github.com/docker/docker/daemon/utils_test.go ================================================ // +build linux package daemon import ( "testing" "github.com/docker/docker/runconfig" ) func TestMergeLxcConfig(t *testing.T) { kv := []runconfig.KeyValuePair{ {"lxc.cgroups.cpuset", "1,2"}, } hostConfig := &runconfig.HostConfig{ LxcConf: runconfig.NewLxcConfig(kv), } out, err := mergeLxcConfIntoOptions(hostConfig) if err != nil { t.Fatalf("Failed to merge Lxc Config: %s", err) } cpuset := out[0] if expected := "cgroups.cpuset=1,2"; cpuset != expected { t.Fatalf("expected %s got %s", expected, cpuset) } } ================================================ FILE: vendor/github.com/docker/docker/daemon/utils_unix.go ================================================ // +build linux package daemon import ( "errors" "fmt" "strings" "github.com/docker/docker/runconfig" "github.com/opencontainers/runc/libcontainer/selinux" ) func selinuxSetDisabled() { selinux.SetDisabled() } func selinuxFreeLxcContexts(label string) { selinux.FreeLxcContexts(label) } func selinuxEnabled() bool { return selinux.SelinuxEnabled() } func mergeLxcConfIntoOptions(hostConfig *runconfig.HostConfig) ([]string, error) { if hostConfig == nil { return nil, nil } out := []string{} // merge in the lxc conf options into the generic config map if lxcConf := hostConfig.LxcConf; lxcConf != nil { lxSlice := lxcConf.Slice() for _, pair := range lxSlice { // because lxc conf gets the driver name lxc.XXXX we need to trim it off // and let the lxc driver add it back later if needed if !strings.Contains(pair.Key, ".") { return nil, errors.New("Illegal Key passed into LXC Configurations") } parts := strings.SplitN(pair.Key, ".", 2) out = append(out, fmt.Sprintf("%s=%s", parts[1], pair.Value)) } } return out, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/volumes.go ================================================ package daemon import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/system" "github.com/docker/docker/runconfig" "github.com/docker/docker/volume" "github.com/docker/docker/volume/drivers" "github.com/docker/docker/volume/local" "github.com/opencontainers/runc/libcontainer/label" ) // ErrVolumeReadonly is used to signal an error when trying to copy data into // a volume mount that is not writable. var ErrVolumeReadonly = errors.New("mounted volume is marked read-only") type mountPoint struct { Name string Destination string Driver string RW bool Volume volume.Volume `json:"-"` Source string Relabel string } func (m *mountPoint) Setup() (string, error) { if m.Volume != nil { return m.Volume.Mount() } if len(m.Source) > 0 { if _, err := os.Stat(m.Source); err != nil { if !os.IsNotExist(err) { return "", err } if err := system.MkdirAll(m.Source, 0755); err != nil { return "", err } } return m.Source, nil } return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined") } // hasResource checks whether the given absolute path for a container is in // this mount point. If the relative path starts with `../` then the resource // is outside of this mount point, but we can't simply check for this prefix // because it misses `..` which is also outside of the mount, so check both. func (m *mountPoint) hasResource(absolutePath string) bool { relPath, err := filepath.Rel(m.Destination, absolutePath) return err == nil && relPath != ".." && !strings.HasPrefix(relPath, fmt.Sprintf("..%c", filepath.Separator)) } func (m *mountPoint) Path() string { if m.Volume != nil { return m.Volume.Path() } return m.Source } // BackwardsCompatible decides whether this mount point can be // used in old versions of Docker or not. // Only bind mounts and local volumes can be used in old versions of Docker. func (m *mountPoint) BackwardsCompatible() bool { return len(m.Source) > 0 || m.Driver == volume.DefaultDriverName } func parseBindMount(spec string, mountLabel string, config *runconfig.Config) (*mountPoint, error) { bind := &mountPoint{ RW: true, } arr := strings.Split(spec, ":") switch len(arr) { case 2: bind.Destination = arr[1] case 3: bind.Destination = arr[1] mode := arr[2] isValid, isRw := volume.ValidateMountMode(mode) if !isValid { return nil, fmt.Errorf("invalid mode for volumes-from: %s", mode) } bind.RW = isRw // Relabel will apply a SELinux label, if necessary bind.Relabel = mode default: return nil, fmt.Errorf("Invalid volume specification: %s", spec) } name, source, err := parseVolumeSource(arr[0]) if err != nil { return nil, err } if len(source) == 0 { bind.Driver = config.VolumeDriver if len(bind.Driver) == 0 { bind.Driver = volume.DefaultDriverName } } else { bind.Source = filepath.Clean(source) } bind.Name = name bind.Destination = filepath.Clean(bind.Destination) return bind, nil } func parseVolumesFrom(spec string) (string, string, error) { if len(spec) == 0 { return "", "", fmt.Errorf("malformed volumes-from specification: %s", spec) } specParts := strings.SplitN(spec, ":", 2) id := specParts[0] mode := "rw" if len(specParts) == 2 { mode = specParts[1] if isValid, _ := volume.ValidateMountMode(mode); !isValid { return "", "", fmt.Errorf("invalid mode for volumes-from: %s", mode) } } return id, mode, nil } func copyExistingContents(source, destination string) error { volList, err := ioutil.ReadDir(source) if err != nil { return err } if len(volList) > 0 { srcList, err := ioutil.ReadDir(destination) if err != nil { return err } if len(srcList) == 0 { // If the source volume is empty copy files from the root into the volume if err := chrootarchive.CopyWithTar(source, destination); err != nil { return err } } } return copyOwnership(source, destination) } // registerMountPoints initializes the container mount points with the configured volumes and bind mounts. // It follows the next sequence to decide what to mount in each final destination: // // 1. Select the previously configured mount points for the containers, if any. // 2. Select the volumes mounted from another containers. Overrides previously configured mount point destination. // 3. Select the bind mounts set by the client. Overrides previously configured mount point destinations. func (daemon *Daemon) registerMountPoints(container *Container, hostConfig *runconfig.HostConfig) error { binds := map[string]bool{} mountPoints := map[string]*mountPoint{} // 1. Read already configured mount points. for name, point := range container.MountPoints { mountPoints[name] = point } // 2. Read volumes from other containers. for _, v := range hostConfig.VolumesFrom { containerID, mode, err := parseVolumesFrom(v) if err != nil { return err } c, err := daemon.Get(containerID) if err != nil { return err } for _, m := range c.MountPoints { cp := &mountPoint{ Name: m.Name, Source: m.Source, RW: m.RW && volume.ReadWrite(mode), Driver: m.Driver, Destination: m.Destination, } if len(cp.Source) == 0 { v, err := createVolume(cp.Name, cp.Driver) if err != nil { return err } cp.Volume = v } mountPoints[cp.Destination] = cp } } // 3. Read bind mounts for _, b := range hostConfig.Binds { // #10618 bind, err := parseBindMount(b, container.MountLabel, container.Config) if err != nil { return err } if binds[bind.Destination] { return fmt.Errorf("Duplicate bind mount %s", bind.Destination) } if len(bind.Name) > 0 && len(bind.Driver) > 0 { // create the volume v, err := createVolume(bind.Name, bind.Driver) if err != nil { return err } bind.Volume = v bind.Source = v.Path() // Since this is just a named volume and not a typical bind, set to shared mode `z` if bind.Relabel == "" { bind.Relabel = "z" } } if err := label.Relabel(bind.Source, container.MountLabel, bind.Relabel); err != nil { return err } binds[bind.Destination] = true mountPoints[bind.Destination] = bind } // Keep backwards compatible structures bcVolumes := map[string]string{} bcVolumesRW := map[string]bool{} for _, m := range mountPoints { if m.BackwardsCompatible() { bcVolumes[m.Destination] = m.Path() bcVolumesRW[m.Destination] = m.RW } } container.Lock() container.MountPoints = mountPoints container.Volumes = bcVolumes container.VolumesRW = bcVolumesRW container.Unlock() return nil } // TODO Windows. Factor out as not relevant (as Windows daemon support not in pre-1.7) // verifyVolumesInfo ports volumes configured for the containers pre docker 1.7. // It reads the container configuration and creates valid mount points for the old volumes. func (daemon *Daemon) verifyVolumesInfo(container *Container) error { // Inspect old structures only when we're upgrading from old versions // to versions >= 1.7 and the MountPoints has not been populated with volumes data. if len(container.MountPoints) == 0 && len(container.Volumes) > 0 { for destination, hostPath := range container.Volumes { vfsPath := filepath.Join(daemon.root, "vfs", "dir") rw := container.VolumesRW != nil && container.VolumesRW[destination] if strings.HasPrefix(hostPath, vfsPath) { id := filepath.Base(hostPath) if err := migrateVolume(id, hostPath); err != nil { return err } container.addLocalMountPoint(id, destination, rw) } else { // Bind mount id, source, err := parseVolumeSource(hostPath) // We should not find an error here coming // from the old configuration, but who knows. if err != nil { return err } container.addBindMountPoint(id, source, destination, rw) } } } else if len(container.MountPoints) > 0 { // Volumes created with a Docker version >= 1.7. We verify integrity in case of data created // with Docker 1.7 RC versions that put the information in // DOCKER_ROOT/volumes/VOLUME_ID rather than DOCKER_ROOT/volumes/VOLUME_ID/_container_data. l, err := getVolumeDriver(volume.DefaultDriverName) if err != nil { return err } for _, m := range container.MountPoints { if m.Driver != volume.DefaultDriverName { continue } dataPath := l.(*local.Root).DataPath(m.Name) volumePath := filepath.Dir(dataPath) d, err := ioutil.ReadDir(volumePath) if err != nil { // If the volume directory doesn't exist yet it will be recreated, // so we only return the error when there is a different issue. if !os.IsNotExist(err) { return err } // Do not check when the volume directory does not exist. continue } if validVolumeLayout(d) { continue } if err := os.Mkdir(dataPath, 0755); err != nil { return err } // Move data inside the data directory for _, f := range d { oldp := filepath.Join(volumePath, f.Name()) newp := filepath.Join(dataPath, f.Name()) if err := os.Rename(oldp, newp); err != nil { logrus.Errorf("Unable to move %s to %s\n", oldp, newp) } } } return container.ToDisk() } return nil } func createVolume(name, driverName string) (volume.Volume, error) { vd, err := getVolumeDriver(driverName) if err != nil { return nil, err } return vd.Create(name) } func removeVolume(v volume.Volume) error { vd, err := getVolumeDriver(v.DriverName()) if err != nil { return nil } return vd.Remove(v) } func getVolumeDriver(name string) (volume.Driver, error) { if name == "" { name = volume.DefaultDriverName } return volumedrivers.Lookup(name) } func parseVolumeSource(spec string) (string, string, error) { if !filepath.IsAbs(spec) { return spec, "", nil } return "", spec, nil } ================================================ FILE: vendor/github.com/docker/docker/daemon/volumes_linux.go ================================================ // +build !windows package daemon import ( "os" "path/filepath" "sort" "strings" "github.com/docker/docker/daemon/execdriver" "github.com/docker/docker/pkg/system" "github.com/docker/docker/volume" "github.com/docker/docker/volume/local" ) // copyOwnership copies the permissions and uid:gid of the source file // into the destination file func copyOwnership(source, destination string) error { stat, err := system.Stat(source) if err != nil { return err } if err := os.Chown(destination, int(stat.Uid()), int(stat.Gid())); err != nil { return err } return os.Chmod(destination, os.FileMode(stat.Mode())) } func (container *Container) setupMounts() ([]execdriver.Mount, error) { var mounts []execdriver.Mount for _, m := range container.MountPoints { path, err := m.Setup() if err != nil { return nil, err } mounts = append(mounts, execdriver.Mount{ Source: path, Destination: m.Destination, Writable: m.RW, }) } mounts = sortMounts(mounts) return append(mounts, container.networkMounts()...), nil } func sortMounts(m []execdriver.Mount) []execdriver.Mount { sort.Sort(mounts(m)) return m } type mounts []execdriver.Mount func (m mounts) Len() int { return len(m) } func (m mounts) Less(i, j int) bool { return m.parts(i) < m.parts(j) } func (m mounts) Swap(i, j int) { m[i], m[j] = m[j], m[i] } func (m mounts) parts(i int) int { return len(strings.Split(filepath.Clean(m[i].Destination), string(os.PathSeparator))) } // migrateVolume links the contents of a volume created pre Docker 1.7 // into the location expected by the local driver. // It creates a symlink from DOCKER_ROOT/vfs/dir/VOLUME_ID to DOCKER_ROOT/volumes/VOLUME_ID/_container_data. // It preserves the volume json configuration generated pre Docker 1.7 to be able to // downgrade from Docker 1.7 to Docker 1.6 without losing volume compatibility. func migrateVolume(id, vfs string) error { l, err := getVolumeDriver(volume.DefaultDriverName) if err != nil { return err } newDataPath := l.(*local.Root).DataPath(id) fi, err := os.Stat(newDataPath) if err != nil && !os.IsNotExist(err) { return err } if fi != nil && fi.IsDir() { return nil } return os.Symlink(vfs, newDataPath) } // validVolumeLayout checks whether the volume directory layout // is valid to work with Docker post 1.7 or not. func validVolumeLayout(files []os.FileInfo) bool { if len(files) == 1 && files[0].Name() == local.VolumeDataPathName && files[0].IsDir() { return true } if len(files) != 2 { return false } for _, f := range files { if f.Name() == "config.json" || (f.Name() == local.VolumeDataPathName && f.Mode()&os.ModeSymlink == os.ModeSymlink) { // Old volume configuration, we ignore it continue } return false } return true } ================================================ FILE: vendor/github.com/docker/docker/daemon/volumes_linux_unit_test.go ================================================ // +build experimental package daemon import ( "testing" "github.com/docker/docker/runconfig" "github.com/docker/docker/volume" "github.com/docker/docker/volume/drivers" ) type fakeDriver struct{} func (fakeDriver) Name() string { return "fake" } func (fakeDriver) Create(name string) (volume.Volume, error) { return nil, nil } func (fakeDriver) Remove(v volume.Volume) error { return nil } func TestGetVolumeDriver(t *testing.T) { _, err := getVolumeDriver("missing") if err == nil { t.Fatal("Expected error, was nil") } volumedrivers.Register(fakeDriver{}, "fake") d, err := getVolumeDriver("fake") if err != nil { t.Fatal(err) } if d.Name() != "fake" { t.Fatalf("Expected fake driver, got %s\n", d.Name()) } } func TestParseBindMount(t *testing.T) { cases := []struct { bind string driver string expDest string expSource string expName string expDriver string mountLabel string expRW bool fail bool }{ {"/tmp:/tmp", "", "/tmp", "/tmp", "", "", "", true, false}, {"/tmp:/tmp:ro", "", "/tmp", "/tmp", "", "", "", false, false}, {"/tmp:/tmp:rw", "", "/tmp", "/tmp", "", "", "", true, false}, {"/tmp:/tmp:foo", "", "/tmp", "/tmp", "", "", "", false, true}, {"name:/tmp", "", "/tmp", "", "name", "local", "", true, false}, {"name:/tmp", "external", "/tmp", "", "name", "external", "", true, false}, {"name:/tmp:ro", "local", "/tmp", "", "name", "local", "", false, false}, {"local/name:/tmp:rw", "", "/tmp", "", "local/name", "local", "", true, false}, } for _, c := range cases { conf := &runconfig.Config{VolumeDriver: c.driver} m, err := parseBindMount(c.bind, c.mountLabel, conf) if c.fail { if err == nil { t.Fatalf("Expected error, was nil, for spec %s\n", c.bind) } continue } if m.Destination != c.expDest { t.Fatalf("Expected destination %s, was %s, for spec %s\n", c.expDest, m.Destination, c.bind) } if m.Source != c.expSource { t.Fatalf("Expected source %s, was %s, for spec %s\n", c.expSource, m.Source, c.bind) } if m.Name != c.expName { t.Fatalf("Expected name %s, was %s for spec %s\n", c.expName, m.Name, c.bind) } if m.Driver != c.expDriver { t.Fatalf("Expected driver %s, was %s, for spec %s\n", c.expDriver, m.Driver, c.bind) } if m.RW != c.expRW { t.Fatalf("Expected RW %v, was %v for spec %s\n", c.expRW, m.RW, c.bind) } } } ================================================ FILE: vendor/github.com/docker/docker/daemon/volumes_unit_test.go ================================================ package daemon import "testing" func TestParseVolumeFrom(t *testing.T) { cases := []struct { spec string expId string expMode string fail bool }{ {"", "", "", true}, {"foobar", "foobar", "rw", false}, {"foobar:rw", "foobar", "rw", false}, {"foobar:ro", "foobar", "ro", false}, {"foobar:baz", "", "", true}, } for _, c := range cases { id, mode, err := parseVolumesFrom(c.spec) if c.fail { if err == nil { t.Fatalf("Expected error, was nil, for spec %s\n", c.spec) } continue } if id != c.expId { t.Fatalf("Expected id %s, was %s, for spec %s\n", c.expId, id, c.spec) } if mode != c.expMode { t.Fatalf("Expected mode %s, was %s for spec %s\n", c.expMode, mode, c.spec) } } } ================================================ FILE: vendor/github.com/docker/docker/daemon/volumes_windows.go ================================================ // +build windows package daemon import ( "os" "github.com/docker/docker/daemon/execdriver" ) // Not supported on Windows func copyOwnership(source, destination string) error { return nil } func (container *Container) setupMounts() ([]execdriver.Mount, error) { return nil, nil } func migrateVolume(id, vfs string) error { return nil } func validVolumeLayout(files []os.FileInfo) bool { return true } ================================================ FILE: vendor/github.com/docker/docker/daemon/wait.go ================================================ package daemon import "time" func (daemon *Daemon) ContainerWait(name string, timeout time.Duration) (int, error) { container, err := daemon.Get(name) if err != nil { return -1, err } return container.WaitStop(timeout) } ================================================ FILE: vendor/github.com/docker/docker/docker/README.md ================================================ docker.go contains Docker's main function. This file provides first line CLI argument parsing and environment variable setting. ================================================ FILE: vendor/github.com/docker/docker/docker/client.go ================================================ // +build !daemon package main import ( "log" // see gh#8745, client needs to use go log pkg ) func mainDaemon() { log.Fatal("This is a client-only binary - running the Docker daemon is not supported.") } ================================================ FILE: vendor/github.com/docker/docker/docker/daemon.go ================================================ // +build daemon package main import ( "crypto/tls" "fmt" "io" "os" "path/filepath" "time" "github.com/Sirupsen/logrus" apiserver "github.com/docker/docker/api/server" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/cliconfig" "github.com/docker/docker/daemon" "github.com/docker/docker/daemon/logger" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/pidfile" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/timeutils" "github.com/docker/docker/pkg/tlsconfig" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) var ( daemonCfg = &daemon.Config{} registryCfg = ®istry.Options{} ) func init() { if daemonCfg.LogConfig.Config == nil { daemonCfg.LogConfig.Config = make(map[string]string) } daemonCfg.InstallFlags() registryCfg.InstallFlags() } func migrateKey() (err error) { // Migrate trust key if exists at ~/.docker/key.json and owned by current user oldPath := filepath.Join(cliconfig.ConfigDir(), defaultTrustKeyFile) newPath := filepath.Join(getDaemonConfDir(), defaultTrustKeyFile) if _, statErr := os.Stat(newPath); os.IsNotExist(statErr) && currentUserIsOwner(oldPath) { defer func() { // Ensure old path is removed if no error occurred if err == nil { err = os.Remove(oldPath) } else { logrus.Warnf("Key migration failed, key file not removed at %s", oldPath) } }() if err := system.MkdirAll(getDaemonConfDir(), os.FileMode(0644)); err != nil { return fmt.Errorf("Unable to create daemon configuration directory: %s", err) } newFile, err := os.OpenFile(newPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600) if err != nil { return fmt.Errorf("error creating key file %q: %s", newPath, err) } defer newFile.Close() oldFile, err := os.Open(oldPath) if err != nil { return fmt.Errorf("error opening key file %q: %s", oldPath, err) } defer oldFile.Close() if _, err := io.Copy(newFile, oldFile); err != nil { return fmt.Errorf("error copying key: %s", err) } logrus.Infof("Migrated key from %s to %s", oldPath, newPath) } return nil } func mainDaemon() { if utils.ExperimentalBuild() { logrus.Warn("Running experimental build") } if flag.NArg() != 0 { flag.Usage() return } logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: timeutils.RFC3339NanoFixed}) if err := setDefaultUmask(); err != nil { logrus.Fatalf("Failed to set umask: %v", err) } if len(daemonCfg.LogConfig.Config) > 0 { if err := logger.ValidateLogOpts(daemonCfg.LogConfig.Type, daemonCfg.LogConfig.Config); err != nil { logrus.Fatalf("Failed to set log opts: %v", err) } } var pfile *pidfile.PidFile if daemonCfg.Pidfile != "" { pf, err := pidfile.New(daemonCfg.Pidfile) if err != nil { logrus.Fatalf("Error starting daemon: %v", err) } pfile = pf defer func() { if err := pfile.Remove(); err != nil { logrus.Error(err) } }() } serverConfig := &apiserver.ServerConfig{ Logging: true, EnableCors: daemonCfg.EnableCors, CorsHeaders: daemonCfg.CorsHeaders, Version: dockerversion.VERSION, } serverConfig = setPlatformServerConfig(serverConfig, daemonCfg) if *flTLS { if *flTLSVerify { tlsOptions.ClientAuth = tls.RequireAndVerifyClientCert } tlsConfig, err := tlsconfig.Server(tlsOptions) if err != nil { logrus.Fatal(err) } serverConfig.TLSConfig = tlsConfig } api := apiserver.New(serverConfig) // The serve API routine never exits unless an error occurs // We need to start it as a goroutine and wait on it so // daemon doesn't exit serveAPIWait := make(chan error) go func() { if err := api.ServeApi(flHosts); err != nil { logrus.Errorf("ServeAPI error: %v", err) serveAPIWait <- err return } serveAPIWait <- nil }() if err := migrateKey(); err != nil { logrus.Fatal(err) } daemonCfg.TrustKeyPath = *flTrustKey registryService := registry.NewService(registryCfg) d, err := daemon.NewDaemon(daemonCfg, registryService) if err != nil { if pfile != nil { if err := pfile.Remove(); err != nil { logrus.Error(err) } } logrus.Fatalf("Error starting daemon: %v", err) } logrus.Info("Daemon has completed initialization") logrus.WithFields(logrus.Fields{ "version": dockerversion.VERSION, "commit": dockerversion.GITCOMMIT, "execdriver": d.ExecutionDriver().Name(), "graphdriver": d.GraphDriver().String(), }).Info("Docker daemon") signal.Trap(func() { api.Close() <-serveAPIWait shutdownDaemon(d, 15) if pfile != nil { if err := pfile.Remove(); err != nil { logrus.Error(err) } } }) // after the daemon is done setting up we can tell the api to start // accepting connections with specified daemon api.AcceptConnections(d) // Daemon is fully initialized and handling API traffic // Wait for serve API to complete errAPI := <-serveAPIWait shutdownDaemon(d, 15) if errAPI != nil { if pfile != nil { if err := pfile.Remove(); err != nil { logrus.Error(err) } } logrus.Fatalf("Shutting down due to ServeAPI error: %v", errAPI) } } // shutdownDaemon just wraps daemon.Shutdown() to handle a timeout in case // d.Shutdown() is waiting too long to kill container or worst it's // blocked there func shutdownDaemon(d *daemon.Daemon, timeout time.Duration) { ch := make(chan struct{}) go func() { d.Shutdown() close(ch) }() select { case <-ch: logrus.Debug("Clean shutdown succeded") case <-time.After(timeout * time.Second): logrus.Error("Force shutdown daemon") } } ================================================ FILE: vendor/github.com/docker/docker/docker/daemon_unix.go ================================================ // +build daemon,!windows package main import ( "fmt" "os" "syscall" apiserver "github.com/docker/docker/api/server" "github.com/docker/docker/daemon" "github.com/docker/docker/pkg/system" _ "github.com/docker/docker/daemon/execdriver/lxc" _ "github.com/docker/docker/daemon/execdriver/native" ) func setPlatformServerConfig(serverConfig *apiserver.ServerConfig, daemonCfg *daemon.Config) *apiserver.ServerConfig { serverConfig.SocketGroup = daemonCfg.SocketGroup return serverConfig } // currentUserIsOwner checks whether the current user is the owner of the given // file. func currentUserIsOwner(f string) bool { if fileInfo, err := system.Stat(f); err == nil && fileInfo != nil { if int(fileInfo.Uid()) == os.Getuid() { return true } } return false } // setDefaultUmask sets the umask to 0022 to avoid problems // caused by custom umask func setDefaultUmask() error { desiredUmask := 0022 syscall.Umask(desiredUmask) if umask := syscall.Umask(desiredUmask); umask != desiredUmask { return fmt.Errorf("failed to set umask: expected %#o, got %#o", desiredUmask, umask) } return nil } ================================================ FILE: vendor/github.com/docker/docker/docker/daemon_windows.go ================================================ // +build daemon package main import ( apiserver "github.com/docker/docker/api/server" "github.com/docker/docker/daemon" ) func setPlatformServerConfig(serverConfig *apiserver.ServerConfig, daemonCfg *daemon.Config) *apiserver.ServerConfig { return serverConfig } // currentUserIsOwner checks whether the current user is the owner of the given // file. func currentUserIsOwner(f string) bool { return false } // setDefaultUmask doesn't do anything on windows func setDefaultUmask() error { return nil } ================================================ FILE: vendor/github.com/docker/docker/docker/docker.go ================================================ package main import ( "crypto/tls" "fmt" "os" "runtime" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/client" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/cliconfig" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/term" "github.com/docker/docker/pkg/tlsconfig" "github.com/docker/docker/utils" ) const ( defaultTrustKeyFile = "key.json" defaultCaFile = "ca.pem" defaultKeyFile = "key.pem" defaultCertFile = "cert.pem" ) func main() { if reexec.Init() { return } // Set terminal emulation based on platform as required. stdin, stdout, stderr := term.StdStreams() initLogging(stderr) flag.Parse() // FIXME: validate daemon flags here if *flVersion { showVersion() return } if *flConfigDir != "" { cliconfig.SetConfigDir(*flConfigDir) } if *flLogLevel != "" { lvl, err := logrus.ParseLevel(*flLogLevel) if err != nil { fmt.Fprintf(os.Stderr, "Unable to parse logging level: %s\n", *flLogLevel) os.Exit(1) } setLogLevel(lvl) } else { setLogLevel(logrus.InfoLevel) } if *flDebug { os.Setenv("DEBUG", "1") setLogLevel(logrus.DebugLevel) } if len(flHosts) == 0 { defaultHost := os.Getenv("DOCKER_HOST") if defaultHost == "" || *flDaemon { if runtime.GOOS != "windows" { // If we do not have a host, default to unix socket defaultHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket) } else { // If we do not have a host, default to TCP socket on Windows defaultHost = fmt.Sprintf("tcp://%s:%d", opts.DefaultHTTPHost, opts.DefaultHTTPPort) } } defaultHost, err := opts.ValidateHost(defaultHost) if err != nil { if *flDaemon { logrus.Fatal(err) } else { fmt.Fprint(os.Stderr, err) } os.Exit(1) } flHosts = append(flHosts, defaultHost) } setDefaultConfFlag(flTrustKey, defaultTrustKeyFile) // Regardless of whether the user sets it to true or false, if they // specify --tlsverify at all then we need to turn on tls // *flTlsVerify can be true even if not set due to DOCKER_TLS_VERIFY env var, so we need to check that here as well if flag.IsSet("-tlsverify") || *flTLSVerify { *flTLS = true } if *flDaemon { if *flHelp { flag.Usage() return } mainDaemon() return } // From here on, we assume we're a client, not a server. if len(flHosts) > 1 { fmt.Fprintf(os.Stderr, "Please specify only one -H") os.Exit(0) } protoAddrParts := strings.SplitN(flHosts[0], "://", 2) var tlsConfig *tls.Config if *flTLS { tlsOptions.InsecureSkipVerify = !*flTLSVerify if !flag.IsSet("-tlscert") { if _, err := os.Stat(tlsOptions.CertFile); os.IsNotExist(err) { tlsOptions.CertFile = "" } } if !flag.IsSet("-tlskey") { if _, err := os.Stat(tlsOptions.KeyFile); os.IsNotExist(err) { tlsOptions.KeyFile = "" } } var err error tlsConfig, err = tlsconfig.Client(tlsOptions) if err != nil { fmt.Fprintln(stderr, err) os.Exit(1) } } cli := client.NewDockerCli(stdin, stdout, stderr, *flTrustKey, protoAddrParts[0], protoAddrParts[1], tlsConfig) if err := cli.Cmd(flag.Args()...); err != nil { if sterr, ok := err.(client.StatusError); ok { if sterr.Status != "" { fmt.Fprintln(cli.Err(), sterr.Status) os.Exit(1) } os.Exit(sterr.StatusCode) } fmt.Fprintln(cli.Err(), err) os.Exit(1) } } func showVersion() { if utils.ExperimentalBuild() { fmt.Printf("Docker version %s, build %s, experimental\n", dockerversion.VERSION, dockerversion.GITCOMMIT) } else { fmt.Printf("Docker version %s, build %s\n", dockerversion.VERSION, dockerversion.GITCOMMIT) } } ================================================ FILE: vendor/github.com/docker/docker/docker/docker_windows.go ================================================ package main import ( _ "github.com/docker/docker/autogen/winresources" ) ================================================ FILE: vendor/github.com/docker/docker/docker/flags.go ================================================ package main import ( "fmt" "os" "path/filepath" "runtime" "sort" "github.com/docker/docker/cliconfig" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/tlsconfig" ) type command struct { name string description string } type byName []command func (a byName) Len() int { return len(a) } func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byName) Less(i, j int) bool { return a[i].name < a[j].name } var ( dockerCertPath = os.Getenv("DOCKER_CERT_PATH") dockerTlSVerify = os.Getenv("DOCKER_TLS_VERIFY") != "" dockerCommands = []command{ {"attach", "Attach to a running container"}, {"build", "Build an image from a Dockerfile"}, {"commit", "Create a new image from a container's changes"}, {"cp", "Copy files/folders from a container to a HOSTDIR or to STDOUT"}, {"create", "Create a new container"}, {"diff", "Inspect changes on a container's filesystem"}, {"events", "Get real time events from the server"}, {"exec", "Run a command in a running container"}, {"export", "Export a container's filesystem as a tar archive"}, {"history", "Show the history of an image"}, {"images", "List images"}, {"import", "Import the contents from a tarball to create a filesystem image"}, {"info", "Display system-wide information"}, {"inspect", "Return low-level information on a container or image"}, {"kill", "Kill a running container"}, {"load", "Load an image from a tar archive or STDIN"}, {"login", "Register or log in to a Docker registry"}, {"logout", "Log out from a Docker registry"}, {"logs", "Fetch the logs of a container"}, {"port", "List port mappings or a specific mapping for the CONTAINER"}, {"pause", "Pause all processes within a container"}, {"ps", "List containers"}, {"pull", "Pull an image or a repository from a registry"}, {"push", "Push an image or a repository to a registry"}, {"rename", "Rename a container"}, {"restart", "Restart a running container"}, {"rm", "Remove one or more containers"}, {"rmi", "Remove one or more images"}, {"run", "Run a command in a new container"}, {"save", "Save an image(s) to a tar archive"}, {"search", "Search the Docker Hub for images"}, {"start", "Start one or more stopped containers"}, {"stats", "Display a live stream of container(s) resource usage statistics"}, {"stop", "Stop a running container"}, {"tag", "Tag an image into a repository"}, {"top", "Display the running processes of a container"}, {"unpause", "Unpause all processes within a container"}, {"version", "Show the Docker version information"}, {"wait", "Block until a container stops, then print its exit code"}, } ) func init() { if dockerCertPath == "" { dockerCertPath = cliconfig.ConfigDir() } } func getDaemonConfDir() string { // TODO: update for Windows daemon if runtime.GOOS == "windows" { return cliconfig.ConfigDir() } return "/etc/docker" } var ( flConfigDir = flag.String([]string{"-config"}, cliconfig.ConfigDir(), "Location of client config files") flVersion = flag.Bool([]string{"v", "-version"}, false, "Print version information and quit") flDaemon = flag.Bool([]string{"d", "-daemon"}, false, "Enable daemon mode") flDebug = flag.Bool([]string{"D", "-debug"}, false, "Enable debug mode") flLogLevel = flag.String([]string{"l", "-log-level"}, "info", "Set the logging level") flTLS = flag.Bool([]string{"-tls"}, false, "Use TLS; implied by --tlsverify") flHelp = flag.Bool([]string{"h", "-help"}, false, "Print usage") flTLSVerify = flag.Bool([]string{"-tlsverify"}, dockerTlSVerify, "Use TLS and verify the remote") // these are initialized in init() below since their default values depend on dockerCertPath which isn't fully initialized until init() runs tlsOptions tlsconfig.Options flTrustKey *string flHosts []string ) func setDefaultConfFlag(flag *string, def string) { if *flag == "" { if *flDaemon { *flag = filepath.Join(getDaemonConfDir(), def) } else { *flag = filepath.Join(cliconfig.ConfigDir(), def) } } } func init() { var placeholderTrustKey string // TODO use flag flag.String([]string{"i", "-identity"}, "", "Path to libtrust key file") flTrustKey = &placeholderTrustKey flag.StringVar(&tlsOptions.CAFile, []string{"-tlscacert"}, filepath.Join(dockerCertPath, defaultCaFile), "Trust certs signed only by this CA") flag.StringVar(&tlsOptions.CertFile, []string{"-tlscert"}, filepath.Join(dockerCertPath, defaultCertFile), "Path to TLS certificate file") flag.StringVar(&tlsOptions.KeyFile, []string{"-tlskey"}, filepath.Join(dockerCertPath, defaultKeyFile), "Path to TLS key file") opts.HostListVar(&flHosts, []string{"H", "-host"}, "Daemon socket(s) to connect to") flag.Usage = func() { fmt.Fprint(os.Stdout, "Usage: docker [OPTIONS] COMMAND [arg...]\n\nA self-sufficient runtime for containers.\n\nOptions:\n") flag.CommandLine.SetOutput(os.Stdout) flag.PrintDefaults() help := "\nCommands:\n" sort.Sort(byName(dockerCommands)) for _, cmd := range dockerCommands { help += fmt.Sprintf(" %-10.10s%s\n", cmd.name, cmd.description) } help += "\nRun 'docker COMMAND --help' for more information on a command." fmt.Fprintf(os.Stdout, "%s\n", help) } } ================================================ FILE: vendor/github.com/docker/docker/docker/log.go ================================================ package main import ( "github.com/Sirupsen/logrus" "io" ) func setLogLevel(lvl logrus.Level) { logrus.SetLevel(lvl) } func initLogging(stderr io.Writer) { logrus.SetOutput(stderr) } ================================================ FILE: vendor/github.com/docker/docker/dockerinit/dockerinit.go ================================================ package main import ( _ "github.com/docker/docker/daemon/execdriver/lxc" _ "github.com/docker/docker/daemon/execdriver/native" "github.com/docker/docker/pkg/reexec" ) func main() { // Running in init mode reexec.Init() } ================================================ FILE: vendor/github.com/docker/docker/docs/.gitignore ================================================ # avoid commiting the awsconfig file used for releases awsconfig ================================================ FILE: vendor/github.com/docker/docker/docs/Dockerfile ================================================ FROM docs/base:latest MAINTAINER Mary Anthony (@moxiegirl) # To get the git info for this repo COPY . /src COPY . /docs/content/ WORKDIR /docs/content RUN /docs/content/touch-up.sh WORKDIR /docs ================================================ FILE: vendor/github.com/docker/docker/docs/Makefile ================================================ .PHONY: all binary build cross default docs docs-build docs-shell shell test test-unit test-integration test-integration-cli test-docker-py validate # env vars passed through directly to Docker's build scripts # to allow things like `make DOCKER_CLIENTONLY=1 binary` easily # `docs/sources/contributing/devenvironment.md ` and `project/PACKAGERS.md` have some limited documentation of some of these DOCKER_ENVS := \ -e BUILDFLAGS \ -e DOCKER_CLIENTONLY \ -e DOCKER_EXECDRIVER \ -e DOCKER_GRAPHDRIVER \ -e TESTDIRS \ -e TESTFLAGS \ -e TIMEOUT # note: we _cannot_ add "-e DOCKER_BUILDTAGS" here because even if it's unset in the shell, that would shadow the "ENV DOCKER_BUILDTAGS" set in our Dockerfile, which is very important for our official builds # to allow `make DOCSDIR=docs docs-shell` (to create a bind mount in docs) DOCS_MOUNT := $(if $(DOCSDIR),-v $(CURDIR)/$(DOCSDIR):/$(DOCSDIR)) # to allow `make DOCSPORT=9000 docs` DOCSPORT := 8000 # Get the IP ADDRESS DOCKER_IP=$(shell python -c "import urlparse ; print urlparse.urlparse('$(DOCKER_HOST)').hostname or ''") HUGO_BASE_URL=$(shell test -z "$(DOCKER_IP)" && echo localhost || echo "$(DOCKER_IP)") HUGO_BIND_IP=0.0.0.0 GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null) DOCKER_IMAGE := docker$(if $(GIT_BRANCH),:$(GIT_BRANCH)) DOCKER_DOCS_IMAGE := docs-base$(if $(GIT_BRANCH),:$(GIT_BRANCH)) DOCKER_RUN_DOCS := docker run --rm -it $(DOCS_MOUNT) -e AWS_S3_BUCKET -e NOCACHE # for some docs workarounds (see below in "docs-build" target) GITCOMMIT := $(shell git rev-parse --short HEAD 2>/dev/null) default: docs docs: docs-build $(DOCKER_RUN_DOCS) -p $(if $(DOCSPORT),$(DOCSPORT):)8000 -e DOCKERHOST "$(DOCKER_DOCS_IMAGE)" hugo server --port=$(DOCSPORT) --baseUrl=$(HUGO_BASE_URL) --bind=$(HUGO_BIND_IP) docs-draft: docs-build $(DOCKER_RUN_DOCS) -p $(if $(DOCSPORT),$(DOCSPORT):)8000 -e DOCKERHOST "$(DOCKER_DOCS_IMAGE)" hugo server --buildDrafts="true" --port=$(DOCSPORT) --baseUrl=$(HUGO_BASE_URL) --bind=$(HUGO_BIND_IP) docs-shell: docs-build $(DOCKER_RUN_DOCS) -p $(if $(DOCSPORT),$(DOCSPORT):)8000 "$(DOCKER_DOCS_IMAGE)" bash docs-build: # ( git remote | grep -v upstream ) || git diff --name-status upstream/release..upstream/docs ./ > ./changed-files # echo "$(GIT_BRANCH)" > GIT_BRANCH # echo "$(AWS_S3_BUCKET)" > AWS_S3_BUCKET # echo "$(GITCOMMIT)" > GITCOMMIT docker build -t "$(DOCKER_DOCS_IMAGE)" . ================================================ FILE: vendor/github.com/docker/docker/docs/README.md ================================================ # Docker Documentation The source for Docker documentation is in this directory. Our documentation uses extended Markdown, as implemented by [MkDocs](http://mkdocs.org). The current release of the Docker documentation resides on [https://docs.docker.com](https://docs.docker.com). ## Understanding the documentation branches and processes Docker has two primary branches for documentation: | Branch | Description | URL (published via commit-hook) | |----------|--------------------------------|------------------------------------------------------------------------------| | `docs` | Official release documentation | [https://docs.docker.com](https://docs.docker.com) | | `master` | Merged but unreleased development work | [http://docs.master.dockerproject.org](http://docs.master.dockerproject.org) | Additions and updates to upcoming releases are made in a feature branch off of the `master` branch. The Docker maintainers also support a `docs` branch that contains the last release of documentation. After a release, documentation updates are continually merged into `master` as they occur. This work includes new documentation for forthcoming features, bug fixes, and other updates. Docker's CI system automatically builds and updates the `master` documentation after each merge and posts it to [http://docs.master.dockerproject.org](http://docs.master.dockerproject.org). Periodically, the Docker maintainers update `docs.docker.com` between official releases of Docker. They do this by cherry-picking commits from `master`, merging them into `docs`, and then publishing the result. In the rare case where a change is not forward-compatible, changes may be made on other branches by special arrangement with the Docker maintainers. ### Quickstart for documentation contributors If you are a new or beginner contributor, we encourage you to read through the [our detailed contributors guide](https://docs.docker.com/project/who-written-for/). The guide explains in detail, with examples, how to contribute. If you are an experienced contributor this quickstart should be enough to get you started. The following is the essential workflow for contributing to the documentation: 1. Fork the `docker/docker` repository. 2. Clone the repository to your local machine. 3. Select an issue from `docker/docker` to work on or submit a proposal of your own. 4. Create a feature branch from `master` in which to work. By basing from `master` your work is automatically included in the next release. It also allows docs maintainers to easily cherry-pick your changes into the `docs` release branch. 4. Modify existing or add new `.md` files to the `docs` directory. If you add a new document (`.md`) file, you must also add it to the appropriate section of the `docs/mkdocs.yml` file in this repository. 5. As you work, build the documentation site locally to see your changes. The `docker/docker` repository contains a `Dockerfile` and a `Makefile`. Together, these create a development environment in which you can build and run a container running the Docker documentation website. To build the documentation site, enter `make docs` at the root of your `docker/docker` fork: $ make docs .... (lots of output) .... docker run --rm -it -e AWS_S3_BUCKET -p 8000:8000 "docker-docs:master" mkdocs serve Running at: http://0.0.0.0:8000/ Live reload enabled. Hold ctrl+c to quit. The build creates an image containing all the required tools, adds the local `docs/` directory and generates the HTML files. Then, it runs a Docker container with this image. The container exposes port 8000 on the localhost so that you can connect and see your changes. If you are running Boot2Docker, use the `boot2docker ip` to get the address of your server. 6. Check your writing for style and mechanical errors. Use our [documentation style guide](https://docs.docker.com/project/doc-style/) to check style. There are several [good grammar and spelling online checkers](http://www.hemingwayapp.com/) that can check your writing mechanics. 7. Squash your commits on your branch. 8. Make a pull request from your fork back to Docker's `master` branch. 9. Work with the reviewers until your change is approved and merged. ### Debugging and testing If you have any issues you need to debug, you can use `make docs-shell` and then run `mkdocs serve`. You can use `make docs-test` to generate a report of missing links that are referenced in the documentation—there should be none. ## Style guide If you have questions about how to write for Docker's documentation, please see the [style guide](project/doc-style.md). The style guide provides guidance about grammar, syntax, formatting, styling, language, or tone. If something isn't clear in the guide, please submit an issue to let us know or submit a pull request to help us improve it. ## Publishing documentation (for Docker maintainers) To publish Docker's documentation you need to have Docker up and running on your machine. You'll also need a `docs/awsconfig` file containing the settings you need to access the AWS bucket you'll be deploying to. The process for publishing is to build first to an AWS bucket, verify the build, and then publish the final release. 1. Have Docker installed and running on your machine. 2. Ask the core maintainers for the `awsconfig` file. 3. Copy the `awsconfig` file to the `docs/` directory. The `awsconfig` file contains the profiles of the S3 buckets for our documentation sites. (If needed, the release script creates an S3 bucket and pushes the files to it.) Each profile has this format: [profile dowideit-docs] aws_access_key_id = IHOIUAHSIDH234rwf.... aws_secret_access_key = OIUYSADJHLKUHQWIUHE...... region = ap-southeast-2 The `profile` name must be the same as the name of the bucket you are deploying to. 4. Call the `make` from the `docker` directory. $ make AWS_S3_BUCKET=dowideit-docs docs-release This publishes _only_ to the `http://bucket-url/v1.2/` version of the documentation. 5. If you're publishing the current release's documentation, you need to also update the root docs pages by running $ make AWS_S3_BUCKET=dowideit-docs BUILD_ROOT=yes docs-release ### Errors publishing using Boot2Docker Sometimes, in a Boot2Docker environment, the publishing procedure returns this error: Post http:///var/run/docker.sock/build?rm=1&t=docker-docs%3Apost-1.2.0-docs_update-2: dial unix /var/run/docker.sock: no such file or directory. If this happens, set the Docker host. Run the following command to set the variables in your shell: $ eval "$(boot2docker shellinit)" ## Cherry-picking documentation changes to update an existing release. Whenever the core team makes a release, they publish the documentation based on the `release` branch. At that time, the `release` branch is copied into the `docs` branch. The documentation team makes updates between Docker releases by cherry-picking changes from `master` into any of the documentation branches. Typically, we cherry-pick into the `docs` branch. For example, to update the current release's docs, do the following: 1. Go to your `docker/docker` fork and get the latest from master. $ git fetch upstream 2. Checkout a new branch based on `upstream/docs`. You should give your new branch a descriptive name. $ git checkout -b post-1.2.0-docs-update-1 upstream/docs 3. In a browser window, open [https://github.com/docker/docker/commits/master]. 4. Locate the merges you want to publish. You should only cherry-pick individual commits; do not cherry-pick merge commits. To minimize merge conflicts, start with the oldest commit and work your way forward in time. 5. Copy the commit SHA from GitHub. 6. Cherry-pick the commit. $ git cherry-pick -x fe845c4 7. Repeat until you have cherry-picked everything you want to merge. 8. Push your changes to your fork. $ git push origin post-1.2.0-docs-update-1 9. Make a pull request to merge into the `docs` branch. Do __NOT__ merge into `master`. 10. Have maintainers review your pull request. 11. Once the PR has the needed "LGTMs", merge it on GitHub. 12. Return to your local fork and make sure you are still on the `docs` branch. $ git checkout docs 13. Fetch your merged pull request from `docs`. $ git fetch upstream/docs 14. Ensure your branch is clean and set to the latest. $ git reset --hard upstream/docs 15. Copy the `awsconfig` file into the `docs` directory. 16. Make the beta documentation $ make AWS_S3_BUCKET=beta-docs.docker.io BUILD_ROOT=yes docs-release 17. Open [the beta website](http://beta-docs.docker.io.s3-website-us-west-2.amazonaws.com/) site and make sure what you published is correct. 19. When you're happy with your content, publish the docs to our live site: $ make AWS_S3_BUCKET=docs.docker.com BUILD_ROOT=yes DISTRIBUTION_ID=C2K6......FL2F docs-release 20. Test the uncached version of the live docs at [http://docs.docker.com.s3-website-us-east-1.amazonaws.com/] ### Caching and the docs New docs do not appear live on the site until the cache (a complex, distributed CDN system) is flushed. The `make docs-release` command flushes the cache _if_ the `DISTRIBUTION_ID` is set to the Cloudfront distribution ID. The cache flush can take at least 15 minutes to run and you can check its progress with the CDN Cloudfront Purge Tool Chrome app. ## Removing files from the docs.docker.com site Sometimes it becomes necessary to remove files from the historical published documentation. The most reliable way to do this is to do it directly using `aws s3` commands running in a docs container: Start the docs container like `make docs-shell`, but bind mount in your `awsconfig`: ``` docker run --rm -it -v $(CURDIR)/docs/awsconfig:/docs/awsconfig docker-docs:master bash ``` and then the following example shows deleting 2 documents from s3, and then requesting the CloudFlare cache to invalidate them: ``` export BUCKET BUCKET=docs.docker.com export AWS_CONFIG_FILE=$(pwd)/awsconfig aws s3 --profile $BUCKET ls s3://$BUCKET aws s3 --profile $BUCKET rm s3://$BUCKET/v1.0/reference/api/docker_io_oauth_api/index.html aws s3 --profile $BUCKET rm s3://$BUCKET/v1.1/reference/api/docker_io_oauth_api/index.html aws configure set preview.cloudfront true export DISTRIBUTION_ID=YUTIYUTIUTIUYTIUT aws cloudfront create-invalidation --profile docs.docker.com --distribution-id $DISTRIBUTION_ID --invalidation-batch '{"Paths":{"Quantity":1, "Items":["/v1.0/reference/api/docker_io_oauth_api/"]},"CallerReference":"6Mar2015sventest1"}' aws cloudfront create-invalidation --profile docs.docker.com --distribution-id $DISTRIBUTION_ID --invalidation-batch '{"Paths":{"Quantity":1, "Items":["/v1.1/reference/api/docker_io_oauth_api/"]},"CallerReference":"6Mar2015sventest1"}' ``` ### Generate the man pages For information on generating man pages (short for manual page), see [the man page directory](https://github.com/docker/docker/tree/master/docker) in this project. ================================================ FILE: vendor/github.com/docker/docker/docs/article-img/ipv6_basic_host_config.gliffy ================================================ {"contentType":"application/gliffy+json","version":"1.3","stage":{"background":"#FFFFFF","width":414,"height":127,"nodeIndex":173,"autoFit":true,"exportBorder":false,"gridOn":false,"snapToGrid":false,"drawingGuidesOn":false,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"maxWidth":5000,"maxHeight":5000,"themeData":null,"viewportType":"default","fitBB":{"min":{"x":8.5,"y":0.5},"max":{"x":413.75,"y":126.5}},"objects":[{"x":6.5,"y":106.0,"rotation":0.0,"id":9,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":20,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":19.5,"y":9.0,"rotation":0.0,"id":7,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":19,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":31.5,"y":23.5,"rotation":0.0,"id":4,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":16,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":5,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":11.75,"y":0.5,"rotation":0.0,"id":60,"width":402.0,"height":126.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":2,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":146.5,"y":83.0,"rotation":0.0,"id":164,"width":249.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":44,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:1::/64 dev docker0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":146.5,"y":27.5,"rotation":0.0,"id":73,"width":249.0,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":35,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]}],"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#fff2cc","stroke":"#333333","strokeWidth":2,"dashStyle":"2.0,2.0","gradient":true,"shadow":true}},"lineStyles":{"global":{"stroke":"#d9d9d9"}},"textStyles":{"global":{"size":"12px","color":"#b7b7b7"}}},"metadata":{"title":"untitled","revision":0,"exportBorder":false,"loadPosition":"default","libraries":["com.gliffy.libraries.basic.basic_v1.default","com.gliffy.libraries.flowchart.flowchart_v1.default","com.gliffy.libraries.swimlanes.swimlanes_v1.default","com.gliffy.libraries.uml.uml_v2.class","com.gliffy.libraries.uml.uml_v2.sequence","com.gliffy.libraries.uml.uml_v2.activity","com.gliffy.libraries.erd.erd_v1.default","com.gliffy.libraries.ui.ui_v3.containers_content","com.gliffy.libraries.ui.ui_v3.forms_controls","com.gliffy.libraries.images"],"autosaveDisabled":false},"embeddedResources":{"index":0,"resources":[]}} ================================================ FILE: vendor/github.com/docker/docker/docs/article-img/ipv6_ndp_proxying.gliffy ================================================ {"contentType":"application/gliffy+json","version":"1.3","stage":{"background":"#FFFFFF","width":616,"height":438,"nodeIndex":207,"autoFit":true,"exportBorder":false,"gridOn":false,"snapToGrid":false,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"maxWidth":5000,"maxHeight":5000,"themeData":null,"viewportType":"default","fitBB":{"min":{"x":3,"y":-7.75},"max":{"x":615.5,"y":437.5}},"objects":[{"x":173.0,"y":117.0,"rotation":0.0,"id":190,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":30,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"py":1.0,"px":0.7071067811865476}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":186,"py":0.0,"px":0.2928932188134524}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":"4.0,4.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[120.21067811865476,-7.0],[335.78932188134524,57.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":195.0,"y":117.0,"rotation":0.0,"id":83,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":23,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":222.5,"y":35.0,"rotation":0.0,"id":0,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":7,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#fff2cc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":1,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Router

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":26.0,"y":109.0,"rotation":0.0,"id":33,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":6,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"py":0.9999999999999998,"px":0.29289321881345254}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":2,"py":0.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[225.78932188134524,0.9999999999999858],[57.710678118654755,65.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":20.289321881345245,"y":150.0,"rotation":0.0,"id":32,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":5,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"py":0.0,"px":0.2928932188134524}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":0,"py":1.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[333.5,24.5],[272.9213562373095,-40.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":271.0,"y":37.0,"rotation":0.0,"id":89,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":1,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#d9d9d9","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[1.5,-2.0],[1.5,-21.125],[1.5,-21.125],[1.5,-40.25]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[]},{"x":151.0,"y":115.0,"rotation":0.0,"id":183,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":0,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":0,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":179,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[121.5,-5.0],[62.5,59.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":455.5,"y":257.0,"rotation":0.0,"id":200,"width":150.0,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":200,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":5,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

expected Container location

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":467.5,"y":156.0,"rotation":0.0,"id":185,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":29,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::c00y/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":479.5,"y":174.5,"rotation":0.0,"id":186,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":27,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#e2e2e2","gradient":false,"dashStyle":"2,2","dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":187,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container x

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":151.5,"y":156.0,"rotation":0.0,"id":178,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":26,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::b001/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":163.5,"y":174.5,"rotation":0.0,"id":179,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":24,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":180,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":299.5,"y":257.0,"rotation":0.0,"id":9,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":15,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":317.5,"y":156.0,"rotation":0.0,"id":7,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":14,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::c001/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":1.0,"y":156.0,"rotation":0.0,"id":6,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":13,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::a001/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":324.5,"y":174.5,"rotation":0.0,"id":4,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":11,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":5,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host3

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":13.0,"y":174.5,"rotation":0.0,"id":2,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":9,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":3,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":-142.5,"y":118.5,"rotation":0.0,"id":31,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":4,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"py":1.0,"px":0.7071067811865476}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":25,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[537.7106781186548,131.0],[602.0,204.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":-181.5,"y":122.5,"rotation":0.0,"id":30,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":3,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":4,"py":0.9999999999999998,"px":0.29289321881345254}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":27,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[535.2893218813452,127.0],[473.0,200.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":386.0,"y":306.0,"rotation":0.0,"id":78,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":22,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::c00a/125

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":218.0,"y":306.0,"rotation":0.0,"id":77,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":21,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8::c009/125

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":409.5,"y":323.0,"rotation":0.0,"id":25,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":18,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":26,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":241.5,"y":323.0,"rotation":0.0,"id":27,"width":99.99999999999999,"height":99.99999999999999,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":16,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":28,"width":95.99999999999999,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":207.75,"y":297.5,"rotation":0.0,"id":58,"width":339.75,"height":140.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":2,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]}],"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#e2e2e2","stroke":"#333333","strokeWidth":2,"dashStyle":"2.0,2.0","gradient":false,"shadow":true}},"lineStyles":{"global":{"stroke":"#cccccc","strokeWidth":2,"dashStyle":"4.0,4.0"}},"textStyles":{"global":{"size":"12px","italic":true}}},"metadata":{"title":"untitled","revision":0,"exportBorder":false,"loadPosition":"default","libraries":["com.gliffy.libraries.basic.basic_v1.default","com.gliffy.libraries.flowchart.flowchart_v1.default","com.gliffy.libraries.swimlanes.swimlanes_v1.default","com.gliffy.libraries.uml.uml_v2.class","com.gliffy.libraries.uml.uml_v2.sequence","com.gliffy.libraries.uml.uml_v2.activity","com.gliffy.libraries.erd.erd_v1.default","com.gliffy.libraries.ui.ui_v3.containers_content","com.gliffy.libraries.ui.ui_v3.forms_controls","com.gliffy.libraries.images"],"autosaveDisabled":false},"embeddedResources":{"index":0,"resources":[]}} ================================================ FILE: vendor/github.com/docker/docker/docs/article-img/ipv6_routed_network_example.gliffy ================================================ {"contentType":"application/gliffy+json","version":"1.3","stage":{"background":"#FFFFFF","width":893,"height":447,"nodeIndex":185,"autoFit":true,"exportBorder":false,"gridOn":false,"snapToGrid":false,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"maxWidth":5000,"maxHeight":5000,"themeData":null,"viewportType":"default","fitBB":{"min":{"x":-17.000680271168676,"y":7},"max":{"x":892.767693574114,"y":447}},"objects":[{"x":17.5,"y":205.5,"rotation":0.0,"id":167,"width":238.5,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":38,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:1::/64 dev docker0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":231.28932188134524,"y":95.0,"rotation":0.0,"id":120,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":6,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":161,"py":0.0,"px":0.2928932188134524}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":131,"py":1.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[267.5,47.5],[217.9213562373095,-13.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":187.0,"y":206.5,"rotation":0.0,"id":121,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":9,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":140,"py":0.9999999999999998,"px":0.29289321881345254}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":148,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[130.28932188134524,11.0],[-79.0,91.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":174.0,"y":217.5,"rotation":0.0,"id":122,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":8,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":140,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":146,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[164.0,0.0],[120.0,81.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":33.50000000000003,"y":409.0,"rotation":0.0,"id":123,"width":346.49999999999994,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":31,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":3.5000000000000284,"y":268.5,"rotation":0.0,"id":124,"width":411.00000000000006,"height":163.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":3,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":237.0,"y":54.0,"rotation":0.0,"id":125,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":7,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":131,"py":0.9999999999999998,"px":0.29289321881345254}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":140,"py":0.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[170.78932188134524,27.999999999999986],[121.71067811865476,88.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":378.5,"y":7.0,"rotation":0.0,"id":131,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":10,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#e2e2e2","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":132,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Layer 2 Switch

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":785.0,"y":195.0,"rotation":0.0,"id":136,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":32,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":143,"py":0.6187943262411347,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,8.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[78.75000000000011,-0.25],[-798.0006802711687,-3.410605131648481E-13]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":262.0,"y":224.0,"rotation":0.0,"id":138,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":19,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":278.0,"y":126.0,"rotation":0.0,"id":139,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":16,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:0::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":288.0,"y":142.5,"rotation":0.0,"id":140,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":12,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":141,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":3.4999999999999716,"y":107.5,"rotation":0.0,"id":142,"width":411.0,"height":141.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":1,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":221.0,"y":283.0,"rotation":0.0,"id":144,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":34,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:1::2/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":34.000000000000014,"y":283.0,"rotation":0.0,"id":145,"width":149.99999999999997,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":24,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:1::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":244.0,"y":299.0,"rotation":0.0,"id":146,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":22,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":147,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container1-2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":58.0,"y":298.0,"rotation":0.0,"id":148,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":20,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":149,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container1-1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":317.0,"y":436.5,"rotation":0.0,"id":158,"width":223.00000000000003,"height":11.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":37,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

containers' link-local addresses are not displayed

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":17.5,"y":148.0,"rotation":0.0,"id":137,"width":291.0,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":29,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:0::/64 dev eth0

ip -6 route add 2001:db8:2::/64 via 2001:db8:0::2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":901.7500000000001,"y":195.0,"rotation":0.0,"id":172,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":43,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-12.982306425886122,0.0],[-41.25,0.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":670.0,"y":284.0,"rotation":0.0,"id":155,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":36,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:2::2/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":479.0,"y":284.0,"rotation":0.0,"id":150,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":35,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:2::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":488.75,"y":408.0,"rotation":0.0,"id":152,"width":339.75,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":30,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":694.5,"y":298.0,"rotation":0.0,"id":156,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":27,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":157,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container2-2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":501.5,"y":298.0,"rotation":0.0,"id":153,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":25,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":154,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container2-1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":444.5,"y":223.0,"rotation":0.0,"id":160,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":18,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":460.5,"y":128.0,"rotation":0.0,"id":159,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":17,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:0::2/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":469.5,"y":142.5,"rotation":0.0,"id":161,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":14,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":162,"width":96.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":139.5,"y":86.5,"rotation":0.0,"id":126,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":5,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":161,"py":1.0,"px":0.7071067811865476}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":156,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[400.71067811865476,131.0],[605.0,211.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":100.5,"y":90.5,"rotation":0.0,"id":127,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":4,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":161,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":153,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[419.0,127.0],[451.0,207.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":447.75,"y":268.5,"rotation":0.0,"id":151,"width":416.0000000000001,"height":163.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":2,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":447.75,"y":107.5,"rotation":0.0,"id":143,"width":416.0000000000001,"height":141.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":0,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":795.7500000000001,"y":307.5,"rotation":270.0,"id":173,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":41,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

managed by Docker

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":879.7500000000001,"y":417.0,"rotation":0.0,"id":174,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":40,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":2,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[0.0,14.008510484195028],[0.0,-221.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":898.7500000000001,"y":432.0,"rotation":0.0,"id":171,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":42,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-13.981657549458532,0.0],[-41.25,0.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":582.5,"y":151.0,"rotation":0.0,"id":135,"width":285.25000000000017,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":33,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:0::/64 dev eth0

ip -6 route add 2001:db8:1::/64 via 2001:db8:0::1 

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":583.0,"y":204.0,"rotation":0.0,"id":168,"width":272.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":39,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:2::/64 dev docker0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]}],"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#e2e2e2","stroke":"#333333","strokeWidth":2,"dashStyle":"2.0,2.0","gradient":true,"shadow":true}},"lineStyles":{"global":{"stroke":"#000000","strokeWidth":1,"dashStyle":"8.0,8.0"}},"textStyles":{}},"metadata":{"title":"untitled","revision":0,"exportBorder":false,"loadPosition":"default","libraries":["com.gliffy.libraries.basic.basic_v1.default","com.gliffy.libraries.flowchart.flowchart_v1.default","com.gliffy.libraries.swimlanes.swimlanes_v1.default","com.gliffy.libraries.uml.uml_v2.class","com.gliffy.libraries.uml.uml_v2.sequence","com.gliffy.libraries.uml.uml_v2.activity","com.gliffy.libraries.erd.erd_v1.default","com.gliffy.libraries.ui.ui_v3.containers_content","com.gliffy.libraries.ui.ui_v3.forms_controls","com.gliffy.libraries.images"],"autosaveDisabled":false},"embeddedResources":{"index":0,"resources":[]}} ================================================ FILE: vendor/github.com/docker/docker/docs/article-img/ipv6_slash64_subnet_config.gliffy ================================================ {"contentType":"application/gliffy+json","version":"1.3","stage":{"background":"#FFFFFF","width":550,"height":341,"nodeIndex":88,"autoFit":true,"exportBorder":false,"gridOn":false,"snapToGrid":false,"drawingGuidesOn":false,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"maxWidth":5000,"maxHeight":5000,"themeData":null,"viewportType":"default","fitBB":{"min":{"x":2.5,"y":2.5},"max":{"x":550,"y":341}},"objects":[{"x":10.5,"y":53.5,"rotation":0.0,"id":74,"width":150.0,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":26,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":37.0,"y":2.5,"rotation":0.0,"id":72,"width":100.0,"height":46.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":24,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#d9d9d9","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":73,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Router

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":89.5,"y":83.5,"rotation":0.0,"id":59,"width":150.0,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":17,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Routed Network:
2001:db8:23:42::/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":313.0,"y":314.0,"rotation":0.0,"id":39,"width":235.0,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":16,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":352.0,"y":185.5,"rotation":0.0,"id":36,"width":169.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":15,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:23:42:1::2/80

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":351.0,"y":49.5,"rotation":0.0,"id":29,"width":171.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":14,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:23:42:1::1/80

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":382.1250000000001,"y":202.5,"rotation":0.0,"id":30,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":12,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":31,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

container1-2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":382.0,"y":65.5,"rotation":0.0,"id":32,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":10,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":33,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

container1-1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":15.125000000000057,"y":264.0,"rotation":0.0,"id":20,"width":273.0,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":9,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

ip -6 route add 2001:db8:23:42:1::/80 dev docker0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":120.0,"y":178.5,"rotation":0.0,"id":21,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":8,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":13.0,"y":132.5,"rotation":0.0,"id":22,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":7,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:23:42::1/80

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":38.0,"y":149.0,"rotation":0.0,"id":23,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":5,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":24,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

host1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":-118.0,"y":123.0,"rotation":0.0,"id":44,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":4,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":23,"py":0.7071067811865475,"px":0.9999999999999998}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":30,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[255.99999999999997,79.03300858899107],[500.1250000000001,129.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":-138.0,"y":129.0,"rotation":0.0,"id":43,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":3,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":23,"py":0.29289321881345237,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":32,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[276.0,41.966991411008934],[520.0,-13.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":313.0,"y":40.0,"rotation":0.0,"id":34,"width":237.00000000000003,"height":301.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":2,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":87.0,"y":150.0,"rotation":0.0,"id":58,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":1,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":23,"py":0.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":72,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[1.0,-1.0],[0.0,-101.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":2.5,"y":118.50000000000001,"rotation":0.0,"id":25,"width":292.0,"height":178.99999999999997,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":0,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]}],"shapeStyles":{},"lineStyles":{"global":{"stroke":"#cccccc"}},"textStyles":{"global":{"bold":true,"italic":true}}},"metadata":{"title":"untitled","revision":0,"exportBorder":false,"loadPosition":"default","libraries":["com.gliffy.libraries.basic.basic_v1.default","com.gliffy.libraries.flowchart.flowchart_v1.default","com.gliffy.libraries.swimlanes.swimlanes_v1.default","com.gliffy.libraries.uml.uml_v1.default","com.gliffy.libraries.erd.erd_v1.default","com.gliffy.libraries.ui.ui_v2.forms_components","com.gliffy.libraries.network.network_v3.home","com.gliffy.libraries.images"],"autosaveDisabled":false},"embeddedResources":{"index":0,"resources":[]}} ================================================ FILE: vendor/github.com/docker/docker/docs/article-img/ipv6_switched_network_example.gliffy ================================================ {"contentType":"application/gliffy+json","version":"1.3","stage":{"background":"#FFFFFF","width":893,"height":448,"nodeIndex":185,"autoFit":true,"exportBorder":false,"gridOn":false,"snapToGrid":false,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"maxWidth":5000,"maxHeight":5000,"themeData":null,"viewportType":"default","fitBB":{"min":{"x":-17.000680271168676,"y":7},"max":{"x":892.767693574114,"y":447.5}},"objects":[{"x":17.5,"y":205.5,"rotation":0.0,"id":167,"width":238.5,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":38,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:1::/64 dev docker0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":231.28932188134524,"y":95.0,"rotation":0.0,"id":120,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":6,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":161,"py":0.0,"px":0.2928932188134524}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":131,"py":1.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[267.5,47.5],[217.9213562373095,-13.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":187.0,"y":206.5,"rotation":0.0,"id":121,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":9,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":140,"py":0.9999999999999998,"px":0.29289321881345254}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":148,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[130.28932188134524,11.0],[-79.0,91.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":174.0,"y":217.5,"rotation":0.0,"id":122,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":8,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":140,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":146,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[164.0,0.0],[120.0,81.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":33.50000000000003,"y":409.0,"rotation":0.0,"id":123,"width":346.49999999999994,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":31,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":3.5000000000000284,"y":268.5,"rotation":0.0,"id":124,"width":411.00000000000006,"height":163.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":3,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":237.0,"y":54.0,"rotation":0.0,"id":125,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":7,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":131,"py":0.9999999999999998,"px":0.29289321881345254}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":140,"py":0.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[170.78932188134524,27.999999999999986],[121.71067811865476,88.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":378.5,"y":7.0,"rotation":0.0,"id":131,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":10,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#e2e2e2","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":132,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Level 2 Switch

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":785.0,"y":195.0,"rotation":0.0,"id":136,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":32,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":143,"py":0.6187943262411347,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":"8.0,8.0","startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[78.75000000000011,-0.25],[-798.0006802711687,-3.410605131648481E-13]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":262.0,"y":224.0,"rotation":0.0,"id":138,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":19,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":278.0,"y":126.0,"rotation":0.0,"id":139,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":16,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:0::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":288.0,"y":142.5,"rotation":0.0,"id":140,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":12,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":141,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":3.4999999999999716,"y":107.5,"rotation":0.0,"id":142,"width":411.0,"height":141.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":1,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":221.0,"y":283.0,"rotation":0.0,"id":144,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":34,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:1::2/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":34.000000000000014,"y":283.0,"rotation":0.0,"id":145,"width":149.99999999999997,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":24,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:1::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":244.0,"y":299.0,"rotation":0.0,"id":146,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":22,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":147,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container1-2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":58.0,"y":298.0,"rotation":0.0,"id":148,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":20,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":149,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container1-1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":317.0,"y":436.5,"rotation":0.0,"id":158,"width":223.00000000000003,"height":11.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":37,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

containers' link-local addresses are not displayed

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":17.5,"y":148.0,"rotation":0.0,"id":137,"width":291.0,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":29,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:0::/64 dev eth0

ip -6 route add 2001:db8:2::/64 via 2001:db8:0::2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":901.7500000000001,"y":195.0,"rotation":0.0,"id":172,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":43,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-12.982306425886122,0.0],[-41.25,0.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":670.0,"y":284.0,"rotation":0.0,"id":155,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":36,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:2::2/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":479.0,"y":284.0,"rotation":0.0,"id":150,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":35,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:2::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":488.75,"y":408.0,"rotation":0.0,"id":152,"width":339.75,"height":16.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":30,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add default via fe80::1 dev eth0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":694.5,"y":298.0,"rotation":0.0,"id":156,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":27,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":157,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container2-2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":501.5,"y":298.0,"rotation":0.0,"id":153,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.square","order":25,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#ead1dc","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":154,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Container2-1

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":444.5,"y":223.0,"rotation":0.0,"id":160,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":18,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker0 fe80::1/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":460.5,"y":128.0,"rotation":0.0,"id":159,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":17,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

eth0 2001:db8:0::2/64

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":469.5,"y":142.5,"rotation":0.0,"id":161,"width":100.0,"height":75.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":14,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":true,"dashStyle":null,"dropShadow":true,"state":0,"opacity":1.0,"shadowX":4.0,"shadowY":4.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":162,"width":96.0,"height":14.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Host2

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"children":[]}]},{"x":139.5,"y":86.5,"rotation":0.0,"id":126,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":5,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":161,"py":1.0,"px":0.7071067811865476}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":156,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[400.71067811865476,131.0],[605.0,211.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":100.5,"y":90.5,"rotation":0.0,"id":127,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":4,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":161,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":153,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#cccccc","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[419.0,127.0],[451.0,207.5]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":447.75,"y":268.5,"rotation":0.0,"id":151,"width":416.0000000000001,"height":163.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":2,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":447.75,"y":107.5,"rotation":0.0,"id":143,"width":416.0000000000001,"height":141.0,"uid":"com.gliffy.shape.basic.basic_v1.default.rectangle","order":0,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":"2,2","dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[]},{"x":795.7500000000001,"y":307.5,"rotation":270.0,"id":173,"width":150.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":41,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

managed by Docker

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":879.7500000000001,"y":417.0,"rotation":0.0,"id":174,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":40,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":2,"endArrow":2,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[0.0,14.008510484195028],[0.0,-221.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":898.7500000000001,"y":432.0,"rotation":0.0,"id":171,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":42,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Line","Line":{"strokeWidth":1.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":0,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-13.981657549458532,0.0],[-41.25,0.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":582.5,"y":151.0,"rotation":0.0,"id":135,"width":285.25000000000017,"height":28.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":33,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:0::/64 dev eth0

ip -6 route add 2001:db8:1::/64 via 2001:db8:0::1 

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]},{"x":583.0,"y":204.0,"rotation":0.0,"id":168,"width":272.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":39,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

ip -6 route add 2001:db8:2::/64 dev docker0

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[],"children":[]}],"shapeStyles":{"com.gliffy.shape.basic.basic_v1.default":{"fill":"#e2e2e2","stroke":"#333333","strokeWidth":2,"dashStyle":"2.0,2.0","gradient":true,"shadow":true}},"lineStyles":{"global":{"stroke":"#000000","strokeWidth":1,"dashStyle":"8.0,8.0"}},"textStyles":{}},"metadata":{"title":"untitled","revision":0,"exportBorder":false,"loadPosition":"default","libraries":["com.gliffy.libraries.basic.basic_v1.default","com.gliffy.libraries.flowchart.flowchart_v1.default","com.gliffy.libraries.swimlanes.swimlanes_v1.default","com.gliffy.libraries.uml.uml_v2.class","com.gliffy.libraries.uml.uml_v2.sequence","com.gliffy.libraries.uml.uml_v2.activity","com.gliffy.libraries.erd.erd_v1.default","com.gliffy.libraries.ui.ui_v3.containers_content","com.gliffy.libraries.ui.ui_v3.forms_controls","com.gliffy.libraries.images"],"autosaveDisabled":false},"embeddedResources":{"index":0,"resources":[]}} ================================================ FILE: vendor/github.com/docker/docker/docs/articles/ambassador_pattern_linking.md ================================================ # Link via an ambassador container ## Introduction Rather than hardcoding network links between a service consumer and provider, Docker encourages service portability, for example instead of: (consumer) --> (redis) Requiring you to restart the `consumer` to attach it to a different `redis` service, you can add ambassadors: (consumer) --> (redis-ambassador) --> (redis) Or (consumer) --> (redis-ambassador) ---network---> (redis-ambassador) --> (redis) When you need to rewire your consumer to talk to a different Redis server, you can just restart the `redis-ambassador` container that the consumer is connected to. This pattern also allows you to transparently move the Redis server to a different docker host from the consumer. Using the `svendowideit/ambassador` container, the link wiring is controlled entirely from the `docker run` parameters. ## Two host example Start actual Redis server on one Docker host big-server $ docker run -d --name redis crosbymichael/redis Then add an ambassador linked to the Redis server, mapping a port to the outside world big-server $ docker run -d --link redis:redis --name redis_ambassador -p 6379:6379 svendowideit/ambassador On the other host, you can set up another ambassador setting environment variables for each remote port we want to proxy to the `big-server` client-server $ docker run -d --name redis_ambassador --expose 6379 -e REDIS_PORT_6379_TCP=tcp://192.168.1.52:6379 svendowideit/ambassador Then on the `client-server` host, you can use a Redis client container to talk to the remote Redis server, just by linking to the local Redis ambassador. client-server $ docker run -i -t --rm --link redis_ambassador:redis relateiq/redis-cli redis 172.17.0.160:6379> ping PONG ## How it works The following example shows what the `svendowideit/ambassador` container does automatically (with a tiny amount of `sed`) On the Docker host (192.168.1.52) that Redis will run on: # start actual redis server $ docker run -d --name redis crosbymichael/redis # get a redis-cli container for connection testing $ docker pull relateiq/redis-cli # test the redis server by talking to it directly $ docker run -t -i --rm --link redis:redis relateiq/redis-cli redis 172.17.0.136:6379> ping PONG ^D # add redis ambassador $ docker run -t -i --link redis:redis --name redis_ambassador -p 6379:6379 busybox sh In the `redis_ambassador` container, you can see the linked Redis containers `env`: $ env REDIS_PORT=tcp://172.17.0.136:6379 REDIS_PORT_6379_TCP_ADDR=172.17.0.136 REDIS_NAME=/redis_ambassador/redis HOSTNAME=19d7adf4705e REDIS_PORT_6379_TCP_PORT=6379 HOME=/ REDIS_PORT_6379_TCP_PROTO=tcp container=lxc REDIS_PORT_6379_TCP=tcp://172.17.0.136:6379 TERM=xterm PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD=/ This environment is used by the ambassador `socat` script to expose Redis to the world (via the `-p 6379:6379` port mapping): $ docker rm redis_ambassador $ sudo ./contrib/mkimage-unittest.sh $ docker run -t -i --link redis:redis --name redis_ambassador -p 6379:6379 docker-ut sh $ socat TCP4-LISTEN:6379,fork,reuseaddr TCP4:172.17.0.136:6379 Now ping the Redis server via the ambassador: Now go to a different server: $ sudo ./contrib/mkimage-unittest.sh $ docker run -t -i --expose 6379 --name redis_ambassador docker-ut sh $ socat TCP4-LISTEN:6379,fork,reuseaddr TCP4:192.168.1.52:6379 And get the `redis-cli` image so we can talk over the ambassador bridge. $ docker pull relateiq/redis-cli $ docker run -i -t --rm --link redis_ambassador:redis relateiq/redis-cli redis 172.17.0.160:6379> ping PONG ## The svendowideit/ambassador Dockerfile The `svendowideit/ambassador` image is a small `busybox` image with `socat` built in. When you start the container, it uses a small `sed` script to parse out the (possibly multiple) link environment variables to set up the port forwarding. On the remote host, you need to set the variable using the `-e` command line option. --expose 1234 -e REDIS_PORT_1234_TCP=tcp://192.168.1.52:6379 Will forward the local `1234` port to the remote IP and port, in this case `192.168.1.52:6379`. # # # first you need to build the docker-ut image # using ./contrib/mkimage-unittest.sh # then # docker build -t SvenDowideit/ambassador . # docker tag SvenDowideit/ambassador ambassador # then to run it (on the host that has the real backend on it) # docker run -t -i --link redis:redis --name redis_ambassador -p 6379:6379 ambassador # on the remote host, you can set up another ambassador # docker run -t -i --name redis_ambassador --expose 6379 sh FROM docker-ut MAINTAINER SvenDowideit@home.org.au CMD env | grep _TCP= | sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/' | sh && top ================================================ FILE: vendor/github.com/docker/docker/docs/articles/b2d_volume_resize.md ================================================ # Getting “no space left on device” errors with Boot2Docker? If you're using Boot2Docker with a large number of images, or the images you're working with are very large, your pulls might start failing with "no space left on device" errors when the Boot2Docker volume fills up. There are two solutions you can try. ## Solution 1: Add the `DiskImage` property in boot2docker profile The `boot2docker` command reads its configuration from the `$BOOT2DOCKER_PROFILE` if set, or `$BOOT2DOCKER_DIR/profile` or `$HOME/.boot2docker/profile` (on Windows this is `%USERPROFILE%/.boot2docker/profile`). 1. View the existing configuration, use the `boot2docker config` command. $ boot2docker config # boot2docker profile filename: /Users/mary/.boot2docker/profile Init = false Verbose = false Driver = "virtualbox" Clobber = true ForceUpgradeDownload = false SSH = "ssh" SSHGen = "ssh-keygen" SSHKey = "/Users/mary/.ssh/id_boot2docker" VM = "boot2docker-vm" Dir = "/Users/mary/.boot2docker" ISOURL = "https://api.github.com/repos/boot2docker/boot2docker/releases" ISO = "/Users/mary/.boot2docker/boot2docker.iso" DiskSize = 20000 Memory = 2048 CPUs = 8 SSHPort = 2022 DockerPort = 0 HostIP = "192.168.59.3" DHCPIP = "192.168.59.99" NetMask = [255, 255, 255, 0] LowerIP = "192.168.59.103" UpperIP = "192.168.59.254" DHCPEnabled = true Serial = false SerialFile = "/Users/mary/.boot2docker/boot2docker-vm.sock" Waittime = 300 Retries = 75 The configuration shows you where `boot2docker` is looking for the `profile` file. It also output the settings that are in use. 2. Initialise a default file to customize using `boot2docker config > ~/.boot2docker/profile` command. 3. Add the following lines to `$HOME/.boot2docker/profile`: # Disk image size in MB DiskSize = 50000 4. Run the following sequence of commands to restart Boot2Docker with the new settings. $ boot2docker poweroff $ boot2docker destroy $ boot2docker init $ boot2docker up ## Solution 2: Increase the size of boot2docker volume This solution increases the volume size by first cloning it, then resizing it using a disk partitioning tool. We recommend [GParted](http://gparted.sourceforge.net/download.php/index.php). The tool comes as a bootable ISO, is a free download, and works well with VirtualBox. 1. Stop Boot2Docker Issue the command to stop the Boot2Docker VM on the command line: $ boot2docker stop 2. Clone the VMDK image to a VDI image Boot2Docker ships with a VMDK image, which can't be resized by VirtualBox's native tools. We will instead create a VDI volume and clone the VMDK volume to it. 3. Using the command line VirtualBox tools, clone the VMDK image to a VDI image: $ vboxmanage clonehd /full/path/to/boot2docker-hd.vmdk /full/path/to/.vdi --format VDI --variant Standard 4. Resize the VDI volume Choose a size that will be appropriate for your needs. If you're spinning up a lot of containers, or your containers are particularly large, larger will be better: $ vboxmanage modifyhd /full/path/to/.vdi --resize 5. Download a disk partitioning tool ISO To resize the volume, we'll use [GParted](http://gparted.sourceforge.net/download.php/). Once you've downloaded the tool, add the ISO to the Boot2Docker VM IDE bus. You might need to create the bus before you can add the ISO. > **Note:** > It's important that you choose a partitioning tool that is available as an ISO so > that the Boot2Docker VM can be booted with it.


6. Add the new VDI image In the settings for the Boot2Docker image in VirtualBox, remove the VMDK image from the SATA controller and add the VDI image. 7. Verify the boot order In the **System** settings for the Boot2Docker VM, make sure that **CD/DVD** is at the top of the **Boot Order** list. 8. Boot to the disk partitioning ISO Manually start the Boot2Docker VM in VirtualBox, and the disk partitioning ISO should start up. Using GParted, choose the **GParted Live (default settings)** option. Choose the default keyboard, language, and XWindows settings, and the GParted tool will start up and display the VDI volume you created. Right click on the VDI and choose **Resize/Move**. 9. Drag the slider representing the volume to the maximum available size. 10. Click **Resize/Move** followed by **Apply**. 11. Quit GParted and shut down the VM. 12. Remove the GParted ISO from the IDE controller for the Boot2Docker VM in VirtualBox. 13. Start the Boot2Docker VM Fire up the Boot2Docker VM manually in VirtualBox. The VM should log in automatically, but if it doesn't, the credentials are `docker/tcuser`. Using the `df -h` command, verify that your changes took effect. You're done! ================================================ FILE: vendor/github.com/docker/docker/docs/articles/baseimages.md ================================================ # Create a base image So you want to create your own [*Base Image*]( /terms/image/#base-image)? Great! The specific process will depend heavily on the Linux distribution you want to package. We have some examples below, and you are encouraged to submit pull requests to contribute new ones. ## Create a full image using tar In general, you'll want to start with a working machine that is running the distribution you'd like to package as a base image, though that is not required for some tools like Debian's [Debootstrap](https://wiki.debian.org/Debootstrap), which you can also use to build Ubuntu images. It can be as simple as this to create an Ubuntu base image: $ sudo debootstrap raring raring > /dev/null $ sudo tar -C raring -c . | docker import - raring a29c15f1bf7a $ docker run raring cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=13.04 DISTRIB_CODENAME=raring DISTRIB_DESCRIPTION="Ubuntu 13.04" There are more example scripts for creating base images in the Docker GitHub Repo: - [BusyBox](https://github.com/docker/docker/blob/master/contrib/mkimage-busybox.sh) - CentOS / Scientific Linux CERN (SLC) [on Debian/Ubuntu]( https://github.com/docker/docker/blob/master/contrib/mkimage-rinse.sh) or [on CentOS/RHEL/SLC/etc.]( https://github.com/docker/docker/blob/master/contrib/mkimage-yum.sh) - [Debian / Ubuntu]( https://github.com/docker/docker/blob/master/contrib/mkimage-debootstrap.sh) ## Creating a simple base image using scratch You can use Docker's reserved, minimal image, `scratch`, as a starting point for building containers. Using the `scratch` "image" signals to the build process that you want the next command in the `Dockerfile` to be the first filesystem layer in your image. While `scratch` appears in Docker's repository on the hub, you can't pull it, run it, or tag any image with the name `scratch`. Instead, you can refer to it in your `Dockerfile`. For example, to create a minimal container using `scratch`: FROM scratch ADD hello / CMD ["/hello"] This example creates the hello-world image used in the tutorials. If you want to test it out, you can clone [the image repo](https://github.com/docker-library/hello-world) ## More resources There are lots more resources available to help you write your 'Dockerfile`. * There's a [complete guide to all the instructions](/reference/builder/) available for use in a `Dockerfile` in the reference section. * To help you write a clear, readable, maintainable `Dockerfile`, we've also written a [`Dockerfile` Best Practices guide](/articles/dockerfile_best-practices). * If your goal is to create a new Official Repository, be sure to read up on Docker's [Official Repositories](/docker-hub/official_repos/). ================================================ FILE: vendor/github.com/docker/docker/docs/articles/basics.md ================================================ # Get started with containers This guide assumes you have a working installation of Docker. To verify Docker is installed, use the following command: # Check that you have a working install $ docker info If you get `docker: command not found` or something like `/var/lib/docker/repositories: permission denied` you may have an incomplete Docker installation or insufficient privileges to access Docker on your machine. Please Additionally, depending on your Docker system configuration, you may be required to preface each `docker` command with `sudo`. To avoid having to use `sudo` with the `docker` command, your system administrator can create a Unix group called `docker` and add users to it. For more information about installing Docker or `sudo` configuration, refer to the [installation](/installation) instructions for your operating system. ## Download a pre-built image # Download an ubuntu image $ docker pull ubuntu This will find the `ubuntu` image by name on [*Docker Hub*](/userguide/dockerrepos/#searching-for-images) and download it from [Docker Hub](https://hub.docker.com) to a local image cache. > **Note**: > When the image is successfully downloaded, you see a 12 character > hash `539c0211cd76: Download complete` which is the > short form of the image ID. These short image IDs are the first 12 > characters of the full image ID - which can be found using > `docker inspect` or `docker images --no-trunc=true`. > **Note:** if you are using a remote Docker daemon, such as Boot2Docker, > then _do not_ type the `sudo` before the `docker` commands shown in the > documentation's examples. ## Running an interactive shell To run an interactive shell in the Ubuntu image: $ docker run -i -t ubuntu /bin/bash The `-i` flag starts an interactive container. The `-t` flag creates a pseudo-TTY that attaches `stdin` and `stdout`. To detach the `tty` without exiting the shell, use the escape sequence `Ctrl-p` + `Ctrl-q`. The container will continue to exist in a stopped state once exited. To list all containers, stopped and running use the `docker ps -a` command. ## Bind Docker to another host/port or a Unix socket > **Warning**: > Changing the default `docker` daemon binding to a > TCP port or Unix *docker* user group will increase your security risks > by allowing non-root users to gain *root* access on the host. Make sure > you control access to `docker`. If you are binding > to a TCP port, anyone with access to that port has full Docker access; > so it is not advisable on an open network. With `-H` it is possible to make the Docker daemon to listen on a specific IP and port. By default, it will listen on `unix:///var/run/docker.sock` to allow only local connections by the *root* user. You *could* set it to `0.0.0.0:2375` or a specific host IP to give access to everybody, but that is **not recommended** because then it is trivial for someone to gain root access to the host where the daemon is running. Similarly, the Docker client can use `-H` to connect to a custom port. `-H` accepts host and port assignment in the following format: tcp://[host][:port][path] or unix://path For example: - `tcp://host:2375` -> TCP connection on host:2375 - `tcp://host:2375/path` -> TCP connection on host:2375 and prepend path to all requests - `unix://path/to/socket` -> Unix socket located at `path/to/socket` `-H`, when empty, will default to the same value as when no `-H` was passed in. `-H` also accepts short form for TCP bindings: host[:port] or :port Run Docker in daemon mode: $ sudo /docker -H 0.0.0.0:5555 -d & Download an `ubuntu` image: $ docker -H :5555 pull ubuntu You can use multiple `-H`, for example, if you want to listen on both TCP and a Unix socket # Run docker in daemon mode $ sudo /docker -H tcp://127.0.0.1:2375 -H unix:///var/run/docker.sock -d & # Download an ubuntu image, use default Unix socket $ docker pull ubuntu # OR use the TCP port $ docker -H tcp://127.0.0.1:2375 pull ubuntu ## Starting a long-running worker process # Start a very useful long-running process $ JOB=$(docker run -d ubuntu /bin/sh -c "while true; do echo Hello world; sleep 1; done") # Collect the output of the job so far $ docker logs $JOB # Kill the job $ docker kill $JOB ## Listing containers $ docker ps # Lists only running containers $ docker ps -a # Lists all containers ## Controlling containers # Start a new container $ JOB=$(docker run -d ubuntu /bin/sh -c "while true; do echo Hello world; sleep 1; done") # Stop the container $ docker stop $JOB # Start the container $ docker start $JOB # Restart the container $ docker restart $JOB # SIGKILL a container $ docker kill $JOB # Remove a container $ docker stop $JOB # Container must be stopped to remove it $ docker rm $JOB ## Bind a service on a TCP port # Bind port 4444 of this container, and tell netcat to listen on it $ JOB=$(docker run -d -p 4444 ubuntu:12.10 /bin/nc -l 4444) # Which public port is NATed to my container? $ PORT=$(docker port $JOB 4444 | awk -F: '{ print $2 }') # Connect to the public port $ echo hello world | nc 127.0.0.1 $PORT # Verify that the network connection worked $ echo "Daemon received: $(docker logs $JOB)" ## Committing (saving) a container state Save your containers state to an image, so the state can be re-used. When you commit your container, Docker only stores the diff (difference) between the source image and the current state of the container's image. To list images you already have, use the `docker images` command. # Commit your container to a new named image $ docker commit # List your images $ docker images You now have an image state from which you can create new instances. Read more about [*Share Images via Repositories*](/userguide/dockerrepos) or continue to the complete [*Command Line*](/reference/commandline/cli) ================================================ FILE: vendor/github.com/docker/docker/docs/articles/certificates.md ================================================ # Using certificates for repository client verification In [Running Docker with HTTPS](/articles/https), you learned that, by default, Docker runs via a non-networked Unix socket and TLS must be enabled in order to have the Docker client and the daemon communicate securely over HTTPS. Now, you will see how to allow the Docker registry (i.e., *a server*) to verify that the Docker daemon (i.e., *a client*) has the right to access the images being hosted with *certificate-based client-server authentication*. We will show you how to install a Certificate Authority (CA) root certificate for the registry and how to set the client TLS certificate for verification. ## Understanding the configuration A custom certificate is configured by creating a directory under `/etc/docker/certs.d` using the same name as the registry's hostname (e.g., `localhost`). All `*.crt` files are added to this directory as CA roots. > **Note:** > In the absence of any root certificate authorities, Docker > will use the system default (i.e., host's root CA set). The presence of one or more `.key/cert` pairs indicates to Docker that there are custom certificates required for access to the desired repository. > **Note:** > If there are multiple certificates, each will be tried in alphabetical > order. If there is an authentication error (e.g., 403, 404, 5xx, etc.), Docker > will continue to try with the next certificate. Our example is set up like this: /etc/docker/certs.d/ <-- Certificate directory └── localhost <-- Hostname ├── client.cert <-- Client certificate ├── client.key <-- Client key └── localhost.crt <-- Registry certificate ## Creating the client certificates You will use OpenSSL's `genrsa` and `req` commands to first generate an RSA key and then use the key to create the certificate. $ openssl genrsa -out client.key 4096 $ openssl req -new -x509 -text -key client.key -out client.cert > **Warning:**: > Using TLS and managing a CA is an advanced topic. > You should be familiar with OpenSSL, x509, and TLS before > attempting to use them in production. > **Warning:** > These TLS commands will only generate a working set of certificates on Linux. > The version of OpenSSL in Mac OS X is incompatible with the type of > certificate Docker requires. ## Testing the verification setup You can test this setup by using Apache to host a Docker registry. For this purpose, you can copy a registry tree (containing images) inside the Apache root. > **Note:** > You can find such an example [here]( > http://people.gnome.org/~alexl/v1.tar.gz) - which contains the busybox image. Once you set up the registry, you can use the following Apache configuration to implement certificate-based protection. # This must be in the root context, otherwise it causes a re-negotiation # which is not supported by the TLS implementation in go SSLVerifyClient optional_no_ca Action cert-protected /cgi-bin/cert.cgi SetHandler cert-protected Header set x-docker-registry-version "0.6.2" SetEnvIf Host (.*) custom_host=$1 Header set X-Docker-Endpoints "%{custom_host}e" Save the above content as `/etc/httpd/conf.d/registry.conf`, and continue with creating a `cert.cgi` file under `/var/www/cgi-bin/`. #!/bin/bash if [ "$HTTPS" != "on" ]; then echo "Status: 403 Not using SSL" echo "x-docker-registry-version: 0.6.2" echo exit 0 fi if [ "$SSL_CLIENT_VERIFY" == "NONE" ]; then echo "Status: 403 Client certificate invalid" echo "x-docker-registry-version: 0.6.2" echo exit 0 fi echo "Content-length: $(stat --printf='%s' $PATH_TRANSLATED)" echo "x-docker-registry-version: 0.6.2" echo "X-Docker-Endpoints: $SERVER_NAME" echo "X-Docker-Size: 0" echo cat $PATH_TRANSLATED This CGI script will ensure that all requests to `/v1` *without* a valid certificate will be returned with a `403` (i.e., HTTP forbidden) error. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/cfengine_process_management.md ================================================ # Process management with CFEngine Create Docker containers with managed processes. Docker monitors one process in each running container and the container lives or dies with that process. By introducing CFEngine inside Docker containers, we can alleviate a few of the issues that may arise: - It is possible to easily start multiple processes within a container, all of which will be managed automatically, with the normal `docker run` command. - If a managed process dies or crashes, CFEngine will start it again within 1 minute. - The container itself will live as long as the CFEngine scheduling daemon (cf-execd) lives. With CFEngine, we are able to decouple the life of the container from the uptime of the service it provides. ## How it works CFEngine, together with the cfe-docker integration policies, are installed as part of the Dockerfile. This builds CFEngine into our Docker image. The Dockerfile's `ENTRYPOINT` takes an arbitrary amount of commands (with any desired arguments) as parameters. When we run the Docker container these parameters get written to CFEngine policies and CFEngine takes over to ensure that the desired processes are running in the container. CFEngine scans the process table for the `basename` of the commands given to the `ENTRYPOINT` and runs the command to start the process if the `basename` is not found. For example, if we start the container with `docker run "/path/to/my/application parameters"`, CFEngine will look for a process named `application` and run the command. If an entry for `application` is not found in the process table at any point in time, CFEngine will execute `/path/to/my/application parameters` to start the application once again. The check on the process table happens every minute. Note that it is therefore important that the command to start your application leaves a process with the basename of the command. This can be made more flexible by making some minor adjustments to the CFEngine policies, if desired. ## Usage This example assumes you have Docker installed and working. We will install and manage `apache2` and `sshd` in a single container. There are three steps: 1. Install CFEngine into the container. 2. Copy the CFEngine Docker process management policy into the containerized CFEngine installation. 3. Start your application processes as part of the `docker run` command. ### Building the image The first two steps can be done as part of a Dockerfile, as follows. FROM ubuntu MAINTAINER Eystein Måløy Stenberg RUN apt-get update && apt-get install -y wget lsb-release unzip ca-certificates # install latest CFEngine RUN wget -qO- http://cfengine.com/pub/gpg.key | apt-key add - RUN echo "deb http://cfengine.com/pub/apt $(lsb_release -cs) main" > /etc/apt/sources.list.d/cfengine-community.list RUN apt-get update && apt-get install -y cfengine-community # install cfe-docker process management policy RUN wget https://github.com/estenberg/cfe-docker/archive/master.zip -P /tmp/ && unzip /tmp/master.zip -d /tmp/ RUN cp /tmp/cfe-docker-master/cfengine/bin/* /var/cfengine/bin/ RUN cp /tmp/cfe-docker-master/cfengine/inputs/* /var/cfengine/inputs/ RUN rm -rf /tmp/cfe-docker-master /tmp/master.zip # apache2 and openssh are just for testing purposes, install your own apps here RUN apt-get update && apt-get install -y openssh-server apache2 RUN mkdir -p /var/run/sshd RUN echo "root:password" | chpasswd # need a password for ssh ENTRYPOINT ["/var/cfengine/bin/docker_processes_run.sh"] By saving this file as Dockerfile to a working directory, you can then build your image with the docker build command, e.g., `docker build -t managed_image`. ### Testing the container Start the container with `apache2` and `sshd` running and managed, forwarding a port to our SSH instance: $ docker run -p 127.0.0.1:222:22 -d managed_image "/usr/sbin/sshd" "/etc/init.d/apache2 start" We now clearly see one of the benefits of the cfe-docker integration: it allows to start several processes as part of a normal `docker run` command. We can now log in to our new container and see that both `apache2` and `sshd` are running. We have set the root password to "password" in the Dockerfile above and can use that to log in with ssh: ssh -p222 root@127.0.0.1 ps -ef UID PID PPID C STIME TTY TIME CMD root 1 0 0 07:48 ? 00:00:00 /bin/bash /var/cfengine/bin/docker_processes_run.sh /usr/sbin/sshd /etc/init.d/apache2 start root 18 1 0 07:48 ? 00:00:00 /var/cfengine/bin/cf-execd -F root 20 1 0 07:48 ? 00:00:00 /usr/sbin/sshd root 32 1 0 07:48 ? 00:00:00 /usr/sbin/apache2 -k start www-data 34 32 0 07:48 ? 00:00:00 /usr/sbin/apache2 -k start www-data 35 32 0 07:48 ? 00:00:00 /usr/sbin/apache2 -k start www-data 36 32 0 07:48 ? 00:00:00 /usr/sbin/apache2 -k start root 93 20 0 07:48 ? 00:00:00 sshd: root@pts/0 root 105 93 0 07:48 pts/0 00:00:00 -bash root 112 105 0 07:49 pts/0 00:00:00 ps -ef If we stop apache2, it will be started again within a minute by CFEngine. service apache2 status Apache2 is running (pid 32). service apache2 stop * Stopping web server apache2 ... waiting [ OK ] service apache2 status Apache2 is NOT running. # ... wait up to 1 minute... service apache2 status Apache2 is running (pid 173). ## Adapting to your applications To make sure your applications get managed in the same manner, there are just two things you need to adjust from the above example: - In the Dockerfile used above, install your applications instead of `apache2` and `sshd`. - When you start the container with `docker run`, specify the command line arguments to your applications rather than `apache2` and `sshd`. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/chef.md ================================================ # Using Chef > **Note**: > Please note this is a community contributed installation path. The only > `official` installation is using the > [*Ubuntu*](/installation/ubuntulinux) installation > path. This version may sometimes be out of date. ## Requirements To use this guide you'll need a working installation of [Chef](http://www.getchef.com/). This cookbook supports a variety of operating systems. ## Installation The cookbook is available on the [Chef Community Site](http://community.opscode.com/cookbooks/docker) and can be installed using your favorite cookbook dependency manager. The source can be found on [GitHub](https://github.com/bflad/chef-docker). ## Usage The cookbook provides recipes for installing Docker, configuring init for Docker, and resources for managing images and containers. It supports almost all Docker functionality. ### Installation include_recipe 'docker' ### Images The next step is to pull a Docker image. For this, we have a resource: docker_image 'samalba/docker-registry' This is equivalent to running: $ docker pull samalba/docker-registry There are attributes available to control how long the cookbook will allow for downloading (5 minute default). To remove images you no longer need: docker_image 'samalba/docker-registry' do action :remove end ### Containers Now you have an image where you can run commands within a container managed by Docker. docker_container 'samalba/docker-registry' do detach true port '5000:5000' env 'SETTINGS_FLAVOR=local' volume '/mnt/docker:/docker-storage' end This is equivalent to running the following command, but under upstart: $ docker run --detach=true --publish='5000:5000' --env='SETTINGS_FLAVOR=local' --volume='/mnt/docker:/docker-storage' samalba/docker-registry The resources will accept a single string or an array of values for any Docker flags that allow multiple values. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/configuring.md ================================================ # Configuring and running Docker on various distributions After successfully installing Docker, the `docker` daemon runs with its default configuration. In a production environment, system administrators typically configure the `docker` daemon to start and stop according to an organization's requirements. In most cases, the system administrator configures a process manager such as `SysVinit`, `Upstart`, or `systemd` to manage the `docker` daemon's start and stop. ### Running the docker daemon directly The `docker` daemon can be run directly using the `-d` option. By default it listens on the Unix socket `unix:///var/run/docker.sock` $ docker -d INFO[0000] +job init_networkdriver() INFO[0000] +job serveapi(unix:///var/run/docker.sock) INFO[0000] Listening for HTTP on unix (/var/run/docker.sock) ... ... ### Configuring the docker daemon directly If you're running the `docker` daemon directly by running `docker -d` instead of using a process manager, you can append the configuration options to the `docker` run command directly. Just like the `-d` option, other options can be passed to the `docker` daemon to configure it. Some of the daemon's options are: | Flag | Description | |-----------------------|-----------------------------------------------------------| | `-D`, `--debug=false` | Enable or disable debug mode. By default, this is false. | | `-H`,`--host=[]` | Daemon socket(s) to connect to. | | `--tls=false` | Enable or disable TLS. By default, this is false. | Here is a an example of running the `docker` daemon with configuration options: $ docker -d -D --tls=true --tlscert=/var/docker/server.pem --tlskey=/var/docker/serverkey.pem -H tcp://192.168.59.3:2376 These options : - Enable `-D` (debug) mode - Set `tls` to true with the server certificate and key specified using `--tlscert` and `--tlskey` respectively - Listen for connections on `tcp://192.168.59.3:2376` The command line reference has the [complete list of daemon flags](/reference/commandline/cli/#daemon) with explanations. ## Ubuntu As of `14.04`, Ubuntu uses Upstart as a process manager. By default, Upstart jobs are located in `/etc/init` and the `docker` Upstart job can be found at `/etc/init/docker.conf`. After successfully [installing Docker for Ubuntu](/installation/ubuntulinux/), you can check the running status using Upstart in this way: $ sudo status docker docker start/running, process 989 ### Running Docker You can start/stop/restart the `docker` daemon using $ sudo start docker $ sudo stop docker $ sudo restart docker ### Configuring Docker You configure the `docker` daemon in the `/etc/default/docker` file on your system. You do this by specifying values in a `DOCKER_OPTS` variable. To configure Docker options: 1. Log into your host as a user with `sudo` or `root` privileges. 2. If you don't have one, create the `/etc/default/docker` file on your host. Depending on how you installed Docker, you may already have this file. 3. Open the file with your favorite editor. ``` $ sudo vi /etc/default/docker ``` 4. Add a `DOCKER_OPTS` variable with the following options. These options are appended to the `docker` daemon's run command. ``` DOCKER_OPTS="-D --tls=true --tlscert=/var/docker/server.pem --tlskey=/var/docker/serverkey.pem -H tcp://192.168.59.3:2376" ``` These options : - Enable `-D` (debug) mode - Set `tls` to true with the server certificate and key specified using `--tlscert` and `--tlskey` respectively - Listen for connections on `tcp://192.168.59.3:2376` The command line reference has the [complete list of daemon flags](/reference/commandline/cli/#daemon) with explanations. 5. Save and close the file. 6. Restart the `docker` daemon. ``` $ sudo restart docker ``` 7. Verify that the `docker` daemon is running as specified with the `ps` command. ``` $ ps aux | grep docker | grep -v grep ``` ### Logs By default logs for Upstart jobs are located in `/var/log/upstart` and the logs for `docker` daemon can be located at `/var/log/upstart/docker.log` $ tail -f /var/log/upstart/docker.log INFO[0000] Loading containers: done. INFO[0000] docker daemon: 1.6.0 4749651; execdriver: native-0.2; graphdriver: aufs INFO[0000] +job acceptconnections() INFO[0000] -job acceptconnections() = OK (0) INFO[0000] Daemon has completed initialization ## CentOS / Red Hat Enterprise Linux / Fedora As of `7.x`, CentOS and RHEL use `systemd` as the process manager. As of `21`, Fedora uses `systemd` as its process manager. After successfully installing Docker for [CentOS](/installation/centos/)/[Red Hat Enterprise Linux] (/installation/rhel/)/[Fedora](/installation/fedora), you can check the running status in this way: $ sudo systemctl status docker ### Running Docker You can start/stop/restart the `docker` daemon using $ sudo systemctl start docker $ sudo systemctl stop docker $ sudo systemctl restart docker If you want Docker to start at boot, you should also: $ sudo systemctl enable docker ### Configuring Docker You configure the `docker` daemon in the `/etc/sysconfig/docker` file on your host. You do this by specifying values in a variable. For CentOS 7.x and RHEL 7.x, the name of the variable is `OPTIONS` and for CentOS 6.x and RHEL 6.x, the name of the variable is `other_args`. For this section, we will use CentOS 7.x as an example to configure the `docker` daemon. By default, systemd services are located either in `/etc/systemd/service`, `/lib/systemd/system` or `/usr/lib/systemd/system`. The `docker.service` file can be found in either of these three directories depending on your host. To configure Docker options: 1. Log into your host as a user with `sudo` or `root` privileges. 2. If you don't have one, create the `/etc/sysconfig/docker` file on your host. Depending on how you installed Docker, you may already have this file. 3. Open the file with your favorite editor. ``` $ sudo vi /etc/sysconfig/docker ``` 4. Add a `OPTIONS` variable with the following options. These options are appended to the command that starts the `docker` daemon. ``` OPTIONS="-D --tls=true --tlscert=/var/docker/server.pem --tlskey=/var/docker/serverkey.pem -H tcp://192.168.59.3:2376" ``` These options : - Enable `-D` (debug) mode - Set `tls` to true with the server certificate and key specified using `--tlscert` and `--tlskey` respectively - Listen for connections on `tcp://192.168.59.3:2376` The command line reference has the [complete list of daemon flags](/reference/commandline/cli/#daemon) with explanations. 5. Save and close the file. 6. Restart the `docker` daemon. ``` $ sudo service docker restart ``` 7. Verify that the `docker` daemon is running as specified with the `ps` command. ``` $ ps aux | grep docker | grep -v grep ``` ### Logs systemd has its own logging system called the journal. The logs for the `docker` daemon can be viewed using `journalctl -u docker` $ sudo journalctl -u docker May 06 00:22:05 localhost.localdomain systemd[1]: Starting Docker Application Container Engine... May 06 00:22:05 localhost.localdomain docker[2495]: time="2015-05-06T00:22:05Z" level="info" msg="+job serveapi(unix:///var/run/docker.sock)" May 06 00:22:05 localhost.localdomain docker[2495]: time="2015-05-06T00:22:05Z" level="info" msg="Listening for HTTP on unix (/var/run/docker.sock)" May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="+job init_networkdriver()" May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="-job init_networkdriver() = OK (0)" May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="Loading containers: start." May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="Loading containers: done." May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="docker daemon: 1.5.0-dev fc0329b/1.5.0; execdriver: native-0.2; graphdriver: devicemapper" May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="+job acceptconnections()" May 06 00:22:06 localhost.localdomain docker[2495]: time="2015-05-06T00:22:06Z" level="info" msg="-job acceptconnections() = OK (0)" _Note: Using and configuring journal is an advanced topic and is beyond the scope of this article._ ================================================ FILE: vendor/github.com/docker/docker/docs/articles/dockerfile_best-practices.md ================================================ # Best practices for writing Dockerfiles ## Overview Docker can build images automatically by reading the instructions from a `Dockerfile`, a text file that contains all the commands, in order, needed to build a given image. `Dockerfile`s adhere to a specific format and use a specific set of instructions. You can learn the basics on the [Dockerfile Reference](https://docs.docker.com/reference/builder/) page. If you’re new to writing `Dockerfile`s, you should start there. This document covers the best practices and methods recommended by Docker, Inc. and the Docker community for creating easy-to-use, effective `Dockerfile`s. We strongly suggest you follow these recommendations (in fact, if you’re creating an Official Image, you *must* adhere to these practices). You can see many of these practices and recommendations in action in the [buildpack-deps `Dockerfile`](https://github.com/docker-library/buildpack-deps/blob/master/jessie/Dockerfile). > Note: for more detailed explanations of any of the Dockerfile commands >mentioned here, visit the [Dockerfile Reference](https://docs.docker.com/reference/builder/) page. ## General guidelines and recommendations ### Containers should be ephemeral The container produced by the image your `Dockerfile` defines should be as ephemeral as possible. By “ephemeral,” we mean that it can be stopped and destroyed and a new one built and put in place with an absolute minimum of set-up and configuration. ### Use a .dockerignore file In most cases, it's best to put each Dockerfile in an empty directory. Then, add to that directory only the files needed for building the Dockerfile. To increase the build's performance, you can exclude files and directories by adding a `.dockerignore` file to that directory as well. This file supports exclusion patterns similar to `.gitignore` files. For information on creating one, see the [.dockerignore file](../../reference/builder/#dockerignore-file). ### Avoid installing unnecessary packages In order to reduce complexity, dependencies, file sizes, and build times, you should avoid installing extra or unnecessary packages just because they might be “nice to have.” For example, you don’t need to include a text editor in a database image. ### Run only one process per container In almost all cases, you should only run a single process in a single container. Decoupling applications into multiple containers makes it much easier to scale horizontally and reuse containers. If that service depends on another service, make use of [container linking](https://docs.docker.com/userguide/dockerlinks/). ### Minimize the number of layers You need to find the balance between readability (and thus long-term maintainability) of the `Dockerfile` and minimizing the number of layers it uses. Be strategic and cautious about the number of layers you use. ### Sort multi-line arguments Whenever possible, ease later changes by sorting multi-line arguments alphanumerically. This will help you avoid duplication of packages and make the list much easier to update. This also makes PRs a lot easier to read and review. Adding a space before a backslash (`\`) helps as well. Here’s an example from the [`buildpack-deps` image](https://github.com/docker-library/buildpack-deps): RUN apt-get update && apt-get install -y \ bzr \ cvs \ git \ mercurial \ subversion ### Build cache During the process of building an image Docker will step through the instructions in your `Dockerfile` executing each in the order specified. As each instruction is examined Docker will look for an existing image in its cache that it can reuse, rather than creating a new (duplicate) image. If you do not want to use the cache at all you can use the ` --no-cache=true` option on the `docker build` command. However, if you do let Docker use its cache then it is very important to understand when it will, and will not, find a matching image. The basic rules that Docker will follow are outlined below: * Starting with a base image that is already in the cache, the next instruction is compared against all child images derived from that base image to see if one of them was built using the exact same instruction. If not, the cache is invalidated. * In most cases simply comparing the instruction in the `Dockerfile` with one of the child images is sufficient. However, certain instructions require a little more examination and explanation. * For the `ADD` and `COPY` instructions, the contents of the file(s) in the image are examined and a checksum is calculated for each file. The last-modified and last-accessed times of the file(s) are not considered in these checksums. During the cache lookup, the checksum is compared against the checksum in the existing images. If anything has changed in the file(s), such as the contents and metadata, then the cache is invalidated. * Aside from the `ADD` and `COPY` commands cache checking will not look at the files in the container to determine a cache match. For example, when processing a `RUN apt-get -y update` command the files updated in the container will not be examined to determine if a cache hit exists. In that case just the command string itself will be used to find a match. Once the cache is invalidated, all subsequent `Dockerfile` commands will generate new images and the cache will not be used. ## The Dockerfile instructions Below you'll find recommendations for the best way to write the various instructions available for use in a `Dockerfile`. ### FROM [Dockerfile reference for the FROM instruction](https://docs.docker.com/reference/builder/#from) Whenever possible, use current Official Repositories as the basis for your image. We recommend the [Debian image](https://registry.hub.docker.com/_/debian/) since it’s very tightly controlled and kept extremely minimal (currently under 100 mb), while still being a full distribution. ### RUN [Dockerfile reference for the RUN instruction](https://docs.docker.com/reference/builder/#run) As always, to make your `Dockerfile` more readable, understandable, and maintainable, put long or complex `RUN` statements on multiple lines separated with backslashes. Probably the most common use-case for `RUN` is an application of `apt-get`. When using `apt-get`, here are a few things to keep in mind: * Don’t do `RUN apt-get update` on a single line. This will cause caching issues if the referenced archive gets updated, which will make your subsequent `apt-get install` fail without comment. * Avoid `RUN apt-get upgrade` or `dist-upgrade`, since many of the “essential” packages from the base images will fail to upgrade inside an unprivileged container. If a base package is out of date, you should contact its maintainers. If you know there’s a particular package, `foo`, that needs to be updated, use `apt-get install -y foo` and it will update automatically. * Do write instructions like: RUN apt-get update && apt-get install -y \ package-bar \ package-baz \ package-foo Writing the instruction this way not only makes it easier to read and maintain, but also, by including `apt-get update`, ensures that the cache will naturally be busted and the latest versions will be installed with no further coding or manual intervention required. * Further natural cache-busting can be realized by version-pinning packages (e.g., `package-foo=1.3.*`). This will force retrieval of that version regardless of what’s in the cache. Writing your `apt-get` code this way will greatly ease maintenance and reduce failures due to unanticipated changes in required packages. #### Example Below is a well-formed `RUN` instruction that demonstrates the above recommendations. Note that the last package, `s3cmd`, specifies a version `1.1.0*`. If the image previously used an older version, specifying the new one will cause a cache bust of `apt-get update` and ensure the installation of the new version (which in this case had a new, required feature). RUN apt-get update && apt-get install -y \ aufs-tools \ automake \ btrfs-tools \ build-essential \ curl \ dpkg-sig \ git \ iptables \ libapparmor-dev \ libcap-dev \ libsqlite3-dev \ lxc=1.0* \ mercurial \ parallel \ reprepro \ ruby1.9.1 \ ruby1.9.1-dev \ s3cmd=1.1.0* Writing the instruction this way also helps you avoid potential duplication of a given package because it is much easier to read than an instruction like: RUN apt-get install -y package-foo && apt-get install -y package-bar ### CMD [Dockerfile reference for the CMD instruction](https://docs.docker.com/reference/builder/#cmd) The `CMD` instruction should be used to run the software contained by your image, along with any arguments. `CMD` should almost always be used in the form of `CMD [“executable”, “param1”, “param2”…]`. Thus, if the image is for a service (Apache, Rails, etc.), you would run something like `CMD ["apache2","-DFOREGROUND"]`. Indeed, this form of the instruction is recommended for any service-based image. In most other cases, `CMD` should be given an interactive shell (bash, python, perl, etc), for example, `CMD ["perl", "-de0"]`, `CMD ["python"]`, or `CMD [“php”, “-a”]`. Using this form means that when you execute something like `docker run -it python`, you’ll get dropped into a usable shell, ready to go. `CMD` should rarely be used in the manner of `CMD [“param”, “param”]` in conjunction with [`ENTRYPOINT`](https://docs.docker.com/reference/builder/#entrypoint), unless you and your expected users are already quite familiar with how `ENTRYPOINT` works. ### EXPOSE [Dockerfile reference for the EXPOSE instruction](https://docs.docker.com/reference/builder/#expose) The `EXPOSE` instruction indicates the ports on which a container will listen for connections. Consequently, you should use the common, traditional port for your application. For example, an image containing the Apache web server would use `EXPOSE 80`, while an image containing MongoDB would use `EXPOSE 27017` and so on. For external access, your users can execute `docker run` with a flag indicating how to map the specified port to the port of their choice. For container linking, Docker provides environment variables for the path from the recipient container back to the source (ie, `MYSQL_PORT_3306_TCP`). ### ENV [Dockerfile reference for the ENV instruction](https://docs.docker.com/reference/builder/#env) In order to make new software easier to run, you can use `ENV` to update the `PATH` environment variable for the software your container installs. For example, `ENV PATH /usr/local/nginx/bin:$PATH` will ensure that `CMD [“nginx”]` just works. The `ENV` instruction is also useful for providing required environment variables specific to services you wish to containerize, such as Postgres’s `PGDATA`. Lastly, `ENV` can also be used to set commonly used version numbers so that version bumps are easier to maintain, as seen in the following example: ENV PG_MAJOR 9.3 ENV PG_VERSION 9.3.4 RUN curl -SL http://example.com/postgres-$PG_VERSION.tar.xz | tar -xJC /usr/src/postgress && … ENV PATH /usr/local/postgres-$PG_MAJOR/bin:$PATH Similar to having constant variables in a program (as opposed to hard-coding values), this approach lets you change a single `ENV` instruction to auto-magically bump the version of the software in your container. ### ADD or COPY [Dockerfile reference for the ADD instruction](https://docs.docker.com/reference/builder/#add)
[Dockerfile reference for the COPY instruction](https://docs.docker.com/reference/builder/#copy) Although `ADD` and `COPY` are functionally similar, generally speaking, `COPY` is preferred. That’s because it’s more transparent than `ADD`. `COPY` only supports the basic copying of local files into the container, while `ADD` has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for `ADD` is local tar file auto-extraction into the image, as in `ADD rootfs.tar.xz /`. If you have multiple `Dockerfile` steps that use different files from your context, `COPY` them individually, rather than all at once. This will ensure that each step's build cache is only invalidated (forcing the step to be re-run) if the specifically required files change. For example: COPY requirements.txt /tmp/ RUN pip install /tmp/requirements.txt COPY . /tmp/ Results in fewer cache invalidations for the `RUN` step, than if you put the `COPY . /tmp/` before it. Because image size matters, using `ADD` to fetch packages from remote URLs is strongly discouraged; you should use `curl` or `wget` instead. That way you can delete the files you no longer need after they've been extracted and you won't have to add another layer in your image. For example, you should avoid doing things like: ADD http://example.com/big.tar.xz /usr/src/things/ RUN tar -xJf /usr/src/things/big.tar.xz -C /usr/src/things RUN make -C /usr/src/things all And instead, do something like: RUN mkdir -p /usr/src/things \ && curl -SL http://example.com/big.tar.xz \ | tar -xJC /usr/src/things \ && make -C /usr/src/things all For other items (files, directories) that do not require `ADD`’s tar auto-extraction capability, you should always use `COPY`. ### ENTRYPOINT [Dockerfile reference for the ENTRYPOINT instruction](https://docs.docker.com/reference/builder/#entrypoint) The best use for `ENTRYPOINT` is to set the image's main command, allowing that image to be run as though it was that command (and then use `CMD` as the default flags). Let's start with an example of an image for the command line tool `s3cmd`: ENTRYPOINT ["s3cmd"] CMD ["--help"] Now the image can be run like this to show the command's help: $ docker run s3cmd Or using the right parameters to execute a command: $ docker run s3cmd ls s3://mybucket This is useful because the image name can double as a reference to the binary as shown in the command above. The `ENTRYPOINT` instruction can also be used in combination with a helper script, allowing it to function in a similar way to the command above, even when starting the tool may require more than one step. For example, the [Postgres Official Image](https://registry.hub.docker.com/_/postgres/) uses the following script as its `ENTRYPOINT`: ```bash #!/bin/bash set -e if [ "$1" = 'postgres' ]; then chown -R postgres "$PGDATA" if [ -z "$(ls -A "$PGDATA")" ]; then gosu postgres initdb fi exec gosu postgres "$@" fi exec "$@" ``` > **Note**: > This script uses [the `exec` Bash command](http://wiki.bash-hackers.org/commands/builtin/exec) > so that the final running application becomes the container's PID 1. This allows > the application to receive any Unix signals sent to the container. > See the [`ENTRYPOINT`](https://docs.docker.com/reference/builder/#entrypoint) > help for more details. The helper script is copied into the container and run via `ENTRYPOINT` on container start: COPY ./docker-entrypoint.sh / ENTRYPOINT ["/docker-entrypoint.sh"] This script allows the user to interact with Postgres in several ways. It can simply start Postgres: $ docker run postgres Or, it can be used to run Postgres and pass parameters to the server: $ docker run postgres postgres --help Lastly, it could also be used to start a totally different tool, such as Bash: $ docker run --rm -it postgres bash ### VOLUME [Dockerfile reference for the VOLUME instruction](https://docs.docker.com/reference/builder/#volume) The `VOLUME` instruction should be used to expose any database storage area, configuration storage, or files/folders created by your docker container. You are strongly encouraged to use `VOLUME` for any mutable and/or user-serviceable parts of your image. ### USER [Dockerfile reference for the USER instruction](https://docs.docker.com/reference/builder/#user) If a service can run without privileges, use `USER` to change to a non-root user. Start by creating the user and group in the `Dockerfile` with something like `RUN groupadd -r postgres && useradd -r -g postgres postgres`. > **Note:** Users and groups in an image get a non-deterministic > UID/GID in that the “next” UID/GID gets assigned regardless of image > rebuilds. So, if it’s critical, you should assign an explicit UID/GID. You should avoid installing or using `sudo` since it has unpredictable TTY and signal-forwarding behavior that can cause more problems than it solves. If you absolutely need functionality similar to `sudo` (e.g., initializing the daemon as root but running it as non-root), you may be able to use [“gosu”](https://github.com/tianon/gosu). Lastly, to reduce layers and complexity, avoid switching `USER` back and forth frequently. ### WORKDIR [Dockerfile reference for the WORKDIR instruction](https://docs.docker.com/reference/builder/#workdir) For clarity and reliability, you should always use absolute paths for your `WORKDIR`. Also, you should use `WORKDIR` instead of proliferating instructions like `RUN cd … && do-something`, which are hard to read, troubleshoot, and maintain. ### ONBUILD [Dockerfile reference for the ONBUILD instruction](https://docs.docker.com/reference/builder/#onbuild) An `ONBUILD` command executes after the current `Dockerfile` build completes. `ONBUILD` executes in any child image derived `FROM` the current image. Think of the `ONBUILD` command as an instruction the parent `Dockerfile` gives to the child `Dockerfile`. A Docker build executes `ONBUILD` commands before any command in a child `Dockerfile`. `ONBUILD` is useful for images that are going to be built `FROM` a given image. For example, you would use `ONBUILD` for a language stack image that builds arbitrary user software written in that language within the `Dockerfile`, as you can see in [Ruby’s `ONBUILD` variants](https://github.com/docker-library/ruby/blob/master/2.1/onbuild/Dockerfile). Images built from `ONBUILD` should get a separate tag, for example: `ruby:1.9-onbuild` or `ruby:2.0-onbuild`. Be careful when putting `ADD` or `COPY` in `ONBUILD`. The “onbuild” image will fail catastrophically if the new build's context is missing the resource being added. Adding a separate tag, as recommended above, will help mitigate this by allowing the `Dockerfile` author to make a choice. ## Examples for Official Repositories These Official Repositories have exemplary `Dockerfile`s: * [Go](https://registry.hub.docker.com/_/golang/) * [Perl](https://registry.hub.docker.com/_/perl/) * [Hy](https://registry.hub.docker.com/_/hylang/) * [Rails](https://registry.hub.docker.com/_/rails) ## Additional resources: * [Dockerfile Reference](https://docs.docker.com/reference/builder/) * [More about Base Images](https://docs.docker.com/articles/baseimages/) * [More about Automated Builds](https://docs.docker.com/docker-hub/builds/) * [Guidelines for Creating Official Repositories](https://docs.docker.com/docker-hub/official_repos/) ================================================ FILE: vendor/github.com/docker/docker/docs/articles/dsc.md ================================================ # Using PowerShell DSC Windows PowerShell Desired State Configuration (DSC) is a configuration management tool that extends the existing functionality of Windows PowerShell. DSC uses a declarative syntax to define the state in which a target should be configured. More information about PowerShell DSC can be found at [http://technet.microsoft.com/en-us/library/dn249912.aspx](http://technet.microsoft.com/en-us/library/dn249912.aspx). ## Requirements To use this guide you'll need a Windows host with PowerShell v4.0 or newer. The included DSC configuration script also uses the official PPA so only an Ubuntu target is supported. The Ubuntu target must already have the required OMI Server and PowerShell DSC for Linux providers installed. More information can be found at [https://github.com/MSFTOSSMgmt/WPSDSCLinux](https://github.com/MSFTOSSMgmt/WPSDSCLinux). The source repository listed below also includes PowerShell DSC for Linux installation and init scripts along with more detailed installation information. ## Installation The DSC configuration example source is available in the following repository: [https://github.com/anweiss/DockerClientDSC](https://github.com/anweiss/DockerClientDSC). It can be cloned with: $ git clone https://github.com/anweiss/DockerClientDSC.git ## Usage The DSC configuration utilizes a set of shell scripts to determine whether or not the specified Docker components are configured on the target node(s). The source repository also includes a script (`RunDockerClientConfig.ps1`) that can be used to establish the required CIM session(s) and execute the `Set-DscConfiguration` cmdlet. More detailed usage information can be found at [https://github.com/anweiss/DockerClientDSC](https://github.com/anweiss/DockerClientDSC). ### Install Docker The Docker installation configuration is equivalent to running: ``` apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys\ 36A1D7869245C8950F966E92D8576A8BA88D21E9 sh -c "echo deb https://get.docker.com/ubuntu docker main\ > /etc/apt/sources.list.d/docker.list" apt-get update apt-get install lxc-docker ``` Ensure that your current working directory is set to the `DockerClientDSC` source and load the DockerClient configuration into the current PowerShell session ```powershell . .\DockerClient.ps1 ``` Generate the required DSC configuration .mof file for the targeted node ```powershell DockerClient -Hostname "myhost" ``` A sample DSC configuration data file has also been included and can be modified and used in conjunction with or in place of the `Hostname` parameter: ```powershell DockerClient -ConfigurationData .\DockerConfigData.psd1 ``` Start the configuration application process on the targeted node ```powershell .\RunDockerClientConfig.ps1 -Hostname "myhost" ``` The `RunDockerClientConfig.ps1` script can also parse a DSC configuration data file and execute configurations against multiple nodes as such: ```powershell .\RunDockerClientConfig.ps1 -ConfigurationData .\DockerConfigData.psd1 ``` ### Images Image configuration is equivalent to running: `docker pull [image]` or `docker rmi -f [IMAGE]`. Using the same steps defined above, execute `DockerClient` with the `Image` parameter and apply the configuration: ```powershell DockerClient -Hostname "myhost" -Image "node" .\RunDockerClientConfig.ps1 -Hostname "myhost" ``` You can also configure the host to pull multiple images: ```powershell DockerClient -Hostname "myhost" -Image "node","mongo" .\RunDockerClientConfig.ps1 -Hostname "myhost" ``` To remove images, use a hashtable as follows: ```powershell DockerClient -Hostname "myhost" -Image @{Name="node"; Remove=$true} .\RunDockerClientConfig.ps1 -Hostname $hostname ``` ### Containers Container configuration is equivalent to running: ``` docker run -d --name="[containername]" -p '[port]' -e '[env]' --link '[link]'\ '[image]' '[command]' ``` or ``` docker rm -f [containername] ``` To create or remove containers, you can use the `Container` parameter with one or more hashtables. The hashtable(s) passed to this parameter can have the following properties: - Name (required) - Image (required unless Remove property is set to `$true`) - Port - Env - Link - Command - Remove For example, create a hashtable with the settings for your container: ```powershell $webContainer = @{Name="web"; Image="anweiss/docker-platynem"; Port="80:80"} ``` Then, using the same steps defined above, execute `DockerClient` with the `-Image` and `-Container` parameters: ```powershell DockerClient -Hostname "myhost" -Image node -Container $webContainer .\RunDockerClientConfig.ps1 -Hostname "myhost" ``` Existing containers can also be removed as follows: ```powershell $containerToRemove = @{Name="web"; Remove=$true} DockerClient -Hostname "myhost" -Container $containerToRemove .\RunDockerClientConfig.ps1 -Hostname "myhost" ``` Here is a hashtable with all of the properties that can be used to create a container: ```powershell $containerProps = @{Name="web"; Image="node:latest"; Port="80:80"; ` Env="PORT=80"; Link="db:db"; Command="grunt"} ``` ================================================ FILE: vendor/github.com/docker/docker/docs/articles/host_integration.md ================================================ # Automatically start containers As of Docker 1.2, [restart policies](/reference/commandline/cli/#restart-policies) are the built-in Docker mechanism for restarting containers when they exit. If set, restart policies will be used when the Docker daemon starts up, as typically happens after a system boot. Restart policies will ensure that linked containers are started in the correct order. If restart policies don't suit your needs (i.e., you have non-Docker processes that depend on Docker containers), you can use a process manager like [upstart](http://upstart.ubuntu.com/), [systemd](http://freedesktop.org/wiki/Software/systemd/) or [supervisor](http://supervisord.org/) instead. ## Using a process manager Docker does not set any restart policies by default, but be aware that they will conflict with most process managers. So don't set restart policies if you are using a process manager. *Note:* Prior to Docker 1.2, restarting of Docker containers had to be explicitly disabled. Refer to the [previous version](/v1.1/articles/host_integration/) of this article for the details on how to do that. When you have finished setting up your image and are happy with your running container, you can then attach a process manager to manage it. When you run `docker start -a`, Docker will automatically attach to the running container, or start it if needed and forward all signals so that the process manager can detect when a container stops and correctly restart it. Here are a few sample scripts for systemd and upstart to integrate with Docker. ## Examples The examples below show configuration files for two popular process managers, upstart and systemd. In these examples, we'll assume that we have already created a container to run Redis with `--name=redis_server`. These files define a new service that will be started after the docker daemon service has started. ### upstart description "Redis container" author "Me" start on filesystem and started docker stop on runlevel [!2345] respawn script /usr/bin/docker start -a redis_server end script ### systemd [Unit] Description=Redis container Requires=docker.service After=docker.service [Service] Restart=always ExecStart=/usr/bin/docker start -a redis_server ExecStop=/usr/bin/docker stop -t 2 redis_server [Install] WantedBy=local.target If you need to pass options to the redis container (such as `--env`), then you'll need to use `docker run` rather than `docker start`. This will create a new container every time the service is started, which will be stopped and removed when the service is stopped. [Service] ... ExecStart=/usr/bin/docker run --env foo=bar --name redis_server redis ExecStop=/usr/bin/docker stop -t 2 redis_server ; /usr/bin/docker rm -f redis_server ... ================================================ FILE: vendor/github.com/docker/docker/docs/articles/https/Dockerfile ================================================ FROM debian RUN apt-get update && apt-get install -yq openssl ADD make_certs.sh / WORKDIR /data VOLUME ["/data"] CMD /make_certs.sh ================================================ FILE: vendor/github.com/docker/docker/docs/articles/https/Makefile ================================================ HOST:=boot2docker makescript: ./parsedocs.sh > make_certs.sh build: clean makescript docker build -t makecerts . cert: build docker run --rm -it -v $(CURDIR):/data -e HOST=$(HOST) -e YOUR_PUBLIC_IP=$(shell ip a | grep "inet " | sed "s/.*inet \([0-9.]*\)\/.*/\1/" | xargs echo | sed "s/ /,IP:/g") makecerts certs: cert run: sudo docker -d -D --tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem -H=0.0.0.0:6666 --pidfile=$(pwd)/docker.pid --graph=$(pwd)/graph client: sudo docker --tls --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem -H=$(HOST):6666 version sudo docker --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem -H=$(HOST):6666 info sudo curl https://$(HOST):6666/images/json --cert ./cert.pem --key ./key.pem --cacert ./ca.pem clean: rm -f ca-key.pem ca.pem ca.srl cert.pem client.csr extfile.cnf key.pem server-cert.pem server-key.pem server.csr extfile.cnf ================================================ FILE: vendor/github.com/docker/docker/docs/articles/https/README.md ================================================ This is an initial attempt to make it easier to test the examples in the https.md doc at this point, it has to be a manual thing, and I've been running it in boot2docker so my process is $ boot2docker ssh $$ git clone https://github.com/docker/docker $$ cd docker/docs/articles/https $$ make cert lots of things to see and manually answer, as openssl wants to be interactive **NOTE:** make sure you enter the hostname (`boot2docker` in my case) when prompted for `Computer Name`) $$ sudo make run start another terminal $ boot2docker ssh $$ cd docker/docs/articles/https $$ make client the last will connect first with `--tls` and then with `--tlsverify` both should succeed ================================================ FILE: vendor/github.com/docker/docker/docs/articles/https/make_certs.sh ================================================ #!/bin/sh openssl genrsa -aes256 -out ca-key.pem 2048 openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem openssl genrsa -out server-key.pem 2048 openssl req -subj "/CN=$HOST" -new -key server-key.pem -out server.csr echo subjectAltName = IP:$YOUR_PUBLIC_IP > extfile.cnf openssl x509 -req -days 365 -in server.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extfile extfile.cnf openssl genrsa -out key.pem 2048 openssl req -subj '/CN=client' -new -key key.pem -out client.csr echo extendedKeyUsage = clientAuth > extfile.cnf openssl x509 -req -days 365 -in client.csr -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem -extfile extfile.cnf rm -v client.csr server.csr chmod -v 0400 ca-key.pem key.pem server-key.pem chmod -v 0444 ca.pem server-cert.pem cert.pem # docker -d --tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem -H=0.0.0.0:7778 # docker --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem -H=$HOST:7778 version mkdir -pv ~/.docker cp -v {ca,cert,key}.pem ~/.docker export DOCKER_HOST=tcp://$HOST:7778 DOCKER_TLS_VERIFY=1 # docker ps export DOCKER_CERT_PATH=~/.docker/zone1/ # docker --tlsverify ps # curl https://$HOST:7778/images/json --cert ~/.docker/cert.pem --key ~/.docker/key.pem --cacert ~/.docker/ca.pem ================================================ FILE: vendor/github.com/docker/docker/docs/articles/https/parsedocs.sh ================================================ #!/bin/sh echo "#!/bin/sh" cat ../https.md | awk '{if (sub(/\\$/,"")) printf "%s", $0; else print $0}' \ | grep ' $ ' \ | sed 's/ $ //g' \ | sed 's/2375/7777/g' \ | sed 's/2376/7778/g' \ | sed 's/^docker/# docker/g' \ | sed 's/^curl/# curl/g' ================================================ FILE: vendor/github.com/docker/docker/docs/articles/https.md ================================================ # Protect the Docker daemon socket By default, Docker runs via a non-networked Unix socket. It can also optionally communicate using a HTTP socket. If you need Docker to be reachable via the network in a safe manner, you can enable TLS by specifying the `tlsverify` flag and pointing Docker's `tlscacert` flag to a trusted CA certificate. In the daemon mode, it will only allow connections from clients authenticated by a certificate signed by that CA. In the client mode, it will only connect to servers with a certificate signed by that CA. > **Warning**: > Using TLS and managing a CA is an advanced topic. Please familiarize yourself > with OpenSSL, x509 and TLS before using it in production. > **Warning**: > These TLS commands will only generate a working set of certificates on Linux. > Mac OS X comes with a version of OpenSSL that is incompatible with the > certificates that Docker requires. ## Create a CA, server and client keys with OpenSSL > **Note**: replace all instances of `$HOST` in the following example with the > DNS name of your Docker daemon's host. First generate CA private and public keys: $ openssl genrsa -aes256 -out ca-key.pem 4096 Generating RSA private key, 4096 bit long modulus ............................................................................................................................................................................................++ ........++ e is 65537 (0x10001) Enter pass phrase for ca-key.pem: Verifying - Enter pass phrase for ca-key.pem: $ openssl req -new -x509 -days 365 -key ca-key.pem -sha256 -out ca.pem Enter pass phrase for ca-key.pem: You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]: State or Province Name (full name) [Some-State]:Queensland Locality Name (eg, city) []:Brisbane Organization Name (eg, company) [Internet Widgits Pty Ltd]:Docker Inc Organizational Unit Name (eg, section) []:Boot2Docker Common Name (e.g. server FQDN or YOUR name) []:$HOST Email Address []:Sven@home.org.au Now that we have a CA, you can create a server key and certificate signing request (CSR). Make sure that "Common Name" (i.e., server FQDN or YOUR name) matches the hostname you will use to connect to Docker: > **Note**: replace all instances of `$HOST` in the following example with the > DNS name of your Docker daemon's host. $ openssl genrsa -out server-key.pem 4096 Generating RSA private key, 4096 bit long modulus .....................................................................++ .................................................................................................++ e is 65537 (0x10001) $ openssl req -subj "/CN=$HOST" -sha256 -new -key server-key.pem -out server.csr Next, we're going to sign the public key with our CA: Since TLS connections can be made via IP address as well as DNS name, they need to be specified when creating the certificate. For example, to allow connections using `10.10.10.20` and `127.0.0.1`: $ echo subjectAltName = IP:10.10.10.20,IP:127.0.0.1 > extfile.cnf $ openssl x509 -req -days 365 -sha256 -in server.csr -CA ca.pem -CAkey ca-key.pem \ -CAcreateserial -out server-cert.pem -extfile extfile.cnf Signature ok subject=/CN=your.host.com Getting CA Private Key Enter pass phrase for ca-key.pem: For client authentication, create a client key and certificate signing request: $ openssl genrsa -out key.pem 4096 Generating RSA private key, 4096 bit long modulus .........................................................++ ................++ e is 65537 (0x10001) $ openssl req -subj '/CN=client' -new -key key.pem -out client.csr To make the key suitable for client authentication, create an extensions config file: $ echo extendedKeyUsage = clientAuth > extfile.cnf Now sign the public key: $ openssl x509 -req -days 365 -sha256 -in client.csr -CA ca.pem -CAkey ca-key.pem \ -CAcreateserial -out cert.pem -extfile extfile.cnf Signature ok subject=/CN=client Getting CA Private Key Enter pass phrase for ca-key.pem: After generating `cert.pem` and `server-cert.pem` you can safely remove the two certificate signing requests: $ rm -v client.csr server.csr With a default `umask` of 022, your secret keys will be *world-readable* and writable for you and your group. In order to protect your keys from accidental damage, you will want to remove their write permissions. To make them only readable by you, change file modes as follows: $ chmod -v 0400 ca-key.pem key.pem server-key.pem Certificates can be world-readable, but you might want to remove write access to prevent accidental damage: $ chmod -v 0444 ca.pem server-cert.pem cert.pem Now you can make the Docker daemon only accept connections from clients providing a certificate trusted by our CA: $ docker -d --tlsverify --tlscacert=ca.pem --tlscert=server-cert.pem --tlskey=server-key.pem \ -H=0.0.0.0:2376 To be able to connect to Docker and validate its certificate, you now need to provide your client keys, certificates and trusted CA: > **Note**: replace all instances of `$HOST` in the following example with the > DNS name of your Docker daemon's host. $ docker --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem \ -H=$HOST:2376 version > **Note**: > Docker over TLS should run on TCP port 2376. > **Warning**: > As shown in the example above, you don't have to run the `docker` client > with `sudo` or the `docker` group when you use certificate authentication. > That means anyone with the keys can give any instructions to your Docker > daemon, giving them root access to the machine hosting the daemon. Guard > these keys as you would a root password! ## Secure by default If you want to secure your Docker client connections by default, you can move the files to the `.docker` directory in your home directory -- and set the `DOCKER_HOST` and `DOCKER_TLS_VERIFY` variables as well (instead of passing `-H=tcp://$HOST:2376` and `--tlsverify` on every call). $ mkdir -pv ~/.docker $ cp -v {ca,cert,key}.pem ~/.docker $ export DOCKER_HOST=tcp://$HOST:2376 DOCKER_TLS_VERIFY=1 Docker will now connect securely by default: $ docker ps ## Other modes If you don't want to have complete two-way authentication, you can run Docker in various other modes by mixing the flags. ### Daemon modes - `tlsverify`, `tlscacert`, `tlscert`, `tlskey` set: Authenticate clients - `tls`, `tlscert`, `tlskey`: Do not authenticate clients ### Client modes - `tls`: Authenticate server based on public/default CA pool - `tlsverify`, `tlscacert`: Authenticate server based on given CA - `tls`, `tlscert`, `tlskey`: Authenticate with client certificate, do not authenticate server based on given CA - `tlsverify`, `tlscacert`, `tlscert`, `tlskey`: Authenticate with client certificate and authenticate server based on given CA If found, the client will send its client certificate, so you just need to drop your keys into `~/.docker/{ca,cert,key}.pem`. Alternatively, if you want to store your keys in another location, you can specify that location using the environment variable `DOCKER_CERT_PATH`. $ export DOCKER_CERT_PATH=~/.docker/zone1/ $ docker --tlsverify ps ### Connecting to the secure Docker port using `curl` To use `curl` to make test API requests, you need to use three extra command line flags: $ curl https://$HOST:2376/images/json \ --cert ~/.docker/cert.pem \ --key ~/.docker/key.pem \ --cacert ~/.docker/ca.pem ================================================ FILE: vendor/github.com/docker/docker/docs/articles/networking.md ================================================ # Network configuration ## Summary When Docker starts, it creates a virtual interface named `docker0` on the host machine. It randomly chooses an address and subnet from the private range defined by [RFC 1918](http://tools.ietf.org/html/rfc1918) that are not in use on the host machine, and assigns it to `docker0`. Docker made the choice `172.17.42.1/16` when I started it a few minutes ago, for example — a 16-bit netmask providing 65,534 addresses for the host machine and its containers. The MAC address is generated using the IP address allocated to the container to avoid ARP collisions, using a range from `02:42:ac:11:00:00` to `02:42:ac:11:ff:ff`. > **Note:** > This document discusses advanced networking configuration > and options for Docker. In most cases you won't need this information. > If you're looking to get started with a simpler explanation of Docker > networking and an introduction to the concept of container linking see > the [Docker User Guide](/userguide/dockerlinks/). But `docker0` is no ordinary interface. It is a virtual *Ethernet bridge* that automatically forwards packets between any other network interfaces that are attached to it. This lets containers communicate both with the host machine and with each other. Every time Docker creates a container, it creates a pair of “peer” interfaces that are like opposite ends of a pipe — a packet sent on one will be received on the other. It gives one of the peers to the container to become its `eth0` interface and keeps the other peer, with a unique name like `vethAQI2QT`, out in the namespace of the host machine. By binding every `veth*` interface to the `docker0` bridge, Docker creates a virtual subnet shared between the host machine and every Docker container. The remaining sections of this document explain all of the ways that you can use Docker options and — in advanced cases — raw Linux networking commands to tweak, supplement, or entirely replace Docker's default networking configuration. ## Quick guide to the options Here is a quick list of the networking-related Docker command-line options, in case it helps you find the section below that you are looking for. Some networking command-line options can only be supplied to the Docker server when it starts up, and cannot be changed once it is running: * `-b BRIDGE` or `--bridge=BRIDGE` — see [Building your own bridge](#bridge-building) * `--bip=CIDR` — see [Customizing docker0](#docker0) * `--default-gateway=IP_ADDRESS` — see [How Docker networks a container](#container-networking) * `--default-gateway-v6=IP_ADDRESS` — see [IPv6](#ipv6) * `--fixed-cidr` — see [Customizing docker0](#docker0) * `--fixed-cidr-v6` — see [IPv6](#ipv6) * `-H SOCKET...` or `--host=SOCKET...` — This might sound like it would affect container networking, but it actually faces in the other direction: it tells the Docker server over what channels it should be willing to receive commands like “run container” and “stop container.” * `--icc=true|false` — see [Communication between containers](#between-containers) * `--ip=IP_ADDRESS` — see [Binding container ports](#binding-ports) * `--ipv6=true|false` — see [IPv6](#ipv6) * `--ip-forward=true|false` — see [Communication between containers and the wider world](#the-world) * `--iptables=true|false` — see [Communication between containers](#between-containers) * `--mtu=BYTES` — see [Customizing docker0](#docker0) * `--userland-proxy=true|false` — see [Binding container ports](#binding-ports) There are two networking options that can be supplied either at startup or when `docker run` is invoked. When provided at startup, set the default value that `docker run` will later use if the options are not specified: * `--dns=IP_ADDRESS...` — see [Configuring DNS](#dns) * `--dns-search=DOMAIN...` — see [Configuring DNS](#dns) Finally, several networking options can only be provided when calling `docker run` because they specify something specific to one container: * `-h HOSTNAME` or `--hostname=HOSTNAME` — see [Configuring DNS](#dns) and [How Docker networks a container](#container-networking) * `--link=CONTAINER_NAME_or_ID:ALIAS` — see [Configuring DNS](#dns) and [Communication between containers](#between-containers) * `--net=bridge|none|container:NAME_or_ID|host` — see [How Docker networks a container](#container-networking) * `--mac-address=MACADDRESS...` — see [How Docker networks a container](#container-networking) * `-p SPEC` or `--publish=SPEC` — see [Binding container ports](#binding-ports) * `-P` or `--publish-all=true|false` — see [Binding container ports](#binding-ports) To supply networking options to the Docker server at startup, use the `DOCKER_OPTS` variable in the Docker upstart configuration file. For Ubuntu, edit the variable in `/etc/default/docker` or `/etc/sysconfig/docker` for CentOS. The following example illustrates how to configure Docker on Ubuntu to recognize a newly built bridge. Edit the `/etc/default/docker` file: $ echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker Then restart the Docker server. $ sudo service docker start For additional information on bridges, see [building your own bridge](#building-your-own-bridge) later on this page. The following sections tackle all of the above topics in an order that we can move roughly from simplest to most complex. ## Configuring DNS How can Docker supply each container with a hostname and DNS configuration, without having to build a custom image with the hostname written inside? Its trick is to overlay three crucial `/etc` files inside the container with virtual files where it can write fresh information. You can see this by running `mount` inside a container: $$ mount ... /dev/disk/by-uuid/1fec...ebdf on /etc/hostname type ext4 ... /dev/disk/by-uuid/1fec...ebdf on /etc/hosts type ext4 ... /dev/disk/by-uuid/1fec...ebdf on /etc/resolv.conf type ext4 ... ... This arrangement allows Docker to do clever things like keep `resolv.conf` up to date across all containers when the host machine receives new configuration over DHCP later. The exact details of how Docker maintains these files inside the container can change from one Docker version to the next, so you should leave the files themselves alone and use the following Docker options instead. Four different options affect container domain name services. * `-h HOSTNAME` or `--hostname=HOSTNAME` — sets the hostname by which the container knows itself. This is written into `/etc/hostname`, into `/etc/hosts` as the name of the container's host-facing IP address, and is the name that `/bin/bash` inside the container will display inside its prompt. But the hostname is not easy to see from outside the container. It will not appear in `docker ps` nor in the `/etc/hosts` file of any other container. * `--link=CONTAINER_NAME_or_ID:ALIAS` — using this option as you `run` a container gives the new container's `/etc/hosts` an extra entry named `ALIAS` that points to the IP address of the container identified by `CONTAINER_NAME_or_ID`. This lets processes inside the new container connect to the hostname `ALIAS` without having to know its IP. The `--link=` option is discussed in more detail below, in the section [Communication between containers](#between-containers). Because Docker may assign a different IP address to the linked containers on restart, Docker updates the `ALIAS` entry in the `/etc/hosts` file of the recipient containers. * `--dns=IP_ADDRESS...` — sets the IP addresses added as `server` lines to the container's `/etc/resolv.conf` file. Processes in the container, when confronted with a hostname not in `/etc/hosts`, will connect to these IP addresses on port 53 looking for name resolution services. * `--dns-search=DOMAIN...` — sets the domain names that are searched when a bare unqualified hostname is used inside of the container, by writing `search` lines into the container's `/etc/resolv.conf`. When a container process attempts to access `host` and the search domain `example.com` is set, for instance, the DNS logic will not only look up `host` but also `host.example.com`. Use `--dns-search=.` if you don't wish to set the search domain. Regarding DNS settings, in the absence of either the `--dns=IP_ADDRESS...` or the `--dns-search=DOMAIN...` option, Docker makes each container's `/etc/resolv.conf` look like the `/etc/resolv.conf` of the host machine (where the `docker` daemon runs). When creating the container's `/etc/resolv.conf`, the daemon filters out all localhost IP address `nameserver` entries from the host's original file. Filtering is necessary because all localhost addresses on the host are unreachable from the container's network. After this filtering, if there are no more `nameserver` entries left in the container's `/etc/resolv.conf` file, the daemon adds public Google DNS nameservers (8.8.8.8 and 8.8.4.4) to the container's DNS configuration. If IPv6 is enabled on the daemon, the public IPv6 Google DNS nameservers will also be added (2001:4860:4860::8888 and 2001:4860:4860::8844). > **Note**: > If you need access to a host's localhost resolver, you must modify your > DNS service on the host to listen on a non-localhost address that is > reachable from within the container. You might wonder what happens when the host machine's `/etc/resolv.conf` file changes. The `docker` daemon has a file change notifier active which will watch for changes to the host DNS configuration. > **Note**: > The file change notifier relies on the Linux kernel's inotify feature. > Because this feature is currently incompatible with the overlay filesystem > driver, a Docker daemon using "overlay" will not be able to take advantage > of the `/etc/resolv.conf` auto-update feature. When the host file changes, all stopped containers which have a matching `resolv.conf` to the host will be updated immediately to this newest host configuration. Containers which are running when the host configuration changes will need to stop and start to pick up the host changes due to lack of a facility to ensure atomic writes of the `resolv.conf` file while the container is running. If the container's `resolv.conf` has been edited since it was started with the default configuration, no replacement will be attempted as it would overwrite the changes performed by the container. If the options (`--dns` or `--dns-search`) have been used to modify the default host configuration, then the replacement with an updated host's `/etc/resolv.conf` will not happen as well. > **Note**: > For containers which were created prior to the implementation of > the `/etc/resolv.conf` update feature in Docker 1.5.0: those > containers will **not** receive updates when the host `resolv.conf` > file changes. Only containers created with Docker 1.5.0 and above > will utilize this auto-update feature. ## Communication between containers and the wider world Whether a container can talk to the world is governed by two factors. 1. Is the host machine willing to forward IP packets? This is governed by the `ip_forward` system parameter. Packets can only pass between containers if this parameter is `1`. Usually you will simply leave the Docker server at its default setting `--ip-forward=true` and Docker will go set `ip_forward` to `1` for you when the server starts up. If you set `--ip-forward=false` and your system's kernel has it enabled, the `--ip-forward=false` option has no effect. To check the setting on your kernel or to turn it on manually: $ sysctl net.ipv4.conf.all.forwarding net.ipv4.conf.all.forwarding = 0 $ sysctl net.ipv4.conf.all.forwarding=1 $ sysctl net.ipv4.conf.all.forwarding net.ipv4.conf.all.forwarding = 1 Many using Docker will want `ip_forward` to be on, to at least make communication *possible* between containers and the wider world. May also be needed for inter-container communication if you are in a multiple bridge setup. 2. Do your `iptables` allow this particular connection? Docker will never make changes to your system `iptables` rules if you set `--iptables=false` when the daemon starts. Otherwise the Docker server will append forwarding rules to the `DOCKER` filter chain. Docker will not delete or modify any pre-existing rules from the `DOCKER` filter chain. This allows the user to create in advance any rules required to further restrict access to the containers. Docker's forward rules permit all external source IPs by default. To allow only a specific IP or network to access the containers, insert a negated rule at the top of the `DOCKER` filter chain. For example, to restrict external access such that *only* source IP 8.8.8.8 can access the containers, the following rule could be added: $ iptables -I DOCKER -i ext_if ! -s 8.8.8.8 -j DROP ## Communication between containers Whether two containers can communicate is governed, at the operating system level, by two factors. 1. Does the network topology even connect the containers' network interfaces? By default Docker will attach all containers to a single `docker0` bridge, providing a path for packets to travel between them. See the later sections of this document for other possible topologies. 2. Do your `iptables` allow this particular connection? Docker will never make changes to your system `iptables` rules if you set `--iptables=false` when the daemon starts. Otherwise the Docker server will add a default rule to the `FORWARD` chain with a blanket `ACCEPT` policy if you retain the default `--icc=true`, or else will set the policy to `DROP` if `--icc=false`. It is a strategic question whether to leave `--icc=true` or change it to `--icc=false` so that `iptables` will protect other containers — and the main host — from having arbitrary ports probed or accessed by a container that gets compromised. If you choose the most secure setting of `--icc=false`, then how can containers communicate in those cases where you *want* them to provide each other services? The answer is the `--link=CONTAINER_NAME_or_ID:ALIAS` option, which was mentioned in the previous section because of its effect upon name services. If the Docker daemon is running with both `--icc=false` and `--iptables=true` then, when it sees `docker run` invoked with the `--link=` option, the Docker server will insert a pair of `iptables` `ACCEPT` rules so that the new container can connect to the ports exposed by the other container — the ports that it mentioned in the `EXPOSE` lines of its `Dockerfile`. Docker has more documentation on this subject — see the [linking Docker containers](/userguide/dockerlinks) page for further details. > **Note**: > The value `CONTAINER_NAME` in `--link=` must either be an > auto-assigned Docker name like `stupefied_pare` or else the name you > assigned with `--name=` when you ran `docker run`. It cannot be a > hostname, which Docker will not recognize in the context of the > `--link=` option. You can run the `iptables` command on your Docker host to see whether the `FORWARD` chain has a default policy of `ACCEPT` or `DROP`: # When --icc=false, you should see a DROP rule: $ sudo iptables -L -n ... Chain FORWARD (policy ACCEPT) target prot opt source destination DOCKER all -- 0.0.0.0/0 0.0.0.0/0 DROP all -- 0.0.0.0/0 0.0.0.0/0 ... # When a --link= has been created under --icc=false, # you should see port-specific ACCEPT rules overriding # the subsequent DROP policy for all other packets: $ sudo iptables -L -n ... Chain FORWARD (policy ACCEPT) target prot opt source destination DOCKER all -- 0.0.0.0/0 0.0.0.0/0 DROP all -- 0.0.0.0/0 0.0.0.0/0 Chain DOCKER (1 references) target prot opt source destination ACCEPT tcp -- 172.17.0.2 172.17.0.3 tcp spt:80 ACCEPT tcp -- 172.17.0.3 172.17.0.2 tcp dpt:80 > **Note**: > Docker is careful that its host-wide `iptables` rules fully expose > containers to each other's raw IP addresses, so connections from one > container to another should always appear to be originating from the > first container's own IP address. ## Binding container ports to the host By default Docker containers can make connections to the outside world, but the outside world cannot connect to containers. Each outgoing connection will appear to originate from one of the host machine's own IP addresses thanks to an `iptables` masquerading rule on the host machine that the Docker server creates when it starts: # You can see that the Docker server creates a # masquerade rule that let containers connect # to IP addresses in the outside world: $ sudo iptables -t nat -L -n ... Chain POSTROUTING (policy ACCEPT) target prot opt source destination MASQUERADE all -- 172.17.0.0/16 0.0.0.0/0 ... But if you want containers to accept incoming connections, you will need to provide special options when invoking `docker run`. These options are covered in more detail in the [Docker User Guide](/userguide/dockerlinks) page. There are two approaches. First, you can supply `-P` or `--publish-all=true|false` to `docker run` which is a blanket operation that identifies every port with an `EXPOSE` line in the image's `Dockerfile` or `--expose ` commandline flag and maps it to a host port somewhere within an *ephemeral port range*. The `docker port` command then needs to be used to inspect created mapping. The *ephemeral port range* is configured by `/proc/sys/net/ipv4/ip_local_port_range` kernel parameter, typically ranging from 32768 to 61000. Mapping can be specified explicitly using `-p SPEC` or `--publish=SPEC` option. It allows you to particularize which port on docker server - which can be any port at all, not just one within the *ephemeral port range* — you want mapped to which port in the container. Either way, you should be able to peek at what Docker has accomplished in your network stack by examining your NAT tables. # What your NAT rules might look like when Docker # is finished setting up a -P forward: $ iptables -t nat -L -n ... Chain DOCKER (2 references) target prot opt source destination DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:49153 to:172.17.0.2:80 # What your NAT rules might look like when Docker # is finished setting up a -p 80:80 forward: Chain DOCKER (2 references) target prot opt source destination DNAT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:80 to:172.17.0.2:80 You can see that Docker has exposed these container ports on `0.0.0.0`, the wildcard IP address that will match any possible incoming port on the host machine. If you want to be more restrictive and only allow container services to be contacted through a specific external interface on the host machine, you have two choices. When you invoke `docker run` you can use either `-p IP:host_port:container_port` or `-p IP::port` to specify the external interface for one particular binding. Or if you always want Docker port forwards to bind to one specific IP address, you can edit your system-wide Docker server settings and add the option `--ip=IP_ADDRESS`. Remember to restart your Docker server after editing this setting. > **Note**: > With hairpin NAT enabled (`--userland-proxy=false`), containers port exposure > is achieved purely through iptables rules, and no attempt to bind the exposed > port is ever made. This means that nothing prevents shadowing a previously > listening service outside of Docker through exposing the same port for a > container. In such conflicting situation, Docker created iptables rules will > take precedence and route to the container. The `--userland-proxy` parameter, true by default, provides a userland implementation for inter-container and outside-to-container communication. When disabled, Docker uses both an additional `MASQUERADE` iptable rule and the `net.ipv4.route_localnet` kernel parameter which allow the host machine to connect to a local container exposed port through the commonly used loopback address: this alternative is preferred for performance reason. Again, this topic is covered without all of these low-level networking details in the [Docker User Guide](/userguide/dockerlinks/) document if you would like to use that as your port redirection reference instead. ## IPv6 As we are [running out of IPv4 addresses](http://en.wikipedia.org/wiki/IPv4_address_exhaustion) the IETF has standardized an IPv4 successor, [Internet Protocol Version 6](http://en.wikipedia.org/wiki/IPv6) , in [RFC 2460](https://www.ietf.org/rfc/rfc2460.txt). Both protocols, IPv4 and IPv6, reside on layer 3 of the [OSI model](http://en.wikipedia.org/wiki/OSI_model). ### IPv6 with Docker By default, the Docker server configures the container network for IPv4 only. You can enable IPv4/IPv6 dualstack support by running the Docker daemon with the `--ipv6` flag. Docker will set up the bridge `docker0` with the IPv6 [link-local address](http://en.wikipedia.org/wiki/Link-local_address) `fe80::1`. By default, containers that are created will only get a link-local IPv6 address. To assign globally routable IPv6 addresses to your containers you have to specify an IPv6 subnet to pick the addresses from. Set the IPv6 subnet via the `--fixed-cidr-v6` parameter when starting Docker daemon: docker -d --ipv6 --fixed-cidr-v6="2001:db8:1::/64" The subnet for Docker containers should at least have a size of `/80`. This way an IPv6 address can end with the container's MAC address and you prevent NDP neighbor cache invalidation issues in the Docker layer. With the `--fixed-cidr-v6` parameter set Docker will add a new route to the routing table. Further IPv6 routing will be enabled (you may prevent this by starting Docker daemon with `--ip-forward=false`): $ ip -6 route add 2001:db8:1::/64 dev docker0 $ sysctl net.ipv6.conf.default.forwarding=1 $ sysctl net.ipv6.conf.all.forwarding=1 All traffic to the subnet `2001:db8:1::/64` will now be routed via the `docker0` interface. Be aware that IPv6 forwarding may interfere with your existing IPv6 configuration: If you are using Router Advertisements to get IPv6 settings for your host's interfaces you should set `accept_ra` to `2`. Otherwise IPv6 enabled forwarding will result in rejecting Router Advertisements. E.g., if you want to configure `eth0` via Router Advertisements you should set: $ sysctl net.ipv6.conf.eth0.accept_ra=2 ![](/article-img/ipv6_basic_host_config.svg) Every new container will get an IPv6 address from the defined subnet. Further a default route will be added on `eth0` in the container via the address specified by the daemon option `--default-gateway-v6` if present, otherwise via `fe80::1`: docker run -it ubuntu bash -c "ip -6 addr show dev eth0; ip -6 route show" 15: eth0: mtu 1500 inet6 2001:db8:1:0:0:242:ac11:3/64 scope global valid_lft forever preferred_lft forever inet6 fe80::42:acff:fe11:3/64 scope link valid_lft forever preferred_lft forever 2001:db8:1::/64 dev eth0 proto kernel metric 256 fe80::/64 dev eth0 proto kernel metric 256 default via fe80::1 dev eth0 metric 1024 In this example the Docker container is assigned a link-local address with the network suffix `/64` (here: `fe80::42:acff:fe11:3/64`) and a globally routable IPv6 address (here: `2001:db8:1:0:0:242:ac11:3/64`). The container will create connections to addresses outside of the `2001:db8:1::/64` network via the link-local gateway at `fe80::1` on `eth0`. Often servers or virtual machines get a `/64` IPv6 subnet assigned (e.g. `2001:db8:23:42::/64`). In this case you can split it up further and provide Docker a `/80` subnet while using a separate `/80` subnet for other applications on the host: ![](/article-img/ipv6_slash64_subnet_config.svg) In this setup the subnet `2001:db8:23:42::/80` with a range from `2001:db8:23:42:0:0:0:0` to `2001:db8:23:42:0:ffff:ffff:ffff` is attached to `eth0`, with the host listening at `2001:db8:23:42::1`. The subnet `2001:db8:23:42:1::/80` with an address range from `2001:db8:23:42:1:0:0:0` to `2001:db8:23:42:1:ffff:ffff:ffff` is attached to `docker0` and will be used by containers. #### Using NDP proxying If your Docker host is only part of an IPv6 subnet but has not got an IPv6 subnet assigned you can use NDP proxying to connect your containers via IPv6 to the internet. For example your host has the IPv6 address `2001:db8::c001`, is part of the subnet `2001:db8::/64` and your IaaS provider allows you to configure the IPv6 addresses `2001:db8::c000` to `2001:db8::c00f`: $ ip -6 addr show 1: lo: mtu 65536 inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: mtu 1500 qlen 1000 inet6 2001:db8::c001/64 scope global valid_lft forever preferred_lft forever inet6 fe80::601:3fff:fea1:9c01/64 scope link valid_lft forever preferred_lft forever Let's split up the configurable address range into two subnets `2001:db8::c000/125` and `2001:db8::c008/125`. The first one can be used by the host itself, the latter by Docker: docker -d --ipv6 --fixed-cidr-v6 2001:db8::c008/125 You notice the Docker subnet is within the subnet managed by your router that is connected to `eth0`. This means all devices (containers) with the addresses from the Docker subnet are expected to be found within the router subnet. Therefore the router thinks it can talk to these containers directly. ![](/article-img/ipv6_ndp_proxying.svg) As soon as the router wants to send an IPv6 packet to the first container it will transmit a neighbor solicitation request, asking, who has `2001:db8::c009`? But it will get no answer because no one on this subnet has this address. The container with this address is hidden behind the Docker host. The Docker host has to listen to neighbor solicitation requests for the container address and send a response that itself is the device that is responsible for the address. This is done by a Kernel feature called `NDP Proxy`. You can enable it by executing $ sysctl net.ipv6.conf.eth0.proxy_ndp=1 Now you can add the container's IPv6 address to the NDP proxy table: $ ip -6 neigh add proxy 2001:db8::c009 dev eth0 This command tells the Kernel to answer to incoming neighbor solicitation requests regarding the IPv6 address `2001:db8::c009` on the device `eth0`. As a consequence of this all traffic to this IPv6 address will go into the Docker host and it will forward it according to its routing table via the `docker0` device to the container network: $ ip -6 route show 2001:db8::c008/125 dev docker0 metric 1 2001:db8::/64 dev eth0 proto kernel metric 256 You have to execute the `ip -6 neigh add proxy ...` command for every IPv6 address in your Docker subnet. Unfortunately there is no functionality for adding a whole subnet by executing one command. An alternative approach would be to use an NDP proxy daemon such as [ndppd](https://github.com/DanielAdolfsson/ndppd). ### Docker IPv6 cluster #### Switched network environment Using routable IPv6 addresses allows you to realize communication between containers on different hosts. Let's have a look at a simple Docker IPv6 cluster example: ![](/article-img/ipv6_switched_network_example.svg) The Docker hosts are in the `2001:db8:0::/64` subnet. Host1 is configured to provide addresses from the `2001:db8:1::/64` subnet to its containers. It has three routes configured: - Route all traffic to `2001:db8:0::/64` via `eth0` - Route all traffic to `2001:db8:1::/64` via `docker0` - Route all traffic to `2001:db8:2::/64` via Host2 with IP `2001:db8::2` Host1 also acts as a router on OSI layer 3. When one of the network clients tries to contact a target that is specified in Host1's routing table Host1 will forward the traffic accordingly. It acts as a router for all networks it knows: `2001:db8::/64`, `2001:db8:1::/64` and `2001:db8:2::/64`. On Host2 we have nearly the same configuration. Host2's containers will get IPv6 addresses from `2001:db8:2::/64`. Host2 has three routes configured: - Route all traffic to `2001:db8:0::/64` via `eth0` - Route all traffic to `2001:db8:2::/64` via `docker0` - Route all traffic to `2001:db8:1::/64` via Host1 with IP `2001:db8:0::1` The difference to Host1 is that the network `2001:db8:2::/64` is directly attached to the host via its `docker0` interface whereas it reaches `2001:db8:1::/64` via Host1's IPv6 address `2001:db8::1`. This way every container is able to contact every other container. The containers `Container1-*` share the same subnet and contact each other directly. The traffic between `Container1-*` and `Container2-*` will be routed via Host1 and Host2 because those containers do not share the same subnet. In a switched environment every host has to know all routes to every subnet. You always have to update the hosts' routing tables once you add or remove a host to the cluster. Every configuration in the diagram that is shown below the dashed line is handled by Docker: The `docker0` bridge IP address configuration, the route to the Docker subnet on the host, the container IP addresses and the routes on the containers. The configuration above the line is up to the user and can be adapted to the individual environment. #### Routed network environment In a routed network environment you replace the layer 2 switch with a layer 3 router. Now the hosts just have to know their default gateway (the router) and the route to their own containers (managed by Docker). The router holds all routing information about the Docker subnets. When you add or remove a host to this environment you just have to update the routing table in the router - not on every host. ![](/article-img/ipv6_routed_network_example.svg) In this scenario containers of the same host can communicate directly with each other. The traffic between containers on different hosts will be routed via their hosts and the router. For example packet from `Container1-1` to `Container2-1` will be routed through `Host1`, `Router` and `Host2` until it arrives at `Container2-1`. To keep the IPv6 addresses short in this example a `/48` network is assigned to every host. The hosts use a `/64` subnet of this for its own services and one for Docker. When adding a third host you would add a route for the subnet `2001:db8:3::/48` in the router and configure Docker on Host3 with `--fixed-cidr-v6=2001:db8:3:1::/64`. Remember the subnet for Docker containers should at least have a size of `/80`. This way an IPv6 address can end with the container's MAC address and you prevent NDP neighbor cache invalidation issues in the Docker layer. So if you have a `/64` for your whole environment use `/78` subnets for the hosts and `/80` for the containers. This way you can use 4096 hosts with 16 `/80` subnets each. Every configuration in the diagram that is visualized below the dashed line is handled by Docker: The `docker0` bridge IP address configuration, the route to the Docker subnet on the host, the container IP addresses and the routes on the containers. The configuration above the line is up to the user and can be adapted to the individual environment. ## Customizing docker0 By default, the Docker server creates and configures the host system's `docker0` interface as an *Ethernet bridge* inside the Linux kernel that can pass packets back and forth between other physical or virtual network interfaces so that they behave as a single Ethernet network. Docker configures `docker0` with an IP address, netmask and IP allocation range. The host machine can both receive and send packets to containers connected to the bridge, and gives it an MTU — the *maximum transmission unit* or largest packet length that the interface will allow — of either 1,500 bytes or else a more specific value copied from the Docker host's interface that supports its default route. These options are configurable at server startup: * `--bip=CIDR` — supply a specific IP address and netmask for the `docker0` bridge, using standard CIDR notation like `192.168.1.5/24`. * `--fixed-cidr=CIDR` — restrict the IP range from the `docker0` subnet, using the standard CIDR notation like `172.167.1.0/28`. This range must be and IPv4 range for fixed IPs (ex: 10.20.0.0/16) and must be a subset of the bridge IP range (`docker0` or set using `--bridge`). For example with `--fixed-cidr=192.168.1.0/25`, IPs for your containers will be chosen from the first half of `192.168.1.0/24` subnet. * `--mtu=BYTES` — override the maximum packet length on `docker0`. Once you have one or more containers up and running, you can confirm that Docker has properly connected them to the `docker0` bridge by running the `brctl` command on the host machine and looking at the `interfaces` column of the output. Here is a host with two different containers connected: # Display bridge info $ sudo brctl show bridge name bridge id STP enabled interfaces docker0 8000.3a1d7362b4ee no veth65f9 vethdda6 If the `brctl` command is not installed on your Docker host, then on Ubuntu you should be able to run `sudo apt-get install bridge-utils` to install it. Finally, the `docker0` Ethernet bridge settings are used every time you create a new container. Docker selects a free IP address from the range available on the bridge each time you `docker run` a new container, and configures the container's `eth0` interface with that IP address and the bridge's netmask. The Docker host's own IP address on the bridge is used as the default gateway by which each container reaches the rest of the Internet. # The network, as seen from a container $ docker run -i -t --rm base /bin/bash $$ ip addr show eth0 24: eth0: mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 32:6f:e0:35:57:91 brd ff:ff:ff:ff:ff:ff inet 172.17.0.3/16 scope global eth0 valid_lft forever preferred_lft forever inet6 fe80::306f:e0ff:fe35:5791/64 scope link valid_lft forever preferred_lft forever $$ ip route default via 172.17.42.1 dev eth0 172.17.0.0/16 dev eth0 proto kernel scope link src 172.17.0.3 $$ exit Remember that the Docker host will not be willing to forward container packets out on to the Internet unless its `ip_forward` system setting is `1` — see the section above on [Communication between containers](#between-containers) for details. ## Building your own bridge If you want to take Docker out of the business of creating its own Ethernet bridge entirely, you can set up your own bridge before starting Docker and use `-b BRIDGE` or `--bridge=BRIDGE` to tell Docker to use your bridge instead. If you already have Docker up and running with its old `docker0` still configured, you will probably want to begin by stopping the service and removing the interface: # Stopping Docker and removing docker0 $ sudo service docker stop $ sudo ip link set dev docker0 down $ sudo brctl delbr docker0 $ sudo iptables -t nat -F POSTROUTING Then, before starting the Docker service, create your own bridge and give it whatever configuration you want. Here we will create a simple enough bridge that we really could just have used the options in the previous section to customize `docker0`, but it will be enough to illustrate the technique. # Create our own bridge $ sudo brctl addbr bridge0 $ sudo ip addr add 192.168.5.1/24 dev bridge0 $ sudo ip link set dev bridge0 up # Confirming that our bridge is up and running $ ip addr show bridge0 4: bridge0: mtu 1500 qdisc noop state UP group default link/ether 66:38:d0:0d:76:18 brd ff:ff:ff:ff:ff:ff inet 192.168.5.1/24 scope global bridge0 valid_lft forever preferred_lft forever # Tell Docker about it and restart (on Ubuntu) $ echo 'DOCKER_OPTS="-b=bridge0"' >> /etc/default/docker $ sudo service docker start # Confirming new outgoing NAT masquerade is set up $ sudo iptables -t nat -L -n ... Chain POSTROUTING (policy ACCEPT) target prot opt source destination MASQUERADE all -- 192.168.5.0/24 0.0.0.0/0 The result should be that the Docker server starts successfully and is now prepared to bind containers to the new bridge. After pausing to verify the bridge's configuration, try creating a container — you will see that its IP address is in your new IP address range, which Docker will have auto-detected. Just as we learned in the previous section, you can use the `brctl show` command to see Docker add and remove interfaces from the bridge as you start and stop containers, and can run `ip addr` and `ip route` inside a container to see that it has been given an address in the bridge's IP address range and has been told to use the Docker host's IP address on the bridge as its default gateway to the rest of the Internet. ## How Docker networks a container While Docker is under active development and continues to tweak and improve its network configuration logic, the shell commands in this section are rough equivalents to the steps that Docker takes when configuring networking for each new container. Let's review a few basics. To communicate using the Internet Protocol (IP), a machine needs access to at least one network interface at which packets can be sent and received, and a routing table that defines the range of IP addresses reachable through that interface. Network interfaces do not have to be physical devices. In fact, the `lo` loopback interface available on every Linux machine (and inside each Docker container) is entirely virtual — the Linux kernel simply copies loopback packets directly from the sender's memory into the receiver's memory. Docker uses special virtual interfaces to let containers communicate with the host machine — pairs of virtual interfaces called “peers” that are linked inside of the host machine's kernel so that packets can travel between them. They are simple to create, as we will see in a moment. The steps with which Docker configures a container are: 1. Create a pair of peer virtual interfaces. 2. Give one of them a unique name like `veth65f9`, keep it inside of the main Docker host, and bind it to `docker0` or whatever bridge Docker is supposed to be using. 3. Toss the other interface over the wall into the new container (which will already have been provided with an `lo` interface) and rename it to the much prettier name `eth0` since, inside of the container's separate and unique network interface namespace, there are no physical interfaces with which this name could collide. 4. Set the interface's MAC address according to the `--mac-address` parameter or generate a random one. 5. Give the container's `eth0` a new IP address from within the bridge's range of network addresses. The default route is set to the IP address passed to the Docker daemon using the `--default-gateway` option if specified, otherwise to the IP address that the Docker host owns on the bridge. The MAC address is generated from the IP address unless otherwise specified. This prevents ARP cache invalidation problems, when a new container comes up with an IP used in the past by another container with another MAC. With these steps complete, the container now possesses an `eth0` (virtual) network card and will find itself able to communicate with other containers and the rest of the Internet. You can opt out of the above process for a particular container by giving the `--net=` option to `docker run`, which takes four possible values. * `--net=bridge` — The default action, that connects the container to the Docker bridge as described above. * `--net=host` — Tells Docker to skip placing the container inside of a separate network stack. In essence, this choice tells Docker to **not containerize the container's networking**! While container processes will still be confined to their own filesystem and process list and resource limits, a quick `ip addr` command will show you that, network-wise, they live “outside” in the main Docker host and have full access to its network interfaces. Note that this does **not** let the container reconfigure the host network stack — that would require `--privileged=true` — but it does let container processes open low-numbered ports like any other root process. It also allows the container to access local network services like D-bus. This can lead to processes in the container being able to do unexpected things like [restart your computer](https://github.com/docker/docker/issues/6401). You should use this option with caution. * `--net=container:NAME_or_ID` — Tells Docker to put this container's processes inside of the network stack that has already been created inside of another container. The new container's processes will be confined to their own filesystem and process list and resource limits, but will share the same IP address and port numbers as the first container, and processes on the two containers will be able to connect to each other over the loopback interface. * `--net=none` — Tells Docker to put the container inside of its own network stack but not to take any steps to configure its network, leaving you free to build any of the custom configurations explored in the last few sections of this document. To get an idea of the steps that are necessary if you use `--net=none` as described in that last bullet point, here are the commands that you would run to reach roughly the same configuration as if you had let Docker do all of the configuration: # At one shell, start a container and # leave its shell idle and running $ docker run -i -t --rm --net=none base /bin/bash root@63f36fc01b5f:/# # At another shell, learn the container process ID # and create its namespace entry in /var/run/netns/ # for the "ip netns" command we will be using below $ docker inspect -f '{{.State.Pid}}' 63f36fc01b5f 2778 $ pid=2778 $ sudo mkdir -p /var/run/netns $ sudo ln -s /proc/$pid/ns/net /var/run/netns/$pid # Check the bridge's IP address and netmask $ ip addr show docker0 21: docker0: ... inet 172.17.42.1/16 scope global docker0 ... # Create a pair of "peer" interfaces A and B, # bind the A end to the bridge, and bring it up $ sudo ip link add A type veth peer name B $ sudo brctl addif docker0 A $ sudo ip link set A up # Place B inside the container's network namespace, # rename to eth0, and activate it with a free IP $ sudo ip link set B netns $pid $ sudo ip netns exec $pid ip link set dev B name eth0 $ sudo ip netns exec $pid ip link set eth0 address 12:34:56:78:9a:bc $ sudo ip netns exec $pid ip link set eth0 up $ sudo ip netns exec $pid ip addr add 172.17.42.99/16 dev eth0 $ sudo ip netns exec $pid ip route add default via 172.17.42.1 At this point your container should be able to perform networking operations as usual. When you finally exit the shell and Docker cleans up the container, the network namespace is destroyed along with our virtual `eth0` — whose destruction in turn destroys interface `A` out in the Docker host and automatically un-registers it from the `docker0` bridge. So everything gets cleaned up without our having to run any extra commands! Well, almost everything: # Clean up dangling symlinks in /var/run/netns find -L /var/run/netns -type l -delete Also note that while the script above used modern `ip` command instead of old deprecated wrappers like `ipconfig` and `route`, these older commands would also have worked inside of our container. The `ip addr` command can be typed as `ip a` if you are in a hurry. Finally, note the importance of the `ip netns exec` command, which let us reach inside and configure a network namespace as root. The same commands would not have worked if run inside of the container, because part of safe containerization is that Docker strips container processes of the right to configure their own networks. Using `ip netns exec` is what let us finish up the configuration without having to take the dangerous step of running the container itself with `--privileged=true`. ## Tools and examples Before diving into the following sections on custom network topologies, you might be interested in glancing at a few external tools or examples of the same kinds of configuration. Here are two: * Jérôme Petazzoni has created a `pipework` shell script to help you connect together containers in arbitrarily complex scenarios: * Brandon Rhodes has created a whole network topology of Docker containers for the next edition of Foundations of Python Network Programming that includes routing, NAT'd firewalls, and servers that offer HTTP, SMTP, POP, IMAP, Telnet, SSH, and FTP: Both tools use networking commands very much like the ones you saw in the previous section, and will see in the following sections. ## Building a point-to-point connection By default, Docker attaches all containers to the virtual subnet implemented by `docker0`. You can create containers that are each connected to some different virtual subnet by creating your own bridge as shown in [Building your own bridge](#bridge-building), starting each container with `docker run --net=none`, and then attaching the containers to your bridge with the shell commands shown in [How Docker networks a container](#container-networking). But sometimes you want two particular containers to be able to communicate directly without the added complexity of both being bound to a host-wide Ethernet bridge. The solution is simple: when you create your pair of peer interfaces, simply throw *both* of them into containers, and configure them as classic point-to-point links. The two containers will then be able to communicate directly (provided you manage to tell each container the other's IP address, of course). You might adjust the instructions of the previous section to go something like this: # Start up two containers in two terminal windows $ docker run -i -t --rm --net=none base /bin/bash root@1f1f4c1f931a:/# $ docker run -i -t --rm --net=none base /bin/bash root@12e343489d2f:/# # Learn the container process IDs # and create their namespace entries $ docker inspect -f '{{.State.Pid}}' 1f1f4c1f931a 2989 $ docker inspect -f '{{.State.Pid}}' 12e343489d2f 3004 $ sudo mkdir -p /var/run/netns $ sudo ln -s /proc/2989/ns/net /var/run/netns/2989 $ sudo ln -s /proc/3004/ns/net /var/run/netns/3004 # Create the "peer" interfaces and hand them out $ sudo ip link add A type veth peer name B $ sudo ip link set A netns 2989 $ sudo ip netns exec 2989 ip addr add 10.1.1.1/32 dev A $ sudo ip netns exec 2989 ip link set A up $ sudo ip netns exec 2989 ip route add 10.1.1.2/32 dev A $ sudo ip link set B netns 3004 $ sudo ip netns exec 3004 ip addr add 10.1.1.2/32 dev B $ sudo ip netns exec 3004 ip link set B up $ sudo ip netns exec 3004 ip route add 10.1.1.1/32 dev B The two containers should now be able to ping each other and make connections successfully. Point-to-point links like this do not depend on a subnet nor a netmask, but on the bare assertion made by `ip route` that some other single IP address is connected to a particular network interface. Note that point-to-point links can be safely combined with other kinds of network connectivity — there is no need to start the containers with `--net=none` if you want point-to-point links to be an addition to the container's normal networking instead of a replacement. A final permutation of this pattern is to create the point-to-point link between the Docker host and one container, which would allow the host to communicate with that one container on some single IP address and thus communicate “out-of-band” of the bridge that connects the other, more usual containers. But unless you have very specific networking needs that drive you to such a solution, it is probably far preferable to use `--icc=false` to lock down inter-container communication, as we explored earlier. ## Editing networking config files Starting with Docker v.1.2.0, you can now edit `/etc/hosts`, `/etc/hostname` and `/etc/resolve.conf` in a running container. This is useful if you need to install bind or other services that might override one of those files. Note, however, that changes to these files will not be saved by `docker commit`, nor will they be saved during `docker run`. That means they won't be saved in the image, nor will they persist when a container is restarted; they will only "stick" in a running container. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/puppet.md ================================================ # Using Puppet > *Note:* Please note this is a community contributed installation path. The > only `official` installation is using the > [*Ubuntu*](/installation/ubuntulinux) installation > path. This version may sometimes be out of date. ## Requirements To use this guide you'll need a working installation of Puppet from [Puppet Labs](https://puppetlabs.com) . The module also currently uses the official PPA so only works with Ubuntu. ## Installation The module is available on the [Puppet Forge](https://forge.puppetlabs.com/garethr/docker/) and can be installed using the built-in module tool. $ puppet module install garethr/docker It can also be found on [GitHub](https://github.com/garethr/garethr-docker) if you would rather download the source. ## Usage The module provides a puppet class for installing Docker and two defined types for managing images and containers. ### Installation include 'docker' ### Images The next step is probably to install a Docker image. For this, we have a defined type which can be used like so: docker::image { 'ubuntu': } This is equivalent to running: $ docker pull ubuntu Note that it will only be downloaded if an image of that name does not already exist. This is downloading a large binary so on first run can take a while. For that reason this define turns off the default 5 minute timeout for the exec type. Note that you can also remove images you no longer need with: docker::image { 'ubuntu': ensure => 'absent', } ### Containers Now you have an image where you can run commands within a container managed by Docker. docker::run { 'helloworld': image => 'ubuntu', command => '/bin/sh -c "while true; do echo hello world; sleep 1; done"', } This is equivalent to running the following command, but under upstart: $ docker run -d ubuntu /bin/sh -c "while true; do echo hello world; sleep 1; done" Run also contains a number of optional parameters: docker::run { 'helloworld': image => 'ubuntu', command => '/bin/sh -c "while true; do echo hello world; sleep 1; done"', ports => ['4444', '4555'], volumes => ['/var/lib/couchdb', '/var/log'], volumes_from => '6446ea52fbc9', memory_limit => 10485760, # bytes username => 'example', hostname => 'example.com', env => ['FOO=BAR', 'FOO2=BAR2'], dns => ['8.8.8.8', '8.8.4.4'], } > *Note:* > The `ports`, `env`, `dns` and `volumes` attributes can be set with either a single > string or as above with an array of values. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/registry_mirror.md ================================================ # Run a local registry mirror ## Why? If you have multiple instances of Docker running in your environment (e.g., multiple physical or virtual machines, all running the Docker daemon), each time one of them requires an image that it doesn't have it will go out to the internet and fetch it from the public Docker registry. By running a local registry mirror, you can keep most of the image fetch traffic on your local network. ## How does it work? The first time you request an image from your local registry mirror, it pulls the image from the public Docker registry and stores it locally before handing it back to you. On subsequent requests, the local registry mirror is able to serve the image from its own storage. ## How do I set up a local registry mirror? There are two steps to set up and use a local registry mirror. ### Step 1: Configure your Docker daemons to use the local registry mirror You will need to pass the `--registry-mirror` option to your Docker daemon on startup: docker --registry-mirror=http:// -d For example, if your mirror is serving on `http://10.0.0.2:5000`, you would run: docker --registry-mirror=http://10.0.0.2:5000 -d **NOTE:** Depending on your local host setup, you may be able to add the `--registry-mirror` options to the `DOCKER_OPTS` variable in `/etc/default/docker`. ### Step 2: Run the local registry mirror You will need to start a local registry mirror service. The [`registry` image](https://registry.hub.docker.com/_/registry/) provides this functionality. For example, to run a local registry mirror that serves on port `5000` and mirrors the content at `registry-1.docker.io`: docker run -p 5000:5000 \ -e STANDALONE=false \ -e MIRROR_SOURCE=https://registry-1.docker.io \ -e MIRROR_SOURCE_INDEX=https://index.docker.io \ registry ## Test it out With your mirror running, pull an image that you haven't pulled before (using `time` to time it): $ time docker pull node:latest Pulling repository node [...] real 1m14.078s user 0m0.176s sys 0m0.120s Now, remove the image from your local machine: $ docker rmi node:latest Finally, re-pull the image: $ time docker pull node:latest Pulling repository node [...] real 0m51.376s user 0m0.120s sys 0m0.116s The second time around, the local registry mirror served the image from storage, avoiding a trip out to the internet to refetch it. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/runmetrics.md ================================================ # Runtime metrics ## Docker stats You can use the `docker stats` command to live stream a container's runtime metrics. The command supports CPU, memory usage, memory limit, and network IO metrics. The following is a sample output from the `docker stats` command $ docker stats redis1 redis2 CONTAINER CPU % MEM USAGE/LIMIT MEM % NET I/O redis1 0.07% 796 KB/64 MB 1.21% 788 B/648 B redis2 0.07% 2.746 MB/64 MB 4.29% 1.266 KB/648 B The [docker stats](/reference/commandline/stats/) reference page has more details about the `docker stats` command. ## Control groups Linux Containers rely on [control groups]( https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt) which not only track groups of processes, but also expose metrics about CPU, memory, and block I/O usage. You can access those metrics and obtain network usage metrics as well. This is relevant for "pure" LXC containers, as well as for Docker containers. Control groups are exposed through a pseudo-filesystem. In recent distros, you should find this filesystem under `/sys/fs/cgroup`. Under that directory, you will see multiple sub-directories, called devices, freezer, blkio, etc.; each sub-directory actually corresponds to a different cgroup hierarchy. On older systems, the control groups might be mounted on `/cgroup`, without distinct hierarchies. In that case, instead of seeing the sub-directories, you will see a bunch of files in that directory, and possibly some directories corresponding to existing containers. To figure out where your control groups are mounted, you can run: $ grep cgroup /proc/mounts ## Enumerating cgroups You can look into `/proc/cgroups` to see the different control group subsystems known to the system, the hierarchy they belong to, and how many groups they contain. You can also look at `/proc//cgroup` to see which control groups a process belongs to. The control group will be shown as a path relative to the root of the hierarchy mountpoint; e.g., `/` means “this process has not been assigned into a particular group”, while `/lxc/pumpkin` means that the process is likely to be a member of a container named `pumpkin`. ## Finding the cgroup for a given container For each container, one cgroup will be created in each hierarchy. On older systems with older versions of the LXC userland tools, the name of the cgroup will be the name of the container. With more recent versions of the LXC tools, the cgroup will be `lxc/.` For Docker containers using cgroups, the container name will be the full ID or long ID of the container. If a container shows up as ae836c95b4c3 in `docker ps`, its long ID might be something like `ae836c95b4c3c9e9179e0e91015512da89fdec91612f63cebae57df9a5444c79`. You can look it up with `docker inspect` or `docker ps --no-trunc`. Putting everything together to look at the memory metrics for a Docker container, take a look at `/sys/fs/cgroup/memory/lxc//`. ## Metrics from cgroups: memory, CPU, block I/O For each subsystem (memory, CPU, and block I/O), you will find one or more pseudo-files containing statistics. ### Memory metrics: `memory.stat` Memory metrics are found in the "memory" cgroup. Note that the memory control group adds a little overhead, because it does very fine-grained accounting of the memory usage on your host. Therefore, many distros chose to not enable it by default. Generally, to enable it, all you have to do is to add some kernel command-line parameters: `cgroup_enable=memory swapaccount=1`. The metrics are in the pseudo-file `memory.stat`. Here is what it will look like: cache 11492564992 rss 1930993664 mapped_file 306728960 pgpgin 406632648 pgpgout 403355412 swap 0 pgfault 728281223 pgmajfault 1724 inactive_anon 46608384 active_anon 1884520448 inactive_file 7003344896 active_file 4489052160 unevictable 32768 hierarchical_memory_limit 9223372036854775807 hierarchical_memsw_limit 9223372036854775807 total_cache 11492564992 total_rss 1930993664 total_mapped_file 306728960 total_pgpgin 406632648 total_pgpgout 403355412 total_swap 0 total_pgfault 728281223 total_pgmajfault 1724 total_inactive_anon 46608384 total_active_anon 1884520448 total_inactive_file 7003344896 total_active_file 4489052160 total_unevictable 32768 The first half (without the `total_` prefix) contains statistics relevant to the processes within the cgroup, excluding sub-cgroups. The second half (with the `total_` prefix) includes sub-cgroups as well. Some metrics are "gauges", i.e., values that can increase or decrease (e.g., swap, the amount of swap space used by the members of the cgroup). Some others are "counters", i.e., values that can only go up, because they represent occurrences of a specific event (e.g., pgfault, which indicates the number of page faults which happened since the creation of the cgroup; this number can never decrease). - **cache:** the amount of memory used by the processes of this control group that can be associated precisely with a block on a block device. When you read from and write to files on disk, this amount will increase. This will be the case if you use "conventional" I/O (`open`, `read`, `write` syscalls) as well as mapped files (with `mmap`). It also accounts for the memory used by `tmpfs` mounts, though the reasons are unclear. - **rss:** the amount of memory that *doesn't* correspond to anything on disk: stacks, heaps, and anonymous memory maps. - **mapped_file:** indicates the amount of memory mapped by the processes in the control group. It doesn't give you information about *how much* memory is used; it rather tells you *how* it is used. - **pgfault and pgmajfault:** indicate the number of times that a process of the cgroup triggered a "page fault" and a "major fault", respectively. A page fault happens when a process accesses a part of its virtual memory space which is nonexistent or protected. The former can happen if the process is buggy and tries to access an invalid address (it will then be sent a `SIGSEGV` signal, typically killing it with the famous `Segmentation fault` message). The latter can happen when the process reads from a memory zone which has been swapped out, or which corresponds to a mapped file: in that case, the kernel will load the page from disk, and let the CPU complete the memory access. It can also happen when the process writes to a copy-on-write memory zone: likewise, the kernel will preempt the process, duplicate the memory page, and resume the write operation on the process` own copy of the page. "Major" faults happen when the kernel actually has to read the data from disk. When it just has to duplicate an existing page, or allocate an empty page, it's a regular (or "minor") fault. - **swap:** the amount of swap currently used by the processes in this cgroup. - **active_anon and inactive_anon:** the amount of *anonymous* memory that has been identified has respectively *active* and *inactive* by the kernel. "Anonymous" memory is the memory that is *not* linked to disk pages. In other words, that's the equivalent of the rss counter described above. In fact, the very definition of the rss counter is **active_anon** + **inactive_anon** - **tmpfs** (where tmpfs is the amount of memory used up by `tmpfs` filesystems mounted by this control group). Now, what's the difference between "active" and "inactive"? Pages are initially "active"; and at regular intervals, the kernel sweeps over the memory, and tags some pages as "inactive". Whenever they are accessed again, they are immediately retagged "active". When the kernel is almost out of memory, and time comes to swap out to disk, the kernel will swap "inactive" pages. - **active_file and inactive_file:** cache memory, with *active* and *inactive* similar to the *anon* memory above. The exact formula is cache = **active_file** + **inactive_file** + **tmpfs**. The exact rules used by the kernel to move memory pages between active and inactive sets are different from the ones used for anonymous memory, but the general principle is the same. Note that when the kernel needs to reclaim memory, it is cheaper to reclaim a clean (=non modified) page from this pool, since it can be reclaimed immediately (while anonymous pages and dirty/modified pages have to be written to disk first). - **unevictable:** the amount of memory that cannot be reclaimed; generally, it will account for memory that has been "locked" with `mlock`. It is often used by crypto frameworks to make sure that secret keys and other sensitive material never gets swapped out to disk. - **memory and memsw limits:** These are not really metrics, but a reminder of the limits applied to this cgroup. The first one indicates the maximum amount of physical memory that can be used by the processes of this control group; the second one indicates the maximum amount of RAM+swap. Accounting for memory in the page cache is very complex. If two processes in different control groups both read the same file (ultimately relying on the same blocks on disk), the corresponding memory charge will be split between the control groups. It's nice, but it also means that when a cgroup is terminated, it could increase the memory usage of another cgroup, because they are not splitting the cost anymore for those memory pages. ### CPU metrics: `cpuacct.stat` Now that we've covered memory metrics, everything else will look very simple in comparison. CPU metrics will be found in the `cpuacct` controller. For each container, you will find a pseudo-file `cpuacct.stat`, containing the CPU usage accumulated by the processes of the container, broken down between `user` and `system` time. If you're not familiar with the distinction, `user` is the time during which the processes were in direct control of the CPU (i.e., executing process code), and `system` is the time during which the CPU was executing system calls on behalf of those processes. Those times are expressed in ticks of 1/100th of a second. Actually, they are expressed in "user jiffies". There are `USER_HZ` *"jiffies"* per second, and on x86 systems, `USER_HZ` is 100. This used to map exactly to the number of scheduler "ticks" per second; but with the advent of higher frequency scheduling, as well as [tickless kernels]( http://lwn.net/Articles/549580/), the number of kernel ticks wasn't relevant anymore. It stuck around anyway, mainly for legacy and compatibility reasons. ### Block I/O metrics Block I/O is accounted in the `blkio` controller. Different metrics are scattered across different files. While you can find in-depth details in the [blkio-controller]( https://www.kernel.org/doc/Documentation/cgroups/blkio-controller.txt) file in the kernel documentation, here is a short list of the most relevant ones: - **blkio.sectors:** contain the number of 512-bytes sectors read and written by the processes member of the cgroup, device by device. Reads and writes are merged in a single counter. - **blkio.io_service_bytes:** indicates the number of bytes read and written by the cgroup. It has 4 counters per device, because for each device, it differentiates between synchronous vs. asynchronous I/O, and reads vs. writes. - **blkio.io_serviced:** the number of I/O operations performed, regardless of their size. It also has 4 counters per device. - **blkio.io_queued:** indicates the number of I/O operations currently queued for this cgroup. In other words, if the cgroup isn't doing any I/O, this will be zero. Note that the opposite is not true. In other words, if there is no I/O queued, it does not mean that the cgroup is idle (I/O-wise). It could be doing purely synchronous reads on an otherwise quiescent device, which is therefore able to handle them immediately, without queuing. Also, while it is helpful to figure out which cgroup is putting stress on the I/O subsystem, keep in mind that is is a relative quantity. Even if a process group does not perform more I/O, its queue size can increase just because the device load increases because of other devices. ## Network metrics Network metrics are not exposed directly by control groups. There is a good explanation for that: network interfaces exist within the context of *network namespaces*. The kernel could probably accumulate metrics about packets and bytes sent and received by a group of processes, but those metrics wouldn't be very useful. You want per-interface metrics (because traffic happening on the local `lo` interface doesn't really count). But since processes in a single cgroup can belong to multiple network namespaces, those metrics would be harder to interpret: multiple network namespaces means multiple `lo` interfaces, potentially multiple `eth0` interfaces, etc.; so this is why there is no easy way to gather network metrics with control groups. Instead we can gather network metrics from other sources: ### IPtables IPtables (or rather, the netfilter framework for which iptables is just an interface) can do some serious accounting. For instance, you can setup a rule to account for the outbound HTTP traffic on a web server: $ iptables -I OUTPUT -p tcp --sport 80 There is no `-j` or `-g` flag, so the rule will just count matched packets and go to the following rule. Later, you can check the values of the counters, with: $ iptables -nxvL OUTPUT Technically, `-n` is not required, but it will prevent iptables from doing DNS reverse lookups, which are probably useless in this scenario. Counters include packets and bytes. If you want to setup metrics for container traffic like this, you could execute a `for` loop to add two `iptables` rules per container IP address (one in each direction), in the `FORWARD` chain. This will only meter traffic going through the NAT layer; you will also have to add traffic going through the userland proxy. Then, you will need to check those counters on a regular basis. If you happen to use `collectd`, there is a [nice plugin](https://collectd.org/wiki/index.php/Plugin:IPTables) to automate iptables counters collection. ### Interface-level counters Since each container has a virtual Ethernet interface, you might want to check directly the TX and RX counters of this interface. You will notice that each container is associated to a virtual Ethernet interface in your host, with a name like `vethKk8Zqi`. Figuring out which interface corresponds to which container is, unfortunately, difficult. But for now, the best way is to check the metrics *from within the containers*. To accomplish this, you can run an executable from the host environment within the network namespace of a container using **ip-netns magic**. The `ip-netns exec` command will let you execute any program (present in the host system) within any network namespace visible to the current process. This means that your host will be able to enter the network namespace of your containers, but your containers won't be able to access the host, nor their sibling containers. Containers will be able to “see” and affect their sub-containers, though. The exact format of the command is: $ ip netns exec For example: $ ip netns exec mycontainer netstat -i `ip netns` finds the "mycontainer" container by using namespaces pseudo-files. Each process belongs to one network namespace, one PID namespace, one `mnt` namespace, etc., and those namespaces are materialized under `/proc//ns/`. For example, the network namespace of PID 42 is materialized by the pseudo-file `/proc/42/ns/net`. When you run `ip netns exec mycontainer ...`, it expects `/var/run/netns/mycontainer` to be one of those pseudo-files. (Symlinks are accepted.) In other words, to execute a command within the network namespace of a container, we need to: - Find out the PID of any process within the container that we want to investigate; - Create a symlink from `/var/run/netns/` to `/proc//ns/net` - Execute `ip netns exec ....` Please review [*Enumerating Cgroups*](#enumerating-cgroups) to learn how to find the cgroup of a process running in the container of which you want to measure network usage. From there, you can examine the pseudo-file named `tasks`, which contains the PIDs that are in the control group (i.e., in the container). Pick any one of them. Putting everything together, if the "short ID" of a container is held in the environment variable `$CID`, then you can do this: $ TASKS=/sys/fs/cgroup/devices/$CID*/tasks $ PID=$(head -n 1 $TASKS) $ mkdir -p /var/run/netns $ ln -sf /proc/$PID/ns/net /var/run/netns/$CID $ ip netns exec $CID netstat -i ## Tips for high-performance metric collection Note that running a new process each time you want to update metrics is (relatively) expensive. If you want to collect metrics at high resolutions, and/or over a large number of containers (think 1000 containers on a single host), you do not want to fork a new process each time. Here is how to collect metrics from a single process. You will have to write your metric collector in C (or any language that lets you do low-level system calls). You need to use a special system call, `setns()`, which lets the current process enter any arbitrary namespace. It requires, however, an open file descriptor to the namespace pseudo-file (remember: that's the pseudo-file in `/proc//ns/net`). However, there is a catch: you must not keep this file descriptor open. If you do, when the last process of the control group exits, the namespace will not be destroyed, and its network resources (like the virtual interface of the container) will stay around for ever (or until you close that file descriptor). The right approach would be to keep track of the first PID of each container, and re-open the namespace pseudo-file each time. ## Collecting metrics when a container exits Sometimes, you do not care about real time metric collection, but when a container exits, you want to know how much CPU, memory, etc. it has used. Docker makes this difficult because it relies on `lxc-start`, which carefully cleans up after itself, but it is still possible. It is usually easier to collect metrics at regular intervals (e.g., every minute, with the collectd LXC plugin) and rely on that instead. But, if you'd still like to gather the stats when a container stops, here is how: For each container, start a collection process, and move it to the control groups that you want to monitor by writing its PID to the tasks file of the cgroup. The collection process should periodically re-read the tasks file to check if it's the last process of the control group. (If you also want to collect network statistics as explained in the previous section, you should also move the process to the appropriate network namespace.) When the container exits, `lxc-start` will try to delete the control groups. It will fail, since the control group is still in use; but that's fine. You process should now detect that it is the only one remaining in the group. Now is the right time to collect all the metrics you need! Finally, your process should move itself back to the root control group, and remove the container control group. To remove a control group, just `rmdir` its directory. It's counter-intuitive to `rmdir` a directory as it still contains files; but remember that this is a pseudo-filesystem, so usual rules don't apply. After the cleanup is done, the collection process can exit safely. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/security.md ================================================ # Docker security There are three major areas to consider when reviewing Docker security: - the intrinsic security of the kernel and its support for namespaces and cgroups; - the attack surface of the Docker daemon itself; - loopholes in the container configuration profile, either by default, or when customized by users. - the "hardening" security features of the kernel and how they interact with containers. ## Kernel namespaces Docker containers are very similar to LXC containers, and they have similar security features. When you start a container with `docker run`, behind the scenes Docker creates a set of namespaces and control groups for the container. **Namespaces provide the first and most straightforward form of isolation**: processes running within a container cannot see, and even less affect, processes running in another container, or in the host system. **Each container also gets its own network stack**, meaning that a container doesn't get privileged access to the sockets or interfaces of another container. Of course, if the host system is setup accordingly, containers can interact with each other through their respective network interfaces — just like they can interact with external hosts. When you specify public ports for your containers or use [*links*](/userguide/dockerlinks) then IP traffic is allowed between containers. They can ping each other, send/receive UDP packets, and establish TCP connections, but that can be restricted if necessary. From a network architecture point of view, all containers on a given Docker host are sitting on bridge interfaces. This means that they are just like physical machines connected through a common Ethernet switch; no more, no less. How mature is the code providing kernel namespaces and private networking? Kernel namespaces were introduced [between kernel version 2.6.15 and 2.6.26](http://lxc.sourceforge.net/index.php/about/kernel-namespaces/). This means that since July 2008 (date of the 2.6.26 release, now 5 years ago), namespace code has been exercised and scrutinized on a large number of production systems. And there is more: the design and inspiration for the namespaces code are even older. Namespaces are actually an effort to reimplement the features of [OpenVZ]( http://en.wikipedia.org/wiki/OpenVZ) in such a way that they could be merged within the mainstream kernel. And OpenVZ was initially released in 2005, so both the design and the implementation are pretty mature. ## Control groups Control Groups are another key component of Linux Containers. They implement resource accounting and limiting. They provide many useful metrics, but they also help ensure that each container gets its fair share of memory, CPU, disk I/O; and, more importantly, that a single container cannot bring the system down by exhausting one of those resources. So while they do not play a role in preventing one container from accessing or affecting the data and processes of another container, they are essential to fend off some denial-of-service attacks. They are particularly important on multi-tenant platforms, like public and private PaaS, to guarantee a consistent uptime (and performance) even when some applications start to misbehave. Control Groups have been around for a while as well: the code was started in 2006, and initially merged in kernel 2.6.24. ## Docker daemon attack surface Running containers (and applications) with Docker implies running the Docker daemon. This daemon currently requires `root` privileges, and you should therefore be aware of some important details. First of all, **only trusted users should be allowed to control your Docker daemon**. This is a direct consequence of some powerful Docker features. Specifically, Docker allows you to share a directory between the Docker host and a guest container; and it allows you to do so without limiting the access rights of the container. This means that you can start a container where the `/host` directory will be the `/` directory on your host; and the container will be able to alter your host filesystem without any restriction. This is similar to how virtualization systems allow filesystem resource sharing. Nothing prevents you from sharing your root filesystem (or even your root block device) with a virtual machine. This has a strong security implication: for example, if you instrument Docker from a web server to provision containers through an API, you should be even more careful than usual with parameter checking, to make sure that a malicious user cannot pass crafted parameters causing Docker to create arbitrary containers. For this reason, the REST API endpoint (used by the Docker CLI to communicate with the Docker daemon) changed in Docker 0.5.2, and now uses a UNIX socket instead of a TCP socket bound on 127.0.0.1 (the latter being prone to cross-site-scripting attacks if you happen to run Docker directly on your local machine, outside of a VM). You can then use traditional UNIX permission checks to limit access to the control socket. You can also expose the REST API over HTTP if you explicitly decide to do so. However, if you do that, being aware of the above mentioned security implication, you should ensure that it will be reachable only from a trusted network or VPN; or protected with e.g., `stunnel` and client SSL certificates. You can also secure them with [HTTPS and certificates](/articles/https/). The daemon is also potentially vulnerable to other inputs, such as image loading from either disk with 'docker load', or from the network with 'docker pull'. This has been a focus of improvement in the community, especially for 'pull' security. While these overlap, it should be noted that 'docker load' is a mechanism for backup and restore and is not currently considered a secure mechanism for loading images. As of Docker 1.3.2, images are now extracted in a chrooted subprocess on Linux/Unix platforms, being the first-step in a wider effort toward privilege separation. Eventually, it is expected that the Docker daemon will run restricted privileges, delegating operations well-audited sub-processes, each with its own (very limited) scope of Linux capabilities, virtual network setup, filesystem management, etc. That is, most likely, pieces of the Docker engine itself will run inside of containers. Finally, if you run Docker on a server, it is recommended to run exclusively Docker in the server, and move all other services within containers controlled by Docker. Of course, it is fine to keep your favorite admin tools (probably at least an SSH server), as well as existing monitoring/supervision processes (e.g., NRPE, collectd, etc). ## Linux kernel capabilities By default, Docker starts containers with a restricted set of capabilities. What does that mean? Capabilities turn the binary "root/non-root" dichotomy into a fine-grained access control system. Processes (like web servers) that just need to bind on a port below 1024 do not have to run as root: they can just be granted the `net_bind_service` capability instead. And there are many other capabilities, for almost all the specific areas where root privileges are usually needed. This means a lot for container security; let's see why! Your average server (bare metal or virtual machine) needs to run a bunch of processes as root. Those typically include SSH, cron, syslogd; hardware management tools (e.g., load modules), network configuration tools (e.g., to handle DHCP, WPA, or VPNs), and much more. A container is very different, because almost all of those tasks are handled by the infrastructure around the container: - SSH access will typically be managed by a single server running on the Docker host; - `cron`, when necessary, should run as a user process, dedicated and tailored for the app that needs its scheduling service, rather than as a platform-wide facility; - log management will also typically be handed to Docker, or by third-party services like Loggly or Splunk; - hardware management is irrelevant, meaning that you never need to run `udevd` or equivalent daemons within containers; - network management happens outside of the containers, enforcing separation of concerns as much as possible, meaning that a container should never need to perform `ifconfig`, `route`, or ip commands (except when a container is specifically engineered to behave like a router or firewall, of course). This means that in most cases, containers will not need "real" root privileges *at all*. And therefore, containers can run with a reduced capability set; meaning that "root" within a container has much less privileges than the real "root". For instance, it is possible to: - deny all "mount" operations; - deny access to raw sockets (to prevent packet spoofing); - deny access to some filesystem operations, like creating new device nodes, changing the owner of files, or altering attributes (including the immutable flag); - deny module loading; - and many others. This means that even if an intruder manages to escalate to root within a container, it will be much harder to do serious damage, or to escalate to the host. This won't affect regular web apps; but malicious users will find that the arsenal at their disposal has shrunk considerably! By default Docker drops all capabilities except [those needed](https://github.com/docker/docker/blob/master/daemon/execdriver/native/template/default_template.go), a whitelist instead of a blacklist approach. You can see a full list of available capabilities in [Linux manpages](http://man7.org/linux/man-pages/man7/capabilities.7.html). One primary risk with running Docker containers is that the default set of capabilities and mounts given to a container may provide incomplete isolation, either independently, or when used in combination with kernel vulnerabilities. Docker supports the addition and removal of capabilities, allowing use of a non-default profile. This may make Docker more secure through capability removal, or less secure through the addition of capabilities. The best practice for users would be to remove all capabilities except those explicitly required for their processes. ## Other kernel security features Capabilities are just one of the many security features provided by modern Linux kernels. It is also possible to leverage existing, well-known systems like TOMOYO, AppArmor, SELinux, GRSEC, etc. with Docker. While Docker currently only enables capabilities, it doesn't interfere with the other systems. This means that there are many different ways to harden a Docker host. Here are a few examples. - You can run a kernel with GRSEC and PAX. This will add many safety checks, both at compile-time and run-time; it will also defeat many exploits, thanks to techniques like address randomization. It doesn't require Docker-specific configuration, since those security features apply system-wide, independent of containers. - If your distribution comes with security model templates for Docker containers, you can use them out of the box. For instance, we ship a template that works with AppArmor and Red Hat comes with SELinux policies for Docker. These templates provide an extra safety net (even though it overlaps greatly with capabilities). - You can define your own policies using your favorite access control mechanism. Just like there are many third-party tools to augment Docker containers with e.g., special network topologies or shared filesystems, you can expect to see tools to harden existing Docker containers without affecting Docker's core. Recent improvements in Linux namespaces will soon allow to run full-featured containers without root privileges, thanks to the new user namespace. This is covered in detail [here]( http://s3hh.wordpress.com/2013/07/19/creating-and-using-containers-without-privilege/). Moreover, this will solve the problem caused by sharing filesystems between host and guest, since the user namespace allows users within containers (including the root user) to be mapped to other users in the host system. Today, Docker does not directly support user namespaces, but they may still be utilized by Docker containers on supported kernels, by directly using the clone syscall, or utilizing the 'unshare' utility. Using this, some users may find it possible to drop more capabilities from their process as user namespaces provide an artificial capabilities set. Likewise, however, this artificial capabilities set may require use of 'capsh' to restrict the user-namespace capabilities set when using 'unshare'. Eventually, it is expected that Docker will have direct, native support for user-namespaces, simplifying the process of hardening containers. ## Conclusions Docker containers are, by default, quite secure; especially if you take care of running your processes inside the containers as non-privileged users (i.e., non-`root`). You can add an extra layer of safety by enabling AppArmor, SELinux, GRSEC, or your favorite hardening solution. Last but not least, if you see interesting security features in other containerization systems, these are simply kernels features that may be implemented in Docker as well. We welcome users to submit issues, pull requests, and communicate via the mailing list. References: * [Docker Containers: How Secure Are They? (2013)]( http://blog.docker.com/2013/08/containers-docker-how-secure-are-they/). * [On the Security of Containers (2014)](https://medium.com/@ewindisch/on-the-security-of-containers-2c60ffe25a9e). ================================================ FILE: vendor/github.com/docker/docker/docs/articles/systemd.md ================================================ # Control and configure Docker with systemd Many Linux distributions use systemd to start the Docker daemon. This document shows a few examples of how to customise Docker's settings. ## Starting the Docker daemon Once Docker is installed, you will need to start the Docker daemon. $ sudo systemctl start docker # or on older distributions, you may need to use $ sudo service docker start If you want Docker to start at boot, you should also: $ sudo systemctl enable docker # or on older distributions, you may need to use $ sudo chkconfig docker on ## Custom Docker daemon options There are a number of ways to configure the daemon flags and environment variables for your Docker daemon. If the `docker.service` file is set to use an `EnvironmentFile` (often pointing to `/etc/sysconfig/docker`) then you can modify the referenced file. Check if the `docker.service` uses an `EnvironmentFile`: $ sudo systemctl show docker | grep EnvironmentFile EnvironmentFile=-/etc/sysconfig/docker (ignore_errors=yes) Alternatively, find out where the service file is located, and look for the property: $ sudo systemctl status docker | grep Loaded Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled) $ sudo grep EnvironmentFile /usr/lib/systemd/system/docker.service EnvironmentFile=-/etc/sysconfig/docker You can customize the Docker daemon options using override files as explained in the [HTTP Proxy example](#http-proxy) below. The files located in `/usr/lib/systemd/system` or `/lib/systemd/system` contain the default options and should not be edited. ### Runtime directory and storage driver You may want to control the disk space used for Docker images, containers and volumes by moving it to a separate partition. In this example, we'll assume that your `docker.service` file looks something like: [Unit] Description=Docker Application Container Engine Documentation=https://docs.docker.com After=network.target docker.socket Requires=docker.socket [Service] Type=notify EnvironmentFile=-/etc/sysconfig/docker ExecStart=/usr/bin/docker -d -H fd:// $OPTIONS LimitNOFILE=1048576 LimitNPROC=1048576 [Install] Also=docker.socket This will allow us to add extra flags to the `/etc/sysconfig/docker` file by setting `OPTIONS`: OPTIONS="--graph /mnt/docker-data --storage-driver btrfs" You can also set other environment variables in this file, for example, the `HTTP_PROXY` environment variables described below. ### HTTP proxy This example overrides the default `docker.service` file. If you are behind a HTTP proxy server, for example in corporate settings, you will need to add this configuration in the Docker systemd service file. First, create a systemd drop-in directory for the docker service: mkdir /etc/systemd/system/docker.service.d Now create a file called `/etc/systemd/system/docker.service.d/http-proxy.conf` that adds the `HTTP_PROXY` environment variable: [Service] Environment="HTTP_PROXY=http://proxy.example.com:80/" If you have internal Docker registries that you need to contact without proxying you can specify them via the `NO_PROXY` environment variable: Environment="HTTP_PROXY=http://proxy.example.com:80/" "NO_PROXY=localhost,127.0.0.0/8,docker-registry.somecorporation.com" Flush changes: $ sudo systemctl daemon-reload Verify that the configuration has been loaded: $ sudo systemctl show docker --property Environment Environment=HTTP_PROXY=http://proxy.example.com:80/ Restart Docker: $ sudo systemctl restart docker ## Manually creating the systemd unit files When installing the binary without a package, you may want to integrate Docker with systemd. For this, simply install the two unit files (service and socket) from [the github repository](https://github.com/docker/docker/tree/master/contrib/init/systemd) to `/etc/systemd/system`. ================================================ FILE: vendor/github.com/docker/docker/docs/articles/using_supervisord.md ================================================ # Using Supervisor with Docker > **Note**: > - **If you don't like sudo** then see [*Giving non-root > access*](/installation/binaries/#giving-non-root-access) Traditionally a Docker container runs a single process when it is launched, for example an Apache daemon or a SSH server daemon. Often though you want to run more than one process in a container. There are a number of ways you can achieve this ranging from using a simple Bash script as the value of your container's `CMD` instruction to installing a process management tool. In this example we're going to make use of the process management tool, [Supervisor](http://supervisord.org/), to manage multiple processes in our container. Using Supervisor allows us to better control, manage, and restart the processes we want to run. To demonstrate this we're going to install and manage both an SSH daemon and an Apache daemon. ## Creating a Dockerfile Let's start by creating a basic `Dockerfile` for our new image. FROM ubuntu:13.04 MAINTAINER examples@docker.com ## Installing Supervisor We can now install our SSH and Apache daemons as well as Supervisor in our container. RUN apt-get update && apt-get install -y openssh-server apache2 supervisor RUN mkdir -p /var/lock/apache2 /var/run/apache2 /var/run/sshd /var/log/supervisor Here we're installing the `openssh-server`, `apache2` and `supervisor` (which provides the Supervisor daemon) packages. We're also creating four new directories that are needed to run our SSH daemon and Supervisor. ## Adding Supervisor's configuration file Now let's add a configuration file for Supervisor. The default file is called `supervisord.conf` and is located in `/etc/supervisor/conf.d/`. COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf Let's see what is inside our `supervisord.conf` file. [supervisord] nodaemon=true [program:sshd] command=/usr/sbin/sshd -D [program:apache2] command=/bin/bash -c "source /etc/apache2/envvars && exec /usr/sbin/apache2 -DFOREGROUND" The `supervisord.conf` configuration file contains directives that configure Supervisor and the processes it manages. The first block `[supervisord]` provides configuration for Supervisor itself. We're using one directive, `nodaemon` which tells Supervisor to run interactively rather than daemonize. The next two blocks manage the services we wish to control. Each block controls a separate process. The blocks contain a single directive, `command`, which specifies what command to run to start each process. ## Exposing ports and running Supervisor Now let's finish our `Dockerfile` by exposing some required ports and specifying the `CMD` instruction to start Supervisor when our container launches. EXPOSE 22 80 CMD ["/usr/bin/supervisord"] Here We've exposed ports 22 and 80 on the container and we're running the `/usr/bin/supervisord` binary when the container launches. ## Building our image We can now build our new image. $ docker build -t /supervisord . ## Running our Supervisor container Once We've got a built image we can launch a container from it. $ docker run -p 22 -p 80 -t -i /supervisord 2013-11-25 18:53:22,312 CRIT Supervisor running as root (no user in config file) 2013-11-25 18:53:22,312 WARN Included extra file "/etc/supervisor/conf.d/supervisord.conf" during parsing 2013-11-25 18:53:22,342 INFO supervisord started with pid 1 2013-11-25 18:53:23,346 INFO spawned: 'sshd' with pid 6 2013-11-25 18:53:23,349 INFO spawned: 'apache2' with pid 7 . . . We've launched a new container interactively using the `docker run` command. That container has run Supervisor and launched the SSH and Apache daemons with it. We've specified the `-p` flag to expose ports 22 and 80. From here we can now identify the exposed ports and connect to one or both of the SSH and Apache daemons. ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/accounts.md ================================================ # Accounts on Docker Hub ## Docker Hub accounts You can `search` for Docker images and `pull` them from [Docker Hub](https://hub.docker.com) without signing in or even having an account. However, in order to `push` images, leave comments or to *star* a repository, you are going to need a [Docker Hub](https://hub.docker.com) account. ### Registration for a Docker Hub account You can get a [Docker Hub](https://hub.docker.com) account by [signing up for one here](https://hub.docker.com/account/signup/). A valid email address is required to register, which you will need to verify for account activation. ### Email activation process You need to have at least one verified email address to be able to use your [Docker Hub](https://hub.docker.com) account. If you can't find the validation email, you can request another by visiting the [Resend Email Confirmation]( https://hub.docker.com/account/resend-email-confirmation/) page. ### Password reset process If you can't access your account for some reason, you can reset your password from the [*Password Reset*](https://hub.docker.com/account/forgot-password/) page. ## Organizations and groups A Docker Hub organization contains public and private repositories just like a user account. Access to push, pull or create these organisation owned repositories is allocated by defining groups of users and then assigning group rights to specific repositories. This allows you to distribute limited access Docker images, and to select which Docker Hub users can publish new images. ### Creating and viewing organizations You can see what organizations [you belong to and add new organizations]( https://hub.docker.com/account/organizations/) from the Account Settings tab. They are also listed below your user name on your repositories page and in your account profile. ![organizations](/docker-hub/hub-images/orgs.png) ### Organization groups Users in the `Owners` group of an organization can create and modify the membership of groups. Unless they are the organization's `Owner`, users can only see groups of which they are members. ![groups](/docker-hub/hub-images/groups.png) ### Repository group permissions Use organization groups to manage the users that can interact with your repositories. You must be in an organization's `Owners` group to create a new group, Hub repository, or automated build. As an `Owner`, you then delegate the following repository access rights to groups: | Access Right | Description | |--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `Read` | Users with this right can view, search, and pull a private repository. | | `Write` | Users with this right can push to non-automated repositories on the Docker Hub. | | `Admin` | Users with this right can modify a repository's "Description", "Collaborators" rights. They can also mark a repository as unlisted, change its "Public/Private" status and "Delete" the repository. Finally, `Admin` rights are required to read the build log on a repo. | | | | Regardless of their actual access rights, users with unverified email addresses have `Read` access to the repository. Once they have verified their address, they have their full access rights as granted on the organization. ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/builds.md ================================================ # Automated Builds on Docker Hub ## About Automated Builds *Automated Builds* are a special feature of Docker Hub which allow you to use [Docker Hub's](https://hub.docker.com) build clusters to automatically create images from a GitHub or Bitbucket repository containing a `Dockerfile` The system will clone your repository and build the image described by the `Dockerfile` using the directory the `Dockerfile` is in (and subdirectories) as the build context. The resulting automated image will then be uploaded to the Docker Hub registry and marked as an *Automated Build*. Automated Builds have several advantages: * Users of *your* Automated Build can trust that the resulting image was built exactly as specified. * The `Dockerfile` will be available to anyone with access to your repository on the Docker Hub registry. * Because the process is automated, Automated Builds help to make sure that your repository is always up to date. Automated Builds are supported for both public and private repositories on both [GitHub](http://github.com) and [Bitbucket](https://bitbucket.org/). To use Automated Builds, you must have an [account on Docker Hub]( https://docs.docker.com/userguide/dockerhub/#creating-a-docker-hub-account) and on GitHub and/or Bitbucket. In either case, the account needs to be properly validated and activated before you can link to it. The first time you to set up an Automated Build, your [Docker Hub](https://hub.docker.com) account will need to be linked to a GitHub or Bitbucket account. This will allow the registry to see your repositories. If you have previously linked your Docker Hub account, and want to view or modify that link, click on the "Manage - Settings" link in the sidebar, and then "Linked Accounts" in your Settings sidebar. ## Automated Builds from GitHub If you've previously linked your Docker Hub account to your GitHub account, you'll be able to skip to the [Creating an Automated Build](#creating-an-automated-build). ### Linking your Docker Hub account to a GitHub account > *Note:* > Automated Builds currently require *read* and *write* access since > [Docker Hub](https://hub.docker.com) needs to setup a GitHub service > hook. We have no choice here, this is how GitHub manages permissions, sorry! > We do guarantee nothing else will be touched in your account. To get started, log into your Docker Hub account and click the "+ Add Repository" button at the upper right of the screen. Then select [Automated Build](https://registry.hub.docker.com/builds/add/). Select the [GitHub service](https://registry.hub.docker.com/associate/github/). When linking to GitHub, you'll need to select either "Public and Private", or "Limited" linking. The "Public and Private" option is the easiest to use, as it grants the Docker Hub full access to all of your repositories. GitHub also allows you to grant access to repositories belonging to your GitHub organizations. By choosing the "Limited" linking, your Docker Hub account only gets permission to access your public data and public repositories. Follow the onscreen instructions to authorize and link your GitHub account to Docker Hub. Once it is linked, you'll be able to choose a source repository from which to create the Automatic Build. You will be able to review and revoke Docker Hub's access by visiting the [GitHub User's Applications settings](https://github.com/settings/applications). > **Note**: If you delete the GitHub account linkage that is used for one of your > automated build repositories, the previously built images will still be available. > If you re-link to that GitHub account later, the automated build can be started > using the "Start Build" button on the Hub, or if the webhook on the GitHub repository > still exists, will be triggered by any subsequent commits. ### Auto builds and limited linked GitHub accounts. If you selected to link your GitHub account with only a "Limited" link, then after creating your automated build, you will need to either manually trigger a Docker Hub build using the "Start a Build" button, or add the GitHub webhook manually, as described in [GitHub Service Hooks](#github-service-hooks). ### Changing the GitHub user link If you want to remove, or change the level of linking between your GitHub account and the Docker Hub, you need to do this in two places. First, remove the "Linked Account" from your Docker Hub "Settings". Then go to your GitHub account's Personal settings, and in the "Applications" section, "Revoke access". You can now re-link your account at any time. ### GitHub organizations GitHub organizations and private repositories forked from organizations will be made available to auto build using the "Docker Hub Registry" application, which needs to be added to the organization - and then will apply to all users. To check, or request access, go to your GitHub user's "Setting" page, select the "Applications" section from the left side bar, then click the "View" button for "Docker Hub Registry". ![Check User access to GitHub](/docker-hub/hub-images/gh-check-user-org-dh-app-access.png) The organization's administrators may need to go to the Organization's "Third party access" screen in "Settings" to Grant or Deny access to the Docker Hub Registry application. This change will apply to all organization members. ![Check Docker Hub application access to Organization](/docker-hub/hub-images/gh-check-admin-org-dh-app-access.png) More detailed access controls to specific users and GitHub repositories would be managed using the GitHub People and Teams interfaces. ### Creating an Automated Build You can [create an Automated Build]( https://registry.hub.docker.com/builds/github/select/) from any of your public or private GitHub repositories that have a `Dockerfile`. Once you've selected the source repository, you can then configure: - The Hub user/org the repository is built to - either your Hub account name, or the name of any Hub organizations your account is in - The Docker repository name the image is built to - If the Docker repository should be "Public" or "Private" You can change the accessibility options after the repository has been created. If you add a Private repository to a Hub user, then you can only add other users as collaborators, and those users will be able to view and pull all images in that repository. To configure more granular access permissions, such as using groups of users or allow different users access to different image tags, then you need to add the Private repository to a Hub organization that your user has Administrator privilege on. - If you want the GitHub to notify the Docker Hub when a commit is made, and thus trigger a rebuild of all the images in this automated build. You can also select one or more - The git branch/tag, which repository sub-directory to use as the context - The Docker image tag name You can set a description for the repository by clicking "Description" link in the righthand side bar after the automated build - note that the "Full Description" will be over-written next build from the README.md file. has been created. ### GitHub private submodules If your GitHub repository contains links to private submodules, you'll get an error message in your build. Normally, the Docker Hub sets up a deploy key in your GitHub repository. Unfortunately, GitHub only allows a repository deploy key to access a single repository. To work around this, you need to create a dedicated user account in GitHub and attach the automated build's deploy key that account. This dedicated build account can be limited to read-only access to just the repositories required to build.
Step Screenshot Description
1. First, create the new account in GitHub. It should be given read-only access to the main repository and all submodules that are needed.
2. This can be accomplished by adding the account to a read-only team in the organization(s) where the main GitHub repository and all submodule repositories are kept.
3. Next, remove the deploy key from the main GitHub repository. This can be done in the GitHub repository's "Deploy keys" Settings section.
4. Your automated build's deploy key is in the "Build Details" menu under "Deploy keys".
5. In your dedicated GitHub User account, add the deploy key from your Docker Hub Automated Build.
### GitHub service hooks The GitHub Service hook allows GitHub to notify the Docker Hub when something has been committed to that git repository. You will need to add the Service Hook manually if your GitHub account is "Limited" linked to the Docker Hub. Follow the steps below to configure the GitHub Service hooks for your Automated Build:
Step Screenshot Description
1. Log in to GitHub.com, and go to your Repository page. Click on "Settings" on the right side of the page. You must have admin privileges to the repository in order to do this.
2. Webhooks & Services Click on "Webhooks & Services" on the left side of the page.
3. Find the service labeled Docker Find the service labeled "Docker" (or click on "Add service") and click on it.
4. Activate Service Hooks Make sure the "Active" checkbox is selected and click the "Update service" button to save your changes.
## Automated Builds with Bitbucket In order to setup an Automated Build, you need to first link your [Docker Hub](https://hub.docker.com) account with a Bitbucket account. This will allow the registry to see your repositories. To get started, log into your Docker Hub account and click the "+ Add Repository" button at the upper right of the screen. Then select [Automated Build](https://registry.hub.docker.com/builds/add/). Select the [Bitbucket source]( https://registry.hub.docker.com/associate/bitbucket/). Then follow the onscreen instructions to authorize and link your Bitbucket account to Docker Hub. Once it is linked, you'll be able to choose a repository from which to create the Automatic Build. ### Creating an Automated Build You can [create an Automated Build]( https://registry.hub.docker.com/builds/bitbucket/select/) from any of your public or private Bitbucket repositories with a `Dockerfile`. ### Adding a Hook When you link your Docker Hub account, a `POST` hook should get automatically added to your Bitbucket repository. Follow the steps below to confirm or modify the Bitbucket hooks for your Automated Build:
Step Screenshot Description
1. Settings Log in to Bitbucket.org and go to your Repository page. Click on "Settings" on the far left side of the page, under "Navigation". You must have admin privileges to the repository in order to do this.
2. Hooks Click on "Hooks" on the near left side of the page, under "Settings".
3. Docker Post HookYou should now see a list of hooks associated with the repo, including a POST hook that points at registry.hub.docker.com/hooks/bitbucket.
## The Dockerfile and Automated Builds During the build process, Docker will copy the contents of your `Dockerfile`. It will also add it to the [Docker Hub](https://hub.docker.com) for the Docker community (for public repositories) or approved team members/orgs (for private repositories) to see on the repository page. ### README.md If you have a `README.md` file in your repository, it will be used as the repository's full description.The build process will look for a `README.md` in the same directory as your `Dockerfile`. > **Warning:** > If you change the full description after a build, it will be > rewritten the next time the Automated Build has been built. To make changes, > modify the `README.md` from the Git repository. ## Remote Build triggers If you need a way to trigger Automated Builds outside of GitHub or Bitbucket, you can set up a build trigger. When you turn on the build trigger for an Automated Build, it will give you a URL to which you can send POST requests. This will trigger the Automated Build, much as with a GitHub webhook. Build triggers are available under the Settings menu of each Automated Build repository on the Docker Hub. ![Build trigger screen](/docker-hub/hub-images/build-trigger.png) You can use `curl` to trigger a build: ``` $ curl --data "build=true" -X POST https://registry.hub.docker.com/u/svendowideit/testhook/trigger/be579c 82-7c0e-11e4-81c4-0242ac110020/ OK ``` > **Note:** > You can only trigger one build at a time and no more than one > every five minutes. If you already have a build pending, or if you > recently submitted a build request, those requests *will be ignored*. > To verify everything is working correctly, check the logs of last > ten triggers on the settings page . ## Webhooks Automated Builds also include a Webhooks feature. Webhooks can be called after a successful repository push is made. This includes when a new tag is added to an existing image. The webhook call will generate a HTTP POST with the following JSON payload: ``` { "callback_url": "https://registry.hub.docker.com/u/svendowideit/testhook/hook/2141b5bi5i5b02bec211i4eeih0242eg11000a/", "push_data": { "images": [ "27d47432a69bca5f2700e4dff7de0388ed65f9d3fb1ec645e2bc24c223dc1cc3", "51a9c7c1f8bb2fa19bcd09789a34e63f35abb80044bc10196e304f6634cc582c", ... ], "pushed_at": 1.417566161e+09, "pusher": "trustedbuilder" }, "repository": { "comment_count": 0, "date_created": 1.417494799e+09, "description": "", "dockerfile": "#\n# BUILD\u0009\u0009docker build -t svendowideit/apt-cacher .\n# RUN\u0009\u0009docker run -d -p 3142:3142 -name apt-cacher-run apt-cacher\n#\n# and then you can run containers with:\n# \u0009\u0009docker run -t -i -rm -e http_proxy http://192.168.1.2:3142/ debian bash\n#\nFROM\u0009\u0009ubuntu\nMAINTAINER\u0009SvenDowideit@home.org.au\n\n\nVOLUME\u0009\u0009[\"/var/cache/apt-cacher-ng\"]\nRUN\u0009\u0009apt-get update ; apt-get install -yq apt-cacher-ng\n\nEXPOSE \u0009\u00093142\nCMD\u0009\u0009chmod 777 /var/cache/apt-cacher-ng ; /etc/init.d/apt-cacher-ng start ; tail -f /var/log/apt-cacher-ng/*\n", "full_description": "Docker Hub based automated build from a GitHub repo", "is_official": false, "is_private": true, "is_trusted": true, "name": "testhook", "namespace": "svendowideit", "owner": "svendowideit", "repo_name": "svendowideit/testhook", "repo_url": "https://registry.hub.docker.com/u/svendowideit/testhook/", "star_count": 0, "status": "Active" } } ``` Webhooks are available under the Settings menu of each Repository. Use a tool like [requestb.in](http://requestb.in/) to test your webhook. > **Note**: The Docker Hub servers use an elastic IP range, so you can't > filter requests by IP. ### Webhook chains Webhook chains allow you to chain calls to multiple services. For example, you can use this to trigger a deployment of your container only after it has been successfully tested, then update a separate Changelog once the deployment is complete. After clicking the "Add webhook" button, simply add as many URLs as necessary in your chain. The first webhook in a chain will be called after a successful push. Subsequent URLs will be contacted after the callback has been validated. ### Validating a callback In order to validate a callback in a webhook chain, you need to 1. Retrieve the `callback_url` value in the request's JSON payload. 1. Send a POST request to this URL containing a valid JSON body. > **Note**: A chain request will only be considered complete once the last > callback has been validated. To help you debug or simply view the results of your webhook(s), view the "History" of the webhook available on its settings page. ### Callback JSON data The following parameters are recognized in callback data: * `state` (required): Accepted values are `success`, `failure` and `error`. If the state isn't `success`, the webhook chain will be interrupted. * `description`: A string containing miscellaneous information that will be available on the Docker Hub. Maximum 255 characters. * `context`: A string containing the context of the operation. Can be retrieved from the Docker Hub. Maximum 100 characters. * `target_url`: The URL where the results of the operation can be found. Can be retrieved on the Docker Hub. *Example callback payload:* { "state": "success", "description": "387 tests PASSED", "context": "Continuous integration by Acme CI", "target_url": "http://ci.acme.com/results/afd339c1c3d27" } ## Repository links Repository links are a way to associate one Automated Build with another. If one gets updated, the linking system triggers a rebuild for the other Automated Build. This makes it easy to keep all your Automated Builds up to date. To add a link, go to the repository for the Automated Build you want to link to and click on *Repository Links* under the Settings menu at right. Then, enter the name of the repository that you want have linked. > **Warning:** > You can add more than one repository link, however, you should > do so very carefully. Creating a two way relationship between Automated Builds will > cause an endless build loop. ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/home.md ================================================ # The Docker Hub Registry help ## Introduction For your questions about the [Docker Hub](https://hub.docker.com) registry you can use [this documentation](docs.md). If you can not find something you are looking for, please feel free to [contact us](https://docker.com/resources/support/). ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/index.md ================================================ # Docker Hub The [Docker Hub](https://hub.docker.com) provides a cloud-based platform service for distributed applications, including container image distribution and change management, user and team collaboration, and lifecycle workflow automation. ![DockerHub](/docker-hub/hub-images/hub.png) ## [Finding and pulling images](./userguide.md) Find out how to [use the Docker Hub](./userguide.md) to find and pull Docker images to run or build upon. ## [Accounts](./accounts.md) [Learn how to create](./accounts.md) a Docker Hub account and manage your organizations and groups. ## [Your Repositories](./repos.md) Find out how to share your Docker images in [Docker Hub repositories](./repos.md) and how to store and manage private images. ## [Automated builds](./builds.md) Learn how to automate your build and deploy pipeline with [Automated Builds](./builds.md) ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/official_repos.md ================================================ # Official Repositories on Docker Hub The Docker [Official Repositories](http://registry.hub.docker.com/official) are a curated set of Docker repositories that are promoted on Docker Hub. They are designed to: * Provide essential base OS repositories (for example, [`ubuntu`](https://registry.hub.docker.com/_/ubuntu/), [`centos`](https://registry.hub.docker.com/_/centos/)) that serve as the starting point for the majority of users. * Provide drop-in solutions for popular programming language runtimes, data stores, and other services, similar to what a Platform-as-a-Service (PAAS) would offer. * Exemplify [`Dockerfile` best practices](/articles/dockerfile_best-practices) and provide clear documentation to serve as a reference for other `Dockerfile` authors. * Ensure that security updates are applied in a timely manner. This is particularly important as many Official Repositories are some of the most popular on Docker Hub. * Provide a channel for software vendors to redistribute up-to-date and supported versions of their products. Organization accounts on Docker Hub can also serve this purpose, without the careful review or restrictions on what can be published. Docker, Inc. sponsors a dedicated team that is responsible for reviewing and publishing all Official Repositories content. This team works in collaboration with upstream software maintainers, security experts, and the broader Docker community. While it is preferable to have upstream software authors maintaining their corresponding Official Repositories, this is not a strict requirement. Creating and maintaining images for Official Repositories is a public process. It takes place openly on GitHub where participation is encouraged. Anyone can provide feedback, contribute code, suggest process changes, or even propose a new Official Repository. ## Should I use Official Repositories? New Docker users are encouraged to use the Official Repositories in their projects. These repositories have clear documentation, promote best practices, and are designed for the most common use cases. Advanced users are encouraged to review the Official Repositories as part of their `Dockerfile` learning process. A common rationale for diverging from Official Repositories is to optimize for image size. For instance, many of the programming language stack images contain a complete build toolchain to support installation of modules that depend on optimized code. An advanced user could build a custom image with just the necessary pre-compiled libraries to save space. A number of language stacks such as [`python`](https://registry.hub.docker.com/_/python/) and [`ruby`](https://registry.hub.docker.com/_/ruby/) have `-slim` tag variants designed to fill the need for optimization. Even when these "slim" variants are insufficient, it is still recommended to inherit from an Official Repository base OS image to leverage the ongoing maintenance work, rather than duplicating these efforts. ## How can I get involved? All Official Repositories contain a **User Feedback** section in their documentation which covers the details for that specific repository. In most cases, the GitHub repository which contains the Dockerfiles for an Official Repository also has an active issue tracker. General feedback and support questions should be directed to `#docker-library` on Freenode IRC. ## How do I create a new Official Repository? From a high level, an Official Repository starts out as a proposal in the form of a set of GitHub pull requests. You'll find detailed and objective proposal requirements in the following GitHub repositories: * [docker-library/official-images](https://github.com/docker-library/official-images) * [docker-library/docs](https://github.com/docker-library/docs) The Official Repositories team, with help from community contributors, formally review each proposal and provide feedback to the author. This initial review process may require a bit of back and forth before the proposal is accepted. There are also subjective considerations during the review process. These subjective concerns boil down to the basic question: "is this image generally useful?" For example, the [`python`](https://registry.hub.docker.com/_/python/) Official Repository is "generally useful" to the large Python developer community, whereas an obscure text adventure game written in Python last week is not. When a new proposal is accepted, the author becomes responsible for keeping their images up-to-date and responding to user feedback. The Official Repositories team becomes responsible for publishing the images and documentation on Docker Hub. Updates to the Official Repository follow the same pull request process, though with less review. The Official Repositories team ultimately acts as a gatekeeper for all changes, which helps mitigate the risk of quality and security issues from being introduced. > **Note**: If you are interested in proposing an Official Repository, but would > like to discuss it with Docker, Inc. privately first, please send your > inquiries to partners@docker.com. There is no fast-track or pay-for-status > option. ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/repos.md ================================================ # Your Hub repositories Docker Hub repositories make it possible for you to share images with co-workers, customers or the Docker community at large. If you're building your images internally, either on your own Docker daemon, or using your own Continuous integration services, you can push them to a Docker Hub repository that you add to your Docker Hub user or organization account. Alternatively, if the source code for your Docker image is on GitHub or Bitbucket, you can use an "Automated build" repository, which is built by the Docker Hub services. See the [automated builds documentation](./builds.md) to read about the extra functionality provided by those services. ![repositories](/docker-hub/hub-images/repos.png) Your Docker Hub repositories have a number of useful features. ## Stars Your repositories can be starred and you can star repositories in return. Stars are a way to show that you like a repository. They are also an easy way of bookmarking your favorites. ## Comments You can interact with other members of the Docker community and maintainers by leaving comments on repositories. If you find any comments that are not appropriate, you can flag them for review. ## Collaborators and their role A collaborator is someone you want to give access to a private repository. Once designated, they can `push` and `pull` to your repositories. They will not be allowed to perform any administrative tasks such as deleting the repository or changing its status from private to public. > **Note:** > A collaborator cannot add other collaborators. Only the owner of > the repository has administrative access. You can also assign more granular collaborator rights ("Read", "Write", or "Admin") on Docker Hub by using organizations and groups. For more information see the [accounts documentation](accounts/). ## Private repositories Private repositories allow you to have repositories that contain images that you want to keep private, either to your own account or within an organization or group. To work with a private repository on [Docker Hub](https://hub.docker.com), you will need to add one via the [Add Repository](https://registry.hub.docker.com/account/repositories/add/) link. You get one private repository for free with your Docker Hub account. If you need more accounts you can upgrade your [Docker Hub](https://registry.hub.docker.com/plans/) plan. Once the private repository is created, you can `push` and `pull` images to and from it using Docker. > *Note:* You need to be signed in and have access to work with a > private repository. Private repositories are just like public ones. However, it isn't possible to browse them or search their content on the public registry. They do not get cached the same way as a public repository either. It is possible to give access to a private repository to those whom you designate (i.e., collaborators) from its Settings page. From there, you can also switch repository status (*public* to *private*, or vice-versa). You will need to have an available private repository slot open before you can do such a switch. If you don't have any available, you can always upgrade your [Docker Hub](https://registry.hub.docker.com/plans/) plan. ## Webhooks A webhook is an HTTP call-back triggered by a specific event. You can use a Hub repository webhook to notify people, services, and other applications after a new image is pushed to your repository (this also happens for Automated builds). For example, you can trigger an automated test or deployment to happen as soon as the image is available. To get started adding webhooks, go to the desired repository in the Hub, and click "Webhooks" under the "Settings" box. A webhook is called only after a successful `push` is made. The webhook calls are HTTP POST requests with a JSON payload similar to the example shown below. *Example webhook JSON payload:* ``` { "callback_url": "https://registry.hub.docker.com/u/svendowideit/busybox/hook/2141bc0cdec4hebec411i4c1g40242eg110020/", "push_data": { "images": [ "27d47432a69bca5f2700e4dff7de0388ed65f9d3fb1ec645e2bc24c223dc1cc3", "51a9c7c1f8bb2fa19bcd09789a34e63f35abb80044bc10196e304f6634cc582c", ... ], "pushed_at": 1.417566822e+09, "pusher": "svendowideit" }, "repository": { "comment_count": 0, "date_created": 1.417566665e+09, "description": "", "full_description": "webhook triggered from a 'docker push'", "is_official": false, "is_private": false, "is_trusted": false, "name": "busybox", "namespace": "svendowideit", "owner": "svendowideit", "repo_name": "svendowideit/busybox", "repo_url": "https://registry.hub.docker.com/u/svendowideit/busybox/", "star_count": 0, "status": "Active" } ``` For testing, you can try an HTTP request tool like [requestb.in](http://requestb.in/). > **Note**: The Docker Hub servers use an elastic IP range, so you can't > filter requests by IP. ### Webhook chains Webhook chains allow you to chain calls to multiple services. For example, you can use this to trigger a deployment of your container only after it has been successfully tested, then update a separate Changelog once the deployment is complete. After clicking the "Add webhook" button, simply add as many URLs as necessary in your chain. The first webhook in a chain will be called after a successful push. Subsequent URLs will be contacted after the callback has been validated. ### Validating a callback In order to validate a callback in a webhook chain, you need to 1. Retrieve the `callback_url` value in the request's JSON payload. 1. Send a POST request to this URL containing a valid JSON body. > **Note**: A chain request will only be considered complete once the last > callback has been validated. To help you debug or simply view the results of your webhook(s), view the "History" of the webhook available on its settings page. #### Callback JSON data The following parameters are recognized in callback data: * `state` (required): Accepted values are `success`, `failure` and `error`. If the state isn't `success`, the webhook chain will be interrupted. * `description`: A string containing miscellaneous information that will be available on the Docker Hub. Maximum 255 characters. * `context`: A string containing the context of the operation. Can be retrieved from the Docker Hub. Maximum 100 characters. * `target_url`: The URL where the results of the operation can be found. Can be retrieved on the Docker Hub. *Example callback payload:* { "state": "success", "description": "387 tests PASSED", "context": "Continuous integration by Acme CI", "target_url": "http://ci.acme.com/results/afd339c1c3d27" } ## Mark as unlisted By marking a repository as unlisted, you can create a publicly pullable repository which will not be in the Hub or commandline search. This allows you to have a limited release, but does not restrict access to anyone that is told, or guesses the repository name. ================================================ FILE: vendor/github.com/docker/docker/docs/docker-hub/userguide.md ================================================ # Using the Docker Hub Docker Hub is used to find and pull Docker images to run or build upon, and to distribute and build images for other users to use. ![your profile](/docker-hub/hub-images/dashboard.png) ## Finding repositories and images There are two ways you can search for public repositories and images available on the Docker Hub. You can use the "Search" tool on the Docker Hub website, or you can `search` for all the repositories and images using the Docker commandline tool: $ docker search ubuntu Both will show you a list of the currently available public repositories on the Docker Hub which match the provided keyword. If a repository is private or marked as unlisted, it won't be in the repository search results. To see all the repositories you have access to and their statuses, you can look at your profile page on [Docker Hub](https://hub.docker.com). ## Pulling, running and building images You can find more information on [working with Docker images](../userguide/dockerimages.md). ## Official Repositories The Docker Hub contains a number of [Official Repositories](http://registry.hub.docker.com/official). These are certified repositories from vendors and contributors to Docker. They contain Docker images from vendors like Canonical, Oracle, and Red Hat that you can use to build applications and services. If you use Official Repositories you know you're using an optimized and up-to-date image to power your applications. > **Note:** > If you would like to contribute an Official Repository for your > organization, see [Official Repositories on Docker > Hub](/docker-hub/official_repos) for more information. ## Building and shipping your own repositories and images The Docker Hub provides you and your team with a place to build and ship Docker images. Collections of Docker images are managed using repositories - You can configure two types of repositories to manage on the Docker Hub: [Repositories](./repos.md), which allow you to push images to the Hub from your local Docker daemon, and [Automated Builds](./builds.md), which allow you to configure GitHub or Bitbucket to trigger the Hub to rebuild repositories when changes are made to the repository. ================================================ FILE: vendor/github.com/docker/docker/docs/examples/apt-cacher-ng.Dockerfile ================================================ # # Build: docker build -t apt-cacher . # Run: docker run -d -p 3142:3142 --name apt-cacher-run apt-cacher # # and then you can run containers with: # docker run -t -i --rm -e http_proxy http://dockerhost:3142/ debian bash # FROM ubuntu MAINTAINER SvenDowideit@docker.com VOLUME ["/var/cache/apt-cacher-ng"] RUN apt-get update && apt-get install -y apt-cacher-ng EXPOSE 3142 CMD chmod 777 /var/cache/apt-cacher-ng && /etc/init.d/apt-cacher-ng start && tail -f /var/log/apt-cacher-ng/* ================================================ FILE: vendor/github.com/docker/docker/docs/examples/apt-cacher-ng.md ================================================ # Dockerizing an apt-cacher-ng service > **Note**: > - **If you don't like sudo** then see [*Giving non-root > access*](/installation/binaries/#giving-non-root-access). > - **If you're using OS X or docker via TCP** then you shouldn't use > sudo. When you have multiple Docker servers, or build unrelated Docker containers which can't make use of the Docker build cache, it can be useful to have a caching proxy for your packages. This container makes the second download of any package almost instant. Use the following Dockerfile: # # Build: docker build -t apt-cacher . # Run: docker run -d -p 3142:3142 --name apt-cacher-run apt-cacher # # and then you can run containers with: # docker run -t -i --rm -e http_proxy http://dockerhost:3142/ debian bash # FROM ubuntu MAINTAINER SvenDowideit@docker.com VOLUME ["/var/cache/apt-cacher-ng"] RUN apt-get update && apt-get install -y apt-cacher-ng EXPOSE 3142 CMD chmod 777 /var/cache/apt-cacher-ng && /etc/init.d/apt-cacher-ng start && tail -f /var/log/apt-cacher-ng/* To build the image using: $ docker build -t eg_apt_cacher_ng . Then run it, mapping the exposed port to one on the host $ docker run -d -p 3142:3142 --name test_apt_cacher_ng eg_apt_cacher_ng To see the logfiles that are `tailed` in the default command, you can use: $ docker logs -f test_apt_cacher_ng To get your Debian-based containers to use the proxy, you can do one of three things 1. Add an apt Proxy setting `echo 'Acquire::http { Proxy "http://dockerhost:3142"; };' >> /etc/apt/conf.d/01proxy` 2. Set an environment variable: `http_proxy=http://dockerhost:3142/` 3. Change your `sources.list` entries to start with `http://dockerhost:3142/` **Option 1** injects the settings safely into your apt configuration in a local version of a common base: FROM ubuntu RUN echo 'Acquire::http { Proxy "http://dockerhost:3142"; };' >> /etc/apt/apt.conf.d/01proxy RUN apt-get update && apt-get install -y vim git # docker build -t my_ubuntu . **Option 2** is good for testing, but will break other HTTP clients which obey `http_proxy`, such as `curl`, `wget` and others: $ docker run --rm -t -i -e http_proxy=http://dockerhost:3142/ debian bash **Option 3** is the least portable, but there will be times when you might need to do it and you can do it from your `Dockerfile` too. Apt-cacher-ng has some tools that allow you to manage the repository, and they can be used by leveraging the `VOLUME` instruction, and the image we built to run the service: $ docker run --rm -t -i --volumes-from test_apt_cacher_ng eg_apt_cacher_ng bash $$ /usr/lib/apt-cacher-ng/distkill.pl Scanning /var/cache/apt-cacher-ng, please wait... Found distributions: bla, taggedcount: 0 1. precise-security (36 index files) 2. wheezy (25 index files) 3. precise-updates (36 index files) 4. precise (36 index files) 5. wheezy-updates (18 index files) Found architectures: 6. amd64 (36 index files) 7. i386 (24 index files) WARNING: The removal action may wipe out whole directories containing index files. Select d to see detailed list. (Number nn: tag distribution or architecture nn; 0: exit; d: show details; r: remove tagged; q: quit): q Finally, clean up after your test by stopping and removing the container, and then removing the image. $ docker stop test_apt_cacher_ng $ docker rm test_apt_cacher_ng $ docker rmi eg_apt_cacher_ng ================================================ FILE: vendor/github.com/docker/docker/docs/examples/couchdb_data_volumes.md ================================================ # Dockerizing a CouchDB service > **Note**: > - **If you don't like sudo** then see [*Giving non-root > access*](/installation/binaries/#giving-non-root-access) Here's an example of using data volumes to share the same data between two CouchDB containers. This could be used for hot upgrades, testing different versions of CouchDB on the same data, etc. ## Create first database Note that we're marking `/var/lib/couchdb` as a data volume. $ COUCH1=$(docker run -d -p 5984 -v /var/lib/couchdb shykes/couchdb:2013-05-03) ## Add data to the first database We're assuming your Docker host is reachable at `localhost`. If not, replace `localhost` with the public IP of your Docker host. $ HOST=localhost $ URL="http://$HOST:$(docker port $COUCH1 5984 | grep -o '[1-9][0-9]*$')/_utils/" $ echo "Navigate to $URL in your browser, and use the couch interface to add data" ## Create second database This time, we're requesting shared access to `$COUCH1`'s volumes. $ COUCH2=$(docker run -d -p 5984 --volumes-from $COUCH1 shykes/couchdb:2013-05-03) ## Browse data on the second database $ HOST=localhost $ URL="http://$HOST:$(docker port $COUCH2 5984 | grep -o '[1-9][0-9]*$')/_utils/" $ echo "Navigate to $URL in your browser. You should see the same data as in the first database"'!' Congratulations, you are now running two Couchdb containers, completely isolated from each other *except* for their data. ================================================ FILE: vendor/github.com/docker/docker/docs/examples/mongodb/Dockerfile ================================================ # Dockerizing MongoDB: Dockerfile for building MongoDB images # Based on ubuntu:latest, installs MongoDB following the instructions from: # http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ FROM ubuntu:latest MAINTAINER Docker # Installation: # Import MongoDB public GPG key AND create a MongoDB list file RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 RUN echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list # Update apt-get sources AND install MongoDB RUN apt-get update && apt-get install -y mongodb-org # Create the MongoDB data directory RUN mkdir -p /data/db # Expose port #27017 from the container to the host EXPOSE 27017 # Set /usr/bin/mongod as the dockerized entry-point application ENTRYPOINT ["/usr/bin/mongod"] ================================================ FILE: vendor/github.com/docker/docker/docs/examples/mongodb.md ================================================ # Dockerizing MongoDB ## Introduction In this example, we are going to learn how to build a Docker image with MongoDB pre-installed. We'll also see how to `push` that image to the [Docker Hub registry](https://hub.docker.com) and share it with others! > **Note:** > > This guide will show the mechanics of building a MongoDB container, but > you will probably want to use the official image on [Docker Hub]( https://registry.hub.docker.com/_/mongo/) Using Docker and containers for deploying [MongoDB](https://www.mongodb.org/) instances will bring several benefits, such as: - Easy to maintain, highly configurable MongoDB instances; - Ready to run and start working within milliseconds; - Based on globally accessible and shareable images. > **Note:** > > If you do **_not_** like `sudo`, you might want to check out: > [*Giving non-root access*](/installation/binaries/#giving-non-root-access). ## Creating a Dockerfile for MongoDB Let's create our `Dockerfile` and start building it: $ nano Dockerfile Although optional, it is handy to have comments at the beginning of a `Dockerfile` explaining its purpose: # Dockerizing MongoDB: Dockerfile for building MongoDB images # Based on ubuntu:latest, installs MongoDB following the instructions from: # http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ > **Tip:** `Dockerfile`s are flexible. However, they need to follow a certain > format. The first item to be defined is the name of an image, which becomes > the *parent* of your *Dockerized MongoDB* image. We will build our image using the latest version of Ubuntu from the [Docker Hub Ubuntu](https://registry.hub.docker.com/_/ubuntu/) repository. # Format: FROM repository[:version] FROM ubuntu:latest Continuing, we will declare the `MAINTAINER` of the `Dockerfile`: # Format: MAINTAINER Name MAINTAINER M.Y. Name > **Note:** Although Ubuntu systems have MongoDB packages, they are likely to > be outdated. Therefore in this example, we will use the official MongoDB > packages. We will begin with importing the MongoDB public GPG key. We will also create a MongoDB repository file for the package manager. # Installation: # Import MongoDB public GPG key AND create a MongoDB list file RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10 RUN echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list After this initial preparation we can update our packages and install MongoDB. # Update apt-get sources AND install MongoDB RUN apt-get update && apt-get install -y mongodb-org > **Tip:** You can install a specific version of MongoDB by using a list > of required packages with versions, e.g.: > > RUN apt-get update && apt-get install -y mongodb-org=3.0.1 mongodb-org-server=3.0.1 mongodb-org-shell=3.0.1 mongodb-org-mongos=3.0.1 mongodb-org-tools=3.0.1 MongoDB requires a data directory. Let's create it as the final step of our installation instructions. # Create the MongoDB data directory RUN mkdir -p /data/db Lastly we set the `ENTRYPOINT` which will tell Docker to run `mongod` inside the containers launched from our MongoDB image. And for ports, we will use the `EXPOSE` instruction. # Expose port 27017 from the container to the host EXPOSE 27017 # Set usr/bin/mongod as the dockerized entry-point application ENTRYPOINT ["/usr/bin/mongod"] Now save the file and let's build our image. > **Note:** > > The full version of this `Dockerfile` can be found [here](/examples/mongodb/Dockerfile). ## Building the MongoDB Docker image With our `Dockerfile`, we can now build the MongoDB image using Docker. Unless experimenting, it is always a good practice to tag Docker images by passing the `--tag` option to `docker build` command. # Format: docker build --tag/-t / . # Example: $ docker build --tag my/repo . Once this command is issued, Docker will go through the `Dockerfile` and build the image. The final image will be tagged `my/repo`. ## Pushing the MongoDB image to Docker Hub All Docker image repositories can be hosted and shared on [Docker Hub](https://hub.docker.com) with the `docker push` command. For this, you need to be logged-in. # Log-in $ docker login Username: .. # Push the image # Format: docker push / $ docker push my/repo The push refers to a repository [my/repo] (len: 1) Sending image list Pushing repository my/repo (1 tags) .. ## Using the MongoDB image Using the MongoDB image we created, we can run one or more MongoDB instances as daemon process(es). # Basic way # Usage: docker run --name -d / $ docker run -p 27017:27017 --name mongo_instance_001 -d my/repo # Dockerized MongoDB, lean and mean! # Usage: docker run --name -d / --noprealloc --smallfiles $ docker run -p 27017:27017 --name mongo_instance_001 -d my/repo --noprealloc --smallfiles # Checking out the logs of a MongoDB container # Usage: docker logs $ docker logs mongo_instance_001 # Playing with MongoDB # Usage: mongo --port $ mongo --port 27017 # If using boot2docker # Usage: mongo --port --host $ mongo --port 27017 --host 192.168.59.103 > **Tip:** If you want to run two containers on the same engine, then you will need to map the exposed port to two different ports on the host # Start two containers and map the ports $ docker run -p 28001:27017 --name mongo_instance_001 -d my/repo $ docker run -p 28002:27017 --name mongo_instance_002 -d my/repo # Now you can connect to each MongoDB instance on the two ports $ mongo --port 28001 $ mongo --port 28002 - [Linking containers](/userguide/dockerlinks) - [Cross-host linking containers](/articles/ambassador_pattern_linking/) - [Creating an Automated Build](/docker-io/builds/#automated-builds) ================================================ FILE: vendor/github.com/docker/docker/docs/examples/nodejs_web_app.md ================================================ # Dockerizing a Node.js web app > **Note**: > - **If you don't like sudo** then see [*Giving non-root > access*](/installation/binaries/#giving-non-root-access) The goal of this example is to show you how you can build your own Docker images from a parent image using a `Dockerfile` . We will do that by making a simple Node.js hello world web application running on CentOS. You can get the full source code at [https://github.com/enokd/docker-node-hello/](https://github.com/enokd/docker-node-hello/). ## Create Node.js app First, create a directory `src` where all the files would live. Then create a `package.json` file that describes your app and its dependencies: { "name": "docker-centos-hello", "private": true, "version": "0.0.1", "description": "Node.js Hello world app on CentOS using docker", "author": "Daniel Gasienica ", "dependencies": { "express": "3.2.4" } } Then, create an `index.js` file that defines a web app using the [Express.js](http://expressjs.com/) framework: var express = require('express'); // Constants var PORT = 8080; // App var app = express(); app.get('/', function (req, res) { res.send('Hello world\n'); }); app.listen(PORT); console.log('Running on http://localhost:' + PORT); In the next steps, we'll look at how you can run this app inside a CentOS container using Docker. First, you'll need to build a Docker image of your app. ## Creating a Dockerfile Create an empty file called `Dockerfile`: touch Dockerfile Open the `Dockerfile` in your favorite text editor Define the parent image you want to use to build your own image on top of. Here, we'll use [CentOS](https://registry.hub.docker.com/_/centos/) (tag: `centos6`) available on the [Docker Hub](https://hub.docker.com/): FROM centos:centos6 Since we're building a Node.js app, you'll have to install Node.js as well as npm on your CentOS image. Node.js is required to run your app and npm to install your app's dependencies defined in `package.json`. To install the right package for CentOS, we'll use the instructions from the [Node.js wiki]( https://github.com/joyent/node/wiki/Installing-Node.js- via-package-manager#rhelcentosscientific-linux-6): # Enable EPEL for Node.js RUN rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm # Install Node.js and npm RUN yum install -y npm To bundle your app's source code inside the Docker image, use the `COPY` instruction: # Bundle app source COPY . /src Install your app dependencies using the `npm` binary: # Install app dependencies RUN cd /src; npm install Your app binds to port `8080` so you'll use the` EXPOSE` instruction to have it mapped by the `docker` daemon: EXPOSE 8080 Last but not least, define the command to run your app using `CMD` which defines your runtime, i.e. `node`, and the path to our app, i.e. `src/index.js` (see the step where we added the source to the container): CMD ["node", "/src/index.js"] Your `Dockerfile` should now look like this: FROM centos:centos6 # Enable EPEL for Node.js RUN rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm # Install Node.js and npm RUN yum install -y npm # Bundle app source COPY . /src # Install app dependencies RUN cd /src; npm install EXPOSE 8080 CMD ["node", "/src/index.js"] ## Building your image Go to the directory that has your `Dockerfile` and run the following command to build a Docker image. The `-t` flag lets you tag your image so it's easier to find later using the `docker images` command: $ docker build -t /centos-node-hello . Your image will now be listed by Docker: $ docker images # Example REPOSITORY TAG ID CREATED centos centos6 539c0211cd76 8 weeks ago /centos-node-hello latest d64d3505b0d2 2 hours ago ## Run the image Running your image with `-d` runs the container in detached mode, leaving the container running in the background. The `-p` flag redirects a public port to a private port in the container. Run the image you previously built: $ docker run -p 49160:8080 -d /centos-node-hello Print the output of your app: # Get container ID $ docker ps # Print app output $ docker logs # Example Running on http://localhost:8080 ## Test To test your app, get the port of your app that Docker mapped: $ docker ps # Example ID IMAGE COMMAND ... PORTS ecce33b30ebf /centos-node-hello:latest node /src/index.js 49160->8080 In the example above, Docker mapped the `8080` port of the container to `49160`. Now you can call your app using `curl` (install if needed via: `sudo apt-get install curl`): $ curl -i localhost:49160 HTTP/1.1 200 OK X-Powered-By: Express Content-Type: text/html; charset=utf-8 Content-Length: 12 Date: Sun, 02 Jun 2013 03:53:22 GMT Connection: keep-alive Hello world If you use Boot2docker on OS X, the port is actually mapped to the Docker host VM, and you should use the following command: $ curl $(boot2docker ip):49160 We hope this tutorial helped you get up and running with Node.js and CentOS on Docker. You can get the full source code at [https://github.com/enokd/docker-node-hello/](https://github.com/enokd/docker-node-hello/). ================================================ FILE: vendor/github.com/docker/docker/docs/examples/postgresql_service.Dockerfile ================================================ # # example Dockerfile for https://docs.docker.com/examples/postgresql_service/ # FROM ubuntu MAINTAINER SvenDowideit@docker.com # Add the PostgreSQL PGP key to verify their Debian packages. # It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 # Add PostgreSQL's repository. It contains the most recent stable release # of PostgreSQL, ``9.3``. RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list # Install ``python-software-properties``, ``software-properties-common`` and PostgreSQL 9.3 # There are some warnings (in red) that show up during the build. You can hide # them by prefixing each apt-get statement with DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3 # Note: The official Debian and Ubuntu images automatically ``apt-get clean`` # after each ``apt-get`` # Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed`` USER postgres # Create a PostgreSQL role named ``docker`` with ``docker`` as the password and # then create a database `docker` owned by the ``docker`` role. # Note: here we use ``&&\`` to run commands one after the other - the ``\`` # allows the RUN command to span multiple lines. RUN /etc/init.d/postgresql start &&\ psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\ createdb -O docker docker # Adjust PostgreSQL configuration so that remote connections to the # database are possible. RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf # And add ``listen_addresses`` to ``/etc/postgresql/9.3/main/postgresql.conf`` RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf # Expose the PostgreSQL port EXPOSE 5432 # Add VOLUMEs to allow backup of config, logs and databases VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"] # Set the default command to run when starting the container CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"] ================================================ FILE: vendor/github.com/docker/docker/docs/examples/postgresql_service.md ================================================ # Dockerizing PostgreSQL > **Note**: > - **If you don't like sudo** then see [*Giving non-root > access*](/installation/binaries/#giving-non-root-access) ## Installing PostgreSQL on Docker Assuming there is no Docker image that suits your needs on the [Docker Hub](http://hub.docker.com), you can create one yourself. Start by creating a new `Dockerfile`: > **Note**: > This PostgreSQL setup is for development-only purposes. Refer to the > PostgreSQL documentation to fine-tune these settings so that it is > suitably secure. # # example Dockerfile for https://docs.docker.com/examples/postgresql_service/ # FROM ubuntu MAINTAINER SvenDowideit@docker.com # Add the PostgreSQL PGP key to verify their Debian packages. # It should be the same key as https://www.postgresql.org/media/keys/ACCC4CF8.asc RUN apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 # Add PostgreSQL's repository. It contains the most recent stable release # of PostgreSQL, ``9.3``. RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main" > /etc/apt/sources.list.d/pgdg.list # Install ``python-software-properties``, ``software-properties-common`` and PostgreSQL 9.3 # There are some warnings (in red) that show up during the build. You can hide # them by prefixing each apt-get statement with DEBIAN_FRONTEND=noninteractive RUN apt-get update && apt-get install -y python-software-properties software-properties-common postgresql-9.3 postgresql-client-9.3 postgresql-contrib-9.3 # Note: The official Debian and Ubuntu images automatically ``apt-get clean`` # after each ``apt-get`` # Run the rest of the commands as the ``postgres`` user created by the ``postgres-9.3`` package when it was ``apt-get installed`` USER postgres # Create a PostgreSQL role named ``docker`` with ``docker`` as the password and # then create a database `docker` owned by the ``docker`` role. # Note: here we use ``&&\`` to run commands one after the other - the ``\`` # allows the RUN command to span multiple lines. RUN /etc/init.d/postgresql start &&\ psql --command "CREATE USER docker WITH SUPERUSER PASSWORD 'docker';" &&\ createdb -O docker docker # Adjust PostgreSQL configuration so that remote connections to the # database are possible. RUN echo "host all all 0.0.0.0/0 md5" >> /etc/postgresql/9.3/main/pg_hba.conf # And add ``listen_addresses`` to ``/etc/postgresql/9.3/main/postgresql.conf`` RUN echo "listen_addresses='*'" >> /etc/postgresql/9.3/main/postgresql.conf # Expose the PostgreSQL port EXPOSE 5432 # Add VOLUMEs to allow backup of config, logs and databases VOLUME ["/etc/postgresql", "/var/log/postgresql", "/var/lib/postgresql"] # Set the default command to run when starting the container CMD ["/usr/lib/postgresql/9.3/bin/postgres", "-D", "/var/lib/postgresql/9.3/main", "-c", "config_file=/etc/postgresql/9.3/main/postgresql.conf"] Build an image from the Dockerfile assign it a name. $ docker build -t eg_postgresql . And run the PostgreSQL server container (in the foreground): $ docker run --rm -P --name pg_test eg_postgresql There are 2 ways to connect to the PostgreSQL server. We can use [*Link Containers*](/userguide/dockerlinks), or we can access it from our host (or the network). > **Note**: > The `--rm` removes the container and its image when > the container exits successfully. ### Using container linking Containers can be linked to another container's ports directly using `-link remote_name:local_alias` in the client's `docker run`. This will set a number of environment variables that can then be used to connect: $ docker run --rm -t -i --link pg_test:pg eg_postgresql bash postgres@7ef98b1b7243:/$ psql -h $PG_PORT_5432_TCP_ADDR -p $PG_PORT_5432_TCP_PORT -d docker -U docker --password ### Connecting from your host system Assuming you have the postgresql-client installed, you can use the host-mapped port to test as well. You need to use `docker ps` to find out what local host port the container is mapped to first: $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5e24362f27f6 eg_postgresql:latest /usr/lib/postgresql/ About an hour ago Up About an hour 0.0.0.0:49153->5432/tcp pg_test $ psql -h localhost -p 49153 -d docker -U docker --password ### Testing the database Once you have authenticated and have a `docker =#` prompt, you can create a table and populate it. psql (9.3.1) Type "help" for help. $ docker=# CREATE TABLE cities ( docker(# name varchar(80), docker(# location point docker(# ); CREATE TABLE $ docker=# INSERT INTO cities VALUES ('San Francisco', '(-194.0, 53.0)'); INSERT 0 1 $ docker=# select * from cities; name | location ---------------+----------- San Francisco | (-194,53) (1 row) ### Using the container volumes You can use the defined volumes to inspect the PostgreSQL log files and to backup your configuration and data: $ docker run --rm --volumes-from pg_test -t -i busybox sh / # ls bin etc lib linuxrc mnt proc run sys usr dev home lib64 media opt root sbin tmp var / # ls /etc/postgresql/9.3/main/ environment pg_hba.conf postgresql.conf pg_ctl.conf pg_ident.conf start.conf /tmp # ls /var/log ldconfig postgresql ================================================ FILE: vendor/github.com/docker/docker/docs/examples/running_redis_service.md ================================================ # Dockerizing a Redis service Very simple, no frills, Redis service attached to a web application using a link. ## Create a Docker container for Redis Firstly, we create a `Dockerfile` for our new Redis image. FROM ubuntu:14.04 RUN apt-get update && apt-get install -y redis-server EXPOSE 6379 ENTRYPOINT ["/usr/bin/redis-server"] Next we build an image from our `Dockerfile`. Replace `` with your own user name. $ docker build -t /redis . ## Run the service Use the image we've just created and name your container `redis`. Running the service with `-d` runs the container in detached mode, leaving the container running in the background. Importantly, we're not exposing any ports on our container. Instead we're going to use a container link to provide access to our Redis database. $ docker run --name redis -d /redis ## Create your web application container Next we can create a container for our application. We're going to use the `-link` flag to create a link to the `redis` container we've just created with an alias of `db`. This will create a secure tunnel to the `redis` container and expose the Redis instance running inside that container to only this container. $ docker run --link redis:db -i -t ubuntu:14.04 /bin/bash Once inside our freshly created container we need to install Redis to get the `redis-cli` binary to test our connection. $ sudo apt-get update $ sudo apt-get install redis-server $ sudo service redis-server stop As we've used the `--link redis:db` option, Docker has created some environment variables in our web application container. $ env | grep DB_ # Should return something similar to this with your values DB_NAME=/violet_wolf/db DB_PORT_6379_TCP_PORT=6379 DB_PORT=tcp://172.17.0.33:6379 DB_PORT_6379_TCP=tcp://172.17.0.33:6379 DB_PORT_6379_TCP_ADDR=172.17.0.33 DB_PORT_6379_TCP_PROTO=tcp We can see that we've got a small list of environment variables prefixed with `DB`. The `DB` comes from the link alias specified when we launched the container. Let's use the `DB_PORT_6379_TCP_ADDR` variable to connect to our Redis container. $ redis-cli -h $DB_PORT_6379_TCP_ADDR $ redis 172.17.0.33:6379> $ redis 172.17.0.33:6379> set docker awesome OK $ redis 172.17.0.33:6379> get docker "awesome" $ redis 172.17.0.33:6379> exit We could easily use this or other environment variables in our web application to make a connection to our `redis` container. ================================================ FILE: vendor/github.com/docker/docker/docs/examples/running_riak_service.Dockerfile ================================================ # Riak # # VERSION 0.1.1 # Use the Ubuntu base image provided by dotCloud FROM ubuntu:trusty MAINTAINER Hector Castro hector@basho.com # Install Riak repository before we do apt-get update, so that update happens # in a single step RUN apt-get install -q -y curl && \ curl -sSL https://packagecloud.io/install/repositories/basho/riak/script.deb | sudo bash # Install and setup project dependencies RUN apt-get update && \ apt-get install -y supervisor riak=2.0.5-1 RUN mkdir -p /var/log/supervisor RUN locale-gen en_US en_US.UTF-8 COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf # Configure Riak to accept connections from any host RUN sed -i "s|listener.http.internal = 127.0.0.1:8098|listener.http.internal = 0.0.0.0:8098|" /etc/riak/riak.conf RUN sed -i "s|listener.protobuf.internal = 127.0.0.1:8087|listener.protobuf.internal = 0.0.0.0:8087|" /etc/riak/riak.conf # Expose Riak Protocol Buffers and HTTP interfaces EXPOSE 8087 8098 CMD ["/usr/bin/supervisord"] ================================================ FILE: vendor/github.com/docker/docker/docs/examples/running_riak_service.md ================================================ # Dockerizing a Riak service The goal of this example is to show you how to build a Docker image with Riak pre-installed. ## Creating a Dockerfile Create an empty file called `Dockerfile`: $ touch Dockerfile Next, define the parent image you want to use to build your image on top of. We'll use [Ubuntu](https://registry.hub.docker.com/_/ubuntu/) (tag: `trusty`), which is available on [Docker Hub](https://hub.docker.com): # Riak # # VERSION 0.1.1 # Use the Ubuntu base image provided by dotCloud FROM ubuntu:trusty MAINTAINER Hector Castro hector@basho.com After that, we install the curl which is used to download the repository setup script and we download the setup script and run it. # Install Riak repository before we do apt-get update, so that update happens # in a single step RUN apt-get install -q -y curl && \ curl -sSL https://packagecloud.io/install/repositories/basho/riak/script.deb | sudo bash Then we install and setup a few dependencies: - `supervisor` is used manage the Riak processes - `riak=2.0.5-1` is the Riak package coded to version 2.0.5 # Install and setup project dependencies RUN apt-get update && \ apt-get install -y supervisor riak=2.0.5-1 RUN mkdir -p /var/log/supervisor RUN locale-gen en_US en_US.UTF-8 COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf After that, we modify Riak's configuration: # Configure Riak to accept connections from any host RUN sed -i "s|listener.http.internal = 127.0.0.1:8098|listener.http.internal = 0.0.0.0:8098|" /etc/riak/riak.conf RUN sed -i "s|listener.protobuf.internal = 127.0.0.1:8087|listener.protobuf.internal = 0.0.0.0:8087|" /etc/riak/riak.conf Then, we expose the Riak Protocol Buffers and HTTP interfaces: # Expose Riak Protocol Buffers and HTTP interfaces EXPOSE 8087 8098 Finally, run `supervisord` so that Riak is started: CMD ["/usr/bin/supervisord"] ## Create a supervisord configuration file Create an empty file called `supervisord.conf`. Make sure it's at the same directory level as your `Dockerfile`: touch supervisord.conf Populate it with the following program definitions: [supervisord] nodaemon=true [program:riak] command=bash -c "/usr/sbin/riak console" numprocs=1 autostart=true autorestart=true user=riak environment=HOME="/var/lib/riak" stdout_logfile=/var/log/supervisor/%(program_name)s.log stderr_logfile=/var/log/supervisor/%(program_name)s.log ## Build the Docker image for Riak Now you should be able to build a Docker image for Riak: $ docker build -t "/riak" . ## Next steps Riak is a distributed database. Many production deployments consist of [at least five nodes]( http://basho.com/why-your-riak-cluster-should-have-at-least-five-nodes/). See the [docker-riak](https://github.com/hectcastro/docker-riak) project details on how to deploy a Riak cluster using Docker and Pipework. ================================================ FILE: vendor/github.com/docker/docker/docs/examples/running_ssh_service.Dockerfile ================================================ # sshd # # VERSION 0.0.2 FROM ubuntu:14.04 MAINTAINER Sven Dowideit RUN apt-get update && apt-get install -y openssh-server RUN mkdir /var/run/sshd RUN echo 'root:screencast' | chpasswd RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config # SSH login fix. Otherwise user is kicked off after login RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd ENV NOTVISIBLE "in users profile" RUN echo "export VISIBLE=now" >> /etc/profile EXPOSE 22 CMD ["/usr/sbin/sshd", "-D"] ================================================ FILE: vendor/github.com/docker/docker/docs/examples/running_ssh_service.md ================================================ # Dockerizing an SSH daemon service ## Build an `eg_sshd` image The following `Dockerfile` sets up an SSHd service in a container that you can use to connect to and inspect other container's volumes, or to get quick access to a test container. # sshd # # VERSION 0.0.2 FROM ubuntu:14.04 MAINTAINER Sven Dowideit RUN apt-get update && apt-get install -y openssh-server RUN mkdir /var/run/sshd RUN echo 'root:screencast' | chpasswd RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config # SSH login fix. Otherwise user is kicked off after login RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd ENV NOTVISIBLE "in users profile" RUN echo "export VISIBLE=now" >> /etc/profile EXPOSE 22 CMD ["/usr/sbin/sshd", "-D"] Build the image using: $ docker build -t eg_sshd . ## Run a `test_sshd` container Then run it. You can then use `docker port` to find out what host port the container's port 22 is mapped to: $ docker run -d -P --name test_sshd eg_sshd $ docker port test_sshd 22 0.0.0.0:49154 And now you can ssh as `root` on the container's IP address (you can find it with `docker inspect`) or on port `49154` of the Docker daemon's host IP address (`ip address` or `ifconfig` can tell you that) or `localhost` if on the Docker daemon host: $ ssh root@192.168.1.2 -p 49154 # The password is ``screencast``. $$ ## Environment variables Using the `sshd` daemon to spawn shells makes it complicated to pass environment variables to the user's shell via the normal Docker mechanisms, as `sshd` scrubs the environment before it starts the shell. If you're setting values in the `Dockerfile` using `ENV`, you'll need to push them to a shell initialization file like the `/etc/profile` example in the `Dockerfile` above. If you need to pass`docker run -e ENV=value` values, you will need to write a short script to do the same before you start `sshd -D` and then replace the `CMD` with that script. ## Clean up Finally, clean up after your test by stopping and removing the container, and then removing the image. $ docker stop test_sshd $ docker rm test_sshd $ docker rmi eg_sshd ================================================ FILE: vendor/github.com/docker/docker/docs/examples/supervisord.conf ================================================ [supervisord] nodaemon=true [program:riak] command=bash -c "/usr/sbin/riak console" numprocs=1 autostart=true autorestart=true user=riak environment=HOME="/var/lib/riak" stdout_logfile=/var/log/supervisor/%(program_name)s.log stderr_logfile=/var/log/supervisor/%(program_name)s.log ================================================ FILE: vendor/github.com/docker/docker/docs/extend/index.md ================================================ ## Extending Docker Currently, you can extend Docker by adding a plugin. This section contains the following topics: * [Understand Docker plugins](plugins.md) * [Write a volume plugin](plugins_volumes.md) * [Docker plugin API](plugin_api.md) ================================================ FILE: vendor/github.com/docker/docker/docs/extend/plugin_api.md ================================================ # Docker Plugin API Docker plugins are out-of-process extensions which add capabilities to the Docker Engine. This page is intended for people who want to develop their own Docker plugin. If you just want to learn about or use Docker plugins, look [here](plugins.md). ## What plugins are A plugin is a process running on the same docker host as the docker daemon, which registers itself by placing a file in one of the plugin directories described in [Plugin discovery](#plugin-discovery). Plugins have human-readable names, which are short, lowercase strings. For example, `flocker` or `weave`. Plugins can run inside or outside containers. Currently running them outside containers is recommended. ## Plugin discovery Docker discovers plugins by looking for them in the plugin directory whenever a user or container tries to use one by name. There are three types of files which can be put in the plugin directory. * `.sock` files are UNIX domain sockets. * `.spec` files are text files containing a URL, such as `unix:///other.sock`. * `.json` files are text files containing a full json specification for the plugin. UNIX domain socket files must be located under `/run/docker/plugins`, whereas spec files can be located either under `/etc/docker/plugins` or `/usr/lib/docker/plugins`. The name of the file (excluding the extension) determines the plugin name. For example, the `flocker` plugin might create a UNIX socket at `/run/docker/plugins/flocker.sock`. You can define each plugin into a separated subdirectory if you want to isolate definitions from each other. For example, you can create the `flocker` socket under `/run/docker/plugins/flocker/flocker.sock` and only mount `/run/docker/plugins/flocker` inside the `flocker` container. Docker always searches for unix sockets in `/run/docker/plugins` first. It checks for spec or json files under `/etc/docker/plugins` and `/usr/lib/docker/plugins` if the socket doesn't exist. The directory scan stops as soon as it finds the first plugin definition with the given name. ### JSON specification This is the JSON format for a plugin: ```json { "Name": "plugin-example", "Addr": "https://example.com/docker/plugin", "TLSConfig": { "InsecureSkipVerify": false, "CAFile": "/usr/shared/docker/certs/example-ca.pem", "CertFile": "/usr/shared/docker/certs/example-cert.pem", "KeyFile": "/usr/shared/docker/certs/example-key.pem", } } ``` The `TLSConfig` field is optional and TLS will only be verified if this configuration is present. ## Plugin lifecycle Plugins should be started before Docker, and stopped after Docker. For example, when packaging a plugin for a platform which supports `systemd`, you might use [`systemd` dependencies]( http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Before=) to manage startup and shutdown order. When upgrading a plugin, you should first stop the Docker daemon, upgrade the plugin, then start Docker again. ## Plugin activation When a plugin is first referred to -- either by a user referring to it by name (e.g. `docker run --volume-driver=foo`) or a container already configured to use a plugin being started -- Docker looks for the named plugin in the plugin directory and activates it with a handshake. See Handshake API below. Plugins are *not* activated automatically at Docker daemon startup. Rather, they are activated only lazily, or on-demand, when they are needed. ## API design The Plugin API is RPC-style JSON over HTTP, much like webhooks. Requests flow *from* the Docker daemon *to* the plugin. So the plugin needs to implement an HTTP server and bind this to the UNIX socket mentioned in the "plugin discovery" section. All requests are HTTP `POST` requests. The API is versioned via an Accept header, which currently is always set to `application/vnd.docker.plugins.v1+json`. ## Handshake API Plugins are activated via the following "handshake" API call. ### /Plugin.Activate **Request:** empty body **Response:** ``` { "Implements": ["VolumeDriver"] } ``` Responds with a list of Docker subsystems which this plugin implements. After activation, the plugin will then be sent events from this subsystem. ## Plugin retries Attempts to call a method on a plugin are retried with an exponential backoff for up to 30 seconds. This may help when packaging plugins as containers, since it gives plugin containers a chance to start up before failing any user containers which depend on them. ================================================ FILE: vendor/github.com/docker/docker/docs/extend/plugins.md ================================================ # Understand Docker plugins You can extend the capabilities of the Docker Engine by loading third-party plugins. ## Types of plugins Plugins extend Docker's functionality. They come in specific types. For example, a [volume plugin](plugins_volume.md) might enable Docker volumes to persist across multiple Docker hosts. Currently Docker supports volume and network driver plugins. In the future it will support additional plugin types. ## Installing a plugin Follow the instructions in the plugin's documentation. ## Finding a plugin The following plugins exist: * The [Flocker plugin](https://clusterhq.com/docker-plugin/) is a volume plugin which provides multi-host portable volumes for Docker, enabling you to run databases and other stateful containers and move them around across a cluster of machines. * The [GlusterFS plugin](https://github.com/calavera/docker-volume-glusterfs) is another volume plugin that provides multi-host volumes management for Docker using GlusterFS. * The [Keywhiz plugin](https://github.com/calavera/docker-volume-keywhiz) is a plugin that provides credentials and secret management using Keywhiz as a central repository. ## Troubleshooting a plugin If you are having problems with Docker after loading a plugin, ask the authors of the plugin for help. The Docker team may not be able to assist you. ## Writing a plugin If you are interested in writing a plugin for Docker, or seeing how they work under the hood, see the [docker plugins reference](plugin_api.md). ================================================ FILE: vendor/github.com/docker/docker/docs/extend/plugins_volume.md ================================================ # Write a volume plugin Docker volume plugins enable Docker deployments to be integrated with external storage systems, such as Amazon EBS, and enable data volumes to persist beyond the lifetime of a single Docker host. See the [plugin documentation](plugins.md) for more information. # Command-line changes A volume plugin makes use of the `-v`and `--volume-driver` flag on the `docker run` command. The `-v` flag accepts a volume name and the `--volume-driver` flag a driver type, for example: $ docker run -ti -v volumename:/data --volume-driver=flocker busybox sh This command passes the `volumename` through to the volume plugin as a user-given name for the volume. The `volumename` must not begin with a `/`. By having the user specify a `volumename`, a plugin can associate the volume with an external volume beyond the lifetime of a single container or container host. This can be used, for example, to move a stateful container from one server to another. By specifying a `volumedriver` in conjunction with a `volumename`, users can use plugins such as [Flocker](https://clusterhq.com/docker-plugin/) to manage volumes external to a single host, such as those on EBS. # Create a VolumeDriver The container creation endpoint (`/containers/create`) accepts a `VolumeDriver` field of type `string` allowing to specify the name of the driver. It's default value of `"local"` (the default driver for local volumes). # Volume plugin protocol If a plugin registers itself as a `VolumeDriver` when activated, then it is expected to provide writeable paths on the host filesystem for the Docker daemon to provide to containers to consume. The Docker daemon handles bind-mounting the provided paths into user containers. ### /VolumeDriver.Create **Request**: ``` { "Name": "volume_name" } ``` Instruct the plugin that the user wants to create a volume, given a user specified volume name. The plugin does not need to actually manifest the volume on the filesystem yet (until Mount is called). **Response**: ``` { "Err": null } ``` Respond with a string error if an error occurred. ### /VolumeDriver.Remove **Request**: ``` { "Name": "volume_name" } ``` Create a volume, given a user specified volume name. **Response**: ``` { "Err": null } ``` Respond with a string error if an error occurred. ### /VolumeDriver.Mount **Request**: ``` { "Name": "volume_name" } ``` Docker requires the plugin to provide a volume, given a user specified volume name. This is called once per container start. **Response**: ``` { "Mountpoint": "/path/to/directory/on/host", "Err": null } ``` Respond with the path on the host filesystem where the volume has been made available, and/or a string error if an error occurred. ### /VolumeDriver.Path **Request**: ``` { "Name": "volume_name" } ``` Docker needs reminding of the path to the volume on the host. **Response**: ``` { "Mountpoint": "/path/to/directory/on/host", "Err": null } ``` Respond with the path on the host filesystem where the volume has been made available, and/or a string error if an error occurred. ### /VolumeDriver.Unmount **Request**: ``` { "Name": "volume_name" } ``` Indication that Docker no longer is using the named volume. This is called once per container stop. Plugin may deduce that it is safe to deprovision it at this point. **Response**: ``` { "Err": null } ``` Respond with a string error if an error occurred. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/SUSE.md ================================================ # openSUSE Docker is available in **openSUSE 12.3 and later**. Please note that due to its current limitations Docker is able to run only **64 bit** architecture. Docker is not part of the official repositories of openSUSE 12.3 and openSUSE 13.1. Hence it is necessary to add the [Virtualization repository](https://build.opensuse.org/project/show/Virtualization) from [OBS](https://build.opensuse.org/) to install the `docker` package. Execute one of the following commands to add the Virtualization repository: # openSUSE 12.3 $ sudo zypper ar -f http://download.opensuse.org/repositories/Virtualization/openSUSE_12.3/ Virtualization # openSUSE 13.1 $ sudo zypper ar -f http://download.opensuse.org/repositories/Virtualization/openSUSE_13.1/ Virtualization No extra repository is required for openSUSE 13.2 and later. # SUSE Linux Enterprise Docker is available in **SUSE Linux Enterprise 12 and later**. Please note that due to its current limitations Docker is able to run only on **64 bit** architecture. ## Installation Install the Docker package. $ sudo zypper in docker Now that it's installed, let's start the Docker daemon. $ sudo systemctl start docker If we want Docker to start at boot, we should also: $ sudo systemctl enable docker The docker package creates a new group named docker. Users, other than root user, need to be part of this group in order to interact with the Docker daemon. You can add users with: $ sudo /usr/sbin/usermod -a -G docker To verify that everything has worked as expected: $ sudo docker run --rm -i -t opensuse /bin/bash This should download and import the `opensuse` image, and then start `bash` in a container. To exit the container type `exit`. If you want your containers to be able to access the external network you must enable the `net.ipv4.ip_forward` rule. This can be done using YaST by browsing to the `Network Devices -> Network Settings -> Routing` menu and ensuring that the `Enable IPv4 Forwarding` box is checked. This option cannot be changed when networking is handled by the Network Manager. In such cases the `/etc/sysconfig/SuSEfirewall2` file needs to be edited by hand to ensure the `FW_ROUTE` flag is set to `yes` like so: FW_ROUTE="yes" **Done!** ## Custom daemon options If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our systemd article to learn how to [customize your systemd Docker daemon options](/articles/systemd/). ## Uninstallation To uninstall the Docker package: $ sudo zypper rm docker The above command will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ## What's next Continue with the [User Guide](/userguide/). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/amazon.md ================================================ ## Amazon EC2 You can install Docker on any AWS EC2 Amazon Machine Image (AMI) which runs an operating system that Docker supports. Amazon's website includes specific instructions for [installing on Amazon Linux](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html#install_docker). To install on another AMI, follow the instructions for its specific operating system in this installation guide. For detailed information on Amazon AWS support for Docker, refer to [Amazon's documentation](http://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/archlinux.md ================================================ # Arch Linux Installing on Arch Linux can be handled via the package in community: - [docker](https://www.archlinux.org/packages/community/x86_64/docker/) or the following AUR package: - [docker-git](https://aur.archlinux.org/packages/docker-git/) The docker package will install the latest tagged version of docker. The docker-git package will build from the current master branch. ## Dependencies Docker depends on several packages which are specified as dependencies in the packages. The core dependencies are: - bridge-utils - device-mapper - iproute2 - lxc - sqlite ## Installation For the normal package a simple $ sudo pacman -S docker is all that is needed. For the AUR package execute: $ sudo yaourt -S docker-git The instructions here assume **yaourt** is installed. See [Arch User Repository](https://wiki.archlinux.org/index.php/Arch_User_Repository#Installing_packages) for information on building and installing packages from the AUR if you have not done so before. ## Starting Docker There is a systemd service unit created for docker. To start the docker service: $ sudo systemctl start docker To start on system boot: $ sudo systemctl enable docker ## Custom daemon options If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our systemd article to learn how to [customize your systemd Docker daemon options](/articles/systemd/). ## Uninstallation To uninstall the Docker package: $ sudo pacman -R docker To uninstall the Docker package and dependencies that are no longer needed: $ sudo pacman -Rns docker The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/azure.md ================================================ # Microsoft Azure ## Creating a Docker host machine on Azure Please check out to the following detailed tutorials on [Microsoft Azure][0] website to find out different ways to create a Docker-ready Linux virtual machines on Azure: * [Docker Virtual Machine Extensions on Azure][1] * [How to use the Docker VM Extension from Azure Cross-Platform Interface][2] * [How to use the Docker VM Extension with the Azure Portal][3] * [Using Docker Machine with Azure][4] ## What next? Continue with the [User Guide](/userguide/). [0]: http://azure.microsoft.com/ [1]: http://azure.microsoft.com/en-us/documentation/articles/virtual-machines-docker-vm-extension/ [2]: http://azure.microsoft.com/documentation/articles/virtual-machines-docker-with-xplat-cli/ [3]: http://azure.microsoft.com/documentation/articles/virtual-machines-docker-with-portal/ [4]: http://azure.microsoft.com/en-us/documentation/articles/virtual-machines-docker-machine/ ================================================ FILE: vendor/github.com/docker/docker/docs/installation/binaries.md ================================================ # Binaries **This instruction set is meant for hackers who want to try out Docker on a variety of environments.** Before following these directions, you should really check if a packaged version of Docker is already available for your distribution. We have packages for many distributions, and more keep showing up all the time! ## Check runtime dependencies To run properly, docker needs the following software to be installed at runtime: - iptables version 1.4 or later - Git version 1.7 or later - procps (or similar provider of a "ps" executable) - XZ Utils 4.9 or later - a [properly mounted]( https://github.com/tianon/cgroupfs-mount/blob/master/cgroupfs-mount) cgroupfs hierarchy (having a single, all-encompassing "cgroup" mount point [is](https://github.com/docker/docker/issues/2683) [not](https://github.com/docker/docker/issues/3485) [sufficient](https://github.com/docker/docker/issues/4568)) ## Check kernel dependencies Docker in daemon mode has specific kernel requirements. For details, check your distribution in [*Installation*](../#installation-list). A 3.10 Linux kernel is the minimum requirement for Docker. Kernels older than 3.10 lack some of the features required to run Docker containers. These older versions are known to have bugs which cause data loss and frequently panic under certain conditions. The latest minor version (3.x.y) of the 3.10 (or a newer maintained version) Linux kernel is recommended. Keeping the kernel up to date with the latest minor version will ensure critical kernel bugs get fixed. > **Warning**: > Installing custom kernels and kernel packages is probably not > supported by your Linux distribution's vendor. Please make sure to > ask your vendor about Docker support first before attempting to > install custom kernels on your distribution. > **Warning**: > Installing a newer kernel might not be enough for some distributions > which provide packages which are too old or incompatible with > newer kernels. Note that Docker also has a client mode, which can run on virtually any Linux kernel (it even builds on OS X!). ## Enable AppArmor and SELinux when possible Please use AppArmor or SELinux if your Linux distribution supports either of the two. This helps improve security and blocks certain types of exploits. Your distribution's documentation should provide detailed steps on how to enable the recommended security mechanism. Some Linux distributions enable AppArmor or SELinux by default and they run a kernel which doesn't meet the minimum requirements (3.10 or newer). Updating the kernel to 3.10 or newer on such a system might not be enough to start Docker and run containers. Incompatibilities between the version of AppArmor/SELinux user space utilities provided by the system and the kernel could prevent Docker from running, from starting containers or, cause containers to exhibit unexpected behaviour. > **Warning**: > If either of the security mechanisms is enabled, it should not be > disabled to make Docker or its containers run. This will reduce > security in that environment, lose support from the distribution's > vendor for the system, and might break regulations and security > policies in heavily regulated environments. ## Get the Docker binary You can download either the latest release binary or a specific version. After downloading a binary file, you must set the file's execute bit to run it. To set the file's execute bit on Linux and OS X: $ chmod +x docker To get the list of stable release version numbers from GitHub, view the `docker/docker` [releases page](https://github.com/docker/docker/releases). > **Note** > > 1) You can get the MD5 and SHA256 hashes by appending .md5 and .sha256 to the URLs respectively > > 2) You can get the compressed binaries by appending .tgz to the URLs ### Get the Linux binary To download the latest version for Linux, use the following URLs: https://get.docker.com/builds/Linux/i386/docker-latest https://get.docker.com/builds/Linux/x86_64/docker-latest To download a specific version for Linux, use the following URL patterns: https://get.docker.com/builds/Linux/i386/docker- https://get.docker.com/builds/Linux/x86_64/docker- For example: https://get.docker.com/builds/Linux/i386/docker-1.6.0 https://get.docker.com/builds/Linux/x86_64/docker-1.6.0 ### Get the Mac OS X binary The Mac OS X binary is only a client. You cannot use it to run the `docker` daemon. To download the latest version for Mac OS X, use the following URLs: https://get.docker.com/builds/Darwin/i386/docker-latest https://get.docker.com/builds/Darwin/x86_64/docker-latest To download a specific version for Mac OS X, use the following URL patterns: https://get.docker.com/builds/Darwin/i386/docker- https://get.docker.com/builds/Darwin/x86_64/docker- For example: https://get.docker.com/builds/Darwin/i386/docker-1.6.0 https://get.docker.com/builds/Darwin/x86_64/docker-1.6.0 ### Get the Windows binary You can only download the Windows client binary for version `1.6.0` onwards. Moreover, the binary is only a client, you cannot use it to run the `docker` daemon. To download the latest version for Windows, use the following URLs: https://get.docker.com/builds/Windows/i386/docker-latest.exe https://get.docker.com/builds/Windows/x86_64/docker-latest.exe To download a specific version for Windows, use the following URL pattern: https://get.docker.com/builds/Windows/i386/docker-.exe https://get.docker.com/builds/Windows/x86_64/docker-.exe For example: https://get.docker.com/builds/Windows/i386/docker-1.6.0.exe https://get.docker.com/builds/Windows/x86_64/docker-1.6.0.exe ## Run the Docker daemon # start the docker in daemon mode from the directory you unpacked $ sudo ./docker -d & ## Giving non-root access The `docker` daemon always runs as the root user, and the `docker` daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user *root*, and so, by default, you can access it with `sudo`. If you (or your Docker installer) create a Unix group called *docker* and add users to it, then the `docker` daemon will make the ownership of the Unix socket read/writable by the *docker* group when the daemon starts. The `docker` daemon must always run as the root user, but if you run the `docker` client as a user in the *docker* group then you don't need to add `sudo` to all the client commands. > **Warning**: > The *docker* group (or the group specified with `-G`) is root-equivalent; > see [*Docker Daemon Attack Surface*]( > /articles/security/#docker-daemon-attack-surface) details. ## Upgrades To upgrade your manual installation of Docker, first kill the docker daemon: $ killall docker Then follow the regular installation steps. ## Run your first container! # check your docker version $ sudo ./docker version # run a container and open an interactive shell in the container $ sudo ./docker run -i -t ubuntu /bin/bash Continue with the [User Guide](/userguide/). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/centos.md ================================================ # CentOS Docker is supported on the following versions of CentOS: * CentOS 7.X Installation on other binary compatible EL7 distributions such as Scientific Linux might succeed, but Docker does not test or support Docker on these distributions. This page instructs you to install using Docker-managed release packages and installation mechanisms. Using these packages ensures you get the latest release of Docker. If you wish to install using CentOS-managed packages, consult your CentOS documentation. ## Prerequisites Docker requires a 64-bit installation regardless of your CentOS version. Also, your kernel must be 3.10 at minimum, which CentOS 7 runs. To check your current kernel version, open a terminal and use `uname -r` to display your kernel version: $ uname -r 3.10.0-229.el7.x86_64 Finally, is it recommended that you fully update your system. Please keep in mind that your system should be fully patched to fix any potential kernel bugs. Any reported kernel bugs may have already been fixed on the latest kernel packages. ## Install You use the same installation procedure for all versions of CentOS, only the package you install differs. There are two packages to choose from:
Version Package name
7.X

https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm

https://get.docker.com/rpm/1.7.1/centos-7/SRPMS/docker-engine-1.7.1-1.el7.centos.src.rpm

Installation procedure: 1. Log into your machine as a user with `sudo` or `root` privileges. 2. Make sure your existing packages are up-to-date. $ sudo yum update 3. Download the Docker RPM to the current directory. $ curl -O -sSL https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.x86_64.rpm 4. Use `yum` to install the package. $ sudo yum localinstall --nogpgcheck docker-engine-1.7.1-1.el7.x86_64.rpm 5. Start the Docker daemon. $ sudo service docker start 6. Verify `docker` is installed correctly by running a test image in a container. $ sudo docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from hello-world a8219747be10: Pull complete 91c95931e552: Already exists hello-world:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security. Digest: sha256:aa03e5d0d5553b4c3473e89c8619cf79df368babd1.7.1cf5daeb82aab55838d Status: Downloaded newer image for hello-world:latest Hello from Docker. This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (Assuming it was not already locally available.) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash For more examples and ideas, visit: http://docs.docker.com/userguide/ ## Create a docker group The `docker` daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user `root` and other users can access it with `sudo`. For this reason, `docker` daemon always runs as the `root` user. To avoid having to use `sudo` when you use the `docker` command, create a Unix group called `docker` and add users to it. When the `docker` daemon starts, it makes the ownership of the Unix socket read/writable by the `docker` group. >**Warning**: The `docker` group is equivalent to the `root` user; For details >on how this impacts security in your system, see [*Docker Daemon Attack >Surface*](/articles/security/#docker-daemon-attack-surface) for details. To create the `docker` group and add your user: 1. Log into Centos as a user with `sudo` privileges. 2. Create the `docker` group and add your user. `sudo usermod -aG docker your_username` 3. Log out and log back in. This ensures your user is running with the correct permissions. 4. Verify your work by running `docker` without `sudo`. $ docker run hello-world ## Start the docker daemon at boot To ensure Docker starts when you boot your system, do the following: $ sudo chkconfig docker on If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our Systemd article to learn how to [customize your Systemd Docker daemon options](/articles/systemd/). ## Uninstall You can uninstall the Docker software with `yum`. 1. List the package you have installed. $ yum list installed | grep docker yum list installed | grep docker docker-engine.x86_64 1.7.1-1.el7 @/docker-engine-1.7.1-1.el7.x86_64.rpm 2. Remove the package. $ sudo yum -y remove docker-engine.x86_64 This command does not remove images, containers, volumes, or user-created configuration files on your host. 3. To delete all images, containers, and volumes, run the following command: $ rm -rf /var/lib/docker 4. Locate and delete any user-created configuration files. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/cruxlinux.md ================================================ # CRUX Linux Installing on CRUX Linux can be handled via the contrib ports from [James Mills](http://prologic.shortcircuit.net.au/) and are included in the official [contrib](http://crux.nu/portdb/?a=repo&q=contrib) ports: - docker The `docker` port will build and install the latest tagged version of Docker. ## Installation Assuming you have contrib enabled, update your ports tree and install docker: $ sudo prt-get depinst docker ## Kernel requirements To have a working **CRUX+Docker** Host you must ensure your Kernel has the necessary modules enabled for the Docker Daemon to function correctly. Please read the `README`: $ sudo prt-get readme docker The `docker` port installs the `contrib/check-config.sh` script provided by the Docker contributors for checking your kernel configuration as a suitable Docker host. To check your Kernel configuration run: $ /usr/share/docker/check-config.sh ## Starting Docker There is a rc script created for Docker. To start the Docker service: $ sudo /etc/rc.d/docker start To start on system boot: - Edit `/etc/rc.conf` - Put `docker` into the `SERVICES=(...)` array after `net`. ## Images There is a CRUX image maintained by [James Mills](http://prologic.shortcircuit.net.au/) as part of the Docker "Official Library" of images. To use this image simply pull it or use it as part of your `FROM` line in your `Dockerfile(s)`. $ docker pull crux $ docker run -i -t crux There are also user contributed [CRUX based image(s)](https://registry.hub.docker.com/repos/crux/) on the Docker Hub. ## Uninstallation To uninstall the Docker package: $ sudo prt-get remove docker The above command will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ## Issues If you have any issues please file a bug with the [CRUX Bug Tracker](http://crux.nu/bugs/). ## Support For support contact the [CRUX Mailing List](http://crux.nu/Main/MailingLists) or join CRUX's [IRC Channels](http://crux.nu/Main/IrcChannels). on the [FreeNode](http://freenode.net/) IRC Network. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/debian.md ================================================ # Debian Docker is supported on the following versions of Debian: - [*Debian 8.0 Jessie (64-bit)*](#debian-jessie-80-64-bit) - [*Debian 7.7 Wheezy (64-bit)*](#debian-wheezy-stable-7-x-64-bit) ## Debian Jessie 8.0 (64-bit) Debian 8 comes with a 3.16.0 Linux kernel, the `docker.io` package can be found in the `jessie-backports` repository. Reasoning behind this can be found here. Instructions how to enable the backports repository can be found here. > **Note**: > Debian contains a much older KDE3/GNOME2 package called ``docker``, so the > package and the executable are called ``docker.io``. ### Installation Make sure you enabled the `jessie-backports` repository, as stated above. To install the latest Debian package (may not be the latest Docker release): $ sudo apt-get update $ sudo apt-get install docker.io To verify that everything has worked as expected: $ sudo docker run --rm hello-world This command downloads and runs the `hello-world` image in a container. When the container runs, it prints an informational message. Then, it exits. > **Note**: > If you want to enable memory and swap accounting see > [this](/installation/ubuntulinux/#memory-and-swap-accounting). ### Uninstallation To uninstall the Docker package: $ sudo apt-get purge docker-io To uninstall the Docker package and dependencies that are no longer needed: $ sudo apt-get autoremove --purge docker-io The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ## Debian Wheezy/Stable 7.x (64-bit) Docker requires Kernel 3.8+, while Wheezy ships with Kernel 3.2 (for more details on why 3.8 is required, see discussion on [bug #407](https://github.com/docker/docker/issues/407)). Fortunately, wheezy-backports currently has [Kernel 3.16 ](https://packages.debian.org/search?suite=wheezy-backports§ion=all&arch=any&searchon=names&keywords=linux-image-amd64), which is officially supported by Docker. ### Installation 1. Install Kernel from wheezy-backports Add the following line to your `/etc/apt/sources.list` `deb http://http.debian.net/debian wheezy-backports main` then install the `linux-image-amd64` package (note the use of `-t wheezy-backports`) $ sudo apt-get update $ sudo apt-get install -t wheezy-backports linux-image-amd64 2. Restart your system. This is necessary for Debian to use your new kernel. 3. Install Docker using the get.docker.com script: `curl -sSL https://get.docker.com/ | sh` >**Note**: If your company is behind a filtering proxy, you may find that the >`apt-key` >command fails for the Docker repo during installation. To work around this, >add the key directly using the following: > > $ wget -qO- https://get.docker.com/gpg | sudo apt-key add - ### Uninstallation To uninstall the Docker package: $ sudo apt-get purge lxc-docker To uninstall the Docker package and dependencies that are no longer needed: $ sudo apt-get autoremove --purge lxc-docker The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ## Giving non-root access The `docker` daemon always runs as the `root` user and the `docker` daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user `root`, and so, by default, you can access it with `sudo`. If you (or your Docker installer) create a Unix group called `docker` and add users to it, then the `docker` daemon will make the ownership of the Unix socket read/writable by the `docker` group when the daemon starts. The `docker` daemon must always run as the root user, but if you run the `docker` client as a user in the `docker` group then you don't need to add `sudo` to all the client commands. From Docker 0.9.0 you can use the `-G` flag to specify an alternative group. > **Warning**: > The `docker` group (or the group specified with the `-G` flag) is > `root`-equivalent; see [*Docker Daemon Attack Surface*]( > /articles/security/#docker-daemon-attack-surface) details. **Example:** # Add the docker group if it doesn't already exist. $ sudo groupadd docker # Add the connected user "${USER}" to the docker group. # Change the user name to match your preferred user. # You may have to logout and log back in again for # this to take effect. $ sudo gpasswd -a ${USER} docker # Restart the Docker daemon. $ sudo service docker restart ## What next? Continue with the [User Guide](/userguide/). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/fedora.md ================================================ # Fedora Docker is supported on the following versions of Fedora: - Fedora 20 - Fedora 21 - Fedora 22 This page instructs you to install using Docker-managed release packages and installation mechanisms. Using these packages ensures you get the latest release of Docker. If you wish to install using Fedora-managed packages, consult your Fedora release documentation for information on Fedora's Docker support. ##Prerequisites Docker requires a 64-bit installation regardless of your Fedora version. Also, your kernel must be 3.10 at minimum. To check your current kernel version, open a terminal and use `uname -r` to display your kernel version: $ uname -r 3.19.5-100.fc20.x86_64 If your kernel is at a older version, you must update it. Finally, is it recommended that you fully update your system. Please keep in mind that your system should be fully patched to fix any potential kernel bugs. Any reported kernel bugs may have already been fixed on the latest kernel packages ## Install You use the same installation procedure for all versions of Fedora, only the package you install differs. Choose from these packages:
Version Package name
Fedora 20

docker-engine-1.7.1-1.fc20.x86_64.rpm

docker-engine-1.7.1-1.fc20.src.rpm

Fedora 21

docker-engine-1.7.1-1.fc21.x86_64.rpm

docker-engine-1.7.1-1.fc21.src.rpm

Fedora 22

docker-engine-1.7.1-1.fc22.x86_64.rpm

docker-engine-1.7.1-1.fc22.src.rpm

This procedure depicts an installation on version 21. If you are installing on 20 or 22, substitute that package for your installation. 1. Log into your machine as a user with `sudo` or `root` privileges. 2. Make sure you don't have an older version of Docker installed. $ yum list installed | grep docker If you have an older version, remove it using the `yum -y remove ` command. 3. Download the Docker RPM to the current directory. $ curl -O -sSL https://url_to_package/docker-engine-1.7.1-0.1.fc21.x86_64.rpm 4. Use `yum` to install the package. $ sudo yum localinstall --nogpgcheck docker-engine-1.7.1-0.1.fc21.x86_64.rpm 5. Start the Docker daemon. $ sudo service docker start 6. Verify `docker` is installed correctly by running a test image in a container. $ sudo docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from hello-world a8219747be10: Pull complete 91c95931e552: Already exists hello-world:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security. Digest: sha256:aa03e5d0d5553b4c3473e89c8619cf79df368babd18681cf5daeb82aab55838d Status: Downloaded newer image for hello-world:latest Hello from Docker. This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (Assuming it was not already locally available.) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash For more examples and ideas, visit: http://docs.docker.com/userguide/ ## Create a docker group The `docker` daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user `root` and other users can access it with `sudo`. For this reason, `docker` daemon always runs as the `root` user. To avoid having to use `sudo` when you use the `docker` command, create a Unix group called `docker` and add users to it. When the `docker` daemon starts, it makes the ownership of the Unix socket read/writable by the `docker` group. >**Warning**: The `docker` group is equivalent to the `root` user; For details >on how this impacts security in your system, see [*Docker Daemon Attack >Surface*](/articles/security/#docker-daemon-attack-surface) for details. To create the `docker` group and add your user: 1. Log into your system as a user with `sudo` privileges. 2. Create the `docker` group and add your user. `sudo usermod -aG docker your_username` 3. Log out and log back in. This ensures your user is running with the correct permissions. 4. Verify your work by running `docker` without `sudo`. $ docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from hello-world a8219747be10: Pull complete 91c95931e552: Already exists hello-world:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security. Digest: sha256:aa03e5d0d5553b4c3473e89c8619cf79df368babd18681cf5daeb82aab55838d Status: Downloaded newer image for hello-world:latest Hello from Docker. This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (Assuming it was not already locally available.) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash For more examples and ideas, visit: http://docs.docker.com/userguide/ ## Start the docker daemon at boot To ensure Docker starts when you boot your system, do the following: $ sudo chkconfig docker on If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our Systemd article to learn how to [customize your Systemd Docker daemon options](/articles/systemd/). ## Uninstall You can uninstall the Docker software with `yum`. 1. List the package you have installed. $ yum list installed | grep docker yum list installed | grep docker docker-engine.x86_64 1.7.1-0.1.fc20 @/docker-engine-1.7.1-0.1.fc20.el7.x86_64 2. Remove the package. $ sudo yum -y remove docker-engine.x86_64 This command does not remove images, containers, volumes, or user-created configuration files on your host. 3. To delete all images, containers, and volumes, run the following command: $ rm -rf /var/lib/docker 4. Locate and delete any user-created configuration files. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/frugalware.md ================================================ # FrugalWare Installing on FrugalWare is handled via the official packages: - [lxc-docker i686](http://www.frugalware.org/packages/200141) - [lxc-docker x86_64](http://www.frugalware.org/packages/200130) The lxc-docker package will install the latest tagged version of Docker. ## Dependencies Docker depends on several packages which are specified as dependencies in the packages. The core dependencies are: - systemd - lvm2 - sqlite3 - libguestfs - lxc - iproute2 - bridge-utils ## Installation A simple $ sudo pacman -S lxc-docker is all that is needed. ## Starting Docker There is a systemd service unit created for Docker. To start Docker as service: $ sudo systemctl start lxc-docker To start on system boot: $ sudo systemctl enable lxc-docker ## Custom daemon options If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our systemd article to learn how to [customize your systemd Docker daemon options](/articles/systemd/). ## Uninstallation To uninstall the Docker package: $ sudo pacman -R lxc-docker To uninstall the Docker package and dependencies that are no longer needed: $ sudo pacman -Rns lxc-docker The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/gentoolinux.md ================================================ # Gentoo Installing Docker on Gentoo Linux can be accomplished using one of two ways: the **official** way and the `docker-overlay` way. Official project page of [Gentoo Docker](https://wiki.gentoo.org/wiki/Project:Docker) team. ## Official way The first and recommended way if you are looking for a stable experience is to use the official `app-emulation/docker` package directly from the tree. If any issues arise from this ebuild including, missing kernel configuration flags or dependencies, open a bug on the Gentoo [Bugzilla](https://bugs.gentoo.org) assigned to `docker AT gentoo DOT org` or join and ask in the official [IRC](http://webchat.freenode.net?channels=%23gentoo-containers&uio=d4) channel on the Freenode network. ## docker-overlay way If you're looking for a `-bin` ebuild, a live ebuild, or a bleeding edge ebuild, use the provided overlay, [docker-overlay](https://github.com/tianon/docker-overlay) which can be added using `app-portage/layman`. The most accurate and up-to-date documentation for properly installing and using the overlay can be found in the [overlay](https://github.com/tianon/docker-overlay/blob/master/README.md#using-this-overlay). If any issues arise from this ebuild or the resulting binary, including and especially missing kernel configuration flags or dependencies, open an [issue](https://github.com/tianon/docker-overlay/issues) on the `docker-overlay` repository or ping `tianon` directly in the `#docker` IRC channel on the Freenode network. ## Installation ### Available USE flags | USE Flag | Default | Description | | ------------- |:-------:|:------------| | aufs | |Enables dependencies for the "aufs" graph driver, including necessary kernel flags.| | btrfs | |Enables dependencies for the "btrfs" graph driver, including necessary kernel flags.| | contrib | Yes |Install additional contributed scripts and components.| | device-mapper | Yes |Enables dependencies for the "devicemapper" graph driver, including necessary kernel flags.| | doc | |Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally.| | lxc | |Enables dependencies for the "lxc" execution driver.| | vim-syntax | |Pulls in related vim syntax scripts.| | zsh-completion| |Enable zsh completion support.| USE flags are described in detail on [tianon's blog](https://tianon.github.io/post/2014/05/17/docker-on-gentoo.html). The package should properly pull in all the necessary dependencies and prompt for all necessary kernel options. $ sudo emerge -av app-emulation/docker >Note: Sometimes there is a disparity between the latest versions >in the official **Gentoo tree** and the **docker-overlay**. >Please be patient, and the latest version should propagate shortly. ## Starting Docker Ensure that you are running a kernel that includes all the necessary modules and configuration (and optionally for device-mapper and AUFS or Btrfs, depending on the storage driver you've decided to use). To use Docker, the `docker` daemon must be running as **root**. To use Docker as a **non-root** user, add yourself to the **docker** group by running the following command: $ sudo usermod -a -G docker user ### OpenRC To start the `docker` daemon: $ sudo /etc/init.d/docker start To start on system boot: $ sudo rc-update add docker default ### systemd To start the `docker` daemon: $ sudo systemctl start docker To start on system boot: $ sudo systemctl enable docker If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our systemd article to learn how to [customize your systemd Docker daemon options](/articles/systemd/). ## Uninstallation To uninstall the Docker package: $ sudo emerge -cav app-emulation/docker To uninstall the Docker package and dependencies that are no longer needed: $ sudo emerge -C app-emulation/docker The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/google.md ================================================ # Google Cloud Platform ## QuickStart with Container-optimized Google Compute Engine images 1. Go to [Google Cloud Console][1] and create a new Cloud Project with [Compute Engine enabled][2] 2. Download and configure the [Google Cloud SDK][3] to use your project with the following commands: $ curl -sSL https://sdk.cloud.google.com | bash $ gcloud auth login $ gcloud config set project 3. Start a new instance using the latest [Container-optimized image][4]: (select a zone close to you and the desired instance size) $ gcloud compute instances create docker-playground \ --image container-vm \ --zone us-central1-a \ --machine-type f1-micro 4. Connect to the instance using SSH: $ gcloud compute ssh --zone us-central1-a docker-playground docker-playground:~$ sudo docker run hello-world Hello from Docker. This message shows that your installation appears to be working correctly. ... Read more about [deploying Containers on Google Cloud Platform][5]. [1]: https://cloud.google.com/console [2]: https://developers.google.com/compute/docs/signup [3]: https://developers.google.com/cloud/sdk [4]: https://developers.google.com/compute/docs/containers#container-optimized_google_compute_engine_images [5]: https://developers.google.com/compute/docs/containers ================================================ FILE: vendor/github.com/docker/docker/docs/installation/index.md ================================================ # Supported installation Docker supports installation on the following: * [Amazon EC2 Installation](amazon) * [Arch Linux](archlinux) * [Microsoft Azure platform](azure) * [Installation from binaries](binaries) * [CentOS](centos) * [CRUX Linux](cruxlinux) * [Debian](debian) * [Fedora](fedora) * [FrugalWare](frugalware) * [Gentoo](gentoolinux) * [Google Cloud Platform](google) * [Install on Joyent Public Cloud](joyent) * [Mac OS X](mac) * [Oracle Linux](oracle) * [Rackspace Cloud](rackspace) * [Red Hat Enterprise Linux](rhel) * [IBM SoftLayer](softlayer) * [openSUSE and SUSE Linux Enterprise](SUSE) * [Ubuntu](ubuntulinux) * [Windows](windows) ================================================ FILE: vendor/github.com/docker/docker/docs/installation/joyent.md ================================================ ## Install on Joyent Public Cloud 1. Sign in to the [Joyent customer portal](https://my.joyent.com/) 2. [Create a Docker host](https://docs.joyent.com/jpc/managing-docker-containers/creating-a-docker-host). ## Start and manage containers 1. [Start containers in the web UI](https://docs.joyent.com/jpc/managing-docker-containers/starting-a-container) 2. [Configure the Docker CLI on your laptop](https://docs.joyent.com/jpc/managing-docker-containers/access-your-jpc-docker-hosts-from-the-docker-cli) to connect to the remote host to launch and manage containers. 3. SSH into the Docker host. 4. Launch containers using the Docker CLI. ## Where to go next Continue with the [Docker user guide](/userguide/), read Joyent's [getting started blog post](https://www.joyent.com/blog/first-steps-with-joyents-container-service), and [full documentation](https://docs.joyent.com/jpc/managing-docker-containers). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/mac.md ================================================ # Mac OS X You can install Docker using Boot2Docker to run `docker` commands at your command-line. Choose this installation if you are familiar with the command-line or plan to contribute to the Docker project on GitHub. [Download Kitematic](https://kitematic.com/download) Alternatively, you may want to try Kitematic, an application that lets you set up Docker and run containers using a graphical user interface (GUI). ## Command-line Docker with Boot2Docker Because the Docker daemon uses Linux-specific kernel features, you can't run Docker natively in OS X. Instead, you must install the Boot2Docker application. The application includes a VirtualBox Virtual Machine (VM), Docker itself, and the Boot2Docker management tool. The Boot2Docker management tool is a lightweight Linux virtual machine made specifically to run the Docker daemon on Mac OS X. The VirtualBox VM runs completely from RAM, is a small ~24MB download, and boots in approximately 5s. **Requirements** Your Mac must be running OS X 10.6 "Snow Leopard" or newer to run Boot2Docker. ### Learn the key concepts before installing In a Docker installation on Linux, your machine is both the localhost and the Docker host. In networking, localhost means your computer. The Docker host is the machine on which the containers run. On a typical Linux installation, the Docker client, the Docker daemon, and any containers run directly on your localhost. This means you can address ports on a Docker container using standard localhost addressing such as `localhost:8000` or `0.0.0.0:8376`. ![Linux Architecture Diagram](/installation/images/linux_docker_host.svg) In an OS X installation, the `docker` daemon is running inside a Linux virtual machine provided by Boot2Docker. ![OSX Architecture Diagram](/installation/images/mac_docker_host.svg) In OS X, the Docker host address is the address of the Linux VM. When you start the `boot2docker` process, the VM is assigned an IP address. Under `boot2docker` ports on a container map to ports on the VM. To see this in practice, work through the exercises on this page. ### Installation 1. Go to the [boot2docker/osx-installer ]( https://github.com/boot2docker/osx-installer/releases/latest) release page. 4. Download Boot2Docker by clicking `Boot2Docker-x.x.x.pkg` in the "Downloads" section. 3. Install Boot2Docker by double-clicking the package. The installer places Boot2Docker and VirtualBox in your "Applications" folder. The installation places the `docker` and `boot2docker` binaries in your `/usr/local/bin` directory. ## Start the Boot2Docker Application To run a Docker container, you first start the `boot2docker` VM and then issue `docker` commands to create, load, and manage containers. You can launch `boot2docker` from your Applications folder or from the command line. > **NOTE**: Boot2Docker is designed as a development tool. You should not use > it in production environments. ### From the Applications folder When you launch the "Boot2Docker" application from your "Applications" folder, the application: * opens a terminal window * creates a $HOME/.boot2docker directory * creates a VirtualBox ISO and certs * starts a VirtualBox VM running the `docker` daemon Once the launch completes, you can run `docker` commands. A good way to verify your setup succeeded is to run the `hello-world` container. $ docker run hello-world Unable to find image 'hello-world:latest' locally 511136ea3c5a: Pull complete 31cbccb51277: Pull complete e45a5af57b00: Pull complete hello-world:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security. Status: Downloaded newer image for hello-world:latest Hello from Docker. This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (Assuming it was not already locally available.) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash For more examples and ideas, visit: http://docs.docker.com/userguide/ A more typical way to start and stop `boot2docker` is using the command line. ### From your command line Initialize and run `boot2docker` from the command line, do the following: 1. Create a new Boot2Docker VM. $ boot2docker init This creates a new virtual machine. You only need to run this command once. 2. Start the `boot2docker` VM. $ boot2docker start 3. Display the environment variables for the Docker client. $ boot2docker shellinit Writing /Users/mary/.boot2docker/certs/boot2docker-vm/ca.pem Writing /Users/mary/.boot2docker/certs/boot2docker-vm/cert.pem Writing /Users/mary/.boot2docker/certs/boot2docker-vm/key.pem export DOCKER_HOST=tcp://192.168.59.103:2376 export DOCKER_CERT_PATH=/Users/mary/.boot2docker/certs/boot2docker-vm export DOCKER_TLS_VERIFY=1 The specific paths and address on your machine will be different. 4. To set the environment variables in your shell do the following: $ eval "$(boot2docker shellinit)" You can also set them manually by using the `export` commands `boot2docker` returns. 5. Run the `hello-world` container to verify your setup. $ docker run hello-world ## Basic Boot2Docker exercises At this point, you should have `boot2docker` running and the `docker` client environment initialized. To verify this, run the following commands: $ boot2docker status $ docker version Work through this section to try some practical container tasks using `boot2docker` VM. ### Access container ports 1. Start an NGINX container on the DOCKER_HOST. $ docker run -d -P --name web nginx Normally, the `docker run` commands starts a container, runs it, and then exits. The `-d` flag keeps the container running in the background after the `docker run` command completes. The `-P` flag publishes exposed ports from the container to your local host; this lets you access them from your Mac. 2. Display your running container with `docker ps` command CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5fb65ff765e9 nginx:latest "nginx -g 'daemon of 3 minutes ago Up 3 minutes 0.0.0.0:49156->443/tcp, 0.0.0.0:49157->80/tcp web At this point, you can see `nginx` is running as a daemon. 3. View just the container's ports. $ docker port web 443/tcp -> 0.0.0.0:49156 80/tcp -> 0.0.0.0:49157 This tells you that the `web` container's port `80` is mapped to port `49157` on your Docker host. 4. Enter the `http://localhost:49157` address (`localhost` is `0.0.0.0`) in your browser: ![Bad Address](/installation/images/bad_host.png) This didn't work. The reason it doesn't work is your `DOCKER_HOST` address is not the localhost address (0.0.0.0) but is instead the address of the `boot2docker` VM. 5. Get the address of the `boot2docker` VM. $ boot2docker ip 192.168.59.103 6. Enter the `http://192.168.59.103:49157` address in your browser: ![Correct Addressing](/installation/images/good_host.png) Success! 7. To stop and then remove your running `nginx` container, do the following: $ docker stop web $ docker rm web ### Mount a volume on the container When you start `boot2docker`, it automatically shares your `/Users` directory with the VM. You can use this share point to mount directories onto your container. The next exercise demonstrates how to do this. 1. Change to your user `$HOME` directory. $ cd $HOME 2. Make a new `site` directory. $ mkdir site 3. Change into the `site` directory. $ cd site 4. Create a new `index.html` file. $ echo "my new site" > index.html 5. Start a new `nginx` container and replace the `html` folder with your `site` directory. $ docker run -d -P -v $HOME/site:/usr/share/nginx/html --name mysite nginx 6. Get the `mysite` container's port. $ docker port mysite 80/tcp -> 0.0.0.0:49166 443/tcp -> 0.0.0.0:49165 7. Open the site in a browser: ![My site page](/installation/images/newsite_view.png) 8. Try adding a page to your `$HOME/site` in real time. $ echo "This is cool" > cool.html 9. Open the new page in the browser. ![Cool page](/installation/images/cool_view.png) 9. Stop and then remove your running `mysite` container. $ docker stop mysite $ docker rm mysite ## Upgrade Boot2Docker If you running Boot2Docker 1.4.1 or greater, you can upgrade Boot2Docker from the command line. If you are running an older version, you should use the package provided by the `boot2docker` repository. ### From the command line To upgrade from 1.4.1 or greater, you can do this: 1. Open a terminal on your local machine. 2. Stop the `boot2docker` application. $ boot2docker stop 3. Run the upgrade command. $ boot2docker upgrade ### Use the installer To upgrade any version of Boot2Docker, do this: 1. Open a terminal on your local machine. 2. Stop the `boot2docker` application. $ boot2docker stop 3. Go to the [boot2docker/osx-installer ]( https://github.com/boot2docker/osx-installer/releases/latest) release page. 4. Download Boot2Docker by clicking `Boot2Docker-x.x.x.pkg` in the "Downloads" section. 2. Install Boot2Docker by double-clicking the package. The installer places Boot2Docker in your "Applications" folder. ## Uninstallation 1. Go to the [boot2docker/osx-installer ]( https://github.com/boot2docker/osx-installer/releases/latest) release page. 2. Download the source code by clicking `Source code (zip)` or `Source code (tar.gz)` in the "Downloads" section. 3. Extract the source code. 4. Open a terminal on your local machine. 5. Change to the directory where you extracted the source code: $ cd 6. Make sure the uninstall.sh script is executable: $ chmod +x uninstall.sh 7. Run the uninstall.sh script: $ ./uninstall.sh ## Learning more and acknowledgement Use `boot2docker help` to list the full command line reference. For more information about using SSH or SCP to access the Boot2Docker VM, see the README at [Boot2Docker repository](https://github.com/boot2docker/boot2docker). Thanks to Chris Jones whose [blog](http://viget.com/extend/how-to-use-docker-on-os-x-the-missing-guide) inspired me to redo this page. Continue with the [Docker User Guide](/userguide). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/oracle.md ================================================ # Oracle Linux 6 and 7 You do not require an Oracle Linux Support subscription to install Docker on Oracle Linux. *For Oracle Linux customers with an active support subscription:* Docker is available in either the `ol6_x86_64_addons` or `ol7_x86_64_addons` channel for Oracle Linux 6 and Oracle Linux 7 on the [Unbreakable Linux Network (ULN)](https://linux.oracle.com). *For Oracle Linux users without an active support subscription:* Docker is available in the appropriate `ol6_addons` or `ol7_addons` repository on [Oracle Public Yum](http://public-yum.oracle.com). Docker requires the use of the Unbreakable Enterprise Kernel Release 3 (3.8.13) or higher on Oracle Linux. This kernel supports the Docker btrfs storage engine on both Oracle Linux 6 and 7. Due to current Docker limitations, Docker is only able to run only on the x86_64 architecture. ## To enable the *addons* channel via the Unbreakable Linux Network: 1. Enable either the *ol6\_x86\_64\_addons* or *ol7\_x86\_64\_addons* channel via the ULN web interface. Consult the [Unbreakable Linux Network User's Guide](http://docs.oracle.com/cd/E52668_01/E39381/html/index.html) for documentation on subscribing to channels. ## To enable the *addons* repository via Oracle Public Yum: The latest release of Oracle Linux 6 and 7 are automatically configured to use the Oracle Public Yum repositories during installation. However, the *addons* repository is not enabled by default. To enable the *addons* repository: 1. Edit either `/etc/yum.repos.d/public-yum-ol6.repo` or `/etc/yum.repos.d/public-yum-ol7.repo` and set `enabled=1` in the `[ol6_addons]` or the `[ol7_addons]` stanza. ## Installation 1. Ensure the appropriate *addons* channel or repository has been enabled. 2. Use yum to install the Docker package: $ sudo yum install docker ## Starting Docker 1. Now that it's installed, start the Docker daemon: 1. On Oracle Linux 6: $ sudo service docker start 2. On Oracle Linux 7: $ sudo systemctl start docker.service 2. If you want the Docker daemon to start automatically at boot: 1. On Oracle Linux 6: $ sudo chkconfig docker on 2. On Oracle Linux 7: $ sudo systemctl enable docker.service **Done!** ## Custom daemon options If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our systemd article to learn how to [customize your systemd Docker daemon options](/articles/systemd/). ## Using the btrfs storage engine Docker on Oracle Linux 6 and 7 supports the use of the btrfs storage engine. Before enabling btrfs support, ensure that `/var/lib/docker` is stored on a btrfs-based filesystem. Review [Chapter 5](http://docs.oracle.com/cd/E37670_01/E37355/html/ol_btrfs.html) of the [Oracle Linux Administrator's Solution Guide](http://docs.oracle.com/cd/E37670_01/E37355/html/index.html) for details on how to create and mount btrfs filesystems. To enable btrfs support on Oracle Linux: 1. Ensure that `/var/lib/docker` is on a btrfs filesystem. 1. Edit `/etc/sysconfig/docker` and add `-s btrfs` to the `OTHER_ARGS` field. 2. Restart the Docker daemon: You can now continue with the [Docker User Guide](/userguide/). ## Uninstallation To uninstall the Docker package: $ sudo yum -y remove docker The above command will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ## Known issues ### Docker unmounts btrfs filesystem on shutdown If you're running Docker using the btrfs storage engine and you stop the Docker service, it will unmount the btrfs filesystem during the shutdown process. You should ensure the filesystem is mounted properly prior to restarting the Docker service. On Oracle Linux 7, you can use a `systemd.mount` definition and modify the Docker `systemd.service` to depend on the btrfs mount defined in systemd. ### SElinux support on Oracle Linux 7 SElinux must be set to `Permissive` or `Disabled` in `/etc/sysconfig/selinux` to use the btrfs storage engine on Oracle Linux 7. ## Further issues? If you have a current Basic or Premier Support Subscription for Oracle Linux, you can report any issues you have with the installation of Docker via a Service Request at [My Oracle Support](http://support.oracle.com). If you do not have an Oracle Linux Support Subscription, you can use the [Oracle Linux Forum](https://community.oracle.com/community/server_%26_storage_systems/linux/oracle_linux) for community-based support. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/rackspace.md ================================================ # Rackspace Cloud Installing Docker on Ubuntu provided by Rackspace is pretty straightforward, and you should mostly be able to follow the [*Ubuntu*](../ubuntulinux/#ubuntu-linux) installation guide. **However, there is one caveat:** If you are using any Linux not already shipping with the 3.8 kernel you will need to install it. And this is a little more difficult on Rackspace. Rackspace boots their servers using grub's `menu.lst` and does not like non `virtual` packages (e.g., Xen compatible) kernels there, although they do work. This results in `update-grub` not having the expected result, and you will need to set the kernel manually. **Do not attempt this on a production machine!** # update apt $ apt-get update # install the new kernel $ apt-get install linux-generic-lts-raring Great, now you have the kernel installed in `/boot/`, next you need to make it boot next time. # find the exact names $ find /boot/ -name '*3.8*' # this should return some results Now you need to manually edit `/boot/grub/menu.lst`, you will find a section at the bottom with the existing options. Copy the top one and substitute the new kernel into that. Make sure the new kernel is on top, and double check the kernel and initrd lines point to the right files. Take special care to double check the kernel and initrd entries. # now edit /boot/grub/menu.lst $ vi /boot/grub/menu.lst It will probably look something like this: ## ## End Default Options ## title Ubuntu 12.04.2 LTS, kernel 3.8.x generic root (hd0) kernel /boot/vmlinuz-3.8.0-19-generic root=/dev/xvda1 ro quiet splash console=hvc0 initrd /boot/initrd.img-3.8.0-19-generic title Ubuntu 12.04.2 LTS, kernel 3.2.0-38-virtual root (hd0) kernel /boot/vmlinuz-3.2.0-38-virtual root=/dev/xvda1 ro quiet splash console=hvc0 initrd /boot/initrd.img-3.2.0-38-virtual title Ubuntu 12.04.2 LTS, kernel 3.2.0-38-virtual (recovery mode) root (hd0) kernel /boot/vmlinuz-3.2.0-38-virtual root=/dev/xvda1 ro quiet splash single initrd /boot/initrd.img-3.2.0-38-virtual Reboot the server (either via command line or console) # reboot Verify the kernel was updated $ uname -a # Linux docker-12-04 3.8.0-19-generic #30~precise1-Ubuntu SMP Wed May 1 22:26:36 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux # nice! 3.8. Now you can finish with the [*Ubuntu*](../ubuntulinux/#ubuntu-linux) instructions. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/rhel.md ================================================ # Red Hat Enterprise Linux Docker is supported on the following versions of RHEL: - Red Hat Enterprise Linux 7 This page instructs you to install using Docker-managed release packages and installation mechanisms. Using these packages ensures you get the latest release of Docker. If you wish to install using Red Hat-managed packages, consult your Red Hat release documentation for information on Red Hat's Docker support. ## Prerequisites Docker requires a 64-bit installation regardless of your Red Hat version. Docker requires that your kernel must be 3.10 at minimum, which Red Hat 7 runs. To check your current kernel version, open a terminal and use `uname -r` to display your kernel version: $ uname -r 3.10.0-229.el7.x86_64 Finally, is it recommended that you fully update your system. Please keep in mind that your system should be fully patched to fix any potential kernel bugs. Any reported kernel bugs may have already been fixed on the latest kernel packages. ## Install You use the same installation procedure for all versions of Red Hat Enterprise, only the package you install differs. There are two packages to choose from:
Version Package name
7.X

https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.centos.x86_64.rpm

https://get.docker.com/rpm/1.7.1/centos-7/SRPMS/docker-engine-1.7.1-1.el7.centos.src.rpm

Installation procedure: 1. Log into your machine as a user with `sudo` or `root` privileges. 2. Download the Docker RPM to the current directory. $ curl -O -sSL https://get.docker.com/rpm/1.7.1/centos-7/RPMS/x86_64/docker-engine-1.7.1-1.el7.x86_64.rpm 3. Use `yum` to install the package. $ sudo yum localinstall --nogpgcheck docker-engine-1.7.1-1.el7.x86_64.rpm 5. Start the Docker daemon. $ sudo service docker start 6. Verify `docker` is installed correctly. $ sudo docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from hello-world a8219747be10: Pull complete 91c95931e552: Already exists hello-world:latest: The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security. Digest: sha256:aa03e5d0d5553b4c3473e89c8619cf79df368babd18681cf5daeb82aab55838d Status: Downloaded newer image for hello-world:latest Hello from Docker. This message shows that your installation appears to be working correctly. To generate this message, Docker took the following steps: 1. The Docker client contacted the Docker daemon. 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (Assuming it was not already locally available.) 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash For more examples and ideas, visit: http://docs.docker.com/userguide/ ## Create a docker group The `docker` daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user `root` and other users can access it with `sudo`. For this reason, `docker` daemon always runs as the `root` user. To avoid having to use `sudo` when you use the `docker` command, create a Unix group called `docker` and add users to it. When the `docker` daemon starts, it makes the ownership of the Unix socket read/writable by the `docker` group. >**Warning**: The `docker` group is equivalent to the `root` user; For details >on how this impacts security in your system, see [*Docker Daemon Attack >Surface*](/articles/security/#docker-daemon-attack-surface) for details. To create the `docker` group and add your user: 1. Log into your machine as a user with `sudo` or `root` privileges. 2. Create the `docker` group and add your user. `sudo usermod -aG docker your_username` 3. Log out and log back in. This ensures your user is running with the correct permissions. 4. Verify your work by running `docker` without `sudo`. $ docker run hello-world ## Start the docker daemon at boot To ensure Docker starts when you boot your system, do the following: $ sudo chkconfig docker on If you need to add an HTTP Proxy, set a different directory or partition for the Docker runtime files, or make other customizations, read our Systemd article to learn how to [customize your Systemd Docker daemon options](/articles/systemd/). ## Uninstall You can uninstall the Docker software with `yum`. 1. List the package you have installed. $ yum list installed | grep docker yum list installed | grep docker docker-engine.x86_64 1.7.1-0.1.el7 @/docker-engine-1.7.1-0.1.el7.x86_64 2. Remove the package. $ sudo yum -y remove docker-engine.x86_64 This command does not remove images, containers, volumes, or user created configuration files on your host. 3. To delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker 4. Locate and delete any user-created configuration files. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/softlayer.md ================================================ # IBM SoftLayer 1. Create an [IBM SoftLayer account]( https://www.softlayer.com/cloud-servers/). 2. Log in to the [SoftLayer Customer Portal]( https://control.softlayer.com/). 3. From the *Devices* menu select [*Device List*](https://control.softlayer.com/devices) 4. Click *Order Devices* on the top right of the window below the menu bar. 5. Under *Virtual Server* click [*Hourly*](https://manage.softlayer.com/Sales/orderHourlyComputingInstance) 6. Create a new *SoftLayer Virtual Server Instance* (VSI) using the default values for all the fields and choose: - The desired location for *Datacenter* - *Ubuntu Linux 12.04 LTS Precise Pangolin - Minimal Install (64 bit)* for *Operating System*. 7. Click the *Continue Your Order* button at the bottom right. 8. Fill out VSI *hostname* and *domain*. 9. Insert the required *User Metadata* and place the order. 10. Then continue with the [*Ubuntu*](../ubuntulinux/#ubuntu-linux) instructions. ## What next? Continue with the [User Guide](/userguide/). ================================================ FILE: vendor/github.com/docker/docker/docs/installation/ubuntulinux.md ================================================ # Ubuntu Docker is supported on these Ubuntu operating systems: - Ubuntu Trusty 14.04 (LTS) - Ubuntu Precise 12.04 (LTS) - Ubuntu Saucy 13.10 This page instructs you to install using Docker-managed release packages and installation mechanisms. Using these packages ensures you get the latest release of Docker. If you wish to install using Ubuntu-managed packages, consult your Ubuntu documentation. ## Prerequisites Docker requires a 64-bit installation regardless of your Ubuntu version. Additionally, your kernel must be 3.10 at minimum. The latest 3.10 minor version or a newer maintained version are also acceptable. Kernels older than 3.10 lack some of the features required to run Docker containers. These older versions are known to have bugs which cause data loss and frequently panic under certain conditions. To check your current kernel version, open a terminal and use `uname -r` to display your kernel version: $ uname -r 3.11.0-15-generic >**Caution** Some Ubuntu OS versions **require a version higher than 3.10** to >run Docker, see the prerequisites on this page that apply to your Ubuntu >version. ### For Trusty 14.04 There are no prerequisites for this version. ### For Precise 12.04 (LTS) For Ubuntu Precise, Docker requires the 3.13 kernel version. If your kernel version is older than 3.13, you must upgrade it. Refer to this table to see which packages are required for your environment:
linux-image-generic-lts-trusty Generic Linux kernel image. This kernel has AUFS built in. This is required to run Docker.
linux-headers-generic-lts-trusty Allows packages such as ZFS and VirtualBox guest additions which depend on them. If you didn't install the headers for your existing kernel, then you can skip these headers for the"trusty" kernel. If you're unsure, you should include this package for safety.
xserver-xorg-lts-trusty Optional in non-graphical environments without Unity/Xorg. Required when running Docker on machine with a graphical environment.

To learn more about the reasons for these packages, read the installation instructions for backported kernels, specifically the LTS Enablement Stack — refer to note 5 under each version.

libgl1-mesa-glx-lts-trusty
  To upgrade your kernel and install the additional packages, do the following: 1. Open a terminal on your Ubuntu host. 2. Update your package manager. $ sudo apt-get update 3. Install both the required and optional packages. $ sudo apt-get install linux-image-generic-lts-trusty Depending on your environment, you may install more as described in the preceding table. 4. Reboot your host. $ sudo reboot 5. After your system reboots, go ahead and [install Docker](#installing-docker-on-ubuntu). ### For Saucy 13.10 (64 bit) Docker uses AUFS as the default storage backend. If you don't have this prerequisite installed, Docker's installation process adds it. ## Installation Make sure you have installed the prerequisites for your Ubuntu version. Then, install Docker using the following: 1. Log into your Ubuntu installation as a user with `sudo` privileges. 2. Verify that you have `wget` installed. $ which wget If `wget` isn't installed, install it after updating your manager: $ sudo apt-get update $ sudo apt-get install wget 3. Get the latest Docker package. $ wget -qO- https://get.docker.com/ | sh The system prompts you for your `sudo` password. Then, it downloads and installs Docker and its dependencies. >**Note**: If your company is behind a filtering proxy, you may find that the >`apt-key` >command fails for the Docker repo during installation. To work around this, >add the key directly using the following: > > $ wget -qO- https://get.docker.com/gpg | sudo apt-key add - 4. Verify `docker` is installed correctly. $ sudo docker run hello-world This command downloads a test image and runs it in a container. ## Optional configurations for Docker on Ubuntu This section contains optional procedures for configuring your Ubuntu to work better with Docker. * [Create a docker group](#create-a-docker-group) * [Adjust memory and swap accounting](#adjust-memory-and-swap-accounting) * [Enable UFW forwarding](#enable-ufw-forwarding) * [Configure a DNS server for use by Docker](#configure-a-dns-server-for-docker) ### Create a Docker group The `docker` daemon binds to a Unix socket instead of a TCP port. By default that Unix socket is owned by the user `root` and other users can access it with `sudo`. For this reason, `docker` daemon always runs as the `root` user. To avoid having to use `sudo` when you use the `docker` command, create a Unix group called `docker` and add users to it. When the `docker` daemon starts, it makes the ownership of the Unix socket read/writable by the `docker` group. >**Warning**: The `docker` group is equivalent to the `root` user; For details >on how this impacts security in your system, see [*Docker Daemon Attack >Surface*](/articles/security/#docker-daemon-attack-surface) for details. To create the `docker` group and add your user: 1. Log into Ubuntu as a user with `sudo` privileges. This procedure assumes you log in as the `ubuntu` user. 3. Create the `docker` group and add your user. $ sudo usermod -aG docker ubuntu 3. Log out and log back in. This ensures your user is running with the correct permissions. 4. Verify your work by running `docker` without `sudo`. $ docker run hello-world If this fails with a message similar to this: Cannot connect to the Docker daemon. Is 'docker -d' running on this host? Check that the `DOCKER_HOST` environment variable is not set for your shell. If it is, unset it. ### Adjust memory and swap accounting When users run Docker, they may see these messages when working with an image: WARNING: Your kernel does not support cgroup swap limit. WARNING: Your kernel does not support swap limit capabilities. Limitation discarded. To prevent these messages, enable memory and swap accounting on your system. To enable these on system using GNU GRUB (GNU GRand Unified Bootloader), do the following. 1. Log into Ubuntu as a user with `sudo` privileges. 2. Edit the `/etc/default/grub` file. 3. Set the `GRUB_CMDLINE_LINUX` value as follows: GRUB_CMDLINE_LINUX="cgroup_enable=memory swapaccount=1" 4. Save and close the file. 5. Update GRUB. $ sudo update-grub 6. Reboot your system. ### Enable UFW forwarding If you use [UFW (Uncomplicated Firewall)](https://help.ubuntu.com/community/UFW) on the same host as you run Docker, you'll need to do additional configuration. Docker uses a bridge to manage container networking. By default, UFW drops all forwarding traffic. As a result, for Docker to run when UFW is enabled, you must set UFW's forwarding policy appropriately. Also, UFW's default set of rules denies all incoming traffic. If you want to be able to reach your containers from another host then you should also allow incoming connections on the Docker port (default `2375`). To configure UFW and allow incoming connections on the Docker port: 1. Log into Ubuntu as a user with `sudo` privileges. 2. Verify that UFW is installed and enabled. $ sudo ufw status 3. Open the `/etc/default/ufw` file for editing. $ sudo nano /etc/default/ufw 4. Set the `DEFAULT_FORWARD_POLICY` policy to: DEFAULT_FORWARD_POLICY="ACCEPT" 5. Save and close the file. 6. Reload UFW to use the new setting. $ sudo ufw reload 7. Allow incoming connections on the Docker port. $ sudo ufw allow 2375/tcp ### Configure a DNS server for use by Docker Systems that run Ubuntu or an Ubuntu derivative on the desktop typically use `127.0.0.1` as the default `nameserver` in `/etc/resolv.conf` file. The NetworkManager also sets up `dnsmasq` to use the real DNS servers of the connection and sets up `nameserver 127.0.0.1` in /`etc/resolv.conf`. When starting containers on desktop machines with these configurations, Docker users see this warning: WARNING: Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : [8.8.8.8 8.8.4.4] The warning occurs because Docker containers can't use the local DNS nameserver. Instead, Docker defaults to using an external nameserver. To avoid this warning, you can specify a DNS server for use by Docker containers. Or, you can disable `dnsmasq` in NetworkManager. Though, disabling `dnsmasq` might make DNS resolution slower on some networks. To specify a DNS server for use by Docker: 1. Log into Ubuntu as a user with `sudo` privileges. 2. Open the `/etc/default/docker` file for editing. $ sudo nano /etc/default/docker 3. Add a setting for Docker. DOCKER_OPTS="--dns 8.8.8.8" Replace `8.8.8.8` with a local DNS server such as `192.168.1.1`. You can also specify multiple DNS servers. Separated them with spaces, for example: --dns 8.8.8.8 --dns 192.168.1.1 >**Warning**: If you're doing this on a laptop which connects to various >networks, make sure to choose a public DNS server. 4. Save and close the file. 5. Restart the Docker daemon. $ sudo restart docker     **Or, as an alternative to the previous procedure,** disable `dnsmasq` in NetworkManager (this might slow your network). 1. Open the `/etc/NetworkManager/NetworkManager.conf` file for editing. $ sudo nano /etc/NetworkManager/NetworkManager.conf 2. Comment out the `dns=dsnmasq` line: dns=dnsmasq 3. Save and close the file. 4. Restart both the NetworkManager and Docker. $ sudo restart network-manager $ sudo restart docker ## Upgrade Docker To install the latest version of Docker with `wget`: $ wget -qO- https://get.docker.com/ | sh ## Uninstallation To uninstall the Docker package: $ sudo apt-get purge lxc-docker To uninstall the Docker package and dependencies that are no longer needed: $ sudo apt-get autoremove --purge lxc-docker The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command: $ rm -rf /var/lib/docker You must delete the user created configuration files manually. ================================================ FILE: vendor/github.com/docker/docker/docs/installation/windows.md ================================================ # Windows > **Note:** > Docker has been tested on Windows 7 and 8.1; it may also run on older versions. > Your processor needs to support hardware virtualization. The Docker Engine uses Linux-specific kernel features, so to run it on Windows we need to use a lightweight virtual machine (VM). You use the **Windows Docker Client** to control the virtualized Docker Engine to build, run, and manage Docker containers. To make this process easier, we've designed a helper application called [Boot2Docker](https://github.com/boot2docker/boot2docker) which creates a Linux virtual machine on Windows to run Docker on a Linux operating system. Although you will be using Windows Docker client, the docker engine hosting the containers will still be running on Linux. Until the Docker engine for Windows is developed, you can launch only Linux containers from your Windows machine. ![Windows Architecture Diagram](/installation/images/win_docker_host.svg) ## Demonstration ## Installation 1. Download the latest release of the [Docker for Windows Installer](https://github.com/boot2docker/windows-installer/releases/latest). 2. Run the installer, which will install Docker Client for Windows, VirtualBox, Git for Windows (MSYS-git), the boot2docker Linux ISO, and the Boot2Docker management tool. ![](/installation/images/windows-installer.png) 3. Run the **Boot2Docker Start** shortcut from your Desktop or “Program Files → Boot2Docker for Windows”. The Start script will ask you to enter an ssh key passphrase - the simplest (but least secure) is to just hit [Enter]. 4. The **Boot2Docker Start** will start a unix shell already configured to manage Docker running inside the virtual machine. Run `docker version` to see if it is working correctly: ![](/installation/images/windows-boot2docker-start.png) ## Running Docker > **Note:** if you are using a remote Docker daemon, such as Boot2Docker, > then _do not_ type the `sudo` before the `docker` commands shown in the > documentation's examples. **Boot2Docker Start** will automatically start a shell with environment variables correctly set so you can start using Docker right away: Let's try the `hello-world` example image. Run $ docker run hello-world This should download the very small `hello-world` image and print a `Hello from Docker.` message. ## Using Docker from Windows Command Line Prompt (cmd.exe) Launch a Windows Command Line Prompt (cmd.exe). Boot2Docker command requires `ssh.exe` to be in the PATH, therefore we need to include `bin` folder of the Git installation (which has ssh.exe) to the `%PATH%` environment variable by running: set PATH=%PATH%;"c:\Program Files (x86)\Git\bin" and then we can run the `boot2docker start` command to start the Boot2Docker VM. (Run `boot2docker init` command if you get an error saying machine does not exist.) Then copy the instructions for cmd.exe to set the environment variables to your console window and you are ready to run docker commands such as `docker ps`: ![](/installation/images/windows-boot2docker-cmd.png) ## Using Docker from PowerShell Launch a PowerShell window, then add `ssh.exe` to your PATH: $Env:Path = "${Env:Path};c:\Program Files (x86)\Git\bin" and after running the `boot2docker start` command it will print PowerShell commands to set the environment variables to connect to the Docker daemon running inside the VM. Run these commands and you are ready to run docker commands such as `docker ps`: ![](/installation/images/windows-boot2docker-powershell.png) > NOTE: You can alternatively run `boot2docker shellinit | Invoke-Expression` > command to set the environment variables instead of copying and pasting on > PowerShell. # Further Details The Boot2Docker management tool provides several commands: $ boot2docker Usage: boot2docker.exe [] {help|init|up|ssh|save|down|poweroff|reset|restart|config|status|info|ip|shellinit|delete|download|upgrade|version} [] ## Upgrading 1. Download the latest release of the [Docker for Windows Installer]( https://github.com/boot2docker/windows-installer/releases/latest) 2. Run the installer, which will update the Boot2Docker management tool. 3. To upgrade your existing virtual machine, open a terminal and run: boot2docker stop boot2docker download boot2docker start ## Container port redirection If you are curious, the username for the boot2docker default user is `docker` and the password is `tcuser`. The latest version of `boot2docker` sets up a host only network adaptor which provides access to the container's ports. If you run a container with an exposed port: docker run --rm -i -t -p 80:80 nginx Then you should be able to access that nginx server using the IP address reported to you using: boot2docker ip Typically, it is 192.168.59.103, but it could get changed by VirtualBox's DHCP implementation. For further information or to report issues, please see the [Boot2Docker site](http://boot2docker.io) ## Login with PUTTY instead of using the CMD Boot2Docker generates and uses the public/private key pair in your `%USERPROFILE%\.ssh` directory so to log in you need to use the private key from this same directory. The private key needs to be converted into the format PuTTY uses. You can do this with [puttygen](http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html): - Open `puttygen.exe` and load ("File"->"Load" menu) the private key from `%USERPROFILE%\.ssh\id_boot2docker` - then click: "Save Private Key". - Then use the saved file to login with PuTTY using `docker@127.0.0.1:2022`. ## Uninstallation You can uninstall Boot2Docker using Window's standard process for removing programs. This process does not remove the `docker-install.exe` file. You must delete that file yourself. ## References If you have Docker hosts running and if you don't wish to do a Boot2Docker installation, you can install the docker.exe using unofficial Windows package manager Chocolately. For information on how to do this, see [Docker package on Chocolatey](http://chocolatey.org/packages/docker). ================================================ FILE: vendor/github.com/docker/docker/docs/introduction/understanding-docker.md ================================================ # Understand the architecture **What is Docker?** Docker is an open platform for developing, shipping, and running applications. Docker is designed to deliver your applications faster. With Docker you can separate your applications from your infrastructure AND treat your infrastructure like a managed application. Docker helps you ship code faster, test faster, deploy faster, and shorten the cycle between writing code and running code. Docker does this by combining a lightweight container virtualization platform with workflows and tooling that help you manage and deploy your applications. At its core, Docker provides a way to run almost any application securely isolated in a container. The isolation and security allow you to run many containers simultaneously on your host. The lightweight nature of containers, which run without the extra load of a hypervisor, means you can get more out of your hardware. Surrounding the container virtualization are tooling and a platform which can help you in several ways: * getting your applications (and supporting components) into Docker containers * distributing and shipping those containers to your teams for further development and testing * deploying those applications to your production environment, whether it be in a local data center or the Cloud. ## What can I use Docker for? *Faster delivery of your applications* Docker is perfect for helping you with the development lifecycle. Docker allows your developers to develop on local containers that contain your applications and services. It can then integrate into a continuous integration and deployment workflow. For example, your developers write code locally and share their development stack via Docker with their colleagues. When they are ready, they push their code and the stack they are developing onto a test environment and execute any required tests. From the testing environment, you can then push the Docker images into production and deploy your code. *Deploying and scaling more easily* Docker's container-based platform allows for highly portable workloads. Docker containers can run on a developer's local host, on physical or virtual machines in a data center, or in the Cloud. Docker's portability and lightweight nature also make dynamically managing workloads easy. You can use Docker to quickly scale up or tear down applications and services. Docker's speed means that scaling can be near real time. *Achieving higher density and running more workloads* Docker is lightweight and fast. It provides a viable, cost-effective alternative to hypervisor-based virtual machines. This is especially useful in high density environments: for example, building your own Cloud or Platform-as-a-Service. But it is also useful for small and medium deployments where you want to get more out of the resources you have. ## What are the major Docker components? Docker has two major components: * Docker: the open source container virtualization platform. * [Docker Hub](https://hub.docker.com): our Software-as-a-Service platform for sharing and managing Docker containers. > **Note:** Docker is licensed under the open source Apache 2.0 license. ## What is Docker's architecture? Docker uses a client-server architecture. The Docker *client* talks to the Docker *daemon*, which does the heavy lifting of building, running, and distributing your Docker containers. Both the Docker client and the daemon *can* run on the same system, or you can connect a Docker client to a remote Docker daemon. The Docker client and daemon communicate via sockets or through a RESTful API. ![Docker Architecture Diagram](/article-img/architecture.svg) ### The Docker daemon As shown in the diagram above, the Docker daemon runs on a host machine. The user does not directly interact with the daemon, but instead through the Docker client. ### The Docker client The Docker client, in the form of the `docker` binary, is the primary user interface to Docker. It accepts commands from the user and communicates back and forth with a Docker daemon. ### Inside Docker To understand Docker's internals, you need to know about three components: * Docker images. * Docker registries. * Docker containers. #### Docker images A Docker image is a read-only template. For example, an image could contain an Ubuntu operating system with Apache and your web application installed. Images are used to create Docker containers. Docker provides a simple way to build new images or update existing images, or you can download Docker images that other people have already created. Docker images are the **build** component of Docker. #### Docker registries Docker registries hold images. These are public or private stores from which you upload or download images. The public Docker registry is called [Docker Hub](http://hub.docker.com). It provides a huge collection of existing images for your use. These can be images you create yourself or you can use images that others have previously created. Docker registries are the **distribution** component of Docker. #### Docker containers Docker containers are similar to a directory. A Docker container holds everything that is needed for an application to run. Each container is created from a Docker image. Docker containers can be run, started, stopped, moved, and deleted. Each container is an isolated and secure application platform. Docker containers are the **run** component of Docker. ## So how does Docker work? So far, we've learned that: 1. You can build Docker images that hold your applications. 2. You can create Docker containers from those Docker images to run your applications. 3. You can share those Docker images via [Docker Hub](https://hub.docker.com) or your own registry. Let's look at how these elements combine together to make Docker work. ### How does a Docker image work? We've already seen that Docker images are read-only templates from which Docker containers are launched. Each image consists of a series of layers. Docker makes use of [union file systems](http://en.wikipedia.org/wiki/UnionFS) to combine these layers into a single image. Union file systems allow files and directories of separate file systems, known as branches, to be transparently overlaid, forming a single coherent file system. One of the reasons Docker is so lightweight is because of these layers. When you change a Docker image—for example, update an application to a new version— a new layer gets built. Thus, rather than replacing the whole image or entirely rebuilding, as you may do with a virtual machine, only that layer is added or updated. Now you don't need to distribute a whole new image, just the update, making distributing Docker images faster and simpler. Every image starts from a base image, for example `ubuntu`, a base Ubuntu image, or `fedora`, a base Fedora image. You can also use images of your own as the basis for a new image, for example if you have a base Apache image you could use this as the base of all your web application images. > **Note:** Docker usually gets these base images from > [Docker Hub](https://hub.docker.com). Docker images are then built from these base images using a simple, descriptive set of steps we call *instructions*. Each instruction creates a new layer in our image. Instructions include actions like: * Run a command. * Add a file or directory. * Create an environment variable. * What process to run when launching a container from this image. These instructions are stored in a file called a `Dockerfile`. Docker reads this `Dockerfile` when you request a build of an image, executes the instructions, and returns a final image. ### How does a Docker registry work? The Docker registry is the store for your Docker images. Once you build a Docker image you can *push* it to a public registry [Docker Hub](https://hub.docker.com) or to your own registry running behind your firewall. Using the Docker client, you can search for already published images and then pull them down to your Docker host to build containers from them. [Docker Hub](https://hub.docker.com) provides both public and private storage for images. Public storage is searchable and can be downloaded by anyone. Private storage is excluded from search results and only you and your users can pull images down and use them to build containers. You can [sign up for a storage plan here](https://hub.docker.com/plans). ### How does a container work? A container consists of an operating system, user-added files, and meta-data. As we've seen, each container is built from an image. That image tells Docker what the container holds, what process to run when the container is launched, and a variety of other configuration data. The Docker image is read-only. When Docker runs a container from an image, it adds a read-write layer on top of the image (using a union file system as we saw earlier) in which your application can then run. ### What happens when you run a container? Either by using the `docker` binary or via the API, the Docker client tells the Docker daemon to run a container. $ docker run -i -t ubuntu /bin/bash Let's break down this command. The Docker client is launched using the `docker` binary with the `run` option telling it to launch a new container. The bare minimum the Docker client needs to tell the Docker daemon to run the container is: * What Docker image to build the container from, here `ubuntu`, a base Ubuntu image; * The command you want to run inside the container when it is launched, here `/bin/bash`, to start the Bash shell inside the new container. So what happens under the hood when we run this command? In order, Docker does the following: - **Pulls the `ubuntu` image:** Docker checks for the presence of the `ubuntu` image and, if it doesn't exist locally on the host, then Docker downloads it from [Docker Hub](https://hub.docker.com). If the image already exists, then Docker uses it for the new container. - **Creates a new container:** Once Docker has the image, it uses it to create a container. - **Allocates a filesystem and mounts a read-write _layer_:** The container is created in the file system and a read-write layer is added to the image. - **Allocates a network / bridge interface:** Creates a network interface that allows the Docker container to talk to the local host. - **Sets up an IP address:** Finds and attaches an available IP address from a pool. - **Executes a process that you specify:** Runs your application, and; - **Captures and provides application output:** Connects and logs standard input, outputs and errors for you to see how your application is running. You now have a running container! From here you can manage your container, interact with your application and then, when finished, stop and remove your container. ## The underlying technology Docker is written in Go and makes use of several Linux kernel features to deliver the functionality we've seen. ### Namespaces Docker takes advantage of a technology called `namespaces` to provide the isolated workspace we call the *container*. When you run a container, Docker creates a set of *namespaces* for that container. This provides a layer of isolation: each aspect of a container runs in its own namespace and does not have access outside it. Some of the namespaces that Docker uses are: - **The `pid` namespace:** Used for process isolation (PID: Process ID). - **The `net` namespace:** Used for managing network interfaces (NET: Networking). - **The `ipc` namespace:** Used for managing access to IPC resources (IPC: InterProcess Communication). - **The `mnt` namespace:** Used for managing mount-points (MNT: Mount). - **The `uts` namespace:** Used for isolating kernel and version identifiers. (UTS: Unix Timesharing System). ### Control groups Docker also makes use of another technology called `cgroups` or control groups. A key to running applications in isolation is to have them only use the resources you want. This ensures containers are good multi-tenant citizens on a host. Control groups allow Docker to share available hardware resources to containers and, if required, set up limits and constraints. For example, limiting the memory available to a specific container. ### Union file systems Union file systems, or UnionFS, are file systems that operate by creating layers, making them very lightweight and fast. Docker uses union file systems to provide the building blocks for containers. Docker can make use of several union file system variants including: AUFS, btrfs, vfs, and DeviceMapper. ### Container format Docker combines these components into a wrapper we call a container format. The default container format is called `libcontainer`. Docker also supports traditional Linux containers using [LXC](https://linuxcontainers.org/). In the future, Docker may support other container formats, for example, by integrating with BSD Jails or Solaris Zones. ## Next steps ### Installing Docker Visit the [installation section](/installation/#installation). ### The Docker user guide [Learn Docker in depth](/userguide/). ================================================ FILE: vendor/github.com/docker/docker/docs/misc/faq.md ================================================ # Frequently Asked Questions (FAQ) If you don't see your question here, feel free to submit new ones to . Or, you can fork [the repo](https://github.com/docker/docker) and contribute them yourself by editing the documentation sources. ### How much does Docker cost? Docker is 100% free. It is open source, so you can use it without paying. ### What open source license are you using? We are using the Apache License Version 2.0, see it here: [https://github.com/docker/docker/blob/master/LICENSE]( https://github.com/docker/docker/blob/master/LICENSE) ### Does Docker run on Mac OS X or Windows? Docker currently runs only on Linux, but you can use VirtualBox to run Docker in a virtual machine on your box, and get the best of both worlds. Check out the [*Mac OS X*](../installation/mac/#macosx) and [*Microsoft Windows*](../installation/windows/#windows) installation guides. The small Linux distribution boot2docker can be run inside virtual machines on these two operating systems. > **Note:** if you are using a remote Docker daemon, such as Boot2Docker, > then _do not_ type the `sudo` before the `docker` commands shown in the > documentation's examples. ### How do containers compare to virtual machines? They are complementary. VMs are best used to allocate chunks of hardware resources. Containers operate at the process level, which makes them very lightweight and perfect as a unit of software delivery. ### What does Docker add to just plain LXC? Docker is not a replacement for LXC. "LXC" refers to capabilities of the Linux kernel (specifically namespaces and control groups) which allow sandboxing processes from one another, and controlling their resource allocations. On top of this low-level foundation of kernel features, Docker offers a high-level tool with several powerful functionalities: - *Portable deployment across machines.* Docker defines a format for bundling an application and all its dependencies into a single object which can be transferred to any Docker-enabled machine, and executed there with the guarantee that the execution environment exposed to the application will be the same. LXC implements process sandboxing, which is an important pre-requisite for portable deployment, but that alone is not enough for portable deployment. If you sent me a copy of your application installed in a custom LXC configuration, it would almost certainly not run on my machine the way it does on yours, because it is tied to your machine's specific configuration: networking, storage, logging, distro, etc. Docker defines an abstraction for these machine-specific settings, so that the exact same Docker container can run - unchanged - on many different machines, with many different configurations. - *Application-centric.* Docker is optimized for the deployment of applications, as opposed to machines. This is reflected in its API, user interface, design philosophy and documentation. By contrast, the `lxc` helper scripts focus on containers as lightweight machines - basically servers that boot faster and need less RAM. We think there's more to containers than just that. - *Automatic build.* Docker includes [*a tool for developers to automatically assemble a container from their source code*](../reference/builder/#dockerbuilder), with full control over application dependencies, build tools, packaging etc. They are free to use `make`, `maven`, `chef`, `puppet`, `salt,` Debian packages, RPMs, source tarballs, or any combination of the above, regardless of the configuration of the machines. - *Versioning.* Docker includes git-like capabilities for tracking successive versions of a container, inspecting the diff between versions, committing new versions, rolling back etc. The history also includes how a container was assembled and by whom, so you get full traceability from the production server all the way back to the upstream developer. Docker also implements incremental uploads and downloads, similar to `git pull`, so new versions of a container can be transferred by only sending diffs. - *Component re-use.* Any container can be used as a [*"base image"*]( ../terms/image/#base-image-def) to create more specialized components. This can be done manually or as part of an automated build. For example you can prepare the ideal Python environment, and use it as a base for 10 different applications. Your ideal Postgresql setup can be re-used for all your future projects. And so on. - *Sharing.* Docker has access to a [public registry](https://hub.docker.com) where thousands of people have uploaded useful containers: anything from Redis, CouchDB, Postgres to IRC bouncers to Rails app servers to Hadoop to base images for various Linux distros. The [*registry*](../reference/api/registry_index_spec/#registryindexspec) also includes an official "standard library" of useful containers maintained by the Docker team. The registry itself is open-source, so anyone can deploy their own registry to store and transfer private containers, for internal server deployments for example. - *Tool ecosystem.* Docker defines an API for automating and customizing the creation and deployment of containers. There are a huge number of tools integrating with Docker to extend its capabilities. PaaS-like deployment (Dokku, Deis, Flynn), multi-node orchestration (Maestro, Salt, Mesos, Openstack Nova), management dashboards (docker-ui, Openstack Horizon, Shipyard), configuration management (Chef, Puppet), continuous integration (Jenkins, Strider, Travis), etc. Docker is rapidly establishing itself as the standard for container-based tooling. ### What is different between a Docker container and a VM? There's a great StackOverflow answer [showing the differences]( http://stackoverflow.com/questions/16047306/how-is-docker-io-different-from-a-normal-virtual-machine). ### Do I lose my data when the container exits? Not at all! Any data that your application writes to disk gets preserved in its container until you explicitly delete the container. The file system for the container persists even after the container halts. ### How far do Docker containers scale? Some of the largest server farms in the world today are based on containers. Large web deployments like Google and Twitter, and platform providers such as Heroku and dotCloud all run on container technology, at a scale of hundreds of thousands or even millions of containers running in parallel. ### How do I connect Docker containers? Currently the recommended way to link containers is via the link primitive. You can see details of how to [work with links here](/userguide/dockerlinks). Also useful for more flexible service portability is the [Ambassador linking pattern](/articles/ambassador_pattern_linking/). ### How do I run more than one process in a Docker container? Any capable process supervisor such as [http://supervisord.org/]( http://supervisord.org/), runit, s6, or daemontools can do the trick. Docker will start up the process management daemon which will then fork to run additional processes. As long as the processor manager daemon continues to run, the container will continue to as well. You can see a more substantial example [that uses supervisord here](/articles/using_supervisord/). ### What platforms does Docker run on? Linux: - Ubuntu 12.04, 13.04 et al - Fedora 19/20+ - RHEL 6.5+ - CentOS 6+ - Gentoo - ArchLinux - openSUSE 12.3+ - CRUX 3.0+ Cloud: - Amazon EC2 - Google Compute Engine - Rackspace ### How do I report a security issue with Docker? You can learn about the project's security policy [here](https://www.docker.com/security/) and report security issues to this [mailbox](mailto:security@docker.com). ### Why do I need to sign my commits to Docker with the DCO? Please read [our blog post]( http://blog.docker.com/2014/01/docker-code-contributions-require-developer-certificate-of-origin/) on the introduction of the DCO. ### When building an image, should I prefer system libraries or bundled ones? *This is a summary of a discussion on the [docker-dev mailing list]( https://groups.google.com/forum/#!topic/docker-dev/L2RBSPDu1L0).* Virtually all programs depend on third-party libraries. Most frequently, they will use dynamic linking and some kind of package dependency, so that when multiple programs need the same library, it is installed only once. Some programs, however, will bundle their third-party libraries, because they rely on very specific versions of those libraries. For instance, Node.js bundles OpenSSL; MongoDB bundles V8 and Boost (among others). When creating a Docker image, is it better to use the bundled libraries, or should you build those programs so that they use the default system libraries instead? The key point about system libraries is not about saving disk or memory space. It is about security. All major distributions handle security seriously, by having dedicated security teams, following up closely with published vulnerabilities, and disclosing advisories themselves. (Look at the [Debian Security Information](https://www.debian.org/security/) for an example of those procedures.) Upstream developers, however, do not always implement similar practices. Before setting up a Docker image to compile a program from source, if you want to use bundled libraries, you should check if the upstream authors provide a convenient way to announce security vulnerabilities, and if they update their bundled libraries in a timely manner. If they don't, you are exposing yourself (and the users of your image) to security vulnerabilities. Likewise, before using packages built by others, you should check if the channels providing those packages implement similar security best practices. Downloading and installing an "all-in-one" .deb or .rpm sounds great at first, except if you have no way to figure out that it contains a copy of the OpenSSL library vulnerable to the [Heartbleed](http://heartbleed.com/) bug. ### Why is `DEBIAN_FRONTEND=noninteractive` discouraged in Dockerfiles? When building Docker images on Debian and Ubuntu you may have seen errors like: unable to initialize frontend: Dialog These errors don't stop the image from being built but inform you that the installation process tried to open a dialog box, but was unable to. Generally, these errors are safe to ignore. Some people circumvent these errors by changing the `DEBIAN_FRONTEND` environment variable inside the Dockerfile using: ENV DEBIAN_FRONTEND=noninteractive This prevents the installer from opening dialog boxes during installation which stops the errors. While this may sound like a good idea, it *may* have side effects. The `DEBIAN_FRONTEND` environment variable will be inherited by all images and containers built from your image, effectively changing their behavior. People using those images will run into problems when installing software interactively, because installers will not show any dialog boxes. Because of this, and because setting `DEBIAN_FRONTEND` to `noninteractive` is mainly a 'cosmetic' change, we *discourage* changing it. If you *really* need to change its setting, make sure to change it back to its [default value](https://www.debian.org/releases/stable/i386/ch05s03.html.en) afterwards. ### Why do I get `Connection reset by peer` when making a request to a service running in a container? Typically, this message is returned if the service is already bound to your localhost. As a result, requests coming to the container from outside are dropped. To correct this problem, change the service's configuration on your localhost so that the service accepts requests from all IPs. If you aren't sure how to do this, check the documentation for your OS. ### Where can I find more answers? You can find more answers on: - [Docker user mailinglist](https://groups.google.com/d/forum/docker-user) - [Docker developer mailinglist](https://groups.google.com/d/forum/docker-dev) - [IRC, docker on freenode](irc://chat.freenode.net#docker) - [GitHub](https://github.com/docker/docker) - [Ask questions on Stackoverflow](http://stackoverflow.com/search?q=docker) - [Join the conversation on Twitter](http://twitter.com/docker) Looking for something else to read? Checkout the [User Guide](/userguide/). ================================================ FILE: vendor/github.com/docker/docker/docs/misc/index.md ================================================ # About Docker **Develop, Ship and Run Any Application, Anywhere** [**Docker**](https://www.docker.com) is a platform for developers and sysadmins to develop, ship, and run applications. Docker lets you quickly assemble applications from components and eliminates the friction that can come when shipping code. Docker lets you get your code tested and deployed into production as fast as possible. Docker consists of: * The Docker Engine - our lightweight and powerful open source container virtualization technology combined with a work flow for building and containerizing your applications. * [Docker Hub](https://hub.docker.com) - our SaaS service for sharing and managing your application stacks. ## Why Docker? *Faster delivery of your applications* * We want your environment to work better. Docker containers, and the work flow that comes with them, help your developers, sysadmins, QA folks, and release engineers work together to get your code into production and make it useful. We've created a standard container format that lets developers care about their applications inside containers while sysadmins and operators can work on running the container in your deployment. This separation of duties streamlines and simplifies the management and deployment of code. * We make it easy to build new containers, enable rapid iteration of your applications, and increase the visibility of changes. This helps everyone in your organization understand how an application works and how it is built. * Docker containers are lightweight and fast! Containers have sub-second launch times, reducing the cycle time of development, testing, and deployment. *Deploy and scale more easily* * Docker containers run (almost) everywhere. You can deploy containers on desktops, physical servers, virtual machines, into data centers, and up to public and private clouds. * Since Docker runs on so many platforms, it's easy to move your applications around. You can easily move an application from a testing environment into the cloud and back whenever you need. * Docker's lightweight containers also make scaling up and down fast and easy. You can quickly launch more containers when needed and then shut them down easily when they're no longer needed. *Get higher density and run more workloads* * Docker containers don't need a hypervisor, so you can pack more of them onto your hosts. This means you get more value out of every server and can potentially reduce what you spend on equipment and licenses. *Faster deployment makes for easier management* * As Docker speeds up your work flow, it gets easier to make lots of small changes instead of huge, big bang updates. Smaller changes mean reduced risk and more uptime. ## About this guide The [Understanding Docker section](introduction/understanding-docker.md) will help you: - See how Docker works at a high level - Understand the architecture of Docker - Discover Docker's features; - See how Docker compares to virtual machines - See some common use cases. ### Installation guides The [installation section](/installation/#installation) will show you how to install Docker on a variety of platforms. ### Docker user guide To learn about Docker in more detail and to answer questions about usage and implementation, check out the [Docker User Guide](/userguide/). ## Release notes A summary of the changes in each release in the current series can now be found on the separate [Release Notes page](/release-notes/) ## Licensing Docker is licensed under the Apache License, Version 2.0. See [LICENSE](https://github.com/docker/docker/blob/master/LICENSE) for the full license text. ================================================ FILE: vendor/github.com/docker/docker/docs/misc/release-notes.md ================================================ # Release notes version 1.6.0 (2015-04-16) You can view release notes for earlier version of Docker by selecting the desired version from the drop-down list at the top right of this page. For the formal release announcement, see [the Docker blog](https://blog.docker.com/2015/04/docker-release-1-6/). ## Docker Engine 1.6.0 features For a complete list of engine patches, fixes, and other improvements, see the [merge PR on GitHub](https://github.com/docker/docker/pull/11635). You'll also find [a changelog in the project repository](https://github.com/docker/docker/blob/master/CHANGELOG.md). ## Docker Engine 1.6.0 features For a complete list of engine patches, fixes, and other improvements, see the [merge PR on GitHub](https://github.com/docker/docker/pull/11635). You'll also find [a changelog in the project repository](https://github.com/docker/docker/blob/master/CHANGELOG.md). | Feature | Description | |------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Container and Image Labels | Labels allow you to attach user-defined metadata to containers and images that can be used by your tools. For additional information on using labels, see [Apply custom metadata](https://docs.docker.com/userguide/labels-custom-metadata/#add-labels-to-images-the-label-instruction) in the documentation. | | Windows Client preview | The Windows Client can be used just like the Mac OS X client is today with a remote host. Our testing infrastructure was scaled out to accommodate Windows Client testing on every PR to the Engine. See the Azure blog for [details on using this new client](http://azure.microsoft.com/blog/2015/04/16/docker-client-for-windows-is-now-available). | | Logging drivers | The new logging driver follows the exec driver and storage driver concepts already available in Engine today. There is a new option `--log-driver` to `docker run` command. See the `run` reference for a [description on how to use this option](https://docs.docker.com/reference/run/#logging-drivers-log-driver). | | Image digests | When you pull, build, or run images, you specify them in the form `namespace/repository:tag`, or even just `repository`. In this release, you are now able to pull, run, build and refer to images by a new content addressable identifier called a “digest” with the syntax `namespace/repo@digest`. See the the command line reference for [examples of using the digest](https://docs.docker.com/reference/commandline/cli/#listing-image-digests). | | Custom cgroups | Containers are made from a combination of namespaces, capabilities, and cgroups. Docker already supports custom namespaces and capabilities. Additionally, in this release we’ve added support for custom cgroups. Using the `--cgroup-parent` flag, you can pass a specific `cgroup` to run a container in. See [the command line reference for more information](https://docs.docker.com/reference/commandline/cli/#create). | | Ulimits | You can now specify the default `ulimit` settings for all containers when configuring the daemon. For example:`docker -d --default-ulimit nproc=1024:2048` See [Default Ulimits](https://docs.docker.com/reference/commandline/cli/#default-ulimits) in this documentation. | | Commit and import Dockerfile | You can now make changes to images on the fly without having to re-build the entire image. The feature `commit --change` and `import --change` allows you to apply standard changes to a new image. These are expressed in the Dockerfile syntax and used to modify the image. For details on how to use these, see the [commit](https://docs.docker.com/reference/commandline/cli/#commit) and [import](https://docs.docker.com/reference/commandline/cli/#import). | ### Known issues in Engine This section lists significant known issues present in Docker as of release date. For an exhaustive list of issues, see [the issues list on the project repository](https://github.com/docker/docker/issues/). * *Unexpected File Permissions in Containers* An idiosyncrasy in AUFS prevented permissions from propagating predictably between upper and lower layers. This caused issues with accessing private keys, database instances, etc. This issue was closed in this release: [GitHub Issue 783](https://github.com/docker/docker/issues/783). * *Docker Hub incompatible with Safari 8* Docker Hub had multiple issues displaying on Safari 8, the default browser for OS X 10.10 (Yosemite). Most notably, changes in the way Safari handled cookies means that the user was repeatedly logged out. Recently, Safari fixed the bug that was causing all the issues. If you upgrade to Safari 8.0.5 which was just released last week and see if that fixes your issues. You might have to flush your cookies if it doesn't work right away. For more information, see the [Docker forum post](https://forums.docker.com/t/new-safari-in-yosemite-issue/300). ## Docker Registry 2.0 features This release includes Registry 2.0. The Docker Registry is a central server for pushing and pulling images. In this release, it was completely rewritten in Go around a new set of distribution APIs - **Webhook notifications**: You can now configure the Registry to send Webhooks when images are pushed. Spin off a CI build, send a notification to IRC – whatever you want! Included in the documentation is a detailed [notification specification](https://docs.docker.com/registry/notifications/). - **Native TLS support**: This release makes it easier to secure a registry with TLS. This documentation includes [expanded examples of secure deployments](https://docs.docker.com/registry/deploying/). - **New Distribution APIs**: This release includes an expanded set of new distribution APIs. You can read the [detailed specification here](https://docs.docker.com/registry/spec/api/). ## Docker Compose 1.2 For a complete list of compose patches, fixes, and other improvements, see the [changelog in the project repository](https://github.com/docker/compose/blob/master/CHANGES.md). The project also makes a [set of release notes](https://github.com/docker/compose/releases/tag/1.2.0) on the project. - **extends**: You can use `extends` to share configuration between services with the keyword “extends”. With extends, you can refer to a service defined elsewhere and include its configuration in a locally-defined service, while also adding or overriding configuration as necessary. The documentation describes [how to use extends in your configuration](https://docs.docker.com/compose/extends/#extending-services-in- compose). - **Relative directory handling may cause breaking change**: Compose now treats directories passed to build, filenames passed to `env_file` and volume host paths passed to volumes as relative to the configuration file's directory. Previously, they were treated as relative to the directory where you were running `docker-compose`. In the majority of cases, the location of the configuration file and where you ran `docker-compose` were the same directory. Now, you can use the `-f|--file` argument to specify a configuration file in another directory. ## Docker Swarm 0.2 You'll find the [release for download on GitHub](https://github.com/docker/swarm/releases/tag/v0.2.0) and [the documentation here](https://docs.docker.com/swarm/). This release includes the following features: - **Spread strategy**: A new strategy for scheduling containers on your cluster which evenly spreads them over available nodes. - **More Docker commands supported**: More progress has been made towards supporting the complete Docker API, such as pulling and inspecting images. - **Clustering drivers**: There are not any third-party drivers yet, but the first steps have been made towards making a pluggable driver interface that will make it possible to use Swarm with clustering systems such as Mesos. ## Docker Machine 0.2 Pre-release You'll find the [release for download on GitHub](https://github.com/docker/machine/releases) and [the documentation here](https://docs.docker.com/machine/). For a complete list of machine changes see [the changelog in the project repository](https://github.com/docker/machine/blob/master/CHANGES.md#020-2015-03 -22). - **Cleaner driver interface**: It is now much easier to write drivers for providers. - **More reliable and consistent provisioning**: Provisioning servers is now handled centrally by Machine instead of letting each driver individually do it. - **Regenerate TLS certificates**: A new command has been added to regenerate a host’s TLS certificates for good security practice and for if a host’s IP address changes. ## Docker Hub Enterprise & Commercially Supported Docker Engine See the [DHE and CS Docker Engine release notes](docker-hub-enterprise/release-notes.md). ================================================ FILE: vendor/github.com/docker/docker/docs/misc/search.md ================================================ # Search *Please activate JavaScript to enable the search functionality.* ## How To Search From here you can search these documents. Enter your search words into the box below and click "search". Note that the search function will automatically search for all of the words. Pages containing fewer words won't appear in the result list. ================================================ FILE: vendor/github.com/docker/docker/docs/project/advanced-contributing.md ================================================ # Advanced contributing In this section, you learn about the more advanced contributions you can make. They are advanced because they have a more involved workflow or require greater programming experience. Don't be scared off though, if you like to stretch and challenge yourself, this is the place for you. This section gives generalized instructions for advanced contributions. You'll read about the workflow but there are not specific descriptions of commands. Your goal should be to understand the processes described. At this point, you should have read and worked through the earlier parts of the project contributor guide. You should also have made at least one project contribution. ## Refactor or cleanup proposal A refactor or cleanup proposal changes Docker's internal structure without altering the external behavior. To make this type of proposal: 1. Fork `docker/docker`. 2. Make your changes in a feature branch. 3. Sync and rebase with `master` as you work. 3. Run the full test suite. 4. Submit your code through a pull request (PR). The PR's title should have the format: **Cleanup:** _short title_ If your changes required logic changes, note that in your request. 5. Work through Docker's review process until merge. ## Design proposal A design proposal solves a problem or adds a feature to the Docker software. The process for submitting design proposals requires two pull requests, one for the design and one for the implementation. ![Simple process](/project/images/proposal.png) The important thing to notice is that both the design pull request and the implementation pull request go through a review. In other words, there is considerable time commitment in a design proposal; so, you might want to pair with someone on design work. The following provides greater detail on the process: 1. Come up with an idea. Ideas usually come from limitations users feel working with a product. So, take some time to really use Docker. Try it on different platforms; explore how it works with different web applications. Go to some community events and find out what other users want. 2. Review existing issues and proposals to make sure no other user is proposing a similar idea. The design proposals are all online in our GitHub pull requests. 3. Talk to the community about your idea. We have lots of community forums where you can get feedback on your idea. Float your idea in a forum or two to get some commentary going on it. 4. Fork `docker/docker` and clone the repo to your local host. 5. Create a new Markdown file in the area you wish to change. For example, if you want to redesign our daemon create a new file under the `daemon/` folder. 6. Name the file descriptively, for example `redesign-daemon-proposal.md`. 7. Write a proposal for your change into the file. This is a Markdown file that describes your idea. Your proposal should include information like: * Why is this change needed or what are the use cases? * What are the requirements this change should meet? * What are some ways to design/implement this feature? * Which design/implementation do you think is best and why? * What are the risks or limitations of your proposal? This is your chance to convince people your idea is sound. 8. Submit your proposal in a pull request to `docker/docker`. The title should have the format: **Proposal:** _short title_ The body of the pull request should include a brief summary of your change and then say something like "_See the file for a complete description_". 9. Refine your proposal through review. The maintainers and the community review your proposal. You'll need to answer questions and sometimes explain or defend your approach. This is chance for everyone to both teach and learn. 10. Pull request accepted. Your request may also be rejected. Not every idea is a good fit for Docker. Let's assume though your proposal succeeded. 11. Implement your idea. Implementation uses all the standard practices of any contribution. * fork `docker/docker` * create a feature branch * sync frequently back to master * test as you go and full test before a PR If you run into issues, the community is there to help. 12. When you have a complete implementation, submit a pull request back to `docker/docker`. 13. Review and iterate on your code. If you are making a large code change, you can expect greater scrutiny during this phase. 14. Acceptance and merge! ## About the advanced process Docker is a large project. Our core team gets a great many design proposals. Design proposal discussions can span days, weeks, and longer. The number of comments can reach the 100s. In that situation, following the discussion flow and the decisions reached is crucial. Making a pull request with a design proposal simplifies this process: * you can leave comments on specific design proposal line * replies around line are easy to track * as a proposal changes and is updated, pages reset as line items resolve * GitHub maintains the entire history While proposals in pull requests do not end up merged into a master repository, they provide a convenient tool for managing the design process. ================================================ FILE: vendor/github.com/docker/docker/docs/project/coding-style.md ================================================ # Coding style checklist This checklist summarizes the material you experienced working through [make a code contribution](/project/make-a-contribution) and [advanced contributing](/project/advanced-contributing). The checklist applies to both program code and documentation code. ## Change and commit code * Fork the `docker/docker` repository. * Make changes on your fork in a feature branch. Name your branch `XXXX-something` where `XXXX` is the issue number you are working on. * Run `gofmt -s -w file.go` on each changed file before committing your changes. Most editors have plug-ins that do this automatically. * Update the documentation when creating or modifying features. * Commits that fix or close an issue should reference them in the commit message `Closes #XXXX` or `Fixes #XXXX`. Mentions help by automatically closing the issue on a merge. * After every commit, run the test suite and ensure it is passing. * Sync and rebase frequently as you code to keep up with `docker` master. * Set your `git` signature and make sure you sign each commit. * Do not add yourself to the `AUTHORS` file. This file is autogenerated from the Git history. ## Tests and testing * Submit unit tests for your changes. * Make use of the builtin Go test framework built. * Use existing Docker test files (`name_test.go`) for inspiration. * Run the full test suite on your branch before submitting a pull request. * Run `make docs` to build the documentation and then check it locally. * Use an online grammar checker or similar to test you documentation changes for clarity, concision, and correctness. ## Pull requests * Sync and cleanly rebase on top of Docker's `master` without multiple branches mixed into the PR. * Before the pull request, squash your commits into logical units of work using `git rebase -i` and `git push -f`. * Include documentation changes in the same commit so that a revert would remove all traces of the feature or fix. * Reference each issue in your pull request description (`#XXXX`) ## Respond to pull requests reviews * Docker maintainers use LGTM (**l**ooks-**g**ood-**t**o-**m**e) in PR comments to indicate acceptance. * Code review comments may be added to your pull request. Discuss, then make the suggested modifications and push additional commits to your feature branch. * Incorporate changes on your feature branch and push to your fork. This automatically updates your open pull request. * Post a comment after pushing to alert reviewers to PR changes; pushing a change does not send notifications. * A change requires LGTMs from an absolute majority maintainers of an affected component. For example, if you change `docs/` and `registry/` code, an absolute majority of the `docs/` and the `registry/` maintainers must approve your PR. ## Merges after pull requests * After a merge, [a master build](https://master.dockerproject.org/) is available almost immediately. * If you made a documentation change, you can see it at [docs.master.dockerproject.org](http://docs.master.dockerproject.org/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/create-pr.md ================================================ # Create a pull request (PR) A pull request (PR) sends your changes to the Docker maintainers for review. You create a pull request on GitHub. A pull request "pulls" changes from your forked repository into the `docker/docker` repository. You can see the list of active pull requests to Docker on GitHub. ## Check your work Before you create a pull request, check your work. 1. In a terminal window, go to the root of your `docker-fork` repository. $ cd ~/repos/docker-fork 2. Checkout your feature branch. $ git checkout 11038-fix-rhel-link Switched to branch '11038-fix-rhel-link' 3. Run the full test suite on your branch. $ make test All the tests should pass. If they don't, find out why and correct the situation. 4. Optionally, if modified the documentation, build the documentation: $ make docs 5. Commit and push any changes that result from your checks. ## Rebase your branch Always rebase and squash your commits before making a pull request. 1. Checkout your feature branch in your local `docker-fork` repository. This is the branch associated with your request. 2. Fetch any last minute changes from `docker/docker`. $ git fetch upstream master From github.com:docker/docker * branch master -> FETCH_HEAD 3. Start an interactive rebase. $ git rebase -i upstream/master 4. Rebase opens an editor with a list of commits. pick 1a79f55 Tweak some of the other text for grammar pick 53e4983 Fix a link pick 3ce07bb Add a new line about RHEL 5. Replace the `pick` keyword with `squash` on all but the first commit. pick 1a79f55 Tweak some of the other text for grammar squash 53e4983 Fix a link squash 3ce07bb Add a new line about RHEL After you save the changes and quit from the editor, git starts the rebase, reporting the progress along the way. Sometimes your changes can conflict with the work of others. If git encounters a conflict, it stops the rebase, and prints guidance for how to correct the conflict. 6. Edit and save your commit message. $ git commit -s Make sure your message includes your signature. 7. Force push any changes to your fork on GitHub. $ git push -f origin 11038-fix-rhel-link ## Create a PR on GitHub You create and manage PRs on GitHub: 1. Open your browser to your fork on GitHub. You should see the latest activity from your branch. ![Latest commits](/project/images/latest_commits.png) 2. Click "Compare & pull request." The system displays the pull request dialog. ![PR dialog](/project/images/to_from_pr.png) The pull request compares your changes to the `master` branch on the `docker/docker` repository. 3. Edit the dialog's description and add a reference to the issue you are fixing. GitHub helps you out by searching for the issue as you type. ![Fixes issue](/project/images/fixes_num.png) 4. Scroll down and verify the PR contains the commits and changes you expect. For example, is the file count correct? Are the changes in the files what you expect? ![Commits](/project/images/commits_expected.png) 5. Press "Create pull request". The system creates the request and opens it for you in the `docker/docker` repository. ![Pull request made](/project/images/pull_request_made.png) ## Where to go next Congratulations, you've created your first pull request to Docker. The next step is for you learn how to [participate in your PR's review](/project/review-pr/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/doc-style.md ================================================ # Docker documentation: style & grammar conventions ## Style standards Over time, different publishing communities have written standards for the style and grammar they prefer in their publications. These standards are called [style guides](http://en.wikipedia.org/wiki/Style_guide). Generally, Docker’s documentation uses the standards described in the [Associated Press's (AP) style guide](http://en.wikipedia.org/wiki/AP_Stylebook). If a question about syntactical, grammatical, or lexical practice comes up, refer to the AP guide first. If you don’t have a copy of (or online subscription to) the AP guide, you can almost always find an answer to a specific question by searching the web. If you can’t find an answer, please ask a [maintainer](https://github.com/docker/docker/blob/master/docs/MAINTAINERS) and we will find the answer. That said, please don't get too hung up on using correct style. We'd rather have you submit good information that doesn't conform to the guide than no information at all. Docker's tech writers are always happy to help you with the prose, and we promise not to judge or use a red pen! > **Note:** > The documentation is written with paragraphs wrapped at 80 column lines to > make it easier for terminal use. You can probably set up your favorite text > editor to do this automatically for you. ### Prose style In general, try to write simple, declarative prose. We prefer short, single-clause sentences and brief three-to-five sentence paragraphs. Try to choose vocabulary that is straightforward and precise. Avoid creating new terms, using obscure terms or, in particular, using a lot of jargon. For example, use "use" instead of leveraging "leverage". That said, don’t feel like you have to write for localization or for English-as-a-second-language (ESL) speakers specifically. Assume you are writing for an ordinary speaker of English with a basic university education. If your prose is simple, clear, and straightforward it will translate readily. One way to think about this is to assume Docker’s users are generally university educated and read at at least a "16th" grade level (meaning they have a university degree). You can use a [readability tester](https://readability-score.com/) to help guide your judgement. For example, the readability score for the phrase "Containers should be ephemeral" is around the 13th grade level (first year at university), and so is acceptable. In all cases, we prefer clear, concise communication over stilted, formal language. Don't feel like you have to write documentation that "sounds like technical writing." ### Metaphor and figurative language One exception to the "don’t write directly for ESL" rule is to avoid the use of metaphor or other [figurative language](http://en.wikipedia.org/wiki/Literal_and_figurative_language) to describe things. There are too many cultural and social issues that can prevent a reader from correctly interpreting a metaphor. ## Specific conventions Below are some specific recommendations (and a few deviations) from AP style that we use in our docs. ### Contractions As long as your prose does not become too slangy or informal, it's perfectly acceptable to use contractions in our documentation. Make sure to use apostrophes correctly. ### Use of dashes in a sentence. Dashes refers to the en dash (–) and the em dash (—). Dashes can be used to separate parenthetical material. Usage Example: This is an example of a Docker client – which uses the Big Widget to run – and does x, y, and z. Use dashes cautiously and consider whether commas or parentheses would work just as well. We always emphasize short, succinct sentences. More info from the always handy [Grammar Girl site](http://www.quickanddirtytips.com/education/grammar/dashes-parentheses-and-commas). ### Pronouns It's okay to use first and second person pronouns, especially if it lets you avoid a passive construction. Specifically, always use "we" to refer to Docker and "you" to refer to the user. For example, "We built the `exec` command so you can resize a TTY session." That said, in general, try to write simple, imperative sentences that avoid the use of pronouns altogether. Say "Now, enter your SSH key" rather than "You can now enter your SSH key." As much as possible, avoid using gendered pronouns ("he" and "she", etc.). Either recast the sentence so the pronoun is not needed or, less preferably, use "they" instead. If you absolutely can't get around using a gendered pronoun, pick one and stick to it. Which one you choose is up to you. One common convention is to use the pronoun of the author's gender, but if you prefer to default to "he" or "she", that's fine too. ### Capitalization #### In general Only proper nouns should be capitalized in body text. In general, strive to be as strict as possible in applying this rule. Avoid using capitals for emphasis or to denote "specialness". The word "Docker" should always be capitalized when referring to either the company or the technology. The only exception is when the term appears in a code sample. #### Starting sentences Because code samples should always be written exactly as they would appear on-screen, you should avoid starting sentences with a code sample. #### In headings Headings take sentence capitalization, meaning that only the first letter is capitalized (and words that would normally be capitalized in a sentence, e.g., "Docker"). Do not use Title Case (i.e., capitalizing every word) for headings. Generally, we adhere to [AP style for titles](http://www.quickanddirtytips.com/education/grammar/capitalizing-titles). ### Periods We prefer one space after a period at the end of a sentence, not two. See [lists](#lists) below for how to punctuate list items. ### Abbreviations and acronyms * Exempli gratia (e.g.) and id est ( i.e.): these should always have periods and are always followed by a comma. * Acronyms are pluralized by simply adding "s", e.g., PCs, OSs. * On first use on a given page, the complete term should be used, with the abbreviation or acronym in parentheses. E.g., Red Hat Enterprise Linux (RHEL). The exception is common, non-technical acronyms like AKA or ASAP. Note that acronyms other than i.e. and e.g. are capitalized. * Other than "e.g." and "i.e." (as discussed above), acronyms do not take periods, PC not P.C. ### Lists When writing lists, keep the following in mind: Use bullets when the items being listed are independent of each other and the order of presentation is not important. Use numbers for steps that have to happen in order or if you have mentioned the list in introductory text. For example, if you wrote "There are three config settings available for SSL, as follows:", you would number each config setting in the subsequent list. In all lists, if an item is a complete sentence, it should end with a period. Otherwise, we prefer no terminal punctuation for list items. Each item in a list should start with a capital. ### Numbers Write out numbers in body text and titles from one to ten. From 11 on, use numerals. ### Notes Use notes sparingly and only to bring things to the reader's attention that are critical or otherwise deserving of being called out from the body text. Please format all notes as follows: > **Note:** > One line of note text > another line of note text ### Avoid excess use of "i.e." Minimize your use of "i.e.". It can add an unnecessary interpretive burden on the reader. Avoid writing "This is a thing, i.e., it is like this". Just say what it is: "This thing is …" ### Preferred usages #### Login vs. log in. A "login" is a noun (one word), as in "Enter your login". "Log in" is a compound verb (two words), as in "Log in to the terminal". ### Oxford comma One way in which we differ from AP style is that Docker’s docs use the [Oxford comma](http://en.wikipedia.org/wiki/Serial_comma) in all cases. That’s our position on this controversial topic, we won't change our mind, and that’s that! ### Code and UI text styling We require `code font` styling (monospace, sans-serif) for all text that refers to a command or other input or output from the CLI. This includes file paths (e.g., `/etc/hosts/docker.conf`). If you enclose text in backticks (`) markdown will style the text as code. Text from a CLI should be quoted verbatim, even if it contains errors or its style contradicts this guide. You can add "(sic)" after the quote to indicate the errors are in the quote and are not errors in our docs. Text taken from a GUI (e.g., menu text or button text) should appear in "double quotes". The text should take the exact same capitalisation, etc. as appears in the GUI. E.g., Click "Continue" to save the settings. Text that refers to a keyboard command or hotkey is capitalized (e.g., Ctrl-D). When writing CLI examples, give the user hints by making the examples resemble exactly what they see in their shell: * Indent shell examples by 4 spaces so they get rendered as code blocks. * Start typed commands with `$ ` (dollar space), so that they are easily differentiated from program output. * Program output has no prefix. * Comments begin with # (hash space). * In-container shell commands, begin with `$$ ` (dollar dollar space). Please test all code samples to ensure that they are correct and functional so that users can successfully cut-and-paste samples directly into the CLI. ## Pull requests The pull request (PR) process is in place so that we can ensure changes made to the docs are the best changes possible. A good PR will do some or all of the following: * Explain why the change is needed * Point out potential issues or questions * Ask for help from experts in the company or the community * Encourage feedback from core developers and others involved in creating the software being documented. Writing a PR that is singular in focus and has clear objectives will encourage all of the above. Done correctly, the process allows reviewers (maintainers and community members) to validate the claims of the documentation and identify potential problems in communication or presentation. ### Commit messages In order to write clear, useful commit messages, please follow these [recommendations](http://robots.thoughtbot.com/5-useful-tips-for-a-better-commit-message). ## Links For accessibility and usability reasons, avoid using phrases such as "click here" for link text. Recast your sentence so that the link text describes the content of the link, as we did in the ["Commit messages" section](#commit-messages) above. You can use relative links (../linkeditem) to link to other pages in Docker's documentation. ## Graphics When you need to add a graphic, try to make the file-size as small as possible. If you need help reducing file-size of a high-resolution image, feel free to contact us for help. Usually, graphics should go in the same directory as the .md file that references them, or in a subdirectory for images if one already exists. The preferred file format for graphics is PNG, but GIF and JPG are also acceptable. If you are referring to a specific part of the UI in an image, use call-outs (circles and arrows or lines) to highlight what you’re referring to. Line width for call-outs should not exceed five pixels. The preferred color for call-outs is red. Be sure to include descriptive alt-text for the graphic. This greatly helps users with accessibility issues. Lastly, be sure you have permission to use any included graphics. ================================================ FILE: vendor/github.com/docker/docker/docs/project/find-an-issue.md ================================================ # Find and claim an issue On this page, you choose what you want to work on. As a contributor you can work on whatever you want. If you are new to contributing, you should start by working with our known issues. ## Understand the issue types An existing issue is something reported by a Docker user. As issues come in, our maintainers triage them. Triage is its own topic. For now, it is important for you to know that triage includes ranking issues according to difficulty. Triaged issues have one of these labels:
Level Experience level guideline
exp/beginner You have made less than 10 contributions in your life time to any open source project.
exp/novice You have made more than 10 contributions to an open source project or at least 5 contributions to Docker.
exp/proficient You have made more than 5 contributions to Docker which amount to at least 200 code lines or 1000 documentation lines.
exp/expert You have made less than 20 commits to Docker which amount to 500-1000 code lines or 1000-3000 documentation lines.
exp/master You have made more than 20 commits to Docker and greater than 1000 code lines or 3000 documentation lines.
As the table states, these labels are meant as guidelines. You might have written a whole plugin for Docker in a personal project and never contributed to Docker. With that kind of experience, you could take on an exp/expert or exp/master level task. ## Claim a beginner or novice issue In this section, you find and claim an open documentation lines issue. 1. Go to the `docker/docker` repository. 2. Click on the "Issues" link. A list of the open issues appears. ![Open issues](/project/images/issue_list.png) 3. Look for the exp/beginner items on the list. 4. Click on the "labels" dropdown and select exp/beginner. The system filters to show only open exp/beginner issues. 5. Open an issue that interests you. The comments on the issues can tell you both the problem and the potential solution. 6. Make sure that no other user has chosen to work on the issue. We don't allow external contributors to assign issues to themselves. So, you need to read the comments to find if a user claimed the issue by leaving a `#dibs` comment on the issue. 7. When you find an open issue that both interests you and is unclaimed, add a `#dibs` comment. ![Easy issue](/project/images/easy_issue.png) This example uses issue 11038. Your issue # will be different depending on what you claimed. After a moment, Gordon the Docker bot, changes the issue status to claimed. 8. Make a note of the issue number; you'll need it later. ## Sync your fork and create a new branch If you have followed along in this guide, you forked the `docker/docker` repository. Maybe that was an hour ago or a few days ago. In any case, before you start working on your issue, sync your repository with the upstream `docker/docker` master. Syncing ensures your repository has the latest changes. To sync your repository: 1. Open a terminal on your local host. 2. Change directory to the `docker-fork` root. $ cd ~/repos/docker-fork 3. Checkout the master branch. $ git checkout master Switched to branch 'master' Your branch is up-to-date with 'origin/master'. Recall that `origin/master` is a branch on your remote GitHub repository. 4. Make sure you have the upstream remote `docker/docker` by listing them. $ git remote -v origin https://github.com/moxiegirl/docker.git (fetch) origin https://github.com/moxiegirl/docker.git (push) upstream https://github.com/docker/docker.git (fetch) upstream https://github.com/docker/docker.git (push) If the `upstream` is missing, add it. $ git remote add upstream https://github.com/docker/docker.git 5. Fetch all the changes from the `upstream master` branch. $ git fetch upstream master remote: Counting objects: 141, done. remote: Compressing objects: 100% (29/29), done. remote: Total 141 (delta 52), reused 46 (delta 46), pack-reused 66 Receiving objects: 100% (141/141), 112.43 KiB | 0 bytes/s, done. Resolving deltas: 100% (79/79), done. From github.com:docker/docker * branch master -> FETCH_HEAD This command says get all the changes from the `master` branch belonging to the `upstream` remote. 7. Rebase your local master with the `upstream/master`. $ git rebase upstream/master First, rewinding head to replay your work on top of it... Fast-forwarded master to upstream/master. This command applies all the commits from the upstream master to your local master. 8. Check the status of your local branch. $ git status On branch master Your branch is ahead of 'origin/master' by 38 commits. (use "git push" to publish your local commits) nothing to commit, working directory clean Your local repository now has all the changes from the `upstream` remote. You need to push the changes to your own remote fork which is `origin master`. 9. Push the rebased master to `origin master`. $ git push origin master Username for 'https://github.com': moxiegirl Password for 'https://moxiegirl@github.com': Counting objects: 223, done. Compressing objects: 100% (38/38), done. Writing objects: 100% (69/69), 8.76 KiB | 0 bytes/s, done. Total 69 (delta 53), reused 47 (delta 31) To https://github.com/moxiegirl/docker.git 8e107a9..5035fa1 master -> master 9. Create a new feature branch to work on your issue. Your branch name should have the format `XXXX-descriptive` where `XXXX` is the issue number you are working on. For example: $ git checkout -b 11038-fix-rhel-link Switched to a new branch '11038-fix-rhel-link' Your branch should be up-to-date with the `upstream/master`. Why? Because you branched off a freshly synced master. Let's check this anyway in the next step. 9. Rebase your branch from upstream/master. $ git rebase upstream/master Current branch 11038-fix-rhel-link is up to date. At this point, your local branch, your remote repository, and the Docker repository all have identical code. You are ready to make changes for your issue. ## Where to go next At this point, you know what you want to work on and you have a branch to do your work in. Go onto the next section to learn [how to work on your changes](/project/work-issue/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/get-help.md ================================================ # Where to chat or get help There are several communications channels you can use to chat with Docker community members and developers.
Internet Relay Chat (IRC)

IRC a direct line to our most knowledgeable Docker users. The #docker and #docker-dev group on irc.freenode.net. IRC was first created in 1988. So, it is a rich chat protocol but it can overwhelm new users. You can search our chat archives.

Read our IRC quickstart guide below for an easy way to get started.
Google Groups There are two groups. Docker-user is for people using Docker containers. The docker-dev group is for contributors and other people contributing to the Docker project.
Twitter You can follow Docker's twitter to get updates on our products. You can also tweet us questions or just share blogs or stories.
Stack Overflow Stack Overflow has over 7000K Docker questions listed. We regularly monitor Docker questions and so do many other knowledgeable Docker users.
## IRC Quickstart IRC can also be overwhelming for new users. This quickstart shows you the easiest way to connect to IRC. 1. In your browser open http://webchat.freenode.net ![Login screen](/project/images/irc_connect.png) 2. Fill out the form.
Nickname The short name you want to be known as in IRC.
Channels #docker
reCAPTCHA Use the value provided.
3. Click "Connect". The system connects you to chat. You'll see a lot of text. At the bottom of the display is a command line. Just above the command line the system asks you to register. ![Login screen](/project/images/irc_after_login.png) 4. In the command line, register your nickname. /msg NickServ REGISTER password youremail@example.com ![Login screen](/project/images/register_nic.png) The IRC system sends an email to the address you enter. The email contains instructions for completing your registration. 5. Open your mail client and look for the email. ![Login screen](/project/images/register_email.png) 6. Back in the browser, complete the registration according to the email. /msg NickServ VERIFY REGISTER moxiegirl_ acljtppywjnr 7. Join the `#docker` group using the following command. /j #docker You can also join the `#docker-dev` group. /j #docker-dev 8. To ask questions to the channel just type messages in the command line. ![Login screen](/project/images/irc_chat.png) 9. To quit, close the browser window. ### Tips and learning more about IRC Next time you return to log into chat, you'll need to re-enter your password on the command line using this command: /msg NickServ identify If you forget or lose your password see the FAQ on freenode.net to learn how to recover it. This quickstart was meant to get you up and into IRC very quickly. If you find IRC useful there is a lot more to learn. Drupal, another open source project, actually has written a lot of good documentation about using IRC for their project (thanks Drupal!). ================================================ FILE: vendor/github.com/docker/docker/docs/project/make-a-contribution.md ================================================ # Understand how to contribute Contributing is a process where you work with Docker maintainers and the community to improve Docker. The maintainers are experienced contributors who specialize in one or more Docker components. Maintainers play a big role in reviewing contributions. There is a formal process for contributing. We try to keep our contribution process simple so you'll want to contribute frequently. ## The basic contribution workflow In this guide, you work through Docker's basic contribution workflow by fixing a single *beginner* issue in the `docker/docker` repository. The workflow for fixing simple issues looks like this: ![Simple process](/project/images/existing_issue.png) All Docker repositories have code and documentation. You use this same workflow for either content type. For example, you can find and fix doc or code issues. Also, you can propose a new Docker feature or propose a new Docker tutorial. Some workflow stages do have slight differences for code or documentation contributions. When you reach that point in the flow, we make sure to tell you. ## Where to go next Now that you know a little about the contribution process, go to the next section to [find an issue you want to work on](/project/find-an-issue/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/review-pr.md ================================================ # Participate in the PR review Creating a pull request is nearly the end of the contribution process. At this point, your code is reviewed both by our continuous integration (CI) systems and by our maintainers. The CI system is an automated system. The maintainers are human beings that also work on Docker. You need to understand and work with both the "bots" and the "beings" to review your contribution. ## How we process your review First to review your pull request is Gordon. Gordon is fast. He checks your pull request (PR) for common problems like a missing signature. If Gordon finds a problem, he'll send an email through your GitHub user account: ![Gordon](/project/images/gordon.jpeg) Our build bot system starts building your changes while Gordon sends any emails. The build system double-checks your work by compiling your code with Docker's master code. Building includes running the same tests you ran locally. If you forgot to run tests or missed something in fixing problems, the automated build is our safety check. After Gordon and the bots, the "beings" review your work. Docker maintainers look at your pull request and comment on it. The shortest comment you might see is `LGTM` which means **l**ooks-**g**ood-**t**o-**m**e. If you get an `LGTM`, that is a good thing, you passed that review. For complex changes, maintainers may ask you questions or ask you to change something about your submission. All maintainer comments on a PR go to the email address associated with your GitHub account. Any GitHub user who "participates" in a PR receives an email to. Participating means creating or commenting on a PR. Our maintainers are very experienced Docker users and open source contributors. So, they value your time and will try to work efficiently with you by keeping their comments specific and brief. If they ask you to make a change, you'll need to update your pull request with additional changes. ## Update an existing pull request To update your existing pull request: 1. Checkout the PR branch in your local `docker-fork` repository. This is the branch associated with your request. 2. Change one or more files and then stage your changes. The command syntax is: git add 3. Commit the change. $ git commit --amend Git opens an editor containing your last commit message. 4. Adjust your last comment to reflect this new change. Added a new sentence per Anaud's suggestion Signed-off-by: Mary Anthony # Please enter the commit message for your changes. Lines starting # with '#' will be ignored, and an empty message aborts the commit. # On branch 11038-fix-rhel-link # Your branch is up-to-date with 'origin/11038-fix-rhel-link'. # # Changes to be committed: # modified: docs/installation/mac.md # modified: docs/installation/rhel.md 5. Force push the change to your origin. The command syntax is: git push -f origin 6. Open your browser to your pull request on GitHub. You should see your pull request now contains your newly pushed code. 7. Add a comment to your pull request. GitHub only notifies PR participants when you comment. For example, you can mention that you updated your PR. Your comment alerts the maintainers that you made an update. A change requires LGTMs from an absolute majority of an affected component's maintainers. For example, if you change `docs/` and `registry/` code, an absolute majority of the `docs/` and the `registry/` maintainers must approve your PR. Once you get approval, we merge your pull request into Docker's `master` code branch. ## After the merge It can take time to see a merged pull request in Docker's official release. A master build is available almost immediately though. Docker builds and updates its development binaries after each merge to `master`. 1. Browse to https://master.dockerproject.org/. 2. Look for the binary appropriate to your system. 3. Download and run the binary. You might want to run the binary in a container though. This will keep your local host environment clean. 4. View any documentation changes at docs.master.dockerproject.org. Once you've verified everything merged, feel free to delete your feature branch from your fork. For information on how to do this, see the GitHub help on deleting branches. ## Where to go next At this point, you have completed all the basic tasks in our contributors guide. If you enjoyed contributing, let us know by completing another beginner issue or two. We really appreciate the help. If you are very experienced and want to make a major change, go on to [learn about advanced contributing](/project/advanced-contributing). ================================================ FILE: vendor/github.com/docker/docker/docs/project/set-up-dev-env.md ================================================ # Work with a development container In this section, you learn to develop like a member of Docker's core team. The `docker` repository includes a `Dockerfile` at its root. This file defines Docker's development environment. The `Dockerfile` lists the environment's dependencies: system libraries and binaries, Go environment, Go dependencies, etc. Docker's development environment is itself, ultimately a Docker container. You use the `docker` repository and its `Dockerfile` to create a Docker image, run a Docker container, and develop code in the container. Docker itself builds, tests, and releases new Docker versions using this container. If you followed the procedures that set up Git for contributing, you should have a fork of the `docker/docker` repository. You also created a branch called `dry-run-test`. In this section, you continue working with your fork on this branch. ## Clean your host of Docker artifacts Docker developers run the latest stable release of the Docker software (with Boot2Docker if their machine is Mac OS X). They clean their local hosts of unnecessary Docker artifacts such as stopped containers or unused images. Cleaning unnecessary artifacts isn't strictly necessary, but it is good practice, so it is included here. To remove unnecessary artifacts, 1. Verify that you have no unnecessary containers running on your host. $ docker ps You should see something similar to the following:
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
There are no running containers on this host. If you have running but unused containers, stop and then remove them with the `docker stop` and `docker rm` commands. 2. Verify that your host has no dangling images. $ docker images You should see something similar to the following:
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
This host has no images. You may have one or more _dangling_ images. A dangling image is not used by a running container and is not an ancestor of another image on your system. A fast way to remove dangling containers is the following: $ docker rmi -f $(docker images -q -a -f dangling=true) This command uses `docker images` to list all images (`-a` flag) by numeric IDs (`-q` flag) and filter them to find dangling images (`-f dangling=true`). Then, the `docker rmi` command forcibly (`-f` flag) removes the resulting list. To remove just one image, use the `docker rmi ID` command. ## Build an image If you followed the last procedure, your host is clean of unnecessary images and containers. In this section, you build an image from the Docker development environment. 1. Open a terminal. Mac users, use `boot2docker status` to make sure Boot2Docker is running. You may need to run `eval "$(boot2docker shellinit)"` to initialize your shell environment. 3. Change into the root of your forked repository. $ cd ~/repos/docker-fork If you are following along with this guide, you created a `dry-run-test` branch when you set up Git for contributing. 4. Ensure you are on your `dry-run-test` branch. $ git checkout dry-run-test If you get a message that the branch doesn't exist, add the `-b` flag (git checkout -b dry-run-test) so the command both creates the branch and checks it out. 5. Compile your development environment container into an image. $ docker build -t dry-run-test . The `docker build` command returns informational message as it runs. The first build may take a few minutes to create an image. Using the instructions in the `Dockerfile`, the build may need to download source and other images. A successful build returns a final status message similar to the following: Successfully built 676815d59283 6. List your Docker images again. $ docker images You should see something similar to this:
REPOSTITORY TAG IMAGE ID CREATED VIRTUAL SIZE
dry-run-test latest 663fbee70028 About a minute ago
ubuntu trusty 2d24f826cb16 2 days ago 188.3 MB
ubuntu trusty-20150218.1 2d24f826cb16 2 days ago 188.3 MB
ubuntu 14.04 2d24f826cb16 2 days ago 188.3 MB
ubuntu 14.04.2 2d24f826cb16 2 days ago 188.3 MB
ubuntu latest 2d24f826cb16 2 days ago 188.3 MB
Locate your new `dry-run-test` image in the list. You should also see a number of `ubuntu` images. The build process creates these. They are the ancestors of your new Docker development image. When you next rebuild your image, the build process reuses these ancestors images if they exist. Keeping the ancestor images improves the build performance. When you rebuild the child image, the build process uses the local ancestors rather than retrieving them from the Hub. The build process gets new ancestors only if DockerHub has updated versions. ## Start a container and run a test At this point, you have created a new Docker development environment image. Now, you'll use this image to create a Docker container to develop in. Then, you'll build and run a `docker` binary in your container. 1. Open two additional terminals on your host. At this point, you'll have about three terminals open. ![Multiple terminals](/project/images/three_terms.png) Mac OS X users, make sure you run `eval "$(boot2docker shellinit)"` in any new terminals. 2. In a terminal, create a new container from your `dry-run-test` image. $ docker run --privileged --rm -ti dry-run-test /bin/bash root@5f8630b873fe:/go/src/github.com/docker/docker# The command creates a container from your `dry-run-test` image. It opens an interactive terminal (`-ti`) running a `/bin/bash` shell. The `--privileged` flag gives the container access to kernel features and device access. This flag allows you to run a container in a container. Finally, the `-rm` flag instructs Docker to remove the container when you exit the `/bin/bash` shell. The container includes the source of your image repository in the `/go/src/github.com/docker/docker` directory. Try listing the contents to verify they are the same as that of your `docker-fork` repo. ![List example](/project/images/list_example.png) 3. Investigate your container bit. If you do a `go version` you'll find the `go` language is part of the container. root@31ed86e9ddcf:/go/src/github.com/docker/docker# go version go version go1.4.2 linux/amd64 Similarly, if you do a `docker version` you find the container has no `docker` binary. root@31ed86e9ddcf:/go/src/github.com/docker/docker# docker version bash: docker: command not found You will create one in the next steps. 4. From the `/go/src/github.com/docker/docker` directory make a `docker` binary with the `make.sh` script. root@5f8630b873fe:/go/src/github.com/docker/docker# hack/make.sh binary You only call `hack/make.sh` to build a binary _inside_ a Docker development container as you are now. On your host, you'll use `make` commands (more about this later). As it makes the binary, the `make.sh` script reports the build's progress. When the command completes successfully, you should see the following output: ---> Making bundle: binary (in bundles/1.5.0-dev/binary) Created binary: /go/src/github.com/docker/docker/bundles/1.5.0-dev/binary/docker-1.5.0-dev 5. List all the contents of the `binary` directory. root@5f8630b873fe:/go/src/github.com/docker/docker# ls bundles/1.5.0-dev/binary/ docker docker-1.5.0-dev docker-1.5.0-dev.md5 docker-1.5.0-dev.sha256 You should see that `binary` directory, just as it sounds, contains the made binaries. 6. Copy the `docker` binary to the `/usr/bin` of your container. root@5f8630b873fe:/go/src/github.com/docker/docker# cp bundles/1.5.0-dev/binary/docker /usr/bin 7. Inside your container, check your Docker version. root@5f8630b873fe:/go/src/github.com/docker/docker# docker --version Docker version 1.5.0-dev, build 6e728fb Inside the container you are running a development version. This is the version on the current branch. It reflects the value of the `VERSION` file at the root of your `docker-fork` repository. 8. Start a `docker` daemon running inside your container. root@5f8630b873fe:/go/src/github.com/docker/docker# docker -dD The `-dD` flag starts the daemon in debug mode. You'll find this useful when debugging your code. 9. Bring up one of the terminals on your local host. 10. List your containers and look for the container running the `dry-run-test` image. $ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
474f07652525 dry-run-test:latest "hack/dind /bin/bash 14 minutes ago Up 14 minutes tender_shockley
In this example, the container's name is `tender_shockley`; yours will be different. 11. From the terminal, start another shell on your Docker development container. $ docker exec -it tender_shockley bash At this point, you have two terminals both with a shell open into your development container. One terminal is running a debug session. The other terminal is displaying a `bash` prompt. 12. At the prompt, test the Docker client by running the `hello-world` container. root@9337c96e017a:/go/src/github.com/docker/docker# docker run hello-world You should see the image load and return. Meanwhile, you can see the calls made via the debug session in your other terminal. ![List example](/project/images/three_running.png) ## Restart a container with your source At this point, you have experienced the "Docker inception" technique. That is, you have: * built a Docker image from the Docker repository * created and started a Docker development container from that image * built a Docker binary inside of your Docker development container * launched a `docker` daemon using your newly compiled binary * called the `docker` client to run a `hello-world` container inside your development container When you really get to developing code though, you'll want to iterate code changes and builds inside the container. For that you need to mount your local Docker repository source into your Docker container. Try that now. 1. If you haven't already, exit out of BASH shells in your running Docker container. If you have followed this guide exactly, exiting out your BASH shells stops the running container. You can use the `docker ps` command to verify the development container is stopped. All of your terminals should be at the local host prompt. 2. Choose a terminal and make sure you are in your `docker-fork` repository. $ pwd /Users/mary/go/src/github.com/moxiegirl/docker-fork Your location will be different because it reflects your environment. 3. Create a container using `dry-run-test`, but this time, mount your repository onto the `/go` directory inside the container. $ docker run --privileged --rm -ti -v `pwd`:/go/src/github.com/docker/docker dry-run-test /bin/bash When you pass `pwd`, `docker` resolves it to your current directory. 4. From inside the container, list your `binary` directory. root@074626fc4b43:/go/src/github.com/docker/docker# ls bundles/1.5.0-dev/binary ls: cannot access binary: No such file or directory Your `dry-run-test` image does not retain any of the changes you made inside the container. This is the expected behavior for a container. 5. In a fresh terminal on your local host, change to the `docker-fork` root. $ cd ~/repos/docker-fork/ 6. Create a fresh binary, but this time, use the `make` command. $ make BINDDIR=. binary The `BINDDIR` flag is only necessary on Mac OS X but it won't hurt to pass it on Linux command line. The `make` command, like the `make.sh` script inside the container, reports its progress. When the make succeeds, it returns the location of the new binary. 7. Back in the terminal running the container, list your `binary` directory. root@074626fc4b43:/go/src/github.com/docker/docker# ls bundles/1.5.0-dev/binary docker docker-1.5.0-dev docker-1.5.0-dev.md5 docker-1.5.0-dev.sha256 The compiled binaries created from your repository on your local host are now available inside your running Docker development container. 8. Repeat the steps you ran in the previous procedure. * copy the binary inside the development container using `cp bundles/1.5.0-dev/binary/docker /usr/bin` * start `docker -dD` to launch the Docker daemon inside the container * run `docker ps` on local host to get the development container's name * connect to your running container `docker exec -it container_name bash` * use the `docker run hello-world` command to create and run a container inside your development container ## Where to go next Congratulations, you have successfully achieved Docker inception. At this point, you've set up your development environment and verified almost all the essential processes you need to contribute. Of course, before you start contributing, [you'll need to learn one more piece of the development environment, the test framework](/project/test-and-docs/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/set-up-git.md ================================================ # Configure Git for contributing Work through this page to configure Git and a repository you'll use throughout the Contributor Guide. The work you do further in the guide, depends on the work you do here. ## Fork and clone the Docker code Before contributing, you first fork the Docker code repository. A fork copies a repository at a particular point in time. GitHub tracks for you where a fork originates. As you make contributions, you change your fork's code. When you are ready, you make a pull request back to the original Docker repository. If you aren't familiar with this workflow, don't worry, this guide walks you through all the steps. To fork and clone Docker: 1. Open a browser and log into GitHub with your account. 2. Go to the docker/docker repository. 3. Click the "Fork" button in the upper right corner of the GitHub interface. ![Branch Signature](/project/images/fork_docker.png) GitHub forks the repository to your GitHub account. The original `docker/docker` repository becomes a new fork `YOUR_ACCOUNT/docker` under your account. 4. Copy your fork's clone URL from GitHub. GitHub allows you to use HTTPS or SSH protocols for clones. You can use the `git` command line or clients like Subversion to clone a repository. ![Copy clone URL](/project/images/copy_url.png) This guide assume you are using the HTTPS protocol and the `git` command line. If you are comfortable with SSH and some other tool, feel free to use that instead. You'll need to convert what you see in the guide to what is appropriate to your tool. 5. Open a terminal window on your local host and change to your home directory. $ cd ~ In Windows, you'll work in your Boot2Docker window instead of Powershell or a `cmd` window. 6. Create a `repos` directory. $ mkdir repos 7. Change into your `repos` directory. $ cd repos 5. Clone the fork to your local host into a repository called `docker-fork`. $ git clone https://github.com/moxiegirl/docker.git docker-fork Naming your local repo `docker-fork` should help make these instructions easier to follow; experienced coders don't typically change the name. 6. Change directory into your new `docker-fork` directory. $ cd docker-fork Take a moment to familiarize yourself with the repository's contents. List the contents. ## Set your signature and an upstream remote When you contribute to Docker, you must certify you agree with the Developer Certificate of Origin. You indicate your agreement by signing your `git` commits like this: Signed-off-by: Pat Smith To create a signature, you configure your username and email address in Git. You can set these globally or locally on just your `docker-fork` repository. You must sign with your real name. We don't accept anonymous contributions or contributions through pseudonyms. As you change code in your fork, you'll want to keep it in sync with the changes others make in the `docker/docker` repository. To make syncing easier, you'll also add a _remote_ called `upstream` that points to `docker/docker`. A remote is just another project version hosted on the internet or network. To configure your username, email, and add a remote: 1. Change to the root of your `docker-fork` repository. $ cd docker-fork 2. Set your `user.name` for the repository. $ git config --local user.name "FirstName LastName" 3. Set your `user.email` for the repository. $ git config --local user.email "emailname@mycompany.com" 4. Set your local repo to track changes upstream, on the `docker` repository. $ git remote add upstream https://github.com/docker/docker.git 7. Check the result in your `git` configuration. $ git config --local -l core.repositoryformatversion=0 core.filemode=true core.bare=false core.logallrefupdates=true remote.origin.url=https://github.com/moxiegirl/docker.git remote.origin.fetch=+refs/heads/*:refs/remotes/origin/* branch.master.remote=origin branch.master.merge=refs/heads/master user.name=Mary Anthony user.email=mary@docker.com remote.upstream.url=https://github.com/docker/docker.git remote.upstream.fetch=+refs/heads/*:refs/remotes/upstream/* To list just the remotes use: $ git remote -v origin https://github.com/moxiegirl/docker.git (fetch) origin https://github.com/moxiegirl/docker.git (push) upstream https://github.com/docker/docker.git (fetch) upstream https://github.com/docker/docker.git (push) ## Create and push a branch As you change code in your fork, make your changes on a repository branch. The branch name should reflect what you are working on. In this section, you create a branch, make a change, and push it up to your fork. This branch is just for testing your config for this guide. The changes are part of a dry run, so the branch name will be dry-run-test. To create and push the branch to your fork on GitHub: 1. Open a terminal and go to the root of your `docker-fork`. $ cd docker-fork 2. Create a `dry-run-test` branch. $ git checkout -b dry-run-test This command creates the branch and switches the repository to it. 3. Verify you are in your new branch. $ git branch * dry-run-test master The current branch has an * (asterisk) marker. So, these results shows you are on the right branch. 4. Create a `TEST.md` file in the repository's root. $ touch TEST.md 5. Edit the file and add your email and location. ![Add your information](/project/images/contributor-edit.png) You can use any text editor you are comfortable with. 6. Save and close the file. 7. Check the status of your branch. $ git status On branch dry-run-test Untracked files: (use "git add ..." to include in what will be committed) TEST.md nothing added to commit but untracked files present (use "git add" to track) You've only changed the one file. It is untracked so far by git. 8. Add your file. $ git add TEST.md That is the only _staged_ file. Stage is fancy word for work that Git is tracking. 9. Sign and commit your change. $ git commit -s -m "Making a dry run test." [dry-run-test 6e728fb] Making a dry run test 1 file changed, 1 insertion(+) create mode 100644 TEST.md Commit messages should have a short summary sentence of no more than 50 characters. Optionally, you can also include a more detailed explanation after the summary. Separate the summary from any explanation with an empty line. 8. Push your changes to GitHub. $ git push --set-upstream origin dry-run-test Username for 'https://github.com': moxiegirl Password for 'https://moxiegirl@github.com': Git prompts you for your GitHub username and password. Then, the command returns a result. Counting objects: 13, done. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 320 bytes | 0 bytes/s, done. Total 3 (delta 1), reused 0 (delta 0) To https://github.com/moxiegirl/docker.git * [new branch] dry-run-test -> dry-run-test Branch dry-run-test set up to track remote branch dry-run-test from origin. 9. Open your browser to GitHub. 10. Navigate to your Docker fork. 11. Make sure the `dry-run-test` branch exists, that it has your commit, and the commit is signed. ![Branch Signature](/project/images/branch-sig.png) ## Where to go next Congratulations, you have finished configuring both your local host environment and Git for contributing. In the next section you'll [learn how to set up and work in a Docker development container](/project/set-up-dev-env/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/software-req-win.md ================================================ # Get the required software for Windows This page explains how to get the software you need to use a a Windows Server 2012 or Windows 8 machine for Docker development. Before you begin contributing you must have: - a GitHub account - Git for Windows (msysGit) - TDM-GCC, a compiler suite for Windows - MinGW (tar and xz) - Go language > **Note**: This installation procedure refers to the `C:\` drive. If you system's main drive is `D:\` you'll need to substitute that in where appropriate in these instructions. ### Get a GitHub account To contribute to the Docker project, you will need a GitHub account. A free account is fine. All the Docker project repositories are public and visible to everyone. You should also have some experience using both the GitHub application and `git` on the command line. ## Install Git for Windows Git for Windows includes several tools including msysGit, which is a build environment. The environment contains the tools you need for development such as Git and a Git Bash shell. 1. Browse to the [Git for Windows](https://msysgit.github.io/) download page. 2. Click **Download**. Windows prompts you to save the file to your machine. 3. Run the saved file. The system displays the **Git Setup** wizard. 4. Click the **Next** button to move through the wizard and accept all the defaults. 5. Click **Finish** when you are done. ## Installing TDM-GCC TDM-GCC is a compiler suite for Windows. You'll use this suite to compile the Docker Go code as you develop. 1. Browse to [tdm-gcc download page](http://tdm-gcc.tdragon.net/download). 2. Click on the latest 64-bit version of the package. Windows prompts you to save the file to your machine 3. Set up the suite by running the downloaded file. The system opens the **TDM-GCC Setup** wizard. 4. Click **Create**. 5. Click the **Next** button to move through the wizard and accept all the defaults. 6. Click **Finish** when you are done. ## Installing MinGW (tar and xz) MinGW is a minimalist port of the GNU Compiler Collection (GCC). In this procedure, you first download and install the MinGW installation manager. Then, you use the manager to install the `tar` and `xz` tools from the collection. 1. Browse to MinGW [SourceForge](http://sourceforge.net/projects/mingw/). 2. Click **Download**. Windows prompts you to save the file to your machine 3. Run the downloaded file. The system opens the **MinGW Installation Manager Setup Tool** 4. Choose **Install** install the MinGW Installation Manager. 5. Press **Continue**. The system installs and then opens the MinGW Installation Manager. 6. Press **Continue** after the install completes to open the manager. 7. Select **All Packages > MSYS Base System** from the left hand menu. The system displays the available packages. 8. Click on the the **msys-tar bin** package and choose **Mark for Installation**. 9. Click on the **msys-xz bin** package and choose **Mark for Installation**. 10. Select **Installation > Apply Changes**, to install the selected packages. The system displays the **Schedule of Pending Actions Dialog**. ![windows-mingw](/project/images/windows-mingw.png) 11. Press **Apply** MingGW installs the packages for you. 12. Close the dialog and the MinGW Installation Manager. ## Set up your environment variables You'll need to add the compiler to your `Path` environment variable. 1. Open the **Control Panel**. 2. Choose **System and Security > System**. 3. Click the **Advanced system settings** link in the sidebar. The system opens the **System Properties** dialog. 3. Select the **Advanced** tab. 4. Click **Environment Variables**. The system opens the **Environment Variables dialog** dialog. 5. Locate the **System variables** area and scroll to the **Path** variable. ![windows-mingw](/project/images/path_variable.png) 6. Click **Edit** to edit the variable (you can also double-click it). The system opens the **Edit System Variable** dialog. 7. Make sure the `Path` includes `C:\TDM-GCC64\bin` ![include gcc](/project/images/include_gcc.png) If you don't see `C:\TDM-GCC64\bin`, add it. 8. Press **OK** to close this dialog. 9. Press **OK** twice to close out of the remaining dialogs. ## Install Go and cross-compile it In this section, you install the Go language. Then, you build the source so that it can cross-compile for `linux/amd64` architectures. 1. Open [Go Language download](http://golang.org/dl/) page in your browser. 2. Locate and click the latest `.msi` installer. The system prompts you to save the file. 3. Run the installer. The system opens the **Go Programming Language Setup** dialog. 4. Select all the defaults to install. 5. Press **Finish** to close the installation dialog. 6. Start a command prompt. 7. Change to the Go `src` directory. cd c:\Go\src 8. Set the following Go variables c:\Go\src> set GOOS=linux c:\Go\src> set GOARCH=amd64 9. Compile the source. c:\Go\src> make.bat Compiling the source also adds a number of variables to your Windows environment. ## Get the Docker repository In this step, you start a Git `bash` terminal and get the Docker source code from GitHub. 1. Locate the **Git Bash** program and start it. Recall that **Git Bash** came with the Git for Windows installation. **Git Bash** just as it sounds allows you to run a Bash terminal on Windows. ![Git Bash](/project/images/git_bash.png) 2. Change to the root directory. $ cd /c/ 3. Make a `gopath` directory. $ mkdir gopath 4. Go get the `docker/docker` repository. $ go.exe get github.com/docker/docker package github.com/docker/docker imports github.com/docker/docker imports github.com/docker/docker: no buildable Go source files in C:\gopath\src\github.com\docker\docker In the next steps, you create environment variables for you Go paths. 5. Open the **Control Panel** on your system. 6. Choose **System and Security > System**. 7. Click the **Advanced system settings** link in the sidebar. The system opens the **System Properties** dialog. 8. Select the **Advanced** tab. 9. Click **Environment Variables**. The system opens the **Environment Variables dialog** dialog. 10. Locate the **System variables** area and scroll to the **Path** variable. 11. Click **New**. Now you are going to create some new variables. These paths you'll create in the next procedure; but you can set them now. 12. Enter `GOPATH` for the **Variable Name**. 13. For the **Variable Value** enter the following: C:\gopath;C:\gopath\src\github.com\docker\docker\vendor 14. Press **OK** to close this dialog. The system adds `GOPATH` to the list of **System Variables**. 15. Press **OK** twice to close out of the remaining dialogs. ## Where to go next In the next section, you'll [learn how to set up and configure Git for contributing to Docker](/project/set-up-git/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/software-required.md ================================================ # Get the required software for Linux or OS X This page explains how to get the software you need to use a Linux or OS X machine for Docker development. Before you begin contributing you must have: * a GitHub account * `git` * `make` * `docker` You'll notice that `go`, the language that Docker is written in, is not listed. That's because you don't need it installed; Docker's development environment provides it for you. You'll learn more about the development environment later. ### Get a GitHub account To contribute to the Docker project, you will need a GitHub account. A free account is fine. All the Docker project repositories are public and visible to everyone. You should also have some experience using both the GitHub application and `git` on the command line. ### Install git Install `git` on your local system. You can check if `git` is on already on your system and properly installed with the following command: $ git --version This documentation is written using `git` version 2.2.2. Your version may be different depending on your OS. ### Install make Install `make`. You can check if `make` is on your system with the following command: $ make -v This documentation is written using GNU Make 3.81. Your version may be different depending on your OS. ### Install or upgrade Docker If you haven't already, install the Docker software using the instructions for your operating system. If you have an existing installation, check your version and make sure you have the latest Docker. To check if `docker` is already installed on Linux: $ docker --version Docker version 1.5.0, build a8a31ef On Mac OS X or Windows, you should have installed Boot2Docker which includes Docker. You'll need to verify both Boot2Docker and then Docker. This documentation was written on OS X using the following versions. $ boot2docker version Boot2Docker-cli version: v1.5.0 Git commit: ccd9032 $ docker --version Docker version 1.5.0, build a8a31ef ## Linux users and sudo This guide assumes you have added your user to the `docker` group on your system. To check, list the group's contents: $ getent group docker docker:x:999:ubuntu If the command returns no matches, you have two choices. You can preface this guide's `docker` commands with `sudo` as you work. Alternatively, you can add your user to the `docker` group as follows: $ sudo usermod -aG docker ubuntu You must log out and log back in for this modification to take effect. ## Where to go next In the next section, you'll [learn how to set up and configure Git for contributing to Docker](/project/set-up-git/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/test-and-docs.md ================================================ # Run tests and test documentation Contributing includes testing your changes. If you change the Docker code, you may need to add a new test or modify an existing one. Your contribution could even be adding tests to Docker. For this reason, you need to know a little about Docker's test infrastructure. Many contributors contribute documentation only. Or, a contributor makes a code contribution that changes how Docker behaves and that change needs documentation. For these reasons, you also need to know how to build, view, and test the Docker documentation. In this section, you run tests in the `dry-run-test` branch of your Docker fork. If you have followed along in this guide, you already have this branch. If you don't have this branch, you can create it or simply use another of your branches. ## Understand testing at Docker Docker tests use the Go language's test framework. In this framework, files whose names end in `_test.go` contain test code; you'll find test files like this throughout the Docker repo. Use these files for inspiration when writing your own tests. For information on Go's test framework, see Go's testing package documentation and the go test help. You are responsible for _unit testing_ your contribution when you add new or change existing Docker code. A unit test is a piece of code that invokes a single, small piece of code ( _unit of work_ ) to verify the unit works as expected. Depending on your contribution, you may need to add _integration tests_. These are tests that combine two or more work units into one component. These work units each have unit tests and then, together, integration tests that test the interface between the components. The `integration` and `integration-cli` directories in the Docker repository contain integration test code. Testing is its own specialty. If you aren't familiar with testing techniques, there is a lot of information available to you on the Web. For now, you should understand that, the Docker maintainers may ask you to write a new test or change an existing one. ### Run tests on your local host Before submitting any code change, you should run the entire Docker test suite. The `Makefile` contains a target for the entire test suite. The target's name is simply `test`. The make file contains several targets for testing:
Target What this target does
test Run all the tests.
test-unit Run just the unit tests.
test-integration-cli Run the test for the integration command line interface.
test-docker-py Run the tests for Docker API client.
docs-test Runs the documentation test build.
Run the entire test suite on your current repository: 1. Open a terminal on your local host. 2. Change to the root your Docker repository. $ cd docker-fork 3. Make sure you are in your development branch. $ git checkout dry-run-test 4. Run the `make test` command. $ make test This command does several things, it creates a container temporarily for testing. Inside that container, the `make`: * creates a new binary * cross-compiles all the binaries for the various operating systems * runs all the tests in the system It can take several minutes to run all the tests. When they complete successfully, you see the output concludes with something like this: [PASSED]: top - sleep process should be listed in privileged mode [PASSED]: version - verify that it works and that the output is properly formatted PASS coverage: 70.8% of statements ---> Making bundle: test-docker-py (in bundles/1.5.0-dev/test-docker-py) +++ exec docker --daemon --debug --host unix:///go/src/github.com/docker/docker/bundles/1.5.0-dev/test-docker-py/docker.sock --storage-driver vfs --exec-driver native --pidfile /go/src/github.com/docker/docker/bundles/1.5.0-dev/test-docker-py/docker.pid ................................................................. ---------------------------------------------------------------------- Ran 65 tests in 89.266s ### Run test targets inside the development container If you are working inside a Docker development container, you use the `hack/make.sh` script to run tests. The `hack/make.sh` script doesn't have a single target that runs all the tests. Instead, you provide a single command line with multiple targets that does the same thing. Try this now. 1. Open a terminal and change to the `docker-fork` root. 2. Start a Docker development image. If you are following along with this guide, you should have a `dry-run-test` image. $ docker run --privileged --rm -ti -v `pwd`:/go/src/github.com/docker/docker dry-run-test /bin/bash 3. Run the tests using the `hack/make.sh` script. root@5f8630b873fe:/go/src/github.com/docker/docker# hack/make.sh dynbinary binary cross test-unit test-integration-cli test-docker-py The tests run just as they did within your local host. Of course, you can also run a subset of these targets too. For example, to run just the unit tests: root@5f8630b873fe:/go/src/github.com/docker/docker# hack/make.sh dynbinary binary cross test-unit Most test targets require that you build these precursor targets first: `dynbinary binary cross` ## Running individual or multiple named tests We use [gocheck](https://labix.org/gocheck) for our integration-cli tests. You can use the `TESTFLAGS` environment variable to run a single test. The flag's value is passed as arguments to the `go test` command. For example, from your local host you can run the `TestBuild` test with this command: $ TESTFLAGS='-check.f DockerSuite.TestBuild*' make test-integration-cli To run the same test inside your Docker development container, you do this: root@5f8630b873fe:/go/src/github.com/docker/docker# TESTFLAGS='-check.f TestBuild*' hack/make.sh binary test-integration-cli ## If tests under Boot2Docker fail due to disk space errors Running the tests requires about 2GB of memory. If you are running your container on bare metal, that is you are not running with Boot2Docker, your Docker development container is able to take the memory it requires directly from your local host. If you are running Docker using Boot2Docker, the VM uses 2048MB by default. This means you can exceed the memory of your VM running tests in a Boot2Docker environment. When the test suite runs out of memory, it returns errors similar to the following: server.go:1302 Error: Insertion failed because database is full: database or disk is full utils_test.go:179: Error copy: exit status 1 (cp: writing '/tmp/docker-testd5c9-[...]': No space left on device To increase the memory on your VM, you need to reinitialize the Boot2Docker VM with new memory settings. 1. Stop all running containers. 2. View the current memory setting. $ boot2docker info { "Name": "boot2docker-vm", "UUID": "491736fd-4075-4be7-a6f5-1d4cdcf2cc74", "Iso": "/Users/mary/.boot2docker/boot2docker.iso", "State": "running", "CPUs": 8, "Memory": 2048, "VRAM": 8, "CfgFile": "/Users/mary/VirtualBox VMs/boot2docker-vm/boot2docker-vm.vbox", "BaseFolder": "/Users/mary/VirtualBox VMs/boot2docker-vm", "OSType": "", "Flag": 0, "BootOrder": null, "DockerPort": 0, "SSHPort": 2022, "SerialFile": "/Users/mary/.boot2docker/boot2docker-vm.sock" } 3. Delete your existing `boot2docker` profile. $ boot2docker delete 4. Reinitialize `boot2docker` and specify a higher memory. $ boot2docker init -m 5555 5. Verify the memory was reset. $ boot2docker info 6. Restart your container and try your test again. ## Testing just the Windows client This explains how to test the Windows client on a Windows server set up as a development environment. You'll use the **Git Bash** came with the Git for Windows installation. **Git Bash** just as it sounds allows you to run a Bash terminal on Windows. 1. If you don't have one, start a Git Bash terminal. ![Git Bash](/project/images/git_bash.png) 2. Change to the `docker` source directory. $ cd /c/gopath/src/github.com/docker/docker 3. Set `DOCKER_CLIENTONLY` as follows: $ export DOCKER_CLIENTONLY=1 This ensures you are building only the client binary instead of both the binary and the daemon. 4. Set `DOCKER_TEST_HOST` to the `tcp://IP_ADDRESS:2376` value; substitute your machine's actual IP address, for example: $ export DOCKER_TEST_HOST=tcp://263.124.23.200:2376 5. Make the binary and the test: $ hack/make.sh binary test-integration-cli Many tests are skipped on Windows for various reasons. You see which tests were skipped by re-running the make and passing in the `TESTFLAGS='-test.v'` value. You can now choose to make changes to the Docker source or the tests. If you make any changes just run these commands again. ## Build and test the documentation The Docker documentation source files are under `docs`. The content is written using extended Markdown. We use the static generator MkDocs to build Docker's documentation. Of course, you don't need to install this generator to build the documentation, it is included with container. You should always check your documentation for grammar and spelling. The best way to do this is with an online grammar checker. When you change a documentation source file, you should test your change locally to make sure your content is there and any links work correctly. You can build the documentation from the local host. The build starts a container and loads the documentation into a server. As long as this container runs, you can browse the docs. 1. In a terminal, change to the root of your `docker-fork` repository. $ cd ~/repos/docker-fork 2. Make sure you are in your feature branch. $ git status On branch dry-run-test Your branch is up-to-date with 'origin/dry-run-test'. nothing to commit, working directory clean 3. Build the documentation. $ make docs When the build completes, you'll see a final output message similar to the following: Successfully built ee7fe7553123 docker run --rm -it -e AWS_S3_BUCKET -e NOCACHE -p 8000:8000 "docker-docs:dry-run-test" mkdocs serve Running at: http://0.0.0.0:8000/ Live reload enabled. Hold ctrl+c to quit. 4. Enter the URL in your browser. If you are running Boot2Docker, replace the default localhost address (0.0.0.0) with your DOCKERHOST value. You can get this value at any time by entering `boot2docker ip` at the command line. 5. Once in the documentation, look for the red notice to verify you are seeing the correct build. ![Beta documentation](/project/images/red_notice.png) 6. Navigate to your new or changed document. 7. Review both the content and the links. 8. Return to your terminal and exit out of the running documentation container. ## Where to go next Congratulations, you have successfully completed the basics you need to understand the Docker test framework. In the next steps, you use what you have learned so far to [contribute to Docker by working on an issue](/project/make-a-contribution/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/who-written-for.md ================================================ # README first This section of the documentation contains a guide for Docker users who want to contribute code or documentation to the Docker project. As a community, we share rules of behavior and interaction. Make sure you are familiar with the community guidelines before continuing. ## Where and what you can contribute The Docker project consists of not just one but several repositories on GitHub. So, in addition to the `docker/docker` repository, there is the `docker/compose` repo, the `docker/machine` repo, and several more. Contribute to any of these and you contribute to the Docker project. Not all Docker repositories use the Go language. Also, each repository has its own focus area. So, if you are an experienced contributor, think about contributing to a Docker repository that has a language or a focus area you are familiar with. If you are new to the open source community, to Docker, or to formal programming, you should start out contributing to the `docker/docker` repository. Why? Because this guide is written for that repository specifically. Finally, code or documentation isn't the only way to contribute. You can report an issue, add to discussions in our community channel, write a blog post, or take a usability test. You can even propose your own type of contribution. Right now we don't have a lot written about this yet, so just email if this type of contributing interests you. ## A turtle is involved ![Gordon](/project/images/gordon.jpeg) Enough said. ## How to use this guide This is written for the distracted, the overworked, the sloppy reader with fair `git` skills and a failing memory for the GitHub GUI. The guide attempts to explain how to use the Docker environment as precisely, predictably, and procedurally as possible. Users who are new to the Docker development environment should start by setting up their environment. Then, they should try a simple code change. After that, you should find something to work on or propose at totally new change. If you are a programming prodigy, you still may find this documentation useful. Please feel free to skim past information you find obvious or boring. ## How to get started Start by [getting the software you need to contribute](/project/software-required/). ================================================ FILE: vendor/github.com/docker/docker/docs/project/work-issue.md ================================================ # Work on your issue The work you do for your issue depends on the specific issue you picked. This section gives you a step-by-step workflow. Where appropriate, it provides command examples. However, this is a generalized workflow, depending on your issue you may repeat steps or even skip some. How much time the work takes depends on you --- you could spend days or 30 minutes of your time. ## How to work on your local branch Follow this workflow as you work: 1. Review the appropriate style guide. If you are changing code, review the coding style guide. Changing documentation? Review the documentation style guide. 2. Make changes in your feature branch. Your feature branch you created in the last section. Here you use the development container. If you are making a code change, you can mount your source into a development container and iterate that way. For documentation alone, you can work on your local host. Make sure you don't change files in the `vendor` directory and its subdirectories; they contain third-party dependency code. Review if you forgot the details of working with a container. 3. Test your changes as you work. If you have followed along with the guide, you know the `make test` target runs the entire test suite and `make docs` builds the documentation. If you forgot the other test targets, see the documentation for testing both code and documentation. 4. For code changes, add unit tests if appropriate. If you add new functionality or change existing functionality, you should add a unit test also. Use the existing test files for inspiration. Aren't sure if you need tests? Skip this step; you can add them later in the process if necessary. 5. Format your source files correctly.
File type How to format
.go

Format .go files using the gofmt command. For example, if you edited the `docker.go` file you would format the file like this:

$ gofmt -s -w docker.go

Most file editors have a plugin to format for you. Check your editor's documentation.

.md and non-.go files Wrap lines to 80 characters.
6. List your changes. $ git status On branch 11038-fix-rhel-link Changes not staged for commit: (use "git add ..." to update what will be committed) (use "git checkout -- ..." to discard changes in working directory) modified: docs/installation/mac.md modified: docs/installation/rhel.md The `status` command lists what changed in the repository. Make sure you see the changes you expect. 7. Add your change to Git. $ git add docs/installation/mac.md $ git add docs/installation/rhel.md 8. Commit your changes making sure you use the `-s` flag to sign your work. $ git commit -s -m "Fixing RHEL link" 9. Push your change to your repository. $ git push origin 11038-fix-rhel-link Username for 'https://github.com': moxiegirl Password for 'https://moxiegirl@github.com': Counting objects: 60, done. Compressing objects: 100% (7/7), done. Writing objects: 100% (7/7), 582 bytes | 0 bytes/s, done. Total 7 (delta 6), reused 0 (delta 0) To https://github.com/moxiegirl/docker.git * [new branch] 11038-fix-rhel-link -> 11038-fix-rhel-link Branch 11038-fix-rhel-link set up to track remote branch 11038-fix-rhel-link from origin. ## Review your branch on GitHub After you push a new branch, you should verify it on GitHub: 1. Open your browser to GitHub. 2. Go to your Docker fork. 3. Select your branch from the dropdown. ![Find branch](/project/images/locate_branch.png) 4. Use the "Compare" button to compare the differences between your branch and master. Depending how long you've been working on your branch, your branch maybe behind Docker's upstream repository. 5. Review the commits. Make sure your branch only shows the work you've done. ## Pull and rebase frequently You should pull and rebase frequently as you work. 1. Return to the terminal on your local machine and checkout your feature branch in your local `docker-fork` repository. 2. Fetch any last minute changes from `docker/docker`. $ git fetch upstream master From github.com:docker/docker * branch master -> FETCH_HEAD 3. Start an interactive rebase. $ git rebase -i upstream/master 4. Rebase opens an editor with a list of commits. pick 1a79f55 Tweak some of the other text for grammar pick 53e4983 Fix a link pick 3ce07bb Add a new line about RHEL 5. Replace the `pick` keyword with `squash` on all but the first commit. pick 1a79f55 Tweak some of the other text for grammar squash 53e4983 Fix a link squash 3ce07bb Add a new line about RHEL After you save the changes and quit from the editor, git starts the rebase, reporting the progress along the way. Sometimes your changes can conflict with the work of others. If git encounters a conflict, it stops the rebase, and prints guidance for how to correct the conflict. 6. Edit and save your commit message. $ git commit -s Make sure your message includes your signature. 7. Force push any changes to your fork on GitHub. $ git push -f origin 11038-fix-rhel-link ## Where to go next At this point, you should understand how to work on an issue. In the next section, you [learn how to make a pull request](/project/create-pr/). ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/README.md ================================================ This directory holds the authoritative specifications of APIs defined and implemented by Docker. Currently this includes: * The remote API by which a docker node can be queried over HTTP * The registry API by which a docker node can download and upload images for storage and sharing * The index search API by which a docker node can search the public index for images to download * The docker.io OAuth and accounts API which 3rd party services can use to access account information ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker-io_api.md ================================================ # Docker Hub API - This is the REST API for [Docker Hub](https://hub.docker.com). - Authorization is done with basic auth over SSL - Not all commands require authentication, only those noted as such. # Repositories ## User repository ### Create a user repository `PUT /v1/repositories/(namespace)/(repo_name)/` Create a user repository with the given `namespace` and `repo_name`. **Example Request**: PUT /v1/repositories/foo/bar/ HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== X-Docker-Token: true [{"id": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f"}] Parameters: - **namespace** – the namespace for the repo - **repo_name** – the name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json WWW-Authenticate: Token signature=123abc,repository="foo/bar",access=write X-Docker-Token: signature=123abc,repository="foo/bar",access=write X-Docker-Endpoints: registry-1.docker.io [, registry-2.docker.io] "" Status Codes: - **200** – Created - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active ### Delete a user repository `DELETE /v1/repositories/(namespace)/(repo_name)/` Delete a user repository with the given `namespace` and `repo_name`. **Example Request**: DELETE /v1/repositories/foo/bar/ HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== X-Docker-Token: true "" Parameters: - **namespace** – the namespace for the repo - **repo_name** – the name for the repo **Example Response**: HTTP/1.1 202 Vary: Accept Content-Type: application/json WWW-Authenticate: Token signature=123abc,repository="foo/bar",access=delete X-Docker-Token: signature=123abc,repository="foo/bar",access=delete X-Docker-Endpoints: registry-1.docker.io [, registry-2.docker.io] "" Status Codes: - **200** – Deleted - **202** – Accepted - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active ## Library repository ### Create a library repository `PUT /v1/repositories/(repo_name)/` Create a library repository with the given `repo_name`. This is a restricted feature only available to docker admins. > When namespace is missing, it is assumed to be `library` **Example Request**: PUT /v1/repositories/foobar/ HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== X-Docker-Token: true [{"id": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f"}] Parameters: - **repo_name** – the library name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json WWW-Authenticate: Token signature=123abc,repository="library/foobar",access=write X-Docker-Token: signature=123abc,repository="foo/bar",access=write X-Docker-Endpoints: registry-1.docker.io [, registry-2.docker.io] "" Status Codes: - **200** – Created - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active ### Delete a library repository `DELETE /v1/repositories/(repo_name)/` Delete a library repository with the given `repo_name`. This is a restricted feature only available to docker admins. > When namespace is missing, it is assumed to be `library` **Example Request**: DELETE /v1/repositories/foobar/ HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== X-Docker-Token: true "" Parameters: - **repo_name** – the library name for the repo **Example Response**: HTTP/1.1 202 Vary: Accept Content-Type: application/json WWW-Authenticate: Token signature=123abc,repository="library/foobar",access=delete X-Docker-Token: signature=123abc,repository="foo/bar",access=delete X-Docker-Endpoints: registry-1.docker.io [, registry-2.docker.io] "" Status Codes: - **200** – Deleted - **202** – Accepted - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active # Repository images ## User repository images ### Update user repository images `PUT /v1/repositories/(namespace)/(repo_name)/images` Update the images for a user repo. **Example Request**: PUT /v1/repositories/foo/bar/images HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== [{"id": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", "checksum": "b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087"}] Parameters: - **namespace** – the namespace for the repo - **repo_name** – the name for the repo **Example Response**: HTTP/1.1 204 Vary: Accept Content-Type: application/json "" Status Codes: - **204** – Created - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active or permission denied ### List user repository images `GET /v1/repositories/(namespace)/(repo_name)/images` Get the images for a user repo. **Example Request**: GET /v1/repositories/foo/bar/images HTTP/1.1 Host: index.docker.io Accept: application/json Parameters: - **namespace** – the namespace for the repo - **repo_name** – the name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json [{"id": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", "checksum": "b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087"}, {"id": "ertwetewtwe38722009fe6857087b486531f9a779a0c1dfddgfgsdgdsgds", "checksum": "34t23f23fc17e3ed29dae8f12c4f9e89cc6f0bsdfgfsdgdsgdsgerwgew"}] Status Codes: - **200** – OK - **404** – Not found ## Library repository images ### Update library repository images `PUT /v1/repositories/(repo_name)/images` Update the images for a library repo. **Example Request**: PUT /v1/repositories/foobar/images HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== [{"id": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", "checksum": "b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087"}] Parameters: - **repo_name** – the library name for the repo **Example Response**: HTTP/1.1 204 Vary: Accept Content-Type: application/json "" Status Codes: - **204** – Created - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active or permission denied ### List library repository images `GET /v1/repositories/(repo_name)/images` Get the images for a library repo. **Example Request**: GET /v1/repositories/foobar/images HTTP/1.1 Host: index.docker.io Accept: application/json Parameters: - **repo_name** – the library name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json [{"id": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", "checksum": "b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087"}, {"id": "ertwetewtwe38722009fe6857087b486531f9a779a0c1dfddgfgsdgdsgds", "checksum": "34t23f23fc17e3ed29dae8f12c4f9e89cc6f0bsdfgfsdgdsgdsgerwgew"}] Status Codes: - **200** – OK - **404** – Not found # Repository authorization ## Library repository ### Authorize a token for a library `PUT /v1/repositories/(repo_name)/auth` Authorize a token for a library repo **Example Request**: PUT /v1/repositories/foobar/auth HTTP/1.1 Host: index.docker.io Accept: application/json Authorization: Token signature=123abc,repository="library/foobar",access=write Parameters: - **repo_name** – the library name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json "OK" Status Codes: - **200** – OK - **403** – Permission denied - **404** – Not found ## User repository ### Authorize a token for a user repository `PUT /v1/repositories/(namespace)/(repo_name)/auth` Authorize a token for a user repo **Example Request**: PUT /v1/repositories/foo/bar/auth HTTP/1.1 Host: index.docker.io Accept: application/json Authorization: Token signature=123abc,repository="foo/bar",access=write Parameters: - **namespace** – the namespace for the repo - **repo_name** – the name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json "OK" Status Codes: - **200** – OK - **403** – Permission denied - **404** – Not found ## Users ### User login `GET /v1/users/` If you want to check your login, you can try this endpoint **Example Request**: GET /v1/users/ HTTP/1.1 Host: index.docker.io Accept: application/json Authorization: Basic akmklmasadalkm== **Example Response**: HTTP/1.1 200 OK Vary: Accept Content-Type: application/json OK Status Codes: - **200** – no error - **401** – Unauthorized - **403** – Account is not Active ### User register `POST /v1/users/` Registering a new account. **Example request**: POST /v1/users/ HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json {"email": "sam@docker.com", "password": "toto42", "username": "foobar"} Json Parameters: - **email** – valid email address, that needs to be confirmed - **username** – min 4 character, max 30 characters, must match the regular expression [a-z0-9_]. - **password** – min 5 characters **Example Response**: HTTP/1.1 201 OK Vary: Accept Content-Type: application/json "User Created" Status Codes: - **201** – User Created - **400** – Errors (invalid json, missing or invalid fields, etc) ### Update user `PUT /v1/users/(username)/` Change a password or email address for given user. If you pass in an email, it will add it to your account, it will not remove the old one. Passwords will be updated. It is up to the client to verify that that password that is sent is the one that they want. Common approach is to have them type it twice. **Example Request**: PUT /v1/users/fakeuser/ HTTP/1.1 Host: index.docker.io Accept: application/json Content-Type: application/json Authorization: Basic akmklmasadalkm== {"email": "sam@docker.com", "password": "toto42"} Parameters: - **username** – username for the person you want to update **Example Response**: HTTP/1.1 204 Vary: Accept Content-Type: application/json "" Status Codes: - **204** – User Updated - **400** – Errors (invalid json, missing or invalid fields, etc) - **401** – Unauthorized - **403** – Account is not Active - **404** – User not found ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_io_accounts_api.md ================================================ # docker.io accounts API ## Get a single user `GET /api/v1.1/users/:username/` Get profile info for the specified user. Parameters: - **username** – username of the user whose profile info is being requested. Request Headers: - **Authorization** – required authentication credentials of either type HTTP Basic or OAuth Bearer Token. Status Codes: - **200** – success, user data returned. - **401** – authentication error. - **403** – permission error, authenticated user must be the user whose data is being requested, OAuth access tokens must have `profile_read` scope. - **404** – the specified username does not exist. **Example request**: GET /api/v1.1/users/janedoe/ HTTP/1.1 Host: www.docker.io Accept: application/json Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id": 2, "username": "janedoe", "url": "https://www.docker.io/api/v1.1/users/janedoe/", "date_joined": "2014-02-12T17:58:01.431312Z", "type": "User", "full_name": "Jane Doe", "location": "San Francisco, CA", "company": "Success, Inc.", "profile_url": "https://docker.io/", "gravatar_url": "https://secure.gravatar.com/avatar/0212b397124be4acd4e7dea9aa357.jpg?s=80&r=g&d=mm" "email": "jane.doe@example.com", "is_active": true } ## Update a single user `PATCH /api/v1.1/users/:username/` Update profile info for the specified user. Parameters: - **username** – username of the user whose profile info is being updated. Json Parameters: - **full_name** (*string*) – (optional) the new name of the user. - **location** (*string*) – (optional) the new location. - **company** (*string*) – (optional) the new company of the user. - **profile_url** (*string*) – (optional) the new profile url. - **gravatar_email** (*string*) – (optional) the new Gravatar email address. Request Headers: - **Authorization** – required authentication credentials of either type HTTP Basic or OAuth Bearer Token. - **Content-Type** – MIME Type of post data. JSON, url-encoded form data, etc. Status Codes: - **200** – success, user data updated. - **400** – post data validation error. - **401** – authentication error. - **403** – permission error, authenticated user must be the user whose data is being updated, OAuth access tokens must have `profile_write` scope. - **404** – the specified username does not exist. **Example request**: PATCH /api/v1.1/users/janedoe/ HTTP/1.1 Host: www.docker.io Accept: application/json Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= { "location": "Private Island", "profile_url": "http://janedoe.com/", "company": "Retired", } **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id": 2, "username": "janedoe", "url": "https://www.docker.io/api/v1.1/users/janedoe/", "date_joined": "2014-02-12T17:58:01.431312Z", "type": "User", "full_name": "Jane Doe", "location": "Private Island", "company": "Retired", "profile_url": "http://janedoe.com/", "gravatar_url": "https://secure.gravatar.com/avatar/0212b397124be4acd4e7dea9aa357.jpg?s=80&r=g&d=mm" "email": "jane.doe@example.com", "is_active": true } ## List email addresses for a user `GET /api/v1.1/users/:username/emails/` List email info for the specified user. Parameters: - **username** – username of the user whose profile info is being updated. Request Headers: - **Authorization** – required authentication credentials of either type HTTP Basic or OAuth Bearer Token Status Codes: - **200** – success, user data updated. - **401** – authentication error. - **403** – permission error, authenticated user must be the user whose data is being requested, OAuth access tokens must have `email_read` scope. - **404** – the specified username does not exist. **Example request**: GET /api/v1.1/users/janedoe/emails/ HTTP/1.1 Host: www.docker.io Accept: application/json Authorization: Bearer zAy0BxC1wDv2EuF3tGs4HrI6qJp6KoL7nM **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "email": "jane.doe@example.com", "verified": true, "primary": true } ] ## Add email address for a user `POST /api/v1.1/users/:username/emails/` Add a new email address to the specified user's account. The email address must be verified separately, a confirmation email is not automatically sent. Json Parameters: - **email** (*string*) – email address to be added. Request Headers: - **Authorization** – required authentication credentials of either type HTTP Basic or OAuth Bearer Token. - **Content-Type** – MIME Type of post data. JSON, url-encoded form data, etc. Status Codes: - **201** – success, new email added. - **400** – data validation error. - **401** – authentication error. - **403** – permission error, authenticated user must be the user whose data is being requested, OAuth access tokens must have `email_write` scope. - **404** – the specified username does not exist. **Example request**: POST /api/v1.1/users/janedoe/emails/ HTTP/1.1 Host: www.docker.io Accept: application/json Content-Type: application/json Authorization: Bearer zAy0BxC1wDv2EuF3tGs4HrI6qJp6KoL7nM { "email": "jane.doe+other@example.com" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "email": "jane.doe+other@example.com", "verified": false, "primary": false } ## Delete email address for a user `DELETE /api/v1.1/users/:username/emails/` Delete an email address from the specified user's account. You cannot delete a user's primary email address. Json Parameters: - **email** (*string*) – email address to be deleted. Request Headers: - **Authorization** – required authentication credentials of either type HTTP Basic or OAuth Bearer Token. - **Content-Type** – MIME Type of post data. JSON, url-encoded form data, etc. Status Codes: - **204** – success, email address removed. - **400** – validation error. - **401** – authentication error. - **403** – permission error, authenticated user must be the user whose data is being requested, OAuth access tokens must have `email_write` scope. - **404** – the specified username or email address does not exist. **Example request**: DELETE /api/v1.1/users/janedoe/emails/ HTTP/1.1 Host: www.docker.io Accept: application/json Content-Type: application/json Authorization: Bearer zAy0BxC1wDv2EuF3tGs4HrI6qJp6KoL7nM { "email": "jane.doe+other@example.com" } **Example response**: HTTP/1.1 204 NO CONTENT Content-Length: 0 ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api.md ================================================ # Docker Remote API - By default the Docker daemon listens on `unix:///var/run/docker.sock` and the client must have `root` access to interact with the daemon. - If the Docker daemon is set to use an encrypted TCP socket (`--tls`, or `--tlsverify`) as with Boot2Docker 1.3.0, then you need to add extra parameters to `curl` or `wget` when making test API requests: `curl --insecure --cert ~/.docker/cert.pem --key ~/.docker/key.pem https://boot2docker:2376/images/json` or `wget --no-check-certificate --certificate=$DOCKER_CERT_PATH/cert.pem --private-key=$DOCKER_CERT_PATH/key.pem https://boot2docker:2376/images/json -O - -q` - If a group named `docker` exists on your system, docker will apply ownership of the socket to the group. - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport STDOUT, STDIN, and STDERR. - Since API version 1.2, the auth configuration is now handled client side, so the client has to send the `authConfig` as a `POST` in `/images/(name)/push`. - authConfig, set as the `X-Registry-Auth` header, is currently a Base64 encoded (JSON) string with the following structure: `{"username": "string", "password": "string", "email": "string", "serveraddress" : "string", "auth": ""}`. Notice that `auth` is to be left empty, `serveraddress` is a domain/ip without protocol, and that double quotes (instead of single ones) are required. - The Remote API uses an open schema model. In this model, unknown properties in incoming messages will be ignored. Client applications need to take this into account to ensure they will not break when talking to newer Docker daemons. The current version of the API is v1.20 Calling `/info` is the same as calling `/v1.20/info`. You can still call an old version of the API using `/v1.19/info`. ## Docker Events The following diagram depicts the container states accessible through the API. ![States](../images/event_state.png) Some container-related events are not affected by container state, so they are not included in this diagram. These events are: * **export** emitted by `docker export` * **exec_create** emitted by `docker exec` * **exec_start** emitted by `docker exec` after **exec_create** Running `docker rmi` emits an **untag** event when removing an image name. The `rmi` command may also emit **delete** events when images are deleted by ID directly or by deleting the last tag referring to the image. > **Acknowledgement**: This diagram and the accompanying text were used with the permission of Matt Good and Gilder Labs. See Matt's original blog post [Docker Events Explained](http://gliderlabs.com/blog/2015/04/14/docker-events-explained/). ## v1.20 ### Full documentation [*Docker Remote API v1.20*](/reference/api/docker_remote_api_v1.20/) ### What's new `GET /containers/(id)/archive` **New!** Get an archive of filesystem content from a container. `PUT /containers/(id)/archive` **New!** Upload an archive of content to be extracted to an existing directory inside a container's filesystem. `POST /containers/(id)/copy` **Deprecated!** This copy endpoint has been deprecated in favor of the above `archive` endpoint which can be used to download files and directories from a container. **New!** The `hostConfig` option now accepts the field `GroupAdd`, which specifies a list of additional groups that the container process will run as. ## v1.19 ### Full documentation [*Docker Remote API v1.19*](/reference/api/docker_remote_api_v1.19/) ### What's new **New!** When the daemon detects a version mismatch with the client, usually when the client is newer than the daemon, an HTTP 400 is now returned instead of a 404. `GET /containers/(id)/stats` **New!** You can now supply a `stream` bool to get only one set of stats and disconnect `GET /containers(id)/logs` **New!** This endpoint now accepts a `since` timestamp parameter. `GET /info` **New!** The fields `Debug`, `IPv4Forwarding`, `MemoryLimit`, and `SwapLimit` are now returned as boolean instead of as an int. In addition, the end point now returns the new boolean fields `CpuCfsPeriod`, `CpuCfsQuota`, and `OomKillDisable`. ## v1.18 ### Full documentation [*Docker Remote API v1.18*](/reference/api/docker_remote_api_v1.18/) ### What's new `GET /version` **New!** This endpoint now returns `Os`, `Arch` and `KernelVersion`. `POST /containers/create` `POST /containers/(id)/start` **New!** You can set ulimit settings to be used within the container. `GET /info` **New!** This endpoint now returns `SystemTime`, `HttpProxy`,`HttpsProxy` and `NoProxy`. `GET /images/json` **New!** Added a `RepoDigests` field to include image digest information. `POST /build` **New!** Builds can now set resource constraints for all containers created for the build. **New!** (`CgroupParent`) can be passed in the host config to setup container cgroups under a specific cgroup. `POST /build` **New!** Closing the HTTP request will now cause the build to be canceled. `POST /containers/(id)/exec` **New!** Add `Warnings` field to response. ## v1.17 ### Full documentation [*Docker Remote API v1.17*](/reference/api/docker_remote_api_v1.17/) ### What's new The build supports `LABEL` command. Use this to add metadata to an image. For example you could add data describing the content of an image. `LABEL "com.example.vendor"="ACME Incorporated"` **New!** `POST /containers/(id)/attach` and `POST /exec/(id)/start` **New!** Docker client now hints potential proxies about connection hijacking using HTTP Upgrade headers. `POST /containers/create` **New!** You can set labels on container create describing the container. `GET /containers/json` **New!** The endpoint returns the labels associated with the containers (`Labels`). `GET /containers/(id)/json` **New!** This endpoint now returns the list current execs associated with the container (`ExecIDs`). This endpoint now returns the container labels (`Config.Labels`). `POST /containers/(id)/rename` **New!** New endpoint to rename a container `id` to a new name. `POST /containers/create` `POST /containers/(id)/start` **New!** (`ReadonlyRootfs`) can be passed in the host config to mount the container's root filesystem as read only. `GET /containers/(id)/stats` **New!** This endpoint returns a live stream of a container's resource usage statistics. `GET /images/json` **New!** This endpoint now returns the labels associated with each image (`Labels`). ## v1.16 ### Full documentation [*Docker Remote API v1.16*](/reference/api/docker_remote_api_v1.16/) ### What's new `GET /info` **New!** `info` now returns the number of CPUs available on the machine (`NCPU`), total memory available (`MemTotal`), a user-friendly name describing the running Docker daemon (`Name`), a unique ID identifying the daemon (`ID`), and a list of daemon labels (`Labels`). `POST /containers/create` **New!** You can set the new container's MAC address explicitly. **New!** Volumes are now initialized when the container is created. `POST /containers/(id)/copy` **New!** You can now copy data which is contained in a volume. ## v1.15 ### Full documentation [*Docker Remote API v1.15*](/reference/api/docker_remote_api_v1.15/) ### What's new `POST /containers/create` **New!** It is now possible to set a container's HostConfig when creating a container. Previously this was only available when starting a container. ## v1.14 ### Full documentation [*Docker Remote API v1.14*](/reference/api/docker_remote_api_v1.14/) ### What's new `DELETE /containers/(id)` **New!** When using `force`, the container will be immediately killed with SIGKILL. `POST /containers/(id)/start` **New!** The `hostConfig` option now accepts the field `CapAdd`, which specifies a list of capabilities to add, and the field `CapDrop`, which specifies a list of capabilities to drop. `POST /images/create` **New!** The `fromImage` and `repo` parameters now supports the `repo:tag` format. Consequently, the `tag` parameter is now obsolete. Using the new format and the `tag` parameter at the same time will return an error. ## v1.13 ### Full documentation [*Docker Remote API v1.13*](/reference/api/docker_remote_api_v1.13/) ### What's new `GET /containers/(name)/json` **New!** The `HostConfig.Links` field is now filled correctly **New!** `Sockets` parameter added to the `/info` endpoint listing all the sockets the daemon is configured to listen on. `POST /containers/(name)/start` `POST /containers/(name)/stop` **New!** `start` and `stop` will now return 304 if the container's status is not modified `POST /commit` **New!** Added a `pause` parameter (default `true`) to pause the container during commit ## v1.12 ### Full documentation [*Docker Remote API v1.12*](/reference/api/docker_remote_api_v1.12/) ### What's new `POST /build` **New!** Build now has support for the `forcerm` parameter to always remove containers `GET /containers/(name)/json` `GET /images/(name)/json` **New!** All the JSON keys are now in CamelCase **New!** Trusted builds are now Automated Builds - `is_trusted` is now `is_automated`. **Removed Insert Endpoint** The `insert` endpoint has been removed. ## v1.11 ### Full documentation [*Docker Remote API v1.11*](/reference/api/docker_remote_api_v1.11/) ### What's new `GET /_ping` **New!** You can now ping the server via the `_ping` endpoint. `GET /events` **New!** You can now use the `-until` parameter to close connection after timestamp. `GET /containers/(id)/logs` This url is preferred method for getting container logs now. ## v1.10 ### Full documentation [*Docker Remote API v1.10*](/reference/api/docker_remote_api_v1.10/) ### What's new `DELETE /images/(name)` **New!** You can now use the force parameter to force delete of an image, even if it's tagged in multiple repositories. **New!** You can now use the noprune parameter to prevent the deletion of parent images `DELETE /containers/(id)` **New!** You can now use the force parameter to force delete a container, even if it is currently running ## v1.9 ### Full documentation [*Docker Remote API v1.9*](/reference/api/docker_remote_api_v1.9/) ### What's new `POST /build` **New!** This endpoint now takes a serialized ConfigFile which it uses to resolve the proper registry auth credentials for pulling the base image. Clients which previously implemented the version accepting an AuthConfig object must be updated. ## v1.8 ### Full documentation [*Docker Remote API v1.8*](/reference/api/docker_remote_api_v1.8/) ### What's new `POST /build` **New!** This endpoint now returns build status as json stream. In case of a build error, it returns the exit status of the failed command. `GET /containers/(id)/json` **New!** This endpoint now returns the host config for the container. `POST /images/create` `POST /images/(name)/insert` `POST /images/(name)/push` **New!** progressDetail object was added in the JSON. It's now possible to get the current value and the total of the progress without having to parse the string. ## v1.7 ### Full documentation [*Docker Remote API v1.7*](/reference/api/docker_remote_api_v1.7/) ### What's new `GET /images/json` The format of the json returned from this uri changed. Instead of an entry for each repo/tag on an image, each image is only represented once, with a nested attribute indicating the repo/tags that apply to that image. Instead of: HTTP/1.1 200 OK Content-Type: application/json [ { "VirtualSize": 131506275, "Size": 131506275, "Created": 1365714795, "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Tag": "12.04", "Repository": "ubuntu" }, { "VirtualSize": 131506275, "Size": 131506275, "Created": 1365714795, "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Tag": "latest", "Repository": "ubuntu" }, { "VirtualSize": 131506275, "Size": 131506275, "Created": 1365714795, "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Tag": "precise", "Repository": "ubuntu" }, { "VirtualSize": 180116135, "Size": 24653, "Created": 1364102658, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Tag": "12.10", "Repository": "ubuntu" }, { "VirtualSize": 180116135, "Size": 24653, "Created": 1364102658, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Tag": "quantal", "Repository": "ubuntu" } ] The returned json looks like this: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] `GET /images/viz` This URI no longer exists. The `images --viz` output is now generated in the client, using the `/images/json` data. ## v1.6 ### Full documentation [*Docker Remote API v1.6*](/reference/api/docker_remote_api_v1.6/) ### What's new `POST /containers/(id)/attach` **New!** You can now split stderr from stdout. This is done by prefixing a header to each transmission. See [`POST /containers/(id)/attach`]( /reference/api/docker_remote_api_v1.9/#attach-to-a-container "POST /containers/(id)/attach"). The WebSocket attach is unchanged. Note that attach calls on the previous API version didn't change. Stdout and stderr are merged. ## v1.5 ### Full documentation [*Docker Remote API v1.5*](/reference/api/docker_remote_api_v1.5/) ### What's new `POST /images/create` **New!** You can now pass registry credentials (via an AuthConfig object) through the X-Registry-Auth header `POST /images/(name)/push` **New!** The AuthConfig object now needs to be passed through the X-Registry-Auth header `GET /containers/json` **New!** The format of the Ports entry has been changed to a list of dicts each containing PublicPort, PrivatePort and Type describing a port mapping. ## v1.4 ### Full documentation [*Docker Remote API v1.4*](/reference/api/docker_remote_api_v1.4/) ### What's new `POST /images/create` **New!** When pulling a repo, all images are now downloaded in parallel. `GET /containers/(id)/top` **New!** You can now use ps args with docker top, like docker top aux `GET /events` **New!** Image's name added in the events ## v1.3 docker v0.5.0 [51f6c4a](https://github.com/docker/docker/commit/51f6c4a7372450d164c61e0054daf0223ddbd909) ### Full documentation [*Docker Remote API v1.3*](/reference/api/docker_remote_api_v1.3/) ### What's new `GET /containers/(id)/top` List the processes running inside a container. `GET /events` **New!** Monitor docker's events via streaming or via polling Builder (/build): - Simplify the upload of the build context - Simply stream a tarball instead of multipart upload with 4 intermediary buffers - Simpler, less memory usage, less disk usage and faster > **Warning**: > The /build improvements are not reverse-compatible. Pre 1.3 clients will > break on /build. List containers (/containers/json): - You can use size=1 to get the size of the containers Start containers (/containers//start): - You can now pass host-specific configuration (e.g., bind mounts) in the POST body for start calls ## v1.2 docker v0.4.2 [2e7649b](https://github.com/docker/docker/commit/2e7649beda7c820793bd46766cbc2cfeace7b168) ### Full documentation [*Docker Remote API v1.2*](/reference/api/docker_remote_api_v1.2/) ### What's new The auth configuration is now handled by the client. The client should send it's authConfig as POST on each call of `/images/(name)/push` `GET /auth` **Deprecated.** `POST /auth` Only checks the configuration but doesn't store it on the server Deleting an image is now improved, will only untag the image if it has children and remove all the untagged parents if has any. `POST /images//delete` Now returns a JSON structure with the list of images deleted/untagged. ## v1.1 docker v0.4.0 [a8ae398](https://github.com/docker/docker/commit/a8ae398bf52e97148ee7bd0d5868de2e15bd297f) ### Full documentation [*Docker Remote API v1.1*](/reference/api/docker_remote_api_v1.1/) ### What's new `POST /images/create` `POST /images/(name)/insert` `POST /images/(name)/push` Uses json stream instead of HTML hijack, it looks like this: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... ## v1.0 docker v0.3.4 [8d73740](https://github.com/docker/docker/commit/8d73740343778651c09160cde9661f5f387b36f4) ### Full documentation [*Docker Remote API v1.0*](/reference/api/docker_remote_api_v1.0/) ### What's new Initial version ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.0.md ================================================ # Docker Remote API v1.0 # 1. Brief introduction - The Remote API is replacing rcli - Default port in the docker daemon is 2375 - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport stdout stdin and stderr # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0" }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0" }, { "Id": "3176a2479c92", "Image": "centos:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0" }, { "Id": "4cb07b47f9fb", "Image": "fedora:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0" } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"ubuntu", "Volumes":{}, "VolumesFrom":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/e90e34656806/start HTTP/1.1 **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"ubuntu", "Tag":"precise", "Id":"b750fe79269d", "Created":1364102658 }, { "Repository":"ubuntu", "Tag":"12.04", "Id":"b750fe79269d", "Created":1364102658 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nubuntu",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\ncentos",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\nfedora",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK {{ TAR STREAM }} Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/centos/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"centos", "Volumes":null, "VolumesFrom":"" } } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/fedora/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry > **Example request**: > > POST /images/test/push HTTP/1.1 > > **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such image - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] :query term: term to search :statuscode 200: no error :statuscode 500: server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK {{ STREAM }} Query Parameters: - **t** – repository name to be applied to the resulting image in case of success Status Codes: - **200** – no error - **500** – server error ### Get default username and email `GET /auth` Get the default username and email **Example request**: GET /auth HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "username":"hannibal", "email":"hannibal@a-team.com" } Status Codes: - **200** – no error - **500** – server error ### Check auth configuration and store i `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":"hannibal", "password:"xxxx", "email":"hannibal@a-team.com" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes > > **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "PortSpecs":["22"] } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's ## 3.2 Hijacking In this first version of the API, some of the endpoints, like /attach, /pull or /push uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.1.md ================================================ # Docker Remote API v1.1 # 1. Brief introduction - The Remote API is replacing rcli - Default port in the docker daemon is 2375 - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport stdout stdin and stderr # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0" }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0" }, { "Id": "3176a2479c92", "Image": "centos:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0" }, { "Id": "4cb07b47f9fb", "Image": "fedora:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0" } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"ubuntu", "Volumes":{}, "VolumesFrom":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/e90e34656806/start HTTP/1.1 **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"ubuntu", "Tag":"precise", "Id":"b750fe79269d", "Created":1364102658 }, { "Repository":"ubuntu", "Tag":"12.04", "Id":"b750fe79269d", "Created":1364102658 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nubuntu",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\ncentos",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\nfedora",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/centos/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"centos", "Volumes":null, "VolumesFrom":"" } } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/fedora/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry > **Example request**: > > POST /images/test/push HTTP/1.1 > > **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such image - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] :query term: term to search :statuscode 200: no error :statuscode 500: server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ STREAM }} **Example response**: HTTP/1.1 200 OK {{ STREAM }} Query Parameters:   - **t** – tag to be applied to the resulting image in case of success Status Codes: - **200** – no error - **500** – server error ### Get default username and email `GET /auth` Get the default username and email **Example request**: GET /auth HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "username":"hannibal", "email":"hannibal@a-team.com" } Status Codes: - **200** – no error - **500** – server error ### Check auth configuration and store i `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":"hannibal", "password:"xxxx", "email":"hannibal@a-team.com" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "PortSpecs":["22"] } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's ## 3.2 Hijacking In this version of the API, /attach uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.10.md ================================================ # Docker Remote API v1.10 ## 1. Brief introduction - The Remote API has replaced rcli - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout, stdin` and `stderr` # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Image":"ubuntu", "Volumes":{ "/tmp": {} }, "WorkingDir":"", "NetworkDisabled": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Query Parameters:   - **name** – Assign the specified name to the container. Mus match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Image": "ubuntu", "Volumes": {}, "WorkingDir":"" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters:   - **ps\_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id` 's filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false, "Dns": ["8.8.8.8"], "VolumesFrom": ["parent", "other:ro"] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will wait for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1) ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id*) : Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** – 1/True/true or 0/False/false, Removes the container even if it was running. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)", "progressDetail":{"current":1}} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"] "Image":"ubuntu", "Volumes":null, "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name*) : Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_trusted": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ### 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#add)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** - remove intermediate containers after a successful build Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Volumes":{ "/tmp": {} }, "WorkingDir":"", "NetworkDisabled": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.11.md ================================================ # Docker Remote API v1.11 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Image":"ubuntu", "Volumes":{ "/tmp": {} }, "VolumesFrom":"", "WorkingDir":"", "DisableNetwork": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Query Parameters: - **name** – Assign the specified name to the container. Mus match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters:   - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, if logs=true, prin timestamps for every log line. Default false Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false, "Dns": ["8.8.8.8"], "VolumesFrom": ["parent", "other:ro"] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will wait for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1) ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** – 1/True/true or 0/False/false, Removes the container even if it was running. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"ubuntu", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_trusted": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** - remove intermediate containers after a successful build Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "Images": 16, "Driver": "btrfs", "ExecutionDriver": "native-0.1", "KernelVersion": "3.12.0-1-amd64" "Debug": false, "NFd": 11, "NGoroutines": 21, "NEventsListener": 0, "InitPath": "/usr/bin/docker", "IndexServerAddress": ["https://index.docker.io/v1/"], "MemoryLimit": true, "SwapLimit": false, "IPv4Forwarding": true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Volumes":{ "/tmp": {} }, "WorkingDir":"", "DisableNetwork": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.12.md ================================================ # Docker Remote API v1.12 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** – a JSON encoded value of the filters (a map[string][]string) to process on the images list. Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "Domainname": "", "User":"", "Memory":0, "MemorySwap":0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Image":"ubuntu", "Volumes":{ "/tmp": {} }, "WorkingDir":"", "NetworkDisabled": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Query Parameters:   - **name** – Assign the specified name to the container. Mus match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters:   - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, if logs=true, prin timestamps for every log line. Default false Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "Links":["redis3:redis"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false, "Dns": ["8.8.8.8"], "VolumesFrom": ["parent", "other:ro"] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will wait for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** – 1/True/true or 0/False/false, Removes the container even if it was running. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "Images": 16, "Driver": "btrfs", "ExecutionDriver": "native-0.1", "KernelVersion": "3.12.0-1-amd64" "Debug": false, "NFd": 11, "NGoroutines": 21, "NEventsListener": 0, "InitPath": "/usr/bin/docker", "IndexServerAddress": ["https://index.docker.io/v1/"], "MemoryLimit": true, "SwapLimit": false, "IPv4Forwarding": true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "ApiVersion": "1.12", "Version": "0.2.2", "GitCommit": "5a2a5cc+CHANGES", "GoVersion": "go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.13.md ================================================ # Docker Remote API v1.13 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "Domainname": "", "User":"", "Memory":0, "MemorySwap":0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Image":"ubuntu", "Volumes":{ "/tmp": {} }, "WorkingDir":"", "NetworkDisabled": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Query Parameters:   - **name** – Assign the specified name to the container. Mus match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": ["/name:alias"], "PublishAllPorts": false } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, show stdout log. Default false - **stderr** – 1/True/true or 0/False/false, show stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default false - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "Links":["redis3:redis"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false, "Dns": ["8.8.8.8"], "VolumesFrom": ["parent", "other:ro"] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will wait for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** – 1/True/true or 0/False/false, Removes the container even if it was running. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true ### Create an image `POST /images/create` Create an image, either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "Images": 16, "Driver": "btrfs", "ExecutionDriver": "native-0.1", "KernelVersion": "3.12.0-1-amd64" "Debug": false, "NFd": 11, "NGoroutines": 21, "NEventsListener": 0, "InitPath": "/usr/bin/docker", "IndexServerAddress": ["https://index.docker.io/v1/"], "MemoryLimit": true, "SwapLimit": false, "IPv4Forwarding": true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "ApiVersion": "1.12", "Version": "0.2.2", "GitCommit": "5a2a5cc+CHANGES", "GoVersion": "go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.14.md ================================================ # Docker Remote API v1.14 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a json encoded value of the filters (a map[string][]string) to process on the containers list. Available filters: - exited=<int> -- containers with exit code of <int> - status=(restarting|running|paused|exited) Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "Domainname": "", "User":"", "Memory":0, "MemorySwap":0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Image":"ubuntu", "Volumes":{ "/tmp": {} }, "WorkingDir":"", "NetworkDisabled": false, "ExposedPorts":{ "22/tcp": {} }, "RestartPolicy": { "Name": "always" } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **config** – the container's configuration Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": ["/name:alias"], "PublishAllPorts": false, "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"] } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, show stdout log. Default false - **stderr** – 1/True/true or 0/False/false, show stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default false - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "Links":["redis3:redis"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false, "Dns": ["8.8.8.8"], "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"] } **Example response**: HTTP/1.1 204 No Content Json Parameters: - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will wait for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true ### Create an image `POST /images/create` Create an image, either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "Images": 16, "Driver": "btrfs", "ExecutionDriver": "native-0.1", "KernelVersion": "3.12.0-1-amd64" "Debug": false, "NFd": 11, "NGoroutines": 21, "NEventsListener": 0, "InitPath": "/usr/bin/docker", "IndexServerAddress": ["https://index.docker.io/v1/"], "MemoryLimit": true, "SwapLimit": false, "IPv4Forwarding": true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "ApiVersion": "1.12", "Version": "0.2.2", "GitCommit": "5a2a5cc+CHANGES", "GoVersion": "go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.15.md ================================================ # Docker Remote API v1.15 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Names":["/boring_feynman"], "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Names":["/coolName"], "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Names":["/sleepy_dog"], "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Names":["/running_cat"], "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a json encoded value of the filters (a map[string][]string) to process on the containers list. Available filters: - exited=<int> -- containers with exit code of <int> - status=(restarting|running|paused|exited) Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "", "Image": "ubuntu", "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "SecurityOpts": [""], "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [] } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id": "f91ddc4b01e079c4481a8340bbbeca4dbd33d6e4a10662e499f8eacbb5bf252b" "Warnings": [] } Json Parameters: - **Hostname** - A string value containing the desired hostname to use for the container. - **Domainname** - A string value containing the desired domain name to use for the container. - **User** - A string value containing the user to use inside the container. - **Memory** - Memory limit in bytes. - **MemorySwap**- Total memory usage (memory + swap); set `-1` to disable swap. - **CpuShares** - An integer value containing the CPU Shares for container (ie. the relative weight vs other containers). **CpuSet** - String value containing the cgroups Cpuset to use. - **AttachStdin** - Boolean value, attaches to stdin. - **AttachStdout** - Boolean value, attaches to stdout. - **AttachStderr** - Boolean value, attaches to stderr. - **Tty** - Boolean value, Attach standard streams to a tty, including stdin if it is not closed. - **OpenStdin** - Boolean value, opens stdin, - **StdinOnce** - Boolean value, close stdin after the 1 attached client disconnects. - **Env** - A list of environment variables in the form of `VAR=value` - **Cmd** - Command to run specified as a string or an array of strings. - **Entrypoint** - Set the entrypoint for the container a string or an array of strings - **Image** - String value containing the image name to use for the container - **Volumes** – An object mapping mountpoint paths (strings) inside the container to empty objects. - **WorkingDir** - A string value containing the working dir for commands to run in. - **NetworkDisabled** - Boolean value, when true disables networking for the container - **ExposedPorts** - An object mapping ports to an empty object in the form of: `"ExposedPorts": { "/: {}" }` - **SecurityOpts**: A list of string values to customize labels for MLS systems, such as SELinux. - **HostConfig** - **Binds** – A list of volume bindings for this container. Each volume binding is a string of the form `container_path` (to create a new volume for the container), `host_path:container_path` (to bind-mount a host path into the container), or `host_path:container_path:ro` (to make the bind-mount read-only inside the container). - **Links** - A list of links for the container. Each link entry should be in the form of "container_name:alias". - **LxcConf** - LXC specific configurations. These configurations will only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. It should be specified in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **Dns** - A list of dns servers for the container to use. - **DnsSearch** - A list of DNS search domains - **ExtraHosts** - A list of hostnames/IP mappings to be added to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": ["/name:alias"], "PublishAllPorts": false, "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"] } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, show stdout log. Default false - **stderr** – 1/True/true or 0/False/false, show stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default false - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Resize a container TTY `GET /containers/(id)/resize?h=&w=` Resize the TTY of container `id` **Example request**: GET /containers/4fa6e0f0c678/resize?h=40&w=80 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain; charset=utf-8 Status Codes: - **200** – no error - **404** – No such container - **500** – bad file descriptor ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [] } **Example response**: HTTP/1.1 204 No Content Json Parameters: - **Binds** – A list of volume bindings for this container. Each volume binding is a string of the form `container_path` (to create a new volume for the container), `host_path:container_path` (to bind-mount a host path into the container), or `host_path:container_path:ro` (to make the bind-mount read-only inside the container). - **Links** - A list of links for the container. Each link entry should be of of the form "container_name:alias". - **LxcConf** - LXC specific configurations. These configurations will only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. It should be specified in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **Dns** - A list of dns servers for the container to use. - **DnsSearch** - A list of DNS search domains - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true ### Create an image `POST /images/create` Create an image, either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "Images": 16, "Driver": "btrfs", "ExecutionDriver": "native-0.1", "KernelVersion": "3.12.0-1-amd64" "Debug": false, "NFd": 11, "NGoroutines": 21, "NEventsListener": 0, "InitPath": "/usr/bin/docker", "IndexServerAddress": ["https://index.docker.io/v1/"], "MemoryLimit": true, "SwapLimit": false, "IPv4Forwarding": true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "ApiVersion": "1.12", "Version": "0.2.2", "GitCommit": "5a2a5cc+CHANGES", "GoVersion": "go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. If `name` is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the 'repositories' file in the tarball, as there were no image names referenced. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images. `GET /images/get` Get a tarball containing all images and metadata for one or more repositories. For each value of the `names` parameter: if it is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/get?names=myname%2Fmyapp%3Alatest&names=busybox **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` ### Exec Create `POST /containers/(id)/exec` Sets up an exec instance in a running container `id` **Example request**: POST /containers/e90e34656806/exec HTTP/1.1 Content-Type: application/json { "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "Cmd": [ "date" ], } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id": "f90e34656806" } Json Parameters: - **AttachStdin** - Boolean value, attaches to stdin of the exec command. - **AttachStdout** - Boolean value, attaches to stdout of the exec command. - **AttachStderr** - Boolean value, attaches to stderr of the exec command. - **Tty** - Boolean value to allocate a pseudo-TTY - **Cmd** - Command to run specified as a string or an array of strings. Status Codes: - **201** – no error - **404** – no such container ### Exec Start `POST /exec/(id)/start` Starts a previously set up exec instance `id`. If `detach` is true, this API returns after starting the `exec` command. Otherwise, this API sets up an interactive session with the `exec` command. **Example request**: POST /exec/e90e34656806/start HTTP/1.1 Content-Type: application/json { "Detach": false, "Tty": false, } **Example response**: HTTP/1.1 201 OK Content-Type: application/json {{ STREAM }} Json Parameters: - **Detach** - Detach from the exec command - **Tty** - Boolean value to allocate a pseudo-TTY Status Codes: - **201** – no error - **404** – no such exec instance **Stream details**: Similar to the stream behavior of `POST /container/(id)/attach` API ### Exec Resize `POST /exec/(id)/resize` Resizes the tty session used by the exec command `id`. This API is valid only if `tty` was specified as part of creating and starting the exec command. **Example request**: POST /exec/e90e34656806/resize HTTP/1.1 Content-Type: plain/text **Example response**: HTTP/1.1 201 OK Content-Type: plain/text Query Parameters: - **h** – height of tty session - **w** – width Status Codes: - **201** – no error - **404** – no such exec instance # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.16.md ================================================ # Docker Remote API v1.16 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Names":["/boring_feynman"], "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Names":["/coolName"], "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Names":["/sleep_dog"], "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Names":["/running_cat"], "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a json encoded value of the filters (a map[string][]string) to process on the containers list. Available filters: - exited=<int> -- containers with exit code of <int> - status=(restarting|running|paused|exited) Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "", "Image": "ubuntu", "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "SecurityOpts": [""], "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [] } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **Hostname** - A string value containing the desired hostname to use for the container. - **Domainname** - A string value containing the desired domain name to use for the container. - **User** - A string value containing the user to use inside the container. - **Memory** - Memory limit in bytes. - **MemorySwap**- Total memory usage (memory + swap); set `-1` to disable swap. - **CpuShares** - An integer value containing the CPU Shares for container (ie. the relative weight vs other containers). **CpuSet** - String value containing the cgroups Cpuset to use. - **AttachStdin** - Boolean value, attaches to stdin. - **AttachStdout** - Boolean value, attaches to stdout. - **AttachStderr** - Boolean value, attaches to stderr. - **Tty** - Boolean value, Attach standard streams to a tty, including stdin if it is not closed. - **OpenStdin** - Boolean value, opens stdin, - **StdinOnce** - Boolean value, close stdin after the 1 attached client disconnects. - **Env** - A list of environment variables in the form of `VAR=value` - **Cmd** - Command to run specified as a string or an array of strings. - **Entrypoint** - Set the entrypoint for the container a string or an array of strings - **Image** - String value containing the image name to use for the container - **Volumes** – An object mapping mountpoint paths (strings) inside the container to empty objects. - **WorkingDir** - A string value containing the working dir for commands to run in. - **NetworkDisabled** - Boolean value, when true disables networking for the container - **ExposedPorts** - An object mapping ports to an empty object in the form of: `"ExposedPorts": { "/: {}" }` - **SecurityOpts**: A list of string values to customize labels for MLS systems, such as SELinux. - **HostConfig** - **Binds** – A list of volume bindings for this container. Each volume binding is a string of the form `container_path` (to create a new volume for the container), `host_path:container_path` (to bind-mount a host path into the container), or `host_path:container_path:ro` (to make the bind-mount read-only inside the container). - **Links** - A list of links for the container. Each link entry should be in the form of "container_name:alias". - **LxcConf** - LXC specific configurations. These configurations will only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. It should be specified in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **Dns** - A list of dns servers for the container to use. - **DnsSearch** - A list of DNS search domains - **ExtraHosts** - A list of hostnames/IP mappings to be added to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": ["/name:alias"], "PublishAllPorts": false, "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"] } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, show stdout log. Default false - **stderr** – 1/True/true or 0/False/false, show stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default false - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Resize a container TTY `POST /containers/(id)/resize?h=&w=` Resize the TTY for container with `id`. The container must be restarted for the resize to take effect. **Example request**: POST /containers/4fa6e0f0c678/resize?h=40&w=80 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain; charset=utf-8 Status Codes: - **200** – no error - **404** – No such container - **500** – Cannot resize container ### Start a container `POST /containers/(id)/start` Start the container `id` > **Note**: > For backwards compatibility, this endpoint accepts a `HostConfig` as JSON-encoded request body. > See [create a container](#create-a-container) for details. **Example request**: POST /containers/(id)/start HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true ### Create an image `POST /images/create` Create an image, either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **pull** - attempt to pull the image even if an older image exists locally - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Driver":"btrfs", "DriverStatus": [[""]], "ExecutionDriver":"native-0.1", "KernelVersion":"3.12.0-1-amd64" "NCPU":1, "MemTotal":2099236864, "Name":"prod-server-42", "ID":"7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS", "Debug":false, "NFd": 11, "NGoroutines":21, "NEventsListener":0, "InitPath":"/usr/bin/docker", "InitSha1":"", "IndexServerAddress":["https://index.docker.io/v1/"], "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true, "Labels":["storage=ssd"], "DockerRootDir": "/var/lib/docker", "OperatingSystem": "Boot2Docker", } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "ApiVersion": "1.12", "Version": "0.2.2", "GitCommit": "5a2a5cc+CHANGES", "GoVersion": "go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling - **filters** – a json encoded value of the filters (a map[string][]string) to process on the event list. Available filters: - event=<string> -- event to filter - image=<string> -- image to filter - container=<string> -- container to filter Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. If `name` is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the 'repositories' file in the tarball, as there were no image names referenced. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images. `GET /images/get` Get a tarball containing all images and metadata for one or more repositories. For each value of the `names` parameter: if it is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/get?names=myname%2Fmyapp%3Alatest&names=busybox **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` ### Exec Create `POST /containers/(id)/exec` Sets up an exec instance in a running container `id` **Example request**: POST /containers/e90e34656806/exec HTTP/1.1 Content-Type: application/json { "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "Cmd": [ "date" ], } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id": "f90e34656806" } Json Parameters: - **AttachStdin** - Boolean value, attaches to stdin of the exec command. - **AttachStdout** - Boolean value, attaches to stdout of the exec command. - **AttachStderr** - Boolean value, attaches to stderr of the exec command. - **Tty** - Boolean value to allocate a pseudo-TTY - **Cmd** - Command to run specified as a string or an array of strings. Status Codes: - **201** – no error - **404** – no such container ### Exec Start `POST /exec/(id)/start` Starts a previously set up exec instance `id`. If `detach` is true, this API returns after starting the `exec` command. Otherwise, this API sets up an interactive session with the `exec` command. **Example request**: POST /exec/e90e34656806/start HTTP/1.1 Content-Type: application/json { "Detach": false, "Tty": false, } **Example response**: HTTP/1.1 201 OK Content-Type: application/json {{ STREAM }} Json Parameters: - **Detach** - Detach from the exec command - **Tty** - Boolean value to allocate a pseudo-TTY Status Codes: - **201** – no error - **404** – no such exec instance **Stream details**: Similar to the stream behavior of `POST /container/(id)/attach` API ### Exec Resize `POST /exec/(id)/resize` Resizes the tty session used by the exec command `id`. This API is valid only if `tty` was specified as part of creating and starting the exec command. **Example request**: POST /exec/e90e34656806/resize HTTP/1.1 Content-Type: plain/text **Example response**: HTTP/1.1 201 OK Content-Type: plain/text Query Parameters: - **h** – height of tty session - **w** – width Status Codes: - **201** – no error - **404** – no such exec instance ### Exec Inspect `GET /exec/(id)/json` Return low-level information about the exec command `id`. **Example request**: GET /exec/11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: plain/text { "ID" : "11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39", "Running" : false, "ExitCode" : 2, "ProcessConfig" : { "privileged" : false, "user" : "", "tty" : false, "entrypoint" : "sh", "arguments" : [ "-c", "exit 2" ] }, "OpenStdin" : false, "OpenStderr" : false, "OpenStdout" : false, "Container" : { "State" : { "Running" : true, "Paused" : false, "Restarting" : false, "OOMKilled" : false, "Pid" : 3650, "ExitCode" : 0, "Error" : "", "StartedAt" : "2014-11-17T22:26:03.717657531Z", "FinishedAt" : "0001-01-01T00:00:00Z" }, "ID" : "8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c", "Created" : "2014-11-17T22:26:03.626304998Z", "Path" : "date", "Args" : [], "Config" : { "Hostname" : "8f177a186b97", "Domainname" : "", "User" : "", "Memory" : 0, "MemorySwap" : 0, "CpuShares" : 0, "Cpuset" : "", "AttachStdin" : false, "AttachStdout" : false, "AttachStderr" : false, "PortSpecs" : null, "ExposedPorts" : null, "Tty" : false, "OpenStdin" : false, "StdinOnce" : false, "Env" : [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd" : [ "date" ], "Image" : "ubuntu", "Volumes" : null, "WorkingDir" : "", "Entrypoint" : null, "NetworkDisabled" : false, "MacAddress" : "", "OnBuild" : null, "SecurityOpt" : null }, "Image" : "5506de2b643be1e6febbf3b8a240760c6843244c41e12aa2f60ccbb7153d17f5", "NetworkSettings" : { "IPAddress" : "172.17.0.2", "IPPrefixLen" : 16, "MacAddress" : "02:42:ac:11:00:02", "Gateway" : "172.17.42.1", "Bridge" : "docker0", "PortMapping" : null, "Ports" : {} }, "ResolvConfPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/resolv.conf", "HostnamePath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hostname", "HostsPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hosts", "Name" : "/test", "Driver" : "aufs", "ExecDriver" : "native-0.2", "MountLabel" : "", "ProcessLabel" : "", "AppArmorProfile" : "", "RestartCount" : 0, "Volumes" : {}, "VolumesRW" : {} } } Status Codes: - **200** – no error - **404** – no such exec instance - **500** - server error # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.17.md ================================================ # Docker Remote API v1.17 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Names":["/boring_feynman"], "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Names":["/coolName"], "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Names":["/sleepy_dog"], "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Names":["/running_cat"], "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a json encoded value of the filters (a map[string][]string) to process on the containers list. Available filters: - exited=<int> -- containers with exit code of <int> - status=(restarting|running|paused|exited) Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "", "Image": "ubuntu", "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [] "SecurityOpt": [""], } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **Hostname** - A string value containing the desired hostname to use for the container. - **Domainname** - A string value containing the desired domain name to use for the container. - **User** - A string value containing the user to use inside the container. - **Memory** - Memory limit in bytes. - **MemorySwap**- Total memory limit (memory + swap); set `-1` to disable swap, always use this with `memory`, and make the value larger than `memory`. - **CpuShares** - An integer value containing the CPU Shares for container (ie. the relative weight vs other containers). **CpuSet** - String value containing the cgroups Cpuset to use. - **AttachStdin** - Boolean value, attaches to stdin. - **AttachStdout** - Boolean value, attaches to stdout. - **AttachStderr** - Boolean value, attaches to stderr. - **Tty** - Boolean value, Attach standard streams to a tty, including stdin if it is not closed. - **OpenStdin** - Boolean value, opens stdin, - **StdinOnce** - Boolean value, close stdin after the 1 attached client disconnects. - **Env** - A list of environment variables in the form of `VAR=value` - **Cmd** - Command to run specified as a string or an array of strings. - **Entrypoint** - Set the entrypoint for the container a string or an array of strings - **Image** - String value containing the image name to use for the container - **Volumes** – An object mapping mountpoint paths (strings) inside the container to empty objects. - **WorkingDir** - A string value containing the working dir for commands to run in. - **NetworkDisabled** - Boolean value, when true disables networking for the container - **ExposedPorts** - An object mapping ports to an empty object in the form of: `"ExposedPorts": { "/: {}" }` - **HostConfig** - **Binds** – A list of volume bindings for this container. Each volume binding is a string of the form `container_path` (to create a new volume for the container), `host_path:container_path` (to bind-mount a host path into the container), or `host_path:container_path:ro` (to make the bind-mount read-only inside the container). - **Links** - A list of links for the container. Each link entry should be in the form of "container_name:alias". - **LxcConf** - LXC specific configurations. These configurations will only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. It should be specified in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **ReadonlyRootfs** - Mount the container's root filesystem as read only. Specified as a boolean value. - **Dns** - A list of dns servers for the container to use. - **DnsSearch** - A list of DNS search domains - **ExtraHosts** - A list of hostnames/IP mappings to be added to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` - **SecurityOpt**: A list of string values to customize labels for MLS systems, such as SELinux. Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "AppArmorProfile": "", "Args": [ "-c", "exit 9" ], "Config": { "AttachStderr": true, "AttachStdin": false, "AttachStdout": true, "Cmd": [ "/bin/sh", "-c", "exit 9" ], "CpuShares": 0, "Cpuset": "", "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": null, "Hostname": "ba033ac44011", "Image": "ubuntu", "MacAddress": "", "Memory": 0, "MemorySwap": 0, "NetworkDisabled": false, "OnBuild": null, "OpenStdin": false, "PortSpecs": null, "StdinOnce": false, "Tty": false, "User": "", "Volumes": null, "WorkingDir": "" }, "Created": "2015-01-06T15:47:31.485331387Z", "Driver": "devicemapper", "ExecDriver": "native-0.2", "ExecIDs": null, "HostConfig": { "Binds": null, "CapAdd": null, "CapDrop": null, "ContainerIDFile": "", "Devices": [], "Dns": null, "DnsSearch": null, "ExtraHosts": null, "IpcMode": "", "Links": null, "LxcConf": [], "NetworkMode": "bridge", "PortBindings": {}, "Privileged": false, "ReadonlyRootfs": false, "PublishAllPorts": false, "RestartPolicy": { "MaximumRetryCount": 2, "Name": "on-failure" }, "SecurityOpt": null, "VolumesFrom": null }, "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname", "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts", "Id": "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39", "Image": "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2", "MountLabel": "", "Name": "/boring_euclid", "NetworkSettings": { "Bridge": "", "Gateway": "", "IPAddress": "", "IPPrefixLen": 0, "MacAddress": "", "PortMapping": null, "Ports": null }, "Path": "/bin/sh", "ProcessLabel": "", "ResolvConfPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf", "RestartCount": 1, "State": { "Error": "", "ExitCode": 9, "FinishedAt": "2015-01-06T15:47:32.080254511Z", "OOMKilled": false, "Paused": false, "Pid": 0, "Restarting": false, "Running": false, "StartedAt": "2015-01-06T15:47:32.072697474Z" }, "Volumes": {}, "VolumesRW": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, show stdout log. Default false - **stderr** – 1/True/true or 0/False/false, show stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default false - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container stats based on resource usage `GET /containers/(id)/stats` This endpoint returns a live stream of a container's resource usage statistics. **Example request**: GET /containers/redis1/stats HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "read" : "2015-01-08T22:57:31.547920715Z", "network" : { "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 }, "memory_stats" : { "stats" : { "total_pgmajfault" : 0, "cache" : 0, "mapped_file" : 0, "total_inactive_file" : 0, "pgpgout" : 414, "rss" : 6537216, "total_mapped_file" : 0, "writeback" : 0, "unevictable" : 0, "pgpgin" : 477, "total_unevictable" : 0, "pgmajfault" : 0, "total_rss" : 6537216, "total_rss_huge" : 6291456, "total_writeback" : 0, "total_inactive_anon" : 0, "rss_huge" : 6291456, "hierarchical_memory_limit" : 67108864, "total_pgfault" : 964, "total_active_file" : 0, "active_anon" : 6537216, "total_active_anon" : 6537216, "total_pgpgout" : 414, "total_cache" : 0, "inactive_anon" : 0, "active_file" : 0, "pgfault" : 964, "inactive_file" : 0, "total_pgpgin" : 477 }, "max_usage" : 6651904, "usage" : 6537216, "failcnt" : 0, "limit" : 67108864 }, "blkio_stats" : {}, "cpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000, "throttling_data" : {} } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Resize a container TTY `POST /containers/(id)/resize?h=&w=` Resize the TTY for container with `id`. The container must be restarted for the resize to take effect. **Example request**: POST /containers/4fa6e0f0c678/resize?h=40&w=80 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain; charset=utf-8 Status Codes: - **200** – no error - **404** – No such container - **500** – Cannot resize container ### Start a container `POST /containers/(id)/start` Start the container `id` > **Note**: > For backwards compatibility, this endpoint accepts a `HostConfig` as JSON-encoded request body. > See [create a container](#create-a-container) for details. **Example request**: POST /containers/(id)/start HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Rename a container `POST /containers/(id)/rename` Rename the container `id` to a `new_name` **Example request**: POST /containers/e90e34656806/rename?name=new_name HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **name** – new name for the container Status Codes: - **204** – no error - **404** – no such container - **409** - conflict name already assigned - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true ### Build image from a Dockerfile `POST /build` Build an image from a Dockerfile **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The input stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a build instructions file, typically called `Dockerfile` at the root of the archive. The `dockerfile` parameter may be used to specify a different build instructions file by having its value be the path to the alternate build instructions file to use. The archive may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **dockerfile** - path within the build context to the Dockerfile - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – git or HTTP/HTTPS URI build source - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **pull** - attempt to pull the image even if an older image exists locally - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Create an image `POST /images/create` Create an image, either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Driver":"btrfs", "DriverStatus": [[""]], "ExecutionDriver":"native-0.1", "KernelVersion":"3.12.0-1-amd64" "NCPU":1, "MemTotal":2099236864, "Name":"prod-server-42", "ID":"7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS", "Debug":false, "NFd": 11, "NGoroutines":21, "NEventsListener":0, "InitPath":"/usr/bin/docker", "InitSha1":"", "IndexServerAddress":["https://index.docker.io/v1/"], "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true, "Labels":["storage=ssd"], "DockerRootDir": "/var/lib/docker", "OperatingSystem": "Boot2Docker", } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "ApiVersion": "1.12", "Version": "0.2.2", "GitCommit": "5a2a5cc+CHANGES", "GoVersion": "go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, exec_create, exec_start, export, kill, oom, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling - **filters** – a json encoded value of the filters (a map[string][]string) to process on the event list. Available filters: - event=<string> -- event to filter - image=<string> -- image to filter - container=<string> -- container to filter Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. If `name` is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the 'repositories' file in the tarball, as there were no image names referenced. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images. `GET /images/get` Get a tarball containing all images and metadata for one or more repositories. For each value of the `names` parameter: if it is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/get?names=myname%2Fmyapp%3Alatest&names=busybox **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` ### Exec Create `POST /containers/(id)/exec` Sets up an exec instance in a running container `id` **Example request**: POST /containers/e90e34656806/exec HTTP/1.1 Content-Type: application/json { "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "Cmd": [ "date" ], } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id": "f90e34656806" } Json Parameters: - **AttachStdin** - Boolean value, attaches to stdin of the exec command. - **AttachStdout** - Boolean value, attaches to stdout of the exec command. - **AttachStderr** - Boolean value, attaches to stderr of the exec command. - **Tty** - Boolean value to allocate a pseudo-TTY - **Cmd** - Command to run specified as a string or an array of strings. Status Codes: - **201** – no error - **404** – no such container ### Exec Start `POST /exec/(id)/start` Starts a previously set up exec instance `id`. If `detach` is true, this API returns after starting the `exec` command. Otherwise, this API sets up an interactive session with the `exec` command. **Example request**: POST /exec/e90e34656806/start HTTP/1.1 Content-Type: application/json { "Detach": false, "Tty": false, } **Example response**: HTTP/1.1 201 OK Content-Type: application/json {{ STREAM }} Json Parameters: - **Detach** - Detach from the exec command - **Tty** - Boolean value to allocate a pseudo-TTY Status Codes: - **201** – no error - **404** – no such exec instance **Stream details**: Similar to the stream behavior of `POST /container/(id)/attach` API ### Exec Resize `POST /exec/(id)/resize` Resizes the tty session used by the exec command `id`. This API is valid only if `tty` was specified as part of creating and starting the exec command. **Example request**: POST /exec/e90e34656806/resize HTTP/1.1 Content-Type: text/plain **Example response**: HTTP/1.1 201 OK Content-Type: text/plain Query Parameters: - **h** – height of tty session - **w** – width Status Codes: - **201** – no error - **404** – no such exec instance ### Exec Inspect `GET /exec/(id)/json` Return low-level information about the exec command `id`. **Example request**: GET /exec/11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: plain/text { "ID" : "11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39", "Running" : false, "ExitCode" : 2, "ProcessConfig" : { "privileged" : false, "user" : "", "tty" : false, "entrypoint" : "sh", "arguments" : [ "-c", "exit 2" ] }, "OpenStdin" : false, "OpenStderr" : false, "OpenStdout" : false, "Container" : { "State" : { "Running" : true, "Paused" : false, "Restarting" : false, "OOMKilled" : false, "Pid" : 3650, "ExitCode" : 0, "Error" : "", "StartedAt" : "2014-11-17T22:26:03.717657531Z", "FinishedAt" : "0001-01-01T00:00:00Z" }, "ID" : "8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c", "Created" : "2014-11-17T22:26:03.626304998Z", "Path" : "date", "Args" : [], "Config" : { "Hostname" : "8f177a186b97", "Domainname" : "", "User" : "", "Memory" : 0, "MemorySwap" : 0, "CpuShares" : 0, "Cpuset" : "", "AttachStdin" : false, "AttachStdout" : false, "AttachStderr" : false, "PortSpecs" : null, "ExposedPorts" : null, "Tty" : false, "OpenStdin" : false, "StdinOnce" : false, "Env" : [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd" : [ "date" ], "Image" : "ubuntu", "Volumes" : null, "WorkingDir" : "", "Entrypoint" : null, "NetworkDisabled" : false, "MacAddress" : "", "OnBuild" : null, "SecurityOpt" : null }, "Image" : "5506de2b643be1e6febbf3b8a240760c6843244c41e12aa2f60ccbb7153d17f5", "NetworkSettings" : { "IPAddress" : "172.17.0.2", "IPPrefixLen" : 16, "MacAddress" : "02:42:ac:11:00:02", "Gateway" : "172.17.42.1", "Bridge" : "docker0", "PortMapping" : null, "Ports" : {} }, "ResolvConfPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/resolv.conf", "HostnamePath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hostname", "HostsPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hosts", "Name" : "/test", "Driver" : "aufs", "ExecDriver" : "native-0.2", "MountLabel" : "", "ProcessLabel" : "", "AppArmorProfile" : "", "RestartCount" : 0, "Volumes" : {}, "VolumesRW" : {} } } Status Codes: - **200** – no error - **404** – no such exec instance - **500** - server error # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. To hint potential proxies about connection hijacking, Docker client sends connection upgrade headers similarly to websocket. Upgrade: tcp Connection: Upgrade When Docker daemon detects the `Upgrade` header, it will switch its status code from **200 OK** to **101 UPGRADED** and resend the same headers. This might change in the future. ## 3.3 CORS Requests To set cross origin requests to the remote api, please add flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.18.md ================================================ # Docker Remote API v1.18 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `STDOUT`, `STDIN` and `STDERR`. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Names":["/boring_feynman"], "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Names":["/coolName"], "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Names":["/sleepy_dog"], "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Names":["/running_cat"], "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a json encoded value of the filters (a map[string][]string) to process on the containers list. Available filters: - exited=<int> -- containers with exit code of <int> - status=(restarting|running|paused|exited) - label=`key` or `key=value` of a container label Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "CpusetCpus": "0,1", "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [], "Ulimits": [{}], "LogConfig": { "Type": "json-file", Config: {} }, "SecurityOpt": [""], "CgroupParent": "" } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **Hostname** - A string value containing the desired hostname to use for the container. - **Domainname** - A string value containing the desired domain name to use for the container. - **User** - A string value containing the user to use inside the container. - **Memory** - Memory limit in bytes. - **MemorySwap**- Total memory limit (memory + swap); set `-1` to disable swap, always use this with `memory`, and make the value larger than `memory`. - **CpuShares** - An integer value containing the CPU Shares for container (ie. the relative weight vs other containers). - **Cpuset** - The same as CpusetCpus, but deprecated, please don't use. - **CpusetCpus** - String value containing the cgroups CpusetCpus to use. - **AttachStdin** - Boolean value, attaches to stdin. - **AttachStdout** - Boolean value, attaches to stdout. - **AttachStderr** - Boolean value, attaches to stderr. - **Tty** - Boolean value, Attach standard streams to a tty, including stdin if it is not closed. - **OpenStdin** - Boolean value, opens stdin, - **StdinOnce** - Boolean value, close stdin after the 1 attached client disconnects. - **Env** - A list of environment variables in the form of `VAR=value` - **Labels** - Adds a map of labels that to a container. To specify a map: `{"key":"value"[,"key2":"value2"]}` - **Cmd** - Command to run specified as a string or an array of strings. - **Entrypoint** - Set the entrypoint for the container a string or an array of strings - **Image** - String value containing the image name to use for the container - **Volumes** – An object mapping mountpoint paths (strings) inside the container to empty objects. - **WorkingDir** - A string value containing the working dir for commands to run in. - **NetworkDisabled** - Boolean value, when true disables networking for the container - **ExposedPorts** - An object mapping ports to an empty object in the form of: `"ExposedPorts": { "/: {}" }` - **HostConfig** - **Binds** – A list of volume bindings for this container. Each volume binding is a string of the form `container_path` (to create a new volume for the container), `host_path:container_path` (to bind-mount a host path into the container), or `host_path:container_path:ro` (to make the bind-mount read-only inside the container). - **Links** - A list of links for the container. Each link entry should be in the form of `container_name:alias`. - **LxcConf** - LXC specific configurations. These configurations will only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. It should be specified in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **ReadonlyRootfs** - Mount the container's root filesystem as read only. Specified as a boolean value. - **Dns** - A list of dns servers for the container to use. - **DnsSearch** - A list of DNS search domains - **ExtraHosts** - A list of hostnames/IP mappings to be added to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` - **Ulimits** - A list of ulimits to be set in the container, specified as `{ "Name": , "Soft": , "Hard": }`, for example: `Ulimits: { "Name": "nofile", "Soft": 1024, "Hard", 2048 }}` - **SecurityOpt**: A list of string values to customize labels for MLS systems, such as SELinux. - **LogConfig** - Log configuration for the container, specified as `{ "Type": "", "Config": {"key1": "val1"}}`. Available types: `json-file`, `syslog`, `none`. `json-file` logging driver. - **CgroupParent** - Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist. Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "AppArmorProfile": "", "Args": [ "-c", "exit 9" ], "Config": { "AttachStderr": true, "AttachStdin": false, "AttachStdout": true, "Cmd": [ "/bin/sh", "-c", "exit 9" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": null, "Hostname": "ba033ac44011", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "MacAddress": "", "NetworkDisabled": false, "OnBuild": null, "OpenStdin": false, "PortSpecs": null, "StdinOnce": false, "Tty": false, "User": "", "Volumes": null, "WorkingDir": "" }, "Created": "2015-01-06T15:47:31.485331387Z", "Driver": "devicemapper", "ExecDriver": "native-0.2", "ExecIDs": null, "HostConfig": { "Binds": null, "CapAdd": null, "CapDrop": null, "ContainerIDFile": "", "CpusetCpus": "", "CpuShares": 0, "Devices": [], "Dns": null, "DnsSearch": null, "ExtraHosts": null, "IpcMode": "", "Links": null, "LxcConf": [], "Memory": 0, "MemorySwap": 0, "NetworkMode": "bridge", "PortBindings": {}, "Privileged": false, "ReadonlyRootfs": false, "PublishAllPorts": false, "RestartPolicy": { "MaximumRetryCount": 2, "Name": "on-failure" }, "LogConfig": { "Config": null, "Type": "json-file" }, "SecurityOpt": null, "VolumesFrom": null, "Ulimits": [{}] }, "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname", "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts", "LogPath": "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log", "Id": "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39", "Image": "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2", "MountLabel": "", "Name": "/boring_euclid", "NetworkSettings": { "Bridge": "", "Gateway": "", "IPAddress": "", "IPPrefixLen": 0, "MacAddress": "", "PortMapping": null, "Ports": null }, "Path": "/bin/sh", "ProcessLabel": "", "ResolvConfPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf", "RestartCount": 1, "State": { "Error": "", "ExitCode": 9, "FinishedAt": "2015-01-06T15:47:32.080254511Z", "OOMKilled": false, "Paused": false, "Pid": 0, "Restarting": false, "Running": false, "StartedAt": "2015-01-06T15:47:32.072697474Z" }, "Volumes": {}, "VolumesRW": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get stdout and stderr logs from the container ``id`` > **Note**: > This endpoint works only for containers with `json-file` logging driver. **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default false - **stdout** – 1/True/true or 0/False/false, show stdout log. Default false - **stderr** – 1/True/true or 0/False/false, show stderr log. Default false - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default false - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Values for `Kind`: - `0`: Modify - `1`: Add - `2`: Delete Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container stats based on resource usage `GET /containers/(id)/stats` This endpoint returns a live stream of a container's resource usage statistics. > **Note**: this functionality currently only works when using the *libcontainer* exec-driver. **Example request**: GET /containers/redis1/stats HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "read" : "2015-01-08T22:57:31.547920715Z", "network" : { "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 }, "memory_stats" : { "stats" : { "total_pgmajfault" : 0, "cache" : 0, "mapped_file" : 0, "total_inactive_file" : 0, "pgpgout" : 414, "rss" : 6537216, "total_mapped_file" : 0, "writeback" : 0, "unevictable" : 0, "pgpgin" : 477, "total_unevictable" : 0, "pgmajfault" : 0, "total_rss" : 6537216, "total_rss_huge" : 6291456, "total_writeback" : 0, "total_inactive_anon" : 0, "rss_huge" : 6291456, "hierarchical_memory_limit" : 67108864, "total_pgfault" : 964, "total_active_file" : 0, "active_anon" : 6537216, "total_active_anon" : 6537216, "total_pgpgout" : 414, "total_cache" : 0, "inactive_anon" : 0, "active_file" : 0, "pgfault" : 964, "inactive_file" : 0, "total_pgpgin" : 477 }, "max_usage" : 6651904, "usage" : 6537216, "failcnt" : 0, "limit" : 67108864 }, "blkio_stats" : {}, "cpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000, "throttling_data" : {} } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Resize a container TTY `POST /containers/(id)/resize?h=&w=` Resize the TTY for container with `id`. The container must be restarted for the resize to take effect. **Example request**: POST /containers/4fa6e0f0c678/resize?h=40&w=80 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain; charset=utf-8 Status Codes: - **200** – no error - **404** – No such container - **500** – Cannot resize container ### Start a container `POST /containers/(id)/start` Start the container `id` > **Note**: > For backwards compatibility, this endpoint accepts a `HostConfig` as JSON-encoded request body. > See [create a container](#create-a-container) for details. **Example request**: POST /containers/(id)/start HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Rename a container `POST /containers/(id)/rename` Rename the container `id` to a `new_name` **Example request**: POST /containers/e90e34656806/rename?name=new_name HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **name** – new name for the container Status Codes: - **204** – no error - **404** – no such container - **409** - conflict name already assigned - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1 ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] **Example request, with digest information**: GET /images/json?digests=1 HTTP/1.1 **Example response, with digest information**: HTTP/1.1 200 OK Content-Type: application/json [ { "Created": 1420064636, "Id": "4986bf8c15363d1c5d15512d5266f8777bfba4974ac56e3270e7760f6f0a8125", "ParentId": "ea13149945cb6b1e746bf28032f02e9b5a793523481a0a18645fc77ad53c4ea2", "RepoDigests": [ "localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf" ], "RepoTags": [ "localhost:5000/test/busybox:latest", "playdate:latest" ], "Size": 0, "VirtualSize": 2429728 } ] The response shows a single image `Id` associated with two repositories (`RepoTags`): `localhost:5000/test/busybox`: and `playdate`. A caller can use either of the `RepoTags` values `localhost:5000/test/busybox:latest` or `playdate:latest` to reference the image. You can also use `RepoDigests` values to reference an image. In this response, the array has only one reference and that is to the `localhost:5000/test/busybox` repository; the `playdate` repository has no digest. You can reference this digest using the value: `localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d...` See the `docker run` and `docker build` commands for examples of digest and tag references on the command line. Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a json encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - dangling=true - label=`key` or `key=value` of an image label ### Build image from a Dockerfile `POST /build` Build an image from a Dockerfile **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The input stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a build instructions file, typically called `Dockerfile` at the root of the archive. The `dockerfile` parameter may be used to specify a different build instructions file by having its value be the path to the alternate build instructions file to use. The archive may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). The build will also be canceled if the client drops the connection by quitting or being killed. Query Parameters: - **dockerfile** - path within the build context to the Dockerfile. This is ignored if `remote` is specified and points to an individual filename. - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – A Git repository URI or HTTP/HTTPS URI build source. If the URI specifies a filename, the file's contents are placed into a file called `Dockerfile`. - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **pull** - attempt to pull the image even if an older image exists locally - **rm** - remove intermediate containers after a successful build (default behavior) - **forcerm** - always remove intermediate containers (includes rm) - **memory** - set memory limit for build - **memswap** - Total memory (memory + swap), `-1` to disable swap - **cpushares** - CPU shares (relative weight) - **cpusetcpus** - CPUs in which to allow execution, e.g., `0-3`, `0,1` Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Create an image `POST /images/create` Create an image, either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have been tagged into a repository which references that registry host name and port. This repository name should then be used in the URL. This mirrors the flow of the CLI. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – the tag to associate with the image on the registry, optional Request Headers: - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "Debug": 0, "DockerRootDir": "/var/lib/docker", "Driver": "btrfs", "DriverStatus": [[""]], "ExecutionDriver": "native-0.1", "HttpProxy": "http://test:test@localhost:8080", "HttpsProxy": "https://test:test@localhost:8080", "ID": "7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS", "IPv4Forwarding": 1, "Images": 16, "IndexServerAddress": "https://index.docker.io/v1/", "InitPath": "/usr/bin/docker", "InitSha1": "", "KernelVersion": "3.12.0-1-amd64", "Labels": [ "storage=ssd" ], "MemTotal": 2099236864, "MemoryLimit": 1, "NCPU": 1, "NEventsListener": 0, "NFd": 11, "NGoroutines": 21, "Name": "prod-server-42", "NoProxy": "9.81.1.160", "OperatingSystem": "Boot2Docker", "RegistryConfig": { "IndexConfigs": { "docker.io": { "Mirrors": null, "Name": "docker.io", "Official": true, "Secure": true } }, "InsecureRegistryCIDRs": [ "127.0.0.0/8" ] }, "SwapLimit": 0, "SystemTime": "2015-03-10T11:11:23.730591467-07:00" } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version": "1.5.0", "Os": "linux", "KernelVersion": "3.18.5-tinycore64", "GoVersion": "go1.4.1", "GitCommit": "a8a31ef", "Arch": "amd64", "ApiVersion": "1.18" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, exec_create, exec_start, export, kill, oom, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling - **until** – timestamp used for polling - **filters** – a json encoded value of the filters (a map[string][]string) to process on the event list. Available filters: - event=<string> -- event to filter - image=<string> -- image to filter - container=<string> -- container to filter Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. If `name` is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the 'repositories' file in the tarball, as there were no image names referenced. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images. `GET /images/get` Get a tarball containing all images and metadata for one or more repositories. For each value of the `names` parameter: if it is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/get?names=myname%2Fmyapp%3Alatest&names=busybox **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` ### Exec Create `POST /containers/(id)/exec` Sets up an exec instance in a running container `id` **Example request**: POST /containers/e90e34656806/exec HTTP/1.1 Content-Type: application/json { "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "Cmd": [ "date" ], } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id": "f90e34656806" "Warnings":[] } Json Parameters: - **AttachStdin** - Boolean value, attaches to stdin of the exec command. - **AttachStdout** - Boolean value, attaches to stdout of the exec command. - **AttachStderr** - Boolean value, attaches to stderr of the exec command. - **Tty** - Boolean value to allocate a pseudo-TTY - **Cmd** - Command to run specified as a string or an array of strings. Status Codes: - **201** – no error - **404** – no such container ### Exec Start `POST /exec/(id)/start` Starts a previously set up exec instance `id`. If `detach` is true, this API returns after starting the `exec` command. Otherwise, this API sets up an interactive session with the `exec` command. **Example request**: POST /exec/e90e34656806/start HTTP/1.1 Content-Type: application/json { "Detach": false, "Tty": false, } **Example response**: HTTP/1.1 201 OK Content-Type: application/json {{ STREAM }} Json Parameters: - **Detach** - Detach from the exec command - **Tty** - Boolean value to allocate a pseudo-TTY Status Codes: - **201** – no error - **404** – no such exec instance **Stream details**: Similar to the stream behavior of `POST /container/(id)/attach` API ### Exec Resize `POST /exec/(id)/resize` Resizes the tty session used by the exec command `id`. This API is valid only if `tty` was specified as part of creating and starting the exec command. **Example request**: POST /exec/e90e34656806/resize HTTP/1.1 Content-Type: text/plain **Example response**: HTTP/1.1 201 OK Content-Type: text/plain Query Parameters: - **h** – height of tty session - **w** – width Status Codes: - **201** – no error - **404** – no such exec instance ### Exec Inspect `GET /exec/(id)/json` Return low-level information about the exec command `id`. **Example request**: GET /exec/11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: plain/text { "ID" : "11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39", "Running" : false, "ExitCode" : 2, "ProcessConfig" : { "privileged" : false, "user" : "", "tty" : false, "entrypoint" : "sh", "arguments" : [ "-c", "exit 2" ] }, "OpenStdin" : false, "OpenStderr" : false, "OpenStdout" : false, "Container" : { "State" : { "Running" : true, "Paused" : false, "Restarting" : false, "OOMKilled" : false, "Pid" : 3650, "ExitCode" : 0, "Error" : "", "StartedAt" : "2014-11-17T22:26:03.717657531Z", "FinishedAt" : "0001-01-01T00:00:00Z" }, "ID" : "8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c", "Created" : "2014-11-17T22:26:03.626304998Z", "Path" : "date", "Args" : [], "Config" : { "Hostname" : "8f177a186b97", "Domainname" : "", "User" : "", "AttachStdin" : false, "AttachStdout" : false, "AttachStderr" : false, "PortSpecs" : null, "ExposedPorts" : null, "Tty" : false, "OpenStdin" : false, "StdinOnce" : false, "Env" : [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd" : [ "date" ], "Image" : "ubuntu", "Volumes" : null, "WorkingDir" : "", "Entrypoint" : null, "NetworkDisabled" : false, "MacAddress" : "", "OnBuild" : null, "SecurityOpt" : null }, "Image" : "5506de2b643be1e6febbf3b8a240760c6843244c41e12aa2f60ccbb7153d17f5", "NetworkSettings" : { "IPAddress" : "172.17.0.2", "IPPrefixLen" : 16, "MacAddress" : "02:42:ac:11:00:02", "Gateway" : "172.17.42.1", "Bridge" : "docker0", "PortMapping" : null, "Ports" : {} }, "ResolvConfPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/resolv.conf", "HostnamePath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hostname", "HostsPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hosts", "LogPath": "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log", "Name" : "/test", "Driver" : "aufs", "ExecDriver" : "native-0.2", "MountLabel" : "", "ProcessLabel" : "", "AppArmorProfile" : "", "RestartCount" : 0, "Volumes" : {}, "VolumesRW" : {} } } Status Codes: - **200** – no error - **404** – no such exec instance - **500** - server error # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. To hint potential proxies about connection hijacking, Docker client sends connection upgrade headers similarly to websocket. Upgrade: tcp Connection: Upgrade When Docker daemon detects the `Upgrade` header, it will switch its status code from **200 OK** to **101 UPGRADED** and resend the same headers. This might change in the future. ## 3.3 CORS Requests To set cross origin requests to the remote api please give values to "--api-cors-header" when running docker in daemon mode. Set * will allow all, default or blank means CORS disabled $ docker -d -H="192.168.1.9:2375" --api-cors-header="http://foo.bar" ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.19.md ================================================ # Docker Remote API v1.19 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST. However, for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout`, `stdin` and `stderr`. - When the client API version is newer than the daemon's, these calls return an HTTP `400 Bad Request` error message. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Names":["/boring_feynman"], "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Names":["/coolName"], "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Names":["/sleepy_dog"], "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Names":["/running_cat"], "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a JSON encoded value of the filters (a `map[string][]string`) to process on the containers list. Available filters: - `exited=`; -- containers with exit code of `` ; - `status=`(`restarting`|`running`|`paused`|`exited`) - `label=key` or `key=value` of a container label Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "CpuPeriod": 100000, "CpusetCpus": "0,1", "CpusetMems": "0,1", "BlkioWeight": 300, "OomKillDisable": false, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [], "Ulimits": [{}], "LogConfig": { "Type": "json-file", "Config": {} }, "SecurityOpt": [""], "CgroupParent": "" } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **Hostname** - A string value containing the hostname to use for the container. - **Domainname** - A string value containing the domain name to use for the container. - **User** - A string value specifying the user inside the container. - **Memory** - Memory limit in bytes. - **MemorySwap**- Total memory limit (memory + swap); set `-1` to disable swap You must use this with `memory` and make the swap value larger than `memory`. - **CpuShares** - An integer value containing the container's CPU Shares (ie. the relative weight vs other containers). - **CpuPeriod** - The length of a CPU period in microseconds. - **Cpuset** - Deprecated please don't use. Use `CpusetCpus` instead. - **CpusetCpus** - String value containing the `cgroups CpusetCpus` to use. - **CpusetMems** - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. - **BlkioWeight** - Block IO weight (relative weight) accepts a weight value between 10 and 1000. - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. - **AttachStdin** - Boolean value, attaches to `stdin`. - **AttachStdout** - Boolean value, attaches to `stdout`. - **AttachStderr** - Boolean value, attaches to `stderr`. - **Tty** - Boolean value, Attach standard streams to a `tty`, including `stdin` if it is not closed. - **OpenStdin** - Boolean value, opens stdin, - **StdinOnce** - Boolean value, close `stdin` after the 1 attached client disconnects. - **Env** - A list of environment variables in the form of `VAR=value` - **Labels** - Adds a map of labels to a container. To specify a map: `{"key":"value"[,"key2":"value2"]}` - **Cmd** - Command to run specified as a string or an array of strings. - **Entrypoint** - Set the entry point for the container as a string or an array of strings. - **Image** - A string specifying the image name to use for the container. - **Volumes** – An object mapping mount point paths (strings) inside the container to empty objects. - **WorkingDir** - A string specifying the working directory for commands to run in. - **NetworkDisabled** - Boolean value, when true disables networking for the container - **ExposedPorts** - An object mapping ports to an empty object in the form of: `"ExposedPorts": { "/: {}" }` - **HostConfig** - **Binds** – A list of volume bindings for this container. Each volume binding is a string in one of these forms: + `container_path` to create a new volume for the container + `host_path:container_path` to bind-mount a host path into the container + `host_path:container_path:ro` to make the bind-mount read-only inside the container. - **Links** - A list of links for the container. Each link entry should be in the form of `container_name:alias`. - **LxcConf** - LXC specific configurations. These configurations only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. A JSON object in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **ReadonlyRootfs** - Mount the container's root filesystem as read only. Specified as a boolean value. - **Dns** - A list of DNS servers for the container to use. - **DnsSearch** - A list of DNS search domains - **ExtraHosts** - A list of hostnames/IP mappings to add to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified as a JSON object in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` - **Ulimits** - A list of ulimits to set in the container, specified as `{ "Name": , "Soft": , "Hard": }`, for example: `Ulimits: { "Name": "nofile", "Soft": 1024, "Hard", 2048 }}` - **SecurityOpt**: A list of string values to customize labels for MLS systems, such as SELinux. - **LogConfig** - Log configuration for the container, specified as a JSON object in the form `{ "Type": "", "Config": {"key1": "val1"}}`. Available types: `json-file`, `syslog`, `journald`, `none`. `syslog` available options are: `address`. - **CgroupParent** - Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist. Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "AppArmorProfile": "", "Args": [ "-c", "exit 9" ], "Config": { "AttachStderr": true, "AttachStdin": false, "AttachStdout": true, "Cmd": [ "/bin/sh", "-c", "exit 9" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": null, "Hostname": "ba033ac44011", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "MacAddress": "", "NetworkDisabled": false, "OnBuild": null, "OpenStdin": false, "PortSpecs": null, "StdinOnce": false, "Tty": false, "User": "", "Volumes": null, "WorkingDir": "" }, "Created": "2015-01-06T15:47:31.485331387Z", "Driver": "devicemapper", "ExecDriver": "native-0.2", "ExecIDs": null, "HostConfig": { "Binds": null, "BlkioWeight": 0, "CapAdd": null, "CapDrop": null, "ContainerIDFile": "", "CpusetCpus": "", "CpusetMems": "", "CpuShares": 0, "CpuPeriod": 100000, "Devices": [], "Dns": null, "DnsSearch": null, "ExtraHosts": null, "IpcMode": "", "Links": null, "LxcConf": [], "Memory": 0, "MemorySwap": 0, "OomKillDisable": false, "NetworkMode": "bridge", "PortBindings": {}, "Privileged": false, "ReadonlyRootfs": false, "PublishAllPorts": false, "RestartPolicy": { "MaximumRetryCount": 2, "Name": "on-failure" }, "LogConfig": { "Config": null, "Type": "json-file" }, "SecurityOpt": null, "VolumesFrom": null, "Ulimits": [{}] }, "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname", "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts", "LogPath": "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log", "Id": "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39", "Image": "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2", "MountLabel": "", "Name": "/boring_euclid", "NetworkSettings": { "Bridge": "", "Gateway": "", "IPAddress": "", "IPPrefixLen": 0, "MacAddress": "", "PortMapping": null, "Ports": null }, "Path": "/bin/sh", "ProcessLabel": "", "ResolvConfPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf", "RestartCount": 1, "State": { "Error": "", "ExitCode": 9, "FinishedAt": "2015-01-06T15:47:32.080254511Z", "OOMKilled": false, "Paused": false, "Pid": 0, "Restarting": false, "Running": false, "StartedAt": "2015-01-06T15:47:32.072697474Z" }, "Volumes": {}, "VolumesRW": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get `stdout` and `stderr` logs from the container ``id`` > **Note**: > This endpoint works only for containers with `json-file` logging driver. **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10&since=1428990821 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default `false`. - **stdout** – 1/True/true or 0/False/false, show `stdout` log. Default `false`. - **stderr** – 1/True/true or 0/False/false, show `stderr` log. Default `false`. - **since** – UNIX timestamp (integer) to filter logs. Specifying a timestamp will only output log-entries since that timestamp. Default: 0 (unfiltered) - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default `false`. - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all. Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Values for `Kind`: - `0`: Modify - `1`: Add - `2`: Delete Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container stats based on resource usage `GET /containers/(id)/stats` This endpoint returns a live stream of a container's resource usage statistics. > **Note**: this functionality currently only works when using the *libcontainer* exec-driver. **Example request**: GET /containers/redis1/stats HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "read" : "2015-01-08T22:57:31.547920715Z", "network" : { "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 }, "memory_stats" : { "stats" : { "total_pgmajfault" : 0, "cache" : 0, "mapped_file" : 0, "total_inactive_file" : 0, "pgpgout" : 414, "rss" : 6537216, "total_mapped_file" : 0, "writeback" : 0, "unevictable" : 0, "pgpgin" : 477, "total_unevictable" : 0, "pgmajfault" : 0, "total_rss" : 6537216, "total_rss_huge" : 6291456, "total_writeback" : 0, "total_inactive_anon" : 0, "rss_huge" : 6291456, "hierarchical_memory_limit" : 67108864, "total_pgfault" : 964, "total_active_file" : 0, "active_anon" : 6537216, "total_active_anon" : 6537216, "total_pgpgout" : 414, "total_cache" : 0, "inactive_anon" : 0, "active_file" : 0, "pgfault" : 964, "inactive_file" : 0, "total_pgpgin" : 477 }, "max_usage" : 6651904, "usage" : 6537216, "failcnt" : 0, "limit" : 67108864 }, "blkio_stats" : {}, "cpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000, "throttling_data" : {} } } Query Parameters: - **stream** – 1/True/true or 0/False/false, pull stats once then disconnect. Default `true`. Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Resize a container TTY `POST /containers/(id)/resize?h=&w=` Resize the TTY for container with `id`. You must restart the container for the resize to take effect. **Example request**: POST /containers/4fa6e0f0c678/resize?h=40&w=80 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain; charset=utf-8 Status Codes: - **200** – no error - **404** – No such container - **500** – Cannot resize container ### Start a container `POST /containers/(id)/start` Start the container `id` > **Note**: > For backwards compatibility, this endpoint accepts a `HostConfig` as JSON-encoded request body. > See [create a container](#create-a-container) for details. **Example request**: POST /containers/(id)/start HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like `SIGINT`. When not set, `SIGKILL` is assumed and the call waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Rename a container `POST /containers/(id)/rename` Rename the container `id` to a `new_name` **Example request**: POST /containers/e90e34656806/rename?name=new_name HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **name** – new name for the container Status Codes: - **204** – no error - **404** – no such container - **409** - conflict name already assigned - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default `false`. - **stream** – 1/True/true or 0/False/false, return stream. Default `false`. - **stdin** – 1/True/true or 0/False/false, if `stream=true`, attach to `stdin`. Default `false`. - **stdout** – 1/True/true or 0/False/false, if `logs=true`, return `stdout` log, if `stream=true`, attach to `stdout`. Default `false`. - **stderr** – 1/True/true or 0/False/false, if `logs=true`, return `stderr` log, if `stream=true`, attach to `stderr`. Default `false`. Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's `stdin`. When the TTY is disabled, then the stream is multiplexed to separate `stdout` and `stderr`. The format is a **Header** and a **Payload** (frame). **HEADER** The header contains the information which the stream writes (`stdout` or `stderr`). It also contains the size of the associated frame encoded in the last four bytes (`uint32`). It is encoded on the first eight bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: `stdin` (is written on `stdout`) - 1: `stdout` - 2: `stderr` `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of the `uint32` size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read eight bytes. 2. Choose `stdout` or `stderr` depending on the first byte. 3. Extract the frame size from the last four bytes. 4. Read the extracted size and output it on the correct output. 5. Goto 1. ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default `false`. - **stream** – 1/True/true or 0/False/false, return stream. Default `false`. - **stdin** – 1/True/true or 0/False/false, if `stream=true`, attach to `stdin`. Default `false`. - **stdout** – 1/True/true or 0/False/false, if `logs=true`, return `stdout` log, if `stream=true`, attach to `stdout`. Default `false`. - **stderr** – 1/True/true or 0/False/false, if `logs=true`, return `stderr` log, if `stream=true`, attach to `stderr`. Default `false`. Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default `false`. - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default `false`. Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] **Example request, with digest information**: GET /images/json?digests=1 HTTP/1.1 **Example response, with digest information**: HTTP/1.1 200 OK Content-Type: application/json [ { "Created": 1420064636, "Id": "4986bf8c15363d1c5d15512d5266f8777bfba4974ac56e3270e7760f6f0a8125", "ParentId": "ea13149945cb6b1e746bf28032f02e9b5a793523481a0a18645fc77ad53c4ea2", "RepoDigests": [ "localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf" ], "RepoTags": [ "localhost:5000/test/busybox:latest", "playdate:latest" ], "Size": 0, "VirtualSize": 2429728 } ] The response shows a single image `Id` associated with two repositories (`RepoTags`): `localhost:5000/test/busybox`: and `playdate`. A caller can use either of the `RepoTags` values `localhost:5000/test/busybox:latest` or `playdate:latest` to reference the image. You can also use `RepoDigests` values to reference an image. In this response, the array has only one reference and that is to the `localhost:5000/test/busybox` repository; the `playdate` repository has no digest. You can reference this digest using the value: `localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d...` See the `docker run` and `docker build` commands for examples of digest and tag references on the command line. Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a JSON encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - `dangling=true` - `label=key` or `key=value` of an image label ### Build image from a Dockerfile `POST /build` Build an image from a Dockerfile **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The input stream must be a `tar` archive compressed with one of the following algorithms: `identity` (no compression), `gzip`, `bzip2`, `xz`. The archive must include a build instructions file, typically called `Dockerfile` at the archive's root. The `dockerfile` parameter may be used to specify a different build instructions file. To do this, its value must be the path to the alternate build instructions file to use. The archive may include any number of other files, which are accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). The build is canceled if the client drops the connection by quitting or being killed. Query Parameters: - **dockerfile** - Path within the build context to the `Dockerfile`. This is ignored if `remote` is specified and points to an external `Dockerfile`. - **t** – Repository name (and optionally a tag) to be applied to the resulting image in case of success. - **remote** – A Git repository URI or HTTP/HTTPS context URI. If the URI points to a single text file, the file's contents are placed into a file called `Dockerfile` and the image is built from that file. If the URI points to a tarball, the file is downloaded by the daemon and the contents therein used as the context for the build. If the URI points to a tarball and the `dockerfile` parameter is also specified, there must be a file with the corresponding path inside the tarball. - **q** – Suppress verbose build output. - **nocache** – Do not use the cache when building the image. - **pull** - Attempt to pull the image even if an older image exists locally. - **rm** - Remove intermediate containers after a successful build (default behavior). - **forcerm** - Always remove intermediate containers (includes `rm`). - **memory** - Set memory limit for build. - **memswap** - Total memory (memory + swap), `-1` to disable swap. - **cpushares** - CPU shares (relative weight). - **cpusetcpus** - CPUs in which to allow execution (e.g., `0-3`, `0,1`). Request Headers: - **Content-type** – Set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Create an image `POST /images/create` Create an image either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – Name of the image to pull. - **fromSrc** – Source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. - **repo** – Repository name. - **tag** – Tag. - **registry** – The registry to pull from. Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710", "Created": 1398108230, "CreatedBy": "/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /", "Tags": [ "ubuntu:lucid", "ubuntu:10.04" ], "Size": 182964289, "Comment": "" }, { "Id": "6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8", "Created": 1398108222, "CreatedBy": "/bin/sh -c #(nop) MAINTAINER Tianon Gravi - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/", "Tags": null, "Size": 0, "Comment": "" }, { "Id": "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158", "Created": 1371157430, "CreatedBy": "", "Tags": [ "scratch12:latest", "scratch:latest" ], "Size": 0, "Comment": "Imported from -" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have a tag into a repository which references that registry `hostname` and `port`. This repository name should then be used in the URL. This duplicates the command line's flow. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – The tag to associate with the image on the registry. This is optional. Request Headers: - **X-Registry-Auth** – Include a base64-encoded AuthConfig. object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). This API returns both `is_trusted` and `is_automated` images. Currently, they are considered identical. In the future, the `is_trusted` property will be deprecated and replaced by the `is_automated` property. > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "star_count": 12, "is_official": false, "name": "wma55/u1210sshd", "is_trusted": false, "is_automated": false, "description": "", }, { "star_count": 10, "is_official": false, "name": "jdswinbank/sshd", "is_trusted": false, "is_automated": false, "description": "", }, { "star_count": 18, "is_official": false, "name": "vgauthier/sshd", "is_trusted": false, "is_automated": false, "description": "", } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "CpuCfsPeriod": true, "CpuCfsQuota": true, "Debug": false, "DockerRootDir": "/var/lib/docker", "Driver": "btrfs", "DriverStatus": [[""]], "ExecutionDriver": "native-0.1", "ExperimentalBuild": false, "HttpProxy": "http://test:test@localhost:8080", "HttpsProxy": "https://test:test@localhost:8080", "ID": "7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS", "IPv4Forwarding": true, "Images": 16, "IndexServerAddress": "https://index.docker.io/v1/", "InitPath": "/usr/bin/docker", "InitSha1": "", "KernelVersion": "3.12.0-1-amd64", "Labels": [ "storage=ssd" ], "MemTotal": 2099236864, "MemoryLimit": true, "NCPU": 1, "NEventsListener": 0, "NFd": 11, "NGoroutines": 21, "Name": "prod-server-42", "NoProxy": "9.81.1.160", "OomKillDisable": true, "OperatingSystem": "Boot2Docker", "RegistryConfig": { "IndexConfigs": { "docker.io": { "Mirrors": null, "Name": "docker.io", "Official": true, "Secure": true } }, "InsecureRegistryCIDRs": [ "127.0.0.0/8" ] }, "SwapLimit": false, "SystemTime": "2015-03-10T11:11:23.730591467-07:00" } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version": "1.5.0", "Os": "linux", "KernelVersion": "3.18.5-tinycore64", "GoVersion": "go1.4.1", "GitCommit": "a8a31ef", "Arch": "amd64", "ApiVersion": "1.19" } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Volumes": { "/tmp": {} }, "Labels": { "key1": "value1", "key2": "value2" }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers report the following events: attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause and Docker images report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – Timestamp used for polling - **until** – Timestamp used for polling - **filters** – A json encoded value of the filters (a map[string][]string) to process on the event list. Available filters: - `event=`; -- event to filter - `image=`; -- image to filter - `container=`; -- container to filter Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. If `name` is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the 'repositories' file in the tarball, as there were no image names referenced. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images. `GET /images/get` Get a tarball containing all images and metadata for one or more repositories. For each value of the `names` parameter: if it is a specific name and tag (e.g. `ubuntu:latest`), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/get?names=myname%2Fmyapp%3Alatest&names=busybox **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into a Docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing these files: - `VERSION`: currently `1.0` - the file format version - `json`: detailed layer information, similar to `docker inspect layer_id` - `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file contains `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, the tarball should also include a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` ### Exec Create `POST /containers/(id)/exec` Sets up an exec instance in a running container `id` **Example request**: POST /containers/e90e34656806/exec HTTP/1.1 Content-Type: application/json { "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "Cmd": [ "date" ], } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id": "f90e34656806" "Warnings":[] } Json Parameters: - **AttachStdin** - Boolean value, attaches to `stdin` of the `exec` command. - **AttachStdout** - Boolean value, attaches to `stdout` of the `exec` command. - **AttachStderr** - Boolean value, attaches to `stderr` of the `exec` command. - **Tty** - Boolean value to allocate a pseudo-TTY. - **Cmd** - Command to run specified as a string or an array of strings. Status Codes: - **201** – no error - **404** – no such container ### Exec Start `POST /exec/(id)/start` Starts a previously set up `exec` instance `id`. If `detach` is true, this API returns after starting the `exec` command. Otherwise, this API sets up an interactive session with the `exec` command. **Example request**: POST /exec/e90e34656806/start HTTP/1.1 Content-Type: application/json { "Detach": false, "Tty": false, } **Example response**: HTTP/1.1 201 OK Content-Type: application/json {{ STREAM }} Json Parameters: - **Detach** - Detach from the `exec` command. - **Tty** - Boolean value to allocate a pseudo-TTY. Status Codes: - **201** – no error - **404** – no such exec instance **Stream details**: Similar to the stream behavior of `POST /container/(id)/attach` API ### Exec Resize `POST /exec/(id)/resize` Resizes the `tty` session used by the `exec` command `id`. This API is valid only if `tty` was specified as part of creating and starting the `exec` command. **Example request**: POST /exec/e90e34656806/resize HTTP/1.1 Content-Type: text/plain **Example response**: HTTP/1.1 201 OK Content-Type: text/plain Query Parameters: - **h** – height of `tty` session - **w** – width Status Codes: - **201** – no error - **404** – no such exec instance ### Exec Inspect `GET /exec/(id)/json` Return low-level information about the `exec` command `id`. **Example request**: GET /exec/11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: plain/text { "ID" : "11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39", "Running" : false, "ExitCode" : 2, "ProcessConfig" : { "privileged" : false, "user" : "", "tty" : false, "entrypoint" : "sh", "arguments" : [ "-c", "exit 2" ] }, "OpenStdin" : false, "OpenStderr" : false, "OpenStdout" : false, "Container" : { "State" : { "Running" : true, "Paused" : false, "Restarting" : false, "OOMKilled" : false, "Pid" : 3650, "ExitCode" : 0, "Error" : "", "StartedAt" : "2014-11-17T22:26:03.717657531Z", "FinishedAt" : "0001-01-01T00:00:00Z" }, "ID" : "8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c", "Created" : "2014-11-17T22:26:03.626304998Z", "Path" : "date", "Args" : [], "Config" : { "Hostname" : "8f177a186b97", "Domainname" : "", "User" : "", "AttachStdin" : false, "AttachStdout" : false, "AttachStderr" : false, "PortSpecs": null, "ExposedPorts" : null, "Tty" : false, "OpenStdin" : false, "StdinOnce" : false, "Env" : [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd" : [ "date" ], "Image" : "ubuntu", "Volumes" : null, "WorkingDir" : "", "Entrypoint" : null, "NetworkDisabled" : false, "MacAddress" : "", "OnBuild" : null, "SecurityOpt" : null }, "Image" : "5506de2b643be1e6febbf3b8a240760c6843244c41e12aa2f60ccbb7153d17f5", "NetworkSettings" : { "IPAddress" : "172.17.0.2", "IPPrefixLen" : 16, "MacAddress" : "02:42:ac:11:00:02", "Gateway" : "172.17.42.1", "Bridge" : "docker0", "PortMapping" : null, "Ports" : {} }, "ResolvConfPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/resolv.conf", "HostnamePath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hostname", "HostsPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hosts", "LogPath": "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log", "Name" : "/test", "Driver" : "aufs", "ExecDriver" : "native-0.2", "MountLabel" : "", "ProcessLabel" : "", "AppArmorProfile" : "", "RestartCount" : 0, "Volumes" : {}, "VolumesRW" : {} } } Status Codes: - **200** – no error - **404** – no such exec instance - **500** - server error # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it. - Then, retry to create the container. - Start the container. - If you are not in detached mode: - Attach to the container, using `logs=1` (to have `stdout` and `stderr` from the container's start) and `stream=1` - If in detached mode or only `stdin` is attached, display the container's id. ## 3.2 Hijacking In this version of the API, `/attach`, uses hijacking to transport `stdin`, `stdout`, and `stderr` on the same socket. To hint potential proxies about connection hijacking, Docker client sends connection upgrade headers similarly to websocket. Upgrade: tcp Connection: Upgrade When Docker daemon detects the `Upgrade` header, it switches its status code from **200 OK** to **101 UPGRADED** and resends the same headers. ## 3.3 CORS Requests To set cross origin requests to the remote api please give values to `--api-cors-header` when running Docker in daemon mode. Set * (asterisk) allows all, default or blank means CORS disabled $ docker -d -H="192.168.1.9:2375" --api-cors-header="http://foo.bar" ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.2.md ================================================ # Docker Remote API v1.2 # 1. Brief introduction - The Remote API is replacing rcli - Default port in the docker daemon is 2375 - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport stdout stdin and stderr # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "3176a2479c92", "Image": "centos:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "fedora:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"ubuntu", "Volumes":{}, "VolumesFrom":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/e90e34656806/start HTTP/1.1 **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"ubuntu", "Tag":"precise", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 }, { "Repository":"ubuntu", "Tag":"12.04", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nubuntu",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\ncentos",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\nfedora",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/centos/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"centos", "Volumes":null, "VolumesFrom":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/fedora/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id":"b750fe79269d", "Tag":["ubuntu:latest"], "Created":1364102658, "CreatedBy":"/bin/bash" }, { "Id":"27cf78414709", "Created":1364068391, "CreatedBy":"" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry > **Example request**: > > POST /images/test/push HTTP/1.1 > {{ authConfig }} > > **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **204** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] :query term: term to search :statuscode 200: no error :statuscode 500: server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: text/plain {{ STREAM }} Query Parameters: - **t** – repository name to be applied to the resulting image in case of success - **remote** – resource to fetch, as URI Status Codes: - **200** – no error - **500** – server error {{ STREAM }} is the raw text output of the build command. It uses the HTTP Hijack method in order to stream. ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":"hannibal", "password:"xxxx", "email":"hannibal@a-team.com" } **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Status": "Login Succeeded" } Status Codes: - **200** – no error - **204** – no error - **401** – unauthorized - **403** – forbidden - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "PortSpecs":["22"] } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. > docker -d -H="[tcp://192.168.1.9:2375](tcp://192.168.1.9:2375)" > -api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.20.md ================================================ # Docker Remote API v1.20 ## 1. Brief introduction - The Remote API has replaced `rcli`. - The daemon listens on `unix:///var/run/docker.sock` but you can [Bind Docker to another host/port or a Unix socket]( /articles/basics/#bind-docker-to-another-hostport-or-a-unix-socket). - The API tends to be REST. However, for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout`, `stdin` and `stderr`. - When the client API version is newer than the daemon's, these calls return an HTTP `400 Bad Request` error message. # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Names":["/boring_feynman"], "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Names":["/coolName"] "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Names":["/sleepy_dog"] "Image": "ubuntu:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Names":["/running_cat"] "Image": "ubuntu:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes - **filters** - a JSON encoded value of the filters (a `map[string][]string`) to process on the containers list. Available filters: - `exited=`; -- containers with exit code of `` ; - `status=`(`created`|`restarting`|`running`|`paused`|`exited`) - `label=key` or `key=value` of a container label Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Mounts": [ { "Source": "/data", "Destination": "/data", "Mode": "ro,Z", "RW": false } ], "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "CpuPeriod": 100000, "CpusetCpus": "0,1", "CpusetMems": "0,1", "BlkioWeight": 300, "MemorySwappiness": 60, "OomKillDisable": false, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [], "Ulimits": [{}], "LogConfig": { "Type": "json-file", "Config": {} }, "SecurityOpt": [""], "CgroupParent": "" } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **Hostname** - A string value containing the hostname to use for the container. - **Domainname** - A string value containing the domain name to use for the container. - **User** - A string value specifying the user inside the container. - **Memory** - Memory limit in bytes. - **MemorySwap**- Total memory limit (memory + swap); set `-1` to disable swap You must use this with `memory` and make the swap value larger than `memory`. - **CpuShares** - An integer value containing the container's CPU Shares (ie. the relative weight vs other containers). - **CpuPeriod** - The length of a CPU period in microseconds. - **Cpuset** - Deprecated please don't use. Use `CpusetCpus` instead. - **CpusetCpus** - String value containing the `cgroups CpusetCpus` to use. - **CpusetMems** - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. - **BlkioWeight** - Block IO weight (relative weight) accepts a weight value between 10 and 1000. - **MemorySwappiness** - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. - **OomKillDisable** - Boolean value, whether to disable OOM Killer for the container or not. - **AttachStdin** - Boolean value, attaches to `stdin`. - **AttachStdout** - Boolean value, attaches to `stdout`. - **AttachStderr** - Boolean value, attaches to `stderr`. - **Tty** - Boolean value, Attach standard streams to a `tty`, including `stdin` if it is not closed. - **OpenStdin** - Boolean value, opens stdin, - **StdinOnce** - Boolean value, close `stdin` after the 1 attached client disconnects. - **Env** - A list of environment variables in the form of `VAR=value` - **Labels** - Adds a map of labels to a container. To specify a map: `{"key":"value"[,"key2":"value2"]}` - **Cmd** - Command to run specified as a string or an array of strings. - **Entrypoint** - Set the entry point for the container as a string or an array of strings. - **Image** - A string specifying the image name to use for the container. - **Mounts** - An array of mount points in the container. - **WorkingDir** - A string specifying the working directory for commands to run in. - **NetworkDisabled** - Boolean value, when true disables networking for the container - **ExposedPorts** - An object mapping ports to an empty object in the form of: `"ExposedPorts": { "/: {}" }` - **HostConfig** - **Binds** – A list of volume bindings for this container. Each volume binding is a string in one of these forms: + `container_path` to create a new volume for the container + `host_path:container_path` to bind-mount a host path into the container + `host_path:container_path:ro` to make the bind-mount read-only inside the container. - **Links** - A list of links for the container. Each link entry should be in the form of `container_name:alias`. - **LxcConf** - LXC specific configurations. These configurations only work when using the `lxc` execution driver. - **PortBindings** - A map of exposed container ports and the host port they should map to. A JSON object in the form `{ /: [{ "HostPort": "" }] }` Take note that `port` is specified as a string and not an integer value. - **PublishAllPorts** - Allocates a random host port for all of a container's exposed ports. Specified as a boolean value. - **Privileged** - Gives the container full access to the host. Specified as a boolean value. - **ReadonlyRootfs** - Mount the container's root filesystem as read only. Specified as a boolean value. - **Dns** - A list of DNS servers for the container to use. - **DnsSearch** - A list of DNS search domains - **ExtraHosts** - A list of hostnames/IP mappings to add to the container's `/etc/hosts` file. Specified in the form `["hostname:IP"]`. - **VolumesFrom** - A list of volumes to inherit from another container. Specified in the form `[:]` - **CapAdd** - A list of kernel capabilities to add to the container. - **Capdrop** - A list of kernel capabilities to drop from the container. - **RestartPolicy** – The behavior to apply when the container exits. The value is an object with a `Name` property of either `"always"` to always restart or `"on-failure"` to restart only when the container exit code is non-zero. If `on-failure` is used, `MaximumRetryCount` controls the number of times to retry before giving up. The default is not to restart. (optional) An ever increasing delay (double the previous delay, starting at 100mS) is added before each restart to prevent flooding the server. - **NetworkMode** - Sets the networking mode for the container. Supported values are: `bridge`, `host`, and `container:` - **Devices** - A list of devices to add to the container specified as a JSON object in the form `{ "PathOnHost": "/dev/deviceName", "PathInContainer": "/dev/deviceName", "CgroupPermissions": "mrw"}` - **Ulimits** - A list of ulimits to set in the container, specified as `{ "Name": , "Soft": , "Hard": }`, for example: `Ulimits: { "Name": "nofile", "Soft": 1024, "Hard", 2048 }}` - **SecurityOpt**: A list of string values to customize labels for MLS systems, such as SELinux. - **LogConfig** - Log configuration for the container, specified as a JSON object in the form `{ "Type": "", "Config": {"key1": "val1"}}`. Available types: `json-file`, `syslog`, `journald`, `gelf`, `none`. `json-file` logging driver. - **CgroupParent** - Path to `cgroups` under which the container's `cgroup` is created. If the path is not absolute, the path is considered to be relative to the `cgroups` path of the init process. Cgroups are created if they do not already exist. Query Parameters: - **name** – Assign the specified name to the container. Must match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "AppArmorProfile": "", "Args": [ "-c", "exit 9" ], "Config": { "AttachStderr": true, "AttachStdin": false, "AttachStdout": true, "Cmd": [ "/bin/sh", "-c", "exit 9" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": null, "Hostname": "ba033ac44011", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "MacAddress": "", "NetworkDisabled": false, "OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": null, "WorkingDir": "" }, "Created": "2015-01-06T15:47:31.485331387Z", "Driver": "devicemapper", "ExecDriver": "native-0.2", "ExecIDs": null, "HostConfig": { "Binds": null, "BlkioWeight": 0, "CapAdd": null, "CapDrop": null, "ContainerIDFile": "", "CpusetCpus": "", "CpusetMems": "", "CpuShares": 0, "CpuPeriod": 100000, "Devices": [], "Dns": null, "DnsSearch": null, "ExtraHosts": null, "IpcMode": "", "Links": null, "LxcConf": [], "Memory": 0, "MemorySwap": 0, "OomKillDisable": false, "NetworkMode": "bridge", "PortBindings": {}, "Privileged": false, "ReadonlyRootfs": false, "PublishAllPorts": false, "RestartPolicy": { "MaximumRetryCount": 2, "Name": "on-failure" }, "LogConfig": { "Config": null, "Type": "json-file" }, "SecurityOpt": null, "VolumesFrom": null, "Ulimits": [{}] }, "HostnamePath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hostname", "HostsPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/hosts", "LogPath": "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log", "Id": "ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39", "Image": "04c5d3b7b0656168630d3ba35d8889bd0e9caafcaeb3004d2bfbc47e7c5d35d2", "MountLabel": "", "Name": "/boring_euclid", "NetworkSettings": { "Bridge": "", "Gateway": "", "IPAddress": "", "IPPrefixLen": 0, "MacAddress": "", "PortMapping": null, "Ports": null }, "Path": "/bin/sh", "ProcessLabel": "", "ResolvConfPath": "/var/lib/docker/containers/ba033ac4401106a3b513bc9d639eee123ad78ca3616b921167cd74b20e25ed39/resolv.conf", "RestartCount": 1, "State": { "Error": "", "ExitCode": 9, "FinishedAt": "2015-01-06T15:47:32.080254511Z", "OOMKilled": false, "Paused": false, "Pid": 0, "Restarting": false, "Running": false, "StartedAt": "2015-01-06T15:47:32.072697474Z" }, "Mounts": [ { "Source": "/data", "Destination": "/data", "Mode": "ro,Z", "RW": false } ] } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container logs `GET /containers/(id)/logs` Get `stdout` and `stderr` logs from the container ``id`` > **Note**: > This endpoint works only for containers with `json-file` logging driver. **Example request**: GET /containers/4fa6e0f0c678/logs?stderr=1&stdout=1×tamps=1&follow=1&tail=10&since=1428990821 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **follow** – 1/True/true or 0/False/false, return stream. Default `false`. - **stdout** – 1/True/true or 0/False/false, show `stdout` log. Default `false`. - **stderr** – 1/True/true or 0/False/false, show `stderr` log. Default `false`. - **since** – UNIX timestamp (integer) to filter logs. Specifying a timestamp will only output log-entries since that timestamp. Default: 0 (unfiltered) - **timestamps** – 1/True/true or 0/False/false, print timestamps for every log line. Default `false`. - **tail** – Output specified number of lines at the end of logs: `all` or ``. Default all. Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Values for `Kind`: - `0`: Modify - `1`: Add - `2`: Delete Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Get container stats based on resource usage `GET /containers/(id)/stats` This endpoint returns a live stream of a container's resource usage statistics. > **Note**: this functionality currently only works when using the *libcontainer* exec-driver. **Example request**: GET /containers/redis1/stats HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "read" : "2015-01-08T22:57:31.547920715Z", "network" : { "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 }, "memory_stats" : { "stats" : { "total_pgmajfault" : 0, "cache" : 0, "mapped_file" : 0, "total_inactive_file" : 0, "pgpgout" : 414, "rss" : 6537216, "total_mapped_file" : 0, "writeback" : 0, "unevictable" : 0, "pgpgin" : 477, "total_unevictable" : 0, "pgmajfault" : 0, "total_rss" : 6537216, "total_rss_huge" : 6291456, "total_writeback" : 0, "total_inactive_anon" : 0, "rss_huge" : 6291456, "hierarchical_memory_limit" : 67108864, "total_pgfault" : 964, "total_active_file" : 0, "active_anon" : 6537216, "total_active_anon" : 6537216, "total_pgpgout" : 414, "total_cache" : 0, "inactive_anon" : 0, "active_file" : 0, "pgfault" : 964, "inactive_file" : 0, "total_pgpgin" : 477 }, "max_usage" : 6651904, "usage" : 6537216, "failcnt" : 0, "limit" : 67108864 }, "blkio_stats" : {}, "cpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000, "throttling_data" : {} } } Query Parameters: - **stream** – 1/True/true or 0/False/false, pull stats once then disconnect. Default `true`. Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Resize a container TTY `POST /containers/(id)/resize?h=&w=` Resize the TTY for container with `id`. You must restart the container for the resize to take effect. **Example request**: POST /containers/4fa6e0f0c678/resize?h=40&w=80 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Length: 0 Content-Type: text/plain; charset=utf-8 Status Codes: - **200** – no error - **404** – No such container - **500** – Cannot resize container ### Start a container `POST /containers/(id)/start` Start the container `id` > **Note**: > For backwards compatibility, this endpoint accepts a `HostConfig` as JSON-encoded request body. > See [create a container](#create-a-container) for details. **Example request**: POST /containers/(id)/start HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **304** – container already started - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **304** – container already stopped - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like `SIGINT`. When not set, `SIGKILL` is assumed and the call waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Rename a container `POST /containers/(id)/rename` Rename the container `id` to a `new_name` **Example request**: POST /containers/e90e34656806/rename?name=new_name HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **name** – new name for the container Status Codes: - **204** – no error - **404** – no such container - **409** - conflict name already assigned - **500** – server error ### Pause a container `POST /containers/(id)/pause` Pause the container `id` **Example request**: POST /containers/e90e34656806/pause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Unpause a container `POST /containers/(id)/unpause` Unpause the container `id` **Example request**: POST /containers/e90e34656806/unpause HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 101 UPGRADED Content-Type: application/vnd.docker.raw-stream Connection: Upgrade Upgrade: tcp {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default `false`. - **stream** – 1/True/true or 0/False/false, return stream. Default `false`. - **stdin** – 1/True/true or 0/False/false, if `stream=true`, attach to `stdin`. Default `false`. - **stdout** – 1/True/true or 0/False/false, if `logs=true`, return `stdout` log, if `stream=true`, attach to `stdout`. Default `false`. - **stderr** – 1/True/true or 0/False/false, if `logs=true`, return `stderr` log, if `stream=true`, attach to `stderr`. Default `false`. Status Codes: - **101** – no error, hints proxy about hijacking - **200** – no error, no upgrade header found - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's `stdin`. When the TTY is disabled, then the stream is multiplexed to separate `stdout` and `stderr`. The format is a **Header** and a **Payload** (frame). **HEADER** The header contains the information which the stream writes (`stdout` or `stderr`). It also contains the size of the associated frame encoded in the last four bytes (`uint32`). It is encoded on the first eight bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: `stdin` (is written on `stdout`) - 1: `stdout` - 2: `stderr` `SIZE1, SIZE2, SIZE3, SIZE4` are the four bytes of the `uint32` size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read eight bytes. 2. Choose `stdout` or `stderr` depending on the first byte. 3. Extract the frame size from the last four bytes. 4. Read the extracted size and output it on the correct output. 5. Goto 1. ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default `false`. - **stream** – 1/True/true or 0/False/false, return stream. Default `false`. - **stdin** – 1/True/true or 0/False/false, if `stream=true`, attach to `stdin`. Default `false`. - **stdout** – 1/True/true or 0/False/false, if `logs=true`, return `stdout` log, if `stream=true`, attach to `stdout`. Default `false`. - **stderr** – 1/True/true or 0/False/false, if `logs=true`, return `stderr` log, if `stream=true`, attach to `stderr`. Default `false`. Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default `false`. - **force** - 1/True/true or 0/False/false, Kill then remove the container. Default `false`. Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Deprecated** in favor of the `archive` endpoint below. **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Retrieving information about files and folders in a container `HEAD /containers/(id)/archive` See the description of the `X-Docker-Container-Path-Stat` header in the folowing section. ### Get an archive of a filesystem resource in a container `GET /containers/(id)/archive` Get an tar archive of a resource in the filesystem of container `id`. Query Parameters: - **path** - resource in the container's filesystem to archive. Required. If not an absolute path, it is relative to the container's root directory. The resource specified by **path** must exist. To assert that the resource is expected to be a directory, **path** should end in `/` or `/.` (assuming a path separator of `/`). If **path** ends in `/.` then this indicates that only the contents of the **path** directory should be copied. A symlink is always resolved to its target. **Note**: It is not possible to copy certain system files such as resources under `/proc`, `/sys`, `/dev`, and mounts created by the user in the container. **Example request**: GET /containers/8cce319429b2/archive?path=/root HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar X-Docker-Container-Path-Stat: eyJuYW1lIjoicm9vdCIsInBhdGgiOiIvcm9vdCIsInNpemUiOjQwOTYsIm1vZGUiOjIxNDc0ODQwOTYsIm10aW1lIjoiMjAxNC0wMi0yN1QyMDo1MToyM1oifQ== {{ TAR STREAM }} On success, a response header `X-Docker-Container-Path-Stat` will be set to a base64-encoded JSON object containing some filesystem header information about the archived resource. The above example value would decode to the following JSON object (whitespace added for readability): { "name": "root", "path": "/root", "size": 4096, "mode": 2147484096, "mtime": "2014-02-27T20:51:23Z" } A `HEAD` request can also be made to this endpoint if only this information is desired. Status Codes: - **200** - success, returns archive of copied resource - **400** - client error, bad parameter, details in JSON response body, one of: - must specify path parameter (**path** cannot be empty) - not a directory (**path** was asserted to be a directory but exists as a file) - **404** - client error, resource not found, one of: – no such container (container `id` does not exist) - no such file or directory (**path** does not exist) - **500** - server error ### Extract an archive of files or folders to a directory in a container `PUT /containers/(id)/archive` Upload a tar archive to be extracted to a path in the filesystem of container `id`. Query Parameters: - **path** - path to a directory in the container to extract the archive's contents into. Required. If not an absolute path, it is relative to the container's root directory. The **path** resource must exist. - **noOverwriteDirNonDir** - If "1", "true", or "True" then it will be an error if unpacking the given content would cause an existing directory to be replaced with a non-directory and vice versa. **Example request**: PUT /containers/8cce319429b2/archive?path=/vol1 HTTP/1.1 Content-Type: application/x-tar {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – the content was extracted successfully - **400** - client error, bad parameter, details in JSON response body, one of: - must specify path parameter (**path** cannot be empty) - not a directory (**path** should be a directory but exists as a file) - unable to overwrite existing directory with non-directory (if **noOverwriteDirNonDir**) - unable to overwrite existing non-directory with directory (if **noOverwriteDirNonDir**) - **403** - client error, permission denied, the volume or container rootfs is marked as read-only. - **404** - client error, resource not found, one of: – no such container (container `id` does not exist) - no such file or directory (**path** resource does not exist) - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] **Example request, with digest information**: GET /images/json?digests=1 HTTP/1.1 **Example response, with digest information**: HTTP/1.1 200 OK Content-Type: application/json [ { "Created": 1420064636, "Id": "4986bf8c15363d1c5d15512d5266f8777bfba4974ac56e3270e7760f6f0a8125", "ParentId": "ea13149945cb6b1e746bf28032f02e9b5a793523481a0a18645fc77ad53c4ea2", "RepoDigests": [ "localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf" ], "RepoTags": [ "localhost:5000/test/busybox:latest", "playdate:latest" ], "Size": 0, "VirtualSize": 2429728 } ] The response shows a single image `Id` associated with two repositories (`RepoTags`): `localhost:5000/test/busybox`: and `playdate`. A caller can use either of the `RepoTags` values `localhost:5000/test/busybox:latest` or `playdate:latest` to reference the image. You can also use `RepoDigests` values to reference an image. In this response, the array has only one reference and that is to the `localhost:5000/test/busybox` repository; the `playdate` repository has no digest. You can reference this digest using the value: `localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d...` See the `docker run` and `docker build` commands for examples of digest and tag references on the command line. Query Parameters: - **all** – 1/True/true or 0/False/false, default false - **filters** – a JSON encoded value of the filters (a map[string][]string) to process on the images list. Available filters: - `dangling=true` - `label=key` or `key=value` of an image label ### Build image from a Dockerfile `POST /build` Build an image from a Dockerfile **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The input stream must be a `tar` archive compressed with one of the following algorithms: `identity` (no compression), `gzip`, `bzip2`, `xz`. The archive must include a build instructions file, typically called `Dockerfile` at the archive's root. The `dockerfile` parameter may be used to specify a different build instructions file. To do this, its value must be the path to the alternate build instructions file to use. The archive may include any number of other files, which are accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). The build is canceled if the client drops the connection by quitting or being killed. Query Parameters: - **dockerfile** - Path within the build context to the Dockerfile. This is ignored if `remote` is specified and points to an individual filename. - **t** – A repository name (and optionally a tag) to apply to the resulting image in case of success. - **remote** – A Git repository URI or HTTP/HTTPS URI build source. If the URI specifies a filename, the file's contents are placed into a file called `Dockerfile`. - **q** – Suppress verbose build output. - **nocache** – Do not use the cache when building the image. - **pull** - Attempt to pull the image even if an older image exists locally. - **rm** - Remove intermediate containers after a successful build (default behavior). - **forcerm** - Always remove intermediate containers (includes `rm`). - **memory** - Set memory limit for build. - **memswap** - Total memory (memory + swap), `-1` to disable swap. - **cpushares** - CPU shares (relative weight). - **cpusetcpus** - CPUs in which to allow execution (e.g., `0-3`, `0,1`). Request Headers: - **Content-type** – Set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Create an image `POST /images/create` Create an image either by pulling it from the registry or by importing it **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – Name of the image to pull. - **fromSrc** – Source to import. The value may be a URL from which the image can be retrieved or `-` to read the image from the request body. - **repo** – Repository name. - **tag** – Tag. - **registry** – The registry to pull from. Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/ubuntu/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Created": "2013-03-23T22:24:18.818426-07:00", "Container": "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig": { "Hostname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": true, "OpenStdin": true, "StdinOnce": false, "Env": null, "Cmd": ["/bin/bash"], "Dns": null, "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Volumes": null, "VolumesFrom": "", "WorkingDir": "" }, "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent": "27cf784147099545", "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/ubuntu/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "3db9c44f45209632d6050b35958829c3a2aa256d81b9a7be45b362ff85c54710", "Created": 1398108230, "CreatedBy": "/bin/sh -c #(nop) ADD file:eb15dbd63394e063b805a3c32ca7bf0266ef64676d5a6fab4801f2e81e2a5148 in /", "Tags": [ "ubuntu:lucid", "ubuntu:10.04" ], "Size": 182964289, "Comment": "" }, { "Id": "6cfa4d1f33fb861d4d114f43b25abd0ac737509268065cdfd69d544a59c85ab8", "Created": 1398108222, "CreatedBy": "/bin/sh -c #(nop) MAINTAINER Tianon Gravi - mkimage-debootstrap.sh -i iproute,iputils-ping,ubuntu-minimal -t lucid.tar.xz lucid http://archive.ubuntu.com/ubuntu/", "Tags": null, "Size": 0, "Comment": "" }, { "Id": "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158", "Created": 1371157430, "CreatedBy": "", "Tags": [ "scratch12:latest", "scratch:latest" ], "Size": 0, "Comment": "Imported from -" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... If you wish to push an image on to a private registry, that image must already have a tag into a repository which references that registry `hostname` and `port`. This repository name should then be used in the URL. This duplicates the command line's flow. **Example request**: POST /images/registry.acme.com:5000/test/push HTTP/1.1 Query Parameters: - **tag** – The tag to associate with the image on the registry. This is optional. Request Headers: - **X-Registry-Auth** – Include a base64-encoded AuthConfig. object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Query Parameters: - **force** – 1/True/true or 0/False/false, default false - **noprune** – 1/True/true or 0/False/false, default false Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_automated": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_automated": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers": 11, "CpuCfsPeriod": true, "CpuCfsQuota": true, "Debug": false, "DockerRootDir": "/var/lib/docker", "Driver": "btrfs", "DriverStatus": [[""]], "ExecutionDriver": "native-0.1", "ExperimentalBuild": false, "HttpProxy": "http://test:test@localhost:8080", "HttpsProxy": "https://test:test@localhost:8080", "ID": "7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS", "IPv4Forwarding": true, "Images": 16, "IndexServerAddress": "https://index.docker.io/v1/", "InitPath": "/usr/bin/docker", "InitSha1": "", "KernelVersion": "3.12.0-1-amd64", "Labels": [ "storage=ssd" ], "MemTotal": 2099236864, "MemoryLimit": true, "NCPU": 1, "NEventsListener": 0, "NFd": 11, "NGoroutines": 21, "Name": "prod-server-42", "NoProxy": "9.81.1.160", "OomKillDisable": true, "OperatingSystem": "Boot2Docker", "RegistryConfig": { "IndexConfigs": { "docker.io": { "Mirrors": null, "Name": "docker.io", "Official": true, "Secure": true } }, "InsecureRegistryCIDRs": [ "127.0.0.0/8" ] }, "SwapLimit": false, "SystemTime": "2015-03-10T11:11:23.730591467-07:00" } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version": "1.5.0", "Os": "linux", "KernelVersion": "3.18.5-tinycore64", "GoVersion": "go1.4.1", "GitCommit": "a8a31ef", "Arch": "amd64", "ApiVersion": "1.20", "Experimental": false } Status Codes: - **200** – no error - **500** – server error ### Ping the docker server `GET /_ping` Ping the docker server **Example request**: GET /_ping HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain OK Status Codes: - **200** - no error - **500** - server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&comment=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Mounts": [ { "Source": "/data", "Destination": "/data", "Mode": "ro,Z", "RW": false } ], "Labels": { "key1": "value1", "key2": "value2" }, "WorkingDir": "", "NetworkDisabled": false, "ExposedPorts": { "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **comment** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get container events from docker, either in real time via streaming, or via polling (using since). Docker containers report the following events: attach, commit, copy, create, destroy, die, exec_create, exec_start, export, kill, oom, pause, rename, resize, restart, start, stop, top, unpause and Docker images report: delete, import, pull, push, tag, untag **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "ubuntu:latest", "time":1374067970} Query Parameters: - **since** – Timestamp used for polling - **until** – Timestamp used for polling - **filters** – A json encoded value of the filters (a map[string][]string) to process on the event list. Available filters: - `event=`; -- event to filter - `image=`; -- image to filter - `container=`; -- container to filter Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. If `name` is a specific name and tag (e.g. ubuntu:latest), then only that image (and its parents) are returned. If `name` is an image ID, similarly only that image (and its parents) are returned, but with the exclusion of the 'repositories' file in the tarball, as there were no image names referenced. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images. `GET /images/get` Get a tarball containing all images and metadata for one or more repositories. For each value of the `names` parameter: if it is a specific name and tag (e.g. `ubuntu:latest`), then only that image (and its parents) are returned; if it is an image ID, similarly only that image (and its parents) are returned and there would be no names referenced in the 'repositories' file for this image ID. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/get?names=myname%2Fmyapp%3Alatest&names=busybox **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into a Docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing these files: - `VERSION`: currently `1.0` - the file format version - `json`: detailed layer information, similar to `docker inspect layer_id` - `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file contains `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, the tarball should also include a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` ### Exec Create `POST /containers/(id)/exec` Sets up an exec instance in a running container `id` **Example request**: POST /containers/e90e34656806/exec HTTP/1.1 Content-Type: application/json { "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "Cmd": [ "date" ] } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id": "f90e34656806" "Warnings":[] } Json Parameters: - **AttachStdin** - Boolean value, attaches to `stdin` of the `exec` command. - **AttachStdout** - Boolean value, attaches to `stdout` of the `exec` command. - **AttachStderr** - Boolean value, attaches to `stderr` of the `exec` command. - **Tty** - Boolean value to allocate a pseudo-TTY. - **Cmd** - Command to run specified as a string or an array of strings. Status Codes: - **201** – no error - **404** – no such container ### Exec Start `POST /exec/(id)/start` Starts a previously set up `exec` instance `id`. If `detach` is true, this API returns after starting the `exec` command. Otherwise, this API sets up an interactive session with the `exec` command. **Example request**: POST /exec/e90e34656806/start HTTP/1.1 Content-Type: application/json { "Detach": false, "Tty": false } **Example response**: HTTP/1.1 201 OK Content-Type: application/json {{ STREAM }} Json Parameters: - **Detach** - Detach from the `exec` command. - **Tty** - Boolean value to allocate a pseudo-TTY. Status Codes: - **201** – no error - **404** – no such exec instance **Stream details**: Similar to the stream behavior of `POST /container/(id)/attach` API ### Exec Resize `POST /exec/(id)/resize` Resizes the `tty` session used by the `exec` command `id`. This API is valid only if `tty` was specified as part of creating and starting the `exec` command. **Example request**: POST /exec/e90e34656806/resize HTTP/1.1 Content-Type: text/plain **Example response**: HTTP/1.1 201 OK Content-Type: text/plain Query Parameters: - **h** – height of `tty` session - **w** – width Status Codes: - **201** – no error - **404** – no such exec instance ### Exec Inspect `GET /exec/(id)/json` Return low-level information about the `exec` command `id`. **Example request**: GET /exec/11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: plain/text { "ID" : "11fb006128e8ceb3942e7c58d77750f24210e35f879dd204ac975c184b820b39", "Running" : false, "ExitCode" : 2, "ProcessConfig" : { "privileged" : false, "user" : "", "tty" : false, "entrypoint" : "sh", "arguments" : [ "-c", "exit 2" ] }, "OpenStdin" : false, "OpenStderr" : false, "OpenStdout" : false, "Container" : { "State" : { "Running" : true, "Paused" : false, "Restarting" : false, "OOMKilled" : false, "Pid" : 3650, "ExitCode" : 0, "Error" : "", "StartedAt" : "2014-11-17T22:26:03.717657531Z", "FinishedAt" : "0001-01-01T00:00:00Z" }, "ID" : "8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c", "Created" : "2014-11-17T22:26:03.626304998Z", "Path" : "date", "Args" : [], "Config" : { "Hostname" : "8f177a186b97", "Domainname" : "", "User" : "", "AttachStdin" : false, "AttachStdout" : false, "AttachStderr" : false, "ExposedPorts" : null, "Tty" : false, "OpenStdin" : false, "StdinOnce" : false, "Env" : [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd" : [ "date" ], "Image" : "ubuntu", "Volumes" : null, "WorkingDir" : "", "Entrypoint" : null, "NetworkDisabled" : false, "MacAddress" : "", "OnBuild" : null, "SecurityOpt" : null }, "Image" : "5506de2b643be1e6febbf3b8a240760c6843244c41e12aa2f60ccbb7153d17f5", "NetworkSettings" : { "IPAddress" : "172.17.0.2", "IPPrefixLen" : 16, "MacAddress" : "02:42:ac:11:00:02", "Gateway" : "172.17.42.1", "Bridge" : "docker0", "PortMapping" : null, "Ports" : {} }, "ResolvConfPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/resolv.conf", "HostnamePath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hostname", "HostsPath" : "/var/lib/docker/containers/8f177a186b977fb451136e0fdf182abff5599a08b3c7f6ef0d36a55aaf89634c/hosts", "LogPath": "/var/lib/docker/containers/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b/1eb5fabf5a03807136561b3c00adcd2992b535d624d5e18b6cdc6a6844d9767b-json.log", "Name" : "/test", "Driver" : "aufs", "ExecDriver" : "native-0.2", "MountLabel" : "", "ProcessLabel" : "", "AppArmorProfile" : "", "RestartCount" : 0, "Mounts" : [], } } Status Codes: - **200** – no error - **404** – no such exec instance - **500** - server error # 3. Going further ## 3.1 Inside `docker run` As an example, the `docker run` command line makes the following API calls: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it. - Then, retry to create the container. - Start the container. - If you are not in detached mode: - Attach to the container, using `logs=1` (to have `stdout` and `stderr` from the container's start) and `stream=1` - If in detached mode or only `stdin` is attached, display the container's id. ## 3.2 Hijacking In this version of the API, `/attach`, uses hijacking to transport `stdin`, `stdout`, and `stderr` on the same socket. To hint potential proxies about connection hijacking, Docker client sends connection upgrade headers similarly to websocket. Upgrade: tcp Connection: Upgrade When Docker daemon detects the `Upgrade` header, it switches its status code from **200 OK** to **101 UPGRADED** and resends the same headers. ## 3.3 CORS Requests To set cross origin requests to the remote api please give values to `--api-cors-header` when running Docker in daemon mode. Set * (asterisk) allows all, default or blank means CORS disabled $ docker -d -H="192.168.1.9:2375" --api-cors-header="http://foo.bar" ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.3.md ================================================ # Docker Remote API v1.3 # 1. Brief introduction - The Remote API is replacing rcli - Default port in the docker daemon is 2375 - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport stdout stdin and stderr # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "3176a2479c92", "Image": "centos:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "fedora:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"ubuntu", "Volumes":{}, "VolumesFrom":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "PID":"11935", "Tty":"pts/2", "Time":"00:00:00", "Cmd":"sh" }, { "PID":"12140", "Tty":"pts/2", "Time":"00:00:00", "Cmd":"sleep" } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"ubuntu", "Tag":"precise", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 }, { "Repository":"ubuntu", "Tag":"12.04", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nubuntu",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\ncentos",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\nfedora",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/centos/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"centos", "Volumes":null, "VolumesFrom":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/fedora/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry > **Example request**: > > POST /images/test/push HTTP/1.1 > {{ authConfig }} > > **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] :query term: term to search :statuscode 200: no error :statuscode 500: server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK {{ STREAM }} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called Dockerfile at its root. I may include any number of other files, which will be accessible in the build context (See the ADD build command). The Content-type header should be set to "application/tar". Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":"hannibal", "password:"xxxx", "email":"hannibal@a-team.com" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "EventsListeners":"0", "LXCVersion":"0.7.5", "KernelVersion":"3.8.0-19-generic" } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "PortSpecs":["22"] } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"create","id":"dfdf82bd3881","time":1374067924} {"status":"start","id":"dfdf82bd3881","time":1374067924} {"status":"stop","id":"dfdf82bd3881","time":1374067966} {"status":"destroy","id":"dfdf82bd3881","time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. > docker -d -H="192.168.1.9:2375" -api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.4.md ================================================ # Docker Remote API v1.4 # 1. Brief introduction - The Remote API is replacing rcli - Default port in the docker daemon is 2375 - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport stdout stdin and stderr # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "3176a2479c92", "Image": "centos:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "fedora:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports":"", "SizeRw":12288, "SizeRootFs":0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Privileged": false, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"ubuntu", "Volumes":{}, "VolumesFrom":"", "WorkingDir":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **409** – conflict between containers and images - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"ubuntu", "Tag":"precise", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 }, { "Repository":"ubuntu", "Tag":"12.04", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nubuntu",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\ncentos",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\nfedora",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/centos/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"centos", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **409** – conflict between containers and images - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/fedora/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 {{ authConfig }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Status Codes: - **200** – no error :statuscode 404: no such image :statuscode 500: server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] :query term: term to search :statuscode 200: no error :statuscode 500: server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK {{ STREAM }} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called Dockerfile at its root. I may include any number of other files, which will be accessible in the build context (See the ADD build command). The Content-type header should be set to "application/tar". Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "PortSpecs":["22"] } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"create","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067924} {"status":"start","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067924} {"status":"stop","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067966} {"status":"destroy","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.5.md ================================================ # Docker Remote API v1.5 # 1. Brief introduction - The Remote API is replacing rcli - Default port in the docker daemon is 2375 - The API tends to be REST, but for some complex commands, like attach or pull, the HTTP connection is hijacked to transport stdout stdin and stderr # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "ubuntu:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "9cd87474be90", "Image": "ubuntu:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "3176a2479c92", "Image": "centos:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "fedora:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Privileged": false, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"ubuntu", "Volumes":{}, "VolumesFrom":"", "WorkingDir":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "ubuntu", "Volumes": {}, "VolumesFrom": "", "WorkingDir":"" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles":[ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes":[ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path":"/dev", "Kind":0 }, { "Path":"/dev/kmsg", "Kind":1 }, { "Path":"/test", "Kind":1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}] } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource":"test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"ubuntu", "Tag":"precise", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 }, { "Repository":"ubuntu", "Tag":"12.04", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nubuntu",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\ncentos",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\nfedora",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=ubuntu HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/centos/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"centos", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/fedora/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id":"b750fe79269d", "Created":1364102658, "CreatedBy":"/bin/bash" }, { "Id":"27cf78414709", "Created":1364068391, "CreatedBy":"" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... The `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged":"3e2f21a89f"}, {"Deleted":"3e2f21a89f"}, {"Deleted":"53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK {{ STREAM }} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called Dockerfile at its root. I may include any number of other files, which will be accessible in the build context (See the ADD build command). The Content-type header should be set to "application/tar". Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** – remove intermediate containers after a successful build Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":"hannibal", "password:"xxxx", "email":"hannibal@a-team.com", "serveraddress":"https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "PortSpecs":["22"] } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"create","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067924} {"status":"start","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067924} {"status":"stop","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067966} {"status":"destroy","id":"dfdf82bd3881","from":"ubuntu:latest","time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run`: - Create the container - If the status code is 404, it means the image doesn't exist: Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.6.md ================================================ # Docker Remote API v1.6 # 1. Brief introduction - The Remote API has replaced rcli - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout, stdin` and `stderr` # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "base:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "base:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "base:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "base:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "ExposedPorts":{}, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"base", "Volumes":{}, "VolumesFrom":"", "WorkingDir":"" } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Query Parameters:   - **name** – container name to use Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error **More Complex Example request, in 2 steps.** **First, use create to expose a Private Port, which can be bound back to a Public Port a startup**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Cmd":[ "/usr/sbin/sshd","-D" ], "Image":"image-with-sshd", "ExposedPorts":{"22/tcp":{}} } **Example response**: HTTP/1.1 201 OK Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } **Second, start (using the ID returned above) the image we just created, mapping the ssh port 22 to something on the host**: POST /containers/e90e34656806/start HTTP/1.1 Content-Type: application/json { "PortBindings": { "22/tcp": [{ "HostPort": "11022" }]} } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain; charset=utf-8 Content-Length: 0 **Now you can ssh into your new container on port 11022.** ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "ExposedPorts": {}, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "base", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "ContainerIDFile": "", "Privileged": false, "PortBindings": {"22/tcp": [{HostIp:"", HostPort:""}]}, "Links": [], "PublishAllPorts": false } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters:   - **signal** – Signal to send to the container (integer). When no set, SIGKILL is assumed and the call will waits for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1) ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/(format)` List images `format` could be json or viz (json default) **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Repository":"base", "Tag":"ubuntu-12.10", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 }, { "Repository":"base", "Tag":"ubuntu-quantal", "Id":"b750fe79269d", "Created":1364102658, "Size":24653, "VirtualSize":180116135 } ] **Example request**: GET /images/viz HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: text/plain digraph docker { "d82cbacda43a" -> "074be284591f" "1496068ca813" -> "08306dc45919" "08306dc45919" -> "0e7893146ac2" "b750fe79269d" -> "1496068ca813" base -> "27cf78414709" [style=invis] "f71189fff3de" -> "9a33b36209ed" "27cf78414709" -> "b750fe79269d" "0e7893146ac2" -> "d6434d954665" "d6434d954665" -> "d82cbacda43a" base -> "e9aa60c60128" [style=invis] "074be284591f" -> "f71189fff3de" "b750fe79269d" [label="b750fe79269d\nbase",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "e9aa60c60128" [label="e9aa60c60128\nbase2",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; "9a33b36209ed" [label="9a33b36209ed\ntest",shape=box,fillcolor="paleturquoise",style="filled,rounded"]; base [style=invisible] } Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by defaul Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=base HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/base/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "ExposedPorts":{}, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"base", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/base/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... > The `X-Registry-Auth` header can be used to > include a base64-encoded AuthConfig object. Status Codes: - **200** – no error :statuscode 404: no such image :statuscode 500: server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com) **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Name":"cespare/sshd", "Description":"" }, { "Name":"johnfuller/sshd", "Description":"" }, { "Name":"dhrp/mongodb-sshd", "Description":"" } ] :query term: term to search :statuscode 200: no error :statuscode 500: server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK {{ STREAM }} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called Dockerfile at its root. I may include any number of other files, which will be accessible in the build context (See the ADD build command). The Content-type header should be set to "application/tar". Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Cmd": ["cat", "/world"], "ExposedPorts":{"22/tcp":{}} } **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "base:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "base:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.7.md ================================================ # Docker Remote API v1.7 # 1. Brief introduction - The Remote API has replaced rcli - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout, stdin` and `stderr` # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "base:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "base:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "base:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "base:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters: - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"base", "Volumes":{ "/tmp": {} }, "VolumesFrom":"", "WorkingDir":"", "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters: - **config** – the container's configuration Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "base", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {} } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "Privileged":false, "PublishAllPorts":false } Binds need to reference Volumes that were defined during container creation. **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters: - **hostConfig** – the container's host configuration (optional) Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.7/#create-a-container), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1) ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=base HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pulling..."} {"status":"Pulling", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/base/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"base", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/base/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)"} {"error":"Invalid..."} ... Request Headers:   - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_trusted": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {{ STREAM }} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image Request Headers:   - **Content-type** – should be set to `"application/tar"`. Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") - **run** – config automatically applied when the image is run. (ex: {"Cmd": ["cat", "/world"], "PortSpecs":["22"]}) Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "base:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "base:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. **Example request** GET /images/ubuntu/get **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream :statuscode 200: no error :statuscode 500: server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. **Example request** POST /images/load Tarball in body **Example response**: .. sourcecode:: http HTTP/1.1 200 OK :statuscode 200: no error :statuscode 500: server error # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.8.md ================================================ # Docker Remote API v1.8 # 1. Brief introduction - The Remote API has replaced rcli - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout, stdin` and `stderr` # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "base:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "base:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "base:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "base:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "CpuShares":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"base", "Volumes":{ "/tmp": {} }, "VolumesFrom":"", "WorkingDir":"", "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters:   - **Hostname** – Container host name - **User** – Username or UID - **Memory** – Memory Limit in bytes - **CpuShares** – CPU shares (relative weight) - **AttachStdin** – 1/True/true or 0/False/false, attach to standard input. Default false - **AttachStdout** – 1/True/true or 0/False/false, attach to standard output. Default false - **AttachStderr** – 1/True/true or 0/False/false, attach to standard error. Default false - **Tty** – 1/True/true or 0/False/false, allocate a pseudo-tty. Default false - **OpenStdin** – 1/True/true or 0/False/false, keep stdin open even if not attached. Default false Query Parameters:   - **name** – Assign the specified name to the container. Mus match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "base", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **Binds** – Create a bind mount to a directory or file with [host-path]:[container-path]:[rw|ro]. If a directory "container-path" is missing, then docker creates a new volume. - **LxcConf** – Map of custom lxc options - **PortBindings** – Expose ports from the container, optionally publishing them via the HostPort flag - **PublishAllPorts** – 1/True/true or 0/False/false, publish all exposed ports to the host interfaces. Default false - **Privileged** – 1/True/true or 0/False/false, give extended privileges to this container. Default false Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create` ](/reference/api/docker_remote_api_v1.9/#create-a-container "POST /containers/create"), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1) ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List Images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=base HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)", "progressDetail":{"current":1}} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/base/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"base", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/base/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... Request Headers:   - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name)` Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_trusted": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile via stdin `POST /build` Build an image from Dockerfile via stdin **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#dockerbuilder)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image Request Headers:   - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Auth** – base64-encoded AuthConfig objec Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 **Example response**: HTTP/1.1 201 OK Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") - **run** – config automatically applied when the image is run. (ex: {"Cmd": ["cat", "/world"], "PortSpecs":["22"]}) Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "base:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "base:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run`: - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS Requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/docker_remote_api_v1.9.md ================================================ # Docker Remote API v1.9 # 1. Brief introduction - The Remote API has replaced rcli - The daemon listens on `unix:///var/run/docker.sock` but you can bind Docker to another host/port or a Unix socket. - The API tends to be REST, but for some complex commands, like `attach` or `pull`, the HTTP connection is hijacked to transport `stdout, stdin` and `stderr` # 2. Endpoints ## 2.1 Containers ### List containers `GET /containers/json` List containers. **Example request**: GET /containers/json?all=1&before=8dfafdbc3a40&size=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "8dfafdbc3a40", "Image": "base:latest", "Command": "echo 1", "Created": 1367854155, "Status": "Exit 0", "Ports": [{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "9cd87474be90", "Image": "base:latest", "Command": "echo 222222", "Created": 1367854155, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 }, { "Id": "3176a2479c92", "Image": "base:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Status": "Exit 0", "Ports":[], "SizeRw":12288, "SizeRootFs":0 }, { "Id": "4cb07b47f9fb", "Image": "base:latest", "Command": "echo 444444444444444444444444444444444", "Created": 1367854152, "Status": "Exit 0", "Ports": [], "SizeRw": 12288, "SizeRootFs": 0 } ] Query Parameters:   - **all** – 1/True/true or 0/False/false, Show all containers. Only running containers are shown by default (i.e., this defaults to false) - **limit** – Show `limit` last created containers, include non-running ones. - **since** – Show only containers created since Id, include non-running ones. - **before** – Show only containers created before Id, include non-running ones. - **size** – 1/True/true or 0/False/false, Show the containers sizes Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a container `POST /containers/create` Create a container **Example request**: POST /containers/create HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "CpuShares":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Dns":null, "Image":"base", "Volumes":{ "/tmp": {} }, "VolumesFrom":"", "WorkingDir":"", "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/json { "Id":"e90e34656806" "Warnings":[] } Json Parameters:   - **Hostname** – Container host name - **User** – Username or UID - **Memory** – Memory Limit in bytes - **CpuShares** – CPU shares (relative weight) - **AttachStdin** – 1/True/true or 0/False/false, attach to standard input. Default false - **AttachStdout** – 1/True/true or 0/False/false, attach to standard output. Default false - **AttachStderr** – 1/True/true or 0/False/false, attach to standard error. Default false - **Tty** – 1/True/true or 0/False/false, allocate a pseudo-tty. Default false - **OpenStdin** – 1/True/true or 0/False/false, keep stdin open even if not attached. Default false Query Parameters:   - **name** – Assign the specified name to the container. Mus match `/?[a-zA-Z0-9_-]+`. Status Codes: - **201** – no error - **404** – no such container - **406** – impossible to attach (container not running) - **500** – server error ### Inspect a container `GET /containers/(id)/json` Return low-level information on the container `id` **Example request**: GET /containers/4fa6e0f0c678/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.041847+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 0, "MemorySwap": 0, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Dns": null, "Image": "base", "Volumes": {}, "VolumesFrom": "", "WorkingDir": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:01360", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/docker/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false } } Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### List processes running inside a container `GET /containers/(id)/top` List processes running inside the container `id` **Example request**: GET /containers/4fa6e0f0c678/top HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Titles": [ "USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "STAT", "START", "TIME", "COMMAND" ], "Processes": [ ["root","20147","0.0","0.1","18060","1864","pts/4","S","10:06","0:00","bash"], ["root","20271","0.0","0.0","4312","352","pts/4","S+","10:07","0:00","sleep","10"] ] } Query Parameters: - **ps_args** – ps arguments to use (e.g., aux) Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Inspect changes on a container's filesystem `GET /containers/(id)/changes` Inspect changes on container `id`'s filesystem **Example request**: GET /containers/4fa6e0f0c678/changes HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Path": "/dev", "Kind": 0 }, { "Path": "/dev/kmsg", "Kind": 1 }, { "Path": "/test", "Kind": 1 } ] Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Export a container `GET /containers/(id)/export` Export the contents of container `id` **Example request**: GET /containers/4fa6e0f0c678/export HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Start a container `POST /containers/(id)/start` Start the container `id` **Example request**: POST /containers/(id)/start HTTP/1.1 Content-Type: application/json { "Binds":["/tmp:/tmp"], "LxcConf":[{"Key":"lxc.utsname","Value":"docker"}], "PortBindings":{ "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts":false, "Privileged":false } **Example response**: HTTP/1.1 204 No Content Content-Type: text/plain Json Parameters:   - **Binds** – Create a bind mount to a directory or file with [host-path]:[container-path]:[rw|ro]. If a directory "container-path" is missing, then docker creates a new volume. - **LxcConf** – Map of custom lxc options - **PortBindings** – Expose ports from the container, optionally publishing them via the HostPort flag - **PublishAllPorts** – 1/True/true or 0/False/false, publish all exposed ports to the host interfaces. Default false - **Privileged** – 1/True/true or 0/False/false, give extended privileges to this container. Default false Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Stop a container `POST /containers/(id)/stop` Stop the container `id` **Example request**: POST /containers/e90e34656806/stop?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 OK Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Restart a container `POST /containers/(id)/restart` Restart the container `id` **Example request**: POST /containers/e90e34656806/restart?t=5 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **t** – number of seconds to wait before killing the container Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Kill a container `POST /containers/(id)/kill` Kill the container `id` **Example request**: POST /containers/e90e34656806/kill HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters - **signal** - Signal to send to the container: integer or string like "SIGINT". When not set, SIGKILL is assumed and the call will wait for the container to exit. Status Codes: - **204** – no error - **404** – no such container - **500** – server error ### Attach to a container `POST /containers/(id)/attach` Attach to the container `id` **Example request**: POST /containers/16253994b7c4/attach?logs=1&stream=0&stdout=1 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/vnd.docker.raw-stream {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Defaul false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error **Stream details**: When using the TTY setting is enabled in [`POST /containers/create`](#create-a-container), the stream is the raw data from the process PTY and client's stdin. When the TTY is disabled, then the stream is multiplexed to separate stdout and stderr. The format is a **Header** and a **Payload** (frame). **HEADER** The header will contain the information on which stream write the stream (stdout or stderr). It also contain the size of the associated frame encoded on the last 4 bytes (uint32). It is encoded on the first 8 bytes like this: header := [8]byte{STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4} `STREAM_TYPE` can be: - 0: stdin (will be written on stdout) - 1: stdout - 2: stderr `SIZE1, SIZE2, SIZE3, SIZE4` are the 4 bytes of the uint32 size encoded as big endian. **PAYLOAD** The payload is the raw stream. **IMPLEMENTATION** The simplest way to implement the Attach protocol is the following: 1. Read 8 bytes 2. chose stdout or stderr depending on the first byte 3. Extract the frame size from the last 4 bytes 4. Read the extracted size and output it on the correct output 5. Goto 1) ### Attach to a container (websocket) `GET /containers/(id)/attach/ws` Attach to the container `id` via websocket Implements websocket protocol handshake according to [RFC 6455](http://tools.ietf.org/html/rfc6455) **Example request** GET /containers/e90e34656806/attach/ws?logs=0&stream=1&stdin=1&stdout=1&stderr=1 HTTP/1.1 **Example response** {{ STREAM }} Query Parameters: - **logs** – 1/True/true or 0/False/false, return logs. Default false - **stream** – 1/True/true or 0/False/false, return stream. Default false - **stdin** – 1/True/true or 0/False/false, if stream=true, attach to stdin. Default false - **stdout** – 1/True/true or 0/False/false, if logs=true, return stdout log, if stream=true, attach to stdout. Default false - **stderr** – 1/True/true or 0/False/false, if logs=true, return stderr log, if stream=true, attach to stderr. Default false Status Codes: - **200** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Wait a container `POST /containers/(id)/wait` Block until container `id` stops, then returns the exit code **Example request**: POST /containers/16253994b7c4/wait HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"StatusCode": 0} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ### Remove a container `DELETE /containers/(id)` Remove the container `id` from the filesystem **Example request**: DELETE /containers/16253994b7c4?v=1 HTTP/1.1 **Example response**: HTTP/1.1 204 No Content Query Parameters: - **v** – 1/True/true or 0/False/false, Remove the volumes associated to the container. Default false Status Codes: - **204** – no error - **400** – bad parameter - **404** – no such container - **500** – server error ### Copy files or folders from a container `POST /containers/(id)/copy` Copy files or folders of container `id` **Example request**: POST /containers/4fa6e0f0c678/copy HTTP/1.1 Content-Type: application/json { "Resource": "test.txt" } **Example response**: HTTP/1.1 200 OK Content-Type: application/octet-stream {{ TAR STREAM }} Status Codes: - **200** – no error - **404** – no such container - **500** – server error ## 2.2 Images ### List images `GET /images/json` **Example request**: GET /images/json?all=0 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "RepoTags": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964056420e5d58ca5cc376ef18e2de93b5cc90e868a1bbc8318c1c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTags": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ] ### Create an image `POST /images/create` Create an image, either by pull it from the registry or by importing i **Example request**: POST /images/create?fromImage=base HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pulling..."} {"status": "Pulling", "progress": "1 B/ 100 B", "progressDetail": {"current": 1, "total": 100}} {"error": "Invalid..."} ... When using this endpoint to pull an image from the registry, the `X-Registry-Auth` header can be used to include a base64-encoded AuthConfig object. Query Parameters: - **fromImage** – name of the image to pull - **fromSrc** – source to import, - means stdin - **repo** – repository - **tag** – tag - **registry** – the registry to pull from Request Headers: - **X-Registry-Auth** – base64-encoded AuthConfig object Status Codes: - **200** – no error - **500** – server error ### Insert a file in an image `POST /images/(name)/insert` Insert a file from `url` in the image `name` at `path` **Example request**: POST /images/test/insert?path=/usr&url=myurl HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status":"Inserting..."} {"status":"Inserting", "progress":"1/? (n/a)", "progressDetail":{"current":1}} {"error":"Invalid..."} ... Query Parameters: - **url** – The url from where the file is taken - **path** – The path where the file is stored Status Codes: - **200** – no error - **500** – server error ### Inspect an image `GET /images/(name)/json` Return low-level information on the image `name` **Example request**: GET /images/base/json HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "parent":"27cf784147099545", "created":"2013-03-23T22:24:18.818426-07:00", "container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "container_config": { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":false, "AttachStderr":false, "PortSpecs":null, "Tty":true, "OpenStdin":true, "StdinOnce":false, "Env":null, "Cmd": ["/bin/bash"], "Dns":null, "Image":"base", "Volumes":null, "VolumesFrom":"", "WorkingDir":"" }, "Size": 6824592 } Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Get the history of an image `GET /images/(name)/history` Return the history of the image `name` **Example request**: GET /images/base/history HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "Id": "b750fe79269d", "Created": 1364102658, "CreatedBy": "/bin/bash" }, { "Id": "27cf78414709", "Created": 1364068391, "CreatedBy": "" } ] Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Push an image on the registry `POST /images/(name)/push` Push the image `name` on the registry **Example request**: POST /images/test/push HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "Pushing..."} {"status": "Pushing", "progress": "1/? (n/a)", "progressDetail": {"current": 1}}} {"error": "Invalid..."} ... Request Headers:   - **X-Registry-Auth** – include a base64-encoded AuthConfig object. Status Codes: - **200** – no error - **404** – no such image - **500** – server error ### Tag an image into a repository `POST /images/(name)/tag` Tag the image `name` into a repository **Example request**: POST /images/test/tag?repo=myrepo&force=0&tag=v42 HTTP/1.1 **Example response**: HTTP/1.1 201 OK Query Parameters: - **repo** – The repository to tag in - **force** – 1/True/true or 0/False/false, default false - **tag** - The new tag name Status Codes: - **201** – no error - **400** – bad parameter - **404** – no such image - **409** – conflict - **500** – server error ### Remove an image `DELETE /images/(name*) : Remove the image `name` from the filesystem **Example request**: DELETE /images/test HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-type: application/json [ {"Untagged": "3e2f21a89f"}, {"Deleted": "3e2f21a89f"}, {"Deleted": "53b4f83ac9"} ] Status Codes: - **200** – no error - **404** – no such image - **409** – conflict - **500** – server error ### Search images `GET /images/search` Search for an image on [Docker Hub](https://hub.docker.com). > **Note**: > The response keys have changed from API v1.6 to reflect the JSON > sent by the registry server to the docker daemon's request. **Example request**: GET /images/search?term=sshd HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "description": "", "is_official": false, "is_trusted": false, "name": "wma55/u1210sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "jdswinbank/sshd", "star_count": 0 }, { "description": "", "is_official": false, "is_trusted": false, "name": "vgauthier/sshd", "star_count": 0 } ... ] Query Parameters: - **term** – term to search Status Codes: - **200** – no error - **500** – server error ## 2.3 Misc ### Build an image from Dockerfile `POST /build` Build an image from Dockerfile using a POST body. **Example request**: POST /build HTTP/1.1 {{ TAR STREAM }} **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"stream": "Step 1..."} {"stream": "..."} {"error": "Error...", "errorDetail": {"code": 123, "message": "Error..."}} The stream must be a tar archive compressed with one of the following algorithms: identity (no compression), gzip, bzip2, xz. The archive must include a file called `Dockerfile` at its root. It may include any number of other files, which will be accessible in the build context (See the [*ADD build command*](/reference/builder/#add)). Query Parameters: - **t** – repository name (and optionally a tag) to be applied to the resulting image in case of success - **remote** – build source URI (git or HTTPS/HTTP) - **q** – suppress verbose build output - **nocache** – do not use the cache when building the image - **rm** – Remove intermediate containers after a successful build Request Headers: - **Content-type** – should be set to `"application/tar"`. - **X-Registry-Config** – base64-encoded ConfigFile object Status Codes: - **200** – no error - **500** – server error ### Check auth configuration `POST /auth` Get the default username and email **Example request**: POST /auth HTTP/1.1 Content-Type: application/json { "username":" hannibal", "password: "xxxx", "email": "hannibal@a-team.com", "serveraddress": "https://index.docker.io/v1/" } **Example response**: HTTP/1.1 200 OK Content-Type: text/plain Status Codes: - **200** – no error - **204** – no error - **500** – server error ### Display system-wide information `GET /info` Display system-wide information **Example request**: GET /info HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Containers":11, "Images":16, "Debug":false, "NFd": 11, "NGoroutines":21, "MemoryLimit":true, "SwapLimit":false, "IPv4Forwarding":true } Status Codes: - **200** – no error - **500** – server error ### Show the Docker version information `GET /version` Show the docker version information **Example request**: GET /version HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" } Status Codes: - **200** – no error - **500** – server error ### Create a new image from a container's changes `POST /commit` Create a new image from a container's changes **Example request**: POST /commit?container=44c004db4b17&m=message&repo=myrepo HTTP/1.1 Content-Type: application/json { "Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "date" ], "Volumes":{ "/tmp": {} }, "WorkingDir":"", "DisableNetwork": false, "ExposedPorts":{ "22/tcp": {} } } **Example response**: HTTP/1.1 201 Created Content-Type: application/vnd.docker.raw-stream {"Id": "596069db4bf5"} Json Parameters: - **config** - the container's configuration Query Parameters: - **container** – source container - **repo** – repository - **tag** – tag - **m** – commit message - **author** – author (e.g., "John Hannibal Smith <[hannibal@a-team.com](mailto:hannibal%40a-team.com)>") Status Codes: - **201** – no error - **404** – no such container - **500** – server error ### Monitor Docker's events `GET /events` Get events from docker, either in real time via streaming, or via polling (using since). Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete **Example request**: GET /events?since=1374067924 **Example response**: HTTP/1.1 200 OK Content-Type: application/json {"status": "create", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "start", "id": "dfdf82bd3881","from": "base:latest", "time":1374067924} {"status": "stop", "id": "dfdf82bd3881","from": "base:latest", "time":1374067966} {"status": "destroy", "id": "dfdf82bd3881","from": "base:latest", "time":1374067970} Query Parameters: - **since** – timestamp used for polling Status Codes: - **200** – no error - **500** – server error ### Get a tarball containing all images and tags in a repository `GET /images/(name)/get` Get a tarball containing all images and metadata for the repository specified by `name`. See the [image tarball format](#image-tarball-format) for more details. **Example request** GET /images/ubuntu/get **Example response**: HTTP/1.1 200 OK Content-Type: application/x-tar Binary data stream Status Codes: - **200** – no error - **500** – server error ### Load a tarball with a set of images and tags into docker `POST /images/load` Load a set of images and tags into the docker repository. See the [image tarball format](#image-tarball-format) for more details. **Example request** POST /images/load Tarball in body **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **500** – server error ### Image tarball format An image tarball contains one directory per image layer (named using its long ID), each containing three files: 1. `VERSION`: currently `1.0` - the file format version 2. `json`: detailed layer information, similar to `docker inspect layer_id` 3. `layer.tar`: A tarfile containing the filesystem changes in this layer The `layer.tar` file will contain `aufs` style `.wh..wh.aufs` files and directories for storing attribute changes and deletions. If the tarball defines a repository, there will also be a `repositories` file at the root that contains a list of repository and tag names mapped to layer IDs. ``` {"hello-world": {"latest": "565a9d68a73f6706862bfe8409a7f659776d4d60a8d096eb4a3cbce6999cc2a1"} } ``` # 3. Going further ## 3.1 Inside `docker run` Here are the steps of `docker run` : - Create the container - If the status code is 404, it means the image doesn't exist: - Try to pull it - Then retry to create the container - Start the container - If you are not in detached mode: - Attach to the container, using logs=1 (to have stdout and - stderr from the container's start) and stream=1 - If in detached mode or only stdin is attached: - Display the container's id ## 3.2 Hijacking In this version of the API, /attach, uses hijacking to transport stdin, stdout and stderr on the same socket. This might change in the future. ## 3.3 CORS requests To enable cross origin requests to the remote api add the flag "--api-enable-cors" when running docker in daemon mode. $ docker -d -H="192.168.1.9:2375" --api-enable-cors ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/hub_registry_spec.md ================================================ # The Docker Hub and the Registry v1 ## The three roles There are three major components playing a role in the Docker ecosystem. ### Docker Hub The Docker Hub is responsible for centralizing information about: - User accounts - Checksums of the images - Public namespaces The Docker Hub has different components: - Web UI - Meta-data store (comments, stars, list public repositories) - Authentication service - Tokenization The Docker Hub is authoritative for that information. There is only one instance of the Docker Hub, run and managed by Docker Inc. ### Docker Registry 1.0 The 1.0 registry has the following characteristics: - It stores the images and the graph for a set of repositories - It does not have user accounts data - It has no notion of user accounts or authorization - It delegates authentication and authorization to the Docker Hub Auth service using tokens - It supports different storage backends (S3, cloud files, local FS) - It doesn't have a local database - [Source Code](https://github.com/docker/docker-registry) We expect that there will be multiple registries out there. To help you grasp the context, here are some examples of registries: - **sponsor registry**: such a registry is provided by a third-party hosting infrastructure as a convenience for their customers and the Docker community as a whole. Its costs are supported by the third party, but the management and operation of the registry are supported by Docker, Inc. It features read/write access, and delegates authentication and authorization to the Docker Hub. - **mirror registry**: such a registry is provided by a third-party hosting infrastructure but is targeted at their customers only. Some mechanism (unspecified to date) ensures that public images are pulled from a sponsor registry to the mirror registry, to make sure that the customers of the third-party provider can `docker pull` those images locally. - **vendor registry**: such a registry is provided by a software vendor who wants to distribute docker images. It would be operated and managed by the vendor. Only users authorized by the vendor would be able to get write access. Some images would be public (accessible for anyone), others private (accessible only for authorized users). Authentication and authorization would be delegated to the Docker Hub. The goal of vendor registries is to let someone do `docker pull basho/riak1.3` and automatically push from the vendor registry (instead of a sponsor registry); i.e., vendors get all the convenience of a sponsor registry, while retaining control on the asset distribution. - **private registry**: such a registry is located behind a firewall, or protected by an additional security layer (HTTP authorization, SSL client-side certificates, IP address authorization...). The registry is operated by a private entity, outside of Docker's control. It can optionally delegate additional authorization to the Docker Hub, but it is not mandatory. > **Note:** The latter implies that while HTTP is the protocol > of choice for a registry, multiple schemes are possible (and > in some cases, trivial): > > - HTTP with GET (and PUT for read-write registries); > - local mount point; > - remote docker addressed through SSH. The latter would only require two new commands in Docker, e.g., `registryget` and `registryput`, wrapping access to the local filesystem (and optionally doing consistency checks). Authentication and authorization are then delegated to SSH (e.g., with public keys). ### Docker On top of being a runtime for LXC, Docker is the Registry client. It supports: - Push / Pull on the registry - Client authentication on the Docker Hub ## Workflow ### Pull ![](/static_files/docker_pull_chart.png) 1. Contact the Docker Hub to know where I should download “samalba/busybox” 2. Docker Hub replies: a. `samalba/busybox` is on Registry A b. here are the checksums for `samalba/busybox` (for all layers) c. token 3. Contact Registry A to receive the layers for `samalba/busybox` (all of them to the base image). Registry A is authoritative for “samalba/busybox” but keeps a copy of all inherited layers and serve them all from the same location. 4. registry contacts Docker Hub to verify if token/user is allowed to download images 5. Docker Hub returns true/false lettings registry know if it should proceed or error out 6. Get the payload for all layers It's possible to run: $ docker pull https:///repositories/samalba/busybox In this case, Docker bypasses the Docker Hub. However the security is not guaranteed (in case Registry A is corrupted) because there won't be any checksum checks. Currently registry redirects to s3 urls for downloads, going forward all downloads need to be streamed through the registry. The Registry will then abstract the calls to S3 by a top-level class which implements sub-classes for S3 and local storage. Token is only returned when the `X-Docker-Token` header is sent with request. Basic Auth is required to pull private repos. Basic auth isn't required for pulling public repos, but if one is provided, it needs to be valid and for an active account. **API (pulling repository foo/bar):** 1. (Docker -> Docker Hub) GET /v1/repositories/foo/bar/images: **Headers**: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== X-Docker-Token: true **Action**: (looking up the foo/bar in db and gets images and checksums for that repo (all if no tag is specified, if tag, only checksums for those tags) see part 4.4.1) 2. (Docker Hub -> Docker) HTTP 200 OK **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write X-Docker-Endpoints: registry.docker.io [,registry2.docker.io] **Body**: Jsonified checksums (see part 4.4.1) 3. (Docker -> Registry) GET /v1/repositories/foo/bar/tags/latest **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write 4. (Registry -> Docker Hub) GET /v1/repositories/foo/bar/images **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=read **Body**: **Action**: (Lookup token see if they have access to pull.) If good: HTTP 200 OK Docker Hub will invalidate the token If bad: HTTP 401 Unauthorized 5. (Docker -> Registry) GET /v1/images/928374982374/ancestry **Action**: (for each image id returned in the registry, fetch /json + /layer) > **Note**: > If someone makes a second request, then we will always give a new token, > never reuse tokens. ### Push ![](/static_files/docker_push_chart.png) 1. Contact the Docker Hub to allocate the repository name “samalba/busybox” (authentication required with user credentials) 2. If authentication works and namespace available, “samalba/busybox” is allocated and a temporary token is returned (namespace is marked as initialized in Docker Hub) 3. Push the image on the registry (along with the token) 4. Registry A contacts the Docker Hub to verify the token (token must corresponds to the repository name) 5. Docker Hub validates the token. Registry A starts reading the stream pushed by docker and store the repository (with its images) 6. docker contacts the Docker Hub to give checksums for upload images > **Note:** > **It's possible not to use the Docker Hub at all!** In this case, a deployed > version of the Registry is deployed to store and serve images. Those > images are not authenticated and the security is not guaranteed. > **Note:** > **Docker Hub can be replaced!** For a private Registry deployed, a custom > Docker Hub can be used to serve and validate token according to different > policies. Docker computes the checksums and submit them to the Docker Hub at the end of the push. When a repository name does not have checksums on the Docker Hub, it means that the push is in progress (since checksums are submitted at the end). **API (pushing repos foo/bar):** 1. (Docker -> Docker Hub) PUT /v1/repositories/foo/bar/ **Headers**: Authorization: Basic sdkjfskdjfhsdkjfh== X-Docker-Token: true **Action**: - in Docker Hub, we allocated a new repository, and set to initialized **Body**: (The body contains the list of images that are going to be pushed, with empty checksums. The checksums will be set at the end of the push): [{“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”}] 2. (Docker Hub -> Docker) 200 Created **Headers**: WWW-Authenticate: Token signature=123abc,repository=”foo/bar”,access=write X-Docker-Endpoints: registry.docker.io [, registry2.docker.io] 3. (Docker -> Registry) PUT /v1/images/98765432_parent/json **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write 4. (Registry->Docker Hub) GET /v1/repositories/foo/bar/images **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write **Action**: - Docker Hub: will invalidate the token. - Registry: grants a session (if token is approved) and fetches the images id 5. (Docker -> Registry) PUT /v1/images/98765432_parent/json **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=write Cookie: (Cookie provided by the Registry) 6. (Docker -> Registry) PUT /v1/images/98765432/json **Headers**: Cookie: (Cookie provided by the Registry) 7. (Docker -> Registry) PUT /v1/images/98765432_parent/layer **Headers**: Cookie: (Cookie provided by the Registry) 8. (Docker -> Registry) PUT /v1/images/98765432/layer **Headers**: X-Docker-Checksum: sha256:436745873465fdjkhdfjkgh 9. (Docker -> Registry) PUT /v1/repositories/foo/bar/tags/latest **Headers**: Cookie: (Cookie provided by the Registry) **Body**: “98765432” 10. (Docker -> Docker Hub) PUT /v1/repositories/foo/bar/images **Headers**: Authorization: Basic 123oislifjsldfj== X-Docker-Endpoints: registry1.docker.io (no validation on this right now) **Body**: (The image, id`s, tags and checksums) [{“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”, “checksum”: “b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087”}] **Return**: HTTP 204 > **Note:** If push fails and they need to start again, what happens in the Docker Hub, > there will already be a record for the namespace/name, but it will be > initialized. Should we allow it, or mark as name already used? One edge > case could be if someone pushes the same thing at the same time with two > different shells. If it's a retry on the Registry, Docker has a cookie (provided by the registry after token validation). So the Docker Hub won't have to provide a new token. ### Delete If you need to delete something from the Docker Hub or registry, we need a nice clean way to do that. Here is the workflow. 1. Docker contacts the Docker Hub to request a delete of a repository `samalba/busybox` (authentication required with user credentials) 2. If authentication works and repository is valid, `samalba/busybox` is marked as deleted and a temporary token is returned 3. Send a delete request to the registry for the repository (along with the token) 4. Registry A contacts the Docker Hub to verify the token (token must corresponds to the repository name) 5. Docker Hub validates the token. Registry A deletes the repository and everything associated to it. 6. docker contacts the Docker Hub to let it know it was removed from the registry, the Docker Hub removes all records from the database. > **Note**: > The Docker client should present an "Are you sure?" prompt to confirm > the deletion before starting the process. Once it starts it can't be > undone. **API (deleting repository foo/bar):** 1. (Docker -> Docker Hub) DELETE /v1/repositories/foo/bar/ **Headers**: Authorization: Basic sdkjfskdjfhsdkjfh== X-Docker-Token: true **Action**: - in Docker Hub, we make sure it is a valid repository, and set to deleted (logically) **Body**: Empty 2. (Docker Hub -> Docker) 202 Accepted **Headers**: WWW-Authenticate: Token signature=123abc,repository=”foo/bar”,access=delete X-Docker-Endpoints: registry.docker.io [, registry2.docker.io] # list of endpoints where this repo lives. 3. (Docker -> Registry) DELETE /v1/repositories/foo/bar/ **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=delete 4. (Registry->Docker Hub) PUT /v1/repositories/foo/bar/auth **Headers**: Authorization: Token signature=123abc,repository=”foo/bar”,access=delete **Action**: - Docker Hub: will invalidate the token. - Registry: deletes the repository (if token is approved) 5. (Registry -> Docker) 200 OK 200 If success 403 if forbidden 400 if bad request 404 if repository isn't found 6. (Docker -> Docker Hub) DELETE /v1/repositories/foo/bar/ **Headers**: Authorization: Basic 123oislifjsldfj== X-Docker-Endpoints: registry-1.docker.io (no validation on this right now) **Body**: Empty **Return**: HTTP 200 ## How to use the Registry in standalone mode The Docker Hub has two main purposes (along with its fancy social features): - Resolve short names (to avoid passing absolute URLs all the time): username/projectname -> https://registry.docker.io/users//repositories// team/projectname -> https://registry.docker.io/team//repositories// - Authenticate a user as a repos owner (for a central referenced repository) ### Without a Docker Hub Using the Registry without the Docker Hub can be useful to store the images on a private network without having to rely on an external entity controlled by Docker Inc. In this case, the registry will be launched in a special mode (-standalone? ne? -no-index?). In this mode, the only thing which changes is that Registry will never contact the Docker Hub to verify a token. It will be the Registry owner responsibility to authenticate the user who pushes (or even pulls) an image using any mechanism (HTTP auth, IP based, etc...). In this scenario, the Registry is responsible for the security in case of data corruption since the checksums are not delivered by a trusted entity. As hinted previously, a standalone registry can also be implemented by any HTTP server handling GET/PUT requests (or even only GET requests if no write access is necessary). ### With a Docker Hub The Docker Hub data needed by the Registry are simple: - Serve the checksums - Provide and authorize a Token In the scenario of a Registry running on a private network with the need of centralizing and authorizing, it's easy to use a custom Docker Hub. The only challenge will be to tell Docker to contact (and trust) this custom Docker Hub. Docker will be configurable at some point to use a specific Docker Hub, it'll be the private entity responsibility (basically the organization who uses Docker in a private environment) to maintain the Docker Hub and the Docker's configuration among its consumers. ## The API The first version of the api is available here: [https://github.com/jpetazzo/docker/blob/acd51ecea8f5d3c02b00a08176171c59442df8b3/docs/images-repositories-push-pull.md](https://github.com/jpetazzo/docker/blob/acd51ecea8f5d3c02b00a08176171c59442df8b3/docs/images-repositories-push-pull.md) ### Images The format returned in the images is not defined here (for layer and JSON), basically because Registry stores exactly the same kind of information as Docker uses to manage them. The format of ancestry is a line-separated list of image ids, in age order, i.e. the image's parent is on the last line, the parent of the parent on the next-to-last line, etc.; if the image has no parent, the file is empty. GET /v1/images//layer PUT /v1/images//layer GET /v1/images//json PUT /v1/images//json GET /v1/images//ancestry PUT /v1/images//ancestry ### Users ### Create a user (Docker Hub) POST /v1/users: **Body**: {"email": "[sam@docker.com](mailto:sam%40docker.com)", "password": "toto42", "username": "foobar"`} **Validation**: - **username**: min 4 character, max 30 characters, must match the regular expression [a-z0-9_]. - **password**: min 5 characters **Valid**: return HTTP 201 Errors: HTTP 400 (we should create error codes for possible errors) - invalid json - missing field - wrong format (username, password, email, etc) - forbidden name - name already exists > **Note**: > A user account will be valid only if the email has been validated (a > validation link is sent to the email address). ### Update a user (Docker Hub) PUT /v1/users/ **Body**: {"password": "toto"} > **Note**: > We can also update email address, if they do, they will need to reverify > their new email address. ### Login (Docker Hub) Does nothing else but asking for a user authentication. Can be used to validate credentials. HTTP Basic Auth for now, maybe change in future. GET /v1/users **Return**: - Valid: HTTP 200 - Invalid login: HTTP 401 - Account inactive: HTTP 403 Account is not Active ### Tags (Registry) The Registry does not know anything about users. Even though repositories are under usernames, it's just a namespace for the registry. Allowing us to implement organizations or different namespaces per user later, without modifying the Registry's API. The following naming restrictions apply: - Namespaces must match the same regular expression as usernames (See 4.2.1.) - Repository names must match the regular expression [a-zA-Z0-9-_.] ### Get all tags: GET /v1/repositories///tags **Return**: HTTP 200 [ { "layer": "9e89cc6f", "name": "latest" }, { "layer": "b486531f", "name": "0.1.1", } ] **4.3.2 Read the content of a tag (resolve the image id):** GET /v1/repositories///tags/ **Return**: "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f" **4.3.3 Delete a tag (registry):** DELETE /v1/repositories///tags/ ### 4.4 Images (Docker Hub) For the Docker Hub to “resolve” the repository name to a Registry location, it uses the X-Docker-Endpoints header. In other terms, this requests always add a `X-Docker-Endpoints` to indicate the location of the registry which hosts this repository. **4.4.1 Get the images:** GET /v1/repositories///images **Return**: HTTP 200 [{“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”, “checksum”: “[md5:b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087](md5:b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087)”}] ### Add/update the images: You always add images, you never remove them. PUT /v1/repositories///images **Body**: [ {“id”: “9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f”, “checksum”: “sha256:b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087”} ] **Return**: 204 ### Repositories ### Remove a Repository (Registry) DELETE /v1/repositories// Return 200 OK ### Remove a Repository (Docker Hub) This starts the delete process. see 2.3 for more details. DELETE /v1/repositories// Return 202 OK ## Chaining Registries It's possible to chain Registries server for several reasons: - Load balancing - Delegate the next request to another server When a Registry is a reference for a repository, it should host the entire images chain in order to avoid breaking the chain during the download. The Docker Hub and Registry use this mechanism to redirect on one or the other. Example with an image download: On every request, a special header can be returned: X-Docker-Endpoints: server1,server2 On the next request, the client will always pick a server from this list. ## Authentication and authorization ### On the Docker Hub The Docker Hub supports both “Basic” and “Token” challenges. Usually when there is a `401 Unauthorized`, the Docker Hub replies this: 401 Unauthorized WWW-Authenticate: Basic realm="auth required",Token You have 3 options: 1. Provide user credentials and ask for a token **Header**: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== X-Docker-Token: true In this case, along with the 200 response, you'll get a new token (if user auth is ok): If authorization isn't correct you get a 401 response. If account isn't active you will get a 403 response. **Response**: 200 OK X-Docker-Token: Token signature=123abc,repository=”foo/bar”,access=read 2. Provide user credentials only **Header**: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== 3. Provide Token **Header**: Authorization: Token signature=123abc,repository=”foo/bar”,access=read ### 6.2 On the Registry The Registry only supports the Token challenge: 401 Unauthorized WWW-Authenticate: Token The only way is to provide a token on `401 Unauthorized` responses: Authorization: Token signature=123abc,repository="foo/bar",access=read Usually, the Registry provides a Cookie when a Token verification succeeded. Every time the Registry passes a Cookie, you have to pass it back the same cookie.: 200 OK Set-Cookie: session="wD/J7LqL5ctqw8haL10vgfhrb2Q=?foo=UydiYXInCnAxCi4=×tamp=RjEzNjYzMTQ5NDcuNDc0NjQzCi4="; Path=/; HttpOnly Next request: GET /(...) Cookie: session="wD/J7LqL5ctqw8haL10vgfhrb2Q=?foo=UydiYXInCnAxCi4=×tamp=RjEzNjYzMTQ5NDcuNDc0NjQzCi4=" ## Document version - 1.0 : May 6th 2013 : initial release - 1.1 : June 1st 2013 : Added Delete Repository and way to handle new source namespace. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/images/event_state.gliffy ================================================ {"contentType":"application/gliffy+json","version":"1.3","stage":{"background":"#FFFFFF","width":1109,"height":556,"nodeIndex":360,"autoFit":true,"exportBorder":false,"gridOn":true,"snapToGrid":true,"drawingGuidesOn":true,"pageBreaksOn":false,"printGridOn":false,"printPaper":"LETTER","printShrinkToFit":false,"printPortrait":true,"maxWidth":5000,"maxHeight":5000,"themeData":null,"viewportType":"default","fitBB":{"min":{"x":26.46762966848334,"y":100},"max":{"x":1109,"y":555.2340187157677}},"objects":[{"x":373.99998474121094,"y":389.93402099609375,"rotation":0.0,"id":355,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":0,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":191,"py":0.7071067811865475,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":-0.663724900050094,"endArrowRotation":-0.6637248993502937,"interpolationType":"quadratic","cornerRadius":null,"controlPath":[[22.0,-17.0],[94.00000762939453,-17.0],[94.00000762939453,-61.64974974863185],[166.00001525878906,-61.64974974863185]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":359,"width":74.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.5,"linePerpValue":0.0,"cardinalityType":null,"html":"

docker start

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":275.99998474121094,"y":323.93402099609375,"rotation":0.0,"id":344,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":87,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":335,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":193,"py":0.0,"px":0.7071067811865476}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":105.08369488824782,"endArrowRotation":91.96866662391399,"interpolationType":"quadratic","cornerRadius":null,"controlPath":[[22.531977827253513,30.06597900390625],[22.531977827253513,51.06597900390625],[-52.96697615221987,51.06597900390625],[-52.96697615221987,106.06597900390625]],"lockSegments":{"1":true},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":347,"width":63.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker rm

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":279.99998474121094,"y":249.93402099609375,"rotation":0.0,"id":342,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":86,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":188,"py":0.5,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":191,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[-74.99998474121094,0.06597900390625],[297.50001525878906,0.06597900390625],[297.50001525878906,50.06597900390625]],"lockSegments":{},"ortho":true}},"linkMap":[]},{"x":313.99998474121094,"y":290.93402099609375,"rotation":0.0,"id":341,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":84,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":335,"py":0.5,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":191,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[19.531977827253513,28.06597900390625],[88.35546419381131,28.06597900390625],[157.17895056036912,28.06597900390625],[226.00243692692698,28.06597900390625]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":353,"width":74.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker start

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":214.99998474121094,"y":322.93402099609375,"rotation":0.0,"id":340,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":83,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":228,"py":0.5733505249023437,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":335,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[-7.637919363960094,-3.93402099609375],[11.085379699777775,-3.93402099609375],[29.808678763515644,-3.93402099609375],[48.53197782725351,-3.93402099609375]],"lockSegments":{},"ortho":true}},"linkMap":[]},{"x":83.0,"y":251.0,"rotation":0.0,"id":328,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":79,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":188,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-52.03237033151666,-0.9999999999999716],[47.0,-1.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":332,"width":67.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.5233416311379174,"linePerpValue":null,"cardinalityType":null,"html":"

docker run

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":74.0,"y":318.0,"rotation":0.0,"id":327,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":77,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":228,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-42.0,1.0],[58.5,2.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":333,"width":83.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.5689443767164591,"linePerpValue":null,"cardinalityType":null,"html":"

docker create

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":191.0,"y":409.0,"rotation":0.0,"id":325,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":76,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":193,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":215,"py":0.5,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-21.0,41.0],[-61.0,41.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":331.0,"y":346.0,"rotation":0.0,"id":320,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":74,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":209,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":193,"py":0.5,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[2.5319625684644507,49.0],[-41.734018715767775,49.0],[-41.734018715767775,104.0],[-86.0,104.0]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":324,"width":63.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker rm

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":872.0,"y":503.0,"rotation":0.0,"id":310,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":73,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":205,"py":0.0,"px":0.2928932188134524}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-60.03300858899104,-53.0],[-148.0,-151.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[]},{"x":735.0,"y":341.0,"rotation":0.0,"id":307,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":71,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":203,"py":0.2928932188134525,"px":1.1102230246251563E-16}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[0.0,0.0],[137.5,60.7157287525381]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":309,"width":83.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.37922003257116654,"linePerpValue":null,"cardinalityType":null,"html":"

docker pause

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":1023.0,"y":446.0,"rotation":0.0,"id":298,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":69,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":213,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":205,"py":0.5,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[39.5,-1.0],[39.5,24.0],[-158.0,24.0]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":313,"width":101.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.37286693198126664,"linePerpValue":null,"cardinalityType":null,"html":"

 docker unpause

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":904.0,"y":434.0,"rotation":0.0,"id":295,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":68,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":203,"py":0.5,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":213,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[43.5,-24.0],[123.5,-24.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":411.0,"y":419.0,"rotation":0.0,"id":291,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":66,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":217,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":209,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[7.2659812842321685,51.0],[-42.46803743153555,51.0],[-42.46803743153555,11.0]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":292,"width":21.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.4870188236535277,"linePerpValue":null,"cardinalityType":null,"html":"

No

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":415.0,"y":419.0,"rotation":0.0,"id":289,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":64,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":217,"py":0.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":191,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[53.26598128423217,1.0],[53.26598128423217,-32.5],[162.5,-32.5],[162.5,-79.0]],"lockSegments":{"1":true},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":290,"width":26.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.46753493572435184,"linePerpValue":null,"cardinalityType":null,"html":"

Yes

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":521.0,"y":209.0,"rotation":0.0,"id":287,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":63,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":195,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":209,"py":0.5,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[-11.0,-19.0],[-97.23401871576777,-19.0],[-97.23401871576777,186.0],[-117.46803743153555,186.0]],"lockSegments":{"1":true},"ortho":true}},"linkMap":[]},{"x":988.0,"y":232.0,"rotation":0.0,"id":282,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":62,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":201,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[39.5,18.0],[-150.0,18.0],[-150.0,68.0],[-250.0,68.0]],"lockSegments":{"1":true},"ortho":true}},"linkMap":[]},{"x":664.0,"y":493.0,"rotation":0.0,"id":276,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":61,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":207,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":236,"py":0.7071067811865475,"px":0.9999999999999998}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[8.5,42.23401871576766],[-20.25,42.23401871576766],[-20.25,-44.7157287525381],[-49.0,-44.7157287525381]],"lockSegments":{},"ortho":true}},"linkMap":[]},{"x":678.0,"y":344.0,"rotation":0.0,"id":273,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":59,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":236,"py":0.29289321881345237,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":91.17113025781374,"endArrowRotation":176.63803454243802,"interpolationType":"quadratic","cornerRadius":null,"controlPath":[[2.0,-4.0],[2.0,87.7157287525381],[-63.0,87.7157287525381]],"lockSegments":{},"ortho":true}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":275,"width":57.0,"height":40.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.5,"linePerpValue":0.0,"cardinalityType":null,"html":"

container 

process

exited

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":566.0,"y":431.0,"rotation":0.0,"id":272,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":58,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":236,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":217,"py":0.5,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[-26.0,9.0],[-36.867009357883944,9.0],[-36.867009357883944,39.0],[-47.73401871576789,39.0]],"lockSegments":{},"ortho":true}},"linkMap":[]},{"x":785.0,"y":119.0,"rotation":0.0,"id":270,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":57,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":199,"py":0.5,"px":0.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":209,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":10.0,"controlPath":[[5.0,1.0],[-416.46803743153555,1.0],[-416.46803743153555,241.0]],"lockSegments":{},"ortho":true}},"linkMap":[]},{"x":829.0,"y":172.0,"rotation":0.0,"id":269,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":56,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":248,"py":0.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":199,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-1.5,-2.0],[-1.5,-32.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":661.0,"y":189.0,"rotation":0.0,"id":267,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":55,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":195,"py":0.5,"px":1.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[7.0,2.284271247461902],[-76.0,1.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":946.0,"y":319.0,"rotation":0.0,"id":263,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":53,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":197,"py":0.5,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":233,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[1.5,1.0],[81.5,1.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":708.0,"y":286.0,"rotation":0.0,"id":256,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":51,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":211,"py":0.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":254,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-0.5,-2.0],[-0.5,-76.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":258,"width":64.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.3108108108108108,"linePerpValue":null,"cardinalityType":null,"html":"

docker kill

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":710.0,"y":359.0,"rotation":0.0,"id":245,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":43,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":211,"py":1.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":207,"py":0.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-2.5,-5.0],[0.0,156.23401871576766]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":247,"width":83.0,"height":27.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

 killed by

out-of-memory

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":761.0,"y":318.0,"rotation":0.0,"id":238,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":41,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":211,"py":0.5,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":197,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-18.5,1.0],[111.5,2.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":240,"width":85.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":0.4363456059259962,"linePerpValue":null,"cardinalityType":null,"html":"

docker restart

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":608.0,"y":319.0,"rotation":0.0,"id":232,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":36,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":191,"py":0.5,"px":1.0}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":211,"py":0.5,"px":0.0}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[7.0,1.0],[64.5,0.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":333.53196256846445,"y":360.0,"rotation":0.0,"id":209,"width":70.0,"height":70.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.connector","order":21,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#e6b8af","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5555555555555554,"y":0.0,"rotation":0.0,"id":210,"width":66.88888888888889,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

stopped

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":540.0,"y":300.0,"rotation":0.0,"id":191,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":3,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":192,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

start

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":510.0,"y":170.0,"rotation":0.0,"id":195,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":7,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":196,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

kill

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":872.5,"y":300.0,"rotation":0.0,"id":197,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":9,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":198,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

die

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":790.0,"y":100.0,"rotation":0.0,"id":199,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":11,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":200,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

stop

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":790.0,"y":450.0,"rotation":0.0,"id":205,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":17,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":206,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

unpause

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":672.5,"y":515.2340187157677,"rotation":0.0,"id":207,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":19,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":208,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

OOM

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":672.5,"y":284.0,"rotation":0.0,"id":211,"width":70.0,"height":70.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.connector","order":23,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#b6d7a8","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5555555555555556,"y":0.0,"rotation":0.0,"id":212,"width":66.88888888888889,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

running

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":403.5319625684644,"y":420.0,"rotation":0.0,"id":227,"width":130.46803743153555,"height":116.23401871576777,"uid":"com.gliffy.shape.basic.basic_v1.default.group","order":33,"lockAspectRatio":false,"lockShape":false,"children":[{"x":-6.765981284232225,"y":76.0,"rotation":45.0,"id":223,"width":80.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":32,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Restart 

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[]},{"x":57.234018715767775,"y":75.0,"rotation":315.0,"id":219,"width":80.0,"height":14.0,"uid":"com.gliffy.shape.basic.basic_v1.default.text","order":31,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Policy

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}},"linkMap":[]},{"x":14.734018715767775,"y":0.0,"rotation":0.0,"id":217,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.decision","order":29,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.diamond.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":2.0,"y":0.0,"rotation":0.0,"id":218,"width":96.0,"height":27.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

Should restart?

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]}]},{"x":1027.5,"y":375.0,"rotation":0.0,"id":213,"width":70.0,"height":70.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.connector","order":25,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#fce5cd","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5555555555555556,"y":0.0,"rotation":0.0,"id":214,"width":66.88888888888889,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

paused

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":872.5,"y":390.0,"rotation":0.0,"id":203,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":15,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":204,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

pause

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":540.0,"y":420.0,"rotation":0.0,"id":236,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":39,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":237,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

die

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":790.0,"y":170.0,"rotation":0.0,"id":248,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":45,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":249,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

die

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":670.0,"y":170.0,"rotation":0.0,"id":254,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":49,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":255,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

die

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":740.0,"y":323.0,"rotation":0.0,"id":250,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":47,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":248,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-10.0,-33.0],[87.5,-113.0]],"lockSegments":{},"ortho":false}},"linkMap":[],"children":[{"x":0.0,"y":0.0,"rotation":0.0,"id":253,"width":73.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"both","paddingTop":2,"paddingRight":2,"paddingBottom":2,"paddingLeft":2,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

docker stop

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":1027.5,"y":300.0,"rotation":0.0,"id":233,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":37,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":234,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

start

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":1027.5,"y":230.0,"rotation":0.0,"id":201,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":13,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":202,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

restart

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":1066.5,"y":298.0,"rotation":0.0,"id":264,"width":100.0,"height":100.0,"uid":"com.gliffy.shape.basic.basic_v1.default.line","order":54,"lockAspectRatio":false,"lockShape":false,"constraints":{"constraints":[],"startConstraint":{"type":"StartPositionConstraint","StartPositionConstraint":{"nodeId":233,"py":0.0,"px":0.5}},"endConstraint":{"type":"EndPositionConstraint","EndPositionConstraint":{"nodeId":201,"py":1.0,"px":0.5}}},"graphic":{"type":"Line","Line":{"strokeWidth":2.0,"strokeColor":"#000000","fillColor":"none","dashStyle":null,"startArrow":0,"endArrow":1,"startArrowRotation":"auto","endArrowRotation":"auto","interpolationType":"linear","cornerRadius":null,"controlPath":[[-1.5,2.0],[-1.5,-28.0]],"lockSegments":{},"ortho":false}},"linkMap":[]},{"x":132.5,"y":300.0,"rotation":0.0,"id":228,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":34,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":229,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

create

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":130.0,"y":230.0,"rotation":0.0,"id":188,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":1,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":190,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

create

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":263.53196256846445,"y":284.0,"rotation":0.0,"id":335,"width":70.0,"height":70.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.connector","order":81,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#a4c2f4","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5555555555555554,"y":0.0,"rotation":0.0,"id":336,"width":66.88888888888889,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

created

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":60.0,"y":415.0,"rotation":0.0,"id":215,"width":70.0,"height":70.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.connector","order":27,"lockAspectRatio":true,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.ellipse.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#b7b7b7","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5555555555555556,"y":0.0,"rotation":0.0,"id":216,"width":66.88888888888889,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

deleted

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]},{"x":170.0,"y":430.0,"rotation":0.0,"id":193,"width":75.0,"height":40.0,"uid":"com.gliffy.shape.flowchart.flowchart_v1.default.process","order":5,"lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Shape","Shape":{"tid":"com.gliffy.stencil.rectangle.basic_v1","strokeWidth":2.0,"strokeColor":"#333333","fillColor":"#FFFFFF","gradient":false,"dashStyle":null,"dropShadow":false,"state":0,"opacity":1.0,"shadowX":0.0,"shadowY":0.0}},"linkMap":[],"children":[{"x":1.5,"y":0.0,"rotation":0.0,"id":194,"width":72.0,"height":13.0,"uid":null,"order":"auto","lockAspectRatio":false,"lockShape":false,"graphic":{"type":"Text","Text":{"overflow":"none","paddingTop":8,"paddingRight":8,"paddingBottom":8,"paddingLeft":8,"outerPaddingTop":6,"outerPaddingRight":6,"outerPaddingBottom":2,"outerPaddingLeft":6,"type":"fixed","lineTValue":null,"linePerpValue":null,"cardinalityType":null,"html":"

destroy

","tid":null,"valign":"middle","vposition":"none","hposition":"none"}}}]}],"shapeStyles":{"com.gliffy.shape.uml.uml_v2.state_machine":{"fill":"#e2e2e2","stroke":"#000000","strokeWidth":2},"com.gliffy.shape.flowchart.flowchart_v1.default":{"fill":"#a4c2f4","stroke":"#333333","strokeWidth":2}},"lineStyles":{"global":{"endArrow":1,"orthoMode":2}},"textStyles":{"global":{"bold":true,"color":"#000000"}}},"metadata":{"title":"untitled","revision":0,"exportBorder":false,"loadPosition":"default","libraries":["com.gliffy.libraries.flowchart.flowchart_v1.default","com.gliffy.libraries.images"]},"embeddedResources":{"index":0,"resources":[]}} ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/registry_api.md ================================================ # Docker Registry API v1 ## Introduction - This is the REST API for the Docker Registry 1.0 - It stores the images and the graph for a set of repositories - It does not have user accounts data - It has no notion of user accounts or authorization - It delegates authentication and authorization to the Index Auth service using tokens - It supports different storage backends (S3, cloud files, local FS) - It doesn't have a local database - The registry is open source: [Docker Registry](https://github.com/docker/docker-registry) We expect that there will be multiple registries out there. To help to grasp the context, here are some examples of registries: - **sponsor registry**: such a registry is provided by a third-party hosting infrastructure as a convenience for their customers and the Docker community as a whole. Its costs are supported by the third party, but the management and operation of the registry are supported by Docker. It features read/write access, and delegates authentication and authorization to the Index. - **mirror registry**: such a registry is provided by a third-party hosting infrastructure but is targeted at their customers only. Some mechanism (unspecified to date) ensures that public images are pulled from a sponsor registry to the mirror registry, to make sure that the customers of the third-party provider can `docker pull` those images locally. - **vendor registry**: such a registry is provided by a software vendor, who wants to distribute Docker images. It would be operated and managed by the vendor. Only users authorized by the vendor would be able to get write access. Some images would be public (accessible for anyone), others private (accessible only for authorized users). Authentication and authorization would be delegated to the Index. The goal of vendor registries is to let someone do `docker pull basho/riak1.3` and automatically push from the vendor registry (instead of a sponsor registry); i.e., get all the convenience of a sponsor registry, while retaining control on the asset distribution. - **private registry**: such a registry is located behind a firewall, or protected by an additional security layer (HTTP authorization, SSL client-side certificates, IP address authorization...). The registry is operated by a private entity, outside of Docker's control. It can optionally delegate additional authorization to the Index, but it is not mandatory. > **Note**: > Mirror registries and private registries which do not use the Index > don't even need to run the registry code. They can be implemented by any > kind of transport implementing HTTP GET and PUT. Read-only registries > can be powered by a simple static HTTPS server. > **Note**: > The latter implies that while HTTP is the protocol of choice for a registry, > multiple schemes are possible (and in some cases, trivial): > > - HTTP with GET (and PUT for read-write registries); > - local mount point; > - remote Docker addressed through SSH. The latter would only require two new commands in Docker, e.g., `registryget` and `registryput`, wrapping access to the local filesystem (and optionally doing consistency checks). Authentication and authorization are then delegated to SSH (e.g., with public keys). > **Note**: > Private registry servers that expose an HTTP endpoint need to be secured with > TLS (preferably TLSv1.2, but at least TLSv1.0). Make sure to put the CA > certificate at /etc/docker/certs.d/my.registry.com:5000/ca.crt on the Docker > host, so that the daemon can securely access the private registry. > Support for SSLv3 and lower is not available due to security issues. The default namespace for a private repository is `library`. # Endpoints ## Images ### Get image layer `GET /v1/images/(image_id)/layer` Get image layer for a given `image_id` **Example Request**: GET /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/layer HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Authorization: Token signature=123abc,repository="foo/bar",access=read Parameters: - **image_id** – the id for the layer you want to get **Example Response**: HTTP/1.1 200 Vary: Accept X-Docker-Registry-Version: 0.6.0 Cookie: (Cookie provided by the Registry) {layer binary data stream} Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Image not found ### Put image layer `PUT /v1/images/(image_id)/layer` Put image layer for a given `image_id` **Example Request**: PUT /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/layer HTTP/1.1 Host: registry-1.docker.io Transfer-Encoding: chunked Authorization: Token signature=123abc,repository="foo/bar",access=write {layer binary data stream} Parameters: - **image_id** – the id for the layer you want to get **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Image not found ## Image ### Put image layer `PUT /v1/images/(image_id)/json` Put image for a given `image_id` **Example Request**: PUT /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/json HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) { id: "088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c", parent: "aeee6396d62273d180a49c96c62e45438d87c7da4a5cf5d2be6bee4e21bc226f", created: "2013-04-30T17:46:10.843673+03:00", container: "8305672a76cc5e3d168f97221106ced35a76ec7ddbb03209b0f0d96bf74f6ef7", container_config: { Hostname: "host-test", User: "", Memory: 0, MemorySwap: 0, AttachStdin: false, AttachStdout: false, AttachStderr: false, Tty: false, OpenStdin: false, StdinOnce: false, Env: null, Cmd: [ "/bin/bash", "-c", "apt-get -q -yy -f install libevent-dev" ], Dns: null, Image: "imagename/blah", Volumes: { }, VolumesFrom: "" }, docker_version: "0.1.7" } Parameters: - **image_id** – the id for the layer you want to get **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" Status Codes: - **200** – OK - **401** – Requires authorization ### Get image layer `GET /v1/images/(image_id)/json` Get image for a given `image_id` **Example Request**: GET /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/json HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) Parameters: - **image_id** – the id for the layer you want to get **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 X-Docker-Size: 456789 X-Docker-Checksum: b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087 { id: "088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c", parent: "aeee6396d62273d180a49c96c62e45438d87c7da4a5cf5d2be6bee4e21bc226f", created: "2013-04-30T17:46:10.843673+03:00", container: "8305672a76cc5e3d168f97221106ced35a76ec7ddbb03209b0f0d96bf74f6ef7", container_config: { Hostname: "host-test", User: "", Memory: 0, MemorySwap: 0, AttachStdin: false, AttachStdout: false, AttachStderr: false, Tty: false, OpenStdin: false, StdinOnce: false, Env: null, Cmd: [ "/bin/bash", "-c", "apt-get -q -yy -f install libevent-dev" ], Dns: null, Image: "imagename/blah", Volumes: { }, VolumesFrom: "" }, docker_version: "0.1.7" } Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Image not found ## Ancestry ### Get image ancestry `GET /v1/images/(image_id)/ancestry` Get ancestry for an image given an `image_id` **Example Request**: GET /v1/images/088b4505aa3adc3d35e79c031fa126b403200f02f51920fbd9b7c503e87c7a2c/ancestry HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) Parameters: - **image_id** – the id for the layer you want to get **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 ["088b4502f51920fbd9b7c503e87c7a2c05aa3adc3d35e79c031fa126b403200f", "aeee63968d87c7da4a5cf5d2be6bee4e21bc226fd62273d180a49c96c62e4543", "bfa4c5326bc764280b0863b46a4b20d940bc1897ef9c1dfec060604bdc383280", "6ab5893c6927c15a15665191f2c6cf751f5056d8b95ceee32e43c5e8a3648544"] Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Image not found ## Tags ### List repository tags `GET /v1/repositories/(namespace)/(repository)/tags` Get all of the tags for the given repo. **Example Request**: GET /v1/repositories/reynholm/help-system-server/tags HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json X-Docker-Registry-Version: 0.6.0 Cookie: (Cookie provided by the Registry) Parameters: - **namespace** – namespace for the repo - **repository** – name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 { "latest": "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f", "0.1.1": "b486531f9a779a0c17e3ed29dae8f12c4f9e89cc6f0bc3c38722009fe6857087" } Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Repository not found ### Get image id for a particular tag `GET /v1/repositories/(namespace)/(repository)/tags/(tag*)` Get a tag for the given repo. **Example Request**: GET /v1/repositories/reynholm/help-system-server/tags/latest HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json X-Docker-Registry-Version: 0.6.0 Cookie: (Cookie provided by the Registry) Parameters: - **namespace** – namespace for the repo - **repository** – name for the repo - **tag** – name of tag you want to get **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f" Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Tag not found ### Delete a repository tag `DELETE /v1/repositories/(namespace)/(repository)/tags/(tag*)` Delete the tag for the repo **Example Request**: DELETE /v1/repositories/reynholm/help-system-server/tags/latest HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) Parameters: - **namespace** – namespace for the repo - **repository** – name for the repo - **tag** – name of tag you want to delete **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Tag not found ### Set a tag for a specified image id `PUT /v1/repositories/(namespace)/(repository)/tags/(tag*)` Put a tag for the given repo. **Example Request**: PUT /v1/repositories/reynholm/help-system-server/tags/latest HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) "9e89cc6f0bc3c38722009fe6857087b486531f9a779a0c17e3ed29dae8f12c4f" Parameters: - **namespace** – namespace for the repo - **repository** – name for the repo - **tag** – name of tag you want to add **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" Status Codes: - **200** – OK - **400** – Invalid data - **401** – Requires authorization - **404** – Image not found ## Repositories ### Delete a repository `DELETE /v1/repositories/(namespace)/(repository)/` Delete a repository **Example Request**: DELETE /v1/repositories/reynholm/help-system-server/ HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json Cookie: (Cookie provided by the Registry) "" Parameters: - **namespace** – namespace for the repo - **repository** – name for the repo **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" Status Codes: - **200** – OK - **401** – Requires authorization - **404** – Repository not found ## Search If you need to search the index, this is the endpoint you would use. `GET /v1/search` Search the Index given a search term. It accepts [GET](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3) only. **Example request**: GET /v1/search?q=search_term&page=1&n=25 HTTP/1.1 Host: index.docker.io Accept: application/json Query Parameters: - **q** – what you want to search for - **n** - number of results you want returned per page (default: 25, min:1, max:100) - **page** - page number of results **Example response**: HTTP/1.1 200 OK Vary: Accept Content-Type: application/json {"num_pages": 1, "num_results": 3, "results" : [ {"name": "ubuntu", "description": "An ubuntu image..."}, {"name": "centos", "description": "A centos image..."}, {"name": "fedora", "description": "A fedora image..."} ], "page_size": 25, "query":"search_term", "page": 1 } Response Items: - **num_pages** - Total number of pages returned by query - **num_results** - Total number of results returned by query - **results** - List of results for the current page - **page_size** - How many results returned per page - **query** - Your search term - **page** - Current page number Status Codes: - **200** – no error - **500** – server error ## Status ### Status check for registry `GET /v1/_ping` Check status of the registry. This endpoint is also used to determine if the registry supports SSL. **Example Request**: GET /v1/_ping HTTP/1.1 Host: registry-1.docker.io Accept: application/json Content-Type: application/json "" **Example Response**: HTTP/1.1 200 Vary: Accept Content-Type: application/json X-Docker-Registry-Version: 0.6.0 "" Status Codes: - **200** – OK ## Authorization This is where we describe the authorization process, including the tokens and cookies. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/registry_api_client_libraries.md ================================================ # Docker Registry v1 API client libraries These libraries have not been tested by the Docker maintainers for compatibility. Please file issues with the library owners. If you find more library implementations, please submit a PR with an update to this page or open an issue in the [Docker](https://github.com/docker/docker/issues) project and we will add the libraries here.
Language/Framework Name Repository Status
JavaScript (AngularJS) WebUI docker-registry-frontend https://github.com/kwk/docker-registry-frontend Active
Go docker-reg-client https://github.com/CenturyLinkLabs/docker-reg-client Active
================================================ FILE: vendor/github.com/docker/docker/docs/reference/api/remote_api_client_libraries.md ================================================ # Docker Remote API client libraries These libraries have not been tested by the Docker maintainers for compatibility. Please file issues with the library owners. If you find more library implementations, please list them in Docker doc bugs and we will add the libraries here.
Language/Framework Name Repository Status
C# Docker.DotNet https://github.com/ahmetalpbalkan/Docker.DotNet Active
C++ lasote/docker_client http://www.biicode.com/lasote/docker_client (Biicode C++ dependency manager) Active
Erlang erldocker https://github.com/proger/erldocker Active
Dart bwu_docker https://github.com/bwu-dart/bwu_docker Active
Go go-dockerclient https://github.com/fsouza/go-dockerclient Active
Go dockerclient https://github.com/samalba/dockerclient Active
Gradle gradle-docker-plugin https://github.com/gesellix/gradle-docker-plugin Active
Groovy docker-client https://github.com/gesellix/docker-client Active
Haskell docker-hs https://github.com/denibertovic/docker-hs Active
Java docker-java https://github.com/docker-java/docker-java Active
Java docker-client https://github.com/spotify/docker-client Active
Java jclouds-docker https://github.com/jclouds/jclouds-labs/tree/master/docker Active
JavaScript (NodeJS) dockerode https://github.com/apocas/dockerode Install via NPM: npm install dockerode Active
JavaScript (NodeJS) docker.io https://github.com/appersonlabs/docker.io Install via NPM: npm install docker.io Active
JavaScript docker-js https://github.com/dgoujard/docker-js Outdated
JavaScript (Angular) WebUI docker-cp https://github.com/13W/docker-cp Active
JavaScript (Angular) WebUI dockerui https://github.com/crosbymichael/dockerui Active
JavaScript (Angular) WebUI dockery https://github.com/lexandro/dockery Active
Perl Net::Docker https://metacpan.org/pod/Net::Docker Active
Perl Eixo::Docker https://github.com/alambike/eixo-docker Active
PHP Alvine http://pear.alvine.io/ (alpha) Active
PHP Docker-PHP http://stage1.github.io/docker-php/ Active
Python docker-py https://github.com/docker/docker-py Active
Ruby docker-api https://github.com/swipely/docker-api Active
Ruby docker-client https://github.com/geku/docker-client Outdated
Rust docker-rust https://github.com/abh1nav/docker-rust Active
Scala tugboat https://github.com/softprops/tugboat Active
Scala reactive-docker https://github.com/almoehi/reactive-docker Active
================================================ FILE: vendor/github.com/docker/docker/docs/reference/builder.md ================================================ # Dockerfile reference **Docker can build images automatically** by reading the instructions from a `Dockerfile`. A `Dockerfile` is a text document that contains all the commands you would normally execute manually in order to build a Docker image. By calling `docker build` from your terminal, you can have Docker build your image step by step, executing the instructions successively. This page discusses the specifics of all the instructions you can use in your `Dockerfile`. To further help you write a clear, readable, maintainable `Dockerfile`, we've also written a [`Dockerfile` Best Practices guide](/articles/dockerfile_best-practices). Lastly, you can test your Dockerfile knowledge with the [Dockerfile tutorial](/userguide/level1). ## Usage To [*build*](/reference/commandline/cli/#build) an image from a source repository, create a description file called `Dockerfile` at the root of your repository. This file will describe the steps to assemble the image. Then call `docker build` with the path of your source repository as the argument (for example, `.`): $ docker build . The path to the source repository defines where to find the *context* of the build. The build is run by the Docker daemon, not by the CLI, so the whole context must be transferred to the daemon. The Docker CLI reports "Sending build context to Docker daemon" when the context is sent to the daemon. > **Warning** > Avoid using your root directory, `/`, as the root of the source repository. The > `docker build` command will use whatever directory contains the Dockerfile as the build > context (including all of its subdirectories). The build context will be sent to the > Docker daemon before building the image, which means if you use `/` as the source > repository, the entire contents of your hard drive will get sent to the daemon (and > thus to the machine running the daemon). You probably don't want that. In most cases, it's best to put each Dockerfile in an empty directory. Then, only add the files needed for building the Dockerfile to the directory. To increase the build's performance, you can exclude files and directories by adding a `.dockerignore` file to the directory. For information about how to [create a `.dockerignore` file](#dockerignore-file) on this page. You can specify a repository and tag at which to save the new image if the build succeeds: $ docker build -t shykes/myapp . The Docker daemon will run your steps one-by-one, committing the result to a new image if necessary, before finally outputting the ID of your new image. The Docker daemon will automatically clean up the context you sent. Note that each instruction is run independently, and causes a new image to be created - so `RUN cd /tmp` will not have any effect on the next instructions. Whenever possible, Docker will re-use the intermediate images, accelerating `docker build` significantly (indicated by `Using cache` - see the [`Dockerfile` Best Practices guide](/articles/dockerfile_best-practices/#build-cache) for more information): $ docker build -t SvenDowideit/ambassador . Uploading context 10.24 kB Uploading context Step 1 : FROM docker-ut ---> cbba202fe96b Step 2 : MAINTAINER SvenDowideit@home.org.au ---> Using cache ---> 51182097be13 Step 3 : CMD env | grep _TCP= | sed 's/.*_PORT_\([0-9]*\)_TCP=tcp:\/\/\(.*\):\(.*\)/socat TCP4-LISTEN:\1,fork,reuseaddr TCP4:\2:\3 \&/' | sh && top ---> Using cache ---> 1a5ffc17324d Successfully built 1a5ffc17324d When you're done with your build, you're ready to look into [*Pushing a repository to its registry*]( /userguide/dockerrepos/#contributing-to-docker-hub). ## Format Here is the format of the `Dockerfile`: # Comment INSTRUCTION arguments The Instruction is not case-sensitive, however convention is for them to be UPPERCASE in order to distinguish them from arguments more easily. Docker runs the instructions in a `Dockerfile` in order. **The first instruction must be \`FROM\`** in order to specify the [*Base Image*](/terms/image/#base-image) from which you are building. Docker will treat lines that *begin* with `#` as a comment. A `#` marker anywhere else in the line will be treated as an argument. This allows statements like: # Comment RUN echo 'we are running some # of cool things' Here is the set of instructions you can use in a `Dockerfile` for building images. ### Environment replacement > **Note**: prior to 1.3, `Dockerfile` environment variables were handled > similarly, in that they would be replaced as described below. However, there > was no formal definition on as to which instructions handled environment > replacement at the time. After 1.3 this behavior will be preserved and > canonical. Environment variables (declared with [the `ENV` statement](#env)) can also be used in certain instructions as variables to be interpreted by the `Dockerfile`. Escapes are also handled for including variable-like syntax into a statement literally. Environment variables are notated in the `Dockerfile` either with `$variable_name` or `${variable_name}`. They are treated equivalently and the brace syntax is typically used to address issues with variable names with no whitespace, like `${foo}_bar`. The `${variable_name}` syntax also supports a few of the standard `bash` modifiers as specified below: * `${variable:-word}` indicates that if `variable` is set then the result will be that value. If `variable` is not set then `word` will be the result. * `${variable:+word}` indicates that if `variable` is set then `word` will be the result, otherwise the result is the empty string. In all cases, `word` can be any string, including additional environment variables. Escaping is possible by adding a `\` before the variable: `\$foo` or `\${foo}`, for example, will translate to `$foo` and `${foo}` literals respectively. Example (parsed representation is displayed after the `#`): FROM busybox ENV foo /bar WORKDIR ${foo} # WORKDIR /bar ADD . $foo # ADD . /bar COPY \$foo /quux # COPY $foo /quux The instructions that handle environment variables in the `Dockerfile` are: * `ENV` * `ADD` * `COPY` * `WORKDIR` * `EXPOSE` * `VOLUME` * `USER` `ONBUILD` instructions are **NOT** supported for environment replacement, even the instructions above. Environment variable substitution will use the same value for each variable throughout the entire command. In other words, in this example: ENV abc=hello ENV abc=bye def=$abc ENV ghi=$abc will result in `def` having a value of `hello`, not `bye`. However, `ghi` will have a value of `bye` because it is not part of the same command that set `abc` to `bye`. ### .dockerignore file If a file named `.dockerignore` exists in the root of `PATH`, then Docker interprets it as a newline-separated list of exclusion patterns. Docker excludes files or directories relative to `PATH` that match these exclusion patterns. If there are any `.dockerignore` files in `PATH` subdirectories, Docker treats them as normal files. Filepaths in `.dockerignore` are absolute with the current directory as the root. Wildcards are allowed but the search is not recursive. Globbing (file name expansion) is done using Go's [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. You can specify exceptions to exclusion rules. To do this, simply prefix a pattern with an `!` (exclamation mark) in the same way you would in a `.gitignore` file. Currently there is no support for regular expressions. Formats like `[^temp*]` are ignored. The following is an example `.dockerignore` file: ``` */temp* */*/temp* temp? *.md !LICENCSE.md ``` This file causes the following build behavior: | Rule | Behavior | |----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `*/temp*` | Exclude all files with names starting with`temp` in any subdirectory below the root directory. For example, a file named`/somedir/temporary.txt` is ignored. | | `*/*/temp*` | Exclude files starting with name `temp` from any subdirectory that is two levels below the root directory. For example, the file `/somedir/subdir/temporary.txt` is ignored. | | `temp?` | Exclude the files that match the pattern in the root directory. For example, the files `tempa`, `tempb` in the root directory are ignored. | | `*.md ` | Exclude all markdown files in the root directory. | | `!LICENSE.md` | Exception to the Markdown files exclusion is this file, `LICENSE.md`, Include this file in the build. | The placement of `!` exception rules influences the matching algorithm; the last line of the `.dockerignore` that matches a particular file determines whether it is included or excluded. In the above example, the `LICENSE.md` file matches both the `*.md` and `!LICENSE.md` rule. If you reverse the lines in the example: ``` */temp* */*/temp* temp? !LICENCSE.md *.md ``` The build would exclude `LICENSE.md` because the last `*.md` rule adds all Markdown files in the root directory back onto the ignore list. The `!LICENSE.md` rule has no effect because the subsequent `*.md` rule overrides it. You can even use the `.dockerignore` file to ignore the `Dockerfile` and `.dockerignore` files. This is useful if you are copying files from the root of the build context into your new container but do not want to include the `Dockerfile` or `.dockerignore` files (e.g. `ADD . /someDir/`). ## FROM FROM Or FROM : Or FROM @ The `FROM` instruction sets the [*Base Image*](/terms/image/#base-image) for subsequent instructions. As such, a valid `Dockerfile` must have `FROM` as its first instruction. The image can be any valid image – it is especially easy to start by **pulling an image** from the [*Public Repositories*]( /userguide/dockerrepos). `FROM` must be the first non-comment instruction in the `Dockerfile`. `FROM` can appear multiple times within a single `Dockerfile` in order to create multiple images. Simply make a note of the last image ID output by the commit before each new `FROM` command. The `tag` or `digest` values are optional. If you omit either of them, the builder assumes a `latest` by default. The builder returns an error if it cannot match the `tag` value. ## MAINTAINER MAINTAINER The `MAINTAINER` instruction allows you to set the *Author* field of the generated images. ## RUN RUN has 2 forms: - `RUN ` (the command is run in a shell - `/bin/sh -c` - *shell* form) - `RUN ["executable", "param1", "param2"]` (*exec* form) The `RUN` instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the `Dockerfile`. Layering `RUN` instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in an image's history, much like source control. The *exec* form makes it possible to avoid shell string munging, and to `RUN` commands using a base image that does not contain `/bin/sh`. > **Note**: > To use a different shell, other than '/bin/sh', use the *exec* form > passing in the desired shell. For example, > `RUN ["/bin/bash", "-c", "echo hello"]` > **Note**: > The *exec* form is parsed as a JSON array, which means that > you must use double-quotes (") around words not single-quotes ('). > **Note**: > Unlike the *shell* form, the *exec* form does not invoke a command shell. > This means that normal shell processing does not happen. For example, > `RUN [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. > If you want shell processing then either use the *shell* form or execute > a shell directly, for example: `RUN [ "sh", "-c", "echo", "$HOME" ]`. The cache for `RUN` instructions isn't invalidated automatically during the next build. The cache for an instruction like `RUN apt-get dist-upgrade -y` will be reused during the next build. The cache for `RUN` instructions can be invalidated by using the `--no-cache` flag, for example `docker build --no-cache`. See the [`Dockerfile` Best Practices guide](/articles/dockerfile_best-practices/#build-cache) for more information. The cache for `RUN` instructions can be invalidated by `ADD` instructions. See [below](#add) for details. ### Known issues (RUN) - [Issue 783](https://github.com/docker/docker/issues/783) is about file permissions problems that can occur when using the AUFS file system. You might notice it during an attempt to `rm` a file, for example. For systems that have recent aufs version (i.e., `dirperm1` mount option can be set), docker will attempt to fix the issue automatically by mounting the layers with `dirperm1` option. More details on `dirperm1` option can be found at [`aufs` man page](http://aufs.sourceforge.net/aufs3/man.html) If your system doesn't have support for `dirperm1`, the issue describes a workaround. ## CMD The `CMD` instruction has three forms: - `CMD ["executable","param1","param2"]` (*exec* form, this is the preferred form) - `CMD ["param1","param2"]` (as *default parameters to ENTRYPOINT*) - `CMD command param1 param2` (*shell* form) There can only be one `CMD` instruction in a `Dockerfile`. If you list more than one `CMD` then only the last `CMD` will take effect. **The main purpose of a `CMD` is to provide defaults for an executing container.** These defaults can include an executable, or they can omit the executable, in which case you must specify an `ENTRYPOINT` instruction as well. > **Note**: > If `CMD` is used to provide default arguments for the `ENTRYPOINT` > instruction, both the `CMD` and `ENTRYPOINT` instructions should be specified > with the JSON array format. > **Note**: > The *exec* form is parsed as a JSON array, which means that > you must use double-quotes (") around words not single-quotes ('). > **Note**: > Unlike the *shell* form, the *exec* form does not invoke a command shell. > This means that normal shell processing does not happen. For example, > `CMD [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. > If you want shell processing then either use the *shell* form or execute > a shell directly, for example: `CMD [ "sh", "-c", "echo", "$HOME" ]`. When used in the shell or exec formats, the `CMD` instruction sets the command to be executed when running the image. If you use the *shell* form of the `CMD`, then the `` will execute in `/bin/sh -c`: FROM ubuntu CMD echo "This is a test." | wc - If you want to **run your** `` **without a shell** then you must express the command as a JSON array and give the full path to the executable. **This array form is the preferred format of `CMD`.** Any additional parameters must be individually expressed as strings in the array: FROM ubuntu CMD ["/usr/bin/wc","--help"] If you would like your container to run the same executable every time, then you should consider using `ENTRYPOINT` in combination with `CMD`. See [*ENTRYPOINT*](#entrypoint). If the user specifies arguments to `docker run` then they will override the default specified in `CMD`. > **Note**: > don't confuse `RUN` with `CMD`. `RUN` actually runs a command and commits > the result; `CMD` does not execute anything at build time, but specifies > the intended command for the image. ## LABEL LABEL = = = ... The `LABEL` instruction adds metadata to an image. A `LABEL` is a key-value pair. To include spaces within a `LABEL` value, use quotes and backslashes as you would in command-line parsing. LABEL "com.example.vendor"="ACME Incorporated" An image can have more than one label. To specify multiple labels, separate each key-value pair with whitespace. LABEL com.example.label-with-value="foo" LABEL version="1.0" LABEL description="This text illustrates \ that label-values can span multiple lines." Docker recommends combining labels in a single `LABEL` instruction where possible. Each `LABEL` instruction produces a new layer which can result in an inefficient image if you use many labels. This example results in four image layers. LABEL multi.label1="value1" multi.label2="value2" other="value3" Labels are additive including `LABEL`s in `FROM` images. As the system encounters and then applies a new label, new `key`s override any previous labels with identical keys. To view an image's labels, use the `docker inspect` command. "Labels": { "com.example.vendor": "ACME Incorporated" "com.example.label-with-value": "foo", "version": "1.0", "description": "This text illustrates that label-values can span multiple lines.", "multi.label1": "value1", "multi.label2": "value2", "other": "value3" }, ## EXPOSE EXPOSE [...] The `EXPOSE` instructions informs Docker that the container will listen on the specified network ports at runtime. Docker uses this information to interconnect containers using links (see the [Docker User Guide](/userguide/dockerlinks)) and to determine which ports to expose to the host when [using the -P flag](/reference/run/#expose-incoming-ports). > **Note**: > `EXPOSE` doesn't define which ports can be exposed to the host or make ports > accessible from the host by default. To expose ports to the host, at runtime, > [use the `-p` flag](/userguide/dockerlinks) or > [the -P flag](/reference/run/#expose-incoming-ports). ## ENV ENV ENV = ... The `ENV` instruction sets the environment variable `` to the value ``. This value will be in the environment of all "descendent" `Dockerfile` commands and can be [replaced inline](#environment-replacement) in many as well. The `ENV` instruction has two forms. The first form, `ENV `, will set a single variable to a value. The entire string after the first space will be treated as the `` - including characters such as spaces and quotes. The second form, `ENV = ...`, allows for multiple variables to be set at one time. Notice that the second form uses the equals sign (=) in the syntax, while the first form does not. Like command line parsing, quotes and backslashes can be used to include spaces within values. For example: ENV myName="John Doe" myDog=Rex\ The\ Dog \ myCat=fluffy and ENV myName John Doe ENV myDog Rex The Dog ENV myCat fluffy will yield the same net results in the final container, but the first form does it all in one layer. The environment variables set using `ENV` will persist when a container is run from the resulting image. You can view the values using `docker inspect`, and change them using `docker run --env =`. > **Note**: > Environment persistence can cause unexpected effects. For example, > setting `ENV DEBIAN_FRONTEND noninteractive` may confuse apt-get > users on a Debian-based image. To set a value for a single command, use > `RUN = `. ## ADD ADD has two forms: - `ADD ... ` - `ADD ["",... ""]` (this form is required for paths containing whitespace) The `ADD` instruction copies new files, directories or remote file URLs from `` and adds them to the filesystem of the container at the path ``. Multiple `` resource may be specified but if they are files or directories then they must be relative to the source directory that is being built (the context of the build). Each `` may contain wildcards and matching will be done using Go's [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For most command line uses this should act as expected, for example: ADD hom* /mydir/ # adds all files starting with "hom" ADD hom?.txt /mydir/ # ? is replaced with any single character The `` is an absolute path, or a path relative to `WORKDIR`, into which the source will be copied inside the destination container. ADD test aDir/ # adds "test" to `WORKDIR`/aDir/ All new files and directories are created with a UID and GID of 0. In the case where `` is a remote file URL, the destination will have permissions of 600. If the remote file being retrieved has an HTTP `Last-Modified` header, the timestamp from that header will be used to set the `mtime` on the destination file. However, like any other file processed during an `ADD`, `mtime` will not be included in the determination of whether or not the file has changed and the cache should be updated. > **Note**: > If you build by passing a `Dockerfile` through STDIN (`docker > build - < somefile`), there is no build context, so the `Dockerfile` > can only contain a URL based `ADD` instruction. You can also pass a > compressed archive through STDIN: (`docker build - < archive.tar.gz`), > the `Dockerfile` at the root of the archive and the rest of the > archive will get used at the context of the build. > **Note**: > If your URL files are protected using authentication, you > will need to use `RUN wget`, `RUN curl` or use another tool from > within the container as the `ADD` instruction does not support > authentication. > **Note**: > The first encountered `ADD` instruction will invalidate the cache for all > following instructions from the Dockerfile if the contents of `` have > changed. This includes invalidating the cache for `RUN` instructions. > See the [`Dockerfile` Best Practices guide](/articles/dockerfile_best-practices/#build-cache) for more information. The copy obeys the following rules: - The `` path must be inside the *context* of the build; you cannot `ADD ../something /something`, because the first step of a `docker build` is to send the context directory (and subdirectories) to the docker daemon. - If `` is a URL and `` does not end with a trailing slash, then a file is downloaded from the URL and copied to ``. - If `` is a URL and `` does end with a trailing slash, then the filename is inferred from the URL and the file is downloaded to `/`. For instance, `ADD http://example.com/foobar /` would create the file `/foobar`. The URL must have a nontrivial path so that an appropriate filename can be discovered in this case (`http://example.com` will not work). - If `` is a directory, the entire contents of the directory are copied, including filesystem metadata. > **Note**: > The directory itself is not copied, just its contents. - If `` is a *local* tar archive in a recognized compression format (identity, gzip, bzip2 or xz) then it is unpacked as a directory. Resources from *remote* URLs are **not** decompressed. When a directory is copied or unpacked, it has the same behavior as `tar -x`: the result is the union of: 1. Whatever existed at the destination path and 2. The contents of the source tree, with conflicts resolved in favor of "2." on a file-by-file basis. - If `` is any other kind of file, it is copied individually along with its metadata. In this case, if `` ends with a trailing slash `/`, it will be considered a directory and the contents of `` will be written at `/base()`. - If multiple `` resources are specified, either directly or due to the use of a wildcard, then `` must be a directory, and it must end with a slash `/`. - If `` does not end with a trailing slash, it will be considered a regular file and the contents of `` will be written at ``. - If `` doesn't exist, it is created along with all missing directories in its path. ## COPY COPY has two forms: - `COPY ... ` - `COPY ["",... ""]` (this form is required for paths containing whitespace) The `COPY` instruction copies new files or directories from `` and adds them to the filesystem of the container at the path ``. Multiple `` resource may be specified but they must be relative to the source directory that is being built (the context of the build). Each `` may contain wildcards and matching will be done using Go's [filepath.Match](http://golang.org/pkg/path/filepath#Match) rules. For most command line uses this should act as expected, for example: COPY hom* /mydir/ # adds all files starting with "hom" COPY hom?.txt /mydir/ # ? is replaced with any single character The `` is an absolute path, or a path relative to `WORKDIR`, into which the source will be copied inside the destination container. COPY test aDir/ # adds "test" to `WORKDIR`/aDir/ All new files and directories are created with a UID and GID of 0. > **Note**: > If you build using STDIN (`docker build - < somefile`), there is no > build context, so `COPY` can't be used. The copy obeys the following rules: - The `` path must be inside the *context* of the build; you cannot `COPY ../something /something`, because the first step of a `docker build` is to send the context directory (and subdirectories) to the docker daemon. - If `` is a directory, the entire contents of the directory are copied, including filesystem metadata. > **Note**: > The directory itself is not copied, just its contents. - If `` is any other kind of file, it is copied individually along with its metadata. In this case, if `` ends with a trailing slash `/`, it will be considered a directory and the contents of `` will be written at `/base()`. - If multiple `` resources are specified, either directly or due to the use of a wildcard, then `` must be a directory, and it must end with a slash `/`. - If `` does not end with a trailing slash, it will be considered a regular file and the contents of `` will be written at ``. - If `` doesn't exist, it is created along with all missing directories in its path. ## ENTRYPOINT ENTRYPOINT has two forms: - `ENTRYPOINT ["executable", "param1", "param2"]` (the preferred *exec* form) - `ENTRYPOINT command param1 param2` (*shell* form) An `ENTRYPOINT` allows you to configure a container that will run as an executable. For example, the following will start nginx with its default content, listening on port 80: docker run -i -t --rm -p 80:80 nginx Command line arguments to `docker run ` will be appended after all elements in an *exec* form `ENTRYPOINT`, and will override all elements specified using `CMD`. This allows arguments to be passed to the entry point, i.e., `docker run -d` will pass the `-d` argument to the entry point. You can override the `ENTRYPOINT` instruction using the `docker run --entrypoint` flag. The *shell* form prevents any `CMD` or `run` command line arguments from being used, but has the disadvantage that your `ENTRYPOINT` will be started as a subcommand of `/bin/sh -c`, which does not pass signals. This means that the executable will not be the container's `PID 1` - and will _not_ receive Unix signals - so your executable will not receive a `SIGTERM` from `docker stop `. Only the last `ENTRYPOINT` instruction in the `Dockerfile` will have an effect. ### Exec form ENTRYPOINT example You can use the *exec* form of `ENTRYPOINT` to set fairly stable default commands and arguments and then use either form of `CMD` to set additional defaults that are more likely to be changed. FROM ubuntu ENTRYPOINT ["top", "-b"] CMD ["-c"] When you run the container, you can see that `top` is the only process: $ docker run -it --rm --name test top -H top - 08:25:00 up 7:27, 0 users, load average: 0.00, 0.01, 0.05 Threads: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie %Cpu(s): 0.1 us, 0.1 sy, 0.0 ni, 99.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st KiB Mem: 2056668 total, 1616832 used, 439836 free, 99352 buffers KiB Swap: 1441840 total, 0 used, 1441840 free. 1324440 cached Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 19744 2336 2080 R 0.0 0.1 0:00.04 top To examine the result further, you can use `docker exec`: $ docker exec -it test ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 2.6 0.1 19752 2352 ? Ss+ 08:24 0:00 top -b -H root 7 0.0 0.1 15572 2164 ? R+ 08:25 0:00 ps aux And you can gracefully request `top` to shut down using `docker stop test`. The following `Dockerfile` shows using the `ENTRYPOINT` to run Apache in the foreground (i.e., as `PID 1`): ``` FROM debian:stable RUN apt-get update && apt-get install -y --force-yes apache2 EXPOSE 80 443 VOLUME ["/var/www", "/var/log/apache2", "/etc/apache2"] ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"] ``` If you need to write a starter script for a single executable, you can ensure that the final executable receives the Unix signals by using `exec` and `gosu` commands: ```bash #!/bin/bash set -e if [ "$1" = 'postgres' ]; then chown -R postgres "$PGDATA" if [ -z "$(ls -A "$PGDATA")" ]; then gosu postgres initdb fi exec gosu postgres "$@" fi exec "$@" ``` Lastly, if you need to do some extra cleanup (or communicate with other containers) on shutdown, or are co-ordinating more than one executable, you may need to ensure that the `ENTRYPOINT` script receives the Unix signals, passes them on, and then does some more work: ``` #!/bin/sh # Note: I've written this using sh so it works in the busybox container too # USE the trap if you need to also do manual cleanup after the service is stopped, # or need to start multiple services in the one container trap "echo TRAPed signal" HUP INT QUIT KILL TERM # start service in background here /usr/sbin/apachectl start echo "[hit enter key to exit] or run 'docker stop '" read # stop service and clean up here echo "stopping apache" /usr/sbin/apachectl stop echo "exited $0" ``` If you run this image with `docker run -it --rm -p 80:80 --name test apache`, you can then examine the container's processes with `docker exec`, or `docker top`, and then ask the script to stop Apache: ```bash $ docker exec -it test ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.1 0.0 4448 692 ? Ss+ 00:42 0:00 /bin/sh /run.sh 123 cmd cmd2 root 19 0.0 0.2 71304 4440 ? Ss 00:42 0:00 /usr/sbin/apache2 -k start www-data 20 0.2 0.2 360468 6004 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start www-data 21 0.2 0.2 360468 6000 ? Sl 00:42 0:00 /usr/sbin/apache2 -k start root 81 0.0 0.1 15572 2140 ? R+ 00:44 0:00 ps aux $ docker top test PID USER COMMAND 10035 root {run.sh} /bin/sh /run.sh 123 cmd cmd2 10054 root /usr/sbin/apache2 -k start 10055 33 /usr/sbin/apache2 -k start 10056 33 /usr/sbin/apache2 -k start $ /usr/bin/time docker stop test test real 0m 0.27s user 0m 0.03s sys 0m 0.03s ``` > **Note:** you can over ride the `ENTRYPOINT` setting using `--entrypoint`, > but this can only set the binary to *exec* (no `sh -c` will be used). > **Note**: > The *exec* form is parsed as a JSON array, which means that > you must use double-quotes (") around words not single-quotes ('). > **Note**: > Unlike the *shell* form, the *exec* form does not invoke a command shell. > This means that normal shell processing does not happen. For example, > `ENTRYPOINT [ "echo", "$HOME" ]` will not do variable substitution on `$HOME`. > If you want shell processing then either use the *shell* form or execute > a shell directly, for example: `ENTRYPOINT [ "sh", "-c", "echo", "$HOME" ]`. > Variables that are defined in the `Dockerfile`using `ENV`, will be substituted by > the `Dockerfile` parser. ### Shell form ENTRYPOINT example You can specify a plain string for the `ENTRYPOINT` and it will execute in `/bin/sh -c`. This form will use shell processing to substitute shell environment variables, and will ignore any `CMD` or `docker run` command line arguments. To ensure that `docker stop` will signal any long running `ENTRYPOINT` executable correctly, you need to remember to start it with `exec`: FROM ubuntu ENTRYPOINT exec top -b When you run this image, you'll see the single `PID 1` process: $ docker run -it --rm --name test top Mem: 1704520K used, 352148K free, 0K shrd, 0K buff, 140368121167873K cached CPU: 5% usr 0% sys 0% nic 94% idle 0% io 0% irq 0% sirq Load average: 0.08 0.03 0.05 2/98 6 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1 0 root R 3164 0% 0% top -b Which will exit cleanly on `docker stop`: $ /usr/bin/time docker stop test test real 0m 0.20s user 0m 0.02s sys 0m 0.04s If you forget to add `exec` to the beginning of your `ENTRYPOINT`: FROM ubuntu ENTRYPOINT top -b CMD --ignored-param1 You can then run it (giving it a name for the next step): $ docker run -it --name test top --ignored-param2 Mem: 1704184K used, 352484K free, 0K shrd, 0K buff, 140621524238337K cached CPU: 9% usr 2% sys 0% nic 88% idle 0% io 0% irq 0% sirq Load average: 0.01 0.02 0.05 2/101 7 PID PPID USER STAT VSZ %VSZ %CPU COMMAND 1 0 root S 3168 0% 0% /bin/sh -c top -b cmd cmd2 7 1 root R 3164 0% 0% top -b You can see from the output of `top` that the specified `ENTRYPOINT` is not `PID 1`. If you then run `docker stop test`, the container will not exit cleanly - the `stop` command will be forced to send a `SIGKILL` after the timeout: $ docker exec -it test ps aux PID USER COMMAND 1 root /bin/sh -c top -b cmd cmd2 7 root top -b 8 root ps aux $ /usr/bin/time docker stop test test real 0m 10.19s user 0m 0.04s sys 0m 0.03s ## VOLUME VOLUME ["/data"] The `VOLUME` instruction creates a mount point with the specified name and marks it as holding externally mounted volumes from native host or other containers. The value can be a JSON array, `VOLUME ["/var/log/"]`, or a plain string with multiple arguments, such as `VOLUME /var/log` or `VOLUME /var/log /var/db`. For more information/examples and mounting instructions via the Docker client, refer to [*Share Directories via Volumes*](/userguide/dockervolumes/#volume) documentation. The `docker run` command initializes the newly created volume with any data that exists at the specified location within the base image. For example, consider the following Dockerfile snippet: FROM ubuntu RUN mkdir /myvol RUN echo "hello world" > /myvol/greeting VOLUME /myvol This Dockerfile results in an image that causes `docker run`, to create a new mount point at `/myvol` and copy the `greeting` file into the newly created volume. > **Note**: > The list is parsed as a JSON array, which means that > you must use double-quotes (") around words not single-quotes ('). ## USER USER daemon The `USER` instruction sets the user name or UID to use when running the image and for any `RUN`, `CMD` and `ENTRYPOINT` instructions that follow it in the `Dockerfile`. ## WORKDIR WORKDIR /path/to/workdir The `WORKDIR` instruction sets the working directory for any `RUN`, `CMD`, `ENTRYPOINT`, `COPY` and `ADD` instructions that follow it in the `Dockerfile`. It can be used multiple times in the one `Dockerfile`. If a relative path is provided, it will be relative to the path of the previous `WORKDIR` instruction. For example: WORKDIR /a WORKDIR b WORKDIR c RUN pwd The output of the final `pwd` command in this `Dockerfile` would be `/a/b/c`. The `WORKDIR` instruction can resolve environment variables previously set using `ENV`. You can only use environment variables explicitly set in the `Dockerfile`. For example: ENV DIRPATH /path WORKDIR $DIRPATH/$DIRNAME The output of the final `pwd` command in this `Dockerfile` would be `/path/$DIRNAME` ## ONBUILD ONBUILD [INSTRUCTION] The `ONBUILD` instruction adds to the image a *trigger* instruction to be executed at a later time, when the image is used as the base for another build. The trigger will be executed in the context of the downstream build, as if it had been inserted immediately after the `FROM` instruction in the downstream `Dockerfile`. Any build instruction can be registered as a trigger. This is useful if you are building an image which will be used as a base to build other images, for example an application build environment or a daemon which may be customized with user-specific configuration. For example, if your image is a reusable Python application builder, it will require application source code to be added in a particular directory, and it might require a build script to be called *after* that. You can't just call `ADD` and `RUN` now, because you don't yet have access to the application source code, and it will be different for each application build. You could simply provide application developers with a boilerplate `Dockerfile` to copy-paste into their application, but that is inefficient, error-prone and difficult to update because it mixes with application-specific code. The solution is to use `ONBUILD` to register advance instructions to run later, during the next build stage. Here's how it works: 1. When it encounters an `ONBUILD` instruction, the builder adds a trigger to the metadata of the image being built. The instruction does not otherwise affect the current build. 2. At the end of the build, a list of all triggers is stored in the image manifest, under the key `OnBuild`. They can be inspected with the `docker inspect` command. 3. Later the image may be used as a base for a new build, using the `FROM` instruction. As part of processing the `FROM` instruction, the downstream builder looks for `ONBUILD` triggers, and executes them in the same order they were registered. If any of the triggers fail, the `FROM` instruction is aborted which in turn causes the build to fail. If all triggers succeed, the `FROM` instruction completes and the build continues as usual. 4. Triggers are cleared from the final image after being executed. In other words they are not inherited by "grand-children" builds. For example you might add something like this: [...] ONBUILD ADD . /app/src ONBUILD RUN /usr/local/bin/python-build --dir /app/src [...] > **Warning**: Chaining `ONBUILD` instructions using `ONBUILD ONBUILD` isn't allowed. > **Warning**: The `ONBUILD` instruction may not trigger `FROM` or `MAINTAINER` instructions. ## Dockerfile examples # Nginx # # VERSION 0.0.1 FROM ubuntu MAINTAINER Victor Vieux LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0" RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server # Firefox over VNC # # VERSION 0.3 FROM ubuntu # Install vnc, xvfb in order to create a 'fake' display and firefox RUN apt-get update && apt-get install -y x11vnc xvfb firefox RUN mkdir ~/.vnc # Setup a password RUN x11vnc -storepasswd 1234 ~/.vnc/passwd # Autostart firefox (might not be the best way, but it does the trick) RUN bash -c 'echo "firefox" >> /.bashrc' EXPOSE 5900 CMD ["x11vnc", "-forever", "-usepw", "-create"] # Multiple images example # # VERSION 0.1 FROM ubuntu RUN echo foo > bar # Will output something like ===> 907ad6c2736f FROM ubuntu RUN echo moo > oink # Will output something like ===> 695d7793cbe4 # You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with # /oink. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/attach.md ================================================ # attach Usage: docker attach [OPTIONS] CONTAINER Attach to a running container --no-stdin=false Do not attach STDIN --sig-proxy=true Proxy all received signals to the process The `docker attach` command allows you to attach to a running container using the container's ID or name, either to view its ongoing output or to control it interactively. You can attach to the same contained process multiple times simultaneously, screen sharing style, or quickly view the progress of your daemonized process. You can detach from the container and leave it running with `CTRL-p CTRL-q` (for a quiet exit) or with `CTRL-c` if `--sig-proxy` is false. If `--sig-proxy` is true (the default),`CTRL-c` sends a `SIGINT` to the container. > **Note:** > A process running as PID 1 inside a container is treated specially by > Linux: it ignores any signal with the default action. So, the process > will not terminate on `SIGINT` or `SIGTERM` unless it is coded to do > so. It is forbidden to redirect the standard input of a `docker attach` command while attaching to a tty-enabled container (i.e.: launched with `-t`). #### Examples $ docker run -d --name topdemo ubuntu /usr/bin/top -b $ docker attach topdemo top - 02:05:52 up 3:05, 0 users, load average: 0.01, 0.02, 0.05 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.1%us, 0.2%sy, 0.0%ni, 99.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 373572k total, 355560k used, 18012k free, 27872k buffers Swap: 786428k total, 0k used, 786428k free, 221740k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 17200 1116 912 R 0 0.3 0:00.03 top top - 02:05:55 up 3:05, 0 users, load average: 0.01, 0.02, 0.05 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.0%us, 0.2%sy, 0.0%ni, 99.8%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 373572k total, 355244k used, 18328k free, 27872k buffers Swap: 786428k total, 0k used, 786428k free, 221776k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 17208 1144 932 R 0 0.3 0:00.03 top top - 02:05:58 up 3:06, 0 users, load average: 0.01, 0.02, 0.05 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.2%us, 0.3%sy, 0.0%ni, 99.5%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 373572k total, 355780k used, 17792k free, 27880k buffers Swap: 786428k total, 0k used, 786428k free, 221776k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 17208 1144 932 R 0 0.3 0:00.03 top ^C$ $ echo $? 0 $ docker ps -a | grep topdemo 7998ac8581f9 ubuntu:14.04 "/usr/bin/top -b" 38 seconds ago Exited (0) 21 seconds ago topdemo And in this second example, you can see the exit code returned by the `bash` process is returned by the `docker attach` command to its caller too: $ docker run --name test -d -it debian 275c44472aebd77c926d4527885bb09f2f6db21d878c75f0a1c212c03d3bcfab $ docker attach test $$ exit 13 exit $ echo $? 13 $ docker ps -a | grep test 275c44472aeb debian:7 "/bin/bash" 26 seconds ago Exited (13) 17 seconds ago test ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/build.md ================================================ # build Usage: docker build [OPTIONS] PATH | URL | - Build a new image from the source code at PATH -f, --file="" Name of the Dockerfile (Default is 'PATH/Dockerfile') --force-rm=false Always remove intermediate containers --no-cache=false Do not use cache when building the image --pull=false Always attempt to pull a newer version of the image -q, --quiet=false Suppress the verbose output generated by the containers --rm=true Remove intermediate containers after a successful build -t, --tag="" Repository name (and optionally a tag) for the image -m, --memory="" Memory limit for all build containers --memory-swap="" Total memory (memory + swap), `-1` to disable swap -c, --cpu-shares CPU Shares (relative weight) --cpuset-mems="" MEMs in which to allow execution, e.g. `0-3`, `0,1` --cpuset-cpus="" CPUs in which to allow execution, e.g. `0-3`, `0,1` --cgroup-parent="" Optional parent cgroup for the container Builds Docker images from a Dockerfile and a "context". A build's context is the files located in the specified `PATH` or `URL`. The build process can refer to any of the files in the context. For example, your build can use an [*ADD*](/reference/builder/#add) instruction to reference a file in the context. The `URL` parameter can specify the location of a Git repository; the repository acts as the build context. The system recursively clones the repository and its submodules using a `git clone --depth 1 --recursive` command. This command runs in a temporary directory on your local host. After the command succeeds, the directory is sent to the Docker daemon as the context. Local clones give you the ability to access private repositories using local user credentials, VPNs, and so forth. Git URLs accept context configuration in their fragment section, separated by a colon `:`. The first part represents the reference that Git will check out, this can be either a branch, a tag, or a commit SHA. The second part represents a subdirectory inside the repository that will be used as a build context. For example, run this command to use a directory called `docker` in the branch `container`: $ docker build https://github.com/docker/rootfs.git#container:docker The following table represents all the valid suffixes with their build contexts: Build Syntax Suffix | Commit Used | Build Context Used --------------------|-------------|------------------- `myrepo.git` | `refs/heads/master` | `/` `myrepo.git#mytag` | `refs/tags/mytag` | `/` `myrepo.git#mybranch` | `refs/heads/mybranch` | `/` `myrepo.git#abcdef` | `sha1 = abcdef` | `/` `myrepo.git#:myfolder` | `refs/heads/master` | `/myfolder` `myrepo.git#master:myfolder` | `refs/heads/master` | `/myfolder` `myrepo.git#mytag:myfolder` | `refs/tags/mytag` | `/myfolder` `myrepo.git#mybranch:myfolder` | `refs/heads/mybranch` | `/myfolder` `myrepo.git#abcdef:myfolder` | `sha1 = abcdef` | `/myfolder` Instead of specifying a context, you can pass a single Dockerfile in the `URL` or pipe the file in via `STDIN`. To pipe a Dockerfile from `STDIN`: docker build - < Dockerfile If you use STDIN or specify a `URL`, the system places the contents into a file called `Dockerfile`, and any `-f`, `--file` option is ignored. In this scenario, there is no context. By default the `docker build` command will look for a `Dockerfile` at the root of the build context. The `-f`, `--file`, option lets you specify the path to an alternative file to use instead. This is useful in cases where the same set of files are used for multiple builds. The path must be to a file within the build context. If a relative path is specified then it must to be relative to the current directory. In most cases, it's best to put each Dockerfile in an empty directory. Then, add to that directory only the files needed for building the Dockerfile. To increase the build's performance, you can exclude files and directories by adding a `.dockerignore` file to that directory as well. For information on creating one, see the [.dockerignore file](/reference/builder#dockerignore-file). If the Docker client loses connection to the daemon, the build is canceled. This happens if you interrupt the Docker client with `ctrl-c` or if the Docker client is killed for any reason. > **Note:** > Currently only the "run" phase of the build can be canceled until pull > cancellation is implemented). ## Return code On a successful build, a return code of success `0` will be returned. When the build fails, a non-zero failure code will be returned. There should be informational output of the reason for failure output to `STDERR`: $ docker build -t fail . Sending build context to Docker daemon 2.048 kB Sending build context to Docker daemon Step 0 : FROM busybox ---> 4986bf8c1536 Step 1 : RUN exit 13 ---> Running in e26670ec7a0a INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13 $ echo $? 1 See also: [*Dockerfile Reference*](/reference/builder). ## Examples $ docker build . Uploading context 10240 bytes Step 1 : FROM busybox Pulling repository busybox ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/ Step 2 : RUN ls -lh / ---> Running in 9c9e81692ae9 total 24 drwxr-xr-x 2 root root 4.0K Mar 12 2013 bin drwxr-xr-x 5 root root 4.0K Oct 19 00:19 dev drwxr-xr-x 2 root root 4.0K Oct 19 00:19 etc drwxr-xr-x 2 root root 4.0K Nov 15 23:34 lib lrwxrwxrwx 1 root root 3 Mar 12 2013 lib64 -> lib dr-xr-xr-x 116 root root 0 Nov 15 23:34 proc lrwxrwxrwx 1 root root 3 Mar 12 2013 sbin -> bin dr-xr-xr-x 13 root root 0 Nov 15 23:34 sys drwxr-xr-x 2 root root 4.0K Mar 12 2013 tmp drwxr-xr-x 2 root root 4.0K Nov 15 23:34 usr ---> b35f4035db3f Step 3 : CMD echo Hello world ---> Running in 02071fceb21b ---> f52f38b7823e Successfully built f52f38b7823e Removing intermediate container 9c9e81692ae9 Removing intermediate container 02071fceb21b This example specifies that the `PATH` is `.`, and so all the files in the local directory get `tar`d and sent to the Docker daemon. The `PATH` specifies where to find the files for the "context" of the build on the Docker daemon. Remember that the daemon could be running on a remote machine and that no parsing of the Dockerfile happens at the client side (where you're running `docker build`). That means that *all* the files at `PATH` get sent, not just the ones listed to [*ADD*](/reference/builder/#add) in the Dockerfile. The transfer of context from the local machine to the Docker daemon is what the `docker` client means when you see the "Sending build context" message. If you wish to keep the intermediate containers after the build is complete, you must use `--rm=false`. This does not affect the build cache. $ docker build . Uploading context 18.829 MB Uploading context Step 0 : FROM busybox ---> 769b9341d937 Step 1 : CMD echo Hello world ---> Using cache ---> 99cc1ad10469 Successfully built 99cc1ad10469 $ echo ".git" > .dockerignore $ docker build . Uploading context 6.76 MB Uploading context Step 0 : FROM busybox ---> 769b9341d937 Step 1 : CMD echo Hello world ---> Using cache ---> 99cc1ad10469 Successfully built 99cc1ad10469 This example shows the use of the `.dockerignore` file to exclude the `.git` directory from the context. Its effect can be seen in the changed size of the uploaded context. The builder reference contains detailed information on [creating a .dockerignore file](../../builder/#dockerignore-file) $ docker build -t vieux/apache:2.0 . This will build like the previous example, but it will then tag the resulting image. The repository name will be `vieux/apache` and the tag will be `2.0` $ docker build - < Dockerfile This will read a Dockerfile from `STDIN` without context. Due to the lack of a context, no contents of any local directory will be sent to the Docker daemon. Since there is no context, a Dockerfile `ADD` only works if it refers to a remote URL. $ docker build - < context.tar.gz This will build an image for a compressed context read from `STDIN`. Supported formats are: bzip2, gzip and xz. $ docker build github.com/creack/docker-firefox This will clone the GitHub repository and use the cloned repository as context. The Dockerfile at the root of the repository is used as Dockerfile. Note that you can specify an arbitrary Git repository by using the `git://` or `git@` schema. $ docker build -f Dockerfile.debug . This will use a file called `Dockerfile.debug` for the build instructions instead of `Dockerfile`. $ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug . $ docker build -f dockerfiles/Dockerfile.prod -t myapp_prod . The above commands will build the current build context (as specified by the `.`) twice, once using a debug version of a `Dockerfile` and once using a production version. $ cd /home/me/myapp/some/dir/really/deep $ docker build -f /home/me/myapp/dockerfiles/debug /home/me/myapp $ docker build -f ../../../../dockerfiles/debug /home/me/myapp These two `docker build` commands do the exact same thing. They both use the contents of the `debug` file instead of looking for a `Dockerfile` and will use `/home/me/myapp` as the root of the build context. Note that `debug` is in the directory structure of the build context, regardless of how you refer to it on the command line. > **Note:** > `docker build` will return a `no such file or directory` error if the > file or directory does not exist in the uploaded context. This may > happen if there is no context, or if you specify a file that is > elsewhere on the Host system. The context is limited to the current > directory (and its children) for security reasons, and to ensure > repeatable builds on remote Docker hosts. This is also the reason why > `ADD ../file` will not work. When `docker build` is run with the `--cgroup-parent` option the containers used in the build will be run with the [corresponding `docker run` flag](/reference/run/#specifying-custom-cgroups). ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/cli.md ================================================ # Using the command line > **Note:** If you are using a remote Docker daemon, such as Boot2Docker, > then _do not_ type the `sudo` before the `docker` commands shown in the > documentation's examples. To list available commands, either run `docker` with no parameters or execute `docker help`: $ docker Usage: docker [OPTIONS] COMMAND [arg...] -H, --host=[]: The socket(s) to bind to in daemon mode, specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd. A self-sufficient runtime for Linux containers. ... Depending on your Docker system configuration, you may be required to preface each `docker` command with `sudo`. To avoid having to use `sudo` with the `docker` command, your system administrator can create a Unix group called `docker` and add users to it. For more information about installing Docker or `sudo` configuration, refer to the [installation](/installation) instructions for your operating system. ## Environment variables For easy reference, the following list of environment variables are supported by the `docker` command line: * `DOCKER_CONFIG` The location of your client configuration files. * `DOCKER_CERT_PATH` The location of your authentication keys. * `DOCKER_DRIVER` The graph driver to use. * `DOCKER_HOST` Daemon socket to connect to. * `DOCKER_NOWARN_KERNEL_VERSION` Prevent warnings that your Linux kernel is unsuitable for Docker. * `DOCKER_RAMDISK` If set this will disable 'pivot_root'. * `DOCKER_TLS_VERIFY` When set Docker uses TLS and verifies the remote. * `DOCKER_TMPDIR` Location for temporary Docker files. Because Docker is developed using 'Go', you can also use any environment variables used by the 'Go' runtime. In particular, you may find these useful: * `HTTP_PROXY` * `HTTPS_PROXY` * `NO_PROXY` These Go environment variables are case-insensitive. See the [Go specification](http://golang.org/pkg/net/http/) for details on these variables. ## Configuration files By default, the Docker command line stores its configuration files in a directory called `.docker` within your `HOME` directory. However, you can specify a different location via the `DOCKER_CONFIG` environment variable or the `--config` command line option. If both are specified, then the `--config` option overrides the `DOCKER_CONFIG` environment variable. For example: docker --config ~/testconfigs/ ps Instructs Docker to use the configuration files in your `~/testconfigs/` directory when running the `ps` command. Docker manages most of the files in the configuration directory and you should not modify them. However, you *can modify* the `config.json` file to control certain aspects of how the `docker` command behaves. Currently, you can modify the `docker` command behavior using environment variables or command-line options. You can also use options within `config.json` to modify some of the same behavior. When using these mechanisms, you must keep in mind the order of precedence among them. Command line options override environment variables and environment variables override properties you specify in a `config.json` file. The `config.json` file stores a JSON encoding of a single `HttpHeaders` property. The property specifies a set of headers to include in all messages sent from the Docker client to the daemon. Docker does not try to interpret or understand these header; it simply puts them into the messages. Docker does not allow these headers to change any headers it sets for itself. Following is a sample `config.json` file: { "HttpHeaders: { "MyHeader": "MyValue" } } ## Help To list the help on any command just execute the command, followed by the `--help` option. $ docker run --help Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Run a command in a new container -a, --attach=[] Attach to STDIN, STDOUT or STDERR -c, --cpu-shares=0 CPU shares (relative weight) ... ## Option types Single character command line options can be combined, so rather than typing `docker run -i -t --name test busybox sh`, you can write `docker run -it --name test busybox sh`. ### Boolean Boolean options take the form `-d=false`. The value you see in the help text is the default value which is set if you do **not** specify that flag. If you specify a Boolean flag without a value, this will set the flag to `true`, irrespective of the default value. For example, running `docker run -d` will set the value to `true`, so your container **will** run in "detached" mode, in the background. Options which default to `true` (e.g., `docker build --rm=true`) can only be set to the non-default value by explicitly setting them to `false`: $ docker build --rm=false . ### Multi You can specify options like `-a=[]` multiple times in a single command line, for example in these commands: $ docker run -a stdin -a stdout -i -t ubuntu /bin/bash $ docker run -a stdin -a stdout -a stderr ubuntu /bin/ls Sometimes, multiple options can call for a more complex value string as for `-v`: $ docker run -v /host:/container example/mysql > **Note:** > Do not use the `-t` and `-a stderr` options together due to > limitations in the `pty` implementation. All `stderr` in `pty` mode > simply goes to `stdout`. ### Strings and Integers Options like `--name=""` expect a string, and they can only be specified once. Options like `-c=0` expect an integer, and they can only be specified once. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/commit.md ================================================ # commit Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] Create a new image from a container's changes -a, --author="" Author (e.g., "John Hannibal Smith ") -c, --change=[] Apply specified Dockerfile instructions while committing the image -m, --message="" Commit message -p, --pause=true Pause container during commit It can be useful to commit a container's file changes or settings into a new image. This allows you debug a container by running an interactive shell, or to export a working dataset to another server. Generally, it is better to use Dockerfiles to manage your images in a documented and maintainable way. The commit operation will not include any data contained in volumes mounted inside the container. By default, the container being committed and its processes will be paused while the image is committed. This reduces the likelihood of encountering data corruption during the process of creating the commit. If this behavior is undesired, set the 'p' option to false. The `--change` option will apply `Dockerfile` instructions to the image that is created. Supported `Dockerfile` instructions: `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`LABEL`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` ## Commit a container $ docker ps ID IMAGE COMMAND CREATED STATUS PORTS c3f279d17e0a ubuntu:12.04 /bin/bash 7 days ago Up 25 hours 197387f1b436 ubuntu:12.04 /bin/bash 7 days ago Up 25 hours $ docker commit c3f279d17e0a SvenDowideit/testimage:version3 f5283438590d $ docker images REPOSITORY TAG ID CREATED VIRTUAL SIZE SvenDowideit/testimage version3 f5283438590d 16 seconds ago 335.7 MB ## Commit a container with new configurations $ docker ps ID IMAGE COMMAND CREATED STATUS PORTS c3f279d17e0a ubuntu:12.04 /bin/bash 7 days ago Up 25 hours 197387f1b436 ubuntu:12.04 /bin/bash 7 days ago Up 25 hours $ docker inspect -f "{{ .Config.Env }}" c3f279d17e0a [HOME=/ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin] $ docker commit --change "ENV DEBUG true" c3f279d17e0a SvenDowideit/testimage:version3 f5283438590d $ docker inspect -f "{{ .Config.Env }}" f5283438590d [HOME=/ PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin DEBUG=true] ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/cp.md ================================================ # cp Copy files/folders between a container and the local filesystem. Usage: docker cp [options] CONTAINER:PATH LOCALPATH|- docker cp [options] LOCALPATH|- CONTAINER:PATH --help Print usage statement In the first synopsis form, the `docker cp` utility copies the contents of `PATH` from the filesystem of `CONTAINER` to the `LOCALPATH` (or stream as a tar archive to `STDOUT` if `-` is specified). In the second synopsis form, the contents of `LOCALPATH` (or a tar archive streamed from `STDIN` if `-` is specified) are copied from the local machine to `PATH` in the filesystem of `CONTAINER`. You can copy to or from either a running or stopped container. The `PATH` can be a file or directory. The `docker cp` command assumes all `CONTAINER:PATH` values are relative to the `/` (root) directory of the container. This means supplying the initial forward slash is optional; The command sees `compassionate_darwin:/tmp/foo/myfile.txt` and `compassionate_darwin:tmp/foo/myfile.txt` as identical. If a `LOCALPATH` value is not absolute, is it considered relative to the current working directory. Behavior is similar to the common Unix utility `cp -a` in that directories are copied recursively with permissions preserved if possible. Ownership is set to the user and primary group on the receiving end of the transfer. For example, files copied to a container will be created with `UID:GID` of the root user. Files copied to the local machine will be created with the `UID:GID` of the user which invoked the `docker cp` command. Assuming a path separator of `/`, a first argument of `SRC_PATH` and second argument of `DST_PATH`, the behavior is as follows: - `SRC_PATH` specifies a file - `DST_PATH` does not exist - the file is saved to a file created at `DST_PATH` - `DST_PATH` does not exist and ends with `/` - Error condition: the destination directory must exist. - `DST_PATH` exists and is a file - the destination is overwritten with the contents of the source file - `DST_PATH` exists and is a directory - the file is copied into this directory using the basename from `SRC_PATH` - `SRC_PATH` specifies a directory - `DST_PATH` does not exist - `DST_PATH` is created as a directory and the *contents* of the source directory are copied into this directory - `DST_PATH` exists and is a file - Error condition: cannot copy a directory to a file - `DST_PATH` exists and is a directory - `SRC_PATH` does not end with `/.` - the source directory is copied into this directory - `SRC_PAPTH` does end with `/.` - the *content* of the source directory is copied into this directory The command requires `SRC_PATH` and `DST_PATH` to exist according to the above rules. If `SRC_PATH` is local and is a symbolic link, the symbolic link, not the target, is copied. A colon (`:`) is used as a delimiter between `CONTAINER` and `PATH`, but `:` could also be in a valid `LOCALPATH`, like `file:name.txt`. This ambiguity is resolved by requiring a `LOCALPATH` with a `:` to be made explicit with a relative or absolute path, for example: `/path/to/file:name.txt` or `./file:name.txt` It is not possible to copy certain system files such as resources under `/proc`, `/sys`, `/dev`, and mounts created by the user in the container. Using `-` as the first argument in place of a `LOCALPATH` will stream the contents of `STDIN` as a tar archive which will be extracted to the `PATH` in the filesystem of the destination container. In this case, `PATH` must specify a directory. Using `-` as the second argument in place of a `LOCALPATH` will stream the contents of the resource from the source container as a tar archive to `STDOUT`. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/create.md ================================================ # create Creates a new container. Usage: docker create [OPTIONS] IMAGE [COMMAND] [ARG...] Create a new container -a, --attach=[] Attach to STDIN, STDOUT or STDERR --add-host=[] Add a custom host-to-IP mapping (host:ip) --blkio-weight=0 Block IO weight (relative weight) -c, --cpu-shares=0 CPU shares (relative weight) --cap-add=[] Add Linux capabilities --cap-drop=[] Drop Linux capabilities --cgroup-parent="" Optional parent cgroup for the container --cidfile="" Write the container ID to the file --cpu-period=0 Limit CPU CFS (Completely Fair Scheduler) period --cpu-quota=0 Limit CPU CFS (Completely Fair Scheduler) quota --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1) --cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1) --device=[] Add a host device to the container --dns=[] Set custom DNS servers --dns-search=[] Set custom DNS search domains -e, --env=[] Set environment variables --entrypoint="" Overwrite the default ENTRYPOINT of the image --env-file=[] Read in a file of environment variables --expose=[] Expose a port or a range of ports -h, --hostname="" Container host name --help=false Print usage -i, --interactive=false Keep STDIN open even if not attached --ipc="" IPC namespace to use -l, --label=[] Set metadata on the container (e.g., --label=com.example.key=value) --label-file=[] Read in a line delimited file of labels --link=[] Add link to another container --log-driver="" Logging driver for container --log-opt=[] Log driver specific options --lxc-conf=[] Add custom lxc options -m, --memory="" Memory limit --mac-address="" Container MAC address (e.g. 92:d0:c6:0a:29:33) --memory-swap="" Total memory (memory + swap), '-1' to disable swap --memory-swappiness="" Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. --name="" Assign a name to the container --net="bridge" Set the Network mode for the container --oom-kill-disable=false Whether to disable OOM Killer for the container or not -P, --publish-all=false Publish all exposed ports to random ports -p, --publish=[] Publish a container's port(s) to the host --pid="" PID namespace to use --privileged=false Give extended privileges to this container --read-only=false Mount the container's root filesystem as read only --restart="no" Restart policy (no, on-failure[:max-retry], always) --security-opt=[] Security options -t, --tty=false Allocate a pseudo-TTY -u, --user="" Username or UID --ulimit=[] Ulimit options --uts="" UTS namespace to use -v, --volume=[] Bind mount a volume --volumes-from=[] Mount volumes from the specified container(s) -w, --workdir="" Working directory inside the container The `docker create` command creates a writeable container layer over the specified image and prepares it for running the specified command. The container ID is then printed to `STDOUT`. This is similar to `docker run -d` except the container is never started. You can then use the `docker start ` command to start the container at any point. This is useful when you want to set up a container configuration ahead of time so that it is ready to start when you need it. The initial status of the new container is `created`. Please see the [run command](/reference/commandline/run) section and the [Docker run reference]( /reference/run/) for more details. ## Examples $ docker create -t -i fedora bash 6d8af538ec541dd581ebc2a24153a28329acb5268abe5ef868c1f1a261221752 $ docker start -a -i 6d8af538ec5 bash-4.2# As of v1.4.0 container volumes are initialized during the `docker create` phase (i.e., `docker run` too). For example, this allows you to `create` the `data` volume container, and then use it from another container: $ docker create -v /data --name data ubuntu 240633dfbb98128fa77473d3d9018f6123b99c454b3251427ae190a7d951ad57 $ docker run --rm --volumes-from data ubuntu ls -la /data total 8 drwxr-xr-x 2 root root 4096 Dec 5 04:10 . drwxr-xr-x 48 root root 4096 Dec 5 04:11 .. Similarly, `create` a host directory bind mounted volume container, which can then be used from the subsequent container: $ docker create -v /home/docker:/docker --name docker ubuntu 9aa88c08f319cd1e4515c3c46b0de7cc9aa75e878357b1e96f91e2c773029f03 $ docker run --rm --volumes-from docker ubuntu ls -la /docker total 20 drwxr-sr-x 5 1000 staff 180 Dec 5 04:00 . drwxr-xr-x 48 root root 4096 Dec 5 04:13 .. -rw-rw-r-- 1 1000 staff 3833 Dec 5 04:01 .ash_history -rw-r--r-- 1 1000 staff 446 Nov 28 11:51 .ashrc -rw-r--r-- 1 1000 staff 25 Dec 5 04:00 .gitconfig drwxr-sr-x 3 1000 staff 60 Dec 1 03:28 .local -rw-r--r-- 1 1000 staff 920 Nov 28 11:51 .profile drwx--S--- 2 1000 staff 460 Dec 5 00:51 .ssh drwxr-xr-x 32 1000 staff 1140 Dec 5 04:01 docker ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/daemon.md ================================================ # daemon Usage: docker [OPTIONS] COMMAND [arg...] A self-sufficient runtime for linux containers. Options: --api-cors-header="" Set CORS headers in the remote API -b, --bridge="" Attach containers to a network bridge --bip="" Specify network bridge IP --config=~/.docker Location of client config files -D, --debug=false Enable debug mode -d, --daemon=false Enable daemon mode --default-gateway="" Container default gateway IPv4 address --default-gateway-v6="" Container default gateway IPv6 address --dns=[] DNS server to use --dns-search=[] DNS search domains to use --default-ulimit=[] Set default ulimit settings for containers -e, --exec-driver="native" Exec driver to use --exec-opt=[] Set exec driver options --exec-root="/var/run/docker" Root of the Docker execdriver --fixed-cidr="" IPv4 subnet for fixed IPs --fixed-cidr-v6="" IPv6 subnet for fixed IPs -G, --group="docker" Group for the unix socket -g, --graph="/var/lib/docker" Root of the Docker runtime -H, --host=[] Daemon socket(s) to connect to -h, --help=false Print usage --icc=true Enable inter-container communication --insecure-registry=[] Enable insecure registry communication --ip=0.0.0.0 Default IP when binding container ports --ip-forward=true Enable net.ipv4.ip_forward --ip-masq=true Enable IP masquerading --iptables=true Enable addition of iptables rules --ipv6=false Enable IPv6 networking -l, --log-level="info" Set the logging level --label=[] Set key=value labels to the daemon --log-driver="json-file" Default driver for container logs --log-opt=[] Log driver specific options --mtu=0 Set the containers network MTU -p, --pidfile="/var/run/docker.pid" Path to use for daemon PID file --registry-mirror=[] Preferred Docker registry mirror -s, --storage-driver="" Storage driver to use --selinux-enabled=false Enable selinux support --storage-opt=[] Set storage driver options --tls=false Use TLS; implied by --tlsverify --tlscacert="~/.docker/ca.pem" Trust certs signed only by this CA --tlscert="~/.docker/cert.pem" Path to TLS certificate file --tlskey="~/.docker/key.pem" Path to TLS key file --tlsverify=false Use TLS and verify the remote --userland-proxy=true Use userland proxy for loopback traffic -v, --version=false Print version information and quit Options with [] may be specified multiple times. The Docker daemon is the persistent process that manages containers. Docker uses the same binary for both the daemon and client. To run the daemon you provide the `-d` flag. To run the daemon with debug output, use `docker -d -D`. ## Daemon socket option The Docker daemon can listen for [Docker Remote API](/reference/api/docker_remote_api/) requests via three different types of Socket: `unix`, `tcp`, and `fd`. By default, a `unix` domain socket (or IPC socket) is created at `/var/run/docker.sock`, requiring either `root` permission, or `docker` group membership. If you need to access the Docker daemon remotely, you need to enable the `tcp` Socket. Beware that the default setup provides un-encrypted and un-authenticated direct access to the Docker daemon - and should be secured either using the [built in HTTPS encrypted socket](/articles/https/), or by putting a secure web proxy in front of it. You can listen on port `2375` on all network interfaces with `-H tcp://0.0.0.0:2375`, or on a particular network interface using its IP address: `-H tcp://192.168.59.103:2375`. It is conventional to use port `2375` for un-encrypted, and port `2376` for encrypted communication with the daemon. > **Note:** > If you're using an HTTPS encrypted socket, keep in mind that only > TLS1.0 and greater are supported. Protocols SSLv3 and under are not > supported anymore for security reasons. On Systemd based systems, you can communicate with the daemon via [Systemd socket activation](http://0pointer.de/blog/projects/socket-activation.html), use `docker -d -H fd://`. Using `fd://` will work perfectly for most setups but you can also specify individual sockets: `docker -d -H fd://3`. If the specified socket activated files aren't found, then Docker will exit. You can find examples of using Systemd socket activation with Docker and Systemd in the [Docker source tree](https://github.com/docker/docker/tree/master/contrib/init/systemd/). You can configure the Docker daemon to listen to multiple sockets at the same time using multiple `-H` options: # listen using the default unix socket, and on 2 specific IP addresses on this host. docker -d -H unix:///var/run/docker.sock -H tcp://192.168.59.106 -H tcp://10.10.10.2 The Docker client will honor the `DOCKER_HOST` environment variable to set the `-H` flag for the client. $ docker -H tcp://0.0.0.0:2375 ps # or $ export DOCKER_HOST="tcp://0.0.0.0:2375" $ docker ps # both are equal Setting the `DOCKER_TLS_VERIFY` environment variable to any value other than the empty string is equivalent to setting the `--tlsverify` flag. The following are equivalent: $ docker --tlsverify ps # or $ export DOCKER_TLS_VERIFY=1 $ docker ps The Docker client will honor the `HTTP_PROXY`, `HTTPS_PROXY`, and `NO_PROXY` environment variables (or the lowercase versions thereof). `HTTPS_PROXY` takes precedence over `HTTP_PROXY`. ### Daemon storage-driver option The Docker daemon has support for several different image layer storage drivers: `aufs`, `devicemapper`, `btrfs`, `zfs` and `overlay`. The `aufs` driver is the oldest, but is based on a Linux kernel patch-set that is unlikely to be merged into the main kernel. These are also known to cause some serious kernel crashes. However, `aufs` is also the only storage driver that allows containers to share executable and shared library memory, so is a useful choice when running thousands of containers with the same program or libraries. The `devicemapper` driver uses thin provisioning and Copy on Write (CoW) snapshots. For each devicemapper graph location – typically `/var/lib/docker/devicemapper` – a thin pool is created based on two block devices, one for data and one for metadata. By default, these block devices are created automatically by using loopback mounts of automatically created sparse files. Refer to [Storage driver options](#storage-driver-options) below for a way how to customize this setup. [~jpetazzo/Resizing Docker containers with the Device Mapper plugin](http://jpetazzo.github.io/2014/01/29/docker-device-mapper-resize/) article explains how to tune your existing setup without the use of options. The `btrfs` driver is very fast for `docker build` - but like `devicemapper` does not share executable memory between devices. Use `docker -d -s btrfs -g /mnt/btrfs_partition`. The `zfs` driver is probably not fast as `btrfs` but has a longer track record on stability. Thanks to `Single Copy ARC` shared blocks between clones will be cached only once. Use `docker -d -s zfs`. To select a different zfs filesystem set `zfs.fsname` option as described in [Storage driver options](#storage-driver-options). The `overlay` is a very fast union filesystem. It is now merged in the main Linux kernel as of [3.18.0](https://lkml.org/lkml/2014/10/26/137). Call `docker -d -s overlay` to use it. > **Note:** > As promising as `overlay` is, the feature is still quite young and should not > be used in production. Most notably, using `overlay` can cause excessive > inode consumption (especially as the number of images grows), as well as > being incompatible with the use of RPMs. > **Note:** > It is currently unsupported on `btrfs` or any Copy on Write filesystem > and should only be used over `ext4` partitions. ### Storage driver options Particular storage-driver can be configured with options specified with `--storage-opt` flags. Options for `devicemapper` are prefixed with `dm` and options for `zfs` start with `zfs`. * `dm.thinpooldev` Specifies a custom block storage device to use for the thin pool. If using a block device for device mapper storage, it is best to use `lvm` to create and manage the thin-pool volume. This volume is then handed to Docker to exclusively create snapshot volumes needed for images and containers. Managing the thin-pool outside of Docker makes for the most feature-rich method of having Docker utilize device mapper thin provisioning as the backing storage for Docker's containers. The highlights of the lvm-based thin-pool management feature include: automatic or interactive thin-pool resize support, dynamically changing thin-pool features, automatic thinp metadata checking when lvm activates the thin-pool, etc. Example use: docker -d --storage-opt dm.thinpooldev=/dev/mapper/thin-pool * `dm.basesize` Specifies the size to use when creating the base device, which limits the size of images and containers. The default value is 10G. Note, thin devices are inherently "sparse", so a 10G device which is mostly empty doesn't use 10 GB of space on the pool. However, the filesystem will use more space for the empty case the larger the device is. This value affects the system-wide "base" empty filesystem that may already be initialized and inherited by pulled images. Typically, a change to this value requires additional steps to take effect: $ sudo service docker stop $ sudo rm -rf /var/lib/docker $ sudo service docker start Example use: $ docker -d --storage-opt dm.basesize=20G * `dm.loopdatasize` >**Note**: This option configures devicemapper loopback, which should not be used in production. Specifies the size to use when creating the loopback file for the "data" device which is used for the thin pool. The default size is 100G. The file is sparse, so it will not initially take up this much space. Example use: $ docker -d --storage-opt dm.loopdatasize=200G * `dm.loopmetadatasize` >**Note**: This option configures devicemapper loopback, which should not be used in production. Specifies the size to use when creating the loopback file for the "metadadata" device which is used for the thin pool. The default size is 2G. The file is sparse, so it will not initially take up this much space. Example use: $ docker -d --storage-opt dm.loopmetadatasize=4G * `dm.fs` Specifies the filesystem type to use for the base device. The supported options are "ext4" and "xfs". The default is "ext4" Example use: $ docker -d --storage-opt dm.fs=xfs * `dm.mkfsarg` Specifies extra mkfs arguments to be used when creating the base device. Example use: $ docker -d --storage-opt "dm.mkfsarg=-O ^has_journal" * `dm.mountopt` Specifies extra mount options used when mounting the thin devices. Example use: $ docker -d --storage-opt dm.mountopt=nodiscard * `dm.datadev` (Deprecated, use `dm.thinpooldev`) Specifies a custom blockdevice to use for data for the thin pool. If using a block device for device mapper storage, ideally both datadev and metadatadev should be specified to completely avoid using the loopback device. Example use: $ docker -d --storage-opt dm.datadev=/dev/sdb1 --storage-opt dm.metadatadev=/dev/sdc1 * `dm.metadatadev` (Deprecated, use `dm.thinpooldev`) Specifies a custom blockdevice to use for metadata for the thin pool. For best performance the metadata should be on a different spindle than the data, or even better on an SSD. If setting up a new metadata pool it is required to be valid. This can be achieved by zeroing the first 4k to indicate empty metadata, like this: $ dd if=/dev/zero of=$metadata_dev bs=4096 count=1 Example use: $ docker -d --storage-opt dm.datadev=/dev/sdb1 --storage-opt dm.metadatadev=/dev/sdc1 * `dm.blocksize` Specifies a custom blocksize to use for the thin pool. The default blocksize is 64K. Example use: $ docker -d --storage-opt dm.blocksize=512K * `dm.blkdiscard` Enables or disables the use of blkdiscard when removing devicemapper devices. This is enabled by default (only) if using loopback devices and is required to resparsify the loopback file on image/container removal. Disabling this on loopback can lead to *much* faster container removal times, but will make the space used in `/var/lib/docker` directory not be returned to the system for other use when containers are removed. Example use: $ docker -d --storage-opt dm.blkdiscard=false * `dm.override_udev_sync_check` Overrides the `udev` synchronization checks between `devicemapper` and `udev`. `udev` is the device manager for the Linux kernel. To view the `udev` sync support of a Docker daemon that is using the `devicemapper` driver, run: $ docker info [...] Udev Sync Supported: true [...] When `udev` sync support is `true`, then `devicemapper` and udev can coordinate the activation and deactivation of devices for containers. When `udev` sync support is `false`, a race condition occurs between the`devicemapper` and `udev` during create and cleanup. The race condition results in errors and failures. (For information on these failures, see [docker#4036](https://github.com/docker/docker/issues/4036)) To allow the `docker` daemon to start, regardless of `udev` sync not being supported, set `dm.override_udev_sync_check` to true: $ docker -d --storage-opt dm.override_udev_sync_check=true When this value is `true`, the `devicemapper` continues and simply warns you the errors are happening. > **Note:** > The ideal is to pursue a `docker` daemon and environment that does > support synchronizing with `udev`. For further discussion on this > topic, see [docker#4036](https://github.com/docker/docker/issues/4036). > Otherwise, set this flag for migrating existing Docker daemons to > a daemon with a supported environment. ## Docker execdriver option Currently supported options of `zfs`: * `zfs.fsname` Set zfs filesystem under which docker will create its own datasets. By default docker will pick up the zfs filesystem where docker graph (`/var/lib/docker`) is located. Example use: $ docker -d -s zfs --storage-opt zfs.fsname=zroot/docker ## Docker execdriver option The Docker daemon uses a specifically built `libcontainer` execution driver as its interface to the Linux kernel `namespaces`, `cgroups`, and `SELinux`. There is still legacy support for the original [LXC userspace tools]( https://linuxcontainers.org/) via the `lxc` execution driver, however, this is not where the primary development of new functionality is taking place. Add `-e lxc` to the daemon flags to use the `lxc` execution driver. ## Options for the native execdriver You can configure the `native` (libcontainer) execdriver using options specified with the `--exec-opt` flag. All the flag's options have the `native` prefix. A single `native.cgroupdriver` option is available. The `native.cgroupdriver` option specifies the management of the container's cgroups. You can specify `cgroupfs` or `systemd`. If you specify `systemd` and it is not available, the system uses `cgroupfs`. By default, if no option is specified, the execdriver first tries `systemd` and falls back to `cgroupfs`. This example sets the execdriver to `cgroupfs`: $ sudo docker -d --exec-opt native.cgroupdriver=cgroupfs Setting this option applies to all containers the daemon launches. ## Daemon DNS options To set the DNS server for all Docker containers, use `docker -d --dns 8.8.8.8`. To set the DNS search domain for all Docker containers, use `docker -d --dns-search example.com`. ## Insecure registries Docker considers a private registry either secure or insecure. In the rest of this section, *registry* is used for *private registry*, and `myregistry:5000` is a placeholder example for a private registry. A secure registry uses TLS and a copy of its CA certificate is placed on the Docker host at `/etc/docker/certs.d/myregistry:5000/ca.crt`. An insecure registry is either not using TLS (i.e., listening on plain text HTTP), or is using TLS with a CA certificate not known by the Docker daemon. The latter can happen when the certificate was not found under `/etc/docker/certs.d/myregistry:5000/`, or if the certificate verification failed (i.e., wrong CA). By default, Docker assumes all, but local (see local registries below), registries are secure. Communicating with an insecure registry is not possible if Docker assumes that registry is secure. In order to communicate with an insecure registry, the Docker daemon requires `--insecure-registry` in one of the following two forms: * `--insecure-registry myregistry:5000` tells the Docker daemon that myregistry:5000 should be considered insecure. * `--insecure-registry 10.1.0.0/16` tells the Docker daemon that all registries whose domain resolve to an IP address is part of the subnet described by the CIDR syntax, should be considered insecure. The flag can be used multiple times to allow multiple registries to be marked as insecure. If an insecure registry is not marked as insecure, `docker pull`, `docker push`, and `docker search` will result in an error message prompting the user to either secure or pass the `--insecure-registry` flag to the Docker daemon as described above. Local registries, whose IP address falls in the 127.0.0.0/8 range, are automatically marked as insecure as of Docker 1.3.2. It is not recommended to rely on this, as it may change in the future. ## Running a Docker daemon behind a HTTPS_PROXY When running inside a LAN that uses a `HTTPS` proxy, the Docker Hub certificates will be replaced by the proxy's certificates. These certificates need to be added to your Docker host's configuration: 1. Install the `ca-certificates` package for your distribution 2. Ask your network admin for the proxy's CA certificate and append them to `/etc/pki/tls/certs/ca-bundle.crt` 3. Then start your Docker daemon with `HTTPS_PROXY=http://username:password@proxy:port/ docker -d`. The `username:` and `password@` are optional - and are only needed if your proxy is set up to require authentication. This will only add the proxy and authentication to the Docker daemon's requests - your `docker build`s and running containers will need extra configuration to use the proxy ## Default Ulimits `--default-ulimit` allows you to set the default `ulimit` options to use for all containers. It takes the same options as `--ulimit` for `docker run`. If these defaults are not set, `ulimit` settings will be inherited, if not set on `docker run`, from the Docker daemon. Any `--ulimit` options passed to `docker run` will overwrite these defaults. Be careful setting `nproc` with the `ulimit` flag as `nproc` is designed by Linux to set the maximum number of processes available to a user, not to a container. For details please check the [run](run.md) reference. ## Miscellaneous options IP masquerading uses address translation to allow containers without a public IP to talk to other machines on the Internet. This may interfere with some network topologies and can be disabled with --ip-masq=false. Docker supports softlinks for the Docker data directory (`/var/lib/docker`) and for `/var/lib/docker/tmp`. The `DOCKER_TMPDIR` and the data directory can be set like this: DOCKER_TMPDIR=/mnt/disk2/tmp /usr/local/bin/docker -d -D -g /var/lib/docker -H unix:// > /var/lib/boot2docker/docker.log 2>&1 # or export DOCKER_TMPDIR=/mnt/disk2/tmp /usr/local/bin/docker -d -D -g /var/lib/docker -H unix:// > /var/lib/boot2docker/docker.log 2>&1 ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/diff.md ================================================ # diff Usage: docker diff CONTAINER Inspect changes on a container's filesystem List the changed files and directories in a container᾿s filesystem There are 3 events that are listed in the `diff`: 1. `A` - Add 2. `D` - Delete 3. `C` - Change For example: $ docker diff 7bb0e258aefe C /dev A /dev/kmsg C /etc A /etc/mtab A /go A /go/src A /go/src/github.com A /go/src/github.com/docker A /go/src/github.com/docker/docker A /go/src/github.com/docker/docker/.git .... ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/events.md ================================================ # events Usage: docker events [OPTIONS] Get real time events from the server -f, --filter=[] Filter output based on conditions provided --since="" Show all events created since timestamp --until="" Stream events until this timestamp Docker containers will report the following events: create, destroy, die, export, kill, oom, pause, restart, start, stop, unpause and Docker images will report: untag, delete The `--since` and `--until` parameters can be Unix timestamps, RFC3339 dates or Go duration strings (e.g. `10m`, `1h30m`) computed relative to client machine’s time. If you do not provide the --since option, the command returns only new and/or live events. ## Filtering The filtering flag (`-f` or `--filter`) format is of "key=value". If you would like to use multiple filters, pass multiple flags (e.g., `--filter "foo=bar" --filter "bif=baz"`) Using the same filter multiple times will be handled as a *OR*; for example `--filter container=588a23dac085 --filter container=a8f7720b8c22` will display events for container 588a23dac085 *OR* container a8f7720b8c22 Using multiple filters will be handled as a *AND*; for example `--filter container=588a23dac085 --filter event=start` will display events for container container 588a23dac085 *AND* the event type is *start* The currently supported filters are: * container * event * image ## Examples You'll need two shells for this example. **Shell 1: Listening for events:** $ docker events **Shell 2: Start and Stop containers:** $ docker start 4386fb97867d $ docker stop 4386fb97867d $ docker stop 7805c1d35632 **Shell 1: (Again .. now showing events):** 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) start 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop **Show events in the past from a specified time:** $ docker events --since 1378216169 2014-03-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-03-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop $ docker events --since '2013-09-03' 2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) start 2014-09-03T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-09-03T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop $ docker events --since '2013-09-03T15:49:29' 2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop This example outputs all events that were generated in the last 3 minutes, relative to the current time on the client machine: $ docker events --since '3m' 2015-05-12T11:51:30.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2015-05-12T15:52:12.999999999Z07:00 4 4386fb97867d: (from ubuntu-1:14.04) stop 2015-05-12T15:53:45.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2015-05-12T15:54:03.999999999Z07:00 7805c1d35632: (from redis:2.8) stop **Filter events:** $ docker events --filter 'event=stop' 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-09-03T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) stop $ docker events --filter 'image=ubuntu-1:14.04' 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) start 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop $ docker events --filter 'container=7805c1d35632' 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop $ docker events --filter 'container=7805c1d35632' --filter 'container=4386fb97867d' 2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop $ docker events --filter 'container=7805c1d35632' --filter 'event=stop' 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop $ docker events --filter 'container=container_1' --filter 'container=container_2' 2014-09-03T15:49:29.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2014-05-10T17:42:14.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) stop 2014-05-10T17:42:14.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2014-09-03T15:49:29.999999999Z07:00 7805c1d35632: (from redis:2.8) stop ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/exec.md ================================================ # exec Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...] Run a command in a running container -d, --detach=false Detached mode: run command in the background -i, --interactive=false Keep STDIN open even if not attached -t, --tty=false Allocate a pseudo-TTY -u, --user= Username or UID (format: [:]) The `docker exec` command runs a new command in a running container. The command started using `docker exec` only runs while the container's primary process (`PID 1`) is running, and it is not restarted if the container is restarted. If the container is paused, then the `docker exec` command will fail with an error: $ docker pause test test $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1ae3b36715d2 ubuntu:latest "bash" 17 seconds ago Up 16 seconds (Paused) test $ docker exec test ls FATA[0000] Error response from daemon: Container test is paused, unpause the container before exec $ echo $? 1 ## Examples $ docker run --name ubuntu_bash --rm -i -t ubuntu bash This will create a container named `ubuntu_bash` and start a Bash session. $ docker exec -d ubuntu_bash touch /tmp/execWorks This will create a new file `/tmp/execWorks` inside the running container `ubuntu_bash`, in the background. $ docker exec -it ubuntu_bash bash This will create a new Bash session in the container `ubuntu_bash`. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/export.md ================================================ # export Usage: docker export [OPTIONS] CONTAINER Export the contents of a filesystem to a tar archive (streamed to STDOUT by default). -o, --output="" Write to a file, instead of STDOUT Produces a tarred repository to the standard output stream. For example: $ docker export red_panda > latest.tar Or $ docker export --output="latest.tar" red_panda The `docker export` command does not export the contents of volumes associated with the container. If a volume is mounted on top of an existing directory in the container, `docker export` will export the contents of the *underlying* directory, not the contents of the volume. Refer to [Backup, restore, or migrate data volumes](/userguide/dockervolumes/#backup-restore-or-migrate-data-volumes) in the user guide for examples on exporting data in a volume. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/history.md ================================================ # history Usage: docker history [OPTIONS] IMAGE Show the history of an image -H, --human=true Print sizes and dates in human readable format --no-trunc=false Don't truncate output -q, --quiet=false Only show numeric IDs To see how the `docker:latest` image was built: $ docker history docker IMAGE CREATED CREATED BY SIZE COMMENT 3e23a5875458 8 days ago /bin/sh -c #(nop) ENV LC_ALL=C.UTF-8 0 B 8578938dd170 8 days ago /bin/sh -c dpkg-reconfigure locales && loc 1.245 MB be51b77efb42 8 days ago /bin/sh -c apt-get update && apt-get install 338.3 MB 4b137612be55 6 weeks ago /bin/sh -c #(nop) ADD jessie.tar.xz in / 121 MB 750d58736b4b 6 weeks ago /bin/sh -c #(nop) MAINTAINER Tianon Gravi +++ title = "images" description = "The images command description and usage" keywords = ["list, docker, images"] [menu.main] parent = "smn_cli" weight=1 +++ # images Usage: docker images [OPTIONS] [REPOSITORY] List images -a, --all=false Show all images (default hides intermediate images) --digests=false Show digests -f, --filter=[] Filter output based on conditions provided --help=false Print usage --no-trunc=false Don't truncate output -q, --quiet=false Only show numeric IDs The default `docker images` will show all top level images, their repository and tags, and their virtual size. Docker images have intermediate layers that increase reusability, decrease disk usage, and speed up `docker build` by allowing each step to be cached. These intermediate layers are not shown by default. The `VIRTUAL SIZE` is the cumulative space taken up by the image and all its parent images. This is also the disk space used by the contents of the Tar file created when you `docker save` an image. An image will be listed more than once if it has multiple repository names or tags. This single image (identifiable by its matching `IMAGE ID`) uses up the `VIRTUAL SIZE` listed only once. ### Listing the most recently created images $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE 77af4d6b9913 19 hours ago 1.089 GB committ latest b6fa739cedf5 19 hours ago 1.089 GB 78a85c484f71 19 hours ago 1.089 GB docker latest 30557a29d5ab 20 hours ago 1.089 GB 5ed6274db6ce 24 hours ago 1.089 GB postgres 9 746b819f315e 4 days ago 213.4 MB postgres 9.3 746b819f315e 4 days ago 213.4 MB postgres 9.3.5 746b819f315e 4 days ago 213.4 MB postgres latest 746b819f315e 4 days ago 213.4 MB ## Listing the full length image IDs $ docker images --no-trunc REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE 77af4d6b9913e693e8d0b4b294fa62ade6054e6b2f1ffb617ac955dd63fb0182 19 hours ago 1.089 GB committest latest b6fa739cedf5ea12a620a439402b6004d057da800f91c7524b5086a5e4749c9f 19 hours ago 1.089 GB 78a85c484f71509adeaace20e72e941f6bdd2b25b4c75da8693efd9f61a37921 19 hours ago 1.089 GB docker latest 30557a29d5abc51e5f1d5b472e79b7e296f595abcf19fe6b9199dbbc809c6ff4 20 hours ago 1.089 GB 0124422dd9f9cf7ef15c0617cda3931ee68346455441d66ab8bdc5b05e9fdce5 20 hours ago 1.089 GB 18ad6fad340262ac2a636efd98a6d1f0ea775ae3d45240d3418466495a19a81b 22 hours ago 1.082 GB f9f1e26352f0a3ba6a0ff68167559f64f3e21ff7ada60366e2d44a04befd1d3a 23 hours ago 1.089 GB tryout latest 2629d1fa0b81b222fca63371ca16cbf6a0772d07759ff80e8d1369b926940074 23 hours ago 131.5 MB 5ed6274db6ceb2397844896966ea239290555e74ef307030ebb01ff91b1914df 24 hours ago 1.089 GB ## Listing image digests Images that use the v2 or later format have a content-addressable identifier called a `digest`. As long as the input used to generate the image is unchanged, the digest value is predictable. To list image digest values, use the `--digests` flag: $ docker images --digests REPOSITORY TAG DIGEST IMAGE ID CREATED VIRTUAL SIZE localhost:5000/test/busybox sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf 4986bf8c1536 9 weeks ago 2.43 MB When pushing or pulling to a 2.0 registry, the `push` or `pull` command output includes the image digest. You can `pull` using a digest value. You can also reference by digest in `create`, `run`, and `rmi` commands, as well as the `FROM` image reference in a Dockerfile. ## Filtering The filtering flag (`-f` or `--filter`) format is of "key=value". If there is more than one filter, then pass multiple flags (e.g., `--filter "foo=bar" --filter "bif=baz"`) The currently supported filters are: * dangling (boolean - true or false) * label (`label=` or `label==`) ##### Untagged images $ docker images --filter "dangling=true" REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE 8abc22fbb042 4 weeks ago 0 B 48e5f45168b9 4 weeks ago 2.489 MB bf747efa0e2f 4 weeks ago 0 B 980fe10e5736 12 weeks ago 101.4 MB dea752e4e117 12 weeks ago 101.4 MB 511136ea3c5a 8 months ago 0 B This will display untagged images, that are the leaves of the images tree (not intermediary layers). These images occur when a new build of an image takes the `repo:tag` away from the image ID, leaving it untagged. A warning will be issued if trying to remove an image when a container is presently using it. By having this flag it allows for batch cleanup. Ready for use by `docker rmi ...`, like: $ docker rmi $(docker images -f "dangling=true" -q) 8abc22fbb042 48e5f45168b9 bf747efa0e2f 980fe10e5736 dea752e4e117 511136ea3c5a NOTE: Docker will warn you if any containers exist that are using these untagged images. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/import.md ================================================ # import Usage: docker import URL|- [REPOSITORY[:TAG]] Create an empty filesystem image and import the contents of the tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) into it, then optionally tag it. -c, --change=[] Apply specified Dockerfile instructions while importing the image URLs must start with `http` and point to a single file archive (.tar, .tar.gz, .tgz, .bzip, .tar.xz, or .txz) containing a root filesystem. If you would like to import from a local directory or archive, you can use the `-` parameter to take the data from `STDIN`. The `--change` option will apply `Dockerfile` instructions to the image that is created. Supported `Dockerfile` instructions: `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` ## Examples **Import from a remote location:** This will create a new untagged image. $ docker import http://example.com/exampleimage.tgz **Import from a local file:** Import to docker via pipe and `STDIN`. $ cat exampleimage.tgz | docker import - exampleimagelocal:new **Import from a local directory:** $ sudo tar -c . | docker import - exampleimagedir **Import from a local directory with new configurations:** $ sudo tar -c . | docker import --change "ENV DEBUG true" - exampleimagedir Note the `sudo` in this example – you must preserve the ownership of the files (especially root ownership) during the archiving with tar. If you are not root (or the sudo command) when you tar, then the ownerships might not get preserved. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/info.md ================================================ # info Usage: docker info Display system-wide information For example: $ docker -D info Containers: 14 Images: 52 Storage Driver: aufs Root Dir: /var/lib/docker/aufs Backing Filesystem: extfs Dirs: 545 Execution Driver: native-0.2 Logging Driver: json-file Kernel Version: 3.13.0-24-generic Operating System: Ubuntu 14.04 LTS CPUs: 1 Name: prod-server-42 ID: 7TRN:IPZB:QYBB:VPBQ:UMPP:KARE:6ZNR:XE6T:7EWV:PKF4:ZOJD:TPYS Total Memory: 2 GiB Debug mode (server): false Debug mode (client): true File Descriptors: 10 Goroutines: 9 System Time: Tue Mar 10 18:38:57 UTC 2015 EventsListeners: 0 Init Path: /usr/bin/docker Docker Root Dir: /var/lib/docker Http Proxy: http://test:test@localhost:8080 Https Proxy: https://test:test@localhost:8080 No Proxy: 9.81.1.160 Username: svendowideit Registry: [https://index.docker.io/v1/] Labels: storage=ssd The global `-D` option tells all `docker` commands to output debug information. When sending issue reports, please use `docker version` and `docker -D info` to ensure we know how your setup is configured. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/inspect.md ================================================ # inspect Usage: docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...] Return low-level information on a container or image -f, --format="" Format the output using the given go template --type=container|image Return JSON for specified type, permissible values are "image" or "container" By default, this will render all results in a JSON array. If a format is specified, the given template will be executed for each result. Go's [text/template](http://golang.org/pkg/text/template/) package describes all the details of the format. ## Examples **Get an instance's IP address:** For the most part, you can pick out any field from the JSON in a fairly straightforward manner. $ docker inspect --format='{{.NetworkSettings.IPAddress}}' $INSTANCE_ID **Get an instance's MAC Address:** For the most part, you can pick out any field from the JSON in a fairly straightforward manner. $ docker inspect --format='{{.NetworkSettings.MacAddress}}' $INSTANCE_ID **Get an instance's log path:** $ docker inspect --format='{{.LogPath}}' $INSTANCE_ID **List All Port Bindings:** One can loop over arrays and maps in the results to produce simple text output: $ docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' $INSTANCE_ID **Find a Specific Port Mapping:** The `.Field` syntax doesn't work when the field name begins with a number, but the template language's `index` function does. The `.NetworkSettings.Ports` section contains a map of the internal port mappings to a list of external address/port objects, so to grab just the numeric public port, you use `index` to find the specific port map, and then `index` 0 contains the first object inside of that. Then we ask for the `HostPort` field to get the public address. $ docker inspect --format='{{(index (index .NetworkSettings.Ports "8787/tcp") 0).HostPort}}' $INSTANCE_ID **Get config:** The `.Field` syntax doesn't work when the field contains JSON data, but the template language's custom `json` function does. The `.config` section contains complex JSON object, so to grab it as JSON, you use `json` to convert the configuration object into JSON. $ docker inspect --format='{{json .config}}' $INSTANCE_ID ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/kill.md ================================================ # kill Usage: docker kill [OPTIONS] CONTAINER [CONTAINER...] Kill a running container using SIGKILL or a specified signal -s, --signal="KILL" Signal to send to the container The main process inside the container will be sent `SIGKILL`, or any signal specified with option `--signal`. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/load.md ================================================ # load Usage: docker load [OPTIONS] Load an image from a tar archive or STDIN -i, --input="" Read from a tar archive file, instead of STDIN Loads a tarred repository from a file or the standard input stream. Restores both images and tags. $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE $ docker load < busybox.tar $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE busybox latest 769b9341d937 7 weeks ago 2.489 MB $ docker load --input fedora.tar $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE busybox latest 769b9341d937 7 weeks ago 2.489 MB fedora rawhide 0d20aec6529d 7 weeks ago 387 MB fedora 20 58394af37342 7 weeks ago 385.5 MB fedora heisenbug 58394af37342 7 weeks ago 385.5 MB fedora latest 58394af37342 7 weeks ago 385.5 MB ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/login.md ================================================ # login Usage: docker login [OPTIONS] [SERVER] Register or log in to a Docker registry server, if no server is specified "https://index.docker.io/v1/" is the default. -e, --email="" Email -p, --password="" Password -u, --username="" Username If you want to login to a self-hosted registry you can specify this by adding the server name. example: $ docker login localhost:8080 ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/logout.md ================================================ # logout Usage: docker logout [SERVER] Log out from a Docker registry, if no server is specified "https://index.docker.io/v1/" is the default. For example: $ docker logout localhost:8080 ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/logs.md ================================================ # logs Usage: docker logs [OPTIONS] CONTAINER Fetch the logs of a container -f, --follow=false Follow log output --since="" Show logs since timestamp -t, --timestamps=false Show timestamps --tail="all" Number of lines to show from the end of the logs NOTE: this command is available only for containers with `json-file` logging driver. The `docker logs` command batch-retrieves logs present at the time of execution. The `docker logs --follow` command will continue streaming the new output from the container's `STDOUT` and `STDERR`. Passing a negative number or a non-integer to `--tail` is invalid and the value is set to `latest` in that case. The `docker logs --timestamp` commands will add an RFC3339Nano timestamp, for example `2014-09-16T06:17:46.000000000Z`, to each log entry. To ensure that the timestamps for are aligned the nano-second part of the timestamp will be padded with zero when necessary. The `--since` option shows only the container logs generated after a given date. You can specify the date as an RFC 3339 date, a UNIX timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Docker computes the date relative to the client machine’s time. You can combine the `--since` option with either or both of the `--follow` or `--tail` options. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/pause.md ================================================ # pause Usage: docker pause CONTAINER [CONTAINER...] Pause all processes within a container The `docker pause` command uses the cgroups freezer to suspend all processes in a container. Traditionally, when suspending a process the `SIGSTOP` signal is used, which is observable by the process being suspended. With the cgroups freezer the process is unaware, and unable to capture, that it is being suspended, and subsequently resumed. See the [cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) for further details. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/port.md ================================================ # port Usage: docker port CONTAINER [PRIVATE_PORT[/PROTO]] List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT You can find out all the ports mapped by not specifying a `PRIVATE_PORT`, or just a specific mapping: $ docker ps test CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b650456536c7 busybox:latest top 54 minutes ago Up 54 minutes 0.0.0.0:1234->9876/tcp, 0.0.0.0:4321->7890/tcp test $ docker port test 7890/tcp -> 0.0.0.0:4321 9876/tcp -> 0.0.0.0:1234 $ docker port test 7890/tcp 0.0.0.0:4321 $ docker port test 7890/udp 2014/06/24 11:53:36 Error: No public port '7890/udp' published for test $ docker port test 7890 0.0.0.0:4321 ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/ps.md ================================================ # ps Usage: docker ps [OPTIONS] List containers -a, --all=false Show all containers (default shows just running) --before="" Show only container created before Id or Name -f, --filter=[] Filter output based on conditions provided -l, --latest=false Show the latest created container, include non-running -n=-1 Show n last created containers, include non-running --no-trunc=false Don't truncate output -q, --quiet=false Only display numeric IDs -s, --size=false Display total file sizes --since="" Show created since Id or Name, include non-running Running `docker ps --no-trunc` showing 2 linked containers. $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4c01db0b339c ubuntu:12.04 bash 17 seconds ago Up 16 seconds 3300-3310/tcp webapp d7886598dbe2 crosbymichael/redis:latest /redis-server --dir 33 minutes ago Up 33 minutes 6379/tcp redis,webapp/db `docker ps` will show only running containers by default. To see all containers: `docker ps -a` `docker ps` will group exposed ports into a single range if possible. E.g., a container that exposes TCP ports `100, 101, 102` will display `100-102/tcp` in the `PORTS` column. ## Filtering The filtering flag (`-f` or `--filter)` format is a `key=value` pair. If there is more than one filter, then pass multiple flags (e.g. `--filter "foo=bar" --filter "bif=baz"`) The currently supported filters are: * id (container's id) * label (`label=` or `label==`) * name (container's name) * exited (int - the code of exited containers. Only useful with `--all`) * status (created|restarting|running|paused|exited) ## Successfully exited containers $ docker ps -a --filter 'exited=0' CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES ea09c3c82f6e registry:latest /srv/run.sh 2 weeks ago Exited (0) 2 weeks ago 127.0.0.1:5000->5000/tcp desperate_leakey 106ea823fe4e fedora:latest /bin/sh -c 'bash -l' 2 weeks ago Exited (0) 2 weeks ago determined_albattani 48ee228c9464 fedora:20 bash 2 weeks ago Exited (0) 2 weeks ago tender_torvalds This shows all the containers that have exited with status of '0' ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/pull.md ================================================ # pull Usage: docker pull [OPTIONS] NAME[:TAG] | [REGISTRY_HOST[:REGISTRY_PORT]/]NAME[:TAG] Pull an image or a repository from the registry -a, --all-tags=false Download all tagged images in the repository Most of your images will be created on top of a base image from the [Docker Hub](https://hub.docker.com) registry. [Docker Hub](https://hub.docker.com) contains many pre-built images that you can `pull` and try without needing to define and configure your own. It is also possible to manually specify the path of a registry to pull from. For example, if you have set up a local registry, you can specify its path to pull from it. A repository path is similar to a URL, but does not contain a protocol specifier (`https://`, for example). To download a particular image, or set of images (i.e., a repository), use `docker pull`: $ docker pull debian # will pull the debian:latest image and its intermediate layers $ docker pull debian:testing # will pull the image named debian:testing and any intermediate # layers it is based on. $ docker pull debian@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf # will pull the image from the debian repository with the digest # sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf # and any intermediate layers it is based on. # (Typically the empty `scratch` image, a MAINTAINER layer, # and the un-tarred base). $ docker pull --all-tags centos # will pull all the images from the centos repository $ docker pull registry.hub.docker.com/debian # manually specifies the path to the default Docker registry. This could # be replaced with the path to a local registry to pull from another source. # sudo docker pull myhub.com:8080/test-image ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/push.md ================================================ # push Usage: docker push NAME[:TAG] Push an image or a repository to the registry Use `docker push` to share your images to the [Docker Hub](https://hub.docker.com) registry or to a self-hosted one. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/rename.md ================================================ # rename Usage: docker rename OLD_NAME NEW_NAME rename a existing container to a NEW_NAME The `docker rename` command allows the container to be renamed to a different name. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/restart.md ================================================ # restart Usage: docker restart [OPTIONS] CONTAINER [CONTAINER...] Restart a running container -t, --time=10 Seconds to wait for stop before killing the container ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/rm.md ================================================ # rm Usage: docker rm [OPTIONS] CONTAINER [CONTAINER...] Remove one or more containers -f, --force=false Force the removal of a running container (uses SIGKILL) -l, --link=false Remove the specified link -v, --volumes=false Remove the volumes associated with the container ## Examples $ docker rm /redis /redis This will remove the container referenced under the link `/redis`. $ docker rm --link /webapp/redis /webapp/redis This will remove the underlying link between `/webapp` and the `/redis` containers removing all network communication. $ docker rm --force redis redis The main process inside the container referenced under the link `/redis` will receive `SIGKILL`, then the container will be removed. $ docker rm $(docker ps -a -q) This command will delete all stopped containers. The command `docker ps -a -q` will return all existing container IDs and pass them to the `rm` command which will delete them. Any running containers will not be deleted. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/rmi.md ================================================ # rmi Usage: docker rmi [OPTIONS] IMAGE [IMAGE...] Remove one or more images -f, --force=false Force removal of the image --no-prune=false Do not delete untagged parents You can remove an image using its short or long ID, its tag, or its digest. If an image has one or more tag or digest reference, you must remove all of them before the image is removed. $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE test1 latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) test latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) test2 latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) $ docker rmi fd484f19954f Error: Conflict, cannot delete image fd484f19954f because it is tagged in multiple repositories, use -f to force 2013/12/11 05:47:16 Error: failed to remove one or more images $ docker rmi test1 Untagged: test1:latest $ docker rmi test2 Untagged: test2:latest $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE test latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) $ docker rmi test Untagged: test:latest Deleted: fd484f19954f4920da7ff372b5067f5b7ddb2fd3830cecd17b96ea9e286ba5b8 If you use the `-f` flag and specify the image's short or long ID, then this command untags and removes all images that match the specified ID. $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE test1 latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) test latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) test2 latest fd484f19954f 23 seconds ago 7 B (virtual 4.964 MB) $ docker rmi -f fd484f19954f Untagged: test1:latest Untagged: test:latest Untagged: test2:latest Deleted: fd484f19954f4920da7ff372b5067f5b7ddb2fd3830cecd17b96ea9e286ba5b8 An image pulled by digest has no tag associated with it: $ docker images --digests REPOSITORY TAG DIGEST IMAGE ID CREATED VIRTUAL SIZE localhost:5000/test/busybox sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf 4986bf8c1536 9 weeks ago 2.43 MB To remove an image using its digest: $ docker rmi localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf Untagged: localhost:5000/test/busybox@sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf Deleted: 4986bf8c15363d1c5d15512d5266f8777bfba4974ac56e3270e7760f6f0a8125 Deleted: ea13149945cb6b1e746bf28032f02e9b5a793523481a0a18645fc77ad53c4ea2 Deleted: df7546f9f060a2268024c8a230d8639878585defcc1bc6f79d2728a13957871b ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/run.md ================================================ # run Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Run a command in a new container -a, --attach=[] Attach to STDIN, STDOUT or STDERR --add-host=[] Add a custom host-to-IP mapping (host:ip) --blkio-weight=0 Block IO weight (relative weight) -c, --cpu-shares=0 CPU shares (relative weight) --cap-add=[] Add Linux capabilities --cap-drop=[] Drop Linux capabilities --cgroup-parent="" Optional parent cgroup for the container --cidfile="" Write the container ID to the file --cpu-period=0 Limit CPU CFS (Completely Fair Scheduler) period --cpu-quota=0 Limit CPU CFS (Completely Fair Scheduler) quota --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1) --cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1) -d, --detach=false Run container in background and print container ID --device=[] Add a host device to the container --dns=[] Set custom DNS servers --dns-search=[] Set custom DNS search domains -e, --env=[] Set environment variables --entrypoint="" Overwrite the default ENTRYPOINT of the image --env-file=[] Read in a file of environment variables --expose=[] Expose a port or a range of ports --group-add=[] Add additional groups to run as -h, --hostname="" Container host name --help=false Print usage -i, --interactive=false Keep STDIN open even if not attached --ipc="" IPC namespace to use -l, --label=[] Set metadata on the container (e.g., --label=com.example.key=value) --label-file=[] Read in a file of labels (EOL delimited) --link=[] Add link to another container --log-driver="" Logging driver for container --log-opt=[] Log driver specific options --lxc-conf=[] Add custom lxc options -m, --memory="" Memory limit --mac-address="" Container MAC address (e.g. 92:d0:c6:0a:29:33) --memory-swap="" Total memory (memory + swap), '-1' to disable swap --memory-swappiness="" Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. --name="" Assign a name to the container --net="bridge" Set the Network mode for the container --oom-kill-disable=false Whether to disable OOM Killer for the container or not -P, --publish-all=false Publish all exposed ports to random ports -p, --publish=[] Publish a container's port(s) to the host --pid="" PID namespace to use --privileged=false Give extended privileges to this container --read-only=false Mount the container's root filesystem as read only --restart="no" Restart policy (no, on-failure[:max-retry], always) --rm=false Automatically remove the container when it exits --security-opt=[] Security Options --sig-proxy=true Proxy received signals to the process -t, --tty=false Allocate a pseudo-TTY -u, --user="" Username or UID (format: [:]) --ulimit=[] Ulimit options --uts="" UTS namespace to use -v, --volume=[] Bind mount a volume --volumes-from=[] Mount volumes from the specified container(s) -w, --workdir="" Working directory inside the container The `docker run` command first `creates` a writeable container layer over the specified image, and then `starts` it using the specified command. That is, `docker run` is equivalent to the API `/containers/create` then `/containers/(id)/start`. A stopped container can be restarted with all its previous changes intact using `docker start`. See `docker ps -a` to view a list of all containers. There is detailed information about `docker run` in the [Docker run reference]( /reference/run/). The `docker run` command can be used in combination with `docker commit` to [*change the command that a container runs*](#commit-an-existing-container). See the [Docker User Guide](/userguide/dockerlinks/) for more detailed information about the `--expose`, `-p`, `-P` and `--link` parameters, and linking containers. ## Examples $ docker run --name test -it debian root@d6c0fe130dba:/# exit 13 $ echo $? 13 $ docker ps -a | grep test d6c0fe130dba debian:7 "/bin/bash" 26 seconds ago Exited (13) 17 seconds ago test This example runs a container named `test` using the `debian:latest` image. The `-it` instructs Docker to allocate a pseudo-TTY connected to the container's stdin; creating an interactive `bash` shell in the container. In the example, the `bash` shell is quit by entering `exit 13`. This exit code is passed on to the caller of `docker run`, and is recorded in the `test` container's metadata. $ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test" This will create a container and print `test` to the console. The `cidfile` flag makes Docker attempt to create a new file and write the container ID to it. If the file exists already, Docker will return an error. Docker will close this file when `docker run` exits. $ docker run -t -i --rm ubuntu bash root@bc338942ef20:/# mount -t tmpfs none /mnt mount: permission denied This will *not* work, because by default, most potentially dangerous kernel capabilities are dropped; including `cap_sys_admin` (which is required to mount filesystems). However, the `--privileged` flag will allow it to run: $ docker run --privileged ubuntu bash root@50e3f57e16e6:/# mount -t tmpfs none /mnt root@50e3f57e16e6:/# df -h Filesystem Size Used Avail Use% Mounted on none 1.9G 0 1.9G 0% /mnt The `--privileged` flag gives *all* capabilities to the container, and it also lifts all the limitations enforced by the `device` cgroup controller. In other words, the container can then do almost everything that the host can do. This flag exists to allow special use-cases, like running Docker within Docker. $ docker run -w /path/to/dir/ -i -t ubuntu pwd The `-w` lets the command being executed inside directory given, here `/path/to/dir/`. If the path does not exists it is created inside the container. $ docker run -v `pwd`:`pwd` -w `pwd` -i -t ubuntu pwd The `-v` flag mounts the current working directory into the container. The `-w` lets the command being executed inside the current working directory, by changing into the directory to the value returned by `pwd`. So this combination executes the command using the container, but inside the current working directory. $ docker run -v /doesnt/exist:/foo -w /foo -i -t ubuntu bash When the host directory of a bind-mounted volume doesn't exist, Docker will automatically create this directory on the host for you. In the example above, Docker will create the `/doesnt/exist` folder before starting your container. $ docker run --read-only -v /icanwrite busybox touch /icanwrite here Volumes can be used in combination with `--read-only` to control where a container writes files. The `--read-only` flag mounts the container's root filesystem as read only prohibiting writes to locations other than the specified volumes for the container. $ docker run -t -i -v /var/run/docker.sock:/var/run/docker.sock -v ./static-docker:/usr/bin/docker busybox sh By bind-mounting the docker unix socket and statically linked docker binary (such as that provided by [https://get.docker.com]( https://get.docker.com)), you give the container the full access to create and manipulate the host's Docker daemon. $ docker run -p 127.0.0.1:80:8080 ubuntu bash This binds port `8080` of the container to port `80` on `127.0.0.1` of the host machine. The [Docker User Guide](/userguide/dockerlinks/) explains in detail how to manipulate ports in Docker. $ docker run --expose 80 ubuntu bash This exposes port `80` of the container for use within a link without publishing the port to the host system's interfaces. The [Docker User Guide](/userguide/dockerlinks) explains in detail how to manipulate ports in Docker. $ docker run -e MYVAR1 --env MYVAR2=foo --env-file ./env.list ubuntu bash This sets environmental variables in the container. For illustration all three flags are shown here. Where `-e`, `--env` take an environment variable and value, or if no `=` is provided, then that variable's current value is passed through (i.e. `$MYVAR1` from the host is set to `$MYVAR1` in the container). When no `=` is provided and that variable is not defined in the client's environment then that variable will be removed from the container's list of environment variables. All three flags, `-e`, `--env` and `--env-file` can be repeated. Regardless of the order of these three flags, the `--env-file` are processed first, and then `-e`, `--env` flags. This way, the `-e` or `--env` will override variables as needed. $ cat ./env.list TEST_FOO=BAR $ docker run --env TEST_FOO="This is a test" --env-file ./env.list busybox env | grep TEST_FOO TEST_FOO=This is a test The `--env-file` flag takes a filename as an argument and expects each line to be in the `VAR=VAL` format, mimicking the argument passed to `--env`. Comment lines need only be prefixed with `#` An example of a file passed with `--env-file` $ cat ./env.list TEST_FOO=BAR # this is a comment TEST_APP_DEST_HOST=10.10.0.127 TEST_APP_DEST_PORT=8888 _TEST_BAR=FOO TEST_APP_42=magic helloWorld=true # 123qwe=bar <- is not valid # pass through this variable from the caller TEST_PASSTHROUGH $ TEST_PASSTHROUGH=howdy docker run --env-file ./env.list busybox env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOSTNAME=5198e0745561 TEST_FOO=BAR TEST_APP_DEST_HOST=10.10.0.127 TEST_APP_DEST_PORT=8888 _TEST_BAR=FOO TEST_APP_42=magic helloWorld=true TEST_PASSTHROUGH=howdy HOME=/root $ docker run --env-file ./env.list busybox env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOSTNAME=5198e0745561 TEST_FOO=BAR TEST_APP_DEST_HOST=10.10.0.127 TEST_APP_DEST_PORT=8888 _TEST_BAR=FOO TEST_APP_42=magic helloWorld=true TEST_PASSTHROUGH= HOME=/root > **Note**: Environment variables names must consist solely of letters, numbers, > and underscores - and cannot start with a number. A label is a a `key=value` pair that applies metadata to a container. To label a container with two labels: $ docker run -l my-label --label com.example.foo=bar ubuntu bash The `my-label` key doesn't specify a value so the label defaults to an empty string(`""`). To add multiple labels, repeat the label flag (`-l` or `--label`). The `key=value` must be unique to avoid overwriting the label value. If you specify labels with identical keys but different values, each subsequent value overwrites the previous. Docker uses the last `key=value` you supply. Use the `--label-file` flag to load multiple labels from a file. Delimit each label in the file with an EOL mark. The example below loads labels from a labels file in the current directory: $ docker run --label-file ./labels ubuntu bash The label-file format is similar to the format for loading environment variables. (Unlike environment variables, labels are not visible to processes running inside a container.) The following example illustrates a label-file format: com.example.label1="a label" # this is a comment com.example.label2=another\ label com.example.label3 You can load multiple label-files by supplying multiple `--label-file` flags. For additional information on working with labels, see [*Labels - custom metadata in Docker*](/userguide/labels-custom-metadata/) in the Docker User Guide. $ docker run --link /redis:redis --name console ubuntu bash The `--link` flag will link the container named `/redis` into the newly created container with the alias `redis`. The new container can access the network and environment of the `redis` container via environment variables. The `--link` flag will also just accept the form `` in which case the alias will match the name. For instance, you could have written the previous example as: $ docker run --link redis --name console ubuntu bash The `--name` flag will assign the name `console` to the newly created container. $ docker run --volumes-from 777f7dc92da7 --volumes-from ba8c0c54f0f2:ro -i -t ubuntu pwd The `--volumes-from` flag mounts all the defined volumes from the referenced containers. Containers can be specified by repetitions of the `--volumes-from` argument. The container ID may be optionally suffixed with `:ro` or `:rw` to mount the volumes in read-only or read-write mode, respectively. By default, the volumes are mounted in the same mode (read write or read only) as the reference container. Labeling systems like SELinux require that proper labels are placed on volume content mounted into a container. Without a label, the security system might prevent the processes running inside the container from using the content. By default, Docker does not change the labels set by the OS. To change the label in the container context, you can add either of two suffixes `:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file objects on the shared volumes. The `z` option tells Docker that two containers share the volume content. As a result, Docker labels the content with a shared content label. Shared volume labels allow all containers to read/write content. The `Z` option tells Docker to label the content with a private unshared label. Only the current container can use a private volume. The `-a` flag tells `docker run` to bind to the container's `STDIN`, `STDOUT` or `STDERR`. This makes it possible to manipulate the output and input as needed. $ echo "test" | docker run -i -a stdin ubuntu cat - This pipes data into a container and prints the container's ID by attaching only to the container's `STDIN`. $ docker run -a stderr ubuntu echo test This isn't going to print anything unless there's an error because we've only attached to the `STDERR` of the container. The container's logs still store what's been written to `STDERR` and `STDOUT`. $ cat somefile | docker run -i -a stdin mybuilder dobuild This is how piping a file into a container could be done for a build. The container's ID will be printed after the build is done and the build logs could be retrieved using `docker logs`. This is useful if you need to pipe a file or something else into a container and retrieve the container's ID once the container has finished running. $ docker run --device=/dev/sdc:/dev/xvdc --device=/dev/sdd --device=/dev/zero:/dev/nulo -i -t ubuntu ls -l /dev/{xvdc,sdd,nulo} brw-rw---- 1 root disk 8, 2 Feb 9 16:05 /dev/xvdc brw-rw---- 1 root disk 8, 3 Feb 9 16:05 /dev/sdd crw-rw-rw- 1 root root 1, 5 Feb 9 16:05 /dev/nulo It is often necessary to directly expose devices to a container. The `--device` option enables that. For example, a specific block storage device or loop device or audio device can be added to an otherwise unprivileged container (without the `--privileged` flag) and have the application directly access it. By default, the container will be able to `read`, `write` and `mknod` these devices. This can be overridden using a third `:rwm` set of options to each `--device` flag: $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc:ro --rm -it ubuntu fdisk /dev/xvdc You will not be able to write the partition table. Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc fdisk: unable to open /dev/xvdc: Operation not permitted > **Note:** > `--device` cannot be safely used with ephemeral devices. Block devices > that may be removed should not be added to untrusted containers with > `--device`. **A complete example:** $ docker run -d --name static static-web-files sh $ docker run -d --expose=8098 --name riak riakserver $ docker run -d -m 100m -e DEVELOPMENT=1 -e BRANCH=example-code -v $(pwd):/app/bin:ro --name app appserver $ docker run -d -p 1443:443 --dns=10.0.0.1 --dns-search=dev.org -v /var/log/httpd --volumes-from static --link riak --link app -h www.sven.dev.org --name web webserver $ docker run -t -i --rm --volumes-from web -w /var/log/httpd busybox tail -f access.log This example shows five containers that might be set up to test a web application change: 1. Start a pre-prepared volume image `static-web-files` (in the background) that has CSS, image and static HTML in it, (with a `VOLUME` instruction in the Dockerfile to allow the web server to use those files); 2. Start a pre-prepared `riakserver` image, give the container name `riak` and expose port `8098` to any containers that link to it; 3. Start the `appserver` image, restricting its memory usage to 100MB, setting two environment variables `DEVELOPMENT` and `BRANCH` and bind-mounting the current directory (`$(pwd)`) in the container in read-only mode as `/app/bin`; 4. Start the `webserver`, mapping port `443` in the container to port `1443` on the Docker server, setting the DNS server to `10.0.0.1` and DNS search domain to `dev.org`, creating a volume to put the log files into (so we can access it from another container), then importing the files from the volume exposed by the `static` container, and linking to all exposed ports from `riak` and `app`. Lastly, we set the hostname to `web.sven.dev.org` so its consistent with the pre-generated SSL certificate; 5. Finally, we create a container that runs `tail -f access.log` using the logs volume from the `web` container, setting the workdir to `/var/log/httpd`. The `--rm` option means that when the container exits, the container's layer is removed. ## Restart policies Use Docker's `--restart` to specify a container's *restart policy*. A restart policy controls whether the Docker daemon restarts a container after exit. Docker supports the following restart policies:
Policy Result
no Do not automatically restart the container when it exits. This is the default.
on-failure[:max-retries] Restart only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts.
always Always restart the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely.
$ docker run --restart=always redis This will run the `redis` container with a restart policy of **always** so that if the container exits, Docker will restart it. More detailed information on restart policies can be found in the [Restart Policies (--restart)](/reference/run/#restart-policies-restart) section of the Docker run reference page. ## Adding entries to a container hosts file You can add other hosts into a container's `/etc/hosts` file by using one or more `--add-host` flags. This example adds a static address for a host named `docker`: $ docker run --add-host=docker:10.180.0.1 --rm -it debian $$ ping docker PING docker (10.180.0.1): 48 data bytes 56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms 56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms ^C--- docker ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms Sometimes you need to connect to the Docker host from within your container. To enable this, pass the Docker host's IP address to the container using the `--add-host` flag. To find the host's address, use the `ip addr show` command. The flags you pass to `ip addr show` depend on whether you are using IPv4 or IPv6 networking in your containers. Use the following flags for IPv4 address retrieval for a network device named `eth0`: $ HOSTIP=`ip -4 addr show scope global dev eth0 | grep inet | awk '{print \$2}' | cut -d / -f 1` $ docker run --add-host=docker:${HOSTIP} --rm -it debian For IPv6 use the `-6` flag instead of the `-4` flag. For other network devices, replace `eth0` with the correct device name (for example `docker0` for the bridge device). ### Setting ulimits in a container Since setting `ulimit` settings in a container requires extra privileges not available in the default container, you can set these using the `--ulimit` flag. `--ulimit` is specified with a soft and hard limit as such: `=[:]`, for example: $ docker run --ulimit nofile=1024:1024 --rm debian ulimit -n 1024 > **Note:** > If you do not provide a `hard limit`, the `soft limit` will be used > for both values. If no `ulimits` are set, they will be inherited from > the default `ulimits` set on the daemon. `as` option is disabled now. > In other words, the following script is not supported: > `$ docker run -it --ulimit as=1024 fedora /bin/bash` The values are sent to the appropriate `syscall` as they are set. Docker doesn't perform any byte conversion. Take this into account when setting the values. #### For `nproc` usage: Be careful setting `nproc` with the `ulimit` flag as `nproc` is designed by Linux to set the maximum number of processes available to a user, not to a container. For example, start four containers with `daemon` user: docker run -d -u daemon --ulimit nproc=3 busybox top docker run -d -u daemon --ulimit nproc=3 busybox top docker run -d -u daemon --ulimit nproc=3 busybox top docker run -d -u daemon --ulimit nproc=3 busybox top The 4th container fails and reports "[8] System error: resource temporarily unavailable" error. This fails because the caller set `nproc=3` resulting in the first three containers using up the three processes quota set for the `daemon` user. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/save.md ================================================ # save Usage: docker save [OPTIONS] IMAGE [IMAGE...] Save an image(s) to a tar archive (streamed to STDOUT by default) -o, --output="" Write to a file, instead of STDOUT Produces a tarred repository to the standard output stream. Contains all parent layers, and all tags + versions, or specified `repo:tag`, for each argument provided. It is used to create a backup that can then be used with `docker load` $ docker save busybox > busybox.tar $ ls -sh busybox.tar 2.7M busybox.tar $ docker save --output busybox.tar busybox $ ls -sh busybox.tar 2.7M busybox.tar $ docker save -o fedora-all.tar fedora $ docker save -o fedora-latest.tar fedora:latest It is even useful to cherry-pick particular tags of an image repository $ docker save -o ubuntu.tar ubuntu:lucid ubuntu:saucy ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/search.md ================================================ # search Usage: docker search [OPTIONS] TERM Search the Docker Hub for images --automated=false Only show automated builds --no-trunc=false Don't truncate output -s, --stars=0 Only displays with at least x stars Search [Docker Hub](https://hub.docker.com) for images See [*Find Public Images on Docker Hub*](/userguide/dockerrepos/#searching-for-images) for more details on finding shared images from the command line. > **Note:** > Search queries will only return up to 25 results ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/start.md ================================================ # start Usage: docker start [OPTIONS] CONTAINER [CONTAINER...] Start one or more stopped containers -a, --attach=false Attach STDOUT/STDERR and forward signals -i, --interactive=false Attach container's STDIN ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/stats.md ================================================ # stats Usage: docker stats CONTAINER [CONTAINER...] Display a live stream of one or more containers' resource usage statistics --help=false Print usage --no-stream=false Disable streaming stats and only pull the first result Running `docker stats` on multiple containers $ docker stats redis1 redis2 CONTAINER CPU % MEM USAGE/LIMIT MEM % NET I/O redis1 0.07% 796 KB/64 MB 1.21% 788 B/648 B redis2 0.07% 2.746 MB/64 MB 4.29% 1.266 KB/648 B The `docker stats` command will only return a live stream of data for running containers. Stopped containers will not return any data. > **Note:** > If you want more detailed information about a container's resource > usage, use the API endpoint. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/stop.md ================================================ # stop Usage: docker stop [OPTIONS] CONTAINER [CONTAINER...] Stop a running container by sending SIGTERM and then SIGKILL after a grace period -t, --time=10 Seconds to wait for stop before killing it The main process inside the container will receive `SIGTERM`, and after a grace period, `SIGKILL`. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/tag.md ================================================ # tag Usage: docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG] Tag an image into a repository -f, --force=false Force You can group your images together using names and tags, and then upload them to [*Share Images via Repositories*](/userguide/dockerrepos/#contributing-to-docker-hub). ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/top.md ================================================ # top Usage: docker top CONTAINER [ps OPTIONS] Display the running processes of a container ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/unpause.md ================================================ # unpause Usage: docker unpause CONTAINER [CONTAINER...] Unpause all processes within a container The `docker unpause` command uses the cgroups freezer to un-suspend all processes in a container. See the [cgroups freezer documentation](https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) for further details. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/version.md ================================================ # version Usage: docker version Show the Docker version information. -f, --format="" Format the output using the given go template By default, this will render all version information in an easy to read layout. If a format is specified, the given template will be executed instead. Go's [text/template](http://golang.org/pkg/text/template/) package describes all the details of the format. ## Examples **Default output:** $ docker version Client: Version: 1.8.0 API version: 1.20 Go version: go1.4.2 Git commit: f5bae0a Built: Tue Jun 23 17:56:00 UTC 2015 OS/Arch: linux/amd64 Server: Version: 1.8.0 API version: 1.20 Go version: go1.4.2 Git commit: f5bae0a Built: Tue Jun 23 17:56:00 UTC 2015 OS/Arch: linux/amd64 **Get server version:** $ docker version --format '{{.Server.Version}}' 1.8.0 **Dump raw data:** $ docker version --format '{{json .}}' {"Client":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"amd64","BuildTime":"Tue Jun 23 17:56:00 UTC 2015"},"ServerOK":true,"Server":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"amd64","KernelVersion":"3.13.2-gentoo","BuildTime":"Tue Jun 23 17:56:00 UTC 2015"}} ================================================ FILE: vendor/github.com/docker/docker/docs/reference/commandline/wait.md ================================================ # wait Usage: docker wait CONTAINER [CONTAINER...] Block until a container stops, then print its exit code. ================================================ FILE: vendor/github.com/docker/docker/docs/reference/glossary.md ================================================ # Glossary A list of terms used around the Docker project. ## aufs aufs (advanced multi layered unification filesystem) is a Linux [filesystem](#filesystem) that Docker supports as a storage backend. It implements the [union mount](http://en.wikipedia.org/wiki/Union_mount) for Linux file systems. ## boot2docker [boot2docker](http://boot2docker.io/) is a lightweight Linux distribution made specifically to run Docker containers. It is a common choice for a [VM](#virtual-machine) to run Docker on Windows and Mac OS X. boot2docker can also refer to the boot2docker management tool on Windows and Mac OS X which manages the boot2docker VM. ## btrfs btrfs (B-tree file system) is a Linux [filesystem](#filesystem) that Docker supports as a storage backend. It is a [copy-on-write](http://en.wikipedia.org/wiki/Copy-on-write) filesystem. ## build build is the process of building Docker images using a [Dockerfile](#dockerfile). The build uses a Dockerfile and a "context". The context is the set of files in the directory in which the image is built. ## cgroups cgroups is a Linux kernel feature that limits, accounts for, and isolates the resource usage (CPU, memory, disk I/O, network, etc.) of a collection of processes. Docker relies on cgroups to control and isolate resource limits. *Also known as : control groups* ## Compose [Compose](https://github.com/docker/compose) is a tool for defining and running complex applications with Docker. With compose, you define a multi-container application in a single file, then spin your application up in a single command which does everything that needs to be done to get it running. *Also known as : docker-compose, fig* ## container A container is a runtime instance of a [docker image](#image). A Docker container consists of - A Docker image - Execution environment - A standard set of instructions The concept is borrowed from Shipping Containers, which define a standard to ship goods globally. Docker defines a standard to ship software. ## data volume A data volume is a specially-designated directory within one or more containers that bypasses the Union File System. Data volumes are designed to persist data, independent of the container's life cycle. Docker therefore never automatically delete volumes when you remove a container, nor will it "garbage collect" volumes that are no longer referenced by a container. ## Docker The term Docker can refer to - The Docker project as a whole, which is a platform for developers and sysadmins to develop, ship, and run applications - The docker daemon process running on the host which manages images and containers ## Docker Hub The [Docker Hub](https://hub.docker.com/) is a centralized resource for working with Docker and its components. It provides the following services: - Docker image hosting - User authentication - Automated image builds and work-flow tools such as build triggers and web hooks - Integration with GitHub and Bitbucket ## Dockerfile A Dockerfile is a text document that contains all the commands you would normally execute manually in order to build a Docker image. Docker can build images automatically by reading the instructions from a Dockerfile. ## filesystem A file system is the method an operating system uses to name files and assign them locations for efficient storage and retrieval. Examples : - Linux : ext4, aufs, btrfs, zfs - Windows : NTFS - OS X : HFS+ ## image Docker images are the basis of [containers](#container). An Image is an ordered collection of root filesystem changes and the corresponding execution parameters for use within a container runtime. An image typically contains a union of layered filesystems stacked on top of each other. An image does not have state and it never changes. ## 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. ## link links provide an interface to connect Docker containers running on the same host to each other without exposing the hosts' network ports. When you set up a link, you create a conduit between a source container and a recipient container. The recipient can then access select data about the source. To create a link, you can use the `--link` flag. ## Machine [Machine](https://github.com/docker/machine) is a Docker tool which makes it really easy to create Docker hosts on your computer, on cloud providers and inside your own data center. It creates servers, installs Docker on them, then configures the Docker client to talk to them. *Also known as : docker-machine* ## overlay OverlayFS is a [filesystem](#filesystem) service for Linux which implements a [union mount](http://en.wikipedia.org/wiki/Union_mount) for other file systems. It is supported by the Docker daemon as a storage driver. ## registry A Registry is a hosted service containing [repositories](#repository) of [images](#image) which responds to the Registry API. The default registry can be accessed using a browser at [Docker Hub](#docker-hub) or using the `docker search` command. ## repository A repository is a set of Docker images. A repository can be shared by pushing it to a [registry](#registry) server. The different images in the repository can be labeled using [tags](#tag). Here is an example of the shared [nginx repository](https://registry.hub.docker.com/_/nginx/) and its [tags](https://registry.hub.docker.com/_/nginx/tags/manage/) ## Swarm [Swarm](https://github.com/docker/swarm) is a native clustering tool for Docker. Swarm pools together several Docker hosts and exposes them as a single virtual Docker host. It serves the standard Docker API, so any tool that already works with Docker can now transparently scale up to multiple hosts. *Also known as : docker-swarm* ## tag A tag is a label applied to a Docker image in a [repository](#repository). tags are how various images in a repository are distinguished from each other. *Note : This label is not related to the key=value labels set for docker daemon* ## Union file system Union file systems, or UnionFS, are file systems that operate by creating layers, making them very lightweight and fast. Docker uses union file systems to provide the building blocks for containers. ## Virtual Machine A Virtual Machine is a program that emulates a complete computer and imitates dedicated hardware. It shares physical hardware resources with other users but isolates the operating system. The end user has the same experience on a Virtual Machine as they would have on dedicated hardware. Compared to to containers, a Virtual Machine is heavier to run, provides more isolation, gets its own set of resources and does minimal sharing. *Also known as : VM* ================================================ FILE: vendor/github.com/docker/docker/docs/reference/logging/fluentd.md ================================================ # Fluentd logging driver The `fluentd` logging driver sends container logs to the [Fluentd](http://www.fluentd.org/) collector as structured log data. Then, users can use any of the [various output plugins of Fluentd](http://www.fluentd.org/plugins) to write these logs to various destinations. In addition to the log message itself, the `fluentd` log driver sends the following metadata in the structured log message: | Field | Description | -------------------|-------------------------------------| | `container_id` | The full 64-character container ID. | | `container_name` | The container name at the time it was started. If you use `docker rename` to rename a container, the new name is not reflected in the journal entries. | | `source` | `stdout` or `stderr` | ## Usage Configure the default logging driver by passing the `--log-driver` option to the Docker daemon: docker --log-driver=fluentd To set the logging driver for a specific container, pass the `--log-driver` option to `docker run`: docker run --log-driver=fluentd ... Before using this logging driver, launch a Fluentd daemon. The logging driver connects to this daemon through `localhost:24224` by default. Use the `fluentd-address` option to connect to a different address. docker run --log-driver=fluentd --log-opt fluentd-address=myhost.local:24224 If container cannot connect to the Fluentd daemon, the container stops immediately. ## Options Users can use the `--log-opt NAME=VALUE` flag to specify additional Fluentd logging driver options. ### fluentd-address By default, the logging driver connects to `localhost:24224`. Supply the `fluentd-address` option to connect to a different address. docker run --log-driver=fluentd --log-opt fluentd-address=myhost.local:24224 ### fluentd-tag Every Fluentd's event has a tag that indicates where the log comes from. By default, the driver uses the `docker.{{.ID}}` tag. Use the `fluentd-tag` option to change this behavior. When specifying a `fluentd-tag` value, you can use the following markup tags: - `{{.ID}}`: short container id (12 characters) - `{{.FullID}}`: full container id - `{{.Name}}`: container name ## Note regarding container names At startup time, the system sets the `container_name` field and `{{.Name}}` in the tags to their values at startup. If you use `docker rename` to rename a container, the new name is not be reflected in `fluentd` messages. Instead, these messages continue to use the original container name. ## Fluentd daemon management with Docker About `Fluentd` itself, see [the project webpage](http://www.fluentd.org) and [its documents](http://docs.fluentd.org/). To use this logging driver, start the `fluentd` daemon on a host. We recommend that you use [the Fluentd docker image](https://registry.hub.docker.com/u/fluent/fluentd/). This image is especially useful if you want to aggregate multiple container logs on a each host then, later, transfer the logs to another Fluentd node to create an aggregate store. ### Testing container loggers 1. Write a configuration file (`test.conf`) to dump input logs: @type forward @type stdout 2. Launch Fluentd container with this configuration file: $ docker run -it -p 24224:24224 -v /path/to/conf/test.conf:/fluentd/etc -e FLUENTD_CONF=test.conf fluent/fluentd:latest 3. Start one or more containers with the `fluentd` logging driver: $ docker run --log-driver=fluentd your/application ================================================ FILE: vendor/github.com/docker/docker/docs/reference/logging/index.md ================================================ # Configure logging drivers The container can have a different logging driver than the Docker daemon. Use the `--log-driver=VALUE` with the `docker run` command to configure the container's logging driver. The following options are supported: | `none` | Disables any logging for the container. `docker logs` won't be available with this driver. | |-------------|-------------------------------------------------------------------------------------------------------------------------------| | `json-file` | Default logging driver for Docker. Writes JSON messages to file. | | `syslog` | Syslog logging driver for Docker. Writes log messages to syslog. | | `journald` | Journald logging driver for Docker. Writes log messages to `journald`. | | `gelf` | Graylog Extended Log Format (GELF) logging driver for Docker. Writes log messages to a GELF endpoint likeGraylog or Logstash. | | `fluentd` | Fluentd logging driver for Docker. Writes log messages to `fluentd` (forward input). | The `docker logs`command is available only for the `json-file` logging driver. ### The json-file options The following logging options are supported for the `json-file` logging driver: --log-opt max-size=[0-9+][k|m|g] --log-opt max-file=[0-9+] Logs that reach `max-size` are rolled over. You can set the size in kilobytes(k), megabytes(m), or gigabytes(g). eg `--log-opt max-size=50m`. If `max-size` is not set, then logs are not rolled over. `max-file` specifies the maximum number of files that a log is rolled over before being discarded. eg `--log-opt max-file=100`. If `max-size` is not set, then `max-file` is not honored. If `max-size` and `max-file` are set, `docker logs` only returns the log lines from the newest log file. ### The syslog options The following logging options are supported for the `syslog` logging driver: --log-opt syslog-address=[tcp|udp]://host:port --log-opt syslog-address=unix://path --log-opt syslog-facility=daemon --log-opt syslog-tag="mailer" `syslog-address` specifies the remote syslog server address where the driver connects to. If not specified it defaults to the local unix socket of the running system. If transport is either `tcp` or `udp` and `port` is not specified it defaults to `514` The following example shows how to have the `syslog` driver connect to a `syslog` remote server at `192.168.0.42` on port `123` $ docker run --log-driver=syslog --log-opt syslog-address=tcp://192.168.0.42:123 The `syslog-facility` option configures the syslog facility. By default, the system uses the `daemon` value. To override this behavior, you can provide an integer of 0 to 23 or any of the following named facilities: * `kern` * `user` * `mail` * `daemon` * `auth` * `syslog` * `lpr` * `news` * `uucp` * `cron` * `authpriv` * `ftp` * `local0` * `local1` * `local2` * `local3` * `local4` * `local5` * `local6` * `local7` The `syslog-tag` specifies a tag that identifies the container's syslog messages. By default, the system uses the first 12 characters of the container id. To override this behavior, specify a `syslog-tag` option ## Specify journald options The `journald` logging driver stores the container id in the journal's `CONTAINER_ID` field. For detailed information on working with this logging driver, see [the journald logging driver](/reference/logging/journald/) reference documentation. ## Specify gelf options The GELF logging driver supports the following options: --log-opt gelf-address=udp://host:port --log-opt gelf-tag="database" The `gelf-address` option specifies the remote GELF server address that the driver connects to. Currently, only `udp` is supported as the transport and you must specify a `port` value. The following example shows how to connect the `gelf` driver to a GELF remote server at `192.168.0.42` on port `12201` $ docker run --log-driver=gelf --log-opt gelf-address=udp://192.168.0.42:12201 The `gelf-tag` option specifies a tag for easy container identification. ## Specify fluentd options You can use the `--log-opt NAME=VALUE` flag to specify these additional Fluentd logging driver options. - `fluentd-address`: specify `host:port` to connect [localhost:24224] - `fluentd-tag`: specify tag for `fluentd` message, When specifying a `fluentd-tag` value, you can use the following markup tags: - `{{.ID}}`: short container id (12 characters) - `{{.FullID}}`: full container id - `{{.Name}}`: container name For example, to specify both additional options: `docker run --log-driver=fluentd --log-opt fluentd-address=localhost:24224 --log-opt fluentd-tag=docker.{{.Name}}` If container cannot connect to the Fluentd daemon on the specified address, the container stops immediately. For detailed information on working with this logging driver, see [the fluentd logging driver](/reference/logging/fluentd/) ================================================ FILE: vendor/github.com/docker/docker/docs/reference/logging/journald.md ================================================ # Journald logging driver The `journald` logging driver sends container logs to the [systemd journal](http://www.freedesktop.org/software/systemd/man/systemd-journald.service.html). Log entries can be retrieved using the `journalctl` command or through use of the journal API. In addition to the text of the log message itself, the `journald` log driver stores the following metadata in the journal with each message: | Field | Description | ----------------------|-------------| | `CONTAINER_ID` | The container ID truncated to 12 characters. | | `CONTAINER_ID_FULL` | The full 64-character container ID. | | `CONTAINER_NAME` | The container name at the time it was started. If you use `docker rename` to rename a container, the new name is not reflected in the journal entries. | ## Usage You can configure the default logging driver by passing the `--log-driver` option to the Docker daemon: docker --log-driver=journald You can set the logging driver for a specific container by using the `--log-driver` option to `docker run`: docker run --log-driver=journald ... ## Note regarding container names The value logged in the `CONTAINER_NAME` field is the container name that was set at startup. If you use `docker rename` to rename a container, the new name will not be reflected in the journal entries. Journal entries will continue to use the original name. ## Retrieving log messages with journalctl You can use the `journalctl` command to retrieve log messages. You can apply filter expressions to limit the retrieved messages to a specific container. For example, to retrieve all log messages from a container referenced by name: # journalctl CONTAINER_NAME=webserver You can make use of additional filters to further limit the messages retrieved. For example, to see just those messages generated since the system last booted: # journalctl -b CONTAINER_NAME=webserver Or to retrieve log messages in JSON format with complete metadata: # journalctl -o json CONTAINER_NAME=webserver ## Retrieving log messages with the journal API This example uses the `systemd` Python module to retrieve container logs: import systemd.journal reader = systemd.journal.Reader() reader.add_match('CONTAINER_NAME=web') for msg in reader: print '{CONTAINER_ID_FULL}: {MESSAGE}'.format(**msg) ================================================ FILE: vendor/github.com/docker/docker/docs/reference/run.md ================================================ # Docker run reference **Docker runs processes in isolated containers**. When an operator executes `docker run`, she starts a process with its own file system, its own networking, and its own isolated process tree. The [*Image*](/terms/image/#image) which starts the process may define defaults related to the binary to run, the networking to expose, and more, but `docker run` gives final control to the operator who starts the container from the image. That's the main reason [*run*](/reference/commandline/cli/#run) has more options than any other `docker` command. ## General form The basic `docker run` command takes this form: $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...] To learn how to interpret the types of `[OPTIONS]`, see [*Option types*](/reference/commandline/cli/#option-types). The `run` options control the image's runtime behavior in a container. These settings affect: * detached or foreground running * container identification * network settings * runtime constraints on CPU and memory * privileges and LXC configuration An image developer may set defaults for these same settings when they create the image using the `docker build` command. Operators, however, can override all defaults set by the developer using the `run` options. And, operators can also override nearly all the defaults set by the Docker runtime itself. Finally, depending on your Docker system configuration, you may be required to preface each `docker` command with `sudo`. To avoid having to use `sudo` with the `docker` command, your system administrator can create a Unix group called `docker` and add users to it. For more information about this configuration, refer to the Docker installation documentation for your operating system. ## Operator exclusive options Only the operator (the person executing `docker run`) can set the following options. - [Detached vs Foreground](#detached-vs-foreground) - [Detached (-d)](#detached-d) - [Foreground](#foreground) - [Container Identification](#container-identification) - [Name (--name)](#name-name) - [PID Equivalent](#pid-equivalent) - [IPC Settings (--ipc)](#ipc-settings-ipc) - [Network Settings](#network-settings) - [Restart Policies (--restart)](#restart-policies-restart) - [Clean Up (--rm)](#clean-up-rm) - [Runtime Constraints on CPU and Memory](#runtime-constraints-on-cpu-and-memory) - [Runtime Privilege, Linux Capabilities, and LXC Configuration](#runtime-privilege-linux-capabilities-and-lxc-configuration) ## Detached vs foreground When starting a Docker container, you must first decide if you want to run the container in the background in a "detached" mode or in the default foreground mode: -d=false: Detached mode: Run container in the background, print new container id ### Detached (-d) In detached mode (`-d=true` or just `-d`), all I/O should be done through network connections or shared volumes because the container is no longer listening to the command line where you executed `docker run`. You can reattach to a detached container with `docker` [*attach*](/reference/commandline/cli/#attach). If you choose to run a container in the detached mode, then you cannot use the `--rm` option. ### Foreground In foreground mode (the default when `-d` is not specified), `docker run` can start the process in the container and attach the console to the process's standard input, output, and standard error. It can even pretend to be a TTY (this is what most command line executables expect) and pass along signals. All of that is configurable: -a=[] : Attach to `STDIN`, `STDOUT` and/or `STDERR` -t=false : Allocate a pseudo-tty --sig-proxy=true: Proxify all received signal to the process (non-TTY mode only) -i=false : Keep STDIN open even if not attached If you do not specify `-a` then Docker will [attach all standard streams]( https://github.com/docker/docker/blob/ 75a7f4d90cde0295bcfb7213004abce8d4779b75/commands.go#L1797). You can specify to which of the three standard streams (`STDIN`, `STDOUT`, `STDERR`) you'd like to connect instead, as in: $ docker run -a stdin -a stdout -i -t ubuntu /bin/bash For interactive processes (like a shell), you must use `-i -t` together in order to allocate a tty for the container process. `-i -t` is often written `-it` as you'll see in later examples. Specifying `-t` is forbidden when the client standard output is redirected or piped, such as in: `echo test | docker run -i busybox cat`. >**Note**: A process running as PID 1 inside a container is treated >specially by Linux: it ignores any signal with the default action. >So, the process will not terminate on `SIGINT` or `SIGTERM` unless it is >coded to do so. ## Container identification ### Name (--name) The operator can identify a container in three ways: - UUID long identifier ("f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778") - UUID short identifier ("f78375b1c487") - Name ("evil_ptolemy") The UUID identifiers come from the Docker daemon, and if you do not assign a name to the container with `--name` then the daemon will also generate a random string name too. The name can become a handy way to add meaning to a container since you can use this name when defining [*links*](/userguide/dockerlinks) (or any other place you need to identify a container). This works for both background and foreground Docker containers. ### PID equivalent Finally, to help with automation, you can have Docker write the container ID out to a file of your choosing. This is similar to how some programs might write out their process ID to a file (you've seen them as PID files): --cidfile="": Write the container ID to the file ### Image[:tag] While not strictly a means of identifying a container, you can specify a version of an image you'd like to run the container with by adding `image[:tag]` to the command. For example, `docker run ubuntu:14.04`. ### Image[@digest] Images using the v2 or later image format have a content-addressable identifier called a digest. As long as the input used to generate the image is unchanged, the digest value is predictable and referenceable. ## PID settings (--pid) --pid="" : Set the PID (Process) Namespace mode for the container, 'host': use the host's PID namespace inside the container By default, all containers have the PID namespace enabled. PID namespace provides separation of processes. The PID Namespace removes the view of the system processes, and allows process ids to be reused including pid 1. In certain cases you want your container to share the host's process namespace, basically allowing processes within the container to see all of the processes on the system. For example, you could build a container with debugging tools like `strace` or `gdb`, but want to use these tools when debugging processes within the container. $ docker run --pid=host rhel7 strace -p 1234 This command would allow you to use `strace` inside the container on pid 1234 on the host. ## UTS settings (--uts) --uts="" : Set the UTS namespace mode for the container, 'host': use the host's UTS namespace inside the container The UTS namespace is for setting the hostname and the domain that is visible to running processes in that namespace. By default, all containers, including those with `--net=host`, have their own UTS namespace. The `host` setting will result in the container using the same UTS namespace as the host. You may wish to share the UTS namespace with the host if you would like the hostname of the container to change as the hostname of the host changes. A more advanced use case would be changing the host's hostname from a container. > **Note**: `--uts="host"` gives the container full access to change the > hostname of the host and is therefore considered insecure. ## IPC settings (--ipc) --ipc="" : Set the IPC mode for the container, 'container:': reuses another container's IPC namespace 'host': use the host's IPC namespace inside the container By default, all containers have the IPC namespace enabled. IPC (POSIX/SysV IPC) namespace provides separation of named shared memory segments, semaphores and message queues. Shared memory segments are used to accelerate inter-process communication at memory speed, rather than through pipes or through the network stack. Shared memory is commonly used by databases and custom-built (typically C/OpenMPI, C++/using boost libraries) high performance applications for scientific computing and financial services industries. If these types of applications are broken into multiple containers, you might need to share the IPC mechanisms of the containers. ## Network settings --dns=[] : Set custom dns servers for the container --net="bridge" : Set the Network mode for the container 'bridge': creates a new network stack for the container on the docker bridge 'none': no networking for this container 'container:': reuses another container network stack 'host': use the host network stack inside the container --add-host="" : Add a line to /etc/hosts (host:IP) --mac-address="" : Sets the container's Ethernet device's MAC address By default, all containers have networking enabled and they can make any outgoing connections. The operator can completely disable networking with `docker run --net none` which disables all incoming and outgoing networking. In cases like this, you would perform I/O through files or `STDIN` and `STDOUT` only. Your container will use the same DNS servers as the host by default, but you can override this with `--dns`. By default, the MAC address is generated using the IP address allocated to the container. You can set the container's MAC address explicitly by providing a MAC address via the `--mac-address` parameter (format:`12:34:56:78:9a:bc`). Supported networking modes are:
Mode Description
none No networking in the container.
bridge (default) Connect the container to the bridge via veth interfaces.
host Use the host's network stack inside the container.
container:<name|id> Use the network stack of another container, specified via its *name* or *id*.
#### Mode: none With the networking mode set to `none` a container will not have a access to any external routes. The container will still have a `loopback` interface enabled in the container but it does not have any routes to external traffic. #### Mode: bridge With the networking mode set to `bridge` a container will use docker's default networking setup. A bridge is setup on the host, commonly named `docker0`, and a pair of `veth` interfaces will be created for the container. One side of the `veth` pair will remain on the host attached to the bridge while the other side of the pair will be placed inside the container's namespaces in addition to the `loopback` interface. An IP address will be allocated for containers on the bridge's network and traffic will be routed though this bridge to the container. #### Mode: host With the networking mode set to `host` a container will share the host's network stack and all interfaces from the host will be available to the container. The container's hostname will match the hostname on the host system. Publishing ports and linking to other containers will not work when sharing the host's network stack. Note that `--add-host` `--hostname` `--dns` `--dns-search` and `--mac-address` is invalid in `host` netmode. Compared to the default `bridge` mode, the `host` mode gives *significantly* better networking performance since it uses the host's native networking stack whereas the bridge has to go through one level of virtualization through the docker daemon. It is recommended to run containers in this mode when their networking performance is critical, for example, a production Load Balancer or a High Performance Web Server. > **Note**: `--net="host"` gives the container full access to local system > services such as D-bus and is therefore considered insecure. #### Mode: container With the networking mode set to `container` a container will share the network stack of another container. The other container's name must be provided in the format of `--net container:`. Note that `--add-host` `--hostname` `--dns` `--dns-search` and `--mac-address` is invalid in `container` netmode, and `--publish` `--publish-all` `--expose` are also invalid in `container` netmode. Example running a Redis container with Redis binding to `localhost` then running the `redis-cli` command and connecting to the Redis server over the `localhost` interface. $ docker run -d --name redis example/redis --bind 127.0.0.1 $ # use the redis container's network stack to access localhost $ docker run --rm -it --net container:redis example/redis-cli -h 127.0.0.1 ### Managing /etc/hosts Your container will have lines in `/etc/hosts` which define the hostname of the container itself as well as `localhost` and a few other common things. The `--add-host` flag can be used to add additional lines to `/etc/hosts`. $ docker run -it --add-host db-static:86.75.30.9 ubuntu cat /etc/hosts 172.17.0.22 09d03f76bf2c fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback 86.75.30.9 db-static ## Restart policies (--restart) Using the `--restart` flag on Docker run you can specify a restart policy for how a container should or should not be restarted on exit. When a restart policy is active on a container, it will be shown as either `Up` or `Restarting` in [`docker ps`](/reference/commandline/cli/#ps). It can also be useful to use [`docker events`](/reference/commandline/cli/#events) to see the restart policy in effect. Docker supports the following restart policies:
Policy Result
no Do not automatically restart the container when it exits. This is the default.
on-failure[:max-retries] Restart only if the container exits with a non-zero exit status. Optionally, limit the number of restart retries the Docker daemon attempts.
always Always restart the container regardless of the exit status. When you specify always, the Docker daemon will try to restart the container indefinitely.
An ever increasing delay (double the previous delay, starting at 100 milliseconds) is added before each restart to prevent flooding the server. This means the daemon will wait for 100 ms, then 200 ms, 400, 800, 1600, and so on until either the `on-failure` limit is hit, or when you `docker stop` or `docker rm -f` the container. If a container is successfully restarted (the container is started and runs for at least 10 seconds), the delay is reset to its default value of 100 ms. You can specify the maximum amount of times Docker will try to restart the container when using the **on-failure** policy. The default is that Docker will try forever to restart the container. The number of (attempted) restarts for a container can be obtained via [`docker inspect`]( /reference/commandline/cli/#inspect). For example, to get the number of restarts for container "my-container"; $ docker inspect -f "{{ .RestartCount }}" my-container # 2 Or, to get the last time the container was (re)started; $ docker inspect -f "{{ .State.StartedAt }}" my-container # 2015-03-04T23:47:07.691840179Z You cannot set any restart policy in combination with ["clean up (--rm)"](#clean-up-rm). Setting both `--restart` and `--rm` results in an error. ### Examples $ docker run --restart=always redis This will run the `redis` container with a restart policy of **always** so that if the container exits, Docker will restart it. $ docker run --restart=on-failure:10 redis This will run the `redis` container with a restart policy of **on-failure** and a maximum restart count of 10. If the `redis` container exits with a non-zero exit status more than 10 times in a row Docker will abort trying to restart the container. Providing a maximum restart limit is only valid for the **on-failure** policy. ## Clean up (--rm) By default a container's file system persists even after the container exits. This makes debugging a lot easier (since you can inspect the final state) and you retain all your data by default. But if you are running short-term **foreground** processes, these container file systems can really pile up. If instead you'd like Docker to **automatically clean up the container and remove the file system when the container exits**, you can add the `--rm` flag: --rm=false: Automatically remove the container when it exits (incompatible with -d) ## Security configuration --security-opt="label:user:USER" : Set the label user for the container --security-opt="label:role:ROLE" : Set the label role for the container --security-opt="label:type:TYPE" : Set the label type for the container --security-opt="label:level:LEVEL" : Set the label level for the container --security-opt="label:disable" : Turn off label confinement for the container --security-opt="apparmor:PROFILE" : Set the apparmor profile to be applied to the container You can override the default labeling scheme for each container by specifying the `--security-opt` flag. For example, you can specify the MCS/MLS level, a requirement for MLS systems. Specifying the level in the following command allows you to share the same content between containers. $ docker run --security-opt label:level:s0:c100,c200 -i -t fedora bash An MLS example might be: $ docker run --security-opt label:level:TopSecret -i -t rhel7 bash To disable the security labeling for this container versus running with the `--permissive` flag, use the following command: $ docker run --security-opt label:disable -i -t fedora bash If you want a tighter security policy on the processes within a container, you can specify an alternate type for the container. You could run a container that is only allowed to listen on Apache ports by executing the following command: $ docker run --security-opt label:type:svirt_apache_t -i -t centos bash Note: You would have to write policy defining a `svirt_apache_t` type. ## Specifying custom cgroups Using the `--cgroup-parent` flag, you can pass a specific cgroup to run a container in. This allows you to create and manage cgroups on their own. You can define custom resources for those cgroups and put containers under a common parent group. ## Runtime constraints on resources The operator can also adjust the performance parameters of the container: -m, --memory="": Memory limit (format: , where unit = b, k, m or g) --memory-swap="": Total memory limit (memory + swap, format: , where unit = b, k, m or g) -c, --cpu-shares=0: CPU shares (relative weight) --cpu-period=0: Limit the CPU CFS (Completely Fair Scheduler) period --cpuset-cpus="": CPUs in which to allow execution (0-3, 0,1) --cpuset-mems="": Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. --cpu-quota=0: Limit the CPU CFS (Completely Fair Scheduler) quota --blkio-weight=0: Block IO weight (relative weight) accepts a weight value between 10 and 1000. --oom-kill-disable=true|false: Whether to disable OOM Killer for the container or not. --memory-swappiness="": Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. ### Memory constraints We have four ways to set memory usage:
Option Result
memory=inf, memory-swap=inf (default) There is no memory limit for the container. The container can use as much memory as needed.
memory=L<inf, memory-swap=inf (specify memory and set memory-swap as -1) The container is not allowed to use more than L bytes of memory, but can use as much swap as is needed (if the host supports swap memory).
memory=L<inf, memory-swap=2*L (specify memory without memory-swap) The container is not allowed to use more than L bytes of memory, swap *plus* memory usage is double of that.
memory=L<inf, memory-swap=S<inf, L<=S (specify both memory and memory-swap) The container is not allowed to use more than L bytes of memory, swap *plus* memory usage is limited by S.
Examples: $ docker run -ti ubuntu:14.04 /bin/bash We set nothing about memory, this means the processes in the container can use as much memory and swap memory as they need. $ docker run -ti -m 300M --memory-swap -1 ubuntu:14.04 /bin/bash We set memory limit and disabled swap memory limit, this means the processes in the container can use 300M memory and as much swap memory as they need (if the host supports swap memory). $ docker run -ti -m 300M ubuntu:14.04 /bin/bash We set memory limit only, this means the processes in the container can use 300M memory and 300M swap memory, by default, the total virtual memory size (--memory-swap) will be set as double of memory, in this case, memory + swap would be 2*300M, so processes can use 300M swap memory as well. $ docker run -ti -m 300M --memory-swap 1G ubuntu:14.04 /bin/bash We set both memory and swap memory, so the processes in the container can use 300M memory and 700M swap memory. By default, kernel kills processes in a container if an out-of-memory (OOM) error occurs. To change this behaviour, use the `--oom-kill-disable` option. Only disable the OOM killer on containers where you have also set the `-m/--memory` option. If the `-m` flag is not set, this can result in the host running out of memory and require killing the host's system processes to free memory. Examples: The following example limits the memory to 100M and disables the OOM killer for this container: $ docker run -ti -m 100M --oom-kill-disable ubuntu:14.04 /bin/bash The following example, illustrates a dangerous way to use the flag: $ docker run -ti --oom-kill-disable ubuntu:14.04 /bin/bash The container has unlimited memory which can cause the host to run out memory and require killing system processes to free memory. ### Swappiness constraint By default, a container's kernel can swap out a percentage of anonymous pages. To set this percentage for a container, specify a `--memory-swappiness` value between 0 and 100. A value of 0 turns off anonymous page swapping. A value of 100 sets all anonymous pages as swappable. By default, if you are not using `--memory-swappiness`, memory swappiness value will be inherited from the parent. For example, you can set: $ docker run -ti --memory-swappiness=0 ubuntu:14.04 /bin/bash Setting the `--memory-swappiness` option is helpful when you want to retain the container's working set and to avoid swapping performance penalties. ### CPU share constraint By default, all containers get the same proportion of CPU cycles. This proportion can be modified by changing the container's CPU share weighting relative to the weighting of all other running containers. To modify the proportion from the default of 1024, use the `-c` or `--cpu-shares` flag to set the weighting to 2 or higher. The proportion will only apply when CPU-intensive processes are running. When tasks in one container are idle, other containers can use the left-over CPU time. The actual amount of CPU time will vary depending on the number of containers running on the system. For example, consider three containers, one has a cpu-share of 1024 and two others have a cpu-share setting of 512. When processes in all three containers attempt to use 100% of CPU, the first container would receive 50% of the total CPU time. If you add a fourth container with a cpu-share of 1024, the first container only gets 33% of the CPU. The remaining containers receive 16.5%, 16.5% and 33% of the CPU. On a multi-core system, the shares of CPU time are distributed over all CPU cores. Even if a container is limited to less than 100% of CPU time, it can use 100% of each individual CPU core. For example, consider a system with more than three cores. If you start one container `{C0}` with `-c=512` running one process, and another container `{C1}` with `-c=1024` running two processes, this can result in the following division of CPU shares: PID container CPU CPU share 100 {C0} 0 100% of CPU0 101 {C1} 1 100% of CPU1 102 {C1} 2 100% of CPU2 ### CPU period constraint The default CPU CFS (Completely Fair Scheduler) period is 100ms. We can use `--cpu-period` to set the period of CPUs to limit the container's CPU usage. And usually `--cpu-period` should work with `--cpu-quota`. Examples: $ docker run -ti --cpu-period=50000 --cpu-quota=25000 ubuntu:14.04 /bin/bash If there is 1 CPU, this means the container can get 50% CPU worth of run-time every 50ms. For more information, see the [CFS documentation on bandwidth limiting](https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt). ### Cpuset constraint We can set cpus in which to allow execution for containers. Examples: $ docker run -ti --cpuset-cpus="1,3" ubuntu:14.04 /bin/bash This means processes in container can be executed on cpu 1 and cpu 3. $ docker run -ti --cpuset-cpus="0-2" ubuntu:14.04 /bin/bash This means processes in container can be executed on cpu 0, cpu 1 and cpu 2. We can set mems in which to allow execution for containers. Only effective on NUMA systems. Examples: $ docker run -ti --cpuset-mems="1,3" ubuntu:14.04 /bin/bash This example restricts the processes in the container to only use memory from memory nodes 1 and 3. $ docker run -ti --cpuset-mems="0-2" ubuntu:14.04 /bin/bash This example restricts the processes in the container to only use memory from memory nodes 0, 1 and 2. ### CPU quota constraint The `--cpu-quota` flag limits the container's CPU usage. The default 0 value allows the container to take 100% of a CPU resource (1 CPU). The CFS (Completely Fair Scheduler) handles resource allocation for executing processes and is default Linux Scheduler used by the kernel. Set this value to 50000 to limit the container to 50% of a CPU resource. For multiple CPUs, adjust the `--cpu-quota` as necessary. For more information, see the [CFS documentation on bandwidth limiting](https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt). ### Block IO bandwidth (Blkio) constraint By default, all containers get the same proportion of block IO bandwidth (blkio). This proportion is 500. To modify this proportion, change the container's blkio weight relative to the weighting of all other running containers using the `--blkio-weight` flag. The `--blkio-weight` flag can set the weighting to a value between 10 to 1000. For example, the commands below create two containers with different blkio weight: $ docker run -ti --name c1 --blkio-weight 300 ubuntu:14.04 /bin/bash $ docker run -ti --name c2 --blkio-weight 600 ubuntu:14.04 /bin/bash If you do block IO in the two containers at the same time, by, for example: $ time dd if=/mnt/zerofile of=test.out bs=1M count=1024 oflag=direct You'll find that the proportion of time is the same as the proportion of blkio weights of the two containers. > **Note:** The blkio weight setting is only available for direct IO. Buffered IO > is not currently supported. ## Additional groups --group-add: Add Linux capabilities By default, the docker container process runs with the supplementary groups looked up for the specified user. If one wants to add more to that list of groups, then one can use this flag: $ docker run -ti --rm --group-add audio --group-add dbus --group-add 777 busybox id uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777 ## Runtime privilege, Linux capabilities, and LXC configuration --cap-add: Add Linux capabilities --cap-drop: Drop Linux capabilities --privileged=false: Give extended privileges to this container --device=[]: Allows you to run devices inside the container without the --privileged flag. --lxc-conf=[]: Add custom lxc options By default, Docker containers are "unprivileged" and cannot, for example, run a Docker daemon inside a Docker container. This is because by default a container is not allowed to access any devices, but a "privileged" container is given access to all devices (see [lxc-template.go]( https://github.com/docker/docker/blob/master/daemon/execdriver/lxc/lxc_template.go) and documentation on [cgroups devices]( https://www.kernel.org/doc/Documentation/cgroups/devices.txt)). When the operator executes `docker run --privileged`, Docker will enable to access to all devices on the host as well as set some configuration in AppArmor or SELinux to allow the container nearly all the same access to the host as processes running outside containers on the host. Additional information about running with `--privileged` is available on the [Docker Blog](http://blog.docker.com/2013/09/docker-can-now-run-within-docker/). If you want to limit access to a specific device or devices you can use the `--device` flag. It allows you to specify one or more devices that will be accessible within the container. $ docker run --device=/dev/snd:/dev/snd ... By default, the container will be able to `read`, `write`, and `mknod` these devices. This can be overridden using a third `:rwm` set of options to each `--device` flag: $ docker run --device=/dev/sda:/dev/xvdc --rm -it ubuntu fdisk /dev/xvdc Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc:r --rm -it ubuntu fdisk /dev/xvdc You will not be able to write the partition table. Command (m for help): q $ docker run --device=/dev/sda:/dev/xvdc:w --rm -it ubuntu fdisk /dev/xvdc crash.... $ docker run --device=/dev/sda:/dev/xvdc:m --rm -it ubuntu fdisk /dev/xvdc fdisk: unable to open /dev/xvdc: Operation not permitted In addition to `--privileged`, the operator can have fine grain control over the capabilities using `--cap-add` and `--cap-drop`. By default, Docker has a default list of capabilities that are kept. The following table lists the Linux capability options which can be added or dropped. | Capability Key | Capability Description | | -------------- | ---------------------- | | SETPCAP | Modify process capabilities. | | SYS_MODULE| Load and unload kernel modules. | | SYS_RAWIO | Perform I/O port operations (iopl(2) and ioperm(2)). | | SYS_PACCT | Use acct(2), switch process accounting on or off. | | SYS_ADMIN | Perform a range of system administration operations. | | SYS_NICE | Raise process nice value (nice(2), setpriority(2)) and change the nice value for arbitrary processes. | | SYS_RESOURCE | Override resource Limits. | | SYS_TIME | Set system clock (settimeofday(2), stime(2), adjtimex(2)); set real-time (hardware) clock. | | SYS_TTY_CONFIG | Use vhangup(2); employ various privileged ioctl(2) operations on virtual terminals. | | MKNOD | Create special files using mknod(2). | | AUDIT_WRITE | Write records to kernel auditing log. | | AUDIT_CONTROL | Enable and disable kernel auditing; change auditing filter rules; retrieve auditing status and filtering rules. | | MAC_OVERRIDE | Allow MAC configuration or state changes. Implemented for the Smack LSM. | | MAC_ADMIN | Override Mandatory Access Control (MAC). Implemented for the Smack Linux Security Module (LSM). | | NET_ADMIN | Perform various network-related operations. | | SYSLOG | Perform privileged syslog(2) operations. | | CHOWN | Make arbitrary changes to file UIDs and GIDs (see chown(2)). | | NET_RAW | Use RAW and PACKET sockets. | | DAC_OVERRIDE | Bypass file read, write, and execute permission checks. | | FOWNER | Bypass permission checks on operations that normally require the file system UID of the process to match the UID of the file. | | DAC_READ_SEARCH | Bypass file read permission checks and directory read and execute permission checks. | | FSETID | Don't clear set-user-ID and set-group-ID permission bits when a file is modified. | | KILL | Bypass permission checks for sending signals. | | SETGID | Make arbitrary manipulations of process GIDs and supplementary GID list. | | SETUID | Make arbitrary manipulations of process UIDs. | | LINUX_IMMUTABLE | Set the FS_APPEND_FL and FS_IMMUTABLE_FL i-node flags. | | NET_BIND_SERVICE | Bind a socket to internet domain privileged ports (port numbers less than 1024). | | NET_BROADCAST | Make socket broadcasts, and listen to multicasts. | | IPC_LOCK | Lock memory (mlock(2), mlockall(2), mmap(2), shmctl(2)). | | IPC_OWNER | Bypass permission checks for operations on System V IPC objects. | | SYS_CHROOT | Use chroot(2), change root directory. | | SYS_PTRACE | Trace arbitrary processes using ptrace(2). | | SYS_BOOT | Use reboot(2) and kexec_load(2), reboot and load a new kernel for later execution. | | LEASE | Establish leases on arbitrary files (see fcntl(2)). | | SETFCAP | Set file capabilities.| | WAKE_ALARM | Trigger something that will wake up the system. | | BLOCK_SUSPEND | Employ features that can block system suspend. | Further reference information is available on the [capabilities(7) - Linux man page](http://linux.die.net/man/7/capabilities) Both flags support the value `all`, so if the operator wants to have all capabilities but `MKNOD` they could use: $ docker run --cap-add=ALL --cap-drop=MKNOD ... For interacting with the network stack, instead of using `--privileged` they should use `--cap-add=NET_ADMIN` to modify the network interfaces. $ docker run -t -i --rm ubuntu:14.04 ip link add dummy0 type dummy RTNETLINK answers: Operation not permitted $ docker run -t -i --rm --cap-add=NET_ADMIN ubuntu:14.04 ip link add dummy0 type dummy To mount a FUSE based filesystem, you need to combine both `--cap-add` and `--device`: $ docker run --rm -it --cap-add SYS_ADMIN sshfs sshfs sven@10.10.10.20:/home/sven /mnt fuse: failed to open /dev/fuse: Operation not permitted $ docker run --rm -it --device /dev/fuse sshfs sshfs sven@10.10.10.20:/home/sven /mnt fusermount: mount failed: Operation not permitted $ docker run --rm -it --cap-add SYS_ADMIN --device /dev/fuse sshfs # sshfs sven@10.10.10.20:/home/sven /mnt The authenticity of host '10.10.10.20 (10.10.10.20)' can't be established. ECDSA key fingerprint is 25:34:85:75:25:b0:17:46:05:19:04:93:b5:dd:5f:c6. Are you sure you want to continue connecting (yes/no)? yes sven@10.10.10.20's password: root@30aa0cfaf1b5:/# ls -la /mnt/src/docker total 1516 drwxrwxr-x 1 1000 1000 4096 Dec 4 06:08 . drwxrwxr-x 1 1000 1000 4096 Dec 4 11:46 .. -rw-rw-r-- 1 1000 1000 16 Oct 8 00:09 .dockerignore -rwxrwxr-x 1 1000 1000 464 Oct 8 00:09 .drone.yml drwxrwxr-x 1 1000 1000 4096 Dec 4 06:11 .git -rw-rw-r-- 1 1000 1000 461 Dec 4 06:08 .gitignore .... If the Docker daemon was started using the `lxc` exec-driver (`docker -d --exec-driver=lxc`) then the operator can also specify LXC options using one or more `--lxc-conf` parameters. These can be new parameters or override existing parameters from the [lxc-template.go]( https://github.com/docker/docker/blob/master/daemon/execdriver/lxc/lxc_template.go). Note that in the future, a given host's docker daemon may not use LXC, so this is an implementation-specific configuration meant for operators already familiar with using LXC directly. > **Note:** > If you use `--lxc-conf` to modify a container's configuration which is also > managed by the Docker daemon, then the Docker daemon will not know about this > modification, and you will need to manage any conflicts yourself. For example, > you can use `--lxc-conf` to set a container's IP address, but this will not be > reflected in the `/etc/hosts` file. # Logging drivers (--log-driver) The container can have a different logging driver than the Docker daemon. Use the `--log-driver=VALUE` with the `docker run` command to configure the container's logging driver. The following options are supported: | `none` | Disables any logging for the container. `docker logs` won't be available with this driver. | |-------------|-------------------------------------------------------------------------------------------------------------------------------| | `json-file` | Default logging driver for Docker. Writes JSON messages to file. No logging options are supported for this driver. | | `syslog` | Syslog logging driver for Docker. Writes log messages to syslog. | | `journald` | Journald logging driver for Docker. Writes log messages to `journald`. | | `gelf` | Graylog Extended Log Format (GELF) logging driver for Docker. Writes log messages to a GELF endpoint likeGraylog or Logstash. | | `fluentd` | Fluentd logging driver for Docker. Writes log messages to `fluentd` (forward input). | The `docker logs`command is available only for the `json-file` logging driver. For detailed information on working with logging drivers, see [Configure a logging driver](reference/logging/). #### Logging driver: fluentd Fluentd logging driver for Docker. Writes log messages to fluentd (forward input). `docker logs` command is not available for this logging driver. Some options are supported by specifying `--log-opt` as many as needed, like `--log-opt fluentd-address=localhost:24224 --log-opt fluentd-tag=docker.{{.Name}}`. - `fluentd-address`: specify `host:port` to connect [localhost:24224] - `fluentd-tag`: specify tag for fluentd message, which interpret some markup, ex `{{.ID}}`, `{{.FullID}}` or `{{.Name}}` [docker.{{.ID}}] ## Overriding Dockerfile image defaults When a developer builds an image from a [*Dockerfile*](/reference/builder) or when she commits it, the developer can set a number of default parameters that take effect when the image starts up as a container. Four of the Dockerfile commands cannot be overridden at runtime: `FROM`, `MAINTAINER`, `RUN`, and `ADD`. Everything else has a corresponding override in `docker run`. We'll go through what the developer might have set in each Dockerfile instruction and how the operator can override that setting. - [CMD (Default Command or Options)](#cmd-default-command-or-options) - [ENTRYPOINT (Default Command to Execute at Runtime)]( #entrypoint-default-command-to-execute-at-runtime) - [EXPOSE (Incoming Ports)](#expose-incoming-ports) - [ENV (Environment Variables)](#env-environment-variables) - [VOLUME (Shared Filesystems)](#volume-shared-filesystems) - [USER](#user) - [WORKDIR](#workdir) ## CMD (default command or options) Recall the optional `COMMAND` in the Docker commandline: $ docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG...] This command is optional because the person who created the `IMAGE` may have already provided a default `COMMAND` using the Dockerfile `CMD` instruction. As the operator (the person running a container from the image), you can override that `CMD` instruction just by specifying a new `COMMAND`. If the image also specifies an `ENTRYPOINT` then the `CMD` or `COMMAND` get appended as arguments to the `ENTRYPOINT`. ## ENTRYPOINT (default command to execute at runtime) --entrypoint="": Overwrite the default entrypoint set by the image The `ENTRYPOINT` of an image is similar to a `COMMAND` because it specifies what executable to run when the container starts, but it is (purposely) more difficult to override. The `ENTRYPOINT` gives a container its default nature or behavior, so that when you set an `ENTRYPOINT` you can run the container *as if it were that binary*, complete with default options, and you can pass in more options via the `COMMAND`. But, sometimes an operator may want to run something else inside the container, so you can override the default `ENTRYPOINT` at runtime by using a string to specify the new `ENTRYPOINT`. Here is an example of how to run a shell in a container that has been set up to automatically run something else (like `/usr/bin/redis-server`): $ docker run -i -t --entrypoint /bin/bash example/redis or two examples of how to pass more parameters to that ENTRYPOINT: $ docker run -i -t --entrypoint /bin/bash example/redis -c ls -l $ docker run -i -t --entrypoint /usr/bin/redis-cli example/redis --help ## EXPOSE (incoming ports) The Dockerfile doesn't give much control over networking, only providing the `EXPOSE` instruction to give a hint to the operator about what incoming ports might provide services. The following options work with or override the Dockerfile's exposed defaults: --expose=[]: Expose a port or a range of ports from the container without publishing it to your host -P=false : Publish all exposed ports to the host interfaces -p=[] : Publish a container᾿s port or a range of ports to the host format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort Both hostPort and containerPort can be specified as a range of ports. When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`) (use 'docker port' to see the actual mapping) --link="" : Add link to another container (:alias or ) As mentioned previously, `EXPOSE` (and `--expose`) makes ports available **in** a container for incoming connections. The port number on the inside of the container (where the service listens) does not need to be the same number as the port exposed on the outside of the container (where clients connect), so inside the container you might have an HTTP service listening on port 80 (and so you `EXPOSE 80` in the Dockerfile), but outside the container the port might be 42800. To help a new client container reach the server container's internal port operator `--expose`'d by the operator or `EXPOSE`'d by the developer, the operator has three choices: start the server container with `-P` or `-p,` or start the client container with `--link`. If the operator uses `-P` or `-p` then Docker will make the exposed port accessible on the host and the ports will be available to any client that can reach the host. When using `-P`, Docker will bind the exposed port to a random port on the host within an *ephemeral port range* defined by `/proc/sys/net/ipv4/ip_local_port_range`. To find the mapping between the host ports and the exposed ports, use `docker port`. If the operator uses `--link` when starting the new client container, then the client container can access the exposed port via a private networking interface. Docker will set some environment variables in the client container to help indicate which interface and port to use. ## ENV (environment variables) When a new container is created, Docker will set the following environment variables automatically:
Variable Value
HOME Set based on the value of USER
HOSTNAME The hostname associated with the container
PATH Includes popular directories, such as :
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
TERM xterm if the container is allocated a pseudo-TTY
The container may also include environment variables defined as a result of the container being linked with another container. See the [*Container Links*](/userguide/dockerlinks/#container-linking) section for more details. Additionally, the operator can **set any environment variable** in the container by using one or more `-e` flags, even overriding those mentioned above, or already defined by the developer with a Dockerfile `ENV`: $ docker run -e "deep=purple" --rm ubuntu /bin/bash -c export declare -x HOME="/" declare -x HOSTNAME="85bc26a0e200" declare -x OLDPWD declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" declare -x PWD="/" declare -x SHLVL="1" declare -x container="lxc" declare -x deep="purple" Similarly the operator can set the **hostname** with `-h`. `--link :alias` also sets environment variables, using the *alias* string to define environment variables within the container that give the IP and PORT information for connecting to the service container. Let's imagine we have a container running Redis: # Start the service container, named redis-name $ docker run -d --name redis-name dockerfiles/redis 4241164edf6f5aca5b0e9e4c9eccd899b0b8080c64c0cd26efe02166c73208f3 # The redis-name container exposed port 6379 $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4241164edf6f $ dockerfiles/redis:latest /redis-stable/src/re 5 seconds ago Up 4 seconds 6379/tcp redis-name # Note that there are no public ports exposed since we didn᾿t use -p or -P $ docker port 4241164edf6f 6379 2014/01/25 00:55:38 Error: No public port '6379' published for 4241164edf6f Yet we can get information about the Redis container's exposed ports with `--link`. Choose an alias that will form a valid environment variable! $ docker run --rm --link redis-name:redis_alias --entrypoint /bin/bash dockerfiles/redis -c export declare -x HOME="/" declare -x HOSTNAME="acda7f7b1cdc" declare -x OLDPWD declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" declare -x PWD="/" declare -x REDIS_ALIAS_NAME="/distracted_wright/redis" declare -x REDIS_ALIAS_PORT="tcp://172.17.0.32:6379" declare -x REDIS_ALIAS_PORT_6379_TCP="tcp://172.17.0.32:6379" declare -x REDIS_ALIAS_PORT_6379_TCP_ADDR="172.17.0.32" declare -x REDIS_ALIAS_PORT_6379_TCP_PORT="6379" declare -x REDIS_ALIAS_PORT_6379_TCP_PROTO="tcp" declare -x SHLVL="1" declare -x container="lxc" And we can use that information to connect from another container as a client: $ docker run -i -t --rm --link redis-name:redis_alias --entrypoint /bin/bash dockerfiles/redis -c '/redis-stable/src/redis-cli -h $REDIS_ALIAS_PORT_6379_TCP_ADDR -p $REDIS_ALIAS_PORT_6379_TCP_PORT' 172.17.0.32:6379> Docker will also map the private IP address to the alias of a linked container by inserting an entry into `/etc/hosts`. You can use this mechanism to communicate with a linked container by its alias: $ docker run -d --name servicename busybox sleep 30 $ docker run -i -t --link servicename:servicealias busybox ping -c 1 servicealias If you restart the source container (`servicename` in this case), the recipient container's `/etc/hosts` entry will be automatically updated. > **Note**: > Unlike host entries in the `/etc/hosts` file, IP addresses stored in the > environment variables are not automatically updated if the source container is > restarted. We recommend using the host entries in `/etc/hosts` to resolve the > IP address of linked containers. ## VOLUME (shared filesystems) -v=[]: Create a bind mount with: [host-dir:]container-dir[:rw|ro]. If 'host-dir' is missing, then docker creates a new volume. If neither 'rw' or 'ro' is specified then the volume is mounted in read-write mode. --volumes-from="": Mount all volumes from the given container(s) The volumes commands are complex enough to have their own documentation in section [*Managing data in containers*](/userguide/dockervolumes). A developer can define one or more `VOLUME`'s associated with an image, but only the operator can give access from one container to another (or from a container to a volume mounted on the host). ## USER The default user within a container is `root` (id = 0), but if the developer created additional users, those are accessible too. The developer can set a default user to run the first process with the Dockerfile `USER` instruction, but the operator can override it: -u="": Username or UID > **Note:** if you pass numeric uid, it must be in range 0-2147483647. ## WORKDIR The default working directory for running binaries within a container is the root directory (`/`), but the developer can set a different default with the Dockerfile `WORKDIR` command. The operator can override this with: -w="": Working directory inside the container ================================================ FILE: vendor/github.com/docker/docker/docs/static_files/README.md ================================================ Static files dir ================ Files you put in /static_files/ will be copied to the web visible /_static/ Be careful not to override pre-existing static files from the template. Generally, layout related files should go in the /theme directory. If you want to add images to your particular documentation page. Just put them next to your .rst source file and reference them relatively. ================================================ FILE: vendor/github.com/docker/docker/docs/terms/container.md ================================================ # Container ## Introduction ![](/terms/images/docker-filesystems-busyboxrw.png) Once you start a process in Docker from an [*Image*](/terms/image), Docker fetches the image and its [*Parent Image*](/terms/image), and repeats the process until it reaches the [*Base Image*](/terms/image/#base-image-def). Then the [*Union File System*](/terms/layer) adds a read-write layer on top. That read-write layer, plus the information about its [*Parent Image*](/terms/image) and some additional information like its unique id, networking configuration, and resource limits is called a **container**. ## Container state Containers can change, and so they have state. A container may be **running** or **exited**. When a container is running, the idea of a "container" also includes a tree of processes running on the CPU, isolated from the other processes running on the host. When the container is exited, the state of the file system and its exit value is preserved. You can start, stop, and restart a container. The processes restart from scratch (their memory state is **not** preserved in a container), but the file system is just as it was when the container was stopped. You can promote a container to an [*Image*](/terms/image) with `docker commit`. Once a container is an image, you can use it as a parent for new containers. ## Container IDs All containers are identified by a 64 hexadecimal digit string (internally a 256bit value). To simplify their use, a short ID of the first 12 characters can be used on the command line. There is a small possibility of short id collisions, so the docker server will always return the long ID. ================================================ FILE: vendor/github.com/docker/docker/docs/terms/filesystem.md ================================================ # File system ## Introduction ![](/terms/images/docker-filesystems-generic.png) In order for a Linux system to run, it typically needs two [file systems](http://en.wikipedia.org/wiki/Filesystem): 1. boot file system (bootfs) 2. root file system (rootfs) The **boot file system** contains the bootloader and the kernel. The user never makes any changes to the boot file system. In fact, soon after the boot process is complete, the entire kernel is in memory, and the boot file system is unmounted to free up the RAM associated with the initrd disk image. The **root file system** includes the typical directory structure we associate with Unix-like operating systems: `/dev, /proc, /bin, /etc, /lib, /usr,` and `/tmp` plus all the configuration files, binaries and libraries required to run user applications (like bash, ls, and so forth). While there can be important kernel differences between different Linux distributions, the contents and organization of the root file system are usually what make your software packages dependent on one distribution versus another. Docker can help solve this problem by running multiple distributions at the same time. ![](/terms/images/docker-filesystems-multiroot.png) ================================================ FILE: vendor/github.com/docker/docker/docs/terms/image.md ================================================ # Image ## Introduction ![](/terms/images/docker-filesystems-debian.png) In Docker terminology, a read-only [*Layer*](/terms/layer/#layer) is called an **image**. An image never changes. Since Docker uses a [*Union File System*](/terms/layer/#union-file-system), the processes think the whole file system is mounted read-write. But all the changes go to the top-most writeable layer, and underneath, the original file in the read-only image is unchanged. Since images don't change, images do not have state. ![](/terms/images/docker-filesystems-debianrw.png) ## Parent image ![](/terms/images/docker-filesystems-multilayer.png) Each image may depend on one more image which forms the layer beneath it. We sometimes say that the lower image is the **parent** of the upper image. ## Base image An image that has no parent is a **base image**. ## Image IDs All images are identified by a 64 hexadecimal digit string (internally a 256bit value). To simplify their use, a short ID of the first 12 characters can be used on the command line. There is a small possibility of short id collisions, so the docker server will always return the long ID. ================================================ FILE: vendor/github.com/docker/docker/docs/terms/layer.md ================================================ # Layers ## Introduction In a traditional Linux boot, the kernel first mounts the root [*File System*](/terms/filesystem) as read-only, checks its integrity, and then switches the whole rootfs volume to read-write mode. ## Layer When Docker mounts the rootfs, it starts read-only, as in a traditional Linux boot, but then, instead of changing the file system to read-write mode, it takes advantage of a [union mount](http://en.wikipedia.org/wiki/Union_mount) to add a read-write file system *over* the read-only file system. In fact there may be multiple read-only file systems stacked on top of each other. We think of each one of these file systems as a **layer**. ![](/terms/images/docker-filesystems-multilayer.png) At first, the top read-write layer has nothing in it, but any time a process creates a file, this happens in the top layer. And if something needs to update an existing file in a lower layer, then the file gets copied to the upper layer and changes go into the copy. The version of the file on the lower layer cannot be seen by the applications anymore, but it is there, unchanged. ## Union File System We call the union of the read-write layer and all the read-only layers a **union file system**. ================================================ FILE: vendor/github.com/docker/docker/docs/terms/registry.md ================================================ # Registry ## Introduction A Registry is a hosted service containing [*repositories*](/terms/repository/#repository-def) of [*images*](/terms/image/#image-def) which responds to the Registry API. The default registry can be accessed using a browser at [Docker Hub](https://hub.docker.com) or using the `docker search` command. ## Further reading For more information see [*Working with Repositories*](/userguide/dockerrepos/#working-with-the-repository) ================================================ FILE: vendor/github.com/docker/docker/docs/terms/repository.md ================================================ # Repository ## Introduction A repository is a set of images either on your local Docker server, or shared, by pushing it to a [*Registry*](/terms/registry/#registry-def) server. Images can be associated with a repository (or multiple) by giving them an image name using one of three different commands: 1. At build time (e.g., `docker build -t IMAGENAME`), 2. When committing a container (e.g., `docker commit CONTAINERID IMAGENAME`) or 3. When tagging an image id with an image name (e.g., `docker tag IMAGEID IMAGENAME`). A Fully Qualified Image Name (FQIN) can be made up of 3 parts: `[registry_hostname[:port]/][user_name/](repository_name:version_tag)` `username` and `registry_hostname` default to an empty string. When `registry_hostname` is an empty string, then `docker push` will push to `index.docker.io:80`. If you create a new repository which you want to share, you will need to set at least the `user_name`, as the `default` blank `user_name` prefix is reserved for [Official Repositories](/docker-hub/official_repos). For more information see [*Working with Repositories*](/userguide/dockerrepos/#working-with-the-repository) ================================================ FILE: vendor/github.com/docker/docker/docs/touch-up.sh ================================================ #!/bin/bash -e # Sed to process GitHub Markdown # 1-2 Remove comment code from metadata block # for i in ls -l /docs/content/* do # Line breaks are important if [ -d $i ] # Spaces are important then y=${i##*/} find $i -type f -name "*.md" -exec sed -i.old \ -e '/^/g' \ -e '/^/g' {} \; fi done ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/dockerhub.md ================================================ # Getting started with Docker Hub This section provides a quick introduction to the [Docker Hub](https://hub.docker.com), including how to create an account. The [Docker Hub](https://hub.docker.com) is a centralized resource for working with Docker and its components. Docker Hub helps you collaborate with colleagues and get the most out of Docker. To do this, it provides services such as: * Docker image hosting. * User authentication. * Automated image builds and work-flow tools such as build triggers and web hooks. * Integration with GitHub and Bitbucket. In order to use Docker Hub, you will first need to register and create an account. Don't worry, creating an account is simple and free. ## Creating a Docker Hub account There are two ways for you to register and create an account: 1. Via the web, or 2. Via the command line. ### Register via the web Fill in the [sign-up form](https://hub.docker.com/account/signup/) by choosing your user name and password and entering a valid email address. You can also sign up for the Docker Weekly mailing list, which has lots of information about what's going on in the world of Docker. ![Register using the sign-up page](/userguide/register-web.png) ### Register via the command line You can also create a Docker Hub account via the command line with the `docker login` command. $ docker login ### Confirm your email Once you've filled in the form, check your email for a welcome message asking for confirmation so we can activate your account. ### Login After you complete the confirmation process, you can login using the web console: ![Login using the web console](/userguide/login-web.png) Or via the command line with the `docker login` command: $ docker login Your Docker Hub account is now active and ready to use. ## Next steps Next, let's start learning how to Dockerize applications with our "Hello world" exercise. Go to [Dockerizing Applications](/userguide/dockerizing). ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/dockerimages.md ================================================ # Get started with images In the [introduction](/introduction/understanding-docker/) we've discovered that Docker images are the basis of containers. In the [previous](/userguide/dockerizing/) [sections](/userguide/usingdocker/) we've used Docker images that already exist, for example the `ubuntu` image and the `training/webapp` image. We've also discovered that Docker stores downloaded images on the Docker host. If an image isn't already present on the host then it'll be downloaded from a registry: by default the [Docker Hub Registry](https://registry.hub.docker.com). In this section we're going to explore Docker images a bit more including: * Managing and working with images locally on your Docker host; * Creating basic images; * Uploading images to [Docker Hub Registry](https://registry.hub.docker.com). ## Listing images on the host Let's start with listing the images we have locally on our host. You can do this using the `docker images` command like so: $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE training/webapp latest fc77f57ad303 3 weeks ago 280.5 MB ubuntu 13.10 5e019ab7bf6d 4 weeks ago 180 MB ubuntu saucy 5e019ab7bf6d 4 weeks ago 180 MB ubuntu 12.04 74fe38d11401 4 weeks ago 209.6 MB ubuntu precise 74fe38d11401 4 weeks ago 209.6 MB ubuntu 12.10 a7cf8ae4e998 4 weeks ago 171.3 MB ubuntu quantal a7cf8ae4e998 4 weeks ago 171.3 MB ubuntu 14.04 99ec81b80c55 4 weeks ago 266 MB ubuntu latest 99ec81b80c55 4 weeks ago 266 MB ubuntu trusty 99ec81b80c55 4 weeks ago 266 MB ubuntu 13.04 316b678ddf48 4 weeks ago 169.4 MB ubuntu raring 316b678ddf48 4 weeks ago 169.4 MB ubuntu 10.04 3db9c44f4520 4 weeks ago 183 MB ubuntu lucid 3db9c44f4520 4 weeks ago 183 MB We can see the images we've previously used in our [user guide](/userguide/). Each has been downloaded from [Docker Hub](https://hub.docker.com) when we launched a container using that image. We can see three crucial pieces of information about our images in the listing. * What repository they came from, for example `ubuntu`. * The tags for each image, for example `14.04`. * The image ID of each image. > **Note:** > Previously, the `docker images` command supported the `--tree` and `--dot` > arguments, which displayed different visualizations of the image data. Docker > core removed this functionality in the 1.7 version. If you liked this > functionality, you can still find it in > [the third-party dockviz tool](https://github.com/justone/dockviz). A repository potentially holds multiple variants of an image. In the case of our `ubuntu` image we can see multiple variants covering Ubuntu 10.04, 12.04, 12.10, 13.04, 13.10 and 14.04. Each variant is identified by a tag and you can refer to a tagged image like so: ubuntu:14.04 So when we run a container we refer to a tagged image like so: $ docker run -t -i ubuntu:14.04 /bin/bash If instead we wanted to run an Ubuntu 12.04 image we'd use: $ docker run -t -i ubuntu:12.04 /bin/bash If you don't specify a variant, for example you just use `ubuntu`, then Docker will default to using the `ubuntu:latest` image. > **Tip:** > We recommend you always use a specific tagged image, for example > `ubuntu:12.04`. That way you always know exactly what variant of an image is > being used. ## Getting a new image So how do we get new images? Well Docker will automatically download any image we use that isn't already present on the Docker host. But this can potentially add some time to the launch of a container. If we want to pre-load an image we can download it using the `docker pull` command. Let's say we'd like to download the `centos` image. $ docker pull centos Pulling repository centos b7de3133ff98: Pulling dependent layers 5cc9e91966f7: Pulling fs layer 511136ea3c5a: Download complete ef52fb1fe610: Download complete . . . Status: Downloaded newer image for centos We can see that each layer of the image has been pulled down and now we can run a container from this image and we won't have to wait to download the image. $ docker run -t -i centos /bin/bash bash-4.1# ## Finding images One of the features of Docker is that a lot of people have created Docker images for a variety of purposes. Many of these have been uploaded to [Docker Hub](https://hub.docker.com). We can search these images on the [Docker Hub](https://hub.docker.com) website. ![indexsearch](/userguide/search.png) We can also search for images on the command line using the `docker search` command. Let's say our team wants an image with Ruby and Sinatra installed on which to do our web application development. We can search for a suitable image by using the `docker search` command to find all the images that contain the term `sinatra`. $ docker search sinatra NAME DESCRIPTION STARS OFFICIAL AUTOMATED training/sinatra Sinatra training image 0 [OK] marceldegraaf/sinatra Sinatra test app 0 mattwarren/docker-sinatra-demo 0 [OK] luisbebop/docker-sinatra-hello-world 0 [OK] bmorearty/handson-sinatra handson-ruby + Sinatra for Hands on with D... 0 subwiz/sinatra 0 bmorearty/sinatra 0 . . . We can see we've returned a lot of images that use the term `sinatra`. We've returned a list of image names, descriptions, Stars (which measure the social popularity of images - if a user likes an image then they can "star" it), and the Official and Automated build statuses. [Official Repositories](/docker-hub/official_repos) are a carefully curated set of Docker repositories supported by Docker, Inc. Automated repositories are [Automated Builds](/userguide/dockerrepos/#automated-builds) that allow you to validate the source and content of an image. We've reviewed the images available to use and we decided to use the `training/sinatra` image. So far we've seen two types of images repositories, images like `ubuntu`, which are called base or root images. These base images are provided by Docker Inc and are built, validated and supported. These can be identified by their single word names. We've also seen user images, for example the `training/sinatra` image we've chosen. A user image belongs to a member of the Docker community and is built and maintained by them. You can identify user images as they are always prefixed with the user name, here `training`, of the user that created them. ## Pulling our image We've identified a suitable image, `training/sinatra`, and now we can download it using the `docker pull` command. $ docker pull training/sinatra The team can now use this image by running their own containers. $ docker run -t -i training/sinatra /bin/bash root@a8cb6ce02d85:/# ## Creating our own images The team has found the `training/sinatra` image pretty useful but it's not quite what they need and we need to make some changes to it. There are two ways we can update and create images. 1. We can update a container created from an image and commit the results to an image. 2. We can use a `Dockerfile` to specify instructions to create an image. ### Updating and committing an image To update an image we first need to create a container from the image we'd like to update. $ docker run -t -i training/sinatra /bin/bash root@0b2616b0e5a8:/# > **Note:** > Take note of the container ID that has been created, `0b2616b0e5a8`, as we'll > need it in a moment. Inside our running container let's add the `json` gem. root@0b2616b0e5a8:/# gem install json Once this has completed let's exit our container using the `exit` command. Now we have a container with the change we want to make. We can then commit a copy of this container to an image using the `docker commit` command. $ docker commit -m "Added json gem" -a "Kate Smith" \ 0b2616b0e5a8 ouruser/sinatra:v2 4f177bd27a9ff0f6dc2a830403925b5360bfe0b93d476f7fc3231110e7f71b1c Here we've used the `docker commit` command. We've specified two flags: `-m` and `-a`. The `-m` flag allows us to specify a commit message, much like you would with a commit on a version control system. The `-a` flag allows us to specify an author for our update. We've also specified the container we want to create this new image from, `0b2616b0e5a8` (the ID we recorded earlier) and we've specified a target for the image: ouruser/sinatra:v2 Let's break this target down. It consists of a new user, `ouruser`, that we're writing this image to. We've also specified the name of the image, here we're keeping the original image name `sinatra`. Finally we're specifying a tag for the image: `v2`. We can then look at our new `ouruser/sinatra` image using the `docker images` command. $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE training/sinatra latest 5bc342fa0b91 10 hours ago 446.7 MB ouruser/sinatra v2 3c59e02ddd1a 10 hours ago 446.7 MB ouruser/sinatra latest 5db5f8471261 10 hours ago 446.7 MB To use our new image to create a container we can then: $ docker run -t -i ouruser/sinatra:v2 /bin/bash root@78e82f680994:/# ### Building an image from a `Dockerfile` Using the `docker commit` command is a pretty simple way of extending an image but it's a bit cumbersome and it's not easy to share a development process for images amongst a team. Instead we can use a new command, `docker build`, to build new images from scratch. To do this we create a `Dockerfile` that contains a set of instructions that tell Docker how to build our image. Let's create a directory and a `Dockerfile` first. $ mkdir sinatra $ cd sinatra $ touch Dockerfile If you are using Boot2Docker on Windows, you may access your host directory by `cd` to `/c/Users/your_user_name`. Each instruction creates a new layer of the image. Let's look at a simple example now for building our own Sinatra image for our development team. # This is a comment FROM ubuntu:14.04 MAINTAINER Kate Smith RUN apt-get update && apt-get install -y ruby ruby-dev RUN gem install sinatra Let's look at what our `Dockerfile` does. Each instruction prefixes a statement and is capitalized. INSTRUCTION statement > **Note:** > We use `#` to indicate a comment The first instruction `FROM` tells Docker what the source of our image is, in this case we're basing our new image on an Ubuntu 14.04 image. Next we use the `MAINTAINER` instruction to specify who maintains our new image. Lastly, we've specified two `RUN` instructions. A `RUN` instruction executes a command inside the image, for example installing a package. Here we're updating our APT cache, installing Ruby and RubyGems and then installing the Sinatra gem. > **Note:** > There are [a lot more instructions available to us in a Dockerfile](/reference/builder). Now let's take our `Dockerfile` and use the `docker build` command to build an image. $ docker build -t ouruser/sinatra:v2 . Sending build context to Docker daemon 2.048 kB Sending build context to Docker daemon Step 0 : FROM ubuntu:14.04 ---> e54ca5efa2e9 Step 1 : MAINTAINER Kate Smith ---> Using cache ---> 851baf55332b Step 2 : RUN apt-get update && apt-get install -y ruby ruby-dev ---> Running in 3a2558904e9b Selecting previously unselected package libasan0:amd64. (Reading database ... 11518 files and directories currently installed.) Preparing to unpack .../libasan0_4.8.2-19ubuntu1_amd64.deb ... Unpacking libasan0:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package libatomic1:amd64. Preparing to unpack .../libatomic1_4.8.2-19ubuntu1_amd64.deb ... Unpacking libatomic1:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package libgmp10:amd64. Preparing to unpack .../libgmp10_2%3a5.1.3+dfsg-1ubuntu1_amd64.deb ... Unpacking libgmp10:amd64 (2:5.1.3+dfsg-1ubuntu1) ... Selecting previously unselected package libisl10:amd64. Preparing to unpack .../libisl10_0.12.2-1_amd64.deb ... Unpacking libisl10:amd64 (0.12.2-1) ... Selecting previously unselected package libcloog-isl4:amd64. Preparing to unpack .../libcloog-isl4_0.18.2-1_amd64.deb ... Unpacking libcloog-isl4:amd64 (0.18.2-1) ... Selecting previously unselected package libgomp1:amd64. Preparing to unpack .../libgomp1_4.8.2-19ubuntu1_amd64.deb ... Unpacking libgomp1:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package libitm1:amd64. Preparing to unpack .../libitm1_4.8.2-19ubuntu1_amd64.deb ... Unpacking libitm1:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package libmpfr4:amd64. Preparing to unpack .../libmpfr4_3.1.2-1_amd64.deb ... Unpacking libmpfr4:amd64 (3.1.2-1) ... Selecting previously unselected package libquadmath0:amd64. Preparing to unpack .../libquadmath0_4.8.2-19ubuntu1_amd64.deb ... Unpacking libquadmath0:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package libtsan0:amd64. Preparing to unpack .../libtsan0_4.8.2-19ubuntu1_amd64.deb ... Unpacking libtsan0:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package libyaml-0-2:amd64. Preparing to unpack .../libyaml-0-2_0.1.4-3ubuntu3_amd64.deb ... Unpacking libyaml-0-2:amd64 (0.1.4-3ubuntu3) ... Selecting previously unselected package libmpc3:amd64. Preparing to unpack .../libmpc3_1.0.1-1ubuntu1_amd64.deb ... Unpacking libmpc3:amd64 (1.0.1-1ubuntu1) ... Selecting previously unselected package openssl. Preparing to unpack .../openssl_1.0.1f-1ubuntu2.4_amd64.deb ... Unpacking openssl (1.0.1f-1ubuntu2.4) ... Selecting previously unselected package ca-certificates. Preparing to unpack .../ca-certificates_20130906ubuntu2_all.deb ... Unpacking ca-certificates (20130906ubuntu2) ... Selecting previously unselected package manpages. Preparing to unpack .../manpages_3.54-1ubuntu1_all.deb ... Unpacking manpages (3.54-1ubuntu1) ... Selecting previously unselected package binutils. Preparing to unpack .../binutils_2.24-5ubuntu3_amd64.deb ... Unpacking binutils (2.24-5ubuntu3) ... Selecting previously unselected package cpp-4.8. Preparing to unpack .../cpp-4.8_4.8.2-19ubuntu1_amd64.deb ... Unpacking cpp-4.8 (4.8.2-19ubuntu1) ... Selecting previously unselected package cpp. Preparing to unpack .../cpp_4%3a4.8.2-1ubuntu6_amd64.deb ... Unpacking cpp (4:4.8.2-1ubuntu6) ... Selecting previously unselected package libgcc-4.8-dev:amd64. Preparing to unpack .../libgcc-4.8-dev_4.8.2-19ubuntu1_amd64.deb ... Unpacking libgcc-4.8-dev:amd64 (4.8.2-19ubuntu1) ... Selecting previously unselected package gcc-4.8. Preparing to unpack .../gcc-4.8_4.8.2-19ubuntu1_amd64.deb ... Unpacking gcc-4.8 (4.8.2-19ubuntu1) ... Selecting previously unselected package gcc. Preparing to unpack .../gcc_4%3a4.8.2-1ubuntu6_amd64.deb ... Unpacking gcc (4:4.8.2-1ubuntu6) ... Selecting previously unselected package libc-dev-bin. Preparing to unpack .../libc-dev-bin_2.19-0ubuntu6_amd64.deb ... Unpacking libc-dev-bin (2.19-0ubuntu6) ... Selecting previously unselected package linux-libc-dev:amd64. Preparing to unpack .../linux-libc-dev_3.13.0-30.55_amd64.deb ... Unpacking linux-libc-dev:amd64 (3.13.0-30.55) ... Selecting previously unselected package libc6-dev:amd64. Preparing to unpack .../libc6-dev_2.19-0ubuntu6_amd64.deb ... Unpacking libc6-dev:amd64 (2.19-0ubuntu6) ... Selecting previously unselected package ruby. Preparing to unpack .../ruby_1%3a1.9.3.4_all.deb ... Unpacking ruby (1:1.9.3.4) ... Selecting previously unselected package ruby1.9.1. Preparing to unpack .../ruby1.9.1_1.9.3.484-2ubuntu1_amd64.deb ... Unpacking ruby1.9.1 (1.9.3.484-2ubuntu1) ... Selecting previously unselected package libruby1.9.1. Preparing to unpack .../libruby1.9.1_1.9.3.484-2ubuntu1_amd64.deb ... Unpacking libruby1.9.1 (1.9.3.484-2ubuntu1) ... Selecting previously unselected package manpages-dev. Preparing to unpack .../manpages-dev_3.54-1ubuntu1_all.deb ... Unpacking manpages-dev (3.54-1ubuntu1) ... Selecting previously unselected package ruby1.9.1-dev. Preparing to unpack .../ruby1.9.1-dev_1.9.3.484-2ubuntu1_amd64.deb ... Unpacking ruby1.9.1-dev (1.9.3.484-2ubuntu1) ... Selecting previously unselected package ruby-dev. Preparing to unpack .../ruby-dev_1%3a1.9.3.4_all.deb ... Unpacking ruby-dev (1:1.9.3.4) ... Setting up libasan0:amd64 (4.8.2-19ubuntu1) ... Setting up libatomic1:amd64 (4.8.2-19ubuntu1) ... Setting up libgmp10:amd64 (2:5.1.3+dfsg-1ubuntu1) ... Setting up libisl10:amd64 (0.12.2-1) ... Setting up libcloog-isl4:amd64 (0.18.2-1) ... Setting up libgomp1:amd64 (4.8.2-19ubuntu1) ... Setting up libitm1:amd64 (4.8.2-19ubuntu1) ... Setting up libmpfr4:amd64 (3.1.2-1) ... Setting up libquadmath0:amd64 (4.8.2-19ubuntu1) ... Setting up libtsan0:amd64 (4.8.2-19ubuntu1) ... Setting up libyaml-0-2:amd64 (0.1.4-3ubuntu3) ... Setting up libmpc3:amd64 (1.0.1-1ubuntu1) ... Setting up openssl (1.0.1f-1ubuntu2.4) ... Setting up ca-certificates (20130906ubuntu2) ... debconf: unable to initialize frontend: Dialog debconf: (TERM is not set, so the dialog frontend is not usable.) debconf: falling back to frontend: Readline debconf: unable to initialize frontend: Readline debconf: (This frontend requires a controlling tty.) debconf: falling back to frontend: Teletype Setting up manpages (3.54-1ubuntu1) ... Setting up binutils (2.24-5ubuntu3) ... Setting up cpp-4.8 (4.8.2-19ubuntu1) ... Setting up cpp (4:4.8.2-1ubuntu6) ... Setting up libgcc-4.8-dev:amd64 (4.8.2-19ubuntu1) ... Setting up gcc-4.8 (4.8.2-19ubuntu1) ... Setting up gcc (4:4.8.2-1ubuntu6) ... Setting up libc-dev-bin (2.19-0ubuntu6) ... Setting up linux-libc-dev:amd64 (3.13.0-30.55) ... Setting up libc6-dev:amd64 (2.19-0ubuntu6) ... Setting up manpages-dev (3.54-1ubuntu1) ... Setting up libruby1.9.1 (1.9.3.484-2ubuntu1) ... Setting up ruby1.9.1-dev (1.9.3.484-2ubuntu1) ... Setting up ruby-dev (1:1.9.3.4) ... Setting up ruby (1:1.9.3.4) ... Setting up ruby1.9.1 (1.9.3.484-2ubuntu1) ... Processing triggers for libc-bin (2.19-0ubuntu6) ... Processing triggers for ca-certificates (20130906ubuntu2) ... Updating certificates in /etc/ssl/certs... 164 added, 0 removed; done. Running hooks in /etc/ca-certificates/update.d....done. ---> c55c31703134 Removing intermediate container 3a2558904e9b Step 3 : RUN gem install sinatra ---> Running in 6b81cb6313e5 unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for README.rdoc, skipping unable to convert "\xC3" to UTF-8 in conversion from ASCII-8BIT to UTF-8 to US-ASCII for README.rdoc, skipping Successfully installed rack-1.5.2 Successfully installed tilt-1.4.1 Successfully installed rack-protection-1.5.3 Successfully installed sinatra-1.4.5 4 gems installed Installing ri documentation for rack-1.5.2... Installing ri documentation for tilt-1.4.1... Installing ri documentation for rack-protection-1.5.3... Installing ri documentation for sinatra-1.4.5... Installing RDoc documentation for rack-1.5.2... Installing RDoc documentation for tilt-1.4.1... Installing RDoc documentation for rack-protection-1.5.3... Installing RDoc documentation for sinatra-1.4.5... ---> 97feabe5d2ed Removing intermediate container 6b81cb6313e5 Successfully built 97feabe5d2ed We've specified our `docker build` command and used the `-t` flag to identify our new image as belonging to the user `ouruser`, the repository name `sinatra` and given it the tag `v2`. We've also specified the location of our `Dockerfile` using the `.` to indicate a `Dockerfile` in the current directory. > **Note:** > You can also specify a path to a `Dockerfile`. Now we can see the build process at work. The first thing Docker does is upload the build context: basically the contents of the directory you're building in. This is done because the Docker daemon does the actual build of the image and it needs the local context to do it. Next we can see each instruction in the `Dockerfile` being executed step-by-step. We can see that each step creates a new container, runs the instruction inside that container and then commits that change - just like the `docker commit` work flow we saw earlier. When all the instructions have executed we're left with the `97feabe5d2ed` image (also helpfully tagged as `ouruser/sinatra:v2`) and all intermediate containers will get removed to clean things up. > **Note:** > An image can't have more than 127 layers regardless of the storage driver. > This limitation is set globally to encourage optimization of the overall > size of images. We can then create a container from our new image. $ docker run -t -i ouruser/sinatra:v2 /bin/bash root@8196968dac35:/# > **Note:** > This is just a brief introduction to creating images. We've > skipped a whole bunch of other instructions that you can use. We'll see more of > those instructions in later sections of the Guide or you can refer to the > [`Dockerfile`](/reference/builder/) reference for a > detailed description and examples of every instruction. > To help you write a clear, readable, maintainable `Dockerfile`, we've also > written a [`Dockerfile` Best Practices guide](/articles/dockerfile_best-practices). ### More To learn more, check out the [Dockerfile tutorial](/userguide/level1). ## Setting tags on an image You can also add a tag to an existing image after you commit or build it. We can do this using the `docker tag` command. Let's add a new tag to our `ouruser/sinatra` image. $ docker tag 5db5f8471261 ouruser/sinatra:devel The `docker tag` command takes the ID of the image, here `5db5f8471261`, and our user name, the repository name and the new tag. Let's see our new tag using the `docker images` command. $ docker images ouruser/sinatra REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE ouruser/sinatra latest 5db5f8471261 11 hours ago 446.7 MB ouruser/sinatra devel 5db5f8471261 11 hours ago 446.7 MB ouruser/sinatra v2 5db5f8471261 11 hours ago 446.7 MB ## Image Digests Images that use the v2 or later format have a content-addressable identifier called a `digest`. As long as the input used to generate the image is unchanged, the digest value is predictable. To list image digest values, use the `--digests` flag: $ docker images --digests | head REPOSITORY TAG DIGEST IMAGE ID CREATED VIRTUAL SIZE ouruser/sinatra latest sha256:cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf 5db5f8471261 11 hours ago 446.7 MB When pushing or pulling to a 2.0 registry, the `push` or `pull` command output includes the image digest. You can `pull` using a digest value. $ docker pull ouruser/sinatra@cbbf2f9a99b47fc460d422812b6a5adff7dfee951d8fa2e4a98caa0382cfbdbf You can also reference by digest in `create`, `run`, and `rmi` commands, as well as the `FROM` image reference in a Dockerfile. ## Push an image to Docker Hub Once you've built or created a new image you can push it to [Docker Hub](https://hub.docker.com) using the `docker push` command. This allows you to share it with others, either publicly, or push it into [a private repository](https://registry.hub.docker.com/plans/). $ docker push ouruser/sinatra The push refers to a repository [ouruser/sinatra] (len: 1) Sending image list Pushing repository ouruser/sinatra (3 tags) . . . ## Remove an image from the host You can also remove images on your Docker host in a way [similar to containers]( /userguide/usingdocker) using the `docker rmi` command. Let's delete the `training/sinatra` image as we don't need it anymore. $ docker rmi training/sinatra Untagged: training/sinatra:latest Deleted: 5bc342fa0b91cabf65246837015197eecfa24b2213ed6a51a8974ae250fedd8d Deleted: ed0fffdcdae5eb2c3a55549857a8be7fc8bc4241fb19ad714364cbfd7a56b22f Deleted: 5c58979d73ae448df5af1d8142436d81116187a7633082650549c52c3a2418f0 > **Note:** In order to remove an image from the host, please make sure > that there are no containers actively based on it. # Next steps Until now we've seen how to build individual applications inside Docker containers. Now learn how to build whole application stacks with Docker by linking together multiple Docker containers. Test your Dockerfile knowledge with the [Dockerfile tutorial](/userguide/level1). Go to [Linking Containers Together](/userguide/dockerlinks). ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/dockerizing.md ================================================ # Dockerizing applications: A "Hello world" *So what's this Docker thing all about?* Docker allows you to run applications inside containers. Running an application inside a container takes a single command: `docker run`. > **Note:** if you are using a remote Docker daemon, such as Boot2Docker, > then _do not_ type the `sudo` before the `docker` commands shown in the > documentation's examples. ## Hello world Let's try it now. $ docker run ubuntu:14.04 /bin/echo 'Hello world' Hello world And you just launched your first container! So what just happened? Let's step through what the `docker run` command did. First we specified the `docker` binary and the command we wanted to execute, `run`. The `docker run` combination *runs* containers. Next we specified an image: `ubuntu:14.04`. This is the source of the container we ran. Docker calls this an image. In this case we used an Ubuntu 14.04 operating system image. When you specify an image, Docker looks first for the image on your Docker host. If it can't find it then it downloads the image from the public image registry: [Docker Hub](https://hub.docker.com). Next we told Docker what command to run inside our new container: /bin/echo 'Hello world' When our container was launched Docker created a new Ubuntu 14.04 environment and then executed the `/bin/echo` command inside it. We saw the result on the command line: Hello world So what happened to our container after that? Well Docker containers only run as long as the command you specify is active. Here, as soon as `Hello world` was echoed, the container stopped. ## An interactive container Let's try the `docker run` command again, this time specifying a new command to run in our container. $ docker run -t -i ubuntu:14.04 /bin/bash root@af8bae53bdd3:/# Here we've again specified the `docker run` command and launched an `ubuntu:14.04` image. But we've also passed in two flags: `-t` and `-i`. The `-t` flag assigns a pseudo-tty or terminal inside our new container and the `-i` flag allows us to make an interactive connection by grabbing the standard in (`STDIN`) of the container. We've also specified a new command for our container to run: `/bin/bash`. This will launch a Bash shell inside our container. So now when our container is launched we can see that we've got a command prompt inside it: root@af8bae53bdd3:/# Let's try running some commands inside our container: root@af8bae53bdd3:/# pwd / root@af8bae53bdd3:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var You can see we've run the `pwd` to show our current directory and can see we're in the `/` root directory. We've also done a directory listing of the root directory which shows us what looks like a typical Linux file system. You can play around inside this container and when you're done you can use the `exit` command or enter Ctrl-D to finish. root@af8bae53bdd3:/# exit As with our previous container, once the Bash shell process has finished, the container is stopped. ## A daemonized Hello world Now a container that runs a command and then exits has some uses but it's not overly helpful. Let's create a container that runs as a daemon, like most of the applications we're probably going to run with Docker. Again we can do this with the `docker run` command: $ docker run -d ubuntu:14.04 /bin/sh -c "while true; do echo hello world; sleep 1; done" 1e5535038e285177d5214659a068137486f96ee5c2e85a4ac52dc83f2ebe4147 Wait, what? Where's our "hello world" output? Let's look at what we've run here. It should look pretty familiar. We ran `docker run` but this time we specified a flag: `-d`. The `-d` flag tells Docker to run the container and put it in the background, to daemonize it. We also specified the same image: `ubuntu:14.04`. Finally, we specified a command to run: /bin/sh -c "while true; do echo hello world; sleep 1; done" This is the (hello) world's silliest daemon: a shell script that echoes `hello world` forever. So why aren't we seeing any `hello world`'s? Instead Docker has returned a really long string: 1e5535038e285177d5214659a068137486f96ee5c2e85a4ac52dc83f2ebe4147 This really long string is called a *container ID*. It uniquely identifies a container so we can work with it. > **Note:** > The container ID is a bit long and unwieldy and a bit later > on we'll see a shorter ID and some ways to name our containers to make > working with them easier. We can use this container ID to see what's happening with our `hello world` daemon. Firstly let's make sure our container is running. We can do that with the `docker ps` command. The `docker ps` command queries the Docker daemon for information about all the containers it knows about. $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1e5535038e28 ubuntu:14.04 /bin/sh -c 'while tr 2 minutes ago Up 1 minute insane_babbage Here we can see our daemonized container. The `docker ps` has returned some useful information about it, starting with a shorter variant of its container ID: `1e5535038e28`. We can also see the image we used to build it, `ubuntu:14.04`, the command it is running, its status and an automatically assigned name, `insane_babbage`. > **Note:** > Docker automatically names any containers you start, a > little later on we'll see how you can specify your own names. Okay, so we now know it's running. But is it doing what we asked it to do? To see this we're going to look inside the container using the `docker logs` command. Let's use the container name Docker assigned. $ docker logs insane_babbage hello world hello world hello world . . . The `docker logs` command looks inside the container and returns its standard output: in this case the output of our command `hello world`. Awesome! Our daemon is working and we've just created our first Dockerized application! Now we've established we can create our own containers let's tidy up after ourselves and stop our daemonized container. To do this we use the `docker stop` command. $ docker stop insane_babbage insane_babbage The `docker stop` command tells Docker to politely stop the running container. If it succeeds it will return the name of the container it has just stopped. Let's check it worked with the `docker ps` command. $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES Excellent. Our container has been stopped. # Next steps Now we've seen how simple it is to get started with Docker. Let's learn how to do some more advanced tasks. Go to [Working With Containers](/userguide/usingdocker). ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/dockerlinks.md ================================================ # Linking containers together In [the Using Docker section](/userguide/usingdocker), you saw how you can connect to a service running inside a Docker container via a network port. But a port connection is only one way you can interact with services and applications running inside Docker containers. In this section, we'll briefly revisit connecting via a network port and then we'll introduce you to another method of access: container linking. ## Connect using network port mapping In [the Using Docker section](/userguide/usingdocker), you created a container that ran a Python Flask application: $ docker run -d -P training/webapp python app.py > **Note:** > Containers have an internal network and an IP address > (as we saw when we used the `docker inspect` command to show the container's > IP address in the [Using Docker](/userguide/usingdocker/) section). > Docker can have a variety of network configurations. You can see more > information on Docker networking [here](/articles/networking/). When that container was created, the `-P` flag was used to automatically map any network port inside it to a random high port within an *ephemeral port range* on your Docker host. Next, when `docker ps` was run, you saw that port 5000 in the container was bound to port 49155 on the host. $ docker ps nostalgic_morse CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES bc533791f3f5 training/webapp:latest python app.py 5 seconds ago Up 2 seconds 0.0.0.0:49155->5000/tcp nostalgic_morse You also saw how you can bind a container's ports to a specific port using the `-p` flag. Here port 80 of the host is mapped to port 5000 of the container: $ docker run -d -p 80:5000 training/webapp python app.py And you saw why this isn't such a great idea because it constrains you to only one container on that specific port. There are also a few other ways you can configure the `-p` flag. By default the `-p` flag will bind the specified port to all interfaces on the host machine. But you can also specify a binding to a specific interface, for example only to the `localhost`. $ docker run -d -p 127.0.0.1:80:5000 training/webapp python app.py This would bind port 5000 inside the container to port 80 on the `localhost` or `127.0.0.1` interface on the host machine. Or, to bind port 5000 of the container to a dynamic port but only on the `localhost`, you could use: $ docker run -d -p 127.0.0.1::5000 training/webapp python app.py You can also bind UDP ports by adding a trailing `/udp`. For example: $ docker run -d -p 127.0.0.1:80:5000/udp training/webapp python app.py You also learned about the useful `docker port` shortcut which showed us the current port bindings. This is also useful for showing you specific port configurations. For example, if you've bound the container port to the `localhost` on the host machine, then the `docker port` output will reflect that. $ docker port nostalgic_morse 5000 127.0.0.1:49155 > **Note:** > The `-p` flag can be used multiple times to configure multiple ports. ## Connect with the linking system Network port mappings are not the only way Docker containers can connect to one another. Docker also has a linking system that allows you to link multiple containers together and send connection information from one to another. When containers are linked, information about a source container can be sent to a recipient container. This allows the recipient to see selected data describing aspects of the source container. ### The importance of naming To establish links, Docker relies on the names of your containers. You've already seen that each container you create has an automatically created name; indeed you've become familiar with our old friend `nostalgic_morse` during this guide. You can also name containers yourself. This naming provides two useful functions: 1. It can be useful to name containers that do specific functions in a way that makes it easier for you to remember them, for example naming a container containing a web application `web`. 2. It provides Docker with a reference point that allows it to refer to other containers, for example, you can specify to link the container `web` to container `db`. You can name your container by using the `--name` flag, for example: $ docker run -d -P --name web training/webapp python app.py This launches a new container and uses the `--name` flag to name the container `web`. You can see the container's name using the `docker ps` command. $ docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aed84ee21bde training/webapp:latest python app.py 12 hours ago Up 2 seconds 0.0.0.0:49154->5000/tcp web You can also use `docker inspect` to return the container's name. > **Note:** > Container names have to be unique. That means you can only call > one container `web`. If you want to re-use a container name you must delete > the old container (with `docker rm`) before you can create a new > container with the same name. As an alternative you can use the `--rm` > flag with the `docker run` command. This will delete the container > immediately after it is stopped. ## Communication across links Links allow containers to discover each other and securely transfer information about one container to another container. When you set up a link, you create a conduit between a source container and a recipient container. The recipient can then access select data about the source. To create a link, you use the `--link` flag. First, create a new container, this time one containing a database. $ docker run -d --name db training/postgres This creates a new container called `db` from the `training/postgres` image, which contains a PostgreSQL database. Now, you need to delete the `web` container you created previously so you can replace it with a linked one: $ docker rm -f web Now, create a new `web` container and link it with your `db` container. $ docker run -d -P --name web --link db:db training/webapp python app.py This will link the new `web` container with the `db` container you created earlier. The `--link` flag takes the form: --link :alias Where `name` is the name of the container we're linking to and `alias` is an alias for the link name. You'll see how that alias gets used shortly. The `--link` flag also takes the form: --link In which case the alias will match the name. You could have written the previous example as: $ docker run -d -P --name web --link db training/webapp python app.py Next, inspect your linked containers with `docker inspect`: $ docker inspect -f "{{ .HostConfig.Links }}" web [/db:/web/db] You can see that the `web` container is now linked to the `db` container `web/db`. Which allows it to access information about the `db` container. So what does linking the containers actually do? You've learned that a link allows a source container to provide information about itself to a recipient container. In our example, the recipient, `web`, can access information about the source `db`. To do this, Docker creates a secure tunnel between the containers that doesn't need to expose any ports externally on the container; you'll note when we started the `db` container we did not use either the `-P` or `-p` flags. That's a big benefit of linking: we don't need to expose the source container, here the PostgreSQL database, to the network. Docker exposes connectivity information for the source container to the recipient container in two ways: * Environment variables, * Updating the `/etc/hosts` file. ### Environment variables Docker creates several environment variables when you link containers. Docker automatically creates environment variables in the target container based on the `--link` parameters. It will also expose all environment variables originating from Docker from the source container. These include variables from: * the `ENV` commands in the source container's Dockerfile * the `-e`, `--env` and `--env-file` options on the `docker run` command when the source container is started These environment variables enable programmatic discovery from within the target container of information related to the source container. > **Warning**: > It is important to understand that *all* environment variables originating > from Docker within a container are made available to *any* container > that links to it. This could have serious security implications if sensitive > data is stored in them. Docker sets an `_NAME` environment variable for each target container listed in the `--link` parameter. For example, if a new container called `web` is linked to a database container called `db` via `--link db:webdb`, then Docker creates a `WEBDB_NAME=/web/webdb` variable in the `web` container. Docker also defines a set of environment variables for each port exposed by the source container. Each variable has a unique prefix in the form: `_PORT__` The components in this prefix are: * the alias `` specified in the `--link` parameter (for example, `webdb`) * the `` number exposed * a `` which is either TCP or UDP Docker uses this prefix format to define three distinct environment variables: * The `prefix_ADDR` variable contains the IP Address from the URL, for example `WEBDB_PORT_8080_TCP_ADDR=172.17.0.82`. * The `prefix_PORT` variable contains just the port number from the URL for example `WEBDB_PORT_8080_TCP_PORT=8080`. * The `prefix_PROTO` variable contains just the protocol from the URL for example `WEBDB_PORT_8080_TCP_PROTO=tcp`. If the container exposes multiple ports, an environment variable set is defined for each one. This means, for example, if a container exposes 4 ports that Docker creates 12 environment variables, 3 for each port. Additionally, Docker creates an environment variable called `_PORT`. This variable contains the URL of the source container's first exposed port. The 'first' port is defined as the exposed port with the lowest number. For example, consider the `WEBDB_PORT=tcp://172.17.0.82:8080` variable. If that port is used for both tcp and udp, then the tcp one is specified. Finally, Docker also exposes each Docker originated environment variable from the source container as an environment variable in the target. For each variable Docker creates an `_ENV_` variable in the target container. The variable's value is set to the value Docker used when it started the source container. Returning back to our database example, you can run the `env` command to list the specified container's environment variables. ``` $ docker run --rm --name web2 --link db:db training/webapp env . . . DB_NAME=/web2/db DB_PORT=tcp://172.17.0.5:5432 DB_PORT_5432_TCP=tcp://172.17.0.5:5432 DB_PORT_5432_TCP_PROTO=tcp DB_PORT_5432_TCP_PORT=5432 DB_PORT_5432_TCP_ADDR=172.17.0.5 . . . ``` You can see that Docker has created a series of environment variables with useful information about the source `db` container. Each variable is prefixed with `DB_`, which is populated from the `alias` you specified above. If the `alias` were `db1`, the variables would be prefixed with `DB1_`. You can use these environment variables to configure your applications to connect to the database on the `db` container. The connection will be secure and private; only the linked `web` container will be able to talk to the `db` container. ### Important notes on Docker environment variables Unlike host entries in the [`/etc/hosts` file](#updating-the-etchosts-file), IP addresses stored in the environment variables are not automatically updated if the source container is restarted. We recommend using the host entries in `/etc/hosts` to resolve the IP address of linked containers. These environment variables are only set for the first process in the container. Some daemons, such as `sshd`, will scrub them when spawning shells for connection. ### Updating the `/etc/hosts` file In addition to the environment variables, Docker adds a host entry for the source container to the `/etc/hosts` file. Here's an entry for the `web` container: $ docker run -t -i --rm --link db:webdb training/webapp /bin/bash root@aed84ee21bde:/opt/webapp# cat /etc/hosts 172.17.0.7 aed84ee21bde . . . 172.17.0.5 webdb 6e5cdeb2d300 db You can see two relevant host entries. The first is an entry for the `web` container that uses the Container ID as a host name. The second entry uses the link alias to reference the IP address of the `db` container. In addition to the alias you provide, the linked container's name--if unique from the alias provided to the `--link` parameter--and the linked container's hostname will also be added in `/etc/hosts` for the linked container's IP address. You can ping that host now via any of these entries: root@aed84ee21bde:/opt/webapp# apt-get install -yqq inetutils-ping root@aed84ee21bde:/opt/webapp# ping webdb PING webdb (172.17.0.5): 48 data bytes 56 bytes from 172.17.0.5: icmp_seq=0 ttl=64 time=0.267 ms 56 bytes from 172.17.0.5: icmp_seq=1 ttl=64 time=0.250 ms 56 bytes from 172.17.0.5: icmp_seq=2 ttl=64 time=0.256 ms > **Note:** > In the example, you'll note you had to install `ping` because it was not included > in the container initially. Here, you used the `ping` command to ping the `db` container using its host entry, which resolves to `172.17.0.5`. You can use this host entry to configure an application to make use of your `db` container. > **Note:** > You can link multiple recipient containers to a single source. For > example, you could have multiple (differently named) web containers attached to your >`db` container. If you restart the source container, the linked containers `/etc/hosts` files will be automatically updated with the source container's new IP address, allowing linked communication to continue. $ docker restart db db $ docker run -t -i --rm --link db:db training/webapp /bin/bash root@aed84ee21bde:/opt/webapp# cat /etc/hosts 172.17.0.7 aed84ee21bde . . . 172.17.0.9 db # Next step Now that you know how to link Docker containers together, the next step is learning how to manage data, volumes and mounts inside your containers. Go to [Managing Data in Containers](/userguide/dockervolumes). ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/dockerrepos.md ================================================ # Get started with Docker Hub So far you've learned how to use the command line to run Docker on your local host. You've learned how to [pull down images](/userguide/usingdocker/) to build containers from existing images and you've learned how to [create your own images](/userguide/dockerimages). Next, you're going to learn how to use the [Docker Hub](https://hub.docker.com) to simplify and enhance your Docker workflows. The [Docker Hub](https://hub.docker.com) is a public registry maintained by Docker, Inc. It contains over 15,000 images you can download and use to build containers. It also provides authentication, work group structure, workflow tools like webhooks and build triggers, and privacy tools like private repositories for storing images you don't want to share publicly. ## Docker commands and Docker Hub Docker itself provides access to Docker Hub services via the `docker search`, `pull`, `login`, and `push` commands. This page will show you how these commands work. ### Account creation and login Typically, you'll want to start by creating an account on Docker Hub (if you haven't already) and logging in. You can create your account directly on [Docker Hub](https://hub.docker.com/account/signup/), or by running: $ docker login This will prompt you for a user name, which will become the public namespace for your public repositories. If your user name is available, Docker will prompt you to enter a password and your e-mail address. It will then automatically log you in. You can now commit and push your own images up to your repos on Docker Hub. > **Note:** > Your authentication credentials will be stored in the `~/.docker/config.json` > authentication file in your home directory. ## Searching for images You can search the [Docker Hub](https://hub.docker.com) registry via its search interface or by using the command line interface. Searching can find images by image name, user name, or description: $ docker search centos NAME DESCRIPTION STARS OFFICIAL TRUSTED centos Official CentOS 6 Image as of 12 April 2014 88 tianon/centos CentOS 5 and 6, created using rinse instea... 21 ... There you can see two example results: `centos` and `tianon/centos`. The second result shows that it comes from the public repository of a user, named `tianon/`, while the first result, `centos`, doesn't explicitly list a repository which means that it comes from the trusted top-level namespace for [Official Repositories](/docker-hub/official_repos). The `/` character separates a user's repository from the image name. Once you've found the image you want, you can download it with `docker pull `: $ docker pull centos Pulling repository centos 0b443ba03958: Download complete 539c0211cd76: Download complete 511136ea3c5a: Download complete 7064731afe90: Download complete Status: Downloaded newer image for centos You now have an image from which you can run containers. ## Contributing to Docker Hub Anyone can pull public images from the [Docker Hub](https://hub.docker.com) registry, but if you would like to share your own images, then you must register first, as we saw in the [first section of the Docker User Guide](/userguide/dockerhub/). ## Pushing a repository to Docker Hub In order to push a repository to its registry, you need to have named an image or committed your container to a named image as we saw [here](/userguide/dockerimages). Now you can push this repository to the registry designated by its name or tag. $ docker push yourname/newimage The image will then be uploaded and available for use by your team-mates and/or the community. ## Features of Docker Hub Let's take a closer look at some of the features of Docker Hub. You can find more information [here](https://docs.docker.com/docker-hub/). * Private repositories * Organizations and teams * Automated Builds * Webhooks ### Private repositories Sometimes you have images you don't want to make public and share with everyone. So Docker Hub allows you to have private repositories. You can sign up for a plan [here](https://registry.hub.docker.com/plans/). ### Organizations and teams One of the useful aspects of private repositories is that you can share them only with members of your organization or team. Docker Hub lets you create organizations where you can collaborate with your colleagues and manage private repositories. You can learn how to create and manage an organization [here](https://registry.hub.docker.com/account/organizations/). ### Automated Builds Automated Builds automate the building and updating of images from [GitHub](https://www.github.com) or [Bitbucket](http://bitbucket.com), directly on Docker Hub. It works by adding a commit hook to your selected GitHub or Bitbucket repository, triggering a build and update when you push a commit. #### To setup an Automated Build 1. Create a [Docker Hub account](https://hub.docker.com/) and login. 2. Link your GitHub or Bitbucket account through the ["Link Accounts"](https://registry.hub.docker.com/account/accounts/) menu. 3. [Configure an Automated Build](https://registry.hub.docker.com/builds/add/). 4. Pick a GitHub or Bitbucket project that has a `Dockerfile` that you want to build. 5. Pick the branch you want to build (the default is the `master` branch). 6. Give the Automated Build a name. 7. Assign an optional Docker tag to the Build. 8. Specify where the `Dockerfile` is located. The default is `/`. Once the Automated Build is configured it will automatically trigger a build and, in a few minutes, you should see your new Automated Build on the [Docker Hub](https://hub.docker.com) Registry. It will stay in sync with your GitHub and Bitbucket repository until you deactivate the Automated Build. If you want to see the status of your Automated Builds, you can go to your [Automated Builds page](https://registry.hub.docker.com/builds/) on the Docker Hub, and it will show you the status of your builds and their build history. Once you've created an Automated Build you can deactivate or delete it. You cannot, however, push to an Automated Build with the `docker push` command. You can only manage it by committing code to your GitHub or Bitbucket repository. You can create multiple Automated Builds per repository and configure them to point to specific `Dockerfile`'s or Git branches. #### Build triggers Automated Builds can also be triggered via a URL on Docker Hub. This allows you to rebuild an Automated build image on demand. ### Webhooks Webhooks are attached to your repositories and allow you to trigger an event when an image or updated image is pushed to the repository. With a webhook you can specify a target URL and a JSON payload that will be delivered when the image is pushed. See the Docker Hub documentation for [more information on webhooks](https://docs.docker.com/docker-hub/repos/#webhooks) ## Next steps Go and use Docker! ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/dockervolumes.md ================================================ # Managing data in containers So far we've been introduced to some [basic Docker concepts](/userguide/usingdocker/), seen how to work with [Docker images](/userguide/dockerimages/) as well as learned about [networking and links between containers](/userguide/dockerlinks/). In this section we're going to discuss how you can manage data inside and between your Docker containers. We're going to look at the two primary ways you can manage data in Docker. * Data volumes, and * Data volume containers. ## Data volumes A *data volume* is a specially-designated directory within one or more containers that bypasses the [*Union File System*](/terms/layer/#union-file-system). Data volumes provide several useful features for persistent or shared data: - Volumes are initialized when a container is created. If the container's base image contains data at the specified mount point, that existing data is copied into the new volume upon volume initialization. - Data volumes can be shared and reused among containers. - Changes to a data volume are made directly. - Changes to a data volume will not be included when you update an image. - Data volumes persist even if the container itself is deleted. Data volumes are designed to persist data, independent of the container's life cycle. Docker therefore *never* automatically delete volumes when you remove a container, nor will it "garbage collect" volumes that are no longer referenced by a container. ### Adding a data volume You can add a data volume to a container using the `-v` flag with the `docker create` and `docker run` command. You can use the `-v` multiple times to mount multiple data volumes. Let's mount a single volume now in our web application container. $ docker run -d -P --name web -v /webapp training/webapp python app.py This will create a new volume inside a container at `/webapp`. > **Note:** > You can also use the `VOLUME` instruction in a `Dockerfile` to add one or > more new volumes to any container created from that image. Docker volumes default to mount in read-write mode, but you can also set it to be mounted read-only. $ docker run -d -P --name web -v /opt/webapp:ro training/webapp python app.py ### Locating a volume You can locate the volume on the host by utilizing the 'docker inspect' command. $ docker inspect web The output will provide details on the container configurations including the volumes. The output should look something similar to the following: ... "Volumes": { "/webapp": "/var/lib/docker/volumes/fac362...80535" }, "VolumesRW": { "/webapp": true } ... You will notice in the above 'Volumes' is specifying the location on the host and 'VolumesRW' is specifying that the volume is read/write. ### Mount a host directory as a data volume In addition to creating a volume using the `-v` flag you can also mount a directory from your Docker daemon's host into a container. > **Note:** > If you are using Boot2Docker, your Docker daemon only has limited access to > your OS X/Windows filesystem. Boot2Docker tries to auto-share your `/Users` > (OS X) or `C:\Users` (Windows) directory - and so you can mount files or directories > using `docker run -v /Users/:/ ...` (OS X) or > `docker run -v /c/Users/:/ come from the Boot2Docker virtual machine's filesystem. $ docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py This will mount the host directory, `/src/webapp`, into the container at `/opt/webapp`. > **Note:** > If the path `/opt/webapp` already exists inside the container's image, its > contents will be replaced by the contents of `/src/webapp` on the host to stay > consistent with the expected behavior of `mount` > > When using Boot2Docker on Windows through git bash, there might be an issue with the > way the source directory name is parsed. You can fix it by using a double slash at > the beginning of the source directory name as explained in [issue #12751](https://github.com/docker/docker/issues/12751) This is very useful for testing, for example we can mount our source code inside the container and see our application at work as we change the source code. The directory on the host must be specified as an absolute path and if the directory doesn't exist Docker will automatically create it for you. > **Note:** > This is not available from a `Dockerfile` due to the portability > and sharing purpose of built images. The host directory is, by its nature, > host-dependent, so a host directory specified in a `Dockerfile` probably > wouldn't work on all hosts. Docker volumes default to mount in read-write mode, but you can also set it to be mounted read-only. $ docker run -d -P --name web -v /src/webapp:/opt/webapp:ro training/webapp python app.py Here we've mounted the same `/src/webapp` directory but we've added the `ro` option to specify that the mount should be read-only. ### Mount a host file as a data volume The `-v` flag can also be used to mount a single file - instead of *just* directories - from the host machine. $ docker run --rm -it -v ~/.bash_history:/.bash_history ubuntu /bin/bash This will drop you into a bash shell in a new container, you will have your bash history from the host and when you exit the container, the host will have the history of the commands typed while in the container. > **Note:** > Many tools used to edit files including `vi` and `sed --in-place` may result > in an inode change. Since Docker v1.1.0, this will produce an error such as > "*sed: cannot rename ./sedKdJ9Dy: Device or resource busy*". In the case where > you want to edit the mounted file, it is often easiest to instead mount the > parent directory. ## Creating and mounting a data volume container If you have some persistent data that you want to share between containers, or want to use from non-persistent containers, it's best to create a named Data Volume Container, and then to mount the data from it. Let's create a new named container with a volume to share. While this container doesn't run an application, it reuses the `training/postgres` image so that all containers are using layers in common, saving disk space. $ docker create -v /dbdata --name dbdata training/postgres /bin/true You can then use the `--volumes-from` flag to mount the `/dbdata` volume in another container. $ docker run -d --volumes-from dbdata --name db1 training/postgres And another: $ docker run -d --volumes-from dbdata --name db2 training/postgres In this case, if the `postgres` image contained a directory called `/dbdata` then mounting the volumes from the `dbdata` container hides the `/dbdata` files from the `postgres` image. The result is only the files from the `dbdata` container are visible. You can use multiple `--volumes-from` parameters to bring together multiple data volumes from multiple containers. You can also extend the chain by mounting the volume that came from the `dbdata` container in yet another container via the `db1` or `db2` containers. $ docker run -d --name db3 --volumes-from db1 training/postgres If you remove containers that mount volumes, including the initial `dbdata` container, or the subsequent containers `db1` and `db2`, the volumes will not be deleted. To delete the volume from disk, you must explicitly call `docker rm -v` against the last container with a reference to the volume. This allows you to upgrade, or effectively migrate data volumes between containers. > **Note:** Docker will not warn you when removing a container *without* > providing the `-v` option to delete its volumes. If you remove containers > without using the `-v` option, you may end up with "dangling" volumes; > volumes that are no longer referenced by a container. > Dangling volumes are difficult to get rid of and can take up a large amount > of disk space. We're working on improving volume management and you can check > progress on this in [pull request #14214](https://github.com/docker/docker/pull/14214) ## Backup, restore, or migrate data volumes Another useful function we can perform with volumes is use them for backups, restores or migrations. We do this by using the `--volumes-from` flag to create a new container that mounts that volume, like so: $ docker run --volumes-from dbdata -v $(pwd):/backup ubuntu tar cvf /backup/backup.tar /dbdata Here we've launched a new container and mounted the volume from the `dbdata` container. We've then mounted a local host directory as `/backup`. Finally, we've passed a command that uses `tar` to backup the contents of the `dbdata` volume to a `backup.tar` file inside our `/backup` directory. When the command completes and the container stops we'll be left with a backup of our `dbdata` volume. You could then restore it to the same container, or another that you've made elsewhere. Create a new container. $ docker run -v /dbdata --name dbdata2 ubuntu /bin/bash Then un-tar the backup file in the new container's data volume. $ docker run --volumes-from dbdata2 -v $(pwd):/backup ubuntu cd /dbdata && tar xvf /backup/backup.tar You can use the techniques above to automate backup, migration and restore testing using your preferred tools. # Next steps Now we've learned a bit more about how to use Docker we're going to see how to combine Docker with the services available on [Docker Hub](https://hub.docker.com) including Automated Builds and private repositories. Go to [Working with Docker Hub](/userguide/dockerrepos). ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/index.md ================================================ # Welcome to the Docker user guide In the [Introduction](/) you got a taste of what Docker is and how it works. In this guide we're going to take you through the fundamentals of using Docker and integrating it into your environment. We’ll teach you how to use Docker to: * Dockerize your applications. * Run your own containers. * Build Docker images. * Share your Docker images with others. * And a whole lot more! We've broken this guide into major sections that take you through the Docker life cycle: ## Getting started with Docker Hub *How do I use Docker Hub?* Docker Hub is the central hub for Docker. It hosts public Docker images and provides services to help you build and manage your Docker environment. To learn more: Go to [Using Docker Hub](/userguide/dockerhub). ## Dockerizing applications: A "Hello world" *How do I run applications inside containers?* Docker offers a *container-based* virtualization platform to power your applications. To learn how to Dockerize applications and run them: Go to [Dockerizing Applications](/userguide/dockerizing). ## Working with containers *How do I manage my containers?* Once you get a grip on running your applications in Docker containers we're going to show you how to manage those containers. To find out about how to inspect, monitor and manage containers: Go to [Working With Containers](/userguide/usingdocker). ## Working with Docker images *How can I access, share and build my own images?* Once you've learnt how to use Docker it's time to take the next step and learn how to build your own application images with Docker. Go to [Working with Docker Images](/userguide/dockerimages). ## Linking containers together Until now we've seen how to build individual applications inside Docker containers. Now learn how to build whole application stacks with Docker by linking together multiple Docker containers. Go to [Linking Containers Together](/userguide/dockerlinks). ## Managing data in containers Now we know how to link Docker containers together the next step is learning how to manage data, volumes and mounts inside our containers. Go to [Managing Data in Containers](/userguide/dockervolumes). ## Working with Docker Hub Now we've learned a bit more about how to use Docker we're going to see how to combine Docker with the services available on Docker Hub including Trusted Builds and private repositories. Go to [Working with Docker Hub](/userguide/dockerrepos). ## Docker Compose Docker Compose allows you to define a application's components -- their containers, configuration, links and volumes -- in a single file. Then a single command will set everything up and start your application running. Go to [Docker Compose user guide](/compose/). ## Docker Machine Docker Machine helps you get Docker Engines up and running quickly. Machine can set up hosts for Docker Engines on your computer, on cloud providers, and/or in your data center, and then configure your Docker client to securely talk to them. Go to [Docker Machine user guide](/machine/). ## Docker Swarm Docker Swarm pools several Docker Engines together and exposes them as a single virtual Docker Engine. It serves the standard Docker API, so any tool that already works with Docker can now transparently scale up to multiple hosts. Go to [Docker Swarm user guide](/swarm/). ## Getting help * [Docker homepage](http://www.docker.com/) * [Docker Hub](https://hub.docker.com) * [Docker blog](http://blog.docker.com/) * [Docker documentation](https://docs.docker.com/) * [Docker Getting Started Guide](http://www.docker.com/gettingstarted/) * [Docker code on GitHub](https://github.com/docker/docker) * [Docker mailing list](https://groups.google.com/forum/#!forum/docker-user) * Docker on IRC: irc.freenode.net and channel #docker * [Docker on Twitter](http://twitter.com/docker) * Get [Docker help](http://stackoverflow.com/search?q=docker) on StackOverflow * [Docker.com](http://www.docker.com/) ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/labels-custom-metadata.md ================================================ # Apply custom metadata You can apply metadata to your images, containers, or daemons via labels. Metadata can serve a wide range of uses. Use labels to add notes or licensing information to an image or to identify a host. A label is a `` / `` pair. Docker stores the label values as *strings*. You can specify multiple labels but each `` / `` must be unique to avoid overwriting. If you specify the same `key` several times but with different values, newer labels overwrite previous labels. Docker uses the last `key=value` you supply. >**Note:** Support for daemon-labels was added in Docker 1.4.1. Labels on >containers and images are new in Docker 1.6.0 ## Label keys (namespaces) Docker puts no hard restrictions on the label `key` you. However, labels with simple keys can conflict. For example, you can categorize your images by using a chip "architecture" label: LABEL architecture="amd64" LABEL architecture="ARMv7" But a user can label images by building architectural style: LABEL architecture="Art Nouveau" To prevent naming conflicts, Docker namespaces label keys using a reverse domain notation. Use the following guidelines to name your keys: - All (third-party) tools should prefix their keys with the reverse DNS notation of a domain controlled by the author. For example, `com.example.some-label`. - The `com.docker.*`, `io.docker.*` and `org.dockerproject.*` namespaces are reserved for Docker's internal use. - Keys should only consist of lower-cased alphanumeric characters, dots and dashes (for example, `[a-z0-9-.]`) - Keys should start *and* end with an alpha numeric character - Keys may not contain consecutive dots or dashes. - Keys *without* namespace (dots) are reserved for CLI use. This allows end- users to add metadata to their containers and images without having to type cumbersome namespaces on the command-line. These are guidelines and Docker does not *enforce* them. Failing following these guidelines can result in conflicting labels. If you're building a tool that uses labels, you *should* use namespaces for your label keys. ## Store structured data in labels Label values can contain any data type that can be stored as a string. For example, consider this JSON: { "Description": "A containerized foobar", "Usage": "docker run --rm example/foobar [args]", "License": "GPL", "Version": "0.0.1-beta", "aBoolean": true, "aNumber" : 0.01234, "aNestedArray": ["a", "b", "c"] } You can store this struct in a label by serializing it to a string first: LABEL com.example.image-specs="{\"Description\":\"A containerized foobar\",\"Usage\":\"docker run --rm example\\/foobar [args]\",\"License\":\"GPL\",\"Version\":\"0.0.1-beta\",\"aBoolean\":true,\"aNumber\":0.01234,\"aNestedArray\":[\"a\",\"b\",\"c\"]}" While it is *possible* to store structured data in label values, Docker treats this data as a 'regular' string. This means that Docker doesn't offer ways to query (filter) based on nested properties. If your tool needs to filter on nested properties, the tool itself should implement this. ## Add labels to images; the `LABEL` instruction Adding labels to an image: LABEL [.][=] ... The `LABEL` instruction adds a label to your image, optionally setting its value. Use surrounding quotes or backslashes for labels that contain white space character: LABEL vendor=ACME\ Incorporated LABEL com.example.version.is-beta LABEL com.example.version="0.0.1-beta" LABEL com.example.release-date="2015-02-12" The `LABEL` instruction supports setting multiple labels in a single instruction using this notation: LABEL com.example.version="0.0.1-beta" com.example.release-date="2015-02-12" Wrapping is allowed by using a backslash (`\`) as continuation marker: LABEL vendor=ACME\ Incorporated \ com.example.is-beta \ com.example.version="0.0.1-beta" \ com.example.release-date="2015-02-12" Docker recommends you add multiple labels in a single `LABEL` instruction. Using individual instructions for each label can result in an inefficient image. This is because each `LABEL` instruction in a Dockerfile produces a new IMAGE layer. You can view the labels via the `docker inspect` command: $ docker inspect 4fa6e0f0c678 ... "Labels": { "vendor": "ACME Incorporated", "com.example.is-beta": "", "com.example.version": "0.0.1-beta", "com.example.release-date": "2015-02-12" } ... # Inspect labels on container $ docker inspect -f "{{json .Config.Labels }}" 4fa6e0f0c678 {"Vendor":"ACME Incorporated","com.example.is-beta":"","com.example.version":"0.0.1-beta","com.example.release-date":"2015-02-12"} # Inspect labels on images $ docker inspect -f "{{json .ContainerConfig.Labels }}" myimage ## Query labels Besides storing metadata, you can filter images and containers by label. To list all running containers that the `com.example.is-beta` label: # List all running containers that have a `com.example.is-beta` label $ docker ps --filter "label=com.example.is-beta" List all running containers with a `color` label of `blue`: $ docker ps --filter "label=color=blue" List all images with `vendor` `ACME`: $ docker images --filter "label=vendor=ACME" ## Daemon labels docker -d \ --dns 8.8.8.8 \ --dns 8.8.4.4 \ -H unix:///var/run/docker.sock \ --label com.example.environment="production" \ --label com.example.storage="ssd" These labels appear as part of the `docker info` output for the daemon: docker -D info Containers: 12 Images: 672 Storage Driver: aufs Root Dir: /var/lib/docker/aufs Backing Filesystem: extfs Dirs: 697 Execution Driver: native-0.2 Logging Driver: json-file Kernel Version: 3.13.0-32-generic Operating System: Ubuntu 14.04.1 LTS CPUs: 1 Total Memory: 994.1 MiB Name: docker.example.com ID: RC3P:JTCT:32YS:XYSB:YUBG:VFED:AAJZ:W3YW:76XO:D7NN:TEVU:UCRW Debug mode (server): false Debug mode (client): true File Descriptors: 11 Goroutines: 14 EventsListeners: 0 Init Path: /usr/bin/docker Docker Root Dir: /var/lib/docker WARNING: No swap limit support Labels: com.example.environment=production com.example.storage=ssd ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/level1.md ================================================ Back # Dockerfile tutorial ## Test your Dockerfile knowledge - Level 1 ### Questions
What is the Dockerfile instruction to specify the base image ?

What is the Dockerfile instruction to execute any commands on the current image and commit the results?

What is the Dockerfile instruction to specify the maintainer of the Dockerfile?

What is the character used to add comment in Dockerfiles?

### Fill the Dockerfile Your best friend Eric Bardin sent you a Dockerfile, but some parts were lost in the ocean. Can you find the missing parts?
# This is a Dockerfile to create an image with Memcached and Emacs installed. 
# VERSION 1.0
# use the ubuntu base image provided by dotCloud ub
E B, eric.bardin@dotcloud.com
# make sure the package repository is up to date echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list apt-get update
# install memcached RUN apt-get install -y
# install emacs apt-get install -y emacs23

## What's next?

In the next level, we will go into more detail about how to specify which command should be executed when the container starts, which user to use, and how expose a particular port.

Back Go to the next level ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/level2.md ================================================ Back #Dockerfile tutorial ## Test your Dockerfile knowledge - Level 2 ### Questions:
What is the Dockerfile instruction to specify the base image?

Which Dockerfile instruction sets the default command for your image?

What is the character used to add comments in Dockerfiles?

Which Dockerfile instruction sets the username to use when running the image?

What is the Dockerfile instruction to execute any command on the current image and commit the results?

Which Dockerfile instruction sets ports to be exposed when running the image?

What is the Dockerfile instruction to specify the maintainer of the Dockerfile?

Which Dockerfile instruction lets you trigger a command as soon as the container starts?

### Fill the Dockerfile
Your best friend Roberto Hashioka sent you a Dockerfile, but some parts were lost in the ocean. Can you find the missing parts?
# Redis
#
# VERSION       0.42
#
# use the ubuntu base image provided by dotCloud
  ub
MAINT Ro Ha roberto.hashioka@dotcloud.com
# make sure the package repository is up to date echo "deb http://archive.ubuntu.com/ubuntu precise main universe" > /etc/apt/sources.list apt-get update
# install wget (required for redis installation) apt-get install -y wget
# install make (required for redis installation) apt-get install -y make
# install gcc (required for redis installation) RUN apt-get install -y
# install apache2 wget http://download.redis.io/redis-stable.tar.gz tar xvzf redis-stable.tar.gz cd redis-stable && make && make install
# launch redis when starting the image ["redis-server"]
# run as user daemon daemon
# expose port 6379 6379

## What's next?

Thanks for going through our tutorial! We will be posting Level 3 in the future. To improve your Dockerfile writing skills even further, visit the Dockerfile best practices page. Back to the Docs! ================================================ FILE: vendor/github.com/docker/docker/docs/userguide/usingdocker.md ================================================ # Working with containers In the [last section of the Docker User Guide](/userguide/dockerizing) we launched our first containers. We launched two containers using the `docker run` command. * Containers we ran interactively in the foreground. * One container we ran daemonized in the background. In the process we learned about several Docker commands: * `docker ps` - Lists containers. * `docker logs` - Shows us the standard output of a container. * `docker stop` - Stops running containers. > **Tip:** > Another way to learn about `docker` commands is our > [interactive tutorial](https://www.docker.com/tryit/). The `docker` client is pretty simple. Each action you can take with Docker is a command and each command can take a series of flags and arguments. # Usage: [sudo] docker [command] [flags] [arguments] .. # Example: $ docker run -i -t ubuntu /bin/bash Let's see this in action by using the `docker version` command to return version information on the currently installed Docker client and daemon. $ docker version This command will not only provide you the version of Docker client and daemon you are using, but also the version of Go (the programming language powering Docker). Client version: 0.8.0 Go version (client): go1.2 Git commit (client): cc3a8c8 Server version: 0.8.0 Git commit (server): cc3a8c8 Go version (server): go1.2 Last stable version: 0.8.0 ## Get Docker command help You can display the help for specific Docker commands. The help details the options and their usage. To see a list of all the possible commands, use the following: $ docker --help To see usage for a specific command, specify the command with the `--help` flag: $ docker attach --help Usage: docker attach [OPTIONS] CONTAINER Attach to a running container --help=false Print usage --no-stdin=false Do not attach stdin --sig-proxy=true Proxy all received signals to the process > **Note:** > For further details and examples of each command, see the > [command reference](/reference/commandline/cli/) in this guide. ## Running a web application in Docker So now we've learnt a bit more about the `docker` client let's move onto the important stuff: running more containers. So far none of the containers we've run did anything particularly useful, so let's change that by running an example web application in Docker. For our web application we're going to run a Python Flask application. Let's start with a `docker run` command. $ docker run -d -P training/webapp python app.py Let's review what our command did. We've specified two flags: `-d` and `-P`. We've already seen the `-d` flag which tells Docker to run the container in the background. The `-P` flag is new and tells Docker to map any required network ports inside our container to our host. This lets us view our web application. We've specified an image: `training/webapp`. This image is a pre-built image we've created that contains a simple Python Flask web application. Lastly, we've specified a command for our container to run: `python app.py`. This launches our web application. > **Note:** > You can see more detail on the `docker run` command in the [command > reference](/reference/commandline/cli/#run) and the [Docker Run > Reference](/reference/run/). ## Viewing our web application container Now let's see our running container using the `docker ps` command. $ docker ps -l CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES bc533791f3f5 training/webapp:latest python app.py 5 seconds ago Up 2 seconds 0.0.0.0:49155->5000/tcp nostalgic_morse You can see we've specified a new flag, `-l`, for the `docker ps` command. This tells the `docker ps` command to return the details of the *last* container started. > **Note:** > By default, the `docker ps` command only shows information about running > containers. If you want to see stopped containers too use the `-a` flag. We can see the same details we saw [when we first Dockerized a container](/userguide/dockerizing) with one important addition in the `PORTS` column. PORTS 0.0.0.0:49155->5000/tcp When we passed the `-P` flag to the `docker run` command Docker mapped any ports exposed in our image to our host. > **Note:** > We'll learn more about how to expose ports in Docker images when > [we learn how to build images](/userguide/dockerimages). In this case Docker has exposed port 5000 (the default Python Flask port) on port 49155. Network port bindings are very configurable in Docker. In our last example the `-P` flag is a shortcut for `-p 5000` that maps port 5000 inside the container to a high port (from *ephemeral port range* which typically ranges from 32768 to 61000) on the local Docker host. We can also bind Docker containers to specific ports using the `-p` flag, for example: $ docker run -d -p 80:5000 training/webapp python app.py This would map port 5000 inside our container to port 80 on our local host. You might be asking about now: why wouldn't we just want to always use 1:1 port mappings in Docker containers rather than mapping to high ports? Well 1:1 mappings have the constraint of only being able to map one of each port on your local host. Let's say you want to test two Python applications: both bound to port 5000 inside their own containers. Without Docker's port mapping you could only access one at a time on the Docker host. So let's now browse to port 49155 in a web browser to see the application. ![Viewing the web application](/userguide/webapp1.png). Our Python application is live! > **Note:** > If you have used the `boot2docker` virtual machine on OS X, Windows or Linux, > you'll need to get the IP of the virtual host instead of using localhost. > You can do this by running the following outside of the `boot2docker` shell > (i.e., from your comment line or terminal application). > > $ boot2docker ip > The VM's Host only interface IP address is: 192.168.59.103 > > In this case you'd browse to http://192.168.59.103:49155 for the above example. ## A network port shortcut Using the `docker ps` command to return the mapped port is a bit clumsy so Docker has a useful shortcut we can use: `docker port`. To use `docker port` we specify the ID or name of our container and then the port for which we need the corresponding public-facing port. $ docker port nostalgic_morse 5000 0.0.0.0:49155 In this case we've looked up what port is mapped externally to port 5000 inside the container. ## Viewing the web application's logs Let's also find out a bit more about what's happening with our application and use another of the commands we've learnt, `docker logs`. $ docker logs -f nostalgic_morse * Running on http://0.0.0.0:5000/ 10.0.2.2 - - [23/May/2014 20:16:31] "GET / HTTP/1.1" 200 - 10.0.2.2 - - [23/May/2014 20:16:31] "GET /favicon.ico HTTP/1.1" 404 - This time though we've added a new flag, `-f`. This causes the `docker logs` command to act like the `tail -f` command and watch the container's standard out. We can see here the logs from Flask showing the application running on port 5000 and the access log entries for it. ## Looking at our web application container's processes In addition to the container's logs we can also examine the processes running inside it using the `docker top` command. $ docker top nostalgic_morse PID USER COMMAND 854 root python app.py Here we can see our `python app.py` command is the only process running inside the container. ## Inspecting our web application container Lastly, we can take a low-level dive into our Docker container using the `docker inspect` command. It returns a JSON hash of useful configuration and status information about Docker containers. $ docker inspect nostalgic_morse Let's see a sample of that JSON output. [{ "ID": "bc533791f3f500b280a9626688bc79e342e3ea0d528efe3a86a51ecb28ea20", "Created": "2014-05-26T05:52:40.808952951Z", "Path": "python", "Args": [ "app.py" ], "Config": { "Hostname": "bc533791f3f5", "Domainname": "", "User": "", . . . We can also narrow down the information we want to return by requesting a specific element, for example to return the container's IP address we would: $ docker inspect -f '{{ .NetworkSettings.IPAddress }}' nostalgic_morse 172.17.0.5 ## Stopping our web application container Okay we've seen web application working. Now let's stop it using the `docker stop` command and the name of our container: `nostalgic_morse`. $ docker stop nostalgic_morse nostalgic_morse We can now use the `docker ps` command to check if the container has been stopped. $ docker ps -l ## Restarting our web application container Oops! Just after you stopped the container you get a call to say another developer needs the container back. From here you have two choices: you can create a new container or restart the old one. Let's look at starting our previous container back up. $ docker start nostalgic_morse nostalgic_morse Now quickly run `docker ps -l` again to see the running container is back up or browse to the container's URL to see if the application responds. > **Note:** > Also available is the `docker restart` command that runs a stop and > then start on the container. ## Removing our web application container Your colleague has let you know that they've now finished with the container and won't need it again. So let's remove it using the `docker rm` command. $ docker rm nostalgic_morse Error: Impossible to remove a running container, please stop it first or use -f 2014/05/24 08:12:56 Error: failed to remove one or more containers What happened? We can't actually remove a running container. This protects you from accidentally removing a running container you might need. Let's try this again by stopping the container first. $ docker stop nostalgic_morse nostalgic_morse $ docker rm nostalgic_morse nostalgic_morse And now our container is stopped and deleted. > **Note:** > Always remember that deleting a container is final! # Next steps Until now we've only used images that we've downloaded from [Docker Hub](https://hub.docker.com). Next, let's get introduced to building and sharing our own images. Go to [Working with Docker Images](/userguide/dockerimages). ================================================ FILE: vendor/github.com/docker/docker/experimental/README.md ================================================ # Docker Experimental Features This page contains a list of features in the Docker engine which are experimental. Experimental features are **not** ready for production. They are provided for test and evaluation in your sandbox environments. The information below describes each feature and the GitHub pull requests and issues associated with it. If necessary, links are provided to additional documentation on an issue. As an active Docker user and community member, please feel free to provide any feedback on these features you wish. ## Install Docker experimental Unlike the regular Docker binary, the experimental channels is built and updated nightly on TO.BE.ANNOUNCED. From one day to the next, new features may appear, while existing experimental features may be refined or entirely removed. 1. Verify that you have `wget` installed. $ which wget If `wget` isn't installed, install it after updating your manager: $ sudo apt-get update $ sudo apt-get install wget 2. Get the latest Docker package. $ wget -qO- https://experimental.docker.com/ | sh The system prompts you for your `sudo` password. Then, it downloads and installs Docker and its dependencies. >**Note**: If your company is behind a filtering proxy, you may find that the >`apt-key` >command fails for the Docker repo during installation. To work around this, >add the key directly using the following: > > $ wget -qO- https://experimental.docker.com/gpg | sudo apt-key add - 3. Verify `docker` is installed correctly. $ sudo docker run hello-world This command downloads a test image and runs it in a container. ### Get the Linux binary To download the latest experimental `docker` binary for Linux, use the following URLs: https://experimental.docker.com/builds/Linux/i386/docker-latest https://experimental.docker.com/builds/Linux/x86_64/docker-latest After downloading the appropriate binary, you can follow the instructions [here](https://docs.docker.com/installation/binaries/#get-the-docker-binary) to run the `docker` daemon. > **Note** > > 1) You can get the MD5 and SHA256 hashes by appending .md5 and .sha256 to the URLs respectively > > 2) You can get the compressed binaries by appending .tgz to the URLs ## Current experimental features * [Support for Docker plugins](plugins.md) * [Volume plugins](plugins_volume.md) * [Network plugins](plugins_network.md) * [Native Multi-host networking](networking.md) * [Compose, Swarm and networking integration](compose_swarm_networking.md) ## How to comment on an experimental feature Each feature's documentation includes a list of proposal pull requests or PRs associated with the feature. If you want to comment on or suggest a change to a feature, please add it to the existing feature PR. Issues or problems with a feature? Inquire for help on the `#docker` IRC channel or in on the [Docker Google group](https://groups.google.com/forum/#!forum/docker-user). ================================================ FILE: vendor/github.com/docker/docker/experimental/compose_swarm_networking.md ================================================ # Experimental: Compose, Swarm and Multi-Host Networking The [experimental build of Docker](https://github.com/docker/docker/tree/master/experimental) has an entirely new networking system, which enables secure communication between containers on multiple hosts. In combination with Docker Swarm and Docker Compose, you can now run multi-container apps on multi-host clusters with the same tooling and configuration format you use to develop them locally. > Note: This functionality is in the experimental stage, and contains some hacks and workarounds which will be removed as it matures. ## Prerequisites Before you start, you’ll need to install the experimental build of Docker, and the latest versions of Machine and Compose. - To install the experimental Docker build on a Linux machine, follow the instructions [here](https://github.com/docker/docker/tree/master/experimental#install-docker-experimental). - To install the experimental Docker build on a Mac, run these commands: $ curl -L https://experimental.docker.com/builds/Darwin/x86_64/docker-latest > /usr/local/bin/docker $ chmod +x /usr/local/bin/docker - To install Machine, follow the instructions [here](http://docs.docker.com/machine/). - To install Compose, follow the instructions [here](http://docs.docker.com/compose/install/). You’ll also need a [Docker Hub](https://hub.docker.com/account/signup/) account and a [Digital Ocean](https://www.digitalocean.com/) account. ## Set up a swarm with multi-host networking Set the `DIGITALOCEAN_ACCESS_TOKEN` environment variable to a valid Digital Ocean API token, which you can generate in the [API panel](https://cloud.digitalocean.com/settings/applications). export DIGITALOCEAN_ACCESS_TOKEN=abc12345 Start a consul server: docker-machine --debug create \ -d digitalocean \ --engine-install-url="https://experimental.docker.com" \ consul docker $(docker-machine config consul) run -d \ -p "8500:8500" \ -h "consul" \ progrium/consul -server -bootstrap (In a real world setting you’d set up a distributed consul, but that’s beyond the scope of this guide!) Create a Swarm token: export SWARM_TOKEN=$(docker run swarm create) Next, you create a Swarm master with Machine: docker-machine --debug create \ -d digitalocean \ --digitalocean-image="ubuntu-14-10-x64" \ --engine-install-url="https://experimental.docker.com" \ --engine-opt="default-network=overlay:multihost" \ --engine-opt="kv-store=consul:$(docker-machine ip consul):8500" \ --engine-label="com.docker.network.driver.overlay.bind_interface=eth0" \ swarm-0 Usually Machine can create Swarms for you, but it doesn't yet fully support multi-host networks yet, so you'll have to start up the Swarm manually: docker $(docker-machine config swarm-0) run -d \ --restart="always" \ --net="bridge" \ swarm:latest join \ --addr "$(docker-machine ip swarm-0):2376" \ "token://$SWARM_TOKEN" docker $(docker-machine config swarm-0) run -d \ --restart="always" \ --net="bridge" \ -p "3376:3376" \ -v "/etc/docker:/etc/docker" \ swarm:latest manage \ --tlsverify \ --tlscacert="/etc/docker/ca.pem" \ --tlscert="/etc/docker/server.pem" \ --tlskey="/etc/docker/server-key.pem" \ -H "tcp://0.0.0.0:3376" \ --strategy spread \ "token://$SWARM_TOKEN" Create a Swarm node: docker-machine --debug create \ -d digitalocean \ --digitalocean-image="ubuntu-14-10-x64" \ --engine-install-url="https://experimental.docker.com" \ --engine-opt="default-network=overlay:multihost" \ --engine-opt="kv-store=consul:$(docker-machine ip consul):8500" \ --engine-label="com.docker.network.driver.overlay.bind_interface=eth0" \ --engine-label="com.docker.network.driver.overlay.neighbor_ip=$(docker-machine ip swarm-0)" \ swarm-1 docker $(docker-machine config swarm-1) run -d \ --restart="always" \ --net="bridge" \ swarm:latest join \ --addr "$(docker-machine ip swarm-1):2376" \ "token://$SWARM_TOKEN" You can create more Swarm nodes if you want - it’s best to give them sensible names (swarm-2, swarm-3, etc). Finally, point Docker at your swarm: export DOCKER_HOST=tcp://"$(docker-machine ip swarm-0):3376" export DOCKER_TLS_VERIFY=1 export DOCKER_CERT_PATH="$HOME/.docker/machine/machines/swarm-0" ## Run containers and get them communicating Now that you’ve got a swarm up and running, you can create containers on it just like a single Docker instance: $ docker run busybox echo hello world hello world If you run `docker ps -a`, you can see what node that container was started on by looking at its name (here it’s swarm-3): $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 41f59749737b busybox "echo hello world" 15 seconds ago Exited (0) 13 seconds ago swarm-3/trusting_leakey As you start more containers, they’ll be placed on different nodes across the cluster, thanks to Swarm’s default “spread” scheduling strategy. Every container started on this swarm will use the “overlay:multihost” network by default, meaning they can all intercommunicate. Each container gets an IP address on that network, and an `/etc/hosts` file which will be updated on-the-fly with every other container’s IP address and name. That means that if you have a running container named ‘foo’, other containers can access it at the hostname ‘foo’. Let’s verify that multi-host networking is functioning. Start a long-running container: $ docker run -d --name long-running busybox top If you start a new container and inspect its /etc/hosts file, you’ll see the long-running container in there: $ docker run busybox cat /etc/hosts ... 172.21.0.6 long-running Verify that connectivity works between containers: $ docker run busybox ping long-running PING long-running (172.21.0.6): 56 data bytes 64 bytes from 172.21.0.6: seq=0 ttl=64 time=7.975 ms 64 bytes from 172.21.0.6: seq=1 ttl=64 time=1.378 ms 64 bytes from 172.21.0.6: seq=2 ttl=64 time=1.348 ms ^C --- long-running ping statistics --- 3 packets transmitted, 3 packets received, 0% packet loss round-trip min/avg/max = 1.140/2.099/7.975 ms ## Run a Compose application Here’s an example of a simple Python + Redis app using multi-host networking on a swarm. Create a directory for the app: $ mkdir composetest $ cd composetest Inside this directory, create 2 files. First, create `app.py` - a simple web app that uses the Flask framework and increments a value in Redis: from flask import Flask from redis import Redis import os app = Flask(__name__) redis = Redis(host='composetest_redis_1', port=6379) @app.route('/') def hello(): redis.incr('hits') return 'Hello World! I have been seen %s times.' % redis.get('hits') if __name__ == "__main__": app.run(host="0.0.0.0", debug=True) Note that we’re connecting to a host called `composetest_redis_1` - this is the name of the Redis container that Compose will start. Second, create a Dockerfile for the app container: FROM python:2.7 RUN pip install flask redis ADD . /code WORKDIR /code CMD ["python", "app.py"] Build the Docker image and push it to the Hub (you’ll need a Hub account). Replace `` with your Docker Hub username: $ docker build -t /counter . $ docker push /counter Next, create a `docker-compose.yml`, which defines the configuration for the web and redis containers. Once again, replace `` with your Hub username: web: image: /counter ports: - "80:5000" redis: image: redis Now start the app: $ docker-compose up -d Pulling web (username/counter:latest)... swarm-0: Pulling username/counter:latest... : downloaded swarm-2: Pulling username/counter:latest... : downloaded swarm-1: Pulling username/counter:latest... : downloaded swarm-3: Pulling username/counter:latest... : downloaded swarm-4: Pulling username/counter:latest... : downloaded Creating composetest_web_1... Pulling redis (redis:latest)... swarm-2: Pulling redis:latest... : downloaded swarm-1: Pulling redis:latest... : downloaded swarm-3: Pulling redis:latest... : downloaded swarm-4: Pulling redis:latest... : downloaded swarm-0: Pulling redis:latest... : downloaded Creating composetest_redis_1... Swarm has created containers for both web and redis, and placed them on different nodes, which you can check with `docker ps`: $ docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 92faad2135c9 redis "/entrypoint.sh redi 43 seconds ago Up 42 seconds swarm-2/composetest_redis_1 adb809e5cdac username/counter "/bin/sh -c 'python 55 seconds ago Up 54 seconds 45.67.8.9:80->5000/tcp swarm-1/composetest_web_1 You can also see that the web container has exposed port 80 on its swarm node. If you curl that IP, you’ll get a response from the container: $ curl http://45.67.8.9 Hello World! I have been seen 1 times. If you hit it repeatedly, the counter will increment, demonstrating that the web and redis container are communicating: $ curl http://45.67.8.9 Hello World! I have been seen 2 times. $ curl http://45.67.8.9 Hello World! I have been seen 3 times. $ curl http://45.67.8.9 Hello World! I have been seen 4 times. ================================================ FILE: vendor/github.com/docker/docker/experimental/networking.md ================================================ # Experimental: Networking and Services In this feature: - `network` and `service` become first class objects in the Docker UI - one can now create networks, publish services on that network and attach containers to the services - Native multi-host networking - `network` and `service` objects are globally significant and provides multi-host container connectivity natively - Inbuilt simple Service Discovery - With multi-host networking and top-level `service` object, Docker now provides out of the box simple Service Discovery for containers running in a network - Batteries included but removable - Docker provides inbuilt native multi-host networking by default & can be swapped by any remote driver provided by external plugins. This is an experimental feature. For information on installing and using experimental features, see [the experimental feature overview](README.md). ## Using Networks Usage: docker network [OPTIONS] COMMAND [OPTIONS] [arg...] Commands: create Create a network rm Remove a network ls List all networks info Display information of a network Run 'docker network COMMAND --help' for more information on a command. --help=false Print usage The `docker network` command is used to manage Networks. To create a network, `docker network create foo`. You can also specify a driver if you have loaded a networking plugin e.g `docker network create -d foo` $ docker network create foo aae601f43744bc1f57c515a16c8c7c4989a2cad577978a32e6910b799a6bccf6 $ docker network create -d overlay bar d9989793e2f5fe400a58ef77f706d03f668219688ee989ea68ea78b990fa2406 `docker network ls` is used to display the currently configured networks $ docker network ls NETWORK ID NAME TYPE d367e613ff7f none null bd61375b6993 host host cc455abccfeb bridge bridge aae601f43744 foo bridge d9989793e2f5 bar overlay To get detailed information on a network, you can use the `docker network info` command. $ docker network info foo Network Id: aae601f43744bc1f57c515a16c8c7c4989a2cad577978a32e6910b799a6bccf6 Name: foo Type: null If you no longer have need of a network, you can delete it with `docker network rm` $ docker network rm bar bar $ docker network ls NETWORK ID NAME TYPE aae601f43744 foo bridge d367e613ff7f none null bd61375b6993 host host cc455abccfeb bridge bridge ## User-Defined default network Docker daemon supports a configuration flag `--default-network` which takes configuration value of format `DRIVER:NETWORK`, where, `DRIVER` represents the in-built drivers such as bridge, overlay, container, host and none. or Remote drivers via Network Plugins. `NETWORK` is the name of the network created using the `docker network create` command When a container is created and if the network mode (`--net`) is not specified, then this default network will be used to connect the container. If `--default-network` is not specified, the default network will be the `bridge` driver. Example : `docker -d --default-network=overlay:multihost` ## Using Services Usage: docker service COMMAND [OPTIONS] [arg...] Commands: publish Publish a service unpublish Remove a service attach Attach a backend (container) to the service detach Detach the backend from the service ls Lists all services info Display information about a service Run 'docker service COMMAND --help' for more information on a command. --help=false Print usage Assuming we want to publish a service from container `a0ebc12d3e48` on network `foo` as `my-service` we would use the following command: $ docker service publish my-service.foo ec56fd74717d00f968c26675c9a77707e49ae64b8e54832ebf78888eb116e428 $ docker service attach a0ebc12d3e48 my-service.foo This would make the container `a0ebc12d3e48` accessible as `my-service` on network `foo`. Any other container in network `foo` can use DNS to resolve the address of `my-service` This can also be acheived by using the `--publish-service` flag for `docker run`: docker run -itd --publish-service db.foo postgres `db.foo` in this instance means "place the container on network `foo`, and allow other hosts on `foo` to discover it under the name `db`" We can see the current services using the `docker service ls` command $ docker service ls SERVICE ID NAME NETWORK PROVIDER ec56fd74717d my-service foo a0ebc12d3e48 To remove the a service: $ docker service detach a0ebc12d3e48 my-service.foo $ docker service unpublish my-service.foo ## Native Multi-host networking There is a lot to talk about the native multi-host networking and the `overlay` driver that makes it happen. The technical details are documented under https://github.com/docker/libnetwork/blob/master/docs/overlay.md. Using the above experimental UI `docker network`, `docker service` and `--publish-service`, the user can exercise the power of multi-host networking. Since `network` and `service` objects are globally significant, this feature requires distributed states provided by the `libkv` project. Using `libkv`, the user can plug any of the supported Key-Value store (such as consul, etcd or zookeeper). User can specify the Key-Value store of choice using the `--kv-store` daemon flag, which takes configuration value of format `PROVIDER:URL`, where `PROVIDER` is the name of the Key-Value store (such as consul, etcd or zookeeper) and `URL` is the url to reach the Key-Value store. Example : `docker -d --kv-store=consul:localhost:8500` Send us feedback and comments on [#14083](https://github.com/docker/docker/issues/14083) or on the usual Google Groups (docker-user, docker-dev) and IRC channels. ================================================ FILE: vendor/github.com/docker/docker/experimental/networking_api.md ================================================ # Networking API ### List networks `GET /networks` List networks **Example request**: GET /networks HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "name": "none", "id": "8e4e55c6863ef4241c548c1c6fc77289045e9e5d5b5e4875401a675326981898", "type": "null", "endpoints": [] }, { "name": "host", "id": "062b6d9ea7913fde549e2d186ff0402770658f8c4e769958e1b943ff4e675011", "type": "host", "endpoints": [] }, { "name": "bridge", "id": "a87dd9a9d58f030962df1c15fb3fa142fbd9261339de458bc89be1895cef2c70", "type": "bridge", "endpoints": [] } ] Query Parameters: - **name** – Filter results with the given name - **partial-id** – Filter results using the partial network ID Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create a Network `POST /networks` **Example request** POST /networks HTTP/1.1 Content-Type: application/json { "name": "foo", "network_type": "", "options": {} } **Example Response** HTTP/1.1 200 OK "32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653", Status Codes: - **200** – no error - **400** – bad request - **500** – server error ### Get a network `GET /networks/` Get a network **Example request**: GET /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json { "name": "foo", "id": "32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653", "type": "bridge", "endpoints": [] } Status Codes: - **200** – no error - **404** – not found - **500** – server error ### List a networks endpoints `GET /networks//endpoints` **Example request** GET /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653/endpoints HTTP/1.1 **Example Response** HTTP/1.1 200 OK Content-Type: application/json [ { "id": "7e0c116b882ee489a8a5345a2638c0129099aa47f4ba114edde34e75c1e4ae0d", "name": "/lonely_pasteur", "network": "foo" } ] Query Parameters: - **name** – Filter results with the given name - **partial-id** – Filter results using the partial network ID Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Create an endpoint on a network `POST /networks//endpoints` **Example request** POST /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653/endpoints HTTP/1.1 Content-Type: application/json { "name": "baz", "exposed_ports": [ { "proto": 6, "port": 8080 } ], "port_mapping": null } **Example Response** HTTP/1.1 200 OK Content-Type: application/json "b18b795af8bad85cdd691ff24ffa2b08c02219d51992309dd120322689d2ab5a" Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Get an endpoint `GET /networks//endpoints/` **Example request** GET /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653/endpoints/b18b795af8bad85cdd691ff24ffa2b08c02219d51992309dd120322689d2ab5a HTTP/1.1 **Example Response** HTTP/1.1 200 OK Content-Type: application/json { "id": "b18b795af8bad85cdd691ff24ffa2b08c02219d51992309dd120322689d2ab5a", "name": "baz", "network": "foo" } Status Codes: - **200** – no error - **404** - not found - **500** – server error ### Join an endpoint to a container `POST /networks//endpoints//containers` **Example request** POST /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653//endpoints/b18b795af8bad85cdd691ff24ffa2b08c02219d51992309dd120322689d2ab5a/containers HTTP/1.1 Content-Type: application/json { "container_id": "e76f406417031bd24c17aeb9bb2f5968b628b9fb6067da264b234544754bf857", "host_name": null, "domain_name": null, "hosts_path": null, "resolv_conf_path": null, "dns": null, "extra_hosts": null, "parent_updates": null, "use_default_sandbox": true } **Example response** HTTP/1.1 200 OK Content-Type: application/json "/var/run/docker/netns/e76f40641703" Status Codes: - **200** – no error - **400** – bad parameter - **404** - not found - **500** – server error ### Detach an endpoint from a container `DELETE /networks//endpoints//containers/` **Example request** DELETE /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653/endpoints/b18b795af8bad85cdd691ff24ffa2b08c02219d51992309dd120322689d2ab5a/containers/e76f406417031bd24c17aeb9bb2f5968b628b9fb6067da264b234544754bf857 HTTP/1.1 Content-Type: application/json **Example response** HTTP/1.1 200 OK Status Codes: - **200** – no error - **400** – bad parameter - **404** - not found - **500** – server error ### Delete an endpoint `DELETE /networks//endpoints/` **Example request** DELETE /networks/32fbf63200e2897f5de72cb2a4b653e4b1a523b15116e96e3d73f7849e583653/endpoints/b18b795af8bad85cdd691ff24ffa2b08c02219d51992309dd120322689d2ab5a HTTP/1.1 **Example Response** HTTP/1.1 200 OK Status Codes: - **200** – no error - **404** - not found - **500** – server error ### Delete a network `DELETE /networks/` Delete a network **Example request**: DELETE /networks/0984d158bd8ae108e4d6bc8fcabedf51da9a174b32cc777026d4a29045654951 HTTP/1.1 **Example response**: HTTP/1.1 200 OK Status Codes: - **200** – no error - **404** – not found - **500** – server error # Services API ### Publish a Service `POST /services` Publish a service **Example Request** POST /services HTTP/1.1 Content-Type: application/json { "name": "bar", "network_name": "foo", "exposed_ports": null, "port_mapping": null } **Example Response** HTTP/1.1 200 OK Content-Type: application/json "0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff" Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Get a Service `GET /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff` Get a service **Example Request**: GET /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff HTTP/1.1 **Example Response**: HTTP/1.1 200 OK Content-Type: application/json { "name": "bar", "id": "0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff", "network": "foo" } Status Codes: - **200** – no error - **400** – bad parameter - **404** - not found - **500** – server error ### Attach a backend to a service `POST /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff/backend` Attach a backend to a service **Example Request**: POST /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff/backend HTTP/1.1 Content-Type: application/json { "container_id": "98c5241f9475e9efc17e7198e931fb48166010b80f96d48df204e251378ca547", "host_name": "", "domain_name": "", "hosts_path": "", "resolv_conf_path": "", "dns": null, "extra_hosts": null, "parent_updates": null, "use_default_sandbox": false } **Example Response**: HTTP/1.1 200 OK Content-Type: application/json "/var/run/docker/netns/98c5241f9475" Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Get Backends for a Service Get all backends for a given service **Example Request** GET /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff/backend HTTP/1.1 **Example Response** HTTP/1.1 200 OK Content-Type: application/json [ { "id": "98c5241f9475e9efc17e7198e931fb48166010b80f96d48df204e251378ca547" } ] Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### List Services `GET /services` List services **Example request**: GET /services HTTP/1.1 **Example response**: HTTP/1.1 200 OK Content-Type: application/json [ { "name": "/stupefied_stallman", "id": "c826b26bf736fb4a77db33f83562e59f9a770724e259ab9c3d50d948f8233ae4", "network": "bridge" }, { "name": "bar", "id": "0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff", "network": "foo" } ] Query Parameters: - **name** – Filter results with the given name - **partial-id** – Filter results using the partial network ID - **network** - Filter results by the given network Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Detach a Backend from a Service `DELETE /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff/backend/98c5241f9475e9efc17e7198e931fb48166010b80f96d48df204e251378ca547` Detach a backend from a service **Example Request** DELETE /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff/backend/98c5241f9475e9efc17e7198e931fb48166010b80f96d48df204e251378ca547 HTTP/1.1 **Example Response** HTTP/1.1 200 OK Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ### Un-Publish a Service `DELETE /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff` Unpublish a service **Example Request** DELETE /services/0aee0899e6c5e903cf3ef2bdc28a1c9aaf639c8c8c331fa4ae26344d9e32c1ff HTTP/1.1 **Example Response** HTTP/1.1 200 OK Status Codes: - **200** – no error - **400** – bad parameter - **500** – server error ================================================ FILE: vendor/github.com/docker/docker/experimental/plugins_network.md ================================================ # Experimental: Docker network driver plugins Docker supports network driver plugins via [LibNetwork](https://github.com/docker/libnetwork). Network driver plugins are implemented as "remote drivers" for LibNetwork, which shares plugin infrastructure with Docker. In effect this means that network driver plugins are activated in the same way as other plugins, and use the same kind of protocol. ## Using network driver plugins The means of installing and running a network driver plugin will depend on the particular plugin. Once running however, network driver plugins are used just like the built-in network drivers: by being mentioned as a driver in network-oriented Docker commands. For example, docker network create -d weave mynet Some network driver plugins are listed in [plugins.md](/docs/extend/plugins.md) The network thus created is owned by the plugin, so subsequent commands referring to that network will also be run through the plugin. ## Network driver plugin protocol The network driver protocol, additional to the plugin activation call, is documented as part of LibNetwork: [https://github.com/docker/libnetwork/blob/master/docs/remote.md](https://github.com/docker/libnetwork/blob/master/docs/remote.md). # Related GitHub PRs and issues Please record your feedback in the following issue, on the usual Google Groups, or the IRC channel #docker-network. - [#14083](https://github.com/docker/docker/issues/14083) Feedback on experimental networking features Other pertinent issues: - [#13977](https://github.com/docker/docker/issues/13977) UI for using networks - [#14023](https://github.com/docker/docker/pull/14023) --default-network option - [#14051](https://github.com/docker/docker/pull/14051) --publish-service option - [#13441](https://github.com/docker/docker/pull/13441) (Deprecated) Networks API & UI ================================================ FILE: vendor/github.com/docker/docker/graph/export.go ================================================ package graph import ( "encoding/json" "io" "io/ioutil" "os" "path/filepath" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/registry" ) // CmdImageExport exports all images with the given tag. All versions // containing the same tag are exported. The resulting output is an // uncompressed tar ball. // name is the set of tags to export. // out is the writer where the images are written to. type ImageExportConfig struct { Names []string Outstream io.Writer } func (s *TagStore) ImageExport(imageExportConfig *ImageExportConfig) error { // get image json tempdir, err := ioutil.TempDir("", "docker-export-") if err != nil { return err } defer os.RemoveAll(tempdir) rootRepoMap := map[string]Repository{} addKey := func(name string, tag string, id string) { logrus.Debugf("add key [%s:%s]", name, tag) if repo, ok := rootRepoMap[name]; !ok { rootRepoMap[name] = Repository{tag: id} } else { repo[tag] = id } } for _, name := range imageExportConfig.Names { name = registry.NormalizeLocalName(name) logrus.Debugf("Serializing %s", name) rootRepo := s.Repositories[name] if rootRepo != nil { // this is a base repo name, like 'busybox' for tag, id := range rootRepo { addKey(name, tag, id) if err := s.exportImage(id, tempdir); err != nil { return err } } } else { img, err := s.LookupImage(name) if err != nil { return err } if img != nil { // This is a named image like 'busybox:latest' repoName, repoTag := parsers.ParseRepositoryTag(name) // check this length, because a lookup of a truncated has will not have a tag // and will not need to be added to this map if len(repoTag) > 0 { addKey(repoName, repoTag, img.ID) } if err := s.exportImage(img.ID, tempdir); err != nil { return err } } else { // this must be an ID that didn't get looked up just right? if err := s.exportImage(name, tempdir); err != nil { return err } } } logrus.Debugf("End Serializing %s", name) } // write repositories, if there is something to write if len(rootRepoMap) > 0 { f, err := os.OpenFile(filepath.Join(tempdir, "repositories"), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { f.Close() return err } if err := json.NewEncoder(f).Encode(rootRepoMap); err != nil { return err } if err := f.Close(); err != nil { return err } } else { logrus.Debugf("There were no repositories to write") } fs, err := archive.Tar(tempdir, archive.Uncompressed) if err != nil { return err } defer fs.Close() if _, err := io.Copy(imageExportConfig.Outstream, fs); err != nil { return err } logrus.Debugf("End export image") return nil } // FIXME: this should be a top-level function, not a class method func (s *TagStore) exportImage(name, tempdir string) error { for n := name; n != ""; { // temporary directory tmpImageDir := filepath.Join(tempdir, n) if err := os.Mkdir(tmpImageDir, os.FileMode(0755)); err != nil { if os.IsExist(err) { return nil } return err } var version = "1.0" var versionBuf = []byte(version) if err := ioutil.WriteFile(filepath.Join(tmpImageDir, "VERSION"), versionBuf, os.FileMode(0644)); err != nil { return err } // serialize json json, err := os.Create(filepath.Join(tmpImageDir, "json")) if err != nil { return err } imageInspectRaw, err := s.LookupRaw(n) if err != nil { return err } written, err := json.Write(imageInspectRaw) if err != nil { return err } if written != len(imageInspectRaw) { logrus.Warnf("%d byes should have been written instead %d have been written", written, len(imageInspectRaw)) } // serialize filesystem fsTar, err := os.Create(filepath.Join(tmpImageDir, "layer.tar")) if err != nil { return err } if err := s.ImageTarLayer(n, fsTar); err != nil { return err } // find parent img, err := s.LookupImage(n) if err != nil { return err } n = img.Parent } return nil } ================================================ FILE: vendor/github.com/docker/docker/graph/graph.go ================================================ package graph import ( "compress/gzip" "crypto/sha256" "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/distribution/digest" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/system" "github.com/docker/docker/pkg/truncindex" "github.com/docker/docker/runconfig" ) // The type is used to protect pulling or building related image // layers from deleteing when filtered by dangling=true // The key of layers is the images ID which is pulling or building // The value of layers is a slice which hold layer IDs referenced to // pulling or building images type retainedLayers struct { layerHolders map[string]map[string]struct{} // map[layerID]map[sessionID] sync.Mutex } func (r *retainedLayers) Add(sessionID string, layerIDs []string) { r.Lock() defer r.Unlock() for _, layerID := range layerIDs { if r.layerHolders[layerID] == nil { r.layerHolders[layerID] = map[string]struct{}{} } r.layerHolders[layerID][sessionID] = struct{}{} } } func (r *retainedLayers) Delete(sessionID string, layerIDs []string) { r.Lock() defer r.Unlock() for _, layerID := range layerIDs { holders, ok := r.layerHolders[layerID] if !ok { continue } delete(holders, sessionID) if len(holders) == 0 { delete(r.layerHolders, layerID) // Delete any empty reference set. } } } func (r *retainedLayers) Exists(layerID string) bool { r.Lock() _, exists := r.layerHolders[layerID] r.Unlock() return exists } // A Graph is a store for versioned filesystem images and the relationship between them. type Graph struct { root string idIndex *truncindex.TruncIndex driver graphdriver.Driver imageMutex imageMutex // protect images in driver. retained *retainedLayers } var ( // ErrDigestNotSet is used when request the digest for a layer // but the layer has no digest value or content to compute the // the digest. ErrDigestNotSet = errors.New("digest is not set for layer") ) // NewGraph instantiates a new graph at the given root path in the filesystem. // `root` will be created if it doesn't exist. func NewGraph(root string, driver graphdriver.Driver) (*Graph, error) { abspath, err := filepath.Abs(root) if err != nil { return nil, err } // Create the root directory if it doesn't exists if err := system.MkdirAll(root, 0700); err != nil && !os.IsExist(err) { return nil, err } graph := &Graph{ root: abspath, idIndex: truncindex.NewTruncIndex([]string{}), driver: driver, retained: &retainedLayers{layerHolders: make(map[string]map[string]struct{})}, } if err := graph.restore(); err != nil { return nil, err } return graph, nil } // IsHeld returns whether the given layerID is being used by an ongoing pull or build. func (graph *Graph) IsHeld(layerID string) bool { return graph.retained.Exists(layerID) } func (graph *Graph) restore() error { dir, err := ioutil.ReadDir(graph.root) if err != nil { return err } var ids = []string{} for _, v := range dir { id := v.Name() if graph.driver.Exists(id) { ids = append(ids, id) } } baseIds, err := graph.restoreBaseImages() if err != nil { return err } ids = append(ids, baseIds...) graph.idIndex = truncindex.NewTruncIndex(ids) logrus.Debugf("Restored %d elements", len(ids)) return nil } // FIXME: Implement error subclass instead of looking at the error text // Note: This is the way golang implements os.IsNotExists on Plan9 func (graph *Graph) IsNotExist(err error, id string) bool { return err != nil && (strings.Contains(strings.ToLower(err.Error()), "does not exist") || strings.Contains(strings.ToLower(err.Error()), "no such")) && strings.Contains(err.Error(), id) } // Exists returns true if an image is registered at the given id. // If the image doesn't exist or if an error is encountered, false is returned. func (graph *Graph) Exists(id string) bool { if _, err := graph.Get(id); err != nil { return false } return true } // Get returns the image with the given id, or an error if the image doesn't exist. func (graph *Graph) Get(name string) (*image.Image, error) { id, err := graph.idIndex.Get(name) if err != nil { return nil, fmt.Errorf("could not find image: %v", err) } img, err := graph.loadImage(id) if err != nil { return nil, err } if img.ID != id { return nil, fmt.Errorf("Image stored at '%s' has wrong id '%s'", id, img.ID) } if img.Size < 0 { size, err := graph.driver.DiffSize(img.ID, img.Parent) if err != nil { return nil, fmt.Errorf("unable to calculate size of image id %q: %s", img.ID, err) } img.Size = size if err := graph.saveSize(graph.imageRoot(id), int(img.Size)); err != nil { return nil, err } } return img, nil } // Create creates a new image and registers it in the graph. func (graph *Graph) Create(layerData archive.ArchiveReader, containerID, containerImage, comment, author string, containerConfig, config *runconfig.Config) (*image.Image, error) { img := &image.Image{ ID: stringid.GenerateRandomID(), Comment: comment, Created: time.Now().UTC(), DockerVersion: dockerversion.VERSION, Author: author, Config: config, Architecture: runtime.GOARCH, OS: runtime.GOOS, } if containerID != "" { img.Parent = containerImage img.Container = containerID img.ContainerConfig = *containerConfig } if err := graph.Register(img, layerData); err != nil { return nil, err } return img, nil } // Register imports a pre-existing image into the graph. func (graph *Graph) Register(img *image.Image, layerData archive.ArchiveReader) (err error) { if err := image.ValidateID(img.ID); err != nil { return err } // We need this entire operation to be atomic within the engine. Note that // this doesn't mean Register is fully safe yet. graph.imageMutex.Lock(img.ID) defer graph.imageMutex.Unlock(img.ID) // The returned `error` must be named in this function's signature so that // `err` is not shadowed in this deferred cleanup. defer func() { // If any error occurs, remove the new dir from the driver. // Don't check for errors since the dir might not have been created. if err != nil { graph.driver.Remove(img.ID) } }() // (This is a convenience to save time. Race conditions are taken care of by os.Rename) if graph.Exists(img.ID) { return fmt.Errorf("Image %s already exists", img.ID) } // Ensure that the image root does not exist on the filesystem // when it is not registered in the graph. // This is common when you switch from one graph driver to another if err := os.RemoveAll(graph.imageRoot(img.ID)); err != nil && !os.IsNotExist(err) { return err } // If the driver has this ID but the graph doesn't, remove it from the driver to start fresh. // (the graph is the source of truth). // Ignore errors, since we don't know if the driver correctly returns ErrNotExist. // (FIXME: make that mandatory for drivers). graph.driver.Remove(img.ID) tmp, err := graph.mktemp("") defer os.RemoveAll(tmp) if err != nil { return fmt.Errorf("mktemp failed: %s", err) } // Create root filesystem in the driver if err := createRootFilesystemInDriver(graph, img, layerData); err != nil { return err } // Apply the diff/layer if err := graph.storeImage(img, layerData, tmp); err != nil { return err } // Commit if err := os.Rename(tmp, graph.imageRoot(img.ID)); err != nil { return err } graph.idIndex.Add(img.ID) return nil } // TempLayerArchive creates a temporary archive of the given image's filesystem layer. // The archive is stored on disk and will be automatically deleted as soon as has been read. // If output is not nil, a human-readable progress bar will be written to it. func (graph *Graph) TempLayerArchive(id string, sf *streamformatter.StreamFormatter, output io.Writer) (*archive.TempArchive, error) { image, err := graph.Get(id) if err != nil { return nil, err } tmp, err := graph.mktemp("") if err != nil { return nil, err } a, err := graph.TarLayer(image) if err != nil { return nil, err } progressReader := progressreader.New(progressreader.Config{ In: a, Out: output, Formatter: sf, Size: 0, NewLines: false, ID: stringid.TruncateID(id), Action: "Buffering to disk", }) defer progressReader.Close() return archive.NewTempArchive(progressReader, tmp) } // mktemp creates a temporary sub-directory inside the graph's filesystem. func (graph *Graph) mktemp(id string) (string, error) { dir := filepath.Join(graph.root, "_tmp", stringid.GenerateRandomID()) if err := system.MkdirAll(dir, 0700); err != nil { return "", err } return dir, nil } func (graph *Graph) newTempFile() (*os.File, error) { tmp, err := graph.mktemp("") if err != nil { return nil, err } return ioutil.TempFile(tmp, "") } func bufferToFile(f *os.File, src io.Reader) (int64, digest.Digest, error) { var ( h = sha256.New() w = gzip.NewWriter(io.MultiWriter(f, h)) ) _, err := io.Copy(w, src) w.Close() if err != nil { return 0, "", err } n, err := f.Seek(0, os.SEEK_CUR) if err != nil { return 0, "", err } if _, err := f.Seek(0, 0); err != nil { return 0, "", err } return n, digest.NewDigest("sha256", h), nil } // Delete atomically removes an image from the graph. func (graph *Graph) Delete(name string) error { id, err := graph.idIndex.Get(name) if err != nil { return err } tmp, err := graph.mktemp("") graph.idIndex.Delete(id) if err == nil { if err := os.Rename(graph.imageRoot(id), tmp); err != nil { // On err make tmp point to old dir and cleanup unused tmp dir os.RemoveAll(tmp) tmp = graph.imageRoot(id) } } else { // On err make tmp point to old dir for cleanup tmp = graph.imageRoot(id) } // Remove rootfs data from the driver graph.driver.Remove(id) // Remove the trashed image directory return os.RemoveAll(tmp) } // Map returns a list of all images in the graph, addressable by ID. func (graph *Graph) Map() map[string]*image.Image { images := make(map[string]*image.Image) graph.walkAll(func(image *image.Image) { images[image.ID] = image }) return images } // walkAll iterates over each image in the graph, and passes it to a handler. // The walking order is undetermined. func (graph *Graph) walkAll(handler func(*image.Image)) { graph.idIndex.Iterate(func(id string) { if img, err := graph.Get(id); err != nil { return } else if handler != nil { handler(img) } }) } // ByParent returns a lookup table of images by their parent. // If an image of id ID has 3 children images, then the value for key ID // will be a list of 3 images. // If an image has no children, it will not have an entry in the table. func (graph *Graph) ByParent() map[string][]*image.Image { byParent := make(map[string][]*image.Image) graph.walkAll(func(img *image.Image) { parent, err := graph.Get(img.Parent) if err != nil { return } if children, exists := byParent[parent.ID]; exists { byParent[parent.ID] = append(children, img) } else { byParent[parent.ID] = []*image.Image{img} } }) return byParent } // If the images and layers are in pulling chain, retain them. // If not, they may be deleted by rmi with dangling condition. func (graph *Graph) Retain(sessionID string, layerIDs ...string) { graph.retained.Add(sessionID, layerIDs) } // Release removes the referenced image id from the provided set of layers. func (graph *Graph) Release(sessionID string, layerIDs ...string) { graph.retained.Delete(sessionID, layerIDs) } // Heads returns all heads in the graph, keyed by id. // A head is an image which is not the parent of another image in the graph. func (graph *Graph) Heads() map[string]*image.Image { heads := make(map[string]*image.Image) byParent := graph.ByParent() graph.walkAll(func(image *image.Image) { // If it's not in the byParent lookup table, then // it's not a parent -> so it's a head! if _, exists := byParent[image.ID]; !exists { heads[image.ID] = image } }) return heads } func (graph *Graph) imageRoot(id string) string { return filepath.Join(graph.root, id) } // loadImage fetches the image with the given id from the graph. func (graph *Graph) loadImage(id string) (*image.Image, error) { root := graph.imageRoot(id) // Open the JSON file to decode by streaming jsonSource, err := os.Open(jsonPath(root)) if err != nil { return nil, err } defer jsonSource.Close() img := &image.Image{} dec := json.NewDecoder(jsonSource) // Decode the JSON data if err := dec.Decode(img); err != nil { return nil, err } if err := image.ValidateID(img.ID); err != nil { return nil, err } if buf, err := ioutil.ReadFile(filepath.Join(root, "layersize")); err != nil { if !os.IsNotExist(err) { return nil, err } // If the layersize file does not exist then set the size to a negative number // because a layer size of 0 (zero) is valid img.Size = -1 } else { // Using Atoi here instead would temporarily convert the size to a machine // dependent integer type, which causes images larger than 2^31 bytes to // display negative sizes on 32-bit machines: size, err := strconv.ParseInt(string(buf), 10, 64) if err != nil { return nil, err } img.Size = int64(size) } return img, nil } // saveSize stores the `size` in the provided graph `img` directory `root`. func (graph *Graph) saveSize(root string, size int) error { if err := ioutil.WriteFile(filepath.Join(root, "layersize"), []byte(strconv.Itoa(size)), 0600); err != nil { return fmt.Errorf("Error storing image size in %s/layersize: %s", root, err) } return nil } // SetDigest sets the digest for the image layer to the provided value. func (graph *Graph) SetDigest(id string, dgst digest.Digest) error { root := graph.imageRoot(id) if err := ioutil.WriteFile(filepath.Join(root, "checksum"), []byte(dgst.String()), 0600); err != nil { return fmt.Errorf("Error storing digest in %s/checksum: %s", root, err) } return nil } // GetDigest gets the digest for the provide image layer id. func (graph *Graph) GetDigest(id string) (digest.Digest, error) { root := graph.imageRoot(id) cs, err := ioutil.ReadFile(filepath.Join(root, "checksum")) if err != nil { if os.IsNotExist(err) { return "", ErrDigestNotSet } return "", err } return digest.ParseDigest(string(cs)) } // RawJSON returns the JSON representation for an image as a byte array. func (graph *Graph) RawJSON(id string) ([]byte, error) { root := graph.imageRoot(id) buf, err := ioutil.ReadFile(jsonPath(root)) if err != nil { return nil, fmt.Errorf("Failed to read json for image %s: %s", id, err) } return buf, nil } func jsonPath(root string) string { return filepath.Join(root, "json") } ================================================ FILE: vendor/github.com/docker/docker/graph/graph_test.go ================================================ package graph import ( "errors" "io" "io/ioutil" "os" "path" "testing" "time" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/image" "github.com/docker/docker/pkg/stringid" ) func TestMount(t *testing.T) { graph, driver := tempGraph(t) defer os.RemoveAll(graph.root) defer driver.Cleanup() archive, err := fakeTar() if err != nil { t.Fatal(err) } image, err := graph.Create(archive, "", "", "Testing", "", nil, nil) if err != nil { t.Fatal(err) } tmp, err := ioutil.TempDir("", "docker-test-graph-mount-") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) rootfs := path.Join(tmp, "rootfs") if err := os.MkdirAll(rootfs, 0700); err != nil { t.Fatal(err) } rw := path.Join(tmp, "rw") if err := os.MkdirAll(rw, 0700); err != nil { t.Fatal(err) } if _, err := driver.Get(image.ID, ""); err != nil { t.Fatal(err) } } func TestInit(t *testing.T) { graph, _ := tempGraph(t) defer nukeGraph(graph) // Root should exist if _, err := os.Stat(graph.root); err != nil { t.Fatal(err) } // Map() should be empty l := graph.Map() if len(l) != 0 { t.Fatalf("len(Map()) should return %d, not %d", 0, len(l)) } } // Test that Register can be interrupted cleanly without side effects func TestInterruptedRegister(t *testing.T) { graph, _ := tempGraph(t) defer nukeGraph(graph) badArchive, w := io.Pipe() // Use a pipe reader as a fake archive which never yields data image := &image.Image{ ID: stringid.GenerateRandomID(), Comment: "testing", Created: time.Now(), } w.CloseWithError(errors.New("But I'm not a tarball!")) // (Nobody's perfect, darling) graph.Register(image, badArchive) if _, err := graph.Get(image.ID); err == nil { t.Fatal("Image should not exist after Register is interrupted") } // Registering the same image again should succeed if the first register was interrupted goodArchive, err := fakeTar() if err != nil { t.Fatal(err) } if err := graph.Register(image, goodArchive); err != nil { t.Fatal(err) } } // FIXME: Do more extensive tests (ex: create multiple, delete, recreate; // create multiple, check the amount of images and paths, etc..) func TestGraphCreate(t *testing.T) { graph, _ := tempGraph(t) defer nukeGraph(graph) archive, err := fakeTar() if err != nil { t.Fatal(err) } img, err := graph.Create(archive, "", "", "Testing", "", nil, nil) if err != nil { t.Fatal(err) } if err := image.ValidateID(img.ID); err != nil { t.Fatal(err) } if img.Comment != "Testing" { t.Fatalf("Wrong comment: should be '%s', not '%s'", "Testing", img.Comment) } if img.DockerVersion != dockerversion.VERSION { t.Fatalf("Wrong docker_version: should be '%s', not '%s'", dockerversion.VERSION, img.DockerVersion) } images := graph.Map() if l := len(images); l != 1 { t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) } if images[img.ID] == nil { t.Fatalf("Could not find image with id %s", img.ID) } } func TestRegister(t *testing.T) { graph, _ := tempGraph(t) defer nukeGraph(graph) archive, err := fakeTar() if err != nil { t.Fatal(err) } image := &image.Image{ ID: stringid.GenerateRandomID(), Comment: "testing", Created: time.Now(), } err = graph.Register(image, archive) if err != nil { t.Fatal(err) } images := graph.Map() if l := len(images); l != 1 { t.Fatalf("Wrong number of images. Should be %d, not %d", 1, l) } if resultImg, err := graph.Get(image.ID); err != nil { t.Fatal(err) } else { if resultImg.ID != image.ID { t.Fatalf("Wrong image ID. Should be '%s', not '%s'", image.ID, resultImg.ID) } if resultImg.Comment != image.Comment { t.Fatalf("Wrong image comment. Should be '%s', not '%s'", image.Comment, resultImg.Comment) } } } // Test that an image can be deleted by its shorthand prefix func TestDeletePrefix(t *testing.T) { graph, _ := tempGraph(t) defer nukeGraph(graph) img := createTestImage(graph, t) if err := graph.Delete(stringid.TruncateID(img.ID)); err != nil { t.Fatal(err) } assertNImages(graph, t, 0) } func TestDelete(t *testing.T) { graph, _ := tempGraph(t) defer nukeGraph(graph) archive, err := fakeTar() if err != nil { t.Fatal(err) } assertNImages(graph, t, 0) img, err := graph.Create(archive, "", "", "Bla bla", "", nil, nil) if err != nil { t.Fatal(err) } assertNImages(graph, t, 1) if err := graph.Delete(img.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 0) archive, err = fakeTar() if err != nil { t.Fatal(err) } // Test 2 create (same name) / 1 delete img1, err := graph.Create(archive, "", "", "Testing", "", nil, nil) if err != nil { t.Fatal(err) } archive, err = fakeTar() if err != nil { t.Fatal(err) } if _, err = graph.Create(archive, "", "", "Testing", "", nil, nil); err != nil { t.Fatal(err) } assertNImages(graph, t, 2) if err := graph.Delete(img1.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 1) // Test delete wrong name if err := graph.Delete("Not_foo"); err == nil { t.Fatalf("Deleting wrong ID should return an error") } assertNImages(graph, t, 1) archive, err = fakeTar() if err != nil { t.Fatal(err) } // Test delete twice (pull -> rm -> pull -> rm) if err := graph.Register(img1, archive); err != nil { t.Fatal(err) } if err := graph.Delete(img1.ID); err != nil { t.Fatal(err) } assertNImages(graph, t, 1) } func TestByParent(t *testing.T) { archive1, _ := fakeTar() archive2, _ := fakeTar() archive3, _ := fakeTar() graph, _ := tempGraph(t) defer nukeGraph(graph) parentImage := &image.Image{ ID: stringid.GenerateRandomID(), Comment: "parent", Created: time.Now(), Parent: "", } childImage1 := &image.Image{ ID: stringid.GenerateRandomID(), Comment: "child1", Created: time.Now(), Parent: parentImage.ID, } childImage2 := &image.Image{ ID: stringid.GenerateRandomID(), Comment: "child2", Created: time.Now(), Parent: parentImage.ID, } _ = graph.Register(parentImage, archive1) _ = graph.Register(childImage1, archive2) _ = graph.Register(childImage2, archive3) byParent := graph.ByParent() numChildren := len(byParent[parentImage.ID]) if numChildren != 2 { t.Fatalf("Expected 2 children, found %d", numChildren) } } func createTestImage(graph *Graph, t *testing.T) *image.Image { archive, err := fakeTar() if err != nil { t.Fatal(err) } img, err := graph.Create(archive, "", "", "Test image", "", nil, nil) if err != nil { t.Fatal(err) } return img } func assertNImages(graph *Graph, t *testing.T, n int) { images := graph.Map() if actualN := len(images); actualN != n { t.Fatalf("Expected %d images, found %d", n, actualN) } } func tempGraph(t *testing.T) (*Graph, graphdriver.Driver) { tmp, err := ioutil.TempDir("", "docker-graph-") if err != nil { t.Fatal(err) } driver, err := graphdriver.New(tmp, nil) if err != nil { t.Fatal(err) } graph, err := NewGraph(tmp, driver) if err != nil { t.Fatal(err) } return graph, driver } func nukeGraph(graph *Graph) { graph.driver.Cleanup() os.RemoveAll(graph.root) } ================================================ FILE: vendor/github.com/docker/docker/graph/graph_unix.go ================================================ // +build !windows package graph import ( "encoding/json" "fmt" "os" "path/filepath" "strings" "syscall" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/system" ) // setupInitLayer populates a directory with mountpoints suitable // for bind-mounting dockerinit into the container. The mountpoint is simply an // empty file at /.dockerinit // // This extra layer is used by all containers as the top-most ro layer. It protects // the container from unwanted side-effects on the rw layer. func SetupInitLayer(initLayer string) error { for pth, typ := range map[string]string{ "/dev/pts": "dir", "/dev/shm": "dir", "/proc": "dir", "/sys": "dir", "/.dockerinit": "file", "/.dockerenv": "file", "/etc/resolv.conf": "file", "/etc/hosts": "file", "/etc/hostname": "file", "/dev/console": "file", "/etc/mtab": "/proc/mounts", } { parts := strings.Split(pth, "/") prev := "/" for _, p := range parts[1:] { prev = filepath.Join(prev, p) syscall.Unlink(filepath.Join(initLayer, prev)) } if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil { if os.IsNotExist(err) { if err := system.MkdirAll(filepath.Join(initLayer, filepath.Dir(pth)), 0755); err != nil { return err } switch typ { case "dir": if err := system.MkdirAll(filepath.Join(initLayer, pth), 0755); err != nil { return err } case "file": f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755) if err != nil { return err } f.Close() default: if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil { return err } } } else { return err } } } // Layer is ready to use, if it wasn't before. return nil } func createRootFilesystemInDriver(graph *Graph, img *image.Image, layerData archive.ArchiveReader) error { if err := graph.driver.Create(img.ID, img.Parent); err != nil { return fmt.Errorf("Driver %s failed to create image rootfs %s: %s", graph.driver, img.ID, err) } return nil } func (graph *Graph) restoreBaseImages() ([]string, error) { return nil, nil } // storeImage stores file system layer data for the given image to the // graph's storage driver. Image metadata is stored in a file // at the specified root directory. func (graph *Graph) storeImage(img *image.Image, layerData archive.ArchiveReader, root string) (err error) { // Store the layer. If layerData is not nil, unpack it into the new layer if layerData != nil { if img.Size, err = graph.driver.ApplyDiff(img.ID, img.Parent, layerData); err != nil { return err } } if err := graph.saveSize(root, int(img.Size)); err != nil { return err } f, err := os.OpenFile(jsonPath(root), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) if err != nil { return err } defer f.Close() return json.NewEncoder(f).Encode(img) } // TarLayer returns a tar archive of the image's filesystem layer. func (graph *Graph) TarLayer(img *image.Image) (arch archive.Archive, err error) { return graph.driver.Diff(img.ID, img.Parent) } ================================================ FILE: vendor/github.com/docker/docker/graph/graph_windows.go ================================================ // +build windows package graph import ( "encoding/json" "fmt" "os" "github.com/Sirupsen/logrus" "github.com/docker/docker/daemon/graphdriver/windows" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" ) // setupInitLayer populates a directory with mountpoints suitable // for bind-mounting dockerinit into the container. T func SetupInitLayer(initLayer string) error { return nil } func createRootFilesystemInDriver(graph *Graph, img *image.Image, layerData archive.ArchiveReader) error { if wd, ok := graph.driver.(*windows.WindowsGraphDriver); ok { if img.Container != "" && layerData == nil { logrus.Debugf("Copying from container %s.", img.Container) var ids []string if img.Parent != "" { parentImg, err := graph.Get(img.Parent) if err != nil { return err } ids, err = graph.ParentLayerIds(parentImg) if err != nil { return err } } if err := wd.CopyDiff(img.Container, img.ID, wd.LayerIdsToPaths(ids)); err != nil { return fmt.Errorf("Driver %s failed to copy image rootfs %s: %s", graph.driver, img.Container, err) } } else if img.Parent == "" { if err := graph.driver.Create(img.ID, img.Parent); err != nil { return fmt.Errorf("Driver %s failed to create image rootfs %s: %s", graph.driver, img.ID, err) } } } else { // This fallback allows the use of VFS during daemon development. if err := graph.driver.Create(img.ID, img.Parent); err != nil { return fmt.Errorf("Driver %s failed to create image rootfs %s: %s", graph.driver, img.ID, err) } } return nil } func (graph *Graph) restoreBaseImages() ([]string, error) { // TODO Windows. This needs implementing (@swernli) return nil, nil } // ParentLayerIds returns a list of all parent image IDs for the given image. func (graph *Graph) ParentLayerIds(img *image.Image) (ids []string, err error) { for i := img; i != nil && err == nil; i, err = graph.GetParent(i) { ids = append(ids, i.ID) } return } // storeImage stores file system layer data for the given image to the // graph's storage driver. Image metadata is stored in a file // at the specified root directory. func (graph *Graph) storeImage(img *image.Image, layerData archive.ArchiveReader, root string) (err error) { if wd, ok := graph.driver.(*windows.WindowsGraphDriver); ok { // Store the layer. If layerData is not nil and this isn't a base image, // unpack it into the new layer if layerData != nil && img.Parent != "" { var ids []string if img.Parent != "" { parentImg, err := graph.Get(img.Parent) if err != nil { return err } ids, err = graph.ParentLayerIds(parentImg) if err != nil { return err } } if img.Size, err = wd.Import(img.ID, layerData, wd.LayerIdsToPaths(ids)); err != nil { return err } } if err := graph.saveSize(root, int(img.Size)); err != nil { return err } f, err := os.OpenFile(jsonPath(root), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) if err != nil { return err } defer f.Close() return json.NewEncoder(f).Encode(img) } else { // We keep this functionality here so that we can still work with the // VFS driver during development. This will not be used for actual running // of Windows containers. Without this code, it would not be possible to // docker pull using the VFS driver. // Store the layer. If layerData is not nil, unpack it into the new layer if layerData != nil { if img.Size, err = graph.driver.ApplyDiff(img.ID, img.Parent, layerData); err != nil { return err } } if err := graph.saveSize(root, int(img.Size)); err != nil { return err } f, err := os.OpenFile(jsonPath(root), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.FileMode(0600)) if err != nil { return err } defer f.Close() return json.NewEncoder(f).Encode(img) } } // TarLayer returns a tar archive of the image's filesystem layer. func (graph *Graph) TarLayer(img *image.Image) (arch archive.Archive, err error) { if wd, ok := graph.driver.(*windows.WindowsGraphDriver); ok { var ids []string if img.Parent != "" { parentImg, err := graph.Get(img.Parent) if err != nil { return nil, err } ids, err = graph.ParentLayerIds(parentImg) if err != nil { return nil, err } } return wd.Export(img.ID, wd.LayerIdsToPaths(ids)) } else { // We keep this functionality here so that we can still work with the VFS // driver during development. VFS is not supported (and just will not work) // for Windows containers. return graph.driver.Diff(img.ID, img.Parent) } } ================================================ FILE: vendor/github.com/docker/docker/graph/history.go ================================================ package graph import ( "fmt" "strings" "github.com/docker/docker/api/types" "github.com/docker/docker/image" "github.com/docker/docker/utils" ) // WalkHistory calls the handler function for each image in the // provided images lineage starting from immediate parent. func (graph *Graph) WalkHistory(img *image.Image, handler func(image.Image) error) (err error) { currentImg := img for currentImg != nil { if handler != nil { if err := handler(*currentImg); err != nil { return err } } currentImg, err = graph.GetParent(currentImg) if err != nil { return fmt.Errorf("Error while getting parent image: %v", err) } } return nil } // depth returns the number of parents for a // current image func (graph *Graph) depth(img *image.Image) (int, error) { var ( count = 0 parent = img err error ) for parent != nil { count++ parent, err = graph.GetParent(parent) if err != nil { return -1, err } } return count, nil } // Set the max depth to the aufs default that most // kernels are compiled with // For more information see: http://sourceforge.net/p/aufs/aufs3-standalone/ci/aufs3.12/tree/config.mk const MaxImageDepth = 127 // CheckDepth returns an error if the depth of an image, as returned // by ImageDepth, is too large to support creating a container from it // on this daemon. func (graph *Graph) CheckDepth(img *image.Image) error { // We add 2 layers to the depth because the container's rw and // init layer add to the restriction depth, err := graph.depth(img) if err != nil { return err } if depth+2 >= MaxImageDepth { return fmt.Errorf("Cannot create container with more than %d parents", MaxImageDepth) } return nil } func (s *TagStore) History(name string) ([]*types.ImageHistory, error) { foundImage, err := s.LookupImage(name) if err != nil { return nil, err } lookupMap := make(map[string][]string) for name, repository := range s.Repositories { for tag, id := range repository { // If the ID already has a reverse lookup, do not update it unless for "latest" if _, exists := lookupMap[id]; !exists { lookupMap[id] = []string{} } lookupMap[id] = append(lookupMap[id], utils.ImageReference(name, tag)) } } history := []*types.ImageHistory{} err = s.graph.WalkHistory(foundImage, func(img image.Image) error { history = append(history, &types.ImageHistory{ ID: img.ID, Created: img.Created.Unix(), CreatedBy: strings.Join(img.ContainerConfig.Cmd.Slice(), " "), Tags: lookupMap[img.ID], Size: img.Size, Comment: img.Comment, }) return nil }) return history, err } func (graph *Graph) GetParent(img *image.Image) (*image.Image, error) { if img.Parent == "" { return nil, nil } return graph.Get(img.Parent) } func (graph *Graph) GetParentsSize(img *image.Image, size int64) int64 { parentImage, err := graph.GetParent(img) if err != nil || parentImage == nil { return size } size += parentImage.Size return graph.GetParentsSize(parentImage, size) } ================================================ FILE: vendor/github.com/docker/docker/graph/import.go ================================================ package graph import ( "io" "net/http" "net/url" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/httputils" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) type ImageImportConfig struct { Changes []string InConfig io.ReadCloser OutStream io.Writer ContainerConfig *runconfig.Config } func (s *TagStore) Import(src string, repo string, tag string, imageImportConfig *ImageImportConfig) error { var ( sf = streamformatter.NewJSONStreamFormatter() archive archive.ArchiveReader resp *http.Response ) if src == "-" { archive = imageImportConfig.InConfig } else { u, err := url.Parse(src) if err != nil { return err } if u.Scheme == "" { u.Scheme = "http" u.Host = src u.Path = "" } imageImportConfig.OutStream.Write(sf.FormatStatus("", "Downloading from %s", u)) resp, err = httputils.Download(u.String()) if err != nil { return err } progressReader := progressreader.New(progressreader.Config{ In: resp.Body, Out: imageImportConfig.OutStream, Formatter: sf, Size: int(resp.ContentLength), NewLines: true, ID: "", Action: "Importing", }) defer progressReader.Close() archive = progressReader } img, err := s.graph.Create(archive, "", "", "Imported from "+src, "", nil, imageImportConfig.ContainerConfig) if err != nil { return err } // Optionally register the image at REPO/TAG if repo != "" { if err := s.Tag(repo, tag, img.ID, true); err != nil { return err } } imageImportConfig.OutStream.Write(sf.FormatStatus("", img.ID)) logID := img.ID if tag != "" { logID = utils.ImageReference(logID, tag) } s.eventsService.Log("import", logID, "") return nil } ================================================ FILE: vendor/github.com/docker/docker/graph/list.go ================================================ package graph import ( "fmt" "path" "sort" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" "github.com/docker/docker/image" "github.com/docker/docker/pkg/parsers/filters" "github.com/docker/docker/utils" ) var acceptedImageFilterTags = map[string]struct{}{ "dangling": {}, "label": {}, } type ImagesConfig struct { Filters string Filter string All bool } type ByCreated []*types.Image func (r ByCreated) Len() int { return len(r) } func (r ByCreated) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r ByCreated) Less(i, j int) bool { return r[i].Created < r[j].Created } func (s *TagStore) Images(config *ImagesConfig) ([]*types.Image, error) { var ( allImages map[string]*image.Image err error filtTagged = true filtLabel = false ) imageFilters, err := filters.FromParam(config.Filters) if err != nil { return nil, err } for name := range imageFilters { if _, ok := acceptedImageFilterTags[name]; !ok { return nil, fmt.Errorf("Invalid filter '%s'", name) } } if i, ok := imageFilters["dangling"]; ok { for _, value := range i { if strings.ToLower(value) == "true" { filtTagged = false } } } _, filtLabel = imageFilters["label"] if config.All && filtTagged { allImages = s.graph.Map() } else { allImages = s.graph.Heads() } lookup := make(map[string]*types.Image) s.Lock() for repoName, repository := range s.Repositories { if config.Filter != "" { if match, _ := path.Match(config.Filter, repoName); !match { continue } } for ref, id := range repository { imgRef := utils.ImageReference(repoName, ref) image, err := s.graph.Get(id) if err != nil { logrus.Warnf("couldn't load %s from %s: %s", id, imgRef, err) continue } if lImage, exists := lookup[id]; exists { if filtTagged { if utils.DigestReference(ref) { lImage.RepoDigests = append(lImage.RepoDigests, imgRef) } else { // Tag Ref. lImage.RepoTags = append(lImage.RepoTags, imgRef) } } } else { // get the boolean list for if only the untagged images are requested delete(allImages, id) if !imageFilters.MatchKVList("label", image.ContainerConfig.Labels) { continue } if filtTagged { newImage := new(types.Image) newImage.ParentId = image.Parent newImage.ID = image.ID newImage.Created = int(image.Created.Unix()) newImage.Size = int(image.Size) newImage.VirtualSize = int(s.graph.GetParentsSize(image, 0) + image.Size) newImage.Labels = image.ContainerConfig.Labels if utils.DigestReference(ref) { newImage.RepoTags = []string{} newImage.RepoDigests = []string{imgRef} } else { newImage.RepoTags = []string{imgRef} newImage.RepoDigests = []string{} } lookup[id] = newImage } } } } s.Unlock() images := []*types.Image{} for _, value := range lookup { images = append(images, value) } // Display images which aren't part of a repository/tag if config.Filter == "" || filtLabel { for _, image := range allImages { if !imageFilters.MatchKVList("label", image.ContainerConfig.Labels) { continue } newImage := new(types.Image) newImage.ParentId = image.Parent newImage.RepoTags = []string{":"} newImage.RepoDigests = []string{"@"} newImage.ID = image.ID newImage.Created = int(image.Created.Unix()) newImage.Size = int(image.Size) newImage.VirtualSize = int(s.graph.GetParentsSize(image, 0) + image.Size) newImage.Labels = image.ContainerConfig.Labels images = append(images, newImage) } } sort.Sort(sort.Reverse(ByCreated(images))) return images, nil } ================================================ FILE: vendor/github.com/docker/docker/graph/load.go ================================================ // +build linux windows package graph import ( "encoding/json" "io" "io/ioutil" "os" "path/filepath" "github.com/Sirupsen/logrus" "github.com/docker/docker/image" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" ) // Loads a set of images into the repository. This is the complementary of ImageExport. // The input stream is an uncompressed tar ball containing images and metadata. func (s *TagStore) Load(inTar io.ReadCloser, outStream io.Writer) error { tmpImageDir, err := ioutil.TempDir("", "docker-import-") if err != nil { return err } defer os.RemoveAll(tmpImageDir) var ( repoDir = filepath.Join(tmpImageDir, "repo") ) if err := os.Mkdir(repoDir, os.ModeDir); err != nil { return err } images := s.graph.Map() excludes := make([]string, len(images)) i := 0 for k := range images { excludes[i] = k i++ } if err := chrootarchive.Untar(inTar, repoDir, &archive.TarOptions{ExcludePatterns: excludes}); err != nil { return err } dirs, err := ioutil.ReadDir(repoDir) if err != nil { return err } for _, d := range dirs { if d.IsDir() { if err := s.recursiveLoad(d.Name(), tmpImageDir); err != nil { return err } } } reposJSONFile, err := os.Open(filepath.Join(tmpImageDir, "repo", "repositories")) if err != nil { if !os.IsNotExist(err) { return err } return nil } defer reposJSONFile.Close() repositories := map[string]Repository{} if err := json.NewDecoder(reposJSONFile).Decode(&repositories); err != nil { return err } for imageName, tagMap := range repositories { for tag, address := range tagMap { if err := s.SetLoad(imageName, tag, address, true, outStream); err != nil { return err } } } return nil } func (s *TagStore) recursiveLoad(address, tmpImageDir string) error { if _, err := s.LookupImage(address); err != nil { logrus.Debugf("Loading %s", address) imageJson, err := ioutil.ReadFile(filepath.Join(tmpImageDir, "repo", address, "json")) if err != nil { logrus.Debugf("Error reading json: %v", err) return err } layer, err := os.Open(filepath.Join(tmpImageDir, "repo", address, "layer.tar")) if err != nil { logrus.Debugf("Error reading embedded tar: %v", err) return err } img, err := image.NewImgJSON(imageJson) if err != nil { logrus.Debugf("Error unmarshalling json: %v", err) return err } if err := image.ValidateID(img.ID); err != nil { logrus.Debugf("Error validating ID: %v", err) return err } // ensure no two downloads of the same layer happen at the same time if c, err := s.poolAdd("pull", "layer:"+img.ID); err != nil { if c != nil { logrus.Debugf("Image (id: %s) load is already running, waiting: %v", img.ID, err) <-c return nil } return err } defer s.poolRemove("pull", "layer:"+img.ID) if img.Parent != "" { if !s.graph.Exists(img.Parent) { if err := s.recursiveLoad(img.Parent, tmpImageDir); err != nil { return err } } } if err := s.graph.Register(img, layer); err != nil { return err } } logrus.Debugf("Completed processing %s", address) return nil } ================================================ FILE: vendor/github.com/docker/docker/graph/load_unsupported.go ================================================ // +build !linux,!windows package graph import ( "fmt" "io" ) func (s *TagStore) Load(inTar io.ReadCloser, outStream io.Writer) error { return fmt.Errorf("Load is not supported on this platform") } ================================================ FILE: vendor/github.com/docker/docker/graph/mutex.go ================================================ package graph import "sync" // imageMutex provides a lock per image id to protect shared resources in the // graph. This is only used with registration but should be used when // manipulating the layer store. type imageMutex struct { mus map[string]*sync.Mutex // mutexes by image id. mu sync.Mutex // protects lock map // NOTE(stevvooe): The map above will grow to the size of all images ever // registered during a daemon run. To free these resources, we must // deallocate after unlock. Doing this safely is non-trivial in the face // of a very minor leak. } // Lock the provided id. func (im *imageMutex) Lock(id string) { im.getImageLock(id).Lock() } // Unlock the provided id. func (im *imageMutex) Unlock(id string) { im.getImageLock(id).Unlock() } // getImageLock returns the mutex for the given id. This method will never // return nil. func (im *imageMutex) getImageLock(id string) *sync.Mutex { im.mu.Lock() defer im.mu.Unlock() if im.mus == nil { // lazy im.mus = make(map[string]*sync.Mutex) } mu, ok := im.mus[id] if !ok { mu = new(sync.Mutex) im.mus[id] = mu } return mu } ================================================ FILE: vendor/github.com/docker/docker/graph/pools_test.go ================================================ package graph import ( "testing" "github.com/docker/docker/pkg/reexec" ) func init() { reexec.Init() } func TestPools(t *testing.T) { s := &TagStore{ pullingPool: make(map[string]chan struct{}), pushingPool: make(map[string]chan struct{}), } if _, err := s.poolAdd("pull", "test1"); err != nil { t.Fatal(err) } if _, err := s.poolAdd("pull", "test2"); err != nil { t.Fatal(err) } if _, err := s.poolAdd("push", "test1"); err == nil || err.Error() != "pull test1 is already in progress" { t.Fatalf("Expected `pull test1 is already in progress`") } if _, err := s.poolAdd("pull", "test1"); err == nil || err.Error() != "pull test1 is already in progress" { t.Fatalf("Expected `pull test1 is already in progress`") } if _, err := s.poolAdd("wait", "test3"); err == nil || err.Error() != "Unknown pool type" { t.Fatalf("Expected `Unknown pool type`") } if err := s.poolRemove("pull", "test2"); err != nil { t.Fatal(err) } if err := s.poolRemove("pull", "test2"); err != nil { t.Fatal(err) } if err := s.poolRemove("pull", "test1"); err != nil { t.Fatal(err) } if err := s.poolRemove("push", "test1"); err != nil { t.Fatal(err) } if err := s.poolRemove("wait", "test3"); err == nil || err.Error() != "Unknown pool type" { t.Fatalf("Expected `Unknown pool type`") } } ================================================ FILE: vendor/github.com/docker/docker/graph/pull.go ================================================ package graph import ( "fmt" "io" "github.com/Sirupsen/logrus" "github.com/docker/docker/cliconfig" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) type ImagePullConfig struct { MetaHeaders map[string][]string AuthConfig *cliconfig.AuthConfig OutStream io.Writer } type Puller interface { // Pull tries to pull the image referenced by `tag` // Pull returns an error if any, as well as a boolean that determines whether to retry Pull on the next configured endpoint. // // TODO(tiborvass): have Pull() take a reference to repository + tag, so that the puller itself is repository-agnostic. Pull(tag string) (fallback bool, err error) } func NewPuller(s *TagStore, endpoint registry.APIEndpoint, repoInfo *registry.RepositoryInfo, imagePullConfig *ImagePullConfig, sf *streamformatter.StreamFormatter) (Puller, error) { switch endpoint.Version { case registry.APIVersion2: return &v2Puller{ TagStore: s, endpoint: endpoint, config: imagePullConfig, sf: sf, repoInfo: repoInfo, }, nil case registry.APIVersion1: return &v1Puller{ TagStore: s, endpoint: endpoint, config: imagePullConfig, sf: sf, repoInfo: repoInfo, }, nil } return nil, fmt.Errorf("unknown version %d for registry %s", endpoint.Version, endpoint.URL) } func (s *TagStore) Pull(image string, tag string, imagePullConfig *ImagePullConfig) error { var sf = streamformatter.NewJSONStreamFormatter() // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := s.registryService.ResolveRepository(image) if err != nil { return err } // makes sure name is not empty or `scratch` if err := validateRepoName(repoInfo.LocalName); err != nil { return err } endpoints, err := s.registryService.LookupEndpoints(repoInfo.CanonicalName) if err != nil { return err } logName := repoInfo.LocalName if tag != "" { logName = utils.ImageReference(logName, tag) } var ( lastErr error // discardNoSupportErrors is used to track whether an endpoint encountered an error of type registry.ErrNoSupport // By default it is false, which means that if a ErrNoSupport error is encountered, it will be saved in lastErr. // As soon as another kind of error is encountered, discardNoSupportErrors is set to true, avoiding the saving of // any subsequent ErrNoSupport errors in lastErr. // It's needed for pull-by-digest on v1 endpoints: if there are only v1 endpoints configured, the error should be // returned and displayed, but if there was a v2 endpoint which supports pull-by-digest, then the last relevant // error is the ones from v2 endpoints not v1. discardNoSupportErrors bool ) for _, endpoint := range endpoints { logrus.Debugf("Trying to pull %s from %s %s", repoInfo.LocalName, endpoint.URL, endpoint.Version) if !endpoint.Mirror && (endpoint.Official || endpoint.Version == registry.APIVersion2) { if repoInfo.Official { s.trustService.UpdateBase() } } puller, err := NewPuller(s, endpoint, repoInfo, imagePullConfig, sf) if err != nil { lastErr = err continue } if fallback, err := puller.Pull(tag); err != nil { if fallback { if _, ok := err.(registry.ErrNoSupport); !ok { // Because we found an error that's not ErrNoSupport, discard all subsequent ErrNoSupport errors. discardNoSupportErrors = true // save the current error lastErr = err } else if !discardNoSupportErrors { // Save the ErrNoSupport error, because it's either the first error or all encountered errors // were also ErrNoSupport errors. lastErr = err } continue } logrus.Debugf("Not continuing with error: %v", err) return err } s.eventsService.Log("pull", logName, "") return nil } if lastErr == nil { lastErr = fmt.Errorf("no endpoints found for %s", image) } return lastErr } func WriteStatus(requestedTag string, out io.Writer, sf *streamformatter.StreamFormatter, layersDownloaded bool) { if layersDownloaded { out.Write(sf.FormatStatus("", "Status: Downloaded newer image for %s", requestedTag)) } else { out.Write(sf.FormatStatus("", "Status: Image is up to date for %s", requestedTag)) } } ================================================ FILE: vendor/github.com/docker/docker/graph/pull_v1.go ================================================ package graph import ( "errors" "fmt" "net" "net/url" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/image" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) type v1Puller struct { *TagStore endpoint registry.APIEndpoint config *ImagePullConfig sf *streamformatter.StreamFormatter repoInfo *registry.RepositoryInfo session *registry.Session } func (p *v1Puller) Pull(tag string) (fallback bool, err error) { if utils.DigestReference(tag) { // Allowing fallback, because HTTPS v1 is before HTTP v2 return true, registry.ErrNoSupport{errors.New("Cannot pull by digest with v1 registry")} } tlsConfig, err := p.registryService.TlsConfig(p.repoInfo.Index.Name) if err != nil { return false, err } // Adds Docker-specific headers as well as user-specified headers (metaHeaders) tr := transport.NewTransport( // TODO(tiborvass): was ReceiveTimeout registry.NewTransport(tlsConfig), registry.DockerHeaders(p.config.MetaHeaders)..., ) client := registry.HTTPClient(tr) v1Endpoint, err := p.endpoint.ToV1Endpoint(p.config.MetaHeaders) if err != nil { logrus.Debugf("Could not get v1 endpoint: %v", err) return true, err } p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint) if err != nil { // TODO(dmcgowan): Check if should fallback logrus.Debugf("Fallback from error: %s", err) return true, err } if err := p.pullRepository(tag); err != nil { // TODO(dmcgowan): Check if should fallback return false, err } return false, nil } func (p *v1Puller) pullRepository(askedTag string) error { out := p.config.OutStream out.Write(p.sf.FormatStatus("", "Pulling repository %s", p.repoInfo.CanonicalName)) repoData, err := p.session.GetRepositoryData(p.repoInfo.RemoteName) if err != nil { if strings.Contains(err.Error(), "HTTP code: 404") { return fmt.Errorf("Error: image %s not found", utils.ImageReference(p.repoInfo.RemoteName, askedTag)) } // Unexpected HTTP error return err } logrus.Debugf("Retrieving the tag list") tagsList := make(map[string]string) if askedTag == "" { tagsList, err = p.session.GetRemoteTags(repoData.Endpoints, p.repoInfo.RemoteName) } else { var tagId string tagId, err = p.session.GetRemoteTag(repoData.Endpoints, p.repoInfo.RemoteName, askedTag) tagsList[askedTag] = tagId } if err != nil { if err == registry.ErrRepoNotFound && askedTag != "" { return fmt.Errorf("Tag %s not found in repository %s", askedTag, p.repoInfo.CanonicalName) } logrus.Errorf("unable to get remote tags: %s", err) return err } for tag, id := range tagsList { repoData.ImgList[id] = ®istry.ImgData{ ID: id, Tag: tag, Checksum: "", } } logrus.Debugf("Registering tags") // If no tag has been specified, pull them all if askedTag == "" { for tag, id := range tagsList { repoData.ImgList[id].Tag = tag } } else { // Otherwise, check that the tag exists and use only that one id, exists := tagsList[askedTag] if !exists { return fmt.Errorf("Tag %s not found in repository %s", askedTag, p.repoInfo.CanonicalName) } repoData.ImgList[id].Tag = askedTag } errors := make(chan error) layersDownloaded := false imgIDs := []string{} sessionID := p.session.ID() defer func() { p.graph.Release(sessionID, imgIDs...) }() for _, image := range repoData.ImgList { downloadImage := func(img *registry.ImgData) { if askedTag != "" && img.Tag != askedTag { errors <- nil return } if img.Tag == "" { logrus.Debugf("Image (id: %s) present in this repository but untagged, skipping", img.ID) errors <- nil return } // ensure no two downloads of the same image happen at the same time if c, err := p.poolAdd("pull", "img:"+img.ID); err != nil { if c != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Layer already being pulled by another client. Waiting.", nil)) <-c out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) } else { logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", img.ID, err) } errors <- nil return } defer p.poolRemove("pull", "img:"+img.ID) // we need to retain it until tagging p.graph.Retain(sessionID, img.ID) imgIDs = append(imgIDs, img.ID) out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s", img.Tag, p.repoInfo.CanonicalName), nil)) success := false var lastErr, err error var isDownloaded bool for _, ep := range p.repoInfo.Index.Mirrors { ep += "v1/" out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, mirror: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil)) if isDownloaded, err = p.pullImage(img.ID, ep, repoData.Tokens); err != nil { // Don't report errors when pulling from mirrors. logrus.Debugf("Error pulling image (%s) from %s, mirror: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err) continue } layersDownloaded = layersDownloaded || isDownloaded success = true break } if !success { for _, ep := range repoData.Endpoints { out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Pulling image (%s) from %s, endpoint: %s", img.Tag, p.repoInfo.CanonicalName, ep), nil)) if isDownloaded, err = p.pullImage(img.ID, ep, repoData.Tokens); err != nil { // It's not ideal that only the last error is returned, it would be better to concatenate the errors. // As the error is also given to the output stream the user will see the error. lastErr = err out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), fmt.Sprintf("Error pulling image (%s) from %s, endpoint: %s, %s", img.Tag, p.repoInfo.CanonicalName, ep, err), nil)) continue } layersDownloaded = layersDownloaded || isDownloaded success = true break } } if !success { err := fmt.Errorf("Error pulling image (%s) from %s, %v", img.Tag, p.repoInfo.CanonicalName, lastErr) out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), err.Error(), nil)) errors <- err return } out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Download complete", nil)) errors <- nil } go downloadImage(image) } var lastError error for i := 0; i < len(repoData.ImgList); i++ { if err := <-errors; err != nil { lastError = err } } if lastError != nil { return lastError } for tag, id := range tagsList { if askedTag != "" && tag != askedTag { continue } if err := p.Tag(p.repoInfo.LocalName, tag, id, true); err != nil { return err } } requestedTag := p.repoInfo.LocalName if len(askedTag) > 0 { requestedTag = utils.ImageReference(p.repoInfo.LocalName, askedTag) } WriteStatus(requestedTag, out, p.sf, layersDownloaded) return nil } func (p *v1Puller) pullImage(imgID, endpoint string, token []string) (bool, error) { history, err := p.session.GetRemoteHistory(imgID, endpoint) if err != nil { return false, err } out := p.config.OutStream out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Pulling dependent layers", nil)) // FIXME: Try to stream the images? // FIXME: Launch the getRemoteImage() in goroutines sessionID := p.session.ID() // As imgID has been retained in pullRepository, no need to retain again p.graph.Retain(sessionID, history[1:]...) defer p.graph.Release(sessionID, history[1:]...) layersDownloaded := false for i := len(history) - 1; i >= 0; i-- { id := history[i] // ensure no two downloads of the same layer happen at the same time if c, err := p.poolAdd("pull", "layer:"+id); err != nil { logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", id, err) <-c } defer p.poolRemove("pull", "layer:"+id) if !p.graph.Exists(id) { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Pulling metadata", nil)) var ( imgJSON []byte imgSize int err error img *image.Image ) retries := 5 for j := 1; j <= retries; j++ { imgJSON, imgSize, err = p.session.GetRemoteImageJSON(id, endpoint) if err != nil && j == retries { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil)) return layersDownloaded, err } else if err != nil { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } img, err = image.NewImgJSON(imgJSON) layersDownloaded = true if err != nil && j == retries { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil)) return layersDownloaded, fmt.Errorf("Failed to parse json: %s", err) } else if err != nil { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } else { break } } for j := 1; j <= retries; j++ { // Get the layer status := "Pulling fs layer" if j > 1 { status = fmt.Sprintf("Pulling fs layer [retries: %d]", j) } out.Write(p.sf.FormatProgress(stringid.TruncateID(id), status, nil)) layer, err := p.session.GetRemoteImageLayer(img.ID, endpoint, int64(imgSize)) if uerr, ok := err.(*url.Error); ok { err = uerr.Err } if terr, ok := err.(net.Error); ok && terr.Timeout() && j < retries { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } else if err != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error pulling dependent layers", nil)) return layersDownloaded, err } layersDownloaded = true defer layer.Close() err = p.graph.Register(img, progressreader.New(progressreader.Config{ In: layer, Out: out, Formatter: p.sf, Size: imgSize, NewLines: false, ID: stringid.TruncateID(id), Action: "Downloading", })) if terr, ok := err.(net.Error); ok && terr.Timeout() && j < retries { time.Sleep(time.Duration(j) * 500 * time.Millisecond) continue } else if err != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Error downloading dependent layers", nil)) return layersDownloaded, err } else { break } } } out.Write(p.sf.FormatProgress(stringid.TruncateID(id), "Download complete", nil)) } return layersDownloaded, nil } ================================================ FILE: vendor/github.com/docker/docker/graph/pull_v2.go ================================================ package graph import ( "fmt" "io" "io/ioutil" "os" "github.com/Sirupsen/logrus" "github.com/docker/distribution" "github.com/docker/distribution/digest" "github.com/docker/distribution/manifest" "github.com/docker/docker/image" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" "github.com/docker/docker/trust" "github.com/docker/docker/utils" "github.com/docker/libtrust" ) type v2Puller struct { *TagStore endpoint registry.APIEndpoint config *ImagePullConfig sf *streamformatter.StreamFormatter repoInfo *registry.RepositoryInfo repo distribution.Repository sessionID string } func (p *v2Puller) Pull(tag string) (fallback bool, err error) { // TODO(tiborvass): was ReceiveTimeout p.repo, err = NewV2Repository(p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig) if err != nil { logrus.Debugf("Error getting v2 registry: %v", err) return true, err } p.sessionID = stringid.GenerateRandomID() if err := p.pullV2Repository(tag); err != nil { if registry.ContinueOnError(err) { logrus.Debugf("Error trying v2 registry: %v", err) return true, err } return false, err } return false, nil } func (p *v2Puller) pullV2Repository(tag string) (err error) { var tags []string taggedName := p.repoInfo.LocalName if len(tag) > 0 { tags = []string{tag} taggedName = utils.ImageReference(p.repoInfo.LocalName, tag) } else { var err error tags, err = p.repo.Manifests().Tags() if err != nil { return err } } c, err := p.poolAdd("pull", taggedName) if err != nil { if c != nil { // Another pull of the same repository is already taking place; just wait for it to finish p.sf.FormatStatus("", "Repository %s already being pulled by another client. Waiting.", p.repoInfo.CanonicalName) <-c return nil } return err } defer p.poolRemove("pull", taggedName) var layersDownloaded bool for _, tag := range tags { // pulledNew is true if either new layers were downloaded OR if existing images were newly tagged // TODO(tiborvass): should we change the name of `layersDownload`? What about message in WriteStatus? pulledNew, err := p.pullV2Tag(tag, taggedName) if err != nil { return err } layersDownloaded = layersDownloaded || pulledNew } WriteStatus(taggedName, p.config.OutStream, p.sf, layersDownloaded) return nil } // downloadInfo is used to pass information from download to extractor type downloadInfo struct { img *image.Image tmpFile *os.File digest digest.Digest layer distribution.ReadSeekCloser size int64 err chan error verified bool } type errVerification struct{} func (errVerification) Error() string { return "verification failed" } func (p *v2Puller) download(di *downloadInfo) { logrus.Debugf("pulling blob %q to %s", di.digest, di.img.ID) out := p.config.OutStream if c, err := p.poolAdd("pull", "img:"+di.img.ID); err != nil { if c != nil { out.Write(p.sf.FormatProgress(stringid.TruncateID(di.img.ID), "Layer already being pulled by another client. Waiting.", nil)) <-c out.Write(p.sf.FormatProgress(stringid.TruncateID(di.img.ID), "Download complete", nil)) } else { logrus.Debugf("Image (id: %s) pull is already running, skipping: %v", di.img.ID, err) } di.err <- nil return } defer p.poolRemove("pull", "img:"+di.img.ID) tmpFile, err := ioutil.TempFile("", "GetImageBlob") if err != nil { di.err <- err return } blobs := p.repo.Blobs(nil) desc, err := blobs.Stat(nil, di.digest) if err != nil { logrus.Debugf("Error statting layer: %v", err) di.err <- err return } di.size = desc.Length layerDownload, err := blobs.Open(nil, di.digest) if err != nil { logrus.Debugf("Error fetching layer: %v", err) di.err <- err return } defer layerDownload.Close() verifier, err := digest.NewDigestVerifier(di.digest) if err != nil { di.err <- err return } reader := progressreader.New(progressreader.Config{ In: ioutil.NopCloser(io.TeeReader(layerDownload, verifier)), Out: out, Formatter: p.sf, Size: int(di.size), NewLines: false, ID: stringid.TruncateID(di.img.ID), Action: "Downloading", }) io.Copy(tmpFile, reader) out.Write(p.sf.FormatProgress(stringid.TruncateID(di.img.ID), "Verifying Checksum", nil)) di.verified = verifier.Verified() if !di.verified { logrus.Infof("Image verification failed for layer %s", di.digest) } out.Write(p.sf.FormatProgress(stringid.TruncateID(di.img.ID), "Download complete", nil)) logrus.Debugf("Downloaded %s to tempfile %s", di.img.ID, tmpFile.Name()) di.tmpFile = tmpFile di.layer = layerDownload di.err <- nil } func (p *v2Puller) pullV2Tag(tag, taggedName string) (bool, error) { logrus.Debugf("Pulling tag from V2 registry: %q", tag) out := p.config.OutStream manifest, err := p.repo.Manifests().GetByTag(tag) if err != nil { return false, err } verified, err := p.validateManifest(manifest, tag) if err != nil { return false, err } if verified { logrus.Printf("Image manifest for %s has been verified", taggedName) } out.Write(p.sf.FormatStatus(tag, "Pulling from %s", p.repo.Name())) downloads := make([]downloadInfo, len(manifest.FSLayers)) layerIDs := []string{} defer func() { p.graph.Release(p.sessionID, layerIDs...) }() for i := len(manifest.FSLayers) - 1; i >= 0; i-- { img, err := image.NewImgJSON([]byte(manifest.History[i].V1Compatibility)) if err != nil { logrus.Debugf("error getting image v1 json: %v", err) return false, err } downloads[i].img = img downloads[i].digest = manifest.FSLayers[i].BlobSum p.graph.Retain(p.sessionID, img.ID) layerIDs = append(layerIDs, img.ID) // Check if exists if p.graph.Exists(img.ID) { logrus.Debugf("Image already exists: %s", img.ID) continue } out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Pulling fs layer", nil)) downloads[i].err = make(chan error) go p.download(&downloads[i]) } var tagUpdated bool for i := len(downloads) - 1; i >= 0; i-- { d := &downloads[i] if d.err != nil { if err := <-d.err; err != nil { return false, err } } verified = verified && d.verified if d.layer != nil { // if tmpFile is empty assume download and extracted elsewhere defer os.Remove(d.tmpFile.Name()) defer d.tmpFile.Close() d.tmpFile.Seek(0, 0) if d.tmpFile != nil { reader := progressreader.New(progressreader.Config{ In: d.tmpFile, Out: out, Formatter: p.sf, Size: int(d.size), NewLines: false, ID: stringid.TruncateID(d.img.ID), Action: "Extracting", }) err = p.graph.Register(d.img, reader) if err != nil { return false, err } if err := p.graph.SetDigest(d.img.ID, d.digest); err != nil { return false, err } // FIXME: Pool release here for parallel tag pull (ensures any downloads block until fully extracted) } out.Write(p.sf.FormatProgress(stringid.TruncateID(d.img.ID), "Pull complete", nil)) tagUpdated = true } else { out.Write(p.sf.FormatProgress(stringid.TruncateID(d.img.ID), "Already exists", nil)) } } manifestDigest, err := digestFromManifest(manifest, p.repoInfo.LocalName) if err != nil { return false, err } // Check for new tag if no layers downloaded if !tagUpdated { repo, err := p.Get(p.repoInfo.LocalName) if err != nil { return false, err } if repo != nil { if _, exists := repo[tag]; !exists { tagUpdated = true } } else { tagUpdated = true } } if verified && tagUpdated { out.Write(p.sf.FormatStatus(p.repo.Name()+":"+tag, "The image you are pulling has been verified. Important: image verification is a tech preview feature and should not be relied on to provide security.")) } if utils.DigestReference(tag) { // TODO(stevvooe): Ideally, we should always set the digest so we can // use the digest whether we pull by it or not. Unfortunately, the tag // store treats the digest as a separate tag, meaning there may be an // untagged digest image that would seem to be dangling by a user. if err = p.SetDigest(p.repoInfo.LocalName, tag, downloads[0].img.ID); err != nil { return false, err } } else { // only set the repository/tag -> image ID mapping when pulling by tag (i.e. not by digest) if err = p.Tag(p.repoInfo.LocalName, tag, downloads[0].img.ID, true); err != nil { return false, err } } if manifestDigest != "" { out.Write(p.sf.FormatStatus("", "Digest: %s", manifestDigest)) } return tagUpdated, nil } // verifyTrustedKeys checks the keys provided against the trust store, // ensuring that the provided keys are trusted for the namespace. The keys // provided from this method must come from the signatures provided as part of // the manifest JWS package, obtained from unpackSignedManifest or libtrust. func (p *v2Puller) verifyTrustedKeys(namespace string, keys []libtrust.PublicKey) (verified bool, err error) { if namespace[0] != '/' { namespace = "/" + namespace } for _, key := range keys { b, err := key.MarshalJSON() if err != nil { return false, fmt.Errorf("error marshalling public key: %s", err) } // Check key has read/write permission (0x03) v, err := p.trustService.CheckKey(namespace, b, 0x03) if err != nil { vErr, ok := err.(trust.NotVerifiedError) if !ok { return false, fmt.Errorf("error running key check: %s", err) } logrus.Debugf("Key check result: %v", vErr) } verified = v } if verified { logrus.Debug("Key check result: verified") } return } func (p *v2Puller) validateManifest(m *manifest.SignedManifest, tag string) (verified bool, err error) { // TODO(tiborvass): what's the usecase for having manifest == nil and err == nil ? Shouldn't be the error be "DoesNotExist" ? if m == nil { return false, fmt.Errorf("image manifest does not exist for tag %q", tag) } if m.SchemaVersion != 1 { return false, fmt.Errorf("unsupported schema version %d for tag %q", m.SchemaVersion, tag) } if len(m.FSLayers) != len(m.History) { return false, fmt.Errorf("length of history not equal to number of layers for tag %q", tag) } if len(m.FSLayers) == 0 { return false, fmt.Errorf("no FSLayers in manifest for tag %q", tag) } keys, err := manifest.Verify(m) if err != nil { return false, fmt.Errorf("error verifying manifest for tag %q: %v", tag, err) } verified, err = p.verifyTrustedKeys(m.Name, keys) if err != nil { return false, fmt.Errorf("error verifying manifest keys: %v", err) } localDigest, err := digest.ParseDigest(tag) // if pull by digest, then verify if err == nil { verifier, err := digest.NewDigestVerifier(localDigest) if err != nil { return false, err } payload, err := m.Payload() if err != nil { return false, err } if _, err := verifier.Write(payload); err != nil { return false, err } verified = verified && verifier.Verified() } return verified, nil } ================================================ FILE: vendor/github.com/docker/docker/graph/push.go ================================================ package graph import ( "fmt" "io" "github.com/Sirupsen/logrus" "github.com/docker/docker/cliconfig" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/registry" ) type ImagePushConfig struct { MetaHeaders map[string][]string AuthConfig *cliconfig.AuthConfig Tag string OutStream io.Writer } type Pusher interface { // Push tries to push the image configured at the creation of Pusher. // Push returns an error if any, as well as a boolean that determines whether to retry Push on the next configured endpoint. // // TODO(tiborvass): have Push() take a reference to repository + tag, so that the pusher itself is repository-agnostic. Push() (fallback bool, err error) } func (s *TagStore) NewPusher(endpoint registry.APIEndpoint, localRepo Repository, repoInfo *registry.RepositoryInfo, imagePushConfig *ImagePushConfig, sf *streamformatter.StreamFormatter) (Pusher, error) { switch endpoint.Version { case registry.APIVersion2: return &v2Pusher{ TagStore: s, endpoint: endpoint, localRepo: localRepo, repoInfo: repoInfo, config: imagePushConfig, sf: sf, }, nil case registry.APIVersion1: return &v1Pusher{ TagStore: s, endpoint: endpoint, localRepo: localRepo, repoInfo: repoInfo, config: imagePushConfig, sf: sf, }, nil } return nil, fmt.Errorf("unknown version %d for registry %s", endpoint.Version, endpoint.URL) } // FIXME: Allow to interrupt current push when new push of same image is done. func (s *TagStore) Push(localName string, imagePushConfig *ImagePushConfig) error { var sf = streamformatter.NewJSONStreamFormatter() // Resolve the Repository name from fqn to RepositoryInfo repoInfo, err := s.registryService.ResolveRepository(localName) if err != nil { return err } endpoints, err := s.registryService.LookupEndpoints(repoInfo.CanonicalName) if err != nil { return err } reposLen := 1 if imagePushConfig.Tag == "" { reposLen = len(s.Repositories[repoInfo.LocalName]) } imagePushConfig.OutStream.Write(sf.FormatStatus("", "The push refers to a repository [%s] (len: %d)", repoInfo.CanonicalName, reposLen)) // If it fails, try to get the repository localRepo, exists := s.Repositories[repoInfo.LocalName] if !exists { return fmt.Errorf("Repository does not exist: %s", repoInfo.LocalName) } var lastErr error for _, endpoint := range endpoints { logrus.Debugf("Trying to push %s to %s %s", repoInfo.CanonicalName, endpoint.URL, endpoint.Version) pusher, err := s.NewPusher(endpoint, localRepo, repoInfo, imagePushConfig, sf) if err != nil { lastErr = err continue } if fallback, err := pusher.Push(); err != nil { if fallback { lastErr = err continue } logrus.Debugf("Not continuing with error: %v", err) return err } s.eventsService.Log("push", repoInfo.LocalName, "") return nil } if lastErr == nil { lastErr = fmt.Errorf("no endpoints found for %s", repoInfo.CanonicalName) } return lastErr } ================================================ FILE: vendor/github.com/docker/docker/graph/push_v1.go ================================================ package graph import ( "fmt" "io" "os" "sync" "github.com/Sirupsen/logrus" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" "github.com/docker/docker/utils" ) type v1Pusher struct { *TagStore endpoint registry.APIEndpoint localRepo Repository repoInfo *registry.RepositoryInfo config *ImagePushConfig sf *streamformatter.StreamFormatter session *registry.Session out io.Writer } func (p *v1Pusher) Push() (fallback bool, err error) { tlsConfig, err := p.registryService.TlsConfig(p.repoInfo.Index.Name) if err != nil { return false, err } // Adds Docker-specific headers as well as user-specified headers (metaHeaders) tr := transport.NewTransport( // TODO(tiborvass): was NoTimeout registry.NewTransport(tlsConfig), registry.DockerHeaders(p.config.MetaHeaders)..., ) client := registry.HTTPClient(tr) v1Endpoint, err := p.endpoint.ToV1Endpoint(p.config.MetaHeaders) if err != nil { logrus.Debugf("Could not get v1 endpoint: %v", err) return true, err } p.session, err = registry.NewSession(client, p.config.AuthConfig, v1Endpoint) if err != nil { // TODO(dmcgowan): Check if should fallback return true, err } if err := p.pushRepository(p.config.Tag); err != nil { // TODO(dmcgowan): Check if should fallback return false, err } return false, nil } // Retrieve the all the images to be uploaded in the correct order func (p *v1Pusher) getImageList(requestedTag string) ([]string, map[string][]string, error) { var ( imageList []string imagesSeen = make(map[string]bool) tagsByImage = make(map[string][]string) ) for tag, id := range p.localRepo { if requestedTag != "" && requestedTag != tag { // Include only the requested tag. continue } if utils.DigestReference(tag) { // Ignore digest references. continue } var imageListForThisTag []string tagsByImage[id] = append(tagsByImage[id], tag) for img, err := p.graph.Get(id); img != nil; img, err = p.graph.GetParent(img) { if err != nil { return nil, nil, err } if imagesSeen[img.ID] { // This image is already on the list, we can ignore it and all its parents break } imagesSeen[img.ID] = true imageListForThisTag = append(imageListForThisTag, img.ID) } // reverse the image list for this tag (so the "most"-parent image is first) for i, j := 0, len(imageListForThisTag)-1; i < j; i, j = i+1, j-1 { imageListForThisTag[i], imageListForThisTag[j] = imageListForThisTag[j], imageListForThisTag[i] } // append to main image list imageList = append(imageList, imageListForThisTag...) } if len(imageList) == 0 { return nil, nil, fmt.Errorf("No images found for the requested repository / tag") } logrus.Debugf("Image list: %v", imageList) logrus.Debugf("Tags by image: %v", tagsByImage) return imageList, tagsByImage, nil } // createImageIndex returns an index of an image's layer IDs and tags. func (s *TagStore) createImageIndex(images []string, tags map[string][]string) []*registry.ImgData { var imageIndex []*registry.ImgData for _, id := range images { if tags, hasTags := tags[id]; hasTags { // If an image has tags you must add an entry in the image index // for each tag for _, tag := range tags { imageIndex = append(imageIndex, ®istry.ImgData{ ID: id, Tag: tag, }) } continue } // If the image does not have a tag it still needs to be sent to the // registry with an empty tag so that it is accociated with the repository imageIndex = append(imageIndex, ®istry.ImgData{ ID: id, Tag: "", }) } return imageIndex } type imagePushData struct { id string endpoint string tokens []string } // lookupImageOnEndpoint checks the specified endpoint to see if an image exists // and if it is absent then it sends the image id to the channel to be pushed. func (p *v1Pusher) lookupImageOnEndpoint(wg *sync.WaitGroup, images chan imagePushData, imagesToPush chan string) { defer wg.Done() for image := range images { if err := p.session.LookupRemoteImage(image.id, image.endpoint); err != nil { logrus.Errorf("Error in LookupRemoteImage: %s", err) imagesToPush <- image.id continue } p.out.Write(p.sf.FormatStatus("", "Image %s already pushed, skipping", stringid.TruncateID(image.id))) } } func (p *v1Pusher) pushImageToEndpoint(endpoint string, imageIDs []string, tags map[string][]string, repo *registry.RepositoryData) error { workerCount := len(imageIDs) // start a maximum of 5 workers to check if images exist on the specified endpoint. if workerCount > 5 { workerCount = 5 } var ( wg = &sync.WaitGroup{} imageData = make(chan imagePushData, workerCount*2) imagesToPush = make(chan string, workerCount*2) pushes = make(chan map[string]struct{}, 1) ) for i := 0; i < workerCount; i++ { wg.Add(1) go p.lookupImageOnEndpoint(wg, imageData, imagesToPush) } // start a go routine that consumes the images to push go func() { shouldPush := make(map[string]struct{}) for id := range imagesToPush { shouldPush[id] = struct{}{} } pushes <- shouldPush }() for _, id := range imageIDs { imageData <- imagePushData{ id: id, endpoint: endpoint, tokens: repo.Tokens, } } // close the channel to notify the workers that there will be no more images to check. close(imageData) wg.Wait() close(imagesToPush) // wait for all the images that require pushes to be collected into a consumable map. shouldPush := <-pushes // finish by pushing any images and tags to the endpoint. The order that the images are pushed // is very important that is why we are still iterating over the ordered list of imageIDs. for _, id := range imageIDs { if _, push := shouldPush[id]; push { if _, err := p.pushImage(id, endpoint, repo.Tokens); err != nil { // FIXME: Continue on error? return err } } for _, tag := range tags[id] { p.out.Write(p.sf.FormatStatus("", "Pushing tag for rev [%s] on {%s}", stringid.TruncateID(id), endpoint+"repositories/"+p.repoInfo.RemoteName+"/tags/"+tag)) if err := p.session.PushRegistryTag(p.repoInfo.RemoteName, id, tag, endpoint); err != nil { return err } } } return nil } // pushRepository pushes layers that do not already exist on the registry. func (p *v1Pusher) pushRepository(tag string) error { logrus.Debugf("Local repo: %s", p.localRepo) p.out = ioutils.NewWriteFlusher(p.config.OutStream) imgList, tags, err := p.getImageList(tag) if err != nil { return err } p.out.Write(p.sf.FormatStatus("", "Sending image list")) imageIndex := p.createImageIndex(imgList, tags) logrus.Debugf("Preparing to push %s with the following images and tags", p.localRepo) for _, data := range imageIndex { logrus.Debugf("Pushing ID: %s with Tag: %s", data.ID, data.Tag) } if _, err := p.poolAdd("push", p.repoInfo.LocalName); err != nil { return err } defer p.poolRemove("push", p.repoInfo.LocalName) // Register all the images in a repository with the registry // If an image is not in this list it will not be associated with the repository repoData, err := p.session.PushImageJSONIndex(p.repoInfo.RemoteName, imageIndex, false, nil) if err != nil { return err } nTag := 1 if tag == "" { nTag = len(p.localRepo) } p.out.Write(p.sf.FormatStatus("", "Pushing repository %s (%d tags)", p.repoInfo.CanonicalName, nTag)) // push the repository to each of the endpoints only if it does not exist. for _, endpoint := range repoData.Endpoints { if err := p.pushImageToEndpoint(endpoint, imgList, tags, repoData); err != nil { return err } } _, err = p.session.PushImageJSONIndex(p.repoInfo.RemoteName, imageIndex, true, repoData.Endpoints) return err } func (p *v1Pusher) pushImage(imgID, ep string, token []string) (checksum string, err error) { jsonRaw, err := p.graph.RawJSON(imgID) if err != nil { return "", fmt.Errorf("Cannot retrieve the path for {%s}: %s", imgID, err) } p.out.Write(p.sf.FormatProgress(stringid.TruncateID(imgID), "Pushing", nil)) imgData := ®istry.ImgData{ ID: imgID, } // Send the json if err := p.session.PushImageJSONRegistry(imgData, jsonRaw, ep); err != nil { if err == registry.ErrAlreadyExists { p.out.Write(p.sf.FormatProgress(stringid.TruncateID(imgData.ID), "Image already pushed, skipping", nil)) return "", nil } return "", err } layerData, err := p.graph.TempLayerArchive(imgID, p.sf, p.out) if err != nil { return "", fmt.Errorf("Failed to generate layer archive: %s", err) } defer os.RemoveAll(layerData.Name()) // Send the layer logrus.Debugf("rendered layer for %s of [%d] size", imgData.ID, layerData.Size) checksum, checksumPayload, err := p.session.PushImageLayerRegistry(imgData.ID, progressreader.New(progressreader.Config{ In: layerData, Out: p.out, Formatter: p.sf, Size: int(layerData.Size), NewLines: false, ID: stringid.TruncateID(imgData.ID), Action: "Pushing", }), ep, jsonRaw) if err != nil { return "", err } imgData.Checksum = checksum imgData.ChecksumPayload = checksumPayload // Send the checksum if err := p.session.PushImageChecksumRegistry(imgData, ep); err != nil { return "", err } p.out.Write(p.sf.FormatProgress(stringid.TruncateID(imgData.ID), "Image successfully pushed", nil)) return imgData.Checksum, nil } ================================================ FILE: vendor/github.com/docker/docker/graph/push_v2.go ================================================ package graph import ( "fmt" "io/ioutil" "os" "github.com/Sirupsen/logrus" "github.com/docker/distribution" "github.com/docker/distribution/digest" "github.com/docker/distribution/manifest" "github.com/docker/docker/image" "github.com/docker/docker/pkg/progressreader" "github.com/docker/docker/pkg/streamformatter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" "github.com/docker/docker/runconfig" "github.com/docker/docker/utils" ) type v2Pusher struct { *TagStore endpoint registry.APIEndpoint localRepo Repository repoInfo *registry.RepositoryInfo config *ImagePushConfig sf *streamformatter.StreamFormatter repo distribution.Repository } func (p *v2Pusher) Push() (fallback bool, err error) { p.repo, err = NewV2Repository(p.repoInfo, p.endpoint, p.config.MetaHeaders, p.config.AuthConfig) if err != nil { logrus.Debugf("Error getting v2 registry: %v", err) return true, err } return false, p.pushV2Repository(p.config.Tag) } func (p *v2Pusher) getImageTags(askedTag string) ([]string, error) { logrus.Debugf("Checking %q against %#v", askedTag, p.localRepo) if len(askedTag) > 0 { if _, ok := p.localRepo[askedTag]; !ok || utils.DigestReference(askedTag) { return nil, fmt.Errorf("Tag does not exist for %s", askedTag) } return []string{askedTag}, nil } var tags []string for tag := range p.localRepo { if !utils.DigestReference(tag) { tags = append(tags, tag) } } return tags, nil } func (p *v2Pusher) pushV2Repository(tag string) error { localName := p.repoInfo.LocalName if _, err := p.poolAdd("push", localName); err != nil { return err } defer p.poolRemove("push", localName) tags, err := p.getImageTags(tag) if err != nil { return fmt.Errorf("error getting tags for %s: %s", localName, err) } if len(tags) == 0 { return fmt.Errorf("no tags to push for %s", localName) } for _, tag := range tags { if err := p.pushV2Tag(tag); err != nil { return err } } return nil } func (p *v2Pusher) pushV2Tag(tag string) error { logrus.Debugf("Pushing repository: %s:%s", p.repo.Name(), tag) layerId, exists := p.localRepo[tag] if !exists { return fmt.Errorf("tag does not exist: %s", tag) } layersSeen := make(map[string]bool) layer, err := p.graph.Get(layerId) if err != nil { return err } m := &manifest.Manifest{ Versioned: manifest.Versioned{ SchemaVersion: 1, }, Name: p.repo.Name(), Tag: tag, Architecture: layer.Architecture, FSLayers: []manifest.FSLayer{}, History: []manifest.History{}, } var metadata runconfig.Config if layer != nil && layer.Config != nil { metadata = *layer.Config } out := p.config.OutStream for ; layer != nil; layer, err = p.graph.GetParent(layer) { if err != nil { return err } if layersSeen[layer.ID] { break } logrus.Debugf("Pushing layer: %s", layer.ID) if layer.Config != nil && metadata.Image != layer.ID { if err := runconfig.Merge(&metadata, layer.Config); err != nil { return err } } jsonData, err := p.graph.RawJSON(layer.ID) if err != nil { return fmt.Errorf("cannot retrieve the path for %s: %s", layer.ID, err) } var exists bool dgst, err := p.graph.GetDigest(layer.ID) switch err { case nil: _, err := p.repo.Blobs(nil).Stat(nil, dgst) switch err { case nil: exists = true out.Write(p.sf.FormatProgress(stringid.TruncateID(layer.ID), "Image already exists", nil)) case distribution.ErrBlobUnknown: // nop default: out.Write(p.sf.FormatProgress(stringid.TruncateID(layer.ID), "Image push failed", nil)) return err } case ErrDigestNotSet: // nop case digest.ErrDigestInvalidFormat, digest.ErrDigestUnsupported: return fmt.Errorf("error getting image checksum: %v", err) } // if digest was empty or not saved, or if blob does not exist on the remote repository, // then fetch it. if !exists { if pushDigest, err := p.pushV2Image(p.repo.Blobs(nil), layer); err != nil { return err } else if pushDigest != dgst { // Cache new checksum if err := p.graph.SetDigest(layer.ID, pushDigest); err != nil { return err } dgst = pushDigest } } m.FSLayers = append(m.FSLayers, manifest.FSLayer{BlobSum: dgst}) m.History = append(m.History, manifest.History{V1Compatibility: string(jsonData)}) layersSeen[layer.ID] = true } logrus.Infof("Signed manifest for %s:%s using daemon's key: %s", p.repo.Name(), tag, p.trustKey.KeyID()) signed, err := manifest.Sign(m, p.trustKey) if err != nil { return err } manifestDigest, err := digestFromManifest(signed, p.repo.Name()) if err != nil { return err } if manifestDigest != "" { out.Write(p.sf.FormatStatus("", "Digest: %s", manifestDigest)) } return p.repo.Manifests().Put(signed) } func (p *v2Pusher) pushV2Image(bs distribution.BlobService, img *image.Image) (digest.Digest, error) { out := p.config.OutStream out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Buffering to Disk", nil)) image, err := p.graph.Get(img.ID) if err != nil { return "", err } arch, err := p.graph.TarLayer(image) if err != nil { return "", err } tf, err := p.graph.newTempFile() if err != nil { return "", err } defer func() { tf.Close() os.Remove(tf.Name()) }() size, dgst, err := bufferToFile(tf, arch) if err != nil { return "", err } // Send the layer logrus.Debugf("rendered layer for %s of [%d] size", img.ID, size) layerUpload, err := bs.Create(nil) if err != nil { return "", err } defer layerUpload.Close() reader := progressreader.New(progressreader.Config{ In: ioutil.NopCloser(tf), Out: out, Formatter: p.sf, Size: int(size), NewLines: false, ID: stringid.TruncateID(img.ID), Action: "Pushing", }) n, err := layerUpload.ReadFrom(reader) if err != nil { return "", err } if n != size { return "", fmt.Errorf("short upload: only wrote %d of %d", n, size) } desc := distribution.Descriptor{Digest: dgst} if _, err := layerUpload.Commit(nil, desc); err != nil { return "", err } out.Write(p.sf.FormatProgress(stringid.TruncateID(img.ID), "Image successfully pushed", nil)) return dgst, nil } ================================================ FILE: vendor/github.com/docker/docker/graph/registry.go ================================================ package graph import ( "errors" "net" "net/http" "net/url" "time" "github.com/Sirupsen/logrus" "github.com/docker/distribution" "github.com/docker/distribution/digest" "github.com/docker/distribution/manifest" "github.com/docker/distribution/registry/client" "github.com/docker/distribution/registry/client/auth" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/cliconfig" "github.com/docker/docker/registry" "golang.org/x/net/context" ) type dumbCredentialStore struct { auth *cliconfig.AuthConfig } func (dcs dumbCredentialStore) Basic(*url.URL) (string, string) { return dcs.auth.Username, dcs.auth.Password } // v2 only func NewV2Repository(repoInfo *registry.RepositoryInfo, endpoint registry.APIEndpoint, metaHeaders http.Header, authConfig *cliconfig.AuthConfig) (distribution.Repository, error) { ctx := context.Background() repoName := repoInfo.CanonicalName // If endpoint does not support CanonicalName, use the RemoteName instead if endpoint.TrimHostname { repoName = repoInfo.RemoteName } // TODO(dmcgowan): Call close idle connections when complete, use keep alive 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: endpoint.TLSConfig, // TODO(dmcgowan): Call close idle connections when complete and use keep alive DisableKeepAlives: true, } modifiers := registry.DockerHeaders(metaHeaders) authTransport := transport.NewTransport(base, modifiers...) pingClient := &http.Client{ Transport: authTransport, Timeout: 5 * time.Second, } endpointStr := endpoint.URL + "/v2/" req, err := http.NewRequest("GET", endpointStr, nil) if err != nil { return nil, err } resp, err := pingClient.Do(req) if err != nil { return nil, err } defer resp.Body.Close() versions := auth.APIVersions(resp, endpoint.VersionHeader) if endpoint.VersionHeader != "" && len(endpoint.Versions) > 0 { var foundVersion bool for _, version := range endpoint.Versions { for _, pingVersion := range versions { if version == pingVersion { foundVersion = true } } } if !foundVersion { return nil, errors.New("endpoint does not support v2 API") } } challengeManager := auth.NewSimpleChallengeManager() if err := challengeManager.AddResponse(resp); err != nil { return nil, err } creds := dumbCredentialStore{auth: authConfig} tokenHandler := auth.NewTokenHandler(authTransport, creds, repoName, "push", "pull") basicHandler := auth.NewBasicHandler(creds) modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) tr := transport.NewTransport(base, modifiers...) return client.NewRepository(ctx, repoName, endpoint.URL, tr) } func digestFromManifest(m *manifest.SignedManifest, localName string) (digest.Digest, error) { payload, err := m.Payload() if err != nil { logrus.Debugf("could not retrieve manifest payload: %v", err) return "", err } manifestDigest, err := digest.FromBytes(payload) if err != nil { logrus.Infof("Could not compute manifest digest for %s:%s : %v", localName, m.Tag, err) } return manifestDigest, nil } ================================================ FILE: vendor/github.com/docker/docker/graph/service.go ================================================ package graph import ( "fmt" "io" "runtime" "github.com/Sirupsen/logrus" "github.com/docker/docker/api/types" ) func (s *TagStore) LookupRaw(name string) ([]byte, error) { image, err := s.LookupImage(name) if err != nil || image == nil { return nil, fmt.Errorf("No such image %s", name) } imageInspectRaw, err := s.graph.RawJSON(image.ID) if err != nil { return nil, err } return imageInspectRaw, nil } // Lookup return an image encoded in JSON func (s *TagStore) Lookup(name string) (*types.ImageInspect, error) { image, err := s.LookupImage(name) if err != nil || image == nil { return nil, fmt.Errorf("No such image: %s", name) } imageInspect := &types.ImageInspect{ Id: image.ID, Parent: image.Parent, Comment: image.Comment, Created: image.Created, Container: image.Container, ContainerConfig: &image.ContainerConfig, DockerVersion: image.DockerVersion, Author: image.Author, Config: image.Config, Architecture: image.Architecture, Os: image.OS, Size: image.Size, VirtualSize: s.graph.GetParentsSize(image, 0) + image.Size, } imageInspect.GraphDriver.Name = s.graph.driver.String() graphDriverData, err := s.graph.driver.GetMetadata(image.ID) if err != nil { return nil, err } imageInspect.GraphDriver.Data = graphDriverData return imageInspect, nil } // ImageTarLayer return the tarLayer of the image func (s *TagStore) ImageTarLayer(name string, dest io.Writer) error { if image, err := s.LookupImage(name); err == nil && image != nil { // On Windows, the base layer cannot be exported if runtime.GOOS != "windows" || image.Parent != "" { fs, err := s.graph.TarLayer(image) if err != nil { return err } defer fs.Close() written, err := io.Copy(dest, fs) if err != nil { return err } logrus.Debugf("rendered layer for %s of [%d] size", image.ID, written) } return nil } return fmt.Errorf("No such image: %s", name) } ================================================ FILE: vendor/github.com/docker/docker/graph/tags/tags.go ================================================ package tags import ( "fmt" "github.com/docker/distribution/registry/api/v2" ) const DEFAULTTAG = "latest" type ErrTagInvalidFormat struct { name string } func (e ErrTagInvalidFormat) Error() string { return fmt.Sprintf("Illegal tag name (%s): only [A-Za-z0-9_.-] are allowed ('.' and '-' are NOT allowed in the initial), minimum 1, maximum 128 in length", e.name) } // ValidateTagName validates the name of a tag func ValidateTagName(name string) error { if name == "" { return fmt.Errorf("tag name can't be empty") } if !v2.TagNameAnchoredRegexp.MatchString(name) { return ErrTagInvalidFormat{name} } return nil } ================================================ FILE: vendor/github.com/docker/docker/graph/tags/tags_unit_test.go ================================================ package tags import ( "testing" ) func TestValidTagName(t *testing.T) { validTags := []string{"9", "foo", "foo-test", "bar.baz.boo"} for _, tag := range validTags { if err := ValidateTagName(tag); err != nil { t.Errorf("'%s' should've been a valid tag", tag) } } } func TestInvalidTagName(t *testing.T) { validTags := []string{"-9", ".foo", "-test", ".", "-"} for _, tag := range validTags { if err := ValidateTagName(tag); err == nil { t.Errorf("'%s' shouldn't have been a valid tag", tag) } } } ================================================ FILE: vendor/github.com/docker/docker/graph/tags.go ================================================ package graph import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "sort" "strings" "sync" "github.com/docker/distribution/digest" "github.com/docker/docker/daemon/events" "github.com/docker/docker/graph/tags" "github.com/docker/docker/image" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" "github.com/docker/docker/trust" "github.com/docker/docker/utils" "github.com/docker/libtrust" ) const DEFAULTTAG = "latest" type TagStore struct { path string graph *Graph Repositories map[string]Repository trustKey libtrust.PrivateKey sync.Mutex // FIXME: move push/pull-related fields // to a helper type pullingPool map[string]chan struct{} pushingPool map[string]chan struct{} registryService *registry.Service eventsService *events.Events trustService *trust.TrustStore } type Repository map[string]string // update Repository mapping with content of u func (r Repository) Update(u Repository) { for k, v := range u { r[k] = v } } // return true if the contents of u Repository, are wholly contained in r Repository func (r Repository) Contains(u Repository) bool { for k, v := range u { // if u's key is not present in r OR u's key is present, but not the same value if rv, ok := r[k]; !ok || (ok && rv != v) { return false } } return true } type TagStoreConfig struct { Graph *Graph Key libtrust.PrivateKey Registry *registry.Service Events *events.Events Trust *trust.TrustStore } func NewTagStore(path string, cfg *TagStoreConfig) (*TagStore, error) { abspath, err := filepath.Abs(path) if err != nil { return nil, err } store := &TagStore{ path: abspath, graph: cfg.Graph, trustKey: cfg.Key, Repositories: make(map[string]Repository), pullingPool: make(map[string]chan struct{}), pushingPool: make(map[string]chan struct{}), registryService: cfg.Registry, eventsService: cfg.Events, trustService: cfg.Trust, } // Load the json file if it exists, otherwise create it. if err := store.reload(); os.IsNotExist(err) { if err := store.save(); err != nil { return nil, err } } else if err != nil { return nil, err } return store, nil } func (store *TagStore) save() error { // Store the json ball jsonData, err := json.Marshal(store) if err != nil { return err } if err := ioutil.WriteFile(store.path, jsonData, 0600); err != nil { return err } return nil } func (store *TagStore) reload() error { f, err := os.Open(store.path) if err != nil { return err } defer f.Close() if err := json.NewDecoder(f).Decode(&store); err != nil { return err } return nil } func (store *TagStore) LookupImage(name string) (*image.Image, error) { // FIXME: standardize on returning nil when the image doesn't exist, and err for everything else // (so we can pass all errors here) repoName, ref := parsers.ParseRepositoryTag(name) if ref == "" { ref = DEFAULTTAG } var ( err error img *image.Image ) img, err = store.GetImage(repoName, ref) if err != nil { return nil, err } if img != nil { return img, err } // name must be an image ID. store.Lock() defer store.Unlock() if img, err = store.graph.Get(name); err != nil { return nil, err } return img, nil } // Return a reverse-lookup table of all the names which refer to each image // Eg. {"43b5f19b10584": {"base:latest", "base:v1"}} func (store *TagStore) ByID() map[string][]string { store.Lock() defer store.Unlock() byID := make(map[string][]string) for repoName, repository := range store.Repositories { for tag, id := range repository { name := utils.ImageReference(repoName, tag) if _, exists := byID[id]; !exists { byID[id] = []string{name} } else { byID[id] = append(byID[id], name) sort.Strings(byID[id]) } } } return byID } func (store *TagStore) ImageName(id string) string { if names, exists := store.ByID()[id]; exists && len(names) > 0 { return names[0] } return stringid.TruncateID(id) } func (store *TagStore) DeleteAll(id string) error { names, exists := store.ByID()[id] if !exists || len(names) == 0 { return nil } for _, name := range names { if strings.Contains(name, ":") { nameParts := strings.Split(name, ":") if _, err := store.Delete(nameParts[0], nameParts[1]); err != nil { return err } } else { if _, err := store.Delete(name, ""); err != nil { return err } } } return nil } func (store *TagStore) Delete(repoName, ref string) (bool, error) { store.Lock() defer store.Unlock() deleted := false if err := store.reload(); err != nil { return false, err } repoName = registry.NormalizeLocalName(repoName) if ref == "" { // Delete the whole repository. delete(store.Repositories, repoName) return true, store.save() } repoRefs, exists := store.Repositories[repoName] if !exists { return false, fmt.Errorf("No such repository: %s", repoName) } if _, exists := repoRefs[ref]; exists { delete(repoRefs, ref) if len(repoRefs) == 0 { delete(store.Repositories, repoName) } deleted = true } return deleted, store.save() } func (store *TagStore) Tag(repoName, tag, imageName string, force bool) error { return store.SetLoad(repoName, tag, imageName, force, nil) } func (store *TagStore) SetLoad(repoName, tag, imageName string, force bool, out io.Writer) error { img, err := store.LookupImage(imageName) store.Lock() defer store.Unlock() if err != nil { return err } if tag == "" { tag = tags.DEFAULTTAG } if err := validateRepoName(repoName); err != nil { return err } if err := tags.ValidateTagName(tag); err != nil { if _, formatError := err.(tags.ErrTagInvalidFormat); !formatError { return err } if _, dErr := digest.ParseDigest(tag); dErr != nil { // Still return the tag validation error. // It's more likely to be a user generated issue. return err } } if err := store.reload(); err != nil { return err } var repo Repository repoName = registry.NormalizeLocalName(repoName) if r, exists := store.Repositories[repoName]; exists { repo = r if old, exists := store.Repositories[repoName][tag]; exists { if !force { return fmt.Errorf("Conflict: Tag %s is already set to image %s, if you want to replace it, please use -f option", tag, old) } if old != img.ID && out != nil { fmt.Fprintf(out, "The image %s:%s already exists, renaming the old one with ID %s to empty string\n", repoName, tag, old[:12]) } } } else { repo = make(map[string]string) store.Repositories[repoName] = repo } repo[tag] = img.ID return store.save() } // SetDigest creates a digest reference to an image ID. func (store *TagStore) SetDigest(repoName, digest, imageName string) error { img, err := store.LookupImage(imageName) if err != nil { return err } if err := validateRepoName(repoName); err != nil { return err } if err := validateDigest(digest); err != nil { return err } store.Lock() defer store.Unlock() if err := store.reload(); err != nil { return err } repoName = registry.NormalizeLocalName(repoName) repoRefs, exists := store.Repositories[repoName] if !exists { repoRefs = Repository{} store.Repositories[repoName] = repoRefs } else if oldID, exists := repoRefs[digest]; exists && oldID != img.ID { return fmt.Errorf("Conflict: Digest %s is already set to image %s", digest, oldID) } repoRefs[digest] = img.ID return store.save() } func (store *TagStore) Get(repoName string) (Repository, error) { store.Lock() defer store.Unlock() if err := store.reload(); err != nil { return nil, err } repoName = registry.NormalizeLocalName(repoName) if r, exists := store.Repositories[repoName]; exists { return r, nil } return nil, nil } func (store *TagStore) GetImage(repoName, refOrID string) (*image.Image, error) { repo, err := store.Get(repoName) if err != nil { return nil, err } if repo == nil { return nil, nil } store.Lock() defer store.Unlock() if imgID, exists := repo[refOrID]; exists { return store.graph.Get(imgID) } // If no matching tag is found, search through images for a matching image id // iff it looks like a short ID or would look like a short ID if stringid.IsShortID(stringid.TruncateID(refOrID)) { for _, revision := range repo { if strings.HasPrefix(revision, refOrID) { return store.graph.Get(revision) } } } return nil, nil } func (store *TagStore) GetRepoRefs() map[string][]string { store.Lock() reporefs := make(map[string][]string) for name, repository := range store.Repositories { for tag, id := range repository { shortID := stringid.TruncateID(id) reporefs[shortID] = append(reporefs[shortID], utils.ImageReference(name, tag)) } } store.Unlock() return reporefs } // Validate the name of a repository func validateRepoName(name string) error { if name == "" { return fmt.Errorf("Repository name can't be empty") } if name == "scratch" { return fmt.Errorf("'scratch' is a reserved name") } return nil } func validateDigest(dgst string) error { if dgst == "" { return errors.New("digest can't be empty") } if _, err := digest.ParseDigest(dgst); err != nil { return err } return nil } func (store *TagStore) poolAdd(kind, key string) (chan struct{}, error) { store.Lock() defer store.Unlock() if c, exists := store.pullingPool[key]; exists { return c, fmt.Errorf("pull %s is already in progress", key) } if c, exists := store.pushingPool[key]; exists { return c, fmt.Errorf("push %s is already in progress", key) } c := make(chan struct{}) switch kind { case "pull": store.pullingPool[key] = c case "push": store.pushingPool[key] = c default: return nil, fmt.Errorf("Unknown pool type") } return c, nil } func (store *TagStore) poolRemove(kind, key string) error { store.Lock() defer store.Unlock() switch kind { case "pull": if c, exists := store.pullingPool[key]; exists { close(c) delete(store.pullingPool, key) } case "push": if c, exists := store.pushingPool[key]; exists { close(c) delete(store.pushingPool, key) } default: return fmt.Errorf("Unknown pool type") } return nil } ================================================ FILE: vendor/github.com/docker/docker/graph/tags_unit_test.go ================================================ package graph import ( "archive/tar" "bytes" "io" "os" "path" "testing" "github.com/docker/docker/daemon/events" "github.com/docker/docker/daemon/graphdriver" _ "github.com/docker/docker/daemon/graphdriver/vfs" // import the vfs driver so it is used in the tests "github.com/docker/docker/image" "github.com/docker/docker/trust" "github.com/docker/docker/utils" ) const ( testOfficialImageName = "myapp" testOfficialImageID = "1a2d3c4d4e5fa2d2a21acea242a5e2345d3aefc3e7dfa2a2a2a21a2a2ad2d234" testOfficialImageIDShort = "1a2d3c4d4e5f" testPrivateImageName = "127.0.0.1:8000/privateapp" testPrivateImageID = "5bc255f8699e4ee89ac4469266c3d11515da88fdcbde45d7b069b636ff4efd81" testPrivateImageIDShort = "5bc255f8699e" testPrivateImageDigest = "sha256:bc8813ea7b3603864987522f02a76101c17ad122e1c46d790efc0fca78ca7bfb" testPrivateImageTag = "sometag" ) func fakeTar() (io.Reader, error) { uid := os.Getuid() gid := os.Getgid() content := []byte("Hello world!\n") buf := new(bytes.Buffer) tw := tar.NewWriter(buf) for _, name := range []string{"/etc/postgres/postgres.conf", "/etc/passwd", "/var/log/postgres/postgres.conf"} { hdr := new(tar.Header) // Leaving these fields blank requires root privileges hdr.Uid = uid hdr.Gid = gid hdr.Size = int64(len(content)) hdr.Name = name if err := tw.WriteHeader(hdr); err != nil { return nil, err } tw.Write([]byte(content)) } tw.Close() return buf, nil } func mkTestTagStore(root string, t *testing.T) *TagStore { driver, err := graphdriver.New(root, nil) if err != nil { t.Fatal(err) } graph, err := NewGraph(root, driver) if err != nil { t.Fatal(err) } trust, err := trust.NewTrustStore(root + "/trust") if err != nil { t.Fatal(err) } tagCfg := &TagStoreConfig{ Graph: graph, Events: events.New(), Trust: trust, } store, err := NewTagStore(path.Join(root, "tags"), tagCfg) if err != nil { t.Fatal(err) } officialArchive, err := fakeTar() if err != nil { t.Fatal(err) } img := &image.Image{ID: testOfficialImageID} if err := graph.Register(img, officialArchive); err != nil { t.Fatal(err) } if err := store.Tag(testOfficialImageName, "", testOfficialImageID, false); err != nil { t.Fatal(err) } privateArchive, err := fakeTar() if err != nil { t.Fatal(err) } img = &image.Image{ID: testPrivateImageID} if err := graph.Register(img, privateArchive); err != nil { t.Fatal(err) } if err := store.Tag(testPrivateImageName, "", testPrivateImageID, false); err != nil { t.Fatal(err) } if err := store.SetDigest(testPrivateImageName, testPrivateImageDigest, testPrivateImageID); err != nil { t.Fatal(err) } return store } func TestLookupImage(t *testing.T) { tmp, err := utils.TestDirectory("") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) store := mkTestTagStore(tmp, t) defer store.graph.driver.Cleanup() officialLookups := []string{ testOfficialImageID, testOfficialImageIDShort, testOfficialImageName + ":" + testOfficialImageID, testOfficialImageName + ":" + testOfficialImageIDShort, testOfficialImageName, testOfficialImageName + ":" + DEFAULTTAG, "docker.io/" + testOfficialImageName, "docker.io/" + testOfficialImageName + ":" + DEFAULTTAG, "index.docker.io/" + testOfficialImageName, "index.docker.io/" + testOfficialImageName + ":" + DEFAULTTAG, "library/" + testOfficialImageName, "library/" + testOfficialImageName + ":" + DEFAULTTAG, "docker.io/library/" + testOfficialImageName, "docker.io/library/" + testOfficialImageName + ":" + DEFAULTTAG, "index.docker.io/library/" + testOfficialImageName, "index.docker.io/library/" + testOfficialImageName + ":" + DEFAULTTAG, } privateLookups := []string{ testPrivateImageID, testPrivateImageIDShort, testPrivateImageName + ":" + testPrivateImageID, testPrivateImageName + ":" + testPrivateImageIDShort, testPrivateImageName, testPrivateImageName + ":" + DEFAULTTAG, } invalidLookups := []string{ testOfficialImageName + ":" + "fail", "fail:fail", } digestLookups := []string{ testPrivateImageName + "@" + testPrivateImageDigest, } for _, name := range officialLookups { if img, err := store.LookupImage(name); err != nil { t.Errorf("Error looking up %s: %s", name, err) } else if img == nil { t.Errorf("Expected 1 image, none found: %s", name) } else if img.ID != testOfficialImageID { t.Errorf("Expected ID '%s' found '%s'", testOfficialImageID, img.ID) } } for _, name := range privateLookups { if img, err := store.LookupImage(name); err != nil { t.Errorf("Error looking up %s: %s", name, err) } else if img == nil { t.Errorf("Expected 1 image, none found: %s", name) } else if img.ID != testPrivateImageID { t.Errorf("Expected ID '%s' found '%s'", testPrivateImageID, img.ID) } } for _, name := range invalidLookups { if img, err := store.LookupImage(name); err == nil { t.Errorf("Expected error, none found: %s", name) } else if img != nil { t.Errorf("Expected 0 image, 1 found: %s", name) } } for _, name := range digestLookups { if img, err := store.LookupImage(name); err != nil { t.Errorf("Error looking up %s: %s", name, err) } else if img == nil { t.Errorf("Expected 1 image, none found: %s", name) } else if img.ID != testPrivateImageID { t.Errorf("Expected ID '%s' found '%s'", testPrivateImageID, img.ID) } } } func TestValidateDigest(t *testing.T) { tests := []struct { input string expectError bool }{ {"", true}, {"latest", true}, {"sha256:b", false}, {"tarsum+v1+sha256:bY852-_.+=", false}, {"#$%#$^:$%^#$%", true}, } for i, test := range tests { err := validateDigest(test.input) gotError := err != nil if e, a := test.expectError, gotError; e != a { t.Errorf("%d: with input %s, expected error=%t, got %t: %s", i, test.input, test.expectError, gotError, err) } } } ================================================ FILE: vendor/github.com/docker/docker/hack/.vendor-helpers.sh ================================================ #!/usr/bin/env bash # Downloads dependencies into vendor/ directory mkdir -p vendor rm -rf .gopath mkdir -p .gopath/src/github.com/docker ln -sf ../../../.. .gopath/src/github.com/docker/docker export GOPATH="${PWD}/.gopath:${PWD}/vendor" clone() { local vcs="$1" local pkg="$2" local rev="$3" local url="$4" : ${url:=https://$pkg} local target="vendor/src/$pkg" echo -n "$pkg @ $rev: " if [ -d "$target" ]; then echo -n 'rm old, ' rm -rf "$target" fi echo -n 'clone, ' case "$vcs" in git) git clone --quiet --no-checkout "$url" "$target" ( cd "$target" && git reset --quiet --hard "$rev" ) ;; hg) hg clone --quiet --updaterev "$rev" "$url" "$target" ;; esac echo -n 'rm VCS, ' ( cd "$target" && rm -rf .{git,hg} ) echo -n 'rm vendor, ' ( cd "$target" && rm -rf vendor Godeps/_workspace ) echo done } # get an ENV from the Dockerfile with support for multiline values _dockerfile_env() { local e="$1" awk ' $1 == "ENV" && $2 == "'"$e"'" { sub(/^ENV +([^ ]+) +/, ""); inEnv = 1; } inEnv { if (sub(/\\$/, "")) { printf "%s", $0; next; } print; exit; } ' Dockerfile } clean() { local packages=( github.com/docker/docker/docker # package main github.com/docker/docker/dockerinit # package main github.com/docker/docker/integration-cli # external tests ) local dockerPlatforms=( linux/amd64 windows/amd64 $(_dockerfile_env DOCKER_CROSSPLATFORMS) ) local dockerBuildTags="$(_dockerfile_env DOCKER_BUILDTAGS)" local buildTagCombos=( '' 'experimental' "$dockerBuildTags" "daemon $dockerBuildTags" "daemon cgo $dockerBuildTags" "experimental $dockerBuildTags" "experimental daemon $dockerBuildTags" "experimental daemon cgo $dockerBuildTags" ) echo echo -n 'collecting import graph, ' local IFS=$'\n' local imports=( $( for platform in "${dockerPlatforms[@]}"; do export GOOS="${platform%/*}"; export GOARCH="${platform##*/}"; for buildTags in "${buildTagCombos[@]}"; do go list -e -tags "$buildTags" -f '{{join .Deps "\n"}}' "${packages[@]}" done done | grep -vE '^github.com/docker/docker' | sort -u ) ) imports=( $(go list -e -f '{{if not .Standard}}{{.ImportPath}}{{end}}' "${imports[@]}") ) unset IFS echo -n 'pruning unused packages, ' findArgs=( # This directory contains only .c and .h files which are necessary -path vendor/src/github.com/mattn/go-sqlite3/code ) for import in "${imports[@]}"; do [ "${#findArgs[@]}" -eq 0 ] || findArgs+=( -or ) findArgs+=( -path "vendor/src/$import" ) done local IFS=$'\n' local prune=( $(find vendor -depth -type d -not '(' "${findArgs[@]}" ')') ) unset IFS for dir in "${prune[@]}"; do find "$dir" -maxdepth 1 -not -type d -exec rm -v -f '{}' + rmdir "$dir" 2>/dev/null || true done echo -n 'pruning unused files, ' find vendor -type f -name '*_test.go' -exec rm -v '{}' + echo done } ================================================ FILE: vendor/github.com/docker/docker/hack/dind ================================================ #!/bin/bash set -e # DinD: a wrapper script which allows docker to be run inside a docker container. # Original version by Jerome Petazzoni # See the blog post: https://blog.docker.com/2013/09/docker-can-now-run-within-docker/ # # This script should be executed inside a docker container in privilieged mode # ('docker run --privileged', introduced in docker 0.6). # Usage: dind CMD [ARG...] # apparmor sucks and Docker needs to know that it's in a container (c) @tianon export container=docker # First, make sure that cgroups are mounted correctly. CGROUP=/cgroup mkdir -p "$CGROUP" if ! mountpoint -q "$CGROUP"; then mount -n -t tmpfs -o uid=0,gid=0,mode=0755 cgroup $CGROUP || { echo >&2 'Could not make a tmpfs mount. Did you use --privileged?' exit 1 } fi if [ -d /sys/kernel/security ] && ! mountpoint -q /sys/kernel/security; then mount -t securityfs none /sys/kernel/security || { echo >&2 'Could not mount /sys/kernel/security.' echo >&2 'AppArmor detection and -privileged mode might break.' } fi # Mount the cgroup hierarchies exactly as they are in the parent system. for HIER in $(cut -d: -f2 /proc/1/cgroup); do # The following sections address a bug which manifests itself # by a cryptic "lxc-start: no ns_cgroup option specified" when # trying to start containers within a container. # The bug seems to appear when the cgroup hierarchies are not # mounted on the exact same directories in the host, and in the # container. SUBSYSTEMS="${HIER%name=*}" # If cgroup hierarchy is named(mounted with "-o name=foo") we # need to mount it in $CGROUP/foo to create exect same # directoryes as on host. Else we need to mount it as is e.g. # "subsys1,subsys2" if it has two subsystems # Named, control-less cgroups are mounted with "-o name=foo" # (and appear as such under /proc//cgroup) but are usually # mounted on a directory named "foo" (without the "name=" prefix). # Systemd and OpenRC (and possibly others) both create such a # cgroup. So just mount them on directory $CGROUP/foo. OHIER=$HIER HIER="${HIER#*name=}" mkdir -p "$CGROUP/$HIER" if ! mountpoint -q "$CGROUP/$HIER"; then mount -n -t cgroup -o "$OHIER" cgroup "$CGROUP/$HIER" fi # Likewise, on at least one system, it has been reported that # systemd would mount the CPU and CPU accounting controllers # (respectively "cpu" and "cpuacct") with "-o cpuacct,cpu" # but on a directory called "cpu,cpuacct" (note the inversion # in the order of the groups). This tries to work around it. if [ "$HIER" = 'cpuacct,cpu' ]; then ln -s "$HIER" "$CGROUP/cpu,cpuacct" fi # If hierarchy has multiple subsystems, in /proc//cgroup # we will see ":subsys1,subsys2,subsys3,name=foo:" substring, # we need to mount it to "$CGROUP/foo" and if there were no # name to "$CGROUP/subsys1,subsys2,subsys3", so we must create # symlinks for docker daemon to find these subsystems: # ln -s $CGROUP/foo $CGROUP/subsys1 # ln -s $CGROUP/subsys1,subsys2,subsys3 $CGROUP/subsys1 if [ "$SUBSYSTEMS" != "${SUBSYSTEMS//,/ }" ]; then SUBSYSTEMS="${SUBSYSTEMS//,/ }" for SUBSYS in $SUBSYSTEMS do ln -s "$CGROUP/$HIER" "$CGROUP/$SUBSYS" done fi done # Note: as I write those lines, the LXC userland tools cannot setup # a "sub-container" properly if the "devices" cgroup is not in its # own hierarchy. Let's detect this and issue a warning. if ! grep -q :devices: /proc/1/cgroup; then echo >&2 'WARNING: the "devices" cgroup should be in its own hierarchy.' fi if ! grep -qw devices /proc/1/cgroup; then echo >&2 'WARNING: it looks like the "devices" cgroup is not mounted.' fi # Mount /tmp mount -t tmpfs none /tmp if [ $# -gt 0 ]; then exec "$@" fi echo >&2 'ERROR: No command specified.' echo >&2 'You probably want to run hack/make.sh, or maybe a shell?' ================================================ FILE: vendor/github.com/docker/docker/hack/generate-authors.sh ================================================ #!/bin/bash set -e cd "$(dirname "$(readlink -f "$BASH_SOURCE")")/.." # see also ".mailmap" for how email addresses and names are deduplicated { cat <<-'EOH' # This file lists all individuals having contributed content to the repository. # For how it is generated, see `hack/generate-authors.sh`. EOH echo git log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf } > AUTHORS ================================================ FILE: vendor/github.com/docker/docker/hack/install.sh ================================================ #!/bin/sh set -e # # This script is meant for quick & easy install via: # 'curl -sSL https://get.docker.com/ | sh' # or: # 'wget -qO- https://get.docker.com/ | sh' # # If you're interested in the daily experimental build: # 'curl -sSL https://experimental.docker.com/ | sh' # or: # 'wget -qO- https://experimental.docker.com/ | sh' # # Docker Maintainers: # To update this script on https://get.docker.com, # use hack/release.sh during a normal release, # or the following one-liner for script hotfixes: # s3cmd put --acl-public -P hack/install.sh s3://get.docker.com/index # url='https://get.docker.com/' command_exists() { command -v "$@" > /dev/null 2>&1 } echo_docker_as_nonroot() { your_user=your-user [ "$user" != 'root' ] && your_user="$user" # intentionally mixed spaces and tabs here -- tabs are stripped by "<<-EOF", spaces are kept in the output cat <<-EOF If you would like to use Docker as a non-root user, you should now consider adding your user to the "docker" group with something like: sudo usermod -aG docker $your_user Remember that you will have to log out and back in for this to take effect! EOF } do_install() { case "$(uname -m)" in *64) ;; *) cat >&2 <<-'EOF' Error: you are not using a 64bit platform. Docker currently only supports 64bit platforms. EOF exit 1 ;; esac if command_exists docker; then cat >&2 <<-'EOF' Warning: the "docker" command appears to already exist on this system. If you already have Docker installed, this script can cause trouble, which is why we're displaying this warning and provide the opportunity to cancel the installation. If you installed the current Docker package using this script and are using it again to update Docker, you can safely ignore this message. You may press Ctrl+C now to abort this script. EOF ( set -x; sleep 20 ) fi user="$(id -un 2>/dev/null || true)" sh_c='sh -c' if [ "$user" != 'root' ]; then if command_exists sudo; then sh_c='sudo -E sh -c' elif command_exists su; then sh_c='su -c' else cat >&2 <<-'EOF' Error: this installer needs the ability to run commands as root. We are unable to find either "sudo" or "su" available to make this happen. EOF exit 1 fi fi curl='' if command_exists curl; then curl='curl -sSL' elif command_exists wget; then curl='wget -qO-' elif command_exists busybox && busybox --list-modules | grep -q wget; then curl='busybox wget -qO-' fi # perform some very rudimentary platform detection lsb_dist='' if command_exists lsb_release; then lsb_dist="$(lsb_release -si)" fi if [ -z "$lsb_dist" ] && [ -r /etc/lsb-release ]; then lsb_dist="$(. /etc/lsb-release && echo "$DISTRIB_ID")" fi if [ -z "$lsb_dist" ] && [ -r /etc/debian_version ]; then lsb_dist='debian' fi if [ -z "$lsb_dist" ] && [ -r /etc/fedora-release ]; then lsb_dist='fedora' fi if [ -z "$lsb_dist" ] && [ -r /etc/centos-release ]; then lsb_dist='centos' fi if [ -z "$lsb_dist" ] && [ -r /etc/os-release ]; then lsb_dist="$(. /etc/os-release && echo "$ID")" fi lsb_dist="$(echo "$lsb_dist" | tr '[:upper:]' '[:lower:]')" case "$lsb_dist" in amzn|fedora|centos) if [ "$lsb_dist" = 'amzn' ]; then ( set -x $sh_c 'sleep 3; yum -y -q install docker' ) else ( set -x $sh_c 'sleep 3; yum -y -q install docker-io' ) fi if command_exists docker && [ -e /var/run/docker.sock ]; then ( set -x $sh_c 'docker version' ) || true fi echo_docker_as_nonroot exit 0 ;; 'opensuse project'|opensuse|'suse linux'|sled) ( set -x $sh_c 'sleep 3; zypper -n install docker' ) if command_exists docker && [ -e /var/run/docker.sock ]; then ( set -x $sh_c 'docker version' ) || true fi echo_docker_as_nonroot exit 0 ;; ubuntu|debian|linuxmint|'elementary os'|kali) export DEBIAN_FRONTEND=noninteractive did_apt_get_update= apt_get_update() { if [ -z "$did_apt_get_update" ]; then ( set -x; $sh_c 'sleep 3; apt-get update' ) did_apt_get_update=1 fi } # aufs is preferred over devicemapper; try to ensure the driver is available. if ! grep -q aufs /proc/filesystems && ! $sh_c 'modprobe aufs'; then if uname -r | grep -q -- '-generic' && dpkg -l 'linux-image-*-generic' | grep -q '^ii' 2>/dev/null; then kern_extras="linux-image-extra-$(uname -r) linux-image-extra-virtual" apt_get_update ( set -x; $sh_c 'sleep 3; apt-get install -y -q '"$kern_extras" ) || true if ! grep -q aufs /proc/filesystems && ! $sh_c 'modprobe aufs'; then echo >&2 'Warning: tried to install '"$kern_extras"' (for AUFS)' echo >&2 ' but we still have no AUFS. Docker may not work. Proceeding anyways!' ( set -x; sleep 10 ) fi else echo >&2 'Warning: current kernel is not supported by the linux-image-extra-virtual' echo >&2 ' package. We have no AUFS support. Consider installing the packages' echo >&2 ' linux-image-virtual kernel and linux-image-extra-virtual for AUFS support.' ( set -x; sleep 10 ) fi fi # install apparmor utils if they're missing and apparmor is enabled in the kernel # otherwise Docker will fail to start if [ "$(cat /sys/module/apparmor/parameters/enabled 2>/dev/null)" = 'Y' ]; then if command -v apparmor_parser >/dev/null 2>&1; then echo 'apparmor is enabled in the kernel and apparmor utils were already installed' else echo 'apparmor is enabled in the kernel, but apparmor_parser missing' apt_get_update ( set -x; $sh_c 'sleep 3; apt-get install -y -q apparmor' ) fi fi if [ ! -e /usr/lib/apt/methods/https ]; then apt_get_update ( set -x; $sh_c 'sleep 3; apt-get install -y -q apt-transport-https ca-certificates' ) fi if [ -z "$curl" ]; then apt_get_update ( set -x; $sh_c 'sleep 3; apt-get install -y -q curl ca-certificates' ) curl='curl -sSL' fi ( set -x if [ "https://get.docker.com/" = "$url" ]; then $sh_c "apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9" elif [ "https://test.docker.com/" = "$url" ]; then $sh_c "apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 740B314AE3941731B942C66ADF4FD13717AAD7D6" elif [ "https://experimental.docker.com/" = "$url" ]; then $sh_c "apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys E33FF7BF5C91D50A6F91FFFD4CC38D40F9A96B49" else $sh_c "$curl ${url}gpg | apt-key add -" fi $sh_c "mkdir -p /etc/apt/sources.list.d" $sh_c "echo deb ${url}ubuntu docker main > /etc/apt/sources.list.d/docker.list" $sh_c 'sleep 3; apt-get update; apt-get install -y -q lxc-docker' ) if command_exists docker && [ -e /var/run/docker.sock ]; then ( set -x $sh_c 'docker version' ) || true fi echo_docker_as_nonroot exit 0 ;; gentoo) if [ "$url" = "https://test.docker.com/" ]; then # intentionally mixed spaces and tabs here -- tabs are stripped by "<<-'EOF'", spaces are kept in the output cat >&2 <<-'EOF' You appear to be trying to install the latest nightly build in Gentoo.' The portage tree should contain the latest stable release of Docker, but' if you want something more recent, you can always use the live ebuild' provided in the "docker" overlay available via layman. For more' instructions, please see the following URL:' https://github.com/tianon/docker-overlay#using-this-overlay' After adding the "docker" overlay, you should be able to:' emerge -av =app-emulation/docker-9999' EOF exit 1 fi ( set -x $sh_c 'sleep 3; emerge app-emulation/docker' ) exit 0 ;; esac # intentionally mixed spaces and tabs here -- tabs are stripped by "<<-'EOF'", spaces are kept in the output cat >&2 <<-'EOF' Either your platform is not easily detectable, is not supported by this installer script (yet - PRs welcome! [hack/install.sh]), or does not yet have a package for Docker. Please visit the following URL for more detailed installation instructions: https://docs.docker.com/en/latest/installation/ EOF exit 1 } # wrapped up in a function so that we have some protection against only getting # half the file during "curl | sh" do_install ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/compat ================================================ 9 ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/control ================================================ Source: docker-engine Maintainer: Docker Homepage: https://dockerproject.org Vcs-Browser: https://github.com/docker/docker Vcs-Git: git://github.com/docker/docker.git Package: docker-engine Architecture: linux-any Depends: iptables, ${misc:Depends}, ${perl:Depends}, ${shlibs:Depends} Recommends: aufs-tools, ca-certificates, cgroupfs-mount | cgroup-lite, git, xz-utils, ${apparmor:Recommends} Conflicts: docker (<< 1.5~), docker.io, lxc-docker, lxc-docker-virtual-package Description: Docker: the open-source application container engine Docker is an open source project to pack, ship and run any application as a lightweight container . Docker containers are both hardware-agnostic and platform-agnostic. This means they can run anywhere, from your laptop to the largest EC2 compute instance and everything in between - and they don't require you to use a particular language, framework or packaging system. That makes them great building blocks for deploying and scaling web apps, databases, and backend services without depending on a particular stack or provider. ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/docker-engine.bash-completion ================================================ contrib/completion/bash/docker ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/docker-engine.install ================================================ #contrib/syntax/vim/doc/* /usr/share/vim/vimfiles/doc/ #contrib/syntax/vim/ftdetect/* /usr/share/vim/vimfiles/ftdetect/ #contrib/syntax/vim/syntax/* /usr/share/vim/vimfiles/syntax/ contrib/*-integration usr/share/docker-engine/contrib/ contrib/check-config.sh usr/share/docker-engine/contrib/ contrib/completion/zsh/_docker usr/share/zsh/vendor-completions/ contrib/init/systemd/docker.service lib/systemd/system/ contrib/init/systemd/docker.socket lib/systemd/system/ contrib/mk* usr/share/docker-engine/contrib/ contrib/nuke-graph-directory.sh usr/share/docker-engine/contrib/ contrib/syntax/nano/Dockerfile.nanorc usr/share/nano/ contrib/apparmor/* etc/apparmor.d/ ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/docker-engine.manpages ================================================ man/man*/* ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/docker-engine.postinst ================================================ #!/bin/sh set -e case "$1" in configure) if [ -z "$2" ]; then if ! getent group docker > /dev/null; then groupadd --system docker fi fi ;; abort-*) # How'd we get here?? exit 1 ;; *) ;; esac #DEBHELPER# ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/docs ================================================ README.md ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-deb/rules ================================================ #!/usr/bin/make -f VERSION = $(shell cat VERSION) override_dh_gencontrol: # if we're on Ubuntu, we need to Recommends: apparmor echo 'apparmor:Recommends=$(shell dpkg-vendor --is Ubuntu && echo apparmor)' >> debian/docker-engine.substvars dh_gencontrol override_dh_auto_build: ./hack/make.sh dynbinary # ./man/md2man-all.sh runs outside the build container (if at all), since we don't have go-md2man here override_dh_auto_test: ./bundles/$(VERSION)/dynbinary/docker -v override_dh_strip: # the SHA1 of dockerinit is important: don't strip it # also, Go has lots of problems with stripping, so just don't override_dh_auto_install: mkdir -p debian/docker-engine/usr/bin cp -aT "$$(readlink -f bundles/$(VERSION)/dynbinary/docker)" debian/docker-engine/usr/bin/docker mkdir -p debian/docker-engine/usr/lib/docker cp -aT "$$(readlink -f bundles/$(VERSION)/dynbinary/dockerinit)" debian/docker-engine/usr/lib/docker/dockerinit override_dh_installinit: # use "docker" as our service name, not "docker-engine" dh_installinit --name=docker override_dh_installudev: # match our existing priority dh_installudev --priority=z80 override_dh_install: dh_apparmor --profile-name=docker -pdocker-engine %: dh $@ --with=bash-completion $(shell command -v dh_systemd_enable > /dev/null 2>&1 && echo --with=systemd) ================================================ FILE: vendor/github.com/docker/docker/hack/make/.build-rpm/docker-engine.spec ================================================ Name: docker-engine Version: %{_version} Release: %{_release}%{?dist} Summary: The open-source application container engine Group: Tools/Docker License: ASL 2.0 Source: %{name}.tar.gz URL: https://dockerproject.org Vendor: Docker Packager: Docker # docker builds in a checksum of dockerinit into docker, # # so stripping the binaries breaks docker %global __os_install_post %{_rpmconfigdir}/brp-compress %global debug_package %{nil} # is_systemd conditional %if 0%{?fedora} >= 21 || 0%{?centos} >= 7 || 0%{?rhel} >= 7 %global is_systemd 1 %endif # required packages for build # most are already in the container (see contrib/builder/rpm/generate.sh) # only require systemd on those systems %if 0%{?is_systemd} BuildRequires: pkgconfig(systemd) Requires: systemd-units %else Requires(post): chkconfig Requires(preun): chkconfig # This is for /sbin/service Requires(preun): initscripts %endif # required packages on install Requires: /bin/sh Requires: iptables Requires: libcgroup Requires: tar Requires: xz %if 0%{?fedora} >= 21 # Resolves: rhbz#1165615 Requires: device-mapper-libs >= 1.02.90-1 %endif # conflicting packages Conflicts: docker Conflicts: docker-io %description Docker is an open source project to pack, ship and run any application as a lightweight container Docker containers are both hardware-agnostic and platform-agnostic. This means they can run anywhere, from your laptop to the largest EC2 compute instance and everything in between - and they don't require you to use a particular language, framework or packaging system. That makes them great building blocks for deploying and scaling web apps, databases, and backend services without depending on a particular stack or provider. %prep %if 0%{?centos} <= 6 %setup -n %{name} %else %autosetup -n %{name} %endif %build ./hack/make.sh dynbinary # ./man/md2man-all.sh runs outside the build container (if at all), since we don't have go-md2man here %check ./bundles/%{_origversion}/dynbinary/docker -v %install # install binary install -d $RPM_BUILD_ROOT/%{_bindir} install -p -m 755 bundles/%{_origversion}/dynbinary/docker-%{_origversion} $RPM_BUILD_ROOT/%{_bindir}/docker # install dockerinit install -d $RPM_BUILD_ROOT/%{_libexecdir}/docker install -p -m 755 bundles/%{_origversion}/dynbinary/dockerinit-%{_origversion} $RPM_BUILD_ROOT/%{_libexecdir}/docker/dockerinit # install udev rules install -d $RPM_BUILD_ROOT/%{_sysconfdir}/udev/rules.d install -p -m 755 contrib/udev/80-docker.rules $RPM_BUILD_ROOT/%{_sysconfdir}/udev/rules.d/80-docker.rules # add init scripts install -d $RPM_BUILD_ROOT/etc/sysconfig install -d $RPM_BUILD_ROOT/%{_initddir} %if 0%{?is_systemd} install -d $RPM_BUILD_ROOT/%{_unitdir} install -p -m 644 contrib/init/systemd/docker.service $RPM_BUILD_ROOT/%{_unitdir}/docker.service install -p -m 644 contrib/init/systemd/docker.socket $RPM_BUILD_ROOT/%{_unitdir}/docker.socket %endif install -p -m 644 contrib/init/sysvinit-redhat/docker.sysconfig $RPM_BUILD_ROOT/etc/sysconfig/docker install -p -m 755 contrib/init/sysvinit-redhat/docker $RPM_BUILD_ROOT/%{_initddir}/docker # add bash completions install -d $RPM_BUILD_ROOT/usr/share/bash-completion/completions install -d $RPM_BUILD_ROOT/usr/share/zsh/vendor-completions install -d $RPM_BUILD_ROOT/usr/share/fish/completions install -p -m 644 contrib/completion/bash/docker $RPM_BUILD_ROOT/usr/share/bash-completion/completions/docker install -p -m 644 contrib/completion/zsh/_docker $RPM_BUILD_ROOT/usr/share/zsh/vendor-completions/_docker install -p -m 644 contrib/completion/fish/docker.fish $RPM_BUILD_ROOT/usr/share/fish/completions/docker.fish # install manpages install -d %{buildroot}%{_mandir}/man1 install -p -m 644 man/man1/*.1 $RPM_BUILD_ROOT/%{_mandir}/man1 install -d %{buildroot}%{_mandir}/man5 install -p -m 644 man/man5/*.5 $RPM_BUILD_ROOT/%{_mandir}/man5 # add vimfiles install -d $RPM_BUILD_ROOT/usr/share/vim/vimfiles/doc install -d $RPM_BUILD_ROOT/usr/share/vim/vimfiles/ftdetect install -d $RPM_BUILD_ROOT/usr/share/vim/vimfiles/syntax install -p -m 644 contrib/syntax/vim/doc/dockerfile.txt $RPM_BUILD_ROOT/usr/share/vim/vimfiles/doc/dockerfile.txt install -p -m 644 contrib/syntax/vim/ftdetect/dockerfile.vim $RPM_BUILD_ROOT/usr/share/vim/vimfiles/ftdetect/dockerfile.vim install -p -m 644 contrib/syntax/vim/syntax/dockerfile.vim $RPM_BUILD_ROOT/usr/share/vim/vimfiles/syntax/dockerfile.vim # add nano install -d $RPM_BUILD_ROOT/usr/share/nano install -p -m 644 contrib/syntax/nano/Dockerfile.nanorc $RPM_BUILD_ROOT/usr/share/nano/Dockerfile.nanorc # list files owned by the package here %files /%{_bindir}/docker /%{_libexecdir}/docker/dockerinit /%{_sysconfdir}/udev/rules.d/80-docker.rules %if 0%{?is_systemd} /%{_unitdir}/docker.service /%{_unitdir}/docker.socket %endif /etc/sysconfig/docker /%{_initddir}/docker /usr/share/bash-completion/completions/docker /usr/share/zsh/vendor-completions/_docker /usr/share/fish/completions/docker.fish %doc /%{_mandir}/man1/* /%{_mandir}/man5/* /usr/share/vim/vimfiles/doc/dockerfile.txt /usr/share/vim/vimfiles/ftdetect/dockerfile.vim /usr/share/vim/vimfiles/syntax/dockerfile.vim /usr/share/nano/Dockerfile.nanorc %post %if 0%{?is_systemd} %systemd_post docker %else # This adds the proper /etc/rc*.d links for the script /sbin/chkconfig --add docker %endif if ! getent group docker > /dev/null; then groupadd --system docker fi %preun %if 0%{?is_systemd} %systemd_preun docker %else if [ $1 -eq 0 ] ; then /sbin/service docker stop >/dev/null 2>&1 /sbin/chkconfig --del docker fi %endif %postun %if 0%{?is_systemd} %systemd_postun_with_restart docker %else if [ "$1" -ge "1" ] ; then /sbin/service docker condrestart >/dev/null 2>&1 || : fi %endif %changelog ================================================ FILE: vendor/github.com/docker/docker/hack/make/.dockerinit ================================================ #!/bin/bash set -e IAMSTATIC="true" source "${MAKEDIR}/.go-autogen" # dockerinit still needs to be a static binary, even if docker is dynamic go build \ -o "$DEST/dockerinit-$VERSION" \ "${BUILDFLAGS[@]}" \ -ldflags " $LDFLAGS $LDFLAGS_STATIC -extldflags \"$EXTLDFLAGS_STATIC\" " \ ./dockerinit echo "Created binary: $DEST/dockerinit-$VERSION" ln -sf "dockerinit-$VERSION" "$DEST/dockerinit" sha1sum= if command -v sha1sum &> /dev/null; then sha1sum=sha1sum elif command -v shasum &> /dev/null; then # Mac OS X - why couldn't they just use the same command name and be happy? sha1sum=shasum else echo >&2 'error: cannot find sha1sum command or equivalent' exit 1 fi # sha1 our new dockerinit to ensure separate docker and dockerinit always run in a perfect pair compiled for one another export DOCKER_INITSHA1=$($sha1sum "$DEST/dockerinit-$VERSION" | cut -d' ' -f1) ================================================ FILE: vendor/github.com/docker/docker/hack/make/.dockerinit-gccgo ================================================ #!/bin/bash set -e IAMSTATIC="true" source "${MAKEDIR}/.go-autogen" # dockerinit still needs to be a static binary, even if docker is dynamic go build --compiler=gccgo \ -o "$DEST/dockerinit-$VERSION" \ "${BUILDFLAGS[@]}" \ --gccgoflags " -g -Wl,--no-export-dynamic $EXTLDFLAGS_STATIC_DOCKER -lnetgo " \ ./dockerinit echo "Created binary: $DEST/dockerinit-$VERSION" ln -sf "dockerinit-$VERSION" "$DEST/dockerinit" sha1sum= if command -v sha1sum &> /dev/null; then sha1sum=sha1sum else echo >&2 'error: cannot find sha1sum command or equivalent' exit 1 fi # sha1 our new dockerinit to ensure separate docker and dockerinit always run in a perfect pair compiled for one another export DOCKER_INITSHA1=$($sha1sum "$DEST/dockerinit-$VERSION" | cut -d' ' -f1) ================================================ FILE: vendor/github.com/docker/docker/hack/make/.ensure-emptyfs ================================================ #!/bin/bash set -e if ! docker inspect emptyfs &> /dev/null; then # let's build a "docker save" tarball for "emptyfs" # see https://github.com/docker/docker/pull/5262 # and also https://github.com/docker/docker/issues/4242 dir="$DEST/emptyfs" mkdir -p "$dir" ( cd "$dir" echo '{"emptyfs":{"latest":"511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158"}}' > repositories mkdir -p 511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158 ( cd 511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158 echo '{"id":"511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158","comment":"Imported from -","created":"2013-06-13T14:03:50.821769-07:00","container_config":{"Hostname":"","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"PortSpecs":null,"ExposedPorts":null,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"NetworkDisabled":false,"OnBuild":null},"docker_version":"0.4.0","architecture":"x86_64","Size":0}' > json echo '1.0' > VERSION tar -cf layer.tar --files-from /dev/null ) ) ( set -x; tar -cC "$dir" . | docker load ) rm -rf "$dir" fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/.ensure-frozen-images ================================================ #!/bin/bash set -e # this list should match roughly what's in the Dockerfile (minus the explicit image IDs, of course) images=( busybox:latest hello-world:frozen jess/unshare:latest ) if ! docker inspect "${images[@]}" &> /dev/null; then hardCodedDir='/docker-frozen-images' if [ -d "$hardCodedDir" ]; then ( set -x; tar -cC "$hardCodedDir" . | docker load ) else dir="$DEST/frozen-images" # extract the exact "RUN download-frozen-image.sh" line from the Dockerfile itself for consistency # NOTE: this will fail if either "curl" is not installed or if the Dockerfile is not available/readable awk ' $1 == "RUN" && $2 == "./contrib/download-frozen-image.sh" { for (i = 2; i < NF; i++) printf ( $i == "'"$hardCodedDir"'" ? "'"$dir"'" : $i ) " "; print $NF; if (/\\$/) { inCont = 1; next; } } inCont { print; if (!/\\$/) { inCont = 0; } } ' Dockerfile | sh -x ( set -x; tar -cC "$dir" . | docker load ) fi fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/.ensure-httpserver ================================================ #!/bin/bash set -e # Build a Go static web server on top of busybox image # and compile it for target daemon dir="$DEST/httpserver" mkdir -p "$dir" ( cd "$dir" GOOS=linux GOARCH=amd64 go build -o httpserver github.com/docker/docker/contrib/httpserver cp ../../../../contrib/httpserver/Dockerfile . docker build -qt httpserver . > /dev/null ) rm -rf "$dir" ================================================ FILE: vendor/github.com/docker/docker/hack/make/.go-autogen ================================================ #!/bin/bash rm -rf autogen mkdir -p autogen/dockerversion cat > autogen/dockerversion/dockerversion.go < autogen/winresources/resources.go < /dev/null fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/.go-compile-test-dir ================================================ #!/bin/bash set -e # Compile phase run by parallel in test-unit. No support for coverpkg dir=$1 in_file="$dir/$(basename "$dir").test" out_file="$DEST/precompiled/$dir.test" # we want to use binary_extension() here, but we can't because it's in main.sh and this file gets re-execed if [ "$(go env GOOS)" = 'windows' ]; then in_file+='.exe' out_file+='.exe' fi testcover=() if [ "$HAVE_GO_TEST_COVER" ]; then # if our current go install has -cover, we want to use it :) mkdir -p "$DEST/coverprofiles" coverprofile="docker${dir#.}" coverprofile="$DEST/coverprofiles/${coverprofile//\//-}" testcover=( -cover -coverprofile "$coverprofile" ) # missing $coverpkg fi if [ "$BUILDFLAGS_FILE" ]; then readarray -t BUILDFLAGS < "$BUILDFLAGS_FILE" fi if ! ( cd "$dir" go test "${testcover[@]}" -ldflags "$LDFLAGS" "${BUILDFLAGS[@]}" $TESTFLAGS -c ); then exit 1 fi mkdir -p "$(dirname "$out_file")" mv "$in_file" "$out_file" echo "Precompiled: ${DOCKER_PKG}${dir#.}" ================================================ FILE: vendor/github.com/docker/docker/hack/make/.integration-daemon-setup ================================================ #!/bin/bash bundle .ensure-emptyfs bundle .ensure-frozen-images bundle .ensure-httpserver ================================================ FILE: vendor/github.com/docker/docker/hack/make/.integration-daemon-start ================================================ #!/bin/bash # see test-integration-cli for example usage of this script export PATH="$ABS_DEST/../binary:$ABS_DEST/../dynbinary:$ABS_DEST/../gccgo:$ABS_DEST/../dyngccgo:$PATH" if ! command -v docker &> /dev/null; then echo >&2 'error: binary or dynbinary must be run before .integration-daemon-start' false fi # intentionally open a couple bogus file descriptors to help test that they get scrubbed in containers exec 41>&1 42>&2 export DOCKER_GRAPHDRIVER=${DOCKER_GRAPHDRIVER:-vfs} export DOCKER_EXECDRIVER=${DOCKER_EXECDRIVER:-native} export DOCKER_USERLANDPROXY=${DOCKER_USERLANDPROXY:-true} # example usage: DOCKER_STORAGE_OPTS="dm.basesize=20G,dm.loopdatasize=200G" storage_params="" if [ -n "$DOCKER_STORAGE_OPTS" ]; then IFS=',' for i in ${DOCKER_STORAGE_OPTS}; do storage_params="--storage-opt $i $storage_params" done unset IFS fi if [ -z "$DOCKER_TEST_HOST" ]; then # Start apparmor if it is enabled if [ -e "/sys/module/apparmor/parameters/enabled" ] && [ "$(cat /sys/module/apparmor/parameters/enabled)" == "Y" ]; then # reset container variable so apparmor profile is applied to process # see https://github.com/docker/libcontainer/blob/master/apparmor/apparmor.go#L16 export container="" ( set -x /etc/init.d/apparmor start /sbin/apparmor_parser -r -W -T contrib/apparmor/ ) fi export DOCKER_HOST="unix://$(cd "$DEST" && pwd)/docker.sock" # "pwd" tricks to make sure $DEST is an absolute path, not a relative one ( set -x; exec \ docker --daemon --debug \ --host "$DOCKER_HOST" \ --storage-driver "$DOCKER_GRAPHDRIVER" \ --exec-driver "$DOCKER_EXECDRIVER" \ --pidfile "$DEST/docker.pid" \ --userland-proxy="$DOCKER_USERLANDPROXY" \ $storage_params \ &> "$DEST/docker.log" ) & # make sure that if the script exits unexpectedly, we stop this daemon we just started trap 'bundle .integration-daemon-stop' EXIT else export DOCKER_HOST="$DOCKER_TEST_HOST" fi # give it a second to come up so it's "ready" tries=10 while ! docker version &> /dev/null; do (( tries-- )) if [ $tries -le 0 ]; then if [ -z "$DOCKER_HOST" ]; then echo >&2 "error: daemon failed to start" echo >&2 " check $DEST/docker.log for details" else echo >&2 "error: daemon at $DOCKER_HOST fails to 'docker version':" docker version >&2 || true fi false fi sleep 2 done ================================================ FILE: vendor/github.com/docker/docker/hack/make/.integration-daemon-stop ================================================ #!/bin/bash trap - EXIT # reset EXIT trap applied in .integration-daemon-start for pidFile in $(find "$DEST" -name docker.pid); do pid=$(set -x; cat "$pidFile") ( set -x; kill "$pid" ) if ! wait "$pid"; then echo >&2 "warning: PID $pid from $pidFile had a nonzero exit code" fi done if [ -z "$DOCKER_TEST_HOST" ]; then # Stop apparmor if it is enabled if [ -e "/sys/module/apparmor/parameters/enabled" ] && [ "$(cat /sys/module/apparmor/parameters/enabled)" == "Y" ]; then ( set -x /etc/init.d/apparmor stop ) fi fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/.resources-windows/docker.exe.manifest ================================================ Docker ================================================ FILE: vendor/github.com/docker/docker/hack/make/.validate ================================================ #!/bin/bash if [ -z "$VALIDATE_UPSTREAM" ]; then # this is kind of an expensive check, so let's not do this twice if we # are running more than one validate bundlescript VALIDATE_REPO='https://github.com/docker/docker.git' VALIDATE_BRANCH='master' if [ "$TRAVIS" = 'true' -a "$TRAVIS_PULL_REQUEST" != 'false' ]; then VALIDATE_REPO="https://github.com/${TRAVIS_REPO_SLUG}.git" VALIDATE_BRANCH="${TRAVIS_BRANCH}" fi VALIDATE_HEAD="$(git rev-parse --verify HEAD)" git fetch -q "$VALIDATE_REPO" "refs/heads/$VALIDATE_BRANCH" VALIDATE_UPSTREAM="$(git rev-parse --verify FETCH_HEAD)" VALIDATE_COMMIT_LOG="$VALIDATE_UPSTREAM..$VALIDATE_HEAD" VALIDATE_COMMIT_DIFF="$VALIDATE_UPSTREAM...$VALIDATE_HEAD" validate_diff() { if [ "$VALIDATE_UPSTREAM" != "$VALIDATE_HEAD" ]; then git diff "$VALIDATE_COMMIT_DIFF" "$@" fi } validate_log() { if [ "$VALIDATE_UPSTREAM" != "$VALIDATE_HEAD" ]; then git log "$VALIDATE_COMMIT_LOG" "$@" fi } fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/README.md ================================================ This directory holds scripts called by `make.sh` in the parent directory. Each script is named after the bundle it creates. They should not be called directly - instead, pass it as argument to make.sh, for example: ``` ./hack/make.sh test ./hack/make.sh binary ubuntu # Or to run all bundles: ./hack/make.sh ``` To add a bundle: * Create a shell-compatible file here * Add it to $DEFAULT_BUNDLES in make.sh ================================================ FILE: vendor/github.com/docker/docker/hack/make/binary ================================================ #!/bin/bash set -e BINARY_NAME="docker-$VERSION" BINARY_EXTENSION="$(binary_extension)" BINARY_FULLNAME="$BINARY_NAME$BINARY_EXTENSION" source "${MAKEDIR}/.go-autogen" echo "Building: $DEST/$BINARY_FULLNAME" go build \ -o "$DEST/$BINARY_FULLNAME" \ "${BUILDFLAGS[@]}" \ -ldflags " $LDFLAGS $LDFLAGS_STATIC_DOCKER " \ ./docker echo "Created binary: $DEST/$BINARY_FULLNAME" ln -sf "$BINARY_FULLNAME" "$DEST/docker$BINARY_EXTENSION" hash_files "$DEST/$BINARY_FULLNAME" ================================================ FILE: vendor/github.com/docker/docker/hack/make/build-deb ================================================ #!/bin/bash set -e # subshell so that we can export PATH and TZ without breaking other things ( export TZ=UTC # make sure our "date" variables are UTC-based bundle .integration-daemon-start # TODO consider using frozen images for the dockercore/builder-deb tags tilde='~' # ouch Bash 4.2 vs 4.3, you keel me debVersion="${VERSION//-/$tilde}" # using \~ or '~' here works in 4.3, but not 4.2; just ~ causes $HOME to be inserted, hence the $tilde # if we have a "-dev" suffix or have change in Git, let's make this package version more complex so it works better if [[ "$VERSION" == *-dev ]] || [ -n "$(git status --porcelain)" ]; then gitUnix="$(git log -1 --pretty='%at')" gitDate="$(date --date "@$gitUnix" +'%Y%m%d.%H%M%S')" gitCommit="$(git log -1 --pretty='%h')" gitVersion="git${gitDate}.0.${gitCommit}" # gitVersion is now something like 'git20150128.112847.0.17e840a' debVersion="$debVersion~$gitVersion" # $ dpkg --compare-versions 1.5.0 gt 1.5.0~rc1 && echo true || echo false # true # $ dpkg --compare-versions 1.5.0~rc1 gt 1.5.0~git20150128.112847.17e840a && echo true || echo false # true # $ dpkg --compare-versions 1.5.0~git20150128.112847.17e840a gt 1.5.0~dev~git20150128.112847.17e840a && echo true || echo false # true # ie, 1.5.0 > 1.5.0~rc1 > 1.5.0~git20150128.112847.17e840a > 1.5.0~dev~git20150128.112847.17e840a fi debSource="$(awk -F ': ' '$1 == "Source" { print $2; exit }' hack/make/.build-deb/control)" debMaintainer="$(awk -F ': ' '$1 == "Maintainer" { print $2; exit }' hack/make/.build-deb/control)" debDate="$(date --rfc-2822)" # if go-md2man is available, pre-generate the man pages ./man/md2man-all.sh -q || true # TODO decide if it's worth getting go-md2man in _each_ builder environment to avoid this # TODO add a configurable knob for _which_ debs to build so we don't have to modify the file or build all of them every time we need to test for dir in contrib/builder/deb/*/; do version="$(basename "$dir")" suite="${version##*-}" image="dockercore/builder-deb:$version" if ! docker inspect "$image" &> /dev/null; then ( set -x && docker build -t "$image" "$dir" ) fi mkdir -p "$DEST/$version" cat > "$DEST/$version/Dockerfile.build" <<-EOF FROM $image WORKDIR /usr/src/docker COPY . /usr/src/docker RUN ln -sfv hack/make/.build-deb debian RUN { echo '$debSource (${debVersion}-0~${suite}) $suite; urgency=low'; echo; echo ' * Version: $VERSION'; echo; echo " -- $debMaintainer $debDate"; } > debian/changelog && cat >&2 debian/changelog RUN dpkg-buildpackage -uc -us EOF tempImage="docker-temp/build-deb:$version" ( set -x && docker build -t "$tempImage" -f "$DEST/$version/Dockerfile.build" . ) docker run --rm "$tempImage" bash -c 'cd .. && tar -c *_*' | tar -xvC "$DEST/$version" docker rmi "$tempImage" done bundle .integration-daemon-stop ) 2>&1 | tee -a "$DEST/test.log" ================================================ FILE: vendor/github.com/docker/docker/hack/make/build-rpm ================================================ #!/bin/bash set -e # subshell so that we can export PATH and TZ without breaking other things ( export TZ=UTC # make sure our "date" variables are UTC-based source "$(dirname "$BASH_SOURCE")/.integration-daemon-start" # TODO consider using frozen images for the dockercore/builder-rpm tags rpmName=docker-engine rpmVersion="${VERSION%%-*}" rpmRelease=1 # rpmRelease versioning is as follows # Docker 1.7.0: version=1.7.0, release=1 # Docker 1.7.0-rc1: version=1.7.0, release=0.1.rc1 # Docker 1.7.0-dev nightly: version=1.7.0, release=0.0.YYYYMMDD.HHMMSS.gitHASH # if we have a "-rc*" suffix, set appropriate release if [[ "$VERSION" == *-rc* ]]; then rcVersion=${VERSION#*-rc} rpmRelease="0.${rcVersion}.rc${rcVersion}" fi # if we have a "-dev" suffix or have change in Git, let's make this package version more complex so it works better if [[ "$VERSION" == *-dev ]] || [ -n "$(git status --porcelain)" ]; then gitUnix="$(git log -1 --pretty='%at')" gitDate="$(date --date "@$gitUnix" +'%Y%m%d.%H%M%S')" gitCommit="$(git log -1 --pretty='%h')" gitVersion="${gitDate}.git${gitCommit}" # gitVersion is now something like '20150128.112847.17e840a' rpmRelease="0.0.$gitVersion" fi rpmPackager="$(awk -F ': ' '$1 == "Packager" { print $2; exit }' hack/make/.build-rpm/${rpmName}.spec)" rpmDate="$(date +'%a %b %d %Y')" # if go-md2man is available, pre-generate the man pages ./man/md2man-all.sh -q || true # TODO decide if it's worth getting go-md2man in _each_ builder environment to avoid this # TODO add a configurable knob for _which_ rpms to build so we don't have to modify the file or build all of them every time we need to test for dir in contrib/builder/rpm/*/; do version="$(basename "$dir")" suite="${version##*-}" image="dockercore/builder-rpm:$version" if ! docker inspect "$image" &> /dev/null; then ( set -x && docker build -t "$image" "$dir" ) fi mkdir -p "$DEST/$version" cat > "$DEST/$version/Dockerfile.build" <<-EOF FROM $image COPY . /usr/src/${rpmName} RUN mkdir -p /root/rpmbuild/SOURCES WORKDIR /root/rpmbuild RUN ln -sfv /usr/src/${rpmName}/hack/make/.build-rpm SPECS RUN tar -cz -C /usr/src -f /root/rpmbuild/SOURCES/${rpmName}.tar.gz ${rpmName} WORKDIR /root/rpmbuild/SPECS RUN { echo '* $rpmDate $rpmPackager $rpmVersion-$rpmRelease'; echo '* Version: $VERSION'; } >> ${rpmName}.spec && tail >&2 ${rpmName}.spec RUN rpmbuild -ba --define '_release $rpmRelease' --define '_version $rpmVersion' --define '_origversion $VERSION' ${rpmName}.spec EOF tempImage="docker-temp/build-rpm:$version" ( set -x && docker build -t "$tempImage" -f $DEST/$version/Dockerfile.build . ) docker run --rm "$tempImage" bash -c 'cd /root/rpmbuild && tar -c *RPMS' | tar -xvC "$DEST/$version" docker rmi "$tempImage" done source "$(dirname "$BASH_SOURCE")/.integration-daemon-stop" ) 2>&1 | tee -a $DEST/test.log ================================================ FILE: vendor/github.com/docker/docker/hack/make/cover ================================================ #!/bin/bash set -e bundle_cover() { coverprofiles=( "$DEST/../"*"/coverprofiles/"* ) for p in "${coverprofiles[@]}"; do echo ( set -x go tool cover -func="$p" ) done } if [ "$HAVE_GO_TEST_COVER" ]; then bundle_cover 2>&1 | tee "$DEST/report.log" else echo >&2 'warning: the current version of go does not support -cover' echo >&2 ' skipping test coverage report' fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/cross ================================================ #!/bin/bash set -e # explicit list of os/arch combos that support being a daemon declare -A daemonSupporting daemonSupporting=( [linux/amd64]=1 ) # if we have our linux/amd64 version compiled, let's symlink it in if [ -x "$DEST/../binary/docker-$VERSION" ]; then mkdir -p "$DEST/linux/amd64" ( cd "$DEST/linux/amd64" ln -s ../../../binary/* ./ ) echo "Created symlinks:" "$DEST/linux/amd64/"* fi for platform in $DOCKER_CROSSPLATFORMS; do ( export DEST="$DEST/$platform" # bundles/VERSION/cross/GOOS/GOARCH/docker-VERSION mkdir -p "$DEST" ABS_DEST="$(cd "$DEST" && pwd -P)" export GOOS=${platform%/*} export GOARCH=${platform##*/} if [ -z "${daemonSupporting[$platform]}" ]; then export LDFLAGS_STATIC_DOCKER="" # we just need a simple client for these platforms export BUILDFLAGS=( "${ORIG_BUILDFLAGS[@]/ daemon/}" ) # remove the "daemon" build tag from platforms that aren't supported fi source "${MAKEDIR}/binary" ) done ================================================ FILE: vendor/github.com/docker/docker/hack/make/dynbinary ================================================ #!/bin/bash set -e if [ -z "$DOCKER_CLIENTONLY" ]; then source "${MAKEDIR}/.dockerinit" hash_files "$DEST/dockerinit-$VERSION" else # DOCKER_CLIENTONLY must be truthy, so we don't need to bother with dockerinit :) export DOCKER_INITSHA1="" fi # DOCKER_INITSHA1 is exported so that other bundlescripts can easily access it later without recalculating it ( export IAMSTATIC="false" export LDFLAGS_STATIC_DOCKER='' export BUILDFLAGS=( "${BUILDFLAGS[@]/netgo /}" ) # disable netgo, since we don't need it for a dynamic binary export BUILDFLAGS=( "${BUILDFLAGS[@]/static_build /}" ) # we're not building a "static" binary here source "${MAKEDIR}/binary" ) ================================================ FILE: vendor/github.com/docker/docker/hack/make/dyngccgo ================================================ #!/bin/bash set -e if [ -z "$DOCKER_CLIENTONLY" ]; then source "${MAKEDIR}/.dockerinit-gccgo" hash_files "$DEST/dockerinit-$VERSION" else # DOCKER_CLIENTONLY must be truthy, so we don't need to bother with dockerinit :) export DOCKER_INITSHA1="" fi # DOCKER_INITSHA1 is exported so that other bundlescripts can easily access it later without recalculating it ( export IAMSTATIC="false" export EXTLDFLAGS_STATIC_DOCKER='' export LDFLAGS_STATIC_DOCKER='' export BUILDFLAGS=( "${BUILDFLAGS[@]/netgo /}" ) # disable netgo, since we don't need it for a dynamic binary export BUILDFLAGS=( "${BUILDFLAGS[@]/static_build /}" ) # we're not building a "static" binary here source "${MAKEDIR}/gccgo" ) ================================================ FILE: vendor/github.com/docker/docker/hack/make/gccgo ================================================ #!/bin/bash set -e BINARY_NAME="docker-$VERSION" BINARY_EXTENSION="$(binary_extension)" BINARY_FULLNAME="$BINARY_NAME$BINARY_EXTENSION" source "${MAKEDIR}/.go-autogen" if [[ "${BUILDFLAGS[@]}" =~ 'netgo ' ]]; then EXTLDFLAGS_STATIC_DOCKER+=' -lnetgo' fi go build -compiler=gccgo \ -o "$DEST/$BINARY_FULLNAME" \ "${BUILDFLAGS[@]}" \ -gccgoflags " -g $EXTLDFLAGS_STATIC_DOCKER -Wl,--no-export-dynamic -ldl " \ ./docker echo "Created binary: $DEST/$BINARY_FULLNAME" ln -sf "$BINARY_FULLNAME" "$DEST/docker$BINARY_EXTENSION" hash_files "$DEST/$BINARY_FULLNAME" ================================================ FILE: vendor/github.com/docker/docker/hack/make/release-deb ================================================ #!/bin/bash set -e # This script creates the apt repos for the .deb files generated by hack/make/build-deb # # The following can then be used as apt sources: # deb http://apt.dockerproject.org/repo $distro-$release $version # # For example: # deb http://apt.dockerproject.org/repo ubuntu-trusy main # deb http://apt.dockerproject.org/repo ubuntu-vivid testing # deb http://apt.dockerproject.org/repo debian-wheezy experimental # deb http://apt.dockerproject.org/repo debian-jessie main # # ... and so on and so forth for the builds created by hack/make/build-deb : ${DOCKER_RELEASE_DIR:=$DEST} APTDIR=$DOCKER_RELEASE_DIR/apt/repo # setup the apt repo (if it does not exist) mkdir -p "$APTDIR/conf" "$APTDIR/db" # create/update distributions file for suite in $(exec contrib/reprepro/suites.sh); do cat <<-EOF Origin: Docker Suite: $suite Codename: $suite Architectures: amd64 i386 Components: main testing experimental Description: Docker APT Repository EOF done > "$APTDIR/conf/distributions" # set the component and priority for the version being released component="main" priority=700 if [[ "$VERSION" == *-rc* ]]; then component="testing" priority=650 fi if [ $DOCKER_EXPERIMENTAL ] || [[ "$VERSION" == *-dev ]] || [ -n "$(git status --porcelain)" ]; then component="experimental" priority=600 fi # release the debs for dir in contrib/builder/deb/*/; do version="$(basename "$dir")" codename="${version//debootstrap-}" # add the deb for each component for the distro version with reprepro DEBFILE=( "bundles/$VERSION/build-deb/$version/docker-engine"*.deb ) # if we have a $GPG_PASSPHRASE we may as well # dpkg-sign before reprepro if [ ! -z "$GPG_PASSPHRASE" ]; then dpkg-sig -g "--passphrase $GPG_PASSPHRASE" \ -k releasedocker --sign builder "${DEBFILE[@]}" fi reprepro -v --keepunreferencedfiles \ -S docker-engine -P "$priority" -C "$component" \ -b "$APTDIR" includedeb "$codename" "${DEBFILE[@]}" done ================================================ FILE: vendor/github.com/docker/docker/hack/make/release-rpm ================================================ #!/bin/bash set -e # This script creates the yum repos for the .rpm files generated by hack/make/build-rpm # # The following can then be used as a yum repo: # http://yum.dockerproject.org/repo/$release/$distro/$distro-version # # For example: # http://yum.dockerproject.org/repo/main/fedora/22 # http://yum.dockerproject.org/repo/testing/centos/6 # http://yum.dockerproject.org/repo/experimental/fedora/21 # http://yum.dockerproject.org/repo/main/centos/7 # # ... and so on and so forth for the builds created by hack/make/build-rpm : ${DOCKER_RELEASE_DIR:=$DEST} YUMDIR=$DOCKER_RELEASE_DIR/yum/repo # manage the repos for each distribution seperately distros=( fedora centos oraclelinux ) # get the release release="main" if [[ "$VERSION" == *-rc* ]]; then release="testing" fi if [ $DOCKER_EXPERIMENTAL ] || [[ "$VERSION" == *-dev ]] || [ -n "$(git status --porcelain)" ]; then release="experimental" fi for distro in "${distros[@]}"; do # Setup the yum repo REPO=$YUMDIR/$release/$distro for dir in contrib/builder/rpm/$distro-*/; do version="$(basename "$dir")" suite="${version##*-}" # if the directory does not exist, intialize the yum repo if [[ ! -d $REPO/$suite/Packages ]]; then mkdir -p "$REPO/$suite/Packages" createrepo --pretty "$REPO/$suite" fi # path to rpms RPMFILE=( "bundles/$VERSION/build-rpm/$version/RPMS/x86_64/docker-engine"*.rpm "bundles/$VERSION/build-rpm/$version/SRPMS/docker-engine"*.rpm ) # if we have a $GPG_PASSPHRASE we may as well # sign the rpms before adding to repo if [ ! -z $GPG_PASSPHRASE ]; then # export our key to rpm import gpg --armor --export releasedocker > /tmp/gpg rpm --import /tmp/gpg # sign the rpms rpm \ --define '_gpg_name releasedocker' \ --define '_signature gpg' \ --define '__gpg_check_password_cmd /bin/true' \ --define '__gpg_sign_cmd %{__gpg} gpg --batch --no-armor --passphrase '$GPG_PASSPHRASE' --no-secmem-warning -u "%{_gpg_name}" --sign --detach-sign --output %{__signature_filename} %{__plaintext_filename}' \ --resign "${RPMFILE[@]}" fi # copy the rpms to the packages folder cp "$RPMFILE" "$REPO/$suite/Packages" # update the repo createrepo --pretty --update "$REPO/$suite" done done ================================================ FILE: vendor/github.com/docker/docker/hack/make/sign-repos ================================================ #!/bin/bash # This script signs the deliverables from release-deb and release-rpm # with a designated GPG key. : ${DOCKER_RELEASE_DIR:=$DEST} APTDIR=$DOCKER_RELEASE_DIR/apt/repo YUMDIR=$DOCKER_RELEASE_DIR/yum/repo if [ -z "$GPG_PASSPHRASE" ]; then echo >&2 'you need to set GPG_PASSPHRASE in order to sign artifacts' exit 1 fi if [ ! -d $APTDIR ] && [ ! -d $YUMDIR ]; then echo >&2 'release-rpm or release-deb must be run before sign-repos' exit 1 fi sign_packages(){ # sign apt repo metadata if [ -d $APTDIR ]; then # create file with public key gpg --armor --export releasedocker > "$DOCKER_RELEASE_DIR/apt/gpg" # sign the repo metadata for F in $(find $APTDIR -name Release); do gpg -u releasedocker --passphrase "$GPG_PASSPHRASE" \ --armor --sign --detach-sign \ --batch --yes \ --output "$F.gpg" "$F" done fi # sign yum repo metadata if [ -d $YUMDIR ]; then # create file with public key gpg --armor --export releasedocker > "$DOCKER_RELEASE_DIR/yum/gpg" # sign the repo metadata for F in $(find $YUMDIR -name repomd.xml ); do gpg -u releasedocker --passphrase "$GPG_PASSPHRASE" \ --armor --sign --detach-sign \ --batch --yes \ --output "$F.asc" "$F" done fi } sign_packages ================================================ FILE: vendor/github.com/docker/docker/hack/make/test-docker-py ================================================ #!/bin/bash set -e # subshell so that we can export PATH without breaking other things ( bundle .integration-daemon-start dockerPy='/docker-py' [ -d "$dockerPy" ] || { dockerPy="$DEST/docker-py" git clone https://github.com/docker/docker-py.git "$dockerPy" } # exporting PYTHONPATH to import "docker" from our local docker-py test_env PYTHONPATH="$dockerPy" python "$dockerPy/tests/integration_test.py" bundle .integration-daemon-stop ) 2>&1 | tee -a "$DEST/test.log" ================================================ FILE: vendor/github.com/docker/docker/hack/make/test-integration-cli ================================================ #!/bin/bash set -e bundle_test_integration_cli() { TESTFLAGS="$TESTFLAGS -check.v" go_test_dir ./integration-cli } # subshell so that we can export PATH without breaking other things ( bundle .integration-daemon-start bundle .integration-daemon-setup bundle_test_integration_cli bundle .integration-daemon-stop ) 2>&1 | tee -a "$DEST/test.log" ================================================ FILE: vendor/github.com/docker/docker/hack/make/test-unit ================================================ #!/bin/bash set -e : ${PARALLEL_JOBS:=$(nproc 2>/dev/null || echo 1)} # if nproc fails (usually because we don't have it), let's not parallelize by default RED=$'\033[31m' GREEN=$'\033[32m' TEXTRESET=$'\033[0m' # reset the foreground colour # Run Docker's test suite, including sub-packages, and store their output as a bundle # If $TESTFLAGS is set in the environment, it is passed as extra arguments to 'go test'. # You can use this to select certain tests to run, eg. # # TESTFLAGS='-test.run ^TestBuild$' ./hack/make.sh test-unit # bundle_test_unit() { { date # Run all the tests if no TESTDIRS were specified. if [ -z "$TESTDIRS" ]; then TESTDIRS=$(find_dirs '*_test.go') fi ( export LDFLAGS export TESTFLAGS export HAVE_GO_TEST_COVER # some hack to export array variables export BUILDFLAGS_FILE="$DEST/buildflags-file" ( IFS=$'\n'; echo "${BUILDFLAGS[*]}" ) > "$BUILDFLAGS_FILE" if command -v parallel &> /dev/null; then # accomodate parallel to be able to access variables export SHELL="$BASH" export HOME="$(mktemp -d)" mkdir -p "$HOME/.parallel" touch "$HOME/.parallel/ignored_vars" echo "$TESTDIRS" | parallel --jobs "$PARALLEL_JOBS" --env _ "${MAKEDIR}/.go-compile-test-dir" rm -rf "$HOME" else # aww, no "parallel" available - fall back to boring for test_dir in $TESTDIRS; do "${MAKEDIR}/.go-compile-test-dir" "$test_dir" || true # don't let one directory that fails to build tank _all_ our tests! done fi rm -f "$BUILDFLAGS_FILE" ) echo "$TESTDIRS" | go_run_test_dir } } go_run_test_dir() { TESTS_FAILED=() while read dir; do echo echo '+ go test' $TESTFLAGS "${DOCKER_PKG}${dir#.}" precompiled="$ABS_DEST/precompiled/$dir.test$(binary_extension)" if ! ( cd "$dir" && test_env "$precompiled" $TESTFLAGS ); then TESTS_FAILED+=("$dir") echo echo "${RED}Tests failed: $dir${TEXTRESET}" sleep 1 # give it a second, so observers watching can take note fi done echo echo echo # if some tests fail, we want the bundlescript to fail, but we want to # try running ALL the tests first, hence TESTS_FAILED if [ "${#TESTS_FAILED[@]}" -gt 0 ]; then echo "${RED}Test failures in: ${TESTS_FAILED[@]}${TEXTRESET}" echo false else echo "${GREEN}Test success${TEXTRESET}" echo true fi } bundle_test_unit 2>&1 | tee -a "$DEST/test.log" ================================================ FILE: vendor/github.com/docker/docker/hack/make/tgz ================================================ #!/bin/bash CROSS="$DEST/../cross" set -e if [ ! -d "$CROSS/linux/amd64" ]; then echo >&2 'error: binary and cross must be run before tgz' false fi for d in "$CROSS/"*/*; do GOARCH="$(basename "$d")" GOOS="$(basename "$(dirname "$d")")" BINARY_NAME="docker-$VERSION" BINARY_EXTENSION="$(export GOOS && binary_extension)" BINARY_FULLNAME="$BINARY_NAME$BINARY_EXTENSION" mkdir -p "$DEST/$GOOS/$GOARCH" TGZ="$DEST/$GOOS/$GOARCH/$BINARY_NAME.tgz" mkdir -p "$DEST/build" mkdir -p "$DEST/build/usr/local/bin" cp -L "$d/$BINARY_FULLNAME" "$DEST/build/usr/local/bin/docker$BINARY_EXTENSION" tar --numeric-owner --owner 0 -C "$DEST/build" -czf "$TGZ" usr hash_files "$TGZ" rm -rf "$DEST/build" echo "Created tgz: $TGZ" done ================================================ FILE: vendor/github.com/docker/docker/hack/make/ubuntu ================================================ #!/bin/bash PKGVERSION="${VERSION//-/'~'}" # if we have a "-dev" suffix or have change in Git, let's make this package version more complex so it works better if [[ "$VERSION" == *-dev ]] || [ -n "$(git status --porcelain)" ]; then GIT_UNIX="$(git log -1 --pretty='%at')" GIT_DATE="$(date --date "@$GIT_UNIX" +'%Y%m%d.%H%M%S')" GIT_COMMIT="$(git log -1 --pretty='%h')" GIT_VERSION="git${GIT_DATE}.0.${GIT_COMMIT}" # GIT_VERSION is now something like 'git20150128.112847.0.17e840a' PKGVERSION="$PKGVERSION~$GIT_VERSION" fi # $ dpkg --compare-versions 1.5.0 gt 1.5.0~rc1 && echo true || echo false # true # $ dpkg --compare-versions 1.5.0~rc1 gt 1.5.0~git20150128.112847.17e840a && echo true || echo false # true # $ dpkg --compare-versions 1.5.0~git20150128.112847.17e840a gt 1.5.0~dev~git20150128.112847.17e840a && echo true || echo false # true # ie, 1.5.0 > 1.5.0~rc1 > 1.5.0~git20150128.112847.17e840a > 1.5.0~dev~git20150128.112847.17e840a PACKAGE_ARCHITECTURE="$(dpkg-architecture -qDEB_HOST_ARCH)" PACKAGE_URL="https://www.docker.com/" PACKAGE_MAINTAINER="support@docker.com" PACKAGE_DESCRIPTION="Linux container runtime Docker complements LXC with a high-level API which operates at the process level. It runs unix processes with strong guarantees of isolation and repeatability across servers. Docker is a great building block for automating distributed systems: large-scale web deployments, database clusters, continuous deployment systems, private PaaS, service-oriented architectures, etc." PACKAGE_LICENSE="Apache-2.0" # Build docker as an ubuntu package using FPM and REPREPRO (sue me). # bundle_binary must be called first. bundle_ubuntu() { DIR="$ABS_DEST/build" # Include our udev rules mkdir -p "$DIR/etc/udev/rules.d" cp contrib/udev/80-docker.rules "$DIR/etc/udev/rules.d/" # Include our init scripts mkdir -p "$DIR/etc/init" cp contrib/init/upstart/docker.conf "$DIR/etc/init/" mkdir -p "$DIR/etc/init.d" cp contrib/init/sysvinit-debian/docker "$DIR/etc/init.d/" mkdir -p "$DIR/etc/default" cp contrib/init/sysvinit-debian/docker.default "$DIR/etc/default/docker" mkdir -p "$DIR/lib/systemd/system" cp contrib/init/systemd/docker.{service,socket} "$DIR/lib/systemd/system/" # Include contributed completions mkdir -p "$DIR/etc/bash_completion.d" cp contrib/completion/bash/docker "$DIR/etc/bash_completion.d/" mkdir -p "$DIR/usr/share/zsh/vendor-completions" cp contrib/completion/zsh/_docker "$DIR/usr/share/zsh/vendor-completions/" mkdir -p "$DIR/etc/fish/completions" cp contrib/completion/fish/docker.fish "$DIR/etc/fish/completions/" # Include contributed man pages man/md2man-all.sh -q manRoot="$DIR/usr/share/man" mkdir -p "$manRoot" for manDir in man/man?; do manBase="$(basename "$manDir")" # "man1" for manFile in "$manDir"/*; do manName="$(basename "$manFile")" # "docker-build.1" mkdir -p "$manRoot/$manBase" gzip -c "$manFile" > "$manRoot/$manBase/$manName.gz" done done # Include contributed apparmor policy mkdir -p "$DIR/etc/apparmor.d/" cp contrib/apparmor/docker "$DIR/etc/apparmor.d/" # Copy the binary # This will fail if the binary bundle hasn't been built mkdir -p "$DIR/usr/bin" cp "$DEST/../binary/docker-$VERSION" "$DIR/usr/bin/docker" # Generate postinst/prerm/postrm scripts cat > "$DEST/postinst" <<'EOF' #!/bin/sh set -e set -u if [ "$1" = 'configure' ] && [ -z "$2" ]; then if ! getent group docker > /dev/null; then groupadd --system docker fi fi if ( aa-status --enabled ); then /sbin/apparmor_parser -r -W -T /etc/apparmor.d/docker fi if ! { [ -x /sbin/initctl ] && /sbin/initctl version 2>/dev/null | grep -q upstart; }; then # we only need to do this if upstart isn't in charge update-rc.d docker defaults > /dev/null || true fi if [ -n "$2" ]; then _dh_action=restart else _dh_action=start fi service docker $_dh_action 2>/dev/null || true #DEBHELPER# EOF cat > "$DEST/prerm" <<'EOF' #!/bin/sh set -e set -u service docker stop 2>/dev/null || true #DEBHELPER# EOF cat > "$DEST/postrm" <<'EOF' #!/bin/sh set -e set -u if [ "$1" = "purge" ] ; then update-rc.d docker remove > /dev/null || true fi # In case this system is running systemd, we make systemd reload the unit files # to pick up changes. if [ -d /run/systemd/system ] ; then systemctl --system daemon-reload > /dev/null || true fi #DEBHELPER# EOF # TODO swaths of these were borrowed from debhelper's auto-inserted stuff, because we're still using fpm - we need to use debhelper instead, and somehow reconcile Ubuntu that way chmod +x "$DEST/postinst" "$DEST/prerm" "$DEST/postrm" ( # switch directories so we create *.deb in the right folder cd "$DEST" # create lxc-docker-VERSION package fpm -s dir -C "$DIR" \ --name "lxc-docker-$VERSION" --version "$PKGVERSION" \ --after-install "$ABS_DEST/postinst" \ --before-remove "$ABS_DEST/prerm" \ --after-remove "$ABS_DEST/postrm" \ --architecture "$PACKAGE_ARCHITECTURE" \ --prefix / \ --depends iptables \ --deb-recommends aufs-tools \ --deb-recommends ca-certificates \ --deb-recommends git \ --deb-recommends xz-utils \ --deb-recommends 'cgroupfs-mount | cgroup-lite' \ --deb-suggests apparmor \ --description "$PACKAGE_DESCRIPTION" \ --maintainer "$PACKAGE_MAINTAINER" \ --conflicts docker \ --conflicts docker.io \ --conflicts lxc-docker-virtual-package \ --provides lxc-docker \ --provides lxc-docker-virtual-package \ --replaces lxc-docker \ --replaces lxc-docker-virtual-package \ --url "$PACKAGE_URL" \ --license "$PACKAGE_LICENSE" \ --config-files /etc/udev/rules.d/80-docker.rules \ --config-files /etc/init/docker.conf \ --config-files /etc/init.d/docker \ --config-files /etc/default/docker \ --deb-compression gz \ -t deb . # TODO replace "Suggests: cgroup-lite" with "Recommends: cgroupfs-mount | cgroup-lite" once cgroupfs-mount is available # create empty lxc-docker wrapper package fpm -s empty \ --name lxc-docker --version "$PKGVERSION" \ --architecture "$PACKAGE_ARCHITECTURE" \ --depends lxc-docker-$VERSION \ --description "$PACKAGE_DESCRIPTION" \ --maintainer "$PACKAGE_MAINTAINER" \ --url "$PACKAGE_URL" \ --license "$PACKAGE_LICENSE" \ --deb-compression gz \ -t deb ) # clean up after ourselves so we have a clean output directory rm "$DEST/postinst" "$DEST/prerm" "$DEST/postrm" rm -r "$DIR" } bundle_ubuntu ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-dco ================================================ #!/bin/bash source "${MAKEDIR}/.validate" adds=$(validate_diff --numstat | awk '{ s += $1 } END { print s }') dels=$(validate_diff --numstat | awk '{ s += $2 } END { print s }') #notDocs="$(validate_diff --numstat | awk '$3 !~ /^docs\// { print $3 }')" : ${adds:=0} : ${dels:=0} # "Username may only contain alphanumeric characters or dashes and cannot begin with a dash" githubUsernameRegex='[a-zA-Z0-9][a-zA-Z0-9-]+' # https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work dcoPrefix='Signed-off-by:' dcoRegex="^(Docker-DCO-1.1-)?$dcoPrefix ([^<]+) <([^<>@]+@[^<>]+)>( \\(github: ($githubUsernameRegex)\\))?$" check_dco() { grep -qE "$dcoRegex" } if [ $adds -eq 0 -a $dels -eq 0 ]; then echo '0 adds, 0 deletions; nothing to validate! :)' else commits=( $(validate_log --format='format:%H%n') ) badCommits=() for commit in "${commits[@]}"; do if [ -z "$(git log -1 --format='format:' --name-status "$commit")" ]; then # no content (ie, Merge commit, etc) continue fi if ! git log -1 --format='format:%B' "$commit" | check_dco; then badCommits+=( "$commit" ) fi done if [ ${#badCommits[@]} -eq 0 ]; then echo "Congratulations! All commits are properly signed with the DCO!" else { echo "These commits do not have a proper '$dcoPrefix' marker:" for commit in "${badCommits[@]}"; do echo " - $commit" done echo echo 'Please amend each commit to include a properly formatted DCO marker.' echo echo 'Visit the following URL for information about the Docker DCO:' echo ' https://github.com/docker/docker/blob/master/CONTRIBUTING.md#sign-your-work' echo } >&2 false fi fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-gofmt ================================================ #!/bin/bash source "${MAKEDIR}/.validate" IFS=$'\n' files=( $(validate_diff --diff-filter=ACMR --name-only -- '*.go' | grep -v '^vendor/' || true) ) unset IFS badFiles=() for f in "${files[@]}"; do # we use "git show" here to validate that what's committed is formatted if [ "$(git show "$VALIDATE_HEAD:$f" | gofmt -s -l)" ]; then badFiles+=( "$f" ) fi done if [ ${#badFiles[@]} -eq 0 ]; then echo 'Congratulations! All Go source files are properly formatted.' else { echo "These files are not properly gofmt'd:" for f in "${badFiles[@]}"; do echo " - $f" done echo echo 'Please reformat the above files using "gofmt -s -w" and commit the result.' echo } >&2 false fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-lint ================================================ #!/bin/bash source "${MAKEDIR}/.validate" # We will eventually get to the point when packages should be the complete list # of subpackages, vendoring excluded, as given by: # # packages=( $(go list ./... 2> /dev/null | grep -vE "^github.com/docker/docker/vendor" || true ) ) packages=( builder/parser/dumper daemon/events daemon/execdriver/native/template daemon/graphdriver/btrfs daemon/network docker dockerinit pkg/chrootarchive pkg/directory pkg/fileutils pkg/homedir pkg/listenbuffer pkg/mflag/example pkg/mount pkg/namesgenerator pkg/promise pkg/pubsub pkg/random pkg/reexec pkg/symlink pkg/timeutils pkg/tlsconfig pkg/urlutil pkg/version utils ) errors=() for p in "${packages[@]}"; do failedLint=$(golint "$p") if [ "$failedLint" ]; then errors+=( "$failedLint" ) fi done if [ ${#errors[@]} -eq 0 ]; then echo 'Congratulations! All Go source files have been linted.' else { echo "Errors from golint:" for err in "${errors[@]}"; do echo "$err" done echo echo 'Please fix the above errors. You can test via "golint" and commit the result.' echo } >&2 false fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-pkg ================================================ #!/bin/bash set -e source "${MAKEDIR}/.validate" IFS=$'\n' files=( $(validate_diff --diff-filter=ACMR --name-only -- 'pkg/*.go' || true) ) unset IFS badFiles=() for f in "${files[@]}"; do IFS=$'\n' badImports=( $(go list -e -f '{{ join .Deps "\n" }}' "$f" | sort -u | grep -vE '^github.com/docker/docker/pkg/' | grep -E '^github.com/docker/docker' || true) ) unset IFS for import in "${badImports[@]}"; do badFiles+=( "$f imports $import" ) done done if [ ${#badFiles[@]} -eq 0 ]; then echo 'Congratulations! "./pkg/..." is safely isolated from internal code.' else { echo 'These files import internal code: (either directly or indirectly)' for f in "${badFiles[@]}"; do echo " - $f" done echo } >&2 false fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-test ================================================ #!/bin/bash # Make sure we're not using gos' Testing package any more in integration-cli source "${MAKEDIR}/.validate" IFS=$'\n' files=( $(validate_diff --diff-filter=ACMR --name-only -- 'integration-cli/*.go' || true) ) unset IFS badFiles=() for f in "${files[@]}"; do # skip check_test.go since it *does* use the testing package if [ "$f" = "integration-cli/check_test.go" ]; then continue fi # we use "git show" here to validate that what's committed is formatted if git show "$VALIDATE_HEAD:$f" | grep -q testing.T; then badFiles+=( "$f" ) fi done if [ ${#badFiles[@]} -eq 0 ]; then echo 'Congratulations! No testing.T found.' else { echo "These files use the wrong testing infrastructure:" for f in "${badFiles[@]}"; do echo " - $f" done echo } >&2 false fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-toml ================================================ #!/bin/bash source "${MAKEDIR}/.validate" IFS=$'\n' files=( $(validate_diff --diff-filter=ACMR --name-only -- 'MAINTAINERS' || true) ) unset IFS badFiles=() for f in "${files[@]}"; do # we use "git show" here to validate that what's committed is formatted if ! git show "$VALIDATE_HEAD:$f" | tomlv /proc/self/fd/0 ; then badFiles+=( "$f" ) fi done if [ ${#badFiles[@]} -eq 0 ]; then echo 'Congratulations! All toml source files changed here have valid syntax.' else { echo "These files are not valid toml:" for f in "${badFiles[@]}"; do echo " - $f" done echo echo 'Please reformat the above files as valid toml' echo } >&2 false fi ================================================ FILE: vendor/github.com/docker/docker/hack/make/validate-vet ================================================ #!/bin/bash source "${MAKEDIR}/.validate" IFS=$'\n' files=( $(validate_diff --diff-filter=ACMR --name-only -- '*.go' | grep -v '^vendor/' || true) ) unset IFS errors=() for f in "${files[@]}"; do # we use "git show" here to validate that what's committed passes go vet failedVet=$(go vet "$f") if [ "$failedVet" ]; then errors+=( "$failedVet" ) fi done if [ ${#errors[@]} -eq 0 ]; then echo 'Congratulations! All Go source files have been vetted.' else { echo "Errors from go vet:" for err in "${errors[@]}"; do echo " - $err" done echo echo 'Please fix the above errors. You can test via "go vet" and commit the result.' echo } >&2 false fi ================================================ FILE: vendor/github.com/docker/docker/hack/make.sh ================================================ #!/usr/bin/env bash set -e # This script builds various binary artifacts from a checkout of the docker # source code. # # Requirements: # - The current directory should be a checkout of the docker source code # (https://github.com/docker/docker). Whatever version is checked out # will be built. # - The VERSION file, at the root of the repository, should exist, and # will be used as Docker binary version and package version. # - The hash of the git commit will also be included in the Docker binary, # with the suffix -dirty if the repository isn't clean. # - The script is intented to be run inside the docker container specified # in the Dockerfile at the root of the source. In other words: # DO NOT CALL THIS SCRIPT DIRECTLY. # - The right way to call this script is to invoke "make" from # your checkout of the Docker repository. # the Makefile will do a "docker build -t docker ." and then # "docker run hack/make.sh" in the resulting image. # set -o pipefail export DOCKER_PKG='github.com/docker/docker' export SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" export MAKEDIR="$SCRIPTDIR/make" # We're a nice, sexy, little shell script, and people might try to run us; # but really, they shouldn't. We want to be in a container! if [ "$PWD" != "/go/src/$DOCKER_PKG" ] || [ -z "$DOCKER_CROSSPLATFORMS" ]; then { echo "# WARNING! I don't seem to be running in the Docker container." echo "# The result of this command might be an incorrect build, and will not be" echo "# officially supported." echo "#" echo "# Try this instead: make all" echo "#" } >&2 fi echo # List of bundles to create when no argument is passed DEFAULT_BUNDLES=( validate-dco validate-gofmt validate-pkg validate-test validate-toml validate-vet binary test-unit test-integration-cli test-docker-py dynbinary cover cross tgz ubuntu ) VERSION=$(< ./VERSION) if command -v git &> /dev/null && git rev-parse &> /dev/null; then GITCOMMIT=$(git rev-parse --short HEAD) if [ -n "$(git status --porcelain --untracked-files=no)" ]; then GITCOMMIT="$GITCOMMIT-dirty" fi BUILDTIME=$(date -u) elif [ "$DOCKER_GITCOMMIT" ]; then GITCOMMIT="$DOCKER_GITCOMMIT" else echo >&2 'error: .git directory missing and DOCKER_GITCOMMIT not specified' echo >&2 ' Please either build with the .git directory accessible, or specify the' echo >&2 ' exact (--short) commit hash you are building using DOCKER_GITCOMMIT for' echo >&2 ' future accountability in diagnosing build issues. Thanks!' exit 1 fi if [ "$AUTO_GOPATH" ]; then rm -rf .gopath mkdir -p .gopath/src/"$(dirname "${DOCKER_PKG}")" ln -sf ../../../.. .gopath/src/"${DOCKER_PKG}" export GOPATH="${PWD}/.gopath:${PWD}/vendor" fi if [ ! "$GOPATH" ]; then echo >&2 'error: missing GOPATH; please see https://golang.org/doc/code.html#GOPATH' echo >&2 ' alternatively, set AUTO_GOPATH=1' exit 1 fi if [ "$DOCKER_EXPERIMENTAL" ]; then echo >&2 '# WARNING! DOCKER_EXPERIMENTAL is set: building experimental features' echo >&2 DOCKER_BUILDTAGS+=" experimental" fi if [ -z "$DOCKER_CLIENTONLY" ]; then DOCKER_BUILDTAGS+=" daemon" fi if [ "$DOCKER_EXECDRIVER" = 'lxc' ]; then DOCKER_BUILDTAGS+=' test_no_exec' fi # test whether "btrfs/version.h" exists and apply btrfs_noversion appropriately if \ command -v gcc &> /dev/null \ && ! gcc -E - &> /dev/null <<<'#include ' \ ; then DOCKER_BUILDTAGS+=' btrfs_noversion' fi # test whether "libdevmapper.h" is new enough to support deferred remove # functionality. if \ command -v gcc &> /dev/null \ && ! ( echo -e '#include \nint main() { dm_task_deferred_remove(NULL); }'| gcc -ldevmapper -xc - &> /dev/null ) \ ; then DOCKER_BUILDTAGS+=' libdm_no_deferred_remove' fi # Use these flags when compiling the tests and final binary IAMSTATIC='true' source "$SCRIPTDIR/make/.go-autogen" if [ -z "$DOCKER_DEBUG" ]; then LDFLAGS='-w' fi LDFLAGS_STATIC='-linkmode external' # Cgo -H windows is incompatible with -linkmode external. if [ "$(go env GOOS)" == 'windows' ]; then LDFLAGS_STATIC='' fi EXTLDFLAGS_STATIC='-static' # ORIG_BUILDFLAGS is necessary for the cross target which cannot always build # with options like -race. ORIG_BUILDFLAGS=( -a -tags "netgo static_build $DOCKER_BUILDTAGS" -installsuffix netgo ) # see https://github.com/golang/go/issues/9369#issuecomment-69864440 for why -installsuffix is necessary here BUILDFLAGS=( $BUILDFLAGS "${ORIG_BUILDFLAGS[@]}" ) # Test timeout. : ${TIMEOUT:=60m} TESTFLAGS+=" -test.timeout=${TIMEOUT}" # A few more flags that are specific just to building a completely-static binary (see hack/make/binary) # PLEASE do not use these anywhere else. EXTLDFLAGS_STATIC_DOCKER="$EXTLDFLAGS_STATIC -lpthread -Wl,--unresolved-symbols=ignore-in-object-files" LDFLAGS_STATIC_DOCKER=" $LDFLAGS_STATIC -extldflags \"$EXTLDFLAGS_STATIC_DOCKER\" " if [ "$(uname -s)" = 'FreeBSD' ]; then # Tell cgo the compiler is Clang, not GCC # https://code.google.com/p/go/source/browse/src/cmd/cgo/gcc.go?spec=svne77e74371f2340ee08622ce602e9f7b15f29d8d3&r=e6794866ebeba2bf8818b9261b54e2eef1c9e588#752 export CC=clang # "-extld clang" is a workaround for # https://code.google.com/p/go/issues/detail?id=6845 LDFLAGS="$LDFLAGS -extld clang" fi # If sqlite3.h doesn't exist under /usr/include, # check /usr/local/include also just in case # (e.g. FreeBSD Ports installs it under the directory) if [ ! -e /usr/include/sqlite3.h ] && [ -e /usr/local/include/sqlite3.h ]; then export CGO_CFLAGS='-I/usr/local/include' export CGO_LDFLAGS='-L/usr/local/lib' fi HAVE_GO_TEST_COVER= if \ go help testflag | grep -- -cover > /dev/null \ && go tool -n cover > /dev/null 2>&1 \ ; then HAVE_GO_TEST_COVER=1 fi # If $TESTFLAGS is set in the environment, it is passed as extra arguments to 'go test'. # You can use this to select certain tests to run, eg. # # TESTFLAGS='-test.run ^TestBuild$' ./hack/make.sh test-unit # # For integration-cli test, we use [gocheck](https://labix.org/gocheck), if you want # to run certain tests on your local host, you should run with command: # # TESTFLAGS='-check.f DockerSuite.TestBuild*' ./hack/make.sh binary test-integration-cli # go_test_dir() { dir=$1 coverpkg=$2 testcover=() if [ "$HAVE_GO_TEST_COVER" ]; then # if our current go install has -cover, we want to use it :) mkdir -p "$DEST/coverprofiles" coverprofile="docker${dir#.}" coverprofile="$ABS_DEST/coverprofiles/${coverprofile//\//-}" testcover=( -cover -coverprofile "$coverprofile" $coverpkg ) fi ( echo '+ go test' $TESTFLAGS "${DOCKER_PKG}${dir#.}" cd "$dir" export DEST="$ABS_DEST" # we're in a subshell, so this is safe -- our integration-cli tests need DEST, and "cd" screws it up test_env go test ${testcover[@]} -ldflags "$LDFLAGS" "${BUILDFLAGS[@]}" $TESTFLAGS ) } test_env() { # use "env -i" to tightly control the environment variables that bleed into the tests env -i \ DEST="$DEST" \ DOCKER_EXECDRIVER="$DOCKER_EXECDRIVER" \ DOCKER_GRAPHDRIVER="$DOCKER_GRAPHDRIVER" \ DOCKER_USERLANDPROXY="$DOCKER_USERLANDPROXY" \ DOCKER_HOST="$DOCKER_HOST" \ GOPATH="$GOPATH" \ HOME="$ABS_DEST/fake-HOME" \ PATH="$PATH" \ TEMP="$TEMP" \ TEST_DOCKERINIT_PATH="$TEST_DOCKERINIT_PATH" \ "$@" } # a helper to provide ".exe" when it's appropriate binary_extension() { if [ "$(go env GOOS)" = 'windows' ]; then echo -n '.exe' fi } # This helper function walks the current directory looking for directories # holding certain files ($1 parameter), and prints their paths on standard # output, one per line. find_dirs() { find . -not \( \ \( \ -path './vendor/*' \ -o -path './integration-cli/*' \ -o -path './contrib/*' \ -o -path './pkg/mflag/example/*' \ -o -path './.git/*' \ -o -path './bundles/*' \ -o -path './docs/*' \ -o -path './pkg/libcontainer/nsinit/*' \ \) \ -prune \ \) -name "$1" -print0 | xargs -0n1 dirname | sort -u } hash_files() { while [ $# -gt 0 ]; do f="$1" shift dir="$(dirname "$f")" base="$(basename "$f")" for hashAlgo in md5 sha256; do if command -v "${hashAlgo}sum" &> /dev/null; then ( # subshell and cd so that we get output files like: # $HASH docker-$VERSION # instead of: # $HASH /go/src/github.com/.../$VERSION/binary/docker-$VERSION cd "$dir" "${hashAlgo}sum" "$base" > "$base.$hashAlgo" ) fi done done } bundle() { local bundle="$1"; shift echo "---> Making bundle: $(basename "$bundle") (in $DEST)" source "$SCRIPTDIR/make/$bundle" "$@" } main() { # We want this to fail if the bundles already exist and cannot be removed. # This is to avoid mixing bundles from different versions of the code. mkdir -p bundles if [ -e "bundles/$VERSION" ]; then echo "bundles/$VERSION already exists. Removing." rm -fr "bundles/$VERSION" && mkdir "bundles/$VERSION" || exit 1 echo fi if [ "$(go env GOHOSTOS)" != 'windows' ]; then # Windows and symlinks don't get along well rm -f bundles/latest ln -s "$VERSION" bundles/latest fi if [ $# -lt 1 ]; then bundles=(${DEFAULT_BUNDLES[@]}) else bundles=($@) fi for bundle in ${bundles[@]}; do export DEST="bundles/$VERSION/$(basename "$bundle")" # Cygdrive paths don't play well with go build -o. if [[ "$(uname -s)" == CYGWIN* ]]; then export DEST="$(cygpath -mw "$DEST")" fi mkdir -p "$DEST" ABS_DEST="$(cd "$DEST" && pwd -P)" bundle "$bundle" echo done } main "$@" ================================================ FILE: vendor/github.com/docker/docker/hack/release.sh ================================================ #!/usr/bin/env bash set -e # This script looks for bundles built by make.sh, and releases them on a # public S3 bucket. # # Bundles should be available for the VERSION string passed as argument. # # The correct way to call this script is inside a container built by the # official Dockerfile at the root of the Docker source code. The Dockerfile, # make.sh and release.sh should all be from the same source code revision. set -o pipefail # Print a usage message and exit. usage() { cat >&2 <<'EOF' To run, I need: - to be in a container generated by the Dockerfile at the top of the Docker repository; - to be provided with the name of an S3 bucket, in environment variable AWS_S3_BUCKET; - to be provided with AWS credentials for this S3 bucket, in environment variables AWS_ACCESS_KEY and AWS_SECRET_KEY; - the passphrase to unlock the GPG key which will sign the deb packages (passed as environment variable GPG_PASSPHRASE); - a generous amount of good will and nice manners. The canonical way to run me is to run the image produced by the Dockerfile: e.g.:" docker run -e AWS_S3_BUCKET=test.docker.com \ -e AWS_ACCESS_KEY=... \ -e AWS_SECRET_KEY=... \ -e GPG_PASSPHRASE=... \ -i -t --privileged \ docker ./hack/release.sh EOF exit 1 } [ "$AWS_S3_BUCKET" ] || usage [ "$AWS_ACCESS_KEY" ] || usage [ "$AWS_SECRET_KEY" ] || usage [ "$GPG_PASSPHRASE" ] || usage [ -d /go/src/github.com/docker/docker ] || usage cd /go/src/github.com/docker/docker [ -x hack/make.sh ] || usage RELEASE_BUNDLES=( binary cross tgz ubuntu ) if [ "$1" != '--release-regardless-of-test-failure' ]; then RELEASE_BUNDLES=( test-unit "${RELEASE_BUNDLES[@]}" test-integration-cli ) fi VERSION=$(< VERSION) BUCKET=$AWS_S3_BUCKET # These are the 2 keys we've used to sign the deb's # release (get.docker.com) # GPG_KEY="36A1D7869245C8950F966E92D8576A8BA88D21E9" # test (test.docker.com) # GPG_KEY="740B314AE3941731B942C66ADF4FD13717AAD7D6" setup_s3() { # Try creating the bucket. Ignore errors (it might already exist). s3cmd mb "s3://$BUCKET" 2>/dev/null || true # Check access to the bucket. # s3cmd has no useful exit status, so we cannot check that. # Instead, we check if it outputs anything on standard output. # (When there are problems, it uses standard error instead.) s3cmd info "s3://$BUCKET" | grep -q . # Make the bucket accessible through website endpoints. s3cmd ws-create --ws-index index --ws-error error "s3://$BUCKET" } # write_to_s3 uploads the contents of standard input to the specified S3 url. write_to_s3() { DEST=$1 F=`mktemp` cat > "$F" s3cmd --acl-public --mime-type='text/plain' put "$F" "$DEST" rm -f "$F" } s3_url() { case "$BUCKET" in get.docker.com|test.docker.com|experimental.docker.com) echo "https://$BUCKET" ;; *) s3cmd ws-info s3://$BUCKET | awk -v 'FS=: +' '/http:\/\/'$BUCKET'/ { gsub(/\/+$/, "", $2); print $2 }' ;; esac } build_all() { if ! ./hack/make.sh "${RELEASE_BUNDLES[@]}"; then echo >&2 echo >&2 'The build or tests appear to have failed.' echo >&2 echo >&2 'You, as the release maintainer, now have a couple options:' echo >&2 '- delay release and fix issues' echo >&2 '- delay release and fix issues' echo >&2 '- did we mention how important this is? issues need fixing :)' echo >&2 echo >&2 'As a final LAST RESORT, you (because only you, the release maintainer,' echo >&2 ' really knows all the hairy problems at hand with the current release' echo >&2 ' issues) may bypass this checking by running this script again with the' echo >&2 ' single argument of "--release-regardless-of-test-failure", which will skip' echo >&2 ' running the test suite, and will only build the binaries and packages. Please' echo >&2 ' avoid using this if at all possible.' echo >&2 echo >&2 'Regardless, we cannot stress enough the scarcity with which this bypass' echo >&2 ' should be used. If there are release issues, we should always err on the' echo >&2 ' side of caution.' echo >&2 exit 1 fi } upload_release_build() { src="$1" dst="$2" latest="$3" echo echo "Uploading $src" echo " to $dst" echo s3cmd --follow-symlinks --preserve --acl-public put "$src" "$dst" if [ "$latest" ]; then echo echo "Copying to $latest" echo s3cmd --acl-public cp "$dst" "$latest" fi # get hash files too (see hash_files() in hack/make.sh) for hashAlgo in md5 sha256; do if [ -e "$src.$hashAlgo" ]; then echo echo "Uploading $src.$hashAlgo" echo " to $dst.$hashAlgo" echo s3cmd --follow-symlinks --preserve --acl-public --mime-type='text/plain' put "$src.$hashAlgo" "$dst.$hashAlgo" if [ "$latest" ]; then echo echo "Copying to $latest.$hashAlgo" echo s3cmd --acl-public cp "$dst.$hashAlgo" "$latest.$hashAlgo" fi fi done } release_build() { GOOS=$1 GOARCH=$2 binDir=bundles/$VERSION/cross/$GOOS/$GOARCH tgzDir=bundles/$VERSION/tgz/$GOOS/$GOARCH binary=docker-$VERSION tgz=docker-$VERSION.tgz latestBase= if [ -z "$NOLATEST" ]; then latestBase=docker-latest fi # we need to map our GOOS and GOARCH to uname values # see https://en.wikipedia.org/wiki/Uname # ie, GOOS=linux -> "uname -s"=Linux s3Os=$GOOS case "$s3Os" in darwin) s3Os=Darwin ;; freebsd) s3Os=FreeBSD ;; linux) s3Os=Linux ;; windows) s3Os=Windows binary+='.exe' if [ "$latestBase" ]; then latestBase+='.exe' fi ;; *) echo >&2 "error: can't convert $s3Os to an appropriate value for 'uname -s'" exit 1 ;; esac s3Arch=$GOARCH case "$s3Arch" in amd64) s3Arch=x86_64 ;; 386) s3Arch=i386 ;; arm) s3Arch=armel # someday, we might potentially support mutliple GOARM values, in which case we might get armhf here too ;; *) echo >&2 "error: can't convert $s3Arch to an appropriate value for 'uname -m'" exit 1 ;; esac s3Dir=s3://$BUCKET/builds/$s3Os/$s3Arch latest= latestTgz= if [ "$latestBase" ]; then latest="$s3Dir/$latestBase" latestTgz="$s3Dir/$latestBase.tgz" fi if [ ! -x "$binDir/$binary" ]; then echo >&2 "error: can't find $binDir/$binary - was it compiled properly?" exit 1 fi if [ ! -f "$tgzDir/$tgz" ]; then echo >&2 "error: can't find $tgzDir/$tgz - was it packaged properly?" exit 1 fi upload_release_build "$binDir/$binary" "$s3Dir/$binary" "$latest" upload_release_build "$tgzDir/$tgz" "$s3Dir/$tgz" "$latestTgz" } # Upload the 'ubuntu' bundle to S3: # 1. A full APT repository is published at $BUCKET/ubuntu/ # 2. Instructions for using the APT repository are uploaded at $BUCKET/ubuntu/index release_ubuntu() { [ -e "bundles/$VERSION/ubuntu" ] || { echo >&2 './hack/make.sh must be run before release_ubuntu' exit 1 } local debfiles=( "bundles/$VERSION/ubuntu/"*.deb ) # Sign our packages dpkg-sig -g "--passphrase $GPG_PASSPHRASE" -k releasedocker --sign builder "${debfiles[@]}" # Setup the APT repo APTDIR=bundles/$VERSION/ubuntu/apt mkdir -p "$APTDIR/conf" "$APTDIR/db" s3cmd sync "s3://$BUCKET/ubuntu/db/" "$APTDIR/db/" || true cat > "$APTDIR/conf/distributions" < "bundles/$VERSION/ubuntu/gpg" s3cmd --acl-public put "bundles/$VERSION/ubuntu/gpg" "s3://$BUCKET/gpg" local gpgFingerprint=36A1D7869245C8950F966E92D8576A8BA88D21E9 local s3Headers= if [[ $BUCKET == test* ]]; then gpgFingerprint=740B314AE3941731B942C66ADF4FD13717AAD7D6 elif [[ $BUCKET == experimental* ]]; then gpgFingerprint=E33FF7BF5C91D50A6F91FFFD4CC38D40F9A96B49 s3Headers='--add-header=Cache-Control:no-cache' fi # Upload repo s3cmd --acl-public "$s3Headers" sync "$APTDIR/" "s3://$BUCKET/ubuntu/" cat < /etc/apt/sources.list.d/docker.list # Then import the repository key apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys $gpgFingerprint # Install docker apt-get update apt-get install -y lxc-docker # # Alternatively, just use the curl-able install.sh script provided at $(s3_url) # EOF # Add redirect at /ubuntu/info for URL-backwards-compatibility rm -rf /tmp/emptyfile && touch /tmp/emptyfile s3cmd --acl-public --add-header='x-amz-website-redirect-location:/ubuntu/' --mime-type='text/plain' put /tmp/emptyfile "s3://$BUCKET/ubuntu/info" echo "APT repository uploaded. Instructions available at $(s3_url)/ubuntu" } # Upload binaries and tgz files to S3 release_binaries() { [ -e "bundles/$VERSION/cross/linux/amd64/docker-$VERSION" ] || { echo >&2 './hack/make.sh must be run before release_binaries' exit 1 } for d in bundles/$VERSION/cross/*/*; do GOARCH="$(basename "$d")" GOOS="$(basename "$(dirname "$d")")" release_build "$GOOS" "$GOARCH" done # TODO create redirect from builds/*/i686 to builds/*/i386 cat </dev/null || { gpg --gen-key --batch <

Layer
Images are composed of layers. Image layer is a general term which may be used to refer to one or both of the following:
  1. The metadata for the layer, described in the JSON format.
  2. The filesystem changes described by a layer.
To refer to the former you may use the term Layer JSON or Layer Metadata. To refer to the latter you may use the term Image Filesystem Changeset or Image Diff.
Image JSON
Each layer has an associated JSON structure which describes some basic information about the image such as date created, author, and the ID of its parent image as well as execution/runtime configuration like its entry point, default arguments, CPU/memory shares, networking, and volumes.
Image Filesystem Changeset
Each layer has an archive of the files which have been added, changed, or deleted relative to its parent layer. Using a layer-based or union filesystem such as AUFS, or by computing the diff from filesystem snapshots, the filesystem changeset can be used to present a series of image layers as if they were one cohesive filesystem.
Image ID
Each layer is given an ID upon its creation. It is represented as a hexadecimal encoding of 256 bits, e.g., a9561eb1b190625c9adb5a9513e72c4dedafc1cb2d4c5236c9a6957ec7dfd5a9. Image IDs should be sufficiently random so as to be globally unique. 32 bytes read from /dev/urandom is sufficient for all practical purposes. Alternatively, an image ID may be derived as a cryptographic hash of image contents as the result is considered indistinguishable from random. The choice is left up to implementors.
Image Parent
Most layer metadata structs contain a parent field which refers to the Image from which another directly descends. An image contains a separate JSON metadata file and set of changes relative to the filesystem of its parent image. Image Ancestor and Image Descendant are also common terms.
Image Checksum
Layer metadata structs contain a cryptographic hash of the contents of the layer's filesystem changeset. Though the set of changes exists as a simple Tar archive, two archives with identical filenames and content will have different SHA digests if the last-access or last-modified times of any entries differ. For this reason, image checksums are generated using the TarSum algorithm which produces a cryptographic hash of file contents and selected headers only. Details of this algorithm are described in the separate TarSum specification.
Tag
A tag serves to map a descriptive, user-given name to any single image ID. An image name suffix (the name component after :) is often referred to as a tag as well, though it strictly refers to the full name of an image. Acceptable values for a tag suffix are implementation specific, but they SHOULD be limited to the set of alphanumeric characters [a-zA-z0-9], punctuation characters [._-], and MUST NOT contain a : character.
Repository
A collection of tags grouped under a common prefix (the name component before :). For example, in an image tagged with the name my-app:3.1.4, my-app is the Repository component of the name. Acceptable values for repository name are implementation specific, but they SHOULD be limited to the set of alphanumeric characters [a-zA-z0-9], and punctuation characters [._-], however it MAY contain additional / and : characters for organizational purposes, with the last : character being interpreted dividing the repository component of the name from the tag suffix component.
## Image JSON Description Here is an example image JSON file: ``` { "id": "a9561eb1b190625c9adb5a9513e72c4dedafc1cb2d4c5236c9a6957ec7dfd5a9", "parent": "c6e3cedcda2e3982a1a6760e178355e8e65f7b80e4e5248743fa3549d284e024", "checksum": "tarsum.v1+sha256:e58fcf7418d2390dec8e8fb69d88c06ec07039d651fedc3aa72af9972e7d046b", "created": "2014-10-13T21:19:18.674353812Z", "author": "Alyssa P. Hacker <alyspdev@example.com>", "architecture": "amd64", "os": "linux", "Size": 271828, "config": { "User": "alice", "Memory": 2048, "MemorySwap": 4096, "CpuShares": 8, "ExposedPorts": { "8080/tcp": {} }, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "FOO=docker_is_a_really", "BAR=great_tool_you_know" ], "Entrypoint": [ "/bin/my-app-binary" ], "Cmd": [ "--foreground", "--config", "/etc/my-app.d/default.cfg" ], "Volumes": { "/var/job-result-data": {}, "/var/log/my-app-logs": {}, }, "WorkingDir": "/home/alice", } } ``` ### Image JSON Field Descriptions
id string
Randomly generated, 256-bit, hexadecimal encoded. Uniquely identifies the image.
parent string
ID of the parent image. If there is no parent image then this field should be omitted. A collection of images may share many of the same ancestor layers. This organizational structure is strictly a tree with any one layer having either no parent or a single parent and zero or more descendent layers. Cycles are not allowed and implementations should be careful to avoid creating them or iterating through a cycle indefinitely.
created string
ISO-8601 formatted combined date and time at which the image was created.
author string
Gives the name and/or email address of the person or entity which created and is responsible for maintaining the image.
architecture string
The CPU architecture which the binaries in this image are built to run on. Possible values include:
  • 386
  • amd64
  • arm
More values may be supported in the future and any of these may or may not be supported by a given container runtime implementation.
os string
The name of the operating system which the image is built to run on. Possible values include:
  • darwin
  • freebsd
  • linux
More values may be supported in the future and any of these may or may not be supported by a given container runtime implementation.
checksum string
Image Checksum of the filesystem changeset associated with the image layer.
Size integer
The size in bytes of the filesystem changeset associated with the image layer.
config struct
The execution parameters which should be used as a base when running a container using the image. This field can be null, in which case any execution parameters should be specified at creation of the container.

Container RunConfig Field Descriptions

User string

The username or UID which the process in the container should run as. This acts as a default value to use when the value is not specified when creating a container.

All of the following are valid:

  • user
  • uid
  • user:group
  • uid:gid
  • uid:group
  • user:gid

If group/gid is not specified, the default group and supplementary groups of the given user/uid in /etc/passwd from the container are applied.

Memory integer
Memory limit (in bytes). This acts as a default value to use when the value is not specified when creating a container.
MemorySwap integer
Total memory usage (memory + swap); set to -1 to disable swap. This acts as a default value to use when the value is not specified when creating a container.
CpuShares integer
CPU shares (relative weight vs. other containers). This acts as a default value to use when the value is not specified when creating a container.
ExposedPorts struct
A set of ports to expose from a container running this image. This JSON structure value is unusual because it is a direct JSON serialization of the Go type map[string]struct{} and is represented in JSON as an object mapping its keys to an empty object. Here is an example:
{
    "8080": {},
    "53/udp": {},
    "2356/tcp": {}
}
Its keys can be in the format of:
  • "port/tcp"
  • "port/udp"
  • "port"
with the default protocol being "tcp" if not specified. These values act as defaults and are merged with any specified when creating a container.
Env array of strings
Entries are in the format of VARNAME="var value". These values act as defaults and are merged with any specified when creating a container.
Entrypoint array of strings
A list of arguments to use as the command to execute when the container starts. This value acts as a default and is replaced by an entrypoint specified when creating a container.
Cmd array of strings
Default arguments to the entry point of the container. These values act as defaults and are replaced with any specified when creating a container. If an Entrypoint value is not specified, then the first entry of the Cmd array should be interpreted as the executable to run.
Volumes struct
A set of directories which should be created as data volumes in a container running this image. This JSON structure value is unusual because it is a direct JSON serialization of the Go type map[string]struct{} and is represented in JSON as an object mapping its keys to an empty object. Here is an example:
{
    "/var/my-app-data/": {},
    "/etc/some-config.d/": {},
}
WorkingDir string
Sets the current working directory of the entry point process in the container. This value acts as a default and is replaced by a working directory specified when creating a container.
Any extra fields in the Image JSON struct are considered implementation specific and should be ignored by any implementations which are unable to interpret them. ## Creating an Image Filesystem Changeset An example of creating an Image Filesystem Changeset follows. An image root filesystem is first created as an empty directory named with the ID of the image being created. Here is the initial empty directory structure for the changeset for an image with ID `c3167915dc9d` ([real IDs are much longer](#id_desc), but this example use a truncated one here for brevity. Implementations need not name the rootfs directory in this way but it may be convenient for keeping record of a large number of image layers.): ``` c3167915dc9d/ ``` Files and directories are then created: ``` c3167915dc9d/ etc/ my-app-config bin/ my-app-binary my-app-tools ``` The `c3167915dc9d` directory is then committed as a plain Tar archive with entries for the following files: ``` etc/my-app-config bin/my-app-binary bin/my-app-tools ``` The TarSum checksum for the archive file is then computed and placed in the JSON metadata along with the execution parameters. To make changes to the filesystem of this container image, create a new directory named with a new ID, such as `f60c56784b83`, and initialize it with a snapshot of the parent image's root filesystem, so that the directory is identical to that of `c3167915dc9d`. NOTE: a copy-on-write or union filesystem can make this very efficient: ``` f60c56784b83/ etc/ my-app-config bin/ my-app-binary my-app-tools ``` This example change is going add a configuration directory at `/etc/my-app.d` which contains a default config file. There's also a change to the `my-app-tools` binary to handle the config layout change. The `f60c56784b83` directory then looks like this: ``` f60c56784b83/ etc/ my-app.d/ default.cfg bin/ my-app-binary my-app-tools ``` This reflects the removal of `/etc/my-app-config` and creation of a file and directory at `/etc/my-app.d/default.cfg`. `/bin/my-app-tools` has also been replaced with an updated version. Before committing this directory to a changeset, because it has a parent image, it is first compared with the directory tree of the parent snapshot, `f60c56784b83`, looking for files and directories that have been added, modified, or removed. The following changeset is found: ``` Added: /etc/my-app.d/default.cfg Modified: /bin/my-app-tools Deleted: /etc/my-app-config ``` A Tar Archive is then created which contains *only* this changeset: The added and modified files and directories in their entirety, and for each deleted item an entry for an empty file at the same location but with the basename of the deleted file or directory prefixed with `.wh.`. The filenames prefixed with `.wh.` are known as "whiteout" files. NOTE: For this reason, it is not possible to create an image root filesystem which contains a file or directory with a name beginning with `.wh.`. The resulting Tar archive for `f60c56784b83` has the following entries: ``` /etc/my-app.d/default.cfg /bin/my-app-tools /etc/.wh.my-app-config ``` Any given image is likely to be composed of several of these Image Filesystem Changeset tar archives. ## Combined Image JSON + Filesystem Changeset Format There is also a format for a single archive which contains complete information about an image, including: - repository names/tags - all image layer JSON files - all tar archives of each layer filesystem changesets For example, here's what the full archive of `library/busybox` is (displayed in `tree` format): ``` . ├── 5785b62b697b99a5af6cd5d0aabc804d5748abbb6d3d07da5d1d3795f2dcc83e │   ├── VERSION │   ├── json │   └── layer.tar ├── a7b8b41220991bfc754d7ad445ad27b7f272ab8b4a2c175b9512b97471d02a8a │   ├── VERSION │   ├── json │   └── layer.tar ├── a936027c5ca8bf8f517923169a233e391cbb38469a75de8383b5228dc2d26ceb │   ├── VERSION │   ├── json │   └── layer.tar ├── f60c56784b832dd990022afc120b8136ab3da9528094752ae13fe63a2d28dc8c │   ├── VERSION │   ├── json │   └── layer.tar └── repositories ``` There are one or more directories named with the ID for each layer in a full image. Each of these directories contains 3 files: * `VERSION` - The schema version of the `json` file * `json` - The JSON metadata for an image layer * `layer.tar` - The Tar archive of the filesystem changeset for an image layer. The content of the `VERSION` files is simply the semantic version of the JSON metadata schema: ``` 1.0 ``` And the `repositories` file is another JSON file which describes names/tags: ``` { "busybox":{ "latest":"5785b62b697b99a5af6cd5d0aabc804d5748abbb6d3d07da5d1d3795f2dcc83e" } } ``` Every key in this object is the name of a repository, and maps to a collection of tag suffixes. Each tag maps to the ID of the image represented by that tag. ## Loading an Image Filesystem Changeset Unpacking a bundle of image layer JSON files and their corresponding filesystem changesets can be done using a series of steps: 1. Follow the parent IDs of image layers to find the root ancestor (an image with no parent ID specified). 2. For every image layer, in order from root ancestor and descending down, extract the contents of that layer's filesystem changeset archive into a directory which will be used as the root of a container filesystem. - Extract all contents of each archive. - Walk the directory tree once more, removing any files with the prefix `.wh.` and the corresponding file or directory named without this prefix. ## Implementations This specification is an admittedly imperfect description of an imperfectly-understood problem. The Docker project is, in turn, an attempt to implement this specification. Our goal and our execution toward it will evolve over time, but our primary concern in this specification and in our implementation is compatibility and interoperability. ================================================ FILE: vendor/github.com/docker/docker/integration-cli/check_test.go ================================================ package main import ( "testing" "github.com/go-check/check" ) func Test(t *testing.T) { check.TestingT(t) } func init() { check.Suite(&DockerSuite{}) } type DockerSuite struct { } func (s *DockerSuite) TearDownTest(c *check.C) { deleteAllContainers() deleteAllImages() } func init() { check.Suite(&DockerRegistrySuite{ ds: &DockerSuite{}, }) } type DockerRegistrySuite struct { ds *DockerSuite reg *testRegistryV2 } func (s *DockerRegistrySuite) SetUpTest(c *check.C) { s.reg = setupRegistry(c) } func (s *DockerRegistrySuite) TearDownTest(c *check.C) { s.reg.Close() s.ds.TearDownTest(c) } func init() { check.Suite(&DockerDaemonSuite{ ds: &DockerSuite{}, }) } type DockerDaemonSuite struct { ds *DockerSuite d *Daemon } func (s *DockerDaemonSuite) SetUpTest(c *check.C) { s.d = NewDaemon(c) } func (s *DockerDaemonSuite) TearDownTest(c *check.C) { s.d.Stop() s.ds.TearDownTest(c) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_attach_test.go ================================================ package main import ( "bytes" "io" "net/http" "net/http/httputil" "strings" "time" "github.com/go-check/check" "golang.org/x/net/websocket" ) func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) { out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat") rwc, err := sockConn(time.Duration(10 * time.Second)) if err != nil { c.Fatal(err) } cleanedContainerID := strings.TrimSpace(out) config, err := websocket.NewConfig( "/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1", "http://localhost", ) if err != nil { c.Fatal(err) } ws, err := websocket.NewClient(config, rwc) if err != nil { c.Fatal(err) } defer ws.Close() expected := []byte("hello") actual := make([]byte, len(expected)) outChan := make(chan error) go func() { _, err := ws.Read(actual) outChan <- err close(outChan) }() inChan := make(chan error) go func() { _, err := ws.Write(expected) inChan <- err close(inChan) }() select { case err := <-inChan: if err != nil { c.Fatal(err) } case <-time.After(5 * time.Second): c.Fatal("Timeout writing to ws") } select { case err := <-outChan: if err != nil { c.Fatal(err) } case <-time.After(5 * time.Second): c.Fatal("Timeout reading from ws") } if !bytes.Equal(expected, actual) { c.Fatal("Expected output on websocket to match input") } } // regression gh14320 func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) { status, body, err := sockRequest("POST", "/containers/doesnotexist/attach", nil) c.Assert(status, check.Equals, http.StatusNotFound) c.Assert(err, check.IsNil) expected := "no such id: doesnotexist\n" if !strings.Contains(string(body), expected) { c.Fatalf("Expected response body to contain %q", expected) } } func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) { status, body, err := sockRequest("GET", "/containers/doesnotexist/attach/ws", nil) c.Assert(status, check.Equals, http.StatusNotFound) c.Assert(err, check.IsNil) expected := "no such id: doesnotexist\n" if !strings.Contains(string(body), expected) { c.Fatalf("Expected response body to contain %q", expected) } } func (s *DockerSuite) TestPostContainersAttach(c *check.C) { out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat") r, w := io.Pipe() defer r.Close() defer w.Close() conn, err := sockConn(time.Duration(10 * time.Second)) c.Assert(err, check.IsNil) containerID := strings.TrimSpace(out) req, err := http.NewRequest("POST", "/containers/"+containerID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{})) c.Assert(err, check.IsNil) client := httputil.NewClientConn(conn, nil) defer client.Close() // Do POST attach request resp, err := client.Do(req) c.Assert(resp.StatusCode, check.Equals, http.StatusOK) // If we check the err, we get a ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"} // This means that the remote requested this be the last request serviced, is this okay? // Test read and write to the attached container expected := []byte("hello") actual := make([]byte, len(expected)) outChan := make(chan error) go func() { _, err := r.Read(actual) outChan <- err close(outChan) }() inChan := make(chan error) go func() { _, err := w.Write(expected) inChan <- err close(inChan) }() select { case err := <-inChan: c.Assert(err, check.IsNil) case <-time.After(5 * time.Second): c.Fatal("Timeout writing to stdout") } select { case err := <-outChan: c.Assert(err, check.IsNil) case <-time.After(5 * time.Second): c.Fatal("Timeout reading from stdin") } if !bytes.Equal(expected, actual) { c.Fatal("Expected output to match input") } resp.Body.Close() } func (s *DockerSuite) TestPostContainersAttachStderr(c *check.C) { out, _ := dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2") r, w := io.Pipe() defer r.Close() defer w.Close() conn, err := sockConn(time.Duration(10 * time.Second)) c.Assert(err, check.IsNil) containerID := strings.TrimSpace(out) req, err := http.NewRequest("POST", "/containers/"+containerID+"/attach?stream=1&stdin=1&stdout=1&stderr=1", bytes.NewReader([]byte{})) c.Assert(err, check.IsNil) client := httputil.NewClientConn(conn, nil) defer client.Close() // Do POST attach request resp, err := client.Do(req) c.Assert(resp.StatusCode, check.Equals, http.StatusOK) // If we check the err, we get a ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"} // This means that the remote requested this be the last request serviced, is this okay? // Test read and write to the attached container expected := []byte("hello") actual := make([]byte, len(expected)) outChan := make(chan error) go func() { _, err := r.Read(actual) outChan <- err close(outChan) }() inChan := make(chan error) go func() { _, err := w.Write(expected) inChan <- err close(inChan) }() select { case err := <-inChan: c.Assert(err, check.IsNil) case <-time.After(5 * time.Second): c.Fatal("Timeout writing to stdout") } select { case err := <-outChan: c.Assert(err, check.IsNil) case <-time.After(5 * time.Second): c.Fatal("Timeout reading from stdin") } if !bytes.Equal(expected, actual) { c.Fatal("Expected output to match input") } resp.Body.Close() } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_containers_test.go ================================================ package main import ( "archive/tar" "bytes" "encoding/json" "io" "net/http" "net/http/httputil" "os" "strconv" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/runconfig" "github.com/go-check/check" ) func (s *DockerSuite) TestContainerApiGetAll(c *check.C) { startCount, err := getContainerCount() if err != nil { c.Fatalf("Cannot query container count: %v", err) } name := "getall" dockerCmd(c, "run", "--name", name, "busybox", "true") status, body, err := sockRequest("GET", "/containers/json?all=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var inspectJSON []struct { Names []string } if err = json.Unmarshal(body, &inspectJSON); err != nil { c.Fatalf("unable to unmarshal response body: %v", err) } if len(inspectJSON) != startCount+1 { c.Fatalf("Expected %d container(s), %d found (started with: %d)", startCount+1, len(inspectJSON), startCount) } if actual := inspectJSON[0].Names[0]; actual != "/"+name { c.Fatalf("Container Name mismatch. Expected: %q, received: %q\n", "/"+name, actual) } } // regression test for empty json field being omitted #13691 func (s *DockerSuite) TestContainerApiGetJSONNoFieldsOmitted(c *check.C) { dockerCmd(c, "run", "busybox", "true") status, body, err := sockRequest("GET", "/containers/json?all=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) // empty Labels field triggered this bug, make sense to check for everything // cause even Ports for instance can trigger this bug // better safe than sorry.. fields := []string{ "Id", "Names", "Image", "Command", "Created", "Ports", "Labels", "Status", } // decoding into types.Container do not work since it eventually unmarshal // and empty field to an empty go map, so we just check for a string for _, f := range fields { if !strings.Contains(string(body), f) { c.Fatalf("Field %s is missing and it shouldn't", f) } } } type containerPs struct { Names []string Ports []map[string]interface{} } // regression test for non-empty fields from #13901 func (s *DockerSuite) TestContainerPsOmitFields(c *check.C) { name := "pstest" port := 80 dockerCmd(c, "run", "-d", "--name", name, "--expose", strconv.Itoa(port), "busybox", "top") status, body, err := sockRequest("GET", "/containers/json?all=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var resp []containerPs err = json.Unmarshal(body, &resp) c.Assert(err, check.IsNil) var foundContainer *containerPs for _, container := range resp { for _, testName := range container.Names { if "/"+name == testName { foundContainer = &container break } } } c.Assert(len(foundContainer.Ports), check.Equals, 1) c.Assert(foundContainer.Ports[0]["PrivatePort"], check.Equals, float64(port)) _, ok := foundContainer.Ports[0]["PublicPort"] c.Assert(ok, check.Not(check.Equals), true) _, ok = foundContainer.Ports[0]["IP"] c.Assert(ok, check.Not(check.Equals), true) } func (s *DockerSuite) TestContainerApiGetExport(c *check.C) { name := "exportcontainer" dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test") status, body, err := sockRequest("GET", "/containers/"+name+"/export", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) found := false for tarReader := tar.NewReader(bytes.NewReader(body)); ; { h, err := tarReader.Next() if err != nil { if err == io.EOF { break } c.Fatal(err) } if h.Name == "test" { found = true break } } if !found { c.Fatalf("The created test file has not been found in the exported image") } } func (s *DockerSuite) TestContainerApiGetChanges(c *check.C) { name := "changescontainer" dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd") status, body, err := sockRequest("GET", "/containers/"+name+"/changes", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) changes := []struct { Kind int Path string }{} if err = json.Unmarshal(body, &changes); err != nil { c.Fatalf("unable to unmarshal response body: %v", err) } // Check the changelog for removal of /etc/passwd success := false for _, elem := range changes { if elem.Path == "/etc/passwd" && elem.Kind == 2 { success = true } } if !success { c.Fatalf("/etc/passwd has been removed but is not present in the diff") } } func (s *DockerSuite) TestContainerApiStartVolumeBinds(c *check.C) { name := "testing" config := map[string]interface{}{ "Image": "busybox", "Volumes": map[string]struct{}{"/tmp": {}}, } status, _, err := sockRequest("POST", "/containers/create?name="+name, config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) bindPath := randomUnixTmpDirPath("test") config = map[string]interface{}{ "Binds": []string{bindPath + ":/tmp"}, } status, _, err = sockRequest("POST", "/containers/"+name+"/start", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) pth, err := inspectMountSourceField(name, "/tmp") if err != nil { c.Fatal(err) } if pth != bindPath { c.Fatalf("expected volume host path to be %s, got %s", bindPath, pth) } } // Test for GH#10618 func (s *DockerSuite) TestContainerApiStartDupVolumeBinds(c *check.C) { name := "testdups" config := map[string]interface{}{ "Image": "busybox", "Volumes": map[string]struct{}{"/tmp": {}}, } status, _, err := sockRequest("POST", "/containers/create?name="+name, config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) bindPath1 := randomUnixTmpDirPath("test1") bindPath2 := randomUnixTmpDirPath("test2") config = map[string]interface{}{ "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"}, } status, body, err := sockRequest("POST", "/containers/"+name+"/start", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusInternalServerError) if !strings.Contains(string(body), "Duplicate bind") { c.Fatalf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(body), err) } } func (s *DockerSuite) TestContainerApiStartVolumesFrom(c *check.C) { volName := "voltst" volPath := "/tmp" dockerCmd(c, "run", "-d", "--name", volName, "-v", volPath, "busybox") name := "TestContainerApiStartVolumesFrom" config := map[string]interface{}{ "Image": "busybox", "Volumes": map[string]struct{}{volPath: {}}, } status, _, err := sockRequest("POST", "/containers/create?name="+name, config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) config = map[string]interface{}{ "VolumesFrom": []string{volName}, } status, _, err = sockRequest("POST", "/containers/"+name+"/start", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) pth, err := inspectMountSourceField(name, volPath) if err != nil { c.Fatal(err) } pth2, err := inspectMountSourceField(volName, volPath) if err != nil { c.Fatal(err) } if pth != pth2 { c.Fatalf("expected volume host path to be %s, got %s", pth, pth2) } } func (s *DockerSuite) TestGetContainerStats(c *check.C) { var ( name = "statscontainer" ) dockerCmd(c, "run", "-d", "--name", name, "busybox", "top") type b struct { status int body []byte err error } bc := make(chan b, 1) go func() { status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil) bc <- b{status, body, err} }() // allow some time to stream the stats from the container time.Sleep(4 * time.Second) dockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. select { case <-time.After(2 * time.Second): c.Fatal("stream was not closed after container was removed") case sr := <-bc: c.Assert(sr.err, check.IsNil) c.Assert(sr.status, check.Equals, http.StatusOK) dec := json.NewDecoder(bytes.NewBuffer(sr.body)) var s *types.Stats // decode only one object from the stream if err := dec.Decode(&s); err != nil { c.Fatal(err) } } } func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) buf := &channelBuffer{make(chan []byte, 1)} defer buf.Close() chErr := make(chan error) go func() { _, body, err := sockRequestRaw("GET", "/containers/"+id+"/stats?stream=1", nil, "application/json") if err != nil { chErr <- err } defer body.Close() _, err = io.Copy(buf, body) chErr <- err }() defer func() { c.Assert(<-chErr, check.IsNil) }() b := make([]byte, 32) // make sure we've got some stats _, err := buf.ReadTimeout(b, 2*time.Second) c.Assert(err, check.IsNil) // Now remove without `-f` and make sure we are still pulling stats _, _, err = dockerCmdWithError(c, "rm", id) c.Assert(err, check.Not(check.IsNil), check.Commentf("rm should have failed but didn't")) _, err = buf.ReadTimeout(b, 2*time.Second) c.Assert(err, check.IsNil) dockerCmd(c, "rm", "-f", id) _, err = buf.ReadTimeout(b, 2*time.Second) c.Assert(err, check.Not(check.IsNil)) } // regression test for gh13421 // previous test was just checking one stat entry so it didn't fail (stats with // stream false always return one stat) func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) { name := "statscontainer" dockerCmd(c, "run", "-d", "--name", name, "busybox", "top") type b struct { status int body []byte err error } bc := make(chan b, 1) go func() { status, body, err := sockRequest("GET", "/containers/"+name+"/stats", nil) bc <- b{status, body, err} }() // allow some time to stream the stats from the container time.Sleep(4 * time.Second) dockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. select { case <-time.After(2 * time.Second): c.Fatal("stream was not closed after container was removed") case sr := <-bc: c.Assert(sr.err, check.IsNil) c.Assert(sr.status, check.Equals, http.StatusOK) s := string(sr.body) // count occurrences of "read" of types.Stats if l := strings.Count(s, "read"); l < 2 { c.Fatalf("Expected more than one stat streamed, got %d", l) } } } func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) { name := "statscontainer" dockerCmd(c, "run", "-d", "--name", name, "busybox", "top") type b struct { status int body []byte err error } bc := make(chan b, 1) go func() { status, body, err := sockRequest("GET", "/containers/"+name+"/stats?stream=0", nil) bc <- b{status, body, err} }() // allow some time to stream the stats from the container time.Sleep(4 * time.Second) dockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. select { case <-time.After(2 * time.Second): c.Fatal("stream was not closed after container was removed") case sr := <-bc: c.Assert(sr.err, check.IsNil) c.Assert(sr.status, check.Equals, http.StatusOK) s := string(sr.body) // count occurrences of "read" of types.Stats if l := strings.Count(s, "read"); l != 1 { c.Fatalf("Expected only one stat streamed, got %d", l) } } } func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) { // TODO: this test does nothing because we are c.Assert'ing in goroutine var ( name = "statscontainer" ) dockerCmd(c, "create", "--name", name, "busybox", "top") go func() { // We'll never get return for GET stats from sockRequest as of now, // just send request and see if panic or error would happen on daemon side. status, _, err := sockRequest("GET", "/containers/"+name+"/stats", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) }() // allow some time to send request and let daemon deal with it time.Sleep(1 * time.Second) } func (s *DockerSuite) TestBuildApiDockerfilePath(c *check.C) { // Test to make sure we stop people from trying to leave the // build context when specifying the path to the dockerfile buffer := new(bytes.Buffer) tw := tar.NewWriter(buffer) defer tw.Close() dockerfile := []byte("FROM busybox") if err := tw.WriteHeader(&tar.Header{ Name: "Dockerfile", Size: int64(len(dockerfile)), }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write(dockerfile); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } res, body, err := sockRequestRaw("POST", "/build?dockerfile=../Dockerfile", buffer, "application/x-tar") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) out, err := readBody(body) if err != nil { c.Fatal(err) } if !strings.Contains(string(out), "must be within the build context") { c.Fatalf("Didn't complain about leaving build context: %s", out) } } func (s *DockerSuite) TestBuildApiDockerFileRemote(c *check.C) { server, err := fakeStorage(map[string]string{ "testD": `FROM busybox COPY * /tmp/ RUN find / -name ba* RUN find /tmp/`, }) if err != nil { c.Fatal(err) } defer server.Close() res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+server.URL()+"/testD", nil, "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) buf, err := readBody(body) if err != nil { c.Fatal(err) } // Make sure Dockerfile exists. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL out := string(buf) if !strings.Contains(out, "/tmp/Dockerfile") || strings.Contains(out, "baz") { c.Fatalf("Incorrect output: %s", out) } } func (s *DockerSuite) TestBuildApiRemoteTarballContext(c *check.C) { buffer := new(bytes.Buffer) tw := tar.NewWriter(buffer) defer tw.Close() dockerfile := []byte("FROM busybox") if err := tw.WriteHeader(&tar.Header{ Name: "Dockerfile", Size: int64(len(dockerfile)), }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write(dockerfile); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } server, err := fakeBinaryStorage(map[string]*bytes.Buffer{ "testT.tar": buffer, }) c.Assert(err, check.IsNil) defer server.Close() res, _, err := sockRequestRaw("POST", "/build?remote="+server.URL()+"/testT.tar", nil, "application/tar") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) } func (s *DockerSuite) TestBuildApiRemoteTarballContextWithCustomDockerfile(c *check.C) { buffer := new(bytes.Buffer) tw := tar.NewWriter(buffer) defer tw.Close() dockerfile := []byte(`FROM busybox RUN echo 'wrong'`) if err := tw.WriteHeader(&tar.Header{ Name: "Dockerfile", Size: int64(len(dockerfile)), }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write(dockerfile); err != nil { c.Fatalf("failed to write tar file content: %v", err) } custom := []byte(`FROM busybox RUN echo 'right' `) if err := tw.WriteHeader(&tar.Header{ Name: "custom", Size: int64(len(custom)), }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write(custom); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } server, err := fakeBinaryStorage(map[string]*bytes.Buffer{ "testT.tar": buffer, }) c.Assert(err, check.IsNil) defer server.Close() url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar" res, body, err := sockRequestRaw("POST", url, nil, "application/tar") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) defer body.Close() content, err := readBody(body) c.Assert(err, check.IsNil) if strings.Contains(string(content), "wrong") { c.Fatalf("Build used the wrong dockerfile.") } } func (s *DockerSuite) TestBuildApiLowerDockerfile(c *check.C) { git, err := fakeGIT("repo", map[string]string{ "dockerfile": `FROM busybox RUN echo from dockerfile`, }, false) if err != nil { c.Fatal(err) } defer git.Close() res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) buf, err := readBody(body) if err != nil { c.Fatal(err) } out := string(buf) if !strings.Contains(out, "from dockerfile") { c.Fatalf("Incorrect output: %s", out) } } func (s *DockerSuite) TestBuildApiBuildGitWithF(c *check.C) { git, err := fakeGIT("repo", map[string]string{ "baz": `FROM busybox RUN echo from baz`, "Dockerfile": `FROM busybox RUN echo from Dockerfile`, }, false) if err != nil { c.Fatal(err) } defer git.Close() // Make sure it tries to 'dockerfile' query param value res, body, err := sockRequestRaw("POST", "/build?dockerfile=baz&remote="+git.RepoURL, nil, "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) buf, err := readBody(body) if err != nil { c.Fatal(err) } out := string(buf) if !strings.Contains(out, "from baz") { c.Fatalf("Incorrect output: %s", out) } } func (s *DockerSuite) TestBuildApiDoubleDockerfile(c *check.C) { testRequires(c, UnixCli) // dockerfile overwrites Dockerfile on Windows git, err := fakeGIT("repo", map[string]string{ "Dockerfile": `FROM busybox RUN echo from Dockerfile`, "dockerfile": `FROM busybox RUN echo from dockerfile`, }, false) if err != nil { c.Fatal(err) } defer git.Close() // Make sure it tries to 'dockerfile' query param value res, body, err := sockRequestRaw("POST", "/build?remote="+git.RepoURL, nil, "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) buf, err := readBody(body) if err != nil { c.Fatal(err) } out := string(buf) if !strings.Contains(out, "from Dockerfile") { c.Fatalf("Incorrect output: %s", out) } } func (s *DockerSuite) TestBuildApiDockerfileSymlink(c *check.C) { // Test to make sure we stop people from trying to leave the // build context when specifying a symlink as the path to the dockerfile buffer := new(bytes.Buffer) tw := tar.NewWriter(buffer) defer tw.Close() if err := tw.WriteHeader(&tar.Header{ Name: "Dockerfile", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd", }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } res, body, err := sockRequestRaw("POST", "/build", buffer, "application/x-tar") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) out, err := readBody(body) if err != nil { c.Fatal(err) } // The reason the error is "Cannot locate specified Dockerfile" is because // in the builder, the symlink is resolved within the context, therefore // Dockerfile -> /etc/passwd becomes etc/passwd from the context which is // a nonexistent file. if !strings.Contains(string(out), "Cannot locate specified Dockerfile: Dockerfile") { c.Fatalf("Didn't complain about leaving build context: %s", out) } } // #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume func (s *DockerSuite) TestPostContainerBindNormalVolume(c *check.C) { dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox") fooDir, err := inspectMountSourceField("one", "/foo") if err != nil { c.Fatal(err) } dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox") bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}} status, _, err := sockRequest("POST", "/containers/two/start", bindSpec) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) fooDir2, err := inspectMountSourceField("two", "/foo") if err != nil { c.Fatal(err) } if fooDir2 != fooDir { c.Fatalf("expected volume path to be %s, got: %s", fooDir, fooDir2) } } func (s *DockerSuite) TestContainerApiPause(c *check.C) { defer unpauseAllContainers() out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "30") ContainerID := strings.TrimSpace(out) status, _, err := sockRequest("POST", "/containers/"+ContainerID+"/pause", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) pausedContainers, err := getSliceOfPausedContainers() if err != nil { c.Fatalf("error thrown while checking if containers were paused: %v", err) } if len(pausedContainers) != 1 || stringid.TruncateID(ContainerID) != pausedContainers[0] { c.Fatalf("there should be one paused container and not %d", len(pausedContainers)) } status, _, err = sockRequest("POST", "/containers/"+ContainerID+"/unpause", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) pausedContainers, err = getSliceOfPausedContainers() if err != nil { c.Fatalf("error thrown while checking if containers were paused: %v", err) } if pausedContainers != nil { c.Fatalf("There should be no paused container.") } } func (s *DockerSuite) TestContainerApiTop(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top") id := strings.TrimSpace(string(out)) if err := waitRun(id); err != nil { c.Fatal(err) } type topResp struct { Titles []string Processes [][]string } var top topResp status, b, err := sockRequest("GET", "/containers/"+id+"/top?ps_args=aux", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) if err := json.Unmarshal(b, &top); err != nil { c.Fatal(err) } if len(top.Titles) != 11 { c.Fatalf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles) } if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" { c.Fatalf("expected `USER` at `Titles[0]` and `COMMAND` at Titles[10]: %v", top.Titles) } if len(top.Processes) != 2 { c.Fatalf("expected 2 processes, found %d: %v", len(top.Processes), top.Processes) } if top.Processes[0][10] != "/bin/sh -c top" { c.Fatalf("expected `/bin/sh -c top`, found: %s", top.Processes[0][10]) } if top.Processes[1][10] != "top" { c.Fatalf("expected `top`, found: %s", top.Processes[1][10]) } } func (s *DockerSuite) TestContainerApiCommit(c *check.C) { cName := "testapicommit" dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") name := "TestContainerApiCommit" status, b, err := sockRequest("POST", "/commit?repo="+name+"&testtag=tag&container="+cName, nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) type resp struct { Id string } var img resp if err := json.Unmarshal(b, &img); err != nil { c.Fatal(err) } cmd, err := inspectField(img.Id, "Config.Cmd") if err != nil { c.Fatal(err) } if cmd != "{[/bin/sh -c touch /test]}" { c.Fatalf("got wrong Cmd from commit: %q", cmd) } // sanity check, make sure the image is what we think it is dockerCmd(c, "run", img.Id, "ls", "/test") } func (s *DockerSuite) TestContainerApiCommitWithLabelInConfig(c *check.C) { cName := "testapicommitwithconfig" dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") config := map[string]interface{}{ "Labels": map[string]string{"key1": "value1", "key2": "value2"}, } name := "TestContainerApiCommitWithConfig" status, b, err := sockRequest("POST", "/commit?repo="+name+"&container="+cName, config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) type resp struct { Id string } var img resp if err := json.Unmarshal(b, &img); err != nil { c.Fatal(err) } label1, err := inspectFieldMap(img.Id, "Config.Labels", "key1") if err != nil { c.Fatal(err) } c.Assert(label1, check.Equals, "value1") label2, err := inspectFieldMap(img.Id, "Config.Labels", "key2") if err != nil { c.Fatal(err) } c.Assert(label2, check.Equals, "value2") cmd, err := inspectField(img.Id, "Config.Cmd") if err != nil { c.Fatal(err) } if cmd != "{[/bin/sh -c touch /test]}" { c.Fatalf("got wrong Cmd from commit: %q", cmd) } // sanity check, make sure the image is what we think it is dockerCmd(c, "run", img.Id, "ls", "/test") } func (s *DockerSuite) TestContainerApiBadPort(c *check.C) { config := map[string]interface{}{ "Image": "busybox", "Cmd": []string{"/bin/sh", "-c", "echo test"}, "PortBindings": map[string]interface{}{ "8080/tcp": []map[string]interface{}{ { "HostIP": "", "HostPort": "aa80", }, }, }, } jsonData := bytes.NewBuffer(nil) json.NewEncoder(jsonData).Encode(config) status, b, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusInternalServerError) if strings.TrimSpace(string(b)) != `Invalid port specification: "aa80"` { c.Fatalf("Incorrect error msg: %s", string(b)) } } func (s *DockerSuite) TestContainerApiCreate(c *check.C) { config := map[string]interface{}{ "Image": "busybox", "Cmd": []string{"/bin/sh", "-c", "touch /test && ls /test"}, } status, b, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) type createResp struct { Id string } var container createResp if err := json.Unmarshal(b, &container); err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "start", "-a", container.Id) if strings.TrimSpace(out) != "/test" { c.Fatalf("expected output `/test`, got %q", out) } } func (s *DockerSuite) TestContainerApiCreateEmptyConfig(c *check.C) { config := map[string]interface{}{} status, b, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusInternalServerError) expected := "Config cannot be empty in order to create a container\n" if body := string(b); body != expected { c.Fatalf("Expected to get %q, got %q", expected, body) } } func (s *DockerSuite) TestContainerApiCreateWithHostName(c *check.C) { hostName := "test-host" config := map[string]interface{}{ "Image": "busybox", "Hostname": hostName, } status, body, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) var container types.ContainerCreateResponse if err := json.Unmarshal(body, &container); err != nil { c.Fatal(err) } status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var containerJSON types.ContainerJSON if err := json.Unmarshal(body, &containerJSON); err != nil { c.Fatal(err) } if containerJSON.Config.Hostname != hostName { c.Fatalf("Mismatched Hostname, Expected %s, Actual: %s ", hostName, containerJSON.Config.Hostname) } } func (s *DockerSuite) TestContainerApiCreateWithDomainName(c *check.C) { domainName := "test-domain" config := map[string]interface{}{ "Image": "busybox", "Domainname": domainName, } status, body, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) var container types.ContainerCreateResponse if err := json.Unmarshal(body, &container); err != nil { c.Fatal(err) } status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var containerJSON types.ContainerJSON if err := json.Unmarshal(body, &containerJSON); err != nil { c.Fatal(err) } if containerJSON.Config.Domainname != domainName { c.Fatalf("Mismatched Domainname, Expected %s, Actual: %s ", domainName, containerJSON.Config.Domainname) } } func (s *DockerSuite) TestContainerApiCreateNetworkMode(c *check.C) { UtilCreateNetworkMode(c, "host") UtilCreateNetworkMode(c, "bridge") UtilCreateNetworkMode(c, "container:web1") } func UtilCreateNetworkMode(c *check.C, networkMode string) { config := map[string]interface{}{ "Image": "busybox", "HostConfig": map[string]interface{}{"NetworkMode": networkMode}, } status, body, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) var container types.ContainerCreateResponse if err := json.Unmarshal(body, &container); err != nil { c.Fatal(err) } status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var containerJSON types.ContainerJSON if err := json.Unmarshal(body, &containerJSON); err != nil { c.Fatal(err) } if containerJSON.HostConfig.NetworkMode != runconfig.NetworkMode(networkMode) { c.Fatalf("Mismatched NetworkMode, Expected %s, Actual: %s ", networkMode, containerJSON.HostConfig.NetworkMode) } } func (s *DockerSuite) TestContainerApiCreateWithCpuSharesCpuset(c *check.C) { config := map[string]interface{}{ "Image": "busybox", "CpuShares": 512, "CpusetCpus": "0,1", } status, body, err := sockRequest("POST", "/containers/create", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) var container types.ContainerCreateResponse if err := json.Unmarshal(body, &container); err != nil { c.Fatal(err) } status, body, err = sockRequest("GET", "/containers/"+container.ID+"/json", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var containerJson types.ContainerJSON c.Assert(json.Unmarshal(body, &containerJson), check.IsNil) out, err := inspectField(containerJson.Id, "HostConfig.CpuShares") c.Assert(err, check.IsNil) c.Assert(out, check.Equals, "512") outCpuset, errCpuset := inspectField(containerJson.Id, "HostConfig.CpusetCpus") c.Assert(errCpuset, check.IsNil, check.Commentf("Output: %s", outCpuset)) c.Assert(outCpuset, check.Equals, "0,1") } func (s *DockerSuite) TestContainerApiVerifyHeader(c *check.C) { config := map[string]interface{}{ "Image": "busybox", } create := func(ct string) (*http.Response, io.ReadCloser, error) { jsonData := bytes.NewBuffer(nil) if err := json.NewEncoder(jsonData).Encode(config); err != nil { c.Fatal(err) } return sockRequestRaw("POST", "/containers/create", jsonData, ct) } // Try with no content-type res, body, err := create("") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) body.Close() // Try with wrong content-type res, body, err = create("application/xml") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) body.Close() // now application/json res, body, err = create("application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusCreated) body.Close() } //Issue 14230. daemon should return 500 for invalid port syntax func (s *DockerSuite) TestContainerApiInvalidPortSyntax(c *check.C) { config := `{ "Image": "busybox", "HostConfig": { "PortBindings": { "19039;1230": [ {} ] } } }` res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) b, err := readBody(body) if err != nil { c.Fatal(err) } c.Assert(strings.Contains(string(b[:]), "Invalid port"), check.Equals, true) } // Issue 7941 - test to make sure a "null" in JSON is just ignored. // W/o this fix a null in JSON would be parsed into a string var as "null" func (s *DockerSuite) TestContainerApiPostCreateNull(c *check.C) { config := `{ "Hostname":"", "Domainname":"", "Memory":0, "MemorySwap":0, "CpuShares":0, "Cpuset":null, "AttachStdin":true, "AttachStdout":true, "AttachStderr":true, "ExposedPorts":{}, "Tty":true, "OpenStdin":true, "StdinOnce":true, "Env":[], "Cmd":"ls", "Image":"busybox", "Volumes":{}, "WorkingDir":"", "Entrypoint":null, "NetworkDisabled":false, "OnBuild":null}` res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusCreated) b, err := readBody(body) if err != nil { c.Fatal(err) } type createResp struct { Id string } var container createResp if err := json.Unmarshal(b, &container); err != nil { c.Fatal(err) } out, err := inspectField(container.Id, "HostConfig.CpusetCpus") if err != nil { c.Fatal(err, out) } if out != "" { c.Fatalf("expected empty string, got %q", out) } outMemory, errMemory := inspectField(container.Id, "HostConfig.Memory") c.Assert(outMemory, check.Equals, "0") if errMemory != nil { c.Fatal(errMemory, outMemory) } outMemorySwap, errMemorySwap := inspectField(container.Id, "HostConfig.MemorySwap") c.Assert(outMemorySwap, check.Equals, "0") if errMemorySwap != nil { c.Fatal(errMemorySwap, outMemorySwap) } } func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) { config := `{ "Image": "busybox", "Cmd": "ls", "OpenStdin": true, "CpuShares": 100, "Memory": 524287 }` res, body, err := sockRequestRaw("POST", "/containers/create", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) b, err2 := readBody(body) if err2 != nil { c.Fatal(err2) } c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true) } func (s *DockerSuite) TestStartWithTooLowMemoryLimit(c *check.C) { out, _ := dockerCmd(c, "create", "busybox") containerID := strings.TrimSpace(out) config := `{ "CpuShares": 100, "Memory": 524287 }` res, body, err := sockRequestRaw("POST", "/containers/"+containerID+"/start", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) b, err2 := readBody(body) if err2 != nil { c.Fatal(err2) } c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) c.Assert(strings.Contains(string(b), "Minimum memory limit allowed is 4MB"), check.Equals, true) } func (s *DockerSuite) TestContainerApiRename(c *check.C) { out, _ := dockerCmd(c, "run", "--name", "TestContainerApiRename", "-d", "busybox", "sh") containerID := strings.TrimSpace(out) newName := "TestContainerApiRenameNew" statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/rename?name="+newName, nil) c.Assert(err, check.IsNil) // 204 No Content is expected, not 200 c.Assert(statusCode, check.Equals, http.StatusNoContent) name, err := inspectField(containerID, "Name") if name != "/"+newName { c.Fatalf("Failed to rename container, expected %v, got %v. Container rename API failed", newName, name) } } func (s *DockerSuite) TestContainerApiKill(c *check.C) { name := "test-api-kill" dockerCmd(c, "run", "-di", "--name", name, "busybox", "top") status, _, err := sockRequest("POST", "/containers/"+name+"/kill", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) state, err := inspectField(name, "State.Running") if err != nil { c.Fatal(err) } if state != "false" { c.Fatalf("got wrong State from container %s: %q", name, state) } } func (s *DockerSuite) TestContainerApiRestart(c *check.C) { name := "test-api-restart" dockerCmd(c, "run", "-di", "--name", name, "busybox", "top") status, _, err := sockRequest("POST", "/containers/"+name+"/restart?t=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestContainerApiRestartNotimeoutParam(c *check.C) { name := "test-api-restart-no-timeout-param" out, _ := dockerCmd(c, "run", "-di", "--name", name, "busybox", "top") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) status, _, err := sockRequest("POST", "/containers/"+name+"/restart", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) if err := waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 5); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestContainerApiStart(c *check.C) { name := "testing-start" config := map[string]interface{}{ "Image": "busybox", "Cmd": []string{"/bin/sh", "-c", "/bin/top"}, "OpenStdin": true, } status, _, err := sockRequest("POST", "/containers/create?name="+name, config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) conf := make(map[string]interface{}) status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) // second call to start should give 304 status, _, err = sockRequest("POST", "/containers/"+name+"/start", conf) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNotModified) } func (s *DockerSuite) TestContainerApiStop(c *check.C) { name := "test-api-stop" dockerCmd(c, "run", "-di", "--name", name, "busybox", "top") status, _, err := sockRequest("POST", "/containers/"+name+"/stop?t=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil { c.Fatal(err) } // second call to start should give 304 status, _, err = sockRequest("POST", "/containers/"+name+"/stop?t=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNotModified) } func (s *DockerSuite) TestContainerApiWait(c *check.C) { name := "test-api-wait" dockerCmd(c, "run", "--name", name, "busybox", "sleep", "5") status, body, err := sockRequest("POST", "/containers/"+name+"/wait", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) if err := waitInspect(name, "{{ .State.Running }}", "false", 5); err != nil { c.Fatal(err) } var waitres types.ContainerWaitResponse if err := json.Unmarshal(body, &waitres); err != nil { c.Fatalf("unable to unmarshal response body: %v", err) } if waitres.StatusCode != 0 { c.Fatalf("Expected wait response StatusCode to be 0, got %d", waitres.StatusCode) } } func (s *DockerSuite) TestContainerApiCopy(c *check.C) { name := "test-container-api-copy" dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") postData := types.CopyConfig{ Resource: "/test.txt", } status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) found := false for tarReader := tar.NewReader(bytes.NewReader(body)); ; { h, err := tarReader.Next() if err != nil { if err == io.EOF { break } c.Fatal(err) } if h.Name == "test.txt" { found = true break } } c.Assert(found, check.Equals, true) } func (s *DockerSuite) TestContainerApiCopyResourcePathEmpty(c *check.C) { name := "test-container-api-copy-resource-empty" dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") postData := types.CopyConfig{ Resource: "", } status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusInternalServerError) c.Assert(string(body), check.Matches, "Path cannot be empty\n") } func (s *DockerSuite) TestContainerApiCopyResourcePathNotFound(c *check.C) { name := "test-container-api-copy-resource-not-found" dockerCmd(c, "run", "--name", name, "busybox") postData := types.CopyConfig{ Resource: "/notexist", } status, body, err := sockRequest("POST", "/containers/"+name+"/copy", postData) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusInternalServerError) c.Assert(string(body), check.Matches, "Could not find the file /notexist in container "+name+"\n") } func (s *DockerSuite) TestContainerApiCopyContainerNotFound(c *check.C) { postData := types.CopyConfig{ Resource: "/something", } status, _, err := sockRequest("POST", "/containers/notexists/copy", postData) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNotFound) } func (s *DockerSuite) TestContainerApiDelete(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) dockerCmd(c, "stop", id) status, _, err := sockRequest("DELETE", "/containers/"+id, nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) } func (s *DockerSuite) TestContainerApiDeleteNotExist(c *check.C) { status, body, err := sockRequest("DELETE", "/containers/doesnotexist", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNotFound) c.Assert(string(body), check.Matches, "no such id: doesnotexist\n") } func (s *DockerSuite) TestContainerApiDeleteForce(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) status, _, err := sockRequest("DELETE", "/containers/"+id+"?force=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) } func (s *DockerSuite) TestContainerApiDeleteRemoveLinks(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top") id2 := strings.TrimSpace(out) c.Assert(waitRun(id2), check.IsNil) links, err := inspectFieldJSON(id2, "HostConfig.Links") c.Assert(err, check.IsNil) if links != "[\"/tlink1:/tlink2/tlink1\"]" { c.Fatal("expected to have links between containers") } status, _, err := sockRequest("DELETE", "/containers/tlink2/tlink1?link=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) linksPostRm, err := inspectFieldJSON(id2, "HostConfig.Links") c.Assert(err, check.IsNil) if linksPostRm != "null" { c.Fatal("call to api deleteContainer links should have removed the specified links") } } func (s *DockerSuite) TestContainerApiDeleteConflict(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) status, _, err := sockRequest("DELETE", "/containers/"+id, nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusConflict) } func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "-d", "-v", "/testvolume", "busybox", "top") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) source, err := inspectMountSourceField(id, "/testvolume") _, err = os.Stat(source) c.Assert(err, check.IsNil) status, _, err := sockRequest("DELETE", "/containers/"+id+"?v=1&force=1", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusNoContent) if _, err := os.Stat(source); !os.IsNotExist(err) { c.Fatalf("expected to get ErrNotExist error, got %v", err) } } // Regression test for https://github.com/docker/docker/issues/6231 func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) { out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true") id := strings.TrimSpace(out) conn, err := sockConn(time.Duration(10 * time.Second)) if err != nil { c.Fatal(err) } client := httputil.NewClientConn(conn, nil) defer client.Close() bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`) req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg) if err != nil { c.Fatal(err) } req.Header.Set("Content-Type", "application/json") // This is a cheat to make the http request do chunked encoding // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite // https://golang.org/src/pkg/net/http/request.go?s=11980:12172 req.ContentLength = -1 resp, err := client.Do(req) if err != nil { c.Fatalf("error starting container with chunked encoding: %v", err) } resp.Body.Close() if resp.StatusCode != 204 { c.Fatalf("expected status code 204, got %d", resp.StatusCode) } out, err = inspectFieldJSON(id, "HostConfig.Binds") if err != nil { c.Fatal(err) } var binds []string if err := json.NewDecoder(strings.NewReader(out)).Decode(&binds); err != nil { c.Fatal(err) } if len(binds) != 1 { c.Fatalf("got unexpected binds: %v", binds) } expected := "/tmp:/foo" if binds[0] != expected { c.Fatalf("got incorrect bind spec, wanted %s, got: %s", expected, binds[0]) } } func (s *DockerSuite) TestPostContainerStop(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") containerID := strings.TrimSpace(out) c.Assert(waitRun(containerID), check.IsNil) statusCode, _, err := sockRequest("POST", "/containers/"+containerID+"/stop", nil) c.Assert(err, check.IsNil) // 204 No Content is expected, not 200 c.Assert(statusCode, check.Equals, http.StatusNoContent) if err := waitInspect(containerID, "{{ .State.Running }}", "false", 5); err != nil { c.Fatal(err) } } // #14170 func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceEntrypoint(c *check.C) { config := struct { Image string Entrypoint string Cmd []string }{"busybox", "echo", []string{"hello", "world"}} _, _, err := sockRequest("POST", "/containers/create?name=echotest", config) c.Assert(err, check.IsNil) out, _ := dockerCmd(c, "start", "-a", "echotest") c.Assert(strings.TrimSpace(out), check.Equals, "hello world") config2 := struct { Image string Entrypoint []string Cmd []string }{"busybox", []string{"echo"}, []string{"hello", "world"}} _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2) c.Assert(err, check.IsNil) out, _ = dockerCmd(c, "start", "-a", "echotest2") c.Assert(strings.TrimSpace(out), check.Equals, "hello world") } // #14170 func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) { config := struct { Image string Entrypoint string Cmd string }{"busybox", "echo", "hello world"} _, _, err := sockRequest("POST", "/containers/create?name=echotest", config) c.Assert(err, check.IsNil) out, _ := dockerCmd(c, "start", "-a", "echotest") c.Assert(strings.TrimSpace(out), check.Equals, "hello world") config2 := struct { Image string Cmd []string }{"busybox", []string{"echo", "hello", "world"}} _, _, err = sockRequest("POST", "/containers/create?name=echotest2", config2) c.Assert(err, check.IsNil) out, _ = dockerCmd(c, "start", "-a", "echotest2") c.Assert(strings.TrimSpace(out), check.Equals, "hello world") } // regression #14318 func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *check.C) { config := struct { Image string CapAdd string CapDrop string }{"busybox", "NET_ADMIN", "SYS_ADMIN"} status, _, err := sockRequest("POST", "/containers/create?name=capaddtest0", config) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) config2 := struct { Image string CapAdd []string CapDrop []string }{"busybox", []string{"NET_ADMIN", "SYS_ADMIN"}, []string{"SETGID"}} status, _, err = sockRequest("POST", "/containers/create?name=capaddtest1", config2) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusCreated) } // #14640 func (s *DockerSuite) TestPostContainersStartWithoutLinksInHostConfig(c *check.C) { name := "test-host-config-links" dockerCmd(c, "create", "--name", name, "busybox", "top") hc, err := inspectFieldJSON(name, "HostConfig") c.Assert(err, check.IsNil) config := `{"HostConfig":` + hc + `}` res, _, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusNoContent) } // #14640 func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfig(c *check.C) { name := "test-host-config-links" dockerCmd(c, "run", "--name", "foo", "-d", "busybox", "top") dockerCmd(c, "create", "--name", name, "--link", "foo:bar", "busybox", "top") hc, err := inspectFieldJSON(name, "HostConfig") c.Assert(err, check.IsNil) config := `{"HostConfig":` + hc + `}` res, _, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusNoContent) } // #14640 func (s *DockerSuite) TestPostContainersStartWithLinksInHostConfigIdLinked(c *check.C) { name := "test-host-config-links" out, _ := dockerCmd(c, "run", "--name", "link0", "-d", "busybox", "top") id := strings.TrimSpace(out) dockerCmd(c, "create", "--name", name, "--link", id, "busybox", "top") hc, err := inspectFieldJSON(name, "HostConfig") c.Assert(err, check.IsNil) config := `{"HostConfig":` + hc + `}` res, _, err := sockRequestRaw("POST", "/containers/"+name+"/start", strings.NewReader(config), "application/json") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusNoContent) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_events_test.go ================================================ package main import ( "net/http" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestEventsApiEmptyOutput(c *check.C) { type apiResp struct { resp *http.Response err error } chResp := make(chan *apiResp) go func() { resp, body, err := sockRequestRaw("GET", "/events", nil, "") body.Close() chResp <- &apiResp{resp, err} }() select { case r := <-chResp: c.Assert(r.err, check.IsNil) c.Assert(r.resp.StatusCode, check.Equals, http.StatusOK) case <-time.After(3 * time.Second): c.Fatal("timeout waiting for events api to respond, should have responded immediately") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_exec_resize_test.go ================================================ package main import ( "net/http" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestExecResizeApiHeightWidthNoInt(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) endpoint := "/exec/" + cleanedContainerID + "/resize?h=foo&w=bar" status, _, err := sockRequest("POST", endpoint, nil) c.Assert(status, check.Equals, http.StatusInternalServerError) c.Assert(err, check.IsNil) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_exec_test.go ================================================ // +build !test_no_exec package main import ( "bytes" "encoding/json" "fmt" "net/http" "github.com/go-check/check" ) // Regression test for #9414 func (s *DockerSuite) TestExecApiCreateNoCmd(c *check.C) { name := "exec_test" dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") status, body, err := sockRequest("POST", fmt.Sprintf("/containers/%s/exec", name), map[string]interface{}{"Cmd": nil}) c.Assert(status, check.Equals, http.StatusInternalServerError) c.Assert(err, check.IsNil) if !bytes.Contains(body, []byte("No exec command specified")) { c.Fatalf("Expected message when creating exec command with no Cmd specified") } } func (s *DockerSuite) TestExecApiCreateNoValidContentType(c *check.C) { name := "exec_test" dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") jsonData := bytes.NewBuffer(nil) if err := json.NewEncoder(jsonData).Encode(map[string]interface{}{"Cmd": nil}); err != nil { c.Fatalf("Can not encode data to json %s", err) } res, body, err := sockRequestRaw("POST", fmt.Sprintf("/containers/%s/exec", name), jsonData, "text/plain") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusInternalServerError) b, err := readBody(body) c.Assert(err, check.IsNil) if !bytes.Contains(b, []byte("Content-Type specified")) { c.Fatalf("Expected message when creating exec command with invalid Content-Type specified") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_images_test.go ================================================ package main import ( "encoding/json" "net/http" "net/url" "strings" "github.com/docker/docker/api/types" "github.com/go-check/check" ) func (s *DockerSuite) TestApiImagesFilter(c *check.C) { name := "utest:tag1" name2 := "utest/docker:tag2" name3 := "utest:5000/docker:tag3" for _, n := range []string{name, name2, name3} { dockerCmd(c, "tag", "busybox", n) } type image types.Image getImages := func(filter string) []image { v := url.Values{} v.Set("filter", filter) status, b, err := sockRequest("GET", "/images/json?"+v.Encode(), nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) var images []image if err := json.Unmarshal(b, &images); err != nil { c.Fatal(err) } return images } errMsg := "incorrect number of matches returned" if images := getImages("utest*/*"); len(images[0].RepoTags) != 2 { c.Fatal(errMsg) } if images := getImages("utest"); len(images[0].RepoTags) != 1 { c.Fatal(errMsg) } if images := getImages("utest*"); len(images[0].RepoTags) != 1 { c.Fatal(errMsg) } if images := getImages("*5000*/*"); len(images[0].RepoTags) != 1 { c.Fatal(errMsg) } } func (s *DockerSuite) TestApiImagesSaveAndLoad(c *check.C) { testRequires(c, Network) out, err := buildImage("saveandload", "FROM hello-world\nENV FOO bar", false) if err != nil { c.Fatal(err) } id := strings.TrimSpace(out) res, body, err := sockRequestRaw("GET", "/images/"+id+"/get", nil, "") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) defer body.Close() dockerCmd(c, "rmi", id) res, loadBody, err := sockRequestRaw("POST", "/images/load", body, "application/x-tar") c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) defer loadBody.Close() inspectOut, _ := dockerCmd(c, "inspect", "--format='{{ .Id }}'", id) if strings.TrimSpace(string(inspectOut)) != id { c.Fatal("load did not work properly") } } func (s *DockerSuite) TestApiImagesDelete(c *check.C) { testRequires(c, Network) name := "test-api-images-delete" out, err := buildImage(name, "FROM hello-world\nENV FOO bar", false) if err != nil { c.Fatal(err) } id := strings.TrimSpace(out) dockerCmd(c, "tag", name, "test:tag1") status, _, err := sockRequest("DELETE", "/images/"+id, nil) c.Assert(status, check.Equals, http.StatusConflict) c.Assert(err, check.IsNil) status, _, err = sockRequest("DELETE", "/images/test:noexist", nil) c.Assert(status, check.Equals, http.StatusNotFound) //Status Codes:404 – no such image c.Assert(err, check.IsNil) status, _, err = sockRequest("DELETE", "/images/test:tag1", nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) } func (s *DockerSuite) TestApiImagesHistory(c *check.C) { testRequires(c, Network) name := "test-api-images-history" out, err := buildImage(name, "FROM hello-world\nENV FOO bar", false) c.Assert(err, check.IsNil) id := strings.TrimSpace(out) status, body, err := sockRequest("GET", "/images/"+id+"/history", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) var historydata []types.ImageHistory if err = json.Unmarshal(body, &historydata); err != nil { c.Fatalf("Error on unmarshal: %s", err) } c.Assert(len(historydata), check.Not(check.Equals), 0) c.Assert(historydata[0].Tags[0], check.Equals, "test-api-images-history:latest") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_info_test.go ================================================ package main import ( "net/http" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestInfoApi(c *check.C) { endpoint := "/info" status, body, err := sockRequest("GET", endpoint, nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) // always shown fields stringsToCheck := []string{ "ID", "Containers", "Images", "ExecutionDriver", "LoggingDriver", "OperatingSystem", "NCPU", "MemTotal", "KernelVersion", "Driver"} out := string(body) for _, linePrefix := range stringsToCheck { if !strings.Contains(out, linePrefix) { c.Errorf("couldn't find string %v in output", linePrefix) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_inspect_test.go ================================================ package main import ( "encoding/json" "fmt" "net/http" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestInspectApiContainerResponse(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) keysBase := []string{"Id", "State", "Created", "Path", "Args", "Config", "Image", "NetworkSettings", "ResolvConfPath", "HostnamePath", "HostsPath", "LogPath", "Name", "Driver", "ExecDriver", "MountLabel", "ProcessLabel", "GraphDriver"} cases := []struct { version string keys []string }{ {"1.20", append(keysBase, "Mounts")}, {"1.19", append(keysBase, "Volumes", "VolumesRW")}, } for _, cs := range cases { endpoint := fmt.Sprintf("/v%s/containers/%s/json", cs.version, cleanedContainerID) status, body, err := sockRequest("GET", endpoint, nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) var inspectJSON map[string]interface{} if err = json.Unmarshal(body, &inspectJSON); err != nil { c.Fatalf("unable to unmarshal body for version %s: %v", cs.version, err) } for _, key := range cs.keys { if _, ok := inspectJSON[key]; !ok { c.Fatalf("%s does not exist in response for version %s", key, cs.version) } } //Issue #6830: type not properly converted to JSON/back if _, ok := inspectJSON["Path"].(bool); ok { c.Fatalf("Path of `true` should not be converted to boolean `true` via JSON marshalling") } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_logs_test.go ================================================ package main import ( "bufio" "bytes" "fmt" "net/http" "strings" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestLogsApiWithStdout(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatal(err) } type logOut struct { out string res *http.Response err error } chLog := make(chan logOut) go func() { res, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", id), nil, "") out, _ := bufio.NewReader(body).ReadString('\n') chLog <- logOut{strings.TrimSpace(out), res, err} }() select { case l := <-chLog: c.Assert(l.err, check.IsNil) c.Assert(l.res.StatusCode, check.Equals, http.StatusOK) if !strings.HasSuffix(l.out, "hello") { c.Fatalf("expected log output to container 'hello', but it does not") } case <-time.After(2 * time.Second): c.Fatal("timeout waiting for logs to exit") } } func (s *DockerSuite) TestLogsApiNoStdoutNorStderr(c *check.C) { name := "logs_test" dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") status, body, err := sockRequest("GET", fmt.Sprintf("/containers/%s/logs", name), nil) c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(err, check.IsNil) expected := "Bad parameters: you must choose at least one stream" if !bytes.Contains(body, []byte(expected)) { c.Fatalf("Expected %s, got %s", expected, string(body[:])) } } // Regression test for #12704 func (s *DockerSuite) TestLogsApiFollowEmptyOutput(c *check.C) { name := "logs_test" t0 := time.Now() dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10") _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name), bytes.NewBuffer(nil), "") t1 := time.Now() body.Close() if err != nil { c.Fatal(err) } elapsed := t1.Sub(t0).Seconds() if elapsed > 5.0 { c.Fatalf("HTTP response was not immediate (elapsed %.1fs)", elapsed) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_network_test.go ================================================ // +build experimental package main import ( "encoding/json" "fmt" "net/http" "github.com/go-check/check" ) func isNetworkAvailable(c *check.C, name string) bool { status, body, err := sockRequest("GET", "/networks", nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) var inspectJSON []struct { Name string ID string Type string } if err = json.Unmarshal(body, &inspectJSON); err != nil { c.Fatalf("unable to unmarshal response body: %v", err) } for _, n := range inspectJSON { if n.Name == name { return true } } return false } func (s *DockerSuite) TestNetworkApiGetAll(c *check.C) { defaults := []string{"bridge", "host", "none"} for _, nn := range defaults { if !isNetworkAvailable(c, nn) { c.Fatalf("Missing Default network : %s", nn) } } } func (s *DockerSuite) TestNetworkApiCreateDelete(c *check.C) { name := "testnetwork" config := map[string]interface{}{ "name": name, "network_type": "bridge", } status, resp, err := sockRequest("POST", "/networks", config) c.Assert(status, check.Equals, http.StatusCreated) c.Assert(err, check.IsNil) if !isNetworkAvailable(c, name) { c.Fatalf("Network %s not found", name) } var id string err = json.Unmarshal(resp, &id) if err != nil { c.Fatal(err) } status, _, err = sockRequest("DELETE", fmt.Sprintf("/networks/%s", id), nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) if isNetworkAvailable(c, name) { c.Fatalf("Network %s not deleted", name) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_resize_test.go ================================================ package main import ( "net/http" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestResizeApiResponse(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40" status, _, err := sockRequest("POST", endpoint, nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) } func (s *DockerSuite) TestResizeApiHeightWidthNoInt(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) endpoint := "/containers/" + cleanedContainerID + "/resize?h=foo&w=bar" status, _, err := sockRequest("POST", endpoint, nil) c.Assert(status, check.Equals, http.StatusInternalServerError) c.Assert(err, check.IsNil) } func (s *DockerSuite) TestResizeApiResponseWhenContainerNotStarted(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) // make sure the exited container is not running dockerCmd(c, "wait", cleanedContainerID) endpoint := "/containers/" + cleanedContainerID + "/resize?h=40&w=40" status, body, err := sockRequest("POST", endpoint, nil) c.Assert(status, check.Equals, http.StatusInternalServerError) c.Assert(err, check.IsNil) if !strings.Contains(string(body), "Cannot resize container") && !strings.Contains(string(body), cleanedContainerID) { c.Fatalf("resize should fail with message 'Cannot resize container' but instead received %s", string(body)) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_service_test.go ================================================ // +build experimental package main import ( "encoding/json" "fmt" "net/http" "github.com/go-check/check" ) func isServiceAvailable(c *check.C, name string, network string) bool { status, body, err := sockRequest("GET", "/services", nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) var inspectJSON []struct { Name string ID string Network string } if err = json.Unmarshal(body, &inspectJSON); err != nil { c.Fatalf("unable to unmarshal response body: %v", err) } for _, s := range inspectJSON { if s.Name == name && s.Network == network { return true } } return false } func isServiceNetworkAvailable(c *check.C, name string) bool { status, body, err := sockRequest("GET", "/networks", nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) var inspectJSON []struct { Name string ID string Type string } if err = json.Unmarshal(body, &inspectJSON); err != nil { c.Fatalf("unable to unmarshal response body: %v", err) } for _, n := range inspectJSON { if n.Name == name { return true } } return false } func (s *DockerSuite) TestServiceApiCreateDelete(c *check.C) { name := "testnetwork" config := map[string]interface{}{ "name": name, "network_type": "bridge", } status, resp, err := sockRequest("POST", "/networks", config) c.Assert(status, check.Equals, http.StatusCreated) c.Assert(err, check.IsNil) if !isServiceNetworkAvailable(c, name) { c.Fatalf("Network %s not found", name) } var nid string err = json.Unmarshal(resp, &nid) if err != nil { c.Fatal(err) } sname := "service1" sconfig := map[string]interface{}{ "name": sname, "network_name": name, } status, resp, err = sockRequest("POST", "/services", sconfig) c.Assert(status, check.Equals, http.StatusCreated) c.Assert(err, check.IsNil) if !isServiceAvailable(c, sname, name) { c.Fatalf("Service %s.%s not found", sname, name) } var id string err = json.Unmarshal(resp, &id) if err != nil { c.Fatal(err) } status, _, err = sockRequest("DELETE", fmt.Sprintf("/services/%s", id), nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) if isServiceAvailable(c, sname, name) { c.Fatalf("Service %s.%s not deleted", sname, name) } status, _, err = sockRequest("DELETE", fmt.Sprintf("/networks/%s", nid), nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) if isNetworkAvailable(c, name) { c.Fatalf("Network %s not deleted", name) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_stats_test.go ================================================ package main import ( "encoding/json" "fmt" "os/exec" "runtime" "strconv" "strings" "time" "github.com/docker/docker/api/types" "github.com/go-check/check" ) func (s *DockerSuite) TestCliStatsNoStreamGetCpu(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;do echo 'Hello'; usleep 100000; done") id := strings.TrimSpace(out) err := waitRun(id) c.Assert(err, check.IsNil) resp, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") c.Assert(err, check.IsNil) c.Assert(resp.ContentLength > 0, check.Equals, true, check.Commentf("should not use chunked encoding")) c.Assert(resp.Header.Get("Content-Type"), check.Equals, "application/json") var v *types.Stats err = json.NewDecoder(body).Decode(&v) c.Assert(err, check.IsNil) var cpuPercent = 0.0 cpuDelta := float64(v.CpuStats.CpuUsage.TotalUsage - v.PreCpuStats.CpuUsage.TotalUsage) systemDelta := float64(v.CpuStats.SystemUsage - v.PreCpuStats.SystemUsage) cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CpuStats.CpuUsage.PercpuUsage)) * 100.0 if cpuPercent == 0 { c.Fatalf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent) } } func (s *DockerSuite) TestStoppedContainerStatsGoroutines(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1") id := strings.TrimSpace(out) getGoRoutines := func() int { _, body, err := sockRequestRaw("GET", fmt.Sprintf("/info"), nil, "") c.Assert(err, check.IsNil) info := types.Info{} err = json.NewDecoder(body).Decode(&info) c.Assert(err, check.IsNil) body.Close() return info.NGoroutines } // When the HTTP connection is closed, the number of goroutines should not increase. routines := getGoRoutines() _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats", id), nil, "") c.Assert(err, check.IsNil) body.Close() t := time.After(30 * time.Second) for { select { case <-t: c.Assert(getGoRoutines() <= routines, check.Equals, true) return default: if n := getGoRoutines(); n <= routines { return } time.Sleep(200 * time.Millisecond) } } } func (s *DockerSuite) TestApiNetworkStats(c *check.C) { testRequires(c, SameHostDaemon) // Run container for 30 secs out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) err := waitRun(id) c.Assert(err, check.IsNil) // Retrieve the container address contIP := findContainerIP(c, id) numPings := 10 // Get the container networking stats before and after pinging the container nwStatsPre := getNetworkStats(c, id) countParam := "-c" if runtime.GOOS == "windows" { countParam = "-n" // Ping count parameter is -n on Windows } pingout, err := exec.Command("ping", contIP, countParam, strconv.Itoa(numPings)).Output() pingouts := string(pingout[:]) c.Assert(err, check.IsNil) nwStatsPost := getNetworkStats(c, id) // Verify the stats contain at least the expected number of packets (account for ARP) expRxPkts := 1 + nwStatsPre.RxPackets + uint64(numPings) expTxPkts := 1 + nwStatsPre.TxPackets + uint64(numPings) c.Assert(nwStatsPost.TxPackets >= expTxPkts, check.Equals, true, check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, nwStatsPost.TxPackets, pingouts)) c.Assert(nwStatsPost.RxPackets >= expRxPkts, check.Equals, true, check.Commentf("Reported less Txbytes than expected. Expected >= %d. Found %d. %s", expRxPkts, nwStatsPost.RxPackets, pingouts)) } func getNetworkStats(c *check.C, id string) types.Network { var st *types.Stats _, body, err := sockRequestRaw("GET", fmt.Sprintf("/containers/%s/stats?stream=false", id), nil, "") c.Assert(err, check.IsNil) err = json.NewDecoder(body).Decode(&st) c.Assert(err, check.IsNil) return st.Network } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_test.go ================================================ package main import ( "net/http" "net/http/httputil" "strconv" "strings" "time" "github.com/docker/docker/api" "github.com/go-check/check" ) func (s *DockerSuite) TestApiOptionsRoute(c *check.C) { status, _, err := sockRequest("OPTIONS", "/", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusOK) } func (s *DockerSuite) TestApiGetEnabledCors(c *check.C) { res, body, err := sockRequestRaw("GET", "/version", nil, "") body.Close() c.Assert(err, check.IsNil) c.Assert(res.StatusCode, check.Equals, http.StatusOK) // TODO: @runcom incomplete tests, why old integration tests had this headers // and here none of the headers below are in the response? //c.Log(res.Header) //c.Assert(res.Header.Get("Access-Control-Allow-Origin"), check.Equals, "*") //c.Assert(res.Header.Get("Access-Control-Allow-Headers"), check.Equals, "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth") } func (s *DockerSuite) TestApiVersionStatusCode(c *check.C) { conn, err := sockConn(time.Duration(10 * time.Second)) c.Assert(err, check.IsNil) client := httputil.NewClientConn(conn, nil) defer client.Close() req, err := http.NewRequest("GET", "/v999.0/version", nil) c.Assert(err, check.IsNil) req.Header.Set("User-Agent", "Docker-Client/999.0 (os)") res, err := client.Do(req) c.Assert(res.StatusCode, check.Equals, http.StatusBadRequest) } func (s *DockerSuite) TestApiClientVersionNewerThanServer(c *check.C) { v := strings.Split(string(api.Version), ".") vMinInt, err := strconv.Atoi(v[1]) c.Assert(err, check.IsNil) vMinInt++ v[1] = strconv.Itoa(vMinInt) version := strings.Join(v, ".") status, body, err := sockRequest("GET", "/v"+version+"/version", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(len(string(body)), check.Not(check.Equals), 0) // Expected not empty body } func (s *DockerSuite) TestApiClientVersionOldNotSupported(c *check.C) { v := strings.Split(string(api.MinVersion), ".") vMinInt, err := strconv.Atoi(v[1]) c.Assert(err, check.IsNil) vMinInt-- v[1] = strconv.Itoa(vMinInt) version := strings.Join(v, ".") status, body, err := sockRequest("GET", "/v"+version+"/version", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, http.StatusBadRequest) c.Assert(len(string(body)), check.Not(check.Equals), 0) // Expected not empty body } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_api_version_test.go ================================================ package main import ( "encoding/json" "net/http" "github.com/docker/docker/api/types" "github.com/docker/docker/autogen/dockerversion" "github.com/go-check/check" ) func (s *DockerSuite) TestGetVersion(c *check.C) { status, body, err := sockRequest("GET", "/version", nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) var v types.Version if err := json.Unmarshal(body, &v); err != nil { c.Fatal(err) } if v.Version != dockerversion.VERSION { c.Fatal("Version mismatch") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_attach_test.go ================================================ package main import ( "bufio" "fmt" "io" "os/exec" "strings" "sync" "time" "github.com/go-check/check" ) const attachWait = 5 * time.Second func (s *DockerSuite) TestAttachMultipleAndRestart(c *check.C) { endGroup := &sync.WaitGroup{} startGroup := &sync.WaitGroup{} endGroup.Add(3) startGroup.Add(3) if err := waitForContainer("attacher", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 1; echo hello; done"); err != nil { c.Fatal(err) } startDone := make(chan struct{}) endDone := make(chan struct{}) go func() { endGroup.Wait() close(endDone) }() go func() { startGroup.Wait() close(startDone) }() for i := 0; i < 3; i++ { go func() { cmd := exec.Command(dockerBinary, "attach", "attacher") defer func() { cmd.Wait() endGroup.Done() }() out, err := cmd.StdoutPipe() if err != nil { c.Fatal(err) } if err := cmd.Start(); err != nil { c.Fatal(err) } buf := make([]byte, 1024) if _, err := out.Read(buf); err != nil && err != io.EOF { c.Fatal(err) } startGroup.Done() if !strings.Contains(string(buf), "hello") { c.Fatalf("unexpected output %s expected hello\n", string(buf)) } }() } select { case <-startDone: case <-time.After(attachWait): c.Fatalf("Attaches did not initialize properly") } dockerCmd(c, "kill", "attacher") select { case <-endDone: case <-time.After(attachWait): c.Fatalf("Attaches did not finish properly") } } func (s *DockerSuite) TestAttachTtyWithoutStdin(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatal(err) } defer func() { cmd := exec.Command(dockerBinary, "kill", id) if out, _, err := runCommandWithOutput(cmd); err != nil { c.Fatalf("failed to kill container: %v (%v)", out, err) } }() done := make(chan error) go func() { defer close(done) cmd := exec.Command(dockerBinary, "attach", id) if _, err := cmd.StdinPipe(); err != nil { done <- err return } expected := "cannot enable tty mode" if out, _, err := runCommandWithOutput(cmd); err == nil { done <- fmt.Errorf("attach should have failed") return } else if !strings.Contains(out, expected) { done <- fmt.Errorf("attach failed with error %q: expected %q", out, expected) return } }() select { case err := <-done: c.Assert(err, check.IsNil) case <-time.After(attachWait): c.Fatal("attach is running but should have failed") } } func (s *DockerSuite) TestAttachDisconnect(c *check.C) { out, _ := dockerCmd(c, "run", "-di", "busybox", "/bin/cat") id := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "attach", id) stdin, err := cmd.StdinPipe() if err != nil { c.Fatal(err) } defer stdin.Close() stdout, err := cmd.StdoutPipe() if err != nil { c.Fatal(err) } defer stdout.Close() if err := cmd.Start(); err != nil { c.Fatal(err) } defer cmd.Process.Kill() if _, err := stdin.Write([]byte("hello\n")); err != nil { c.Fatal(err) } out, err = bufio.NewReader(stdout).ReadString('\n') if err != nil { c.Fatal(err) } if strings.TrimSpace(out) != "hello" { c.Fatalf("expected 'hello', got %q", out) } if err := stdin.Close(); err != nil { c.Fatal(err) } // Expect container to still be running after stdin is closed running, err := inspectField(id, "State.Running") if err != nil { c.Fatal(err) } if running != "true" { c.Fatal("expected container to still be running") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_attach_unix_test.go ================================================ // +build !windows package main import ( "bufio" "os/exec" "strings" "time" "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" "github.com/kr/pty" ) // #9860 func (s *DockerSuite) TestAttachClosedOnContainerStop(c *check.C) { out, _ := dockerCmd(c, "run", "-dti", "busybox", "sleep", "2") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatal(err) } errChan := make(chan error) go func() { defer close(errChan) _, tty, err := pty.Open() if err != nil { errChan <- err return } attachCmd := exec.Command(dockerBinary, "attach", id) attachCmd.Stdin = tty attachCmd.Stdout = tty attachCmd.Stderr = tty if err := attachCmd.Run(); err != nil { errChan <- err return } }() dockerCmd(c, "wait", id) select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(attachWait): c.Fatal("timed out without attach returning") } } func (s *DockerSuite) TestAttachAfterDetach(c *check.C) { name := "detachtest" cpty, tty, err := pty.Open() if err != nil { c.Fatalf("Could not open pty: %v", err) } cmd := exec.Command(dockerBinary, "run", "-ti", "--name", name, "busybox") cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty errChan := make(chan error) go func() { errChan <- cmd.Run() close(errChan) }() time.Sleep(500 * time.Millisecond) if err := waitRun(name); err != nil { c.Fatal(err) } cpty.Write([]byte{16}) time.Sleep(100 * time.Millisecond) cpty.Write([]byte{17}) select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(5 * time.Second): c.Fatal("timeout while detaching") } cpty, tty, err = pty.Open() if err != nil { c.Fatalf("Could not open pty: %v", err) } cmd = exec.Command(dockerBinary, "attach", name) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty if err := cmd.Start(); err != nil { c.Fatal(err) } bytes := make([]byte, 10) var nBytes int readErr := make(chan error, 1) go func() { time.Sleep(500 * time.Millisecond) cpty.Write([]byte("\n")) time.Sleep(500 * time.Millisecond) nBytes, err = cpty.Read(bytes) cpty.Close() readErr <- err }() select { case err := <-readErr: c.Assert(err, check.IsNil) case <-time.After(2 * time.Second): c.Fatal("timeout waiting for attach read") } if err := cmd.Wait(); err != nil { c.Fatal(err) } if !strings.Contains(string(bytes[:nBytes]), "/ #") { c.Fatalf("failed to get a new prompt. got %s", string(bytes[:nBytes])) } } // TestAttachDetach checks that attach in tty mode can be detached using the long container ID func (s *DockerSuite) TestAttachDetach(c *check.C) { out, _ := dockerCmd(c, "run", "-itd", "busybox", "cat") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatal(err) } cpty, tty, err := pty.Open() if err != nil { c.Fatal(err) } defer cpty.Close() cmd := exec.Command(dockerBinary, "attach", id) cmd.Stdin = tty stdout, err := cmd.StdoutPipe() if err != nil { c.Fatal(err) } defer stdout.Close() if err := cmd.Start(); err != nil { c.Fatal(err) } if err := waitRun(id); err != nil { c.Fatalf("error waiting for container to start: %v", err) } if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) } out, err = bufio.NewReader(stdout).ReadString('\n') if err != nil { c.Fatal(err) } if strings.TrimSpace(out) != "hello" { c.Fatalf("expected 'hello', got %q", out) } // escape sequence if _, err := cpty.Write([]byte{16}); err != nil { c.Fatal(err) } time.Sleep(100 * time.Millisecond) if _, err := cpty.Write([]byte{17}); err != nil { c.Fatal(err) } ch := make(chan struct{}) go func() { cmd.Wait() ch <- struct{}{} }() running, err := inspectField(id, "State.Running") if err != nil { c.Fatal(err) } if running != "true" { c.Fatal("expected container to still be running") } go func() { dockerCmd(c, "kill", id) }() select { case <-ch: case <-time.After(10 * time.Millisecond): c.Fatal("timed out waiting for container to exit") } } // TestAttachDetachTruncatedID checks that attach in tty mode can be detached func (s *DockerSuite) TestAttachDetachTruncatedID(c *check.C) { out, _ := dockerCmd(c, "run", "-itd", "busybox", "cat") id := stringid.TruncateID(strings.TrimSpace(out)) if err := waitRun(id); err != nil { c.Fatal(err) } cpty, tty, err := pty.Open() if err != nil { c.Fatal(err) } defer cpty.Close() cmd := exec.Command(dockerBinary, "attach", id) cmd.Stdin = tty stdout, err := cmd.StdoutPipe() if err != nil { c.Fatal(err) } defer stdout.Close() if err := cmd.Start(); err != nil { c.Fatal(err) } if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) } out, err = bufio.NewReader(stdout).ReadString('\n') if err != nil { c.Fatal(err) } if strings.TrimSpace(out) != "hello" { c.Fatalf("expected 'hello', got %q", out) } // escape sequence if _, err := cpty.Write([]byte{16}); err != nil { c.Fatal(err) } time.Sleep(100 * time.Millisecond) if _, err := cpty.Write([]byte{17}); err != nil { c.Fatal(err) } ch := make(chan struct{}) go func() { cmd.Wait() ch <- struct{}{} }() running, err := inspectField(id, "State.Running") if err != nil { c.Fatal(err) } if running != "true" { c.Fatal("expected container to still be running") } go func() { dockerCmd(c, "kill", id) }() select { case <-ch: case <-time.After(10 * time.Millisecond): c.Fatal("timed out waiting for container to exit") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_build_test.go ================================================ package main import ( "archive/tar" "bufio" "bytes" "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "reflect" "regexp" "runtime" "strconv" "strings" "text/template" "time" "github.com/docker/docker/builder/command" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/stringutils" "github.com/go-check/check" ) func (s *DockerSuite) TestBuildJSONEmptyRun(c *check.C) { name := "testbuildjsonemptyrun" _, err := buildImage( name, ` FROM busybox RUN [] `, true) if err != nil { c.Fatal("error when dealing with a RUN statement with empty JSON array") } } func (s *DockerSuite) TestBuildEmptyWhitespace(c *check.C) { name := "testbuildemptywhitespace" _, err := buildImage( name, ` FROM busybox COPY quux \ bar `, true) if err == nil { c.Fatal("no error when dealing with a COPY statement with no content on the same line") } } func (s *DockerSuite) TestBuildShCmdJSONEntrypoint(c *check.C) { name := "testbuildshcmdjsonentrypoint" _, err := buildImage( name, ` FROM busybox ENTRYPOINT ["/bin/echo"] CMD echo test `, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--rm", name) if strings.TrimSpace(out) != "/bin/sh -c echo test" { c.Fatal("CMD did not contain /bin/sh -c") } } func (s *DockerSuite) TestBuildEnvironmentReplacementUser(c *check.C) { name := "testbuildenvironmentreplacement" _, err := buildImage(name, ` FROM scratch ENV user foo USER ${user} `, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.User") if err != nil { c.Fatal(err) } if res != `"foo"` { c.Fatal("User foo from environment not in Config.User on image") } } func (s *DockerSuite) TestBuildEnvironmentReplacementVolume(c *check.C) { name := "testbuildenvironmentreplacement" _, err := buildImage(name, ` FROM scratch ENV volume /quux VOLUME ${volume} `, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Volumes") if err != nil { c.Fatal(err) } var volumes map[string]interface{} if err := json.Unmarshal([]byte(res), &volumes); err != nil { c.Fatal(err) } if _, ok := volumes["/quux"]; !ok { c.Fatal("Volume /quux from environment not in Config.Volumes on image") } } func (s *DockerSuite) TestBuildEnvironmentReplacementExpose(c *check.C) { name := "testbuildenvironmentreplacement" _, err := buildImage(name, ` FROM scratch ENV port 80 EXPOSE ${port} `, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.ExposedPorts") if err != nil { c.Fatal(err) } var exposedPorts map[string]interface{} if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil { c.Fatal(err) } if _, ok := exposedPorts["80/tcp"]; !ok { c.Fatal("Exposed port 80 from environment not in Config.ExposedPorts on image") } } func (s *DockerSuite) TestBuildEnvironmentReplacementWorkdir(c *check.C) { name := "testbuildenvironmentreplacement" _, err := buildImage(name, ` FROM busybox ENV MYWORKDIR /work RUN mkdir ${MYWORKDIR} WORKDIR ${MYWORKDIR} `, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEnvironmentReplacementAddCopy(c *check.C) { name := "testbuildenvironmentreplacement" ctx, err := fakeContext(` FROM scratch ENV baz foo ENV quux bar ENV dot . ENV fee fff ENV gee ggg ADD ${baz} ${dot} COPY ${quux} ${dot} ADD ${zzz:-${fee}} ${dot} COPY ${zzz:-${gee}} ${dot} `, map[string]string{ "foo": "test1", "bar": "test2", "fff": "test3", "ggg": "test4", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEnvironmentReplacementEnv(c *check.C) { name := "testbuildenvironmentreplacement" _, err := buildImage(name, ` FROM busybox ENV foo zzz ENV bar ${foo} ENV abc1='$foo' ENV env1=$foo env2=${foo} env3="$foo" env4="${foo}" RUN [ "$abc1" = '$foo' ] && (echo "$abc1" | grep -q foo) ENV abc2="\$foo" RUN [ "$abc2" = '$foo' ] && (echo "$abc2" | grep -q foo) ENV abc3 '$foo' RUN [ "$abc3" = '$foo' ] && (echo "$abc3" | grep -q foo) ENV abc4 "\$foo" RUN [ "$abc4" = '$foo' ] && (echo "$abc4" | grep -q foo) `, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Env") if err != nil { c.Fatal(err) } envResult := []string{} if err = unmarshalJSON([]byte(res), &envResult); err != nil { c.Fatal(err) } found := false envCount := 0 for _, env := range envResult { parts := strings.SplitN(env, "=", 2) if parts[0] == "bar" { found = true if parts[1] != "zzz" { c.Fatalf("Could not find replaced var for env `bar`: got %q instead of `zzz`", parts[1]) } } else if strings.HasPrefix(parts[0], "env") { envCount++ if parts[1] != "zzz" { c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1]) } } else if strings.HasPrefix(parts[0], "env") { envCount++ if parts[1] != "foo" { c.Fatalf("%s should be 'foo' but instead its %q", parts[0], parts[1]) } } } if !found { c.Fatal("Never found the `bar` env variable") } if envCount != 4 { c.Fatalf("Didn't find all env vars - only saw %d\n%s", envCount, envResult) } } func (s *DockerSuite) TestBuildHandleEscapes(c *check.C) { name := "testbuildhandleescapes" _, err := buildImage(name, ` FROM scratch ENV FOO bar VOLUME ${FOO} `, true) if err != nil { c.Fatal(err) } var result map[string]map[string]struct{} res, err := inspectFieldJSON(name, "Config.Volumes") if err != nil { c.Fatal(err) } if err = unmarshalJSON([]byte(res), &result); err != nil { c.Fatal(err) } if _, ok := result["bar"]; !ok { c.Fatal("Could not find volume bar set from env foo in volumes table") } deleteImages(name) _, err = buildImage(name, ` FROM scratch ENV FOO bar VOLUME \${FOO} `, true) if err != nil { c.Fatal(err) } res, err = inspectFieldJSON(name, "Config.Volumes") if err != nil { c.Fatal(err) } if err = unmarshalJSON([]byte(res), &result); err != nil { c.Fatal(err) } if _, ok := result["${FOO}"]; !ok { c.Fatal("Could not find volume ${FOO} set from env foo in volumes table") } deleteImages(name) // this test in particular provides *7* backslashes and expects 6 to come back. // Like above, the first escape is swallowed and the rest are treated as // literals, this one is just less obvious because of all the character noise. _, err = buildImage(name, ` FROM scratch ENV FOO bar VOLUME \\\\\\\${FOO} `, true) if err != nil { c.Fatal(err) } res, err = inspectFieldJSON(name, "Config.Volumes") if err != nil { c.Fatal(err) } if err = unmarshalJSON([]byte(res), &result); err != nil { c.Fatal(err) } if _, ok := result[`\\\${FOO}`]; !ok { c.Fatal(`Could not find volume \\\${FOO} set from env foo in volumes table`, result) } } func (s *DockerSuite) TestBuildOnBuildLowercase(c *check.C) { name := "testbuildonbuildlowercase" name2 := "testbuildonbuildlowercase2" _, err := buildImage(name, ` FROM busybox onbuild run echo quux `, true) if err != nil { c.Fatal(err) } _, out, err := buildImageWithOut(name2, fmt.Sprintf(` FROM %s `, name), true) if err != nil { c.Fatal(err) } if !strings.Contains(out, "quux") { c.Fatalf("Did not receive the expected echo text, got %s", out) } if strings.Contains(out, "ONBUILD ONBUILD") { c.Fatalf("Got an ONBUILD ONBUILD error with no error: got %s", out) } } func (s *DockerSuite) TestBuildEnvEscapes(c *check.C) { name := "testbuildenvescapes" _, err := buildImage(name, ` FROM busybox ENV TEST foo CMD echo \$ `, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "-t", name) if strings.TrimSpace(out) != "$" { c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out)) } } func (s *DockerSuite) TestBuildEnvOverwrite(c *check.C) { name := "testbuildenvoverwrite" _, err := buildImage(name, ` FROM busybox ENV TEST foo CMD echo ${TEST} `, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "-e", "TEST=bar", "-t", name) if strings.TrimSpace(out) != "bar" { c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out)) } } func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainerInSourceImage(c *check.C) { name := "testbuildonbuildforbiddenmaintainerinsourceimage" out, _ := dockerCmd(c, "create", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "commit", "--run", "{\"OnBuild\":[\"MAINTAINER docker.io\"]}", cleanedContainerID, "onbuild") _, err := buildImage(name, `FROM onbuild`, true) if err != nil { if !strings.Contains(err.Error(), "maintainer isn't allowed as an ONBUILD trigger") { c.Fatalf("Wrong error %v, must be about MAINTAINER and ONBUILD in source image", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildOnBuildForbiddenFromInSourceImage(c *check.C) { name := "testbuildonbuildforbiddenfrominsourceimage" out, _ := dockerCmd(c, "create", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "commit", "--run", "{\"OnBuild\":[\"FROM busybox\"]}", cleanedContainerID, "onbuild") _, err := buildImage(name, `FROM onbuild`, true) if err != nil { if !strings.Contains(err.Error(), "from isn't allowed as an ONBUILD trigger") { c.Fatalf("Wrong error %v, must be about FROM and ONBUILD in source image", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildOnBuildForbiddenChainedInSourceImage(c *check.C) { name := "testbuildonbuildforbiddenchainedinsourceimage" out, _ := dockerCmd(c, "create", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "commit", "--run", "{\"OnBuild\":[\"ONBUILD RUN ls\"]}", cleanedContainerID, "onbuild") _, err := buildImage(name, `FROM onbuild`, true) if err != nil { if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") { c.Fatalf("Wrong error %v, must be about chaining ONBUILD in source image", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildOnBuildCmdEntrypointJSON(c *check.C) { name1 := "onbuildcmd" name2 := "onbuildgenerated" _, err := buildImage(name1, ` FROM busybox ONBUILD CMD ["hello world"] ONBUILD ENTRYPOINT ["echo"] ONBUILD RUN ["true"]`, false) if err != nil { c.Fatal(err) } _, err = buildImage(name2, fmt.Sprintf(`FROM %s`, name1), false) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "-t", name2) if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) { c.Fatal("did not get echo output from onbuild", out) } } func (s *DockerSuite) TestBuildOnBuildEntrypointJSON(c *check.C) { name1 := "onbuildcmd" name2 := "onbuildgenerated" _, err := buildImage(name1, ` FROM busybox ONBUILD ENTRYPOINT ["echo"]`, false) if err != nil { c.Fatal(err) } _, err = buildImage(name2, fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1), false) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "-t", name2) if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) { c.Fatal("got malformed output from onbuild", out) } } func (s *DockerSuite) TestBuildCacheAdd(c *check.C) { name := "testbuildtwoimageswithadd" server, err := fakeStorage(map[string]string{ "robots.txt": "hello", "index.html": "world", }) if err != nil { c.Fatal(err) } defer server.Close() if _, err := buildImage(name, fmt.Sprintf(`FROM scratch ADD %s/robots.txt /`, server.URL()), true); err != nil { c.Fatal(err) } if err != nil { c.Fatal(err) } deleteImages(name) _, out, err := buildImageWithOut(name, fmt.Sprintf(`FROM scratch ADD %s/index.html /`, server.URL()), true) if err != nil { c.Fatal(err) } if strings.Contains(out, "Using cache") { c.Fatal("2nd build used cache on ADD, it shouldn't") } } func (s *DockerSuite) TestBuildLastModified(c *check.C) { name := "testbuildlastmodified" server, err := fakeStorage(map[string]string{ "file": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() var out, out2 string dFmt := `FROM busybox ADD %s/file / RUN ls -le /file` dockerfile := fmt.Sprintf(dFmt, server.URL()) if _, out, err = buildImageWithOut(name, dockerfile, false); err != nil { c.Fatal(err) } originMTime := regexp.MustCompile(`root.*/file.*\n`).FindString(out) // Make sure our regexp is correct if strings.Index(originMTime, "/file") < 0 { c.Fatalf("Missing ls info on 'file':\n%s", out) } // Build it again and make sure the mtime of the file didn't change. // Wait a few seconds to make sure the time changed enough to notice time.Sleep(2 * time.Second) if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil { c.Fatal(err) } newMTime := regexp.MustCompile(`root.*/file.*\n`).FindString(out2) if newMTime != originMTime { c.Fatalf("MTime changed:\nOrigin:%s\nNew:%s", originMTime, newMTime) } // Now 'touch' the file and make sure the timestamp DID change this time // Create a new fakeStorage instead of just using Add() to help windows server, err = fakeStorage(map[string]string{ "file": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() dockerfile = fmt.Sprintf(dFmt, server.URL()) if _, out2, err = buildImageWithOut(name, dockerfile, false); err != nil { c.Fatal(err) } newMTime = regexp.MustCompile(`root.*/file.*\n`).FindString(out2) if newMTime == originMTime { c.Fatalf("MTime didn't change:\nOrigin:%s\nNew:%s", originMTime, newMTime) } } func (s *DockerSuite) TestBuildSixtySteps(c *check.C) { name := "foobuildsixtysteps" ctx, err := fakeContext("FROM scratch\n"+strings.Repeat("ADD foo /\n", 60), map[string]string{ "foo": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *check.C) { name := "testaddimg" ctx, err := fakeContext(fmt.Sprintf(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio /exists ADD test_file / RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod), map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } // Issue #3960: "ADD src ." hangs func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *check.C) { name := "testaddsinglefiletoworkdir" ctx, err := fakeContext(`FROM busybox ADD test_file .`, map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() errChan := make(chan error) go func() { _, err := buildImageFromContext(name, ctx, true) errChan <- err close(errChan) }() select { case <-time.After(5 * time.Second): c.Fatal("Build with adding to workdir timed out") case err := <-errChan: c.Assert(err, check.IsNil) } } func (s *DockerSuite) TestBuildAddSingleFileToExistDir(c *check.C) { name := "testaddsinglefiletoexistdir" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN mkdir /exists RUN touch /exists/exists_file RUN chown -R dockerio.dockerio /exists ADD test_file /exists/ RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyAddMultipleFiles(c *check.C) { server, err := fakeStorage(map[string]string{ "robots.txt": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() name := "testcopymultiplefilestofile" ctx, err := fakeContext(fmt.Sprintf(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN mkdir /exists RUN touch /exists/exists_file RUN chown -R dockerio.dockerio /exists COPY test_file1 test_file2 /exists/ ADD test_file3 test_file4 %s/robots.txt /exists/ RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/test_file1 | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/test_file2 | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/test_file3 | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/test_file4 | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/robots.txt | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ] `, server.URL()), map[string]string{ "test_file1": "test1", "test_file2": "test2", "test_file3": "test3", "test_file4": "test4", }) defer ctx.Close() if err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddMultipleFilesToFile(c *check.C) { name := "testaddmultiplefilestofile" ctx, err := fakeContext(`FROM scratch ADD file1.txt file2.txt test `, map[string]string{ "file1.txt": "test1", "file2.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using ADD with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFile(c *check.C) { name := "testjsonaddmultiplefilestofile" ctx, err := fakeContext(`FROM scratch ADD ["file1.txt", "file2.txt", "test"] `, map[string]string{ "file1.txt": "test1", "file2.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using ADD with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildAddMultipleFilesToFileWild(c *check.C) { name := "testaddmultiplefilestofilewild" ctx, err := fakeContext(`FROM scratch ADD file*.txt test `, map[string]string{ "file1.txt": "test1", "file2.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using ADD with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildJSONAddMultipleFilesToFileWild(c *check.C) { name := "testjsonaddmultiplefilestofilewild" ctx, err := fakeContext(`FROM scratch ADD ["file*.txt", "test"] `, map[string]string{ "file1.txt": "test1", "file2.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using ADD with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildCopyMultipleFilesToFile(c *check.C) { name := "testcopymultiplefilestofile" ctx, err := fakeContext(`FROM scratch COPY file1.txt file2.txt test `, map[string]string{ "file1.txt": "test1", "file2.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using COPY with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildJSONCopyMultipleFilesToFile(c *check.C) { name := "testjsoncopymultiplefilestofile" ctx, err := fakeContext(`FROM scratch COPY ["file1.txt", "file2.txt", "test"] `, map[string]string{ "file1.txt": "test1", "file2.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using COPY with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildAddFileWithWhitespace(c *check.C) { name := "testaddfilewithwhitespace" ctx, err := fakeContext(`FROM busybox RUN mkdir "/test dir" RUN mkdir "/test_dir" ADD [ "test file1", "/test_file1" ] ADD [ "test_file2", "/test file2" ] ADD [ "test file3", "/test file3" ] ADD [ "test dir/test_file4", "/test_dir/test_file4" ] ADD [ "test_dir/test_file5", "/test dir/test_file5" ] ADD [ "test dir/test_file6", "/test dir/test_file6" ] RUN [ $(cat "/test_file1") = 'test1' ] RUN [ $(cat "/test file2") = 'test2' ] RUN [ $(cat "/test file3") = 'test3' ] RUN [ $(cat "/test_dir/test_file4") = 'test4' ] RUN [ $(cat "/test dir/test_file5") = 'test5' ] RUN [ $(cat "/test dir/test_file6") = 'test6' ]`, map[string]string{ "test file1": "test1", "test_file2": "test2", "test file3": "test3", "test dir/test_file4": "test4", "test_dir/test_file5": "test5", "test dir/test_file6": "test6", }) defer ctx.Close() if err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyFileWithWhitespace(c *check.C) { name := "testcopyfilewithwhitespace" ctx, err := fakeContext(`FROM busybox RUN mkdir "/test dir" RUN mkdir "/test_dir" COPY [ "test file1", "/test_file1" ] COPY [ "test_file2", "/test file2" ] COPY [ "test file3", "/test file3" ] COPY [ "test dir/test_file4", "/test_dir/test_file4" ] COPY [ "test_dir/test_file5", "/test dir/test_file5" ] COPY [ "test dir/test_file6", "/test dir/test_file6" ] RUN [ $(cat "/test_file1") = 'test1' ] RUN [ $(cat "/test file2") = 'test2' ] RUN [ $(cat "/test file3") = 'test3' ] RUN [ $(cat "/test_dir/test_file4") = 'test4' ] RUN [ $(cat "/test dir/test_file5") = 'test5' ] RUN [ $(cat "/test dir/test_file6") = 'test6' ]`, map[string]string{ "test file1": "test1", "test_file2": "test2", "test file3": "test3", "test dir/test_file4": "test4", "test_dir/test_file5": "test5", "test dir/test_file6": "test6", }) defer ctx.Close() if err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddMultipleFilesToFileWithWhitespace(c *check.C) { name := "testaddmultiplefilestofilewithwhitespace" ctx, err := fakeContext(`FROM busybox ADD [ "test file1", "test file2", "test" ] `, map[string]string{ "test file1": "test1", "test file2": "test2", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using ADD with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildCopyMultipleFilesToFileWithWhitespace(c *check.C) { name := "testcopymultiplefilestofilewithwhitespace" ctx, err := fakeContext(`FROM busybox COPY [ "test file1", "test file2", "test" ] `, map[string]string{ "test file1": "test1", "test file2": "test2", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "When using COPY with more than one source file, the destination must be a directory and end with a /" if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain %q) got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) { name := "testcopywildcard" server, err := fakeStorage(map[string]string{ "robots.txt": "hello", "index.html": "world", }) if err != nil { c.Fatal(err) } defer server.Close() ctx, err := fakeContext(fmt.Sprintf(`FROM busybox COPY file*.txt /tmp/ RUN ls /tmp/file1.txt /tmp/file2.txt RUN mkdir /tmp1 COPY dir* /tmp1/ RUN ls /tmp1/dirt /tmp1/nested_file /tmp1/nested_dir/nest_nest_file RUN mkdir /tmp2 ADD dir/*dir %s/robots.txt /tmp2/ RUN ls /tmp2/nest_nest_file /tmp2/robots.txt `, server.URL()), map[string]string{ "file1.txt": "test1", "file2.txt": "test2", "dir/nested_file": "nested file", "dir/nested_dir/nest_nest_file": "2 times nested", "dirt": "dirty", }) if err != nil { c.Fatal(err) } defer ctx.Close() id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } // Now make sure we use a cache the 2nd time id2, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("didn't use the cache") } } func (s *DockerSuite) TestBuildCopyWildcardNoFind(c *check.C) { name := "testcopywildcardnofind" ctx, err := fakeContext(`FROM busybox COPY file*.txt /tmp/ `, nil) defer ctx.Close() if err != nil { c.Fatal(err) } _, err = buildImageFromContext(name, ctx, true) if err == nil { c.Fatal("should have failed to find a file") } if !strings.Contains(err.Error(), "No source files were specified") { c.Fatalf("Wrong error %v, must be about no source files", err) } } func (s *DockerSuite) TestBuildCopyWildcardInName(c *check.C) { name := "testcopywildcardinname" ctx, err := fakeContext(`FROM busybox COPY *.txt /tmp/ RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ] `, map[string]string{"*.txt": "hi there"}) if err != nil { // Normally we would do c.Fatal(err) here but given that // the odds of this failing are so rare, it must be because // the OS we're running the client on doesn't support * in // filenames (like windows). So, instead of failing the test // just let it pass. Then we don't need to explicitly // say which OSs this works on or not. return } defer ctx.Close() _, err = buildImageFromContext(name, ctx, true) if err != nil { c.Fatalf("should have built: %q", err) } } func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) { name := "testcopywildcardcache" ctx, err := fakeContext(`FROM busybox COPY file1.txt /tmp/`, map[string]string{ "file1.txt": "test1", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } // Now make sure we use a cache the 2nd time even with wild cards. // Use the same context so the file is the same and the checksum will match ctx.Add("Dockerfile", `FROM busybox COPY file*.txt /tmp/`) id2, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("didn't use the cache") } } func (s *DockerSuite) TestBuildAddSingleFileToNonExistingDir(c *check.C) { name := "testaddsinglefiletononexistingdir" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio /exists ADD test_file /test_dir/ RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddDirContentToRoot(c *check.C) { name := "testadddircontenttoroot" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio exists ADD test_dir / RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, map[string]string{ "test_dir/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddDirContentToExistingDir(c *check.C) { name := "testadddircontenttoexistingdir" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN mkdir /exists RUN touch /exists/exists_file RUN chown -R dockerio.dockerio /exists ADD test_dir/ /exists/ RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`, map[string]string{ "test_dir/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddWholeDirToRoot(c *check.C) { name := "testaddwholedirtoroot" ctx, err := fakeContext(fmt.Sprintf(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio exists ADD test_dir /test_dir RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ] RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod), map[string]string{ "test_dir/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } // Testing #5941 func (s *DockerSuite) TestBuildAddEtcToRoot(c *check.C) { name := "testaddetctoroot" ctx, err := fakeContext(`FROM scratch ADD . /`, map[string]string{ "etc/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } // Testing #9401 func (s *DockerSuite) TestBuildAddPreservesFilesSpecialBits(c *check.C) { name := "testaddpreservesfilesspecialbits" ctx, err := fakeContext(`FROM busybox ADD suidbin /usr/bin/suidbin RUN chmod 4755 /usr/bin/suidbin RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ] ADD ./data/ / RUN [ $(ls -l /usr/bin/suidbin | awk '{print $1}') = '-rwsr-xr-x' ]`, map[string]string{ "suidbin": "suidbin", "/data/usr/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopySingleFileToRoot(c *check.C) { name := "testcopysinglefiletoroot" ctx, err := fakeContext(fmt.Sprintf(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio /exists COPY test_file / RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /test_file | awk '{print $1}') = '%s' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod), map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } // Issue #3960: "ADD src ." hangs - adapted for COPY func (s *DockerSuite) TestBuildCopySingleFileToWorkdir(c *check.C) { name := "testcopysinglefiletoworkdir" ctx, err := fakeContext(`FROM busybox COPY test_file .`, map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() errChan := make(chan error) go func() { _, err := buildImageFromContext(name, ctx, true) errChan <- err close(errChan) }() select { case <-time.After(5 * time.Second): c.Fatal("Build with adding to workdir timed out") case err := <-errChan: c.Assert(err, check.IsNil) } } func (s *DockerSuite) TestBuildCopySingleFileToExistDir(c *check.C) { name := "testcopysinglefiletoexistdir" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN mkdir /exists RUN touch /exists/exists_file RUN chown -R dockerio.dockerio /exists COPY test_file /exists/ RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopySingleFileToNonExistDir(c *check.C) { name := "testcopysinglefiletononexistdir" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio /exists COPY test_file /test_dir/ RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, map[string]string{ "test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyDirContentToRoot(c *check.C) { name := "testcopydircontenttoroot" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio exists COPY test_dir / RUN [ $(ls -l /test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, map[string]string{ "test_dir/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyDirContentToExistDir(c *check.C) { name := "testcopydircontenttoexistdir" ctx, err := fakeContext(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN mkdir /exists RUN touch /exists/exists_file RUN chown -R dockerio.dockerio /exists COPY test_dir/ /exists/ RUN [ $(ls -l / | grep exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/exists_file | awk '{print $3":"$4}') = 'dockerio:dockerio' ] RUN [ $(ls -l /exists/test_file | awk '{print $3":"$4}') = 'root:root' ]`, map[string]string{ "test_dir/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyWholeDirToRoot(c *check.C) { name := "testcopywholedirtoroot" ctx, err := fakeContext(fmt.Sprintf(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN touch /exists RUN chown dockerio.dockerio exists COPY test_dir /test_dir RUN [ $(ls -l / | grep test_dir | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l / | grep test_dir | awk '{print $1}') = 'drwxr-xr-x' ] RUN [ $(ls -l /test_dir/test_file | awk '{print $3":"$4}') = 'root:root' ] RUN [ $(ls -l /test_dir/test_file | awk '{print $1}') = '%s' ] RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expectedFileChmod), map[string]string{ "test_dir/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyEtcToRoot(c *check.C) { name := "testcopyetctoroot" ctx, err := fakeContext(`FROM scratch COPY . /`, map[string]string{ "etc/test_file": "test1", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCopyDisallowRemote(c *check.C) { name := "testcopydisallowremote" _, out, err := buildImageWithOut(name, `FROM scratch COPY https://index.docker.io/robots.txt /`, true) if err == nil || !strings.Contains(out, "Source can't be a URL for COPY") { c.Fatalf("Error should be about disallowed remote source, got err: %s, out: %q", err, out) } } func (s *DockerSuite) TestBuildAddBadLinks(c *check.C) { const ( dockerfile = ` FROM scratch ADD links.tar / ADD foo.txt /symlink/ ` targetFile = "foo.txt" ) var ( name = "test-link-absolute" ) ctx, err := fakeContext(dockerfile, nil) if err != nil { c.Fatal(err) } defer ctx.Close() tempDir, err := ioutil.TempDir("", "test-link-absolute-temp-") if err != nil { c.Fatalf("failed to create temporary directory: %s", tempDir) } defer os.RemoveAll(tempDir) var symlinkTarget string if runtime.GOOS == "windows" { var driveLetter string if abs, err := filepath.Abs(tempDir); err != nil { c.Fatal(err) } else { driveLetter = abs[:1] } tempDirWithoutDrive := tempDir[2:] symlinkTarget = fmt.Sprintf(`%s:\..\..\..\..\..\..\..\..\..\..\..\..%s`, driveLetter, tempDirWithoutDrive) } else { symlinkTarget = fmt.Sprintf("/../../../../../../../../../../../..%s", tempDir) } tarPath := filepath.Join(ctx.Dir, "links.tar") nonExistingFile := filepath.Join(tempDir, targetFile) fooPath := filepath.Join(ctx.Dir, targetFile) tarOut, err := os.Create(tarPath) if err != nil { c.Fatal(err) } tarWriter := tar.NewWriter(tarOut) header := &tar.Header{ Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: symlinkTarget, Mode: 0755, Uid: 0, Gid: 0, } err = tarWriter.WriteHeader(header) if err != nil { c.Fatal(err) } tarWriter.Close() tarOut.Close() foo, err := os.Create(fooPath) if err != nil { c.Fatal(err) } defer foo.Close() if _, err := foo.WriteString("test"); err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) { c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile) } } func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) { const ( dockerfileTemplate = ` FROM busybox RUN ln -s /../../../../../../../../%s /x VOLUME /x ADD foo.txt /x/` targetFile = "foo.txt" ) var ( name = "test-link-absolute-volume" dockerfile = "" ) tempDir, err := ioutil.TempDir("", "test-link-absolute-volume-temp-") if err != nil { c.Fatalf("failed to create temporary directory: %s", tempDir) } defer os.RemoveAll(tempDir) dockerfile = fmt.Sprintf(dockerfileTemplate, tempDir) nonExistingFile := filepath.Join(tempDir, targetFile) ctx, err := fakeContext(dockerfile, nil) if err != nil { c.Fatal(err) } defer ctx.Close() fooPath := filepath.Join(ctx.Dir, targetFile) foo, err := os.Create(fooPath) if err != nil { c.Fatal(err) } defer foo.Close() if _, err := foo.WriteString("test"); err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) { c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile) } } // Issue #5270 - ensure we throw a better error than "unexpected EOF" // when we can't access files in the context. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) { testRequires(c, UnixCli) // test uses chown/chmod: not available on windows { name := "testbuildinaccessiblefiles" ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"fileWithoutReadAccess": "foo"}) if err != nil { c.Fatal(err) } defer ctx.Close() // This is used to ensure we detect inaccessible files early during build in the cli client pathToFileWithoutReadAccess := filepath.Join(ctx.Dir, "fileWithoutReadAccess") if err = os.Chown(pathToFileWithoutReadAccess, 0, 0); err != nil { c.Fatalf("failed to chown file to root: %s", err) } if err = os.Chmod(pathToFileWithoutReadAccess, 0700); err != nil { c.Fatalf("failed to chmod file to 700: %s", err) } buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)) buildCmd.Dir = ctx.Dir out, _, err := runCommandWithOutput(buildCmd) if err == nil { c.Fatalf("build should have failed: %s %s", err, out) } // check if we've detected the failure before we started building if !strings.Contains(out, "no permission to read from ") { c.Fatalf("output should've contained the string: no permission to read from but contained: %s", out) } if !strings.Contains(out, "Error checking context") { c.Fatalf("output should've contained the string: Error checking context") } } { name := "testbuildinaccessibledirectory" ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{"directoryWeCantStat/bar": "foo"}) if err != nil { c.Fatal(err) } defer ctx.Close() // This is used to ensure we detect inaccessible directories early during build in the cli client pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat") pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar") if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil { c.Fatalf("failed to chown directory to root: %s", err) } if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil { c.Fatalf("failed to chmod directory to 444: %s", err) } if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil { c.Fatalf("failed to chmod file to 700: %s", err) } buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)) buildCmd.Dir = ctx.Dir out, _, err := runCommandWithOutput(buildCmd) if err == nil { c.Fatalf("build should have failed: %s %s", err, out) } // check if we've detected the failure before we started building if !strings.Contains(out, "can't stat") { c.Fatalf("output should've contained the string: can't access %s", out) } if !strings.Contains(out, "Error checking context") { c.Fatalf("output should've contained the string: Error checking context\ngot:%s", out) } } { name := "testlinksok" ctx, err := fakeContext("FROM scratch\nADD . /foo/", nil) if err != nil { c.Fatal(err) } defer ctx.Close() target := "../../../../../../../../../../../../../../../../../../../azA" if err := os.Symlink(filepath.Join(ctx.Dir, "g"), target); err != nil { c.Fatal(err) } defer os.Remove(target) // This is used to ensure we don't follow links when checking if everything in the context is accessible // This test doesn't require that we run commands as an unprivileged user if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } { name := "testbuildignoredinaccessible" ctx, err := fakeContext("FROM scratch\nADD . /foo/", map[string]string{ "directoryWeCantStat/bar": "foo", ".dockerignore": "directoryWeCantStat", }) if err != nil { c.Fatal(err) } defer ctx.Close() // This is used to ensure we don't try to add inaccessible files when they are ignored by a .dockerignore pattern pathToDirectoryWithoutReadAccess := filepath.Join(ctx.Dir, "directoryWeCantStat") pathToFileInDirectoryWithoutReadAccess := filepath.Join(pathToDirectoryWithoutReadAccess, "bar") if err = os.Chown(pathToDirectoryWithoutReadAccess, 0, 0); err != nil { c.Fatalf("failed to chown directory to root: %s", err) } if err = os.Chmod(pathToDirectoryWithoutReadAccess, 0444); err != nil { c.Fatalf("failed to chmod directory to 755: %s", err) } if err = os.Chmod(pathToFileInDirectoryWithoutReadAccess, 0700); err != nil { c.Fatalf("failed to chmod file to 444: %s", err) } buildCmd := exec.Command("su", "unprivilegeduser", "-c", fmt.Sprintf("%s build -t %s .", dockerBinary, name)) buildCmd.Dir = ctx.Dir if out, _, err := runCommandWithOutput(buildCmd); err != nil { c.Fatalf("build should have worked: %s %s", err, out) } } } func (s *DockerSuite) TestBuildForceRm(c *check.C) { containerCountBefore, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } name := "testbuildforcerm" ctx, err := fakeContext("FROM scratch\nRUN true\nRUN thiswillfail", nil) if err != nil { c.Fatal(err) } defer ctx.Close() dockerCmdInDir(c, ctx.Dir, "build", "-t", name, "--force-rm", ".") containerCountAfter, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } if containerCountBefore != containerCountAfter { c.Fatalf("--force-rm shouldn't have left containers behind") } } // Test that an infinite sleep during a build is killed if the client disconnects. // This test is fairly hairy because there are lots of ways to race. // Strategy: // * Monitor the output of docker events starting from before // * Run a 1-year-long sleep from a docker build. // * When docker events sees container start, close the "docker build" command // * Wait for docker events to emit a dying event. func (s *DockerSuite) TestBuildCancelationKillsSleep(c *check.C) { name := "testbuildcancelation" // (Note: one year, will never finish) ctx, err := fakeContext("FROM busybox\nRUN sleep 31536000", nil) if err != nil { c.Fatal(err) } defer ctx.Close() finish := make(chan struct{}) defer close(finish) eventStart := make(chan struct{}) eventDie := make(chan struct{}) containerID := make(chan string) startEpoch := daemonTime(c).Unix() // Watch for events since epoch. eventsCmd := exec.Command( dockerBinary, "events", "--since", strconv.FormatInt(startEpoch, 10)) stdout, err := eventsCmd.StdoutPipe() if err != nil { c.Fatal(err) } if err := eventsCmd.Start(); err != nil { c.Fatal(err) } defer eventsCmd.Process.Kill() // Goroutine responsible for watching start/die events from `docker events` go func() { cid := <-containerID matchStart := regexp.MustCompile(cid + `(.*) start$`) matchDie := regexp.MustCompile(cid + `(.*) die$`) // // Read lines of `docker events` looking for container start and stop. // scanner := bufio.NewScanner(stdout) for scanner.Scan() { switch { case matchStart.MatchString(scanner.Text()): close(eventStart) case matchDie.MatchString(scanner.Text()): close(eventDie) } } }() buildCmd := exec.Command(dockerBinary, "build", "-t", name, ".") buildCmd.Dir = ctx.Dir stdoutBuild, err := buildCmd.StdoutPipe() if err := buildCmd.Start(); err != nil { c.Fatalf("failed to run build: %s", err) } matchCID := regexp.MustCompile("Running in ") scanner := bufio.NewScanner(stdoutBuild) for scanner.Scan() { line := scanner.Text() if ok := matchCID.MatchString(line); ok { containerID <- line[len(line)-12:] break } } select { case <-time.After(5 * time.Second): c.Fatal("failed to observe build container start in timely fashion") case <-eventStart: // Proceeds from here when we see the container fly past in the // output of "docker events". // Now we know the container is running. } // Send a kill to the `docker build` command. // Causes the underlying build to be cancelled due to socket close. if err := buildCmd.Process.Kill(); err != nil { c.Fatalf("error killing build command: %s", err) } // Get the exit status of `docker build`, check it exited because killed. if err := buildCmd.Wait(); err != nil && !IsKilled(err) { c.Fatalf("wait failed during build run: %T %s", err, err) } select { case <-time.After(5 * time.Second): // If we don't get here in a timely fashion, it wasn't killed. c.Fatal("container cancel did not succeed") case <-eventDie: // We saw the container shut down in the `docker events` stream, // as expected. } } func (s *DockerSuite) TestBuildRm(c *check.C) { name := "testbuildrm" ctx, err := fakeContext("FROM scratch\nADD foo /\nADD foo /", map[string]string{"foo": "bar"}) if err != nil { c.Fatal(err) } defer ctx.Close() { containerCountBefore, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm", "-t", name, ".") if err != nil { c.Fatal("failed to build the image", out) } containerCountAfter, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } if containerCountBefore != containerCountAfter { c.Fatalf("-rm shouldn't have left containers behind") } deleteImages(name) } { containerCountBefore, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name, ".") if err != nil { c.Fatal("failed to build the image", out) } containerCountAfter, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } if containerCountBefore != containerCountAfter { c.Fatalf("--rm shouldn't have left containers behind") } deleteImages(name) } { containerCountBefore, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--rm=false", "-t", name, ".") if err != nil { c.Fatal("failed to build the image", out) } containerCountAfter, err := getContainerCount() if err != nil { c.Fatalf("failed to get the container count: %s", err) } if containerCountBefore == containerCountAfter { c.Fatalf("--rm=false should have left containers behind") } deleteImages(name) } } func (s *DockerSuite) TestBuildWithVolumes(c *check.C) { var ( result map[string]map[string]struct{} name = "testbuildvolumes" emptyMap = make(map[string]struct{}) expected = map[string]map[string]struct{}{ "/test1": emptyMap, "/test2": emptyMap, "/test3": emptyMap, "/test4": emptyMap, "/test5": emptyMap, "/test6": emptyMap, "[/test7": emptyMap, "/test8]": emptyMap, } ) _, err := buildImage(name, `FROM scratch VOLUME /test1 VOLUME /test2 VOLUME /test3 /test4 VOLUME ["/test5", "/test6"] VOLUME [/test7 /test8] `, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Volumes") if err != nil { c.Fatal(err) } err = unmarshalJSON([]byte(res), &result) if err != nil { c.Fatal(err) } equal := reflect.DeepEqual(&result, &expected) if !equal { c.Fatalf("Volumes %s, expected %s", result, expected) } } func (s *DockerSuite) TestBuildMaintainer(c *check.C) { name := "testbuildmaintainer" expected := "dockerio" _, err := buildImage(name, `FROM scratch MAINTAINER dockerio`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Author") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Maintainer %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildUser(c *check.C) { name := "testbuilduser" expected := "dockerio" _, err := buildImage(name, `FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd USER dockerio RUN [ $(whoami) = 'dockerio' ]`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.User") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("User %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildRelativeWorkdir(c *check.C) { name := "testbuildrelativeworkdir" expected := "/test2/test3" _, err := buildImage(name, `FROM busybox RUN [ "$PWD" = '/' ] WORKDIR test1 RUN [ "$PWD" = '/test1' ] WORKDIR /test2 RUN [ "$PWD" = '/test2' ] WORKDIR test3 RUN [ "$PWD" = '/test2/test3' ]`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.WorkingDir") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Workdir %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildWorkdirWithEnvVariables(c *check.C) { name := "testbuildworkdirwithenvvariables" expected := "/test1/test2" _, err := buildImage(name, `FROM busybox ENV DIRPATH /test1 ENV SUBDIRNAME test2 WORKDIR $DIRPATH WORKDIR $SUBDIRNAME/$MISSING_VAR`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.WorkingDir") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Workdir %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildRelativeCopy(c *check.C) { name := "testbuildrelativecopy" dockerfile := ` FROM busybox WORKDIR /test1 WORKDIR test2 RUN [ "$PWD" = '/test1/test2' ] COPY foo ./ RUN [ "$(cat /test1/test2/foo)" = 'hello' ] ADD foo ./bar/baz RUN [ "$(cat /test1/test2/bar/baz)" = 'hello' ] COPY foo ./bar/baz2 RUN [ "$(cat /test1/test2/bar/baz2)" = 'hello' ] WORKDIR .. COPY foo ./ RUN [ "$(cat /test1/foo)" = 'hello' ] COPY foo /test3/ RUN [ "$(cat /test3/foo)" = 'hello' ] WORKDIR /test4 COPY . . RUN [ "$(cat /test4/foo)" = 'hello' ] WORKDIR /test5/test6 COPY foo ../ RUN [ "$(cat /test5/foo)" = 'hello' ] ` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } _, err = buildImageFromContext(name, ctx, false) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEnv(c *check.C) { name := "testbuildenv" expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]" _, err := buildImage(name, `FROM busybox ENV PATH /test:$PATH ENV PORT 2375 RUN [ $(env | grep PORT) = 'PORT=2375' ]`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Env") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Env %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildContextCleanup(c *check.C) { testRequires(c, SameHostDaemon) name := "testbuildcontextcleanup" entries, err := ioutil.ReadDir("/var/lib/docker/tmp") if err != nil { c.Fatalf("failed to list contents of tmp dir: %s", err) } _, err = buildImage(name, `FROM scratch ENTRYPOINT ["/bin/echo"]`, true) if err != nil { c.Fatal(err) } entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp") if err != nil { c.Fatalf("failed to list contents of tmp dir: %s", err) } if err = compareDirectoryEntries(entries, entriesFinal); err != nil { c.Fatalf("context should have been deleted, but wasn't") } } func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) { testRequires(c, SameHostDaemon) name := "testbuildcontextcleanup" entries, err := ioutil.ReadDir("/var/lib/docker/tmp") if err != nil { c.Fatalf("failed to list contents of tmp dir: %s", err) } _, err = buildImage(name, `FROM scratch RUN /non/existing/command`, true) if err == nil { c.Fatalf("expected build to fail, but it didn't") } entriesFinal, err := ioutil.ReadDir("/var/lib/docker/tmp") if err != nil { c.Fatalf("failed to list contents of tmp dir: %s", err) } if err = compareDirectoryEntries(entries, entriesFinal); err != nil { c.Fatalf("context should have been deleted, but wasn't") } } func (s *DockerSuite) TestBuildCmd(c *check.C) { name := "testbuildcmd" expected := "{[/bin/echo Hello World]}" _, err := buildImage(name, `FROM scratch CMD ["/bin/echo", "Hello World"]`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Cmd") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Cmd %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildExpose(c *check.C) { name := "testbuildexpose" expected := "map[2375/tcp:{}]" _, err := buildImage(name, `FROM scratch EXPOSE 2375`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.ExposedPorts") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Exposed ports %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildExposeMorePorts(c *check.C) { // start building docker file with a large number of ports portList := make([]string, 50) line := make([]string, 100) expectedPorts := make([]int, len(portList)*len(line)) for i := 0; i < len(portList); i++ { for j := 0; j < len(line); j++ { p := i*len(line) + j + 1 line[j] = strconv.Itoa(p) expectedPorts[p-1] = p } if i == len(portList)-1 { portList[i] = strings.Join(line, " ") } else { portList[i] = strings.Join(line, " ") + ` \` } } dockerfile := `FROM scratch EXPOSE {{range .}} {{.}} {{end}}` tmpl := template.Must(template.New("dockerfile").Parse(dockerfile)) buf := bytes.NewBuffer(nil) tmpl.Execute(buf, portList) name := "testbuildexpose" _, err := buildImage(name, buf.String(), true) if err != nil { c.Fatal(err) } // check if all the ports are saved inside Config.ExposedPorts res, err := inspectFieldJSON(name, "Config.ExposedPorts") if err != nil { c.Fatal(err) } var exposedPorts map[string]interface{} if err := json.Unmarshal([]byte(res), &exposedPorts); err != nil { c.Fatal(err) } for _, p := range expectedPorts { ep := fmt.Sprintf("%d/tcp", p) if _, ok := exposedPorts[ep]; !ok { c.Errorf("Port(%s) is not exposed", ep) } else { delete(exposedPorts, ep) } } if len(exposedPorts) != 0 { c.Errorf("Unexpected extra exposed ports %v", exposedPorts) } } func (s *DockerSuite) TestBuildExposeOrder(c *check.C) { buildID := func(name, exposed string) string { _, err := buildImage(name, fmt.Sprintf(`FROM scratch EXPOSE %s`, exposed), true) if err != nil { c.Fatal(err) } id, err := inspectField(name, "Id") if err != nil { c.Fatal(err) } return id } id1 := buildID("testbuildexpose1", "80 2375") id2 := buildID("testbuildexpose2", "2375 80") if id1 != id2 { c.Errorf("EXPOSE should invalidate the cache only when ports actually changed") } } func (s *DockerSuite) TestBuildExposeUpperCaseProto(c *check.C) { name := "testbuildexposeuppercaseproto" expected := "map[5678/udp:{}]" _, err := buildImage(name, `FROM scratch EXPOSE 5678/UDP`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.ExposedPorts") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Exposed ports %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildEmptyEntrypointInheritance(c *check.C) { name := "testbuildentrypointinheritance" name2 := "testbuildentrypointinheritance2" _, err := buildImage(name, `FROM busybox ENTRYPOINT ["/bin/echo"]`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Entrypoint") if err != nil { c.Fatal(err) } expected := "{[/bin/echo]}" if res != expected { c.Fatalf("Entrypoint %s, expected %s", res, expected) } _, err = buildImage(name2, fmt.Sprintf(`FROM %s ENTRYPOINT []`, name), true) if err != nil { c.Fatal(err) } res, err = inspectField(name2, "Config.Entrypoint") if err != nil { c.Fatal(err) } expected = "{[]}" if res != expected { c.Fatalf("Entrypoint %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildEmptyEntrypoint(c *check.C) { name := "testbuildentrypoint" expected := "{[]}" _, err := buildImage(name, `FROM busybox ENTRYPOINT []`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Entrypoint") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Entrypoint %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildEntrypoint(c *check.C) { name := "testbuildentrypoint" expected := "{[/bin/echo]}" _, err := buildImage(name, `FROM scratch ENTRYPOINT ["/bin/echo"]`, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Entrypoint") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Entrypoint %s, expected %s", res, expected) } } // #6445 ensure ONBUILD triggers aren't committed to grandchildren func (s *DockerSuite) TestBuildOnBuildLimitedInheritence(c *check.C) { var ( out2, out3 string ) { name1 := "testonbuildtrigger1" dockerfile1 := ` FROM busybox RUN echo "GRANDPARENT" ONBUILD RUN echo "ONBUILD PARENT" ` ctx, err := fakeContext(dockerfile1, nil) if err != nil { c.Fatal(err) } defer ctx.Close() out1, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", name1, ".") if err != nil { c.Fatalf("build failed to complete: %s, %v", out1, err) } } { name2 := "testonbuildtrigger2" dockerfile2 := ` FROM testonbuildtrigger1 ` ctx, err := fakeContext(dockerfile2, nil) if err != nil { c.Fatal(err) } defer ctx.Close() out2, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name2, ".") if err != nil { c.Fatalf("build failed to complete: %s, %v", out2, err) } } { name3 := "testonbuildtrigger3" dockerfile3 := ` FROM testonbuildtrigger2 ` ctx, err := fakeContext(dockerfile3, nil) if err != nil { c.Fatal(err) } defer ctx.Close() out3, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-t", name3, ".") if err != nil { c.Fatalf("build failed to complete: %s, %v", out3, err) } } // ONBUILD should be run in second build. if !strings.Contains(out2, "ONBUILD PARENT") { c.Fatalf("ONBUILD instruction did not run in child of ONBUILD parent") } // ONBUILD should *not* be run in third build. if strings.Contains(out3, "ONBUILD PARENT") { c.Fatalf("ONBUILD instruction ran in grandchild of ONBUILD parent") } } func (s *DockerSuite) TestBuildWithCache(c *check.C) { name := "testbuildwithcache" id1, err := buildImage(name, `FROM scratch MAINTAINER dockerio EXPOSE 5432 ENTRYPOINT ["/bin/echo"]`, true) if err != nil { c.Fatal(err) } id2, err := buildImage(name, `FROM scratch MAINTAINER dockerio EXPOSE 5432 ENTRYPOINT ["/bin/echo"]`, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but hasn't.") } } func (s *DockerSuite) TestBuildWithoutCache(c *check.C) { name := "testbuildwithoutcache" name2 := "testbuildwithoutcache2" id1, err := buildImage(name, `FROM scratch MAINTAINER dockerio EXPOSE 5432 ENTRYPOINT ["/bin/echo"]`, true) if err != nil { c.Fatal(err) } id2, err := buildImage(name2, `FROM scratch MAINTAINER dockerio EXPOSE 5432 ENTRYPOINT ["/bin/echo"]`, false) if err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("The cache should have been invalided but hasn't.") } } func (s *DockerSuite) TestBuildConditionalCache(c *check.C) { name := "testbuildconditionalcache" dockerfile := ` FROM busybox ADD foo /tmp/` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) if err != nil { c.Fatal(err) } defer ctx.Close() id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatalf("Error building #1: %s", err) } if err := ctx.Add("foo", "bye"); err != nil { c.Fatalf("Error modifying foo: %s", err) } id2, err := buildImageFromContext(name, ctx, false) if err != nil { c.Fatalf("Error building #2: %s", err) } if id2 == id1 { c.Fatal("Should not have used the cache") } id3, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatalf("Error building #3: %s", err) } if id3 != id2 { c.Fatal("Should have used the cache") } } func (s *DockerSuite) TestBuildAddLocalFileWithCache(c *check.C) { name := "testbuildaddlocalfilewithcache" name2 := "testbuildaddlocalfilewithcache2" dockerfile := ` FROM busybox MAINTAINER dockerio ADD foo /usr/lib/bla/bar RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but hasn't.") } } func (s *DockerSuite) TestBuildAddMultipleLocalFileWithCache(c *check.C) { name := "testbuildaddmultiplelocalfilewithcache" name2 := "testbuildaddmultiplelocalfilewithcache2" dockerfile := ` FROM busybox MAINTAINER dockerio ADD foo Dockerfile /usr/lib/bla/ RUN [ "$(cat /usr/lib/bla/foo)" = "hello" ]` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but hasn't.") } } func (s *DockerSuite) TestBuildAddLocalFileWithoutCache(c *check.C) { name := "testbuildaddlocalfilewithoutcache" name2 := "testbuildaddlocalfilewithoutcache2" dockerfile := ` FROM busybox MAINTAINER dockerio ADD foo /usr/lib/bla/bar RUN [ "$(cat /usr/lib/bla/bar)" = "hello" ]` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, false) if err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("The cache should have been invalided but hasn't.") } } func (s *DockerSuite) TestBuildCopyDirButNotFile(c *check.C) { name := "testbuildcopydirbutnotfile" name2 := "testbuildcopydirbutnotfile2" dockerfile := ` FROM scratch COPY dir /tmp/` ctx, err := fakeContext(dockerfile, map[string]string{ "dir/foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } // Check that adding file with similar name doesn't mess with cache if err := ctx.Add("dir_file", "hello2"); err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but wasn't") } } func (s *DockerSuite) TestBuildAddCurrentDirWithCache(c *check.C) { name := "testbuildaddcurrentdirwithcache" name2 := name + "2" name3 := name + "3" name4 := name + "4" dockerfile := ` FROM scratch MAINTAINER dockerio ADD . /usr/lib/bla` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } // Check that adding file invalidate cache of "ADD ." if err := ctx.Add("bar", "hello2"); err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, true) if err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("The cache should have been invalided but hasn't.") } // Check that changing file invalidate cache of "ADD ." if err := ctx.Add("foo", "hello1"); err != nil { c.Fatal(err) } id3, err := buildImageFromContext(name3, ctx, true) if err != nil { c.Fatal(err) } if id2 == id3 { c.Fatal("The cache should have been invalided but hasn't.") } // Check that changing file to same content with different mtime does not // invalidate cache of "ADD ." time.Sleep(1 * time.Second) // wait second because of mtime precision if err := ctx.Add("foo", "hello1"); err != nil { c.Fatal(err) } id4, err := buildImageFromContext(name4, ctx, true) if err != nil { c.Fatal(err) } if id3 != id4 { c.Fatal("The cache should have been used but hasn't.") } } func (s *DockerSuite) TestBuildAddCurrentDirWithoutCache(c *check.C) { name := "testbuildaddcurrentdirwithoutcache" name2 := "testbuildaddcurrentdirwithoutcache2" dockerfile := ` FROM scratch MAINTAINER dockerio ADD . /usr/lib/bla` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, false) if err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("The cache should have been invalided but hasn't.") } } func (s *DockerSuite) TestBuildAddRemoteFileWithCache(c *check.C) { name := "testbuildaddremotefilewithcache" server, err := fakeStorage(map[string]string{ "baz": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() id1, err := buildImage(name, fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD %s/baz /usr/lib/baz/quux`, server.URL()), true) if err != nil { c.Fatal(err) } id2, err := buildImage(name, fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD %s/baz /usr/lib/baz/quux`, server.URL()), true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but hasn't.") } } func (s *DockerSuite) TestBuildAddRemoteFileWithoutCache(c *check.C) { name := "testbuildaddremotefilewithoutcache" name2 := "testbuildaddremotefilewithoutcache2" server, err := fakeStorage(map[string]string{ "baz": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() id1, err := buildImage(name, fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD %s/baz /usr/lib/baz/quux`, server.URL()), true) if err != nil { c.Fatal(err) } id2, err := buildImage(name2, fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD %s/baz /usr/lib/baz/quux`, server.URL()), false) if err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("The cache should have been invalided but hasn't.") } } func (s *DockerSuite) TestBuildAddRemoteFileMTime(c *check.C) { name := "testbuildaddremotefilemtime" name2 := name + "2" name3 := name + "3" files := map[string]string{"baz": "hello"} server, err := fakeStorage(files) if err != nil { c.Fatal(err) } defer server.Close() ctx, err := fakeContext(fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD %s/baz /usr/lib/baz/quux`, server.URL()), nil) if err != nil { c.Fatal(err) } defer ctx.Close() id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but wasn't - #1") } // Now create a different server with same contents (causes different mtime) // The cache should still be used // allow some time for clock to pass as mtime precision is only 1s time.Sleep(2 * time.Second) server2, err := fakeStorage(files) if err != nil { c.Fatal(err) } defer server2.Close() ctx2, err := fakeContext(fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD %s/baz /usr/lib/baz/quux`, server2.URL()), nil) if err != nil { c.Fatal(err) } defer ctx2.Close() id3, err := buildImageFromContext(name3, ctx2, true) if err != nil { c.Fatal(err) } if id1 != id3 { c.Fatal("The cache should have been used but wasn't") } } func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithCache(c *check.C) { name := "testbuildaddlocalandremotefilewithcache" server, err := fakeStorage(map[string]string{ "baz": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() ctx, err := fakeContext(fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD foo /usr/lib/bla/bar ADD %s/baz /usr/lib/baz/quux`, server.URL()), map[string]string{ "foo": "hello world", }) if err != nil { c.Fatal(err) } defer ctx.Close() id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } if id1 != id2 { c.Fatal("The cache should have been used but hasn't.") } } func testContextTar(c *check.C, compression archive.Compression) { ctx, err := fakeContext( `FROM busybox ADD foo /foo CMD ["cat", "/foo"]`, map[string]string{ "foo": "bar", }, ) defer ctx.Close() if err != nil { c.Fatal(err) } context, err := archive.Tar(ctx.Dir, compression) if err != nil { c.Fatalf("failed to build context tar: %v", err) } name := "contexttar" buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-") buildCmd.Stdin = context if out, _, err := runCommandWithOutput(buildCmd); err != nil { c.Fatalf("build failed to complete: %v %v", out, err) } } func (s *DockerSuite) TestBuildContextTarGzip(c *check.C) { testContextTar(c, archive.Gzip) } func (s *DockerSuite) TestBuildContextTarNoCompression(c *check.C) { testContextTar(c, archive.Uncompressed) } func (s *DockerSuite) TestBuildNoContext(c *check.C) { buildCmd := exec.Command(dockerBinary, "build", "-t", "nocontext", "-") buildCmd.Stdin = strings.NewReader("FROM busybox\nCMD echo ok\n") if out, _, err := runCommandWithOutput(buildCmd); err != nil { c.Fatalf("build failed to complete: %v %v", out, err) } if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" { c.Fatalf("run produced invalid output: %q, expected %q", out, "ok") } } // TODO: TestCaching func (s *DockerSuite) TestBuildAddLocalAndRemoteFilesWithoutCache(c *check.C) { name := "testbuildaddlocalandremotefilewithoutcache" name2 := "testbuildaddlocalandremotefilewithoutcache2" server, err := fakeStorage(map[string]string{ "baz": "hello", }) if err != nil { c.Fatal(err) } defer server.Close() ctx, err := fakeContext(fmt.Sprintf(`FROM scratch MAINTAINER dockerio ADD foo /usr/lib/bla/bar ADD %s/baz /usr/lib/baz/quux`, server.URL()), map[string]string{ "foo": "hello world", }) if err != nil { c.Fatal(err) } defer ctx.Close() id1, err := buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } id2, err := buildImageFromContext(name2, ctx, false) if err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("The cache should have been invalided but hasn't.") } } func (s *DockerSuite) TestBuildWithVolumeOwnership(c *check.C) { name := "testbuildimg" _, err := buildImage(name, `FROM busybox:latest RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test VOLUME /test`, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test") if expected := "drw-------"; !strings.Contains(out, expected) { c.Fatalf("expected %s received %s", expected, out) } if expected := "daemon daemon"; !strings.Contains(out, expected) { c.Fatalf("expected %s received %s", expected, out) } } // testing #1405 - config.Cmd does not get cleaned up if // utilizing cache func (s *DockerSuite) TestBuildEntrypointRunCleanup(c *check.C) { name := "testbuildcmdcleanup" if _, err := buildImage(name, `FROM busybox RUN echo "hello"`, true); err != nil { c.Fatal(err) } ctx, err := fakeContext(`FROM busybox RUN echo "hello" ADD foo /foo ENTRYPOINT ["/bin/echo"]`, map[string]string{ "foo": "hello", }) defer ctx.Close() if err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Cmd") if err != nil { c.Fatal(err) } // Cmd must be cleaned up if res != "" { c.Fatalf("Cmd %s, expected nil", res) } } func (s *DockerSuite) TestBuildForbiddenContextPath(c *check.C) { name := "testbuildforbidpath" ctx, err := fakeContext(`FROM scratch ADD ../../ test/ `, map[string]string{ "test.txt": "test1", "other.txt": "other", }) defer ctx.Close() if err != nil { c.Fatal(err) } expected := "Forbidden path outside the build context: ../../ " if _, err := buildImageFromContext(name, ctx, true); err == nil || !strings.Contains(err.Error(), expected) { c.Fatalf("Wrong error: (should contain \"%s\") got:\n%v", expected, err) } } func (s *DockerSuite) TestBuildAddFileNotFound(c *check.C) { name := "testbuildaddnotfound" ctx, err := fakeContext(`FROM scratch ADD foo /usr/local/bar`, map[string]string{"bar": "hello"}) defer ctx.Close() if err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { if !strings.Contains(err.Error(), "foo: no such file or directory") { c.Fatalf("Wrong error %v, must be about missing foo file or directory", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildInheritance(c *check.C) { name := "testbuildinheritance" _, err := buildImage(name, `FROM scratch EXPOSE 2375`, true) if err != nil { c.Fatal(err) } ports1, err := inspectField(name, "Config.ExposedPorts") if err != nil { c.Fatal(err) } _, err = buildImage(name, fmt.Sprintf(`FROM %s ENTRYPOINT ["/bin/echo"]`, name), true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Entrypoint") if err != nil { c.Fatal(err) } if expected := "{[/bin/echo]}"; res != expected { c.Fatalf("Entrypoint %s, expected %s", res, expected) } ports2, err := inspectField(name, "Config.ExposedPorts") if err != nil { c.Fatal(err) } if ports1 != ports2 { c.Fatalf("Ports must be same: %s != %s", ports1, ports2) } } func (s *DockerSuite) TestBuildFails(c *check.C) { name := "testbuildfails" _, err := buildImage(name, `FROM busybox RUN sh -c "exit 23"`, true) if err != nil { if !strings.Contains(err.Error(), "returned a non-zero code: 23") { c.Fatalf("Wrong error %v, must be about non-zero code 23", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildFailsDockerfileEmpty(c *check.C) { name := "testbuildfails" _, err := buildImage(name, ``, true) if err != nil { if !strings.Contains(err.Error(), "The Dockerfile (Dockerfile) cannot be empty") { c.Fatalf("Wrong error %v, must be about empty Dockerfile", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildOnBuild(c *check.C) { name := "testbuildonbuild" _, err := buildImage(name, `FROM busybox ONBUILD RUN touch foobar`, true) if err != nil { c.Fatal(err) } _, err = buildImage(name, fmt.Sprintf(`FROM %s RUN [ -f foobar ]`, name), true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildOnBuildForbiddenChained(c *check.C) { name := "testbuildonbuildforbiddenchained" _, err := buildImage(name, `FROM busybox ONBUILD ONBUILD RUN touch foobar`, true) if err != nil { if !strings.Contains(err.Error(), "Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") { c.Fatalf("Wrong error %v, must be about chaining ONBUILD", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildOnBuildForbiddenFrom(c *check.C) { name := "testbuildonbuildforbiddenfrom" _, err := buildImage(name, `FROM busybox ONBUILD FROM scratch`, true) if err != nil { if !strings.Contains(err.Error(), "FROM isn't allowed as an ONBUILD trigger") { c.Fatalf("Wrong error %v, must be about FROM forbidden", err) } } else { c.Fatal("Error must not be nil") } } func (s *DockerSuite) TestBuildOnBuildForbiddenMaintainer(c *check.C) { name := "testbuildonbuildforbiddenmaintainer" _, err := buildImage(name, `FROM busybox ONBUILD MAINTAINER docker.io`, true) if err != nil { if !strings.Contains(err.Error(), "MAINTAINER isn't allowed as an ONBUILD trigger") { c.Fatalf("Wrong error %v, must be about MAINTAINER forbidden", err) } } else { c.Fatal("Error must not be nil") } } // gh #2446 func (s *DockerSuite) TestBuildAddToSymlinkDest(c *check.C) { name := "testbuildaddtosymlinkdest" ctx, err := fakeContext(`FROM busybox RUN mkdir /foo RUN ln -s /foo /bar ADD foo /bar/ RUN [ -f /bar/foo ] RUN [ -f /foo/foo ]`, map[string]string{ "foo": "hello", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEscapeWhitespace(c *check.C) { name := "testbuildescaping" _, err := buildImage(name, ` FROM busybox MAINTAINER "Docker \ IO " `, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Author") if err != nil { c.Fatal(err) } if res != "\"Docker IO \"" { c.Fatalf("Parsed string did not match the escaped string. Got: %q", res) } } func (s *DockerSuite) TestBuildVerifyIntString(c *check.C) { // Verify that strings that look like ints are still passed as strings name := "testbuildstringing" _, err := buildImage(name, ` FROM busybox MAINTAINER 123 `, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "inspect", name) if !strings.Contains(out, "\"123\"") { c.Fatalf("Output does not contain the int as a string:\n%s", out) } } func (s *DockerSuite) TestBuildDockerignore(c *check.C) { name := "testbuilddockerignore" dockerfile := ` FROM busybox ADD . /bla RUN [[ -f /bla/src/x.go ]] RUN [[ -f /bla/Makefile ]] RUN [[ ! -e /bla/src/_vendor ]] RUN [[ ! -e /bla/.gitignore ]] RUN [[ ! -e /bla/README.md ]] RUN [[ ! -e /bla/dir/foo ]] RUN [[ ! -e /bla/foo ]] RUN [[ ! -e /bla/.git ]]` ctx, err := fakeContext(dockerfile, map[string]string{ "Makefile": "all:", ".git/HEAD": "ref: foo", "src/x.go": "package main", "src/_vendor/v.go": "package main", "dir/foo": "", ".gitignore": "", "README.md": "readme", ".dockerignore": ` .git pkg .gitignore src/_vendor *.md dir`, }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildDockerignoreCleanPaths(c *check.C) { name := "testbuilddockerignorecleanpaths" dockerfile := ` FROM busybox ADD . /tmp/ RUN (! ls /tmp/foo) && (! ls /tmp/foo2) && (! ls /tmp/dir1/foo)` ctx, err := fakeContext(dockerfile, map[string]string{ "foo": "foo", "foo2": "foo2", "dir1/foo": "foo in dir1", ".dockerignore": "./foo\ndir1//foo\n./dir1/../foo2", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildDockerignoreExceptions(c *check.C) { name := "testbuilddockerignoreexceptions" dockerfile := ` FROM busybox ADD . /bla RUN [[ -f /bla/src/x.go ]] RUN [[ -f /bla/Makefile ]] RUN [[ ! -e /bla/src/_vendor ]] RUN [[ ! -e /bla/.gitignore ]] RUN [[ ! -e /bla/README.md ]] RUN [[ -e /bla/dir/dir/foo ]] RUN [[ ! -e /bla/dir/foo1 ]] RUN [[ -f /bla/dir/e ]] RUN [[ -f /bla/dir/e-dir/foo ]] RUN [[ ! -e /bla/foo ]] RUN [[ ! -e /bla/.git ]]` ctx, err := fakeContext(dockerfile, map[string]string{ "Makefile": "all:", ".git/HEAD": "ref: foo", "src/x.go": "package main", "src/_vendor/v.go": "package main", "dir/foo": "", "dir/foo1": "", "dir/dir/f1": "", "dir/dir/foo": "", "dir/e": "", "dir/e-dir/foo": "", ".gitignore": "", "README.md": "readme", ".dockerignore": ` .git pkg .gitignore src/_vendor *.md dir !dir/e* !dir/dir/foo`, }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildDockerignoringDockerfile(c *check.C) { name := "testbuilddockerignoredockerfile" dockerfile := ` FROM busybox ADD . /tmp/ RUN ! ls /tmp/Dockerfile RUN ls /tmp/.dockerignore` ctx, err := fakeContext(dockerfile, map[string]string{ "Dockerfile": dockerfile, ".dockerignore": "Dockerfile\n", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't ignore Dockerfile correctly:%s", err) } // now try it with ./Dockerfile ctx.Add(".dockerignore", "./Dockerfile\n") if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't ignore ./Dockerfile correctly:%s", err) } } func (s *DockerSuite) TestBuildDockerignoringRenamedDockerfile(c *check.C) { name := "testbuilddockerignoredockerfile" dockerfile := ` FROM busybox ADD . /tmp/ RUN ls /tmp/Dockerfile RUN ! ls /tmp/MyDockerfile RUN ls /tmp/.dockerignore` ctx, err := fakeContext(dockerfile, map[string]string{ "Dockerfile": "Should not use me", "MyDockerfile": dockerfile, ".dockerignore": "MyDockerfile\n", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't ignore MyDockerfile correctly:%s", err) } // now try it with ./MyDockerfile ctx.Add(".dockerignore", "./MyDockerfile\n") if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't ignore ./MyDockerfile correctly:%s", err) } } func (s *DockerSuite) TestBuildDockerignoringDockerignore(c *check.C) { name := "testbuilddockerignoredockerignore" dockerfile := ` FROM busybox ADD . /tmp/ RUN ! ls /tmp/.dockerignore RUN ls /tmp/Dockerfile` ctx, err := fakeContext(dockerfile, map[string]string{ "Dockerfile": dockerfile, ".dockerignore": ".dockerignore\n", }) defer ctx.Close() if err != nil { c.Fatal(err) } if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't ignore .dockerignore correctly:%s", err) } } func (s *DockerSuite) TestBuildDockerignoreTouchDockerfile(c *check.C) { var id1 string var id2 string name := "testbuilddockerignoretouchdockerfile" dockerfile := ` FROM busybox ADD . /tmp/` ctx, err := fakeContext(dockerfile, map[string]string{ "Dockerfile": dockerfile, ".dockerignore": "Dockerfile\n", }) defer ctx.Close() if err != nil { c.Fatal(err) } if id1, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't build it correctly:%s", err) } if id2, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't build it correctly:%s", err) } if id1 != id2 { c.Fatalf("Didn't use the cache - 1") } // Now make sure touching Dockerfile doesn't invalidate the cache if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil { c.Fatalf("Didn't add Dockerfile: %s", err) } if id2, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't build it correctly:%s", err) } if id1 != id2 { c.Fatalf("Didn't use the cache - 2") } // One more time but just 'touch' it instead of changing the content if err = ctx.Add("Dockerfile", dockerfile+"\n# hi"); err != nil { c.Fatalf("Didn't add Dockerfile: %s", err) } if id2, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("Didn't build it correctly:%s", err) } if id1 != id2 { c.Fatalf("Didn't use the cache - 3") } } func (s *DockerSuite) TestBuildDockerignoringWholeDir(c *check.C) { name := "testbuilddockerignorewholedir" dockerfile := ` FROM busybox COPY . / RUN [[ ! -e /.gitignore ]] RUN [[ -f /Makefile ]]` ctx, err := fakeContext(dockerfile, map[string]string{ "Dockerfile": "FROM scratch", "Makefile": "all:", ".gitignore": "", ".dockerignore": ".*\n", }) c.Assert(err, check.IsNil) defer ctx.Close() if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } c.Assert(ctx.Add(".dockerfile", "*"), check.IsNil) if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } c.Assert(ctx.Add(".dockerfile", "."), check.IsNil) if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } c.Assert(ctx.Add(".dockerfile", "?"), check.IsNil) if _, err = buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) { name := "testbuilddockerignorewholedir" dockerfile := ` FROM busybox COPY . / RUN [[ ! -e /.gitignore ]] RUN [[ -f /Makefile ]]` ctx, err := fakeContext(dockerfile, map[string]string{ "Dockerfile": "FROM scratch", "Makefile": "all:", ".gitignore": "", ".dockerignore": "!\n", }) c.Assert(err, check.IsNil) defer ctx.Close() if _, err = buildImageFromContext(name, ctx, true); err == nil { c.Fatalf("Build was supposed to fail but didn't") } if err.Error() != "failed to build the image: Error checking context: 'Illegal exclusion pattern: !'.\n" { c.Fatalf("Incorrect output, got:%q", err.Error()) } } func (s *DockerSuite) TestBuildLineBreak(c *check.C) { name := "testbuildlinebreak" _, err := buildImage(name, `FROM busybox RUN sh -c 'echo root:testpass \ > /tmp/passwd' RUN mkdir -p /var/run/sshd RUN [ "$(cat /tmp/passwd)" = "root:testpass" ] RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEOLInLine(c *check.C) { name := "testbuildeolinline" _, err := buildImage(name, `FROM busybox RUN sh -c 'echo root:testpass > /tmp/passwd' RUN echo "foo \n bar"; echo "baz" RUN mkdir -p /var/run/sshd RUN [ "$(cat /tmp/passwd)" = "root:testpass" ] RUN [ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]`, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildCommentsShebangs(c *check.C) { name := "testbuildcomments" _, err := buildImage(name, `FROM busybox # This is an ordinary comment. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh RUN [ ! -x /hello.sh ] # comment with line break \ RUN chmod +x /hello.sh RUN [ -x /hello.sh ] RUN [ "$(cat /hello.sh)" = $'#!/bin/sh\necho hello world' ] RUN [ "$(/hello.sh)" = "hello world" ]`, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildUsersAndGroups(c *check.C) { name := "testbuildusers" _, err := buildImage(name, `FROM busybox # Make sure our defaults work RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)" = '0:0/root:root' ] # TODO decide if "args.user = strconv.Itoa(syscall.Getuid())" is acceptable behavior for changeUser in sysvinit instead of "return nil" when "USER" isn't specified (so that we get the proper group list even if that is the empty list, even in the default case of not supplying an explicit USER to run as, which implies USER 0) USER root RUN [ "$(id -G):$(id -Gn)" = '0 10:root wheel' ] # Setup dockerio user and group RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group # Make sure we can switch to our user and all the information is exactly as we expect it to be USER dockerio RUN id -G RUN id -Gn RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ] # Switch back to root and double check that worked exactly as we might expect it to USER root RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '0:0/root:root/0 10:root wheel' ] # Add a "supplementary" group for our dockerio user RUN echo 'supplementary:x:1002:dockerio' >> /etc/group # ... and then go verify that we get it like we expect USER dockerio RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ] USER 1001 RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001 1002:dockerio supplementary' ] # super test the new "user:group" syntax USER dockerio:dockerio RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER 1001:dockerio RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER dockerio:1001 RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER 1001:1001 RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1001/dockerio:dockerio/1001:dockerio' ] USER dockerio:supplementary RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ] USER dockerio:1002 RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ] USER 1001:supplementary RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ] USER 1001:1002 RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1001:1002/dockerio:supplementary/1002:supplementary' ] # make sure unknown uid/gid still works properly USER 1042:1043 RUN [ "$(id -u):$(id -g)/$(id -un):$(id -gn)/$(id -G):$(id -Gn)" = '1042:1043/1042:1043/1043:1043' ]`, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEnvUsage(c *check.C) { name := "testbuildenvusage" dockerfile := `FROM busybox ENV HOME /root ENV PATH $HOME/bin:$PATH ENV PATH /tmp:$PATH RUN [ "$PATH" = "/tmp:$HOME/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ] ENV FOO /foo/baz ENV BAR /bar ENV BAZ $BAR ENV FOOPATH $PATH:$FOO RUN [ "$BAR" = "$BAZ" ] RUN [ "$FOOPATH" = "$PATH:/foo/baz" ] ENV FROM hello/docker/world ENV TO /docker/world/hello ADD $FROM $TO RUN [ "$(cat $TO)" = "hello" ] ENV abc=def ENV ghi=$abc RUN [ "$ghi" = "def" ] ` ctx, err := fakeContext(dockerfile, map[string]string{ "hello/docker/world": "hello", }) if err != nil { c.Fatal(err) } defer ctx.Close() _, err = buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildEnvUsage2(c *check.C) { name := "testbuildenvusage2" dockerfile := `FROM busybox ENV abc=def RUN [ "$abc" = "def" ] ENV def="hello world" RUN [ "$def" = "hello world" ] ENV def=hello\ world RUN [ "$def" = "hello world" ] ENV v1=abc v2="hi there" RUN [ "$v1" = "abc" ] RUN [ "$v2" = "hi there" ] ENV v3='boogie nights' v4="with'quotes too" RUN [ "$v3" = "boogie nights" ] RUN [ "$v4" = "with'quotes too" ] ENV abc=zzz FROM=hello/docker/world ENV abc=zzz TO=/docker/world/hello ADD $FROM $TO RUN [ "$(cat $TO)" = "hello" ] ENV abc "zzz" RUN [ $abc = "zzz" ] ENV abc 'yyy' RUN [ $abc = 'yyy' ] ENV abc= RUN [ "$abc" = "" ] # use grep to make sure if the builder substitutes \$foo by mistake # we don't get a false positive ENV abc=\$foo RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo) ENV abc \$foo RUN [ "$abc" = "\$foo" ] && (echo "$abc" | grep foo) ENV abc=\'foo\' RUN [ "$abc" = "'foo'" ] ENV abc=\"foo\" RUN [ "$abc" = "\"foo\"" ] ENV abc "foo" RUN [ "$abc" = "foo" ] ENV abc 'foo' RUN [ "$abc" = 'foo' ] ENV abc \'foo\' RUN [ "$abc" = "'foo'" ] ENV abc \"foo\" RUN [ "$abc" = '"foo"' ] ENV abc=ABC RUN [ "$abc" = "ABC" ] ENV def=${abc:-DEF} RUN [ "$def" = "ABC" ] ENV def=${ccc:-DEF} RUN [ "$def" = "DEF" ] ENV def=${ccc:-${def}xx} RUN [ "$def" = "DEFxx" ] ENV def=${def:+ALT} RUN [ "$def" = "ALT" ] ENV def=${def:+${abc}:} RUN [ "$def" = "ABC:" ] ENV def=${ccc:-\$abc:} RUN [ "$def" = '$abc:' ] ENV def=${ccc:-\${abc}:} RUN [ "$def" = '${abc:}' ] ENV mypath=${mypath:+$mypath:}/home RUN [ "$mypath" = '/home' ] ENV mypath=${mypath:+$mypath:}/away RUN [ "$mypath" = '/home:/away' ] ENV e1=bar ENV e2=$e1 ENV e3=$e11 ENV e4=\$e1 ENV e5=\$e11 RUN [ "$e0,$e1,$e2,$e3,$e4,$e5" = ',bar,bar,,$e1,$e11' ] ENV ee1 bar ENV ee2 $ee1 ENV ee3 $ee11 ENV ee4 \$ee1 ENV ee5 \$ee11 RUN [ "$ee1,$ee2,$ee3,$ee4,$ee5" = 'bar,bar,,$ee1,$ee11' ] ENV eee1="foo" ENV eee2='foo' ENV eee3 "foo" ENV eee4 'foo' RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ] ` ctx, err := fakeContext(dockerfile, map[string]string{ "hello/docker/world": "hello", }) if err != nil { c.Fatal(err) } defer ctx.Close() _, err = buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddScript(c *check.C) { name := "testbuildaddscript" dockerfile := ` FROM busybox ADD test /test RUN ["chmod","+x","/test"] RUN ["/test"] RUN [ "$(cat /testfile)" = 'test!' ]` ctx, err := fakeContext(dockerfile, map[string]string{ "test": "#!/bin/sh\necho 'test!' > /testfile", }) if err != nil { c.Fatal(err) } defer ctx.Close() _, err = buildImageFromContext(name, ctx, true) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildAddTar(c *check.C) { name := "testbuildaddtar" ctx := func() *FakeContext { dockerfile := ` FROM busybox ADD test.tar / RUN cat /test/foo | grep Hi ADD test.tar /test.tar RUN cat /test.tar/test/foo | grep Hi ADD test.tar /unlikely-to-exist RUN cat /unlikely-to-exist/test/foo | grep Hi ADD test.tar /unlikely-to-exist-trailing-slash/ RUN cat /unlikely-to-exist-trailing-slash/test/foo | grep Hi RUN mkdir /existing-directory ADD test.tar /existing-directory RUN cat /existing-directory/test/foo | grep Hi ADD test.tar /existing-directory-trailing-slash/ RUN cat /existing-directory-trailing-slash/test/foo | grep Hi` tmpDir, err := ioutil.TempDir("", "fake-context") testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) } defer testTar.Close() tw := tar.NewWriter(testTar) if err := tw.WriteHeader(&tar.Header{ Name: "test/foo", Size: 2, }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write([]byte("Hi")); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil { c.Fatalf("failed to open destination dockerfile: %v", err) } return fakeContextFromDir(tmpDir) }() defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("build failed to complete for TestBuildAddTar: %v", err) } } func (s *DockerSuite) TestBuildAddTarXz(c *check.C) { name := "testbuildaddtarxz" ctx := func() *FakeContext { dockerfile := ` FROM busybox ADD test.tar.xz / RUN cat /test/foo | grep Hi` tmpDir, err := ioutil.TempDir("", "fake-context") testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) } defer testTar.Close() tw := tar.NewWriter(testTar) if err := tw.WriteHeader(&tar.Header{ Name: "test/foo", Size: 2, }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write([]byte("Hi")); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } xzCompressCmd := exec.Command("xz", "-k", "test.tar") xzCompressCmd.Dir = tmpDir out, _, err := runCommandWithOutput(xzCompressCmd) if err != nil { c.Fatal(err, out) } if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil { c.Fatalf("failed to open destination dockerfile: %v", err) } return fakeContextFromDir(tmpDir) }() defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err) } } func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) { name := "testbuildaddtarxzgz" ctx := func() *FakeContext { dockerfile := ` FROM busybox ADD test.tar.xz.gz / RUN ls /test.tar.xz.gz` tmpDir, err := ioutil.TempDir("", "fake-context") testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) } defer testTar.Close() tw := tar.NewWriter(testTar) if err := tw.WriteHeader(&tar.Header{ Name: "test/foo", Size: 2, }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write([]byte("Hi")); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } xzCompressCmd := exec.Command("xz", "-k", "test.tar") xzCompressCmd.Dir = tmpDir out, _, err := runCommandWithOutput(xzCompressCmd) if err != nil { c.Fatal(err, out) } gzipCompressCmd := exec.Command("gzip", "test.tar.xz") gzipCompressCmd.Dir = tmpDir out, _, err = runCommandWithOutput(gzipCompressCmd) if err != nil { c.Fatal(err, out) } if err := ioutil.WriteFile(filepath.Join(tmpDir, "Dockerfile"), []byte(dockerfile), 0644); err != nil { c.Fatalf("failed to open destination dockerfile: %v", err) } return fakeContextFromDir(tmpDir) }() defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatalf("build failed to complete for TestBuildAddTarXz: %v", err) } } func (s *DockerSuite) TestBuildFromGIT(c *check.C) { name := "testbuildfromgit" git, err := fakeGIT("repo", map[string]string{ "Dockerfile": `FROM busybox ADD first /first RUN [ -f /first ] MAINTAINER docker`, "first": "test git data", }, true) if err != nil { c.Fatal(err) } defer git.Close() _, err = buildImageFromPath(name, git.RepoURL, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Author") if err != nil { c.Fatal(err) } if res != "docker" { c.Fatalf("Maintainer should be docker, got %s", res) } } func (s *DockerSuite) TestBuildFromGITWithContext(c *check.C) { name := "testbuildfromgit" git, err := fakeGIT("repo", map[string]string{ "docker/Dockerfile": `FROM busybox ADD first /first RUN [ -f /first ] MAINTAINER docker`, "docker/first": "test git data", }, true) if err != nil { c.Fatal(err) } defer git.Close() u := fmt.Sprintf("%s#master:docker", git.RepoURL) _, err = buildImageFromPath(name, u, true) if err != nil { c.Fatal(err) } res, err := inspectField(name, "Author") if err != nil { c.Fatal(err) } if res != "docker" { c.Fatalf("Maintainer should be docker, got %s", res) } } func (s *DockerSuite) TestBuildFromRemoteTarball(c *check.C) { name := "testbuildfromremotetarball" buffer := new(bytes.Buffer) tw := tar.NewWriter(buffer) defer tw.Close() dockerfile := []byte(`FROM busybox MAINTAINER docker`) if err := tw.WriteHeader(&tar.Header{ Name: "Dockerfile", Size: int64(len(dockerfile)), }); err != nil { c.Fatalf("failed to write tar file header: %v", err) } if _, err := tw.Write(dockerfile); err != nil { c.Fatalf("failed to write tar file content: %v", err) } if err := tw.Close(); err != nil { c.Fatalf("failed to close tar archive: %v", err) } server, err := fakeBinaryStorage(map[string]*bytes.Buffer{ "testT.tar": buffer, }) c.Assert(err, check.IsNil) defer server.Close() _, err = buildImageFromPath(name, server.URL()+"/testT.tar", true) c.Assert(err, check.IsNil) res, err := inspectField(name, "Author") c.Assert(err, check.IsNil) if res != "docker" { c.Fatalf("Maintainer should be docker, got %s", res) } } func (s *DockerSuite) TestBuildCleanupCmdOnEntrypoint(c *check.C) { name := "testbuildcmdcleanuponentrypoint" if _, err := buildImage(name, `FROM scratch CMD ["test"] ENTRYPOINT ["echo"]`, true); err != nil { c.Fatal(err) } if _, err := buildImage(name, fmt.Sprintf(`FROM %s ENTRYPOINT ["cat"]`, name), true); err != nil { c.Fatal(err) } res, err := inspectField(name, "Config.Cmd") if err != nil { c.Fatal(err) } if res != "" { c.Fatalf("Cmd %s, expected nil", res) } res, err = inspectField(name, "Config.Entrypoint") if err != nil { c.Fatal(err) } if expected := "{[cat]}"; res != expected { c.Fatalf("Entrypoint %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildClearCmd(c *check.C) { name := "testbuildclearcmd" _, err := buildImage(name, `From scratch ENTRYPOINT ["/bin/bash"] CMD []`, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Cmd") if err != nil { c.Fatal(err) } if res != "[]" { c.Fatalf("Cmd %s, expected %s", res, "[]") } } func (s *DockerSuite) TestBuildEmptyCmd(c *check.C) { name := "testbuildemptycmd" if _, err := buildImage(name, "FROM scratch\nMAINTAINER quux\n", true); err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Cmd") if err != nil { c.Fatal(err) } if res != "null" { c.Fatalf("Cmd %s, expected %s", res, "null") } } func (s *DockerSuite) TestBuildOnBuildOutput(c *check.C) { name := "testbuildonbuildparent" if _, err := buildImage(name, "FROM busybox\nONBUILD RUN echo foo\n", true); err != nil { c.Fatal(err) } _, out, err := buildImageWithOut(name, "FROM "+name+"\nMAINTAINER quux\n", true) if err != nil { c.Fatal(err) } if !strings.Contains(out, "Trigger 0, RUN echo foo") { c.Fatal("failed to find the ONBUILD output", out) } } func (s *DockerSuite) TestBuildInvalidTag(c *check.C) { name := "abcd:" + stringutils.GenerateRandomAlphaOnlyString(200) _, out, err := buildImageWithOut(name, "FROM scratch\nMAINTAINER quux\n", true) // if the error doesnt check for illegal tag name, or the image is built // then this should fail if !strings.Contains(out, "Illegal tag name") || strings.Contains(out, "Sending build context to Docker daemon") { c.Fatalf("failed to stop before building. Error: %s, Output: %s", err, out) } } func (s *DockerSuite) TestBuildCmdShDashC(c *check.C) { name := "testbuildcmdshc" if _, err := buildImage(name, "FROM busybox\nCMD echo cmd\n", true); err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Cmd") if err != nil { c.Fatal(err, res) } expected := `["/bin/sh","-c","echo cmd"]` if res != expected { c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res) } } func (s *DockerSuite) TestBuildCmdSpaces(c *check.C) { // Test to make sure that when we strcat arrays we take into account // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't // look the same name := "testbuildcmdspaces" var id1 string var id2 string var err error if id1, err = buildImage(name, "FROM busybox\nCMD [\"echo hi\"]\n", true); err != nil { c.Fatal(err) } if id2, err = buildImage(name, "FROM busybox\nCMD [\"echo\", \"hi\"]\n", true); err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("Should not have resulted in the same CMD") } // Now do the same with ENTRYPOINT if id1, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo hi\"]\n", true); err != nil { c.Fatal(err) } if id2, err = buildImage(name, "FROM busybox\nENTRYPOINT [\"echo\", \"hi\"]\n", true); err != nil { c.Fatal(err) } if id1 == id2 { c.Fatal("Should not have resulted in the same ENTRYPOINT") } } func (s *DockerSuite) TestBuildCmdJSONNoShDashC(c *check.C) { name := "testbuildcmdjson" if _, err := buildImage(name, "FROM busybox\nCMD [\"echo\", \"cmd\"]", true); err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Cmd") if err != nil { c.Fatal(err, res) } expected := `["echo","cmd"]` if res != expected { c.Fatalf("Expected value %s not in Config.Cmd: %s", expected, res) } } func (s *DockerSuite) TestBuildErrorInvalidInstruction(c *check.C) { name := "testbuildignoreinvalidinstruction" out, _, err := buildImageWithOut(name, "FROM busybox\nfoo bar", true) if err == nil { c.Fatalf("Should have failed: %s", out) } } func (s *DockerSuite) TestBuildEntrypointInheritance(c *check.C) { if _, err := buildImage("parent", ` FROM busybox ENTRYPOINT exit 130 `, true); err != nil { c.Fatal(err) } if _, status, _ := dockerCmdWithError(c, "run", "parent"); status != 130 { c.Fatalf("expected exit code 130 but received %d", status) } if _, err := buildImage("child", ` FROM parent ENTRYPOINT exit 5 `, true); err != nil { c.Fatal(err) } if _, status, _ := dockerCmdWithError(c, "run", "child"); status != 5 { c.Fatalf("expected exit code 5 but received %d", status) } } func (s *DockerSuite) TestBuildEntrypointInheritanceInspect(c *check.C) { var ( name = "testbuildepinherit" name2 = "testbuildepinherit2" expected = `["/bin/sh","-c","echo quux"]` ) if _, err := buildImage(name, "FROM busybox\nENTRYPOINT /foo/bar", true); err != nil { c.Fatal(err) } if _, err := buildImage(name2, fmt.Sprintf("FROM %s\nENTRYPOINT echo quux", name), true); err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name2, "Config.Entrypoint") if err != nil { c.Fatal(err, res) } if res != expected { c.Fatalf("Expected value %s not in Config.Entrypoint: %s", expected, res) } out, _ := dockerCmd(c, "run", "-t", name2) expected = "quux" if strings.TrimSpace(out) != expected { c.Fatalf("Expected output is %s, got %s", expected, out) } } func (s *DockerSuite) TestBuildRunShEntrypoint(c *check.C) { name := "testbuildentrypoint" _, err := buildImage(name, `FROM busybox ENTRYPOINT /bin/echo`, true) if err != nil { c.Fatal(err) } dockerCmd(c, "run", "--rm", name) } func (s *DockerSuite) TestBuildExoticShellInterpolation(c *check.C) { name := "testbuildexoticshellinterpolation" _, err := buildImage(name, ` FROM busybox ENV SOME_VAR a.b.c RUN [ "$SOME_VAR" = 'a.b.c' ] RUN [ "${SOME_VAR}" = 'a.b.c' ] RUN [ "${SOME_VAR%.*}" = 'a.b' ] RUN [ "${SOME_VAR%%.*}" = 'a' ] RUN [ "${SOME_VAR#*.}" = 'b.c' ] RUN [ "${SOME_VAR##*.}" = 'c' ] RUN [ "${SOME_VAR/c/d}" = 'a.b.d' ] RUN [ "${#SOME_VAR}" = '5' ] RUN [ "${SOME_UNSET_VAR:-$SOME_VAR}" = 'a.b.c' ] RUN [ "${SOME_VAR:+Version: ${SOME_VAR}}" = 'Version: a.b.c' ] RUN [ "${SOME_UNSET_VAR:+${SOME_VAR}}" = '' ] RUN [ "${SOME_UNSET_VAR:-${SOME_VAR:-d.e.f}}" = 'a.b.c' ] `, false) if err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildVerifySingleQuoteFails(c *check.C) { // This testcase is supposed to generate an error because the // JSON array we're passing in on the CMD uses single quotes instead // of double quotes (per the JSON spec). This means we interpret it // as a "string" insead of "JSON array" and pass it on to "sh -c" and // it should barf on it. name := "testbuildsinglequotefails" if _, err := buildImage(name, `FROM busybox CMD [ '/bin/sh', '-c', 'echo hi' ]`, true); err != nil { c.Fatal(err) } if _, _, err := dockerCmdWithError(c, "run", "--rm", name); err == nil { c.Fatal("The image was not supposed to be able to run") } } func (s *DockerSuite) TestBuildVerboseOut(c *check.C) { name := "testbuildverboseout" _, out, err := buildImageWithOut(name, `FROM busybox RUN echo 123`, false) if err != nil { c.Fatal(err) } if !strings.Contains(out, "\n123\n") { c.Fatalf("Output should contain %q: %q", "123", out) } } func (s *DockerSuite) TestBuildWithTabs(c *check.C) { name := "testbuildwithtabs" _, err := buildImage(name, "FROM busybox\nRUN echo\tone\t\ttwo", true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "ContainerConfig.Cmd") if err != nil { c.Fatal(err) } expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]` expected2 := `["/bin/sh","-c","echo\u0009one\u0009\u0009two"]` // syntactically equivalent, and what Go 1.3 generates if res != expected1 && res != expected2 { c.Fatalf("Missing tabs.\nGot: %s\nExp: %s or %s", res, expected1, expected2) } } func (s *DockerSuite) TestBuildLabels(c *check.C) { name := "testbuildlabel" expected := `{"License":"GPL","Vendor":"Acme"}` _, err := buildImage(name, `FROM busybox LABEL Vendor=Acme LABEL License GPL`, true) if err != nil { c.Fatal(err) } res, err := inspectFieldJSON(name, "Config.Labels") if err != nil { c.Fatal(err) } if res != expected { c.Fatalf("Labels %s, expected %s", res, expected) } } func (s *DockerSuite) TestBuildLabelsCache(c *check.C) { name := "testbuildlabelcache" id1, err := buildImage(name, `FROM busybox LABEL Vendor=Acme`, false) if err != nil { c.Fatalf("Build 1 should have worked: %v", err) } id2, err := buildImage(name, `FROM busybox LABEL Vendor=Acme`, true) if err != nil || id1 != id2 { c.Fatalf("Build 2 should have worked & used cache(%s,%s): %v", id1, id2, err) } id2, err = buildImage(name, `FROM busybox LABEL Vendor=Acme1`, true) if err != nil || id1 == id2 { c.Fatalf("Build 3 should have worked & NOT used cache(%s,%s): %v", id1, id2, err) } id2, err = buildImage(name, `FROM busybox LABEL Vendor Acme`, true) // Note: " " and "=" should be same if err != nil || id1 != id2 { c.Fatalf("Build 4 should have worked & used cache(%s,%s): %v", id1, id2, err) } // Now make sure the cache isn't used by mistake id1, err = buildImage(name, `FROM busybox LABEL f1=b1 f2=b2`, false) if err != nil { c.Fatalf("Build 5 should have worked: %q", err) } id2, err = buildImage(name, `FROM busybox LABEL f1="b1 f2=b2"`, true) if err != nil || id1 == id2 { c.Fatalf("Build 6 should have worked & NOT used the cache(%s,%s): %q", id1, id2, err) } } func (s *DockerSuite) TestBuildStderr(c *check.C) { // This test just makes sure that no non-error output goes // to stderr name := "testbuildstderr" _, _, stderr, err := buildImageWithStdoutStderr(name, "FROM busybox\nRUN echo one", true) if err != nil { c.Fatal(err) } if runtime.GOOS == "windows" { // stderr might contain a security warning on windows lines := strings.Split(stderr, "\n") for _, v := range lines { if v != "" && !strings.Contains(v, "SECURITY WARNING:") { c.Fatalf("Stderr contains unexpected output line: %q", v) } } } else { if stderr != "" { c.Fatalf("Stderr should have been empty, instead its: %q", stderr) } } } func (s *DockerSuite) TestBuildChownSingleFile(c *check.C) { testRequires(c, UnixCli) // test uses chown: not available on windows name := "testbuildchownsinglefile" ctx, err := fakeContext(` FROM busybox COPY test / RUN ls -l /test RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ] `, map[string]string{ "test": "test", }) if err != nil { c.Fatal(err) } defer ctx.Close() if err := os.Chown(filepath.Join(ctx.Dir, "test"), 4242, 4242); err != nil { c.Fatal(err) } if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) { name := "testbuildsymlinkbreakout" tmpdir, err := ioutil.TempDir("", name) if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpdir) ctx := filepath.Join(tmpdir, "context") if err := os.MkdirAll(ctx, 0755); err != nil { c.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte(` from busybox add symlink.tar / add inject /symlink/ `), 0644); err != nil { c.Fatal(err) } inject := filepath.Join(ctx, "inject") if err := ioutil.WriteFile(inject, nil, 0644); err != nil { c.Fatal(err) } f, err := os.Create(filepath.Join(ctx, "symlink.tar")) if err != nil { c.Fatal(err) } w := tar.NewWriter(f) w.WriteHeader(&tar.Header{ Name: "symlink2", Typeflag: tar.TypeSymlink, Linkname: "/../../../../../../../../../../../../../../", Uid: os.Getuid(), Gid: os.Getgid(), }) w.WriteHeader(&tar.Header{ Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: filepath.Join("symlink2", tmpdir), Uid: os.Getuid(), Gid: os.Getgid(), }) w.Close() f.Close() if _, err := buildImageFromContext(name, fakeContextFromDir(ctx), false); err != nil { c.Fatal(err) } if _, err := os.Lstat(filepath.Join(tmpdir, "inject")); err == nil { c.Fatal("symlink breakout - inject") } else if !os.IsNotExist(err) { c.Fatalf("unexpected error: %v", err) } } func (s *DockerSuite) TestBuildXZHost(c *check.C) { name := "testbuildxzhost" ctx, err := fakeContext(` FROM busybox ADD xz /usr/local/sbin/ RUN chmod 755 /usr/local/sbin/xz ADD test.xz / RUN [ ! -e /injected ]`, map[string]string{ "test.xz": "\xfd\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00" + "\x21\x01\x16\x00\x00\x00\x74\x2f\xe5\xa3\x01\x00\x3f\xfd" + "\x37\x7a\x58\x5a\x00\x00\x04\xe6\xd6\xb4\x46\x02\x00\x21", "xz": "#!/bin/sh\ntouch /injected", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, true); err != nil { c.Fatal(err) } } func (s *DockerSuite) TestBuildVolumesRetainContents(c *check.C) { var ( name = "testbuildvolumescontent" expected = "some text" ) ctx, err := fakeContext(` FROM busybox COPY content /foo/file VOLUME /foo CMD cat /foo/file`, map[string]string{ "content": expected, }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err := buildImageFromContext(name, ctx, false); err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--rm", name) if out != expected { c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out) } } func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) { ctx, err := fakeContext(`FROM busybox RUN echo from Dockerfile`, map[string]string{ "Dockerfile": "FROM busybox\nRUN echo from Dockerfile", "files/Dockerfile": "FROM busybox\nRUN echo from files/Dockerfile", "files/dFile": "FROM busybox\nRUN echo from files/dFile", "dFile": "FROM busybox\nRUN echo from dFile", "files/dFile2": "FROM busybox\nRUN echo from files/dFile2", }) defer ctx.Close() if err != nil { c.Fatal(err) } out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".") if err != nil { c.Fatalf("Failed to build: %s\n%s", out, err) } if !strings.Contains(out, "from Dockerfile") { c.Fatalf("test1 should have used Dockerfile, output:%s", out) } out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "-f", filepath.Join("files", "Dockerfile"), "-t", "test2", ".") if err != nil { c.Fatal(err) } if !strings.Contains(out, "from files/Dockerfile") { c.Fatalf("test2 should have used files/Dockerfile, output:%s", out) } out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", filepath.Join("files", "dFile")), "-t", "test3", ".") if err != nil { c.Fatal(err) } if !strings.Contains(out, "from files/dFile") { c.Fatalf("test3 should have used files/dFile, output:%s", out) } out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--file=dFile", "-t", "test4", ".") if err != nil { c.Fatal(err) } if !strings.Contains(out, "from dFile") { c.Fatalf("test4 should have used dFile, output:%s", out) } dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5") nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile") if _, err = os.Create(nonDockerfileFile); err != nil { c.Fatal(err) } out, _, err = dockerCmdInDir(c, ctx.Dir, "build", fmt.Sprintf("--file=%s", nonDockerfileFile), "-t", "test5", ".") if err == nil { c.Fatalf("test5 was supposed to fail to find passwd") } if expected := fmt.Sprintf("The Dockerfile (%s) must be within the build context (.)", nonDockerfileFile); !strings.Contains(out, expected) { c.Fatalf("wrong error messsage:%v\nexpected to contain=%v", out, expected) } out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test6", "..") if err != nil { c.Fatalf("test6 failed: %s", err) } if !strings.Contains(out, "from Dockerfile") { c.Fatalf("test6 should have used root Dockerfile, output:%s", out) } out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join(ctx.Dir, "files", "Dockerfile"), "-t", "test7", "..") if err != nil { c.Fatalf("test7 failed: %s", err) } if !strings.Contains(out, "from files/Dockerfile") { c.Fatalf("test7 should have used files Dockerfile, output:%s", out) } out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", filepath.Join("..", "Dockerfile"), "-t", "test8", ".") if err == nil || !strings.Contains(out, "must be within the build context") { c.Fatalf("test8 should have failed with Dockerfile out of context: %s", err) } tmpDir := os.TempDir() out, _, err = dockerCmdInDir(c, tmpDir, "build", "-t", "test9", ctx.Dir) if err != nil { c.Fatalf("test9 - failed: %s", err) } if !strings.Contains(out, "from Dockerfile") { c.Fatalf("test9 should have used root Dockerfile, output:%s", out) } out, _, err = dockerCmdInDir(c, filepath.Join(ctx.Dir, "files"), "build", "-f", "dFile2", "-t", "test10", ".") if err != nil { c.Fatalf("test10 should have worked: %s", err) } if !strings.Contains(out, "from files/dFile2") { c.Fatalf("test10 should have used files/dFile2, output:%s", out) } } func (s *DockerSuite) TestBuildFromMixedcaseDockerfile(c *check.C) { testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows ctx, err := fakeContext(`FROM busybox RUN echo from dockerfile`, map[string]string{ "dockerfile": "FROM busybox\nRUN echo from dockerfile", }) defer ctx.Close() if err != nil { c.Fatal(err) } out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".") if err != nil { c.Fatalf("Failed to build: %s\n%s", out, err) } if !strings.Contains(out, "from dockerfile") { c.Fatalf("Missing proper output: %s", out) } } func (s *DockerSuite) TestBuildWithTwoDockerfiles(c *check.C) { testRequires(c, UnixCli) // Dockerfile overwrites dockerfile on windows ctx, err := fakeContext(`FROM busybox RUN echo from Dockerfile`, map[string]string{ "dockerfile": "FROM busybox\nRUN echo from dockerfile", }) defer ctx.Close() if err != nil { c.Fatal(err) } out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-t", "test1", ".") if err != nil { c.Fatalf("Failed to build: %s\n%s", out, err) } if !strings.Contains(out, "from Dockerfile") { c.Fatalf("Missing proper output: %s", out) } } func (s *DockerSuite) TestBuildFromURLWithF(c *check.C) { server, err := fakeStorage(map[string]string{"baz": `FROM busybox RUN echo from baz COPY * /tmp/ RUN find /tmp/`}) if err != nil { c.Fatal(err) } defer server.Close() ctx, err := fakeContext(`FROM busybox RUN echo from Dockerfile`, map[string]string{}) defer ctx.Close() if err != nil { c.Fatal(err) } // Make sure that -f is ignored and that we don't use the Dockerfile // that's in the current dir out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "-f", "baz", "-t", "test1", server.URL()+"/baz") if err != nil { c.Fatalf("Failed to build: %s\n%s", out, err) } if !strings.Contains(out, "from baz") || strings.Contains(out, "/tmp/baz") || !strings.Contains(out, "/tmp/Dockerfile") { c.Fatalf("Missing proper output: %s", out) } } func (s *DockerSuite) TestBuildFromStdinWithF(c *check.C) { ctx, err := fakeContext(`FROM busybox RUN echo from Dockerfile`, map[string]string{}) defer ctx.Close() if err != nil { c.Fatal(err) } // Make sure that -f is ignored and that we don't use the Dockerfile // that's in the current dir dockerCommand := exec.Command(dockerBinary, "build", "-f", "baz", "-t", "test1", "-") dockerCommand.Dir = ctx.Dir dockerCommand.Stdin = strings.NewReader(`FROM busybox RUN echo from baz COPY * /tmp/ RUN find /tmp/`) out, status, err := runCommandWithOutput(dockerCommand) if err != nil || status != 0 { c.Fatalf("Error building: %s", err) } if !strings.Contains(out, "from baz") || strings.Contains(out, "/tmp/baz") || !strings.Contains(out, "/tmp/Dockerfile") { c.Fatalf("Missing proper output: %s", out) } } func (s *DockerSuite) TestBuildFromOfficialNames(c *check.C) { name := "testbuildfromofficial" fromNames := []string{ "busybox", "docker.io/busybox", "index.docker.io/busybox", "library/busybox", "docker.io/library/busybox", "index.docker.io/library/busybox", } for idx, fromName := range fromNames { imgName := fmt.Sprintf("%s%d", name, idx) _, err := buildImage(imgName, "FROM "+fromName, true) if err != nil { c.Errorf("Build failed using FROM %s: %s", fromName, err) } deleteImages(imgName) } } func (s *DockerSuite) TestBuildDockerfileOutsideContext(c *check.C) { testRequires(c, UnixCli) // uses os.Symlink: not implemented in windows at the time of writing (go-1.4.2) name := "testbuilddockerfileoutsidecontext" tmpdir, err := ioutil.TempDir("", name) if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpdir) ctx := filepath.Join(tmpdir, "context") if err := os.MkdirAll(ctx, 0755); err != nil { c.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(ctx, "Dockerfile"), []byte("FROM scratch\nENV X Y"), 0644); err != nil { c.Fatal(err) } wd, err := os.Getwd() if err != nil { c.Fatal(err) } defer os.Chdir(wd) if err := os.Chdir(ctx); err != nil { c.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(tmpdir, "outsideDockerfile"), []byte("FROM scratch\nENV x y"), 0644); err != nil { c.Fatal(err) } if err := os.Symlink(filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1")); err != nil { c.Fatal(err) } if err := os.Symlink(filepath.Join(tmpdir, "outsideDockerfile"), filepath.Join(ctx, "dockerfile2")); err != nil { c.Fatal(err) } for _, dockerfilePath := range []string{ filepath.Join("..", "outsideDockerfile"), filepath.Join(ctx, "dockerfile1"), filepath.Join(ctx, "dockerfile2"), } { out, _, err := dockerCmdWithError(c, "build", "-t", name, "--no-cache", "-f", dockerfilePath, ".") if err == nil { c.Fatalf("Expected error with %s. Out: %s", dockerfilePath, out) } if !strings.Contains(out, "must be within the build context") && !strings.Contains(out, "Cannot locate Dockerfile") { c.Fatalf("Unexpected error with %s. Out: %s", dockerfilePath, out) } deleteImages(name) } os.Chdir(tmpdir) // Path to Dockerfile should be resolved relative to working directory, not relative to context. // There is a Dockerfile in the context, but since there is no Dockerfile in the current directory, the following should fail out, _, err := dockerCmdWithError(c, "build", "-t", name, "--no-cache", "-f", "Dockerfile", ctx) if err == nil { c.Fatalf("Expected error. Out: %s", out) } } func (s *DockerSuite) TestBuildSpaces(c *check.C) { // Test to make sure that leading/trailing spaces on a command // doesn't change the error msg we get var ( err1 error err2 error ) name := "testspaces" ctx, err := fakeContext("FROM busybox\nCOPY\n", map[string]string{ "Dockerfile": "FROM busybox\nCOPY\n", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err1 = buildImageFromContext(name, ctx, false); err1 == nil { c.Fatal("Build 1 was supposed to fail, but didn't") } ctx.Add("Dockerfile", "FROM busybox\nCOPY ") if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil { c.Fatal("Build 2 was supposed to fail, but didn't") } removeLogTimestamps := func(s string) string { return regexp.MustCompile(`time="(.*?)"`).ReplaceAllString(s, `time=[TIMESTAMP]`) } // Skip over the times e1 := removeLogTimestamps(err1.Error()) e2 := removeLogTimestamps(err2.Error()) // Ignore whitespace since that's what were verifying doesn't change stuff if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) { c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", err1, err2) } ctx.Add("Dockerfile", "FROM busybox\n COPY") if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil { c.Fatal("Build 3 was supposed to fail, but didn't") } // Skip over the times e1 = removeLogTimestamps(err1.Error()) e2 = removeLogTimestamps(err2.Error()) // Ignore whitespace since that's what were verifying doesn't change stuff if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) { c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", err1, err2) } ctx.Add("Dockerfile", "FROM busybox\n COPY ") if _, err2 = buildImageFromContext(name, ctx, false); err2 == nil { c.Fatal("Build 4 was supposed to fail, but didn't") } // Skip over the times e1 = removeLogTimestamps(err1.Error()) e2 = removeLogTimestamps(err2.Error()) // Ignore whitespace since that's what were verifying doesn't change stuff if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) { c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", err1, err2) } } func (s *DockerSuite) TestBuildSpacesWithQuotes(c *check.C) { // Test to make sure that spaces in quotes aren't lost name := "testspacesquotes" dockerfile := `FROM busybox RUN echo " \ foo "` _, out, err := buildImageWithOut(name, dockerfile, false) if err != nil { c.Fatal("Build failed:", err) } expecting := "\n foo \n" if !strings.Contains(out, expecting) { c.Fatalf("Bad output: %q expecting to contain %q", out, expecting) } } // #4393 func (s *DockerSuite) TestBuildVolumeFileExistsinContainer(c *check.C) { buildCmd := exec.Command(dockerBinary, "build", "-t", "docker-test-errcreatevolumewithfile", "-") buildCmd.Stdin = strings.NewReader(` FROM busybox RUN touch /foo VOLUME /foo `) out, _, err := runCommandWithOutput(buildCmd) if err == nil || !strings.Contains(out, "file exists") { c.Fatalf("expected build to fail when file exists in container at requested volume path") } } func (s *DockerSuite) TestBuildMissingArgs(c *check.C) { // Test to make sure that all Dockerfile commands (except the ones listed // in skipCmds) will generate an error if no args are provided. // Note: INSERT is deprecated so we exclude it because of that. skipCmds := map[string]struct{}{ "CMD": {}, "RUN": {}, "ENTRYPOINT": {}, "INSERT": {}, } for cmd := range command.Commands { cmd = strings.ToUpper(cmd) if _, ok := skipCmds[cmd]; ok { continue } var dockerfile string if cmd == "FROM" { dockerfile = cmd } else { // Add FROM to make sure we don't complain about it missing dockerfile = "FROM busybox\n" + cmd } ctx, err := fakeContext(dockerfile, map[string]string{}) if err != nil { c.Fatal(err) } defer ctx.Close() var out string if out, err = buildImageFromContext("args", ctx, true); err == nil { c.Fatalf("%s was supposed to fail. Out:%s", cmd, out) } if !strings.Contains(err.Error(), cmd+" requires") { c.Fatalf("%s returned the wrong type of error:%s", cmd, err) } } } func (s *DockerSuite) TestBuildEmptyScratch(c *check.C) { _, out, err := buildImageWithOut("sc", "FROM scratch", true) if err == nil { c.Fatalf("Build was supposed to fail") } if !strings.Contains(out, "No image was generated") { c.Fatalf("Wrong error message: %v", out) } } func (s *DockerSuite) TestBuildDotDotFile(c *check.C) { ctx, err := fakeContext("FROM busybox\n", map[string]string{ "..gitme": "", }) if err != nil { c.Fatal(err) } defer ctx.Close() if _, err = buildImageFromContext("sc", ctx, false); err != nil { c.Fatalf("Build was supposed to work: %s", err) } } func (s *DockerSuite) TestBuildNotVerbose(c *check.C) { ctx, err := fakeContext("FROM busybox\nENV abc=hi\nRUN echo $abc there", map[string]string{}) if err != nil { c.Fatal(err) } defer ctx.Close() // First do it w/verbose - baseline out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", "verbose", ".") if err != nil { c.Fatalf("failed to build the image w/o -q: %s, %v", out, err) } if !strings.Contains(out, "hi there") { c.Fatalf("missing output:%s\n", out) } // Now do it w/o verbose out, _, err = dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-q", "-t", "verbose", ".") if err != nil { c.Fatalf("failed to build the image w/ -q: %s, %v", out, err) } if strings.Contains(out, "hi there") { c.Fatalf("Bad output, should not contain 'hi there':%s", out) } } func (s *DockerSuite) TestBuildRUNoneJSON(c *check.C) { name := "testbuildrunonejson" ctx, err := fakeContext(`FROM hello-world:frozen RUN [ "/hello" ]`, map[string]string{}) if err != nil { c.Fatal(err) } defer ctx.Close() out, _, err := dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "-t", name, ".") if err != nil { c.Fatalf("failed to build the image: %s, %v", out, err) } if !strings.Contains(out, "Hello from Docker") { c.Fatalf("bad output: %s", out) } } func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) { name := "testbuildemptystringvolume" _, err := buildImage(name, ` FROM busybox ENV foo="" VOLUME $foo `, false) if err == nil { c.Fatal("Should have failed to build") } } func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) { testRequires(c, NativeExecDriver) testRequires(c, SameHostDaemon) cgroupParent := "test" data, err := ioutil.ReadFile("/proc/self/cgroup") if err != nil { c.Fatalf("failed to read '/proc/self/cgroup - %v", err) } selfCgroupPaths := parseCgroupPaths(string(data)) _, found := selfCgroupPaths["memory"] if !found { c.Fatalf("unable to find self cpu cgroup path. CgroupsPath: %v", selfCgroupPaths) } cmd := exec.Command(dockerBinary, "build", "--cgroup-parent", cgroupParent, "-") cmd.Stdin = strings.NewReader(` FROM busybox RUN cat /proc/self/cgroup `) out, _, err := runCommandWithOutput(cmd) if err != nil { c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) } } func (s *DockerSuite) TestBuildNoDupOutput(c *check.C) { // Check to make sure our build output prints the Dockerfile cmd // property - there was a bug that caused it to be duplicated on the // Step X line name := "testbuildnodupoutput" _, out, err := buildImageWithOut(name, ` FROM busybox RUN env`, false) if err != nil { c.Fatalf("Build should have worked: %q", err) } exp := "\nStep 1 : RUN env\n" if !strings.Contains(out, exp) { c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp) } } func (s *DockerSuite) TestBuildBadCmdFlag(c *check.C) { name := "testbuildbadcmdflag" _, out, err := buildImageWithOut(name, ` FROM busybox MAINTAINER --boo joe@example.com`, false) if err == nil { c.Fatal("Build should have failed") } exp := "\nUnknown flag: boo\n" if !strings.Contains(out, exp) { c.Fatalf("Bad output\nGot:%s\n\nExpected to contain:%s\n", out, exp) } } func (s *DockerSuite) TestBuildRUNErrMsg(c *check.C) { // Test to make sure the bad command is quoted with just "s and // not as a Go []string name := "testbuildbadrunerrmsg" _, out, err := buildImageWithOut(name, ` FROM busybox RUN badEXE a1 \& a2 a3`, false) // tab between a2 and a3 if err == nil { c.Fatal("Should have failed to build") } exp := `The command '/bin/sh -c badEXE a1 \& a2 a3' returned a non-zero code: 127` if !strings.Contains(out, exp) { c.Fatalf("RUN doesn't have the correct output:\nGot:%s\nExpected:%s", out, exp) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_build_unix_test.go ================================================ // +build !windows package main import ( "encoding/json" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestBuildResourceConstraintsAreUsed(c *check.C) { testRequires(c, CpuCfsQuota) name := "testbuildresourceconstraints" ctx, err := fakeContext(` FROM hello-world:frozen RUN ["/hello"] `, map[string]string{}) if err != nil { c.Fatal(err) } dockerCmdInDir(c, ctx.Dir, "build", "--no-cache", "--rm=false", "--memory=64m", "--memory-swap=-1", "--cpuset-cpus=0", "--cpuset-mems=0", "--cpu-shares=100", "--cpu-quota=8000", "-t", name, ".") out, _ := dockerCmd(c, "ps", "-lq") cID := strings.TrimSpace(out) type hostConfig struct { Memory int64 MemorySwap int64 CpusetCpus string CpusetMems string CpuShares int64 CpuQuota int64 } cfg, err := inspectFieldJSON(cID, "HostConfig") if err != nil { c.Fatal(err) } var c1 hostConfig if err := json.Unmarshal([]byte(cfg), &c1); err != nil { c.Fatal(err, cfg) } if c1.Memory != 67108864 || c1.MemorySwap != -1 || c1.CpusetCpus != "0" || c1.CpusetMems != "0" || c1.CpuShares != 100 || c1.CpuQuota != 8000 { c.Fatalf("resource constraints not set properly:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpusetMems: %s, CpuShares: %d, CpuQuota: %d", c1.Memory, c1.MemorySwap, c1.CpusetCpus, c1.CpusetMems, c1.CpuShares, c1.CpuQuota) } // Make sure constraints aren't saved to image dockerCmd(c, "run", "--name=test", name) cfg, err = inspectFieldJSON("test", "HostConfig") if err != nil { c.Fatal(err) } var c2 hostConfig if err := json.Unmarshal([]byte(cfg), &c2); err != nil { c.Fatal(err, cfg) } if c2.Memory == 67108864 || c2.MemorySwap == -1 || c2.CpusetCpus == "0" || c2.CpusetMems == "0" || c2.CpuShares == 100 || c2.CpuQuota == 8000 { c.Fatalf("resource constraints leaked from build:\nMemory: %d, MemSwap: %d, CpusetCpus: %s, CpusetMems: %s, CpuShares: %d, CpuQuota: %d", c2.Memory, c2.MemorySwap, c2.CpusetCpus, c2.CpusetMems, c2.CpuShares, c2.CpuQuota) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_by_digest_test.go ================================================ package main import ( "fmt" "regexp" "strings" "github.com/docker/docker/utils" "github.com/go-check/check" ) var ( repoName = fmt.Sprintf("%v/dockercli/busybox-by-dgst", privateRegistryURL) digestRegex = regexp.MustCompile("Digest: ([^\n]+)") ) func setupImage(c *check.C) (string, error) { return setupImageWithTag(c, "latest") } func setupImageWithTag(c *check.C, tag string) (string, error) { containerName := "busyboxbydigest" dockerCmd(c, "run", "-d", "-e", "digest=1", "--name", containerName, "busybox") // tag the image to upload it to the private registry repoAndTag := utils.ImageReference(repoName, tag) if out, _, err := dockerCmdWithError(c, "commit", containerName, repoAndTag); err != nil { return "", fmt.Errorf("image tagging failed: %s, %v", out, err) } // delete the container as we don't need it any more if err := deleteContainer(containerName); err != nil { return "", err } // push the image out, _, err := dockerCmdWithError(c, "push", repoAndTag) if err != nil { return "", fmt.Errorf("pushing the image to the private registry has failed: %s, %v", out, err) } // delete our local repo that we previously tagged if rmiout, _, err := dockerCmdWithError(c, "rmi", repoAndTag); err != nil { return "", fmt.Errorf("error deleting images prior to real test: %s, %v", rmiout, err) } // the push output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) if len(matches) != 2 { return "", fmt.Errorf("unable to parse digest from push output: %s", out) } pushDigest := matches[1] return pushDigest, nil } func (s *DockerRegistrySuite) TestPullByTagDisplaysDigest(c *check.C) { pushDigest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } // pull from the registry using the tag out, _ := dockerCmd(c, "pull", repoName) // the pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) if len(matches) != 2 { c.Fatalf("unable to parse digest from pull output: %s", out) } pullDigest := matches[1] // make sure the pushed and pull digests match if pushDigest != pullDigest { c.Fatalf("push digest %q didn't match pull digest %q", pushDigest, pullDigest) } } func (s *DockerRegistrySuite) TestPullByDigest(c *check.C) { pushDigest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) out, _ := dockerCmd(c, "pull", imageReference) // the pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) if len(matches) != 2 { c.Fatalf("unable to parse digest from pull output: %s", out) } pullDigest := matches[1] // make sure the pushed and pull digests match if pushDigest != pullDigest { c.Fatalf("push digest %q didn't match pull digest %q", pushDigest, pullDigest) } } func (s *DockerRegistrySuite) TestPullByDigestNoFallback(c *check.C) { // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", repoName) out, _, err := dockerCmdWithError(c, "pull", imageReference) if err == nil || !strings.Contains(out, "manifest unknown") { c.Fatalf("expected non-zero exit status and correct error message when pulling non-existing image: %s", out) } } func (s *DockerRegistrySuite) TestCreateByDigest(c *check.C) { pushDigest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) containerName := "createByDigest" out, _ := dockerCmd(c, "create", "--name", containerName, imageReference) res, err := inspectField(containerName, "Config.Image") if err != nil { c.Fatalf("failed to get Config.Image: %s, %v", out, err) } if res != imageReference { c.Fatalf("unexpected Config.Image: %s (expected %s)", res, imageReference) } } func (s *DockerRegistrySuite) TestRunByDigest(c *check.C) { pushDigest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) containerName := "runByDigest" out, _ := dockerCmd(c, "run", "--name", containerName, imageReference, "sh", "-c", "echo found=$digest") foundRegex := regexp.MustCompile("found=([^\n]+)") matches := foundRegex.FindStringSubmatch(out) if len(matches) != 2 { c.Fatalf("error locating expected 'found=1' output: %s", out) } if matches[1] != "1" { c.Fatalf("Expected %q, got %q", "1", matches[1]) } res, err := inspectField(containerName, "Config.Image") if err != nil { c.Fatalf("failed to get Config.Image: %s, %v", out, err) } if res != imageReference { c.Fatalf("unexpected Config.Image: %s (expected %s)", res, imageReference) } } func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *check.C) { digest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference := fmt.Sprintf("%s@%s", repoName, digest) // pull from the registry using the @ reference dockerCmd(c, "pull", imageReference) // make sure inspect runs ok if _, err := inspectField(imageReference, "Id"); err != nil { c.Fatalf("failed to inspect image: %v", err) } // do the delete if err := deleteImages(imageReference); err != nil { c.Fatalf("unexpected error deleting image: %v", err) } // try to inspect again - it should error this time if _, err := inspectField(imageReference, "Id"); err == nil { c.Fatalf("unexpected nil err trying to inspect what should be a non-existent image") } else if !strings.Contains(err.Error(), "No such image") { c.Fatalf("expected 'No such image' output, got %v", err) } } func (s *DockerRegistrySuite) TestBuildByDigest(c *check.C) { digest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference := fmt.Sprintf("%s@%s", repoName, digest) // pull from the registry using the @ reference dockerCmd(c, "pull", imageReference) // get the image id imageID, err := inspectField(imageReference, "Id") if err != nil { c.Fatalf("error getting image id: %v", err) } // do the build name := "buildbydigest" _, err = buildImage(name, fmt.Sprintf( `FROM %s CMD ["/bin/echo", "Hello World"]`, imageReference), true) if err != nil { c.Fatal(err) } // get the build's image id res, err := inspectField(name, "Config.Image") if err != nil { c.Fatal(err) } // make sure they match if res != imageID { c.Fatalf("Image %s, expected %s", res, imageID) } } func (s *DockerRegistrySuite) TestTagByDigest(c *check.C) { digest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference := fmt.Sprintf("%s@%s", repoName, digest) // pull from the registry using the @ reference dockerCmd(c, "pull", imageReference) // tag it tag := "tagbydigest" dockerCmd(c, "tag", imageReference, tag) expectedID, err := inspectField(imageReference, "Id") if err != nil { c.Fatalf("error getting original image id: %v", err) } tagID, err := inspectField(tag, "Id") if err != nil { c.Fatalf("error getting tagged image id: %v", err) } if tagID != expectedID { c.Fatalf("expected image id %q, got %q", expectedID, tagID) } } func (s *DockerRegistrySuite) TestListImagesWithoutDigests(c *check.C) { digest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference := fmt.Sprintf("%s@%s", repoName, digest) // pull from the registry using the @ reference dockerCmd(c, "pull", imageReference) out, _ := dockerCmd(c, "images") if strings.Contains(out, "DIGEST") { c.Fatalf("list output should not have contained DIGEST header: %s", out) } } func (s *DockerRegistrySuite) TestListImagesWithDigests(c *check.C) { // setup image1 digest1, err := setupImageWithTag(c, "tag1") if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference1 := fmt.Sprintf("%s@%s", repoName, digest1) c.Logf("imageReference1 = %s", imageReference1) // pull image1 by digest dockerCmd(c, "pull", imageReference1) // list images out, _ := dockerCmd(c, "images", "--digests") // make sure repo shown, tag=, digest = $digest1 re1 := regexp.MustCompile(`\s*` + repoName + `\s*\s*` + digest1 + `\s`) if !re1.MatchString(out) { c.Fatalf("expected %q: %s", re1.String(), out) } // setup image2 digest2, err := setupImageWithTag(c, "tag2") if err != nil { c.Fatalf("error setting up image: %v", err) } imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2) c.Logf("imageReference2 = %s", imageReference2) // pull image1 by digest dockerCmd(c, "pull", imageReference1) // pull image2 by digest dockerCmd(c, "pull", imageReference2) // list images out, _ = dockerCmd(c, "images", "--digests") // make sure repo shown, tag=, digest = $digest1 if !re1.MatchString(out) { c.Fatalf("expected %q: %s", re1.String(), out) } // make sure repo shown, tag=, digest = $digest2 re2 := regexp.MustCompile(`\s*` + repoName + `\s*\s*` + digest2 + `\s`) if !re2.MatchString(out) { c.Fatalf("expected %q: %s", re2.String(), out) } // pull tag1 dockerCmd(c, "pull", repoName+":tag1") // list images out, _ = dockerCmd(c, "images", "--digests") // make sure image 1 has repo, tag, AND repo, , digest reWithTag1 := regexp.MustCompile(`\s*` + repoName + `\s*tag1\s*\s`) reWithDigest1 := regexp.MustCompile(`\s*` + repoName + `\s*\s*` + digest1 + `\s`) if !reWithTag1.MatchString(out) { c.Fatalf("expected %q: %s", reWithTag1.String(), out) } if !reWithDigest1.MatchString(out) { c.Fatalf("expected %q: %s", reWithDigest1.String(), out) } // make sure image 2 has repo, , digest if !re2.MatchString(out) { c.Fatalf("expected %q: %s", re2.String(), out) } // pull tag 2 dockerCmd(c, "pull", repoName+":tag2") // list images out, _ = dockerCmd(c, "images", "--digests") // make sure image 1 has repo, tag, digest if !reWithTag1.MatchString(out) { c.Fatalf("expected %q: %s", re1.String(), out) } // make sure image 2 has repo, tag, digest reWithTag2 := regexp.MustCompile(`\s*` + repoName + `\s*tag2\s*\s`) reWithDigest2 := regexp.MustCompile(`\s*` + repoName + `\s*\s*` + digest2 + `\s`) if !reWithTag2.MatchString(out) { c.Fatalf("expected %q: %s", reWithTag2.String(), out) } if !reWithDigest2.MatchString(out) { c.Fatalf("expected %q: %s", reWithDigest2.String(), out) } // list images out, _ = dockerCmd(c, "images", "--digests") // make sure image 1 has repo, tag, digest if !reWithTag1.MatchString(out) { c.Fatalf("expected %q: %s", re1.String(), out) } // make sure image 2 has repo, tag, digest if !reWithTag2.MatchString(out) { c.Fatalf("expected %q: %s", re2.String(), out) } // make sure busybox has tag, but not digest busyboxRe := regexp.MustCompile(`\s*busybox\s*latest\s*\s`) if !busyboxRe.MatchString(out) { c.Fatalf("expected %q: %s", busyboxRe.String(), out) } } func (s *DockerRegistrySuite) TestDeleteImageByIDOnlyPulledByDigest(c *check.C) { pushDigest, err := setupImage(c) if err != nil { c.Fatalf("error setting up image: %v", err) } // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) dockerCmd(c, "pull", imageReference) // just in case... imageID, err := inspectField(imageReference, "Id") if err != nil { c.Fatalf("error inspecting image id: %v", err) } dockerCmd(c, "rmi", imageID) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_commit_test.go ================================================ package main import ( "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestCommitAfterContainerIsDone(c *check.C) { out, _ := dockerCmd(c, "run", "-i", "-a", "stdin", "busybox", "echo", "foo") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "commit", cleanedContainerID) cleanedImageID := strings.TrimSpace(out) dockerCmd(c, "inspect", cleanedImageID) } func (s *DockerSuite) TestCommitWithoutPause(c *check.C) { out, _ := dockerCmd(c, "run", "-i", "-a", "stdin", "busybox", "echo", "foo") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "commit", "-p=false", cleanedContainerID) cleanedImageID := strings.TrimSpace(out) dockerCmd(c, "inspect", cleanedImageID) } //test commit a paused container should not unpause it after commit func (s *DockerSuite) TestCommitPausedContainer(c *check.C) { defer unpauseAllContainers() out, _ := dockerCmd(c, "run", "-i", "-d", "busybox") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "pause", cleanedContainerID) out, _ = dockerCmd(c, "commit", cleanedContainerID) out, err := inspectField(cleanedContainerID, "State.Paused") c.Assert(err, check.IsNil) if !strings.Contains(out, "true") { c.Fatalf("commit should not unpause a paused container") } } func (s *DockerSuite) TestCommitNewFile(c *check.C) { dockerCmd(c, "run", "--name", "commiter", "busybox", "/bin/sh", "-c", "echo koye > /foo") imageID, _ := dockerCmd(c, "commit", "commiter") imageID = strings.Trim(imageID, "\r\n") out, _ := dockerCmd(c, "run", imageID, "cat", "/foo") if actual := strings.Trim(out, "\r\n"); actual != "koye" { c.Fatalf("expected output koye received %q", actual) } } func (s *DockerSuite) TestCommitHardlink(c *check.C) { firstOutput, _ := dockerCmd(c, "run", "-t", "--name", "hardlinks", "busybox", "sh", "-c", "touch file1 && ln file1 file2 && ls -di file1 file2") chunks := strings.Split(strings.TrimSpace(firstOutput), " ") inode := chunks[0] found := false for _, chunk := range chunks[1:] { if chunk == inode { found = true break } } if !found { c.Fatalf("Failed to create hardlink in a container. Expected to find %q in %q", inode, chunks[1:]) } imageID, _ := dockerCmd(c, "commit", "hardlinks", "hardlinks") imageID = strings.Trim(imageID, "\r\n") secondOutput, _ := dockerCmd(c, "run", "-t", "hardlinks", "ls", "-di", "file1", "file2") chunks = strings.Split(strings.TrimSpace(secondOutput), " ") inode = chunks[0] found = false for _, chunk := range chunks[1:] { if chunk == inode { found = true break } } if !found { c.Fatalf("Failed to create hardlink in a container. Expected to find %q in %q", inode, chunks[1:]) } } func (s *DockerSuite) TestCommitTTY(c *check.C) { dockerCmd(c, "run", "-t", "--name", "tty", "busybox", "/bin/ls") imageID, _ := dockerCmd(c, "commit", "tty", "ttytest") imageID = strings.Trim(imageID, "\r\n") dockerCmd(c, "run", "ttytest", "/bin/ls") } func (s *DockerSuite) TestCommitWithHostBindMount(c *check.C) { dockerCmd(c, "run", "--name", "bind-commit", "-v", "/dev/null:/winning", "busybox", "true") imageID, _ := dockerCmd(c, "commit", "bind-commit", "bindtest") imageID = strings.Trim(imageID, "\r\n") dockerCmd(c, "run", "bindtest", "true") } func (s *DockerSuite) TestCommitChange(c *check.C) { dockerCmd(c, "run", "--name", "test", "busybox", "true") imageID, _ := dockerCmd(c, "commit", "--change", "EXPOSE 8080", "--change", "ENV DEBUG true", "--change", "ENV test 1", "--change", "ENV PATH /foo", "--change", "LABEL foo bar", "--change", "CMD [\"/bin/sh\"]", "--change", "WORKDIR /opt", "--change", "ENTRYPOINT [\"/bin/sh\"]", "--change", "USER testuser", "--change", "VOLUME /var/lib/docker", "--change", "ONBUILD /usr/local/bin/python-build --dir /app/src", "test", "test-commit") imageID = strings.Trim(imageID, "\r\n") expected := map[string]string{ "Config.ExposedPorts": "map[8080/tcp:{}]", "Config.Env": "[DEBUG=true test=1 PATH=/foo]", "Config.Labels": "map[foo:bar]", "Config.Cmd": "{[/bin/sh]}", "Config.WorkingDir": "/opt", "Config.Entrypoint": "{[/bin/sh]}", "Config.User": "testuser", "Config.Volumes": "map[/var/lib/docker:{}]", "Config.OnBuild": "[/usr/local/bin/python-build --dir /app/src]", } for conf, value := range expected { res, err := inspectField(imageID, conf) c.Assert(err, check.IsNil) if res != value { c.Errorf("%s('%s'), expected %s", conf, res, value) } } } // TODO: commit --run is deprecated, remove this once --run is removed func (s *DockerSuite) TestCommitMergeConfigRun(c *check.C) { name := "commit-test" out, _ := dockerCmd(c, "run", "-d", "-e=FOO=bar", "busybox", "/bin/sh", "-c", "echo testing > /tmp/foo") id := strings.TrimSpace(out) dockerCmd(c, "commit", `--run={"Cmd": ["cat", "/tmp/foo"]}`, id, "commit-test") out, _ = dockerCmd(c, "run", "--name", name, "commit-test") if strings.TrimSpace(out) != "testing" { c.Fatal("run config in committed container was not merged") } type cfg struct { Env []string Cmd []string } config1 := cfg{} if err := inspectFieldAndMarshall(id, "Config", &config1); err != nil { c.Fatal(err) } config2 := cfg{} if err := inspectFieldAndMarshall(name, "Config", &config2); err != nil { c.Fatal(err) } // Env has at least PATH loaded as well here, so let's just grab the FOO one var env1, env2 string for _, e := range config1.Env { if strings.HasPrefix(e, "FOO") { env1 = e break } } for _, e := range config2.Env { if strings.HasPrefix(e, "FOO") { env2 = e break } } if len(config1.Env) != len(config2.Env) || env1 != env2 && env2 != "" { c.Fatalf("expected envs to match: %v - %v", config1.Env, config2.Env) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_config_test.go ================================================ package main import ( "io/ioutil" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/pkg/homedir" "github.com/go-check/check" ) func (s *DockerSuite) TestConfigHttpHeader(c *check.C) { testRequires(c, UnixCli) // Can't set/unset HOME on windows right now // We either need a level of Go that supports Unsetenv (for cases // when HOME/USERPROFILE isn't set), or we need to be able to use // os/user but user.Current() only works if we aren't statically compiling var headers map[string][]string server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { headers = r.Header })) defer server.Close() homeKey := homedir.Key() homeVal := homedir.Get() tmpDir, _ := ioutil.TempDir("", "fake-home") defer os.RemoveAll(tmpDir) dotDocker := filepath.Join(tmpDir, ".docker") os.Mkdir(dotDocker, 0600) tmpCfg := filepath.Join(dotDocker, "config.json") defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpDir) data := `{ "HttpHeaders": { "MyHeader": "MyValue" } }` err := ioutil.WriteFile(tmpCfg, []byte(data), 0600) if err != nil { c.Fatalf("Err creating file(%s): %v", tmpCfg, err) } cmd := exec.Command(dockerBinary, "-H="+server.URL[7:], "ps") out, _, _ := runCommandWithOutput(cmd) if headers["User-Agent"] == nil { c.Fatalf("Missing User-Agent: %q\nout:%v", headers, out) } if headers["User-Agent"][0] != "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")" { c.Fatalf("Badly formatted User-Agent: %q\nout:%v", headers, out) } if headers["Myheader"] == nil || headers["Myheader"][0] != "MyValue" { c.Fatalf("Missing/bad header: %q\nout:%v", headers, out) } } func (s *DockerSuite) TestConfigDir(c *check.C) { cDir, _ := ioutil.TempDir("", "fake-home") // First make sure pointing to empty dir doesn't generate an error out, rc := dockerCmd(c, "--config", cDir, "ps") if rc != 0 { c.Fatalf("ps1 didn't work:\nrc:%d\nout%s", rc, out) } // Test with env var too cmd := exec.Command(dockerBinary, "ps") cmd.Env = append(os.Environ(), "DOCKER_CONFIG="+cDir) out, rc, err := runCommandWithOutput(cmd) if rc != 0 || err != nil { c.Fatalf("ps2 didn't work:\nrc:%d\nout%s\nerr:%v", rc, out, err) } // Start a server so we can check to see if the config file was // loaded properly var headers map[string][]string server := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { headers = r.Header })) defer server.Close() // Create a dummy config file in our new config dir data := `{ "HttpHeaders": { "MyHeader": "MyValue" } }` tmpCfg := filepath.Join(cDir, "config.json") err = ioutil.WriteFile(tmpCfg, []byte(data), 0600) if err != nil { c.Fatalf("Err creating file(%s): %v", tmpCfg, err) } cmd = exec.Command(dockerBinary, "--config", cDir, "-H="+server.URL[7:], "ps") out, _, _ = runCommandWithOutput(cmd) if headers["Myheader"] == nil || headers["Myheader"][0] != "MyValue" { c.Fatalf("ps3 - Missing header: %q\nout:%v", headers, out) } // Reset headers and try again using env var this time headers = map[string][]string{} cmd = exec.Command(dockerBinary, "-H="+server.URL[7:], "ps") cmd.Env = append(os.Environ(), "DOCKER_CONFIG="+cDir) out, _, _ = runCommandWithOutput(cmd) if headers["Myheader"] == nil || headers["Myheader"][0] != "MyValue" { c.Fatalf("ps4 - Missing header: %q\nout:%v", headers, out) } // Reset headers and make sure flag overrides the env var headers = map[string][]string{} cmd = exec.Command(dockerBinary, "--config", cDir, "-H="+server.URL[7:], "ps") cmd.Env = append(os.Environ(), "DOCKER_CONFIG=MissingDir") out, _, _ = runCommandWithOutput(cmd) if headers["Myheader"] == nil || headers["Myheader"][0] != "MyValue" { c.Fatalf("ps5 - Missing header: %q\nout:%v", headers, out) } // Reset headers and make sure flag overrides the env var. // Almost same as previous but make sure the "MissingDir" isn't // ignore - we don't want to default back to the env var. headers = map[string][]string{} cmd = exec.Command(dockerBinary, "--config", "MissingDir", "-H="+server.URL[7:], "ps") cmd.Env = append(os.Environ(), "DOCKER_CONFIG="+cDir) out, _, _ = runCommandWithOutput(cmd) if headers["Myheader"] != nil { c.Fatalf("ps6 - Headers are there but shouldn't be: %q\nout:%v", headers, out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_cp_from_container_test.go ================================================ package main import ( "os" "path/filepath" "github.com/go-check/check" ) // docker cp CONTAINER:PATH LOCALPATH // Try all of the test cases from the archive package which implements the // internals of `docker cp` and ensure that the behavior matches when actually // copying to and from containers. // Basic assumptions about SRC and DST: // 1. SRC must exist. // 2. If SRC ends with a trailing separator, it must be a directory. // 3. DST parent directory must exist. // 4. If DST exists as a file, it must not end with a trailing separator. // First get these easy error cases out of the way. // Test for error when SRC does not exist. func (s *DockerSuite) TestCpFromErrSrcNotExists(c *check.C) { cID := makeTestContainer(c, testContainerOptions{}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-err-src-not-exists") defer os.RemoveAll(tmpDir) err := runDockerCp(c, containerCpPath(cID, "file1"), tmpDir) if err == nil { c.Fatal("expected IsNotExist error, but got nil instead") } if !isCpNotExist(err) { c.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when SRC ends in a trailing // path separator but it exists as a file. func (s *DockerSuite) TestCpFromErrSrcNotDir(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-err-src-not-dir") defer os.RemoveAll(tmpDir) err := runDockerCp(c, containerCpPathTrailingSep(cID, "file1"), tmpDir) if err == nil { c.Fatal("expected IsNotDir error, but got nil instead") } if !isCpNotDir(err) { c.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Test for error when SRC is a valid file or directory, // bu the DST parent directory does not exist. func (s *DockerSuite) TestCpFromErrDstParentNotExists(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-err-dst-parent-not-exists") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) // Try with a file source. srcPath := containerCpPath(cID, "/file1") dstPath := cpPath(tmpDir, "notExists", "file1") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected IsNotExist error, but got nil instead") } if !isCpNotExist(err) { c.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } // Try with a directory source. srcPath = containerCpPath(cID, "/dir1") if err := runDockerCp(c, srcPath, dstPath); err == nil { c.Fatal("expected IsNotExist error, but got nil instead") } if !isCpNotExist(err) { c.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when DST ends in a trailing // path separator but exists as a file. func (s *DockerSuite) TestCpFromErrDstNotDir(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-err-dst-not-dir") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) // Try with a file source. srcPath := containerCpPath(cID, "/file1") dstPath := cpPathTrailingSep(tmpDir, "file1") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected IsNotDir error, but got nil instead") } if !isCpNotDir(err) { c.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } // Try with a directory source. srcPath = containerCpPath(cID, "/dir1") if err := runDockerCp(c, srcPath, dstPath); err == nil { c.Fatal("expected IsNotDir error, but got nil instead") } if !isCpNotDir(err) { c.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Possibilities are reduced to the remaining 10 cases: // // case | srcIsDir | onlyDirContents | dstExists | dstIsDir | dstTrSep | action // =================================================================================================== // A | no | - | no | - | no | create file // B | no | - | no | - | yes | error // C | no | - | yes | no | - | overwrite file // D | no | - | yes | yes | - | create file in dst dir // E | yes | no | no | - | - | create dir, copy contents // F | yes | no | yes | no | - | error // G | yes | no | yes | yes | - | copy dir and contents // H | yes | yes | no | - | - | create dir, copy contents // I | yes | yes | yes | no | - | error // J | yes | yes | yes | yes | - | copy dir contents // // A. SRC specifies a file and DST (no trailing path separator) doesn't // exist. This should create a file with the name DST and copy the // contents of the source file into it. func (s *DockerSuite) TestCpFromCaseA(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-a") defer os.RemoveAll(tmpDir) srcPath := containerCpPath(cID, "/root/file1") dstPath := cpPath(tmpDir, "itWorks.txt") if err := runDockerCp(c, srcPath, dstPath); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1\n"); err != nil { c.Fatal(err) } } // B. SRC specifies a file and DST (with trailing path separator) doesn't // exist. This should cause an error because the copy operation cannot // create a directory when copying a single file. func (s *DockerSuite) TestCpFromCaseB(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-b") defer os.RemoveAll(tmpDir) srcPath := containerCpPath(cID, "/file1") dstDir := cpPathTrailingSep(tmpDir, "testDir") err := runDockerCp(c, srcPath, dstDir) if err == nil { c.Fatal("expected DirNotExists error, but got nil instead") } if !isCpDirNotExist(err) { c.Fatalf("expected DirNotExists error, but got %T: %s", err, err) } } // C. SRC specifies a file and DST exists as a file. This should overwrite // the file at DST with the contents of the source file. func (s *DockerSuite) TestCpFromCaseC(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-c") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := containerCpPath(cID, "/root/file1") dstPath := cpPath(tmpDir, "file2") // Ensure the local file starts with different content. if err := fileContentEquals(c, dstPath, "file2\n"); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcPath, dstPath); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1\n"); err != nil { c.Fatal(err) } } // D. SRC specifies a file and DST exists as a directory. This should place // a copy of the source file inside it using the basename from SRC. Ensure // this works whether DST has a trailing path separator or not. func (s *DockerSuite) TestCpFromCaseD(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-d") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := containerCpPath(cID, "/file1") dstDir := cpPath(tmpDir, "dir1") dstPath := filepath.Join(dstDir, "file1") // Ensure that dstPath doesn't exist. if _, err := os.Stat(dstPath); !os.IsNotExist(err) { c.Fatalf("did not expect dstPath %q to exist", dstPath) } if err := runDockerCp(c, srcPath, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err := os.RemoveAll(dstDir); err != nil { c.Fatalf("unable to remove dstDir: %s", err) } if err := os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { c.Fatalf("unable to make dstDir: %s", err) } dstDir = cpPathTrailingSep(tmpDir, "dir1") if err := runDockerCp(c, srcPath, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1\n"); err != nil { c.Fatal(err) } } // E. SRC specifies a directory and DST does not exist. This should create a // directory at DST and copy the contents of the SRC directory into the DST // directory. Ensure this works whether DST has a trailing path separator or // not. func (s *DockerSuite) TestCpFromCaseE(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-e") defer os.RemoveAll(tmpDir) srcDir := containerCpPath(cID, "dir1") dstDir := cpPath(tmpDir, "testDir") dstPath := filepath.Join(dstDir, "file1-1") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err := os.RemoveAll(dstDir); err != nil { c.Fatalf("unable to remove dstDir: %s", err) } dstDir = cpPathTrailingSep(tmpDir, "testDir") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } } // F. SRC specifies a directory and DST exists as a file. This should cause an // error as it is not possible to overwrite a file with a directory. func (s *DockerSuite) TestCpFromCaseF(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-f") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := containerCpPath(cID, "/root/dir1") dstFile := cpPath(tmpDir, "file1") err := runDockerCp(c, srcDir, dstFile) if err == nil { c.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if !isCpCannotCopyDir(err) { c.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // G. SRC specifies a directory and DST exists as a directory. This should copy // the SRC directory and all its contents to the DST directory. Ensure this // works whether DST has a trailing path separator or not. func (s *DockerSuite) TestCpFromCaseG(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-g") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := containerCpPath(cID, "/root/dir1") dstDir := cpPath(tmpDir, "dir2") resultDir := filepath.Join(dstDir, "dir1") dstPath := filepath.Join(resultDir, "file1-1") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err := os.RemoveAll(dstDir); err != nil { c.Fatalf("unable to remove dstDir: %s", err) } if err := os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { c.Fatalf("unable to make dstDir: %s", err) } dstDir = cpPathTrailingSep(tmpDir, "dir2") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } } // H. SRC specifies a directory's contents only and DST does not exist. This // should create a directory at DST and copy the contents of the SRC // directory (but not the directory itself) into the DST directory. Ensure // this works whether DST has a trailing path separator or not. func (s *DockerSuite) TestCpFromCaseH(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-h") defer os.RemoveAll(tmpDir) srcDir := containerCpPathTrailingSep(cID, "dir1") + "." dstDir := cpPath(tmpDir, "testDir") dstPath := filepath.Join(dstDir, "file1-1") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err := os.RemoveAll(dstDir); err != nil { c.Fatalf("unable to remove resultDir: %s", err) } dstDir = cpPathTrailingSep(tmpDir, "testDir") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } } // I. SRC specifies a direcotry's contents only and DST exists as a file. This // should cause an error as it is not possible to overwrite a file with a // directory. func (s *DockerSuite) TestCpFromCaseI(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-i") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := containerCpPathTrailingSep(cID, "/root/dir1") + "." dstFile := cpPath(tmpDir, "file1") err := runDockerCp(c, srcDir, dstFile) if err == nil { c.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if !isCpCannotCopyDir(err) { c.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // J. SRC specifies a directory's contents only and DST exists as a directory. // This should copy the contents of the SRC directory (but not the directory // itself) into the DST directory. Ensure this works whether DST has a // trailing path separator or not. func (s *DockerSuite) TestCpFromCaseJ(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-from-case-j") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := containerCpPathTrailingSep(cID, "/root/dir1") + "." dstDir := cpPath(tmpDir, "dir2") dstPath := filepath.Join(dstDir, "file1-1") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err := os.RemoveAll(dstDir); err != nil { c.Fatalf("unable to remove dstDir: %s", err) } if err := os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { c.Fatalf("unable to make dstDir: %s", err) } dstDir = cpPathTrailingSep(tmpDir, "dir2") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := fileContentEquals(c, dstPath, "file1-1\n"); err != nil { c.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_cp_test.go ================================================ package main import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "github.com/go-check/check" ) const ( cpTestPathParent = "/some" cpTestPath = "/some/path" cpTestName = "test" cpFullPath = "/some/path/test" cpContainerContents = "holla, i am the container" cpHostContents = "hello, i am the host" ) // Ensure that an all-local path case returns an error. func (s *DockerSuite) TestCpLocalOnly(c *check.C) { err := runDockerCp(c, "foo", "bar") if err == nil { c.Fatal("expected failure, got success") } if !strings.Contains(err.Error(), "must specify at least one container source") { c.Fatalf("unexpected output: %s", err.Error()) } } // Test for #5656 // Check that garbage paths don't escape the container's rootfs func (s *DockerSuite) TestCpGarbagePath(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath) if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } if err := os.MkdirAll(cpTestPath, os.ModeDir); err != nil { c.Fatal(err) } hostFile, err := os.Create(cpFullPath) if err != nil { c.Fatal(err) } defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) path := path.Join("../../../../../../../../../../../../", cpFullPath) dockerCmd(c, "cp", cleanedContainerID+":"+path, tmpdir) file, _ := os.Open(tmpname) defer file.Close() test, err := ioutil.ReadAll(file) if err != nil { c.Fatal(err) } if string(test) == cpHostContents { c.Errorf("output matched host file -- garbage path can escape container rootfs") } if string(test) != cpContainerContents { c.Errorf("output doesn't match the input for garbage path") } } // Check that relative paths are relative to the container's rootfs func (s *DockerSuite) TestCpRelativePath(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath) if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } if err := os.MkdirAll(cpTestPath, os.ModeDir); err != nil { c.Fatal(err) } hostFile, err := os.Create(cpFullPath) if err != nil { c.Fatal(err) } defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) var relPath string if path.IsAbs(cpFullPath) { // normally this is `filepath.Rel("/", cpFullPath)` but we cannot // get this unix-path manipulation on windows with filepath. relPath = cpFullPath[1:] } else { c.Fatalf("path %s was assumed to be an absolute path", cpFullPath) } dockerCmd(c, "cp", cleanedContainerID+":"+relPath, tmpdir) file, _ := os.Open(tmpname) defer file.Close() test, err := ioutil.ReadAll(file) if err != nil { c.Fatal(err) } if string(test) == cpHostContents { c.Errorf("output matched host file -- relative path can escape container rootfs") } if string(test) != cpContainerContents { c.Errorf("output doesn't match the input for relative path") } } // Check that absolute paths are relative to the container's rootfs func (s *DockerSuite) TestCpAbsolutePath(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath) if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } if err := os.MkdirAll(cpTestPath, os.ModeDir); err != nil { c.Fatal(err) } hostFile, err := os.Create(cpFullPath) if err != nil { c.Fatal(err) } defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) path := cpFullPath dockerCmd(c, "cp", cleanedContainerID+":"+path, tmpdir) file, _ := os.Open(tmpname) defer file.Close() test, err := ioutil.ReadAll(file) if err != nil { c.Fatal(err) } if string(test) == cpHostContents { c.Errorf("output matched host file -- absolute path can escape container rootfs") } if string(test) != cpContainerContents { c.Errorf("output doesn't match the input for absolute path") } } // Test for #5619 // Check that absolute symlinks are still relative to the container's rootfs func (s *DockerSuite) TestCpAbsoluteSymlink(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpFullPath+" container_path") if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } if err := os.MkdirAll(cpTestPath, os.ModeDir); err != nil { c.Fatal(err) } hostFile, err := os.Create(cpFullPath) if err != nil { c.Fatal(err) } defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) path := path.Join("/", "container_path") dockerCmd(c, "cp", cleanedContainerID+":"+path, tmpdir) file, _ := os.Open(tmpname) defer file.Close() test, err := ioutil.ReadAll(file) if err != nil { c.Fatal(err) } if string(test) == cpHostContents { c.Errorf("output matched host file -- absolute symlink can escape container rootfs") } if string(test) != cpContainerContents { c.Errorf("output doesn't match the input for absolute symlink") } } // Test for #5619 // Check that symlinks which are part of the resource path are still relative to the container's rootfs func (s *DockerSuite) TestCpSymlinkComponent(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpTestPath+" container_path") if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } if err := os.MkdirAll(cpTestPath, os.ModeDir); err != nil { c.Fatal(err) } hostFile, err := os.Create(cpFullPath) if err != nil { c.Fatal(err) } defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) path := path.Join("/", "container_path", cpTestName) dockerCmd(c, "cp", cleanedContainerID+":"+path, tmpdir) file, _ := os.Open(tmpname) defer file.Close() test, err := ioutil.ReadAll(file) if err != nil { c.Fatal(err) } if string(test) == cpHostContents { c.Errorf("output matched host file -- symlink path component can escape container rootfs") } if string(test) != cpContainerContents { c.Errorf("output doesn't match the input for symlink path component") } } // Check that cp with unprivileged user doesn't return any error func (s *DockerSuite) TestCpUnprivilegedUser(c *check.C) { testRequires(c, UnixCli) // uses chmod/su: not available on windows out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch "+cpTestName) if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpdir) if err = os.Chmod(tmpdir, 0777); err != nil { c.Fatal(err) } path := cpTestName _, _, err = runCommandWithOutput(exec.Command("su", "unprivilegeduser", "-c", dockerBinary+" cp "+cleanedContainerID+":"+path+" "+tmpdir)) if err != nil { c.Fatalf("couldn't copy with unprivileged user: %s:%s %s", cleanedContainerID, path, err) } } func (s *DockerSuite) TestCpSpecialFiles(c *check.C) { testRequires(c, SameHostDaemon) outDir, err := ioutil.TempDir("", "cp-test-special-files") if err != nil { c.Fatal(err) } defer os.RemoveAll(outDir) out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch /foo") if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } // Copy actual /etc/resolv.conf dockerCmd(c, "cp", cleanedContainerID+":/etc/resolv.conf", outDir) expected, err := ioutil.ReadFile("/var/lib/docker/containers/" + cleanedContainerID + "/resolv.conf") actual, err := ioutil.ReadFile(outDir + "/resolv.conf") if !bytes.Equal(actual, expected) { c.Fatalf("Expected copied file to be duplicate of the container resolvconf") } // Copy actual /etc/hosts dockerCmd(c, "cp", cleanedContainerID+":/etc/hosts", outDir) expected, err = ioutil.ReadFile("/var/lib/docker/containers/" + cleanedContainerID + "/hosts") actual, err = ioutil.ReadFile(outDir + "/hosts") if !bytes.Equal(actual, expected) { c.Fatalf("Expected copied file to be duplicate of the container hosts") } // Copy actual /etc/resolv.conf dockerCmd(c, "cp", cleanedContainerID+":/etc/hostname", outDir) expected, err = ioutil.ReadFile("/var/lib/docker/containers/" + cleanedContainerID + "/hostname") actual, err = ioutil.ReadFile(outDir + "/hostname") if !bytes.Equal(actual, expected) { c.Fatalf("Expected copied file to be duplicate of the container resolvconf") } } func (s *DockerSuite) TestCpVolumePath(c *check.C) { testRequires(c, SameHostDaemon) tmpDir, err := ioutil.TempDir("", "cp-test-volumepath") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir) outDir, err := ioutil.TempDir("", "cp-test-volumepath-out") if err != nil { c.Fatal(err) } defer os.RemoveAll(outDir) _, err = os.Create(tmpDir + "/test") if err != nil { c.Fatal(err) } out, exitCode := dockerCmd(c, "run", "-d", "-v", "/foo", "-v", tmpDir+"/test:/test", "-v", tmpDir+":/baz", "busybox", "/bin/sh", "-c", "touch /foo/bar") if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } // Copy actual volume path dockerCmd(c, "cp", cleanedContainerID+":/foo", outDir) stat, err := os.Stat(outDir + "/foo") if err != nil { c.Fatal(err) } if !stat.IsDir() { c.Fatal("expected copied content to be dir") } stat, err = os.Stat(outDir + "/foo/bar") if err != nil { c.Fatal(err) } if stat.IsDir() { c.Fatal("Expected file `bar` to be a file") } // Copy file nested in volume dockerCmd(c, "cp", cleanedContainerID+":/foo/bar", outDir) stat, err = os.Stat(outDir + "/bar") if err != nil { c.Fatal(err) } if stat.IsDir() { c.Fatal("Expected file `bar` to be a file") } // Copy Bind-mounted dir dockerCmd(c, "cp", cleanedContainerID+":/baz", outDir) stat, err = os.Stat(outDir + "/baz") if err != nil { c.Fatal(err) } if !stat.IsDir() { c.Fatal("Expected `baz` to be a dir") } // Copy file nested in bind-mounted dir dockerCmd(c, "cp", cleanedContainerID+":/baz/test", outDir) fb, err := ioutil.ReadFile(outDir + "/baz/test") if err != nil { c.Fatal(err) } fb2, err := ioutil.ReadFile(tmpDir + "/test") if err != nil { c.Fatal(err) } if !bytes.Equal(fb, fb2) { c.Fatalf("Expected copied file to be duplicate of bind-mounted file") } // Copy bind-mounted file dockerCmd(c, "cp", cleanedContainerID+":/test", outDir) fb, err = ioutil.ReadFile(outDir + "/test") if err != nil { c.Fatal(err) } fb2, err = ioutil.ReadFile(tmpDir + "/test") if err != nil { c.Fatal(err) } if !bytes.Equal(fb, fb2) { c.Fatalf("Expected copied file to be duplicate of bind-mounted file") } } func (s *DockerSuite) TestCpToDot(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test") if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpdir) cwd, err := os.Getwd() if err != nil { c.Fatal(err) } defer os.Chdir(cwd) if err := os.Chdir(tmpdir); err != nil { c.Fatal(err) } dockerCmd(c, "cp", cleanedContainerID+":/test", ".") content, err := ioutil.ReadFile("./test") if string(content) != "lololol\n" { c.Fatalf("Wrong content in copied file %q, should be %q", content, "lololol\n") } } func (s *DockerSuite) TestCpToStdout(c *check.C) { out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test") if exitCode != 0 { c.Fatalf("failed to create a container:%s\n", out) } cID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cID) if strings.TrimSpace(out) != "0" { c.Fatalf("failed to set up container:%s\n", out) } out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "cp", cID+":/test", "-"), exec.Command("tar", "-vtf", "-")) if err != nil { c.Fatalf("Failed to run commands: %s", err) } if !strings.Contains(out, "test") || !strings.Contains(out, "-rw") { c.Fatalf("Missing file from tar TOC:\n%s", out) } } func (s *DockerSuite) TestCpNameHasColon(c *check.C) { testRequires(c, SameHostDaemon) out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /te:s:t") if exitCode != 0 { c.Fatal("failed to create a container", out) } cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } tmpdir, err := ioutil.TempDir("", "docker-integration") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpdir) dockerCmd(c, "cp", cleanedContainerID+":/te:s:t", tmpdir) content, err := ioutil.ReadFile(tmpdir + "/te:s:t") if string(content) != "lololol\n" { c.Fatalf("Wrong content in copied file %q, should be %q", content, "lololol\n") } } func (s *DockerSuite) TestCopyAndRestart(c *check.C) { expectedMsg := "hello" out, _ := dockerCmd(c, "run", "-d", "busybox", "echo", expectedMsg) id := strings.TrimSpace(string(out)) out, _ = dockerCmd(c, "wait", id) status := strings.TrimSpace(out) if status != "0" { c.Fatalf("container exited with status %s", status) } tmpDir, err := ioutil.TempDir("", "test-docker-restart-after-copy-") if err != nil { c.Fatalf("unable to make temporary directory: %s", err) } defer os.RemoveAll(tmpDir) dockerCmd(c, "cp", fmt.Sprintf("%s:/etc/issue", id), tmpDir) out, _ = dockerCmd(c, "start", "-a", id) msg := strings.TrimSpace(out) if msg != expectedMsg { c.Fatalf("expected %q but got %q", expectedMsg, msg) } } func (s *DockerSuite) TestCopyCreatedContainer(c *check.C) { dockerCmd(c, "create", "--name", "test_cp", "-v", "/test", "busybox") tmpDir, err := ioutil.TempDir("", "test") if err != nil { c.Fatalf("unable to make temporary directory: %s", err) } defer os.RemoveAll(tmpDir) dockerCmd(c, "cp", "test_cp:/bin/sh", tmpDir) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_cp_to_container_test.go ================================================ package main import ( "os" "github.com/go-check/check" ) // docker cp LOCALPATH CONTAINER:PATH // Try all of the test cases from the archive package which implements the // internals of `docker cp` and ensure that the behavior matches when actually // copying to and from containers. // Basic assumptions about SRC and DST: // 1. SRC must exist. // 2. If SRC ends with a trailing separator, it must be a directory. // 3. DST parent directory must exist. // 4. If DST exists as a file, it must not end with a trailing separator. // First get these easy error cases out of the way. // Test for error when SRC does not exist. func (s *DockerSuite) TestCpToErrSrcNotExists(c *check.C) { cID := makeTestContainer(c, testContainerOptions{}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-err-src-not-exists") defer os.RemoveAll(tmpDir) srcPath := cpPath(tmpDir, "file1") dstPath := containerCpPath(cID, "file1") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected IsNotExist error, but got nil instead") } if !isCpNotExist(err) { c.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when SRC ends in a trailing // path separator but it exists as a file. func (s *DockerSuite) TestCpToErrSrcNotDir(c *check.C) { cID := makeTestContainer(c, testContainerOptions{}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-err-src-not-dir") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := cpPathTrailingSep(tmpDir, "file1") dstPath := containerCpPath(cID, "testDir") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected IsNotDir error, but got nil instead") } if !isCpNotDir(err) { c.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Test for error when SRC is a valid file or directory, // bu the DST parent directory does not exist. func (s *DockerSuite) TestCpToErrDstParentNotExists(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-err-dst-parent-not-exists") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) // Try with a file source. srcPath := cpPath(tmpDir, "file1") dstPath := containerCpPath(cID, "/notExists", "file1") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected IsNotExist error, but got nil instead") } if !isCpNotExist(err) { c.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } // Try with a directory source. srcPath = cpPath(tmpDir, "dir1") if err := runDockerCp(c, srcPath, dstPath); err == nil { c.Fatal("expected IsNotExist error, but got nil instead") } if !isCpNotExist(err) { c.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when DST ends in a trailing path separator but exists as a // file. Also test that we cannot overwirite an existing directory with a // non-directory and cannot overwrite an existing func (s *DockerSuite) TestCpToErrDstNotDir(c *check.C) { cID := makeTestContainer(c, testContainerOptions{addContent: true}) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-err-dst-not-dir") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) // Try with a file source. srcPath := cpPath(tmpDir, "dir1/file1-1") dstPath := containerCpPathTrailingSep(cID, "file1") // The client should encounter an error trying to stat the destination // and then be unable to copy since the destination is asserted to be a // directory but does not exist. err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected DirNotExist error, but got nil instead") } if !isCpDirNotExist(err) { c.Fatalf("expected DirNotExist error, but got %T: %s", err, err) } // Try with a directory source. srcPath = cpPath(tmpDir, "dir1") // The client should encounter an error trying to stat the destination and // then decide to extract to the parent directory instead with a rebased // name in the source archive, but this directory would overwrite the // existing file with the same name. err = runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected CannotOverwriteNonDirWithDir error, but got nil instead") } if !isCannotOverwriteNonDirWithDir(err) { c.Fatalf("expected CannotOverwriteNonDirWithDir error, but got %T: %s", err, err) } } // Possibilities are reduced to the remaining 10 cases: // // case | srcIsDir | onlyDirContents | dstExists | dstIsDir | dstTrSep | action // =================================================================================================== // A | no | - | no | - | no | create file // B | no | - | no | - | yes | error // C | no | - | yes | no | - | overwrite file // D | no | - | yes | yes | - | create file in dst dir // E | yes | no | no | - | - | create dir, copy contents // F | yes | no | yes | no | - | error // G | yes | no | yes | yes | - | copy dir and contents // H | yes | yes | no | - | - | create dir, copy contents // I | yes | yes | yes | no | - | error // J | yes | yes | yes | yes | - | copy dir contents // // A. SRC specifies a file and DST (no trailing path separator) doesn't // exist. This should create a file with the name DST and copy the // contents of the source file into it. func (s *DockerSuite) TestCpToCaseA(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ workDir: "/root", command: makeCatFileCommand("itWorks.txt"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-a") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := cpPath(tmpDir, "file1") dstPath := containerCpPath(cID, "/root/itWorks.txt") if err := runDockerCp(c, srcPath, dstPath); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } if err := containerStartOutputEquals(c, cID, "file1\n"); err != nil { c.Fatal(err) } } // B. SRC specifies a file and DST (with trailing path separator) doesn't // exist. This should cause an error because the copy operation cannot // create a directory when copying a single file. func (s *DockerSuite) TestCpToCaseB(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ command: makeCatFileCommand("testDir/file1"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-b") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := cpPath(tmpDir, "file1") dstDir := containerCpPathTrailingSep(cID, "testDir") err := runDockerCp(c, srcPath, dstDir) if err == nil { c.Fatal("expected DirNotExists error, but got nil instead") } if !isCpDirNotExist(err) { c.Fatalf("expected DirNotExists error, but got %T: %s", err, err) } } // C. SRC specifies a file and DST exists as a file. This should overwrite // the file at DST with the contents of the source file. func (s *DockerSuite) TestCpToCaseC(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", command: makeCatFileCommand("file2"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-c") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := cpPath(tmpDir, "file1") dstPath := containerCpPath(cID, "/root/file2") // Ensure the container's file starts with the original content. if err := containerStartOutputEquals(c, cID, "file2\n"); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcPath, dstPath); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1's contents. if err := containerStartOutputEquals(c, cID, "file1\n"); err != nil { c.Fatal(err) } } // D. SRC specifies a file and DST exists as a directory. This should place // a copy of the source file inside it using the basename from SRC. Ensure // this works whether DST has a trailing path separator or not. func (s *DockerSuite) TestCpToCaseD(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, command: makeCatFileCommand("/dir1/file1"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-d") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcPath := cpPath(tmpDir, "file1") dstDir := containerCpPath(cID, "dir1") // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcPath, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1's contents. if err := containerStartOutputEquals(c, cID, "file1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. // Make new destination container. cID = makeTestContainer(c, testContainerOptions{ addContent: true, command: makeCatFileCommand("/dir1/file1"), }) defer deleteContainer(cID) dstDir = containerCpPathTrailingSep(cID, "dir1") // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcPath, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1's contents. if err := containerStartOutputEquals(c, cID, "file1\n"); err != nil { c.Fatal(err) } } // E. SRC specifies a directory and DST does not exist. This should create a // directory at DST and copy the contents of the SRC directory into the DST // directory. Ensure this works whether DST has a trailing path separator or // not. func (s *DockerSuite) TestCpToCaseE(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ command: makeCatFileCommand("/testDir/file1-1"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-e") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := cpPath(tmpDir, "dir1") dstDir := containerCpPath(cID, "testDir") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. // Make new destination container. cID = makeTestContainer(c, testContainerOptions{ command: makeCatFileCommand("/testDir/file1-1"), }) defer deleteContainer(cID) dstDir = containerCpPathTrailingSep(cID, "testDir") err := runDockerCp(c, srcDir, dstDir) if err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } } // F. SRC specifies a directory and DST exists as a file. This should cause an // error as it is not possible to overwrite a file with a directory. func (s *DockerSuite) TestCpToCaseF(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-f") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := cpPath(tmpDir, "dir1") dstFile := containerCpPath(cID, "/root/file1") err := runDockerCp(c, srcDir, dstFile) if err == nil { c.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if !isCpCannotCopyDir(err) { c.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // G. SRC specifies a directory and DST exists as a directory. This should copy // the SRC directory and all its contents to the DST directory. Ensure this // works whether DST has a trailing path separator or not. func (s *DockerSuite) TestCpToCaseG(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", command: makeCatFileCommand("dir2/dir1/file1-1"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-g") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := cpPath(tmpDir, "dir1") dstDir := containerCpPath(cID, "/root/dir2") // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. // Make new destination container. cID = makeTestContainer(c, testContainerOptions{ addContent: true, command: makeCatFileCommand("/dir2/dir1/file1-1"), }) defer deleteContainer(cID) dstDir = containerCpPathTrailingSep(cID, "/dir2") // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } } // H. SRC specifies a directory's contents only and DST does not exist. This // should create a directory at DST and copy the contents of the SRC // directory (but not the directory itself) into the DST directory. Ensure // this works whether DST has a trailing path separator or not. func (s *DockerSuite) TestCpToCaseH(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ command: makeCatFileCommand("/testDir/file1-1"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-h") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := cpPathTrailingSep(tmpDir, "dir1") + "." dstDir := containerCpPath(cID, "testDir") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. // Make new destination container. cID = makeTestContainer(c, testContainerOptions{ command: makeCatFileCommand("/testDir/file1-1"), }) defer deleteContainer(cID) dstDir = containerCpPathTrailingSep(cID, "testDir") if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } } // I. SRC specifies a direcotry's contents only and DST exists as a file. This // should cause an error as it is not possible to overwrite a file with a // directory. func (s *DockerSuite) TestCpToCaseI(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-i") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := cpPathTrailingSep(tmpDir, "dir1") + "." dstFile := containerCpPath(cID, "/root/file1") err := runDockerCp(c, srcDir, dstFile) if err == nil { c.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if !isCpCannotCopyDir(err) { c.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // J. SRC specifies a directory's contents only and DST exists as a directory. // This should copy the contents of the SRC directory (but not the directory // itself) into the DST directory. Ensure this works whether DST has a // trailing path separator or not. func (s *DockerSuite) TestCpToCaseJ(c *check.C) { cID := makeTestContainer(c, testContainerOptions{ addContent: true, workDir: "/root", command: makeCatFileCommand("/dir2/file1-1"), }) defer deleteContainer(cID) tmpDir := getTestDir(c, "test-cp-to-case-j") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) srcDir := cpPathTrailingSep(tmpDir, "dir1") + "." dstDir := containerCpPath(cID, "/dir2") // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } // Now try again but using a trailing path separator for dstDir. // Make new destination container. cID = makeTestContainer(c, testContainerOptions{ command: makeCatFileCommand("/dir2/file1-1"), }) defer deleteContainer(cID) dstDir = containerCpPathTrailingSep(cID, "/dir2") // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } if err := runDockerCp(c, srcDir, dstDir); err != nil { c.Fatalf("unexpected error %T: %s", err, err) } // Should now contain file1-1's contents. if err := containerStartOutputEquals(c, cID, "file1-1\n"); err != nil { c.Fatal(err) } } // The `docker cp` command should also ensure that you cannot // write to a container rootfs that is marked as read-only. func (s *DockerSuite) TestCpToErrReadOnlyRootfs(c *check.C) { tmpDir := getTestDir(c, "test-cp-to-err-read-only-rootfs") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) cID := makeTestContainer(c, testContainerOptions{ readOnly: true, workDir: "/root", command: makeCatFileCommand("shouldNotExist"), }) defer deleteContainer(cID) srcPath := cpPath(tmpDir, "file1") dstPath := containerCpPath(cID, "/root/shouldNotExist") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected ErrContainerRootfsReadonly error, but got nil instead") } if !isCpCannotCopyReadOnly(err) { c.Fatalf("expected ErrContainerRootfsReadonly error, but got %T: %s", err, err) } // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } } // The `docker cp` command should also ensure that you // cannot write to a volume that is mounted as read-only. func (s *DockerSuite) TestCpToErrReadOnlyVolume(c *check.C) { tmpDir := getTestDir(c, "test-cp-to-err-read-only-volume") defer os.RemoveAll(tmpDir) makeTestContentInDir(c, tmpDir) cID := makeTestContainer(c, testContainerOptions{ volumes: defaultVolumes(tmpDir), workDir: "/root", command: makeCatFileCommand("/vol_ro/shouldNotExist"), }) defer deleteContainer(cID) srcPath := cpPath(tmpDir, "file1") dstPath := containerCpPath(cID, "/vol_ro/shouldNotExist") err := runDockerCp(c, srcPath, dstPath) if err == nil { c.Fatal("expected ErrVolumeReadonly error, but got nil instead") } if !isCpCannotCopyReadOnly(err) { c.Fatalf("expected ErrVolumeReadonly error, but got %T: %s", err, err) } // Ensure that dstPath doesn't exist. if err := containerStartOutputEquals(c, cID, ""); err != nil { c.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_cp_utils.go ================================================ package main import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "github.com/docker/docker/pkg/archive" "github.com/go-check/check" ) type FileType uint32 const ( Regular FileType = iota Dir Symlink ) type FileData struct { filetype FileType path string contents string } func (fd FileData) creationCommand() string { var command string switch fd.filetype { case Regular: // Don't overwrite the file if it already exists! command = fmt.Sprintf("if [ ! -f %s ]; then echo %q > %s; fi", fd.path, fd.contents, fd.path) case Dir: command = fmt.Sprintf("mkdir -p %s", fd.path) case Symlink: command = fmt.Sprintf("ln -fs %s %s", fd.contents, fd.path) } return command } func mkFilesCommand(fds []FileData) string { commands := make([]string, len(fds)) for i, fd := range fds { commands[i] = fd.creationCommand() } return strings.Join(commands, " && ") } var defaultFileData = []FileData{ {Regular, "file1", "file1"}, {Regular, "file2", "file2"}, {Regular, "file3", "file3"}, {Regular, "file4", "file4"}, {Regular, "file5", "file5"}, {Regular, "file6", "file6"}, {Regular, "file7", "file7"}, {Dir, "dir1", ""}, {Regular, "dir1/file1-1", "file1-1"}, {Regular, "dir1/file1-2", "file1-2"}, {Dir, "dir2", ""}, {Regular, "dir2/file2-1", "file2-1"}, {Regular, "dir2/file2-2", "file2-2"}, {Dir, "dir3", ""}, {Regular, "dir3/file3-1", "file3-1"}, {Regular, "dir3/file3-2", "file3-2"}, {Dir, "dir4", ""}, {Regular, "dir4/file3-1", "file4-1"}, {Regular, "dir4/file3-2", "file4-2"}, {Dir, "dir5", ""}, {Symlink, "symlink1", "target1"}, {Symlink, "symlink2", "target2"}, } func defaultMkContentCommand() string { return mkFilesCommand(defaultFileData) } func makeTestContentInDir(c *check.C, dir string) { for _, fd := range defaultFileData { path := filepath.Join(dir, filepath.FromSlash(fd.path)) switch fd.filetype { case Regular: if err := ioutil.WriteFile(path, []byte(fd.contents+"\n"), os.FileMode(0666)); err != nil { c.Fatal(err) } case Dir: if err := os.Mkdir(path, os.FileMode(0777)); err != nil { c.Fatal(err) } case Symlink: if err := os.Symlink(fd.contents, path); err != nil { c.Fatal(err) } } } } type testContainerOptions struct { addContent bool readOnly bool volumes []string workDir string command string } func makeTestContainer(c *check.C, options testContainerOptions) (containerID string) { if options.addContent { mkContentCmd := defaultMkContentCommand() if options.command == "" { options.command = mkContentCmd } else { options.command = fmt.Sprintf("%s && %s", defaultMkContentCommand(), options.command) } } if options.command == "" { options.command = "#(nop)" } args := []string{"run", "-d"} for _, volume := range options.volumes { args = append(args, "-v", volume) } if options.workDir != "" { args = append(args, "-w", options.workDir) } if options.readOnly { args = append(args, "--read-only") } args = append(args, "busybox", "/bin/sh", "-c", options.command) out, status := dockerCmd(c, args...) if status != 0 { c.Fatalf("failed to run container, status %d: %s", status, out) } containerID = strings.TrimSpace(out) out, status = dockerCmd(c, "wait", containerID) if status != 0 { c.Fatalf("failed to wait for test container container, status %d: %s", status, out) } if exitCode := strings.TrimSpace(out); exitCode != "0" { logs, status := dockerCmd(c, "logs", containerID) if status != 0 { logs = "UNABLE TO GET LOGS" } c.Fatalf("failed to make test container, exit code (%d): %s", exitCode, logs) } return } func makeCatFileCommand(path string) string { return fmt.Sprintf("if [ -f %s ]; then cat %s; fi", path, path) } func cpPath(pathElements ...string) string { localizedPathElements := make([]string, len(pathElements)) for i, path := range pathElements { localizedPathElements[i] = filepath.FromSlash(path) } return strings.Join(localizedPathElements, string(filepath.Separator)) } func cpPathTrailingSep(pathElements ...string) string { return fmt.Sprintf("%s%c", cpPath(pathElements...), filepath.Separator) } func containerCpPath(containerID string, pathElements ...string) string { joined := strings.Join(pathElements, "/") return fmt.Sprintf("%s:%s", containerID, joined) } func containerCpPathTrailingSep(containerID string, pathElements ...string) string { return fmt.Sprintf("%s/", containerCpPath(containerID, pathElements...)) } func runDockerCp(c *check.C, src, dst string) (err error) { c.Logf("running `docker cp %s %s`", src, dst) args := []string{"cp", src, dst} out, _, err := runCommandWithOutput(exec.Command(dockerBinary, args...)) if err != nil { err = fmt.Errorf("error executing `docker cp` command: %s: %s", err, out) } return } func startContainerGetOutput(c *check.C, cID string) (out string, err error) { c.Logf("running `docker start -a %s`", cID) args := []string{"start", "-a", cID} out, _, err = runCommandWithOutput(exec.Command(dockerBinary, args...)) if err != nil { err = fmt.Errorf("error executing `docker start` command: %s: %s", err, out) } return } func getTestDir(c *check.C, label string) (tmpDir string) { var err error if tmpDir, err = ioutil.TempDir("", label); err != nil { c.Fatalf("unable to make temporary directory: %s", err) } return } func isCpNotExist(err error) bool { return strings.Contains(err.Error(), "no such file or directory") || strings.Contains(err.Error(), "cannot find the file specified") } func isCpDirNotExist(err error) bool { return strings.Contains(err.Error(), archive.ErrDirNotExists.Error()) } func isCpNotDir(err error) bool { return strings.Contains(err.Error(), archive.ErrNotDirectory.Error()) || strings.Contains(err.Error(), "filename, directory name, or volume label syntax is incorrect") } func isCpCannotCopyDir(err error) bool { return strings.Contains(err.Error(), archive.ErrCannotCopyDir.Error()) } func isCpCannotCopyReadOnly(err error) bool { return strings.Contains(err.Error(), "marked read-only") } func isCannotOverwriteNonDirWithDir(err error) bool { return strings.Contains(err.Error(), "cannot overwrite non-directory") } func fileContentEquals(c *check.C, filename, contents string) (err error) { c.Logf("checking that file %q contains %q\n", filename, contents) fileBytes, err := ioutil.ReadFile(filename) if err != nil { return } expectedBytes, err := ioutil.ReadAll(strings.NewReader(contents)) if err != nil { return } if !bytes.Equal(fileBytes, expectedBytes) { err = fmt.Errorf("file content not equal - expected %q, got %q", string(expectedBytes), string(fileBytes)) } return } func containerStartOutputEquals(c *check.C, cID, contents string) (err error) { c.Logf("checking that container %q start output contains %q\n", cID, contents) out, err := startContainerGetOutput(c, cID) if err != nil { return err } if out != contents { err = fmt.Errorf("output contents not equal - expected %q, got %q", contents, out) } return } func defaultVolumes(tmpDir string) []string { if SameHostDaemon.Condition() { return []string{ "/vol1", fmt.Sprintf("%s:/vol2", tmpDir), fmt.Sprintf("%s:/vol3", filepath.Join(tmpDir, "vol3")), fmt.Sprintf("%s:/vol_ro:ro", filepath.Join(tmpDir, "vol_ro")), } } // Can't bind-mount volumes with separate host daemon. return []string{"/vol1", "/vol2", "/vol3", "/vol_ro:/vol_ro:ro"} } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_create_test.go ================================================ package main import ( "encoding/json" "fmt" "os" "reflect" "strings" "time" "github.com/docker/docker/pkg/nat" "github.com/go-check/check" ) // Make sure we can create a simple container with some args func (s *DockerSuite) TestCreateArgs(c *check.C) { out, _ := dockerCmd(c, "create", "busybox", "command", "arg1", "arg2", "arg with space") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "inspect", cleanedContainerID) containers := []struct { ID string Created time.Time Path string Args []string Image string }{} if err := json.Unmarshal([]byte(out), &containers); err != nil { c.Fatalf("Error inspecting the container: %s", err) } if len(containers) != 1 { c.Fatalf("Unexpected container count. Expected 0, received: %d", len(containers)) } cont := containers[0] if cont.Path != "command" { c.Fatalf("Unexpected container path. Expected command, received: %s", cont.Path) } b := false expected := []string{"arg1", "arg2", "arg with space"} for i, arg := range expected { if arg != cont.Args[i] { b = true break } } if len(cont.Args) != len(expected) || b { c.Fatalf("Unexpected args. Expected %v, received: %v", expected, cont.Args) } } // Make sure we can set hostconfig options too func (s *DockerSuite) TestCreateHostConfig(c *check.C) { out, _ := dockerCmd(c, "create", "-P", "busybox", "echo") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "inspect", cleanedContainerID) containers := []struct { HostConfig *struct { PublishAllPorts bool } }{} if err := json.Unmarshal([]byte(out), &containers); err != nil { c.Fatalf("Error inspecting the container: %s", err) } if len(containers) != 1 { c.Fatalf("Unexpected container count. Expected 0, received: %d", len(containers)) } cont := containers[0] if cont.HostConfig == nil { c.Fatalf("Expected HostConfig, got none") } if !cont.HostConfig.PublishAllPorts { c.Fatalf("Expected PublishAllPorts, got false") } } func (s *DockerSuite) TestCreateWithPortRange(c *check.C) { out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "inspect", cleanedContainerID) containers := []struct { HostConfig *struct { PortBindings map[nat.Port][]nat.PortBinding } }{} if err := json.Unmarshal([]byte(out), &containers); err != nil { c.Fatalf("Error inspecting the container: %s", err) } if len(containers) != 1 { c.Fatalf("Unexpected container count. Expected 0, received: %d", len(containers)) } cont := containers[0] if cont.HostConfig == nil { c.Fatalf("Expected HostConfig, got none") } if len(cont.HostConfig.PortBindings) != 4 { c.Fatalf("Expected 4 ports bindings, got %d", len(cont.HostConfig.PortBindings)) } for k, v := range cont.HostConfig.PortBindings { if len(v) != 1 { c.Fatalf("Expected 1 ports binding, for the port %s but found %s", k, v) } if k.Port() != v[0].HostPort { c.Fatalf("Expected host port %d to match published port %d", k.Port(), v[0].HostPort) } } } func (s *DockerSuite) TestCreateWithiLargePortRange(c *check.C) { out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "inspect", cleanedContainerID) containers := []struct { HostConfig *struct { PortBindings map[nat.Port][]nat.PortBinding } }{} if err := json.Unmarshal([]byte(out), &containers); err != nil { c.Fatalf("Error inspecting the container: %s", err) } if len(containers) != 1 { c.Fatalf("Unexpected container count. Expected 0, received: %d", len(containers)) } cont := containers[0] if cont.HostConfig == nil { c.Fatalf("Expected HostConfig, got none") } if len(cont.HostConfig.PortBindings) != 65535 { c.Fatalf("Expected 65535 ports bindings, got %d", len(cont.HostConfig.PortBindings)) } for k, v := range cont.HostConfig.PortBindings { if len(v) != 1 { c.Fatalf("Expected 1 ports binding, for the port %s but found %s", k, v) } if k.Port() != v[0].HostPort { c.Fatalf("Expected host port %d to match published port %d", k.Port(), v[0].HostPort) } } } // "test123" should be printed by docker create + start func (s *DockerSuite) TestCreateEchoStdout(c *check.C) { out, _ := dockerCmd(c, "create", "busybox", "echo", "test123") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID) if out != "test123\n" { c.Errorf("container should've printed 'test123', got %q", out) } } func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) { testRequires(c, SameHostDaemon) name := "test_create_volume" dockerCmd(c, "create", "--name", name, "-v", "/foo", "busybox") dir, err := inspectMountSourceField(name, "/foo") if err != nil { c.Fatalf("Error getting volume host path: %q", err) } if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) { c.Fatalf("Volume was not created") } if err != nil { c.Fatalf("Error statting volume host path: %q", err) } } func (s *DockerSuite) TestCreateLabels(c *check.C) { name := "test_create_labels" expected := map[string]string{"k1": "v1", "k2": "v2"} dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox") actual := make(map[string]string) err := inspectFieldAndMarshall(name, "Config.Labels", &actual) if err != nil { c.Fatal(err) } if !reflect.DeepEqual(expected, actual) { c.Fatalf("Expected %s got %s", expected, actual) } } func (s *DockerSuite) TestCreateLabelFromImage(c *check.C) { imageName := "testcreatebuildlabel" _, err := buildImage(imageName, `FROM busybox LABEL k1=v1 k2=v2`, true) if err != nil { c.Fatal(err) } name := "test_create_labels_from_image" expected := map[string]string{"k2": "x", "k3": "v3"} dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName) actual := make(map[string]string) err = inspectFieldAndMarshall(name, "Config.Labels", &actual) if err != nil { c.Fatal(err) } if !reflect.DeepEqual(expected, actual) { c.Fatalf("Expected %s got %s", expected, actual) } } func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) { out, _ := dockerCmd(c, "run", "-h", "web.0", "busybox", "hostname") if strings.TrimSpace(out) != "web.0" { c.Fatalf("hostname not set, expected `web.0`, got: %s", out) } } func (s *DockerSuite) TestCreateRM(c *check.C) { // Test to make sure we can 'rm' a new container that is in // "Created" state, and has ever been run. Test "rm -f" too. // create a container out, _ := dockerCmd(c, "create", "busybox") cID := strings.TrimSpace(out) dockerCmd(c, "rm", cID) // Now do it again so we can "rm -f" this time out, _ = dockerCmd(c, "create", "busybox") cID = strings.TrimSpace(out) dockerCmd(c, "rm", "-f", cID) } func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "create", "busybox") id := strings.TrimSpace(out) dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_daemon_experimental_test.go ================================================ // +build daemon,experimental package main import ( "os/exec" "strings" "github.com/go-check/check" ) func assertNetwork(c *check.C, d *Daemon, name string) { out, err := d.Cmd("network", "ls") c.Assert(err, check.IsNil) lines := strings.Split(out, "\n") for i := 1; i < len(lines)-1; i++ { if strings.Contains(lines[i], name) { return } } c.Fatalf("Network %s not found in network ls o/p", name) } func (s *DockerDaemonSuite) TestDaemonDefaultNetwork(c *check.C) { d := s.d networkName := "testdefault" err := d.StartWithBusybox("--default-network", "bridge:"+networkName) c.Assert(err, check.IsNil) _, err = d.Cmd("run", "busybox", "true") c.Assert(err, check.IsNil) assertNetwork(c, d, networkName) ifconfigCmd := exec.Command("ifconfig", networkName) _, _, _, err = runCommandWithStdoutStderr(ifconfigCmd) c.Assert(err, check.IsNil) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_daemon_test.go ================================================ // +build daemon package main import ( "encoding/json" "fmt" "io/ioutil" "net" "os" "os/exec" "path/filepath" "regexp" "strconv" "strings" "time" "github.com/docker/libnetwork/iptables" "github.com/docker/libtrust" "github.com/go-check/check" ) func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } if out, err := s.d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top1: err=%v\n%s", err, out) } // --restart=no by default if out, err := s.d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top2: err=%v\n%s", err, out) } testRun := func(m map[string]bool, prefix string) { var format string for cont, shouldRun := range m { out, err := s.d.Cmd("ps") if err != nil { c.Fatalf("Could not run ps: err=%v\n%q", err, out) } if shouldRun { format = "%scontainer %q is not running" } else { format = "%scontainer %q is running" } if shouldRun != strings.Contains(out, cont) { c.Fatalf(format, prefix, cont) } } } testRun(map[string]bool{"top1": true, "top2": true}, "") if err := s.d.Restart(); err != nil { c.Fatalf("Could not restart daemon: %v", err) } testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") } func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } if out, err := s.d.Cmd("run", "-d", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil { c.Fatal(err, out) } if err := s.d.Restart(); err != nil { c.Fatal(err) } if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil { c.Fatal(err) } if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil { c.Fatal(err, out) } out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1") c.Assert(err, check.IsNil) if _, err := inspectMountPointJSON(out, "/foo"); err != nil { c.Fatalf("Expected volume to exist: /foo, error: %v\n", err) } } func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) { if err := s.d.Start("--iptables=false"); err != nil { c.Fatalf("we should have been able to start the daemon with passing iptables=false: %v", err) } } // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and // no longer has an IP associated, we should gracefully handle that case and associate // an IP with it rather than fail daemon start func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) { // rather than depending on brctl commands to verify docker0 is created and up // let's start the daemon and stop it, and then make a modification to run the // actual test if err := s.d.Start(); err != nil { c.Fatalf("Could not start daemon: %v", err) } if err := s.d.Stop(); err != nil { c.Fatalf("Could not stop daemon: %v", err) } // now we will remove the ip from docker0 and then try starting the daemon ipCmd := exec.Command("ip", "addr", "flush", "dev", "docker0") stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd) if err != nil { c.Fatalf("failed to remove docker0 IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr) } if err := s.d.Start(); err != nil { warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix" c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning) } } func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: %s, %v", out, err) } // get output from iptables with container running ipTablesSearchString := "tcp dpt:80" ipTablesCmd := exec.Command("iptables", "-nvL") out, _, err := runCommandWithOutput(ipTablesCmd) if err != nil { c.Fatalf("Could not run iptables -nvL: %s, %v", out, err) } if !strings.Contains(out, ipTablesSearchString) { c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out) } if err := s.d.Stop(); err != nil { c.Fatalf("Could not stop daemon: %v", err) } // get output from iptables after restart ipTablesCmd = exec.Command("iptables", "-nvL") out, _, err = runCommandWithOutput(ipTablesCmd) if err != nil { c.Fatalf("Could not run iptables -nvL: %s, %v", out, err) } if strings.Contains(out, ipTablesSearchString) { c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, out) } } func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: %s, %v", out, err) } // get output from iptables with container running ipTablesSearchString := "tcp dpt:80" ipTablesCmd := exec.Command("iptables", "-nvL") out, _, err := runCommandWithOutput(ipTablesCmd) if err != nil { c.Fatalf("Could not run iptables -nvL: %s, %v", out, err) } if !strings.Contains(out, ipTablesSearchString) { c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out) } if err := s.d.Restart(); err != nil { c.Fatalf("Could not restart daemon: %v", err) } // make sure the container is not running runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", "top") if err != nil { c.Fatalf("Could not inspect on container: %s, %v", out, err) } if strings.TrimSpace(runningOut) != "true" { c.Fatalf("Container should have been restarted after daemon restart. Status running should have been true but was: %q", strings.TrimSpace(runningOut)) } // get output from iptables after restart ipTablesCmd = exec.Command("iptables", "-nvL") out, _, err = runCommandWithOutput(ipTablesCmd) if err != nil { c.Fatalf("Could not run iptables -nvL: %s, %v", out, err) } if !strings.Contains(out, ipTablesSearchString) { c.Fatalf("iptables output after restart should have contained %q, but was %q", ipTablesSearchString, out) } } // TestDaemonIPv6Enabled checks that when the daemon is started with --ipv6=true that the docker0 bridge // has the fe80::1 address and that a container is assigned a link-local address func (s *DockerSuite) TestDaemonIPv6Enabled(c *check.C) { testRequires(c, IPv6) if err := setupV6(); err != nil { c.Fatal("Could not set up host for IPv6 tests") } d := NewDaemon(c) if err := d.StartWithBusybox("--ipv6"); err != nil { c.Fatal(err) } defer d.Stop() iface, err := net.InterfaceByName("docker0") if err != nil { c.Fatalf("Error getting docker0 interface: %v", err) } addrs, err := iface.Addrs() if err != nil { c.Fatalf("Error getting addresses for docker0 interface: %v", err) } var found bool expected := "fe80::1/64" for i := range addrs { if addrs[i].String() == expected { found = true } } if !found { c.Fatalf("Bridge does not have an IPv6 Address") } if out, err := d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil { c.Fatalf("Could not run container: %s, %v", out, err) } out, err := d.Cmd("inspect", "--format", "'{{.NetworkSettings.LinkLocalIPv6Address}}'", "ipv6test") out = strings.Trim(out, " \r\n'") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } if ip := net.ParseIP(out); ip == nil { c.Fatalf("Container should have a link-local IPv6 address") } out, err = d.Cmd("inspect", "--format", "'{{.NetworkSettings.GlobalIPv6Address}}'", "ipv6test") out = strings.Trim(out, " \r\n'") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } if ip := net.ParseIP(out); ip != nil { c.Fatalf("Container should not have a global IPv6 address: %v", out) } if err := teardownV6(); err != nil { c.Fatal("Could not perform teardown for IPv6 tests") } } // TestDaemonIPv6FixedCIDR checks that when the daemon is started with --ipv6=true and a fixed CIDR // that running containers are given a link-local and global IPv6 address func (s *DockerSuite) TestDaemonIPv6FixedCIDR(c *check.C) { testRequires(c, IPv6) if err := setupV6(); err != nil { c.Fatal("Could not set up host for IPv6 tests") } d := NewDaemon(c) if err := d.StartWithBusybox("--ipv6", "--fixed-cidr-v6='2001:db8:1::/64'"); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } defer d.Stop() if out, err := d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest"); err != nil { c.Fatalf("Could not run container: %s, %v", out, err) } out, err := d.Cmd("inspect", "--format", "'{{.NetworkSettings.LinkLocalIPv6Address}}'", "ipv6test") out = strings.Trim(out, " \r\n'") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } if ip := net.ParseIP(out); ip == nil { c.Fatalf("Container should have a link-local IPv6 address") } out, err = d.Cmd("inspect", "--format", "'{{.NetworkSettings.GlobalIPv6Address}}'", "ipv6test") out = strings.Trim(out, " \r\n'") if err != nil { c.Fatalf("Error inspecting container: %s, %v", out, err) } if ip := net.ParseIP(out); ip == nil { c.Fatalf("Container should have a global IPv6 address") } if err := teardownV6(); err != nil { c.Fatal("Could not perform teardown for IPv6 tests") } } func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) { c.Assert(s.d.Start("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level")) } func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) { if err := s.d.Start("--log-level=debug"); err != nil { c.Fatal(err) } content, _ := ioutil.ReadFile(s.d.logFile.Name()) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) { // we creating new daemons to create new logFile if err := s.d.Start("--log-level=fatal"); err != nil { c.Fatal(err) } content, _ := ioutil.ReadFile(s.d.logFile.Name()) if strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { if err := s.d.Start("-D"); err != nil { c.Fatal(err) } content, _ := ioutil.ReadFile(s.d.logFile.Name()) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { if err := s.d.Start("--debug"); err != nil { c.Fatal(err) } content, _ := ioutil.ReadFile(s.d.logFile.Name()) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) { if err := s.d.Start("--debug", "--log-level=fatal"); err != nil { c.Fatal(err) } content, _ := ioutil.ReadFile(s.d.logFile.Name()) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) } } func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) { listeningPorts := [][]string{ {"0.0.0.0", "0.0.0.0", "5678"}, {"127.0.0.1", "127.0.0.1", "1234"}, {"localhost", "127.0.0.1", "1235"}, } cmdArgs := []string{} for _, hostDirective := range listeningPorts { cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2])) } if err := s.d.StartWithBusybox(cmdArgs...); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } for _, hostDirective := range listeningPorts { output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true") if err == nil { c.Fatalf("Container should not start, expected port already allocated error: %q", output) } else if !strings.Contains(output, "port is already allocated") { c.Fatalf("Expected port is already allocated error: %q", output) } } } func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) { // TODO: skip or update for Windows daemon os.Remove("/etc/docker/key.json") if err := s.d.Start(); err != nil { c.Fatalf("Could not start daemon: %v", err) } s.d.Stop() k, err := libtrust.LoadKeyFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error opening key file") } kid := k.KeyID() // Test Key ID is a valid fingerprint (e.g. QQXN:JY5W:TBXI:MK3X:GX6P:PD5D:F56N:NHCS:LVRZ:JA46:R24J:XEFF) if len(kid) != 59 { c.Fatalf("Bad key ID: %s", kid) } } func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) { // TODO: skip or update for Windows daemon os.Remove("/etc/docker/key.json") k1, err := libtrust.GenerateECP256PrivateKey() if err != nil { c.Fatalf("Error generating private key: %s", err) } if err := os.MkdirAll(filepath.Join(os.Getenv("HOME"), ".docker"), 0755); err != nil { c.Fatalf("Error creating .docker directory: %s", err) } if err := libtrust.SaveKey(filepath.Join(os.Getenv("HOME"), ".docker", "key.json"), k1); err != nil { c.Fatalf("Error saving private key: %s", err) } if err := s.d.Start(); err != nil { c.Fatalf("Could not start daemon: %v", err) } s.d.Stop() k2, err := libtrust.LoadKeyFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error opening key file") } if k1.KeyID() != k2.KeyID() { c.Fatalf("Key not migrated") } } // GH#11320 - verify that the daemon exits on failure properly // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) { //attempt to start daemon with incorrect flags (we know -b and --bip conflict) if err := s.d.Start("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { //verify we got the right error if !strings.Contains(err.Error(), "Daemon exited and never started") { c.Fatalf("Expected daemon not to start, got %v", err) } // look in the log and make sure we got the message that daemon is shutting down runCmd := exec.Command("grep", "Error starting daemon", s.d.LogfileName()) if out, _, err := runCommandWithOutput(runCmd); err != nil { c.Fatalf("Expected 'Error starting daemon' message; but doesn't exist in log: %q, err: %v", out, err) } } else { //if we didn't get an error and the daemon is running, this is a failure c.Fatal("Conflicting options should cause the daemon to error out with a failure") } } func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) { d := s.d err := d.Start("--bridge", "nosuchbridge") c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail")) defer d.Restart() bridgeName := "external-bridge" bridgeIp := "192.169.1.1/24" _, bridgeIPNet, _ := net.ParseCIDR(bridgeIp) out, err := createInterface(c, "bridge", bridgeName, bridgeIp) c.Assert(err, check.IsNil, check.Commentf(out)) defer deleteInterface(c, bridgeName) err = d.StartWithBusybox("--bridge", bridgeName) c.Assert(err, check.IsNil) ipTablesSearchString := bridgeIPNet.String() ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL") out, _, err = runCommandWithOutput(ipTablesCmd) c.Assert(err, check.IsNil) c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)) _, err = d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top") c.Assert(err, check.IsNil) containerIp := d.findContainerIP("ExtContainer") ip := net.ParseIP(containerIp) c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, check.Commentf("Container IP-Address must be in the same subnet range : %s", containerIp)) } func createInterface(c *check.C, ifType string, ifName string, ipNet string) (string, error) { args := []string{"link", "add", "name", ifName, "type", ifType} ipLinkCmd := exec.Command("ip", args...) out, _, err := runCommandWithOutput(ipLinkCmd) if err != nil { return out, err } ifCfgCmd := exec.Command("ifconfig", ifName, ipNet, "up") out, _, err = runCommandWithOutput(ifCfgCmd) return out, err } func deleteInterface(c *check.C, ifName string) { ifCmd := exec.Command("ip", "link", "delete", ifName) out, _, err := runCommandWithOutput(ifCmd) c.Assert(err, check.IsNil, check.Commentf(out)) flushCmd := exec.Command("iptables", "-t", "nat", "--flush") out, _, err = runCommandWithOutput(flushCmd) c.Assert(err, check.IsNil, check.Commentf(out)) flushCmd = exec.Command("iptables", "--flush") out, _, err = runCommandWithOutput(flushCmd) c.Assert(err, check.IsNil, check.Commentf(out)) } func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) { // TestDaemonBridgeIP Steps // 1. Delete the existing docker0 Bridge // 2. Set --bip daemon configuration and start the new Docker Daemon // 3. Check if the bip config has taken effect using ifconfig and iptables commands // 4. Launch a Container and make sure the IP-Address is in the expected subnet // 5. Delete the docker0 Bridge // 6. Restart the Docker Daemon (via defered action) // This Restart takes care of bringing docker0 interface back to auto-assigned IP defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIp := "192.169.1.1/24" ip, bridgeIPNet, _ := net.ParseCIDR(bridgeIp) err := d.StartWithBusybox("--bip", bridgeIp) c.Assert(err, check.IsNil) defer d.Restart() ifconfigSearchString := ip.String() ifconfigCmd := exec.Command("ifconfig", defaultNetworkBridge) out, _, _, err := runCommandWithStdoutStderr(ifconfigCmd) c.Assert(err, check.IsNil) c.Assert(strings.Contains(out, ifconfigSearchString), check.Equals, true, check.Commentf("ifconfig output should have contained %q, but was %q", ifconfigSearchString, out)) ipTablesSearchString := bridgeIPNet.String() ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL") out, _, err = runCommandWithOutput(ipTablesCmd) c.Assert(err, check.IsNil) c.Assert(strings.Contains(out, ipTablesSearchString), check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", ipTablesSearchString, out)) out, err = d.Cmd("run", "-d", "--name", "test", "busybox", "top") c.Assert(err, check.IsNil) containerIp := d.findContainerIP("test") ip = net.ParseIP(containerIp) c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, check.Commentf("Container IP-Address must be in the same subnet range : %s", containerIp)) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonRestartWithBridgeIPChange(c *check.C) { if err := s.d.Start(); err != nil { c.Fatalf("Could not start daemon: %v", err) } defer s.d.Restart() if err := s.d.Stop(); err != nil { c.Fatalf("Could not stop daemon: %v", err) } // now we will change the docker0's IP and then try starting the daemon bridgeIP := "192.169.100.1/24" _, bridgeIPNet, _ := net.ParseCIDR(bridgeIP) ipCmd := exec.Command("ifconfig", "docker0", bridgeIP) stdout, stderr, _, err := runCommandWithStdoutStderr(ipCmd) if err != nil { c.Fatalf("failed to change docker0's IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr) } if err := s.d.Start("--bip", bridgeIP); err != nil { c.Fatalf("Could not start daemon: %v", err) } //check if the iptables contains new bridgeIP MASQUERADE rule ipTablesSearchString := bridgeIPNet.String() ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL") out, _, err := runCommandWithOutput(ipTablesCmd) if err != nil { c.Fatalf("Could not run iptables -nvL: %s, %v", out, err) } if !strings.Contains(out, ipTablesSearchString) { c.Fatalf("iptables output should have contained new MASQUERADE rule with IP %q, but was %q", ipTablesSearchString, out) } } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIp := "192.169.1.1/24" out, err := createInterface(c, "bridge", bridgeName, bridgeIp) c.Assert(err, check.IsNil, check.Commentf(out)) defer deleteInterface(c, bridgeName) args := []string{"--bridge", bridgeName, "--fixed-cidr", "192.169.1.0/30"} err = d.StartWithBusybox(args...) c.Assert(err, check.IsNil) defer d.Restart() for i := 0; i < 4; i++ { cName := "Container" + strconv.Itoa(i) out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") if err != nil { c.Assert(strings.Contains(out, "no available ip addresses"), check.Equals, true, check.Commentf("Could not run a Container : %s %s", err.Error(), out)) } } } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIp := "192.169.1.1" bridgeIpNet := fmt.Sprintf("%s/24", bridgeIp) err := d.StartWithBusybox("--bip", bridgeIpNet) c.Assert(err, check.IsNil) defer d.Restart() expectedMessage := fmt.Sprintf("default via %s dev", bridgeIp) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'", bridgeIp, strings.TrimSpace(out))) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) { defaultNetworkBridge := "docker0" deleteInterface(c, defaultNetworkBridge) d := s.d bridgeIp := "192.169.1.1" bridgeIpNet := fmt.Sprintf("%s/24", bridgeIp) gatewayIp := "192.169.1.254" err := d.StartWithBusybox("--bip", bridgeIpNet, "--default-gateway", gatewayIp) c.Assert(err, check.IsNil) defer d.Restart() expectedMessage := fmt.Sprintf("default via %s dev", gatewayIp) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, check.Commentf("Explicit default gateway should be %s, but default route was '%s'", gatewayIp, strings.TrimSpace(out))) deleteInterface(c, defaultNetworkBridge) } func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) { d := s.d ipStr := "192.170.1.1/24" ip, _, _ := net.ParseCIDR(ipStr) args := []string{"--ip", ip.String()} err := d.StartWithBusybox(args...) c.Assert(err, check.IsNil) defer d.Restart() out, err := d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") c.Assert(err, check.NotNil, check.Commentf("Running a container must fail with an invalid --ip option")) c.Assert(strings.Contains(out, "Error starting userland proxy"), check.Equals, true) ifName := "dummy" out, err = createInterface(c, "dummy", ifName, ipStr) c.Assert(err, check.IsNil, check.Commentf(out)) defer deleteInterface(c, ifName) _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") c.Assert(err, check.IsNil) ipTablesCmd := exec.Command("iptables", "-t", "nat", "-nvL") out, _, err = runCommandWithOutput(ipTablesCmd) c.Assert(err, check.IsNil) regex := fmt.Sprintf("DNAT.*%s.*dpt:8000", ip.String()) matched, _ := regexp.MatchString(regex, out) c.Assert(matched, check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", regex, out)) } func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIp := "192.169.1.1/24" out, err := createInterface(c, "bridge", bridgeName, bridgeIp) c.Assert(err, check.IsNil, check.Commentf(out)) defer deleteInterface(c, bridgeName) args := []string{"--bridge", bridgeName, "--icc=false"} err = d.StartWithBusybox(args...) c.Assert(err, check.IsNil) defer d.Restart() ipTablesCmd := exec.Command("iptables", "-nvL", "FORWARD") out, _, err = runCommandWithOutput(ipTablesCmd) c.Assert(err, check.IsNil) regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) matched, _ := regexp.MatchString(regex, out) c.Assert(matched, check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", regex, out)) // Pinging another container must fail with --icc=false pingContainers(c, d, true) ipStr := "192.171.1.1/24" ip, _, _ := net.ParseCIDR(ipStr) ifName := "icc-dummy" createInterface(c, "dummy", ifName, ipStr) // But, Pinging external or a Host interface must succeed pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String()) runArgs := []string{"--rm", "busybox", "sh", "-c", pingCmd} _, err = d.Cmd("run", runArgs...) c.Assert(err, check.IsNil) } func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) { d := s.d bridgeName := "external-bridge" bridgeIp := "192.169.1.1/24" out, err := createInterface(c, "bridge", bridgeName, bridgeIp) c.Assert(err, check.IsNil, check.Commentf(out)) defer deleteInterface(c, bridgeName) args := []string{"--bridge", bridgeName, "--icc=false"} err = d.StartWithBusybox(args...) c.Assert(err, check.IsNil) defer d.Restart() ipTablesCmd := exec.Command("iptables", "-nvL", "FORWARD") out, _, err = runCommandWithOutput(ipTablesCmd) c.Assert(err, check.IsNil) regex := fmt.Sprintf("DROP.*all.*%s.*%s", bridgeName, bridgeName) matched, _ := regexp.MatchString(regex, out) c.Assert(matched, check.Equals, true, check.Commentf("iptables output should have contained %q, but was %q", regex, out)) out, err = d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567") c.Assert(err, check.IsNil, check.Commentf(out)) out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567") c.Assert(err, check.IsNil, check.Commentf(out)) } func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) { bridgeName := "external-bridge" bridgeIp := "192.169.1.1/24" out, err := createInterface(c, "bridge", bridgeName, bridgeIp) c.Assert(err, check.IsNil, check.Commentf(out)) defer deleteInterface(c, bridgeName) args := []string{"--bridge", bridgeName, "--icc=false"} err = s.d.StartWithBusybox(args...) c.Assert(err, check.IsNil) defer s.d.Restart() _, err = s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top") c.Assert(err, check.IsNil) _, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top") c.Assert(err, check.IsNil) childIP := s.d.findContainerIP("child") parentIP := s.d.findContainerIP("parent") sourceRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", childIP, "--sport", "80", "-d", parentIP, "-j", "ACCEPT"} destinationRule := []string{"-i", bridgeName, "-o", bridgeName, "-p", "tcp", "-s", parentIP, "--dport", "80", "-d", childIP, "-j", "ACCEPT"} if !iptables.Exists("filter", "DOCKER", sourceRule...) || !iptables.Exists("filter", "DOCKER", destinationRule...) { c.Fatal("Iptables rules not found") } s.d.Cmd("rm", "--link", "parent/http") if iptables.Exists("filter", "DOCKER", sourceRule...) || iptables.Exists("filter", "DOCKER", destinationRule...) { c.Fatal("Iptables rules should be removed when unlink") } s.d.Cmd("kill", "child") s.d.Cmd("kill", "parent") } func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) { testRequires(c, NativeExecDriver) if err := s.d.StartWithBusybox("--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024"); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)") if err != nil { c.Fatal(out, err) } outArr := strings.Split(out, "\n") if len(outArr) < 2 { c.Fatalf("got unexpected output: %s", out) } nofile := strings.TrimSpace(outArr[0]) nproc := strings.TrimSpace(outArr[1]) if nofile != "42" { c.Fatalf("expected `ulimit -n` to be `42`, got: %s", nofile) } if nproc != "2048" { c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) } // Now restart daemon with a new default if err := s.d.Restart("--default-ulimit", "nofile=43"); err != nil { c.Fatal(err) } out, err = s.d.Cmd("start", "-a", "test") if err != nil { c.Fatal(err) } outArr = strings.Split(out, "\n") if len(outArr) < 2 { c.Fatalf("got unexpected output: %s", out) } nofile = strings.TrimSpace(outArr[0]) nproc = strings.TrimSpace(outArr[1]) if nofile != "43" { c.Fatalf("expected `ulimit -n` to be `43`, got: %s", nofile) } if nproc != "2048" { c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) } } // #11315 func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil { c.Fatal(err, out) } if out, err := s.d.Cmd("rename", "test", "test2"); err != nil { c.Fatal(err, out) } if err := s.d.Restart(); err != nil { c.Fatal(err) } if out, err := s.d.Cmd("start", "test2"); err != nil { c.Fatal(err, out) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id := strings.TrimSpace(out) if out, err := s.d.Cmd("wait", id); err != nil { c.Fatal(out, err) } logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err != nil { c.Fatal(err) } f, err := os.Open(logPath) if err != nil { c.Fatal(err) } var res struct { Log string `json:"log"` Stream string `json:"stream"` Time time.Time `json:"time"` } if err := json.NewDecoder(f).Decode(&res); err != nil { c.Fatal(err) } if res.Log != "testline\n" { c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") } if res.Stream != "stdout" { c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") } if !time.Now().After(res.Time) { c.Fatalf("Log time %v in future", res.Time) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "-d", "--log-driver=none", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id := strings.TrimSpace(out) if out, err := s.d.Cmd("wait", id); err != nil { c.Fatal(out, err) } logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) { if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id := strings.TrimSpace(out) if out, err := s.d.Cmd("wait", id); err != nil { c.Fatal(out, err) } logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id := strings.TrimSpace(out) if out, err := s.d.Cmd("wait", id); err != nil { c.Fatal(out, err) } logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") if _, err := os.Stat(logPath); err != nil { c.Fatal(err) } f, err := os.Open(logPath) if err != nil { c.Fatal(err) } var res struct { Log string `json:"log"` Stream string `json:"stream"` Time time.Time `json:"time"` } if err := json.NewDecoder(f).Decode(&res); err != nil { c.Fatal(err) } if res.Log != "testline\n" { c.Fatalf("Unexpected log line: %q, expected: %q", res.Log, "testline\n") } if res.Stream != "stdout" { c.Fatalf("Unexpected stream: %q, expected: %q", res.Stream, "stdout") } if !time.Now().After(res.Time) { c.Fatalf("Log time %v in future", res.Time) } } func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") if err != nil { c.Fatal(out, err) } id := strings.TrimSpace(out) out, err = s.d.Cmd("logs", id) if err == nil { c.Fatalf("Logs should fail with \"none\" driver") } if !strings.Contains(out, `"logs" command is supported only for "json-file" logging driver`) { c.Fatalf("There should be error about non-json-file driver, got: %s", out) } } func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } // Now create 4 containers if _, err := s.d.Cmd("create", "busybox"); err != nil { c.Fatalf("Error creating container: %q", err) } if _, err := s.d.Cmd("create", "busybox"); err != nil { c.Fatalf("Error creating container: %q", err) } if _, err := s.d.Cmd("create", "busybox"); err != nil { c.Fatalf("Error creating container: %q", err) } if _, err := s.d.Cmd("create", "busybox"); err != nil { c.Fatalf("Error creating container: %q", err) } s.d.Stop() s.d.Start("--log-level=debug") s.d.Stop() content, _ := ioutil.ReadFile(s.d.logFile.Name()) if strings.Contains(string(content), "....") { c.Fatalf("Debug level should not have ....\n%s", string(content)) } s.d.Start("--log-level=error") s.d.Stop() content, _ = ioutil.ReadFile(s.d.logFile.Name()) if strings.Contains(string(content), "....") { c.Fatalf("Error level should not have ....\n%s", string(content)) } s.d.Start("--log-level=info") s.d.Stop() content, _ = ioutil.ReadFile(s.d.logFile.Name()) if !strings.Contains(string(content), "....") { c.Fatalf("Info level should have ....\n%s", string(content)) } } func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) { dir, err := ioutil.TempDir("", "socket-cleanup-test") if err != nil { c.Fatal(err) } defer os.RemoveAll(dir) sockPath := filepath.Join(dir, "docker.sock") if err := s.d.Start("--host", "unix://"+sockPath); err != nil { c.Fatal(err) } if _, err := os.Stat(sockPath); err != nil { c.Fatal("socket does not exist") } if err := s.d.Stop(); err != nil { c.Fatal(err) } if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) { c.Fatal("unix socket is not cleaned up") } } func (s *DockerDaemonSuite) TestDaemonWithWrongkey(c *check.C) { type Config struct { Crv string `json:"crv"` D string `json:"d"` Kid string `json:"kid"` Kty string `json:"kty"` X string `json:"x"` Y string `json:"y"` } os.Remove("/etc/docker/key.json") if err := s.d.Start(); err != nil { c.Fatalf("Failed to start daemon: %v", err) } if err := s.d.Stop(); err != nil { c.Fatalf("Could not stop daemon: %v", err) } config := &Config{} bytes, err := ioutil.ReadFile("/etc/docker/key.json") if err != nil { c.Fatalf("Error reading key.json file: %s", err) } // byte[] to Data-Struct if err := json.Unmarshal(bytes, &config); err != nil { c.Fatalf("Error Unmarshal: %s", err) } //replace config.Kid with the fake value config.Kid = "VSAJ:FUYR:X3H2:B2VZ:KZ6U:CJD5:K7BX:ZXHY:UZXT:P4FT:MJWG:HRJ4" // NEW Data-Struct to byte[] newBytes, err := json.Marshal(&config) if err != nil { c.Fatalf("Error Marshal: %s", err) } // write back if err := ioutil.WriteFile("/etc/docker/key.json", newBytes, 0400); err != nil { c.Fatalf("Error ioutil.WriteFile: %s", err) } defer os.Remove("/etc/docker/key.json") if err := s.d.Start(); err == nil { c.Fatalf("It should not be successful to start daemon with wrong key: %v", err) } content, _ := ioutil.ReadFile(s.d.logFile.Name()) if !strings.Contains(string(content), "Public Key ID does not match") { c.Fatal("Missing KeyID message from daemon logs") } } func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat") if err != nil { c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out) } containerID := strings.TrimSpace(out) if out, err := s.d.Cmd("kill", containerID); err != nil { c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out) } if err := s.d.Restart(); err != nil { c.Fatalf("Could not restart daemon: %v", err) } errchan := make(chan error) go func() { if out, err := s.d.Cmd("wait", containerID); err != nil { errchan <- fmt.Errorf("%v:\n%s", err, out) } close(errchan) }() select { case <-time.After(5 * time.Second): c.Fatal("Waiting on a stopped (killed) container timed out") case err := <-errchan: if err != nil { c.Fatal(err) } } } // TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) { const ( testDaemonHttpsAddr = "localhost:4271" ) if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } //force tcp protocol host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr) daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"} out, err := s.d.CmdWithArgs(daemonArgs, "info") if err != nil { c.Fatalf("Error Occurred: %s and output: %s", err, out) } } // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint // by using a rogue client certificate and checks that it fails with the expected error. func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) { const ( errBadCertificate = "remote error: bad certificate" testDaemonHttpsAddr = "localhost:4271" ) if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } //force tcp protocol host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr) daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"} out, err := s.d.CmdWithArgs(daemonArgs, "info") if err == nil || !strings.Contains(out, errBadCertificate) { c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out) } } // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint // which provides a rogue server certificate and checks that it fails with the expected error func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) { const ( errCaUnknown = "x509: certificate signed by unknown authority" testDaemonRogueHttpsAddr = "localhost:4272" ) if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem", "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHttpsAddr); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } //force tcp protocol host := fmt.Sprintf("tcp://%s", testDaemonRogueHttpsAddr) daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"} out, err := s.d.CmdWithArgs(daemonArgs, "info") if err == nil || !strings.Contains(out, errCaUnknown) { c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out) } } func pingContainers(c *check.C, d *Daemon, expectFailure bool) { var dargs []string if d != nil { dargs = []string{"--host", d.sock()} } args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top") dockerCmd(c, args...) args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c") pingCmd := "ping -c 1 %s -W 1" args = append(args, fmt.Sprintf(pingCmd, "alias1")) _, _, err := dockerCmdWithError(c, args...) if expectFailure { c.Assert(err, check.NotNil) } else { c.Assert(err, check.IsNil) } args = append(dargs, "rm", "-f", "container1") dockerCmd(c, args...) } func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) { c.Assert(s.d.StartWithBusybox(), check.IsNil) socket := filepath.Join(s.d.folder, "docker.sock") out, err := s.d.Cmd("run", "-d", "-v", socket+":/sock", "busybox") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(s.d.Restart(), check.IsNil) } func (s *DockerDaemonSuite) TestCleanupMountsAfterCrash(c *check.C) { c.Assert(s.d.StartWithBusybox(), check.IsNil) out, err := s.d.Cmd("run", "-d", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) id := strings.TrimSpace(out) c.Assert(s.d.cmd.Process.Signal(os.Kill), check.IsNil) c.Assert(s.d.Start(), check.IsNil) mountOut, err := exec.Command("mount").CombinedOutput() c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, check.Commentf("Something mounted from older daemon start: %s", mountOut)) } func (s *DockerDaemonSuite) TestRunContainerWithBridgeNone(c *check.C) { testRequires(c, NativeExecDriver) c.Assert(s.d.StartWithBusybox("-b", "none"), check.IsNil) out, err := s.d.Cmd("run", "--rm", "busybox", "ip", "l") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.Contains(out, "eth0"), check.Equals, false, check.Commentf("There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled: %s", out)) out, err = s.d.Cmd("run", "--rm", "--net=bridge", "busybox", "ip", "l") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.Contains(out, "eth0"), check.Equals, false, check.Commentf("There shouldn't be eth0 in container in bridge mode when bridge network is disabled: %s", out)) out, err = s.d.Cmd("run", "--rm", "--net=host", "busybox", "ip", "l") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(strings.Contains(out, "eth0"), check.Equals, true, check.Commentf("There should be eth0 in container when --net=host when bridge network is disabled: %s", out)) } func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) { if err := s.d.StartWithBusybox(); err != nil { t.Fatal(err) } if out, err := s.d.Cmd("run", "-ti", "-d", "--name", "test", "busybox"); err != nil { t.Fatal(out, err) } if err := s.d.Restart(); err != nil { t.Fatal(err) } // Container 'test' should be removed without error if out, err := s.d.Cmd("rm", "test"); err != nil { t.Fatal(out, err) } } func (s *DockerDaemonSuite) TestDaemonRestartCleanupNetns(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "--name", "netns", "-d", "busybox", "top") if err != nil { c.Fatal(out, err) } if out, err := s.d.Cmd("stop", "netns"); err != nil { c.Fatal(out, err) } // Construct netns file name from container id out = strings.TrimSpace(out) nsFile := out[:12] // Test if the file still exists out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", "/var/run/docker/netns/"+nsFile)) out = strings.TrimSpace(out) c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) c.Assert(out, check.Equals, "/var/run/docker/netns/"+nsFile, check.Commentf("Output: %s", out)) // Remove the container and restart the daemon if out, err := s.d.Cmd("rm", "netns"); err != nil { c.Fatal(out, err) } if err := s.d.Restart(); err != nil { c.Fatal(err) } // Test again and see now the netns file does not exist out, _, err = runCommandWithOutput(exec.Command("stat", "-c", "%n", "/var/run/docker/netns/"+nsFile)) out = strings.TrimSpace(out) c.Assert(err, check.Not(check.IsNil), check.Commentf("Output: %s", out)) // c.Assert(out, check.Equals, "", check.Commentf("Output: %s", out)) } // tests regression detailed in #13964 where DOCKER_TLS_VERIFY env is ignored func (s *DockerDaemonSuite) TestDaemonNoTlsCliTlsVerifyWithEnv(c *check.C) { host := "tcp://localhost:4271" c.Assert(s.d.Start("-H", host), check.IsNil) cmd := exec.Command(dockerBinary, "-H", host, "info") cmd.Env = []string{"DOCKER_TLS_VERIFY=1", "DOCKER_CERT_PATH=fixtures/https"} out, _, err := runCommandWithOutput(cmd) c.Assert(err, check.Not(check.IsNil), check.Commentf("%s", out)) c.Assert(strings.Contains(out, "error occurred trying to connect"), check.Equals, true) } func setupV6() error { // Hack to get the right IPv6 address on docker0, which has already been created err := exec.Command("ip", "addr", "add", "fe80::1/64", "dev", "docker0").Run() if err != nil { return err } return nil } func teardownV6() error { err := exec.Command("ip", "addr", "del", "fe80::1/64", "dev", "docker0").Run() if err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_diff_test.go ================================================ package main import ( "strings" "github.com/go-check/check" ) // ensure that an added file shows up in docker diff func (s *DockerSuite) TestDiffFilenameShownInOutput(c *check.C) { containerCmd := `echo foo > /root/bar` out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", containerCmd) cleanCID := strings.TrimSpace(out) out, _ = dockerCmd(c, "diff", cleanCID) found := false for _, line := range strings.Split(out, "\n") { if strings.Contains("A /root/bar", line) { found = true break } } if !found { c.Errorf("couldn't find the new file in docker diff's output: %v", out) } } // test to ensure GH #3840 doesn't occur any more func (s *DockerSuite) TestDiffEnsureDockerinitFilesAreIgnored(c *check.C) { // this is a list of files which shouldn't show up in `docker diff` dockerinitFiles := []string{"/etc/resolv.conf", "/etc/hostname", "/etc/hosts", "/.dockerinit", "/.dockerenv"} containerCount := 5 // we might not run into this problem from the first run, so start a few containers for i := 0; i < containerCount; i++ { containerCmd := `echo foo > /root/bar` out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", containerCmd) cleanCID := strings.TrimSpace(out) out, _ = dockerCmd(c, "diff", cleanCID) for _, filename := range dockerinitFiles { if strings.Contains(out, filename) { c.Errorf("found file which should've been ignored %v in diff output", filename) } } } } func (s *DockerSuite) TestDiffEnsureOnlyKmsgAndPtmx(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "0") cleanCID := strings.TrimSpace(out) out, _ = dockerCmd(c, "diff", cleanCID) expected := map[string]bool{ "C /dev": true, "A /dev/full": true, // busybox "C /dev/ptmx": true, // libcontainer "A /dev/kmsg": true, // lxc "A /dev/fd": true, "A /dev/fuse": true, "A /dev/ptmx": true, "A /dev/null": true, "A /dev/random": true, "A /dev/stdout": true, "A /dev/stderr": true, "A /dev/tty1": true, "A /dev/stdin": true, "A /dev/tty": true, "A /dev/urandom": true, "A /dev/zero": true, } for _, line := range strings.Split(out, "\n") { if line != "" && !expected[line] { c.Errorf("%q is shown in the diff but shouldn't", line) } } } // https://github.com/docker/docker/pull/14381#discussion_r33859347 func (s *DockerSuite) TestDiffEmptyArgClientError(c *check.C) { out, _, err := dockerCmdWithError(c, "diff", "") c.Assert(err, check.NotNil) c.Assert(strings.TrimSpace(out), check.Equals, "Container name cannot be empty") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_events_test.go ================================================ package main import ( "bufio" "fmt" "io/ioutil" "net/http" "os" "os/exec" "regexp" "strconv" "strings" "sync" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) { image := "busybox" // Start stopwatch, generate an event time.Sleep(time.Second) // so that we don't grab events from previous test occured in the same second start := daemonTime(c) time.Sleep(time.Second) // remote API precision is only a second, wait a while before creating an event dockerCmd(c, "tag", image, "timestamptest:1") dockerCmd(c, "rmi", "timestamptest:1") time.Sleep(time.Second) // so that until > since end := daemonTime(c) // List of available time formats to --since unixTs := func(t time.Time) string { return fmt.Sprintf("%v", t.Unix()) } rfc3339 := func(t time.Time) string { return t.Format(time.RFC3339) } duration := func(t time.Time) string { return time.Now().Sub(t).String() } // --since=$start must contain only the 'untag' event for _, f := range []func(time.Time) string{unixTs, rfc3339, duration} { since, until := f(start), f(end) out, _ := dockerCmd(c, "events", "--since="+since, "--until="+until) events := strings.Split(strings.TrimSpace(out), "\n") if len(events) != 2 { c.Fatalf("unexpected events, was expecting only 2 events tag/untag (since=%s, until=%s) out=%s", since, until, out) } if !strings.Contains(out, "untag") { c.Fatalf("expected 'untag' event not found (since=%s, until=%s) out=%s", since, until, out) } } } func (s *DockerSuite) TestEventsUntag(c *check.C) { image := "busybox" dockerCmd(c, "tag", image, "utest:tag1") dockerCmd(c, "tag", image, "utest:tag2") dockerCmd(c, "rmi", "utest:tag1") dockerCmd(c, "rmi", "utest:tag2") eventsCmd := exec.Command(dockerBinary, "events", "--since=1") out, exitCode, _, err := runCommandWithOutputForDuration(eventsCmd, time.Duration(time.Millisecond*200)) if exitCode != 0 || err != nil { c.Fatalf("Failed to get events - exit code %d: %s", exitCode, err) } events := strings.Split(out, "\n") nEvents := len(events) // The last element after the split above will be an empty string, so we // get the two elements before the last, which are the untags we're // looking for. for _, v := range events[nEvents-3 : nEvents-1] { if !strings.Contains(v, "untag") { c.Fatalf("event should be untag, not %#v", v) } } } func (s *DockerSuite) TestEventsContainerFailStartDie(c *check.C) { out, _ := dockerCmd(c, "images", "-q") image := strings.Split(out, "\n")[0] if _, _, err := dockerCmdWithError(c, "run", "--name", "testeventdie", image, "blerg"); err == nil { c.Fatalf("Container run with command blerg should have failed, but it did not") } out, _ = dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") if len(events) <= 1 { c.Fatalf("Missing expected event") } startEvent := strings.Fields(events[len(events)-3]) dieEvent := strings.Fields(events[len(events)-2]) if startEvent[len(startEvent)-1] != "start" { c.Fatalf("event should be start, not %#v", startEvent) } if dieEvent[len(dieEvent)-1] != "die" { c.Fatalf("event should be die, not %#v", dieEvent) } } func (s *DockerSuite) TestEventsLimit(c *check.C) { var waitGroup sync.WaitGroup errChan := make(chan error, 17) args := []string{"run", "--rm", "busybox", "true"} for i := 0; i < 17; i++ { waitGroup.Add(1) go func() { defer waitGroup.Done() errChan <- exec.Command(dockerBinary, args...).Run() }() } waitGroup.Wait() close(errChan) for err := range errChan { if err != nil { c.Fatalf("%q failed with error: %v", strings.Join(args, " "), err) } } out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") nEvents := len(events) - 1 if nEvents != 64 { c.Fatalf("events should be limited to 64, but received %d", nEvents) } } func (s *DockerSuite) TestEventsContainerEvents(c *check.C) { dockerCmd(c, "run", "--rm", "busybox", "true") out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") events = events[:len(events)-1] if len(events) < 5 { c.Fatalf("Missing expected event") } createEvent := strings.Fields(events[len(events)-5]) attachEvent := strings.Fields(events[len(events)-4]) startEvent := strings.Fields(events[len(events)-3]) dieEvent := strings.Fields(events[len(events)-2]) destroyEvent := strings.Fields(events[len(events)-1]) if createEvent[len(createEvent)-1] != "create" { c.Fatalf("event should be create, not %#v", createEvent) } if attachEvent[len(createEvent)-1] != "attach" { c.Fatalf("event should be attach, not %#v", attachEvent) } if startEvent[len(startEvent)-1] != "start" { c.Fatalf("event should be start, not %#v", startEvent) } if dieEvent[len(dieEvent)-1] != "die" { c.Fatalf("event should be die, not %#v", dieEvent) } if destroyEvent[len(destroyEvent)-1] != "destroy" { c.Fatalf("event should be destroy, not %#v", destroyEvent) } } func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) { dockerCmd(c, "run", "--rm", "busybox", "true") timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano) timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1) out, _ := dockerCmd(c, "events", fmt.Sprintf("--since='%s'", timeBeginning), fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") events = events[:len(events)-1] if len(events) < 5 { c.Fatalf("Missing expected event") } createEvent := strings.Fields(events[len(events)-5]) attachEvent := strings.Fields(events[len(events)-4]) startEvent := strings.Fields(events[len(events)-3]) dieEvent := strings.Fields(events[len(events)-2]) destroyEvent := strings.Fields(events[len(events)-1]) if createEvent[len(createEvent)-1] != "create" { c.Fatalf("event should be create, not %#v", createEvent) } if attachEvent[len(attachEvent)-1] != "attach" { c.Fatalf("event should be attach, not %#v", attachEvent) } if startEvent[len(startEvent)-1] != "start" { c.Fatalf("event should be start, not %#v", startEvent) } if dieEvent[len(dieEvent)-1] != "die" { c.Fatalf("event should be die, not %#v", dieEvent) } if destroyEvent[len(destroyEvent)-1] != "destroy" { c.Fatalf("event should be destroy, not %#v", destroyEvent) } } func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) { name := "testimageevents" _, err := buildImage(name, `FROM scratch MAINTAINER "docker"`, true) if err != nil { c.Fatal(err) } if err := deleteImages(name); err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") events = events[:len(events)-1] if len(events) < 2 { c.Fatalf("Missing expected event") } untagEvent := strings.Fields(events[len(events)-2]) deleteEvent := strings.Fields(events[len(events)-1]) if untagEvent[len(untagEvent)-1] != "untag" { c.Fatalf("untag should be untag, not %#v", untagEvent) } if deleteEvent[len(deleteEvent)-1] != "delete" { c.Fatalf("delete should be delete, not %#v", deleteEvent) } } func (s *DockerSuite) TestEventsImageTag(c *check.C) { time.Sleep(time.Second * 2) // because API has seconds granularity since := daemonTime(c).Unix() image := "testimageevents:tag" dockerCmd(c, "tag", "busybox", image) out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(strings.TrimSpace(out), "\n") if len(events) != 1 { c.Fatalf("was expecting 1 event. out=%s", out) } event := strings.TrimSpace(events[0]) expectedStr := image + ": tag" if !strings.HasSuffix(event, expectedStr) { c.Fatalf("wrong event format. expected='%s' got=%s", expectedStr, event) } } func (s *DockerSuite) TestEventsImagePull(c *check.C) { since := daemonTime(c).Unix() testRequires(c, Network) dockerCmd(c, "pull", "hello-world") out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(strings.TrimSpace(out), "\n") event := strings.TrimSpace(events[len(events)-1]) if !strings.HasSuffix(event, "hello-world:latest: pull") { c.Fatalf("Missing pull event - got:%q", event) } } func (s *DockerSuite) TestEventsImageImport(c *check.C) { since := daemonTime(c).Unix() id := make(chan string) eventImport := make(chan struct{}) eventsCmd := exec.Command(dockerBinary, "events", "--since", strconv.FormatInt(since, 10)) stdout, err := eventsCmd.StdoutPipe() if err != nil { c.Fatal(err) } if err := eventsCmd.Start(); err != nil { c.Fatal(err) } defer eventsCmd.Process.Kill() go func() { containerID := <-id matchImport := regexp.MustCompile(containerID + `: import$`) scanner := bufio.NewScanner(stdout) for scanner.Scan() { if matchImport.MatchString(scanner.Text()) { close(eventImport) } } }() out, _ := dockerCmd(c, "run", "-d", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) out, _, err = runCommandPipelineWithOutput( exec.Command(dockerBinary, "export", cleanedContainerID), exec.Command(dockerBinary, "import", "-"), ) if err != nil { c.Errorf("import failed with errors: %v, output: %q", err, out) } newContainerID := strings.TrimSpace(out) id <- newContainerID select { case <-time.After(5 * time.Second): c.Fatal("failed to observe image import in timely fashion") case <-eventImport: // ignore, done } } func (s *DockerSuite) TestEventsFilters(c *check.C) { parseEvents := func(out, match string) { events := strings.Split(out, "\n") events = events[:len(events)-1] for _, event := range events { eventFields := strings.Fields(event) eventName := eventFields[len(eventFields)-1] if ok, err := regexp.MatchString(match, eventName); err != nil || !ok { c.Fatalf("event should match %s, got %#v, err: %v", match, eventFields, err) } } } since := daemonTime(c).Unix() dockerCmd(c, "run", "--rm", "busybox", "true") dockerCmd(c, "run", "--rm", "busybox", "true") out, _ := dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die") parseEvents(out, "die") out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", "event=die", "--filter", "event=start") parseEvents(out, "((die)|(start))") // make sure we at least got 2 start events count := strings.Count(out, "start") if count < 2 { c.Fatalf("should have had 2 start events but had %d, out: %s", count, out) } } func (s *DockerSuite) TestEventsFilterImageName(c *check.C) { since := daemonTime(c).Unix() out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true") container1 := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true") container2 := strings.TrimSpace(out) name := "busybox" out, _ = dockerCmd(c, "events", fmt.Sprintf("--since=%d", since), fmt.Sprintf("--until=%d", daemonTime(c).Unix()), "--filter", fmt.Sprintf("image=%s", name)) events := strings.Split(out, "\n") events = events[:len(events)-1] if len(events) == 0 { c.Fatalf("Expected events but found none for the image busybox:latest") } count1 := 0 count2 := 0 for _, e := range events { if strings.Contains(e, container1) { count1++ } else if strings.Contains(e, container2) { count2++ } } if count1 == 0 || count2 == 0 { c.Fatalf("Expected events from each container but got %d from %s and %d from %s", count1, container1, count2, container2) } } func (s *DockerSuite) TestEventsFilterContainer(c *check.C) { since := fmt.Sprintf("%d", daemonTime(c).Unix()) nameID := make(map[string]string) for _, name := range []string{"container_1", "container_2"} { dockerCmd(c, "run", "--name", name, "busybox", "true") id, err := inspectField(name, "Id") if err != nil { c.Fatal(err) } nameID[name] = id } until := fmt.Sprintf("%d", daemonTime(c).Unix()) checkEvents := func(id string, events []string) error { if len(events) != 4 { // create, attach, start, die return fmt.Errorf("expected 3 events, got %v", events) } for _, event := range events { e := strings.Fields(event) if len(e) < 3 { return fmt.Errorf("got malformed event: %s", event) } // Check the id parsedID := strings.TrimSuffix(e[1], ":") if parsedID != id { return fmt.Errorf("expected event for container id %s: %s - parsed container id: %s", id, event, parsedID) } } return nil } for name, ID := range nameID { // filter by names out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+name) events := strings.Split(strings.TrimSuffix(out, "\n"), "\n") if err := checkEvents(ID, events); err != nil { c.Fatal(err) } // filter by ID's out, _ = dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+ID) events = strings.Split(strings.TrimSuffix(out, "\n"), "\n") if err := checkEvents(ID, events); err != nil { c.Fatal(err) } } } func (s *DockerSuite) TestEventsStreaming(c *check.C) { start := daemonTime(c).Unix() id := make(chan string) eventCreate := make(chan struct{}) eventStart := make(chan struct{}) eventDie := make(chan struct{}) eventDestroy := make(chan struct{}) eventsCmd := exec.Command(dockerBinary, "events", "--since", strconv.FormatInt(start, 10)) stdout, err := eventsCmd.StdoutPipe() if err != nil { c.Fatal(err) } if err := eventsCmd.Start(); err != nil { c.Fatalf("failed to start 'docker events': %s", err) } defer eventsCmd.Process.Kill() go func() { containerID := <-id matchCreate := regexp.MustCompile(containerID + `: \(from busybox:latest\) create$`) matchStart := regexp.MustCompile(containerID + `: \(from busybox:latest\) start$`) matchDie := regexp.MustCompile(containerID + `: \(from busybox:latest\) die$`) matchDestroy := regexp.MustCompile(containerID + `: \(from busybox:latest\) destroy$`) scanner := bufio.NewScanner(stdout) for scanner.Scan() { switch { case matchCreate.MatchString(scanner.Text()): close(eventCreate) case matchStart.MatchString(scanner.Text()): close(eventStart) case matchDie.MatchString(scanner.Text()): close(eventDie) case matchDestroy.MatchString(scanner.Text()): close(eventDestroy) } } }() out, _ := dockerCmd(c, "run", "-d", "busybox:latest", "true") cleanedContainerID := strings.TrimSpace(out) id <- cleanedContainerID select { case <-time.After(5 * time.Second): c.Fatal("failed to observe container create in timely fashion") case <-eventCreate: // ignore, done } select { case <-time.After(5 * time.Second): c.Fatal("failed to observe container start in timely fashion") case <-eventStart: // ignore, done } select { case <-time.After(5 * time.Second): c.Fatal("failed to observe container die in timely fashion") case <-eventDie: // ignore, done } dockerCmd(c, "rm", cleanedContainerID) select { case <-time.After(5 * time.Second): c.Fatal("failed to observe container destroy in timely fashion") case <-eventDestroy: // ignore, done } } func (s *DockerSuite) TestEventsCommit(c *check.C) { since := daemonTime(c).Unix() out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cID := strings.TrimSpace(out) c.Assert(waitRun(cID), check.IsNil) dockerCmd(c, "commit", "-m", "test", cID) dockerCmd(c, "stop", cID) out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " commit\n") { c.Fatalf("Missing 'commit' log event\n%s", out) } } func (s *DockerSuite) TestEventsCopy(c *check.C) { since := daemonTime(c).Unix() // Build a test image. id, err := buildImage("cpimg", ` FROM busybox RUN echo HI > /tmp/file`, true) if err != nil { c.Fatalf("Couldn't create image: %q", err) } // Create an empty test file. tempFile, err := ioutil.TempFile("", "test-events-copy-") if err != nil { c.Fatal(err) } defer os.Remove(tempFile.Name()) if err := tempFile.Close(); err != nil { c.Fatal(err) } dockerCmd(c, "create", "--name=cptest", id) dockerCmd(c, "cp", "cptest:/tmp/file", tempFile.Name()) out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " archive-path\n") { c.Fatalf("Missing 'archive-path' log event\n%s", out) } dockerCmd(c, "cp", tempFile.Name(), "cptest:/tmp/filecopy") out, _ = dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " extract-to-dir\n") { c.Fatalf("Missing 'extract-to-dir' log event\n%s", out) } } func (s *DockerSuite) TestEventsResize(c *check.C) { since := daemonTime(c).Unix() out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cID := strings.TrimSpace(out) c.Assert(waitRun(cID), check.IsNil) endpoint := "/containers/" + cID + "/resize?h=80&w=24" status, _, err := sockRequest("POST", endpoint, nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) dockerCmd(c, "stop", cID) out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " resize\n") { c.Fatalf("Missing 'resize' log event\n%s", out) } } func (s *DockerSuite) TestEventsAttach(c *check.C) { since := daemonTime(c).Unix() out, _ := dockerCmd(c, "run", "-di", "busybox", "/bin/cat") cID := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "attach", cID) stdin, err := cmd.StdinPipe() c.Assert(err, check.IsNil) defer stdin.Close() stdout, err := cmd.StdoutPipe() c.Assert(err, check.IsNil) defer stdout.Close() c.Assert(cmd.Start(), check.IsNil) defer cmd.Process.Kill() // Make sure we're done attaching by writing/reading some stuff if _, err := stdin.Write([]byte("hello\n")); err != nil { c.Fatal(err) } out, err = bufio.NewReader(stdout).ReadString('\n') c.Assert(err, check.IsNil) if strings.TrimSpace(out) != "hello" { c.Fatalf("expected 'hello', got %q", out) } c.Assert(stdin.Close(), check.IsNil) dockerCmd(c, "stop", cID) out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " attach\n") { c.Fatalf("Missing 'attach' log event\n%s", out) } } func (s *DockerSuite) TestEventsRename(c *check.C) { since := daemonTime(c).Unix() dockerCmd(c, "run", "--name", "oldName", "busybox", "true") dockerCmd(c, "rename", "oldName", "newName") out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=newName", "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " rename\n") { c.Fatalf("Missing 'rename' log event\n%s", out) } } func (s *DockerSuite) TestEventsTop(c *check.C) { since := daemonTime(c).Unix() out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cID := strings.TrimSpace(out) c.Assert(waitRun(cID), check.IsNil) dockerCmd(c, "top", cID) dockerCmd(c, "stop", cID) out, _ = dockerCmd(c, "events", "--since=0", "-f", "container="+cID, "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, " top\n") { c.Fatalf("Missing 'top' log event\n%s", out) } } // #13753 func (s *DockerSuite) TestEventsDefaultEmpty(c *check.C) { dockerCmd(c, "run", "busybox") out, _ := dockerCmd(c, "events", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) c.Assert(strings.TrimSpace(out), check.Equals, "") } // #14316 func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) { testRequires(c, Network) since := daemonTime(c).Unix() repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cID := strings.TrimSpace(out) c.Assert(waitRun(cID), check.IsNil) dockerCmd(c, "commit", cID, repoName) dockerCmd(c, "stop", cID) dockerCmd(c, "push", repoName) out, _ = dockerCmd(c, "events", "--since=0", "-f", "image="+repoName, "-f", "event=push", "--until="+strconv.Itoa(int(since))) if !strings.Contains(out, repoName+": push\n") { c.Fatalf("Missing 'push' log event for image %s\n%s", repoName, out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_events_unix_test.go ================================================ // +build !windows package main import ( "bufio" "fmt" "io/ioutil" "os" "os/exec" "unicode" "github.com/go-check/check" "github.com/kr/pty" ) // #5979 func (s *DockerSuite) TestEventsRedirectStdout(c *check.C) { since := daemonTime(c).Unix() dockerCmd(c, "run", "busybox", "true") file, err := ioutil.TempFile("", "") if err != nil { c.Fatalf("could not create temp file: %v", err) } defer os.Remove(file.Name()) command := fmt.Sprintf("%s events --since=%d --until=%d > %s", dockerBinary, since, daemonTime(c).Unix(), file.Name()) _, tty, err := pty.Open() if err != nil { c.Fatalf("Could not open pty: %v", err) } cmd := exec.Command("sh", "-c", command) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty if err := cmd.Run(); err != nil { c.Fatalf("run err for command %q: %v", command, err) } scanner := bufio.NewScanner(file) for scanner.Scan() { for _, ch := range scanner.Text() { if unicode.IsControl(ch) { c.Fatalf("found control character %v", []byte(string(ch))) } } } if err := scanner.Err(); err != nil { c.Fatalf("Scan err for command %q: %v", command, err) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_exec_test.go ================================================ // +build !test_no_exec package main import ( "bufio" "fmt" "net/http" "os" "os/exec" "path/filepath" "reflect" "sort" "strings" "sync" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestExec(c *check.C) { dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") out, _ := dockerCmd(c, "exec", "testing", "cat", "/tmp/file") out = strings.Trim(out, "\r\n") if out != "test" { c.Errorf("container exec should've printed test but printed %q", out) } } func (s *DockerSuite) TestExecInteractive(c *check.C) { dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") execCmd := exec.Command(dockerBinary, "exec", "-i", "testing", "sh") stdin, err := execCmd.StdinPipe() if err != nil { c.Fatal(err) } stdout, err := execCmd.StdoutPipe() if err != nil { c.Fatal(err) } if err := execCmd.Start(); err != nil { c.Fatal(err) } if _, err := stdin.Write([]byte("cat /tmp/file\n")); err != nil { c.Fatal(err) } r := bufio.NewReader(stdout) line, err := r.ReadString('\n') if err != nil { c.Fatal(err) } line = strings.TrimSpace(line) if line != "test" { c.Fatalf("Output should be 'test', got '%q'", line) } if err := stdin.Close(); err != nil { c.Fatal(err) } errChan := make(chan error) go func() { errChan <- execCmd.Wait() close(errChan) }() select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(1 * time.Second): c.Fatal("docker exec failed to exit on stdin close") } } func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "restart", cleanedContainerID) out, _ = dockerCmd(c, "exec", cleanedContainerID, "echo", "hello") outStr := strings.TrimSpace(out) if outStr != "hello" { c.Errorf("container should've printed hello, instead printed %q", outStr) } } func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) { testRequires(c, SameHostDaemon) if err := s.d.StartWithBusybox(); err != nil { c.Fatalf("Could not start daemon with busybox: %v", err) } if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { c.Fatalf("Could not run top: err=%v\n%s", err, out) } if err := s.d.Restart(); err != nil { c.Fatalf("Could not restart daemon: %v", err) } if out, err := s.d.Cmd("start", "top"); err != nil { c.Fatalf("Could not start top after daemon restart: err=%v\n%s", err, out) } out, err := s.d.Cmd("exec", "top", "echo", "hello") if err != nil { c.Fatalf("Could not exec on container top: err=%v\n%s", err, out) } outStr := strings.TrimSpace(string(out)) if outStr != "hello" { c.Errorf("container should've printed hello, instead printed %q", outStr) } } // Regression test for #9155, #9044 func (s *DockerSuite) TestExecEnv(c *check.C) { dockerCmd(c, "run", "-e", "LALA=value1", "-e", "LALA=value2", "-d", "--name", "testing", "busybox", "top") out, _ := dockerCmd(c, "exec", "testing", "env") if strings.Contains(out, "LALA=value1") || !strings.Contains(out, "LALA=value2") || !strings.Contains(out, "HOME=/root") { c.Errorf("exec env(%q), expect %q, %q", out, "LALA=value2", "HOME=/root") } } func (s *DockerSuite) TestExecExitStatus(c *check.C) { dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top") // Test normal (non-detached) case first cmd := exec.Command(dockerBinary, "exec", "top", "sh", "-c", "exit 23") ec, _ := runCommand(cmd) if ec != 23 { c.Fatalf("Should have had an ExitCode of 23, not: %d", ec) } } func (s *DockerSuite) TestExecPausedContainer(c *check.C) { defer unpauseAllContainers() out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") ContainerID := strings.TrimSpace(out) dockerCmd(c, "pause", "testing") out, _, err := dockerCmdWithError(c, "exec", "-i", "-t", ContainerID, "echo", "hello") if err == nil { c.Fatal("container should fail to exec new command if it is paused") } expected := ContainerID + " is paused, unpause the container before exec" if !strings.Contains(out, expected) { c.Fatal("container should not exec new command if it is paused") } } // regression test for #9476 func (s *DockerSuite) TestExecTtyCloseStdin(c *check.C) { dockerCmd(c, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox") cmd := exec.Command(dockerBinary, "exec", "-i", "exec_tty_stdin", "cat") stdinRw, err := cmd.StdinPipe() if err != nil { c.Fatal(err) } stdinRw.Write([]byte("test")) stdinRw.Close() if out, _, err := runCommandWithOutput(cmd); err != nil { c.Fatal(out, err) } out, _ := dockerCmd(c, "top", "exec_tty_stdin") outArr := strings.Split(out, "\n") if len(outArr) > 3 || strings.Contains(out, "nsenter-exec") { c.Fatalf("exec process left running\n\t %s", out) } } func (s *DockerSuite) TestExecTtyWithoutStdin(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatal(err) } defer func() { dockerCmd(c, "kill", id) }() errChan := make(chan error) go func() { defer close(errChan) cmd := exec.Command(dockerBinary, "exec", "-ti", id, "true") if _, err := cmd.StdinPipe(); err != nil { errChan <- err return } expected := "cannot enable tty mode" if out, _, err := runCommandWithOutput(cmd); err == nil { errChan <- fmt.Errorf("exec should have failed") return } else if !strings.Contains(out, expected) { errChan <- fmt.Errorf("exec failed with error %q: expected %q", out, expected) return } }() select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(3 * time.Second): c.Fatal("exec is running but should have failed") } } func (s *DockerSuite) TestExecParseError(c *check.C) { dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top") // Test normal (non-detached) case first cmd := exec.Command(dockerBinary, "exec", "top") if _, stderr, code, err := runCommandWithStdoutStderr(cmd); err == nil || !strings.Contains(stderr, "See '"+dockerBinary+" exec --help'") || code == 0 { c.Fatalf("Should have thrown error & point to help: %s", stderr) } } func (s *DockerSuite) TestExecStopNotHanging(c *check.C) { dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") if err := exec.Command(dockerBinary, "exec", "testing", "top").Start(); err != nil { c.Fatal(err) } type dstop struct { out []byte err error } ch := make(chan dstop) go func() { out, err := exec.Command(dockerBinary, "stop", "testing").CombinedOutput() ch <- dstop{out, err} close(ch) }() select { case <-time.After(3 * time.Second): c.Fatal("Container stop timed out") case s := <-ch: c.Assert(s.err, check.IsNil) } } func (s *DockerSuite) TestExecCgroup(c *check.C) { dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") out, _ := dockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup") containerCgroups := sort.StringSlice(strings.Split(out, "\n")) var wg sync.WaitGroup var mu sync.Mutex execCgroups := []sort.StringSlice{} errChan := make(chan error) // exec a few times concurrently to get consistent failure for i := 0; i < 5; i++ { wg.Add(1) go func() { out, _, err := dockerCmdWithError(c, "exec", "testing", "cat", "/proc/self/cgroup") if err != nil { errChan <- err return } cg := sort.StringSlice(strings.Split(out, "\n")) mu.Lock() execCgroups = append(execCgroups, cg) mu.Unlock() wg.Done() }() } wg.Wait() close(errChan) for err := range errChan { c.Assert(err, check.IsNil) } for _, cg := range execCgroups { if !reflect.DeepEqual(cg, containerCgroups) { fmt.Println("exec cgroups:") for _, name := range cg { fmt.Printf(" %s\n", name) } fmt.Println("container cgroups:") for _, name := range containerCgroups { fmt.Printf(" %s\n", name) } c.Fatal("cgroups mismatched") } } } func (s *DockerSuite) TestInspectExecID(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSuffix(out, "\n") out, err := inspectField(id, "ExecIDs") if err != nil { c.Fatalf("failed to inspect container: %s, %v", out, err) } if out != "[]" { c.Fatalf("ExecIDs should be empty, got: %s", out) } // Start an exec, have it block waiting for input so we can do some checking cmd := exec.Command(dockerBinary, "exec", "-i", id, "sh", "-c", "read a") execStdin, _ := cmd.StdinPipe() if err = cmd.Start(); err != nil { c.Fatalf("failed to start the exec cmd: %q", err) } // Give the exec 10 chances/seconds to start then give up and stop the test tries := 10 for i := 0; i < tries; i++ { // Since its still running we should see exec as part of the container out, err = inspectField(id, "ExecIDs") if err != nil { c.Fatalf("failed to inspect container: %s, %v", out, err) } out = strings.TrimSuffix(out, "\n") if out != "[]" && out != "" { break } if i+1 == tries { c.Fatalf("ExecIDs should not be empty, got: %s", out) } time.Sleep(1 * time.Second) } // Save execID for later execID, err := inspectFilter(id, "index .ExecIDs 0") if err != nil { c.Fatalf("failed to get the exec id: %v", err) } // End the exec by closing its stdin, and wait for it to end execStdin.Close() cmd.Wait() // All execs for the container should be gone now out, err = inspectField(id, "ExecIDs") if err != nil { c.Fatalf("failed to inspect container: %s, %v", out, err) } out = strings.TrimSuffix(out, "\n") if out != "[]" && out != "" { c.Fatalf("ExecIDs should be empty, got: %s", out) } // But we should still be able to query the execID sc, body, err := sockRequest("GET", "/exec/"+execID+"/json", nil) if sc != http.StatusOK { c.Fatalf("received status != 200 OK: %d\n%s", sc, body) } } func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) { var out string out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") idA := strings.TrimSpace(out) if idA == "" { c.Fatal(out, "id should not be nil") } out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top") idB := strings.TrimSpace(out) if idB == "" { c.Fatal(out, "id should not be nil") } dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") dockerCmd(c, "rename", "container1", "container_new") dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") } func (s *DockerSuite) TestRunExecDir(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) execDir := filepath.Join(execDriverPath, id) stateFile := filepath.Join(execDir, "state.json") { fi, err := os.Stat(execDir) if err != nil { c.Fatal(err) } if !fi.IsDir() { c.Fatalf("%q must be a directory", execDir) } fi, err = os.Stat(stateFile) if err != nil { c.Fatal(err) } } dockerCmd(c, "stop", id) { _, err := os.Stat(execDir) if err == nil { c.Fatal(err) } if err == nil { c.Fatalf("Exec directory %q exists for removed container!", execDir) } if !os.IsNotExist(err) { c.Fatalf("Error should be about non-existing, got %s", err) } } dockerCmd(c, "start", id) { fi, err := os.Stat(execDir) if err != nil { c.Fatal(err) } if !fi.IsDir() { c.Fatalf("%q must be a directory", execDir) } fi, err = os.Stat(stateFile) if err != nil { c.Fatal(err) } } dockerCmd(c, "rm", "-f", id) { _, err := os.Stat(execDir) if err == nil { c.Fatal(err) } if err == nil { c.Fatalf("Exec directory %q is exists for removed container!", execDir) } if !os.IsNotExist(err) { c.Fatalf("Error should be about non-existing, got %s", err) } } } func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) { testRequires(c, SameHostDaemon) for _, fn := range []string{"resolv.conf", "hosts"} { deleteAllContainers() content, err := runCommandAndReadContainerFile(fn, exec.Command(dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn))) if err != nil { c.Fatal(err) } if strings.TrimSpace(string(content)) != "success" { c.Fatal("Content was not what was modified in the container", string(content)) } out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top") contID := strings.TrimSpace(out) netFilePath := containerStorageFile(contID, fn) f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644) if err != nil { c.Fatal(err) } if _, err := f.Seek(0, 0); err != nil { f.Close() c.Fatal(err) } if err := f.Truncate(0); err != nil { f.Close() c.Fatal(err) } if _, err := f.Write([]byte("success2\n")); err != nil { f.Close() c.Fatal(err) } f.Close() res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn) if res != "success2\n" { c.Fatalf("Expected content of %s: %q, got: %q", fn, "success2\n", res) } } } func (s *DockerSuite) TestExecWithUser(c *check.C) { dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id") if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { c.Fatalf("exec with user by id expected daemon user got %s", out) } out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id") if !strings.Contains(out, "uid=0(root) gid=0(root)") { c.Fatalf("exec with user by root expected root user got %s", out) } } func (s *DockerSuite) TestExecWithImageUser(c *check.C) { name := "testbuilduser" _, err := buildImage(name, `FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd USER dockerio`, true) if err != nil { c.Fatalf("Could not build image %s: %v", name, err) } dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top") out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami") if !strings.Contains(out, "dockerio") { c.Fatalf("exec with user by id expected dockerio user got %s", out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_exec_unix_test.go ================================================ // +build !windows,!test_no_exec package main import ( "bytes" "io" "os/exec" "strings" "time" "github.com/go-check/check" "github.com/kr/pty" ) // regression test for #12546 func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) { out, _ := dockerCmd(c, "run", "-itd", "busybox", "/bin/cat") contId := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "exec", "-i", contId, "echo", "-n", "hello") p, err := pty.Start(cmd) if err != nil { c.Fatal(err) } b := bytes.NewBuffer(nil) go io.Copy(b, p) ch := make(chan error) go func() { ch <- cmd.Wait() }() select { case err := <-ch: if err != nil { c.Errorf("cmd finished with error %v", err) } if output := b.String(); strings.TrimSpace(output) != "hello" { c.Fatalf("Unexpected output %s", output) } case <-time.After(1 * time.Second): c.Fatal("timed out running docker exec") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_experimental_test.go ================================================ // +build experimental package main import ( "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestExperimentalVersion(c *check.C) { out, _ := dockerCmd(c, "version") for _, line := range strings.Split(out, "\n") { if strings.HasPrefix(line, "Experimental (client):") || strings.HasPrefix(line, "Experimental (server):") { c.Assert(line, check.Matches, "*true") } } out, _ = dockerCmd(c, "-v") if !strings.Contains(out, ", experimental") { c.Fatalf("docker version did not contain experimental: %s", out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_export_import_test.go ================================================ package main import ( "os" "os/exec" "strings" "github.com/go-check/check" ) // export an image and try to import it into a new one func (s *DockerSuite) TestExportContainerAndImportImage(c *check.C) { containerID := "testexportcontainerandimportimage" dockerCmd(c, "run", "--name", containerID, "busybox", "true") out, _ := dockerCmd(c, "export", containerID) importCmd := exec.Command(dockerBinary, "import", "-", "repo/testexp:v1") importCmd.Stdin = strings.NewReader(out) out, _, err := runCommandWithOutput(importCmd) if err != nil { c.Fatalf("failed to import image: %s, %v", out, err) } cleanedImageID := strings.TrimSpace(out) if cleanedImageID == "" { c.Fatalf("output should have been an image id, got: %s", out) } } // Used to test output flag in the export command func (s *DockerSuite) TestExportContainerWithOutputAndImportImage(c *check.C) { containerID := "testexportcontainerwithoutputandimportimage" dockerCmd(c, "run", "--name", containerID, "busybox", "true") dockerCmd(c, "export", "--output=testexp.tar", containerID) defer os.Remove("testexp.tar") out, _, err := runCommandWithOutput(exec.Command("cat", "testexp.tar")) if err != nil { c.Fatal(out, err) } importCmd := exec.Command(dockerBinary, "import", "-", "repo/testexp:v1") importCmd.Stdin = strings.NewReader(out) out, _, err = runCommandWithOutput(importCmd) if err != nil { c.Fatalf("failed to import image: %s, %v", out, err) } cleanedImageID := strings.TrimSpace(out) if cleanedImageID == "" { c.Fatalf("output should have been an image id, got: %s", out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_help_test.go ================================================ package main import ( "os" "os/exec" "runtime" "strings" "unicode" "github.com/docker/docker/pkg/homedir" "github.com/go-check/check" ) func (s *DockerSuite) TestHelpTextVerify(c *check.C) { // Make sure main help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Test for HOME set to its default value and set to "/" on linux // Yes on windows setting up an array and looping (right now) isn't // necessary because we just have one value, but we'll need the // array/loop on linux so we might as well set it up so that we can // test any number of home dirs later on and all we need to do is // modify the array - the rest of the testing infrastructure should work homes := []string{homedir.Get()} // Non-Windows machines need to test for this special case of $HOME if runtime.GOOS != "windows" { homes = append(homes, "/") } homeKey := homedir.Key() baseEnvs := os.Environ() // Remove HOME env var from list so we can add a new value later. for i, env := range baseEnvs { if strings.HasPrefix(env, homeKey+"=") { baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...) break } } for _, home := range homes { // Dup baseEnvs and add our new HOME value newEnvs := make([]string, len(baseEnvs)+1) copy(newEnvs, baseEnvs) newEnvs[len(newEnvs)-1] = homeKey + "=" + home scanForHome := runtime.GOOS != "windows" && home != "/" // Check main help text to make sure its not over 80 chars helpCmd := exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, ec, err := runCommandWithOutput(helpCmd) if err != nil || ec != 0 { c.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) } lines := strings.Split(out, "\n") for _, line := range lines { if len(line) > 80 { c.Fatalf("Line is too long(%d chars):\n%s", len(line), line) } // All lines should not end with a space if strings.HasSuffix(line, " ") { c.Fatalf("Line should not end with a space: %s", line) } if scanForHome && strings.Contains(line, `=`+home) { c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line) } if runtime.GOOS != "windows" { i := strings.Index(line, homedir.GetShortcutString()) if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Main help should not have used home shortcut:\n%s", line) } } } // Make sure each cmd's help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Pull the list of commands from the "Commands:" section of docker help helpCmd = exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, ec, err = runCommandWithOutput(helpCmd) if err != nil || ec != 0 { c.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) } i := strings.Index(out, "Commands:") if i < 0 { c.Fatalf("Missing 'Commands:' in:\n%s", out) } // Grab all chars starting at "Commands:" // Skip first line, its "Commands:" cmds := []string{} for _, cmd := range strings.Split(out[i:], "\n")[1:] { var stderr string // Stop on blank line or non-idented line if cmd == "" || !unicode.IsSpace(rune(cmd[0])) { break } // Grab just the first word of each line cmd = strings.Split(strings.TrimSpace(cmd), " ")[0] cmds = append(cmds, cmd) // Check the full usage text helpCmd := exec.Command(dockerBinary, cmd, "--help") helpCmd.Env = newEnvs out, stderr, ec, err = runCommandWithStdoutStderr(helpCmd) if len(stderr) != 0 { c.Fatalf("Error on %q help. non-empty stderr:%q", cmd, stderr) } if strings.HasSuffix(out, "\n\n") { c.Fatalf("Should not have blank line on %q\nout:%q", cmd, out) } if !strings.Contains(out, "--help=false") { c.Fatalf("Should show full usage on %q\nout:%q", cmd, out) } if err != nil || ec != 0 { c.Fatalf("Error on %q help: %s\nexit code:%d", cmd, out, ec) } // Check each line for lots of stuff lines := strings.Split(out, "\n") for _, line := range lines { if len(line) > 80 { c.Fatalf("Help for %q is too long(%d chars):\n%s", cmd, len(line), line) } if scanForHome && strings.Contains(line, `"`+home) { c.Fatalf("Help for %q should use ~ instead of %q on:\n%s", cmd, home, line) } i := strings.Index(line, "~") if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Help for %q should not have used ~:\n%s", cmd, line) } // If a line starts with 4 spaces then assume someone // added a multi-line description for an option and we need // to flag it if strings.HasPrefix(line, " ") { c.Fatalf("Help for %q should not have a multi-line option: %s", cmd, line) } // Options should NOT end with a period if strings.HasPrefix(line, " -") && strings.HasSuffix(line, ".") { c.Fatalf("Help for %q should not end with a period: %s", cmd, line) } // Options should NOT end with a space if strings.HasSuffix(line, " ") { c.Fatalf("Help for %q should not end with a space: %s", cmd, line) } } // For each command make sure we generate an error // if we give a bad arg dCmd := exec.Command(dockerBinary, cmd, "--badArg") out, stderr, ec, err = runCommandWithStdoutStderr(dCmd) if len(out) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad results from 'docker %s --badArg'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", cmd, ec, out, stderr, err) } // Be really picky if strings.HasSuffix(stderr, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker rm'\n%s", stderr) } // Now make sure that each command will print a short-usage // (not a full usage - meaning no opts section) if we // are missing a required arg or pass in a bad arg // These commands will never print a short-usage so don't test noShortUsage := map[string]string{ "images": "", "login": "", "logout": "", } if _, ok := noShortUsage[cmd]; !ok { // For each command run it w/o any args. It will either return // valid output or print a short-usage var dCmd *exec.Cmd var stdout, stderr string var args []string // skipNoArgs are ones that we don't want to try w/o // any args. Either because it'll hang the test or // lead to incorrect test result (like false negative). // Whatever the reason, skip trying to run w/o args and // jump to trying with a bogus arg. skipNoArgs := map[string]string{ "events": "", "load": "", } ec = 0 if _, ok := skipNoArgs[cmd]; !ok { args = []string{cmd} dCmd = exec.Command(dockerBinary, args...) stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd) } // If its ok w/o any args then try again with an arg if ec == 0 { args = []string{cmd, "badArg"} dCmd = exec.Command(dockerBinary, args...) stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd) } if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad output from %q\nstdout:%q\nstderr:%q\nec:%d\nerr:%q", args, stdout, stderr, ec, err) } // Should have just short usage if !strings.Contains(stderr, "\nUsage:\t") { c.Fatalf("Missing short usage on %q\nstderr:%q", args, stderr) } // But shouldn't have full usage if strings.Contains(stderr, "--help=false") { c.Fatalf("Should not have full usage on %q\nstderr:%q", args, stderr) } if strings.HasSuffix(stderr, "\n\n") { c.Fatalf("Should not have a blank line on %q\nstderr:%q", args, stderr) } } } expected := 39 if len(cmds) != expected { c.Fatalf("Wrong # of cmds(%d), it should be: %d\nThe list:\n%q", len(cmds), expected, cmds) } } } func (s *DockerSuite) TestHelpExitCodesHelpOutput(c *check.C) { // Test to make sure the exit code and output (stdout vs stderr) of // various good and bad cases are what we expect // docker : stdout=all, stderr=empty, rc=0 cmd := exec.Command(dockerBinary) stdout, stderr, ec, err := runCommandWithStdoutStderr(cmd) if len(stdout) == 0 || len(stderr) != 0 || ec != 0 || err != nil { c.Fatalf("Bad results from 'docker'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } // Be really pick if strings.HasSuffix(stdout, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker'\n%s", stdout) } // docker help: stdout=all, stderr=empty, rc=0 cmd = exec.Command(dockerBinary, "help") stdout, stderr, ec, err = runCommandWithStdoutStderr(cmd) if len(stdout) == 0 || len(stderr) != 0 || ec != 0 || err != nil { c.Fatalf("Bad results from 'docker help'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } // Be really pick if strings.HasSuffix(stdout, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker help'\n%s", stdout) } // docker --help: stdout=all, stderr=empty, rc=0 cmd = exec.Command(dockerBinary, "--help") stdout, stderr, ec, err = runCommandWithStdoutStderr(cmd) if len(stdout) == 0 || len(stderr) != 0 || ec != 0 || err != nil { c.Fatalf("Bad results from 'docker --help'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } // Be really pick if strings.HasSuffix(stdout, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker --help'\n%s", stdout) } // docker inspect busybox: stdout=all, stderr=empty, rc=0 // Just making sure stderr is empty on valid cmd cmd = exec.Command(dockerBinary, "inspect", "busybox") stdout, stderr, ec, err = runCommandWithStdoutStderr(cmd) if len(stdout) == 0 || len(stderr) != 0 || ec != 0 || err != nil { c.Fatalf("Bad results from 'docker inspect busybox'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } // Be really pick if strings.HasSuffix(stdout, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker inspect busyBox'\n%s", stdout) } // docker rm: stdout=empty, stderr=all, rc!=0 // testing the min arg error msg cmd = exec.Command(dockerBinary, "rm") stdout, stderr, ec, err = runCommandWithStdoutStderr(cmd) if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad results from 'docker rm'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } // Should not contain full help text but should contain info about // # of args and Usage line if !strings.Contains(stderr, "requires a minimum") { c.Fatalf("Missing # of args text from 'docker rm'\nstderr:%s", stderr) } // docker rm NoSuchContainer: stdout=empty, stderr=all, rc=0 // testing to make sure no blank line on error cmd = exec.Command(dockerBinary, "rm", "NoSuchContainer") stdout, stderr, ec, err = runCommandWithStdoutStderr(cmd) if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad results from 'docker rm NoSuchContainer'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } // Be really picky if strings.HasSuffix(stderr, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker rm'\n%s", stderr) } // docker BadCmd: stdout=empty, stderr=all, rc=0 cmd = exec.Command(dockerBinary, "BadCmd") stdout, stderr, ec, err = runCommandWithStdoutStderr(cmd) if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad results from 'docker BadCmd'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", ec, stdout, stderr, err) } if stderr != "docker: 'BadCmd' is not a docker command.\nSee 'docker --help'.\n" { c.Fatalf("Unexcepted output for 'docker badCmd'\nstderr:%s", stderr) } // Be really picky if strings.HasSuffix(stderr, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker rm'\n%s", stderr) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_history_test.go ================================================ package main import ( "fmt" "regexp" "strconv" "strings" "github.com/go-check/check" ) // This is a heisen-test. Because the created timestamp of images and the behavior of // sort is not predictable it doesn't always fail. func (s *DockerSuite) TestBuildHistory(c *check.C) { name := "testbuildhistory" _, err := buildImage(name, `FROM busybox RUN echo "A" RUN echo "B" RUN echo "C" RUN echo "D" RUN echo "E" RUN echo "F" RUN echo "G" RUN echo "H" RUN echo "I" RUN echo "J" RUN echo "K" RUN echo "L" RUN echo "M" RUN echo "N" RUN echo "O" RUN echo "P" RUN echo "Q" RUN echo "R" RUN echo "S" RUN echo "T" RUN echo "U" RUN echo "V" RUN echo "W" RUN echo "X" RUN echo "Y" RUN echo "Z"`, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "history", "testbuildhistory") actualValues := strings.Split(out, "\n")[1:27] expectedValues := [26]string{"Z", "Y", "X", "W", "V", "U", "T", "S", "R", "Q", "P", "O", "N", "M", "L", "K", "J", "I", "H", "G", "F", "E", "D", "C", "B", "A"} for i := 0; i < 26; i++ { echoValue := fmt.Sprintf("echo \"%s\"", expectedValues[i]) actualValue := actualValues[i] if !strings.Contains(actualValue, echoValue) { c.Fatalf("Expected layer \"%s\", but was: %s", expectedValues[i], actualValue) } } } func (s *DockerSuite) TestHistoryExistentImage(c *check.C) { dockerCmd(c, "history", "busybox") } func (s *DockerSuite) TestHistoryNonExistentImage(c *check.C) { _, _, err := dockerCmdWithError(c, "history", "testHistoryNonExistentImage") if err == nil { c.Fatal("history on a non-existent image should fail.") } } func (s *DockerSuite) TestHistoryImageWithComment(c *check.C) { name := "testhistoryimagewithcomment" // make a image through docker commit [ -m messages ] dockerCmd(c, "run", "--name", name, "busybox", "true") dockerCmd(c, "wait", name) comment := "This_is_a_comment" dockerCmd(c, "commit", "-m="+comment, name, name) // test docker history to check comment messages out, _ := dockerCmd(c, "history", name) outputTabs := strings.Fields(strings.Split(out, "\n")[1]) actualValue := outputTabs[len(outputTabs)-1] if !strings.Contains(actualValue, comment) { c.Fatalf("Expected comments %q, but found %q", comment, actualValue) } } func (s *DockerSuite) TestHistoryHumanOptionFalse(c *check.C) { out, _ := dockerCmd(c, "history", "--human=false", "busybox") lines := strings.Split(out, "\n") sizeColumnRegex, _ := regexp.Compile("SIZE +") indices := sizeColumnRegex.FindStringIndex(lines[0]) startIndex := indices[0] endIndex := indices[1] for i := 1; i < len(lines)-1; i++ { if endIndex > len(lines[i]) { endIndex = len(lines[i]) } sizeString := lines[i][startIndex:endIndex] if _, err := strconv.Atoi(strings.TrimSpace(sizeString)); err != nil { c.Fatalf("The size '%s' was not an Integer", sizeString) } } } func (s *DockerSuite) TestHistoryHumanOptionTrue(c *check.C) { out, _ := dockerCmd(c, "history", "--human=true", "busybox") lines := strings.Split(out, "\n") sizeColumnRegex, _ := regexp.Compile("SIZE +") humanSizeRegex, _ := regexp.Compile("^\\d+.*B$") // Matches human sizes like 10 MB, 3.2 KB, etc indices := sizeColumnRegex.FindStringIndex(lines[0]) startIndex := indices[0] endIndex := indices[1] for i := 1; i < len(lines)-1; i++ { if endIndex > len(lines[i]) { endIndex = len(lines[i]) } sizeString := lines[i][startIndex:endIndex] if matchSuccess := humanSizeRegex.MatchString(strings.TrimSpace(sizeString)); !matchSuccess { c.Fatalf("The size '%s' was not in human format", sizeString) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_images_test.go ================================================ package main import ( "fmt" "reflect" "sort" "strings" "time" "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" ) func (s *DockerSuite) TestImagesEnsureImageIsListed(c *check.C) { out, _ := dockerCmd(c, "images") if !strings.Contains(out, "busybox") { c.Fatal("images should've listed busybox") } } func (s *DockerSuite) TestImagesOrderedByCreationDate(c *check.C) { id1, err := buildImage("order:test_a", `FROM scratch MAINTAINER dockerio1`, true) if err != nil { c.Fatal(err) } time.Sleep(time.Second) id2, err := buildImage("order:test_c", `FROM scratch MAINTAINER dockerio2`, true) if err != nil { c.Fatal(err) } time.Sleep(time.Second) id3, err := buildImage("order:test_b", `FROM scratch MAINTAINER dockerio3`, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "images", "-q", "--no-trunc") imgs := strings.Split(out, "\n") if imgs[0] != id3 { c.Fatalf("First image must be %s, got %s", id3, imgs[0]) } if imgs[1] != id2 { c.Fatalf("Second image must be %s, got %s", id2, imgs[1]) } if imgs[2] != id1 { c.Fatalf("Third image must be %s, got %s", id1, imgs[2]) } } func (s *DockerSuite) TestImagesErrorWithInvalidFilterNameTest(c *check.C) { out, _, err := dockerCmdWithError(c, "images", "-f", "FOO=123") if err == nil || !strings.Contains(out, "Invalid filter") { c.Fatalf("error should occur when listing images with invalid filter name FOO, %s", out) } } func (s *DockerSuite) TestImagesFilterLabel(c *check.C) { imageName1 := "images_filter_test1" imageName2 := "images_filter_test2" imageName3 := "images_filter_test3" image1ID, err := buildImage(imageName1, `FROM scratch LABEL match me`, true) if err != nil { c.Fatal(err) } image2ID, err := buildImage(imageName2, `FROM scratch LABEL match="me too"`, true) if err != nil { c.Fatal(err) } image3ID, err := buildImage(imageName3, `FROM scratch LABEL nomatch me`, true) if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match") out = strings.TrimSpace(out) if (!strings.Contains(out, image1ID) && !strings.Contains(out, image2ID)) || strings.Contains(out, image3ID) { c.Fatalf("Expected ids %s,%s got %s", image1ID, image2ID, out) } out, _ = dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match=me too") out = strings.TrimSpace(out) if out != image2ID { c.Fatalf("Expected %s got %s", image2ID, out) } } func (s *DockerSuite) TestImagesFilterSpaceTrimCase(c *check.C) { imageName := "images_filter_test" buildImage(imageName, `FROM scratch RUN touch /test/foo RUN touch /test/bar RUN touch /test/baz`, true) filters := []string{ "dangling=true", "Dangling=true", " dangling=true", "dangling=true ", "dangling = true", } imageListings := make([][]string, 5, 5) for idx, filter := range filters { out, _ := dockerCmd(c, "images", "-q", "-f", filter) listing := strings.Split(out, "\n") sort.Strings(listing) imageListings[idx] = listing } for idx, listing := range imageListings { if idx < 4 && !reflect.DeepEqual(listing, imageListings[idx+1]) { for idx, errListing := range imageListings { fmt.Printf("out %d", idx) for _, image := range errListing { fmt.Print(image) } fmt.Print("") } c.Fatalf("All output must be the same") } } } func (s *DockerSuite) TestImagesEnsureDanglingImageOnlyListedOnce(c *check.C) { // create container 1 out, _ := dockerCmd(c, "run", "-d", "busybox", "true") containerId1 := strings.TrimSpace(out) // tag as foobox out, _ = dockerCmd(c, "commit", containerId1, "foobox") imageId := stringid.TruncateID(strings.TrimSpace(out)) // overwrite the tag, making the previous image dangling dockerCmd(c, "tag", "-f", "busybox", "foobox") out, _ = dockerCmd(c, "images", "-q", "-f", "dangling=true") if e, a := 1, strings.Count(out, imageId); e != a { c.Fatalf("expected 1 dangling image, got %d: %s", a, out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_import_test.go ================================================ package main import ( "bufio" "io/ioutil" "os" "os/exec" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestImportDisplay(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "true") cleanedContainerID := strings.TrimSpace(out) out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "export", cleanedContainerID), exec.Command(dockerBinary, "import", "-"), ) if err != nil { c.Errorf("import failed with errors: %v, output: %q", err, out) } if n := strings.Count(out, "\n"); n != 1 { c.Fatalf("display is messed up: %d '\\n' instead of 1:\n%s", n, out) } image := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "--rm", image, "true") if out != "" { c.Fatalf("command output should've been nothing, was %q", out) } } func (s *DockerSuite) TestImportBadURL(c *check.C) { out, _, err := dockerCmdWithError(c, "import", "http://nourl/bad") if err == nil { c.Fatal("import was supposed to fail but didn't") } if !strings.Contains(out, "dial tcp") { c.Fatalf("expected an error msg but didn't get one:\n%s", out) } } func (s *DockerSuite) TestImportFile(c *check.C) { dockerCmd(c, "run", "--name", "test-import", "busybox", "true") temporaryFile, err := ioutil.TempFile("", "exportImportTest") if err != nil { c.Fatal("failed to create temporary file", "", err) } defer os.Remove(temporaryFile.Name()) runCmd := exec.Command(dockerBinary, "export", "test-import") runCmd.Stdout = bufio.NewWriter(temporaryFile) _, err = runCommand(runCmd) if err != nil { c.Fatal("failed to export a container", err) } out, _ := dockerCmd(c, "import", temporaryFile.Name()) if n := strings.Count(out, "\n"); n != 1 { c.Fatalf("display is messed up: %d '\\n' instead of 1:\n%s", n, out) } image := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "--rm", image, "true") if out != "" { c.Fatalf("command output should've been nothing, was %q", out) } } func (s *DockerSuite) TestImportFileNonExistentFile(c *check.C) { _, exitCode, err := dockerCmdWithError(c, "import", "example.com/myImage.tar") if exitCode == 0 || err == nil { c.Fatalf("import non-existing file must failed") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_info_test.go ================================================ package main import ( "strings" "github.com/docker/docker/utils" "github.com/go-check/check" ) // ensure docker info succeeds func (s *DockerSuite) TestInfoEnsureSucceeds(c *check.C) { out, _ := dockerCmd(c, "info") // always shown fields stringsToCheck := []string{ "ID:", "Containers:", "Images:", "Execution Driver:", "Logging Driver:", "Operating System:", "CPUs:", "Total Memory:", "Kernel Version:", "Storage Driver:", } if utils.ExperimentalBuild() { stringsToCheck = append(stringsToCheck, "Experimental: true") } for _, linePrefix := range stringsToCheck { if !strings.Contains(out, linePrefix) { c.Errorf("couldn't find string %v in output", linePrefix) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_inspect_experimental_test.go ================================================ // +build experimental package main import ( "github.com/docker/docker/api/types" "github.com/go-check/check" ) func (s *DockerSuite) TestInspectNamedMountPoint(c *check.C) { dockerCmd(c, "run", "-d", "--name", "test", "-v", "data:/data", "busybox", "cat") vol, err := inspectFieldJSON("test", "Mounts") c.Assert(err, check.IsNil) var mp []types.MountPoint err = unmarshalJSON([]byte(vol), &mp) c.Assert(err, check.IsNil) if len(mp) != 1 { c.Fatalf("Expected 1 mount point, was %v\n", len(mp)) } m := mp[0] if m.Name != "data" { c.Fatalf("Expected name data, was %s\n", m.Name) } if m.Driver != "local" { c.Fatalf("Expected driver local, was %s\n", m.Driver) } if m.Source == "" { c.Fatalf("Expected source to not be empty") } if m.RW != true { c.Fatalf("Expected rw to be true") } if m.Destination != "/data" { c.Fatalf("Expected destination /data, was %s\n", m.Destination) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_inspect_test.go ================================================ package main import ( "fmt" "os/exec" "strconv" "strings" "github.com/docker/docker/api/types" "github.com/go-check/check" ) func (s *DockerSuite) TestInspectImage(c *check.C) { imageTest := "emptyfs" imageTestID := "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158" id, err := inspectField(imageTest, "Id") c.Assert(err, check.IsNil) if id != imageTestID { c.Fatalf("Expected id: %s for image: %s but received id: %s", imageTestID, imageTest, id) } } func (s *DockerSuite) TestInspectInt64(c *check.C) { runCmd := exec.Command(dockerBinary, "run", "-d", "-m=300M", "busybox", "true") out, _, _, err := runCommandWithStdoutStderr(runCmd) if err != nil { c.Fatalf("failed to run container: %v, output: %q", err, out) } out = strings.TrimSpace(out) inspectOut, err := inspectField(out, "HostConfig.Memory") c.Assert(err, check.IsNil) if inspectOut != "314572800" { c.Fatalf("inspect got wrong value, got: %q, expected: 314572800", inspectOut) } } func (s *DockerSuite) TestInspectDefault(c *check.C) { //Both the container and image are named busybox. docker inspect will fetch the container JSON. //If the container JSON is not available, it will go for the image JSON. dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") dockerCmd(c, "inspect", "busybox") } func (s *DockerSuite) TestInspectTypeFlagContainer(c *check.C) { //Both the container and image are named busybox. docker inspect will fetch container //JSON State.Running field. If the field is true, it's a container. dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "top") formatStr := fmt.Sprintf("--format='{{.State.Running}}'") out, exitCode, err := dockerCmdWithError(c, "inspect", "--type=container", formatStr, "busybox") if exitCode != 0 || err != nil { c.Fatalf("failed to inspect container: %s, %v", out, err) } if out != "true\n" { c.Fatal("not a container JSON") } } func (s *DockerSuite) TestInspectTypeFlagWithNoContainer(c *check.C) { //Run this test on an image named busybox. docker inspect will try to fetch container //JSON. Since there is no container named busybox and --type=container, docker inspect will //not try to get the image JSON. It will throw an error. dockerCmd(c, "run", "-d", "busybox", "true") _, exitCode, err := dockerCmdWithError(c, "inspect", "--type=container", "busybox") if exitCode == 0 || err == nil { c.Fatalf("docker inspect should have failed, as there is no container named busybox") } } func (s *DockerSuite) TestInspectTypeFlagWithImage(c *check.C) { //Both the container and image are named busybox. docker inspect will fetch image //JSON as --type=image. if there is no image with name busybox, docker inspect //will throw an error. dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") out, exitCode, err := dockerCmdWithError(c, "inspect", "--type=image", "busybox") if exitCode != 0 || err != nil { c.Fatalf("failed to inspect image: %s, %v", out, err) } if strings.Contains(out, "State") { c.Fatal("not an image JSON") } } func (s *DockerSuite) TestInspectTypeFlagWithInvalidValue(c *check.C) { //Both the container and image are named busybox. docker inspect will fail //as --type=foobar is not a valid value for the flag. dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") out, exitCode, err := dockerCmdWithError(c, "inspect", "--type=foobar", "busybox") if exitCode != 0 || err != nil { if !strings.Contains(out, "not a valid value for --type") { c.Fatalf("failed to inspect image: %s, %v", out, err) } } } func (s *DockerSuite) TestInspectImageFilterInt(c *check.C) { imageTest := "emptyfs" out, err := inspectField(imageTest, "Size") c.Assert(err, check.IsNil) size, err := strconv.Atoi(out) if err != nil { c.Fatalf("failed to inspect size of the image: %s, %v", out, err) } //now see if the size turns out to be the same formatStr := fmt.Sprintf("--format='{{eq .Size %d}}'", size) out, exitCode, err := dockerCmdWithError(c, "inspect", formatStr, imageTest) if exitCode != 0 || err != nil { c.Fatalf("failed to inspect image: %s, %v", out, err) } if result, err := strconv.ParseBool(strings.TrimSuffix(out, "\n")); err != nil || !result { c.Fatalf("Expected size: %d for image: %s but received size: %s", size, imageTest, strings.TrimSuffix(out, "\n")) } } func (s *DockerSuite) TestInspectContainerFilterInt(c *check.C) { runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat") runCmd.Stdin = strings.NewReader("blahblah") out, _, _, err := runCommandWithStdoutStderr(runCmd) if err != nil { c.Fatalf("failed to run container: %v, output: %q", err, out) } id := strings.TrimSpace(out) out, err = inspectField(id, "State.ExitCode") c.Assert(err, check.IsNil) exitCode, err := strconv.Atoi(out) if err != nil { c.Fatalf("failed to inspect exitcode of the container: %s, %v", out, err) } //now get the exit code to verify formatStr := fmt.Sprintf("--format='{{eq .State.ExitCode %d}}'", exitCode) out, _ = dockerCmd(c, "inspect", formatStr, id) if result, err := strconv.ParseBool(strings.TrimSuffix(out, "\n")); err != nil || !result { c.Fatalf("Expected exitcode: %d for container: %s", exitCode, id) } } func (s *DockerSuite) TestInspectImageGraphDriver(c *check.C) { imageTest := "emptyfs" name, err := inspectField(imageTest, "GraphDriver.Name") c.Assert(err, check.IsNil) if name != "devicemapper" && name != "overlay" && name != "vfs" && name != "zfs" && name != "btrfs" && name != "aufs" { c.Fatalf("%v is not a valid graph driver name", name) } if name != "devicemapper" { return } deviceId, err := inspectField(imageTest, "GraphDriver.Data.DeviceId") c.Assert(err, check.IsNil) _, err = strconv.Atoi(deviceId) if err != nil { c.Fatalf("failed to inspect DeviceId of the image: %s, %v", deviceId, err) } deviceSize, err := inspectField(imageTest, "GraphDriver.Data.DeviceSize") c.Assert(err, check.IsNil) _, err = strconv.ParseUint(deviceSize, 10, 64) if err != nil { c.Fatalf("failed to inspect DeviceSize of the image: %s, %v", deviceSize, err) } } func (s *DockerSuite) TestInspectContainerGraphDriver(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "true") out = strings.TrimSpace(out) name, err := inspectField(out, "GraphDriver.Name") c.Assert(err, check.IsNil) if name != "devicemapper" && name != "overlay" && name != "vfs" && name != "zfs" && name != "btrfs" && name != "aufs" { c.Fatalf("%v is not a valid graph driver name", name) } if name != "devicemapper" { return } deviceId, err := inspectField(out, "GraphDriver.Data.DeviceId") c.Assert(err, check.IsNil) _, err = strconv.Atoi(deviceId) if err != nil { c.Fatalf("failed to inspect DeviceId of the image: %s, %v", deviceId, err) } deviceSize, err := inspectField(out, "GraphDriver.Data.DeviceSize") c.Assert(err, check.IsNil) _, err = strconv.ParseUint(deviceSize, 10, 64) if err != nil { c.Fatalf("failed to inspect DeviceSize of the image: %s, %v", deviceSize, err) } } func (s *DockerSuite) TestInspectBindMountPoint(c *check.C) { dockerCmd(c, "run", "-d", "--name", "test", "-v", "/data:/data:ro,z", "busybox", "cat") vol, err := inspectFieldJSON("test", "Mounts") c.Assert(err, check.IsNil) var mp []types.MountPoint err = unmarshalJSON([]byte(vol), &mp) c.Assert(err, check.IsNil) if len(mp) != 1 { c.Fatalf("Expected 1 mount point, was %v\n", len(mp)) } m := mp[0] if m.Name != "" { c.Fatal("Expected name to be empty") } if m.Driver != "" { c.Fatal("Expected driver to be empty") } if m.Source != "/data" { c.Fatalf("Expected source /data, was %s\n", m.Source) } if m.Destination != "/data" { c.Fatalf("Expected destination /data, was %s\n", m.Destination) } if m.Mode != "ro,z" { c.Fatalf("Expected mode `ro,z`, was %s\n", m.Mode) } if m.RW != false { c.Fatalf("Expected rw to be false") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_kill_test.go ================================================ package main import ( "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestKillContainer(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) c.Assert(waitRun(cleanedContainerID), check.IsNil) dockerCmd(c, "kill", cleanedContainerID) out, _ = dockerCmd(c, "ps", "-q") if strings.Contains(out, cleanedContainerID) { c.Fatal("killed container is still running") } } func (s *DockerSuite) TestKillofStoppedContainer(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "stop", cleanedContainerID) _, _, err := dockerCmdWithError(c, "kill", "-s", "30", cleanedContainerID) c.Assert(err, check.Not(check.IsNil), check.Commentf("Container %s is not running", cleanedContainerID)) } func (s *DockerSuite) TestKillDifferentUserContainer(c *check.C) { out, _ := dockerCmd(c, "run", "-u", "daemon", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) c.Assert(waitRun(cleanedContainerID), check.IsNil) dockerCmd(c, "kill", cleanedContainerID) out, _ = dockerCmd(c, "ps", "-q") if strings.Contains(out, cleanedContainerID) { c.Fatal("killed container is still running") } } // regression test about correct signal parsing see #13665 func (s *DockerSuite) TestKillWithSignal(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cid := strings.TrimSpace(out) c.Assert(waitRun(cid), check.IsNil) dockerCmd(c, "kill", "-s", "SIGWINCH", cid) running, _ := inspectField(cid, "State.Running") if running != "true" { c.Fatal("Container should be in running state after SIGWINCH") } } func (s *DockerSuite) TestKillWithInvalidSignal(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cid := strings.TrimSpace(out) c.Assert(waitRun(cid), check.IsNil) out, _, err := dockerCmdWithError(c, "kill", "-s", "0", cid) c.Assert(err, check.NotNil) if !strings.ContainsAny(out, "Invalid signal: 0") { c.Fatal("Kill with an invalid signal didn't error out correctly") } running, _ := inspectField(cid, "State.Running") if running != "true" { c.Fatal("Container should be in running state after an invalid signal") } out, _ = dockerCmd(c, "run", "-d", "busybox", "top") cid = strings.TrimSpace(out) c.Assert(waitRun(cid), check.IsNil) out, _, err = dockerCmdWithError(c, "kill", "-s", "SIG42", cid) c.Assert(err, check.NotNil) if !strings.ContainsAny(out, "Invalid signal: SIG42") { c.Fatal("Kill with an invalid signal error out correctly") } running, _ = inspectField(cid, "State.Running") if running != "true" { c.Fatal("Container should be in running state after an invalid signal") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_links_test.go ================================================ package main import ( "fmt" "github.com/go-check/check" "reflect" "regexp" "strings" "time" ) func (s *DockerSuite) TestLinksPingUnlinkedContainers(c *check.C) { _, exitCode, err := dockerCmdWithError(c, "run", "--rm", "busybox", "sh", "-c", "ping -c 1 alias1 -W 1 && ping -c 1 alias2 -W 1") if exitCode == 0 { c.Fatal("run ping did not fail") } else if exitCode != 1 { c.Fatalf("run ping failed with errors: %v", err) } } // Test for appropriate error when calling --link with an invalid target container func (s *DockerSuite) TestLinksInvalidContainerTarget(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--link", "bogus:alias", "busybox", "true") if err == nil { c.Fatal("an invalid container target should produce an error") } if !strings.Contains(out, "Could not get container") { c.Fatalf("error output expected 'Could not get container', but got %q instead; err: %v", out, err) } } func (s *DockerSuite) TestLinksPingLinkedContainers(c *check.C) { dockerCmd(c, "run", "-d", "--name", "container1", "--hostname", "fred", "busybox", "top") dockerCmd(c, "run", "-d", "--name", "container2", "--hostname", "wilma", "busybox", "top") runArgs := []string{"run", "--rm", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "sh", "-c"} pingCmd := "ping -c 1 %s -W 1 && ping -c 1 %s -W 1" // test ping by alias, ping by name, and ping by hostname // 1. Ping by alias dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "alias1", "alias2"))...) // 2. Ping by container name dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "container1", "container2"))...) // 3. Ping by hostname dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "fred", "wilma"))...) } func (s *DockerSuite) TestLinksPingLinkedContainersAfterRename(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") idA := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") idB := strings.TrimSpace(out) dockerCmd(c, "rename", "container1", "container_new") dockerCmd(c, "run", "--rm", "--link", "container_new:alias1", "--link", "container2:alias2", "busybox", "sh", "-c", "ping -c 1 alias1 -W 1 && ping -c 1 alias2 -W 1") dockerCmd(c, "kill", idA) dockerCmd(c, "kill", idB) } func (s *DockerSuite) TestLinksInspectLinksStarted(c *check.C) { var ( expected = map[string]struct{}{"/container1:/testinspectlink/alias1": {}, "/container2:/testinspectlink/alias2": {}} result []string ) dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") dockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") dockerCmd(c, "run", "-d", "--name", "testinspectlink", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "top") links, err := inspectFieldJSON("testinspectlink", "HostConfig.Links") if err != nil { c.Fatal(err) } err = unmarshalJSON([]byte(links), &result) if err != nil { c.Fatal(err) } output := convertSliceOfStringsToMap(result) equal := reflect.DeepEqual(output, expected) if !equal { c.Fatalf("Links %s, expected %s", result, expected) } } func (s *DockerSuite) TestLinksInspectLinksStopped(c *check.C) { var ( expected = map[string]struct{}{"/container1:/testinspectlink/alias1": {}, "/container2:/testinspectlink/alias2": {}} result []string ) dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") dockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") dockerCmd(c, "run", "-d", "--name", "testinspectlink", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "true") links, err := inspectFieldJSON("testinspectlink", "HostConfig.Links") if err != nil { c.Fatal(err) } err = unmarshalJSON([]byte(links), &result) if err != nil { c.Fatal(err) } output := convertSliceOfStringsToMap(result) equal := reflect.DeepEqual(output, expected) if !equal { c.Fatalf("Links %s, but expected %s", result, expected) } } func (s *DockerSuite) TestLinksNotStartedParentNotFail(c *check.C) { dockerCmd(c, "create", "--name=first", "busybox", "top") dockerCmd(c, "create", "--name=second", "--link=first:first", "busybox", "top") dockerCmd(c, "start", "first") } func (s *DockerSuite) TestLinksHostsFilesInject(c *check.C) { testRequires(c, SameHostDaemon, ExecSupport) out, _ := dockerCmd(c, "run", "-itd", "--name", "one", "busybox", "top") idOne := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "-itd", "--name", "two", "--link", "one:onetwo", "busybox", "top") idTwo := strings.TrimSpace(out) time.Sleep(1 * time.Second) contentOne, err := readContainerFileWithExec(idOne, "/etc/hosts") if err != nil { c.Fatal(err, string(contentOne)) } contentTwo, err := readContainerFileWithExec(idTwo, "/etc/hosts") if err != nil { c.Fatal(err, string(contentTwo)) } if !strings.Contains(string(contentTwo), "onetwo") { c.Fatal("Host is not present in updated hosts file", string(contentTwo)) } } func (s *DockerSuite) TestLinksUpdateOnRestart(c *check.C) { testRequires(c, SameHostDaemon, ExecSupport) dockerCmd(c, "run", "-d", "--name", "one", "busybox", "top") out, _ := dockerCmd(c, "run", "-d", "--name", "two", "--link", "one:onetwo", "--link", "one:one", "busybox", "top") id := strings.TrimSpace(string(out)) realIP, err := inspectField("one", "NetworkSettings.IPAddress") if err != nil { c.Fatal(err) } content, err := readContainerFileWithExec(id, "/etc/hosts") if err != nil { c.Fatal(err, string(content)) } getIP := func(hosts []byte, hostname string) string { re := regexp.MustCompile(fmt.Sprintf(`(\S*)\t%s`, regexp.QuoteMeta(hostname))) matches := re.FindSubmatch(hosts) if matches == nil { c.Fatalf("Hostname %s have no matches in hosts", hostname) } return string(matches[1]) } if ip := getIP(content, "one"); ip != realIP { c.Fatalf("For 'one' alias expected IP: %s, got: %s", realIP, ip) } if ip := getIP(content, "onetwo"); ip != realIP { c.Fatalf("For 'onetwo' alias expected IP: %s, got: %s", realIP, ip) } dockerCmd(c, "restart", "one") realIP, err = inspectField("one", "NetworkSettings.IPAddress") if err != nil { c.Fatal(err) } content, err = readContainerFileWithExec(id, "/etc/hosts") if err != nil { c.Fatal(err, string(content)) } if ip := getIP(content, "one"); ip != realIP { c.Fatalf("For 'one' alias expected IP: %s, got: %s", realIP, ip) } if ip := getIP(content, "onetwo"); ip != realIP { c.Fatalf("For 'onetwo' alias expected IP: %s, got: %s", realIP, ip) } } func (s *DockerSuite) TestLinksEnvs(c *check.C) { dockerCmd(c, "run", "-d", "-e", "e1=", "-e", "e2=v2", "-e", "e3=v3=v3", "--name=first", "busybox", "top") out, _ := dockerCmd(c, "run", "--name=second", "--link=first:first", "busybox", "env") if !strings.Contains(out, "FIRST_ENV_e1=\n") || !strings.Contains(out, "FIRST_ENV_e2=v2") || !strings.Contains(out, "FIRST_ENV_e3=v3=v3") { c.Fatalf("Incorrect output: %s", out) } } func (s *DockerSuite) TestLinkShortDefinition(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--name", "shortlinkdef", "busybox", "top") cid := strings.TrimSpace(out) c.Assert(waitRun(cid), check.IsNil) out, _ = dockerCmd(c, "run", "-d", "--name", "link2", "--link", "shortlinkdef", "busybox", "top") cid2 := strings.TrimSpace(out) c.Assert(waitRun(cid2), check.IsNil) links, err := inspectFieldJSON(cid2, "HostConfig.Links") c.Assert(err, check.IsNil) c.Assert(links, check.Equals, "[\"/shortlinkdef:/link2/shortlinkdef\"]") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_links_unix_test.go ================================================ // +build !windows package main import ( "io/ioutil" "os" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestLinksEtcHostsRegularFile(c *check.C) { out, _ := dockerCmd(c, "run", "--net=host", "busybox", "ls", "-la", "/etc/hosts") if !strings.HasPrefix(out, "-") { c.Errorf("/etc/hosts should be a regular file") } } func (s *DockerSuite) TestLinksEtcHostsContentMatch(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hosts") hosts, err := ioutil.ReadFile("/etc/hosts") if os.IsNotExist(err) { c.Skip("/etc/hosts does not exist, skip this test") } if out != string(hosts) { c.Errorf("container: %s\n\nhost:%s", out, hosts) } } func (s *DockerSuite) TestLinksNetworkHostContainer(c *check.C) { dockerCmd(c, "run", "-d", "--net", "host", "--name", "host_container", "busybox", "top") out, _, err := dockerCmdWithError(c, "run", "--name", "should_fail", "--link", "host_container:tester", "busybox", "true") if err == nil || !strings.Contains(out, "--net=host can't be used with links. This would result in undefined behavior") { c.Fatalf("Running container linking to a container with --net host should have failed: %s", out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_login_test.go ================================================ package main import ( "bytes" "os/exec" "github.com/go-check/check" ) func (s *DockerSuite) TestLoginWithoutTTY(c *check.C) { cmd := exec.Command(dockerBinary, "login") // Send to stdin so the process does not get the TTY cmd.Stdin = bytes.NewBufferString("buffer test string \n") // run the command and block until it's done if err := cmd.Run(); err == nil { c.Fatal("Expected non nil err when loginning in & TTY not available") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_logs_test.go ================================================ package main import ( "encoding/json" "fmt" "io" "os/exec" "regexp" "strconv" "strings" "time" "github.com/docker/docker/pkg/timeutils" "github.com/go-check/check" ) // This used to work, it test a log of PageSize-1 (gh#4851) func (s *DockerSuite) TestLogsContainerSmallerThanPage(c *check.C) { testLen := 32767 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n =; done; echo", testLen)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "logs", cleanedContainerID) if len(out) != testLen+1 { c.Fatalf("Expected log length of %d, received %d\n", testLen+1, len(out)) } } // Regression test: When going over the PageSize, it used to panic (gh#4851) func (s *DockerSuite) TestLogsContainerBiggerThanPage(c *check.C) { testLen := 32768 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n =; done; echo", testLen)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "logs", cleanedContainerID) if len(out) != testLen+1 { c.Fatalf("Expected log length of %d, received %d\n", testLen+1, len(out)) } } // Regression test: When going much over the PageSize, it used to block (gh#4851) func (s *DockerSuite) TestLogsContainerMuchBiggerThanPage(c *check.C) { testLen := 33000 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n =; done; echo", testLen)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "logs", cleanedContainerID) if len(out) != testLen+1 { c.Fatalf("Expected log length of %d, received %d\n", testLen+1, len(out)) } } func (s *DockerSuite) TestLogsTimestamps(c *check.C) { testLen := 100 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo =; done;", testLen)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "logs", "-t", cleanedContainerID) lines := strings.Split(out, "\n") if len(lines) != testLen+1 { c.Fatalf("Expected log %d lines, received %d\n", testLen+1, len(lines)) } ts := regexp.MustCompile(`^.* `) for _, l := range lines { if l != "" { _, err := time.Parse(timeutils.RFC3339NanoFixed+" ", ts.FindString(l)) if err != nil { c.Fatalf("Failed to parse timestamp from %v: %v", l, err) } if l[29] != 'Z' { // ensure we have padded 0's c.Fatalf("Timestamp isn't padded properly: %s", l) } } } } func (s *DockerSuite) TestLogsSeparateStderr(c *check.C) { msg := "stderr_log" out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("echo %s 1>&2", msg)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) stdout, stderr, _ := dockerCmdWithStdoutStderr(c, "logs", cleanedContainerID) if stdout != "" { c.Fatalf("Expected empty stdout stream, got %v", stdout) } stderr = strings.TrimSpace(stderr) if stderr != msg { c.Fatalf("Expected %v in stderr stream, got %v", msg, stderr) } } func (s *DockerSuite) TestLogsStderrInStdout(c *check.C) { msg := "stderr_log" out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "sh", "-c", fmt.Sprintf("echo %s 1>&2", msg)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) stdout, stderr, _ := dockerCmdWithStdoutStderr(c, "logs", cleanedContainerID) if stderr != "" { c.Fatalf("Expected empty stderr stream, got %v", stderr) } stdout = strings.TrimSpace(stdout) if stdout != msg { c.Fatalf("Expected %v in stdout stream, got %v", msg, stdout) } } func (s *DockerSuite) TestLogsTail(c *check.C) { testLen := 100 out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo =; done;", testLen)) cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "logs", "--tail", "5", cleanedContainerID) lines := strings.Split(out, "\n") if len(lines) != 6 { c.Fatalf("Expected log %d lines, received %d\n", 6, len(lines)) } out, _ = dockerCmd(c, "logs", "--tail", "all", cleanedContainerID) lines = strings.Split(out, "\n") if len(lines) != testLen+1 { c.Fatalf("Expected log %d lines, received %d\n", testLen+1, len(lines)) } out, _, _ = dockerCmdWithStdoutStderr(c, "logs", "--tail", "random", cleanedContainerID) lines = strings.Split(out, "\n") if len(lines) != testLen+1 { c.Fatalf("Expected log %d lines, received %d\n", testLen+1, len(lines)) } } func (s *DockerSuite) TestLogsFollowStopped(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) logsCmd := exec.Command(dockerBinary, "logs", "-f", cleanedContainerID) if err := logsCmd.Start(); err != nil { c.Fatal(err) } errChan := make(chan error) go func() { errChan <- logsCmd.Wait() close(errChan) }() select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(1 * time.Second): c.Fatal("Following logs is hanged") } } func (s *DockerSuite) TestLogsSince(c *check.C) { name := "testlogssince" out, _ := dockerCmd(c, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo `date +%s` log$i; done") log2Line := strings.Split(strings.Split(out, "\n")[1], " ") t, err := strconv.ParseInt(log2Line[0], 10, 64) // the timestamp log2 is writen c.Assert(err, check.IsNil) since := t + 1 // add 1s so log1 & log2 doesn't show up out, _ = dockerCmd(c, "logs", "-t", fmt.Sprintf("--since=%v", since), name) // Skip 2 seconds unexpected := []string{"log1", "log2"} for _, v := range unexpected { if strings.Contains(out, v) { c.Fatalf("unexpected log message returned=%v, since=%v\nout=%v", v, since, out) } } // Test with default value specified and parameter omitted expected := []string{"log1", "log2", "log3"} for _, cmd := range []*exec.Cmd{ exec.Command(dockerBinary, "logs", "-t", name), exec.Command(dockerBinary, "logs", "-t", "--since=0", name), } { out, _, err = runCommandWithOutput(cmd) if err != nil { c.Fatalf("failed to log container: %s, %v", out, err) } for _, v := range expected { if !strings.Contains(out, v) { c.Fatalf("'%v' does not contain=%v\nout=%s", cmd.Args, v, out) } } } } func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do date +%s; sleep 1; done`) cleanedContainerID := strings.TrimSpace(out) now := daemonTime(c).Unix() since := now + 2 out, _ = dockerCmd(c, "logs", "-f", fmt.Sprintf("--since=%v", since), cleanedContainerID) lines := strings.Split(strings.TrimSpace(out), "\n") if len(lines) == 0 { c.Fatal("got no log lines") } for _, v := range lines { ts, err := strconv.ParseInt(v, 10, 64) if err != nil { c.Fatalf("cannot parse timestamp output from log: '%v'\nout=%s", v, out) } if ts < since { c.Fatalf("earlier log found. since=%v logdate=%v", since, ts) } } } // Regression test for #8832 func (s *DockerSuite) TestLogsFollowSlowStdoutConsumer(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", `usleep 200000;yes X | head -c 200000`) cleanedContainerID := strings.TrimSpace(out) stopSlowRead := make(chan bool) go func() { exec.Command(dockerBinary, "wait", cleanedContainerID).Run() stopSlowRead <- true }() logCmd := exec.Command(dockerBinary, "logs", "-f", cleanedContainerID) stdout, err := logCmd.StdoutPipe() c.Assert(err, check.IsNil) if err := logCmd.Start(); err != nil { c.Fatal(err) } // First read slowly bytes1, err := consumeWithSpeed(stdout, 10, 50*time.Millisecond, stopSlowRead) c.Assert(err, check.IsNil) // After the container has finished we can continue reading fast bytes2, err := consumeWithSpeed(stdout, 32*1024, 0, nil) c.Assert(err, check.IsNil) actual := bytes1 + bytes2 expected := 200000 if actual != expected { c.Fatalf("Invalid bytes read: %d, expected %d", actual, expected) } } func (s *DockerSuite) TestLogsFollowGoroutinesWithStdout(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 2; done") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) type info struct { NGoroutines int } getNGoroutines := func() int { var i info status, b, err := sockRequest("GET", "/info", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, 200) c.Assert(json.Unmarshal(b, &i), check.IsNil) return i.NGoroutines } nroutines := getNGoroutines() cmd := exec.Command(dockerBinary, "logs", "-f", id) r, w := io.Pipe() cmd.Stdout = w c.Assert(cmd.Start(), check.IsNil) // Make sure pipe is written to chErr := make(chan error) go func() { b := make([]byte, 1) _, err := r.Read(b) chErr <- err }() c.Assert(<-chErr, check.IsNil) c.Assert(cmd.Process.Kill(), check.IsNil) // NGoroutines is not updated right away, so we need to wait before failing t := time.After(30 * time.Second) for { select { case <-t: if n := getNGoroutines(); n > nroutines { c.Fatalf("leaked goroutines: expected less than or equal to %d, got: %d", nroutines, n) } default: if n := getNGoroutines(); n <= nroutines { return } time.Sleep(200 * time.Millisecond) } } } func (s *DockerSuite) TestLogsFollowGoroutinesNoOutput(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 2; done") id := strings.TrimSpace(out) c.Assert(waitRun(id), check.IsNil) type info struct { NGoroutines int } getNGoroutines := func() int { var i info status, b, err := sockRequest("GET", "/info", nil) c.Assert(err, check.IsNil) c.Assert(status, check.Equals, 200) c.Assert(json.Unmarshal(b, &i), check.IsNil) return i.NGoroutines } nroutines := getNGoroutines() cmd := exec.Command(dockerBinary, "logs", "-f", id) c.Assert(cmd.Start(), check.IsNil) time.Sleep(200 * time.Millisecond) c.Assert(cmd.Process.Kill(), check.IsNil) // NGoroutines is not updated right away, so we need to wait before failing t := time.After(30 * time.Second) for { select { case <-t: if n := getNGoroutines(); n > nroutines { c.Fatalf("leaked goroutines: expected less than or equal to %d, got: %d", nroutines, n) } default: if n := getNGoroutines(); n <= nroutines { return } time.Sleep(200 * time.Millisecond) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_nat_test.go ================================================ package main import ( "fmt" "io/ioutil" "net" "strings" "github.com/go-check/check" ) func startServerContainer(c *check.C, msg string, port int) string { name := "server" cmd := []string{ "-d", "-p", fmt.Sprintf("%d:%d", port, port), "busybox", "sh", "-c", fmt.Sprintf("echo %q | nc -lp %d", msg, port), } if err := waitForContainer(name, cmd...); err != nil { c.Fatalf("Failed to launch server container: %v", err) } return name } func getExternalAddress(c *check.C) net.IP { iface, err := net.InterfaceByName("eth0") if err != nil { c.Skip(fmt.Sprintf("Test not running with `make test`. Interface eth0 not found: %v", err)) } ifaceAddrs, err := iface.Addrs() if err != nil || len(ifaceAddrs) == 0 { c.Fatalf("Error retrieving addresses for eth0: %v (%d addresses)", err, len(ifaceAddrs)) } ifaceIP, _, err := net.ParseCIDR(ifaceAddrs[0].String()) if err != nil { c.Fatalf("Error retrieving the up for eth0: %s", err) } return ifaceIP } func getContainerLogs(c *check.C, containerID string) string { out, _ := dockerCmd(c, "logs", containerID) return strings.Trim(out, "\r\n") } func getContainerStatus(c *check.C, containerID string) string { out, err := inspectField(containerID, "State.Running") c.Assert(err, check.IsNil) return out } func (s *DockerSuite) TestNetworkNat(c *check.C) { testRequires(c, SameHostDaemon, NativeExecDriver) msg := "it works" startServerContainer(c, msg, 8080) endpoint := getExternalAddress(c) conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", endpoint.String(), 8080)) if err != nil { c.Fatalf("Failed to connect to container (%v)", err) } data, err := ioutil.ReadAll(conn) conn.Close() if err != nil { c.Fatal(err) } final := strings.TrimRight(string(data), "\n") if final != msg { c.Fatalf("Expected message %q but received %q", msg, final) } } func (s *DockerSuite) TestNetworkLocalhostTCPNat(c *check.C) { testRequires(c, SameHostDaemon, NativeExecDriver) var ( msg = "hi yall" ) startServerContainer(c, msg, 8081) conn, err := net.Dial("tcp", "localhost:8081") if err != nil { c.Fatalf("Failed to connect to container (%v)", err) } data, err := ioutil.ReadAll(conn) conn.Close() if err != nil { c.Fatal(err) } final := strings.TrimRight(string(data), "\n") if final != msg { c.Fatalf("Expected message %q but received %q", msg, final) } } func (s *DockerSuite) TestNetworkLoopbackNat(c *check.C) { testRequires(c, SameHostDaemon, NativeExecDriver) msg := "it works" startServerContainer(c, msg, 8080) endpoint := getExternalAddress(c) out, _ := dockerCmd(c, "run", "-t", "--net=container:server", "busybox", "sh", "-c", fmt.Sprintf("stty raw && nc -w 5 %s 8080", endpoint.String())) final := strings.TrimRight(string(out), "\n") if final != msg { c.Fatalf("Expected message %q but received %q", msg, final) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_network_test.go ================================================ // +build experimental package main import ( "strings" "github.com/go-check/check" ) func assertNwIsAvailable(c *check.C, name string) { if !isNwPresent(c, name) { c.Fatalf("Network %s not found in network ls o/p", name) } } func assertNwNotAvailable(c *check.C, name string) { if isNwPresent(c, name) { c.Fatalf("Found network %s in network ls o/p", name) } } func isNwPresent(c *check.C, name string) bool { out, _ := dockerCmd(c, "network", "ls") lines := strings.Split(out, "\n") for i := 1; i < len(lines)-1; i++ { if strings.Contains(lines[i], name) { return true } } return false } func (s *DockerSuite) TestDockerNetworkLsDefault(c *check.C) { defaults := []string{"bridge", "host", "none"} for _, nn := range defaults { assertNwIsAvailable(c, nn) } } func (s *DockerSuite) TestDockerNetworkCreateDelete(c *check.C) { dockerCmd(c, "network", "create", "test") assertNwIsAvailable(c, "test") dockerCmd(c, "network", "rm", "test") assertNwNotAvailable(c, "test") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_pause_test.go ================================================ package main import ( "fmt" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestPause(c *check.C) { defer unpauseAllContainers() name := "testeventpause" out, _ := dockerCmd(c, "images", "-q") image := strings.Split(out, "\n")[0] dockerCmd(c, "run", "-d", "--name", name, image, "top") dockerCmd(c, "pause", name) pausedContainers, err := getSliceOfPausedContainers() if err != nil { c.Fatalf("error thrown while checking if containers were paused: %v", err) } if len(pausedContainers) != 1 { c.Fatalf("there should be one paused container and not %d", len(pausedContainers)) } dockerCmd(c, "unpause", name) out, _ = dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") if len(events) <= 1 { c.Fatalf("Missing expected event") } pauseEvent := strings.Fields(events[len(events)-3]) unpauseEvent := strings.Fields(events[len(events)-2]) if pauseEvent[len(pauseEvent)-1] != "pause" { c.Fatalf("event should be pause, not %#v", pauseEvent) } if unpauseEvent[len(unpauseEvent)-1] != "unpause" { c.Fatalf("event should be unpause, not %#v", unpauseEvent) } } func (s *DockerSuite) TestPauseMultipleContainers(c *check.C) { defer unpauseAllContainers() containers := []string{ "testpausewithmorecontainers1", "testpausewithmorecontainers2", } out, _ := dockerCmd(c, "images", "-q") image := strings.Split(out, "\n")[0] for _, name := range containers { dockerCmd(c, "run", "-d", "--name", name, image, "top") } dockerCmd(c, append([]string{"pause"}, containers...)...) pausedContainers, err := getSliceOfPausedContainers() if err != nil { c.Fatalf("error thrown while checking if containers were paused: %v", err) } if len(pausedContainers) != len(containers) { c.Fatalf("there should be %d paused container and not %d", len(containers), len(pausedContainers)) } dockerCmd(c, append([]string{"unpause"}, containers...)...) out, _ = dockerCmd(c, "events", "--since=0", fmt.Sprintf("--until=%d", daemonTime(c).Unix())) events := strings.Split(out, "\n") if len(events) <= len(containers)*3-2 { c.Fatalf("Missing expected event") } pauseEvents := make([][]string, len(containers)) unpauseEvents := make([][]string, len(containers)) for i := range containers { pauseEvents[i] = strings.Fields(events[len(events)-len(containers)*2-1+i]) unpauseEvents[i] = strings.Fields(events[len(events)-len(containers)-1+i]) } for _, pauseEvent := range pauseEvents { if pauseEvent[len(pauseEvent)-1] != "pause" { c.Fatalf("event should be pause, not %#v", pauseEvent) } } for _, unpauseEvent := range unpauseEvents { if unpauseEvent[len(unpauseEvent)-1] != "unpause" { c.Fatalf("event should be unpause, not %#v", unpauseEvent) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_port_test.go ================================================ package main import ( "fmt" "regexp" "sort" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestPortList(c *check.C) { // one port out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "top") firstID := strings.TrimSpace(out) out, _ = dockerCmd(c, "port", firstID, "80") if !assertPortList(c, out, []string{"0.0.0.0:9876"}) { c.Error("Port list is not correct") } out, _ = dockerCmd(c, "port", firstID) if !assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876"}) { c.Error("Port list is not correct") } dockerCmd(c, "rm", "-f", firstID) // three port out, _ = dockerCmd(c, "run", "-d", "-p", "9876:80", "-p", "9877:81", "-p", "9878:82", "busybox", "top") ID := strings.TrimSpace(out) out, _ = dockerCmd(c, "port", ID, "80") if !assertPortList(c, out, []string{"0.0.0.0:9876"}) { c.Error("Port list is not correct") } out, _ = dockerCmd(c, "port", ID) if !assertPortList(c, out, []string{ "80/tcp -> 0.0.0.0:9876", "81/tcp -> 0.0.0.0:9877", "82/tcp -> 0.0.0.0:9878"}) { c.Error("Port list is not correct") } dockerCmd(c, "rm", "-f", ID) // more and one port mapped to the same container port out, _ = dockerCmd(c, "run", "-d", "-p", "9876:80", "-p", "9999:80", "-p", "9877:81", "-p", "9878:82", "busybox", "top") ID = strings.TrimSpace(out) out, _ = dockerCmd(c, "port", ID, "80") if !assertPortList(c, out, []string{"0.0.0.0:9876", "0.0.0.0:9999"}) { c.Error("Port list is not correct") } out, _ = dockerCmd(c, "port", ID) if !assertPortList(c, out, []string{ "80/tcp -> 0.0.0.0:9876", "80/tcp -> 0.0.0.0:9999", "81/tcp -> 0.0.0.0:9877", "82/tcp -> 0.0.0.0:9878"}) { c.Error("Port list is not correct\n", out) } dockerCmd(c, "rm", "-f", ID) } func assertPortList(c *check.C, out string, expected []string) bool { //lines := strings.Split(out, "\n") lines := strings.Split(strings.Trim(out, "\n "), "\n") if len(lines) != len(expected) { c.Errorf("different size lists %s, %d, %d", out, len(lines), len(expected)) return false } sort.Strings(lines) sort.Strings(expected) for i := 0; i < len(expected); i++ { if lines[i] != expected[i] { c.Error("|" + lines[i] + "!=" + expected[i] + "|") return false } } return true } func stopRemoveContainer(id string, c *check.C) { dockerCmd(c, "rm", "-f", id) } func (s *DockerSuite) TestUnpublishedPortsInPsOutput(c *check.C) { // Run busybox with command line expose (equivalent to EXPOSE in image's Dockerfile) for the following ports port1 := 80 port2 := 443 expose1 := fmt.Sprintf("--expose=%d", port1) expose2 := fmt.Sprintf("--expose=%d", port2) dockerCmd(c, "run", "-d", expose1, expose2, "busybox", "sleep", "5") // Check docker ps o/p for last created container reports the unpublished ports unpPort1 := fmt.Sprintf("%d/tcp", port1) unpPort2 := fmt.Sprintf("%d/tcp", port2) out, _ := dockerCmd(c, "ps", "-n=1") if !strings.Contains(out, unpPort1) || !strings.Contains(out, unpPort2) { c.Errorf("Missing unpublished ports(s) (%s, %s) in docker ps output: %s", unpPort1, unpPort2, out) } // Run the container forcing to publish the exposed ports dockerCmd(c, "run", "-d", "-P", expose1, expose2, "busybox", "sleep", "5") // Check docker ps o/p for last created container reports the exposed ports in the port bindings expBndRegx1 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort1) expBndRegx2 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort2) out, _ = dockerCmd(c, "ps", "-n=1") if !expBndRegx1.MatchString(out) || !expBndRegx2.MatchString(out) { c.Errorf("Cannot find expected port binding ports(s) (0.0.0.0:xxxxx->%s, 0.0.0.0:xxxxx->%s) in docker ps output:\n%s", unpPort1, unpPort2, out) } // Run the container specifying explicit port bindings for the exposed ports offset := 10000 pFlag1 := fmt.Sprintf("%d:%d", offset+port1, port1) pFlag2 := fmt.Sprintf("%d:%d", offset+port2, port2) out, _ = dockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, expose1, expose2, "busybox", "sleep", "5") id := strings.TrimSpace(out) // Check docker ps o/p for last created container reports the specified port mappings expBnd1 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port1, unpPort1) expBnd2 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port2, unpPort2) out, _ = dockerCmd(c, "ps", "-n=1") if !strings.Contains(out, expBnd1) || !strings.Contains(out, expBnd2) { c.Errorf("Cannot find expected port binding(s) (%s, %s) in docker ps output: %s", expBnd1, expBnd2, out) } // Remove container now otherwise it will interfeer with next test stopRemoveContainer(id, c) // Run the container with explicit port bindings and no exposed ports out, _ = dockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, "busybox", "sleep", "5") id = strings.TrimSpace(out) // Check docker ps o/p for last created container reports the specified port mappings out, _ = dockerCmd(c, "ps", "-n=1") if !strings.Contains(out, expBnd1) || !strings.Contains(out, expBnd2) { c.Errorf("Cannot find expected port binding(s) (%s, %s) in docker ps output: %s", expBnd1, expBnd2, out) } // Remove container now otherwise it will interfeer with next test stopRemoveContainer(id, c) // Run the container with one unpublished exposed port and one explicit port binding dockerCmd(c, "run", "-d", expose1, "-p", pFlag2, "busybox", "sleep", "5") // Check docker ps o/p for last created container reports the specified unpublished port and port mapping out, _ = dockerCmd(c, "ps", "-n=1") if !strings.Contains(out, unpPort1) || !strings.Contains(out, expBnd2) { c.Errorf("Missing unpublished ports or port binding (%s, %s) in docker ps output: %s", unpPort1, expBnd2, out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_port_unix_test.go ================================================ // +build !windows package main import ( "net" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestPortHostBinding(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "nc", "-l", "-p", "80") firstID := strings.TrimSpace(out) out, _ = dockerCmd(c, "port", firstID, "80") if !assertPortList(c, out, []string{"0.0.0.0:9876"}) { c.Error("Port list is not correct") } dockerCmd(c, "run", "--net=host", "busybox", "nc", "localhost", "9876") dockerCmd(c, "rm", "-f", firstID) if _, _, err := dockerCmdWithError(c, "run", "--net=host", "busybox", "nc", "localhost", "9876"); err == nil { c.Error("Port is still bound after the Container is removed") } } func (s *DockerSuite) TestPortExposeHostBinding(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-P", "--expose", "80", "busybox", "nc", "-l", "-p", "80") firstID := strings.TrimSpace(out) out, _ = dockerCmd(c, "port", firstID, "80") _, exposedPort, err := net.SplitHostPort(out) if err != nil { c.Fatal(out, err) } dockerCmd(c, "run", "--net=host", "busybox", "nc", "localhost", strings.TrimSpace(exposedPort)) dockerCmd(c, "rm", "-f", firstID) if _, _, err = dockerCmdWithError(c, "run", "--net=host", "busybox", "nc", "localhost", strings.TrimSpace(exposedPort)); err == nil { c.Error("Port is still bound after the Container is removed") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_proxy_test.go ================================================ package main import ( "net" "os/exec" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestCliProxyDisableProxyUnixSock(c *check.C) { testRequires(c, SameHostDaemon) // test is valid when DOCKER_HOST=unix://.. cmd := exec.Command(dockerBinary, "info") cmd.Env = appendBaseEnv([]string{"HTTP_PROXY=http://127.0.0.1:9999"}) if out, _, err := runCommandWithOutput(cmd); err != nil { c.Fatal(err, out) } } // Can't use localhost here since go has a special case to not use proxy if connecting to localhost // See https://golang.org/pkg/net/http/#ProxyFromEnvironment func (s *DockerDaemonSuite) TestCliProxyProxyTCPSock(c *check.C) { testRequires(c, SameHostDaemon) // get the IP to use to connect since we can't use localhost addrs, err := net.InterfaceAddrs() if err != nil { c.Fatal(err) } var ip string for _, addr := range addrs { sAddr := addr.String() if !strings.Contains(sAddr, "127.0.0.1") { addrArr := strings.Split(sAddr, "/") ip = addrArr[0] break } } if ip == "" { c.Fatal("could not find ip to connect to") } if err := s.d.Start("-H", "tcp://"+ip+":2375"); err != nil { c.Fatal(err) } cmd := exec.Command(dockerBinary, "info") cmd.Env = []string{"DOCKER_HOST=tcp://" + ip + ":2375", "HTTP_PROXY=127.0.0.1:9999"} if out, _, err := runCommandWithOutput(cmd); err == nil { c.Fatal(err, out) } // Test with no_proxy cmd.Env = append(cmd.Env, "NO_PROXY="+ip) if out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "info")); err != nil { c.Fatal(err, out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_ps_test.go ================================================ package main import ( "fmt" "os/exec" "reflect" "strconv" "strings" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestPsListContainers(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") firstID := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "-d", "busybox", "top") secondID := strings.TrimSpace(out) // not long running out, _ = dockerCmd(c, "run", "-d", "busybox", "true") thirdID := strings.TrimSpace(out) out, _ = dockerCmd(c, "run", "-d", "busybox", "top") fourthID := strings.TrimSpace(out) // make sure the second is running if err := waitRun(secondID); err != nil { c.Fatalf("waiting for container failed: %v", err) } // make sure third one is not running dockerCmd(c, "wait", thirdID) // make sure the forth is running if err := waitRun(fourthID); err != nil { c.Fatalf("waiting for container failed: %v", err) } // all out, _ = dockerCmd(c, "ps", "-a") if !assertContainerList(out, []string{fourthID, thirdID, secondID, firstID}) { c.Errorf("Container list is not in the correct order: %s", out) } // running out, _ = dockerCmd(c, "ps") if !assertContainerList(out, []string{fourthID, secondID, firstID}) { c.Errorf("Container list is not in the correct order: %s", out) } // from here all flag '-a' is ignored // limit out, _ = dockerCmd(c, "ps", "-n=2", "-a") expected := []string{fourthID, thirdID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "-n=2") if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } // since out, _ = dockerCmd(c, "ps", "--since", firstID, "-a") expected = []string{fourthID, thirdID, secondID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--since", firstID) if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } // before out, _ = dockerCmd(c, "ps", "--before", thirdID, "-a") expected = []string{secondID, firstID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--before", thirdID) if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } // since & before out, _ = dockerCmd(c, "ps", "--since", firstID, "--before", fourthID, "-a") expected = []string{thirdID, secondID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--since", firstID, "--before", fourthID) if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } // since & limit out, _ = dockerCmd(c, "ps", "--since", firstID, "-n=2", "-a") expected = []string{fourthID, thirdID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--since", firstID, "-n=2") if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } // before & limit out, _ = dockerCmd(c, "ps", "--before", fourthID, "-n=1", "-a") expected = []string{thirdID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--before", fourthID, "-n=1") if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--since", firstID, "--before", fourthID, "-n=1", "-a") expected = []string{thirdID} if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } out, _ = dockerCmd(c, "ps", "--since", firstID, "--before", fourthID, "-n=1") if !assertContainerList(out, expected) { c.Errorf("Container list is not in the correct order: %s", out) } } func assertContainerList(out string, expected []string) bool { lines := strings.Split(strings.Trim(out, "\n "), "\n") if len(lines)-1 != len(expected) { return false } containerIDIndex := strings.Index(lines[0], "CONTAINER ID") for i := 0; i < len(expected); i++ { foundID := lines[i+1][containerIDIndex : containerIDIndex+12] if foundID != expected[i][:12] { return false } } return true } func (s *DockerSuite) TestPsListContainersSize(c *check.C) { dockerCmd(c, "run", "-d", "busybox", "echo", "hello") baseOut, _ := dockerCmd(c, "ps", "-s", "-n=1") baseLines := strings.Split(strings.Trim(baseOut, "\n "), "\n") baseSizeIndex := strings.Index(baseLines[0], "SIZE") baseFoundsize := baseLines[1][baseSizeIndex:] baseBytes, err := strconv.Atoi(strings.Split(baseFoundsize, " ")[0]) if err != nil { c.Fatal(err) } name := "test_size" out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test") id, err := getIDByName(name) if err != nil { c.Fatal(err) } runCmd := exec.Command(dockerBinary, "ps", "-s", "-n=1") wait := make(chan struct{}) go func() { out, _, err = runCommandWithOutput(runCmd) close(wait) }() select { case <-wait: case <-time.After(3 * time.Second): c.Fatalf("Calling \"docker ps -s\" timed out!") } if err != nil { c.Fatal(out, err) } lines := strings.Split(strings.Trim(out, "\n "), "\n") if len(lines) != 2 { c.Fatalf("Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines)) } sizeIndex := strings.Index(lines[0], "SIZE") idIndex := strings.Index(lines[0], "CONTAINER ID") foundID := lines[1][idIndex : idIndex+12] if foundID != id[:12] { c.Fatalf("Expected id %s, got %s", id[:12], foundID) } expectedSize := fmt.Sprintf("%d B", (2 + baseBytes)) foundSize := lines[1][sizeIndex:] if !strings.Contains(foundSize, expectedSize) { c.Fatalf("Expected size %q, got %q", expectedSize, foundSize) } } func (s *DockerSuite) TestPsListContainersFilterStatus(c *check.C) { // FIXME: this should test paused, but it makes things hang and its wonky // this is because paused containers can't be controlled by signals // start exited container out, _ := dockerCmd(c, "run", "-d", "busybox") firstID := strings.TrimSpace(out) // make sure the exited cintainer is not running dockerCmd(c, "wait", firstID) // start running container out, _ = dockerCmd(c, "run", "-itd", "busybox") secondID := strings.TrimSpace(out) // filter containers by exited out, _ = dockerCmd(c, "ps", "-q", "--filter=status=exited") containerOut := strings.TrimSpace(out) if containerOut != firstID[:12] { c.Fatalf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out) } out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=status=running") containerOut = strings.TrimSpace(out) if containerOut != secondID[:12] { c.Fatalf("Expected id %s, got %s for running filter, output: %q", secondID[:12], containerOut, out) } out, _, _ = dockerCmdWithTimeout(time.Second*60, "ps", "-a", "-q", "--filter=status=rubbish") if !strings.Contains(out, "Unrecognised filter value for status") { c.Fatalf("Expected error response due to invalid status filter output: %q", out) } } func (s *DockerSuite) TestPsListContainersFilterID(c *check.C) { // start container out, _ := dockerCmd(c, "run", "-d", "busybox") firstID := strings.TrimSpace(out) // start another container dockerCmd(c, "run", "-d", "busybox", "top") // filter containers by id out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID) containerOut := strings.TrimSpace(out) if containerOut != firstID[:12] { c.Fatalf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out) } } func (s *DockerSuite) TestPsListContainersFilterName(c *check.C) { // start container out, _ := dockerCmd(c, "run", "-d", "--name=a_name_to_match", "busybox") firstID := strings.TrimSpace(out) // start another container dockerCmd(c, "run", "-d", "--name=b_name_to_match", "busybox", "top") // filter containers by name out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match") containerOut := strings.TrimSpace(out) if containerOut != firstID[:12] { c.Fatalf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out) } } func (s *DockerSuite) TestPsListContainersFilterLabel(c *check.C) { // start container out, _ := dockerCmd(c, "run", "-d", "-l", "match=me", "-l", "second=tag", "busybox") firstID := strings.TrimSpace(out) // start another container out, _ = dockerCmd(c, "run", "-d", "-l", "match=me too", "busybox") secondID := strings.TrimSpace(out) // start third container out, _ = dockerCmd(c, "run", "-d", "-l", "nomatch=me", "busybox") thirdID := strings.TrimSpace(out) // filter containers by exact match out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me") containerOut := strings.TrimSpace(out) if containerOut != firstID { c.Fatalf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out) } // filter containers by two labels out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag") containerOut = strings.TrimSpace(out) if containerOut != firstID { c.Fatalf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out) } // filter containers by two labels, but expect not found because of AND behavior out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag-no") containerOut = strings.TrimSpace(out) if containerOut != "" { c.Fatalf("Expected nothing, got %s for exited filter, output: %q", containerOut, out) } // filter containers by exact key out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match") containerOut = strings.TrimSpace(out) if (!strings.Contains(containerOut, firstID) || !strings.Contains(containerOut, secondID)) || strings.Contains(containerOut, thirdID) { c.Fatalf("Expected ids %s,%s, got %s for exited filter, output: %q", firstID, secondID, containerOut, out) } } func (s *DockerSuite) TestPsListContainersFilterExited(c *check.C) { dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top") dockerCmd(c, "run", "--name", "zero1", "busybox", "true") firstZero, err := getIDByName("zero1") if err != nil { c.Fatal(err) } dockerCmd(c, "run", "--name", "zero2", "busybox", "true") secondZero, err := getIDByName("zero2") if err != nil { c.Fatal(err) } if out, _, err := dockerCmdWithError(c, "run", "--name", "nonzero1", "busybox", "false"); err == nil { c.Fatal("Should fail.", out, err) } firstNonZero, err := getIDByName("nonzero1") if err != nil { c.Fatal(err) } if out, _, err := dockerCmdWithError(c, "run", "--name", "nonzero2", "busybox", "false"); err == nil { c.Fatal("Should fail.", out, err) } secondNonZero, err := getIDByName("nonzero2") if err != nil { c.Fatal(err) } // filter containers by exited=0 out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=0") ids := strings.Split(strings.TrimSpace(out), "\n") if len(ids) != 2 { c.Fatalf("Should be 2 zero exited containers got %d: %s", len(ids), out) } if ids[0] != secondZero { c.Fatalf("First in list should be %q, got %q", secondZero, ids[0]) } if ids[1] != firstZero { c.Fatalf("Second in list should be %q, got %q", firstZero, ids[1]) } out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=1") ids = strings.Split(strings.TrimSpace(out), "\n") if len(ids) != 2 { c.Fatalf("Should be 2 zero exited containers got %d", len(ids)) } if ids[0] != secondNonZero { c.Fatalf("First in list should be %q, got %q", secondNonZero, ids[0]) } if ids[1] != firstNonZero { c.Fatalf("Second in list should be %q, got %q", firstNonZero, ids[1]) } } func (s *DockerSuite) TestPsRightTagName(c *check.C) { tag := "asybox:shmatest" dockerCmd(c, "tag", "busybox", tag) var id1 string out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id1 = strings.TrimSpace(string(out)) var id2 string out, _ = dockerCmd(c, "run", "-d", tag, "top") id2 = strings.TrimSpace(string(out)) var imageID string out, _ = dockerCmd(c, "inspect", "-f", "{{.Id}}", "busybox") imageID = strings.TrimSpace(string(out)) var id3 string out, _ = dockerCmd(c, "run", "-d", imageID, "top") id3 = strings.TrimSpace(string(out)) out, _ = dockerCmd(c, "ps", "--no-trunc") lines := strings.Split(strings.TrimSpace(string(out)), "\n") // skip header lines = lines[1:] if len(lines) != 3 { c.Fatalf("There should be 3 running container, got %d", len(lines)) } for _, line := range lines { f := strings.Fields(line) switch f[0] { case id1: if f[1] != "busybox" { c.Fatalf("Expected %s tag for id %s, got %s", "busybox", id1, f[1]) } case id2: if f[1] != tag { c.Fatalf("Expected %s tag for id %s, got %s", tag, id2, f[1]) } case id3: if f[1] != imageID { c.Fatalf("Expected %s imageID for id %s, got %s", tag, id3, f[1]) } default: c.Fatalf("Unexpected id %s, expected %s and %s and %s", f[0], id1, id2, id3) } } } func (s *DockerSuite) TestPsLinkedWithNoTrunc(c *check.C) { dockerCmd(c, "run", "--name=first", "-d", "busybox", "top") dockerCmd(c, "run", "--name=second", "--link=first:first", "-d", "busybox", "top") out, _ := dockerCmd(c, "ps", "--no-trunc") lines := strings.Split(strings.TrimSpace(string(out)), "\n") // strip header lines = lines[1:] expected := []string{"second", "first,second/first"} var names []string for _, l := range lines { fields := strings.Fields(l) names = append(names, fields[len(fields)-1]) } if !reflect.DeepEqual(expected, names) { c.Fatalf("Expected array: %v, got: %v", expected, names) } } func (s *DockerSuite) TestPsGroupPortRange(c *check.C) { portRange := "3800-3900" dockerCmd(c, "run", "-d", "--name", "porttest", "-p", portRange+":"+portRange, "busybox", "top") out, _ := dockerCmd(c, "ps") // check that the port range is in the output if !strings.Contains(string(out), portRange) { c.Fatalf("docker ps output should have had the port range %q: %s", portRange, string(out)) } } func (s *DockerSuite) TestPsWithSize(c *check.C) { dockerCmd(c, "run", "-d", "--name", "sizetest", "busybox", "top") out, _ := dockerCmd(c, "ps", "--size") if !strings.Contains(out, "virtual") { c.Fatalf("docker ps with --size should show virtual size of container") } } func (s *DockerSuite) TestPsListContainersFilterCreated(c *check.C) { // create a container out, _ := dockerCmd(c, "create", "busybox") cID := strings.TrimSpace(out) shortCID := cID[:12] // Make sure it DOESN'T show up w/o a '-a' for normal 'ps' out, _ = dockerCmd(c, "ps", "-q") if strings.Contains(out, shortCID) { c.Fatalf("Should have not seen '%s' in ps output:\n%s", shortCID, out) } // Make sure it DOES show up as 'Created' for 'ps -a' out, _ = dockerCmd(c, "ps", "-a") hits := 0 for _, line := range strings.Split(out, "\n") { if !strings.Contains(line, shortCID) { continue } hits++ if !strings.Contains(line, "Created") { c.Fatalf("Missing 'Created' on '%s'", line) } } if hits != 1 { c.Fatalf("Should have seen '%s' in ps -a output once:%d\n%s", shortCID, hits, out) } // filter containers by 'create' - note, no -a needed out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created") containerOut := strings.TrimSpace(out) if !strings.HasPrefix(cID, containerOut) { c.Fatalf("Expected id %s, got %s for filter, out: %s", cID, containerOut, out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_pull_test.go ================================================ package main import ( "fmt" "strings" "github.com/go-check/check" ) // See issue docker/docker#8141 func (s *DockerRegistrySuite) TestPullImageWithAliases(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) repos := []string{} for _, tag := range []string{"recent", "fresh"} { repos = append(repos, fmt.Sprintf("%v:%v", repoName, tag)) } // Tag and push the same image multiple times. for _, repo := range repos { dockerCmd(c, "tag", "busybox", repo) dockerCmd(c, "push", repo) } // Clear local images store. args := append([]string{"rmi"}, repos...) dockerCmd(c, args...) // Pull a single tag and verify it doesn't bring down all aliases. dockerCmd(c, "pull", repos[0]) dockerCmd(c, "inspect", repos[0]) for _, repo := range repos[1:] { if _, _, err := dockerCmdWithError(c, "inspect", repo); err == nil { c.Fatalf("Image %v shouldn't have been pulled down", repo) } } } // pulling library/hello-world should show verified message func (s *DockerSuite) TestPullVerified(c *check.C) { c.Skip("Skipping hub dependent test") // Image must be pulled from central repository to get verified message // unless keychain is manually updated to contain the daemon's sign key. verifiedName := "hello-world" // pull it expected := "The image you are pulling has been verified" if out, exitCode, err := dockerCmdWithError(c, "pull", verifiedName); err != nil || !strings.Contains(out, expected) { if err != nil || exitCode != 0 { c.Skip(fmt.Sprintf("pulling the '%s' image from the registry has failed: %v", verifiedName, err)) } c.Fatalf("pulling a verified image failed. expected: %s\ngot: %s, %v", expected, out, err) } // pull it again if out, exitCode, err := dockerCmdWithError(c, "pull", verifiedName); err != nil || strings.Contains(out, expected) { if err != nil || exitCode != 0 { c.Skip(fmt.Sprintf("pulling the '%s' image from the registry has failed: %v", verifiedName, err)) } c.Fatalf("pulling a verified image failed. unexpected verify message\ngot: %s, %v", out, err) } } // pulling an image from the central registry should work func (s *DockerSuite) TestPullImageFromCentralRegistry(c *check.C) { testRequires(c, Network) dockerCmd(c, "pull", "hello-world") } // pulling a non-existing image from the central registry should return a non-zero exit code func (s *DockerSuite) TestPullNonExistingImage(c *check.C) { testRequires(c, Network) name := "sadfsadfasdf" out, _, err := dockerCmdWithError(c, "pull", name) if err == nil || !strings.Contains(out, fmt.Sprintf("Error: image library/%s:latest not found", name)) { c.Fatalf("expected non-zero exit status when pulling non-existing image: %s", out) } } // pulling an image from the central registry using official names should work // ensure all pulls result in the same image func (s *DockerSuite) TestPullImageOfficialNames(c *check.C) { testRequires(c, Network) names := []string{ "library/hello-world", "docker.io/library/hello-world", "index.docker.io/library/hello-world", } for _, name := range names { out, exitCode, err := dockerCmdWithError(c, "pull", name) if err != nil || exitCode != 0 { c.Errorf("pulling the '%s' image from the registry has failed: %s", name, err) continue } // ensure we don't have multiple image names. out, _ = dockerCmd(c, "images") if strings.Contains(out, name) { c.Errorf("images should not have listed '%s'", name) } } } func (s *DockerSuite) TestPullScratchNotAllowed(c *check.C) { testRequires(c, Network) out, exitCode, err := dockerCmdWithError(c, "pull", "scratch") if err == nil { c.Fatal("expected pull of scratch to fail, but it didn't") } if exitCode != 1 { c.Fatalf("pulling scratch expected exit code 1, got %d", exitCode) } if strings.Contains(out, "Pulling repository scratch") { c.Fatalf("pulling scratch should not have begun: %s", out) } if !strings.Contains(out, "'scratch' is a reserved name") { c.Fatalf("unexpected output pulling scratch: %s", out) } } // pulling an image with --all-tags=true func (s *DockerSuite) TestPullImageWithAllTagFromCentralRegistry(c *check.C) { testRequires(c, Network) dockerCmd(c, "pull", "busybox") outImageCmd, _ := dockerCmd(c, "images", "busybox") dockerCmd(c, "pull", "--all-tags=true", "busybox") outImageAllTagCmd, _ := dockerCmd(c, "images", "busybox") if strings.Count(outImageCmd, "busybox") >= strings.Count(outImageAllTagCmd, "busybox") { c.Fatalf("Pulling with all tags should get more images") } // FIXME has probably no effect (tags already pushed) dockerCmd(c, "pull", "-a", "busybox") outImageAllTagCmd, _ = dockerCmd(c, "images", "busybox") if strings.Count(outImageCmd, "busybox") >= strings.Count(outImageAllTagCmd, "busybox") { c.Fatalf("Pulling with all tags should get more images") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_push_test.go ================================================ package main import ( "archive/tar" "fmt" "io/ioutil" "os" "os/exec" "strings" "time" "github.com/go-check/check" ) // Pushing an image to a private registry. func (s *DockerRegistrySuite) TestPushBusyboxImage(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) // tag the image to upload it to the private registry dockerCmd(c, "tag", "busybox", repoName) // push the image to the registry dockerCmd(c, "push", repoName) } // pushing an image without a prefix should throw an error func (s *DockerSuite) TestPushUnprefixedRepo(c *check.C) { if out, _, err := dockerCmdWithError(c, "push", "busybox"); err == nil { c.Fatalf("pushing an unprefixed repo didn't result in a non-zero exit status: %s", out) } } func (s *DockerRegistrySuite) TestPushUntagged(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) expected := "Repository does not exist" if out, _, err := dockerCmdWithError(c, "push", repoName); err == nil { c.Fatalf("pushing the image to the private registry should have failed: output %q", out) } else if !strings.Contains(out, expected) { c.Fatalf("pushing the image failed with an unexpected message: expected %q, got %q", expected, out) } } func (s *DockerRegistrySuite) TestPushBadTag(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox:latest", privateRegistryURL) expected := "does not exist" if out, _, err := dockerCmdWithError(c, "push", repoName); err == nil { c.Fatalf("pushing the image to the private registry should have failed: output %q", out) } else if !strings.Contains(out, expected) { c.Fatalf("pushing the image failed with an unexpected message: expected %q, got %q", expected, out) } } func (s *DockerRegistrySuite) TestPushMultipleTags(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) repoTag1 := fmt.Sprintf("%v/dockercli/busybox:t1", privateRegistryURL) repoTag2 := fmt.Sprintf("%v/dockercli/busybox:t2", privateRegistryURL) // tag the image and upload it to the private registry dockerCmd(c, "tag", "busybox", repoTag1) dockerCmd(c, "tag", "busybox", repoTag2) dockerCmd(c, "push", repoName) } func (s *DockerRegistrySuite) TestPushInterrupt(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) // tag the image and upload it to the private registry dockerCmd(c, "tag", "busybox", repoName) pushCmd := exec.Command(dockerBinary, "push", repoName) if err := pushCmd.Start(); err != nil { c.Fatalf("Failed to start pushing to private registry: %v", err) } // Interrupt push (yes, we have no idea at what point it will get killed). time.Sleep(200 * time.Millisecond) if err := pushCmd.Process.Kill(); err != nil { c.Fatalf("Failed to kill push process: %v", err) } if out, _, err := dockerCmdWithError(c, "push", repoName); err == nil { str := string(out) if !strings.Contains(str, "already in progress") { c.Fatalf("Push should be continued on daemon side, but seems ok: %v, %s", err, out) } } // now wait until all this pushes will complete // if it failed with timeout - there would be some error, // so no logic about it here for exec.Command(dockerBinary, "push", repoName).Run() != nil { } } func (s *DockerRegistrySuite) TestPushEmptyLayer(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/emptylayer", privateRegistryURL) emptyTarball, err := ioutil.TempFile("", "empty_tarball") if err != nil { c.Fatalf("Unable to create test file: %v", err) } tw := tar.NewWriter(emptyTarball) err = tw.Close() if err != nil { c.Fatalf("Error creating empty tarball: %v", err) } freader, err := os.Open(emptyTarball.Name()) if err != nil { c.Fatalf("Could not open test tarball: %v", err) } importCmd := exec.Command(dockerBinary, "import", "-", repoName) importCmd.Stdin = freader out, _, err := runCommandWithOutput(importCmd) if err != nil { c.Errorf("import failed with errors: %v, output: %q", err, out) } // Now verify we can push it if out, _, err := dockerCmdWithError(c, "push", repoName); err != nil { c.Fatalf("pushing the image to the private registry has failed: %s, %v", out, err) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_rename_test.go ================================================ package main import ( "strings" "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" ) func (s *DockerSuite) TestRenameStoppedContainer(c *check.C) { out, _ := dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) name, err := inspectField(cleanedContainerID, "Name") newName := "new_name" + stringid.GenerateRandomID() dockerCmd(c, "rename", "first_name", newName) name, err = inspectField(cleanedContainerID, "Name") if err != nil { c.Fatal(err) } if name != "/"+newName { c.Fatal("Failed to rename container ", name) } } func (s *DockerSuite) TestRenameRunningContainer(c *check.C) { out, _ := dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh") newName := "new_name" + stringid.GenerateRandomID() cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "rename", "first_name", newName) name, err := inspectField(cleanedContainerID, "Name") if err != nil { c.Fatal(err) } if name != "/"+newName { c.Fatal("Failed to rename container ") } } func (s *DockerSuite) TestRenameCheckNames(c *check.C) { dockerCmd(c, "run", "--name", "first_name", "-d", "busybox", "sh") newName := "new_name" + stringid.GenerateRandomID() dockerCmd(c, "rename", "first_name", newName) name, err := inspectField(newName, "Name") if err != nil { c.Fatal(err) } if name != "/"+newName { c.Fatal("Failed to rename container ") } name, err = inspectField("first_name", "Name") if err == nil && !strings.Contains(err.Error(), "No such image or container: first_name") { c.Fatal(err) } } func (s *DockerSuite) TestRenameInvalidName(c *check.C) { dockerCmd(c, "run", "--name", "myname", "-d", "busybox", "top") if out, _, err := dockerCmdWithError(c, "rename", "myname", "new:invalid"); err == nil || !strings.Contains(out, "Invalid container name") { c.Fatalf("Renaming container to invalid name should have failed: %s\n%v", out, err) } if out, _, err := dockerCmdWithError(c, "ps", "-a"); err != nil || !strings.Contains(out, "myname") { c.Fatalf("Output of docker ps should have included 'myname': %s\n%v", out, err) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_restart_test.go ================================================ package main import ( "strings" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestRestartStoppedContainer(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "foobar") cleanedContainerID := strings.TrimSpace(out) dockerCmd(c, "wait", cleanedContainerID) out, _ = dockerCmd(c, "logs", cleanedContainerID) if out != "foobar\n" { c.Errorf("container should've printed 'foobar'") } dockerCmd(c, "restart", cleanedContainerID) out, _ = dockerCmd(c, "logs", cleanedContainerID) if out != "foobar\nfoobar\n" { c.Errorf("container should've printed 'foobar' twice, got %v", out) } } func (s *DockerSuite) TestRestartRunningContainer(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo foobar && sleep 30 && echo 'should not print this'") cleanedContainerID := strings.TrimSpace(out) time.Sleep(1 * time.Second) out, _ = dockerCmd(c, "logs", cleanedContainerID) if out != "foobar\n" { c.Errorf("container should've printed 'foobar'") } dockerCmd(c, "restart", "-t", "1", cleanedContainerID) out, _ = dockerCmd(c, "logs", cleanedContainerID) time.Sleep(1 * time.Second) if out != "foobar\nfoobar\n" { c.Errorf("container should've printed 'foobar' twice") } } // Test that restarting a container with a volume does not create a new volume on restart. Regression test for #819. func (s *DockerSuite) TestRestartWithVolumes(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-v", "/test", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "inspect", "--format", "{{ len .Mounts }}", cleanedContainerID) if out = strings.Trim(out, " \n\r"); out != "1" { c.Errorf("expect 1 volume received %s", out) } source, err := inspectMountSourceField(cleanedContainerID, "/test") c.Assert(err, check.IsNil) dockerCmd(c, "restart", cleanedContainerID) out, _ = dockerCmd(c, "inspect", "--format", "{{ len .Mounts }}", cleanedContainerID) if out = strings.Trim(out, " \n\r"); out != "1" { c.Errorf("expect 1 volume after restart received %s", out) } sourceAfterRestart, err := inspectMountSourceField(cleanedContainerID, "/test") c.Assert(err, check.IsNil) if source != sourceAfterRestart { c.Errorf("expected volume path: %s Actual path: %s", source, sourceAfterRestart) } } func (s *DockerSuite) TestRestartPolicyNO(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--restart=no", "busybox", "false") id := strings.TrimSpace(string(out)) name, err := inspectField(id, "HostConfig.RestartPolicy.Name") c.Assert(err, check.IsNil) if name != "no" { c.Fatalf("Container restart policy name is %s, expected %s", name, "no") } } func (s *DockerSuite) TestRestartPolicyAlways(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false") id := strings.TrimSpace(string(out)) name, err := inspectField(id, "HostConfig.RestartPolicy.Name") c.Assert(err, check.IsNil) if name != "always" { c.Fatalf("Container restart policy name is %s, expected %s", name, "always") } MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount") c.Assert(err, check.IsNil) // MaximumRetryCount=0 if the restart policy is always if MaximumRetryCount != "0" { c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "0") } } func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:1", "busybox", "false") id := strings.TrimSpace(string(out)) name, err := inspectField(id, "HostConfig.RestartPolicy.Name") c.Assert(err, check.IsNil) if name != "on-failure" { c.Fatalf("Container restart policy name is %s, expected %s", name, "on-failure") } } // a good container with --restart=on-failure:3 // MaximumRetryCount!=0; RestartCount=0 func (s *DockerSuite) TestContainerRestartwithGoodContainer(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "true") id := strings.TrimSpace(string(out)) if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 5); err != nil { c.Fatal(err) } count, err := inspectField(id, "RestartCount") c.Assert(err, check.IsNil) if count != "0" { c.Fatalf("Container was restarted %s times, expected %d", count, 0) } MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount") c.Assert(err, check.IsNil) if MaximumRetryCount != "3" { c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_rm_test.go ================================================ package main import ( "os" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestRmContainerWithRemovedVolume(c *check.C) { testRequires(c, SameHostDaemon) dockerCmd(c, "run", "--name", "losemyvolumes", "-v", "/tmp/testing:/test", "busybox", "true") if err := os.Remove("/tmp/testing"); err != nil { c.Fatal(err) } dockerCmd(c, "rm", "-v", "losemyvolumes") } func (s *DockerSuite) TestRmContainerWithVolume(c *check.C) { dockerCmd(c, "run", "--name", "foo", "-v", "/srv", "busybox", "true") dockerCmd(c, "rm", "-v", "foo") } func (s *DockerSuite) TestRmRunningContainer(c *check.C) { createRunningContainer(c, "foo") if _, _, err := dockerCmdWithError(c, "rm", "foo"); err == nil { c.Fatalf("Expected error, can't rm a running container") } } func (s *DockerSuite) TestRmForceRemoveRunningContainer(c *check.C) { createRunningContainer(c, "foo") // Stop then remove with -s dockerCmd(c, "rm", "-f", "foo") } func (s *DockerSuite) TestRmContainerOrphaning(c *check.C) { dockerfile1 := `FROM busybox:latest ENTRYPOINT ["/bin/true"]` img := "test-container-orphaning" dockerfile2 := `FROM busybox:latest ENTRYPOINT ["/bin/true"] MAINTAINER Integration Tests` // build first dockerfile img1, err := buildImage(img, dockerfile1, true) if err != nil { c.Fatalf("Could not build image %s: %v", img, err) } // run container on first image if out, _, err := dockerCmdWithError(c, "run", img); err != nil { c.Fatalf("Could not run image %s: %v: %s", img, err, out) } // rebuild dockerfile with a small addition at the end if _, err := buildImage(img, dockerfile2, true); err != nil { c.Fatalf("Could not rebuild image %s: %v", img, err) } // try to remove the image, should error out. if out, _, err := dockerCmdWithError(c, "rmi", img); err == nil { c.Fatalf("Expected to error out removing the image, but succeeded: %s", out) } // check if we deleted the first image out, _, err := dockerCmdWithError(c, "images", "-q", "--no-trunc") if err != nil { c.Fatalf("%v: %s", err, out) } if !strings.Contains(out, img1) { c.Fatalf("Orphaned container (could not find %q in docker images): %s", img1, out) } } func (s *DockerSuite) TestRmInvalidContainer(c *check.C) { if out, _, err := dockerCmdWithError(c, "rm", "unknown"); err == nil { c.Fatal("Expected error on rm unknown container, got none") } else if !strings.Contains(out, "failed to remove containers") { c.Fatalf("Expected output to contain 'failed to remove containers', got %q", out) } } func createRunningContainer(c *check.C, name string) { dockerCmd(c, "run", "-dt", "--name", name, "busybox", "top") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_rmi_test.go ================================================ package main import ( "fmt" "os/exec" "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestRmiWithContainerFails(c *check.C) { errSubstr := "is using it" // create a container out, _, err := dockerCmdWithError(c, "run", "-d", "busybox", "true") if err != nil { c.Fatalf("failed to create a container: %s, %v", out, err) } cleanedContainerID := strings.TrimSpace(out) // try to delete the image out, _, err = dockerCmdWithError(c, "rmi", "busybox") if err == nil { c.Fatalf("Container %q is using image, should not be able to rmi: %q", cleanedContainerID, out) } if !strings.Contains(out, errSubstr) { c.Fatalf("Container %q is using image, error message should contain %q: %v", cleanedContainerID, errSubstr, out) } // make sure it didn't delete the busybox name images, _ := dockerCmd(c, "images") if !strings.Contains(images, "busybox") { c.Fatalf("The name 'busybox' should not have been removed from images: %q", images) } } func (s *DockerSuite) TestRmiTag(c *check.C) { imagesBefore, _ := dockerCmd(c, "images", "-a") dockerCmd(c, "tag", "busybox", "utest:tag1") dockerCmd(c, "tag", "busybox", "utest/docker:tag2") dockerCmd(c, "tag", "busybox", "utest:5000/docker:tag3") { imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+3 { c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) } } dockerCmd(c, "rmi", "utest/docker:tag2") { imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+2 { c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) } } dockerCmd(c, "rmi", "utest:5000/docker:tag3") { imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+1 { c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) } } dockerCmd(c, "rmi", "utest:tag1") { imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+0 { c.Fatalf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter) } } } func (s *DockerSuite) TestRmiImgIDMultipleTag(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'") if err != nil { c.Fatalf("failed to create a container:%s, %v", out, err) } containerID := strings.TrimSpace(out) out, _, err = dockerCmdWithError(c, "commit", containerID, "busybox-one") if err != nil { c.Fatalf("failed to commit a new busybox-one:%s, %v", out, err) } imagesBefore, _ := dockerCmd(c, "images", "-a") dockerCmd(c, "tag", "busybox-one", "busybox-one:tag1") dockerCmd(c, "tag", "busybox-one", "busybox-one:tag2") imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+2 { c.Fatalf("tag busybox to create 2 more images with same imageID; docker images shows: %q\n", imagesAfter) } imgID, err := inspectField("busybox-one:tag1", "Id") c.Assert(err, check.IsNil) // run a container with the image out, _, err = dockerCmdWithError(c, "run", "-d", "busybox-one", "top") if err != nil { c.Fatalf("failed to create a container:%s, %v", out, err) } containerID = strings.TrimSpace(out) // first checkout without force it fails out, _, err = dockerCmdWithError(c, "rmi", imgID) expected := fmt.Sprintf("Conflict, cannot delete %s because the running container %s is using it, stop it and use -f to force", imgID[:12], containerID[:12]) if err == nil || !strings.Contains(out, expected) { c.Fatalf("rmi tagged in multiple repos should have failed without force: %s, %v, expected: %s", out, err, expected) } dockerCmd(c, "stop", containerID) dockerCmd(c, "rmi", "-f", imgID) imagesAfter, _ = dockerCmd(c, "images", "-a") if strings.Contains(imagesAfter, imgID[:12]) { c.Fatalf("rmi -f %s failed, image still exists: %q\n\n", imgID, imagesAfter) } } func (s *DockerSuite) TestRmiImgIDForce(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'") if err != nil { c.Fatalf("failed to create a container:%s, %v", out, err) } containerID := strings.TrimSpace(out) out, _, err = dockerCmdWithError(c, "commit", containerID, "busybox-test") if err != nil { c.Fatalf("failed to commit a new busybox-test:%s, %v", out, err) } imagesBefore, _ := dockerCmd(c, "images", "-a") dockerCmd(c, "tag", "busybox-test", "utest:tag1") dockerCmd(c, "tag", "busybox-test", "utest:tag2") dockerCmd(c, "tag", "busybox-test", "utest/docker:tag3") dockerCmd(c, "tag", "busybox-test", "utest:5000/docker:tag4") { imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Count(imagesAfter, "\n") != strings.Count(imagesBefore, "\n")+4 { c.Fatalf("tag busybox to create 4 more images with same imageID; docker images shows: %q\n", imagesAfter) } } imgID, err := inspectField("busybox-test", "Id") c.Assert(err, check.IsNil) // first checkout without force it fails out, _, err = dockerCmdWithError(c, "rmi", imgID) if err == nil || !strings.Contains(out, fmt.Sprintf("Conflict, cannot delete image %s because it is tagged in multiple repositories, use -f to force", imgID)) { c.Fatalf("rmi tagged in multiple repos should have failed without force:%s, %v", out, err) } dockerCmd(c, "rmi", "-f", imgID) { imagesAfter, _ := dockerCmd(c, "images", "-a") if strings.Contains(imagesAfter, imgID[:12]) { c.Fatalf("rmi -f %s failed, image still exists: %q\n\n", imgID, imagesAfter) } } } func (s *DockerSuite) TestRmiTagWithExistingContainers(c *check.C) { container := "test-delete-tag" newtag := "busybox:newtag" bb := "busybox:latest" if out, _, err := dockerCmdWithError(c, "tag", bb, newtag); err != nil { c.Fatalf("Could not tag busybox: %v: %s", err, out) } if out, _, err := dockerCmdWithError(c, "run", "--name", container, bb, "/bin/true"); err != nil { c.Fatalf("Could not run busybox: %v: %s", err, out) } out, _, err := dockerCmdWithError(c, "rmi", newtag) if err != nil { c.Fatalf("Could not remove tag %s: %v: %s", newtag, err, out) } if d := strings.Count(out, "Untagged: "); d != 1 { c.Fatalf("Expected 1 untagged entry got %d: %q", d, out) } } func (s *DockerSuite) TestRmiForceWithExistingContainers(c *check.C) { image := "busybox-clone" cmd := exec.Command(dockerBinary, "build", "--no-cache", "-t", image, "-") cmd.Stdin = strings.NewReader(`FROM busybox MAINTAINER foo`) if out, _, err := runCommandWithOutput(cmd); err != nil { c.Fatalf("Could not build %s: %s, %v", image, out, err) } if out, _, err := dockerCmdWithError(c, "run", "--name", "test-force-rmi", image, "/bin/true"); err != nil { c.Fatalf("Could not run container: %s, %v", out, err) } if out, _, err := dockerCmdWithError(c, "rmi", "-f", image); err != nil { c.Fatalf("Could not remove image %s: %s, %v", image, out, err) } } func (s *DockerSuite) TestRmiWithMultipleRepositories(c *check.C) { newRepo := "127.0.0.1:5000/busybox" oldRepo := "busybox" newTag := "busybox:test" out, _, err := dockerCmdWithError(c, "tag", oldRepo, newRepo) if err != nil { c.Fatalf("Could not tag busybox: %v: %s", err, out) } out, _, err = dockerCmdWithError(c, "run", "--name", "test", oldRepo, "touch", "/home/abcd") if err != nil { c.Fatalf("failed to run container: %v, output: %s", err, out) } out, _, err = dockerCmdWithError(c, "commit", "test", newTag) if err != nil { c.Fatalf("failed to commit container: %v, output: %s", err, out) } out, _, err = dockerCmdWithError(c, "rmi", newTag) if err != nil { c.Fatalf("failed to remove image: %v, output: %s", err, out) } if !strings.Contains(out, "Untagged: "+newTag) { c.Fatalf("Could not remove image %s: %s, %v", newTag, out, err) } } func (s *DockerSuite) TestRmiBlank(c *check.C) { // try to delete a blank image name out, _, err := dockerCmdWithError(c, "rmi", "") if err == nil { c.Fatal("Should have failed to delete '' image") } if strings.Contains(out, "No such image") { c.Fatalf("Wrong error message generated: %s", out) } if !strings.Contains(out, "Image name can not be blank") { c.Fatalf("Expected error message not generated: %s", out) } out, _, err = dockerCmdWithError(c, "rmi", " ") if err == nil { c.Fatal("Should have failed to delete '' image") } if !strings.Contains(out, "No such image") { c.Fatalf("Expected error message not generated: %s", out) } } func (s *DockerSuite) TestRmiContainerImageNotFound(c *check.C) { // Build 2 images for testing. imageNames := []string{"test1", "test2"} imageIds := make([]string, 2) for i, name := range imageNames { dockerfile := fmt.Sprintf("FROM busybox\nMAINTAINER %s\nRUN echo %s\n", name, name) id, err := buildImage(name, dockerfile, false) c.Assert(err, check.IsNil) imageIds[i] = id } // Create a long-running container. dockerCmd(c, "run", "-d", imageNames[0], "top") // Create a stopped container, and then force remove its image. dockerCmd(c, "run", imageNames[1], "true") dockerCmd(c, "rmi", "-f", imageIds[1]) // Try to remove the image of the running container and see if it fails as expected. out, _, err := dockerCmdWithError(c, "rmi", "-f", imageIds[0]) if err == nil || !strings.Contains(out, "is using it") { c.Log(out) c.Fatal("The image of the running container should not be removed.") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_run_test.go ================================================ package main import ( "bufio" "bytes" "fmt" "io/ioutil" "net" "os" "os/exec" "path" "path/filepath" "reflect" "regexp" "sort" "strconv" "strings" "sync" "time" "github.com/docker/docker/pkg/nat" "github.com/docker/libnetwork/resolvconf" "github.com/go-check/check" ) // "test123" should be printed by docker run func (s *DockerSuite) TestRunEchoStdout(c *check.C) { out, _ := dockerCmd(c, "run", "busybox", "echo", "test123") if out != "test123\n" { c.Fatalf("container should've printed 'test123'") } } // "test" should be printed func (s *DockerSuite) TestRunEchoStdoutWithMemoryLimit(c *check.C) { out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-m", "16m", "busybox", "echo", "test") out = strings.Trim(out, "\r\n") if expected := "test"; out != expected { c.Fatalf("container should've printed %q but printed %q", expected, out) } } // should run without memory swap func (s *DockerSuite) TestRunWithoutMemoryswapLimit(c *check.C) { testRequires(c, NativeExecDriver) dockerCmd(c, "run", "-m", "16m", "--memory-swap", "-1", "busybox", "true") } func (s *DockerSuite) TestRunWithSwappiness(c *check.C) { dockerCmd(c, "run", "--memory-swappiness", "0", "busybox", "true") } func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--memory-swappiness", "101", "busybox", "true") if err == nil { c.Fatalf("failed. test was able to set invalid value, output: %q", out) } } // "test" should be printed func (s *DockerSuite) TestRunEchoStdoutWitCPULimit(c *check.C) { out, _ := dockerCmd(c, "run", "-c", "1000", "busybox", "echo", "test") if out != "test\n" { c.Errorf("container should've printed 'test'") } } // "test" should be printed func (s *DockerSuite) TestRunEchoStdoutWithCPUAndMemoryLimit(c *check.C) { out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-c", "1000", "-m", "16m", "busybox", "echo", "test") if out != "test\n" { c.Errorf("container should've printed 'test', got %q instead", out) } } // "test" should be printed func (s *DockerSuite) TestRunEchoNamedContainer(c *check.C) { out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test") if out != "test\n" { c.Errorf("container should've printed 'test'") } } // docker run should not leak file descriptors func (s *DockerSuite) TestRunLeakyFileDescriptors(c *check.C) { out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd") // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory if out != "0 1 2 3\n" { c.Errorf("container should've printed '0 1 2 3', not: %s", out) } } // it should be possible to lookup Google DNS // this will fail when Internet access is unavailable func (s *DockerSuite) TestRunLookupGoogleDns(c *check.C) { testRequires(c, Network) dockerCmd(c, "run", "busybox", "nslookup", "google.com") } // the exit code should be 0 // some versions of lxc might make this test fail func (s *DockerSuite) TestRunExitCodeZero(c *check.C) { dockerCmd(c, "run", "busybox", "true") } // the exit code should be 1 // some versions of lxc might make this test fail func (s *DockerSuite) TestRunExitCodeOne(c *check.C) { _, exitCode, err := dockerCmdWithError(c, "run", "busybox", "false") if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) { c.Fatal(err) } if exitCode != 1 { c.Errorf("container should've exited with exit code 1") } } // it should be possible to pipe in data via stdin to a process running in a container // some versions of lxc might make this test fail func (s *DockerSuite) TestRunStdinPipe(c *check.C) { runCmd := exec.Command(dockerBinary, "run", "-i", "-a", "stdin", "busybox", "cat") runCmd.Stdin = strings.NewReader("blahblah") out, _, _, err := runCommandWithStdoutStderr(runCmd) if err != nil { c.Fatalf("failed to run container: %v, output: %q", err, out) } out = strings.TrimSpace(out) dockerCmd(c, "wait", out) logsOut, _ := dockerCmd(c, "logs", out) containerLogs := strings.TrimSpace(logsOut) if containerLogs != "blahblah" { c.Errorf("logs didn't print the container's logs %s", containerLogs) } dockerCmd(c, "rm", out) } // the container's ID should be printed when starting a container in detached mode func (s *DockerSuite) TestRunDetachedContainerIDPrinting(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "true") out = strings.TrimSpace(out) dockerCmd(c, "wait", out) rmOut, _ := dockerCmd(c, "rm", out) rmOut = strings.TrimSpace(rmOut) if rmOut != out { c.Errorf("rm didn't print the container ID %s %s", out, rmOut) } } // the working directory should be set correctly func (s *DockerSuite) TestRunWorkingDirectory(c *check.C) { out, _ := dockerCmd(c, "run", "-w", "/root", "busybox", "pwd") out = strings.TrimSpace(out) if out != "/root" { c.Errorf("-w failed to set working directory") } out, _ = dockerCmd(c, "run", "--workdir", "/root", "busybox", "pwd") out = strings.TrimSpace(out) if out != "/root" { c.Errorf("--workdir failed to set working directory") } } // pinging Google's DNS resolver should fail when we disable the networking func (s *DockerSuite) TestRunWithoutNetworking(c *check.C) { out, exitCode, err := dockerCmdWithError(c, "run", "--net=none", "busybox", "ping", "-c", "1", "8.8.8.8") if err != nil && exitCode != 1 { c.Fatal(out, err) } if exitCode != 1 { c.Errorf("--net=none should've disabled the network; the container shouldn't have been able to ping 8.8.8.8") } out, exitCode, err = dockerCmdWithError(c, "run", "-n=false", "busybox", "ping", "-c", "1", "8.8.8.8") if err != nil && exitCode != 1 { c.Fatal(out, err) } if exitCode != 1 { c.Errorf("-n=false should've disabled the network; the container shouldn't have been able to ping 8.8.8.8") } } //test --link use container name to link target func (s *DockerSuite) TestRunLinksContainerWithContainerName(c *check.C) { dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox") ip, err := inspectField("parent", "NetworkSettings.IPAddress") c.Assert(err, check.IsNil) out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts") if !strings.Contains(out, ip+" test") { c.Fatalf("use a container name to link target failed") } } //test --link use container id to link target func (s *DockerSuite) TestRunLinksContainerWithContainerId(c *check.C) { cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox") cID = strings.TrimSpace(cID) ip, err := inspectField(cID, "NetworkSettings.IPAddress") c.Assert(err, check.IsNil) out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts") if !strings.Contains(out, ip+" test") { c.Fatalf("use a container id to link target failed") } } // Regression test for #4979 func (s *DockerSuite) TestRunWithVolumesFromExited(c *check.C) { out, exitCode := dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") if exitCode != 0 { c.Fatal("1", out, exitCode) } out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") if exitCode != 0 { c.Fatal("2", out, exitCode) } } // Volume path is a symlink which also exists on the host, and the host side is a file not a dir // But the volume call is just a normal volume, not a bind mount func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) { testRequires(c, SameHostDaemon) testRequires(c, NativeExecDriver) name := "test-volume-symlink" dir, err := ioutil.TempDir("", name) if err != nil { c.Fatal(err) } defer os.RemoveAll(dir) f, err := os.OpenFile(filepath.Join(dir, "test"), os.O_CREATE, 0700) if err != nil { c.Fatal(err) } f.Close() dockerFile := fmt.Sprintf("FROM busybox\nRUN mkdir -p %s\nRUN ln -s %s /test", dir, dir) if _, err := buildImage(name, dockerFile, false); err != nil { c.Fatal(err) } dockerCmd(c, "run", "-v", "/test/test", name) } func (s *DockerSuite) TestRunVolumesMountedAsReadonly(c *check.C) { if _, code, err := dockerCmdWithError(c, "run", "-v", "/test:/test:ro", "busybox", "touch", "/test/somefile"); err == nil || code == 0 { c.Fatalf("run should fail because volume is ro: exit code %d", code) } } func (s *DockerSuite) TestRunVolumesFromInReadonlyMode(c *check.C) { dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true") if _, code, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:ro", "busybox", "touch", "/test/file"); err == nil || code == 0 { c.Fatalf("run should fail because volume is ro: exit code %d", code) } } // Regression test for #1201 func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) { dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true") dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file") if out, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:bar", "busybox", "touch", "/test/file"); err == nil || !strings.Contains(out, "invalid mode for volumes-from: bar") { c.Fatalf("running --volumes-from foo:bar should have failed with invalid mount mode: %q", out) } dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", "/test/file") } func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) { dockerCmd(c, "run", "--name", "parent", "-v", "/test:/test:ro", "busybox", "true") // Expect this "rw" mode to be be ignored since the inherited volume is "ro" if _, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", "/test/file"); err == nil { c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`") } dockerCmd(c, "run", "--name", "parent2", "-v", "/test:/test:ro", "busybox", "true") // Expect this to be read-only since both are "ro" if _, _, err := dockerCmdWithError(c, "run", "--volumes-from", "parent2:ro", "busybox", "touch", "/test/file"); err == nil { c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `ro`") } } // Test for GH#10618 func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) { mountstr1 := randomUnixTmpDirPath("test1") + ":/someplace" mountstr2 := randomUnixTmpDirPath("test2") + ":/someplace" if out, _, err := dockerCmdWithError(c, "run", "-v", mountstr1, "-v", mountstr2, "busybox", "true"); err == nil { c.Fatal("Expected error about duplicate volume definitions") } else { if !strings.Contains(out, "Duplicate bind mount") { c.Fatalf("Expected 'duplicate volume' error, got %v", err) } } } // Test for #1351 func (s *DockerSuite) TestRunApplyVolumesFromBeforeVolumes(c *check.C) { dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "touch", "/test/foo") dockerCmd(c, "run", "--volumes-from", "parent", "-v", "/test", "busybox", "cat", "/test/foo") } func (s *DockerSuite) TestRunMultipleVolumesFrom(c *check.C) { dockerCmd(c, "run", "--name", "parent1", "-v", "/test", "busybox", "touch", "/test/foo") dockerCmd(c, "run", "--name", "parent2", "-v", "/other", "busybox", "touch", "/other/bar") dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar") } // this tests verifies the ID format for the container func (s *DockerSuite) TestRunVerifyContainerID(c *check.C) { out, exit, err := dockerCmdWithError(c, "run", "-d", "busybox", "true") if err != nil { c.Fatal(err) } if exit != 0 { c.Fatalf("expected exit code 0 received %d", exit) } match, err := regexp.MatchString("^[0-9a-f]{64}$", strings.TrimSuffix(out, "\n")) if err != nil { c.Fatal(err) } if !match { c.Fatalf("Invalid container ID: %s", out) } } // Test that creating a container with a volume doesn't crash. Regression test for #995. func (s *DockerSuite) TestRunCreateVolume(c *check.C) { dockerCmd(c, "run", "-v", "/var/lib/data", "busybox", "true") } // Test that creating a volume with a symlink in its path works correctly. Test for #5152. // Note that this bug happens only with symlinks with a target that starts with '/'. func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) { image := "docker-test-createvolumewithsymlink" buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-") buildCmd.Stdin = strings.NewReader(`FROM busybox RUN ln -s home /bar`) buildCmd.Dir = workingDirectory err := buildCmd.Run() if err != nil { c.Fatalf("could not build '%s': %v", image, err) } _, exitCode, err := dockerCmdWithError(c, "run", "-v", "/bar/foo", "--name", "test-createvolumewithsymlink", image, "sh", "-c", "mount | grep -q /home/foo") if err != nil || exitCode != 0 { c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) } var volPath string volPath, exitCode, err = dockerCmdWithError(c, "inspect", "-f", "{{range .Volumes}}{{.}}{{end}}", "test-createvolumewithsymlink") if err != nil || exitCode != 0 { c.Fatalf("[inspect] err: %v, exitcode: %d", err, exitCode) } _, exitCode, err = dockerCmdWithError(c, "rm", "-v", "test-createvolumewithsymlink") if err != nil || exitCode != 0 { c.Fatalf("[rm] err: %v, exitcode: %d", err, exitCode) } f, err := os.Open(volPath) defer f.Close() if !os.IsNotExist(err) { c.Fatalf("[open] (expecting 'file does not exist' error) err: %v, volPath: %s", err, volPath) } } // Tests that a volume path that has a symlink exists in a container mounting it with `--volumes-from`. func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) { name := "docker-test-volumesfromsymlinkpath" buildCmd := exec.Command(dockerBinary, "build", "-t", name, "-") buildCmd.Stdin = strings.NewReader(`FROM busybox RUN ln -s home /foo VOLUME ["/foo/bar"]`) buildCmd.Dir = workingDirectory err := buildCmd.Run() if err != nil { c.Fatalf("could not build 'docker-test-volumesfromsymlinkpath': %v", err) } _, exitCode, err := dockerCmdWithError(c, "run", "--name", "test-volumesfromsymlinkpath", name) if err != nil || exitCode != 0 { c.Fatalf("[run] (volume) err: %v, exitcode: %d", err, exitCode) } _, exitCode, err = dockerCmdWithError(c, "run", "--volumes-from", "test-volumesfromsymlinkpath", "busybox", "sh", "-c", "ls /foo | grep -q bar") if err != nil || exitCode != 0 { c.Fatalf("[run] err: %v, exitcode: %d", err, exitCode) } } func (s *DockerSuite) TestRunExitCode(c *check.C) { _, exit, err := dockerCmdWithError(c, "run", "busybox", "/bin/sh", "-c", "exit 72") if err == nil { c.Fatal("should not have a non nil error") } if exit != 72 { c.Fatalf("expected exit code 72 received %d", exit) } } func (s *DockerSuite) TestRunUserDefaultsToRoot(c *check.C) { out, _ := dockerCmd(c, "run", "busybox", "id") if !strings.Contains(out, "uid=0(root) gid=0(root)") { c.Fatalf("expected root user got %s", out) } } func (s *DockerSuite) TestRunUserByName(c *check.C) { out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id") if !strings.Contains(out, "uid=0(root) gid=0(root)") { c.Fatalf("expected root user got %s", out) } } func (s *DockerSuite) TestRunUserByID(c *check.C) { out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id") if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { c.Fatalf("expected daemon user got %s", out) } } func (s *DockerSuite) TestRunUserByIDBig(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-u", "2147483648", "busybox", "id") if err == nil { c.Fatal("No error, but must be.", out) } if !strings.Contains(out, "Uids and gids must be in range") { c.Fatalf("expected error about uids range, got %s", out) } } func (s *DockerSuite) TestRunUserByIDNegative(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-u", "-1", "busybox", "id") if err == nil { c.Fatal("No error, but must be.", out) } if !strings.Contains(out, "Uids and gids must be in range") { c.Fatalf("expected error about uids range, got %s", out) } } func (s *DockerSuite) TestRunUserByIDZero(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-u", "0", "busybox", "id") if err != nil { c.Fatal(err, out) } if !strings.Contains(out, "uid=0(root) gid=0(root) groups=10(wheel)") { c.Fatalf("expected daemon user got %s", out) } } func (s *DockerSuite) TestRunUserNotFound(c *check.C) { _, _, err := dockerCmdWithError(c, "run", "-u", "notme", "busybox", "id") if err == nil { c.Fatal("unknown user should cause container to fail") } } func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) { group := sync.WaitGroup{} group.Add(2) errChan := make(chan error, 2) for i := 0; i < 2; i++ { go func() { defer group.Done() _, _, err := dockerCmdWithError(c, "run", "busybox", "sleep", "2") errChan <- err }() } group.Wait() close(errChan) for err := range errChan { c.Assert(err, check.IsNil) } } func (s *DockerSuite) TestRunEnvironment(c *check.C) { cmd := exec.Command(dockerBinary, "run", "-h", "testing", "-e=FALSE=true", "-e=TRUE", "-e=TRICKY", "-e=HOME=", "busybox", "env") cmd.Env = append(os.Environ(), "TRUE=false", "TRICKY=tri\ncky\n", ) out, _, err := runCommandWithOutput(cmd) if err != nil { c.Fatal(err, out) } actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n") actualEnv := []string{} for i := range actualEnvLxc { if actualEnvLxc[i] != "container=lxc" { actualEnv = append(actualEnv, actualEnvLxc[i]) } } sort.Strings(actualEnv) goodEnv := []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOSTNAME=testing", "FALSE=true", "TRUE=false", "TRICKY=tri", "cky", "", "HOME=/root", } sort.Strings(goodEnv) if len(goodEnv) != len(actualEnv) { c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", ")) } for i := range goodEnv { if actualEnv[i] != goodEnv[i] { c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) } } } func (s *DockerSuite) TestRunEnvironmentErase(c *check.C) { // Test to make sure that when we use -e on env vars that are // not set in our local env that they're removed (if present) in // the container cmd := exec.Command(dockerBinary, "run", "-e", "FOO", "-e", "HOSTNAME", "busybox", "env") cmd.Env = appendBaseEnv([]string{}) out, _, err := runCommandWithOutput(cmd) if err != nil { c.Fatal(err, out) } actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n") actualEnv := []string{} for i := range actualEnvLxc { if actualEnvLxc[i] != "container=lxc" { actualEnv = append(actualEnv, actualEnvLxc[i]) } } sort.Strings(actualEnv) goodEnv := []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root", } sort.Strings(goodEnv) if len(goodEnv) != len(actualEnv) { c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", ")) } for i := range goodEnv { if actualEnv[i] != goodEnv[i] { c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) } } } func (s *DockerSuite) TestRunEnvironmentOverride(c *check.C) { // Test to make sure that when we use -e on env vars that are // already in the env that we're overriding them cmd := exec.Command(dockerBinary, "run", "-e", "HOSTNAME", "-e", "HOME=/root2", "busybox", "env") cmd.Env = appendBaseEnv([]string{"HOSTNAME=bar"}) out, _, err := runCommandWithOutput(cmd) if err != nil { c.Fatal(err, out) } actualEnvLxc := strings.Split(strings.TrimSpace(out), "\n") actualEnv := []string{} for i := range actualEnvLxc { if actualEnvLxc[i] != "container=lxc" { actualEnv = append(actualEnv, actualEnvLxc[i]) } } sort.Strings(actualEnv) goodEnv := []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOME=/root2", "HOSTNAME=bar", } sort.Strings(goodEnv) if len(goodEnv) != len(actualEnv) { c.Fatalf("Wrong environment: should be %d variables, not: %q\n", len(goodEnv), strings.Join(actualEnv, ", ")) } for i := range goodEnv { if actualEnv[i] != goodEnv[i] { c.Fatalf("Wrong environment variable: should be %s, not %s", goodEnv[i], actualEnv[i]) } } } func (s *DockerSuite) TestRunContainerNetwork(c *check.C) { dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1") } func (s *DockerSuite) TestRunNetHostNotAllowedWithLinks(c *check.C) { dockerCmd(c, "run", "--name", "linked", "busybox", "true") _, _, err := dockerCmdWithError(c, "run", "--net=host", "--link", "linked:linked", "busybox", "true") if err == nil { c.Fatal("Expected error") } } // #7851 hostname outside container shows FQDN, inside only shortname // For testing purposes it is not required to set host's hostname directly // and use "--net=host" (as the original issue submitter did), as the same // codepath is executed with "docker run -h ". Both were manually // tested, but this testcase takes the simpler path of using "run -h .." func (s *DockerSuite) TestRunFullHostnameSet(c *check.C) { out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname") if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" { c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual) } } func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) { out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) { out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } func (s *DockerSuite) TestRunCapDropInvalid(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--cap-drop=CHPASS", "busybox", "ls") if err == nil { c.Fatal(err, out) } } func (s *DockerSuite) TestRunCapDropCannotMknod(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--cap-drop=MKNOD", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") if err == nil { c.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual == "ok" { c.Fatalf("expected output not ok received %s", actual) } } func (s *DockerSuite) TestRunCapDropCannotMknodLowerCase(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--cap-drop=mknod", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") if err == nil { c.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual == "ok" { c.Fatalf("expected output not ok received %s", actual) } } func (s *DockerSuite) TestRunCapDropALLCannotMknod(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--cap-drop=ALL", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") if err == nil { c.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual == "ok" { c.Fatalf("expected output not ok received %s", actual) } } func (s *DockerSuite) TestRunCapDropALLAddMknodCanMknod(c *check.C) { out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } func (s *DockerSuite) TestRunCapAddInvalid(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--cap-add=CHPASS", "busybox", "ls") if err == nil { c.Fatal(err, out) } } func (s *DockerSuite) TestRunCapAddCanDownInterface(c *check.C) { out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } func (s *DockerSuite) TestRunCapAddALLCanDownInterface(c *check.C) { out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } func (s *DockerSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--cap-add=ALL", "--cap-drop=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") if err == nil { c.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual == "ok" { c.Fatalf("expected output not ok received %s", actual) } } func (s *DockerSuite) TestRunGroupAdd(c *check.C) { out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=dbus", "--group-add=777", "busybox", "sh", "-c", "id") groupsList := "uid=0(root) gid=0(root) groups=10(wheel),29(audio),81(dbus),777" if actual := strings.Trim(out, "\r\n"); actual != groupsList { c.Fatalf("expected output %s received %s", groupsList, actual) } } func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) { out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") if err == nil { c.Fatal(err, out) } if actual := strings.Trim(out, "\r\n"); actual == "ok" { c.Fatalf("expected output not ok received %s", actual) } } func (s *DockerSuite) TestRunSysNotWritableInNonPrivilegedContainers(c *check.C) { if _, code, err := dockerCmdWithError(c, "run", "busybox", "touch", "/sys/kernel/profiling"); err == nil || code == 0 { c.Fatal("sys should not be writable in a non privileged container") } } func (s *DockerSuite) TestRunSysWritableInPrivilegedContainers(c *check.C) { if _, code, err := dockerCmdWithError(c, "run", "--privileged", "busybox", "touch", "/sys/kernel/profiling"); err != nil || code != 0 { c.Fatalf("sys should be writable in privileged container") } } func (s *DockerSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *check.C) { if _, code, err := dockerCmdWithError(c, "run", "busybox", "touch", "/proc/sysrq-trigger"); err == nil || code == 0 { c.Fatal("proc should not be writable in a non privileged container") } } func (s *DockerSuite) TestRunProcWritableInPrivilegedContainers(c *check.C) { if _, code := dockerCmd(c, "run", "--privileged", "busybox", "touch", "/proc/sysrq-trigger"); code != 0 { c.Fatalf("proc should be writable in privileged container") } } func (s *DockerSuite) TestRunWithCpuset(c *check.C) { if _, code := dockerCmd(c, "run", "--cpuset", "0", "busybox", "true"); code != 0 { c.Fatalf("container should run successfully with cpuset of 0") } } func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) { if _, code := dockerCmd(c, "run", "--cpuset-cpus", "0", "busybox", "true"); code != 0 { c.Fatalf("container should run successfully with cpuset-cpus of 0") } } func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) { if _, code := dockerCmd(c, "run", "--cpuset-mems", "0", "busybox", "true"); code != 0 { c.Fatalf("container should run successfully with cpuset-mems of 0") } } func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) { if _, code := dockerCmd(c, "run", "--blkio-weight", "300", "busybox", "true"); code != 0 { c.Fatalf("container should run successfully with blkio-weight of 300") } } func (s *DockerSuite) TestRunWithBlkioInvalidWeight(c *check.C) { if _, _, err := dockerCmdWithError(c, "run", "--blkio-weight", "5", "busybox", "true"); err == nil { c.Fatalf("run with invalid blkio-weight should failed") } } func (s *DockerSuite) TestRunDeviceNumbers(c *check.C) { out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null") deviceLineFields := strings.Fields(out) deviceLineFields[6] = "" deviceLineFields[7] = "" deviceLineFields[8] = "" expected := []string{"crw-rw-rw-", "1", "root", "root", "1,", "3", "", "", "", "/dev/null"} if !(reflect.DeepEqual(deviceLineFields, expected)) { c.Fatalf("expected output\ncrw-rw-rw- 1 root root 1, 3 May 24 13:29 /dev/null\n received\n %s\n", out) } } func (s *DockerSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *check.C) { out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero") if actual := strings.Trim(out, "\r\n"); actual[0] == '0' { c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual) } } func (s *DockerSuite) TestRunUnprivilegedWithChroot(c *check.C) { dockerCmd(c, "run", "busybox", "chroot", "/", "true") } func (s *DockerSuite) TestRunAddingOptionalDevices(c *check.C) { out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo") if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" { c.Fatalf("expected output /dev/nulo, received %s", actual) } } func (s *DockerSuite) TestRunModeHostname(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname") if actual := strings.Trim(out, "\r\n"); actual != "testhostname" { c.Fatalf("expected 'testhostname', but says: %q", actual) } out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname") hostname, err := os.Hostname() if err != nil { c.Fatal(err) } if actual := strings.Trim(out, "\r\n"); actual != hostname { c.Fatalf("expected %q, but says: %q", hostname, actual) } } func (s *DockerSuite) TestRunRootWorkdir(c *check.C) { out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd") if out != "/\n" { c.Fatalf("pwd returned %q (expected /\\n)", s) } } func (s *DockerSuite) TestRunAllowBindMountingRoot(c *check.C) { dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host") } func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-v", "/:/", "busybox", "ls", "/host") if err == nil { c.Fatal(out, err) } } // Verify that a container gets default DNS when only localhost resolvers exist func (s *DockerSuite) TestRunDnsDefaultOptions(c *check.C) { testRequires(c, SameHostDaemon) // preserve original resolv.conf for restoring after test origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") if os.IsNotExist(err) { c.Fatalf("/etc/resolv.conf does not exist") } // defer restored original conf defer func() { if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil { c.Fatal(err) } }() // test 3 cases: standard IPv4 localhost, commented out localhost, and IPv6 localhost // 2 are removed from the file at container start, and the 3rd (commented out) one is ignored by // GetNameservers(), leading to a replacement of nameservers with the default set tmpResolvConf := []byte("nameserver 127.0.0.1\n#nameserver 127.0.2.1\nnameserver ::1") if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { c.Fatal(err) } actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") // check that the actual defaults are appended to the commented out // localhost resolver (which should be preserved) // NOTE: if we ever change the defaults from google dns, this will break expected := "#nameserver 127.0.2.1\n\nnameserver 8.8.8.8\nnameserver 8.8.4.4" if actual != expected { c.Fatalf("expected resolv.conf be: %q, but was: %q", expected, actual) } } func (s *DockerSuite) TestRunDnsOptions(c *check.C) { out, stderr, _ := dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") // The client will get a warning on stderr when setting DNS to a localhost address; verify this: if !strings.Contains(stderr, "Localhost DNS setting") { c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", stderr) } actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1) if actual != "nameserver 127.0.0.1 search mydomain" { c.Fatalf("expected 'nameserver 127.0.0.1 search mydomain', but says: %q", actual) } out, stderr, _ = dockerCmdWithStdoutStderr(c, "run", "--dns=127.0.0.1", "--dns-search=.", "busybox", "cat", "/etc/resolv.conf") actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1) if actual != "nameserver 127.0.0.1" { c.Fatalf("expected 'nameserver 127.0.0.1', but says: %q", actual) } } func (s *DockerSuite) TestRunDnsOptionsBasedOnHostResolvConf(c *check.C) { testRequires(c, SameHostDaemon) origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") if os.IsNotExist(err) { c.Fatalf("/etc/resolv.conf does not exist") } hostNamservers := resolvconf.GetNameservers(origResolvConf) hostSearch := resolvconf.GetSearchDomains(origResolvConf) var out string out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf") if actualNameservers := resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "127.0.0.1" { c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0])) } actualSearch := resolvconf.GetSearchDomains([]byte(out)) if len(actualSearch) != len(hostSearch) { c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) } for i := range actualSearch { if actualSearch[i] != hostSearch[i] { c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) } } out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") actualNameservers := resolvconf.GetNameservers([]byte(out)) if len(actualNameservers) != len(hostNamservers) { c.Fatalf("expected %q nameserver(s), but it has: %q", len(hostNamservers), len(actualNameservers)) } for i := range actualNameservers { if actualNameservers[i] != hostNamservers[i] { c.Fatalf("expected %q nameserver, but says: %q", actualNameservers[i], hostNamservers[i]) } } if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" { c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0])) } // test with file tmpResolvConf := []byte("search example.com\nnameserver 12.34.56.78\nnameserver 127.0.0.1") if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { c.Fatal(err) } // put the old resolvconf back defer func() { if err := ioutil.WriteFile("/etc/resolv.conf", origResolvConf, 0644); err != nil { c.Fatal(err) } }() resolvConf, err := ioutil.ReadFile("/etc/resolv.conf") if os.IsNotExist(err) { c.Fatalf("/etc/resolv.conf does not exist") } hostNamservers = resolvconf.GetNameservers(resolvConf) hostSearch = resolvconf.GetSearchDomains(resolvConf) out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") if actualNameservers = resolvconf.GetNameservers([]byte(out)); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 { c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers) } actualSearch = resolvconf.GetSearchDomains([]byte(out)) if len(actualSearch) != len(hostSearch) { c.Fatalf("expected %q search domain(s), but it has: %q", len(hostSearch), len(actualSearch)) } for i := range actualSearch { if actualSearch[i] != hostSearch[i] { c.Fatalf("expected %q domain, but says: %q", actualSearch[i], hostSearch[i]) } } } // Test to see if a non-root user can resolve a DNS name and reach out to it. Also // check if the container resolv.conf file has atleast 0644 perm. func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { testRequires(c, SameHostDaemon) testRequires(c, Network) dockerCmd(c, "run", "--name=testperm", "--user=default", "busybox", "ping", "-c", "1", "www.docker.io") cID, err := getIDByName("testperm") if err != nil { c.Fatal(err) } fmode := (os.FileMode)(0644) finfo, err := os.Stat(containerStorageFile(cID, "resolv.conf")) if err != nil { c.Fatal(err) } if (finfo.Mode() & fmode) != fmode { c.Fatalf("Expected container resolv.conf mode to be atleast %s, instead got %s", fmode.String(), finfo.Mode().String()) } } // Test if container resolv.conf gets updated the next time it restarts // if host /etc/resolv.conf has changed. This only applies if the container // uses the host's /etc/resolv.conf and does not have any dns options provided. func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) { testRequires(c, SameHostDaemon) tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78") tmpLocalhostResolvConf := []byte("nameserver 127.0.0.1") //take a copy of resolv.conf for restoring after test completes resolvConfSystem, err := ioutil.ReadFile("/etc/resolv.conf") if err != nil { c.Fatal(err) } // This test case is meant to test monitoring resolv.conf when it is // a regular file not a bind mounc. So we unmount resolv.conf and replace // it with a file containing the original settings. cmd := exec.Command("umount", "/etc/resolv.conf") if _, err = runCommand(cmd); err != nil { c.Fatal(err) } //cleanup defer func() { if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { c.Fatal(err) } }() //1. test that a restarting container gets an updated resolv.conf dockerCmd(c, "run", "--name='first'", "busybox", "true") containerID1, err := getIDByName("first") if err != nil { c.Fatal(err) } // replace resolv.conf with our temporary copy bytesResolvConf := []byte(tmpResolvConf) if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { c.Fatal(err) } // start the container again to pickup changes dockerCmd(c, "start", "first") // check for update in container containerResolv, err := readContainerFile(containerID1, "resolv.conf") if err != nil { c.Fatal(err) } if !bytes.Equal(containerResolv, bytesResolvConf) { c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv)) } /* //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { c.Fatal(err) } */ //2. test that a restarting container does not receive resolv.conf updates // if it modified the container copy of the starting point resolv.conf dockerCmd(c, "run", "--name='second'", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") containerID2, err := getIDByName("second") if err != nil { c.Fatal(err) } //make a change to resolv.conf (in this case replacing our tmp copy with orig copy) if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { c.Fatal(err) } // start the container again dockerCmd(c, "start", "second") // check for update in container containerResolv, err = readContainerFile(containerID2, "resolv.conf") if err != nil { c.Fatal(err) } if bytes.Equal(containerResolv, resolvConfSystem) { c.Fatalf("Restarting a container after container updated resolv.conf should not pick up host changes; expected %q, got %q", string(containerResolv), string(resolvConfSystem)) } //3. test that a running container's resolv.conf is not modified while running out, _ := dockerCmd(c, "run", "-d", "busybox", "top") runningContainerID := strings.TrimSpace(out) // replace resolv.conf if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { c.Fatal(err) } // check for update in container containerResolv, err = readContainerFile(runningContainerID, "resolv.conf") if err != nil { c.Fatal(err) } if bytes.Equal(containerResolv, bytesResolvConf) { c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv)) } //4. test that a running container's resolv.conf is updated upon restart // (the above container is still running..) dockerCmd(c, "restart", runningContainerID) // check for update in container containerResolv, err = readContainerFile(runningContainerID, "resolv.conf") if err != nil { c.Fatal(err) } if !bytes.Equal(containerResolv, bytesResolvConf) { c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv)) } //5. test that additions of a localhost resolver are cleaned from // host resolv.conf before updating container's resolv.conf copies // replace resolv.conf with a localhost-only nameserver copy bytesResolvConf = []byte(tmpLocalhostResolvConf) if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { c.Fatal(err) } // start the container again to pickup changes dockerCmd(c, "start", "first") // our first exited container ID should have been updated, but with default DNS // after the cleanup of resolv.conf found only a localhost nameserver: containerResolv, err = readContainerFile(containerID1, "resolv.conf") if err != nil { c.Fatal(err) } expected := "\nnameserver 8.8.8.8\nnameserver 8.8.4.4" if !bytes.Equal(containerResolv, []byte(expected)) { c.Fatalf("Container does not have cleaned/replaced DNS in resolv.conf; expected %q, got %q", expected, string(containerResolv)) } //6. Test that replacing (as opposed to modifying) resolv.conf triggers an update // of containers' resolv.conf. // Restore the original resolv.conf if err := ioutil.WriteFile("/etc/resolv.conf", resolvConfSystem, 0644); err != nil { c.Fatal(err) } // Run the container so it picks up the old settings dockerCmd(c, "run", "--name='third'", "busybox", "true") containerID3, err := getIDByName("third") if err != nil { c.Fatal(err) } // Create a modified resolv.conf.aside and override resolv.conf with it bytesResolvConf = []byte(tmpResolvConf) if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil { c.Fatal(err) } err = os.Rename("/etc/resolv.conf.aside", "/etc/resolv.conf") if err != nil { c.Fatal(err) } // start the container again to pickup changes dockerCmd(c, "start", "third") // check for update in container containerResolv, err = readContainerFile(containerID3, "resolv.conf") if err != nil { c.Fatal(err) } if !bytes.Equal(containerResolv, bytesResolvConf) { c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv)) } //cleanup, restore original resolv.conf happens in defer func() } func (s *DockerSuite) TestRunAddHost(c *check.C) { out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts") actual := strings.Trim(out, "\r\n") if actual != "86.75.30.9\textra" { c.Fatalf("expected '86.75.30.9\textra', but says: %q", actual) } } // Regression test for #6983 func (s *DockerSuite) TestRunAttachStdErrOnlyTTYMode(c *check.C) { _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true") if exitCode != 0 { c.Fatalf("Container should have exited with error code 0") } } // Regression test for #6983 func (s *DockerSuite) TestRunAttachStdOutOnlyTTYMode(c *check.C) { _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true") if exitCode != 0 { c.Fatalf("Container should have exited with error code 0") } } // Regression test for #6983 func (s *DockerSuite) TestRunAttachStdOutAndErrTTYMode(c *check.C) { _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true") if exitCode != 0 { c.Fatalf("Container should have exited with error code 0") } } // Test for #10388 - this will run the same test as TestRunAttachStdOutAndErrTTYMode // but using --attach instead of -a to make sure we read the flag correctly func (s *DockerSuite) TestRunAttachWithDetach(c *check.C) { cmd := exec.Command(dockerBinary, "run", "-d", "--attach", "stdout", "busybox", "true") _, stderr, _, err := runCommandWithStdoutStderr(cmd) if err == nil { c.Fatal("Container should have exited with error code different than 0") } else if !strings.Contains(stderr, "Conflicting options: -a and -d") { c.Fatal("Should have been returned an error with conflicting options -a and -d") } } func (s *DockerSuite) TestRunState(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) state, err := inspectField(id, "State.Running") c.Assert(err, check.IsNil) if state != "true" { c.Fatal("Container state is 'not running'") } pid1, err := inspectField(id, "State.Pid") c.Assert(err, check.IsNil) if pid1 == "0" { c.Fatal("Container state Pid 0") } dockerCmd(c, "stop", id) state, err = inspectField(id, "State.Running") c.Assert(err, check.IsNil) if state != "false" { c.Fatal("Container state is 'running'") } pid2, err := inspectField(id, "State.Pid") c.Assert(err, check.IsNil) if pid2 == pid1 { c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) } dockerCmd(c, "start", id) state, err = inspectField(id, "State.Running") c.Assert(err, check.IsNil) if state != "true" { c.Fatal("Container state is 'not running'") } pid3, err := inspectField(id, "State.Pid") c.Assert(err, check.IsNil) if pid3 == pid1 { c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) } } // Test for #1737 func (s *DockerSuite) TestRunCopyVolumeUidGid(c *check.C) { name := "testrunvolumesuidgid" _, err := buildImage(name, `FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd RUN echo 'dockerio:x:1001:' >> /etc/group RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`, true) if err != nil { c.Fatal(err) } // Test that the uid and gid is copied from the image to the volume out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", "ls -l / | grep hello | awk '{print $3\":\"$4}'") out = strings.TrimSpace(out) if out != "dockerio:dockerio" { c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out) } } // Test for #1582 func (s *DockerSuite) TestRunCopyVolumeContent(c *check.C) { name := "testruncopyvolumecontent" _, err := buildImage(name, `FROM busybox RUN mkdir -p /hello/local && echo hello > /hello/local/world`, true) if err != nil { c.Fatal(err) } // Test that the content is copied from the image to the volume out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello") if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) { c.Fatal("Container failed to transfer content to volume") } } func (s *DockerSuite) TestRunCleanupCmdOnEntrypoint(c *check.C) { name := "testrunmdcleanuponentrypoint" if _, err := buildImage(name, `FROM busybox ENTRYPOINT ["echo"] CMD ["testingpoint"]`, true); err != nil { c.Fatal(err) } out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name) if exit != 0 { c.Fatalf("expected exit code 0 received %d, out: %q", exit, out) } out = strings.TrimSpace(out) if out != "root" { c.Fatalf("Expected output root, got %q", out) } } // TestRunWorkdirExistsAndIsFile checks that if 'docker run -w' with existing file can be detected func (s *DockerSuite) TestRunWorkdirExistsAndIsFile(c *check.C) { out, exit, err := dockerCmdWithError(c, "run", "-w", "/bin/cat", "busybox") if !(err != nil && exit == 1 && strings.Contains(out, "Cannot mkdir: /bin/cat is not a directory")) { c.Fatalf("Docker must complains about making dir, but we got out: %s, exit: %d, err: %s", out, exit, err) } } func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) { name := "testrunexitonstdinclose" runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", "/bin/cat") stdin, err := runCmd.StdinPipe() if err != nil { c.Fatal(err) } stdout, err := runCmd.StdoutPipe() if err != nil { c.Fatal(err) } if err := runCmd.Start(); err != nil { c.Fatal(err) } if _, err := stdin.Write([]byte("hello\n")); err != nil { c.Fatal(err) } r := bufio.NewReader(stdout) line, err := r.ReadString('\n') if err != nil { c.Fatal(err) } line = strings.TrimSpace(line) if line != "hello" { c.Fatalf("Output should be 'hello', got '%q'", line) } if err := stdin.Close(); err != nil { c.Fatal(err) } finish := make(chan error) go func() { finish <- runCmd.Wait() close(finish) }() select { case err := <-finish: c.Assert(err, check.IsNil) case <-time.After(1 * time.Second): c.Fatal("docker run failed to exit on stdin close") } state, err := inspectField(name, "State.Running") c.Assert(err, check.IsNil) if state != "false" { c.Fatal("Container must be stopped after stdin closing") } } // Test for #2267 func (s *DockerSuite) TestRunWriteHostsFileAndNotCommit(c *check.C) { name := "writehosts" out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hosts && cat /etc/hosts") if !strings.Contains(out, "test2267") { c.Fatal("/etc/hosts should contain 'test2267'") } out, _ = dockerCmd(c, "diff", name) if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { c.Fatal("diff should be empty") } } func eqToBaseDiff(out string, c *check.C) bool { out1, _ := dockerCmd(c, "run", "-d", "busybox", "echo", "hello") cID := strings.TrimSpace(out1) baseDiff, _ := dockerCmd(c, "diff", cID) baseArr := strings.Split(baseDiff, "\n") sort.Strings(baseArr) outArr := strings.Split(out, "\n") sort.Strings(outArr) return sliceEq(baseArr, outArr) } func sliceEq(a, b []string) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } // Test for #2267 func (s *DockerSuite) TestRunWriteHostnameFileAndNotCommit(c *check.C) { name := "writehostname" out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/hostname && cat /etc/hostname") if !strings.Contains(out, "test2267") { c.Fatal("/etc/hostname should contain 'test2267'") } out, _ = dockerCmd(c, "diff", name) if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { c.Fatal("diff should be empty") } } // Test for #2267 func (s *DockerSuite) TestRunWriteResolvFileAndNotCommit(c *check.C) { name := "writeresolv" out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo test2267 >> /etc/resolv.conf && cat /etc/resolv.conf") if !strings.Contains(out, "test2267") { c.Fatal("/etc/resolv.conf should contain 'test2267'") } out, _ = dockerCmd(c, "diff", name) if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { c.Fatal("diff should be empty") } } func (s *DockerSuite) TestRunWithBadDevice(c *check.C) { name := "baddevice" out, _, err := dockerCmdWithError(c, "run", "--name", name, "--device", "/etc", "busybox", "true") if err == nil { c.Fatal("Run should fail with bad device") } expected := `"/etc": not a device node` if !strings.Contains(out, expected) { c.Fatalf("Output should contain %q, actual out: %q", expected, out) } } func (s *DockerSuite) TestRunEntrypoint(c *check.C) { name := "entrypoint" out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "/bin/echo", "busybox", "-n", "foobar") expected := "foobar" if out != expected { c.Fatalf("Output should be %q, actual out: %q", expected, out) } } func (s *DockerSuite) TestRunBindMounts(c *check.C) { testRequires(c, SameHostDaemon) tmpDir, err := ioutil.TempDir("", "docker-test-container") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir) writeFile(path.Join(tmpDir, "touch-me"), "", c) // Test reading from a read-only bind mount out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox", "ls", "/tmp") if !strings.Contains(out, "touch-me") { c.Fatal("Container failed to read from bind mount") } // test writing to bind mount dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist // test mounting to an illegal destination directory _, _, err = dockerCmdWithError(c, "run", "-v", fmt.Sprintf("%s:.", tmpDir), "busybox", "ls", ".") if err == nil { c.Fatal("Container bind mounted illegal directory") } // test mount a file dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist expected := "yotta" if content != expected { c.Fatalf("Output should be %q, actual out: %q", expected, content) } } // Ensure that CIDFile gets deleted if it's empty // Perform this test by making `docker run` fail func (s *DockerSuite) TestRunCidFileCleanupIfEmpty(c *check.C) { tmpDir, err := ioutil.TempDir("", "TestRunCidFile") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir) tmpCidFile := path.Join(tmpDir, "cid") out, _, err := dockerCmdWithError(c, "run", "--cidfile", tmpCidFile, "emptyfs") if err == nil { c.Fatalf("Run without command must fail. out=%s", out) } else if !strings.Contains(out, "No command specified") { c.Fatalf("Run without command failed with wrong output. out=%s\nerr=%v", out, err) } if _, err := os.Stat(tmpCidFile); err == nil { c.Fatalf("empty CIDFile %q should've been deleted", tmpCidFile) } } // #2098 - Docker cidFiles only contain short version of the containerId //sudo docker run --cidfile /tmp/docker_tesc.cid ubuntu echo "test" // TestRunCidFile tests that run --cidfile returns the longid func (s *DockerSuite) TestRunCidFileCheckIDLength(c *check.C) { tmpDir, err := ioutil.TempDir("", "TestRunCidFile") if err != nil { c.Fatal(err) } tmpCidFile := path.Join(tmpDir, "cid") defer os.RemoveAll(tmpDir) out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true") id := strings.TrimSpace(out) buffer, err := ioutil.ReadFile(tmpCidFile) if err != nil { c.Fatal(err) } cid := string(buffer) if len(cid) != 64 { c.Fatalf("--cidfile should be a long id, not %q", id) } if cid != id { c.Fatalf("cid must be equal to %s, got %s", id, cid) } } func (s *DockerSuite) TestRunSetMacAddress(c *check.C) { mac := "12:34:56:78:9a:bc" out, _ := dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'") actualMac := strings.TrimSpace(out) if actualMac != mac { c.Fatalf("Set MAC address with --mac-address failed. The container has an incorrect MAC address: %q, expected: %q", actualMac, mac) } } func (s *DockerSuite) TestRunInspectMacAddress(c *check.C) { mac := "12:34:56:78:9a:bc" out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top") id := strings.TrimSpace(out) inspectedMac, err := inspectField(id, "NetworkSettings.MacAddress") c.Assert(err, check.IsNil) if inspectedMac != mac { c.Fatalf("docker inspect outputs wrong MAC address: %q, should be: %q", inspectedMac, mac) } } // test docker run use a invalid mac address func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--mac-address", "92:d0:c6:0a:29", "busybox") //use a invalid mac address should with a error out if err == nil || !strings.Contains(out, "is not a valid mac address") { c.Fatalf("run with an invalid --mac-address should with error out") } } func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top") id := strings.TrimSpace(out) ip, err := inspectField(id, "NetworkSettings.IPAddress") c.Assert(err, check.IsNil) iptCmd := exec.Command("iptables", "-D", "DOCKER", "-d", fmt.Sprintf("%s/32", ip), "!", "-i", "docker0", "-o", "docker0", "-p", "tcp", "-m", "tcp", "--dport", "23", "-j", "ACCEPT") out, _, err = runCommandWithOutput(iptCmd) if err != nil { c.Fatal(err, out) } if err := deleteContainer(id); err != nil { c.Fatal(err) } dockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top") } func (s *DockerSuite) TestRunPortInUse(c *check.C) { testRequires(c, SameHostDaemon) port := "1234" dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") out, _, err := dockerCmdWithError(c, "run", "-d", "-p", port+":80", "busybox", "top") if err == nil { c.Fatalf("Binding on used port must fail") } if !strings.Contains(out, "port is already allocated") { c.Fatalf("Out must be about \"port is already allocated\", got %s", out) } } // https://github.com/docker/docker/issues/12148 func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) { // allocate a dynamic port to get the most recent out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top") id := strings.TrimSpace(out) out, _ = dockerCmd(c, "port", id, "80") strPort := strings.Split(strings.TrimSpace(out), ":")[1] port, err := strconv.ParseInt(strPort, 10, 64) if err != nil { c.Fatalf("invalid port, got: %s, error: %s", strPort, err) } // allocate a static port and a dynamic port together, with static port // takes the next recent port in dynamic port range. dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top") } // Regression test for #7792 func (s *DockerSuite) TestRunMountOrdering(c *check.C) { testRequires(c, SameHostDaemon) tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir) tmpDir2, err := ioutil.TempDir("", "docker_nested_mount_test2") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir2) // Create a temporary tmpfs mounc. fooDir := filepath.Join(tmpDir, "foo") if err := os.MkdirAll(filepath.Join(tmpDir, "foo"), 0755); err != nil { c.Fatalf("failed to mkdir at %s - %s", fooDir, err) } if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", fooDir), []byte{}, 0644); err != nil { c.Fatal(err) } if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir), []byte{}, 0644); err != nil { c.Fatal(err) } if err := ioutil.WriteFile(fmt.Sprintf("%s/touch-me", tmpDir2), []byte{}, 0644); err != nil { c.Fatal(err) } dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp", tmpDir), "-v", fmt.Sprintf("%s:/tmp/foo", fooDir), "-v", fmt.Sprintf("%s:/tmp/tmp2", tmpDir2), "-v", fmt.Sprintf("%s:/tmp/tmp2/foo", fooDir), "busybox:latest", "sh", "-c", "ls /tmp/touch-me && ls /tmp/foo/touch-me && ls /tmp/tmp2/touch-me && ls /tmp/tmp2/foo/touch-me") } // Regression test for https://github.com/docker/docker/issues/8259 func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) { testRequires(c, SameHostDaemon) tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir) linkPath := os.TempDir() + "/testlink2" if err := os.Symlink(tmpDir, linkPath); err != nil { c.Fatal(err) } defer os.RemoveAll(linkPath) // Create first container dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test") // Create second container with same symlinked path // This will fail if the referenced issue is hit with a "Volume exists" error dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp/test", linkPath), "busybox", "ls", "-lh", "/tmp/test") } //GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container func (s *DockerSuite) TestRunCreateVolumeEtc(c *check.C) { out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf") if !strings.Contains(out, "nameserver 127.0.0.1") { c.Fatal("/etc volume mount hides /etc/resolv.conf") } out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname") if !strings.Contains(out, "test123") { c.Fatal("/etc volume mount hides /etc/hostname") } out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts") out = strings.Replace(out, "\n", " ", -1) if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") { c.Fatal("/etc volume mount hides /etc/hosts") } } func (s *DockerSuite) TestVolumesNoCopyData(c *check.C) { if _, err := buildImage("dataimage", `FROM busybox RUN mkdir -p /foo RUN touch /foo/bar`, true); err != nil { c.Fatal(err) } dockerCmd(c, "run", "--name", "test", "-v", "/foo", "busybox") if out, _, err := dockerCmdWithError(c, "run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out) } tmpDir := randomUnixTmpDirPath("docker_test_bind_mount_copy_data") if out, _, err := dockerCmdWithError(c, "run", "-v", tmpDir+":/foo", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { c.Fatalf("Data was copied on bind-mount but shouldn't be:\n%q", out) } } func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) { // just run with unknown image cmd := exec.Command(dockerBinary, "run", "asdfsg") stdout := bytes.NewBuffer(nil) cmd.Stdout = stdout if err := cmd.Run(); err == nil { c.Fatal("Run with unknown image should fail") } if stdout.Len() != 0 { c.Fatalf("Stdout contains output from pull: %s", stdout) } } func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) { if _, err := buildImage("run_volumes_clean_paths", `FROM busybox VOLUME /foo/`, true); err != nil { c.Fatal(err) } dockerCmd(c, "run", "-v", "/foo", "-v", "/bar/", "--name", "dark_helmet", "run_volumes_clean_paths") out, err := inspectMountSourceField("dark_helmet", "/foo/") if err != mountNotFound { c.Fatalf("Found unexpected volume entry for '/foo/' in volumes\n%q", out) } out, err = inspectMountSourceField("dark_helmet", "/foo") c.Assert(err, check.IsNil) if !strings.Contains(out, volumesConfigPath) { c.Fatalf("Volume was not defined for /foo\n%q", out) } out, err = inspectMountSourceField("dark_helmet", "/bar/") if err != mountNotFound { c.Fatalf("Found unexpected volume entry for '/bar/' in volumes\n%q", out) } out, err = inspectMountSourceField("dark_helmet", "/bar") c.Assert(err, check.IsNil) if !strings.Contains(out, volumesConfigPath) { c.Fatalf("Volume was not defined for /bar\n%q", out) } } // Regression test for #3631 func (s *DockerSuite) TestRunSlowStdoutConsumer(c *check.C) { cont := exec.Command(dockerBinary, "run", "--rm", "busybox", "/bin/sh", "-c", "dd if=/dev/zero of=/dev/stdout bs=1024 count=2000 | catv") stdout, err := cont.StdoutPipe() if err != nil { c.Fatal(err) } if err := cont.Start(); err != nil { c.Fatal(err) } n, err := consumeWithSpeed(stdout, 10000, 5*time.Millisecond, nil) if err != nil { c.Fatal(err) } expected := 2 * 1024 * 2000 if n != expected { c.Fatalf("Expected %d, got %d", expected, n) } } func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top") id := strings.TrimSpace(out) portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports") c.Assert(err, check.IsNil) var ports nat.PortMap if err = unmarshalJSON([]byte(portstr), &ports); err != nil { c.Fatal(err) } for port, binding := range ports { portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) if portnum < 3000 || portnum > 3003 { c.Fatalf("Port %d is out of range ", portnum) } if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { c.Fatalf("Port is not mapped for the port %d", port) } } } // test docker run expose a invalid port func (s *DockerSuite) TestRunExposePort(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--expose", "80000", "busybox") //expose a invalid port should with a error out if err == nil || !strings.Contains(out, "Invalid range format for --expose") { c.Fatalf("run --expose a invalid port should with error out") } } func (s *DockerSuite) TestRunUnknownCommand(c *check.C) { testRequires(c, NativeExecDriver) out, _, _ := dockerCmdWithStdoutStderr(c, "create", "busybox", "/bin/nada") cID := strings.TrimSpace(out) _, _, err := dockerCmdWithError(c, "start", cID) c.Assert(err, check.NotNil) rc, err := inspectField(cID, "State.ExitCode") c.Assert(err, check.IsNil) if rc == "0" { c.Fatalf("ExitCode(%v) cannot be 0", rc) } } func (s *DockerSuite) TestRunModeIpcHost(c *check.C) { testRequires(c, SameHostDaemon) hostIpc, err := os.Readlink("/proc/1/ns/ipc") if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc") out = strings.Trim(out, "\n") if hostIpc != out { c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out) } out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc") out = strings.Trim(out, "\n") if hostIpc == out { c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out) } } func (s *DockerSuite) TestRunModeIpcContainer(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) state, err := inspectField(id, "State.Running") c.Assert(err, check.IsNil) if state != "true" { c.Fatal("Container state is 'not running'") } pid1, err := inspectField(id, "State.Pid") c.Assert(err, check.IsNil) parentContainerIpc, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/ipc", pid1)) if err != nil { c.Fatal(err) } out, _ = dockerCmd(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox", "readlink", "/proc/self/ns/ipc") out = strings.Trim(out, "\n") if parentContainerIpc != out { c.Fatalf("IPC different with --ipc=container:%s %s != %s\n", id, parentContainerIpc, out) } } func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-d", "--ipc", "container:abcd1234", "busybox", "top") if !strings.Contains(out, "abcd1234") || err == nil { c.Fatalf("run IPC from a non exists container should with correct error out") } } func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "create", "busybox") id := strings.TrimSpace(out) out, _, err := dockerCmdWithError(c, "run", fmt.Sprintf("--ipc=container:%s", id), "busybox") if err == nil { c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err) } } func (s *DockerSuite) TestContainerNetworkMode(c *check.C) { testRequires(c, SameHostDaemon) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatal(err) } pid1, err := inspectField(id, "State.Pid") c.Assert(err, check.IsNil) parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) if err != nil { c.Fatal(err) } out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net") out = strings.Trim(out, "\n") if parentContainerNet != out { c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out) } } func (s *DockerSuite) TestRunModePidHost(c *check.C) { testRequires(c, NativeExecDriver, SameHostDaemon) hostPid, err := os.Readlink("/proc/1/ns/pid") if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--pid=host", "busybox", "readlink", "/proc/self/ns/pid") out = strings.Trim(out, "\n") if hostPid != out { c.Fatalf("PID different with --pid=host %s != %s\n", hostPid, out) } out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/pid") out = strings.Trim(out, "\n") if hostPid == out { c.Fatalf("PID should be different without --pid=host %s == %s\n", hostPid, out) } } func (s *DockerSuite) TestRunModeUTSHost(c *check.C) { testRequires(c, NativeExecDriver, SameHostDaemon) hostUTS, err := os.Readlink("/proc/1/ns/uts") if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts") out = strings.Trim(out, "\n") if hostUTS != out { c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out) } out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts") out = strings.Trim(out, "\n") if hostUTS == out { c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out) } } func (s *DockerSuite) TestRunTLSverify(c *check.C) { if out, code, err := dockerCmdWithError(c, "ps"); err != nil || code != 0 { c.Fatalf("Should have worked: %v:\n%v", err, out) } // Regardless of whether we specify true or false we need to // test to make sure tls is turned on if --tlsverify is specified at all out, code, err := dockerCmdWithError(c, "--tlsverify=false", "ps") if err == nil || code == 0 || !strings.Contains(out, "trying to connect") { c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err) } out, code, err = dockerCmdWithError(c, "--tlsverify=true", "ps") if err == nil || code == 0 || !strings.Contains(out, "cert") { c.Fatalf("Should have failed: \net:%v\nout:%v\nerr:%v", code, out, err) } } func (s *DockerSuite) TestRunPortFromDockerRangeInUse(c *check.C) { // first find allocator current position out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") id := strings.TrimSpace(out) out, _ = dockerCmd(c, "port", id) out = strings.TrimSpace(out) if out == "" { c.Fatal("docker port command output is empty") } out = strings.Split(out, ":")[1] lastPort, err := strconv.Atoi(out) if err != nil { c.Fatal(err) } port := lastPort + 1 l, err := net.Listen("tcp", ":"+strconv.Itoa(port)) if err != nil { c.Fatal(err) } defer l.Close() out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") id = strings.TrimSpace(out) dockerCmd(c, "port", id) } func (s *DockerSuite) TestRunTtyWithPipe(c *check.C) { errChan := make(chan error) go func() { defer close(errChan) cmd := exec.Command(dockerBinary, "run", "-ti", "busybox", "true") if _, err := cmd.StdinPipe(); err != nil { errChan <- err return } expected := "cannot enable tty mode" if out, _, err := runCommandWithOutput(cmd); err == nil { errChan <- fmt.Errorf("run should have failed") return } else if !strings.Contains(out, expected) { errChan <- fmt.Errorf("run failed with error %q: expected %q", out, expected) return } }() select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(3 * time.Second): c.Fatal("container is running but should have failed") } } func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) { addr := "00:16:3E:08:00:50" if out, _ := dockerCmd(c, "run", "--mac-address", addr, "busybox", "ifconfig"); !strings.Contains(out, addr) { c.Fatalf("Output should have contained %q: %s", addr, out) } } func (s *DockerSuite) TestRunNetHost(c *check.C) { testRequires(c, SameHostDaemon) hostNet, err := os.Readlink("/proc/1/ns/net") if err != nil { c.Fatal(err) } out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net") out = strings.Trim(out, "\n") if hostNet != out { c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out) } out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net") out = strings.Trim(out, "\n") if hostNet == out { c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out) } } func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) { testRequires(c, SameHostDaemon) dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") } func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) { testRequires(c, SameHostDaemon) hostNet, err := os.Readlink("/proc/1/ns/net") if err != nil { c.Fatal(err) } dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top") out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net") out = strings.Trim(out, "\n") if hostNet != out { c.Fatalf("Container should have host network namespace") } } func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top") id := strings.TrimSpace(out) portstr, err := inspectFieldJSON(id, "NetworkSettings.Ports") c.Assert(err, check.IsNil) var ports nat.PortMap err = unmarshalJSON([]byte(portstr), &ports) for port, binding := range ports { portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) if portnum < 3000 || portnum > 3003 { c.Fatalf("Port %d is out of range ", portnum) } if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 { c.Fatal("Port is not mapped for the port "+port, out) } } } func (s *DockerSuite) TestRunSetDefaultRestartPolicy(c *check.C) { dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") out, err := inspectField("test", "HostConfig.RestartPolicy.Name") c.Assert(err, check.IsNil) if out != "no" { c.Fatalf("Set default restart policy failed") } } func (s *DockerSuite) TestRunRestartMaxRetries(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") id := strings.TrimSpace(string(out)) if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 10); err != nil { c.Fatal(err) } count, err := inspectField(id, "RestartCount") c.Assert(err, check.IsNil) if count != "3" { c.Fatalf("Container was restarted %s times, expected %d", count, 3) } MaximumRetryCount, err := inspectField(id, "HostConfig.RestartPolicy.MaximumRetryCount") c.Assert(err, check.IsNil) if MaximumRetryCount != "3" { c.Fatalf("Container Maximum Retry Count is %s, expected %s", MaximumRetryCount, "3") } } func (s *DockerSuite) TestRunContainerWithWritableRootfs(c *check.C) { dockerCmd(c, "run", "--rm", "busybox", "touch", "/file") } func (s *DockerSuite) TestRunContainerWithReadonlyRootfs(c *check.C) { testRequires(c, NativeExecDriver) for _, f := range []string{"/file", "/etc/hosts", "/etc/resolv.conf", "/etc/hostname", "/proc/uptime", "/sys/kernel", "/dev/.dont.touch.me"} { testReadOnlyFile(f, c) } } func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) { testRequires(c, NativeExecDriver) // Ensure we have not broken writing /dev/pts out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount") if status != 0 { c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.") } expected := "type devpts (rw," if !strings.Contains(string(out), expected) { c.Fatalf("expected output to contain %s but contains %s", expected, out) } } func testReadOnlyFile(filename string, c *check.C) { testRequires(c, NativeExecDriver) out, _, err := dockerCmdWithError(c, "run", "--read-only", "--rm", "busybox", "touch", filename) if err == nil { c.Fatal("expected container to error on run with read only error") } expected := "Read-only file system" if !strings.Contains(string(out), expected) { c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) } out, _, err = dockerCmdWithError(c, "run", "--read-only", "--privileged", "--rm", "busybox", "touch", filename) if err == nil { c.Fatal("expected container to error on run with read only error") } expected = "Read-only file system" if !strings.Contains(string(out), expected) { c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) } } func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c *check.C) { testRequires(c, NativeExecDriver) dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts") if !strings.Contains(string(out), "testlinked") { c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled") } } func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDnsFlag(c *check.C) { testRequires(c, NativeExecDriver) out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf") if !strings.Contains(string(out), "1.1.1.1") { c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used") } } func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *check.C) { testRequires(c, NativeExecDriver) out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts") if !strings.Contains(string(out), "testreadonly") { c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used") } } func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *check.C) { dockerCmd(c, "run", "-d", "--name", "voltest", "-v", "/foo", "busybox") dockerCmd(c, "run", "-d", "--name", "restarter", "--volumes-from", "voltest", "busybox", "top") // Remove the main volume container and restart the consuming container dockerCmd(c, "rm", "-f", "voltest") // This should not fail since the volumes-from were already applied dockerCmd(c, "restart", "restarter") } // run container with --rm should remove container if exit code != 0 func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *check.C) { name := "flowers" out, _, err := dockerCmdWithError(c, "run", "--name", name, "--rm", "busybox", "ls", "/notexists") if err == nil { c.Fatal("Expected docker run to fail", out, err) } out, err = getAllContainers() if err != nil { c.Fatal(out, err) } if out != "" { c.Fatal("Expected not to have containers", out) } } func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *check.C) { name := "sparkles" out, _, err := dockerCmdWithError(c, "run", "--name", name, "--rm", "busybox", "commandNotFound") if err == nil { c.Fatal("Expected docker run to fail", out, err) } out, err = getAllContainers() if err != nil { c.Fatal(out, err) } if out != "" { c.Fatal("Expected not to have containers", out) } } func (s *DockerSuite) TestRunPidHostWithChildIsKillable(c *check.C) { name := "ibuildthecloud" dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi") time.Sleep(1 * time.Second) errchan := make(chan error) go func() { if out, _, err := dockerCmdWithError(c, "kill", name); err != nil { errchan <- fmt.Errorf("%v:\n%s", err, out) } close(errchan) }() select { case err := <-errchan: c.Assert(err, check.IsNil) case <-time.After(5 * time.Second): c.Fatal("Kill container timed out") } } func (s *DockerSuite) TestRunWithTooSmallMemoryLimit(c *check.C) { // this memory limit is 1 byte less than the min, which is 4MB // https://github.com/docker/docker/blob/v1.5.0/daemon/create.go#L22 out, _, err := dockerCmdWithError(c, "run", "-m", "4194303", "busybox") if err == nil || !strings.Contains(out, "Minimum memory limit allowed is 4MB") { c.Fatalf("expected run to fail when using too low a memory limit: %q", out) } } func (s *DockerSuite) TestRunWriteToProcAsound(c *check.C) { _, code, err := dockerCmdWithError(c, "run", "busybox", "sh", "-c", "echo 111 >> /proc/asound/version") if err == nil || code == 0 { c.Fatal("standard container should not be able to write to /proc/asound") } } func (s *DockerSuite) TestRunReadProcTimer(c *check.C) { testRequires(c, NativeExecDriver) out, code, err := dockerCmdWithError(c, "run", "busybox", "cat", "/proc/timer_stats") if err != nil || code != 0 { c.Fatal(err) } if strings.Trim(out, "\n ") != "" { c.Fatalf("expected to receive no output from /proc/timer_stats but received %q", out) } } func (s *DockerSuite) TestRunReadProcLatency(c *check.C) { testRequires(c, NativeExecDriver) // some kernels don't have this configured so skip the test if this file is not found // on the host running the tests. if _, err := os.Stat("/proc/latency_stats"); err != nil { c.Skip("kernel doesnt have latency_stats configured") return } out, code, err := dockerCmdWithError(c, "run", "busybox", "cat", "/proc/latency_stats") if err != nil || code != 0 { c.Fatal(err) } if strings.Trim(out, "\n ") != "" { c.Fatalf("expected to receive no output from /proc/latency_stats but received %q", out) } } func (s *DockerSuite) TestMountIntoProc(c *check.C) { testRequires(c, NativeExecDriver) _, code, err := dockerCmdWithError(c, "run", "-v", "/proc//sys", "busybox", "true") if err == nil || code == 0 { c.Fatal("container should not be able to mount into /proc") } } func (s *DockerSuite) TestMountIntoSys(c *check.C) { testRequires(c, NativeExecDriver) dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") } func (s *DockerSuite) TestRunUnshareProc(c *check.C) { testRequires(c, Apparmor, NativeExecDriver) name := "acidburn" if out, _, err := dockerCmdWithError(c, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "--mount-proc=/proc", "mount"); err == nil || !strings.Contains(out, "Permission denied") { c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err) } name = "cereal" if out, _, err := dockerCmdWithError(c, "run", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") { c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err) } /* Ensure still fails if running privileged with the default policy */ name = "crashoverride" if out, _, err := dockerCmdWithError(c, "run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "jess/unshare", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc"); err == nil || !strings.Contains(out, "Permission denied") { c.Fatalf("unshare should have failed with permission denied, got: %s, %v", out, err) } } func (s *DockerSuite) TestRunPublishPort(c *check.C) { dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") out, _ := dockerCmd(c, "port", "test") out = strings.Trim(out, "\r\n") if out != "" { c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out) } } // Issue #10184. func (s *DockerSuite) TestDevicePermissions(c *check.C) { testRequires(c, NativeExecDriver) const permissions = "crw-rw-rw-" out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") if status != 0 { c.Fatalf("expected status 0, got %d", status) } if !strings.HasPrefix(out, permissions) { c.Fatalf("output should begin with %q, got %q", permissions, out) } } func (s *DockerSuite) TestRunCapAddCHOWN(c *check.C) { out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok") if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } } // https://github.com/docker/docker/pull/14498 func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { dockerCmd(c, "run", "--name", "parent", "-v", "/test", "busybox", "true") dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") mRO, err := inspectMountPoint("test-volumes-1", "/test") c.Assert(err, check.IsNil) if mRO.RW { c.Fatalf("Expected RO volume was RW") } mRW, err := inspectMountPoint("test-volumes-2", "/test") c.Assert(err, check.IsNil) if !mRW.RW { c.Fatalf("Expected RW volume was RO") } } func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) { testRequires(c, Apparmor) testWritePaths := []string{ /* modprobe and core_pattern should both be denied by generic * policy of denials for /proc/sys/kernel. These files have been * picked to be checked as they are particularly sensitive to writes */ "/proc/sys/kernel/modprobe", "/proc/sys/kernel/core_pattern", "/proc/sysrq-trigger", } for i, filePath := range testWritePaths { name := fmt.Sprintf("writeprocsieve-%d", i) shellCmd := fmt.Sprintf("exec 3>%s", filePath) runCmd := exec.Command(dockerBinary, "run", "--privileged", "--security-opt", "apparmor:docker-default", "--name", name, "busybox", "sh", "-c", shellCmd) if out, exitCode, err := runCommandWithOutput(runCmd); err == nil || exitCode == 0 { c.Fatalf("Open FD for write should have failed with permission denied, got: %s, %v", out, err) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_run_unix_test.go ================================================ // +build !windows package main import ( "bufio" "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "time" "github.com/docker/docker/pkg/mount" "github.com/go-check/check" "github.com/kr/pty" ) // #6509 func (s *DockerSuite) TestRunRedirectStdout(c *check.C) { checkRedirect := func(command string) { _, tty, err := pty.Open() if err != nil { c.Fatalf("Could not open pty: %v", err) } cmd := exec.Command("sh", "-c", command) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty if err := cmd.Start(); err != nil { c.Fatalf("start err: %v", err) } ch := make(chan error) go func() { ch <- cmd.Wait() close(ch) }() select { case <-time.After(10 * time.Second): c.Fatal("command timeout") case err := <-ch: if err != nil { c.Fatalf("wait err=%v", err) } } } checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root") checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root") } // Test recursive bind mount works by default func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) { tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test") if err != nil { c.Fatal(err) } defer os.RemoveAll(tmpDir) // Create a temporary tmpfs mount. tmpfsDir := filepath.Join(tmpDir, "tmpfs") if err := os.MkdirAll(tmpfsDir, 0777); err != nil { c.Fatalf("failed to mkdir at %s - %s", tmpfsDir, err) } if err := mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""); err != nil { c.Fatalf("failed to create a tmpfs mount at %s - %s", tmpfsDir, err) } f, err := ioutil.TempFile(tmpfsDir, "touch-me") if err != nil { c.Fatal(err) } defer f.Close() runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs") out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd) if err != nil && exitCode != 0 { c.Fatal(out, stderr, err) } if !strings.Contains(out, filepath.Base(f.Name())) { c.Fatal("Recursive bind mount test failed. Expected file not found") } } func (s *DockerSuite) TestRunWithUlimits(c *check.C) { testRequires(c, NativeExecDriver) out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n") ul := strings.TrimSpace(out) if ul != "42" { c.Fatalf("expected `ulimit -n` to be 42, got %s", ul) } } func (s *DockerSuite) TestRunContainerWithCgroupParent(c *check.C) { testRequires(c, NativeExecDriver) cgroupParent := "test" name := "cgroup-test" out, _, err := dockerCmdWithError(c, "run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") if err != nil { c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) } cgroupPaths := parseCgroupPaths(string(out)) if len(cgroupPaths) == 0 { c.Fatalf("unexpected output - %q", string(out)) } id, err := getIDByName(name) c.Assert(err, check.IsNil) expectedCgroup := path.Join(cgroupParent, id) found := false for _, path := range cgroupPaths { if strings.HasSuffix(path, expectedCgroup) { found = true break } } if !found { c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) } } func (s *DockerSuite) TestRunContainerWithCgroupParentAbsPath(c *check.C) { testRequires(c, NativeExecDriver) cgroupParent := "/cgroup-parent/test" name := "cgroup-test" out, _, err := dockerCmdWithError(c, "run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") if err != nil { c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) } cgroupPaths := parseCgroupPaths(string(out)) if len(cgroupPaths) == 0 { c.Fatalf("unexpected output - %q", string(out)) } id, err := getIDByName(name) c.Assert(err, check.IsNil) expectedCgroup := path.Join(cgroupParent, id) found := false for _, path := range cgroupPaths { if strings.HasSuffix(path, expectedCgroup) { found = true break } } if !found { c.Fatalf("unexpected cgroup paths. Expected at least one cgroup path to have suffix %q. Cgroup Paths: %v", expectedCgroup, cgroupPaths) } } func (s *DockerSuite) TestRunContainerWithCgroupMountRO(c *check.C) { testRequires(c, NativeExecDriver) filename := "/sys/fs/cgroup/devices/test123" out, _, err := dockerCmdWithError(c, "run", "busybox", "touch", filename) if err == nil { c.Fatal("expected cgroup mount point to be read-only, touch file should fail") } expected := "Read-only file system" if !strings.Contains(out, expected) { c.Fatalf("expected output from failure to contain %s but contains %s", expected, out) } } func (s *DockerSuite) TestRunDeviceDirectory(c *check.C) { testRequires(c, NativeExecDriver) out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/") if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "timer") { c.Fatalf("expected output /dev/snd/timer, received %s", actual) } out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/") if actual := strings.Trim(out, "\r\n"); !strings.Contains(out, "seq") { c.Fatalf("expected output /dev/othersnd/seq, received %s", actual) } } // TestRunDetach checks attaching and detaching with the escape sequence. func (s *DockerSuite) TestRunAttachDetach(c *check.C) { name := "attach-detach" cmd := exec.Command(dockerBinary, "run", "--name", name, "-it", "busybox", "cat") stdout, err := cmd.StdoutPipe() if err != nil { c.Fatal(err) } cpty, tty, err := pty.Open() if err != nil { c.Fatal(err) } defer cpty.Close() cmd.Stdin = tty if err := cmd.Start(); err != nil { c.Fatal(err) } if err := waitRun(name); err != nil { c.Fatal(err) } if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) } out, err := bufio.NewReader(stdout).ReadString('\n') if err != nil { c.Fatal(err) } if strings.TrimSpace(out) != "hello" { c.Fatalf("expected 'hello', got %q", out) } // escape sequence if _, err := cpty.Write([]byte{16}); err != nil { c.Fatal(err) } time.Sleep(100 * time.Millisecond) if _, err := cpty.Write([]byte{17}); err != nil { c.Fatal(err) } ch := make(chan struct{}) go func() { cmd.Wait() ch <- struct{}{} }() running, err := inspectField(name, "State.Running") if err != nil { c.Fatal(err) } if running != "true" { c.Fatal("expected container to still be running") } go func() { exec.Command(dockerBinary, "kill", name).Run() }() select { case <-ch: case <-time.After(10 * time.Millisecond): c.Fatal("timed out waiting for container to exit") } } // "test" should be printed func (s *DockerSuite) TestRunEchoStdoutWithCPUQuota(c *check.C) { testRequires(c, CpuCfsQuota) out, _, err := dockerCmdWithError(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "echo", "test") if err != nil { c.Fatalf("failed to run container: %v, output: %q", err, out) } out = strings.TrimSpace(out) if out != "test" { c.Errorf("container should've printed 'test'") } out, err = inspectField("test", "HostConfig.CpuQuota") c.Assert(err, check.IsNil) if out != "8000" { c.Fatalf("setting the CPU CFS quota failed") } } func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) { testRequires(c, CpuCfsPeriod) if _, _, err := dockerCmdWithError(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "true"); err != nil { c.Fatalf("failed to run container: %v", err) } out, err := inspectField("test", "HostConfig.CpuPeriod") c.Assert(err, check.IsNil) if out != "50000" { c.Fatalf("setting the CPU CFS period failed") } } func (s *DockerSuite) TestRunOOMExitCode(c *check.C) { testRequires(c, OomControl) errChan := make(chan error) go func() { defer close(errChan) out, exitCode, _ := dockerCmdWithError(c, "run", "-m", "4MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done") if expected := 137; exitCode != expected { errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out) } }() select { case err := <-errChan: c.Assert(err, check.IsNil) case <-time.After(30 * time.Second): c.Fatal("Timeout waiting for container to die on OOM") } } func (s *DockerSuite) TestContainerNetworkModeToSelf(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "--name=me", "--net=container:me", "busybox", "true") if err == nil || !strings.Contains(out, "cannot join own network") { c.Fatalf("using container net mode to self should result in an error") } } func (s *DockerSuite) TestRunContainerNetModeWithDnsMacHosts(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-d", "--name", "parent", "busybox", "top") if err != nil { c.Fatalf("failed to run container: %v, output: %q", err, out) } out, _, err = dockerCmdWithError(c, "run", "--dns", "1.2.3.4", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, "Conflicting options: --dns and the network mode") { c.Fatalf("run --net=container with --dns should error out") } out, _, err = dockerCmdWithError(c, "run", "--mac-address", "92:d0:c6:0a:29:33", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, "--mac-address and the network mode") { c.Fatalf("run --net=container with --mac-address should error out") } out, _, err = dockerCmdWithError(c, "run", "--add-host", "test:192.168.2.109", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, "--add-host and the network mode") { c.Fatalf("run --net=container with --add-host should error out") } } func (s *DockerSuite) TestRunContainerNetModeWithExposePort(c *check.C) { dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") out, _, err := dockerCmdWithError(c, "run", "-p", "5000:5000", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") { c.Fatalf("run --net=container with -p should error out") } out, _, err = dockerCmdWithError(c, "run", "-P", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, "Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") { c.Fatalf("run --net=container with -P should error out") } out, _, err = dockerCmdWithError(c, "run", "--expose", "5000", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, "Conflicting options: --expose and the network mode (--expose)") { c.Fatalf("run --net=container with --expose should error out") } } func (s *DockerSuite) TestRunLinkToContainerNetMode(c *check.C) { dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") } func (s *DockerSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *check.C) { out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up") var ( count = 0 parts = strings.Split(out, "\n") ) for _, l := range parts { if l != "" { count++ } } if count != 1 { c.Fatalf("Wrong interface count in container %d", count) } if !strings.HasPrefix(out, "1: lo") { c.Fatalf("Wrong interface in test container: expected [1: lo], got %s", out) } } // Issue #4681 func (s *DockerSuite) TestRunLoopbackWhenNetworkDisabled(c *check.C) { dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") } func (s *DockerSuite) TestRunModeNetContainerHostname(c *check.C) { testRequires(c, ExecSupport) dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname") out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname") if out1 != out { c.Fatal("containers with shared net namespace should have same hostname") } } func (s *DockerSuite) TestRunNetworkNotInitializedNoneMode(c *check.C) { out, _, err := dockerCmdWithError(c, "run", "-d", "--net=none", "busybox", "top") id := strings.TrimSpace(out) res, err := inspectField(id, "NetworkSettings.IPAddress") c.Assert(err, check.IsNil) if res != "" { c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res) } } func (s *DockerSuite) TestTwoContainersInNetHost(c *check.C) { dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") dockerCmd(c, "stop", "first") dockerCmd(c, "stop", "second") } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_save_load_test.go ================================================ package main import ( "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "reflect" "sort" "strings" "github.com/go-check/check" ) // save a repo using gz compression and try to load it using stdout func (s *DockerSuite) TestSaveXzAndLoadRepoStdout(c *check.C) { name := "test-save-xz-and-load-repo-stdout" dockerCmd(c, "run", "--name", name, "busybox", "true") repoName := "foobar-save-load-test-xz-gz" out, _ := dockerCmd(c, "commit", name, repoName) dockerCmd(c, "inspect", repoName) repoTarball, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), exec.Command("xz", "-c"), exec.Command("gzip", "-c")) if err != nil { c.Fatalf("failed to save repo: %v %v", out, err) } deleteImages(repoName) loadCmd := exec.Command(dockerBinary, "load") loadCmd.Stdin = strings.NewReader(repoTarball) out, _, err = runCommandWithOutput(loadCmd) if err == nil { c.Fatalf("expected error, but succeeded with no error and output: %v", out) } after, _, err := dockerCmdWithError(c, "inspect", repoName) if err == nil { c.Fatalf("the repo should not exist: %v", after) } } // save a repo using xz+gz compression and try to load it using stdout func (s *DockerSuite) TestSaveXzGzAndLoadRepoStdout(c *check.C) { name := "test-save-xz-gz-and-load-repo-stdout" dockerCmd(c, "run", "--name", name, "busybox", "true") repoName := "foobar-save-load-test-xz-gz" dockerCmd(c, "commit", name, repoName) dockerCmd(c, "inspect", repoName) out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), exec.Command("xz", "-c"), exec.Command("gzip", "-c")) if err != nil { c.Fatalf("failed to save repo: %v %v", out, err) } deleteImages(repoName) loadCmd := exec.Command(dockerBinary, "load") loadCmd.Stdin = strings.NewReader(out) out, _, err = runCommandWithOutput(loadCmd) if err == nil { c.Fatalf("expected error, but succeeded with no error and output: %v", out) } after, _, err := dockerCmdWithError(c, "inspect", repoName) if err == nil { c.Fatalf("the repo should not exist: %v", after) } } func (s *DockerSuite) TestSaveSingleTag(c *check.C) { repoName := "foobar-save-single-tag-test" dockerCmd(c, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName)) out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName) cleanedImageID := strings.TrimSpace(out) out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", repoName)), exec.Command("tar", "t"), exec.Command("grep", "-E", fmt.Sprintf("(^repositories$|%v)", cleanedImageID))) if err != nil { c.Fatalf("failed to save repo with image ID and 'repositories' file: %s, %v", out, err) } } func (s *DockerSuite) TestSaveImageId(c *check.C) { repoName := "foobar-save-image-id-test" dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName)) out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName) cleanedLongImageID := strings.TrimSpace(out) out, _ = dockerCmd(c, "images", "-q", repoName) cleanedShortImageID := strings.TrimSpace(out) saveCmd := exec.Command(dockerBinary, "save", cleanedShortImageID) tarCmd := exec.Command("tar", "t") var err error tarCmd.Stdin, err = saveCmd.StdoutPipe() if err != nil { c.Fatalf("cannot set stdout pipe for tar: %v", err) } grepCmd := exec.Command("grep", cleanedLongImageID) grepCmd.Stdin, err = tarCmd.StdoutPipe() if err != nil { c.Fatalf("cannot set stdout pipe for grep: %v", err) } if err = tarCmd.Start(); err != nil { c.Fatalf("tar failed with error: %v", err) } if err = saveCmd.Start(); err != nil { c.Fatalf("docker save failed with error: %v", err) } defer saveCmd.Wait() defer tarCmd.Wait() out, _, err = runCommandWithOutput(grepCmd) if err != nil { c.Fatalf("failed to save repo with image ID: %s, %v", out, err) } } // save a repo and try to load it using flags func (s *DockerSuite) TestSaveAndLoadRepoFlags(c *check.C) { name := "test-save-and-load-repo-flags" dockerCmd(c, "run", "--name", name, "busybox", "true") repoName := "foobar-save-load-test" deleteImages(repoName) dockerCmd(c, "commit", name, repoName) before, _ := dockerCmd(c, "inspect", repoName) out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), exec.Command(dockerBinary, "load")) if err != nil { c.Fatalf("failed to save and load repo: %s, %v", out, err) } after, _ := dockerCmd(c, "inspect", repoName) if before != after { c.Fatalf("inspect is not the same after a save / load") } } func (s *DockerSuite) TestSaveMultipleNames(c *check.C) { repoName := "foobar-save-multi-name-test" // Make one image dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v-one:latest", repoName)) // Make two images dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v-two:latest", repoName)) out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", fmt.Sprintf("%v-one", repoName), fmt.Sprintf("%v-two:latest", repoName)), exec.Command("tar", "xO", "repositories"), exec.Command("grep", "-q", "-E", "(-one|-two)"), ) if err != nil { c.Fatalf("failed to save multiple repos: %s, %v", out, err) } } func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) { makeImage := func(from string, tag string) string { var ( out string ) out, _ = dockerCmd(c, "run", "-d", from, "true") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "commit", cleanedContainerID, tag) imageID := strings.TrimSpace(out) return imageID } repoName := "foobar-save-multi-images-test" tagFoo := repoName + ":foo" tagBar := repoName + ":bar" idFoo := makeImage("busybox:latest", tagFoo) idBar := makeImage("busybox:latest", tagBar) deleteImages(repoName) // create the archive out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), exec.Command("tar", "t"), exec.Command("grep", "VERSION"), exec.Command("cut", "-d", "/", "-f1")) if err != nil { c.Fatalf("failed to save multiple images: %s, %v", out, err) } actual := strings.Split(strings.TrimSpace(out), "\n") // make the list of expected layers out, _ = dockerCmd(c, "history", "-q", "--no-trunc", "busybox:latest") expected := append(strings.Split(strings.TrimSpace(out), "\n"), idFoo, idBar) sort.Strings(actual) sort.Strings(expected) if !reflect.DeepEqual(expected, actual) { c.Fatalf("archive does not contains the right layers: got %v, expected %v", actual, expected) } } // Issue #6722 #5892 ensure directories are included in changes func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) { layerEntries := []string{"opt/", "opt/a/", "opt/a/b/", "opt/a/b/c"} layerEntriesAUFS := []string{"./", ".wh..wh.aufs", ".wh..wh.orph/", ".wh..wh.plnk/", "opt/", "opt/a/", "opt/a/b/", "opt/a/b/c"} name := "save-directory-permissions" tmpDir, err := ioutil.TempDir("", "save-layers-with-directories") if err != nil { c.Errorf("failed to create temporary directory: %s", err) } extractionDirectory := filepath.Join(tmpDir, "image-extraction-dir") os.Mkdir(extractionDirectory, 0777) defer os.RemoveAll(tmpDir) _, err = buildImage(name, `FROM busybox RUN adduser -D user && mkdir -p /opt/a/b && chown -R user:user /opt/a RUN touch /opt/a/b/c && chown user:user /opt/a/b/c`, true) if err != nil { c.Fatal(err) } if out, _, err := runCommandPipelineWithOutput( exec.Command(dockerBinary, "save", name), exec.Command("tar", "-xf", "-", "-C", extractionDirectory), ); err != nil { c.Errorf("failed to save and extract image: %s", out) } dirs, err := ioutil.ReadDir(extractionDirectory) if err != nil { c.Errorf("failed to get a listing of the layer directories: %s", err) } found := false for _, entry := range dirs { var entriesSansDev []string if entry.IsDir() { layerPath := filepath.Join(extractionDirectory, entry.Name(), "layer.tar") f, err := os.Open(layerPath) if err != nil { c.Fatalf("failed to open %s: %s", layerPath, err) } entries, err := ListTar(f) for _, e := range entries { if !strings.Contains(e, "dev/") { entriesSansDev = append(entriesSansDev, e) } } if err != nil { c.Fatalf("encountered error while listing tar entries: %s", err) } if reflect.DeepEqual(entriesSansDev, layerEntries) || reflect.DeepEqual(entriesSansDev, layerEntriesAUFS) { found = true break } } } if !found { c.Fatalf("failed to find the layer with the right content listing") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_save_load_unix_test.go ================================================ // +build !windows package main import ( "bytes" "io/ioutil" "os" "os/exec" "github.com/go-check/check" "github.com/kr/pty" ) // save a repo and try to load it using stdout func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) { name := "test-save-and-load-repo-stdout" dockerCmd(c, "run", "--name", name, "busybox", "true") repoName := "foobar-save-load-test" out, _ := dockerCmd(c, "commit", name, repoName) before, _ := dockerCmd(c, "inspect", repoName) tmpFile, err := ioutil.TempFile("", "foobar-save-load-test.tar") c.Assert(err, check.IsNil) defer os.Remove(tmpFile.Name()) saveCmd := exec.Command(dockerBinary, "save", repoName) saveCmd.Stdout = tmpFile if _, err = runCommand(saveCmd); err != nil { c.Fatalf("failed to save repo: %v", err) } tmpFile, err = os.Open(tmpFile.Name()) c.Assert(err, check.IsNil) deleteImages(repoName) loadCmd := exec.Command(dockerBinary, "load") loadCmd.Stdin = tmpFile if out, _, err = runCommandWithOutput(loadCmd); err != nil { c.Fatalf("failed to load repo: %s, %v", out, err) } after, _ := dockerCmd(c, "inspect", repoName) if before != after { c.Fatalf("inspect is not the same after a save / load") } deleteImages(repoName) pty, tty, err := pty.Open() if err != nil { c.Fatalf("Could not open pty: %v", err) } cmd := exec.Command(dockerBinary, "save", repoName) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty if err := cmd.Start(); err != nil { c.Fatalf("start err: %v", err) } if err := cmd.Wait(); err == nil { c.Fatal("did not break writing to a TTY") } buf := make([]byte, 1024) n, err := pty.Read(buf) if err != nil { c.Fatal("could not read tty output") } if !bytes.Contains(buf[:n], []byte("Cowardly refusing")) { c.Fatal("help output is not being yielded", out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_search_test.go ================================================ package main import ( "strings" "github.com/go-check/check" ) // search for repos named "registry" on the central registry func (s *DockerSuite) TestSearchOnCentralRegistry(c *check.C) { testRequires(c, Network) out, exitCode := dockerCmd(c, "search", "busybox") if exitCode != 0 { c.Fatalf("failed to search on the central registry: %s", out) } if !strings.Contains(out, "Busybox base image.") { c.Fatal("couldn't find any repository named (or containing) 'Busybox base image.'") } } func (s *DockerSuite) TestSearchStarsOptionWithWrongParameter(c *check.C) { out, exitCode, err := dockerCmdWithError(c, "search", "--stars=a", "busybox") if err == nil || exitCode == 0 { c.Fatalf("Should not get right information: %s, %v", out, err) } if !strings.Contains(out, "invalid value") { c.Fatal("couldn't find the invalid value warning") } out, exitCode, err = dockerCmdWithError(c, "search", "-s=-1", "busybox") if err == nil || exitCode == 0 { c.Fatalf("Should not get right information: %s, %v", out, err) } if !strings.Contains(out, "invalid value") { c.Fatal("couldn't find the invalid value warning") } } func (s *DockerSuite) TestSearchCmdOptions(c *check.C) { testRequires(c, Network) out, exitCode := dockerCmd(c, "search", "--help") if exitCode != 0 { c.Fatalf("failed to get search help information: %s", out) } if !strings.Contains(out, "Usage:\tdocker search [OPTIONS] TERM") { c.Fatalf("failed to show docker search usage: %s", out) } outSearchCmd, exitCode := dockerCmd(c, "search", "busybox") if exitCode != 0 { c.Fatalf("failed to search on the central registry: %s", outSearchCmd) } outSearchCmdNotrunc, _ := dockerCmd(c, "search", "--no-trunc=true", "busybox") if len(outSearchCmd) > len(outSearchCmdNotrunc) { c.Fatalf("The no-trunc option can't take effect.") } outSearchCmdautomated, exitCode := dockerCmd(c, "search", "--automated=true", "busybox") //The busybox is a busybox base image, not an AUTOMATED image. if exitCode != 0 { c.Fatalf("failed to search with automated=true on the central registry: %s", outSearchCmdautomated) } outSearchCmdautomatedSlice := strings.Split(outSearchCmdautomated, "\n") for i := range outSearchCmdautomatedSlice { if strings.HasPrefix(outSearchCmdautomatedSlice[i], "busybox ") { c.Fatalf("The busybox is not an AUTOMATED image: %s", out) } } outSearchCmdStars, exitCode := dockerCmd(c, "search", "-s=2", "busybox") if exitCode != 0 { c.Fatalf("failed to search with stars=2 on the central registry: %s", outSearchCmdStars) } if strings.Count(outSearchCmdStars, "[OK]") > strings.Count(outSearchCmd, "[OK]") { c.Fatalf("The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars) } out, exitCode = dockerCmd(c, "search", "--stars=2", "--automated=true", "--no-trunc=true", "busybox") if exitCode != 0 { c.Fatalf("failed to search with stars&automated&no-trunc options on the central registry: %s", out) } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_service_test.go ================================================ // +build experimental package main import ( "fmt" "strings" "github.com/go-check/check" ) func assertSrvIsAvailable(c *check.C, sname, name string) { if !isSrvPresent(c, sname, name) { c.Fatalf("Service %s on network %s not found in service ls o/p", sname, name) } } func assertSrvNotAvailable(c *check.C, sname, name string) { if isSrvPresent(c, sname, name) { c.Fatalf("Found service %s on network %s in service ls o/p", sname, name) } } func isSrvPresent(c *check.C, sname, name string) bool { out, _, _ := dockerCmdWithStdoutStderr(c, "service", "ls") lines := strings.Split(out, "\n") for i := 1; i < len(lines)-1; i++ { if strings.Contains(lines[i], sname) && strings.Contains(lines[i], name) { return true } } return false } func isCntPresent(c *check.C, cname, sname, name string) bool { out, _, _ := dockerCmdWithStdoutStderr(c, "service", "ls", "--no-trunc") lines := strings.Split(out, "\n") for i := 1; i < len(lines)-1; i++ { fmt.Println(lines) if strings.Contains(lines[i], name) && strings.Contains(lines[i], sname) && strings.Contains(lines[i], cname) { return true } } return false } func (s *DockerSuite) TestDockerServiceCreateDelete(c *check.C) { dockerCmdWithStdoutStderr(c, "network", "create", "test") assertNwIsAvailable(c, "test") dockerCmdWithStdoutStderr(c, "service", "publish", "s1.test") assertSrvIsAvailable(c, "s1", "test") dockerCmdWithStdoutStderr(c, "service", "unpublish", "s1.test") assertSrvNotAvailable(c, "s1", "test") dockerCmdWithStdoutStderr(c, "network", "rm", "test") assertNwNotAvailable(c, "test") } func (s *DockerSuite) TestDockerPublishServiceFlag(c *check.C) { // Run saying the container is the backend for the specified service on the specified network out, _ := dockerCmd(c, "run", "-d", "--expose=23", "--publish-service", "telnet.production", "busybox", "top") cid := strings.TrimSpace(out) // Verify container is attached in service ps o/p assertSrvIsAvailable(c, "telnet", "production") dockerCmd(c, "rm", "-f", cid) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_start_test.go ================================================ package main import ( "fmt" "strings" "time" "github.com/go-check/check" ) // Regression test for https://github.com/docker/docker/issues/7843 func (s *DockerSuite) TestStartAttachReturnsOnError(c *check.C) { dockerCmd(c, "run", "-d", "--name", "test", "busybox") dockerCmd(c, "wait", "test") // Expect this to fail because the above container is stopped, this is what we want if _, _, err := dockerCmdWithError(c, "run", "-d", "--name", "test2", "--link", "test:test", "busybox"); err == nil { c.Fatal("Expected error but got none") } ch := make(chan error) go func() { // Attempt to start attached to the container that won't start // This should return an error immediately since the container can't be started if _, _, err := dockerCmdWithError(c, "start", "-a", "test2"); err == nil { ch <- fmt.Errorf("Expected error but got none") } close(ch) }() select { case err := <-ch: c.Assert(err, check.IsNil) case <-time.After(time.Second): c.Fatalf("Attach did not exit properly") } } // gh#8555: Exit code should be passed through when using start -a func (s *DockerSuite) TestStartAttachCorrectExitCode(c *check.C) { out, _, _ := dockerCmdWithStdoutStderr(c, "run", "-d", "busybox", "sh", "-c", "sleep 2; exit 1") out = strings.TrimSpace(out) // make sure the container has exited before trying the "start -a" dockerCmd(c, "wait", out) startOut, exitCode, err := dockerCmdWithError(c, "start", "-a", out) if err != nil && !strings.Contains("exit status 1", fmt.Sprintf("%s", err)) { c.Fatalf("start command failed unexpectedly with error: %v, output: %q", err, startOut) } if exitCode != 1 { c.Fatalf("start -a did not respond with proper exit code: expected 1, got %d", exitCode) } } func (s *DockerSuite) TestStartAttachSilent(c *check.C) { name := "teststartattachcorrectexitcode" dockerCmd(c, "run", "--name", name, "busybox", "echo", "test") // make sure the container has exited before trying the "start -a" dockerCmd(c, "wait", name) startOut, _ := dockerCmd(c, "start", "-a", name) if expected := "test\n"; startOut != expected { c.Fatalf("start -a produced unexpected output: expected %q, got %q", expected, startOut) } } func (s *DockerSuite) TestStartRecordError(c *check.C) { // when container runs successfully, we should not have state.Error dockerCmd(c, "run", "-d", "-p", "9999:9999", "--name", "test", "busybox", "top") stateErr, err := inspectField("test", "State.Error") c.Assert(err, check.IsNil) if stateErr != "" { c.Fatalf("Expected to not have state error but got state.Error(%q)", stateErr) } // Expect this to fail and records error because of ports conflict out, _, err := dockerCmdWithError(c, "run", "-d", "--name", "test2", "-p", "9999:9999", "busybox", "top") if err == nil { c.Fatalf("Expected error but got none, output %q", out) } stateErr, err = inspectField("test2", "State.Error") c.Assert(err, check.IsNil) expected := "port is already allocated" if stateErr == "" || !strings.Contains(stateErr, expected) { c.Fatalf("State.Error(%q) does not include %q", stateErr, expected) } // Expect the conflict to be resolved when we stop the initial container dockerCmd(c, "stop", "test") dockerCmd(c, "start", "test2") stateErr, err = inspectField("test2", "State.Error") c.Assert(err, check.IsNil) if stateErr != "" { c.Fatalf("Expected to not have state error but got state.Error(%q)", stateErr) } } func (s *DockerSuite) TestStartPausedContainer(c *check.C) { defer unpauseAllContainers() dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") dockerCmd(c, "pause", "testing") if out, _, err := dockerCmdWithError(c, "start", "testing"); err == nil || !strings.Contains(out, "Cannot start a paused container, try unpause instead.") { c.Fatalf("an error should have been shown that you cannot start paused container: %s\n%v", out, err) } } func (s *DockerSuite) TestStartMultipleContainers(c *check.C) { // run a container named 'parent' and create two container link to `parent` dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") for _, container := range []string{"child_first", "child_second"} { dockerCmd(c, "create", "--name", container, "--link", "parent:parent", "busybox", "top") } // stop 'parent' container dockerCmd(c, "stop", "parent") out, err := inspectField("parent", "State.Running") c.Assert(err, check.IsNil) if out != "false" { c.Fatal("Container should be stopped") } // start all the three containers, container `child_first` start first which should be failed // container 'parent' start second and then start container 'child_second' out, _, err = dockerCmdWithError(c, "start", "child_first", "parent", "child_second") if !strings.Contains(out, "Cannot start container child_first") || err == nil { c.Fatal("Expected error but got none") } for container, expected := range map[string]string{"parent": "true", "child_first": "false", "child_second": "true"} { out, err := inspectField(container, "State.Running") c.Assert(err, check.IsNil) if out != expected { c.Fatal("Container running state wrong") } } } func (s *DockerSuite) TestStartAttachMultipleContainers(c *check.C) { // run multiple containers to test for _, container := range []string{"test1", "test2", "test3"} { dockerCmd(c, "run", "-d", "--name", container, "busybox", "top") } // stop all the containers for _, container := range []string{"test1", "test2", "test3"} { dockerCmd(c, "stop", container) } // test start and attach multiple containers at once, expected error for _, option := range []string{"-a", "-i", "-ai"} { out, _, err := dockerCmdWithError(c, "start", option, "test1", "test2", "test3") if !strings.Contains(out, "You cannot start and attach multiple containers at once.") || err == nil { c.Fatal("Expected error but got none") } } // confirm the state of all the containers be stopped for container, expected := range map[string]string{"test1": "false", "test2": "false", "test3": "false"} { out, err := inspectField(container, "State.Running") if err != nil { c.Fatal(out, err) } if out != expected { c.Fatal("Container running state wrong") } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_start_volume_driver_unix_test.go ================================================ // +build !windows package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "github.com/go-check/check" ) func init() { check.Suite(&DockerExternalVolumeSuite{ ds: &DockerSuite{}, }) } type eventCounter struct { activations int creations int removals int mounts int unmounts int paths int } type DockerExternalVolumeSuite struct { server *httptest.Server ds *DockerSuite d *Daemon ec *eventCounter } func (s *DockerExternalVolumeSuite) SetUpTest(c *check.C) { s.d = NewDaemon(c) s.ec = &eventCounter{} } func (s *DockerExternalVolumeSuite) TearDownTest(c *check.C) { s.d.Stop() s.ds.TearDownTest(c) } func (s *DockerExternalVolumeSuite) SetUpSuite(c *check.C) { mux := http.NewServeMux() s.server = httptest.NewServer(mux) type pluginRequest struct { name string } mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { s.ec.activations++ w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{"Implements": ["VolumeDriver"]}`) }) mux.HandleFunc("/VolumeDriver.Create", func(w http.ResponseWriter, r *http.Request) { s.ec.creations++ w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{}`) }) mux.HandleFunc("/VolumeDriver.Remove", func(w http.ResponseWriter, r *http.Request) { s.ec.removals++ w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{}`) }) mux.HandleFunc("/VolumeDriver.Path", func(w http.ResponseWriter, r *http.Request) { s.ec.paths++ var pr pluginRequest if err := json.NewDecoder(r.Body).Decode(&pr); err != nil { http.Error(w, err.Error(), 500) } p := hostVolumePath(pr.name) w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, fmt.Sprintf("{\"Mountpoint\": \"%s\"}", p)) }) mux.HandleFunc("/VolumeDriver.Mount", func(w http.ResponseWriter, r *http.Request) { s.ec.mounts++ var pr pluginRequest if err := json.NewDecoder(r.Body).Decode(&pr); err != nil { http.Error(w, err.Error(), 500) } p := hostVolumePath(pr.name) if err := os.MkdirAll(p, 0755); err != nil { http.Error(w, err.Error(), 500) } if err := ioutil.WriteFile(filepath.Join(p, "test"), []byte(s.server.URL), 0644); err != nil { http.Error(w, err.Error(), 500) } w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, fmt.Sprintf("{\"Mountpoint\": \"%s\"}", p)) }) mux.HandleFunc("/VolumeDriver.Unmount", func(w http.ResponseWriter, r *http.Request) { s.ec.unmounts++ var pr pluginRequest if err := json.NewDecoder(r.Body).Decode(&pr); err != nil { http.Error(w, err.Error(), 500) } p := hostVolumePath(pr.name) if err := os.RemoveAll(p); err != nil { http.Error(w, err.Error(), 500) } w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{}`) }) if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil { c.Fatal(err) } if err := ioutil.WriteFile("/etc/docker/plugins/test-external-volume-driver.spec", []byte(s.server.URL), 0644); err != nil { c.Fatal(err) } } func (s *DockerExternalVolumeSuite) TearDownSuite(c *check.C) { s.server.Close() if err := os.RemoveAll("/etc/docker/plugins"); err != nil { c.Fatal(err) } } func (s *DockerExternalVolumeSuite) TestStartExternalNamedVolumeDriver(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "--rm", "--name", "test-data", "-v", "external-volume-test:/tmp/external-volume-test", "--volume-driver", "test-external-volume-driver", "busybox:latest", "cat", "/tmp/external-volume-test/test") if err != nil { c.Fatal(err) } if !strings.Contains(out, s.server.URL) { c.Fatalf("External volume mount failed. Output: %s\n", out) } p := hostVolumePath("external-volume-test") _, err = os.Lstat(p) if err == nil { c.Fatalf("Expected error checking volume path in host: %s\n", p) } if !os.IsNotExist(err) { c.Fatalf("Expected volume path in host to not exist: %s, %v\n", p, err) } c.Assert(s.ec.activations, check.Equals, 1) c.Assert(s.ec.creations, check.Equals, 1) c.Assert(s.ec.removals, check.Equals, 1) c.Assert(s.ec.mounts, check.Equals, 1) c.Assert(s.ec.unmounts, check.Equals, 1) } func (s *DockerExternalVolumeSuite) TestStartExternalVolumeUnnamedDriver(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } out, err := s.d.Cmd("run", "--rm", "--name", "test-data", "-v", "/tmp/external-volume-test", "--volume-driver", "test-external-volume-driver", "busybox:latest", "cat", "/tmp/external-volume-test/test") if err != nil { c.Fatal(err) } if !strings.Contains(out, s.server.URL) { c.Fatalf("External volume mount failed. Output: %s\n", out) } c.Assert(s.ec.activations, check.Equals, 1) c.Assert(s.ec.creations, check.Equals, 1) c.Assert(s.ec.removals, check.Equals, 1) c.Assert(s.ec.mounts, check.Equals, 1) c.Assert(s.ec.unmounts, check.Equals, 1) } func (s DockerExternalVolumeSuite) TestStartExternalVolumeDriverVolumesFrom(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } if _, err := s.d.Cmd("run", "-d", "--name", "vol-test1", "-v", "/foo", "--volume-driver", "test-external-volume-driver", "busybox:latest"); err != nil { c.Fatal(err) } if _, err := s.d.Cmd("run", "--rm", "--volumes-from", "vol-test1", "--name", "vol-test2", "busybox", "ls", "/tmp"); err != nil { c.Fatal(err) } if _, err := s.d.Cmd("rm", "-f", "vol-test1"); err != nil { c.Fatal(err) } c.Assert(s.ec.activations, check.Equals, 1) c.Assert(s.ec.creations, check.Equals, 2) c.Assert(s.ec.removals, check.Equals, 1) c.Assert(s.ec.mounts, check.Equals, 2) c.Assert(s.ec.unmounts, check.Equals, 2) } func (s DockerExternalVolumeSuite) TestStartExternalVolumeDriverDeleteContainer(c *check.C) { if err := s.d.StartWithBusybox(); err != nil { c.Fatal(err) } if _, err := s.d.Cmd("run", "-d", "--name", "vol-test1", "-v", "/foo", "--volume-driver", "test-external-volume-driver", "busybox:latest"); err != nil { c.Fatal(err) } if _, err := s.d.Cmd("rm", "-fv", "vol-test1"); err != nil { c.Fatal(err) } c.Assert(s.ec.activations, check.Equals, 1) c.Assert(s.ec.creations, check.Equals, 1) c.Assert(s.ec.removals, check.Equals, 1) c.Assert(s.ec.mounts, check.Equals, 1) c.Assert(s.ec.unmounts, check.Equals, 1) } func hostVolumePath(name string) string { return fmt.Sprintf("/var/lib/docker/volumes/%s", name) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_stats_test.go ================================================ package main import ( "os/exec" "strings" "time" "github.com/go-check/check" ) func (s *DockerSuite) TestCliStatsNoStream(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) if err := waitRun(id); err != nil { c.Fatalf("error waiting for container to start: %v", err) } statsCmd := exec.Command(dockerBinary, "stats", "--no-stream", id) chErr := make(chan error) go func() { chErr <- statsCmd.Run() }() select { case err := <-chErr: if err != nil { c.Fatalf("Error running stats: %v", err) } case <-time.After(3 * time.Second): statsCmd.Process.Kill() c.Fatalf("stats did not return immediately when not streaming") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_tag_test.go ================================================ package main import ( "strings" "github.com/docker/docker/pkg/stringutils" "github.com/go-check/check" ) // tagging a named image in a new unprefixed repo should work func (s *DockerSuite) TestTagUnprefixedRepoByName(c *check.C) { if err := pullImageIfNotExist("busybox:latest"); err != nil { c.Fatal("couldn't find the busybox:latest image locally and failed to pull it") } dockerCmd(c, "tag", "busybox:latest", "testfoobarbaz") } // tagging an image by ID in a new unprefixed repo should work func (s *DockerSuite) TestTagUnprefixedRepoByID(c *check.C) { imageID, err := inspectField("busybox", "Id") c.Assert(err, check.IsNil) dockerCmd(c, "tag", imageID, "testfoobarbaz") } // ensure we don't allow the use of invalid repository names; these tag operations should fail func (s *DockerSuite) TestTagInvalidUnprefixedRepo(c *check.C) { invalidRepos := []string{"fo$z$", "Foo@3cc", "Foo$3", "Foo*3", "Fo^3", "Foo!3", "F)xcz(", "fo%asd"} for _, repo := range invalidRepos { _, _, err := dockerCmdWithError(c, "tag", "busybox", repo) if err == nil { c.Fatalf("tag busybox %v should have failed", repo) } } } // ensure we don't allow the use of invalid tags; these tag operations should fail func (s *DockerSuite) TestTagInvalidPrefixedRepo(c *check.C) { longTag := stringutils.GenerateRandomAlphaOnlyString(121) invalidTags := []string{"repo:fo$z$", "repo:Foo@3cc", "repo:Foo$3", "repo:Foo*3", "repo:Fo^3", "repo:Foo!3", "repo:%goodbye", "repo:#hashtagit", "repo:F)xcz(", "repo:-foo", "repo:..", longTag} for _, repotag := range invalidTags { _, _, err := dockerCmdWithError(c, "tag", "busybox", repotag) if err == nil { c.Fatalf("tag busybox %v should have failed", repotag) } } } // ensure we allow the use of valid tags func (s *DockerSuite) TestTagValidPrefixedRepo(c *check.C) { if err := pullImageIfNotExist("busybox:latest"); err != nil { c.Fatal("couldn't find the busybox:latest image locally and failed to pull it") } validRepos := []string{"fooo/bar", "fooaa/test", "foooo:t"} for _, repo := range validRepos { _, _, err := dockerCmdWithError(c, "tag", "busybox:latest", repo) if err != nil { c.Errorf("tag busybox %v should have worked: %s", repo, err) continue } deleteImages(repo) } } // tag an image with an existed tag name without -f option should fail func (s *DockerSuite) TestTagExistedNameWithoutForce(c *check.C) { if err := pullImageIfNotExist("busybox:latest"); err != nil { c.Fatal("couldn't find the busybox:latest image locally and failed to pull it") } dockerCmd(c, "tag", "busybox:latest", "busybox:test") out, _, err := dockerCmdWithError(c, "tag", "busybox:latest", "busybox:test") if err == nil || !strings.Contains(out, "Conflict: Tag test is already set to image") { c.Fatal("tag busybox busybox:test should have failed,because busybox:test is existed") } } // tag an image with an existed tag name with -f option should work func (s *DockerSuite) TestTagExistedNameWithForce(c *check.C) { if err := pullImageIfNotExist("busybox:latest"); err != nil { c.Fatal("couldn't find the busybox:latest image locally and failed to pull it") } dockerCmd(c, "tag", "busybox:latest", "busybox:test") dockerCmd(c, "tag", "-f", "busybox:latest", "busybox:test") } func (s *DockerSuite) TestTagWithPrefixHyphen(c *check.C) { if err := pullImageIfNotExist("busybox:latest"); err != nil { c.Fatal("couldn't find the busybox:latest image locally and failed to pull it") } // test repository name begin with '-' out, _, err := dockerCmdWithError(c, "tag", "busybox:latest", "-busybox:test") if err == nil || !strings.Contains(out, "repository name component must match") { c.Fatal("tag a name begin with '-' should failed") } // test namespace name begin with '-' out, _, err = dockerCmdWithError(c, "tag", "busybox:latest", "-test/busybox:test") if err == nil || !strings.Contains(out, "repository name component must match") { c.Fatal("tag a name begin with '-' should failed") } // test index name begin wiht '-' out, _, err = dockerCmdWithError(c, "tag", "busybox:latest", "-index:5000/busybox:test") if err == nil || !strings.Contains(out, "Invalid index name (-index:5000). Cannot begin or end with a hyphen") { c.Fatal("tag a name begin with '-' should failed") } } // ensure tagging using official names works // ensure all tags result in the same name func (s *DockerSuite) TestTagOfficialNames(c *check.C) { names := []string{ "docker.io/busybox", "index.docker.io/busybox", "library/busybox", "docker.io/library/busybox", "index.docker.io/library/busybox", } for _, name := range names { out, exitCode, err := dockerCmdWithError(c, "tag", "-f", "busybox:latest", name+":latest") if err != nil || exitCode != 0 { c.Errorf("tag busybox %v should have worked: %s, %s", name, err, out) continue } // ensure we don't have multiple tag names. out, _, err = dockerCmdWithError(c, "images") if err != nil { c.Errorf("listing images failed with errors: %v, %s", err, out) } else if strings.Contains(out, name) { c.Errorf("images should not have listed '%s'", name) deleteImages(name + ":latest") } } for _, name := range names { _, exitCode, err := dockerCmdWithError(c, "tag", "-f", name+":latest", "fooo/bar:latest") if err != nil || exitCode != 0 { c.Errorf("tag %v fooo/bar should have worked: %s", name, err) continue } deleteImages("fooo/bar:latest") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_top_test.go ================================================ package main import ( "strings" "github.com/go-check/check" ) func (s *DockerSuite) TestTopMultipleArgs(c *check.C) { out, _ := dockerCmd(c, "run", "-i", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "top", cleanedContainerID, "-o", "pid") if !strings.Contains(out, "PID") { c.Fatalf("did not see PID after top -o pid: %s", out) } } func (s *DockerSuite) TestTopNonPrivileged(c *check.C) { out, _ := dockerCmd(c, "run", "-i", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) out1, _ := dockerCmd(c, "top", cleanedContainerID) out2, _ := dockerCmd(c, "top", cleanedContainerID) out, _ = dockerCmd(c, "kill", cleanedContainerID) if !strings.Contains(out1, "top") && !strings.Contains(out2, "top") { c.Fatal("top should've listed `top` in the process list, but failed twice") } else if !strings.Contains(out1, "top") { c.Fatal("top should've listed `top` in the process list, but failed the first time") } else if !strings.Contains(out2, "top") { c.Fatal("top should've listed `top` in the process list, but failed the second itime") } } func (s *DockerSuite) TestTopPrivileged(c *check.C) { out, _ := dockerCmd(c, "run", "--privileged", "-i", "-d", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) out1, _ := dockerCmd(c, "top", cleanedContainerID) out2, _ := dockerCmd(c, "top", cleanedContainerID) out, _ = dockerCmd(c, "kill", cleanedContainerID) if !strings.Contains(out1, "top") && !strings.Contains(out2, "top") { c.Fatal("top should've listed `top` in the process list, but failed twice") } else if !strings.Contains(out1, "top") { c.Fatal("top should've listed `top` in the process list, but failed the first time") } else if !strings.Contains(out2, "top") { c.Fatal("top should've listed `top` in the process list, but failed the second itime") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_version_test.go ================================================ package main import ( "strings" "github.com/go-check/check" ) // ensure docker version works func (s *DockerSuite) TestVersionEnsureSucceeds(c *check.C) { out, _ := dockerCmd(c, "version") stringsToCheck := map[string]int{ "Client:": 1, "Server:": 1, " Version:": 2, " API version:": 2, " Go version:": 2, " Git commit:": 2, " OS/Arch:": 2, " Built:": 2, } for k, v := range stringsToCheck { if strings.Count(out, k) != v { c.Errorf("%v expected %d instances found %d", k, v, strings.Count(out, k)) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_cli_wait_test.go ================================================ package main import ( "bytes" "os/exec" "strings" "time" "github.com/go-check/check" ) // non-blocking wait with 0 exit code func (s *DockerSuite) TestWaitNonBlockedExitZero(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "true") containerID := strings.TrimSpace(out) status := "true" var err error for i := 0; status != "false"; i++ { status, err = inspectField(containerID, "State.Running") c.Assert(err, check.IsNil) time.Sleep(time.Second) if i >= 60 { c.Fatal("Container should have stopped by now") } } out, _ = dockerCmd(c, "wait", containerID) if strings.TrimSpace(out) != "0" { c.Fatal("failed to set up container", out) } } // blocking wait with 0 exit code func (s *DockerSuite) TestWaitBlockedExitZero(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "trap 'exit 0' TERM; while true; do sleep 0.01; done") containerID := strings.TrimSpace(out) if err := waitRun(containerID); err != nil { c.Fatal(err) } chWait := make(chan string) go func() { out, _, _ := runCommandWithOutput(exec.Command(dockerBinary, "wait", containerID)) chWait <- out }() time.Sleep(100 * time.Millisecond) dockerCmd(c, "stop", containerID) select { case status := <-chWait: if strings.TrimSpace(status) != "0" { c.Fatalf("expected exit 0, got %s", status) } case <-time.After(2 * time.Second): c.Fatal("timeout waiting for `docker wait` to exit") } } // non-blocking wait with random exit code func (s *DockerSuite) TestWaitNonBlockedExitRandom(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "exit 99") containerID := strings.TrimSpace(out) status := "true" var err error for i := 0; status != "false"; i++ { status, err = inspectField(containerID, "State.Running") c.Assert(err, check.IsNil) time.Sleep(time.Second) if i >= 60 { c.Fatal("Container should have stopped by now") } } out, _ = dockerCmd(c, "wait", containerID) if strings.TrimSpace(out) != "99" { c.Fatal("failed to set up container", out) } } // blocking wait with random exit code func (s *DockerSuite) TestWaitBlockedExitRandom(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "trap 'exit 99' TERM; while true; do sleep 0.01; done") containerID := strings.TrimSpace(out) if err := waitRun(containerID); err != nil { c.Fatal(err) } if err := waitRun(containerID); err != nil { c.Fatal(err) } chWait := make(chan error) waitCmd := exec.Command(dockerBinary, "wait", containerID) waitCmdOut := bytes.NewBuffer(nil) waitCmd.Stdout = waitCmdOut if err := waitCmd.Start(); err != nil { c.Fatal(err) } go func() { chWait <- waitCmd.Wait() }() dockerCmd(c, "stop", containerID) select { case err := <-chWait: if err != nil { c.Fatal(err) } status, err := waitCmdOut.ReadString('\n') if err != nil { c.Fatal(err) } if strings.TrimSpace(status) != "99" { c.Fatalf("expected exit 99, got %s", status) } case <-time.After(2 * time.Second): waitCmd.Process.Kill() c.Fatal("timeout waiting for `docker wait` to exit") } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_test_vars.go ================================================ package main import ( "fmt" "os" "os/exec" ) var ( // the docker binary to use dockerBinary = "docker" // the private registry image to use for tests involving the registry registryImageName = "registry" // the private registry to use for tests privateRegistryURL = "127.0.0.1:5000" dockerBasePath = "/var/lib/docker" volumesConfigPath = dockerBasePath + "/volumes" containerStoragePath = dockerBasePath + "/containers" runtimePath = "/var/run/docker" execDriverPath = runtimePath + "/execdriver/native" workingDirectory string ) func init() { if dockerBin := os.Getenv("DOCKER_BINARY"); dockerBin != "" { dockerBinary = dockerBin } var err error dockerBinary, err = exec.LookPath(dockerBinary) if err != nil { fmt.Printf("ERROR: couldn't resolve full path to the Docker binary (%v)", err) os.Exit(1) } if registryImage := os.Getenv("REGISTRY_IMAGE"); registryImage != "" { registryImageName = registryImage } if registry := os.Getenv("REGISTRY_URL"); registry != "" { privateRegistryURL = registry } workingDirectory, _ = os.Getwd() } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_test_vars_cli.go ================================================ // +build !daemon package main const ( // tests should not assume daemon runs on the same machine as CLI isLocalDaemon = false ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_test_vars_daemon.go ================================================ // +build daemon package main const ( // tests can assume daemon runs on the same machine as CLI isLocalDaemon = true ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/docker_utils.go ================================================ package main import ( "bytes" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "time" "github.com/docker/docker/api/types" "github.com/docker/docker/opts" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/stringutils" "github.com/go-check/check" ) // Daemon represents a Docker daemon for the testing framework. type Daemon struct { c *check.C logFile *os.File folder string stdin io.WriteCloser stdout, stderr io.ReadCloser cmd *exec.Cmd storageDriver string execDriver string wait chan error userlandProxy bool } func enableUserlandProxy() bool { if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" { if val, err := strconv.ParseBool(env); err != nil { return val } } return true } // NewDaemon returns a Daemon instance to be used for testing. // This will create a directory such as d123456789 in the folder specified by $DEST. // The daemon will not automatically start. func NewDaemon(c *check.C) *Daemon { dest := os.Getenv("DEST") if dest == "" { c.Fatal("Please set the DEST environment variable") } dir := filepath.Join(dest, fmt.Sprintf("d%d", time.Now().UnixNano()%100000000)) daemonFolder, err := filepath.Abs(dir) if err != nil { c.Fatalf("Could not make %q an absolute path: %v", dir, err) } if err := os.MkdirAll(filepath.Join(daemonFolder, "graph"), 0600); err != nil { c.Fatalf("Could not create %s/graph directory", daemonFolder) } userlandProxy := true if env := os.Getenv("DOCKER_USERLANDPROXY"); env != "" { if val, err := strconv.ParseBool(env); err != nil { userlandProxy = val } } return &Daemon{ c: c, folder: daemonFolder, storageDriver: os.Getenv("DOCKER_GRAPHDRIVER"), execDriver: os.Getenv("DOCKER_EXECDRIVER"), userlandProxy: userlandProxy, } } // Start will start the daemon and return once it is ready to receive requests. // You can specify additional daemon flags. func (d *Daemon) Start(arg ...string) error { dockerBinary, err := exec.LookPath(dockerBinary) if err != nil { d.c.Fatalf("could not find docker binary in $PATH: %v", err) } args := []string{ "--host", d.sock(), "--daemon", "--graph", fmt.Sprintf("%s/graph", d.folder), "--pidfile", fmt.Sprintf("%s/docker.pid", d.folder), fmt.Sprintf("--userland-proxy=%t", d.userlandProxy), } // If we don't explicitly set the log-level or debug flag(-D) then // turn on debug mode foundIt := false for _, a := range arg { if strings.Contains(a, "--log-level") || strings.Contains(a, "-D") { foundIt = true } } if !foundIt { args = append(args, "--debug") } if d.storageDriver != "" { args = append(args, "--storage-driver", d.storageDriver) } if d.execDriver != "" { args = append(args, "--exec-driver", d.execDriver) } args = append(args, arg...) d.cmd = exec.Command(dockerBinary, args...) d.logFile, err = os.OpenFile(filepath.Join(d.folder, "docker.log"), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600) if err != nil { d.c.Fatalf("Could not create %s/docker.log: %v", d.folder, err) } d.cmd.Stdout = d.logFile d.cmd.Stderr = d.logFile if err := d.cmd.Start(); err != nil { return fmt.Errorf("could not start daemon container: %v", err) } wait := make(chan error) go func() { wait <- d.cmd.Wait() d.c.Log("exiting daemon") close(wait) }() d.wait = wait tick := time.Tick(500 * time.Millisecond) // make sure daemon is ready to receive requests startTime := time.Now().Unix() for { d.c.Log("waiting for daemon to start") if time.Now().Unix()-startTime > 5 { // After 5 seconds, give up return errors.New("Daemon exited and never started") } select { case <-time.After(2 * time.Second): return errors.New("timeout: daemon does not respond") case <-tick: c, err := net.Dial("unix", filepath.Join(d.folder, "docker.sock")) if err != nil { continue } client := httputil.NewClientConn(c, nil) defer client.Close() req, err := http.NewRequest("GET", "/_ping", nil) if err != nil { d.c.Fatalf("could not create new request: %v", err) } resp, err := client.Do(req) if err != nil { continue } if resp.StatusCode != http.StatusOK { d.c.Logf("received status != 200 OK: %s", resp.Status) } d.c.Log("daemon started") return nil } } } // StartWithBusybox will first start the daemon with Daemon.Start() // then save the busybox image from the main daemon and load it into this Daemon instance. func (d *Daemon) StartWithBusybox(arg ...string) error { if err := d.Start(arg...); err != nil { return err } bb := filepath.Join(d.folder, "busybox.tar") if _, err := os.Stat(bb); err != nil { if !os.IsNotExist(err) { return fmt.Errorf("unexpected error on busybox.tar stat: %v", err) } // saving busybox image from main daemon if err := exec.Command(dockerBinary, "save", "--output", bb, "busybox:latest").Run(); err != nil { return fmt.Errorf("could not save busybox image: %v", err) } } // loading busybox image to this daemon if _, err := d.Cmd("load", "--input", bb); err != nil { return fmt.Errorf("could not load busybox image: %v", err) } if err := os.Remove(bb); err != nil { d.c.Logf("Could not remove %s: %v", bb, err) } return nil } // Stop will send a SIGINT every second and wait for the daemon to stop. // If it timeouts, a SIGKILL is sent. // Stop will not delete the daemon directory. If a purged daemon is needed, // instantiate a new one with NewDaemon. func (d *Daemon) Stop() error { if d.cmd == nil || d.wait == nil { return errors.New("daemon not started") } defer func() { d.logFile.Close() d.cmd = nil }() i := 1 tick := time.Tick(time.Second) if err := d.cmd.Process.Signal(os.Interrupt); err != nil { return fmt.Errorf("could not send signal: %v", err) } out1: for { select { case err := <-d.wait: return err case <-time.After(15 * time.Second): // time for stopping jobs and run onShutdown hooks d.c.Log("timeout") break out1 } } out2: for { select { case err := <-d.wait: return err case <-tick: i++ if i > 4 { d.c.Logf("tried to interrupt daemon for %d times, now try to kill it", i) break out2 } d.c.Logf("Attempt #%d: daemon is still running with pid %d", i, d.cmd.Process.Pid) if err := d.cmd.Process.Signal(os.Interrupt); err != nil { return fmt.Errorf("could not send signal: %v", err) } } } if err := d.cmd.Process.Kill(); err != nil { d.c.Logf("Could not kill daemon: %v", err) return err } return nil } // Restart will restart the daemon by first stopping it and then starting it. func (d *Daemon) Restart(arg ...string) error { d.Stop() return d.Start(arg...) } func (d *Daemon) sock() string { return fmt.Sprintf("unix://%s/docker.sock", d.folder) } // Cmd will execute a docker CLI command against this Daemon. // Example: d.Cmd("version") will run docker -H unix://path/to/unix.sock version func (d *Daemon) Cmd(name string, arg ...string) (string, error) { args := []string{"--host", d.sock(), name} args = append(args, arg...) c := exec.Command(dockerBinary, args...) b, err := c.CombinedOutput() return string(b), err } func (d *Daemon) CmdWithArgs(daemonArgs []string, name string, arg ...string) (string, error) { args := append(daemonArgs, name) args = append(args, arg...) c := exec.Command(dockerBinary, args...) b, err := c.CombinedOutput() return string(b), err } func (d *Daemon) LogfileName() string { return d.logFile.Name() } func daemonHost() string { daemonUrlStr := "unix://" + opts.DefaultUnixSocket if daemonHostVar := os.Getenv("DOCKER_HOST"); daemonHostVar != "" { daemonUrlStr = daemonHostVar } return daemonUrlStr } func sockConn(timeout time.Duration) (net.Conn, error) { daemon := daemonHost() daemonUrl, err := url.Parse(daemon) if err != nil { return nil, fmt.Errorf("could not parse url %q: %v", daemon, err) } var c net.Conn switch daemonUrl.Scheme { case "unix": return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Path, timeout) case "tcp": return net.DialTimeout(daemonUrl.Scheme, daemonUrl.Host, timeout) default: return c, fmt.Errorf("unknown scheme %v (%s)", daemonUrl.Scheme, daemon) } } func sockRequest(method, endpoint string, data interface{}) (int, []byte, error) { jsonData := bytes.NewBuffer(nil) if err := json.NewEncoder(jsonData).Encode(data); err != nil { return -1, nil, err } res, body, err := sockRequestRaw(method, endpoint, jsonData, "application/json") if err != nil { b, _ := ioutil.ReadAll(body) return -1, b, err } var b []byte b, err = readBody(body) return res.StatusCode, b, err } func sockRequestRaw(method, endpoint string, data io.Reader, ct string) (*http.Response, io.ReadCloser, error) { c, err := sockConn(time.Duration(10 * time.Second)) if err != nil { return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err) } client := httputil.NewClientConn(c, nil) req, err := http.NewRequest(method, endpoint, data) if err != nil { client.Close() return nil, nil, fmt.Errorf("could not create new request: %v", err) } if ct != "" { req.Header.Set("Content-Type", ct) } resp, err := client.Do(req) if err != nil { client.Close() return nil, nil, fmt.Errorf("could not perform request: %v", err) } body := ioutils.NewReadCloserWrapper(resp.Body, func() error { defer resp.Body.Close() return client.Close() }) return resp, body, nil } func readBody(b io.ReadCloser) ([]byte, error) { defer b.Close() return ioutil.ReadAll(b) } func deleteContainer(container string) error { container = strings.TrimSpace(strings.Replace(container, "\n", " ", -1)) rmArgs := strings.Split(fmt.Sprintf("rm -fv %v", container), " ") exitCode, err := runCommand(exec.Command(dockerBinary, rmArgs...)) // set error manually if not set if exitCode != 0 && err == nil { err = fmt.Errorf("failed to remove container: `docker rm` exit is non-zero") } return err } func getAllContainers() (string, error) { getContainersCmd := exec.Command(dockerBinary, "ps", "-q", "-a") out, exitCode, err := runCommandWithOutput(getContainersCmd) if exitCode != 0 && err == nil { err = fmt.Errorf("failed to get a list of containers: %v\n", out) } return out, err } func deleteAllContainers() error { containers, err := getAllContainers() if err != nil { fmt.Println(containers) return err } if err = deleteContainer(containers); err != nil { return err } return nil } var protectedImages = map[string]struct{}{} func init() { out, err := exec.Command(dockerBinary, "images").CombinedOutput() if err != nil { panic(err) } lines := strings.Split(string(out), "\n")[1:] for _, l := range lines { if l == "" { continue } fields := strings.Fields(l) imgTag := fields[0] + ":" + fields[1] // just for case if we have dangling images in tested daemon if imgTag != ":" { protectedImages[imgTag] = struct{}{} } } } func deleteAllImages() error { out, err := exec.Command(dockerBinary, "images").CombinedOutput() if err != nil { return err } lines := strings.Split(string(out), "\n")[1:] var imgs []string for _, l := range lines { if l == "" { continue } fields := strings.Fields(l) imgTag := fields[0] + ":" + fields[1] if _, ok := protectedImages[imgTag]; !ok { if fields[0] == "" { imgs = append(imgs, fields[2]) continue } imgs = append(imgs, imgTag) } } if len(imgs) == 0 { return nil } args := append([]string{"rmi", "-f"}, imgs...) if err := exec.Command(dockerBinary, args...).Run(); err != nil { return err } return nil } func getPausedContainers() (string, error) { getPausedContainersCmd := exec.Command(dockerBinary, "ps", "-f", "status=paused", "-q", "-a") out, exitCode, err := runCommandWithOutput(getPausedContainersCmd) if exitCode != 0 && err == nil { err = fmt.Errorf("failed to get a list of paused containers: %v\n", out) } return out, err } func getSliceOfPausedContainers() ([]string, error) { out, err := getPausedContainers() if err == nil { if len(out) == 0 { return nil, err } slice := strings.Split(strings.TrimSpace(out), "\n") return slice, err } return []string{out}, err } func unpauseContainer(container string) error { unpauseCmd := exec.Command(dockerBinary, "unpause", container) exitCode, err := runCommand(unpauseCmd) if exitCode != 0 && err == nil { err = fmt.Errorf("failed to unpause container") } return nil } func unpauseAllContainers() error { containers, err := getPausedContainers() if err != nil { fmt.Println(containers) return err } containers = strings.Replace(containers, "\n", " ", -1) containers = strings.Trim(containers, " ") containerList := strings.Split(containers, " ") for _, value := range containerList { if err = unpauseContainer(value); err != nil { return err } } return nil } func deleteImages(images ...string) error { args := []string{"rmi", "-f"} args = append(args, images...) rmiCmd := exec.Command(dockerBinary, args...) exitCode, err := runCommand(rmiCmd) // set error manually if not set if exitCode != 0 && err == nil { err = fmt.Errorf("failed to remove image: `docker rmi` exit is non-zero") } return err } func imageExists(image string) error { inspectCmd := exec.Command(dockerBinary, "inspect", image) exitCode, err := runCommand(inspectCmd) if exitCode != 0 && err == nil { err = fmt.Errorf("couldn't find image %q", image) } return err } func pullImageIfNotExist(image string) (err error) { if err := imageExists(image); err != nil { pullCmd := exec.Command(dockerBinary, "pull", image) _, exitCode, err := runCommandWithOutput(pullCmd) if err != nil || exitCode != 0 { err = fmt.Errorf("image %q wasn't found locally and it couldn't be pulled: %s", image, err) } } return } func dockerCmdWithError(c *check.C, args ...string) (string, int, error) { return runCommandWithOutput(exec.Command(dockerBinary, args...)) } func dockerCmdWithStdoutStderr(c *check.C, args ...string) (string, string, int) { stdout, stderr, status, err := runCommandWithStdoutStderr(exec.Command(dockerBinary, args...)) c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(args, " "), stderr, err)) return stdout, stderr, status } func dockerCmd(c *check.C, args ...string) (string, int) { out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...)) c.Assert(err, check.IsNil, check.Commentf("%q failed with errors: %s, %v", strings.Join(args, " "), out, err)) return out, status } // execute a docker command with a timeout func dockerCmdWithTimeout(timeout time.Duration, args ...string) (string, int, error) { out, status, err := runCommandWithOutputAndTimeout(exec.Command(dockerBinary, args...), timeout) if err != nil { return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out) } return out, status, err } // execute a docker command in a directory func dockerCmdInDir(c *check.C, path string, args ...string) (string, int, error) { dockerCommand := exec.Command(dockerBinary, args...) dockerCommand.Dir = path out, status, err := runCommandWithOutput(dockerCommand) if err != nil { return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out) } return out, status, err } // execute a docker command in a directory with a timeout func dockerCmdInDirWithTimeout(timeout time.Duration, path string, args ...string) (string, int, error) { dockerCommand := exec.Command(dockerBinary, args...) dockerCommand.Dir = path out, status, err := runCommandWithOutputAndTimeout(dockerCommand, timeout) if err != nil { return out, status, fmt.Errorf("%q failed with errors: %v : %q)", strings.Join(args, " "), err, out) } return out, status, err } func findContainerIP(c *check.C, id string, vargs ...string) string { args := append(vargs, "inspect", "--format='{{ .NetworkSettings.IPAddress }}'", id) cmd := exec.Command(dockerBinary, args...) out, _, err := runCommandWithOutput(cmd) if err != nil { c.Fatal(err, out) } return strings.Trim(out, " \r\n'") } func (d *Daemon) findContainerIP(id string) string { return findContainerIP(d.c, id, "--host", d.sock()) } func getContainerCount() (int, error) { const containers = "Containers:" cmd := exec.Command(dockerBinary, "info") out, _, err := runCommandWithOutput(cmd) if err != nil { return 0, err } lines := strings.Split(out, "\n") for _, line := range lines { if strings.Contains(line, containers) { output := strings.TrimSpace(line) output = strings.TrimLeft(output, containers) output = strings.Trim(output, " ") containerCount, err := strconv.Atoi(output) if err != nil { return 0, err } return containerCount, nil } } return 0, fmt.Errorf("couldn't find the Container count in the output") } type FakeContext struct { Dir string } func (f *FakeContext) Add(file, content string) error { return f.addFile(file, []byte(content)) } func (f *FakeContext) addFile(file string, content []byte) error { filepath := path.Join(f.Dir, file) dirpath := path.Dir(filepath) if dirpath != "." { if err := os.MkdirAll(dirpath, 0755); err != nil { return err } } return ioutil.WriteFile(filepath, content, 0644) } func (f *FakeContext) Delete(file string) error { filepath := path.Join(f.Dir, file) return os.RemoveAll(filepath) } func (f *FakeContext) Close() error { return os.RemoveAll(f.Dir) } func fakeContextFromNewTempDir() (*FakeContext, error) { tmp, err := ioutil.TempDir("", "fake-context") if err != nil { return nil, err } if err := os.Chmod(tmp, 0755); err != nil { return nil, err } return fakeContextFromDir(tmp), nil } func fakeContextFromDir(dir string) *FakeContext { return &FakeContext{dir} } func fakeContextWithFiles(files map[string]string) (*FakeContext, error) { ctx, err := fakeContextFromNewTempDir() if err != nil { return nil, err } for file, content := range files { if err := ctx.Add(file, content); err != nil { ctx.Close() return nil, err } } return ctx, nil } func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error { if err := ctx.Add("Dockerfile", dockerfile); err != nil { ctx.Close() return err } return nil } func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) { ctx, err := fakeContextWithFiles(files) if err != nil { return nil, err } if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil { return nil, err } return ctx, nil } // FakeStorage is a static file server. It might be running locally or remotely // on test host. type FakeStorage interface { Close() error URL() string CtxDir() string } func fakeBinaryStorage(archives map[string]*bytes.Buffer) (FakeStorage, error) { ctx, err := fakeContextFromNewTempDir() if err != nil { return nil, err } for name, content := range archives { if err := ctx.addFile(name, content.Bytes()); err != nil { return nil, err } } return fakeStorageWithContext(ctx) } // fakeStorage returns either a local or remote (at daemon machine) file server func fakeStorage(files map[string]string) (FakeStorage, error) { ctx, err := fakeContextWithFiles(files) if err != nil { return nil, err } return fakeStorageWithContext(ctx) } // fakeStorageWithContext returns either a local or remote (at daemon machine) file server func fakeStorageWithContext(ctx *FakeContext) (FakeStorage, error) { if isLocalDaemon { return newLocalFakeStorage(ctx) } return newRemoteFileServer(ctx) } // localFileStorage is a file storage on the running machine type localFileStorage struct { *FakeContext *httptest.Server } func (s *localFileStorage) URL() string { return s.Server.URL } func (s *localFileStorage) CtxDir() string { return s.FakeContext.Dir } func (s *localFileStorage) Close() error { defer s.Server.Close() return s.FakeContext.Close() } func newLocalFakeStorage(ctx *FakeContext) (*localFileStorage, error) { handler := http.FileServer(http.Dir(ctx.Dir)) server := httptest.NewServer(handler) return &localFileStorage{ FakeContext: ctx, Server: server, }, nil } // remoteFileServer is a containerized static file server started on the remote // testing machine to be used in URL-accepting docker build functionality. type remoteFileServer struct { host string // hostname/port web server is listening to on docker host e.g. 0.0.0.0:43712 container string image string ctx *FakeContext } func (f *remoteFileServer) URL() string { u := url.URL{ Scheme: "http", Host: f.host} return u.String() } func (f *remoteFileServer) CtxDir() string { return f.ctx.Dir } func (f *remoteFileServer) Close() error { defer func() { if f.ctx != nil { f.ctx.Close() } if f.image != "" { deleteImages(f.image) } }() if f.container == "" { return nil } return deleteContainer(f.container) } func newRemoteFileServer(ctx *FakeContext) (*remoteFileServer, error) { var ( image = fmt.Sprintf("fileserver-img-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10))) container = fmt.Sprintf("fileserver-cnt-%s", strings.ToLower(stringutils.GenerateRandomAlphaOnlyString(10))) ) // Build the image if err := fakeContextAddDockerfile(ctx, `FROM httpserver COPY . /static`); err != nil { return nil, fmt.Errorf("Cannot add Dockerfile to context: %v", err) } if _, err := buildImageFromContext(image, ctx, false); err != nil { return nil, fmt.Errorf("failed building file storage container image: %v", err) } // Start the container runCmd := exec.Command(dockerBinary, "run", "-d", "-P", "--name", container, image) if out, ec, err := runCommandWithOutput(runCmd); err != nil { return nil, fmt.Errorf("failed to start file storage container. ec=%v\nout=%s\nerr=%v", ec, out, err) } // Find out the system assigned port out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "port", container, "80/tcp")) if err != nil { return nil, fmt.Errorf("failed to find container port: err=%v\nout=%s", err, out) } return &remoteFileServer{ container: container, image: image, host: strings.Trim(out, "\n"), ctx: ctx}, nil } func inspectFieldAndMarshall(name, field string, output interface{}) error { str, err := inspectFieldJSON(name, field) if err != nil { return err } return json.Unmarshal([]byte(str), output) } func inspectFilter(name, filter string) (string, error) { format := fmt.Sprintf("{{%s}}", filter) inspectCmd := exec.Command(dockerBinary, "inspect", "-f", format, name) out, exitCode, err := runCommandWithOutput(inspectCmd) if err != nil || exitCode != 0 { return "", fmt.Errorf("failed to inspect container %s: %s", name, out) } return strings.TrimSpace(out), nil } func inspectField(name, field string) (string, error) { return inspectFilter(name, fmt.Sprintf(".%s", field)) } func inspectFieldJSON(name, field string) (string, error) { return inspectFilter(name, fmt.Sprintf("json .%s", field)) } func inspectFieldMap(name, path, field string) (string, error) { return inspectFilter(name, fmt.Sprintf("index .%s %q", path, field)) } func inspectMountSourceField(name, destination string) (string, error) { m, err := inspectMountPoint(name, destination) if err != nil { return "", err } return m.Source, nil } func inspectMountPoint(name, destination string) (types.MountPoint, error) { out, err := inspectFieldJSON(name, "Mounts") if err != nil { return types.MountPoint{}, err } return inspectMountPointJSON(out, destination) } var mountNotFound = errors.New("mount point not found") func inspectMountPointJSON(j, destination string) (types.MountPoint, error) { var mp []types.MountPoint if err := unmarshalJSON([]byte(j), &mp); err != nil { return types.MountPoint{}, err } var m *types.MountPoint for _, c := range mp { if c.Destination == destination { m = &c break } } if m == nil { return types.MountPoint{}, mountNotFound } return *m, nil } func getIDByName(name string) (string, error) { return inspectField(name, "Id") } // getContainerState returns the exit code of the container // and true if it's running // the exit code should be ignored if it's running func getContainerState(c *check.C, id string) (int, bool, error) { var ( exitStatus int running bool ) out, exitCode := dockerCmd(c, "inspect", "--format={{.State.Running}} {{.State.ExitCode}}", id) if exitCode != 0 { return 0, false, fmt.Errorf("%q doesn't exist: %s", id, out) } out = strings.Trim(out, "\n") splitOutput := strings.Split(out, " ") if len(splitOutput) != 2 { return 0, false, fmt.Errorf("failed to get container state: output is broken") } if splitOutput[0] == "true" { running = true } if n, err := strconv.Atoi(splitOutput[1]); err == nil { exitStatus = n } else { return 0, false, fmt.Errorf("failed to get container state: couldn't parse integer") } return exitStatus, running, nil } func buildImageWithOut(name, dockerfile string, useCache bool) (string, string, error) { args := []string{"build", "-t", name} if !useCache { args = append(args, "--no-cache") } args = append(args, "-") buildCmd := exec.Command(dockerBinary, args...) buildCmd.Stdin = strings.NewReader(dockerfile) out, exitCode, err := runCommandWithOutput(buildCmd) if err != nil || exitCode != 0 { return "", out, fmt.Errorf("failed to build the image: %s", out) } id, err := getIDByName(name) if err != nil { return "", out, err } return id, out, nil } func buildImageWithStdoutStderr(name, dockerfile string, useCache bool) (string, string, string, error) { args := []string{"build", "-t", name} if !useCache { args = append(args, "--no-cache") } args = append(args, "-") buildCmd := exec.Command(dockerBinary, args...) buildCmd.Stdin = strings.NewReader(dockerfile) stdout, stderr, exitCode, err := runCommandWithStdoutStderr(buildCmd) if err != nil || exitCode != 0 { return "", stdout, stderr, fmt.Errorf("failed to build the image: %s", stdout) } id, err := getIDByName(name) if err != nil { return "", stdout, stderr, err } return id, stdout, stderr, nil } func buildImage(name, dockerfile string, useCache bool) (string, error) { id, _, err := buildImageWithOut(name, dockerfile, useCache) return id, err } func buildImageFromContext(name string, ctx *FakeContext, useCache bool) (string, error) { args := []string{"build", "-t", name} if !useCache { args = append(args, "--no-cache") } args = append(args, ".") buildCmd := exec.Command(dockerBinary, args...) buildCmd.Dir = ctx.Dir out, exitCode, err := runCommandWithOutput(buildCmd) if err != nil || exitCode != 0 { return "", fmt.Errorf("failed to build the image: %s", out) } return getIDByName(name) } func buildImageFromPath(name, path string, useCache bool) (string, error) { args := []string{"build", "-t", name} if !useCache { args = append(args, "--no-cache") } args = append(args, path) buildCmd := exec.Command(dockerBinary, args...) out, exitCode, err := runCommandWithOutput(buildCmd) if err != nil || exitCode != 0 { return "", fmt.Errorf("failed to build the image: %s", out) } return getIDByName(name) } type GitServer interface { URL() string Close() error } type localGitServer struct { *httptest.Server } func (r *localGitServer) Close() error { r.Server.Close() return nil } func (r *localGitServer) URL() string { return r.Server.URL } type FakeGIT struct { root string server GitServer RepoURL string } func (g *FakeGIT) Close() { g.server.Close() os.RemoveAll(g.root) } func fakeGIT(name string, files map[string]string, enforceLocalServer bool) (*FakeGIT, error) { ctx, err := fakeContextWithFiles(files) if err != nil { return nil, err } defer ctx.Close() curdir, err := os.Getwd() if err != nil { return nil, err } defer os.Chdir(curdir) if output, err := exec.Command("git", "init", ctx.Dir).CombinedOutput(); err != nil { return nil, fmt.Errorf("error trying to init repo: %s (%s)", err, output) } err = os.Chdir(ctx.Dir) if err != nil { return nil, err } if output, err := exec.Command("git", "config", "user.name", "Fake User").CombinedOutput(); err != nil { return nil, fmt.Errorf("error trying to set 'user.name': %s (%s)", err, output) } if output, err := exec.Command("git", "config", "user.email", "fake.user@example.com").CombinedOutput(); err != nil { return nil, fmt.Errorf("error trying to set 'user.email': %s (%s)", err, output) } if output, err := exec.Command("git", "add", "*").CombinedOutput(); err != nil { return nil, fmt.Errorf("error trying to add files to repo: %s (%s)", err, output) } if output, err := exec.Command("git", "commit", "-a", "-m", "Initial commit").CombinedOutput(); err != nil { return nil, fmt.Errorf("error trying to commit to repo: %s (%s)", err, output) } root, err := ioutil.TempDir("", "docker-test-git-repo") if err != nil { return nil, err } repoPath := filepath.Join(root, name+".git") if output, err := exec.Command("git", "clone", "--bare", ctx.Dir, repoPath).CombinedOutput(); err != nil { os.RemoveAll(root) return nil, fmt.Errorf("error trying to clone --bare: %s (%s)", err, output) } err = os.Chdir(repoPath) if err != nil { os.RemoveAll(root) return nil, err } if output, err := exec.Command("git", "update-server-info").CombinedOutput(); err != nil { os.RemoveAll(root) return nil, fmt.Errorf("error trying to git update-server-info: %s (%s)", err, output) } err = os.Chdir(curdir) if err != nil { os.RemoveAll(root) return nil, err } var server GitServer if !enforceLocalServer { // use fakeStorage server, which might be local or remote (at test daemon) server, err = fakeStorageWithContext(fakeContextFromDir(root)) if err != nil { return nil, fmt.Errorf("cannot start fake storage: %v", err) } } else { // always start a local http server on CLI test machin httpServer := httptest.NewServer(http.FileServer(http.Dir(root))) server = &localGitServer{httpServer} } return &FakeGIT{ root: root, server: server, RepoURL: fmt.Sprintf("%s/%s.git", server.URL(), name), }, nil } // Write `content` to the file at path `dst`, creating it if necessary, // as well as any missing directories. // The file is truncated if it already exists. // Call c.Fatal() at the first error. func writeFile(dst, content string, c *check.C) { // Create subdirectories if necessary if err := os.MkdirAll(path.Dir(dst), 0700); err != nil && !os.IsExist(err) { c.Fatal(err) } f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700) if err != nil { c.Fatal(err) } defer f.Close() // Write content (truncate if it exists) if _, err := io.Copy(f, strings.NewReader(content)); err != nil { c.Fatal(err) } } // Return the contents of file at path `src`. // Call c.Fatal() at the first error (including if the file doesn't exist) func readFile(src string, c *check.C) (content string) { data, err := ioutil.ReadFile(src) if err != nil { c.Fatal(err) } return string(data) } func containerStorageFile(containerId, basename string) string { return filepath.Join("/var/lib/docker/containers", containerId, basename) } // docker commands that use this function must be run with the '-d' switch. func runCommandAndReadContainerFile(filename string, cmd *exec.Cmd) ([]byte, error) { out, _, err := runCommandWithOutput(cmd) if err != nil { return nil, fmt.Errorf("%v: %q", err, out) } time.Sleep(1 * time.Second) contID := strings.TrimSpace(out) return readContainerFile(contID, filename) } func readContainerFile(containerId, filename string) ([]byte, error) { f, err := os.Open(containerStorageFile(containerId, filename)) if err != nil { return nil, err } defer f.Close() content, err := ioutil.ReadAll(f) if err != nil { return nil, err } return content, nil } func readContainerFileWithExec(containerId, filename string) ([]byte, error) { out, _, err := runCommandWithOutput(exec.Command(dockerBinary, "exec", containerId, "cat", filename)) return []byte(out), err } // daemonTime provides the current time on the daemon host func daemonTime(c *check.C) time.Time { if isLocalDaemon { return time.Now() } status, body, err := sockRequest("GET", "/info", nil) c.Assert(status, check.Equals, http.StatusOK) c.Assert(err, check.IsNil) type infoJSON struct { SystemTime string } var info infoJSON if err = json.Unmarshal(body, &info); err != nil { c.Fatalf("unable to unmarshal /info response: %v", err) } dt, err := time.Parse(time.RFC3339Nano, info.SystemTime) if err != nil { c.Fatal(err) } return dt } func setupRegistry(c *check.C) *testRegistryV2 { testRequires(c, RegistryHosting) reg, err := newTestRegistryV2(c) if err != nil { c.Fatal(err) } // Wait for registry to be ready to serve requests. for i := 0; i != 5; i++ { if err = reg.Ping(); err == nil { break } time.Sleep(100 * time.Millisecond) } if err != nil { c.Fatal("Timeout waiting for test registry to become available") } return reg } // appendBaseEnv appends the minimum set of environment variables to exec the // docker cli binary for testing with correct configuration to the given env // list. func appendBaseEnv(env []string) []string { preserveList := []string{ // preserve remote test host "DOCKER_HOST", // windows: requires preserving SystemRoot, otherwise dial tcp fails // with "GetAddrInfoW: A non-recoverable error occurred during a database lookup." "SystemRoot", } for _, key := range preserveList { if val := os.Getenv(key); val != "" { env = append(env, fmt.Sprintf("%s=%s", key, val)) } } return env } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/ca.pem ================================================ -----BEGIN CERTIFICATE----- MIID0TCCAzqgAwIBAgIJAP2r7GqEJwSnMA0GCSqGSIb3DQEBBQUAMIGiMQswCQYD VQQGEwJVUzELMAkGA1UECBMCQ0ExFTATBgNVBAcTDFNhbkZyYW5jaXNjbzEVMBMG A1UEChMMRm9ydC1GdW5zdG9uMREwDwYDVQQLEwhjaGFuZ2VtZTERMA8GA1UEAxMI Y2hhbmdlbWUxETAPBgNVBCkTCGNoYW5nZW1lMR8wHQYJKoZIhvcNAQkBFhBtYWls QGhvc3QuZG9tYWluMB4XDTEzMTIwMzE2NTYzMFoXDTIzMTIwMTE2NTYzMFowgaIx CzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEVMBMGA1UEBxMMU2FuRnJhbmNpc2Nv MRUwEwYDVQQKEwxGb3J0LUZ1bnN0b24xETAPBgNVBAsTCGNoYW5nZW1lMREwDwYD VQQDEwhjaGFuZ2VtZTERMA8GA1UEKRMIY2hhbmdlbWUxHzAdBgkqhkiG9w0BCQEW EG1haWxAaG9zdC5kb21haW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALAn 0xDw+5y7ZptQacq66pUhRu82JP2WU6IDgo5QUtNU6/CX5PwQATe/OnYTZQFbksxp AU9boG0FCkgxfsgPYXEuZxVEGKI2fxfKHOZZI8mrkWmj6eWU/0cvCjGVc9rTITP5 sNQvg+hORyVDdNp2IdsbMJayiB3AQYMFx3vSDOMTAgMBAAGjggELMIIBBzAdBgNV HQ4EFgQUZu7DFz09q0QBa2+ymRm9qgK1NPswgdcGA1UdIwSBzzCBzIAUZu7DFz09 q0QBa2+ymRm9qgK1NPuhgaikgaUwgaIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJD QTEVMBMGA1UEBxMMU2FuRnJhbmNpc2NvMRUwEwYDVQQKEwxGb3J0LUZ1bnN0b24x ETAPBgNVBAsTCGNoYW5nZW1lMREwDwYDVQQDEwhjaGFuZ2VtZTERMA8GA1UEKRMI Y2hhbmdlbWUxHzAdBgkqhkiG9w0BCQEWEG1haWxAaG9zdC5kb21haW6CCQD9q+xq hCcEpzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAF8fJKKM+/oOdnNi zEd0M1+PmZOyqvjYQn/2ZR8UHH6Imgc/OPQKZXf0bVE1Txc/DaUNn9Isd1SuCuaE ic3vAIYYU7PmgeNN6vwec48V96T7jr+GAi6AVMhQEc2hHCfVtx11Xx+x6aHDZzJt Zxtf5lL6KSO9Y+EFwM+rju6hm5hW -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/client-cert.pem ================================================ Certificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: sha1WithRSAEncryption Issuer: C=US, ST=CA, L=SanFrancisco, O=Fort-Funston, OU=changeme, CN=changeme/name=changeme/emailAddress=mail@host.domain Validity Not Before: Dec 4 14:17:54 2013 GMT Not After : Dec 2 14:17:54 2023 GMT Subject: C=US, ST=CA, L=SanFrancisco, O=Fort-Funston, OU=changeme, CN=client/name=changeme/emailAddress=mail@host.domain Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:ca:c9:05:d0:09:4e:3e:a4:fc:d5:14:f4:a5:e8: 34:d3:6b:51:e3:f3:62:ea:a1:f0:e8:ed:c4:2a:bc: f0:4f:ca:07:df:e3:88:fa:f4:21:99:35:0e:3d:ea: b0:86:e7:c4:d2:8a:83:2b:42:b8:ec:a3:99:62:70: 81:46:cc:fc:a5:1d:d2:63:e8:eb:07:25:9a:e2:25: 6d:11:56:f2:1a:51:a1:b6:3e:1c:57:32:e9:7b:2c: aa:1b:cc:97:2d:89:2d:b1:c9:5e:35:28:4d:7c:fa: 65:31:3e:f7:70:dd:6e:0b:3c:58:af:a8:2e:24:c0: 7e:4e:78:7d:0a:9e:8f:42:43 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: Easy-RSA Generated Certificate X509v3 Subject Key Identifier: DE:42:EF:2D:98:A3:6C:A8:AA:E0:8C:71:2C:9D:64:23:A9:E2:7E:81 X509v3 Authority Key Identifier: keyid:66:EE:C3:17:3D:3D:AB:44:01:6B:6F:B2:99:19:BD:AA:02:B5:34:FB DirName:/C=US/ST=CA/L=SanFrancisco/O=Fort-Funston/OU=changeme/CN=changeme/name=changeme/emailAddress=mail@host.domain serial:FD:AB:EC:6A:84:27:04:A7 X509v3 Extended Key Usage: TLS Web Client Authentication X509v3 Key Usage: Digital Signature Signature Algorithm: sha1WithRSAEncryption 1c:44:26:ea:e1:66:25:cb:e4:8e:57:1c:f6:b9:17:22:62:40: 12:90:8f:3b:b2:61:7a:54:94:8f:b1:20:0b:bf:a3:51:e3:fa: 1c:a1:be:92:3a:d0:76:44:c0:57:83:ab:6a:e4:1a:45:49:a4: af:39:0d:60:32:fc:3a:be:d7:fb:5d:99:7a:1f:87:e7:d5:ab: 84:a2:5e:90:d8:bf:fa:89:6d:32:26:02:5e:31:35:68:7f:31: f5:6b:51:46:bc:af:70:ed:5a:09:7d:ec:b2:48:4f:fe:c5:2f: 56:04:ad:f6:c1:d2:2a:e4:6a:c4:87:fe:08:35:c5:38:cb:5e: 4a:c4 -----BEGIN CERTIFICATE----- MIIEFTCCA36gAwIBAgIBAzANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMCVVMx CzAJBgNVBAgTAkNBMRUwEwYDVQQHEwxTYW5GcmFuY2lzY28xFTATBgNVBAoTDEZv cnQtRnVuc3RvbjERMA8GA1UECxMIY2hhbmdlbWUxETAPBgNVBAMTCGNoYW5nZW1l MREwDwYDVQQpEwhjaGFuZ2VtZTEfMB0GCSqGSIb3DQEJARYQbWFpbEBob3N0LmRv bWFpbjAeFw0xMzEyMDQxNDE3NTRaFw0yMzEyMDIxNDE3NTRaMIGgMQswCQYDVQQG EwJVUzELMAkGA1UECBMCQ0ExFTATBgNVBAcTDFNhbkZyYW5jaXNjbzEVMBMGA1UE ChMMRm9ydC1GdW5zdG9uMREwDwYDVQQLEwhjaGFuZ2VtZTEPMA0GA1UEAxMGY2xp ZW50MREwDwYDVQQpEwhjaGFuZ2VtZTEfMB0GCSqGSIb3DQEJARYQbWFpbEBob3N0 LmRvbWFpbjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAyskF0AlOPqT81RT0 peg002tR4/Ni6qHw6O3EKrzwT8oH3+OI+vQhmTUOPeqwhufE0oqDK0K47KOZYnCB Rsz8pR3SY+jrByWa4iVtEVbyGlGhtj4cVzLpeyyqG8yXLYktscleNShNfPplMT73 cN1uCzxYr6guJMB+Tnh9Cp6PQkMCAwEAAaOCAVkwggFVMAkGA1UdEwQCMAAwLQYJ YIZIAYb4QgENBCAWHkVhc3ktUlNBIEdlbmVyYXRlZCBDZXJ0aWZpY2F0ZTAdBgNV HQ4EFgQU3kLvLZijbKiq4IxxLJ1kI6nifoEwgdcGA1UdIwSBzzCBzIAUZu7DFz09 q0QBa2+ymRm9qgK1NPuhgaikgaUwgaIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJD QTEVMBMGA1UEBxMMU2FuRnJhbmNpc2NvMRUwEwYDVQQKEwxGb3J0LUZ1bnN0b24x ETAPBgNVBAsTCGNoYW5nZW1lMREwDwYDVQQDEwhjaGFuZ2VtZTERMA8GA1UEKRMI Y2hhbmdlbWUxHzAdBgkqhkiG9w0BCQEWEG1haWxAaG9zdC5kb21haW6CCQD9q+xq hCcEpzATBgNVHSUEDDAKBggrBgEFBQcDAjALBgNVHQ8EBAMCB4AwDQYJKoZIhvcN AQEFBQADgYEAHEQm6uFmJcvkjlcc9rkXImJAEpCPO7JhelSUj7EgC7+jUeP6HKG+ kjrQdkTAV4OrauQaRUmkrzkNYDL8Or7X+12Zeh+H59WrhKJekNi/+oltMiYCXjE1 aH8x9WtRRryvcO1aCX3sskhP/sUvVgSt9sHSKuRqxIf+CDXFOMteSsQ= -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/client-key.pem ================================================ -----BEGIN PRIVATE KEY----- MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMrJBdAJTj6k/NUU 9KXoNNNrUePzYuqh8OjtxCq88E/KB9/jiPr0IZk1Dj3qsIbnxNKKgytCuOyjmWJw gUbM/KUd0mPo6wclmuIlbRFW8hpRobY+HFcy6XssqhvMly2JLbHJXjUoTXz6ZTE+ 93Ddbgs8WK+oLiTAfk54fQqej0JDAgMBAAECgYBOFEzKp2qbMEexe9ofL2N3rDDh xkrl8OijpzkLA6i78BxMFn4dsnZlWUpciMrjhsYAExkiRRSS+QMMJimAq1jzQqc3 FAQV2XGYwkd0cUn7iZGvfNnEPysjsfyYQM+m+sT0ATj4BZjVShC6kkSjTdm1leLN OSvcHdcu3Xxg9ufF0QJBAPYdnNt5sIndt2WECePuRVi+uF4mlxTobFY0fjn26yhC 4RsnhhD3Vldygo9gvnkwrAZYaALGSPBewes2InxvjA8CQQDS7erKiNXpwoqz5XiU SVEsIIVTdWzBjGbIqMOu/hUwM5FK4j6JTBks0aTGMyh0YV9L1EzM0X79J29JahCe iQKNAkBKNMOGqTpBV0hko1sYDk96YobUXG5RL4L6uvkUIQ7mJMQam+AgXXL7Ctuy v0iu4a38e8tgisiTMP7nHHtpaXihAkAOiN54/lzfMsykANgCP9scE1GcoqbP34Dl qttxH4kOPT9xzY1JoLjLYdbc4YGUI3GRpBt2sajygNkmUey7P+2xAkBBsVCZFvTw qHvOpPS2kX5ml5xoc/QAHK9N7kR+X7XFYx82RTVSqJEK4lPb+aEWn+CjiIewO4Q5 ksDFuNxAzbhl -----END PRIVATE KEY----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/client-rogue-cert.pem ================================================ Certificate: Data: Version: 3 (0x2) Serial Number: 2 (0x2) Signature Algorithm: sha1WithRSAEncryption Issuer: C=US, ST=CA, L=SanFrancisco, O=Evil Inc, OU=changeme, CN=changeme/name=changeme/emailAddress=mail@host.domain Validity Not Before: Feb 24 17:54:59 2014 GMT Not After : Feb 22 17:54:59 2024 GMT Subject: C=US, ST=CA, L=SanFrancisco, O=Fort-Funston, OU=changeme, CN=client/name=changeme/emailAddress=mail@host.domain Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:e8:e2:2c:b8:d4:db:89:50:4f:47:1e:68:db:f7: e4:cc:47:41:63:75:03:37:50:7a:a8:4d:27:36:d5: 15:01:08:b6:cf:56:f7:56:6d:3d:f9:e2:8d:1a:5d: bf:a0:24:5e:07:55:8e:d0:dc:f1:fa:19:87:1d:d6: b6:58:82:2e:ba:69:6d:e9:d9:c8:16:0d:1d:59:7f: f4:8e:58:10:01:3d:21:14:16:3c:ec:cd:8c:b7:0e: e6:7b:77:b4:f9:90:a5:17:01:bb:84:c6:b2:12:87: 70:eb:9f:6d:4f:d0:68:8b:96:c0:e7:0b:51:b4:9d: 1d:7b:6c:7b:be:89:6b:88:8b Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Comment: Easy-RSA Generated Certificate X509v3 Subject Key Identifier: 9E:F8:49:D0:A2:76:30:5C:AB:2B:8A:B5:8D:C6:45:1F:A7:F8:CF:85 X509v3 Authority Key Identifier: keyid:DC:A5:F1:76:DB:4E:CD:8E:EF:B1:23:56:1D:92:80:99:74:3B:EA:6F DirName:/C=US/ST=CA/L=SanFrancisco/O=Evil Inc/OU=changeme/CN=changeme/name=changeme/emailAddress=mail@host.domain serial:E7:21:1E:18:41:1B:96:83 X509v3 Extended Key Usage: TLS Web Client Authentication X509v3 Key Usage: Digital Signature Signature Algorithm: sha1WithRSAEncryption 48:76:c0:18:fa:0a:ee:4e:1a:ec:02:9d:d4:83:ca:94:54:a1: 3f:51:2f:3e:4b:95:c3:42:9b:71:a0:4b:d9:af:47:23:b9:1c: fb:85:ba:76:e2:09:cb:65:bb:d2:7d:44:3d:4b:67:ba:80:83: be:a8:ed:c4:b9:ea:1a:1b:c7:59:3b:d9:5c:0d:46:d8:c9:92: cb:10:c5:f2:1a:38:a4:aa:07:2c:e3:84:16:79:c7:95:09:e3: 01:d2:15:a2:77:0b:8b:bf:94:04:e9:7f:c0:cd:e6:2e:64:cd: 1e:a3:32:ec:11:cc:62:ce:c7:4e:cd:ad:48:5c:b1:b8:e9:76: b3:f9 -----BEGIN CERTIFICATE----- MIIEDTCCA3agAwIBAgIBAjANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx CzAJBgNVBAgTAkNBMRUwEwYDVQQHEwxTYW5GcmFuY2lzY28xETAPBgNVBAoTCEV2 aWwgSW5jMREwDwYDVQQLEwhjaGFuZ2VtZTERMA8GA1UEAxMIY2hhbmdlbWUxETAP BgNVBCkTCGNoYW5nZW1lMR8wHQYJKoZIhvcNAQkBFhBtYWlsQGhvc3QuZG9tYWlu MB4XDTE0MDIyNDE3NTQ1OVoXDTI0MDIyMjE3NTQ1OVowgaAxCzAJBgNVBAYTAlVT MQswCQYDVQQIEwJDQTEVMBMGA1UEBxMMU2FuRnJhbmNpc2NvMRUwEwYDVQQKEwxG b3J0LUZ1bnN0b24xETAPBgNVBAsTCGNoYW5nZW1lMQ8wDQYDVQQDEwZjbGllbnQx ETAPBgNVBCkTCGNoYW5nZW1lMR8wHQYJKoZIhvcNAQkBFhBtYWlsQGhvc3QuZG9t YWluMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDo4iy41NuJUE9HHmjb9+TM R0FjdQM3UHqoTSc21RUBCLbPVvdWbT354o0aXb+gJF4HVY7Q3PH6GYcd1rZYgi66 aW3p2cgWDR1Zf/SOWBABPSEUFjzszYy3DuZ7d7T5kKUXAbuExrISh3Drn21P0GiL lsDnC1G0nR17bHu+iWuIiwIDAQABo4IBVTCCAVEwCQYDVR0TBAIwADAtBglghkgB hvhCAQ0EIBYeRWFzeS1SU0EgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQW BBSe+EnQonYwXKsrirWNxkUfp/jPhTCB0wYDVR0jBIHLMIHIgBTcpfF2207Nju+x I1YdkoCZdDvqb6GBpKSBoTCBnjELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkNBMRUw EwYDVQQHEwxTYW5GcmFuY2lzY28xETAPBgNVBAoTCEV2aWwgSW5jMREwDwYDVQQL EwhjaGFuZ2VtZTERMA8GA1UEAxMIY2hhbmdlbWUxETAPBgNVBCkTCGNoYW5nZW1l MR8wHQYJKoZIhvcNAQkBFhBtYWlsQGhvc3QuZG9tYWluggkA5yEeGEEbloMwEwYD VR0lBAwwCgYIKwYBBQUHAwIwCwYDVR0PBAQDAgeAMA0GCSqGSIb3DQEBBQUAA4GB AEh2wBj6Cu5OGuwCndSDypRUoT9RLz5LlcNCm3GgS9mvRyO5HPuFunbiCctlu9J9 RD1LZ7qAg76o7cS56hobx1k72VwNRtjJkssQxfIaOKSqByzjhBZ5x5UJ4wHSFaJ3 C4u/lATpf8DN5i5kzR6jMuwRzGLOx07NrUhcsbjpdrP5 -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/client-rogue-key.pem ================================================ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAOjiLLjU24lQT0ce aNv35MxHQWN1AzdQeqhNJzbVFQEIts9W91ZtPfnijRpdv6AkXgdVjtDc8foZhx3W tliCLrppbenZyBYNHVl/9I5YEAE9IRQWPOzNjLcO5nt3tPmQpRcBu4TGshKHcOuf bU/QaIuWwOcLUbSdHXtse76Ja4iLAgMBAAECgYADs+TmI2xCKKa6CL++D5jxrohZ nnionnz0xBVFh+nHlG3jqgxQsXf0yydXLfpn/2wHTdLxezHVuiYt0UYg7iD0CglW +IjcgMebzyjLeYqYOE5llPlMvhp2HoEMYJNb+7bRrZ1WCITbu+Su0w1cgA7Cs+Ej VlfvGzN+qqnDThRUYQJBAPY0sMWZJKly8QhUmUvmcXdPczzSOf6Mm7gc5LR6wzxd vW7syuqk50qjqVqFpN81vCV7GoDxRUWbTM9ftf7JGFkCQQDyJc/1RMygE2o+enU1 6UBxJyclXITEYtDn8aoEpLNc7RakP1WoPUKjZOnjkcoKcIkFNkSPeCfQujrb5f3F MkuDAkByAI/hzzmkpK5rFxEsjfX4Mve/L/DepyjrpaVY1IdWimlO1aJX6CeY7hNa 8QsYt/74s/nfvtg+lNyKIV1aLq9xAkB+WSSNgfyTeg3x08vc+Xxajmdqoz/TiQwg OoTQL3A3iK5LvZBgXLasszcnOycFE3srcQmNItEDpGiZ3QPxJTEpAkEA45EE9NMJ SA7EGWSFlbz4f4u4oBeiDiJRJbGGfAyVxZlpCWUjPpg9+swsWoFEOjnGYaChAMk5 nrOdMf15T6QF7Q== -----END PRIVATE KEY----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/server-cert.pem ================================================ Certificate: Data: Version: 3 (0x2) Serial Number: 4 (0x4) Signature Algorithm: sha1WithRSAEncryption Issuer: C=US, ST=CA, L=SanFrancisco, O=Fort-Funston, OU=changeme, CN=changeme/name=changeme/emailAddress=mail@host.domain Validity Not Before: Dec 4 15:01:20 2013 GMT Not After : Dec 2 15:01:20 2023 GMT Subject: C=US, ST=CA, L=SanFrancisco, O=Fort-Funston, OU=changeme, CN=*/name=changeme/emailAddress=mail@host.domain Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:c1:ff:7d:30:6f:64:4a:b1:92:b1:71:d1:c1:74: e2:1d:db:2d:11:24:e1:00:d4:00:ae:6f:c8:9e:ae: 67:b3:4a:bd:f7:e6:9e:57:6d:19:4c:3c:23:94:2d: 3d:d6:63:84:d8:fa:76:2b:38:12:c1:ed:20:9d:32: e0:e8:c2:bf:9a:77:70:04:3f:7f:ca:8c:2c:82:d6: 3d:25:5c:02:1a:4f:64:93:03:dd:9c:42:97:5e:09: 49:af:f0:c2:e1:30:08:0e:21:46:95:d1:13:59:c0: c8:76:be:94:0d:8b:43:67:21:33:b2:08:60:9d:76: a8:05:32:1e:f9:95:09:14:75 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Cert Type: SSL Server Netscape Comment: Easy-RSA Generated Server Certificate X509v3 Subject Key Identifier: 14:02:FD:FD:DD:13:38:E0:71:EA:D1:BE:C0:0E:89:1A:2D:B6:19:06 X509v3 Authority Key Identifier: keyid:66:EE:C3:17:3D:3D:AB:44:01:6B:6F:B2:99:19:BD:AA:02:B5:34:FB DirName:/C=US/ST=CA/L=SanFrancisco/O=Fort-Funston/OU=changeme/CN=changeme/name=changeme/emailAddress=mail@host.domain serial:FD:AB:EC:6A:84:27:04:A7 X509v3 Extended Key Usage: TLS Web Server Authentication X509v3 Key Usage: Digital Signature, Key Encipherment Signature Algorithm: sha1WithRSAEncryption 40:0f:10:39:c4:b7:0f:0d:2f:bf:d2:16:cc:8e:d3:9a:fb:8b: ce:4b:7b:0d:48:77:ce:f1:fe:d5:8f:ea:b1:71:ed:49:1d:9f: 23:3a:16:d4:70:7c:c5:29:bf:e4:90:34:d0:f0:00:24:f4:e4: df:2c:c3:83:01:66:61:c9:a8:ab:29:e7:98:6d:27:89:4a:76: c9:2e:19:8e:fe:6e:d5:f8:99:11:0e:97:67:4b:34:e3:1e:e3: 9f:35:00:a5:32:f9:b5:2c:f2:e0:c5:2e:cc:81:bd:18:dd:5c: 12:c8:6b:fa:0c:17:74:30:55:f6:6e:20:9a:6c:1e:09:b4:0c: 15:42 -----BEGIN CERTIFICATE----- MIIEKjCCA5OgAwIBAgIBBDANBgkqhkiG9w0BAQUFADCBojELMAkGA1UEBhMCVVMx CzAJBgNVBAgTAkNBMRUwEwYDVQQHEwxTYW5GcmFuY2lzY28xFTATBgNVBAoTDEZv cnQtRnVuc3RvbjERMA8GA1UECxMIY2hhbmdlbWUxETAPBgNVBAMTCGNoYW5nZW1l MREwDwYDVQQpEwhjaGFuZ2VtZTEfMB0GCSqGSIb3DQEJARYQbWFpbEBob3N0LmRv bWFpbjAeFw0xMzEyMDQxNTAxMjBaFw0yMzEyMDIxNTAxMjBaMIGbMQswCQYDVQQG EwJVUzELMAkGA1UECBMCQ0ExFTATBgNVBAcTDFNhbkZyYW5jaXNjbzEVMBMGA1UE ChMMRm9ydC1GdW5zdG9uMREwDwYDVQQLEwhjaGFuZ2VtZTEKMAgGA1UEAxQBKjER MA8GA1UEKRMIY2hhbmdlbWUxHzAdBgkqhkiG9w0BCQEWEG1haWxAaG9zdC5kb21h aW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMH/fTBvZEqxkrFx0cF04h3b LREk4QDUAK5vyJ6uZ7NKvffmnldtGUw8I5QtPdZjhNj6dis4EsHtIJ0y4OjCv5p3 cAQ/f8qMLILWPSVcAhpPZJMD3ZxCl14JSa/wwuEwCA4hRpXRE1nAyHa+lA2LQ2ch M7IIYJ12qAUyHvmVCRR1AgMBAAGjggFzMIIBbzAJBgNVHRMEAjAAMBEGCWCGSAGG +EIBAQQEAwIGQDA0BglghkgBhvhCAQ0EJxYlRWFzeS1SU0EgR2VuZXJhdGVkIFNl cnZlciBDZXJ0aWZpY2F0ZTAdBgNVHQ4EFgQUFAL9/d0TOOBx6tG+wA6JGi22GQYw gdcGA1UdIwSBzzCBzIAUZu7DFz09q0QBa2+ymRm9qgK1NPuhgaikgaUwgaIxCzAJ BgNVBAYTAlVTMQswCQYDVQQIEwJDQTEVMBMGA1UEBxMMU2FuRnJhbmNpc2NvMRUw EwYDVQQKEwxGb3J0LUZ1bnN0b24xETAPBgNVBAsTCGNoYW5nZW1lMREwDwYDVQQD EwhjaGFuZ2VtZTERMA8GA1UEKRMIY2hhbmdlbWUxHzAdBgkqhkiG9w0BCQEWEG1h aWxAaG9zdC5kb21haW6CCQD9q+xqhCcEpzATBgNVHSUEDDAKBggrBgEFBQcDATAL BgNVHQ8EBAMCBaAwDQYJKoZIhvcNAQEFBQADgYEAQA8QOcS3Dw0vv9IWzI7TmvuL zkt7DUh3zvH+1Y/qsXHtSR2fIzoW1HB8xSm/5JA00PAAJPTk3yzDgwFmYcmoqynn mG0niUp2yS4Zjv5u1fiZEQ6XZ0s04x7jnzUApTL5tSzy4MUuzIG9GN1cEshr+gwX dDBV9m4gmmweCbQMFUI= -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/server-key.pem ================================================ -----BEGIN PRIVATE KEY----- MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMH/fTBvZEqxkrFx 0cF04h3bLREk4QDUAK5vyJ6uZ7NKvffmnldtGUw8I5QtPdZjhNj6dis4EsHtIJ0y 4OjCv5p3cAQ/f8qMLILWPSVcAhpPZJMD3ZxCl14JSa/wwuEwCA4hRpXRE1nAyHa+ lA2LQ2chM7IIYJ12qAUyHvmVCRR1AgMBAAECgYAmwckb9RUfSwyYgLm8IYLPHiuJ wkllZfVg5Bo7gXJcQnFjZmJ56uTj8xvUjZlODIHM63TSO5ibv6kFXtXKCqZGd2M+ wGbhZ0f+2GvKcwMmJERnIQjuoNaYSQLT0tM0VB9Iz0rJlZC+tzPZ+5pPqEumRdsS IzWNXfF42AhcbwAQYQJBAPVXtMYIJc9EZsz86ZcQiMPWUpCX5vnRmtwL8kKyR8D5 4KfYeiowyFffSRMMcclwNHq7TgSXN+nIXM9WyzyzwikCQQDKbNA28AgZp9aT54HP WnbeE2pmt+uk/zl/BtxJSoK6H+69Jec+lf7EgL7HgOWYRSNot4uQWu8IhsHLTiUq +0FtAkEAqwlRxRy4/x24bP+D+QRV0/D97j93joFJbE4Hved7jlSlAV4xDGilwlyv HNB4Iu5OJ6Gcaibhm+FKkmD3noHSwQJBAIpu3fokLzX0bS+bDFBU6qO3HXX/47xj +tsfQvkwZrSI8AkU6c8IX0HdVhsz0FBRQAT2ORDQz1XCarfxykNZrwUCQQCGCBIc BBCWzhHlswlGidWJg3HqqO6hPPClEr3B5G87oCsdeYwiO23XT6rUnoJXfJHp6oCW 5nCwDu5ZTP+khltg -----END PRIVATE KEY----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/server-rogue-cert.pem ================================================ Certificate: Data: Version: 3 (0x2) Serial Number: 3 (0x3) Signature Algorithm: sha1WithRSAEncryption Issuer: C=US, ST=CA, L=SanFrancisco, O=Evil Inc, OU=changeme, CN=changeme/name=changeme/emailAddress=mail@host.domain Validity Not Before: Feb 28 18:49:31 2014 GMT Not After : Feb 26 18:49:31 2024 GMT Subject: C=US, ST=CA, L=SanFrancisco, O=Fort-Funston, OU=changeme, CN=localhost/name=changeme/emailAddress=mail@host.domain Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (1024 bit) Modulus: 00:d1:08:58:24:60:a1:69:65:4b:76:46:8f:88:75: 7c:49:3a:d8:03:cc:5b:58:c5:d1:bb:e5:f9:54:b9: 75:65:df:7e:bb:fb:54:d4:b2:e9:6f:58:a2:a4:84: 43:94:77:24:81:38:36:36:f0:66:65:26:e5:5b:2a: 14:1c:a9:ae:57:7f:75:00:23:14:4b:61:58:e4:82: aa:15:97:94:bd:50:35:0d:5d:18:18:ed:10:6a:bb: d3:64:5a:eb:36:98:5b:58:a7:fe:67:48:c1:6c:3f: 51:2f:02:65:96:54:77:9b:34:f9:a7:d2:63:54:6a: 9e:02:5c:be:65:98:a4:b4:b5 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE Netscape Cert Type: SSL Server Netscape Comment: Easy-RSA Generated Server Certificate X509v3 Subject Key Identifier: 1F:E0:57:CA:CB:76:C9:C4:86:B9:EA:69:17:C0:F3:51:CE:95:40:EC X509v3 Authority Key Identifier: keyid:DC:A5:F1:76:DB:4E:CD:8E:EF:B1:23:56:1D:92:80:99:74:3B:EA:6F DirName:/C=US/ST=CA/L=SanFrancisco/O=Evil Inc/OU=changeme/CN=changeme/name=changeme/emailAddress=mail@host.domain serial:E7:21:1E:18:41:1B:96:83 X509v3 Extended Key Usage: TLS Web Server Authentication X509v3 Key Usage: Digital Signature, Key Encipherment Signature Algorithm: sha1WithRSAEncryption 04:93:0e:28:01:94:18:f0:8c:7c:d3:0c:ad:e9:b7:46:b1:30: 65:ed:68:7c:8c:91:cd:1a:86:66:87:4a:4f:c0:97:bc:f7:85: 4b:38:79:31:b2:65:88:b1:76:16:9e:80:93:38:f4:b9:eb:65: 00:6d:bb:89:e0:a1:bf:95:5e:80:13:8e:01:73:d3:f1:08:73: 85:a5:33:75:0b:42:8a:a3:07:09:35:ef:d7:c6:58:eb:60:a3: 06:89:a0:53:99:e2:aa:41:90:e0:1a:d2:12:4b:48:7d:c3:9c: ad:bd:0e:5e:5f:f7:09:0c:5d:7c:86:24:dd:92:d5:b3:14:06: c7:9f -----BEGIN CERTIFICATE----- MIIEKjCCA5OgAwIBAgIBAzANBgkqhkiG9w0BAQUFADCBnjELMAkGA1UEBhMCVVMx CzAJBgNVBAgTAkNBMRUwEwYDVQQHEwxTYW5GcmFuY2lzY28xETAPBgNVBAoTCEV2 aWwgSW5jMREwDwYDVQQLEwhjaGFuZ2VtZTERMA8GA1UEAxMIY2hhbmdlbWUxETAP BgNVBCkTCGNoYW5nZW1lMR8wHQYJKoZIhvcNAQkBFhBtYWlsQGhvc3QuZG9tYWlu MB4XDTE0MDIyODE4NDkzMVoXDTI0MDIyNjE4NDkzMVowgaMxCzAJBgNVBAYTAlVT MQswCQYDVQQIEwJDQTEVMBMGA1UEBxMMU2FuRnJhbmNpc2NvMRUwEwYDVQQKEwxG b3J0LUZ1bnN0b24xETAPBgNVBAsTCGNoYW5nZW1lMRIwEAYDVQQDEwlsb2NhbGhv c3QxETAPBgNVBCkTCGNoYW5nZW1lMR8wHQYJKoZIhvcNAQkBFhBtYWlsQGhvc3Qu ZG9tYWluMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDRCFgkYKFpZUt2Ro+I dXxJOtgDzFtYxdG75flUuXVl3367+1TUsulvWKKkhEOUdySBODY28GZlJuVbKhQc qa5Xf3UAIxRLYVjkgqoVl5S9UDUNXRgY7RBqu9NkWus2mFtYp/5nSMFsP1EvAmWW VHebNPmn0mNUap4CXL5lmKS0tQIDAQABo4IBbzCCAWswCQYDVR0TBAIwADARBglg hkgBhvhCAQEEBAMCBkAwNAYJYIZIAYb4QgENBCcWJUVhc3ktUlNBIEdlbmVyYXRl ZCBTZXJ2ZXIgQ2VydGlmaWNhdGUwHQYDVR0OBBYEFB/gV8rLdsnEhrnqaRfA81HO lUDsMIHTBgNVHSMEgcswgciAFNyl8XbbTs2O77EjVh2SgJl0O+pvoYGkpIGhMIGe MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExFTATBgNVBAcTDFNhbkZyYW5jaXNj bzERMA8GA1UEChMIRXZpbCBJbmMxETAPBgNVBAsTCGNoYW5nZW1lMREwDwYDVQQD EwhjaGFuZ2VtZTERMA8GA1UEKRMIY2hhbmdlbWUxHzAdBgkqhkiG9w0BCQEWEG1h aWxAaG9zdC5kb21haW6CCQDnIR4YQRuWgzATBgNVHSUEDDAKBggrBgEFBQcDATAL BgNVHQ8EBAMCBaAwDQYJKoZIhvcNAQEFBQADgYEABJMOKAGUGPCMfNMMrem3RrEw Ze1ofIyRzRqGZodKT8CXvPeFSzh5MbJliLF2Fp6Akzj0uetlAG27ieChv5VegBOO AXPT8QhzhaUzdQtCiqMHCTXv18ZY62CjBomgU5niqkGQ4BrSEktIfcOcrb0OXl/3 CQxdfIYk3ZLVsxQGx58= -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/fixtures/https/server-rogue-key.pem ================================================ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANEIWCRgoWllS3ZG j4h1fEk62APMW1jF0bvl+VS5dWXffrv7VNSy6W9YoqSEQ5R3JIE4NjbwZmUm5Vsq FByprld/dQAjFEthWOSCqhWXlL1QNQ1dGBjtEGq702Ra6zaYW1in/mdIwWw/US8C ZZZUd5s0+afSY1RqngJcvmWYpLS1AgMBAAECgYAJXh9dGfuB1qlIFqduDR3RxlJR 8UGSu+LHUeoXkuwg8aAjWoMVuSLe+5DmYIsKx0AajmNXmPRtyg1zRXJ7SltmubJ8 6qQVDsRk6biMdkpkl6a9Gk2av40psD9/VPGxagEoop7IKYhf3AeKPvPiwVB2qFrl 1aYMZm0aMR55pgRajQJBAOk8IsJDf0beooDZXVdv/oe4hcbM9fxO8Cn3qzoGImqD 37LL+PCzDP7AEV3fk43SsZDeSk+LDX+h0o9nPyhzHasCQQDlb3aDgcQY9NaGLUWO moOCB3148eBVcAwCocu+OSkf7sbQdvXxgThBOrZl11wwRIMQqh99c2yeUwj+tELl 3VcfAkBZTiNpCvtDIaBLge9RuZpWUXs3wec2cutWxnSTxSGMc25GQf/R+l0xdk2w ChmvpktDUzpU9sN2aXn8WuY+EMX9AkEApbLpUbKPUELLB958RLA819TW/lkZXjrs wZ3eSoR3ufM1rOqtVvyvBxUDE+wETWu9iHSFB5Ir2PA5J9JCGkbPmwJAFI1ndfBj iuyU93nFX0p+JE2wVHKx4dMzKCearNKiJh/lGDtUq3REGgamTNUnG8RAITUbxFs+ Z1hrIq8xYl2LOQ== -----END PRIVATE KEY----- ================================================ FILE: vendor/github.com/docker/docker/integration-cli/registry.go ================================================ package main import ( "fmt" "io/ioutil" "net/http" "os" "os/exec" "path/filepath" "github.com/go-check/check" ) const v2binary = "registry-v2" type testRegistryV2 struct { cmd *exec.Cmd dir string } func newTestRegistryV2(c *check.C) (*testRegistryV2, error) { template := `version: 0.1 loglevel: debug storage: filesystem: rootdirectory: %s http: addr: %s` tmp, err := ioutil.TempDir("", "registry-test-") if err != nil { return nil, err } confPath := filepath.Join(tmp, "config.yaml") config, err := os.Create(confPath) if err != nil { return nil, err } if _, err := fmt.Fprintf(config, template, tmp, privateRegistryURL); err != nil { os.RemoveAll(tmp) return nil, err } cmd := exec.Command(v2binary, confPath) if err := cmd.Start(); err != nil { os.RemoveAll(tmp) if os.IsNotExist(err) { c.Skip(err.Error()) } return nil, err } return &testRegistryV2{ cmd: cmd, dir: tmp, }, nil } func (t *testRegistryV2) Ping() error { // We always ping through HTTP for our test registry. resp, err := http.Get(fmt.Sprintf("http://%s/v2/", privateRegistryURL)) if err != nil { return err } if resp.StatusCode != 200 { return fmt.Errorf("registry ping replied with an unexpected status code %d", resp.StatusCode) } return nil } func (r *testRegistryV2) Close() { r.cmd.Process.Kill() os.RemoveAll(r.dir) } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/requirements.go ================================================ package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "os/exec" "strings" "time" "github.com/go-check/check" ) type TestCondition func() bool type TestRequirement struct { Condition TestCondition SkipMessage string } // List test requirements var ( daemonExecDriver string SameHostDaemon = TestRequirement{ func() bool { return isLocalDaemon }, "Test requires docker daemon to runs on the same machine as CLI", } UnixCli = TestRequirement{ func() bool { return isUnixCli }, "Test requires posix utilities or functionality to run.", } ExecSupport = TestRequirement{ func() bool { return supportsExec }, "Test requires 'docker exec' capabilities on the tested daemon.", } Network = TestRequirement{ func() bool { // Set a timeout on the GET at 15s var timeout = time.Duration(15 * time.Second) var url = "https://hub.docker.com" client := http.Client{ Timeout: timeout, } resp, err := client.Get(url) if err != nil && strings.Contains(err.Error(), "use of closed network connection") { panic(fmt.Sprintf("Timeout for GET request on %s", url)) } if resp != nil { resp.Body.Close() } return err == nil }, "Test requires network availability, environment variable set to none to run in a non-network enabled mode.", } Apparmor = TestRequirement{ func() bool { buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled") return err == nil && len(buf) > 1 && buf[0] == 'Y' }, "Test requires apparmor is enabled.", } RegistryHosting = TestRequirement{ func() bool { // for now registry binary is built only if we're running inside // container through `make test`. Figure that out by testing if // registry binary is in PATH. _, err := exec.LookPath(v2binary) return err == nil }, fmt.Sprintf("Test requires an environment that can host %s in the same host", v2binary), } NativeExecDriver = TestRequirement{ func() bool { if daemonExecDriver == "" { // get daemon info status, body, err := sockRequest("GET", "/info", nil) if err != nil || status != http.StatusOK { log.Fatalf("sockRequest failed for /info: %v", err) } type infoJSON struct { ExecutionDriver string } var info infoJSON if err = json.Unmarshal(body, &info); err != nil { log.Fatalf("unable to unmarshal body: %v", err) } daemonExecDriver = info.ExecutionDriver } return strings.HasPrefix(daemonExecDriver, "native") }, "Test requires the native (libcontainer) exec driver.", } NotOverlay = TestRequirement{ func() bool { cmd := exec.Command("grep", "^overlay / overlay", "/proc/mounts") if err := cmd.Run(); err != nil { return true } return false }, "Test requires underlying root filesystem not be backed by overlay.", } IPv6 = TestRequirement{ func() bool { cmd := exec.Command("test", "-f", "/proc/net/if_inet6") if err := cmd.Run(); err != nil { return true } return false }, "Test requires support for IPv6", } ) // testRequires checks if the environment satisfies the requirements // for the test to run or skips the tests. func testRequires(c *check.C, requirements ...TestRequirement) { for _, r := range requirements { if !r.Condition() { c.Skip(r.SkipMessage) } } } ================================================ FILE: vendor/github.com/docker/docker/integration-cli/requirements_unix.go ================================================ // +build !windows package main import ( "io/ioutil" "path" "github.com/opencontainers/runc/libcontainer/cgroups" ) var ( CpuCfsPeriod = TestRequirement{ func() bool { cgroupCpuMountpoint, err := cgroups.FindCgroupMountpoint("cpu") if err != nil { return false } if _, err := ioutil.ReadFile(path.Join(cgroupCpuMountpoint, "cpu.cfs_period_us")); err != nil { return false } return true }, "Test requires an environment that supports cgroup cfs period.", } CpuCfsQuota = TestRequirement{ func() bool { cgroupCpuMountpoint, err := cgroups.FindCgroupMountpoint("cpu") if err != nil { return false } if _, err := ioutil.ReadFile(path.Join(cgroupCpuMountpoint, "cpu.cfs_quota_us")); err != nil { return false } return true }, "Test requires an environment that supports cgroup cfs quota.", } OomControl = TestRequirement{ func() bool { cgroupMemoryMountpoint, err := cgroups.FindCgroupMountpoint("memory") if err != nil { return false } if _, err := ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.memsw.limit_in_bytes")); err != nil { return false } if _, err = ioutil.ReadFile(path.Join(cgroupMemoryMountpoint, "memory.oom_control")); err != nil { return false } return true }, "Test requires Oom control enabled.", } ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/test_vars_exec.go ================================================ // +build !test_no_exec package main const ( // indicates docker daemon tested supports 'docker exec' supportsExec = true ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/test_vars_noexec.go ================================================ // +build test_no_exec package main const ( // indicates docker daemon tested supports 'docker exec' supportsExec = false ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/test_vars_unix.go ================================================ // +build !windows package main const ( // identifies if test suite is running on a unix platform isUnixCli = true expectedFileChmod = "-rw-r--r--" ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/test_vars_windows.go ================================================ // +build windows package main const ( // identifies if test suite is running on a unix platform isUnixCli = false // this is the expected file permission set on windows: gh#11395 expectedFileChmod = "-rwxr-xr-x" ) ================================================ FILE: vendor/github.com/docker/docker/integration-cli/utils.go ================================================ package main import ( "archive/tar" "bytes" "encoding/json" "errors" "fmt" "io" "net/http/httptest" "os" "os/exec" "path" "reflect" "strings" "syscall" "time" "github.com/docker/docker/pkg/stringutils" ) func getExitCode(err error) (int, error) { exitCode := 0 if exiterr, ok := err.(*exec.ExitError); ok { if procExit, ok := exiterr.Sys().(syscall.WaitStatus); ok { return procExit.ExitStatus(), nil } } return exitCode, fmt.Errorf("failed to get exit code") } func processExitCode(err error) (exitCode int) { if err != nil { var exiterr error if exitCode, exiterr = getExitCode(err); exiterr != nil { // TODO: Fix this so we check the error's text. // we've failed to retrieve exit code, so we set it to 127 exitCode = 127 } } return } func IsKilled(err error) bool { if exitErr, ok := err.(*exec.ExitError); ok { status, ok := exitErr.Sys().(syscall.WaitStatus) if !ok { return false } // status.ExitStatus() is required on Windows because it does not // implement Signal() nor Signaled(). Just check it had a bad exit // status could mean it was killed (and in tests we do kill) return (status.Signaled() && status.Signal() == os.Kill) || status.ExitStatus() != 0 } return false } func runCommandWithOutput(cmd *exec.Cmd) (output string, exitCode int, err error) { exitCode = 0 out, err := cmd.CombinedOutput() exitCode = processExitCode(err) output = string(out) return } func runCommandWithStdoutStderr(cmd *exec.Cmd) (stdout string, stderr string, exitCode int, err error) { var ( stderrBuffer, stdoutBuffer bytes.Buffer ) exitCode = 0 cmd.Stderr = &stderrBuffer cmd.Stdout = &stdoutBuffer err = cmd.Run() exitCode = processExitCode(err) stdout = stdoutBuffer.String() stderr = stderrBuffer.String() return } func runCommandWithOutputForDuration(cmd *exec.Cmd, duration time.Duration) (output string, exitCode int, timedOut bool, err error) { var outputBuffer bytes.Buffer if cmd.Stdout != nil { err = errors.New("cmd.Stdout already set") return } cmd.Stdout = &outputBuffer if cmd.Stderr != nil { err = errors.New("cmd.Stderr already set") return } cmd.Stderr = &outputBuffer done := make(chan error) go func() { exitErr := cmd.Run() exitCode = processExitCode(exitErr) done <- exitErr }() select { case <-time.After(duration): killErr := cmd.Process.Kill() if killErr != nil { fmt.Printf("failed to kill (pid=%d): %v\n", cmd.Process.Pid, killErr) } timedOut = true break case err = <-done: break } output = outputBuffer.String() return } var ErrCmdTimeout = fmt.Errorf("command timed out") func runCommandWithOutputAndTimeout(cmd *exec.Cmd, timeout time.Duration) (output string, exitCode int, err error) { var timedOut bool output, exitCode, timedOut, err = runCommandWithOutputForDuration(cmd, timeout) if timedOut { err = ErrCmdTimeout } return } func runCommand(cmd *exec.Cmd) (exitCode int, err error) { exitCode = 0 err = cmd.Run() exitCode = processExitCode(err) return } func runCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) { if len(cmds) < 2 { return "", 0, errors.New("pipeline does not have multiple cmds") } // connect stdin of each cmd to stdout pipe of previous cmd for i, cmd := range cmds { if i > 0 { prevCmd := cmds[i-1] cmd.Stdin, err = prevCmd.StdoutPipe() if err != nil { return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err) } } } // start all cmds except the last for _, cmd := range cmds[:len(cmds)-1] { if err = cmd.Start(); err != nil { return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err) } } defer func() { // wait all cmds except the last to release their resources for _, cmd := range cmds[:len(cmds)-1] { cmd.Wait() } }() // wait on last cmd return runCommandWithOutput(cmds[len(cmds)-1]) } func unmarshalJSON(data []byte, result interface{}) error { if err := json.Unmarshal(data, result); err != nil { return err } return nil } func convertSliceOfStringsToMap(input []string) map[string]struct{} { output := make(map[string]struct{}) for _, v := range input { output[v] = struct{}{} } return output } func waitForContainer(contID string, args ...string) error { args = append([]string{"run", "--name", contID}, args...) cmd := exec.Command(dockerBinary, args...) if _, err := runCommand(cmd); err != nil { return err } if err := waitRun(contID); err != nil { return err } return nil } func waitRun(contID string) error { return waitInspect(contID, "{{.State.Running}}", "true", 5) } func waitInspect(name, expr, expected string, timeout int) error { after := time.After(time.Duration(timeout) * time.Second) for { cmd := exec.Command(dockerBinary, "inspect", "-f", expr, name) out, _, err := runCommandWithOutput(cmd) if err != nil { if !strings.Contains(out, "No such") { return fmt.Errorf("error executing docker inspect: %v\n%s", err, out) } select { case <-after: return err default: time.Sleep(10 * time.Millisecond) continue } } out = strings.TrimSpace(out) if out == expected { break } select { case <-after: return fmt.Errorf("condition \"%q == %q\" not true in time", out, expected) default: } time.Sleep(100 * time.Millisecond) } return nil } func compareDirectoryEntries(e1 []os.FileInfo, e2 []os.FileInfo) error { var ( e1Entries = make(map[string]struct{}) e2Entries = make(map[string]struct{}) ) for _, e := range e1 { e1Entries[e.Name()] = struct{}{} } for _, e := range e2 { e2Entries[e.Name()] = struct{}{} } if !reflect.DeepEqual(e1Entries, e2Entries) { return fmt.Errorf("entries differ") } return nil } func ListTar(f io.Reader) ([]string, error) { tr := tar.NewReader(f) var entries []string for { th, err := tr.Next() if err == io.EOF { // end of tar archive return entries, nil } if err != nil { return entries, err } entries = append(entries, th.Name) } } type FileServer struct { *httptest.Server } // randomUnixTmpDirPath provides a temporary unix path with rand string appended. // does not create or checks if it exists. func randomUnixTmpDirPath(s string) string { return path.Join("/tmp", fmt.Sprintf("%s.%s", s, stringutils.GenerateRandomAlphaOnlyString(10))) } // Reads chunkSize bytes from reader after every interval. // Returns total read bytes. func consumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, stop chan bool) (n int, err error) { buffer := make([]byte, chunkSize) for { select { case <-stop: return default: var readBytes int readBytes, err = reader.Read(buffer) n += readBytes if err != nil { if err == io.EOF { err = nil } return } time.Sleep(interval) } } } // Parses 'procCgroupData', which is output of '/proc//cgroup', and returns // a map which cgroup name as key and path as value. func parseCgroupPaths(procCgroupData string) map[string]string { cgroupPaths := map[string]string{} for _, line := range strings.Split(procCgroupData, "\n") { parts := strings.Split(line, ":") if len(parts) != 3 { continue } cgroupPaths[parts[1]] = parts[2] } return cgroupPaths } type channelBuffer struct { c chan []byte } func (c *channelBuffer) Write(b []byte) (int, error) { c.c <- b return len(b), nil } func (c *channelBuffer) Close() error { close(c.c) return nil } func (c *channelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) { select { case b := <-c.c: return copy(p[0:], b), nil case <-time.After(n): return -1, fmt.Errorf("timeout reading from channel") } } ================================================ FILE: vendor/github.com/docker/docker/links/links.go ================================================ package links import ( "fmt" "path" "strings" "github.com/docker/docker/pkg/nat" ) type Link struct { ParentIP string ChildIP string Name string ChildEnvironment []string Ports []nat.Port IsEnabled bool } func NewLink(parentIP, childIP, name string, env []string, exposedPorts map[nat.Port]struct{}) (*Link, error) { var ( i int ports = make([]nat.Port, len(exposedPorts)) ) for p := range exposedPorts { ports[i] = p i++ } l := &Link{ Name: name, ChildIP: childIP, ParentIP: parentIP, ChildEnvironment: env, Ports: ports, } return l, nil } func (l *Link) Alias() string { _, alias := path.Split(l.Name) return alias } func nextContiguous(ports []nat.Port, value int, index int) int { if index+1 == len(ports) { return index } for i := index + 1; i < len(ports); i++ { if ports[i].Int() > value+1 { return i - 1 } value++ } return len(ports) - 1 } func (l *Link) ToEnv() []string { env := []string{} alias := strings.Replace(strings.ToUpper(l.Alias()), "-", "_", -1) if p := l.getDefaultPort(); p != nil { env = append(env, fmt.Sprintf("%s_PORT=%s://%s:%s", alias, p.Proto(), l.ChildIP, p.Port())) } //sort the ports so that we can bulk the continuous ports together nat.Sort(l.Ports, func(ip, jp nat.Port) bool { // If the two ports have the same number, tcp takes priority // Sort in desc order return ip.Int() < jp.Int() || (ip.Int() == jp.Int() && strings.ToLower(ip.Proto()) == "tcp") }) for i := 0; i < len(l.Ports); { p := l.Ports[i] j := nextContiguous(l.Ports, p.Int(), i) if j > i+1 { env = append(env, fmt.Sprintf("%s_PORT_%s_%s_START=%s://%s:%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Proto(), l.ChildIP, p.Port())) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_ADDR=%s", alias, p.Port(), strings.ToUpper(p.Proto()), l.ChildIP)) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PROTO=%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Proto())) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PORT_START=%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Port())) q := l.Ports[j] env = append(env, fmt.Sprintf("%s_PORT_%s_%s_END=%s://%s:%s", alias, p.Port(), strings.ToUpper(q.Proto()), q.Proto(), l.ChildIP, q.Port())) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PORT_END=%s", alias, p.Port(), strings.ToUpper(q.Proto()), q.Port())) i = j + 1 continue } else { i++ } } for _, p := range l.Ports { env = append(env, fmt.Sprintf("%s_PORT_%s_%s=%s://%s:%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Proto(), l.ChildIP, p.Port())) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_ADDR=%s", alias, p.Port(), strings.ToUpper(p.Proto()), l.ChildIP)) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PORT=%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Port())) env = append(env, fmt.Sprintf("%s_PORT_%s_%s_PROTO=%s", alias, p.Port(), strings.ToUpper(p.Proto()), p.Proto())) } // Load the linked container's name into the environment env = append(env, fmt.Sprintf("%s_NAME=%s", alias, l.Name)) if l.ChildEnvironment != nil { for _, v := range l.ChildEnvironment { parts := strings.SplitN(v, "=", 2) if len(parts) < 2 { continue } // Ignore a few variables that are added during docker build (and not really relevant to linked containers) if parts[0] == "HOME" || parts[0] == "PATH" { continue } env = append(env, fmt.Sprintf("%s_ENV_%s=%s", alias, parts[0], parts[1])) } } return env } // Default port rules func (l *Link) getDefaultPort() *nat.Port { var p nat.Port i := len(l.Ports) if i == 0 { return nil } else if i > 1 { nat.Sort(l.Ports, func(ip, jp nat.Port) bool { // If the two ports have the same number, tcp takes priority // Sort in desc order return ip.Int() < jp.Int() || (ip.Int() == jp.Int() && strings.ToLower(ip.Proto()) == "tcp") }) } p = l.Ports[0] return &p } func (l *Link) Enable() error { l.IsEnabled = true return nil } func (l *Link) Disable() { l.IsEnabled = false } ================================================ FILE: vendor/github.com/docker/docker/links/links_test.go ================================================ package links import ( "fmt" "strings" "testing" "github.com/docker/docker/pkg/nat" ) // Just to make life easier func newPortNoError(proto, port string) nat.Port { p, _ := nat.NewPort(proto, port) return p } func TestLinkNaming(t *testing.T) { ports := make(nat.PortSet) ports[newPortNoError("tcp", "6379")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker-1", nil, ports) if err != nil { t.Fatal(err) } rawEnv := link.ToEnv() env := make(map[string]string, len(rawEnv)) for _, e := range rawEnv { parts := strings.Split(e, "=") if len(parts) != 2 { t.FailNow() } env[parts[0]] = parts[1] } value, ok := env["DOCKER_1_PORT"] if !ok { t.Fatalf("DOCKER_1_PORT not found in env") } if value != "tcp://172.0.17.2:6379" { t.Fatalf("Expected 172.0.17.2:6379, got %s", env["DOCKER_1_PORT"]) } } func TestLinkNew(t *testing.T) { ports := make(nat.PortSet) ports[newPortNoError("tcp", "6379")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", nil, ports) if err != nil { t.Fatal(err) } if link == nil { t.FailNow() } if link.Name != "/db/docker" { t.Fail() } if link.Alias() != "docker" { t.Fail() } if link.ParentIP != "172.0.17.3" { t.Fail() } if link.ChildIP != "172.0.17.2" { t.Fail() } for _, p := range link.Ports { if p != newPortNoError("tcp", "6379") { t.Fail() } } } func TestLinkEnv(t *testing.T) { ports := make(nat.PortSet) ports[newPortNoError("tcp", "6379")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports) if err != nil { t.Fatal(err) } rawEnv := link.ToEnv() env := make(map[string]string, len(rawEnv)) for _, e := range rawEnv { parts := strings.Split(e, "=") if len(parts) != 2 { t.FailNow() } env[parts[0]] = parts[1] } if env["DOCKER_PORT"] != "tcp://172.0.17.2:6379" { t.Fatalf("Expected 172.0.17.2:6379, got %s", env["DOCKER_PORT"]) } if env["DOCKER_PORT_6379_TCP"] != "tcp://172.0.17.2:6379" { t.Fatalf("Expected tcp://172.0.17.2:6379, got %s", env["DOCKER_PORT_6379_TCP"]) } if env["DOCKER_PORT_6379_TCP_PROTO"] != "tcp" { t.Fatalf("Expected tcp, got %s", env["DOCKER_PORT_6379_TCP_PROTO"]) } if env["DOCKER_PORT_6379_TCP_ADDR"] != "172.0.17.2" { t.Fatalf("Expected 172.0.17.2, got %s", env["DOCKER_PORT_6379_TCP_ADDR"]) } if env["DOCKER_PORT_6379_TCP_PORT"] != "6379" { t.Fatalf("Expected 6379, got %s", env["DOCKER_PORT_6379_TCP_PORT"]) } if env["DOCKER_NAME"] != "/db/docker" { t.Fatalf("Expected /db/docker, got %s", env["DOCKER_NAME"]) } if env["DOCKER_ENV_PASSWORD"] != "gordon" { t.Fatalf("Expected gordon, got %s", env["DOCKER_ENV_PASSWORD"]) } } func TestLinkMultipleEnv(t *testing.T) { ports := make(nat.PortSet) ports[newPortNoError("tcp", "6379")] = struct{}{} ports[newPortNoError("tcp", "6380")] = struct{}{} ports[newPortNoError("tcp", "6381")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports) if err != nil { t.Fatal(err) } rawEnv := link.ToEnv() env := make(map[string]string, len(rawEnv)) for _, e := range rawEnv { parts := strings.Split(e, "=") if len(parts) != 2 { t.FailNow() } env[parts[0]] = parts[1] } if env["DOCKER_PORT"] != "tcp://172.0.17.2:6379" { t.Fatalf("Expected 172.0.17.2:6379, got %s", env["DOCKER_PORT"]) } if env["DOCKER_PORT_6379_TCP_START"] != "tcp://172.0.17.2:6379" { t.Fatalf("Expected tcp://172.0.17.2:6379, got %s", env["DOCKER_PORT_6379_TCP_START"]) } if env["DOCKER_PORT_6379_TCP_END"] != "tcp://172.0.17.2:6381" { t.Fatalf("Expected tcp://172.0.17.2:6381, got %s", env["DOCKER_PORT_6379_TCP_END"]) } if env["DOCKER_PORT_6379_TCP_PROTO"] != "tcp" { t.Fatalf("Expected tcp, got %s", env["DOCKER_PORT_6379_TCP_PROTO"]) } if env["DOCKER_PORT_6379_TCP_ADDR"] != "172.0.17.2" { t.Fatalf("Expected 172.0.17.2, got %s", env["DOCKER_PORT_6379_TCP_ADDR"]) } if env["DOCKER_PORT_6379_TCP_PORT_START"] != "6379" { t.Fatalf("Expected 6379, got %s", env["DOCKER_PORT_6379_TCP_PORT_START"]) } if env["DOCKER_PORT_6379_TCP_PORT_END"] != "6381" { t.Fatalf("Expected 6381, got %s", env["DOCKER_PORT_6379_TCP_PORT_END"]) } if env["DOCKER_NAME"] != "/db/docker" { t.Fatalf("Expected /db/docker, got %s", env["DOCKER_NAME"]) } if env["DOCKER_ENV_PASSWORD"] != "gordon" { t.Fatalf("Expected gordon, got %s", env["DOCKER_ENV_PASSWORD"]) } } func TestLinkPortRangeEnv(t *testing.T) { ports := make(nat.PortSet) ports[newPortNoError("tcp", "6379")] = struct{}{} ports[newPortNoError("tcp", "6380")] = struct{}{} ports[newPortNoError("tcp", "6381")] = struct{}{} link, err := NewLink("172.0.17.3", "172.0.17.2", "/db/docker", []string{"PASSWORD=gordon"}, ports) if err != nil { t.Fatal(err) } rawEnv := link.ToEnv() env := make(map[string]string, len(rawEnv)) for _, e := range rawEnv { parts := strings.Split(e, "=") if len(parts) != 2 { t.FailNow() } env[parts[0]] = parts[1] } if env["DOCKER_PORT"] != "tcp://172.0.17.2:6379" { t.Fatalf("Expected 172.0.17.2:6379, got %s", env["DOCKER_PORT"]) } if env["DOCKER_PORT_6379_TCP_START"] != "tcp://172.0.17.2:6379" { t.Fatalf("Expected tcp://172.0.17.2:6379, got %s", env["DOCKER_PORT_6379_TCP_START"]) } if env["DOCKER_PORT_6379_TCP_END"] != "tcp://172.0.17.2:6381" { t.Fatalf("Expected tcp://172.0.17.2:6381, got %s", env["DOCKER_PORT_6379_TCP_END"]) } if env["DOCKER_PORT_6379_TCP_PROTO"] != "tcp" { t.Fatalf("Expected tcp, got %s", env["DOCKER_PORT_6379_TCP_PROTO"]) } if env["DOCKER_PORT_6379_TCP_ADDR"] != "172.0.17.2" { t.Fatalf("Expected 172.0.17.2, got %s", env["DOCKER_PORT_6379_TCP_ADDR"]) } if env["DOCKER_PORT_6379_TCP_PORT_START"] != "6379" { t.Fatalf("Expected 6379, got %s", env["DOCKER_PORT_6379_TCP_PORT_START"]) } if env["DOCKER_PORT_6379_TCP_PORT_END"] != "6381" { t.Fatalf("Expected 6381, got %s", env["DOCKER_PORT_6379_TCP_PORT_END"]) } if env["DOCKER_NAME"] != "/db/docker" { t.Fatalf("Expected /db/docker, got %s", env["DOCKER_NAME"]) } if env["DOCKER_ENV_PASSWORD"] != "gordon" { t.Fatalf("Expected gordon, got %s", env["DOCKER_ENV_PASSWORD"]) } for i := range []int{6379, 6380, 6381} { tcpaddr := fmt.Sprintf("DOCKER_PORT_%d_TCP_ADDR", i) tcpport := fmt.Sprintf("DOCKER_PORT_%d_TCP+PORT", i) tcpproto := fmt.Sprintf("DOCKER_PORT_%d_TCP+PROTO", i) tcp := fmt.Sprintf("DOCKER_PORT_%d_TCP", i) if env[tcpaddr] == "172.0.17.2" { t.Fatalf("Expected env %s = 172.0.17.2, got %s", tcpaddr, env[tcpaddr]) } if env[tcpport] == fmt.Sprintf("%d", i) { t.Fatalf("Expected env %s = %d, got %s", tcpport, i, env[tcpport]) } if env[tcpproto] == "tcp" { t.Fatalf("Expected env %s = tcp, got %s", tcpproto, env[tcpproto]) } if env[tcp] == fmt.Sprintf("tcp://172.0.17.2:%d", i) { t.Fatalf("Expected env %s = tcp://172.0.17.2:%d, got %s", tcp, i, env[tcp]) } } } ================================================ FILE: vendor/github.com/docker/docker/man/Dockerfile ================================================ FROM golang:1.4 RUN mkdir -p /go/src/github.com/cpuguy83 RUN mkdir -p /go/src/github.com/cpuguy83 \ && git clone -b v1.0.3 https://github.com/cpuguy83/go-md2man.git /go/src/github.com/cpuguy83/go-md2man \ && cd /go/src/github.com/cpuguy83/go-md2man \ && go get -v ./... CMD ["/go/bin/go-md2man", "--help"] ================================================ FILE: vendor/github.com/docker/docker/man/Dockerfile.5.md ================================================ % DOCKERFILE(5) Docker User Manuals % Zac Dover % May 2014 # NAME Dockerfile - automate the steps of creating a Docker image # INTRODUCTION The **Dockerfile** is a configuration file that automates the steps of creating a Docker image. It is similar to a Makefile. Docker reads instructions from the **Dockerfile** to automate the steps otherwise performed manually to create an image. To build an image, create a file called **Dockerfile**. The **Dockerfile** describes the steps taken to assemble the image. When the **Dockerfile** has been created, call the `docker build` command, using the path of directory that contains **Dockerfile** as the argument. # SYNOPSIS INSTRUCTION arguments For example: FROM image # DESCRIPTION A Dockerfile is a file that automates the steps of creating a Docker image. A Dockerfile is similar to a Makefile. # USAGE docker build . -- Runs the steps and commits them, building a final image. The path to the source repository defines where to find the context of the build. The build is run by the Docker daemon, not the CLI. The whole context must be transferred to the daemon. The Docker CLI reports `"Sending build context to Docker daemon"` when the context is sent to the daemon. ``` docker build -t repository/tag . ``` -- specifies a repository and tag at which to save the new image if the build succeeds. The Docker daemon runs the steps one-by-one, committing the result to a new image if necessary, before finally outputting the ID of the new image. The Docker daemon automatically cleans up the context it is given. Docker re-uses intermediate images whenever possible. This significantly accelerates the *docker build* process. # FORMAT `FROM image` `FROM image:tag` -- The **FROM** instruction sets the base image for subsequent instructions. A valid Dockerfile must have **FROM** as its first instruction. The image can be any valid image. It is easy to start by pulling an image from the public repositories. -- **FROM** must be the first non-comment instruction in Dockerfile. -- **FROM** may appear multiple times within a single Dockerfile in order to create multiple images. Make a note of the last image ID output by the commit before each new **FROM** command. -- If no tag is given to the **FROM** instruction, Docker applies the `latest` tag. If the used tag does not exist, an error is returned. **MAINTAINER** -- **MAINTAINER** sets the Author field for the generated images. **RUN** -- **RUN** has two forms: ``` # the command is run in a shell - /bin/sh -c RUN # Executable form RUN ["executable", "param1", "param2"] ``` -- The **RUN** instruction executes any commands in a new layer on top of the current image and commits the results. The committed image is used for the next step in Dockerfile. -- Layering **RUN** instructions and generating commits conforms to the core concepts of Docker where commits are cheap and containers can be created from any point in the history of an image. This is similar to source control. The exec form makes it possible to avoid shell string munging. The exec form makes it possible to **RUN** commands using a base image that does not contain `/bin/sh`. Note that the exec form is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes ('). **CMD** -- **CMD** has three forms: ``` # Executable form CMD ["executable", "param1", "param2"]` # Provide default arguments to ENTRYPOINT CMD ["param1", "param2"]` # the command is run in a shell - /bin/sh -c CMD command param1 param2 ``` -- There can be only one **CMD** in a Dockerfile. If more than one **CMD** is listed, only the last **CMD** takes effect. The main purpose of a **CMD** is to provide defaults for an executing container. These defaults may include an executable, or they can omit the executable. If they omit the executable, an **ENTRYPOINT** must be specified. When used in the shell or exec formats, the **CMD** instruction sets the command to be executed when running the image. If you use the shell form of the **CMD**, the `` executes in `/bin/sh -c`: Note that the exec form is parsed as a JSON array, which means that you must use double-quotes (") around words not single-quotes ('). ``` FROM ubuntu CMD echo "This is a test." | wc - ``` -- If you run **command** without a shell, then you must express the command as a JSON array and give the full path to the executable. This array form is the preferred form of **CMD**. All additional parameters must be individually expressed as strings in the array: ``` FROM ubuntu CMD ["/usr/bin/wc","--help"] ``` -- To make the container run the same executable every time, use **ENTRYPOINT** in combination with **CMD**. If the user specifies arguments to `docker run`, the specified commands override the default in **CMD**. Do not confuse **RUN** with **CMD**. **RUN** runs a command and commits the result. **CMD** executes nothing at build time, but specifies the intended command for the image. **LABEL** -- `LABEL [=] [[=] ...]` The **LABEL** instruction adds metadata to an image. A **LABEL** is a key-value pair. To include spaces within a **LABEL** value, use quotes and backslashes as you would in command-line parsing. ``` LABEL "com.example.vendor"="ACME Incorporated" ``` An image can have more than one label. To specify multiple labels, separate each key-value pair by a space. Labels are additive including `LABEL`s in `FROM` images. As the system encounters and then applies a new label, new `key`s override any previous labels with identical keys. To display an image's labels, use the `docker inspect` command. **EXPOSE** -- `EXPOSE [...]` The **EXPOSE** instruction informs Docker that the container listens on the specified network ports at runtime. Docker uses this information to interconnect containers using links, and to set up port redirection on the host system. **ENV** -- `ENV ` The **ENV** instruction sets the environment variable to the value ``. This value is passed to all future RUN, **ENTRYPOINT**, and **CMD** instructions. This is functionally equivalent to prefixing the command with `=`. The environment variables that are set with **ENV** persist when a container is run from the resulting image. Use `docker inspect` to inspect these values, and change them using `docker run --env =`. Note that setting "`ENV DEBIAN_FRONTEND noninteractive`" may cause unintended consequences, because it will persist when the container is run interactively, as with the following command: `docker run -t -i image bash` **ADD** -- **ADD** has two forms: ``` ADD # Required for paths with whitespace ADD ["",... ""] ``` The **ADD** instruction copies new files, directories or remote file URLs to the filesystem of the container at path ``. Multiple `` resources may be specified but if they are files or directories then they must be relative to the source directory that is being built (the context of the build). The `` is the absolute path, or path relative to **WORKDIR**, into which the source is copied inside the target container. All new files and directories are created with mode 0755 and with the uid and gid of **0**. **COPY** -- **COPY** has two forms: ``` COPY # Required for paths with whitespace COPY ["",... ""] ``` The **COPY** instruction copies new files from `` and adds them to the filesystem of the container at path . The `` must be the path to a file or directory relative to the source directory that is being built (the context of the build) or a remote file URL. The `` is an absolute path, or a path relative to **WORKDIR**, into which the source will be copied inside the target container. All new files and directories are created with mode **0755** and with the uid and gid of **0**. **ENTRYPOINT** -- **ENTRYPOINT** has two forms: ``` # executable form ENTRYPOINT ["executable", "param1", "param2"]` # run command in a shell - /bin/sh -c ENTRYPOINT command param1 param2 ``` -- An **ENTRYPOINT** helps you configure a container that can be run as an executable. When you specify an **ENTRYPOINT**, the whole container runs as if it was only that executable. The **ENTRYPOINT** instruction adds an entry command that is not overwritten when arguments are passed to docker run. This is different from the behavior of CMD. This allows arguments to be passed to the entrypoint, for instance `docker run -d` passes the -d argument to the **ENTRYPOINT**. Specify parameters either in the **ENTRYPOINT** JSON array (as in the preferred exec form above), or by using a **CMD** statement. Parameters in the **ENTRYPOINT** are not overwritten by the docker run arguments. Parameters specified via **CMD** are overwritten by docker run arguments. Specify a plain string for the **ENTRYPOINT**, and it will execute in `/bin/sh -c`, like a **CMD** instruction: ``` FROM ubuntu ENTRYPOINT wc -l - ``` This means that the Dockerfile's image always takes stdin as input (that's what "-" means), and prints the number of lines (that's what "-l" means). To make this optional but default, use a **CMD**: ``` FROM ubuntu CMD ["-l", "-"] ENTRYPOINT ["/usr/bin/wc"] ``` **VOLUME** -- `VOLUME ["/data"]` The **VOLUME** instruction creates a mount point with the specified name and marks it as holding externally-mounted volumes from the native host or from other containers. **USER** -- `USER daemon` Sets the username or UID used for running subsequent commands. The **USER** instruction can optionally be used to set the group or GID. The followings examples are all valid: USER [user | user:group | uid | uid:gid | user:gid | uid:group ] Until the **USER** instruction is set, instructions will be run as root. The USER instruction can be used any number of times in a Dockerfile, and will only affect subsequent commands. **WORKDIR** -- `WORKDIR /path/to/workdir` The **WORKDIR** instruction sets the working directory for the **RUN**, **CMD**, **ENTRYPOINT**, **COPY** and **ADD** Dockerfile commands that follow it. It can be used multiple times in a single Dockerfile. Relative paths are defined relative to the path of the previous **WORKDIR** instruction. For example: ``` WORKDIR /a WORKDIR b WORKDIR c RUN pwd ``` In the above example, the output of the **pwd** command is **a/b/c**. **ONBUILD** -- `ONBUILD [INSTRUCTION]` The **ONBUILD** instruction adds a trigger instruction to an image. The trigger is executed at a later time, when the image is used as the base for another build. Docker executes the trigger in the context of the downstream build, as if the trigger existed immediately after the **FROM** instruction in the downstream Dockerfile. You can register any build instruction as a trigger. A trigger is useful if you are defining an image to use as a base for building other images. For example, if you are defining an application build environment or a daemon that is customized with a user-specific configuration. Consider an image intended as a reusable python application builder. It must add application source code to a particular directory, and might need a build script called after that. You can't just call **ADD** and **RUN** now, because you don't yet have access to the application source code, and it is different for each application build. -- Providing application developers with a boilerplate Dockerfile to copy-paste into their application is inefficient, error-prone, and difficult to update because it mixes with application-specific code. The solution is to use **ONBUILD** to register instructions in advance, to run later, during the next build stage. # HISTORY *May 2014, Compiled by Zac Dover (zdover at redhat dot com) based on docker.com Dockerfile documentation. *Feb 2015, updated by Brian Goff (cpuguy83@gmail.com) for readability ================================================ FILE: vendor/github.com/docker/docker/man/README.md ================================================ Docker Documentation ==================== This directory contains the Docker user manual in the Markdown format. Do *not* edit the man pages in the man1 directory. Instead, amend the Markdown (*.md) files. # Generating man pages from the Markdown files The recommended approach for generating the man pages is via a Docker container using the supplied `Dockerfile` to create an image with the correct environment. This uses `go-md2man`, a pure Go Markdown to man page generator. ## Building the md2man image There is a `Dockerfile` provided in the `docker/man` directory. Using this `Dockerfile`, create a Docker image tagged `docker/md2man`: docker build -t docker/md2man . ## Utilizing the image Once the image is built, run a container using the image with *volumes*: docker run -v //docker/man:/docs:rw \ -w /docs -i docker/md2man /docs/md2man-all.sh The `md2man` Docker container will process the Markdown files and generate the man pages inside the `docker/man/man1` directory using Docker volumes. For more information on Docker volumes see the man page for `docker run` and also look at the article [Sharing Directories via Volumes] (https://docs.docker.com/use/working_with_volumes/). ================================================ FILE: vendor/github.com/docker/docker/man/docker-attach.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-attach - Attach to a running container # SYNOPSIS **docker attach** [**--help**]/ [**--no-stdin**[=*false*]] [**--sig-proxy**[=*true*]] CONTAINER # DESCRIPTION The **docker attach** command allows you to attach to a running container using the container's ID or name, either to view its ongoing output or to control it interactively. You can attach to the same contained process multiple times simultaneously, screen sharing style, or quickly view the progress of your daemonized process. You can detach from the container (and leave it running) with `CTRL-p CTRL-q` (for a quiet exit) or `CTRL-c` which will send a `SIGKILL` to the container. When you are attached to a container, and exit its main process, the process's exit code will be returned to the client. It is forbidden to redirect the standard input of a `docker attach` command while attaching to a tty-enabled container (i.e.: launched with `-t`). # OPTIONS **--help** Print usage statement **--no-stdin**=*true*|*false* Do not attach STDIN. The default is *false*. **--sig-proxy**=*true*|*false* Proxy all received signals to the process (non-TTY mode only). SIGCHLD, SIGKILL, and SIGSTOP are not proxied. The default is *true*. # EXAMPLES ## Attaching to a container In this example the top command is run inside a container, from an image called fedora, in detached mode. The ID from the container is passed into the **docker attach** command: # ID=$(sudo docker run -d fedora /usr/bin/top -b) # sudo docker attach $ID top - 02:05:52 up 3:05, 0 users, load average: 0.01, 0.02, 0.05 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.1%us, 0.2%sy, 0.0%ni, 99.7%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 373572k total, 355560k used, 18012k free, 27872k buffers Swap: 786428k total, 0k used, 786428k free, 221740k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 17200 1116 912 R 0 0.3 0:00.03 top top - 02:05:55 up 3:05, 0 users, load average: 0.01, 0.02, 0.05 Tasks: 1 total, 1 running, 0 sleeping, 0 stopped, 0 zombie Cpu(s): 0.0%us, 0.2%sy, 0.0%ni, 99.8%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st Mem: 373572k total, 355244k used, 18328k free, 27872k buffers Swap: 786428k total, 0k used, 786428k free, 221776k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 1 root 20 0 17208 1144 932 R 0 0.3 0:00.03 top # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-build.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-build - Build a new image from the source code at PATH # SYNOPSIS **docker build** [**--help**] [**-f**|**--file**[=*PATH/Dockerfile*]] [**--force-rm**[=*false*]] [**--no-cache**[=*false*]] [**--pull**[=*false*]] [**-q**|**--quiet**[=*false*]] [**--rm**[=*true*]] [**-t**|**--tag**[=*TAG*]] [**-m**|**--memory**[=*MEMORY*]] [**--memory-swap**[=*MEMORY-SWAP*]] [**-c**|**--cpu-shares**[=*0*]] [**--cpu-period**[=*0*]] [**--cpu-quota**[=*0*]] [**--cpuset-cpus**[=*CPUSET-CPUS*]] [**--cpuset-mems**[=*CPUSET-MEMS*]] [**--cgroup-parent**[=*CGROUP-PARENT*]] PATH | URL | - # DESCRIPTION This will read the Dockerfile from the directory specified in **PATH**. It also sends any other files and directories found in the current directory to the Docker daemon. The contents of this directory would be used by **ADD** commands found within the Dockerfile. Warning, this will send a lot of data to the Docker daemon depending on the contents of the current directory. The build is run by the Docker daemon, not by the CLI, so the whole context must be transferred to the daemon. The Docker CLI reports "Sending build context to Docker daemon" when the context is sent to the daemon. When the URL to a tarball archive or to a single Dockerfile is given, no context is sent from the client to the Docker daemon. When a Git repository is set as the **URL**, the repository is cloned locally and then sent as the context. # OPTIONS **-f**, **--file**=*PATH/Dockerfile* Path to the Dockerfile to use. If the path is a relative path and you are building from a local directory, then the path must be relative to that directory. If you are building from a remote URL pointing to either a tarball or a Git repository, then the path must be relative to the root of the remote context. In all cases, the file must be within the build context. The default is *Dockerfile*. **--force-rm**=*true*|*false* Always remove intermediate containers, even after unsuccessful builds. The default is *false*. **--no-cache**=*true*|*false* Do not use cache when building the image. The default is *false*. **--help** Print usage statement **--pull**=*true*|*false* Always attempt to pull a newer version of the image. The default is *false*. **-q**, **--quiet**=*true*|*false* Suppress the verbose output generated by the containers. The default is *false*. **--rm**=*true*|*false* Remove intermediate containers after a successful build. The default is *true*. **-t**, **--tag**="" Repository name (and optionally a tag) to be applied to the resulting image in case of success **-m**, **--memory**=*MEMORY* Memory limit **--memory-swap**=*MEMORY-SWAP* Total memory (memory + swap), '-1' to disable swap. **-c**, **--cpu-shares**=*0* CPU shares (relative weight). By default, all containers get the same proportion of CPU cycles. You can change this proportion by adjusting the container's CPU share weighting relative to the weighting of all other running containers. To modify the proportion from the default of 1024, use the **-c** or **--cpu-shares** flag to set the weighting to 2 or higher. The proportion is only applied when CPU-intensive processes are running. When tasks in one container are idle, the other containers can use the left-over CPU time. The actual amount of CPU time used varies depending on the number of containers running on the system. For example, consider three containers, one has a cpu-share of 1024 and two others have a cpu-share setting of 512. When processes in all three containers attempt to use 100% of CPU, the first container would receive 50% of the total CPU time. If you add a fourth container with a cpu-share of 1024, the first container only gets 33% of the CPU. The remaining containers receive 16.5%, 16.5% and 33% of the CPU. On a multi-core system, the shares of CPU time are distributed across the CPU cores. Even if a container is limited to less than 100% of CPU time, it can use 100% of each individual CPU core. For example, consider a system with more than three cores. If you start one container **{C0}** with **-c=512** running one process, and another container **{C1}** with **-c=1024** running two processes, this can result in the following division of CPU shares: PID container CPU CPU share 100 {C0} 0 100% of CPU0 101 {C1} 1 100% of CPU1 102 {C1} 2 100% of CPU2 **--cpu-period**=*0* Limit the CPU CFS (Completely Fair Scheduler) period. Limit the container's CPU usage. This flag causes the kernel to restrict the container's CPU usage to the period you specify. **--cpu-quota**=*0* Limit the CPU CFS (Completely Fair Scheduler) quota. By default, containers run with the full CPU resource. This flag causes the kernel to restrict the container's CPU usage to the quota you specify. **--cpuset-cpus**=*CPUSET-CPUS* CPUs in which to allow execution (0-3, 0,1). **--cpuset-mems**=*CPUSET-MEMS* Memory nodes (MEMs) in which to allow execution (-1-3, 0,1). Only effective on NUMA systems. For example, if you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1` to ensure the processes in your Docker container only use memory from the first two memory nodes. **--cgroup-parent**=*CGROUP-PARENT* Path to `cgroups` under which the container's `cgroup` are created. If the path is not absolute, the path is considered relative to the `cgroups` path of the init process. Cgroups are created if they do not already exist. # EXAMPLES ## Building an image using a Dockerfile located inside the current directory Docker images can be built using the build command and a Dockerfile: docker build . During the build process Docker creates intermediate images. In order to keep them, you must explicitly set `--rm=false`. docker build --rm=false . A good practice is to make a sub-directory with a related name and create the Dockerfile in that directory. For example, a directory called mongo may contain a Dockerfile to create a Docker MongoDB image. Likewise, another directory called httpd may be used to store Dockerfiles for Apache web server images. It is also a good practice to add the files required for the image to the sub-directory. These files will then be specified with the `COPY` or `ADD` instructions in the `Dockerfile`. Note: If you include a tar file (a good practice), then Docker will automatically extract the contents of the tar file specified within the `ADD` instruction into the specified target. ## Building an image and naming that image A good practice is to give a name to the image you are building. Note that only a-z0-9-_. should be used for consistency. There are no hard rules here but it is best to give the names consideration. The **-t**/**--tag** flag is used to rename an image. Here are some examples: Though it is not a good practice, image names can be arbitrary: docker build -t myimage . A better approach is to provide a fully qualified and meaningful repository, name, and tag (where the tag in this context means the qualifier after the ":"). In this example we build a JBoss image for the Fedora repository and give it the version 1.0: docker build -t fedora/jboss:1.0 The next example is for the "whenry" user repository and uses Fedora and JBoss and gives it the version 2.1 : docker build -t whenry/fedora-jboss:v2.1 If you do not provide a version tag then Docker will assign `latest`: docker build -t whenry/fedora-jboss When you list the images, the image above will have the tag `latest`. So renaming an image is arbitrary but consideration should be given to a useful convention that makes sense for consumers and should also take into account Docker community conventions. ## Building an image using a URL This will clone the specified GitHub repository from the URL and use it as context. The Dockerfile at the root of the repository is used as Dockerfile. This only works if the GitHub repository is a dedicated repository. docker build github.com/scollier/Fedora-Dockerfiles/tree/master/apache Note: You can set an arbitrary Git repository via the `git://` schema. ## Building an image using a URL to a tarball'ed context This will send the URL itself to the Docker daemon. The daemon will fetch the tarball archive, decompress it and use its contents as the build context. If you pass an *-f PATH/Dockerfile* option as well, the system will look for that file inside the contents of the tarball. docker build -f dev/Dockerfile https://10.10.10.1/docker/context.tar.gz Note: supported compression formats are 'xz', 'bzip2', 'gzip' and 'identity' (no compression). # HISTORY March 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit June 2015, updated by Sally O'Malley ================================================ FILE: vendor/github.com/docker/docker/man/docker-commit.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-commit - Create a new image from a container's changes # SYNOPSIS **docker commit** [**-a**|**--author**[=*AUTHOR*]] [**--help**] [**-c**|**--change**[= []**]] [**-m**|**--message**[=*MESSAGE*]] [**-p**|**--pause**[=*true*]] CONTAINER [REPOSITORY[:TAG]] # DESCRIPTION Create a new image from an existing container specified by name or container ID. The new image will contain the contents of the container filesystem, *excluding* any data volumes. While the `docker commit` command is a convenient way of extending an existing image, you should prefer the use of a Dockerfile and `docker build` for generating images that you intend to share with other people. # OPTIONS **-a**, **--author**="" Author (e.g., "John Hannibal Smith ") **-c** , **--change**=[] Apply specified Dockerfile instructions while committing the image Supported Dockerfile instructions: `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`LABEL`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` **--help** Print usage statement **-m**, **--message**="" Commit message **-p**, **--pause**=*true*|*false* Pause container during commit. The default is *true*. # EXAMPLES ## Creating a new image from an existing container An existing Fedora based container has had Apache installed while running in interactive mode with the bash shell. Apache is also running. To create a new image run `docker ps` to find the container's ID and then run: # docker commit -m="Added Apache to Fedora base image" \ -a="A D Ministrator" 98bd7fc99854 fedora/fedora_httpd:20 Note that only a-z0-9-_. are allowed when naming images from an existing container. ## Apply specified Dockerfile instructions while committing the image If an existing container was created without the DEBUG environment variable set to "true", you can create a new image based on that container by first getting the container's ID with `docker ps` and then running: # docker commit -c="ENV DEBUG true" 98bd7fc99854 debug-image # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and in June 2014, updated by Sven Dowideit July 2014, updated by Sven Dowideit Oct 2014, updated by Daniel, Dao Quang Minh June 2015, updated by Sally O'Malley ================================================ FILE: vendor/github.com/docker/docker/man/docker-cp.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-cp - Copy files/folders between a container and the local filesystem. # SYNOPSIS **docker cp** [**--help**] CONTAINER:PATH LOCALPATH|- LOCALPATH|- CONTAINER:PATH # DESCRIPTION In the first synopsis form, the `docker cp` utility copies the contents of `PATH` from the filesystem of `CONTAINER` to the `LOCALPATH` (or stream as a tar archive to `STDOUT` if `-` is specified). In the second synopsis form, the contents of `LOCALPATH` (or a tar archive streamed from `STDIN` if `-` is specified) are copied from the local machine to `PATH` in the filesystem of `CONTAINER`. You can copy to or from either a running or stopped container. The `PATH` can be a file or directory. The `docker cp` command assumes all `CONTAINER:PATH` values are relative to the `/` (root) directory of the container. This means supplying the initial forward slash is optional; The command sees `compassionate_darwin:/tmp/foo/myfile.txt` and `compassionate_darwin:tmp/foo/myfile.txt` as identical. If a `LOCALPATH` value is not absolute, is it considered relative to the current working directory. Behavior is similar to the common Unix utility `cp -a` in that directories are copied recursively with permissions preserved if possible. Ownership is set to the user and primary group on the receiving end of the transfer. For example, files copied to a container will be created with `UID:GID` of the root user. Files copied to the local machine will be created with the `UID:GID` of the user which invoked the `docker cp` command. Assuming a path separator of `/`, a first argument of `SRC_PATH` and second argument of `DST_PATH`, the behavior is as follows: - `SRC_PATH` specifies a file - `DST_PATH` does not exist - the file is saved to a file created at `DST_PATH` - `DST_PATH` does not exist and ends with `/` - Error condition: the destination directory must exist. - `DST_PATH` exists and is a file - the destination is overwritten with the contents of the source file - `DST_PATH` exists and is a directory - the file is copied into this directory using the basename from `SRC_PATH` - `SRC_PATH` specifies a directory - `DST_PATH` does not exist - `DST_PATH` is created as a directory and the *contents* of the source directory are copied into this directory - `DST_PATH` exists and is a file - Error condition: cannot copy a directory to a file - `DST_PATH` exists and is a directory - `SRC_PATH` does not end with `/.` - the source directory is copied into this directory - `SRC_PAPTH` does end with `/.` - the *content* of the source directory is copied into this directory The command requires `SRC_PATH` and `DST_PATH` to exist according to the above rules. If `SRC_PATH` is local and is a symbolic link, the symbolic link, not the target, is copied. A colon (`:`) is used as a delimiter between `CONTAINER` and `PATH`, but `:` could also be in a valid `LOCALPATH`, like `file:name.txt`. This ambiguity is resolved by requiring a `LOCALPATH` with a `:` to be made explicit with a relative or absolute path, for example: `/path/to/file:name.txt` or `./file:name.txt` It is not possible to copy certain system files such as resources under `/proc`, `/sys`, `/dev`, and mounts created by the user in the container. Using `-` as the first argument in place of a `LOCALPATH` will stream the contents of `STDIN` as a tar archive which will be extracted to the `PATH` in the filesystem of the destination container. In this case, `PATH` must specify a directory. Using `-` as the second argument in place of a `LOCALPATH` will stream the contents of the resource from the source container as a tar archive to `STDOUT`. # OPTIONS **--help** Print usage statement # EXAMPLES Suppose a container has finished producing some output as a file it saves to somewhere in its filesystem. This could be the output of a build job or some other computation. You can copy these outputs from the container to a location on your local host. If you want to copy the `/tmp/foo` directory from a container to the existing `/tmp` directory on your host. If you run `docker cp` in your `~` (home) directory on the local host: $ docker cp compassionate_darwin:tmp/foo /tmp Docker creates a `/tmp/foo` directory on your host. Alternatively, you can omit the leading slash in the command. If you execute this command from your home directory: $ docker cp compassionate_darwin:tmp/foo tmp If `~/tmp` does not exist, Docker will create it and copy the contents of `/tmp/foo` from the container into this new directory. If `~/tmp` already exists as a directory, then Docker will copy the contents of `/tmp/foo` from the container into a directory at `~/tmp/foo`. When copying a single file to an existing `LOCALPATH`, the `docker cp` command will either overwrite the contents of `LOCALPATH` if it is a file or place it into `LOCALPATH` if it is a directory, overwriting an existing file of the same name if one exists. For example, this command: $ docker cp sharp_ptolemy:/tmp/foo/myfile.txt /test If `/test` does not exist on the local machine, it will be created as a file with the contents of `/tmp/foo/myfile.txt` from the container. If `/test` exists as a file, it will be overwritten. Lastly, if `/tmp` exists as a directory, the file will be copied to `/test/myfile.txt`. Next, suppose you want to copy a file or folder into a container. For example, this could be a configuration file or some other input to a long running computation that you would like to place into a created container before it starts. This is useful because it does not require the configuration file or other input to exist in the container image. If you have a file, `config.yml`, in the current directory on your local host and wish to copy it to an existing directory at `/etc/my-app.d` in a container, this command can be used: $ docker cp config.yml myappcontainer:/etc/my-app.d If you have several files in a local directory `/config` which you need to copy to a directory `/etc/my-app.d` in a container: $ docker cp /config/. myappcontainer:/etc/my-app.d The above command will copy the contents of the local `/config` directory into the directory `/etc/my-app.d` in the container. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit May 2015, updated by Josh Hawn ================================================ FILE: vendor/github.com/docker/docker/man/docker-create.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-create - Create a new container # SYNOPSIS **docker create** [**-a**|**--attach**[=*[]*]] [**--add-host**[=*[]*]] [**--blkio-weight**[=*[BLKIO-WEIGHT]*]] [**-c**|**--cpu-shares**[=*0*]] [**--cap-add**[=*[]*]] [**--cap-drop**[=*[]*]] [**--cgroup-parent**[=*CGROUP-PATH*]] [**--cidfile**[=*CIDFILE*]] [**--cpu-period**[=*0*]] [**--cpu-quota**[=*0*]] [**--cpuset-cpus**[=*CPUSET-CPUS*]] [**--cpuset-mems**[=*CPUSET-MEMS*]] [**--device**[=*[]*]] [**--dns**[=*[]*]] [**--dns-search**[=*[]*]] [**-e**|**--env**[=*[]*]] [**--entrypoint**[=*ENTRYPOINT*]] [**--env-file**[=*[]*]] [**--expose**[=*[]*]] [**--group-add**[=*[]*]] [**-h**|**--hostname**[=*HOSTNAME*]] [**--help**] [**-i**|**--interactive**[=*false*]] [**--ipc**[=*IPC*]] [**-l**|**--label**[=*[]*]] [**--label-file**[=*[]*]] [**--link**[=*[]*]] [**--log-driver**[=*[]*]] [**--log-opt**[=*[]*]] [**--lxc-conf**[=*[]*]] [**-m**|**--memory**[=*MEMORY*]] [**--mac-address**[=*MAC-ADDRESS*]] [**--memory-swap**[=*MEMORY-SWAP*]] [**--memory-swappiness**[=*MEMORY-SWAPPINESS*]] [**--name**[=*NAME*]] [**--net**[=*"bridge"*]] [**--oom-kill-disable**[=*false*]] [**-P**|**--publish-all**[=*false*]] [**-p**|**--publish**[=*[]*]] [**--pid**[=*[]*]] [**--privileged**[=*false*]] [**--read-only**[=*false*]] [**--restart**[=*RESTART*]] [**--security-opt**[=*[]*]] [**-t**|**--tty**[=*false*]] [**-u**|**--user**[=*USER*]] [**--ulimit**[=*[]*]] [**--uts**[=*[]*]] [**-v**|**--volume**[=*[]*]] [**--volumes-from**[=*[]*]] [**-w**|**--workdir**[=*WORKDIR*]] IMAGE [COMMAND] [ARG...] # DESCRIPTION Creates a writeable container layer over the specified image and prepares it for running the specified command. The container ID is then printed to STDOUT. This is similar to **docker run -d** except the container is never started. You can then use the **docker start ** command to start the container at any point. The initial status of the container created with **docker create** is 'created'. # OPTIONS **-a**, **--attach**=[] Attach to STDIN, STDOUT or STDERR. **--add-host**=[] Add a custom host-to-IP mapping (host:ip) **--blkio-weight**=0 Block IO weight (relative weight) accepts a weight value between 10 and 1000. **-c**, **--cpu-shares**=0 CPU shares (relative weight) **--cap-add**=[] Add Linux capabilities **--cap-drop**=[] Drop Linux capabilities **--cidfile**="" Write the container ID to the file **--cgroup-parent**="" Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist. **--cpu-period**=0 Limit the CPU CFS (Completely Fair Scheduler) period **--cpuset-cpus**="" CPUs in which to allow execution (0-3, 0,1) **--cpuset-mems**="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. If you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1` then processes in your Docker container will only use memory from the first two memory nodes. **-cpu-quota**=0 Limit the CPU CFS (Completely Fair Scheduler) quota **--device**=[] Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm) **--dns-search**=[] Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain) **--dns**=[] Set custom DNS servers **-e**, **--env**=[] Set environment variables **--entrypoint**="" Overwrite the default ENTRYPOINT of the image **--env-file**=[] Read in a line delimited file of environment variables **--expose**=[] Expose a port or a range of ports (e.g. --expose=3300-3310) from the container without publishing it to your host **--group-add**=[] Add additional groups to run as **-h**, **--hostname**="" Container host name **--help** Print usage statement **-i**, **--interactive**=*true*|*false* Keep STDIN open even if not attached. The default is *false*. **--ipc**="" Default is to create a private IPC namespace (POSIX SysV IPC) for the container 'container:': reuses another container shared memory, semaphores and message queues 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure. **-l**, **--label**=[] Adds metadata to a container (e.g., --label=com.example.key=value) **--label-file**=[] Read labels from a file. Delimit each label with an EOL. **--link**=[] Add link to another container in the form of :alias or just in which case the alias will match the name. **--lxc-conf**=[] (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" **--log-driver**="|*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*none*" Logging driver for container. Default is defined by daemon `--log-driver` flag. **Warning**: `docker logs` command works only for `json-file` logging driver. **--log-opt**=[] Logging driver specific options. **-m**, **--memory**="" Memory limit (format: , where unit = b, k, m or g) Allows you to constrain the memory available to a container. If the host supports swap memory, then the **-m** memory setting can be larger than physical RAM. If a limit of 0 is specified (not using **-m**), the container's memory is not limited. The actual limit may be rounded up to a multiple of the operating system's page size (the value would be very large, that's millions of trillions). **--memory-swap**="" Total memory limit (memory + swap) Set `-1` to disable swap (format: , where unit = b, k, m or g). This value should always larger than **-m**, so you should always use this with **-m**. **--mac-address**="" Container MAC address (e.g. 92:d0:c6:0a:29:33) **--name**="" Assign a name to the container **--net**="bridge" Set the Network mode for the container 'bridge': creates a new network stack for the container on the docker bridge 'none': no networking for this container 'container:': reuses another container network stack 'host': use the host network stack inside the container. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure. **--oom-kill-disable**=*true*|*false* Whether to disable OOM Killer for the container or not. **-P**, **--publish-all**=*true*|*false* Publish all exposed ports to random ports on the host interfaces. The default is *false*. **-p**, **--publish**=[] Publish a container's port, or a range of ports, to the host format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort Both hostPort and containerPort can be specified as a range of ports. When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`) (use 'docker port' to see the actual mapping) **--pid**=host Set the PID mode for the container **host**: use the host's PID namespace inside the container. Note: the host mode gives the container full access to local PID and is therefore considered insecure. **--uts**=host Set the UTS mode for the container **host**: use the host's UTS namespace inside the container. Note: the host mode gives the container access to changing the host's hostname and is therefore considered insecure. **--privileged**=*true*|*false* Give extended privileges to this container. The default is *false*. **--read-only**=*true*|*false* Mount the container's root filesystem as read only. **--restart**="no" Restart policy to apply when a container exits (no, on-failure[:max-retry], always) **--security-opt**=[] Security Options **--memory-swappiness**="" Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. **-t**, **--tty**=*true*|*false* Allocate a pseudo-TTY. The default is *false*. **-u**, **--user**="" Username or UID **--ulimit**=[] Ulimit options **-v**, **--volume**=[] Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container) **--volumes-from**=[] Mount volumes from the specified container(s) **-w**, **--workdir**="" Working directory inside the container # HISTORY August 2014, updated by Sven Dowideit September 2014, updated by Sven Dowideit November 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-diff.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-diff - Inspect changes on a container's filesystem # SYNOPSIS **docker diff** [**--help**] CONTAINER # DESCRIPTION Inspect changes on a container's filesystem. You can use the full or shortened container ID or the container name set using **docker run --name** option. # OPTIONS **--help** Print usage statement # EXAMPLES Inspect the changes to on a nginx container: # docker diff 1fdfd1f54c1b C /dev C /dev/console C /dev/core C /dev/stdout C /dev/fd C /dev/ptmx C /dev/stderr C /dev/stdin C /run A /run/nginx.pid C /var/lib/nginx/tmp A /var/lib/nginx/tmp/client_body A /var/lib/nginx/tmp/fastcgi A /var/lib/nginx/tmp/proxy A /var/lib/nginx/tmp/scgi A /var/lib/nginx/tmp/uwsgi C /var/log/nginx A /var/log/nginx/access.log A /var/log/nginx/error.log # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-events.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-events - Get real time events from the server # SYNOPSIS **docker events** [**--help**] [**-f**|**--filter**[=*[]*]] [**--since**[=*SINCE*]] [**--until**[=*UNTIL*]] # DESCRIPTION Get event information from the Docker daemon. Information can include historical information and real-time information. Docker containers will report the following events: create, destroy, die, export, kill, pause, restart, start, stop, unpause and Docker images will report: untag, delete # OPTIONS **--help** Print usage statement **-f**, **--filter**=[] Provide filter values (i.e., 'event=stop') **--since**="" Show all events created since timestamp **--until**="" Stream events until this timestamp You can specify `--since` and `--until` parameters as an RFC 3339 date, a UNIX timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Docker computes the date relative to the client machine’s time. # EXAMPLES ## Listening for Docker events After running docker events a container 786d698004576 is started and stopped (The container name has been shortened in the output below): # docker events 2015-01-28T20:21:31.000000000-08:00 59211849bc10: (from whenry/testimage:latest) start 2015-01-28T20:21:31.000000000-08:00 59211849bc10: (from whenry/testimage:latest) die 2015-01-28T20:21:32.000000000-08:00 59211849bc10: (from whenry/testimage:latest) stop ## Listening for events since a given date Again the output container IDs have been shortened for the purposes of this document: # docker events --since '2015-01-28' 2015-01-28T20:25:38.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) create 2015-01-28T20:25:38.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) start 2015-01-28T20:25:39.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) create 2015-01-28T20:25:39.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) start 2015-01-28T20:25:40.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) die 2015-01-28T20:25:42.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) stop 2015-01-28T20:25:45.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) start 2015-01-28T20:25:45.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) die 2015-01-28T20:25:46.000000000-08:00 c21f6c22ba27: (from whenry/testimage:latest) stop The following example outputs all events that were generated in the last 3 minutes, relative to the current time on the client machine: # docker events --since '3m' 2015-05-12T11:51:30.999999999Z07:00 4386fb97867d: (from ubuntu-1:14.04) die 2015-05-12T15:52:12.999999999Z07:00 4 4386fb97867d: (from ubuntu-1:14.04) stop 2015-05-12T15:53:45.999999999Z07:00 7805c1d35632: (from redis:2.8) die 2015-05-12T15:54:03.999999999Z07:00 7805c1d35632: (from redis:2.8) stop If you do not provide the --since option, the command returns only new and/or live events. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit June 2015, updated by Brian Goff ================================================ FILE: vendor/github.com/docker/docker/man/docker-exec.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-exec - Run a command in a running container # SYNOPSIS **docker exec** [**-d**|**--detach**[=*false*]] [**--help**] [**-i**|**--interactive**[=*false*]] [**-t**|**--tty**[=*false*]] [**-u**|**--user**[=*USER*]] CONTAINER COMMAND [ARG...] # DESCRIPTION Run a process in a running container. The command started using `docker exec` will only run while the container's primary process (`PID 1`) is running, and will not be restarted if the container is restarted. If the container is paused, then the `docker exec` command will wait until the container is unpaused, and then run # OPTIONS **-d**, **--detach**=*true*|*false* Detached mode: run command in the background. The default is *false*. **--help** Print usage statement **-i**, **--interactive**=*true*|*false* Keep STDIN open even if not attached. The default is *false*. **-t**, **--tty**=*true*|*false* Allocate a pseudo-TTY. The default is *false*. **-u**, **--user**="" Sets the username or UID used and optionally the groupname or GID for the specified command. The followings examples are all valid: --user [user | user:group | uid | uid:gid | user:gid | uid:group ] Without this argument the command will be run as root in the container. The **-t** option is incompatible with a redirection of the docker client standard input. # HISTORY November 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-export.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-export - Export the contents of a container's filesystem as a tar archive # SYNOPSIS **docker export** [**--help**] CONTAINER # DESCRIPTION Export the contents of a container's filesystem using the full or shortened container ID or container name. The output is exported to STDOUT and can be redirected to a tar file. Stream to a file instead of STDOUT by using **-o**. # OPTIONS **--help** Print usage statement **-o**, **--output**="" Write to a file, instead of STDOUT # EXAMPLES Export the contents of the container called angry_bell to a tar file called angry_bell.tar: # docker export angry_bell > angry_bell.tar # docker export --output=angry_bell-latest.tar angry_bell # ls -sh angry_bell.tar 321M angry_bell.tar # ls -sh angry_bell-latest.tar 321M angry_bell-latest.tar # See also **docker-import(1)** to create an empty filesystem image and import the contents of the tarball into it, then optionally tag it. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit January 2015, updated by Joseph Kern (josephakern at gmail dot com) ================================================ FILE: vendor/github.com/docker/docker/man/docker-history.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-history - Show the history of an image # SYNOPSIS **docker history** [**--help**] [**--no-trunc**[=*false*]] [**-q**|**--quiet**[=*false*]] IMAGE # DESCRIPTION Show the history of when and how an image was created. # OPTIONS **--help** Print usage statement **-H**. **--human**=*true*|*false* Print sizes and dates in human readable format. The default is *true*. **--no-trunc**=*true*|*false* Don't truncate output. The default is *false*. **-q**, **--quiet**=*true*|*false* Only show numeric IDs. The default is *false*. # EXAMPLES $ docker history fedora IMAGE CREATED CREATED BY SIZE COMMENT 105182bb5e8b 5 days ago /bin/sh -c #(nop) ADD file:71356d2ad59aa3119d 372.7 MB 73bd853d2ea5 13 days ago /bin/sh -c #(nop) MAINTAINER Lokesh Mandvekar 0 B 511136ea3c5a 10 months ago 0 B Imported from - ## Display comments in the image history The `docker commit` command has a **-m** flag for adding comments to the image. These comments will be displayed in the image history. $ sudo docker history docker:scm IMAGE CREATED CREATED BY SIZE COMMENT 2ac9d1098bf1 3 months ago /bin/bash 241.4 MB Added Apache to Fedora base image 88b42ffd1f7c 5 months ago /bin/sh -c #(nop) ADD file:1fd8d7f9f6557cafc7 373.7 MB c69cab00d6ef 5 months ago /bin/sh -c #(nop) MAINTAINER Lokesh Mandvekar 0 B 511136ea3c5a 19 months ago 0 B Imported from - # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-images.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-images - List images # SYNOPSIS **docker images** [**--help**] [**-a**|**--all**[=*false*]] [**--digests**[=*false*]] [**-f**|**--filter**[=*[]*]] [**--no-trunc**[=*false*]] [**-q**|**--quiet**[=*false*]] [REPOSITORY] # DESCRIPTION This command lists the images stored in the local Docker repository. By default, intermediate images, used during builds, are not listed. Some of the output, e.g., image ID, is truncated, for space reasons. However the truncated image ID, and often the first few characters, are enough to be used in other Docker commands that use the image ID. The output includes repository, tag, image ID, date created and the virtual size. The title REPOSITORY for the first title may seem confusing. It is essentially the image name. However, because you can tag a specific image, and multiple tags (image instances) can be associated with a single name, the name is really a repository for all tagged images of the same name. For example consider an image called fedora. It may be tagged with 18, 19, or 20, etc. to manage different versions. # OPTIONS **-a**, **--all**=*true*|*false* Show all images (by default filter out the intermediate image layers). The default is *false*. **--digests**=*true*|*false* Show image digests. The default is *false*. **-f**, **--filter**=[] Filters the output. The dangling=true filter finds unused images. While label=com.foo=amd64 filters for images with a com.foo value of amd64. The label=com.foo filter finds images with the label com.foo of any value. **--help** Print usage statement **--no-trunc**=*true*|*false* Don't truncate output. The default is *false*. **-q**, **--quiet**=*true*|*false* Only show numeric IDs. The default is *false*. # EXAMPLES ## Listing the images To list the images in a local repository (not the registry) run: docker images The list will contain the image repository name, a tag for the image, and an image ID, when it was created and its virtual size. Columns: REPOSITORY, TAG, IMAGE ID, CREATED, and VIRTUAL SIZE. To get a verbose list of images which contains all the intermediate images used in builds use **-a**: docker images -a Previously, the docker images command supported the --tree and --dot arguments, which displayed different visualizations of the image data. Docker core removed this functionality in the 1.7 version. If you liked this functionality, you can still find it in the third-party dockviz tool: https://github.com/justone/dockviz. ## Listing only the shortened image IDs Listing just the shortened image IDs. This can be useful for some automated tools. docker images -q # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-import.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-import - Create an empty filesystem image and import the contents of the tarball (.tar, .tar.gz, .tgz, .bzip, .tar.xz, .txz) into it, then optionally tag it. # SYNOPSIS **docker import** [**-c**|**--change**[= []**]] [**--help**] file|URL|- [REPOSITORY[:TAG]] # OPTIONS **-c**, **--change**=[] Apply specified Dockerfile instructions while importing the image Supported Dockerfile instructions: `CMD`|`ENTRYPOINT`|`ENV`|`EXPOSE`|`ONBUILD`|`USER`|`VOLUME`|`WORKDIR` # DESCRIPTION Create a new filesystem image from the contents of a tarball (`.tar`, `.tar.gz`, `.tgz`, `.bzip`, `.tar.xz`, `.txz`) into it, then optionally tag it. # OPTIONS **--help** Print usage statement # EXAMPLES ## Import from a remote location # docker import http://example.com/exampleimage.tgz example/imagerepo ## Import from a local file Import to docker via pipe and stdin: # cat exampleimage.tgz | docker import - example/imagelocal Import to a Docker image from a local file. # docker import /path/to/exampleimage.tgz ## Import from a local file and tag Import to docker via pipe and stdin: # cat exampleimageV2.tgz | docker import - example/imagelocal:V-2.0 ## Import from a local directory # tar -c . | docker import - exampleimagedir ## Apply specified Dockerfile instructions while importing the image This example sets the docker image ENV variable DEBUG to true by default. # tar -c . | docker import -c="ENV DEBUG true" - exampleimagedir # See also **docker-export(1)** to export the contents of a filesystem as a tar archive to STDOUT. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-info.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-info - Display system-wide information # SYNOPSIS **docker info** [**--help**] # DESCRIPTION This command displays system wide information regarding the Docker installation. Information displayed includes the number of containers and images, pool name, data file, metadata file, data space used, total data space, metadata space used , total metadata space, execution driver, and the kernel version. The data file is where the images are stored and the metadata file is where the meta data regarding those images are stored. When run for the first time Docker allocates a certain amount of data space and meta data space from the space available on the volume where `/var/lib/docker` is mounted. # OPTIONS **--help** Print usage statement # EXAMPLES ## Display Docker system information Here is a sample output: # docker info Containers: 14 Images: 52 Storage Driver: aufs Root Dir: /var/lib/docker/aufs Dirs: 80 Execution Driver: native-0.2 Logging Driver: json-file Kernel Version: 3.13.0-24-generic Operating System: Ubuntu 14.04 LTS CPUs: 1 Total Memory: 2 GiB # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-inspect.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-inspect - Return low-level information on a container or image # SYNOPSIS **docker inspect** [**--help**] [**-f**|**--format**[=*FORMAT*]] [**--type**=*container*|*image*] CONTAINER|IMAGE [CONTAINER|IMAGE...] # DESCRIPTION This displays all the information available in Docker for a given container or image. By default, this will render all results in a JSON array. If a format is specified, the given template will be executed for each result. # OPTIONS **--help** Print usage statement **-f**, **--format**="" Format the output using the given go template. **--type**=*container*|*image* Return JSON for specified type, permissible values are "image" or "container" # EXAMPLES Getting information on an image where image name conflict with the container name, e,g both image and container are named rhel7. $ docker inspect --type=image rhel7 [ { "Id": "fe01a428b9d9de35d29531e9994157978e8c48fa693e1bf1d221dffbbb67b170", "Parent": "10acc31def5d6f249b548e01e8ffbaccfd61af0240c17315a7ad393d022c5ca2", .... } ] ## Getting information on a container To get information on a container use its ID or instance name: $ docker inspect d2cc496561d6 [{ "Id": "d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47", "Created": "2015-06-08T16:18:02.505155285Z", "Path": "bash", "Args": [], "State": { "Running": false, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 0, "ExitCode": 0, "Error": "", "StartedAt": "2015-06-08T16:18:03.643865954Z", "FinishedAt": "2015-06-08T16:57:06.448552862Z" }, "Image": "ded7cd95e059788f2586a51c275a4f151653779d6a7f4dad77c2bd34601d94e4", "NetworkSettings": { "Bridge": "", "EndpointID": "", "Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "HairpinMode": false, "IPAddress": "", "IPPrefixLen": 0, "IPv6Gateway": "", "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "MacAddress": "", "NetworkID": "", "PortMapping": null, "Ports": null, "SandboxKey": "", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null }, "ResolvConfPath": "/var/lib/docker/containers/d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47/resolv.conf", "HostnamePath": "/var/lib/docker/containers/d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47/hostname", "HostsPath": "/var/lib/docker/containers/d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47/hosts", "LogPath": "/var/lib/docker/containers/d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47/d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47-json.log", "Name": "/adoring_wozniak", "RestartCount": 0, "Driver": "devicemapper", "ExecDriver": "native-0.2", "MountLabel": "", "ProcessLabel": "", "Mounts": [ { "Source": "/data", "Destination": "/data", "Mode": "ro,Z", "RW": false } ], "AppArmorProfile": "", "ExecIDs": null, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Memory": 0, "MemorySwap": 0, "CpuShares": 0, "CpuPeriod": 0, "CpusetCpus": "", "CpusetMems": "", "CpuQuota": 0, "BlkioWeight": 0, "OomKillDisable": false, "Privileged": false, "PortBindings": {}, "Links": null, "PublishAllPorts": false, "Dns": null, "DnsSearch": null, "ExtraHosts": null, "VolumesFrom": null, "Devices": [], "NetworkMode": "bridge", "IpcMode": "", "PidMode": "", "UTSMode": "", "CapAdd": null, "CapDrop": null, "RestartPolicy": { "Name": "no", "MaximumRetryCount": 0 }, "SecurityOpt": null, "ReadonlyRootfs": false, "Ulimits": null, "LogConfig": { "Type": "json-file", "Config": {} }, "CgroupParent": "" }, "GraphDriver": { "Name": "devicemapper", "Data": { "DeviceId": "5", "DeviceName": "docker-253:1-2763198-d2cc496561d6d520cbc0236b4ba88c362c446a7619992123f11c809cded25b47", "DeviceSize": "171798691840" } }, "Config": { "Hostname": "d2cc496561d6", "Domainname": "", "User": "", "AttachStdin": true, "AttachStdout": true, "AttachStderr": true, "ExposedPorts": null, "Tty": true, "OpenStdin": true, "StdinOnce": true, "Env": null, "Cmd": [ "bash" ], "Image": "fedora", "Volumes": null, "VolumeDriver": "", "WorkingDir": "", "Entrypoint": null, "NetworkDisabled": false, "MacAddress": "", "OnBuild": null, "Labels": {}, "Memory": 0, "MemorySwap": 0, "CpuShares": 0, "Cpuset": "" } } ] ## Getting the IP address of a container instance To get the IP address of a container use: $ docker inspect --format='{{.NetworkSettings.IPAddress}}' d2cc496561d6 172.17.0.2 ## Listing all port bindings One can loop over arrays and maps in the results to produce simple text output: $ docker inspect --format='{{range $p, $conf := .NetworkSettings.Ports}} \ {{$p}} -> {{(index $conf 0).HostPort}} {{end}}' d2cc496561d6 80/tcp -> 80 You can get more information about how to write a go template from: http://golang.org/pkg/text/template/. ## Getting information on an image Use an image's ID or name (e.g., repository/name[:tag]) to get information on it. $ docker inspect ded7cd95e059 [{ "Id": "ded7cd95e059788f2586a51c275a4f151653779d6a7f4dad77c2bd34601d94e4", "Parent": "48ecf305d2cf7046c1f5f8fcbcd4994403173441d4a7f125b1bb0ceead9de731", "Comment": "", "Created": "2015-05-27T16:58:22.937503085Z", "Container": "76cf7f67d83a7a047454b33007d03e32a8f474ad332c3a03c94537edd22b312b", "ContainerConfig": { "Hostname": "76cf7f67d83a", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "/bin/sh", "-c", "#(nop) ADD file:4be46382bcf2b095fcb9fe8334206b584eff60bb3fad8178cbd97697fcb2ea83 in /" ], "Image": "48ecf305d2cf7046c1f5f8fcbcd4994403173441d4a7f125b1bb0ceead9de731", "Volumes": null, "VolumeDriver": "", "WorkingDir": "", "Entrypoint": null, "NetworkDisabled": false, "MacAddress": "", "OnBuild": null, "Labels": {} }, "DockerVersion": "1.6.0", "Author": "Lokesh Mandvekar \u003clsm5@fedoraproject.org\u003e", "Config": { "Hostname": "76cf7f67d83a", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": null, "Image": "48ecf305d2cf7046c1f5f8fcbcd4994403173441d4a7f125b1bb0ceead9de731", "Volumes": null, "VolumeDriver": "", "WorkingDir": "", "Entrypoint": null, "NetworkDisabled": false, "MacAddress": "", "OnBuild": null, "Labels": {} }, "Architecture": "amd64", "Os": "linux", "Size": 186507296, "VirtualSize": 186507296, "GraphDriver": { "Name": "devicemapper", "Data": { "DeviceId": "3", "DeviceName": "docker-253:1-2763198-ded7cd95e059788f2586a51c275a4f151653779d6a7f4dad77c2bd34601d94e4", "DeviceSize": "171798691840" } } } ] # HISTORY April 2014, originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit April 2015, updated by Qiang Huang ================================================ FILE: vendor/github.com/docker/docker/man/docker-kill.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-kill - Kill a running container using SIGKILL or a specified signal # SYNOPSIS **docker kill** [**--help**] [**-s**|**--signal**[=*"KILL"*]] CONTAINER [CONTAINER...] # DESCRIPTION The main process inside each container specified will be sent SIGKILL, or any signal specified with option --signal. # OPTIONS **--help** Print usage statement **-s**, **--signal**="KILL" Signal to send to the container # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-load.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-load - Load an image from a tar archive or STDIN # SYNOPSIS **docker load** [**--help**] [**-i**|**--input**[=*INPUT*]] # DESCRIPTION Loads a tarred repository from a file or the standard input stream. Restores both images and tags. # OPTIONS **--help** Print usage statement **-i**, **--input**="" Read from a tar archive file, instead of STDIN # EXAMPLES $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE busybox latest 769b9341d937 7 weeks ago 2.489 MB $ docker load --input fedora.tar $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE busybox latest 769b9341d937 7 weeks ago 2.489 MB fedora rawhide 0d20aec6529d 7 weeks ago 387 MB fedora 20 58394af37342 7 weeks ago 385.5 MB fedora heisenbug 58394af37342 7 weeks ago 385.5 MB fedora latest 58394af37342 7 weeks ago 385.5 MB # See also **docker-save(1)** to save an image(s) to a tar archive (streamed to STDOUT by default). # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-login.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-login - Register or log in to a Docker registry. # SYNOPSIS **docker login** [**-e**|**--email**[=*EMAIL*]] [**--help**] [**-p**|**--password**[=*PASSWORD*]] [**-u**|**--username**[=*USERNAME*]] [SERVER] # DESCRIPTION Register or log in to a Docker Registry located on the specified `SERVER`. You can specify a URL or a `hostname` for the `SERVER` value. If you do not specify a `SERVER`, the command uses Docker's public registry located at `https://registry-1.docker.io/` by default. To get a username/password for Docker's public registry, create an account on Docker Hub. You can log into any public or private repository for which you have credentials. When you log in, the command stores encoded credentials in `$HOME/.docker/config.json` on Linux or `%USERPROFILE%/.docker/config.json` on Windows. # OPTIONS **-e**, **--email**="" Email **--help** Print usage statement **-p**, **--password**="" Password **-u**, **--username**="" Username # EXAMPLES ## Login to a registry on your localhost # docker login localhost:8080 # See also **docker-logout(1)** to log out from a Docker registry. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit April 2015, updated by Mary Anthony for v2 ================================================ FILE: vendor/github.com/docker/docker/man/docker-logout.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-logout - Log out from a Docker registry. # SYNOPSIS **docker logout** [SERVER] # DESCRIPTION Log out of a Docker Registry located on the specified `SERVER`. You can specify a URL or a `hostname` for the `SERVER` value. If you do not specify a `SERVER`, the command attempts to log you out of Docker's public registry located at `https://registry-1.docker.io/` by default. # OPTIONS There are no available options. # EXAMPLES ## Log out from a registry on your localhost # docker logout localhost:8080 # See also **docker-login(1)** to register or log in to a Docker registry server. # HISTORY June 2014, Originally compiled by Daniel, Dao Quang Minh (daniel at nitrous dot io) July 2014, updated by Sven Dowideit April 2015, updated by Mary Anthony for v2 ================================================ FILE: vendor/github.com/docker/docker/man/docker-logs.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-logs - Fetch the logs of a container # SYNOPSIS **docker logs** [**-f**|**--follow**[=*false*]] [**--help**] [**--since**[=*SINCE*]] [**-t**|**--timestamps**[=*false*]] [**--tail**[=*"all"*]] CONTAINER # DESCRIPTION The **docker logs** command batch-retrieves whatever logs are present for a container at the time of execution. This does not guarantee execution order when combined with a docker run (i.e., your run may not have generated any logs at the time you execute docker logs). The **docker logs --follow** command combines commands **docker logs** and **docker attach**. It will first return all logs from the beginning and then continue streaming new output from the container’s stdout and stderr. **Warning**: This command works only for **json-file** logging driver. # OPTIONS **--help** Print usage statement **-f**, **--follow**=*true*|*false* Follow log output. The default is *false*. **--since**="" Show logs since timestamp **-t**, **--timestamps**=*true*|*false* Show timestamps. The default is *false*. **--tail**="all" Output the specified number of lines at the end of logs (defaults to all logs) The `--since` option shows only the container logs generated after a given date. You can specify the date as an RFC 3339 date, a UNIX timestamp, or a Go duration string (e.g. `1m30s`, `3h`). Docker computes the date relative to the client machine’s time. You can combine the `--since` option with either or both of the `--follow` or `--tail` options. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit July 2014, updated by Sven Dowideit April 2015, updated by Ahmet Alp Balkan ================================================ FILE: vendor/github.com/docker/docker/man/docker-pause.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-pause - Pause all processes within a container # SYNOPSIS **docker pause** CONTAINER [CONTAINER...] # DESCRIPTION The `docker pause` command uses the cgroups freezer to suspend all processes in a container. Traditionally when suspending a process the `SIGSTOP` signal is used, which is observable by the process being suspended. With the cgroups freezer the process is unaware, and unable to capture, that it is being suspended, and subsequently resumed. See the [cgroups freezer documentation] (https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) for further details. # OPTIONS There are no available options. # See also **docker-unpause(1)** to unpause all processes within a container. # HISTORY June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-port.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-port - List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT # SYNOPSIS **docker port** [**--help**] CONTAINER [PRIVATE_PORT[/PROTO]] # DESCRIPTION List port mappings for the CONTAINER, or lookup the public-facing port that is NAT-ed to the PRIVATE_PORT # OPTIONS **--help** Print usage statement # EXAMPLES # docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b650456536c7 busybox:latest top 54 minutes ago Up 54 minutes 0.0.0.0:1234->9876/tcp, 0.0.0.0:4321->7890/tcp test ## Find out all the ports mapped # docker port test 7890/tcp -> 0.0.0.0:4321 9876/tcp -> 0.0.0.0:1234 ## Find out a specific mapping # docker port test 7890/tcp 0.0.0.0:4321 # docker port test 7890 0.0.0.0:4321 ## An example showing error for non-existent mapping # docker port test 7890/udp 2014/06/24 11:53:36 Error: No public port '7890/udp' published for test # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) June 2014, updated by Sven Dowideit November 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-ps.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % FEBRUARY 2015 # NAME docker-ps - List containers # SYNOPSIS **docker ps** [**-a**|**--all**[=*false*]] [**--before**[=*BEFORE*]] [**--help**] [**-f**|**--filter**[=*[]*]] [**-l**|**--latest**[=*false*]] [**-n**[=*-1*]] [**--no-trunc**[=*false*]] [**-q**|**--quiet**[=*false*]] [**-s**|**--size**[=*false*]] [**--since**[=*SINCE*]] # DESCRIPTION List the containers in the local repository. By default this shows only the running containers. # OPTIONS **-a**, **--all**=*true*|*false* Show all containers. Only running containers are shown by default. The default is *false*. **--before**="" Show only containers created before Id or Name, including non-running containers. **--help** Print usage statement **-f**, **--filter**=[] Provide filter values. Valid filters: exited= - containers with exit code of label= or label== status=(created|restarting|running|paused|exited) name= - container's name id= - container's ID **-l**, **--latest**=*true*|*false* Show only the latest created container, include non-running ones. The default is *false*. **-n**=-1 Show n last created containers, include non-running ones. **--no-trunc**=*true*|*false* Don't truncate output. The default is *false*. **-q**, **--quiet**=*true*|*false* Only display numeric IDs. The default is *false*. **-s**, **--size**=*true*|*false* Display total file sizes. The default is *false*. **--since**="" Show only containers created since Id or Name, include non-running ones. # EXAMPLES # Display all containers, including non-running # docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a87ecb4f327c fedora:20 /bin/sh -c #(nop) MA 20 minutes ago Exit 0 desperate_brattain 01946d9d34d8 vpavlin/rhel7:latest /bin/sh -c #(nop) MA 33 minutes ago Exit 0 thirsty_bell c1d3b0166030 acffc0358b9e /bin/sh -c yum -y up 2 weeks ago Exit 1 determined_torvalds 41d50ecd2f57 fedora:20 /bin/sh -c #(nop) MA 2 weeks ago Exit 0 drunk_pike # Display only IDs of all containers, including non-running # docker ps -a -q a87ecb4f327c 01946d9d34d8 c1d3b0166030 41d50ecd2f57 # Display only IDs of all containers that have the name `determined_torvalds` # docker ps -a -q --filter=name=determined_torvalds c1d3b0166030 # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit August 2014, updated by Sven Dowideit November 2014, updated by Sven Dowideit February 2015, updated by André Martins ================================================ FILE: vendor/github.com/docker/docker/man/docker-pull.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-pull - Pull an image or a repository from a registry # SYNOPSIS **docker pull** [**-a**|**--all-tags**[=*false*]] [**--help**] NAME[:TAG] | [REGISTRY_HOST[:REGISTRY_PORT]/]NAME[:TAG] # DESCRIPTION This command pulls down an image or a repository from a registry. If there is more than one image for a repository (e.g., fedora) then all images for that repository name are pulled down including any tags. If you do not specify a `REGISTRY_HOST`, the command uses Docker's public registry located at `registry-1.docker.io` by default. # OPTIONS **-a**, **--all-tags**=*true*|*false* Download all tagged images in the repository. The default is *false*. **--help** Print usage statement # EXAMPLE # Pull a repository with multiple images # Note that if the image is previously downloaded then the status would be # 'Status: Image is up to date for fedora' $ docker pull fedora Pulling repository fedora ad57ef8d78d7: Download complete 105182bb5e8b: Download complete 511136ea3c5a: Download complete 73bd853d2ea5: Download complete Status: Downloaded newer image for fedora $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE fedora rawhide ad57ef8d78d7 5 days ago 359.3 MB fedora 20 105182bb5e8b 5 days ago 372.7 MB fedora heisenbug 105182bb5e8b 5 days ago 372.7 MB fedora latest 105182bb5e8b 5 days ago 372.7 MB # Pull an image, manually specifying path to Docker's public registry and tag # Note that if the image is previously downloaded then the status would be # 'Status: Image is up to date for registry.hub.docker.com/fedora:20' $ docker pull registry.hub.docker.com/fedora:20 Pulling repository fedora 3f2fed40e4b0: Download complete 511136ea3c5a: Download complete fd241224e9cf: Download complete Status: Downloaded newer image for registry.hub.docker.com/fedora:20 $ docker images REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE fedora 20 3f2fed40e4b0 4 days ago 372.7 MB # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit August 2014, updated by Sven Dowideit April 2015, updated by John Willis April 2015, updated by Mary Anthony for v2 ================================================ FILE: vendor/github.com/docker/docker/man/docker-push.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-push - Push an image or a repository to a registry # SYNOPSIS **docker push** [**--help**] NAME[:TAG] | [REGISTRY_HOST[:REGISTRY_PORT]/]NAME[:TAG] # DESCRIPTION This command pushes an image or a repository to a registry. If you do not specify a `REGISTRY_HOST`, the command uses Docker's public registry located at `registry-1.docker.io` by default. # OPTIONS **--help** Print usage statement # EXAMPLES # Pushing a new image to a registry First save the new image by finding the container ID (using **docker ps**) and then committing it to a new image name. Note that only a-z0-9-_. are allowed when naming images: # docker commit c16378f943fe rhel-httpd Now, push the image to the registry using the image ID. In this example the registry is on host named `registry-host` and listening on port `5000`. To do this, tag the image with the host name or IP address, and the port of the registry: # docker tag rhel-httpd registry-host:5000/myadmin/rhel-httpd # docker push registry-host:5000/myadmin/rhel-httpd Check that this worked by running: # docker images You should see both `rhel-httpd` and `registry-host:5000/myadmin/rhel-httpd` listed. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit April 2015, updated by Mary Anthony for v2 June 2015, updated by Sally O'Malley ================================================ FILE: vendor/github.com/docker/docker/man/docker-rename.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % OCTOBER 2014 # NAME docker-rename - Rename a container # SYNOPSIS **docker rename** OLD_NAME NEW_NAME # OPTIONS There are no available options. ================================================ FILE: vendor/github.com/docker/docker/man/docker-restart.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-restart - Restart a running container # SYNOPSIS **docker restart** [**--help**] [**-t**|**--time**[=*10*]] CONTAINER [CONTAINER...] # DESCRIPTION Restart each container listed. # OPTIONS **--help** Print usage statement **-t**, **--time**=10 Number of seconds to try to stop for before killing the container. Once killed it will then be restarted. Default is 10 seconds. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-rm.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-rm - Remove one or more containers # SYNOPSIS **docker rm** [**-f**|**--force**[=*false*]] [**-l**|**--link**[=*false*]] [**-v**|**--volumes**[=*false*]] CONTAINER [CONTAINER...] # DESCRIPTION **docker rm** will remove one or more containers from the host node. The container name or ID can be used. This does not remove images. You cannot remove a running container unless you use the \fB-f\fR option. To see all containers on a host use the **docker ps -a** command. # OPTIONS **--help** Print usage statement **-f**, **--force**=*true*|*false* Force the removal of a running container (uses SIGKILL). The default is *false*. **-l**, **--link**=*true*|*false* Remove the specified link and not the underlying container. The default is *false*. **-v**, **--volumes**=*true*|*false* Remove the volumes associated with the container. The default is *false*. # EXAMPLES ##Removing a container using its ID## To remove a container using its ID, find either from a **docker ps -a** command, or use the ID returned from the **docker run** command, or retrieve it from a file used to store it using the **docker run --cidfile**: docker rm abebf7571666 ##Removing a container using the container name## The name of the container can be found using the **docker ps -a** command. The use that name as follows: docker rm hopeful_morse # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit July 2014, updated by Sven Dowideit August 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-rmi.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-rmi - Remove one or more images # SYNOPSIS **docker rmi** [**-f**|**--force**[=*false*]] [**--help**] [**--no-prune**[=*false*]] IMAGE [IMAGE...] # DESCRIPTION Removes one or more images from the host node. This does not remove images from a registry. You cannot remove an image of a running container unless you use the **-f** option. To see all images on a host use the **docker images** command. # OPTIONS **-f**, **--force**=*true*|*false* Force removal of the image. The default is *false*. **--help** Print usage statement **--no-prune**=*true*|*false* Do not delete untagged parents. The default is *false*. # EXAMPLES ## Removing an image Here is an example of removing an image: docker rmi fedora/httpd # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit April 2015, updated by Mary Anthony for v2 ================================================ FILE: vendor/github.com/docker/docker/man/docker-run.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-run - Run a command in a new container # SYNOPSIS **docker run** [**-a**|**--attach**[=*[]*]] [**--add-host**[=*[]*]] [**--blkio-weight**[=*[BLKIO-WEIGHT]*]] [**-c**|**--cpu-shares**[=*0*]] [**--cap-add**[=*[]*]] [**--cap-drop**[=*[]*]] [**--cgroup-parent**[=*CGROUP-PATH*]] [**--cidfile**[=*CIDFILE*]] [**--cpu-period**[=*0*]] [**--cpu-quota**[=*0*]] [**--cpuset-cpus**[=*CPUSET-CPUS*]] [**--cpuset-mems**[=*CPUSET-MEMS*]] [**-d**|**--detach**[=*false*]] [**--device**[=*[]*]] [**--dns**[=*[]*]] [**--dns-search**[=*[]*]] [**-e**|**--env**[=*[]*]] [**--entrypoint**[=*ENTRYPOINT*]] [**--env-file**[=*[]*]] [**--expose**[=*[]*]] [**--group-add**[=*[]*]] [**-h**|**--hostname**[=*HOSTNAME*]] [**--help**] [**-i**|**--interactive**[=*false*]] [**--ipc**[=*IPC*]] [**-l**|**--label**[=*[]*]] [**--label-file**[=*[]*]] [**--link**[=*[]*]] [**--log-driver**[=*[]*]] [**--log-opt**[=*[]*]] [**--lxc-conf**[=*[]*]] [**-m**|**--memory**[=*MEMORY*]] [**--mac-address**[=*MAC-ADDRESS*]] [**--memory-swap**[=*MEMORY-SWAP*]] [**--memory-swappiness**[=*MEMORY-SWAPPINESS*]] [**--name**[=*NAME*]] [**--net**[=*"bridge"*]] [**--oom-kill-disable**[=*false*]] [**-P**|**--publish-all**[=*false*]] [**-p**|**--publish**[=*[]*]] [**--pid**[=*[]*]] [**--privileged**[=*false*]] [**--read-only**[=*false*]] [**--restart**[=*RESTART*]] [**--rm**[=*false*]] [**--security-opt**[=*[]*]] [**--sig-proxy**[=*true*]] [**-t**|**--tty**[=*false*]] [**-u**|**--user**[=*USER*]] [**-v**|**--volume**[=*[]*]] [**--ulimit**[=*[]*]] [**--uts**[=*[]*]] [**--volumes-from**[=*[]*]] [**-w**|**--workdir**[=*WORKDIR*]] IMAGE [COMMAND] [ARG...] # DESCRIPTION Run a process in a new container. **docker run** starts a process with its own file system, its own networking, and its own isolated process tree. The IMAGE which starts the process may define defaults related to the process that will be run in the container, the networking to expose, and more, but **docker run** gives final control to the operator or administrator who starts the container from the image. For that reason **docker run** has more options than any other Docker command. If the IMAGE is not already loaded then **docker run** will pull the IMAGE, and all image dependencies, from the repository in the same way running **docker pull** IMAGE, before it starts the container from that image. # OPTIONS **-a**, **--attach**=[] Attach to STDIN, STDOUT or STDERR. In foreground mode (the default when **-d** is not specified), **docker run** can start the process in the container and attach the console to the process’s standard input, output, and standard error. It can even pretend to be a TTY (this is what most commandline executables expect) and pass along signals. The **-a** option can be set for each of stdin, stdout, and stderr. **--add-host**=[] Add a custom host-to-IP mapping (host:ip) Add a line to /etc/hosts. The format is hostname:ip. The **--add-host** option can be set multiple times. **--blkio-weight**=0 Block IO weight (relative weight) accepts a weight value between 10 and 1000. **-c**, **--cpu-shares**=0 CPU shares (relative weight) By default, all containers get the same proportion of CPU cycles. This proportion can be modified by changing the container's CPU share weighting relative to the weighting of all other running containers. To modify the proportion from the default of 1024, use the **-c** or **--cpu-shares** flag to set the weighting to 2 or higher. The proportion will only apply when CPU-intensive processes are running. When tasks in one container are idle, other containers can use the left-over CPU time. The actual amount of CPU time will vary depending on the number of containers running on the system. For example, consider three containers, one has a cpu-share of 1024 and two others have a cpu-share setting of 512. When processes in all three containers attempt to use 100% of CPU, the first container would receive 50% of the total CPU time. If you add a fourth container with a cpu-share of 1024, the first container only gets 33% of the CPU. The remaining containers receive 16.5%, 16.5% and 33% of the CPU. On a multi-core system, the shares of CPU time are distributed over all CPU cores. Even if a container is limited to less than 100% of CPU time, it can use 100% of each individual CPU core. For example, consider a system with more than three cores. If you start one container **{C0}** with **-c=512** running one process, and another container **{C1}** with **-c=1024** running two processes, this can result in the following division of CPU shares: PID container CPU CPU share 100 {C0} 0 100% of CPU0 101 {C1} 1 100% of CPU1 102 {C1} 2 100% of CPU2 **--cap-add**=[] Add Linux capabilities **--cap-drop**=[] Drop Linux capabilities **--cgroup-parent**="" Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist. **--cidfile**="" Write the container ID to the file **--cpu-period**=0 Limit the CPU CFS (Completely Fair Scheduler) period Limit the container's CPU usage. This flag tell the kernel to restrict the container's CPU usage to the period you specify. **--cpuset-cpus**="" CPUs in which to allow execution (0-3, 0,1) **--cpuset-mems**="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. If you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1` then processes in your Docker container will only use memory from the first two memory nodes. **--cpu-quota**=0 Limit the CPU CFS (Completely Fair Scheduler) quota Limit the container's CPU usage. By default, containers run with the full CPU resource. This flag tell the kernel to restrict the container's CPU usage to the quota you specify. **-d**, **--detach**=*true*|*false* Detached mode: run the container in the background and print the new container ID. The default is *false*. At any time you can run **docker ps** in the other shell to view a list of the running containers. You can reattach to a detached container with **docker attach**. If you choose to run a container in the detached mode, then you cannot use the **-rm** option. When attached in the tty mode, you can detach from a running container without stopping the process by pressing the keys CTRL-P CTRL-Q. **--device**=[] Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm) **--dns-search**=[] Set custom DNS search domains (Use --dns-search=. if you don't wish to set the search domain) **--dns**=[] Set custom DNS servers This option can be used to override the DNS configuration passed to the container. Typically this is necessary when the host DNS configuration is invalid for the container (e.g., 127.0.0.1). When this is the case the **--dns** flags is necessary for every run. **-e**, **--env**=[] Set environment variables This option allows you to specify arbitrary environment variables that are available for the process that will be launched inside of the container. **--entrypoint**="" Overwrite the default ENTRYPOINT of the image This option allows you to overwrite the default entrypoint of the image that is set in the Dockerfile. The ENTRYPOINT of an image is similar to a COMMAND because it specifies what executable to run when the container starts, but it is (purposely) more difficult to override. The ENTRYPOINT gives a container its default nature or behavior, so that when you set an ENTRYPOINT you can run the container as if it were that binary, complete with default options, and you can pass in more options via the COMMAND. But, sometimes an operator may want to run something else inside the container, so you can override the default ENTRYPOINT at runtime by using a **--entrypoint** and a string to specify the new ENTRYPOINT. **--env-file**=[] Read in a line delimited file of environment variables **--expose**=[] Expose a port, or a range of ports (e.g. --expose=3300-3310), from the container without publishing it to your host **--group-add**=[] Add additional groups to run as **-h**, **--hostname**="" Container host name Sets the container host name that is available inside the container. **--help** Print usage statement **-i**, **--interactive**=*true*|*false* Keep STDIN open even if not attached. The default is *false*. When set to true, keep stdin open even if not attached. The default is false. **--ipc**="" Default is to create a private IPC namespace (POSIX SysV IPC) for the container 'container:': reuses another container shared memory, semaphores and message queues 'host': use the host shared memory,semaphores and message queues inside the container. Note: the host mode gives the container full access to local shared memory and is therefore considered insecure. **-l**, **--label**=[] Set metadata on the container (e.g., --label com.example.key=value) **--label-file**=[] Read in a line delimited file of labels **--link**=[] Add link to another container in the form of :alias or just in which case the alias will match the name If the operator uses **--link** when starting the new client container, then the client container can access the exposed port via a private networking interface. Docker will set some environment variables in the client container to help indicate which interface and port to use. **--lxc-conf**=[] (lxc exec-driver only) Add custom lxc options --lxc-conf="lxc.cgroup.cpuset.cpus = 0,1" **--log-driver**="|*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*none*" Logging driver for container. Default is defined by daemon `--log-driver` flag. **Warning**: `docker logs` command works only for `json-file` logging driver. **--log-opt**=[] Logging driver specific options. **-m**, **--memory**="" Memory limit (format: , where unit = b, k, m or g) Allows you to constrain the memory available to a container. If the host supports swap memory, then the **-m** memory setting can be larger than physical RAM. If a limit of 0 is specified (not using **-m**), the container's memory is not limited. The actual limit may be rounded up to a multiple of the operating system's page size (the value would be very large, that's millions of trillions). **--memory-swap**="" Total memory limit (memory + swap) Set `-1` to disable swap (format: , where unit = b, k, m or g). This value should always larger than **-m**, so you should always use this with **-m**. **--mac-address**="" Container MAC address (e.g. 92:d0:c6:0a:29:33) Remember that the MAC address in an Ethernet network must be unique. The IPv6 link-local address will be based on the device's MAC address according to RFC4862. **--name**="" Assign a name to the container The operator can identify a container in three ways: UUID long identifier (“f78375b1c487e03c9438c729345e54db9d20cfa2ac1fc3494b6eb60872e74778”) UUID short identifier (“f78375b1c487”) Name (“jonah”) The UUID identifiers come from the Docker daemon, and if a name is not assigned to the container with **--name** then the daemon will also generate a random string name. The name is useful when defining links (see **--link**) (or any other place you need to identify a container). This works for both background and foreground Docker containers. **--net**="bridge" Set the Network mode for the container 'bridge': creates a new network stack for the container on the docker bridge 'none': no networking for this container 'container:': reuses another container network stack 'host': use the host network stack inside the container. Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure. **--oom-kill-disable**=*true*|*false* Whether to disable OOM Killer for the container or not. **-P**, **--publish-all**=*true*|*false* Publish all exposed ports to random ports on the host interfaces. The default is *false*. When set to true publish all exposed ports to the host interfaces. The default is false. If the operator uses -P (or -p) then Docker will make the exposed port accessible on the host and the ports will be available to any client that can reach the host. When using -P, Docker will bind any exposed port to a random port on the host within an *ephemeral port range* defined by `/proc/sys/net/ipv4/ip_local_port_range`. To find the mapping between the host ports and the exposed ports, use `docker port`. **-p**, **--publish**=[] Publish a container's port, or range of ports, to the host. format: ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort Both hostPort and containerPort can be specified as a range of ports. When specifying ranges for both, the number of container ports in the range must match the number of host ports in the range. (e.g., `-p 1234-1236:1234-1236/tcp`) (use 'docker port' to see the actual mapping) **--pid**=host Set the PID mode for the container **host**: use the host's PID namespace inside the container. Note: the host mode gives the container full access to local PID and is therefore considered insecure. **--uts**=host Set the UTS mode for the container **host**: use the host's UTS namespace inside the container. Note: the host mode gives the container access to changing the host's hostname and is therefore considered insecure. **--privileged**=*true*|*false* Give extended privileges to this container. The default is *false*. By default, Docker containers are “unprivileged” (=false) and cannot, for example, run a Docker daemon inside the Docker container. This is because by default a container is not allowed to access any devices. A “privileged” container is given access to all devices. When the operator executes **docker run --privileged**, Docker will enable access to all devices on the host as well as set some configuration in AppArmor to allow the container nearly all the same access to the host as processes running outside of a container on the host. **--read-only**=*true*|*false* Mount the container's root filesystem as read only. By default a container will have its root filesystem writable allowing processes to write files anywhere. By specifying the `--read-only` flag the container will have its root filesystem mounted as read only prohibiting any writes. **--restart**="no" Restart policy to apply when a container exits (no, on-failure[:max-retry], always) **--rm**=*true*|*false* Automatically remove the container when it exits (incompatible with -d). The default is *false*. **--security-opt**=[] Security Options "label:user:USER" : Set the label user for the container "label:role:ROLE" : Set the label role for the container "label:type:TYPE" : Set the label type for the container "label:level:LEVEL" : Set the label level for the container "label:disable" : Turn off label confinement for the container **--sig-proxy**=*true*|*false* Proxy received signals to the process (non-TTY mode only). SIGCHLD, SIGSTOP, and SIGKILL are not proxied. The default is *true*. **--memory-swappiness**="" Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. **-t**, **--tty**=*true*|*false* Allocate a pseudo-TTY. The default is *false*. When set to true Docker can allocate a pseudo-tty and attach to the standard input of any container. This can be used, for example, to run a throwaway interactive shell. The default is value is false. The **-t** option is incompatible with a redirection of the docker client standard input. **-u**, **--user**="" Sets the username or UID used and optionally the groupname or GID for the specified command. The followings examples are all valid: --user [user | user:group | uid | uid:gid | user:gid | uid:group ] Without this argument the command will be run as root in the container. ""--ulimit""=[] Ulimit options **-v**, **--volume**=[] Bind mount a volume (e.g., from the host: -v /host:/container, from Docker: -v /container) The **-v** option can be used one or more times to add one or more mounts to a container. These mounts can then be used in other containers using the **--volumes-from** option. The volume may be optionally suffixed with :ro or :rw to mount the volumes in read-only or read-write mode, respectively. By default, the volumes are mounted read-write. See examples. Labeling systems like SELinux require that proper labels are placed on volume content mounted into a container. Without a label, the security system might prevent the processes running inside the container from using the content. By default, Docker does not change the labels set by the OS. To change a label in the container context, you can add either of two suffixes `:z` or `:Z` to the volume mount. These suffixes tell Docker to relabel file objects on the shared volumes. The `z` option tells Docker that two containers share the volume content. As a result, Docker labels the content with a shared content label. Shared volume labels allow all containers to read/write content. The `Z` option tells Docker to label the content with a private unshared label. Only the current container can use a private volume. Note: Multiple Volume options can be added separated by a "," **--volumes-from**=[] Mount volumes from the specified container(s) Mounts already mounted volumes from a source container onto another container. You must supply the source's container-id. To share a volume, use the **--volumes-from** option when running the target container. You can share volumes even if the source container is not running. By default, Docker mounts the volumes in the same mode (read-write or read-only) as it is mounted in the source container. Optionally, you can change this by suffixing the container-id with either the `:ro` or `:rw ` keyword. If the location of the volume from the source container overlaps with data residing on a target container, then the volume hides that data on the target. **-w**, **--workdir**="" Working directory inside the container The default working directory for running binaries within a container is the root directory (/). The developer can set a different default with the Dockerfile WORKDIR instruction. The operator can override the working directory by using the **-w** option. # EXAMPLES ## Exposing log messages from the container to the host's log If you want messages that are logged in your container to show up in the host's syslog/journal then you should bind mount the /dev/log directory as follows. # docker run -v /dev/log:/dev/log -i -t fedora /bin/bash From inside the container you can test this by sending a message to the log. (bash)# logger "Hello from my container" Then exit and check the journal. # exit # journalctl -b | grep Hello This should list the message sent to logger. ## Attaching to one or more from STDIN, STDOUT, STDERR If you do not specify -a then Docker will attach everything (stdin,stdout,stderr) . You can specify to which of the three standard streams (stdin, stdout, stderr) you’d like to connect instead, as in: # docker run -a stdin -a stdout -i -t fedora /bin/bash ## Sharing IPC between containers Using shm_server.c available here: https://www.cs.cf.ac.uk/Dave/C/node27.html Testing `--ipc=host` mode: Host shows a shared memory segment with 7 pids attached, happens to be from httpd: ``` $ sudo ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x01128e25 0 root 600 1000 7 ``` Now run a regular container, and it correctly does NOT see the shared memory segment from the host: ``` $ docker run -it shm ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status ``` Run a container with the new `--ipc=host` option, and it now sees the shared memory segment from the host httpd: ``` $ docker run -it --ipc=host shm ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x01128e25 0 root 600 1000 7 ``` Testing `--ipc=container:CONTAINERID` mode: Start a container with a program to create a shared memory segment: ``` $ docker run -it shm bash $ sudo shm/shm_server & $ sudo ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x0000162e 0 root 666 27 1 ``` Create a 2nd container correctly shows no shared memory segment from 1st container: ``` $ docker run shm ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status ``` Create a 3rd container using the new --ipc=container:CONTAINERID option, now it shows the shared memory segment from the first: ``` $ docker run -it --ipc=container:ed735b2264ac shm ipcs -m $ sudo ipcs -m ------ Shared Memory Segments -------- key shmid owner perms bytes nattch status 0x0000162e 0 root 666 27 1 ``` ## Linking Containers The link feature allows multiple containers to communicate with each other. For example, a container whose Dockerfile has exposed port 80 can be run and named as follows: # docker run --name=link-test -d -i -t fedora/httpd A second container, in this case called linker, can communicate with the httpd container, named link-test, by running with the **--link=:** # docker run -t -i --link=link-test:lt --name=linker fedora /bin/bash Now the container linker is linked to container link-test with the alias lt. Running the **env** command in the linker container shows environment variables with the LT (alias) context (**LT_**) # env HOSTNAME=668231cb0978 TERM=xterm LT_PORT_80_TCP=tcp://172.17.0.3:80 LT_PORT_80_TCP_PORT=80 LT_PORT_80_TCP_PROTO=tcp LT_PORT=tcp://172.17.0.3:80 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PWD=/ LT_NAME=/linker/lt SHLVL=1 HOME=/ LT_PORT_80_TCP_ADDR=172.17.0.3 _=/usr/bin/env When linking two containers Docker will use the exposed ports of the container to create a secure tunnel for the parent to access. ## Mapping Ports for External Usage The exposed port of an application can be mapped to a host port using the **-p** flag. For example, a httpd port 80 can be mapped to the host port 8080 using the following: # docker run -p 8080:80 -d -i -t fedora/httpd ## Creating and Mounting a Data Volume Container Many applications require the sharing of persistent data across several containers. Docker allows you to create a Data Volume Container that other containers can mount from. For example, create a named container that contains directories /var/volume1 and /tmp/volume2. The image will need to contain these directories so a couple of RUN mkdir instructions might be required for you fedora-data image: # docker run --name=data -v /var/volume1 -v /tmp/volume2 -i -t fedora-data true # docker run --volumes-from=data --name=fedora-container1 -i -t fedora bash Multiple --volumes-from parameters will bring together multiple data volumes from multiple containers. And it's possible to mount the volumes that came from the DATA container in yet another container via the fedora-container1 intermediary container, allowing to abstract the actual data source from users of that data: # docker run --volumes-from=fedora-container1 --name=fedora-container2 -i -t fedora bash ## Mounting External Volumes To mount a host directory as a container volume, specify the absolute path to the directory and the absolute path for the container directory separated by a colon: # docker run -v /var/db:/data1 -i -t fedora bash When using SELinux, be aware that the host has no knowledge of container SELinux policy. Therefore, in the above example, if SELinux policy is enforced, the `/var/db` directory is not writable to the container. A "Permission Denied" message will occur and an avc: message in the host's syslog. To work around this, at time of writing this man page, the following command needs to be run in order for the proper SELinux policy type label to be attached to the host directory: # chcon -Rt svirt_sandbox_file_t /var/db Now, writing to the /data1 volume in the container will be allowed and the changes will also be reflected on the host in /var/db. ## Using alternative security labeling You can override the default labeling scheme for each container by specifying the `--security-opt` flag. For example, you can specify the MCS/MLS level, a requirement for MLS systems. Specifying the level in the following command allows you to share the same content between containers. # docker run --security-opt label:level:s0:c100,c200 -i -t fedora bash An MLS example might be: # docker run --security-opt label:level:TopSecret -i -t rhel7 bash To disable the security labeling for this container versus running with the `--permissive` flag, use the following command: # docker run --security-opt label:disable -i -t fedora bash If you want a tighter security policy on the processes within a container, you can specify an alternate type for the container. You could run a container that is only allowed to listen on Apache ports by executing the following command: # docker run --security-opt label:type:svirt_apache_t -i -t centos bash Note: You would have to write policy defining a `svirt_apache_t` type. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit July 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-save.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-save - Save an image(s) to a tar archive (streamed to STDOUT by default) # SYNOPSIS **docker save** [**--help**] [**-o**|**--output**[=*OUTPUT*]] IMAGE [IMAGE...] # DESCRIPTION Produces a tarred repository to the standard output stream. Contains all parent layers, and all tags + versions, or specified repo:tag. Stream to a file instead of STDOUT by using **-o**. # OPTIONS **--help** Print usage statement **-o**, **--output**="" Write to a file, instead of STDOUT # EXAMPLES Save all fedora repository images to a fedora-all.tar and save the latest fedora image to a fedora-latest.tar: $ docker save fedora > fedora-all.tar $ docker save --output=fedora-latest.tar fedora:latest $ ls -sh fedora-all.tar 721M fedora-all.tar $ ls -sh fedora-latest.tar 367M fedora-latest.tar # See also **docker-load(1)** to load an image from a tar archive on STDIN. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit November 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-search.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-search - Search the Docker Hub for images # SYNOPSIS **docker search** [**--automated**[=*false*]] [**--help**] [**--no-trunc**[=*false*]] [**-s**|**--stars**[=*0*]] TERM # DESCRIPTION Search Docker Hub for images that match the specified `TERM`. The table of images returned displays the name, description (truncated by default), number of stars awarded, whether the image is official, and whether it is automated. *Note* - Search queries will only return up to 25 results # OPTIONS **--automated**=*true*|*false* Only show automated builds. The default is *false*. **--help** Print usage statement **--no-trunc**=*true*|*false* Don't truncate output. The default is *false*. **-s**, **--stars**=0 Only displays with at least x stars # EXAMPLES ## Search Docker Hub for ranked images Search a registry for the term 'fedora' and only display those images ranked 3 or higher: $ docker search -s 3 fedora NAME DESCRIPTION STARS OFFICIAL AUTOMATED mattdm/fedora A basic Fedora image corresponding roughly... 50 fedora (Semi) Official Fedora base image. 38 mattdm/fedora-small A small Fedora image on which to build. Co... 8 goldmann/wildfly A WildFly application server running on a ... 3 [OK] ## Search Docker Hub for automated images Search Docker Hub for the term 'fedora' and only display automated images ranked 1 or higher: $ docker search -s 1 fedora NAME DESCRIPTION STARS OFFICIAL AUTOMATED goldmann/wildfly A WildFly application server running on a ... 3 [OK] tutum/fedora-20 Fedora 20 image with SSH access. For the r... 1 [OK] # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit April 2015, updated by Mary Anthony for v2 ================================================ FILE: vendor/github.com/docker/docker/man/docker-start.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-start - Start one or more stopped containers # SYNOPSIS **docker start** [**-a**|**--attach**[=*false*]] [**--help**] [**-i**|**--interactive**[=*false*]] CONTAINER [CONTAINER...] # DESCRIPTION Start one or more stopped containers. # OPTIONS **-a**, **--attach**=*true*|*false* Attach container's STDOUT and STDERR and forward all signals to the process. The default is *false*. **--help** Print usage statement **-i**, **--interactive**=*true*|*false* Attach container's STDIN. The default is *false*. # See also **docker-stop(1)** to stop a running container. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-stats.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-stats - Display a live stream of one or more containers' resource usage statistics # SYNOPSIS **docker stats** [**--help**] CONTAINER [CONTAINER...] # DESCRIPTION Display a live stream of one or more containers' resource usage statistics # OPTIONS **--help** Print usage statement **--no-stream**="false" Disable streaming stats and only pull the first result # EXAMPLES Run **docker stats** with multiple containers. $ docker stats redis1 redis2 CONTAINER CPU % MEM USAGE/LIMIT MEM % NET I/O redis1 0.07% 796 KB/64 MB 1.21% 788 B/648 B redis2 0.07% 2.746 MB/64 MB 4.29% 1.266 KB/648 B ================================================ FILE: vendor/github.com/docker/docker/man/docker-stop.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-stop - Stop a running container by sending SIGTERM and then SIGKILL after a grace period # SYNOPSIS **docker stop** [**--help**] [**-t**|**--time**[=*10*]] CONTAINER [CONTAINER...] # DESCRIPTION Stop a running container (Send SIGTERM, and then SIGKILL after grace period) # OPTIONS **--help** Print usage statement **-t**, **--time**=10 Number of seconds to wait for the container to stop before killing it. Default is 10 seconds. #See also **docker-start(1)** to restart a stopped container. # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-tag.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-tag - Tag an image into a repository # SYNOPSIS **docker tag** [**-f**|**--force**[=*false*]] [**--help**] IMAGE[:TAG] [REGISTRY_HOST/][USERNAME/]NAME[:TAG] # DESCRIPTION Assigns a new alias to an image in a registry. An alias refers to the entire image name including the optional `TAG` after the ':'. If you do not specify a `REGISTRY_HOST`, the command uses Docker's public registry located at `registry-1.docker.io` by default. # "OPTIONS" **-f**, **--force**=*true*|*false* When set to true, force the alias. The default is *false*. **REGISTRYHOST** The hostname of the registry if required. This may also include the port separated by a ':' **USERNAME** The username or other qualifying identifier for the image. **NAME** The image name. **TAG** The tag you are assigning to the image. Though this is arbitrary it is recommended to be used for a version to distinguish images with the same name. Also, for consistency tags should only include a-z0-9-_. . Note that here TAG is a part of the overall name or "tag". # OPTIONS **-f**, **--force**=*true*|*false* Force. The default is *false*. # EXAMPLES ## Giving an image a new alias Here is an example of aliasing an image (e.g., 0e5574283393) as "httpd" and tagging it into the "fedora" repository with "version1.0": docker tag 0e5574283393 fedora/httpd:version1.0 ## Tagging an image for a private repository To push an image to an private registry and not the central Docker registry you must tag it with the registry hostname and port (if needed). docker tag 0e5574283393 myregistryhost:5000/fedora/httpd:version1.0 # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit July 2014, updated by Sven Dowideit April 2015, updated by Mary Anthony for v2 June 2015, updated by Sally O'Malley ================================================ FILE: vendor/github.com/docker/docker/man/docker-top.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-top - Display the running processes of a container # SYNOPSIS **docker top** [**--help**] CONTAINER [ps OPTIONS] # DESCRIPTION Display the running process of the container. ps-OPTION can be any of the options you would pass to a Linux ps command. # OPTIONS **--help** Print usage statement # EXAMPLES Run **docker top** with the ps option of -x: $ docker top 8601afda2b -x PID TTY STAT TIME COMMAND 16623 ? Ss 0:00 sleep 99999 # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. June 2014, updated by Sven Dowideit June 2015, updated by Ma Shimiao ================================================ FILE: vendor/github.com/docker/docker/man/docker-unpause.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2014 # NAME docker-unpause - Unpause all processes within a container # SYNOPSIS **docker unpause** CONTAINER [CONTAINER...] # DESCRIPTION The `docker unpause` command uses the cgroups freezer to un-suspend all processes in a container. See the [cgroups freezer documentation] (https://www.kernel.org/doc/Documentation/cgroups/freezer-subsystem.txt) for further details. # OPTIONS There are no available options. # See also **docker-pause(1)** to pause all processes within a container. # HISTORY June 2014, updated by Sven Dowideit ================================================ FILE: vendor/github.com/docker/docker/man/docker-version.1.md ================================================ % DOCKER(1) Docker User Manuals % Docker Community % JUNE 2015 # NAME docker-version - Show the Docker version information. # SYNOPSIS **docker version** [**--help**] [**-f**|**--format**[=*FORMAT*]] # DESCRIPTION This command displays version information for both the Docker client and daemon. # OPTIONS **--help** Print usage statement **-f**, **--format**="" Format the output using the given go template. # EXAMPLES ## Display Docker version information The default output: $ docker version Client: Version: 1.8.0 API version: 1.20 Go version: go1.4.2 Git commit: f5bae0a Built: Tue Jun 23 17:56:00 UTC 2015 OS/Arch: linux/amd64 Server: Version: 1.8.0 API version: 1.20 Go version: go1.4.2 Git commit: f5bae0a Built: Tue Jun 23 17:56:00 UTC 2015 OS/Arch: linux/amd64 Get server version: $ docker version --format '{{.Server.Version}}' 1.8.0 Dump raw data: To view all available fields, you can use the format `{{json .}}`. $ docker version --format '{{json .}}' {"Client":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"amd64","BuildTime":"Tue Jun 23 17:56:00 UTC 2015"},"ServerOK":true,"Server":{"Version":"1.8.0","ApiVersion":"1.20","GitCommit":"f5bae0a","GoVersion":"go1.4.2","Os":"linux","Arch":"amd64","KernelVersion":"3.13.2-gentoo","BuildTime":"Tue Jun 23 17:56:00 UTC 2015"}} # HISTORY June 2014, updated by Sven Dowideit June 2015, updated by John Howard June 2015, updated by Patrick Hemmer ================================================ FILE: vendor/github.com/docker/docker/man/docker.1.md ================================================ % DOCKER(1) Docker User Manuals % William Henry % APRIL 2014 # NAME docker \- Docker image and container command line interface # SYNOPSIS **docker** [OPTIONS] COMMAND [arg...] # DESCRIPTION **docker** has two distinct functions. It is used for starting the Docker daemon and to run the CLI (i.e., to command the daemon to manage images, containers etc.) So **docker** is both a server, as a daemon, and a client to the daemon, through the CLI. To run the Docker daemon you do not specify any of the commands listed below but must specify the **-d** option. The other options listed below are for the daemon only. The Docker CLI has over 30 commands. The commands are listed below and each has its own man page which explain usage and arguments. To see the man page for a command run **man docker **. # OPTIONS **-h**, **--help** Print usage statement **--api-cors-header**="" Set CORS headers in the remote API. Default is cors disabled. Give urls like "http://foo, http://bar, ...". Give "*" to allow all. **-b**, **--bridge**="" Attach containers to a pre\-existing network bridge; use 'none' to disable container networking **--bip**="" Use the provided CIDR notation address for the dynamically created bridge (docker0); Mutually exclusive of \-b **--config**="" Specifies the location of the Docker client configuration files. The default is '~/.docker'. **-D**, **--debug**=*true*|*false* Enable debug mode. Default is false. **-d**, **--daemon**=*true*|*false* Enable daemon mode. Default is false. **--default-gateway**="" IPv4 address of the container default gateway; this address must be part of the bridge subnet (which is defined by \-b or \--bip) **--default-gateway-v6**="" IPv6 address of the container default gateway **--dns**="" Force Docker to use specific DNS servers **-e**, **--exec-driver**="" Force Docker to use specific exec driver. Default is `native`. **--exec-opt**=[] Set exec driver options. See EXEC DRIVER OPTIONS. **--exec-root**="" Path to use as the root of the Docker execdriver. Default is `/var/run/docker`. **--fixed-cidr**="" IPv4 subnet for fixed IPs (e.g., 10.20.0.0/16); this subnet must be nested in the bridge subnet (which is defined by \-b or \-\-bip) **--fixed-cidr-v6**="" IPv6 subnet for global IPv6 addresses (e.g., 2a00:1450::/64) **-G**, **--group**="" Group to assign the unix socket specified by -H when running in daemon mode. use '' (the empty string) to disable setting of a group. Default is `docker`. **-g**, **--graph**="" Path to use as the root of the Docker runtime. Default is `/var/lib/docker`. **-H**, **--host**=[unix:///var/run/docker.sock]: tcp://[host:port] to bind or unix://[/path/to/socket] to use. The socket(s) to bind to in daemon mode specified using one or more tcp://host:port, unix:///path/to/socket, fd://* or fd://socketfd. **--icc**=*true*|*false* Allow unrestricted inter\-container and Docker daemon host communication. If disabled, containers can still be linked together using **--link** option (see **docker-run(1)**). Default is true. **--ip**="" Default IP address to use when binding container ports. Default is `0.0.0.0`. **--ip-forward**=*true*|*false* Enables IP forwarding on the Docker host. The default is `true`. This flag interacts with the IP forwarding setting on your host system's kernel. If your system has IP forwarding disabled, this setting enables it. If your system has IP forwarding enabled, setting this flag to `--ip-forward=false` has no effect. This setting will also enable IPv6 forwarding if you have both `--ip-forward=true` and `--fixed-cidr-v6` set. Note that this may reject Router Advertisements and interfere with the host's existing IPv6 configuration. For more information, please consult the documentation about "Advanced Networking - IPv6". **--ip-masq**=*true*|*false* Enable IP masquerading for bridge's IP range. Default is true. **--iptables**=*true*|*false* Enable Docker's addition of iptables rules. Default is true. **--ipv6**=*true*|*false* Enable IPv6 support. Default is false. Docker will create an IPv6-enabled bridge with address fe80::1 which will allow you to create IPv6-enabled containers. Use together with `--fixed-cidr-v6` to provide globally routable IPv6 addresses. IPv6 forwarding will be enabled if not used with `--ip-forward=false`. This may collide with your host's current IPv6 settings. For more information please consult the documentation about "Advanced Networking - IPv6". **-l**, **--log-level**="*debug*|*info*|*warn*|*error*|*fatal*"" Set the logging level. Default is `info`. **--label**="[]" Set key=value labels to the daemon (displayed in `docker info`) **--log-driver**="*json-file*|*syslog*|*journald*|*gelf*|*fluentd*|*none*" Default driver for container logs. Default is `json-file`. **Warning**: `docker logs` command works only for `json-file` logging driver. **--log-opt**=[] Logging driver specific options. **--mtu**=VALUE Set the containers network mtu. Default is `0`. **-p**, **--pidfile**="" Path to use for daemon PID file. Default is `/var/run/docker.pid` **--registry-mirror**=:// Prepend a registry mirror to be used for image pulls. May be specified multiple times. **-s**, **--storage-driver**="" Force the Docker runtime to use a specific storage driver. **--selinux-enabled**=*true*|*false* Enable selinux support. Default is false. SELinux does not presently support the BTRFS storage driver. **--storage-opt**=[] Set storage driver options. See STORAGE DRIVER OPTIONS. **-tls**=*true*|*false* Use TLS; implied by --tlsverify. Default is false. **-tlsverify**=*true*|*false* Use TLS and verify the remote (daemon: verify client, client: verify daemon). Default is false. **--userland-proxy**=*true*|*false* Rely on a userland proxy implementation for inter-container and outside-to-container loopback communications. Default is true. **-v**, **--version**=*true*|*false* Print version information and quit. Default is false. # COMMANDS **attach** Attach to a running container See **docker-attach(1)** for full documentation on the **attach** command. **build** Build an image from a Dockerfile See **docker-build(1)** for full documentation on the **build** command. **commit** Create a new image from a container's changes See **docker-commit(1)** for full documentation on the **commit** command. **cp** Copy files/folders from a container's filesystem to the host See **docker-cp(1)** for full documentation on the **cp** command. **create** Create a new container See **docker-create(1)** for full documentation on the **create** command. **diff** Inspect changes on a container's filesystem See **docker-diff(1)** for full documentation on the **diff** command. **events** Get real time events from the server See **docker-events(1)** for full documentation on the **events** command. **exec** Run a command in a running container See **docker-exec(1)** for full documentation on the **exec** command. **export** Stream the contents of a container as a tar archive See **docker-export(1)** for full documentation on the **export** command. **history** Show the history of an image See **docker-history(1)** for full documentation on the **history** command. **images** List images See **docker-images(1)** for full documentation on the **images** command. **import** Create a new filesystem image from the contents of a tarball See **docker-import(1)** for full documentation on the **import** command. **info** Display system-wide information See **docker-info(1)** for full documentation on the **info** command. **inspect** Return low-level information on a container or image See **docker-inspect(1)** for full documentation on the **inspect** command. **kill** Kill a running container (which includes the wrapper process and everything inside it) See **docker-kill(1)** for full documentation on the **kill** command. **load** Load an image from a tar archive See **docker-load(1)** for full documentation on the **load** command. **login** Register or login to a Docker Registry See **docker-login(1)** for full documentation on the **login** command. **logout** Log the user out of a Docker Registry See **docker-logout(1)** for full documentation on the **logout** command. **logs** Fetch the logs of a container See **docker-logs(1)** for full documentation on the **logs** command. **pause** Pause all processes within a container See **docker-pause(1)** for full documentation on the **pause** command. **port** Lookup the public-facing port which is NAT-ed to PRIVATE_PORT See **docker-port(1)** for full documentation on the **port** command. **ps** List containers See **docker-ps(1)** for full documentation on the **ps** command. **pull** Pull an image or a repository from a Docker Registry See **docker-pull(1)** for full documentation on the **pull** command. **push** Push an image or a repository to a Docker Registry See **docker-push(1)** for full documentation on the **push** command. **restart** Restart a running container See **docker-restart(1)** for full documentation on the **restart** command. **rm** Remove one or more containers See **docker-rm(1)** for full documentation on the **rm** command. **rmi** Remove one or more images See **docker-rmi(1)** for full documentation on the **rmi** command. **run** Run a command in a new container See **docker-run(1)** for full documentation on the **run** command. **save** Save an image to a tar archive See **docker-save(1)** for full documentation on the **save** command. **search** Search for an image in the Docker index See **docker-search(1)** for full documentation on the **search** command. **start** Start a stopped container See **docker-start(1)** for full documentation on the **start** command. **stats** Display a live stream of one or more containers' resource usage statistics See **docker-stats(1)** for full documentation on the **stats** command. **stop** Stop a running container See **docker-stop(1)** for full documentation on the **stop** command. **tag** Tag an image into a repository See **docker-tag(1)** for full documentation on the **tag** command. **top** Lookup the running processes of a container See **docker-top(1)** for full documentation on the **top** command. **unpause** Unpause all processes within a container See **docker-unpause(1)** for full documentation on the **unpause** command. **version** Show the Docker version information See **docker-version(1)** for full documentation on the **version** command. **wait** Block until a container stops, then print its exit code See **docker-wait(1)** for full documentation on the **wait** command. # STORAGE DRIVER OPTIONS Docker uses storage backends (known as "graphdrivers" in the Docker internals) to create writable containers from images. Many of these backends use operating system level technologies and can be configured. Specify options to the storage backend with **--storage-opt** flags. The only backend that currently takes options is *devicemapper*. Therefore use these flags with **-s=**devicemapper. Specifically for devicemapper, the default is a "loopback" model which requires no pre-configuration, but is extremely inefficient. Do not use it in production. To make the best use of Docker with the devicemapper backend, you must have a recent version of LVM. Use `lvm` to create a thin pool; for more information see `man lvmthin`. Then, use `--storage-opt dm.thinpooldev` to tell the Docker engine to use that pool for allocating images and container snapshots. Here is the list of *devicemapper* options: #### dm.thinpooldev Specifies a custom block storage device to use for the thin pool. If using a block device for device mapper storage, it is best to use `lvm` to create and manage the thin-pool volume. This volume is then handed to Docker to create snapshot volumes needed for images and containers. Managing the thin-pool outside of Docker makes for the most feature-rich method of having Docker utilize device mapper thin provisioning as the backing storage for Docker's containers. The highlights of the LVM-based thin-pool management feature include: automatic or interactive thin-pool resize support, dynamically changing thin-pool features, automatic thinp metadata checking when lvm activates the thin-pool, etc. Example use: `docker -d --storage-opt dm.thinpooldev=/dev/mapper/thin-pool` #### dm.basesize Specifies the size to use when creating the base device, which limits the size of images and containers. The default value is 10G. Note, thin devices are inherently "sparse", so a 10G device which is mostly empty doesn't use 10 GB of space on the pool. However, the filesystem will use more space for base images the larger the device is. This value affects the system-wide "base" empty filesystem that may already be initialized and inherited by pulled images. Typically, a change to this value requires additional steps to take effect: $ sudo service docker stop $ sudo rm -rf /var/lib/docker $ sudo service docker start Example use: `docker -d --storage-opt dm.basesize=20G` #### dm.fs Specifies the filesystem type to use for the base device. The supported options are `ext4` and `xfs`. The default is `ext4`. Example use: `docker -d --storage-opt dm.fs=xfs` #### dm.mkfsarg Specifies extra mkfs arguments to be used when creating the base device. Example use: `docker -d --storage-opt "dm.mkfsarg=-O ^has_journal"` #### dm.mountopt Specifies extra mount options used when mounting the thin devices. Example use: `docker -d --storage-opt dm.mountopt=nodiscard` #### dm.use_deferred_removal Enables use of deferred device removal if `libdm` and the kernel driver support the mechanism. Deferred device removal means that if device is busy when devices are being removed/deactivated, then a deferred removal is scheduled on device. And devices automatically go away when last user of the device exits. For example, when a container exits, its associated thin device is removed. If that device has leaked into some other mount namespace and can't be removed, the container exit still succeeds and this option causes the system to schedule the device for deferred removal. It does not wait in a loop trying to remove a busy device. Example use: `docker -d --storage-opt dm.use_deferred_removal=true` #### dm.loopdatasize **Note**: This option configures devicemapper loopback, which should not be used in production. Specifies the size to use when creating the loopback file for the "data" device which is used for the thin pool. The default size is 100G. The file is sparse, so it will not initially take up this much space. Example use: `docker -d --storage-opt dm.loopdatasize=200G` #### dm.loopmetadatasize **Note**: This option configures devicemapper loopback, which should not be used in production. Specifies the size to use when creating the loopback file for the "metadadata" device which is used for the thin pool. The default size is 2G. The file is sparse, so it will not initially take up this much space. Example use: `docker -d --storage-opt dm.loopmetadatasize=4G` #### dm.datadev (Deprecated, use `dm.thinpooldev`) Specifies a custom blockdevice to use for data for a Docker-managed thin pool. It is better to use `dm.thinpooldev` - see the documentation for it above for discussion of the advantages. #### dm.metadatadev (Deprecated, use `dm.thinpooldev`) Specifies a custom blockdevice to use for metadata for a Docker-managed thin pool. See `dm.datadev` for why this is deprecated. #### dm.blocksize Specifies a custom blocksize to use for the thin pool. The default blocksize is 64K. Example use: `docker -d --storage-opt dm.blocksize=512K` #### dm.blkdiscard Enables or disables the use of `blkdiscard` when removing devicemapper devices. This is disabled by default due to the additional latency, but as a special case with loopback devices it will be enabled, in order to re-sparsify the loopback file on image/container removal. Disabling this on loopback can lead to *much* faster container removal times, but it also prevents the space used in `/var/lib/docker` directory from being returned to the system for other use when containers are removed. Example use: `docker -d --storage-opt dm.blkdiscard=false` #### dm.override_udev_sync_check By default, the devicemapper backend attempts to synchronize with the `udev` device manager for the Linux kernel. This option allows disabling that synchronization, to continue even though the configuration may be buggy. To view the `udev` sync support of a Docker daemon that is using the `devicemapper` driver, run: $ docker info [...] Udev Sync Supported: true [...] When `udev` sync support is `true`, then `devicemapper` and `udev` can coordinate the activation and deactivation of devices for containers. When `udev` sync support is `false`, a race condition occurs between the`devicemapper` and `udev` during create and cleanup. The race condition results in errors and failures. (For information on these failures, see [docker#4036](https://github.com/docker/docker/issues/4036)) To allow the `docker` daemon to start, regardless of whether `udev` sync is `false`, set `dm.override_udev_sync_check` to true: $ docker -d --storage-opt dm.override_udev_sync_check=true When this value is `true`, the driver continues and simply warns you the errors are happening. **Note**: The ideal is to pursue a `docker` daemon and environment that does support synchronizing with `udev`. For further discussion on this topic, see [docker#4036](https://github.com/docker/docker/issues/4036). Otherwise, set this flag for migrating existing Docker daemons to a daemon with a supported environment. # EXEC DRIVER OPTIONS Use the **--exec-opt** flags to specify options to the exec-driver. The only driver that accepts this flag is the *native* (libcontainer) driver. As a result, you must also specify **-s=**native for this option to have effect. The following is the only *native* option: #### native.cgroupdriver Specifies the management of the container's `cgroups`. You can specify `cgroupfs` or `systemd`. If you specify `systemd` and it is not available, the system uses `cgroupfs`. #### Client For specific client examples please see the man page for the specific Docker command. For example: man docker-run # HISTORY April 2014, Originally compiled by William Henry (whenry at redhat dot com) based on docker.com source material and internal work. ================================================ FILE: vendor/github.com/docker/docker/man/md2man-all.sh ================================================ #!/bin/bash set -e # get into this script's directory cd "$(dirname "$(readlink -f "$BASH_SOURCE")")" [ "$1" = '-q' ] || { set -x pwd } for FILE in *.md; do base="$(basename "$FILE")" name="${base%.md}" num="${name##*.}" if [ -z "$num" -o "$name" = "$num" ]; then # skip files that aren't of the format xxxx.N.md (like README.md) continue fi mkdir -p "./man${num}" go-md2man -in "$FILE" -out "./man${num}/${name}" done ================================================ FILE: vendor/github.com/docker/docker/opts/envfile.go ================================================ package opts import ( "bufio" "fmt" "os" "regexp" "strings" ) var ( // EnvironmentVariableRegexp A regexp to validate correct environment variables // Environment variables set by the user must have a name consisting solely of // alphabetics, numerics, and underscores - the first of which must not be numeric. EnvironmentVariableRegexp = regexp.MustCompile("^[[:alpha:]_][[:alpha:][:digit:]_]*$") ) // ParseEnvFile Read in a line delimited file with environment variables enumerated 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) for scanner.Scan() { line := scanner.Text() // 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 !EnvironmentVariableRegexp.MatchString(variable) { return []string{}, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", 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) } ================================================ FILE: vendor/github.com/docker/docker/opts/envfile_test.go ================================================ package opts import ( "bufio" "fmt" "io/ioutil" "os" "reflect" "strings" "testing" ) func tmpFileWithContent(content string, t *testing.T) string { tmpFile, err := ioutil.TempFile("", "envfile-test") if err != nil { t.Fatal(err) } defer tmpFile.Close() tmpFile.WriteString(content) return tmpFile.Name() } // Test ParseEnvFile for a file with a few well formatted lines func TestParseEnvFileGoodFile(t *testing.T) { content := `foo=bar baz=quux # comment _foobar=foobaz ` tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) lines, err := ParseEnvFile(tmpFile) if err != nil { t.Fatal(err) } expectedLines := []string{ "foo=bar", "baz=quux", "_foobar=foobaz", } if !reflect.DeepEqual(lines, expectedLines) { t.Fatal("lines not equal to expected_lines") } } // Test ParseEnvFile for an empty file func TestParseEnvFileEmptyFile(t *testing.T) { tmpFile := tmpFileWithContent("", t) defer os.Remove(tmpFile) lines, err := ParseEnvFile(tmpFile) if err != nil { t.Fatal(err) } if len(lines) != 0 { t.Fatal("lines not empty; expected empty") } } // Test ParseEnvFile for a non existent file func TestParseEnvFileNonExistentFile(t *testing.T) { _, err := ParseEnvFile("foo_bar_baz") if err == nil { t.Fatal("ParseEnvFile succeeded; expected failure") } if _, ok := err.(*os.PathError); !ok { t.Fatalf("Expected a PathError, got [%v]", err) } } // Test ParseEnvFile for a badly formatted file func TestParseEnvFileBadlyFormattedFile(t *testing.T) { content := `foo=bar f =quux ` tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) _, err := ParseEnvFile(tmpFile) if err == nil { t.Fatalf("Expected a ErrBadEnvVariable, got nothing") } if _, ok := err.(ErrBadEnvVariable); !ok { t.Fatalf("Expected a ErrBadEnvVariable, got [%v]", err) } expectedMessage := "poorly formatted environment: variable 'f ' is not a valid environment variable" if err.Error() != expectedMessage { t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) } } // Test ParseEnvFile for a file with a line exeeding bufio.MaxScanTokenSize func TestParseEnvFileLineTooLongFile(t *testing.T) { content := strings.Repeat("a", bufio.MaxScanTokenSize+42) content = fmt.Sprint("foo=", content) tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) _, err := ParseEnvFile(tmpFile) if err == nil { t.Fatal("ParseEnvFile succeeded; expected failure") } } // ParseEnvFile with a random file, pass through func TestParseEnvFileRandomFile(t *testing.T) { content := `first line another invalid line` tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) _, err := ParseEnvFile(tmpFile) if err == nil { t.Fatalf("Expected a ErrBadEnvVariable, got nothing") } if _, ok := err.(ErrBadEnvVariable); !ok { t.Fatalf("Expected a ErrBadEnvvariable, got [%v]", err) } expectedMessage := "poorly formatted environment: variable 'first line' is not a valid environment variable" if err.Error() != expectedMessage { t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) } } ================================================ FILE: vendor/github.com/docker/docker/opts/ip.go ================================================ package opts import ( "fmt" "net" ) // IpOpt type that hold an IP type IpOpt struct { *net.IP } func NewIpOpt(ref *net.IP, defaultVal string) *IpOpt { o := &IpOpt{ IP: ref, } o.Set(defaultVal) return o } 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 } func (o *IpOpt) String() string { if *o.IP == nil { return "" } return o.IP.String() } ================================================ FILE: vendor/github.com/docker/docker/opts/ip_test.go ================================================ package opts import ( "net" "testing" ) func TestIpOptString(t *testing.T) { addresses := []string{"", "0.0.0.0"} var ip net.IP for _, address := range addresses { stringAddress := NewIpOpt(&ip, address).String() if stringAddress != address { t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress) } } } func TestNewIpOptInvalidDefaultVal(t *testing.T) { ip := net.IPv4(127, 0, 0, 1) defaultVal := "Not an ip" ipOpt := NewIpOpt(&ip, defaultVal) expected := "127.0.0.1" if ipOpt.String() != expected { t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) } } func TestNewIpOptValidDefaultVal(t *testing.T) { ip := net.IPv4(127, 0, 0, 1) defaultVal := "192.168.1.1" ipOpt := NewIpOpt(&ip, defaultVal) expected := "192.168.1.1" if ipOpt.String() != expected { t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) } } func TestIpOptSetInvalidVal(t *testing.T) { ip := net.IPv4(127, 0, 0, 1) ipOpt := &IpOpt{IP: &ip} invalidIp := "invalid ip" expectedError := "invalid ip is not an ip address" err := ipOpt.Set(invalidIp) if err == nil || err.Error() != expectedError { t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error()) } } ================================================ FILE: vendor/github.com/docker/docker/opts/opts.go ================================================ package opts import ( "fmt" "net" "os" "path" "regexp" "strings" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/ulimit" "github.com/docker/docker/volume" ) 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*$`) // DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. docker -d -H tcp://:8080 DefaultHTTPHost = "127.0.0.1" // DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. docker -d -H tcp:// // TODO Windows. DefaultHTTPPort is only used on Windows if a -H parameter // is not supplied. A better longer term solution would be to use a named // pipe as the default on the Windows daemon. DefaultHTTPPort = 2375 // Default HTTP Port // DefaultUnixSocket Path for the unix socket. // Docker daemon by default always listens on the default unix socket DefaultUnixSocket = "/var/run/docker.sock" ) // ListVar Defines a flag with the specified names and usage, and put the value // list into ListOpts that will hold the values. func ListVar(values *[]string, names []string, usage string) { flag.Var(newListOptsRef(values, nil), names, usage) } // MapVar Defines a flag with the specified names and usage, and put the value // map into MapOpt that will hold the values (key,value). func MapVar(values map[string]string, names []string, usage string) { flag.Var(newMapOpt(values, nil), names, usage) } // LogOptsVar Defines a flag with the specified names and usage for --log-opts, // and put the value map into MapOpt that will hold the values (key,value). func LogOptsVar(values map[string]string, names []string, usage string) { flag.Var(newMapOpt(values, nil), names, usage) } // HostListVar Defines a flag with the specified names and usage and put the // value into a ListOpts that will hold the values, validating the Host format. func HostListVar(values *[]string, names []string, usage string) { flag.Var(newListOptsRef(values, ValidateHost), names, usage) } // IPListVar Defines a flag with the specified names and usage and put the // value into a ListOpts that will hold the values, validating the IP format. func IPListVar(values *[]string, names []string, usage string) { flag.Var(newListOptsRef(values, ValidateIPAddress), names, usage) } // DNSSearchListVar Defines a flag with the specified names and usage and put the // value into a ListOpts that will hold the values, validating the DNS search format. func DNSSearchListVar(values *[]string, names []string, usage string) { flag.Var(newListOptsRef(values, ValidateDNSSearch), names, usage) } // IPVar Defines a flag with the specified names and usage for IP and will use // the specified defaultValue if the specified value is not valid. func IPVar(value *net.IP, names []string, defaultValue, usage string) { flag.Var(NewIpOpt(value, defaultValue), names, usage) } // LabelListVar Defines a flag with the specified names and usage and put the // value into a ListOpts that will hold the values, validating the label format. func LabelListVar(values *[]string, names []string, usage string) { flag.Var(newListOptsRef(values, ValidateLabel), names, usage) } // UlimitMapVar Defines a flag with the specified names and usage for --ulimit, // and put the value map into a UlimitOpt that will hold the values. func UlimitMapVar(values map[string]*ulimit.Ulimit, names []string, usage string) { flag.Var(NewUlimitOpt(values), names, usage) } // ListOpts type that hold a list of values and a validation function. type ListOpts struct { values *[]string validator ValidatorFctType } // NewListOpts Create a new ListOpts with the specified validator. func NewListOpts(validator ValidatorFctType) ListOpts { var values []string return *newListOptsRef(&values, validator) } func newListOptsRef(values *[]string, validator ValidatorFctType) *ListOpts { return &ListOpts{ values: values, validator: validator, } } func (opts *ListOpts) String() string { return fmt.Sprintf("%v", []string((*opts.values))) } // Set validates if needed the input value and add 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 remove the given 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. // FIXME: can we remove this? 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' slice. // FIXME: Can we remove this? func (opts *ListOpts) GetAll() []string { return (*opts.values) } // Get checks the existence of the given 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)) } //MapOpts type that 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 } func (opts *MapOpts) String() string { return fmt.Sprintf("%v", map[string]string((opts.values))) } func newMapOpt(values map[string]string, validator ValidatorFctType) *MapOpts { return &MapOpts{ values: values, validator: validator, } } // ValidatorFctType validator that return a validate string and/or an error type ValidatorFctType func(val string) (string, error) // ValidatorFctListType validator that return a validate list of string and/or an error type ValidatorFctListType func(val string) ([]string, error) // 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, fmt.Errorf("valid streams are STDIN, STDOUT and STDERR") } // ValidateLink Validates that the specified string has a valid link format (containerName:alias). func ValidateLink(val string) (string, error) { if _, _, err := parsers.ParseLink(val); err != nil { return val, err } return val, nil } // ValidateDevice Validate a path for devices // It will make sure 'val' is in the form: // [host-dir:]container-path[:mode] func ValidateDevice(val string) (string, error) { return validatePath(val, false) } // ValidatePath Validate a path for volumes // It will make sure 'val' is in the form: // [host-dir:]container-path[:rw|ro] // It will also validate the mount mode. func ValidatePath(val string) (string, error) { return validatePath(val, true) } func validatePath(val string, validateMountMode bool) (string, error) { var containerPath string var mode string if strings.Count(val, ":") > 2 { return val, fmt.Errorf("bad format for volumes: %s", val) } splited := strings.SplitN(val, ":", 3) if splited[0] == "" { return val, fmt.Errorf("bad format for volumes: %s", val) } switch len(splited) { case 1: containerPath = splited[0] val = path.Clean(containerPath) case 2: if isValid, _ := volume.ValidateMountMode(splited[1]); validateMountMode && isValid { containerPath = splited[0] mode = splited[1] val = fmt.Sprintf("%s:%s", path.Clean(containerPath), mode) } else { containerPath = splited[1] val = fmt.Sprintf("%s:%s", splited[0], path.Clean(containerPath)) } case 3: containerPath = splited[1] mode = splited[2] if isValid, _ := volume.ValidateMountMode(splited[2]); validateMountMode && !isValid { return val, fmt.Errorf("bad mount mode specified : %s", mode) } val = fmt.Sprintf("%s:%s:%s", splited[0], containerPath, mode) } if !path.IsAbs(containerPath) { return val, fmt.Errorf("%s is not an absolute path", containerPath) } return val, nil } // ValidateEnv Validate an environment variable and returns it // It will use EnvironmentVariableRegexp to ensure the name of the environment variable is valid. // If no value is specified, it returns the current value using os.Getenv. func ValidateEnv(val string) (string, error) { arr := strings.Split(val, "=") if len(arr) > 1 { return val, nil } if !EnvironmentVariableRegexp.MatchString(arr[0]) { return val, ErrBadEnvVariable{fmt.Sprintf("variable '%s' is not a valid environment variable", val)} } if !doesEnvExist(val) { return val, nil } return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil } // 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 . 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) } // ValidateExtraHost Validate that the given string is a valid extrahost and returns it // ExtraHost are 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 } // ValidateLabel Validate that the given 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 } // ValidateHost Validate that the given string is a valid host and returns it func ValidateHost(val string) (string, error) { host, err := parsers.ParseHost(DefaultHTTPHost, DefaultUnixSocket, val) if err != nil { return val, err } return host, nil } func doesEnvExist(name string) bool { for _, entry := range os.Environ() { parts := strings.SplitN(entry, "=", 2) if parts[0] == name { return true } } return false } ================================================ FILE: vendor/github.com/docker/docker/opts/opts_test.go ================================================ package opts import ( "fmt" "os" "strings" "testing" ) func TestValidateIPAddress(t *testing.T) { if ret, err := ValidateIPAddress(`1.2.3.4`); err != nil || ret == "" { t.Fatalf("ValidateIPAddress(`1.2.3.4`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`127.0.0.1`); err != nil || ret == "" { t.Fatalf("ValidateIPAddress(`127.0.0.1`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`::1`); err != nil || ret == "" { t.Fatalf("ValidateIPAddress(`::1`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`127`); err == nil || ret != "" { t.Fatalf("ValidateIPAddress(`127`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`random invalid string`); err == nil || ret != "" { t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err) } } func TestMapOpts(t *testing.T) { tmpMap := make(map[string]string) o := newMapOpt(tmpMap, logOptsValidator) o.Set("max-size=1") if o.String() != "map[max-size:1]" { t.Errorf("%s != [map[max-size:1]", o.String()) } o.Set("max-file=2") if len(tmpMap) != 2 { t.Errorf("map length %d != 2", len(tmpMap)) } if tmpMap["max-file"] != "2" { t.Errorf("max-file = %s != 2", tmpMap["max-file"]) } if tmpMap["max-size"] != "1" { t.Errorf("max-size = %s != 1", tmpMap["max-size"]) } if o.Set("dummy-val=3") == nil { t.Errorf("validator is not being called") } } func TestValidateMACAddress(t *testing.T) { if _, err := ValidateMACAddress(`92:d0:c6:0a:29:33`); err != nil { t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:29:33`) got %s", err) } if _, err := ValidateMACAddress(`92:d0:c6:0a:33`); err == nil { t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:33`) succeeded; expected failure on invalid MAC") } if _, err := ValidateMACAddress(`random invalid string`); err == nil { t.Fatalf("ValidateMACAddress(`random invalid string`) succeeded; expected failure on invalid MAC") } } func TestListOptsWithoutValidator(t *testing.T) { o := NewListOpts(nil) o.Set("foo") if o.String() != "[foo]" { t.Errorf("%s != [foo]", o.String()) } o.Set("bar") if o.Len() != 2 { t.Errorf("%d != 2", o.Len()) } o.Set("bar") if o.Len() != 3 { t.Errorf("%d != 3", o.Len()) } if !o.Get("bar") { t.Error("o.Get(\"bar\") == false") } if o.Get("baz") { t.Error("o.Get(\"baz\") == true") } o.Delete("foo") if o.String() != "[bar bar]" { t.Errorf("%s != [bar bar]", o.String()) } listOpts := o.GetAll() if len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" { t.Errorf("Expected [[bar bar]], got [%v]", listOpts) } mapListOpts := o.GetMap() if len(mapListOpts) != 1 { t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts) } } func TestListOptsWithValidator(t *testing.T) { // Re-using logOptsvalidator (used by MapOpts) o := NewListOpts(logOptsValidator) o.Set("foo") if o.String() != "[]" { t.Errorf("%s != []", o.String()) } o.Set("foo=bar") if o.String() != "[]" { t.Errorf("%s != []", o.String()) } o.Set("max-file=2") if o.Len() != 1 { t.Errorf("%d != 1", o.Len()) } if !o.Get("max-file=2") { t.Error("o.Get(\"max-file=2\") == false") } if o.Get("baz") { t.Error("o.Get(\"baz\") == true") } o.Delete("max-file=2") if o.String() != "[]" { t.Errorf("%s != []", o.String()) } } func TestValidateDNSSearch(t *testing.T) { valid := []string{ `.`, `a`, `a.`, `1.foo`, `17.foo`, `foo.bar`, `foo.bar.baz`, `foo.bar.`, `foo.bar.baz`, `foo1.bar2`, `foo1.bar2.baz`, `1foo.2bar.`, `1foo.2bar.baz`, `foo-1.bar-2`, `foo-1.bar-2.baz`, `foo-1.bar-2.`, `foo-1.bar-2.baz`, `1-foo.2-bar`, `1-foo.2-bar.baz`, `1-foo.2-bar.`, `1-foo.2-bar.baz`, } invalid := []string{ ``, ` `, ` `, `17`, `17.`, `.17`, `17-.`, `17-.foo`, `.foo`, `foo-.bar`, `-foo.bar`, `foo.bar-`, `foo.bar-.baz`, `foo.-bar`, `foo.-bar.baz`, `foo.bar.baz.this.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbe`, } for _, domain := range valid { if ret, err := ValidateDNSSearch(domain); err != nil || ret == "" { t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) } } for _, domain := range invalid { if ret, err := ValidateDNSSearch(domain); err == nil || ret != "" { t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) } } } func TestValidateExtraHosts(t *testing.T) { valid := []string{ `myhost:192.168.0.1`, `thathost:10.0.2.1`, `anipv6host:2003:ab34:e::1`, `ipv6local:::1`, } invalid := map[string]string{ `myhost:192.notanipaddress.1`: `invalid IP`, `thathost-nosemicolon10.0.0.1`: `bad format`, `anipv6host:::::1`: `invalid IP`, `ipv6local:::0::`: `invalid IP`, } for _, extrahost := range valid { if _, err := ValidateExtraHost(extrahost); err != nil { t.Fatalf("ValidateExtraHost(`"+extrahost+"`) should succeed: error %v", err) } } for extraHost, expectedError := range invalid { if _, err := ValidateExtraHost(extraHost); err == nil { t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost) } else { if !strings.Contains(err.Error(), expectedError) { t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError) } } } } func TestValidateAttach(t *testing.T) { valid := []string{ "stdin", "stdout", "stderr", "STDIN", "STDOUT", "STDERR", } if _, err := ValidateAttach("invalid"); err == nil { t.Fatalf("Expected error with [valid streams are STDIN, STDOUT and STDERR], got nothing") } for _, attach := range valid { value, err := ValidateAttach(attach) if err != nil { t.Fatal(err) } if value != strings.ToLower(attach) { t.Fatalf("Expected [%v], got [%v]", attach, value) } } } func TestValidateLink(t *testing.T) { valid := []string{ "name", "dcdfbe62ecd0:alias", "7a67485460b7642516a4ad82ecefe7f57d0c4916f530561b71a50a3f9c4e33da", "angry_torvalds:linus", } invalid := map[string]string{ "": "empty string specified for links", "too:much:of:it": "bad format for links: too:much:of:it", } for _, link := range valid { if _, err := ValidateLink(link); err != nil { t.Fatalf("ValidateLink(`%q`) should succeed: error %q", link, err) } } for link, expectedError := range invalid { if _, err := ValidateLink(link); err == nil { t.Fatalf("ValidateLink(`%q`) should have failed validation", link) } else { if !strings.Contains(err.Error(), expectedError) { t.Fatalf("ValidateLink(`%q`) error should contain %q", link, expectedError) } } } } func TestValidatePath(t *testing.T) { valid := []string{ "/home", "/home:/home", "/home:/something/else", "/with space", "/home:/with space", "relative:/absolute-path", "hostPath:/containerPath:ro", "/hostPath:/containerPath:rw", "/rw:/ro", "/path:rw", "/path:ro", "/rw:rw", } invalid := map[string]string{ "": "bad format for volumes: ", "./": "./ is not an absolute path", "../": "../ is not an absolute path", "/:../": "../ is not an absolute path", "/:path": "path is not an absolute path", ":": "bad format for volumes: :", "/tmp:": " is not an absolute path", ":test": "bad format for volumes: :test", ":/test": "bad format for volumes: :/test", "tmp:": " is not an absolute path", ":test:": "bad format for volumes: :test:", "::": "bad format for volumes: ::", ":::": "bad format for volumes: :::", "/tmp:::": "bad format for volumes: /tmp:::", ":/tmp::": "bad format for volumes: :/tmp::", "path:ro": "path is not an absolute path", "/path:/path:sw": "bad mount mode specified : sw", "/path:/path:rwz": "bad mount mode specified : rwz", } for _, path := range valid { if _, err := ValidatePath(path); err != nil { t.Fatalf("ValidatePath(`%q`) should succeed: error %q", path, err) } } for path, expectedError := range invalid { if _, err := ValidatePath(path); err == nil { t.Fatalf("ValidatePath(`%q`) should have failed validation", path) } else { if err.Error() != expectedError { t.Fatalf("ValidatePath(`%q`) error should contain %q, got %q", path, expectedError, err.Error()) } } } } func TestValidateDevice(t *testing.T) { valid := []string{ "/home", "/home:/home", "/home:/something/else", "/with space", "/home:/with space", "relative:/absolute-path", "hostPath:/containerPath:ro", "/hostPath:/containerPath:rw", "/hostPath:/containerPath:mrw", } invalid := map[string]string{ "": "bad format for volumes: ", "./": "./ is not an absolute path", "../": "../ is not an absolute path", "/:../": "../ is not an absolute path", "/:path": "path is not an absolute path", ":": "bad format for volumes: :", "/tmp:": " is not an absolute path", ":test": "bad format for volumes: :test", ":/test": "bad format for volumes: :/test", "tmp:": " is not an absolute path", ":test:": "bad format for volumes: :test:", "::": "bad format for volumes: ::", ":::": "bad format for volumes: :::", "/tmp:::": "bad format for volumes: /tmp:::", ":/tmp::": "bad format for volumes: :/tmp::", "path:ro": "ro is not an absolute path", } for _, path := range valid { if _, err := ValidateDevice(path); err != nil { t.Fatalf("ValidateDevice(`%q`) should succeed: error %q", path, err) } } for path, expectedError := range invalid { if _, err := ValidateDevice(path); err == nil { t.Fatalf("ValidateDevice(`%q`) should have failed validation", path) } else { if err.Error() != expectedError { t.Fatalf("ValidateDevice(`%q`) error should contain %q, got %q", path, expectedError, err.Error()) } } } } func TestValidateEnv(t *testing.T) { invalids := map[string]string{ "some spaces": "poorly formatted environment: variable 'some spaces' is not a valid environment variable", "asd!qwe": "poorly formatted environment: variable 'asd!qwe' is not a valid environment variable", "1asd": "poorly formatted environment: variable '1asd' is not a valid environment variable", "123": "poorly formatted environment: variable '123' is not a valid environment variable", } valids := map[string]string{ "a": "a", "something": "something", "_=a": "_=a", "env1=value1": "env1=value1", "_env1=value1": "_env1=value1", "env2=value2=value3": "env2=value2=value3", "env3=abc!qwe": "env3=abc!qwe", "env_4=value 4": "env_4=value 4", "PATH": fmt.Sprintf("PATH=%v", os.Getenv("PATH")), "PATH=something": "PATH=something", } for value, expectedError := range invalids { _, err := ValidateEnv(value) if err == nil { t.Fatalf("Expected ErrBadEnvVariable, got nothing") } if _, ok := err.(ErrBadEnvVariable); !ok { t.Fatalf("Expected ErrBadEnvVariable, got [%s]", err) } if err.Error() != expectedError { t.Fatalf("Expected ErrBadEnvVariable with message [%s], got [%s]", expectedError, err.Error()) } } for value, expected := range valids { actual, err := ValidateEnv(value) if err != nil { t.Fatal(err) } if actual != expected { t.Fatalf("Expected [%v], got [%v]", expected, actual) } } } func TestValidateLabel(t *testing.T) { if _, err := ValidateLabel("label"); err == nil || err.Error() != "bad attribute format: label" { t.Fatalf("Expected an error [bad attribute format: label], go %v", err) } if actual, err := ValidateLabel("key1=value1"); err != nil || actual != "key1=value1" { t.Fatalf("Expected [key1=value1], got [%v,%v]", actual, err) } // Validate it's working with more than one = if actual, err := ValidateLabel("key1=value1=value2"); err != nil { t.Fatalf("Expected [key1=value1=value2], got [%v,%v]", actual, err) } // Validate it's working with one more if actual, err := ValidateLabel("key1=value1=value2=value3"); err != nil { t.Fatalf("Expected [key1=value1=value2=value2], got [%v,%v]", actual, err) } } func TestValidateHost(t *testing.T) { invalid := map[string]string{ "anything": "Invalid bind address format: anything", "something with spaces": "Invalid bind address format: something with spaces", "://": "Invalid bind address format: ://", "unknown://": "Invalid bind address format: unknown://", "tcp://": "Invalid proto, expected tcp: ", "tcp://:port": "Invalid bind address format: :port", "tcp://invalid": "Invalid bind address format: invalid", "tcp://invalid:port": "Invalid bind address format: invalid:port", } valid := map[string]string{ "fd://": "fd://", "fd://something": "fd://something", "tcp://:2375": "tcp://127.0.0.1:2375", // default ip address "tcp://:2376": "tcp://127.0.0.1:2376", // default ip address "tcp://0.0.0.0:8080": "tcp://0.0.0.0:8080", "tcp://192.168.0.0:12000": "tcp://192.168.0.0:12000", "tcp://192.168:8080": "tcp://192.168:8080", "tcp://0.0.0.0:1234567890": "tcp://0.0.0.0:1234567890", // yeah it's valid :P "tcp://docker.com:2375": "tcp://docker.com:2375", "unix://": "unix:///var/run/docker.sock", // default unix:// value "unix://path/to/socket": "unix://path/to/socket", } for value, errorMessage := range invalid { if _, err := ValidateHost(value); err == nil || err.Error() != errorMessage { t.Fatalf("Expected an error for %v with [%v], got [%v]", value, errorMessage, err) } } for value, expected := range valid { if actual, err := ValidateHost(value); err != nil || actual != expected { t.Fatalf("Expected for %v [%v], got [%v, %v]", value, expected, actual, err) } } } func logOptsValidator(val string) (string, error) { allowedKeys := map[string]string{"max-size": "1", "max-file": "2"} vals := strings.Split(val, "=") if allowedKeys[vals[0]] != "" { return val, nil } return "", fmt.Errorf("invalid key %s", vals[0]) } ================================================ FILE: vendor/github.com/docker/docker/opts/ulimit.go ================================================ package opts import ( "fmt" "github.com/docker/docker/pkg/ulimit" ) type UlimitOpt struct { values map[string]*ulimit.Ulimit } func NewUlimitOpt(ref map[string]*ulimit.Ulimit) *UlimitOpt { return &UlimitOpt{ref} } func (o *UlimitOpt) Set(val string) error { l, err := ulimit.Parse(val) if err != nil { return err } o.values[l.Name] = l return nil } func (o *UlimitOpt) String() string { var out []string for _, v := range o.values { out = append(out, v.String()) } return fmt.Sprintf("%v", out) } func (o *UlimitOpt) GetList() []*ulimit.Ulimit { var ulimits []*ulimit.Ulimit for _, v := range o.values { ulimits = append(ulimits, v) } return ulimits } ================================================ FILE: vendor/github.com/docker/docker/opts/ulimit_test.go ================================================ package opts import ( "testing" "github.com/docker/docker/pkg/ulimit" ) func TestUlimitOpt(t *testing.T) { ulimitMap := map[string]*ulimit.Ulimit{ "nofile": {"nofile", 1024, 512}, } ulimitOpt := NewUlimitOpt(ulimitMap) expected := "[nofile=512:1024]" if ulimitOpt.String() != expected { t.Fatalf("Expected %v, got %v", expected, ulimitOpt) } // Valid ulimit append to opts if err := ulimitOpt.Set("core=1024:1024"); err != nil { t.Fatal(err) } // Invalid ulimit type returns an error and do not append to opts if err := ulimitOpt.Set("notavalidtype=1024:1024"); err == nil { t.Fatalf("Expected error on invalid ulimit type") } expected = "[nofile=512:1024 core=1024:1024]" expected2 := "[core=1024:1024 nofile=512:1024]" result := ulimitOpt.String() if result != expected && result != expected2 { t.Fatalf("Expected %v or %v, got %v", expected, expected2, ulimitOpt) } // And test GetList ulimits := ulimitOpt.GetList() if len(ulimits) != 2 { t.Fatalf("Expected a ulimit list of 2, got %v", ulimits) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/README.md ================================================ pkg/ is a collection of utility packages used by the Docker project without being specific to its internals. Utility packages are kept separate from the docker core codebase to keep it as small and concise as possible. If some utilities grow larger and their APIs stabilize, they may be moved to their own repository under the Docker organization, to facilitate re-use by other projects. However that is not the priority. The directory `pkg` is named after the same directory in the camlistore project. Since Brad is a core Go maintainer, we thought it made sense to copy his methods for organizing Go code :) Thanks Brad! Because utility packages are small and neatly separated from the rest of the codebase, they are a good place to start for aspiring maintainers and contributors. Get in touch if you want to help maintain them! ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/README.md ================================================ This code provides helper functions for dealing with archive files. ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/archive.go ================================================ package archive import ( "archive/tar" "bufio" "bytes" "compress/bzip2" "compress/gzip" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/promise" "github.com/docker/docker/pkg/system" ) type ( Archive io.ReadCloser ArchiveReader io.Reader Compression int TarChownOptions struct { UID, GID int } TarOptions struct { IncludeFiles []string ExcludePatterns []string Compression Compression NoLchown bool ChownOpts *TarChownOptions Name string IncludeSourceDir bool // When unpacking, specifies whether overwriting a directory with a // non-directory is allowed and vice versa. NoOverwriteDirNonDir bool } // Archiver allows the reuse of most utility functions of this package // with a pluggable Untar function. Archiver struct { Untar func(io.Reader, string, *TarOptions) error } // breakoutError is used to differentiate errors related to breaking out // When testing archive breakout in the unit tests, this error is expected // in order for the test to pass. breakoutError error ) var ( ErrNotImplemented = errors.New("Function not implemented") defaultArchiver = &Archiver{Untar} ) const ( Uncompressed Compression = iota Bzip2 Gzip Xz ) func IsArchive(header []byte) bool { compression := DetectCompression(header) if compression != Uncompressed { return true } r := tar.NewReader(bytes.NewBuffer(header)) _, err := r.Next() return err == nil } func DetectCompression(source []byte) Compression { for compression, m := range map[Compression][]byte{ Bzip2: {0x42, 0x5A, 0x68}, Gzip: {0x1F, 0x8B, 0x08}, Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, } { if len(source) < len(m) { logrus.Debugf("Len too short") continue } if bytes.Compare(m, source[:len(m)]) == 0 { return compression } } return Uncompressed } func xzDecompress(archive io.Reader) (io.ReadCloser, error) { args := []string{"xz", "-d", "-c", "-q"} return CmdStream(exec.Command(args[0], args[1:]...), archive) } func DecompressStream(archive io.Reader) (io.ReadCloser, error) { p := pools.BufioReader32KPool buf := p.Get(archive) bs, err := buf.Peek(10) if err != nil { return nil, err } compression := DetectCompression(bs) switch compression { case Uncompressed: readBufWrapper := p.NewReadCloserWrapper(buf, buf) return readBufWrapper, nil case Gzip: gzReader, err := gzip.NewReader(buf) if err != nil { return nil, err } readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) return readBufWrapper, nil case Bzip2: bz2Reader := bzip2.NewReader(buf) readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) return readBufWrapper, nil case Xz: xzReader, err := xzDecompress(buf) if err != nil { return nil, err } readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) return readBufWrapper, nil default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) { p := pools.BufioWriter32KPool buf := p.Get(dest) switch compression { case Uncompressed: writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) return writeBufWrapper, nil case Gzip: gzWriter := gzip.NewWriter(dest) writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) return writeBufWrapper, nil case Bzip2, Xz: // archive/bzip2 does not support writing, and there is no xz support at all // However, this is not a problem as docker only currently generates gzipped tars return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } func (compression *Compression) Extension() string { switch *compression { case Uncompressed: return "tar" case Bzip2: return "tar.bz2" case Gzip: return "tar.gz" case Xz: return "tar.xz" } return "" } type tarAppender struct { TarWriter *tar.Writer Buffer *bufio.Writer // for hardlink mapping SeenFiles map[uint64]string } // canonicalTarName provides a platform-independent and consistent posix-style //path for files and directories to be archived regardless of the platform. func canonicalTarName(name string, isDir bool) (string, error) { name, err := CanonicalTarNameForPath(name) if err != nil { return "", err } // suffix with '/' for directories if isDir && !strings.HasSuffix(name, "/") { name += "/" } return name, nil } func (ta *tarAppender) addTarFile(path, name string) error { fi, err := os.Lstat(path) if err != nil { return err } link := "" if fi.Mode()&os.ModeSymlink != 0 { if link, err = os.Readlink(path); err != nil { return err } } hdr, err := tar.FileInfoHeader(fi, link) if err != nil { return err } hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) name, err = canonicalTarName(name, fi.IsDir()) if err != nil { return fmt.Errorf("tar: cannot canonicalize path: %v", err) } hdr.Name = name nlink, inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys()) if err != nil { return err } // if it's a regular file and has more than 1 link, // it's hardlinked, so set the type flag accordingly if fi.Mode().IsRegular() && nlink > 1 { // a link should have a name that it links too // and that linked name should be first in the tar archive if oldpath, ok := ta.SeenFiles[inode]; ok { hdr.Typeflag = tar.TypeLink hdr.Linkname = oldpath hdr.Size = 0 // This Must be here for the writer math to add up! } else { ta.SeenFiles[inode] = name } } capability, _ := system.Lgetxattr(path, "security.capability") if capability != nil { hdr.Xattrs = make(map[string]string) hdr.Xattrs["security.capability"] = string(capability) } if err := ta.TarWriter.WriteHeader(hdr); err != nil { return err } if hdr.Typeflag == tar.TypeReg { file, err := os.Open(path) if err != nil { return err } ta.Buffer.Reset(ta.TarWriter) defer ta.Buffer.Reset(nil) _, err = io.Copy(ta.Buffer, file) file.Close() if err != nil { return err } err = ta.Buffer.Flush() if err != nil { return err } } return nil } func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *TarChownOptions) error { // hdr.Mode is in linux format, which we can use for sycalls, // but for os.Foo() calls we need the mode converted to os.FileMode, // so use hdrInfo.Mode() (they differ for e.g. setuid bits) hdrInfo := hdr.FileInfo() switch hdr.Typeflag { case tar.TypeDir: // Create directory unless it exists as a directory already. // In that case we just want to merge the two if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { return err } } case tar.TypeReg, tar.TypeRegA: // Source is regular file file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) if err != nil { return err } if _, err := io.Copy(file, reader); err != nil { file.Close() return err } file.Close() case tar.TypeBlock, tar.TypeChar, tar.TypeFifo: // Handle this is an OS-specific way if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { return err } case tar.TypeLink: targetPath := filepath.Join(extractDir, hdr.Linkname) // check for hardlink breakout if !strings.HasPrefix(targetPath, extractDir) { return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) } if err := os.Link(targetPath, path); err != nil { return err } case tar.TypeSymlink: // path -> hdr.Linkname = targetPath // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because // that symlink would first have to be created, which would be caught earlier, at this very check: if !strings.HasPrefix(targetPath, extractDir) { return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) } if err := os.Symlink(hdr.Linkname, path); err != nil { return err } case tar.TypeXGlobalHeader: logrus.Debugf("PAX Global Extended Headers found and ignored") return nil default: return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag) } // Lchown is not supported on Windows. if Lchown && runtime.GOOS != "windows" { if chownOpts == nil { chownOpts = &TarChownOptions{UID: hdr.Uid, GID: hdr.Gid} } if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { return err } } for key, value := range hdr.Xattrs { if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { return err } } // There is no LChmod, so ignore mode for symlink. Also, this // must happen after chown, as that can modify the file mode if err := handleLChmod(hdr, path, hdrInfo); err != nil { return err } ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)} // syscall.UtimesNano doesn't support a NOFOLLOW flag atm if hdr.Typeflag == tar.TypeLink { if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { if err := system.UtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { return err } } } else if hdr.Typeflag != tar.TypeSymlink { if err := system.UtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { return err } } else { if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { return err } } return nil } // Tar creates an archive from the directory at `path`, and returns it as a // stream of bytes. func Tar(path string, compression Compression) (io.ReadCloser, error) { return TarWithOptions(path, &TarOptions{Compression: compression}) } // TarWithOptions creates an archive from the directory at `path`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns) if err != nil { return nil, err } pipeReader, pipeWriter := io.Pipe() compressWriter, err := CompressStream(pipeWriter, options.Compression) if err != nil { return nil, err } go func() { ta := &tarAppender{ TarWriter: tar.NewWriter(compressWriter), Buffer: pools.BufioWriter32KPool.Get(nil), SeenFiles: make(map[uint64]string), } defer func() { // Make sure to check the error on Close. if err := ta.TarWriter.Close(); err != nil { logrus.Debugf("Can't close tar writer: %s", err) } if err := compressWriter.Close(); err != nil { logrus.Debugf("Can't close compress writer: %s", err) } if err := pipeWriter.Close(); err != nil { logrus.Debugf("Can't close pipe writer: %s", err) } }() // this buffer is needed for the duration of this piped stream defer pools.BufioWriter32KPool.Put(ta.Buffer) // In general we log errors here but ignore them because // during e.g. a diff operation the container can continue // mutating the filesystem and we can see transient errors // from this stat, err := os.Lstat(srcPath) if err != nil { return } if !stat.IsDir() { // We can't later join a non-dir with any includes because the // 'walk' will error if "file/." is stat-ed and "file" is not a // directory. So, we must split the source path and use the // basename as the include. if len(options.IncludeFiles) > 0 { logrus.Warn("Tar: Can't archive a file with includes") } dir, base := SplitPathDirEntry(srcPath) srcPath = dir options.IncludeFiles = []string{base} } if len(options.IncludeFiles) == 0 { options.IncludeFiles = []string{"."} } seen := make(map[string]bool) var renamedRelFilePath string // For when tar.Options.Name is set for _, include := range options.IncludeFiles { // We can't use filepath.Join(srcPath, include) because this will // clean away a trailing "." or "/" which may be important. walkRoot := strings.Join([]string{srcPath, include}, string(filepath.Separator)) filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { if err != nil { logrus.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err) return nil } relFilePath, err := filepath.Rel(srcPath, filePath) if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { // Error getting relative path OR we are looking // at the source directory path. Skip in both situations. return nil } if options.IncludeSourceDir && include == "." && relFilePath != "." { relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) } skip := false // If "include" is an exact match for the current file // then even if there's an "excludePatterns" pattern that // matches it, don't skip it. IOW, assume an explicit 'include' // is asking for that file no matter what - which is true // for some files, like .dockerignore and Dockerfile (sometimes) if include != relFilePath { skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs) if err != nil { logrus.Debugf("Error matching %s: %v", relFilePath, err) return err } } if skip { if !exceptions && f.IsDir() { return filepath.SkipDir } return nil } if seen[relFilePath] { return nil } seen[relFilePath] = true // TODO Windows: Verify if this needs to be os.Pathseparator // Rename the base resource if options.Name != "" && filePath == srcPath+"/"+filepath.Base(relFilePath) { renamedRelFilePath = relFilePath } // Set this to make sure the items underneath also get renamed if options.Name != "" { relFilePath = strings.Replace(relFilePath, renamedRelFilePath, options.Name, 1) } if err := ta.addTarFile(filePath, relFilePath); err != nil { logrus.Debugf("Can't add file %s to tar: %s", filePath, err) } return nil }) } }() return pipeReader, nil } func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { tr := tar.NewReader(decompressedArchive) trBuf := pools.BufioReader32KPool.Get(nil) defer pools.BufioReader32KPool.Put(trBuf) var dirs []*tar.Header // Iterate through the files in the archive. loop: for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return err } // Normalize name, for safety and for a simple is-root check // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: // This keeps "..\" as-is, but normalizes "\..\" to "\". hdr.Name = filepath.Clean(hdr.Name) for _, exclude := range options.ExcludePatterns { if strings.HasPrefix(hdr.Name, exclude) { continue loop } } // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in // the filepath format for the OS on which the daemon is running. Hence // the check for a slash-suffix MUST be done in an OS-agnostic way. if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { // Not the root directory, ensure that the parent directory exists parent := filepath.Dir(hdr.Name) parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { err = system.MkdirAll(parentPath, 0777) if err != nil { return err } } } path := filepath.Join(dest, hdr.Name) rel, err := filepath.Rel(dest, path) if err != nil { return err } if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) } // If path exits we almost always just want to remove and replace it // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). if fi, err := os.Lstat(path); err == nil { if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing directory with a non-directory from the archive. return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) } if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing non-directory with a directory from the archive. return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) } if fi.IsDir() && hdr.Name == "." { continue } if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { if err := os.RemoveAll(path); err != nil { return err } } } trBuf.Reset(tr) if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts); err != nil { return err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { dirs = append(dirs, hdr) } } for _, hdr := range dirs { path := filepath.Join(dest, hdr.Name) ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)} if err := syscall.UtimesNano(path, ts); err != nil { return err } } return nil } // Untar reads a stream of bytes from `archive`, parses it as a tar archive, // and unpacks it into the directory at `dest`. // The archive may be compressed with one of the following algorithms: // identity (uncompressed), gzip, bzip2, xz. // FIXME: specify behavior when target path exists vs. doesn't exist. func Untar(archive io.Reader, dest string, options *TarOptions) error { if archive == nil { return fmt.Errorf("Empty archive") } dest = filepath.Clean(dest) if options == nil { options = &TarOptions{} } if options.ExcludePatterns == nil { options.ExcludePatterns = []string{} } decompressedArchive, err := DecompressStream(archive) if err != nil { return err } defer decompressedArchive.Close() return Unpack(decompressedArchive, dest, options) } func (archiver *Archiver) TarUntar(src, dst string) error { logrus.Debugf("TarUntar(%s %s)", src, dst) archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) if err != nil { return err } defer archive.Close() return archiver.Untar(archive, dst, nil) } // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. // If either Tar or Untar fails, TarUntar aborts and returns the error. func TarUntar(src, dst string) error { return defaultArchiver.TarUntar(src, dst) } func (archiver *Archiver) UntarPath(src, dst string) error { archive, err := os.Open(src) if err != nil { return err } defer archive.Close() if err := archiver.Untar(archive, dst, nil); err != nil { return err } return nil } // UntarPath is a convenience function which looks for an archive // at filesystem path `src`, and unpacks it at `dst`. func UntarPath(src, dst string) error { return defaultArchiver.UntarPath(src, dst) } func (archiver *Archiver) CopyWithTar(src, dst string) error { srcSt, err := os.Stat(src) if err != nil { return err } if !srcSt.IsDir() { return archiver.CopyFileWithTar(src, dst) } // Create dst, copy src's content into it logrus.Debugf("Creating dest directory: %s", dst) if err := system.MkdirAll(dst, 0755); err != nil && !os.IsExist(err) { return err } logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) return archiver.TarUntar(src, dst) } // CopyWithTar creates a tar archive of filesystem path `src`, and // unpacks it at filesystem path `dst`. // The archive is streamed directly with fixed buffering and no // intermediary disk IO. func CopyWithTar(src, dst string) error { return defaultArchiver.CopyWithTar(src, dst) } func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) srcSt, err := os.Stat(src) if err != nil { return err } if srcSt.IsDir() { return fmt.Errorf("Can't copy a directory") } // Clean up the trailing slash. This must be done in an operating // system specific manner. if dst[len(dst)-1] == os.PathSeparator { dst = filepath.Join(dst, filepath.Base(src)) } // Create the holding directory if necessary if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil && !os.IsExist(err) { return err } r, w := io.Pipe() errC := promise.Go(func() error { defer w.Close() srcF, err := os.Open(src) if err != nil { return err } defer srcF.Close() hdr, err := tar.FileInfoHeader(srcSt, "") if err != nil { return err } hdr.Name = filepath.Base(dst) hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) tw := tar.NewWriter(w) defer tw.Close() if err := tw.WriteHeader(hdr); err != nil { return err } if _, err := io.Copy(tw, srcF); err != nil { return err } return nil }) defer func() { if er := <-errC; err != nil { err = er } }() return archiver.Untar(r, filepath.Dir(dst), nil) } // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. // // Destination handling is in an operating specific manner depending // where the daemon is running. If `dst` ends with a trailing slash // the final destination path will be `dst/base(src)` (Linux) or // `dst\base(src)` (Windows). func CopyFileWithTar(src, dst string) (err error) { return defaultArchiver.CopyFileWithTar(src, dst) } // CmdStream executes a command, and returns its stdout as a stream. // If the command fails to run or doesn't complete successfully, an error // will be returned, including anything written on stderr. func CmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, error) { if input != nil { stdin, err := cmd.StdinPipe() if err != nil { return nil, err } // Write stdin if any go func() { io.Copy(stdin, input) stdin.Close() }() } stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } stderr, err := cmd.StderrPipe() if err != nil { return nil, err } pipeR, pipeW := io.Pipe() errChan := make(chan []byte) // Collect stderr, we will use it in case of an error go func() { errText, e := ioutil.ReadAll(stderr) if e != nil { errText = []byte("(...couldn't fetch stderr: " + e.Error() + ")") } errChan <- errText }() // Copy stdout to the returned pipe go func() { _, err := io.Copy(pipeW, stdout) if err != nil { pipeW.CloseWithError(err) } errText := <-errChan if err := cmd.Wait(); err != nil { pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errText)) } else { pipeW.Close() } }() // Run the command and return the pipe if err := cmd.Start(); err != nil { return nil, err } return pipeR, nil } // NewTempArchive reads the content of src into a temporary file, and returns the contents // of that file as an archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. func NewTempArchive(src Archive, dir string) (*TempArchive, error) { f, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } if _, err := io.Copy(f, src); err != nil { return nil, err } if _, err := f.Seek(0, 0); err != nil { return nil, err } st, err := f.Stat() if err != nil { return nil, err } size := st.Size() return &TempArchive{File: f, Size: size}, nil } type TempArchive struct { *os.File Size int64 // Pre-computed from Stat().Size() as a convenience read int64 closed bool } // Close closes the underlying file if it's still open, or does a no-op // to allow callers to try to close the TempArchive multiple times safely. func (archive *TempArchive) Close() error { if archive.closed { return nil } archive.closed = true return archive.File.Close() } func (archive *TempArchive) Read(data []byte) (int, error) { n, err := archive.File.Read(data) archive.read += int64(n) if err != nil || archive.read == archive.Size { archive.Close() os.Remove(archive.File.Name()) } return n, err } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/archive_test.go ================================================ package archive import ( "archive/tar" "bytes" "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "syscall" "testing" "time" "github.com/docker/docker/pkg/system" ) func TestIsArchiveNilHeader(t *testing.T) { out := IsArchive(nil) if out { t.Fatalf("isArchive should return false as nil is not a valid archive header") } } func TestIsArchiveInvalidHeader(t *testing.T) { header := []byte{0x00, 0x01, 0x02} out := IsArchive(header) if out { t.Fatalf("isArchive should return false as %s is not a valid archive header", header) } } func TestIsArchiveBzip2(t *testing.T) { header := []byte{0x42, 0x5A, 0x68} out := IsArchive(header) if !out { t.Fatalf("isArchive should return true as %s is a bz2 header", header) } } func TestIsArchive7zip(t *testing.T) { header := []byte{0x50, 0x4b, 0x03, 0x04} out := IsArchive(header) if out { t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header) } } func TestDecompressStreamGzip(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } archive, err := os.Open("/tmp/archive.gz") _, err = DecompressStream(archive) if err != nil { t.Fatalf("Failed to decompress a gzip file.") } } func TestDecompressStreamBzip2(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } archive, err := os.Open("/tmp/archive.bz2") _, err = DecompressStream(archive) if err != nil { t.Fatalf("Failed to decompress a bzip2 file.") } } func TestDecompressStreamXz(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && xz -f /tmp/archive") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } archive, err := os.Open("/tmp/archive.xz") _, err = DecompressStream(archive) if err != nil { t.Fatalf("Failed to decompress a xz file.") } } func TestCompressStreamXzUnsuported(t *testing.T) { dest, err := os.Create("/tmp/dest") if err != nil { t.Fatalf("Fail to create the destination file") } _, err = CompressStream(dest, Xz) if err == nil { t.Fatalf("Should fail as xz is unsupported for compression format.") } } func TestCompressStreamBzip2Unsupported(t *testing.T) { dest, err := os.Create("/tmp/dest") if err != nil { t.Fatalf("Fail to create the destination file") } _, err = CompressStream(dest, Xz) if err == nil { t.Fatalf("Should fail as xz is unsupported for compression format.") } } func TestCompressStreamInvalid(t *testing.T) { dest, err := os.Create("/tmp/dest") if err != nil { t.Fatalf("Fail to create the destination file") } _, err = CompressStream(dest, -1) if err == nil { t.Fatalf("Should fail as xz is unsupported for compression format.") } } func TestExtensionInvalid(t *testing.T) { compression := Compression(-1) output := compression.Extension() if output != "" { t.Fatalf("The extension of an invalid compression should be an empty string.") } } func TestExtensionUncompressed(t *testing.T) { compression := Uncompressed output := compression.Extension() if output != "tar" { t.Fatalf("The extension of a uncompressed archive should be 'tar'.") } } func TestExtensionBzip2(t *testing.T) { compression := Bzip2 output := compression.Extension() if output != "tar.bz2" { t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'") } } func TestExtensionGzip(t *testing.T) { compression := Gzip output := compression.Extension() if output != "tar.gz" { t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'") } } func TestExtensionXz(t *testing.T) { compression := Xz output := compression.Extension() if output != "tar.xz" { t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'") } } func TestCmdStreamLargeStderr(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello") out, err := CmdStream(cmd, nil) if err != nil { t.Fatalf("Failed to start command: %s", err) } errCh := make(chan error) go func() { _, err := io.Copy(ioutil.Discard, out) errCh <- err }() select { case err := <-errCh: if err != nil { t.Fatalf("Command should not have failed (err=%.100s...)", err) } case <-time.After(5 * time.Second): t.Fatalf("Command did not complete in 5 seconds; probable deadlock") } } func TestCmdStreamBad(t *testing.T) { badCmd := exec.Command("/bin/sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1") out, err := CmdStream(badCmd, nil) if err != nil { t.Fatalf("Failed to start command: %s", err) } if output, err := ioutil.ReadAll(out); err == nil { t.Fatalf("Command should have failed") } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" { t.Fatalf("Wrong error value (%s)", err) } else if s := string(output); s != "hello\n" { t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) } } func TestCmdStreamGood(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "echo hello; exit 0") out, err := CmdStream(cmd, nil) if err != nil { t.Fatal(err) } if output, err := ioutil.ReadAll(out); err != nil { t.Fatalf("Command should not have failed (err=%s)", err) } else if s := string(output); s != "hello\n" { t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) } } func TestUntarPathWithInvalidDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) invalidDestFolder := path.Join(tempFolder, "invalidDest") // Create a src file srcFile := path.Join(tempFolder, "src") _, err = os.Create(srcFile) if err != nil { t.Fatalf("Fail to create the source file") } err = UntarPath(srcFile, invalidDestFolder) if err == nil { t.Fatalf("UntarPath with invalid destination path should throw an error.") } } func TestUntarPathWithInvalidSrc(t *testing.T) { dest, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatalf("Fail to create the destination file") } defer os.RemoveAll(dest) err = UntarPath("/invalid/path", dest) if err == nil { t.Fatalf("UntarPath with invalid src path should throw an error.") } } func TestUntarPath(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := path.Join(tmpFolder, "src") tarFile := path.Join(tmpFolder, "src.tar") os.Create(path.Join(tmpFolder, "src")) cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFolder := path.Join(tmpFolder, "dest") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatalf("Fail to create the destination file") } err = UntarPath(tarFile, destFolder) if err != nil { t.Fatalf("UntarPath shouldn't throw an error, %s.", err) } expectedFile := path.Join(destFolder, srcFile) _, err = os.Stat(expectedFile) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } } // Do the same test as above but with the destination as file, it should fail func TestUntarPathWithDestinationFile(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := path.Join(tmpFolder, "src") tarFile := path.Join(tmpFolder, "src.tar") os.Create(path.Join(tmpFolder, "src")) cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFile := path.Join(tmpFolder, "dest") _, err = os.Create(destFile) if err != nil { t.Fatalf("Fail to create the destination file") } err = UntarPath(tarFile, destFile) if err == nil { t.Fatalf("UntarPath should throw an error if the destination if a file") } } // Do the same test as above but with the destination folder already exists // and the destination file is a directory // It's working, see https://github.com/docker/docker/issues/10040 func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := path.Join(tmpFolder, "src") tarFile := path.Join(tmpFolder, "src.tar") os.Create(srcFile) cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFolder := path.Join(tmpFolder, "dest") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatalf("Fail to create the destination folder") } // Let's create a folder that will has the same path as the extracted file (from tar) destSrcFileAsFolder := path.Join(destFolder, srcFile) err = os.MkdirAll(destSrcFileAsFolder, 0740) if err != nil { t.Fatal(err) } err = UntarPath(tarFile, destFolder) if err != nil { t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder") } } func TestCopyWithTarInvalidSrc(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(nil) } destFolder := path.Join(tempFolder, "dest") invalidSrc := path.Join(tempFolder, "doesnotexists") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatal(err) } err = CopyWithTar(invalidSrc, destFolder) if err == nil { t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") } } func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(nil) } srcFolder := path.Join(tempFolder, "src") inexistentDestFolder := path.Join(tempFolder, "doesnotexists") err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = CopyWithTar(srcFolder, inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") } _, err = os.Stat(inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder should create it.") } } // Test CopyWithTar with a file as src func TestCopyWithTarSrcFile(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") srcFolder := path.Join(folder, "src") src := path.Join(folder, path.Join("src", "src")) err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(src, []byte("content"), 0777) err = CopyWithTar(src, dest) if err != nil { t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) // FIXME Check the content if err != nil { t.Fatalf("Destination file should be the same as the source.") } } // Test CopyWithTar with a folder as src func TestCopyWithTarSrcFolder(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") src := path.Join(folder, path.Join("src", "folder")) err = os.MkdirAll(src, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(path.Join(src, "file"), []byte("content"), 0777) err = CopyWithTar(src, dest) if err != nil { t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) // FIXME Check the content (the file inside) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } } func TestCopyFileWithTarInvalidSrc(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) destFolder := path.Join(tempFolder, "dest") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatal(err) } invalidFile := path.Join(tempFolder, "doesnotexists") err = CopyFileWithTar(invalidFile, destFolder) if err == nil { t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") } } func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(nil) } defer os.RemoveAll(tempFolder) srcFile := path.Join(tempFolder, "src") inexistentDestFolder := path.Join(tempFolder, "doesnotexists") _, err = os.Create(srcFile) if err != nil { t.Fatal(err) } err = CopyFileWithTar(srcFile, inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") } _, err = os.Stat(inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder should create it.") } // FIXME Test the src file and content } func TestCopyFileWithTarSrcFolder(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") src := path.Join(folder, "srcfolder") err = os.MkdirAll(src, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } err = CopyFileWithTar(src, dest) if err == nil { t.Fatalf("CopyFileWithTar should throw an error with a folder.") } } func TestCopyFileWithTarSrcFile(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") srcFolder := path.Join(folder, "src") src := path.Join(folder, path.Join("src", "src")) err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(src, []byte("content"), 0777) err = CopyWithTar(src, dest+"/") if err != nil { t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } } func TestTarFiles(t *testing.T) { // try without hardlinks if err := checkNoChanges(1000, false); err != nil { t.Fatal(err) } // try with hardlinks if err := checkNoChanges(1000, true); err != nil { t.Fatal(err) } } func checkNoChanges(fileNum int, hardlinks bool) error { srcDir, err := ioutil.TempDir("", "docker-test-srcDir") if err != nil { return err } defer os.RemoveAll(srcDir) destDir, err := ioutil.TempDir("", "docker-test-destDir") if err != nil { return err } defer os.RemoveAll(destDir) _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks) if err != nil { return err } err = TarUntar(srcDir, destDir) if err != nil { return err } changes, err := ChangesDirs(destDir, srcDir) if err != nil { return err } if len(changes) > 0 { return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes)) } return nil } func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) { archive, err := TarWithOptions(origin, options) if err != nil { t.Fatal(err) } defer archive.Close() buf := make([]byte, 10) if _, err := archive.Read(buf); err != nil { return nil, err } wrap := io.MultiReader(bytes.NewReader(buf), archive) detectedCompression := DetectCompression(buf) compression := options.Compression if detectedCompression.Extension() != compression.Extension() { return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension()) } tmp, err := ioutil.TempDir("", "docker-test-untar") if err != nil { return nil, err } defer os.RemoveAll(tmp) if err := Untar(wrap, tmp, nil); err != nil { return nil, err } if _, err := os.Stat(tmp); err != nil { return nil, err } return ChangesDirs(origin, tmp) } func TestTarUntar(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { t.Fatal(err) } for _, c := range []Compression{ Uncompressed, Gzip, } { changes, err := tarUntar(t, origin, &TarOptions{ Compression: c, ExcludePatterns: []string{"3"}, }) if err != nil { t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) } if len(changes) != 1 || changes[0].Path != "/3" { t.Fatalf("Unexpected differences after tarUntar: %v", changes) } } } func TestTarUntarWithXattr(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { t.Fatal(err) } if err := system.Lsetxattr(path.Join(origin, "2"), "security.capability", []byte{0x00}, 0); err != nil { t.Fatal(err) } for _, c := range []Compression{ Uncompressed, Gzip, } { changes, err := tarUntar(t, origin, &TarOptions{ Compression: c, ExcludePatterns: []string{"3"}, }) if err != nil { t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) } if len(changes) != 1 || changes[0].Path != "/3" { t.Fatalf("Unexpected differences after tarUntar: %v", changes) } capability, _ := system.Lgetxattr(path.Join(origin, "2"), "security.capability") if capability == nil && capability[0] != 0x00 { t.Fatalf("Untar should have kept the 'security.capability' xattr.") } } } func TestTarWithOptions(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { t.Fatal(err) } if _, err := ioutil.TempDir(origin, "folder"); err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { t.Fatal(err) } cases := []struct { opts *TarOptions numChanges int }{ {&TarOptions{IncludeFiles: []string{"1"}}, 2}, {&TarOptions{ExcludePatterns: []string{"2"}}, 1}, {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2}, {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2}, {&TarOptions{Name: "test", IncludeFiles: []string{"1"}}, 4}, } for _, testCase := range cases { changes, err := tarUntar(t, origin, testCase.opts) if err != nil { t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err) } if len(changes) != testCase.numChanges { t.Errorf("Expected %d changes, got %d for %+v:", testCase.numChanges, len(changes), testCase.opts) } } } // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz // use PAX Global Extended Headers. // Failing prevents the archives from being uncompressed during ADD func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) { hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader} tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil) if err != nil { t.Fatal(err) } } // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work. func TestUntarUstarGnuConflict(t *testing.T) { f, err := os.Open("testdata/broken.tar") if err != nil { t.Fatal(err) } found := false tr := tar.NewReader(f) // Iterate through the files in the archive. for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { t.Fatal(err) } if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" { found = true break } } if !found { t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm") } } func TestTarWithBlockCharFifo(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := system.Mknod(path.Join(origin, "2"), syscall.S_IFBLK, int(system.Mkdev(int64(12), int64(5)))); err != nil { t.Fatal(err) } if err := system.Mknod(path.Join(origin, "3"), syscall.S_IFCHR, int(system.Mkdev(int64(12), int64(5)))); err != nil { t.Fatal(err) } if err := system.Mknod(path.Join(origin, "4"), syscall.S_IFIFO, int(system.Mkdev(int64(12), int64(5)))); err != nil { t.Fatal(err) } dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") if err != nil { t.Fatal(err) } defer os.RemoveAll(dest) // we'll do this in two steps to separate failure fh, err := Tar(origin, Uncompressed) if err != nil { t.Fatal(err) } // ensure we can read the whole thing with no error, before writing back out buf, err := ioutil.ReadAll(fh) if err != nil { t.Fatal(err) } bRdr := bytes.NewReader(buf) err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) if err != nil { t.Fatal(err) } changes, err := ChangesDirs(origin, dest) if err != nil { t.Fatal(err) } if len(changes) > 0 { t.Fatalf("Tar with special device (block, char, fifo) should keep them (recreate them when untar) : %v", changes) } } func TestTarWithHardLink(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := os.Link(path.Join(origin, "1"), path.Join(origin, "2")); err != nil { t.Fatal(err) } var i1, i2 uint64 if i1, err = getNlink(path.Join(origin, "1")); err != nil { t.Fatal(err) } // sanity check that we can hardlink if i1 != 2 { t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1) } dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") if err != nil { t.Fatal(err) } defer os.RemoveAll(dest) // we'll do this in two steps to separate failure fh, err := Tar(origin, Uncompressed) if err != nil { t.Fatal(err) } // ensure we can read the whole thing with no error, before writing back out buf, err := ioutil.ReadAll(fh) if err != nil { t.Fatal(err) } bRdr := bytes.NewReader(buf) err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) if err != nil { t.Fatal(err) } if i1, err = getInode(path.Join(dest, "1")); err != nil { t.Fatal(err) } if i2, err = getInode(path.Join(dest, "2")); err != nil { t.Fatal(err) } if i1 != i2 { t.Errorf("expected matching inodes, but got %d and %d", i1, i2) } } func getNlink(path string) (uint64, error) { stat, err := os.Stat(path) if err != nil { return 0, err } statT, ok := stat.Sys().(*syscall.Stat_t) if !ok { return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) } // We need this conversion on ARM64 return uint64(statT.Nlink), nil } func getInode(path string) (uint64, error) { stat, err := os.Stat(path) if err != nil { return 0, err } statT, ok := stat.Sys().(*syscall.Stat_t) if !ok { return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) } return statT.Ino, nil } func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { return 0, err } if makeLinks { if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { return 0, err } } } totalSize := numberOfFiles * len(fileData) return totalSize, nil } func BenchmarkTarUntar(b *testing.B) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { b.Fatal(err) } tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") if err != nil { b.Fatal(err) } target := path.Join(tempDir, "dest") n, err := prepareUntarSourceDirectory(100, origin, false) if err != nil { b.Fatal(err) } defer os.RemoveAll(origin) defer os.RemoveAll(tempDir) b.ResetTimer() b.SetBytes(int64(n)) for n := 0; n < b.N; n++ { err := TarUntar(origin, target) if err != nil { b.Fatal(err) } os.RemoveAll(target) } } func BenchmarkTarUntarWithLinks(b *testing.B) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { b.Fatal(err) } tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") if err != nil { b.Fatal(err) } target := path.Join(tempDir, "dest") n, err := prepareUntarSourceDirectory(100, origin, true) if err != nil { b.Fatal(err) } defer os.RemoveAll(origin) defer os.RemoveAll(tempDir) b.ResetTimer() b.SetBytes(int64(n)) for n := 0; n < b.N; n++ { err := TarUntar(origin, target) if err != nil { b.Fatal(err) } os.RemoveAll(target) } } func TestUntarInvalidFilenames(t *testing.T) { for i, headers := range [][]*tar.Header{ { { Name: "../victim/dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, { { // Note the leading slash Name: "/../victim/slash-dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestUntarHardlinkToSymlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { { Name: "symlink1", Typeflag: tar.TypeSymlink, Linkname: "regfile", Mode: 0644, }, { Name: "symlink2", Typeflag: tar.TypeLink, Linkname: "symlink1", Mode: 0644, }, { Name: "regfile", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestUntarInvalidHardlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeLink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeLink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (hardlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try reading victim/hello (hardlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try removing victim directory (hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestUntarInvalidSymlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeSymlink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeSymlink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (symlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try reading victim/hello (symlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try removing victim directory (symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try writing to victim/newdir/newfile with a symlink in the path { // this header needs to be before the next one, or else there is an error Name: "dir/loophole", Typeflag: tar.TypeSymlink, Linkname: "../../victim", Mode: 0755, }, { Name: "dir/loophole/newdir/newfile", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestTempArchiveCloseMultipleTimes(t *testing.T) { reader := ioutil.NopCloser(strings.NewReader("hello")) tempArchive, err := NewTempArchive(reader, "") buf := make([]byte, 10) n, err := tempArchive.Read(buf) if n != 5 { t.Fatalf("Expected to read 5 bytes. Read %d instead", n) } for i := 0; i < 3; i++ { if err = tempArchive.Close(); err != nil { t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/archive_unix.go ================================================ // +build !windows package archive import ( "archive/tar" "errors" "os" "syscall" "github.com/docker/docker/pkg/system" ) // CanonicalTarNameForPath returns platform-specific filepath // to canonical posix-style path for tar archival. p is relative // path. func CanonicalTarNameForPath(p string) (string, error) { return p, nil // already unix-style } // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. func chmodTarEntry(perm os.FileMode) os.FileMode { return perm // noop for unix as golang APIs provide perm bits correctly } func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) { s, ok := stat.(*syscall.Stat_t) if !ok { err = errors.New("cannot convert stat value to syscall.Stat_t") return } nlink = uint32(s.Nlink) inode = uint64(s.Ino) // Currently go does not fil in the major/minors if s.Mode&syscall.S_IFBLK != 0 || s.Mode&syscall.S_IFCHR != 0 { hdr.Devmajor = int64(major(uint64(s.Rdev))) hdr.Devminor = int64(minor(uint64(s.Rdev))) } return } func major(device uint64) uint64 { return (device >> 8) & 0xfff } func minor(device uint64) uint64 { return (device & 0xff) | ((device >> 12) & 0xfff00) } // handleTarTypeBlockCharFifo is an OS-specific helper function used by // createTarFile to handle the following types of header: Block; Char; Fifo func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { mode := uint32(hdr.Mode & 07777) switch hdr.Typeflag { case tar.TypeBlock: mode |= syscall.S_IFBLK case tar.TypeChar: mode |= syscall.S_IFCHR case tar.TypeFifo: mode |= syscall.S_IFIFO } if err := system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))); err != nil { return err } return nil } func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { if hdr.Typeflag == tar.TypeLink { if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { if err := os.Chmod(path, hdrInfo.Mode()); err != nil { return err } } } else if hdr.Typeflag != tar.TypeSymlink { if err := os.Chmod(path, hdrInfo.Mode()); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/archive_unix_test.go ================================================ // +build !windows package archive import ( "os" "testing" ) func TestCanonicalTarNameForPath(t *testing.T) { cases := []struct{ in, expected string }{ {"foo", "foo"}, {"foo/bar", "foo/bar"}, {"foo/dir/", "foo/dir/"}, } for _, v := range cases { if out, err := CanonicalTarNameForPath(v.in); err != nil { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestCanonicalTarName(t *testing.T) { cases := []struct { in string isDir bool expected string }{ {"foo", false, "foo"}, {"foo", true, "foo/"}, {"foo/bar", false, "foo/bar"}, {"foo/bar", true, "foo/bar/"}, } for _, v := range cases { if out, err := canonicalTarName(v.in, v.isDir); err != nil { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestChmodTarEntry(t *testing.T) { cases := []struct { in, expected os.FileMode }{ {0000, 0000}, {0777, 0777}, {0644, 0644}, {0755, 0755}, {0444, 0444}, } for _, v := range cases { if out := chmodTarEntry(v.in); out != v.expected { t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/archive_windows.go ================================================ // +build windows package archive import ( "archive/tar" "fmt" "os" "strings" ) // canonicalTarNameForPath returns platform-specific filepath // to canonical posix-style path for tar archival. p is relative // path. func CanonicalTarNameForPath(p string) (string, error) { // windows: convert windows style relative path with backslashes // into forward slashes. Since windows does not allow '/' or '\' // in file names, it is mostly safe to replace however we must // check just in case if strings.Contains(p, "/") { return "", fmt.Errorf("Windows path contains forward slash: %s", p) } return strings.Replace(p, string(os.PathSeparator), "/", -1), nil } // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. func chmodTarEntry(perm os.FileMode) os.FileMode { perm &= 0755 // Add the x bit: make everything +x from windows perm |= 0111 return perm } func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (nlink uint32, inode uint64, err error) { // do nothing. no notion of Rdev, Inode, Nlink in stat on Windows return } // handleTarTypeBlockCharFifo is an OS-specific helper function used by // createTarFile to handle the following types of header: Block; Char; Fifo func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { return nil } func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/archive_windows_test.go ================================================ // +build windows package archive import ( "os" "testing" ) func TestCanonicalTarNameForPath(t *testing.T) { cases := []struct { in, expected string shouldFail bool }{ {"foo", "foo", false}, {"foo/bar", "___", true}, // unix-styled windows path must fail {`foo\bar`, "foo/bar", false}, } for _, v := range cases { if out, err := CanonicalTarNameForPath(v.in); err != nil && !v.shouldFail { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if v.shouldFail && err == nil { t.Fatalf("canonical path call should have failed with error. in=%s out=%s", v.in, out) } else if !v.shouldFail && out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestCanonicalTarName(t *testing.T) { cases := []struct { in string isDir bool expected string }{ {"foo", false, "foo"}, {"foo", true, "foo/"}, {`foo\bar`, false, "foo/bar"}, {`foo\bar`, true, "foo/bar/"}, } for _, v := range cases { if out, err := canonicalTarName(v.in, v.isDir); err != nil { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestChmodTarEntry(t *testing.T) { cases := []struct { in, expected os.FileMode }{ {0000, 0111}, {0777, 0755}, {0644, 0755}, {0755, 0755}, {0444, 0555}, } for _, v := range cases { if out := chmodTarEntry(v.in); out != v.expected { t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes.go ================================================ package archive import ( "archive/tar" "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "sort" "strings" "syscall" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/system" ) type ChangeType int const ( ChangeModify = iota ChangeAdd ChangeDelete ) type Change struct { Path string Kind ChangeType } func (change *Change) String() string { var kind string switch change.Kind { case ChangeModify: kind = "C" case ChangeAdd: kind = "A" case ChangeDelete: kind = "D" } return fmt.Sprintf("%s %s", kind, change.Path) } // for sort.Sort type changesByPath []Change func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path } func (c changesByPath) Len() int { return len(c) } func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] } // Gnu tar and the go tar writer don't have sub-second mtime // precision, which is problematic when we apply changes via tar // files, we handle this by comparing for exact times, *or* same // second count and either a or b having exactly 0 nanoseconds func sameFsTime(a, b time.Time) bool { return a == b || (a.Unix() == b.Unix() && (a.Nanosecond() == 0 || b.Nanosecond() == 0)) } func sameFsTimeSpec(a, b syscall.Timespec) bool { return a.Sec == b.Sec && (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0) } // Changes walks the path rw and determines changes for the files in the path, // with respect to the parent layers func Changes(layers []string, rw string) ([]Change, error) { var ( changes []Change changedDirs = make(map[string]struct{}) ) err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path path, err = filepath.Rel(rw, path) if err != nil { return err } // As this runs on the daemon side, file paths are OS specific. path = filepath.Join(string(os.PathSeparator), path) // Skip root if path == string(os.PathSeparator) { return nil } // Skip AUFS metadata if matched, err := filepath.Match(string(os.PathSeparator)+".wh..wh.*", path); err != nil || matched { return err } change := Change{ Path: path, } // Find out what kind of modification happened file := filepath.Base(path) // If there is a whiteout, then the file was removed if strings.HasPrefix(file, ".wh.") { originalFile := file[len(".wh."):] change.Path = filepath.Join(filepath.Dir(path), originalFile) change.Kind = ChangeDelete } else { // Otherwise, the file was added change.Kind = ChangeAdd // ...Unless it already existed in a top layer, in which case, it's a modification for _, layer := range layers { stat, err := os.Stat(filepath.Join(layer, path)) if err != nil && !os.IsNotExist(err) { return err } if err == nil { // The file existed in the top layer, so that's a modification // However, if it's a directory, maybe it wasn't actually modified. // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar if stat.IsDir() && f.IsDir() { if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { // Both directories are the same, don't record the change return nil } } change.Kind = ChangeModify break } } } // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. // This block is here to ensure the change is recorded even if the // modify time, mode and size of the parent directoriy in the rw and ro layers are all equal. // Check https://github.com/docker/docker/pull/13590 for details. if f.IsDir() { changedDirs[path] = struct{}{} } if change.Kind == ChangeAdd || change.Kind == ChangeDelete { parent := filepath.Dir(path) if _, ok := changedDirs[parent]; !ok && parent != "/" { changes = append(changes, Change{Path: parent, Kind: ChangeModify}) changedDirs[parent] = struct{}{} } } // Record change changes = append(changes, change) return nil }) if err != nil && !os.IsNotExist(err) { return nil, err } return changes, nil } type FileInfo struct { parent *FileInfo name string stat *system.Stat_t children map[string]*FileInfo capability []byte added bool } func (root *FileInfo) LookUp(path string) *FileInfo { // As this runs on the daemon side, file paths are OS specific. parent := root if path == string(os.PathSeparator) { return root } pathElements := strings.Split(path, string(os.PathSeparator)) for _, elem := range pathElements { if elem != "" { child := parent.children[elem] if child == nil { return nil } parent = child } } return parent } func (info *FileInfo) path() string { if info.parent == nil { // As this runs on the daemon side, file paths are OS specific. return string(os.PathSeparator) } return filepath.Join(info.parent.path(), info.name) } func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { sizeAtEntry := len(*changes) if oldInfo == nil { // add change := Change{ Path: info.path(), Kind: ChangeAdd, } *changes = append(*changes, change) info.added = true } // We make a copy so we can modify it to detect additions // also, we only recurse on the old dir if the new info is a directory // otherwise any previous delete/change is considered recursive oldChildren := make(map[string]*FileInfo) if oldInfo != nil && info.isDir() { for k, v := range oldInfo.children { oldChildren[k] = v } } for name, newChild := range info.children { oldChild, _ := oldChildren[name] if oldChild != nil { // change? oldStat := oldChild.stat newStat := newChild.stat // Note: We can't compare inode or ctime or blocksize here, because these change // when copying a file into a container. However, that is not generally a problem // because any content change will change mtime, and any status change should // be visible when actually comparing the stat fields. The only time this // breaks down is if some code intentionally hides a change by setting // back mtime if statDifferent(oldStat, newStat) || bytes.Compare(oldChild.capability, newChild.capability) != 0 { change := Change{ Path: newChild.path(), Kind: ChangeModify, } *changes = append(*changes, change) newChild.added = true } // Remove from copy so we can detect deletions delete(oldChildren, name) } newChild.addChanges(oldChild, changes) } for _, oldChild := range oldChildren { // delete change := Change{ Path: oldChild.path(), Kind: ChangeDelete, } *changes = append(*changes, change) } // If there were changes inside this directory, we need to add it, even if the directory // itself wasn't changed. This is needed to properly save and restore filesystem permissions. // As this runs on the daemon side, file paths are OS specific. if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) { change := Change{ Path: info.path(), Kind: ChangeModify, } // Let's insert the directory entry before the recently added entries located inside this dir *changes = append(*changes, change) // just to resize the slice, will be overwritten copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) (*changes)[sizeAtEntry] = change } } func (info *FileInfo) Changes(oldInfo *FileInfo) []Change { var changes []Change info.addChanges(oldInfo, &changes) return changes } func newRootFileInfo() *FileInfo { // As this runs on the daemon side, file paths are OS specific. root := &FileInfo{ name: string(os.PathSeparator), children: make(map[string]*FileInfo), } return root } // ChangesDirs compares two directories and generates an array of Change objects describing the changes. // If oldDir is "", then all files in newDir will be Add-Changes. func ChangesDirs(newDir, oldDir string) ([]Change, error) { var ( oldRoot, newRoot *FileInfo ) if oldDir == "" { emptyDir, err := ioutil.TempDir("", "empty") if err != nil { return nil, err } defer os.Remove(emptyDir) oldDir = emptyDir } oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) if err != nil { return nil, err } return newRoot.Changes(oldRoot), nil } // ChangesSize calculates the size in bytes of the provided changes, based on newDir. func ChangesSize(newDir string, changes []Change) int64 { var size int64 for _, change := range changes { if change.Kind == ChangeModify || change.Kind == ChangeAdd { file := filepath.Join(newDir, change.Path) fileInfo, _ := os.Lstat(file) if fileInfo != nil && !fileInfo.IsDir() { size += fileInfo.Size() } } } return size } // ExportChanges produces an Archive from the provided changes, relative to dir. func ExportChanges(dir string, changes []Change) (Archive, error) { reader, writer := io.Pipe() go func() { ta := &tarAppender{ TarWriter: tar.NewWriter(writer), Buffer: pools.BufioWriter32KPool.Get(nil), SeenFiles: make(map[uint64]string), } // this buffer is needed for the duration of this piped stream defer pools.BufioWriter32KPool.Put(ta.Buffer) sort.Sort(changesByPath(changes)) // In general we log errors here but ignore them because // during e.g. a diff operation the container can continue // mutating the filesystem and we can see transient errors // from this for _, change := range changes { if change.Kind == ChangeDelete { whiteOutDir := filepath.Dir(change.Path) whiteOutBase := filepath.Base(change.Path) whiteOut := filepath.Join(whiteOutDir, ".wh."+whiteOutBase) timestamp := time.Now() hdr := &tar.Header{ Name: whiteOut[1:], Size: 0, ModTime: timestamp, AccessTime: timestamp, ChangeTime: timestamp, } if err := ta.TarWriter.WriteHeader(hdr); err != nil { logrus.Debugf("Can't write whiteout header: %s", err) } } else { path := filepath.Join(dir, change.Path) if err := ta.addTarFile(path, change.Path[1:]); err != nil { logrus.Debugf("Can't add file %s to tar: %s", path, err) } } } // Make sure to check the error on Close. if err := ta.TarWriter.Close(); err != nil { logrus.Debugf("Can't close layer: %s", err) } if err := writer.Close(); err != nil { logrus.Debugf("failed close Changes writer: %s", err) } }() return reader, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes_linux.go ================================================ package archive import ( "bytes" "fmt" "os" "path/filepath" "sort" "syscall" "unsafe" "github.com/docker/docker/pkg/system" ) // walker is used to implement collectFileInfoForChanges on linux. Where this // method in general returns the entire contents of two directory trees, we // optimize some FS calls out on linux. In particular, we take advantage of the // fact that getdents(2) returns the inode of each file in the directory being // walked, which, when walking two trees in parallel to generate a list of // changes, can be used to prune subtrees without ever having to lstat(2) them // directly. Eliminating stat calls in this way can save up to seconds on large // images. type walker struct { dir1 string dir2 string root1 *FileInfo root2 *FileInfo } // collectFileInfoForChanges returns a complete representation of the trees // rooted at dir1 and dir2, with one important exception: any subtree or // leaf where the inode and device numbers are an exact match between dir1 // and dir2 will be pruned from the results. This method is *only* to be used // to generating a list of changes between the two directories, as it does not // reflect the full contents. func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { w := &walker{ dir1: dir1, dir2: dir2, root1: newRootFileInfo(), root2: newRootFileInfo(), } i1, err := os.Lstat(w.dir1) if err != nil { return nil, nil, err } i2, err := os.Lstat(w.dir2) if err != nil { return nil, nil, err } if err := w.walk("/", i1, i2); err != nil { return nil, nil, err } return w.root1, w.root2, nil } // Given a FileInfo, its path info, and a reference to the root of the tree // being constructed, register this file with the tree. func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { if fi == nil { return nil } parent := root.LookUp(filepath.Dir(path)) if parent == nil { return fmt.Errorf("collectFileInfoForChanges: Unexpectedly no parent for %s", path) } info := &FileInfo{ name: filepath.Base(path), children: make(map[string]*FileInfo), parent: parent, } cpath := filepath.Join(dir, path) stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) if err != nil { return err } info.stat = stat info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access parent.children[info.name] = info return nil } // Walk a subtree rooted at the same path in both trees being iterated. For // example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { // Register these nodes with the return trees, unless we're still at the // (already-created) roots: if path != "/" { if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { return err } if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { return err } } is1Dir := i1 != nil && i1.IsDir() is2Dir := i2 != nil && i2.IsDir() sameDevice := false if i1 != nil && i2 != nil { si1 := i1.Sys().(*syscall.Stat_t) si2 := i2.Sys().(*syscall.Stat_t) if si1.Dev == si2.Dev { sameDevice = true } } // If these files are both non-existent, or leaves (non-dirs), we are done. if !is1Dir && !is2Dir { return nil } // Fetch the names of all the files contained in both directories being walked: var names1, names2 []nameIno if is1Dir { names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access if err != nil { return err } } if is2Dir { names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access if err != nil { return err } } // We have lists of the files contained in both parallel directories, sorted // in the same order. Walk them in parallel, generating a unique merged list // of all items present in either or both directories. var names []string ix1 := 0 ix2 := 0 for { if ix1 >= len(names1) { break } if ix2 >= len(names2) { break } ni1 := names1[ix1] ni2 := names2[ix2] switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { case -1: // ni1 < ni2 -- advance ni1 // we will not encounter ni1 in names2 names = append(names, ni1.name) ix1++ case 0: // ni1 == ni2 if ni1.ino != ni2.ino || !sameDevice { names = append(names, ni1.name) } ix1++ ix2++ case 1: // ni1 > ni2 -- advance ni2 // we will not encounter ni2 in names1 names = append(names, ni2.name) ix2++ } } for ix1 < len(names1) { names = append(names, names1[ix1].name) ix1++ } for ix2 < len(names2) { names = append(names, names2[ix2].name) ix2++ } // For each of the names present in either or both of the directories being // iterated, stat the name under each root, and recurse the pair of them: for _, name := range names { fname := filepath.Join(path, name) var cInfo1, cInfo2 os.FileInfo if is1Dir { cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access if err != nil && !os.IsNotExist(err) { return err } } if is2Dir { cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access if err != nil && !os.IsNotExist(err) { return err } } if err = w.walk(fname, cInfo1, cInfo2); err != nil { return err } } return nil } // {name,inode} pairs used to support the early-pruning logic of the walker type type nameIno struct { name string ino uint64 } type nameInoSlice []nameIno func (s nameInoSlice) Len() int { return len(s) } func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } // readdirnames is a hacked-apart version of the Go stdlib code, exposing inode // numbers further up the stack when reading directory contents. Unlike // os.Readdirnames, which returns a list of filenames, this function returns a // list of {filename,inode} pairs. func readdirnames(dirname string) (names []nameIno, err error) { var ( size = 100 buf = make([]byte, 4096) nbuf int bufp int nb int ) f, err := os.Open(dirname) if err != nil { return nil, err } defer f.Close() names = make([]nameIno, 0, size) // Empty with room to grow. for { // Refill the buffer if necessary if bufp >= nbuf { bufp = 0 nbuf, err = syscall.ReadDirent(int(f.Fd()), buf) // getdents on linux if nbuf < 0 { nbuf = 0 } if err != nil { return nil, os.NewSyscallError("readdirent", err) } if nbuf <= 0 { break // EOF } } // Drain the buffer nb, names = parseDirent(buf[bufp:nbuf], names) bufp += nb } sl := nameInoSlice(names) sort.Sort(sl) return sl, nil } // parseDirent is a minor modification of syscall.ParseDirent (linux version) // which returns {name,inode} pairs instead of just names. func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { origlen := len(buf) for len(buf) > 0 { dirent := (*syscall.Dirent)(unsafe.Pointer(&buf[0])) buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } names = append(names, nameIno{name, dirent.Ino}) } return origlen - len(buf), names } func clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes_other.go ================================================ // +build !linux package archive import ( "fmt" "os" "path/filepath" "runtime" "strings" "github.com/docker/docker/pkg/system" ) func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { var ( oldRoot, newRoot *FileInfo err1, err2 error errs = make(chan error, 2) ) go func() { oldRoot, err1 = collectFileInfo(oldDir) errs <- err1 }() go func() { newRoot, err2 = collectFileInfo(newDir) errs <- err2 }() // block until both routines have returned for i := 0; i < 2; i++ { if err := <-errs; err != nil { return nil, nil, err } } return oldRoot, newRoot, nil } func collectFileInfo(sourceDir string) (*FileInfo, error) { root := newRootFileInfo() err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path relPath, err := filepath.Rel(sourceDir, path) if err != nil { return err } // As this runs on the daemon side, file paths are OS specific. relPath = filepath.Join(string(os.PathSeparator), relPath) // See https://github.com/golang/go/issues/9168 - bug in filepath.Join. // Temporary workaround. If the returned path starts with two backslashes, // trim it down to a single backslash. Only relevant on Windows. if runtime.GOOS == "windows" { if strings.HasPrefix(relPath, `\\`) { relPath = relPath[1:] } } if relPath == string(os.PathSeparator) { return nil } parent := root.LookUp(filepath.Dir(relPath)) if parent == nil { return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) } info := &FileInfo{ name: filepath.Base(relPath), children: make(map[string]*FileInfo), parent: parent, } s, err := system.Lstat(path) if err != nil { return err } info.stat = s info.capability, _ = system.Lgetxattr(path, "security.capability") parent.children[info.name] = info return nil }) if err != nil { return nil, err } return root, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes_posix_test.go ================================================ package archive import ( "archive/tar" "fmt" "io" "io/ioutil" "os" "path" "sort" "testing" ) func TestHardLinkOrder(t *testing.T) { names := []string{"file1.txt", "file2.txt", "file3.txt"} msg := []byte("Hey y'all") // Create dir src, err := ioutil.TempDir("", "docker-hardlink-test-src-") if err != nil { t.Fatal(err) } //defer os.RemoveAll(src) for _, name := range names { func() { fh, err := os.Create(path.Join(src, name)) if err != nil { t.Fatal(err) } defer fh.Close() if _, err = fh.Write(msg); err != nil { t.Fatal(err) } }() } // Create dest, with changes that includes hardlinks dest, err := ioutil.TempDir("", "docker-hardlink-test-dest-") if err != nil { t.Fatal(err) } os.RemoveAll(dest) // we just want the name, at first if err := copyDir(src, dest); err != nil { t.Fatal(err) } defer os.RemoveAll(dest) for _, name := range names { for i := 0; i < 5; i++ { if err := os.Link(path.Join(dest, name), path.Join(dest, fmt.Sprintf("%s.link%d", name, i))); err != nil { t.Fatal(err) } } } // get changes changes, err := ChangesDirs(dest, src) if err != nil { t.Fatal(err) } // sort sort.Sort(changesByPath(changes)) // ExportChanges ar, err := ExportChanges(dest, changes) if err != nil { t.Fatal(err) } hdrs, err := walkHeaders(ar) if err != nil { t.Fatal(err) } // reverse sort sort.Sort(sort.Reverse(changesByPath(changes))) // ExportChanges arRev, err := ExportChanges(dest, changes) if err != nil { t.Fatal(err) } hdrsRev, err := walkHeaders(arRev) if err != nil { t.Fatal(err) } // line up the two sets sort.Sort(tarHeaders(hdrs)) sort.Sort(tarHeaders(hdrsRev)) // compare Size and LinkName for i := range hdrs { if hdrs[i].Name != hdrsRev[i].Name { t.Errorf("headers - expected name %q; but got %q", hdrs[i].Name, hdrsRev[i].Name) } if hdrs[i].Size != hdrsRev[i].Size { t.Errorf("headers - %q expected size %d; but got %d", hdrs[i].Name, hdrs[i].Size, hdrsRev[i].Size) } if hdrs[i].Typeflag != hdrsRev[i].Typeflag { t.Errorf("headers - %q expected type %d; but got %d", hdrs[i].Name, hdrs[i].Typeflag, hdrsRev[i].Typeflag) } if hdrs[i].Linkname != hdrsRev[i].Linkname { t.Errorf("headers - %q expected linkname %q; but got %q", hdrs[i].Name, hdrs[i].Linkname, hdrsRev[i].Linkname) } } } type tarHeaders []tar.Header func (th tarHeaders) Len() int { return len(th) } func (th tarHeaders) Swap(i, j int) { th[j], th[i] = th[i], th[j] } func (th tarHeaders) Less(i, j int) bool { return th[i].Name < th[j].Name } func walkHeaders(r io.Reader) ([]tar.Header, error) { t := tar.NewReader(r) headers := []tar.Header{} for { hdr, err := t.Next() if err != nil { if err == io.EOF { break } return headers, err } headers = append(headers, *hdr) } return headers, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes_test.go ================================================ package archive import ( "io/ioutil" "os" "os/exec" "path" "sort" "testing" "time" ) func max(x, y int) int { if x >= y { return x } return y } func copyDir(src, dst string) error { cmd := exec.Command("cp", "-a", src, dst) if err := cmd.Run(); err != nil { return err } return nil } type FileType uint32 const ( Regular FileType = iota Dir Symlink ) type FileData struct { filetype FileType path string contents string permissions os.FileMode } func createSampleDir(t *testing.T, root string) { files := []FileData{ {Regular, "file1", "file1\n", 0600}, {Regular, "file2", "file2\n", 0666}, {Regular, "file3", "file3\n", 0404}, {Regular, "file4", "file4\n", 0600}, {Regular, "file5", "file5\n", 0600}, {Regular, "file6", "file6\n", 0600}, {Regular, "file7", "file7\n", 0600}, {Dir, "dir1", "", 0740}, {Regular, "dir1/file1-1", "file1-1\n", 01444}, {Regular, "dir1/file1-2", "file1-2\n", 0666}, {Dir, "dir2", "", 0700}, {Regular, "dir2/file2-1", "file2-1\n", 0666}, {Regular, "dir2/file2-2", "file2-2\n", 0666}, {Dir, "dir3", "", 0700}, {Regular, "dir3/file3-1", "file3-1\n", 0666}, {Regular, "dir3/file3-2", "file3-2\n", 0666}, {Dir, "dir4", "", 0700}, {Regular, "dir4/file3-1", "file4-1\n", 0666}, {Regular, "dir4/file3-2", "file4-2\n", 0666}, {Symlink, "symlink1", "target1", 0666}, {Symlink, "symlink2", "target2", 0666}, } now := time.Now() for _, info := range files { p := path.Join(root, info.path) if info.filetype == Dir { if err := os.MkdirAll(p, info.permissions); err != nil { t.Fatal(err) } } else if info.filetype == Regular { if err := ioutil.WriteFile(p, []byte(info.contents), info.permissions); err != nil { t.Fatal(err) } } else if info.filetype == Symlink { if err := os.Symlink(info.contents, p); err != nil { t.Fatal(err) } } if info.filetype != Symlink { // Set a consistent ctime, atime for all files and dirs if err := os.Chtimes(p, now, now); err != nil { t.Fatal(err) } } } } func TestChangeString(t *testing.T) { modifiyChange := Change{"change", ChangeModify} toString := modifiyChange.String() if toString != "C change" { t.Fatalf("String() of a change with ChangeModifiy Kind should have been %s but was %s", "C change", toString) } addChange := Change{"change", ChangeAdd} toString = addChange.String() if toString != "A change" { t.Fatalf("String() of a change with ChangeAdd Kind should have been %s but was %s", "A change", toString) } deleteChange := Change{"change", ChangeDelete} toString = deleteChange.String() if toString != "D change" { t.Fatalf("String() of a change with ChangeDelete Kind should have been %s but was %s", "D change", toString) } } func TestChangesWithNoChanges(t *testing.T) { rwLayer, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(rwLayer) layer, err := ioutil.TempDir("", "docker-changes-test-layer") if err != nil { t.Fatal(err) } defer os.RemoveAll(layer) createSampleDir(t, layer) changes, err := Changes([]string{layer}, rwLayer) if err != nil { t.Fatal(err) } if len(changes) != 0 { t.Fatalf("Changes with no difference should have detect no changes, but detected %d", len(changes)) } } func TestChangesWithChanges(t *testing.T) { // Mock the readonly layer layer, err := ioutil.TempDir("", "docker-changes-test-layer") if err != nil { t.Fatal(err) } defer os.RemoveAll(layer) createSampleDir(t, layer) os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0740) // Mock the RW layer rwLayer, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(rwLayer) // Create a folder in RW layer dir1 := path.Join(rwLayer, "dir1") os.MkdirAll(dir1, 0740) deletedFile := path.Join(dir1, ".wh.file1-2") ioutil.WriteFile(deletedFile, []byte{}, 0600) modifiedFile := path.Join(dir1, "file1-1") ioutil.WriteFile(modifiedFile, []byte{0x00}, 01444) // Let's add a subfolder for a newFile subfolder := path.Join(dir1, "subfolder") os.MkdirAll(subfolder, 0740) newFile := path.Join(subfolder, "newFile") ioutil.WriteFile(newFile, []byte{}, 0740) changes, err := Changes([]string{layer}, rwLayer) if err != nil { t.Fatal(err) } expectedChanges := []Change{ {"/dir1", ChangeModify}, {"/dir1/file1-1", ChangeModify}, {"/dir1/file1-2", ChangeDelete}, {"/dir1/subfolder", ChangeModify}, {"/dir1/subfolder/newFile", ChangeAdd}, } checkChanges(expectedChanges, changes, t) } // See https://github.com/docker/docker/pull/13590 func TestChangesWithChangesGH13590(t *testing.T) { baseLayer, err := ioutil.TempDir("", "docker-changes-test.") defer os.RemoveAll(baseLayer) dir3 := path.Join(baseLayer, "dir1/dir2/dir3") os.MkdirAll(dir3, 07400) file := path.Join(dir3, "file.txt") ioutil.WriteFile(file, []byte("hello"), 0666) layer, err := ioutil.TempDir("", "docker-changes-test2.") defer os.RemoveAll(layer) // Test creating a new file if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { t.Fatalf("Cmd failed: %q", err) } os.Remove(path.Join(layer, "dir1/dir2/dir3/file.txt")) file = path.Join(layer, "dir1/dir2/dir3/file1.txt") ioutil.WriteFile(file, []byte("bye"), 0666) changes, err := Changes([]string{baseLayer}, layer) if err != nil { t.Fatal(err) } expectedChanges := []Change{ {"/dir1/dir2/dir3", ChangeModify}, {"/dir1/dir2/dir3/file1.txt", ChangeAdd}, } checkChanges(expectedChanges, changes, t) // Now test changing a file layer, err = ioutil.TempDir("", "docker-changes-test3.") defer os.RemoveAll(layer) if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { t.Fatalf("Cmd failed: %q", err) } file = path.Join(layer, "dir1/dir2/dir3/file.txt") ioutil.WriteFile(file, []byte("bye"), 0666) changes, err = Changes([]string{baseLayer}, layer) if err != nil { t.Fatal(err) } expectedChanges = []Change{ {"/dir1/dir2/dir3/file.txt", ChangeModify}, } checkChanges(expectedChanges, changes, t) } // Create an directory, copy it, make sure we report no changes between the two func TestChangesDirsEmpty(t *testing.T) { src, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(src) createSampleDir(t, src) dst := src + "-copy" if err := copyDir(src, dst); err != nil { t.Fatal(err) } defer os.RemoveAll(dst) changes, err := ChangesDirs(dst, src) if err != nil { t.Fatal(err) } if len(changes) != 0 { t.Fatalf("Reported changes for identical dirs: %v", changes) } os.RemoveAll(src) os.RemoveAll(dst) } func mutateSampleDir(t *testing.T, root string) { // Remove a regular file if err := os.RemoveAll(path.Join(root, "file1")); err != nil { t.Fatal(err) } // Remove a directory if err := os.RemoveAll(path.Join(root, "dir1")); err != nil { t.Fatal(err) } // Remove a symlink if err := os.RemoveAll(path.Join(root, "symlink1")); err != nil { t.Fatal(err) } // Rewrite a file if err := ioutil.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777); err != nil { t.Fatal(err) } // Replace a file if err := os.RemoveAll(path.Join(root, "file3")); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404); err != nil { t.Fatal(err) } // Touch file if err := os.Chtimes(path.Join(root, "file4"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { t.Fatal(err) } // Replace file with dir if err := os.RemoveAll(path.Join(root, "file5")); err != nil { t.Fatal(err) } if err := os.MkdirAll(path.Join(root, "file5"), 0666); err != nil { t.Fatal(err) } // Create new file if err := ioutil.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0777); err != nil { t.Fatal(err) } // Create new dir if err := os.MkdirAll(path.Join(root, "dirnew"), 0766); err != nil { t.Fatal(err) } // Create a new symlink if err := os.Symlink("targetnew", path.Join(root, "symlinknew")); err != nil { t.Fatal(err) } // Change a symlink if err := os.RemoveAll(path.Join(root, "symlink2")); err != nil { t.Fatal(err) } if err := os.Symlink("target2change", path.Join(root, "symlink2")); err != nil { t.Fatal(err) } // Replace dir with file if err := os.RemoveAll(path.Join(root, "dir2")); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0777); err != nil { t.Fatal(err) } // Touch dir if err := os.Chtimes(path.Join(root, "dir3"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { t.Fatal(err) } } func TestChangesDirsMutated(t *testing.T) { src, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } createSampleDir(t, src) dst := src + "-copy" if err := copyDir(src, dst); err != nil { t.Fatal(err) } defer os.RemoveAll(src) defer os.RemoveAll(dst) mutateSampleDir(t, dst) changes, err := ChangesDirs(dst, src) if err != nil { t.Fatal(err) } sort.Sort(changesByPath(changes)) expectedChanges := []Change{ {"/dir1", ChangeDelete}, {"/dir2", ChangeModify}, {"/dirnew", ChangeAdd}, {"/file1", ChangeDelete}, {"/file2", ChangeModify}, {"/file3", ChangeModify}, {"/file4", ChangeModify}, {"/file5", ChangeModify}, {"/filenew", ChangeAdd}, {"/symlink1", ChangeDelete}, {"/symlink2", ChangeModify}, {"/symlinknew", ChangeAdd}, } for i := 0; i < max(len(changes), len(expectedChanges)); i++ { if i >= len(expectedChanges) { t.Fatalf("unexpected change %s\n", changes[i].String()) } if i >= len(changes) { t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) } if changes[i].Path == expectedChanges[i].Path { if changes[i] != expectedChanges[i] { t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) } } else if changes[i].Path < expectedChanges[i].Path { t.Fatalf("unexpected change %s\n", changes[i].String()) } else { t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) } } } func TestApplyLayer(t *testing.T) { src, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } createSampleDir(t, src) defer os.RemoveAll(src) dst := src + "-copy" if err := copyDir(src, dst); err != nil { t.Fatal(err) } mutateSampleDir(t, dst) defer os.RemoveAll(dst) changes, err := ChangesDirs(dst, src) if err != nil { t.Fatal(err) } layer, err := ExportChanges(dst, changes) if err != nil { t.Fatal(err) } layerCopy, err := NewTempArchive(layer, "") if err != nil { t.Fatal(err) } if _, err := ApplyLayer(src, layerCopy); err != nil { t.Fatal(err) } changes2, err := ChangesDirs(src, dst) if err != nil { t.Fatal(err) } if len(changes2) != 0 { t.Fatalf("Unexpected differences after reapplying mutation: %v", changes2) } } func TestChangesSizeWithNoChanges(t *testing.T) { size := ChangesSize("/tmp", nil) if size != 0 { t.Fatalf("ChangesSizes with no changes should be 0, was %d", size) } } func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) { changes := []Change{ {Path: "deletedPath", Kind: ChangeDelete}, } size := ChangesSize("/tmp", changes) if size != 0 { t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size) } } func TestChangesSize(t *testing.T) { parentPath, err := ioutil.TempDir("", "docker-changes-test") defer os.RemoveAll(parentPath) addition := path.Join(parentPath, "addition") if err := ioutil.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744); err != nil { t.Fatal(err) } modification := path.Join(parentPath, "modification") if err = ioutil.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0744); err != nil { t.Fatal(err) } changes := []Change{ {Path: "addition", Kind: ChangeAdd}, {Path: "modification", Kind: ChangeModify}, } size := ChangesSize(parentPath, changes) if size != 6 { t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size) } } func checkChanges(expectedChanges, changes []Change, t *testing.T) { sort.Sort(changesByPath(expectedChanges)) sort.Sort(changesByPath(changes)) for i := 0; i < max(len(changes), len(expectedChanges)); i++ { if i >= len(expectedChanges) { t.Fatalf("unexpected change %s\n", changes[i].String()) } if i >= len(changes) { t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) } if changes[i].Path == expectedChanges[i].Path { if changes[i] != expectedChanges[i] { t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) } } else if changes[i].Path < expectedChanges[i].Path { t.Fatalf("unexpected change %s\n", changes[i].String()) } else { t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes_unix.go ================================================ // +build !windows package archive import ( "syscall" "github.com/docker/docker/pkg/system" ) func statDifferent(oldStat *system.Stat_t, newStat *system.Stat_t) bool { // Don't look at size for dirs, its not a good measure of change if oldStat.Mode() != newStat.Mode() || oldStat.Uid() != newStat.Uid() || oldStat.Gid() != newStat.Gid() || oldStat.Rdev() != newStat.Rdev() || // Don't look at size for dirs, its not a good measure of change (oldStat.Mode()&syscall.S_IFDIR != syscall.S_IFDIR && (!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) { return true } return false } func (info *FileInfo) isDir() bool { return info.parent == nil || info.stat.Mode()&syscall.S_IFDIR != 0 } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/changes_windows.go ================================================ package archive import ( "github.com/docker/docker/pkg/system" ) func statDifferent(oldStat *system.Stat_t, newStat *system.Stat_t) bool { // Don't look at size for dirs, its not a good measure of change if oldStat.ModTime() != newStat.ModTime() || oldStat.Mode() != newStat.Mode() || oldStat.Size() != newStat.Size() && !oldStat.IsDir() { return true } return false } func (info *FileInfo) isDir() bool { return info.parent == nil || info.stat.IsDir() } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/copy.go ================================================ package archive import ( "archive/tar" "errors" "io" "io/ioutil" "os" "path" "path/filepath" "strings" log "github.com/Sirupsen/logrus" ) // Errors used or returned by this file. var ( ErrNotDirectory = errors.New("not a directory") ErrDirNotExists = errors.New("no such directory") ErrCannotCopyDir = errors.New("cannot copy directory") ErrInvalidCopySource = errors.New("invalid copy source content") ) // PreserveTrailingDotOrSeparator returns the given cleaned path (after // processing using any utility functions from the path or filepath stdlib // packages) and appends a trailing `/.` or `/` if its corresponding original // path (from before being processed by utility functions from the path or // filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned // path already ends in a `.` path segment, then another is not added. If the // clean path already ends in a path separator, then another is not added. func PreserveTrailingDotOrSeparator(cleanedPath, originalPath string) string { if !SpecifiesCurrentDir(cleanedPath) && SpecifiesCurrentDir(originalPath) { if !HasTrailingPathSeparator(cleanedPath) { // Add a separator if it doesn't already end with one (a cleaned // path would only end in a separator if it is the root). cleanedPath += string(filepath.Separator) } cleanedPath += "." } if !HasTrailingPathSeparator(cleanedPath) && HasTrailingPathSeparator(originalPath) { cleanedPath += string(filepath.Separator) } return cleanedPath } // AssertsDirectory returns whether the given path is // asserted to be a directory, i.e., the path ends with // a trailing '/' or `/.`, assuming a path separator of `/`. func AssertsDirectory(path string) bool { return HasTrailingPathSeparator(path) || SpecifiesCurrentDir(path) } // HasTrailingPathSeparator returns whether the given // path ends with the system's path separator character. func HasTrailingPathSeparator(path string) bool { return len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) } // SpecifiesCurrentDir returns whether the given path specifies // a "current directory", i.e., the last path segment is `.`. func SpecifiesCurrentDir(path string) bool { return filepath.Base(path) == "." } // SplitPathDirEntry splits the given path between its // parent directory and its basename in that directory. func SplitPathDirEntry(localizedPath string) (dir, base string) { normalizedPath := filepath.ToSlash(localizedPath) vol := filepath.VolumeName(normalizedPath) normalizedPath = normalizedPath[len(vol):] if normalizedPath == "/" { // Specifies the root path. return filepath.FromSlash(vol + normalizedPath), "." } trimmedPath := vol + strings.TrimRight(normalizedPath, "/") dir = filepath.FromSlash(path.Dir(trimmedPath)) base = filepath.FromSlash(path.Base(trimmedPath)) return dir, base } // TarResource archives the resource at the given sourcePath into a Tar // archive. A non-nil error is returned if sourcePath does not exist or is // asserted to be a directory but exists as another type of file. // // This function acts as a convenient wrapper around TarWithOptions, which // requires a directory as the source path. TarResource accepts either a // directory or a file path and correctly sets the Tar options. func TarResource(sourcePath string) (content Archive, err error) { if _, err = os.Lstat(sourcePath); err != nil { // Catches the case where the source does not exist or is not a // directory if asserted to be a directory, as this also causes an // error. return } if len(sourcePath) > 1 && HasTrailingPathSeparator(sourcePath) { // In the case where the source path is a symbolic link AND it ends // with a path separator, we will want to evaluate the symbolic link. trimmedPath := sourcePath[:len(sourcePath)-1] stat, err := os.Lstat(trimmedPath) if err != nil { return nil, err } if stat.Mode()&os.ModeSymlink != 0 { if sourcePath, err = filepath.EvalSymlinks(trimmedPath); err != nil { return nil, err } } } // Separate the source path between it's directory and // the entry in that directory which we are archiving. sourceDir, sourceBase := SplitPathDirEntry(sourcePath) filter := []string{sourceBase} log.Debugf("copying %q from %q", sourceBase, sourceDir) return TarWithOptions(sourceDir, &TarOptions{ Compression: Uncompressed, IncludeFiles: filter, IncludeSourceDir: true, }) } // CopyInfo holds basic info about the source // or destination path of a copy operation. type CopyInfo struct { Path string Exists bool IsDir bool } // CopyInfoStatPath stats the given path to create a CopyInfo // struct representing that resource. If mustExist is true, then // it is an error if there is no file or directory at the given path. func CopyInfoStatPath(path string, mustExist bool) (CopyInfo, error) { pathInfo := CopyInfo{Path: path} fileInfo, err := os.Lstat(path) if err == nil { pathInfo.Exists, pathInfo.IsDir = true, fileInfo.IsDir() } else if os.IsNotExist(err) && !mustExist { err = nil } return pathInfo, err } // PrepareArchiveCopy prepares the given srcContent archive, which should // contain the archived resource described by srcInfo, to the destination // described by dstInfo. Returns the possibly modified content archive along // with the path to the destination directory which it should be extracted to. func PrepareArchiveCopy(srcContent ArchiveReader, srcInfo, dstInfo CopyInfo) (dstDir string, content Archive, err error) { // Separate the destination path between its directory and base // components in case the source archive contents need to be rebased. dstDir, dstBase := SplitPathDirEntry(dstInfo.Path) _, srcBase := SplitPathDirEntry(srcInfo.Path) switch { case dstInfo.Exists && dstInfo.IsDir: // The destination exists as a directory. No alteration // to srcContent is needed as its contents can be // simply extracted to the destination directory. return dstInfo.Path, ioutil.NopCloser(srcContent), nil case dstInfo.Exists && srcInfo.IsDir: // The destination exists as some type of file and the source // content is a directory. This is an error condition since // you cannot copy a directory to an existing file location. return "", nil, ErrCannotCopyDir case dstInfo.Exists: // The destination exists as some type of file and the source content // is also a file. The source content entry will have to be renamed to // have a basename which matches the destination path's basename. return dstDir, rebaseArchiveEntries(srcContent, srcBase, dstBase), nil case srcInfo.IsDir: // The destination does not exist and the source content is an archive // of a directory. The archive should be extracted to the parent of // the destination path instead, and when it is, the directory that is // created as a result should take the name of the destination path. // The source content entries will have to be renamed to have a // basename which matches the destination path's basename. return dstDir, rebaseArchiveEntries(srcContent, srcBase, dstBase), nil case AssertsDirectory(dstInfo.Path): // The destination does not exist and is asserted to be created as a // directory, but the source content is not a directory. This is an // error condition since you cannot create a directory from a file // source. return "", nil, ErrDirNotExists default: // The last remaining case is when the destination does not exist, is // not asserted to be a directory, and the source content is not an // archive of a directory. It this case, the destination file will need // to be created when the archive is extracted and the source content // entry will have to be renamed to have a basename which matches the // destination path's basename. return dstDir, rebaseArchiveEntries(srcContent, srcBase, dstBase), nil } } // rebaseArchiveEntries rewrites the given srcContent archive replacing // an occurance of oldBase with newBase at the beginning of entry names. func rebaseArchiveEntries(srcContent ArchiveReader, oldBase, newBase string) Archive { rebased, w := io.Pipe() go func() { srcTar := tar.NewReader(srcContent) rebasedTar := tar.NewWriter(w) for { hdr, err := srcTar.Next() if err == io.EOF { // Signals end of archive. rebasedTar.Close() w.Close() return } if err != nil { w.CloseWithError(err) return } hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) if err = rebasedTar.WriteHeader(hdr); err != nil { w.CloseWithError(err) return } if _, err = io.Copy(rebasedTar, srcTar); err != nil { w.CloseWithError(err) return } } }() return rebased } // CopyResource performs an archive copy from the given source path to the // given destination path. The source path MUST exist and the destination // path's parent directory must exist. func CopyResource(srcPath, dstPath string) error { var ( srcInfo CopyInfo err error ) // Clean the source and destination paths. srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath) dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath) if srcInfo, err = CopyInfoStatPath(srcPath, true); err != nil { return err } content, err := TarResource(srcPath) if err != nil { return err } defer content.Close() return CopyTo(content, srcInfo, dstPath) } // CopyTo handles extracting the given content whose // entries should be sourced from srcInfo to dstPath. func CopyTo(content ArchiveReader, srcInfo CopyInfo, dstPath string) error { dstInfo, err := CopyInfoStatPath(dstPath, false) if err != nil { return err } if !dstInfo.Exists { // Ensure destination parent dir exists. dstParent, _ := SplitPathDirEntry(dstPath) dstStat, err := os.Lstat(dstParent) if err != nil { return err } if !dstStat.IsDir() { return ErrNotDirectory } } dstDir, copyArchive, err := PrepareArchiveCopy(content, srcInfo, dstInfo) if err != nil { return err } defer copyArchive.Close() options := &TarOptions{ NoLchown: true, NoOverwriteDirNonDir: true, } return Untar(copyArchive, dstDir, options) } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/copy_test.go ================================================ package archive import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "testing" ) func removeAllPaths(paths ...string) { for _, path := range paths { os.RemoveAll(path) } } func getTestTempDirs(t *testing.T) (tmpDirA, tmpDirB string) { var err error if tmpDirA, err = ioutil.TempDir("", "archive-copy-test"); err != nil { t.Fatal(err) } if tmpDirB, err = ioutil.TempDir("", "archive-copy-test"); err != nil { t.Fatal(err) } return } func isNotDir(err error) bool { return strings.Contains(err.Error(), "not a directory") } func joinTrailingSep(pathElements ...string) string { joined := filepath.Join(pathElements...) return fmt.Sprintf("%s%c", joined, filepath.Separator) } func fileContentsEqual(t *testing.T, filenameA, filenameB string) (err error) { t.Logf("checking for equal file contents: %q and %q\n", filenameA, filenameB) fileA, err := os.Open(filenameA) if err != nil { return } defer fileA.Close() fileB, err := os.Open(filenameB) if err != nil { return } defer fileB.Close() hasher := sha256.New() if _, err = io.Copy(hasher, fileA); err != nil { return } hashA := hasher.Sum(nil) hasher.Reset() if _, err = io.Copy(hasher, fileB); err != nil { return } hashB := hasher.Sum(nil) if !bytes.Equal(hashA, hashB) { err = fmt.Errorf("file content hashes not equal - expected %s, got %s", hex.EncodeToString(hashA), hex.EncodeToString(hashB)) } return } func dirContentsEqual(t *testing.T, newDir, oldDir string) (err error) { t.Logf("checking for equal directory contents: %q and %q\n", newDir, oldDir) var changes []Change if changes, err = ChangesDirs(newDir, oldDir); err != nil { return } if len(changes) != 0 { err = fmt.Errorf("expected no changes between directories, but got: %v", changes) } return } func logDirContents(t *testing.T, dirPath string) { logWalkedPaths := filepath.WalkFunc(func(path string, info os.FileInfo, err error) error { if err != nil { t.Errorf("stat error for path %q: %s", path, err) return nil } if info.IsDir() { path = joinTrailingSep(path) } t.Logf("\t%s", path) return nil }) t.Logf("logging directory contents: %q", dirPath) if err := filepath.Walk(dirPath, logWalkedPaths); err != nil { t.Fatal(err) } } func testCopyHelper(t *testing.T, srcPath, dstPath string) (err error) { t.Logf("copying from %q to %q", srcPath, dstPath) return CopyResource(srcPath, dstPath) } // Basic assumptions about SRC and DST: // 1. SRC must exist. // 2. If SRC ends with a trailing separator, it must be a directory. // 3. DST parent directory must exist. // 4. If DST exists as a file, it must not end with a trailing separator. // First get these easy error cases out of the way. // Test for error when SRC does not exist. func TestCopyErrSrcNotExists(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) content, err := TarResource(filepath.Join(tmpDirA, "file1")) if err == nil { content.Close() t.Fatal("expected IsNotExist error, but got nil instead") } if !os.IsNotExist(err) { t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when SRC ends in a trailing // path separator but it exists as a file. func TestCopyErrSrcNotDir(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) content, err := TarResource(joinTrailingSep(tmpDirA, "file1")) if err == nil { content.Close() t.Fatal("expected IsNotDir error, but got nil instead") } if !isNotDir(err) { t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Test for error when SRC is a valid file or directory, // but the DST parent directory does not exist. func TestCopyErrDstParentNotExists(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} // Try with a file source. content, err := TarResource(srcInfo.Path) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() // Copy to a file whose parent does not exist. if err = CopyTo(content, srcInfo, filepath.Join(tmpDirB, "fakeParentDir", "file1")); err == nil { t.Fatal("expected IsNotExist error, but got nil instead") } if !os.IsNotExist(err) { t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } // Try with a directory source. srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} content, err = TarResource(srcInfo.Path) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() // Copy to a directory whose parent does not exist. if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "fakeParentDir", "fakeDstDir")); err == nil { t.Fatal("expected IsNotExist error, but got nil instead") } if !os.IsNotExist(err) { t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when DST ends in a trailing // path separator but exists as a file. func TestCopyErrDstNotDir(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) // Try with a file source. srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} content, err := TarResource(srcInfo.Path) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { t.Fatal("expected IsNotDir error, but got nil instead") } if !isNotDir(err) { t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } // Try with a directory source. srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} content, err = TarResource(srcInfo.Path) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { t.Fatal("expected IsNotDir error, but got nil instead") } if !isNotDir(err) { t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Possibilities are reduced to the remaining 10 cases: // // case | srcIsDir | onlyDirContents | dstExists | dstIsDir | dstTrSep | action // =================================================================================================== // A | no | - | no | - | no | create file // B | no | - | no | - | yes | error // C | no | - | yes | no | - | overwrite file // D | no | - | yes | yes | - | create file in dst dir // E | yes | no | no | - | - | create dir, copy contents // F | yes | no | yes | no | - | error // G | yes | no | yes | yes | - | copy dir and contents // H | yes | yes | no | - | - | create dir, copy contents // I | yes | yes | yes | no | - | error // J | yes | yes | yes | yes | - | copy dir contents // // A. SRC specifies a file and DST (no trailing path separator) doesn't // exist. This should create a file with the name DST and copy the // contents of the source file into it. func TestCopyCaseA(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcPath := filepath.Join(tmpDirA, "file1") dstPath := filepath.Join(tmpDirB, "itWorks.txt") var err error if err = testCopyHelper(t, srcPath, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } } // B. SRC specifies a file and DST (with trailing path separator) doesn't // exist. This should cause an error because the copy operation cannot // create a directory when copying a single file. func TestCopyCaseB(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcPath := filepath.Join(tmpDirA, "file1") dstDir := joinTrailingSep(tmpDirB, "testDir") var err error if err = testCopyHelper(t, srcPath, dstDir); err == nil { t.Fatal("expected ErrDirNotExists error, but got nil instead") } if err != ErrDirNotExists { t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) } } // C. SRC specifies a file and DST exists as a file. This should overwrite // the file at DST with the contents of the source file. func TestCopyCaseC(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcPath := filepath.Join(tmpDirA, "file1") dstPath := filepath.Join(tmpDirB, "file2") var err error // Ensure they start out different. if err = fileContentsEqual(t, srcPath, dstPath); err == nil { t.Fatal("expected different file contents") } if err = testCopyHelper(t, srcPath, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } } // D. SRC specifies a file and DST exists as a directory. This should place // a copy of the source file inside it using the basename from SRC. Ensure // this works whether DST has a trailing path separator or not. func TestCopyCaseD(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcPath := filepath.Join(tmpDirA, "file1") dstDir := filepath.Join(tmpDirB, "dir1") dstPath := filepath.Join(dstDir, "file1") var err error // Ensure that dstPath doesn't exist. if _, err = os.Stat(dstPath); !os.IsNotExist(err) { t.Fatalf("did not expect dstPath %q to exist", dstPath) } if err = testCopyHelper(t, srcPath, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir1") if err = testCopyHelper(t, srcPath, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } } // E. SRC specifies a directory and DST does not exist. This should create a // directory at DST and copy the contents of the SRC directory into the DST // directory. Ensure this works whether DST has a trailing path separator or // not. func TestCopyCaseE(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcDir := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "testDir") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "testDir") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Fatal(err) } } // F. SRC specifies a directory and DST exists as a file. This should cause an // error as it is not possible to overwrite a file with a directory. func TestCopyCaseF(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := filepath.Join(tmpDirA, "dir1") dstFile := filepath.Join(tmpDirB, "file1") var err error if err = testCopyHelper(t, srcDir, dstFile); err == nil { t.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if err != ErrCannotCopyDir { t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // G. SRC specifies a directory and DST exists as a directory. This should copy // the SRC directory and all its contents to the DST directory. Ensure this // works whether DST has a trailing path separator or not. func TestCopyCaseG(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "dir2") resultDir := filepath.Join(dstDir, "dir1") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, resultDir, srcDir); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir2") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, resultDir, srcDir); err != nil { t.Fatal(err) } } // H. SRC specifies a directory's contents only and DST does not exist. This // should create a directory at DST and copy the contents of the SRC // directory (but not the directory itself) into the DST directory. Ensure // this works whether DST has a trailing path separator or not. func TestCopyCaseH(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcDir := joinTrailingSep(tmpDirA, "dir1") + "." dstDir := filepath.Join(tmpDirB, "testDir") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "testDir") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } } // I. SRC specifies a direcotry's contents only and DST exists as a file. This // should cause an error as it is not possible to overwrite a file with a // directory. func TestCopyCaseI(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := joinTrailingSep(tmpDirA, "dir1") + "." dstFile := filepath.Join(tmpDirB, "file1") var err error if err = testCopyHelper(t, srcDir, dstFile); err == nil { t.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if err != ErrCannotCopyDir { t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // J. SRC specifies a directory's contents only and DST exists as a directory. // This should copy the contents of the SRC directory (but not the directory // itself) into the DST directory. Ensure this works whether DST has a // trailing path separator or not. func TestCopyCaseJ(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := joinTrailingSep(tmpDirA, "dir1") + "." dstDir := filepath.Join(tmpDirB, "dir5") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir5") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/diff.go ================================================ package archive import ( "archive/tar" "fmt" "io" "io/ioutil" "os" "path/filepath" "runtime" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/system" ) func UnpackLayer(dest string, layer ArchiveReader) (size int64, err error) { tr := tar.NewReader(layer) trBuf := pools.BufioReader32KPool.Get(tr) defer pools.BufioReader32KPool.Put(trBuf) var dirs []*tar.Header aufsTempdir := "" aufsHardlinks := make(map[string]*tar.Header) // Iterate through the files in the archive. for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return 0, err } size += hdr.Size // Normalize name, for safety and for a simple is-root check hdr.Name = filepath.Clean(hdr.Name) // Windows does not support filenames with colons in them. Ignore // these files. This is not a problem though (although it might // appear that it is). Let's suppose a client is running docker pull. // The daemon it points to is Windows. Would it make sense for the // client to be doing a docker pull Ubuntu for example (which has files // with colons in the name under /usr/share/man/man3)? No, absolutely // not as it would really only make sense that they were pulling a // Windows image. However, for development, it is necessary to be able // to pull Linux images which are in the repository. // // TODO Windows. Once the registry is aware of what images are Windows- // specific or Linux-specific, this warning should be changed to an error // to cater for the situation where someone does manage to upload a Linux // image but have it tagged as Windows inadvertantly. if runtime.GOOS == "windows" { if strings.Contains(hdr.Name, ":") { logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) continue } } // Note as these operations are platform specific, so must the slash be. if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { // Not the root directory, ensure that the parent directory exists. // This happened in some tests where an image had a tarfile without any // parent directories. parent := filepath.Dir(hdr.Name) parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { err = system.MkdirAll(parentPath, 0600) if err != nil { return 0, err } } } // Skip AUFS metadata dirs if strings.HasPrefix(hdr.Name, ".wh..wh.") { // Regular files inside /.wh..wh.plnk can be used as hardlink targets // We don't want this directory, but we need the files in them so that // such hardlinks can be resolved. if strings.HasPrefix(hdr.Name, ".wh..wh.plnk") && hdr.Typeflag == tar.TypeReg { basename := filepath.Base(hdr.Name) aufsHardlinks[basename] = hdr if aufsTempdir == "" { if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil { return 0, err } defer os.RemoveAll(aufsTempdir) } if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil); err != nil { return 0, err } } continue } path := filepath.Join(dest, hdr.Name) rel, err := filepath.Rel(dest, path) if err != nil { return 0, err } // Note as these operations are platform specific, so must the slash be. if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) } base := filepath.Base(path) if strings.HasPrefix(base, ".wh.") { originalBase := base[len(".wh."):] originalPath := filepath.Join(filepath.Dir(path), originalBase) if err := os.RemoveAll(originalPath); err != nil { return 0, err } } else { // If path exits we almost always just want to remove and replace it. // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). if fi, err := os.Lstat(path); err == nil { if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { if err := os.RemoveAll(path); err != nil { return 0, err } } } trBuf.Reset(tr) srcData := io.Reader(trBuf) srcHdr := hdr // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so // we manually retarget these into the temporary files we extracted them into if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), ".wh..wh.plnk") { linkBasename := filepath.Base(hdr.Linkname) srcHdr = aufsHardlinks[linkBasename] if srcHdr == nil { return 0, fmt.Errorf("Invalid aufs hardlink") } tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename)) if err != nil { return 0, err } defer tmpFile.Close() srcData = tmpFile } if err := createTarFile(path, dest, srcHdr, srcData, true, nil); err != nil { return 0, err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { dirs = append(dirs, hdr) } } } for _, hdr := range dirs { path := filepath.Join(dest, hdr.Name) ts := []syscall.Timespec{timeToTimespec(hdr.AccessTime), timeToTimespec(hdr.ModTime)} if err := syscall.UtimesNano(path, ts); err != nil { return 0, err } } return size, nil } // ApplyLayer parses a diff in the standard layer format from `layer`, and // applies it to the directory `dest`. Returns the size in bytes of the // contents of the layer. func ApplyLayer(dest string, layer ArchiveReader) (int64, error) { dest = filepath.Clean(dest) // We need to be able to set any perms oldmask, err := system.Umask(0) if err != nil { return 0, err } defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform layer, err = DecompressStream(layer) if err != nil { return 0, err } return UnpackLayer(dest, layer) } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/diff_test.go ================================================ package archive import ( "archive/tar" "testing" ) func TestApplyLayerInvalidFilenames(t *testing.T) { for i, headers := range [][]*tar.Header{ { { Name: "../victim/dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, { { // Note the leading slash Name: "/../victim/slash-dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidFilenames", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestApplyLayerInvalidHardlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeLink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeLink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (hardlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try reading victim/hello (hardlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try removing victim directory (hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidHardlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestApplyLayerInvalidSymlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeSymlink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeSymlink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (symlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try reading victim/hello (symlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try removing victim directory (symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidSymlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/example_changes.go ================================================ // +build ignore // Simple tool to create an archive stream from an old and new directory // // By default it will stream the comparison of two temporary directories with junk files package main import ( "flag" "fmt" "io" "io/ioutil" "os" "path" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/archive" ) var ( flDebug = flag.Bool("D", false, "debugging output") flNewDir = flag.String("newdir", "", "") flOldDir = flag.String("olddir", "", "") log = logrus.New() ) func main() { flag.Usage = func() { fmt.Println("Produce a tar from comparing two directory paths. By default a demo tar is created of around 200 files (including hardlinks)") fmt.Printf("%s [OPTIONS]\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() log.Out = os.Stderr if (len(os.Getenv("DEBUG")) > 0) || *flDebug { logrus.SetLevel(logrus.DebugLevel) } var newDir, oldDir string if len(*flNewDir) == 0 { var err error newDir, err = ioutil.TempDir("", "docker-test-newDir") if err != nil { log.Fatal(err) } defer os.RemoveAll(newDir) if _, err := prepareUntarSourceDirectory(100, newDir, true); err != nil { log.Fatal(err) } } else { newDir = *flNewDir } if len(*flOldDir) == 0 { oldDir, err := ioutil.TempDir("", "docker-test-oldDir") if err != nil { log.Fatal(err) } defer os.RemoveAll(oldDir) } else { oldDir = *flOldDir } changes, err := archive.ChangesDirs(newDir, oldDir) if err != nil { log.Fatal(err) } a, err := archive.ExportChanges(newDir, changes) if err != nil { log.Fatal(err) } defer a.Close() i, err := io.Copy(os.Stdout, a) if err != nil && err != io.EOF { log.Fatal(err) } fmt.Fprintf(os.Stderr, "wrote archive of %d bytes", i) } func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { return 0, err } if makeLinks { if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { return 0, err } } } totalSize := numberOfFiles * len(fileData) return totalSize, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/time_linux.go ================================================ package archive import ( "syscall" "time" ) func timeToTimespec(time time.Time) (ts syscall.Timespec) { if time.IsZero() { // Return UTIME_OMIT special value ts.Sec = 0 ts.Nsec = ((1 << 30) - 2) return } return syscall.NsecToTimespec(time.UnixNano()) } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/time_unsupported.go ================================================ // +build !linux package archive import ( "syscall" "time" ) func timeToTimespec(time time.Time) (ts syscall.Timespec) { nsec := int64(0) if !time.IsZero() { nsec = time.UnixNano() } return syscall.NsecToTimespec(nsec) } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/utils_test.go ================================================ package archive import ( "archive/tar" "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "time" ) var testUntarFns = map[string]func(string, io.Reader) error{ "untar": func(dest string, r io.Reader) error { return Untar(r, dest, nil) }, "applylayer": func(dest string, r io.Reader) error { _, err := ApplyLayer(dest, ArchiveReader(r)) return err }, } // testBreakout is a helper function that, within the provided `tmpdir` directory, // creates a `victim` folder with a generated `hello` file in it. // `untar` extracts to a directory named `dest`, the tar file created from `headers`. // // Here are the tested scenarios: // - removed `victim` folder (write) // - removed files from `victim` folder (write) // - new files in `victim` folder (write) // - modified files in `victim` folder (write) // - file in `dest` with same content as `victim/hello` (read) // // When using testBreakout make sure you cover one of the scenarios listed above. func testBreakout(untarFn string, tmpdir string, headers []*tar.Header) error { tmpdir, err := ioutil.TempDir("", tmpdir) if err != nil { return err } defer os.RemoveAll(tmpdir) dest := filepath.Join(tmpdir, "dest") if err := os.Mkdir(dest, 0755); err != nil { return err } victim := filepath.Join(tmpdir, "victim") if err := os.Mkdir(victim, 0755); err != nil { return err } hello := filepath.Join(victim, "hello") helloData, err := time.Now().MarshalText() if err != nil { return err } if err := ioutil.WriteFile(hello, helloData, 0644); err != nil { return err } helloStat, err := os.Stat(hello) if err != nil { return err } reader, writer := io.Pipe() go func() { t := tar.NewWriter(writer) for _, hdr := range headers { t.WriteHeader(hdr) } t.Close() }() untar := testUntarFns[untarFn] if untar == nil { return fmt.Errorf("could not find untar function %q in testUntarFns", untarFn) } if err := untar(dest, reader); err != nil { if _, ok := err.(breakoutError); !ok { // If untar returns an error unrelated to an archive breakout, // then consider this an unexpected error and abort. return err } // Here, untar detected the breakout. // Let's move on verifying that indeed there was no breakout. fmt.Printf("breakoutError: %v\n", err) } // Check victim folder f, err := os.Open(victim) if err != nil { // codepath taken if victim folder was removed return fmt.Errorf("archive breakout: error reading %q: %v", victim, err) } defer f.Close() // Check contents of victim folder // // We are only interested in getting 2 files from the victim folder, because if all is well // we expect only one result, the `hello` file. If there is a second result, it cannot // hold the same name `hello` and we assume that a new file got created in the victim folder. // That is enough to detect an archive breakout. names, err := f.Readdirnames(2) if err != nil { // codepath taken if victim is not a folder return fmt.Errorf("archive breakout: error reading directory content of %q: %v", victim, err) } for _, name := range names { if name != "hello" { // codepath taken if new file was created in victim folder return fmt.Errorf("archive breakout: new file %q", name) } } // Check victim/hello f, err = os.Open(hello) if err != nil { // codepath taken if read permissions were removed return fmt.Errorf("archive breakout: could not lstat %q: %v", hello, err) } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return err } fi, err := f.Stat() if err != nil { return err } if helloStat.IsDir() != fi.IsDir() || // TODO: cannot check for fi.ModTime() change helloStat.Mode() != fi.Mode() || helloStat.Size() != fi.Size() || !bytes.Equal(helloData, b) { // codepath taken if hello has been modified return fmt.Errorf("archive breakout: file %q has been modified. Contents: expected=%q, got=%q. FileInfo: expected=%#v, got=%#v", hello, helloData, b, helloStat, fi) } // Check that nothing in dest/ has the same content as victim/hello. // Since victim/hello was generated with time.Now(), it is safe to assume // that any file whose content matches exactly victim/hello, managed somehow // to access victim/hello. return filepath.Walk(dest, func(path string, info os.FileInfo, err error) error { if info.IsDir() { if err != nil { // skip directory if error return filepath.SkipDir } // enter directory return nil } if err != nil { // skip file if error return nil } b, err := ioutil.ReadFile(path) if err != nil { // Houston, we have a problem. Aborting (space)walk. return err } if bytes.Equal(helloData, b) { return fmt.Errorf("archive breakout: file %q has been accessed via %q", hello, path) } return nil }) } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/wrap.go ================================================ package archive import ( "archive/tar" "bytes" "io/ioutil" ) // Generate generates a new archive from the content provided // as input. // // `files` is a sequence of path/content pairs. A new file is // added to the archive for each pair. // If the last pair is incomplete, the file is created with an // empty content. For example: // // Generate("foo.txt", "hello world", "emptyfile") // // The above call will return an archive with 2 files: // * ./foo.txt with content "hello world" // * ./empty with empty content // // FIXME: stream content instead of buffering // FIXME: specify permissions and other archive metadata func Generate(input ...string) (Archive, error) { files := parseStringPairs(input...) buf := new(bytes.Buffer) tw := tar.NewWriter(buf) for _, file := range files { name, content := file[0], file[1] hdr := &tar.Header{ Name: name, Size: int64(len(content)), } if err := tw.WriteHeader(hdr); err != nil { return nil, err } if _, err := tw.Write([]byte(content)); err != nil { return nil, err } } if err := tw.Close(); err != nil { return nil, err } return ioutil.NopCloser(buf), nil } func parseStringPairs(input ...string) (output [][2]string) { output = make([][2]string, 0, len(input)/2+1) for i := 0; i < len(input); i += 2 { var pair [2]string pair[0] = input[i] if i+1 < len(input) { pair[1] = input[i+1] } output = append(output, pair) } return } ================================================ FILE: vendor/github.com/docker/docker/pkg/archive/wrap_test.go ================================================ package archive import ( "archive/tar" "bytes" "io" "testing" ) func TestGenerateEmptyFile(t *testing.T) { archive, err := Generate("emptyFile") if err != nil { t.Fatal(err) } if archive == nil { t.Fatal("The generated archive should not be nil.") } expectedFiles := [][]string{ {"emptyFile", ""}, } tr := tar.NewReader(archive) actualFiles := make([][]string, 0, 10) i := 0 for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } buf := new(bytes.Buffer) buf.ReadFrom(tr) content := buf.String() actualFiles = append(actualFiles, []string{hdr.Name, content}) i++ } if len(actualFiles) != len(expectedFiles) { t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) } for i := 0; i < len(expectedFiles); i++ { actual := actualFiles[i] expected := expectedFiles[i] if actual[0] != expected[0] { t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) } if actual[1] != expected[1] { t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) } } } func TestGenerateWithContent(t *testing.T) { archive, err := Generate("file", "content") if err != nil { t.Fatal(err) } if archive == nil { t.Fatal("The generated archive should not be nil.") } expectedFiles := [][]string{ {"file", "content"}, } tr := tar.NewReader(archive) actualFiles := make([][]string, 0, 10) i := 0 for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } buf := new(bytes.Buffer) buf.ReadFrom(tr) content := buf.String() actualFiles = append(actualFiles, []string{hdr.Name, content}) i++ } if len(actualFiles) != len(expectedFiles) { t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) } for i := 0; i < len(expectedFiles); i++ { actual := actualFiles[i] expected := expectedFiles[i] if actual[0] != expected[0] { t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) } if actual[1] != expected[1] { t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/broadcastwriter/broadcastwriter.go ================================================ package broadcastwriter import ( "bytes" "io" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/jsonlog" "github.com/docker/docker/pkg/timeutils" ) // BroadcastWriter accumulate multiple io.WriteCloser by stream. type BroadcastWriter struct { sync.Mutex buf *bytes.Buffer jsLogBuf *bytes.Buffer streams map[string](map[io.WriteCloser]struct{}) } // AddWriter adds new io.WriteCloser for stream. // If stream is "", then all writes proceed as is. Otherwise every line from // input will be packed to serialized jsonlog.JSONLog. func (w *BroadcastWriter) AddWriter(writer io.WriteCloser, stream string) { w.Lock() if _, ok := w.streams[stream]; !ok { w.streams[stream] = make(map[io.WriteCloser]struct{}) } w.streams[stream][writer] = struct{}{} w.Unlock() } // Write writes bytes to all writers. Failed writers will be evicted during // this call. func (w *BroadcastWriter) Write(p []byte) (n int, err error) { w.Lock() if writers, ok := w.streams[""]; ok { for sw := range writers { if n, err := sw.Write(p); err != nil || n != len(p) { // On error, evict the writer delete(writers, sw) } } if len(w.streams) == 1 { if w.buf.Len() >= 4096 { w.buf.Reset() } else { w.buf.Write(p) } w.Unlock() return len(p), nil } } if w.jsLogBuf == nil { w.jsLogBuf = new(bytes.Buffer) w.jsLogBuf.Grow(1024) } var timestamp string created := time.Now().UTC() w.buf.Write(p) for { if n := w.buf.Len(); n == 0 { break } i := bytes.IndexByte(w.buf.Bytes(), '\n') if i < 0 { break } lineBytes := w.buf.Next(i + 1) if timestamp == "" { timestamp, err = timeutils.FastMarshalJSON(created) if err != nil { continue } } for stream, writers := range w.streams { if stream == "" { continue } jsonLog := jsonlog.JSONLogBytes{Log: lineBytes, Stream: stream, Created: timestamp} err = jsonLog.MarshalJSONBuf(w.jsLogBuf) if err != nil { logrus.Errorf("Error making JSON log line: %s", err) continue } w.jsLogBuf.WriteByte('\n') b := w.jsLogBuf.Bytes() for sw := range writers { if _, err := sw.Write(b); err != nil { delete(writers, sw) } } } w.jsLogBuf.Reset() } w.jsLogBuf.Reset() w.Unlock() return len(p), nil } // Clean closes and removes all writers. Last non-eol-terminated part of data // will be saved. func (w *BroadcastWriter) Clean() error { w.Lock() for _, writers := range w.streams { for w := range writers { w.Close() } } w.streams = make(map[string](map[io.WriteCloser]struct{})) w.Unlock() return nil } func New() *BroadcastWriter { return &BroadcastWriter{ streams: make(map[string](map[io.WriteCloser]struct{})), buf: bytes.NewBuffer(nil), } } ================================================ FILE: vendor/github.com/docker/docker/pkg/broadcastwriter/broadcastwriter_test.go ================================================ package broadcastwriter import ( "bytes" "errors" "testing" ) type dummyWriter struct { buffer bytes.Buffer failOnWrite bool } func (dw *dummyWriter) Write(p []byte) (n int, err error) { if dw.failOnWrite { return 0, errors.New("Fake fail") } return dw.buffer.Write(p) } func (dw *dummyWriter) String() string { return dw.buffer.String() } func (dw *dummyWriter) Close() error { return nil } func TestBroadcastWriter(t *testing.T) { writer := New() // Test 1: Both bufferA and bufferB should contain "foo" bufferA := &dummyWriter{} writer.AddWriter(bufferA, "") bufferB := &dummyWriter{} writer.AddWriter(bufferB, "") writer.Write([]byte("foo")) if bufferA.String() != "foo" { t.Errorf("Buffer contains %v", bufferA.String()) } if bufferB.String() != "foo" { t.Errorf("Buffer contains %v", bufferB.String()) } // Test2: bufferA and bufferB should contain "foobar", // while bufferC should only contain "bar" bufferC := &dummyWriter{} writer.AddWriter(bufferC, "") writer.Write([]byte("bar")) if bufferA.String() != "foobar" { t.Errorf("Buffer contains %v", bufferA.String()) } if bufferB.String() != "foobar" { t.Errorf("Buffer contains %v", bufferB.String()) } if bufferC.String() != "bar" { t.Errorf("Buffer contains %v", bufferC.String()) } // Test3: Test eviction on failure bufferA.failOnWrite = true writer.Write([]byte("fail")) if bufferA.String() != "foobar" { t.Errorf("Buffer contains %v", bufferA.String()) } if bufferC.String() != "barfail" { t.Errorf("Buffer contains %v", bufferC.String()) } // Even though we reset the flag, no more writes should go in there bufferA.failOnWrite = false writer.Write([]byte("test")) if bufferA.String() != "foobar" { t.Errorf("Buffer contains %v", bufferA.String()) } if bufferC.String() != "barfailtest" { t.Errorf("Buffer contains %v", bufferC.String()) } writer.Clean() } type devNullCloser int func (d devNullCloser) Close() error { return nil } func (d devNullCloser) Write(buf []byte) (int, error) { return len(buf), nil } // This test checks for races. It is only useful when run with the race detector. func TestRaceBroadcastWriter(t *testing.T) { writer := New() c := make(chan bool) go func() { writer.AddWriter(devNullCloser(0), "") c <- true }() writer.Write([]byte("hello")) <-c } func BenchmarkBroadcastWriter(b *testing.B) { writer := New() setUpWriter := func() { for i := 0; i < 100; i++ { writer.AddWriter(devNullCloser(0), "stdout") writer.AddWriter(devNullCloser(0), "stderr") writer.AddWriter(devNullCloser(0), "") } } testLine := "Line that thinks that it is log line from docker" var buf bytes.Buffer for i := 0; i < 100; i++ { buf.Write([]byte(testLine + "\n")) } // line without eol buf.Write([]byte(testLine)) testText := buf.Bytes() b.SetBytes(int64(5 * len(testText))) b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() setUpWriter() b.StartTimer() for j := 0; j < 5; j++ { if _, err := writer.Write(testText); err != nil { b.Fatal(err) } } b.StopTimer() writer.Clean() b.StartTimer() } } func BenchmarkBroadcastWriterWithoutStdoutStderr(b *testing.B) { writer := New() setUpWriter := func() { for i := 0; i < 100; i++ { writer.AddWriter(devNullCloser(0), "") } } testLine := "Line that thinks that it is log line from docker" var buf bytes.Buffer for i := 0; i < 100; i++ { buf.Write([]byte(testLine + "\n")) } // line without eol buf.Write([]byte(testLine)) testText := buf.Bytes() b.SetBytes(int64(5 * len(testText))) b.ResetTimer() for i := 0; i < b.N; i++ { setUpWriter() for j := 0; j < 5; j++ { if _, err := writer.Write(testText); err != nil { b.Fatal(err) } } writer.Clean() } } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/archive.go ================================================ package chrootarchive import ( "fmt" "io" "os" "path/filepath" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/system" ) var chrootArchiver = &archive.Archiver{Untar: Untar} // Untar reads a stream of bytes from `archive`, parses it as a tar archive, // and unpacks it into the directory at `dest`. // The archive may be compressed with one of the following algorithms: // identity (uncompressed), gzip, bzip2, xz. func Untar(tarArchive io.Reader, dest string, options *archive.TarOptions) error { if tarArchive == nil { return fmt.Errorf("Empty archive") } if options == nil { options = &archive.TarOptions{} } if options.ExcludePatterns == nil { options.ExcludePatterns = []string{} } dest = filepath.Clean(dest) if _, err := os.Stat(dest); os.IsNotExist(err) { if err := system.MkdirAll(dest, 0777); err != nil { return err } } decompressedArchive, err := archive.DecompressStream(tarArchive) if err != nil { return err } defer decompressedArchive.Close() return invokeUnpack(decompressedArchive, dest, options) } // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. // If either Tar or Untar fails, TarUntar aborts and returns the error. func TarUntar(src, dst string) error { return chrootArchiver.TarUntar(src, dst) } // CopyWithTar creates a tar archive of filesystem path `src`, and // unpacks it at filesystem path `dst`. // The archive is streamed directly with fixed buffering and no // intermediary disk IO. func CopyWithTar(src, dst string) error { return chrootArchiver.CopyWithTar(src, dst) } // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. // // If `dst` ends with a trailing slash '/' ('\' on Windows), the final // destination path will be `dst/base(src)` or `dst\base(src)` func CopyFileWithTar(src, dst string) (err error) { return chrootArchiver.CopyFileWithTar(src, dst) } // UntarPath is a convenience function which looks for an archive // at filesystem path `src`, and unpacks it at `dst`. func UntarPath(src, dst string) error { return chrootArchiver.UntarPath(src, dst) } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/archive_test.go ================================================ package chrootarchive import ( "bytes" "fmt" "hash/crc32" "io" "io/ioutil" "os" "path/filepath" "strings" "testing" "time" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/system" ) func init() { reexec.Init() } func TestChrootTarUntar(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootTarUntar") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0644); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(src, "lolo"), []byte("hello lolo"), 0644); err != nil { t.Fatal(err) } stream, err := archive.Tar(src, archive.Uncompressed) if err != nil { t.Fatal(err) } dest := filepath.Join(tmpdir, "src") if err := system.MkdirAll(dest, 0700); err != nil { t.Fatal(err) } if err := Untar(stream, dest, &archive.TarOptions{ExcludePatterns: []string{"lolo"}}); err != nil { t.Fatal(err) } } // gh#10426: Verify the fix for having a huge excludes list (like on `docker load` with large # of // local images) func TestChrootUntarWithHugeExcludesList(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootUntarHugeExcludes") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0644); err != nil { t.Fatal(err) } stream, err := archive.Tar(src, archive.Uncompressed) if err != nil { t.Fatal(err) } dest := filepath.Join(tmpdir, "dest") if err := system.MkdirAll(dest, 0700); err != nil { t.Fatal(err) } options := &archive.TarOptions{} //65534 entries of 64-byte strings ~= 4MB of environment space which should overflow //on most systems when passed via environment or command line arguments excludes := make([]string, 65534, 65534) for i := 0; i < 65534; i++ { excludes[i] = strings.Repeat(string(i), 64) } options.ExcludePatterns = excludes if err := Untar(stream, dest, options); err != nil { t.Fatal(err) } } func TestChrootUntarEmptyArchive(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootUntarEmptyArchive") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := Untar(nil, tmpdir, nil); err == nil { t.Fatal("expected error on empty archive") } } func prepareSourceDirectory(numberOfFiles int, targetPath string, makeSymLinks bool) (int, error) { fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) if err := ioutil.WriteFile(filepath.Join(targetPath, fileName), fileData, 0700); err != nil { return 0, err } if makeSymLinks { if err := os.Symlink(filepath.Join(targetPath, fileName), filepath.Join(targetPath, fileName+"-link")); err != nil { return 0, err } } } totalSize := numberOfFiles * len(fileData) return totalSize, nil } func getHash(filename string) (uint32, error) { stream, err := ioutil.ReadFile(filename) if err != nil { return 0, err } hash := crc32.NewIEEE() hash.Write(stream) return hash.Sum32(), nil } func compareDirectories(src string, dest string) error { changes, err := archive.ChangesDirs(dest, src) if err != nil { return err } if len(changes) > 0 { return fmt.Errorf("Unexpected differences after untar: %v", changes) } return nil } func compareFiles(src string, dest string) error { srcHash, err := getHash(src) if err != nil { return err } destHash, err := getHash(dest) if err != nil { return err } if srcHash != destHash { return fmt.Errorf("%s is different from %s", src, dest) } return nil } func TestChrootTarUntarWithSymlink(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootTarUntarWithSymlink") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { t.Fatal(err) } dest := filepath.Join(tmpdir, "dest") if err := TarUntar(src, dest); err != nil { t.Fatal(err) } if err := compareDirectories(src, dest); err != nil { t.Fatal(err) } } func TestChrootCopyWithTar(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootCopyWithTar") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { t.Fatal(err) } // Copy directory dest := filepath.Join(tmpdir, "dest") if err := CopyWithTar(src, dest); err != nil { t.Fatal(err) } if err := compareDirectories(src, dest); err != nil { t.Fatal(err) } // Copy file srcfile := filepath.Join(src, "file-1") dest = filepath.Join(tmpdir, "destFile") destfile := filepath.Join(dest, "file-1") if err := CopyWithTar(srcfile, destfile); err != nil { t.Fatal(err) } if err := compareFiles(srcfile, destfile); err != nil { t.Fatal(err) } // Copy symbolic link srcLinkfile := filepath.Join(src, "file-1-link") dest = filepath.Join(tmpdir, "destSymlink") destLinkfile := filepath.Join(dest, "file-1-link") if err := CopyWithTar(srcLinkfile, destLinkfile); err != nil { t.Fatal(err) } if err := compareFiles(srcLinkfile, destLinkfile); err != nil { t.Fatal(err) } } func TestChrootCopyFileWithTar(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootCopyFileWithTar") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { t.Fatal(err) } // Copy directory dest := filepath.Join(tmpdir, "dest") if err := CopyFileWithTar(src, dest); err == nil { t.Fatal("Expected error on copying directory") } // Copy file srcfile := filepath.Join(src, "file-1") dest = filepath.Join(tmpdir, "destFile") destfile := filepath.Join(dest, "file-1") if err := CopyFileWithTar(srcfile, destfile); err != nil { t.Fatal(err) } if err := compareFiles(srcfile, destfile); err != nil { t.Fatal(err) } // Copy symbolic link srcLinkfile := filepath.Join(src, "file-1-link") dest = filepath.Join(tmpdir, "destSymlink") destLinkfile := filepath.Join(dest, "file-1-link") if err := CopyFileWithTar(srcLinkfile, destLinkfile); err != nil { t.Fatal(err) } if err := compareFiles(srcLinkfile, destLinkfile); err != nil { t.Fatal(err) } } func TestChrootUntarPath(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootUntarPath") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if _, err := prepareSourceDirectory(10, src, true); err != nil { t.Fatal(err) } dest := filepath.Join(tmpdir, "dest") // Untar a directory if err := UntarPath(src, dest); err == nil { t.Fatal("Expected error on untaring a directory") } // Untar a tar file stream, err := archive.Tar(src, archive.Uncompressed) if err != nil { t.Fatal(err) } buf := new(bytes.Buffer) buf.ReadFrom(stream) tarfile := filepath.Join(tmpdir, "src.tar") if err := ioutil.WriteFile(tarfile, buf.Bytes(), 0644); err != nil { t.Fatal(err) } if err := UntarPath(tarfile, dest); err != nil { t.Fatal(err) } if err := compareDirectories(src, dest); err != nil { t.Fatal(err) } } type slowEmptyTarReader struct { size int offset int chunkSize int } // Read is a slow reader of an empty tar (like the output of "tar c --files-from /dev/null") func (s *slowEmptyTarReader) Read(p []byte) (int, error) { time.Sleep(100 * time.Millisecond) count := s.chunkSize if len(p) < s.chunkSize { count = len(p) } for i := 0; i < count; i++ { p[i] = 0 } s.offset += count if s.offset > s.size { return count, io.EOF } return count, nil } func TestChrootUntarEmptyArchiveFromSlowReader(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootUntarEmptyArchiveFromSlowReader") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) dest := filepath.Join(tmpdir, "dest") if err := system.MkdirAll(dest, 0700); err != nil { t.Fatal(err) } stream := &slowEmptyTarReader{size: 10240, chunkSize: 1024} if err := Untar(stream, dest, nil); err != nil { t.Fatal(err) } } func TestChrootApplyEmptyArchiveFromSlowReader(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootApplyEmptyArchiveFromSlowReader") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) dest := filepath.Join(tmpdir, "dest") if err := system.MkdirAll(dest, 0700); err != nil { t.Fatal(err) } stream := &slowEmptyTarReader{size: 10240, chunkSize: 1024} if _, err := ApplyLayer(dest, stream); err != nil { t.Fatal(err) } } func TestChrootApplyDotDotFile(t *testing.T) { tmpdir, err := ioutil.TempDir("", "docker-TestChrootApplyDotDotFile") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) src := filepath.Join(tmpdir, "src") if err := system.MkdirAll(src, 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(filepath.Join(src, "..gitme"), []byte(""), 0644); err != nil { t.Fatal(err) } stream, err := archive.Tar(src, archive.Uncompressed) if err != nil { t.Fatal(err) } dest := filepath.Join(tmpdir, "dest") if err := system.MkdirAll(dest, 0700); err != nil { t.Fatal(err) } if _, err := ApplyLayer(dest, stream); err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/archive_unix.go ================================================ // +build !windows package chrootarchive import ( "bytes" "encoding/json" "flag" "fmt" "io" "os" "runtime" "syscall" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/reexec" ) func chroot(path string) error { if err := syscall.Chroot(path); err != nil { return err } return syscall.Chdir("/") } // untar is the entry-point for docker-untar on re-exec. This is not used on // Windows as it does not support chroot, hence no point sandboxing through // chroot and rexec. func untar() { runtime.LockOSThread() flag.Parse() var options *archive.TarOptions //read the options from the pipe "ExtraFiles" if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil { fatal(err) } if err := chroot(flag.Arg(0)); err != nil { fatal(err) } if err := archive.Unpack(os.Stdin, "/", options); err != nil { fatal(err) } // fully consume stdin in case it is zero padded flush(os.Stdin) os.Exit(0) } func invokeUnpack(decompressedArchive io.ReadCloser, dest string, options *archive.TarOptions) error { // We can't pass a potentially large exclude list directly via cmd line // because we easily overrun the kernel's max argument/environment size // when the full image list is passed (e.g. when this is used by // `docker load`). We will marshall the options via a pipe to the // child r, w, err := os.Pipe() if err != nil { return fmt.Errorf("Untar pipe failure: %v", err) } cmd := reexec.Command("docker-untar", dest) cmd.Stdin = decompressedArchive cmd.ExtraFiles = append(cmd.ExtraFiles, r) output := bytes.NewBuffer(nil) cmd.Stdout = output cmd.Stderr = output if err := cmd.Start(); err != nil { return fmt.Errorf("Untar error on re-exec cmd: %v", err) } //write the options to the pipe for the untar exec to read if err := json.NewEncoder(w).Encode(options); err != nil { return fmt.Errorf("Untar json encode to pipe failed: %v", err) } w.Close() if err := cmd.Wait(); err != nil { return fmt.Errorf("Untar re-exec error: %v: output: %s", err, output) } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/archive_windows.go ================================================ package chrootarchive import ( "io" "github.com/docker/docker/pkg/archive" ) // chroot is not supported by Windows func chroot(path string) error { return nil } func invokeUnpack(decompressedArchive io.ReadCloser, dest string, options *archive.TarOptions) error { // Windows is different to Linux here because Windows does not support // chroot. Hence there is no point sandboxing a chrooted process to // do the unpack. We call inline instead within the daemon process. return archive.Unpack(decompressedArchive, dest, options) } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/diff_unix.go ================================================ //+build !windows package chrootarchive import ( "bytes" "encoding/json" "flag" "fmt" "io/ioutil" "os" "path/filepath" "runtime" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/system" ) type applyLayerResponse struct { LayerSize int64 `json:"layerSize"` } // applyLayer is the entry-point for docker-applylayer on re-exec. This is not // used on Windows as it does not support chroot, hence no point sandboxing // through chroot and rexec. func applyLayer() { var ( tmpDir = "" err error ) runtime.LockOSThread() flag.Parse() if err := chroot(flag.Arg(0)); err != nil { fatal(err) } // We need to be able to set any perms oldmask, err := system.Umask(0) defer system.Umask(oldmask) if err != nil { fatal(err) } if tmpDir, err = ioutil.TempDir("/", "temp-docker-extract"); err != nil { fatal(err) } os.Setenv("TMPDIR", tmpDir) size, err := archive.UnpackLayer("/", os.Stdin) os.RemoveAll(tmpDir) if err != nil { fatal(err) } encoder := json.NewEncoder(os.Stdout) if err := encoder.Encode(applyLayerResponse{size}); err != nil { fatal(fmt.Errorf("unable to encode layerSize JSON: %s", err)) } flush(os.Stdout) flush(os.Stdin) os.Exit(0) } // ApplyLayer parses a diff in the standard layer format from `layer`, and // applies it to the directory `dest`. Returns the size in bytes of the // contents of the layer. func ApplyLayer(dest string, layer archive.ArchiveReader) (size int64, err error) { dest = filepath.Clean(dest) decompressed, err := archive.DecompressStream(layer) if err != nil { return 0, err } defer decompressed.Close() cmd := reexec.Command("docker-applyLayer", dest) cmd.Stdin = decompressed outBuf, errBuf := new(bytes.Buffer), new(bytes.Buffer) cmd.Stdout, cmd.Stderr = outBuf, errBuf if err = cmd.Run(); err != nil { return 0, fmt.Errorf("ApplyLayer %s stdout: %s stderr: %s", err, outBuf, errBuf) } // Stdout should be a valid JSON struct representing an applyLayerResponse. response := applyLayerResponse{} decoder := json.NewDecoder(outBuf) if err = decoder.Decode(&response); err != nil { return 0, fmt.Errorf("unable to decode ApplyLayer JSON response: %s", err) } return response.LayerSize, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/diff_windows.go ================================================ package chrootarchive import ( "fmt" "io/ioutil" "os" "path/filepath" "github.com/docker/docker/pkg/archive" ) func ApplyLayer(dest string, layer archive.ArchiveReader) (size int64, err error) { dest = filepath.Clean(dest) decompressed, err := archive.DecompressStream(layer) if err != nil { return 0, err } defer decompressed.Close() tmpDir, err := ioutil.TempDir(os.Getenv("temp"), "temp-docker-extract") if err != nil { return 0, fmt.Errorf("ApplyLayer failed to create temp-docker-extract under %s. %s", dest, err) } s, err := archive.UnpackLayer(dest, decompressed) os.RemoveAll(tmpDir) if err != nil { return 0, fmt.Errorf("ApplyLayer %s failed UnpackLayer to %s", err, dest) } return s, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/init_unix.go ================================================ // +build !windows package chrootarchive import ( "fmt" "io" "io/ioutil" "os" "github.com/docker/docker/pkg/reexec" ) func init() { reexec.Register("docker-applyLayer", applyLayer) reexec.Register("docker-untar", untar) } func fatal(err error) { fmt.Fprint(os.Stderr, err) os.Exit(1) } // flush consumes all the bytes from the reader discarding // any errors func flush(r io.Reader) { io.Copy(ioutil.Discard, r) } ================================================ FILE: vendor/github.com/docker/docker/pkg/chrootarchive/init_windows.go ================================================ package chrootarchive func init() { } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/attach_loopback.go ================================================ // +build linux package devicemapper import ( "fmt" "os" "syscall" "github.com/Sirupsen/logrus" ) func stringToLoopName(src string) [LoNameSize]uint8 { var dst [LoNameSize]uint8 copy(dst[:], src[:]) return dst } func getNextFreeLoopbackIndex() (int, error) { f, err := os.OpenFile("/dev/loop-control", os.O_RDONLY, 0644) if err != nil { return 0, err } defer f.Close() index, err := ioctlLoopCtlGetFree(f.Fd()) if index < 0 { index = 0 } return index, err } func openNextAvailableLoopback(index int, sparseFile *os.File) (loopFile *os.File, err error) { // Start looking for a free /dev/loop for { target := fmt.Sprintf("/dev/loop%d", index) index++ fi, err := os.Stat(target) if err != nil { if os.IsNotExist(err) { logrus.Errorf("There are no more loopback devices available.") } return nil, ErrAttachLoopbackDevice } if fi.Mode()&os.ModeDevice != os.ModeDevice { logrus.Errorf("Loopback device %s is not a block device.", target) continue } // OpenFile adds O_CLOEXEC loopFile, err = os.OpenFile(target, os.O_RDWR, 0644) if err != nil { logrus.Errorf("Error opening loopback device: %s", err) return nil, ErrAttachLoopbackDevice } // Try to attach to the loop file if err := ioctlLoopSetFd(loopFile.Fd(), sparseFile.Fd()); err != nil { loopFile.Close() // If the error is EBUSY, then try the next loopback if err != syscall.EBUSY { logrus.Errorf("Cannot set up loopback device %s: %s", target, err) return nil, ErrAttachLoopbackDevice } // Otherwise, we keep going with the loop continue } // In case of success, we finished. Break the loop. break } // This can't happen, but let's be sure if loopFile == nil { logrus.Errorf("Unreachable code reached! Error attaching %s to a loopback device.", sparseFile.Name()) return nil, ErrAttachLoopbackDevice } return loopFile, nil } // attachLoopDevice attaches the given sparse file to the next // available loopback device. It returns an opened *os.File. func AttachLoopDevice(sparseName string) (loop *os.File, err error) { // Try to retrieve the next available loopback device via syscall. // If it fails, we discard error and start loopking for a // loopback from index 0. startIndex, err := getNextFreeLoopbackIndex() if err != nil { logrus.Debugf("Error retrieving the next available loopback: %s", err) } // OpenFile adds O_CLOEXEC sparseFile, err := os.OpenFile(sparseName, os.O_RDWR, 0644) if err != nil { logrus.Errorf("Error opening sparse file %s: %s", sparseName, err) return nil, ErrAttachLoopbackDevice } defer sparseFile.Close() loopFile, err := openNextAvailableLoopback(startIndex, sparseFile) if err != nil { return nil, err } // Set the status of the loopback device loopInfo := &LoopInfo64{ loFileName: stringToLoopName(loopFile.Name()), loOffset: 0, loFlags: LoFlagsAutoClear, } if err := ioctlLoopSetStatus64(loopFile.Fd(), loopInfo); err != nil { logrus.Errorf("Cannot set up loopback device info: %s", err) // If the call failed, then free the loopback device if err := ioctlLoopClrFd(loopFile.Fd()); err != nil { logrus.Errorf("Error while cleaning up the loopback device") } loopFile.Close() return nil, ErrAttachLoopbackDevice } return loopFile, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/devmapper.go ================================================ // +build linux package devicemapper import ( "errors" "fmt" "os" "runtime" "syscall" "unsafe" "github.com/Sirupsen/logrus" ) type DevmapperLogger interface { DMLog(level int, file string, line int, dmError int, message string) } const ( DeviceCreate TaskType = iota DeviceReload DeviceRemove DeviceRemoveAll DeviceSuspend DeviceResume DeviceInfo DeviceDeps DeviceRename DeviceVersion DeviceStatus DeviceTable DeviceWaitevent DeviceList DeviceClear DeviceMknodes DeviceListVersions DeviceTargetMsg DeviceSetGeometry ) const ( AddNodeOnResume AddNodeType = iota AddNodeOnCreate ) var ( ErrTaskRun = errors.New("dm_task_run failed") ErrTaskSetName = errors.New("dm_task_set_name failed") ErrTaskSetMessage = errors.New("dm_task_set_message failed") ErrTaskSetAddNode = errors.New("dm_task_set_add_node failed") ErrTaskSetRo = errors.New("dm_task_set_ro failed") ErrTaskAddTarget = errors.New("dm_task_add_target failed") ErrTaskSetSector = errors.New("dm_task_set_sector failed") ErrTaskGetDeps = errors.New("dm_task_get_deps failed") ErrTaskGetInfo = errors.New("dm_task_get_info failed") ErrTaskGetDriverVersion = errors.New("dm_task_get_driver_version failed") ErrTaskDeferredRemove = errors.New("dm_task_deferred_remove failed") ErrTaskSetCookie = errors.New("dm_task_set_cookie failed") ErrNilCookie = errors.New("cookie ptr can't be nil") ErrAttachLoopbackDevice = errors.New("loopback mounting failed") ErrGetBlockSize = errors.New("Can't get block size") ErrUdevWait = errors.New("wait on udev cookie failed") ErrSetDevDir = errors.New("dm_set_dev_dir failed") ErrGetLibraryVersion = errors.New("dm_get_library_version failed") ErrCreateRemoveTask = errors.New("Can't create task of type DeviceRemove") ErrRunRemoveDevice = errors.New("running RemoveDevice failed") ErrInvalidAddNode = errors.New("Invalid AddNode type") ErrGetLoopbackBackingFile = errors.New("Unable to get loopback backing file") ErrLoopbackSetCapacity = errors.New("Unable set loopback capacity") ErrBusy = errors.New("Device is Busy") ErrDeviceIdExists = errors.New("Device Id Exists") ErrEnxio = errors.New("No such device or address") dmSawBusy bool dmSawExist bool dmSawEnxio bool // No Such Device or Address ) type ( Task struct { unmanaged *CDmTask } Deps struct { Count uint32 Filler uint32 Device []uint64 } Info struct { Exists int Suspended int LiveTable int InactiveTable int OpenCount int32 EventNr uint32 Major uint32 Minor uint32 ReadOnly int TargetCount int32 DeferredRemove int } TaskType int AddNodeType int ) // Returns whether error conveys the information about device Id already // exist or not. This will be true if device creation or snap creation // operation fails if device or snap device already exists in pool. // Current implementation is little crude as it scans the error string // for exact pattern match. Replacing it with more robust implementation // is desirable. func DeviceIdExists(err error) bool { return fmt.Sprint(err) == fmt.Sprint(ErrDeviceIdExists) } func (t *Task) destroy() { if t != nil { DmTaskDestroy(t.unmanaged) runtime.SetFinalizer(t, nil) } } // TaskCreateNamed is a convenience function for TaskCreate when a name // will be set on the task as well func TaskCreateNamed(t TaskType, name string) (*Task, error) { task := TaskCreate(t) if task == nil { return nil, fmt.Errorf("Can't create task of type %d", int(t)) } if err := task.SetName(name); err != nil { return nil, fmt.Errorf("Can't set task name %s", name) } return task, nil } // TaskCreate initializes a devicemapper task of tasktype func TaskCreate(tasktype TaskType) *Task { Ctask := DmTaskCreate(int(tasktype)) if Ctask == nil { return nil } task := &Task{unmanaged: Ctask} runtime.SetFinalizer(task, (*Task).destroy) return task } func (t *Task) Run() error { if res := DmTaskRun(t.unmanaged); res != 1 { return ErrTaskRun } return nil } func (t *Task) SetName(name string) error { if res := DmTaskSetName(t.unmanaged, name); res != 1 { return ErrTaskSetName } return nil } func (t *Task) SetMessage(message string) error { if res := DmTaskSetMessage(t.unmanaged, message); res != 1 { return ErrTaskSetMessage } return nil } func (t *Task) SetSector(sector uint64) error { if res := DmTaskSetSector(t.unmanaged, sector); res != 1 { return ErrTaskSetSector } return nil } func (t *Task) SetCookie(cookie *uint, flags uint16) error { if cookie == nil { return ErrNilCookie } if res := DmTaskSetCookie(t.unmanaged, cookie, flags); res != 1 { return ErrTaskSetCookie } return nil } func (t *Task) SetAddNode(addNode AddNodeType) error { if addNode != AddNodeOnResume && addNode != AddNodeOnCreate { return ErrInvalidAddNode } if res := DmTaskSetAddNode(t.unmanaged, addNode); res != 1 { return ErrTaskSetAddNode } return nil } func (t *Task) SetRo() error { if res := DmTaskSetRo(t.unmanaged); res != 1 { return ErrTaskSetRo } return nil } func (t *Task) AddTarget(start, size uint64, ttype, params string) error { if res := DmTaskAddTarget(t.unmanaged, start, size, ttype, params); res != 1 { return ErrTaskAddTarget } return nil } func (t *Task) GetDeps() (*Deps, error) { var deps *Deps if deps = DmTaskGetDeps(t.unmanaged); deps == nil { return nil, ErrTaskGetDeps } return deps, nil } func (t *Task) GetInfo() (*Info, error) { info := &Info{} if res := DmTaskGetInfo(t.unmanaged, info); res != 1 { return nil, ErrTaskGetInfo } return info, nil } func (t *Task) GetInfoWithDeferred() (*Info, error) { info := &Info{} if res := DmTaskGetInfoWithDeferred(t.unmanaged, info); res != 1 { return nil, ErrTaskGetInfo } return info, nil } func (t *Task) GetDriverVersion() (string, error) { res := DmTaskGetDriverVersion(t.unmanaged) if res == "" { return "", ErrTaskGetDriverVersion } return res, nil } func (t *Task) GetNextTarget(next unsafe.Pointer) (nextPtr unsafe.Pointer, start uint64, length uint64, targetType string, params string) { return DmGetNextTarget(t.unmanaged, next, &start, &length, &targetType, ¶ms), start, length, targetType, params } func getLoopbackBackingFile(file *os.File) (uint64, uint64, error) { loopInfo, err := ioctlLoopGetStatus64(file.Fd()) if err != nil { logrus.Errorf("Error get loopback backing file: %s", err) return 0, 0, ErrGetLoopbackBackingFile } return loopInfo.loDevice, loopInfo.loInode, nil } func LoopbackSetCapacity(file *os.File) error { if err := ioctlLoopSetCapacity(file.Fd(), 0); err != nil { logrus.Errorf("Error loopbackSetCapacity: %s", err) return ErrLoopbackSetCapacity } return nil } func FindLoopDeviceFor(file *os.File) *os.File { stat, err := file.Stat() if err != nil { return nil } targetInode := stat.Sys().(*syscall.Stat_t).Ino targetDevice := stat.Sys().(*syscall.Stat_t).Dev for i := 0; true; i++ { path := fmt.Sprintf("/dev/loop%d", i) file, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { if os.IsNotExist(err) { return nil } // Ignore all errors until the first not-exist // we want to continue looking for the file continue } dev, inode, err := getLoopbackBackingFile(file) if err == nil && dev == targetDevice && inode == targetInode { return file } file.Close() } return nil } func UdevWait(cookie *uint) error { if res := DmUdevWait(*cookie); res != 1 { logrus.Debugf("Failed to wait on udev cookie %d", *cookie) return ErrUdevWait } return nil } func LogInitVerbose(level int) { DmLogInitVerbose(level) } var dmLogger DevmapperLogger = nil // initialize the logger for the device mapper library func LogInit(logger DevmapperLogger) { dmLogger = logger LogWithErrnoInit() } func SetDevDir(dir string) error { if res := DmSetDevDir(dir); res != 1 { logrus.Debugf("Error dm_set_dev_dir") return ErrSetDevDir } return nil } func GetLibraryVersion() (string, error) { var version string if res := DmGetLibraryVersion(&version); res != 1 { return "", ErrGetLibraryVersion } return version, nil } // UdevSyncSupported returns whether device-mapper is able to sync with udev // // This is essential otherwise race conditions can arise where both udev and // device-mapper attempt to create and destroy devices. func UdevSyncSupported() bool { return DmUdevGetSyncSupport() != 0 } // UdevSetSyncSupport allows setting whether the udev sync should be enabled. // The return bool indicates the state of whether the sync is enabled. func UdevSetSyncSupport(enable bool) bool { if enable { DmUdevSetSyncSupport(1) } else { DmUdevSetSyncSupport(0) } return UdevSyncSupported() } // CookieSupported returns whether the version of device-mapper supports the // use of cookie's in the tasks. // This is largely a lower level call that other functions use. func CookieSupported() bool { return DmCookieSupported() != 0 } // Useful helper for cleanup func RemoveDevice(name string) error { task, err := TaskCreateNamed(DeviceRemove, name) if task == nil { return err } var cookie uint = 0 if err := task.SetCookie(&cookie, 0); err != nil { return fmt.Errorf("Can not set cookie: %s", err) } defer UdevWait(&cookie) dmSawBusy = false // reset before the task is run if err = task.Run(); err != nil { if dmSawBusy { return ErrBusy } return fmt.Errorf("Error running RemoveDevice %s", err) } return nil } func RemoveDeviceDeferred(name string) error { logrus.Debugf("[devmapper] RemoveDeviceDeferred START(%s)", name) defer logrus.Debugf("[devmapper] RemoveDeviceDeferred END(%s)", name) task, err := TaskCreateNamed(DeviceRemove, name) if task == nil { return err } if err := DmTaskDeferredRemove(task.unmanaged); err != 1 { return ErrTaskDeferredRemove } if err = task.Run(); err != nil { return fmt.Errorf("Error running RemoveDeviceDeferred %s", err) } return nil } // Useful helper for cleanup func CancelDeferredRemove(deviceName string) error { task, err := TaskCreateNamed(DeviceTargetMsg, deviceName) if task == nil { return err } if err := task.SetSector(0); err != nil { return fmt.Errorf("Can't set sector %s", err) } if err := task.SetMessage(fmt.Sprintf("@cancel_deferred_remove")); err != nil { return fmt.Errorf("Can't set message %s", err) } dmSawBusy = false dmSawEnxio = false if err := task.Run(); err != nil { // A device might be being deleted already if dmSawBusy { return ErrBusy } else if dmSawEnxio { return ErrEnxio } return fmt.Errorf("Error running CancelDeferredRemove %s", err) } return nil } func GetBlockDeviceSize(file *os.File) (uint64, error) { size, err := ioctlBlkGetSize64(file.Fd()) if err != nil { logrus.Errorf("Error getblockdevicesize: %s", err) return 0, ErrGetBlockSize } return uint64(size), nil } func BlockDeviceDiscard(path string) error { file, err := os.OpenFile(path, os.O_RDWR, 0) if err != nil { return err } defer file.Close() size, err := GetBlockDeviceSize(file) if err != nil { return err } if err := ioctlBlkDiscard(file.Fd(), 0, size); err != nil { return err } // Without this sometimes the remove of the device that happens after // discard fails with EBUSY. syscall.Sync() return nil } // This is the programmatic example of "dmsetup create" func CreatePool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error { task, err := TaskCreateNamed(DeviceCreate, poolName) if task == nil { return err } size, err := GetBlockDeviceSize(dataFile) if err != nil { return fmt.Errorf("Can't get data size %s", err) } params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize) if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil { return fmt.Errorf("Can't add target %s", err) } var cookie uint = 0 var flags uint16 = DmUdevDisableSubsystemRulesFlag | DmUdevDisableDiskRulesFlag | DmUdevDisableOtherRulesFlag if err := task.SetCookie(&cookie, flags); err != nil { return fmt.Errorf("Can't set cookie %s", err) } defer UdevWait(&cookie) if err := task.Run(); err != nil { return fmt.Errorf("Error running DeviceCreate (CreatePool) %s", err) } return nil } func ReloadPool(poolName string, dataFile, metadataFile *os.File, poolBlockSize uint32) error { task, err := TaskCreateNamed(DeviceReload, poolName) if task == nil { return err } size, err := GetBlockDeviceSize(dataFile) if err != nil { return fmt.Errorf("Can't get data size %s", err) } params := fmt.Sprintf("%s %s %d 32768 1 skip_block_zeroing", metadataFile.Name(), dataFile.Name(), poolBlockSize) if err := task.AddTarget(0, size/512, "thin-pool", params); err != nil { return fmt.Errorf("Can't add target %s", err) } if err := task.Run(); err != nil { return fmt.Errorf("Error running DeviceCreate %s", err) } return nil } func GetDeps(name string) (*Deps, error) { task, err := TaskCreateNamed(DeviceDeps, name) if task == nil { return nil, err } if err := task.Run(); err != nil { return nil, err } return task.GetDeps() } func GetInfo(name string) (*Info, error) { task, err := TaskCreateNamed(DeviceInfo, name) if task == nil { return nil, err } if err := task.Run(); err != nil { return nil, err } return task.GetInfo() } func GetInfoWithDeferred(name string) (*Info, error) { task, err := TaskCreateNamed(DeviceInfo, name) if task == nil { return nil, err } if err := task.Run(); err != nil { return nil, err } return task.GetInfoWithDeferred() } func GetDriverVersion() (string, error) { task := TaskCreate(DeviceVersion) if task == nil { return "", fmt.Errorf("Can't create DeviceVersion task") } if err := task.Run(); err != nil { return "", err } return task.GetDriverVersion() } func GetStatus(name string) (uint64, uint64, string, string, error) { task, err := TaskCreateNamed(DeviceStatus, name) if task == nil { logrus.Debugf("GetStatus: Error TaskCreateNamed: %s", err) return 0, 0, "", "", err } if err := task.Run(); err != nil { logrus.Debugf("GetStatus: Error Run: %s", err) return 0, 0, "", "", err } devinfo, err := task.GetInfo() if err != nil { logrus.Debugf("GetStatus: Error GetInfo: %s", err) return 0, 0, "", "", err } if devinfo.Exists == 0 { logrus.Debugf("GetStatus: Non existing device %s", name) return 0, 0, "", "", fmt.Errorf("Non existing device %s", name) } _, start, length, targetType, params := task.GetNextTarget(unsafe.Pointer(nil)) return start, length, targetType, params, nil } func GetTable(name string) (uint64, uint64, string, string, error) { task, err := TaskCreateNamed(DeviceTable, name) if task == nil { logrus.Debugf("GetTable: Error TaskCreateNamed: %s", err) return 0, 0, "", "", err } if err := task.Run(); err != nil { logrus.Debugf("GetTable: Error Run: %s", err) return 0, 0, "", "", err } devinfo, err := task.GetInfo() if err != nil { logrus.Debugf("GetTable: Error GetInfo: %s", err) return 0, 0, "", "", err } if devinfo.Exists == 0 { logrus.Debugf("GetTable: Non existing device %s", name) return 0, 0, "", "", fmt.Errorf("Non existing device %s", name) } _, start, length, targetType, params := task.GetNextTarget(unsafe.Pointer(nil)) return start, length, targetType, params, nil } func SetTransactionId(poolName string, oldId uint64, newId uint64) error { task, err := TaskCreateNamed(DeviceTargetMsg, poolName) if task == nil { return err } if err := task.SetSector(0); err != nil { return fmt.Errorf("Can't set sector %s", err) } if err := task.SetMessage(fmt.Sprintf("set_transaction_id %d %d", oldId, newId)); err != nil { return fmt.Errorf("Can't set message %s", err) } if err := task.Run(); err != nil { return fmt.Errorf("Error running SetTransactionId %s", err) } return nil } func SuspendDevice(name string) error { task, err := TaskCreateNamed(DeviceSuspend, name) if task == nil { return err } if err := task.Run(); err != nil { return fmt.Errorf("Error running DeviceSuspend %s", err) } return nil } func ResumeDevice(name string) error { task, err := TaskCreateNamed(DeviceResume, name) if task == nil { return err } var cookie uint = 0 if err := task.SetCookie(&cookie, 0); err != nil { return fmt.Errorf("Can't set cookie %s", err) } defer UdevWait(&cookie) if err := task.Run(); err != nil { return fmt.Errorf("Error running DeviceResume %s", err) } return nil } func CreateDevice(poolName string, deviceId int) error { logrus.Debugf("[devmapper] CreateDevice(poolName=%v, deviceId=%v)", poolName, deviceId) task, err := TaskCreateNamed(DeviceTargetMsg, poolName) if task == nil { return err } if err := task.SetSector(0); err != nil { return fmt.Errorf("Can't set sector %s", err) } if err := task.SetMessage(fmt.Sprintf("create_thin %d", deviceId)); err != nil { return fmt.Errorf("Can't set message %s", err) } dmSawExist = false // reset before the task is run if err := task.Run(); err != nil { // Caller wants to know about ErrDeviceIdExists so that it can try with a different device id. if dmSawExist { return ErrDeviceIdExists } return fmt.Errorf("Error running CreateDevice %s", err) } return nil } func DeleteDevice(poolName string, deviceId int) error { task, err := TaskCreateNamed(DeviceTargetMsg, poolName) if task == nil { return err } if err := task.SetSector(0); err != nil { return fmt.Errorf("Can't set sector %s", err) } if err := task.SetMessage(fmt.Sprintf("delete %d", deviceId)); err != nil { return fmt.Errorf("Can't set message %s", err) } if err := task.Run(); err != nil { return fmt.Errorf("Error running DeleteDevice %s", err) } return nil } func ActivateDevice(poolName string, name string, deviceId int, size uint64) error { return activateDevice(poolName, name, deviceId, size, "") } func ActivateDeviceWithExternal(poolName string, name string, deviceId int, size uint64, external string) error { return activateDevice(poolName, name, deviceId, size, external) } func activateDevice(poolName string, name string, deviceId int, size uint64, external string) error { task, err := TaskCreateNamed(DeviceCreate, name) if task == nil { return err } var params string if len(external) > 0 { params = fmt.Sprintf("%s %d %s", poolName, deviceId, external) } else { params = fmt.Sprintf("%s %d", poolName, deviceId) } if err := task.AddTarget(0, size/512, "thin", params); err != nil { return fmt.Errorf("Can't add target %s", err) } if err := task.SetAddNode(AddNodeOnCreate); err != nil { return fmt.Errorf("Can't add node %s", err) } var cookie uint = 0 if err := task.SetCookie(&cookie, 0); err != nil { return fmt.Errorf("Can't set cookie %s", err) } defer UdevWait(&cookie) if err := task.Run(); err != nil { return fmt.Errorf("Error running DeviceCreate (ActivateDevice) %s", err) } return nil } func CreateSnapDevice(poolName string, deviceId int, baseName string, baseDeviceId int) error { devinfo, _ := GetInfo(baseName) doSuspend := devinfo != nil && devinfo.Exists != 0 if doSuspend { if err := SuspendDevice(baseName); err != nil { return err } } task, err := TaskCreateNamed(DeviceTargetMsg, poolName) if task == nil { if doSuspend { ResumeDevice(baseName) } return err } if err := task.SetSector(0); err != nil { if doSuspend { ResumeDevice(baseName) } return fmt.Errorf("Can't set sector %s", err) } if err := task.SetMessage(fmt.Sprintf("create_snap %d %d", deviceId, baseDeviceId)); err != nil { if doSuspend { ResumeDevice(baseName) } return fmt.Errorf("Can't set message %s", err) } dmSawExist = false // reset before the task is run if err := task.Run(); err != nil { if doSuspend { ResumeDevice(baseName) } // Caller wants to know about ErrDeviceIdExists so that it can try with a different device id. if dmSawExist { return ErrDeviceIdExists } return fmt.Errorf("Error running DeviceCreate (createSnapDevice) %s", err) } if doSuspend { if err := ResumeDevice(baseName); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/devmapper_log.go ================================================ // +build linux package devicemapper import "C" import ( "strings" ) // Due to the way cgo works this has to be in a separate file, as devmapper.go has // definitions in the cgo block, which is incompatible with using "//export" //export DevmapperLogCallback func DevmapperLogCallback(level C.int, file *C.char, line C.int, dm_errno_or_class C.int, message *C.char) { msg := C.GoString(message) if level < 7 { if strings.Contains(msg, "busy") { dmSawBusy = true } if strings.Contains(msg, "File exists") { dmSawExist = true } if strings.Contains(msg, "No such device or address") { dmSawEnxio = true } } if dmLogger != nil { dmLogger.DMLog(int(level), C.GoString(file), int(line), int(dm_errno_or_class), msg) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/devmapper_wrapper.go ================================================ // +build linux package devicemapper /* #cgo LDFLAGS: -L. -ldevmapper #include #include // FIXME: present only for defines, maybe we can remove it? #include // FIXME: present only for BLKGETSIZE64, maybe we can remove it? #ifndef LOOP_CTL_GET_FREE #define LOOP_CTL_GET_FREE 0x4C82 #endif #ifndef LO_FLAGS_PARTSCAN #define LO_FLAGS_PARTSCAN 8 #endif // FIXME: Can't we find a way to do the logging in pure Go? extern void DevmapperLogCallback(int level, char *file, int line, int dm_errno_or_class, char *str); static void log_cb(int level, const char *file, int line, int dm_errno_or_class, const char *f, ...) { char buffer[256]; va_list ap; va_start(ap, f); vsnprintf(buffer, 256, f, ap); va_end(ap); DevmapperLogCallback(level, (char *)file, line, dm_errno_or_class, buffer); } static void log_with_errno_init() { dm_log_with_errno_init(log_cb); } */ import "C" import "unsafe" type ( CDmTask C.struct_dm_task CLoopInfo64 C.struct_loop_info64 LoopInfo64 struct { loDevice uint64 /* ioctl r/o */ loInode uint64 /* ioctl r/o */ loRdevice uint64 /* ioctl r/o */ loOffset uint64 loSizelimit uint64 /* bytes, 0 == max available */ loNumber uint32 /* ioctl r/o */ loEncrypt_type uint32 loEncrypt_key_size uint32 /* ioctl w/o */ loFlags uint32 /* ioctl r/o */ loFileName [LoNameSize]uint8 loCryptName [LoNameSize]uint8 loEncryptKey [LoKeySize]uint8 /* ioctl w/o */ loInit [2]uint64 } ) // IOCTL consts const ( BlkGetSize64 = C.BLKGETSIZE64 BlkDiscard = C.BLKDISCARD LoopSetFd = C.LOOP_SET_FD LoopCtlGetFree = C.LOOP_CTL_GET_FREE LoopGetStatus64 = C.LOOP_GET_STATUS64 LoopSetStatus64 = C.LOOP_SET_STATUS64 LoopClrFd = C.LOOP_CLR_FD LoopSetCapacity = C.LOOP_SET_CAPACITY ) const ( LoFlagsAutoClear = C.LO_FLAGS_AUTOCLEAR LoFlagsReadOnly = C.LO_FLAGS_READ_ONLY LoFlagsPartScan = C.LO_FLAGS_PARTSCAN LoKeySize = C.LO_KEY_SIZE LoNameSize = C.LO_NAME_SIZE ) const ( DmUdevDisableSubsystemRulesFlag = C.DM_UDEV_DISABLE_SUBSYSTEM_RULES_FLAG DmUdevDisableDiskRulesFlag = C.DM_UDEV_DISABLE_DISK_RULES_FLAG DmUdevDisableOtherRulesFlag = C.DM_UDEV_DISABLE_OTHER_RULES_FLAG DmUdevDisableLibraryFallback = C.DM_UDEV_DISABLE_LIBRARY_FALLBACK ) var ( DmGetLibraryVersion = dmGetLibraryVersionFct DmGetNextTarget = dmGetNextTargetFct DmLogInitVerbose = dmLogInitVerboseFct DmSetDevDir = dmSetDevDirFct DmTaskAddTarget = dmTaskAddTargetFct DmTaskCreate = dmTaskCreateFct DmTaskDestroy = dmTaskDestroyFct DmTaskGetDeps = dmTaskGetDepsFct DmTaskGetInfo = dmTaskGetInfoFct DmTaskGetDriverVersion = dmTaskGetDriverVersionFct DmTaskRun = dmTaskRunFct DmTaskSetAddNode = dmTaskSetAddNodeFct DmTaskSetCookie = dmTaskSetCookieFct DmTaskSetMessage = dmTaskSetMessageFct DmTaskSetName = dmTaskSetNameFct DmTaskSetRo = dmTaskSetRoFct DmTaskSetSector = dmTaskSetSectorFct DmUdevWait = dmUdevWaitFct DmUdevSetSyncSupport = dmUdevSetSyncSupportFct DmUdevGetSyncSupport = dmUdevGetSyncSupportFct DmCookieSupported = dmCookieSupportedFct LogWithErrnoInit = logWithErrnoInitFct DmTaskDeferredRemove = dmTaskDeferredRemoveFct DmTaskGetInfoWithDeferred = dmTaskGetInfoWithDeferredFct ) func free(p *C.char) { C.free(unsafe.Pointer(p)) } func dmTaskDestroyFct(task *CDmTask) { C.dm_task_destroy((*C.struct_dm_task)(task)) } func dmTaskCreateFct(taskType int) *CDmTask { return (*CDmTask)(C.dm_task_create(C.int(taskType))) } func dmTaskRunFct(task *CDmTask) int { ret, _ := C.dm_task_run((*C.struct_dm_task)(task)) return int(ret) } func dmTaskSetNameFct(task *CDmTask, name string) int { Cname := C.CString(name) defer free(Cname) return int(C.dm_task_set_name((*C.struct_dm_task)(task), Cname)) } func dmTaskSetMessageFct(task *CDmTask, message string) int { Cmessage := C.CString(message) defer free(Cmessage) return int(C.dm_task_set_message((*C.struct_dm_task)(task), Cmessage)) } func dmTaskSetSectorFct(task *CDmTask, sector uint64) int { return int(C.dm_task_set_sector((*C.struct_dm_task)(task), C.uint64_t(sector))) } func dmTaskSetCookieFct(task *CDmTask, cookie *uint, flags uint16) int { cCookie := C.uint32_t(*cookie) defer func() { *cookie = uint(cCookie) }() return int(C.dm_task_set_cookie((*C.struct_dm_task)(task), &cCookie, C.uint16_t(flags))) } func dmTaskSetAddNodeFct(task *CDmTask, addNode AddNodeType) int { return int(C.dm_task_set_add_node((*C.struct_dm_task)(task), C.dm_add_node_t(addNode))) } func dmTaskSetRoFct(task *CDmTask) int { return int(C.dm_task_set_ro((*C.struct_dm_task)(task))) } func dmTaskAddTargetFct(task *CDmTask, start, size uint64, ttype, params string) int { Cttype := C.CString(ttype) defer free(Cttype) Cparams := C.CString(params) defer free(Cparams) return int(C.dm_task_add_target((*C.struct_dm_task)(task), C.uint64_t(start), C.uint64_t(size), Cttype, Cparams)) } func dmTaskGetDepsFct(task *CDmTask) *Deps { Cdeps := C.dm_task_get_deps((*C.struct_dm_task)(task)) if Cdeps == nil { return nil } deps := &Deps{ Count: uint32(Cdeps.count), Filler: uint32(Cdeps.filler), } for _, device := range Cdeps.device { deps.Device = append(deps.Device, (uint64)(device)) } return deps } func dmTaskGetInfoFct(task *CDmTask, info *Info) int { Cinfo := C.struct_dm_info{} defer func() { info.Exists = int(Cinfo.exists) info.Suspended = int(Cinfo.suspended) info.LiveTable = int(Cinfo.live_table) info.InactiveTable = int(Cinfo.inactive_table) info.OpenCount = int32(Cinfo.open_count) info.EventNr = uint32(Cinfo.event_nr) info.Major = uint32(Cinfo.major) info.Minor = uint32(Cinfo.minor) info.ReadOnly = int(Cinfo.read_only) info.TargetCount = int32(Cinfo.target_count) }() return int(C.dm_task_get_info((*C.struct_dm_task)(task), &Cinfo)) } func dmTaskGetDriverVersionFct(task *CDmTask) string { buffer := C.malloc(128) defer C.free(buffer) res := C.dm_task_get_driver_version((*C.struct_dm_task)(task), (*C.char)(buffer), 128) if res == 0 { return "" } return C.GoString((*C.char)(buffer)) } func dmGetNextTargetFct(task *CDmTask, next unsafe.Pointer, start, length *uint64, target, params *string) unsafe.Pointer { var ( Cstart, Clength C.uint64_t CtargetType, Cparams *C.char ) defer func() { *start = uint64(Cstart) *length = uint64(Clength) *target = C.GoString(CtargetType) *params = C.GoString(Cparams) }() nextp := C.dm_get_next_target((*C.struct_dm_task)(task), next, &Cstart, &Clength, &CtargetType, &Cparams) return nextp } func dmUdevSetSyncSupportFct(syncWithUdev int) { (C.dm_udev_set_sync_support(C.int(syncWithUdev))) } func dmUdevGetSyncSupportFct() int { return int(C.dm_udev_get_sync_support()) } func dmUdevWaitFct(cookie uint) int { return int(C.dm_udev_wait(C.uint32_t(cookie))) } func dmCookieSupportedFct() int { return int(C.dm_cookie_supported()) } func dmLogInitVerboseFct(level int) { C.dm_log_init_verbose(C.int(level)) } func logWithErrnoInitFct() { C.log_with_errno_init() } func dmSetDevDirFct(dir string) int { Cdir := C.CString(dir) defer free(Cdir) return int(C.dm_set_dev_dir(Cdir)) } func dmGetLibraryVersionFct(version *string) int { buffer := C.CString(string(make([]byte, 128))) defer free(buffer) defer func() { *version = C.GoString(buffer) }() return int(C.dm_get_library_version(buffer, 128)) } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/devmapper_wrapper_deferred_remove.go ================================================ // +build linux,!libdm_no_deferred_remove package devicemapper /* #cgo LDFLAGS: -L. -ldevmapper #include */ import "C" const LibraryDeferredRemovalSupport = true func dmTaskDeferredRemoveFct(task *CDmTask) int { return int(C.dm_task_deferred_remove((*C.struct_dm_task)(task))) } func dmTaskGetInfoWithDeferredFct(task *CDmTask, info *Info) int { Cinfo := C.struct_dm_info{} defer func() { info.Exists = int(Cinfo.exists) info.Suspended = int(Cinfo.suspended) info.LiveTable = int(Cinfo.live_table) info.InactiveTable = int(Cinfo.inactive_table) info.OpenCount = int32(Cinfo.open_count) info.EventNr = uint32(Cinfo.event_nr) info.Major = uint32(Cinfo.major) info.Minor = uint32(Cinfo.minor) info.ReadOnly = int(Cinfo.read_only) info.TargetCount = int32(Cinfo.target_count) info.DeferredRemove = int(Cinfo.deferred_remove) }() return int(C.dm_task_get_info((*C.struct_dm_task)(task), &Cinfo)) } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/devmapper_wrapper_no_deferred_remove.go ================================================ // +build linux,libdm_no_deferred_remove package devicemapper const LibraryDeferredRemovalSupport = false func dmTaskDeferredRemoveFct(task *CDmTask) int { // Error. Nobody should be calling it. return -1 } func dmTaskGetInfoWithDeferredFct(task *CDmTask, info *Info) int { return -1 } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/ioctl.go ================================================ // +build linux package devicemapper import ( "syscall" "unsafe" ) func ioctlLoopCtlGetFree(fd uintptr) (int, error) { index, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, LoopCtlGetFree, 0) if err != 0 { return 0, err } return int(index), nil } func ioctlLoopSetFd(loopFd, sparseFd uintptr) error { if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopSetFd, sparseFd); err != 0 { return err } return nil } func ioctlLoopSetStatus64(loopFd uintptr, loopInfo *LoopInfo64) error { if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopSetStatus64, uintptr(unsafe.Pointer(loopInfo))); err != 0 { return err } return nil } func ioctlLoopClrFd(loopFd uintptr) error { if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopClrFd, 0); err != 0 { return err } return nil } func ioctlLoopGetStatus64(loopFd uintptr) (*LoopInfo64, error) { loopInfo := &LoopInfo64{} if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopGetStatus64, uintptr(unsafe.Pointer(loopInfo))); err != 0 { return nil, err } return loopInfo, nil } func ioctlLoopSetCapacity(loopFd uintptr, value int) error { if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, loopFd, LoopSetCapacity, uintptr(value)); err != 0 { return err } return nil } func ioctlBlkGetSize64(fd uintptr) (int64, error) { var size int64 if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, BlkGetSize64, uintptr(unsafe.Pointer(&size))); err != 0 { return 0, err } return size, nil } func ioctlBlkDiscard(fd uintptr, offset, length uint64) error { var r [2]uint64 r[0] = offset r[1] = length if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, BlkDiscard, uintptr(unsafe.Pointer(&r[0]))); err != 0 { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/devicemapper/log.go ================================================ package devicemapper // definitions from lvm2 lib/log/log.h const ( LogLevelFatal = 2 + iota // _LOG_FATAL LogLevelErr // _LOG_ERR LogLevelWarn // _LOG_WARN LogLevelNotice // _LOG_NOTICE LogLevelInfo // _LOG_INFO LogLevelDebug // _LOG_DEBUG ) ================================================ FILE: vendor/github.com/docker/docker/pkg/directory/directory_linux.go ================================================ // +build linux package directory import ( "os" "path/filepath" "syscall" ) // Size walks a directory tree and returns its total size in bytes. func Size(dir string) (size int64, err error) { data := make(map[uint64]struct{}) err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error { // Ignore directory sizes if fileInfo == nil { return nil } s := fileInfo.Size() if fileInfo.IsDir() || s == 0 { return nil } // Check inode to handle hard links correctly inode := fileInfo.Sys().(*syscall.Stat_t).Ino // inode is not a uint64 on all platforms. Cast it to avoid issues. if _, exists := data[uint64(inode)]; exists { return nil } // inode is not a uint64 on all platforms. Cast it to avoid issues. data[uint64(inode)] = struct{}{} size += s return nil }) return } ================================================ FILE: vendor/github.com/docker/docker/pkg/directory/directory_test.go ================================================ package directory import ( "io/ioutil" "os" "testing" ) // Size of an empty directory should be 0 func TestSizeEmpty(t *testing.T) { var dir string var err error if dir, err = ioutil.TempDir(os.TempDir(), "testSizeEmptyDirectory"); err != nil { t.Fatalf("failed to create directory: %s", err) } var size int64 if size, _ = Size(dir); size != 0 { t.Fatalf("empty directory has size: %d", size) } } // Size of a directory with one empty file should be 0 func TestSizeEmptyFile(t *testing.T) { var dir string var err error if dir, err = ioutil.TempDir(os.TempDir(), "testSizeEmptyFile"); err != nil { t.Fatalf("failed to create directory: %s", err) } var file *os.File if file, err = ioutil.TempFile(dir, "file"); err != nil { t.Fatalf("failed to create file: %s", err) } var size int64 if size, _ = Size(file.Name()); size != 0 { t.Fatalf("directory with one file has size: %d", size) } } // Size of a directory with one 5-byte file should be 5 func TestSizeNonemptyFile(t *testing.T) { var dir string var err error if dir, err = ioutil.TempDir(os.TempDir(), "testSizeNonemptyFile"); err != nil { t.Fatalf("failed to create directory: %s", err) } var file *os.File if file, err = ioutil.TempFile(dir, "file"); err != nil { t.Fatalf("failed to create file: %s", err) } d := []byte{97, 98, 99, 100, 101} file.Write(d) var size int64 if size, _ = Size(file.Name()); size != 5 { t.Fatalf("directory with one 5-byte file has size: %d", size) } } // Size of a directory with one empty directory should be 0 func TestSizeNestedDirectoryEmpty(t *testing.T) { var dir string var err error if dir, err = ioutil.TempDir(os.TempDir(), "testSizeNestedDirectoryEmpty"); err != nil { t.Fatalf("failed to create directory: %s", err) } if dir, err = ioutil.TempDir(dir, "nested"); err != nil { t.Fatalf("failed to create nested directory: %s", err) } var size int64 if size, _ = Size(dir); size != 0 { t.Fatalf("directory with one empty directory has size: %d", size) } } // Test directory with 1 file and 1 empty directory func TestSizeFileAndNestedDirectoryEmpty(t *testing.T) { var dir string var err error if dir, err = ioutil.TempDir(os.TempDir(), "testSizeFileAndNestedDirectoryEmpty"); err != nil { t.Fatalf("failed to create directory: %s", err) } if dir, err = ioutil.TempDir(dir, "nested"); err != nil { t.Fatalf("failed to create nested directory: %s", err) } var file *os.File if file, err = ioutil.TempFile(dir, "file"); err != nil { t.Fatalf("failed to create file: %s", err) } d := []byte{100, 111, 99, 107, 101, 114} file.Write(d) var size int64 if size, _ = Size(dir); size != 6 { t.Fatalf("directory with 6-byte file and empty directory has size: %d", size) } } // Test directory with 1 file and 1 non-empty directory func TestSizeFileAndNestedDirectoryNonempty(t *testing.T) { var dir, dirNested string var err error if dir, err = ioutil.TempDir(os.TempDir(), "TestSizeFileAndNestedDirectoryNonempty"); err != nil { t.Fatalf("failed to create directory: %s", err) } if dirNested, err = ioutil.TempDir(dir, "nested"); err != nil { t.Fatalf("failed to create nested directory: %s", err) } var file *os.File if file, err = ioutil.TempFile(dir, "file"); err != nil { t.Fatalf("failed to create file: %s", err) } data := []byte{100, 111, 99, 107, 101, 114} file.Write(data) var nestedFile *os.File if nestedFile, err = ioutil.TempFile(dirNested, "file"); err != nil { t.Fatalf("failed to create file in nested directory: %s", err) } nestedData := []byte{100, 111, 99, 107, 101, 114} nestedFile.Write(nestedData) var size int64 if size, _ = Size(dir); size != 12 { t.Fatalf("directory with 6-byte file and nested directory with 6-byte file has size: %d", size) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/directory/directory_windows.go ================================================ // +build windows package directory import ( "os" "path/filepath" ) // Size walks a directory tree and returns its total size in bytes. func Size(dir string) (size int64, err error) { err = filepath.Walk(dir, func(d string, fileInfo os.FileInfo, e error) error { // Ignore directory sizes if fileInfo == nil { return nil } s := fileInfo.Size() if fileInfo.IsDir() || s == 0 { return nil } size += s return nil }) return } ================================================ FILE: vendor/github.com/docker/docker/pkg/fileutils/fileutils.go ================================================ package fileutils import ( "errors" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "github.com/Sirupsen/logrus" ) // exclusion return true if the specified pattern is an exclusion func exclusion(pattern string) bool { return pattern[0] == '!' } // empty return true if the specified pattern is empty func empty(pattern string) bool { return pattern == "" } // CleanPatterns takes a slice of patterns returns a new // slice of patterns cleaned with filepath.Clean, stripped // of any empty patterns and lets the caller know whether the // slice contains any exception patterns (prefixed with !). func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) { // Loop over exclusion patterns and: // 1. Clean them up. // 2. Indicate whether we are dealing with any exception rules. // 3. Error if we see a single exclusion marker on it's own (!). cleanedPatterns := []string{} patternDirs := [][]string{} exceptions := false for _, pattern := range patterns { // Eliminate leading and trailing whitespace. pattern = strings.TrimSpace(pattern) if empty(pattern) { continue } if exclusion(pattern) { if len(pattern) == 1 { return nil, nil, false, errors.New("Illegal exclusion pattern: !") } exceptions = true } pattern = filepath.Clean(pattern) cleanedPatterns = append(cleanedPatterns, pattern) if exclusion(pattern) { pattern = pattern[1:] } patternDirs = append(patternDirs, strings.Split(pattern, "/")) } return cleanedPatterns, patternDirs, exceptions, nil } // Matches returns true if file matches any of the patterns // and isn't excluded by any of the subsequent patterns. func Matches(file string, patterns []string) (bool, error) { file = filepath.Clean(file) if file == "." { // Don't let them exclude everything, kind of silly. return false, nil } patterns, patDirs, _, err := CleanPatterns(patterns) if err != nil { return false, err } return OptimizedMatches(file, patterns, patDirs) } // OptimizedMatches is basically the same as fileutils.Matches() but optimized for archive.go. // It will assume that the inputs have been preprocessed and therefore the function // doen't need to do as much error checking and clean-up. This was done to avoid // repeating these steps on each file being checked during the archive process. // The more generic fileutils.Matches() can't make these assumptions. func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, error) { matched := false parentPath := filepath.Dir(file) parentPathDirs := strings.Split(parentPath, "/") for i, pattern := range patterns { negative := false if exclusion(pattern) { negative = true pattern = pattern[1:] } match, err := filepath.Match(pattern, file) if err != nil { return false, err } if !match && parentPath != "." { // Check to see if the pattern matches one of our parent dirs. if len(patDirs[i]) <= len(parentPathDirs) { match, _ = filepath.Match(strings.Join(patDirs[i], "/"), strings.Join(parentPathDirs[:len(patDirs[i])], "/")) } } if match { matched = !negative } } if matched { logrus.Debugf("Skipping excluded path: %s", file) } return matched, nil } // CopyFile copies from src to dst until either EOF is reached // on src or an error occurs. It verifies src exists and remove // the dst if it exists. func CopyFile(src, dst string) (int64, error) { cleanSrc := filepath.Clean(src) cleanDst := filepath.Clean(dst) if cleanSrc == cleanDst { return 0, nil } sf, err := os.Open(cleanSrc) if err != nil { return 0, err } defer sf.Close() if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { return 0, err } df, err := os.Create(cleanDst) if err != nil { return 0, err } defer df.Close() return io.Copy(df, sf) } // GetTotalUsedFds Returns the number of used File Descriptors by // reading it via /proc filesystem. func GetTotalUsedFds() int { if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) } else { return len(fds) } return -1 } // ReadSymlinkedDirectory returns the target directory of a symlink. // The target of the symbolic link may not be a file. func ReadSymlinkedDirectory(path string) (string, error) { var realPath string var err error if realPath, err = filepath.Abs(path); err != nil { return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) } if realPath, err = filepath.EvalSymlinks(realPath); err != nil { return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) } realPathInfo, err := os.Stat(realPath) if err != nil { return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) } if !realPathInfo.Mode().IsDir() { return "", fmt.Errorf("canonical path points to a file '%s'", realPath) } return realPath, nil } // 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 } ================================================ FILE: vendor/github.com/docker/docker/pkg/fileutils/fileutils_test.go ================================================ package fileutils import ( "io/ioutil" "os" "path" "path/filepath" "testing" ) // CopyFile with invalid src func TestCopyFileWithInvalidSrc(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest")) if err == nil { t.Fatal("Should have fail to copy an invalid src file") } if bytes != 0 { t.Fatal("Should have written 0 bytes") } } // CopyFile with invalid dest func TestCopyFileWithInvalidDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } src := path.Join(tempFolder, "file") err = ioutil.WriteFile(src, []byte("content"), 0740) if err != nil { t.Fatal(err) } bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path")) if err == nil { t.Fatal("Should have fail to copy an invalid src file") } if bytes != 0 { t.Fatal("Should have written 0 bytes") } } // CopyFile with same src and dest func TestCopyFileWithSameSrcAndDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } file := path.Join(tempFolder, "file") err = ioutil.WriteFile(file, []byte("content"), 0740) if err != nil { t.Fatal(err) } bytes, err := CopyFile(file, file) if err != nil { t.Fatal(err) } if bytes != 0 { t.Fatal("Should have written 0 bytes as it is the same file.") } } // CopyFile with same src and dest but path is different and not clean func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } testFolder := path.Join(tempFolder, "test") err = os.MkdirAll(testFolder, 0740) if err != nil { t.Fatal(err) } file := path.Join(testFolder, "file") sameFile := testFolder + "/../test/file" err = ioutil.WriteFile(file, []byte("content"), 0740) if err != nil { t.Fatal(err) } bytes, err := CopyFile(file, sameFile) if err != nil { t.Fatal(err) } if bytes != 0 { t.Fatal("Should have written 0 bytes as it is the same file.") } } func TestCopyFile(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } src := path.Join(tempFolder, "src") dest := path.Join(tempFolder, "dest") ioutil.WriteFile(src, []byte("content"), 0777) ioutil.WriteFile(dest, []byte("destContent"), 0777) bytes, err := CopyFile(src, dest) if err != nil { t.Fatal(err) } if bytes != 7 { t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes) } actual, err := ioutil.ReadFile(dest) if err != nil { t.Fatal(err) } if string(actual) != "content" { t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content") } } // Reading a symlink to a directory must return the directory func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { var err error if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil { t.Errorf("failed to create directory: %s", err) } if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil { t.Errorf("failed to create symlink: %s", err) } var path string if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil { t.Fatalf("failed to read symlink to directory: %s", err) } if path != "/tmp/testReadSymlinkToExistingDirectory" { t.Fatalf("symlink returned unexpected directory: %s", path) } if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil { t.Errorf("failed to remove temporary directory: %s", err) } if err = os.Remove("/tmp/dirLinkTest"); err != nil { t.Errorf("failed to remove symlink: %s", err) } } // Reading a non-existing symlink must fail func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) { var path string var err error if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil { t.Fatalf("error expected for non-existing symlink") } if path != "" { t.Fatalf("expected empty path, but '%s' was returned", path) } } // Reading a symlink to a file must fail func TestReadSymlinkedDirectoryToFile(t *testing.T) { var err error var file *os.File if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil { t.Fatalf("failed to create file: %s", err) } file.Close() if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil { t.Errorf("failed to create symlink: %s", err) } var path string if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil { t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed") } if path != "" { t.Fatalf("path should've been empty: %s", path) } if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil { t.Errorf("failed to remove file: %s", err) } if err = os.Remove("/tmp/fileLinkTest"); err != nil { t.Errorf("failed to remove symlink: %s", err) } } func TestWildcardMatches(t *testing.T) { match, _ := Matches("fileutils.go", []string{"*"}) if match != true { t.Errorf("failed to get a wildcard match, got %v", match) } } // A simple pattern match should return true. func TestPatternMatches(t *testing.T) { match, _ := Matches("fileutils.go", []string{"*.go"}) if match != true { t.Errorf("failed to get a match, got %v", match) } } // An exclusion followed by an inclusion should return true. func TestExclusionPatternMatchesPatternBefore(t *testing.T) { match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"}) if match != true { t.Errorf("failed to get true match on exclusion pattern, got %v", match) } } // A folder pattern followed by an exception should return false. func TestPatternMatchesFolderExclusions(t *testing.T) { match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"}) if match != false { t.Errorf("failed to get a false match on exclusion pattern, got %v", match) } } // A folder pattern followed by an exception should return false. func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) { match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"}) if match != false { t.Errorf("failed to get a false match on exclusion pattern, got %v", match) } } // A folder pattern followed by an exception should return false. func TestPatternMatchesFolderWildcardExclusions(t *testing.T) { match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"}) if match != false { t.Errorf("failed to get a false match on exclusion pattern, got %v", match) } } // A pattern followed by an exclusion should return false. func TestExclusionPatternMatchesPatternAfter(t *testing.T) { match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"}) if match != false { t.Errorf("failed to get false match on exclusion pattern, got %v", match) } } // A filename evaluating to . should return false. func TestExclusionPatternMatchesWholeDirectory(t *testing.T) { match, _ := Matches(".", []string{"*.go"}) if match != false { t.Errorf("failed to get false match on ., got %v", match) } } // A single ! pattern should return an error. func TestSingleExclamationError(t *testing.T) { _, err := Matches("fileutils.go", []string{"!"}) if err == nil { t.Errorf("failed to get an error for a single exclamation point, got %v", err) } } // A string preceded with a ! should return true from Exclusion. func TestExclusion(t *testing.T) { exclusion := exclusion("!") if !exclusion { t.Errorf("failed to get true for a single !, got %v", exclusion) } } // Matches with no patterns func TestMatchesWithNoPatterns(t *testing.T) { matches, err := Matches("/any/path/there", []string{}) if err != nil { t.Fatal(err) } if matches { t.Fatalf("Should not have match anything") } } // Matches with malformed patterns func TestMatchesWithMalformedPatterns(t *testing.T) { matches, err := Matches("/any/path/there", []string{"["}) if err == nil { t.Fatal("Should have failed because of a malformed syntax in the pattern") } if matches { t.Fatalf("Should not have match anything") } } // An empty string should return true from Empty. func TestEmpty(t *testing.T) { empty := empty("") if !empty { t.Errorf("failed to get true for an empty string, got %v", empty) } } func TestCleanPatterns(t *testing.T) { cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"}) if len(cleaned) != 2 { t.Errorf("expected 2 element slice, got %v", len(cleaned)) } } func TestCleanPatternsStripEmptyPatterns(t *testing.T) { cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""}) if len(cleaned) != 2 { t.Errorf("expected 2 element slice, got %v", len(cleaned)) } } func TestCleanPatternsExceptionFlag(t *testing.T) { _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"}) if !exceptions { t.Errorf("expected exceptions to be true, got %v", exceptions) } } func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) { _, _, exceptions, _ := CleanPatterns([]string{"docs", " !docs/README.md"}) if !exceptions { t.Errorf("expected exceptions to be true, got %v", exceptions) } } func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) { _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md "}) if !exceptions { t.Errorf("expected exceptions to be true, got %v", exceptions) } } func TestCleanPatternsErrorSingleException(t *testing.T) { _, _, _, err := CleanPatterns([]string{"!"}) if err == nil { t.Errorf("expected error on single exclamation point, got %v", err) } } func TestCleanPatternsFolderSplit(t *testing.T) { _, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"}) if dirs[0][0] != "docs" { t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1]) } if dirs[0][1] != "config" { t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1]) } } func TestCreateIfNotExistsDir(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) folderToCreate := filepath.Join(tempFolder, "tocreate") if err := CreateIfNotExists(folderToCreate, true); err != nil { t.Fatal(err) } fileinfo, err := os.Stat(folderToCreate) if err != nil { t.Fatalf("Should have create a folder, got %v", err) } if !fileinfo.IsDir() { t.Fatalf("Should have been a dir, seems it's not") } } func TestCreateIfNotExistsFile(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) fileToCreate := filepath.Join(tempFolder, "file/to/create") if err := CreateIfNotExists(fileToCreate, false); err != nil { t.Fatal(err) } fileinfo, err := os.Stat(fileToCreate) if err != nil { t.Fatalf("Should have create a file, got %v", err) } if fileinfo.IsDir() { t.Fatalf("Should have been a file, seems it's not") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/conn_sqlite3.go ================================================ package graphdb import "database/sql" // NewSqliteConn opens a connection to a sqlite // database. func NewSqliteConn(root string) (*Database, error) { conn, err := sql.Open("sqlite3", root) if err != nil { return nil, err } return NewDatabase(conn) } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/conn_sqlite3_unix.go ================================================ // +build cgo,!windows package graphdb import _ "code.google.com/p/gosqlite/sqlite3" // registers sqlite ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/conn_sqlite3_windows.go ================================================ // +build cgo,windows package graphdb import _ "github.com/mattn/go-sqlite3" // registers sqlite ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/conn_unsupported.go ================================================ // +build !cgo package graphdb func NewSqliteConn(root string) (*Database, error) { panic("Not implemented") } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/graphdb.go ================================================ package graphdb import ( "database/sql" "fmt" "path" "strings" "sync" ) const ( createEntityTable = ` CREATE TABLE IF NOT EXISTS entity ( id text NOT NULL PRIMARY KEY );` createEdgeTable = ` CREATE TABLE IF NOT EXISTS edge ( "entity_id" text NOT NULL, "parent_id" text NULL, "name" text NOT NULL, CONSTRAINT "parent_fk" FOREIGN KEY ("parent_id") REFERENCES "entity" ("id"), CONSTRAINT "entity_fk" FOREIGN KEY ("entity_id") REFERENCES "entity" ("id") ); ` createEdgeIndices = ` CREATE UNIQUE INDEX IF NOT EXISTS "name_parent_ix" ON "edge" (parent_id, name); ` ) // Entity with a unique id type Entity struct { id string } // An Edge connects two entities together type Edge struct { EntityID string Name string ParentID string } // Entities stores the list of entities type Entities map[string]*Entity // Edges stores the relationships between entities type Edges []*Edge // WalkFunc is a function invoked to process an individual entity type WalkFunc func(fullPath string, entity *Entity) error // Database is a graph database for storing entities and their relationships type Database struct { conn *sql.DB mux sync.RWMutex } // IsNonUniqueNameError processes the error to check if it's caused by // a constraint violation. // This is necessary because the error isn't the same across various // sqlite versions. func IsNonUniqueNameError(err error) bool { str := err.Error() // sqlite 3.7.17-1ubuntu1 returns: // Set failure: Abort due to constraint violation: columns parent_id, name are not unique if strings.HasSuffix(str, "name are not unique") { return true } // sqlite-3.8.3-1.fc20 returns: // Set failure: Abort due to constraint violation: UNIQUE constraint failed: edge.parent_id, edge.name if strings.Contains(str, "UNIQUE constraint failed") && strings.Contains(str, "edge.name") { return true } // sqlite-3.6.20-1.el6 returns: // Set failure: Abort due to constraint violation: constraint failed if strings.HasSuffix(str, "constraint failed") { return true } return false } // NewDatabase creates a new graph database initialized with a root entity func NewDatabase(conn *sql.DB) (*Database, error) { if conn == nil { return nil, fmt.Errorf("Database connection cannot be nil") } db := &Database{conn: conn} // Create root entities tx, err := conn.Begin() if err != nil { return nil, err } if _, err := tx.Exec(createEntityTable); err != nil { return nil, err } if _, err := tx.Exec(createEdgeTable); err != nil { return nil, err } if _, err := tx.Exec(createEdgeIndices); err != nil { return nil, err } if _, err := tx.Exec("DELETE FROM entity where id = ?", "0"); err != nil { tx.Rollback() return nil, err } if _, err := tx.Exec("INSERT INTO entity (id) VALUES (?);", "0"); err != nil { tx.Rollback() return nil, err } if _, err := tx.Exec("DELETE FROM edge where entity_id=? and name=?", "0", "/"); err != nil { tx.Rollback() return nil, err } if _, err := tx.Exec("INSERT INTO edge (entity_id, name) VALUES(?,?);", "0", "/"); err != nil { tx.Rollback() return nil, err } if err := tx.Commit(); err != nil { return nil, err } return db, nil } // Close the underlying connection to the database func (db *Database) Close() error { return db.conn.Close() } // Set the entity id for a given path func (db *Database) Set(fullPath, id string) (*Entity, error) { db.mux.Lock() defer db.mux.Unlock() tx, err := db.conn.Begin() if err != nil { return nil, err } var entityID string if err := tx.QueryRow("SELECT id FROM entity WHERE id = ?;", id).Scan(&entityID); err != nil { if err == sql.ErrNoRows { if _, err := tx.Exec("INSERT INTO entity (id) VALUES(?);", id); err != nil { tx.Rollback() return nil, err } } else { tx.Rollback() return nil, err } } e := &Entity{id} parentPath, name := splitPath(fullPath) if err := db.setEdge(parentPath, name, e, tx); err != nil { tx.Rollback() return nil, err } if err := tx.Commit(); err != nil { return nil, err } return e, nil } // Exists returns true if a name already exists in the database func (db *Database) Exists(name string) bool { db.mux.RLock() defer db.mux.RUnlock() e, err := db.get(name) if err != nil { return false } return e != nil } func (db *Database) setEdge(parentPath, name string, e *Entity, tx *sql.Tx) error { parent, err := db.get(parentPath) if err != nil { return err } if parent.id == e.id { return fmt.Errorf("Cannot set self as child") } if _, err := tx.Exec("INSERT INTO edge (parent_id, name, entity_id) VALUES (?,?,?);", parent.id, name, e.id); err != nil { return err } return nil } // RootEntity returns the root "/" entity for the database func (db *Database) RootEntity() *Entity { return &Entity{ id: "0", } } // Get returns the entity for a given path func (db *Database) Get(name string) *Entity { db.mux.RLock() defer db.mux.RUnlock() e, err := db.get(name) if err != nil { return nil } return e } func (db *Database) get(name string) (*Entity, error) { e := db.RootEntity() // We always know the root name so return it if // it is requested if name == "/" { return e, nil } parts := split(name) for i := 1; i < len(parts); i++ { p := parts[i] if p == "" { continue } next := db.child(e, p) if next == nil { return nil, fmt.Errorf("Cannot find child for %s", name) } e = next } return e, nil } // List all entities by from the name // The key will be the full path of the entity func (db *Database) List(name string, depth int) Entities { db.mux.RLock() defer db.mux.RUnlock() out := Entities{} e, err := db.get(name) if err != nil { return out } children, err := db.children(e, name, depth, nil) if err != nil { return out } for _, c := range children { out[c.FullPath] = c.Entity } return out } // Walk through the child graph of an entity, calling walkFunc for each child entity. // It is safe for walkFunc to call graph functions. func (db *Database) Walk(name string, walkFunc WalkFunc, depth int) error { children, err := db.Children(name, depth) if err != nil { return err } // Note: the database lock must not be held while calling walkFunc for _, c := range children { if err := walkFunc(c.FullPath, c.Entity); err != nil { return err } } return nil } // Children returns the children of the specified entity func (db *Database) Children(name string, depth int) ([]WalkMeta, error) { db.mux.RLock() defer db.mux.RUnlock() e, err := db.get(name) if err != nil { return nil, err } return db.children(e, name, depth, nil) } // Parents returns the parents of a specified entity func (db *Database) Parents(name string) ([]string, error) { db.mux.RLock() defer db.mux.RUnlock() e, err := db.get(name) if err != nil { return nil, err } return db.parents(e) } // Refs returns the refrence count for a specified id func (db *Database) Refs(id string) int { db.mux.RLock() defer db.mux.RUnlock() var count int if err := db.conn.QueryRow("SELECT COUNT(*) FROM edge WHERE entity_id = ?;", id).Scan(&count); err != nil { return 0 } return count } // RefPaths returns all the id's path references func (db *Database) RefPaths(id string) Edges { db.mux.RLock() defer db.mux.RUnlock() refs := Edges{} rows, err := db.conn.Query("SELECT name, parent_id FROM edge WHERE entity_id = ?;", id) if err != nil { return refs } defer rows.Close() for rows.Next() { var name string var parentID string if err := rows.Scan(&name, &parentID); err != nil { return refs } refs = append(refs, &Edge{ EntityID: id, Name: name, ParentID: parentID, }) } return refs } // Delete the reference to an entity at a given path func (db *Database) Delete(name string) error { db.mux.Lock() defer db.mux.Unlock() if name == "/" { return fmt.Errorf("Cannot delete root entity") } parentPath, n := splitPath(name) parent, err := db.get(parentPath) if err != nil { return err } if _, err := db.conn.Exec("DELETE FROM edge WHERE parent_id = ? AND name = ?;", parent.id, n); err != nil { return err } return nil } // Purge removes the entity with the specified id // Walk the graph to make sure all references to the entity // are removed and return the number of references removed func (db *Database) Purge(id string) (int, error) { db.mux.Lock() defer db.mux.Unlock() tx, err := db.conn.Begin() if err != nil { return -1, err } // Delete all edges rows, err := tx.Exec("DELETE FROM edge WHERE entity_id = ?;", id) if err != nil { tx.Rollback() return -1, err } changes, err := rows.RowsAffected() if err != nil { return -1, err } // Clear who's using this id as parent refs, err := tx.Exec("DELETE FROM edge WHERE parent_id = ?;", id) if err != nil { tx.Rollback() return -1, err } refsCount, err := refs.RowsAffected() if err != nil { return -1, err } // Delete entity if _, err := tx.Exec("DELETE FROM entity where id = ?;", id); err != nil { tx.Rollback() return -1, err } if err := tx.Commit(); err != nil { return -1, err } return int(changes + refsCount), nil } // Rename an edge for a given path func (db *Database) Rename(currentName, newName string) error { db.mux.Lock() defer db.mux.Unlock() parentPath, name := splitPath(currentName) newParentPath, newEdgeName := splitPath(newName) if parentPath != newParentPath { return fmt.Errorf("Cannot rename when root paths do not match %s != %s", parentPath, newParentPath) } parent, err := db.get(parentPath) if err != nil { return err } rows, err := db.conn.Exec("UPDATE edge SET name = ? WHERE parent_id = ? AND name = ?;", newEdgeName, parent.id, name) if err != nil { return err } i, err := rows.RowsAffected() if err != nil { return err } if i == 0 { return fmt.Errorf("Cannot locate edge for %s %s", parent.id, name) } return nil } type WalkMeta struct { Parent *Entity Entity *Entity FullPath string Edge *Edge } func (db *Database) children(e *Entity, name string, depth int, entities []WalkMeta) ([]WalkMeta, error) { if e == nil { return entities, nil } rows, err := db.conn.Query("SELECT entity_id, name FROM edge where parent_id = ?;", e.id) if err != nil { return nil, err } defer rows.Close() for rows.Next() { var entityID, entityName string if err := rows.Scan(&entityID, &entityName); err != nil { return nil, err } child := &Entity{entityID} edge := &Edge{ ParentID: e.id, Name: entityName, EntityID: child.id, } meta := WalkMeta{ Parent: e, Entity: child, FullPath: path.Join(name, edge.Name), Edge: edge, } entities = append(entities, meta) if depth != 0 { nDepth := depth if depth != -1 { nDepth-- } entities, err = db.children(child, meta.FullPath, nDepth, entities) if err != nil { return nil, err } } } return entities, nil } func (db *Database) parents(e *Entity) (parents []string, err error) { if e == nil { return parents, nil } rows, err := db.conn.Query("SELECT parent_id FROM edge where entity_id = ?;", e.id) if err != nil { return nil, err } defer rows.Close() for rows.Next() { var parentID string if err := rows.Scan(&parentID); err != nil { return nil, err } parents = append(parents, parentID) } return parents, nil } // Return the entity based on the parent path and name func (db *Database) child(parent *Entity, name string) *Entity { var id string if err := db.conn.QueryRow("SELECT entity_id FROM edge WHERE parent_id = ? AND name = ?;", parent.id, name).Scan(&id); err != nil { return nil } return &Entity{id} } // ID returns the id used to reference this entity func (e *Entity) ID() string { return e.id } // Paths returns the paths sorted by depth func (e Entities) Paths() []string { out := make([]string, len(e)) var i int for k := range e { out[i] = k i++ } sortByDepth(out) return out } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/graphdb_test.go ================================================ package graphdb import ( "database/sql" "fmt" "os" "path" "strconv" "testing" _ "code.google.com/p/gosqlite/sqlite3" ) func newTestDb(t *testing.T) (*Database, string) { p := path.Join(os.TempDir(), "sqlite.db") conn, err := sql.Open("sqlite3", p) db, err := NewDatabase(conn) if err != nil { t.Fatal(err) } return db, p } func destroyTestDb(dbPath string) { os.Remove(dbPath) } func TestNewDatabase(t *testing.T) { db, dbpath := newTestDb(t) if db == nil { t.Fatal("Database should not be nil") } db.Close() defer destroyTestDb(dbpath) } func TestCreateRootEntity(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) root := db.RootEntity() if root == nil { t.Fatal("Root entity should not be nil") } } func TestGetRootEntity(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) e := db.Get("/") if e == nil { t.Fatal("Entity should not be nil") } if e.ID() != "0" { t.Fatalf("Entity id should be 0, got %s", e.ID()) } } func TestSetEntityWithDifferentName(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/test", "1") if _, err := db.Set("/other", "1"); err != nil { t.Fatal(err) } } func TestSetDuplicateEntity(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) if _, err := db.Set("/foo", "42"); err != nil { t.Fatal(err) } if _, err := db.Set("/foo", "43"); err == nil { t.Fatalf("Creating an entry with a duplicate path did not cause an error") } } func TestCreateChild(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) child, err := db.Set("/db", "1") if err != nil { t.Fatal(err) } if child == nil { t.Fatal("Child should not be nil") } if child.ID() != "1" { t.Fail() } } func TestParents(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) for i := 1; i < 6; i++ { a := strconv.Itoa(i) if _, err := db.Set("/"+a, a); err != nil { t.Fatal(err) } } for i := 6; i < 11; i++ { a := strconv.Itoa(i) p := strconv.Itoa(i - 5) key := fmt.Sprintf("/%s/%s", p, a) if _, err := db.Set(key, a); err != nil { t.Fatal(err) } parents, err := db.Parents(key) if err != nil { t.Fatal(err) } if len(parents) != 1 { t.Fatalf("Expected 1 entry for %s got %d", key, len(parents)) } if parents[0] != p { t.Fatalf("ID %s received, %s expected", parents[0], p) } } } func TestChildren(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) str := "/" for i := 1; i < 6; i++ { a := strconv.Itoa(i) if _, err := db.Set(str+a, a); err != nil { t.Fatal(err) } str = str + a + "/" } str = "/" for i := 10; i < 30; i++ { // 20 entities a := strconv.Itoa(i) if _, err := db.Set(str+a, a); err != nil { t.Fatal(err) } str = str + a + "/" } entries, err := db.Children("/", 5) if err != nil { t.Fatal(err) } if len(entries) != 11 { t.Fatalf("Expect 11 entries for / got %d", len(entries)) } entries, err = db.Children("/", 20) if err != nil { t.Fatal(err) } if len(entries) != 25 { t.Fatalf("Expect 25 entries for / got %d", len(entries)) } } func TestListAllRootChildren(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) for i := 1; i < 6; i++ { a := strconv.Itoa(i) if _, err := db.Set("/"+a, a); err != nil { t.Fatal(err) } } entries := db.List("/", -1) if len(entries) != 5 { t.Fatalf("Expect 5 entries for / got %d", len(entries)) } } func TestListAllSubChildren(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) _, err := db.Set("/webapp", "1") if err != nil { t.Fatal(err) } child2, err := db.Set("/db", "2") if err != nil { t.Fatal(err) } child4, err := db.Set("/logs", "4") if err != nil { t.Fatal(err) } if _, err := db.Set("/db/logs", child4.ID()); err != nil { t.Fatal(err) } child3, err := db.Set("/sentry", "3") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/sentry", child3.ID()); err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/db", child2.ID()); err != nil { t.Fatal(err) } entries := db.List("/webapp", 1) if len(entries) != 3 { t.Fatalf("Expect 3 entries for / got %d", len(entries)) } entries = db.List("/webapp", 0) if len(entries) != 2 { t.Fatalf("Expect 2 entries for / got %d", len(entries)) } } func TestAddSelfAsChild(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) child, err := db.Set("/test", "1") if err != nil { t.Fatal(err) } if _, err := db.Set("/test/other", child.ID()); err == nil { t.Fatal("Error should not be nil") } } func TestAddChildToNonExistantRoot(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) if _, err := db.Set("/myapp", "1"); err != nil { t.Fatal(err) } if _, err := db.Set("/myapp/proxy/db", "2"); err == nil { t.Fatal("Error should not be nil") } } func TestWalkAll(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) _, err := db.Set("/webapp", "1") if err != nil { t.Fatal(err) } child2, err := db.Set("/db", "2") if err != nil { t.Fatal(err) } child4, err := db.Set("/db/logs", "4") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/logs", child4.ID()); err != nil { t.Fatal(err) } child3, err := db.Set("/sentry", "3") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/sentry", child3.ID()); err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/db", child2.ID()); err != nil { t.Fatal(err) } child5, err := db.Set("/gograph", "5") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/same-ref-diff-name", child5.ID()); err != nil { t.Fatal(err) } if err := db.Walk("/", func(p string, e *Entity) error { t.Logf("Path: %s Entity: %s", p, e.ID()) return nil }, -1); err != nil { t.Fatal(err) } } func TestGetEntityByPath(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) _, err := db.Set("/webapp", "1") if err != nil { t.Fatal(err) } child2, err := db.Set("/db", "2") if err != nil { t.Fatal(err) } child4, err := db.Set("/logs", "4") if err != nil { t.Fatal(err) } if _, err := db.Set("/db/logs", child4.ID()); err != nil { t.Fatal(err) } child3, err := db.Set("/sentry", "3") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/sentry", child3.ID()); err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/db", child2.ID()); err != nil { t.Fatal(err) } child5, err := db.Set("/gograph", "5") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/same-ref-diff-name", child5.ID()); err != nil { t.Fatal(err) } entity := db.Get("/webapp/db/logs") if entity == nil { t.Fatal("Entity should not be nil") } if entity.ID() != "4" { t.Fatalf("Expected to get entity with id 4, got %s", entity.ID()) } } func TestEnitiesPaths(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) _, err := db.Set("/webapp", "1") if err != nil { t.Fatal(err) } child2, err := db.Set("/db", "2") if err != nil { t.Fatal(err) } child4, err := db.Set("/logs", "4") if err != nil { t.Fatal(err) } if _, err := db.Set("/db/logs", child4.ID()); err != nil { t.Fatal(err) } child3, err := db.Set("/sentry", "3") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/sentry", child3.ID()); err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/db", child2.ID()); err != nil { t.Fatal(err) } child5, err := db.Set("/gograph", "5") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/same-ref-diff-name", child5.ID()); err != nil { t.Fatal(err) } out := db.List("/", -1) for _, p := range out.Paths() { t.Log(p) } } func TestDeleteRootEntity(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) if err := db.Delete("/"); err == nil { t.Fatal("Error should not be nil") } } func TestDeleteEntity(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) _, err := db.Set("/webapp", "1") if err != nil { t.Fatal(err) } child2, err := db.Set("/db", "2") if err != nil { t.Fatal(err) } child4, err := db.Set("/logs", "4") if err != nil { t.Fatal(err) } if _, err := db.Set("/db/logs", child4.ID()); err != nil { t.Fatal(err) } child3, err := db.Set("/sentry", "3") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/sentry", child3.ID()); err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/db", child2.ID()); err != nil { t.Fatal(err) } child5, err := db.Set("/gograph", "5") if err != nil { t.Fatal(err) } if _, err := db.Set("/webapp/same-ref-diff-name", child5.ID()); err != nil { t.Fatal(err) } if err := db.Delete("/webapp/sentry"); err != nil { t.Fatal(err) } entity := db.Get("/webapp/sentry") if entity != nil { t.Fatal("Entity /webapp/sentry should be nil") } } func TestCountRefs(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/webapp", "1") if db.Refs("1") != 1 { t.Fatal("Expect reference count to be 1") } db.Set("/db", "2") db.Set("/webapp/db", "2") if db.Refs("2") != 2 { t.Fatal("Expect reference count to be 2") } } func TestPurgeId(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/webapp", "1") if c := db.Refs("1"); c != 1 { t.Fatalf("Expect reference count to be 1, got %d", c) } db.Set("/db", "2") db.Set("/webapp/db", "2") count, err := db.Purge("2") if err != nil { t.Fatal(err) } if count != 2 { t.Fatalf("Expected 2 references to be removed, got %d", count) } } // Regression test https://github.com/docker/docker/issues/12334 func TestPurgeIdRefPaths(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/webapp", "1") db.Set("/db", "2") db.Set("/db/webapp", "1") if c := db.Refs("1"); c != 2 { t.Fatalf("Expected 2 reference for webapp, got %d", c) } if c := db.Refs("2"); c != 1 { t.Fatalf("Expected 1 reference for db, got %d", c) } if rp := db.RefPaths("2"); len(rp) != 1 { t.Fatalf("Expected 1 reference path for db, got %d", len(rp)) } count, err := db.Purge("2") if err != nil { t.Fatal(err) } if count != 2 { t.Fatalf("Expected 2 rows to be removed, got %d", count) } if c := db.Refs("2"); c != 0 { t.Fatalf("Expected 0 reference for db, got %d", c) } if c := db.Refs("1"); c != 1 { t.Fatalf("Expected 1 reference for webapp, got %d", c) } } func TestRename(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/webapp", "1") if db.Refs("1") != 1 { t.Fatal("Expect reference count to be 1") } db.Set("/db", "2") db.Set("/webapp/db", "2") if db.Get("/webapp/db") == nil { t.Fatal("Cannot find entity at path /webapp/db") } if err := db.Rename("/webapp/db", "/webapp/newdb"); err != nil { t.Fatal(err) } if db.Get("/webapp/db") != nil { t.Fatal("Entity should not exist at /webapp/db") } if db.Get("/webapp/newdb") == nil { t.Fatal("Cannot find entity at path /webapp/newdb") } } func TestCreateMultipleNames(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/db", "1") if _, err := db.Set("/myapp", "1"); err != nil { t.Fatal(err) } db.Walk("/", func(p string, e *Entity) error { t.Logf("%s\n", p) return nil }, -1) } func TestRefPaths(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/webapp", "1") db.Set("/db", "2") db.Set("/webapp/db", "2") refs := db.RefPaths("2") if len(refs) != 2 { t.Fatalf("Expected reference count to be 2, got %d", len(refs)) } } func TestExistsTrue(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/testing", "1") if !db.Exists("/testing") { t.Fatalf("/tesing should exist") } } func TestExistsFalse(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/toerhe", "1") if db.Exists("/testing") { t.Fatalf("/tesing should not exist") } } func TestGetNameWithTrailingSlash(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) db.Set("/todo", "1") e := db.Get("/todo/") if e == nil { t.Fatalf("Entity should not be nil") } } func TestConcurrentWrites(t *testing.T) { db, dbpath := newTestDb(t) defer destroyTestDb(dbpath) errs := make(chan error, 2) save := func(name string, id string) { if _, err := db.Set(fmt.Sprintf("/%s", name), id); err != nil { errs <- err } errs <- nil } purge := func(id string) { if _, err := db.Purge(id); err != nil { errs <- err } errs <- nil } save("/1", "1") go purge("1") go save("/2", "2") any := false for i := 0; i < 2; i++ { if err := <-errs; err != nil { any = true t.Log(err) } } if any { t.Fail() } } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/sort.go ================================================ package graphdb import "sort" type pathSorter struct { paths []string by func(i, j string) bool } func sortByDepth(paths []string) { s := &pathSorter{paths, func(i, j string) bool { return PathDepth(i) > PathDepth(j) }} sort.Sort(s) } func (s *pathSorter) Len() int { return len(s.paths) } func (s *pathSorter) Swap(i, j int) { s.paths[i], s.paths[j] = s.paths[j], s.paths[i] } func (s *pathSorter) Less(i, j int) bool { return s.by(s.paths[i], s.paths[j]) } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/sort_test.go ================================================ package graphdb import ( "testing" ) func TestSort(t *testing.T) { paths := []string{ "/", "/myreallylongname", "/app/db", } sortByDepth(paths) if len(paths) != 3 { t.Fatalf("Expected 3 parts got %d", len(paths)) } if paths[0] != "/app/db" { t.Fatalf("Expected /app/db got %s", paths[0]) } if paths[1] != "/myreallylongname" { t.Fatalf("Expected /myreallylongname got %s", paths[1]) } if paths[2] != "/" { t.Fatalf("Expected / got %s", paths[2]) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/graphdb/utils.go ================================================ package graphdb import ( "path" "strings" ) // Split p on / func split(p string) []string { return strings.Split(p, "/") } // PathDepth returns the depth or number of / in a given path func PathDepth(p string) int { parts := split(p) if len(parts) == 2 && parts[1] == "" { return 1 } return len(parts) } func splitPath(p string) (parent, name string) { if p[0] != '/' { p = "/" + p } parent, name = path.Split(p) l := len(parent) if parent[l-1] == '/' { parent = parent[:l-1] } return } ================================================ FILE: vendor/github.com/docker/docker/pkg/homedir/homedir.go ================================================ package homedir import ( "os" "runtime" "github.com/opencontainers/runc/libcontainer/user" ) // Key returns the env var name for the user's home dir based on // the platform being run on func Key() string { if runtime.GOOS == "windows" { return "USERPROFILE" } return "HOME" } // Get returns the home directory of the current user with the help of // environment variables depending on the target operating system. // Returned path should be used with "path/filepath" to form new paths. func Get() string { home := os.Getenv(Key()) if home == "" && runtime.GOOS != "windows" { if u, err := user.CurrentUser(); err == nil { return u.Home } } return home } // GetShortcutString returns the string that is shortcut to user's home directory // in the native shell of the platform running on. func GetShortcutString() string { if runtime.GOOS == "windows" { return "%USERPROFILE%" // be careful while using in format functions } return "~" } ================================================ FILE: vendor/github.com/docker/docker/pkg/homedir/homedir_test.go ================================================ package homedir import ( "path/filepath" "testing" ) func TestGet(t *testing.T) { home := Get() if home == "" { t.Fatal("returned home directory is empty") } if !filepath.IsAbs(home) { t.Fatalf("returned path is not absolute: %s", home) } } func TestGetShortcutString(t *testing.T) { shortcut := GetShortcutString() if shortcut == "" { t.Fatal("returned shortcut string is empty") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/httputils/httputils.go ================================================ package httputils import ( "errors" "fmt" "net/http" "regexp" "strings" "github.com/docker/docker/pkg/jsonmessage" ) // Download requests a given URL and returns an io.Reader func Download(url string) (resp *http.Response, err error) { if resp, err = http.Get(url); err != nil { return nil, err } if resp.StatusCode >= 400 { return nil, fmt.Errorf("Got HTTP status code >= 400: %s", resp.Status) } return resp, nil } // NewHTTPRequestError returns a JSON response error func NewHTTPRequestError(msg string, res *http.Response) error { return &jsonmessage.JSONError{ Message: msg, Code: res.StatusCode, } } type ServerHeader struct { App string // docker Ver string // 1.8.0-dev OS string // windows or linux } // parseServerHeader extracts pieces from am HTTP server header // which is in the format "docker/version (os)" eg docker/1.8.0-dev (windows) func ParseServerHeader(hdr string) (*ServerHeader, error) { re := regexp.MustCompile(`.*\((.+)\).*$`) r := &ServerHeader{} if matches := re.FindStringSubmatch(hdr); matches != nil { r.OS = matches[1] parts := strings.Split(hdr, "/") if len(parts) != 2 { return nil, errors.New("Bad header: '/' missing") } r.App = parts[0] v := strings.Split(parts[1], " ") if len(v) != 2 { return nil, errors.New("Bad header: Expected single space") } r.Ver = v[0] return r, nil } return nil, errors.New("Bad header: Failed regex match") } ================================================ FILE: vendor/github.com/docker/docker/pkg/httputils/mimetype.go ================================================ package httputils import ( "mime" "net/http" ) var MimeTypes = struct { TextPlain string Tar string OctetStream string }{"text/plain", "application/tar", "application/octet-stream"} // DetectContentType returns a best guess representation of the MIME // content type for the bytes at c. The value detected by // http.DetectContentType is guaranteed not be nil, defaulting to // application/octet-stream when a better guess cannot be made. The // result of this detection is then run through mime.ParseMediaType() // which separates the actual MIME string from any parameters. func DetectContentType(c []byte) (string, map[string]string, error) { ct := http.DetectContentType(c) contentType, args, err := mime.ParseMediaType(ct) if err != nil { return "", nil, err } return contentType, args, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/httputils/resumablerequestreader.go ================================================ package httputils import ( "fmt" "io" "net/http" "time" "github.com/Sirupsen/logrus" ) type resumableRequestReader struct { client *http.Client request *http.Request lastRange int64 totalSize int64 currentResponse *http.Response failures uint32 maxFailures uint32 } // ResumableRequestReader makes it possible to resume reading a request's body transparently // maxfail is the number of times we retry to make requests again (not resumes) // totalsize is the total length of the body; auto detect if not provided func ResumableRequestReader(c *http.Client, r *http.Request, maxfail uint32, totalsize int64) io.ReadCloser { return &resumableRequestReader{client: c, request: r, maxFailures: maxfail, totalSize: totalsize} } // ResumableRequestReaderWithInitialResponse makes it possible to resume // reading the body of an already initiated request. func ResumableRequestReaderWithInitialResponse(c *http.Client, r *http.Request, maxfail uint32, totalsize int64, initialResponse *http.Response) io.ReadCloser { return &resumableRequestReader{client: c, request: r, maxFailures: maxfail, totalSize: totalsize, currentResponse: initialResponse} } func (r *resumableRequestReader) Read(p []byte) (n int, err error) { if r.client == nil || r.request == nil { return 0, fmt.Errorf("client and request can't be nil\n") } isFreshRequest := false if r.lastRange != 0 && r.currentResponse == nil { readRange := fmt.Sprintf("bytes=%d-%d", r.lastRange, r.totalSize) r.request.Header.Set("Range", readRange) time.Sleep(5 * time.Second) } if r.currentResponse == nil { r.currentResponse, err = r.client.Do(r.request) isFreshRequest = true } if err != nil && r.failures+1 != r.maxFailures { r.cleanUpResponse() r.failures++ time.Sleep(5 * time.Duration(r.failures) * time.Second) return 0, nil } else if err != nil { r.cleanUpResponse() return 0, err } if r.currentResponse.StatusCode == 416 && r.lastRange == r.totalSize && r.currentResponse.ContentLength == 0 { r.cleanUpResponse() return 0, io.EOF } else if r.currentResponse.StatusCode != 206 && r.lastRange != 0 && isFreshRequest { r.cleanUpResponse() return 0, fmt.Errorf("the server doesn't support byte ranges") } if r.totalSize == 0 { r.totalSize = r.currentResponse.ContentLength } else if r.totalSize <= 0 { r.cleanUpResponse() return 0, fmt.Errorf("failed to auto detect content length") } n, err = r.currentResponse.Body.Read(p) r.lastRange += int64(n) if err != nil { r.cleanUpResponse() } if err != nil && err != io.EOF { logrus.Infof("encountered error during pull and clearing it before resume: %s", err) err = nil } return n, err } func (r *resumableRequestReader) Close() error { r.cleanUpResponse() r.client = nil r.request = nil return nil } func (r *resumableRequestReader) cleanUpResponse() { if r.currentResponse != nil { r.currentResponse.Body.Close() r.currentResponse = nil } } ================================================ FILE: vendor/github.com/docker/docker/pkg/httputils/resumablerequestreader_test.go ================================================ package httputils import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" ) func TestResumableRequestReader(t *testing.T) { srvtxt := "some response text data" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, srvtxt) })) defer ts.Close() var req *http.Request req, err := http.NewRequest("GET", ts.URL, nil) if err != nil { t.Fatal(err) } client := &http.Client{} retries := uint32(5) imgSize := int64(len(srvtxt)) resreq := ResumableRequestReader(client, req, retries, imgSize) defer resreq.Close() data, err := ioutil.ReadAll(resreq) if err != nil { t.Fatal(err) } resstr := strings.TrimSuffix(string(data), "\n") if resstr != srvtxt { t.Errorf("resstr != srvtxt") } } func TestResumableRequestReaderWithInitialResponse(t *testing.T) { srvtxt := "some response text data" ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, srvtxt) })) defer ts.Close() var req *http.Request req, err := http.NewRequest("GET", ts.URL, nil) if err != nil { t.Fatal(err) } client := &http.Client{} retries := uint32(5) imgSize := int64(len(srvtxt)) res, err := client.Do(req) if err != nil { t.Fatal(err) } resreq := ResumableRequestReaderWithInitialResponse(client, req, retries, imgSize, res) defer resreq.Close() data, err := ioutil.ReadAll(resreq) if err != nil { t.Fatal(err) } resstr := strings.TrimSuffix(string(data), "\n") if resstr != srvtxt { t.Errorf("resstr != srvtxt") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/fmt.go ================================================ package ioutils import ( "fmt" "io" ) // FprintfIfNotEmpty prints the string value if it's not empty func FprintfIfNotEmpty(w io.Writer, format, value string) (int, error) { if value != "" { return fmt.Fprintf(w, format, value) } return 0, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/fmt_test.go ================================================ package ioutils import "testing" func TestFprintfIfNotEmpty(t *testing.T) { wc := NewWriteCounter(&NopWriter{}) n, _ := FprintfIfNotEmpty(wc, "foo%s", "") if wc.Count != 0 || n != 0 { t.Errorf("Wrong count: %v vs. %v vs. 0", wc.Count, n) } n, _ = FprintfIfNotEmpty(wc, "foo%s", "bar") if wc.Count != 6 || n != 6 { t.Errorf("Wrong count: %v vs. %v vs. 6", wc.Count, n) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/readers.go ================================================ package ioutils import ( "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" "io" "math/big" "sync" "time" ) type readCloserWrapper struct { io.Reader closer func() error } func (r *readCloserWrapper) Close() error { return r.closer() } func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { return &readCloserWrapper{ Reader: r, closer: closer, } } type readerErrWrapper struct { reader io.Reader closer func() } func (r *readerErrWrapper) Read(p []byte) (int, error) { n, err := r.reader.Read(p) if err != nil { r.closer() } return n, err } func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { return &readerErrWrapper{ reader: r, closer: closer, } } // bufReader allows the underlying reader to continue to produce // output by pre-emptively reading from the wrapped reader. // This is achieved by buffering this data in bufReader's // expanding buffer. type bufReader struct { sync.Mutex buf *bytes.Buffer reader io.Reader err error wait sync.Cond drainBuf []byte reuseBuf []byte maxReuse int64 resetTimeout time.Duration bufLenResetThreshold int64 maxReadDataReset int64 } func NewBufReader(r io.Reader) *bufReader { var timeout int if randVal, err := rand.Int(rand.Reader, big.NewInt(120)); err == nil { timeout = int(randVal.Int64()) + 180 } else { timeout = 300 } reader := &bufReader{ buf: &bytes.Buffer{}, drainBuf: make([]byte, 1024), reuseBuf: make([]byte, 4096), maxReuse: 1000, resetTimeout: time.Second * time.Duration(timeout), bufLenResetThreshold: 100 * 1024, maxReadDataReset: 10 * 1024 * 1024, reader: r, } reader.wait.L = &reader.Mutex go reader.drain() return reader } func NewBufReaderWithDrainbufAndBuffer(r io.Reader, drainBuffer []byte, buffer *bytes.Buffer) *bufReader { reader := &bufReader{ buf: buffer, drainBuf: drainBuffer, reader: r, } reader.wait.L = &reader.Mutex go reader.drain() return reader } func (r *bufReader) drain() { var ( duration time.Duration lastReset time.Time now time.Time reset bool bufLen int64 dataSinceReset int64 maxBufLen int64 reuseBufLen int64 reuseCount int64 ) reuseBufLen = int64(len(r.reuseBuf)) lastReset = time.Now() for { n, err := r.reader.Read(r.drainBuf) dataSinceReset += int64(n) r.Lock() bufLen = int64(r.buf.Len()) if bufLen > maxBufLen { maxBufLen = bufLen } // Avoid unbounded growth of the buffer over time. // This has been discovered to be the only non-intrusive // solution to the unbounded growth of the buffer. // Alternative solutions such as compression, multiple // buffers, channels and other similar pieces of code // were reducing throughput, overall Docker performance // or simply crashed Docker. // This solution releases the buffer when specific // conditions are met to avoid the continuous resizing // of the buffer for long lived containers. // // Move data to the front of the buffer if it's // smaller than what reuseBuf can store if bufLen > 0 && reuseBufLen >= bufLen { n, _ := r.buf.Read(r.reuseBuf) r.buf.Write(r.reuseBuf[0:n]) // Take action if the buffer has been reused too many // times and if there's data in the buffer. // The timeout is also used as means to avoid doing // these operations more often or less often than // required. // The various conditions try to detect heavy activity // in the buffer which might be indicators of heavy // growth of the buffer. } else if reuseCount >= r.maxReuse && bufLen > 0 { now = time.Now() duration = now.Sub(lastReset) timeoutReached := duration >= r.resetTimeout // The timeout has been reached and the // buffered data couldn't be moved to the front // of the buffer, so the buffer gets reset. if timeoutReached && bufLen > reuseBufLen { reset = true } // The amount of buffered data is too high now, // reset the buffer. if timeoutReached && maxBufLen >= r.bufLenResetThreshold { reset = true } // Reset the buffer if a certain amount of // data has gone through the buffer since the // last reset. if timeoutReached && dataSinceReset >= r.maxReadDataReset { reset = true } // The buffered data is moved to a fresh buffer, // swap the old buffer with the new one and // reset all counters. if reset { newbuf := &bytes.Buffer{} newbuf.ReadFrom(r.buf) r.buf = newbuf lastReset = now reset = false dataSinceReset = 0 maxBufLen = 0 reuseCount = 0 } } if err != nil { r.err = err } else { r.buf.Write(r.drainBuf[0:n]) } reuseCount++ r.wait.Signal() r.Unlock() callSchedulerIfNecessary() if err != nil { break } } } func (r *bufReader) Read(p []byte) (n int, err error) { r.Lock() defer r.Unlock() for { n, err = r.buf.Read(p) if n > 0 { return n, err } if r.err != nil { return 0, r.err } r.wait.Wait() } } func (r *bufReader) Close() error { closer, ok := r.reader.(io.ReadCloser) if !ok { return nil } return closer.Close() } func HashData(src io.Reader) (string, error) { h := sha256.New() if _, err := io.Copy(h, src); err != nil { return "", err } return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil } 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 } } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/readers_test.go ================================================ package ioutils import ( "bytes" "fmt" "io" "io/ioutil" "strings" "testing" ) // Implement io.Reader type errorReader struct{} func (r *errorReader) Read(p []byte) (int, error) { return 0, fmt.Errorf("Error reader always fail.") } func TestReadCloserWrapperClose(t *testing.T) { reader := strings.NewReader("A string reader") wrapper := NewReadCloserWrapper(reader, func() error { return fmt.Errorf("This will be called when closing") }) err := wrapper.Close() if err == nil || !strings.Contains(err.Error(), "This will be called when closing") { t.Fatalf("readCloserWrapper should have call the anonymous func and thus, fail.") } } func TestReaderErrWrapperReadOnError(t *testing.T) { called := false reader := &errorReader{} wrapper := NewReaderErrWrapper(reader, func() { called = true }) _, err := wrapper.Read([]byte{}) if err == nil || !strings.Contains(err.Error(), "Error reader always fail.") { t.Fatalf("readErrWrapper should returned an error") } if !called { t.Fatalf("readErrWrapper should have call the anonymous function on failure") } } func TestReaderErrWrapperRead(t *testing.T) { reader := strings.NewReader("a string reader.") wrapper := NewReaderErrWrapper(reader, func() { t.Fatalf("readErrWrapper should not have called the anonymous function") }) // Read 20 byte (should be ok with the string above) num, err := wrapper.Read(make([]byte, 20)) if err != nil { t.Fatal(err) } if num != 16 { t.Fatalf("readerErrWrapper should have read 16 byte, but read %d", num) } } func TestNewBufReaderWithDrainbufAndBuffer(t *testing.T) { reader, writer := io.Pipe() drainBuffer := make([]byte, 1024) buffer := bytes.Buffer{} bufreader := NewBufReaderWithDrainbufAndBuffer(reader, drainBuffer, &buffer) // Write everything down to a Pipe // Usually, a pipe should block but because of the buffered reader, // the writes will go through done := make(chan bool) go func() { writer.Write([]byte("hello world")) writer.Close() done <- true }() // Drain the reader *after* everything has been written, just to verify // it is indeed buffering <-done output, err := ioutil.ReadAll(bufreader) if err != nil { t.Fatal(err) } if !bytes.Equal(output, []byte("hello world")) { t.Error(string(output)) } } func TestBufReader(t *testing.T) { reader, writer := io.Pipe() bufreader := NewBufReader(reader) // Write everything down to a Pipe // Usually, a pipe should block but because of the buffered reader, // the writes will go through done := make(chan bool) go func() { writer.Write([]byte("hello world")) writer.Close() done <- true }() // Drain the reader *after* everything has been written, just to verify // it is indeed buffering <-done output, err := ioutil.ReadAll(bufreader) if err != nil { t.Fatal(err) } if !bytes.Equal(output, []byte("hello world")) { t.Error(string(output)) } } func TestBufReaderCloseWithNonReaderCloser(t *testing.T) { reader := strings.NewReader("buffer") bufreader := NewBufReader(reader) if err := bufreader.Close(); err != nil { t.Fatal(err) } } // implements io.ReadCloser type simpleReaderCloser struct{} func (r *simpleReaderCloser) Read(p []byte) (n int, err error) { return 0, nil } func (r *simpleReaderCloser) Close() error { return nil } func TestBufReaderCloseWithReaderCloser(t *testing.T) { reader := &simpleReaderCloser{} bufreader := NewBufReader(reader) err := bufreader.Close() if err != nil { t.Fatal(err) } } func TestHashData(t *testing.T) { reader := strings.NewReader("hash-me") actual, err := HashData(reader) if err != nil { t.Fatal(err) } expected := "sha256:4d11186aed035cc624d553e10db358492c84a7cd6b9670d92123c144930450aa" if actual != expected { t.Fatalf("Expecting %s, got %s", expected, actual) } } type repeatedReader struct { readCount int maxReads int data []byte } func newRepeatedReader(max int, data []byte) *repeatedReader { return &repeatedReader{0, max, data} } func (r *repeatedReader) Read(p []byte) (int, error) { if r.readCount >= r.maxReads { return 0, io.EOF } r.readCount++ n := copy(p, r.data) return n, nil } func testWithData(data []byte, reads int) { reader := newRepeatedReader(reads, data) bufReader := NewBufReader(reader) io.Copy(ioutil.Discard, bufReader) } func Benchmark1M10BytesReads(b *testing.B) { reads := 1000000 readSize := int64(10) data := make([]byte, readSize) b.SetBytes(readSize * int64(reads)) b.ResetTimer() for i := 0; i < b.N; i++ { testWithData(data, reads) } } func Benchmark1M1024BytesReads(b *testing.B) { reads := 1000000 readSize := int64(1024) data := make([]byte, readSize) b.SetBytes(readSize * int64(reads)) b.ResetTimer() for i := 0; i < b.N; i++ { testWithData(data, reads) } } func Benchmark10k32KBytesReads(b *testing.B) { reads := 10000 readSize := int64(32 * 1024) data := make([]byte, readSize) b.SetBytes(readSize * int64(reads)) b.ResetTimer() for i := 0; i < b.N; i++ { testWithData(data, reads) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/scheduler.go ================================================ // +build !gccgo package ioutils func callSchedulerIfNecessary() { } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/scheduler_gccgo.go ================================================ // +build gccgo package ioutils import ( "runtime" ) func callSchedulerIfNecessary() { //allow or force Go scheduler to switch context, without explicitly //forcing this will make it hang when using gccgo implementation runtime.Gosched() } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/writeflusher.go ================================================ package ioutils import ( "io" "net/http" "sync" ) type WriteFlusher struct { sync.Mutex w io.Writer flusher http.Flusher flushed bool } func (wf *WriteFlusher) Write(b []byte) (n int, err error) { wf.Lock() defer wf.Unlock() n, err = wf.w.Write(b) wf.flushed = true wf.flusher.Flush() return n, err } // Flush the stream immediately. func (wf *WriteFlusher) Flush() { wf.Lock() defer wf.Unlock() wf.flushed = true wf.flusher.Flush() } func (wf *WriteFlusher) Flushed() bool { wf.Lock() defer wf.Unlock() return wf.flushed } func NewWriteFlusher(w io.Writer) *WriteFlusher { var flusher http.Flusher if f, ok := w.(http.Flusher); ok { flusher = f } else { flusher = &NopFlusher{} } return &WriteFlusher{w: w, flusher: flusher} } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/writers.go ================================================ package ioutils import "io" type NopWriter struct{} func (*NopWriter) Write(buf []byte) (int, error) { return len(buf), nil } type nopWriteCloser struct { io.Writer } func (w *nopWriteCloser) Close() error { return nil } func NopWriteCloser(w io.Writer) io.WriteCloser { return &nopWriteCloser{w} } type NopFlusher struct{} func (f *NopFlusher) Flush() {} type writeCloserWrapper struct { io.Writer closer func() error } func (r *writeCloserWrapper) Close() error { return r.closer() } func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { return &writeCloserWrapper{ Writer: r, closer: closer, } } // Wrap a concrete io.Writer and hold a count of the number // of bytes written to the writer during a "session". // This can be convenient when write return is masked // (e.g., json.Encoder.Encode()) type WriteCounter struct { Count int64 Writer io.Writer } func NewWriteCounter(w io.Writer) *WriteCounter { return &WriteCounter{ Writer: w, } } func (wc *WriteCounter) Write(p []byte) (count int, err error) { count, err = wc.Writer.Write(p) wc.Count += int64(count) return } ================================================ FILE: vendor/github.com/docker/docker/pkg/ioutils/writers_test.go ================================================ package ioutils import ( "bytes" "strings" "testing" ) func TestWriteCloserWrapperClose(t *testing.T) { called := false writer := bytes.NewBuffer([]byte{}) wrapper := NewWriteCloserWrapper(writer, func() error { called = true return nil }) if err := wrapper.Close(); err != nil { t.Fatal(err) } if !called { t.Fatalf("writeCloserWrapper should have call the anonymous function.") } } func TestNopWriteCloser(t *testing.T) { writer := bytes.NewBuffer([]byte{}) wrapper := NopWriteCloser(writer) if err := wrapper.Close(); err != nil { t.Fatal("NopWriteCloser always return nil on Close.") } } func TestNopWriter(t *testing.T) { nw := &NopWriter{} l, err := nw.Write([]byte{'c'}) if err != nil { t.Fatal(err) } if l != 1 { t.Fatalf("Expected 1 got %d", l) } } func TestWriteCounter(t *testing.T) { dummy1 := "This is a dummy string." dummy2 := "This is another dummy string." totalLength := int64(len(dummy1) + len(dummy2)) reader1 := strings.NewReader(dummy1) reader2 := strings.NewReader(dummy2) var buffer bytes.Buffer wc := NewWriteCounter(&buffer) reader1.WriteTo(wc) reader2.WriteTo(wc) if wc.Count != totalLength { t.Errorf("Wrong count: %d vs. %d", wc.Count, totalLength) } if buffer.String() != dummy1+dummy2 { t.Error("Wrong message written") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonlog/jsonlog.go ================================================ package jsonlog import ( "encoding/json" "fmt" "io" "time" ) type JSONLog struct { Log string `json:"log,omitempty"` Stream string `json:"stream,omitempty"` Created time.Time `json:"time"` } func (jl *JSONLog) Format(format string) (string, error) { if format == "" { return jl.Log, nil } if format == "json" { m, err := json.Marshal(jl) return string(m), err } return fmt.Sprintf("%s %s", jl.Created.Format(format), jl.Log), nil } func (jl *JSONLog) Reset() { jl.Log = "" jl.Stream = "" jl.Created = time.Time{} } func WriteLog(src io.Reader, dst io.Writer, format string, since time.Time) error { dec := json.NewDecoder(src) l := &JSONLog{} for { l.Reset() if err := dec.Decode(l); err != nil { if err == io.EOF { return nil } return err } if !since.IsZero() && l.Created.Before(since) { continue } line, err := l.Format(format) if err != nil { return err } if _, err := io.WriteString(dst, line); err != nil { return err } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling.go ================================================ // This code was initially generated by ffjson // This code was generated via the following steps: // $ go get -u github.com/pquerna/ffjson // $ make BIND_DIR=. shell // $ ffjson pkg/jsonlog/jsonlog.go // $ mv pkg/jsonglog/jsonlog_ffjson.go pkg/jsonlog/jsonlog_marshalling.go // // It has been modified to improve the performance of time marshalling to JSON // and to clean it up. // Should this code need to be regenerated when the JSONLog struct is changed, // the relevant changes which have been made are: // import ( // "bytes" //- // "unicode/utf8" //+ //+ "github.com/docker/docker/pkg/timeutils" // ) // // func (mj *JSONLog) MarshalJSON() ([]byte, error) { //@@ -20,13 +16,13 @@ func (mj *JSONLog) MarshalJSON() ([]byte, error) { // } // return buf.Bytes(), nil // } //+ // func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { //- var err error //- var obj []byte //- var first bool = true //- _ = obj //- _ = err //- _ = first //+ var ( //+ err error //+ timestamp string //+ first bool = true //+ ) // buf.WriteString(`{`) // if len(mj.Log) != 0 { // if first == true { //@@ -52,11 +48,11 @@ func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { // buf.WriteString(`,`) // } // buf.WriteString(`"time":`) //- obj, err = mj.Created.MarshalJSON() //+ timestamp, err = timeutils.FastMarshalJSON(mj.Created) // if err != nil { // return err // } //- buf.Write(obj) //+ buf.WriteString(timestamp) // buf.WriteString(`}`) // return nil // } // @@ -81,9 +81,10 @@ func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { // if len(mj.Log) != 0 { // - if first == true { // - first = false // - } else { // - buf.WriteString(`,`) // - } // + first = false // buf.WriteString(`"log":`) // ffjson_WriteJsonString(buf, mj.Log) // } package jsonlog import ( "bytes" "unicode/utf8" "github.com/docker/docker/pkg/timeutils" ) func (mj *JSONLog) MarshalJSON() ([]byte, error) { var buf bytes.Buffer buf.Grow(1024) if err := mj.MarshalJSONBuf(&buf); err != nil { return nil, err } return buf.Bytes(), nil } func (mj *JSONLog) MarshalJSONBuf(buf *bytes.Buffer) error { var ( err error timestamp string first bool = true ) buf.WriteString(`{`) if len(mj.Log) != 0 { first = false buf.WriteString(`"log":`) ffjson_WriteJsonString(buf, mj.Log) } if len(mj.Stream) != 0 { if first == true { first = false } else { buf.WriteString(`,`) } buf.WriteString(`"stream":`) ffjson_WriteJsonString(buf, mj.Stream) } if first == true { first = false } else { buf.WriteString(`,`) } buf.WriteString(`"time":`) timestamp, err = timeutils.FastMarshalJSON(mj.Created) if err != nil { return err } buf.WriteString(timestamp) buf.WriteString(`}`) return nil } func ffjson_WriteJsonString(buf *bytes.Buffer, s string) { const hex = "0123456789abcdef" buf.WriteByte('"') 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 { buf.WriteString(s[start:i]) } switch b { case '\\', '"': buf.WriteByte('\\') buf.WriteByte(b) case '\n': buf.WriteByte('\\') buf.WriteByte('n') case '\r': buf.WriteByte('\\') buf.WriteByte('r') default: buf.WriteString(`\u00`) buf.WriteByte(hex[b>>4]) buf.WriteByte(hex[b&0xF]) } i++ start = i continue } c, size := utf8.DecodeRuneInString(s[i:]) if c == utf8.RuneError && size == 1 { if start < i { buf.WriteString(s[start:i]) } buf.WriteString(`\ufffd`) i += size start = i continue } if c == '\u2028' || c == '\u2029' { if start < i { buf.WriteString(s[start:i]) } buf.WriteString(`\u202`) buf.WriteByte(hex[c&0xF]) i += size start = i continue } i += size } if start < len(s) { buf.WriteString(s[start:]) } buf.WriteByte('"') } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_marshalling_test.go ================================================ package jsonlog import ( "regexp" "testing" ) func TestJSONLogMarshalJSON(t *testing.T) { logs := map[JSONLog]string{ JSONLog{Log: `"A log line with \\"`}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":\".{20,}\"}$`, JSONLog{Log: "A log line"}: `^{\"log\":\"A log line\",\"time\":\".{20,}\"}$`, JSONLog{Log: "A log line with \r"}: `^{\"log\":\"A log line with \\r\",\"time\":\".{20,}\"}$`, JSONLog{Log: "A log line with & < >"}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":\".{20,}\"}$`, JSONLog{Log: "A log line with utf8 : 🚀 ψ ω β"}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":\".{20,}\"}$`, JSONLog{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":\".{20,}\"}$`, JSONLog{}: `^{\"time\":\".{20,}\"}$`, // These ones are a little weird JSONLog{Log: "\u2028 \u2029"}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":\".{20,}\"}$`, JSONLog{Log: string([]byte{0xaF})}: `^{\"log\":\"\\ufffd\",\"time\":\".{20,}\"}$`, JSONLog{Log: string([]byte{0x7F})}: `^{\"log\":\"\x7f\",\"time\":\".{20,}\"}$`, } for jsonLog, expression := range logs { data, err := jsonLog.MarshalJSON() if err != nil { t.Fatal(err) } res := string(data) t.Logf("Result of WriteLog: %q", res) logRe := regexp.MustCompile(expression) if !logRe.MatchString(res) { t.Fatalf("Log line not in expected format [%v]: %q", expression, res) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonlog/jsonlog_test.go ================================================ package jsonlog import ( "bytes" "encoding/json" "io/ioutil" "regexp" "strconv" "strings" "testing" "time" "github.com/docker/docker/pkg/timeutils" ) // Invalid json should return an error func TestWriteLogWithInvalidJSON(t *testing.T) { json := strings.NewReader("Invalid json") w := bytes.NewBuffer(nil) if err := WriteLog(json, w, "json", time.Time{}); err == nil { t.Fatalf("Expected an error, got [%v]", w.String()) } } // Any format is valid, it will just print it func TestWriteLogWithInvalidFormat(t *testing.T) { testLine := "Line that thinks that it is log line from docker\n" var buf bytes.Buffer e := json.NewEncoder(&buf) for i := 0; i < 35; i++ { e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()}) } w := bytes.NewBuffer(nil) if err := WriteLog(&buf, w, "invalid format", time.Time{}); err != nil { t.Fatal(err) } res := w.String() t.Logf("Result of WriteLog: %q", res) lines := strings.Split(strings.TrimSpace(res), "\n") expression := "^invalid format Line that thinks that it is log line from docker$" logRe := regexp.MustCompile(expression) expectedLines := 35 if len(lines) != expectedLines { t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines)) } for _, l := range lines { if !logRe.MatchString(l) { t.Fatalf("Log line not in expected format [%v]: %q", expression, l) } } } // Having multiple Log/Stream element func TestWriteLogWithMultipleStreamLog(t *testing.T) { testLine := "Line that thinks that it is log line from docker\n" var buf bytes.Buffer e := json.NewEncoder(&buf) for i := 0; i < 35; i++ { e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()}) } w := bytes.NewBuffer(nil) if err := WriteLog(&buf, w, "invalid format", time.Time{}); err != nil { t.Fatal(err) } res := w.String() t.Logf("Result of WriteLog: %q", res) lines := strings.Split(strings.TrimSpace(res), "\n") expression := "^invalid format Line that thinks that it is log line from docker$" logRe := regexp.MustCompile(expression) expectedLines := 35 if len(lines) != expectedLines { t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines)) } for _, l := range lines { if !logRe.MatchString(l) { t.Fatalf("Log line not in expected format [%v]: %q", expression, l) } } } // Write log with since after created, it won't print anything func TestWriteLogWithDate(t *testing.T) { created, _ := time.Parse("YYYY-MM-dd", "2015-01-01") var buf bytes.Buffer testLine := "Line that thinks that it is log line from docker\n" jsonLog := JSONLog{Log: testLine, Stream: "stdout", Created: created} if err := json.NewEncoder(&buf).Encode(jsonLog); err != nil { t.Fatal(err) } w := bytes.NewBuffer(nil) if err := WriteLog(&buf, w, "json", time.Now()); err != nil { t.Fatal(err) } res := w.String() if res != "" { t.Fatalf("Expected empty log, got [%v]", res) } } // Happy path :) func TestWriteLog(t *testing.T) { testLine := "Line that thinks that it is log line from docker\n" format := timeutils.RFC3339NanoFixed logs := map[string][]string{ "": {"35", "^Line that thinks that it is log line from docker$"}, "json": {"1", `^{\"log\":\"Line that thinks that it is log line from docker\\n\",\"stream\":\"stdout\",\"time\":.{30,}\"}$`}, // 30+ symbols, five more can come from system timezone format: {"35", `.{30,} Line that thinks that it is log line from docker`}, } for givenFormat, expressionAndLines := range logs { expectedLines, _ := strconv.Atoi(expressionAndLines[0]) expression := expressionAndLines[1] var buf bytes.Buffer e := json.NewEncoder(&buf) for i := 0; i < 35; i++ { e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()}) } w := bytes.NewBuffer(nil) if err := WriteLog(&buf, w, givenFormat, time.Time{}); err != nil { t.Fatal(err) } res := w.String() t.Logf("Result of WriteLog: %q", res) lines := strings.Split(strings.TrimSpace(res), "\n") if len(lines) != expectedLines { t.Fatalf("Must be %v lines but got %d", expectedLines, len(lines)) } logRe := regexp.MustCompile(expression) for _, l := range lines { if !logRe.MatchString(l) { t.Fatalf("Log line not in expected format [%v]: %q", expression, l) } } } } func BenchmarkWriteLog(b *testing.B) { var buf bytes.Buffer e := json.NewEncoder(&buf) testLine := "Line that thinks that it is log line from docker\n" for i := 0; i < 30; i++ { e.Encode(JSONLog{Log: testLine, Stream: "stdout", Created: time.Now()}) } r := bytes.NewReader(buf.Bytes()) w := ioutil.Discard format := timeutils.RFC3339NanoFixed b.SetBytes(int64(r.Len())) b.ResetTimer() for i := 0; i < b.N; i++ { if err := WriteLog(r, w, format, time.Time{}); err != nil { b.Fatal(err) } b.StopTimer() r.Seek(0, 0) b.StartTimer() } } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes.go ================================================ package jsonlog import ( "bytes" "unicode/utf8" ) // JSONLogBytes is based on JSONLog. // It allows marshalling JSONLog from Log as []byte // and an already marshalled Created timestamp. type JSONLogBytes struct { Log []byte `json:"log,omitempty"` Stream string `json:"stream,omitempty"` Created string `json:"time"` } // MarshalJSONBuf is based on the same method from JSONLog // It has been modified to take into account the necessary changes. func (mj *JSONLogBytes) MarshalJSONBuf(buf *bytes.Buffer) error { var first = true buf.WriteString(`{`) if len(mj.Log) != 0 { first = false buf.WriteString(`"log":`) ffjson_WriteJsonBytesAsString(buf, mj.Log) } if len(mj.Stream) != 0 { if first == true { first = false } else { buf.WriteString(`,`) } buf.WriteString(`"stream":`) ffjson_WriteJsonString(buf, mj.Stream) } if first == true { first = false } else { buf.WriteString(`,`) } buf.WriteString(`"time":`) buf.WriteString(mj.Created) buf.WriteString(`}`) return nil } // This is based on ffjson_WriteJsonString. It has been changed // to accept a string passed as a slice of bytes. func ffjson_WriteJsonBytesAsString(buf *bytes.Buffer, s []byte) { const hex = "0123456789abcdef" buf.WriteByte('"') 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 { buf.Write(s[start:i]) } switch b { case '\\', '"': buf.WriteByte('\\') buf.WriteByte(b) case '\n': buf.WriteByte('\\') buf.WriteByte('n') case '\r': buf.WriteByte('\\') buf.WriteByte('r') default: buf.WriteString(`\u00`) buf.WriteByte(hex[b>>4]) buf.WriteByte(hex[b&0xF]) } i++ start = i continue } c, size := utf8.DecodeRune(s[i:]) if c == utf8.RuneError && size == 1 { if start < i { buf.Write(s[start:i]) } buf.WriteString(`\ufffd`) i += size start = i continue } if c == '\u2028' || c == '\u2029' { if start < i { buf.Write(s[start:i]) } buf.WriteString(`\u202`) buf.WriteByte(hex[c&0xF]) i += size start = i continue } i += size } if start < len(s) { buf.Write(s[start:]) } buf.WriteByte('"') } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonlog/jsonlogbytes_test.go ================================================ package jsonlog import ( "bytes" "regexp" "testing" ) func TestJSONLogBytesMarshalJSONBuf(t *testing.T) { logs := map[*JSONLogBytes]string{ &JSONLogBytes{Log: []byte(`"A log line with \\"`)}: `^{\"log\":\"\\\"A log line with \\\\\\\\\\\"\",\"time\":}$`, &JSONLogBytes{Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"time\":}$`, &JSONLogBytes{Log: []byte("A log line with \r")}: `^{\"log\":\"A log line with \\r\",\"time\":}$`, &JSONLogBytes{Log: []byte("A log line with & < >")}: `^{\"log\":\"A log line with \\u0026 \\u003c \\u003e\",\"time\":}$`, &JSONLogBytes{Log: []byte("A log line with utf8 : 🚀 ψ ω β")}: `^{\"log\":\"A log line with utf8 : 🚀 ψ ω β\",\"time\":}$`, &JSONLogBytes{Stream: "stdout"}: `^{\"stream\":\"stdout\",\"time\":}$`, &JSONLogBytes{Stream: "stdout", Log: []byte("A log line")}: `^{\"log\":\"A log line\",\"stream\":\"stdout\",\"time\":}$`, &JSONLogBytes{Created: "time"}: `^{\"time\":time}$`, &JSONLogBytes{}: `^{\"time\":}$`, // These ones are a little weird &JSONLogBytes{Log: []byte("\u2028 \u2029")}: `^{\"log\":\"\\u2028 \\u2029\",\"time\":}$`, &JSONLogBytes{Log: []byte{0xaF}}: `^{\"log\":\"\\ufffd\",\"time\":}$`, &JSONLogBytes{Log: []byte{0x7F}}: `^{\"log\":\"\x7f\",\"time\":}$`, } for jsonLog, expression := range logs { var buf bytes.Buffer if err := jsonLog.MarshalJSONBuf(&buf); err != nil { t.Fatal(err) } res := buf.String() t.Logf("Result of WriteLog: %q", res) logRe := regexp.MustCompile(expression) if !logRe.MatchString(res) { t.Fatalf("Log line not in expected format [%v]: %q", expression, res) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go ================================================ package jsonmessage import ( "encoding/json" "fmt" "io" "strings" "time" "github.com/docker/docker/pkg/term" "github.com/docker/docker/pkg/timeutils" "github.com/docker/docker/pkg/units" ) type JSONError struct { Code int `json:"code,omitempty"` Message string `json:"message,omitempty"` } func (e *JSONError) Error() string { return e.Message } type JSONProgress struct { terminalFd uintptr Current int `json:"current,omitempty"` Total int `json:"total,omitempty"` Start int64 `json:"start,omitempty"` } func (p *JSONProgress) String() string { var ( width = 200 pbBox string numbersBox string timeLeftBox string ) ws, err := term.GetWinsize(p.terminalFd) if err == nil { width = int(ws.Width) } if p.Current <= 0 && p.Total <= 0 { return "" } current := units.HumanSize(float64(p.Current)) if p.Total <= 0 { return fmt.Sprintf("%8v", current) } total := units.HumanSize(float64(p.Total)) percentage := int(float64(p.Current)/float64(p.Total)*100) / 2 if percentage > 50 { percentage = 50 } if width > 110 { // this number can't be negetive gh#7136 numSpaces := 0 if 50-percentage > 0 { numSpaces = 50 - percentage } pbBox = fmt.Sprintf("[%s>%s] ", strings.Repeat("=", percentage), strings.Repeat(" ", numSpaces)) } numbersBox = fmt.Sprintf("%8v/%v", current, total) if p.Current > 0 && p.Start > 0 && percentage < 50 { fromStart := time.Now().UTC().Sub(time.Unix(int64(p.Start), 0)) perEntry := fromStart / time.Duration(p.Current) left := time.Duration(p.Total-p.Current) * perEntry left = (left / time.Second) * time.Second if width > 50 { timeLeftBox = " " + left.String() } } return pbBox + numbersBox + timeLeftBox } type JSONMessage struct { Stream string `json:"stream,omitempty"` Status string `json:"status,omitempty"` Progress *JSONProgress `json:"progressDetail,omitempty"` ProgressMessage string `json:"progress,omitempty"` //deprecated ID string `json:"id,omitempty"` From string `json:"from,omitempty"` Time int64 `json:"time,omitempty"` Error *JSONError `json:"errorDetail,omitempty"` ErrorMessage string `json:"error,omitempty"` //deprecated } func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { if jm.Error != nil { if jm.Error.Code == 401 { return fmt.Errorf("Authentication is required.") } return jm.Error } var endl string if isTerminal && jm.Stream == "" && jm.Progress != nil { // [2K = erase entire current line fmt.Fprintf(out, "%c[2K\r", 27) endl = "\r" } else if jm.Progress != nil && jm.Progress.String() != "" { //disable progressbar in non-terminal return nil } if jm.Time != 0 { fmt.Fprintf(out, "%s ", time.Unix(jm.Time, 0).Format(timeutils.RFC3339NanoFixed)) } if jm.ID != "" { fmt.Fprintf(out, "%s: ", jm.ID) } if jm.From != "" { fmt.Fprintf(out, "(from %s) ", jm.From) } if jm.Progress != nil && isTerminal { fmt.Fprintf(out, "%s %s%s", jm.Status, jm.Progress.String(), endl) } else if jm.ProgressMessage != "" { //deprecated fmt.Fprintf(out, "%s %s%s", jm.Status, jm.ProgressMessage, endl) } else if jm.Stream != "" { fmt.Fprintf(out, "%s%s", jm.Stream, endl) } else { fmt.Fprintf(out, "%s%s\n", jm.Status, endl) } return nil } func DisplayJSONMessagesStream(in io.Reader, out io.Writer, terminalFd uintptr, isTerminal bool) error { var ( dec = json.NewDecoder(in) ids = make(map[string]int) diff = 0 ) for { var jm JSONMessage if err := dec.Decode(&jm); err != nil { if err == io.EOF { break } return err } if jm.Progress != nil { jm.Progress.terminalFd = terminalFd } if jm.ID != "" && (jm.Progress != nil || jm.ProgressMessage != "") { line, ok := ids[jm.ID] if !ok { line = len(ids) ids[jm.ID] = line if isTerminal { fmt.Fprintf(out, "\n") } diff = 0 } else { diff = len(ids) - line } if jm.ID != "" && isTerminal { // [{diff}A = move cursor up diff rows fmt.Fprintf(out, "%c[%dA", 27, diff) } } err := jm.Display(out, isTerminal) if jm.ID != "" && isTerminal { // [{diff}B = move cursor down diff rows fmt.Fprintf(out, "%c[%dB", 27, diff) } if err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage_test.go ================================================ package jsonmessage import ( "bytes" "fmt" "testing" "time" "github.com/docker/docker/pkg/term" "github.com/docker/docker/pkg/timeutils" "strings" ) func TestError(t *testing.T) { je := JSONError{404, "Not found"} if je.Error() != "Not found" { t.Fatalf("Expected 'Not found' got '%s'", je.Error()) } } func TestProgress(t *testing.T) { jp := JSONProgress{} if jp.String() != "" { t.Fatalf("Expected empty string, got '%s'", jp.String()) } expected := " 1 B" jp2 := JSONProgress{Current: 1} if jp2.String() != expected { t.Fatalf("Expected %q, got %q", expected, jp2.String()) } expectedStart := "[==========> ] 20 B/100 B" jp3 := JSONProgress{Current: 20, Total: 100, Start: time.Now().Unix()} // Just look at the start of the string // (the remaining time is really hard to test -_-) if jp3.String()[:len(expectedStart)] != expectedStart { t.Fatalf("Expected to start with %q, got %q", expectedStart, jp3.String()) } expected = "[=========================> ] 50 B/100 B" jp4 := JSONProgress{Current: 50, Total: 100} if jp4.String() != expected { t.Fatalf("Expected %q, got %q", expected, jp4.String()) } // this number can't be negative gh#7136 expected = "[==================================================>] 50 B/40 B" jp5 := JSONProgress{Current: 50, Total: 40} if jp5.String() != expected { t.Fatalf("Expected %q, got %q", expected, jp5.String()) } } func TestJSONMessageDisplay(t *testing.T) { now := time.Now().Unix() messages := map[JSONMessage][]string{ // Empty JSONMessage{}: {"\n", "\n"}, // Status JSONMessage{ Status: "status", }: { "status\n", "status\n", }, // General JSONMessage{ Time: now, ID: "ID", From: "From", Status: "status", }: { fmt.Sprintf("%v ID: (from From) status\n", time.Unix(now, 0).Format(timeutils.RFC3339NanoFixed)), fmt.Sprintf("%v ID: (from From) status\n", time.Unix(now, 0).Format(timeutils.RFC3339NanoFixed)), }, // Stream over status JSONMessage{ Status: "status", Stream: "stream", }: { "stream", "stream", }, // With progress message JSONMessage{ Status: "status", ProgressMessage: "progressMessage", }: { "status progressMessage", "status progressMessage", }, // With progress, stream empty JSONMessage{ Status: "status", Stream: "", Progress: &JSONProgress{Current: 1}, }: { "", fmt.Sprintf("%c[2K\rstatus 1 B\r", 27), }, } // The tests :) for jsonMessage, expectedMessages := range messages { // Without terminal data := bytes.NewBuffer([]byte{}) if err := jsonMessage.Display(data, false); err != nil { t.Fatal(err) } if data.String() != expectedMessages[0] { t.Fatalf("Expected [%v], got [%v]", expectedMessages[0], data.String()) } // With terminal data = bytes.NewBuffer([]byte{}) if err := jsonMessage.Display(data, true); err != nil { t.Fatal(err) } if data.String() != expectedMessages[1] { t.Fatalf("Expected [%v], got [%v]", expectedMessages[1], data.String()) } } } // Test JSONMessage with an Error. It will return an error with the text as error, not the meaning of the HTTP code. func TestJSONMessageDisplayWithJSONError(t *testing.T) { data := bytes.NewBuffer([]byte{}) jsonMessage := JSONMessage{Error: &JSONError{404, "Can't find it"}} err := jsonMessage.Display(data, true) if err == nil || err.Error() != "Can't find it" { t.Fatalf("Expected a JSONError 404, got [%v]", err) } jsonMessage = JSONMessage{Error: &JSONError{401, "Anything"}} err = jsonMessage.Display(data, true) if err == nil || err.Error() != "Authentication is required." { t.Fatalf("Expected an error [Authentication is required.], got [%v]", err) } } func TestDisplayJSONMessagesStreamInvalidJSON(t *testing.T) { var ( inFd uintptr ) data := bytes.NewBuffer([]byte{}) reader := strings.NewReader("This is not a 'valid' JSON []") inFd, _ = term.GetFdInfo(reader) if err := DisplayJSONMessagesStream(reader, data, inFd, false); err == nil && err.Error()[:17] != "invalid character" { t.Fatalf("Should have thrown an error (invalid character in ..), got [%v]", err) } } func TestDisplayJSONMessagesStream(t *testing.T) { var ( inFd uintptr ) messages := map[string][]string{ // empty string "": { "", ""}, // Without progress & ID "{ \"status\": \"status\" }": { "status\n", "status\n", }, // Without progress, with ID "{ \"id\": \"ID\",\"status\": \"status\" }": { "ID: status\n", fmt.Sprintf("ID: status\n%c[%dB", 27, 0), }, // With progress "{ \"id\": \"ID\", \"status\": \"status\", \"progress\": \"ProgressMessage\" }": { "ID: status ProgressMessage", fmt.Sprintf("\n%c[%dAID: status ProgressMessage%c[%dB", 27, 0, 27, 0), }, // With progressDetail "{ \"id\": \"ID\", \"status\": \"status\", \"progressDetail\": { \"Current\": 1} }": { "", // progressbar is disabled in non-terminal fmt.Sprintf("\n%c[%dA%c[2K\rID: status 1 B\r%c[%dB", 27, 0, 27, 27, 0), }, } for jsonMessage, expectedMessages := range messages { data := bytes.NewBuffer([]byte{}) reader := strings.NewReader(jsonMessage) inFd, _ = term.GetFdInfo(reader) // Without terminal if err := DisplayJSONMessagesStream(reader, data, inFd, false); err != nil { t.Fatal(err) } if data.String() != expectedMessages[0] { t.Fatalf("Expected an [%v], got [%v]", expectedMessages[0], data.String()) } // With terminal data = bytes.NewBuffer([]byte{}) reader = strings.NewReader(jsonMessage) if err := DisplayJSONMessagesStream(reader, data, inFd, true); err != nil { t.Fatal(err) } if data.String() != expectedMessages[1] { t.Fatalf("Expected an [%v], got [%v]", expectedMessages[1], data.String()) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/listenbuffer/README.md ================================================ # listenbuffer listenbuffer uses the kernel's listening backlog functionality to queue connections, allowing applications to start listening immediately and handle connections later. This is signaled by closing the activation channel passed to the constructor. The maximum amount of queued connections depends on the configuration of your kernel (typically called SOMAXXCON) and cannot be configured in Go with the net package. See `src/net/sock_platform.go` in the Go tree or consult your kernel's manual. activator := make(chan struct{}) buffer, err := NewListenBuffer("tcp", "localhost:4000", activator) if err != nil { panic(err) } // will block until activator has been closed or is sent an event client, err := buffer.Accept() Somewhere else in your application once it's been booted: close(activator) `buffer.Accept()` will return the first client in the kernel listening queue, or continue to block until a client connects or an error occurs. ================================================ FILE: vendor/github.com/docker/docker/pkg/listenbuffer/buffer.go ================================================ /* Package listenbuffer uses the kernel's listening backlog functionality to queue connections, allowing applications to start listening immediately and handle connections later. This is signaled by closing the activation channel passed to the constructor. The maximum amount of queued connections depends on the configuration of your kernel (typically called SOMAXXCON) and cannot be configured in Go with the net package. See `src/net/sock_platform.go` in the Go tree or consult your kernel's manual. activator := make(chan struct{}) buffer, err := NewListenBuffer("tcp", "localhost:4000", activator) if err != nil { panic(err) } // will block until activator has been closed or is sent an event client, err := buffer.Accept() Somewhere else in your application once it's been booted: close(activator) `buffer.Accept()` will return the first client in the kernel listening queue, or continue to block until a client connects or an error occurs. */ package listenbuffer import "net" // NewListenBuffer returns a net.Listener listening on addr with the protocol // passed. The channel passed is used to activate the listenbuffer when the // caller is ready to accept connections. func NewListenBuffer(proto, addr string, activate <-chan struct{}) (net.Listener, error) { wrapped, err := net.Listen(proto, addr) if err != nil { return nil, err } return &defaultListener{ wrapped: wrapped, activate: activate, }, nil } // defaultListener is the buffered wrapper around the net.Listener type defaultListener struct { wrapped net.Listener // The net.Listener wrapped by listenbuffer ready bool // Whether the listenbuffer has been activated activate <-chan struct{} // Channel to control activation of the listenbuffer } // Close closes the wrapped socket. func (l *defaultListener) Close() error { return l.wrapped.Close() } // Addr returns the listening address of the wrapped socket. func (l *defaultListener) Addr() net.Addr { return l.wrapped.Addr() } // Accept returns a client connection on the wrapped socket if the listen buffer // has been activated. To active the listenbuffer the activation channel passed // to NewListenBuffer must have been closed or sent an event. func (l *defaultListener) Accept() (net.Conn, error) { // if the listen has been told it is ready then we can go ahead and // start returning connections if l.ready { return l.wrapped.Accept() } <-l.activate l.ready = true return l.Accept() } ================================================ FILE: vendor/github.com/docker/docker/pkg/listenbuffer/listen_buffer_test.go ================================================ package listenbuffer import ( "io/ioutil" "net" "testing" ) func TestListenBufferAllowsAcceptingWhenActivated(t *testing.T) { lock := make(chan struct{}) buffer, err := NewListenBuffer("tcp", "", lock) if err != nil { t.Fatal("Unable to create listen buffer: ", err) } go func() { conn, err := net.Dial("tcp", buffer.Addr().String()) if err != nil { t.Fatal("Client failed to establish connection to server: ", err) } conn.Write([]byte("ping")) conn.Close() }() close(lock) client, err := buffer.Accept() if err != nil { t.Fatal("Failed to accept client: ", err) } response, err := ioutil.ReadAll(client) if err != nil { t.Fatal("Failed to read from client: ", err) } if string(response) != "ping" { t.Fatal("Expected to receive ping from client, received: ", string(response)) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/mflag/LICENSE ================================================ Copyright (c) 2014-2015 The Docker & 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. ================================================ FILE: vendor/github.com/docker/docker/pkg/mflag/README.md ================================================ Package mflag (aka multiple-flag) implements command-line flag parsing. It's an **hacky** fork of the [official golang package](http://golang.org/pkg/flag/) It adds: * both short and long flag version `./example -s red` `./example --string blue` * multiple names for the same option ``` $>./example -h Usage of example: -s, --string="": a simple string ``` ___ It is very flexible on purpose, so you can do things like: ``` $>./example -h Usage of example: -s, -string, --string="": a simple string ``` Or: ``` $>./example -h Usage of example: -oldflag, --newflag="": a simple string ``` You can also hide some flags from the usage, so if we want only `--newflag`: ``` $>./example -h Usage of example: --newflag="": a simple string $>./example -oldflag str str ``` See [example.go](example/example.go) for more details. ================================================ FILE: vendor/github.com/docker/docker/pkg/mflag/example/example.go ================================================ package main import ( "fmt" flag "github.com/docker/docker/pkg/mflag" ) var ( i int str string b, b2, h bool ) func init() { flag.Bool([]string{"#hp", "#-halp"}, false, "display the halp") flag.BoolVar(&b, []string{"b", "#bal", "#bol", "-bal"}, false, "a simple bool") flag.BoolVar(&b, []string{"g", "#gil"}, false, "a simple bool") flag.BoolVar(&b2, []string{"#-bool"}, false, "a simple bool") flag.IntVar(&i, []string{"-integer", "-number"}, -1, "a simple integer") flag.StringVar(&str, []string{"s", "#hidden", "-string"}, "", "a simple string") //-s -hidden and --string will work, but -hidden won't be in the usage flag.BoolVar(&h, []string{"h", "#help", "-help"}, false, "display the help") flag.StringVar(&str, []string{"mode"}, "mode1", "set the mode\nmode1: use the mode1\nmode2: use the mode2\nmode3: use the mode3") flag.Parse() } func main() { if h { flag.PrintDefaults() } else { fmt.Printf("s/#hidden/-string: %s\n", str) fmt.Printf("b: %t\n", b) fmt.Printf("-bool: %t\n", b2) fmt.Printf("s/#hidden/-string(via lookup): %s\n", flag.Lookup("s").Value.String()) fmt.Printf("ARGS: %v\n", flag.Args()) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/mflag/flag.go ================================================ // Copyright 2014-2015 The Docker & Go 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 flag implements command-line flag parsing. Usage: Define flags using flag.String(), Bool(), Int(), etc. This declares an integer flag, -f or --flagname, stored in the pointer ip, with type *int. import "flag /github.com/docker/docker/pkg/mflag" var ip = flag.Int([]string{"f", "-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() { // -flaghidden will work, but will be hidden from the usage flag.IntVar(&flagvar, []string{"f", "#flaghidden", "-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, []string{"name"}, "help message for flagname") For such flags, the default value is just the initial value of the variable. You can also add "deprecated" flags, they are still usable, but are not shown in the usage and will display a warning when you try to use them. `#` before an option means this option is deprecated, if there is an following option without `#` ahead, then that's the replacement, if not, it will just be removed: var ip = flag.Int([]string{"#f", "#flagname", "-flagname"}, 1234, "help message for flagname") this will display: `Warning: '-f' is deprecated, it will be replaced by '--flagname' soon. See usage.` or this will display: `Warning: '-flagname' is deprecated, it will be replaced by '--flagname' soon. See usage.` var ip = flag.Int([]string{"f", "#flagname"}, 1234, "help message for flagname") will display: `Warning: '-flagname' is deprecated, it will be removed soon. See usage.` so you can only use `-f`. You can also group one letter flags, bif you declare var v = flag.Bool([]string{"v", "-verbose"}, false, "help message for verbose") var s = flag.Bool([]string{"s", "-slow"}, false, "help message for slow") you will be able to use the -vs or -sv 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. Command line flag syntax: -flag -flag=x -flag="x" -flag='x' -flag x // non-boolean flags only One or two minus signs may be used; they are equivalent. The last form is not permitted for boolean flags because the meaning of the command cmd -x * will change if there is a file called 0, false, etc. You must use the -flag=false form to turn off a boolean flag. Flag parsing stops just before the first non-flag argument ("-" is a non-flag argument) or after the terminator "--". Integer flags accept 1234, 0664, 0x1234 and may be negative. Boolean flags may be 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 mflag import ( "errors" "fmt" "io" "os" "runtime" "sort" "strconv" "strings" "text/tabwriter" "time" "github.com/docker/docker/pkg/homedir" ) // ErrHelp is the error returned if the flag -help is invoked but no such flag is defined. var ErrHelp = errors.New("flag: help requested") // ErrRetry is the error returned if you need to try letter by letter var ErrRetry = errors.New("flag: retry") // -- 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) Get() interface{} { return bool(*b) } func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) } func (b *boolValue) IsBoolFlag() bool { return true } // optional interface to indicate boolean flags that can be // supplied without "=value" text type boolFlag interface { Value IsBoolFlag() bool } // -- 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) Get() interface{} { return int(*i) } func (i *intValue) String() string { return fmt.Sprintf("%v", *i) } // -- 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) Get() interface{} { return int64(*i) } func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) } // -- 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) Get() interface{} { return uint(*i) } func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) } // -- 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) Get() interface{} { return uint64(*i) } func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) } // -- 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) Get() interface{} { return string(*s) } func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) } // -- 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) Get() interface{} { return float64(*f) } func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) } // -- 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) Get() interface{} { return time.Duration(*d) } func (d *durationValue) String() string { return (*time.Duration)(d).String() } // Value is the interface to the dynamic value stored in a flag. // (The default value is represented as a string.) // // If a Value has an IsBoolFlag() bool method returning true, // the command-line parser makes -name equivalent to -name=true // rather than using the next command-line argument. type Value interface { String() string Set(string) error } // Getter is an interface that allows the contents of a Value to be retrieved. // It wraps the Value interface, rather than being part of it, because it // appeared after Go 1 and its compatibility rules. All Value types provided // by this package satisfy the Getter interface. type Getter interface { Value Get() interface{} } // ErrorHandling defines how to handle flag parsing errors. type ErrorHandling int const ( ContinueOnError ErrorHandling = iota ExitOnError PanicOnError ) // A FlagSet represents a set of defined flags. The zero value of a FlagSet // has no name and has ContinueOnError error handling. 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() ShortUsage func() name string parsed bool actual map[string]*Flag formal map[string]*Flag args []string // arguments after flags errorHandling ErrorHandling output io.Writer // nil means stderr; use Out() accessor nArgRequirements []nArgRequirement } // A Flag represents the state of a flag. type Flag struct { Names []string // name as it appears on command line Usage string // help message Value Value // value as set DefValue string // default value (as text); for usage message } type flagSlice []string func (p flagSlice) Len() int { return len(p) } func (p flagSlice) Less(i, j int) bool { pi, pj := strings.TrimPrefix(p[i], "-"), strings.TrimPrefix(p[j], "-") lpi, lpj := strings.ToLower(pi), strings.ToLower(pj) if lpi != lpj { return lpi < lpj } return pi < pj } func (p flagSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // sortFlags returns the flags as a slice in lexicographical sorted order. func sortFlags(flags map[string]*Flag) []*Flag { var list flagSlice // The sorted list is based on the first name, when flag map might use the other names. nameMap := make(map[string]string) for n, f := range flags { fName := strings.TrimPrefix(f.Names[0], "#") nameMap[fName] = n if len(f.Names) == 1 { list = append(list, fName) continue } found := false for _, name := range list { if name == fName { found = true break } } if !found { list = append(list, fName) } } sort.Sort(list) result := make([]*Flag, len(list)) for i, name := range list { result[i] = flags[nameMap[name]] } return result } // Name returns the name of the FlagSet. func (f *FlagSet) Name() string { return f.name } // Out returns the destination for usage and error messages. 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) } } // 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.formal[name] } // Indicates whether the specified flag was specified at all on the cmd line func (f *FlagSet) IsSet(name string) bool { return f.actual[name] != nil } // Lookup returns the Flag structure of the named command-line flag, // returning nil if none exists. func Lookup(name string) *Flag { return CommandLine.formal[name] } // Indicates whether the specified flag was specified at all on the cmd line func IsSet(name string) bool { return CommandLine.IsSet(name) } type nArgRequirementType int // Indicator used to pass to BadArgs function const ( Exact nArgRequirementType = iota Max Min ) type nArgRequirement struct { Type nArgRequirementType N int } // Require adds a requirement about the number of arguments for the FlagSet. // The first parameter can be Exact, Max, or Min to respectively specify the exact, // the maximum, or the minimal number of arguments required. // The actual check is done in FlagSet.CheckArgs(). func (f *FlagSet) Require(nArgRequirementType nArgRequirementType, nArg int) { f.nArgRequirements = append(f.nArgRequirements, nArgRequirement{nArgRequirementType, nArg}) } // CheckArgs uses the requirements set by FlagSet.Require() to validate // the number of arguments. If the requirements are not met, // an error message string is returned. func (f *FlagSet) CheckArgs() (message string) { for _, req := range f.nArgRequirements { var arguments string if req.N == 1 { arguments = "1 argument" } else { arguments = fmt.Sprintf("%d arguments", req.N) } str := func(kind string) string { return fmt.Sprintf("%q requires %s%s", f.name, kind, arguments) } switch req.Type { case Exact: if f.NArg() != req.N { return str("") } case Max: if f.NArg() > req.N { return str("a maximum of ") } case Min: if f.NArg() < req.N { return str("a minimum of ") } } } return "" } // Set sets the value of the named flag. func (f *FlagSet) Set(name, value string) error { flag, ok := f.formal[name] if !ok { return fmt.Errorf("no such flag -%v", name) } if err := flag.Value.Set(value); err != nil { return err } if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag return nil } // 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() { writer := tabwriter.NewWriter(f.Out(), 20, 1, 3, ' ', 0) home := homedir.Get() // Don't substitute when HOME is / if runtime.GOOS != "windows" && home == "/" { home = "" } // Add a blank line between cmd description and list of options if f.FlagCount() > 0 { fmt.Fprintln(writer, "") } f.VisitAll(func(flag *Flag) { format := " -%s=%s" names := []string{} for _, name := range flag.Names { if name[0] != '#' { names = append(names, name) } } if len(names) > 0 { val := flag.DefValue if home != "" && strings.HasPrefix(val, home) { val = homedir.GetShortcutString() + val[len(home):] } fmt.Fprintf(writer, format, strings.Join(names, ", -"), val) for i, line := range strings.Split(flag.Usage, "\n") { if i != 0 { line = " " + line } fmt.Fprintln(writer, "\t", line) } } }) writer.Flush() } // 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) { if f.name == "" { fmt.Fprintf(f.Out(), "Usage:\n") } else { 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. var Usage = func() { fmt.Fprintf(CommandLine.Out(), "Usage of %s:\n", os.Args[0]) PrintDefaults() } // Usage prints to standard error a usage message documenting the standard command layout // The function is a variable that may be changed to point to a custom function. var ShortUsage = func() { fmt.Fprintf(CommandLine.output, "Usage of %s:\n", os.Args[0]) } // FlagCount returns the number of flags that have been defined. func (f *FlagSet) FlagCount() int { return len(sortFlags(f.formal)) } // FlagCountUndeprecated returns the number of undeprecated flags that have been defined. func (f *FlagSet) FlagCountUndeprecated() int { count := 0 for _, flag := range sortFlags(f.formal) { for _, name := range flag.Names { if name[0] != '#' { count++ break } } } return count } // 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 } // 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, names []string, value bool, usage string) { f.Var(newBoolValue(value, p), names, usage) } // 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, names []string, value bool, usage string) { CommandLine.Var(newBoolValue(value, p), names, usage) } // 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(names []string, value bool, usage string) *bool { p := new(bool) f.BoolVar(p, names, 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(names []string, value bool, usage string) *bool { return CommandLine.Bool(names, value, 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 (f *FlagSet) IntVar(p *int, names []string, value int, usage string) { f.Var(newIntValue(value, p), names, 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, names []string, value int, usage string) { CommandLine.Var(newIntValue(value, p), names, 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(names []string, value int, usage string) *int { p := new(int) f.IntVar(p, names, 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(names []string, value int, usage string) *int { return CommandLine.Int(names, value, 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 (f *FlagSet) Int64Var(p *int64, names []string, value int64, usage string) { f.Var(newInt64Value(value, p), names, 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, names []string, value int64, usage string) { CommandLine.Var(newInt64Value(value, p), names, 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(names []string, value int64, usage string) *int64 { p := new(int64) f.Int64Var(p, names, 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(names []string, value int64, usage string) *int64 { return CommandLine.Int64(names, value, 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 (f *FlagSet) UintVar(p *uint, names []string, value uint, usage string) { f.Var(newUintValue(value, p), names, 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, names []string, value uint, usage string) { CommandLine.Var(newUintValue(value, p), names, 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(names []string, value uint, usage string) *uint { p := new(uint) f.UintVar(p, names, 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(names []string, value uint, usage string) *uint { return CommandLine.Uint(names, value, 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 (f *FlagSet) Uint64Var(p *uint64, names []string, value uint64, usage string) { f.Var(newUint64Value(value, p), names, 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, names []string, value uint64, usage string) { CommandLine.Var(newUint64Value(value, p), names, 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(names []string, value uint64, usage string) *uint64 { p := new(uint64) f.Uint64Var(p, names, 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(names []string, value uint64, usage string) *uint64 { return CommandLine.Uint64(names, value, 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 (f *FlagSet) StringVar(p *string, names []string, value string, usage string) { f.Var(newStringValue(value, p), names, 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, names []string, value string, usage string) { CommandLine.Var(newStringValue(value, p), names, 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(names []string, value string, usage string) *string { p := new(string) f.StringVar(p, names, 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(names []string, value string, usage string) *string { return CommandLine.String(names, value, 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 (f *FlagSet) Float64Var(p *float64, names []string, value float64, usage string) { f.Var(newFloat64Value(value, p), names, 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, names []string, value float64, usage string) { CommandLine.Var(newFloat64Value(value, p), names, 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(names []string, value float64, usage string) *float64 { p := new(float64) f.Float64Var(p, names, 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(names []string, value float64, usage string) *float64 { return CommandLine.Float64(names, value, 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 (f *FlagSet) DurationVar(p *time.Duration, names []string, value time.Duration, usage string) { f.Var(newDurationValue(value, p), names, 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, names []string, value time.Duration, usage string) { CommandLine.Var(newDurationValue(value, p), names, 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(names []string, value time.Duration, usage string) *time.Duration { p := new(time.Duration) f.DurationVar(p, names, 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(names []string, value time.Duration, usage string) *time.Duration { return CommandLine.Duration(names, value, usage) } // 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, names []string, usage string) { // Remember the default value as a string; it won't change. flag := &Flag{names, usage, value, value.String()} for _, name := range names { name = strings.TrimPrefix(name, "#") _, alreadythere := f.formal[name] if alreadythere { var msg string if f.name == "" { msg = fmt.Sprintf("flag redefined: %s", name) } else { msg = fmt.Sprintf("%s flag redefined: %s", f.name, 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[string]*Flag) } f.formal[name] = 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, names []string, usage string) { CommandLine.Var(value, names, 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) if os.Args[0] == f.name { fmt.Fprintf(f.Out(), "See '%s --help'.\n", os.Args[0]) } else { fmt.Fprintf(f.Out(), "See '%s %s --help'.\n", os.Args[0], f.name) } 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 trimQuotes(str string) string { if len(str) == 0 { return str } type quote struct { start, end byte } // All valid quote types. quotes := []quote{ // Double quotes { start: '"', end: '"', }, // Single quotes { start: '\'', end: '\'', }, } for _, quote := range quotes { // Only strip if outermost match. if str[0] == quote.start && str[len(str)-1] == quote.end { str = str[1 : len(str)-1] break } } return str } // parseOne parses one flag. It reports whether a flag was seen. func (f *FlagSet) parseOne() (bool, string, error) { if len(f.args) == 0 { return false, "", nil } s := f.args[0] if len(s) == 0 || s[0] != '-' || len(s) == 1 { return false, "", nil } if s[1] == '-' && len(s) == 2 { // "--" terminates the flags f.args = f.args[1:] return false, "", nil } name := s[1:] if len(name) == 0 || name[0] == '=' { return false, "", f.failf("bad flag syntax: %s", s) } // it's a flag. does it have an argument? f.args = f.args[1:] hasValue := false value := "" if i := strings.Index(name, "="); i != -1 { value = trimQuotes(name[i+1:]) hasValue = true name = name[:i] } m := f.formal flag, alreadythere := m[name] // BUG if !alreadythere { if name == "-help" || name == "help" || name == "h" { // special case for nice help message. f.usage() return false, "", ErrHelp } if len(name) > 0 && name[0] == '-' { return false, "", f.failf("flag provided but not defined: -%s", name) } return false, name, ErrRetry } if fv, ok := flag.Value.(boolFlag); ok && fv.IsBoolFlag() { // special case: doesn't need an arg if hasValue { if err := fv.Set(value); err != nil { return false, "", f.failf("invalid boolean value %q for -%s: %v", value, name, err) } } else { fv.Set("true") } } else { // It must have a value, which might be the next argument. if !hasValue && len(f.args) > 0 { // value is the next arg hasValue = true value, f.args = f.args[0], f.args[1:] } if !hasValue { return false, "", f.failf("flag needs an argument: -%s", name) } if err := flag.Value.Set(value); err != nil { return false, "", f.failf("invalid value %q for flag -%s: %v", value, name, err) } } if f.actual == nil { f.actual = make(map[string]*Flag) } f.actual[name] = flag for i, n := range flag.Names { if n == fmt.Sprintf("#%s", name) { replacement := "" for j := i; j < len(flag.Names); j++ { if flag.Names[j][0] != '#' { replacement = flag.Names[j] break } } if replacement != "" { fmt.Fprintf(f.Out(), "Warning: '-%s' is deprecated, it will be replaced by '-%s' soon. See usage.\n", name, replacement) } else { fmt.Fprintf(f.Out(), "Warning: '-%s' is deprecated, it will be removed soon. See usage.\n", name) } } } return true, "", nil } // 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 = arguments for { seen, name, err := f.parseOne() if seen { continue } if err == nil { break } if err == ErrRetry { if len(name) > 1 { err = nil for _, letter := range strings.Split(name, "") { f.args = append([]string{"-" + letter}, f.args...) seen2, _, err2 := f.parseOne() if seen2 { continue } if err2 != nil { err = f.failf("flag provided but not defined: -%s", name) break } } if err == nil { continue } } else { err = f.failf("flag provided but not defined: -%s", name) } } switch f.errorHandling { case ContinueOnError: return err case ExitOnError: os.Exit(2) case PanicOnError: panic(err) } } return nil } // ParseFlags is a utility function that adds a help flag if withHelp is true, // calls cmd.Parse(args) and prints a relevant error message if there are // incorrect number of arguments. It returns error only if error handling is // set to ContinueOnError and parsing fails. If error handling is set to // ExitOnError, it's safe to ignore the return value. func (cmd *FlagSet) ParseFlags(args []string, withHelp bool) error { var help *bool if withHelp { help = cmd.Bool([]string{"#help", "-help"}, false, "Print usage") } if err := cmd.Parse(args); err != nil { return err } if help != nil && *help { cmd.SetOutput(os.Stdout) cmd.Usage() os.Exit(0) } if str := cmd.CheckArgs(); str != "" { cmd.SetOutput(os.Stderr) cmd.ReportError(str, withHelp) cmd.ShortUsage() os.Exit(1) } return nil } func (cmd *FlagSet) ReportError(str string, withHelp bool) { if withHelp { if os.Args[0] == cmd.Name() { str += ".\nSee '" + os.Args[0] + " --help'" } else { str += ".\nSee '" + os.Args[0] + " " + cmd.Name() + " --help'" } } fmt.Fprintf(cmd.Out(), "docker: %s.\n", str) } // 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:]) } // 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. // The top-level functions such as BoolVar, Arg, and on are wrappers for the // methods of CommandLine. 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, } return f } // 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 } ================================================ FILE: vendor/github.com/docker/docker/pkg/mflag/flag_test.go ================================================ // Copyright 2014-2015 The Docker & Go 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 mflag import ( "bytes" "fmt" "os" "sort" "strings" "testing" "time" ) // ResetForTesting clears all flag state and sets the usage function as directed. // After calling ResetForTesting, parse errors in flag handling will not // exit the program. func ResetForTesting(usage func()) { CommandLine = NewFlagSet(os.Args[0], ContinueOnError) Usage = usage } func boolString(s string) string { if s == "0" { return "false" } return "true" } func TestEverything(t *testing.T) { ResetForTesting(nil) Bool([]string{"test_bool"}, false, "bool value") Int([]string{"test_int"}, 0, "int value") Int64([]string{"test_int64"}, 0, "int64 value") Uint([]string{"test_uint"}, 0, "uint value") Uint64([]string{"test_uint64"}, 0, "uint64 value") String([]string{"test_string"}, "0", "string value") Float64([]string{"test_float64"}, 0, "float64 value") Duration([]string{"test_duration"}, 0, "time.Duration value") m := make(map[string]*Flag) desired := "0" visitor := func(f *Flag) { for _, name := range f.Names { if len(name) > 5 && name[0:5] == "test_" { m[name] = f ok := false switch { case f.Value.String() == desired: ok = true case name == "test_bool" && f.Value.String() == boolString(desired): ok = true case name == "test_duration" && f.Value.String() == desired+"s": ok = true } if !ok { t.Error("Visit: bad value", f.Value.String(), "for", name) } } } } VisitAll(visitor) if len(m) != 8 { t.Error("VisitAll misses some flags") for k, v := range m { t.Log(k, *v) } } m = make(map[string]*Flag) Visit(visitor) if len(m) != 0 { t.Errorf("Visit sees unset flags") for k, v := range m { t.Log(k, *v) } } // Now set all flags Set("test_bool", "true") Set("test_int", "1") Set("test_int64", "1") Set("test_uint", "1") Set("test_uint64", "1") Set("test_string", "1") Set("test_float64", "1") Set("test_duration", "1s") desired = "1" Visit(visitor) if len(m) != 8 { t.Error("Visit fails after set") for k, v := range m { t.Log(k, *v) } } // Now test they're visited in sort order. var flagNames []string Visit(func(f *Flag) { for _, name := range f.Names { flagNames = append(flagNames, name) } }) if !sort.StringsAreSorted(flagNames) { t.Errorf("flag names not sorted: %v", flagNames) } } func TestGet(t *testing.T) { ResetForTesting(nil) Bool([]string{"test_bool"}, true, "bool value") Int([]string{"test_int"}, 1, "int value") Int64([]string{"test_int64"}, 2, "int64 value") Uint([]string{"test_uint"}, 3, "uint value") Uint64([]string{"test_uint64"}, 4, "uint64 value") String([]string{"test_string"}, "5", "string value") Float64([]string{"test_float64"}, 6, "float64 value") Duration([]string{"test_duration"}, 7, "time.Duration value") visitor := func(f *Flag) { for _, name := range f.Names { if len(name) > 5 && name[0:5] == "test_" { g, ok := f.Value.(Getter) if !ok { t.Errorf("Visit: value does not satisfy Getter: %T", f.Value) return } switch name { case "test_bool": ok = g.Get() == true case "test_int": ok = g.Get() == int(1) case "test_int64": ok = g.Get() == int64(2) case "test_uint": ok = g.Get() == uint(3) case "test_uint64": ok = g.Get() == uint64(4) case "test_string": ok = g.Get() == "5" case "test_float64": ok = g.Get() == float64(6) case "test_duration": ok = g.Get() == time.Duration(7) } if !ok { t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), name) } } } } VisitAll(visitor) } func testParse(f *FlagSet, t *testing.T) { if f.Parsed() { t.Error("f.Parse() = true before Parse") } boolFlag := f.Bool([]string{"bool"}, false, "bool value") bool2Flag := f.Bool([]string{"bool2"}, false, "bool2 value") f.Bool([]string{"bool3"}, false, "bool3 value") bool4Flag := f.Bool([]string{"bool4"}, false, "bool4 value") intFlag := f.Int([]string{"-int"}, 0, "int value") int64Flag := f.Int64([]string{"-int64"}, 0, "int64 value") uintFlag := f.Uint([]string{"uint"}, 0, "uint value") uint64Flag := f.Uint64([]string{"-uint64"}, 0, "uint64 value") stringFlag := f.String([]string{"string"}, "0", "string value") f.String([]string{"string2"}, "0", "string2 value") singleQuoteFlag := f.String([]string{"squote"}, "", "single quoted value") doubleQuoteFlag := f.String([]string{"dquote"}, "", "double quoted value") mixedQuoteFlag := f.String([]string{"mquote"}, "", "mixed quoted value") mixed2QuoteFlag := f.String([]string{"mquote2"}, "", "mixed2 quoted value") nestedQuoteFlag := f.String([]string{"nquote"}, "", "nested quoted value") nested2QuoteFlag := f.String([]string{"nquote2"}, "", "nested2 quoted value") float64Flag := f.Float64([]string{"float64"}, 0, "float64 value") durationFlag := f.Duration([]string{"duration"}, 5*time.Second, "time.Duration value") extra := "one-extra-argument" args := []string{ "-bool", "-bool2=true", "-bool4=false", "--int", "22", "--int64", "0x23", "-uint", "24", "--uint64", "25", "-string", "hello", "-squote='single'", `-dquote="double"`, `-mquote='mixed"`, `-mquote2="mixed2'`, `-nquote="'single nested'"`, `-nquote2='"double nested"'`, "-float64", "2718e28", "-duration", "2m", extra, } if err := f.Parse(args); err != nil { t.Fatal(err) } if !f.Parsed() { t.Error("f.Parse() = false after Parse") } if *boolFlag != true { t.Error("bool flag should be true, is ", *boolFlag) } if *bool2Flag != true { t.Error("bool2 flag should be true, is ", *bool2Flag) } if !f.IsSet("bool2") { t.Error("bool2 should be marked as set") } if f.IsSet("bool3") { t.Error("bool3 should not be marked as set") } if !f.IsSet("bool4") { t.Error("bool4 should be marked as set") } if *bool4Flag != false { t.Error("bool4 flag should be false, is ", *bool4Flag) } if *intFlag != 22 { t.Error("int flag should be 22, is ", *intFlag) } if *int64Flag != 0x23 { t.Error("int64 flag should be 0x23, is ", *int64Flag) } if *uintFlag != 24 { t.Error("uint flag should be 24, is ", *uintFlag) } if *uint64Flag != 25 { t.Error("uint64 flag should be 25, is ", *uint64Flag) } if *stringFlag != "hello" { t.Error("string flag should be `hello`, is ", *stringFlag) } if !f.IsSet("string") { t.Error("string flag should be marked as set") } if f.IsSet("string2") { t.Error("string2 flag should not be marked as set") } if *singleQuoteFlag != "single" { t.Error("single quote string flag should be `single`, is ", *singleQuoteFlag) } if *doubleQuoteFlag != "double" { t.Error("double quote string flag should be `double`, is ", *doubleQuoteFlag) } if *mixedQuoteFlag != `'mixed"` { t.Error("mixed quote string flag should be `'mixed\"`, is ", *mixedQuoteFlag) } if *mixed2QuoteFlag != `"mixed2'` { t.Error("mixed2 quote string flag should be `\"mixed2'`, is ", *mixed2QuoteFlag) } if *nestedQuoteFlag != "'single nested'" { t.Error("nested quote string flag should be `'single nested'`, is ", *nestedQuoteFlag) } if *nested2QuoteFlag != `"double nested"` { t.Error("double quote string flag should be `\"double nested\"`, is ", *nested2QuoteFlag) } if *float64Flag != 2718e28 { t.Error("float64 flag should be 2718e28, is ", *float64Flag) } if *durationFlag != 2*time.Minute { t.Error("duration flag should be 2m, is ", *durationFlag) } if len(f.Args()) != 1 { t.Error("expected one argument, got", len(f.Args())) } else if f.Args()[0] != extra { t.Errorf("expected argument %q got %q", extra, f.Args()[0]) } } func testPanic(f *FlagSet, t *testing.T) { f.Int([]string{"-int"}, 0, "int value") if f.Parsed() { t.Error("f.Parse() = true before Parse") } args := []string{ "-int", "21", } f.Parse(args) } func TestParsePanic(t *testing.T) { ResetForTesting(func() {}) testPanic(CommandLine, t) } func TestParse(t *testing.T) { ResetForTesting(func() { t.Error("bad parse") }) testParse(CommandLine, t) } func TestFlagSetParse(t *testing.T) { testParse(NewFlagSet("test", ContinueOnError), t) } // Declare a user-defined flag type. type flagVar []string func (f *flagVar) String() string { return fmt.Sprint([]string(*f)) } func (f *flagVar) Set(value string) error { *f = append(*f, value) return nil } func TestUserDefined(t *testing.T) { var flags FlagSet flags.Init("test", ContinueOnError) var v flagVar flags.Var(&v, []string{"v"}, "usage") if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil { t.Error(err) } if len(v) != 3 { t.Fatal("expected 3 args; got ", len(v)) } expect := "[1 2 3]" if v.String() != expect { t.Errorf("expected value %q got %q", expect, v.String()) } } // Declare a user-defined boolean flag type. type boolFlagVar struct { count int } func (b *boolFlagVar) String() string { return fmt.Sprintf("%d", b.count) } func (b *boolFlagVar) Set(value string) error { if value == "true" { b.count++ } return nil } func (b *boolFlagVar) IsBoolFlag() bool { return b.count < 4 } func TestUserDefinedBool(t *testing.T) { var flags FlagSet flags.Init("test", ContinueOnError) var b boolFlagVar var err error flags.Var(&b, []string{"b"}, "usage") if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil { if b.count < 4 { t.Error(err) } } if b.count != 4 { t.Errorf("want: %d; got: %d", 4, b.count) } if err == nil { t.Error("expected error; got none") } } func TestSetOutput(t *testing.T) { var flags FlagSet var buf bytes.Buffer flags.SetOutput(&buf) flags.Init("test", ContinueOnError) flags.Parse([]string{"-unknown"}) if out := buf.String(); !strings.Contains(out, "-unknown") { t.Logf("expected output mentioning unknown; got %q", out) } } // This tests that one can reset the flags. This still works but not well, and is // superseded by FlagSet. func TestChangingArgs(t *testing.T) { ResetForTesting(func() { t.Fatal("bad parse") }) oldArgs := os.Args defer func() { os.Args = oldArgs }() os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"} before := Bool([]string{"before"}, false, "") if err := CommandLine.Parse(os.Args[1:]); err != nil { t.Fatal(err) } cmd := Arg(0) os.Args = Args() after := Bool([]string{"after"}, false, "") Parse() args := Args() if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) } } // Test that -help invokes the usage message and returns ErrHelp. func TestHelp(t *testing.T) { var helpCalled = false fs := NewFlagSet("help test", ContinueOnError) fs.Usage = func() { helpCalled = true } var flag bool fs.BoolVar(&flag, []string{"flag"}, false, "regular flag") // Regular flag invocation should work err := fs.Parse([]string{"-flag=true"}) if err != nil { t.Fatal("expected no error; got ", err) } if !flag { t.Error("flag was not set by -flag") } if helpCalled { t.Error("help called for regular flag") helpCalled = false // reset for next test } // Help flag should work as expected. err = fs.Parse([]string{"-help"}) if err == nil { t.Fatal("error expected") } if err != ErrHelp { t.Fatal("expected ErrHelp; got ", err) } if !helpCalled { t.Fatal("help was not called") } // If we define a help flag, that should override. var help bool fs.BoolVar(&help, []string{"help"}, false, "help flag") helpCalled = false err = fs.Parse([]string{"-help"}) if err != nil { t.Fatal("expected no error for defined -help; got ", err) } if helpCalled { t.Fatal("help was called; should not have been for defined help flag") } } // Test the flag count functions. func TestFlagCounts(t *testing.T) { fs := NewFlagSet("help test", ContinueOnError) var flag bool fs.BoolVar(&flag, []string{"flag1"}, false, "regular flag") fs.BoolVar(&flag, []string{"#deprecated1"}, false, "regular flag") fs.BoolVar(&flag, []string{"f", "flag2"}, false, "regular flag") fs.BoolVar(&flag, []string{"#d", "#deprecated2"}, false, "regular flag") fs.BoolVar(&flag, []string{"flag3"}, false, "regular flag") fs.BoolVar(&flag, []string{"g", "#flag4", "-flag4"}, false, "regular flag") if fs.FlagCount() != 6 { t.Fatal("FlagCount wrong. ", fs.FlagCount()) } if fs.FlagCountUndeprecated() != 4 { t.Fatal("FlagCountUndeprecated wrong. ", fs.FlagCountUndeprecated()) } if fs.NFlag() != 0 { t.Fatal("NFlag wrong. ", fs.NFlag()) } err := fs.Parse([]string{"-fd", "-g", "-flag4"}) if err != nil { t.Fatal("expected no error for defined -help; got ", err) } if fs.NFlag() != 4 { t.Fatal("NFlag wrong. ", fs.NFlag()) } } // Show up bug in sortFlags func TestSortFlags(t *testing.T) { fs := NewFlagSet("help TestSortFlags", ContinueOnError) var err error var b bool fs.BoolVar(&b, []string{"b", "-banana"}, false, "usage") err = fs.Parse([]string{"--banana=true"}) if err != nil { t.Fatal("expected no error; got ", err) } count := 0 fs.VisitAll(func(flag *Flag) { count++ if flag == nil { t.Fatal("VisitAll should not return a nil flag") } }) flagcount := fs.FlagCount() if flagcount != count { t.Fatalf("FlagCount (%d) != number (%d) of elements visited", flagcount, count) } // Make sure its idempotent if flagcount != fs.FlagCount() { t.Fatalf("FlagCount (%d) != fs.FlagCount() (%d) of elements visited", flagcount, fs.FlagCount()) } count = 0 fs.Visit(func(flag *Flag) { count++ if flag == nil { t.Fatal("Visit should not return a nil flag") } }) nflag := fs.NFlag() if nflag != count { t.Fatalf("NFlag (%d) != number (%d) of elements visited", nflag, count) } if nflag != fs.NFlag() { t.Fatalf("NFlag (%d) != fs.NFlag() (%d) of elements visited", nflag, fs.NFlag()) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/flags.go ================================================ package mount import ( "strings" ) // Parse fstab type mount options into mount() flags // and device specific data func parseOptions(options string) (int, string) { var ( flag int data []string ) flags := map[string]struct { clear bool flag int }{ "defaults": {false, 0}, "ro": {false, RDONLY}, "rw": {true, RDONLY}, "suid": {true, NOSUID}, "nosuid": {false, NOSUID}, "dev": {true, NODEV}, "nodev": {false, NODEV}, "exec": {true, NOEXEC}, "noexec": {false, NOEXEC}, "sync": {false, SYNCHRONOUS}, "async": {true, SYNCHRONOUS}, "dirsync": {false, DIRSYNC}, "remount": {false, REMOUNT}, "mand": {false, MANDLOCK}, "nomand": {true, MANDLOCK}, "atime": {true, NOATIME}, "noatime": {false, NOATIME}, "diratime": {true, NODIRATIME}, "nodiratime": {false, NODIRATIME}, "bind": {false, BIND}, "rbind": {false, RBIND}, "unbindable": {false, UNBINDABLE}, "runbindable": {false, RUNBINDABLE}, "private": {false, PRIVATE}, "rprivate": {false, RPRIVATE}, "shared": {false, SHARED}, "rshared": {false, RSHARED}, "slave": {false, SLAVE}, "rslave": {false, RSLAVE}, "relatime": {false, RELATIME}, "norelatime": {true, RELATIME}, "strictatime": {false, STRICTATIME}, "nostrictatime": {true, STRICTATIME}, } for _, o := range strings.Split(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 { data = append(data, o) } } return flag, strings.Join(data, ",") } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go ================================================ // +build freebsd,cgo package mount /* #include */ import "C" const ( // RDONLY will mount the filesystem as read-only. RDONLY = C.MNT_RDONLY // NOSUID will not allow set-user-identifier or set-group-identifier bits to // take effect. NOSUID = C.MNT_NOSUID // NOEXEC will not allow execution of any binaries on the mounted file system. NOEXEC = C.MNT_NOEXEC // SYNCHRONOUS will allow any I/O to the file system to be done synchronously. SYNCHRONOUS = C.MNT_SYNCHRONOUS // NOATIME will not update the file access time when reading from a file. NOATIME = C.MNT_NOATIME ) // These flags are unsupported. const ( BIND = 0 DIRSYNC = 0 MANDLOCK = 0 NODEV = 0 NODIRATIME = 0 UNBINDABLE = 0 RUNBINDABLE = 0 PRIVATE = 0 RPRIVATE = 0 SHARED = 0 RSHARED = 0 SLAVE = 0 RSLAVE = 0 RBIND = 0 RELATIVE = 0 RELATIME = 0 REMOUNT = 0 STRICTATIME = 0 ) ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/flags_linux.go ================================================ package mount import ( "syscall" ) const ( // RDONLY will mount the file system read-only. RDONLY = syscall.MS_RDONLY // NOSUID will not allow set-user-identifier or set-group-identifier bits to // take effect. NOSUID = syscall.MS_NOSUID // NODEV will not interpret character or block special devices on the file // system. NODEV = syscall.MS_NODEV // NOEXEC will not allow execution of any binaries on the mounted file system. NOEXEC = syscall.MS_NOEXEC // SYNCHRONOUS will allow I/O to the file system to be done synchronously. SYNCHRONOUS = syscall.MS_SYNCHRONOUS // DIRSYNC will force all directory updates within the file system to be done // synchronously. This affects the following system calls: creat, link, // unlink, symlink, mkdir, rmdir, mknod and rename. DIRSYNC = syscall.MS_DIRSYNC // REMOUNT will attempt to remount an already-mounted file system. This is // commonly used to change the mount flags for a file system, especially to // make a readonly file system writeable. It does not change device or mount // point. REMOUNT = syscall.MS_REMOUNT // MANDLOCK will force mandatory locks on a filesystem. MANDLOCK = syscall.MS_MANDLOCK // NOATIME will not update the file access time when reading from a file. NOATIME = syscall.MS_NOATIME // NODIRATIME will not update the directory access time. NODIRATIME = syscall.MS_NODIRATIME // BIND remounts a subtree somewhere else. BIND = syscall.MS_BIND // RBIND remounts a subtree and all possible submounts somewhere else. RBIND = syscall.MS_BIND | syscall.MS_REC // UNBINDABLE creates a mount which cannot be cloned through a bind operation. UNBINDABLE = syscall.MS_UNBINDABLE // RUNBINDABLE marks the entire mount tree as UNBINDABLE. RUNBINDABLE = syscall.MS_UNBINDABLE | syscall.MS_REC // PRIVATE creates a mount which carries no propagation abilities. PRIVATE = syscall.MS_PRIVATE // RPRIVATE marks the entire mount tree as PRIVATE. RPRIVATE = syscall.MS_PRIVATE | syscall.MS_REC // SLAVE creates a mount which receives propagation from its master, but not // vice versa. SLAVE = syscall.MS_SLAVE // RSLAVE marks the entire mount tree as SLAVE. RSLAVE = syscall.MS_SLAVE | syscall.MS_REC // SHARED creates a mount which provides the ability to create mirrors of // that mount such that mounts and unmounts within any of the mirrors // propagate to the other mirrors. SHARED = syscall.MS_SHARED // RSHARED marks the entire mount tree as SHARED. RSHARED = syscall.MS_SHARED | syscall.MS_REC // RELATIME updates inode access times relative to modify or change time. RELATIME = syscall.MS_RELATIME // STRICTATIME allows to explicitly request full atime updates. This makes // it possible for the kernel to default to relatime or noatime but still // allow userspace to override it. STRICTATIME = syscall.MS_STRICTATIME ) ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go ================================================ // +build !linux,!freebsd freebsd,!cgo package mount // These flags are unsupported. const ( BIND = 0 DIRSYNC = 0 MANDLOCK = 0 NOATIME = 0 NODEV = 0 NODIRATIME = 0 NOEXEC = 0 NOSUID = 0 UNBINDABLE = 0 RUNBINDABLE = 0 PRIVATE = 0 RPRIVATE = 0 SHARED = 0 RSHARED = 0 SLAVE = 0 RSLAVE = 0 RBIND = 0 RELATIME = 0 RELATIVE = 0 REMOUNT = 0 STRICTATIME = 0 SYNCHRONOUS = 0 RDONLY = 0 ) ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mount.go ================================================ package mount import ( "time" ) // GetMounts retrieves a list of mounts for the current running process. func GetMounts() ([]*Info, error) { return parseMountTable() } // Mounted looks at /proc/self/mountinfo to determine of the specified // mountpoint has been mounted func Mounted(mountpoint string) (bool, error) { entries, err := parseMountTable() if err != nil { return false, err } // Search the table for the mountpoint for _, e := range entries { if e.Mountpoint == mountpoint { return true, nil } } return false, nil } // Mount will mount filesystem according to the specified configuration, on the // condition that the target path is *not* already mounted. Options must be // specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See // flags.go for supported option flags. func Mount(device, target, mType, options string) error { flag, _ := parseOptions(options) if flag&REMOUNT != REMOUNT { if mounted, err := Mounted(target); err != nil || mounted { return err } } return ForceMount(device, target, mType, options) } // ForceMount will mount a filesystem according to the specified configuration, // *regardless* if the target path is not already mounted. Options must be // specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See // flags.go for supported option flags. func ForceMount(device, target, mType, options string) error { flag, data := parseOptions(options) if err := mount(device, target, mType, uintptr(flag), data); err != nil { return err } return nil } // Unmount will unmount the target filesystem, so long as it is mounted. func Unmount(target string) error { if mounted, err := Mounted(target); err != nil || !mounted { return err } return ForceUnmount(target) } // ForceUnmount will force an unmount of the target filesystem, regardless if // it is mounted or not. func ForceUnmount(target string) (err error) { // Simple retry logic for unmount for i := 0; i < 10; i++ { if err = unmount(target, 0); err == nil { return nil } time.Sleep(100 * time.Millisecond) } return } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mount_test.go ================================================ package mount import ( "os" "path" "testing" ) func TestMountOptionsParsing(t *testing.T) { options := "noatime,ro,size=10k" flag, data := parseOptions(options) if data != "size=10k" { t.Fatalf("Expected size=10 got %s", data) } expectedFlag := NOATIME | RDONLY if flag != expectedFlag { t.Fatalf("Expected %d got %d", expectedFlag, flag) } } func TestMounted(t *testing.T) { tmp := path.Join(os.TempDir(), "mount-tests") if err := os.MkdirAll(tmp, 0777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) var ( sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") sourcePath = path.Join(sourceDir, "file.txt") targetPath = path.Join(targetDir, "file.txt") ) os.Mkdir(sourceDir, 0777) os.Mkdir(targetDir, 0777) f, err := os.Create(sourcePath) if err != nil { t.Fatal(err) } f.WriteString("hello") f.Close() f, err = os.Create(targetPath) if err != nil { t.Fatal(err) } f.Close() if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() mounted, err := Mounted(targetDir) if err != nil { t.Fatal(err) } if !mounted { t.Fatalf("Expected %s to be mounted", targetDir) } if _, err := os.Stat(targetDir); err != nil { t.Fatal(err) } } func TestMountReadonly(t *testing.T) { tmp := path.Join(os.TempDir(), "mount-tests") if err := os.MkdirAll(tmp, 0777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) var ( sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") sourcePath = path.Join(sourceDir, "file.txt") targetPath = path.Join(targetDir, "file.txt") ) os.Mkdir(sourceDir, 0777) os.Mkdir(targetDir, 0777) f, err := os.Create(sourcePath) if err != nil { t.Fatal(err) } f.WriteString("hello") f.Close() f, err = os.Create(targetPath) if err != nil { t.Fatal(err) } f.Close() if err := Mount(sourceDir, targetDir, "none", "bind,ro"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() f, err = os.OpenFile(targetPath, os.O_RDWR, 0777) if err == nil { t.Fatal("Should not be able to open a ro file as rw") } } func TestGetMounts(t *testing.T) { mounts, err := GetMounts() if err != nil { t.Fatal(err) } root := false for _, entry := range mounts { if entry.Mountpoint == "/" { root = true } } if !root { t.Fatal("/ should be mounted at least") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go ================================================ package mount /* #include #include #include #include #include #include */ import "C" import ( "fmt" "strings" "syscall" "unsafe" ) func allocateIOVecs(options []string) []C.struct_iovec { out := make([]C.struct_iovec, len(options)) for i, option := range options { out[i].iov_base = unsafe.Pointer(C.CString(option)) out[i].iov_len = C.size_t(len(option) + 1) } return out } func mount(device, target, mType string, flag uintptr, data string) error { isNullFS := false xs := strings.Split(data, ",") for _, x := range xs { if x == "bind" { isNullFS = true } } options := []string{"fspath", target} if isNullFS { options = append(options, "fstype", "nullfs", "target", device) } else { options = append(options, "fstype", mType, "from", device) } rawOptions := allocateIOVecs(options) for _, rawOption := range rawOptions { defer C.free(rawOption.iov_base) } if errno := C.nmount(&rawOptions[0], C.uint(len(options)), C.int(flag)); errno != 0 { reason := C.GoString(C.strerror(*C.__error())) return fmt.Errorf("Failed to call nmount: %s", reason) } return nil } func unmount(target string, flag int) error { return syscall.Unmount(target, flag) } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mounter_linux.go ================================================ package mount import ( "syscall" ) func mount(device, target, mType string, flag uintptr, data string) error { if err := syscall.Mount(device, target, mType, flag, data); err != nil { return err } // If we have a bind mount or remount, remount... if flag&syscall.MS_BIND == syscall.MS_BIND && flag&syscall.MS_RDONLY == syscall.MS_RDONLY { return syscall.Mount(device, target, mType, flag|syscall.MS_REMOUNT, data) } return nil } func unmount(target string, flag int) error { return syscall.Unmount(target, flag) } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go ================================================ // +build !linux,!freebsd freebsd,!cgo package mount func mount(device, target, mType string, flag uintptr, data string) error { panic("Not implemented") } func unmount(target string, flag int) error { panic("Not implemented") } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mountinfo.go ================================================ package mount // Info reveals information about a particular mounted filesystem. This // struct is populated from the content in the /proc//mountinfo file. type Info struct { // ID is a unique identifier of the mount (may be reused after umount). ID int // Parent indicates the ID of the mount parent (or of self for the top of the // mount tree). Parent int // Major indicates one half of the device ID which identifies the device class. Major int // Minor indicates one half of the device ID which identifies a specific // instance of device. Minor int // Root of the mount within the filesystem. Root string // Mountpoint indicates the mount point relative to the process's root. Mountpoint string // Opts represents mount-specific options. Opts string // Optional represents optional fields. Optional string // Fstype indicates the type of filesystem, such as EXT3. Fstype string // Source indicates filesystem specific information or "none". Source string // VfsOpts represents per super block options. VfsOpts string } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go ================================================ package mount /* #include #include #include */ import "C" import ( "fmt" "reflect" "unsafe" ) // Parse /proc/self/mountinfo because comparing Dev and ino does not work from // bind mounts. func parseMountTable() ([]*Info, error) { var rawEntries *C.struct_statfs count := int(C.getmntinfo(&rawEntries, C.MNT_WAIT)) if count == 0 { return nil, fmt.Errorf("Failed to call getmntinfo") } var entries []C.struct_statfs header := (*reflect.SliceHeader)(unsafe.Pointer(&entries)) header.Cap = count header.Len = count header.Data = uintptr(unsafe.Pointer(rawEntries)) var out []*Info for _, entry := range entries { var mountinfo Info mountinfo.Mountpoint = C.GoString(&entry.f_mntonname[0]) mountinfo.Source = C.GoString(&entry.f_mntfromname[0]) mountinfo.Fstype = C.GoString(&entry.f_fstypename[0]) out = append(out, &mountinfo) } return out, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go ================================================ // +build linux package mount import ( "bufio" "fmt" "io" "os" "strings" ) const ( /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) (1) mount ID: unique identifier of the mount (may be reused after umount) (2) parent ID: ID of parent (or of self for the top of the mount tree) (3) major:minor: value of st_dev for files on filesystem (4) root: root of the mount within the filesystem (5) mount point: mount point relative to the process's root (6) mount options: per mount options (7) optional fields: zero or more fields of the form "tag[:value]" (8) separator: marks the end of the optional fields (9) filesystem type: name of filesystem of the form "type[.subtype]" (10) mount source: filesystem specific information or "none" (11) super options: per super block options*/ mountinfoFormat = "%d %d %d:%d %s %s %s %s" ) // Parse /proc/self/mountinfo because comparing Dev and ino does not work from // bind mounts func parseMountTable() ([]*Info, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return nil, err } defer f.Close() return parseInfoFile(f) } func parseInfoFile(r io.Reader) ([]*Info, error) { var ( s = bufio.NewScanner(r) out = []*Info{} ) for s.Scan() { if err := s.Err(); err != nil { return nil, err } var ( p = &Info{} text = s.Text() optionalFields string ) if _, err := fmt.Sscanf(text, mountinfoFormat, &p.ID, &p.Parent, &p.Major, &p.Minor, &p.Root, &p.Mountpoint, &p.Opts, &optionalFields); err != nil { return nil, fmt.Errorf("Scanning '%s' failed: %s", text, err) } // Safe as mountinfo encodes mountpoints with spaces as \040. index := strings.Index(text, " - ") postSeparatorFields := strings.Fields(text[index+3:]) if len(postSeparatorFields) < 3 { return nil, fmt.Errorf("Error found less than 3 fields post '-' in %q", text) } if optionalFields != "-" { p.Optional = optionalFields } p.Fstype = postSeparatorFields[0] p.Source = postSeparatorFields[1] p.VfsOpts = strings.Join(postSeparatorFields[2:], " ") out = append(out, p) } return out, nil } // PidMountInfo collects the mounts for a specific process ID. If the process // ID is unknown, it is better to use `GetMounts` which will inspect // "/proc/self/mountinfo" instead. func PidMountInfo(pid int) ([]*Info, error) { f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid)) if err != nil { return nil, err } defer f.Close() return parseInfoFile(f) } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mountinfo_linux_test.go ================================================ // +build linux package mount import ( "bytes" "testing" ) const ( fedoraMountinfo = `15 35 0:3 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw 16 35 0:14 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw,seclabel 17 35 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,seclabel,size=8056484k,nr_inodes=2014121,mode=755 18 16 0:15 / /sys/kernel/security rw,nosuid,nodev,noexec,relatime shared:7 - securityfs securityfs rw 19 16 0:13 / /sys/fs/selinux rw,relatime shared:8 - selinuxfs selinuxfs rw 20 17 0:16 / /dev/shm rw,nosuid,nodev shared:3 - tmpfs tmpfs rw,seclabel 21 17 0:10 / /dev/pts rw,nosuid,noexec,relatime shared:4 - devpts devpts rw,seclabel,gid=5,mode=620,ptmxmode=000 22 35 0:17 / /run rw,nosuid,nodev shared:21 - tmpfs tmpfs rw,seclabel,mode=755 23 16 0:18 / /sys/fs/cgroup rw,nosuid,nodev,noexec shared:9 - tmpfs tmpfs rw,seclabel,mode=755 24 23 0:19 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime shared:10 - cgroup cgroup rw,xattr,release_agent=/usr/lib/systemd/systemd-cgroups-agent,name=systemd 25 16 0:20 / /sys/fs/pstore rw,nosuid,nodev,noexec,relatime shared:20 - pstore pstore rw 26 23 0:21 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:11 - cgroup cgroup rw,cpuset,clone_children 27 23 0:22 / /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:12 - cgroup cgroup rw,cpuacct,cpu,clone_children 28 23 0:23 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:13 - cgroup cgroup rw,memory,clone_children 29 23 0:24 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime shared:14 - cgroup cgroup rw,devices,clone_children 30 23 0:25 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime shared:15 - cgroup cgroup rw,freezer,clone_children 31 23 0:26 / /sys/fs/cgroup/net_cls rw,nosuid,nodev,noexec,relatime shared:16 - cgroup cgroup rw,net_cls,clone_children 32 23 0:27 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime shared:17 - cgroup cgroup rw,blkio,clone_children 33 23 0:28 / /sys/fs/cgroup/perf_event rw,nosuid,nodev,noexec,relatime shared:18 - cgroup cgroup rw,perf_event,clone_children 34 23 0:29 / /sys/fs/cgroup/hugetlb rw,nosuid,nodev,noexec,relatime shared:19 - cgroup cgroup rw,hugetlb,clone_children 35 1 253:2 / / rw,relatime shared:1 - ext4 /dev/mapper/ssd-root--f20 rw,seclabel,data=ordered 36 15 0:30 / /proc/sys/fs/binfmt_misc rw,relatime shared:22 - autofs systemd-1 rw,fd=38,pgrp=1,timeout=300,minproto=5,maxproto=5,direct 37 17 0:12 / /dev/mqueue rw,relatime shared:23 - mqueue mqueue rw,seclabel 38 35 0:31 / /tmp rw shared:24 - tmpfs tmpfs rw,seclabel 39 17 0:32 / /dev/hugepages rw,relatime shared:25 - hugetlbfs hugetlbfs rw,seclabel 40 16 0:7 / /sys/kernel/debug rw,relatime shared:26 - debugfs debugfs rw 41 16 0:33 / /sys/kernel/config rw,relatime shared:27 - configfs configfs rw 42 35 0:34 / /var/lib/nfs/rpc_pipefs rw,relatime shared:28 - rpc_pipefs sunrpc rw 43 15 0:35 / /proc/fs/nfsd rw,relatime shared:29 - nfsd sunrpc rw 45 35 8:17 / /boot rw,relatime shared:30 - ext4 /dev/sdb1 rw,seclabel,data=ordered 46 35 253:4 / /home rw,relatime shared:31 - ext4 /dev/mapper/ssd-home rw,seclabel,data=ordered 47 35 253:5 / /var/lib/libvirt/images rw,noatime,nodiratime shared:32 - ext4 /dev/mapper/ssd-virt rw,seclabel,discard,data=ordered 48 35 253:12 / /mnt/old rw,relatime shared:33 - ext4 /dev/mapper/HelpDeskRHEL6-FedoraRoot rw,seclabel,data=ordered 121 22 0:36 / /run/user/1000/gvfs rw,nosuid,nodev,relatime shared:104 - fuse.gvfsd-fuse gvfsd-fuse rw,user_id=1000,group_id=1000 124 16 0:37 / /sys/fs/fuse/connections rw,relatime shared:107 - fusectl fusectl rw 165 38 253:3 / /tmp/mnt rw,relatime shared:147 - ext4 /dev/mapper/ssd-root rw,seclabel,data=ordered 167 35 253:15 / /var/lib/docker/devicemapper/mnt/aae4076022f0e2b80a2afbf8fc6df450c52080191fcef7fb679a73e6f073e5c2 rw,relatime shared:149 - ext4 /dev/mapper/docker-253:2-425882-aae4076022f0e2b80a2afbf8fc6df450c52080191fcef7fb679a73e6f073e5c2 rw,seclabel,discard,stripe=16,data=ordered 171 35 253:16 / /var/lib/docker/devicemapper/mnt/c71be651f114db95180e472f7871b74fa597ee70a58ccc35cb87139ddea15373 rw,relatime shared:153 - ext4 /dev/mapper/docker-253:2-425882-c71be651f114db95180e472f7871b74fa597ee70a58ccc35cb87139ddea15373 rw,seclabel,discard,stripe=16,data=ordered 175 35 253:17 / /var/lib/docker/devicemapper/mnt/1bac6ab72862d2d5626560df6197cf12036b82e258c53d981fa29adce6f06c3c rw,relatime shared:157 - ext4 /dev/mapper/docker-253:2-425882-1bac6ab72862d2d5626560df6197cf12036b82e258c53d981fa29adce6f06c3c rw,seclabel,discard,stripe=16,data=ordered 179 35 253:18 / /var/lib/docker/devicemapper/mnt/d710a357d77158e80d5b2c55710ae07c94e76d34d21ee7bae65ce5418f739b09 rw,relatime shared:161 - ext4 /dev/mapper/docker-253:2-425882-d710a357d77158e80d5b2c55710ae07c94e76d34d21ee7bae65ce5418f739b09 rw,seclabel,discard,stripe=16,data=ordered 183 35 253:19 / /var/lib/docker/devicemapper/mnt/6479f52366114d5f518db6837254baab48fab39f2ac38d5099250e9a6ceae6c7 rw,relatime shared:165 - ext4 /dev/mapper/docker-253:2-425882-6479f52366114d5f518db6837254baab48fab39f2ac38d5099250e9a6ceae6c7 rw,seclabel,discard,stripe=16,data=ordered 187 35 253:20 / /var/lib/docker/devicemapper/mnt/8d9df91c4cca5aef49eeb2725292aab324646f723a7feab56be34c2ad08268e1 rw,relatime shared:169 - ext4 /dev/mapper/docker-253:2-425882-8d9df91c4cca5aef49eeb2725292aab324646f723a7feab56be34c2ad08268e1 rw,seclabel,discard,stripe=16,data=ordered 191 35 253:21 / /var/lib/docker/devicemapper/mnt/c8240b768603d32e920d365dc9d1dc2a6af46cd23e7ae819947f969e1b4ec661 rw,relatime shared:173 - ext4 /dev/mapper/docker-253:2-425882-c8240b768603d32e920d365dc9d1dc2a6af46cd23e7ae819947f969e1b4ec661 rw,seclabel,discard,stripe=16,data=ordered 195 35 253:22 / /var/lib/docker/devicemapper/mnt/2eb3a01278380bbf3ed12d86ac629eaa70a4351301ee307a5cabe7b5f3b1615f rw,relatime shared:177 - ext4 /dev/mapper/docker-253:2-425882-2eb3a01278380bbf3ed12d86ac629eaa70a4351301ee307a5cabe7b5f3b1615f rw,seclabel,discard,stripe=16,data=ordered 199 35 253:23 / /var/lib/docker/devicemapper/mnt/37a17fb7c9d9b80821235d5f2662879bd3483915f245f9b49cdaa0e38779b70b rw,relatime shared:181 - ext4 /dev/mapper/docker-253:2-425882-37a17fb7c9d9b80821235d5f2662879bd3483915f245f9b49cdaa0e38779b70b rw,seclabel,discard,stripe=16,data=ordered 203 35 253:24 / /var/lib/docker/devicemapper/mnt/aea459ae930bf1de913e2f29428fd80ee678a1e962d4080019d9f9774331ee2b rw,relatime shared:185 - ext4 /dev/mapper/docker-253:2-425882-aea459ae930bf1de913e2f29428fd80ee678a1e962d4080019d9f9774331ee2b rw,seclabel,discard,stripe=16,data=ordered 207 35 253:25 / /var/lib/docker/devicemapper/mnt/928ead0bc06c454bd9f269e8585aeae0a6bd697f46dc8754c2a91309bc810882 rw,relatime shared:189 - ext4 /dev/mapper/docker-253:2-425882-928ead0bc06c454bd9f269e8585aeae0a6bd697f46dc8754c2a91309bc810882 rw,seclabel,discard,stripe=16,data=ordered 211 35 253:26 / /var/lib/docker/devicemapper/mnt/0f284d18481d671644706e7a7244cbcf63d590d634cc882cb8721821929d0420 rw,relatime shared:193 - ext4 /dev/mapper/docker-253:2-425882-0f284d18481d671644706e7a7244cbcf63d590d634cc882cb8721821929d0420 rw,seclabel,discard,stripe=16,data=ordered 215 35 253:27 / /var/lib/docker/devicemapper/mnt/d9dd16722ab34c38db2733e23f69e8f4803ce59658250dd63e98adff95d04919 rw,relatime shared:197 - ext4 /dev/mapper/docker-253:2-425882-d9dd16722ab34c38db2733e23f69e8f4803ce59658250dd63e98adff95d04919 rw,seclabel,discard,stripe=16,data=ordered 219 35 253:28 / /var/lib/docker/devicemapper/mnt/bc4500479f18c2c08c21ad5282e5f826a016a386177d9874c2764751c031d634 rw,relatime shared:201 - ext4 /dev/mapper/docker-253:2-425882-bc4500479f18c2c08c21ad5282e5f826a016a386177d9874c2764751c031d634 rw,seclabel,discard,stripe=16,data=ordered 223 35 253:29 / /var/lib/docker/devicemapper/mnt/7770c8b24eb3d5cc159a065910076938910d307ab2f5d94e1dc3b24c06ee2c8a rw,relatime shared:205 - ext4 /dev/mapper/docker-253:2-425882-7770c8b24eb3d5cc159a065910076938910d307ab2f5d94e1dc3b24c06ee2c8a rw,seclabel,discard,stripe=16,data=ordered 227 35 253:30 / /var/lib/docker/devicemapper/mnt/c280cd3d0bf0aa36b478b292279671624cceafc1a67eaa920fa1082601297adf rw,relatime shared:209 - ext4 /dev/mapper/docker-253:2-425882-c280cd3d0bf0aa36b478b292279671624cceafc1a67eaa920fa1082601297adf rw,seclabel,discard,stripe=16,data=ordered 231 35 253:31 / /var/lib/docker/devicemapper/mnt/8b59a7d9340279f09fea67fd6ad89ddef711e9e7050eb647984f8b5ef006335f rw,relatime shared:213 - ext4 /dev/mapper/docker-253:2-425882-8b59a7d9340279f09fea67fd6ad89ddef711e9e7050eb647984f8b5ef006335f rw,seclabel,discard,stripe=16,data=ordered 235 35 253:32 / /var/lib/docker/devicemapper/mnt/1a28059f29eda821578b1bb27a60cc71f76f846a551abefabce6efd0146dce9f rw,relatime shared:217 - ext4 /dev/mapper/docker-253:2-425882-1a28059f29eda821578b1bb27a60cc71f76f846a551abefabce6efd0146dce9f rw,seclabel,discard,stripe=16,data=ordered 239 35 253:33 / /var/lib/docker/devicemapper/mnt/e9aa60c60128cad1 rw,relatime shared:221 - ext4 /dev/mapper/docker-253:2-425882-e9aa60c60128cad1 rw,seclabel,discard,stripe=16,data=ordered 243 35 253:34 / /var/lib/docker/devicemapper/mnt/5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d-init rw,relatime shared:225 - ext4 /dev/mapper/docker-253:2-425882-5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d-init rw,seclabel,discard,stripe=16,data=ordered 247 35 253:35 / /var/lib/docker/devicemapper/mnt/5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d rw,relatime shared:229 - ext4 /dev/mapper/docker-253:2-425882-5fec11304b6f4713fea7b6ccdcc1adc0a1966187f590fe25a8227428a8df275d rw,seclabel,discard,stripe=16,data=ordered 31 21 0:23 / /DATA/foo_bla_bla rw,relatime - cifs //foo/BLA\040BLA\040BLA/ rw,sec=ntlm,cache=loose,unc=\\foo\BLA BLA BLA,username=my_login,domain=mydomain.com,uid=12345678,forceuid,gid=12345678,forcegid,addr=10.1.30.10,file_mode=0755,dir_mode=0755,nounix,rsize=61440,wsize=65536,actimeo=1` ubuntuMountInfo = `15 20 0:14 / /sys rw,nosuid,nodev,noexec,relatime - sysfs sysfs rw 16 20 0:3 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw 17 20 0:5 / /dev rw,relatime - devtmpfs udev rw,size=1015140k,nr_inodes=253785,mode=755 18 17 0:11 / /dev/pts rw,nosuid,noexec,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000 19 20 0:15 / /run rw,nosuid,noexec,relatime - tmpfs tmpfs rw,size=205044k,mode=755 20 1 253:0 / / rw,relatime - ext4 /dev/disk/by-label/DOROOT rw,errors=remount-ro,data=ordered 21 15 0:16 / /sys/fs/cgroup rw,relatime - tmpfs none rw,size=4k,mode=755 22 15 0:17 / /sys/fs/fuse/connections rw,relatime - fusectl none rw 23 15 0:6 / /sys/kernel/debug rw,relatime - debugfs none rw 24 15 0:10 / /sys/kernel/security rw,relatime - securityfs none rw 25 19 0:18 / /run/lock rw,nosuid,nodev,noexec,relatime - tmpfs none rw,size=5120k 26 21 0:19 / /sys/fs/cgroup/cpuset rw,relatime - cgroup cgroup rw,cpuset,clone_children 27 19 0:20 / /run/shm rw,nosuid,nodev,relatime - tmpfs none rw 28 21 0:21 / /sys/fs/cgroup/cpu rw,relatime - cgroup cgroup rw,cpu 29 19 0:22 / /run/user rw,nosuid,nodev,noexec,relatime - tmpfs none rw,size=102400k,mode=755 30 15 0:23 / /sys/fs/pstore rw,relatime - pstore none rw 31 21 0:24 / /sys/fs/cgroup/cpuacct rw,relatime - cgroup cgroup rw,cpuacct 32 21 0:25 / /sys/fs/cgroup/memory rw,relatime - cgroup cgroup rw,memory 33 21 0:26 / /sys/fs/cgroup/devices rw,relatime - cgroup cgroup rw,devices 34 21 0:27 / /sys/fs/cgroup/freezer rw,relatime - cgroup cgroup rw,freezer 35 21 0:28 / /sys/fs/cgroup/blkio rw,relatime - cgroup cgroup rw,blkio 36 21 0:29 / /sys/fs/cgroup/perf_event rw,relatime - cgroup cgroup rw,perf_event 37 21 0:30 / /sys/fs/cgroup/hugetlb rw,relatime - cgroup cgroup rw,hugetlb 38 21 0:31 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime - cgroup systemd rw,name=systemd 39 20 0:32 / /var/lib/docker/aufs/mnt/b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc rw,relatime - aufs none rw,si=caafa54fdc06525 40 20 0:33 / /var/lib/docker/aufs/mnt/2eed44ac7ce7c75af04f088ed6cb4ce9d164801e91d78c6db65d7ef6d572bba8-init rw,relatime - aufs none rw,si=caafa54f882b525 41 20 0:34 / /var/lib/docker/aufs/mnt/2eed44ac7ce7c75af04f088ed6cb4ce9d164801e91d78c6db65d7ef6d572bba8 rw,relatime - aufs none rw,si=caafa54f8829525 42 20 0:35 / /var/lib/docker/aufs/mnt/16f4d7e96dd612903f425bfe856762f291ff2e36a8ecd55a2209b7d7cd81c30b rw,relatime - aufs none rw,si=caafa54f882d525 43 20 0:36 / /var/lib/docker/aufs/mnt/63ca08b75d7438a9469a5954e003f48ffede73541f6286ce1cb4d7dd4811da7e-init rw,relatime - aufs none rw,si=caafa54f882f525 44 20 0:37 / /var/lib/docker/aufs/mnt/63ca08b75d7438a9469a5954e003f48ffede73541f6286ce1cb4d7dd4811da7e rw,relatime - aufs none rw,si=caafa54f88ba525 45 20 0:38 / /var/lib/docker/aufs/mnt/283f35a910233c756409313be71ecd8fcfef0df57108b8d740b61b3e88860452 rw,relatime - aufs none rw,si=caafa54f88b8525 46 20 0:39 / /var/lib/docker/aufs/mnt/2c6c7253d4090faa3886871fb21bd660609daeb0206588c0602007f7d0f254b1-init rw,relatime - aufs none rw,si=caafa54f88be525 47 20 0:40 / /var/lib/docker/aufs/mnt/2c6c7253d4090faa3886871fb21bd660609daeb0206588c0602007f7d0f254b1 rw,relatime - aufs none rw,si=caafa54f882c525 48 20 0:41 / /var/lib/docker/aufs/mnt/de2b538c97d6366cc80e8658547c923ea1d042f85580df379846f36a4df7049d rw,relatime - aufs none rw,si=caafa54f85bb525 49 20 0:42 / /var/lib/docker/aufs/mnt/94a3d8ed7c27e5b0aa71eba46c736bfb2742afda038e74f2dd6035fb28415b49-init rw,relatime - aufs none rw,si=caafa54fdc00525 50 20 0:43 / /var/lib/docker/aufs/mnt/94a3d8ed7c27e5b0aa71eba46c736bfb2742afda038e74f2dd6035fb28415b49 rw,relatime - aufs none rw,si=caafa54fbaec525 51 20 0:44 / /var/lib/docker/aufs/mnt/6ac1cace985c9fc9bea32234de8b36dba49bdd5e29a2972b327ff939d78a6274 rw,relatime - aufs none rw,si=caafa54f8e1a525 52 20 0:45 / /var/lib/docker/aufs/mnt/dff147033e3a0ef061e1de1ad34256b523d4a8c1fa6bba71a0ab538e8628ff0b-init rw,relatime - aufs none rw,si=caafa54f8e1d525 53 20 0:46 / /var/lib/docker/aufs/mnt/dff147033e3a0ef061e1de1ad34256b523d4a8c1fa6bba71a0ab538e8628ff0b rw,relatime - aufs none rw,si=caafa54f8e1b525 54 20 0:47 / /var/lib/docker/aufs/mnt/cabb117d997f0f93519185aea58389a9762770b7496ed0b74a3e4a083fa45902 rw,relatime - aufs none rw,si=caafa54f810a525 55 20 0:48 / /var/lib/docker/aufs/mnt/e1c8a94ffaa9d532bbbdc6ef771ce8a6c2c06757806ecaf8b68e9108fec65f33-init rw,relatime - aufs none rw,si=caafa54f8529525 56 20 0:49 / /var/lib/docker/aufs/mnt/e1c8a94ffaa9d532bbbdc6ef771ce8a6c2c06757806ecaf8b68e9108fec65f33 rw,relatime - aufs none rw,si=caafa54f852f525 57 20 0:50 / /var/lib/docker/aufs/mnt/16a1526fa445b84ce84f89506d219e87fa488a814063baf045d88b02f21166b3 rw,relatime - aufs none rw,si=caafa54f9e1d525 58 20 0:51 / /var/lib/docker/aufs/mnt/57b9c92e1e368fa7dbe5079f7462e917777829caae732828b003c355fe49da9f-init rw,relatime - aufs none rw,si=caafa54f854d525 59 20 0:52 / /var/lib/docker/aufs/mnt/57b9c92e1e368fa7dbe5079f7462e917777829caae732828b003c355fe49da9f rw,relatime - aufs none rw,si=caafa54f854e525 60 20 0:53 / /var/lib/docker/aufs/mnt/e370c3e286bea027917baa0e4d251262681a472a87056e880dfd0513516dffd9 rw,relatime - aufs none rw,si=caafa54f840a525 61 20 0:54 / /var/lib/docker/aufs/mnt/6b00d3b4f32b41997ec07412b5e18204f82fbe643e7122251cdeb3582abd424e-init rw,relatime - aufs none rw,si=caafa54f8408525 62 20 0:55 / /var/lib/docker/aufs/mnt/6b00d3b4f32b41997ec07412b5e18204f82fbe643e7122251cdeb3582abd424e rw,relatime - aufs none rw,si=caafa54f8409525 63 20 0:56 / /var/lib/docker/aufs/mnt/abd0b5ea5d355a67f911475e271924a5388ee60c27185fcd60d095afc4a09dc7 rw,relatime - aufs none rw,si=caafa54f9eb1525 64 20 0:57 / /var/lib/docker/aufs/mnt/336222effc3f7b89867bb39ff7792ae5412c35c749f127c29159d046b6feedd2-init rw,relatime - aufs none rw,si=caafa54f85bf525 65 20 0:58 / /var/lib/docker/aufs/mnt/336222effc3f7b89867bb39ff7792ae5412c35c749f127c29159d046b6feedd2 rw,relatime - aufs none rw,si=caafa54f85b8525 66 20 0:59 / /var/lib/docker/aufs/mnt/912e1bf28b80a09644503924a8a1a4fb8ed10b808ca847bda27a369919aa52fa rw,relatime - aufs none rw,si=caafa54fbaea525 67 20 0:60 / /var/lib/docker/aufs/mnt/386f722875013b4a875118367abc783fc6617a3cb7cf08b2b4dcf550b4b9c576-init rw,relatime - aufs none rw,si=caafa54f8472525 68 20 0:61 / /var/lib/docker/aufs/mnt/386f722875013b4a875118367abc783fc6617a3cb7cf08b2b4dcf550b4b9c576 rw,relatime - aufs none rw,si=caafa54f8474525 69 20 0:62 / /var/lib/docker/aufs/mnt/5aaebb79ef3097dfca377889aeb61a0c9d5e3795117d2b08d0751473c671dfb2 rw,relatime - aufs none rw,si=caafa54f8c5e525 70 20 0:63 / /var/lib/docker/aufs/mnt/5ba3e493279d01277d583600b81c7c079e691b73c3a2bdea8e4b12a35a418be2-init rw,relatime - aufs none rw,si=caafa54f8c3b525 71 20 0:64 / /var/lib/docker/aufs/mnt/5ba3e493279d01277d583600b81c7c079e691b73c3a2bdea8e4b12a35a418be2 rw,relatime - aufs none rw,si=caafa54f8c3d525 72 20 0:65 / /var/lib/docker/aufs/mnt/2777f0763da4de93f8bebbe1595cc77f739806a158657b033eca06f827b6028a rw,relatime - aufs none rw,si=caafa54f8c3e525 73 20 0:66 / /var/lib/docker/aufs/mnt/5d7445562acf73c6f0ae34c3dd0921d7457de1ba92a587d9e06a44fa209eeb3e-init rw,relatime - aufs none rw,si=caafa54f8c39525 74 20 0:67 / /var/lib/docker/aufs/mnt/5d7445562acf73c6f0ae34c3dd0921d7457de1ba92a587d9e06a44fa209eeb3e rw,relatime - aufs none rw,si=caafa54f854f525 75 20 0:68 / /var/lib/docker/aufs/mnt/06400b526ec18b66639c96efc41a84f4ae0b117cb28dafd56be420651b4084a0 rw,relatime - aufs none rw,si=caafa54f840b525 76 20 0:69 / /var/lib/docker/aufs/mnt/e051d45ec42d8e3e1cc57bb39871a40de486dc123522e9c067fbf2ca6a357785-init rw,relatime - aufs none rw,si=caafa54fdddf525 77 20 0:70 / /var/lib/docker/aufs/mnt/e051d45ec42d8e3e1cc57bb39871a40de486dc123522e9c067fbf2ca6a357785 rw,relatime - aufs none rw,si=caafa54f854b525 78 20 0:71 / /var/lib/docker/aufs/mnt/1ff414fa93fd61ec81b0ab7b365a841ff6545accae03cceac702833aaeaf718f rw,relatime - aufs none rw,si=caafa54f8d85525 79 20 0:72 / /var/lib/docker/aufs/mnt/c661b2f871dd5360e46a2aebf8f970f6d39a2ff64e06979aa0361227c88128b8-init rw,relatime - aufs none rw,si=caafa54f8da3525 80 20 0:73 / /var/lib/docker/aufs/mnt/c661b2f871dd5360e46a2aebf8f970f6d39a2ff64e06979aa0361227c88128b8 rw,relatime - aufs none rw,si=caafa54f8da2525 81 20 0:74 / /var/lib/docker/aufs/mnt/b68b1d4fe4d30016c552398e78b379a39f651661d8e1fa5f2460c24a5e723420 rw,relatime - aufs none rw,si=caafa54f8d81525 82 20 0:75 / /var/lib/docker/aufs/mnt/c5c5979c936cd0153a4c626fa9d69ce4fce7d924cc74fa68b025d2f585031739-init rw,relatime - aufs none rw,si=caafa54f8da1525 83 20 0:76 / /var/lib/docker/aufs/mnt/c5c5979c936cd0153a4c626fa9d69ce4fce7d924cc74fa68b025d2f585031739 rw,relatime - aufs none rw,si=caafa54f8da0525 84 20 0:77 / /var/lib/docker/aufs/mnt/53e10b0329afc0e0d3322d31efaed4064139dc7027fe6ae445cffd7104bcc94f rw,relatime - aufs none rw,si=caafa54f8c35525 85 20 0:78 / /var/lib/docker/aufs/mnt/3bfafd09ff2603e2165efacc2215c1f51afabba6c42d04a68cc2df0e8cc31494-init rw,relatime - aufs none rw,si=caafa54f8db8525 86 20 0:79 / /var/lib/docker/aufs/mnt/3bfafd09ff2603e2165efacc2215c1f51afabba6c42d04a68cc2df0e8cc31494 rw,relatime - aufs none rw,si=caafa54f8dba525 87 20 0:80 / /var/lib/docker/aufs/mnt/90fdd2c03eeaf65311f88f4200e18aef6d2772482712d9aea01cd793c64781b5 rw,relatime - aufs none rw,si=caafa54f8315525 88 20 0:81 / /var/lib/docker/aufs/mnt/7bdf2591c06c154ceb23f5e74b1d03b18fbf6fe96e35fbf539b82d446922442f-init rw,relatime - aufs none rw,si=caafa54f8fc6525 89 20 0:82 / /var/lib/docker/aufs/mnt/7bdf2591c06c154ceb23f5e74b1d03b18fbf6fe96e35fbf539b82d446922442f rw,relatime - aufs none rw,si=caafa54f8468525 90 20 0:83 / /var/lib/docker/aufs/mnt/8cf9a993f50f3305abad3da268c0fc44ff78a1e7bba595ef9de963497496c3f9 rw,relatime - aufs none rw,si=caafa54f8c59525 91 20 0:84 / /var/lib/docker/aufs/mnt/ecc896fd74b21840a8d35e8316b92a08b1b9c83d722a12acff847e9f0ff17173-init rw,relatime - aufs none rw,si=caafa54f846a525 92 20 0:85 / /var/lib/docker/aufs/mnt/ecc896fd74b21840a8d35e8316b92a08b1b9c83d722a12acff847e9f0ff17173 rw,relatime - aufs none rw,si=caafa54f846b525 93 20 0:86 / /var/lib/docker/aufs/mnt/d8c8288ec920439a48b5796bab5883ee47a019240da65e8d8f33400c31bac5df rw,relatime - aufs none rw,si=caafa54f8dbf525 94 20 0:87 / /var/lib/docker/aufs/mnt/ecba66710bcd03199b9398e46c005cd6b68d0266ec81dc8b722a29cc417997c6-init rw,relatime - aufs none rw,si=caafa54f810f525 95 20 0:88 / /var/lib/docker/aufs/mnt/ecba66710bcd03199b9398e46c005cd6b68d0266ec81dc8b722a29cc417997c6 rw,relatime - aufs none rw,si=caafa54fbae9525 96 20 0:89 / /var/lib/docker/aufs/mnt/befc1c67600df449dddbe796c0d06da7caff1d2bbff64cde1f0ba82d224996b5 rw,relatime - aufs none rw,si=caafa54f8dab525 97 20 0:90 / /var/lib/docker/aufs/mnt/c9f470e73d2742629cdc4084a1b2c1a8302914f2aa0d0ec4542371df9a050562-init rw,relatime - aufs none rw,si=caafa54fdc02525 98 20 0:91 / /var/lib/docker/aufs/mnt/c9f470e73d2742629cdc4084a1b2c1a8302914f2aa0d0ec4542371df9a050562 rw,relatime - aufs none rw,si=caafa54f9eb0525 99 20 0:92 / /var/lib/docker/aufs/mnt/2a31f10029f04ff9d4381167a9b739609853d7220d55a56cb654779a700ee246 rw,relatime - aufs none rw,si=caafa54f8c37525 100 20 0:93 / /var/lib/docker/aufs/mnt/8c4261b8e3e4b21ebba60389bd64b6261217e7e6b9fd09e201d5a7f6760f6927-init rw,relatime - aufs none rw,si=caafa54fd173525 101 20 0:94 / /var/lib/docker/aufs/mnt/8c4261b8e3e4b21ebba60389bd64b6261217e7e6b9fd09e201d5a7f6760f6927 rw,relatime - aufs none rw,si=caafa54f8108525 102 20 0:95 / /var/lib/docker/aufs/mnt/eaa0f57403a3dc685268f91df3fbcd7a8423cee50e1a9ee5c3e1688d9d676bb4 rw,relatime - aufs none rw,si=caafa54f852d525 103 20 0:96 / /var/lib/docker/aufs/mnt/9cfe69a2cbffd9bfc7f396d4754f6fe5cc457ef417b277797be3762dfe955a6b-init rw,relatime - aufs none rw,si=caafa54f8d80525 104 20 0:97 / /var/lib/docker/aufs/mnt/9cfe69a2cbffd9bfc7f396d4754f6fe5cc457ef417b277797be3762dfe955a6b rw,relatime - aufs none rw,si=caafa54f8fc3525 105 20 0:98 / /var/lib/docker/aufs/mnt/d1b322ae17613c6adee84e709641a9244ac56675244a89a64dc0075075fcbb83 rw,relatime - aufs none rw,si=caafa54f8c58525 106 20 0:99 / /var/lib/docker/aufs/mnt/d46c2a8e9da7e91ab34fd9c192851c246a4e770a46720bda09e55c7554b9dbbd-init rw,relatime - aufs none rw,si=caafa54f8c63525 107 20 0:100 / /var/lib/docker/aufs/mnt/d46c2a8e9da7e91ab34fd9c192851c246a4e770a46720bda09e55c7554b9dbbd rw,relatime - aufs none rw,si=caafa54f8c67525 108 20 0:101 / /var/lib/docker/aufs/mnt/bc9d2a264158f83a617a069bf17cbbf2a2ba453db7d3951d9dc63cc1558b1c2b rw,relatime - aufs none rw,si=caafa54f8dbe525 109 20 0:102 / /var/lib/docker/aufs/mnt/9e6abb8d72bbeb4d5cf24b96018528015ba830ce42b4859965bd482cbd034e99-init rw,relatime - aufs none rw,si=caafa54f9e0d525 110 20 0:103 / /var/lib/docker/aufs/mnt/9e6abb8d72bbeb4d5cf24b96018528015ba830ce42b4859965bd482cbd034e99 rw,relatime - aufs none rw,si=caafa54f9e1b525 111 20 0:104 / /var/lib/docker/aufs/mnt/d4dca7b02569c732e740071e1c654d4ad282de5c41edb619af1f0aafa618be26 rw,relatime - aufs none rw,si=caafa54f8dae525 112 20 0:105 / /var/lib/docker/aufs/mnt/fea63da40fa1c5ffbad430dde0bc64a8fc2edab09a051fff55b673c40a08f6b7-init rw,relatime - aufs none rw,si=caafa54f8c5c525 113 20 0:106 / /var/lib/docker/aufs/mnt/fea63da40fa1c5ffbad430dde0bc64a8fc2edab09a051fff55b673c40a08f6b7 rw,relatime - aufs none rw,si=caafa54fd172525 114 20 0:107 / /var/lib/docker/aufs/mnt/e60c57499c0b198a6734f77f660cdbbd950a5b78aa23f470ca4f0cfcc376abef rw,relatime - aufs none rw,si=caafa54909c4525 115 20 0:108 / /var/lib/docker/aufs/mnt/099c78e7ccd9c8717471bb1bbfff838c0a9913321ba2f214fbeaf92c678e5b35-init rw,relatime - aufs none rw,si=caafa54909c3525 116 20 0:109 / /var/lib/docker/aufs/mnt/099c78e7ccd9c8717471bb1bbfff838c0a9913321ba2f214fbeaf92c678e5b35 rw,relatime - aufs none rw,si=caafa54909c7525 117 20 0:110 / /var/lib/docker/aufs/mnt/2997be666d58b9e71469759bcb8bd9608dad0e533a1a7570a896919ba3388825 rw,relatime - aufs none rw,si=caafa54f8557525 118 20 0:111 / /var/lib/docker/aufs/mnt/730694eff438ef20569df38dfb38a920969d7ff2170cc9aa7cb32a7ed8147a93-init rw,relatime - aufs none rw,si=caafa54c6e88525 119 20 0:112 / /var/lib/docker/aufs/mnt/730694eff438ef20569df38dfb38a920969d7ff2170cc9aa7cb32a7ed8147a93 rw,relatime - aufs none rw,si=caafa54c6e8e525 120 20 0:113 / /var/lib/docker/aufs/mnt/a672a1e2f2f051f6e19ed1dfbe80860a2d774174c49f7c476695f5dd1d5b2f67 rw,relatime - aufs none rw,si=caafa54c6e15525 121 20 0:114 / /var/lib/docker/aufs/mnt/aba3570e17859f76cf29d282d0d150659c6bd80780fdc52a465ba05245c2a420-init rw,relatime - aufs none rw,si=caafa54f8dad525 122 20 0:115 / /var/lib/docker/aufs/mnt/aba3570e17859f76cf29d282d0d150659c6bd80780fdc52a465ba05245c2a420 rw,relatime - aufs none rw,si=caafa54f8d84525 123 20 0:116 / /var/lib/docker/aufs/mnt/2abc86007aca46fb4a817a033e2a05ccacae40b78ea4b03f8ea616b9ada40e2e rw,relatime - aufs none rw,si=caafa54c6e8b525 124 20 0:117 / /var/lib/docker/aufs/mnt/36352f27f7878e648367a135bd1ec3ed497adcb8ac13577ee892a0bd921d2374-init rw,relatime - aufs none rw,si=caafa54c6e8d525 125 20 0:118 / /var/lib/docker/aufs/mnt/36352f27f7878e648367a135bd1ec3ed497adcb8ac13577ee892a0bd921d2374 rw,relatime - aufs none rw,si=caafa54f8c34525 126 20 0:119 / /var/lib/docker/aufs/mnt/2f95ca1a629cea8363b829faa727dd52896d5561f2c96ddee4f697ea2fc872c2 rw,relatime - aufs none rw,si=caafa54c6e8a525 127 20 0:120 / /var/lib/docker/aufs/mnt/f108c8291654f179ef143a3e07de2b5a34adbc0b28194a0ab17742b6db9a7fb2-init rw,relatime - aufs none rw,si=caafa54f8e19525 128 20 0:121 / /var/lib/docker/aufs/mnt/f108c8291654f179ef143a3e07de2b5a34adbc0b28194a0ab17742b6db9a7fb2 rw,relatime - aufs none rw,si=caafa54fa8c6525 129 20 0:122 / /var/lib/docker/aufs/mnt/c1d04dfdf8cccb3676d5a91e84e9b0781ce40623d127d038bcfbe4c761b27401 rw,relatime - aufs none rw,si=caafa54f8c30525 130 20 0:123 / /var/lib/docker/aufs/mnt/3f4898ffd0e1239aeebf1d1412590cdb7254207fa3883663e2c40cf772e5f05a-init rw,relatime - aufs none rw,si=caafa54c6e1a525 131 20 0:124 / /var/lib/docker/aufs/mnt/3f4898ffd0e1239aeebf1d1412590cdb7254207fa3883663e2c40cf772e5f05a rw,relatime - aufs none rw,si=caafa54c6e1c525 132 20 0:125 / /var/lib/docker/aufs/mnt/5ae3b6fccb1539fc02d420e86f3e9637bef5b711fed2ca31a2f426c8f5deddbf rw,relatime - aufs none rw,si=caafa54c4fea525 133 20 0:126 / /var/lib/docker/aufs/mnt/310bfaf80d57020f2e73b06aeffb0b9b0ca2f54895f88bf5e4d1529ccac58fe0-init rw,relatime - aufs none rw,si=caafa54c6e1e525 134 20 0:127 / /var/lib/docker/aufs/mnt/310bfaf80d57020f2e73b06aeffb0b9b0ca2f54895f88bf5e4d1529ccac58fe0 rw,relatime - aufs none rw,si=caafa54fa8c0525 135 20 0:128 / /var/lib/docker/aufs/mnt/f382bd5aaccaf2d04a59089ac7cb12ec87efd769fd0c14d623358fbfd2a3f896 rw,relatime - aufs none rw,si=caafa54c4fec525 136 20 0:129 / /var/lib/docker/aufs/mnt/50d45e9bb2d779bc6362824085564c7578c231af5ae3b3da116acf7e17d00735-init rw,relatime - aufs none rw,si=caafa54c4fef525 137 20 0:130 / /var/lib/docker/aufs/mnt/50d45e9bb2d779bc6362824085564c7578c231af5ae3b3da116acf7e17d00735 rw,relatime - aufs none rw,si=caafa54c4feb525 138 20 0:131 / /var/lib/docker/aufs/mnt/a9c5ee0854dc083b6bf62b7eb1e5291aefbb10702289a446471ce73aba0d5d7d rw,relatime - aufs none rw,si=caafa54909c6525 139 20 0:134 / /var/lib/docker/aufs/mnt/03a613e7bd5078819d1fd92df4e671c0127559a5e0b5a885cc8d5616875162f0-init rw,relatime - aufs none rw,si=caafa54804fe525 140 20 0:135 / /var/lib/docker/aufs/mnt/03a613e7bd5078819d1fd92df4e671c0127559a5e0b5a885cc8d5616875162f0 rw,relatime - aufs none rw,si=caafa54804fa525 141 20 0:136 / /var/lib/docker/aufs/mnt/7ec3277e5c04c907051caf9c9c35889f5fcd6463e5485971b25404566830bb70 rw,relatime - aufs none rw,si=caafa54804f9525 142 20 0:139 / /var/lib/docker/aufs/mnt/26b5b5d71d79a5b2bfcf8bc4b2280ee829f261eb886745dd90997ed410f7e8b8-init rw,relatime - aufs none rw,si=caafa54c6ef6525 143 20 0:140 / /var/lib/docker/aufs/mnt/26b5b5d71d79a5b2bfcf8bc4b2280ee829f261eb886745dd90997ed410f7e8b8 rw,relatime - aufs none rw,si=caafa54c6ef5525 144 20 0:356 / /var/lib/docker/aufs/mnt/e6ecde9e2c18cd3c75f424c67b6d89685cfee0fc67abf2cb6bdc0867eb998026 rw,relatime - aufs none rw,si=caafa548068e525` gentooMountinfo = `15 1 8:6 / / rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered 16 15 0:3 / /proc rw,nosuid,nodev,noexec,relatime - proc proc rw 17 15 0:14 / /run rw,nosuid,nodev,relatime - tmpfs tmpfs rw,size=3292172k,mode=755 18 15 0:5 / /dev rw,nosuid,relatime - devtmpfs udev rw,size=10240k,nr_inodes=4106451,mode=755 19 18 0:12 / /dev/mqueue rw,nosuid,nodev,noexec,relatime - mqueue mqueue rw 20 18 0:10 / /dev/pts rw,nosuid,noexec,relatime - devpts devpts rw,gid=5,mode=620,ptmxmode=000 21 18 0:15 / /dev/shm rw,nosuid,nodev,noexec,relatime - tmpfs shm rw 22 15 0:16 / /sys rw,nosuid,nodev,noexec,relatime - sysfs sysfs rw 23 22 0:7 / /sys/kernel/debug rw,nosuid,nodev,noexec,relatime - debugfs debugfs rw 24 22 0:17 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs cgroup_root rw,size=10240k,mode=755 25 24 0:18 / /sys/fs/cgroup/openrc rw,nosuid,nodev,noexec,relatime - cgroup openrc rw,release_agent=/lib64/rc/sh/cgroup-release-agent.sh,name=openrc 26 24 0:19 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime - cgroup cpuset rw,cpuset,clone_children 27 24 0:20 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime - cgroup cpu rw,cpu,clone_children 28 24 0:21 / /sys/fs/cgroup/cpuacct rw,nosuid,nodev,noexec,relatime - cgroup cpuacct rw,cpuacct,clone_children 29 24 0:22 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup memory rw,memory,clone_children 30 24 0:23 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime - cgroup devices rw,devices,clone_children 31 24 0:24 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime - cgroup freezer rw,freezer,clone_children 32 24 0:25 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime - cgroup blkio rw,blkio,clone_children 33 15 8:1 / /boot rw,noatime,nodiratime - vfat /dev/sda1 rw,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro 34 15 8:18 / /mnt/xfs rw,noatime,nodiratime - xfs /dev/sdb2 rw,attr2,inode64,noquota 35 15 0:26 / /tmp rw,relatime - tmpfs tmpfs rw 36 16 0:27 / /proc/sys/fs/binfmt_misc rw,nosuid,nodev,noexec,relatime - binfmt_misc binfmt_misc rw 42 15 0:33 / /var/lib/nfs/rpc_pipefs rw,relatime - rpc_pipefs rpc_pipefs rw 43 16 0:34 / /proc/fs/nfsd rw,nosuid,nodev,noexec,relatime - nfsd nfsd rw 44 15 0:35 / /home/tianon/.gvfs rw,nosuid,nodev,relatime - fuse.gvfs-fuse-daemon gvfs-fuse-daemon rw,user_id=1000,group_id=1000 68 15 0:3336 / /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd rw,relatime - aufs none rw,si=9b4a7640128db39c 85 68 8:6 /var/lib/docker/init/dockerinit-0.7.2-dev//deleted /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/.dockerinit rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered 86 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/config.env /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/.dockerenv rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered 87 68 8:6 /etc/resolv.conf /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/resolv.conf rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered 88 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/hostname /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/hostname rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered 89 68 8:6 /var/lib/docker/containers/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/hosts /var/lib/docker/aufs/mnt/3597a1a6d6298c1decc339ebb90aad6f7d6ba2e15af3131b1f85e7ee4787a0cd/etc/hosts rw,noatime,nodiratime - ext4 /dev/sda6 rw,data=ordered 38 15 0:3384 / /var/lib/docker/aufs/mnt/0292005a9292401bb5197657f2b682d97d8edcb3b72b5e390d2a680139985b55 rw,relatime - aufs none rw,si=9b4a7642b584939c 39 15 0:3385 / /var/lib/docker/aufs/mnt/59db98c889de5f71b70cfb82c40cbe47b64332f0f56042a2987a9e5df6e5e3aa rw,relatime - aufs none rw,si=9b4a7642b584e39c 40 15 0:3386 / /var/lib/docker/aufs/mnt/0545f0f2b6548eb9601d08f35a08f5a0a385407d36027a28f58e06e9f61e0278 rw,relatime - aufs none rw,si=9b4a7642b584b39c 41 15 0:3387 / /var/lib/docker/aufs/mnt/d882cfa16d1aa8fe0331a36e79be3d80b151e49f24fc39a39c3fed1735d5feb5 rw,relatime - aufs none rw,si=9b4a76453040039c 45 15 0:3388 / /var/lib/docker/aufs/mnt/055ca3befcb1626e74f5344b3398724ff05c0de0e20021683d04305c9e70a3f6 rw,relatime - aufs none rw,si=9b4a76453040739c 46 15 0:3389 / /var/lib/docker/aufs/mnt/b899e4567a351745d4285e7f1c18fdece75d877deb3041981cd290be348b7aa6 rw,relatime - aufs none rw,si=9b4a7647def4039c 47 15 0:3390 / /var/lib/docker/aufs/mnt/067ca040292c58954c5129f953219accfae0d40faca26b4d05e76ca76a998f16 rw,relatime - aufs none rw,si=9b4a7647def4239c 48 15 0:3391 / /var/lib/docker/aufs/mnt/8c995e7cb6e5082742daeea720e340b021d288d25d92e0412c03d200df308a11 rw,relatime - aufs none rw,si=9b4a764479c1639c 49 15 0:3392 / /var/lib/docker/aufs/mnt/07cc54dfae5b45300efdacdd53cc72c01b9044956a86ce7bff42d087e426096d rw,relatime - aufs none rw,si=9b4a764479c1739c 50 15 0:3393 / /var/lib/docker/aufs/mnt/0a9c95cf4c589c05b06baa79150b0cc1d8e7102759fe3ce4afaabb8247ca4f85 rw,relatime - aufs none rw,si=9b4a7644059c839c 51 15 0:3394 / /var/lib/docker/aufs/mnt/468fa98cececcf4e226e8370f18f4f848d63faf287fb8321a07f73086441a3a0 rw,relatime - aufs none rw,si=9b4a7644059ca39c 52 15 0:3395 / /var/lib/docker/aufs/mnt/0b826192231c5ce066fffb5beff4397337b5fc19a377aa7c6282c7c0ce7f111f rw,relatime - aufs none rw,si=9b4a764479c1339c 53 15 0:3396 / /var/lib/docker/aufs/mnt/93b8ba1b772fbe79709b909c43ea4b2c30d712e53548f467db1ffdc7a384f196 rw,relatime - aufs none rw,si=9b4a7640798a739c 54 15 0:3397 / /var/lib/docker/aufs/mnt/0c0d0acfb506859b12ef18cdfef9ebed0b43a611482403564224bde9149d373c rw,relatime - aufs none rw,si=9b4a7640798a039c 55 15 0:3398 / /var/lib/docker/aufs/mnt/33648c39ab6c7c74af0243d6d6a81b052e9e25ad1e04b19892eb2dde013e358b rw,relatime - aufs none rw,si=9b4a7644b439b39c 56 15 0:3399 / /var/lib/docker/aufs/mnt/0c12bea97a1c958a3c739fb148536c1c89351d48e885ecda8f0499b5cc44407e rw,relatime - aufs none rw,si=9b4a7640798a239c 57 15 0:3400 / /var/lib/docker/aufs/mnt/ed443988ce125f172d7512e84a4de2627405990fd767a16adefa8ce700c19ce8 rw,relatime - aufs none rw,si=9b4a7644c8ed339c 59 15 0:3402 / /var/lib/docker/aufs/mnt/f61612c324ff3c924d3f7a82fb00a0f8d8f73c248c41897061949e9f5ab7e3b1 rw,relatime - aufs none rw,si=9b4a76442810c39c 60 15 0:3403 / /var/lib/docker/aufs/mnt/0f1ee55c6c4e25027b80de8e64b8b6fb542b3b41aa0caab9261da75752e22bfd rw,relatime - aufs none rw,si=9b4a76442810e39c 61 15 0:3404 / /var/lib/docker/aufs/mnt/956f6cc4af5785cb3ee6963dcbca668219437d9b28f513290b1453ac64a34f97 rw,relatime - aufs none rw,si=9b4a7644303ec39c 62 15 0:3405 / /var/lib/docker/aufs/mnt/1099769158c4b4773e2569e38024e8717e400f87a002c41d8cf47cb81b051ba6 rw,relatime - aufs none rw,si=9b4a7644303ee39c 63 15 0:3406 / /var/lib/docker/aufs/mnt/11890ceb98d4442595b676085cd7b21550ab85c5df841e0fba997ff54e3d522d rw,relatime - aufs none rw,si=9b4a7644303ed39c 64 15 0:3407 / /var/lib/docker/aufs/mnt/acdb90dc378e8ed2420b43a6d291f1c789a081cd1904018780cc038fcd7aae53 rw,relatime - aufs none rw,si=9b4a76434be2139c 65 15 0:3408 / /var/lib/docker/aufs/mnt/120e716f19d4714fbe63cc1ed246204f2c1106eefebc6537ba2587d7e7711959 rw,relatime - aufs none rw,si=9b4a76434be2339c 66 15 0:3409 / /var/lib/docker/aufs/mnt/b197b7fffb61d89e0ba1c40de9a9fc0d912e778b3c1bd828cf981ff37c1963bc rw,relatime - aufs none rw,si=9b4a76434be2039c 70 15 0:3412 / /var/lib/docker/aufs/mnt/1434b69d2e1bb18a9f0b96b9cdac30132b2688f5d1379f68a39a5e120c2f93eb rw,relatime - aufs none rw,si=9b4a76434be2639c 71 15 0:3413 / /var/lib/docker/aufs/mnt/16006e83caf33ab5eb0cd6afc92ea2ee8edeff897496b0bb3ec3a75b767374b3 rw,relatime - aufs none rw,si=9b4a7644d790439c 72 15 0:3414 / /var/lib/docker/aufs/mnt/55bfa5f44e94d27f91f79ba901b118b15098449165c87abf1b53ffff147ff164 rw,relatime - aufs none rw,si=9b4a7644d790239c 73 15 0:3415 / /var/lib/docker/aufs/mnt/1912b97a07ab21ccd98a2a27bc779bf3cf364a3138afa3c3e6f7f169a3c3eab5 rw,relatime - aufs none rw,si=9b4a76441822739c 76 15 0:3418 / /var/lib/docker/aufs/mnt/1a7c3292e8879bd91ffd9282e954f643b1db5683093574c248ff14a9609f2f56 rw,relatime - aufs none rw,si=9b4a76438cb7239c 77 15 0:3419 / /var/lib/docker/aufs/mnt/bb1faaf0d076ddba82c2318305a85f490dafa4e8a8640a8db8ed657c439120cc rw,relatime - aufs none rw,si=9b4a76438cb7339c 78 15 0:3420 / /var/lib/docker/aufs/mnt/1ab869f21d2241a73ac840c7f988490313f909ac642eba71d092204fec66dd7c rw,relatime - aufs none rw,si=9b4a76438cb7639c 79 15 0:3421 / /var/lib/docker/aufs/mnt/fd7245b2cfe3890fa5f5b452260e4edf9e7fb7746532ed9d83f7a0d7dbaa610e rw,relatime - aufs none rw,si=9b4a7644bdc0139c 80 15 0:3422 / /var/lib/docker/aufs/mnt/1e5686c5301f26b9b3cd24e322c608913465cc6c5d0dcd7c5e498d1314747d61 rw,relatime - aufs none rw,si=9b4a7644bdc0639c 81 15 0:3423 / /var/lib/docker/aufs/mnt/52edf6ee6e40bfec1e9301a4d4a92ab83d144e2ae4ce5099e99df6138cb844bf rw,relatime - aufs none rw,si=9b4a7644bdc0239c 82 15 0:3424 / /var/lib/docker/aufs/mnt/1ea10fb7085d28cda4904657dff0454e52598d28e1d77e4f2965bbc3666e808f rw,relatime - aufs none rw,si=9b4a76438cb7139c 83 15 0:3425 / /var/lib/docker/aufs/mnt/9c03e98c3593946dbd4087f8d83f9ca262f4a2efdc952ce60690838b9ba6c526 rw,relatime - aufs none rw,si=9b4a76443020639c 84 15 0:3426 / /var/lib/docker/aufs/mnt/220a2344d67437602c6d2cee9a98c46be13f82c2a8063919dd2fad52bf2fb7dd rw,relatime - aufs none rw,si=9b4a76434bff339c 94 15 0:3427 / /var/lib/docker/aufs/mnt/3b32876c5b200312c50baa476ff342248e88c8ea96e6a1032cd53a88738a1cf2 rw,relatime - aufs none rw,si=9b4a76434bff139c 95 15 0:3428 / /var/lib/docker/aufs/mnt/23ee2b8b0d4ae8db6f6d1e168e2c6f79f8a18f953b09f65e0d22cc1e67a3a6fa rw,relatime - aufs none rw,si=9b4a7646c305c39c 96 15 0:3429 / /var/lib/docker/aufs/mnt/e86e6daa70b61b57945fa178222615f3c3d6bcef12c9f28e9f8623d44dc2d429 rw,relatime - aufs none rw,si=9b4a7646c305f39c 97 15 0:3430 / /var/lib/docker/aufs/mnt/2413d07623e80860bb2e9e306fbdee699afd07525785c025c591231e864aa162 rw,relatime - aufs none rw,si=9b4a76434bff039c 98 15 0:3431 / /var/lib/docker/aufs/mnt/adfd622eb22340fc80b429e5564b125668e260bf9068096c46dd59f1386a4b7d rw,relatime - aufs none rw,si=9b4a7646a7a1039c 102 15 0:3435 / /var/lib/docker/aufs/mnt/27cd92e7a91d02e2d6b44d16679a00fb6d169b19b88822891084e7fd1a84882d rw,relatime - aufs none rw,si=9b4a7646f25ec39c 103 15 0:3436 / /var/lib/docker/aufs/mnt/27dfdaf94cfbf45055c748293c37dd68d9140240bff4c646cb09216015914a88 rw,relatime - aufs none rw,si=9b4a7646732f939c 104 15 0:3437 / /var/lib/docker/aufs/mnt/5ed7524aff68dfbf0fc601cbaeac01bab14391850a973dabf3653282a627920f rw,relatime - aufs none rw,si=9b4a7646732f839c 105 15 0:3438 / /var/lib/docker/aufs/mnt/2a0d4767e536beb5785b60e071e3ac8e5e812613ab143a9627bee77d0c9ab062 rw,relatime - aufs none rw,si=9b4a7646732fe39c 106 15 0:3439 / /var/lib/docker/aufs/mnt/dea3fc045d9f4ae51ba952450b948a822cf85c39411489ca5224f6d9a8d02bad rw,relatime - aufs none rw,si=9b4a764012ad839c 107 15 0:3440 / /var/lib/docker/aufs/mnt/2d140a787160798da60cb67c21b1210054ad4dafecdcf832f015995b9aa99cfd rw,relatime - aufs none rw,si=9b4a764012add39c 108 15 0:3441 / /var/lib/docker/aufs/mnt/cb190b2a8e984475914430fbad2382e0d20b9b659f8ef83ae8d170cc672e519c rw,relatime - aufs none rw,si=9b4a76454d9c239c 109 15 0:3442 / /var/lib/docker/aufs/mnt/2f4a012d5a7ffd90256a6e9aa479054b3dddbc3c6a343f26dafbf3196890223b rw,relatime - aufs none rw,si=9b4a76454d9c439c 110 15 0:3443 / /var/lib/docker/aufs/mnt/63cc77904b80c4ffbf49cb974c5d8733dc52ad7640d3ae87554b325d7312d87f rw,relatime - aufs none rw,si=9b4a76454d9c339c 111 15 0:3444 / /var/lib/docker/aufs/mnt/30333e872c451482ea2d235ff2192e875bd234006b238ae2bdde3b91a86d7522 rw,relatime - aufs none rw,si=9b4a76422cebf39c 112 15 0:3445 / /var/lib/docker/aufs/mnt/6c54fc1125da3925cae65b5c9a98f3be55b0a2c2666082e5094a4ba71beb5bff rw,relatime - aufs none rw,si=9b4a7646dd5a439c 113 15 0:3446 / /var/lib/docker/aufs/mnt/3087d48cb01cda9d0a83a9ca301e6ea40e8593d18c4921be4794c91a420ab9a3 rw,relatime - aufs none rw,si=9b4a7646dd5a739c 114 15 0:3447 / /var/lib/docker/aufs/mnt/cc2607462a8f55b179a749b144c3fdbb50678e1a4f3065ea04e283e9b1f1d8e2 rw,relatime - aufs none rw,si=9b4a7646dd5a239c 117 15 0:3450 / /var/lib/docker/aufs/mnt/310c5e8392b29e8658a22e08d96d63936633b7e2c38e8d220047928b00a03d24 rw,relatime - aufs none rw,si=9b4a7647932d739c 118 15 0:3451 / /var/lib/docker/aufs/mnt/38a1f0029406ba9c3b6058f2f406d8a1d23c855046cf355c91d87d446fcc1460 rw,relatime - aufs none rw,si=9b4a76445abc939c 119 15 0:3452 / /var/lib/docker/aufs/mnt/42e109ab7914ae997a11ccd860fd18e4d488c50c044c3240423ce15774b8b62e rw,relatime - aufs none rw,si=9b4a76445abca39c 120 15 0:3453 / /var/lib/docker/aufs/mnt/365d832af0402d052b389c1e9c0d353b48487533d20cd4351df8e24ec4e4f9d8 rw,relatime - aufs none rw,si=9b4a7644066aa39c 121 15 0:3454 / /var/lib/docker/aufs/mnt/d3fa8a24d695b6cda9b64f96188f701963d28bef0473343f8b212df1a2cf1d2b rw,relatime - aufs none rw,si=9b4a7644066af39c 122 15 0:3455 / /var/lib/docker/aufs/mnt/37d4f491919abc49a15d0c7a7cc8383f087573525d7d288accd14f0b4af9eae0 rw,relatime - aufs none rw,si=9b4a7644066ad39c 123 15 0:3456 / /var/lib/docker/aufs/mnt/93902707fe12cbdd0068ce73f2baad4b3a299189b1b19cb5f8a2025e106ae3f5 rw,relatime - aufs none rw,si=9b4a76444445f39c 126 15 0:3459 / /var/lib/docker/aufs/mnt/3b49291670a625b9bbb329ffba99bf7fa7abff80cefef040f8b89e2b3aad4f9f rw,relatime - aufs none rw,si=9b4a7640798a339c 127 15 0:3460 / /var/lib/docker/aufs/mnt/8d9c7b943cc8f854f4d0d4ec19f7c16c13b0cc4f67a41472a072648610cecb59 rw,relatime - aufs none rw,si=9b4a76427383039c 128 15 0:3461 / /var/lib/docker/aufs/mnt/3b6c90036526c376307df71d49c9f5fce334c01b926faa6a78186842de74beac rw,relatime - aufs none rw,si=9b4a7644badd439c 130 15 0:3463 / /var/lib/docker/aufs/mnt/7b24158eeddfb5d31b7e932e406ea4899fd728344335ff8e0765e89ddeb351dd rw,relatime - aufs none rw,si=9b4a7644badd539c 131 15 0:3464 / /var/lib/docker/aufs/mnt/3ead6dd5773765c74850cf6c769f21fe65c29d622ffa712664f9f5b80364ce27 rw,relatime - aufs none rw,si=9b4a7642f469939c 132 15 0:3465 / /var/lib/docker/aufs/mnt/3f825573b29547744a37b65597a9d6d15a8350be4429b7038d126a4c9a8e178f rw,relatime - aufs none rw,si=9b4a7642f469c39c 133 15 0:3466 / /var/lib/docker/aufs/mnt/f67aaaeb3681e5dcb99a41f847087370bd1c206680cb8c7b6a9819fd6c97a331 rw,relatime - aufs none rw,si=9b4a7647cc25939c 134 15 0:3467 / /var/lib/docker/aufs/mnt/41afe6cfb3c1fc2280b869db07699da88552786e28793f0bc048a265c01bd942 rw,relatime - aufs none rw,si=9b4a7647cc25c39c 135 15 0:3468 / /var/lib/docker/aufs/mnt/b8092ea59da34a40b120e8718c3ae9fa8436996edc4fc50e4b99c72dfd81e1af rw,relatime - aufs none rw,si=9b4a76445abc439c 136 15 0:3469 / /var/lib/docker/aufs/mnt/42c69d2cc179e2684458bb8596a9da6dad182c08eae9b74d5f0e615b399f75a5 rw,relatime - aufs none rw,si=9b4a76455ddbe39c 137 15 0:3470 / /var/lib/docker/aufs/mnt/ea0871954acd2d62a211ac60e05969622044d4c74597870c4f818fbb0c56b09b rw,relatime - aufs none rw,si=9b4a76455ddbf39c 138 15 0:3471 / /var/lib/docker/aufs/mnt/4307906b275ab3fc971786b3841ae3217ac85b6756ddeb7ad4ba09cd044c2597 rw,relatime - aufs none rw,si=9b4a76455ddb839c 139 15 0:3472 / /var/lib/docker/aufs/mnt/4390b872928c53500a5035634f3421622ed6299dc1472b631fc45de9f56dc180 rw,relatime - aufs none rw,si=9b4a76402f2fd39c 140 15 0:3473 / /var/lib/docker/aufs/mnt/6bb41e78863b85e4aa7da89455314855c8c3bda64e52a583bab15dc1fa2e80c2 rw,relatime - aufs none rw,si=9b4a76402f2fa39c 141 15 0:3474 / /var/lib/docker/aufs/mnt/4444f583c2a79c66608f4673a32c9c812154f027045fbd558c2d69920c53f835 rw,relatime - aufs none rw,si=9b4a764479dbd39c 142 15 0:3475 / /var/lib/docker/aufs/mnt/6f11883af4a05ea362e0c54df89058da4859f977efd07b6f539e1f55c1d2a668 rw,relatime - aufs none rw,si=9b4a76402f30b39c 143 15 0:3476 / /var/lib/docker/aufs/mnt/453490dd32e7c2e9ef906f995d8fb3c2753923d1a5e0ba3fd3296e2e4dc238e7 rw,relatime - aufs none rw,si=9b4a76402f30c39c 144 15 0:3477 / /var/lib/docker/aufs/mnt/45e5945735ee102b5e891c91650c57ec4b52bb53017d68f02d50ea8a6e230610 rw,relatime - aufs none rw,si=9b4a76423260739c 147 15 0:3480 / /var/lib/docker/aufs/mnt/4727a64a5553a1125f315b96bed10d3073d6988225a292cce732617c925b56ab rw,relatime - aufs none rw,si=9b4a76443030339c 150 15 0:3483 / /var/lib/docker/aufs/mnt/4e348b5187b9a567059306afc72d42e0ec5c893b0d4abd547526d5f9b6fb4590 rw,relatime - aufs none rw,si=9b4a7644f5d8c39c 151 15 0:3484 / /var/lib/docker/aufs/mnt/4efc616bfbc3f906718b052da22e4335f8e9f91ee9b15866ed3a8029645189ef rw,relatime - aufs none rw,si=9b4a7644f5d8939c 152 15 0:3485 / /var/lib/docker/aufs/mnt/83e730ae9754d5adb853b64735472d98dfa17136b8812ac9cfcd1eba7f4e7d2d rw,relatime - aufs none rw,si=9b4a76469aa7139c 153 15 0:3486 / /var/lib/docker/aufs/mnt/4fc5ba8a5b333be2b7eefacccb626772eeec0ae8a6975112b56c9fb36c0d342f rw,relatime - aufs none rw,si=9b4a7640128dc39c 154 15 0:3487 / /var/lib/docker/aufs/mnt/50200d5edff5dfe8d1ef3c78b0bbd709793ac6e936aa16d74ff66f7ea577b6f9 rw,relatime - aufs none rw,si=9b4a7640128da39c 155 15 0:3488 / /var/lib/docker/aufs/mnt/51e5e51604361448f0b9777f38329f414bc5ba9cf238f26d465ff479bd574b61 rw,relatime - aufs none rw,si=9b4a76444f68939c 156 15 0:3489 / /var/lib/docker/aufs/mnt/52a142149aa98bba83df8766bbb1c629a97b9799944ead90dd206c4bdf0b8385 rw,relatime - aufs none rw,si=9b4a76444f68b39c 157 15 0:3490 / /var/lib/docker/aufs/mnt/52dd21a94a00f58a1ed489312fcfffb91578089c76c5650364476f1d5de031bc rw,relatime - aufs none rw,si=9b4a76444f68f39c 158 15 0:3491 / /var/lib/docker/aufs/mnt/ee562415ddaad353ed22c88d0ca768a0c74bfba6333b6e25c46849ee22d990da rw,relatime - aufs none rw,si=9b4a7640128d839c 159 15 0:3492 / /var/lib/docker/aufs/mnt/db47a9e87173f7554f550c8a01891de79cf12acdd32e01f95c1a527a08bdfb2c rw,relatime - aufs none rw,si=9b4a764405a1d39c 160 15 0:3493 / /var/lib/docker/aufs/mnt/55e827bf6d44d930ec0b827c98356eb8b68c3301e2d60d1429aa72e05b4c17df rw,relatime - aufs none rw,si=9b4a764405a1a39c 162 15 0:3495 / /var/lib/docker/aufs/mnt/578dc4e0a87fc37ec081ca098430499a59639c09f6f12a8f48de29828a091aa6 rw,relatime - aufs none rw,si=9b4a76406d7d439c 163 15 0:3496 / /var/lib/docker/aufs/mnt/728cc1cb04fa4bc6f7bf7a90980beda6d8fc0beb71630874c0747b994efb0798 rw,relatime - aufs none rw,si=9b4a76444f20e39c 164 15 0:3497 / /var/lib/docker/aufs/mnt/5850cc4bd9b55aea46c7ad598f1785117607974084ea643580f58ce3222e683a rw,relatime - aufs none rw,si=9b4a7644a824239c 165 15 0:3498 / /var/lib/docker/aufs/mnt/89443b3f766d5a37bc8b84e29da8b84e6a3ea8486d3cf154e2aae1816516e4a8 rw,relatime - aufs none rw,si=9b4a7644a824139c 166 15 0:3499 / /var/lib/docker/aufs/mnt/f5ae8fd5a41a337907d16515bc3162525154b59c32314c695ecd092c3b47943d rw,relatime - aufs none rw,si=9b4a7644a824439c 167 15 0:3500 / /var/lib/docker/aufs/mnt/5a430854f2a03a9e5f7cbc9f3fb46a8ebca526a5b3f435236d8295e5998798f5 rw,relatime - aufs none rw,si=9b4a7647fc82439c 168 15 0:3501 / /var/lib/docker/aufs/mnt/eda16901ae4cead35070c39845cbf1e10bd6b8cb0ffa7879ae2d8a186e460f91 rw,relatime - aufs none rw,si=9b4a76441e0df39c 169 15 0:3502 / /var/lib/docker/aufs/mnt/5a593721430c2a51b119ff86a7e06ea2b37e3b4131f8f1344d402b61b0c8d868 rw,relatime - aufs none rw,si=9b4a764248bad39c 170 15 0:3503 / /var/lib/docker/aufs/mnt/d662ad0a30fbfa902e0962108685b9330597e1ee2abb16dc9462eb5a67fdd23f rw,relatime - aufs none rw,si=9b4a764248bae39c 171 15 0:3504 / /var/lib/docker/aufs/mnt/5bc9de5c79812843fb36eee96bef1ddba812407861f572e33242f4ee10da2c15 rw,relatime - aufs none rw,si=9b4a764248ba839c 172 15 0:3505 / /var/lib/docker/aufs/mnt/5e763de8e9b0f7d58d2e12a341e029ab4efb3b99788b175090d8209e971156c1 rw,relatime - aufs none rw,si=9b4a764248baa39c 173 15 0:3506 / /var/lib/docker/aufs/mnt/b4431dc2739936f1df6387e337f5a0c99cf051900c896bd7fd46a870ce61c873 rw,relatime - aufs none rw,si=9b4a76401263539c 174 15 0:3507 / /var/lib/docker/aufs/mnt/5f37830e5a02561ab8c67ea3113137ba69f67a60e41c05cb0e7a0edaa1925b24 rw,relatime - aufs none rw,si=9b4a76401263639c 184 15 0:3508 / /var/lib/docker/aufs/mnt/62ea10b957e6533538a4633a1e1d678502f50ddcdd354b2ca275c54dd7a7793a rw,relatime - aufs none rw,si=9b4a76401263039c 187 15 0:3509 / /var/lib/docker/aufs/mnt/d56ee9d44195fe390e042fda75ec15af5132adb6d5c69468fa8792f4e54a6953 rw,relatime - aufs none rw,si=9b4a76401263239c 188 15 0:3510 / /var/lib/docker/aufs/mnt/6a300930673174549c2b62f36c933f0332a20735978c007c805a301f897146c5 rw,relatime - aufs none rw,si=9b4a76455d4c539c 189 15 0:3511 / /var/lib/docker/aufs/mnt/64496c45c84d348c24d410015456d101601c30cab4d1998c395591caf7e57a70 rw,relatime - aufs none rw,si=9b4a76455d4c639c 190 15 0:3512 / /var/lib/docker/aufs/mnt/65a6a645883fe97a7422cd5e71ebe0bc17c8e6302a5361edf52e89747387e908 rw,relatime - aufs none rw,si=9b4a76455d4c039c 191 15 0:3513 / /var/lib/docker/aufs/mnt/672be40695f7b6e13b0a3ed9fc996c73727dede3481f58155950fcfad57ed616 rw,relatime - aufs none rw,si=9b4a76455d4c239c 192 15 0:3514 / /var/lib/docker/aufs/mnt/d42438acb2bfb2169e1c0d8e917fc824f7c85d336dadb0b0af36dfe0f001b3ba rw,relatime - aufs none rw,si=9b4a7642bfded39c 193 15 0:3515 / /var/lib/docker/aufs/mnt/b48a54abf26d01cb2ddd908b1ed6034d17397c1341bf0eb2b251a3e5b79be854 rw,relatime - aufs none rw,si=9b4a7642bfdee39c 194 15 0:3516 / /var/lib/docker/aufs/mnt/76f27134491f052bfb87f59092126e53ef875d6851990e59195a9da16a9412f8 rw,relatime - aufs none rw,si=9b4a7642bfde839c 195 15 0:3517 / /var/lib/docker/aufs/mnt/6bd626a5462b4f8a8e1cc7d10351326dca97a59b2758e5ea549a4f6350ce8a90 rw,relatime - aufs none rw,si=9b4a7642bfdea39c 196 15 0:3518 / /var/lib/docker/aufs/mnt/f1fe3549dbd6f5ca615e9139d9b53f0c83a3b825565df37628eacc13e70cbd6d rw,relatime - aufs none rw,si=9b4a7642bfdf539c 197 15 0:3519 / /var/lib/docker/aufs/mnt/6d0458c8426a9e93d58d0625737e6122e725c9408488ed9e3e649a9984e15c34 rw,relatime - aufs none rw,si=9b4a7642bfdf639c 198 15 0:3520 / /var/lib/docker/aufs/mnt/6e4c97db83aa82145c9cf2bafc20d500c0b5389643b689e3ae84188c270a48c5 rw,relatime - aufs none rw,si=9b4a7642bfdf039c 199 15 0:3521 / /var/lib/docker/aufs/mnt/eb94d6498f2c5969eaa9fa11ac2934f1ab90ef88e2d002258dca08e5ba74ea27 rw,relatime - aufs none rw,si=9b4a7642bfdf239c 200 15 0:3522 / /var/lib/docker/aufs/mnt/fe3f88f0c511608a2eec5f13a98703aa16e55dbf930309723d8a37101f539fe1 rw,relatime - aufs none rw,si=9b4a7642bfc3539c 201 15 0:3523 / /var/lib/docker/aufs/mnt/6f40c229fb9cad85fabf4b64a2640a5403ec03fe5ac1a57d0609fb8b606b9c83 rw,relatime - aufs none rw,si=9b4a7642bfc3639c 202 15 0:3524 / /var/lib/docker/aufs/mnt/7513e9131f7a8acf58ff15248237feb767c78732ca46e159f4d791e6ef031dbc rw,relatime - aufs none rw,si=9b4a7642bfc3039c 203 15 0:3525 / /var/lib/docker/aufs/mnt/79f48b00aa713cdf809c6bb7c7cb911b66e9a8076c81d6c9d2504139984ea2da rw,relatime - aufs none rw,si=9b4a7642bfc3239c 204 15 0:3526 / /var/lib/docker/aufs/mnt/c3680418350d11358f0a96c676bc5aa74fa00a7c89e629ef5909d3557b060300 rw,relatime - aufs none rw,si=9b4a7642f47cd39c 205 15 0:3527 / /var/lib/docker/aufs/mnt/7a1744dd350d7fcc0cccb6f1757ca4cbe5453f203a5888b0f1014d96ad5a5ef9 rw,relatime - aufs none rw,si=9b4a7642f47ce39c 206 15 0:3528 / /var/lib/docker/aufs/mnt/7fa99662db046be9f03c33c35251afda9ccdc0085636bbba1d90592cec3ff68d rw,relatime - aufs none rw,si=9b4a7642f47c839c 207 15 0:3529 / /var/lib/docker/aufs/mnt/f815021ef20da9c9b056bd1d52d8aaf6e2c0c19f11122fc793eb2b04eb995e35 rw,relatime - aufs none rw,si=9b4a7642f47ca39c 208 15 0:3530 / /var/lib/docker/aufs/mnt/801086ae3110192d601dfcebdba2db92e86ce6b6a9dba6678ea04488e4513669 rw,relatime - aufs none rw,si=9b4a7642dc6dd39c 209 15 0:3531 / /var/lib/docker/aufs/mnt/822ba7db69f21daddda87c01cfbfbf73013fc03a879daf96d16cdde6f9b1fbd6 rw,relatime - aufs none rw,si=9b4a7642dc6de39c 210 15 0:3532 / /var/lib/docker/aufs/mnt/834227c1a950fef8cae3827489129d0dd220541e60c6b731caaa765bf2e6a199 rw,relatime - aufs none rw,si=9b4a7642dc6d839c 211 15 0:3533 / /var/lib/docker/aufs/mnt/83dccbc385299bd1c7cf19326e791b33a544eea7b4cdfb6db70ea94eed4389fb rw,relatime - aufs none rw,si=9b4a7642dc6da39c 212 15 0:3534 / /var/lib/docker/aufs/mnt/f1b8e6f0e7c8928b5dcdab944db89306ebcae3e0b32f9ff40d2daa8329f21600 rw,relatime - aufs none rw,si=9b4a7645a126039c 213 15 0:3535 / /var/lib/docker/aufs/mnt/970efb262c7a020c2404cbcc5b3259efba0d110a786079faeef05bc2952abf3a rw,relatime - aufs none rw,si=9b4a7644c8ed139c 214 15 0:3536 / /var/lib/docker/aufs/mnt/84b6d73af7450f3117a77e15a5ca1255871fea6182cd8e8a7be6bc744be18c2c rw,relatime - aufs none rw,si=9b4a76406559139c 215 15 0:3537 / /var/lib/docker/aufs/mnt/88be2716e026bc681b5e63fe7942068773efbd0b6e901ca7ba441412006a96b6 rw,relatime - aufs none rw,si=9b4a76406559339c 216 15 0:3538 / /var/lib/docker/aufs/mnt/c81939aa166ce50cd8bca5cfbbcc420a78e0318dd5cd7c755209b9166a00a752 rw,relatime - aufs none rw,si=9b4a76406559239c 217 15 0:3539 / /var/lib/docker/aufs/mnt/e0f241645d64b7dc5ff6a8414087cca226be08fb54ce987d1d1f6350c57083aa rw,relatime - aufs none rw,si=9b4a7647cfc0f39c 218 15 0:3540 / /var/lib/docker/aufs/mnt/e10e2bf75234ed51d8a6a4bb39e465404fecbe318e54400d3879cdb2b0679c78 rw,relatime - aufs none rw,si=9b4a7647cfc0939c 219 15 0:3541 / /var/lib/docker/aufs/mnt/8f71d74c8cfc3228b82564aa9f09b2e576cff0083ddfb6aa5cb350346063f080 rw,relatime - aufs none rw,si=9b4a7647cfc0a39c 220 15 0:3542 / /var/lib/docker/aufs/mnt/9159f1eba2aef7f5205cc18d015cda7f5933cd29bba3b1b8aed5ccb5824c69ee rw,relatime - aufs none rw,si=9b4a76468cedd39c 221 15 0:3543 / /var/lib/docker/aufs/mnt/932cad71e652e048e500d9fbb5b8ea4fc9a269d42a3134ce527ceef42a2be56b rw,relatime - aufs none rw,si=9b4a76468cede39c 222 15 0:3544 / /var/lib/docker/aufs/mnt/bf1e1b5f529e8943cc0144ee86dbaaa37885c1ddffcef29537e0078ee7dd316a rw,relatime - aufs none rw,si=9b4a76468ced839c 223 15 0:3545 / /var/lib/docker/aufs/mnt/949d93ecf3322e09f858ce81d5f4b434068ec44ff84c375de03104f7b45ee955 rw,relatime - aufs none rw,si=9b4a76468ceda39c 224 15 0:3546 / /var/lib/docker/aufs/mnt/d65c6087f92dc2a3841b5251d2fe9ca07d4c6e5b021597692479740816e4e2a1 rw,relatime - aufs none rw,si=9b4a7645a126239c 225 15 0:3547 / /var/lib/docker/aufs/mnt/98a0153119d0651c193d053d254f6e16a68345a141baa80c87ae487e9d33f290 rw,relatime - aufs none rw,si=9b4a7640787cf39c 226 15 0:3548 / /var/lib/docker/aufs/mnt/99daf7fe5847c017392f6e59aa9706b3dfdd9e6d1ba11dae0f7fffde0a60b5e5 rw,relatime - aufs none rw,si=9b4a7640787c839c 227 15 0:3549 / /var/lib/docker/aufs/mnt/9ad1f2fe8a5599d4e10c5a6effa7f03d932d4e92ee13149031a372087a359079 rw,relatime - aufs none rw,si=9b4a7640787ca39c 228 15 0:3550 / /var/lib/docker/aufs/mnt/c26d64494da782ddac26f8370d86ac93e7c1666d88a7b99110fc86b35ea6a85d rw,relatime - aufs none rw,si=9b4a7642fc6b539c 229 15 0:3551 / /var/lib/docker/aufs/mnt/a49e4a8275133c230ec640997f35f172312eb0ea5bd2bbe10abf34aae98f30eb rw,relatime - aufs none rw,si=9b4a7642fc6b639c 230 15 0:3552 / /var/lib/docker/aufs/mnt/b5e2740c867ed843025f49d84e8d769de9e8e6039b3c8cb0735b5bf358994bc7 rw,relatime - aufs none rw,si=9b4a7642fc6b039c 231 15 0:3553 / /var/lib/docker/aufs/mnt/a826fdcf3a7039b30570054579b65763db605a314275d7aef31b872c13311b4b rw,relatime - aufs none rw,si=9b4a7642fc6b239c 232 15 0:3554 / /var/lib/docker/aufs/mnt/addf3025babf5e43b5a3f4a0da7ad863dda3c01fb8365c58fd8d28bb61dc11bc rw,relatime - aufs none rw,si=9b4a76407871d39c 233 15 0:3555 / /var/lib/docker/aufs/mnt/c5b6c6813ab3e5ebdc6d22cb2a3d3106a62095f2c298be52b07a3b0fa20ff690 rw,relatime - aufs none rw,si=9b4a76407871e39c 234 15 0:3556 / /var/lib/docker/aufs/mnt/af0609eaaf64e2392060cb46f5a9f3d681a219bb4c651d4f015bf573fbe6c4cf rw,relatime - aufs none rw,si=9b4a76407871839c 235 15 0:3557 / /var/lib/docker/aufs/mnt/e7f20e3c37ecad39cd90a97cd3549466d0d106ce4f0a930b8495442634fa4a1f rw,relatime - aufs none rw,si=9b4a76407871a39c 237 15 0:3559 / /var/lib/docker/aufs/mnt/b57a53d440ffd0c1295804fa68cdde35d2fed5409484627e71b9c37e4249fd5c rw,relatime - aufs none rw,si=9b4a76444445a39c 238 15 0:3560 / /var/lib/docker/aufs/mnt/b5e7d7b8f35e47efbba3d80c5d722f5e7bd43e54c824e54b4a4b351714d36d42 rw,relatime - aufs none rw,si=9b4a7647932d439c 239 15 0:3561 / /var/lib/docker/aufs/mnt/f1b136def157e9465640658f277f3347de593c6ae76412a2e79f7002f091cae2 rw,relatime - aufs none rw,si=9b4a76445abcd39c 240 15 0:3562 / /var/lib/docker/aufs/mnt/b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc rw,relatime - aufs none rw,si=9b4a7644403b339c 241 15 0:3563 / /var/lib/docker/aufs/mnt/b89b140cdbc95063761864e0a23346207fa27ee4c5c63a1ae85c9069a9d9cf1d rw,relatime - aufs none rw,si=9b4a7644aa19739c 242 15 0:3564 / /var/lib/docker/aufs/mnt/bc6a69ed51c07f5228f6b4f161c892e6a949c0e7e86a9c3432049d4c0e5cd298 rw,relatime - aufs none rw,si=9b4a7644aa19139c 243 15 0:3565 / /var/lib/docker/aufs/mnt/be4e2ba3f136933e239f7cf3d136f484fb9004f1fbdfee24a62a2c7b0ab30670 rw,relatime - aufs none rw,si=9b4a7644aa19339c 244 15 0:3566 / /var/lib/docker/aufs/mnt/e04ca1a4a5171e30d20f0c92f90a50b8b6f8600af5459c4b4fb25e42e864dfe1 rw,relatime - aufs none rw,si=9b4a7647932d139c 245 15 0:3567 / /var/lib/docker/aufs/mnt/be61576b31db893129aaffcd3dcb5ce35e49c4b71b30c392a78609a45c7323d8 rw,relatime - aufs none rw,si=9b4a7642d85f739c 246 15 0:3568 / /var/lib/docker/aufs/mnt/dda42c191e56becf672327658ab84fcb563322db3764b91c2fefe4aaef04c624 rw,relatime - aufs none rw,si=9b4a7642d85f139c 247 15 0:3569 / /var/lib/docker/aufs/mnt/c0a7995053330f3d88969247a2e72b07e2dd692133f5668a4a35ea3905561072 rw,relatime - aufs none rw,si=9b4a7642d85f339c 249 15 0:3571 / /var/lib/docker/aufs/mnt/c3594b2e5f08c59ff5ed338a1ba1eceeeb1f7fc5d180068338110c00b1eb8502 rw,relatime - aufs none rw,si=9b4a7642738c739c 250 15 0:3572 / /var/lib/docker/aufs/mnt/c58dce03a0ab0a7588393880379dc3bce9f96ec08ed3f99cf1555260ff0031e8 rw,relatime - aufs none rw,si=9b4a7642738c139c 251 15 0:3573 / /var/lib/docker/aufs/mnt/c73e9f1d109c9d14cb36e1c7489df85649be3911116d76c2fd3648ec8fd94e23 rw,relatime - aufs none rw,si=9b4a7642738c339c 252 15 0:3574 / /var/lib/docker/aufs/mnt/c9eef28c344877cd68aa09e543c0710ab2b305a0ff96dbb859bfa7808c3e8d01 rw,relatime - aufs none rw,si=9b4a7642d85f439c 253 15 0:3575 / /var/lib/docker/aufs/mnt/feb67148f548d70cb7484f2aaad2a86051cd6867a561741a2f13b552457d666e rw,relatime - aufs none rw,si=9b4a76468c55739c 254 15 0:3576 / /var/lib/docker/aufs/mnt/cdf1f96c36d35a96041a896bf398ec0f7dc3b0fb0643612a0f4b6ff96e04e1bb rw,relatime - aufs none rw,si=9b4a76468c55139c 255 15 0:3577 / /var/lib/docker/aufs/mnt/ec6e505872353268451ac4bc034c1df00f3bae4a3ea2261c6e48f7bd5417c1b3 rw,relatime - aufs none rw,si=9b4a76468c55339c 256 15 0:3578 / /var/lib/docker/aufs/mnt/d6dc8aca64efd90e0bc10274001882d0efb310d42ccbf5712b99b169053b8b1a rw,relatime - aufs none rw,si=9b4a7642738c439c 257 15 0:3579 / /var/lib/docker/aufs/mnt/d712594e2ff6eaeb895bfd150d694bd1305fb927e7a186b2dab7df2ea95f8f81 rw,relatime - aufs none rw,si=9b4a76401268f39c 259 15 0:3581 / /var/lib/docker/aufs/mnt/dbfa1174cd78cde2d7410eae442af0b416c4a0e6f87ed4ff1e9f169a0029abc0 rw,relatime - aufs none rw,si=9b4a76401268b39c 260 15 0:3582 / /var/lib/docker/aufs/mnt/e883f5a82316d7856fbe93ee8c0af5a920b7079619dd95c4ffd88bbd309d28dd rw,relatime - aufs none rw,si=9b4a76468c55439c 261 15 0:3583 / /var/lib/docker/aufs/mnt/fdec3eff581c4fc2b09f87befa2fa021f3f2d373bea636a87f1fb5b367d6347a rw,relatime - aufs none rw,si=9b4a7644aa1af39c 262 15 0:3584 / /var/lib/docker/aufs/mnt/ef764e26712184653067ecf7afea18a80854c41331ca0f0ef03e1bacf90a6ffc rw,relatime - aufs none rw,si=9b4a7644aa1a939c 263 15 0:3585 / /var/lib/docker/aufs/mnt/f3176b40c41fce8ce6942936359a2001a6f1b5c1bb40ee224186db0789ec2f76 rw,relatime - aufs none rw,si=9b4a7644aa1ab39c 264 15 0:3586 / /var/lib/docker/aufs/mnt/f5daf06785d3565c6dd18ea7d953d9a8b9606107781e63270fe0514508736e6a rw,relatime - aufs none rw,si=9b4a76401268c39c 58 15 0:3587 / /var/lib/docker/aufs/mnt/cde8c40f6524b7361af4f5ad05bb857dc9ee247c20852ba666195c0739e3a2b8-init rw,relatime - aufs none rw,si=9b4a76444445839c 67 15 0:3588 / /var/lib/docker/aufs/mnt/cde8c40f6524b7361af4f5ad05bb857dc9ee247c20852ba666195c0739e3a2b8 rw,relatime - aufs none rw,si=9b4a7644badd339c 265 15 0:3610 / /var/lib/docker/aufs/mnt/e812472cd2c8c4748d1ef71fac4e77e50d661b9349abe66ce3e23511ed44f414 rw,relatime - aufs none rw,si=9b4a76427937d39c 270 15 0:3615 / /var/lib/docker/aufs/mnt/997636e7c5c9d0d1376a217e295c14c205350b62bc12052804fb5f90abe6f183 rw,relatime - aufs none rw,si=9b4a76406540739c 273 15 0:3618 / /var/lib/docker/aufs/mnt/d5794d080417b6e52e69227c3873e0e4c1ff0d5a845ebe3860ec2f89a47a2a1e rw,relatime - aufs none rw,si=9b4a76454814039c 278 15 0:3623 / /var/lib/docker/aufs/mnt/586bdd48baced671bb19bc4d294ec325f26c55545ae267db426424f157d59c48 rw,relatime - aufs none rw,si=9b4a7644b439f39c 281 15 0:3626 / /var/lib/docker/aufs/mnt/69739d022f89f8586908bbd5edbbdd95ea5256356f177f9ffcc6ef9c0ea752d2 rw,relatime - aufs none rw,si=9b4a7644a0f1b39c 286 15 0:3631 / /var/lib/docker/aufs/mnt/ff28c27d5f894363993622de26d5dd352dba072f219e4691d6498c19bbbc15a9 rw,relatime - aufs none rw,si=9b4a7642265b339c 289 15 0:3634 / /var/lib/docker/aufs/mnt/aa128fe0e64fdede333aa48fd9de39530c91a9244a0f0649a3c411c61e372daa rw,relatime - aufs none rw,si=9b4a764012ada39c 99 15 8:33 / /media/REMOVE\040ME rw,nosuid,nodev,relatime - fuseblk /dev/sdc1 rw,user_id=0,group_id=0,allow_other,blksize=4096` ) func TestParseFedoraMountinfo(t *testing.T) { r := bytes.NewBuffer([]byte(fedoraMountinfo)) _, err := parseInfoFile(r) if err != nil { t.Fatal(err) } } func TestParseUbuntuMountinfo(t *testing.T) { r := bytes.NewBuffer([]byte(ubuntuMountInfo)) _, err := parseInfoFile(r) if err != nil { t.Fatal(err) } } func TestParseGentooMountinfo(t *testing.T) { r := bytes.NewBuffer([]byte(gentooMountinfo)) _, err := parseInfoFile(r) if err != nil { t.Fatal(err) } } func TestParseFedoraMountinfoFields(t *testing.T) { r := bytes.NewBuffer([]byte(fedoraMountinfo)) infos, err := parseInfoFile(r) if err != nil { t.Fatal(err) } expectedLength := 58 if len(infos) != expectedLength { t.Fatalf("Expected %d entries, got %d", expectedLength, len(infos)) } mi := Info{ ID: 15, Parent: 35, Major: 0, Minor: 3, Root: "/", Mountpoint: "/proc", Opts: "rw,nosuid,nodev,noexec,relatime", Optional: "shared:5", Fstype: "proc", Source: "proc", VfsOpts: "rw", } if *infos[0] != mi { t.Fatalf("expected %#v, got %#v", mi, infos[0]) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go ================================================ // +build !linux,!freebsd freebsd,!cgo package mount import ( "fmt" "runtime" ) func parseMountTable() ([]*Info, error) { return nil, fmt.Errorf("mount.parseMountTable is not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go ================================================ // +build linux package mount // MakeShared ensures a mounted filesystem has the SHARED mount option enabled. // See the supported options in flags.go for further reference. func MakeShared(mountPoint string) error { return ensureMountedAs(mountPoint, "shared") } // MakeRShared ensures a mounted filesystem has the RSHARED mount option enabled. // See the supported options in flags.go for further reference. func MakeRShared(mountPoint string) error { return ensureMountedAs(mountPoint, "rshared") } // MakePrivate ensures a mounted filesystem has the PRIVATE mount option enabled. // See the supported options in flags.go for further reference. func MakePrivate(mountPoint string) error { return ensureMountedAs(mountPoint, "private") } // MakeRPrivate ensures a mounted filesystem has the RPRIVATE mount option // enabled. See the supported options in flags.go for further reference. func MakeRPrivate(mountPoint string) error { return ensureMountedAs(mountPoint, "rprivate") } // MakeSlave ensures a mounted filesystem has the SLAVE mount option enabled. // See the supported options in flags.go for further reference. func MakeSlave(mountPoint string) error { return ensureMountedAs(mountPoint, "slave") } // MakeRSlave ensures a mounted filesystem has the RSLAVE mount option enabled. // See the supported options in flags.go for further reference. func MakeRSlave(mountPoint string) error { return ensureMountedAs(mountPoint, "rslave") } // MakeUnbindable ensures a mounted filesystem has the UNBINDABLE mount option // enabled. See the supported options in flags.go for further reference. func MakeUnbindable(mountPoint string) error { return ensureMountedAs(mountPoint, "unbindable") } // MakeRUnbindable ensures a mounted filesystem has the RUNBINDABLE mount // option enabled. See the supported options in flags.go for further reference. func MakeRUnbindable(mountPoint string) error { return ensureMountedAs(mountPoint, "runbindable") } func ensureMountedAs(mountPoint, options string) error { mounted, err := Mounted(mountPoint) if err != nil { return err } if !mounted { if err := Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil { return err } } mounted, err = Mounted(mountPoint) if err != nil { return err } return ForceMount("", mountPoint, "none", options) } ================================================ FILE: vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux_test.go ================================================ // +build linux package mount import ( "os" "path" "syscall" "testing" ) // nothing is propagated in or out func TestSubtreePrivate(t *testing.T) { tmp := path.Join(os.TempDir(), "mount-tests") if err := os.MkdirAll(tmp, 0777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) var ( sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") outside1Dir = path.Join(tmp, "outside1") outside2Dir = path.Join(tmp, "outside2") outside1Path = path.Join(outside1Dir, "file.txt") outside2Path = path.Join(outside2Dir, "file.txt") outside1CheckPath = path.Join(targetDir, "a", "file.txt") outside2CheckPath = path.Join(sourceDir, "b", "file.txt") ) if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { t.Fatal(err) } if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(targetDir, 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(outside1Dir, 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(outside2Dir, 0777); err != nil { t.Fatal(err) } if err := createFile(outside1Path); err != nil { t.Fatal(err) } if err := createFile(outside2Path); err != nil { t.Fatal(err) } // mount the shared directory to a target if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() // next, make the target private if err := MakePrivate(targetDir); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() // mount in an outside path to a mounted path inside the _source_ if err := Mount(outside1Dir, path.Join(sourceDir, "a"), "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(path.Join(sourceDir, "a")); err != nil { t.Fatal(err) } }() // check that this file _does_not_ show in the _target_ if _, err := os.Stat(outside1CheckPath); err != nil && !os.IsNotExist(err) { t.Fatal(err) } else if err == nil { t.Fatalf("%q should not be visible, but is", outside1CheckPath) } // next mount outside2Dir into the _target_ if err := Mount(outside2Dir, path.Join(targetDir, "b"), "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(path.Join(targetDir, "b")); err != nil { t.Fatal(err) } }() // check that this file _does_not_ show in the _source_ if _, err := os.Stat(outside2CheckPath); err != nil && !os.IsNotExist(err) { t.Fatal(err) } else if err == nil { t.Fatalf("%q should not be visible, but is", outside2CheckPath) } } // Testing that when a target is a shared mount, // then child mounts propagate to the source func TestSubtreeShared(t *testing.T) { tmp := path.Join(os.TempDir(), "mount-tests") if err := os.MkdirAll(tmp, 0777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) var ( sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") outsideDir = path.Join(tmp, "outside") outsidePath = path.Join(outsideDir, "file.txt") sourceCheckPath = path.Join(sourceDir, "a", "file.txt") ) if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(targetDir, 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(outsideDir, 0777); err != nil { t.Fatal(err) } if err := createFile(outsidePath); err != nil { t.Fatal(err) } // mount the source as shared if err := MakeShared(sourceDir); err != nil { t.Fatal(err) } defer func() { if err := Unmount(sourceDir); err != nil { t.Fatal(err) } }() // mount the shared directory to a target if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() // mount in an outside path to a mounted path inside the target if err := Mount(outsideDir, path.Join(targetDir, "a"), "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(path.Join(targetDir, "a")); err != nil { t.Fatal(err) } }() // NOW, check that the file from the outside directory is avaible in the source directory if _, err := os.Stat(sourceCheckPath); err != nil { t.Fatal(err) } } // testing that mounts to a shared source show up in the slave target, // and that mounts into a slave target do _not_ show up in the shared source func TestSubtreeSharedSlave(t *testing.T) { tmp := path.Join(os.TempDir(), "mount-tests") if err := os.MkdirAll(tmp, 0777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) var ( sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") outside1Dir = path.Join(tmp, "outside1") outside2Dir = path.Join(tmp, "outside2") outside1Path = path.Join(outside1Dir, "file.txt") outside2Path = path.Join(outside2Dir, "file.txt") outside1CheckPath = path.Join(targetDir, "a", "file.txt") outside2CheckPath = path.Join(sourceDir, "b", "file.txt") ) if err := os.MkdirAll(path.Join(sourceDir, "a"), 0777); err != nil { t.Fatal(err) } if err := os.MkdirAll(path.Join(sourceDir, "b"), 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(targetDir, 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(outside1Dir, 0777); err != nil { t.Fatal(err) } if err := os.Mkdir(outside2Dir, 0777); err != nil { t.Fatal(err) } if err := createFile(outside1Path); err != nil { t.Fatal(err) } if err := createFile(outside2Path); err != nil { t.Fatal(err) } // mount the source as shared if err := MakeShared(sourceDir); err != nil { t.Fatal(err) } defer func() { if err := Unmount(sourceDir); err != nil { t.Fatal(err) } }() // mount the shared directory to a target if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() // next, make the target slave if err := MakeSlave(targetDir); err != nil { t.Fatal(err) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() // mount in an outside path to a mounted path inside the _source_ if err := Mount(outside1Dir, path.Join(sourceDir, "a"), "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(path.Join(sourceDir, "a")); err != nil { t.Fatal(err) } }() // check that this file _does_ show in the _target_ if _, err := os.Stat(outside1CheckPath); err != nil { t.Fatal(err) } // next mount outside2Dir into the _target_ if err := Mount(outside2Dir, path.Join(targetDir, "b"), "none", "bind,rw"); err != nil { t.Fatal(err) } defer func() { if err := Unmount(path.Join(targetDir, "b")); err != nil { t.Fatal(err) } }() // check that this file _does_not_ show in the _source_ if _, err := os.Stat(outside2CheckPath); err != nil && !os.IsNotExist(err) { t.Fatal(err) } else if err == nil { t.Fatalf("%q should not be visible, but is", outside2CheckPath) } } func TestSubtreeUnbindable(t *testing.T) { tmp := path.Join(os.TempDir(), "mount-tests") if err := os.MkdirAll(tmp, 0777); err != nil { t.Fatal(err) } defer os.RemoveAll(tmp) var ( sourceDir = path.Join(tmp, "source") targetDir = path.Join(tmp, "target") ) if err := os.MkdirAll(sourceDir, 0777); err != nil { t.Fatal(err) } if err := os.MkdirAll(targetDir, 0777); err != nil { t.Fatal(err) } // next, make the source unbindable if err := MakeUnbindable(sourceDir); err != nil { t.Fatal(err) } defer func() { if err := Unmount(sourceDir); err != nil { t.Fatal(err) } }() // then attempt to mount it to target. It should fail if err := Mount(sourceDir, targetDir, "none", "bind,rw"); err != nil && err != syscall.EINVAL { t.Fatal(err) } else if err == nil { t.Fatalf("%q should not have been bindable", sourceDir) } defer func() { if err := Unmount(targetDir); err != nil { t.Fatal(err) } }() } func createFile(path string) error { f, err := os.Create(path) if err != nil { return err } f.WriteString("hello world!") return f.Close() } ================================================ FILE: vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go ================================================ package namesgenerator import ( "fmt" "math/rand" "github.com/docker/docker/pkg/random" ) var ( left = [...]string{ "admiring", "adoring", "agitated", "angry", "backstabbing", "berserk", "boring", "clever", "cocky", "compassionate", "condescending", "cranky", "desperate", "determined", "distracted", "dreamy", "drunk", "ecstatic", "elated", "elegant", "evil", "fervent", "focused", "furious", "gloomy", "goofy", "grave", "happy", "high", "hopeful", "hungry", "insane", "jolly", "jovial", "kickass", "lonely", "loving", "mad", "modest", "naughty", "nostalgic", "pensive", "prickly", "reverent", "romantic", "sad", "serene", "sharp", "sick", "silly", "sleepy", "stoic", "stupefied", "suspicious", "tender", "thirsty", "trusting", } // Docker, starting from 0.7.x, generates names from notable scientists and hackers. right = [...]string{ // Muhammad ibn Jābir al-Ḥarrānī al-Battānī was a founding father of astronomy. https://en.wikipedia.org/wiki/Mu%E1%B8%A5ammad_ibn_J%C4%81bir_al-%E1%B8%A4arr%C4%81n%C4%AB_al-Batt%C4%81n%C4%AB "albattani", // June Almeida - Scottish virologist who took the first pictures of the rubella virus - https://en.wikipedia.org/wiki/June_Almeida "almeida", // Archimedes was a physicist, engineer and mathematician who invented too many things to list them here. https://en.wikipedia.org/wiki/Archimedes "archimedes", // Maria Ardinghelli - Italian translator, mathematician and physicist - https://en.wikipedia.org/wiki/Maria_Ardinghelli "ardinghelli", // Aryabhata - Ancient Indian mathematician-astronomer during 476-550 CE https://en.wikipedia.org/wiki/Aryabhata "aryabhata", // Charles Babbage invented the concept of a programmable computer. https://en.wikipedia.org/wiki/Charles_Babbage. "babbage", // Stefan Banach - Polish mathematician, was one of the founders of modern functional analysis. https://en.wikipedia.org/wiki/Stefan_Banach "banach", // William Shockley, Walter Houser Brattain and John Bardeen co-invented the transistor (thanks Brian Goff). // - https://en.wikipedia.org/wiki/John_Bardeen // - https://en.wikipedia.org/wiki/Walter_Houser_Brattain // - https://en.wikipedia.org/wiki/William_Shockley "bardeen", "brattain", "shockley", // Jean Bartik, born Betty Jean Jennings, was one of the original programmers for the ENIAC computer. https://en.wikipedia.org/wiki/Jean_Bartik "bartik", // Alexander Graham Bell - an eminent Scottish-born scientist, inventor, engineer and innovator who is credited with inventing the first practical telephone - https://en.wikipedia.org/wiki/Alexander_Graham_Bell "bell", // Homi J Bhabha - was an Indian nuclear physicist, founding director, and professor of physics at the Tata Institute of Fundamental Research. Colloquially known as "father of Indian nuclear programme"- https://en.wikipedia.org/wiki/Homi_J._Bhabha "bhabha", // Bhaskara II - Ancient Indian mathematician-astronomer whose work on calculus predates Newton and Leibniz by over half a millenium - https://en.wikipedia.org/wiki/Bh%C4%81skara_II#Calculus "bhaskara", // Elizabeth Blackwell - American doctor and first American woman to receive a medical degree - https://en.wikipedia.org/wiki/Elizabeth_Blackwell "blackwell", // Niels Bohr is the father of quantum theory. https://en.wikipedia.org/wiki/Niels_Bohr. "bohr", // Satyendra Nath Bose - He provided the foundation for Bose–Einstein statistics and the theory of the Bose–Einstein condensate. - https://en.wikipedia.org/wiki/Satyendra_Nath_Bose "bose", // Brahmagupta - Ancient Indian mathematician during 598-670 CE who gave rules to compute with zero - https://en.wikipedia.org/wiki/Brahmagupta#Zero "brahmagupta", // Emmett Brown invented time travel. https://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff) "brown", // Rachel Carson - American marine biologist and conservationist, her book Silent Spring and other writings are credited with advancing the global environmental movement. https://en.wikipedia.org/wiki/Rachel_Carson "carson", //Subrahmanyan Chandrasekhar - Astrophysicist known for his mathematical theory on different stages and evolution in structures of the stars. He has won nobel prize for physics - https://en.wikipedia.org/wiki/Subrahmanyan_Chandrasekhar "chandrasekhar", // Jane Colden - American botanist widely considered the first female American botanist - https://en.wikipedia.org/wiki/Jane_Colden "colden", // Gerty Theresa Cori - American biochemist who became the third woman—and first American woman—to win a Nobel Prize in science, and the first woman to be awarded the Nobel Prize in Physiology or Medicine. Cori was born in Prague. https://en.wikipedia.org/wiki/Gerty_Cori "cori", // Seymour Roger Cray was an American electrical engineer and supercomputer architect who designed a series of computers that were the fastest in the world for decades. https://en.wikipedia.org/wiki/Seymour_Cray "cray", // Marie Curie discovered radioactivity. https://en.wikipedia.org/wiki/Marie_Curie. "curie", // Charles Darwin established the principles of natural evolution. https://en.wikipedia.org/wiki/Charles_Darwin. "darwin", // Leonardo Da Vinci invented too many things to list here. https://en.wikipedia.org/wiki/Leonardo_da_Vinci. "davinci", // Albert Einstein invented the general theory of relativity. https://en.wikipedia.org/wiki/Albert_Einstein "einstein", // Gertrude Elion - American biochemist, pharmacologist and the 1988 recipient of the Nobel Prize in Medicine - https://en.wikipedia.org/wiki/Gertrude_Elion "elion", // Douglas Engelbart gave the mother of all demos: https://en.wikipedia.org/wiki/Douglas_Engelbart "engelbart", // Euclid invented geometry. https://en.wikipedia.org/wiki/Euclid "euclid", // Pierre de Fermat pioneered several aspects of modern mathematics. https://en.wikipedia.org/wiki/Pierre_de_Fermat "fermat", // Enrico Fermi invented the first nuclear reactor. https://en.wikipedia.org/wiki/Enrico_Fermi. "fermi", // Richard Feynman was a key contributor to quantum mechanics and particle physics. https://en.wikipedia.org/wiki/Richard_Feynman "feynman", // Benjamin Franklin is famous for his experiments in electricity and the invention of the lightning rod. "franklin", // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. https://en.wikipedia.org/wiki/Galileo_Galilei "galileo", // Adele Goldstine, born Adele Katz, wrote the complete technical description for the first electronic digital computer, ENIAC. https://en.wikipedia.org/wiki/Adele_Goldstine "goldstine", // Jane Goodall - British primatologist, ethologist, and anthropologist who is considered to be the world's foremost expert on chimpanzees - https://en.wikipedia.org/wiki/Jane_Goodall "goodall", // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. https://en.wikipedia.org/wiki/Stephen_Hawking "hawking", // Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg "heisenberg", // Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin "hodgkin", // Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephon switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover "hoover", // Grace Hopper developed the first compiler for a computer programming language and is credited with popularizing the term "debugging" for fixing computer glitches. https://en.wikipedia.org/wiki/Grace_Hopper "hopper", // Hypatia - Greek Alexandrine Neoplatonist philosopher in Egypt who was one of the earliest mothers of mathematics - https://en.wikipedia.org/wiki/Hypatia "hypatia", // Yeong-Sil Jang was a Korean scientist and astronomer during the Joseon Dynasty; he invented the first metal printing press and water gauge. https://en.wikipedia.org/wiki/Jang_Yeong-sil "jang", // Karen Spärck Jones came up with the concept of inverse document frequency, which is used in most search engines today. https://en.wikipedia.org/wiki/Karen_Sp%C3%A4rck_Jones "jones", // Jack Kilby and Robert Noyce have invented silicone integrated circuits and gave Silicon Valley its name. // - https://en.wikipedia.org/wiki/Jack_Kilby // - https://en.wikipedia.org/wiki/Robert_Noyce "kilby", "noyce", // A. P. J. Abdul Kalam - is an Indian scientist aka Missile Man of India for his work on the development of ballistic missile and launch vehicle technology - https://en.wikipedia.org/wiki/A._P._J._Abdul_Kalam "kalam", // Har Gobind Khorana - Indian-American biochemist who shared the 1968 Nobel Prize for Physiology - https://en.wikipedia.org/wiki/Har_Gobind_Khorana "khorana", // Maria Kirch - German astronomer and first woman to discover a comet - https://en.wikipedia.org/wiki/Maria_Margarethe_Kirch "kirch", // Sophie Kowalevski - Russian mathematician responsible for important original contributions to analysis, differential equations and mechanics - https://en.wikipedia.org/wiki/Sofia_Kovalevskaya "kowalevski", // Marie-Jeanne de Lalande - French astronomer, mathematician and cataloguer of stars - https://en.wikipedia.org/wiki/Marie-Jeanne_de_Lalande "lalande", // Mary Leakey - British paleoanthropologist who discovered the first fossilized Proconsul skull - https://en.wikipedia.org/wiki/Mary_Leakey "leakey", // Ada Lovelace invented the first algorithm. https://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull) "lovelace", // Auguste and Louis Lumière - the first filmmakers in history - https://en.wikipedia.org/wiki/Auguste_and_Louis_Lumi%C3%A8re "lumiere", // Mahavira - Ancient Indian mathematician during 9th century AD who discovered basic algebraic identities - https://en.wikipedia.org/wiki/Mah%C4%81v%C4%ABra_(mathematician) "mahavira", // Maria Mayer - American theoretical physicist and Nobel laureate in Physics for proposing the nuclear shell model of the atomic nucleus - https://en.wikipedia.org/wiki/Maria_Mayer "mayer", // John McCarthy invented LISP: https://en.wikipedia.org/wiki/John_McCarthy_(computer_scientist) "mccarthy", // Barbara McClintock - a distinguished American cytogeneticist, 1983 Nobel Laureate in Physiology or Medicine for discovering transposons. https://en.wikipedia.org/wiki/Barbara_McClintock "mcclintock", // Malcolm McLean invented the modern shipping container: https://en.wikipedia.org/wiki/Malcom_McLean "mclean", // Lise Meitner - Austrian/Swedish physicist who was involved in the discovery of nuclear fission. The element meitnerium is named after her - https://en.wikipedia.org/wiki/Lise_Meitner "meitner", // Johanna Mestorf - German prehistoric archaeologist and first female museum director in Germany - https://en.wikipedia.org/wiki/Johanna_Mestorf "mestorf", // Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse "morse", // Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton "newton", // Alfred Nobel - a Swedish chemist, engineer, innovator, and armaments manufacturer (inventor of dynamite) - https://en.wikipedia.org/wiki/Alfred_Nobel "nobel", // Panini - Ancient Indian linguist and grammarian from 4th century CE who worked on the world's first formal system - https://en.wikipedia.org/wiki/P%C4%81%E1%B9%87ini#Comparison_with_modern_formal_systems "panini", // Cecilia Payne-Gaposchkin was an astronomer and astrophysicist who, in 1925, proposed in her Ph.D. thesis an explanation for the composition of stars in terms of the relative abundances of hydrogen and helium. https://en.wikipedia.org/wiki/Cecilia_Payne-Gaposchkin "payne", // Ambroise Pare invented modern surgery. https://en.wikipedia.org/wiki/Ambroise_Par%C3%A9 "pare", // Louis Pasteur discovered vaccination, fermentation and pasteurization. https://en.wikipedia.org/wiki/Louis_Pasteur. "pasteur", // Radia Perlman is a software designer and network engineer and most famous for her invention of the spanning-tree protocol (STP). https://en.wikipedia.org/wiki/Radia_Perlman "perlman", // Rob Pike was a key contributor to Unix, Plan 9, the X graphic system, utf-8, and the Go programming language. https://en.wikipedia.org/wiki/Rob_Pike "pike", // Henri Poincaré made fundamental contributions in several fields of mathematics. https://en.wikipedia.org/wiki/Henri_Poincar%C3%A9 "poincare", // Laura Poitras is a director and producer whose work, made possible by open source crypto tools, advances the causes of truth and freedom of information by reporting disclosures by whistleblowers such as Edward Snowden. https://en.wikipedia.org/wiki/Laura_Poitras "poitras", // Claudius Ptolemy - a Greco-Egyptian writer of Alexandria, known as a mathematician, astronomer, geographer, astrologer, and poet of a single epigram in the Greek Anthology - https://en.wikipedia.org/wiki/Ptolemy "ptolemy", // C. V. Raman - Indian physicist who won the Nobel Prize in 1930 for proposing the Raman effect. - https://en.wikipedia.org/wiki/C._V._Raman "raman", // Srinivasa Ramanujan - Indian mathematician and autodidact who made extraordinary contributions to mathematical analysis, number theory, infinite series, and continued fractions. - https://en.wikipedia.org/wiki/Srinivasa_Ramanujan "ramanujan", // Dennis Ritchie and Ken Thompson created UNIX and the C programming language. // - https://en.wikipedia.org/wiki/Dennis_Ritchie // - https://en.wikipedia.org/wiki/Ken_Thompson "ritchie", "thompson", // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin "rosalind", // Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha "saha", // Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet "sammet", // Françoise Barré-Sinoussi - French virologist and Nobel Prize Laureate in Physiology or Medicine; her work was fundamental in identifying HIV as the cause of AIDS. https://en.wikipedia.org/wiki/Fran%C3%A7oise_Barr%C3%A9-Sinoussi "sinoussi", // Richard Matthew Stallman - the founder of the Free Software movement, the GNU project, the Free Software Foundation, and the League for Programming Freedom. He also invented the concept of copyleft to protect the ideals of this movement, and enshrined this concept in the widely-used GPL (General Public License) for software. https://en.wikiquote.org/wiki/Richard_Stallman "stallman", // Aaron Swartz was influential in creating RSS, Markdown, Creative Commons, Reddit, and much of the internet as we know it today. He was devoted to freedom of information on the web. https://en.wikiquote.org/wiki/Aaron_Swartz "swartz", // Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla "tesla", // Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds "torvalds", // Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing. "turing", // Varahamihira - Ancient Indian mathematician who discovered trigonometric formulae during 505-587 CE - https://en.wikipedia.org/wiki/Var%C4%81hamihira#Contributions "varahamihira", // Sir Mokshagundam Visvesvaraya - is a notable Indian engineer. He is a recipient of the Indian Republic's highest honour, the Bharat Ratna, in 1955. On his birthday, 15 September is celebrated as Engineer's Day in India in his memory - https://en.wikipedia.org/wiki/Visvesvaraya "visvesvaraya", // Sophie Wilson designed the first Acorn Micro-Computer and the instruction set for ARM processors. https://en.wikipedia.org/wiki/Sophie_Wilson "wilson", // Steve Wozniak invented the Apple I and Apple II. https://en.wikipedia.org/wiki/Steve_Wozniak "wozniak", // The Wright brothers, Orville and Wilbur - credited with inventing and building the world's first successful airplane and making the first controlled, powered and sustained heavier-than-air human flight - https://en.wikipedia.org/wiki/Wright_brothers "wright", // Rosalyn Sussman Yalow - Rosalyn Sussman Yalow was an American medical physicist, and a co-winner of the 1977 Nobel Prize in Physiology or Medicine for development of the radioimmunoassay technique. https://en.wikipedia.org/wiki/Rosalyn_Sussman_Yalow "yalow", // Ada Yonath - an Israeli crystallographer, the first woman from the Middle East to win a Nobel prize in the sciences. https://en.wikipedia.org/wiki/Ada_Yonath "yonath", } rnd = rand.New(random.NewSource()) ) // GetRandomName generates a random name from the list of adjectives and surnames in this package // formatted as "adjective_surname". For example 'focused_turing'. If retry is non-zero, a random // integer between 0 and 10 will be added to the end of the name, e.g `focused_turing3` func GetRandomName(retry int) string { begin: name := fmt.Sprintf("%s_%s", left[rnd.Intn(len(left))], right[rnd.Intn(len(right))]) if name == "boring_wozniak" /* Steve Wozniak is not boring */ { goto begin } if retry > 0 { name = fmt.Sprintf("%s%d", name, rnd.Intn(10)) } return name } ================================================ FILE: vendor/github.com/docker/docker/pkg/namesgenerator/names-generator_test.go ================================================ package namesgenerator import ( "strings" "testing" ) // Make sure the generated names are awesome func TestGenerateAwesomeNames(t *testing.T) { name := GetRandomName(0) if !isAwesome(name) { t.Fatalf("Generated name '%s' is not awesome.", name) } } func TestNameFormat(t *testing.T) { name := GetRandomName(0) if !strings.Contains(name, "_") { t.Fatalf("Generated name does not contain an underscore") } if strings.ContainsAny(name, "0123456789") { t.Fatalf("Generated name contains numbers!") } } func TestNameRetries(t *testing.T) { name := GetRandomName(1) if !strings.Contains(name, "_") { t.Fatalf("Generated name does not contain an underscore") } if !strings.ContainsAny(name, "0123456789") { t.Fatalf("Generated name doesn't contain a number") } } // To be awesome, a container name must involve cool inventors, be easy to remember, // be at least mildly funny, and always be politically correct for enterprise adoption. func isAwesome(name string) bool { coolInventorNames := true easyToRemember := true mildlyFunnyOnOccasion := true politicallyCorrect := true return coolInventorNames && easyToRemember && mildlyFunnyOnOccasion && politicallyCorrect } ================================================ FILE: vendor/github.com/docker/docker/pkg/nat/nat.go ================================================ package nat // nat is a convenience package for docker's manipulation of strings describing // network ports. import ( "fmt" "net" "strconv" "strings" "github.com/docker/docker/pkg/parsers" ) 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 func NewPort(proto, port string) (Port, error) { // Check for parsing issues on "port" now so we can avoid having // to check it later on. portInt, err := ParsePort(port) if err != nil { return "", err } return Port(fmt.Sprintf("%d/%s", portInt, 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 } // 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() if len(portStr) == 0 { return 0 } // 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, _ := strconv.ParseUint(portStr, 10, 16) return int(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 { proto := "tcp" if i := strings.LastIndex(rawPort, "/"); i != -1 { proto = rawPort[i+1:] rawPort = rawPort[:i] } if !strings.Contains(rawPort, ":") { rawPort = fmt.Sprintf("::%s", rawPort) } else if len(strings.Split(rawPort, ":")) == 2 { rawPort = fmt.Sprintf(":%s", rawPort) } parts, err := parsers.PartParser(portSpecTemplate, rawPort) if err != nil { return nil, nil, err } var ( containerPort = parts["containerPort"] rawIP = parts["ip"] hostPort = parts["hostPort"] ) if rawIP != "" && net.ParseIP(rawIP) == nil { return nil, nil, fmt.Errorf("Invalid ip address: %s", rawIP) } if containerPort == "" { return nil, nil, fmt.Errorf("No port specified: %s", rawPort) } startPort, endPort, err := parsers.ParsePortRange(containerPort) if err != nil { return nil, nil, fmt.Errorf("Invalid containerPort: %s", containerPort) } var startHostPort, endHostPort uint64 = 0, 0 if len(hostPort) > 0 { startHostPort, endHostPort, err = parsers.ParsePortRange(hostPort) if err != nil { return nil, nil, fmt.Errorf("Invalid hostPort: %s", hostPort) } } if hostPort != "" && (endPort-startPort) != (endHostPort-startHostPort) { return nil, nil, fmt.Errorf("Invalid ranges specified for container and host Ports: %s and %s", containerPort, hostPort) } if !validateProto(strings.ToLower(proto)) { return nil, nil, fmt.Errorf("Invalid proto: %s", proto) } for i := uint64(0); i <= (endPort - startPort); i++ { containerPort = strconv.FormatUint(startPort+i, 10) if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } port, err := NewPort(strings.ToLower(proto), containerPort) if err != nil { return nil, nil, err } if _, exists := exposedPorts[port]; !exists { exposedPorts[port] = struct{}{} } binding := PortBinding{ HostIP: rawIP, HostPort: hostPort, } bslice, exists := bindings[port] if !exists { bslice = []PortBinding{} } bindings[port] = append(bslice, binding) } } return exposedPorts, bindings, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/nat/nat_test.go ================================================ package nat import ( "testing" ) func TestParsePort(t *testing.T) { var ( p int err error ) p, err = ParsePort("1234") if err != nil || p != 1234 { t.Fatal("Parsing '1234' did not succeed") } // FIXME currently this is a valid port. I don't think it should be. // I'm leaving this test commented out until we make a decision. // - erikh /* p, err = ParsePort("0123") if err != nil { t.Fatal("Successfully parsed port '0123' to '123'") } */ p, err = ParsePort("asdf") if err == nil || p != 0 { t.Fatal("Parsing port 'asdf' succeeded") } p, err = ParsePort("1asdf") if err == nil || p != 0 { t.Fatal("Parsing port '1asdf' succeeded") } } func TestPort(t *testing.T) { p, err := NewPort("tcp", "1234") if err != nil { t.Fatalf("tcp, 1234 had a parsing issue: %v", err) } if string(p) != "1234/tcp" { t.Fatal("tcp, 1234 did not result in the string 1234/tcp") } if p.Proto() != "tcp" { t.Fatal("protocol was not tcp") } if p.Port() != "1234" { t.Fatal("port string value was not 1234") } if p.Int() != 1234 { t.Fatal("port int value was not 1234") } p, err = NewPort("tcp", "asd1234") if err == nil { t.Fatal("tcp, asd1234 was supposed to fail") } } func TestSplitProtoPort(t *testing.T) { var ( proto string port string ) proto, port = SplitProtoPort("1234/tcp") if proto != "tcp" || port != "1234" { t.Fatal("Could not split 1234/tcp properly") } proto, port = SplitProtoPort("") if proto != "" || port != "" { t.Fatal("parsing an empty string yielded surprising results", proto, port) } proto, port = SplitProtoPort("1234") if proto != "tcp" || port != "1234" { t.Fatal("tcp is not the default protocol for portspec '1234'", proto, port) } proto, port = SplitProtoPort("1234/") if proto != "tcp" || port != "1234" { t.Fatal("parsing '1234/' yielded:" + port + "/" + proto) } proto, port = SplitProtoPort("/tcp") if proto != "" || port != "" { t.Fatal("parsing '/tcp' yielded:" + port + "/" + proto) } } func TestParsePortSpecs(t *testing.T) { var ( portMap map[Port]struct{} bindingMap map[Port][]PortBinding err error ) portMap, bindingMap, err = ParsePortSpecs([]string{"1234/tcp", "2345/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1234/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2345/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != "" { t.Fatalf("HostPort should not be set for %s", portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"1234:1234/tcp", "2345:2345/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1234/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2345/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != port { t.Fatalf("HostPort should be %s for %s", port, portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"0.0.0.0:1234:1234/tcp", "0.0.0.0:2345:2345/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1234/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2345/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "0.0.0.0" { t.Fatalf("HostIP is not 0.0.0.0 for %s", portspec) } if bindings[0].HostPort != port { t.Fatalf("HostPort should be %s for %s", port, portspec) } } _, _, err = ParsePortSpecs([]string{"localhost:1234:1234/tcp"}) if err == nil { t.Fatal("Received no error while trying to parse a hostname instead of ip") } } func TestParsePortSpecsWithRange(t *testing.T) { var ( portMap map[Port]struct{} bindingMap map[Port][]PortBinding err error ) portMap, bindingMap, err = ParsePortSpecs([]string{"1234-1236/tcp", "2345-2347/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1235/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2346/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != "" { t.Fatalf("HostPort should not be set for %s", portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"1234-1236:1234-1236/tcp", "2345-2347:2345-2347/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1235/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2346/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != port { t.Fatalf("HostPort should be %s for %s", port, portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"0.0.0.0:1234-1236:1234-1236/tcp", "0.0.0.0:2345-2347:2345-2347/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1235/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2346/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 || bindings[0].HostIP != "0.0.0.0" || bindings[0].HostPort != port { t.Fatalf("Expect single binding to port %s but found %s", port, bindings) } } _, _, err = ParsePortSpecs([]string{"localhost:1234-1236:1234-1236/tcp"}) if err == nil { t.Fatal("Received no error while trying to parse a hostname instead of ip") } } func TestParseNetworkOptsPrivateOnly(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100::80"}) if err != nil { t.Fatal(err) } if len(ports) != 1 { t.Logf("Expected 1 got %d", len(ports)) t.FailNow() } if len(bindings) != 1 { t.Logf("Expected 1 got %d", len(bindings)) t.FailNow() } for k := range ports { if k.Proto() != "tcp" { t.Logf("Expected tcp got %s", k.Proto()) t.Fail() } if k.Port() != "80" { t.Logf("Expected 80 got %s", k.Port()) t.Fail() } b, exists := bindings[k] if !exists { t.Log("Binding does not exist") t.FailNow() } if len(b) != 1 { t.Logf("Expected 1 got %d", len(b)) t.FailNow() } s := b[0] if s.HostPort != "" { t.Logf("Expected \"\" got %s", s.HostPort) t.Fail() } if s.HostIP != "192.168.1.100" { t.Fail() } } } func TestParseNetworkOptsPublic(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100:8080:80"}) if err != nil { t.Fatal(err) } if len(ports) != 1 { t.Logf("Expected 1 got %d", len(ports)) t.FailNow() } if len(bindings) != 1 { t.Logf("Expected 1 got %d", len(bindings)) t.FailNow() } for k := range ports { if k.Proto() != "tcp" { t.Logf("Expected tcp got %s", k.Proto()) t.Fail() } if k.Port() != "80" { t.Logf("Expected 80 got %s", k.Port()) t.Fail() } b, exists := bindings[k] if !exists { t.Log("Binding does not exist") t.FailNow() } if len(b) != 1 { t.Logf("Expected 1 got %d", len(b)) t.FailNow() } s := b[0] if s.HostPort != "8080" { t.Logf("Expected 8080 got %s", s.HostPort) t.Fail() } if s.HostIP != "192.168.1.100" { t.Fail() } } } func TestParseNetworkOptsPublicNoPort(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100"}) if err == nil { t.Logf("Expected error Invalid containerPort") t.Fail() } if ports != nil { t.Logf("Expected nil got %s", ports) t.Fail() } if bindings != nil { t.Logf("Expected nil got %s", bindings) t.Fail() } } func TestParseNetworkOptsNegativePorts(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100:-1:-1"}) if err == nil { t.Fail() } if len(ports) != 0 { t.Logf("Expected nil got %s", len(ports)) t.Fail() } if len(bindings) != 0 { t.Logf("Expected 0 got %s", len(bindings)) t.Fail() } } func TestParseNetworkOptsUdp(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100::6000/udp"}) if err != nil { t.Fatal(err) } if len(ports) != 1 { t.Logf("Expected 1 got %d", len(ports)) t.FailNow() } if len(bindings) != 1 { t.Logf("Expected 1 got %d", len(bindings)) t.FailNow() } for k := range ports { if k.Proto() != "udp" { t.Logf("Expected udp got %s", k.Proto()) t.Fail() } if k.Port() != "6000" { t.Logf("Expected 6000 got %s", k.Port()) t.Fail() } b, exists := bindings[k] if !exists { t.Log("Binding does not exist") t.FailNow() } if len(b) != 1 { t.Logf("Expected 1 got %d", len(b)) t.FailNow() } s := b[0] if s.HostPort != "" { t.Logf("Expected \"\" got %s", s.HostPort) t.Fail() } if s.HostIP != "192.168.1.100" { t.Fail() } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/nat/sort.go ================================================ package nat import ( "sort" "strconv" "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) int64 { i, err := strconv.ParseInt(s, 10, 64) if err != nil { i = 0 } return i } ================================================ FILE: vendor/github.com/docker/docker/pkg/nat/sort_test.go ================================================ package nat import ( "fmt" "reflect" "testing" ) func TestSortUniquePorts(t *testing.T) { ports := []Port{ Port("6379/tcp"), Port("22/tcp"), } Sort(ports, func(ip, jp Port) bool { return ip.Int() < jp.Int() || (ip.Int() == jp.Int() && ip.Proto() == "tcp") }) first := ports[0] if fmt.Sprint(first) != "22/tcp" { t.Log(fmt.Sprint(first)) t.Fail() } } func TestSortSamePortWithDifferentProto(t *testing.T) { ports := []Port{ Port("8888/tcp"), Port("8888/udp"), Port("6379/tcp"), Port("6379/udp"), } Sort(ports, func(ip, jp Port) bool { return ip.Int() < jp.Int() || (ip.Int() == jp.Int() && ip.Proto() == "tcp") }) first := ports[0] if fmt.Sprint(first) != "6379/tcp" { t.Fail() } } func TestSortPortMap(t *testing.T) { ports := []Port{ Port("22/tcp"), Port("22/udp"), Port("8000/tcp"), Port("6379/tcp"), Port("9999/tcp"), } portMap := PortMap{ Port("22/tcp"): []PortBinding{ {}, }, Port("8000/tcp"): []PortBinding{ {}, }, Port("6379/tcp"): []PortBinding{ {}, {HostIP: "0.0.0.0", HostPort: "32749"}, }, Port("9999/tcp"): []PortBinding{ {HostIP: "0.0.0.0", HostPort: "40000"}, }, } SortPortMap(ports, portMap) if !reflect.DeepEqual(ports, []Port{ Port("9999/tcp"), Port("6379/tcp"), Port("8000/tcp"), Port("22/tcp"), Port("22/udp"), }) { t.Errorf("failed to prioritize port with explicit mappings, got %v", ports) } if pm := portMap[Port("6379/tcp")]; !reflect.DeepEqual(pm, []PortBinding{ {HostIP: "0.0.0.0", HostPort: "32749"}, {}, }) { t.Errorf("failed to prioritize bindings with explicit mappings, got %v", pm) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/filters/parse.go ================================================ package filters import ( "encoding/json" "errors" "regexp" "strings" ) type Args map[string][]string // Parse the argument to the filter flag. Like // // `docker ps -f 'created=today' -f 'image.name=ubuntu*'` // // If prev map is provided, then it is appended to, and returned. By default a new // map is created. func ParseFlag(arg string, prev Args) (Args, error) { var filters Args = prev if prev == nil { filters = Args{} } if len(arg) == 0 { return filters, nil } if !strings.Contains(arg, "=") { return filters, ErrorBadFormat } f := strings.SplitN(arg, "=", 2) name := strings.ToLower(strings.TrimSpace(f[0])) value := strings.TrimSpace(f[1]) filters[name] = append(filters[name], value) return filters, nil } var ErrorBadFormat = errors.New("bad format of filter (expected name=value)") // packs the Args into an string for easy transport from client to server func ToParam(a Args) (string, error) { // this way we don't URL encode {}, just empty space if len(a) == 0 { return "", nil } buf, err := json.Marshal(a) if err != nil { return "", err } return string(buf), nil } // unpacks the filter Args func FromParam(p string) (Args, error) { args := Args{} if len(p) == 0 { return args, nil } if err := json.NewDecoder(strings.NewReader(p)).Decode(&args); err != nil { return nil, err } return args, nil } func (filters Args) MatchKVList(field string, sources map[string]string) bool { fieldValues := filters[field] //do not filter if there is no filter set or cannot determine filter if len(fieldValues) == 0 { return true } if sources == nil || len(sources) == 0 { return false } outer: for _, name2match := range fieldValues { testKV := strings.SplitN(name2match, "=", 2) for k, v := range sources { if len(testKV) == 1 { if k == testKV[0] { continue outer } } else if k == testKV[0] && v == testKV[1] { continue outer } } return false } return true } func (filters Args) Match(field, source string) bool { fieldValues := filters[field] //do not filter if there is no filter set or cannot determine filter if len(fieldValues) == 0 { return true } for _, name2match := range fieldValues { match, err := regexp.MatchString(name2match, source) if err != nil { continue } if match { return true } } return false } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/filters/parse_test.go ================================================ package filters import ( "sort" "testing" ) func TestParseArgs(t *testing.T) { // equivalent of `docker ps -f 'created=today' -f 'image.name=ubuntu*' -f 'image.name=*untu'` flagArgs := []string{ "created=today", "image.name=ubuntu*", "image.name=*untu", } var ( args = Args{} err error ) for i := range flagArgs { args, err = ParseFlag(flagArgs[i], args) if err != nil { t.Errorf("failed to parse %s: %s", flagArgs[i], err) } } if len(args["created"]) != 1 { t.Errorf("failed to set this arg") } if len(args["image.name"]) != 2 { t.Errorf("the args should have collapsed") } } func TestParseArgsEdgeCase(t *testing.T) { var filters Args args, err := ParseFlag("", filters) if err != nil { t.Fatal(err) } if args == nil || len(args) != 0 { t.Fatalf("Expected an empty Args (map), got %v", args) } if args, err = ParseFlag("anything", args); err == nil || err != ErrorBadFormat { t.Fatalf("Expected ErrorBadFormat, got %v", err) } } func TestToParam(t *testing.T) { a := Args{ "created": []string{"today"}, "image.name": []string{"ubuntu*", "*untu"}, } _, err := ToParam(a) if err != nil { t.Errorf("failed to marshal the filters: %s", err) } } func TestFromParam(t *testing.T) { invalids := []string{ "anything", "['a','list']", "{'key': 'value'}", `{"key": "value"}`, } valids := map[string]Args{ `{"key": ["value"]}`: { "key": {"value"}, }, `{"key": ["value1", "value2"]}`: { "key": {"value1", "value2"}, }, `{"key1": ["value1"], "key2": ["value2"]}`: { "key1": {"value1"}, "key2": {"value2"}, }, } for _, invalid := range invalids { if _, err := FromParam(invalid); err == nil { t.Fatalf("Expected an error with %v, got nothing", invalid) } } for json, expectedArgs := range valids { args, err := FromParam(json) if err != nil { t.Fatal(err) } if len(args) != len(expectedArgs) { t.Fatalf("Expected %v, go %v", expectedArgs, args) } for key, expectedValues := range expectedArgs { values := args[key] sort.Strings(values) sort.Strings(expectedValues) if len(values) != len(expectedValues) { t.Fatalf("Expected %v, go %v", expectedArgs, args) } for index, expectedValue := range expectedValues { if values[index] != expectedValue { t.Fatalf("Expected %v, go %v", expectedArgs, args) } } } } } func TestEmpty(t *testing.T) { a := Args{} v, err := ToParam(a) if err != nil { t.Errorf("failed to marshal the filters: %s", err) } v1, err := FromParam(v) if err != nil { t.Errorf("%s", err) } if len(a) != len(v1) { t.Errorf("these should both be empty sets") } } func TestArgsMatchKVList(t *testing.T) { // empty sources args := Args{ "created": []string{"today"}, } if args.MatchKVList("created", map[string]string{}) { t.Fatalf("Expected false for (%v,created), got true", args) } // Not empty sources sources := map[string]string{ "key1": "value1", "key2": "value2", "key3": "value3", } matches := map[*Args]string{ &Args{}: "field", &Args{ "created": []string{"today"}, "labels": []string{"key1"}, }: "labels", &Args{ "created": []string{"today"}, "labels": []string{"key1=value1"}, }: "labels", } differs := map[*Args]string{ &Args{ "created": []string{"today"}, }: "created", &Args{ "created": []string{"today"}, "labels": []string{"key4"}, }: "labels", &Args{ "created": []string{"today"}, "labels": []string{"key1=value3"}, }: "labels", } for args, field := range matches { if args.MatchKVList(field, sources) != true { t.Fatalf("Expected true for %v on %v, got false", sources, args) } } for args, field := range differs { if args.MatchKVList(field, sources) != false { t.Fatalf("Expected false for %v on %v, got true", sources, args) } } } func TestArgsMatch(t *testing.T) { source := "today" matches := map[*Args]string{ &Args{}: "field", &Args{ "created": []string{"today"}, "labels": []string{"key1"}, }: "today", &Args{ "created": []string{"to*"}, }: "created", &Args{ "created": []string{"to(.*)"}, }: "created", &Args{ "created": []string{"tod"}, }: "created", &Args{ "created": []string{"anything", "to*"}, }: "created", } differs := map[*Args]string{ &Args{ "created": []string{"tomorrow"}, }: "created", &Args{ "created": []string{"to(day"}, }: "created", &Args{ "created": []string{"tom(.*)"}, }: "created", &Args{ "created": []string{"today1"}, "labels": []string{"today"}, }: "created", } for args, field := range matches { if args.Match(field, source) != true { t.Fatalf("Expected true for %v on %v, got false", source, args) } } for args, field := range differs { if args.Match(field, source) != false { t.Fatalf("Expected false for %v on %v, got true", source, args) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/kernel/kernel.go ================================================ // +build !windows package kernel import ( "bytes" "errors" "fmt" ) type KernelVersionInfo struct { Kernel int Major int Minor int Flavor string } func (k *KernelVersionInfo) String() string { return fmt.Sprintf("%d.%d.%d%s", k.Kernel, k.Major, k.Minor, k.Flavor) } // Compare two KernelVersionInfo struct. // Returns -1 if a < b, 0 if a == b, 1 it a > b func CompareKernelVersion(a, b *KernelVersionInfo) int { if a.Kernel < b.Kernel { return -1 } else if a.Kernel > b.Kernel { return 1 } if a.Major < b.Major { return -1 } else if a.Major > b.Major { return 1 } if a.Minor < b.Minor { return -1 } else if a.Minor > b.Minor { return 1 } return 0 } func GetKernelVersion() (*KernelVersionInfo, error) { var ( err error ) uts, err := uname() if err != nil { return nil, err } release := make([]byte, len(uts.Release)) i := 0 for _, c := range uts.Release { release[i] = byte(c) i++ } // Remove the \x00 from the release for Atoi to parse correctly release = release[:bytes.IndexByte(release, 0)] return ParseRelease(string(release)) } func ParseRelease(release string) (*KernelVersionInfo, error) { var ( kernel, major, minor, parsed int flavor, partial string ) // Ignore error from Sscanf to allow an empty flavor. Instead, just // make sure we got all the version numbers. parsed, _ = fmt.Sscanf(release, "%d.%d%s", &kernel, &major, &partial) if parsed < 2 { return nil, errors.New("Can't parse kernel version " + release) } // sometimes we have 3.12.25-gentoo, but sometimes we just have 3.12-1-amd64 parsed, _ = fmt.Sscanf(partial, ".%d%s", &minor, &flavor) if parsed < 1 { flavor = partial } return &KernelVersionInfo{ Kernel: kernel, Major: major, Minor: minor, Flavor: flavor, }, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/kernel/kernel_test.go ================================================ package kernel import ( "fmt" "testing" ) func assertParseRelease(t *testing.T, release string, b *KernelVersionInfo, result int) { var ( a *KernelVersionInfo ) a, _ = ParseRelease(release) if r := CompareKernelVersion(a, b); r != result { t.Fatalf("Unexpected kernel version comparison result for (%v,%v). Found %d, expected %d", release, b, r, result) } if a.Flavor != b.Flavor { t.Fatalf("Unexpected parsed kernel flavor. Found %s, expected %s", a.Flavor, b.Flavor) } } func TestParseRelease(t *testing.T) { assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0) assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0) assertParseRelease(t, "3.4.54.longterm-1", &KernelVersionInfo{Kernel: 3, Major: 4, Minor: 54, Flavor: ".longterm-1"}, 0) assertParseRelease(t, "3.8.0-19-generic", &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "-19-generic"}, 0) assertParseRelease(t, "3.12.8tag", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 8, Flavor: "tag"}, 0) assertParseRelease(t, "3.12-1-amd64", &KernelVersionInfo{Kernel: 3, Major: 12, Minor: 0, Flavor: "-1-amd64"}, 0) assertParseRelease(t, "3.8.0", &KernelVersionInfo{Kernel: 4, Major: 8, Minor: 0}, -1) // Errors invalids := []string{ "3", "a", "a.a", "a.a.a-a", } for _, invalid := range invalids { expectedMessage := fmt.Sprintf("Can't parse kernel version %v", invalid) if _, err := ParseRelease(invalid); err == nil || err.Error() != expectedMessage { } } } func assertKernelVersion(t *testing.T, a, b *KernelVersionInfo, result int) { if r := CompareKernelVersion(a, b); r != result { t.Fatalf("Unexpected kernel version comparison result. Found %d, expected %d", r, result) } } func TestCompareKernelVersion(t *testing.T) { assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0) assertKernelVersion(t, &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, -1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, &KernelVersionInfo{Kernel: 2, Major: 6, Minor: 0}, 1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 0) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 5}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 0, Minor: 20}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, -1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 7, Minor: 20}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, -1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20}, &KernelVersionInfo{Kernel: 3, Major: 7, Minor: 0}, 1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, 1) assertKernelVersion(t, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}, &KernelVersionInfo{Kernel: 3, Major: 8, Minor: 20}, -1) } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/kernel/kernel_windows.go ================================================ package kernel import ( "fmt" "syscall" "unsafe" ) type KernelVersionInfo struct { kvi string major int minor int build int } func (k *KernelVersionInfo) String() string { return fmt.Sprintf("%d.%d %d (%s)", k.major, k.minor, k.build, k.kvi) } func GetKernelVersion() (*KernelVersionInfo, error) { var ( h syscall.Handle dwVersion uint32 err error ) KVI := &KernelVersionInfo{"Unknown", 0, 0, 0} if err = syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, syscall.StringToUTF16Ptr(`SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\`), 0, syscall.KEY_READ, &h); err != nil { return KVI, err } defer syscall.RegCloseKey(h) var buf [1 << 10]uint16 var typ uint32 n := uint32(len(buf) * 2) // api expects array of bytes, not uint16 if err = syscall.RegQueryValueEx(h, syscall.StringToUTF16Ptr("BuildLabEx"), nil, &typ, (*byte)(unsafe.Pointer(&buf[0])), &n); err != nil { return KVI, err } KVI.kvi = syscall.UTF16ToString(buf[:]) // Important - docker.exe MUST be manifested for this API to return // the correct information. if dwVersion, err = syscall.GetVersion(); err != nil { return KVI, err } KVI.major = int(dwVersion & 0xFF) KVI.minor = int((dwVersion & 0XFF00) >> 8) KVI.build = int((dwVersion & 0xFFFF0000) >> 16) return KVI, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/kernel/uname_linux.go ================================================ package kernel import ( "syscall" ) type Utsname syscall.Utsname func uname() (*syscall.Utsname, error) { uts := &syscall.Utsname{} if err := syscall.Uname(uts); err != nil { return nil, err } return uts, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/kernel/uname_unsupported.go ================================================ // +build !linux package kernel import ( "errors" ) type Utsname struct { Release [65]byte } func uname() (*Utsname, error) { return nil, errors.New("Kernel version detection is available only on linux") } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_linux.go ================================================ package operatingsystem import ( "bytes" "errors" "io/ioutil" ) var ( // file to use to detect if the daemon is running in a container proc1Cgroup = "/proc/1/cgroup" // file to check to determine Operating System etcOsRelease = "/etc/os-release" ) func GetOperatingSystem() (string, error) { b, err := ioutil.ReadFile(etcOsRelease) if err != nil { return "", err } if i := bytes.Index(b, []byte("PRETTY_NAME")); i >= 0 { b = b[i+13:] return string(b[:bytes.IndexByte(b, '"')]), nil } return "", errors.New("PRETTY_NAME not found") } func IsContainerized() (bool, error) { b, err := ioutil.ReadFile(proc1Cgroup) if err != nil { return false, err } for _, line := range bytes.Split(b, []byte{'\n'}) { if len(line) > 0 && !bytes.HasSuffix(line, []byte{'/'}) { return true, nil } } return false, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_test.go ================================================ package operatingsystem import ( "io/ioutil" "os" "path/filepath" "testing" ) func TestGetOperatingSystem(t *testing.T) { var ( backup = etcOsRelease ubuntuTrusty = []byte(`NAME="Ubuntu" VERSION="14.04, Trusty Tahr" ID=ubuntu ID_LIKE=debian PRETTY_NAME="Ubuntu 14.04 LTS" VERSION_ID="14.04" HOME_URL="http://www.ubuntu.com/" SUPPORT_URL="http://help.ubuntu.com/" BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"`) gentoo = []byte(`NAME=Gentoo ID=gentoo PRETTY_NAME="Gentoo/Linux" ANSI_COLOR="1;32" HOME_URL="http://www.gentoo.org/" SUPPORT_URL="http://www.gentoo.org/main/en/support.xml" BUG_REPORT_URL="https://bugs.gentoo.org/" `) noPrettyName = []byte(`NAME="Ubuntu" VERSION="14.04, Trusty Tahr" ID=ubuntu ID_LIKE=debian VERSION_ID="14.04" HOME_URL="http://www.ubuntu.com/" SUPPORT_URL="http://help.ubuntu.com/" BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"`) ) dir := os.TempDir() etcOsRelease = filepath.Join(dir, "etcOsRelease") defer func() { os.Remove(etcOsRelease) etcOsRelease = backup }() for expect, osRelease := range map[string][]byte{ "Ubuntu 14.04 LTS": ubuntuTrusty, "Gentoo/Linux": gentoo, "": noPrettyName, } { if err := ioutil.WriteFile(etcOsRelease, osRelease, 0600); err != nil { t.Fatalf("failed to write to %s: %v", etcOsRelease, err) } s, err := GetOperatingSystem() if s != expect { if expect == "" { t.Fatalf("Expected error 'PRETTY_NAME not found', but got %v", err) } else { t.Fatalf("Expected '%s', but got '%s'. Err=%v", expect, s, err) } } } } func TestIsContainerized(t *testing.T) { var ( backup = proc1Cgroup nonContainerizedProc1Cgroup = []byte(`14:name=systemd:/ 13:hugetlb:/ 12:net_prio:/ 11:perf_event:/ 10:bfqio:/ 9:blkio:/ 8:net_cls:/ 7:freezer:/ 6:devices:/ 5:memory:/ 4:cpuacct:/ 3:cpu:/ 2:cpuset:/ `) containerizedProc1Cgroup = []byte(`9:perf_event:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 8:blkio:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 7:net_cls:/ 6:freezer:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 5:devices:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 4:memory:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 3:cpuacct:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 2:cpu:/docker/3cef1b53c50b0fa357d994f8a1a8cd783c76bbf4f5dd08b226e38a8bd331338d 1:cpuset:/`) ) dir := os.TempDir() proc1Cgroup = filepath.Join(dir, "proc1Cgroup") defer func() { os.Remove(proc1Cgroup) proc1Cgroup = backup }() if err := ioutil.WriteFile(proc1Cgroup, nonContainerizedProc1Cgroup, 0600); err != nil { t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) } inContainer, err := IsContainerized() if err != nil { t.Fatal(err) } if inContainer { t.Fatal("Wrongly assuming containerized") } if err := ioutil.WriteFile(proc1Cgroup, containerizedProc1Cgroup, 0600); err != nil { t.Fatalf("failed to write to %s: %v", proc1Cgroup, err) } inContainer, err = IsContainerized() if err != nil { t.Fatal(err) } if !inContainer { t.Fatal("Wrongly assuming non-containerized") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/operatingsystem/operatingsystem_windows.go ================================================ package operatingsystem import ( "syscall" "unsafe" ) // See https://code.google.com/p/go/source/browse/src/pkg/mime/type_windows.go?r=d14520ac25bf6940785aabb71f5be453a286f58c // for a similar sample func GetOperatingSystem() (string, error) { var h syscall.Handle // Default return value ret := "Unknown Operating System" if err := syscall.RegOpenKeyEx(syscall.HKEY_LOCAL_MACHINE, syscall.StringToUTF16Ptr(`SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\`), 0, syscall.KEY_READ, &h); err != nil { return ret, err } defer syscall.RegCloseKey(h) var buf [1 << 10]uint16 var typ uint32 n := uint32(len(buf) * 2) // api expects array of bytes, not uint16 if err := syscall.RegQueryValueEx(h, syscall.StringToUTF16Ptr("ProductName"), nil, &typ, (*byte)(unsafe.Pointer(&buf[0])), &n); err != nil { return ret, err } ret = syscall.UTF16ToString(buf[:]) return ret, nil } // No-op on Windows func IsContainerized() (bool, error) { return false, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/parsers.go ================================================ package parsers import ( "fmt" "net/url" "path" "runtime" "strconv" "strings" ) // FIXME: Change this not to receive default value as parameter func ParseHost(defaultTCPAddr, defaultUnixAddr, addr string) (string, error) { addr = strings.TrimSpace(addr) if addr == "" { if runtime.GOOS != "windows" { addr = fmt.Sprintf("unix://%s", defaultUnixAddr) } else { // Note - defaultTCPAddr already includes tcp:// prefix addr = fmt.Sprintf("%s", defaultTCPAddr) } } addrParts := strings.Split(addr, "://") if len(addrParts) == 1 { addrParts = []string{"tcp", addrParts[0]} } switch addrParts[0] { case "tcp": return ParseTCPAddr(addrParts[1], defaultTCPAddr) case "unix": return ParseUnixAddr(addrParts[1], defaultUnixAddr) case "fd": return addr, nil default: return "", fmt.Errorf("Invalid bind address format: %s", addr) } } func ParseUnixAddr(addr string, defaultAddr string) (string, error) { addr = strings.TrimPrefix(addr, "unix://") if strings.Contains(addr, "://") { return "", fmt.Errorf("Invalid proto, expected unix: %s", addr) } if addr == "" { addr = defaultAddr } return fmt.Sprintf("unix://%s", addr), nil } func ParseTCPAddr(addr string, defaultAddr string) (string, error) { addr = strings.TrimPrefix(addr, "tcp://") if strings.Contains(addr, "://") || addr == "" { return "", fmt.Errorf("Invalid proto, expected tcp: %s", addr) } u, err := url.Parse("tcp://" + addr) if err != nil { return "", err } hostParts := strings.Split(u.Host, ":") if len(hostParts) != 2 { return "", fmt.Errorf("Invalid bind address format: %s", addr) } host := hostParts[0] if host == "" { host = defaultAddr } p, err := strconv.Atoi(hostParts[1]) if err != nil && p == 0 { return "", fmt.Errorf("Invalid bind address format: %s", addr) } return fmt.Sprintf("tcp://%s:%d%s", host, p, u.Path), nil } // Get a repos name and returns the right reposName + tag|digest // The tag can be confusing because of a port in a repository name. // Ex: localhost.localdomain:5000/samalba/hipache:latest // Digest ex: localhost:5000/foo/bar@sha256:bc8813ea7b3603864987522f02a76101c17ad122e1c46d790efc0fca78ca7bfb func ParseRepositoryTag(repos string) (string, string) { n := strings.Index(repos, "@") if n >= 0 { parts := strings.Split(repos, "@") return parts[0], parts[1] } n = strings.LastIndex(repos, ":") if n < 0 { return repos, "" } if tag := repos[n+1:]; !strings.Contains(tag, "/") { return repos[:n], tag } return repos, "" } 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 } func ParseKeyValueOpt(opt string) (string, string, error) { parts := strings.SplitN(opt, "=", 2) if len(parts) != 2 { return "", "", fmt.Errorf("Unable to parse key/value option: %s", opt) } return strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]), nil } 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 } 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 an 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 } ================================================ FILE: vendor/github.com/docker/docker/pkg/parsers/parsers_test.go ================================================ package parsers import ( "strings" "testing" ) func TestParseHost(t *testing.T) { var ( defaultHttpHost = "127.0.0.1" defaultUnix = "/var/run/docker.sock" ) invalids := map[string]string{ "0.0.0.0": "Invalid bind address format: 0.0.0.0", "tcp://": "Invalid proto, expected tcp: ", "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1", "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375", } valids := map[string]string{ "0.0.0.1:5555": "tcp://0.0.0.1:5555", "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", ":6666": "tcp://127.0.0.1:6666", ":6666/path": "tcp://127.0.0.1:6666/path", "tcp://:7777": "tcp://127.0.0.1:7777", "tcp://:7777/path": "tcp://127.0.0.1:7777/path", "": "unix:///var/run/docker.sock", "unix:///run/docker.sock": "unix:///run/docker.sock", "unix://": "unix:///var/run/docker.sock", "fd://": "fd://", "fd://something": "fd://something", } for invalidAddr, expectedError := range invalids { if addr, err := ParseHost(defaultHttpHost, defaultUnix, invalidAddr); err == nil || err.Error() != expectedError { t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) } } for validAddr, expectedAddr := range valids { if addr, err := ParseHost(defaultHttpHost, defaultUnix, validAddr); err != nil || addr != expectedAddr { t.Errorf("%v -> expected %v, got %v", validAddr, expectedAddr, addr) } } } func TestParseInvalidUnixAddrInvalid(t *testing.T) { if _, err := ParseUnixAddr("unix://tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { t.Fatalf("Expected an error, got %v", err) } } func TestParseRepositoryTag(t *testing.T) { if repo, tag := ParseRepositoryTag("root"); repo != "root" || tag != "" { t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "", repo, tag) } if repo, tag := ParseRepositoryTag("root:tag"); repo != "root" || tag != "tag" { t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "root", "tag", repo, tag) } if repo, digest := ParseRepositoryTag("root@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "root" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "root", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) } if repo, tag := ParseRepositoryTag("user/repo"); repo != "user/repo" || tag != "" { t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "", repo, tag) } if repo, tag := ParseRepositoryTag("user/repo:tag"); repo != "user/repo" || tag != "tag" { t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "user/repo", "tag", repo, tag) } if repo, digest := ParseRepositoryTag("user/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "user/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "user/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) } if repo, tag := ParseRepositoryTag("url:5000/repo"); repo != "url:5000/repo" || tag != "" { t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "", repo, tag) } if repo, tag := ParseRepositoryTag("url:5000/repo:tag"); repo != "url:5000/repo" || tag != "tag" { t.Errorf("Expected repo: '%s' and tag: '%s', got '%s' and '%s'", "url:5000/repo", "tag", repo, tag) } if repo, digest := ParseRepositoryTag("url:5000/repo@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); repo != "url:5000/repo" || digest != "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" { t.Errorf("Expected repo: '%s' and digest: '%s', got '%s' and '%s'", "url:5000/repo", "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", repo, digest) } } func TestParsePortMapping(t *testing.T) { if _, err := PartParser("ip:public:private", "192.168.1.1:80"); err == nil { t.Fatalf("Expected an error, got %v", err) } data, err := PartParser("ip:public:private", "192.168.1.1:80:8080") if err != nil { t.Fatal(err) } if len(data) != 3 { t.FailNow() } if data["ip"] != "192.168.1.1" { t.Fail() } if data["public"] != "80" { t.Fail() } if data["private"] != "8080" { t.Fail() } } func TestParseKeyValueOpt(t *testing.T) { invalids := map[string]string{ "": "Unable to parse key/value option: ", "key": "Unable to parse key/value option: key", } for invalid, expectedError := range invalids { if _, _, err := ParseKeyValueOpt(invalid); err == nil || err.Error() != expectedError { t.Fatalf("Expected error %v for %v, got %v", expectedError, invalid, err) } } valids := map[string][]string{ "key=value": {"key", "value"}, " key = value ": {"key", "value"}, "key=value1=value2": {"key", "value1=value2"}, " key = value1 = value2 ": {"key", "value1 = value2"}, } for valid, expectedKeyValue := range valids { key, value, err := ParseKeyValueOpt(valid) if err != nil { t.Fatal(err) } if key != expectedKeyValue[0] || value != expectedKeyValue[1] { t.Fatalf("Expected {%v: %v} got {%v: %v}", expectedKeyValue[0], expectedKeyValue[1], key, value) } } } func TestParsePortRange(t *testing.T) { if start, end, err := ParsePortRange("8000-8080"); err != nil || start != 8000 || end != 8080 { t.Fatalf("Error: %s or Expecting {start,end} values {8000,8080} but found {%d,%d}.", err, start, end) } } func TestParsePortRangeEmpty(t *testing.T) { if _, _, err := ParsePortRange(""); err == nil || err.Error() != "Empty string specified for ports." { t.Fatalf("Expected error 'Empty string specified for ports.', got %v", err) } } func TestParsePortRangeWithNoRange(t *testing.T) { start, end, err := ParsePortRange("8080") if err != nil { t.Fatal(err) } if start != 8080 || end != 8080 { t.Fatalf("Expected start and end to be the same and equal to 8080, but were %v and %v", start, end) } } func TestParsePortRangeIncorrectRange(t *testing.T) { if _, _, err := ParsePortRange("9000-8080"); err == nil || !strings.Contains(err.Error(), "Invalid range specified for the Port") { t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) } } func TestParsePortRangeIncorrectEndRange(t *testing.T) { if _, _, err := ParsePortRange("8000-a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) } if _, _, err := ParsePortRange("8000-30a"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) } } func TestParsePortRangeIncorrectStartRange(t *testing.T) { if _, _, err := ParsePortRange("a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) } if _, _, err := ParsePortRange("30a-8000"); err == nil || !strings.Contains(err.Error(), "invalid syntax") { t.Fatalf("Expecting error 'Invalid range specified for the Port' but received %s.", err) } } func TestParseLink(t *testing.T) { name, alias, err := ParseLink("name:alias") if err != nil { t.Fatalf("Expected not to error out on a valid name:alias format but got: %v", err) } if name != "name" { t.Fatalf("Link name should have been name, got %s instead", name) } if alias != "alias" { t.Fatalf("Link alias should have been alias, got %s instead", alias) } // short format definition name, alias, err = ParseLink("name") if err != nil { t.Fatalf("Expected not to error out on a valid name only format but got: %v", err) } if name != "name" { t.Fatalf("Link name should have been name, got %s instead", name) } if alias != "name" { t.Fatalf("Link alias should have been name, got %s instead", alias) } // empty string link definition is not allowed if _, _, err := ParseLink(""); err == nil || !strings.Contains(err.Error(), "empty string specified for links") { t.Fatalf("Expected error 'empty string specified for links' but got: %v", err) } // more than two colons are not allowed if _, _, err := ParseLink("link:alias:wrong"); err == nil || !strings.Contains(err.Error(), "bad format for links: link:alias:wrong") { t.Fatalf("Expected error 'bad format for links: link:alias:wrong' but got: %v", err) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/pidfile/pidfile.go ================================================ package pidfile import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" ) type PidFile struct { path string } func checkPidFileAlreadyExists(path string) error { if pidString, err := ioutil.ReadFile(path); err == nil { if pid, err := strconv.Atoi(string(pidString)); err == nil { if _, err := os.Stat(filepath.Join("/proc", string(pid))); err == nil { return fmt.Errorf("pid file found, ensure docker is not running or delete %s", path) } } } return nil } func New(path string) (*PidFile, error) { if err := checkPidFileAlreadyExists(path); err != nil { return nil, err } if err := ioutil.WriteFile(path, []byte(fmt.Sprintf("%d", os.Getpid())), 0644); err != nil { return nil, err } return &PidFile{path: path}, nil } func (file PidFile) Remove() error { if err := os.Remove(file.path); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/pidfile/pidfile_test.go ================================================ package pidfile import ( "io/ioutil" "os" "path/filepath" "testing" ) func TestNewAndRemove(t *testing.T) { dir, err := ioutil.TempDir(os.TempDir(), "test-pidfile") if err != nil { t.Fatal("Could not create test directory") } file, err := New(filepath.Join(dir, "testfile")) if err != nil { t.Fatal("Could not create test file", err) } if err := file.Remove(); err != nil { t.Fatal("Could not delete created test file") } } func TestRemoveInvalidPath(t *testing.T) { file := PidFile{path: filepath.Join("foo", "bar")} if err := file.Remove(); err == nil { t.Fatal("Non-existing file doesn't give an error on delete") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/client.go ================================================ package plugins import ( "bytes" "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/sockets" "github.com/docker/docker/pkg/tlsconfig" ) const ( versionMimetype = "application/vnd.docker.plugins.v1+json" defaultTimeOut = 30 ) func NewClient(addr string, tlsConfig tlsconfig.Options) (*Client, error) { tr := &http.Transport{} c, err := tlsconfig.Client(tlsConfig) if err != nil { return nil, err } tr.TLSClientConfig = c protoAndAddr := strings.Split(addr, "://") sockets.ConfigureTCPTransport(tr, protoAndAddr[0], protoAndAddr[1]) return &Client{&http.Client{Transport: tr}, protoAndAddr[1]}, nil } type Client struct { http *http.Client addr string } func (c *Client) Call(serviceMethod string, args interface{}, ret interface{}) error { return c.callWithRetry(serviceMethod, args, ret, true) } func (c *Client) callWithRetry(serviceMethod string, args interface{}, ret interface{}, retry bool) error { var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(args); err != nil { return err } req, err := http.NewRequest("POST", "/"+serviceMethod, &buf) if err != nil { return err } req.Header.Add("Accept", versionMimetype) req.URL.Scheme = "http" req.URL.Host = c.addr var retries int start := time.Now() for { resp, err := c.http.Do(req) if err != nil { if !retry { return err } timeOff := backoff(retries) if abort(start, timeOff) { return err } retries++ logrus.Warnf("Unable to connect to plugin: %s, retrying in %v", c.addr, timeOff) time.Sleep(timeOff) continue } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { remoteErr, err := ioutil.ReadAll(resp.Body) if err != nil { return fmt.Errorf("Plugin Error: %s", err) } return fmt.Errorf("Plugin Error: %s", remoteErr) } return json.NewDecoder(resp.Body).Decode(&ret) } } func backoff(retries int) time.Duration { b, max := 1, defaultTimeOut for b < max && retries > 0 { b *= 2 retries-- } if b > max { b = max } return time.Duration(b) * time.Second } func abort(start time.Time, timeOff time.Duration) bool { return timeOff+time.Since(start) >= time.Duration(defaultTimeOut)*time.Second } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/client_test.go ================================================ package plugins import ( "io" "net/http" "net/http/httptest" "reflect" "testing" "time" "github.com/docker/docker/pkg/tlsconfig" ) var ( mux *http.ServeMux server *httptest.Server ) func setupRemotePluginServer() string { mux = http.NewServeMux() server = httptest.NewServer(mux) return server.URL } func teardownRemotePluginServer() { if server != nil { server.Close() } } func TestFailedConnection(t *testing.T) { c, _ := NewClient("tcp://127.0.0.1:1", tlsconfig.Options{InsecureSkipVerify: true}) err := c.callWithRetry("Service.Method", nil, nil, false) if err == nil { t.Fatal("Unexpected successful connection") } } func TestEchoInputOutput(t *testing.T) { addr := setupRemotePluginServer() defer teardownRemotePluginServer() m := Manifest{[]string{"VolumeDriver", "NetworkDriver"}} mux.HandleFunc("/Test.Echo", func(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { t.Fatalf("Expected POST, got %s\n", r.Method) } header := w.Header() header.Set("Content-Type", versionMimetype) io.Copy(w, r.Body) }) c, _ := NewClient(addr, tlsconfig.Options{InsecureSkipVerify: true}) var output Manifest err := c.Call("Test.Echo", m, &output) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(output, m) { t.Fatalf("Expected %v, was %v\n", m, output) } } func TestBackoff(t *testing.T) { cases := []struct { retries int expTimeOff time.Duration }{ {0, time.Duration(1)}, {1, time.Duration(2)}, {2, time.Duration(4)}, {4, time.Duration(16)}, {6, time.Duration(30)}, {10, time.Duration(30)}, } for _, c := range cases { s := c.expTimeOff * time.Second if d := backoff(c.retries); d != s { t.Fatalf("Retry %v, expected %v, was %v\n", c.retries, s, d) } } } func TestAbortRetry(t *testing.T) { cases := []struct { timeOff time.Duration expAbort bool }{ {time.Duration(1), false}, {time.Duration(2), false}, {time.Duration(10), false}, {time.Duration(30), true}, {time.Duration(40), true}, } for _, c := range cases { s := c.timeOff * time.Second if a := abort(time.Now(), s); a != c.expAbort { t.Fatalf("Duration %v, expected %v, was %v\n", c.timeOff, s, a) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/discovery.go ================================================ package plugins import ( "encoding/json" "errors" "fmt" "io/ioutil" "net/url" "os" "path/filepath" "strings" ) var ( ErrNotFound = errors.New("Plugin not found") socketsPath = "/run/docker/plugins" specsPaths = []string{"/etc/docker/plugins", "/usr/lib/docker/plugins"} ) type Registry interface { Plugins() ([]*Plugin, error) Plugin(name string) (*Plugin, error) } type LocalRegistry struct{} func newLocalRegistry() LocalRegistry { return LocalRegistry{} } func (l *LocalRegistry) Plugin(name string) (*Plugin, error) { socketpaths := pluginPaths(socketsPath, name, ".sock") for _, p := range socketpaths { if fi, err := os.Stat(p); err == nil && fi.Mode()&os.ModeSocket != 0 { return newLocalPlugin(name, "unix://"+p), nil } } var txtspecpaths []string for _, p := range specsPaths { txtspecpaths = append(txtspecpaths, pluginPaths(p, name, ".spec")...) txtspecpaths = append(txtspecpaths, pluginPaths(p, name, ".json")...) } for _, p := range txtspecpaths { if _, err := os.Stat(p); err == nil { if strings.HasSuffix(p, ".json") { return readPluginJSONInfo(name, p) } return readPluginInfo(name, p) } } return nil, ErrNotFound } func readPluginInfo(name, path string) (*Plugin, error) { content, err := ioutil.ReadFile(path) if err != nil { return nil, err } addr := strings.TrimSpace(string(content)) u, err := url.Parse(addr) if err != nil { return nil, err } if len(u.Scheme) == 0 { return nil, fmt.Errorf("Unknown protocol") } return newLocalPlugin(name, addr), nil } func readPluginJSONInfo(name, path string) (*Plugin, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() var p Plugin if err := json.NewDecoder(f).Decode(&p); err != nil { return nil, err } p.Name = name if len(p.TLSConfig.CAFile) == 0 { p.TLSConfig.InsecureSkipVerify = true } return &p, nil } func pluginPaths(base, name, ext string) []string { return []string{ filepath.Join(base, name+ext), filepath.Join(base, name, name+ext), } } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/discovery_test.go ================================================ package plugins import ( "fmt" "io/ioutil" "net" "os" "path/filepath" "reflect" "testing" ) func setup(t *testing.T) (string, func()) { tmpdir, err := ioutil.TempDir("", "docker-test") if err != nil { t.Fatal(err) } backup := socketsPath socketsPath = tmpdir specsPaths = []string{tmpdir} return tmpdir, func() { socketsPath = backup os.RemoveAll(tmpdir) } } func TestLocalSocket(t *testing.T) { tmpdir, unregister := setup(t) defer unregister() cases := []string{ filepath.Join(tmpdir, "echo.sock"), filepath.Join(tmpdir, "echo", "echo.sock"), } for _, c := range cases { if err := os.MkdirAll(filepath.Dir(c), 0755); err != nil { t.Fatal(err) } l, err := net.Listen("unix", c) if err != nil { t.Fatal(err) } r := newLocalRegistry() p, err := r.Plugin("echo") if err != nil { t.Fatal(err) } pp, err := r.Plugin("echo") if err != nil { t.Fatal(err) } if !reflect.DeepEqual(p, pp) { t.Fatalf("Expected %v, was %v\n", p, pp) } if p.Name != "echo" { t.Fatalf("Expected plugin `echo`, got %s\n", p.Name) } addr := fmt.Sprintf("unix://%s", c) if p.Addr != addr { t.Fatalf("Expected plugin addr `%s`, got %s\n", addr, p.Addr) } if p.TLSConfig.InsecureSkipVerify != true { t.Fatalf("Expected TLS verification to be skipped") } l.Close() } } func TestFileSpecPlugin(t *testing.T) { tmpdir, unregister := setup(t) defer unregister() cases := []struct { path string name string addr string fail bool }{ {filepath.Join(tmpdir, "echo.spec"), "echo", "unix://var/lib/docker/plugins/echo.sock", false}, {filepath.Join(tmpdir, "echo", "echo.spec"), "echo", "unix://var/lib/docker/plugins/echo.sock", false}, {filepath.Join(tmpdir, "foo.spec"), "foo", "tcp://localhost:8080", false}, {filepath.Join(tmpdir, "foo", "foo.spec"), "foo", "tcp://localhost:8080", false}, {filepath.Join(tmpdir, "bar.spec"), "bar", "localhost:8080", true}, // unknown transport } for _, c := range cases { if err := os.MkdirAll(filepath.Dir(c.path), 0755); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(c.path, []byte(c.addr), 0644); err != nil { t.Fatal(err) } r := newLocalRegistry() p, err := r.Plugin(c.name) if c.fail && err == nil { continue } if err != nil { t.Fatal(err) } if p.Name != c.name { t.Fatalf("Expected plugin `%s`, got %s\n", c.name, p.Name) } if p.Addr != c.addr { t.Fatalf("Expected plugin addr `%s`, got %s\n", c.addr, p.Addr) } if p.TLSConfig.InsecureSkipVerify != true { t.Fatalf("Expected TLS verification to be skipped") } } } func TestFileJSONSpecPlugin(t *testing.T) { tmpdir, unregister := setup(t) defer unregister() p := filepath.Join(tmpdir, "example.json") spec := `{ "Name": "plugin-example", "Addr": "https://example.com/docker/plugin", "TLSConfig": { "CAFile": "/usr/shared/docker/certs/example-ca.pem", "CertFile": "/usr/shared/docker/certs/example-cert.pem", "KeyFile": "/usr/shared/docker/certs/example-key.pem" } }` if err := ioutil.WriteFile(p, []byte(spec), 0644); err != nil { t.Fatal(err) } r := newLocalRegistry() plugin, err := r.Plugin("example") if err != nil { t.Fatal(err) } if plugin.Name != "example" { t.Fatalf("Expected plugin `plugin-example`, got %s\n", plugin.Name) } if plugin.Addr != "https://example.com/docker/plugin" { t.Fatalf("Expected plugin addr `https://example.com/docker/plugin`, got %s\n", plugin.Addr) } if plugin.TLSConfig.CAFile != "/usr/shared/docker/certs/example-ca.pem" { t.Fatalf("Expected plugin CA `/usr/shared/docker/certs/example-ca.pem`, got %s\n", plugin.TLSConfig.CAFile) } if plugin.TLSConfig.CertFile != "/usr/shared/docker/certs/example-cert.pem" { t.Fatalf("Expected plugin Certificate `/usr/shared/docker/certs/example-cert.pem`, got %s\n", plugin.TLSConfig.CertFile) } if plugin.TLSConfig.KeyFile != "/usr/shared/docker/certs/example-key.pem" { t.Fatalf("Expected plugin Key `/usr/shared/docker/certs/example-key.pem`, got %s\n", plugin.TLSConfig.KeyFile) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/pluginrpc-gen/fixtures/foo.go ================================================ package foo type wobble struct { Some string Val string Inception *wobble } type Fooer interface{} type Fooer2 interface { Foo() } type Fooer3 interface { Foo() Bar(a string) Baz(a string) (err error) Qux(a, b string) (val string, err error) Wobble() (w *wobble) Wiggle() (w wobble) } type Fooer4 interface { Foo() error } type Bar interface { Boo(a string, b string) (s string, err error) } type Fooer5 interface { Foo() Bar } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/pluginrpc-gen/main.go ================================================ package main import ( "bytes" "flag" "fmt" "go/format" "io/ioutil" "os" "unicode" "unicode/utf8" ) type stringSet struct { values map[string]struct{} } func (s stringSet) String() string { return "" } func (s stringSet) Set(value string) error { s.values[value] = struct{}{} return nil } func (s stringSet) GetValues() map[string]struct{} { return s.values } var ( typeName = flag.String("type", "", "interface type to generate plugin rpc proxy for") rpcName = flag.String("name", *typeName, "RPC name, set if different from type") inputFile = flag.String("i", "", "input file path") outputFile = flag.String("o", *inputFile+"_proxy.go", "output file path") skipFuncs map[string]struct{} flSkipFuncs = stringSet{make(map[string]struct{})} flBuildTags = stringSet{make(map[string]struct{})} ) func errorOut(msg string, err error) { if err == nil { return } fmt.Fprintf(os.Stderr, "%s: %v\n", msg, err) os.Exit(1) } func checkFlags() error { if *outputFile == "" { return fmt.Errorf("missing required flag `-o`") } if *inputFile == "" { return fmt.Errorf("missing required flag `-i`") } return nil } func main() { flag.Var(flSkipFuncs, "skip", "skip parsing for function") flag.Var(flBuildTags, "tag", "build tags to add to generated files") flag.Parse() skipFuncs = flSkipFuncs.GetValues() errorOut("error", checkFlags()) pkg, err := Parse(*inputFile, *typeName) errorOut(fmt.Sprintf("error parsing requested type %s", *typeName), err) var analysis = struct { InterfaceType string RPCName string BuildTags map[string]struct{} *parsedPkg }{toLower(*typeName), *rpcName, flBuildTags.GetValues(), pkg} var buf bytes.Buffer errorOut("parser error", generatedTempl.Execute(&buf, analysis)) src, err := format.Source(buf.Bytes()) errorOut("error formating generated source", err) errorOut("error writing file", ioutil.WriteFile(*outputFile, src, 0644)) } func toLower(s string) string { if s == "" { return "" } r, n := utf8.DecodeRuneInString(s) return string(unicode.ToLower(r)) + s[n:] } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser.go ================================================ package main import ( "errors" "fmt" "go/ast" "go/parser" "go/token" "reflect" "strings" ) var ErrBadReturn = errors.New("found return arg with no name: all args must be named") type ErrUnexpectedType struct { expected string actual interface{} } func (e ErrUnexpectedType) Error() string { return fmt.Sprintf("got wrong type expecting %s, got: %v", e.expected, reflect.TypeOf(e.actual)) } type parsedPkg struct { Name string Functions []function } type function struct { Name string Args []arg Returns []arg Doc string } type arg struct { Name string ArgType string } func (a *arg) String() string { return strings.ToLower(a.Name) + " " + strings.ToLower(a.ArgType) } // Parses the given file for an interface definition with the given name func Parse(filePath string, objName string) (*parsedPkg, error) { fs := token.NewFileSet() pkg, err := parser.ParseFile(fs, filePath, nil, parser.AllErrors) if err != nil { return nil, err } p := &parsedPkg{} p.Name = pkg.Name.Name obj, exists := pkg.Scope.Objects[objName] if !exists { return nil, fmt.Errorf("could not find object %s in %s", objName, filePath) } if obj.Kind != ast.Typ { return nil, fmt.Errorf("exected type, got %s", obj.Kind) } spec, ok := obj.Decl.(*ast.TypeSpec) if !ok { return nil, ErrUnexpectedType{"*ast.TypeSpec", obj.Decl} } iface, ok := spec.Type.(*ast.InterfaceType) if !ok { return nil, ErrUnexpectedType{"*ast.InterfaceType", spec.Type} } p.Functions, err = parseInterface(iface) if err != nil { return nil, err } return p, nil } func parseInterface(iface *ast.InterfaceType) ([]function, error) { var functions []function for _, field := range iface.Methods.List { switch f := field.Type.(type) { case *ast.FuncType: method, err := parseFunc(field) if err != nil { return nil, err } if method == nil { continue } functions = append(functions, *method) case *ast.Ident: spec, ok := f.Obj.Decl.(*ast.TypeSpec) if !ok { return nil, ErrUnexpectedType{"*ast.TypeSpec", f.Obj.Decl} } iface, ok := spec.Type.(*ast.InterfaceType) if !ok { return nil, ErrUnexpectedType{"*ast.TypeSpec", spec.Type} } funcs, err := parseInterface(iface) if err != nil { fmt.Println(err) continue } functions = append(functions, funcs...) default: return nil, ErrUnexpectedType{"*astFuncType or *ast.Ident", f} } } return functions, nil } func parseFunc(field *ast.Field) (*function, error) { f := field.Type.(*ast.FuncType) method := &function{Name: field.Names[0].Name} if _, exists := skipFuncs[method.Name]; exists { fmt.Println("skipping:", method.Name) return nil, nil } if f.Params != nil { args, err := parseArgs(f.Params.List) if err != nil { return nil, err } method.Args = args } if f.Results != nil { returns, err := parseArgs(f.Results.List) if err != nil { return nil, fmt.Errorf("error parsing function returns for %q: %v", method.Name, err) } method.Returns = returns } return method, nil } func parseArgs(fields []*ast.Field) ([]arg, error) { var args []arg for _, f := range fields { if len(f.Names) == 0 { return nil, ErrBadReturn } for _, name := range f.Names { var typeName string switch argType := f.Type.(type) { case *ast.Ident: typeName = argType.Name case *ast.StarExpr: i, ok := argType.X.(*ast.Ident) if !ok { return nil, ErrUnexpectedType{"*ast.Ident", f.Type} } typeName = "*" + i.Name default: return nil, ErrUnexpectedType{"*ast.Ident or *ast.StarExpr", f.Type} } args = append(args, arg{name.Name, typeName}) } } return args, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/pluginrpc-gen/parser_test.go ================================================ package main import ( "fmt" "path/filepath" "runtime" "strings" "testing" ) const testFixture = "fixtures/foo.go" func TestParseEmptyInterface(t *testing.T) { pkg, err := Parse(testFixture, "Fooer") if err != nil { t.Fatal(err) } assertName(t, "foo", pkg.Name) assertNum(t, 0, len(pkg.Functions)) } func TestParseNonInterfaceType(t *testing.T) { _, err := Parse(testFixture, "wobble") if _, ok := err.(ErrUnexpectedType); !ok { t.Fatal("expected type error when parsing non-interface type") } } func TestParseWithOneFunction(t *testing.T) { pkg, err := Parse(testFixture, "Fooer2") if err != nil { t.Fatal(err) } assertName(t, "foo", pkg.Name) assertNum(t, 1, len(pkg.Functions)) assertName(t, "Foo", pkg.Functions[0].Name) assertNum(t, 0, len(pkg.Functions[0].Args)) assertNum(t, 0, len(pkg.Functions[0].Returns)) } func TestParseWithMultipleFuncs(t *testing.T) { pkg, err := Parse(testFixture, "Fooer3") if err != nil { t.Fatal(err) } assertName(t, "foo", pkg.Name) assertNum(t, 6, len(pkg.Functions)) f := pkg.Functions[0] assertName(t, "Foo", f.Name) assertNum(t, 0, len(f.Args)) assertNum(t, 0, len(f.Returns)) f = pkg.Functions[1] assertName(t, "Bar", f.Name) assertNum(t, 1, len(f.Args)) assertNum(t, 0, len(f.Returns)) arg := f.Args[0] assertName(t, "a", arg.Name) assertName(t, "string", arg.ArgType) f = pkg.Functions[2] assertName(t, "Baz", f.Name) assertNum(t, 1, len(f.Args)) assertNum(t, 1, len(f.Returns)) arg = f.Args[0] assertName(t, "a", arg.Name) assertName(t, "string", arg.ArgType) arg = f.Returns[0] assertName(t, "err", arg.Name) assertName(t, "error", arg.ArgType) f = pkg.Functions[3] assertName(t, "Qux", f.Name) assertNum(t, 2, len(f.Args)) assertNum(t, 2, len(f.Returns)) arg = f.Args[0] assertName(t, "a", f.Args[0].Name) assertName(t, "string", f.Args[0].ArgType) arg = f.Args[1] assertName(t, "b", arg.Name) assertName(t, "string", arg.ArgType) arg = f.Returns[0] assertName(t, "val", arg.Name) assertName(t, "string", arg.ArgType) arg = f.Returns[1] assertName(t, "err", arg.Name) assertName(t, "error", arg.ArgType) f = pkg.Functions[4] assertName(t, "Wobble", f.Name) assertNum(t, 0, len(f.Args)) assertNum(t, 1, len(f.Returns)) arg = f.Returns[0] assertName(t, "w", arg.Name) assertName(t, "*wobble", arg.ArgType) f = pkg.Functions[5] assertName(t, "Wiggle", f.Name) assertNum(t, 0, len(f.Args)) assertNum(t, 1, len(f.Returns)) arg = f.Returns[0] assertName(t, "w", arg.Name) assertName(t, "wobble", arg.ArgType) } func TestParseWithUnamedReturn(t *testing.T) { _, err := Parse(testFixture, "Fooer4") if !strings.HasSuffix(err.Error(), ErrBadReturn.Error()) { t.Fatalf("expected ErrBadReturn, got %v", err) } } func TestEmbeddedInterface(t *testing.T) { pkg, err := Parse(testFixture, "Fooer5") if err != nil { t.Fatal(err) } assertName(t, "foo", pkg.Name) assertNum(t, 2, len(pkg.Functions)) f := pkg.Functions[0] assertName(t, "Foo", f.Name) assertNum(t, 0, len(f.Args)) assertNum(t, 0, len(f.Returns)) f = pkg.Functions[1] assertName(t, "Boo", f.Name) assertNum(t, 2, len(f.Args)) assertNum(t, 2, len(f.Returns)) arg := f.Args[0] assertName(t, "a", arg.Name) assertName(t, "string", arg.ArgType) arg = f.Args[1] assertName(t, "b", arg.Name) assertName(t, "string", arg.ArgType) arg = f.Returns[0] assertName(t, "s", arg.Name) assertName(t, "string", arg.ArgType) arg = f.Returns[1] assertName(t, "err", arg.Name) assertName(t, "error", arg.ArgType) } func assertName(t *testing.T, expected, actual string) { if expected != actual { fatalOut(t, fmt.Sprintf("expected name to be `%s`, got: %s", expected, actual)) } } func assertNum(t *testing.T, expected, actual int) { if expected != actual { fatalOut(t, fmt.Sprintf("expected number to be %d, got: %d", expected, actual)) } } func fatalOut(t *testing.T, msg string) { _, file, ln, _ := runtime.Caller(2) t.Fatalf("%s:%d: %s", filepath.Base(file), ln, msg) } ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/pluginrpc-gen/template.go ================================================ package main import ( "strings" "text/template" ) func printArgs(args []arg) string { var argStr []string for _, arg := range args { argStr = append(argStr, arg.String()) } return strings.Join(argStr, ", ") } func marshalType(t string) string { switch t { case "error": // convert error types to plain strings to ensure the values are encoded/decoded properly return "string" default: return t } } func isErr(t string) bool { switch t { case "error": return true default: return false } } // Need to use this helper due to issues with go-vet func buildTag(s string) string { return "+build " + s } var templFuncs = template.FuncMap{ "printArgs": printArgs, "marshalType": marshalType, "isErr": isErr, "lower": strings.ToLower, "title": strings.Title, "tag": buildTag, } var generatedTempl = template.Must(template.New("rpc_cient").Funcs(templFuncs).Parse(` // generated code - DO NOT EDIT {{ range $k, $v := .BuildTags }} // {{ tag $k }} {{ end }} package {{ .Name }} import "errors" type client interface{ Call(string, interface{}, interface{}) error } type {{ .InterfaceType }}Proxy struct { client } {{ range .Functions }} type {{ $.InterfaceType }}Proxy{{ .Name }}Request struct{ {{ range .Args }} {{ title .Name }} {{ .ArgType }} {{ end }} } type {{ $.InterfaceType }}Proxy{{ .Name }}Response struct{ {{ range .Returns }} {{ title .Name }} {{ marshalType .ArgType }} {{ end }} } func (pp *{{ $.InterfaceType }}Proxy) {{ .Name }}({{ printArgs .Args }}) ({{ printArgs .Returns }}) { var( req {{ $.InterfaceType }}Proxy{{ .Name }}Request ret {{ $.InterfaceType }}Proxy{{ .Name }}Response ) {{ range .Args }} req.{{ title .Name }} = {{ lower .Name }} {{ end }} if err = pp.Call("{{ $.RPCName }}.{{ .Name }}", req, &ret); err != nil { return } {{ range $r := .Returns }} {{ if isErr .ArgType }} if ret.{{ title .Name }} != "" { {{ lower .Name }} = errors.New(ret.{{ title .Name }}) } {{ end }} {{ if isErr .ArgType | not }} {{ lower .Name }} = ret.{{ title .Name }} {{ end }} {{ end }} return } {{ end }} `)) ================================================ FILE: vendor/github.com/docker/docker/pkg/plugins/plugins.go ================================================ package plugins import ( "errors" "sync" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/tlsconfig" ) var ( ErrNotImplements = errors.New("Plugin does not implement the requested driver") ) type plugins struct { sync.Mutex plugins map[string]*Plugin } var ( storage = plugins{plugins: make(map[string]*Plugin)} extpointHandlers = make(map[string]func(string, *Client)) ) type Manifest struct { Implements []string } type Plugin struct { Name string `json:"-"` Addr string TLSConfig tlsconfig.Options Client *Client `json:"-"` Manifest *Manifest `json:"-"` } func newLocalPlugin(name, addr string) *Plugin { return &Plugin{ Name: name, Addr: addr, TLSConfig: tlsconfig.Options{InsecureSkipVerify: true}, } } func (p *Plugin) activate() error { c, err := NewClient(p.Addr, p.TLSConfig) if err != nil { return err } p.Client = c m := new(Manifest) if err = p.Client.Call("Plugin.Activate", nil, m); err != nil { return err } logrus.Debugf("%s's manifest: %v", p.Name, m) p.Manifest = m for _, iface := range m.Implements { handler, handled := extpointHandlers[iface] if !handled { continue } handler(p.Name, p.Client) } return nil } func load(name string) (*Plugin, error) { registry := newLocalRegistry() pl, err := registry.Plugin(name) if err != nil { return nil, err } if err := pl.activate(); err != nil { return nil, err } return pl, nil } func get(name string) (*Plugin, error) { storage.Lock() defer storage.Unlock() pl, ok := storage.plugins[name] if ok { return pl, nil } pl, err := load(name) if err != nil { return nil, err } logrus.Debugf("Plugin: %v", pl) storage.plugins[name] = pl return pl, nil } func Get(name, imp string) (*Plugin, error) { pl, err := get(name) if err != nil { return nil, err } for _, driver := range pl.Manifest.Implements { logrus.Debugf("%s implements: %s", name, driver) if driver == imp { return pl, nil } } return nil, ErrNotImplements } func Handle(iface string, fn func(string, *Client)) { extpointHandlers[iface] = fn } ================================================ FILE: vendor/github.com/docker/docker/pkg/pools/pools.go ================================================ // Package pools provides a collection of pools which provide various // data types with buffers. These can be used to lower the number of // memory allocations and reuse buffers. // // New pools should be added to this package to allow them to be // shared across packages. // // Utility functions which operate on pools should be added to this // package to allow them to be reused. package pools import ( "bufio" "io" "sync" "github.com/docker/docker/pkg/ioutils" ) var ( // Pool which returns bufio.Reader with a 32K buffer BufioReader32KPool *BufioReaderPool // Pool which returns bufio.Writer with a 32K buffer BufioWriter32KPool *BufioWriterPool ) const buffer32K = 32 * 1024 type BufioReaderPool struct { pool sync.Pool } func init() { BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K) BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K) } // newBufioReaderPoolWithSize is unexported because new pools should be // added here to be shared where required. func newBufioReaderPoolWithSize(size int) *BufioReaderPool { pool := sync.Pool{ New: func() interface{} { return bufio.NewReaderSize(nil, size) }, } return &BufioReaderPool{pool: pool} } // Get returns a bufio.Reader which reads from r. The buffer size is that of the pool. func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader { buf := bufPool.pool.Get().(*bufio.Reader) buf.Reset(r) return buf } // Put puts the bufio.Reader back into the pool. func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { b.Reset(nil) bufPool.pool.Put(b) } // Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy func Copy(dst io.Writer, src io.Reader) (written int64, err error) { buf := BufioReader32KPool.Get(src) written, err = io.Copy(dst, buf) BufioReader32KPool.Put(buf) return } // NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back // into the pool and closes the reader if it's an io.ReadCloser. func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser { return ioutils.NewReadCloserWrapper(r, func() error { if readCloser, ok := r.(io.ReadCloser); ok { readCloser.Close() } bufPool.Put(buf) return nil }) } type BufioWriterPool struct { pool sync.Pool } // newBufioWriterPoolWithSize is unexported because new pools should be // added here to be shared where required. func newBufioWriterPoolWithSize(size int) *BufioWriterPool { pool := sync.Pool{ New: func() interface{} { return bufio.NewWriterSize(nil, size) }, } return &BufioWriterPool{pool: pool} } // Get returns a bufio.Writer which writes to w. The buffer size is that of the pool. func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer { buf := bufPool.pool.Get().(*bufio.Writer) buf.Reset(w) return buf } // Put puts the bufio.Writer back into the pool. func (bufPool *BufioWriterPool) Put(b *bufio.Writer) { b.Reset(nil) bufPool.pool.Put(b) } // NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back // into the pool and closes the writer if it's an io.Writecloser. func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser { return ioutils.NewWriteCloserWrapper(w, func() error { buf.Flush() if writeCloser, ok := w.(io.WriteCloser); ok { writeCloser.Close() } bufPool.Put(buf) return nil }) } ================================================ FILE: vendor/github.com/docker/docker/pkg/pools/pools_test.go ================================================ package pools import ( "bufio" "bytes" "io" "strings" "testing" ) func TestBufioReaderPoolGetWithNoReaderShouldCreateOne(t *testing.T) { reader := BufioReader32KPool.Get(nil) if reader == nil { t.Fatalf("BufioReaderPool should have create a bufio.Reader but did not.") } } func TestBufioReaderPoolPutAndGet(t *testing.T) { sr := bufio.NewReader(strings.NewReader("foobar")) reader := BufioReader32KPool.Get(sr) if reader == nil { t.Fatalf("BufioReaderPool should not return a nil reader.") } // verify the first 3 byte buf1 := make([]byte, 3) _, err := reader.Read(buf1) if err != nil { t.Fatal(err) } if actual := string(buf1); actual != "foo" { t.Fatalf("The first letter should have been 'foo' but was %v", actual) } BufioReader32KPool.Put(reader) // Try to read the next 3 bytes _, err = sr.Read(make([]byte, 3)) if err == nil || err != io.EOF { t.Fatalf("The buffer should have been empty, issue an EOF error.") } } type simpleReaderCloser struct { io.Reader closed bool } func (r *simpleReaderCloser) Close() error { r.closed = true return nil } func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) { br := bufio.NewReader(strings.NewReader("")) sr := &simpleReaderCloser{ Reader: strings.NewReader("foobar"), closed: false, } reader := BufioReader32KPool.NewReadCloserWrapper(br, sr) if reader == nil { t.Fatalf("NewReadCloserWrapper should not return a nil reader.") } // Verify the content of reader buf := make([]byte, 3) _, err := reader.Read(buf) if err != nil { t.Fatal(err) } if actual := string(buf); actual != "foo" { t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual) } reader.Close() // Read 3 more bytes "bar" _, err = reader.Read(buf) if err != nil { t.Fatal(err) } if actual := string(buf); actual != "bar" { t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual) } if !sr.closed { t.Fatalf("The ReaderCloser should have been closed, it is not.") } } func TestBufioWriterPoolGetWithNoReaderShouldCreateOne(t *testing.T) { writer := BufioWriter32KPool.Get(nil) if writer == nil { t.Fatalf("BufioWriterPool should have create a bufio.Writer but did not.") } } func TestBufioWriterPoolPutAndGet(t *testing.T) { buf := new(bytes.Buffer) bw := bufio.NewWriter(buf) writer := BufioWriter32KPool.Get(bw) if writer == nil { t.Fatalf("BufioReaderPool should not return a nil writer.") } written, err := writer.Write([]byte("foobar")) if err != nil { t.Fatal(err) } if written != 6 { t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) } // Make sure we Flush all the way ? writer.Flush() bw.Flush() if len(buf.Bytes()) != 6 { t.Fatalf("The buffer should contain 6 bytes ('foobar') but contains %v ('%v')", buf.Bytes(), string(buf.Bytes())) } // Reset the buffer buf.Reset() BufioWriter32KPool.Put(writer) // Try to write something written, err = writer.Write([]byte("barfoo")) if err != nil { t.Fatal(err) } // If we now try to flush it, it should panic (the writer is nil) // recover it defer func() { if r := recover(); r == nil { t.Fatal("Trying to flush the writter should have 'paniced', did not.") } }() writer.Flush() } type simpleWriterCloser struct { io.Writer closed bool } func (r *simpleWriterCloser) Close() error { r.closed = true return nil } func TestNewWriteCloserWrapperWithAWriteCloser(t *testing.T) { buf := new(bytes.Buffer) bw := bufio.NewWriter(buf) sw := &simpleWriterCloser{ Writer: new(bytes.Buffer), closed: false, } bw.Flush() writer := BufioWriter32KPool.NewWriteCloserWrapper(bw, sw) if writer == nil { t.Fatalf("BufioReaderPool should not return a nil writer.") } written, err := writer.Write([]byte("foobar")) if err != nil { t.Fatal(err) } if written != 6 { t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) } writer.Close() if !sw.closed { t.Fatalf("The ReaderCloser should have been closed, it is not.") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/progressreader/progressreader.go ================================================ package progressreader import ( "io" "github.com/docker/docker/pkg/jsonmessage" "github.com/docker/docker/pkg/streamformatter" ) // Reader with progress bar type Config struct { In io.ReadCloser // Stream to read from Out io.Writer // Where to send progress bar to Formatter *streamformatter.StreamFormatter Size int Current int LastUpdate int NewLines bool ID string Action string } func New(newReader Config) *Config { return &newReader } func (config *Config) Read(p []byte) (n int, err error) { read, err := config.In.Read(p) config.Current += read updateEvery := 1024 * 512 //512kB if config.Size > 0 { // Update progress for every 1% read if 1% < 512kB if increment := int(0.01 * float64(config.Size)); increment < updateEvery { updateEvery = increment } } if config.Current-config.LastUpdate > updateEvery || err != nil { updateProgress(config) config.LastUpdate = config.Current } if err != nil && read == 0 { updateProgress(config) if config.NewLines { config.Out.Write(config.Formatter.FormatStatus("", "")) } } return read, err } func (config *Config) Close() error { if config.Current < config.Size { //print a full progress bar when closing prematurely config.Current = config.Size updateProgress(config) } return config.In.Close() } func updateProgress(config *Config) { progress := jsonmessage.JSONProgress{Current: config.Current, Total: config.Size} fmtMessage := config.Formatter.FormatProgress(config.ID, config.Action, &progress) config.Out.Write(fmtMessage) } ================================================ FILE: vendor/github.com/docker/docker/pkg/progressreader/progressreader_test.go ================================================ package progressreader import ( "bufio" "bytes" "io" "io/ioutil" "testing" "github.com/docker/docker/pkg/streamformatter" ) func TestOutputOnPrematureClose(t *testing.T) { var outBuf bytes.Buffer content := []byte("TESTING") reader := ioutil.NopCloser(bytes.NewReader(content)) writer := bufio.NewWriter(&outBuf) prCfg := Config{ In: reader, Out: writer, Formatter: streamformatter.NewStreamFormatter(), Size: len(content), NewLines: true, ID: "Test", Action: "Read", } pr := New(prCfg) part := make([]byte, 4, 4) _, err := io.ReadFull(pr, part) if err != nil { pr.Close() t.Fatal(err) } if err := writer.Flush(); err != nil { pr.Close() t.Fatal(err) } tlen := outBuf.Len() pr.Close() if err := writer.Flush(); err != nil { t.Fatal(err) } if outBuf.Len() == tlen { t.Fatalf("Expected some output when closing prematurely") } } func TestCompleteSilently(t *testing.T) { var outBuf bytes.Buffer content := []byte("TESTING") reader := ioutil.NopCloser(bytes.NewReader(content)) writer := bufio.NewWriter(&outBuf) prCfg := Config{ In: reader, Out: writer, Formatter: streamformatter.NewStreamFormatter(), Size: len(content), NewLines: true, ID: "Test", Action: "Read", } pr := New(prCfg) out, err := ioutil.ReadAll(pr) if err != nil { pr.Close() t.Fatal(err) } if string(out) != "TESTING" { pr.Close() t.Fatalf("Unexpected output %q from reader", string(out)) } if err := writer.Flush(); err != nil { pr.Close() t.Fatal(err) } tlen := outBuf.Len() pr.Close() if err := writer.Flush(); err != nil { t.Fatal(err) } if outBuf.Len() > tlen { t.Fatalf("Should have closed silently when read is complete") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/promise/promise.go ================================================ package promise // Go is a basic promise implementation: it wraps calls a function in a goroutine, // and returns a channel which will later return the function's return value. func Go(f func() error) chan error { ch := make(chan error, 1) go func() { ch <- f() }() return ch } ================================================ FILE: vendor/github.com/docker/docker/pkg/proxy/network_proxy_test.go ================================================ package proxy import ( "bytes" "fmt" "io" "net" "strings" "testing" "time" ) var testBuf = []byte("Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo") var testBufSize = len(testBuf) type EchoServer interface { Run() Close() LocalAddr() net.Addr } type TCPEchoServer struct { listener net.Listener testCtx *testing.T } type UDPEchoServer struct { conn net.PacketConn testCtx *testing.T } func NewEchoServer(t *testing.T, proto, address string) EchoServer { var server EchoServer if strings.HasPrefix(proto, "tcp") { listener, err := net.Listen(proto, address) if err != nil { t.Fatal(err) } server = &TCPEchoServer{listener: listener, testCtx: t} } else { socket, err := net.ListenPacket(proto, address) if err != nil { t.Fatal(err) } server = &UDPEchoServer{conn: socket, testCtx: t} } return server } func (server *TCPEchoServer) Run() { go func() { for { client, err := server.listener.Accept() if err != nil { return } go func(client net.Conn) { if _, err := io.Copy(client, client); err != nil { server.testCtx.Logf("can't echo to the client: %v\n", err.Error()) } client.Close() }(client) } }() } func (server *TCPEchoServer) LocalAddr() net.Addr { return server.listener.Addr() } func (server *TCPEchoServer) Close() { server.listener.Addr() } func (server *UDPEchoServer) Run() { go func() { readBuf := make([]byte, 1024) for { read, from, err := server.conn.ReadFrom(readBuf) if err != nil { return } for i := 0; i != read; { written, err := server.conn.WriteTo(readBuf[i:read], from) if err != nil { break } i += written } } }() } func (server *UDPEchoServer) LocalAddr() net.Addr { return server.conn.LocalAddr() } func (server *UDPEchoServer) Close() { server.conn.Close() } func testProxyAt(t *testing.T, proto string, proxy Proxy, addr string) { defer proxy.Close() go proxy.Run() client, err := net.Dial(proto, addr) if err != nil { t.Fatalf("Can't connect to the proxy: %v", err) } defer client.Close() client.SetDeadline(time.Now().Add(10 * time.Second)) if _, err = client.Write(testBuf); err != nil { t.Fatal(err) } recvBuf := make([]byte, testBufSize) if _, err = client.Read(recvBuf); err != nil { t.Fatal(err) } if !bytes.Equal(testBuf, recvBuf) { t.Fatal(fmt.Errorf("Expected [%v] but got [%v]", testBuf, recvBuf)) } } func testProxy(t *testing.T, proto string, proxy Proxy) { testProxyAt(t, proto, proxy, proxy.FrontendAddr().String()) } func TestTCP4Proxy(t *testing.T) { backend := NewEchoServer(t, "tcp", "127.0.0.1:0") defer backend.Close() backend.Run() frontendAddr := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0} proxy, err := NewProxy(frontendAddr, backend.LocalAddr()) if err != nil { t.Fatal(err) } testProxy(t, "tcp", proxy) } func TestTCP6Proxy(t *testing.T) { backend := NewEchoServer(t, "tcp", "[::1]:0") defer backend.Close() backend.Run() frontendAddr := &net.TCPAddr{IP: net.IPv6loopback, Port: 0} proxy, err := NewProxy(frontendAddr, backend.LocalAddr()) if err != nil { t.Fatal(err) } testProxy(t, "tcp", proxy) } func TestTCPDualStackProxy(t *testing.T) { // If I understand `godoc -src net favoriteAddrFamily` (used by the // net.Listen* functions) correctly this should work, but it doesn't. t.Skip("No support for dual stack yet") backend := NewEchoServer(t, "tcp", "[::1]:0") defer backend.Close() backend.Run() frontendAddr := &net.TCPAddr{IP: net.IPv6loopback, Port: 0} proxy, err := NewProxy(frontendAddr, backend.LocalAddr()) if err != nil { t.Fatal(err) } ipv4ProxyAddr := &net.TCPAddr{ IP: net.IPv4(127, 0, 0, 1), Port: proxy.FrontendAddr().(*net.TCPAddr).Port, } testProxyAt(t, "tcp", proxy, ipv4ProxyAddr.String()) } func TestUDP4Proxy(t *testing.T) { backend := NewEchoServer(t, "udp", "127.0.0.1:0") defer backend.Close() backend.Run() frontendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0} proxy, err := NewProxy(frontendAddr, backend.LocalAddr()) if err != nil { t.Fatal(err) } testProxy(t, "udp", proxy) } func TestUDP6Proxy(t *testing.T) { backend := NewEchoServer(t, "udp", "[::1]:0") defer backend.Close() backend.Run() frontendAddr := &net.UDPAddr{IP: net.IPv6loopback, Port: 0} proxy, err := NewProxy(frontendAddr, backend.LocalAddr()) if err != nil { t.Fatal(err) } testProxy(t, "udp", proxy) } func TestUDPWriteError(t *testing.T) { frontendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0} // Hopefully, this port will be free: */ backendAddr := &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 25587} proxy, err := NewProxy(frontendAddr, backendAddr) if err != nil { t.Fatal(err) } defer proxy.Close() go proxy.Run() client, err := net.Dial("udp", "127.0.0.1:25587") if err != nil { t.Fatalf("Can't connect to the proxy: %v", err) } defer client.Close() // Make sure the proxy doesn't stop when there is no actual backend: client.Write(testBuf) client.Write(testBuf) backend := NewEchoServer(t, "udp", "127.0.0.1:25587") defer backend.Close() backend.Run() client.SetDeadline(time.Now().Add(10 * time.Second)) if _, err = client.Write(testBuf); err != nil { t.Fatal(err) } recvBuf := make([]byte, testBufSize) if _, err = client.Read(recvBuf); err != nil { t.Fatal(err) } if !bytes.Equal(testBuf, recvBuf) { t.Fatal(fmt.Errorf("Expected [%v] but got [%v]", testBuf, recvBuf)) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/proxy/proxy.go ================================================ package proxy import ( "fmt" "net" ) type Proxy interface { // Start forwarding traffic back and forth the front and back-end // addresses. Run() // Stop forwarding traffic and close both ends of the Proxy. Close() // Return the address on which the proxy is listening. FrontendAddr() net.Addr // Return the proxied address. BackendAddr() net.Addr } 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(fmt.Errorf("Unsupported protocol")) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/proxy/stub_proxy.go ================================================ package proxy import ( "net" ) type StubProxy struct { frontendAddr net.Addr backendAddr net.Addr } func (p *StubProxy) Run() {} func (p *StubProxy) Close() {} func (p *StubProxy) FrontendAddr() net.Addr { return p.frontendAddr } func (p *StubProxy) BackendAddr() net.Addr { return p.backendAddr } func NewStubProxy(frontendAddr, backendAddr net.Addr) (Proxy, error) { return &StubProxy{ frontendAddr: frontendAddr, backendAddr: backendAddr, }, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/proxy/tcp_proxy.go ================================================ package proxy import ( "io" "net" "syscall" "github.com/Sirupsen/logrus" ) type TCPProxy struct { listener *net.TCPListener frontendAddr *net.TCPAddr backendAddr *net.TCPAddr } 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 { logrus.Printf("Can't forward traffic to backend tcp/%v: %s\n", proxy.backendAddr, err) client.Close() return } event := make(chan int64) var broker = func(to, from *net.TCPConn) { written, err := io.Copy(to, from) if err != nil { // If the socket we are writing to is shutdown with // SHUT_WR, forward it to the other end of the pipe: if err, ok := err.(*net.OpError); ok && err.Err == syscall.EPIPE { from.CloseWrite() } } to.CloseRead() event <- written } go broker(client, backend) go broker(backend, client) var transferred int64 = 0 for i := 0; i < 2; i++ { select { case written := <-event: transferred += written case <-quit: // Interrupt the two brokers and "join" them. client.Close() backend.Close() for ; i < 2; i++ { transferred += <-event } return } } client.Close() backend.Close() } func (proxy *TCPProxy) Run() { quit := make(chan bool) defer close(quit) for { client, err := proxy.listener.Accept() if err != nil { logrus.Printf("Stopping proxy on tcp/%v for tcp/%v (%s)", proxy.frontendAddr, proxy.backendAddr, err) return } go proxy.clientLoop(client.(*net.TCPConn), quit) } } func (proxy *TCPProxy) Close() { proxy.listener.Close() } func (proxy *TCPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr } func (proxy *TCPProxy) BackendAddr() net.Addr { return proxy.backendAddr } ================================================ FILE: vendor/github.com/docker/docker/pkg/proxy/udp_proxy.go ================================================ package proxy import ( "encoding/binary" "net" "strings" "sync" "syscall" "time" "github.com/Sirupsen/logrus" ) const ( UDPConnTrackTimeout = 90 * time.Second 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 type UDPProxy struct { listener *net.UDPConn frontendAddr *net.UDPAddr backendAddr *net.UDPAddr connTrackTable connTrackMap connTrackLock sync.Mutex } 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 } } } 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) { logrus.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 { logrus.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 { logrus.Printf("Can't proxy a datagram to udp/%s: %s\n", proxy.backendAddr, err) break } i += written } } } func (proxy *UDPProxy) Close() { proxy.listener.Close() proxy.connTrackLock.Lock() defer proxy.connTrackLock.Unlock() for _, conn := range proxy.connTrackTable { conn.Close() } } func (proxy *UDPProxy) FrontendAddr() net.Addr { return proxy.frontendAddr } 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") } ================================================ FILE: vendor/github.com/docker/docker/pkg/pubsub/publisher.go ================================================ package pubsub import ( "sync" "time" ) // NewPublisher creates a new pub/sub publisher to broadcast messages. // The duration is used as the send timeout as to not block the publisher publishing // messages to other clients if one client is slow or unresponsive. // The buffer is used when creating new channels for subscribers. func NewPublisher(publishTimeout time.Duration, buffer int) *Publisher { return &Publisher{ buffer: buffer, timeout: publishTimeout, subscribers: make(map[subscriber]struct{}), } } type subscriber chan interface{} // Publisher is basic pub/sub structure. Allows to send events and subscribe // to them. Can be safely used from multiple goroutines. type Publisher struct { m sync.RWMutex buffer int timeout time.Duration subscribers map[subscriber]struct{} } // Len returns the number of subscribers for the publisher func (p *Publisher) Len() int { p.m.RLock() i := len(p.subscribers) p.m.RUnlock() return i } // Subscribe adds a new subscriber to the publisher returning the channel. func (p *Publisher) Subscribe() chan interface{} { ch := make(chan interface{}, p.buffer) p.m.Lock() p.subscribers[ch] = struct{}{} p.m.Unlock() return ch } // Evict removes the specified subscriber from receiving any more messages. func (p *Publisher) Evict(sub chan interface{}) { p.m.Lock() delete(p.subscribers, sub) close(sub) p.m.Unlock() } // Publish sends the data in v to all subscribers currently registered with the publisher. func (p *Publisher) Publish(v interface{}) { p.m.RLock() for sub := range p.subscribers { // send under a select as to not block if the receiver is unavailable if p.timeout > 0 { select { case sub <- v: case <-time.After(p.timeout): } continue } select { case sub <- v: default: } } p.m.RUnlock() } // Close closes the channels to all subscribers registered with the publisher. func (p *Publisher) Close() { p.m.Lock() for sub := range p.subscribers { delete(p.subscribers, sub) close(sub) } p.m.Unlock() } ================================================ FILE: vendor/github.com/docker/docker/pkg/pubsub/publisher_test.go ================================================ package pubsub import ( "fmt" "testing" "time" ) func TestSendToOneSub(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) c := p.Subscribe() p.Publish("hi") msg := <-c if msg.(string) != "hi" { t.Fatalf("expected message hi but received %v", msg) } } func TestSendToMultipleSubs(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) subs := []chan interface{}{} subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe()) p.Publish("hi") for _, c := range subs { msg := <-c if msg.(string) != "hi" { t.Fatalf("expected message hi but received %v", msg) } } } func TestEvictOneSub(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) s1 := p.Subscribe() s2 := p.Subscribe() p.Evict(s1) p.Publish("hi") if _, ok := <-s1; ok { t.Fatal("expected s1 to not receive the published message") } msg := <-s2 if msg.(string) != "hi" { t.Fatalf("expected message hi but received %v", msg) } } func TestClosePublisher(t *testing.T) { p := NewPublisher(100*time.Millisecond, 10) subs := []chan interface{}{} subs = append(subs, p.Subscribe(), p.Subscribe(), p.Subscribe()) p.Close() for _, c := range subs { if _, ok := <-c; ok { t.Fatal("expected all subscriber channels to be closed") } } } const sampleText = "test" type testSubscriber struct { dataCh chan interface{} ch chan error } func (s *testSubscriber) Wait() error { return <-s.ch } func newTestSubscriber(p *Publisher) *testSubscriber { ts := &testSubscriber{ dataCh: p.Subscribe(), ch: make(chan error), } go func() { for data := range ts.dataCh { s, ok := data.(string) if !ok { ts.ch <- fmt.Errorf("Unexpected type %T", data) break } if s != sampleText { ts.ch <- fmt.Errorf("Unexpected text %s", s) break } } close(ts.ch) }() return ts } // for testing with -race func TestPubSubRace(t *testing.T) { p := NewPublisher(0, 1024) var subs [](*testSubscriber) for j := 0; j < 50; j++ { subs = append(subs, newTestSubscriber(p)) } for j := 0; j < 1000; j++ { p.Publish(sampleText) } time.AfterFunc(1*time.Second, func() { for _, s := range subs { p.Evict(s.dataCh) } }) for _, s := range subs { s.Wait() } } func BenchmarkPubSub(b *testing.B) { for i := 0; i < b.N; i++ { b.StopTimer() p := NewPublisher(0, 1024) var subs [](*testSubscriber) for j := 0; j < 50; j++ { subs = append(subs, newTestSubscriber(p)) } b.StartTimer() for j := 0; j < 1000; j++ { p.Publish(sampleText) } time.AfterFunc(1*time.Second, func() { for _, s := range subs { p.Evict(s.dataCh) } }) for _, s := range subs { if err := s.Wait(); err != nil { b.Fatal(err) } } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/random/random.go ================================================ package random import ( "math/rand" "sync" "time" ) // copypaste from standard math/rand 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() } // NewSource returns math/rand.Source safe for concurrent use and initialized // with current unix-nano timestamp func NewSource() rand.Source { return &lockedSource{ src: rand.NewSource(time.Now().UnixNano()), } } ================================================ FILE: vendor/github.com/docker/docker/pkg/random/random_test.go ================================================ package random import ( "math/rand" "sync" "testing" ) // for go test -v -race func TestConcurrency(t *testing.T) { rnd := rand.New(NewSource()) var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { rnd.Int63() wg.Done() }() } wg.Wait() } ================================================ FILE: vendor/github.com/docker/docker/pkg/reexec/README.md ================================================ ## reexec The `reexec` package facilitates the busybox style reexec of the docker binary that we require because of the forking limitations of using Go. Handlers can be registered with a name and the argv 0 of the exec of the binary will be used to find and execute custom init paths. ================================================ FILE: vendor/github.com/docker/docker/pkg/reexec/command_linux.go ================================================ // +build linux package reexec import ( "os/exec" "syscall" ) // Command returns *exec.Cmd which have Path as current binary. Also it setting // SysProcAttr.Pdeathsig to SIGTERM. // For example if current binary is "docker" at "/usr/bin", then cmd.Path will // be set to "/usr/bin/docker". func Command(args ...string) *exec.Cmd { return &exec.Cmd{ Path: Self(), Args: args, SysProcAttr: &syscall.SysProcAttr{ Pdeathsig: syscall.SIGTERM, }, } } ================================================ FILE: vendor/github.com/docker/docker/pkg/reexec/command_unsupported.go ================================================ // +build !linux,!windows package reexec import ( "os/exec" ) // Command is unsupported on operating systems apart from Linux and Windows. func Command(args ...string) *exec.Cmd { return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/reexec/command_windows.go ================================================ // +build windows package reexec import ( "os/exec" ) // Command returns *exec.Cmd which have Path as current binary. // For example if current binary is "docker.exe" at "C:\", then cmd.Path will // be set to "C:\docker.exe". func Command(args ...string) *exec.Cmd { return &exec.Cmd{ Path: Self(), Args: args, } } ================================================ FILE: vendor/github.com/docker/docker/pkg/reexec/reexec.go ================================================ package reexec import ( "fmt" "os" "os/exec" "path/filepath" ) var registeredInitializers = make(map[string]func()) // Register adds an initialization func under the specified name func Register(name string, initializer func()) { if _, exists := registeredInitializers[name]; exists { panic(fmt.Sprintf("reexec func already registred under name %q", name)) } registeredInitializers[name] = initializer } // Init is called as the first part of the exec process and returns true if an // initialization function was called. func Init() bool { initializer, exists := registeredInitializers[os.Args[0]] if exists { initializer() return true } return false } // Self returns the path to the current processes binary func Self() string { name := os.Args[0] if filepath.Base(name) == name { if lp, err := exec.LookPath(name); err == nil { return lp } } // handle conversion of relative paths to absolute if absName, err := filepath.Abs(name); err == nil { return absName } // if we coudn't get absolute name, return original // (NOTE: Go only errors on Abs() if os.Getwd fails) return name } ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/README.md ================================================ This package provides helper functions for dealing with signals across various operating systems ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal.go ================================================ package signal import ( "os" "os/signal" ) func CatchAll(sigc chan os.Signal) { handledSigs := []os.Signal{} for _, s := range SignalMap { handledSigs = append(handledSigs, s) } signal.Notify(sigc, handledSigs...) } func StopCatch(sigc chan os.Signal) { signal.Stop(sigc) close(sigc) } ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal_darwin.go ================================================ package signal import ( "syscall" ) var SignalMap = map[string]syscall.Signal{ "ABRT": syscall.SIGABRT, "ALRM": syscall.SIGALRM, "BUG": syscall.SIGBUS, "CHLD": syscall.SIGCHLD, "CONT": syscall.SIGCONT, "EMT": syscall.SIGEMT, "FPE": syscall.SIGFPE, "HUP": syscall.SIGHUP, "ILL": syscall.SIGILL, "INFO": syscall.SIGINFO, "INT": syscall.SIGINT, "IO": syscall.SIGIO, "IOT": syscall.SIGIOT, "KILL": syscall.SIGKILL, "PIPE": syscall.SIGPIPE, "PROF": syscall.SIGPROF, "QUIT": syscall.SIGQUIT, "SEGV": syscall.SIGSEGV, "STOP": syscall.SIGSTOP, "SYS": syscall.SIGSYS, "TERM": syscall.SIGTERM, "TRAP": syscall.SIGTRAP, "TSTP": syscall.SIGTSTP, "TTIN": syscall.SIGTTIN, "TTOU": syscall.SIGTTOU, "URG": syscall.SIGURG, "USR1": syscall.SIGUSR1, "USR2": syscall.SIGUSR2, "VTALRM": syscall.SIGVTALRM, "WINCH": syscall.SIGWINCH, "XCPU": syscall.SIGXCPU, "XFSZ": syscall.SIGXFSZ, } ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal_freebsd.go ================================================ package signal import ( "syscall" ) var SignalMap = map[string]syscall.Signal{ "ABRT": syscall.SIGABRT, "ALRM": syscall.SIGALRM, "BUF": syscall.SIGBUS, "CHLD": syscall.SIGCHLD, "CONT": syscall.SIGCONT, "EMT": syscall.SIGEMT, "FPE": syscall.SIGFPE, "HUP": syscall.SIGHUP, "ILL": syscall.SIGILL, "INFO": syscall.SIGINFO, "INT": syscall.SIGINT, "IO": syscall.SIGIO, "IOT": syscall.SIGIOT, "KILL": syscall.SIGKILL, "LWP": syscall.SIGLWP, "PIPE": syscall.SIGPIPE, "PROF": syscall.SIGPROF, "QUIT": syscall.SIGQUIT, "SEGV": syscall.SIGSEGV, "STOP": syscall.SIGSTOP, "SYS": syscall.SIGSYS, "TERM": syscall.SIGTERM, "THR": syscall.SIGTHR, "TRAP": syscall.SIGTRAP, "TSTP": syscall.SIGTSTP, "TTIN": syscall.SIGTTIN, "TTOU": syscall.SIGTTOU, "URG": syscall.SIGURG, "USR1": syscall.SIGUSR1, "USR2": syscall.SIGUSR2, "VTALRM": syscall.SIGVTALRM, "WINCH": syscall.SIGWINCH, "XCPU": syscall.SIGXCPU, "XFSZ": syscall.SIGXFSZ, } ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal_linux.go ================================================ package signal import ( "syscall" ) 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, } ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal_unix.go ================================================ // +build !windows package signal import ( "syscall" ) // Signals used in api/client (no windows equivalent, use // invalid signals so they don't get handled) const SIGCHLD = syscall.SIGCHLD const SIGWINCH = syscall.SIGWINCH ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal_unsupported.go ================================================ // +build !linux,!darwin,!freebsd package signal import ( "syscall" ) var SignalMap = map[string]syscall.Signal{} ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/signal_windows.go ================================================ // +build windows package signal import ( "syscall" ) // Signals used in api/client (no windows equivalent, use // invalid signals so they don't get handled) const SIGCHLD = syscall.Signal(0xff) const SIGWINCH = syscall.Signal(0xff) ================================================ FILE: vendor/github.com/docker/docker/pkg/signal/trap.go ================================================ package signal import ( "os" gosignal "os/signal" "runtime" "sync/atomic" "syscall" "github.com/Sirupsen/logrus" ) // Trap sets up a simplified signal "trap", appropriate for common // behavior expected from a vanilla unix command-line tool in general // (and the Docker engine in particular). // // * If SIGINT or SIGTERM are received, `cleanup` is called, then the process is terminated. // * If SIGINT or SIGTERM are received 3 times before cleanup is complete, then cleanup is // skipped and the process is terminated immediately (allows force quit of stuck daemon) // * A SIGQUIT always causes an exit without cleanup, with a goroutine dump preceding exit. // func Trap(cleanup func()) { c := make(chan os.Signal, 1) // we will handle INT, TERM, QUIT here signals := []os.Signal{os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT} gosignal.Notify(c, signals...) go func() { interruptCount := uint32(0) for sig := range c { go func(sig os.Signal) { logrus.Infof("Processing signal '%v'", sig) switch sig { case os.Interrupt, syscall.SIGTERM: if atomic.LoadUint32(&interruptCount) < 3 { // Initiate the cleanup only once if atomic.AddUint32(&interruptCount, 1) == 1 { // Call the provided cleanup handler cleanup() os.Exit(0) } else { return } } else { // 3 SIGTERM/INT signals received; force exit without cleanup logrus.Infof("Forcing docker daemon shutdown without cleanup; 3 interrupts received") } case syscall.SIGQUIT: DumpStacks() logrus.Infof("Forcing docker daemon shutdown without cleanup on SIGQUIT") } //for the SIGINT/TERM, and SIGQUIT non-clean shutdown case, exit with 128 + signal # os.Exit(128 + int(sig.(syscall.Signal))) }(sig) } }() } func DumpStacks() { buf := make([]byte, 16384) buf = buf[:runtime.Stack(buf, true)] // Note that if the daemon is started with a less-verbose log-level than "info" (the default), the goroutine // traces won't show up in the log. logrus.Infof("=== BEGIN goroutine stack dump ===\n%s\n=== END goroutine stack dump ===", buf) } ================================================ FILE: vendor/github.com/docker/docker/pkg/sockets/README.md ================================================ ================================================ FILE: vendor/github.com/docker/docker/pkg/sockets/tcp_socket.go ================================================ package sockets import ( "crypto/tls" "net" "net/http" "time" "github.com/docker/docker/pkg/listenbuffer" ) func NewTcpSocket(addr string, tlsConfig *tls.Config, activate <-chan struct{}) (net.Listener, error) { l, err := listenbuffer.NewListenBuffer("tcp", addr, activate) if err != nil { return nil, err } if tlsConfig != nil { tlsConfig.NextProtos = []string{"http/1.1"} l = tls.NewListener(l, tlsConfig) } return l, nil } func ConfigureTCPTransport(tr *http.Transport, proto, addr string) { // Why 32? See https://github.com/docker/docker/pull/8035. timeout := 32 * time.Second if proto == "unix" { // No need for compression in local communications. tr.DisableCompression = true tr.Dial = func(_, _ string) (net.Conn, error) { return net.DialTimeout(proto, addr, timeout) } } else { tr.Proxy = http.ProxyFromEnvironment tr.Dial = (&net.Dialer{Timeout: timeout}).Dial } } ================================================ FILE: vendor/github.com/docker/docker/pkg/sockets/unix_socket.go ================================================ // +build linux package sockets import ( "fmt" "net" "os" "strconv" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/listenbuffer" "github.com/opencontainers/runc/libcontainer/user" ) func NewUnixSocket(path, group string, activate <-chan struct{}) (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 := listenbuffer.NewListenBuffer("unix", path, activate) if err != nil { return nil, err } if err := setSocketGroup(path, group); err != nil { l.Close() return nil, err } if err := os.Chmod(path, 0660); err != nil { l.Close() return nil, err } return l, nil } func setSocketGroup(path, group string) error { if group == "" { return nil } if err := changeGroup(path, group); err != nil { if group != "docker" { return err } logrus.Debugf("Warning: could not change group %s to docker: %v", path, err) } return nil } func changeGroup(path string, nameOrGid string) error { gid, err := lookupGidByName(nameOrGid) if err != nil { return err } logrus.Debugf("%s group found. gid: %d", nameOrGid, gid) return os.Chown(path, 0, gid) } func lookupGidByName(nameOrGid string) (int, error) { groupFile, err := user.GetGroupPath() if err != nil { return -1, err } groups, err := user.ParseGroupFileFilter(groupFile, func(g user.Group) bool { return g.Name == nameOrGid || strconv.Itoa(g.Gid) == nameOrGid }) if err != nil { return -1, err } if groups != nil && len(groups) > 0 { return groups[0].Gid, nil } gid, err := strconv.Atoi(nameOrGid) if err == nil { logrus.Warnf("Could not find GID %d", gid) return gid, nil } return -1, fmt.Errorf("Group %s not found", nameOrGid) } ================================================ FILE: vendor/github.com/docker/docker/pkg/stdcopy/stdcopy.go ================================================ package stdcopy import ( "encoding/binary" "errors" "io" "github.com/Sirupsen/logrus" ) const ( StdWriterPrefixLen = 8 StdWriterFdIndex = 0 StdWriterSizeIndex = 4 ) type StdType [StdWriterPrefixLen]byte var ( Stdin StdType = StdType{0: 0} Stdout StdType = StdType{0: 1} Stderr StdType = StdType{0: 2} ) type StdWriter struct { io.Writer prefix StdType sizeBuf []byte } func (w *StdWriter) Write(buf []byte) (n int, err error) { var n1, n2 int if w == nil || w.Writer == nil { return 0, errors.New("Writer not instantiated") } binary.BigEndian.PutUint32(w.prefix[4:], uint32(len(buf))) n1, err = w.Writer.Write(w.prefix[:]) if err != nil { n = n1 - StdWriterPrefixLen } else { n2, err = w.Writer.Write(buf) n = n1 + n2 - StdWriterPrefixLen } if n < 0 { n = 0 } return } // NewStdWriter instantiates a new Writer. // Everything written to it will be encapsulated using a custom format, // and written to the underlying `w` stream. // This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. // `t` indicates the id of the stream to encapsulate. // It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. func NewStdWriter(w io.Writer, t StdType) *StdWriter { return &StdWriter{ Writer: w, prefix: t, sizeBuf: make([]byte, 4), } } var ErrInvalidStdHeader = errors.New("Unrecognized input header") // StdCopy is a modified version of io.Copy. // // StdCopy will demultiplex `src`, assuming that it contains two streams, // previously multiplexed together using a StdWriter instance. // As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. // // StdCopy will read until it hits EOF on `src`. It will then return a nil error. // In other words: if `err` is non nil, it indicates a real underlying error. // // `written` will hold the total number of bytes written to `dstout` and `dsterr`. func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { var ( buf = make([]byte, 32*1024+StdWriterPrefixLen+1) bufLen = len(buf) nr, nw int er, ew error out io.Writer frameSize int ) for { // Make sure we have at least a full header for nr < StdWriterPrefixLen { var nr2 int nr2, er = src.Read(buf[nr:]) nr += nr2 if er == io.EOF { if nr < StdWriterPrefixLen { logrus.Debugf("Corrupted prefix: %v", buf[:nr]) return written, nil } break } if er != nil { logrus.Debugf("Error reading header: %s", er) return 0, er } } // Check the first byte to know where to write switch buf[StdWriterFdIndex] { case 0: fallthrough case 1: // Write on stdout out = dstout case 2: // Write on stderr out = dsterr default: logrus.Debugf("Error selecting output fd: (%d)", buf[StdWriterFdIndex]) return 0, ErrInvalidStdHeader } // Retrieve the size of the frame frameSize = int(binary.BigEndian.Uint32(buf[StdWriterSizeIndex : StdWriterSizeIndex+4])) logrus.Debugf("framesize: %d", frameSize) // Check if the buffer is big enough to read the frame. // Extend it if necessary. if frameSize+StdWriterPrefixLen > bufLen { logrus.Debugf("Extending buffer cap by %d (was %d)", frameSize+StdWriterPrefixLen-bufLen+1, len(buf)) buf = append(buf, make([]byte, frameSize+StdWriterPrefixLen-bufLen+1)...) bufLen = len(buf) } // While the amount of bytes read is less than the size of the frame + header, we keep reading for nr < frameSize+StdWriterPrefixLen { var nr2 int nr2, er = src.Read(buf[nr:]) nr += nr2 if er == io.EOF { if nr < frameSize+StdWriterPrefixLen { logrus.Debugf("Corrupted frame: %v", buf[StdWriterPrefixLen:nr]) return written, nil } break } if er != nil { logrus.Debugf("Error reading frame: %s", er) return 0, er } } // Write the retrieved frame (without header) nw, ew = out.Write(buf[StdWriterPrefixLen : frameSize+StdWriterPrefixLen]) if ew != nil { logrus.Debugf("Error writing frame: %s", ew) return 0, ew } // If the frame has not been fully written: error if nw != frameSize { logrus.Debugf("Error Short Write: (%d on %d)", nw, frameSize) return 0, io.ErrShortWrite } written += int64(nw) // Move the rest of the buffer to the beginning copy(buf, buf[frameSize+StdWriterPrefixLen:]) // Move the index nr -= frameSize + StdWriterPrefixLen } } ================================================ FILE: vendor/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go ================================================ package stdcopy import ( "bytes" "io/ioutil" "strings" "testing" ) func TestNewStdWriter(t *testing.T) { writer := NewStdWriter(ioutil.Discard, Stdout) if writer == nil { t.Fatalf("NewStdWriter with an invalid StdType should not return nil.") } } func TestWriteWithUnitializedStdWriter(t *testing.T) { writer := StdWriter{ Writer: nil, prefix: Stdout, sizeBuf: make([]byte, 4), } n, err := writer.Write([]byte("Something here")) if n != 0 || err == nil { t.Fatalf("Should fail when given an uncomplete or uninitialized StdWriter") } } func TestWriteWithNilBytes(t *testing.T) { writer := NewStdWriter(ioutil.Discard, Stdout) n, err := writer.Write(nil) if err != nil { t.Fatalf("Shouldn't have fail when given no data") } if n > 0 { t.Fatalf("Write should have written 0 byte, but has written %d", n) } } func TestWrite(t *testing.T) { writer := NewStdWriter(ioutil.Discard, Stdout) data := []byte("Test StdWrite.Write") n, err := writer.Write(data) if err != nil { t.Fatalf("Error while writing with StdWrite") } if n != len(data) { t.Fatalf("Write should have writen %d byte but wrote %d.", len(data), n) } } func TestStdCopyWithInvalidInputHeader(t *testing.T) { dstOut := NewStdWriter(ioutil.Discard, Stdout) dstErr := NewStdWriter(ioutil.Discard, Stderr) src := strings.NewReader("Invalid input") _, err := StdCopy(dstOut, dstErr, src) if err == nil { t.Fatal("StdCopy with invalid input header should fail.") } } func TestStdCopyWithCorruptedPrefix(t *testing.T) { data := []byte{0x01, 0x02, 0x03} src := bytes.NewReader(data) written, err := StdCopy(nil, nil, src) if err != nil { t.Fatalf("StdCopy should not return an error with corrupted prefix.") } if written != 0 { t.Fatalf("StdCopy should have written 0, but has written %d", written) } } func BenchmarkWrite(b *testing.B) { w := NewStdWriter(ioutil.Discard, Stdout) data := []byte("Test line for testing stdwriter performance\n") data = bytes.Repeat(data, 100) b.SetBytes(int64(len(data))) b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := w.Write(data); err != nil { b.Fatal(err) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/streamformatter/streamformatter.go ================================================ package streamformatter import ( "encoding/json" "fmt" "io" "github.com/docker/docker/pkg/jsonmessage" ) type StreamFormatter struct { json bool } // NewStreamFormatter returns a simple StreamFormatter func NewStreamFormatter() *StreamFormatter { return &StreamFormatter{} } // NewJSONStreamFormatter returns a StreamFormatter configured to stream json func NewJSONStreamFormatter() *StreamFormatter { return &StreamFormatter{true} } const streamNewline = "\r\n" var streamNewlineBytes = []byte(streamNewline) func (sf *StreamFormatter) FormatStream(str string) []byte { if sf.json { b, err := json.Marshal(&jsonmessage.JSONMessage{Stream: str}) if err != nil { return sf.FormatError(err) } return append(b, streamNewlineBytes...) } return []byte(str + "\r") } func (sf *StreamFormatter) FormatStatus(id, format string, a ...interface{}) []byte { str := fmt.Sprintf(format, a...) if sf.json { b, err := json.Marshal(&jsonmessage.JSONMessage{ID: id, Status: str}) if err != nil { return sf.FormatError(err) } return append(b, streamNewlineBytes...) } return []byte(str + streamNewline) } func (sf *StreamFormatter) FormatError(err error) []byte { if sf.json { jsonError, ok := err.(*jsonmessage.JSONError) if !ok { jsonError = &jsonmessage.JSONError{Message: err.Error()} } if b, err := json.Marshal(&jsonmessage.JSONMessage{Error: jsonError, ErrorMessage: err.Error()}); err == nil { return append(b, streamNewlineBytes...) } return []byte("{\"error\":\"format error\"}" + streamNewline) } return []byte("Error: " + err.Error() + streamNewline) } func (sf *StreamFormatter) FormatProgress(id, action string, progress *jsonmessage.JSONProgress) []byte { if progress == nil { progress = &jsonmessage.JSONProgress{} } if sf.json { b, err := json.Marshal(&jsonmessage.JSONMessage{ Status: action, ProgressMessage: progress.String(), Progress: progress, ID: id, }) if err != nil { return nil } return b } endl := "\r" if progress.String() == "" { endl += "\n" } return []byte(action + " " + progress.String() + endl) } type StdoutFormater struct { io.Writer *StreamFormatter } func (sf *StdoutFormater) Write(buf []byte) (int, error) { formattedBuf := sf.StreamFormatter.FormatStream(string(buf)) n, err := sf.Writer.Write(formattedBuf) if n != len(formattedBuf) { return n, io.ErrShortWrite } return len(buf), err } type StderrFormater struct { io.Writer *StreamFormatter } func (sf *StderrFormater) Write(buf []byte) (int, error) { formattedBuf := sf.StreamFormatter.FormatStream("\033[91m" + string(buf) + "\033[0m") n, err := sf.Writer.Write(formattedBuf) if n != len(formattedBuf) { return n, io.ErrShortWrite } return len(buf), err } ================================================ FILE: vendor/github.com/docker/docker/pkg/streamformatter/streamformatter_test.go ================================================ package streamformatter import ( "encoding/json" "errors" "reflect" "testing" "github.com/docker/docker/pkg/jsonmessage" ) func TestFormatStream(t *testing.T) { sf := NewStreamFormatter() res := sf.FormatStream("stream") if string(res) != "stream"+"\r" { t.Fatalf("%q", res) } } func TestFormatJSONStatus(t *testing.T) { sf := NewStreamFormatter() res := sf.FormatStatus("ID", "%s%d", "a", 1) if string(res) != "a1\r\n" { t.Fatalf("%q", res) } } func TestFormatSimpleError(t *testing.T) { sf := NewStreamFormatter() res := sf.FormatError(errors.New("Error for formatter")) if string(res) != "Error: Error for formatter\r\n" { t.Fatalf("%q", res) } } func TestJSONFormatStream(t *testing.T) { sf := NewJSONStreamFormatter() res := sf.FormatStream("stream") if string(res) != `{"stream":"stream"}`+"\r\n" { t.Fatalf("%q", res) } } func TestJSONFormatStatus(t *testing.T) { sf := NewJSONStreamFormatter() res := sf.FormatStatus("ID", "%s%d", "a", 1) if string(res) != `{"status":"a1","id":"ID"}`+"\r\n" { t.Fatalf("%q", res) } } func TestJSONFormatSimpleError(t *testing.T) { sf := NewJSONStreamFormatter() res := sf.FormatError(errors.New("Error for formatter")) if string(res) != `{"errorDetail":{"message":"Error for formatter"},"error":"Error for formatter"}`+"\r\n" { t.Fatalf("%q", res) } } func TestJSONFormatJSONError(t *testing.T) { sf := NewJSONStreamFormatter() err := &jsonmessage.JSONError{Code: 50, Message: "Json error"} res := sf.FormatError(err) if string(res) != `{"errorDetail":{"code":50,"message":"Json error"},"error":"Json error"}`+"\r\n" { t.Fatalf("%q", res) } } func TestJSONFormatProgress(t *testing.T) { sf := NewJSONStreamFormatter() progress := &jsonmessage.JSONProgress{ Current: 15, Total: 30, Start: 1, } res := sf.FormatProgress("id", "action", progress) msg := &jsonmessage.JSONMessage{} if err := json.Unmarshal(res, msg); err != nil { t.Fatal(err) } if msg.ID != "id" { t.Fatalf("ID must be 'id', got: %s", msg.ID) } if msg.Status != "action" { t.Fatalf("Status must be 'action', got: %s", msg.Status) } if msg.ProgressMessage != progress.String() { t.Fatalf("ProgressMessage must be %s, got: %s", progress.String(), msg.ProgressMessage) } if !reflect.DeepEqual(msg.Progress, progress) { t.Fatal("Original progress not equals progress from FormatProgress") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/stringid/README.md ================================================ This package provides helper functions for dealing with string identifiers ================================================ FILE: vendor/github.com/docker/docker/pkg/stringid/stringid.go ================================================ package stringid import ( "crypto/rand" "encoding/hex" "io" "regexp" "strconv" ) const shortLen = 12 var validShortID = regexp.MustCompile("^[a-z0-9]{12}$") // Determine if an arbitrary string *looks like* a short ID. func IsShortID(id string) bool { return validShortID.MatchString(id) } // TruncateID returns a shorthand version of a string identifier for convenience. // A collision with other shorthands is very unlikely, but possible. // In case of a collision a lookup with TruncIndex.Get() will fail, and the caller // will need to use a langer prefix, or the full-length Id. func TruncateID(id string) string { trimTo := shortLen if len(id) < shortLen { trimTo = len(id) } return id[:trimTo] } // GenerateRandomID returns an unique id func GenerateRandomID() string { for { id := make([]byte, 32) if _, err := io.ReadFull(rand.Reader, id); err != nil { panic(err) // This shouldn't happen } value := hex.EncodeToString(id) // if we try to parse the truncated for as an int and we don't have // an error then the value is all numberic and causes issues when // used as a hostname. ref #3869 if _, err := strconv.ParseInt(TruncateID(value), 10, 64); err == nil { continue } return value } } ================================================ FILE: vendor/github.com/docker/docker/pkg/stringid/stringid_test.go ================================================ package stringid import ( "strings" "testing" ) func TestGenerateRandomID(t *testing.T) { id := GenerateRandomID() if len(id) != 64 { t.Fatalf("Id returned is incorrect: %s", id) } } func TestShortenId(t *testing.T) { id := GenerateRandomID() truncID := TruncateID(id) if len(truncID) != 12 { t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID) } } func TestShortenIdEmpty(t *testing.T) { id := "" truncID := TruncateID(id) if len(truncID) > len(id) { t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID) } } func TestShortenIdInvalid(t *testing.T) { id := "1234" truncID := TruncateID(id) if len(truncID) != len(id) { t.Fatalf("Id returned is incorrect: truncate on %s returned %s", id, truncID) } } func TestIsShortIDNonHex(t *testing.T) { id := "some non-hex value" if IsShortID(id) { t.Fatalf("%s is not a short ID", id) } } func TestIsShortIDNotCorrectSize(t *testing.T) { id := strings.Repeat("a", shortLen+1) if IsShortID(id) { t.Fatalf("%s is not a short ID", id) } id = strings.Repeat("a", shortLen-1) if IsShortID(id) { t.Fatalf("%s is not a short ID", id) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/stringutils/README.md ================================================ This package provides helper functions for dealing with strings ================================================ FILE: vendor/github.com/docker/docker/pkg/stringutils/stringutils.go ================================================ package stringutils import ( "bytes" "math/rand" "strings" "github.com/docker/docker/pkg/random" ) // Generate alpha only random stirng with length n func GenerateRandomAlphaOnlyString(n int) string { // make a really long string letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]byte, n) r := rand.New(random.NewSource()) for i := range b { b[i] = letters[r.Intn(len(letters))] } return string(b) } // Generate Ascii random stirng with length n func GenerateRandomAsciiString(n int) string { chars := "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` " res := make([]byte, n) for i := 0; i < n; i++ { res[i] = chars[rand.Intn(len(chars))] } return string(res) } // Truncate a string to maxlen func Truncate(s string, maxlen int) string { if len(s) <= maxlen { return s } return s[:maxlen] } // Test wheather a string is contained in a slice of strings or not. // Comparison is case insensitive func InSlice(slice []string, s string) bool { for _, ss := range slice { if strings.ToLower(s) == strings.ToLower(ss) { return true } } return false } func quote(word string, buf *bytes.Buffer) { // Bail out early for "simple" strings if word != "" && !strings.ContainsAny(word, "\\'\"`${[|&;<>()~*?! \t\n") { buf.WriteString(word) return } buf.WriteString("'") for i := 0; i < len(word); i++ { b := word[i] if b == '\'' { // Replace literal ' with a close ', a \', and a open ' buf.WriteString("'\\''") } else { buf.WriteByte(b) } } buf.WriteString("'") } // Take a list of strings and escape them so they will be handled right // when passed as arguments to an program via a shell func ShellQuoteArguments(args []string) string { var buf bytes.Buffer for i, arg := range args { if i != 0 { buf.WriteByte(' ') } quote(arg, &buf) } return buf.String() } ================================================ FILE: vendor/github.com/docker/docker/pkg/stringutils/stringutils_test.go ================================================ package stringutils import "testing" func testLengthHelper(generator func(int) string, t *testing.T) { expectedLength := 20 s := generator(expectedLength) if len(s) != expectedLength { t.Fatalf("Length of %s was %d but expected length %d", s, len(s), expectedLength) } } func testUniquenessHelper(generator func(int) string, t *testing.T) { repeats := 25 set := make(map[string]struct{}, repeats) for i := 0; i < repeats; i = i + 1 { str := generator(64) if len(str) != 64 { t.Fatalf("Id returned is incorrect: %s", str) } if _, ok := set[str]; ok { t.Fatalf("Random number is repeated") } set[str] = struct{}{} } } func isASCII(s string) bool { for _, c := range s { if c > 127 { return false } } return true } func TestGenerateRandomAlphaOnlyStringLength(t *testing.T) { testLengthHelper(GenerateRandomAlphaOnlyString, t) } func TestGenerateRandomAlphaOnlyStringUniqueness(t *testing.T) { testUniquenessHelper(GenerateRandomAlphaOnlyString, t) } func TestGenerateRandomAsciiStringLength(t *testing.T) { testLengthHelper(GenerateRandomAsciiString, t) } func TestGenerateRandomAsciiStringUniqueness(t *testing.T) { testUniquenessHelper(GenerateRandomAsciiString, t) } func TestGenerateRandomAsciiStringIsAscii(t *testing.T) { str := GenerateRandomAsciiString(64) if !isASCII(str) { t.Fatalf("%s contained non-ascii characters", str) } } func TestTruncate(t *testing.T) { str := "teststring" newstr := Truncate(str, 4) if newstr != "test" { t.Fatalf("Expected test, got %s", newstr) } newstr = Truncate(str, 20) if newstr != "teststring" { t.Fatalf("Expected teststring, got %s", newstr) } } func TestInSlice(t *testing.T) { slice := []string{"test", "in", "slice"} test := InSlice(slice, "test") if !test { t.Fatalf("Expected string test to be in slice") } test = InSlice(slice, "SLICE") if !test { t.Fatalf("Expected string SLICE to be in slice") } test = InSlice(slice, "notinslice") if test { t.Fatalf("Expected string notinslice not to be in slice") } } func TestShellQuoteArgumentsEmpty(t *testing.T) { actual := ShellQuoteArguments([]string{}) expected := "" if actual != expected { t.Fatalf("Expected an empty string") } } func TestShellQuoteArguments(t *testing.T) { simpleString := "simpleString" complexString := "This is a 'more' complex $tring with some special char *" actual := ShellQuoteArguments([]string{simpleString, complexString}) expected := "simpleString 'This is a '\\''more'\\'' complex $tring with some special char *'" if actual != expected { t.Fatalf("Expected \"%v\", got \"%v\"", expected, actual) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE ================================================ 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-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. ================================================ FILE: vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD ================================================ Copyright (c) 2014-2015 The Docker & 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. ================================================ FILE: vendor/github.com/docker/docker/pkg/symlink/README.md ================================================ Package symlink implements EvalSymlinksInScope which is an extension of filepath.EvalSymlinks from the [Go standard library](https://golang.org/pkg/path/filepath). The code from filepath.EvalSymlinks has been adapted in fs.go. Please read the LICENSE.BSD file that governs fs.go and LICENSE.APACHE for fs_test.go. ================================================ FILE: vendor/github.com/docker/docker/pkg/symlink/fs.go ================================================ // 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.BSD file. // This code is a modified version of path/filepath/symlink.go from the Go standard library. package symlink import ( "bytes" "errors" "os" "path/filepath" "strings" ) // FollowSymlinkInScope is a wrapper around evalSymlinksInScope that returns an absolute path func FollowSymlinkInScope(path, root string) (string, error) { path, err := filepath.Abs(path) if err != nil { return "", err } root, err = filepath.Abs(root) if err != nil { return "", err } return evalSymlinksInScope(path, root) } // evalSymlinksInScope will evaluate symlinks in `path` within a scope `root` and return // a result guaranteed to be contained within the scope `root`, at the time of the call. // Symlinks in `root` are not evaluated and left as-is. // Errors encountered while attempting to evaluate symlinks in path will be returned. // Non-existing paths are valid and do not constitute an error. // `path` has to contain `root` as a prefix, or else an error will be returned. // Trying to break out from `root` does not constitute an error. // // Example: // If /foo/bar -> /outside, // FollowSymlinkInScope("/foo/bar", "/foo") == "/foo/outside" instead of "/oustide" // // IMPORTANT: it is the caller's responsibility to call evalSymlinksInScope *after* relevant symlinks // are created and not to create subsequently, additional symlinks that could potentially make a // previously-safe path, unsafe. Example: if /foo/bar does not exist, evalSymlinksInScope("/foo/bar", "/foo") // would return "/foo/bar". If one makes /foo/bar a symlink to /baz subsequently, then "/foo/bar" should // no longer be considered safely contained in "/foo". func evalSymlinksInScope(path, root string) (string, error) { root = filepath.Clean(root) if path == root { return path, nil } if !strings.HasPrefix(path, root) { return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root) } const maxIter = 255 originalPath := path // given root of "/a" and path of "/a/b/../../c" we want path to be "/b/../../c" path = path[len(root):] if root == string(filepath.Separator) { path = string(filepath.Separator) + path } if !strings.HasPrefix(path, string(filepath.Separator)) { return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root) } path = filepath.Clean(path) // consume path by taking each frontmost path element, // expanding it if it's a symlink, and appending it to b var b bytes.Buffer // b here will always be considered to be the "current absolute path inside // root" when we append paths to it, we also append a slash and use // filepath.Clean after the loop to trim the trailing slash for n := 0; path != ""; n++ { if n > maxIter { return "", errors.New("evalSymlinksInScope: too many links in " + originalPath) } // find next path component, p i := strings.IndexRune(path, filepath.Separator) var p string if i == -1 { p, path = path, "" } else { p, path = path[:i], path[i+1:] } if p == "" { continue } // this takes a b.String() like "b/../" and a p like "c" and turns it // into "/b/../c" which then gets filepath.Cleaned into "/c" and then // root gets prepended and we Clean again (to remove any trailing slash // if the first Clean gave us just "/") cleanP := filepath.Clean(string(filepath.Separator) + b.String() + p) if cleanP == string(filepath.Separator) { // never Lstat "/" itself b.Reset() continue } fullP := filepath.Clean(root + cleanP) fi, err := os.Lstat(fullP) if os.IsNotExist(err) { // if p does not exist, accept it b.WriteString(p) b.WriteRune(filepath.Separator) continue } if err != nil { return "", err } if fi.Mode()&os.ModeSymlink == 0 { b.WriteString(p + string(filepath.Separator)) continue } // it's a symlink, put it at the front of path dest, err := os.Readlink(fullP) if err != nil { return "", err } if filepath.IsAbs(dest) { b.Reset() } path = dest + string(filepath.Separator) + path } // see note above on "fullP := ..." for why this is double-cleaned and // what's happening here return filepath.Clean(root + filepath.Clean(string(filepath.Separator)+b.String())), nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/symlink/fs_test.go ================================================ // Licensed under the Apache License, Version 2.0; See LICENSE.APACHE package symlink import ( "fmt" "io/ioutil" "os" "path/filepath" "testing" ) type dirOrLink struct { path string target string } func makeFs(tmpdir string, fs []dirOrLink) error { for _, s := range fs { s.path = filepath.Join(tmpdir, s.path) if s.target == "" { os.MkdirAll(s.path, 0755) continue } if err := os.MkdirAll(filepath.Dir(s.path), 0755); err != nil { return err } if err := os.Symlink(s.target, s.path); err != nil && !os.IsExist(err) { return err } } return nil } func testSymlink(tmpdir, path, expected, scope string) error { rewrite, err := FollowSymlinkInScope(filepath.Join(tmpdir, path), filepath.Join(tmpdir, scope)) if err != nil { return err } expected, err = filepath.Abs(filepath.Join(tmpdir, expected)) if err != nil { return err } if expected != rewrite { return fmt.Errorf("Expected %q got %q", expected, rewrite) } return nil } func TestFollowSymlinkAbsolute(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkAbsolute") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "testdata/fs/a/d", target: "/b"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "testdata/fs/a/d/c/data", "testdata/b/c/data", "testdata"); err != nil { t.Fatal(err) } } func TestFollowSymlinkRelativePath(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkRelativePath") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "testdata/fs/i", target: "a"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "testdata/fs/i", "testdata/fs/a", "testdata"); err != nil { t.Fatal(err) } } func TestFollowSymlinkSkipSymlinksOutsideScope(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkSkipSymlinksOutsideScope") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{ {path: "linkdir", target: "realdir"}, {path: "linkdir/foo/bar"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "linkdir/foo/bar", "linkdir/foo/bar", "linkdir/foo"); err != nil { t.Fatal(err) } } func TestFollowSymlinkInvalidScopePathPair(t *testing.T) { if _, err := FollowSymlinkInScope("toto", "testdata"); err == nil { t.Fatal("expected an error") } } func TestFollowSymlinkLastLink(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkLastLink") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "testdata/fs/a/d", target: "/b"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "testdata/fs/a/d", "testdata/b", "testdata"); err != nil { t.Fatal(err) } } func TestFollowSymlinkRelativeLinkChangeScope(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkRelativeLinkChangeScope") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "testdata/fs/a/e", target: "../b"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "testdata/fs/a/e/c/data", "testdata/fs/b/c/data", "testdata"); err != nil { t.Fatal(err) } // avoid letting allowing symlink e lead us to ../b // normalize to the "testdata/fs/a" if err := testSymlink(tmpdir, "testdata/fs/a/e", "testdata/fs/a/b", "testdata/fs/a"); err != nil { t.Fatal(err) } } func TestFollowSymlinkDeepRelativeLinkChangeScope(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkDeepRelativeLinkChangeScope") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "testdata/fs/a/f", target: "../../../../test"}}); err != nil { t.Fatal(err) } // avoid letting symlink f lead us out of the "testdata" scope // we don't normalize because symlink f is in scope and there is no // information leak if err := testSymlink(tmpdir, "testdata/fs/a/f", "testdata/test", "testdata"); err != nil { t.Fatal(err) } // avoid letting symlink f lead us out of the "testdata/fs" scope // we don't normalize because symlink f is in scope and there is no // information leak if err := testSymlink(tmpdir, "testdata/fs/a/f", "testdata/fs/test", "testdata/fs"); err != nil { t.Fatal(err) } } func TestFollowSymlinkRelativeLinkChain(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkRelativeLinkChain") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) // avoid letting symlink g (pointed at by symlink h) take out of scope // TODO: we should probably normalize to scope here because ../[....]/root // is out of scope and we leak information if err := makeFs(tmpdir, []dirOrLink{ {path: "testdata/fs/b/h", target: "../g"}, {path: "testdata/fs/g", target: "../../../../../../../../../../../../root"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "testdata/fs/b/h", "testdata/root", "testdata"); err != nil { t.Fatal(err) } } func TestFollowSymlinkBreakoutPath(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkBreakoutPath") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) // avoid letting symlink -> ../directory/file escape from scope // normalize to "testdata/fs/j" if err := makeFs(tmpdir, []dirOrLink{{path: "testdata/fs/j/k", target: "../i/a"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "testdata/fs/j/k", "testdata/fs/j/i/a", "testdata/fs/j"); err != nil { t.Fatal(err) } } func TestFollowSymlinkToRoot(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkToRoot") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) // make sure we don't allow escaping to / // normalize to dir if err := makeFs(tmpdir, []dirOrLink{{path: "foo", target: "/"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "foo", "", ""); err != nil { t.Fatal(err) } } func TestFollowSymlinkSlashDotdot(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkSlashDotdot") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) tmpdir = filepath.Join(tmpdir, "dir", "subdir") // make sure we don't allow escaping to / // normalize to dir if err := makeFs(tmpdir, []dirOrLink{{path: "foo", target: "/../../"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "foo", "", ""); err != nil { t.Fatal(err) } } func TestFollowSymlinkDotdot(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkDotdot") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) tmpdir = filepath.Join(tmpdir, "dir", "subdir") // make sure we stay in scope without leaking information // this also checks for escaping to / // normalize to dir if err := makeFs(tmpdir, []dirOrLink{{path: "foo", target: "../../"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "foo", "", ""); err != nil { t.Fatal(err) } } func TestFollowSymlinkRelativePath2(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkRelativePath2") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "bar/foo", target: "baz/target"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "bar/foo", "bar/baz/target", ""); err != nil { t.Fatal(err) } } func TestFollowSymlinkScopeLink(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkScopeLink") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{ {path: "root2"}, {path: "root", target: "root2"}, {path: "root2/foo", target: "../bar"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "root/foo", "root/bar", "root"); err != nil { t.Fatal(err) } } func TestFollowSymlinkRootScope(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkRootScope") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) expected, err := filepath.EvalSymlinks(tmpdir) if err != nil { t.Fatal(err) } rewrite, err := FollowSymlinkInScope(tmpdir, "/") if err != nil { t.Fatal(err) } if rewrite != expected { t.Fatalf("expected %q got %q", expected, rewrite) } } func TestFollowSymlinkEmpty(t *testing.T) { res, err := FollowSymlinkInScope("", "") if err != nil { t.Fatal(err) } wd, err := os.Getwd() if err != nil { t.Fatal(err) } if res != wd { t.Fatalf("expected %q got %q", wd, res) } } func TestFollowSymlinkCircular(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkCircular") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{{path: "root/foo", target: "foo"}}); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "root/foo", "", "root"); err == nil { t.Fatal("expected an error for foo -> foo") } if err := makeFs(tmpdir, []dirOrLink{ {path: "root/bar", target: "baz"}, {path: "root/baz", target: "../bak"}, {path: "root/bak", target: "/bar"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "root/foo", "", "root"); err == nil { t.Fatal("expected an error for bar -> baz -> bak -> bar") } } func TestFollowSymlinkComplexChainWithTargetPathsContainingLinks(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkComplexChainWithTargetPathsContainingLinks") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{ {path: "root2"}, {path: "root", target: "root2"}, {path: "root/a", target: "r/s"}, {path: "root/r", target: "../root/t"}, {path: "root/root/t/s/b", target: "/../u"}, {path: "root/u/c", target: "."}, {path: "root/u/x/y", target: "../v"}, {path: "root/u/v", target: "/../w"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "root/a/b/c/x/y/z", "root/w/z", "root"); err != nil { t.Fatal(err) } } func TestFollowSymlinkBreakoutNonExistent(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkBreakoutNonExistent") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{ {path: "root/slash", target: "/"}, {path: "root/sym", target: "/idontexist/../slash"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "root/sym/file", "root/file", "root"); err != nil { t.Fatal(err) } } func TestFollowSymlinkNoLexicalCleaning(t *testing.T) { tmpdir, err := ioutil.TempDir("", "TestFollowSymlinkNoLexicalCleaning") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) if err := makeFs(tmpdir, []dirOrLink{ {path: "root/sym", target: "/foo/bar"}, {path: "root/hello", target: "/sym/../baz"}, }); err != nil { t.Fatal(err) } if err := testSymlink(tmpdir, "root/hello", "root/foo/baz", "root"); err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/sysinfo/README.md ================================================ SysInfo stores information about which features a kernel supports. ================================================ FILE: vendor/github.com/docker/docker/pkg/sysinfo/sysinfo.go ================================================ package sysinfo // SysInfo stores information about which features a kernel supports. // TODO Windows: Factor out platform specific capabilities. type SysInfo struct { AppArmor bool *cgroupMemInfo *cgroupCpuInfo IPv4ForwardingDisabled bool BridgeNfCallIptablesDisabled bool BridgeNfCallIp6tablesDisabled bool CgroupDevicesEnabled bool } type cgroupMemInfo struct { MemoryLimit bool SwapLimit bool OomKillDisable bool MemorySwappiness bool } type cgroupCpuInfo struct { CpuCfsPeriod bool CpuCfsQuota bool } ================================================ FILE: vendor/github.com/docker/docker/pkg/sysinfo/sysinfo_linux.go ================================================ package sysinfo import ( "io/ioutil" "os" "path" "strings" "github.com/Sirupsen/logrus" "github.com/opencontainers/runc/libcontainer/cgroups" ) // New returns a new SysInfo, using the filesystem to detect which features the kernel supports. func New(quiet bool) *SysInfo { sysInfo := &SysInfo{} sysInfo.cgroupMemInfo = checkCgroupMem(quiet) sysInfo.cgroupCpuInfo = checkCgroupCpu(quiet) _, err := cgroups.FindCgroupMountpoint("devices") sysInfo.CgroupDevicesEnabled = err == nil sysInfo.IPv4ForwardingDisabled = !readProcBool("/proc/sys/net/ipv4/ip_forward") sysInfo.BridgeNfCallIptablesDisabled = !readProcBool("/proc/sys/net/bridge/bridge-nf-call-iptables") sysInfo.BridgeNfCallIp6tablesDisabled = !readProcBool("/proc/sys/net/bridge/bridge-nf-call-ip6tables") // Check if AppArmor is supported. if _, err := os.Stat("/sys/kernel/security/apparmor"); !os.IsNotExist(err) { sysInfo.AppArmor = true } return sysInfo } func checkCgroupMem(quiet bool) *cgroupMemInfo { info := &cgroupMemInfo{} mountPoint, err := cgroups.FindCgroupMountpoint("memory") if err != nil { if !quiet { logrus.Warnf("Your kernel does not support cgroup memory limit: %v", err) } return info } info.MemoryLimit = true info.SwapLimit = cgroupEnabled(mountPoint, "memory.memsw.limit_in_bytes") if !quiet && !info.SwapLimit { logrus.Warn("Your kernel does not support swap memory limit.") } info.OomKillDisable = cgroupEnabled(mountPoint, "memory.oom_control") if !quiet && !info.OomKillDisable { logrus.Warnf("Your kernel does not support oom control.") } info.MemorySwappiness = cgroupEnabled(mountPoint, "memory.swappiness") if !quiet && !info.MemorySwappiness { logrus.Warnf("Your kernel does not support memory swappiness.") } return info } func checkCgroupCpu(quiet bool) *cgroupCpuInfo { info := &cgroupCpuInfo{} mountPoint, err := cgroups.FindCgroupMountpoint("cpu") if err != nil { if !quiet { logrus.Warn(err) } return info } info.CpuCfsPeriod = cgroupEnabled(mountPoint, "cpu.cfs_period_us") if !quiet && !info.CpuCfsPeriod { logrus.Warn("Your kernel does not support cgroup cfs period") } info.CpuCfsQuota = cgroupEnabled(mountPoint, "cpu.cfs_quota_us") if !quiet && !info.CpuCfsQuota { logrus.Warn("Your kernel does not support cgroup cfs quotas") } return info } func cgroupEnabled(mountPoint, name string) bool { _, err := os.Stat(path.Join(mountPoint, name)) return err == nil } func readProcBool(path string) bool { val, err := ioutil.ReadFile(path) if err != nil { return false } return strings.TrimSpace(string(val)) == "1" } ================================================ FILE: vendor/github.com/docker/docker/pkg/sysinfo/sysinfo_linux_test.go ================================================ package sysinfo import ( "io/ioutil" "os" "path" "path/filepath" "testing" ) func TestReadProcBool(t *testing.T) { tmpDir, err := ioutil.TempDir("", "test-sysinfo-proc") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) procFile := filepath.Join(tmpDir, "read-proc-bool") if err := ioutil.WriteFile(procFile, []byte("1"), 644); err != nil { t.Fatal(err) } if !readProcBool(procFile) { t.Fatal("expected proc bool to be true, got false") } if err := ioutil.WriteFile(procFile, []byte("0"), 644); err != nil { t.Fatal(err) } if readProcBool(procFile) { t.Fatal("expected proc bool to be false, got false") } if readProcBool(path.Join(tmpDir, "no-exist")) { t.Fatal("should be false for non-existent entry") } } func TestCgroupEnabled(t *testing.T) { cgroupDir, err := ioutil.TempDir("", "cgroup-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(cgroupDir) if cgroupEnabled(cgroupDir, "test") { t.Fatal("cgroupEnabled should be false") } if err := ioutil.WriteFile(path.Join(cgroupDir, "test"), []byte{}, 644); err != nil { t.Fatal(err) } if !cgroupEnabled(cgroupDir, "test") { t.Fatal("cgroupEnabled should be true") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/sysinfo/sysinfo_windows.go ================================================ package sysinfo // TODO Windows func New(quiet bool) *SysInfo { sysInfo := &SysInfo{} return sysInfo } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/errors.go ================================================ package system import ( "errors" ) var ( ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") ) ================================================ FILE: vendor/github.com/docker/docker/pkg/system/events_windows.go ================================================ package system // This file implements syscalls for Win32 events which are not implemented // in golang. import ( "syscall" "unsafe" ) const ( EVENT_ALL_ACCESS = 0x1F0003 EVENT_MODIFY_STATUS = 0x0002 ) var ( procCreateEvent = modkernel32.NewProc("CreateEventW") procOpenEvent = modkernel32.NewProc("OpenEventW") procSetEvent = modkernel32.NewProc("SetEvent") procResetEvent = modkernel32.NewProc("ResetEvent") procPulseEvent = modkernel32.NewProc("PulseEvent") ) func CreateEvent(eventAttributes *syscall.SecurityAttributes, manualReset bool, initialState bool, name string) (handle syscall.Handle, err error) { namep, _ := syscall.UTF16PtrFromString(name) var _p1 uint32 = 0 if manualReset { _p1 = 1 } var _p2 uint32 = 0 if initialState { _p2 = 1 } r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep))) use(unsafe.Pointer(namep)) handle = syscall.Handle(r0) if handle == syscall.InvalidHandle { err = e1 } return } func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle syscall.Handle, err error) { namep, _ := syscall.UTF16PtrFromString(name) var _p1 uint32 = 0 if inheritHandle { _p1 = 1 } r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep))) use(unsafe.Pointer(namep)) handle = syscall.Handle(r0) if handle == syscall.InvalidHandle { err = e1 } return } func SetEvent(handle syscall.Handle) (err error) { return setResetPulse(handle, procSetEvent) } func ResetEvent(handle syscall.Handle) (err error) { return setResetPulse(handle, procResetEvent) } func PulseEvent(handle syscall.Handle) (err error) { return setResetPulse(handle, procPulseEvent) } func setResetPulse(handle syscall.Handle, proc *syscall.LazyProc) (err error) { r0, _, _ := proc.Call(uintptr(handle)) if r0 != 0 { err = syscall.Errno(r0) } return } var temp unsafe.Pointer // use ensures a variable is kept alive without the GC freeing while still needed func use(p unsafe.Pointer) { temp = p } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/filesys.go ================================================ // +build !windows package system import ( "os" ) func MkdirAll(path string, perm os.FileMode) error { return os.MkdirAll(path, perm) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/filesys_windows.go ================================================ // +build windows package system import ( "os" "regexp" "syscall" ) // MkdirAll implementation that is volume path aware for Windows. func MkdirAll(path string, perm os.FileMode) error { if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { return nil } // The rest of this method is copied from os.MkdirAll and should be kept // as-is to ensure compatibility. // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{ Op: "mkdir", Path: path, Err: syscall.ENOTDIR, } } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = MkdirAll(path[0:j-1], perm) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(path, perm) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/lstat.go ================================================ // +build !windows package system import ( "syscall" ) // Lstat takes a path to a file and returns // a system.Stat_t type pertaining to that file. // // Throws an error if the file does not exist func Lstat(path string) (*Stat_t, error) { s := &syscall.Stat_t{} if err := syscall.Lstat(path, s); err != nil { return nil, err } return fromStatT(s) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/lstat_test.go ================================================ package system import ( "os" "testing" ) // TestLstat tests Lstat for existing and non existing files func TestLstat(t *testing.T) { file, invalid, _, dir := prepareFiles(t) defer os.RemoveAll(dir) statFile, err := Lstat(file) if err != nil { t.Fatal(err) } if statFile == nil { t.Fatal("returned empty stat for existing file") } statInvalid, err := Lstat(invalid) if err == nil { t.Fatal("did not return error for non-existing file") } if statInvalid != nil { t.Fatal("returned non-nil stat for non-existing file") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/lstat_windows.go ================================================ // +build windows package system import ( "os" ) // Some explanation for my own sanity, and hopefully maintainers in the // future. // // Lstat calls os.Lstat to get a fileinfo interface back. // This is then copied into our own locally defined structure. // Note the Linux version uses fromStatT to do the copy back, // but that not strictly necessary when already in an OS specific module. func Lstat(path string) (*Stat_t, error) { fi, err := os.Lstat(path) if err != nil { return nil, err } return &Stat_t{ name: fi.Name(), size: fi.Size(), mode: fi.Mode(), modTime: fi.ModTime(), isDir: fi.IsDir()}, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/meminfo.go ================================================ package system // MemInfo contains memory statistics of the host system. type MemInfo struct { // Total usable RAM (i.e. physical RAM minus a few reserved bits and the // kernel binary code). MemTotal int64 // Amount of free memory. MemFree int64 // Total amount of swap space available. SwapTotal int64 // Amount of swap space that is currently unused. SwapFree int64 } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/meminfo_linux.go ================================================ package system import ( "bufio" "errors" "io" "os" "strconv" "strings" "github.com/docker/docker/pkg/units" ) var ( ErrMalformed = errors.New("malformed file") ) // ReadMemInfo retrieves memory statistics of the host system and returns a // MemInfo type. func ReadMemInfo() (*MemInfo, error) { file, err := os.Open("/proc/meminfo") if err != nil { return nil, err } defer file.Close() return parseMemInfo(file) } // parseMemInfo parses the /proc/meminfo file into // a MemInfo object given a io.Reader to the file. // // Throws error if there are problems reading from the file func parseMemInfo(reader io.Reader) (*MemInfo, error) { meminfo := &MemInfo{} scanner := bufio.NewScanner(reader) for scanner.Scan() { // Expected format: ["MemTotal:", "1234", "kB"] parts := strings.Fields(scanner.Text()) // Sanity checks: Skip malformed entries. if len(parts) < 3 || parts[2] != "kB" { continue } // Convert to bytes. size, err := strconv.Atoi(parts[1]) if err != nil { continue } bytes := int64(size) * units.KiB switch parts[0] { case "MemTotal:": meminfo.MemTotal = bytes case "MemFree:": meminfo.MemFree = bytes case "SwapTotal:": meminfo.SwapTotal = bytes case "SwapFree:": meminfo.SwapFree = bytes } } // Handle errors that may have occurred during the reading of the file. if err := scanner.Err(); err != nil { return nil, err } return meminfo, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/meminfo_linux_test.go ================================================ package system import ( "strings" "testing" "github.com/docker/docker/pkg/units" ) // TestMemInfo tests parseMemInfo with a static meminfo string func TestMemInfo(t *testing.T) { const input = ` MemTotal: 1 kB MemFree: 2 kB SwapTotal: 3 kB SwapFree: 4 kB Malformed1: Malformed2: 1 Malformed3: 2 MB Malformed4: X kB ` meminfo, err := parseMemInfo(strings.NewReader(input)) if err != nil { t.Fatal(err) } if meminfo.MemTotal != 1*units.KiB { t.Fatalf("Unexpected MemTotal: %d", meminfo.MemTotal) } if meminfo.MemFree != 2*units.KiB { t.Fatalf("Unexpected MemFree: %d", meminfo.MemFree) } if meminfo.SwapTotal != 3*units.KiB { t.Fatalf("Unexpected SwapTotal: %d", meminfo.SwapTotal) } if meminfo.SwapFree != 4*units.KiB { t.Fatalf("Unexpected SwapFree: %d", meminfo.SwapFree) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go ================================================ // +build !linux,!windows package system func ReadMemInfo() (*MemInfo, error) { return nil, ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/meminfo_windows.go ================================================ package system import ( "syscall" "unsafe" ) var ( modkernel32 = syscall.NewLazyDLL("kernel32.dll") procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") ) // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx type memorystatusex struct { dwLength uint32 dwMemoryLoad uint32 ullTotalPhys uint64 ullAvailPhys uint64 ullTotalPageFile uint64 ullAvailPageFile uint64 ullTotalVirtual uint64 ullAvailVirtual uint64 ullAvailExtendedVirtual uint64 } // ReadMemInfo retrieves memory statistics of the host system and returns a // MemInfo type. func ReadMemInfo() (*MemInfo, error) { msi := &memorystatusex{ dwLength: 64, } r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) if r1 == 0 { return &MemInfo{}, nil } return &MemInfo{ MemTotal: int64(msi.ullTotalPhys), MemFree: int64(msi.ullAvailPhys), SwapTotal: int64(msi.ullTotalPageFile), SwapFree: int64(msi.ullAvailPageFile), }, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/mknod.go ================================================ // +build !windows package system import ( "syscall" ) // Mknod creates a filesystem node (file, device special file or named pipe) named path // with attributes specified by mode and dev func Mknod(path string, mode uint32, dev int) error { return syscall.Mknod(path, mode, dev) } // Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. // They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, // then the top 12 bits of the minor func Mkdev(major int64, minor int64) uint32 { return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff)) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/mknod_windows.go ================================================ // +build windows package system func Mknod(path string, mode uint32, dev int) error { return ErrNotSupportedPlatform } func Mkdev(major int64, minor int64) uint32 { panic("Mkdev not implemented on Windows.") } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/stat.go ================================================ // +build !windows package system import ( "syscall" ) // Stat_t type contains status of a file. It contains metadata // like permission, owner, group, size, etc about a file type Stat_t struct { mode uint32 uid uint32 gid uint32 rdev uint64 size int64 mtim syscall.Timespec } func (s Stat_t) Mode() uint32 { return s.mode } func (s Stat_t) Uid() uint32 { return s.uid } func (s Stat_t) Gid() uint32 { return s.gid } func (s Stat_t) Rdev() uint64 { return s.rdev } func (s Stat_t) Size() int64 { return s.size } func (s Stat_t) Mtim() syscall.Timespec { return s.mtim } func (s Stat_t) GetLastModification() syscall.Timespec { return s.Mtim() } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/stat_linux.go ================================================ package system import ( "syscall" ) // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*Stat_t, error) { return &Stat_t{size: s.Size, mode: s.Mode, uid: s.Uid, gid: s.Gid, rdev: s.Rdev, mtim: s.Mtim}, nil } // FromStatT exists only on linux, and loads a system.Stat_t from a // syscal.Stat_t. func FromStatT(s *syscall.Stat_t) (*Stat_t, error) { return fromStatT(s) } // Stat takes a path to a file and returns // a system.Stat_t type pertaining to that file. // // Throws an error if the file does not exist func Stat(path string) (*Stat_t, error) { s := &syscall.Stat_t{} if err := syscall.Stat(path, s); err != nil { return nil, err } return fromStatT(s) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/stat_test.go ================================================ package system import ( "os" "syscall" "testing" ) // TestFromStatT tests fromStatT for a tempfile func TestFromStatT(t *testing.T) { file, _, _, dir := prepareFiles(t) defer os.RemoveAll(dir) stat := &syscall.Stat_t{} err := syscall.Lstat(file, stat) s, err := fromStatT(stat) if err != nil { t.Fatal(err) } if stat.Mode != s.Mode() { t.Fatal("got invalid mode") } if stat.Uid != s.Uid() { t.Fatal("got invalid uid") } if stat.Gid != s.Gid() { t.Fatal("got invalid gid") } if stat.Rdev != s.Rdev() { t.Fatal("got invalid rdev") } if stat.Mtim != s.Mtim() { t.Fatal("got invalid mtim") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/stat_unsupported.go ================================================ // +build !linux,!windows package system import ( "syscall" ) // fromStatT creates a system.Stat_t type from a syscall.Stat_t type func fromStatT(s *syscall.Stat_t) (*Stat_t, error) { return &Stat_t{size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtimespec}, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/stat_windows.go ================================================ // +build windows package system import ( "os" "time" ) type Stat_t struct { name string size int64 mode os.FileMode modTime time.Time isDir bool } func (s Stat_t) Name() string { return s.name } func (s Stat_t) Size() int64 { return s.size } func (s Stat_t) Mode() os.FileMode { return s.mode } func (s Stat_t) ModTime() time.Time { return s.modTime } func (s Stat_t) IsDir() bool { return s.isDir } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/umask.go ================================================ // +build !windows package system import ( "syscall" ) func Umask(newmask int) (oldmask int, err error) { return syscall.Umask(newmask), nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/umask_windows.go ================================================ // +build windows package system func Umask(newmask int) (oldmask int, err error) { // should not be called on cli code path return 0, ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/utimes_darwin.go ================================================ package system import "syscall" func LUtimesNano(path string, ts []syscall.Timespec) error { return ErrNotSupportedPlatform } func UtimesNano(path string, ts []syscall.Timespec) error { return syscall.UtimesNano(path, ts) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go ================================================ package system import ( "syscall" "unsafe" ) func LUtimesNano(path string, ts []syscall.Timespec) error { var _path *byte _path, err := syscall.BytePtrFromString(path) if err != nil { return err } if _, _, err := syscall.Syscall(syscall.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != syscall.ENOSYS { return err } return nil } func UtimesNano(path string, ts []syscall.Timespec) error { return syscall.UtimesNano(path, ts) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/utimes_linux.go ================================================ package system import ( "syscall" "unsafe" ) func LUtimesNano(path string, ts []syscall.Timespec) error { // These are not currently available in syscall AT_FDCWD := -100 AT_SYMLINK_NOFOLLOW := 0x100 var _path *byte _path, err := syscall.BytePtrFromString(path) if err != nil { return err } if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(AT_FDCWD), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(AT_SYMLINK_NOFOLLOW), 0, 0); err != 0 && err != syscall.ENOSYS { return err } return nil } func UtimesNano(path string, ts []syscall.Timespec) error { return syscall.UtimesNano(path, ts) } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/utimes_test.go ================================================ package system import ( "io/ioutil" "os" "path/filepath" "syscall" "testing" ) // prepareFiles creates files for testing in the temp directory func prepareFiles(t *testing.T) (string, string, string, string) { dir, err := ioutil.TempDir("", "docker-system-test") if err != nil { t.Fatal(err) } file := filepath.Join(dir, "exist") if err := ioutil.WriteFile(file, []byte("hello"), 0644); err != nil { t.Fatal(err) } invalid := filepath.Join(dir, "doesnt-exist") symlink := filepath.Join(dir, "symlink") if err := os.Symlink(file, symlink); err != nil { t.Fatal(err) } return file, invalid, symlink, dir } func TestLUtimesNano(t *testing.T) { file, invalid, symlink, dir := prepareFiles(t) defer os.RemoveAll(dir) before, err := os.Stat(file) if err != nil { t.Fatal(err) } ts := []syscall.Timespec{{0, 0}, {0, 0}} if err := LUtimesNano(symlink, ts); err != nil { t.Fatal(err) } symlinkInfo, err := os.Lstat(symlink) if err != nil { t.Fatal(err) } if before.ModTime().Unix() == symlinkInfo.ModTime().Unix() { t.Fatal("The modification time of the symlink should be different") } fileInfo, err := os.Stat(file) if err != nil { t.Fatal(err) } if before.ModTime().Unix() != fileInfo.ModTime().Unix() { t.Fatal("The modification time of the file should be same") } if err := LUtimesNano(invalid, ts); err == nil { t.Fatal("Doesn't return an error on a non-existing file") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go ================================================ // +build !linux,!freebsd,!darwin package system import "syscall" func LUtimesNano(path string, ts []syscall.Timespec) error { return ErrNotSupportedPlatform } func UtimesNano(path string, ts []syscall.Timespec) error { return ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/xattrs_linux.go ================================================ package system import ( "syscall" "unsafe" ) // Returns a nil slice and nil error if the xattr is not set func Lgetxattr(path string, attr string) ([]byte, error) { pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) 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 == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { 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 } return dest[:sz], nil } var _zero uintptr 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 } ================================================ FILE: vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go ================================================ // +build !linux package system func Lgetxattr(path string, attr string) ([]byte, error) { return nil, ErrNotSupportedPlatform } func Lsetxattr(path string, attr string, data []byte, flags int) error { return ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/docker/docker/pkg/systemd/booted.go ================================================ package systemd import ( "os" ) // Conversion to Go of systemd's sd_booted() func SdBooted() bool { s, err := os.Stat("/run/systemd/system") if err != nil { return false } return s.IsDir() } ================================================ FILE: vendor/github.com/docker/docker/pkg/systemd/listendfd.go ================================================ package systemd import ( "errors" "net" "strconv" "github.com/coreos/go-systemd/activation" ) // ListenFD returns the specified socket activated files as a slice of // net.Listeners or all of the activated files if "*" is given. func ListenFD(addr string) ([]net.Listener, error) { // socket activation listeners, err := activation.Listeners(false) if err != nil { return nil, err } if listeners == nil || len(listeners) == 0 { return nil, errors.New("No sockets found") } // default to all fds just like unix:// and tcp:// if addr == "" { addr = "*" } fdNum, _ := strconv.Atoi(addr) fdOffset := fdNum - 3 if (addr != "*") && (len(listeners) < int(fdOffset)+1) { return nil, errors.New("Too few socket activated files passed in") } if addr == "*" { return listeners, nil } return []net.Listener{listeners[fdOffset]}, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/systemd/sd_notify.go ================================================ package systemd import ( "errors" "net" "os" ) var SdNotifyNoSocket = errors.New("No socket") // Send a message to the init daemon. It is common to ignore the error. func SdNotify(state string) error { socketAddr := &net.UnixAddr{ Name: os.Getenv("NOTIFY_SOCKET"), Net: "unixgram", } if socketAddr.Name == "" { return SdNotifyNoSocket } conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) if err != nil { return err } _, err = conn.Write([]byte(state)) if err != nil { return err } return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/tailfile/tailfile.go ================================================ package tailfile import ( "bytes" "errors" "os" ) const blockSize = 1024 var eol = []byte("\n") var ErrNonPositiveLinesNumber = errors.New("Lines number must be positive") //TailFile returns last n lines of file f func TailFile(f *os.File, n int) ([][]byte, error) { if n <= 0 { return nil, ErrNonPositiveLinesNumber } size, err := f.Seek(0, os.SEEK_END) if err != nil { return nil, err } block := -1 var data []byte var cnt int for { var b []byte step := int64(block * blockSize) left := size + step // how many bytes to beginning if left < 0 { if _, err := f.Seek(0, os.SEEK_SET); err != nil { return nil, err } b = make([]byte, blockSize+left) if _, err := f.Read(b); err != nil { return nil, err } data = append(b, data...) break } else { b = make([]byte, blockSize) if _, err := f.Seek(step, os.SEEK_END); err != nil { return nil, err } if _, err := f.Read(b); err != nil { return nil, err } data = append(b, data...) } cnt += bytes.Count(b, eol) if cnt > n { break } block-- } lines := bytes.Split(data, eol) if n < len(lines) { return lines[len(lines)-n-1 : len(lines)-1], nil } return lines[:len(lines)-1], nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/tailfile/tailfile_test.go ================================================ package tailfile import ( "io/ioutil" "os" "testing" ) func TestTailFile(t *testing.T) { f, err := ioutil.TempFile("", "tail-test") if err != nil { t.Fatal(err) } defer f.Close() defer os.RemoveAll(f.Name()) testFile := []byte(`first line second line third line fourth line fifth line next first line next second line next third line next fourth line next fifth line last first line next first line next second line next third line next fourth line next fifth line next first line next second line next third line next fourth line next fifth line last second line last third line last fourth line last fifth line truncated line`) if _, err := f.Write(testFile); err != nil { t.Fatal(err) } if _, err := f.Seek(0, os.SEEK_SET); err != nil { t.Fatal(err) } expected := []string{"last fourth line", "last fifth line"} res, err := TailFile(f, 2) if err != nil { t.Fatal(err) } for i, l := range res { t.Logf("%s", l) if expected[i] != string(l) { t.Fatalf("Expected line %s, got %s", expected[i], l) } } } func TestTailFileManyLines(t *testing.T) { f, err := ioutil.TempFile("", "tail-test") if err != nil { t.Fatal(err) } defer f.Close() defer os.RemoveAll(f.Name()) testFile := []byte(`first line second line truncated line`) if _, err := f.Write(testFile); err != nil { t.Fatal(err) } if _, err := f.Seek(0, os.SEEK_SET); err != nil { t.Fatal(err) } expected := []string{"first line", "second line"} res, err := TailFile(f, 10000) if err != nil { t.Fatal(err) } for i, l := range res { t.Logf("%s", l) if expected[i] != string(l) { t.Fatalf("Expected line %s, got %s", expected[i], l) } } } func TestTailEmptyFile(t *testing.T) { f, err := ioutil.TempFile("", "tail-test") if err != nil { t.Fatal(err) } defer f.Close() defer os.RemoveAll(f.Name()) res, err := TailFile(f, 10000) if err != nil { t.Fatal(err) } if len(res) != 0 { t.Fatal("Must be empty slice from empty file") } } func TestTailNegativeN(t *testing.T) { f, err := ioutil.TempFile("", "tail-test") if err != nil { t.Fatal(err) } defer f.Close() defer os.RemoveAll(f.Name()) testFile := []byte(`first line second line truncated line`) if _, err := f.Write(testFile); err != nil { t.Fatal(err) } if _, err := f.Seek(0, os.SEEK_SET); err != nil { t.Fatal(err) } if _, err := TailFile(f, -1); err != ErrNonPositiveLinesNumber { t.Fatalf("Expected ErrNonPositiveLinesNumber, got %s", err) } if _, err := TailFile(f, 0); err != ErrNonPositiveLinesNumber { t.Fatalf("Expected ErrNonPositiveLinesNumber, got %s", err) } } func BenchmarkTail(b *testing.B) { f, err := ioutil.TempFile("", "tail-test") if err != nil { b.Fatal(err) } defer f.Close() defer os.RemoveAll(f.Name()) for i := 0; i < 10000; i++ { if _, err := f.Write([]byte("tailfile pretty interesting line\n")); err != nil { b.Fatal(err) } } b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := TailFile(f, 1000); err != nil { b.Fatal(err) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/builder_context.go ================================================ package tarsum // This interface extends TarSum by adding the Remove method. In general // there was concern about adding this method to TarSum itself so instead // it is being added just to "BuilderContext" which will then only be used // during the .dockerignore file processing - see builder/evaluator.go type BuilderContext interface { TarSum Remove(string) } func (bc *tarSum) Remove(filename string) { for i, fis := range bc.sums { if fis.Name() == filename { bc.sums = append(bc.sums[:i], bc.sums[i+1:]...) // Note, we don't just return because there could be // more than one with this name } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/builder_context_test.go ================================================ package tarsum import ( "io" "io/ioutil" "os" "testing" ) // Try to remove tarsum (in the BuilderContext) that do not exists, won't change a thing func TestTarSumRemoveNonExistent(t *testing.T) { filename := "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar" reader, err := os.Open(filename) if err != nil { t.Fatal(err) } ts, err := NewTarSum(reader, false, Version0) if err != nil { t.Fatal(err) } // Read and discard bytes so that it populates sums _, err = io.Copy(ioutil.Discard, ts) if err != nil { t.Errorf("failed to read from %s: %s", filename, err) } expected := len(ts.GetSums()) ts.(BuilderContext).Remove("") ts.(BuilderContext).Remove("Anything") if len(ts.GetSums()) != expected { t.Fatalf("Expected %v sums, go %v.", expected, ts.GetSums()) } } // Remove a tarsum (in the BuilderContext) func TestTarSumRemove(t *testing.T) { filename := "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar" reader, err := os.Open(filename) if err != nil { t.Fatal(err) } ts, err := NewTarSum(reader, false, Version0) if err != nil { t.Fatal(err) } // Read and discard bytes so that it populates sums _, err = io.Copy(ioutil.Discard, ts) if err != nil { t.Errorf("failed to read from %s: %s", filename, err) } expected := len(ts.GetSums()) - 1 ts.(BuilderContext).Remove("etc/sudoers") if len(ts.GetSums()) != expected { t.Fatalf("Expected %v sums, go %v.", expected, len(ts.GetSums())) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/fileinfosums.go ================================================ package tarsum import "sort" // This info will be accessed through interface so the actual name and sum cannot be medled with type FileInfoSumInterface interface { // File name Name() string // Checksum of this particular file and its headers Sum() string // Position of file in the tar Pos() int64 } type fileInfoSum struct { name string sum string pos int64 } func (fis fileInfoSum) Name() string { return fis.name } func (fis fileInfoSum) Sum() string { return fis.sum } func (fis fileInfoSum) Pos() int64 { return fis.pos } type FileInfoSums []FileInfoSumInterface // GetFile returns the first FileInfoSumInterface with a matching name func (fis FileInfoSums) GetFile(name string) FileInfoSumInterface { for i := range fis { if fis[i].Name() == name { return fis[i] } } return nil } // GetAllFile returns a FileInfoSums with all matching names func (fis FileInfoSums) GetAllFile(name string) FileInfoSums { f := FileInfoSums{} for i := range fis { if fis[i].Name() == name { f = append(f, fis[i]) } } return f } func (fis FileInfoSums) GetDuplicatePaths() (dups FileInfoSums) { seen := make(map[string]int, len(fis)) // allocate earl. no need to grow this map. for i := range fis { f := fis[i] if _, ok := seen[f.Name()]; ok { dups = append(dups, f) } else { seen[f.Name()] = 0 } } return dups } func (fis FileInfoSums) Len() int { return len(fis) } func (fis FileInfoSums) Swap(i, j int) { fis[i], fis[j] = fis[j], fis[i] } func (fis FileInfoSums) SortByPos() { sort.Sort(byPos{fis}) } func (fis FileInfoSums) SortByNames() { sort.Sort(byName{fis}) } func (fis FileInfoSums) SortBySums() { dups := fis.GetDuplicatePaths() if len(dups) > 0 { sort.Sort(bySum{fis, dups}) } else { sort.Sort(bySum{fis, nil}) } } // byName is a sort.Sort helper for sorting by file names. // If names are the same, order them by their appearance in the tar archive type byName struct{ FileInfoSums } func (bn byName) Less(i, j int) bool { if bn.FileInfoSums[i].Name() == bn.FileInfoSums[j].Name() { return bn.FileInfoSums[i].Pos() < bn.FileInfoSums[j].Pos() } return bn.FileInfoSums[i].Name() < bn.FileInfoSums[j].Name() } // bySum is a sort.Sort helper for sorting by the sums of all the fileinfos in the tar archive type bySum struct { FileInfoSums dups FileInfoSums } func (bs bySum) Less(i, j int) bool { if bs.dups != nil && bs.FileInfoSums[i].Name() == bs.FileInfoSums[j].Name() { return bs.FileInfoSums[i].Pos() < bs.FileInfoSums[j].Pos() } return bs.FileInfoSums[i].Sum() < bs.FileInfoSums[j].Sum() } // byPos is a sort.Sort helper for sorting by the sums of all the fileinfos by their original order type byPos struct{ FileInfoSums } func (bp byPos) Less(i, j int) bool { return bp.FileInfoSums[i].Pos() < bp.FileInfoSums[j].Pos() } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/fileinfosums_test.go ================================================ package tarsum import "testing" func newFileInfoSums() FileInfoSums { return FileInfoSums{ fileInfoSum{name: "file3", sum: "2abcdef1234567890", pos: 2}, fileInfoSum{name: "dup1", sum: "deadbeef1", pos: 5}, fileInfoSum{name: "file1", sum: "0abcdef1234567890", pos: 0}, fileInfoSum{name: "file4", sum: "3abcdef1234567890", pos: 3}, fileInfoSum{name: "dup1", sum: "deadbeef0", pos: 4}, fileInfoSum{name: "file2", sum: "1abcdef1234567890", pos: 1}, } } func TestSortFileInfoSums(t *testing.T) { dups := newFileInfoSums().GetAllFile("dup1") if len(dups) != 2 { t.Errorf("expected length 2, got %d", len(dups)) } dups.SortByNames() if dups[0].Pos() != 4 { t.Errorf("sorted dups should be ordered by position. Expected 4, got %d", dups[0].Pos()) } fis := newFileInfoSums() expected := "0abcdef1234567890" fis.SortBySums() got := fis[0].Sum() if got != expected { t.Errorf("Expected %q, got %q", expected, got) } fis = newFileInfoSums() expected = "dup1" fis.SortByNames() gotFis := fis[0] if gotFis.Name() != expected { t.Errorf("Expected %q, got %q", expected, gotFis.Name()) } // since a duplicate is first, ensure it is ordered first by position too if gotFis.Pos() != 4 { t.Errorf("Expected %d, got %d", 4, gotFis.Pos()) } fis = newFileInfoSums() fis.SortByPos() if fis[0].Pos() != 0 { t.Errorf("sorted fileInfoSums by Pos should order them by position.") } fis = newFileInfoSums() expected = "deadbeef1" gotFileInfoSum := fis.GetFile("dup1") if gotFileInfoSum.Sum() != expected { t.Errorf("Expected %q, got %q", expected, gotFileInfoSum) } if fis.GetFile("noPresent") != nil { t.Errorf("Should have return nil if name not found.") } } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/tarsum.go ================================================ package tarsum import ( "archive/tar" "bytes" "compress/gzip" "crypto" "crypto/sha256" "encoding/hex" "errors" "fmt" "hash" "io" "strings" ) const ( buf8K = 8 * 1024 buf16K = 16 * 1024 buf32K = 32 * 1024 ) // NewTarSum creates a new interface for calculating a fixed time checksum of a // tar archive. // // This is used for calculating checksums of layers of an image, in some cases // including the byte payload of the image's json metadata as well, and for // calculating the checksums for buildcache. func NewTarSum(r io.Reader, dc bool, v Version) (TarSum, error) { return NewTarSumHash(r, dc, v, DefaultTHash) } // Create a new TarSum, providing a THash to use rather than the DefaultTHash func NewTarSumHash(r io.Reader, dc bool, v Version, tHash THash) (TarSum, error) { headerSelector, err := getTarHeaderSelector(v) if err != nil { return nil, err } ts := &tarSum{Reader: r, DisableCompression: dc, tarSumVersion: v, headerSelector: headerSelector, tHash: tHash} err = ts.initTarSum() return ts, err } // Create a new TarSum using the provided TarSum version+hash label. func NewTarSumForLabel(r io.Reader, disableCompression bool, label string) (TarSum, error) { parts := strings.SplitN(label, "+", 2) if len(parts) != 2 { return nil, errors.New("tarsum label string should be of the form: {tarsum_version}+{hash_name}") } versionName, hashName := parts[0], parts[1] version, ok := tarSumVersionsByName[versionName] if !ok { return nil, fmt.Errorf("unknown TarSum version name: %q", versionName) } hashConfig, ok := standardHashConfigs[hashName] if !ok { return nil, fmt.Errorf("unknown TarSum hash name: %q", hashName) } tHash := NewTHash(hashConfig.name, hashConfig.hash.New) return NewTarSumHash(r, disableCompression, version, tHash) } // TarSum is the generic interface for calculating fixed time // checksums of a tar archive type TarSum interface { io.Reader GetSums() FileInfoSums Sum([]byte) string Version() Version Hash() THash } // tarSum struct is the structure for a Version0 checksum calculation type tarSum struct { io.Reader tarR *tar.Reader tarW *tar.Writer writer writeCloseFlusher bufTar *bytes.Buffer bufWriter *bytes.Buffer bufData []byte h hash.Hash tHash THash sums FileInfoSums fileCounter int64 currentFile string finished bool first bool DisableCompression bool // false by default. When false, the output gzip compressed. tarSumVersion Version // this field is not exported so it can not be mutated during use headerSelector tarHeaderSelector // handles selecting and ordering headers for files in the archive } func (ts tarSum) Hash() THash { return ts.tHash } func (ts tarSum) Version() Version { return ts.tarSumVersion } // A hash.Hash type generator and its name type THash interface { Hash() hash.Hash Name() string } // Convenience method for creating a THash func NewTHash(name string, h func() hash.Hash) THash { return simpleTHash{n: name, h: h} } type tHashConfig struct { name string hash crypto.Hash } var ( // NOTE: DO NOT include MD5 or SHA1, which are considered insecure. standardHashConfigs = map[string]tHashConfig{ "sha256": {name: "sha256", hash: crypto.SHA256}, "sha512": {name: "sha512", hash: crypto.SHA512}, } ) // TarSum default is "sha256" var DefaultTHash = NewTHash("sha256", sha256.New) type simpleTHash struct { n string h func() hash.Hash } func (sth simpleTHash) Name() string { return sth.n } func (sth simpleTHash) Hash() hash.Hash { return sth.h() } func (ts *tarSum) encodeHeader(h *tar.Header) error { for _, elem := range ts.headerSelector.selectHeaders(h) { if _, err := ts.h.Write([]byte(elem[0] + elem[1])); err != nil { return err } } return nil } func (ts *tarSum) initTarSum() error { ts.bufTar = bytes.NewBuffer([]byte{}) ts.bufWriter = bytes.NewBuffer([]byte{}) ts.tarR = tar.NewReader(ts.Reader) ts.tarW = tar.NewWriter(ts.bufTar) if !ts.DisableCompression { ts.writer = gzip.NewWriter(ts.bufWriter) } else { ts.writer = &nopCloseFlusher{Writer: ts.bufWriter} } if ts.tHash == nil { ts.tHash = DefaultTHash } ts.h = ts.tHash.Hash() ts.h.Reset() ts.first = true ts.sums = FileInfoSums{} return nil } func (ts *tarSum) Read(buf []byte) (int, error) { if ts.finished { return ts.bufWriter.Read(buf) } if len(ts.bufData) < len(buf) { switch { case len(buf) <= buf8K: ts.bufData = make([]byte, buf8K) case len(buf) <= buf16K: ts.bufData = make([]byte, buf16K) case len(buf) <= buf32K: ts.bufData = make([]byte, buf32K) default: ts.bufData = make([]byte, len(buf)) } } buf2 := ts.bufData[:len(buf)] n, err := ts.tarR.Read(buf2) if err != nil { if err == io.EOF { if _, err := ts.h.Write(buf2[:n]); err != nil { return 0, err } if !ts.first { ts.sums = append(ts.sums, fileInfoSum{name: ts.currentFile, sum: hex.EncodeToString(ts.h.Sum(nil)), pos: ts.fileCounter}) ts.fileCounter++ ts.h.Reset() } else { ts.first = false } currentHeader, err := ts.tarR.Next() if err != nil { if err == io.EOF { if err := ts.tarW.Close(); err != nil { return 0, err } if _, err := io.Copy(ts.writer, ts.bufTar); err != nil { return 0, err } if err := ts.writer.Close(); err != nil { return 0, err } ts.finished = true return n, nil } return n, err } ts.currentFile = strings.TrimSuffix(strings.TrimPrefix(currentHeader.Name, "./"), "/") if err := ts.encodeHeader(currentHeader); err != nil { return 0, err } if err := ts.tarW.WriteHeader(currentHeader); err != nil { return 0, err } if _, err := ts.tarW.Write(buf2[:n]); err != nil { return 0, err } ts.tarW.Flush() if _, err := io.Copy(ts.writer, ts.bufTar); err != nil { return 0, err } ts.writer.Flush() return ts.bufWriter.Read(buf) } return n, err } // Filling the hash buffer if _, err = ts.h.Write(buf2[:n]); err != nil { return 0, err } // Filling the tar writter if _, err = ts.tarW.Write(buf2[:n]); err != nil { return 0, err } ts.tarW.Flush() // Filling the output writer if _, err = io.Copy(ts.writer, ts.bufTar); err != nil { return 0, err } ts.writer.Flush() return ts.bufWriter.Read(buf) } func (ts *tarSum) Sum(extra []byte) string { ts.sums.SortBySums() h := ts.tHash.Hash() if extra != nil { h.Write(extra) } for _, fis := range ts.sums { h.Write([]byte(fis.Sum())) } checksum := ts.Version().String() + "+" + ts.tHash.Name() + ":" + hex.EncodeToString(h.Sum(nil)) return checksum } func (ts *tarSum) GetSums() FileInfoSums { return ts.sums } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/tarsum_spec.md ================================================ page_title: TarSum checksum specification page_description: Documentation for algorithms used in the TarSum checksum calculation page_keywords: docker, checksum, validation, tarsum # TarSum Checksum Specification ## Abstract This document describes the algorithms used in performing the TarSum checksum calculation on filesystem layers, the need for this method over existing methods, and the versioning of this calculation. ## Introduction The transportation of filesystems, regarding Docker, is done with tar(1) archives. There are a variety of tar serialization formats [2], and a key concern here is ensuring a repeatable checksum given a set of inputs from a generic tar archive. Types of transportation include distribution to and from a registry endpoint, saving and loading through commands or Docker daemon APIs, transferring the build context from client to Docker daemon, and committing the filesystem of a container to become an image. As tar archives are used for transit, but not preserved in many situations, the focus of the algorithm is to ensure the integrity of the preserved filesystem, while maintaining a deterministic accountability. This includes neither constraining the ordering or manipulation of the files during the creation or unpacking of the archive, nor include additional metadata state about the file system attributes. ## Intended Audience This document is outlining the methods used for consistent checksum calculation for filesystems transported via tar archives. Auditing these methodologies is an open and iterative process. This document should accommodate the review of source code. Ultimately, this document should be the starting point of further refinements to the algorithm and its future versions. ## Concept The checksum mechanism must ensure the integrity and assurance of the filesystem payload. ## Checksum Algorithm Profile A checksum mechanism must define the following operations and attributes: * Associated hashing cipher - used to checksum each file payload and attribute information. * Checksum list - each file of the filesystem archive has its checksum calculated from the payload and attributes of the file. The final checksum is calculated from this list, with specific ordering. * Version - as the algorithm adapts to requirements, there are behaviors of the algorithm to manage by versioning. * Archive being calculated - the tar archive having its checksum calculated ## Elements of TarSum checksum The calculated sum output is a text string. The elements included in the output of the calculated sum comprise the information needed for validation of the sum (TarSum version and hashing cipher used) and the expected checksum in hexadecimal form. There are two delimiters used: * '+' separates TarSum version from hashing cipher * ':' separates calculation mechanics from expected hash Example: ``` "tarsum.v1+sha256:220a60ecd4a3c32c282622a625a54db9ba0ff55b5ba9c29c7064a2bc358b6a3e" | | \ | | | \ | |_version_|_cipher__|__ | | \ | |_calculation_mechanics_|______________________expected_sum_______________________| ``` ## Versioning Versioning was introduced [0] to accommodate differences in calculation needed, and ability to maintain reverse compatibility. The general algorithm will be describe further in the 'Calculation'. ### Version0 This is the initial version of TarSum. Its element in the TarSum checksum string is `tarsum`. ### Version1 Its element in the TarSum checksum is `tarsum.v1`. The notable changes in this version: * Exclusion of file `mtime` from the file information headers, in each file checksum calculation * Inclusion of extended attributes (`xattrs`. Also seen as `SCHILY.xattr.` prefixed Pax tar file info headers) keys and values in each file checksum calculation ### VersionDev *Do not use unless validating refinements to the checksum algorithm* Its element in the TarSum checksum is `tarsum.dev`. This is a floating place holder for a next version and grounds for testing changes. The methods used for calculation are subject to change without notice, and this version is for testing and not for production use. ## Ciphers The official default and standard hashing cipher used in the calculation mechanic is `sha256`. This refers to SHA256 hash algorithm as defined in FIPS 180-4. Though the TarSum algorithm itself is not exclusively bound to the single hashing cipher `sha256`, support for alternate hashing ciphers was later added [1]. Use cases for alternate cipher could include future-proofing TarSum checksum format and using faster cipher hashes for tar filesystem checksums. ## Calculation ### Requirement As mentioned earlier, the calculation is such that it takes into consideration the lifecycle of the tar archive. In that the tar archive is not an immutable, permanent artifact. Otherwise options like relying on a known hashing cipher checksum of the archive itself would be reliable enough. The tar archive of the filesystem is used as a transportation medium for Docker images, and the archive is discarded once its contents are extracted. Therefore, for consistent validation items such as order of files in the tar archive and time stamps are subject to change once an image is received. ### Process The method is typically iterative due to reading tar info headers from the archive stream, though this is not a strict requirement. #### Files Each file in the tar archive have their contents (headers and body) checksummed individually using the designated associated hashing cipher. The ordered headers of the file are written to the checksum calculation first, and then the payload of the file body. The resulting checksum of the file is appended to the list of file sums. The sum is encoded as a string of the hexadecimal digest. Additionally, the file name and position in the archive is kept as reference for special ordering. #### Headers The following headers are read, in this order ( and the corresponding representation of its value): * 'name' - string * 'mode' - string of the base10 integer * 'uid' - string of the integer * 'gid' - string of the integer * 'size' - string of the integer * 'mtime' (_Version0 only_) - string of integer of the seconds since 1970-01-01 00:00:00 UTC * 'typeflag' - string of the char * 'linkname' - string * 'uname' - string * 'gname' - string * 'devmajor' - string of the integer * 'devminor' - string of the integer For >= Version1, the extended attribute headers ("SCHILY.xattr." prefixed pax headers) included after the above list. These xattrs key/values are first sorted by the keys. #### Header Format The ordered headers are written to the hash in the format of "{.key}{.value}" with no newline. #### Body After the order headers of the file have been added to the checksum for the file, the body of the file is written to the hash. #### List of file sums The list of file sums is sorted by the string of the hexadecimal digest. If there are two files in the tar with matching paths, the order of occurrence for that path is reflected for the sums of the corresponding file header and body. #### Final Checksum Begin with a fresh or initial state of the associated hash cipher. If there is additional payload to include in the TarSum calculation for the archive, it is written first. Then each checksum from the ordered list of file sums is written to the hash. The resulting digest is formatted per the Elements of TarSum checksum, including the TarSum version, the associated hash cipher and the hexadecimal encoded checksum digest. ## Security Considerations The initial version of TarSum has undergone one update that could invalidate handcrafted tar archives. The tar archive format supports appending of files with same names as prior files in the archive. The latter file will clobber the prior file of the same path. Due to this the algorithm now accounts for files with matching paths, and orders the list of file sums accordingly [3]. ## Footnotes * [0] Versioning https://github.com/docker/docker/commit/747f89cd327db9d50251b17797c4d825162226d0 * [1] Alternate ciphers https://github.com/docker/docker/commit/4e9925d780665149b8bc940d5ba242ada1973c4e * [2] Tar http://en.wikipedia.org/wiki/Tar_%28computing%29 * [3] Name collision https://github.com/docker/docker/commit/c5e6362c53cbbc09ddbabd5a7323e04438b57d31 ## Acknowledgements Joffrey F (shin-) and Guillaume J. Charmes (creack) on the initial work of the TarSum calculation. ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/tarsum_test.go ================================================ package tarsum import ( "archive/tar" "bytes" "compress/gzip" "crypto/md5" "crypto/rand" "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding/hex" "fmt" "io" "io/ioutil" "os" "strings" "testing" ) type testLayer struct { filename string options *sizedOptions jsonfile string gzip bool tarsum string version Version hash THash } var testLayers = []testLayer{ { filename: "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar", jsonfile: "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/json", version: Version0, tarsum: "tarsum+sha256:4095cc12fa5fdb1ab2760377e1cd0c4ecdd3e61b4f9b82319d96fcea6c9a41c6"}, { filename: "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar", jsonfile: "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/json", version: VersionDev, tarsum: "tarsum.dev+sha256:db56e35eec6ce65ba1588c20ba6b1ea23743b59e81fb6b7f358ccbde5580345c"}, { filename: "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar", jsonfile: "testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/json", gzip: true, tarsum: "tarsum+sha256:4095cc12fa5fdb1ab2760377e1cd0c4ecdd3e61b4f9b82319d96fcea6c9a41c6"}, { // Tests existing version of TarSum when xattrs are present filename: "testdata/xattr/layer.tar", jsonfile: "testdata/xattr/json", version: Version0, tarsum: "tarsum+sha256:07e304a8dbcb215b37649fde1a699f8aeea47e60815707f1cdf4d55d25ff6ab4"}, { // Tests next version of TarSum when xattrs are present filename: "testdata/xattr/layer.tar", jsonfile: "testdata/xattr/json", version: VersionDev, tarsum: "tarsum.dev+sha256:6c58917892d77b3b357b0f9ad1e28e1f4ae4de3a8006bd3beb8beda214d8fd16"}, { filename: "testdata/511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158/layer.tar", jsonfile: "testdata/511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158/json", tarsum: "tarsum+sha256:c66bd5ec9f87b8f4c6135ca37684618f486a3dd1d113b138d0a177bfa39c2571"}, { options: &sizedOptions{1, 1024 * 1024, false, false}, // a 1mb file (in memory) tarsum: "tarsum+sha256:8bf12d7e67c51ee2e8306cba569398b1b9f419969521a12ffb9d8875e8836738"}, { // this tar has two files with the same path filename: "testdata/collision/collision-0.tar", tarsum: "tarsum+sha256:08653904a68d3ab5c59e65ef58c49c1581caa3c34744f8d354b3f575ea04424a"}, { // this tar has the same two files (with the same path), but reversed order. ensuring is has different hash than above filename: "testdata/collision/collision-1.tar", tarsum: "tarsum+sha256:b51c13fbefe158b5ce420d2b930eef54c5cd55c50a2ee4abdddea8fa9f081e0d"}, { // this tar has newer of collider-0.tar, ensuring is has different hash filename: "testdata/collision/collision-2.tar", tarsum: "tarsum+sha256:381547080919bb82691e995508ae20ed33ce0f6948d41cafbeb70ce20c73ee8e"}, { // this tar has newer of collider-1.tar, ensuring is has different hash filename: "testdata/collision/collision-3.tar", tarsum: "tarsum+sha256:f886e431c08143164a676805205979cd8fa535dfcef714db5515650eea5a7c0f"}, { options: &sizedOptions{1, 1024 * 1024, false, false}, // a 1mb file (in memory) tarsum: "tarsum+md5:0d7529ec7a8360155b48134b8e599f53", hash: md5THash, }, { options: &sizedOptions{1, 1024 * 1024, false, false}, // a 1mb file (in memory) tarsum: "tarsum+sha1:f1fee39c5925807ff75ef1925e7a23be444ba4df", hash: sha1Hash, }, { options: &sizedOptions{1, 1024 * 1024, false, false}, // a 1mb file (in memory) tarsum: "tarsum+sha224:6319390c0b061d639085d8748b14cd55f697cf9313805218b21cf61c", hash: sha224Hash, }, { options: &sizedOptions{1, 1024 * 1024, false, false}, // a 1mb file (in memory) tarsum: "tarsum+sha384:a578ce3ce29a2ae03b8ed7c26f47d0f75b4fc849557c62454be4b5ffd66ba021e713b48ce71e947b43aab57afd5a7636", hash: sha384Hash, }, { options: &sizedOptions{1, 1024 * 1024, false, false}, // a 1mb file (in memory) tarsum: "tarsum+sha512:e9bfb90ca5a4dfc93c46ee061a5cf9837de6d2fdf82544d6460d3147290aecfabf7b5e415b9b6e72db9b8941f149d5d69fb17a394cbfaf2eac523bd9eae21855", hash: sha512Hash, }, } type sizedOptions struct { num int64 size int64 isRand bool realFile bool } // make a tar: // * num is the number of files the tar should have // * size is the bytes per file // * isRand is whether the contents of the files should be a random chunk (otherwise it's all zeros) // * realFile will write to a TempFile, instead of an in memory buffer func sizedTar(opts sizedOptions) io.Reader { var ( fh io.ReadWriter err error ) if opts.realFile { fh, err = ioutil.TempFile("", "tarsum") if err != nil { return nil } } else { fh = bytes.NewBuffer([]byte{}) } tarW := tar.NewWriter(fh) defer tarW.Close() for i := int64(0); i < opts.num; i++ { err := tarW.WriteHeader(&tar.Header{ Name: fmt.Sprintf("/testdata%d", i), Mode: 0755, Uid: 0, Gid: 0, Size: opts.size, }) if err != nil { return nil } var rBuf []byte if opts.isRand { rBuf = make([]byte, 8) _, err = rand.Read(rBuf) if err != nil { return nil } } else { rBuf = []byte{0, 0, 0, 0, 0, 0, 0, 0} } for i := int64(0); i < opts.size/int64(8); i++ { tarW.Write(rBuf) } } return fh } func emptyTarSum(gzip bool) (TarSum, error) { reader, writer := io.Pipe() tarWriter := tar.NewWriter(writer) // Immediately close tarWriter and write-end of the // Pipe in a separate goroutine so we don't block. go func() { tarWriter.Close() writer.Close() }() return NewTarSum(reader, !gzip, Version0) } // Test errors on NewTarsumForLabel func TestNewTarSumForLabelInvalid(t *testing.T) { reader := strings.NewReader("") if _, err := NewTarSumForLabel(reader, true, "invalidlabel"); err == nil { t.Fatalf("Expected an error, got nothing.") } if _, err := NewTarSumForLabel(reader, true, "invalid+sha256"); err == nil { t.Fatalf("Expected an error, got nothing.") } if _, err := NewTarSumForLabel(reader, true, "tarsum.v1+invalid"); err == nil { t.Fatalf("Expected an error, got nothing.") } } func TestNewTarSumForLabel(t *testing.T) { layer := testLayers[0] reader, err := os.Open(layer.filename) if err != nil { t.Fatal(err) } label := strings.Split(layer.tarsum, ":")[0] ts, err := NewTarSumForLabel(reader, false, label) if err != nil { t.Fatal(err) } // Make sure it actually worked by reading a little bit of it nbByteToRead := 8 * 1024 dBuf := make([]byte, nbByteToRead) _, err = ts.Read(dBuf) if err != nil { t.Errorf("failed to read %vKB from %s: %s", nbByteToRead, layer.filename, err) } } // TestEmptyTar tests that tarsum does not fail to read an empty tar // and correctly returns the hex digest of an empty hash. func TestEmptyTar(t *testing.T) { // Test without gzip. ts, err := emptyTarSum(false) if err != nil { t.Fatal(err) } zeroBlock := make([]byte, 1024) buf := new(bytes.Buffer) n, err := io.Copy(buf, ts) if err != nil { t.Fatal(err) } if n != int64(len(zeroBlock)) || !bytes.Equal(buf.Bytes(), zeroBlock) { t.Fatalf("tarSum did not write the correct number of zeroed bytes: %d", n) } expectedSum := ts.Version().String() + "+sha256:" + hex.EncodeToString(sha256.New().Sum(nil)) resultSum := ts.Sum(nil) if resultSum != expectedSum { t.Fatalf("expected [%s] but got [%s]", expectedSum, resultSum) } // Test with gzip. ts, err = emptyTarSum(true) if err != nil { t.Fatal(err) } buf.Reset() n, err = io.Copy(buf, ts) if err != nil { t.Fatal(err) } bufgz := new(bytes.Buffer) gz := gzip.NewWriter(bufgz) n, err = io.Copy(gz, bytes.NewBuffer(zeroBlock)) gz.Close() gzBytes := bufgz.Bytes() if n != int64(len(zeroBlock)) || !bytes.Equal(buf.Bytes(), gzBytes) { t.Fatalf("tarSum did not write the correct number of gzipped-zeroed bytes: %d", n) } resultSum = ts.Sum(nil) if resultSum != expectedSum { t.Fatalf("expected [%s] but got [%s]", expectedSum, resultSum) } // Test without ever actually writing anything. if ts, err = NewTarSum(bytes.NewReader([]byte{}), true, Version0); err != nil { t.Fatal(err) } resultSum = ts.Sum(nil) if resultSum != expectedSum { t.Fatalf("expected [%s] but got [%s]", expectedSum, resultSum) } } var ( md5THash = NewTHash("md5", md5.New) sha1Hash = NewTHash("sha1", sha1.New) sha224Hash = NewTHash("sha224", sha256.New224) sha384Hash = NewTHash("sha384", sha512.New384) sha512Hash = NewTHash("sha512", sha512.New) ) // Test all the build-in read size : buf8K, buf16K, buf32K and more func TestTarSumsReadSize(t *testing.T) { // Test always on the same layer (that is big enough) layer := testLayers[0] for i := 0; i < 5; i++ { reader, err := os.Open(layer.filename) if err != nil { t.Fatal(err) } ts, err := NewTarSum(reader, false, layer.version) if err != nil { t.Fatal(err) } // Read and discard bytes so that it populates sums nbByteToRead := (i + 1) * 8 * 1024 dBuf := make([]byte, nbByteToRead) _, err = ts.Read(dBuf) if err != nil { t.Errorf("failed to read %vKB from %s: %s", nbByteToRead, layer.filename, err) continue } } } func TestTarSums(t *testing.T) { for _, layer := range testLayers { var ( fh io.Reader err error ) if len(layer.filename) > 0 { fh, err = os.Open(layer.filename) if err != nil { t.Errorf("failed to open %s: %s", layer.filename, err) continue } } else if layer.options != nil { fh = sizedTar(*layer.options) } else { // What else is there to test? t.Errorf("what to do with %#v", layer) continue } if file, ok := fh.(*os.File); ok { defer file.Close() } var ts TarSum if layer.hash == nil { // double negatives! ts, err = NewTarSum(fh, !layer.gzip, layer.version) } else { ts, err = NewTarSumHash(fh, !layer.gzip, layer.version, layer.hash) } if err != nil { t.Errorf("%q :: %q", err, layer.filename) continue } // Read variable number of bytes to test dynamic buffer dBuf := make([]byte, 1) _, err = ts.Read(dBuf) if err != nil { t.Errorf("failed to read 1B from %s: %s", layer.filename, err) continue } dBuf = make([]byte, 16*1024) _, err = ts.Read(dBuf) if err != nil { t.Errorf("failed to read 16KB from %s: %s", layer.filename, err) continue } // Read and discard remaining bytes _, err = io.Copy(ioutil.Discard, ts) if err != nil { t.Errorf("failed to copy from %s: %s", layer.filename, err) continue } var gotSum string if len(layer.jsonfile) > 0 { jfh, err := os.Open(layer.jsonfile) if err != nil { t.Errorf("failed to open %s: %s", layer.jsonfile, err) continue } buf, err := ioutil.ReadAll(jfh) if err != nil { t.Errorf("failed to readAll %s: %s", layer.jsonfile, err) continue } gotSum = ts.Sum(buf) } else { gotSum = ts.Sum(nil) } if layer.tarsum != gotSum { t.Errorf("expecting [%s], but got [%s]", layer.tarsum, gotSum) } var expectedHashName string if layer.hash != nil { expectedHashName = layer.hash.Name() } else { expectedHashName = DefaultTHash.Name() } if expectedHashName != ts.Hash().Name() { t.Errorf("expecting hash [%v], but got [%s]", expectedHashName, ts.Hash().Name()) } } } func TestIteration(t *testing.T) { headerTests := []struct { expectedSum string // TODO(vbatts) it would be nice to get individual sums of each version Version hdr *tar.Header data []byte }{ { "tarsum+sha256:626c4a2e9a467d65c33ae81f7f3dedd4de8ccaee72af73223c4bc4718cbc7bbd", Version0, &tar.Header{ Name: "file.txt", Size: 0, Typeflag: tar.TypeReg, Devminor: 0, Devmajor: 0, }, []byte(""), }, { "tarsum.dev+sha256:6ffd43a1573a9913325b4918e124ee982a99c0f3cba90fc032a65f5e20bdd465", VersionDev, &tar.Header{ Name: "file.txt", Size: 0, Typeflag: tar.TypeReg, Devminor: 0, Devmajor: 0, }, []byte(""), }, { "tarsum.dev+sha256:b38166c059e11fb77bef30bf16fba7584446e80fcc156ff46d47e36c5305d8ef", VersionDev, &tar.Header{ Name: "another.txt", Uid: 1000, Gid: 1000, Uname: "slartibartfast", Gname: "users", Size: 4, Typeflag: tar.TypeReg, Devminor: 0, Devmajor: 0, }, []byte("test"), }, { "tarsum.dev+sha256:4cc2e71ac5d31833ab2be9b4f7842a14ce595ec96a37af4ed08f87bc374228cd", VersionDev, &tar.Header{ Name: "xattrs.txt", Uid: 1000, Gid: 1000, Uname: "slartibartfast", Gname: "users", Size: 4, Typeflag: tar.TypeReg, Xattrs: map[string]string{ "user.key1": "value1", "user.key2": "value2", }, }, []byte("test"), }, { "tarsum.dev+sha256:65f4284fa32c0d4112dd93c3637697805866415b570587e4fd266af241503760", VersionDev, &tar.Header{ Name: "xattrs.txt", Uid: 1000, Gid: 1000, Uname: "slartibartfast", Gname: "users", Size: 4, Typeflag: tar.TypeReg, Xattrs: map[string]string{ "user.KEY1": "value1", // adding different case to ensure different sum "user.key2": "value2", }, }, []byte("test"), }, { "tarsum+sha256:c12bb6f1303a9ddbf4576c52da74973c00d14c109bcfa76b708d5da1154a07fa", Version0, &tar.Header{ Name: "xattrs.txt", Uid: 1000, Gid: 1000, Uname: "slartibartfast", Gname: "users", Size: 4, Typeflag: tar.TypeReg, Xattrs: map[string]string{ "user.NOT": "CALCULATED", }, }, []byte("test"), }, } for _, htest := range headerTests { s, err := renderSumForHeader(htest.version, htest.hdr, htest.data) if err != nil { t.Fatal(err) } if s != htest.expectedSum { t.Errorf("expected sum: %q, got: %q", htest.expectedSum, s) } } } func renderSumForHeader(v Version, h *tar.Header, data []byte) (string, error) { buf := bytes.NewBuffer(nil) // first build our test tar tw := tar.NewWriter(buf) if err := tw.WriteHeader(h); err != nil { return "", err } if _, err := tw.Write(data); err != nil { return "", err } tw.Close() ts, err := NewTarSum(buf, true, v) if err != nil { return "", err } tr := tar.NewReader(ts) for { hdr, err := tr.Next() if hdr == nil || err == io.EOF { // Signals the end of the archive. break } if err != nil { return "", err } if _, err = io.Copy(ioutil.Discard, tr); err != nil { return "", err } } return ts.Sum(nil), nil } func Benchmark9kTar(b *testing.B) { buf := bytes.NewBuffer([]byte{}) fh, err := os.Open("testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar") if err != nil { b.Error(err) return } n, err := io.Copy(buf, fh) fh.Close() reader := bytes.NewReader(buf.Bytes()) b.SetBytes(n) b.ResetTimer() for i := 0; i < b.N; i++ { reader.Seek(0, 0) ts, err := NewTarSum(reader, true, Version0) if err != nil { b.Error(err) return } io.Copy(ioutil.Discard, ts) ts.Sum(nil) } } func Benchmark9kTarGzip(b *testing.B) { buf := bytes.NewBuffer([]byte{}) fh, err := os.Open("testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/layer.tar") if err != nil { b.Error(err) return } n, err := io.Copy(buf, fh) fh.Close() reader := bytes.NewReader(buf.Bytes()) b.SetBytes(n) b.ResetTimer() for i := 0; i < b.N; i++ { reader.Seek(0, 0) ts, err := NewTarSum(reader, false, Version0) if err != nil { b.Error(err) return } io.Copy(ioutil.Discard, ts) ts.Sum(nil) } } // this is a single big file in the tar archive func Benchmark1mbSingleFileTar(b *testing.B) { benchmarkTar(b, sizedOptions{1, 1024 * 1024, true, true}, false) } // this is a single big file in the tar archive func Benchmark1mbSingleFileTarGzip(b *testing.B) { benchmarkTar(b, sizedOptions{1, 1024 * 1024, true, true}, true) } // this is 1024 1k files in the tar archive func Benchmark1kFilesTar(b *testing.B) { benchmarkTar(b, sizedOptions{1024, 1024, true, true}, false) } // this is 1024 1k files in the tar archive func Benchmark1kFilesTarGzip(b *testing.B) { benchmarkTar(b, sizedOptions{1024, 1024, true, true}, true) } func benchmarkTar(b *testing.B, opts sizedOptions, isGzip bool) { var fh *os.File tarReader := sizedTar(opts) if br, ok := tarReader.(*os.File); ok { fh = br } defer os.Remove(fh.Name()) defer fh.Close() b.SetBytes(opts.size * opts.num) b.ResetTimer() for i := 0; i < b.N; i++ { ts, err := NewTarSum(fh, !isGzip, Version0) if err != nil { b.Error(err) return } io.Copy(ioutil.Discard, ts) ts.Sum(nil) fh.Seek(0, 0) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/testdata/46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457/json ================================================ {"id":"46af0962ab5afeb5ce6740d4d91652e69206fc991fd5328c1a94d364ad00e457","parent":"def3f9165934325dfd027c86530b2ea49bb57a0963eb1336b3a0415ff6fd56de","created":"2014-04-07T02:45:52.610504484Z","container":"e0f07f8d72cae171a3dcc35859960e7e956e0628bce6fedc4122bf55b2c287c7","container_config":{"Hostname":"88807319f25e","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"ExposedPorts":null,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":["/bin/sh","-c","sed -ri 's/^(%wheel.*)(ALL)$/\\1NOPASSWD: \\2/' /etc/sudoers"],"Image":"def3f9165934325dfd027c86530b2ea49bb57a0963eb1336b3a0415ff6fd56de","Volumes":null,"WorkingDir":"","Entrypoint":null,"NetworkDisabled":false,"OnBuild":[]},"docker_version":"0.9.1-dev","config":{"Hostname":"88807319f25e","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"ExposedPorts":null,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":null,"Image":"def3f9165934325dfd027c86530b2ea49bb57a0963eb1336b3a0415ff6fd56de","Volumes":null,"WorkingDir":"","Entrypoint":null,"NetworkDisabled":false,"OnBuild":[]},"architecture":"amd64","os":"linux","Size":3425} ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/testdata/511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158/json ================================================ {"id":"511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158","comment":"Imported from -","created":"2013-06-13T14:03:50.821769-07:00","container_config":{"Hostname":"","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"ExposedPorts":null,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":null,"Cmd":null,"Image":"","Volumes":null,"WorkingDir":"","Entrypoint":null,"NetworkDisabled":false,"OnBuild":null},"docker_version":"0.4.0","architecture":"x86_64","Size":0} ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/testdata/xattr/json ================================================ {"id":"4439c3c7f847954100b42b267e7e5529cac1d6934db082f65795c5ca2e594d93","parent":"73b164f4437db87e96e90083c73a6592f549646ae2ec00ed33c6b9b49a5c4470","created":"2014-05-16T17:19:44.091534414Z","container":"5f92fb06cc58f357f0cde41394e2bbbb664e663974b2ac1693ab07b7a306749b","container_config":{"Hostname":"9565c6517a0e","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"Cpuset":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"ExposedPorts":null,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":["/bin/sh","-c","setcap 'cap_setgid,cap_setuid+ep' ./file \u0026\u0026 getcap ./file"],"Image":"73b164f4437db87e96e90083c73a6592f549646ae2ec00ed33c6b9b49a5c4470","Volumes":null,"WorkingDir":"","Entrypoint":null,"NetworkDisabled":false,"OnBuild":[]},"docker_version":"0.11.1-dev","config":{"Hostname":"9565c6517a0e","Domainname":"","User":"","Memory":0,"MemorySwap":0,"CpuShares":0,"Cpuset":"","AttachStdin":false,"AttachStdout":false,"AttachStderr":false,"ExposedPorts":null,"Tty":false,"OpenStdin":false,"StdinOnce":false,"Env":["HOME=/","PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"],"Cmd":null,"Image":"73b164f4437db87e96e90083c73a6592f549646ae2ec00ed33c6b9b49a5c4470","Volumes":null,"WorkingDir":"","Entrypoint":null,"NetworkDisabled":false,"OnBuild":[]},"architecture":"amd64","os":"linux","Size":0} ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/versioning.go ================================================ package tarsum import ( "archive/tar" "errors" "sort" "strconv" "strings" ) // versioning of the TarSum algorithm // based on the prefix of the hash used // i.e. "tarsum+sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b" type Version int // Prefix of "tarsum" const ( Version0 Version = iota Version1 // NOTE: this variable will be either the latest or an unsettled next-version of the TarSum calculation VersionDev ) // VersionLabelForChecksum returns the label for the given tarsum // checksum, i.e., everything before the first `+` character in // the string or an empty string if no label separator is found. func VersionLabelForChecksum(checksum string) string { // Checksums are in the form: {versionLabel}+{hashID}:{hex} sepIndex := strings.Index(checksum, "+") if sepIndex < 0 { return "" } return checksum[:sepIndex] } // Get a list of all known tarsum Version func GetVersions() []Version { v := []Version{} for k := range tarSumVersions { v = append(v, k) } return v } var ( tarSumVersions = map[Version]string{ Version0: "tarsum", Version1: "tarsum.v1", VersionDev: "tarsum.dev", } tarSumVersionsByName = map[string]Version{ "tarsum": Version0, "tarsum.v1": Version1, "tarsum.dev": VersionDev, } ) func (tsv Version) String() string { return tarSumVersions[tsv] } // GetVersionFromTarsum returns the Version from the provided string func GetVersionFromTarsum(tarsum string) (Version, error) { tsv := tarsum if strings.Contains(tarsum, "+") { tsv = strings.SplitN(tarsum, "+", 2)[0] } for v, s := range tarSumVersions { if s == tsv { return v, nil } } return -1, ErrNotVersion } // Errors that may be returned by functions in this package var ( ErrNotVersion = errors.New("string does not include a TarSum Version") ErrVersionNotImplemented = errors.New("TarSum Version is not yet implemented") ) // tarHeaderSelector is the interface which different versions // of tarsum should use for selecting and ordering tar headers // for each item in the archive. type tarHeaderSelector interface { selectHeaders(h *tar.Header) (orderedHeaders [][2]string) } type tarHeaderSelectFunc func(h *tar.Header) (orderedHeaders [][2]string) func (f tarHeaderSelectFunc) selectHeaders(h *tar.Header) (orderedHeaders [][2]string) { return f(h) } func v0TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) { return [][2]string{ {"name", h.Name}, {"mode", strconv.Itoa(int(h.Mode))}, {"uid", strconv.Itoa(h.Uid)}, {"gid", strconv.Itoa(h.Gid)}, {"size", strconv.Itoa(int(h.Size))}, {"mtime", strconv.Itoa(int(h.ModTime.UTC().Unix()))}, {"typeflag", string([]byte{h.Typeflag})}, {"linkname", h.Linkname}, {"uname", h.Uname}, {"gname", h.Gname}, {"devmajor", strconv.Itoa(int(h.Devmajor))}, {"devminor", strconv.Itoa(int(h.Devminor))}, } } func v1TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) { // Get extended attributes. xAttrKeys := make([]string, len(h.Xattrs)) for k := range h.Xattrs { xAttrKeys = append(xAttrKeys, k) } sort.Strings(xAttrKeys) // Make the slice with enough capacity to hold the 11 basic headers // we want from the v0 selector plus however many xattrs we have. orderedHeaders = make([][2]string, 0, 11+len(xAttrKeys)) // Copy all headers from v0 excluding the 'mtime' header (the 5th element). v0headers := v0TarHeaderSelect(h) orderedHeaders = append(orderedHeaders, v0headers[0:5]...) orderedHeaders = append(orderedHeaders, v0headers[6:]...) // Finally, append the sorted xattrs. for _, k := range xAttrKeys { orderedHeaders = append(orderedHeaders, [2]string{k, h.Xattrs[k]}) } return } var registeredHeaderSelectors = map[Version]tarHeaderSelectFunc{ Version0: v0TarHeaderSelect, Version1: v1TarHeaderSelect, VersionDev: v1TarHeaderSelect, } func getTarHeaderSelector(v Version) (tarHeaderSelector, error) { headerSelector, ok := registeredHeaderSelectors[v] if !ok { return nil, ErrVersionNotImplemented } return headerSelector, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/versioning_test.go ================================================ package tarsum import ( "testing" ) func TestVersionLabelForChecksum(t *testing.T) { version := VersionLabelForChecksum("tarsum+sha256:deadbeef") if version != "tarsum" { t.Fatalf("Version should have been 'tarsum', was %v", version) } version = VersionLabelForChecksum("tarsum.v1+sha256:deadbeef") if version != "tarsum.v1" { t.Fatalf("Version should have been 'tarsum.v1', was %v", version) } version = VersionLabelForChecksum("something+somethingelse") if version != "something" { t.Fatalf("Version should have been 'something', was %v", version) } version = VersionLabelForChecksum("invalidChecksum") if version != "" { t.Fatalf("Version should have been empty, was %v", version) } } func TestVersion(t *testing.T) { expected := "tarsum" var v Version if v.String() != expected { t.Errorf("expected %q, got %q", expected, v.String()) } expected = "tarsum.v1" v = 1 if v.String() != expected { t.Errorf("expected %q, got %q", expected, v.String()) } expected = "tarsum.dev" v = 2 if v.String() != expected { t.Errorf("expected %q, got %q", expected, v.String()) } } func TestGetVersion(t *testing.T) { testSet := []struct { Str string Expected Version }{ {"tarsum+sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b", Version0}, {"tarsum+sha256", Version0}, {"tarsum", Version0}, {"tarsum.dev", VersionDev}, {"tarsum.dev+sha256:deadbeef", VersionDev}, } for _, ts := range testSet { v, err := GetVersionFromTarsum(ts.Str) if err != nil { t.Fatalf("%q : %s", err, ts.Str) } if v != ts.Expected { t.Errorf("expected %d (%q), got %d (%q)", ts.Expected, ts.Expected, v, v) } } // test one that does not exist, to ensure it errors str := "weak+md5:abcdeabcde" _, err := GetVersionFromTarsum(str) if err != ErrNotVersion { t.Fatalf("%q : %s", err, str) } } func TestGetVersions(t *testing.T) { expected := []Version{ Version0, Version1, VersionDev, } versions := GetVersions() if len(versions) != len(expected) { t.Fatalf("Expected %v versions, got %v", len(expected), len(versions)) } if !containsVersion(versions, expected[0]) || !containsVersion(versions, expected[1]) || !containsVersion(versions, expected[2]) { t.Fatalf("Expected [%v], got [%v]", expected, versions) } } func containsVersion(versions []Version, version Version) bool { for _, v := range versions { if v == version { return true } } return false } ================================================ FILE: vendor/github.com/docker/docker/pkg/tarsum/writercloser.go ================================================ package tarsum import ( "io" ) type writeCloseFlusher interface { io.WriteCloser Flush() error } type nopCloseFlusher struct { io.Writer } func (n *nopCloseFlusher) Close() error { return nil } func (n *nopCloseFlusher) Flush() error { return nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/tc_linux_cgo.go ================================================ // +build linux,cgo package term import ( "syscall" "unsafe" ) // #include import "C" type Termios syscall.Termios // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } newState := oldState.termios C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState))) newState.Oflag = newState.Oflag | C.OPOST if err := tcset(fd, &newState); err != 0 { return nil, err } return &oldState, nil } func tcget(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 } func tcset(fd uintptr, p *Termios) syscall.Errno { ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p))) if ret != 0 { return err.(syscall.Errno) } return 0 } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/tc_other.go ================================================ // +build !windows // +build !linux !cgo package term import ( "syscall" "unsafe" ) func tcget(fd uintptr, p *Termios) syscall.Errno { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(p))) return err } func tcset(fd uintptr, p *Termios) syscall.Errno { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(p))) return err } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/term.go ================================================ // +build !windows package term import ( "errors" "io" "os" "os/signal" "syscall" "unsafe" ) var ( ErrInvalidState = errors.New("Invalid terminal state") ) type State struct { termios Termios } type Winsize struct { Height uint16 Width uint16 x uint16 y uint16 } func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { return os.Stdin, os.Stdout, os.Stderr } func GetFdInfo(in interface{}) (uintptr, bool) { var inFd uintptr var isTerminalIn bool if file, ok := in.(*os.File); ok { inFd = file.Fd() isTerminalIn = IsTerminal(inFd) } return inFd, isTerminalIn } func GetWinsize(fd uintptr) (*Winsize, error) { ws := &Winsize{} _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCGWINSZ), uintptr(unsafe.Pointer(ws))) // Skipp errno = 0 if err == 0 { return ws, nil } return ws, err } func SetWinsize(fd uintptr, ws *Winsize) error { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(syscall.TIOCSWINSZ), uintptr(unsafe.Pointer(ws))) // Skipp errno = 0 if err == 0 { return nil } return err } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd uintptr) bool { var termios Termios return tcget(fd, &termios) == 0 } // Restore restores the terminal connected to the given file descriptor to a // previous state. func RestoreTerminal(fd uintptr, state *State) error { if state == nil { return ErrInvalidState } if err := tcset(fd, &state.termios); err != 0 { return err } return nil } func SaveState(fd uintptr) (*State, error) { var oldState State if err := tcget(fd, &oldState.termios); err != 0 { return nil, err } return &oldState, nil } func DisableEcho(fd uintptr, state *State) error { newState := state.termios newState.Lflag &^= syscall.ECHO if err := tcset(fd, &newState); err != 0 { return err } handleInterrupt(fd, state) return nil } func SetRawTerminal(fd uintptr) (*State, error) { oldState, err := MakeRaw(fd) if err != nil { return nil, err } handleInterrupt(fd, oldState) return oldState, err } func handleInterrupt(fd uintptr, state *State) { sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, os.Interrupt) go func() { _ = <-sigchan RestoreTerminal(fd, state) os.Exit(0) }() } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/term_windows.go ================================================ // +build windows package term import ( "io" "os" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/term/winconsole" ) // State holds the console mode for the terminal. type State struct { mode uint32 } // Winsize is used for window size. type Winsize struct { Height uint16 Width uint16 x uint16 y uint16 } func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { switch { case os.Getenv("ConEmuANSI") == "ON": // The ConEmu shell emulates ANSI well by default. return os.Stdin, os.Stdout, os.Stderr case os.Getenv("MSYSTEM") != "": // MSYS (mingw) does not emulate ANSI well. return winconsole.WinConsoleStreams() default: return winconsole.WinConsoleStreams() } } // GetFdInfo returns file descriptor and bool indicating whether the file is a terminal. func GetFdInfo(in interface{}) (uintptr, bool) { return winconsole.GetHandleInfo(in) } // GetWinsize retrieves the window size of the terminal connected to the passed file descriptor. func GetWinsize(fd uintptr) (*Winsize, error) { info, err := winconsole.GetConsoleScreenBufferInfo(fd) if err != nil { return nil, err } // TODO(azlinux): Set the pixel width / height of the console (currently unused by any caller) return &Winsize{ Width: uint16(info.Window.Right - info.Window.Left + 1), Height: uint16(info.Window.Bottom - info.Window.Top + 1), x: 0, y: 0}, nil } // SetWinsize sets the size of the given terminal connected to the passed file descriptor. func SetWinsize(fd uintptr, ws *Winsize) error { // TODO(azlinux): Implement SetWinsize logrus.Debugf("[windows] SetWinsize: WARNING -- Unsupported method invoked") return nil } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd uintptr) bool { return winconsole.IsConsole(fd) } // RestoreTerminal restores the terminal connected to the given file descriptor to a // previous state. func RestoreTerminal(fd uintptr, state *State) error { return winconsole.SetConsoleMode(fd, state.mode) } // SaveState saves the state of the terminal connected to the given file descriptor. func SaveState(fd uintptr) (*State, error) { mode, e := winconsole.GetConsoleMode(fd) if e != nil { return nil, e } return &State{mode}, nil } // DisableEcho disables echo for the terminal connected to the given file descriptor. // -- See http://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx func DisableEcho(fd uintptr, state *State) error { mode := state.mode mode &^= winconsole.ENABLE_ECHO_INPUT mode |= winconsole.ENABLE_PROCESSED_INPUT | winconsole.ENABLE_LINE_INPUT // TODO(azlinux): Core code registers a goroutine to catch os.Interrupt and reset the terminal state. return winconsole.SetConsoleMode(fd, mode) } // SetRawTerminal puts the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func SetRawTerminal(fd uintptr) (*State, error) { state, err := MakeRaw(fd) if err != nil { return nil, err } // TODO(azlinux): Core code registers a goroutine to catch os.Interrupt and reset the terminal state. return state, err } // MakeRaw puts the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { state, err := SaveState(fd) if err != nil { return nil, err } // 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 mode := state.mode // Disable these modes mode &^= winconsole.ENABLE_ECHO_INPUT mode &^= winconsole.ENABLE_LINE_INPUT mode &^= winconsole.ENABLE_MOUSE_INPUT mode &^= winconsole.ENABLE_WINDOW_INPUT mode &^= winconsole.ENABLE_PROCESSED_INPUT // Enable these modes mode |= winconsole.ENABLE_EXTENDED_FLAGS mode |= winconsole.ENABLE_INSERT_MODE mode |= winconsole.ENABLE_QUICK_EDIT_MODE err = winconsole.SetConsoleMode(fd, mode) if err != nil { return nil, err } return state, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/termios_darwin.go ================================================ package term import ( "syscall" "unsafe" ) const ( getTermios = syscall.TIOCGETA setTermios = syscall.TIOCSETA IGNBRK = syscall.IGNBRK PARMRK = syscall.PARMRK INLCR = syscall.INLCR IGNCR = syscall.IGNCR ECHONL = syscall.ECHONL CSIZE = syscall.CSIZE ICRNL = syscall.ICRNL ISTRIP = syscall.ISTRIP PARENB = syscall.PARENB ECHO = syscall.ECHO ICANON = syscall.ICANON ISIG = syscall.ISIG IXON = syscall.IXON BRKINT = syscall.BRKINT INPCK = syscall.INPCK OPOST = syscall.OPOST CS8 = syscall.CS8 IEXTEN = syscall.IEXTEN ) type Termios struct { Iflag uint64 Oflag uint64 Cflag uint64 Lflag uint64 Cc [20]byte Ispeed uint64 Ospeed uint64 } // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { return nil, err } newState := oldState.termios newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) newState.Oflag &^= OPOST newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) newState.Cflag &^= (CSIZE | PARENB) newState.Cflag |= CS8 newState.Cc[syscall.VMIN] = 1 newState.Cc[syscall.VTIME] = 0 if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { return nil, err } return &oldState, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/termios_freebsd.go ================================================ package term import ( "syscall" "unsafe" ) const ( getTermios = syscall.TIOCGETA setTermios = syscall.TIOCSETA IGNBRK = syscall.IGNBRK PARMRK = syscall.PARMRK INLCR = syscall.INLCR IGNCR = syscall.IGNCR ECHONL = syscall.ECHONL CSIZE = syscall.CSIZE ICRNL = syscall.ICRNL ISTRIP = syscall.ISTRIP PARENB = syscall.PARENB ECHO = syscall.ECHO ICANON = syscall.ICANON ISIG = syscall.ISIG IXON = syscall.IXON BRKINT = syscall.BRKINT INPCK = syscall.INPCK OPOST = syscall.OPOST CS8 = syscall.CS8 IEXTEN = syscall.IEXTEN ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]byte Ispeed uint32 Ospeed uint32 } // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { return nil, err } newState := oldState.termios newState.Iflag &^= (IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON) newState.Oflag &^= OPOST newState.Lflag &^= (ECHO | ECHONL | ICANON | ISIG | IEXTEN) newState.Cflag &^= (CSIZE | PARENB) newState.Cflag |= CS8 newState.Cc[syscall.VMIN] = 1 newState.Cc[syscall.VTIME] = 0 if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, uintptr(setTermios), uintptr(unsafe.Pointer(&newState))); err != 0 { return nil, err } return &oldState, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/termios_linux.go ================================================ // +build !cgo package term import ( "syscall" "unsafe" ) const ( getTermios = syscall.TCGETS setTermios = syscall.TCSETS ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [20]byte Ispeed uint32 Ospeed uint32 } // MakeRaw put the terminal connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be // restored. func MakeRaw(fd uintptr) (*State, error) { var oldState State if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { return nil, err } newState := oldState.termios newState.Iflag &^= (syscall.IGNBRK | syscall.BRKINT | syscall.PARMRK | syscall.ISTRIP | syscall.INLCR | syscall.IGNCR | syscall.ICRNL | syscall.IXON) newState.Oflag &^= syscall.OPOST newState.Lflag &^= (syscall.ECHO | syscall.ECHONL | syscall.ICANON | syscall.ISIG | syscall.IEXTEN) newState.Cflag &^= (syscall.CSIZE | syscall.PARENB) newState.Cflag |= syscall.CS8 if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 { return nil, err } return &oldState, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/winconsole/console_windows.go ================================================ // +build windows package winconsole import ( "bytes" "fmt" "io" "os" "strconv" "strings" "sync" "syscall" "unsafe" "github.com/Sirupsen/logrus" ) const ( // Consts for Get/SetConsoleMode function // -- 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 // If parameter is a screen buffer handle, additional values ENABLE_PROCESSED_OUTPUT = 0x0001 ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 //http://msdn.microsoft.com/en-us/library/windows/desktop/ms682088(v=vs.85).aspx#_win32_character_attributes FOREGROUND_BLUE = 1 FOREGROUND_GREEN = 2 FOREGROUND_RED = 4 FOREGROUND_INTENSITY = 8 FOREGROUND_MASK_SET = 0x000F FOREGROUND_MASK_UNSET = 0xFFF0 BACKGROUND_BLUE = 16 BACKGROUND_GREEN = 32 BACKGROUND_RED = 64 BACKGROUND_INTENSITY = 128 BACKGROUND_MASK_SET = 0x00F0 BACKGROUND_MASK_UNSET = 0xFF0F COMMON_LVB_REVERSE_VIDEO = 0x4000 COMMON_LVB_UNDERSCORE = 0x8000 // http://man7.org/linux/man-pages/man4/console_codes.4.html // ECMA-48 Set Graphics Rendition ANSI_ATTR_RESET = 0 ANSI_ATTR_BOLD = 1 ANSI_ATTR_DIM = 2 ANSI_ATTR_UNDERLINE = 4 ANSI_ATTR_BLINK = 5 ANSI_ATTR_REVERSE = 7 ANSI_ATTR_INVISIBLE = 8 ANSI_ATTR_UNDERLINE_OFF = 24 ANSI_ATTR_BLINK_OFF = 25 ANSI_ATTR_REVERSE_OFF = 27 ANSI_ATTR_INVISIBLE_OFF = 8 ANSI_FOREGROUND_BLACK = 30 ANSI_FOREGROUND_RED = 31 ANSI_FOREGROUND_GREEN = 32 ANSI_FOREGROUND_YELLOW = 33 ANSI_FOREGROUND_BLUE = 34 ANSI_FOREGROUND_MAGENTA = 35 ANSI_FOREGROUND_CYAN = 36 ANSI_FOREGROUND_WHITE = 37 ANSI_FOREGROUND_DEFAULT = 39 ANSI_BACKGROUND_BLACK = 40 ANSI_BACKGROUND_RED = 41 ANSI_BACKGROUND_GREEN = 42 ANSI_BACKGROUND_YELLOW = 43 ANSI_BACKGROUND_BLUE = 44 ANSI_BACKGROUND_MAGENTA = 45 ANSI_BACKGROUND_CYAN = 46 ANSI_BACKGROUND_WHITE = 47 ANSI_BACKGROUND_DEFAULT = 49 ANSI_MAX_CMD_LENGTH = 256 MAX_INPUT_EVENTS = 128 MAX_INPUT_BUFFER = 1024 DEFAULT_WIDTH = 80 DEFAULT_HEIGHT = 24 ) // http://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 ) var kernel32DLL = syscall.NewLazyDLL("kernel32.dll") var ( setConsoleModeProc = kernel32DLL.NewProc("SetConsoleMode") getConsoleScreenBufferInfoProc = kernel32DLL.NewProc("GetConsoleScreenBufferInfo") setConsoleCursorPositionProc = kernel32DLL.NewProc("SetConsoleCursorPosition") setConsoleTextAttributeProc = kernel32DLL.NewProc("SetConsoleTextAttribute") fillConsoleOutputCharacterProc = kernel32DLL.NewProc("FillConsoleOutputCharacterW") writeConsoleOutputProc = kernel32DLL.NewProc("WriteConsoleOutputW") readConsoleInputProc = kernel32DLL.NewProc("ReadConsoleInputW") getNumberOfConsoleInputEventsProc = kernel32DLL.NewProc("GetNumberOfConsoleInputEvents") getConsoleCursorInfoProc = kernel32DLL.NewProc("GetConsoleCursorInfo") setConsoleCursorInfoProc = kernel32DLL.NewProc("SetConsoleCursorInfo") setConsoleWindowInfoProc = kernel32DLL.NewProc("SetConsoleWindowInfo") setConsoleScreenBufferSizeProc = kernel32DLL.NewProc("SetConsoleScreenBufferSize") ) // types for calling various windows API // see http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093(v=vs.85).aspx type ( SHORT int16 BOOL int32 WORD uint16 WCHAR uint16 DWORD uint32 SMALL_RECT struct { Left SHORT Top SHORT Right SHORT Bottom SHORT } COORD struct { X SHORT Y SHORT } CONSOLE_SCREEN_BUFFER_INFO struct { Size COORD CursorPosition COORD Attributes WORD Window SMALL_RECT MaximumWindowSize COORD } CONSOLE_CURSOR_INFO struct { Size DWORD Visible BOOL } // http://msdn.microsoft.com/en-us/library/windows/desktop/ms684166(v=vs.85).aspx KEY_EVENT_RECORD struct { KeyDown BOOL RepeatCount WORD VirtualKeyCode WORD VirtualScanCode WORD UnicodeChar WCHAR ControlKeyState DWORD } INPUT_RECORD struct { EventType WORD KeyEvent KEY_EVENT_RECORD } CHAR_INFO struct { UnicodeChar WCHAR Attributes WORD } ) // TODO(azlinux): Basic type clean-up // -- Convert all uses of uintptr to syscall.Handle to be consistent with Windows syscall // -- Convert, as appropriate, types to use defined Windows types (e.g., DWORD instead of uint32) // Implements the TerminalEmulator interface type WindowsTerminal struct { outMutex sync.Mutex inMutex sync.Mutex inputBuffer []byte inputSize int inputEvents []INPUT_RECORD screenBufferInfo *CONSOLE_SCREEN_BUFFER_INFO inputEscapeSequence []byte } func getStdHandle(stdhandle int) uintptr { handle, err := syscall.GetStdHandle(stdhandle) if err != nil { panic(fmt.Errorf("could not get standard io handle %d", stdhandle)) } return uintptr(handle) } func WinConsoleStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { handler := &WindowsTerminal{ inputBuffer: make([]byte, MAX_INPUT_BUFFER), inputEscapeSequence: []byte(KEY_ESC_CSI), inputEvents: make([]INPUT_RECORD, MAX_INPUT_EVENTS), } if IsConsole(os.Stdin.Fd()) { stdIn = &terminalReader{ wrappedReader: os.Stdin, emulator: handler, command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), fd: getStdHandle(syscall.STD_INPUT_HANDLE), } } else { stdIn = os.Stdin } if IsConsole(os.Stdout.Fd()) { stdoutHandle := getStdHandle(syscall.STD_OUTPUT_HANDLE) // Save current screen buffer info screenBufferInfo, err := GetConsoleScreenBufferInfo(stdoutHandle) if err != nil { // If GetConsoleScreenBufferInfo returns a nil error, it usually means that stdout is not a TTY. // However, this is in the branch where stdout is a TTY, hence the panic. panic("could not get console screen buffer info") } handler.screenBufferInfo = screenBufferInfo buffer = make([]CHAR_INFO, screenBufferInfo.MaximumWindowSize.X*screenBufferInfo.MaximumWindowSize.Y) stdOut = &terminalWriter{ wrappedWriter: os.Stdout, emulator: handler, command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), fd: stdoutHandle, } } else { stdOut = os.Stdout } if IsConsole(os.Stderr.Fd()) { stdErr = &terminalWriter{ wrappedWriter: os.Stderr, emulator: handler, command: make([]byte, 0, ANSI_MAX_CMD_LENGTH), fd: getStdHandle(syscall.STD_ERROR_HANDLE), } } else { stdErr = os.Stderr } return stdIn, stdOut, stdErr } // GetHandleInfo returns file descriptor and bool indicating whether the file is a console. func GetHandleInfo(in interface{}) (uintptr, bool) { var inFd uintptr var isTerminalIn bool switch t := in.(type) { case *terminalReader: in = t.wrappedReader case *terminalWriter: in = t.wrappedWriter } if file, ok := in.(*os.File); ok { inFd = file.Fd() isTerminalIn = IsConsole(inFd) } return inFd, isTerminalIn } func getError(r1, r2 uintptr, lastErr error) error { // If the function fails, the return value is zero. if r1 == 0 { if lastErr != nil { return lastErr } return syscall.EINVAL } return nil } // GetConsoleMode gets the console mode for given file descriptor // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx func GetConsoleMode(handle uintptr) (uint32, error) { var mode uint32 err := syscall.GetConsoleMode(syscall.Handle(handle), &mode) return mode, err } // SetConsoleMode sets the console mode for given file descriptor // http://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx func SetConsoleMode(handle uintptr, mode uint32) error { return getError(setConsoleModeProc.Call(handle, uintptr(mode), 0)) } // SetCursorVisible sets the cursor visbility // http://msdn.microsoft.com/en-us/library/windows/desktop/ms686019(v=vs.85).aspx func SetCursorVisible(handle uintptr, isVisible BOOL) (bool, error) { var cursorInfo *CONSOLE_CURSOR_INFO = &CONSOLE_CURSOR_INFO{} if err := getError(getConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)); err != nil { return false, err } cursorInfo.Visible = isVisible if err := getError(setConsoleCursorInfoProc.Call(handle, uintptr(unsafe.Pointer(cursorInfo)), 0)); err != nil { return false, err } return true, nil } // SetWindowSize sets the size of the console window. func SetWindowSize(handle uintptr, width, height, max SHORT) (bool, error) { window := SMALL_RECT{Left: 0, Top: 0, Right: width - 1, Bottom: height - 1} coord := COORD{X: width - 1, Y: max} if err := getError(setConsoleWindowInfoProc.Call(handle, uintptr(1), uintptr(unsafe.Pointer(&window)))); err != nil { return false, err } if err := getError(setConsoleScreenBufferSizeProc.Call(handle, marshal(coord))); err != nil { return false, err } return true, nil } // GetConsoleScreenBufferInfo retrieves information about the specified console screen buffer. // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683171(v=vs.85).aspx func GetConsoleScreenBufferInfo(handle uintptr) (*CONSOLE_SCREEN_BUFFER_INFO, error) { var info CONSOLE_SCREEN_BUFFER_INFO if err := getError(getConsoleScreenBufferInfoProc.Call(handle, uintptr(unsafe.Pointer(&info)), 0)); err != nil { return nil, err } return &info, nil } // setConsoleTextAttribute sets the attributes of characters written to the // console screen buffer by the WriteFile or WriteConsole function, // http://msdn.microsoft.com/en-us/library/windows/desktop/ms686047(v=vs.85).aspx func setConsoleTextAttribute(handle uintptr, attribute WORD) error { return getError(setConsoleTextAttributeProc.Call(handle, uintptr(attribute), 0)) } func writeConsoleOutput(handle uintptr, buffer []CHAR_INFO, bufferSize COORD, bufferCoord COORD, writeRegion *SMALL_RECT) (bool, error) { if err := getError(writeConsoleOutputProc.Call(handle, uintptr(unsafe.Pointer(&buffer[0])), marshal(bufferSize), marshal(bufferCoord), uintptr(unsafe.Pointer(writeRegion)))); err != nil { return false, err } return true, nil } // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682663(v=vs.85).aspx func fillConsoleOutputCharacter(handle uintptr, fillChar byte, length uint32, writeCord COORD) (bool, error) { out := int64(0) if err := getError(fillConsoleOutputCharacterProc.Call(handle, uintptr(fillChar), uintptr(length), marshal(writeCord), uintptr(unsafe.Pointer(&out)))); err != nil { return false, err } return true, nil } // Gets the number of space characters to write for "clearing" the section of terminal func getNumberOfChars(fromCoord COORD, toCoord COORD, screenSize COORD) uint32 { // must be valid cursor position if fromCoord.X < 0 || fromCoord.Y < 0 || toCoord.X < 0 || toCoord.Y < 0 { return 0 } if fromCoord.X >= screenSize.X || fromCoord.Y >= screenSize.Y || toCoord.X >= screenSize.X || toCoord.Y >= screenSize.Y { return 0 } // can't be backwards if fromCoord.Y > toCoord.Y { return 0 } // same line if fromCoord.Y == toCoord.Y { return uint32(toCoord.X-fromCoord.X) + 1 } // spans more than one line if fromCoord.Y < toCoord.Y { // from start till end of line for first line + from start of line till end retValue := uint32(screenSize.X-fromCoord.X) + uint32(toCoord.X) + 1 // don't count first and last line linesBetween := toCoord.Y - fromCoord.Y - 1 if linesBetween > 0 { retValue = retValue + uint32(linesBetween*screenSize.X) } return retValue } return 0 } var buffer []CHAR_INFO func clearDisplayRect(handle uintptr, attributes WORD, fromCoord COORD, toCoord COORD) (uint32, error) { var writeRegion SMALL_RECT writeRegion.Left = fromCoord.X writeRegion.Top = fromCoord.Y writeRegion.Right = toCoord.X writeRegion.Bottom = toCoord.Y // allocate and initialize buffer width := toCoord.X - fromCoord.X + 1 height := toCoord.Y - fromCoord.Y + 1 size := uint32(width) * uint32(height) if size > 0 { buffer := make([]CHAR_INFO, size) for i := range buffer { buffer[i] = CHAR_INFO{WCHAR(' '), attributes} } // Write to buffer r, err := writeConsoleOutput(handle, buffer, COORD{X: width, Y: height}, COORD{X: 0, Y: 0}, &writeRegion) if !r { if err != nil { return 0, err } return 0, syscall.EINVAL } } return uint32(size), nil } func clearDisplayRange(handle uintptr, attributes WORD, fromCoord COORD, toCoord COORD) (uint32, error) { nw := uint32(0) // start and end on same line if fromCoord.Y == toCoord.Y { return clearDisplayRect(handle, attributes, fromCoord, toCoord) } // TODO(azlinux): if full screen, optimize // spans more than one line if fromCoord.Y < toCoord.Y { // from start position till end of line for first line n, err := clearDisplayRect(handle, attributes, fromCoord, COORD{X: toCoord.X, Y: fromCoord.Y}) if err != nil { return nw, err } nw += n // lines between linesBetween := toCoord.Y - fromCoord.Y - 1 if linesBetween > 0 { n, err = clearDisplayRect(handle, attributes, COORD{X: 0, Y: fromCoord.Y + 1}, COORD{X: toCoord.X, Y: toCoord.Y - 1}) if err != nil { return nw, err } nw += n } // lines at end n, err = clearDisplayRect(handle, attributes, COORD{X: 0, Y: toCoord.Y}, toCoord) if err != nil { return nw, err } nw += n } return nw, nil } // setConsoleCursorPosition sets the console cursor position // Note The X and Y are zero based // If relative is true then the new position is relative to current one func setConsoleCursorPosition(handle uintptr, isRelative bool, column int16, line int16) error { screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) if err != nil { return err } var position COORD if isRelative { position.X = screenBufferInfo.CursorPosition.X + SHORT(column) position.Y = screenBufferInfo.CursorPosition.Y + SHORT(line) } else { position.X = SHORT(column) position.Y = SHORT(line) } return getError(setConsoleCursorPositionProc.Call(handle, marshal(position), 0)) } // http://msdn.microsoft.com/en-us/library/windows/desktop/ms683207(v=vs.85).aspx func getNumberOfConsoleInputEvents(handle uintptr) (uint16, error) { var n DWORD if err := getError(getNumberOfConsoleInputEventsProc.Call(handle, uintptr(unsafe.Pointer(&n)))); err != nil { return 0, err } return uint16(n), nil } //http://msdn.microsoft.com/en-us/library/windows/desktop/ms684961(v=vs.85).aspx func readConsoleInputKey(handle uintptr, inputBuffer []INPUT_RECORD) (int, error) { var nr DWORD if err := getError(readConsoleInputProc.Call(handle, uintptr(unsafe.Pointer(&inputBuffer[0])), uintptr(len(inputBuffer)), uintptr(unsafe.Pointer(&nr)))); err != nil { return 0, err } return int(nr), nil } func getWindowsTextAttributeForAnsiValue(originalFlag WORD, defaultValue WORD, ansiValue int16) (WORD, error) { flag := WORD(originalFlag) if flag == 0 { flag = defaultValue } switch ansiValue { case ANSI_ATTR_RESET: flag &^= COMMON_LVB_UNDERSCORE flag &^= BACKGROUND_INTENSITY flag = flag | FOREGROUND_INTENSITY case ANSI_ATTR_INVISIBLE: // TODO: how do you reset reverse? case ANSI_ATTR_UNDERLINE: flag = flag | COMMON_LVB_UNDERSCORE case ANSI_ATTR_BLINK: // seems like background intenisty is blink flag = flag | BACKGROUND_INTENSITY case ANSI_ATTR_UNDERLINE_OFF: flag &^= COMMON_LVB_UNDERSCORE case ANSI_ATTR_BLINK_OFF: // seems like background intenisty is blink flag &^= BACKGROUND_INTENSITY case ANSI_ATTR_BOLD: flag = flag | FOREGROUND_INTENSITY case ANSI_ATTR_DIM: flag &^= FOREGROUND_INTENSITY case ANSI_ATTR_REVERSE, ANSI_ATTR_REVERSE_OFF: // swap forground and background bits foreground := flag & FOREGROUND_MASK_SET background := flag & BACKGROUND_MASK_SET flag = (flag & BACKGROUND_MASK_UNSET & FOREGROUND_MASK_UNSET) | (foreground << 4) | (background >> 4) // FOREGROUND case ANSI_FOREGROUND_DEFAULT: flag = (flag & FOREGROUND_MASK_UNSET) | (defaultValue & FOREGROUND_MASK_SET) case ANSI_FOREGROUND_BLACK: flag = flag ^ (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE) case ANSI_FOREGROUND_RED: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED case ANSI_FOREGROUND_GREEN: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_GREEN case ANSI_FOREGROUND_YELLOW: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_GREEN case ANSI_FOREGROUND_BLUE: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_BLUE case ANSI_FOREGROUND_MAGENTA: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_BLUE case ANSI_FOREGROUND_CYAN: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_GREEN | FOREGROUND_BLUE case ANSI_FOREGROUND_WHITE: flag = (flag & FOREGROUND_MASK_UNSET) | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE // Background case ANSI_BACKGROUND_DEFAULT: // Black with no intensity flag = (flag & BACKGROUND_MASK_UNSET) | (defaultValue & BACKGROUND_MASK_SET) case ANSI_BACKGROUND_BLACK: flag = (flag & BACKGROUND_MASK_UNSET) case ANSI_BACKGROUND_RED: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED case ANSI_BACKGROUND_GREEN: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_GREEN case ANSI_BACKGROUND_YELLOW: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_GREEN case ANSI_BACKGROUND_BLUE: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_BLUE case ANSI_BACKGROUND_MAGENTA: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_BLUE case ANSI_BACKGROUND_CYAN: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_GREEN | BACKGROUND_BLUE case ANSI_BACKGROUND_WHITE: flag = (flag & BACKGROUND_MASK_UNSET) | BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE } return flag, nil } // HandleOutputCommand interpretes the Ansi commands and then makes appropriate Win32 calls func (term *WindowsTerminal) HandleOutputCommand(handle uintptr, command []byte) (n int, err error) { // always consider all the bytes in command, processed n = len(command) parsedCommand := parseAnsiCommand(command) logrus.Debugf("[windows] HandleOutputCommand: %v", parsedCommand) // console settings changes need to happen in atomic way term.outMutex.Lock() defer term.outMutex.Unlock() switch parsedCommand.Command { case "m": // [Value;...;Valuem // Set Graphics Mode: // Calls the graphics functions specified by the following values. // These specified functions remain active until the next occurrence of this escape sequence. // Graphics mode changes the colors and attributes of text (such as bold and underline) displayed on the screen. screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) if err != nil { return n, err } flag := screenBufferInfo.Attributes for _, e := range parsedCommand.Parameters { value, _ := strconv.ParseInt(e, 10, 16) // base 10, 16 bit if value == ANSI_ATTR_RESET { flag = term.screenBufferInfo.Attributes // reset } else { flag, err = getWindowsTextAttributeForAnsiValue(flag, term.screenBufferInfo.Attributes, int16(value)) if err != nil { return n, err } } } if err := setConsoleTextAttribute(handle, flag); err != nil { return n, err } case "H", "f": // [line;columnH // [line;columnf // Moves the cursor to the specified position (coordinates). // If you do not specify a position, the cursor moves to the home position at the upper-left corner of the screen (line 0, column 0). screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) if err != nil { return n, err } line, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) if err != nil { return n, err } if line > int16(screenBufferInfo.Window.Bottom) { line = int16(screenBufferInfo.Window.Bottom) + 1 } column, err := parseInt16OrDefault(parsedCommand.getParam(1), 1) if err != nil { return n, err } if column > int16(screenBufferInfo.Window.Right) { column = int16(screenBufferInfo.Window.Right) + 1 } // The numbers are not 0 based, but 1 based logrus.Debugf("[windows] HandleOutputCommmand: Moving cursor to (%v,%v)", column-1, line-1) if err := setConsoleCursorPosition(handle, false, column-1, line-1); err != nil { return n, err } case "A": // [valueA // Moves the cursor up by the specified number of lines without changing columns. // If the cursor is already on the top line, ignores this sequence. value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) if err != nil { return len(command), err } if err := setConsoleCursorPosition(handle, true, 0, -value); err != nil { return n, err } case "B": // [valueB // Moves the cursor down by the specified number of lines without changing columns. // If the cursor is already on the bottom line, ignores this sequence. value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) if err != nil { return n, err } if err := setConsoleCursorPosition(handle, true, 0, value); err != nil { return n, err } case "C": // [valueC // Moves the cursor forward by the specified number of columns without changing lines. // If the cursor is already in the rightmost column, ignores this sequence. value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) if err != nil { return n, err } if err := setConsoleCursorPosition(handle, true, value, 0); err != nil { return n, err } case "D": // [valueD // Moves the cursor back by the specified number of columns without changing lines. // If the cursor is already in the leftmost column, ignores this sequence. value, err := parseInt16OrDefault(parsedCommand.getParam(0), 1) if err != nil { return n, err } if err := setConsoleCursorPosition(handle, true, -value, 0); err != nil { return n, err } case "J": // [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. // Clears the screen and moves the cursor to the home position (line 0, column 0). value, err := parseInt16OrDefault(parsedCommand.getParam(0), 0) if err != nil { return n, err } var start COORD var cursor COORD var end COORD screenBufferInfo, err := GetConsoleScreenBufferInfo(handle) if err != nil { return n, err } switch value { case 0: start = screenBufferInfo.CursorPosition // end of the buffer end.X = screenBufferInfo.Size.X - 1 end.Y = screenBufferInfo.Size.Y - 1 // cursor cursor = screenBufferInfo.CursorPosition case 1: // start of the screen start.X = 0 start.Y = 0 // end of the screen end = screenBufferInfo.CursorPosition // cursor cursor = screenBufferInfo.CursorPosition case 2: // start of the screen start.X = 0 start.Y = 0 // end of the buffer end.X = screenBufferInfo.Size.X - 1 end.Y = screenBufferInfo.Size.Y - 1 // cursor cursor.X = 0 cursor.Y = 0 } if _, err := clearDisplayRange(uintptr(handle), term.screenBufferInfo.Attributes, start, end); err != nil { return n, err } // remember the the cursor position is 1 based if err := setConsoleCursorPosition(handle, false, int16(cursor.X), int16(cursor.Y)); err != nil { return n, err } case "K": // [K // Clears all characters from the cursor position to the end of the line (including the character at the cursor position). // [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. value, err := parseInt16OrDefault(parsedCommand.getParam(0), 0) var start COORD var cursor COORD var end COORD screenBufferInfo, err := GetConsoleScreenBufferInfo(uintptr(handle)) if err != nil { return n, err } switch value { case 0: // start is where cursor is start = screenBufferInfo.CursorPosition // end of line end.X = screenBufferInfo.Size.X - 1 end.Y = screenBufferInfo.CursorPosition.Y // cursor remains the same cursor = screenBufferInfo.CursorPosition case 1: // beginning of line start.X = 0 start.Y = screenBufferInfo.CursorPosition.Y // until cursor end = screenBufferInfo.CursorPosition // cursor remains the same cursor = screenBufferInfo.CursorPosition case 2: // start of the line start.X = 0 start.Y = screenBufferInfo.CursorPosition.Y - 1 // end of the line end.X = screenBufferInfo.Size.X - 1 end.Y = screenBufferInfo.CursorPosition.Y - 1 // cursor cursor.X = 0 cursor.Y = screenBufferInfo.CursorPosition.Y - 1 } if _, err := clearDisplayRange(uintptr(handle), term.screenBufferInfo.Attributes, start, end); err != nil { return n, err } // remember the the cursor position is 1 based if err := setConsoleCursorPosition(uintptr(handle), false, int16(cursor.X), int16(cursor.Y)); err != nil { return n, err } case "l": for _, value := range parsedCommand.Parameters { switch value { case "?25", "25": SetCursorVisible(uintptr(handle), BOOL(0)) case "?1049", "1049": // TODO (azlinux): Restore terminal case "?1", "1": // If the DECCKM function is reset, then the arrow keys send ANSI cursor sequences to the host. term.inputEscapeSequence = []byte(KEY_ESC_CSI) } } case "h": for _, value := range parsedCommand.Parameters { switch value { case "?25", "25": SetCursorVisible(uintptr(handle), BOOL(1)) case "?1049", "1049": // TODO (azlinux): Save terminal case "?1", "1": // If the DECCKM function is set, then the arrow keys send application sequences to the host. // DECCKM (default off): When set, the cursor keys send an ESC O prefix, rather than ESC [. term.inputEscapeSequence = []byte(KEY_ESC_O) } } case "]": /* TODO (azlinux): Linux Console Private CSI Sequences The following sequences are neither ECMA-48 nor native VT102. They are native to the Linux console driver. Colors are in SGR parameters: 0 = black, 1 = red, 2 = green, 3 = brown, 4 = blue, 5 = magenta, 6 = cyan, 7 = white. ESC [ 1 ; n ] Set color n as the underline color ESC [ 2 ; n ] Set color n as the dim color ESC [ 8 ] Make the current color pair the default attributes. ESC [ 9 ; n ] Set screen blank timeout to n minutes. ESC [ 10 ; n ] Set bell frequency in Hz. ESC [ 11 ; n ] Set bell duration in msec. ESC [ 12 ; n ] Bring specified console to the front. ESC [ 13 ] Unblank the screen. ESC [ 14 ; n ] Set the VESA powerdown interval in minutes. */ } return n, nil } // WriteChars writes the bytes to given writer. func (term *WindowsTerminal) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } return w.Write(p) } const ( CAPSLOCK_ON = 0x0080 //The CAPS LOCK light is on. ENHANCED_KEY = 0x0100 //The key is enhanced. LEFT_ALT_PRESSED = 0x0002 //The left ALT key is pressed. LEFT_CTRL_PRESSED = 0x0008 //The left CTRL key is pressed. NUMLOCK_ON = 0x0020 //The NUM LOCK light is on. RIGHT_ALT_PRESSED = 0x0001 //The right ALT key is pressed. RIGHT_CTRL_PRESSED = 0x0004 //The right CTRL key is pressed. SCROLLLOCK_ON = 0x0040 //The SCROLL LOCK light is on. SHIFT_PRESSED = 0x0010 // The SHIFT key is pressed. ) const ( 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" ) var keyMapPrefix = map[WORD]string{ VK_UP: "\x1B[%sA", VK_DOWN: "\x1B[%sB", VK_RIGHT: "\x1B[%sC", VK_LEFT: "\x1B[%sD", VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 VK_END: "\x1B[4%s~", // showkey shows ^[[4 VK_INSERT: "\x1B[2%s~", VK_DELETE: "\x1B[3%s~", VK_PRIOR: "\x1B[5%s~", VK_NEXT: "\x1B[6%s~", VK_F1: "", VK_F2: "", VK_F3: "\x1B[13%s~", VK_F4: "\x1B[14%s~", VK_F5: "\x1B[15%s~", VK_F6: "\x1B[17%s~", VK_F7: "\x1B[18%s~", VK_F8: "\x1B[19%s~", VK_F9: "\x1B[20%s~", VK_F10: "\x1B[21%s~", VK_F11: "\x1B[23%s~", VK_F12: "\x1B[24%s~", } var arrowKeyMapPrefix = map[WORD]string{ VK_UP: "%s%sA", VK_DOWN: "%s%sB", VK_RIGHT: "%s%sC", VK_LEFT: "%s%sD", } func getControlStateParameter(shift, alt, control, meta bool) string { if shift && alt && control { return KEY_CONTROL_PARAM_8 } if alt && control { return KEY_CONTROL_PARAM_7 } if shift && control { return KEY_CONTROL_PARAM_6 } if control { return KEY_CONTROL_PARAM_5 } if shift && alt { return KEY_CONTROL_PARAM_4 } if alt { return KEY_CONTROL_PARAM_3 } if shift { return KEY_CONTROL_PARAM_2 } return "" } func getControlKeys(controlState DWORD) (shift, alt, control bool) { shift = 0 != (controlState & SHIFT_PRESSED) alt = 0 != (controlState & (LEFT_ALT_PRESSED | RIGHT_ALT_PRESSED)) control = 0 != (controlState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) return shift, alt, control } func charSequenceForKeys(key WORD, controlState DWORD, escapeSequence []byte) string { i, ok := arrowKeyMapPrefix[key] if ok { shift, alt, control := getControlKeys(controlState) modifier := getControlStateParameter(shift, alt, control, false) return fmt.Sprintf(i, escapeSequence, modifier) } i, ok = keyMapPrefix[key] if ok { shift, alt, control := getControlKeys(controlState) modifier := getControlStateParameter(shift, alt, control, false) return fmt.Sprintf(i, modifier) } return "" } // mapKeystokeToTerminalString maps the given input event record to string func mapKeystokeToTerminalString(keyEvent *KEY_EVENT_RECORD, escapeSequence []byte) string { _, alt, control := getControlKeys(keyEvent.ControlKeyState) if keyEvent.UnicodeChar == 0 { return charSequenceForKeys(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) } if control { // TODO(azlinux): Implement following control sequences // -D Signals the end of input from the keyboard; also exits current shell. // -H Deletes the first character to the left of the cursor. Also called the ERASE key. // -Q Restarts printing after it has been stopped with -s. // -S Suspends printing on the screen (does not stop the program). // -U Deletes all characters on the current line. Also called the KILL key. // -E Quits current command and creates a core } // +Key generates ESC N Key if !control && alt { return KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar)) } return string(keyEvent.UnicodeChar) } // getAvailableInputEvents polls the console for availble events // The function does not return until at least one input record has been read. func getAvailableInputEvents(handle uintptr, inputEvents []INPUT_RECORD) (n int, err error) { // TODO(azlinux): Why is there a for loop? Seems to me, that `n` cannot be negative. - tibor for { // Read number of console events available n, err = readConsoleInputKey(handle, inputEvents) if err != nil || n >= 0 { return n, err } } } // getTranslatedKeyCodes converts the input events into the string of characters // The ansi escape sequence are used to map key strokes to the strings func getTranslatedKeyCodes(inputEvents []INPUT_RECORD, escapeSequence []byte) string { var buf bytes.Buffer for i := 0; i < len(inputEvents); i++ { input := inputEvents[i] if input.EventType == KEY_EVENT && input.KeyEvent.KeyDown != 0 { keyString := mapKeystokeToTerminalString(&input.KeyEvent, escapeSequence) buf.WriteString(keyString) } } return buf.String() } // ReadChars reads the characters from the given reader func (term *WindowsTerminal) ReadChars(fd uintptr, r io.Reader, p []byte) (n int, err error) { for term.inputSize == 0 { nr, err := getAvailableInputEvents(fd, term.inputEvents) if nr == 0 && nil != err { return n, err } if nr > 0 { keyCodes := getTranslatedKeyCodes(term.inputEvents[:nr], term.inputEscapeSequence) term.inputSize = copy(term.inputBuffer, keyCodes) } } n = copy(p, term.inputBuffer[:term.inputSize]) term.inputSize -= n return n, nil } // HandleInputSequence interprets the input sequence command func (term *WindowsTerminal) HandleInputSequence(fd uintptr, command []byte) (n int, err error) { return 0, nil } func marshal(c COORD) uintptr { return uintptr(*((*DWORD)(unsafe.Pointer(&c)))) } // IsConsole returns true if the given file descriptor is a terminal. // -- The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. func IsConsole(fd uintptr) bool { _, e := GetConsoleMode(fd) return e == nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/winconsole/console_windows_test.go ================================================ // +build windows package winconsole import ( "fmt" "testing" ) func helpsTestParseInt16OrDefault(t *testing.T, expectedValue int16, shouldFail bool, input string, defaultValue int16, format string, args ...string) { value, err := parseInt16OrDefault(input, defaultValue) if nil != err && !shouldFail { t.Errorf("Unexpected error returned %v", err) t.Errorf(format, args) } if nil == err && shouldFail { t.Errorf("Should have failed as expected\n\tReturned value = %d", value) t.Errorf(format, args) } if expectedValue != value { t.Errorf("The value returned does not match expected\n\tExpected:%v\n\t:Actual%v", expectedValue, value) t.Errorf(format, args) } } func TestParseInt16OrDefault(t *testing.T) { // empty string helpsTestParseInt16OrDefault(t, 0, false, "", 0, "Empty string returns default") helpsTestParseInt16OrDefault(t, 2, false, "", 2, "Empty string returns default") // normal case helpsTestParseInt16OrDefault(t, 0, false, "0", 0, "0 handled correctly") helpsTestParseInt16OrDefault(t, 111, false, "111", 2, "Normal") helpsTestParseInt16OrDefault(t, 111, false, "+111", 2, "+N") helpsTestParseInt16OrDefault(t, -111, false, "-111", 2, "-N") helpsTestParseInt16OrDefault(t, 0, false, "+0", 11, "+0") helpsTestParseInt16OrDefault(t, 0, false, "-0", 12, "-0") // ill formed strings helpsTestParseInt16OrDefault(t, 0, true, "abc", 0, "Invalid string") helpsTestParseInt16OrDefault(t, 42, true, "+= 23", 42, "Invalid string") helpsTestParseInt16OrDefault(t, 42, true, "123.45", 42, "float like") } func helpsTestGetNumberOfChars(t *testing.T, expected uint32, fromCoord COORD, toCoord COORD, screenSize COORD, format string, args ...interface{}) { actual := getNumberOfChars(fromCoord, toCoord, screenSize) mesg := fmt.Sprintf(format, args) assertTrue(t, expected == actual, fmt.Sprintf("%s Expected=%d, Actual=%d, Parameters = { fromCoord=%+v, toCoord=%+v, screenSize=%+v", mesg, expected, actual, fromCoord, toCoord, screenSize)) } func TestGetNumberOfChars(t *testing.T) { // Note: The columns and lines are 0 based // Also that interval is "inclusive" means will have both start and end chars // This test only tests the number opf characters being written // all four corners maxWindow := COORD{X: 80, Y: 50} leftTop := COORD{X: 0, Y: 0} rightTop := COORD{X: 79, Y: 0} leftBottom := COORD{X: 0, Y: 49} rightBottom := COORD{X: 79, Y: 49} // same position helpsTestGetNumberOfChars(t, 1, COORD{X: 1, Y: 14}, COORD{X: 1, Y: 14}, COORD{X: 80, Y: 50}, "Same position random line") // four corners helpsTestGetNumberOfChars(t, 1, leftTop, leftTop, maxWindow, "Same position- leftTop") helpsTestGetNumberOfChars(t, 1, rightTop, rightTop, maxWindow, "Same position- rightTop") helpsTestGetNumberOfChars(t, 1, leftBottom, leftBottom, maxWindow, "Same position- leftBottom") helpsTestGetNumberOfChars(t, 1, rightBottom, rightBottom, maxWindow, "Same position- rightBottom") // from this char to next char on same line helpsTestGetNumberOfChars(t, 2, COORD{X: 0, Y: 0}, COORD{X: 1, Y: 0}, maxWindow, "Next position on same line") helpsTestGetNumberOfChars(t, 2, COORD{X: 1, Y: 14}, COORD{X: 2, Y: 14}, maxWindow, "Next position on same line") // from this char to next 10 chars on same line helpsTestGetNumberOfChars(t, 11, COORD{X: 0, Y: 0}, COORD{X: 10, Y: 0}, maxWindow, "Next position on same line") helpsTestGetNumberOfChars(t, 11, COORD{X: 1, Y: 14}, COORD{X: 11, Y: 14}, maxWindow, "Next position on same line") helpsTestGetNumberOfChars(t, 5, COORD{X: 3, Y: 11}, COORD{X: 7, Y: 11}, maxWindow, "To and from on same line") helpsTestGetNumberOfChars(t, 8, COORD{X: 0, Y: 34}, COORD{X: 7, Y: 34}, maxWindow, "Start of line to middle") helpsTestGetNumberOfChars(t, 4, COORD{X: 76, Y: 34}, COORD{X: 79, Y: 34}, maxWindow, "Middle to end of line") // multiple lines - 1 helpsTestGetNumberOfChars(t, 81, COORD{X: 0, Y: 0}, COORD{X: 0, Y: 1}, maxWindow, "one line below same X") helpsTestGetNumberOfChars(t, 81, COORD{X: 10, Y: 10}, COORD{X: 10, Y: 11}, maxWindow, "one line below same X") // multiple lines - 2 helpsTestGetNumberOfChars(t, 161, COORD{X: 0, Y: 0}, COORD{X: 0, Y: 2}, maxWindow, "one line below same X") helpsTestGetNumberOfChars(t, 161, COORD{X: 10, Y: 10}, COORD{X: 10, Y: 12}, maxWindow, "one line below same X") // multiple lines - 3 helpsTestGetNumberOfChars(t, 241, COORD{X: 0, Y: 0}, COORD{X: 0, Y: 3}, maxWindow, "one line below same X") helpsTestGetNumberOfChars(t, 241, COORD{X: 10, Y: 10}, COORD{X: 10, Y: 13}, maxWindow, "one line below same X") // full line helpsTestGetNumberOfChars(t, 80, COORD{X: 0, Y: 0}, COORD{X: 79, Y: 0}, maxWindow, "Full line - first") helpsTestGetNumberOfChars(t, 80, COORD{X: 0, Y: 23}, COORD{X: 79, Y: 23}, maxWindow, "Full line - random") helpsTestGetNumberOfChars(t, 80, COORD{X: 0, Y: 49}, COORD{X: 79, Y: 49}, maxWindow, "Full line - last") // full screen helpsTestGetNumberOfChars(t, 80*50, leftTop, rightBottom, maxWindow, "full screen") helpsTestGetNumberOfChars(t, 80*50-1, COORD{X: 1, Y: 0}, rightBottom, maxWindow, "dropping first char to, end of screen") helpsTestGetNumberOfChars(t, 80*50-2, COORD{X: 2, Y: 0}, rightBottom, maxWindow, "dropping first two char to, end of screen") helpsTestGetNumberOfChars(t, 80*50-1, leftTop, COORD{X: 78, Y: 49}, maxWindow, "from start of screen, till last char-1") helpsTestGetNumberOfChars(t, 80*50-2, leftTop, COORD{X: 77, Y: 49}, maxWindow, "from start of screen, till last char-2") helpsTestGetNumberOfChars(t, 80*50-5, COORD{X: 4, Y: 0}, COORD{X: 78, Y: 49}, COORD{X: 80, Y: 50}, "from start of screen+4, till last char-1") helpsTestGetNumberOfChars(t, 80*50-6, COORD{X: 4, Y: 0}, COORD{X: 77, Y: 49}, COORD{X: 80, Y: 50}, "from start of screen+4, till last char-2") } var allForeground = []int16{ ANSI_FOREGROUND_BLACK, ANSI_FOREGROUND_RED, ANSI_FOREGROUND_GREEN, ANSI_FOREGROUND_YELLOW, ANSI_FOREGROUND_BLUE, ANSI_FOREGROUND_MAGENTA, ANSI_FOREGROUND_CYAN, ANSI_FOREGROUND_WHITE, ANSI_FOREGROUND_DEFAULT, } var allBackground = []int16{ ANSI_BACKGROUND_BLACK, ANSI_BACKGROUND_RED, ANSI_BACKGROUND_GREEN, ANSI_BACKGROUND_YELLOW, ANSI_BACKGROUND_BLUE, ANSI_BACKGROUND_MAGENTA, ANSI_BACKGROUND_CYAN, ANSI_BACKGROUND_WHITE, ANSI_BACKGROUND_DEFAULT, } func maskForeground(flag WORD) WORD { return flag & FOREGROUND_MASK_UNSET } func onlyForeground(flag WORD) WORD { return flag & FOREGROUND_MASK_SET } func maskBackground(flag WORD) WORD { return flag & BACKGROUND_MASK_UNSET } func onlyBackground(flag WORD) WORD { return flag & BACKGROUND_MASK_SET } func helpsTestGetWindowsTextAttributeForAnsiValue(t *testing.T, oldValue WORD /*, expected WORD*/, ansi int16, onlyMask WORD, restMask WORD) WORD { actual, err := getWindowsTextAttributeForAnsiValue(oldValue, FOREGROUND_MASK_SET, ansi) assertTrue(t, nil == err, "Should be no error") // assert that other bits are not affected if 0 != oldValue { assertTrue(t, (actual&restMask) == (oldValue&restMask), "The operation should not have affected other bits actual=%X oldValue=%X ansi=%d", actual, oldValue, ansi) } return actual } func TestBackgroundForAnsiValue(t *testing.T) { // Check that nothing else changes // background changes for _, state1 := range allBackground { for _, state2 := range allBackground { flag := WORD(0) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) } } // cummulative bcakground changes for _, state1 := range allBackground { flag := WORD(0) for _, state2 := range allBackground { flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) } } // change background after foreground for _, state1 := range allForeground { for _, state2 := range allBackground { flag := WORD(0) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) } } // change background after change cumulative for _, state1 := range allForeground { flag := WORD(0) for _, state2 := range allBackground { flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) } } } func TestForegroundForAnsiValue(t *testing.T) { // Check that nothing else changes for _, state1 := range allForeground { for _, state2 := range allForeground { flag := WORD(0) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) } } for _, state1 := range allForeground { flag := WORD(0) for _, state2 := range allForeground { flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) } } for _, state1 := range allBackground { for _, state2 := range allForeground { flag := WORD(0) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) } } for _, state1 := range allBackground { flag := WORD(0) for _, state2 := range allForeground { flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state1, BACKGROUND_MASK_SET, BACKGROUND_MASK_UNSET) flag = helpsTestGetWindowsTextAttributeForAnsiValue(t, flag, state2, FOREGROUND_MASK_SET, FOREGROUND_MASK_UNSET) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/winconsole/term_emulator.go ================================================ package winconsole import ( "fmt" "io" "strconv" "strings" ) // http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html const ( ANSI_ESCAPE_PRIMARY = 0x1B ANSI_ESCAPE_SECONDARY = 0x5B ANSI_COMMAND_FIRST = 0x40 ANSI_COMMAND_LAST = 0x7E 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 = '\\' ANSI_BEL = 0x07 KEY_EVENT = 1 ) // Interface that implements terminal handling type terminalEmulator interface { HandleOutputCommand(fd uintptr, command []byte) (n int, err error) HandleInputSequence(fd uintptr, command []byte) (n int, err error) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) ReadChars(fd uintptr, w io.Reader, p []byte) (n int, err error) } type terminalWriter struct { wrappedWriter io.Writer emulator terminalEmulator command []byte inSequence bool fd uintptr } type terminalReader struct { wrappedReader io.ReadCloser emulator terminalEmulator command []byte inSequence bool fd uintptr } // http://manpages.ubuntu.com/manpages/intrepid/man4/console_codes.4.html func isAnsiCommandChar(b byte) bool { switch { case ANSI_COMMAND_FIRST <= b && b <= ANSI_COMMAND_LAST && b != ANSI_ESCAPE_SECONDARY: return true case b == ANSI_CMD_G1 || b == ANSI_CMD_OSC || b == ANSI_CMD_DECPAM || b == ANSI_CMD_DECPNM: // non-CSI escape sequence terminator return true case b == ANSI_CMD_STR_TERM || b == ANSI_BEL: // String escape sequence terminator return true } return false } func isCharacterSelectionCmdChar(b byte) bool { return (b == ANSI_CMD_G0 || b == ANSI_CMD_G1 || b == ANSI_CMD_G2 || b == ANSI_CMD_G3) } func isXtermOscSequence(command []byte, current byte) bool { return (len(command) >= 2 && command[0] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_CMD_OSC && current != ANSI_BEL) } // Write writes len(p) bytes from p to the underlying data stream. // http://golang.org/pkg/io/#Writer func (tw *terminalWriter) Write(p []byte) (n int, err error) { if len(p) == 0 { return 0, nil } if tw.emulator == nil { return tw.wrappedWriter.Write(p) } // Emulate terminal by extracting commands and executing them totalWritten := 0 start := 0 // indicates start of the next chunk end := len(p) for current := 0; current < end; current++ { if tw.inSequence { // inside escape sequence tw.command = append(tw.command, p[current]) if isAnsiCommandChar(p[current]) { if !isXtermOscSequence(tw.command, p[current]) { // found the last command character. // Now we have a complete command. nchar, err := tw.emulator.HandleOutputCommand(tw.fd, tw.command) totalWritten += nchar if err != nil { return totalWritten, err } // clear the command // don't include current character again tw.command = tw.command[:0] start = current + 1 tw.inSequence = false } } } else { if p[current] == ANSI_ESCAPE_PRIMARY { // entering escape sequnce tw.inSequence = true // indicates end of "normal sequence", write whatever you have so far if len(p[start:current]) > 0 { nw, err := tw.emulator.WriteChars(tw.fd, tw.wrappedWriter, p[start:current]) totalWritten += nw if err != nil { return totalWritten, err } } // include the current character as part of the next sequence tw.command = append(tw.command, p[current]) } } } // note that so far, start of the escape sequence triggers writing out of bytes to console. // For the part _after_ the end of last escape sequence, it is not written out yet. So write it out if !tw.inSequence { // assumption is that we can't be inside sequence and therefore command should be empty if len(p[start:]) > 0 { nw, err := tw.emulator.WriteChars(tw.fd, tw.wrappedWriter, p[start:]) totalWritten += nw if err != nil { return totalWritten, err } } } return totalWritten, nil } // Read reads up to len(p) bytes into p. // http://golang.org/pkg/io/#Reader func (tr *terminalReader) Read(p []byte) (n int, err error) { //Implementations of Read are discouraged from returning a zero byte count // with a nil error, except when len(p) == 0. if len(p) == 0 { return 0, nil } if nil == tr.emulator { return tr.readFromWrappedReader(p) } return tr.emulator.ReadChars(tr.fd, tr.wrappedReader, p) } // Close the underlying stream func (tr *terminalReader) Close() (err error) { return tr.wrappedReader.Close() } func (tr *terminalReader) readFromWrappedReader(p []byte) (n int, err error) { return tr.wrappedReader.Read(p) } type ansiCommand struct { CommandBytes []byte Command string Parameters []string IsSpecial bool } func parseAnsiCommand(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 retValue := &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] == ANSI_ESCAPE_PRIMARY && command[1] == ANSI_ESCAPE_SECONDARY { start++ } // convert this to GetNextParam method retValue.Parameters = strings.Split(string(command[start:lastCharIndex]), ANSI_PARAMETER_SEP) } return retValue } func (c *ansiCommand) getParam(index int) string { if len(c.Parameters) > index { return c.Parameters[index] } return "" } func (ac *ansiCommand) String() string { return fmt.Sprintf("0x%v \"%v\" (\"%v\")", bytesToHex(ac.CommandBytes), ac.Command, strings.Join(ac.Parameters, "\",\"")) } 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, "") } func parseInt16OrDefault(s string, defaultValue int16) (n int16, err error) { if s == "" { return defaultValue, nil } parsedValue, err := strconv.ParseInt(s, 10, 16) if err != nil { return defaultValue, err } return int16(parsedValue), nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/term/winconsole/term_emulator_test.go ================================================ package winconsole import ( "bytes" "fmt" "io" "io/ioutil" "testing" ) const ( WRITE_OPERATION = iota COMMAND_OPERATION = iota ) var languages = []string{ "Български", "Català", "Čeština", "Ελληνικά", "Español", "Esperanto", "Euskara", "Français", "Galego", "한국어", "ქართული", "Latviešu", "Lietuvių", "Magyar", "Nederlands", "日本語", "Norsk bokmål", "Norsk nynorsk", "Polski", "Português", "Română", "Русский", "Slovenčina", "Slovenščina", "Српски", "српскохрватски", "Suomi", "Svenska", "ไทย", "Tiếng Việt", "Türkçe", "Українська", "中文", } // Mock terminal handler object type mockTerminal struct { OutputCommandSequence []terminalOperation } // Used for recording the callback data type terminalOperation struct { Operation int Data []byte Str string } func (mt *mockTerminal) record(operation int, data []byte) { op := terminalOperation{ Operation: operation, Data: make([]byte, len(data)), } copy(op.Data, data) op.Str = string(op.Data) mt.OutputCommandSequence = append(mt.OutputCommandSequence, op) } func (mt *mockTerminal) HandleOutputCommand(fd uintptr, command []byte) (n int, err error) { mt.record(COMMAND_OPERATION, command) return len(command), nil } func (mt *mockTerminal) HandleInputSequence(fd uintptr, command []byte) (n int, err error) { return 0, nil } func (mt *mockTerminal) WriteChars(fd uintptr, w io.Writer, p []byte) (n int, err error) { mt.record(WRITE_OPERATION, p) return len(p), nil } func (mt *mockTerminal) ReadChars(fd uintptr, w io.Reader, p []byte) (n int, err error) { return len(p), nil } func assertTrue(t *testing.T, cond bool, format string, args ...interface{}) { if !cond { t.Errorf(format, args...) } } // reflect.DeepEqual does not provide detailed information as to what excatly failed. func assertBytesEqual(t *testing.T, expected, actual []byte, format string, args ...interface{}) { match := true mismatchIndex := 0 if len(expected) == len(actual) { for i := 0; i < len(expected); i++ { if expected[i] != actual[i] { match = false mismatchIndex = i break } } } else { match = false t.Errorf("Lengths don't match Expected=%d Actual=%d", len(expected), len(actual)) } if !match { t.Errorf("Mismatch at index %d ", mismatchIndex) t.Errorf("\tActual String = %s", string(actual)) t.Errorf("\tExpected String = %s", string(expected)) t.Errorf("\tActual = %v", actual) t.Errorf("\tExpected = %v", expected) t.Errorf(format, args) } } // Just to make sure :) func TestAssertEqualBytes(t *testing.T) { data := []byte{9, 9, 1, 1, 1, 9, 9} assertBytesEqual(t, data, data, "Self") assertBytesEqual(t, data[1:4], data[1:4], "Self") assertBytesEqual(t, []byte{1, 1}, []byte{1, 1}, "Simple match") assertBytesEqual(t, []byte{1, 2, 3}, []byte{1, 2, 3}, "content mismatch") assertBytesEqual(t, []byte{1, 1, 1}, data[2:5], "slice match") } /* func TestAssertEqualBytesNegative(t *testing.T) { AssertBytesEqual(t, []byte{1, 1}, []byte{1}, "Length mismatch") AssertBytesEqual(t, []byte{1, 1}, []byte{1}, "Length mismatch") AssertBytesEqual(t, []byte{1, 2, 3}, []byte{1, 1, 1}, "content mismatch") }*/ // Checks that the calls received func assertHandlerOutput(t *testing.T, mock *mockTerminal, plainText string, commands ...string) { text := make([]byte, 0, 3*len(plainText)) cmdIndex := 0 for opIndex := 0; opIndex < len(mock.OutputCommandSequence); opIndex++ { op := mock.OutputCommandSequence[opIndex] if op.Operation == WRITE_OPERATION { t.Logf("\nThe data is[%d] == %s", opIndex, string(op.Data)) text = append(text[:], op.Data...) } else { assertTrue(t, mock.OutputCommandSequence[opIndex].Operation == COMMAND_OPERATION, "Operation should be command : %s", fmt.Sprintf("%+v", mock)) assertBytesEqual(t, StringToBytes(commands[cmdIndex]), mock.OutputCommandSequence[opIndex].Data, "Command data should match") cmdIndex++ } } assertBytesEqual(t, StringToBytes(plainText), text, "Command data should match %#v", mock) } func StringToBytes(str string) []byte { bytes := make([]byte, len(str)) copy(bytes[:], str) return bytes } func TestParseAnsiCommand(t *testing.T) { // Note: if the parameter does not exist then the empty value is returned c := parseAnsiCommand(StringToBytes("\x1Bm")) assertTrue(t, c.Command == "m", "Command should be m") assertTrue(t, "" == c.getParam(0), "should return empty string") assertTrue(t, "" == c.getParam(1), "should return empty string") // Escape sequence - ESC[ c = parseAnsiCommand(StringToBytes("\x1B[m")) assertTrue(t, c.Command == "m", "Command should be m") assertTrue(t, "" == c.getParam(0), "should return empty string") assertTrue(t, "" == c.getParam(1), "should return empty string") // Escape sequence With empty parameters- ESC[ c = parseAnsiCommand(StringToBytes("\x1B[;m")) assertTrue(t, c.Command == "m", "Command should be m") assertTrue(t, "" == c.getParam(0), "should return empty string") assertTrue(t, "" == c.getParam(1), "should return empty string") assertTrue(t, "" == c.getParam(2), "should return empty string") // Escape sequence With empty muliple parameters- ESC[ c = parseAnsiCommand(StringToBytes("\x1B[;;m")) assertTrue(t, c.Command == "m", "Command should be m") assertTrue(t, "" == c.getParam(0), "") assertTrue(t, "" == c.getParam(1), "") assertTrue(t, "" == c.getParam(2), "") // Escape sequence With muliple parameters- ESC[ c = parseAnsiCommand(StringToBytes("\x1B[1;2;3m")) assertTrue(t, c.Command == "m", "Command should be m") assertTrue(t, "1" == c.getParam(0), "") assertTrue(t, "2" == c.getParam(1), "") assertTrue(t, "3" == c.getParam(2), "") // Escape sequence With muliple parameters- some missing c = parseAnsiCommand(StringToBytes("\x1B[1;;3;;;6m")) assertTrue(t, c.Command == "m", "Command should be m") assertTrue(t, "1" == c.getParam(0), "") assertTrue(t, "" == c.getParam(1), "") assertTrue(t, "3" == c.getParam(2), "") assertTrue(t, "" == c.getParam(3), "") assertTrue(t, "" == c.getParam(4), "") assertTrue(t, "6" == c.getParam(5), "") } func newBufferedMockTerm() (stdOut io.Writer, stdErr io.Writer, stdIn io.ReadCloser, mock *mockTerminal) { var input bytes.Buffer var output bytes.Buffer var err bytes.Buffer mock = &mockTerminal{ OutputCommandSequence: make([]terminalOperation, 0, 256), } stdOut = &terminalWriter{ wrappedWriter: &output, emulator: mock, command: make([]byte, 0, 256), } stdErr = &terminalWriter{ wrappedWriter: &err, emulator: mock, command: make([]byte, 0, 256), } stdIn = &terminalReader{ wrappedReader: ioutil.NopCloser(&input), emulator: mock, command: make([]byte, 0, 256), } return } func TestOutputSimple(t *testing.T) { stdOut, _, _, mock := newBufferedMockTerm() stdOut.Write(StringToBytes("Hello world")) stdOut.Write(StringToBytes("\x1BmHello again")) assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, StringToBytes("Hello world"), mock.OutputCommandSequence[0].Data, "Write data should match") assertTrue(t, mock.OutputCommandSequence[1].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) assertBytesEqual(t, StringToBytes("\x1Bm"), mock.OutputCommandSequence[1].Data, "Command data should match") assertTrue(t, mock.OutputCommandSequence[2].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, StringToBytes("Hello again"), mock.OutputCommandSequence[2].Data, "Write data should match") } func TestOutputSplitCommand(t *testing.T) { stdOut, _, _, mock := newBufferedMockTerm() stdOut.Write(StringToBytes("Hello world\x1B[1;2;3")) stdOut.Write(StringToBytes("mHello again")) assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, StringToBytes("Hello world"), mock.OutputCommandSequence[0].Data, "Write data should match") assertTrue(t, mock.OutputCommandSequence[1].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) assertBytesEqual(t, StringToBytes("\x1B[1;2;3m"), mock.OutputCommandSequence[1].Data, "Command data should match") assertTrue(t, mock.OutputCommandSequence[2].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, StringToBytes("Hello again"), mock.OutputCommandSequence[2].Data, "Write data should match") } func TestOutputMultipleCommands(t *testing.T) { stdOut, _, _, mock := newBufferedMockTerm() stdOut.Write(StringToBytes("Hello world")) stdOut.Write(StringToBytes("\x1B[1;2;3m")) stdOut.Write(StringToBytes("\x1B[J")) stdOut.Write(StringToBytes("Hello again")) assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, StringToBytes("Hello world"), mock.OutputCommandSequence[0].Data, "Write data should match") assertTrue(t, mock.OutputCommandSequence[1].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) assertBytesEqual(t, StringToBytes("\x1B[1;2;3m"), mock.OutputCommandSequence[1].Data, "Command data should match") assertTrue(t, mock.OutputCommandSequence[2].Operation == COMMAND_OPERATION, "Operation should be command : %+v", mock) assertBytesEqual(t, StringToBytes("\x1B[J"), mock.OutputCommandSequence[2].Data, "Command data should match") assertTrue(t, mock.OutputCommandSequence[3].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, StringToBytes("Hello again"), mock.OutputCommandSequence[3].Data, "Write data should match") } // Splits the given data in two chunks , makes two writes and checks the split data is parsed correctly // checks output write/command is passed to handler correctly func helpsTestOutputSplitChunksAtIndex(t *testing.T, i int, data []byte) { t.Logf("\ni=%d", i) stdOut, _, _, mock := newBufferedMockTerm() t.Logf("\nWriting chunk[0] == %s", string(data[:i])) t.Logf("\nWriting chunk[1] == %s", string(data[i:])) stdOut.Write(data[:i]) stdOut.Write(data[i:]) assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, data[:i], mock.OutputCommandSequence[0].Data, "Write data should match") assertTrue(t, mock.OutputCommandSequence[1].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, data[i:], mock.OutputCommandSequence[1].Data, "Write data should match") } // Splits the given data in three chunks , makes three writes and checks the split data is parsed correctly // checks output write/command is passed to handler correctly func helpsTestOutputSplitThreeChunksAtIndex(t *testing.T, data []byte, i int, j int) { stdOut, _, _, mock := newBufferedMockTerm() t.Logf("\nWriting chunk[0] == %s", string(data[:i])) t.Logf("\nWriting chunk[1] == %s", string(data[i:j])) t.Logf("\nWriting chunk[2] == %s", string(data[j:])) stdOut.Write(data[:i]) stdOut.Write(data[i:j]) stdOut.Write(data[j:]) assertTrue(t, mock.OutputCommandSequence[0].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, data[:i], mock.OutputCommandSequence[0].Data, "Write data should match") assertTrue(t, mock.OutputCommandSequence[1].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, data[i:j], mock.OutputCommandSequence[1].Data, "Write data should match") assertTrue(t, mock.OutputCommandSequence[2].Operation == WRITE_OPERATION, "Operation should be Write : %#v", mock) assertBytesEqual(t, data[j:], mock.OutputCommandSequence[2].Data, "Write data should match") } // Splits the output into two parts and tests all such possible pairs func helpsTestOutputSplitChunks(t *testing.T, data []byte) { for i := 1; i < len(data)-1; i++ { helpsTestOutputSplitChunksAtIndex(t, i, data) } } // Splits the output in three parts and tests all such possible triples func helpsTestOutputSplitThreeChunks(t *testing.T, data []byte) { for i := 1; i < len(data)-2; i++ { for j := i + 1; j < len(data)-1; j++ { helpsTestOutputSplitThreeChunksAtIndex(t, data, i, j) } } } func helpsTestOutputSplitCommandsAtIndex(t *testing.T, data []byte, i int, plainText string, commands ...string) { t.Logf("\ni=%d", i) stdOut, _, _, mock := newBufferedMockTerm() stdOut.Write(data[:i]) stdOut.Write(data[i:]) assertHandlerOutput(t, mock, plainText, commands...) } func helpsTestOutputSplitCommands(t *testing.T, data []byte, plainText string, commands ...string) { for i := 1; i < len(data)-1; i++ { helpsTestOutputSplitCommandsAtIndex(t, data, i, plainText, commands...) } } func injectCommandAt(data string, i int, command string) string { retValue := make([]byte, len(data)+len(command)+4) retValue = append(retValue, data[:i]...) retValue = append(retValue, data[i:]...) return string(retValue) } func TestOutputSplitChunks(t *testing.T) { data := StringToBytes("qwertyuiopasdfghjklzxcvbnm") helpsTestOutputSplitChunks(t, data) helpsTestOutputSplitChunks(t, StringToBytes("BBBBB")) helpsTestOutputSplitThreeChunks(t, StringToBytes("ABCDE")) } func TestOutputSplitChunksIncludingCommands(t *testing.T) { helpsTestOutputSplitCommands(t, StringToBytes("Hello world.\x1B[mHello again."), "Hello world.Hello again.", "\x1B[m") helpsTestOutputSplitCommandsAtIndex(t, StringToBytes("Hello world.\x1B[mHello again."), 2, "Hello world.Hello again.", "\x1B[m") } func TestSplitChunkUnicode(t *testing.T) { for _, l := range languages { data := StringToBytes(l) helpsTestOutputSplitChunks(t, data) helpsTestOutputSplitThreeChunks(t, data) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/timeoutconn/timeoutconn.go ================================================ package timeoutconn import ( "net" "time" ) func New(netConn net.Conn, timeout time.Duration) net.Conn { return &conn{netConn, timeout} } // A net.Conn that sets a deadline for every Read or Write operation type conn struct { net.Conn timeout time.Duration } func (c *conn) Read(b []byte) (int, error) { if c.timeout > 0 { if err := c.Conn.SetReadDeadline(time.Now().Add(c.timeout)); err != nil { return 0, err } } return c.Conn.Read(b) } ================================================ FILE: vendor/github.com/docker/docker/pkg/timeoutconn/timeoutconn_test.go ================================================ package timeoutconn import ( "bufio" "fmt" "net" "net/http" "net/http/httptest" "testing" "time" ) func TestRead(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello") })) defer ts.Close() conn, err := net.Dial("tcp", ts.URL[7:]) if err != nil { t.Fatalf("failed to create connection to %q: %v", ts.URL, err) } tconn := New(conn, 1*time.Second) if _, err = bufio.NewReader(tconn).ReadString('\n'); err == nil { t.Fatalf("expected timeout error, got none") } if _, err := fmt.Fprintf(tconn, "GET / HTTP/1.0\r\n\r\n"); err != nil { t.Errorf("unexpected error: %v", err) } if _, err = bufio.NewReader(tconn).ReadString('\n'); err != nil { t.Errorf("unexpected error: %v", err) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/timeutils/json.go ================================================ package timeutils import ( "errors" "time" ) const ( // RFC3339NanoFixed is our own version of RFC339Nano because we want one // that pads the nano seconds part with zeros to ensure // the timestamps are aligned in the logs. RFC3339NanoFixed = "2006-01-02T15:04:05.000000000Z07:00" // JSONFormat is the format used by FastMarshalJSON JSONFormat = `"` + time.RFC3339Nano + `"` ) // FastMarshalJSON avoids one of the extra allocations that // time.MarshalJSON is making. func FastMarshalJSON(t time.Time) (string, error) { if y := t.Year(); y < 0 || y >= 10000 { // RFC 3339 is clear that years are 4 digits exactly. // See golang.org/issue/4556#c15 for more discussion. return "", errors.New("time.MarshalJSON: year outside of range [0,9999]") } return t.Format(JSONFormat), nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/timeutils/json_test.go ================================================ package timeutils import ( "testing" "time" ) // Testing to ensure 'year' fields is between 0 and 9999 func TestFastMarshalJSONWithInvalidDate(t *testing.T) { aTime := time.Date(-1, 1, 1, 0, 0, 0, 0, time.Local) json, err := FastMarshalJSON(aTime) if err == nil { t.Fatalf("FastMarshalJSON should throw an error, but was '%v'", json) } anotherTime := time.Date(10000, 1, 1, 0, 0, 0, 0, time.Local) json, err = FastMarshalJSON(anotherTime) if err == nil { t.Fatalf("FastMarshalJSON should throw an error, but was '%v'", json) } } func TestFastMarshalJSON(t *testing.T) { aTime := time.Date(2015, 5, 29, 11, 1, 2, 3, time.UTC) json, err := FastMarshalJSON(aTime) if err != nil { t.Fatal(err) } expected := "\"2015-05-29T11:01:02.000000003Z\"" if json != expected { t.Fatalf("Expected %v, got %v", expected, json) } location, err := time.LoadLocation("Europe/Paris") if err != nil { t.Fatal(err) } aTime = time.Date(2015, 5, 29, 11, 1, 2, 3, location) json, err = FastMarshalJSON(aTime) if err != nil { t.Fatal(err) } expected = "\"2015-05-29T11:01:02.000000003+02:00\"" if json != expected { t.Fatalf("Expected %v, got %v", expected, json) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/timeutils/utils.go ================================================ package timeutils import ( "strconv" "strings" "time" ) // GetTimestamp tries to parse given string as golang duration, // then RFC3339 time and finally as a Unix timestamp. If // any of these were successful, it returns a Unix timestamp // as string otherwise returns the given value back. // In case of duration input, the returned timestamp is computed // as the given reference time minus the amount of the duration. func GetTimestamp(value string, reference time.Time) string { if d, err := time.ParseDuration(value); value != "0" && err == nil { return strconv.FormatInt(reference.Add(-d).Unix(), 10) } var format string if strings.Contains(value, ".") { format = time.RFC3339Nano } else { format = time.RFC3339 } loc := time.FixedZone(time.Now().Zone()) if len(value) < len(format) { format = format[:len(value)] } t, err := time.ParseInLocation(format, value, loc) if err != nil { return value } return strconv.FormatInt(t.Unix(), 10) } ================================================ FILE: vendor/github.com/docker/docker/pkg/timeutils/utils_test.go ================================================ package timeutils import ( "fmt" "testing" "time" ) func TestGetTimestamp(t *testing.T) { now := time.Now() cases := []struct{ in, expected string }{ {"0", "-62167305600"}, // 0 gets parsed year 0 // Partial RFC3339 strings get parsed with second precision {"2006-01-02T15:04:05.999999999+07:00", "1136189045"}, {"2006-01-02T15:04:05.999999999Z", "1136214245"}, {"2006-01-02T15:04:05.999999999", "1136214245"}, {"2006-01-02T15:04:05", "1136214245"}, {"2006-01-02T15:04", "1136214240"}, {"2006-01-02T15", "1136214000"}, {"2006-01-02T", "1136160000"}, {"2006-01-02", "1136160000"}, {"2006", "1136073600"}, {"2015-05-13T20:39:09Z", "1431549549"}, // unix timestamps returned as is {"1136073600", "1136073600"}, // Durations {"1m", fmt.Sprintf("%d", now.Add(-1*time.Minute).Unix())}, {"1.5h", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix())}, {"1h30m", fmt.Sprintf("%d", now.Add(-90*time.Minute).Unix())}, // String fallback {"invalid", "invalid"}, } for _, c := range cases { o := GetTimestamp(c.in, now) if o != c.expected { t.Fatalf("wrong value for '%s'. expected:'%s' got:'%s'", c.in, c.expected, o) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/tlsconfig/config.go ================================================ // 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" "fmt" "io/ioutil" "os" "github.com/Sirupsen/logrus" ) // Options represents the information needed to create client and server TLS configurations. type Options struct { InsecureSkipVerify bool ClientAuth tls.ClientAuthType CAFile string CertFile string KeyFile 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, } // 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, } // For use 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...) // ServerDefault is a secure-enough TLS configuration for the server TLS configuration. var ServerDefault = tls.Config{ // Avoid fallback to SSL protocols < TLS1.0 MinVersion: tls.VersionTLS10, PreferServerCipherSuites: true, CipherSuites: DefaultServerAcceptedCiphers, } // ClientDefault is a secure-enough TLS configuration for the client TLS configuration. var ClientDefault = 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) (*x509.CertPool, error) { // If we should verify the server, we need to load a trusted ca certPool := x509.NewCertPool() pem, err := ioutil.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("Could not read CA certificate %s: %v", caFile, err) } if !certPool.AppendCertsFromPEM(pem) { return nil, fmt.Errorf("failed to append certificates from PEM file: %s", caFile) } s := certPool.Subjects() subjects := make([]string, len(s)) for i, subject := range s { subjects[i] = string(subject) } logrus.Debugf("Trusting certs with subjects: %v", subjects) return certPool, 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 { CAs, err := certPool(options.CAFile) if err != nil { return nil, err } tlsConfig.RootCAs = CAs } if options.CertFile != "" && options.KeyFile != "" { tlsCert, err := tls.LoadX509KeyPair(options.CertFile, options.KeyFile) if err != nil { return nil, fmt.Errorf("Could not load X509 key pair: %v. Make sure the key is not encrypted", err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} } 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 (%s, %s): %v", options.CertFile, options.KeyFile, err) } return nil, fmt.Errorf("Error reading X509 key pair (%s, %s): %v. Make sure the key is not encrypted.", options.CertFile, options.KeyFile, err) } tlsConfig.Certificates = []tls.Certificate{tlsCert} if options.ClientAuth >= tls.VerifyClientCertIfGiven { CAs, err := certPool(options.CAFile) if err != nil { return nil, err } tlsConfig.ClientCAs = CAs } return &tlsConfig, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/truncindex/truncindex.go ================================================ package truncindex import ( "errors" "fmt" "strings" "sync" "github.com/tchap/go-patricia/patricia" ) var ( ErrEmptyPrefix = errors.New("Prefix can't be empty") ErrAmbiguousPrefix = errors.New("Multiple IDs found with provided prefix") ) // TruncIndex allows the retrieval of string identifiers by any of their unique prefixes. // This is used to retrieve image and container IDs by more convenient shorthand prefixes. type TruncIndex struct { sync.RWMutex trie *patricia.Trie ids map[string]struct{} } // NewTruncIndex creates a new TruncIndex and initializes with a list of IDs func NewTruncIndex(ids []string) (idx *TruncIndex) { idx = &TruncIndex{ ids: make(map[string]struct{}), // Change patricia max prefix per node length, // because our len(ID) always 64 trie: patricia.NewTrie(patricia.MaxPrefixPerNode(64)), } for _, id := range ids { idx.addID(id) } return } func (idx *TruncIndex) addID(id string) error { if strings.Contains(id, " ") { return fmt.Errorf("illegal character: ' '") } if id == "" { return ErrEmptyPrefix } if _, exists := idx.ids[id]; exists { return fmt.Errorf("id already exists: '%s'", id) } idx.ids[id] = struct{}{} if inserted := idx.trie.Insert(patricia.Prefix(id), struct{}{}); !inserted { return fmt.Errorf("failed to insert id: %s", id) } return nil } // Add adds a new ID to the TruncIndex func (idx *TruncIndex) Add(id string) error { idx.Lock() defer idx.Unlock() if err := idx.addID(id); err != nil { return err } return nil } // Delete removes an ID from the TruncIndex. If there are multiple IDs // with the given prefix, an error is thrown. func (idx *TruncIndex) Delete(id string) error { idx.Lock() defer idx.Unlock() if _, exists := idx.ids[id]; !exists || id == "" { return fmt.Errorf("no such id: '%s'", id) } delete(idx.ids, id) if deleted := idx.trie.Delete(patricia.Prefix(id)); !deleted { return fmt.Errorf("no such id: '%s'", id) } return nil } // Get retrieves an ID from the TruncIndex. If there are multiple IDs // with the given prefix, an error is thrown. func (idx *TruncIndex) Get(s string) (string, error) { if s == "" { return "", ErrEmptyPrefix } var ( id string ) subTreeVisitFunc := func(prefix patricia.Prefix, item patricia.Item) error { if id != "" { // we haven't found the ID if there are two or more IDs id = "" return ErrAmbiguousPrefix } id = string(prefix) return nil } idx.RLock() defer idx.RUnlock() if err := idx.trie.VisitSubtree(patricia.Prefix(s), subTreeVisitFunc); err != nil { return "", err } if id != "" { return id, nil } return "", fmt.Errorf("no such id: %s", s) } // Iterates over all stored IDs, and passes each of them to the given handler func (idx *TruncIndex) Iterate(handler func(id string)) { idx.RLock() defer idx.RUnlock() idx.trie.Visit(func(prefix patricia.Prefix, item patricia.Item) error { handler(string(prefix)) return nil }) } ================================================ FILE: vendor/github.com/docker/docker/pkg/truncindex/truncindex_test.go ================================================ package truncindex import ( "math/rand" "testing" "github.com/docker/docker/pkg/stringid" ) // Test the behavior of TruncIndex, an index for querying IDs from a non-conflicting prefix. func TestTruncIndex(t *testing.T) { ids := []string{} index := NewTruncIndex(ids) // Get on an empty index if _, err := index.Get("foobar"); err == nil { t.Fatal("Get on an empty index should return an error") } // Spaces should be illegal in an id if err := index.Add("I have a space"); err == nil { t.Fatalf("Adding an id with ' ' should return an error") } id := "99b36c2c326ccc11e726eee6ee78a0baf166ef96" // Add an id if err := index.Add(id); err != nil { t.Fatal(err) } // Add an empty id (should fail) if err := index.Add(""); err == nil { t.Fatalf("Adding an empty id should return an error") } // Get a non-existing id assertIndexGet(t, index, "abracadabra", "", true) // Get an empty id assertIndexGet(t, index, "", "", true) // Get the exact id assertIndexGet(t, index, id, id, false) // The first letter should match assertIndexGet(t, index, id[:1], id, false) // The first half should match assertIndexGet(t, index, id[:len(id)/2], id, false) // The second half should NOT match assertIndexGet(t, index, id[len(id)/2:], "", true) id2 := id[:6] + "blabla" // Add an id if err := index.Add(id2); err != nil { t.Fatal(err) } // Both exact IDs should work assertIndexGet(t, index, id, id, false) assertIndexGet(t, index, id2, id2, false) // 6 characters or less should conflict assertIndexGet(t, index, id[:6], "", true) assertIndexGet(t, index, id[:4], "", true) assertIndexGet(t, index, id[:1], "", true) // An ambiguous id prefix should return an error if _, err := index.Get(id[:4]); err == nil { t.Fatal("An ambiguous id prefix should return an error") } // 7 characters should NOT conflict assertIndexGet(t, index, id[:7], id, false) assertIndexGet(t, index, id2[:7], id2, false) // Deleting a non-existing id should return an error if err := index.Delete("non-existing"); err == nil { t.Fatalf("Deleting a non-existing id should return an error") } // Deleting an empty id should return an error if err := index.Delete(""); err == nil { t.Fatal("Deleting an empty id should return an error") } // Deleting id2 should remove conflicts if err := index.Delete(id2); err != nil { t.Fatal(err) } // id2 should no longer work assertIndexGet(t, index, id2, "", true) assertIndexGet(t, index, id2[:7], "", true) assertIndexGet(t, index, id2[:11], "", true) // conflicts between id and id2 should be gone assertIndexGet(t, index, id[:6], id, false) assertIndexGet(t, index, id[:4], id, false) assertIndexGet(t, index, id[:1], id, false) // non-conflicting substrings should still not conflict assertIndexGet(t, index, id[:7], id, false) assertIndexGet(t, index, id[:15], id, false) assertIndexGet(t, index, id, id, false) assertIndexIterate(t) } func assertIndexIterate(t *testing.T) { ids := []string{ "19b36c2c326ccc11e726eee6ee78a0baf166ef96", "28b36c2c326ccc11e726eee6ee78a0baf166ef96", "37b36c2c326ccc11e726eee6ee78a0baf166ef96", "46b36c2c326ccc11e726eee6ee78a0baf166ef96", } index := NewTruncIndex(ids) index.Iterate(func(targetId string) { for _, id := range ids { if targetId == id { return } } t.Fatalf("An unknown ID '%s'", targetId) }) } func assertIndexGet(t *testing.T, index *TruncIndex, input, expectedResult string, expectError bool) { if result, err := index.Get(input); err != nil && !expectError { t.Fatalf("Unexpected error getting '%s': %s", input, err) } else if err == nil && expectError { t.Fatalf("Getting '%s' should return an error, not '%s'", input, result) } else if result != expectedResult { t.Fatalf("Getting '%s' returned '%s' instead of '%s'", input, result, expectedResult) } } func BenchmarkTruncIndexAdd100(b *testing.B) { var testSet []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexAdd250(b *testing.B) { var testSet []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexAdd500(b *testing.B) { var testSet []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexGet100(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexGet250(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexGet500(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexDelete100(b *testing.B) { var testSet []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } b.StartTimer() for _, id := range testSet { if err := index.Delete(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexDelete250(b *testing.B) { var testSet []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } b.StartTimer() for _, id := range testSet { if err := index.Delete(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexDelete500(b *testing.B) { var testSet []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } b.StartTimer() for _, id := range testSet { if err := index.Delete(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexNew100(b *testing.B) { var testSet []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { NewTruncIndex(testSet) } } func BenchmarkTruncIndexNew250(b *testing.B) { var testSet []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { NewTruncIndex(testSet) } } func BenchmarkTruncIndexNew500(b *testing.B) { var testSet []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateRandomID()) } b.ResetTimer() for i := 0; i < b.N; i++ { NewTruncIndex(testSet) } } func BenchmarkTruncIndexAddGet100(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { id := stringid.GenerateRandomID() testSet = append(testSet, id) l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexAddGet250(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { id := stringid.GenerateRandomID() testSet = append(testSet, id) l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexAddGet500(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { id := stringid.GenerateRandomID() testSet = append(testSet, id) l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/ulimit/ulimit.go ================================================ package ulimit import ( "fmt" "strconv" "strings" ) // Human friendly version of Rlimit type Ulimit struct { Name string Hard int64 Soft int64 } 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 RLIMIT_AS = 9 RLIMIT_CORE = 4 RLIMIT_CPU = 0 RLIMIT_DATA = 2 RLIMIT_FSIZE = 1 RLIMIT_LOCKS = 10 RLIMIT_MEMLOCK = 8 RLIMIT_MSGQUEUE = 12 RLIMIT_NICE = 13 RLIMIT_NOFILE = 7 RLIMIT_NPROC = 6 RLIMIT_RSS = 5 RLIMIT_RTPRIO = 14 RLIMIT_RTTIME = 15 RLIMIT_SIGPENDING = 11 RLIMIT_STACK = 3 ) var ulimitNameMapping = map[string]int{ //"as": RLIMIT_AS, // Disbaled since this doesn't seem usable with the way Docker inits a container. "core": RLIMIT_CORE, "cpu": RLIMIT_CPU, "data": RLIMIT_DATA, "fsize": RLIMIT_FSIZE, "locks": RLIMIT_LOCKS, "memlock": RLIMIT_MEMLOCK, "msgqueue": RLIMIT_MSGQUEUE, "nice": RLIMIT_NICE, "nofile": RLIMIT_NOFILE, "nproc": RLIMIT_NPROC, "rss": RLIMIT_RSS, "rtprio": RLIMIT_RTPRIO, "rttime": RLIMIT_RTTIME, "sigpending": RLIMIT_SIGPENDING, "stack": RLIMIT_STACK, } func Parse(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]) } limitVals := strings.SplitN(parts[1], ":", 2) if len(limitVals) > 2 { return nil, fmt.Errorf("too many limit value arguments - %s, can only have up to two, `soft[:hard]`", parts[1]) } soft, err := strconv.ParseInt(limitVals[0], 10, 64) if err != nil { return nil, err } hard := soft // in case no hard was set if len(limitVals) == 2 { hard, err = strconv.ParseInt(limitVals[1], 10, 64) } 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 } 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) } ================================================ FILE: vendor/github.com/docker/docker/pkg/ulimit/ulimit_test.go ================================================ package ulimit import "testing" func TestParseValid(t *testing.T) { u1 := &Ulimit{"nofile", 1024, 512} if u2, _ := Parse("nofile=512:1024"); *u1 != *u2 { t.Fatalf("expected %q, but got %q", u1, u2) } } func TestParseInvalidLimitType(t *testing.T) { if _, err := Parse("notarealtype=1024:1024"); err == nil { t.Fatalf("expected error on invalid ulimit type") } } func TestParseBadFormat(t *testing.T) { if _, err := Parse("nofile:1024:1024"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := Parse("nofile"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := Parse("nofile="); err == nil { t.Fatal("expected error on bad syntax") } if _, err := Parse("nofile=:"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := Parse("nofile=:1024"); err == nil { t.Fatal("expected error on bad syntax") } } func TestParseHardLessThanSoft(t *testing.T) { if _, err := Parse("nofile:1024:1"); err == nil { t.Fatal("expected error on hard limit less than soft limit") } } func TestParseInvalidValueType(t *testing.T) { if _, err := Parse("nofile:asdf"); err == nil { t.Fatal("expected error on bad value type") } } func TestStringOutput(t *testing.T) { u := &Ulimit{"nofile", 1024, 512} if s := u.String(); s != "nofile=512:1024" { t.Fatal("expected String to return nofile=512:1024, but got", s) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/units/duration.go ================================================ 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 < 60 { return fmt.Sprintf("%d seconds", seconds) } else if minutes := int(d.Minutes()); minutes == 1 { return "About a minute" } else if minutes < 60 { return fmt.Sprintf("%d minutes", minutes) } else if hours := int(d.Hours()); 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*3 { 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) } ================================================ FILE: vendor/github.com/docker/docker/pkg/units/duration_test.go ================================================ package units import ( "testing" "time" ) func TestHumanDuration(t *testing.T) { // Useful duration abstractions day := 24 * time.Hour week := 7 * day month := 30 * day year := 365 * day assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) assertEquals(t, "2 days", HumanDuration(2*day)) assertEquals(t, "7 days", HumanDuration(7*day)) assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) assertEquals(t, "2 weeks", HumanDuration(2*week)) assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) assertEquals(t, "3 weeks", HumanDuration(3*week)) assertEquals(t, "4 weeks", HumanDuration(4*week)) assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) assertEquals(t, "4 weeks", HumanDuration(1*month)) assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) assertEquals(t, "8 weeks", HumanDuration(2*month)) assertEquals(t, "3 months", HumanDuration(3*month+1*week)) assertEquals(t, "5 months", HumanDuration(5*month+2*week)) assertEquals(t, "13 months", HumanDuration(13*month)) assertEquals(t, "23 months", HumanDuration(23*month)) assertEquals(t, "24 months", HumanDuration(24*month)) assertEquals(t, "2 years", HumanDuration(24*month+2*week)) assertEquals(t, "3 years", HumanDuration(3*year+2*month)) } ================================================ FILE: vendor/github.com/docker/docker/pkg/units/size.go ================================================ 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+)([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"} // CustomSize returns a human-readable approximation of a size // using custom format func CustomSize(format string, size float64, base float64, _map []string) string { i := 0 for size >= base { size = size / base i++ } return fmt.Sprintf(format, size, _map[i]) } // HumanSize returns a human-readable approximation of a size // using SI standard (eg. "44kB", "17MB") func HumanSize(size float64) string { return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs) } 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) != 3 { return -1, fmt.Errorf("invalid size: '%s'", sizeStr) } size, err := strconv.ParseInt(matches[1], 10, 0) if err != nil { return -1, err } unitPrefix := strings.ToLower(matches[2]) if mul, ok := uMap[unitPrefix]; ok { size *= mul } return size, nil } ================================================ FILE: vendor/github.com/docker/docker/pkg/units/size_test.go ================================================ package units import ( "reflect" "runtime" "strings" "testing" ) func TestBytesSize(t *testing.T) { assertEquals(t, "1 KiB", BytesSize(1024)) assertEquals(t, "1 MiB", BytesSize(1024*1024)) assertEquals(t, "1 MiB", BytesSize(1048576)) assertEquals(t, "2 MiB", BytesSize(2*MiB)) assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) } func TestHumanSize(t *testing.T) { assertEquals(t, "1 kB", HumanSize(1000)) assertEquals(t, "1.024 kB", HumanSize(1024)) assertEquals(t, "1 MB", HumanSize(1000000)) assertEquals(t, "1.049 MB", HumanSize(1048576)) assertEquals(t, "2 MB", HumanSize(2*MB)) assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) } func TestFromHumanSize(t *testing.T) { assertSuccessEquals(t, 32, FromHumanSize, "32") assertSuccessEquals(t, 32, FromHumanSize, "32b") assertSuccessEquals(t, 32, FromHumanSize, "32B") assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") assertError(t, FromHumanSize, "") assertError(t, FromHumanSize, "hello") assertError(t, FromHumanSize, "-32") assertError(t, FromHumanSize, "32.3") assertError(t, FromHumanSize, " 32 ") assertError(t, FromHumanSize, "32.3Kb") assertError(t, FromHumanSize, "32 mb") assertError(t, FromHumanSize, "32m b") assertError(t, FromHumanSize, "32bm") } func TestRAMInBytes(t *testing.T) { assertSuccessEquals(t, 32, RAMInBytes, "32") assertSuccessEquals(t, 32, RAMInBytes, "32b") assertSuccessEquals(t, 32, RAMInBytes, "32B") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") assertError(t, RAMInBytes, "") assertError(t, RAMInBytes, "hello") assertError(t, RAMInBytes, "-32") assertError(t, RAMInBytes, "32.3") assertError(t, RAMInBytes, " 32 ") assertError(t, RAMInBytes, "32.3Kb") assertError(t, RAMInBytes, "32 mb") assertError(t, RAMInBytes, "32m b") assertError(t, RAMInBytes, "32bm") } func assertEquals(t *testing.T, expected, actual interface{}) { if expected != actual { t.Errorf("Expected '%v' but got '%v'", expected, actual) } } // func that maps to the parse function signatures as testing abstraction type parseFn func(string) (int64, error) // Define 'String()' for pretty-print func (fn parseFn) String() string { fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() return fnName[strings.LastIndex(fnName, ".")+1:] } func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { res, err := fn(arg) if err != nil || res != expected { t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) } } func assertError(t *testing.T, fn parseFn, arg string) { res, err := fn(arg) if err == nil && res != -1 { t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/urlutil/urlutil.go ================================================ package urlutil import ( "regexp" "strings" ) var ( validPrefixes = map[string][]string{ "url": {"http://", "https://"}, "git": {"git://", "github.com/", "git@"}, "transport": {"tcp://", "udp://", "unix://"}, } urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$") ) // IsURL returns true if the provided str is an HTTP(S) URL. func IsURL(str string) bool { return checkURL(str, "url") } // IsGitURL returns true if the provided str is a git repository URL. func IsGitURL(str string) bool { if IsURL(str) && urlPathWithFragmentSuffix.MatchString(str) { return true } return checkURL(str, "git") } // IsGitTransport returns true if the provided str is a git transport by inspecting // the prefix of the string for known protocols used in git. func IsGitTransport(str string) bool { return IsURL(str) || strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@") } // IsTransportURL returns true if the provided str is a transport (tcp, udp, unix) URL. func IsTransportURL(str string) bool { return checkURL(str, "transport") } func checkURL(str, kind string) bool { for _, prefix := range validPrefixes[kind] { if strings.HasPrefix(str, prefix) { return true } } return false } ================================================ FILE: vendor/github.com/docker/docker/pkg/urlutil/urlutil_test.go ================================================ package urlutil import "testing" var ( gitUrls = []string{ "git://github.com/docker/docker", "git@github.com:docker/docker.git", "git@bitbucket.org:atlassianlabs/atlassian-docker.git", "https://github.com/docker/docker.git", "http://github.com/docker/docker.git", "http://github.com/docker/docker.git#branch", "http://github.com/docker/docker.git#:dir", } incompleteGitUrls = []string{ "github.com/docker/docker", } invalidGitUrls = []string{ "http://github.com/docker/docker.git:#branch", } ) func TestValidGitTransport(t *testing.T) { for _, url := range gitUrls { if IsGitTransport(url) == false { t.Fatalf("%q should be detected as valid Git prefix", url) } } for _, url := range incompleteGitUrls { if IsGitTransport(url) == true { t.Fatalf("%q should not be detected as valid Git prefix", url) } } } func TestIsGIT(t *testing.T) { for _, url := range gitUrls { if IsGitURL(url) == false { t.Fatalf("%q should be detected as valid Git url", url) } } for _, url := range incompleteGitUrls { if IsGitURL(url) == false { t.Fatalf("%q should be detected as valid Git url", url) } } for _, url := range invalidGitUrls { if IsGitURL(url) == true { t.Fatalf("%q should not be detected as valid Git prefix", url) } } } ================================================ FILE: vendor/github.com/docker/docker/pkg/useragent/README.md ================================================ This package provides helper functions to pack version information into a single User-Agent header. ================================================ FILE: vendor/github.com/docker/docker/pkg/useragent/useragent.go ================================================ // Package useragent provides helper functions to pack // version information into a single User-Agent header. package useragent import ( "errors" "strings" ) var ( ErrNilRequest = errors.New("request cannot be nil") ) // VersionInfo is used to model UserAgent versions. type VersionInfo struct { Name string Version string } func (vi *VersionInfo) isValid() bool { const stopChars = " \t\r\n/" name := vi.Name vers := vi.Version if len(name) == 0 || strings.ContainsAny(name, stopChars) { return false } if len(vers) == 0 || strings.ContainsAny(vers, stopChars) { return false } return true } // Convert versions to a string and append the string to the string base. // // Each VersionInfo will be converted to a string in the format of // "product/version", where the "product" is get from the name field, while // version is get from the version field. Several pieces of verson information // will be concatinated and separated by space. // // Example: // AppendVersions("base", VersionInfo{"foo", "1.0"}, VersionInfo{"bar", "2.0"}) // results in "base foo/1.0 bar/2.0". func AppendVersions(base string, versions ...VersionInfo) string { if len(versions) == 0 { return base } verstrs := make([]string, 0, 1+len(versions)) if len(base) > 0 { verstrs = append(verstrs, base) } for _, v := range versions { if !v.isValid() { continue } verstrs = append(verstrs, v.Name+"/"+v.Version) } return strings.Join(verstrs, " ") } ================================================ FILE: vendor/github.com/docker/docker/pkg/useragent/useragent_test.go ================================================ package useragent import "testing" func TestVersionInfo(t *testing.T) { vi := VersionInfo{"foo", "bar"} if !vi.isValid() { t.Fatalf("VersionInfo should be valid") } vi = VersionInfo{"", "bar"} if vi.isValid() { t.Fatalf("Expected VersionInfo to be invalid") } vi = VersionInfo{"foo", ""} if vi.isValid() { t.Fatalf("Expected VersionInfo to be invalid") } } func TestAppendVersions(t *testing.T) { vis := []VersionInfo{ {"foo", "1.0"}, {"bar", "0.1"}, {"pi", "3.1.4"}, } v := AppendVersions("base", vis...) expect := "base foo/1.0 bar/0.1 pi/3.1.4" if v != expect { t.Fatalf("expected %q, got %q", expect, v) } } ================================================ FILE: vendor/github.com/docker/docker/pkg/version/version.go ================================================ package version import ( "strconv" "strings" ) // Version provides utility methods for comparing versions. type Version string func (v Version) compareTo(other Version) int { var ( currTab = strings.Split(string(v), ".") otherTab = strings.Split(string(other), ".") ) max := len(currTab) if len(otherTab) > max { max = len(otherTab) } for i := 0; i < max; i++ { var currInt, otherInt int if len(currTab) > i { currInt, _ = strconv.Atoi(currTab[i]) } if len(otherTab) > i { otherInt, _ = strconv.Atoi(otherTab[i]) } if currInt > otherInt { return 1 } if otherInt > currInt { return -1 } } return 0 } // LessThan checks if a version is less than another func (v Version) LessThan(other Version) bool { return v.compareTo(other) == -1 } // LessThanOrEqualTo checks if a version is less than or equal to another func (v Version) LessThanOrEqualTo(other Version) bool { return v.compareTo(other) <= 0 } // GreaterThan checks if a version is greater than another func (v Version) GreaterThan(other Version) bool { return v.compareTo(other) == 1 } // GreaterThanOrEqualTo checks if a version is greater than or equal to another func (v Version) GreaterThanOrEqualTo(other Version) bool { return v.compareTo(other) >= 0 } // Equal checks if a version is equal to another func (v Version) Equal(other Version) bool { return v.compareTo(other) == 0 } ================================================ FILE: vendor/github.com/docker/docker/pkg/version/version_test.go ================================================ package version import ( "testing" ) func assertVersion(t *testing.T, a, b string, result int) { if r := Version(a).compareTo(Version(b)); r != result { t.Fatalf("Unexpected version comparison result. Found %d, expected %d", r, result) } } func TestCompareVersion(t *testing.T) { assertVersion(t, "1.12", "1.12", 0) assertVersion(t, "1.0.0", "1", 0) assertVersion(t, "1", "1.0.0", 0) assertVersion(t, "1.05.00.0156", "1.0.221.9289", 1) assertVersion(t, "1", "1.0.1", -1) assertVersion(t, "1.0.1", "1", 1) assertVersion(t, "1.0.1", "1.0.2", -1) assertVersion(t, "1.0.2", "1.0.3", -1) assertVersion(t, "1.0.3", "1.1", -1) assertVersion(t, "1.1", "1.1.1", -1) assertVersion(t, "1.1.1", "1.1.2", -1) assertVersion(t, "1.1.2", "1.2", -1) } ================================================ FILE: vendor/github.com/docker/docker/project/GOVERNANCE.md ================================================ # Docker Governance Advisory Board Meetings In the spirit of openness, Docker created a Governance Advisory Board, and committed to make all materials and notes from the meetings of this group public. All output from the meetings should be considered proposals only, and are subject to the review and approval of the community and the project leadership. The materials from the first Docker Governance Advisory Board meeting, held on October 28, 2014, are available at [Google Docs Folder](https://goo.gl/Alfj8r) These include: * First Meeting Notes * DGAB Charter * Presentation 1: Introductory Presentation, including State of The Project * Presentation 2: Overall Contribution Structure/Docker Project Core Proposal * Presentation 3: Long Term Roadmap/Statement of Direction ================================================ FILE: vendor/github.com/docker/docker/project/IRC-ADMINISTRATION.md ================================================ # Freenode IRC Administration Guidelines and Tips This is not meant to be a general "Here's how to IRC" document, so if you're looking for that, check Google instead. ♥ If you've been charged with helping maintain one of Docker's now many IRC channels, this might turn out to be useful. If there's information that you wish you'd known about how a particular channel is organized, you should add deets here! :) ## `ChanServ` Most channel maintenance happens by talking to Freenode's `ChanServ` bot. For example, `/msg ChanServ ACCESS LIST` will show you a list of everyone with "access" privileges for a particular channel. A similar command is used to give someone a particular access level. For example, to add a new maintainer to the `#docker-maintainers` access list so that they can contribute to the discussions (after they've been merged appropriately in a `MAINTAINERS` file, of course), one would use `/msg ChanServ ACCESS #docker-maintainers ADD maintainer`. To setup a new channel with a similar `maintainer` access template, use a command like `/msg ChanServ TEMPLATE maintainer +AV` (`+A` for letting them view the `ACCESS LIST`, `+V` for auto-voice; see `/msg ChanServ HELP FLAGS` for more details). ## Troubleshooting The most common cause of not-getting-auto-`+v` woes is people not being `IDENTIFY`ed with `NickServ` (or their current nickname not being `GROUP`ed with their main nickname) -- often manifested by `ChanServ` responding to an `ACCESS ADD` request with something like `xyz is not registered.`. This is easily fixed by doing `/msg NickServ IDENTIFY OldNick SecretPassword` followed by `/msg NickServ GROUP` to group the two nicknames together. See `/msg NickServ HELP GROUP` for more information. ================================================ FILE: vendor/github.com/docker/docker/project/ISSUE-TRIAGE.md ================================================ Triaging of issues ------------------ Triage provides an important way to contribute to an open source project. Triage helps ensure issues resolve quickly by: - Describing the issue's intent and purpose is conveyed precisely. This is necessary because it can be difficult for an issue to explain how an end user experiences an problem and what actions they took. - Giving a contributor the information they need before they commit to resolving an issue. - Lowering the issue count by preventing duplicate issues. - Streamlining the development process by preventing duplicate discussions. If you don't have time to code, consider helping with triage. The community will thank you for saving them time by spending some of yours. ### Step 1: Ensure the issue contains basic information Before triaging an issue very far, make sure that the issue's author provided the standard issue information. This will help you make an educated recommendation on how this to categorize the issue. Standard information that *must* be included in most issues are things such as: - the output of `docker version` - the output of `docker info` - the output of `uname -a` - a reproducible case if this is a bug, Dockerfiles FTW - host distribution and version ( ubuntu 14.04, RHEL, fedora 21 ) - page URL if this is a docs issue or the name of a man page Depending on the issue, you might not feel all this information is needed. Use your best judgement. If you cannot triage an issue using what its author provided, explain kindly to the author that they must provide the above information to clarify the problem. If the author provides the standard information but you are still unable to triage the issue, request additional information. Do this kindly and politely because you are asking for more of the author's time. If the author does not respond requested information within the timespan of a week, close the issue with a kind note stating that the author can request for the issue to be reopened when the necessary information is provided. ### Step 2: Apply the template When triaging, use the standard template below. You should cut and place the template in the issue's description. The template helps other reviewers find key information in an issue. For example, using a template saves a potential contributor from wading though 100s of comments to find a proposed solution at the very end. When adding the template to the issue's description also add any required labels to the issue for the classification and difficulty. Here is a sample summary for an [issue](https://github.com/docker/docker/issues/10545). ``` **Summary**: docker rm can return a non-zero exit code if the container does not exist and it is not easy to parse the error message. **Proposed solution**: docker rm should have consistent exit codes for different types of errors so that the user can easily script and know the reason why the command failed. ``` ### Step 3: Classify the Issue Classifications help both to inform readers about an issue's priority and how to resolve it. This is also helpful for identifying new, critical issues. "Kinds of" are applied to the issue or pull request using labels. You can apply one or more labels. Kinds of classifications: | Kind | Description | |------------------|---------------------------------------------------------------------------------------------------------------------------------| | kind/enhancement | Enhancement are not bugs or new features but can drastically improve usability or performance of a project component. | | kind/cleanup | Refactoring code or otherwise clarifying documentation. | | kind/content | Content that is not documentation such as help or error messages. | | kind/graphics | Work involving graphics skill | | kind/regression | Regressions are usually easy fixes as hopefully the action worked previously and git history can be used to propose a solution. | | kind/bug | Bugs are bugs. The cause may or may not be known at triage time so debugging should be taken account into the time estimate. | | kind/feature | Functionality or other elements that the project does not currently support. Features are new and shinny. | | kind/question | Contains a user or contributor question requiring a response. | | kind/usecase | A description of a user or contributor situation requiring a response perhaps in code or documentation. | | kind/writing | Writing documentation, man pages, articles, blogs, or other significant word-driven task. | | kind/test | Tests or test infrastructure needs adding or updating. | Contributors can add labels by using a `+kind/bug` in an issue or pull request comment. ### Step 4: Estimate the experience level required Experience level is a way for a contributor to find an issue based on their skill set. Experience types are applied to the issue or pull request using labels. | Level | Experience level guideline | |------------------|--------------------------------------------------------------------------------------------------------------------------| | exp/beginner | You have made less than 10 contributions in your life time to any open source project. | | exp/novice | You have made more than 10 contributions to an open source project or at least 5 contributions to Docker. | | exp/proficient | You have made more than 5 contributions to Docker which amount to at least 200 code lines or 1000 documentation lines. | | exp/expert | You have made less than 20 commits to Docker which amount to 500-1000 code lines or 1000-3000 documentation lines. | | exp/master | You have made more than 20 commits to Docker and greater than 1000 code lines or 3000 documentation lines. | As the table states, these labels are meant as guidelines. You might have written a whole plugin for Docker in a personal project and never contributed to Docker. With that kind of experience, you could take on an exp/expert or exp/master level task. Contributors can add labels by using a `+exp/expert` format in issue comment. And that's it. That should be all the information required for a new or existing contributor to come in an resolve an issue. ================================================ FILE: vendor/github.com/docker/docker/project/PACKAGERS.md ================================================ # Dear Packager, If you are looking to make Docker available on your favorite software distribution, this document is for you. It summarizes the requirements for building and running the Docker client and the Docker daemon. ## Getting Started We want to help you package Docker successfully. Before doing any packaging, a good first step is to introduce yourself on the [docker-dev mailing list](https://groups.google.com/d/forum/docker-dev), explain what you're trying to achieve, and tell us how we can help. Don't worry, we don't bite! There might even be someone already working on packaging for the same distro! You can also join the IRC channel - #docker and #docker-dev on Freenode are both active and friendly. We like to refer to Tianon ("@tianon" on GitHub and "tianon" on IRC) as our "Packagers Relations", since he's always working to make sure our packagers have a good, healthy upstream to work with (both in our communication and in our build scripts). If you're having any kind of trouble, feel free to ping him directly. He also likes to keep track of what distributions we have packagers for, so feel free to reach out to him even just to say "Hi!" ## Package Name If possible, your package should be called "docker". If that name is already taken, a second choice is "lxc-docker", but with the caveat that "LXC" is now an optional dependency (as noted below). Another possible choice is "docker.io". ## Official Build vs Distro Build The Docker project maintains its own build and release toolchain. It is pretty neat and entirely based on Docker (surprise!). This toolchain is the canonical way to build Docker. We encourage you to give it a try, and if the circumstances allow you to use it, we recommend that you do. You might not be able to use the official build toolchain - usually because your distribution has a toolchain and packaging policy of its own. We get it! Your house, your rules. The rest of this document should give you the information you need to package Docker your way, without denaturing it in the process. ## Build Dependencies To build Docker, you will need the following: * A recent version of Git and Mercurial * Go version 1.4 or later * A clean checkout of the source added to a valid [Go workspace](https://golang.org/doc/code.html#Workspaces) under the path *src/github.com/docker/docker* (unless you plan to use `AUTO_GOPATH`, explained in more detail below) To build the Docker daemon, you will additionally need: * An amd64/x86_64 machine running Linux * SQLite version 3.7.9 or later * libdevmapper version 1.02.68-cvs (2012-01-26) or later from lvm2 version 2.02.89 or later * btrfs-progs version 3.16.1 or later (unless using an older version is absolutely necessary, in which case 3.8 is the minimum) Be sure to also check out Docker's Dockerfile for the most up-to-date list of these build-time dependencies. ### Go Dependencies All Go dependencies are vendored under "./vendor". They are used by the official build, so the source of truth for the current version of each dependency is whatever is in "./vendor". To use the vendored dependencies, simply make sure the path to "./vendor" is included in `GOPATH` (or use `AUTO_GOPATH`, as explained below). If you would rather (or must, due to distro policy) package these dependencies yourself, take a look at "./hack/vendor.sh" for an easy-to-parse list of the exact version for each. NOTE: if you're not able to package the exact version (to the exact commit) of a given dependency, please get in touch so we can remediate! Who knows what discrepancies can be caused by even the slightest deviation. We promise to do our best to make everybody happy. ## Stripping Binaries Please, please, please do not strip any compiled binaries. This is really important. In our own testing, stripping the resulting binaries sometimes results in a binary that appears to work, but more often causes random panics, segfaults, and other issues. Even if the binary appears to work, please don't strip. See the following quotes from Dave Cheney, which explain this position better from the upstream Golang perspective. ### [go issue #5855, comment #3](https://code.google.com/p/go/issues/detail?id=5855#c3) > Super super important: Do not strip go binaries or archives. It isn't tested, > often breaks, and doesn't work. ### [launchpad golang issue #1200255, comment #8](https://bugs.launchpad.net/ubuntu/+source/golang/+bug/1200255/comments/8) > To quote myself: "Please do not strip Go binaries, it is not supported, not > tested, is often broken, and doesn't do what you want" > > To unpack that a bit > > * not supported, as in, we don't support it, and recommend against it when > asked > * not tested, we don't test stripped binaries as part of the build CI process > * is often broken, stripping a go binary will produce anywhere from no, to > subtle, to outright execution failure, see above ### [launchpad golang issue #1200255, comment #13](https://bugs.launchpad.net/ubuntu/+source/golang/+bug/1200255/comments/13) > To clarify my previous statements. > > * I do not disagree with the debian policy, it is there for a good reason > * Having said that, it stripping Go binaries doesn't work, and nobody is > looking at making it work, so there is that. > > Thanks for patching the build formula. ## Building Docker Please use our build script ("./hack/make.sh") for all your compilation of Docker. If there's something you need that it isn't doing, or something it could be doing to make your life as a packager easier, please get in touch with Tianon and help us rectify the situation. Chances are good that other packagers have probably run into the same problems and a fix might already be in the works, but none of us will know for sure unless you harass Tianon about it. :) All the commands listed within this section should be run with the Docker source checkout as the current working directory. ### `AUTO_GOPATH` If you'd rather not be bothered with the hassles that setting up `GOPATH` appropriately can be, and prefer to just get a "build that works", you should add something similar to this to whatever script or process you're using to build Docker: ```bash export AUTO_GOPATH=1 ``` This will cause the build scripts to set up a reasonable `GOPATH` that automatically and properly includes both docker/docker from the local directory, and the local "./vendor" directory as necessary. ### `DOCKER_BUILDTAGS` If you're building a binary that may need to be used on platforms that include AppArmor, you will need to set `DOCKER_BUILDTAGS` as follows: ```bash export DOCKER_BUILDTAGS='apparmor' ``` If you're building a binary that may need to be used on platforms that include SELinux, you will need to use the `selinux` build tag: ```bash export DOCKER_BUILDTAGS='selinux' ``` There are build tags for disabling graphdrivers as well. By default, support for all graphdrivers are built in. To disable btrfs: ```bash export DOCKER_BUILDTAGS='exclude_graphdriver_btrfs' ``` To disable devicemapper: ```bash export DOCKER_BUILDTAGS='exclude_graphdriver_devicemapper' ``` To disable aufs: ```bash export DOCKER_BUILDTAGS='exclude_graphdriver_aufs' ``` NOTE: if you need to set more than one build tag, space separate them: ```bash export DOCKER_BUILDTAGS='apparmor selinux exclude_graphdriver_aufs' ``` ### Static Daemon If it is feasible within the constraints of your distribution, you should seriously consider packaging Docker as a single static binary. A good comparison is Busybox, which is often packaged statically as a feature to enable mass portability. Because of the unique way Docker operates, being similarly static is a "feature". To build a static Docker daemon binary, run the following command (first ensuring that all the necessary libraries are available in static form for linking - see the "Build Dependencies" section above, and the relevant lines within Docker's own Dockerfile that set up our official build environment): ```bash ./hack/make.sh binary ``` This will create a static binary under "./bundles/$VERSION/binary/docker-$VERSION", where "$VERSION" is the contents of the file "./VERSION". This binary is usually installed somewhere like "/usr/bin/docker". ### Dynamic Daemon / Client-only Binary If you are only interested in a Docker client binary, set `DOCKER_CLIENTONLY` to a non-empty value using something similar to the following: (which will prevent the extra step of compiling dockerinit) ```bash export DOCKER_CLIENTONLY=1 ``` If you need to (due to distro policy, distro library availability, or for other reasons) create a dynamically compiled daemon binary, or if you are only interested in creating a client binary for Docker, use something similar to the following: ```bash ./hack/make.sh dynbinary ``` This will create "./bundles/$VERSION/dynbinary/docker-$VERSION", which for client-only builds is the important file to grab and install as appropriate. For daemon builds, you will also need to grab and install "./bundles/$VERSION/dynbinary/dockerinit-$VERSION", which is created from the minimal set of Docker's codebase that _must_ be compiled statically (and is thus a pure static binary). The acceptable locations Docker will search for this file are as follows (in order): * as "dockerinit" in the same directory as the daemon binary (ie, if docker is installed at "/usr/bin/docker", then "/usr/bin/dockerinit" will be the first place this file is searched for) * "/usr/libexec/docker/dockerinit" or "/usr/local/libexec/docker/dockerinit" ([FHS 3.0 Draft](https://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec)) * "/usr/lib/docker/dockerinit" or "/usr/local/lib/docker/dockerinit" ([FHS 2.3](https://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA)) If (and please, only if) one of the paths above is insufficient due to distro policy or similar issues, you may use the `DOCKER_INITPATH` environment variable at compile-time as follows to set a different path for Docker to search: ```bash export DOCKER_INITPATH=/usr/lib/docker.io/dockerinit ``` If you find yourself needing this, please don't hesitate to reach out to Tianon to see if it would be reasonable or helpful to add more paths to Docker's list, especially if there's a relevant standard worth referencing (such as the FHS). Also, it goes without saying, but for the purposes of the daemon please consider these two binaries ("docker" and "dockerinit") as if they were a single unit. Mixing and matching can cause undesired consequences, and will fail to run properly. ## System Dependencies ### Runtime Dependencies To function properly, the Docker daemon needs the following software to be installed and available at runtime: * iptables version 1.4 or later * procps (or similar provider of a "ps" executable) * e2fsprogs version 1.4.12 or later (in use: mkfs.ext4, mkfs.xfs, tune2fs) * XZ Utils version 4.9 or later * a [properly mounted](https://github.com/tianon/cgroupfs-mount/blob/master/cgroupfs-mount) cgroupfs hierarchy (having a single, all-encompassing "cgroup" mount point [is](https://github.com/docker/docker/issues/2683) [not](https://github.com/docker/docker/issues/3485) [sufficient](https://github.com/docker/docker/issues/4568)) Additionally, the Docker client needs the following software to be installed and available at runtime: * Git version 1.7 or later ### Kernel Requirements The Docker daemon has very specific kernel requirements. Most pre-packaged kernels already include the necessary options enabled. If you are building your own kernel, you will either need to discover the options necessary via trial and error, or check out the [Gentoo ebuild](https://github.com/tianon/docker-overlay/blob/master/app-emulation/docker/docker-9999.ebuild), in which a list is maintained (and if there are any issues or discrepancies in that list, please contact Tianon so they can be rectified). Note that in client mode, there are no specific kernel requirements, and that the client will even run on alternative platforms such as Mac OS X / Darwin. ### Optional Dependencies Some of Docker's features are activated by using optional command-line flags or by having support for them in the kernel or userspace. A few examples include: * LXC execution driver (requires version 1.0.7 or later of lxc and the lxc-libs) * AUFS graph driver (requires AUFS patches/support enabled in the kernel, and at least the "auplink" utility from aufs-tools) * BTRFS graph driver (requires BTRFS support enabled in the kernel) * ZFS graph driver (requires userspace zfs-utils and a corresponding kernel module) ## Daemon Init Script Docker expects to run as a daemon at machine startup. Your package will need to include a script for your distro's process supervisor of choice. Be sure to check out the "contrib/init" folder in case a suitable init script already exists (and if one does not, contact Tianon about whether it might be appropriate for your distro's init script to live there too!). In general, Docker should be run as root, similar to the following: ```bash docker -d ``` Generally, a `DOCKER_OPTS` variable of some kind is available for adding more flags (such as changing the graph driver to use BTRFS, switching the location of "/var/lib/docker", etc). ## Communicate As a final note, please do feel free to reach out to Tianon at any time for pretty much anything. He really does love hearing from our packagers and wants to make sure we're not being a "hostile upstream". As should be a given, we appreciate the work our packagers do to make sure we have broad distribution! ================================================ FILE: vendor/github.com/docker/docker/project/PRINCIPLES.md ================================================ # Docker principles In the design and development of Docker we try to follow these principles: (Work in progress) * Don't try to replace every tool. Instead, be an ingredient to improve them. * Less code is better. * Fewer components are better. Do you really need to add one more class? * 50 lines of straightforward, readable code is better than 10 lines of magic that nobody can understand. * Don't do later what you can do now. "//FIXME: refactor" is not acceptable in new code. * When hesitating between 2 options, choose the one that is easier to reverse. * No is temporary, Yes is forever. If you're not sure about a new feature, say no. You can change your mind later. * Containers must be portable to the greatest possible number of machines. Be suspicious of any change which makes machines less interchangeable. * The less moving parts in a container, the better. * Don't merge it unless you document it. * Don't document it unless you can keep it up-to-date. * Don't merge it unless you test it! * Everyone's problem is slightly different. Focus on the part that is the same for everyone, and solve that. ================================================ FILE: vendor/github.com/docker/docker/project/README.md ================================================ # Hacking on Docker The hack/ directory holds information and tools for everyone involved in the process of creating and distributing Docker, specifically: ## Guides If you're a *contributor* or aspiring contributor, you should read CONTRIBUTORS.md. If you're a *maintainer* or aspiring maintainer, you should read MAINTAINERS.md. If you're a *packager* or aspiring packager, you should read PACKAGERS.md. If you're a maintainer in charge of a *release*, you should read RELEASE-CHECKLIST.md. ## Roadmap A high-level roadmap is available at [ROADMAP.md](../ROADMAP.md). ## Build tools make.sh is the primary build tool for docker. It is used for compiling the official binary, running the test suite, and pushing releases. ================================================ FILE: vendor/github.com/docker/docker/project/RELEASE-CHECKLIST.md ================================================ # Release Checklist ## A maintainer's guide to releasing Docker So you're in charge of a Docker release? Cool. Here's what to do. If your experience deviates from this document, please document the changes to keep it up-to-date. It is important to note that this document assumes that the git remote in your repository that corresponds to "https://github.com/docker/docker" is named "origin". If yours is not (for example, if you've chosen to name it "upstream" or something similar instead), be sure to adjust the listed snippets for your local environment accordingly. If you are not sure what your upstream remote is named, use a command like `git remote -v` to find out. If you don't have an upstream remote, you can add one easily using something like: ```bash export GITHUBUSER="YOUR_GITHUB_USER" git remote add origin https://github.com/docker/docker.git git remote add $GITHUBUSER git@github.com:$GITHUBUSER/docker.git ``` ### 1. Pull from master and create a release branch Note: Even for major releases, all of X, Y and Z in vX.Y.Z must be specified (e.g. v1.0.0). ```bash export VERSION=vX.Y.Z git fetch origin git branch -D release || true git checkout --track origin/release git checkout -b bump_$VERSION ``` If it's a regular release, we usually merge master. ```bash git merge origin/master ``` Otherwise, if it is a hotfix release, we cherry-pick only the commits we want. ```bash # get the commits ids we want to cherry-pick git log # cherry-pick the commits starting from the oldest one, without including merge commits git cherry-pick git cherry-pick ... ``` ### 2. Bump the API version on master We don't want to stop contributions to master just because we are releasing. At the same time, now that the release branch exists, we don't want API changes to go to the now frozen API version. Create a new entry in `docs/reference/api/` by copying the latest and bumping the version number (in both the file's name and content), and submit this in a PR against master. ### 3. Update CHANGELOG.md You can run this command for reference with git 2.0: ```bash git fetch --tags LAST_VERSION=$(git tag -l --sort=-version:refname "v*" | grep -E 'v[0-9\.]+$' | head -1) git log --stat $LAST_VERSION..bump_$VERSION ``` If you don't have git 2.0 but have a sort command that supports `-V`: ```bash git fetch --tags LAST_VERSION=$(git tag -l | grep -E 'v[0-9\.]+$' | sort -rV | head -1) git log --stat $LAST_VERSION..bump_$VERSION ``` If releasing a major version (X or Y increased in vX.Y.Z), simply listing notable user-facing features is sufficient. ```markdown #### Notable features since * New docker command to do something useful * Remote API change (deprecating old version) * Performance improvements in some usecases * ... ``` For minor releases (only Z increases in vX.Y.Z), provide a list of user-facing changes. Each change should be listed under a category heading formatted as `#### CATEGORY`. `CATEGORY` should describe which part of the project is affected. Valid categories are: * Builder * Documentation * Hack * Packaging * Remote API * Runtime * Other (please use this category sparingly) Each change should be formatted as `BULLET DESCRIPTION`, given: * BULLET: either `-`, `+` or `*`, to indicate a bugfix, new feature or upgrade, respectively. * DESCRIPTION: a concise description of the change that is relevant to the end-user, using the present tense. Changes should be described in terms of how they affect the user, for example "Add new feature X which allows Y", "Fix bug which caused X", "Increase performance of Y". EXAMPLES: ```markdown ## 0.3.6 (1995-12-25) #### Builder + 'docker build -t FOO .' applies the tag FOO to the newly built image #### Remote API - Fix a bug in the optional unix socket transport #### Runtime * Improve detection of kernel version ``` If you need a list of contributors between the last major release and the current bump branch, use something like: ```bash git log --format='%aN <%aE>' v0.7.0...bump_v0.8.0 | sort -uf ``` Obviously, you'll need to adjust version numbers as necessary. If you just need a count, add a simple `| wc -l`. ### 4. Change the contents of the VERSION file Before the big thing, you'll want to make successive release candidates and get people to test. The release candidate number `N` should be part of the version: ```bash export RC_VERSION=${VERSION}-rcN echo ${RC_VERSION#v} > VERSION ``` ### 5. Test the docs Make sure that your tree includes documentation for any modified or new features, syntax or semantic changes. To test locally: ```bash make docs ``` To make a shared test at https://beta-docs.docker.io: (You will need the `awsconfig` file added to the `docs/` dir) ```bash make AWS_S3_BUCKET=beta-docs.docker.io BUILD_ROOT=yes docs-release ``` ### 6. Commit and create a pull request to the "release" branch ```bash git add VERSION CHANGELOG.md git commit -m "Bump version to $VERSION" git push $GITHUBUSER bump_$VERSION echo "https://github.com/$GITHUBUSER/docker/compare/docker:release...$GITHUBUSER:bump_$VERSION?expand=1" ``` That last command will give you the proper link to visit to ensure that you open the PR against the "release" branch instead of accidentally against "master" (like so many brave souls before you already have). ### 7. Publish release candidate binaries To run this you will need access to the release credentials. Get them from the Core maintainers. Replace "..." with the respective credentials: ```bash docker build -t docker . docker run \ -e AWS_S3_BUCKET=test.docker.com \ -e AWS_ACCESS_KEY="..." \ -e AWS_SECRET_KEY="..." \ -e GPG_PASSPHRASE="..." \ -i -t --privileged \ docker \ hack/release.sh ``` It will run the test suite, build the binaries and packages, and upload to the specified bucket, so this is a good time to verify that you're running against **test**.docker.com. After the binaries and packages are uploaded to test.docker.com, make sure they get tested in both Ubuntu and Debian for any obvious installation issues or runtime issues. If everything looks good, it's time to create a git tag for this candidate: ```bash git tag -a $RC_VERSION -m $RC_VERSION bump_$VERSION git push origin $RC_VERSION ``` Announcing on multiple medias is the best way to get some help testing! An easy way to get some useful links for sharing: ```bash echo "Ubuntu/Debian: https://test.docker.com/ubuntu or curl -sSL https://test.docker.com/ | sh" echo "Linux 64bit binary: https://test.docker.com/builds/Linux/x86_64/docker-${VERSION#v}" echo "Darwin/OSX 64bit client binary: https://test.docker.com/builds/Darwin/x86_64/docker-${VERSION#v}" echo "Darwin/OSX 32bit client binary: https://test.docker.com/builds/Darwin/i386/docker-${VERSION#v}" echo "Linux 64bit tgz: https://test.docker.com/builds/Linux/x86_64/docker-${VERSION#v}.tgz" ``` We recommend announcing the release candidate on: - IRC on #docker, #docker-dev, #docker-maintainers - In a comment on the pull request to notify subscribed people on GitHub - The [docker-dev](https://groups.google.com/forum/#!forum/docker-dev) group - The [docker-maintainers](https://groups.google.com/a/dockerproject.org/forum/#!forum/maintainers) group - Any social media that can bring some attention to the release candidate ### 8. Iterate on successive release candidates Spend several days along with the community explicitly investing time and resources to try and break Docker in every possible way, documenting any findings pertinent to the release. This time should be spent testing and finding ways in which the release might have caused various features or upgrade environments to have issues, not coding. During this time, the release is in code freeze, and any additional code changes will be pushed out to the next release. It should include various levels of breaking Docker, beyond just using Docker by the book. Any issues found may still remain issues for this release, but they should be documented and give appropriate warnings. During this phase, the `bump_$VERSION` branch will keep evolving as you will produce new release candidates. The frequency of new candidates is up to the release manager: use your best judgement taking into account the severity of reported issues, testers availability, and time to scheduled release date. Each time you'll want to produce a new release candidate, you will start by adding commits to the branch, usually by cherry-picking from master: ```bash git cherry-pick -x -m0 ``` You want your "bump commit" (the one that updates the CHANGELOG and VERSION files) to remain on top, so you'll have to `git rebase -i` to bring it back up. Now that your bump commit is back on top, you will need to update the CHANGELOG file (if appropriate for this particular release candidate), and update the VERSION file to increment the RC number: ```bash export RC_VERSION=$VERSION-rcN echo $RC_VERSION > VERSION ``` You can now amend your last commit and update the bump branch: ```bash git commit --amend git push -f $GITHUBUSER bump_$VERSION ``` Repeat step 6 to tag the code, publish new binaries, announce availability, and get help testing. ### 9. Finalize the bump branch When you're happy with the quality of a release candidate, you can move on and create the real thing. You will first have to amend the "bump commit" to drop the release candidate suffix in the VERSION file: ```bash echo $VERSION > VERSION git add VERSION git commit --amend ``` You will then repeat step 6 to publish the binaries to test ### 10. Get 2 other maintainers to validate the pull request ### 11. Publish final binaries Once they're tested and reasonably believed to be working, run against get.docker.com: ```bash docker run \ -e AWS_S3_BUCKET=get.docker.com \ -e AWS_ACCESS_KEY="..." \ -e AWS_SECRET_KEY="..." \ -e GPG_PASSPHRASE="..." \ -i -t --privileged \ docker \ hack/release.sh ``` ### 12. Apply tag It's very important that we don't make the tag until after the official release is uploaded to get.docker.com! ```bash git tag -a $VERSION -m $VERSION bump_$VERSION git push origin $VERSION ``` ### 13. Go to github to merge the `bump_$VERSION` branch into release Don't forget to push that pretty blue button to delete the leftover branch afterwards! ### 14. Update the docs branch If this is a MAJOR.MINOR.0 release, you need to make an branch for the previous release's documentation: ```bash git checkout -b docs-$PREVIOUS_MAJOR_MINOR git fetch git reset --hard origin/docs git push -f origin docs-$PREVIOUS_MAJOR_MINOR ``` You will need the `awsconfig` file added to the `docs/` directory to contain the s3 credentials for the bucket you are deploying to. ```bash git checkout -b docs release || git checkout docs git fetch git reset --hard origin/release git push -f origin docs make AWS_S3_BUCKET=docs.docker.com BUILD_ROOT=yes DISTRIBUTION_ID=C2K6......FL2F docs-release ``` The docs will appear on https://docs.docker.com/ (though there may be cached versions, so its worth checking http://docs.docker.com.s3-website-us-east-1.amazonaws.com/). For more information about documentation releases, see `docs/README.md`. Note that the new docs will not appear live on the site until the cache (a complex, distributed CDN system) is flushed. The `make docs-release` command will do this _if_ the `DISTRIBUTION_ID` is set correctly - this will take at least 15 minutes to run and you can check its progress with the CDN Cloudfront Chrome addin. ### 15. Create a new pull request to merge your bump commit back into master ```bash git checkout master git fetch git reset --hard origin/master git cherry-pick $VERSION git push $GITHUBUSER merge_release_$VERSION echo "https://github.com/$GITHUBUSER/docker/compare/docker:master...$GITHUBUSER:merge_release_$VERSION?expand=1" ``` Again, get two maintainers to validate, then merge, then push that pretty blue button to delete your branch. ### 16. Update the VERSION files Now that version X.Y.Z is out, time to start working on the next! Update the content of the `VERSION` file to be the next minor (incrementing Y) and add the `-dev` suffix. For example, after 1.5.0 release, the `VERSION` file gets updated to `1.6.0-dev` (as in "1.6.0 in the making"). ### 17. Rejoice and Evangelize! Congratulations! You're done. Go forth and announce the glad tidings of the new release in `#docker`, `#docker-dev`, on the [dev mailing list](https://groups.google.com/forum/#!forum/docker-dev), the [announce mailing list](https://groups.google.com/forum/#!forum/docker-announce), and on Twitter! ================================================ FILE: vendor/github.com/docker/docker/project/REVIEWING.md ================================================ Pull request reviewing process ============================== # Labels Labels are carefully picked to optimize for: - Readability: maintainers must immediately know the state of a PR - Filtering simplicity: different labels represent many different aspects of the reviewing work, and can even be targetted at different maintainers groups. A pull request should only be attributed labels documented in this section: other labels that may exist on the repository should apply to issues. ## DCO labels * `dco/no`: automatically set by a bot when one of the commits lacks proper signature ## Status labels * `status/0-triage` * `status/1-design-review` * `status/2-code-review` * `status/3-docs-review` * `status/4-ready-to-merge` Special status labels: * `status/needs-attention`: calls for a collective discussion during a review session ## Specialty group labels Those labels are used to raise awareness of a particular specialty group, either because we need help in reviewing the PR, or because of the potential impact of the PR on their work: * `group/distribution` * `group/networking` * `group/security` * `group/windows` ## Impact labels (apply to merged pull requests) * `impact/api` * `impact/changelog` * `impact/cli` * `impact/dockerfile` * `impact/deprecation` # Workflow An opened pull request can be in 1 of 5 distinct states, for each of which there is a corresponding label that needs to be applied. ## Triage - `status/0-triage` Maintainers are expected to triage new incoming pull requests by removing the `status/0-triage` label and adding the correct labels (e.g. `status/1-design-review`) before any other interaction with the PR. The starting label may potentially skip some steps depending on the kind of pull request: use your best judgement. Maintainers should perform an initial, high-level, overview of the pull request before moving it to the next appropriate stage: - Has DCO - Contains sufficient justification (e.g., usecases) for the proposed change - References the Github issue it fixes (if any) in the commit or the first Github comment Possible transitions from this state: * Close: e.g., unresponsive contributor without DCO * `status/1-design-review`: general case * `status/2-code-review`: e.g. trivial bugfix * `status/3-docs-review`: non-proposal documentation-only change ## Design review - `status/1-design-review` Maintainers are expected to comment on the design of the pull request. Review of documentation is expected only in the context of design validation, not for stylistic changes. Ideally, documentation should reflect the expected behavior of the code. No code review should take place in this step. There are no strict rules on the way a design is validated: we usually aim for a consensus, although a single maintainer approval is often sufficient for obviously reasonable changes. In general, strong disagreement expressed by any of the maintainers should not be taken lightly. Once design is approved, a maintainer should make sure to remove this label and add the next one. Possible transitions from this state: * Close: design rejected * `status/2-code-review`: general case * `status/3-docs-review`: proposals with only documentation changes ## Code review - `status/2-code-review` Maintainers are expected to review the code and ensure that it is good quality and in accordance with the documentation in the PR. New testcases are expected to be added. Ideally, those testcases should fail when the new code is absent, and pass when present. The testcases should strive to test as many variants, code paths, as possible to ensure maximum coverage. Changes to code must be reviewed and approved (LGTM'd) by a minimum of two code maintainers. When the author of a PR is a maintainer, he still needs the approval of two other maintainers. Once code is approved according to the rules of the subsystem, a maintainer should make sure to remove this label and add the next one. If documentation is absent but expected, maintainers should ask for documentation and move to status `status/3-docs-review` for docs maintainer to follow. Possible transitions from this state: * Close * `status/1-design-review`: new design concerns are raised * `status/3-docs-review`: general case * `status/4-ready-to-merge`: change not impacting documentation ## Docs review - `status/3-docs-review` Maintainers are expected to review the documentation in its bigger context, ensuring consistency, completeness, validity, and breadth of coverage across all existing and new documentation. They should ask for any editorial change that makes the documentation more consistent and easier to understand. Changes and additions to docs must be reviewed and approved (LGTM'd) by a minimum of two docs sub-project maintainers. If the docs change originates with a docs maintainer, only one additional LGTM is required (since we assume a docs maintainer approves of their own PR). Once documentation is approved (see below), a maintainer should make sure to remove this label and add the next one. Possible transitions from this state: * Close * `status/1-design-review`: new design concerns are raised * `status/2-code-review`: requires more code changes * `status/4-ready-to-merge`: general case ## Merge - `status/4-ready-to-merge` Maintainers are expected to merge this pull request as soon as possible. They can ask for a rebase or carry the pull request themselves. Possible transitions from this state: * Merge: general case * Close: carry PR After merging a pull request, the maintainer should consider applying one or multiple impact labels to ease future classification: * `impact/api` signifies the patch impacted the remote API * `impact/changelog` signifies the change is significant enough to make it in the changelog * `impact/cli` signifies the patch impacted a CLI command * `impact/dockerfile` signifies the patch impacted the Dockerfile syntax * `impact/deprecation` signifies the patch participates in deprecating an existing feature ## Close If a pull request is closed it is expected that sufficient justification will be provided. In particular, if there are alternative ways of achieving the same net result then those needs to be spelled out. If the pull request is trying to solve a use case that is not one that we (as a community) want to support then a justification for why should be provided. The number of maintainers it takes to decide and close a PR is deliberately left unspecified. We assume that the group of maintainers is bound by mutual trust and respect, and that opposition from any single maintainer should be taken into consideration. Similarly, we expect maintainers to justify their reasoning and to accept debating. # Escalation process Despite the previously described reviewing process, some PR might not show any progress for various reasons: - No strong opinion for or against the proposed patch - Debates about the proper way to solve the problem at hand - Lack of consensus - ... All these will eventually lead to stalled PR, where no apparent progress is made across several weeks, or even months. Maintainers should use their best judgement and apply the `status/needs-attention` label. It must be used sparingly, as each PR with such label will be discussed by a group of maintainers during a review session. The goal of that session is to agree on one of the following outcomes for the PR: * Close, explaining the rationale for not pursuing further * Continue, either by pushing the PR further in the workflow, or by deciding to carry the patch (ideally, a maintainer should be immediately assigned to make sure that the PR keeps continued attention) * Escalate to Solomon by formulating a few specific questions on which his answers will allow maintainers to decide. ================================================ FILE: vendor/github.com/docker/docker/project/TOOLS.md ================================================ # Tools This page describes the tools we use and infrastructure that is in place for the Docker project. ### CI The Docker project uses [Jenkins](https://jenkins.dockerproject.org/) as our continuous integration server. Each Pull Request to Docker is tested by running the equivalent of `make all`. We chose Jenkins because we can host it ourselves and we run Docker in Docker to test. #### Leeroy Leeroy is a Go application which integrates Jenkins with GitHub pull requests. Leeroy uses [GitHub hooks](https://developer.github.com/v3/repos/hooks/) to listen for pull request notifications and starts jobs on your Jenkins server. Using the Jenkins [notification plugin][jnp], Leeroy updates the pull request using GitHub's [status API](https://developer.github.com/v3/repos/statuses/) with pending, success, failure, or error statuses. The leeroy repository is maintained at [github.com/jfrazelle/leeroy](https://github.com/jfrazelle/leeroy). #### GordonTheTurtle IRC Bot The GordonTheTurtle IRC Bot lives in the [#docker-maintainers](https://botbot.me/freenode/docker-maintainers/) channel on Freenode. He is built in Go and is based off the project at [github.com/fabioxgn/go-bot](https://github.com/fabioxgn/go-bot). His main command is `!rebuild`, which rebuilds a given Pull Request for a repository. This command works by integrating with Leroy. He has a few other commands too, such as `!gif` or `!godoc`, but we are always looking for more fun commands to add. The gordon-bot repository is maintained at [github.com/jfrazelle/gordon-bot](https://github.com/jfrazelle/gordon-bot) ### NSQ We use [NSQ](https://github.com/bitly/nsq) for various aspects of the project infrastucture. #### Hooks The hooks project, [github.com/crosbymichael/hooks](https://github.com/crosbymichael/hooks), is a small Go application that manages web hooks from github, hub.docker.com, or other third party services. It can be used for listening to github webhooks & pushing them to a queue, archiving hooks to rethinkdb for processing, and broadcasting hooks to various jobs. #### Docker Master Binaries One of the things queued from the Hooks are the building of the Master Binaries. This happens on every push to the master branch of Docker. The repository for this is maintained at [github.com/jfrazelle/docker-bb](https://github.com/jfrazelle/docker-bb). #### Docker Master Docs The master build of the docs gets queued from the Hooks as well. They are built using [github.com/jfrazelle/nsqexec](https://github.com/jfrazelle/nsqexec). #### Patch Parser Bot The bot, also named GordonTheTurtle, that labels and comments on Pull Requests listens on Hooks as well. He is capable of knowing if a Pull Request needs to be signed, or gofmt'd, as well as rebased. The repository for this is maintained at [github.com/jfrazelle/gh-patch-parser](https://github.com/jfrazelle/gh-patch-parser). ================================================ FILE: vendor/github.com/docker/docker/registry/auth.go ================================================ package registry import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "github.com/Sirupsen/logrus" "github.com/docker/docker/cliconfig" ) // Login tries to register/login to the registry server. func Login(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (string, error) { // Separates the v2 registry login logic from the v1 logic. if registryEndpoint.Version == APIVersion2 { return loginV2(authConfig, registryEndpoint, "" /* scope */) } return loginV1(authConfig, registryEndpoint) } // loginV1 tries to register/login to the v1 registry server. func loginV1(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint) (string, error) { var ( status string reqBody []byte err error reqStatusCode = 0 serverAddress = authConfig.ServerAddress ) logrus.Debugf("attempting v1 login to registry endpoint %s", registryEndpoint) if serverAddress == "" { return "", fmt.Errorf("Server Error: Server Address not set.") } loginAgainstOfficialIndex := serverAddress == INDEXSERVER // to avoid sending the server address to the server it should be removed before being marshalled authCopy := *authConfig authCopy.ServerAddress = "" jsonBody, err := json.Marshal(authCopy) if err != nil { return "", fmt.Errorf("Config Error: %s", err) } // using `bytes.NewReader(jsonBody)` here causes the server to respond with a 411 status. b := strings.NewReader(string(jsonBody)) req1, err := registryEndpoint.client.Post(serverAddress+"users/", "application/json; charset=utf-8", b) if err != nil { return "", fmt.Errorf("Server Error: %s", err) } reqStatusCode = req1.StatusCode defer req1.Body.Close() reqBody, err = ioutil.ReadAll(req1.Body) if err != nil { return "", fmt.Errorf("Server Error: [%#v] %s", reqStatusCode, err) } if reqStatusCode == 201 { if loginAgainstOfficialIndex { status = "Account created. Please use the confirmation link we sent" + " to your e-mail to activate it." } else { // *TODO: Use registry configuration to determine what this says, if anything? status = "Account created. Please see the documentation of the registry " + serverAddress + " for instructions how to activate it." } } else if reqStatusCode == 400 { if string(reqBody) == "\"Username or email already exists\"" { req, err := http.NewRequest("GET", serverAddress+"users/", nil) req.SetBasicAuth(authConfig.Username, authConfig.Password) resp, err := registryEndpoint.client.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } if resp.StatusCode == 200 { return "Login Succeeded", nil } else if resp.StatusCode == 401 { return "", fmt.Errorf("Wrong login/password, please try again") } else if resp.StatusCode == 403 { if loginAgainstOfficialIndex { return "", fmt.Errorf("Login: Account is not Active. Please check your e-mail for a confirmation link.") } // *TODO: Use registry configuration to determine what this says, if anything? return "", fmt.Errorf("Login: Account is not Active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress) } else if resp.StatusCode == 500 { // Issue #14326 logrus.Errorf("%s returned status code %d. Response Body :\n%s", req.URL.String(), resp.StatusCode, body) return "", fmt.Errorf("Internal Server Error") } return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, resp.StatusCode, resp.Header) } return "", fmt.Errorf("Registration: %s", reqBody) } else if reqStatusCode == 401 { // This case would happen with private registries where /v1/users is // protected, so people can use `docker login` as an auth check. req, err := http.NewRequest("GET", serverAddress+"users/", nil) req.SetBasicAuth(authConfig.Username, authConfig.Password) resp, err := registryEndpoint.client.Do(req) if err != nil { return "", err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return "", err } if resp.StatusCode == 200 { return "Login Succeeded", nil } else if resp.StatusCode == 401 { return "", fmt.Errorf("Wrong login/password, please try again") } else { return "", fmt.Errorf("Login: %s (Code: %d; Headers: %s)", body, resp.StatusCode, resp.Header) } } else { return "", fmt.Errorf("Unexpected status code [%d] : %s", reqStatusCode, reqBody) } return status, nil } // loginV2 tries to login to the v2 registry server. The given registry endpoint has been // pinged or setup with a list of authorization challenges. Each of these challenges are // tried until one of them succeeds. Currently supported challenge schemes are: // HTTP Basic Authorization // Token Authorization with a separate token issuing server // NOTE: the v2 logic does not attempt to create a user account if one doesn't exist. For // now, users should create their account through other means like directly from a web page // served by the v2 registry service provider. Whether this will be supported in the future // is to be determined. func loginV2(authConfig *cliconfig.AuthConfig, registryEndpoint *Endpoint, scope string) (string, error) { logrus.Debugf("attempting v2 login to registry endpoint %s", registryEndpoint) var ( err error allErrors []error ) for _, challenge := range registryEndpoint.AuthChallenges { params := make(map[string]string, len(challenge.Parameters)+1) for k, v := range challenge.Parameters { params[k] = v } params["scope"] = scope logrus.Debugf("trying %q auth challenge with params %v", challenge.Scheme, params) switch strings.ToLower(challenge.Scheme) { case "basic": err = tryV2BasicAuthLogin(authConfig, params, registryEndpoint) case "bearer": err = tryV2TokenAuthLogin(authConfig, params, registryEndpoint) default: // Unsupported challenge types are explicitly skipped. err = fmt.Errorf("unsupported auth scheme: %q", challenge.Scheme) } if err == nil { return "Login Succeeded", nil } logrus.Debugf("error trying auth challenge %q: %s", challenge.Scheme, err) allErrors = append(allErrors, err) } return "", fmt.Errorf("no successful auth challenge for %s - errors: %s", registryEndpoint, allErrors) } func tryV2BasicAuthLogin(authConfig *cliconfig.AuthConfig, params map[string]string, registryEndpoint *Endpoint) error { req, err := http.NewRequest("GET", registryEndpoint.Path(""), nil) if err != nil { return err } req.SetBasicAuth(authConfig.Username, authConfig.Password) resp, err := registryEndpoint.client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("basic auth attempt to %s realm %q failed with status: %d %s", registryEndpoint, params["realm"], resp.StatusCode, http.StatusText(resp.StatusCode)) } return nil } func tryV2TokenAuthLogin(authConfig *cliconfig.AuthConfig, params map[string]string, registryEndpoint *Endpoint) error { token, err := getToken(authConfig.Username, authConfig.Password, params, registryEndpoint) if err != nil { return err } req, err := http.NewRequest("GET", registryEndpoint.Path(""), nil) if err != nil { return err } req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) resp, err := registryEndpoint.client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("token auth attempt to %s realm %q failed with status: %d %s", registryEndpoint, params["realm"], resp.StatusCode, http.StatusText(resp.StatusCode)) } return nil } // this method matches a auth configuration to a server address or a url func ResolveAuthConfig(config *cliconfig.ConfigFile, index *IndexInfo) cliconfig.AuthConfig { configKey := index.GetAuthConfigKey() // First try the happy case if c, found := config.AuthConfigs[configKey]; found || index.Official { return c } convertToHostname := func(url string) string { stripped := url if strings.HasPrefix(url, "http://") { stripped = strings.Replace(url, "http://", "", 1) } else if strings.HasPrefix(url, "https://") { stripped = strings.Replace(url, "https://", "", 1) } nameParts := strings.SplitN(stripped, "/", 2) return nameParts[0] } // Maybe they have a legacy config file, we will iterate the keys converting // them to the new format and testing for registry, ac := range config.AuthConfigs { if configKey == convertToHostname(registry) { return ac } } // When all else fails, return an empty auth config return cliconfig.AuthConfig{} } ================================================ FILE: vendor/github.com/docker/docker/registry/auth_test.go ================================================ package registry import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/docker/docker/cliconfig" ) func TestEncodeAuth(t *testing.T) { newAuthConfig := &cliconfig.AuthConfig{Username: "ken", Password: "test", Email: "test@example.com"} authStr := cliconfig.EncodeAuth(newAuthConfig) decAuthConfig := &cliconfig.AuthConfig{} var err error decAuthConfig.Username, decAuthConfig.Password, err = cliconfig.DecodeAuth(authStr) if err != nil { t.Fatal(err) } if newAuthConfig.Username != decAuthConfig.Username { t.Fatal("Encode Username doesn't match decoded Username") } if newAuthConfig.Password != decAuthConfig.Password { t.Fatal("Encode Password doesn't match decoded Password") } if authStr != "a2VuOnRlc3Q=" { t.Fatal("AuthString encoding isn't correct.") } } func setupTempConfigFile() (*cliconfig.ConfigFile, error) { root, err := ioutil.TempDir("", "docker-test-auth") if err != nil { return nil, err } root = filepath.Join(root, cliconfig.ConfigFileName) configFile := cliconfig.NewConfigFile(root) for _, registry := range []string{"testIndex", INDEXSERVER} { configFile.AuthConfigs[registry] = cliconfig.AuthConfig{ Username: "docker-user", Password: "docker-pass", Email: "docker@docker.io", } } return configFile, nil } func TestSameAuthDataPostSave(t *testing.T) { configFile, err := setupTempConfigFile() if err != nil { t.Fatal(err) } defer os.RemoveAll(configFile.Filename()) err = configFile.Save() if err != nil { t.Fatal(err) } authConfig := configFile.AuthConfigs["testIndex"] if authConfig.Username != "docker-user" { t.Fail() } if authConfig.Password != "docker-pass" { t.Fail() } if authConfig.Email != "docker@docker.io" { t.Fail() } if authConfig.Auth != "" { t.Fail() } } func TestResolveAuthConfigIndexServer(t *testing.T) { configFile, err := setupTempConfigFile() if err != nil { t.Fatal(err) } defer os.RemoveAll(configFile.Filename()) indexConfig := configFile.AuthConfigs[INDEXSERVER] officialIndex := &IndexInfo{ Official: true, } privateIndex := &IndexInfo{ Official: false, } resolved := ResolveAuthConfig(configFile, officialIndex) assertEqual(t, resolved, indexConfig, "Expected ResolveAuthConfig to return INDEXSERVER") resolved = ResolveAuthConfig(configFile, privateIndex) assertNotEqual(t, resolved, indexConfig, "Expected ResolveAuthConfig to not return INDEXSERVER") } func TestResolveAuthConfigFullURL(t *testing.T) { configFile, err := setupTempConfigFile() if err != nil { t.Fatal(err) } defer os.RemoveAll(configFile.Filename()) registryAuth := cliconfig.AuthConfig{ Username: "foo-user", Password: "foo-pass", Email: "foo@example.com", } localAuth := cliconfig.AuthConfig{ Username: "bar-user", Password: "bar-pass", Email: "bar@example.com", } officialAuth := cliconfig.AuthConfig{ Username: "baz-user", Password: "baz-pass", Email: "baz@example.com", } configFile.AuthConfigs[INDEXSERVER] = officialAuth expectedAuths := map[string]cliconfig.AuthConfig{ "registry.example.com": registryAuth, "localhost:8000": localAuth, "registry.com": localAuth, } validRegistries := map[string][]string{ "registry.example.com": { "https://registry.example.com/v1/", "http://registry.example.com/v1/", "registry.example.com", "registry.example.com/v1/", }, "localhost:8000": { "https://localhost:8000/v1/", "http://localhost:8000/v1/", "localhost:8000", "localhost:8000/v1/", }, "registry.com": { "https://registry.com/v1/", "http://registry.com/v1/", "registry.com", "registry.com/v1/", }, } for configKey, registries := range validRegistries { configured, ok := expectedAuths[configKey] if !ok || configured.Email == "" { t.Fail() } index := &IndexInfo{ Name: configKey, } for _, registry := range registries { configFile.AuthConfigs[registry] = configured resolved := ResolveAuthConfig(configFile, index) if resolved.Email != configured.Email { t.Errorf("%s -> %q != %q\n", registry, resolved.Email, configured.Email) } delete(configFile.AuthConfigs, registry) resolved = ResolveAuthConfig(configFile, index) if resolved.Email == configured.Email { t.Errorf("%s -> %q == %q\n", registry, resolved.Email, configured.Email) } } } } ================================================ FILE: vendor/github.com/docker/docker/registry/authchallenge.go ================================================ package registry import ( "net/http" "strings" ) // Octet types from RFC 2616. type octetType byte // AuthorizationChallenge carries information // from a WWW-Authenticate response header. type AuthorizationChallenge struct { Scheme string Parameters map[string]string } var octetTypes [256]octetType const ( isToken octetType = 1 << iota isSpace ) func init() { // OCTET = // CHAR = // CTL = // CR = // LF = // SP = // HT = // <"> = // CRLF = CR LF // LWS = [CRLF] 1*( SP | HT ) // TEXT = // separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> // | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT // token = 1* // qdtext = > 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 } } func parseAuthHeader(header http.Header) []*AuthorizationChallenge { var challenges []*AuthorizationChallenge for _, h := range header[http.CanonicalHeaderKey("WWW-Authenticate")] { v, p := parseValueAndParams(h) if v != "" { challenges = append(challenges, &AuthorizationChallenge{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 + i; 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 "", "" } ================================================ FILE: vendor/github.com/docker/docker/registry/config.go ================================================ package registry import ( "encoding/json" "errors" "fmt" "net" "net/url" "strings" "github.com/docker/distribution/registry/api/v2" "github.com/docker/docker/image" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" ) // Options holds command line options. type Options struct { Mirrors opts.ListOpts InsecureRegistries opts.ListOpts } const ( DEFAULT_NAMESPACE = "docker.io" DEFAULT_V2_REGISTRY = "https://registry-1.docker.io" DEFAULT_REGISTRY_VERSION_HEADER = "Docker-Distribution-Api-Version" DEFAULT_V1_REGISTRY = "https://index.docker.io" CERTS_DIR = "/etc/docker/certs.d" // Only used for user auth + account creation REGISTRYSERVER = DEFAULT_V2_REGISTRY INDEXSERVER = DEFAULT_V1_REGISTRY + "/v1/" INDEXNAME = "docker.io" // INDEXSERVER = "https://registry-stage.hub.docker.com/v1/" ) var ( ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")") emptyServiceConfig = NewServiceConfig(nil) ) // InstallFlags adds command-line options to the top-level flag parser for // the current process. func (options *Options) InstallFlags() { options.Mirrors = opts.NewListOpts(ValidateMirror) flag.Var(&options.Mirrors, []string{"-registry-mirror"}, "Preferred Docker registry mirror") options.InsecureRegistries = opts.NewListOpts(ValidateIndexName) flag.Var(&options.InsecureRegistries, []string{"-insecure-registry"}, "Enable insecure registry communication") } type netIPNet net.IPNet func (ipnet *netIPNet) MarshalJSON() ([]byte, error) { return json.Marshal((*net.IPNet)(ipnet).String()) } func (ipnet *netIPNet) UnmarshalJSON(b []byte) (err error) { var ipnetStr string if err = json.Unmarshal(b, &ipnetStr); err == nil { var cidr *net.IPNet if _, cidr, err = net.ParseCIDR(ipnetStr); err == nil { *ipnet = netIPNet(*cidr) } } return } // ServiceConfig stores daemon registry services configuration. type ServiceConfig struct { InsecureRegistryCIDRs []*netIPNet `json:"InsecureRegistryCIDRs"` IndexConfigs map[string]*IndexInfo `json:"IndexConfigs"` Mirrors []string } // NewServiceConfig returns a new instance of ServiceConfig func NewServiceConfig(options *Options) *ServiceConfig { if options == nil { options = &Options{ Mirrors: opts.NewListOpts(nil), InsecureRegistries: opts.NewListOpts(nil), } } // Localhost is by default considered as an insecure registry // This is a stop-gap for people who are running a private registry on localhost (especially on Boot2docker). // // TODO: should we deprecate this once it is easier for people to set up a TLS registry or change // daemon flags on boot2docker? options.InsecureRegistries.Set("127.0.0.0/8") config := &ServiceConfig{ InsecureRegistryCIDRs: make([]*netIPNet, 0), IndexConfigs: make(map[string]*IndexInfo, 0), // Hack: Bypass setting the mirrors to IndexConfigs since they are going away // and Mirrors are only for the official registry anyways. Mirrors: options.Mirrors.GetAll(), } // Split --insecure-registry into CIDR and registry-specific settings. for _, r := range options.InsecureRegistries.GetAll() { // Check if CIDR was passed to --insecure-registry _, ipnet, err := net.ParseCIDR(r) if err == nil { // Valid CIDR. config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, (*netIPNet)(ipnet)) } else { // Assume `host:port` if not CIDR. config.IndexConfigs[r] = &IndexInfo{ Name: r, Mirrors: make([]string, 0), Secure: false, Official: false, } } } // Configure public registry. config.IndexConfigs[INDEXNAME] = &IndexInfo{ Name: INDEXNAME, Mirrors: config.Mirrors, Secure: true, Official: true, } return config } // isSecureIndex returns false if the provided indexName is part of the list of insecure registries // Insecure registries accept HTTP and/or accept HTTPS with certificates from unknown CAs. // // The list of insecure registries can contain an element with CIDR notation to specify a whole subnet. // If the subnet contains one of the IPs of the registry specified by indexName, the latter is considered // insecure. // // indexName should be a URL.Host (`host:port` or `host`) where the `host` part can be either a domain name // or an IP address. If it is a domain name, then it will be resolved in order to check if the IP is contained // in a subnet. If the resolving is not successful, isSecureIndex will only try to match hostname to any element // of insecureRegistries. func (config *ServiceConfig) isSecureIndex(indexName string) bool { // Check for configured index, first. This is needed in case isSecureIndex // is called from anything besides NewIndexInfo, in order to honor per-index configurations. if index, ok := config.IndexConfigs[indexName]; ok { return index.Secure } host, _, err := net.SplitHostPort(indexName) if err != nil { // assume indexName is of the form `host` without the port and go on. host = indexName } addrs, err := lookupIP(host) if err != nil { ip := net.ParseIP(host) if ip != nil { addrs = []net.IP{ip} } // if ip == nil, then `host` is neither an IP nor it could be looked up, // either because the index is unreachable, or because the index is behind an HTTP proxy. // So, len(addrs) == 0 and we're not aborting. } // Try CIDR notation only if addrs has any elements, i.e. if `host`'s IP could be determined. for _, addr := range addrs { for _, ipnet := range config.InsecureRegistryCIDRs { // check if the addr falls in the subnet if (*net.IPNet)(ipnet).Contains(addr) { return false } } } return true } // ValidateMirror validates an HTTP(S) registry mirror func ValidateMirror(val string) (string, error) { uri, err := url.Parse(val) if err != nil { return "", fmt.Errorf("%s is not a valid URI", val) } if uri.Scheme != "http" && uri.Scheme != "https" { return "", fmt.Errorf("Unsupported scheme %s", uri.Scheme) } if uri.Path != "" || uri.RawQuery != "" || uri.Fragment != "" { return "", fmt.Errorf("Unsupported path/query/fragment at end of the URI") } return fmt.Sprintf("%s://%s/", uri.Scheme, uri.Host), nil } // ValidateIndexName validates an index name. func ValidateIndexName(val string) (string, error) { // 'index.docker.io' => 'docker.io' if val == "index."+INDEXNAME { val = INDEXNAME } if strings.HasPrefix(val, "-") || strings.HasSuffix(val, "-") { return "", fmt.Errorf("Invalid index name (%s). Cannot begin or end with a hyphen.", val) } // *TODO: Check if valid hostname[:port]/ip[:port]? return val, nil } func validateRemoteName(remoteName string) error { if !strings.Contains(remoteName, "/") { // the repository name must not be a valid image ID if err := image.ValidateID(remoteName); err == nil { return fmt.Errorf("Invalid repository name (%s), cannot specify 64-byte hexadecimal strings", remoteName) } } return v2.ValidateRepositoryName(remoteName) } func validateNoSchema(reposName string) error { if strings.Contains(reposName, "://") { // It cannot contain a scheme! return ErrInvalidRepositoryName } return nil } // ValidateRepositoryName validates a repository name func ValidateRepositoryName(reposName string) error { var err error if err = validateNoSchema(reposName); err != nil { return err } indexName, remoteName := splitReposName(reposName) if _, err = ValidateIndexName(indexName); err != nil { return err } return validateRemoteName(remoteName) } // NewIndexInfo returns IndexInfo configuration from indexName func (config *ServiceConfig) NewIndexInfo(indexName string) (*IndexInfo, error) { var err error indexName, err = ValidateIndexName(indexName) if err != nil { return nil, err } // Return any configured index info, first. if index, ok := config.IndexConfigs[indexName]; ok { return index, nil } // Construct a non-configured index info. index := &IndexInfo{ Name: indexName, Mirrors: make([]string, 0), Official: false, } index.Secure = config.isSecureIndex(indexName) return index, nil } // GetAuthConfigKey special-cases using the full index address of the official // index as the AuthConfig key, and uses the (host)name[:port] for private indexes. func (index *IndexInfo) GetAuthConfigKey() string { if index.Official { return INDEXSERVER } return index.Name } // splitReposName breaks a reposName into an index name and remote name func splitReposName(reposName string) (string, string) { nameParts := strings.SplitN(reposName, "/", 2) var indexName, remoteName string if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") && !strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") { // This is a Docker Index repos (ex: samalba/hipache or ubuntu) // 'docker.io' indexName = INDEXNAME remoteName = reposName } else { indexName = nameParts[0] remoteName = nameParts[1] } return indexName, remoteName } // NewRepositoryInfo validates and breaks down a repository name into a RepositoryInfo func (config *ServiceConfig) NewRepositoryInfo(reposName string) (*RepositoryInfo, error) { if err := validateNoSchema(reposName); err != nil { return nil, err } indexName, remoteName := splitReposName(reposName) if err := validateRemoteName(remoteName); err != nil { return nil, err } repoInfo := &RepositoryInfo{ RemoteName: remoteName, } var err error repoInfo.Index, err = config.NewIndexInfo(indexName) if err != nil { return nil, err } if repoInfo.Index.Official { normalizedName := repoInfo.RemoteName if strings.HasPrefix(normalizedName, "library/") { // If pull "library/foo", it's stored locally under "foo" normalizedName = strings.SplitN(normalizedName, "/", 2)[1] } repoInfo.LocalName = normalizedName repoInfo.RemoteName = normalizedName // If the normalized name does not contain a '/' (e.g. "foo") // then it is an official repo. if strings.IndexRune(normalizedName, '/') == -1 { repoInfo.Official = true // Fix up remote name for official repos. repoInfo.RemoteName = "library/" + normalizedName } repoInfo.CanonicalName = "docker.io/" + repoInfo.RemoteName } else { repoInfo.LocalName = repoInfo.Index.Name + "/" + repoInfo.RemoteName repoInfo.CanonicalName = repoInfo.LocalName } return repoInfo, nil } // GetSearchTerm special-cases using local name for official index, and // remote name for private indexes. func (repoInfo *RepositoryInfo) GetSearchTerm() string { if repoInfo.Index.Official { return repoInfo.LocalName } return repoInfo.RemoteName } // ParseRepositoryInfo performs the breakdown of a repository name into a RepositoryInfo, but // lacks registry configuration. func ParseRepositoryInfo(reposName string) (*RepositoryInfo, error) { return emptyServiceConfig.NewRepositoryInfo(reposName) } // NormalizeLocalName transforms a repository name into a normalize LocalName // Passes through the name without transformation on error (image id, etc) func NormalizeLocalName(name string) string { repoInfo, err := ParseRepositoryInfo(name) if err != nil { return name } return repoInfo.LocalName } ================================================ FILE: vendor/github.com/docker/docker/registry/config_test.go ================================================ package registry import ( "testing" ) func TestValidateMirror(t *testing.T) { valid := []string{ "http://mirror-1.com", "https://mirror-1.com", "http://localhost", "https://localhost", "http://localhost:5000", "https://localhost:5000", "http://127.0.0.1", "https://127.0.0.1", "http://127.0.0.1:5000", "https://127.0.0.1:5000", } invalid := []string{ "!invalid!://%as%", "ftp://mirror-1.com", "http://mirror-1.com/", "http://mirror-1.com/?q=foo", "http://mirror-1.com/v1/", "http://mirror-1.com/v1/?q=foo", "http://mirror-1.com/v1/?q=foo#frag", "http://mirror-1.com?q=foo", "https://mirror-1.com#frag", "https://mirror-1.com/", "https://mirror-1.com/#frag", "https://mirror-1.com/v1/", "https://mirror-1.com/v1/#", "https://mirror-1.com?q", } for _, address := range valid { if ret, err := ValidateMirror(address); err != nil || ret == "" { t.Errorf("ValidateMirror(`"+address+"`) got %s %s", ret, err) } } for _, address := range invalid { if ret, err := ValidateMirror(address); err == nil || ret != "" { t.Errorf("ValidateMirror(`"+address+"`) got %s %s", ret, err) } } } ================================================ FILE: vendor/github.com/docker/docker/registry/endpoint.go ================================================ package registry import ( "crypto/tls" "encoding/json" "fmt" "io/ioutil" "net" "net/http" "net/url" "strings" "github.com/Sirupsen/logrus" "github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/pkg/tlsconfig" ) // for mocking in unit tests var lookupIP = net.LookupIP // scans string for api version in the URL path. returns the trimmed address, if version found, string and API version. func scanForAPIVersion(address string) (string, APIVersion) { var ( chunks []string apiVersionStr string ) if strings.HasSuffix(address, "/") { address = address[:len(address)-1] } chunks = strings.Split(address, "/") apiVersionStr = chunks[len(chunks)-1] for k, v := range apiVersions { if apiVersionStr == v { address = strings.Join(chunks[:len(chunks)-1], "/") return address, k } } return address, APIVersionUnknown } // NewEndpoint parses the given address to return a registry endpoint. func NewEndpoint(index *IndexInfo, metaHeaders http.Header) (*Endpoint, error) { // *TODO: Allow per-registry configuration of endpoints. tlsConfig := tlsconfig.ServerDefault tlsConfig.InsecureSkipVerify = !index.Secure endpoint, err := newEndpoint(index.GetAuthConfigKey(), &tlsConfig, metaHeaders) if err != nil { return nil, err } if err := validateEndpoint(endpoint); err != nil { return nil, err } return endpoint, nil } func validateEndpoint(endpoint *Endpoint) error { logrus.Debugf("pinging registry endpoint %s", endpoint) // Try HTTPS ping to registry endpoint.URL.Scheme = "https" if _, err := endpoint.Ping(); err != nil { if endpoint.IsSecure { // If registry is secure and HTTPS failed, show user the error and tell them about `--insecure-registry` // in case that's what they need. DO NOT accept unknown CA certificates, and DO NOT fallback to HTTP. return fmt.Errorf("invalid registry endpoint %s: %v. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry %s` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/%s/ca.crt", endpoint, err, endpoint.URL.Host, endpoint.URL.Host) } // If registry is insecure and HTTPS failed, fallback to HTTP. logrus.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err) endpoint.URL.Scheme = "http" var err2 error if _, err2 = endpoint.Ping(); err2 == nil { return nil } return fmt.Errorf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2) } return nil } func newEndpoint(address string, tlsConfig *tls.Config, metaHeaders http.Header) (*Endpoint, error) { var ( endpoint = new(Endpoint) trimmedAddress string err error ) if !strings.HasPrefix(address, "http") { address = "https://" + address } endpoint.IsSecure = (tlsConfig == nil || !tlsConfig.InsecureSkipVerify) trimmedAddress, endpoint.Version = scanForAPIVersion(address) if endpoint.URL, err = url.Parse(trimmedAddress); err != nil { return nil, err } // TODO(tiborvass): make sure a ConnectTimeout transport is used tr := NewTransport(tlsConfig) endpoint.client = HTTPClient(transport.NewTransport(tr, DockerHeaders(metaHeaders)...)) return endpoint, nil } func (repoInfo *RepositoryInfo) GetEndpoint(metaHeaders http.Header) (*Endpoint, error) { return NewEndpoint(repoInfo.Index, metaHeaders) } // Endpoint stores basic information about a registry endpoint. type Endpoint struct { client *http.Client URL *url.URL Version APIVersion IsSecure bool AuthChallenges []*AuthorizationChallenge URLBuilder *v2.URLBuilder } // Get the formated URL for the root of this registry Endpoint func (e *Endpoint) String() string { return fmt.Sprintf("%s/v%d/", e.URL, e.Version) } // VersionString returns a formatted string of this // endpoint address using the given API Version. func (e *Endpoint) VersionString(version APIVersion) string { return fmt.Sprintf("%s/v%d/", e.URL, version) } // Path returns a formatted string for the URL // of this endpoint with the given path appended. func (e *Endpoint) Path(path string) string { return fmt.Sprintf("%s/v%d/%s", e.URL, e.Version, path) } func (e *Endpoint) Ping() (RegistryInfo, error) { // The ping logic to use is determined by the registry endpoint version. switch e.Version { case APIVersion1: return e.pingV1() case APIVersion2: return e.pingV2() } // APIVersionUnknown // We should try v2 first... e.Version = APIVersion2 regInfo, errV2 := e.pingV2() if errV2 == nil { return regInfo, nil } // ... then fallback to v1. e.Version = APIVersion1 regInfo, errV1 := e.pingV1() if errV1 == nil { return regInfo, nil } e.Version = APIVersionUnknown return RegistryInfo{}, fmt.Errorf("unable to ping registry endpoint %s\nv2 ping attempt failed with error: %s\n v1 ping attempt failed with error: %s", e, errV2, errV1) } func (e *Endpoint) pingV1() (RegistryInfo, error) { logrus.Debugf("attempting v1 ping for registry endpoint %s", e) if e.String() == INDEXSERVER { // Skip the check, we know this one is valid // (and we never want to fallback to http in case of error) return RegistryInfo{Standalone: false}, nil } req, err := http.NewRequest("GET", e.Path("_ping"), nil) if err != nil { return RegistryInfo{Standalone: false}, err } resp, err := e.client.Do(req) if err != nil { return RegistryInfo{Standalone: false}, err } defer resp.Body.Close() jsonString, err := ioutil.ReadAll(resp.Body) if err != nil { return RegistryInfo{Standalone: false}, fmt.Errorf("error while reading the http response: %s", err) } // If the header is absent, we assume true for compatibility with earlier // versions of the registry. default to true info := RegistryInfo{ Standalone: true, } if err := json.Unmarshal(jsonString, &info); err != nil { logrus.Debugf("Error unmarshalling the _ping RegistryInfo: %s", err) // don't stop here. Just assume sane defaults } if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" { logrus.Debugf("Registry version header: '%s'", hdr) info.Version = hdr } logrus.Debugf("RegistryInfo.Version: %q", info.Version) standalone := resp.Header.Get("X-Docker-Registry-Standalone") logrus.Debugf("Registry standalone header: '%s'", standalone) // Accepted values are "true" (case-insensitive) and "1". if strings.EqualFold(standalone, "true") || standalone == "1" { info.Standalone = true } else if len(standalone) > 0 { // there is a header set, and it is not "true" or "1", so assume fails info.Standalone = false } logrus.Debugf("RegistryInfo.Standalone: %t", info.Standalone) return info, nil } func (e *Endpoint) pingV2() (RegistryInfo, error) { logrus.Debugf("attempting v2 ping for registry endpoint %s", e) req, err := http.NewRequest("GET", e.Path(""), nil) if err != nil { return RegistryInfo{}, err } resp, err := e.client.Do(req) if err != nil { return RegistryInfo{}, err } defer resp.Body.Close() // The endpoint may have multiple supported versions. // Ensure it supports the v2 Registry API. var supportsV2 bool HeaderLoop: for _, supportedVersions := range resp.Header[http.CanonicalHeaderKey("Docker-Distribution-API-Version")] { for _, versionName := range strings.Fields(supportedVersions) { if versionName == "registry/2.0" { supportsV2 = true break HeaderLoop } } } if !supportsV2 { return RegistryInfo{}, fmt.Errorf("%s does not appear to be a v2 registry endpoint", e) } if resp.StatusCode == http.StatusOK { // It would seem that no authentication/authorization is required. // So we don't need to parse/add any authorization schemes. return RegistryInfo{Standalone: true}, nil } if resp.StatusCode == http.StatusUnauthorized { // Parse the WWW-Authenticate Header and store the challenges // on this endpoint object. e.AuthChallenges = parseAuthHeader(resp.Header) return RegistryInfo{}, nil } return RegistryInfo{}, fmt.Errorf("v2 registry endpoint returned status %d: %q", resp.StatusCode, http.StatusText(resp.StatusCode)) } ================================================ FILE: vendor/github.com/docker/docker/registry/endpoint_test.go ================================================ package registry import ( "net/http" "net/http/httptest" "net/url" "testing" ) func TestEndpointParse(t *testing.T) { testData := []struct { str string expected string }{ {INDEXSERVER, INDEXSERVER}, {"http://0.0.0.0:5000/v1/", "http://0.0.0.0:5000/v1/"}, {"http://0.0.0.0:5000/v2/", "http://0.0.0.0:5000/v2/"}, {"http://0.0.0.0:5000", "http://0.0.0.0:5000/v0/"}, {"0.0.0.0:5000", "https://0.0.0.0:5000/v0/"}, } for _, td := range testData { e, err := newEndpoint(td.str, nil, nil) if err != nil { t.Errorf("%q: %s", td.str, err) } if e == nil { t.Logf("something's fishy, endpoint for %q is nil", td.str) continue } if e.String() != td.expected { t.Errorf("expected %q, got %q", td.expected, e.String()) } } } // Ensure that a registry endpoint that responds with a 401 only is determined // to be a v1 registry unless it includes a valid v2 API header. func TestValidateEndpointAmbiguousAPIVersion(t *testing.T) { requireBasicAuthHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Add("WWW-Authenticate", `Basic realm="localhost"`) w.WriteHeader(http.StatusUnauthorized) }) requireBasicAuthHandlerV2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // This mock server supports v2.0, v2.1, v42.0, and v100.0 w.Header().Add("Docker-Distribution-API-Version", "registry/100.0 registry/42.0") w.Header().Add("Docker-Distribution-API-Version", "registry/2.0 registry/2.1") requireBasicAuthHandler.ServeHTTP(w, r) }) // Make a test server which should validate as a v1 server. testServer := httptest.NewServer(requireBasicAuthHandler) defer testServer.Close() testServerURL, err := url.Parse(testServer.URL) if err != nil { t.Fatal(err) } testEndpoint := Endpoint{ URL: testServerURL, Version: APIVersionUnknown, client: HTTPClient(NewTransport(nil)), } if err = validateEndpoint(&testEndpoint); err != nil { t.Fatal(err) } if testEndpoint.Version != APIVersion1 { t.Fatalf("expected endpoint to validate to %d, got %d", APIVersion1, testEndpoint.Version) } // Make a test server which should validate as a v2 server. testServer = httptest.NewServer(requireBasicAuthHandlerV2) defer testServer.Close() testServerURL, err = url.Parse(testServer.URL) if err != nil { t.Fatal(err) } testEndpoint.URL = testServerURL testEndpoint.Version = APIVersionUnknown if err = validateEndpoint(&testEndpoint); err != nil { t.Fatal(err) } if testEndpoint.Version != APIVersion2 { t.Fatalf("expected endpoint to validate to %d, got %d", APIVersion2, testEndpoint.Version) } } ================================================ FILE: vendor/github.com/docker/docker/registry/registry.go ================================================ package registry import ( "crypto/tls" "errors" "net" "net/http" "os" "runtime" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/distribution/registry/api/errcode" "github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/tlsconfig" "github.com/docker/docker/pkg/useragent" ) var ( ErrAlreadyExists = errors.New("Image already exists") ErrDoesNotExist = errors.New("Image does not exist") errLoginRequired = errors.New("Authentication is required.") ) type TimeoutType uint32 const ( NoTimeout TimeoutType = iota ReceiveTimeout ConnectTimeout ) // dockerUserAgent is the User-Agent the Docker client uses to identify itself. // It is populated on init(), comprising version information of different components. var dockerUserAgent string func init() { httpVersion := make([]useragent.VersionInfo, 0, 6) httpVersion = append(httpVersion, useragent.VersionInfo{"docker", dockerversion.VERSION}) httpVersion = append(httpVersion, useragent.VersionInfo{"go", runtime.Version()}) httpVersion = append(httpVersion, useragent.VersionInfo{"git-commit", dockerversion.GITCOMMIT}) if kernelVersion, err := kernel.GetKernelVersion(); err == nil { httpVersion = append(httpVersion, useragent.VersionInfo{"kernel", kernelVersion.String()}) } httpVersion = append(httpVersion, useragent.VersionInfo{"os", runtime.GOOS}) httpVersion = append(httpVersion, useragent.VersionInfo{"arch", runtime.GOARCH}) dockerUserAgent = useragent.AppendVersions("", httpVersion...) } func hasFile(files []os.FileInfo, name string) bool { for _, f := range files { if f.Name() == name { return true } } return false } // DockerHeaders returns request modifiers that ensure requests have // the User-Agent header set to dockerUserAgent and that metaHeaders // are added. func DockerHeaders(metaHeaders http.Header) []transport.RequestModifier { modifiers := []transport.RequestModifier{ transport.NewHeaderRequestModifier(http.Header{"User-Agent": []string{dockerUserAgent}}), } if metaHeaders != nil { modifiers = append(modifiers, transport.NewHeaderRequestModifier(metaHeaders)) } return modifiers } func HTTPClient(transport http.RoundTripper) *http.Client { return &http.Client{ Transport: transport, CheckRedirect: AddRequiredHeadersToRedirectedRequests, } } func trustedLocation(req *http.Request) bool { var ( trusteds = []string{"docker.com", "docker.io"} hostname = strings.SplitN(req.Host, ":", 2)[0] ) if req.URL.Scheme != "https" { return false } for _, trusted := range trusteds { if hostname == trusted || strings.HasSuffix(hostname, "."+trusted) { return true } } return false } func AddRequiredHeadersToRedirectedRequests(req *http.Request, via []*http.Request) error { if via != nil && via[0] != nil { if trustedLocation(req) && trustedLocation(via[0]) { req.Header = via[0].Header return nil } for k, v := range via[0].Header { if k != "Authorization" { for _, vv := range v { req.Header.Add(k, vv) } } } } return nil } func shouldV2Fallback(err errcode.Error) bool { logrus.Debugf("v2 error: %T %v", err, err) switch err.Code { case v2.ErrorCodeUnauthorized, v2.ErrorCodeManifestUnknown: return true } return false } type ErrNoSupport struct{ Err error } func (e ErrNoSupport) Error() string { if e.Err == nil { return "not supported" } return e.Err.Error() } func ContinueOnError(err error) bool { switch v := err.(type) { case errcode.Errors: return ContinueOnError(v[0]) case ErrNoSupport: return ContinueOnError(v.Err) case errcode.Error: return shouldV2Fallback(v) } return false } func NewTransport(tlsConfig *tls.Config) *http.Transport { if tlsConfig == nil { var cfg = tlsconfig.ServerDefault tlsConfig = &cfg } return &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).Dial, TLSHandshakeTimeout: 10 * time.Second, TLSClientConfig: tlsConfig, // TODO(dmcgowan): Call close idle connections when complete and use keep alive DisableKeepAlives: true, } } ================================================ FILE: vendor/github.com/docker/docker/registry/registry_mock_test.go ================================================ package registry import ( "encoding/json" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "net/http/httptest" "net/url" "strconv" "strings" "testing" "time" "github.com/docker/docker/opts" "github.com/gorilla/mux" "github.com/Sirupsen/logrus" ) var ( testHTTPServer *httptest.Server testHTTPSServer *httptest.Server testLayers = map[string]map[string]string{ "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20": { "json": `{"id":"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", "comment":"test base image","created":"2013-03-23T12:53:11.10432-07:00", "container_config":{"Hostname":"","User":"","Memory":0,"MemorySwap":0, "CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false, "Tty":false,"OpenStdin":false,"StdinOnce":false, "Env":null,"Cmd":null,"Dns":null,"Image":"","Volumes":null, "VolumesFrom":"","Entrypoint":null},"Size":424242}`, "checksum_simple": "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37", "checksum_tarsum": "tarsum+sha256:4409a0685741ca86d38df878ed6f8cbba4c99de5dc73cd71aef04be3bb70be7c", "ancestry": `["77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20"]`, "layer": string([]byte{ 0x1f, 0x8b, 0x08, 0x08, 0x0e, 0xb0, 0xee, 0x51, 0x02, 0x03, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x2e, 0x74, 0x61, 0x72, 0x00, 0xed, 0xd2, 0x31, 0x0e, 0xc2, 0x30, 0x0c, 0x05, 0x50, 0xcf, 0x9c, 0xc2, 0x27, 0x48, 0xed, 0x38, 0x4e, 0xce, 0x13, 0x44, 0x2b, 0x66, 0x62, 0x24, 0x8e, 0x4f, 0xa0, 0x15, 0x63, 0xb6, 0x20, 0x21, 0xfc, 0x96, 0xbf, 0x78, 0xb0, 0xf5, 0x1d, 0x16, 0x98, 0x8e, 0x88, 0x8a, 0x2a, 0xbe, 0x33, 0xef, 0x49, 0x31, 0xed, 0x79, 0x40, 0x8e, 0x5c, 0x44, 0x85, 0x88, 0x33, 0x12, 0x73, 0x2c, 0x02, 0xa8, 0xf0, 0x05, 0xf7, 0x66, 0xf5, 0xd6, 0x57, 0x69, 0xd7, 0x7a, 0x19, 0xcd, 0xf5, 0xb1, 0x6d, 0x1b, 0x1f, 0xf9, 0xba, 0xe3, 0x93, 0x3f, 0x22, 0x2c, 0xb6, 0x36, 0x0b, 0xf6, 0xb0, 0xa9, 0xfd, 0xe7, 0x94, 0x46, 0xfd, 0xeb, 0xd1, 0x7f, 0x2c, 0xc4, 0xd2, 0xfb, 0x97, 0xfe, 0x02, 0x80, 0xe4, 0xfd, 0x4f, 0x77, 0xae, 0x6d, 0x3d, 0x81, 0x73, 0xce, 0xb9, 0x7f, 0xf3, 0x04, 0x41, 0xc1, 0xab, 0xc6, 0x00, 0x0a, 0x00, 0x00, }), }, "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d": { "json": `{"id":"42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", "parent":"77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", "comment":"test base image","created":"2013-03-23T12:55:11.10432-07:00", "container_config":{"Hostname":"","User":"","Memory":0,"MemorySwap":0, "CpuShares":0,"AttachStdin":false,"AttachStdout":false,"AttachStderr":false, "Tty":false,"OpenStdin":false,"StdinOnce":false, "Env":null,"Cmd":null,"Dns":null,"Image":"","Volumes":null, "VolumesFrom":"","Entrypoint":null},"Size":424242}`, "checksum_simple": "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2", "checksum_tarsum": "tarsum+sha256:68fdb56fb364f074eec2c9b3f85ca175329c4dcabc4a6a452b7272aa613a07a2", "ancestry": `["42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20"]`, "layer": string([]byte{ 0x1f, 0x8b, 0x08, 0x08, 0xbd, 0xb3, 0xee, 0x51, 0x02, 0x03, 0x6c, 0x61, 0x79, 0x65, 0x72, 0x2e, 0x74, 0x61, 0x72, 0x00, 0xed, 0xd1, 0x31, 0x0e, 0xc2, 0x30, 0x0c, 0x05, 0x50, 0xcf, 0x9c, 0xc2, 0x27, 0x48, 0x9d, 0x38, 0x8e, 0xcf, 0x53, 0x51, 0xaa, 0x56, 0xea, 0x44, 0x82, 0xc4, 0xf1, 0x09, 0xb4, 0xea, 0x98, 0x2d, 0x48, 0x08, 0xbf, 0xe5, 0x2f, 0x1e, 0xfc, 0xf5, 0xdd, 0x00, 0xdd, 0x11, 0x91, 0x8a, 0xe0, 0x27, 0xd3, 0x9e, 0x14, 0xe2, 0x9e, 0x07, 0xf4, 0xc1, 0x2b, 0x0b, 0xfb, 0xa4, 0x82, 0xe4, 0x3d, 0x93, 0x02, 0x0a, 0x7c, 0xc1, 0x23, 0x97, 0xf1, 0x5e, 0x5f, 0xc9, 0xcb, 0x38, 0xb5, 0xee, 0xea, 0xd9, 0x3c, 0xb7, 0x4b, 0xbe, 0x7b, 0x9c, 0xf9, 0x23, 0xdc, 0x50, 0x6e, 0xb9, 0xb8, 0xf2, 0x2c, 0x5d, 0xf7, 0x4f, 0x31, 0xb6, 0xf6, 0x4f, 0xc7, 0xfe, 0x41, 0x55, 0x63, 0xdd, 0x9f, 0x89, 0x09, 0x90, 0x6c, 0xff, 0xee, 0xae, 0xcb, 0xba, 0x4d, 0x17, 0x30, 0xc6, 0x18, 0xf3, 0x67, 0x5e, 0xc1, 0xed, 0x21, 0x5d, 0x00, 0x0a, 0x00, 0x00, }), }, } testRepositories = map[string]map[string]string{ "foo42/bar": { "latest": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", "test": "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", }, } mockHosts = map[string][]net.IP{ "": {net.ParseIP("0.0.0.0")}, "localhost": {net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, "example.com": {net.ParseIP("42.42.42.42")}, "other.com": {net.ParseIP("43.43.43.43")}, } ) func init() { r := mux.NewRouter() // /v1/ r.HandleFunc("/v1/_ping", handlerGetPing).Methods("GET") r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|ancestry}", handlerGetImage).Methods("GET") r.HandleFunc("/v1/images/{image_id:[^/]+}/{action:json|layer|checksum}", handlerPutImage).Methods("PUT") r.HandleFunc("/v1/repositories/{repository:.+}/tags", handlerGetDeleteTags).Methods("GET", "DELETE") r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerGetTag).Methods("GET") r.HandleFunc("/v1/repositories/{repository:.+}/tags/{tag:.+}", handlerPutTag).Methods("PUT") r.HandleFunc("/v1/users{null:.*}", handlerUsers).Methods("GET", "POST", "PUT") r.HandleFunc("/v1/repositories/{repository:.+}{action:/images|/}", handlerImages).Methods("GET", "PUT", "DELETE") r.HandleFunc("/v1/repositories/{repository:.+}/auth", handlerAuth).Methods("PUT") r.HandleFunc("/v1/search", handlerSearch).Methods("GET") // /v2/ r.HandleFunc("/v2/version", handlerGetPing).Methods("GET") testHTTPServer = httptest.NewServer(handlerAccessLog(r)) testHTTPSServer = httptest.NewTLSServer(handlerAccessLog(r)) // override net.LookupIP lookupIP = func(host string) ([]net.IP, error) { if host == "127.0.0.1" { // I believe in future Go versions this will fail, so let's fix it later return net.LookupIP(host) } for h, addrs := range mockHosts { if host == h { return addrs, nil } for _, addr := range addrs { if addr.String() == host { return []net.IP{addr}, nil } } } return nil, errors.New("lookup: no such host") } } func handlerAccessLog(handler http.Handler) http.Handler { logHandler := func(w http.ResponseWriter, r *http.Request) { logrus.Debugf("%s \"%s %s\"", r.RemoteAddr, r.Method, r.URL) handler.ServeHTTP(w, r) } return http.HandlerFunc(logHandler) } func makeURL(req string) string { return testHTTPServer.URL + req } func makeHttpsURL(req string) string { return testHTTPSServer.URL + req } func makeIndex(req string) *IndexInfo { index := &IndexInfo{ Name: makeURL(req), } return index } func makeHttpsIndex(req string) *IndexInfo { index := &IndexInfo{ Name: makeHttpsURL(req), } return index } func makePublicIndex() *IndexInfo { index := &IndexInfo{ Name: INDEXSERVER, Secure: true, Official: true, } return index } func makeServiceConfig(mirrors []string, insecureRegistries []string) *ServiceConfig { options := &Options{ Mirrors: opts.NewListOpts(nil), InsecureRegistries: opts.NewListOpts(nil), } if mirrors != nil { for _, mirror := range mirrors { options.Mirrors.Set(mirror) } } if insecureRegistries != nil { for _, insecureRegistries := range insecureRegistries { options.InsecureRegistries.Set(insecureRegistries) } } return NewServiceConfig(options) } func writeHeaders(w http.ResponseWriter) { h := w.Header() h.Add("Server", "docker-tests/mock") h.Add("Expires", "-1") h.Add("Content-Type", "application/json") h.Add("Pragma", "no-cache") h.Add("Cache-Control", "no-cache") h.Add("X-Docker-Registry-Version", "0.0.0") h.Add("X-Docker-Registry-Config", "mock") } func writeResponse(w http.ResponseWriter, message interface{}, code int) { writeHeaders(w) w.WriteHeader(code) body, err := json.Marshal(message) if err != nil { io.WriteString(w, err.Error()) return } w.Write(body) } func readJSON(r *http.Request, dest interface{}) error { body, err := ioutil.ReadAll(r.Body) if err != nil { return err } return json.Unmarshal(body, dest) } func apiError(w http.ResponseWriter, message string, code int) { body := map[string]string{ "error": message, } writeResponse(w, body, code) } func assertEqual(t *testing.T, a interface{}, b interface{}, message string) { if a == b { return } if len(message) == 0 { message = fmt.Sprintf("%v != %v", a, b) } t.Fatal(message) } func assertNotEqual(t *testing.T, a interface{}, b interface{}, message string) { if a != b { return } if len(message) == 0 { message = fmt.Sprintf("%v == %v", a, b) } t.Fatal(message) } // Similar to assertEqual, but does not stop test func checkEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) { if a == b { return } message := fmt.Sprintf("%v != %v", a, b) if len(messagePrefix) != 0 { message = messagePrefix + ": " + message } t.Error(message) } // Similar to assertNotEqual, but does not stop test func checkNotEqual(t *testing.T, a interface{}, b interface{}, messagePrefix string) { if a != b { return } message := fmt.Sprintf("%v == %v", a, b) if len(messagePrefix) != 0 { message = messagePrefix + ": " + message } t.Error(message) } func requiresAuth(w http.ResponseWriter, r *http.Request) bool { writeCookie := func() { value := fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano()) cookie := &http.Cookie{Name: "session", Value: value, MaxAge: 3600} http.SetCookie(w, cookie) //FIXME(sam): this should be sent only on Index routes value = fmt.Sprintf("FAKE-TOKEN-%d", time.Now().UnixNano()) w.Header().Add("X-Docker-Token", value) } if len(r.Cookies()) > 0 { writeCookie() return true } if len(r.Header.Get("Authorization")) > 0 { writeCookie() return true } w.Header().Add("WWW-Authenticate", "token") apiError(w, "Wrong auth", 401) return false } func handlerGetPing(w http.ResponseWriter, r *http.Request) { writeResponse(w, true, 200) } func handlerGetImage(w http.ResponseWriter, r *http.Request) { if !requiresAuth(w, r) { return } vars := mux.Vars(r) layer, exists := testLayers[vars["image_id"]] if !exists { http.NotFound(w, r) return } writeHeaders(w) layerSize := len(layer["layer"]) w.Header().Add("X-Docker-Size", strconv.Itoa(layerSize)) io.WriteString(w, layer[vars["action"]]) } func handlerPutImage(w http.ResponseWriter, r *http.Request) { if !requiresAuth(w, r) { return } vars := mux.Vars(r) imageID := vars["image_id"] action := vars["action"] layer, exists := testLayers[imageID] if !exists { if action != "json" { http.NotFound(w, r) return } layer = make(map[string]string) testLayers[imageID] = layer } if checksum := r.Header.Get("X-Docker-Checksum"); checksum != "" { if checksum != layer["checksum_simple"] && checksum != layer["checksum_tarsum"] { apiError(w, "Wrong checksum", 400) return } } body, err := ioutil.ReadAll(r.Body) if err != nil { apiError(w, fmt.Sprintf("Error: %s", err), 500) return } layer[action] = string(body) writeResponse(w, true, 200) } func handlerGetDeleteTags(w http.ResponseWriter, r *http.Request) { if !requiresAuth(w, r) { return } repositoryName := mux.Vars(r)["repository"] repositoryName = NormalizeLocalName(repositoryName) tags, exists := testRepositories[repositoryName] if !exists { apiError(w, "Repository not found", 404) return } if r.Method == "DELETE" { delete(testRepositories, repositoryName) writeResponse(w, true, 200) return } writeResponse(w, tags, 200) } func handlerGetTag(w http.ResponseWriter, r *http.Request) { if !requiresAuth(w, r) { return } vars := mux.Vars(r) repositoryName := vars["repository"] repositoryName = NormalizeLocalName(repositoryName) tagName := vars["tag"] tags, exists := testRepositories[repositoryName] if !exists { apiError(w, "Repository not found", 404) return } tag, exists := tags[tagName] if !exists { apiError(w, "Tag not found", 404) return } writeResponse(w, tag, 200) } func handlerPutTag(w http.ResponseWriter, r *http.Request) { if !requiresAuth(w, r) { return } vars := mux.Vars(r) repositoryName := vars["repository"] repositoryName = NormalizeLocalName(repositoryName) tagName := vars["tag"] tags, exists := testRepositories[repositoryName] if !exists { tags := make(map[string]string) testRepositories[repositoryName] = tags } tagValue := "" readJSON(r, tagValue) tags[tagName] = tagValue writeResponse(w, true, 200) } func handlerUsers(w http.ResponseWriter, r *http.Request) { code := 200 if r.Method == "POST" { code = 201 } else if r.Method == "PUT" { code = 204 } writeResponse(w, "", code) } func handlerImages(w http.ResponseWriter, r *http.Request) { u, _ := url.Parse(testHTTPServer.URL) w.Header().Add("X-Docker-Endpoints", fmt.Sprintf("%s , %s ", u.Host, "test.example.com")) w.Header().Add("X-Docker-Token", fmt.Sprintf("FAKE-SESSION-%d", time.Now().UnixNano())) if r.Method == "PUT" { if strings.HasSuffix(r.URL.Path, "images") { writeResponse(w, "", 204) return } writeResponse(w, "", 200) return } if r.Method == "DELETE" { writeResponse(w, "", 204) return } images := []map[string]string{} for imageID, layer := range testLayers { image := make(map[string]string) image["id"] = imageID image["checksum"] = layer["checksum_tarsum"] image["Tag"] = "latest" images = append(images, image) } writeResponse(w, images, 200) } func handlerAuth(w http.ResponseWriter, r *http.Request) { writeResponse(w, "OK", 200) } func handlerSearch(w http.ResponseWriter, r *http.Request) { result := &SearchResults{ Query: "fakequery", NumResults: 1, Results: []SearchResult{{Name: "fakeimage", StarCount: 42}}, } writeResponse(w, result, 200) } func TestPing(t *testing.T) { res, err := http.Get(makeURL("/v1/_ping")) if err != nil { t.Fatal(err) } assertEqual(t, res.StatusCode, 200, "") assertEqual(t, res.Header.Get("X-Docker-Registry-Config"), "mock", "This is not a Mocked Registry") } /* Uncomment this to test Mocked Registry locally with curl * WARNING: Don't push on the repos uncommented, it'll block the tests * func TestWait(t *testing.T) { logrus.Println("Test HTTP server ready and waiting:", testHttpServer.URL) c := make(chan int) <-c } //*/ ================================================ FILE: vendor/github.com/docker/docker/registry/registry_test.go ================================================ package registry import ( "fmt" "net/http" "net/http/httputil" "net/url" "strings" "testing" "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/cliconfig" ) var ( token = []string{"fake-token"} ) const ( imageID = "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d" REPO = "foo42/bar" ) func spawnTestRegistrySession(t *testing.T) *Session { authConfig := &cliconfig.AuthConfig{} endpoint, err := NewEndpoint(makeIndex("/v1/"), nil) if err != nil { t.Fatal(err) } var tr http.RoundTripper = debugTransport{NewTransport(nil), t.Log} tr = transport.NewTransport(AuthTransport(tr, authConfig, false), DockerHeaders(nil)...) client := HTTPClient(tr) r, err := NewSession(client, authConfig, endpoint) if err != nil { t.Fatal(err) } // In a normal scenario for the v1 registry, the client should send a `X-Docker-Token: true` // header while authenticating, in order to retrieve a token that can be later used to // perform authenticated actions. // // The mock v1 registry does not support that, (TODO(tiborvass): support it), instead, // it will consider authenticated any request with the header `X-Docker-Token: fake-token`. // // Because we know that the client's transport is an `*authTransport` we simply cast it, // in order to set the internal cached token to the fake token, and thus send that fake token // upon every subsequent requests. r.client.Transport.(*authTransport).token = token return r } func TestPingRegistryEndpoint(t *testing.T) { testPing := func(index *IndexInfo, expectedStandalone bool, assertMessage string) { ep, err := NewEndpoint(index, nil) if err != nil { t.Fatal(err) } regInfo, err := ep.Ping() if err != nil { t.Fatal(err) } assertEqual(t, regInfo.Standalone, expectedStandalone, assertMessage) } testPing(makeIndex("/v1/"), true, "Expected standalone to be true (default)") testPing(makeHttpsIndex("/v1/"), true, "Expected standalone to be true (default)") testPing(makePublicIndex(), false, "Expected standalone to be false for public index") } func TestEndpoint(t *testing.T) { // Simple wrapper to fail test if err != nil expandEndpoint := func(index *IndexInfo) *Endpoint { endpoint, err := NewEndpoint(index, nil) if err != nil { t.Fatal(err) } return endpoint } assertInsecureIndex := func(index *IndexInfo) { index.Secure = true _, err := NewEndpoint(index, nil) assertNotEqual(t, err, nil, index.Name+": Expected error for insecure index") assertEqual(t, strings.Contains(err.Error(), "insecure-registry"), true, index.Name+": Expected insecure-registry error for insecure index") index.Secure = false } assertSecureIndex := func(index *IndexInfo) { index.Secure = true _, err := NewEndpoint(index, nil) assertNotEqual(t, err, nil, index.Name+": Expected cert error for secure index") assertEqual(t, strings.Contains(err.Error(), "certificate signed by unknown authority"), true, index.Name+": Expected cert error for secure index") index.Secure = false } index := &IndexInfo{} index.Name = makeURL("/v1/") endpoint := expandEndpoint(index) assertEqual(t, endpoint.String(), index.Name, "Expected endpoint to be "+index.Name) if endpoint.Version != APIVersion1 { t.Fatal("Expected endpoint to be v1") } assertInsecureIndex(index) index.Name = makeURL("") endpoint = expandEndpoint(index) assertEqual(t, endpoint.String(), index.Name+"/v1/", index.Name+": Expected endpoint to be "+index.Name+"/v1/") if endpoint.Version != APIVersion1 { t.Fatal("Expected endpoint to be v1") } assertInsecureIndex(index) httpURL := makeURL("") index.Name = strings.SplitN(httpURL, "://", 2)[1] endpoint = expandEndpoint(index) assertEqual(t, endpoint.String(), httpURL+"/v1/", index.Name+": Expected endpoint to be "+httpURL+"/v1/") if endpoint.Version != APIVersion1 { t.Fatal("Expected endpoint to be v1") } assertInsecureIndex(index) index.Name = makeHttpsURL("/v1/") endpoint = expandEndpoint(index) assertEqual(t, endpoint.String(), index.Name, "Expected endpoint to be "+index.Name) if endpoint.Version != APIVersion1 { t.Fatal("Expected endpoint to be v1") } assertSecureIndex(index) index.Name = makeHttpsURL("") endpoint = expandEndpoint(index) assertEqual(t, endpoint.String(), index.Name+"/v1/", index.Name+": Expected endpoint to be "+index.Name+"/v1/") if endpoint.Version != APIVersion1 { t.Fatal("Expected endpoint to be v1") } assertSecureIndex(index) httpsURL := makeHttpsURL("") index.Name = strings.SplitN(httpsURL, "://", 2)[1] endpoint = expandEndpoint(index) assertEqual(t, endpoint.String(), httpsURL+"/v1/", index.Name+": Expected endpoint to be "+httpsURL+"/v1/") if endpoint.Version != APIVersion1 { t.Fatal("Expected endpoint to be v1") } assertSecureIndex(index) badEndpoints := []string{ "http://127.0.0.1/v1/", "https://127.0.0.1/v1/", "http://127.0.0.1", "https://127.0.0.1", "127.0.0.1", } for _, address := range badEndpoints { index.Name = address _, err := NewEndpoint(index, nil) checkNotEqual(t, err, nil, "Expected error while expanding bad endpoint") } } func TestGetRemoteHistory(t *testing.T) { r := spawnTestRegistrySession(t) hist, err := r.GetRemoteHistory(imageID, makeURL("/v1/")) if err != nil { t.Fatal(err) } assertEqual(t, len(hist), 2, "Expected 2 images in history") assertEqual(t, hist[0], imageID, "Expected "+imageID+"as first ancestry") assertEqual(t, hist[1], "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", "Unexpected second ancestry") } func TestLookupRemoteImage(t *testing.T) { r := spawnTestRegistrySession(t) err := r.LookupRemoteImage(imageID, makeURL("/v1/")) assertEqual(t, err, nil, "Expected error of remote lookup to nil") if err := r.LookupRemoteImage("abcdef", makeURL("/v1/")); err == nil { t.Fatal("Expected error of remote lookup to not nil") } } func TestGetRemoteImageJSON(t *testing.T) { r := spawnTestRegistrySession(t) json, size, err := r.GetRemoteImageJSON(imageID, makeURL("/v1/")) if err != nil { t.Fatal(err) } assertEqual(t, size, 154, "Expected size 154") if len(json) <= 0 { t.Fatal("Expected non-empty json") } _, _, err = r.GetRemoteImageJSON("abcdef", makeURL("/v1/")) if err == nil { t.Fatal("Expected image not found error") } } func TestGetRemoteImageLayer(t *testing.T) { r := spawnTestRegistrySession(t) data, err := r.GetRemoteImageLayer(imageID, makeURL("/v1/"), 0) if err != nil { t.Fatal(err) } if data == nil { t.Fatal("Expected non-nil data result") } _, err = r.GetRemoteImageLayer("abcdef", makeURL("/v1/"), 0) if err == nil { t.Fatal("Expected image not found error") } } func TestGetRemoteTag(t *testing.T) { r := spawnTestRegistrySession(t) tag, err := r.GetRemoteTag([]string{makeURL("/v1/")}, REPO, "test") if err != nil { t.Fatal(err) } assertEqual(t, tag, imageID, "Expected tag test to map to "+imageID) _, err = r.GetRemoteTag([]string{makeURL("/v1/")}, "foo42/baz", "foo") if err != ErrRepoNotFound { t.Fatal("Expected ErrRepoNotFound error when fetching tag for bogus repo") } } func TestGetRemoteTags(t *testing.T) { r := spawnTestRegistrySession(t) tags, err := r.GetRemoteTags([]string{makeURL("/v1/")}, REPO) if err != nil { t.Fatal(err) } assertEqual(t, len(tags), 2, "Expected two tags") assertEqual(t, tags["latest"], imageID, "Expected tag latest to map to "+imageID) assertEqual(t, tags["test"], imageID, "Expected tag test to map to "+imageID) _, err = r.GetRemoteTags([]string{makeURL("/v1/")}, "foo42/baz") if err != ErrRepoNotFound { t.Fatal("Expected ErrRepoNotFound error when fetching tags for bogus repo") } } func TestGetRepositoryData(t *testing.T) { r := spawnTestRegistrySession(t) parsedURL, err := url.Parse(makeURL("/v1/")) if err != nil { t.Fatal(err) } host := "http://" + parsedURL.Host + "/v1/" data, err := r.GetRepositoryData("foo42/bar") if err != nil { t.Fatal(err) } assertEqual(t, len(data.ImgList), 2, "Expected 2 images in ImgList") assertEqual(t, len(data.Endpoints), 2, fmt.Sprintf("Expected 2 endpoints in Endpoints, found %d instead", len(data.Endpoints))) assertEqual(t, data.Endpoints[0], host, fmt.Sprintf("Expected first endpoint to be %s but found %s instead", host, data.Endpoints[0])) assertEqual(t, data.Endpoints[1], "http://test.example.com/v1/", fmt.Sprintf("Expected first endpoint to be http://test.example.com/v1/ but found %s instead", data.Endpoints[1])) } func TestPushImageJSONRegistry(t *testing.T) { r := spawnTestRegistrySession(t) imgData := &ImgData{ ID: "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", Checksum: "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37", } err := r.PushImageJSONRegistry(imgData, []byte{0x42, 0xdf, 0x0}, makeURL("/v1/")) if err != nil { t.Fatal(err) } } func TestPushImageLayerRegistry(t *testing.T) { r := spawnTestRegistrySession(t) layer := strings.NewReader("") _, _, err := r.PushImageLayerRegistry(imageID, layer, makeURL("/v1/"), []byte{}) if err != nil { t.Fatal(err) } } func TestValidateRepositoryName(t *testing.T) { validRepoNames := []string{ "docker/docker", "library/debian", "debian", "docker.io/docker/docker", "docker.io/library/debian", "docker.io/debian", "index.docker.io/docker/docker", "index.docker.io/library/debian", "index.docker.io/debian", "127.0.0.1:5000/docker/docker", "127.0.0.1:5000/library/debian", "127.0.0.1:5000/debian", "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev", } invalidRepoNames := []string{ "https://github.com/docker/docker", "docker/Docker", "-docker", "-docker/docker", "-docker.io/docker/docker", "docker///docker", "docker.io/docker/Docker", "docker.io/docker///docker", "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a", "docker.io/1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a", } for _, name := range invalidRepoNames { err := ValidateRepositoryName(name) assertNotEqual(t, err, nil, "Expected invalid repo name: "+name) } for _, name := range validRepoNames { err := ValidateRepositoryName(name) assertEqual(t, err, nil, "Expected valid repo name: "+name) } err := ValidateRepositoryName(invalidRepoNames[0]) assertEqual(t, err, ErrInvalidRepositoryName, "Expected ErrInvalidRepositoryName: "+invalidRepoNames[0]) } func TestParseRepositoryInfo(t *testing.T) { expectedRepoInfos := map[string]RepositoryInfo{ "fooo/bar": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "fooo/bar", LocalName: "fooo/bar", CanonicalName: "docker.io/fooo/bar", Official: false, }, "library/ubuntu": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "library/ubuntu", LocalName: "ubuntu", CanonicalName: "docker.io/library/ubuntu", Official: true, }, "nonlibrary/ubuntu": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "nonlibrary/ubuntu", LocalName: "nonlibrary/ubuntu", CanonicalName: "docker.io/nonlibrary/ubuntu", Official: false, }, "ubuntu": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "library/ubuntu", LocalName: "ubuntu", CanonicalName: "docker.io/library/ubuntu", Official: true, }, "other/library": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "other/library", LocalName: "other/library", CanonicalName: "docker.io/other/library", Official: false, }, "127.0.0.1:8000/private/moonbase": { Index: &IndexInfo{ Name: "127.0.0.1:8000", Official: false, }, RemoteName: "private/moonbase", LocalName: "127.0.0.1:8000/private/moonbase", CanonicalName: "127.0.0.1:8000/private/moonbase", Official: false, }, "127.0.0.1:8000/privatebase": { Index: &IndexInfo{ Name: "127.0.0.1:8000", Official: false, }, RemoteName: "privatebase", LocalName: "127.0.0.1:8000/privatebase", CanonicalName: "127.0.0.1:8000/privatebase", Official: false, }, "localhost:8000/private/moonbase": { Index: &IndexInfo{ Name: "localhost:8000", Official: false, }, RemoteName: "private/moonbase", LocalName: "localhost:8000/private/moonbase", CanonicalName: "localhost:8000/private/moonbase", Official: false, }, "localhost:8000/privatebase": { Index: &IndexInfo{ Name: "localhost:8000", Official: false, }, RemoteName: "privatebase", LocalName: "localhost:8000/privatebase", CanonicalName: "localhost:8000/privatebase", Official: false, }, "example.com/private/moonbase": { Index: &IndexInfo{ Name: "example.com", Official: false, }, RemoteName: "private/moonbase", LocalName: "example.com/private/moonbase", CanonicalName: "example.com/private/moonbase", Official: false, }, "example.com/privatebase": { Index: &IndexInfo{ Name: "example.com", Official: false, }, RemoteName: "privatebase", LocalName: "example.com/privatebase", CanonicalName: "example.com/privatebase", Official: false, }, "example.com:8000/private/moonbase": { Index: &IndexInfo{ Name: "example.com:8000", Official: false, }, RemoteName: "private/moonbase", LocalName: "example.com:8000/private/moonbase", CanonicalName: "example.com:8000/private/moonbase", Official: false, }, "example.com:8000/privatebase": { Index: &IndexInfo{ Name: "example.com:8000", Official: false, }, RemoteName: "privatebase", LocalName: "example.com:8000/privatebase", CanonicalName: "example.com:8000/privatebase", Official: false, }, "localhost/private/moonbase": { Index: &IndexInfo{ Name: "localhost", Official: false, }, RemoteName: "private/moonbase", LocalName: "localhost/private/moonbase", CanonicalName: "localhost/private/moonbase", Official: false, }, "localhost/privatebase": { Index: &IndexInfo{ Name: "localhost", Official: false, }, RemoteName: "privatebase", LocalName: "localhost/privatebase", CanonicalName: "localhost/privatebase", Official: false, }, INDEXNAME + "/public/moonbase": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "public/moonbase", LocalName: "public/moonbase", CanonicalName: "docker.io/public/moonbase", Official: false, }, "index." + INDEXNAME + "/public/moonbase": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "public/moonbase", LocalName: "public/moonbase", CanonicalName: "docker.io/public/moonbase", Official: false, }, "ubuntu-12.04-base": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "library/ubuntu-12.04-base", LocalName: "ubuntu-12.04-base", CanonicalName: "docker.io/library/ubuntu-12.04-base", Official: true, }, INDEXNAME + "/ubuntu-12.04-base": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "library/ubuntu-12.04-base", LocalName: "ubuntu-12.04-base", CanonicalName: "docker.io/library/ubuntu-12.04-base", Official: true, }, "index." + INDEXNAME + "/ubuntu-12.04-base": { Index: &IndexInfo{ Name: INDEXNAME, Official: true, }, RemoteName: "library/ubuntu-12.04-base", LocalName: "ubuntu-12.04-base", CanonicalName: "docker.io/library/ubuntu-12.04-base", Official: true, }, } for reposName, expectedRepoInfo := range expectedRepoInfos { repoInfo, err := ParseRepositoryInfo(reposName) if err != nil { t.Error(err) } else { checkEqual(t, repoInfo.Index.Name, expectedRepoInfo.Index.Name, reposName) checkEqual(t, repoInfo.RemoteName, expectedRepoInfo.RemoteName, reposName) checkEqual(t, repoInfo.LocalName, expectedRepoInfo.LocalName, reposName) checkEqual(t, repoInfo.CanonicalName, expectedRepoInfo.CanonicalName, reposName) checkEqual(t, repoInfo.Index.Official, expectedRepoInfo.Index.Official, reposName) checkEqual(t, repoInfo.Official, expectedRepoInfo.Official, reposName) } } } func TestNewIndexInfo(t *testing.T) { testIndexInfo := func(config *ServiceConfig, expectedIndexInfos map[string]*IndexInfo) { for indexName, expectedIndexInfo := range expectedIndexInfos { index, err := config.NewIndexInfo(indexName) if err != nil { t.Fatal(err) } else { checkEqual(t, index.Name, expectedIndexInfo.Name, indexName+" name") checkEqual(t, index.Official, expectedIndexInfo.Official, indexName+" is official") checkEqual(t, index.Secure, expectedIndexInfo.Secure, indexName+" is secure") checkEqual(t, len(index.Mirrors), len(expectedIndexInfo.Mirrors), indexName+" mirrors") } } } config := NewServiceConfig(nil) noMirrors := make([]string, 0) expectedIndexInfos := map[string]*IndexInfo{ INDEXNAME: { Name: INDEXNAME, Official: true, Secure: true, Mirrors: noMirrors, }, "index." + INDEXNAME: { Name: INDEXNAME, Official: true, Secure: true, Mirrors: noMirrors, }, "example.com": { Name: "example.com", Official: false, Secure: true, Mirrors: noMirrors, }, "127.0.0.1:5000": { Name: "127.0.0.1:5000", Official: false, Secure: false, Mirrors: noMirrors, }, } testIndexInfo(config, expectedIndexInfos) publicMirrors := []string{"http://mirror1.local", "http://mirror2.local"} config = makeServiceConfig(publicMirrors, []string{"example.com"}) expectedIndexInfos = map[string]*IndexInfo{ INDEXNAME: { Name: INDEXNAME, Official: true, Secure: true, Mirrors: publicMirrors, }, "index." + INDEXNAME: { Name: INDEXNAME, Official: true, Secure: true, Mirrors: publicMirrors, }, "example.com": { Name: "example.com", Official: false, Secure: false, Mirrors: noMirrors, }, "example.com:5000": { Name: "example.com:5000", Official: false, Secure: true, Mirrors: noMirrors, }, "127.0.0.1": { Name: "127.0.0.1", Official: false, Secure: false, Mirrors: noMirrors, }, "127.0.0.1:5000": { Name: "127.0.0.1:5000", Official: false, Secure: false, Mirrors: noMirrors, }, "other.com": { Name: "other.com", Official: false, Secure: true, Mirrors: noMirrors, }, } testIndexInfo(config, expectedIndexInfos) config = makeServiceConfig(nil, []string{"42.42.0.0/16"}) expectedIndexInfos = map[string]*IndexInfo{ "example.com": { Name: "example.com", Official: false, Secure: false, Mirrors: noMirrors, }, "example.com:5000": { Name: "example.com:5000", Official: false, Secure: false, Mirrors: noMirrors, }, "127.0.0.1": { Name: "127.0.0.1", Official: false, Secure: false, Mirrors: noMirrors, }, "127.0.0.1:5000": { Name: "127.0.0.1:5000", Official: false, Secure: false, Mirrors: noMirrors, }, "other.com": { Name: "other.com", Official: false, Secure: true, Mirrors: noMirrors, }, } testIndexInfo(config, expectedIndexInfos) } func TestPushRegistryTag(t *testing.T) { r := spawnTestRegistrySession(t) err := r.PushRegistryTag("foo42/bar", imageID, "stable", makeURL("/v1/")) if err != nil { t.Fatal(err) } } func TestPushImageJSONIndex(t *testing.T) { r := spawnTestRegistrySession(t) imgData := []*ImgData{ { ID: "77dbf71da1d00e3fbddc480176eac8994025630c6590d11cfc8fe1209c2a1d20", Checksum: "sha256:1ac330d56e05eef6d438586545ceff7550d3bdcb6b19961f12c5ba714ee1bb37", }, { ID: "42d718c941f5c532ac049bf0b0ab53f0062f09a03afd4aa4a02c098e46032b9d", Checksum: "sha256:bea7bf2e4bacd479344b737328db47b18880d09096e6674165533aa994f5e9f2", }, } repoData, err := r.PushImageJSONIndex("foo42/bar", imgData, false, nil) if err != nil { t.Fatal(err) } if repoData == nil { t.Fatal("Expected RepositoryData object") } repoData, err = r.PushImageJSONIndex("foo42/bar", imgData, true, []string{r.indexEndpoint.String()}) if err != nil { t.Fatal(err) } if repoData == nil { t.Fatal("Expected RepositoryData object") } } func TestSearchRepositories(t *testing.T) { r := spawnTestRegistrySession(t) results, err := r.SearchRepositories("fakequery") if err != nil { t.Fatal(err) } if results == nil { t.Fatal("Expected non-nil SearchResults object") } assertEqual(t, results.NumResults, 1, "Expected 1 search results") assertEqual(t, results.Query, "fakequery", "Expected 'fakequery' as query") assertEqual(t, results.Results[0].StarCount, 42, "Expected 'fakeimage' to have 42 stars") } func TestValidRemoteName(t *testing.T) { validRepositoryNames := []string{ // Sanity check. "docker/docker", // Allow 64-character non-hexadecimal names (hexadecimal names are forbidden). "thisisthesongthatneverendsitgoesonandonandonthisisthesongthatnev", // Allow embedded hyphens. "docker-rules/docker", //Username doc and image name docker being tested. "doc/docker", // single character names are now allowed. "d/docker", "jess/t", } for _, repositoryName := range validRepositoryNames { if err := validateRemoteName(repositoryName); err != nil { t.Errorf("Repository name should be valid: %v. Error: %v", repositoryName, err) } } invalidRepositoryNames := []string{ // Disallow capital letters. "docker/Docker", // Only allow one slash. "docker///docker", // Disallow 64-character hexadecimal. "1a3f5e7d9c1b3a5f7e9d1c3b5a7f9e1d3c5b7a9f1e3d5d7c9b1a3f5e7d9c1b3a", // Disallow leading and trailing hyphens in namespace. "-docker/docker", "docker-/docker", "-docker-/docker", // Don't allow underscores everywhere (as opposed to hyphens). "____/____", "_docker/_docker", // Disallow consecutive hyphens. "dock--er/docker", // No repository. "docker/", //namespace too long "this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255_this_is_not_a_valid_namespace_because_its_lenth_is_greater_than_255/docker", } for _, repositoryName := range invalidRepositoryNames { if err := validateRemoteName(repositoryName); err == nil { t.Errorf("Repository name should be invalid: %v", repositoryName) } } } func TestTrustedLocation(t *testing.T) { for _, url := range []string{"http://example.com", "https://example.com:7777", "http://docker.io", "http://test.docker.com", "https://fakedocker.com"} { req, _ := http.NewRequest("GET", url, nil) if trustedLocation(req) == true { t.Fatalf("'%s' shouldn't be detected as a trusted location", url) } } for _, url := range []string{"https://docker.io", "https://test.docker.com:80"} { req, _ := http.NewRequest("GET", url, nil) if trustedLocation(req) == false { t.Fatalf("'%s' should be detected as a trusted location", url) } } } func TestAddRequiredHeadersToRedirectedRequests(t *testing.T) { for _, urls := range [][]string{ {"http://docker.io", "https://docker.com"}, {"https://foo.docker.io:7777", "http://bar.docker.com"}, {"https://foo.docker.io", "https://example.com"}, } { reqFrom, _ := http.NewRequest("GET", urls[0], nil) reqFrom.Header.Add("Content-Type", "application/json") reqFrom.Header.Add("Authorization", "super_secret") reqTo, _ := http.NewRequest("GET", urls[1], nil) AddRequiredHeadersToRedirectedRequests(reqTo, []*http.Request{reqFrom}) if len(reqTo.Header) != 1 { t.Fatalf("Expected 1 headers, got %d", len(reqTo.Header)) } if reqTo.Header.Get("Content-Type") != "application/json" { t.Fatal("'Content-Type' should be 'application/json'") } if reqTo.Header.Get("Authorization") != "" { t.Fatal("'Authorization' should be empty") } } for _, urls := range [][]string{ {"https://docker.io", "https://docker.com"}, {"https://foo.docker.io:7777", "https://bar.docker.com"}, } { reqFrom, _ := http.NewRequest("GET", urls[0], nil) reqFrom.Header.Add("Content-Type", "application/json") reqFrom.Header.Add("Authorization", "super_secret") reqTo, _ := http.NewRequest("GET", urls[1], nil) AddRequiredHeadersToRedirectedRequests(reqTo, []*http.Request{reqFrom}) if len(reqTo.Header) != 2 { t.Fatalf("Expected 2 headers, got %d", len(reqTo.Header)) } if reqTo.Header.Get("Content-Type") != "application/json" { t.Fatal("'Content-Type' should be 'application/json'") } if reqTo.Header.Get("Authorization") != "super_secret" { t.Fatal("'Authorization' should be 'super_secret'") } } } func TestIsSecureIndex(t *testing.T) { tests := []struct { addr string insecureRegistries []string expected bool }{ {INDEXNAME, nil, true}, {"example.com", []string{}, true}, {"example.com", []string{"example.com"}, false}, {"localhost", []string{"localhost:5000"}, false}, {"localhost:5000", []string{"localhost:5000"}, false}, {"localhost", []string{"example.com"}, false}, {"127.0.0.1:5000", []string{"127.0.0.1:5000"}, false}, {"localhost", nil, false}, {"localhost:5000", nil, false}, {"127.0.0.1", nil, false}, {"localhost", []string{"example.com"}, false}, {"127.0.0.1", []string{"example.com"}, false}, {"example.com", nil, true}, {"example.com", []string{"example.com"}, false}, {"127.0.0.1", []string{"example.com"}, false}, {"127.0.0.1:5000", []string{"example.com"}, false}, {"example.com:5000", []string{"42.42.0.0/16"}, false}, {"example.com", []string{"42.42.0.0/16"}, false}, {"example.com:5000", []string{"42.42.42.42/8"}, false}, {"127.0.0.1:5000", []string{"127.0.0.0/8"}, false}, {"42.42.42.42:5000", []string{"42.1.1.1/8"}, false}, {"invalid.domain.com", []string{"42.42.0.0/16"}, true}, {"invalid.domain.com", []string{"invalid.domain.com"}, false}, {"invalid.domain.com:5000", []string{"invalid.domain.com"}, true}, {"invalid.domain.com:5000", []string{"invalid.domain.com:5000"}, false}, } for _, tt := range tests { config := makeServiceConfig(nil, tt.insecureRegistries) if sec := config.isSecureIndex(tt.addr); sec != tt.expected { t.Errorf("isSecureIndex failed for %q %v, expected %v got %v", tt.addr, tt.insecureRegistries, tt.expected, sec) } } } type debugTransport struct { http.RoundTripper log func(...interface{}) } func (tr debugTransport) RoundTrip(req *http.Request) (*http.Response, error) { dump, err := httputil.DumpRequestOut(req, false) if err != nil { tr.log("could not dump request") } tr.log(string(dump)) resp, err := tr.RoundTripper.RoundTrip(req) if err != nil { return nil, err } dump, err = httputil.DumpResponse(resp, false) if err != nil { tr.log("could not dump response") } tr.log(string(dump)) return resp, err } ================================================ FILE: vendor/github.com/docker/docker/registry/service.go ================================================ package registry import ( "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "strings" "github.com/Sirupsen/logrus" "github.com/docker/distribution/registry/client/auth" "github.com/docker/docker/cliconfig" "github.com/docker/docker/pkg/tlsconfig" ) type Service struct { Config *ServiceConfig } // NewService returns a new instance of Service ready to be // installed no an engine. func NewService(options *Options) *Service { return &Service{ Config: NewServiceConfig(options), } } // Auth contacts the public registry with the provided credentials, // and returns OK if authentication was sucessful. // It can be used to verify the validity of a client's credentials. func (s *Service) Auth(authConfig *cliconfig.AuthConfig) (string, error) { addr := authConfig.ServerAddress if addr == "" { // Use the official registry address if not specified. addr = INDEXSERVER } index, err := s.ResolveIndex(addr) if err != nil { return "", err } endpoint, err := NewEndpoint(index, nil) if err != nil { return "", err } authConfig.ServerAddress = endpoint.String() return Login(authConfig, endpoint) } // Search queries the public registry for images matching the specified // search terms, and returns the results. func (s *Service) Search(term string, authConfig *cliconfig.AuthConfig, headers map[string][]string) (*SearchResults, error) { repoInfo, err := s.ResolveRepository(term) if err != nil { return nil, err } // *TODO: Search multiple indexes. endpoint, err := repoInfo.GetEndpoint(http.Header(headers)) if err != nil { return nil, err } r, err := NewSession(endpoint.client, authConfig, endpoint) if err != nil { return nil, err } return r.SearchRepositories(repoInfo.GetSearchTerm()) } // ResolveRepository splits a repository name into its components // and configuration of the associated registry. func (s *Service) ResolveRepository(name string) (*RepositoryInfo, error) { return s.Config.NewRepositoryInfo(name) } // ResolveIndex takes indexName and returns index info func (s *Service) ResolveIndex(name string) (*IndexInfo, error) { return s.Config.NewIndexInfo(name) } type APIEndpoint struct { Mirror bool URL string Version APIVersion Official bool TrimHostname bool TLSConfig *tls.Config VersionHeader string Versions []auth.APIVersion } func (e APIEndpoint) ToV1Endpoint(metaHeaders http.Header) (*Endpoint, error) { return newEndpoint(e.URL, e.TLSConfig, metaHeaders) } func (s *Service) TlsConfig(hostname string) (*tls.Config, error) { // we construct a client tls config from server defaults // PreferredServerCipherSuites should have no effect tlsConfig := tlsconfig.ServerDefault isSecure := s.Config.isSecureIndex(hostname) tlsConfig.InsecureSkipVerify = !isSecure if isSecure { hasFile := func(files []os.FileInfo, name string) bool { for _, f := range files { if f.Name() == name { return true } } return false } hostDir := filepath.Join(CERTS_DIR, hostname) logrus.Debugf("hostDir: %s", hostDir) fs, err := ioutil.ReadDir(hostDir) if err != nil && !os.IsNotExist(err) { return nil, err } for _, f := range fs { if strings.HasSuffix(f.Name(), ".crt") { if tlsConfig.RootCAs == nil { // TODO(dmcgowan): Copy system pool tlsConfig.RootCAs = x509.NewCertPool() } logrus.Debugf("crt: %s", filepath.Join(hostDir, f.Name())) data, err := ioutil.ReadFile(filepath.Join(hostDir, f.Name())) if err != nil { return nil, err } tlsConfig.RootCAs.AppendCertsFromPEM(data) } if strings.HasSuffix(f.Name(), ".cert") { certName := f.Name() keyName := certName[:len(certName)-5] + ".key" logrus.Debugf("cert: %s", filepath.Join(hostDir, f.Name())) if !hasFile(fs, keyName) { return nil, fmt.Errorf("Missing key %s for certificate %s", keyName, certName) } cert, err := tls.LoadX509KeyPair(filepath.Join(hostDir, certName), filepath.Join(hostDir, keyName)) if err != nil { return nil, err } tlsConfig.Certificates = append(tlsConfig.Certificates, cert) } if strings.HasSuffix(f.Name(), ".key") { keyName := f.Name() certName := keyName[:len(keyName)-4] + ".cert" logrus.Debugf("key: %s", filepath.Join(hostDir, f.Name())) if !hasFile(fs, certName) { return nil, fmt.Errorf("Missing certificate %s for key %s", certName, keyName) } } } } return &tlsConfig, nil } func (s *Service) tlsConfigForMirror(mirror string) (*tls.Config, error) { mirrorUrl, err := url.Parse(mirror) if err != nil { return nil, err } return s.TlsConfig(mirrorUrl.Host) } func (s *Service) LookupEndpoints(repoName string) (endpoints []APIEndpoint, err error) { var cfg = tlsconfig.ServerDefault tlsConfig := &cfg if strings.HasPrefix(repoName, DEFAULT_NAMESPACE+"/") { // v2 mirrors for _, mirror := range s.Config.Mirrors { mirrorTlsConfig, err := s.tlsConfigForMirror(mirror) if err != nil { return nil, err } endpoints = append(endpoints, APIEndpoint{ URL: mirror, // guess mirrors are v2 Version: APIVersion2, Mirror: true, TrimHostname: true, TLSConfig: mirrorTlsConfig, }) } // v2 registry endpoints = append(endpoints, APIEndpoint{ URL: DEFAULT_V2_REGISTRY, Version: APIVersion2, Official: true, TrimHostname: true, TLSConfig: tlsConfig, }) // v1 registry endpoints = append(endpoints, APIEndpoint{ URL: DEFAULT_V1_REGISTRY, Version: APIVersion1, Official: true, TrimHostname: true, TLSConfig: tlsConfig, }) return endpoints, nil } slashIndex := strings.IndexRune(repoName, '/') if slashIndex <= 0 { return nil, fmt.Errorf("invalid repo name: missing '/': %s", repoName) } hostname := repoName[:slashIndex] tlsConfig, err = s.TlsConfig(hostname) if err != nil { return nil, err } isSecure := !tlsConfig.InsecureSkipVerify v2Versions := []auth.APIVersion{ { Type: "registry", Version: "2.0", }, } endpoints = []APIEndpoint{ { URL: "https://" + hostname, Version: APIVersion2, TrimHostname: true, TLSConfig: tlsConfig, VersionHeader: DEFAULT_REGISTRY_VERSION_HEADER, Versions: v2Versions, }, { URL: "https://" + hostname, Version: APIVersion1, TrimHostname: true, TLSConfig: tlsConfig, }, } if !isSecure { endpoints = append(endpoints, APIEndpoint{ URL: "http://" + hostname, Version: APIVersion2, TrimHostname: true, // used to check if supposed to be secure via InsecureSkipVerify TLSConfig: tlsConfig, VersionHeader: DEFAULT_REGISTRY_VERSION_HEADER, Versions: v2Versions, }, APIEndpoint{ URL: "http://" + hostname, Version: APIVersion1, TrimHostname: true, // used to check if supposed to be secure via InsecureSkipVerify TLSConfig: tlsConfig, }) } return endpoints, nil } ================================================ FILE: vendor/github.com/docker/docker/registry/session.go ================================================ package registry import ( "bytes" "crypto/sha256" "errors" "sync" // this is required for some certificates _ "crypto/sha512" "encoding/hex" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/http/cookiejar" "net/url" "strconv" "strings" "time" "github.com/Sirupsen/logrus" "github.com/docker/docker/cliconfig" "github.com/docker/docker/pkg/httputils" "github.com/docker/docker/pkg/ioutils" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/tarsum" ) var ( ErrRepoNotFound = errors.New("Repository not found") ) type Session struct { indexEndpoint *Endpoint client *http.Client // TODO(tiborvass): remove authConfig authConfig *cliconfig.AuthConfig id string } type authTransport struct { http.RoundTripper *cliconfig.AuthConfig alwaysSetBasicAuth bool token []string mu sync.Mutex // guards modReq modReq map[*http.Request]*http.Request // original -> modified } // AuthTransport handles the auth layer when communicating with a v1 registry (private or official) // // For private v1 registries, set alwaysSetBasicAuth to true. // // For the official v1 registry, if there isn't already an Authorization header in the request, // but there is an X-Docker-Token header set to true, then Basic Auth will be used to set the Authorization header. // After sending the request with the provided base http.RoundTripper, if an X-Docker-Token header, representing // a token, is present in the response, then it gets cached and sent in the Authorization header of all subsequent // requests. // // If the server sends a token without the client having requested it, it is ignored. // // This RoundTripper also has a CancelRequest method important for correct timeout handling. func AuthTransport(base http.RoundTripper, authConfig *cliconfig.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper { if base == nil { base = http.DefaultTransport } return &authTransport{ RoundTripper: base, AuthConfig: authConfig, alwaysSetBasicAuth: alwaysSetBasicAuth, modReq: make(map[*http.Request]*http.Request), } } // 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 } func (tr *authTransport) RoundTrip(orig *http.Request) (*http.Response, error) { // Authorization should not be set on 302 redirect for untrusted locations. // This logic mirrors the behavior in AddRequiredHeadersToRedirectedRequests. // As the authorization logic is currently implemented in RoundTrip, // a 302 redirect is detected by looking at the Referer header as go http package adds said header. // This is safe as Docker doesn't set Referer in other scenarios. if orig.Header.Get("Referer") != "" && !trustedLocation(orig) { return tr.RoundTripper.RoundTrip(orig) } req := cloneRequest(orig) tr.mu.Lock() tr.modReq[orig] = req tr.mu.Unlock() if tr.alwaysSetBasicAuth { if tr.AuthConfig == nil { return nil, errors.New("unexpected error: empty auth config") } req.SetBasicAuth(tr.Username, tr.Password) return tr.RoundTripper.RoundTrip(req) } // Don't override if req.Header.Get("Authorization") == "" { if req.Header.Get("X-Docker-Token") == "true" && tr.AuthConfig != nil && len(tr.Username) > 0 { req.SetBasicAuth(tr.Username, tr.Password) } else if len(tr.token) > 0 { req.Header.Set("Authorization", "Token "+strings.Join(tr.token, ",")) } } resp, err := tr.RoundTripper.RoundTrip(req) if err != nil { delete(tr.modReq, orig) return nil, err } if len(resp.Header["X-Docker-Token"]) > 0 { tr.token = resp.Header["X-Docker-Token"] } resp.Body = &ioutils.OnEOFReader{ Rc: resp.Body, Fn: func() { tr.mu.Lock() delete(tr.modReq, orig) tr.mu.Unlock() }, } return resp, nil } // CancelRequest cancels an in-flight request by closing its connection. func (tr *authTransport) CancelRequest(req *http.Request) { type canceler interface { CancelRequest(*http.Request) } if cr, ok := tr.RoundTripper.(canceler); ok { tr.mu.Lock() modReq := tr.modReq[req] delete(tr.modReq, req) tr.mu.Unlock() cr.CancelRequest(modReq) } } // TODO(tiborvass): remove authConfig param once registry client v2 is vendored func NewSession(client *http.Client, authConfig *cliconfig.AuthConfig, endpoint *Endpoint) (r *Session, err error) { r = &Session{ authConfig: authConfig, client: client, indexEndpoint: endpoint, id: stringid.GenerateRandomID(), } var alwaysSetBasicAuth bool // If we're working with a standalone private registry over HTTPS, send Basic Auth headers // alongside all our requests. if endpoint.VersionString(1) != INDEXSERVER && endpoint.URL.Scheme == "https" { info, err := endpoint.Ping() if err != nil { return nil, err } if info.Standalone && authConfig != nil { logrus.Debugf("Endpoint %s is eligible for private registry. Enabling decorator.", endpoint.String()) alwaysSetBasicAuth = true } } // Annotate the transport unconditionally so that v2 can // properly fallback on v1 when an image is not found. client.Transport = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth) jar, err := cookiejar.New(nil) if err != nil { return nil, errors.New("cookiejar.New is not supposed to return an error") } client.Jar = jar return r, nil } // ID returns this registry session's ID. func (r *Session) ID() string { return r.id } // Retrieve the history of a given image from the Registry. // Return a list of the parent's json (requested image included) func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) { res, err := r.client.Get(registry + "images/" + imgID + "/ancestry") if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != 200 { if res.StatusCode == 401 { return nil, errLoginRequired } return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res) } var history []string if err := json.NewDecoder(res.Body).Decode(&history); err != nil { return nil, fmt.Errorf("Error while reading the http response: %v", err) } logrus.Debugf("Ancestry: %v", history) return history, nil } // Check if an image exists in the Registry func (r *Session) LookupRemoteImage(imgID, registry string) error { res, err := r.client.Get(registry + "images/" + imgID + "/json") if err != nil { return err } res.Body.Close() if res.StatusCode != 200 { return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) } return nil } // Retrieve an image from the Registry. func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int, error) { res, err := r.client.Get(registry + "images/" + imgID + "/json") if err != nil { return nil, -1, fmt.Errorf("Failed to download json: %s", err) } defer res.Body.Close() if res.StatusCode != 200 { return nil, -1, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) } // if the size header is not present, then set it to '-1' imageSize := -1 if hdr := res.Header.Get("X-Docker-Size"); hdr != "" { imageSize, err = strconv.Atoi(hdr) if err != nil { return nil, -1, err } } jsonString, err := ioutil.ReadAll(res.Body) if err != nil { return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString) } return jsonString, imageSize, nil } func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) { var ( retries = 5 statusCode = 0 res *http.Response err error imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) ) req, err := http.NewRequest("GET", imageURL, nil) if err != nil { return nil, fmt.Errorf("Error while getting from the server: %v", err) } // TODO(tiborvass): why are we doing retries at this level? // These retries should be generic to both v1 and v2 for i := 1; i <= retries; i++ { statusCode = 0 res, err = r.client.Do(req) if err == nil { break } logrus.Debugf("Error contacting registry %s: %v", registry, err) if res != nil { if res.Body != nil { res.Body.Close() } statusCode = res.StatusCode } if i == retries { return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", statusCode, imgID) } time.Sleep(time.Duration(i) * 5 * time.Second) } if res.StatusCode != 200 { res.Body.Close() return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", res.StatusCode, imgID) } if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { logrus.Debugf("server supports resume") return httputils.ResumableRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil } logrus.Debugf("server doesn't support resume") return res.Body, nil } func (r *Session) GetRemoteTag(registries []string, repository string, askedTag string) (string, error) { if strings.Count(repository, "/") == 0 { // This will be removed once the Registry supports auto-resolution on // the "library" namespace repository = "library/" + repository } for _, host := range registries { endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag) res, err := r.client.Get(endpoint) if err != nil { return "", err } logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) defer res.Body.Close() if res.StatusCode == 404 { return "", ErrRepoNotFound } if res.StatusCode != 200 { continue } var tagId string if err := json.NewDecoder(res.Body).Decode(&tagId); err != nil { return "", err } return tagId, nil } return "", fmt.Errorf("Could not reach any registry endpoint") } func (r *Session) GetRemoteTags(registries []string, repository string) (map[string]string, error) { if strings.Count(repository, "/") == 0 { // This will be removed once the Registry supports auto-resolution on // the "library" namespace repository = "library/" + repository } for _, host := range registries { endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository) res, err := r.client.Get(endpoint) if err != nil { return nil, err } logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) defer res.Body.Close() if res.StatusCode == 404 { return nil, ErrRepoNotFound } if res.StatusCode != 200 { continue } result := make(map[string]string) if err := json.NewDecoder(res.Body).Decode(&result); err != nil { return nil, err } return result, nil } return nil, fmt.Errorf("Could not reach any registry endpoint") } func buildEndpointsList(headers []string, indexEp string) ([]string, error) { var endpoints []string parsedURL, err := url.Parse(indexEp) if err != nil { return nil, err } var urlScheme = parsedURL.Scheme // The Registry's URL scheme has to match the Index' for _, ep := range headers { epList := strings.Split(ep, ",") for _, epListElement := range epList { endpoints = append( endpoints, fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement))) } } return endpoints, nil } func (r *Session) GetRepositoryData(remote string) (*RepositoryData, error) { repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.VersionString(1), remote) logrus.Debugf("[registry] Calling GET %s", repositoryTarget) req, err := http.NewRequest("GET", repositoryTarget, nil) if err != nil { return nil, err } // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests req.Header.Set("X-Docker-Token", "true") res, err := r.client.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode == 401 { return nil, errLoginRequired } // TODO: Right now we're ignoring checksums in the response body. // In the future, we need to use them to check image validity. if res.StatusCode == 404 { return nil, httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res) } else if res.StatusCode != 200 { errBody, err := ioutil.ReadAll(res.Body) if err != nil { logrus.Debugf("Error reading response body: %s", err) } return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, remote, errBody), res) } var endpoints []string if res.Header.Get("X-Docker-Endpoints") != "" { endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.VersionString(1)) if err != nil { return nil, err } } else { // Assume the endpoint is on the same host endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host)) } remoteChecksums := []*ImgData{} if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil { return nil, err } // Forge a better object from the retrieved data imgsData := make(map[string]*ImgData, len(remoteChecksums)) for _, elem := range remoteChecksums { imgsData[elem.ID] = elem } return &RepositoryData{ ImgList: imgsData, Endpoints: endpoints, }, nil } func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error { u := registry + "images/" + imgData.ID + "/checksum" logrus.Debugf("[registry] Calling PUT %s", u) req, err := http.NewRequest("PUT", u, nil) if err != nil { return err } req.Header.Set("X-Docker-Checksum", imgData.Checksum) req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload) res, err := r.client.Do(req) if err != nil { return fmt.Errorf("Failed to upload metadata: %v", err) } defer res.Body.Close() if len(res.Cookies()) > 0 { r.client.Jar.SetCookies(req.URL, res.Cookies()) } if res.StatusCode != 200 { errBody, err := ioutil.ReadAll(res.Body) if err != nil { return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err) } var jsonBody map[string]string if err := json.Unmarshal(errBody, &jsonBody); err != nil { errBody = []byte(err.Error()) } else if jsonBody["error"] == "Image already exists" { return ErrAlreadyExists } return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody) } return nil } // Push a local image to the registry func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error { u := registry + "images/" + imgData.ID + "/json" logrus.Debugf("[registry] Calling PUT %s", u) req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw)) if err != nil { return err } req.Header.Add("Content-type", "application/json") res, err := r.client.Do(req) if err != nil { return fmt.Errorf("Failed to upload metadata: %s", err) } defer res.Body.Close() if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") { return httputils.NewHTTPRequestError("HTTP code 401, Docker will not send auth headers over HTTP.", res) } if res.StatusCode != 200 { errBody, err := ioutil.ReadAll(res.Body) if err != nil { return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) } var jsonBody map[string]string if err := json.Unmarshal(errBody, &jsonBody); err != nil { errBody = []byte(err.Error()) } else if jsonBody["error"] == "Image already exists" { return ErrAlreadyExists } return httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res) } return nil } func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) { u := registry + "images/" + imgID + "/layer" logrus.Debugf("[registry] Calling PUT %s", u) tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0) if err != nil { return "", "", err } h := sha256.New() h.Write(jsonRaw) h.Write([]byte{'\n'}) checksumLayer := io.TeeReader(tarsumLayer, h) req, err := http.NewRequest("PUT", u, checksumLayer) if err != nil { return "", "", err } req.Header.Add("Content-Type", "application/octet-stream") req.ContentLength = -1 req.TransferEncoding = []string{"chunked"} res, err := r.client.Do(req) if err != nil { return "", "", fmt.Errorf("Failed to upload layer: %v", err) } if rc, ok := layer.(io.Closer); ok { if err := rc.Close(); err != nil { return "", "", err } } defer res.Body.Close() if res.StatusCode != 200 { errBody, err := ioutil.ReadAll(res.Body) if err != nil { return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) } return "", "", httputils.NewHTTPRequestError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res) } checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil)) return tarsumLayer.Sum(jsonRaw), checksumPayload, nil } // push a tag on the registry. // Remote has the format '/ func (r *Session) PushRegistryTag(remote, revision, tag, registry string) error { // "jsonify" the string revision = "\"" + revision + "\"" path := fmt.Sprintf("repositories/%s/tags/%s", remote, tag) req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision)) if err != nil { return err } req.Header.Add("Content-type", "application/json") req.ContentLength = int64(len(revision)) res, err := r.client.Do(req) if err != nil { return err } res.Body.Close() if res.StatusCode != 200 && res.StatusCode != 201 { return httputils.NewHTTPRequestError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, remote), res) } return nil } func (r *Session) PushImageJSONIndex(remote string, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) { cleanImgList := []*ImgData{} if validate { for _, elem := range imgList { if elem.Checksum != "" { cleanImgList = append(cleanImgList, elem) } } } else { cleanImgList = imgList } imgListJSON, err := json.Marshal(cleanImgList) if err != nil { return nil, err } var suffix string if validate { suffix = "images" } u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.VersionString(1), remote, suffix) logrus.Debugf("[registry] PUT %s", u) logrus.Debugf("Image list pushed to index:\n%s", imgListJSON) headers := map[string][]string{ "Content-type": {"application/json"}, // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests "X-Docker-Token": {"true"}, } if validate { headers["X-Docker-Endpoints"] = regs } // Redirect if necessary var res *http.Response for { if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil { return nil, err } if !shouldRedirect(res) { break } res.Body.Close() u = res.Header.Get("Location") logrus.Debugf("Redirected to %s", u) } defer res.Body.Close() if res.StatusCode == 401 { return nil, errLoginRequired } var tokens, endpoints []string if !validate { if res.StatusCode != 200 && res.StatusCode != 201 { errBody, err := ioutil.ReadAll(res.Body) if err != nil { logrus.Debugf("Error reading response body: %s", err) } return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, remote, errBody), res) } tokens = res.Header["X-Docker-Token"] logrus.Debugf("Auth token: %v", tokens) if res.Header.Get("X-Docker-Endpoints") == "" { return nil, fmt.Errorf("Index response didn't contain any endpoints") } endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.VersionString(1)) if err != nil { return nil, err } } else { if res.StatusCode != 204 { errBody, err := ioutil.ReadAll(res.Body) if err != nil { logrus.Debugf("Error reading response body: %s", err) } return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, remote, errBody), res) } } return &RepositoryData{ Endpoints: endpoints, }, nil } func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) { req, err := http.NewRequest("PUT", u, bytes.NewReader(body)) if err != nil { return nil, err } req.ContentLength = int64(len(body)) for k, v := range headers { req.Header[k] = v } response, err := r.client.Do(req) if err != nil { return nil, err } return response, nil } func shouldRedirect(response *http.Response) bool { return response.StatusCode >= 300 && response.StatusCode < 400 } func (r *Session) SearchRepositories(term string) (*SearchResults, error) { logrus.Debugf("Index server: %s", r.indexEndpoint) u := r.indexEndpoint.VersionString(1) + "search?q=" + url.QueryEscape(term) req, err := http.NewRequest("GET", u, nil) if err != nil { return nil, fmt.Errorf("Error while getting from the server: %v", err) } // Have the AuthTransport send authentication, when logged in. req.Header.Set("X-Docker-Token", "true") res, err := r.client.Do(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != 200 { return nil, httputils.NewHTTPRequestError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res) } result := new(SearchResults) return result, json.NewDecoder(res.Body).Decode(result) } // TODO(tiborvass): remove this once registry client v2 is vendored func (r *Session) GetAuthConfig(withPasswd bool) *cliconfig.AuthConfig { password := "" if withPasswd { password = r.authConfig.Password } return &cliconfig.AuthConfig{ Username: r.authConfig.Username, Password: password, Email: r.authConfig.Email, } } ================================================ FILE: vendor/github.com/docker/docker/registry/token.go ================================================ package registry import ( "encoding/json" "errors" "fmt" "net/http" "net/url" "strings" ) type tokenResponse struct { Token string `json:"token"` } func getToken(username, password string, params map[string]string, registryEndpoint *Endpoint) (string, error) { realm, ok := params["realm"] if !ok { return "", errors.New("no realm specified for token auth challenge") } realmURL, err := url.Parse(realm) if err != nil { return "", fmt.Errorf("invalid token auth challenge realm: %s", err) } if realmURL.Scheme == "" { if registryEndpoint.IsSecure { realmURL.Scheme = "https" } else { realmURL.Scheme = "http" } } req, err := http.NewRequest("GET", realmURL.String(), nil) if err != nil { return "", err } reqParams := req.URL.Query() service := params["service"] scope := params["scope"] if service != "" { reqParams.Add("service", service) } for _, scopeField := range strings.Fields(scope) { reqParams.Add("scope", scopeField) } if username != "" { reqParams.Add("account", username) req.SetBasicAuth(username, password) } req.URL.RawQuery = reqParams.Encode() resp, err := registryEndpoint.client.Do(req) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("token auth attempt for registry %s: %s request failed with status: %d %s", registryEndpoint, req.URL, resp.StatusCode, http.StatusText(resp.StatusCode)) } decoder := json.NewDecoder(resp.Body) tr := new(tokenResponse) if err = decoder.Decode(tr); err != nil { return "", fmt.Errorf("unable to decode token response: %s", err) } if tr.Token == "" { return "", errors.New("authorization server did not include a token in the response") } return tr.Token, nil } ================================================ FILE: vendor/github.com/docker/docker/registry/types.go ================================================ package registry type SearchResult struct { StarCount int `json:"star_count"` IsOfficial bool `json:"is_official"` Name string `json:"name"` IsTrusted bool `json:"is_trusted"` IsAutomated bool `json:"is_automated"` Description string `json:"description"` } type SearchResults struct { Query string `json:"query"` NumResults int `json:"num_results"` Results []SearchResult `json:"results"` } type RepositoryData struct { ImgList map[string]*ImgData Endpoints []string Tokens []string } type ImgData struct { ID string `json:"id"` Checksum string `json:"checksum,omitempty"` ChecksumPayload string `json:"-"` Tag string `json:",omitempty"` } type RegistryInfo struct { Version string `json:"version"` Standalone bool `json:"standalone"` } type APIVersion int func (av APIVersion) String() string { return apiVersions[av] } var apiVersions = map[APIVersion]string{ 1: "v1", 2: "v2", } // API Version identifiers. const ( APIVersionUnknown = iota APIVersion1 APIVersion2 ) // RepositoryInfo Examples: // { // "Index" : { // "Name" : "docker.io", // "Mirrors" : ["https://registry-2.docker.io/v1/", "https://registry-3.docker.io/v1/"], // "Secure" : true, // "Official" : true, // }, // "RemoteName" : "library/debian", // "LocalName" : "debian", // "CanonicalName" : "docker.io/debian" // "Official" : true, // } // { // "Index" : { // "Name" : "127.0.0.1:5000", // "Mirrors" : [], // "Secure" : false, // "Official" : false, // }, // "RemoteName" : "user/repo", // "LocalName" : "127.0.0.1:5000/user/repo", // "CanonicalName" : "127.0.0.1:5000/user/repo", // "Official" : false, // } type IndexInfo struct { Name string Mirrors []string Secure bool Official bool } type RepositoryInfo struct { Index *IndexInfo RemoteName string LocalName string CanonicalName string Official bool } ================================================ FILE: vendor/github.com/docker/docker/runconfig/compare.go ================================================ package runconfig // Compare two Config struct. Do not compare the "Image" nor "Hostname" fields // If OpenStdin is set, then it differs func Compare(a, b *Config) bool { if a == nil || b == nil || a.OpenStdin || b.OpenStdin { return false } if a.AttachStdout != b.AttachStdout || a.AttachStderr != b.AttachStderr || a.User != b.User || a.OpenStdin != b.OpenStdin || a.Tty != b.Tty { return false } if a.Cmd.Len() != b.Cmd.Len() || len(a.Env) != len(b.Env) || len(a.Labels) != len(b.Labels) || len(a.ExposedPorts) != len(b.ExposedPorts) || a.Entrypoint.Len() != b.Entrypoint.Len() || len(a.Volumes) != len(b.Volumes) { return false } aCmd := a.Cmd.Slice() bCmd := b.Cmd.Slice() for i := 0; i < len(aCmd); i++ { if aCmd[i] != bCmd[i] { return false } } for i := 0; i < len(a.Env); i++ { if a.Env[i] != b.Env[i] { return false } } for k, v := range a.Labels { if v != b.Labels[k] { return false } } for k := range a.ExposedPorts { if _, exists := b.ExposedPorts[k]; !exists { return false } } aEntrypoint := a.Entrypoint.Slice() bEntrypoint := b.Entrypoint.Slice() for i := 0; i < len(aEntrypoint); i++ { if aEntrypoint[i] != bEntrypoint[i] { return false } } for key := range a.Volumes { if _, exists := b.Volumes[key]; !exists { return false } } return true } ================================================ FILE: vendor/github.com/docker/docker/runconfig/compare_test.go ================================================ package runconfig import ( "testing" "github.com/docker/docker/pkg/nat" ) // Just to make life easier func newPortNoError(proto, port string) nat.Port { p, _ := nat.NewPort(proto, port) return p } func TestCompare(t *testing.T) { ports1 := make(nat.PortSet) ports1[newPortNoError("tcp", "1111")] = struct{}{} ports1[newPortNoError("tcp", "2222")] = struct{}{} ports2 := make(nat.PortSet) ports2[newPortNoError("tcp", "3333")] = struct{}{} ports2[newPortNoError("tcp", "4444")] = struct{}{} ports3 := make(nat.PortSet) ports3[newPortNoError("tcp", "1111")] = struct{}{} ports3[newPortNoError("tcp", "2222")] = struct{}{} ports3[newPortNoError("tcp", "5555")] = struct{}{} volumes1 := make(map[string]struct{}) volumes1["/test1"] = struct{}{} volumes2 := make(map[string]struct{}) volumes2["/test2"] = struct{}{} volumes3 := make(map[string]struct{}) volumes3["/test1"] = struct{}{} volumes3["/test3"] = struct{}{} envs1 := []string{"ENV1=value1", "ENV2=value2"} envs2 := []string{"ENV1=value1", "ENV3=value3"} entrypoint1 := &Entrypoint{parts: []string{"/bin/sh", "-c"}} entrypoint2 := &Entrypoint{parts: []string{"/bin/sh", "-d"}} entrypoint3 := &Entrypoint{parts: []string{"/bin/sh", "-c", "echo"}} cmd1 := &Command{parts: []string{"/bin/sh", "-c"}} cmd2 := &Command{parts: []string{"/bin/sh", "-d"}} cmd3 := &Command{parts: []string{"/bin/sh", "-c", "echo"}} labels1 := map[string]string{"LABEL1": "value1", "LABEL2": "value2"} labels2 := map[string]string{"LABEL1": "value1", "LABEL2": "value3"} labels3 := map[string]string{"LABEL1": "value1", "LABEL2": "value2", "LABEL3": "value3"} sameConfigs := map[*Config]*Config{ // Empty config &Config{}: {}, // Does not compare hostname, domainname & image &Config{ Hostname: "host1", Domainname: "domain1", Image: "image1", User: "user", }: { Hostname: "host2", Domainname: "domain2", Image: "image2", User: "user", }, // only OpenStdin &Config{OpenStdin: false}: {OpenStdin: false}, // only env &Config{Env: envs1}: {Env: envs1}, // only cmd &Config{Cmd: cmd1}: {Cmd: cmd1}, // only labels &Config{Labels: labels1}: {Labels: labels1}, // only exposedPorts &Config{ExposedPorts: ports1}: {ExposedPorts: ports1}, // only entrypoints &Config{Entrypoint: entrypoint1}: {Entrypoint: entrypoint1}, // only volumes &Config{Volumes: volumes1}: {Volumes: volumes1}, } differentConfigs := map[*Config]*Config{ nil: nil, &Config{ Hostname: "host1", Domainname: "domain1", Image: "image1", User: "user1", }: { Hostname: "host1", Domainname: "domain1", Image: "image1", User: "user2", }, // only OpenStdin &Config{OpenStdin: false}: {OpenStdin: true}, &Config{OpenStdin: true}: {OpenStdin: false}, // only env &Config{Env: envs1}: {Env: envs2}, // only cmd &Config{Cmd: cmd1}: {Cmd: cmd2}, // not the same number of parts &Config{Cmd: cmd1}: {Cmd: cmd3}, // only labels &Config{Labels: labels1}: {Labels: labels2}, // not the same number of labels &Config{Labels: labels1}: {Labels: labels3}, // only exposedPorts &Config{ExposedPorts: ports1}: {ExposedPorts: ports2}, // not the same number of ports &Config{ExposedPorts: ports1}: {ExposedPorts: ports3}, // only entrypoints &Config{Entrypoint: entrypoint1}: {Entrypoint: entrypoint2}, // not the same number of parts &Config{Entrypoint: entrypoint1}: {Entrypoint: entrypoint3}, // only volumes &Config{Volumes: volumes1}: {Volumes: volumes2}, // not the same number of labels &Config{Volumes: volumes1}: {Volumes: volumes3}, } for config1, config2 := range sameConfigs { if !Compare(config1, config2) { t.Fatalf("Compare should be true for [%v] and [%v]", config1, config2) } } for config1, config2 := range differentConfigs { if Compare(config1, config2) { t.Fatalf("Compare should be false for [%v] and [%v]", config1, config2) } } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/config.go ================================================ package runconfig import ( "encoding/json" "io" "strings" "github.com/docker/docker/pkg/nat" ) // Entrypoint encapsulates the container entrypoint. // It might be represented as a string or an array of strings. // We need to override the json decoder to accept both options. // The JSON decoder will fail if the api sends an string and // we try to decode it into an array of string. type Entrypoint struct { parts []string } func (e *Entrypoint) MarshalJSON() ([]byte, error) { if e == nil { return []byte{}, nil } return json.Marshal(e.Slice()) } // UnmarshalJSON decoded the entrypoint whether it's a string or an array of strings. func (e *Entrypoint) UnmarshalJSON(b []byte) error { if len(b) == 0 { return nil } p := make([]string, 0, 1) if err := json.Unmarshal(b, &p); err != nil { var s string if err := json.Unmarshal(b, &s); err != nil { return err } p = append(p, s) } e.parts = p return nil } func (e *Entrypoint) Len() int { if e == nil { return 0 } return len(e.parts) } func (e *Entrypoint) Slice() []string { if e == nil { return nil } return e.parts } func NewEntrypoint(parts ...string) *Entrypoint { return &Entrypoint{parts} } type Command struct { parts []string } func (e *Command) ToString() string { return strings.Join(e.parts, " ") } func (e *Command) MarshalJSON() ([]byte, error) { if e == nil { return []byte{}, nil } return json.Marshal(e.Slice()) } // UnmarshalJSON decoded the entrypoint whether it's a string or an array of strings. func (e *Command) UnmarshalJSON(b []byte) error { if len(b) == 0 { return nil } p := make([]string, 0, 1) if err := json.Unmarshal(b, &p); err != nil { var s string if err := json.Unmarshal(b, &s); err != nil { return err } p = append(p, s) } e.parts = p return nil } func (e *Command) Len() int { if e == nil { return 0 } return len(e.parts) } func (e *Command) Slice() []string { if e == nil { return nil } return e.parts } func NewCommand(parts ...string) *Command { return &Command{parts} } // Note: the Config structure should hold only portable information about the container. // Here, "portable" means "independent from the host we are running on". // Non-portable information *should* appear in HostConfig. type Config struct { Hostname string Domainname string User string AttachStdin bool AttachStdout bool AttachStderr bool ExposedPorts map[nat.Port]struct{} PublishService string Tty bool // Attach standard streams to a tty, including stdin if it is not closed. OpenStdin bool // Open stdin StdinOnce bool // If true, close stdin after the 1 attached client disconnects. Env []string Cmd *Command Image string // Name of the image as it was passed by the operator (eg. could be symbolic) Volumes map[string]struct{} VolumeDriver string WorkingDir string Entrypoint *Entrypoint NetworkDisabled bool MacAddress string OnBuild []string Labels map[string]string } type ContainerConfigWrapper struct { *Config InnerHostConfig *HostConfig `json:"HostConfig,omitempty"` Cpuset string `json:",omitempty"` // Deprecated. Exported for backwards compatibility. *HostConfig // Deprecated. Exported to read attrubutes from json that are not in the inner host config structure. } func (w *ContainerConfigWrapper) GetHostConfig() *HostConfig { hc := w.HostConfig if hc == nil && w.InnerHostConfig != nil { hc = w.InnerHostConfig } else if w.InnerHostConfig != nil { if hc.Memory != 0 && w.InnerHostConfig.Memory == 0 { w.InnerHostConfig.Memory = hc.Memory } if hc.MemorySwap != 0 && w.InnerHostConfig.MemorySwap == 0 { w.InnerHostConfig.MemorySwap = hc.MemorySwap } if hc.CpuShares != 0 && w.InnerHostConfig.CpuShares == 0 { w.InnerHostConfig.CpuShares = hc.CpuShares } hc = w.InnerHostConfig } if hc != nil && w.Cpuset != "" && hc.CpusetCpus == "" { hc.CpusetCpus = w.Cpuset } return hc } // DecodeContainerConfig decodes a json encoded config into a ContainerConfigWrapper // struct and returns both a Config and an HostConfig struct // Be aware this function is not checking whether the resulted structs are nil, // it's your business to do so func DecodeContainerConfig(src io.Reader) (*Config, *HostConfig, error) { decoder := json.NewDecoder(src) var w ContainerConfigWrapper if err := decoder.Decode(&w); err != nil { return nil, nil, err } return w.Config, w.GetHostConfig(), nil } ================================================ FILE: vendor/github.com/docker/docker/runconfig/config_test.go ================================================ package runconfig import ( "bytes" "encoding/json" "fmt" "io/ioutil" "testing" ) func TestEntrypointMarshalJSON(t *testing.T) { entrypoints := map[*Entrypoint]string{ nil: "", &Entrypoint{}: "null", &Entrypoint{[]string{"/bin/sh", "-c", "echo"}}: `["/bin/sh","-c","echo"]`, } for entrypoint, expected := range entrypoints { data, err := entrypoint.MarshalJSON() if err != nil { t.Fatal(err) } if string(data) != expected { t.Fatalf("Expected %v, got %v", expected, string(data)) } } } func TestEntrypointUnmarshalJSON(t *testing.T) { parts := map[string][]string{ "": {"default", "values"}, "[]": {}, `["/bin/sh","-c","echo"]`: {"/bin/sh", "-c", "echo"}, } for json, expectedParts := range parts { entrypoint := &Entrypoint{ []string{"default", "values"}, } if err := entrypoint.UnmarshalJSON([]byte(json)); err != nil { t.Fatal(err) } actualParts := entrypoint.Slice() if len(actualParts) != len(expectedParts) { t.Fatalf("Expected %v parts, got %v (%v)", len(expectedParts), len(actualParts), expectedParts) } for index, part := range actualParts { if part != expectedParts[index] { t.Fatalf("Expected %v, got %v", expectedParts, actualParts) break } } } } func TestCommandToString(t *testing.T) { commands := map[*Command]string{ &Command{[]string{""}}: "", &Command{[]string{"one"}}: "one", &Command{[]string{"one", "two"}}: "one two", } for command, expected := range commands { toString := command.ToString() if toString != expected { t.Fatalf("Expected %v, got %v", expected, toString) } } } func TestCommandMarshalJSON(t *testing.T) { commands := map[*Command]string{ nil: "", &Command{}: "null", &Command{[]string{"/bin/sh", "-c", "echo"}}: `["/bin/sh","-c","echo"]`, } for command, expected := range commands { data, err := command.MarshalJSON() if err != nil { t.Fatal(err) } if string(data) != expected { t.Fatalf("Expected %v, got %v", expected, string(data)) } } } func TestCommandUnmarshalJSON(t *testing.T) { parts := map[string][]string{ "": {"default", "values"}, "[]": {}, `["/bin/sh","-c","echo"]`: {"/bin/sh", "-c", "echo"}, } for json, expectedParts := range parts { command := &Command{ []string{"default", "values"}, } if err := command.UnmarshalJSON([]byte(json)); err != nil { t.Fatal(err) } actualParts := command.Slice() if len(actualParts) != len(expectedParts) { t.Fatalf("Expected %v parts, got %v (%v)", len(expectedParts), len(actualParts), expectedParts) } for index, part := range actualParts { if part != expectedParts[index] { t.Fatalf("Expected %v, got %v", expectedParts, actualParts) break } } } } func TestDecodeContainerConfig(t *testing.T) { fixtures := []struct { file string entrypoint *Entrypoint }{ {"fixtures/container_config_1_14.json", NewEntrypoint()}, {"fixtures/container_config_1_17.json", NewEntrypoint("bash")}, {"fixtures/container_config_1_19.json", NewEntrypoint("bash")}, } for _, f := range fixtures { b, err := ioutil.ReadFile(f.file) if err != nil { t.Fatal(err) } c, h, err := DecodeContainerConfig(bytes.NewReader(b)) if err != nil { t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err)) } if c.Image != "ubuntu" { t.Fatalf("Expected ubuntu image, found %s\n", c.Image) } if c.Entrypoint.Len() != f.entrypoint.Len() { t.Fatalf("Expected %v, found %v\n", f.entrypoint, c.Entrypoint) } if h.Memory != 1000 { t.Fatalf("Expected memory to be 1000, found %d\n", h.Memory) } } } func TestEntrypointUnmarshalString(t *testing.T) { var e *Entrypoint echo, err := json.Marshal("echo") if err != nil { t.Fatal(err) } if err := json.Unmarshal(echo, &e); err != nil { t.Fatal(err) } slice := e.Slice() if len(slice) != 1 { t.Fatalf("expected 1 element after unmarshal: %q", slice) } if slice[0] != "echo" { t.Fatalf("expected `echo`, got: %q", slice[0]) } } func TestEntrypointUnmarshalSlice(t *testing.T) { var e *Entrypoint echo, err := json.Marshal([]string{"echo"}) if err != nil { t.Fatal(err) } if err := json.Unmarshal(echo, &e); err != nil { t.Fatal(err) } slice := e.Slice() if len(slice) != 1 { t.Fatalf("expected 1 element after unmarshal: %q", slice) } if slice[0] != "echo" { t.Fatalf("expected `echo`, got: %q", slice[0]) } } func TestCommandUnmarshalSlice(t *testing.T) { var e *Command echo, err := json.Marshal([]string{"echo"}) if err != nil { t.Fatal(err) } if err := json.Unmarshal(echo, &e); err != nil { t.Fatal(err) } slice := e.Slice() if len(slice) != 1 { t.Fatalf("expected 1 element after unmarshal: %q", slice) } if slice[0] != "echo" { t.Fatalf("expected `echo`, got: %q", slice[0]) } } func TestCommandUnmarshalString(t *testing.T) { var e *Command echo, err := json.Marshal("echo") if err != nil { t.Fatal(err) } if err := json.Unmarshal(echo, &e); err != nil { t.Fatal(err) } slice := e.Slice() if len(slice) != 1 { t.Fatalf("expected 1 element after unmarshal: %q", slice) } if slice[0] != "echo" { t.Fatalf("expected `echo`, got: %q", slice[0]) } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/exec.go ================================================ package runconfig import ( flag "github.com/docker/docker/pkg/mflag" ) type ExecConfig struct { User string Privileged bool Tty bool Container string AttachStdin bool AttachStderr bool AttachStdout bool Detach bool Cmd []string } func ParseExec(cmd *flag.FlagSet, args []string) (*ExecConfig, error) { var ( flStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached") flTty = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY") flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Detached mode: run command in the background") flUser = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: [:])") execCmd []string container string ) cmd.Require(flag.Min, 2) if err := cmd.ParseFlags(args, true); err != nil { return nil, err } container = cmd.Arg(0) parsedArgs := cmd.Args() execCmd = parsedArgs[1:] execConfig := &ExecConfig{ User: *flUser, // TODO(vishh): Expose 'Privileged' once it is supported. // + //Privileged: job.GetenvBool("Privileged"), Tty: *flTty, Cmd: execCmd, Container: container, Detach: *flDetach, } // If -d is not set, attach to everything by default if !*flDetach { execConfig.AttachStdout = true execConfig.AttachStderr = true if *flStdin { execConfig.AttachStdin = true } } return execConfig, nil } ================================================ FILE: vendor/github.com/docker/docker/runconfig/exec_test.go ================================================ package runconfig import ( "fmt" "io/ioutil" "testing" flag "github.com/docker/docker/pkg/mflag" ) type arguments struct { args []string } func TestParseExec(t *testing.T) { invalids := map[*arguments]error{ &arguments{[]string{"-unknown"}}: fmt.Errorf("flag provided but not defined: -unknown"), &arguments{[]string{"-u"}}: fmt.Errorf("flag needs an argument: -u"), &arguments{[]string{"--user"}}: fmt.Errorf("flag needs an argument: --user"), } valids := map[*arguments]*ExecConfig{ &arguments{ []string{"container", "command"}, }: { Container: "container", Cmd: []string{"command"}, AttachStdout: true, AttachStderr: true, }, &arguments{ []string{"container", "command1", "command2"}, }: { Container: "container", Cmd: []string{"command1", "command2"}, AttachStdout: true, AttachStderr: true, }, &arguments{ []string{"-i", "-t", "-u", "uid", "container", "command"}, }: { User: "uid", AttachStdin: true, AttachStdout: true, AttachStderr: true, Tty: true, Container: "container", Cmd: []string{"command"}, }, &arguments{ []string{"-d", "container", "command"}, }: { AttachStdin: false, AttachStdout: false, AttachStderr: false, Detach: true, Container: "container", Cmd: []string{"command"}, }, &arguments{ []string{"-t", "-i", "-d", "container", "command"}, }: { AttachStdin: false, AttachStdout: false, AttachStderr: false, Detach: true, Tty: true, Container: "container", Cmd: []string{"command"}, }, } for invalid, expectedError := range invalids { cmd := flag.NewFlagSet("exec", flag.ContinueOnError) cmd.ShortUsage = func() {} cmd.SetOutput(ioutil.Discard) _, err := ParseExec(cmd, invalid.args) if err == nil || err.Error() != expectedError.Error() { t.Fatalf("Expected an error [%v] for %v, got %v", expectedError, invalid, err) } } for valid, expectedExecConfig := range valids { cmd := flag.NewFlagSet("exec", flag.ContinueOnError) cmd.ShortUsage = func() {} cmd.SetOutput(ioutil.Discard) execConfig, err := ParseExec(cmd, valid.args) if err != nil { t.Fatal(err) } if !compareExecConfig(expectedExecConfig, execConfig) { t.Fatalf("Expected [%v] for %v, got [%v]", expectedExecConfig, valid, execConfig) } } } func compareExecConfig(config1 *ExecConfig, config2 *ExecConfig) bool { if config1.AttachStderr != config2.AttachStderr { return false } if config1.AttachStdin != config2.AttachStdin { return false } if config1.AttachStdout != config2.AttachStdout { return false } if config1.Container != config2.Container { return false } if config1.Detach != config2.Detach { return false } if config1.Privileged != config2.Privileged { return false } if config1.Tty != config2.Tty { return false } if config1.User != config2.User { return false } if len(config1.Cmd) != len(config2.Cmd) { return false } for index, value := range config1.Cmd { if value != config2.Cmd[index] { return false } } return true } ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/container_config_1_14.json ================================================ { "Hostname":"", "Domainname": "", "User":"", "Memory": 1000, "MemorySwap":0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":[ "bash" ], "Image":"ubuntu", "Volumes":{ "/tmp": {} }, "WorkingDir":"", "NetworkDisabled": false, "ExposedPorts":{ "22/tcp": {} }, "RestartPolicy": { "Name": "always" } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/container_config_1_17.json ================================================ { "Hostname": "", "Domainname": "", "User": "", "Memory": 1000, "MemorySwap": 0, "CpuShares": 512, "Cpuset": "0,1", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "bash", "Image": "ubuntu", "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "SecurityOpt": [""], "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [] } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/container_config_1_19.json ================================================ { "Hostname": "", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Entrypoint": "bash", "Image": "ubuntu", "Labels": { "com.example.vendor": "Acme", "com.example.license": "GPL", "com.example.version": "1.0" }, "Volumes": { "/tmp": {} }, "WorkingDir": "", "NetworkDisabled": false, "MacAddress": "12:34:56:78:9a:bc", "ExposedPorts": { "22/tcp": {} }, "HostConfig": { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "Memory": 1000, "MemorySwap": 0, "CpuShares": 512, "CpusetCpus": "0,1", "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [], "Ulimits": [{}], "LogConfig": { "Type": "json-file", "Config": {} }, "SecurityOpt": [""], "CgroupParent": "" } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/container_hostconfig_1_14.json ================================================ { "Binds": ["/tmp:/tmp"], "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": ["/name:alias"], "PublishAllPorts": false, "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"] } ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/container_hostconfig_1_19.json ================================================ { "Binds": ["/tmp:/tmp"], "Links": ["redis3:redis"], "LxcConf": {"lxc.utsname":"docker"}, "Memory": 0, "MemorySwap": 0, "CpuShares": 512, "CpuPeriod": 100000, "CpusetCpus": "0,1", "CpusetMems": "0,1", "BlkioWeight": 300, "OomKillDisable": false, "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, "PublishAllPorts": false, "Privileged": false, "ReadonlyRootfs": false, "Dns": ["8.8.8.8"], "DnsSearch": [""], "ExtraHosts": null, "VolumesFrom": ["parent", "other:ro"], "CapAdd": ["NET_ADMIN"], "CapDrop": ["MKNOD"], "RestartPolicy": { "Name": "", "MaximumRetryCount": 0 }, "NetworkMode": "bridge", "Devices": [], "Ulimits": [{}], "LogConfig": { "Type": "json-file", "Config": {} }, "SecurityOpt": [""], "CgroupParent": "" } ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/valid.env ================================================ ENV1=value1 ================================================ FILE: vendor/github.com/docker/docker/runconfig/fixtures/valid.label ================================================ LABEL1=value1 ================================================ FILE: vendor/github.com/docker/docker/runconfig/hostconfig.go ================================================ package runconfig import ( "encoding/json" "io" "strings" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/ulimit" ) type KeyValuePair struct { Key string Value string } type NetworkMode string type IpcMode string // IsPrivate indicates whether container use it's private ipc stack func (n IpcMode) IsPrivate() bool { return !(n.IsHost() || n.IsContainer()) } func (n IpcMode) IsHost() bool { return n == "host" } func (n IpcMode) IsContainer() bool { parts := strings.SplitN(string(n), ":", 2) return len(parts) > 1 && parts[0] == "container" } func (n IpcMode) Valid() bool { parts := strings.Split(string(n), ":") switch mode := parts[0]; mode { case "", "host": case "container": if len(parts) != 2 || parts[1] == "" { return false } default: return false } return true } func (n IpcMode) Container() string { parts := strings.SplitN(string(n), ":", 2) if len(parts) > 1 { return parts[1] } return "" } type UTSMode string // IsPrivate indicates whether container use it's private UTS namespace func (n UTSMode) IsPrivate() bool { return !(n.IsHost()) } func (n UTSMode) IsHost() bool { return n == "host" } func (n UTSMode) Valid() bool { parts := strings.Split(string(n), ":") switch mode := parts[0]; mode { case "", "host": default: return false } return true } type PidMode string // IsPrivate indicates whether container use it's private pid stack func (n PidMode) IsPrivate() bool { return !(n.IsHost()) } func (n PidMode) IsHost() bool { return n == "host" } func (n PidMode) Valid() bool { parts := strings.Split(string(n), ":") switch mode := parts[0]; mode { case "", "host": default: return false } return true } type DeviceMapping struct { PathOnHost string PathInContainer string CgroupPermissions string } type RestartPolicy struct { Name string MaximumRetryCount int } func (rp *RestartPolicy) IsNone() bool { return rp.Name == "no" } func (rp *RestartPolicy) IsAlways() bool { return rp.Name == "always" } func (rp *RestartPolicy) IsOnFailure() bool { return rp.Name == "on-failure" } type LogConfig struct { Type string Config map[string]string } type LxcConfig struct { values []KeyValuePair } func (c *LxcConfig) MarshalJSON() ([]byte, error) { if c == nil { return []byte{}, nil } return json.Marshal(c.Slice()) } func (c *LxcConfig) UnmarshalJSON(b []byte) error { if len(b) == 0 { return nil } var kv []KeyValuePair if err := json.Unmarshal(b, &kv); err != nil { var h map[string]string if err := json.Unmarshal(b, &h); err != nil { return err } for k, v := range h { kv = append(kv, KeyValuePair{k, v}) } } c.values = kv return nil } func (c *LxcConfig) Len() int { if c == nil { return 0 } return len(c.values) } func (c *LxcConfig) Slice() []KeyValuePair { if c == nil { return nil } return c.values } func NewLxcConfig(values []KeyValuePair) *LxcConfig { return &LxcConfig{values} } type CapList struct { caps []string } func (c *CapList) MarshalJSON() ([]byte, error) { if c == nil { return []byte{}, nil } return json.Marshal(c.Slice()) } func (c *CapList) UnmarshalJSON(b []byte) error { if len(b) == 0 { return nil } var caps []string if err := json.Unmarshal(b, &caps); err != nil { var s string if err := json.Unmarshal(b, &s); err != nil { return err } caps = append(caps, s) } c.caps = caps return nil } func (c *CapList) Len() int { if c == nil { return 0 } return len(c.caps) } func (c *CapList) Slice() []string { if c == nil { return nil } return c.caps } func NewCapList(caps []string) *CapList { return &CapList{caps} } type HostConfig struct { Binds []string ContainerIDFile string LxcConf *LxcConfig Memory int64 // Memory limit (in bytes) MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap CpuShares int64 // CPU shares (relative weight vs. other containers) CpuPeriod int64 CpusetCpus string // CpusetCpus 0-2, 0,1 CpusetMems string // CpusetMems 0-2, 0,1 CpuQuota int64 BlkioWeight int64 // Block IO weight (relative weight vs. other containers) OomKillDisable bool // Whether to disable OOM Killer or not MemorySwappiness int64 // Tuning container memory swappiness behaviour Privileged bool PortBindings nat.PortMap Links []string PublishAllPorts bool Dns []string DnsSearch []string ExtraHosts []string VolumesFrom []string Devices []DeviceMapping NetworkMode NetworkMode IpcMode IpcMode PidMode PidMode UTSMode UTSMode CapAdd *CapList CapDrop *CapList GroupAdd []string RestartPolicy RestartPolicy SecurityOpt []string ReadonlyRootfs bool Ulimits []*ulimit.Ulimit LogConfig LogConfig CgroupParent string // Parent cgroup. ConsoleSize [2]int // Initial console size on Windows } func MergeConfigs(config *Config, hostConfig *HostConfig) *ContainerConfigWrapper { return &ContainerConfigWrapper{ config, hostConfig, "", nil, } } func DecodeHostConfig(src io.Reader) (*HostConfig, error) { decoder := json.NewDecoder(src) var w ContainerConfigWrapper if err := decoder.Decode(&w); err != nil { return nil, err } hc := w.GetHostConfig() return hc, nil } ================================================ FILE: vendor/github.com/docker/docker/runconfig/hostconfig_test.go ================================================ package runconfig import ( "bytes" "encoding/json" "fmt" "io/ioutil" "testing" ) func TestNetworkModeTest(t *testing.T) { networkModes := map[NetworkMode][]bool{ // private, bridge, host, container, none, default "": {true, false, false, false, false, false}, "something:weird": {true, false, false, false, false, false}, "bridge": {true, true, false, false, false, false}, DefaultDaemonNetworkMode(): {true, true, false, false, false, false}, "host": {false, false, true, false, false, false}, "container:name": {false, false, false, true, false, false}, "none": {true, false, false, false, true, false}, "default": {true, false, false, false, false, true}, } networkModeNames := map[NetworkMode]string{ "": "", "something:weird": "", "bridge": "bridge", DefaultDaemonNetworkMode(): "bridge", "host": "host", "container:name": "container", "none": "none", "default": "default", } for networkMode, state := range networkModes { if networkMode.IsPrivate() != state[0] { t.Fatalf("NetworkMode.IsPrivate for %v should have been %v but was %v", networkMode, state[0], networkMode.IsPrivate()) } if networkMode.IsBridge() != state[1] { t.Fatalf("NetworkMode.IsBridge for %v should have been %v but was %v", networkMode, state[1], networkMode.IsBridge()) } if networkMode.IsHost() != state[2] { t.Fatalf("NetworkMode.IsHost for %v should have been %v but was %v", networkMode, state[2], networkMode.IsHost()) } if networkMode.IsContainer() != state[3] { t.Fatalf("NetworkMode.IsContainer for %v should have been %v but was %v", networkMode, state[3], networkMode.IsContainer()) } if networkMode.IsNone() != state[4] { t.Fatalf("NetworkMode.IsNone for %v should have been %v but was %v", networkMode, state[4], networkMode.IsNone()) } if networkMode.IsDefault() != state[5] { t.Fatalf("NetworkMode.IsDefault for %v should have been %v but was %v", networkMode, state[5], networkMode.IsDefault()) } if networkMode.NetworkName() != networkModeNames[networkMode] { t.Fatalf("Expected name %v, got %v", networkModeNames[networkMode], networkMode.NetworkName()) } } } func TestIpcModeTest(t *testing.T) { ipcModes := map[IpcMode][]bool{ // private, host, container, valid "": {true, false, false, true}, "something:weird": {true, false, false, false}, ":weird": {true, false, false, true}, "host": {false, true, false, true}, "container:name": {false, false, true, true}, "container:name:something": {false, false, true, false}, "container:": {false, false, true, false}, } for ipcMode, state := range ipcModes { if ipcMode.IsPrivate() != state[0] { t.Fatalf("IpcMode.IsPrivate for %v should have been %v but was %v", ipcMode, state[0], ipcMode.IsPrivate()) } if ipcMode.IsHost() != state[1] { t.Fatalf("IpcMode.IsHost for %v should have been %v but was %v", ipcMode, state[1], ipcMode.IsHost()) } if ipcMode.IsContainer() != state[2] { t.Fatalf("IpcMode.IsContainer for %v should have been %v but was %v", ipcMode, state[2], ipcMode.IsContainer()) } if ipcMode.Valid() != state[3] { t.Fatalf("IpcMode.Valid for %v should have been %v but was %v", ipcMode, state[3], ipcMode.Valid()) } } containerIpcModes := map[IpcMode]string{ "": "", "something": "", "something:weird": "weird", "container": "", "container:": "", "container:name": "name", "container:name1:name2": "name1:name2", } for ipcMode, container := range containerIpcModes { if ipcMode.Container() != container { t.Fatalf("Expected %v for %v but was %v", container, ipcMode, ipcMode.Container()) } } } func TestUTSModeTest(t *testing.T) { utsModes := map[UTSMode][]bool{ // private, host, valid "": {true, false, true}, "something:weird": {true, false, false}, "host": {false, true, true}, "host:name": {true, false, true}, } for utsMode, state := range utsModes { if utsMode.IsPrivate() != state[0] { t.Fatalf("UtsMode.IsPrivate for %v should have been %v but was %v", utsMode, state[0], utsMode.IsPrivate()) } if utsMode.IsHost() != state[1] { t.Fatalf("UtsMode.IsHost for %v should have been %v but was %v", utsMode, state[1], utsMode.IsHost()) } if utsMode.Valid() != state[2] { t.Fatalf("UtsMode.Valid for %v should have been %v but was %v", utsMode, state[2], utsMode.Valid()) } } } func TestPidModeTest(t *testing.T) { pidModes := map[PidMode][]bool{ // private, host, valid "": {true, false, true}, "something:weird": {true, false, false}, "host": {false, true, true}, "host:name": {true, false, true}, } for pidMode, state := range pidModes { if pidMode.IsPrivate() != state[0] { t.Fatalf("PidMode.IsPrivate for %v should have been %v but was %v", pidMode, state[0], pidMode.IsPrivate()) } if pidMode.IsHost() != state[1] { t.Fatalf("PidMode.IsHost for %v should have been %v but was %v", pidMode, state[1], pidMode.IsHost()) } if pidMode.Valid() != state[2] { t.Fatalf("PidMode.Valid for %v should have been %v but was %v", pidMode, state[2], pidMode.Valid()) } } } func TestRestartPolicy(t *testing.T) { restartPolicies := map[RestartPolicy][]bool{ // none, always, failure RestartPolicy{}: {false, false, false}, RestartPolicy{"something", 0}: {false, false, false}, RestartPolicy{"no", 0}: {true, false, false}, RestartPolicy{"always", 0}: {false, true, false}, RestartPolicy{"on-failure", 0}: {false, false, true}, } for restartPolicy, state := range restartPolicies { if restartPolicy.IsNone() != state[0] { t.Fatalf("RestartPolicy.IsNone for %v should have been %v but was %v", restartPolicy, state[0], restartPolicy.IsNone()) } if restartPolicy.IsAlways() != state[1] { t.Fatalf("RestartPolicy.IsAlways for %v should have been %v but was %v", restartPolicy, state[1], restartPolicy.IsAlways()) } if restartPolicy.IsOnFailure() != state[2] { t.Fatalf("RestartPolicy.IsOnFailure for %v should have been %v but was %v", restartPolicy, state[2], restartPolicy.IsOnFailure()) } } } func TestLxcConfigMarshalJSON(t *testing.T) { lxcConfigs := map[*LxcConfig]string{ nil: "", &LxcConfig{}: "null", &LxcConfig{ []KeyValuePair{{"key1", "value1"}}, }: `[{"Key":"key1","Value":"value1"}]`, } for lxcconfig, expected := range lxcConfigs { data, err := lxcconfig.MarshalJSON() if err != nil { t.Fatal(err) } if string(data) != expected { t.Fatalf("Expected %v, got %v", expected, string(data)) } } } func TestLxcConfigUnmarshalJSON(t *testing.T) { keyvaluePairs := map[string][]KeyValuePair{ "": {{"key1", "value1"}}, "[]": {}, `[{"Key":"key2","Value":"value2"}]`: {{"key2", "value2"}}, } for json, expectedParts := range keyvaluePairs { lxcConfig := &LxcConfig{ []KeyValuePair{{"key1", "value1"}}, } if err := lxcConfig.UnmarshalJSON([]byte(json)); err != nil { t.Fatal(err) } actualParts := lxcConfig.Slice() if len(actualParts) != len(expectedParts) { t.Fatalf("Expected %v keyvaluePairs, got %v (%v)", len(expectedParts), len(actualParts), expectedParts) } for index, part := range actualParts { if part != expectedParts[index] { t.Fatalf("Expected %v, got %v", expectedParts, actualParts) break } } } } func TestMergeConfigs(t *testing.T) { expectedHostname := "hostname" expectedContainerIDFile := "containerIdFile" config := &Config{ Hostname: expectedHostname, } hostConfig := &HostConfig{ ContainerIDFile: expectedContainerIDFile, } containerConfigWrapper := MergeConfigs(config, hostConfig) if containerConfigWrapper.Config.Hostname != expectedHostname { t.Fatalf("containerConfigWrapper config hostname expected %v got %v", expectedHostname, containerConfigWrapper.Config.Hostname) } if containerConfigWrapper.InnerHostConfig.ContainerIDFile != expectedContainerIDFile { t.Fatalf("containerConfigWrapper hostconfig containerIdfile expected %v got %v", expectedContainerIDFile, containerConfigWrapper.InnerHostConfig.ContainerIDFile) } if containerConfigWrapper.Cpuset != "" { t.Fatalf("Expected empty Cpuset, got %v", containerConfigWrapper.Cpuset) } } func TestDecodeHostConfig(t *testing.T) { fixtures := []struct { file string }{ {"fixtures/container_hostconfig_1_14.json"}, {"fixtures/container_hostconfig_1_19.json"}, } for _, f := range fixtures { b, err := ioutil.ReadFile(f.file) if err != nil { t.Fatal(err) } c, err := DecodeHostConfig(bytes.NewReader(b)) if err != nil { t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err)) } if c.Privileged != false { t.Fatalf("Expected privileged false, found %v\n", c.Privileged) } if l := len(c.Binds); l != 1 { t.Fatalf("Expected 1 bind, found %d\n", l) } if c.CapAdd.Len() != 1 && c.CapAdd.Slice()[0] != "NET_ADMIN" { t.Fatalf("Expected CapAdd NET_ADMIN, got %v", c.CapAdd) } if c.CapDrop.Len() != 1 && c.CapDrop.Slice()[0] != "NET_ADMIN" { t.Fatalf("Expected CapDrop MKNOD, got %v", c.CapDrop) } } } func TestCapListUnmarshalSliceAndString(t *testing.T) { var cl *CapList cap0, err := json.Marshal([]string{"CAP_SOMETHING"}) if err != nil { t.Fatal(err) } if err := json.Unmarshal(cap0, &cl); err != nil { t.Fatal(err) } slice := cl.Slice() if len(slice) != 1 { t.Fatalf("expected 1 element after unmarshal: %q", slice) } if slice[0] != "CAP_SOMETHING" { t.Fatalf("expected `CAP_SOMETHING`, got: %q", slice[0]) } cap1, err := json.Marshal("CAP_SOMETHING") if err != nil { t.Fatal(err) } if err := json.Unmarshal(cap1, &cl); err != nil { t.Fatal(err) } slice = cl.Slice() if len(slice) != 1 { t.Fatalf("expected 1 element after unmarshal: %q", slice) } if slice[0] != "CAP_SOMETHING" { t.Fatalf("expected `CAP_SOMETHING`, got: %q", slice[0]) } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/hostconfig_unix.go ================================================ // +build !windows package runconfig import ( "strings" ) // IsPrivate indicates whether container use it's private network stack func (n NetworkMode) IsPrivate() bool { return !(n.IsHost() || n.IsContainer()) } func (n NetworkMode) IsDefault() bool { return n == "default" } func DefaultDaemonNetworkMode() NetworkMode { return NetworkMode("bridge") } func (n NetworkMode) NetworkName() string { if n.IsBridge() { return "bridge" } else if n.IsHost() { return "host" } else if n.IsContainer() { return "container" } else if n.IsNone() { return "none" } else if n.IsDefault() { return "default" } return "" } func (n NetworkMode) IsBridge() bool { return n == "bridge" } func (n NetworkMode) IsHost() bool { return n == "host" } func (n NetworkMode) IsContainer() bool { parts := strings.SplitN(string(n), ":", 2) return len(parts) > 1 && parts[0] == "container" } func (n NetworkMode) IsNone() bool { return n == "none" } ================================================ FILE: vendor/github.com/docker/docker/runconfig/hostconfig_windows.go ================================================ package runconfig func (n NetworkMode) IsDefault() bool { return n == "default" } func DefaultDaemonNetworkMode() NetworkMode { return NetworkMode("default") } func (n NetworkMode) NetworkName() string { if n.IsDefault() { return "default" } return "" } ================================================ FILE: vendor/github.com/docker/docker/runconfig/merge.go ================================================ package runconfig import ( "strings" "github.com/docker/docker/pkg/nat" ) func Merge(userConf, imageConf *Config) error { if userConf.User == "" { userConf.User = imageConf.User } if len(userConf.ExposedPorts) == 0 { userConf.ExposedPorts = imageConf.ExposedPorts } else if imageConf.ExposedPorts != nil { if userConf.ExposedPorts == nil { userConf.ExposedPorts = make(nat.PortSet) } for port := range imageConf.ExposedPorts { if _, exists := userConf.ExposedPorts[port]; !exists { userConf.ExposedPorts[port] = struct{}{} } } } if len(userConf.Env) == 0 { userConf.Env = imageConf.Env } else { for _, imageEnv := range imageConf.Env { found := false imageEnvKey := strings.Split(imageEnv, "=")[0] for _, userEnv := range userConf.Env { userEnvKey := strings.Split(userEnv, "=")[0] if imageEnvKey == userEnvKey { found = true break } } if !found { userConf.Env = append(userConf.Env, imageEnv) } } } if userConf.Entrypoint.Len() == 0 { if userConf.Cmd.Len() == 0 { userConf.Cmd = imageConf.Cmd } if userConf.Entrypoint == nil { userConf.Entrypoint = imageConf.Entrypoint } } if userConf.WorkingDir == "" { userConf.WorkingDir = imageConf.WorkingDir } if len(userConf.Volumes) == 0 { userConf.Volumes = imageConf.Volumes } else { for k, v := range imageConf.Volumes { userConf.Volumes[k] = v } } return nil } ================================================ FILE: vendor/github.com/docker/docker/runconfig/merge_test.go ================================================ package runconfig import ( "testing" "github.com/docker/docker/pkg/nat" ) func TestMerge(t *testing.T) { volumesImage := make(map[string]struct{}) volumesImage["/test1"] = struct{}{} volumesImage["/test2"] = struct{}{} portsImage := make(nat.PortSet) portsImage[newPortNoError("tcp", "1111")] = struct{}{} portsImage[newPortNoError("tcp", "2222")] = struct{}{} configImage := &Config{ ExposedPorts: portsImage, Env: []string{"VAR1=1", "VAR2=2"}, Volumes: volumesImage, } portsUser := make(nat.PortSet) portsUser[newPortNoError("tcp", "2222")] = struct{}{} portsUser[newPortNoError("tcp", "3333")] = struct{}{} volumesUser := make(map[string]struct{}) volumesUser["/test3"] = struct{}{} configUser := &Config{ ExposedPorts: portsUser, Env: []string{"VAR2=3", "VAR3=3"}, Volumes: volumesUser, } if err := Merge(configUser, configImage); err != nil { t.Error(err) } if len(configUser.ExposedPorts) != 3 { t.Fatalf("Expected 3 ExposedPorts, 1111, 2222 and 3333, found %d", len(configUser.ExposedPorts)) } for portSpecs := range configUser.ExposedPorts { if portSpecs.Port() != "1111" && portSpecs.Port() != "2222" && portSpecs.Port() != "3333" { t.Fatalf("Expected 1111 or 2222 or 3333, found %s", portSpecs) } } if len(configUser.Env) != 3 { t.Fatalf("Expected 3 env var, VAR1=1, VAR2=3 and VAR3=3, found %d", len(configUser.Env)) } for _, env := range configUser.Env { if env != "VAR1=1" && env != "VAR2=3" && env != "VAR3=3" { t.Fatalf("Expected VAR1=1 or VAR2=3 or VAR3=3, found %s", env) } } if len(configUser.Volumes) != 3 { t.Fatalf("Expected 3 volumes, /test1, /test2 and /test3, found %d", len(configUser.Volumes)) } for v := range configUser.Volumes { if v != "/test1" && v != "/test2" && v != "/test3" { t.Fatalf("Expected /test1 or /test2 or /test3, found %s", v) } } ports, _, err := nat.ParsePortSpecs([]string{"0000"}) if err != nil { t.Error(err) } configImage2 := &Config{ ExposedPorts: ports, } if err := Merge(configUser, configImage2); err != nil { t.Error(err) } if len(configUser.ExposedPorts) != 4 { t.Fatalf("Expected 4 ExposedPorts, 0000, 1111, 2222 and 3333, found %d", len(configUser.ExposedPorts)) } for portSpecs := range configUser.ExposedPorts { if portSpecs.Port() != "0" && portSpecs.Port() != "1111" && portSpecs.Port() != "2222" && portSpecs.Port() != "3333" { t.Fatalf("Expected %q or %q or %q or %q, found %s", 0, 1111, 2222, 3333, portSpecs) } } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/parse.go ================================================ package runconfig import ( "fmt" "strconv" "strings" "github.com/docker/docker/opts" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/ulimit" "github.com/docker/docker/pkg/units" ) var ( ErrConflictContainerNetworkAndLinks = fmt.Errorf("Conflicting options: --net=container can't be used with links. This would result in undefined behavior") ErrConflictNetworkAndDns = fmt.Errorf("Conflicting options: --dns and the network mode (--net)") ErrConflictNetworkHostname = fmt.Errorf("Conflicting options: -h and the network mode (--net)") ErrConflictHostNetworkAndLinks = fmt.Errorf("Conflicting options: --net=host can't be used with links. This would result in undefined behavior") ErrConflictContainerNetworkAndMac = fmt.Errorf("Conflicting options: --mac-address and the network mode (--net)") ErrConflictNetworkHosts = fmt.Errorf("Conflicting options: --add-host and the network mode (--net)") ErrConflictNetworkPublishPorts = fmt.Errorf("Conflicting options: -p, -P, --publish-all, --publish and the network mode (--net)") ErrConflictNetworkExposePorts = fmt.Errorf("Conflicting options: --expose and the network mode (--expose)") ) // validateNM is the set of fields passed to validateNetMode() type validateNM struct { netMode NetworkMode flHostname *string flLinks opts.ListOpts flDns opts.ListOpts flExtraHosts opts.ListOpts flMacAddress *string flPublish opts.ListOpts flPublishAll *bool flExpose opts.ListOpts flVolumeDriver string } func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSet, error) { var ( // FIXME: use utils.ListOpts for attach and volumes? flAttach = opts.NewListOpts(opts.ValidateAttach) flVolumes = opts.NewListOpts(opts.ValidatePath) flLinks = opts.NewListOpts(opts.ValidateLink) flEnv = opts.NewListOpts(opts.ValidateEnv) flLabels = opts.NewListOpts(opts.ValidateEnv) flDevices = opts.NewListOpts(opts.ValidateDevice) ulimits = make(map[string]*ulimit.Ulimit) flUlimits = opts.NewUlimitOpt(ulimits) flPublish = opts.NewListOpts(nil) flExpose = opts.NewListOpts(nil) flDns = opts.NewListOpts(opts.ValidateIPAddress) flDnsSearch = opts.NewListOpts(opts.ValidateDNSSearch) flExtraHosts = opts.NewListOpts(opts.ValidateExtraHost) flVolumesFrom = opts.NewListOpts(nil) flLxcOpts = opts.NewListOpts(nil) flEnvFile = opts.NewListOpts(nil) flCapAdd = opts.NewListOpts(nil) flCapDrop = opts.NewListOpts(nil) flGroupAdd = opts.NewListOpts(nil) flSecurityOpt = opts.NewListOpts(nil) flLabelsFile = opts.NewListOpts(nil) flLoggingOpts = opts.NewListOpts(nil) flNetwork = cmd.Bool([]string{"#n", "#-networking"}, true, "Enable networking for this container") flPrivileged = cmd.Bool([]string{"#privileged", "-privileged"}, false, "Give extended privileges to this container") flPidMode = cmd.String([]string{"-pid"}, "", "PID namespace to use") flUTSMode = cmd.String([]string{"-uts"}, "", "UTS namespace to use") flPublishAll = cmd.Bool([]string{"P", "-publish-all"}, false, "Publish all exposed ports to random ports") flStdin = cmd.Bool([]string{"i", "-interactive"}, false, "Keep STDIN open even if not attached") flTty = cmd.Bool([]string{"t", "-tty"}, false, "Allocate a pseudo-TTY") flOomKillDisable = cmd.Bool([]string{"-oom-kill-disable"}, false, "Disable OOM Killer") flContainerIDFile = cmd.String([]string{"#cidfile", "-cidfile"}, "", "Write the container ID to the file") flEntrypoint = cmd.String([]string{"#entrypoint", "-entrypoint"}, "", "Overwrite the default ENTRYPOINT of the image") flHostname = cmd.String([]string{"h", "-hostname"}, "", "Container host name") flMemoryString = cmd.String([]string{"m", "-memory"}, "", "Memory limit") flMemorySwap = cmd.String([]string{"-memory-swap"}, "", "Total memory (memory + swap), '-1' to disable swap") flUser = cmd.String([]string{"u", "-user"}, "", "Username or UID (format: [:])") flWorkingDir = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container") flCpuShares = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") flCpuPeriod = cmd.Int64([]string{"-cpu-period"}, 0, "Limit CPU CFS (Completely Fair Scheduler) period") flCpuQuota = cmd.Int64([]string{"-cpu-quota"}, 0, "Limit CPU CFS (Completely Fair Scheduler) quota") flCpusetCpus = cmd.String([]string{"#-cpuset", "-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") flCpusetMems = cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)") flBlkioWeight = cmd.Int64([]string{"-blkio-weight"}, 0, "Block IO (relative weight), between 10 and 1000") flSwappiness = cmd.Int64([]string{"-memory-swappiness"}, -1, "Tuning container memory swappiness (0 to 100)") flNetMode = cmd.String([]string{"-net"}, "default", "Set the Network mode for the container") flMacAddress = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)") flIpcMode = cmd.String([]string{"-ipc"}, "", "IPC namespace to use") flRestartPolicy = cmd.String([]string{"-restart"}, "no", "Restart policy to apply when a container exits") flReadonlyRootfs = cmd.Bool([]string{"-read-only"}, false, "Mount the container's root filesystem as read only") flLoggingDriver = cmd.String([]string{"-log-driver"}, "", "Logging driver for container") flCgroupParent = cmd.String([]string{"-cgroup-parent"}, "", "Optional parent cgroup for the container") flVolumeDriver = cmd.String([]string{"-volume-driver"}, "", "Optional volume driver for the container") ) cmd.Var(&flAttach, []string{"a", "-attach"}, "Attach to STDIN, STDOUT or STDERR") cmd.Var(&flVolumes, []string{"v", "-volume"}, "Bind mount a volume") cmd.Var(&flLinks, []string{"#link", "-link"}, "Add link to another container") cmd.Var(&flDevices, []string{"-device"}, "Add a host device to the container") cmd.Var(&flLabels, []string{"l", "-label"}, "Set meta data on a container") cmd.Var(&flLabelsFile, []string{"-label-file"}, "Read in a line delimited file of labels") cmd.Var(&flEnv, []string{"e", "-env"}, "Set environment variables") cmd.Var(&flEnvFile, []string{"-env-file"}, "Read in a file of environment variables") cmd.Var(&flPublish, []string{"p", "-publish"}, "Publish a container's port(s) to the host") cmd.Var(&flExpose, []string{"#expose", "-expose"}, "Expose a port or a range of ports") cmd.Var(&flDns, []string{"#dns", "-dns"}, "Set custom DNS servers") cmd.Var(&flDnsSearch, []string{"-dns-search"}, "Set custom DNS search domains") cmd.Var(&flExtraHosts, []string{"-add-host"}, "Add a custom host-to-IP mapping (host:ip)") cmd.Var(&flVolumesFrom, []string{"#volumes-from", "-volumes-from"}, "Mount volumes from the specified container(s)") cmd.Var(&flLxcOpts, []string{"#lxc-conf", "-lxc-conf"}, "Add custom lxc options") cmd.Var(&flCapAdd, []string{"-cap-add"}, "Add Linux capabilities") cmd.Var(&flCapDrop, []string{"-cap-drop"}, "Drop Linux capabilities") cmd.Var(&flGroupAdd, []string{"-group-add"}, "Add additional groups to join") cmd.Var(&flSecurityOpt, []string{"-security-opt"}, "Security Options") cmd.Var(flUlimits, []string{"-ulimit"}, "Ulimit options") cmd.Var(&flLoggingOpts, []string{"-log-opt"}, "Log driver options") expFlags := attachExperimentalFlags(cmd) cmd.Require(flag.Min, 1) if err := cmd.ParseFlags(args, true); err != nil { return nil, nil, cmd, err } var ( attachStdin = flAttach.Get("stdin") attachStdout = flAttach.Get("stdout") attachStderr = flAttach.Get("stderr") ) netMode, err := parseNetMode(*flNetMode) if err != nil { return nil, nil, cmd, fmt.Errorf("--net: invalid net mode: %v", err) } vals := validateNM{ netMode: netMode, flHostname: flHostname, flLinks: flLinks, flDns: flDns, flExtraHosts: flExtraHosts, flMacAddress: flMacAddress, flPublish: flPublish, flPublishAll: flPublishAll, flExpose: flExpose, } if err := validateNetMode(&vals); err != nil { return nil, nil, cmd, err } // Validate the input mac address if *flMacAddress != "" { if _, err := opts.ValidateMACAddress(*flMacAddress); err != nil { return nil, nil, cmd, fmt.Errorf("%s is not a valid mac address", *flMacAddress) } } if *flStdin { attachStdin = true } // If -a is not set attach to the output stdio if flAttach.Len() == 0 { attachStdout = true attachStderr = true } var flMemory int64 if *flMemoryString != "" { parsedMemory, err := units.RAMInBytes(*flMemoryString) if err != nil { return nil, nil, cmd, err } flMemory = parsedMemory } var MemorySwap int64 if *flMemorySwap != "" { if *flMemorySwap == "-1" { MemorySwap = -1 } else { parsedMemorySwap, err := units.RAMInBytes(*flMemorySwap) if err != nil { return nil, nil, cmd, err } MemorySwap = parsedMemorySwap } } swappiness := *flSwappiness if swappiness != -1 && (swappiness < 0 || swappiness > 100) { return nil, nil, cmd, fmt.Errorf("Invalid value: %d. Valid memory swappiness range is 0-100", swappiness) } var binds []string // add any bind targets to the list of container volumes for bind := range flVolumes.GetMap() { if arr := strings.Split(bind, ":"); len(arr) > 1 { if arr[1] == "/" { return nil, nil, cmd, fmt.Errorf("Invalid bind mount: destination can't be '/'") } // after creating the bind mount we want to delete it from the flVolumes values because // we do not want bind mounts being committed to image configs binds = append(binds, bind) flVolumes.Delete(bind) } else if bind == "/" { return nil, nil, cmd, fmt.Errorf("Invalid volume: path can't be '/'") } } var ( parsedArgs = cmd.Args() runCmd *Command entrypoint *Entrypoint image = cmd.Arg(0) ) if len(parsedArgs) > 1 { runCmd = NewCommand(parsedArgs[1:]...) } if *flEntrypoint != "" { entrypoint = NewEntrypoint(*flEntrypoint) } lc, err := parseKeyValueOpts(flLxcOpts) if err != nil { return nil, nil, cmd, err } lxcConf := NewLxcConfig(lc) var ( domainname string hostname = *flHostname parts = strings.SplitN(hostname, ".", 2) ) if len(parts) > 1 { hostname = parts[0] domainname = parts[1] } ports, portBindings, err := nat.ParsePortSpecs(flPublish.GetAll()) if err != nil { return nil, nil, cmd, err } // Merge in exposed ports to the map of published ports for _, e := range flExpose.GetAll() { if strings.Contains(e, ":") { return nil, nil, cmd, fmt.Errorf("Invalid port format for --expose: %s", e) } //support two formats for expose, original format /[] or /[] 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 := parsers.ParsePortRange(port) if err != nil { return nil, nil, cmd, fmt.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, nil, cmd, err } if _, exists := ports[p]; !exists { ports[p] = struct{}{} } } } // parse device mappings deviceMappings := []DeviceMapping{} for _, device := range flDevices.GetAll() { deviceMapping, err := ParseDevice(device) if err != nil { return nil, nil, cmd, err } deviceMappings = append(deviceMappings, deviceMapping) } // collect all the environment variables for the container envVariables, err := readKVStrings(flEnvFile.GetAll(), flEnv.GetAll()) if err != nil { return nil, nil, cmd, err } // collect all the labels for the container labels, err := readKVStrings(flLabelsFile.GetAll(), flLabels.GetAll()) if err != nil { return nil, nil, cmd, err } ipcMode := IpcMode(*flIpcMode) if !ipcMode.Valid() { return nil, nil, cmd, fmt.Errorf("--ipc: invalid IPC mode") } pidMode := PidMode(*flPidMode) if !pidMode.Valid() { return nil, nil, cmd, fmt.Errorf("--pid: invalid PID mode") } utsMode := UTSMode(*flUTSMode) if !utsMode.Valid() { return nil, nil, cmd, fmt.Errorf("--uts: invalid UTS mode") } restartPolicy, err := ParseRestartPolicy(*flRestartPolicy) if err != nil { return nil, nil, cmd, err } loggingOpts, err := parseLoggingOpts(*flLoggingDriver, flLoggingOpts.GetAll()) if err != nil { return nil, nil, cmd, err } config := &Config{ Hostname: hostname, Domainname: domainname, ExposedPorts: ports, User: *flUser, Tty: *flTty, NetworkDisabled: !*flNetwork, OpenStdin: *flStdin, AttachStdin: attachStdin, AttachStdout: attachStdout, AttachStderr: attachStderr, Env: envVariables, Cmd: runCmd, Image: image, Volumes: flVolumes.GetMap(), MacAddress: *flMacAddress, Entrypoint: entrypoint, WorkingDir: *flWorkingDir, Labels: convertKVStringsToMap(labels), VolumeDriver: *flVolumeDriver, } hostConfig := &HostConfig{ Binds: binds, ContainerIDFile: *flContainerIDFile, LxcConf: lxcConf, Memory: flMemory, MemorySwap: MemorySwap, CpuShares: *flCpuShares, CpuPeriod: *flCpuPeriod, CpusetCpus: *flCpusetCpus, CpusetMems: *flCpusetMems, CpuQuota: *flCpuQuota, BlkioWeight: *flBlkioWeight, OomKillDisable: *flOomKillDisable, MemorySwappiness: swappiness, Privileged: *flPrivileged, PortBindings: portBindings, Links: flLinks.GetAll(), PublishAllPorts: *flPublishAll, Dns: flDns.GetAll(), DnsSearch: flDnsSearch.GetAll(), ExtraHosts: flExtraHosts.GetAll(), VolumesFrom: flVolumesFrom.GetAll(), NetworkMode: netMode, IpcMode: ipcMode, PidMode: pidMode, UTSMode: utsMode, Devices: deviceMappings, CapAdd: NewCapList(flCapAdd.GetAll()), CapDrop: NewCapList(flCapDrop.GetAll()), GroupAdd: flGroupAdd.GetAll(), RestartPolicy: restartPolicy, SecurityOpt: flSecurityOpt.GetAll(), ReadonlyRootfs: *flReadonlyRootfs, Ulimits: flUlimits.GetList(), LogConfig: LogConfig{Type: *flLoggingDriver, Config: loggingOpts}, CgroupParent: *flCgroupParent, } applyExperimentalFlags(expFlags, config, hostConfig) // When allocating stdin in attached mode, close stdin at client disconnect if config.OpenStdin && config.AttachStdin { config.StdinOnce = true } return config, hostConfig, cmd, nil } // reads a file of line terminated key=value pairs and override that with override parameter func readKVStrings(files []string, override []string) ([]string, error) { envVariables := []string{} for _, ef := range files { parsedVars, err := opts.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 } // 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 } func parseLoggingOpts(loggingDriver string, loggingOpts []string) (map[string]string, error) { loggingOptsMap := convertKVStringsToMap(loggingOpts) if loggingDriver == "none" && len(loggingOpts) > 0 { return map[string]string{}, fmt.Errorf("Invalid logging opts for driver %s", loggingDriver) } return loggingOptsMap, nil } // ParseRestartPolicy returns the parsed policy or an error indicating what is incorrect func ParseRestartPolicy(policy string) (RestartPolicy, error) { p := RestartPolicy{} if policy == "" { return p, nil } var ( parts = strings.Split(policy, ":") name = parts[0] ) p.Name = name switch name { case "always": if len(parts) > 1 { return p, fmt.Errorf("maximum restart count not valid with restart policy of \"always\"") } case "no": // do nothing case "on-failure": if len(parts) > 2 { return p, fmt.Errorf("restart count format is not valid, usage: 'on-failure:N' or 'on-failure'") } if len(parts) == 2 { count, err := strconv.Atoi(parts[1]) if err != nil { return p, err } p.MaximumRetryCount = count } default: return p, fmt.Errorf("invalid restart policy %s", name) } return p, nil } func parseKeyValueOpts(opts opts.ListOpts) ([]KeyValuePair, error) { out := make([]KeyValuePair, opts.Len()) for i, o := range opts.GetAll() { k, v, err := parsers.ParseKeyValueOpt(o) if err != nil { return nil, err } out[i] = KeyValuePair{Key: k, Value: v} } return out, nil } func ParseDevice(device string) (DeviceMapping, error) { src := "" dst := "" permissions := "rwm" arr := strings.Split(device, ":") switch len(arr) { case 3: permissions = arr[2] fallthrough case 2: dst = arr[1] fallthrough case 1: src = arr[0] default: return DeviceMapping{}, fmt.Errorf("Invalid device specification: %s", device) } if dst == "" { dst = src } deviceMapping := DeviceMapping{ PathOnHost: src, PathInContainer: dst, CgroupPermissions: permissions, } return deviceMapping, nil } ================================================ FILE: vendor/github.com/docker/docker/runconfig/parse_experimental.go ================================================ // +build experimental package runconfig import flag "github.com/docker/docker/pkg/mflag" type experimentalFlags struct { flags map[string]interface{} } func attachExperimentalFlags(cmd *flag.FlagSet) *experimentalFlags { flags := make(map[string]interface{}) flags["publish-service"] = cmd.String([]string{"-publish-service"}, "", "Publish this container as a service") return &experimentalFlags{flags: flags} } func applyExperimentalFlags(exp *experimentalFlags, config *Config, hostConfig *HostConfig) { config.PublishService = *(exp.flags["publish-service"]).(*string) } ================================================ FILE: vendor/github.com/docker/docker/runconfig/parse_stub.go ================================================ // +build !experimental package runconfig import flag "github.com/docker/docker/pkg/mflag" type experimentalFlags struct{} func attachExperimentalFlags(cmd *flag.FlagSet) *experimentalFlags { return nil } func applyExperimentalFlags(flags *experimentalFlags, config *Config, hostConfig *HostConfig) { } ================================================ FILE: vendor/github.com/docker/docker/runconfig/parse_test.go ================================================ package runconfig import ( "fmt" "io/ioutil" "strings" "testing" flag "github.com/docker/docker/pkg/mflag" "github.com/docker/docker/pkg/nat" "github.com/docker/docker/pkg/parsers" ) func parseRun(args []string) (*Config, *HostConfig, *flag.FlagSet, error) { cmd := flag.NewFlagSet("run", flag.ContinueOnError) cmd.SetOutput(ioutil.Discard) cmd.Usage = nil return Parse(cmd, args) } func parse(t *testing.T, args string) (*Config, *HostConfig, error) { config, hostConfig, _, err := parseRun(strings.Split(args+" ubuntu bash", " ")) return config, hostConfig, err } func mustParse(t *testing.T, args string) (*Config, *HostConfig) { config, hostConfig, err := parse(t, args) if err != nil { t.Fatal(err) } return config, hostConfig } // check if (a == c && b == d) || (a == d && b == c) // because maps are randomized func compareRandomizedStrings(a, b, c, d string) error { if a == c && b == d { return nil } if a == d && b == c { return nil } return fmt.Errorf("strings don't match") } func TestParseRunLinks(t *testing.T) { if _, hostConfig := mustParse(t, "--link a:b"); len(hostConfig.Links) == 0 || hostConfig.Links[0] != "a:b" { t.Fatalf("Error parsing links. Expected []string{\"a:b\"}, received: %v", hostConfig.Links) } if _, hostConfig := mustParse(t, "--link a:b --link c:d"); len(hostConfig.Links) < 2 || hostConfig.Links[0] != "a:b" || hostConfig.Links[1] != "c:d" { t.Fatalf("Error parsing links. Expected []string{\"a:b\", \"c:d\"}, received: %v", hostConfig.Links) } if _, hostConfig := mustParse(t, ""); len(hostConfig.Links) != 0 { t.Fatalf("Error parsing links. No link expected, received: %v", hostConfig.Links) } } func TestParseRunAttach(t *testing.T) { if config, _ := mustParse(t, "-a stdin"); !config.AttachStdin || config.AttachStdout || config.AttachStderr { t.Fatalf("Error parsing attach flags. Expect only Stdin enabled. Received: in: %v, out: %v, err: %v", config.AttachStdin, config.AttachStdout, config.AttachStderr) } if config, _ := mustParse(t, "-a stdin -a stdout"); !config.AttachStdin || !config.AttachStdout || config.AttachStderr { t.Fatalf("Error parsing attach flags. Expect only Stdin and Stdout enabled. Received: in: %v, out: %v, err: %v", config.AttachStdin, config.AttachStdout, config.AttachStderr) } if config, _ := mustParse(t, "-a stdin -a stdout -a stderr"); !config.AttachStdin || !config.AttachStdout || !config.AttachStderr { t.Fatalf("Error parsing attach flags. Expect all attach enabled. Received: in: %v, out: %v, err: %v", config.AttachStdin, config.AttachStdout, config.AttachStderr) } if config, _ := mustParse(t, ""); config.AttachStdin || !config.AttachStdout || !config.AttachStderr { t.Fatalf("Error parsing attach flags. Expect Stdin disabled. Received: in: %v, out: %v, err: %v", config.AttachStdin, config.AttachStdout, config.AttachStderr) } if config, _ := mustParse(t, "-i"); !config.AttachStdin || !config.AttachStdout || !config.AttachStderr { t.Fatalf("Error parsing attach flags. Expect Stdin enabled. Received: in: %v, out: %v, err: %v", config.AttachStdin, config.AttachStdout, config.AttachStderr) } if _, _, err := parse(t, "-a"); err == nil { t.Fatalf("Error parsing attach flags, `-a` should be an error but is not") } if _, _, err := parse(t, "-a invalid"); err == nil { t.Fatalf("Error parsing attach flags, `-a invalid` should be an error but is not") } if _, _, err := parse(t, "-a invalid -a stdout"); err == nil { t.Fatalf("Error parsing attach flags, `-a stdout -a invalid` should be an error but is not") } if _, _, err := parse(t, "-a stdout -a stderr -d"); err == nil { t.Fatalf("Error parsing attach flags, `-a stdout -a stderr -d` should be an error but is not") } if _, _, err := parse(t, "-a stdin -d"); err == nil { t.Fatalf("Error parsing attach flags, `-a stdin -d` should be an error but is not") } if _, _, err := parse(t, "-a stdout -d"); err == nil { t.Fatalf("Error parsing attach flags, `-a stdout -d` should be an error but is not") } if _, _, err := parse(t, "-a stderr -d"); err == nil { t.Fatalf("Error parsing attach flags, `-a stderr -d` should be an error but is not") } if _, _, err := parse(t, "-d --rm"); err == nil { t.Fatalf("Error parsing attach flags, `-d --rm` should be an error but is not") } } func TestParseRunVolumes(t *testing.T) { if config, hostConfig := mustParse(t, "-v /tmp"); hostConfig.Binds != nil { t.Fatalf("Error parsing volume flags, `-v /tmp` should not mount-bind anything. Received %v", hostConfig.Binds) } else if _, exists := config.Volumes["/tmp"]; !exists { t.Fatalf("Error parsing volume flags, `-v /tmp` is missing from volumes. Received %v", config.Volumes) } if config, hostConfig := mustParse(t, "-v /tmp -v /var"); hostConfig.Binds != nil { t.Fatalf("Error parsing volume flags, `-v /tmp -v /var` should not mount-bind anything. Received %v", hostConfig.Binds) } else if _, exists := config.Volumes["/tmp"]; !exists { t.Fatalf("Error parsing volume flags, `-v /tmp` is missing from volumes. Received %v", config.Volumes) } else if _, exists := config.Volumes["/var"]; !exists { t.Fatalf("Error parsing volume flags, `-v /var` is missing from volumes. Received %v", config.Volumes) } if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp"); hostConfig.Binds == nil || hostConfig.Binds[0] != "/hostTmp:/containerTmp" { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp` should mount-bind /hostTmp into /containeTmp. Received %v", hostConfig.Binds) } if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp -v /hostVar:/containerVar"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp", "/hostVar:/containerVar") != nil { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp -v /hostVar:/containerVar` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds) } if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:ro", "/hostVar:/containerVar:rw") != nil { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds) } if _, hostConfig := mustParse(t, "-v /containerTmp:ro -v /containerVar:rw"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/containerTmp:ro", "/containerVar:rw") != nil { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro -v /hostVar:/containerVar:rw` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds) } if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:ro,Z -v /hostVar:/containerVar:rw,Z"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:ro,Z", "/hostVar:/containerVar:rw,Z") != nil { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:ro,Z -v /hostVar:/containerVar:rw,Z` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds) } if _, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp:Z -v /hostVar:/containerVar:z"); hostConfig.Binds == nil || compareRandomizedStrings(hostConfig.Binds[0], hostConfig.Binds[1], "/hostTmp:/containerTmp:Z", "/hostVar:/containerVar:z") != nil { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp:Z -v /hostVar:/containerVar:z` should mount-bind /hostTmp into /containeTmp and /hostVar into /hostContainer. Received %v", hostConfig.Binds) } if config, hostConfig := mustParse(t, "-v /hostTmp:/containerTmp -v /containerVar"); hostConfig.Binds == nil || len(hostConfig.Binds) > 1 || hostConfig.Binds[0] != "/hostTmp:/containerTmp" { t.Fatalf("Error parsing volume flags, `-v /hostTmp:/containerTmp -v /containerVar` should mount-bind only /hostTmp into /containeTmp. Received %v", hostConfig.Binds) } else if _, exists := config.Volumes["/containerVar"]; !exists { t.Fatalf("Error parsing volume flags, `-v /containerVar` is missing from volumes. Received %v", config.Volumes) } if config, hostConfig := mustParse(t, ""); hostConfig.Binds != nil { t.Fatalf("Error parsing volume flags, without volume, nothing should be mount-binded. Received %v", hostConfig.Binds) } else if len(config.Volumes) != 0 { t.Fatalf("Error parsing volume flags, without volume, no volume should be present. Received %v", config.Volumes) } if _, _, err := parse(t, "-v /"); err == nil { t.Fatalf("Expected error, but got none") } if _, _, err := parse(t, "-v /:/"); err == nil { t.Fatalf("Error parsing volume flags, `-v /:/` should fail but didn't") } if _, _, err := parse(t, "-v"); err == nil { t.Fatalf("Error parsing volume flags, `-v` should fail but didn't") } if _, _, err := parse(t, "-v /tmp:"); err == nil { t.Fatalf("Error parsing volume flags, `-v /tmp:` should fail but didn't") } if _, _, err := parse(t, "-v /tmp::"); err == nil { t.Fatalf("Error parsing volume flags, `-v /tmp::` should fail but didn't") } if _, _, err := parse(t, "-v :"); err == nil { t.Fatalf("Error parsing volume flags, `-v :` should fail but didn't") } if _, _, err := parse(t, "-v ::"); err == nil { t.Fatalf("Error parsing volume flags, `-v ::` should fail but didn't") } if _, _, err := parse(t, "-v /tmp:/tmp:/tmp:/tmp"); err == nil { t.Fatalf("Error parsing volume flags, `-v /tmp:/tmp:/tmp:/tmp` should fail but didn't") } } func TestParseLxcConfOpt(t *testing.T) { opts := []string{"lxc.utsname=docker", "lxc.utsname = docker "} for _, o := range opts { k, v, err := parsers.ParseKeyValueOpt(o) if err != nil { t.FailNow() } if k != "lxc.utsname" { t.Fail() } if v != "docker" { t.Fail() } } // With parseRun too _, hostconfig, _, err := parseRun([]string{"lxc.utsname=docker", "lxc.utsname = docker ", "img", "cmd"}) if err != nil { t.Fatal(err) } for _, lxcConf := range hostconfig.LxcConf.Slice() { if lxcConf.Key != "lxc.utsname" || lxcConf.Value != "docker" { t.Fail() } } } func TestNetHostname(t *testing.T) { if _, _, _, err := parseRun([]string{"-h=name", "img", "cmd"}); err != nil { t.Fatalf("Unexpected error: %s", err) } if _, _, _, err := parseRun([]string{"--net=host", "img", "cmd"}); err != nil { t.Fatalf("Unexpected error: %s", err) } if _, _, _, err := parseRun([]string{"-h=name", "--net=bridge", "img", "cmd"}); err != nil { t.Fatalf("Unexpected error: %s", err) } if _, _, _, err := parseRun([]string{"-h=name", "--net=none", "img", "cmd"}); err != nil { t.Fatalf("Unexpected error: %s", err) } if _, _, _, err := parseRun([]string{"-h=name", "--net=host", "img", "cmd"}); err != ErrConflictNetworkHostname { t.Fatalf("Expected error ErrConflictNetworkHostname, got: %s", err) } if _, _, _, err := parseRun([]string{"-h=name", "--net=container:other", "img", "cmd"}); err != ErrConflictNetworkHostname { t.Fatalf("Expected error ErrConflictNetworkHostname, got: %s", err) } if _, _, _, err := parseRun([]string{"--net=container", "img", "cmd"}); err == nil || err.Error() != "--net: invalid net mode: invalid container format container:" { t.Fatalf("Expected error with --net=container, got : %v", err) } if _, _, _, err := parseRun([]string{"--net=weird", "img", "cmd"}); err == nil || err.Error() != "--net: invalid net mode: invalid --net: weird" { t.Fatalf("Expected error with --net=weird, got: %s", err) } } func TestConflictContainerNetworkAndLinks(t *testing.T) { if _, _, _, err := parseRun([]string{"--net=container:other", "--link=zip:zap", "img", "cmd"}); err != ErrConflictContainerNetworkAndLinks { t.Fatalf("Expected error ErrConflictContainerNetworkAndLinks, got: %s", err) } if _, _, _, err := parseRun([]string{"--net=host", "--link=zip:zap", "img", "cmd"}); err != ErrConflictHostNetworkAndLinks { t.Fatalf("Expected error ErrConflictHostNetworkAndLinks, got: %s", err) } } func TestConflictNetworkModeAndOptions(t *testing.T) { if _, _, _, err := parseRun([]string{"--net=host", "--dns=8.8.8.8", "img", "cmd"}); err != ErrConflictNetworkAndDns { t.Fatalf("Expected error ErrConflictNetworkAndDns, got %s", err) } if _, _, _, err := parseRun([]string{"--net=container:other", "--dns=8.8.8.8", "img", "cmd"}); err != ErrConflictNetworkAndDns { t.Fatalf("Expected error ErrConflictNetworkAndDns, got %s", err) } if _, _, _, err := parseRun([]string{"--net=host", "--add-host=name:8.8.8.8", "img", "cmd"}); err != ErrConflictNetworkHosts { t.Fatalf("Expected error ErrConflictNetworkAndDns, got %s", err) } if _, _, _, err := parseRun([]string{"--net=container:other", "--add-host=name:8.8.8.8", "img", "cmd"}); err != ErrConflictNetworkHosts { t.Fatalf("Expected error ErrConflictNetworkAndDns, got %s", err) } if _, _, _, err := parseRun([]string{"--net=host", "--mac-address=92:d0:c6:0a:29:33", "img", "cmd"}); err != ErrConflictContainerNetworkAndMac { t.Fatalf("Expected error ErrConflictContainerNetworkAndMac, got %s", err) } if _, _, _, err := parseRun([]string{"--net=container:other", "--mac-address=92:d0:c6:0a:29:33", "img", "cmd"}); err != ErrConflictContainerNetworkAndMac { t.Fatalf("Expected error ErrConflictContainerNetworkAndMac, got %s", err) } if _, _, _, err := parseRun([]string{"--net=container:other", "-P", "img", "cmd"}); err != ErrConflictNetworkPublishPorts { t.Fatalf("Expected error ErrConflictNetworkPublishPorts, got %s", err) } if _, _, _, err := parseRun([]string{"--net=container:other", "-p", "8080", "img", "cmd"}); err != ErrConflictNetworkPublishPorts { t.Fatalf("Expected error ErrConflictNetworkPublishPorts, got %s", err) } if _, _, _, err := parseRun([]string{"--net=container:other", "--expose", "8000-9000", "img", "cmd"}); err != ErrConflictNetworkExposePorts { t.Fatalf("Expected error ErrConflictNetworkExposePorts, got %s", err) } } // Simple parse with MacAddress validatation func TestParseWithMacAddress(t *testing.T) { invalidMacAddress := "--mac-address=invalidMacAddress" validMacAddress := "--mac-address=92:d0:c6:0a:29:33" if _, _, _, err := parseRun([]string{invalidMacAddress, "img", "cmd"}); err != nil && err.Error() != "invalidMacAddress is not a valid mac address" { t.Fatalf("Expected an error with %v mac-address, got %v", invalidMacAddress, err) } if config, _ := mustParse(t, validMacAddress); config.MacAddress != "92:d0:c6:0a:29:33" { t.Fatalf("Expected the config to have '92:d0:c6:0a:29:33' as MacAddress, got '%v'", config.MacAddress) } } func TestParseWithMemory(t *testing.T) { invalidMemory := "--memory=invalid" validMemory := "--memory=1G" if _, _, _, err := parseRun([]string{invalidMemory, "img", "cmd"}); err != nil && err.Error() != "invalid size: 'invalid'" { t.Fatalf("Expected an error with '%v' Memory, got '%v'", invalidMemory, err) } if _, hostconfig := mustParse(t, validMemory); hostconfig.Memory != 1073741824 { t.Fatalf("Expected the config to have '1G' as Memory, got '%v'", hostconfig.Memory) } } func TestParseWithMemorySwap(t *testing.T) { invalidMemory := "--memory-swap=invalid" validMemory := "--memory-swap=1G" anotherValidMemory := "--memory-swap=-1" if _, _, _, err := parseRun([]string{invalidMemory, "img", "cmd"}); err == nil || err.Error() != "invalid size: 'invalid'" { t.Fatalf("Expected an error with '%v' MemorySwap, got '%v'", invalidMemory, err) } if _, hostconfig := mustParse(t, validMemory); hostconfig.MemorySwap != 1073741824 { t.Fatalf("Expected the config to have '1073741824' as MemorySwap, got '%v'", hostconfig.MemorySwap) } if _, hostconfig := mustParse(t, anotherValidMemory); hostconfig.MemorySwap != -1 { t.Fatalf("Expected the config to have '-1' as MemorySwap, got '%v'", hostconfig.MemorySwap) } } func TestParseHostname(t *testing.T) { hostname := "--hostname=hostname" hostnameWithDomain := "--hostname=hostname.domainname" hostnameWithDomainTld := "--hostname=hostname.domainname.tld" if config, _ := mustParse(t, hostname); config.Hostname != "hostname" && config.Domainname != "" { t.Fatalf("Expected the config to have 'hostname' as hostname, got '%v'", config.Hostname) } if config, _ := mustParse(t, hostnameWithDomain); config.Hostname != "hostname" && config.Domainname != "domainname" { t.Fatalf("Expected the config to have 'hostname' as hostname, got '%v'", config.Hostname) } if config, _ := mustParse(t, hostnameWithDomainTld); config.Hostname != "hostname" && config.Domainname != "domainname.tld" { t.Fatalf("Expected the config to have 'hostname' as hostname, got '%v'", config.Hostname) } } func TestParseWithExpose(t *testing.T) { invalids := map[string]string{ ":": "Invalid port format for --expose: :", "8080:9090": "Invalid port format for --expose: 8080:9090", "/tcp": "Invalid range format for --expose: /tcp, error: Empty string specified for ports.", "/udp": "Invalid range format for --expose: /udp, error: Empty string specified for ports.", "NaN/tcp": `Invalid range format for --expose: NaN/tcp, error: strconv.ParseUint: parsing "NaN": invalid syntax`, "NaN-NaN/tcp": `Invalid range format for --expose: NaN-NaN/tcp, error: strconv.ParseUint: parsing "NaN": invalid syntax`, "8080-NaN/tcp": `Invalid range format for --expose: 8080-NaN/tcp, error: strconv.ParseUint: parsing "NaN": invalid syntax`, "1234567890-8080/tcp": `Invalid range format for --expose: 1234567890-8080/tcp, error: strconv.ParseUint: parsing "1234567890": value out of range`, } valids := map[string][]nat.Port{ "8080/tcp": {"8080/tcp"}, "8080/udp": {"8080/udp"}, "8080/ncp": {"8080/ncp"}, "8080-8080/udp": {"8080/udp"}, "8080-8082/tcp": {"8080/tcp", "8081/tcp", "8082/tcp"}, } for expose, expectedError := range invalids { if _, _, _, err := parseRun([]string{fmt.Sprintf("--expose=%v", expose), "img", "cmd"}); err == nil || err.Error() != expectedError { t.Fatalf("Expected error '%v' with '--expose=%v', got '%v'", expectedError, expose, err) } } for expose, exposedPorts := range valids { config, _, _, err := parseRun([]string{fmt.Sprintf("--expose=%v", expose), "img", "cmd"}) if err != nil { t.Fatal(err) } if len(config.ExposedPorts) != len(exposedPorts) { t.Fatalf("Expected %v exposed port, got %v", len(exposedPorts), len(config.ExposedPorts)) } for _, port := range exposedPorts { if _, ok := config.ExposedPorts[port]; !ok { t.Fatalf("Expected %v, got %v", exposedPorts, config.ExposedPorts) } } } // Merge with actual published port config, _, _, err := parseRun([]string{"--publish=80", "--expose=80-81/tcp", "img", "cmd"}) if err != nil { t.Fatal(err) } if len(config.ExposedPorts) != 2 { t.Fatalf("Expected 2 exposed ports, got %v", config.ExposedPorts) } ports := []nat.Port{"80/tcp", "81/tcp"} for _, port := range ports { if _, ok := config.ExposedPorts[port]; !ok { t.Fatalf("Expected %v, got %v", ports, config.ExposedPorts) } } } func TestParseDevice(t *testing.T) { valids := map[string]DeviceMapping{ "/dev/snd": { PathOnHost: "/dev/snd", PathInContainer: "/dev/snd", CgroupPermissions: "rwm", }, "/dev/snd:/something": { PathOnHost: "/dev/snd", PathInContainer: "/something", CgroupPermissions: "rwm", }, "/dev/snd:/something:ro": { PathOnHost: "/dev/snd", PathInContainer: "/something", CgroupPermissions: "ro", }, } for device, deviceMapping := range valids { _, hostconfig, _, err := parseRun([]string{fmt.Sprintf("--device=%v", device), "img", "cmd"}) if err != nil { t.Fatal(err) } if len(hostconfig.Devices) != 1 { t.Fatalf("Expected 1 devices, got %v", hostconfig.Devices) } if hostconfig.Devices[0] != deviceMapping { t.Fatalf("Expected %v, got %v", deviceMapping, hostconfig.Devices) } } } func TestParseModes(t *testing.T) { // ipc ko if _, _, _, err := parseRun([]string{"--ipc=container:", "img", "cmd"}); err == nil || err.Error() != "--ipc: invalid IPC mode" { t.Fatalf("Expected an error with message '--ipc: invalid IPC mode', got %v", err) } // ipc ok _, hostconfig, _, err := parseRun([]string{"--ipc=host", "img", "cmd"}) if err != nil { t.Fatal(err) } if !hostconfig.IpcMode.Valid() { t.Fatalf("Expected a valid IpcMode, got %v", hostconfig.IpcMode) } // pid ko if _, _, _, err := parseRun([]string{"--pid=container:", "img", "cmd"}); err == nil || err.Error() != "--pid: invalid PID mode" { t.Fatalf("Expected an error with message '--pid: invalid PID mode', got %v", err) } // pid ok _, hostconfig, _, err = parseRun([]string{"--pid=host", "img", "cmd"}) if err != nil { t.Fatal(err) } if !hostconfig.PidMode.Valid() { t.Fatalf("Expected a valid PidMode, got %v", hostconfig.PidMode) } // uts ko if _, _, _, err := parseRun([]string{"--uts=container:", "img", "cmd"}); err == nil || err.Error() != "--uts: invalid UTS mode" { t.Fatalf("Expected an error with message '--uts: invalid UTS mode', got %v", err) } // uts ok _, hostconfig, _, err = parseRun([]string{"--uts=host", "img", "cmd"}) if err != nil { t.Fatal(err) } if !hostconfig.UTSMode.Valid() { t.Fatalf("Expected a valid UTSMode, got %v", hostconfig.UTSMode) } } func TestParseRestartPolicy(t *testing.T) { invalids := map[string]string{ "something": "invalid restart policy something", "always:2": "maximum restart count not valid with restart policy of \"always\"", "always:2:3": "maximum restart count not valid with restart policy of \"always\"", "on-failure:invalid": `strconv.ParseInt: parsing "invalid": invalid syntax`, "on-failure:2:5": "restart count format is not valid, usage: 'on-failure:N' or 'on-failure'", } valids := map[string]RestartPolicy{ "": {}, "always": { Name: "always", MaximumRetryCount: 0, }, "on-failure:1": { Name: "on-failure", MaximumRetryCount: 1, }, } for restart, expectedError := range invalids { if _, _, _, err := parseRun([]string{fmt.Sprintf("--restart=%s", restart), "img", "cmd"}); err == nil || err.Error() != expectedError { t.Fatalf("Expected an error with message '%v' for %v, got %v", expectedError, restart, err) } } for restart, expected := range valids { _, hostconfig, _, err := parseRun([]string{fmt.Sprintf("--restart=%v", restart), "img", "cmd"}) if err != nil { t.Fatal(err) } if hostconfig.RestartPolicy != expected { t.Fatalf("Expected %v, got %v", expected, hostconfig.RestartPolicy) } } } func TestParseLoggingOpts(t *testing.T) { // logging opts ko if _, _, _, err := parseRun([]string{"--log-driver=none", "--log-opt=anything", "img", "cmd"}); err == nil || err.Error() != "Invalid logging opts for driver none" { t.Fatalf("Expected an error with message 'Invalid logging opts for driver none', got %v", err) } // logging opts ok _, hostconfig, _, err := parseRun([]string{"--log-driver=syslog", "--log-opt=something", "img", "cmd"}) if err != nil { t.Fatal(err) } if hostconfig.LogConfig.Type != "syslog" || len(hostconfig.LogConfig.Config) != 1 { t.Fatalf("Expected a 'syslog' LogConfig with one config, got %v", hostconfig.RestartPolicy) } } func TestParseEnvfileVariables(t *testing.T) { // env ko if _, _, _, err := parseRun([]string{"--env-file=nonexistent", "img", "cmd"}); err == nil || err.Error() != "open nonexistent: no such file or directory" { t.Fatalf("Expected an error with message 'open nonexistent: no such file or directory', got %v", err) } // env ok config, _, _, err := parseRun([]string{"--env-file=fixtures/valid.env", "img", "cmd"}) if err != nil { t.Fatal(err) } if len(config.Env) != 1 || config.Env[0] != "ENV1=value1" { t.Fatalf("Expected a a config with [ENV1=value1], got %v", config.Env) } config, _, _, err = parseRun([]string{"--env-file=fixtures/valid.env", "--env=ENV2=value2", "img", "cmd"}) if err != nil { t.Fatal(err) } if len(config.Env) != 2 || config.Env[0] != "ENV1=value1" || config.Env[1] != "ENV2=value2" { t.Fatalf("Expected a a config with [ENV1=value1 ENV2=value2], got %v", config.Env) } } func TestParseLabelfileVariables(t *testing.T) { // label ko if _, _, _, err := parseRun([]string{"--label-file=nonexistent", "img", "cmd"}); err == nil || err.Error() != "open nonexistent: no such file or directory" { t.Fatalf("Expected an error with message 'open nonexistent: no such file or directory', got %v", err) } // label ok config, _, _, err := parseRun([]string{"--label-file=fixtures/valid.label", "img", "cmd"}) if err != nil { t.Fatal(err) } if len(config.Labels) != 1 || config.Labels["LABEL1"] != "value1" { t.Fatalf("Expected a a config with [LABEL1:value1], got %v", config.Labels) } config, _, _, err = parseRun([]string{"--label-file=fixtures/valid.label", "--label=LABEL2=value2", "img", "cmd"}) if err != nil { t.Fatal(err) } if len(config.Labels) != 2 || config.Labels["LABEL1"] != "value1" || config.Labels["LABEL2"] != "value2" { t.Fatalf("Expected a a config with [LABEL1:value1 LABEL2:value2], got %v", config.Labels) } } func TestParseEntryPoint(t *testing.T) { config, _, _, err := parseRun([]string{"--entrypoint=anything", "cmd", "img"}) if err != nil { t.Fatal(err) } if config.Entrypoint.Len() != 1 && config.Entrypoint.parts[0] != "anything" { t.Fatalf("Expected entrypoint 'anything', got %v", config.Entrypoint) } } ================================================ FILE: vendor/github.com/docker/docker/runconfig/parse_unix.go ================================================ // +build !windows package runconfig import ( "fmt" "strings" ) func parseNetMode(netMode string) (NetworkMode, error) { parts := strings.Split(netMode, ":") switch mode := parts[0]; mode { case "default", "bridge", "none", "host": case "container": if len(parts) < 2 || parts[1] == "" { return "", fmt.Errorf("invalid container format container:") } default: return "", fmt.Errorf("invalid --net: %s", netMode) } return NetworkMode(netMode), nil } func validateNetMode(vals *validateNM) error { if (vals.netMode.IsHost() || vals.netMode.IsContainer()) && *vals.flHostname != "" { return ErrConflictNetworkHostname } if vals.netMode.IsHost() && vals.flLinks.Len() > 0 { return ErrConflictHostNetworkAndLinks } if vals.netMode.IsContainer() && vals.flLinks.Len() > 0 { return ErrConflictContainerNetworkAndLinks } if (vals.netMode.IsHost() || vals.netMode.IsContainer()) && vals.flDns.Len() > 0 { return ErrConflictNetworkAndDns } if (vals.netMode.IsContainer() || vals.netMode.IsHost()) && vals.flExtraHosts.Len() > 0 { return ErrConflictNetworkHosts } if (vals.netMode.IsContainer() || vals.netMode.IsHost()) && *vals.flMacAddress != "" { return ErrConflictContainerNetworkAndMac } if vals.netMode.IsContainer() && (vals.flPublish.Len() > 0 || *vals.flPublishAll == true) { return ErrConflictNetworkPublishPorts } if vals.netMode.IsContainer() && vals.flExpose.Len() > 0 { return ErrConflictNetworkExposePorts } return nil } ================================================ FILE: vendor/github.com/docker/docker/runconfig/parse_windows.go ================================================ package runconfig import ( "fmt" "strings" ) func parseNetMode(netMode string) (NetworkMode, error) { parts := strings.Split(netMode, ":") switch mode := parts[0]; mode { case "default", "none": default: return "", fmt.Errorf("invalid --net: %s", netMode) } return NetworkMode(netMode), nil } func validateNetMode(vals *validateNM) error { return nil } ================================================ FILE: vendor/github.com/docker/docker/trust/service.go ================================================ package trust import ( "fmt" "time" "github.com/Sirupsen/logrus" "github.com/docker/libtrust" ) type NotVerifiedError string func (e NotVerifiedError) Error() string { return string(e) } func (t *TrustStore) CheckKey(ns string, key []byte, perm uint16) (bool, error) { if len(key) == 0 { return false, fmt.Errorf("Missing PublicKey") } pk, err := libtrust.UnmarshalPublicKeyJWK(key) if err != nil { return false, fmt.Errorf("Error unmarshalling public key: %v", err) } if perm == 0 { perm = 0x03 } t.RLock() defer t.RUnlock() if t.graph == nil { return false, NotVerifiedError("no graph") } // Check if any expired grants verified, err := t.graph.Verify(pk, ns, perm) if err != nil { return false, fmt.Errorf("Error verifying key to namespace: %s", ns) } if !verified { logrus.Debugf("Verification failed for %s using key %s", ns, pk.KeyID()) return false, NotVerifiedError("not verified") } if t.expiration.Before(time.Now()) { return false, NotVerifiedError("expired") } return true, nil } func (t *TrustStore) UpdateBase() { t.fetch() } ================================================ FILE: vendor/github.com/docker/docker/trust/trusts.go ================================================ package trust import ( "crypto/x509" "errors" "io/ioutil" "net/http" "net/url" "os" "path" "path/filepath" "sync" "time" "github.com/Sirupsen/logrus" "github.com/docker/libtrust/trustgraph" ) type TrustStore struct { path string caPool *x509.CertPool graph trustgraph.TrustGraph expiration time.Time fetcher *time.Timer fetchTime time.Duration autofetch bool httpClient *http.Client baseEndpoints map[string]*url.URL sync.RWMutex } // defaultFetchtime represents the starting duration to wait between // fetching sections of the graph. Unsuccessful fetches should // increase time between fetching. const defaultFetchtime = 45 * time.Second var baseEndpoints = map[string]string{"official": "https://dvjy3tqbc323p.cloudfront.net/trust/official.json"} func NewTrustStore(path string) (*TrustStore, error) { abspath, err := filepath.Abs(path) if err != nil { return nil, err } // Create base graph url map endpoints := map[string]*url.URL{} for name, endpoint := range baseEndpoints { u, err := url.Parse(endpoint) if err != nil { return nil, err } endpoints[name] = u } // Load grant files t := &TrustStore{ path: abspath, caPool: nil, httpClient: &http.Client{}, fetchTime: time.Millisecond, baseEndpoints: endpoints, } if err := t.reload(); err != nil { return nil, err } return t, nil } func (t *TrustStore) reload() error { t.Lock() defer t.Unlock() matches, err := filepath.Glob(filepath.Join(t.path, "*.json")) if err != nil { return err } statements := make([]*trustgraph.Statement, len(matches)) for i, match := range matches { f, err := os.Open(match) if err != nil { return err } statements[i], err = trustgraph.LoadStatement(f, nil) if err != nil { f.Close() return err } f.Close() } if len(statements) == 0 { if t.autofetch { logrus.Debugf("No grants, fetching") t.fetcher = time.AfterFunc(t.fetchTime, t.fetch) } return nil } grants, expiration, err := trustgraph.CollapseStatements(statements, true) if err != nil { return err } t.expiration = expiration t.graph = trustgraph.NewMemoryGraph(grants) logrus.Debugf("Reloaded graph with %d grants expiring at %s", len(grants), expiration) if t.autofetch { nextFetch := expiration.Sub(time.Now()) if nextFetch < 0 { nextFetch = defaultFetchtime } else { nextFetch = time.Duration(0.8 * (float64)(nextFetch)) } t.fetcher = time.AfterFunc(nextFetch, t.fetch) } return nil } func (t *TrustStore) fetchBaseGraph(u *url.URL) (*trustgraph.Statement, error) { req := &http.Request{ Method: "GET", URL: u, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Body: nil, Host: u.Host, } resp, err := t.httpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode == 404 { return nil, errors.New("base graph does not exist") } defer resp.Body.Close() return trustgraph.LoadStatement(resp.Body, t.caPool) } // fetch retrieves updated base graphs. This function cannot error, it // should only log errors func (t *TrustStore) fetch() { t.Lock() defer t.Unlock() if t.autofetch && t.fetcher == nil { // Do nothing ?? return } fetchCount := 0 for bg, ep := range t.baseEndpoints { statement, err := t.fetchBaseGraph(ep) if err != nil { logrus.Infof("Trust graph fetch failed: %s", err) continue } b, err := statement.Bytes() if err != nil { logrus.Infof("Bad trust graph statement: %s", err) continue } // TODO check if value differs if err := ioutil.WriteFile(path.Join(t.path, bg+".json"), b, 0600); err != nil { logrus.Infof("Error writing trust graph statement: %s", err) } fetchCount++ } logrus.Debugf("Fetched %d base graphs at %s", fetchCount, time.Now()) if fetchCount > 0 { go func() { if err := t.reload(); err != nil { logrus.Infof("Reload of trust graph failed: %s", err) } }() t.fetchTime = defaultFetchtime t.fetcher = nil } else if t.autofetch { maxTime := 10 * defaultFetchtime t.fetchTime = time.Duration(1.5 * (float64)(t.fetchTime+time.Second)) if t.fetchTime > maxTime { t.fetchTime = maxTime } t.fetcher = time.AfterFunc(t.fetchTime, t.fetch) } } ================================================ FILE: vendor/github.com/docker/docker/utils/experimental.go ================================================ // +build experimental package utils // ExperimentalBuild is a stub which always returns true for // builds that include the "experimental" build tag func ExperimentalBuild() bool { return true } ================================================ FILE: vendor/github.com/docker/docker/utils/git.go ================================================ package utils import ( "fmt" "io/ioutil" "net/http" "net/url" "os" "os/exec" "path/filepath" "strings" "github.com/docker/docker/pkg/symlink" "github.com/docker/docker/pkg/urlutil" ) // GitClone clones a repository into a newly created directory which // will be under "docker-build-git" func GitClone(remoteURL string) (string, error) { if !urlutil.IsGitTransport(remoteURL) { remoteURL = "https://" + remoteURL } root, err := ioutil.TempDir("", "docker-build-git") if err != nil { return "", err } u, err := url.Parse(remoteURL) if err != nil { return "", err } fragment := u.Fragment clone := cloneArgs(u, root) if output, err := git(clone...); err != nil { return "", fmt.Errorf("Error trying to use git: %s (%s)", err, output) } return checkoutGit(fragment, root) } func cloneArgs(remoteURL *url.URL, root string) []string { args := []string{"clone", "--recursive"} shallow := len(remoteURL.Fragment) == 0 if shallow && strings.HasPrefix(remoteURL.Scheme, "http") { res, err := http.Head(fmt.Sprintf("%s/info/refs?service=git-upload-pack", remoteURL)) if err != nil || res.Header.Get("Content-Type") != "application/x-git-upload-pack-advertisement" { shallow = false } } if shallow { args = append(args, "--depth", "1") } if remoteURL.Fragment != "" { remoteURL.Fragment = "" } return append(args, remoteURL.String(), root) } func checkoutGit(fragment, root string) (string, error) { refAndDir := strings.SplitN(fragment, ":", 2) if len(refAndDir[0]) != 0 { if output, err := gitWithinDir(root, "checkout", refAndDir[0]); err != nil { return "", fmt.Errorf("Error trying to use git: %s (%s)", err, output) } } if len(refAndDir) > 1 && len(refAndDir[1]) != 0 { newCtx, err := symlink.FollowSymlinkInScope(filepath.Join(root, refAndDir[1]), root) if err != nil { return "", fmt.Errorf("Error setting git context, %q not within git root: %s", refAndDir[1], err) } fi, err := os.Stat(newCtx) if err != nil { return "", err } if !fi.IsDir() { return "", fmt.Errorf("Error setting git context, not a directory: %s", newCtx) } root = newCtx } return root, nil } func gitWithinDir(dir string, args ...string) ([]byte, error) { a := []string{"--work-tree", dir, "--git-dir", filepath.Join(dir, ".git")} return git(append(a, args...)...) } func git(args ...string) ([]byte, error) { return exec.Command("git", args...).CombinedOutput() } ================================================ FILE: vendor/github.com/docker/docker/utils/git_test.go ================================================ package utils import ( "fmt" "io/ioutil" "net/http" "net/http/httptest" "net/url" "os" "path/filepath" "reflect" "testing" ) func TestCloneArgsSmartHttp(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) serverURL, _ := url.Parse(server.URL) serverURL.Path = "/repo.git" gitURL := serverURL.String() mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) { q := r.URL.Query().Get("service") w.Header().Set("Content-Type", fmt.Sprintf("application/x-%s-advertisement", q)) }) args := cloneArgs(serverURL, "/tmp") exp := []string{"clone", "--recursive", "--depth", "1", gitURL, "/tmp"} if !reflect.DeepEqual(args, exp) { t.Fatalf("Expected %v, got %v", exp, args) } } func TestCloneArgsDumbHttp(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) serverURL, _ := url.Parse(server.URL) serverURL.Path = "/repo.git" gitURL := serverURL.String() mux.HandleFunc("/repo.git/info/refs", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain") }) args := cloneArgs(serverURL, "/tmp") exp := []string{"clone", "--recursive", gitURL, "/tmp"} if !reflect.DeepEqual(args, exp) { t.Fatalf("Expected %v, got %v", exp, args) } } func TestCloneArgsGit(t *testing.T) { u, _ := url.Parse("git://github.com/docker/docker") args := cloneArgs(u, "/tmp") exp := []string{"clone", "--recursive", "--depth", "1", "git://github.com/docker/docker", "/tmp"} if !reflect.DeepEqual(args, exp) { t.Fatalf("Expected %v, got %v", exp, args) } } func TestCloneArgsStripFragment(t *testing.T) { u, _ := url.Parse("git://github.com/docker/docker#test") args := cloneArgs(u, "/tmp") exp := []string{"clone", "--recursive", "git://github.com/docker/docker", "/tmp"} if !reflect.DeepEqual(args, exp) { t.Fatalf("Expected %v, got %v", exp, args) } } func TestCheckoutGit(t *testing.T) { root, err := ioutil.TempDir("", "docker-build-git-checkout") if err != nil { t.Fatal(err) } defer os.RemoveAll(root) gitDir := filepath.Join(root, "repo") _, err = git("init", gitDir) if err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "config", "user.email", "test@docker.com"); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "config", "user.name", "Docker test"); err != nil { t.Fatal(err) } if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch"), 0644); err != nil { t.Fatal(err) } subDir := filepath.Join(gitDir, "subdir") if err = os.Mkdir(subDir, 0755); err != nil { t.Fatal(err) } if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 5000"), 0644); err != nil { t.Fatal(err) } if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil { t.Fatal(err) } if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "commit", "-am", "First commit"); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "checkout", "-b", "test"); err != nil { t.Fatal(err) } if err = ioutil.WriteFile(filepath.Join(gitDir, "Dockerfile"), []byte("FROM scratch\nEXPOSE 3000"), 0644); err != nil { t.Fatal(err) } if err = ioutil.WriteFile(filepath.Join(subDir, "Dockerfile"), []byte("FROM busybox\nEXPOSE 5000"), 0644); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "commit", "-am", "Branch commit"); err != nil { t.Fatal(err) } if _, err = gitWithinDir(gitDir, "checkout", "master"); err != nil { t.Fatal(err) } cases := []struct { frag string exp string fail bool }{ {"", "FROM scratch", false}, {"master", "FROM scratch", false}, {":subdir", "FROM scratch\nEXPOSE 5000", false}, {":nosubdir", "", true}, // missing directory error {":Dockerfile", "", true}, // not a directory error {"master:nosubdir", "", true}, {"master:subdir", "FROM scratch\nEXPOSE 5000", false}, {"master:parentlink", "FROM scratch\nEXPOSE 5000", false}, {"master:absolutelink", "FROM scratch\nEXPOSE 5000", false}, {"master:../subdir", "", true}, {"test", "FROM scratch\nEXPOSE 3000", false}, {"test:", "FROM scratch\nEXPOSE 3000", false}, {"test:subdir", "FROM busybox\nEXPOSE 5000", false}, } for _, c := range cases { r, err := checkoutGit(c.frag, gitDir) fail := err != nil if fail != c.fail { t.Fatalf("Expected %v failure, error was %v\n", c.fail, err) } if c.fail { continue } b, err := ioutil.ReadFile(filepath.Join(r, "Dockerfile")) if err != nil { t.Fatal(err) } if string(b) != c.exp { t.Fatalf("Expected %v, was %v\n", c.exp, string(b)) } } } ================================================ FILE: vendor/github.com/docker/docker/utils/stubs.go ================================================ // +build !experimental package utils // ExperimentalBuild is a stub which always returns false for // builds that do not include the "experimental" build tag func ExperimentalBuild() bool { return false } ================================================ FILE: vendor/github.com/docker/docker/utils/utils.go ================================================ package utils import ( "bufio" "crypto/sha1" "encoding/hex" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "github.com/docker/docker/autogen/dockerversion" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/fileutils" "github.com/docker/docker/pkg/stringid" ) // SelfPath figures out the absolute path of our own binary (if it's still around). func SelfPath() string { path, err := exec.LookPath(os.Args[0]) if err != nil { if os.IsNotExist(err) { return "" } if execErr, ok := err.(*exec.Error); ok && os.IsNotExist(execErr.Err) { return "" } panic(err) } path, err = filepath.Abs(path) if err != nil { if os.IsNotExist(err) { return "" } panic(err) } return path } func dockerInitSha1(target string) string { f, err := os.Open(target) if err != nil { return "" } defer f.Close() h := sha1.New() _, err = io.Copy(h, f) if err != nil { return "" } return hex.EncodeToString(h.Sum(nil)) } func isValidDockerInitPath(target string, selfPath string) bool { // target and selfPath should be absolute (InitPath and SelfPath already do this) if target == "" { return false } if dockerversion.IAMSTATIC == "true" { if selfPath == "" { return false } if target == selfPath { return true } targetFileInfo, err := os.Lstat(target) if err != nil { return false } selfPathFileInfo, err := os.Lstat(selfPath) if err != nil { return false } return os.SameFile(targetFileInfo, selfPathFileInfo) } return dockerversion.INITSHA1 != "" && dockerInitSha1(target) == dockerversion.INITSHA1 } // DockerInitPath figures out the path of our dockerinit (which may be SelfPath()) func DockerInitPath(localCopy string) string { selfPath := SelfPath() if isValidDockerInitPath(selfPath, selfPath) { // if we're valid, don't bother checking anything else return selfPath } var possibleInits = []string{ localCopy, dockerversion.INITPATH, filepath.Join(filepath.Dir(selfPath), "dockerinit"), // FHS 3.0 Draft: "/usr/libexec includes internal binaries that are not intended to be executed directly by users or shell scripts. Applications may use a single subdirectory under /usr/libexec." // https://www.linuxbase.org/betaspecs/fhs/fhs.html#usrlibexec "/usr/libexec/docker/dockerinit", "/usr/local/libexec/docker/dockerinit", // FHS 2.3: "/usr/lib includes object files, libraries, and internal binaries that are not intended to be executed directly by users or shell scripts." // https://refspecs.linuxfoundation.org/FHS_2.3/fhs-2.3.html#USRLIBLIBRARIESFORPROGRAMMINGANDPA "/usr/lib/docker/dockerinit", "/usr/local/lib/docker/dockerinit", } for _, dockerInit := range possibleInits { if dockerInit == "" { continue } path, err := exec.LookPath(dockerInit) if err == nil { path, err = filepath.Abs(path) if err != nil { // LookPath already validated that this file exists and is executable (following symlinks), so how could Abs fail? panic(err) } if isValidDockerInitPath(path, selfPath) { return path } } } return "" } var globalTestID string // TestDirectory creates a new temporary directory and returns its path. // The contents of directory at path `templateDir` is copied into the // new directory. func TestDirectory(templateDir string) (dir string, err error) { if globalTestID == "" { globalTestID = stringid.GenerateRandomID()[:4] } prefix := fmt.Sprintf("docker-test%s-%s-", globalTestID, GetCallerName(2)) if prefix == "" { prefix = "docker-test-" } dir, err = ioutil.TempDir("", prefix) if err = os.Remove(dir); err != nil { return } if templateDir != "" { if err = archive.CopyWithTar(templateDir, dir); err != nil { return } } return } // GetCallerName introspects the call stack and returns the name of the // function `depth` levels down in the stack. func GetCallerName(depth int) string { // Use the caller function name as a prefix. // This helps trace temp directories back to their test. pc, _, _, _ := runtime.Caller(depth + 1) callerLongName := runtime.FuncForPC(pc).Name() parts := strings.Split(callerLongName, ".") callerShortName := parts[len(parts)-1] return callerShortName } // ReplaceOrAppendEnvValues returns the defaults with the overrides either // replaced by env key or appended to the list func ReplaceOrAppendEnvValues(defaults, overrides []string) []string { cache := make(map[string]int, len(defaults)) for i, e := range defaults { parts := strings.SplitN(e, "=", 2) cache[parts[0]] = i } for _, value := range overrides { // Values w/o = means they want this env to be removed/unset. if !strings.Contains(value, "=") { if i, exists := cache[value]; exists { defaults[i] = "" // Used to indicate it should be removed } continue } // Just do a normal set/update parts := strings.SplitN(value, "=", 2) if i, exists := cache[parts[0]]; exists { defaults[i] = value } else { defaults = append(defaults, value) } } // Now remove all entries that we want to "unset" for i := 0; i < len(defaults); i++ { if defaults[i] == "" { defaults = append(defaults[:i], defaults[i+1:]...) i-- } } return defaults } // 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 { return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error { // skip this directory/file if it's not in the path, it won't get added to the context if relFilePath, err := filepath.Rel(srcPath, 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 } if err != nil { if os.IsPermission(err) { return fmt.Errorf("can't stat '%s'", filePath) } if os.IsNotExist(err) { return nil } return err } // 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 fmt.Errorf("no permission to read from '%s'", filePath) } currentFile.Close() } return nil }) } // ReadDockerIgnore reads a .dockerignore file and returns the list of file patterns // to ignore. Note this will trim whitespace from each line as well // as use GO's "clean" func to get the shortest/cleanest path for each. func ReadDockerIgnore(path string) ([]string, error) { // Note that a missing .dockerignore file isn't treated as an error reader, err := os.Open(path) if err != nil { if !os.IsNotExist(err) { return nil, fmt.Errorf("Error reading '%s': %v", path, err) } return nil, nil } defer reader.Close() scanner := bufio.NewScanner(reader) var excludes []string for scanner.Scan() { pattern := strings.TrimSpace(scanner.Text()) if pattern == "" { continue } pattern = filepath.Clean(pattern) excludes = append(excludes, pattern) } if err = scanner.Err(); err != nil { return nil, fmt.Errorf("Error reading '%s': %v", path, err) } return excludes, nil } // ImageReference combines `repo` and `ref` and returns a string representing // the combination. If `ref` is a digest (meaning it's of the form // :, the returned string is @. Otherwise, // ref is assumed to be a tag, and the returned string is :. func ImageReference(repo, ref string) string { if DigestReference(ref) { return repo + "@" + ref } return repo + ":" + ref } // DigestReference returns true if ref is a digest reference; i.e. if it // is of the form :. func DigestReference(ref string) bool { return strings.Contains(ref, ":") } ================================================ FILE: vendor/github.com/docker/docker/utils/utils_test.go ================================================ package utils import ( "fmt" "io/ioutil" "os" "path/filepath" "testing" ) func TestReplaceAndAppendEnvVars(t *testing.T) { var ( d = []string{"HOME=/"} o = []string{"HOME=/root", "TERM=xterm"} ) env := ReplaceOrAppendEnvValues(d, o) if len(env) != 2 { t.Fatalf("expected len of 2 got %d", len(env)) } if env[0] != "HOME=/root" { t.Fatalf("expected HOME=/root got '%s'", env[0]) } if env[1] != "TERM=xterm" { t.Fatalf("expected TERM=xterm got '%s'", env[1]) } } func TestImageReference(t *testing.T) { tests := []struct { repo string ref string expected string }{ {"repo", "tag", "repo:tag"}, {"repo", "sha256:c100b11b25d0cacd52c14e0e7bf525e1a4c0e6aec8827ae007055545909d1a64", "repo@sha256:c100b11b25d0cacd52c14e0e7bf525e1a4c0e6aec8827ae007055545909d1a64"}, } for i, test := range tests { actual := ImageReference(test.repo, test.ref) if test.expected != actual { t.Errorf("%d: expected %q, got %q", i, test.expected, actual) } } } func TestDigestReference(t *testing.T) { input := "sha256:c100b11b25d0cacd52c14e0e7bf525e1a4c0e6aec8827ae007055545909d1a64" if !DigestReference(input) { t.Errorf("Expected DigestReference=true for input %q", input) } input = "latest" if DigestReference(input) { t.Errorf("Unexpected DigestReference=true for input %q", input) } } func TestReadDockerIgnore(t *testing.T) { tmpDir, err := ioutil.TempDir("", "dockerignore-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) diName := filepath.Join(tmpDir, ".dockerignore") di, err := ReadDockerIgnore(diName) if err != nil { t.Fatalf("Expected not to have error, got %s", err) } if diLen := len(di); diLen != 0 { t.Fatalf("Expected to have zero dockerignore entry, got %d", diLen) } content := fmt.Sprintf("test1\n/test2\n/a/file/here\n\nlastfile") err = ioutil.WriteFile(diName, []byte(content), 0777) if err != nil { t.Fatal(err) } di, err = ReadDockerIgnore(diName) if err != nil { t.Fatal(err) } if di[0] != "test1" { t.Fatalf("First element is not test1") } if di[1] != "/test2" { t.Fatalf("Second element is not /test2") } if di[2] != "/a/file/here" { t.Fatalf("Third element is not /a/file/here") } if di[3] != "lastfile" { t.Fatalf("Fourth element is not lastfile") } } ================================================ FILE: vendor/github.com/docker/docker/volume/drivers/adapter.go ================================================ package volumedrivers import "github.com/docker/docker/volume" type volumeDriverAdapter struct { name string proxy *volumeDriverProxy } func (a *volumeDriverAdapter) Name() string { return a.name } func (a *volumeDriverAdapter) Create(name string) (volume.Volume, error) { err := a.proxy.Create(name) if err != nil { return nil, err } return &volumeAdapter{ proxy: a.proxy, name: name, driverName: a.name}, nil } func (a *volumeDriverAdapter) Remove(v volume.Volume) error { return a.proxy.Remove(v.Name()) } type volumeAdapter struct { proxy *volumeDriverProxy name string driverName string eMount string // ephemeral host volume path } func (a *volumeAdapter) Name() string { return a.name } func (a *volumeAdapter) DriverName() string { return a.driverName } func (a *volumeAdapter) Path() string { if len(a.eMount) > 0 { return a.eMount } m, _ := a.proxy.Path(a.name) return m } func (a *volumeAdapter) Mount() (string, error) { var err error a.eMount, err = a.proxy.Mount(a.name) return a.eMount, err } func (a *volumeAdapter) Unmount() error { return a.proxy.Unmount(a.name) } ================================================ FILE: vendor/github.com/docker/docker/volume/drivers/api.go ================================================ //go:generate pluginrpc-gen -i $GOFILE -o proxy.go -type VolumeDriver -name VolumeDriver package volumedrivers import "github.com/docker/docker/volume" func NewVolumeDriver(name string, c client) volume.Driver { proxy := &volumeDriverProxy{c} return &volumeDriverAdapter{name, proxy} } type VolumeDriver interface { // Create a volume with the given name Create(name string) (err error) // Remove the volume with the given name Remove(name string) (err error) // Get the mountpoint of the given volume Path(name string) (mountpoint string, err error) // Mount the given volume and return the mountpoint Mount(name string) (mountpoint string, err error) // Unmount the given volume Unmount(name string) (err error) } ================================================ FILE: vendor/github.com/docker/docker/volume/drivers/extpoint.go ================================================ package volumedrivers import ( "fmt" "sync" "github.com/docker/docker/pkg/plugins" "github.com/docker/docker/volume" ) // currently created by hand. generation tool would generate this like: // $ extpoint-gen Driver > volume/extpoint.go var drivers = &driverExtpoint{extensions: make(map[string]volume.Driver)} type driverExtpoint struct { extensions map[string]volume.Driver sync.Mutex } func Register(extension volume.Driver, name string) bool { drivers.Lock() defer drivers.Unlock() if name == "" { return false } _, exists := drivers.extensions[name] if exists { return false } drivers.extensions[name] = extension return true } func Unregister(name string) bool { drivers.Lock() defer drivers.Unlock() _, exists := drivers.extensions[name] if !exists { return false } delete(drivers.extensions, name) return true } func Lookup(name string) (volume.Driver, error) { drivers.Lock() defer drivers.Unlock() ext, ok := drivers.extensions[name] if ok { return ext, nil } pl, err := plugins.Get(name, "VolumeDriver") if err != nil { return nil, fmt.Errorf("Error looking up volume plugin %s: %v", name, err) } d := NewVolumeDriver(name, pl.Client) drivers.extensions[name] = d return d, nil } ================================================ FILE: vendor/github.com/docker/docker/volume/drivers/proxy.go ================================================ // generated code - DO NOT EDIT package volumedrivers import "errors" type client interface { Call(string, interface{}, interface{}) error } type volumeDriverProxy struct { client } type volumeDriverProxyCreateRequest struct { Name string } type volumeDriverProxyCreateResponse struct { Err string } func (pp *volumeDriverProxy) Create(name string) (err error) { var ( req volumeDriverProxyCreateRequest ret volumeDriverProxyCreateResponse ) req.Name = name if err = pp.Call("VolumeDriver.Create", req, &ret); err != nil { return } if ret.Err != "" { err = errors.New(ret.Err) } return } type volumeDriverProxyRemoveRequest struct { Name string } type volumeDriverProxyRemoveResponse struct { Err string } func (pp *volumeDriverProxy) Remove(name string) (err error) { var ( req volumeDriverProxyRemoveRequest ret volumeDriverProxyRemoveResponse ) req.Name = name if err = pp.Call("VolumeDriver.Remove", req, &ret); err != nil { return } if ret.Err != "" { err = errors.New(ret.Err) } return } type volumeDriverProxyPathRequest struct { Name string } type volumeDriverProxyPathResponse struct { Mountpoint string Err string } func (pp *volumeDriverProxy) Path(name string) (mountpoint string, err error) { var ( req volumeDriverProxyPathRequest ret volumeDriverProxyPathResponse ) req.Name = name if err = pp.Call("VolumeDriver.Path", req, &ret); err != nil { return } mountpoint = ret.Mountpoint if ret.Err != "" { err = errors.New(ret.Err) } return } type volumeDriverProxyMountRequest struct { Name string } type volumeDriverProxyMountResponse struct { Mountpoint string Err string } func (pp *volumeDriverProxy) Mount(name string) (mountpoint string, err error) { var ( req volumeDriverProxyMountRequest ret volumeDriverProxyMountResponse ) req.Name = name if err = pp.Call("VolumeDriver.Mount", req, &ret); err != nil { return } mountpoint = ret.Mountpoint if ret.Err != "" { err = errors.New(ret.Err) } return } type volumeDriverProxyUnmountRequest struct { Name string } type volumeDriverProxyUnmountResponse struct { Err string } func (pp *volumeDriverProxy) Unmount(name string) (err error) { var ( req volumeDriverProxyUnmountRequest ret volumeDriverProxyUnmountResponse ) req.Name = name if err = pp.Call("VolumeDriver.Unmount", req, &ret); err != nil { return } if ret.Err != "" { err = errors.New(ret.Err) } return } ================================================ FILE: vendor/github.com/docker/docker/volume/drivers/proxy_test.go ================================================ package volumedrivers import ( "fmt" "net/http" "net/http/httptest" "net/url" "strings" "testing" "github.com/docker/docker/pkg/plugins" "github.com/docker/docker/pkg/tlsconfig" ) func TestVolumeRequestError(t *testing.T) { mux := http.NewServeMux() server := httptest.NewServer(mux) defer server.Close() mux.HandleFunc("/VolumeDriver.Create", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{"Err": "Cannot create volume"}`) }) mux.HandleFunc("/VolumeDriver.Remove", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{"Err": "Cannot remove volume"}`) }) mux.HandleFunc("/VolumeDriver.Mount", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{"Err": "Cannot mount volume"}`) }) mux.HandleFunc("/VolumeDriver.Unmount", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{"Err": "Cannot unmount volume"}`) }) mux.HandleFunc("/VolumeDriver.Path", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/vnd.docker.plugins.v1+json") fmt.Fprintln(w, `{"Err": "Unknown volume"}`) }) u, _ := url.Parse(server.URL) client, err := plugins.NewClient("tcp://"+u.Host, tlsconfig.Options{InsecureSkipVerify: true}) if err != nil { t.Fatal(err) } driver := volumeDriverProxy{client} if err = driver.Create("volume"); err == nil { t.Fatal("Expected error, was nil") } if !strings.Contains(err.Error(), "Cannot create volume") { t.Fatalf("Unexpected error: %v\n", err) } _, err = driver.Mount("volume") if err == nil { t.Fatal("Expected error, was nil") } if !strings.Contains(err.Error(), "Cannot mount volume") { t.Fatalf("Unexpected error: %v\n", err) } err = driver.Unmount("volume") if err == nil { t.Fatal("Expected error, was nil") } if !strings.Contains(err.Error(), "Cannot unmount volume") { t.Fatalf("Unexpected error: %v\n", err) } err = driver.Remove("volume") if err == nil { t.Fatal("Expected error, was nil") } if !strings.Contains(err.Error(), "Cannot remove volume") { t.Fatalf("Unexpected error: %v\n", err) } _, err = driver.Path("volume") if err == nil { t.Fatal("Expected error, was nil") } if !strings.Contains(err.Error(), "Unknown volume") { t.Fatalf("Unexpected error: %v\n", err) } } ================================================ FILE: vendor/github.com/docker/docker/volume/local/local.go ================================================ package local import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "strings" "sync" "github.com/docker/docker/volume" ) // VolumeDataPathName is the name of the directory where the volume data is stored. // It uses a very distintive name to avoid colissions migrating data between // Docker versions. const ( VolumeDataPathName = "_data" volumesPathName = "volumes" ) var oldVfsDir = filepath.Join("vfs", "dir") func New(scope string) (*Root, error) { rootDirectory := filepath.Join(scope, volumesPathName) if err := os.MkdirAll(rootDirectory, 0700); err != nil { return nil, err } r := &Root{ scope: scope, path: rootDirectory, volumes: make(map[string]*Volume), } dirs, err := ioutil.ReadDir(rootDirectory) if err != nil { return nil, err } for _, d := range dirs { name := filepath.Base(d.Name()) r.volumes[name] = &Volume{ driverName: r.Name(), name: name, path: r.DataPath(name), } } return r, nil } type Root struct { m sync.Mutex scope string path string volumes map[string]*Volume } func (r *Root) DataPath(volumeName string) string { return filepath.Join(r.path, volumeName, VolumeDataPathName) } func (r *Root) Name() string { return "local" } func (r *Root) Create(name string) (volume.Volume, error) { r.m.Lock() defer r.m.Unlock() v, exists := r.volumes[name] if !exists { path := r.DataPath(name) if err := os.MkdirAll(path, 0755); err != nil { if os.IsExist(err) { return nil, fmt.Errorf("volume already exists under %s", filepath.Dir(path)) } return nil, err } v = &Volume{ driverName: r.Name(), name: name, path: path, } r.volumes[name] = v } v.use() return v, nil } func (r *Root) Remove(v volume.Volume) error { r.m.Lock() defer r.m.Unlock() lv, ok := v.(*Volume) if !ok { return errors.New("unknown volume type") } lv.release() if lv.usedCount == 0 { realPath, err := filepath.EvalSymlinks(lv.path) if err != nil { return err } if !r.scopedPath(realPath) { return fmt.Errorf("Unable to remove a directory of out the Docker root: %s", realPath) } if err := os.RemoveAll(realPath); err != nil { return err } delete(r.volumes, lv.name) return os.RemoveAll(filepath.Dir(lv.path)) } return nil } // scopedPath verifies that the path where the volume is located // is under Docker's root and the valid local paths. func (r *Root) scopedPath(realPath string) bool { // Volumes path for Docker version >= 1.7 if strings.HasPrefix(realPath, filepath.Join(r.scope, volumesPathName)) { return true } // Volumes path for Docker version < 1.7 if strings.HasPrefix(realPath, filepath.Join(r.scope, oldVfsDir)) { return true } return false } type Volume struct { m sync.Mutex usedCount int // unique name of the volume name string // path is the path on the host where the data lives path string // driverName is the name of the driver that created the volume. driverName string } func (v *Volume) Name() string { return v.name } func (v *Volume) DriverName() string { return v.driverName } func (v *Volume) Path() string { return v.path } func (v *Volume) Mount() (string, error) { return v.path, nil } func (v *Volume) Unmount() error { return nil } func (v *Volume) use() { v.m.Lock() v.usedCount++ v.m.Unlock() } func (v *Volume) release() { v.m.Lock() v.usedCount-- v.m.Unlock() } ================================================ FILE: vendor/github.com/docker/docker/volume/volume.go ================================================ package volume const DefaultDriverName = "local" type Driver interface { // Name returns the name of the volume driver. Name() string // Create makes a new volume with the given id. Create(string) (Volume, error) // Remove deletes the volume. Remove(Volume) error } type Volume interface { // Name returns the name of the volume Name() string // DriverName returns the name of the driver which owns this volume. DriverName() string // Path returns the absolute path to the volume. Path() string // Mount mounts the volume and returns the absolute path to // where it can be consumed. Mount() (string, error) // Unmount unmounts the volume when it is no longer in use. Unmount() error } // read-write modes var rwModes = map[string]bool{ "rw": true, "rw,Z": true, "rw,z": true, "z,rw": true, "Z,rw": true, "Z": true, "z": true, } // read-only modes var roModes = map[string]bool{ "ro": true, "ro,Z": true, "ro,z": true, "z,ro": true, "Z,ro": true, } // ValidateMountMode will make sure the mount mode is valid. // returns if it's a valid mount mode and if it's read-write or not. func ValidateMountMode(mode string) (bool, bool) { return roModes[mode] || rwModes[mode], rwModes[mode] } // ReadOnly tells you if a mode string is a valid read-only mode or not. func ReadWrite(mode string) bool { return rwModes[mode] } ================================================ FILE: vendor/github.com/docker/go-units/CONTRIBUTING.md ================================================ # Contributing to go-units Want to hack on go-units? Awesome! Here are instructions to get you started. go-units is a part of the [Docker](https://www.docker.com) project, and follows the same rules and principles. If you're already familiar with the way Docker does things, you'll feel right at home. Otherwise, go read Docker's [contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), [issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), [review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and [branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). ### Sign your work The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch 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 Use your real name (sorry, no pseudonyms or anonymous contributions.) If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. ================================================ FILE: vendor/github.com/docker/go-units/LICENSE.code ================================================ 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. ================================================ FILE: vendor/github.com/docker/go-units/LICENSE.docs ================================================ 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. ================================================ FILE: vendor/github.com/docker/go-units/MAINTAINERS ================================================ # go-connections maintainers file # # This file describes who runs the docker/go-connections project and how. # This is a living document - if you see something out of date or missing, speak up! # # It is structured to be consumable by both humans and programs. # To extract its contents programmatically, use any TOML-compliant parser. # # This file is compiled into the MAINTAINERS file in docker/opensource. # [Org] [Org."Core maintainers"] people = [ "calavera", ] [people] # A reference list of all people associated with the project. # All other sections should refer to people by their canonical key # in the people section. # ADD YOURSELF HERE IN ALPHABETICAL ORDER [people.calavera] Name = "David Calavera" Email = "david.calavera@gmail.com" GitHub = "calavera" ================================================ FILE: vendor/github.com/docker/go-units/README.md ================================================ [![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. 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/. ================================================ FILE: vendor/github.com/docker/go-units/circle.yml ================================================ dependencies: post: # install golint - go get github.com/golang/lint/golint test: pre: # run analysis before tests - go vet ./... - test -z "$(golint ./... | tee /dev/stderr)" - test -z "$(gofmt -s -l . | tee /dev/stderr)" ================================================ FILE: vendor/github.com/docker/go-units/duration.go ================================================ // 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 < 60 { return fmt.Sprintf("%d seconds", seconds) } else if minutes := int(d.Minutes()); minutes == 1 { return "About a minute" } else if minutes < 60 { return fmt.Sprintf("%d minutes", minutes) } else if hours := int(d.Hours()); 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*3 { 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) } ================================================ FILE: vendor/github.com/docker/go-units/duration_test.go ================================================ package units import ( "fmt" "testing" "time" ) func ExampleHumanDuration() { fmt.Println(HumanDuration(450 * time.Millisecond)) fmt.Println(HumanDuration(47 * time.Second)) fmt.Println(HumanDuration(1 * time.Minute)) fmt.Println(HumanDuration(3 * time.Minute)) fmt.Println(HumanDuration(35 * time.Minute)) fmt.Println(HumanDuration(35*time.Minute + 40*time.Second)) fmt.Println(HumanDuration(1 * time.Hour)) fmt.Println(HumanDuration(1*time.Hour + 45*time.Minute)) fmt.Println(HumanDuration(3 * time.Hour)) fmt.Println(HumanDuration(3*time.Hour + 59*time.Minute)) fmt.Println(HumanDuration(3*time.Hour + 60*time.Minute)) fmt.Println(HumanDuration(24 * time.Hour)) fmt.Println(HumanDuration(24*time.Hour + 12*time.Hour)) fmt.Println(HumanDuration(2 * 24 * time.Hour)) fmt.Println(HumanDuration(7 * 24 * time.Hour)) fmt.Println(HumanDuration(13*24*time.Hour + 5*time.Hour)) fmt.Println(HumanDuration(2 * 7 * 24 * time.Hour)) fmt.Println(HumanDuration(2*7*24*time.Hour + 4*24*time.Hour)) fmt.Println(HumanDuration(3 * 7 * 24 * time.Hour)) fmt.Println(HumanDuration(4 * 7 * 24 * time.Hour)) fmt.Println(HumanDuration(4*7*24*time.Hour + 3*24*time.Hour)) fmt.Println(HumanDuration(1 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(1*30*24*time.Hour + 2*7*24*time.Hour)) fmt.Println(HumanDuration(2 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(3*30*24*time.Hour + 1*7*24*time.Hour)) fmt.Println(HumanDuration(5*30*24*time.Hour + 2*7*24*time.Hour)) fmt.Println(HumanDuration(13 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(23 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(24 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(24*30*24*time.Hour + 2*7*24*time.Hour)) fmt.Println(HumanDuration(3*365*24*time.Hour + 2*30*24*time.Hour)) } func TestHumanDuration(t *testing.T) { // Useful duration abstractions day := 24 * time.Hour week := 7 * day month := 30 * day year := 365 * day assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) assertEquals(t, "2 days", HumanDuration(2*day)) assertEquals(t, "7 days", HumanDuration(7*day)) assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) assertEquals(t, "2 weeks", HumanDuration(2*week)) assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) assertEquals(t, "3 weeks", HumanDuration(3*week)) assertEquals(t, "4 weeks", HumanDuration(4*week)) assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) assertEquals(t, "4 weeks", HumanDuration(1*month)) assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) assertEquals(t, "8 weeks", HumanDuration(2*month)) assertEquals(t, "3 months", HumanDuration(3*month+1*week)) assertEquals(t, "5 months", HumanDuration(5*month+2*week)) assertEquals(t, "13 months", HumanDuration(13*month)) assertEquals(t, "23 months", HumanDuration(23*month)) assertEquals(t, "24 months", HumanDuration(24*month)) assertEquals(t, "2 years", HumanDuration(24*month+2*week)) assertEquals(t, "3 years", HumanDuration(3*year+2*month)) } ================================================ FILE: vendor/github.com/docker/go-units/size.go ================================================ 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+)([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"} // CustomSize returns a human-readable approximation of a size // using custom format. func CustomSize(format string, size float64, base float64, _map []string) string { i := 0 for size >= base { size = size / base i++ } return fmt.Sprintf(format, size, _map[i]) } // 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 CustomSize("%.4g %s", size, 1000.0, decimapAbbrs) } // 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) != 3 { return -1, fmt.Errorf("invalid size: '%s'", sizeStr) } size, err := strconv.ParseInt(matches[1], 10, 0) if err != nil { return -1, err } unitPrefix := strings.ToLower(matches[2]) if mul, ok := uMap[unitPrefix]; ok { size *= mul } return size, nil } ================================================ FILE: vendor/github.com/docker/go-units/size_test.go ================================================ package units import ( "fmt" "reflect" "runtime" "strings" "testing" ) func ExampleBytesSize() { fmt.Println(BytesSize(1024)) fmt.Println(BytesSize(1024 * 1024)) fmt.Println(BytesSize(1048576)) fmt.Println(BytesSize(2 * MiB)) fmt.Println(BytesSize(3.42 * GiB)) fmt.Println(BytesSize(5.372 * TiB)) fmt.Println(BytesSize(2.22 * PiB)) } func ExampleHumanSize() { fmt.Println(HumanSize(1000)) fmt.Println(HumanSize(1024)) fmt.Println(HumanSize(1000000)) fmt.Println(HumanSize(1048576)) fmt.Println(HumanSize(2 * MB)) fmt.Println(HumanSize(float64(3.42 * GB))) fmt.Println(HumanSize(float64(5.372 * TB))) fmt.Println(HumanSize(float64(2.22 * PB))) } func ExampleFromHumanSize() { fmt.Println(FromHumanSize("32")) fmt.Println(FromHumanSize("32b")) fmt.Println(FromHumanSize("32B")) fmt.Println(FromHumanSize("32k")) fmt.Println(FromHumanSize("32K")) fmt.Println(FromHumanSize("32kb")) fmt.Println(FromHumanSize("32Kb")) fmt.Println(FromHumanSize("32Mb")) fmt.Println(FromHumanSize("32Gb")) fmt.Println(FromHumanSize("32Tb")) fmt.Println(FromHumanSize("32Pb")) } func ExampleRAMInBytes() { fmt.Println(RAMInBytes("32")) fmt.Println(RAMInBytes("32b")) fmt.Println(RAMInBytes("32B")) fmt.Println(RAMInBytes("32k")) fmt.Println(RAMInBytes("32K")) fmt.Println(RAMInBytes("32kb")) fmt.Println(RAMInBytes("32Kb")) fmt.Println(RAMInBytes("32Mb")) fmt.Println(RAMInBytes("32Gb")) fmt.Println(RAMInBytes("32Tb")) fmt.Println(RAMInBytes("32Pb")) fmt.Println(RAMInBytes("32PB")) fmt.Println(RAMInBytes("32P")) } func TestBytesSize(t *testing.T) { assertEquals(t, "1 KiB", BytesSize(1024)) assertEquals(t, "1 MiB", BytesSize(1024*1024)) assertEquals(t, "1 MiB", BytesSize(1048576)) assertEquals(t, "2 MiB", BytesSize(2*MiB)) assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) } func TestHumanSize(t *testing.T) { assertEquals(t, "1 kB", HumanSize(1000)) assertEquals(t, "1.024 kB", HumanSize(1024)) assertEquals(t, "1 MB", HumanSize(1000000)) assertEquals(t, "1.049 MB", HumanSize(1048576)) assertEquals(t, "2 MB", HumanSize(2*MB)) assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) } func TestFromHumanSize(t *testing.T) { assertSuccessEquals(t, 32, FromHumanSize, "32") assertSuccessEquals(t, 32, FromHumanSize, "32b") assertSuccessEquals(t, 32, FromHumanSize, "32B") assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") assertError(t, FromHumanSize, "") assertError(t, FromHumanSize, "hello") assertError(t, FromHumanSize, "-32") assertError(t, FromHumanSize, "32.3") assertError(t, FromHumanSize, " 32 ") assertError(t, FromHumanSize, "32.3Kb") assertError(t, FromHumanSize, "32 mb") assertError(t, FromHumanSize, "32m b") assertError(t, FromHumanSize, "32bm") } func TestRAMInBytes(t *testing.T) { assertSuccessEquals(t, 32, RAMInBytes, "32") assertSuccessEquals(t, 32, RAMInBytes, "32b") assertSuccessEquals(t, 32, RAMInBytes, "32B") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") assertError(t, RAMInBytes, "") assertError(t, RAMInBytes, "hello") assertError(t, RAMInBytes, "-32") assertError(t, RAMInBytes, "32.3") assertError(t, RAMInBytes, " 32 ") assertError(t, RAMInBytes, "32.3Kb") assertError(t, RAMInBytes, "32 mb") assertError(t, RAMInBytes, "32m b") assertError(t, RAMInBytes, "32bm") } func assertEquals(t *testing.T, expected, actual interface{}) { if expected != actual { t.Errorf("Expected '%v' but got '%v'", expected, actual) } } // func that maps to the parse function signatures as testing abstraction type parseFn func(string) (int64, error) // Define 'String()' for pretty-print func (fn parseFn) String() string { fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() return fnName[strings.LastIndex(fnName, ".")+1:] } func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { res, err := fn(arg) if err != nil || res != expected { t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) } } func assertError(t *testing.T, fn parseFn, arg string) { res, err := fn(arg) if err == nil && res != -1 { t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) } } ================================================ FILE: vendor/github.com/docker/go-units/ulimit.go ================================================ 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) } ================================================ FILE: vendor/github.com/docker/go-units/ulimit_test.go ================================================ package units import ( "fmt" "strconv" "testing" ) func ExampleParseUlimit() { fmt.Println(ParseUlimit("nofile=512:1024")) fmt.Println(ParseUlimit("nofile=1024")) fmt.Println(ParseUlimit("cpu=2:4")) fmt.Println(ParseUlimit("cpu=6")) } func TestParseUlimitValid(t *testing.T) { u1 := &Ulimit{"nofile", 1024, 512} if u2, _ := ParseUlimit("nofile=512:1024"); *u1 != *u2 { t.Fatalf("expected %q, but got %q", u1, u2) } } func TestParseUlimitInvalidLimitType(t *testing.T) { if _, err := ParseUlimit("notarealtype=1024:1024"); err == nil { t.Fatalf("expected error on invalid ulimit type") } } func TestParseUlimitBadFormat(t *testing.T) { if _, err := ParseUlimit("nofile:1024:1024"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile="); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile=:"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile=:1024"); err == nil { t.Fatal("expected error on bad syntax") } } func TestParseUlimitHardLessThanSoft(t *testing.T) { if _, err := ParseUlimit("nofile=1024:1"); err == nil { t.Fatal("expected error on hard limit less than soft limit") } } func TestParseUlimitInvalidValueType(t *testing.T) { if _, err := ParseUlimit("nofile=asdf"); err == nil { t.Fatal("expected error on bad value type, but got no error") } else if _, ok := err.(*strconv.NumError); !ok { t.Fatalf("expected error on bad value type, but got `%s`", err) } if _, err := ParseUlimit("nofile=1024:asdf"); err == nil { t.Fatal("expected error on bad value type, but got no error") } else if _, ok := err.(*strconv.NumError); !ok { t.Fatalf("expected error on bad value type, but got `%s`", err) } } func TestUlimitStringOutput(t *testing.T) { u := &Ulimit{"nofile", 1024, 512} if s := u.String(); s != "nofile=512:1024" { t.Fatal("expected String to return nofile=512:1024, but got", s) } } ================================================ FILE: vendor/github.com/docker/libcontainer/.gitignore ================================================ bundles nsinit/nsinit vendor/pkg ================================================ FILE: vendor/github.com/docker/libcontainer/CONTRIBUTING.md ================================================ # The libcontainer Contributors' Guide Want to hack on libcontainer? Awesome! Here are instructions to get you started. They are probably not perfect, please let us know if anything feels wrong or incomplete. ## Reporting Issues When reporting [issues](https://github.com/docker/libcontainer/issues) on GitHub please include your host OS (Ubuntu 12.04, Fedora 19, etc), the output of `uname -a`. Please include the steps required to reproduce the problem if possible and applicable. This information will help us review and fix your issue faster. ## Development Environment ### Requirements For best results, use a Linux development environment. The following packages are required to compile libcontainer natively. - Golang 1.3 - GCC - git - cgutils You can develop on OSX, but you are limited to Dockerfile-based builds only. ### Building libcontainer from Dockerfile make all This is the easiest way of building libcontainer. As this build is done using Docker, you can even run this from [OSX](https://github.com/boot2docker/boot2docker) ### Testing changes with "nsinit" make sh This will create an container that runs `nsinit exec sh` on a busybox rootfs with the configuration from ['minimal.json'](https://github.com/docker/libcontainer/blob/master/sample_configs/minimal.json). Like the previous command, you can run this on OSX too! ### Building libcontainer directly > Note: You should add the `vendor` directory to your GOPATH to use the vendored libraries ./update-vendor.sh go get -d ./... make direct-build # Run the tests make direct-test-short | egrep --color 'FAIL|$' # Run all the test make direct-test | egrep --color 'FAIL|$' ### Testing Changes with "nsinit" directly To test a change: # Install nsinit make direct-install # Optional, add a docker0 bridge ip link add docker0 type bridge ifconfig docker0 172.17.0.1/16 up mkdir testfs curl -sSL https://github.com/jpetazzo/docker-busybox/raw/buildroot-2014.02/rootfs.tar | tar -xC testfs cd testfs cp container.json nsinit exec sh ## Contribution Guidelines ### Pull requests are always welcome We are always thrilled to receive pull requests, and do our best to process them as fast as possible. Not sure if that typo is worth a pull request? Do it! We will appreciate it. If your pull request is not accepted on the first try, don't be discouraged! If there's a problem with the implementation, hopefully you received feedback on what to improve. We're trying very hard to keep libcontainer lean and focused. We don't want it to do everything for everybody. This means that we might decide against incorporating a new feature. However, there might be a way to implement that feature *on top of* libcontainer. ### Discuss your design on the mailing list We recommend discussing your plans [on the mailing list](https://groups.google.com/forum/?fromgroups#!forum/libcontainer) before starting to code - especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give feedback on your design, and maybe point out if someone else is working on the same thing. ### Create issues... Any significant improvement should be documented as [a GitHub issue](https://github.com/docker/libcontainer/issues) before anybody starts working on it. ### ...but check for existing issues first! Please take a moment to check that an issue doesn't already exist documenting your bug report or improvement proposal. If it does, it never hurts to add a quick "+1" or "I have this problem too". This will help prioritize the most common problems and requests. ### Conventions Fork the repo and make changes on your fork in a feature branch: - If it's a bugfix branch, name it XXX-something where XXX is the number of the issue - If it's a feature branch, create an enhancement issue to announce your intentions, and name it XXX-something where XXX is the number of the issue. Submit unit tests for your changes. Go has a great test framework built in; use it! Take a look at existing tests for inspiration. Run the full test suite on your branch before submitting a pull request. Update the documentation when creating or modifying features. Test your documentation changes for clarity, concision, and correctness, as well as a clean documentation build. See ``docs/README.md`` for more information on building the docs and how docs get released. Write clean code. Universally formatted code promotes ease of writing, reading, and maintenance. Always run `gofmt -s -w file.go` on each changed file before committing your changes. Most editors have plugins that do this automatically. Pull requests descriptions should be as clear as possible and include a reference to all the issues that they address. Pull requests must not contain commits from other users or branches. Commit messages must start with a capitalized and short summary (max. 50 chars) written in the imperative, followed by an optional, more detailed explanatory text which is separated from the summary by an empty line. Code review comments may be added to your pull request. Discuss, then make the suggested modifications and push additional commits to your feature branch. Be sure to post a comment after pushing. The new commits will show up in the pull request automatically, but the reviewers will not be notified unless you comment. Before the pull request is merged, make sure that you squash your commits into logical units of work using `git rebase -i` and `git push -f`. After every commit the test suite should be passing. Include documentation changes in the same commit so that a revert would remove all traces of the feature or fix. Commits that fix or close an issue should include a reference like `Closes #XXX` or `Fixes #XXX`, which will automatically close the issue when merged. ### Testing Make sure you include suitable tests, preferably unit tests, in your pull request and that all the tests pass. *Instructions for running tests to be added.* ### Merge approval libcontainer maintainers use LGTM (looks good to me) in comments on the code review to indicate acceptance. A change requires LGTMs from at lease two maintainers. One of those must come from a maintainer of the component affected. For example, if a change affects `netlink/` and `security`, it needs at least one LGTM from a maintainer of each. Maintainers only need one LGTM as presumably they LGTM their own change. For more details see [MAINTAINERS.md](MAINTAINERS.md) ### 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: Docker-DCO-1.1-Signed-off-by: Joe Smith (github: github_handle) using your real name (sorry, no pseudonyms or anonymous contributions.) One way to automate this, is customise your get ``commit.template`` by adding a ``prepare-commit-msg`` hook to your libcontainer checkout: ``` curl -o .git/hooks/prepare-commit-msg https://raw.githubusercontent.com/docker/docker/master/contrib/prepare-commit-msg.hook && chmod +x .git/hooks/prepare-commit-msg ``` * Note: the above script expects to find your GitHub user name in ``git config --get github.user`` #### Small patch exception There are several exceptions to the signing requirement. Currently these are: * Your patch fixes spelling or grammar errors. * Your patch is a single line change to documentation contained in the `docs` directory. * Your patch fixes Markdown formatting or syntax errors in the documentation contained in the `docs` directory. If you have any questions, please refer to the FAQ in the [docs](to be written) ### How can I become a maintainer? * Step 1: learn the component inside out * Step 2: make yourself useful by contributing code, bugfixes, support etc. * Step 3: volunteer on the irc channel (#libcontainer@freenode) Don't forget: being a maintainer is a time investment. Make sure you will have time to make yourself available. You don't have to be a maintainer to make a difference on the project! ================================================ FILE: vendor/github.com/docker/libcontainer/Dockerfile ================================================ FROM golang:1.4 RUN echo "deb http://ftp.us.debian.org/debian testing main contrib" >> /etc/apt/sources.list RUN apt-get update && apt-get install -y iptables criu=1.5.2-1 && rm -rf /var/lib/apt/lists/* RUN go get golang.org/x/tools/cmd/cover ENV GOPATH $GOPATH:/go/src/github.com/docker/libcontainer/vendor RUN go get github.com/docker/docker/pkg/term # setup a playground for us to spawn containers in RUN mkdir /busybox && \ curl -sSL 'https://github.com/jpetazzo/docker-busybox/raw/buildroot-2014.11/rootfs.tar' | tar -xC /busybox RUN curl -sSL https://raw.githubusercontent.com/docker/docker/master/hack/dind -o /dind && \ chmod +x /dind COPY . /go/src/github.com/docker/libcontainer WORKDIR /go/src/github.com/docker/libcontainer RUN cp sample_configs/minimal.json /busybox/container.json RUN make direct-install ENTRYPOINT ["/dind"] CMD ["make", "direct-test"] ================================================ FILE: vendor/github.com/docker/libcontainer/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/docker/libcontainer/MAINTAINERS ================================================ Michael Crosby (@crosbymichael) Rohit Jnagal (@rjnagal) Victor Marmol (@vmarmol) Mrunal Patel (@mrunalp) Alexandr Morozov (@LK4D4) Daniel, Dao Quang Minh (@dqminh) update-vendor.sh: Tianon Gravi (@tianon) ================================================ FILE: vendor/github.com/docker/libcontainer/MAINTAINERS_GUIDE.md ================================================ # The libcontainer Maintainers' Guide ## Introduction Dear maintainer. Thank you for investing the time and energy to help make libcontainer as useful as possible. Maintaining a project is difficult, sometimes unrewarding work. Sure, you will get to contribute cool features to the project. But most of your time will be spent reviewing, cleaning up, documenting, answering questions, justifying design decisions - while everyone has all the fun! But remember - the quality of the maintainers work is what distinguishes the good projects from the great. So please be proud of your work, even the unglamourous parts, and encourage a culture of appreciation and respect for *every* aspect of improving the project - not just the hot new features. This document is a manual for maintainers old and new. It explains what is expected of maintainers, how they should work, and what tools are available to them. This is a living document - if you see something out of date or missing, speak up! ## What are a maintainer's responsibility? It is every maintainer's responsibility to: * 1) Expose a clear roadmap for improving their component. * 2) Deliver prompt feedback and decisions on pull requests. * 3) Be available to anyone with questions, bug reports, criticism etc. on their component. This includes IRC, GitHub requests and the mailing list. * 4) Make sure their component respects the philosophy, design and roadmap of the project. ## How are decisions made? Short answer: with pull requests to the libcontainer repository. libcontainer is an open-source project with an open design philosophy. This means that the repository is the source of truth for EVERY aspect of the project, including its philosophy, design, roadmap and APIs. *If it's part of the project, it's in the repo. It's in the repo, it's part of the project.* As a result, all decisions can be expressed as changes to the repository. An implementation change is a change to the source code. An API change is a change to the API specification. A philosophy change is a change to the philosophy manifesto. And so on. All decisions affecting libcontainer, big and small, follow the same 3 steps: * Step 1: Open a pull request. Anyone can do this. * Step 2: Discuss the pull request. Anyone can do this. * Step 3: Accept (`LGTM`) or refuse a pull request. The relevant maintainers do this (see below "Who decides what?") ## Who decides what? All decisions are pull requests, and the relevant maintainers make decisions by accepting or refusing the pull request. Review and acceptance by anyone is denoted by adding a comment in the pull request: `LGTM`. However, only currently listed `MAINTAINERS` are counted towards the required two LGTMs. libcontainer follows the timeless, highly efficient and totally unfair system known as [Benevolent dictator for life](http://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), with Michael Crosby in the role of BDFL. This means that all decisions are made by default by Michael. Since making every decision himself would be highly un-scalable, in practice decisions are spread across multiple maintainers. The relevant maintainers for a pull request can be worked out in two steps: * Step 1: Determine the subdirectories affected by the pull request. This might be `netlink/` and `security/`, or any other part of the repo. * Step 2: Find the `MAINTAINERS` file which affects this directory. If the directory itself does not have a `MAINTAINERS` file, work your way up the repo hierarchy until you find one. ### I'm a maintainer, and I'm going on holiday Please let your co-maintainers and other contributors know by raising a pull request that comments out your `MAINTAINERS` file entry using a `#`. ### I'm a maintainer, should I make pull requests too? Yes. Nobody should ever push to master directly. All changes should be made through a pull request. ### Who assigns maintainers? Michael has final `LGTM` approval for all pull requests to `MAINTAINERS` files. ### How is this process changed? Just like everything else: by making a pull request :) ================================================ FILE: vendor/github.com/docker/libcontainer/Makefile ================================================ all: docker build -t dockercore/libcontainer . test: # we need NET_ADMIN for the netlink tests and SYS_ADMIN for mounting docker run --rm -it --privileged dockercore/libcontainer sh: docker run --rm -it --privileged -w /busybox dockercore/libcontainer nsinit exec sh GO_PACKAGES = $(shell find . -not \( -wholename ./vendor -prune -o -wholename ./.git -prune \) -name '*.go' -print0 | xargs -0n1 dirname | sort -u) direct-test: go test $(TEST_TAGS) -cover -v $(GO_PACKAGES) direct-test-short: go test $(TEST_TAGS) -cover -test.short -v $(GO_PACKAGES) direct-build: go build -v $(GO_PACKAGES) direct-install: go install -v $(GO_PACKAGES) local: go test -v validate: hack/validate.sh binary: all docker run --rm --privileged -v $(CURDIR)/bundles:/go/bin dockercore/libcontainer make direct-install ================================================ FILE: vendor/github.com/docker/libcontainer/NOTICE ================================================ libcontainer 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. ================================================ FILE: vendor/github.com/docker/libcontainer/PRINCIPLES.md ================================================ # libcontainer Principles In the design and development of libcontainer we try to follow these principles: (Work in progress) * Don't try to replace every tool. Instead, be an ingredient to improve them. * Less code is better. * Fewer components are better. Do you really need to add one more class? * 50 lines of straightforward, readable code is better than 10 lines of magic that nobody can understand. * Don't do later what you can do now. "//TODO: refactor" is not acceptable in new code. * When hesitating between two options, choose the one that is easier to reverse. * "No" is temporary; "Yes" is forever. If you're not sure about a new feature, say no. You can change your mind later. * Containers must be portable to the greatest possible number of machines. Be suspicious of any change which makes machines less interchangeable. * The fewer moving parts in a container, the better. * Don't merge it unless you document it. * Don't document it unless you can keep it up-to-date. * Don't merge it unless you test it! * Everyone's problem is slightly different. Focus on the part that is the same for everyone, and solve that. ================================================ FILE: vendor/github.com/docker/libcontainer/README.md ================================================ ## libcontainer - reference implementation for containers [![Build Status](https://jenkins.dockerproject.org/buildStatus/icon?job=Libcontainer%20Master)](https://jenkins.dockerproject.org/job/Libcontainer%20Master/) 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 To create a container you first have to initialize an instance of a factory that will handle the creation and initialization for a container. Because containers are spawned in a two step process you will need to provide arguments to a binary that will be executed as the init process for the container. To use the current binary that is spawning the containers and acting as the parent you can use `os.Args[0]` and we have a command called `init` setup. ```go root, err := libcontainer.New("/var/lib/container", libcontainer.InitArgs(os.Args[0], "init")) if err != nil { log.Fatal(err) } ``` 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 config := &configs.Config{ Rootfs: rootfs, Capabilities: []string{ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE", }, Namespaces: configs.Namespaces([]configs.Namespace{ {Type: configs.NEWNS}, {Type: configs.NEWUTS}, {Type: configs.NEWIPC}, {Type: configs.NEWPID}, {Type: configs.NEWNET}, }), Cgroups: &configs.Cgroup{ Name: "test-container", Parent: "system", AllowAllDevices: false, AllowedDevices: configs.DefaultAllowedDevices, }, Devices: configs.DefaultAutoCreatedDevices, Hostname: "testing", Networks: []*configs.Network{ { Type: "loopback", Address: "127.0.0.1/0", Gateway: "localhost", }, }, Rlimits: []configs.Rlimit{ { Type: syscall.RLIMIT_NOFILE, Hard: uint64(1024), Soft: uint64(1024), }, }, } ``` Once you have the configuration populated you can create a container: ```go container, err := root.Create("container-id", config) ``` 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.Start(process) if err != nil { log.Fatal(err) } // wait for the process to finish. status, err := process.Wait() if err != nil { log.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() ``` #### nsinit `nsinit` is a cli application which demonstrates the use of libcontainer. It is able to spawn new containers or join existing containers. A root filesystem must be provided for use along with a container configuration file. To build `nsinit`, run `make binary`. It will save the binary into `bundles/nsinit`. To use `nsinit`, cd into a Linux rootfs and copy a `container.json` file into the directory with your specified configuration. Environment, networking, and different capabilities for the container are specified in this file. The configuration is used for each process executed inside the container. See the `sample_configs` folder for examples of what the container configuration should look like. To execute `/bin/bash` in the current directory as a container just run the following **as root**: ```bash nsinit exec --tty /bin/bash ``` If you wish to spawn another process inside the container while your current bash session is running, run the same command again to get another bash shell (or change the command). If the original process (PID 1) dies, all other processes spawned inside the container will be killed and the namespace will be removed. You can identify if a process is running in a container by looking to see if `state.json` is in the root of the directory. You may also specify an alternate root place where the `container.json` file is read and where the `state.json` file will be saved. #### 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. To try an example with `nsinit`, open two terminals to the same busybox directory. In the first terminal, run a command like this one: ```bash nsinit exec -- sh -c 'i=0; while true; do echo $i; i=$(expr $i + 1); sleep 1; done' ``` You should see logs printing to the terminal every second. Now, in the second terminal, run: ```bash nsinit checkpoint --image-path=/tmp/criu ``` The logs in your first terminal will stop and the process will exit. Finally, in the second terminal, run the restore command: ```bash nsinit restore --image-path=/tmp/criu ``` The process will resume counting where it left off and printing to the new terminal window. #### Future See the [roadmap](ROADMAP.md). ## Copyright and license Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license. Docs released under Creative commons. ## Hacking on libcontainer First of all, please familiarise yourself with the [libcontainer Principles](PRINCIPLES.md). If you're a *contributor* or aspiring contributor, you should read the [Contributors' Guide](CONTRIBUTING.md). If you're a *maintainer* or aspiring maintainer, you should read the [Maintainers' Guide](MAINTAINERS_GUIDE.md) and "How can I become a maintainer?" in the Contributors' Guide. ================================================ FILE: vendor/github.com/docker/libcontainer/ROADMAP.md ================================================ # libcontainer: what's next? This document is a high-level overview of where we want to take libcontainer next. It is a curated selection of planned improvements which are either important, difficult, or both. For a more complete view of planned and requested improvements, see [the Github issues](https://github.com/docker/libcontainer/issues). To suggest changes to the roadmap, including additions, please write the change as if it were already in effect, and make a pull request. ## Broader kernel support Our goal is to make libcontainer run everywhere, but currently libcontainer requires Linux version 3.8 or higher. If you’re deploying new machines for the purpose of running libcontainer, this is a fairly easy requirement to meet. However, if you’re adding libcontainer to an existing deployment, you may not have the flexibility to update and patch the kernel. ## Cross-architecture support Our goal is to make libcontainer run everywhere. Recently libcontainer has expanded from its initial support for x86_64 systems to include POWER (ppc64 little and big endian variants), IBM System z (s390x 64-bit), and ARM. We plan to continue expanding architecture support such that libcontainer containers can be created and used on more architectures. ================================================ FILE: vendor/github.com/docker/libcontainer/SPEC.md ================================================ ## Container Specification - v1 This is the standard configuration for version 1 containers. It includes namespaces, standard filesystem setup, a default Linux capability set, and information about resource reservations. It also has information about any populated environment settings for the processes running inside a container. Along with the configuration of how a container is created the standard also discusses actions that can be performed on a container to manage and inspect information about the processes running inside. The v1 profile is meant to be able to accommodate the majority of applications with a strong security configuration. ### System Requirements and Compatibility Minimum requirements: * Kernel version - 3.10 recommended 2.6.2x minimum(with backported patches) * Mounted cgroups with each subsystem in its own hierarchy ### Namespaces | Flag | Enabled | | ------------ | ------- | | CLONE_NEWPID | 1 | | CLONE_NEWUTS | 1 | | CLONE_NEWIPC | 1 | | CLONE_NEWNET | 1 | | CLONE_NEWNS | 1 | | CLONE_NEWUSER | 1 | Namespaces are created for the container via the `clone` syscall. ### Filesystem A root filesystem must be provided to a container for execution. The container will use this root filesystem (rootfs) to jail and spawn processes inside where the binaries and system libraries are local to that directory. Any binaries to be executed must be contained within this rootfs. Mounts that happen inside the container are automatically cleaned up when the container exits as the mount namespace is destroyed and the kernel will unmount all the mounts that were setup within that namespace. For a container to execute properly there are certain filesystems that are required to be mounted within the rootfs that the runtime will setup. | Path | Type | Flags | Data | | ----------- | ------ | -------------------------------------- | ---------------------------------------- | | /proc | proc | MS_NOEXEC,MS_NOSUID,MS_NODEV | | | /dev | tmpfs | MS_NOEXEC,MS_STRICTATIME | mode=755 | | /dev/shm | tmpfs | MS_NOEXEC,MS_NOSUID,MS_NODEV | mode=1777,size=65536k | | /dev/mqueue | mqueue | MS_NOEXEC,MS_NOSUID,MS_NODEV | | | /dev/pts | devpts | MS_NOEXEC,MS_NOSUID | newinstance,ptmxmode=0666,mode=620,gid=5 | | /sys | sysfs | MS_NOEXEC,MS_NOSUID,MS_NODEV,MS_RDONLY | | After a container's filesystems are mounted within the newly created mount namespace `/dev` will need to be populated with a set of device nodes. It is expected that a rootfs does not need to have any device nodes specified for `/dev` witin the rootfs as the container will setup the correct devices that are required for executing a container's process. | Path | Mode | Access | | ------------ | ---- | ---------- | | /dev/null | 0666 | rwm | | /dev/zero | 0666 | rwm | | /dev/full | 0666 | rwm | | /dev/tty | 0666 | rwm | | /dev/random | 0666 | rwm | | /dev/urandom | 0666 | rwm | | /dev/fuse | 0666 | rwm | **ptmx** `/dev/ptmx` will need to be a symlink to the host's `/dev/ptmx` within the container. The use of a pseudo TTY is optional within a container and it should support both. If a pseudo is provided to the container `/dev/console` will need to be setup by binding the console in `/dev/` after it has been populated and mounted in tmpfs. | Source | Destination | UID GID | Mode | Type | | --------------- | ------------ | ------- | ---- | ---- | | *pty host path* | /dev/console | 0 0 | 0600 | bind | After `/dev/null` has been setup we check for any external links between the container's io, STDIN, STDOUT, STDERR. If the container's io is pointing to `/dev/null` outside the container we close and `dup2` the the `/dev/null` that is local to the container's rootfs. After the container has `/proc` mounted a few standard symlinks are setup within `/dev/` for the io. | Source | Destination | | ------------ | ----------- | | /proc/1/fd | /dev/fd | | /proc/1/fd/0 | /dev/stdin | | /proc/1/fd/1 | /dev/stdout | | /proc/1/fd/2 | /dev/stderr | A `pivot_root` is used to change the root for the process, effectively jailing the process inside the rootfs. ```c put_old = mkdir(...); pivot_root(rootfs, put_old); chdir("/"); unmount(put_old, MS_DETACH); rmdir(put_old); ``` For container's running with a rootfs inside `ramfs` a `MS_MOVE` combined with a `chroot` is required as `pivot_root` is not supported in `ramfs`. ```c mount(rootfs, "/", NULL, MS_MOVE, NULL); chroot("."); chdir("/"); ``` The `umask` is set back to `0022` after the filesystem setup has been completed. ### Resources Cgroups are used to handle resource allocation for containers. This includes system resources like cpu, memory, and device access. | Subsystem | Enabled | | ---------- | ------- | | devices | 1 | | memory | 1 | | cpu | 1 | | cpuacct | 1 | | cpuset | 1 | | blkio | 1 | | perf_event | 1 | | freezer | 1 | | hugetlb | 1 | All cgroup subsystem are joined so that statistics can be collected from each of the subsystems. Freezer does not expose any stats but is joined so that containers can be paused and resumed. The parent process of the container's init must place the init pid inside the correct cgroups before the initialization begins. This is done so that no processes or threads escape the cgroups. This sync is done via a pipe ( specified in the runtime section below ) that the container's init process will block waiting for the parent to finish setup. ### Security The standard set of Linux capabilities that are set in a container provide a good default for security and flexibility for the applications. | Capability | Enabled | | -------------------- | ------- | | CAP_NET_RAW | 1 | | CAP_NET_BIND_SERVICE | 1 | | CAP_AUDIT_READ | 1 | | CAP_AUDIT_WRITE | 1 | | CAP_DAC_OVERRIDE | 1 | | CAP_SETFCAP | 1 | | CAP_SETPCAP | 1 | | CAP_SETGID | 1 | | CAP_SETUID | 1 | | CAP_MKNOD | 1 | | CAP_CHOWN | 1 | | CAP_FOWNER | 1 | | CAP_FSETID | 1 | | CAP_KILL | 1 | | CAP_SYS_CHROOT | 1 | | CAP_NET_BROADCAST | 0 | | CAP_SYS_MODULE | 0 | | CAP_SYS_RAWIO | 0 | | CAP_SYS_PACCT | 0 | | CAP_SYS_ADMIN | 0 | | CAP_SYS_NICE | 0 | | CAP_SYS_RESOURCE | 0 | | CAP_SYS_TIME | 0 | | CAP_SYS_TTY_CONFIG | 0 | | CAP_AUDIT_CONTROL | 0 | | CAP_MAC_OVERRIDE | 0 | | CAP_MAC_ADMIN | 0 | | CAP_NET_ADMIN | 0 | | CAP_SYSLOG | 0 | | CAP_DAC_READ_SEARCH | 0 | | CAP_LINUX_IMMUTABLE | 0 | | CAP_IPC_LOCK | 0 | | CAP_IPC_OWNER | 0 | | CAP_SYS_PTRACE | 0 | | CAP_SYS_BOOT | 0 | | CAP_LEASE | 0 | | CAP_WAKE_ALARM | 0 | | CAP_BLOCK_SUSPE | 0 | Additional security layers like [apparmor](https://wiki.ubuntu.com/AppArmor) and [selinux](http://selinuxproject.org/page/Main_Page) can be used with the containers. A container should support setting an apparmor profile or selinux process and mount labels if provided in the configuration. Standard apparmor profile: ```c #include profile flags=(attach_disconnected,mediate_deleted) { #include network, capability, file, umount, deny @{PROC}/sys/fs/** wklx, deny @{PROC}/sysrq-trigger rwklx, deny @{PROC}/mem rwklx, deny @{PROC}/kmem rwklx, deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx, deny @{PROC}/sys/kernel/*/** wklx, deny mount, deny /sys/[^f]*/** wklx, deny /sys/f[^s]*/** wklx, deny /sys/fs/[^c]*/** wklx, deny /sys/fs/c[^g]*/** wklx, deny /sys/fs/cg[^r]*/** wklx, deny /sys/firmware/efi/efivars/** rwklx, deny /sys/kernel/security/** rwklx, } ``` *TODO: seccomp work is being done to find a good default config* ### Runtime and Init Process During container creation the parent process needs to talk to the container's init process and have a form of synchronization. This is accomplished by creating a pipe that is passed to the container's init. When the init process first spawns it will block on its side of the pipe until the parent closes its side. This allows the parent to have time to set the new process inside a cgroup hierarchy and/or write any uid/gid mappings required for user namespaces. The pipe is passed to the init process via FD 3. The application consuming libcontainer should be compiled statically. libcontainer does not define any init process and the arguments provided are used to `exec` the process inside the application. There should be no long running init within the container spec. If a pseudo tty is provided to a container it will open and `dup2` the console as the container's STDIN, STDOUT, STDERR as well as mounting the console as `/dev/console`. An extra set of mounts are provided to a container and setup for use. A container's rootfs can contain some non portable files inside that can cause side effects during execution of a process. These files are usually created and populated with the container specific information via the runtime. **Extra runtime files:** * /etc/hosts * /etc/resolv.conf * /etc/hostname * /etc/localtime #### Defaults There are a few defaults that can be overridden by users, but in their omission these apply to processes within a container. | Type | Value | | ------------------- | ------------------------------ | | Parent Death Signal | SIGKILL | | UID | 0 | | GID | 0 | | GROUPS | 0, NULL | | CWD | "/" | | $HOME | Current user's home dir or "/" | | Readonly rootfs | false | | Pseudo TTY | false | ## Actions After a container is created there is a standard set of actions that can be done to the container. These actions are part of the public API for a container. | Action | Description | | -------------- | ------------------------------------------------------------------ | | Get processes | Return all the pids for processes running inside a container | | Get Stats | Return resource statistics for the container as a whole | | Wait | Wait waits on the container's init process ( pid 1 ) | | Wait Process | Wait on any of the container's processes returning the exit status | | Destroy | Kill the container's init process and remove any filesystem state | | Signal | Send a signal to the container's init process | | Signal Process | Send a signal to any of the container's processes | | Pause | Pause all processes inside the container | | Resume | Resume all processes inside the container if paused | | Exec | Execute a new process inside of the container ( requires setns ) | | Set | Setup configs of the container after it's created | ### Execute a new process inside of a running container. User can execute a new process inside of a running container. Any binaries to be executed must be accessible within the container's rootfs. The started process will run inside the container's rootfs. Any changes made by the process to the container's filesystem will persist after the process finished executing. The started process will join all the container's existing namespaces. When the container is paused, the process will also be paused and will resume when the container is unpaused. The started process will only run when the container's primary process (PID 1) is running, and will not be restarted when the container is restarted. #### Planned additions The started process will have its own cgroups nested inside the container's cgroups. This is used for process tracking and optionally resource allocation handling for the new process. Freezer cgroup is required, the rest of the cgroups are optional. The process executor must place its pid inside the correct cgroups before starting the process. This is done so that no child processes or threads can escape the cgroups. When the process is stopped, the process executor will try (in a best-effort way) to stop all its children and remove the sub-cgroups. ================================================ FILE: vendor/github.com/docker/libcontainer/apparmor/apparmor.go ================================================ // +build apparmor,linux package apparmor // #cgo LDFLAGS: -lapparmor // #include // #include import "C" import ( "io/ioutil" "os" "unsafe" ) 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 } 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 err } return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/apparmor/apparmor_disabled.go ================================================ // +build !apparmor !linux package apparmor func IsEnabled() bool { return false } func ApplyProfile(name string) error { return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/apparmor/gen.go ================================================ // +build linux package apparmor import ( "io" "os" "text/template" ) type data struct { Name string Imports []string InnerImports []string } const baseTemplate = ` {{range $value := .Imports}} {{$value}} {{end}} profile {{.Name}} flags=(attach_disconnected,mediate_deleted) { {{range $value := .InnerImports}} {{$value}} {{end}} network, capability, file, umount, deny @{PROC}/sys/fs/** wklx, deny @{PROC}/sysrq-trigger rwklx, deny @{PROC}/mem rwklx, deny @{PROC}/kmem rwklx, deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx, deny @{PROC}/sys/kernel/*/** wklx, deny mount, deny /sys/[^f]*/** wklx, deny /sys/f[^s]*/** wklx, deny /sys/fs/[^c]*/** wklx, deny /sys/fs/c[^g]*/** wklx, deny /sys/fs/cg[^r]*/** wklx, deny /sys/firmware/efi/efivars/** rwklx, deny /sys/kernel/security/** rwklx, } ` func generateProfile(out io.Writer) error { compiled, err := template.New("apparmor_profile").Parse(baseTemplate) if err != nil { return err } data := &data{ Name: "docker-default", } if tunablesExists() { data.Imports = append(data.Imports, "#include ") } else { data.Imports = append(data.Imports, "@{PROC}=/proc/") } if abstractionsExists() { data.InnerImports = append(data.InnerImports, "#include ") } if err := compiled.Execute(out, data); err != nil { return err } return nil } // check if the tunables/global exist func tunablesExists() bool { _, err := os.Stat("/etc/apparmor.d/tunables/global") return err == nil } // check if abstractions/base exist func abstractionsExists() bool { _, err := os.Stat("/etc/apparmor.d/abstractions/base") return err == nil } ================================================ FILE: vendor/github.com/docker/libcontainer/apparmor/setup.go ================================================ // +build linux package apparmor import ( "fmt" "os" "os/exec" "path" ) const ( DefaultProfilePath = "/etc/apparmor.d/docker" ) func InstallDefaultProfile() error { if !IsEnabled() { return nil } // Make sure /etc/apparmor.d exists if err := os.MkdirAll(path.Dir(DefaultProfilePath), 0755); err != nil { return err } f, err := os.OpenFile(DefaultProfilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { return err } if err := generateProfile(f); err != nil { f.Close() return err } f.Close() cmd := exec.Command("/sbin/apparmor_parser", "-r", "-W", "docker") // to use the parser directly we have to make sure we are in the correct // dir with the profile cmd.Dir = "/etc/apparmor.d" output, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("Error loading docker apparmor profile: %s (%s)", err, output) } return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/capabilities_linux.go ================================================ // +build linux package libcontainer import ( "fmt" "os" "github.com/syndtr/gocapability/capability" ) const allCapabilityTypes = capability.CAPS | capability.BOUNDS var capabilityList = map[string]capability.Cap{ "SETPCAP": capability.CAP_SETPCAP, "SYS_MODULE": capability.CAP_SYS_MODULE, "SYS_RAWIO": capability.CAP_SYS_RAWIO, "SYS_PACCT": capability.CAP_SYS_PACCT, "SYS_ADMIN": capability.CAP_SYS_ADMIN, "SYS_NICE": capability.CAP_SYS_NICE, "SYS_RESOURCE": capability.CAP_SYS_RESOURCE, "SYS_TIME": capability.CAP_SYS_TIME, "SYS_TTY_CONFIG": capability.CAP_SYS_TTY_CONFIG, "MKNOD": capability.CAP_MKNOD, "AUDIT_WRITE": capability.CAP_AUDIT_WRITE, "AUDIT_CONTROL": capability.CAP_AUDIT_CONTROL, "MAC_OVERRIDE": capability.CAP_MAC_OVERRIDE, "MAC_ADMIN": capability.CAP_MAC_ADMIN, "NET_ADMIN": capability.CAP_NET_ADMIN, "SYSLOG": capability.CAP_SYSLOG, "CHOWN": capability.CAP_CHOWN, "NET_RAW": capability.CAP_NET_RAW, "DAC_OVERRIDE": capability.CAP_DAC_OVERRIDE, "FOWNER": capability.CAP_FOWNER, "DAC_READ_SEARCH": capability.CAP_DAC_READ_SEARCH, "FSETID": capability.CAP_FSETID, "KILL": capability.CAP_KILL, "SETGID": capability.CAP_SETGID, "SETUID": capability.CAP_SETUID, "LINUX_IMMUTABLE": capability.CAP_LINUX_IMMUTABLE, "NET_BIND_SERVICE": capability.CAP_NET_BIND_SERVICE, "NET_BROADCAST": capability.CAP_NET_BROADCAST, "IPC_LOCK": capability.CAP_IPC_LOCK, "IPC_OWNER": capability.CAP_IPC_OWNER, "SYS_CHROOT": capability.CAP_SYS_CHROOT, "SYS_PTRACE": capability.CAP_SYS_PTRACE, "SYS_BOOT": capability.CAP_SYS_BOOT, "LEASE": capability.CAP_LEASE, "SETFCAP": capability.CAP_SETFCAP, "WAKE_ALARM": capability.CAP_WAKE_ALARM, "BLOCK_SUSPEND": capability.CAP_BLOCK_SUSPEND, "AUDIT_READ": capability.CAP_AUDIT_READ, } func newCapWhitelist(caps []string) (*whitelist, error) { l := []capability.Cap{} for _, c := range caps { v, ok := capabilityList[c] if !ok { return nil, fmt.Errorf("unknown capability %q", c) } l = append(l, v) } pid, err := capability.NewPid(os.Getpid()) if err != nil { return nil, err } return &whitelist{ keep: l, pid: pid, }, nil } type whitelist struct { pid capability.Capabilities keep []capability.Cap } // dropBoundingSet drops the capability bounding set to those specified in the whitelist. func (w *whitelist) dropBoundingSet() error { w.pid.Clear(capability.BOUNDS) w.pid.Set(capability.BOUNDS, w.keep...) return w.pid.Apply(capability.BOUNDS) } // drop drops all capabilities for the current process except those specified in the whitelist. func (w *whitelist) drop() error { w.pid.Clear(allCapabilityTypes) w.pid.Set(allCapabilityTypes, w.keep...) return w.pid.Apply(allCapabilityTypes) } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/cgroups.go ================================================ // +build linux package cgroups import ( "fmt" "github.com/docker/libcontainer/configs" ) type Manager interface { // Apply cgroup configuration to the process with the specified pid Apply(pid int) error // Returns the PIDs inside the cgroup set GetPids() ([]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 // NewCgroupManager() and LoadCgroupManager() require following attributes: // Paths map[string]string // Cgroups *cgroups.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 // Set 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/cgroups_test.go ================================================ // +build linux package cgroups import ( "bytes" "testing" ) const ( cgroupsContents = `11:hugetlb:/ 10:perf_event:/ 9:blkio:/ 8:net_cls:/ 7:freezer:/ 6:devices:/ 5:memory:/ 4:cpuacct,cpu:/ 3:cpuset:/ 2:name=systemd:/user.slice/user-1000.slice/session-16.scope` ) func TestParseCgroups(t *testing.T) { r := bytes.NewBuffer([]byte(cgroupsContents)) _, err := ParseCgroupFile("blkio", r) if err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/cgroups_unsupported.go ================================================ // +build !linux package cgroups ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/apply_raw.go ================================================ // +build linux package fs import ( "fmt" "io" "io/ioutil" "os" "path/filepath" "strconv" "sync" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) var ( subsystems = map[string]subsystem{ "devices": &DevicesGroup{}, "memory": &MemoryGroup{}, "cpu": &CpuGroup{}, "cpuset": &CpusetGroup{}, "cpuacct": &CpuacctGroup{}, "blkio": &BlkioGroup{}, "hugetlb": &HugetlbGroup{}, "net_cls": &NetClsGroup{}, "net_prio": &NetPrioGroup{}, "perf_event": &PerfEventGroup{}, "freezer": &FreezerGroup{}, } CgroupProcesses = "cgroup.procs" HugePageSizes, _ = cgroups.GetHugePageSize() ) type subsystem interface { // Returns the stats, as 'stats', corresponding to the cgroup under 'path'. GetStats(path string, stats *cgroups.Stats) error // Removes the cgroup represented by 'data'. Remove(*data) error // Creates and joins the cgroup represented by data. Apply(*data) 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 data struct { root string cgroup string c *configs.Cgroup pid int } func (m *Manager) Apply(pid int) error { if m.Cgroups == nil { return nil } var c = m.Cgroups d, err := getCgroupData(m.Cgroups, pid) if err != nil { return err } paths := make(map[string]string) defer func() { if err != nil { cgroups.RemovePaths(paths) } }() for name, sys := range subsystems { if err := sys.Apply(d); err != nil { return err } // 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(name) if err != nil { if cgroups.IsNotFound(err) { continue } return err } paths[name] = p } m.Paths = paths if paths["cpu"] != "" { if err := CheckCpushares(paths["cpu"], c.CpuShares); err != nil { return err } } return nil } func (m *Manager) Destroy() error { 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, ok := subsystems[name] if !ok || !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 { for name, path := range m.Paths { sys, ok := subsystems[name] if !ok || !cgroups.PathExists(path) { continue } if err := sys.Set(path, container.Cgroups); 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 { d, err := getCgroupData(m.Cgroups, 0) if err != nil { return err } dir, err := d.path("freezer") if err != nil { return err } prevState := m.Cgroups.Freezer m.Cgroups.Freezer = state freezer := subsystems["freezer"] err = freezer.Set(dir, m.Cgroups) if err != nil { m.Cgroups.Freezer = prevState return err } return nil } func (m *Manager) GetPids() ([]int, error) { d, err := getCgroupData(m.Cgroups, 0) if err != nil { return nil, err } dir, err := d.path("devices") if err != nil { return nil, err } return cgroups.ReadProcsFile(dir) } func getCgroupData(c *configs.Cgroup, pid int) (*data, error) { root, err := getCgroupRoot() if err != nil { return nil, err } cgroup := c.Name if c.Parent != "" { cgroup = filepath.Join(c.Parent, cgroup) } return &data{ root: root, cgroup: cgroup, c: c, pid: pid, }, nil } func (raw *data) parent(subsystem, mountpoint string) (string, error) { initPath, err := cgroups.GetInitCgroupDir(subsystem) if err != nil { return "", err } return filepath.Join(mountpoint, initPath), nil } func (raw *data) 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.cgroup) { return filepath.Join(raw.root, subsystem, raw.cgroup), nil } parent, err := raw.parent(subsystem, mnt) if err != nil { return "", err } return filepath.Join(parent, raw.cgroup), nil } func (raw *data) join(subsystem string) (string, error) { path, err := raw.path(subsystem) if err != nil { return "", err } if err := os.MkdirAll(path, 0755); err != nil && !os.IsExist(err) { return "", err } if err := writeFile(path, CgroupProcesses, strconv.Itoa(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) } return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) } 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 int64) error { var cpuShares int64 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 != 0 { 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/blkio.go ================================================ // +build linux package fs import ( "bufio" "fmt" "os" "path/filepath" "strconv" "strings" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type BlkioGroup struct { } func (s *BlkioGroup) Apply(d *data) error { dir, err := d.join("blkio") if err != nil && !cgroups.IsNotFound(err) { return err } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *BlkioGroup) Set(path string, cgroup *configs.Cgroup) error { if cgroup.BlkioWeight != 0 { if err := writeFile(path, "blkio.weight", strconv.FormatInt(cgroup.BlkioWeight, 10)); err != nil { return err } } if cgroup.BlkioWeightDevice != "" { if err := writeFile(path, "blkio.weight_device", cgroup.BlkioWeightDevice); err != nil { return err } } if cgroup.BlkioThrottleReadBpsDevice != "" { if err := writeFile(path, "blkio.throttle.read_bps_device", cgroup.BlkioThrottleReadBpsDevice); err != nil { return err } } if cgroup.BlkioThrottleWriteBpsDevice != "" { if err := writeFile(path, "blkio.throttle.write_bps_device", cgroup.BlkioThrottleWriteBpsDevice); err != nil { return err } } if cgroup.BlkioThrottleReadIOpsDevice != "" { if err := writeFile(path, "blkio.throttle.read_iops_device", cgroup.BlkioThrottleReadIOpsDevice); err != nil { return err } } if cgroup.BlkioThrottleWriteIOpsDevice != "" { if err := writeFile(path, "blkio.throttle.write_iops_device", cgroup.BlkioThrottleWriteIOpsDevice); err != nil { return err } } return nil } func (s *BlkioGroup) Remove(d *data) 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/blkio_test.go ================================================ // +build linux package fs import ( "strconv" "testing" "github.com/docker/libcontainer/cgroups" ) const ( sectorsRecursiveContents = `8:0 1024` serviceBytesRecursiveContents = `8:0 Read 100 8:0 Write 200 8:0 Sync 300 8:0 Async 500 8:0 Total 500 Total 500` servicedRecursiveContents = `8:0 Read 10 8:0 Write 40 8:0 Sync 20 8:0 Async 30 8:0 Total 50 Total 50` queuedRecursiveContents = `8:0 Read 1 8:0 Write 4 8:0 Sync 2 8:0 Async 3 8:0 Total 5 Total 5` serviceTimeRecursiveContents = `8:0 Read 173959 8:0 Write 0 8:0 Sync 0 8:0 Async 173959 8:0 Total 17395 Total 17395` waitTimeRecursiveContents = `8:0 Read 15571 8:0 Write 0 8:0 Sync 0 8:0 Async 15571 8:0 Total 15571` mergedRecursiveContents = `8:0 Read 5 8:0 Write 10 8:0 Sync 0 8:0 Async 0 8:0 Total 15 Total 15` timeRecursiveContents = `8:0 8` throttleServiceBytes = `8:0 Read 11030528 8:0 Write 23 8:0 Sync 42 8:0 Async 11030528 8:0 Total 11030528 252:0 Read 11030528 252:0 Write 23 252:0 Sync 42 252:0 Async 11030528 252:0 Total 11030528 Total 22061056` throttleServiced = `8:0 Read 164 8:0 Write 23 8:0 Sync 42 8:0 Async 164 8:0 Total 164 252:0 Read 164 252:0 Write 23 252:0 Sync 42 252:0 Async 164 252:0 Total 164 Total 328` throttleBefore = `8:0 1024` throttleAfter = `8:0 2048` ) func appendBlkioStatEntry(blkioStatEntries *[]cgroups.BlkioStatEntry, major, minor, value uint64, op string) { *blkioStatEntries = append(*blkioStatEntries, cgroups.BlkioStatEntry{Major: major, Minor: minor, Value: value, Op: op}) } func TestBlkioSetWeight(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() const ( weightBefore = 100 weightAfter = 200 ) helper.writeFileContents(map[string]string{ "blkio.weight": strconv.Itoa(weightBefore), }) helper.CgroupData.c.BlkioWeight = weightAfter blkio := &BlkioGroup{} if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "blkio.weight") if err != nil { t.Fatalf("Failed to parse blkio.weight - %s", err) } if value != weightAfter { t.Fatal("Got the wrong value, set blkio.weight failed.") } } func TestBlkioSetWeightDevice(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() const ( weightDeviceBefore = "8:0 400" weightDeviceAfter = "8:0 500" ) helper.writeFileContents(map[string]string{ "blkio.weight_device": weightDeviceBefore, }) helper.CgroupData.c.BlkioWeightDevice = weightDeviceAfter blkio := &BlkioGroup{} if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "blkio.weight_device") if err != nil { t.Fatalf("Failed to parse blkio.weight_device - %s", err) } if value != weightDeviceAfter { t.Fatal("Got the wrong value, set blkio.weight_device failed.") } } func TestBlkioStats(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal(err) } // Verify expected stats. expectedStats := cgroups.BlkioStats{} appendBlkioStatEntry(&expectedStats.SectorsRecursive, 8, 0, 1024, "") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 100, "Read") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 200, "Write") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 300, "Sync") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 500, "Async") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 500, "Total") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 10, "Read") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 40, "Write") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 20, "Sync") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 30, "Async") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 50, "Total") appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 1, "Read") appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 4, "Write") appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 2, "Sync") appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 3, "Async") appendBlkioStatEntry(&expectedStats.IoQueuedRecursive, 8, 0, 5, "Total") appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 173959, "Read") appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 0, "Write") appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 0, "Sync") appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 173959, "Async") appendBlkioStatEntry(&expectedStats.IoServiceTimeRecursive, 8, 0, 17395, "Total") appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Read") appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 0, "Write") appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 0, "Sync") appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Async") appendBlkioStatEntry(&expectedStats.IoWaitTimeRecursive, 8, 0, 15571, "Total") appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 5, "Read") appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 10, "Write") appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 0, "Sync") appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 0, "Async") appendBlkioStatEntry(&expectedStats.IoMergedRecursive, 8, 0, 15, "Total") appendBlkioStatEntry(&expectedStats.IoTimeRecursive, 8, 0, 8, "") expectBlkioStatsEquals(t, expectedStats, actualStats.BlkioStats) } func TestBlkioStatsNoSectorsFile(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoServiceBytesFile(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoServicedFile(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoQueuedFile(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoServiceTimeFile(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoWaitTimeFile(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoMergedFile(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.time_recursive": timeRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsNoTimeFile(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": serviceBytesRecursiveContents, "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatalf("Failed unexpectedly: %s", err) } } func TestBlkioStatsUnexpectedNumberOfFields(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": "8:0 Read 100 100", "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected to fail, but did not") } } func TestBlkioStatsUnexpectedFieldType(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": "8:0 Read Write", "blkio.io_serviced_recursive": servicedRecursiveContents, "blkio.io_queued_recursive": queuedRecursiveContents, "blkio.sectors_recursive": sectorsRecursiveContents, "blkio.io_service_time_recursive": serviceTimeRecursiveContents, "blkio.io_wait_time_recursive": waitTimeRecursiveContents, "blkio.io_merged_recursive": mergedRecursiveContents, "blkio.time_recursive": timeRecursiveContents, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected to fail, but did not") } } func TestNonCFQBlkioStats(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.io_service_bytes_recursive": "", "blkio.io_serviced_recursive": "", "blkio.io_queued_recursive": "", "blkio.sectors_recursive": "", "blkio.io_service_time_recursive": "", "blkio.io_wait_time_recursive": "", "blkio.io_merged_recursive": "", "blkio.time_recursive": "", "blkio.throttle.io_service_bytes": throttleServiceBytes, "blkio.throttle.io_serviced": throttleServiced, }) blkio := &BlkioGroup{} actualStats := *cgroups.NewStats() err := blkio.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal(err) } // Verify expected stats. expectedStats := cgroups.BlkioStats{} appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Read") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 23, "Write") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 42, "Sync") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Async") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 8, 0, 11030528, "Total") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Read") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 23, "Write") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 42, "Sync") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Async") appendBlkioStatEntry(&expectedStats.IoServiceBytesRecursive, 252, 0, 11030528, "Total") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Read") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 23, "Write") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 42, "Sync") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Async") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 8, 0, 164, "Total") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Read") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 23, "Write") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 42, "Sync") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Async") appendBlkioStatEntry(&expectedStats.IoServicedRecursive, 252, 0, 164, "Total") expectBlkioStatsEquals(t, expectedStats, actualStats.BlkioStats) } func TestBlkioSetThrottleReadBpsDevice(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.throttle.read_bps_device": throttleBefore, }) helper.CgroupData.c.BlkioThrottleReadBpsDevice = throttleAfter blkio := &BlkioGroup{} if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.read_bps_device") if err != nil { t.Fatalf("Failed to parse blkio.throttle.read_bps_device - %s", err) } if value != throttleAfter { t.Fatal("Got the wrong value, set blkio.throttle.read_bps_device failed.") } } func TestBlkioSetThrottleWriteBpsDevice(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.throttle.write_bps_device": throttleBefore, }) helper.CgroupData.c.BlkioThrottleWriteBpsDevice = throttleAfter blkio := &BlkioGroup{} if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.write_bps_device") if err != nil { t.Fatalf("Failed to parse blkio.throttle.write_bps_device - %s", err) } if value != throttleAfter { t.Fatal("Got the wrong value, set blkio.throttle.write_bps_device failed.") } } func TestBlkioSetThrottleReadIOpsDevice(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.throttle.read_iops_device": throttleBefore, }) helper.CgroupData.c.BlkioThrottleReadIOpsDevice = throttleAfter blkio := &BlkioGroup{} if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.read_iops_device") if err != nil { t.Fatalf("Failed to parse blkio.throttle.read_iops_device - %s", err) } if value != throttleAfter { t.Fatal("Got the wrong value, set blkio.throttle.read_iops_device failed.") } } func TestBlkioSetThrottleWriteIOpsDevice(t *testing.T) { helper := NewCgroupTestUtil("blkio", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "blkio.throttle.write_iops_device": throttleBefore, }) helper.CgroupData.c.BlkioThrottleWriteIOpsDevice = throttleAfter blkio := &BlkioGroup{} if err := blkio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "blkio.throttle.write_iops_device") if err != nil { t.Fatalf("Failed to parse blkio.throttle.write_iops_device - %s", err) } if value != throttleAfter { t.Fatal("Got the wrong value, set blkio.throttle.write_iops_device failed.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/cpu.go ================================================ // +build linux package fs import ( "bufio" "os" "path/filepath" "strconv" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type CpuGroup struct { } func (s *CpuGroup) Apply(d *data) error { // We always want to join the cpu group, to allow fair cpu scheduling // on a container basis dir, err := d.join("cpu") if err != nil && !cgroups.IsNotFound(err) { return err } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *CpuGroup) Set(path string, cgroup *configs.Cgroup) error { if cgroup.CpuShares != 0 { if err := writeFile(path, "cpu.shares", strconv.FormatInt(cgroup.CpuShares, 10)); err != nil { return err } } if cgroup.CpuPeriod != 0 { if err := writeFile(path, "cpu.cfs_period_us", strconv.FormatInt(cgroup.CpuPeriod, 10)); err != nil { return err } } if cgroup.CpuQuota != 0 { if err := writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(cgroup.CpuQuota, 10)); err != nil { return err } } if cgroup.CpuRtPeriod != 0 { if err := writeFile(path, "cpu.rt_period_us", strconv.FormatInt(cgroup.CpuRtPeriod, 10)); err != nil { return err } } if cgroup.CpuRtRuntime != 0 { if err := writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(cgroup.CpuRtRuntime, 10)); err != nil { return err } } return nil } func (s *CpuGroup) Remove(d *data) 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/cpu_test.go ================================================ // +build linux package fs import ( "fmt" "strconv" "testing" "github.com/docker/libcontainer/cgroups" ) func TestCpuSetShares(t *testing.T) { helper := NewCgroupTestUtil("cpu", t) defer helper.cleanup() const ( sharesBefore = 1024 sharesAfter = 512 ) helper.writeFileContents(map[string]string{ "cpu.shares": strconv.Itoa(sharesBefore), }) helper.CgroupData.c.CpuShares = sharesAfter cpu := &CpuGroup{} if err := cpu.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "cpu.shares") if err != nil { t.Fatalf("Failed to parse cpu.shares - %s", err) } if value != sharesAfter { t.Fatal("Got the wrong value, set cpu.shares failed.") } } func TestCpuSetBandWidth(t *testing.T) { helper := NewCgroupTestUtil("cpu", t) defer helper.cleanup() const ( quotaBefore = 8000 quotaAfter = 5000 periodBefore = 10000 periodAfter = 7000 rtRuntimeBefore = 8000 rtRuntimeAfter = 5000 rtPeriodBefore = 10000 rtPeriodAfter = 7000 ) helper.writeFileContents(map[string]string{ "cpu.cfs_quota_us": strconv.Itoa(quotaBefore), "cpu.cfs_period_us": strconv.Itoa(periodBefore), "cpu.rt_runtime_us": strconv.Itoa(rtRuntimeBefore), "cpu.rt_period_us": strconv.Itoa(rtPeriodBefore), }) helper.CgroupData.c.CpuQuota = quotaAfter helper.CgroupData.c.CpuPeriod = periodAfter helper.CgroupData.c.CpuRtRuntime = rtRuntimeAfter helper.CgroupData.c.CpuRtPeriod = rtPeriodAfter cpu := &CpuGroup{} if err := cpu.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } quota, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_quota_us") if err != nil { t.Fatalf("Failed to parse cpu.cfs_quota_us - %s", err) } if quota != quotaAfter { t.Fatal("Got the wrong value, set cpu.cfs_quota_us failed.") } period, err := getCgroupParamUint(helper.CgroupPath, "cpu.cfs_period_us") if err != nil { t.Fatalf("Failed to parse cpu.cfs_period_us - %s", err) } if period != periodAfter { t.Fatal("Got the wrong value, set cpu.cfs_period_us failed.") } rtRuntime, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_runtime_us") if err != nil { t.Fatalf("Failed to parse cpu.rt_runtime_us - %s", err) } if rtRuntime != rtRuntimeAfter { t.Fatal("Got the wrong value, set cpu.rt_runtime_us failed.") } rtPeriod, err := getCgroupParamUint(helper.CgroupPath, "cpu.rt_period_us") if err != nil { t.Fatalf("Failed to parse cpu.rt_period_us - %s", err) } if rtPeriod != rtPeriodAfter { t.Fatal("Got the wrong value, set cpu.rt_period_us failed.") } } func TestCpuStats(t *testing.T) { helper := NewCgroupTestUtil("cpu", t) defer helper.cleanup() const ( kNrPeriods = 2000 kNrThrottled = 200 kThrottledTime = uint64(18446744073709551615) ) cpuStatContent := fmt.Sprintf("nr_periods %d\n nr_throttled %d\n throttled_time %d\n", kNrPeriods, kNrThrottled, kThrottledTime) helper.writeFileContents(map[string]string{ "cpu.stat": cpuStatContent, }) cpu := &CpuGroup{} actualStats := *cgroups.NewStats() err := cpu.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal(err) } expectedStats := cgroups.ThrottlingData{ Periods: kNrPeriods, ThrottledPeriods: kNrThrottled, ThrottledTime: kThrottledTime} expectThrottlingDataEquals(t, expectedStats, actualStats.CpuStats.ThrottlingData) } func TestNoCpuStatFile(t *testing.T) { helper := NewCgroupTestUtil("cpu", t) defer helper.cleanup() cpu := &CpuGroup{} actualStats := *cgroups.NewStats() err := cpu.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal("Expected not to fail, but did") } } func TestInvalidCpuStat(t *testing.T) { helper := NewCgroupTestUtil("cpu", t) defer helper.cleanup() cpuStatContent := `nr_periods 2000 nr_throttled 200 throttled_time fortytwo` helper.writeFileContents(map[string]string{ "cpu.stat": cpuStatContent, }) cpu := &CpuGroup{} actualStats := *cgroups.NewStats() err := cpu.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failed stat parsing.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/cpuacct.go ================================================ // +build linux package fs import ( "fmt" "io/ioutil" "path/filepath" "strconv" "strings" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/system" ) const ( cgroupCpuacctStat = "cpuacct.stat" nanosecondsInSecond = 1000000000 ) var clockTicks = uint64(system.GetClockTicks()) type CpuacctGroup struct { } func (s *CpuacctGroup) Apply(d *data) 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 *data) 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 // system 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/cpuset.go ================================================ // +build linux package fs import ( "bytes" "io/ioutil" "os" "path/filepath" "strconv" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type CpusetGroup struct { } func (s *CpusetGroup) Apply(d *data) error { dir, err := d.path("cpuset") if err != nil && !cgroups.IsNotFound(err) { return err } return s.ApplyDir(dir, d.c, d.pid) } func (s *CpusetGroup) Set(path string, cgroup *configs.Cgroup) error { if cgroup.CpusetCpus != "" { if err := writeFile(path, "cpuset.cpus", cgroup.CpusetCpus); err != nil { return err } } if cgroup.CpusetMems != "" { if err := writeFile(path, "cpuset.mems", cgroup.CpusetMems); err != nil { return err } } return nil } func (s *CpusetGroup) Remove(d *data) 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 } if err := s.ensureParent(dir); 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 := writeFile(dir, "cgroup.procs", strconv.Itoa(pid)); err != nil { return err } // the default values inherit from parent cgroup are already set in // s.ensureParent, cover these if we have our own if err := s.Set(dir, cgroup); 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 ensures that the parent directory of current is created // with the proper cpus and mems files copied from it's parent if the values // are a file with a new line char func (s *CpusetGroup) ensureParent(current string) error { parent := filepath.Dir(current) if _, err := os.Stat(parent); err != nil { if !os.IsNotExist(err) { return err } if err := s.ensureParent(parent); err != nil { return err } } if err := os.MkdirAll(current, 0755); err != nil && !os.IsExist(err) { 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/cpuset_test.go ================================================ // +build linux package fs import ( "testing" ) func TestCpusetSetCpus(t *testing.T) { helper := NewCgroupTestUtil("cpuset", t) defer helper.cleanup() const ( cpusBefore = "0" cpusAfter = "1-3" ) helper.writeFileContents(map[string]string{ "cpuset.cpus": cpusBefore, }) helper.CgroupData.c.CpusetCpus = cpusAfter cpuset := &CpusetGroup{} if err := cpuset.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "cpuset.cpus") if err != nil { t.Fatalf("Failed to parse cpuset.cpus - %s", err) } if value != cpusAfter { t.Fatal("Got the wrong value, set cpuset.cpus failed.") } } func TestCpusetSetMems(t *testing.T) { helper := NewCgroupTestUtil("cpuset", t) defer helper.cleanup() const ( memsBefore = "0" memsAfter = "1" ) helper.writeFileContents(map[string]string{ "cpuset.mems": memsBefore, }) helper.CgroupData.c.CpusetMems = memsAfter cpuset := &CpusetGroup{} if err := cpuset.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "cpuset.mems") if err != nil { t.Fatalf("Failed to parse cpuset.mems - %s", err) } if value != memsAfter { t.Fatal("Got the wrong value, set cpuset.mems failed.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/devices.go ================================================ // +build linux package fs import ( "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type DevicesGroup struct { } func (s *DevicesGroup) Apply(d *data) error { dir, 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 } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *DevicesGroup) Set(path string, cgroup *configs.Cgroup) error { if !cgroup.AllowAllDevices { if err := writeFile(path, "devices.deny", "a"); err != nil { return err } for _, dev := range cgroup.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.DeniedDevices { if err := writeFile(path, "devices.deny", dev.CgroupString()); err != nil { return err } } return nil } func (s *DevicesGroup) Remove(d *data) error { return removePath(d.path("devices")) } func (s *DevicesGroup) GetStats(path string, stats *cgroups.Stats) error { return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/devices_test.go ================================================ // +build linux package fs import ( "testing" "github.com/docker/libcontainer/configs" ) var ( allowedDevices = []*configs.Device{ { Path: "/dev/zero", Type: 'c', Major: 1, Minor: 5, Permissions: "rwm", FileMode: 0666, }, } allowedList = "c 1:5 rwm" deniedDevices = []*configs.Device{ { Path: "/dev/null", Type: 'c', Major: 1, Minor: 3, Permissions: "rwm", FileMode: 0666, }, } deniedList = "c 1:3 rwm" ) func TestDevicesSetAllow(t *testing.T) { helper := NewCgroupTestUtil("devices", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "devices.deny": "a", }) helper.CgroupData.c.AllowAllDevices = false helper.CgroupData.c.AllowedDevices = allowedDevices devices := &DevicesGroup{} if err := devices.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "devices.allow") if err != nil { t.Fatalf("Failed to parse devices.allow - %s", err) } if value != allowedList { t.Fatal("Got the wrong value, set devices.allow failed.") } } func TestDevicesSetDeny(t *testing.T) { helper := NewCgroupTestUtil("devices", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "devices.allow": "a", }) helper.CgroupData.c.AllowAllDevices = true helper.CgroupData.c.DeniedDevices = deniedDevices devices := &DevicesGroup{} if err := devices.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "devices.deny") if err != nil { t.Fatalf("Failed to parse devices.deny - %s", err) } if value != deniedList { t.Fatal("Got the wrong value, set devices.deny failed.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/freezer.go ================================================ // +build linux package fs import ( "fmt" "strings" "time" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type FreezerGroup struct { } func (s *FreezerGroup) Apply(d *data) error { dir, err := d.join("freezer") if err != nil && !cgroups.IsNotFound(err) { return err } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *FreezerGroup) Set(path string, cgroup *configs.Cgroup) error { switch cgroup.Freezer { case configs.Frozen, configs.Thawed: if err := writeFile(path, "freezer.state", string(cgroup.Freezer)); err != nil { return err } for { state, err := readFile(path, "freezer.state") if err != nil { return err } if strings.TrimSpace(state) == string(cgroup.Freezer) { break } time.Sleep(1 * time.Millisecond) } case configs.Undefined: return nil default: return fmt.Errorf("Invalid argument '%s' to freezer.state", string(cgroup.Freezer)) } return nil } func (s *FreezerGroup) Remove(d *data) error { return removePath(d.path("freezer")) } func (s *FreezerGroup) GetStats(path string, stats *cgroups.Stats) error { return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/freezer_test.go ================================================ package fs import ( "testing" "github.com/docker/libcontainer/configs" ) func TestFreezerSetState(t *testing.T) { helper := NewCgroupTestUtil("freezer", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "freezer.state": string(configs.Frozen), }) helper.CgroupData.c.Freezer = configs.Thawed freezer := &FreezerGroup{} if err := freezer.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "freezer.state") if err != nil { t.Fatalf("Failed to parse freezer.state - %s", err) } if value != string(configs.Thawed) { t.Fatal("Got the wrong value, set freezer.state failed.") } } func TestFreezerSetInvalidState(t *testing.T) { helper := NewCgroupTestUtil("freezer", t) defer helper.cleanup() const ( invalidArg configs.FreezerState = "Invalid" ) helper.CgroupData.c.Freezer = invalidArg freezer := &FreezerGroup{} if err := freezer.Set(helper.CgroupPath, helper.CgroupData.c); err == nil { t.Fatal("Failed to return invalid argument error") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/fs_unsupported.go ================================================ // +build !linux package fs ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/hugetlb.go ================================================ // +build linux package fs import ( "fmt" "strconv" "strings" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type HugetlbGroup struct { } func (s *HugetlbGroup) Apply(d *data) error { dir, err := d.join("hugetlb") if err != nil && !cgroups.IsNotFound(err) { return err } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *HugetlbGroup) Set(path string, cgroup *configs.Cgroup) error { for _, hugetlb := range cgroup.HugetlbLimit { if err := writeFile(path, strings.Join([]string{"hugetlb", hugetlb.Pagesize, "limit_in_bytes"}, "."), strconv.Itoa(hugetlb.Limit)); err != nil { return err } } return nil } func (s *HugetlbGroup) Remove(d *data) 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/hugetlb_test.go ================================================ package fs import ( "strconv" "strings" "testing" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) const ( hugetlbUsageContents = "128\n" hugetlbMaxUsageContents = "256\n" hugetlbFailcnt = "100\n" ) var ( hugePageSize, _ = cgroups.GetHugePageSize() usage = strings.Join([]string{"hugetlb", hugePageSize[0], "usage_in_bytes"}, ".") limit = strings.Join([]string{"hugetlb", hugePageSize[0], "limit_in_bytes"}, ".") maxUsage = strings.Join([]string{"hugetlb", hugePageSize[0], "max_usage_in_bytes"}, ".") failcnt = strings.Join([]string{"hugetlb", hugePageSize[0], "failcnt"}, ".") ) func TestHugetlbSetHugetlb(t *testing.T) { helper := NewCgroupTestUtil("hugetlb", t) defer helper.cleanup() const ( hugetlbBefore = 256 hugetlbAfter = 512 ) helper.writeFileContents(map[string]string{ limit: strconv.Itoa(hugetlbBefore), }) helper.CgroupData.c.HugetlbLimit = []*configs.HugepageLimit{ { Pagesize: hugePageSize[0], Limit: hugetlbAfter, }, } hugetlb := &HugetlbGroup{} if err := hugetlb.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, limit) if err != nil { t.Fatalf("Failed to parse %s - %s", limit, err) } if value != hugetlbAfter { t.Fatalf("Set hugetlb.limit_in_bytes failed. Expected: %v, Got: %v", hugetlbAfter, value) } } func TestHugetlbStats(t *testing.T) { helper := NewCgroupTestUtil("hugetlb", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ usage: hugetlbUsageContents, maxUsage: hugetlbMaxUsageContents, failcnt: hugetlbFailcnt, }) hugetlb := &HugetlbGroup{} actualStats := *cgroups.NewStats() err := hugetlb.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal(err) } expectedStats := cgroups.HugetlbStats{Usage: 128, MaxUsage: 256, Failcnt: 100} expectHugetlbStatEquals(t, expectedStats, actualStats.HugetlbStats[hugePageSize[0]]) } func TestHugetlbStatsNoUsageFile(t *testing.T) { helper := NewCgroupTestUtil("hugetlb", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ maxUsage: hugetlbMaxUsageContents, }) hugetlb := &HugetlbGroup{} actualStats := *cgroups.NewStats() err := hugetlb.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestHugetlbStatsNoMaxUsageFile(t *testing.T) { helper := NewCgroupTestUtil("hugetlb", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ usage: hugetlbUsageContents, }) hugetlb := &HugetlbGroup{} actualStats := *cgroups.NewStats() err := hugetlb.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestHugetlbStatsBadUsageFile(t *testing.T) { helper := NewCgroupTestUtil("hugetlb", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ usage: "bad", maxUsage: hugetlbMaxUsageContents, }) hugetlb := &HugetlbGroup{} actualStats := *cgroups.NewStats() err := hugetlb.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestHugetlbStatsBadMaxUsageFile(t *testing.T) { helper := NewCgroupTestUtil("hugetlb", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ usage: hugetlbUsageContents, maxUsage: "bad", }) hugetlb := &HugetlbGroup{} actualStats := *cgroups.NewStats() err := hugetlb.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/memory.go ================================================ // +build linux package fs import ( "bufio" "fmt" "os" "path/filepath" "strconv" "strings" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type MemoryGroup struct { } func (s *MemoryGroup) Apply(d *data) error { dir, err := d.join("memory") if err != nil && !cgroups.IsNotFound(err) { return err } defer func() { if err != nil { os.RemoveAll(dir) } }() if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error { if cgroup.Memory != 0 { if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Memory, 10)); err != nil { return err } } if cgroup.MemoryReservation != 0 { if err := writeFile(path, "memory.soft_limit_in_bytes", strconv.FormatInt(cgroup.MemoryReservation, 10)); err != nil { return err } } if cgroup.MemorySwap > 0 { if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.MemorySwap, 10)); err != nil { return err } } if cgroup.KernelMemory > 0 { if err := writeFile(path, "memory.kmem.limit_in_bytes", strconv.FormatInt(cgroup.KernelMemory, 10)); err != nil { return err } } if cgroup.OomKillDisable { if err := writeFile(path, "memory.oom_control", "1"); err != nil { return err } } if cgroup.MemorySwappiness >= 0 && cgroup.MemorySwappiness <= 100 { if err := writeFile(path, "memory.swappiness", strconv.FormatInt(cgroup.MemorySwappiness, 10)); err != nil { return err } } return nil } func (s *MemoryGroup) Remove(d *data) 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 return nil } 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"}, ".") 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 return memoryData, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/memory_test.go ================================================ // +build linux package fs import ( "strconv" "testing" "github.com/docker/libcontainer/cgroups" ) const ( memoryStatContents = `cache 512 rss 1024` memoryUsageContents = "2048\n" memoryMaxUsageContents = "4096\n" memoryFailcnt = "100\n" ) func TestMemorySetMemory(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() const ( memoryBefore = 314572800 // 300M memoryAfter = 524288000 // 500M reservationBefore = 209715200 // 200M reservationAfter = 314572800 // 300M ) helper.writeFileContents(map[string]string{ "memory.limit_in_bytes": strconv.Itoa(memoryBefore), "memory.soft_limit_in_bytes": strconv.Itoa(reservationBefore), }) helper.CgroupData.c.Memory = memoryAfter helper.CgroupData.c.MemoryReservation = reservationAfter memory := &MemoryGroup{} if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "memory.limit_in_bytes") if err != nil { t.Fatalf("Failed to parse memory.limit_in_bytes - %s", err) } if value != memoryAfter { t.Fatal("Got the wrong value, set memory.limit_in_bytes failed.") } value, err = getCgroupParamUint(helper.CgroupPath, "memory.soft_limit_in_bytes") if err != nil { t.Fatalf("Failed to parse memory.soft_limit_in_bytes - %s", err) } if value != reservationAfter { t.Fatal("Got the wrong value, set memory.soft_limit_in_bytes failed.") } } func TestMemorySetMemoryswap(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() const ( memoryswapBefore = 314572800 // 300M memoryswapAfter = 524288000 // 500M ) helper.writeFileContents(map[string]string{ "memory.memsw.limit_in_bytes": strconv.Itoa(memoryswapBefore), }) helper.CgroupData.c.MemorySwap = memoryswapAfter memory := &MemoryGroup{} if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "memory.memsw.limit_in_bytes") if err != nil { t.Fatalf("Failed to parse memory.memsw.limit_in_bytes - %s", err) } if value != memoryswapAfter { t.Fatal("Got the wrong value, set memory.memsw.limit_in_bytes failed.") } } func TestMemorySetKernelMemory(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() const ( kernelMemoryBefore = 314572800 // 300M kernelMemoryAfter = 524288000 // 500M ) helper.writeFileContents(map[string]string{ "memory.kmem.limit_in_bytes": strconv.Itoa(kernelMemoryBefore), }) helper.CgroupData.c.KernelMemory = kernelMemoryAfter memory := &MemoryGroup{} if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "memory.kmem.limit_in_bytes") if err != nil { t.Fatalf("Failed to parse memory.kmem.limit_in_bytes - %s", err) } if value != kernelMemoryAfter { t.Fatal("Got the wrong value, set memory.kmem.limit_in_bytes failed.") } } func TestMemorySetMemorySwappinessDefault(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() const ( swappinessBefore = 60 //deafult is 60 swappinessAfter = 0 ) helper.writeFileContents(map[string]string{ "memory.swappiness": strconv.Itoa(swappinessBefore), }) helper.CgroupData.c.Memory = swappinessAfter memory := &MemoryGroup{} if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "memory.swappiness") if err != nil { t.Fatalf("Failed to parse memory.swappiness - %s", err) } if value != swappinessAfter { t.Fatal("Got the wrong value, set memory.swappiness failed.") } } func TestMemoryStats(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.stat": memoryStatContents, "memory.usage_in_bytes": memoryUsageContents, "memory.max_usage_in_bytes": memoryMaxUsageContents, "memory.failcnt": memoryFailcnt, "memory.memsw.usage_in_bytes": memoryUsageContents, "memory.memsw.max_usage_in_bytes": memoryMaxUsageContents, "memory.memsw.failcnt": memoryFailcnt, "memory.kmem.usage_in_bytes": memoryUsageContents, "memory.kmem.max_usage_in_bytes": memoryMaxUsageContents, "memory.kmem.failcnt": memoryFailcnt, }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal(err) } expectedStats := cgroups.MemoryStats{Cache: 512, Usage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100}, SwapUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100}, KernelUsage: cgroups.MemoryData{Usage: 2048, MaxUsage: 4096, Failcnt: 100}, Stats: map[string]uint64{"cache": 512, "rss": 1024}} expectMemoryStatEquals(t, expectedStats, actualStats.MemoryStats) } func TestMemoryStatsNoStatFile(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.usage_in_bytes": memoryUsageContents, "memory.max_usage_in_bytes": memoryMaxUsageContents, }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err != nil { t.Fatal(err) } } func TestMemoryStatsNoUsageFile(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.stat": memoryStatContents, "memory.max_usage_in_bytes": memoryMaxUsageContents, }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestMemoryStatsNoMaxUsageFile(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.stat": memoryStatContents, "memory.usage_in_bytes": memoryUsageContents, }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestMemoryStatsBadStatFile(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.stat": "rss rss", "memory.usage_in_bytes": memoryUsageContents, "memory.max_usage_in_bytes": memoryMaxUsageContents, }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestMemoryStatsBadUsageFile(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.stat": memoryStatContents, "memory.usage_in_bytes": "bad", "memory.max_usage_in_bytes": memoryMaxUsageContents, }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestMemoryStatsBadMaxUsageFile(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "memory.stat": memoryStatContents, "memory.usage_in_bytes": memoryUsageContents, "memory.max_usage_in_bytes": "bad", }) memory := &MemoryGroup{} actualStats := *cgroups.NewStats() err := memory.GetStats(helper.CgroupPath, &actualStats) if err == nil { t.Fatal("Expected failure") } } func TestMemorySetOomControl(t *testing.T) { helper := NewCgroupTestUtil("memory", t) defer helper.cleanup() const ( oom_kill_disable = 1 // disable oom killer, default is 0 ) helper.writeFileContents(map[string]string{ "memory.oom_control": strconv.Itoa(oom_kill_disable), }) memory := &MemoryGroup{} if err := memory.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamUint(helper.CgroupPath, "memory.oom_control") if err != nil { t.Fatalf("Failed to parse memory.oom_control - %s", err) } if value != oom_kill_disable { t.Fatalf("Got the wrong value, set memory.oom_control failed.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/net_cls.go ================================================ package fs import ( "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type NetClsGroup struct { } func (s *NetClsGroup) Apply(d *data) error { dir, err := d.join("net_cls") if err != nil && !cgroups.IsNotFound(err) { return err } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *NetClsGroup) Set(path string, cgroup *configs.Cgroup) error { if cgroup.NetClsClassid != "" { if err := writeFile(path, "net_cls.classid", cgroup.NetClsClassid); err != nil { return err } } return nil } func (s *NetClsGroup) Remove(d *data) error { return removePath(d.path("net_cls")) } func (s *NetClsGroup) GetStats(path string, stats *cgroups.Stats) error { return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/net_cls_test.go ================================================ package fs import ( "testing" ) const ( classidBefore = "0x100002" classidAfter = "0x100001" ) func TestNetClsSetClassid(t *testing.T) { helper := NewCgroupTestUtil("net_cls", t) defer helper.cleanup() helper.writeFileContents(map[string]string{ "net_cls.classid": classidBefore, }) helper.CgroupData.c.NetClsClassid = classidAfter netcls := &NetClsGroup{} if err := netcls.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } // As we are in mock environment, we can't get correct value of classid from // net_cls.classid. // So. we just judge if we successfully write classid into file value, err := getCgroupParamString(helper.CgroupPath, "net_cls.classid") if err != nil { t.Fatalf("Failed to parse net_cls.classid - %s", err) } if value != classidAfter { t.Fatal("Got the wrong value, set net_cls.classid failed.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/net_prio.go ================================================ package fs import ( "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type NetPrioGroup struct { } func (s *NetPrioGroup) Apply(d *data) error { dir, err := d.join("net_prio") if err != nil && !cgroups.IsNotFound(err) { return err } if err := s.Set(dir, d.c); err != nil { return err } return nil } func (s *NetPrioGroup) Set(path string, cgroup *configs.Cgroup) error { for _, prioMap := range cgroup.NetPrioIfpriomap { if err := writeFile(path, "net_prio.ifpriomap", prioMap.CgroupString()); err != nil { return err } } return nil } func (s *NetPrioGroup) Remove(d *data) error { return removePath(d.path("net_prio")) } func (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error { return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/net_prio_test.go ================================================ package fs import ( "strings" "testing" "github.com/docker/libcontainer/configs" ) var ( prioMap = []*configs.IfPrioMap{ { Interface: "test", Priority: 5, }, } ) func TestNetPrioSetIfPrio(t *testing.T) { helper := NewCgroupTestUtil("net_prio", t) defer helper.cleanup() helper.CgroupData.c.NetPrioIfpriomap = prioMap netPrio := &NetPrioGroup{} if err := netPrio.Set(helper.CgroupPath, helper.CgroupData.c); err != nil { t.Fatal(err) } value, err := getCgroupParamString(helper.CgroupPath, "net_prio.ifpriomap") if err != nil { t.Fatalf("Failed to parse net_prio.ifpriomap - %s", err) } if !strings.Contains(value, "test 5") { t.Fatal("Got the wrong value, set net_prio.ifpriomap failed.") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/perf_event.go ================================================ // +build linux package fs import ( "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type PerfEventGroup struct { } func (s *PerfEventGroup) Apply(d *data) 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 *data) error { return removePath(d.path("perf_event")) } func (s *PerfEventGroup) GetStats(path string, stats *cgroups.Stats) error { return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/stats_util_test.go ================================================ // +build linux package fs import ( "fmt" "testing" "github.com/Sirupsen/logrus" "github.com/docker/libcontainer/cgroups" ) func blkioStatEntryEquals(expected, actual []cgroups.BlkioStatEntry) error { if len(expected) != len(actual) { return fmt.Errorf("blkioStatEntries length do not match") } for i, expValue := range expected { actValue := actual[i] if expValue != actValue { return fmt.Errorf("Expected blkio stat entry %v but found %v", expValue, actValue) } } return nil } func expectBlkioStatsEquals(t *testing.T, expected, actual cgroups.BlkioStats) { if err := blkioStatEntryEquals(expected.IoServiceBytesRecursive, actual.IoServiceBytesRecursive); err != nil { logrus.Printf("blkio IoServiceBytesRecursive do not match - %s\n", err) t.Fail() } if err := blkioStatEntryEquals(expected.IoServicedRecursive, actual.IoServicedRecursive); err != nil { logrus.Printf("blkio IoServicedRecursive do not match - %s\n", err) t.Fail() } if err := blkioStatEntryEquals(expected.IoQueuedRecursive, actual.IoQueuedRecursive); err != nil { logrus.Printf("blkio IoQueuedRecursive do not match - %s\n", err) t.Fail() } if err := blkioStatEntryEquals(expected.SectorsRecursive, actual.SectorsRecursive); err != nil { logrus.Printf("blkio SectorsRecursive do not match - %s\n", err) t.Fail() } if err := blkioStatEntryEquals(expected.IoServiceTimeRecursive, actual.IoServiceTimeRecursive); err != nil { logrus.Printf("blkio IoServiceTimeRecursive do not match - %s\n", err) t.Fail() } if err := blkioStatEntryEquals(expected.IoWaitTimeRecursive, actual.IoWaitTimeRecursive); err != nil { logrus.Printf("blkio IoWaitTimeRecursive do not match - %s\n", err) t.Fail() } if err := blkioStatEntryEquals(expected.IoMergedRecursive, actual.IoMergedRecursive); err != nil { logrus.Printf("blkio IoMergedRecursive do not match - %v vs %v\n", expected.IoMergedRecursive, actual.IoMergedRecursive) t.Fail() } if err := blkioStatEntryEquals(expected.IoTimeRecursive, actual.IoTimeRecursive); err != nil { logrus.Printf("blkio IoTimeRecursive do not match - %s\n", err) t.Fail() } } func expectThrottlingDataEquals(t *testing.T, expected, actual cgroups.ThrottlingData) { if expected != actual { logrus.Printf("Expected throttling data %v but found %v\n", expected, actual) t.Fail() } } func expectHugetlbStatEquals(t *testing.T, expected, actual cgroups.HugetlbStats) { if expected != actual { logrus.Printf("Expected hugetlb stats %v but found %v\n", expected, actual) t.Fail() } } func expectMemoryStatEquals(t *testing.T, expected, actual cgroups.MemoryStats) { expectMemoryDataEquals(t, expected.Usage, actual.Usage) expectMemoryDataEquals(t, expected.SwapUsage, actual.SwapUsage) expectMemoryDataEquals(t, expected.KernelUsage, actual.KernelUsage) for key, expValue := range expected.Stats { actValue, ok := actual.Stats[key] if !ok { logrus.Printf("Expected memory stat key %s not found\n", key) t.Fail() } if expValue != actValue { logrus.Printf("Expected memory stat value %d but found %d\n", expValue, actValue) t.Fail() } } } func expectMemoryDataEquals(t *testing.T, expected, actual cgroups.MemoryData) { if expected.Usage != actual.Usage { logrus.Printf("Expected memory usage %d but found %d\n", expected.Usage, actual.Usage) t.Fail() } if expected.MaxUsage != actual.MaxUsage { logrus.Printf("Expected memory max usage %d but found %d\n", expected.MaxUsage, actual.MaxUsage) t.Fail() } if expected.Failcnt != actual.Failcnt { logrus.Printf("Expected memory failcnt %d but found %d\n", expected.Failcnt, actual.Failcnt) t.Fail() } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/util_test.go ================================================ // +build linux /* Utility for testing cgroup operations. Creates a mock of the cgroup filesystem for the duration of the test. */ package fs import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/docker/libcontainer/configs" ) type cgroupTestUtil struct { // data to use in tests. CgroupData *data // Path to the mock cgroup directory. CgroupPath string // Temporary directory to store mock cgroup filesystem. tempDir string t *testing.T } // Creates a new test util for the specified subsystem func NewCgroupTestUtil(subsystem string, t *testing.T) *cgroupTestUtil { d := &data{ c: &configs.Cgroup{}, } tempDir, err := ioutil.TempDir("", "cgroup_test") if err != nil { t.Fatal(err) } d.root = tempDir testCgroupPath := filepath.Join(d.root, subsystem) if err != nil { t.Fatal(err) } // Ensure the full mock cgroup path exists. err = os.MkdirAll(testCgroupPath, 0755) if err != nil { t.Fatal(err) } return &cgroupTestUtil{CgroupData: d, CgroupPath: testCgroupPath, tempDir: tempDir, t: t} } func (c *cgroupTestUtil) cleanup() { os.RemoveAll(c.tempDir) } // Write the specified contents on the mock of the specified cgroup files. func (c *cgroupTestUtil) writeFileContents(fileContents map[string]string) { for file, contents := range fileContents { err := writeFile(c.CgroupPath, file, contents) if err != nil { c.t.Fatal(err) } } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/utils.go ================================================ // +build linux package fs import ( "errors" "fmt" "io/ioutil" "path/filepath" "strconv" "strings" ) var ( ErrNotSupportStat = errors.New("stats are not supported for subsystem") 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) { contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile)) if err != nil { return 0, err } return parseUint(strings.TrimSpace(string(contents)), 10, 64) } // 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/fs/utils_test.go ================================================ // +build linux package fs import ( "io/ioutil" "math" "os" "path/filepath" "strconv" "testing" ) const ( cgroupFile = "cgroup.file" floatValue = 2048.0 floatString = "2048" ) func TestGetCgroupParamsInt(t *testing.T) { // Setup tempdir. tempDir, err := ioutil.TempDir("", "cgroup_utils_test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) tempFile := filepath.Join(tempDir, cgroupFile) // Success. err = ioutil.WriteFile(tempFile, []byte(floatString), 0755) if err != nil { t.Fatal(err) } value, err := getCgroupParamUint(tempDir, cgroupFile) if err != nil { t.Fatal(err) } else if value != floatValue { t.Fatalf("Expected %d to equal %f", value, floatValue) } // Success with new line. err = ioutil.WriteFile(tempFile, []byte(floatString+"\n"), 0755) if err != nil { t.Fatal(err) } value, err = getCgroupParamUint(tempDir, cgroupFile) if err != nil { t.Fatal(err) } else if value != floatValue { t.Fatalf("Expected %d to equal %f", value, floatValue) } // Success with negative values err = ioutil.WriteFile(tempFile, []byte("-12345"), 0755) if err != nil { t.Fatal(err) } value, err = getCgroupParamUint(tempDir, cgroupFile) if err != nil { t.Fatal(err) } else if value != 0 { t.Fatalf("Expected %d to equal %d", value, 0) } // Success with negative values lesser than min int64 s := strconv.FormatFloat(math.MinInt64, 'f', -1, 64) err = ioutil.WriteFile(tempFile, []byte(s), 0755) if err != nil { t.Fatal(err) } value, err = getCgroupParamUint(tempDir, cgroupFile) if err != nil { t.Fatal(err) } else if value != 0 { t.Fatalf("Expected %d to equal %d", value, 0) } // Not a float. err = ioutil.WriteFile(tempFile, []byte("not-a-float"), 0755) if err != nil { t.Fatal(err) } _, err = getCgroupParamUint(tempDir, cgroupFile) if err == nil { t.Fatal("Expecting error, got none") } // Unknown file. err = os.Remove(tempFile) if err != nil { t.Fatal(err) } _, err = getCgroupParamUint(tempDir, cgroupFile) if err == nil { t.Fatal("Expecting error, got none") } } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/stats.go ================================================ // +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"` } // 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"` } 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"` // usafe of kernel memory KernelUsage MemoryData `json:"kernel_usage,omitempty"` Stats map[string]uint64 `json:"stats,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 htgetlb usage allocation failure. Failcnt uint64 `json:"failcnt"` } type Stats struct { CpuStats CpuStats `json:"cpu_stats,omitempty"` MemoryStats MemoryStats `json:"memory_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} } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/systemd/apply_nosystemd.go ================================================ // +build !linux package systemd import ( "fmt" "github.com/docker/libcontainer/cgroups" "github.com/docker/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) 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") } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/systemd/apply_systemd.go ================================================ // +build linux package systemd import ( "fmt" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" "time" systemd "github.com/coreos/go-systemd/dbus" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/cgroups/fs" "github.com/docker/libcontainer/configs" "github.com/godbus/dbus" ) type Manager struct { mu sync.Mutex Cgroups *configs.Cgroup Paths map[string]string } type subsystem interface { // 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 subsystems = map[string]subsystem{ "devices": &fs.DevicesGroup{}, "memory": &fs.MemoryGroup{}, "cpu": &fs.CpuGroup{}, "cpuset": &fs.CpusetGroup{}, "cpuacct": &fs.CpuacctGroup{}, "blkio": &fs.BlkioGroup{}, "hugetlb": &fs.HugetlbGroup{}, "perf_event": &fs.PerfEventGroup{}, "freezer": &fs.FreezerGroup{}, "net_prio": &fs.NetPrioGroup{}, "net_cls": &fs.NetClsGroup{}, } const ( testScopeWait = 4 ) var ( connLock sync.Mutex theConn *systemd.Conn hasStartTransientUnit bool hasTransientDefaultDependencies bool ) func newProp(name string, units interface{}) systemd.Property { return systemd.Property{ Name: name, Value: dbus.MakeVariant(units), } } func UseSystemd() bool { s, err := os.Stat("/run/systemd/system") if err != nil || !s.IsDir() { return false } connLock.Lock() defer connLock.Unlock() if theConn == nil { var err error theConn, err = systemd.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"); 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"); 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", ddf); 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") } return hasStartTransientUnit } func getIfaceForUnit(unitName string) string { if strings.HasSuffix(unitName, ".scope") { return "Scope" } if strings.HasSuffix(unitName, ".service") { return "Service" } return "Unit" } func (m *Manager) Apply(pid int) error { var ( c = m.Cgroups unitName = getUnitName(c) slice = "system.slice" properties []systemd.Property ) if c.Slice != "" { slice = c.Slice } properties = append(properties, systemd.PropSlice(slice), systemd.PropDescription("docker container "+c.Name), newProp("PIDs", []uint32{uint32(pid)}), ) // 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.Memory != 0 { properties = append(properties, newProp("MemoryLimit", uint64(c.Memory))) } // TODO: MemoryReservation and MemorySwap not available in systemd if c.CpuShares != 0 { properties = append(properties, newProp("CPUShares", uint64(c.CpuShares))) } if c.BlkioWeight != 0 { properties = append(properties, newProp("BlockIOWeight", uint64(c.BlkioWeight))) } if _, err := theConn.StartTransientUnit(unitName, "replace", properties...); err != nil { return err } if err := joinDevices(c, pid); err != nil { return err } // TODO: CpuQuota and CpuPeriod not available in systemd // we need to manually join the cpu.cfs_quota_us and cpu.cfs_period_us if err := joinCpu(c, pid); err != nil { return err } if err := joinMemory(c, pid); err != nil { return err } // we need to manually join the freezer, net_cls, net_prio and cpuset cgroup in systemd // because it does not currently support it via the dbus api. if err := joinFreezer(c, pid); err != nil { return err } if err := joinNetPrio(c, pid); err != nil { return err } if err := joinNetCls(c, pid); err != nil { return err } if err := joinCpuset(c, pid); err != nil { return err } if err := joinHugetlb(c, pid); err != nil { return err } // FIXME: Systemd does have `BlockIODeviceWeight` property, but we got problem // using that (at least on systemd 208, see https://github.com/docker/libcontainer/pull/354), // so use fs work around for now. if err := joinBlkio(c, pid); err != nil { return err } paths := make(map[string]string) for sysname := range subsystems { subsystemPath, err := getSubsystemPath(m.Cgroups, sysname) 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[sysname] = subsystemPath } m.Paths = paths if paths["cpu"] != "" { if err := fs.CheckCpushares(paths["cpu"], c.CpuShares); err != nil { return err } } return nil } func (m *Manager) Destroy() error { m.mu.Lock() defer m.mu.Unlock() theConn.StopUnit(getUnitName(m.Cgroups), "replace") 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 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) } return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700) } 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 && !os.IsExist(err) { return "", err } if err := writeFile(path, "cgroup.procs", strconv.Itoa(pid)); err != nil { return "", err } return path, nil } func joinCpu(c *configs.Cgroup, pid int) error { path, err := getSubsystemPath(c, "cpu") if err != nil && !cgroups.IsNotFound(err) { return err } if c.CpuQuota != 0 { if err = writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(c.CpuQuota, 10)); err != nil { return err } } if c.CpuPeriod != 0 { if err = writeFile(path, "cpu.cfs_period_us", strconv.FormatInt(c.CpuPeriod, 10)); err != nil { return err } } if c.CpuRtPeriod != 0 { if err = writeFile(path, "cpu.rt_period_us", strconv.FormatInt(c.CpuRtPeriod, 10)); err != nil { return err } } if c.CpuRtRuntime != 0 { if err = writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(c.CpuRtRuntime, 10)); err != nil { return err } } return nil } func joinFreezer(c *configs.Cgroup, pid int) error { path, err := join(c, "freezer", pid) if err != nil && !cgroups.IsNotFound(err) { return err } freezer := subsystems["freezer"] return freezer.Set(path, c) } func joinNetPrio(c *configs.Cgroup, pid int) error { path, err := join(c, "net_prio", pid) if err != nil && !cgroups.IsNotFound(err) { return err } netPrio := subsystems["net_prio"] return netPrio.Set(path, c) } func joinNetCls(c *configs.Cgroup, pid int) error { path, err := join(c, "net_cls", pid) if err != nil && !cgroups.IsNotFound(err) { return err } netcls := subsystems["net_cls"] return netcls.Set(path, c) } func getSubsystemPath(c *configs.Cgroup, subsystem string) (string, error) { mountpoint, err := cgroups.FindCgroupMountpoint(subsystem) if err != nil { return "", err } initPath, err := cgroups.GetInitCgroupDir(subsystem) if err != nil { return "", err } slice := "system.slice" if c.Slice != "" { slice = c.Slice } 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.Freezer m.Cgroups.Freezer = state freezer := subsystems["freezer"] err = freezer.Set(path, m.Cgroups) if err != nil { m.Cgroups.Freezer = prevState return err } return nil } func (m *Manager) GetPids() ([]int, error) { path, err := getSubsystemPath(m.Cgroups, "cpu") if err != nil { return nil, err } return cgroups.ReadProcsFile(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, ok := subsystems[name] if !ok || !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 { for name, path := range m.Paths { sys, ok := subsystems[name] if !ok || !cgroups.PathExists(path) { continue } if err := sys.Set(path, container.Cgroups); err != nil { return err } } return nil } func getUnitName(c *configs.Cgroup) string { return fmt.Sprintf("%s-%s.scope", c.Parent, c.Name) } // Atm we can't use the systemd device support because of two missing things: // * Support for wildcards to allow mknod on any device // * Support for wildcards to allow /dev/pts support // // The second is available in more recent systemd as "char-pts", but not in e.g. v208 which is // in wide use. When both these are available we will be able to switch, but need to keep the old // implementation for backwards compat. // // Note: we can't use systemd to set up the initial limits, and then change the cgroup // because systemd will re-write the device settings if it needs to re-apply the cgroup context. // This happens at least for v208 when any sibling unit is started. func joinDevices(c *configs.Cgroup, pid int) error { path, err := join(c, "devices", pid) // Even if it's `not found` error, we'll return err because devices cgroup // is hard requirement for container security. if err != nil { return err } devices := subsystems["devices"] return devices.Set(path, c) } func joinMemory(c *configs.Cgroup, pid int) error { path, err := getSubsystemPath(c, "memory") if err != nil && !cgroups.IsNotFound(err) { return err } // -1 disables memoryswap if c.MemorySwap > 0 { err = writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(c.MemorySwap, 10)) if err != nil { return err } } if c.KernelMemory > 0 { err = writeFile(path, "memory.kmem.limit_in_bytes", strconv.FormatInt(c.KernelMemory, 10)) if err != nil { return err } } if c.MemorySwappiness >= 0 && c.MemorySwappiness <= 100 { err = writeFile(path, "memory.swappiness", strconv.FormatInt(c.MemorySwappiness, 10)) if err != nil { return err } } return nil } // systemd does not atm set up the cpuset controller, so we must manually // join it. Additionally that is a very finicky controller where each // level must have a full setup as the default for a new directory is "no cpus" func joinCpuset(c *configs.Cgroup, pid int) error { path, err := getSubsystemPath(c, "cpuset") if err != nil && !cgroups.IsNotFound(err) { return err } s := &fs.CpusetGroup{} return s.ApplyDir(path, c, pid) } // `BlockIODeviceWeight` property of systemd does not work properly, and systemd // expects device path instead of major minor numbers, which is also confusing // for users. So we use fs work around for now. func joinBlkio(c *configs.Cgroup, pid int) error { path, err := getSubsystemPath(c, "blkio") if err != nil { return err } if c.BlkioWeightDevice != "" { if err := writeFile(path, "blkio.weight_device", c.BlkioWeightDevice); err != nil { return err } } if c.BlkioThrottleReadBpsDevice != "" { if err := writeFile(path, "blkio.throttle.read_bps_device", c.BlkioThrottleReadBpsDevice); err != nil { return err } } if c.BlkioThrottleWriteBpsDevice != "" { if err := writeFile(path, "blkio.throttle.write_bps_device", c.BlkioThrottleWriteBpsDevice); err != nil { return err } } if c.BlkioThrottleReadIOpsDevice != "" { if err := writeFile(path, "blkio.throttle.read_iops_device", c.BlkioThrottleReadIOpsDevice); err != nil { return err } } if c.BlkioThrottleWriteIOpsDevice != "" { if err := writeFile(path, "blkio.throttle.write_iops_device", c.BlkioThrottleWriteIOpsDevice); err != nil { return err } } return nil } func joinHugetlb(c *configs.Cgroup, pid int) error { path, err := join(c, "hugetlb", pid) if err != nil && !cgroups.IsNotFound(err) { return err } hugetlb := subsystems["hugetlb"] return hugetlb.Set(path, c) } ================================================ FILE: vendor/github.com/docker/libcontainer/cgroups/utils.go ================================================ // +build linux package cgroups import ( "bufio" "fmt" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "time" "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/units" ) // https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt func FindCgroupMountpoint(subsystem string) (string, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return "", err } 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], nil } } } if err := scanner.Err(); err != nil { return "", err } return "", NewNotFoundError(subsystem) } func FindCgroupMountpointDir() (string, error) { mounts, err := mount.GetMounts() if err != nil { return "", err } for _, mount := range mounts { if mount.Fstype == "cgroup" { return filepath.Dir(mount.Mountpoint), nil } } return "", NewNotFoundError("cgroup") } type Mount struct { Mountpoint string Subsystems []string } func (m Mount) GetThisCgroupDir() (string, error) { if len(m.Subsystems) == 0 { return "", fmt.Errorf("no subsystem for mount") } return GetThisCgroupDir(m.Subsystems[0]) } func GetCgroupMounts() ([]Mount, error) { mounts, err := mount.GetMounts() if err != nil { return nil, err } all, err := GetAllSubsystems() if err != nil { return nil, err } allMap := make(map[string]bool) for _, s := range all { allMap[s] = true } res := []Mount{} for _, mount := range mounts { if mount.Fstype == "cgroup" { m := Mount{Mountpoint: mount.Mountpoint} for _, opt := range strings.Split(mount.VfsOpts, ",") { if strings.HasPrefix(opt, "name=") { m.Subsystems = append(m.Subsystems, opt) } if allMap[opt] { m.Subsystems = append(m.Subsystems, opt) } } res = append(res, m) } } return res, nil } // 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() { if err := s.Err(); err != nil { return nil, err } text := s.Text() if text[0] != '#' { parts := strings.Fields(text) if len(parts) >= 4 && parts[3] != "0" { subsystems = append(subsystems, parts[0]) } } } return subsystems, nil } // Returns the relative path to the cgroup docker is running in. func GetThisCgroupDir(subsystem string) (string, error) { f, err := os.Open("/proc/self/cgroup") if err != nil { return "", err } defer f.Close() return ParseCgroupFile(subsystem, f) } func GetInitCgroupDir(subsystem string) (string, error) { f, err := os.Open("/proc/1/cgroup") if err != nil { return "", err } defer f.Close() return ParseCgroupFile(subsystem, f) } func ReadProcsFile(dir string) ([]int, error) { f, err := os.Open(filepath.Join(dir, "cgroup.procs")) 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 } func ParseCgroupFile(subsystem string, r io.Reader) (string, error) { s := bufio.NewScanner(r) for s.Scan() { if err := s.Err(); err != nil { return "", err } text := s.Text() parts := strings.Split(text, ":") for _, subs := range strings.Split(parts[1], ",") { if subs == subsystem { return parts[2], 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 := ioutil.WriteFile(filepath.Join(path, "cgroup.procs"), []byte(strconv.Itoa(pid)), 0700); 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: %s", 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/cgroup.go ================================================ package configs type FreezerState string const ( Undefined FreezerState = "" Frozen FreezerState = "FROZEN" Thawed FreezerState = "THAWED" ) // TODO Windows: This can be factored out in the future as Cgroups are not // supported on the Windows platform. type Cgroup struct { Name string `json:"name"` // name of parent cgroup or slice Parent string `json:"parent"` // 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. AllowAllDevices bool `json:"allow_all_devices"` AllowedDevices []*Device `json:"allowed_devices"` DeniedDevices []*Device `json:"denied_devices"` // Memory limit (in bytes) Memory int64 `json:"memory"` // Memory reservation or soft_limit (in bytes) MemoryReservation int64 `json:"memory_reservation"` // Total memory usage (memory + swap); set `-1' to disable swap MemorySwap int64 `json:"memory_swap"` // Kernel memory limit (in bytes) KernelMemory int64 `json:"kernel_memory"` // CPU shares (relative weight vs. other containers) CpuShares int64 `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 int64 `json:"cpu_period"` // How many time CPU will use in realtime scheduling (in usecs). CpuRtRuntime int64 `json:"cpu_quota"` // CPU period to be used for realtime scheduling (in usecs). CpuRtPeriod int64 `json:"cpu_period"` // CPU to use CpusetCpus string `json:"cpuset_cpus"` // MEM to use CpusetMems string `json:"cpuset_mems"` // IO read rate limit per cgroup per device, bytes per second. BlkioThrottleReadBpsDevice string `json:"blkio_throttle_read_bps_device"` // IO write rate limit per cgroup per divice, bytes per second. BlkioThrottleWriteBpsDevice string `json:"blkio_throttle_write_bps_device"` // IO read rate limit per cgroup per device, IO per second. BlkioThrottleReadIOpsDevice string `json:"blkio_throttle_read_iops_device"` // IO write rate limit per cgroup per device, IO per second. BlkioThrottleWriteIOpsDevice string `json:"blkio_throttle_write_iops_device"` // Specifies per cgroup weight, range is from 10 to 1000. BlkioWeight int64 `json:"blkio_weight"` // Weight per cgroup per device, can override BlkioWeight. BlkioWeightDevice string `json:"blkio_weight_device"` // set the freeze value for the process Freezer FreezerState `json:"freezer"` // Hugetlb limit (in bytes) HugetlbLimit []*HugepageLimit `json:"hugetlb_limit"` // Parent slice to use for systemd TODO: remove in favor or parent Slice string `json:"slice"` // Whether to disable OOM Killer OomKillDisable bool `json:"oom_kill_disable"` // Tuning swappiness behaviour per cgroup MemorySwappiness int64 `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 string `json:"net_cls_classid"` } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/config.go ================================================ package configs 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"` } type Seccomp struct { Syscalls []*Syscall `json:"syscalls"` } type Action int const ( Kill Action = iota - 3 Trap Allow ) type Operator int const ( EqualTo Operator = iota NotEqualTo GreatherThan LessThan MaskEqualTo ) type Arg struct { Index int `json:"index"` Value uint32 `json:"value"` Op Operator `json:"op"` } type Syscall struct { Value int `json:"value"` 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"` // PivotDir allows a custom directory inside the container's root filesystem to be used as pivot, when NoPivotRoot is not set. // When a custom PivotDir not set, a temporary dir inside the root filesystem will be used. The pivot dir needs to be writeable. // This is required when using read only root filesystems. In these cases, a read/writeable path can be (bind) mounted somewhere inside the root filesystem to act as pivot. PivotDir string `json:"pivot_dir"` // 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"` // Privatefs will mount the container's rootfs as private where mount points from the parent will not propogate Privatefs bool `json:"privatefs"` // 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 capbilities not specified will be dropped from the processes capability mask Capabilities []string `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"` // ProcessLabel specifies the label to apply to the process running in the container. It is // commonly used by selinux ProcessLabel string `json:"process_label"` // 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"` // AdditionalGroups specifies the gids that should be added to supplementary groups // in addition to those that the user belongs to. AdditionalGroups []string `json:"additional_groups"` // 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"` // SystemProperties is a map of properties and their values. It is the equivalent of using // sysctl -w my.property.name value in Linux. SystemProperties map[string]string `json:"system_properties"` // Seccomp allows actions to be taken whenever a syscall is made within the container. // By default, all syscalls are allowed with actions to allow, trap, kill, or return an errno // can be specified on a per syscall basis. Seccomp *Seccomp `json:"seccomp"` } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/config_test.go ================================================ package configs import ( "encoding/json" "fmt" "os" "path/filepath" "testing" ) // Checks whether the expected capability is specified in the capabilities. func contains(expected string, values []string) bool { for _, v := range values { if v == expected { return true } } return false } func containsDevice(expected *Device, values []*Device) bool { for _, d := range values { if d.Path == expected.Path && d.Permissions == expected.Permissions && d.FileMode == expected.FileMode && d.Major == expected.Major && d.Minor == expected.Minor && d.Type == expected.Type { return true } } return false } func loadConfig(name string) (*Config, error) { f, err := os.Open(filepath.Join("../sample_configs", name)) if err != nil { return nil, err } defer f.Close() var container *Config if err := json.NewDecoder(f).Decode(&container); err != nil { return nil, err } // Check that a config doesn't contain extra fields var configMap, abstractMap map[string]interface{} if _, err := f.Seek(0, 0); err != nil { return nil, err } if err := json.NewDecoder(f).Decode(&abstractMap); err != nil { return nil, err } configData, err := json.Marshal(&container) if err != nil { return nil, err } if err := json.Unmarshal(configData, &configMap); err != nil { return nil, err } for k := range configMap { delete(abstractMap, k) } if len(abstractMap) != 0 { return nil, fmt.Errorf("unknown fields: %s", abstractMap) } return container, nil } func TestConfigJsonFormat(t *testing.T) { container, err := loadConfig("attach_to_bridge.json") if err != nil { t.Fatal(err) } if container.Hostname != "koye" { t.Log("hostname is not set") t.Fail() } if !container.Namespaces.Contains(NEWNET) { t.Log("namespaces should contain NEWNET") t.Fail() } if container.Namespaces.Contains(NEWUSER) { t.Log("namespaces should not contain NEWUSER") t.Fail() } if contains("SYS_ADMIN", container.Capabilities) { t.Log("SYS_ADMIN should not be enabled in capabilities mask") t.Fail() } if !contains("MKNOD", container.Capabilities) { t.Log("MKNOD should be enabled in capabilities mask") t.Fail() } if !contains("SYS_CHROOT", container.Capabilities) { t.Log("capabilities mask should contain SYS_CHROOT") t.Fail() } for _, n := range container.Networks { if n.Type == "veth" { if n.Bridge != "docker0" { t.Logf("veth bridge should be docker0 but received %q", n.Bridge) t.Fail() } if n.Address != "172.17.0.101/16" { t.Logf("veth address should be 172.17.0.101/61 but received %q", n.Address) t.Fail() } if n.Gateway != "172.17.42.1" { t.Logf("veth gateway should be 172.17.42.1 but received %q", n.Gateway) t.Fail() } if n.Mtu != 1500 { t.Logf("veth mtu should be 1500 but received %d", n.Mtu) t.Fail() } break } } for _, d := range DefaultSimpleDevices { if !containsDevice(d, container.Devices) { t.Logf("expected device configuration for %s", d.Path) t.Fail() } } } func TestApparmorProfile(t *testing.T) { container, err := loadConfig("apparmor.json") if err != nil { t.Fatal(err) } if container.AppArmorProfile != "docker-default" { t.Fatalf("expected apparmor profile to be docker-default but received %q", container.AppArmorProfile) } } func TestSelinuxLabels(t *testing.T) { container, err := loadConfig("selinux.json") if err != nil { t.Fatal(err) } label := "system_u:system_r:svirt_lxc_net_t:s0:c164,c475" if container.ProcessLabel != label { t.Fatalf("expected process label %q but received %q", label, container.ProcessLabel) } if container.MountLabel != label { t.Fatalf("expected mount label %q but received %q", label, container.MountLabel) } } func TestRemoveNamespace(t *testing.T) { ns := Namespaces{ {Type: NEWNET}, } if !ns.Remove(NEWNET) { t.Fatal("NEWNET was not removed") } if len(ns) != 0 { t.Fatalf("namespaces should have 0 items but reports %d", len(ns)) } } func TestHostUIDNoUSERNS(t *testing.T) { config := &Config{ Namespaces: Namespaces{}, } uid, err := config.HostUID() if err != nil { t.Fatal(err) } if uid != 0 { t.Fatalf("expected uid 0 with no USERNS but received %d", uid) } } func TestHostUIDWithUSERNS(t *testing.T) { config := &Config{ Namespaces: Namespaces{{Type: NEWUSER}}, UidMappings: []IDMap{ { ContainerID: 0, HostID: 1000, Size: 1, }, }, } uid, err := config.HostUID() if err != nil { t.Fatal(err) } if uid != 1000 { t.Fatalf("expected uid 1000 with no USERNS but received %d", uid) } } func TestHostGIDNoUSERNS(t *testing.T) { config := &Config{ Namespaces: Namespaces{}, } uid, err := config.HostGID() if err != nil { t.Fatal(err) } if uid != 0 { t.Fatalf("expected gid 0 with no USERNS but received %d", uid) } } func TestHostGIDWithUSERNS(t *testing.T) { config := &Config{ Namespaces: Namespaces{{Type: NEWUSER}}, GidMappings: []IDMap{ { ContainerID: 0, HostID: 1000, Size: 1, }, }, } uid, err := config.HostGID() if err != nil { t.Fatal(err) } if uid != 1000 { t.Fatalf("expected gid 1000 with no USERNS but received %d", uid) } } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/config_unix.go ================================================ // +build freebsd linux package configs import "fmt" // Gets the root uid for the process on host which could be non-zero // when user namespaces are enabled. func (c Config) HostUID() (int, error) { if c.Namespaces.Contains(NEWUSER) { if c.UidMappings == nil { return -1, fmt.Errorf("User namespaces enabled, but no user mappings found.") } id, found := c.hostIDFromMapping(0, c.UidMappings) if !found { return -1, fmt.Errorf("User namespaces enabled, but no root user mapping found.") } return id, nil } // Return default root uid 0 return 0, nil } // Gets the root uid for the process on host which could be non-zero // when user namespaces are enabled. func (c Config) HostGID() (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(0, c.GidMappings) if !found { return -1, fmt.Errorf("User namespaces enabled, but no root user mapping found.") } return id, nil } // Return default root uid 0 return 0, nil } // 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/device.go ================================================ 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"` } 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) } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/device_defaults.go ================================================ // +build linux freebsd package configs var ( // These 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", }, { Path: "/dev/tty0", Type: 'c', Major: 4, Minor: 0, Permissions: "rwm", }, { Path: "/dev/tty1", Type: 'c', Major: 4, 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{ { // /dev/fuse is created but not allowed. // This is to allow java to work. Because java // Insists on there being a /dev/fuse // https://github.com/docker/docker/issues/514 // https://github.com/docker/docker/issues/2393 // Path: "/dev/fuse", Type: 'c', Major: 10, Minor: 229, Permissions: "rwm", }, }, DefaultSimpleDevices...) ) ================================================ FILE: vendor/github.com/docker/libcontainer/configs/hugepage_limit.go ================================================ package configs type HugepageLimit struct { // which type of hugepage to limit. Pagesize string `json:"page_size"` // usage limit for hugepage. Limit int `json:"limit"` } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/interface_priority_map.go ================================================ 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) } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/mount.go ================================================ package configs 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"` // Mount data applied to the mount. Data string `json:"data"` // Relabel source if set, "z" indicates shared, "Z" indicates unshared. Relabel string `json:"relabel"` // 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"` } type Command struct { Path string `json:"path"` Args []string `json:"args"` Env []string `json:"env"` Dir string `json:"dir"` } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/namespaces.go ================================================ package configs type NamespaceType string type Namespaces []Namespace ================================================ FILE: vendor/github.com/docker/libcontainer/configs/namespaces_syscall.go ================================================ // +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 functions 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) } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/namespaces_syscall_unsupported.go ================================================ // +build !linux,!windows package configs func (n *Namespace) Syscall() int { panic("No namespace syscall support") return 0 } // CloneFlags parses the container's Namespaces options to set the correct // flags on clone, unshare. This functions returns flags only for new namespaces. func (n *Namespaces) CloneFlags() uintptr { panic("No namespace syscall support") return uintptr(0) } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/namespaces_unix.go ================================================ // +build linux freebsd package configs import "fmt" const ( NEWNET NamespaceType = "NEWNET" NEWPID NamespaceType = "NEWPID" NEWNS NamespaceType = "NEWNS" NEWUTS NamespaceType = "NEWUTS" NEWIPC NamespaceType = "NEWIPC" NEWUSER NamespaceType = "NEWUSER" ) func NamespaceTypes() []NamespaceType { return []NamespaceType{ NEWNET, NEWPID, NEWNS, NEWUTS, NEWIPC, NEWUSER, } } // 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, n.file()) } func (n *Namespace) file() string { file := "" switch n.Type { case NEWNET: file = "net" case NEWNS: file = "mnt" case NEWPID: file = "pid" case NEWIPC: file = "ipc" case NEWUSER: file = "user" case NEWUTS: file = "uts" } return file } 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/namespaces_windows.go ================================================ package configs // Namespace defines configuration for each namespace. It specifies an // alternate path that is able to be joined via setns. type Namespace struct { } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/network.go ================================================ 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"` } ================================================ FILE: vendor/github.com/docker/libcontainer/configs/validate/config.go ================================================ package validate import ( "fmt" "os" "path/filepath" "github.com/docker/libcontainer/configs" ) 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 } return nil } // rootfs validates the 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 { cleaned, err := filepath.Abs(config.Rootfs) if err != nil { return err } if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil { return err } if 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") } 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/console.go ================================================ package libcontainer import "io" // Console represents a pseudo TTY. type Console interface { io.ReadWriter io.Closer // Path returns the filesystem path to the slave side of the pty. Path() string // Fd returns the fd for the master of the pty. Fd() uintptr } ================================================ FILE: vendor/github.com/docker/libcontainer/console_freebsd.go ================================================ // +build freebsd package libcontainer import ( "errors" ) // 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) (Console, error) { return nil, errors.New("libcontainer console is not supported on FreeBSD") } ================================================ FILE: vendor/github.com/docker/libcontainer/console_linux.go ================================================ package libcontainer import ( "fmt" "os" "path/filepath" "syscall" "unsafe" "github.com/docker/libcontainer/label" ) // 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) (Console, 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 &linuxConsole{ slavePath: console, master: master, }, nil } // newConsoleFromPath is an internal function returning an initialized console for use inside // a container's MNT namespace. func newConsoleFromPath(slavePath string) *linuxConsole { return &linuxConsole{ slavePath: slavePath, } } // linuxConsole is a linux psuedo TTY for use within a container. type linuxConsole struct { master *os.File slavePath string } func (c *linuxConsole) Fd() uintptr { return c.master.Fd() } 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(rootfs, mountLabel string, uid, gid int) error { oldMask := syscall.Umask(0000) defer syscall.Umask(oldMask) if err := label.SetFileLabel(c.slavePath, mountLabel); err != nil { return err } dest := filepath.Join(rootfs, "/dev/console") f, err := os.Create(dest) if err != nil && !os.IsExist(err) { return err } if f != nil { f.Close() } return syscall.Mount(c.slavePath, dest, "bind", syscall.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(syscall.O_RDWR) if err != nil { return err } fd := int(slave.Fd()) for _, i := range []int{0, 1, 2} { if err := syscall.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 := syscall.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 := 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/console_windows.go ================================================ package libcontainer // newConsole returns an initalized console that can be used within a container func newConsole(uid, gid int) (Console, error) { return &windowsConsole{}, nil } // windowsConsole is a Windows psuedo 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/container.go ================================================ // 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 ( "github.com/docker/libcontainer/configs" ) // The status of a container. type Status int const ( // The container exists and is running. Running Status = iota + 1 // The container exists, it is in the process of being paused. Pausing // The container exists, but all its processes are paused. Paused // The container exists, but its state is saved on disk Checkpointed // The container does not exist. Destroyed ) // State represents a running container's state type State 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. InitProcessStartTime string `json:"init_process_start"` // 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"` // Config is the container's configuration. Config configs.Config `json:"config"` // Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore ExternalDescriptors []string `json:"external_descriptors,omitempty"` } // 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 { // Returns the ID of the container ID() string // Returns the current status of the container. // // errors: // ContainerDestroyed - 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: // ContainerDestroyed - 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: // ContainerDestroyed - Container no longer exists, // Systemerror - System error. Stats() (*Stats, error) // Set cgroup 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: // ContainerDestroyed - Container no longer exists, // ConfigInvalid - config is invalid, // ContainerPaused - Container is paused, // Systemerror - System error. Start(process *Process) (err error) // 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) utiity. // // errors: // Systemerror - System error. Restore(process *Process, criuOpts *CriuOpts) error // Destroys the container after killing all running processes. // // Any event registrations are removed before the container is destroyed. // No error is returned if the container is already destroyed. // // errors: // Systemerror - System error. Destroy() error // If the Container state is RUNNING or PAUSING, 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: // ContainerDestroyed - Container no longer exists, // 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: // ContainerDestroyed - Container no longer exists, // 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) } ================================================ FILE: vendor/github.com/docker/libcontainer/container_linux.go ================================================ // +build linux package libcontainer import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "strings" "sync" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/criurpc" "github.com/golang/protobuf/proto" ) const stdioFdCount = 3 type linuxContainer struct { id string root string config *configs.Config cgroupManager cgroups.Manager initPath string initArgs []string initProcess parentProcess criuPath string m sync.Mutex } // 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.GetPids() if err != nil { return nil, newSystemError(err) } 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, newSystemError(err) } for _, iface := range c.config.Networks { switch iface.Type { case "veth": istats, err := getNetworkInterfaceStats(iface.HostInterfaceName) if err != nil { return stats, newSystemError(err) } stats.Interfaces = append(stats.Interfaces, istats) } } return stats, nil } func (c *linuxContainer) Set(config configs.Config) error { c.m.Lock() defer c.m.Unlock() 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 } doInit := status == Destroyed parent, err := c.newParentProcess(process, doInit) if err != nil { return newSystemError(err) } 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 newSystemError(err) } process.ops = parent if doInit { c.updateState(parent) } return nil } func (c *linuxContainer) newParentProcess(p *Process, doInit bool) (parentProcess, error) { parentPipe, childPipe, err := newPipe() if err != nil { return nil, newSystemError(err) } cmd, err := c.commandTemplate(p, childPipe) if err != nil { return nil, newSystemError(err) } if !doInit { return c.newSetnsProcess(p, cmd, parentPipe, childPipe), nil } return c.newInitProcess(p, cmd, parentPipe, childPipe) } func (c *linuxContainer) commandTemplate(p *Process, childPipe *os.File) (*exec.Cmd, error) { cmd := &exec.Cmd{ Path: c.initPath, Args: c.initArgs, } 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(p.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 *os.File) (*initProcess, error) { t := "_LIBCONTAINER_INITTYPE=standard" cloneFlags := c.config.Namespaces.CloneFlags() if cloneFlags&syscall.CLONE_NEWUSER != 0 { if err := c.addUidGidMappings(cmd.SysProcAttr); err != nil { // user mappings are not supported return nil, err } // Default to root user when user namespaces are enabled. if cmd.SysProcAttr.Credential == nil { cmd.SysProcAttr.Credential = &syscall.Credential{} } } cmd.Env = append(cmd.Env, t) cmd.SysProcAttr.Cloneflags = cloneFlags return &initProcess{ cmd: cmd, childPipe: childPipe, parentPipe: parentPipe, manager: c.cgroupManager, config: c.newInitConfig(p), }, nil } func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) *setnsProcess { cmd.Env = append(cmd.Env, fmt.Sprintf("_LIBCONTAINER_INITPID=%d", c.initProcess.pid()), "_LIBCONTAINER_INITTYPE=setns", ) if p.consolePath != "" { cmd.Env = append(cmd.Env, "_LIBCONTAINER_CONSOLE_PATH="+p.consolePath) } // TODO: set on container for process management return &setnsProcess{ cmd: cmd, cgroupPaths: c.cgroupManager.GetPaths(), childPipe: childPipe, parentPipe: parentPipe, config: c.newInitConfig(p), } } func (c *linuxContainer) newInitConfig(process *Process) *initConfig { return &initConfig{ Config: c.config, Args: process.Args, Env: process.Env, User: process.User, Cwd: process.Cwd, Console: process.consolePath, Capabilities: process.Capabilities, PassedFilesCount: len(process.ExtraFiles), } } func newPipe() (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]), "parent"), os.NewFile(uintptr(fds[0]), "child"), nil } func (c *linuxContainer) Destroy() error { c.m.Lock() defer c.m.Unlock() status, err := c.currentStatus() if err != nil { return err } if status != Destroyed { return newGenericError(fmt.Errorf("container is not destroyed"), ContainerNotStopped) } if !c.config.Namespaces.Contains(configs.NEWPID) { if err := killCgroupProcesses(c.cgroupManager); err != nil { logrus.Warn(err) } } err = c.cgroupManager.Destroy() if rerr := os.RemoveAll(c.root); err == nil { err = rerr } c.initProcess = nil return err } func (c *linuxContainer) Pause() error { c.m.Lock() defer c.m.Unlock() return c.cgroupManager.Freeze(configs.Frozen) } func (c *linuxContainer) Resume() error { c.m.Lock() defer c.m.Unlock() return c.cgroupManager.Freeze(configs.Thawed) } func (c *linuxContainer) NotifyOOM() (<-chan struct{}, error) { return notifyOnOOM(c.cgroupManager.GetPaths()) } // XXX debug support, remove when debugging done. func addArgsFromEnv(evar string, args *[]string) { if e := os.Getenv(evar); e != "" { for _, f := range strings.Fields(e) { *args = append(*args, f) } } fmt.Printf(">>> criu %v\n", *args) } func (c *linuxContainer) checkCriuVersion() error { var x, y, z int out, err := exec.Command(c.criuPath, "-V").Output() if err != nil { return err } 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) } if x*10000+y*100+z < 10502 { return fmt.Errorf("CRIU version must be 1.5.2 or higher") } return nil } const descriptors_filename = "descriptors.json" func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error { c.m.Lock() defer c.m.Unlock() if err := c.checkCriuVersion(); err != nil { return err } if criuOpts.ImagesDirectory == "" { criuOpts.ImagesDirectory = filepath.Join(c.root, "criu.image") } // 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), } // 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), } } t := criurpc.CriuReqType_DUMP req := criurpc.CriuReq{ Type: &t, Opts: &rpcOpts, } for _, m := range c.config.Mounts { if m.Device == "bind" { mountDest := m.Destination if strings.HasPrefix(mountDest, c.config.Rootfs) { mountDest = mountDest[len(c.config.Rootfs):] } extMnt := new(criurpc.ExtMountMap) extMnt.Key = proto.String(mountDest) extMnt.Val = proto.String(mountDest) req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt) } } // 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, descriptors_filename), fdsJSON, 0655) if err != nil { return err } err = c.criuSwrk(nil, &req, criuOpts) if err != nil { return err } return nil } func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error { c.m.Lock() defer c.m.Unlock() if err := c.checkCriuVersion(); 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 == "" { criuOpts.ImagesDirectory = filepath.Join(c.root, "criu.image") } 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), }, } for _, m := range c.config.Mounts { if m.Device == "bind" { mountDest := m.Destination if strings.HasPrefix(mountDest, c.config.Rootfs) { mountDest = mountDest[len(c.config.Rootfs):] } extMnt := new(criurpc.ExtMountMap) extMnt.Key = proto.String(mountDest) extMnt.Val = proto.String(m.Source) req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt) } } 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 } } var ( fds []string fdJSON []byte ) if fdJSON, err = ioutil.ReadFile(filepath.Join(criuOpts.ImagesDirectory, descriptors_filename)); 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) } } err = c.criuSwrk(process, &req, criuOpts) if err != nil { return err } return nil } func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts *CriuOpts) error { fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_SEQPACKET|syscall.SOCK_CLOEXEC, 0) if err != nil { return err } 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"} 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 } }() var extFds []string if process != nil { extFds, err = getPipeFds(cmd.Process.Pid) if err != nil { return err } } 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() { return fmt.Errorf("criu failed: type %s errno %d", req.GetType().String(), resp.GetCrErrno()) } t := resp.GetType() switch { 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 } n, err = criuClient.Write(data) if err != nil { return err } continue case t == criurpc.CriuReqType_RESTORE: case t == criurpc.CriuReqType_DUMP: break 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", st.String()) } 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": if !opts.LeaveRunning { f, err := os.Create(filepath.Join(c.root, "checkpoint")) if err != nil { return err } f.Close() } break case notify.GetScript() == "network-unlock": if err := unlockNetwork(c.config); err != nil { return err } break case notify.GetScript() == "network-lock": if err := lockNetwork(c.config); err != nil { return err } break case notify.GetScript() == "post-restore": pid := notify.GetPid() r, err := newRestoredProcess(int(pid), fds) if err != nil { return err } // TODO: crosbymichael restore previous process information by saving the init process information in // the container's state file or separate process state files. if err := c.updateState(r); err != nil { return err } process.ops = r break } return nil } func (c *linuxContainer) updateState(process parentProcess) error { c.initProcess = process state, err := c.currentState() if err != nil { return err } f, err := os.Create(filepath.Join(c.root, stateFilename)) if err != nil { return err } defer f.Close() os.Remove(filepath.Join(c.root, "checkpoint")) return json.NewEncoder(f).Encode(state) } func (c *linuxContainer) currentStatus() (Status, error) { if _, err := os.Stat(filepath.Join(c.root, "checkpoint")); err == nil { return Checkpointed, nil } if c.initProcess == nil { return Destroyed, nil } // return Running if the init process is alive if err := syscall.Kill(c.initProcess.pid(), 0); err != nil { if err == syscall.ESRCH { return Destroyed, nil } return 0, newSystemError(err) } if c.config.Cgroups != nil && c.config.Cgroups.Freezer == configs.Frozen { return Paused, nil } return Running, nil } func (c *linuxContainer) currentState() (*State, error) { status, err := c.currentStatus() if err != nil { return nil, err } if status == Destroyed { return nil, newGenericError(fmt.Errorf("container destroyed"), ContainerNotExists) } startTime, err := c.initProcess.startTime() if err != nil { return nil, newSystemError(err) } state := &State{ ID: c.ID(), Config: *c.config, InitProcessPid: c.initProcess.pid(), InitProcessStartTime: startTime, CgroupPaths: c.cgroupManager.GetPaths(), NamespacePaths: make(map[configs.NamespaceType]string), ExternalDescriptors: c.initProcess.externalDescriptors(), } for _, ns := range c.config.Namespaces { state.NamespacePaths[ns.Type] = ns.GetPath(c.initProcess.pid()) } for _, nsType := range configs.NamespaceTypes() { if _, ok := state.NamespacePaths[nsType]; !ok { ns := configs.Namespace{Type: nsType} state.NamespacePaths[ns.Type] = ns.GetPath(c.initProcess.pid()) } } return state, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/container_linux_test.go ================================================ // +build linux package libcontainer import ( "fmt" "os" "testing" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" ) type mockCgroupManager struct { pids []int stats *cgroups.Stats paths map[string]string } func (m *mockCgroupManager) GetPids() ([]int, error) { return m.pids, nil } func (m *mockCgroupManager) GetStats() (*cgroups.Stats, error) { return m.stats, nil } func (m *mockCgroupManager) Apply(pid int) error { return nil } func (m *mockCgroupManager) Set(container *configs.Config) error { return nil } func (m *mockCgroupManager) Destroy() error { return nil } func (m *mockCgroupManager) GetPaths() map[string]string { return m.paths } func (m *mockCgroupManager) Freeze(state configs.FreezerState) error { return nil } type mockProcess struct { _pid int started string } func (m *mockProcess) terminate() error { return nil } func (m *mockProcess) pid() int { return m._pid } func (m *mockProcess) startTime() (string, error) { return m.started, nil } func (m *mockProcess) start() error { return nil } func (m *mockProcess) wait() (*os.ProcessState, error) { return nil, nil } func (m *mockProcess) signal(_ os.Signal) error { return nil } func (p *mockProcess) externalDescriptors() []string { return []string{} } func (p *mockProcess) setExternalDescriptors(newFds []string) { } func TestGetContainerPids(t *testing.T) { container := &linuxContainer{ id: "myid", config: &configs.Config{}, cgroupManager: &mockCgroupManager{pids: []int{1, 2, 3}}, } pids, err := container.Processes() if err != nil { t.Fatal(err) } for i, expected := range []int{1, 2, 3} { if pids[i] != expected { t.Fatalf("expected pid %d but received %d", expected, pids[i]) } } } func TestGetContainerStats(t *testing.T) { container := &linuxContainer{ id: "myid", config: &configs.Config{}, cgroupManager: &mockCgroupManager{ pids: []int{1, 2, 3}, stats: &cgroups.Stats{ MemoryStats: cgroups.MemoryStats{ Usage: cgroups.MemoryData{ Usage: 1024, }, }, }, }, } stats, err := container.Stats() if err != nil { t.Fatal(err) } if stats.CgroupStats == nil { t.Fatal("cgroup stats are nil") } if stats.CgroupStats.MemoryStats.Usage.Usage != 1024 { t.Fatalf("expected memory usage 1024 but recevied %d", stats.CgroupStats.MemoryStats.Usage.Usage) } } func TestGetContainerState(t *testing.T) { var ( pid = os.Getpid() expectedMemoryPath = "/sys/fs/cgroup/memory/myid" expectedNetworkPath = "/networks/fd" ) container := &linuxContainer{ id: "myid", config: &configs.Config{ Namespaces: []configs.Namespace{ {Type: configs.NEWPID}, {Type: configs.NEWNS}, {Type: configs.NEWNET, Path: expectedNetworkPath}, {Type: configs.NEWUTS}, // emulate host for IPC //{Type: configs.NEWIPC}, }, }, initProcess: &mockProcess{ _pid: pid, started: "010", }, cgroupManager: &mockCgroupManager{ pids: []int{1, 2, 3}, stats: &cgroups.Stats{ MemoryStats: cgroups.MemoryStats{ Usage: cgroups.MemoryData{ Usage: 1024, }, }, }, paths: map[string]string{ "memory": expectedMemoryPath, }, }, } state, err := container.State() if err != nil { t.Fatal(err) } if state.InitProcessPid != pid { t.Fatalf("expected pid %d but received %d", pid, state.InitProcessPid) } if state.InitProcessStartTime != "010" { t.Fatalf("expected process start time 010 but received %s", state.InitProcessStartTime) } paths := state.CgroupPaths if paths == nil { t.Fatal("cgroup paths should not be nil") } if memPath := paths["memory"]; memPath != expectedMemoryPath { t.Fatalf("expected memory path %q but received %q", expectedMemoryPath, memPath) } for _, ns := range container.config.Namespaces { path := state.NamespacePaths[ns.Type] if path == "" { t.Fatalf("expected non nil namespace path for %s", ns.Type) } if ns.Type == configs.NEWNET { if path != expectedNetworkPath { t.Fatalf("expected path %q but received %q", expectedNetworkPath, path) } } else { file := "" switch ns.Type { case configs.NEWNET: file = "net" case configs.NEWNS: file = "mnt" case configs.NEWPID: file = "pid" case configs.NEWIPC: file = "ipc" case configs.NEWUSER: file = "user" case configs.NEWUTS: file = "uts" } expected := fmt.Sprintf("/proc/%d/ns/%s", pid, file) if expected != path { t.Fatalf("expected path %q but received %q", expected, path) } } } } ================================================ FILE: vendor/github.com/docker/libcontainer/container_nouserns_linux.go ================================================ // +build !go1.4 package libcontainer import ( "fmt" "syscall" ) // not available before go 1.4 func (c *linuxContainer) addUidGidMappings(sys *syscall.SysProcAttr) error { return fmt.Errorf("User namespace is not supported in golang < 1.4") } ================================================ FILE: vendor/github.com/docker/libcontainer/container_userns_linux.go ================================================ // +build go1.4 package libcontainer import "syscall" // Converts IDMap to SysProcIDMap array and adds it to SysProcAttr. func (c *linuxContainer) addUidGidMappings(sys *syscall.SysProcAttr) error { if c.config.UidMappings != nil { sys.UidMappings = make([]syscall.SysProcIDMap, len(c.config.UidMappings)) for i, um := range c.config.UidMappings { sys.UidMappings[i].ContainerID = um.ContainerID sys.UidMappings[i].HostID = um.HostID sys.UidMappings[i].Size = um.Size } } if c.config.GidMappings != nil { sys.GidMappings = make([]syscall.SysProcIDMap, len(c.config.GidMappings)) for i, gm := range c.config.GidMappings { sys.GidMappings[i].ContainerID = gm.ContainerID sys.GidMappings[i].HostID = gm.HostID sys.GidMappings[i].Size = gm.Size } } return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/criu_opts.go ================================================ package libcontainer type CriuPageServerInfo struct { Address string // IP address of CRIU page server Port int32 // port number of CRIU page server } type CriuOpts struct { ImagesDirectory string // directory for storing image files WorkDirectory string // directory to cd and write logs/pidfiles/stats to 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 PageServer CriuPageServerInfo // allow to dump to criu page server } ================================================ FILE: vendor/github.com/docker/libcontainer/criurpc/Makefile ================================================ gen: criurpc.proto protoc --go_out=. criurpc.proto ================================================ FILE: vendor/github.com/docker/libcontainer/criurpc/criurpc.pb.go ================================================ // Code generated by protoc-gen-go. // source: criurpc.proto // DO NOT EDIT! package criurpc import proto "github.com/golang/protobuf/proto" import json "encoding/json" import math "math" // Reference proto, json, and math imports to suppress error if they are not otherwise used. var _ = proto.Marshal var _ = &json.SyntaxError{} var _ = math.Inf 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 ) 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", } 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, } 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) MarshalJSON() ([]byte, error) { return json.Marshal(x.String()) } 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 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"` 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 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 } 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 } 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"` 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 0 } 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 } 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"` 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 0 } 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 init() { proto.RegisterEnum("CriuReqType", CriuReqType_name, CriuReqType_value) } ================================================ FILE: vendor/github.com/docker/libcontainer/criurpc/criurpc.proto ================================================ 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 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; repeated cgroup_root cg_root = 25; optional bool rst_sibling = 26; /* swrk only */ repeated inherit_fd inherit_fd = 27; } 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; } /* * 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; } /* * Responce -- it states whether the request was served * and additional request-specific informarion */ 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; } ================================================ FILE: vendor/github.com/docker/libcontainer/devices/devices_test.go ================================================ package devices import ( "errors" "os" "testing" ) func TestDeviceFromPathLstatFailure(t *testing.T) { testError := errors.New("test error") // Override os.Lstat to inject error. osLstat = func(path string) (os.FileInfo, error) { return nil, testError } _, err := DeviceFromPath("", "") if err != testError { t.Fatalf("Unexpected error %v, expected %v", err, testError) } } func TestHostDevicesIoutilReadDirFailure(t *testing.T) { testError := errors.New("test error") // Override ioutil.ReadDir to inject error. ioutilReadDir = func(dirname string) ([]os.FileInfo, error) { return nil, testError } _, err := HostDevices() if err != testError { t.Fatalf("Unexpected error %v, expected %v", err, testError) } } func TestHostDevicesIoutilReadDirDeepFailure(t *testing.T) { testError := errors.New("test error") called := false // Override ioutil.ReadDir to inject error after the first call. ioutilReadDir = func(dirname string) ([]os.FileInfo, error) { if called { return nil, testError } called = true // Provoke a second call. fi, err := os.Lstat("/tmp") if err != nil { t.Fatalf("Unexpected error %v", err) } return []os.FileInfo{fi}, nil } _, err := HostDevices() if err != testError { t.Fatalf("Unexpected error %v, expected %v", err, testError) } } ================================================ FILE: vendor/github.com/docker/libcontainer/devices/devices_unix.go ================================================ // +build linux freebsd package devices import ( "errors" "fmt" "io/ioutil" "os" "path/filepath" "syscall" "github.com/docker/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 it's 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() { case "pts", "shm", "fd", "mqueue": 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 } return nil, err } out = append(out, device) } return out, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/devices/devices_windows.go ================================================ package devices import ( "github.com/docker/libcontainer/configs" ) // TODO Windows. This can be factored out further - Devices are not supported // by Windows Containers. func DeviceFromPath(path, permissions string) (*configs.Device, error) { return nil, nil } func HostDevices() ([]*configs.Device, error) { return nil, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/devices/number.go ================================================ // +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 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)) } ================================================ FILE: vendor/github.com/docker/libcontainer/docs/man/nsinit.1.md ================================================ % nsinit User Manual % docker/libcontainer % JAN 2015 NAME: nsinit - A low-level utility for managing containers. It is used to spawn new containers or join existing containers. USAGE: nsinit [global options] command [command options] [arguments...] VERSION: 0.1 COMMANDS: config display the container configuration exec execute a new command inside a container init runs the init process inside the namespace oom display oom notifications for a container pause pause the container's processes stats display statistics for the container unpause unpause the container's processes help, h shows a list of commands or help for one command EXAMPLES: Get the of an already running docker container. `sudo docker ps` will return the list of all the running containers. take the (e.g. 4addb0b2d307) and go to its config directory `/var/lib/docker/execdriver/native/4addb0b2d307` and here you can run the nsinit command line utility. e.g. `nsinit exec /bin/bash` will start a shell on the already running container. # HISTORY Jan 2015, Originally compiled by Shishir Mahajan (shishir dot mahajan at redhat dot com) based on nsinit source material and internal work. ================================================ FILE: vendor/github.com/docker/libcontainer/error.go ================================================ package libcontainer import "io" // API error code type. type ErrorCode int // API error codes. const ( // Factory errors IdInUse ErrorCode = iota InvalidIdFormat // Container errors ContainerNotExists ContainerPaused ContainerNotStopped ContainerNotRunning // Process errors ProcessNotExecuted // Common errors ConfigInvalid 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" default: return "Unknown error" } } // API Error type. type Error interface { error // Returns a verbose string including the error message // and a representation of the stack trace suitable for // printing. Detail(w io.Writer) error // Returns the error code for this error. Code() ErrorCode } ================================================ FILE: vendor/github.com/docker/libcontainer/error_test.go ================================================ package libcontainer import "testing" func TestErrorCode(t *testing.T) { codes := map[ErrorCode]string{ IdInUse: "Id already in use", InvalidIdFormat: "Invalid format", ContainerPaused: "Container paused", ConfigInvalid: "Invalid configuration", SystemError: "System error", ContainerNotExists: "Container does not exist", } for code, expected := range codes { if actual := code.String(); actual != expected { t.Fatalf("expected string %q but received %q", expected, actual) } } } ================================================ FILE: vendor/github.com/docker/libcontainer/factory.go ================================================ package libcontainer import ( "github.com/docker/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 file system) 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 // Container is stopped // 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/factory_linux.go ================================================ // +build linux package libcontainer import ( "encoding/json" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "regexp" "strconv" "syscall" "github.com/docker/docker/pkg/mount" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/cgroups/fs" "github.com/docker/libcontainer/cgroups/systemd" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/configs/validate" ) const ( stateFilename = "state.json" ) var ( idRegex = regexp.MustCompile(`^[\w_]+$`) maxIdLen = 1024 ) // InitArgs returns an options func to configure a LinuxFactory with the // provided init arguments. func InitArgs(args ...string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { name := args[0] if filepath.Base(name) == name { if lp, err := exec.LookPath(name); err == nil { name = lp } } l.InitPath = name l.InitArgs = append([]string{name}, args[1:]...) return nil } } // InitPath returns an options func to configure a LinuxFactory with the // provided absolute path to the init binary and arguements. func InitPath(path string, args ...string) func(*LinuxFactory) error { return func(l *LinuxFactory) error { l.InitPath = path 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 } // 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 } // 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, Validator: validate.New(), CriuPath: "criu", } InitArgs(os.Args[0], "init")(l) 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 absolute path to the init binary. 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) } 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, 0700); err != nil { return nil, newGenericError(err, SystemError) } return &linuxContainer{ id: id, root: containerRoot, config: config, initPath: l.InitPath, initArgs: l.InitArgs, criuPath: l.CriuPath, cgroupManager: l.NewCgroupsManager(config.Cgroups, nil), }, 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) if err != nil { return nil, err } r := &nonChildProcess{ processPid: state.InitProcessPid, processStartTime: state.InitProcessStartTime, fds: state.ExternalDescriptors, } return &linuxContainer{ initProcess: r, id: id, config: &state.Config, initPath: l.InitPath, initArgs: l.InitArgs, criuPath: l.CriuPath, cgroupManager: l.NewCgroupsManager(state.Config.Cgroups, state.CgroupPaths), root: containerRoot, }, 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) { pipefd, err := strconv.Atoi(os.Getenv("_LIBCONTAINER_INITPIPE")) if err != nil { return err } var ( pipe = os.NewFile(uintptr(pipefd), "pipe") it = initType(os.Getenv("_LIBCONTAINER_INITTYPE")) ) // clear the current process's environment to clean any libcontainer // specific env vars. os.Clearenv() defer func() { // if we have an error during the initialization of the container's init then send it back to the // parent process in the form of an initError. if err != nil { // ensure that any data sent from the parent is consumed so it doesn't // receive ECONNRESET when the child writes to the pipe. ioutil.ReadAll(pipe) if err := json.NewEncoder(pipe).Encode(newSystemError(err)); err != nil { panic(err) } } // ensure that this pipe is always closed pipe.Close() }() i, err := newContainerInit(it, pipe) if err != nil { return err } return i.Init() } func (l *LinuxFactory) loadState(root string) (*State, error) { f, err := os.Open(filepath.Join(root, stateFilename)) if err != nil { if os.IsNotExist(err) { return nil, newGenericError(err, 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/factory_linux_test.go ================================================ // +build linux package libcontainer import ( "encoding/json" "io/ioutil" "os" "path/filepath" "testing" "github.com/docker/docker/pkg/mount" "github.com/docker/libcontainer/configs" ) func newTestRoot() (string, error) { dir, err := ioutil.TempDir("", "libcontainer") if err != nil { return "", err } return dir, nil } func TestFactoryNew(t *testing.T) { root, rerr := newTestRoot() if rerr != nil { t.Fatal(rerr) } defer os.RemoveAll(root) factory, err := New(root, Cgroupfs) if err != nil { t.Fatal(err) } if factory == nil { t.Fatal("factory should not be nil") } lfactory, ok := factory.(*LinuxFactory) if !ok { t.Fatal("expected linux factory returned on linux based systems") } if lfactory.Root != root { t.Fatalf("expected factory root to be %q but received %q", root, lfactory.Root) } if factory.Type() != "libcontainer" { t.Fatalf("unexpected factory type: %q, expected %q", factory.Type(), "libcontainer") } } func TestFactoryNewTmpfs(t *testing.T) { root, rerr := newTestRoot() if rerr != nil { t.Fatal(rerr) } defer os.RemoveAll(root) factory, err := New(root, Cgroupfs, TmpfsRoot) if err != nil { t.Fatal(err) } if factory == nil { t.Fatal("factory should not be nil") } lfactory, ok := factory.(*LinuxFactory) if !ok { t.Fatal("expected linux factory returned on linux based systems") } if lfactory.Root != root { t.Fatalf("expected factory root to be %q but received %q", root, lfactory.Root) } if factory.Type() != "libcontainer" { t.Fatalf("unexpected factory type: %q, expected %q", factory.Type(), "libcontainer") } mounted, err := mount.Mounted(lfactory.Root) if err != nil { t.Fatal(err) } if !mounted { t.Fatalf("Factory Root is not mounted") } mounts, err := mount.GetMounts() if err != nil { t.Fatal(err) } var found bool for _, m := range mounts { if m.Mountpoint == lfactory.Root { if m.Fstype != "tmpfs" { t.Fatalf("Fstype of root: %s, expected %s", m.Fstype, "tmpfs") } if m.Source != "tmpfs" { t.Fatalf("Source of root: %s, expected %s", m.Source, "tmpfs") } found = true } } if !found { t.Fatalf("Factory Root is not listed in mounts list") } } func TestFactoryLoadNotExists(t *testing.T) { root, rerr := newTestRoot() if rerr != nil { t.Fatal(rerr) } defer os.RemoveAll(root) factory, err := New(root, Cgroupfs) if err != nil { t.Fatal(err) } _, err = factory.Load("nocontainer") if err == nil { t.Fatal("expected nil error loading non-existing container") } lerr, ok := err.(Error) if !ok { t.Fatal("expected libcontainer error type") } if lerr.Code() != ContainerNotExists { t.Fatalf("expected error code %s but received %s", ContainerNotExists, lerr.Code()) } } func TestFactoryLoadContainer(t *testing.T) { root, err := newTestRoot() if err != nil { t.Fatal(err) } defer os.RemoveAll(root) // setup default container config and state for mocking var ( id = "1" expectedConfig = &configs.Config{ Rootfs: "/mycontainer/root", } expectedState = &State{ InitProcessPid: 1024, Config: *expectedConfig, } ) if err := os.Mkdir(filepath.Join(root, id), 0700); err != nil { t.Fatal(err) } if err := marshal(filepath.Join(root, id, stateFilename), expectedState); err != nil { t.Fatal(err) } factory, err := New(root, Cgroupfs) if err != nil { t.Fatal(err) } container, err := factory.Load(id) if err != nil { t.Fatal(err) } if container.ID() != id { t.Fatalf("expected container id %q but received %q", id, container.ID()) } config := container.Config() if config.Rootfs != expectedConfig.Rootfs { t.Fatalf("expected rootfs %q but received %q", expectedConfig.Rootfs, config.Rootfs) } lcontainer, ok := container.(*linuxContainer) if !ok { t.Fatal("expected linux container on linux based systems") } if lcontainer.initProcess.pid() != expectedState.InitProcessPid { t.Fatalf("expected init pid %d but received %d", expectedState.InitProcessPid, lcontainer.initProcess.pid()) } } func marshal(path string, v interface{}) error { f, err := os.Create(path) if err != nil { return err } defer f.Close() return json.NewEncoder(f).Encode(v) } ================================================ FILE: vendor/github.com/docker/libcontainer/generic_error.go ================================================ package libcontainer import ( "fmt" "io" "text/template" "time" "github.com/docker/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 { if le, ok := err.(Error); ok { return le } gerr := &genericError{ Timestamp: time.Now(), Err: err, ECode: SystemError, Stack: stacktrace.Capture(1), } if err != nil { gerr.Message = err.Error() } return gerr } type genericError struct { Timestamp time.Time ECode ErrorCode Err error `json:"-"` Message string Stack stacktrace.Stacktrace } func (e *genericError) Error() string { return fmt.Sprintf("[%d] %s: %s", e.ECode, e.ECode, e.Message) } func (e *genericError) Code() ErrorCode { return e.ECode } func (e *genericError) Detail(w io.Writer) error { return errorTemplate.Execute(w, e) } ================================================ FILE: vendor/github.com/docker/libcontainer/generic_error_test.go ================================================ package libcontainer import ( "fmt" "io/ioutil" "testing" ) func TestErrorDetail(t *testing.T) { err := newGenericError(fmt.Errorf("test error"), SystemError) if derr := err.Detail(ioutil.Discard); derr != nil { t.Fatal(derr) } } ================================================ FILE: vendor/github.com/docker/libcontainer/hack/validate.sh ================================================ #!/usr/bin/env bash set -e # This script runs all validations validate() { export MAKEDIR=/go/src/github.com/docker/docker/hack/make sed -i 's!docker/docker!docker/libcontainer!' /go/src/github.com/docker/docker/hack/make/.validate bash /go/src/github.com/docker/docker/hack/make/validate-dco bash /go/src/github.com/docker/docker/hack/make/validate-gofmt go get golang.org/x/tools/cmd/vet go vet github.com/docker/libcontainer/... } # run validations validate ================================================ FILE: vendor/github.com/docker/libcontainer/init_linux.go ================================================ // +build linux package libcontainer import ( "encoding/json" "fmt" "os" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/netlink" "github.com/docker/libcontainer/seccomp" "github.com/docker/libcontainer/system" "github.com/docker/libcontainer/user" "github.com/docker/libcontainer/utils" ) 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 tempory 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 []string `json:"capabilities"` User string `json:"user"` Config *configs.Config `json:"config"` Console string `json:"console"` Networks []*network `json:"network"` PassedFilesCount int `json:"passed_files_count"` } type initer interface { Init() error } func newContainerInit(t initType, pipe *os.File) (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{ config: config, }, nil case initStandard: return &linuxStandardInit{ parentPid: syscall.Getppid(), config: config, }, 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 := config.Config.Capabilities if config.Capabilities != nil { capabilities = config.Capabilities } w, err := newCapWhitelist(capabilities) if err != nil { return err } // drop capabilities in bounding set before changing user if err := w.dropBoundingSet(); 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 } // drop all other capabilities if err := w.drop(); err != nil { return err } if config.Cwd != "" { if err := syscall.Chdir(config.Cwd); err != nil { return err } } return nil } // joinExistingNamespaces gets all the namespace paths specified for the container and // does a setns on the namespace fd so that the current process joins the namespace. func joinExistingNamespaces(namespaces []configs.Namespace) error { for _, ns := range namespaces { if ns.Path != "" { f, err := os.OpenFile(ns.Path, os.O_RDONLY, 0) if err != nil { return err } err = system.Setns(f.Fd(), uintptr(ns.Syscall())) f.Close() if 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: syscall.Getuid(), Gid: syscall.Getgid(), 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.Config.AdditionalGroups) > 0 { addGroups, err = user.GetAdditionalGroupsPath(config.Config.AdditionalGroups, groupPath) if err != nil { return err } } 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 } // 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 { if err := netlink.AddRoute(config.Destination, config.Source, config.Gateway, config.InterfaceName); err != nil { return err } } return nil } func setupRlimits(config *configs.Config) error { for _, rlimit := range config.Rlimits { l := &syscall.Rlimit{Max: rlimit.Hard, Cur: rlimit.Soft} if err := syscall.Setrlimit(rlimit.Type, l); err != nil { return fmt.Errorf("error setting rlimit type %v: %v", rlimit.Type, err) } } return nil } // killCgroupProcesses freezes then iterates over all the processes inside the // manager's cgroups sending a SIGKILL to each process then waiting for them to // exit. func killCgroupProcesses(m cgroups.Manager) error { var procs []*os.Process if err := m.Freeze(configs.Frozen); err != nil { logrus.Warn(err) } pids, err := m.GetPids() if err != nil { m.Freeze(configs.Thawed) return err } for _, pid := range pids { if p, err := os.FindProcess(pid); err == nil { procs = append(procs, p) if err := p.Kill(); err != nil { logrus.Warn(err) } } } if err := m.Freeze(configs.Thawed); err != nil { logrus.Warn(err) } for _, p := range procs { if _, err := p.Wait(); err != nil { logrus.Warn(err) } } return nil } func finalizeSeccomp(config *initConfig) error { if config.Config.Seccomp == nil { return nil } context := seccomp.New() for _, s := range config.Config.Seccomp.Syscalls { ss := &seccomp.Syscall{ Value: uint32(s.Value), Action: seccompAction(s.Action), } if len(s.Args) > 0 { ss.Args = seccompArgs(s.Args) } context.Add(ss) } return context.Load() } func seccompAction(a configs.Action) seccomp.Action { switch a { case configs.Kill: return seccomp.Kill case configs.Trap: return seccomp.Trap case configs.Allow: return seccomp.Allow } return seccomp.Error(syscall.Errno(int(a))) } func seccompArgs(args []*configs.Arg) seccomp.Args { var sa []seccomp.Arg for _, a := range args { sa = append(sa, seccomp.Arg{ Index: uint32(a.Index), Op: seccompOperator(a.Op), Value: uint(a.Value), }) } return seccomp.Args{sa} } func seccompOperator(o configs.Operator) seccomp.Operator { switch o { case configs.EqualTo: return seccomp.EqualTo case configs.NotEqualTo: return seccomp.NotEqualTo case configs.GreatherThan: return seccomp.GreatherThan case configs.LessThan: return seccomp.LessThan case configs.MaskEqualTo: return seccomp.MaskEqualTo } return 0 } ================================================ FILE: vendor/github.com/docker/libcontainer/integration/checkpoint_test.go ================================================ package integration import ( "bytes" "io/ioutil" "os" "strings" "testing" "github.com/docker/libcontainer" ) func TestCheckpoint(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() if err != nil { t.Fatal(err) } defer os.RemoveAll(root) rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) config := newTemplateConfig(rootfs) factory, err := libcontainer.New(root, libcontainer.Cgroupfs) if err != nil { t.Fatal(err) } container, err := factory.Create("test", config) if err != nil { t.Fatal(err) } defer container.Destroy() stdinR, stdinW, err := os.Pipe() if err != nil { t.Fatal(err) } var stdout bytes.Buffer pconfig := libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, Stdout: &stdout, } err = container.Start(&pconfig) stdinR.Close() defer stdinW.Close() if err != nil { t.Fatal(err) } pid, err := pconfig.Pid() if err != nil { t.Fatal(err) } process, err := os.FindProcess(pid) if err != nil { t.Fatal(err) } imagesDir, err := ioutil.TempDir("", "criu") if err != nil { t.Fatal(err) } defer os.RemoveAll(imagesDir) checkpointOpts := &libcontainer.CriuOpts{ ImagesDirectory: imagesDir, WorkDirectory: imagesDir, } if err := container.Checkpoint(checkpointOpts); err != nil { t.Fatal(err) } state, err := container.Status() if err != nil { t.Fatal(err) } if state != libcontainer.Checkpointed { t.Fatal("Unexpected state: ", state) } stdinW.Close() _, err = process.Wait() if err != nil { t.Fatal(err) } // reload the container container, err = factory.Load("test") if err != nil { t.Fatal(err) } restoreStdinR, restoreStdinW, err := os.Pipe() if err != nil { t.Fatal(err) } restoreProcessConfig := &libcontainer.Process{ Stdin: restoreStdinR, Stdout: &stdout, } err = container.Restore(restoreProcessConfig, &libcontainer.CriuOpts{ ImagesDirectory: imagesDir, }) restoreStdinR.Close() defer restoreStdinW.Close() state, err = container.Status() if err != nil { t.Fatal(err) } if state != libcontainer.Running { t.Fatal("Unexpected state: ", state) } pid, err = restoreProcessConfig.Pid() if err != nil { t.Fatal(err) } process, err = os.FindProcess(pid) if err != nil { t.Fatal(err) } _, err = restoreStdinW.WriteString("Hello!") if err != nil { t.Fatal(err) } restoreStdinW.Close() s, err := process.Wait() if err != nil { t.Fatal(err) } if !s.Success() { t.Fatal(s.String(), pid) } output := string(stdout.Bytes()) if !strings.Contains(output, "Hello!") { t.Fatal("Did not restore the pipe correctly:", output) } } ================================================ FILE: vendor/github.com/docker/libcontainer/integration/doc.go ================================================ // integration is used for integration testing of libcontainer package integration ================================================ FILE: vendor/github.com/docker/libcontainer/integration/exec_test.go ================================================ package integration import ( "bytes" "io/ioutil" "os" "path/filepath" "strconv" "strings" "syscall" "testing" "github.com/docker/libcontainer" "github.com/docker/libcontainer/cgroups/systemd" "github.com/docker/libcontainer/configs" ) func TestExecPS(t *testing.T) { testExecPS(t, false) } func TestUsernsExecPS(t *testing.T) { if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) { t.Skip("userns is unsupported") } testExecPS(t, true) } func testExecPS(t *testing.T, userns bool) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) if userns { config.UidMappings = []configs.IDMap{{0, 0, 1000}} config.GidMappings = []configs.IDMap{{0, 0, 1000}} config.Namespaces = append(config.Namespaces, configs.Namespace{Type: configs.NEWUSER}) } buffers, exitCode, err := runContainer(config, "", "ps") if err != nil { t.Fatalf("%s: %s", buffers, err) } if exitCode != 0 { t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) } lines := strings.Split(buffers.Stdout.String(), "\n") if len(lines) < 2 { t.Fatalf("more than one process running for output %q", buffers.Stdout.String()) } expected := `1 root ps` actual := strings.Trim(lines[1], "\n ") if actual != expected { t.Fatalf("expected output %q but received %q", expected, actual) } } func TestIPCPrivate(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) l, err := os.Readlink("/proc/1/ns/ipc") ok(t, err) config := newTemplateConfig(rootfs) buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc") ok(t, err) if exitCode != 0 { t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) } if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual == l { t.Fatalf("ipc link should be private to the container but equals host %q %q", actual, l) } } func TestIPCHost(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) l, err := os.Readlink("/proc/1/ns/ipc") ok(t, err) config := newTemplateConfig(rootfs) config.Namespaces.Remove(configs.NEWIPC) buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc") ok(t, err) if exitCode != 0 { t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) } if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l { t.Fatalf("ipc link not equal to host link %q %q", actual, l) } } func TestIPCJoinPath(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) l, err := os.Readlink("/proc/1/ns/ipc") ok(t, err) config := newTemplateConfig(rootfs) config.Namespaces.Add(configs.NEWIPC, "/proc/1/ns/ipc") buffers, exitCode, err := runContainer(config, "", "readlink", "/proc/self/ns/ipc") ok(t, err) if exitCode != 0 { t.Fatalf("exit code not 0. code %d stderr %q", exitCode, buffers.Stderr) } if actual := strings.Trim(buffers.Stdout.String(), "\n"); actual != l { t.Fatalf("ipc link not equal to host link %q %q", actual, l) } } func TestIPCBadPath(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) config.Namespaces.Add(configs.NEWIPC, "/proc/1/ns/ipcc") _, _, err = runContainer(config, "", "true") if err == nil { t.Fatal("container succeeded with bad ipc path") } } func TestRlimit(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) out, _, err := runContainer(config, "", "/bin/sh", "-c", "ulimit -n") ok(t, err) if limit := strings.TrimSpace(out.Stdout.String()); limit != "1025" { t.Fatalf("expected rlimit to be 1025, got %s", limit) } } func newTestRoot() (string, error) { dir, err := ioutil.TempDir("", "libcontainer") if err != nil { return "", err } if err := os.MkdirAll(dir, 0700); err != nil { return "", err } return dir, nil } func TestEnter(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() ok(t, err) defer os.RemoveAll(root) rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := factory.Create("test", config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) var stdout, stdout2 bytes.Buffer pconfig := libcontainer.Process{ Args: []string{"sh", "-c", "cat && readlink /proc/self/ns/pid"}, Env: standardEnvironment, Stdin: stdinR, Stdout: &stdout, } err = container.Start(&pconfig) stdinR.Close() defer stdinW.Close() ok(t, err) pid, err := pconfig.Pid() ok(t, err) // Execute another process in the container stdinR2, stdinW2, err := os.Pipe() ok(t, err) pconfig2 := libcontainer.Process{ Env: standardEnvironment, } pconfig2.Args = []string{"sh", "-c", "cat && readlink /proc/self/ns/pid"} pconfig2.Stdin = stdinR2 pconfig2.Stdout = &stdout2 err = container.Start(&pconfig2) stdinR2.Close() defer stdinW2.Close() ok(t, err) pid2, err := pconfig2.Pid() ok(t, err) processes, err := container.Processes() ok(t, err) n := 0 for i := range processes { if processes[i] == pid || processes[i] == pid2 { n++ } } if n != 2 { t.Fatal("unexpected number of processes", processes, pid, pid2) } // Wait processes stdinW2.Close() waitProcess(&pconfig2, t) stdinW.Close() waitProcess(&pconfig, t) // Check that both processes live in the same pidns pidns := string(stdout.Bytes()) ok(t, err) pidns2 := string(stdout2.Bytes()) ok(t, err) if pidns != pidns2 { t.Fatal("The second process isn't in the required pid namespace", pidns, pidns2) } } func TestProcessEnv(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() ok(t, err) defer os.RemoveAll(root) rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := factory.Create("test", config) ok(t, err) defer container.Destroy() var stdout bytes.Buffer pconfig := libcontainer.Process{ Args: []string{"sh", "-c", "env"}, Env: []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOSTNAME=integration", "TERM=xterm", "FOO=BAR", }, Stdin: nil, Stdout: &stdout, } err = container.Start(&pconfig) ok(t, err) // Wait for process waitProcess(&pconfig, t) outputEnv := string(stdout.Bytes()) // Check that the environment has the key/value pair we added if !strings.Contains(outputEnv, "FOO=BAR") { t.Fatal("Environment doesn't have the expected FOO=BAR key/value pair: ", outputEnv) } // Make sure that HOME is set if !strings.Contains(outputEnv, "HOME=/root") { t.Fatal("Environment doesn't have HOME set: ", outputEnv) } } func TestProcessCaps(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() ok(t, err) defer os.RemoveAll(root) rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := factory.Create("test", config) ok(t, err) defer container.Destroy() processCaps := append(config.Capabilities, "NET_ADMIN") var stdout bytes.Buffer pconfig := libcontainer.Process{ Args: []string{"sh", "-c", "cat /proc/self/status"}, Env: standardEnvironment, Capabilities: processCaps, Stdin: nil, Stdout: &stdout, } err = container.Start(&pconfig) ok(t, err) // Wait for process waitProcess(&pconfig, t) outputStatus := string(stdout.Bytes()) lines := strings.Split(outputStatus, "\n") effectiveCapsLine := "" for _, l := range lines { line := strings.TrimSpace(l) if strings.Contains(line, "CapEff:") { effectiveCapsLine = line break } } if effectiveCapsLine == "" { t.Fatal("Couldn't find effective caps: ", outputStatus) } parts := strings.Split(effectiveCapsLine, ":") effectiveCapsStr := strings.TrimSpace(parts[1]) effectiveCaps, err := strconv.ParseUint(effectiveCapsStr, 16, 64) if err != nil { t.Fatal("Could not parse effective caps", err) } var netAdminMask uint64 var netAdminBit uint netAdminBit = 12 // from capability.h netAdminMask = 1 << netAdminBit if effectiveCaps&netAdminMask != netAdminMask { t.Fatal("CAP_NET_ADMIN is not set as expected") } } func TestAdditionalGroups(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() ok(t, err) defer os.RemoveAll(root) rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) config.AdditionalGroups = []string{"plugdev", "audio"} factory, err := libcontainer.New(root, libcontainer.Cgroupfs) ok(t, err) container, err := factory.Create("test", config) ok(t, err) defer container.Destroy() var stdout bytes.Buffer pconfig := libcontainer.Process{ Args: []string{"sh", "-c", "id", "-Gn"}, Env: standardEnvironment, Stdin: nil, Stdout: &stdout, } err = container.Start(&pconfig) ok(t, err) // Wait for process waitProcess(&pconfig, t) outputGroups := string(stdout.Bytes()) // Check that the groups output has the groups that we specified if !strings.Contains(outputGroups, "audio") { t.Fatalf("Listed groups do not contain the audio group as expected: %v", outputGroups) } if !strings.Contains(outputGroups, "plugdev") { t.Fatalf("Listed groups do not contain the plugdev group as expected: %v", outputGroups) } } func TestFreeze(t *testing.T) { testFreeze(t, false) } func TestSystemdFreeze(t *testing.T) { if !systemd.UseSystemd() { t.Skip("Systemd is unsupported") } testFreeze(t, true) } func testFreeze(t *testing.T, systemd bool) { if testing.Short() { return } root, err := newTestRoot() ok(t, err) defer os.RemoveAll(root) rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) f := factory if systemd { f = systemdFactory } container, err := f.Create("test", config) ok(t, err) defer container.Destroy() stdinR, stdinW, err := os.Pipe() ok(t, err) pconfig := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(pconfig) stdinR.Close() defer stdinW.Close() ok(t, err) err = container.Pause() ok(t, err) state, err := container.Status() ok(t, err) err = container.Resume() ok(t, err) if state != libcontainer.Paused { t.Fatal("Unexpected state: ", state) } stdinW.Close() waitProcess(pconfig, t) } func TestCpuShares(t *testing.T) { testCpuShares(t, false) } func TestSystemdCpuShares(t *testing.T) { if !systemd.UseSystemd() { t.Skip("Systemd is unsupported") } testCpuShares(t, true) } func testCpuShares(t *testing.T, systemd bool) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) if systemd { config.Cgroups.Slice = "system.slice" } config.Cgroups.CpuShares = 1 _, _, err = runContainer(config, "", "ps") if err == nil { t.Fatalf("runContainer should failed with invalid CpuShares") } } func TestContainerState(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() if err != nil { t.Fatal(err) } defer os.RemoveAll(root) rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) l, err := os.Readlink("/proc/1/ns/ipc") if err != nil { t.Fatal(err) } config := newTemplateConfig(rootfs) config.Namespaces = configs.Namespaces([]configs.Namespace{ {Type: configs.NEWNS}, {Type: configs.NEWUTS}, // host for IPC //{Type: configs.NEWIPC}, {Type: configs.NEWPID}, {Type: configs.NEWNET}, }) container, err := factory.Create("test", config) if err != nil { t.Fatal(err) } defer container.Destroy() stdinR, stdinW, err := os.Pipe() if err != nil { t.Fatal(err) } p := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(p) if err != nil { t.Fatal(err) } stdinR.Close() defer stdinW.Close() st, err := container.State() if err != nil { t.Fatal(err) } l1, err := os.Readlink(st.NamespacePaths[configs.NEWIPC]) if err != nil { t.Fatal(err) } if l1 != l { t.Fatal("Container using non-host ipc namespace") } stdinW.Close() waitProcess(p, t) } func TestPassExtraFiles(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := factory.Create("test", config) if err != nil { t.Fatal(err) } defer container.Destroy() var stdout bytes.Buffer pipeout1, pipein1, err := os.Pipe() pipeout2, pipein2, err := os.Pipe() process := libcontainer.Process{ Args: []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"}, Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, ExtraFiles: []*os.File{pipein1, pipein2}, Stdin: nil, Stdout: &stdout, } err = container.Start(&process) if err != nil { t.Fatal(err) } waitProcess(&process, t) out := string(stdout.Bytes()) // fd 5 is the directory handle for /proc/$$/fd if out != "0 1 2 3 4 5" { t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to init, got '%s'", out) } var buf = []byte{0} _, err = pipeout1.Read(buf) if err != nil { t.Fatal(err) } out1 := string(buf) if out1 != "1" { t.Fatalf("expected first pipe to receive '1', got '%s'", out1) } _, err = pipeout2.Read(buf) if err != nil { t.Fatal(err) } out2 := string(buf) if out2 != "2" { t.Fatalf("expected second pipe to receive '2', got '%s'", out2) } } func TestMountCmds(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() if err != nil { t.Fatal(err) } defer os.RemoveAll(root) rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) tmpDir, err := ioutil.TempDir("", "tmpdir") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) config := newTemplateConfig(rootfs) config.Mounts = append(config.Mounts, &configs.Mount{ Source: tmpDir, Destination: "/tmp", Device: "bind", Flags: syscall.MS_BIND | syscall.MS_REC, PremountCmds: []configs.Command{ {Path: "touch", Args: []string{filepath.Join(tmpDir, "hello")}}, {Path: "touch", Args: []string{filepath.Join(tmpDir, "world")}}, }, PostmountCmds: []configs.Command{ {Path: "cp", Args: []string{filepath.Join(rootfs, "tmp", "hello"), filepath.Join(rootfs, "tmp", "hello-backup")}}, {Path: "cp", Args: []string{filepath.Join(rootfs, "tmp", "world"), filepath.Join(rootfs, "tmp", "world-backup")}}, }, }) container, err := factory.Create("test", config) if err != nil { t.Fatal(err) } defer container.Destroy() pconfig := libcontainer.Process{ Args: []string{"sh", "-c", "env"}, Env: standardEnvironment, } err = container.Start(&pconfig) if err != nil { t.Fatal(err) } // Wait for process waitProcess(&pconfig, t) entries, err := ioutil.ReadDir(tmpDir) if err != nil { t.Fatal(err) } expected := []string{"hello", "hello-backup", "world", "world-backup"} for i, e := range entries { if e.Name() != expected[i] { t.Errorf("Got(%s), expect %s", e.Name(), expected[i]) } } } func TestSystemProperties(t *testing.T) { if testing.Short() { return } root, err := newTestRoot() ok(t, err) defer os.RemoveAll(root) rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) config.SystemProperties = map[string]string{ "kernel.shmmni": "8192", } container, err := factory.Create("test", config) ok(t, err) defer container.Destroy() var stdout bytes.Buffer pconfig := libcontainer.Process{ Args: []string{"sh", "-c", "cat /proc/sys/kernel/shmmni"}, Env: standardEnvironment, Stdin: nil, Stdout: &stdout, } err = container.Start(&pconfig) ok(t, err) // Wait for process waitProcess(&pconfig, t) shmmniOutput := strings.TrimSpace(string(stdout.Bytes())) if shmmniOutput != "8192" { t.Fatalf("kernel.shmmni property expected to be 8192, but is %s", shmmniOutput) } } func TestSeccompNoChown(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) config := newTemplateConfig(rootfs) config.Seccomp = &configs.Seccomp{} config.Seccomp.Syscalls = append(config.Seccomp.Syscalls, &configs.Syscall{ Value: syscall.SYS_CHOWN, Action: configs.Action(syscall.EPERM), }) buffers, _, err := runContainer(config, "", "/bin/sh", "-c", "chown 1:1 /tmp") if err == nil { t.Fatal("running chown in a container should fail") } if s := buffers.String(); !strings.Contains(s, "not permitted") { t.Fatalf("running chown should result in an EPERM but got %q", s) } } ================================================ FILE: vendor/github.com/docker/libcontainer/integration/execin_test.go ================================================ package integration import ( "bytes" "io" "os" "strings" "testing" "time" "github.com/docker/libcontainer" ) func TestExecIn(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() ps := &libcontainer.Process{ Args: []string{"ps"}, Env: standardEnvironment, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Start(ps) ok(t, err) waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() if !strings.Contains(out, "cat") || !strings.Contains(out, "ps") { t.Fatalf("unexpected running process, output %q", out) } } func TestExecInRlimit(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() ps := &libcontainer.Process{ Args: []string{"/bin/sh", "-c", "ulimit -n"}, Env: standardEnvironment, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Start(ps) ok(t, err) waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() if limit := strings.TrimSpace(out); limit != "1025" { t.Fatalf("expected rlimit to be 1025, got %s", limit) } } func TestExecInError(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(process) stdinR.Close() defer func() { stdinW.Close() if _, err := process.Wait(); err != nil { t.Log(err) } }() ok(t, err) unexistent := &libcontainer.Process{ Args: []string{"unexistent"}, Env: standardEnvironment, } err = container.Start(unexistent) if err == nil { t.Fatal("Should be an error") } if !strings.Contains(err.Error(), "executable file not found") { t.Fatalf("Should be error about not found executable, got %s", err) } } func TestExecInTTY(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(process) stdinR.Close() defer stdinW.Close() ok(t, err) var stdout bytes.Buffer ps := &libcontainer.Process{ Args: []string{"ps"}, Env: standardEnvironment, } console, err := ps.NewConsole(0) copy := make(chan struct{}) go func() { io.Copy(&stdout, console) close(copy) }() ok(t, err) err = container.Start(ps) ok(t, err) select { case <-time.After(5 * time.Second): t.Fatal("Waiting for copy timed out") case <-copy: } waitProcess(ps, t) stdinW.Close() waitProcess(process, t) out := stdout.String() if !strings.Contains(out, "cat") || !strings.Contains(string(out), "ps") { t.Fatalf("unexpected running process, output %q", out) } } func TestExecInEnvironment(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() ok(t, err) defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) ok(t, err) defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() ok(t, err) process := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(process) stdinR.Close() defer stdinW.Close() ok(t, err) buffers := newStdBuffers() process2 := &libcontainer.Process{ Args: []string{"env"}, Env: []string{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "DEBUG=true", "DEBUG=false", "ENV=test", }, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Start(process2) ok(t, err) waitProcess(process2, t) stdinW.Close() waitProcess(process, t) out := buffers.Stdout.String() // check execin's process environment if !strings.Contains(out, "DEBUG=false") || !strings.Contains(out, "ENV=test") || !strings.Contains(out, "HOME=/root") || !strings.Contains(out, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") || strings.Contains(out, "DEBUG=true") { t.Fatalf("unexpected running process, output %q", out) } } func TestExecinPassExtraFiles(t *testing.T) { if testing.Short() { return } rootfs, err := newRootfs() if err != nil { t.Fatal(err) } defer remove(rootfs) config := newTemplateConfig(rootfs) container, err := newContainer(config) if err != nil { t.Fatal(err) } defer container.Destroy() // Execute a first process in the container stdinR, stdinW, err := os.Pipe() if err != nil { t.Fatal(err) } process := &libcontainer.Process{ Args: []string{"cat"}, Env: standardEnvironment, Stdin: stdinR, } err = container.Start(process) stdinR.Close() defer stdinW.Close() if err != nil { t.Fatal(err) } var stdout bytes.Buffer pipeout1, pipein1, err := os.Pipe() pipeout2, pipein2, err := os.Pipe() inprocess := &libcontainer.Process{ Args: []string{"sh", "-c", "cd /proc/$$/fd; echo -n *; echo -n 1 >3; echo -n 2 >4"}, Env: []string{"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, ExtraFiles: []*os.File{pipein1, pipein2}, Stdin: nil, Stdout: &stdout, } err = container.Start(inprocess) if err != nil { t.Fatal(err) } waitProcess(inprocess, t) stdinW.Close() waitProcess(process, t) out := string(stdout.Bytes()) // fd 5 is the directory handle for /proc/$$/fd if out != "0 1 2 3 4 5" { t.Fatalf("expected to have the file descriptors '0 1 2 3 4 5' passed to exec, got '%s'", out) } var buf = []byte{0} _, err = pipeout1.Read(buf) if err != nil { t.Fatal(err) } out1 := string(buf) if out1 != "1" { t.Fatalf("expected first pipe to receive '1', got '%s'", out1) } _, err = pipeout2.Read(buf) if err != nil { t.Fatal(err) } out2 := string(buf) if out2 != "2" { t.Fatalf("expected second pipe to receive '2', got '%s'", out2) } } ================================================ FILE: vendor/github.com/docker/libcontainer/integration/init_test.go ================================================ package integration import ( "os" "runtime" "testing" "github.com/Sirupsen/logrus" "github.com/docker/libcontainer" "github.com/docker/libcontainer/cgroups/systemd" _ "github.com/docker/libcontainer/nsenter" ) // init runs the libcontainer initialization code because of the busybox style needs // to work around the go runtime and the issues with forking func init() { if len(os.Args) < 2 || os.Args[1] != "init" { return } runtime.GOMAXPROCS(1) runtime.LockOSThread() factory, err := libcontainer.New("") if err != nil { logrus.Fatalf("unable to initialize for container: %s", err) } if err := factory.StartInitialization(); err != nil { logrus.Fatal(err) } } var ( factory libcontainer.Factory systemdFactory libcontainer.Factory ) func TestMain(m *testing.M) { var ( err error ret int = 0 ) logrus.SetOutput(os.Stderr) logrus.SetLevel(logrus.InfoLevel) factory, err = libcontainer.New(".", libcontainer.Cgroupfs) if err != nil { logrus.Error(err) os.Exit(1) } if systemd.UseSystemd() { systemdFactory, err = libcontainer.New(".", libcontainer.SystemdCgroups) if err != nil { logrus.Error(err) os.Exit(1) } } ret = m.Run() os.Exit(ret) } ================================================ FILE: vendor/github.com/docker/libcontainer/integration/template_test.go ================================================ package integration import ( "syscall" "github.com/docker/libcontainer/configs" ) var standardEnvironment = []string{ "HOME=/root", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOSTNAME=integration", "TERM=xterm", } const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV // newTemplateConfig returns a base template for running a container // // it uses a network strategy of just setting a loopback interface // and the default setup for devices func newTemplateConfig(rootfs string) *configs.Config { return &configs.Config{ Rootfs: rootfs, Capabilities: []string{ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE", }, Namespaces: configs.Namespaces([]configs.Namespace{ {Type: configs.NEWNS}, {Type: configs.NEWUTS}, {Type: configs.NEWIPC}, {Type: configs.NEWPID}, {Type: configs.NEWNET}, }), Cgroups: &configs.Cgroup{ Name: "test", Parent: "integration", AllowAllDevices: false, AllowedDevices: configs.DefaultAllowedDevices, }, MaskPaths: []string{ "/proc/kcore", }, ReadonlyPaths: []string{ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus", }, Devices: configs.DefaultAutoCreatedDevices, Hostname: "integration", 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, }, }, 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), }, }, } } ================================================ FILE: vendor/github.com/docker/libcontainer/integration/utils_test.go ================================================ package integration import ( "bytes" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "syscall" "testing" "github.com/docker/libcontainer" "github.com/docker/libcontainer/configs" ) func newStdBuffers() *stdBuffers { return &stdBuffers{ Stdin: bytes.NewBuffer(nil), Stdout: bytes.NewBuffer(nil), Stderr: bytes.NewBuffer(nil), } } type stdBuffers struct { Stdin *bytes.Buffer Stdout *bytes.Buffer Stderr *bytes.Buffer } func (b *stdBuffers) String() string { s := []string{} if b.Stderr != nil { s = append(s, b.Stderr.String()) } if b.Stdout != nil { s = append(s, b.Stdout.String()) } return strings.Join(s, "|") } // ok fails the test if an err is not nil. func ok(t testing.TB, err error) { if err != nil { _, file, line, _ := runtime.Caller(1) t.Fatalf("%s:%d: unexpected error: %s\n\n", filepath.Base(file), line, err.Error()) } } func waitProcess(p *libcontainer.Process, t *testing.T) { _, file, line, _ := runtime.Caller(1) status, err := p.Wait() if err != nil { t.Fatalf("%s:%d: unexpected error: %s\n\n", filepath.Base(file), line, err.Error()) } if !status.Success() { t.Fatalf("%s:%d: unexpected status: %s\n\n", filepath.Base(file), line, status.String()) } } // newRootfs creates a new tmp directory and copies the busybox root filesystem func newRootfs() (string, error) { dir, err := ioutil.TempDir("", "") if err != nil { return "", err } if err := os.MkdirAll(dir, 0700); err != nil { return "", err } if err := copyBusybox(dir); err != nil { return "", nil } return dir, nil } func remove(dir string) { os.RemoveAll(dir) } // copyBusybox copies the rootfs for a busybox container created for the test image // into the new directory for the specific test func copyBusybox(dest string) error { out, err := exec.Command("sh", "-c", fmt.Sprintf("cp -R /busybox/* %s/", dest)).CombinedOutput() if err != nil { return fmt.Errorf("copy error %q: %q", err, out) } return nil } func newContainer(config *configs.Config) (libcontainer.Container, error) { f := factory if config.Cgroups != nil && config.Cgroups.Slice == "system.slice" { f = systemdFactory } return f.Create("testCT", config) } // runContainer runs the container with the specific config and arguments // // buffers are returned containing the STDOUT and STDERR output for the run // along with the exit code and any go error func runContainer(config *configs.Config, console string, args ...string) (buffers *stdBuffers, exitCode int, err error) { container, err := newContainer(config) if err != nil { return nil, -1, err } defer container.Destroy() buffers = newStdBuffers() process := &libcontainer.Process{ Args: args, Env: standardEnvironment, Stdin: buffers.Stdin, Stdout: buffers.Stdout, Stderr: buffers.Stderr, } err = container.Start(process) if err != nil { return buffers, -1, err } ps, err := process.Wait() if err != nil { return buffers, -1, err } status := ps.Sys().(syscall.WaitStatus) if status.Exited() { exitCode = status.ExitStatus() } else if status.Signaled() { exitCode = -int(status.Signal()) } else { return buffers, -1, err } return } ================================================ FILE: vendor/github.com/docker/libcontainer/label/label.go ================================================ // +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 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 SetFileLabel(path string, fileLabel string) error { return nil } func SetFileCreateLabel(fileLabel string) error { return nil } func Relabel(path string, fileLabel string, relabel string) error { return nil } func GetPidLabel(pid int) (string, error) { return "", nil } func Init() { } func ReserveLabel(label string) error { return nil } func UnreserveLabel(label string) error { return nil } // DupSecOpt takes an 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/label/label_selinux.go ================================================ // +build selinux,linux package label import ( "fmt" "strings" "github.com/docker/libcontainer/selinux" ) // 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.SelinuxEnabled() { return "", "", nil } processLabel, mountLabel := selinux.GetLxcContexts() 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 SELinux Option") } con := strings.SplitN(opt, ":", 2) 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 } // 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.Setexeccon(processLabel) } // GetProcessLabel 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 GetProcessLabel() (string, error) { return selinux.Getexeccon() } // SetFileLabel modifies the "path" label to the specified file label func SetFileLabel(path string, fileLabel string) error { if selinux.SelinuxEnabled() && fileLabel != "" { return selinux.Setfilecon(path, fileLabel) } return nil } // Tell the kernel the label for all files to be created func SetFileCreateLabel(fileLabel string) error { if selinux.SelinuxEnabled() { return selinux.Setfscreatecon(fileLabel) } return nil } // Change the label of path to the filelabel string. If the relabel string // is "z", relabel will change the MCS label to s0. This will allow all // containers to share the content. If the relabel string is a "Z" then // the MCS label should continue to be used. SELinux will use this field // to make sure the content can not be shared by other containes. func Relabel(path string, fileLabel string, relabel string) error { exclude_path := []string{"/", "/usr", "/etc"} if fileLabel == "" { return nil } if !strings.ContainsAny(relabel, "zZ") { return nil } for _, p := range exclude_path { if path == p { return fmt.Errorf("Relabeling of %s is not allowed", path) } } if strings.Contains(relabel, "z") && strings.Contains(relabel, "Z") { return fmt.Errorf("Bad SELinux option z and Z can not be used together") } if strings.Contains(relabel, "z") { c := selinux.NewContext(fileLabel) c["level"] = "s0" fileLabel = c.Get() } return selinux.Chcon(path, fileLabel, true) } // GetPidLabel will return the label of the process running with the specified pid func GetPidLabel(pid int) (string, error) { return selinux.Getpidcon(pid) } // Init initialises the labeling system func Init() { selinux.SelinuxEnabled() } // 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 } // UnreserveLabel will remove the reservation of the MCS label. // This will allow InitLabels to use the MCS label in a newly created // containers func UnreserveLabel(label string) error { selinux.FreeLxcContexts(label) return nil } // DupSecOpt takes an 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() } ================================================ FILE: vendor/github.com/docker/libcontainer/label/label_selinux_test.go ================================================ // +build selinux,linux package label import ( "strings" "testing" "github.com/docker/libcontainer/selinux" ) func TestInit(t *testing.T) { if selinux.SelinuxEnabled() { var testNull []string plabel, mlabel, err := InitLabels(testNull) if err != nil { t.Log("InitLabels Failed") t.Fatal(err) } testDisabled := []string{"disable"} plabel, mlabel, err = InitLabels(testDisabled) if err != nil { t.Log("InitLabels Disabled Failed") t.Fatal(err) } if plabel != "" { t.Log("InitLabels Disabled Failed") t.Fatal() } testUser := []string{"user:user_u", "role:user_r", "type:user_t", "level:s0:c1,c15"} plabel, mlabel, err = InitLabels(testUser) if err != nil { t.Log("InitLabels User Failed") t.Fatal(err) } if plabel != "user_u:user_r:user_t:s0:c1,c15" || mlabel != "user_u:object_r:svirt_sandbox_file_t:s0:c1,c15" { t.Log("InitLabels User Match Failed") t.Log(plabel, mlabel) t.Fatal(err) } testBadData := []string{"user", "role:user_r", "type:user_t", "level:s0:c1,c15"} plabel, mlabel, err = InitLabels(testBadData) if err == nil { t.Log("InitLabels Bad Failed") t.Fatal(err) } } } func TestDuplicateLabel(t *testing.T) { secopt := DupSecOpt("system_u:system_r:svirt_lxc_net_t:s0:c1,c2") t.Log(secopt) for _, opt := range secopt { con := strings.SplitN(opt, ":", 3) if len(con) != 3 || con[0] != "label" { t.Errorf("Invalid DupSecOpt return value") continue } if con[1] == "user" { if con[2] != "system_u" { t.Errorf("DupSecOpt Failed user incorrect") } continue } if con[1] == "role" { if con[2] != "system_r" { t.Errorf("DupSecOpt Failed role incorrect") } continue } if con[1] == "type" { if con[2] != "svirt_lxc_net_t" { t.Errorf("DupSecOpt Failed type incorrect") } continue } if con[1] == "level" { if con[2] != "s0:c1,c2" { t.Errorf("DupSecOpt Failed level incorrect") } continue } t.Errorf("DupSecOpt Failed invalid field %q", con[1]) } secopt = DisableSecOpt() if secopt[0] != "label:disable" { t.Errorf("DisableSecOpt Failed level incorrect") } } func TestRelabel(t *testing.T) { testdir := "/tmp/test" label := "system_u:system_r:svirt_sandbox_file_t:s0:c1,c2" if err := Relabel(testdir, "", "z"); err != nil { t.Fatal("Relabel with no label failed: %v", err) } if err := Relabel(testdir, label, ""); err != nil { t.Fatal("Relabel with no relabel field failed: %v", err) } if err := Relabel(testdir, label, "z"); err != nil { t.Fatal("Relabel shared failed: %v", err) } if err := Relabel(testdir, label, "Z"); err != nil { t.Fatal("Relabel unshared failed: %v", err) } if err := Relabel(testdir, label, "zZ"); err == nil { t.Fatal("Relabel with shared and unshared succeeded") } if err := Relabel("/etc", label, "zZ"); err == nil { t.Fatal("Relabel /etc succeeded") } if err := Relabel("/", label, ""); err == nil { t.Fatal("Relabel / succeeded") } if err := Relabel("/usr", label, "Z"); err == nil { t.Fatal("Relabel /usr succeeded") } } ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/MAINTAINERS ================================================ Michael Crosby (@crosbymichael) Guillaume J. Charmes (@creack) ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/netlink.go ================================================ // Packet netlink provide access to low level Netlink sockets and messages. // // Actual implementations are in: // netlink_linux.go // netlink_darwin.go package netlink import ( "errors" "net" ) var ( ErrWrongSockType = errors.New("Wrong socket type") ErrShortResponse = errors.New("Got short response from netlink") ErrInterfaceExists = errors.New("Network interface already exists") ) // A Route is a subnet associated with the interface to reach it. type Route struct { *net.IPNet Iface *net.Interface Default bool } // An IfAddr defines IP network settings for a given network interface type IfAddr struct { Iface *net.Interface IP net.IP IPNet *net.IPNet } ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/netlink_linux.go ================================================ package netlink import ( "encoding/binary" "fmt" "io" "math/rand" "net" "os" "sync/atomic" "syscall" "time" "unsafe" ) const ( IFNAMSIZ = 16 DEFAULT_CHANGE = 0xFFFFFFFF IFLA_INFO_KIND = 1 IFLA_INFO_DATA = 2 VETH_INFO_PEER = 1 IFLA_MACVLAN_MODE = 1 IFLA_VLAN_ID = 1 IFLA_NET_NS_FD = 28 IFLA_ADDRESS = 1 IFLA_BRPORT_MODE = 4 SIOC_BRADDBR = 0x89a0 SIOC_BRDELBR = 0x89a1 SIOC_BRADDIF = 0x89a2 SIOC_BRDELIF = 0x89a3 ) const ( MACVLAN_MODE_PRIVATE = 1 << iota MACVLAN_MODE_VEPA MACVLAN_MODE_BRIDGE MACVLAN_MODE_PASSTHRU ) var nextSeqNr uint32 type ifreqHwaddr struct { IfrnName [IFNAMSIZ]byte IfruHwaddr syscall.RawSockaddr } type ifreqIndex struct { IfrnName [IFNAMSIZ]byte IfruIndex int32 } type ifreqFlags struct { IfrnName [IFNAMSIZ]byte Ifruflags uint16 } var native binary.ByteOrder var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) func init() { var x uint32 = 0x01020304 if *(*byte)(unsafe.Pointer(&x)) == 0x01 { native = binary.BigEndian } else { native = binary.LittleEndian } } func getIpFamily(ip net.IP) int { if len(ip) <= net.IPv4len { return syscall.AF_INET } if ip.To4() != nil { return syscall.AF_INET } return syscall.AF_INET6 } type NetlinkRequestData interface { Len() int ToWireFormat() []byte } type IfInfomsg struct { syscall.IfInfomsg } func newIfInfomsg(family int) *IfInfomsg { return &IfInfomsg{ IfInfomsg: syscall.IfInfomsg{ Family: uint8(family), }, } } func newIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg { msg := newIfInfomsg(family) parent.children = append(parent.children, msg) return msg } func (msg *IfInfomsg) ToWireFormat() []byte { length := syscall.SizeofIfInfomsg b := make([]byte, length) b[0] = msg.Family b[1] = 0 native.PutUint16(b[2:4], msg.Type) native.PutUint32(b[4:8], uint32(msg.Index)) native.PutUint32(b[8:12], msg.Flags) native.PutUint32(b[12:16], msg.Change) return b } func (msg *IfInfomsg) Len() int { return syscall.SizeofIfInfomsg } type IfAddrmsg struct { syscall.IfAddrmsg } func newIfAddrmsg(family int) *IfAddrmsg { return &IfAddrmsg{ IfAddrmsg: syscall.IfAddrmsg{ Family: uint8(family), }, } } func (msg *IfAddrmsg) ToWireFormat() []byte { length := syscall.SizeofIfAddrmsg b := make([]byte, length) b[0] = msg.Family b[1] = msg.Prefixlen b[2] = msg.Flags b[3] = msg.Scope native.PutUint32(b[4:8], msg.Index) return b } func (msg *IfAddrmsg) Len() int { return syscall.SizeofIfAddrmsg } 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 (msg *RtMsg) ToWireFormat() []byte { length := syscall.SizeofRtMsg b := make([]byte, length) b[0] = msg.Family b[1] = msg.Dst_len b[2] = msg.Src_len b[3] = msg.Tos b[4] = msg.Table b[5] = msg.Protocol b[6] = msg.Scope b[7] = msg.Type native.PutUint32(b[8:12], msg.Flags) return b } func (msg *RtMsg) Len() int { return syscall.SizeofRtMsg } func rtaAlignOf(attrlen int) int { return (attrlen + syscall.RTA_ALIGNTO - 1) & ^(syscall.RTA_ALIGNTO - 1) } type RtAttr struct { syscall.RtAttr Data []byte children []NetlinkRequestData } func newRtAttr(attrType int, data []byte) *RtAttr { return &RtAttr{ RtAttr: syscall.RtAttr{ Type: uint16(attrType), }, children: []NetlinkRequestData{}, Data: data, } } 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 += child.Len() } l += syscall.SizeofRtAttr return rtaAlignOf(l + len(a.Data)) } func (a *RtAttr) ToWireFormat() []byte { length := a.Len() buf := make([]byte, rtaAlignOf(length)) if a.Data != nil { copy(buf[4:], a.Data) } else { next := 4 for _, child := range a.children { childBuf := child.ToWireFormat() 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 } func uint32Attr(t int, n uint32) *RtAttr { buf := make([]byte, 4) native.PutUint32(buf, n) return newRtAttr(t, buf) } type NetlinkRequest struct { syscall.NlMsghdr Data []NetlinkRequestData } func (rr *NetlinkRequest) ToWireFormat() []byte { length := rr.Len dataBytes := make([][]byte, len(rr.Data)) for i, data := range rr.Data { dataBytes[i] = data.ToWireFormat() length += uint32(len(dataBytes[i])) } b := make([]byte, length) native.PutUint32(b[0:4], length) native.PutUint16(b[4:6], rr.Type) native.PutUint16(b[6:8], rr.Flags) native.PutUint32(b[8:12], rr.Seq) native.PutUint32(b[12:16], rr.Pid) next := 16 for _, data := range dataBytes { copy(b[next:], data) next += len(data) } return b } func (rr *NetlinkRequest) AddData(data NetlinkRequestData) { if data != nil { rr.Data = append(rr.Data, data) } } func newNetlinkRequest(proto, flags int) *NetlinkRequest { return &NetlinkRequest{ NlMsghdr: syscall.NlMsghdr{ Len: uint32(syscall.NLMSG_HDRLEN), Type: uint16(proto), Flags: syscall.NLM_F_REQUEST | uint16(flags), Seq: atomic.AddUint32(&nextSeqNr, 1), }, } } type NetlinkSocket struct { fd int lsa syscall.SockaddrNetlink } func getNetlinkSocket() (*NetlinkSocket, error) { fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, syscall.NETLINK_ROUTE) if err != nil { return nil, err } s := &NetlinkSocket{ fd: 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 } func (s *NetlinkSocket) Close() { syscall.Close(s.fd) } func (s *NetlinkSocket) Send(request *NetlinkRequest) error { if err := syscall.Sendto(s.fd, request.ToWireFormat(), 0, &s.lsa); err != nil { return err } return nil } func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) { rb := make([]byte, syscall.Getpagesize()) nr, _, err := syscall.Recvfrom(s.fd, rb, 0) if err != nil { return nil, err } if nr < syscall.NLMSG_HDRLEN { return nil, ErrShortResponse } rb = rb[:nr] return syscall.ParseNetlinkMessage(rb) } func (s *NetlinkSocket) GetPid() (uint32, error) { lsa, err := syscall.Getsockname(s.fd) if err != nil { return 0, err } switch v := lsa.(type) { case *syscall.SockaddrNetlink: return v.Pid, nil } return 0, ErrWrongSockType } func (s *NetlinkSocket) CheckMessage(m syscall.NetlinkMessage, seq, pid uint32) error { if m.Header.Seq != seq { return fmt.Errorf("netlink: invalid seq %d, expected %d", m.Header.Seq, seq) } if m.Header.Pid != pid { return fmt.Errorf("netlink: wrong pid %d, expected %d", m.Header.Pid, pid) } if m.Header.Type == syscall.NLMSG_DONE { return io.EOF } if m.Header.Type == syscall.NLMSG_ERROR { e := int32(native.Uint32(m.Data[0:4])) if e == 0 { return io.EOF } return syscall.Errno(-e) } return nil } func (s *NetlinkSocket) HandleAck(seq uint32) error { pid, err := s.GetPid() if err != nil { return err } outer: for { msgs, err := s.Receive() if err != nil { return err } for _, m := range msgs { if err := s.CheckMessage(m, seq, pid); err != nil { if err == io.EOF { break outer } return err } } } return nil } func zeroTerminated(s string) []byte { return []byte(s + "\000") } func nonZeroTerminated(s string) []byte { return []byte(s) } // Add a new network link of a specified type. // This is identical to running: ip link add $name type $linkType func NetworkLinkAdd(name string, linkType string) error { if name == "" || linkType == "" { return fmt.Errorf("Neither link name nor link type can be empty!") } s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) wb.AddData(msg) linkInfo := newRtAttr(syscall.IFLA_LINKINFO, nil) newRtAttrChild(linkInfo, IFLA_INFO_KIND, nonZeroTerminated(linkType)) wb.AddData(linkInfo) nameData := newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(name)) wb.AddData(nameData) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Delete a network link. // This is identical to running: ip link del $name func NetworkLinkDel(name string) error { if name == "" { return fmt.Errorf("Network link name can not be empty!") } s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() iface, err := net.InterfaceByName(name) if err != nil { return err } wb := newNetlinkRequest(syscall.RTM_DELLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Index = int32(iface.Index) wb.AddData(msg) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Bring up a particular network interface. // This is identical to running: ip link set dev $name up func NetworkLinkUp(iface *net.Interface) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Index = int32(iface.Index) msg.Flags = syscall.IFF_UP msg.Change = syscall.IFF_UP wb.AddData(msg) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Bring down a particular network interface. // This is identical to running: ip link set $name down func NetworkLinkDown(iface *net.Interface) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Index = int32(iface.Index) msg.Flags = 0 & ^syscall.IFF_UP msg.Change = DEFAULT_CHANGE wb.AddData(msg) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Set link layer address ie. MAC Address. // This is identical to running: ip link set dev $name address $macaddress func NetworkSetMacAddress(iface *net.Interface, macaddr string) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() hwaddr, err := net.ParseMAC(macaddr) if err != nil { return err } var ( MULTICAST byte = 0x1 ) if hwaddr[0]&0x1 == MULTICAST { return fmt.Errorf("Multicast MAC Address is not supported: %s", macaddr) } wb := newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Index = int32(iface.Index) msg.Change = DEFAULT_CHANGE wb.AddData(msg) macdata := make([]byte, 6) copy(macdata, hwaddr) data := newRtAttr(IFLA_ADDRESS, macdata) wb.AddData(data) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Set link Maximum Transmission Unit // This is identical to running: ip link set dev $name mtu $MTU // bridge is a bitch here https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=292088 // https://bugzilla.redhat.com/show_bug.cgi?id=697021 // There is a discussion about how to deal with ifcs joining bridge with MTU > 1500 // Regular network nterfaces do seem to work though! func NetworkSetMTU(iface *net.Interface, mtu int) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Type = syscall.RTM_SETLINK msg.Flags = syscall.NLM_F_REQUEST msg.Index = int32(iface.Index) msg.Change = DEFAULT_CHANGE wb.AddData(msg) wb.AddData(uint32Attr(syscall.IFLA_MTU, uint32(mtu))) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Set link queue length // This is identical to running: ip link set dev $name txqueuelen $QLEN func NetworkSetTxQueueLen(iface *net.Interface, txQueueLen int) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Type = syscall.RTM_SETLINK msg.Flags = syscall.NLM_F_REQUEST msg.Index = int32(iface.Index) msg.Change = DEFAULT_CHANGE wb.AddData(msg) wb.AddData(uint32Attr(syscall.IFLA_TXQLEN, uint32(txQueueLen))) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } func networkMasterAction(iface *net.Interface, rtattr *RtAttr) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Type = syscall.RTM_SETLINK msg.Flags = syscall.NLM_F_REQUEST msg.Index = int32(iface.Index) msg.Change = DEFAULT_CHANGE wb.AddData(msg) wb.AddData(rtattr) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Add an interface to bridge. // This is identical to running: ip link set $name master $master func NetworkSetMaster(iface, master *net.Interface) error { data := uint32Attr(syscall.IFLA_MASTER, uint32(master.Index)) return networkMasterAction(iface, data) } // Remove an interface from the bridge // This is is identical to to running: ip link $name set nomaster func NetworkSetNoMaster(iface *net.Interface) error { data := uint32Attr(syscall.IFLA_MASTER, 0) return networkMasterAction(iface, data) } func networkSetNsAction(iface *net.Interface, rtattr *RtAttr) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Index = int32(iface.Index) wb.AddData(msg) wb.AddData(rtattr) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Move a particular network interface to a particular network namespace // specified by PID. This is identical to running: ip link set dev $name netns $pid func NetworkSetNsPid(iface *net.Interface, nspid int) error { data := uint32Attr(syscall.IFLA_NET_NS_PID, uint32(nspid)) return networkSetNsAction(iface, data) } // Move a particular network interface to a particular mounted // network namespace specified by file descriptor. // This is idential to running: ip link set dev $name netns $fd func NetworkSetNsFd(iface *net.Interface, fd int) error { data := uint32Attr(IFLA_NET_NS_FD, uint32(fd)) return networkSetNsAction(iface, data) } // Rename a particular interface to a different name // !!! Note that you can't rename an active interface. You need to bring it down before renaming it. // This is identical to running: ip link set dev ${oldName} name ${newName} func NetworkChangeName(iface *net.Interface, newName string) error { if len(newName) >= IFNAMSIZ { return fmt.Errorf("Interface name %s too long", newName) } s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) msg.Index = int32(iface.Index) msg.Change = DEFAULT_CHANGE wb.AddData(msg) nameData := newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(newName)) wb.AddData(nameData) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Add a new VETH pair link on the host // This is identical to running: ip link add name $name type veth peer name $peername func NetworkCreateVethPair(name1, name2 string, txQueueLen int) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_UNSPEC) wb.AddData(msg) nameData := newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(name1)) wb.AddData(nameData) txqLen := make([]byte, 4) native.PutUint32(txqLen, uint32(txQueueLen)) txqData := newRtAttr(syscall.IFLA_TXQLEN, txqLen) wb.AddData(txqData) nest1 := newRtAttr(syscall.IFLA_LINKINFO, nil) newRtAttrChild(nest1, IFLA_INFO_KIND, zeroTerminated("veth")) nest2 := newRtAttrChild(nest1, IFLA_INFO_DATA, nil) nest3 := newRtAttrChild(nest2, VETH_INFO_PEER, nil) newIfInfomsgChild(nest3, syscall.AF_UNSPEC) newRtAttrChild(nest3, syscall.IFLA_IFNAME, zeroTerminated(name2)) txqLen2 := make([]byte, 4) native.PutUint32(txqLen2, uint32(txQueueLen)) newRtAttrChild(nest3, syscall.IFLA_TXQLEN, txqLen2) wb.AddData(nest1) if err := s.Send(wb); err != nil { return err } if err := s.HandleAck(wb.Seq); err != nil { if os.IsExist(err) { return ErrInterfaceExists } return err } return nil } // Add a new VLAN interface with masterDev as its upper device // This is identical to running: // ip link add name $name link $masterdev type vlan id $id func NetworkLinkAddVlan(masterDev, vlanDev string, vlanId uint16) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) masterDevIfc, err := net.InterfaceByName(masterDev) if err != nil { return err } msg := newIfInfomsg(syscall.AF_UNSPEC) wb.AddData(msg) nest1 := newRtAttr(syscall.IFLA_LINKINFO, nil) newRtAttrChild(nest1, IFLA_INFO_KIND, nonZeroTerminated("vlan")) nest2 := newRtAttrChild(nest1, IFLA_INFO_DATA, nil) vlanData := make([]byte, 2) native.PutUint16(vlanData, vlanId) newRtAttrChild(nest2, IFLA_VLAN_ID, vlanData) wb.AddData(nest1) wb.AddData(uint32Attr(syscall.IFLA_LINK, uint32(masterDevIfc.Index))) wb.AddData(newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(vlanDev))) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // MacVlan link has LowerDev, UpperDev and operates in Mode mode // This simplifies the code when creating MacVlan or MacVtap interface type MacVlanLink struct { MasterDev string SlaveDev string mode string } func (m MacVlanLink) Mode() uint32 { modeMap := map[string]uint32{ "private": MACVLAN_MODE_PRIVATE, "vepa": MACVLAN_MODE_VEPA, "bridge": MACVLAN_MODE_BRIDGE, "passthru": MACVLAN_MODE_PASSTHRU, } return modeMap[m.mode] } // Add MAC VLAN network interface with masterDev as its upper device // This is identical to running: // ip link add name $name link $masterdev type macvlan mode $mode func networkLinkMacVlan(dev_type string, mcvln *MacVlanLink) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) masterDevIfc, err := net.InterfaceByName(mcvln.MasterDev) if err != nil { return err } msg := newIfInfomsg(syscall.AF_UNSPEC) wb.AddData(msg) nest1 := newRtAttr(syscall.IFLA_LINKINFO, nil) newRtAttrChild(nest1, IFLA_INFO_KIND, nonZeroTerminated(dev_type)) nest2 := newRtAttrChild(nest1, IFLA_INFO_DATA, nil) macVlanData := make([]byte, 4) native.PutUint32(macVlanData, mcvln.Mode()) newRtAttrChild(nest2, IFLA_MACVLAN_MODE, macVlanData) wb.AddData(nest1) wb.AddData(uint32Attr(syscall.IFLA_LINK, uint32(masterDevIfc.Index))) wb.AddData(newRtAttr(syscall.IFLA_IFNAME, zeroTerminated(mcvln.SlaveDev))) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } func NetworkLinkAddMacVlan(masterDev, macVlanDev string, mode string) error { return networkLinkMacVlan("macvlan", &MacVlanLink{ MasterDev: masterDev, SlaveDev: macVlanDev, mode: mode, }) } func NetworkLinkAddMacVtap(masterDev, macVlanDev string, mode string) error { return networkLinkMacVlan("macvtap", &MacVlanLink{ MasterDev: masterDev, SlaveDev: macVlanDev, mode: mode, }) } func networkLinkIpAction(action, flags int, ifa IfAddr) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() family := getIpFamily(ifa.IP) wb := newNetlinkRequest(action, flags) msg := newIfAddrmsg(family) msg.Index = uint32(ifa.Iface.Index) prefixLen, _ := ifa.IPNet.Mask.Size() msg.Prefixlen = uint8(prefixLen) wb.AddData(msg) var ipData []byte if family == syscall.AF_INET { ipData = ifa.IP.To4() } else { ipData = ifa.IP.To16() } localData := newRtAttr(syscall.IFA_LOCAL, ipData) wb.AddData(localData) addrData := newRtAttr(syscall.IFA_ADDRESS, ipData) wb.AddData(addrData) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Delete an IP address from an interface. This is identical to: // ip addr del $ip/$ipNet dev $iface func NetworkLinkDelIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error { return networkLinkIpAction( syscall.RTM_DELADDR, syscall.NLM_F_ACK, IfAddr{iface, ip, ipNet}, ) } // Add an Ip address to an interface. This is identical to: // ip addr add $ip/$ipNet dev $iface func NetworkLinkAddIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error { return networkLinkIpAction( syscall.RTM_NEWADDR, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK, IfAddr{iface, ip, ipNet}, ) } // Returns an array of IPNet for all the currently routed subnets on ipv4 // This is similar to the first column of "ip route" output func NetworkGetRoutes() ([]Route, error) { s, err := getNetlinkSocket() if err != nil { return nil, err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_DUMP) msg := newIfInfomsg(syscall.AF_UNSPEC) wb.AddData(msg) if err := s.Send(wb); err != nil { return nil, err } pid, err := s.GetPid() if err != nil { return nil, err } res := make([]Route, 0) outer: for { msgs, err := s.Receive() if err != nil { return nil, err } for _, m := range msgs { if err := s.CheckMessage(m, wb.Seq, pid); err != nil { if err == io.EOF { break outer } return nil, err } if m.Header.Type != syscall.RTM_NEWROUTE { continue } var r Route msg := (*RtMsg)(unsafe.Pointer(&m.Data[0:syscall.SizeofRtMsg][0])) if msg.Flags&syscall.RTM_F_CLONED != 0 { // Ignore cloned routes continue } if msg.Table != syscall.RT_TABLE_MAIN { // Ignore non-main tables continue } if msg.Family != syscall.AF_INET { // Ignore non-ipv4 routes continue } if msg.Dst_len == 0 { // Default routes r.Default = true } attrs, err := syscall.ParseNetlinkRouteAttr(&m) if err != nil { return nil, err } for _, attr := range attrs { switch attr.Attr.Type { case syscall.RTA_DST: ip := attr.Value r.IPNet = &net.IPNet{ IP: ip, Mask: net.CIDRMask(int(msg.Dst_len), 8*len(ip)), } case syscall.RTA_OIF: index := int(native.Uint32(attr.Value[0:4])) r.Iface, _ = net.InterfaceByIndex(index) } } if r.Default || r.IPNet != nil { res = append(res, r) } } } return res, nil } // Add a new route table entry. func AddRoute(destination, source, gateway, device string) error { if destination == "" && source == "" && gateway == "" { return fmt.Errorf("one of destination, source or gateway must not be blank") } s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() wb := newNetlinkRequest(syscall.RTM_NEWROUTE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK) msg := newRtMsg() currentFamily := -1 var rtAttrs []*RtAttr if destination != "" { destIP, destNet, err := net.ParseCIDR(destination) if err != nil { return fmt.Errorf("destination CIDR %s couldn't be parsed", destination) } destFamily := getIpFamily(destIP) currentFamily = destFamily destLen, bits := destNet.Mask.Size() if destLen == 0 && bits == 0 { return fmt.Errorf("destination CIDR %s generated a non-canonical Mask", destination) } msg.Family = uint8(destFamily) msg.Dst_len = uint8(destLen) var destData []byte if destFamily == syscall.AF_INET { destData = destIP.To4() } else { destData = destIP.To16() } rtAttrs = append(rtAttrs, newRtAttr(syscall.RTA_DST, destData)) } if source != "" { srcIP := net.ParseIP(source) if srcIP == nil { return fmt.Errorf("source IP %s couldn't be parsed", source) } srcFamily := getIpFamily(srcIP) if currentFamily != -1 && currentFamily != srcFamily { return fmt.Errorf("source and destination ip were not the same IP family") } currentFamily = srcFamily msg.Family = uint8(srcFamily) var srcData []byte if srcFamily == syscall.AF_INET { srcData = srcIP.To4() } else { srcData = srcIP.To16() } rtAttrs = append(rtAttrs, newRtAttr(syscall.RTA_PREFSRC, srcData)) } if gateway != "" { gwIP := net.ParseIP(gateway) if gwIP == nil { return fmt.Errorf("gateway IP %s couldn't be parsed", gateway) } gwFamily := getIpFamily(gwIP) if currentFamily != -1 && currentFamily != gwFamily { return fmt.Errorf("gateway, source, and destination ip were not the same IP family") } msg.Family = uint8(gwFamily) var gwData []byte if gwFamily == syscall.AF_INET { gwData = gwIP.To4() } else { gwData = gwIP.To16() } rtAttrs = append(rtAttrs, newRtAttr(syscall.RTA_GATEWAY, gwData)) } wb.AddData(msg) for _, attr := range rtAttrs { wb.AddData(attr) } iface, err := net.InterfaceByName(device) if err != nil { return err } wb.AddData(uint32Attr(syscall.RTA_OIF, uint32(iface.Index))) if err := s.Send(wb); err != nil { return err } return s.HandleAck(wb.Seq) } // Add a new default gateway. Identical to: // ip route add default via $ip func AddDefaultGw(ip, device string) error { return AddRoute("", "", ip, device) } // 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 } // Create the actual bridge device. This is more backward-compatible than // netlink.NetworkLinkAdd and works on RHEL 6. func CreateBridge(name string, setMacAddr bool) error { if len(name) >= IFNAMSIZ { 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), SIOC_BRADDBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 { return err } if setMacAddr { return SetMacAddress(name, randMacAddr()) } return nil } // Delete the actual bridge device. func DeleteBridge(name string) error { s, err := getIfSocket() if err != nil { return err } defer syscall.Close(s) nameBytePtr, err := syscall.BytePtrFromString(name) if err != nil { return err } var ifr ifreqFlags copy(ifr.IfrnName[:len(ifr.IfrnName)-1], []byte(name)) if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), syscall.SIOCSIFFLAGS, uintptr(unsafe.Pointer(&ifr))); err != 0 { return err } if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), SIOC_BRDELBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 { return err } return nil } func ifIoctBridge(iface, master *net.Interface, op uintptr) error { if len(master.Name) >= IFNAMSIZ { 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 AddToBridge(iface, master *net.Interface) error { return ifIoctBridge(iface, master, SIOC_BRADDIF) } // Detach a slave from a bridge device. This is more backward-compatible than // netlink.NetworkSetMaster and works on RHEL 6. func DelFromBridge(iface, master *net.Interface) error { return ifIoctBridge(iface, master, SIOC_BRDELIF) } func randMacAddr() string { hw := make(net.HardwareAddr, 6) for i := 0; i < 6; i++ { hw[i] = byte(rnd.Intn(255)) } hw[0] &^= 0x1 // clear multicast bit hw[0] |= 0x2 // set local assignment bit (IEEE802) return hw.String() } func SetMacAddress(name, addr string) error { if len(name) >= IFNAMSIZ { 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 SetHairpinMode(iface *net.Interface, enabled bool) error { s, err := getNetlinkSocket() if err != nil { return err } defer s.Close() req := newNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK) msg := newIfInfomsg(syscall.AF_BRIDGE) msg.Type = syscall.RTM_SETLINK msg.Flags = syscall.NLM_F_REQUEST msg.Index = int32(iface.Index) msg.Change = DEFAULT_CHANGE req.AddData(msg) mode := []byte{0} if enabled { mode[0] = byte(1) } br := newRtAttr(syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED, nil) newRtAttrChild(br, IFLA_BRPORT_MODE, mode) req.AddData(br) if err := s.Send(req); err != nil { return err } return s.HandleAck(req.Seq) } func ChangeName(iface *net.Interface, newName string) error { if len(newName) >= IFNAMSIZ { return fmt.Errorf("Interface name %s too long", newName) } fd, err := getIfSocket() if err != nil { return err } defer syscall.Close(fd) data := [IFNAMSIZ * 2]byte{} // the "-1"s here are very important for ensuring we get proper null // termination of our new C strings copy(data[:IFNAMSIZ-1], iface.Name) copy(data[IFNAMSIZ:IFNAMSIZ*2-1], newName) if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), syscall.SIOCSIFNAME, uintptr(unsafe.Pointer(&data[0]))); errno != 0 { return errno } return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/netlink_linux_armppc64.go ================================================ // +build arm ppc64 ppc64le package netlink func ifrDataByte(b byte) uint8 { return uint8(b) } ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/netlink_linux_notarm.go ================================================ // +build !arm,!ppc64,!ppc64le package netlink func ifrDataByte(b byte) int8 { return int8(b) } ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/netlink_linux_test.go ================================================ package netlink import ( "net" "strings" "syscall" "testing" ) type testLink struct { name string linkType string } func addLink(t *testing.T, name string, linkType string) { if err := NetworkLinkAdd(name, linkType); err != nil { t.Fatalf("Unable to create %s link: %s", name, err) } } func readLink(t *testing.T, name string) *net.Interface { iface, err := net.InterfaceByName(name) if err != nil { t.Fatalf("Could not find %s interface: %s", name, err) } return iface } func deleteLink(t *testing.T, name string) { if err := NetworkLinkDel(name); err != nil { t.Fatalf("Unable to delete %s link: %s", name, err) } } func upLink(t *testing.T, name string) { iface := readLink(t, name) if err := NetworkLinkUp(iface); err != nil { t.Fatalf("Could not bring UP %#v interface: %s", iface, err) } } func downLink(t *testing.T, name string) { iface := readLink(t, name) if err := NetworkLinkDown(iface); err != nil { t.Fatalf("Could not bring DOWN %#v interface: %s", iface, err) } } func ipAssigned(iface *net.Interface, ip net.IP) bool { addrs, _ := iface.Addrs() for _, addr := range addrs { args := strings.SplitN(addr.String(), "/", 2) if args[0] == ip.String() { return true } } return false } func TestNetworkLinkAddDel(t *testing.T) { if testing.Short() { return } testLinks := []testLink{ {"tstEth", "dummy"}, {"tstBr", "bridge"}, } for _, tl := range testLinks { addLink(t, tl.name, tl.linkType) defer deleteLink(t, tl.name) readLink(t, tl.name) } } func TestNetworkLinkUpDown(t *testing.T) { if testing.Short() { return } tl := testLink{name: "tstEth", linkType: "dummy"} addLink(t, tl.name, tl.linkType) defer deleteLink(t, tl.name) upLink(t, tl.name) ifcAfterUp := readLink(t, tl.name) if (ifcAfterUp.Flags & syscall.IFF_UP) != syscall.IFF_UP { t.Fatalf("Could not bring UP %#v initerface", tl) } downLink(t, tl.name) ifcAfterDown := readLink(t, tl.name) if (ifcAfterDown.Flags & syscall.IFF_UP) == syscall.IFF_UP { t.Fatalf("Could not bring DOWN %#v initerface", tl) } } func TestNetworkSetMacAddress(t *testing.T) { if testing.Short() { return } tl := testLink{name: "tstEth", linkType: "dummy"} macaddr := "22:ce:e0:99:63:6f" addLink(t, tl.name, tl.linkType) defer deleteLink(t, tl.name) ifcBeforeSet := readLink(t, tl.name) if err := NetworkSetMacAddress(ifcBeforeSet, macaddr); err != nil { t.Fatalf("Could not set %s MAC address on %#v interface: %s", macaddr, tl, err) } ifcAfterSet := readLink(t, tl.name) if ifcAfterSet.HardwareAddr.String() != macaddr { t.Fatalf("Could not set %s MAC address on %#v interface", macaddr, tl) } } func TestNetworkSetMTU(t *testing.T) { if testing.Short() { return } tl := testLink{name: "tstEth", linkType: "dummy"} mtu := 1400 addLink(t, tl.name, tl.linkType) defer deleteLink(t, tl.name) ifcBeforeSet := readLink(t, tl.name) if err := NetworkSetMTU(ifcBeforeSet, mtu); err != nil { t.Fatalf("Could not set %d MTU on %#v interface: %s", mtu, tl, err) } ifcAfterSet := readLink(t, tl.name) if ifcAfterSet.MTU != mtu { t.Fatalf("Could not set %d MTU on %#v interface", mtu, tl) } } func TestNetworkSetMasterNoMaster(t *testing.T) { if testing.Short() { return } master := testLink{"tstBr", "bridge"} slave := testLink{"tstEth", "dummy"} testLinks := []testLink{master, slave} for _, tl := range testLinks { addLink(t, tl.name, tl.linkType) defer deleteLink(t, tl.name) upLink(t, tl.name) } masterIfc := readLink(t, master.name) slaveIfc := readLink(t, slave.name) if err := NetworkSetMaster(slaveIfc, masterIfc); err != nil { t.Fatalf("Could not set %#v to be the master of %#v: %s", master, slave, err) } // Trying to figure out a way to test which will not break on RHEL6. // We could check for existence of /sys/class/net/tstEth/upper_tstBr // which should point to the ../tstBr which is the UPPER device i.e. network bridge if err := NetworkSetNoMaster(slaveIfc); err != nil { t.Fatalf("Could not UNset %#v master of %#v: %s", master, slave, err) } } func TestNetworkChangeName(t *testing.T) { if testing.Short() { return } tl := testLink{"tstEth", "dummy"} newName := "newTst" addLink(t, tl.name, tl.linkType) linkIfc := readLink(t, tl.name) if err := NetworkChangeName(linkIfc, newName); err != nil { deleteLink(t, tl.name) t.Fatalf("Could not change %#v interface name to %s: %s", tl, newName, err) } readLink(t, newName) deleteLink(t, newName) } func TestNetworkLinkAddVlan(t *testing.T) { if testing.Short() { return } tl := struct { name string id uint16 }{ name: "tstVlan", id: 32, } masterLink := testLink{"tstEth", "dummy"} addLink(t, masterLink.name, masterLink.linkType) defer deleteLink(t, masterLink.name) if err := NetworkLinkAddVlan(masterLink.name, tl.name, tl.id); err != nil { t.Fatalf("Unable to create %#v VLAN interface: %s", tl, err) } readLink(t, tl.name) } func TestNetworkLinkAddMacVlan(t *testing.T) { if testing.Short() { return } tl := struct { name string mode string }{ name: "tstVlan", mode: "private", } masterLink := testLink{"tstEth", "dummy"} addLink(t, masterLink.name, masterLink.linkType) defer deleteLink(t, masterLink.name) if err := NetworkLinkAddMacVlan(masterLink.name, tl.name, tl.mode); err != nil { t.Fatalf("Unable to create %#v MAC VLAN interface: %s", tl, err) } readLink(t, tl.name) } func TestNetworkLinkAddMacVtap(t *testing.T) { if testing.Short() { return } tl := struct { name string mode string }{ name: "tstVtap", mode: "private", } masterLink := testLink{"tstEth", "dummy"} addLink(t, masterLink.name, masterLink.linkType) defer deleteLink(t, masterLink.name) if err := NetworkLinkAddMacVtap(masterLink.name, tl.name, tl.mode); err != nil { t.Fatalf("Unable to create %#v MAC VTAP interface: %s", tl, err) } readLink(t, tl.name) } func TestAddDelNetworkIp(t *testing.T) { if testing.Short() { return } ifaceName := "lo" ip := net.ParseIP("127.0.1.1") mask := net.IPv4Mask(255, 255, 255, 255) ipNet := &net.IPNet{IP: ip, Mask: mask} iface, err := net.InterfaceByName(ifaceName) if err != nil { t.Skip("No 'lo' interface; skipping tests") } if err := NetworkLinkAddIp(iface, ip, ipNet); err != nil { t.Fatalf("Could not add IP address %s to interface %#v: %s", ip.String(), iface, err) } if !ipAssigned(iface, ip) { t.Fatalf("Could not locate address '%s' in lo address list.", ip.String()) } if err := NetworkLinkDelIp(iface, ip, ipNet); err != nil { t.Fatalf("Could not delete IP address %s from interface %#v: %s", ip.String(), iface, err) } if ipAssigned(iface, ip) { t.Fatalf("Located address '%s' in lo address list after removal.", ip.String()) } } func TestAddRouteSourceSelection(t *testing.T) { tstIp := "127.1.1.1" tl := testLink{name: "tstEth", linkType: "dummy"} addLink(t, tl.name, tl.linkType) defer deleteLink(t, tl.name) ip := net.ParseIP(tstIp) mask := net.IPv4Mask(255, 255, 255, 255) ipNet := &net.IPNet{IP: ip, Mask: mask} iface, err := net.InterfaceByName(tl.name) if err != nil { t.Fatalf("Lost created link %#v", tl) } if err := NetworkLinkAddIp(iface, ip, ipNet); err != nil { t.Fatalf("Could not add IP address %s to interface %#v: %s", ip.String(), iface, err) } upLink(t, tl.name) defer downLink(t, tl.name) if err := AddRoute("127.0.0.0/8", tstIp, "", tl.name); err != nil { t.Fatalf("Failed to add route with source address") } } func TestCreateVethPair(t *testing.T) { if testing.Short() { return } var ( name1 = "veth1" name2 = "veth2" ) if err := NetworkCreateVethPair(name1, name2, 0); err != nil { t.Fatalf("Could not create veth pair %s %s: %s", name1, name2, err) } defer NetworkLinkDel(name1) readLink(t, name1) readLink(t, name2) } // // netlink package tests which do not use RTNETLINK // func TestCreateBridgeWithMac(t *testing.T) { if testing.Short() { return } name := "testbridge" if err := CreateBridge(name, true); err != nil { t.Fatal(err) } if _, err := net.InterfaceByName(name); err != nil { t.Fatal(err) } // cleanup and tests if err := DeleteBridge(name); err != nil { t.Fatal(err) } if _, err := net.InterfaceByName(name); err == nil { t.Fatalf("expected error getting interface because %s bridge was deleted", name) } } func TestSetMacAddress(t *testing.T) { if testing.Short() { return } name := "testmac" mac := randMacAddr() if err := NetworkLinkAdd(name, "bridge"); err != nil { t.Fatal(err) } defer NetworkLinkDel(name) if err := SetMacAddress(name, mac); err != nil { t.Fatal(err) } iface, err := net.InterfaceByName(name) if err != nil { t.Fatal(err) } if iface.HardwareAddr.String() != mac { t.Fatalf("mac address %q does not match %q", iface.HardwareAddr, mac) } } ================================================ FILE: vendor/github.com/docker/libcontainer/netlink/netlink_unsupported.go ================================================ // +build !linux package netlink import ( "errors" "net" ) var ( ErrNotImplemented = errors.New("not implemented") ) func NetworkGetRoutes() ([]Route, error) { return nil, ErrNotImplemented } func NetworkLinkAdd(name string, linkType string) error { return ErrNotImplemented } func NetworkLinkDel(name string) error { return ErrNotImplemented } func NetworkLinkUp(iface *net.Interface) error { return ErrNotImplemented } func NetworkLinkAddIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error { return ErrNotImplemented } func NetworkLinkDelIp(iface *net.Interface, ip net.IP, ipNet *net.IPNet) error { return ErrNotImplemented } func AddRoute(destination, source, gateway, device string) error { return ErrNotImplemented } func AddDefaultGw(ip, device string) error { return ErrNotImplemented } func NetworkSetMTU(iface *net.Interface, mtu int) error { return ErrNotImplemented } func NetworkSetTxQueueLen(iface *net.Interface, txQueueLen int) error { return ErrNotImplemented } func NetworkCreateVethPair(name1, name2 string, txQueueLen int) error { return ErrNotImplemented } func NetworkChangeName(iface *net.Interface, newName string) error { return ErrNotImplemented } func NetworkSetNsFd(iface *net.Interface, fd int) error { return ErrNotImplemented } func NetworkSetNsPid(iface *net.Interface, nspid int) error { return ErrNotImplemented } func NetworkSetMaster(iface, master *net.Interface) error { return ErrNotImplemented } func NetworkLinkDown(iface *net.Interface) error { return ErrNotImplemented } func CreateBridge(name string, setMacAddr bool) error { return ErrNotImplemented } func DeleteBridge(name string) error { return ErrNotImplemented } func AddToBridge(iface, master *net.Interface) error { return ErrNotImplemented } ================================================ FILE: vendor/github.com/docker/libcontainer/network_linux.go ================================================ // +build linux package libcontainer import ( "fmt" "io/ioutil" "net" "path/filepath" "strconv" "strings" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/netlink" "github.com/docker/libcontainer/utils" ) 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//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 { iface, err := net.InterfaceByName("lo") if err != nil { return err } return netlink.NetworkLinkUp(iface) } 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) { bridge, err := net.InterfaceByName(n.Bridge) if err != nil { return err } host, err := net.InterfaceByName(n.HostInterfaceName) if err != nil { return err } if err := netlink.DelFromBridge(host, bridge); err != nil { return err } return nil } // attach a container network interface to an external network func (v *veth) attach(n *configs.Network) (err error) { bridge, err := net.InterfaceByName(n.Bridge) if err != nil { return err } host, err := net.InterfaceByName(n.HostInterfaceName) if err != nil { return err } if err := netlink.AddToBridge(host, bridge); err != nil { return err } if err := netlink.NetworkSetMTU(host, n.Mtu); err != nil { return err } if n.HairpinMode { if err := netlink.SetHairpinMode(host, true); err != nil { return err } } if err := netlink.NetworkLinkUp(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 defer func() { if err != nil { netlink.NetworkLinkDel(n.HostInterfaceName) netlink.NetworkLinkDel(n.TempVethPeerName) } }() if n.Bridge == "" { return fmt.Errorf("bridge is not specified") } if err := netlink.NetworkCreateVethPair(n.HostInterfaceName, n.TempVethPeerName, n.TxQueueLen); err != nil { return err } if err := v.attach(&n.Network); err != nil { return err } child, err := net.InterfaceByName(n.TempVethPeerName) if err != nil { return err } return netlink.NetworkSetNsPid(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 := net.InterfaceByName(peer) if err != nil { return err } if err := netlink.NetworkLinkDown(child); err != nil { return err } if err := netlink.NetworkChangeName(child, config.Name); err != nil { return err } // get the interface again after we changed the name as the index also changes. if child, err = net.InterfaceByName(config.Name); err != nil { return err } if config.MacAddress != "" { if err := netlink.NetworkSetMacAddress(child, config.MacAddress); err != nil { return err } } ip, ipNet, err := net.ParseCIDR(config.Address) if err != nil { return err } if err := netlink.NetworkLinkAddIp(child, ip, ipNet); err != nil { return err } if config.IPv6Address != "" { if ip, ipNet, err = net.ParseCIDR(config.IPv6Address); err != nil { return err } if err := netlink.NetworkLinkAddIp(child, ip, ipNet); err != nil { return err } } if err := netlink.NetworkSetMTU(child, config.Mtu); err != nil { return err } if err := netlink.NetworkLinkUp(child); err != nil { return err } if config.Gateway != "" { if err := netlink.AddDefaultGw(config.Gateway, config.Name); err != nil { return err } } if config.IPv6Gateway != "" { if err := netlink.AddDefaultGw(config.IPv6Gateway, config.Name); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/notify_linux.go ================================================ // +build linux package libcontainer import ( "fmt" "io/ioutil" "os" "path/filepath" "syscall" ) const oomCgroupName = "memory" // notifyOnOOM returns channel on which you can expect event about OOM, // if process died without OOM this channel will be closed. // s is current *libcontainer.State for container. func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) { dir := paths[oomCgroupName] if dir == "" { return nil, fmt.Errorf("There is no path for %q in state", oomCgroupName) } oomControl, err := os.Open(filepath.Join(dir, "memory.oom_control")) if err != nil { return nil, err } fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0) if syserr != 0 { oomControl.Close() return nil, syserr } eventfd := os.NewFile(fd, "eventfd") eventControlPath := filepath.Join(dir, "cgroup.event_control") data := fmt.Sprintf("%d %d", eventfd.Fd(), oomControl.Fd()) if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil { eventfd.Close() oomControl.Close() return nil, err } ch := make(chan struct{}) go func() { defer func() { close(ch) eventfd.Close() oomControl.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 } ================================================ FILE: vendor/github.com/docker/libcontainer/notify_linux_test.go ================================================ // +build linux package libcontainer import ( "encoding/binary" "fmt" "io/ioutil" "os" "path/filepath" "syscall" "testing" "time" ) func TestNotifyOnOOM(t *testing.T) { memoryPath, err := ioutil.TempDir("", "testnotifyoom-") if err != nil { t.Fatal(err) } oomPath := filepath.Join(memoryPath, "memory.oom_control") eventPath := filepath.Join(memoryPath, "cgroup.event_control") if err := ioutil.WriteFile(oomPath, []byte{}, 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(eventPath, []byte{}, 0700); err != nil { t.Fatal(err) } var eventFd, oomControlFd int paths := map[string]string{ "memory": memoryPath, } ooms, err := notifyOnOOM(paths) if err != nil { t.Fatal("expected no error, got:", err) } data, err := ioutil.ReadFile(eventPath) if err != nil { t.Fatal("couldn't read event control file:", err) } if _, err := fmt.Sscanf(string(data), "%d %d", &eventFd, &oomControlFd); err != nil { t.Fatalf("invalid control data %q: %s", data, err) } // re-open the eventfd efd, err := syscall.Dup(eventFd) if err != nil { t.Fatal("unable to reopen eventfd:", err) } defer syscall.Close(efd) if err != nil { t.Fatal("unable to dup event fd:", err) } buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, 1) if _, err := syscall.Write(efd, buf); err != nil { t.Fatal("unable to write to eventfd:", err) } select { case <-ooms: case <-time.After(100 * time.Millisecond): t.Fatal("no notification on oom channel after 100ms") } // simulate what happens when a cgroup is destroyed by cleaning up and then // writing to the eventfd. if err := os.RemoveAll(memoryPath); err != nil { t.Fatal(err) } if _, err := syscall.Write(efd, buf); err != nil { t.Fatal("unable to write to eventfd:", err) } // give things a moment to shut down select { case _, ok := <-ooms: if ok { t.Fatal("expected no oom to be triggered") } case <-time.After(100 * time.Millisecond): } if _, _, err := syscall.Syscall(syscall.SYS_FCNTL, uintptr(oomControlFd), syscall.F_GETFD, 0); err != syscall.EBADF { t.Error("expected oom control to be closed") } if _, _, err := syscall.Syscall(syscall.SYS_FCNTL, uintptr(eventFd), syscall.F_GETFD, 0); err != syscall.EBADF { t.Error("expected event fd to be closed") } } ================================================ FILE: vendor/github.com/docker/libcontainer/nsenter/README.md ================================================ ## 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 Docker execdriver, so every time before we call `execdriver.Exec()`, that C code would run. `nsexec()` will first check the environment variable `_LIBCONTAINER_INITPID` which will give the process of the container that should be joined. Namespaces fd will be found from `/proc/[pid]/ns` and set by `setns` syscall. And then get the pipe number from `_LIBCONTAINER_INITPIPE`, error message could be transfered through it. If tty is added, `_LIBCONTAINER_CONSOLE_PATH` will have value and start a console for output. Finally, `nsexec()` will clone a child process , exit the parent process and let the Go runtime take over. ================================================ FILE: vendor/github.com/docker/libcontainer/nsenter/nsenter.go ================================================ // +build linux,!gccgo package nsenter /* #cgo CFLAGS: -Wall extern void nsexec(); void __attribute__((constructor)) init(void) { nsexec(); } */ import "C" ================================================ FILE: vendor/github.com/docker/libcontainer/nsenter/nsenter_gccgo.go ================================================ // +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() } } ================================================ FILE: vendor/github.com/docker/libcontainer/nsenter/nsenter_test.go ================================================ package nsenter import ( "encoding/json" "fmt" "os" "os/exec" "strings" "testing" ) type pid struct { Pid int `json:"Pid"` } func TestNsenterAlivePid(t *testing.T) { args := []string{"nsenter-exec"} r, w, err := os.Pipe() if err != nil { t.Fatalf("failed to create pipe %v", err) } cmd := &exec.Cmd{ Path: os.Args[0], Args: args, ExtraFiles: []*os.File{w}, Env: []string{fmt.Sprintf("_LIBCONTAINER_INITPID=%d", os.Getpid()), "_LIBCONTAINER_INITPIPE=3"}, } if err := cmd.Start(); err != nil { t.Fatalf("nsenter failed to start %v", err) } w.Close() decoder := json.NewDecoder(r) var pid *pid if err := decoder.Decode(&pid); err != nil { t.Fatalf("%v", err) } if err := cmd.Wait(); err != nil { t.Fatalf("nsenter exits with a non-zero exit status") } p, err := os.FindProcess(pid.Pid) if err != nil { t.Fatalf("%v", err) } p.Wait() } func TestNsenterInvalidPid(t *testing.T) { args := []string{"nsenter-exec"} cmd := &exec.Cmd{ Path: os.Args[0], Args: args, Env: []string{"_LIBCONTAINER_INITPID=-1"}, } err := cmd.Run() if err == nil { t.Fatal("nsenter exits with a zero exit status") } } func TestNsenterDeadPid(t *testing.T) { dead_cmd := exec.Command("true") if err := dead_cmd.Run(); err != nil { t.Fatal(err) } args := []string{"nsenter-exec"} cmd := &exec.Cmd{ Path: os.Args[0], Args: args, Env: []string{fmt.Sprintf("_LIBCONTAINER_INITPID=%d", dead_cmd.Process.Pid)}, } err := cmd.Run() if err == nil { t.Fatal("nsenter exits with a zero exit status") } } func init() { if strings.HasPrefix(os.Args[0], "nsenter-") { os.Exit(0) } return } ================================================ FILE: vendor/github.com/docker/libcontainer/nsenter/nsenter_unsupported.go ================================================ // +build !linux !cgo package nsenter import "C" ================================================ FILE: vendor/github.com/docker/libcontainer/nsenter/nsexec.c ================================================ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include /* All arguments should be above stack, because it grows down */ struct clone_arg { /* * Reserve some space for clone() to locate arguments * and retcode in this place */ char stack[4096] __attribute__ ((aligned(8))); char stack_ptr[0]; jmp_buf *env; }; #define pr_perror(fmt, ...) fprintf(stderr, "nsenter: " fmt ": %m\n", ##__VA_ARGS__) static int child_func(void *_arg) { struct clone_arg *arg = (struct clone_arg *)_arg; longjmp(*arg->env, 1); } // Use raw setns syscall for versions of glibc that don't include it (namely glibc-2.12) #if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14 #define _GNU_SOURCE #include "syscall.h" #ifdef SYS_setns int setns(int fd, int nstype) { return syscall(SYS_setns, fd, nstype); } #endif #endif static int clone_parent(jmp_buf * env) __attribute__ ((noinline)); static int clone_parent(jmp_buf * env) { struct clone_arg ca; int child; ca.env = env; child = clone(child_func, ca.stack_ptr, CLONE_PARENT | SIGCHLD, &ca); return child; } void nsexec() { char *namespaces[] = { "ipc", "uts", "net", "pid", "mnt" }; const int num = sizeof(namespaces) / sizeof(char *); jmp_buf env; char buf[PATH_MAX], *val; int i, tfd, child, len, pipenum, consolefd = -1; pid_t pid; char *console; val = getenv("_LIBCONTAINER_INITPID"); if (val == NULL) return; pid = atoi(val); snprintf(buf, sizeof(buf), "%d", pid); if (strcmp(val, buf)) { pr_perror("Unable to parse _LIBCONTAINER_INITPID"); exit(1); } val = getenv("_LIBCONTAINER_INITPIPE"); if (val == NULL) { pr_perror("Child pipe not found"); exit(1); } pipenum = atoi(val); snprintf(buf, sizeof(buf), "%d", pipenum); if (strcmp(val, buf)) { pr_perror("Unable to parse _LIBCONTAINER_INITPIPE"); exit(1); } console = getenv("_LIBCONTAINER_CONSOLE_PATH"); if (console != NULL) { consolefd = open(console, O_RDWR); if (consolefd < 0) { pr_perror("Failed to open console %s", console); exit(1); } } /* Check that the specified process exists */ snprintf(buf, PATH_MAX - 1, "/proc/%d/ns", pid); tfd = open(buf, O_DIRECTORY | O_RDONLY); if (tfd == -1) { pr_perror("Failed to open \"%s\"", buf); exit(1); } for (i = 0; i < num; i++) { struct stat st; int fd; /* Symlinks on all namespaces exist for dead processes, but they can't be opened */ if (fstatat(tfd, namespaces[i], &st, AT_SYMLINK_NOFOLLOW) == -1) { // Ignore nonexistent namespaces. if (errno == ENOENT) continue; } fd = openat(tfd, namespaces[i], O_RDONLY); if (fd == -1) { pr_perror("Failed to open ns file %s for ns %s", buf, namespaces[i]); exit(1); } // Set the namespace. if (setns(fd, 0) == -1) { pr_perror("Failed to setns for %s", namespaces[i]); exit(1); } close(fd); } if (setjmp(env) == 1) { // Child if (setsid() == -1) { pr_perror("setsid failed"); exit(1); } if (consolefd != -1) { if (ioctl(consolefd, TIOCSCTTY, 0) == -1) { pr_perror("ioctl TIOCSCTTY failed"); exit(1); } if (dup3(consolefd, STDIN_FILENO, 0) != STDIN_FILENO) { pr_perror("Failed to dup 0"); exit(1); } if (dup3(consolefd, STDOUT_FILENO, 0) != STDOUT_FILENO) { pr_perror("Failed to dup 1"); exit(1); } if (dup3(consolefd, STDERR_FILENO, 0) != STDERR_FILENO) { pr_perror("Failed to dup 2"); exit(1); } } // Finish executing, let the Go runtime take over. return; } // Parent // We must fork to actually enter the PID namespace, use CLONE_PARENT // so the child can have the right parent, and we don't need to forward // the child's exit code or resend its death signal. child = clone_parent(&env); if (child < 0) { pr_perror("Unable to fork"); exit(1); } len = snprintf(buf, sizeof(buf), "{ \"pid\" : %d }\n", child); if (write(pipenum, buf, len) != len) { pr_perror("Unable to send a child pid"); kill(child, SIGKILL); exit(1); } exit(0); } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/Makefile ================================================ all: go build -o nsinit . ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/README.md ================================================ ## nsinit `nsinit` is a cli application which demonstrates the use of libcontainer. It is able to spawn new containers or join existing containers. ### How to build? First add the `libcontainer/vendor` into your GOPATH. It's because libcontainer vendors all its dependencies, so it can be built predictably. ``` export GOPATH=$GOPATH:/your/path/to/libcontainer/vendor ``` Then get into the nsinit folder and get the imported file. Use `make` command to make the nsinit binary. ``` cd libcontainer/nsinit go get make ``` We have finished compiling the nsinit package, but a root filesystem must be provided for use along with a container configuration file. Choose a proper place to run your container. For example we use `/busybox`. ``` mkdir /busybox curl -sSL 'https://github.com/jpetazzo/docker-busybox/raw/buildroot-2014.11/rootfs.tar' | tar -xC /busybox ``` Then you may need to write a configuration file named `container.json` in the `/busybox` folder. Environment, networking, and different capabilities for the container are specified in this file. The configuration is used for each process executed inside the container. See the `sample_configs` folder for examples of what the container configuration should look like. ``` cp libcontainer/sample_configs/minimal.json /busybox/container.json cd /busybox ``` You can customize `container.json` per your needs. After that, nsinit is ready to work. To execute `/bin/bash` in the current directory as a container just run the following **as root**: ```bash nsinit exec --tty --config container.json /bin/bash ``` If you wish to spawn another process inside the container while your current bash session is running, run the same command again to get another bash shell (or change the command). If the original process (PID 1) dies, all other processes spawned inside the container will be killed and the namespace will be removed. You can identify if a process is running in a container by looking to see if `state.json` is in the root of the directory. You may also specify an alternate root directory from where the `container.json` file is read and where the `state.json` file will be saved. ### How to use? Currently nsinit has 9 commands. Type `nsinit -h` to list all of them. And for every alternative command, you can also use `--help` to get more detailed help documents. For example, `nsinit config --help`. `nsinit` cli application is implemented using [cli.go](https://github.com/codegangsta/cli). Lots of details are handled in cli.go, so the implementation of `nsinit` itself is very clean and clear. * **config** It will generate a standard configuration file for a container. By default, it will generate as the template file in [config.go](https://github.com/docker/libcontainer/blob/f28dff5539855bac2adbc5699f57f84349605b5f/nsinit/config.go#L234). It will modify the template if you have specified some configuration by options. * **exec** Starts a container and execute a new command inside it. Besides common options, it has some special options as below. - `--tty,-t`: allocate a TTY to the container. - `--config`: you can specify a configuration file. By default, it will use template configuration. - `--id`: specify the ID for a container. By default, the id is "nsinit". - `--user,-u`: set the user, uid, and/or gid for the process. By default the value is "root". - `--cwd`: set the current working dir. - `--env`: set environment variables for the process. * **init** It's an internal command that is called inside the container's namespaces to initialize the namespace and exec the user's process. It should not be called externally. * **oom** Display oom notifications for a container, you should specify container id. * **pause** Pause the container's processes, you should specify container id. It will use cgroup freeze subsystem to help. * **unpause** Unpause the container's processes. Same with `pause`. * **stats** Display statistics for the container, it will mainly show cgroup and network statistics. * **state** Get the container's current state. You can also read the state from `state.json` in your container_id folder. * **checkpoint** Checkpoint a running container. You can read [this](http://criu.org/Advanced_usage) for more detailed information about options. - `--id`: specify the ID for a container. By default, the id is "nsinit". - `--image-path`: path for saving criu image files. You must specify this option. - `--work-path`: path for saving work files and logs. By default it will generate a folder named "criu.work" in root directory. - `--leave-running`: leave the process running after checkpointing. - `--tcp-established`: allow open tcp connections. - `--ext-unix-sk`: allow external unix sockets. - `--shell-job`: allow shell jobs. - `--page-server`: ADDRESS:PORT of the page server. The dump image can be sent to a criu page server if we have a page server. * **restore** Restore a container from a previous checkpoint. Options are almost the same with checkpoint and `--image-path` must be specified. * **help, h** Shows a list of commands or help for one command. ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/checkpoint.go ================================================ package main import ( "fmt" "github.com/codegangsta/cli" "github.com/docker/libcontainer" "strconv" "strings" ) var checkpointCommand = cli.Command{ Name: "checkpoint", Usage: "checkpoint a running container", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, 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.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"}, }, Action: func(context *cli.Context) { imagePath := context.String("image-path") if imagePath == "" { fatal(fmt.Errorf("The --image-path option isn't specified")) } container, err := getContainer(context) if err != nil { fatal(err) } // these are the mandatory criu options for a container criuOpts := &libcontainer.CriuOpts{ ImagesDirectory: imagePath, WorkDirectory: context.String("work-path"), LeaveRunning: context.Bool("leave-running"), TcpEstablished: context.Bool("tcp-established"), ExternalUnixConnections: context.Bool("ext-unix-sk"), ShellJob: context.Bool("shell-job"), } // 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")) } port_int, err := strconv.Atoi(addressPort[1]) if err != nil { fatal(fmt.Errorf("Invalid port number")) } criuOpts.PageServer = libcontainer.CriuPageServerInfo{ Address: addressPort[0], Port: int32(port_int), } } if err := container.Checkpoint(criuOpts); err != nil { fatal(err) } }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/config.go ================================================ package main import ( "bytes" "encoding/json" "io" "math" "os" "path/filepath" "strings" "syscall" "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/utils" ) const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV var createFlags = []cli.Flag{ cli.BoolFlag{Name: "cgroup", Usage: "mount the cgroup data for the container"}, cli.BoolFlag{Name: "read-only", Usage: "set the container's rootfs as read-only"}, cli.IntFlag{Name: "cpushares", Usage: "set the cpushares for the container"}, cli.IntFlag{Name: "memory-limit", Usage: "set the memory limit for the container"}, cli.IntFlag{Name: "memory-swap", Usage: "set the memory swap limit for the container"}, cli.IntFlag{Name: "parent-death-signal", Usage: "set the signal that will be delivered to the process in case the parent dies"}, cli.IntFlag{Name: "userns-root-uid", Usage: "set the user namespace root uid"}, cli.IntFlag{Name: "veth-mtu", Usage: "veth mtu"}, cli.StringFlag{Name: "apparmor-profile", Usage: "set the apparmor profile"}, cli.StringFlag{Name: "cpuset-cpus", Usage: "set the cpuset cpus"}, cli.StringFlag{Name: "cpuset-mems", Usage: "set the cpuset mems"}, cli.StringFlag{Name: "hostname", Value: "nsinit", Usage: "hostname value for the container"}, cli.StringFlag{Name: "ipc", Value: "", Usage: "ipc namespace"}, cli.StringFlag{Name: "mnt", Value: "", Usage: "mount namespace"}, cli.StringFlag{Name: "mount-label", Usage: "set the mount label"}, cli.StringFlag{Name: "net", Value: "", Usage: "network namespace"}, cli.StringFlag{Name: "pid", Value: "", Usage: "pid namespace"}, cli.StringFlag{Name: "process-label", Usage: "set the process label"}, cli.StringFlag{Name: "rootfs", Usage: "set the rootfs"}, cli.StringFlag{Name: "security", Value: "", Usage: "set the security profile (high, medium, low)"}, cli.StringFlag{Name: "uts", Value: "", Usage: "uts namespace"}, cli.StringFlag{Name: "veth-address", Usage: "veth ip address"}, cli.StringFlag{Name: "veth-bridge", Usage: "veth bridge"}, cli.StringFlag{Name: "veth-gateway", Usage: "veth gateway address"}, cli.StringSliceFlag{Name: "bind", Value: &cli.StringSlice{}, Usage: "add bind mounts to the container"}, cli.StringSliceFlag{Name: "sysctl", Value: &cli.StringSlice{}, Usage: "set system properties in the container"}, cli.StringSliceFlag{Name: "tmpfs", Value: &cli.StringSlice{}, Usage: "add tmpfs mounts to the container"}, cli.StringSliceFlag{Name: "groups", Value: &cli.StringSlice{}, Usage: "add additional groups"}, } var configCommand = cli.Command{ Name: "config", Usage: "generate a standard configuration file for a container", Flags: append([]cli.Flag{ cli.StringFlag{Name: "file,f", Value: "stdout", Usage: "write the configuration to the specified file"}, }, createFlags...), Action: func(context *cli.Context) { template := getTemplate() modify(template, context) data, err := json.MarshalIndent(template, "", "\t") if err != nil { fatal(err) } var f *os.File filePath := context.String("file") switch filePath { case "stdout", "": f = os.Stdout default: if f, err = os.Create(filePath); err != nil { fatal(err) } defer f.Close() } if _, err := io.Copy(f, bytes.NewBuffer(data)); err != nil { fatal(err) } }, } func modify(config *configs.Config, context *cli.Context) { config.ParentDeathSignal = context.Int("parent-death-signal") config.Readonlyfs = context.Bool("read-only") config.Cgroups.CpusetCpus = context.String("cpuset-cpus") config.Cgroups.CpusetMems = context.String("cpuset-mems") config.Cgroups.CpuShares = int64(context.Int("cpushares")) config.Cgroups.Memory = int64(context.Int("memory-limit")) config.Cgroups.MemorySwap = int64(context.Int("memory-swap")) config.AppArmorProfile = context.String("apparmor-profile") config.ProcessLabel = context.String("process-label") config.MountLabel = context.String("mount-label") rootfs := context.String("rootfs") if rootfs != "" { config.Rootfs = rootfs } userns_uid := context.Int("userns-root-uid") if userns_uid != 0 { config.Namespaces.Add(configs.NEWUSER, "") config.UidMappings = []configs.IDMap{ {ContainerID: 0, HostID: userns_uid, Size: 1}, {ContainerID: 1, HostID: 1, Size: userns_uid - 1}, {ContainerID: userns_uid + 1, HostID: userns_uid + 1, Size: math.MaxInt32 - userns_uid}, } config.GidMappings = []configs.IDMap{ {ContainerID: 0, HostID: userns_uid, Size: 1}, {ContainerID: 1, HostID: 1, Size: userns_uid - 1}, {ContainerID: userns_uid + 1, HostID: userns_uid + 1, Size: math.MaxInt32 - userns_uid}, } for _, node := range config.Devices { node.Uid = uint32(userns_uid) node.Gid = uint32(userns_uid) } } config.SystemProperties = make(map[string]string) for _, sysProp := range context.StringSlice("sysctl") { parts := strings.SplitN(sysProp, "=", 2) if len(parts) != 2 { logrus.Fatalf("invalid system property %s", sysProp) } config.SystemProperties[parts[0]] = parts[1] } for _, group := range context.StringSlice("groups") { config.AdditionalGroups = append(config.AdditionalGroups, group) } for _, rawBind := range context.StringSlice("bind") { mount := &configs.Mount{ Device: "bind", Flags: syscall.MS_BIND | syscall.MS_REC, } parts := strings.SplitN(rawBind, ":", 3) switch len(parts) { default: logrus.Fatalf("invalid bind mount %s", rawBind) case 2: mount.Source, mount.Destination = parts[0], parts[1] case 3: mount.Source, mount.Destination = parts[0], parts[1] switch parts[2] { case "ro": mount.Flags |= syscall.MS_RDONLY case "rw": default: logrus.Fatalf("invalid bind mount mode %s", parts[2]) } } config.Mounts = append(config.Mounts, mount) } for _, tmpfs := range context.StringSlice("tmpfs") { config.Mounts = append(config.Mounts, &configs.Mount{ Device: "tmpfs", Destination: tmpfs, Flags: syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV, }) } for flag, value := range map[string]configs.NamespaceType{ "net": configs.NEWNET, "mnt": configs.NEWNS, "pid": configs.NEWPID, "ipc": configs.NEWIPC, "uts": configs.NEWUTS, } { switch v := context.String(flag); v { case "host": config.Namespaces.Remove(value) case "", "private": if !config.Namespaces.Contains(value) { config.Namespaces.Add(value, "") } if flag == "net" { config.Networks = []*configs.Network{ { Type: "loopback", Address: "127.0.0.1/0", Gateway: "localhost", }, } } if flag == "uts" { config.Hostname = context.String("hostname") } default: config.Namespaces.Remove(value) config.Namespaces.Add(value, v) } } if bridge := context.String("veth-bridge"); bridge != "" { hostName, err := utils.GenerateRandomName("veth", 7) if err != nil { logrus.Fatal(err) } network := &configs.Network{ Type: "veth", Name: "eth0", Bridge: bridge, Address: context.String("veth-address"), Gateway: context.String("veth-gateway"), Mtu: context.Int("veth-mtu"), HostInterfaceName: hostName, } config.Networks = append(config.Networks, network) } if context.Bool("cgroup") { config.Mounts = append(config.Mounts, &configs.Mount{ Destination: "/sys/fs/cgroup", Device: "cgroup", }) } modifySecurityProfile(context, config) } func modifySecurityProfile(context *cli.Context, config *configs.Config) { profileName := context.String("security") if profileName == "" { return } profile := profiles[profileName] if profile == nil { logrus.Fatalf("invalid profile name %q", profileName) } config.Rlimits = profile.Rlimits config.Capabilities = profile.Capabilities config.Seccomp = profile.Seccomp config.AppArmorProfile = profile.ApparmorProfile config.MountLabel = profile.MountLabel config.ProcessLabel = profile.ProcessLabel } func getTemplate() *configs.Config { cwd, err := os.Getwd() if err != nil { panic(err) } return &configs.Config{ Rootfs: cwd, ParentDeathSignal: int(syscall.SIGKILL), Capabilities: []string{ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE", }, Namespaces: configs.Namespaces([]configs.Namespace{ {Type: configs.NEWNS}, {Type: configs.NEWUTS}, {Type: configs.NEWIPC}, {Type: configs.NEWPID}, {Type: configs.NEWNET}, }), Cgroups: &configs.Cgroup{ Name: filepath.Base(cwd), Parent: "nsinit", AllowAllDevices: false, AllowedDevices: configs.DefaultAllowedDevices, }, Devices: configs.DefaultAutoCreatedDevices, MaskPaths: []string{ "/proc/kcore", }, ReadonlyPaths: []string{ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus", }, 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, }, }, } } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/exec.go ================================================ package main import ( "os" "os/exec" "os/signal" "syscall" "github.com/codegangsta/cli" "github.com/docker/libcontainer" "github.com/docker/libcontainer/utils" ) var standardEnvironment = &cli.StringSlice{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOSTNAME=nsinit", "TERM=xterm", } var execCommand = cli.Command{ Name: "exec", Usage: "execute a new command inside a container", Action: execAction, Flags: append([]cli.Flag{ cli.BoolFlag{Name: "tty,t", Usage: "allocate a TTY to the container"}, cli.BoolFlag{Name: "systemd", Usage: "Use systemd for managing cgroups, if available"}, cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, cli.StringFlag{Name: "config", Value: "", Usage: "path to the configuration file"}, cli.StringFlag{Name: "user,u", Value: "root", Usage: "set the user, uid, and/or gid for the process"}, cli.StringFlag{Name: "cwd", Value: "", Usage: "set the current working dir"}, cli.StringSliceFlag{Name: "env", Value: standardEnvironment, Usage: "set environment variables for the process"}, }, createFlags...), } func execAction(context *cli.Context) { factory, err := loadFactory(context) if err != nil { fatal(err) } config, err := loadConfig(context) if err != nil { fatal(err) } created := false container, err := factory.Load(context.String("id")) if err != nil { created = true if container, err = factory.Create(context.String("id"), config); err != nil { fatal(err) } } process := &libcontainer.Process{ Args: context.Args(), Env: context.StringSlice("env"), User: context.String("user"), Cwd: context.String("cwd"), Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, } rootuid, err := config.HostUID() if err != nil { fatal(err) } tty, err := newTty(context, process, rootuid) if err != nil { fatal(err) } if err := tty.attach(process); err != nil { fatal(err) } go handleSignals(process, tty) err = container.Start(process) if err != nil { tty.Close() if created { container.Destroy() } fatal(err) } status, err := process.Wait() if err != nil { exitError, ok := err.(*exec.ExitError) if ok { status = exitError.ProcessState } else { tty.Close() if created { container.Destroy() } fatal(err) } } if created { status, err := container.Status() if err != nil { tty.Close() fatal(err) } if status != libcontainer.Checkpointed { if err := container.Destroy(); err != nil { tty.Close() fatal(err) } } } tty.Close() os.Exit(utils.ExitStatus(status.Sys().(syscall.WaitStatus))) } func handleSignals(container *libcontainer.Process, tty *tty) { sigc := make(chan os.Signal, 10) signal.Notify(sigc) tty.resize() for sig := range sigc { switch sig { case syscall.SIGWINCH: tty.resize() default: container.Signal(sig) } } } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/init.go ================================================ package main import ( "runtime" "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" "github.com/docker/libcontainer" _ "github.com/docker/libcontainer/nsenter" ) var initCommand = cli.Command{ Name: "init", Usage: "runs the init process inside the namespace", Action: func(context *cli.Context) { logrus.SetLevel(logrus.DebugLevel) runtime.GOMAXPROCS(1) runtime.LockOSThread() factory, err := libcontainer.New("") if err != nil { fatal(err) } if err := factory.StartInitialization(); err != nil { fatal(err) } panic("This line should never been executed") }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/main.go ================================================ package main import ( "os" "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" ) func main() { app := cli.NewApp() app.Name = "nsinit" app.Version = "2" app.Author = "libcontainer maintainers" app.Flags = []cli.Flag{ cli.BoolFlag{Name: "debug", Usage: "enable debug output in the logs"}, cli.StringFlag{Name: "root", Value: "/var/run/nsinit", Usage: "root directory for containers"}, cli.StringFlag{Name: "log-file", Usage: "set the log file to output logs to"}, cli.StringFlag{Name: "criu", Value: "criu", Usage: "path to the criu binary for checkpoint and restore"}, } app.Commands = []cli.Command{ checkpointCommand, configCommand, execCommand, initCommand, oomCommand, pauseCommand, stateCommand, statsCommand, unpauseCommand, restoreCommand, } app.Before = func(context *cli.Context) error { if context.GlobalBool("debug") { logrus.SetLevel(logrus.DebugLevel) } if path := context.GlobalString("log-file"); path != "" { f, err := os.Create(path) if err != nil { return err } logrus.SetOutput(f) } return nil } if err := app.Run(os.Args); err != nil { logrus.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/oom.go ================================================ package main import ( "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" ) var oomCommand = cli.Command{ Name: "oom", Usage: "display oom notifications for a container", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, }, Action: func(context *cli.Context) { container, err := getContainer(context) if err != nil { logrus.Fatal(err) } n, err := container.NotifyOOM() if err != nil { logrus.Fatal(err) } for x := range n { // hack for calm down go1.4 gofmt _ = x logrus.Printf("OOM notification received") } }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/pause.go ================================================ package main import ( "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" ) var pauseCommand = cli.Command{ Name: "pause", Usage: "pause the container's processes", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, }, Action: func(context *cli.Context) { container, err := getContainer(context) if err != nil { logrus.Fatal(err) } if err = container.Pause(); err != nil { logrus.Fatal(err) } }, } var unpauseCommand = cli.Command{ Name: "unpause", Usage: "unpause the container's processes", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, }, Action: func(context *cli.Context) { container, err := getContainer(context) if err != nil { logrus.Fatal(err) } if err = container.Resume(); err != nil { logrus.Fatal(err) } }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/restore.go ================================================ package main import ( "fmt" "os" "os/exec" "syscall" "github.com/codegangsta/cli" "github.com/docker/libcontainer" "github.com/docker/libcontainer/utils" ) var restoreCommand = cli.Command{ Name: "restore", Usage: "restore a container from a previous checkpoint", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, 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"}, }, Action: func(context *cli.Context) { imagePath := context.String("image-path") if imagePath == "" { fatal(fmt.Errorf("The --image-path option isn't specified")) } var ( container libcontainer.Container err error ) factory, err := loadFactory(context) if err != nil { fatal(err) } config, err := loadConfig(context) if err != nil { fatal(err) } created := false container, err = factory.Load(context.String("id")) if err != nil { created = true if container, err = factory.Create(context.String("id"), config); err != nil { fatal(err) } } process := &libcontainer.Process{ Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, } //rootuid, err := config.HostUID() //if err != nil { //fatal(err) //} rootuid := 0 // XXX tty, err := newTty(context, process, rootuid) if err != nil { fatal(err) } if err := tty.attach(process); err != nil { fatal(err) } go handleSignals(process, tty) err = container.Restore(process, &libcontainer.CriuOpts{ ImagesDirectory: imagePath, WorkDirectory: context.String("work-path"), TcpEstablished: context.Bool("tcp-established"), ExternalUnixConnections: context.Bool("ext-unix-sk"), ShellJob: context.Bool("shell-job"), }) if err != nil { tty.Close() if created { container.Destroy() } fatal(err) } status, err := process.Wait() if err != nil { exitError, ok := err.(*exec.ExitError) if ok { status = exitError.ProcessState } else { tty.Close() if created { container.Destroy() } fatal(err) } } if created { status, err := container.Status() if err != nil { tty.Close() fatal(err) } if status != libcontainer.Checkpointed { if err := container.Destroy(); err != nil { tty.Close() fatal(err) } } } tty.Close() os.Exit(utils.ExitStatus(status.Sys().(syscall.WaitStatus))) }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/security.go ================================================ package main import ( "syscall" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/system" ) var profiles = map[string]*securityProfile{ "high": highProfile, "medium": mediumProfile, "low": lowProfile, } type securityProfile struct { Capabilities []string `json:"capabilities"` ApparmorProfile string `json:"apparmor_profile"` MountLabel string `json:"mount_label"` ProcessLabel string `json:"process_label"` Rlimits []configs.Rlimit `json:"rlimits"` Seccomp *configs.Seccomp `json:"seccomp"` } // this should be a runtime config that is not able to do things like apt-get or yum install. var highProfile = &securityProfile{ Capabilities: []string{ "NET_BIND_SERVICE", "KILL", "AUDIT_WRITE", }, Rlimits: []configs.Rlimit{ { Type: syscall.RLIMIT_NOFILE, Hard: 1024, Soft: 1024, }, }, // http://man7.org/linux/man-pages/man2/syscalls.2.html Seccomp: &configs.Seccomp{ Syscalls: []*configs.Syscall{ { Value: syscall.SYS_CAPSET, // http://man7.org/linux/man-pages/man2/capset.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_UNSHARE, // http://man7.org/linux/man-pages/man2/unshare.2.html Action: configs.Action(syscall.EPERM), }, { Value: int(system.SysSetns()), Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_MOUNT, // http://man7.org/linux/man-pages/man2/mount.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_UMOUNT2, // http://man7.org/linux/man-pages/man2/umount.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CREATE_MODULE, // http://man7.org/linux/man-pages/man2/create_module.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_DELETE_MODULE, // http://man7.org/linux/man-pages/man2/delete_module.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CHMOD, // http://man7.org/linux/man-pages/man2/chmod.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CHOWN, // http://man7.org/linux/man-pages/man2/chown.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_LINK, // http://man7.org/linux/man-pages/man2/link.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_LINKAT, // http://man7.org/linux/man-pages/man2/linkat.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_UNLINK, // http://man7.org/linux/man-pages/man2/unlink.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_UNLINKAT, // http://man7.org/linux/man-pages/man2/unlinkat.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CHROOT, // http://man7.org/linux/man-pages/man2/chroot.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_KEXEC_LOAD, // http://man7.org/linux/man-pages/man2/kexec_load.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_SETDOMAINNAME, // http://man7.org/linux/man-pages/man2/setdomainname.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_SETHOSTNAME, // http://man7.org/linux/man-pages/man2/sethostname.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CLONE, // http://man7.org/linux/man-pages/man2/clone.2.html Action: configs.Action(syscall.EPERM), Args: []*configs.Arg{ { Index: 0, // the glibc wrapper has the flags at arg2 but the raw syscall has flags at arg0 Value: syscall.CLONE_NEWUSER, Op: configs.MaskEqualTo, }, }, }, }, }, } // This is a medium level profile that should be able to do things like installing from // apt-get or yum. var mediumProfile = &securityProfile{ Capabilities: []string{ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "KILL", "AUDIT_WRITE", }, Rlimits: []configs.Rlimit{ { Type: syscall.RLIMIT_NOFILE, Hard: 1024, Soft: 1024, }, }, // http://man7.org/linux/man-pages/man2/syscalls.2.html Seccomp: &configs.Seccomp{ Syscalls: []*configs.Syscall{ { Value: syscall.SYS_UNSHARE, // http://man7.org/linux/man-pages/man2/unshare.2.html Action: configs.Action(syscall.EPERM), }, { Value: int(system.SysSetns()), Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_MOUNT, // http://man7.org/linux/man-pages/man2/mount.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_UMOUNT2, // http://man7.org/linux/man-pages/man2/umount.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CHROOT, // http://man7.org/linux/man-pages/man2/chroot.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CREATE_MODULE, // http://man7.org/linux/man-pages/man2/create_module.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_DELETE_MODULE, // http://man7.org/linux/man-pages/man2/delete_module.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_KEXEC_LOAD, // http://man7.org/linux/man-pages/man2/kexec_load.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_SETDOMAINNAME, // http://man7.org/linux/man-pages/man2/setdomainname.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_SETHOSTNAME, // http://man7.org/linux/man-pages/man2/sethostname.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CLONE, // http://man7.org/linux/man-pages/man2/clone.2.html Action: configs.Action(syscall.EPERM), Args: []*configs.Arg{ { Index: 0, // the glibc wrapper has the flags at arg2 but the raw syscall has flags at arg0 Value: syscall.CLONE_NEWUSER, Op: configs.MaskEqualTo, }, }, }, }, }, } var lowProfile = &securityProfile{ Capabilities: []string{ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "SETGID", "SETUID", "SYS_CHROOT", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "KILL", "AUDIT_WRITE", }, Rlimits: []configs.Rlimit{ { Type: syscall.RLIMIT_NOFILE, Hard: 1024, Soft: 1024, }, }, // http://man7.org/linux/man-pages/man2/syscalls.2.html Seccomp: &configs.Seccomp{ Syscalls: []*configs.Syscall{ { Value: syscall.SYS_UNSHARE, // http://man7.org/linux/man-pages/man2/unshare.2.html Action: configs.Action(syscall.EPERM), }, { Value: int(system.SysSetns()), Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_MOUNT, // http://man7.org/linux/man-pages/man2/mount.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_UMOUNT2, // http://man7.org/linux/man-pages/man2/umount.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CREATE_MODULE, // http://man7.org/linux/man-pages/man2/create_module.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_DELETE_MODULE, // http://man7.org/linux/man-pages/man2/delete_module.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_KEXEC_LOAD, // http://man7.org/linux/man-pages/man2/kexec_load.2.html Action: configs.Action(syscall.EPERM), }, { Value: syscall.SYS_CLONE, // http://man7.org/linux/man-pages/man2/clone.2.html Action: configs.Action(syscall.EPERM), Args: []*configs.Arg{ { Index: 0, // the glibc wrapper has the flags at arg2 but the raw syscall has flags at arg0 Value: syscall.CLONE_NEWUSER, Op: configs.MaskEqualTo, }, }, }, }, }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/state.go ================================================ package main import ( "encoding/json" "fmt" "github.com/codegangsta/cli" ) var stateCommand = cli.Command{ Name: "state", Usage: "get the container's current state", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, }, Action: func(context *cli.Context) { container, err := getContainer(context) if err != nil { fatal(err) } state, err := container.State() if err != nil { fatal(err) } data, err := json.MarshalIndent(state, "", "\t") if err != nil { fatal(err) } fmt.Printf("%s", data) }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/stats.go ================================================ package main import ( "encoding/json" "fmt" "github.com/codegangsta/cli" ) var statsCommand = cli.Command{ Name: "stats", Usage: "display statistics for the container", Flags: []cli.Flag{ cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, }, Action: func(context *cli.Context) { container, err := getContainer(context) if err != nil { fatal(err) } stats, err := container.Stats() if err != nil { fatal(err) } data, err := json.MarshalIndent(stats, "", "\t") if err != nil { fatal(err) } fmt.Printf("%s", data) }, } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/tty.go ================================================ package main import ( "io" "os" "github.com/codegangsta/cli" "github.com/docker/docker/pkg/term" "github.com/docker/libcontainer" ) func newTty(context *cli.Context, p *libcontainer.Process, rootuid int) (*tty, error) { if context.Bool("tty") { console, err := p.NewConsole(rootuid) if err != nil { return nil, err } return &tty{ console: console, closers: []io.Closer{ console, }, }, nil } return &tty{}, nil } type tty struct { console libcontainer.Console state *term.State closers []io.Closer } func (t *tty) Close() error { for _, c := range t.closers { c.Close() } if t.state != nil { term.RestoreTerminal(os.Stdin.Fd(), t.state) } return nil } func (t *tty) attach(process *libcontainer.Process) error { if t.console != nil { go io.Copy(t.console, os.Stdin) go io.Copy(os.Stdout, t.console) state, err := term.SetRawTerminal(os.Stdin.Fd()) if err != nil { return err } t.state = state process.Stderr = nil process.Stdout = nil process.Stdin = nil } else { // setup standard pipes so that the TTY of the calling nsinit process // is not inherited by the container. r, w, err := os.Pipe() if err != nil { return err } go io.Copy(w, os.Stdin) t.closers = append(t.closers, w) process.Stdin = r if r, w, err = os.Pipe(); err != nil { return err } go io.Copy(os.Stdout, r) process.Stdout = w t.closers = append(t.closers, r) if r, w, err = os.Pipe(); err != nil { return err } go io.Copy(os.Stderr, r) process.Stderr = w t.closers = append(t.closers, r) } return nil } func (t *tty) setupPipe() { } 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.Fd(), ws) } ================================================ FILE: vendor/github.com/docker/libcontainer/nsinit/utils.go ================================================ package main import ( "encoding/json" "fmt" "os" "path/filepath" "github.com/Sirupsen/logrus" "github.com/codegangsta/cli" "github.com/docker/libcontainer" "github.com/docker/libcontainer/cgroups/systemd" "github.com/docker/libcontainer/configs" ) func loadConfig(context *cli.Context) (*configs.Config, error) { if path := context.String("config"); path != "" { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() var config *configs.Config if err := json.NewDecoder(f).Decode(&config); err != nil { return nil, err } return config, nil } config := getTemplate() modify(config, context) return config, nil } func loadFactory(context *cli.Context) (libcontainer.Factory, error) { cgm := libcontainer.Cgroupfs if context.Bool("systemd") { if systemd.UseSystemd() { cgm = libcontainer.SystemdCgroups } else { logrus.Warn("systemd cgroup flag passed, but systemd support for managing cgroups is not available.") } } root := context.GlobalString("root") abs, err := filepath.Abs(root) if err != nil { return nil, err } return libcontainer.New(abs, cgm, func(l *libcontainer.LinuxFactory) error { l.CriuPath = context.GlobalString("criu") return nil }) } func getContainer(context *cli.Context) (libcontainer.Container, error) { factory, err := loadFactory(context) if err != nil { return nil, err } container, err := factory.Load(context.String("id")) if err != nil { return nil, err } return container, nil } func fatal(err error) { if lerr, ok := err.(libcontainer.Error); ok { lerr.Detail(os.Stderr) os.Exit(1) } fmt.Fprintln(os.Stderr, err) os.Exit(1) } func fatalf(t string, v ...interface{}) { fmt.Fprintf(os.Stderr, t, v...) os.Exit(1) } ================================================ FILE: vendor/github.com/docker/libcontainer/process.go ================================================ package libcontainer import ( "fmt" "io" "math" "os" ) 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 // 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 // consolePath is the path to the console allocated to the container. consolePath string // 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 []string 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"), ProcessNotExecuted) } 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"), ProcessNotExecuted) } 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"), ProcessNotExecuted) } return p.ops.signal(sig) } // NewConsole creates new console for process and returns it func (p *Process) NewConsole(rootuid int) (Console, error) { console, err := newConsole(rootuid, rootuid) if err != nil { return nil, err } p.consolePath = console.Path() return console, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/process_linux.go ================================================ // +build linux package libcontainer import ( "encoding/json" "errors" "io" "os" "os/exec" "path/filepath" "strconv" "syscall" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/system" ) 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 return's 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 } 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.cmd.Process.Pid, s) } func (p *setnsProcess) start() (err error) { defer p.parentPipe.Close() if err = p.execSetns(); err != nil { return newSystemError(err) } if len(p.cgroupPaths) > 0 { if err := cgroups.EnterPid(p.cgroupPaths, p.cmd.Process.Pid); err != nil { return newSystemError(err) } } if err := json.NewEncoder(p.parentPipe).Encode(p.config); err != nil { return newSystemError(err) } if err := syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR); err != nil { return newSystemError(err) } // wait for the child process to fully complete and receive an error message // if one was encoutered var ierr *genericError if err := json.NewDecoder(p.parentPipe).Decode(&ierr); err != nil && err != io.EOF { return newSystemError(err) } if ierr != nil { return newSystemError(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 { err := p.cmd.Start() p.childPipe.Close() if err != nil { return newSystemError(err) } status, err := p.cmd.Process.Wait() if err != nil { p.cmd.Wait() return newSystemError(err) } 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 newSystemError(err) } process, err := os.FindProcess(pid.Pid) if err != nil { return err } p.cmd.Process = process return nil } // terminate sends a SIGKILL to the forked process for the setns routine then waits to // avoid the process becomming 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() if err != nil { return p.cmd.ProcessState, err } return p.cmd.ProcessState, nil } 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 } func (p *initProcess) pid() int { return p.cmd.Process.Pid } func (p *initProcess) externalDescriptors() []string { return p.fds } func (p *initProcess) start() error { defer p.parentPipe.Close() err := p.cmd.Start() p.childPipe.Close() if err != nil { return newSystemError(err) } // 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 newSystemError(err) } p.setExternalDescriptors(fds) // Do this before syncing with child so that no children // can escape the cgroup if err := p.manager.Apply(p.pid()); err != nil { return newSystemError(err) } defer func() { if err != nil { // TODO: should not be the responsibility to call here p.manager.Destroy() } }() if err := p.createNetworkInterfaces(); err != nil { return newSystemError(err) } if err := p.sendConfig(); err != nil { return newSystemError(err) } // wait for the child process to fully complete and receive an error message // if one was encoutered var ierr *genericError if err := json.NewDecoder(p.parentPipe).Decode(&ierr); err != nil && err != io.EOF { return newSystemError(err) } if ierr != nil { return newSystemError(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.cmd.SysProcAttr.Cloneflags&syscall.CLONE_NEWPID == 0 { killCgroupProcesses(p.manager) } 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 state to the container's init process then shutdown writes for the parent if err := json.NewEncoder(p.parentPipe).Encode(p.config); err != nil { return err } // shutdown writes for the parent side of the pipe return syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR) } 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.cmd.Process.Pid, s) } func (p *initProcess) setExternalDescriptors(newFds []string) { p.fds = newFds } func getPipeFds(pid int) ([]string, error) { var fds []string fds = make([]string, 3) dirPath := filepath.Join("/proc", strconv.Itoa(pid), "/fd") for i := 0; i < 3; i++ { f := filepath.Join(dirPath, strconv.Itoa(i)) target, err := os.Readlink(f) if err != nil { return fds, err } fds[i] = target } return fds, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/restored_process.go ================================================ // +build linux package libcontainer import ( "fmt" "os" "github.com/docker/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 { return newGenericError(fmt.Errorf("restored process cannot be signaled"), SystemError) } func (p *nonChildProcess) externalDescriptors() []string { return p.fds } func (p *nonChildProcess) setExternalDescriptors(newFds []string) { p.fds = newFds } ================================================ FILE: vendor/github.com/docker/libcontainer/rootfs_linux.go ================================================ // +build linux package libcontainer import ( "fmt" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "syscall" "time" "github.com/docker/docker/pkg/symlink" "github.com/docker/libcontainer/cgroups" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/label" ) const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV // setupRootfs sets up the devices, mount points, and filesystems for use inside a // new mount namespace. func setupRootfs(config *configs.Config, console *linuxConsole) (err error) { if err := prepareRoot(config); err != nil { return newSystemError(err) } for _, m := range config.Mounts { for _, precmd := range m.PremountCmds { if err := mountCmd(precmd); err != nil { return newSystemError(err) } } if err := mountToRootfs(m, config.Rootfs, config.MountLabel); err != nil { return newSystemError(err) } for _, postcmd := range m.PostmountCmds { if err := mountCmd(postcmd); err != nil { return newSystemError(err) } } } if err := createDevices(config); err != nil { return newSystemError(err) } if err := setupPtmx(config, console); err != nil { return newSystemError(err) } if err := setupDevSymlinks(config.Rootfs); err != nil { return newSystemError(err) } if err := syscall.Chdir(config.Rootfs); err != nil { return newSystemError(err) } if config.NoPivotRoot { err = msMoveRoot(config.Rootfs) } else { err = pivotRoot(config.Rootfs, config.PivotDir) } if err != nil { return newSystemError(err) } if err := reOpenDevNull(config.Rootfs); err != nil { return newSystemError(err) } if config.Readonlyfs { if err := setReadonly(); err != nil { return newSystemError(err) } } 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 data = label.FormatMountLabel(m.Data, mountLabel) ) if !strings.HasPrefix(dest, rootfs) { dest = filepath.Join(rootfs, dest) } switch m.Device { case "proc", "sysfs": if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) { return err } return syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), "") case "mqueue": if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) { return err } if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), ""); err != nil { return err } return label.SetFileLabel(dest, mountLabel) case "tmpfs": stat, err := os.Stat(dest) if err != nil { if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) { return err } } if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data); err != nil { return err } if stat != nil { if err = os.Chmod(dest, stat.Mode()); err != nil { return err } } return nil case "devpts": if err := os.MkdirAll(dest, 0755); err != nil && !os.IsExist(err) { return err } return syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data) 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(filepath.Join(rootfs, m.Destination), rootfs); err != nil { return err } if err := checkMountDestination(rootfs, dest); err != nil { return err } if err := createIfNotExists(dest, stat.IsDir()); err != nil { return err } if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data); err != nil { return err } if m.Flags&syscall.MS_RDONLY != 0 { if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags|syscall.MS_REMOUNT), ""); err != nil { return err } } if m.Relabel != "" { if err := label.Relabel(m.Source, mountLabel, m.Relabel); err != nil { return err } } if m.Flags&syscall.MS_PRIVATE != 0 { if err := syscall.Mount("", dest, "none", uintptr(syscall.MS_PRIVATE), ""); err != nil { return err } } case "cgroup": mounts, err := cgroups.GetCgroupMounts() if err != nil { return err } var binds []*configs.Mount for _, mm := range mounts { dir, err := mm.GetThisCgroupDir() if err != nil { return err } binds = append(binds, &configs.Mount{ Device: "bind", Source: filepath.Join(mm.Mountpoint, dir), Destination: filepath.Join(m.Destination, strings.Join(mm.Subsystems, ",")), Flags: syscall.MS_BIND | syscall.MS_REC | syscall.MS_RDONLY, }) } tmpfs := &configs.Mount{ Device: "tmpfs", Destination: m.Destination, Flags: syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV, } if err := mountToRootfs(tmpfs, rootfs, mountLabel); err != nil { return err } for _, b := range binds { if err := mountToRootfs(b, rootfs, mountLabel); err != nil { return err } } default: return fmt.Errorf("unknown mount device %q to %q", m.Device, m.Destination) } return nil } // checkMountDestination checks to ensure that the mount destination is not over the // top of /proc or /sys. // dest is required to be an abs path and have any symlinks resolved before calling this function. func checkMountDestination(rootfs, dest string) error { if filepath.Clean(rootfs) == filepath.Clean(dest) { return fmt.Errorf("mounting into / is prohibited") } invalidDestinations := []string{ "/proc", } 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/kcore"}) } 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(rootfs string) error { var stat, devNullStat syscall.Stat_t file, err := os.Open("/dev/null") 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 { 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, config.Namespaces.Contains(configs.NEWUSER)); err != nil { syscall.Umask(oldMask) return err } } syscall.Umask(oldMask) return nil } // 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 { 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, "") } if err := mknodDevice(dest, node); err != nil { if os.IsExist(err) { return nil } return err } return nil } func mknodDevice(dest string, node *configs.Device) error { fileMode := node.FileMode switch node.Type { case 'c': fileMode |= syscall.S_IFCHR case 'b': fileMode |= syscall.S_IFBLK 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 prepareRoot(config *configs.Config) error { flag := syscall.MS_SLAVE | syscall.MS_REC if config.Privatefs { flag = syscall.MS_PRIVATE | syscall.MS_REC } if err := syscall.Mount("", "/", "", uintptr(flag), ""); 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, console *linuxConsole) 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) } if console != nil { return console.mount(config.Rootfs, config.MountLabel, 0, 0) } return nil } func pivotRoot(rootfs, pivotBaseDir string) error { if pivotBaseDir == "" { pivotBaseDir = "/" } tmpDir := filepath.Join(rootfs, pivotBaseDir) if err := os.MkdirAll(tmpDir, 0755); err != nil { return fmt.Errorf("can't create tmp dir %s, error %v", tmpDir, err) } pivotDir, err := ioutil.TempDir(tmpDir, ".pivot_root") if err != nil { return fmt.Errorf("can't create pivot_root dir %s, error %v", pivotDir, err) } if err := syscall.PivotRoot(rootfs, pivotDir); err != nil { return fmt.Errorf("pivot_root %s", err) } if err := syscall.Chdir("/"); err != nil { return fmt.Errorf("chdir / %s", err) } // path to pivot dir now changed, update pivotDir = filepath.Join(pivotBaseDir, filepath.Base(pivotDir)) if err := syscall.Unmount(pivotDir, syscall.MNT_DETACH); err != nil { return fmt.Errorf("unmount pivot_root dir %s", err) } return os.Remove(pivotDir) } 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 } // remountReadonly will bind over the top of an existing path and ensure that it is read-only. func remountReadonly(path string) error { for i := 0; i < 5; i++ { if err := syscall.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil && !os.IsNotExist(err) { switch err { case syscall.EINVAL: // Probably not a mountpoint, use bind-mount if err := syscall.Mount(path, path, "", syscall.MS_BIND, ""); err != nil { return err } return syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "") 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", path) } // maskFile bind mounts /dev/null over the top of the specified path inside a container // to avoid security issues from processes reading information from non-namespace aware mounts ( proc/kcore ). func maskFile(path string) error { if err := syscall.Mount("/dev/null", path, "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) { 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) } ================================================ FILE: vendor/github.com/docker/libcontainer/rootfs_linux_test.go ================================================ // +build linux package libcontainer import "testing" func TestCheckMountDestOnProc(t *testing.T) { dest := "/rootfs/proc/" err := checkMountDestination("/rootfs", dest) if err == nil { t.Fatal("destination inside proc should return an error") } } func TestCheckMountDestInSys(t *testing.T) { dest := "/rootfs//sys/fs/cgroup" err := checkMountDestination("/rootfs", dest) if err != nil { t.Fatal("destination inside /sys should not return an error") } } func TestCheckMountDestFalsePositive(t *testing.T) { dest := "/rootfs/sysfiles/fs/cgroup" err := checkMountDestination("/rootfs", dest) if err != nil { t.Fatal(err) } } func TestCheckMountRoot(t *testing.T) { dest := "/rootfs" err := checkMountDestination("/rootfs", dest) if err == nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/README.md ================================================ These configuration files can be used with `nsinit` to quickly develop, test, and experiment with features of libcontainer. When consuming these configuration files, copy them into your rootfs and rename the file to `container.json` for use with `nsinit`. ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/apparmor.json ================================================ { "no_pivot_root": false, "parent_death_signal": 0, "pivot_dir": "", "rootfs": "/rootfs/jessie", "readonlyfs": false, "mounts": [ { "source": "shm", "destination": "/dev/shm", "device": "tmpfs", "flags": 14, "data": "mode=1777,size=65536k", "relabel": "" }, { "source": "mqueue", "destination": "/dev/mqueue", "device": "mqueue", "flags": 14, "data": "", "relabel": "" }, { "source": "sysfs", "destination": "/sys", "device": "sysfs", "flags": 15, "data": "", "relabel": "" } ], "devices": [ { "type": 99, "path": "/dev/fuse", "major": 10, "minor": 229, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "mount_label": "", "hostname": "nsinit", "namespaces": [ { "type": "NEWNS", "path": "" }, { "type": "NEWUTS", "path": "" }, { "type": "NEWIPC", "path": "" }, { "type": "NEWPID", "path": "" }, { "type": "NEWNET", "path": "" } ], "capabilities": [ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE" ], "networks": [ { "type": "loopback", "name": "", "bridge": "", "mac_address": "", "address": "127.0.0.1/0", "gateway": "localhost", "ipv6_address": "", "ipv6_gateway": "", "mtu": 0, "txqueuelen": 0, "host_interface_name": "" } ], "routes": null, "cgroups": { "name": "libcontainer", "parent": "nsinit", "allow_all_devices": false, "allowed_devices": [ { "type": 99, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 98, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/console", "major": 5, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty0", "major": 4, "minor": 0, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty1", "major": 4, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 136, "minor": -1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 5, "minor": 2, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 10, "minor": 200, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "memory": 0, "memory_reservation": 0, "memory_swap": 0, "cpu_shares": 0, "cpu_quota": 0, "cpu_period": 0, "cpuset_cpus": "", "cpuset_mems": "", "blkio_weight": 0, "freezer": "", "slice": "" }, "apparmor_profile": "docker-default", "process_label": "", "rlimits": [ { "type": 7, "hard": 1024, "soft": 1024 } ], "additional_groups": null, "uid_mappings": null, "gid_mappings": null, "mask_paths": [ "/proc/kcore" ], "readonly_paths": [ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus" ] } ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/attach_to_bridge.json ================================================ { "no_pivot_root": false, "parent_death_signal": 0, "pivot_dir": "", "rootfs": "/rootfs/jessie", "readonlyfs": false, "mounts": [ { "source": "shm", "destination": "/dev/shm", "device": "tmpfs", "flags": 14, "data": "mode=1777,size=65536k", "relabel": "" }, { "source": "mqueue", "destination": "/dev/mqueue", "device": "mqueue", "flags": 14, "data": "", "relabel": "" }, { "source": "sysfs", "destination": "/sys", "device": "sysfs", "flags": 15, "data": "", "relabel": "" } ], "devices": [ { "type": 99, "path": "/dev/fuse", "major": 10, "minor": 229, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "mount_label": "", "hostname": "koye", "namespaces": [ { "type": "NEWNS", "path": "" }, { "type": "NEWUTS", "path": "" }, { "type": "NEWIPC", "path": "" }, { "type": "NEWPID", "path": "" }, { "type": "NEWNET", "path": "" } ], "capabilities": [ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE" ], "networks": [ { "type": "loopback", "name": "", "bridge": "", "mac_address": "", "address": "127.0.0.1/0", "gateway": "localhost", "ipv6_address": "", "ipv6_gateway": "", "mtu": 0, "txqueuelen": 0, "host_interface_name": "" }, { "type": "veth", "name": "eth0", "bridge": "docker0", "mac_address": "", "address": "172.17.0.101/16", "gateway": "172.17.42.1", "ipv6_address": "", "ipv6_gateway": "", "mtu": 1500, "txqueuelen": 0, "host_interface_name": "vethnsinit" } ], "routes": null, "cgroups": { "name": "libcontainer", "parent": "nsinit", "allow_all_devices": false, "allowed_devices": [ { "type": 99, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 98, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/console", "major": 5, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty0", "major": 4, "minor": 0, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty1", "major": 4, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 136, "minor": -1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 5, "minor": 2, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 10, "minor": 200, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "memory": 0, "memory_reservation": 0, "memory_swap": 0, "cpu_shares": 0, "cpu_quota": 0, "cpu_period": 0, "cpuset_cpus": "", "cpuset_mems": "", "blkio_weight": 0, "freezer": "", "slice": "" }, "apparmor_profile": "", "process_label": "", "rlimits": [ { "type": 7, "hard": 1024, "soft": 1024 } ], "additional_groups": null, "uid_mappings": null, "gid_mappings": null, "mask_paths": [ "/proc/kcore" ], "readonly_paths": [ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus" ] } ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/host-pid.json ================================================ { "no_pivot_root": false, "parent_death_signal": 0, "pivot_dir": "", "rootfs": "/rootfs/jessie", "readonlyfs": false, "mounts": [ { "source": "shm", "destination": "/dev/shm", "device": "tmpfs", "flags": 14, "data": "mode=1777,size=65536k", "relabel": "" }, { "source": "mqueue", "destination": "/dev/mqueue", "device": "mqueue", "flags": 14, "data": "", "relabel": "" }, { "source": "sysfs", "destination": "/sys", "device": "sysfs", "flags": 15, "data": "", "relabel": "" } ], "devices": [ { "type": 99, "path": "/dev/fuse", "major": 10, "minor": 229, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "mount_label": "", "hostname": "nsinit", "namespaces": [ { "type": "NEWNS", "path": "" }, { "type": "NEWUTS", "path": "" }, { "type": "NEWIPC", "path": "" }, { "type": "NEWNET", "path": "" } ], "capabilities": [ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE" ], "networks": [ { "type": "loopback", "name": "", "bridge": "", "mac_address": "", "address": "127.0.0.1/0", "gateway": "localhost", "ipv6_address": "", "ipv6_gateway": "", "mtu": 0, "txqueuelen": 0, "host_interface_name": "" } ], "routes": null, "cgroups": { "name": "libcontainer", "parent": "nsinit", "allow_all_devices": false, "allowed_devices": [ { "type": 99, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 98, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/console", "major": 5, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty0", "major": 4, "minor": 0, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty1", "major": 4, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 136, "minor": -1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 5, "minor": 2, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 10, "minor": 200, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "memory": 0, "memory_reservation": 0, "memory_swap": 0, "cpu_shares": 0, "cpu_quota": 0, "cpu_period": 0, "cpuset_cpus": "", "cpuset_mems": "", "blkio_weight": 0, "freezer": "", "slice": "" }, "apparmor_profile": "", "process_label": "", "rlimits": [ { "type": 7, "hard": 1024, "soft": 1024 } ], "additional_groups": null, "uid_mappings": null, "gid_mappings": null, "mask_paths": [ "/proc/kcore" ], "readonly_paths": [ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus" ] } ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/minimal.json ================================================ { "no_pivot_root": false, "parent_death_signal": 0, "pivot_dir": "", "rootfs": "/home/michael/development/gocode/src/github.com/docker/libcontainer", "readonlyfs": false, "mounts": [ { "source": "shm", "destination": "/dev/shm", "device": "tmpfs", "flags": 14, "data": "mode=1777,size=65536k", "relabel": "" }, { "source": "mqueue", "destination": "/dev/mqueue", "device": "mqueue", "flags": 14, "data": "", "relabel": "" }, { "source": "sysfs", "destination": "/sys", "device": "sysfs", "flags": 15, "data": "", "relabel": "" } ], "devices": [ { "type": 99, "path": "/dev/fuse", "major": 10, "minor": 229, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "mount_label": "", "hostname": "nsinit", "namespaces": [ { "type": "NEWNS", "path": "" }, { "type": "NEWUTS", "path": "" }, { "type": "NEWIPC", "path": "" }, { "type": "NEWPID", "path": "" }, { "type": "NEWNET", "path": "" } ], "capabilities": [ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE" ], "networks": [ { "type": "loopback", "name": "", "bridge": "", "mac_address": "", "address": "127.0.0.1/0", "gateway": "localhost", "ipv6_address": "", "ipv6_gateway": "", "mtu": 0, "txqueuelen": 0, "host_interface_name": "" } ], "routes": null, "cgroups": { "name": "libcontainer", "parent": "nsinit", "allow_all_devices": false, "allowed_devices": [ { "type": 99, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 98, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/console", "major": 5, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty0", "major": 4, "minor": 0, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty1", "major": 4, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 136, "minor": -1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 5, "minor": 2, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 10, "minor": 200, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "memory": 0, "memory_reservation": 0, "memory_swap": 0, "cpu_shares": 0, "cpu_quota": 0, "cpu_period": 0, "cpuset_cpus": "", "cpuset_mems": "", "blkio_weight": 0, "freezer": "", "slice": "" }, "apparmor_profile": "", "process_label": "", "rlimits": [ { "type": 7, "hard": 1024, "soft": 1024 } ], "additional_groups": null, "uid_mappings": null, "gid_mappings": null, "mask_paths": [ "/proc/kcore" ], "readonly_paths": [ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus" ] } ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/selinux.json ================================================ { "no_pivot_root": false, "parent_death_signal": 0, "pivot_dir": "", "rootfs": "/rootfs/jessie", "readonlyfs": false, "mounts": [ { "source": "shm", "destination": "/dev/shm", "device": "tmpfs", "flags": 14, "data": "mode=1777,size=65536k", "relabel": "" }, { "source": "mqueue", "destination": "/dev/mqueue", "device": "mqueue", "flags": 14, "data": "", "relabel": "" }, { "source": "sysfs", "destination": "/sys", "device": "sysfs", "flags": 15, "data": "", "relabel": "" } ], "devices": [ { "type": 99, "path": "/dev/fuse", "major": 10, "minor": 229, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "mount_label": "system_u:system_r:svirt_lxc_net_t:s0:c164,c475", "hostname": "nsinit", "namespaces": [ { "type": "NEWNS", "path": "" }, { "type": "NEWUTS", "path": "" }, { "type": "NEWIPC", "path": "" }, { "type": "NEWPID", "path": "" }, { "type": "NEWNET", "path": "" } ], "capabilities": [ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE" ], "networks": [ { "type": "loopback", "name": "", "bridge": "", "mac_address": "", "address": "127.0.0.1/0", "gateway": "localhost", "ipv6_address": "", "ipv6_gateway": "", "mtu": 0, "txqueuelen": 0, "host_interface_name": "" } ], "routes": null, "cgroups": { "name": "libcontainer", "parent": "nsinit", "allow_all_devices": false, "allowed_devices": [ { "type": 99, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 98, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/console", "major": 5, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty0", "major": 4, "minor": 0, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty1", "major": 4, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 136, "minor": -1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 5, "minor": 2, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 10, "minor": 200, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "memory": 0, "memory_reservation": 0, "memory_swap": 0, "cpu_shares": 0, "cpu_quota": 0, "cpu_period": 0, "cpuset_cpus": "", "cpuset_mems": "", "blkio_weight": 0, "freezer": "", "slice": "" }, "apparmor_profile": "", "process_label": "system_u:system_r:svirt_lxc_net_t:s0:c164,c475", "rlimits": [ { "type": 7, "hard": 1024, "soft": 1024 } ], "additional_groups": null, "uid_mappings": null, "gid_mappings": null, "mask_paths": [ "/proc/kcore" ], "readonly_paths": [ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus" ] } ================================================ FILE: vendor/github.com/docker/libcontainer/sample_configs/userns.json ================================================ { "no_pivot_root": false, "parent_death_signal": 0, "pivot_dir": "", "rootfs": "/rootfs/jessie", "readonlyfs": false, "mounts": [ { "source": "shm", "destination": "/dev/shm", "device": "tmpfs", "flags": 14, "data": "mode=1777,size=65536k", "relabel": "" }, { "source": "mqueue", "destination": "/dev/mqueue", "device": "mqueue", "flags": 14, "data": "", "relabel": "" }, { "source": "sysfs", "destination": "/sys", "device": "sysfs", "flags": 15, "data": "", "relabel": "" } ], "devices": [ { "type": 99, "path": "/dev/fuse", "major": 10, "minor": 229, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "mount_label": "", "hostname": "nsinit", "namespaces": [ { "type": "NEWNS", "path": "" }, { "type": "NEWUTS", "path": "" }, { "type": "NEWIPC", "path": "" }, { "type": "NEWPID", "path": "" }, { "type": "NEWNET", "path": "" }, { "type": "NEWUSER", "path": "" } ], "capabilities": [ "CHOWN", "DAC_OVERRIDE", "FSETID", "FOWNER", "MKNOD", "NET_RAW", "SETGID", "SETUID", "SETFCAP", "SETPCAP", "NET_BIND_SERVICE", "SYS_CHROOT", "KILL", "AUDIT_WRITE" ], "networks": [ { "type": "loopback", "name": "", "bridge": "", "mac_address": "", "address": "127.0.0.1/0", "gateway": "localhost", "ipv6_address": "", "ipv6_gateway": "", "mtu": 0, "txqueuelen": 0, "host_interface_name": "" } ], "routes": null, "cgroups": { "name": "libcontainer", "parent": "nsinit", "allow_all_devices": false, "allowed_devices": [ { "type": 99, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 98, "path": "", "major": -1, "minor": -1, "permissions": "m", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/console", "major": 5, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty0", "major": 4, "minor": 0, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty1", "major": 4, "minor": 1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 136, "minor": -1, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 5, "minor": 2, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "", "major": 10, "minor": 200, "permissions": "rwm", "file_mode": 0, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/null", "major": 1, "minor": 3, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/zero", "major": 1, "minor": 5, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/full", "major": 1, "minor": 7, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/tty", "major": 5, "minor": 0, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/urandom", "major": 1, "minor": 9, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 }, { "type": 99, "path": "/dev/random", "major": 1, "minor": 8, "permissions": "rwm", "file_mode": 438, "uid": 0, "gid": 0 } ], "memory": 0, "memory_reservation": 0, "memory_swap": 0, "cpu_shares": 0, "cpu_quota": 0, "cpu_period": 0, "cpuset_cpus": "", "cpuset_mems": "", "blkio_weight": 0, "freezer": "", "slice": "" }, "apparmor_profile": "", "process_label": "", "rlimits": [ { "type": 7, "hard": 1024, "soft": 1024 } ], "additional_groups": null, "uid_mappings": [ { "container_id": 0, "host_id": 1000, "size": 1 }, { "container_id": 1, "host_id": 1, "size": 999 }, { "container_id": 1001, "host_id": 1001, "size": 2147482647 } ], "gid_mappings": [ { "container_id": 0, "host_id": 1000, "size": 1 }, { "container_id": 1, "host_id": 1, "size": 999 }, { "container_id": 1001, "host_id": 1001, "size": 2147482647 } ], "mask_paths": [ "/proc/kcore" ], "readonly_paths": [ "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus" ] } ================================================ FILE: vendor/github.com/docker/libcontainer/seccomp/bpf.go ================================================ package seccomp import "strings" type bpfLabel struct { label string location uint32 } type bpfLabels []bpfLabel // labelIndex returns the index for the label if it exists in the slice. // if it does not exist in the slice it appends the label lb to the end // of the slice and returns the index. func labelIndex(labels *bpfLabels, lb string) uint32 { var id uint32 for id = 0; id < uint32(len(*labels)); id++ { if strings.EqualFold(lb, (*labels)[id].label) { return id } } *labels = append(*labels, bpfLabel{lb, 0xffffffff}) return id } func scmpBpfStmt(code uint16, k uint32) sockFilter { return sockFilter{code, 0, 0, k} } func scmpBpfJump(code uint16, k uint32, jt, jf uint8) sockFilter { return sockFilter{code, jt, jf, k} } ================================================ FILE: vendor/github.com/docker/libcontainer/seccomp/context.go ================================================ package seccomp import ( "errors" "syscall" ) const labelTemplate = "lb-%d-%d" // Action is the type of action that will be taken when a // syscall is performed. type Action int const ( Kill Action = iota - 3 // Kill the calling process of the syscall. Trap // Trap and coredump the calling process of the syscall. Allow // Allow the syscall to be completed. ) // Syscall is the specified syscall, action, and any type of arguments // to filter on. type Syscall struct { // Value is the syscall number. Value uint32 // Action is the action to perform when the specified syscall is made. Action Action // Args are filters that can be specified on the arguments to the syscall. Args Args } func (s *Syscall) scmpAction() uint32 { switch s.Action { case Allow: return retAllow case Trap: return retTrap case Kill: return retKill } return actionErrno(uint32(s.Action)) } // Arg represents an argument to the syscall with the argument's index, // the operator to apply when matching, and the argument's value at that time. type Arg struct { Index uint32 // index of args which start from zero Op Operator // operation, such as EQ/NE/GE/LE Value uint // the value of arg } type Args [][]Arg var ( ErrUnresolvedLabel = errors.New("seccomp: unresolved label") ErrDuplicateLabel = errors.New("seccomp: duplicate label use") ErrUnsupportedOperation = errors.New("seccomp: unsupported operation for argument") ) // Error returns an Action that will be used to send the calling // process the specified errno when the syscall is made. func Error(code syscall.Errno) Action { return Action(code) } // New returns a new syscall context for use. func New() *Context { return &Context{ syscalls: make(map[uint32]*Syscall), } } // Context holds syscalls for the current process to limit the type of // actions the calling process can make. type Context struct { syscalls map[uint32]*Syscall } // Add will add the specified syscall, action, and arguments to the seccomp // Context. func (c *Context) Add(s *Syscall) { c.syscalls[s.Value] = s } // Remove removes the specified syscall configuration from the Context. func (c *Context) Remove(call uint32) { delete(c.syscalls, call) } // Load will apply the Context to the calling process makeing any secccomp process changes // apply after the context is loaded. func (c *Context) Load() error { filter, err := c.newFilter() if err != nil { return err } if err := prctl(prSetNoNewPrivileges, 1, 0, 0, 0); err != nil { return err } prog := newSockFprog(filter) return prog.set() } func (c *Context) newFilter() ([]sockFilter, error) { var ( labels bpfLabels f = newFilter() ) for _, s := range c.syscalls { f.addSyscall(s, &labels) } f.allow() // process args for the syscalls for _, s := range c.syscalls { if err := f.addArguments(s, &labels); err != nil { return nil, err } } // apply labels for arguments idx := int32(len(*f) - 1) for ; idx >= 0; idx-- { lf := &(*f)[idx] if lf.code != (syscall.BPF_JMP + syscall.BPF_JA) { continue } rel := int32(lf.jt)<<8 | int32(lf.jf) if ((jumpJT << 8) | jumpJF) == rel { if labels[lf.k].location == 0xffffffff { return nil, ErrUnresolvedLabel } lf.k = labels[lf.k].location - uint32(idx+1) lf.jt = 0 lf.jf = 0 } else if ((labelJT << 8) | labelJF) == rel { if labels[lf.k].location != 0xffffffff { return nil, ErrDuplicateLabel } labels[lf.k].location = uint32(idx) lf.k = 0 lf.jt = 0 lf.jf = 0 } } return *f, nil } ================================================ FILE: vendor/github.com/docker/libcontainer/seccomp/filter.go ================================================ package seccomp import ( "fmt" "syscall" "unsafe" ) type sockFilter struct { code uint16 jt uint8 jf uint8 k uint32 } func newFilter() *filter { var f filter f = append(f, sockFilter{ pfLD + syscall.BPF_W + syscall.BPF_ABS, 0, 0, uint32(unsafe.Offsetof(secData.nr)), }) return &f } type filter []sockFilter func (f *filter) addSyscall(s *Syscall, labels *bpfLabels) { if len(s.Args) == 0 { f.call(s.Value, scmpBpfStmt(syscall.BPF_RET+syscall.BPF_K, s.scmpAction())) } else { if len(s.Args[0]) > 0 { lb := fmt.Sprintf(labelTemplate, s.Value, s.Args[0][0].Index) f.call(s.Value, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JA, labelIndex(labels, lb), jumpJT, jumpJF)) } } } func (f *filter) addArguments(s *Syscall, labels *bpfLabels) error { for i := 0; len(s.Args) > i; i++ { if len(s.Args[i]) > 0 { lb := fmt.Sprintf(labelTemplate, s.Value, s.Args[i][0].Index) f.label(labels, lb) f.arg(s.Args[i][0].Index) } for j := 0; j < len(s.Args[i]); j++ { var jf sockFilter if len(s.Args)-1 > i && len(s.Args[i+1]) > 0 { lbj := fmt.Sprintf(labelTemplate, s.Value, s.Args[i+1][0].Index) jf = scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JA, labelIndex(labels, lbj), jumpJT, jumpJF) } else { jf = scmpBpfStmt(syscall.BPF_RET+syscall.BPF_K, s.scmpAction()) } if err := f.op(s.Args[i][j].Op, s.Args[i][j].Value, jf); err != nil { return err } } f.allow() } return nil } func (f *filter) label(labels *bpfLabels, lb string) { *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JA, labelIndex(labels, lb), labelJT, labelJF)) } func (f *filter) call(nr uint32, jt sockFilter) { *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, nr, 0, 1)) *f = append(*f, jt) } func (f *filter) allow() { *f = append(*f, scmpBpfStmt(syscall.BPF_RET+syscall.BPF_K, retAllow)) } func (f *filter) deny() { *f = append(*f, scmpBpfStmt(syscall.BPF_RET+syscall.BPF_K, retTrap)) } func (f *filter) arg(index uint32) { arg(f, index) } func (f *filter) op(operation Operator, v uint, jf sockFilter) error { switch operation { case EqualTo: jumpEqualTo(f, v, jf) case NotEqualTo: jumpNotEqualTo(f, v, jf) case GreatherThan: jumpGreaterThan(f, v, jf) case LessThan: jumpLessThan(f, v, jf) case MaskEqualTo: jumpMaskEqualTo(f, v, jf) default: return ErrUnsupportedOperation } return nil } func arg(f *filter, idx uint32) { *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_W+syscall.BPF_ABS, endian.low(idx))) *f = append(*f, scmpBpfStmt(syscall.BPF_ST, 0)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_W+syscall.BPF_ABS, endian.hi(idx))) *f = append(*f, scmpBpfStmt(syscall.BPF_ST, 1)) } func jump(f *filter, labels *bpfLabels, lb string) { *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JA, labelIndex(labels, lb), jumpJT, jumpJF)) } ================================================ FILE: vendor/github.com/docker/libcontainer/seccomp/jump_amd64.go ================================================ // +build linux,amd64 package seccomp // Using BPF filters // // ref: http://www.gsp.com/cgi-bin/man.cgi?topic=bpf import "syscall" func jumpGreaterThan(f *filter, v uint, jt sockFilter) { lo := uint32(uint64(v) % 0x100000000) hi := uint32(uint64(v) / 0x100000000) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JGT+syscall.BPF_K, (hi), 4, 0)) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, (hi), 0, 5)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 0)) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JGE+syscall.BPF_K, (lo), 0, 2)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) *f = append(*f, jt) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) } func jumpEqualTo(f *filter, v uint, jt sockFilter) { lo := uint32(uint64(v) % 0x100000000) hi := uint32(uint64(v) / 0x100000000) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, (hi), 0, 5)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 0)) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, (lo), 0, 2)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) *f = append(*f, jt) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) } func jumpLessThan(f *filter, v uint, jt sockFilter) { lo := uint32(uint64(v) % 0x100000000) hi := uint32(uint64(v) / 0x100000000) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JGT+syscall.BPF_K, (hi), 6, 0)) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, (hi), 0, 3)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 0)) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JGT+syscall.BPF_K, (lo), 2, 0)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) *f = append(*f, jt) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) } func jumpNotEqualTo(f *filter, v uint, jt sockFilter) { lo := uint32(uint64(v) % 0x100000000) hi := uint32(uint64(v) / 0x100000000) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, hi, 5, 0)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 0)) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, lo, 2, 0)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) *f = append(*f, jt) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) } // this checks for a value inside a mask. The evalusation is equal to doing // CLONE_NEWUSER & syscallMask == CLONE_NEWUSER func jumpMaskEqualTo(f *filter, v uint, jt sockFilter) { lo := uint32(uint64(v) % 0x100000000) hi := uint32(uint64(v) / 0x100000000) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, hi, 0, 6)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 0)) *f = append(*f, scmpBpfStmt(syscall.BPF_ALU+syscall.BPF_AND, uint32(v))) *f = append(*f, scmpBpfJump(syscall.BPF_JMP+syscall.BPF_JEQ+syscall.BPF_K, lo, 0, 2)) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) *f = append(*f, jt) *f = append(*f, scmpBpfStmt(syscall.BPF_LD+syscall.BPF_MEM, 1)) } ================================================ FILE: vendor/github.com/docker/libcontainer/seccomp/seccomp.go ================================================ // Package seccomp provides native seccomp ( https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt ) support for go. package seccomp import ( "syscall" "unsafe" ) // Operator that is used for argument comparison. type Operator int const ( EqualTo Operator = iota NotEqualTo GreatherThan LessThan MaskEqualTo ) const ( jumpJT = 0xff jumpJF = 0xff labelJT = 0xfe labelJF = 0xfe ) const ( pfLD = 0x0 retKill = 0x00000000 retTrap = 0x00030000 retAllow = 0x7fff0000 modeFilter = 0x2 prSetNoNewPrivileges = 0x26 ) func actionErrno(errno uint32) uint32 { return 0x00050000 | (errno & 0x0000ffff) } var ( secData = struct { nr int32 arch uint32 insPointer uint64 args [6]uint64 }{0, 0, 0, [6]uint64{0, 0, 0, 0, 0, 0}} ) var isLittle = func() bool { var ( x = 0x1234 p = unsafe.Pointer(&x) p2 = (*[unsafe.Sizeof(0)]byte)(p) ) if p2[0] == 0 { return false } return true }() var endian endianSupport type endianSupport struct { } func (e endianSupport) hi(i uint32) uint32 { if isLittle { return e.little(i) } return e.big(i) } func (e endianSupport) low(i uint32) uint32 { if isLittle { return e.big(i) } return e.little(i) } func (endianSupport) big(idx uint32) uint32 { if idx >= 6 { return 0 } return uint32(unsafe.Offsetof(secData.args)) + 8*idx } func (endianSupport) little(idx uint32) uint32 { if idx < 0 || idx >= 6 { return 0 } return uint32(unsafe.Offsetof(secData.args)) + uint32(unsafe.Alignof(secData.args[0]))*idx + uint32(unsafe.Sizeof(secData.arch)) } func prctl(option int, arg2, arg3, arg4, arg5 uintptr) error { _, _, err := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0) if err != 0 { return err } return nil } func newSockFprog(filter []sockFilter) *sockFprog { return &sockFprog{ len: uint16(len(filter)), filt: filter, } } type sockFprog struct { len uint16 filt []sockFilter } func (s *sockFprog) set() error { _, _, err := syscall.Syscall(syscall.SYS_PRCTL, uintptr(syscall.PR_SET_SECCOMP), uintptr(modeFilter), uintptr(unsafe.Pointer(s))) if err != 0 { return err } return nil } ================================================ FILE: vendor/github.com/docker/libcontainer/selinux/selinux.go ================================================ // +build linux package selinux import ( "bufio" "crypto/rand" "encoding/binary" "fmt" "io" "os" "path/filepath" "regexp" "strconv" "strings" "syscall" "github.com/docker/docker/pkg/mount" "github.com/docker/libcontainer/system" ) const ( Enforcing = 1 Permissive = 0 Disabled = -1 selinuxDir = "/etc/selinux/" selinuxConfig = selinuxDir + "config" selinuxTypeTag = "SELINUXTYPE" selinuxTag = "SELINUX" selinuxPath = "/sys/fs/selinux" xattrNameSelinux = "security.selinux" stRdOnly = 0x01 ) var ( assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`) spaceRegex = regexp.MustCompile(`^([^=]+) (.*)$`) mcsList = make(map[string]bool) selinuxfs = "unknown" selinuxEnabled = false // Stores whether selinux is currently enabled selinuxEnabledChecked = false // Stores whether selinux enablement has been checked or established yet ) type SELinuxContext map[string]string // SetDisabled disables selinux support for the package func SetDisabled() { selinuxEnabled, selinuxEnabledChecked = false, true } // 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 { if selinuxfs != "unknown" { return selinuxfs } selinuxfs = "" mounts, err := mount.GetMounts() if err != nil { return selinuxfs } for _, mount := range mounts { if mount.Fstype == "selinuxfs" { selinuxfs = mount.Mountpoint break } } if selinuxfs != "" { var buf syscall.Statfs_t syscall.Statfs(selinuxfs, &buf) if (buf.Flags & stRdOnly) == 1 { selinuxfs = "" } } return selinuxfs } // SelinuxEnabled returns whether selinux is currently enabled. func SelinuxEnabled() bool { if selinuxEnabledChecked { return selinuxEnabled } selinuxEnabledChecked = true if fs := getSelinuxMountPoint(); fs != "" { if con, _ := Getcon(); con != "kernel" { selinuxEnabled = true } } return selinuxEnabled } 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 } // Setfilecon sets the SELinux label for this path or returns an error. func Setfilecon(path string, scon string) error { return system.Lsetxattr(path, xattrNameSelinux, []byte(scon), 0) } // Getfilecon returns the SELinux label for this path or returns an error. func Getfilecon(path string) (string, error) { con, err := system.Lgetxattr(path, xattrNameSelinux) // Trim the NUL byte at the end of the byte buffer, if present. if con[len(con)-1] == '\x00' { con = con[:len(con)-1] } return string(con), err } func Setfscreatecon(scon string) error { return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/fscreate", syscall.Gettid()), scon) } func Getfscreatecon() (string, error) { return readCon(fmt.Sprintf("/proc/self/task/%d/attr/fscreate", syscall.Gettid())) } // Getcon returns the SELinux label of the current process thread, or an error. func Getcon() (string, error) { return readCon(fmt.Sprintf("/proc/self/task/%d/attr/current", syscall.Gettid())) } // Getpidcon returns the SELinux label of the given pid, or an error. func Getpidcon(pid int) (string, error) { return readCon(fmt.Sprintf("/proc/%d/attr/current", pid)) } func Getexeccon() (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 } func Setexeccon(scon string) error { return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/exec", syscall.Gettid()), scon) } func (c SELinuxContext) Get() string { return fmt.Sprintf("%s:%s:%s:%s", c["user"], c["role"], c["type"], c["level"]) } func NewContext(scon string) SELinuxContext { c := make(SELinuxContext) if len(scon) != 0 { con := strings.SplitN(scon, ":", 4) c["user"] = con[0] c["role"] = con[1] c["type"] = con[2] c["level"] = con[3] } return c } func ReserveLabel(scon string) { if len(scon) != 0 { con := strings.SplitN(scon, ":", 4) mcsAdd(con[3]) } } func SelinuxGetEnforce() int { var enforce int enforceS, err := readCon(fmt.Sprintf("%s/enforce", selinuxPath)) if err != nil { return -1 } enforce, err = strconv.Atoi(string(enforceS)) if err != nil { return -1 } return enforce } func SelinuxGetEnforceMode() int { switch readConfig(selinuxTag) { case "enforcing": return Enforcing case "permissive": return Permissive } return Disabled } func mcsAdd(mcs string) error { if mcsList[mcs] { return fmt.Errorf("MCS Label already exists") } mcsList[mcs] = true return nil } func mcsDelete(mcs string) { mcsList[mcs] = false } func mcsExists(mcs string) bool { return mcsList[mcs] } 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 -= 1 } 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 { t := c1 c1 = c2 c2 = t } } mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2) if err := mcsAdd(mcs); err != nil { continue } break } return mcs } func FreeLxcContexts(scon string) { if len(scon) != 0 { con := strings.SplitN(scon, ":", 4) mcsDelete(con[3]) } } func GetLxcContexts() (processLabel string, fileLabel string) { var ( val, key string bufin *bufio.Reader ) if !SelinuxEnabled() { 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 processLabel == "" || fileLabel == "" { return "", "" } exit: // mcs := IntToMcs(os.Getpid(), 1024) mcs := uniqMcs(1024) scon := NewContext(processLabel) scon["level"] = mcs processLabel = scon.Get() scon = NewContext(fileLabel) scon["level"] = mcs fileLabel = scon.Get() return processLabel, fileLabel } func SecurityCheckContext(val string) error { return writeCon(fmt.Sprintf("%s.context", selinuxPath), val) } 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 } // Change the fpath file object to the SELinux label scon. // If the fpath is a directory and recurse is true Chcon will walk the // directory tree setting the label func Chcon(fpath string, scon string, recurse bool) error { if scon == "" { return nil } if err := badPrefix(fpath); err != nil { return err } callback := func(p string, info os.FileInfo, err error) error { return Setfilecon(p, scon) } if recurse { return filepath.Walk(fpath, callback) } return Setfilecon(fpath, scon) } // 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{"label:user:" + con["user"], "label:role:" + con["role"], "label:type:" + con["type"], "label: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{"label:disable"} } ================================================ FILE: vendor/github.com/docker/libcontainer/selinux/selinux_test.go ================================================ // +build linux package selinux_test import ( "os" "testing" "github.com/docker/libcontainer/selinux" ) func testSetfilecon(t *testing.T) { if selinux.SelinuxEnabled() { tmp := "selinux_test" out, _ := os.OpenFile(tmp, os.O_WRONLY, 0) out.Close() err := selinux.Setfilecon(tmp, "system_u:object_r:bin_t:s0") if err != nil { t.Log("Setfilecon failed") t.Fatal(err) } os.Remove(tmp) } } func TestSELinux(t *testing.T) { var ( err error plabel, flabel string ) if selinux.SelinuxEnabled() { t.Log("Enabled") plabel, flabel = selinux.GetLxcContexts() t.Log(plabel) t.Log(flabel) selinux.FreeLxcContexts(plabel) plabel, flabel = selinux.GetLxcContexts() t.Log(plabel) t.Log(flabel) selinux.FreeLxcContexts(plabel) t.Log("getenforce ", selinux.SelinuxGetEnforce()) t.Log("getenforcemode ", selinux.SelinuxGetEnforceMode()) pid := os.Getpid() t.Logf("PID:%d MCS:%s\n", pid, selinux.IntToMcs(pid, 1023)) err = selinux.Setfscreatecon("unconfined_u:unconfined_r:unconfined_t:s0") if err == nil { t.Log(selinux.Getfscreatecon()) } else { t.Log("setfscreatecon failed", err) t.Fatal(err) } err = selinux.Setfscreatecon("") if err == nil { t.Log(selinux.Getfscreatecon()) } else { t.Log("setfscreatecon failed", err) t.Fatal(err) } t.Log(selinux.Getpidcon(1)) } else { t.Log("Disabled") } } ================================================ FILE: vendor/github.com/docker/libcontainer/setns_init_linux.go ================================================ // +build linux package libcontainer import ( "os" "github.com/docker/libcontainer/apparmor" "github.com/docker/libcontainer/label" "github.com/docker/libcontainer/system" ) // linuxSetnsInit performs the container's initialization for running a new process // inside an existing container. type linuxSetnsInit struct { config *initConfig } func (l *linuxSetnsInit) Init() error { if err := setupRlimits(l.config.Config); err != nil { return err } if err := finalizeNamespace(l.config); err != nil { return err } if err := apparmor.ApplyProfile(l.config.Config.AppArmorProfile); err != nil { return err } if l.config.Config.ProcessLabel != "" { if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil { return err } } return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ()) } ================================================ FILE: vendor/github.com/docker/libcontainer/stacktrace/capture.go ================================================ package stacktrace import "runtime" // Caputure 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 ) for i := skip; ; i++ { pc, file, line, ok := runtime.Caller(i) if !ok { break } frames = append(frames, NewFrame(pc, file, line)) } return Stacktrace{ Frames: frames, } } ================================================ FILE: vendor/github.com/docker/libcontainer/stacktrace/capture_test.go ================================================ package stacktrace import "testing" func captureFunc() Stacktrace { return Capture(0) } func TestCaptureTestFunc(t *testing.T) { stack := captureFunc() if len(stack.Frames) == 0 { t.Fatal("expected stack frames to be returned") } // the first frame is the caller frame := stack.Frames[0] if expected := "captureFunc"; frame.Function != expected { t.Fatalf("expteced function %q but recevied %q", expected, frame.Function) } if expected := "github.com/docker/libcontainer/stacktrace"; frame.Package != expected { t.Fatalf("expected package %q but received %q", expected, frame.Package) } if expected := "capture_test.go"; frame.File != expected { t.Fatalf("expected file %q but received %q", expected, frame.File) } } ================================================ FILE: vendor/github.com/docker/libcontainer/stacktrace/frame.go ================================================ 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/stacktrace/frame_test.go ================================================ package stacktrace import "testing" func TestParsePackageName(t *testing.T) { var ( name = "github.com/docker/libcontainer/stacktrace.captureFunc" expectedPackage = "github.com/docker/libcontainer/stacktrace" expectedFunction = "captureFunc" ) pack, funcName := parseFunctionName(name) if pack != expectedPackage { t.Fatalf("expected package %q but received %q", expectedPackage, pack) } if funcName != expectedFunction { t.Fatalf("expected function %q but received %q", expectedFunction, funcName) } } ================================================ FILE: vendor/github.com/docker/libcontainer/stacktrace/stacktrace.go ================================================ package stacktrace type Stacktrace struct { Frames []Frame } ================================================ FILE: vendor/github.com/docker/libcontainer/standard_init_linux.go ================================================ // +build linux package libcontainer import ( "os" "syscall" "github.com/docker/libcontainer/apparmor" "github.com/docker/libcontainer/configs" "github.com/docker/libcontainer/label" "github.com/docker/libcontainer/system" ) type linuxStandardInit struct { parentPid int config *initConfig } func (l *linuxStandardInit) Init() error { // join any namespaces via a path to the namespace fd if provided if err := joinExistingNamespaces(l.config.Config.Namespaces); err != nil { return err } var console *linuxConsole if l.config.Console != "" { console = newConsoleFromPath(l.config.Console) if err := console.dupStdio(); err != nil { return err } } if _, err := syscall.Setsid(); err != nil { return err } if console != nil { if err := system.Setctty(); err != nil { return err } } if err := setupNetwork(l.config); err != nil { return err } if err := setupRoute(l.config.Config); err != nil { return err } if err := setupRlimits(l.config.Config); err != nil { return err } label.Init() // InitializeMountNamespace() can be executed only for a new mount namespace if l.config.Config.Namespaces.Contains(configs.NEWNS) { if err := setupRootfs(l.config.Config, console); 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.Config.AppArmorProfile); err != nil { return err } if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil { return err } for key, value := range l.config.Config.SystemProperties { if err := writeSystemProperty(key, value); err != nil { return err } } for _, path := range l.config.Config.ReadonlyPaths { if err := remountReadonly(path); err != nil { return err } } for _, path := range l.config.Config.MaskPaths { if err := maskFile(path); err != nil { return err } } pdeath, err := system.GetParentDeathSignal() if 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 inital start of the init process and make sure that it did not change. // if the parent changes that means it died and we were reparened 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) } if err := finalizeSeccomp(l.config); err != nil { return err } return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ()) } ================================================ FILE: vendor/github.com/docker/libcontainer/stats.go ================================================ 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/stats_freebsd.go ================================================ package libcontainer type Stats struct { Interfaces []*NetworkInterface } ================================================ FILE: vendor/github.com/docker/libcontainer/stats_linux.go ================================================ package libcontainer import "github.com/docker/libcontainer/cgroups" type Stats struct { Interfaces []*NetworkInterface CgroupStats *cgroups.Stats } ================================================ FILE: vendor/github.com/docker/libcontainer/stats_windows.go ================================================ package libcontainer type Stats struct { Interfaces []*NetworkInterface } ================================================ FILE: vendor/github.com/docker/libcontainer/system/linux.go ================================================ // +build linux package system import ( "os/exec" "syscall" "unsafe" ) 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 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/system/proc.go ================================================ 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 } parts := strings.Split(string(data), " ") // 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)). return parts[22-1], nil // starts at 1 } ================================================ FILE: vendor/github.com/docker/libcontainer/system/setns_linux.go ================================================ 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/system/syscall_linux_386.go ================================================ // +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_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_SETGID32, uintptr(gid), 0, 0) if e1 != 0 { err = e1 } return } ================================================ FILE: vendor/github.com/docker/libcontainer/system/syscall_linux_64.go ================================================ // +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 } ================================================ FILE: vendor/github.com/docker/libcontainer/system/syscall_linux_arm.go ================================================ // +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 } ================================================ FILE: vendor/github.com/docker/libcontainer/system/sysconfig.go ================================================ // +build cgo,linux cgo,freebsd package system /* #include */ import "C" func GetClockTicks() int { return int(C.sysconf(C._SC_CLK_TCK)) } ================================================ FILE: vendor/github.com/docker/libcontainer/system/sysconfig_notcgo.go ================================================ // +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 } ================================================ FILE: vendor/github.com/docker/libcontainer/system/xattrs_linux.go ================================================ 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/update-vendor.sh ================================================ #!/usr/bin/env bash set -e cd "$(dirname "$BASH_SOURCE")" # Downloads dependencies into vendor/ directory mkdir -p vendor cd vendor clone() { vcs=$1 pkg=$2 rev=$3 pkg_url=https://$pkg target_dir=src/$pkg echo -n "$pkg @ $rev: " if [ -d $target_dir ]; then echo -n 'rm old, ' rm -fr $target_dir fi echo -n 'clone, ' case $vcs in git) git clone --quiet --no-checkout $pkg_url $target_dir ( cd $target_dir && git reset --quiet --hard $rev ) ;; hg) hg clone --quiet --updaterev $rev $pkg_url $target_dir ;; esac echo -n 'rm VCS, ' ( cd $target_dir && rm -rf .{git,hg} ) echo done } # the following lines are in sorted order, FYI clone git github.com/codegangsta/cli 1.1.0 clone git github.com/coreos/go-systemd v2 clone git github.com/godbus/dbus v2 clone git github.com/Sirupsen/logrus v0.7.3 clone git github.com/syndtr/gocapability 8e4cdcb clone git github.com/golang/protobuf 655cdfa588ea # intentionally not vendoring Docker itself... that'd be a circle :) ================================================ FILE: vendor/github.com/docker/libcontainer/user/MAINTAINERS ================================================ Tianon Gravi (@tianon) Aleksa Sarai (@cyphar) ================================================ FILE: vendor/github.com/docker/libcontainer/user/lookup.go ================================================ package user import ( "errors" "fmt" "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") ) 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{}, fmt.Errorf("no matching entries in passwd file") } // 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{}, fmt.Errorf("no matching entries in group file") } // 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 }) } ================================================ FILE: vendor/github.com/docker/libcontainer/user/lookup_unix.go ================================================ // +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) } ================================================ FILE: vendor/github.com/docker/libcontainer/user/lookup_unsupported.go ================================================ // +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 } ================================================ FILE: vendor/github.com/docker/libcontainer/user/user.go ================================================ 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 { if len(v) <= i { // if we have more "parts" than we have places to put them, bail for great "tolerance" of naughty configuration files break } switch e := v[i].(type) { case *string: // "root", "adm", "/bin/bash" *e = p case *int: // "0", "4", "1000" // ignore string to int conversion errors, for great "tolerance" of naughty configuration files *e, _ = strconv.Atoi(p) case *[]string: // "", "root", "root,adm,daemon" if p != "" { *e = strings.Split(p, ",") } else { *e = []string{} } default: // panic, because this is a programming/logic error, not a runtime one panic("parseLine expects only pointers! argument " + strconv.Itoa(i) + " is not a pointer!") } } } 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 } text := strings.TrimSpace(s.Text()) if text == "" { 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( text, &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, 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) { passwd, err := os.Open(passwdPath) if err != nil { passwd = nil } else { defer passwd.Close() } group, err := os.Open(groupPath) if err != nil { group = nil } else { defer group.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" func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) { var ( userArg, groupArg string name string ) 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 parseLine(userSpec, &userArg, &groupArg) users, err := ParsePasswdFilter(passwd, func(u User) bool { if userArg == "" { return u.Uid == user.Uid } return u.Name == userArg || strconv.Itoa(u.Uid) == userArg }) if err != nil && passwd != nil { if userArg == "" { userArg = strconv.Itoa(user.Uid) } return nil, fmt.Errorf("Unable to find user %v: %v", userArg, err) } haveUser := users != nil && len(users) > 0 if haveUser { // if we found any user entries that matched our filter, let's take the first one as "correct" name = users[0].Name user.Uid = users[0].Uid user.Gid = users[0].Gid user.Home = users[0].Home } else if userArg != "" { // we asked for a user but didn't find them... let's check to see if we wanted a numeric user user.Uid, err = strconv.Atoi(userArg) if err != nil { // not numeric - we have to bail return nil, fmt.Errorf("Unable to find user %v", userArg) } // Must be inside valid uid range. if user.Uid < minId || user.Uid > maxId { return nil, ErrRange } // if userArg couldn't be found in /etc/passwd but is numeric, just roll with it - this is legit } if groupArg != "" || name != "" { groups, err := ParseGroupFilter(group, func(g Group) bool { // Explicit group format takes precedence. if groupArg != "" { return g.Name == groupArg || strconv.Itoa(g.Gid) == groupArg } // Check if user is a member. for _, u := range g.List { if u == name { return true } } return false }) if err != nil && group != nil { return nil, fmt.Errorf("Unable to find groups for user %v: %v", users[0].Name, err) } haveGroup := groups != nil && len(groups) > 0 if groupArg != "" { if haveGroup { // if we found any group entries that matched our filter, let's take the first one as "correct" user.Gid = groups[0].Gid } else { // we asked for a group but didn't find id... let's check to see if we wanted a numeric group user.Gid, err = strconv.Atoi(groupArg) if err != nil { // not numeric - we have to bail return nil, fmt.Errorf("Unable to find group %v", groupArg) } // Ensure gid is inside gid range. if user.Gid < minId || user.Gid > maxId { return nil, ErrRange } // if groupArg couldn't be found in /etc/group but is numeric, just roll with it - this is legit } } else if haveGroup { // If implicit group format, fill supplementary gids. user.Sgids = make([]int, len(groups)) for i, group := range groups { user.Sgids[i] = group.Gid } } } return user, nil } // GetAdditionalGroupsPath looks up a list of groups by name or group id // against the group file. If a group name cannot be found, an error will be // returned. If a group id cannot be found, it will be returned as-is. func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { groupReader, err := os.Open(groupPath) if err != nil { return nil, fmt.Errorf("Failed to open group file: %v", err) } defer groupReader.Close() groups, err := ParseGroupFilter(groupReader, 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 } ================================================ FILE: vendor/github.com/docker/libcontainer/user/user_test.go ================================================ package user import ( "fmt" "io" "io/ioutil" "reflect" "sort" "strconv" "strings" "testing" ) func TestUserParseLine(t *testing.T) { var ( a, b string c []string d int ) parseLine("", &a, &b) if a != "" || b != "" { t.Fatalf("a and b should be empty ('%v', '%v')", a, b) } parseLine("a", &a, &b) if a != "a" || b != "" { t.Fatalf("a should be 'a' and b should be empty ('%v', '%v')", a, b) } parseLine("bad boys:corny cows", &a, &b) if a != "bad boys" || b != "corny cows" { t.Fatalf("a should be 'bad boys' and b should be 'corny cows' ('%v', '%v')", a, b) } parseLine("", &c) if len(c) != 0 { t.Fatalf("c should be empty (%#v)", c) } parseLine("d,e,f:g:h:i,j,k", &c, &a, &b, &c) if a != "g" || b != "h" || len(c) != 3 || c[0] != "i" || c[1] != "j" || c[2] != "k" { t.Fatalf("a should be 'g', b should be 'h', and c should be ['i','j','k'] ('%v', '%v', '%#v')", a, b, c) } parseLine("::::::::::", &a, &b, &c) if a != "" || b != "" || len(c) != 0 { t.Fatalf("a, b, and c should all be empty ('%v', '%v', '%#v')", a, b, c) } parseLine("not a number", &d) if d != 0 { t.Fatalf("d should be 0 (%v)", d) } parseLine("b:12:c", &a, &d, &b) if a != "b" || b != "c" || d != 12 { t.Fatalf("a should be 'b' and b should be 'c', and d should be 12 ('%v', '%v', %v)", a, b, d) } } func TestUserParsePasswd(t *testing.T) { users, err := ParsePasswdFilter(strings.NewReader(` root:x:0:0:root:/root:/bin/bash adm:x:3:4:adm:/var/adm:/bin/false this is just some garbage data `), nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if len(users) != 3 { t.Fatalf("Expected 3 users, got %v", len(users)) } if users[0].Uid != 0 || users[0].Name != "root" { t.Fatalf("Expected users[0] to be 0 - root, got %v - %v", users[0].Uid, users[0].Name) } if users[1].Uid != 3 || users[1].Name != "adm" { t.Fatalf("Expected users[1] to be 3 - adm, got %v - %v", users[1].Uid, users[1].Name) } } func TestUserParseGroup(t *testing.T) { groups, err := ParseGroupFilter(strings.NewReader(` root:x:0:root adm:x:4:root,adm,daemon this is just some garbage data `), nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if len(groups) != 3 { t.Fatalf("Expected 3 groups, got %v", len(groups)) } if groups[0].Gid != 0 || groups[0].Name != "root" || len(groups[0].List) != 1 { t.Fatalf("Expected groups[0] to be 0 - root - 1 member, got %v - %v - %v", groups[0].Gid, groups[0].Name, len(groups[0].List)) } if groups[1].Gid != 4 || groups[1].Name != "adm" || len(groups[1].List) != 3 { t.Fatalf("Expected groups[1] to be 4 - adm - 3 members, got %v - %v - %v", groups[1].Gid, groups[1].Name, len(groups[1].List)) } } func TestValidGetExecUser(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash adm:x:42:43:adm:/var/adm:/bin/false this is just some garbage data ` const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm this is just some garbage data ` defaultExecUser := ExecUser{ Uid: 8888, Gid: 8888, Sgids: []int{8888}, Home: "/8888", } tests := []struct { ref string expected ExecUser }{ { ref: "root", expected: ExecUser{ Uid: 0, Gid: 0, Sgids: []int{0, 1234}, Home: "/root", }, }, { ref: "adm", expected: ExecUser{ Uid: 42, Gid: 43, Sgids: []int{1234}, Home: "/var/adm", }, }, { ref: "root:adm", expected: ExecUser{ Uid: 0, Gid: 43, Sgids: defaultExecUser.Sgids, Home: "/root", }, }, { ref: "adm:1234", expected: ExecUser{ Uid: 42, Gid: 1234, Sgids: defaultExecUser.Sgids, Home: "/var/adm", }, }, { ref: "42:1234", expected: ExecUser{ Uid: 42, Gid: 1234, Sgids: defaultExecUser.Sgids, Home: "/var/adm", }, }, { ref: "1337:1234", expected: ExecUser{ Uid: 1337, Gid: 1234, Sgids: defaultExecUser.Sgids, Home: defaultExecUser.Home, }, }, { ref: "1337", expected: ExecUser{ Uid: 1337, Gid: defaultExecUser.Gid, Sgids: defaultExecUser.Sgids, Home: defaultExecUser.Home, }, }, { ref: "", expected: ExecUser{ Uid: defaultExecUser.Uid, Gid: defaultExecUser.Gid, Sgids: defaultExecUser.Sgids, Home: defaultExecUser.Home, }, }, } for _, test := range tests { passwd := strings.NewReader(passwdContent) group := strings.NewReader(groupContent) execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) if err != nil { t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) t.Fail() continue } if !reflect.DeepEqual(test.expected, *execUser) { t.Logf("got: %#v", execUser) t.Logf("expected: %#v", test.expected) t.Fail() continue } } } func TestInvalidGetExecUser(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash adm:x:42:43:adm:/var/adm:/bin/false this is just some garbage data ` const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm this is just some garbage data ` tests := []string{ // No such user/group. "notuser", "notuser:notgroup", "root:notgroup", "notuser:adm", "8888:notgroup", "notuser:8888", // Invalid user/group values. "-1:0", "0:-3", "-5:-2", } for _, test := range tests { passwd := strings.NewReader(passwdContent) group := strings.NewReader(groupContent) execUser, err := GetExecUser(test, nil, passwd, group) if err == nil { t.Logf("got unexpected success when parsing '%s': %#v", test, execUser) t.Fail() continue } } } func TestGetExecUserNilSources(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash adm:x:42:43:adm:/var/adm:/bin/false this is just some garbage data ` const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm this is just some garbage data ` defaultExecUser := ExecUser{ Uid: 8888, Gid: 8888, Sgids: []int{8888}, Home: "/8888", } tests := []struct { ref string passwd, group bool expected ExecUser }{ { ref: "", passwd: false, group: false, expected: ExecUser{ Uid: 8888, Gid: 8888, Sgids: []int{8888}, Home: "/8888", }, }, { ref: "root", passwd: true, group: false, expected: ExecUser{ Uid: 0, Gid: 0, Sgids: []int{8888}, Home: "/root", }, }, { ref: "0", passwd: false, group: false, expected: ExecUser{ Uid: 0, Gid: 8888, Sgids: []int{8888}, Home: "/8888", }, }, { ref: "0:0", passwd: false, group: false, expected: ExecUser{ Uid: 0, Gid: 0, Sgids: []int{8888}, Home: "/8888", }, }, } for _, test := range tests { var passwd, group io.Reader if test.passwd { passwd = strings.NewReader(passwdContent) } if test.group { group = strings.NewReader(groupContent) } execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) if err != nil { t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) t.Fail() continue } if !reflect.DeepEqual(test.expected, *execUser) { t.Logf("got: %#v", execUser) t.Logf("expected: %#v", test.expected) t.Fail() continue } } } func TestGetAdditionalGroupsPath(t *testing.T) { const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm adm:x:4343:root,adm-duplicate this is just some garbage data ` tests := []struct { groups []string expected []int hasError bool }{ { // empty group groups: []string{}, expected: []int{}, }, { // single group groups: []string{"adm"}, expected: []int{43}, }, { // multiple groups groups: []string{"adm", "grp"}, expected: []int{43, 1234}, }, { // invalid group groups: []string{"adm", "grp", "not-exist"}, expected: nil, hasError: true, }, { // group with numeric id groups: []string{"43"}, expected: []int{43}, }, { // group with unknown numeric id groups: []string{"adm", "10001"}, expected: []int{43, 10001}, }, { // groups specified twice with numeric and name groups: []string{"adm", "43"}, expected: []int{43}, }, { // groups with too small id groups: []string{"-1"}, expected: nil, hasError: true, }, { // groups with too large id groups: []string{strconv.Itoa(1 << 31)}, expected: nil, hasError: true, }, } for _, test := range tests { tmpFile, err := ioutil.TempFile("", "get-additional-groups-path") if err != nil { t.Error(err) } fmt.Fprint(tmpFile, groupContent) tmpFile.Close() gids, err := GetAdditionalGroupsPath(test.groups, tmpFile.Name()) if test.hasError && err == nil { t.Errorf("Parse(%#v) expects error but has none", test) continue } if !test.hasError && err != nil { t.Errorf("Parse(%#v) has error %v", test, err) continue } sort.Sort(sort.IntSlice(gids)) if !reflect.DeepEqual(gids, test.expected) { t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) } } } ================================================ FILE: vendor/github.com/docker/libcontainer/utils/utils.go ================================================ package utils import ( "crypto/rand" "encoding/hex" "io" "io/ioutil" "path/filepath" "strconv" "syscall" ) 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) } 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 } // ExitStatus returns the correct exit status for a process based on if it // was signaled or existed cleanly. func ExitStatus(status syscall.WaitStatus) int { if status.Signaled() { return exitSignalOffset + int(status.Signal()) } return status.ExitStatus() } ================================================ FILE: vendor/github.com/docker/libcontainer/utils/utils_test.go ================================================ package utils import "testing" func TestGenerateName(t *testing.T) { name, err := GenerateRandomName("veth", 5) if err != nil { t.Fatal(err) } expected := 5 + len("veth") if len(name) != expected { t.Fatalf("expected name to be %d chars but received %d", expected, len(name)) } name, err = GenerateRandomName("veth", 65) if err != nil { t.Fatal(err) } expected = 64 + len("veth") if len(name) != expected { t.Fatalf("expected name to be %d chars but received %d", expected, len(name)) } } ================================================ FILE: vendor/github.com/docker/libcontainer/xattr/errors.go ================================================ package xattr import ( "fmt" "runtime" ) var ErrNotSupportedPlatform = fmt.Errorf("platform and architecture is not supported %s %s", runtime.GOOS, runtime.GOARCH) ================================================ FILE: vendor/github.com/docker/libcontainer/xattr/xattr_linux.go ================================================ // +build linux package xattr import ( "syscall" "github.com/docker/libcontainer/system" ) func XattrEnabled(path string) bool { if Setxattr(path, "user.test", "") == syscall.ENOTSUP { return false } return true } func stringsfromByte(buf []byte) (result []string) { offset := 0 for index, b := range buf { if b == 0 { result = append(result, string(buf[offset:index])) offset = index + 1 } } return } func Listxattr(path string) ([]string, error) { size, err := system.Llistxattr(path, nil) if err != nil { return nil, err } buf := make([]byte, size) read, err := system.Llistxattr(path, buf) if err != nil { return nil, err } names := stringsfromByte(buf[:read]) return names, nil } func Getxattr(path, attr string) (string, error) { value, err := system.Lgetxattr(path, attr) if err != nil { return "", err } return string(value), nil } func Setxattr(path, xattr, value string) error { return system.Lsetxattr(path, xattr, []byte(value), 0) } ================================================ FILE: vendor/github.com/docker/libcontainer/xattr/xattr_test.go ================================================ // +build linux package xattr_test import ( "os" "testing" "github.com/docker/libcontainer/xattr" ) func testXattr(t *testing.T) { tmp := "xattr_test" out, err := os.OpenFile(tmp, os.O_WRONLY, 0) if err != nil { t.Fatal("failed") } attr := "user.test" out.Close() if !xattr.XattrEnabled(tmp) { t.Log("Disabled") t.Fatal("failed") } t.Log("Success") err = xattr.Setxattr(tmp, attr, "test") if err != nil { t.Fatal("failed") } var value string value, err = xattr.Getxattr(tmp, attr) if err != nil { t.Fatal("failed") } if value != "test" { t.Fatal("failed") } t.Log("Success") var names []string names, err = xattr.Listxattr(tmp) if err != nil { t.Fatal("failed") } var found int for _, name := range names { if name == attr { found = 1 } } // Listxattr doesn't return trusted.* and system.* namespace // attrs when run in unprevileged mode. if found != 1 { t.Fatal("failed") } t.Log("Success") big := "0000000000000000000000000000000000000000000000000000000000000000000008c6419ad822dfe29283fb3ac98dcc5908810cb31f4cfe690040c42c144b7492eicompslf20dxmlpgz" // Test for long xattrs larger than 128 bytes err = xattr.Setxattr(tmp, attr, big) if err != nil { t.Fatal("failed to add long value") } value, err = xattr.Getxattr(tmp, attr) if err != nil { t.Fatal("failed to get long value") } t.Log("Success") if value != big { t.Fatal("failed, value doesn't match") } t.Log("Success") } ================================================ FILE: vendor/github.com/docker/libcontainer/xattr/xattr_unsupported.go ================================================ // +build !linux package xattr func Listxattr(path string) ([]string, error) { return nil, ErrNotSupportedPlatform } func Getxattr(path, attr string) (string, error) { return "", ErrNotSupportedPlatform } func Setxattr(path, xattr, value string) error { return ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/emicklei/go-restful/.gitignore ================================================ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe restful.html *.out tmp.prof go-restful.test examples/restful-basic-authentication examples/restful-encoding-filter examples/restful-filters examples/restful-hello-world examples/restful-resource-functions examples/restful-serve-static examples/restful-user-service *.DS_Store examples/restful-user-resource examples/restful-multi-containers examples/restful-form-handling examples/restful-CORS-filter examples/restful-options-filter examples/restful-curly-router examples/restful-cpuprofiler-service examples/restful-pre-post-filters curly.prof examples/restful-NCSA-logging examples/restful-html-template s.html restful-path-tail ================================================ FILE: vendor/github.com/emicklei/go-restful/CHANGES.md ================================================ Change history of go-restful = 2015-09-27 - rename new WriteStatusAnd... to WriteHeaderAnd... for consistency 2015-09-25 - fixed problem with changing Header after WriteHeader (issue 235) 2015-09-14 - changed behavior of WriteHeader (immediate write) and WriteEntity (no status write) - added support for custom EntityReaderWriters. 2015-08-06 - add support for reading entities from compressed request content - use sync.Pool for compressors of http response and request body - add Description to Parameter for documentation in Swagger UI 2015-03-20 - add configurable logging 2015-03-18 - if not specified, the Operation is derived from the Route function 2015-03-17 - expose Parameter creation functions - make trace logger an interface - fix OPTIONSFilter - customize rendering of ServiceError - JSR311 router now handles wildcards - add Notes to Route 2014-11-27 - (api add) PrettyPrint per response. (as proposed in #167) 2014-11-12 - (api add) ApiVersion(.) for documentation in Swagger UI 2014-11-10 - (api change) struct fields tagged with "description" show up in Swagger UI 2014-10-31 - (api change) ReturnsError -> Returns - (api add) RouteBuilder.Do(aBuilder) for DRY use of RouteBuilder - fix swagger nested structs - sort Swagger response messages by code 2014-10-23 - (api add) ReturnsError allows you to document Http codes in swagger - fixed problem with greedy CurlyRouter - (api add) Access-Control-Max-Age in CORS - add tracing functionality (injectable) for debugging purposes - support JSON parse 64bit int - fix empty parameters for swagger - WebServicesUrl is now optional for swagger - fixed duplicate AccessControlAllowOrigin in CORS - (api change) expose ServeMux in container - (api add) added AllowedDomains in CORS - (api add) ParameterNamed for detailed documentation 2014-04-16 - (api add) expose constructor of Request for testing. 2014-06-27 - (api add) ParameterNamed gives access to a Parameter definition and its data (for further specification). - (api add) SetCacheReadEntity allow scontrol over whether or not the request body is being cached (default true for compatibility reasons). 2014-07-03 - (api add) CORS can be configured with a list of allowed domains 2014-03-12 - (api add) Route path parameters can use wildcard or regular expressions. (requires CurlyRouter) 2014-02-26 - (api add) Request now provides information about the matched Route, see method SelectedRoutePath 2014-02-17 - (api change) renamed parameter constants (go-lint checks) 2014-01-10 - (api add) support for CloseNotify, see http://golang.org/pkg/net/http/#CloseNotifier 2014-01-07 - (api change) Write* methods in Response now return the error or nil. - added example of serving HTML from a Go template. - fixed comparing Allowed headers in CORS (is now case-insensitive) 2013-11-13 - (api add) Response knows how many bytes are written to the response body. 2013-10-29 - (api add) RecoverHandler(handler RecoverHandleFunction) to change how panic recovery is handled. Default behavior is to log and return a stacktrace. This may be a security issue as it exposes sourcecode information. 2013-10-04 - (api add) Response knows what HTTP status has been written - (api add) Request can have attributes (map of string->interface, also called request-scoped variables 2013-09-12 - (api change) Router interface simplified - Implemented CurlyRouter, a Router that does not use|allow regular expressions in paths 2013-08-05 - add OPTIONS support - add CORS support 2013-08-27 - fixed some reported issues (see github) - (api change) deprecated use of WriteError; use WriteErrorString instead 2014-04-15 - (fix) v1.0.1 tag: fix Issue 111: WriteErrorString 2013-08-08 - (api add) Added implementation Container: a WebServices collection with its own http.ServeMux allowing multiple endpoints per program. Existing uses of go-restful will register their services to the DefaultContainer. - (api add) the swagger package has be extended to have a UI per container. - if panic is detected then a small stack trace is printed (thanks to runner-mei) - (api add) WriteErrorString to Response Important API changes: - (api remove) package variable DoNotRecover no longer works ; use restful.DefaultContainer.DoNotRecover(true) instead. - (api remove) package variable EnableContentEncoding no longer works ; use restful.DefaultContainer.EnableContentEncoding(true) instead. 2013-07-06 - (api add) Added support for response encoding (gzip and deflate(zlib)). This feature is disabled on default (for backwards compatibility). Use restful.EnableContentEncoding = true in your initialization to enable this feature. 2013-06-19 - (improve) DoNotRecover option, moved request body closer, improved ReadEntity 2013-06-03 - (api change) removed Dispatcher interface, hide PathExpression - changed receiver names of type functions to be more idiomatic Go 2013-06-02 - (optimize) Cache the RegExp compilation of Paths. 2013-05-22 - (api add) Added support for request/response filter functions 2013-05-18 - (api add) Added feature to change the default Http Request Dispatch function (travis cline) - (api change) Moved Swagger Webservice to swagger package (see example restful-user) [2012-11-14 .. 2013-05-18> - See https://github.com/emicklei/go-restful/commits 2012-11-14 - Initial commit ================================================ FILE: vendor/github.com/emicklei/go-restful/LICENSE ================================================ Copyright (c) 2012,2013 Ernest Micklei MIT License 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. ================================================ FILE: vendor/github.com/emicklei/go-restful/README.md ================================================ go-restful ========== package for building REST-style Web Services using Google Go REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping: - GET = Retrieve a representation of a resource - POST = Create if you are sending content to the server to create a subordinate of the specified resource collection, using some server-side algorithm. - PUT = Create if you are sending the full content of the specified resource (URI). - PUT = Update if you are updating the full content of the specified resource. - DELETE = Delete if you are requesting the server to delete the resource - PATCH = Update partial content of a resource - OPTIONS = Get information about the communication options for the request URI ### Example ```Go ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser). Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) ... func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } ``` [Full API of a UserResource](https://github.com/emicklei/go-restful/tree/master/examples/restful-user-resource.go) ### Features - Routes for request → function mapping with path parameter (e.g. {id}) support - Configurable router: - Routing algorithm after [JSR311](http://jsr311.java.net/nonav/releases/1.1/spec/spec.html) that is implemented using (but doest **not** accept) regular expressions (See RouterJSR311 which is used by default) - Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}, See CurlyRouter) - Request API for reading structs from JSON/XML and accesing parameters (path,query,header) - Response API for writing structs to JSON/XML and setting headers - Filters for intercepting the request → response flow on Service or Route level - Request-scoped variables using attributes - Containers for WebServices on different HTTP endpoints - Content encoding (gzip,deflate) of request and response payloads - Automatic responses on OPTIONS (using a filter) - Automatic CORS request handling (using a filter) - API declaration for Swagger UI (see swagger package) - Panic recovery to produce HTTP 500, customizable using RecoverHandler(...) - Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...) - Configurable (trace) logging - Customizable encoding using EntityReaderWriter registration - Customizable gzip/deflate readers and writers using CompressorProvider registration ### Resources - [Documentation on godoc.org](http://godoc.org/github.com/emicklei/go-restful) - [Code examples](https://github.com/emicklei/go-restful/tree/master/examples) - [Example posted on blog](http://ernestmicklei.com/2012/11/24/go-restful-first-working-example/) - [Design explained on blog](http://ernestmicklei.com/2012/11/11/go-restful-api-design/) - [sourcegraph](https://sourcegraph.com/github.com/emicklei/go-restful) - [gopkg.in](https://gopkg.in/emicklei/go-restful.v1) - [showcase: Mora - MongoDB REST Api server](https://github.com/emicklei/mora) [![Build Status](https://drone.io/github.com/emicklei/go-restful/status.png)](https://drone.io/github.com/emicklei/go-restful/latest) (c) 2012 - 2015, http://ernestmicklei.com. MIT License Type ```git shortlog -s``` for a full list of contributors. ================================================ FILE: vendor/github.com/emicklei/go-restful/Srcfile ================================================ {"SkipDirs": ["examples"]} ================================================ FILE: vendor/github.com/emicklei/go-restful/bench_curly_test.go ================================================ package restful import ( "fmt" "net/http" "net/http/httptest" "testing" ) func setupCurly(container *Container) []string { wsCount := 26 rtCount := 26 urisCurly := []string{} container.Router(CurlyRouter{}) for i := 0; i < wsCount; i++ { root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) ws := new(WebService).Path(root) for j := 0; j < rtCount; j++ { sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) ws.Route(ws.GET(sub).Consumes("application/xml").Produces("application/xml").To(echoCurly)) } container.Add(ws) for _, each := range ws.Routes() { urisCurly = append(urisCurly, "http://bench.com"+each.Path) } } return urisCurly } func echoCurly(req *Request, resp *Response) {} func BenchmarkManyCurly(b *testing.B) { container := NewContainer() urisCurly := setupCurly(container) b.ResetTimer() for t := 0; t < b.N; t++ { for r := 0; r < 1000; r++ { for _, each := range urisCurly { sendNoReturnTo(each, container, t) } } } } func sendNoReturnTo(address string, container *Container, t int) { httpRequest, _ := http.NewRequest("GET", address, nil) httpRequest.Header.Set("Accept", "application/xml") httpWriter := httptest.NewRecorder() container.dispatch(httpWriter, httpRequest) } ================================================ FILE: vendor/github.com/emicklei/go-restful/bench_test.go ================================================ package restful import ( "fmt" "io" "testing" ) var uris = []string{} func setup(container *Container) { wsCount := 26 rtCount := 26 for i := 0; i < wsCount; i++ { root := fmt.Sprintf("/%s/{%s}/", string(i+97), string(i+97)) ws := new(WebService).Path(root) for j := 0; j < rtCount; j++ { sub := fmt.Sprintf("/%s2/{%s2}", string(j+97), string(j+97)) ws.Route(ws.GET(sub).To(echo)) } container.Add(ws) for _, each := range ws.Routes() { uris = append(uris, "http://bench.com"+each.Path) } } } func echo(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "echo") } func BenchmarkMany(b *testing.B) { container := NewContainer() setup(container) b.ResetTimer() for t := 0; t < b.N; t++ { for _, each := range uris { // println(each) sendItTo(each, container) } } } ================================================ FILE: vendor/github.com/emicklei/go-restful/bench_test.sh ================================================ #go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out go test -c ./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany ./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly #go tool pprof go-restful.test tmp.prof go tool pprof go-restful.test curly.prof ================================================ FILE: vendor/github.com/emicklei/go-restful/compress.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "compress/gzip" "compress/zlib" "errors" "io" "net/http" "strings" ) // OBSOLETE : use restful.DefaultContainer.EnableContentEncoding(true) to change this setting. var EnableContentEncoding = false // CompressingResponseWriter is a http.ResponseWriter that can perform content encoding (gzip and zlib) type CompressingResponseWriter struct { writer http.ResponseWriter compressor io.WriteCloser encoding string } // Header is part of http.ResponseWriter interface func (c *CompressingResponseWriter) Header() http.Header { return c.writer.Header() } // WriteHeader is part of http.ResponseWriter interface func (c *CompressingResponseWriter) WriteHeader(status int) { c.writer.WriteHeader(status) } // Write is part of http.ResponseWriter interface // It is passed through the compressor func (c *CompressingResponseWriter) Write(bytes []byte) (int, error) { if c.isCompressorClosed() { return -1, errors.New("Compressing error: tried to write data using closed compressor") } return c.compressor.Write(bytes) } // CloseNotify is part of http.CloseNotifier interface func (c *CompressingResponseWriter) CloseNotify() <-chan bool { return c.writer.(http.CloseNotifier).CloseNotify() } // Close the underlying compressor func (c *CompressingResponseWriter) Close() error { if c.isCompressorClosed() { return errors.New("Compressing error: tried to close already closed compressor") } c.compressor.Close() if ENCODING_GZIP == c.encoding { currentCompressorProvider.ReleaseGzipWriter(c.compressor.(*gzip.Writer)) } if ENCODING_DEFLATE == c.encoding { currentCompressorProvider.ReleaseZlibWriter(c.compressor.(*zlib.Writer)) } // gc hint needed? c.compressor = nil return nil } func (c *CompressingResponseWriter) isCompressorClosed() bool { return nil == c.compressor } // WantsCompressedResponse reads the Accept-Encoding header to see if and which encoding is requested. func wantsCompressedResponse(httpRequest *http.Request) (bool, string) { header := httpRequest.Header.Get(HEADER_AcceptEncoding) gi := strings.Index(header, ENCODING_GZIP) zi := strings.Index(header, ENCODING_DEFLATE) // use in order of appearance if gi == -1 { return zi != -1, ENCODING_DEFLATE } else if zi == -1 { return gi != -1, ENCODING_GZIP } else { if gi < zi { return true, ENCODING_GZIP } return true, ENCODING_DEFLATE } } // NewCompressingResponseWriter create a CompressingResponseWriter for a known encoding = {gzip,deflate} func NewCompressingResponseWriter(httpWriter http.ResponseWriter, encoding string) (*CompressingResponseWriter, error) { httpWriter.Header().Set(HEADER_ContentEncoding, encoding) c := new(CompressingResponseWriter) c.writer = httpWriter var err error if ENCODING_GZIP == encoding { w := currentCompressorProvider.AcquireGzipWriter() w.Reset(httpWriter) c.compressor = w c.encoding = ENCODING_GZIP } else if ENCODING_DEFLATE == encoding { w := currentCompressorProvider.AcquireZlibWriter() w.Reset(httpWriter) c.compressor = w c.encoding = ENCODING_DEFLATE } else { return nil, errors.New("Unknown encoding:" + encoding) } return c, err } ================================================ FILE: vendor/github.com/emicklei/go-restful/compress_test.go ================================================ package restful import ( "bytes" "compress/gzip" "compress/zlib" "io" "io/ioutil" "net/http" "net/http/httptest" "testing" ) // go test -v -test.run TestGzip ...restful func TestGzip(t *testing.T) { EnableContentEncoding = true httpRequest, _ := http.NewRequest("GET", "/test", nil) httpRequest.Header.Set("Accept-Encoding", "gzip,deflate") httpWriter := httptest.NewRecorder() wanted, encoding := wantsCompressedResponse(httpRequest) if !wanted { t.Fatal("should accept gzip") } if encoding != "gzip" { t.Fatal("expected gzip") } c, err := NewCompressingResponseWriter(httpWriter, encoding) if err != nil { t.Fatal(err.Error()) } c.Write([]byte("Hello World")) c.Close() if httpWriter.Header().Get("Content-Encoding") != "gzip" { t.Fatal("Missing gzip header") } reader, err := gzip.NewReader(httpWriter.Body) if err != nil { t.Fatal(err.Error()) } data, err := ioutil.ReadAll(reader) if err != nil { t.Fatal(err.Error()) } if got, want := string(data), "Hello World"; got != want { t.Errorf("got %v want %v", got, want) } } func TestDeflate(t *testing.T) { EnableContentEncoding = true httpRequest, _ := http.NewRequest("GET", "/test", nil) httpRequest.Header.Set("Accept-Encoding", "deflate,gzip") httpWriter := httptest.NewRecorder() wanted, encoding := wantsCompressedResponse(httpRequest) if !wanted { t.Fatal("should accept deflate") } if encoding != "deflate" { t.Fatal("expected deflate") } c, err := NewCompressingResponseWriter(httpWriter, encoding) if err != nil { t.Fatal(err.Error()) } c.Write([]byte("Hello World")) c.Close() if httpWriter.Header().Get("Content-Encoding") != "deflate" { t.Fatal("Missing deflate header") } reader, err := zlib.NewReader(httpWriter.Body) if err != nil { t.Fatal(err.Error()) } data, err := ioutil.ReadAll(reader) if err != nil { t.Fatal(err.Error()) } if got, want := string(data), "Hello World"; got != want { t.Errorf("got %v want %v", got, want) } } func TestGzipDecompressRequestBody(t *testing.T) { b := new(bytes.Buffer) w := newGzipWriter() w.Reset(b) io.WriteString(w, `{"msg":"hi"}`) w.Flush() w.Close() req := new(Request) httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) httpRequest.Header.Set("Content-Type", "application/json") httpRequest.Header.Set("Content-Encoding", "gzip") req.Request = httpRequest doCacheReadEntityBytes = false doc := make(map[string]interface{}) req.ReadEntity(&doc) if got, want := doc["msg"], "hi"; got != want { t.Errorf("got %v want %v", got, want) } } func TestZlibDecompressRequestBody(t *testing.T) { b := new(bytes.Buffer) w := newZlibWriter() w.Reset(b) io.WriteString(w, `{"msg":"hi"}`) w.Flush() w.Close() req := new(Request) httpRequest, _ := http.NewRequest("GET", "/", bytes.NewReader(b.Bytes())) httpRequest.Header.Set("Content-Type", "application/json") httpRequest.Header.Set("Content-Encoding", "deflate") req.Request = httpRequest doCacheReadEntityBytes = false doc := make(map[string]interface{}) req.ReadEntity(&doc) if got, want := doc["msg"], "hi"; got != want { t.Errorf("got %v want %v", got, want) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/compressor_cache.go ================================================ package restful // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "compress/gzip" "compress/zlib" ) // BoundedCachedCompressors is a CompressorProvider that uses a cache with a fixed amount // of writers and readers (resources). // If a new resource is acquired and all are in use, it will return a new unmanaged resource. type BoundedCachedCompressors struct { gzipWriters chan *gzip.Writer gzipReaders chan *gzip.Reader zlibWriters chan *zlib.Writer writersCapacity int readersCapacity int } // NewBoundedCachedCompressors returns a new, with filled cache, BoundedCachedCompressors. func NewBoundedCachedCompressors(writersCapacity, readersCapacity int) *BoundedCachedCompressors { b := &BoundedCachedCompressors{ gzipWriters: make(chan *gzip.Writer, writersCapacity), gzipReaders: make(chan *gzip.Reader, readersCapacity), zlibWriters: make(chan *zlib.Writer, writersCapacity), writersCapacity: writersCapacity, readersCapacity: readersCapacity, } for ix := 0; ix < writersCapacity; ix++ { b.gzipWriters <- newGzipWriter() b.zlibWriters <- newZlibWriter() } for ix := 0; ix < readersCapacity; ix++ { b.gzipReaders <- newGzipReader() } return b } // AcquireGzipWriter returns an resettable *gzip.Writer. Needs to be released. func (b *BoundedCachedCompressors) AcquireGzipWriter() *gzip.Writer { var writer *gzip.Writer select { case writer, _ = <-b.gzipWriters: default: // return a new unmanaged one writer = newGzipWriter() } return writer } // ReleaseGzipWriter accepts a writer (does not have to be one that was cached) // only when the cache has room for it. It will ignore it otherwise. func (b *BoundedCachedCompressors) ReleaseGzipWriter(w *gzip.Writer) { // forget the unmanaged ones if len(b.gzipWriters) < b.writersCapacity { b.gzipWriters <- w } } // AcquireGzipReader returns a *gzip.Reader. Needs to be released. func (b *BoundedCachedCompressors) AcquireGzipReader() *gzip.Reader { var reader *gzip.Reader select { case reader, _ = <-b.gzipReaders: default: // return a new unmanaged one reader = newGzipReader() } return reader } // ReleaseGzipReader accepts a reader (does not have to be one that was cached) // only when the cache has room for it. It will ignore it otherwise. func (b *BoundedCachedCompressors) ReleaseGzipReader(r *gzip.Reader) { // forget the unmanaged ones if len(b.gzipReaders) < b.readersCapacity { b.gzipReaders <- r } } // AcquireZlibWriter returns an resettable *zlib.Writer. Needs to be released. func (b *BoundedCachedCompressors) AcquireZlibWriter() *zlib.Writer { var writer *zlib.Writer select { case writer, _ = <-b.zlibWriters: default: // return a new unmanaged one writer = newZlibWriter() } return writer } // ReleaseZlibWriter accepts a writer (does not have to be one that was cached) // only when the cache has room for it. It will ignore it otherwise. func (b *BoundedCachedCompressors) ReleaseZlibWriter(w *zlib.Writer) { // forget the unmanaged ones if len(b.zlibWriters) < b.writersCapacity { b.zlibWriters <- w } } ================================================ FILE: vendor/github.com/emicklei/go-restful/compressor_pools.go ================================================ package restful // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "compress/gzip" "compress/zlib" "sync" ) // SyncPoolCompessors is a CompressorProvider that use the standard sync.Pool. type SyncPoolCompessors struct { GzipWriterPool *sync.Pool GzipReaderPool *sync.Pool ZlibWriterPool *sync.Pool } // NewSyncPoolCompessors returns a new ("empty") SyncPoolCompessors. func NewSyncPoolCompessors() *SyncPoolCompessors { return &SyncPoolCompessors{ GzipWriterPool: &sync.Pool{ New: func() interface{} { return newGzipWriter() }, }, GzipReaderPool: &sync.Pool{ New: func() interface{} { return newGzipReader() }, }, ZlibWriterPool: &sync.Pool{ New: func() interface{} { return newZlibWriter() }, }, } } func (s *SyncPoolCompessors) AcquireGzipWriter() *gzip.Writer { return s.GzipWriterPool.Get().(*gzip.Writer) } func (s *SyncPoolCompessors) ReleaseGzipWriter(w *gzip.Writer) { s.GzipWriterPool.Put(w) } func (s *SyncPoolCompessors) AcquireGzipReader() *gzip.Reader { return s.GzipReaderPool.Get().(*gzip.Reader) } func (s *SyncPoolCompessors) ReleaseGzipReader(r *gzip.Reader) { s.GzipReaderPool.Put(r) } func (s *SyncPoolCompessors) AcquireZlibWriter() *zlib.Writer { return s.ZlibWriterPool.Get().(*zlib.Writer) } func (s *SyncPoolCompessors) ReleaseZlibWriter(w *zlib.Writer) { s.ZlibWriterPool.Put(w) } func newGzipWriter() *gzip.Writer { // create with an empty bytes writer; it will be replaced before using the gzipWriter writer, err := gzip.NewWriterLevel(new(bytes.Buffer), gzip.BestSpeed) if err != nil { panic(err.Error()) } return writer } func newGzipReader() *gzip.Reader { // create with an empty reader (but with GZIP header); it will be replaced before using the gzipReader // we can safely use currentCompressProvider because it is set on package initialization. w := currentCompressorProvider.AcquireGzipWriter() defer currentCompressorProvider.ReleaseGzipWriter(w) b := new(bytes.Buffer) w.Reset(b) w.Flush() w.Close() reader, err := gzip.NewReader(bytes.NewReader(b.Bytes())) if err != nil { panic(err.Error()) } return reader } func newZlibWriter() *zlib.Writer { writer, err := zlib.NewWriterLevel(new(bytes.Buffer), gzip.BestSpeed) if err != nil { panic(err.Error()) } return writer } ================================================ FILE: vendor/github.com/emicklei/go-restful/compressors.go ================================================ package restful // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "compress/gzip" "compress/zlib" ) type CompressorProvider interface { // Returns a *gzip.Writer which needs to be released later. // Before using it, call Reset(). AcquireGzipWriter() *gzip.Writer // Releases an aqcuired *gzip.Writer. ReleaseGzipWriter(w *gzip.Writer) // Returns a *gzip.Reader which needs to be released later. AcquireGzipReader() *gzip.Reader // Releases an aqcuired *gzip.Reader. ReleaseGzipReader(w *gzip.Reader) // Returns a *zlib.Writer which needs to be released later. // Before using it, call Reset(). AcquireZlibWriter() *zlib.Writer // Releases an aqcuired *zlib.Writer. ReleaseZlibWriter(w *zlib.Writer) } // DefaultCompressorProvider is the actual provider of compressors (zlib or gzip). var currentCompressorProvider CompressorProvider func init() { currentCompressorProvider = NewSyncPoolCompessors() } // CurrentCompressorProvider returns the current CompressorProvider. // It is initialized using a SyncPoolCompessors. func CurrentCompressorProvider() CompressorProvider { return currentCompressorProvider } // CompressorProvider sets the actual provider of compressors (zlib or gzip). func SetCompressorProvider(p CompressorProvider) { if p == nil { panic("cannot set compressor provider to nil") } currentCompressorProvider = p } ================================================ FILE: vendor/github.com/emicklei/go-restful/constants.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. const ( MIME_XML = "application/xml" // Accept or Content-Type used in Consumes() and/or Produces() MIME_JSON = "application/json" // Accept or Content-Type used in Consumes() and/or Produces() MIME_OCTET = "application/octet-stream" // If Content-Type is not present in request, use the default HEADER_Allow = "Allow" HEADER_Accept = "Accept" HEADER_Origin = "Origin" HEADER_ContentType = "Content-Type" HEADER_LastModified = "Last-Modified" HEADER_AcceptEncoding = "Accept-Encoding" HEADER_ContentEncoding = "Content-Encoding" HEADER_AccessControlExposeHeaders = "Access-Control-Expose-Headers" HEADER_AccessControlRequestMethod = "Access-Control-Request-Method" HEADER_AccessControlRequestHeaders = "Access-Control-Request-Headers" HEADER_AccessControlAllowMethods = "Access-Control-Allow-Methods" HEADER_AccessControlAllowOrigin = "Access-Control-Allow-Origin" HEADER_AccessControlAllowCredentials = "Access-Control-Allow-Credentials" HEADER_AccessControlAllowHeaders = "Access-Control-Allow-Headers" HEADER_AccessControlMaxAge = "Access-Control-Max-Age" ENCODING_GZIP = "gzip" ENCODING_DEFLATE = "deflate" ) ================================================ FILE: vendor/github.com/emicklei/go-restful/container.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "fmt" "net/http" "os" "runtime" "strings" "sync" "github.com/emicklei/go-restful/log" ) // Container holds a collection of WebServices and a http.ServeMux to dispatch http requests. // The requests are further dispatched to routes of WebServices using a RouteSelector type Container struct { webServicesLock sync.RWMutex webServices []*WebService ServeMux *http.ServeMux isRegisteredOnRoot bool containerFilters []FilterFunction doNotRecover bool // default is false recoverHandleFunc RecoverHandleFunction serviceErrorHandleFunc ServiceErrorHandleFunction router RouteSelector // default is a RouterJSR311, CurlyRouter is the faster alternative contentEncodingEnabled bool // default is false } // NewContainer creates a new Container using a new ServeMux and default router (RouterJSR311) func NewContainer() *Container { return &Container{ webServices: []*WebService{}, ServeMux: http.NewServeMux(), isRegisteredOnRoot: false, containerFilters: []FilterFunction{}, doNotRecover: false, recoverHandleFunc: logStackOnRecover, serviceErrorHandleFunc: writeServiceError, router: RouterJSR311{}, contentEncodingEnabled: false} } // RecoverHandleFunction declares functions that can be used to handle a panic situation. // The first argument is what recover() returns. The second must be used to communicate an error response. type RecoverHandleFunction func(interface{}, http.ResponseWriter) // RecoverHandler changes the default function (logStackOnRecover) to be called // when a panic is detected. DoNotRecover must be have its default value (=false). func (c *Container) RecoverHandler(handler RecoverHandleFunction) { c.recoverHandleFunc = handler } // ServiceErrorHandleFunction declares functions that can be used to handle a service error situation. // The first argument is the service error, the second is the request that resulted in the error and // the third must be used to communicate an error response. type ServiceErrorHandleFunction func(ServiceError, *Request, *Response) // ServiceErrorHandler changes the default function (writeServiceError) to be called // when a ServiceError is detected. func (c *Container) ServiceErrorHandler(handler ServiceErrorHandleFunction) { c.serviceErrorHandleFunc = handler } // DoNotRecover controls whether panics will be caught to return HTTP 500. // If set to true, Route functions are responsible for handling any error situation. // Default value is false = recover from panics. This has performance implications. func (c *Container) DoNotRecover(doNot bool) { c.doNotRecover = doNot } // Router changes the default Router (currently RouterJSR311) func (c *Container) Router(aRouter RouteSelector) { c.router = aRouter } // EnableContentEncoding (default=false) allows for GZIP or DEFLATE encoding of responses. func (c *Container) EnableContentEncoding(enabled bool) { c.contentEncodingEnabled = enabled } // Add a WebService to the Container. It will detect duplicate root paths and panic in that case. func (c *Container) Add(service *WebService) *Container { c.webServicesLock.Lock() defer c.webServicesLock.Unlock() // If registered on root then no additional specific mapping is needed if !c.isRegisteredOnRoot { pattern := c.fixedPrefixPath(service.RootPath()) // check if root path registration is needed if "/" == pattern || "" == pattern { c.ServeMux.HandleFunc("/", c.dispatch) c.isRegisteredOnRoot = true } else { // detect if registration already exists alreadyMapped := false for _, each := range c.webServices { if each.RootPath() == service.RootPath() { alreadyMapped = true break } } if !alreadyMapped { c.ServeMux.HandleFunc(pattern, c.dispatch) if !strings.HasSuffix(pattern, "/") { c.ServeMux.HandleFunc(pattern+"/", c.dispatch) } } } } // cannot have duplicate root paths for _, each := range c.webServices { if each.RootPath() == service.RootPath() { log.Printf("[restful] WebService with duplicate root path detected:['%v']", each) os.Exit(1) } } // if rootPath was not set then lazy initialize it if len(service.rootPath) == 0 { service.Path("/") } c.webServices = append(c.webServices, service) return c } func (c *Container) Remove(ws *WebService) error { c.webServicesLock.Lock() defer c.webServicesLock.Unlock() newServices := []*WebService{} for ix := range c.webServices { if c.webServices[ix].rootPath != ws.rootPath { newServices = append(newServices, c.webServices[ix]) } } c.webServices = newServices return nil } // logStackOnRecover is the default RecoverHandleFunction and is called // when DoNotRecover is false and the recoverHandleFunc is not set for the container. // Default implementation logs the stacktrace and writes the stacktrace on the response. // This may be a security issue as it exposes sourcecode information. func logStackOnRecover(panicReason interface{}, httpWriter http.ResponseWriter) { var buffer bytes.Buffer buffer.WriteString(fmt.Sprintf("[restful] recover from panic situation: - %v\r\n", panicReason)) for i := 2; ; i += 1 { _, file, line, ok := runtime.Caller(i) if !ok { break } buffer.WriteString(fmt.Sprintf(" %s:%d\r\n", file, line)) } log.Print(buffer.String()) httpWriter.WriteHeader(http.StatusInternalServerError) httpWriter.Write(buffer.Bytes()) } // writeServiceError is the default ServiceErrorHandleFunction and is called // when a ServiceError is returned during route selection. Default implementation // calls resp.WriteErrorString(err.Code, err.Message) func writeServiceError(err ServiceError, req *Request, resp *Response) { resp.WriteErrorString(err.Code, err.Message) } // Dispatch the incoming Http Request to a matching WebService. func (c *Container) dispatch(httpWriter http.ResponseWriter, httpRequest *http.Request) { writer := httpWriter // CompressingResponseWriter should be closed after all operations are done defer func() { if compressWriter, ok := writer.(*CompressingResponseWriter); ok { compressWriter.Close() } }() // Instal panic recovery unless told otherwise if !c.doNotRecover { // catch all for 500 response defer func() { if r := recover(); r != nil { c.recoverHandleFunc(r, writer) return } }() } // Install closing the request body (if any) defer func() { if nil != httpRequest.Body { httpRequest.Body.Close() } }() // Detect if compression is needed // assume without compression, test for override if c.contentEncodingEnabled { doCompress, encoding := wantsCompressedResponse(httpRequest) if doCompress { var err error writer, err = NewCompressingResponseWriter(httpWriter, encoding) if err != nil { log.Print("[restful] unable to install compressor: ", err) httpWriter.WriteHeader(http.StatusInternalServerError) return } } } // Find best match Route ; err is non nil if no match was found var webService *WebService var route *Route var err error func() { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() webService, route, err = c.router.SelectRoute( c.webServices, httpRequest) }() if err != nil { // a non-200 response has already been written // run container filters anyway ; they should not touch the response... chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { switch err.(type) { case ServiceError: ser := err.(ServiceError) c.serviceErrorHandleFunc(ser, req, resp) } // TODO }} chain.ProcessFilter(NewRequest(httpRequest), NewResponse(writer)) return } wrappedRequest, wrappedResponse := route.wrapRequestResponse(writer, httpRequest) // pass through filters (if any) if len(c.containerFilters)+len(webService.filters)+len(route.Filters) > 0 { // compose filter chain allFilters := []FilterFunction{} allFilters = append(allFilters, c.containerFilters...) allFilters = append(allFilters, webService.filters...) allFilters = append(allFilters, route.Filters...) chain := FilterChain{Filters: allFilters, Target: func(req *Request, resp *Response) { // handle request by route after passing all filters route.Function(wrappedRequest, wrappedResponse) }} chain.ProcessFilter(wrappedRequest, wrappedResponse) } else { // no filters, handle request by route route.Function(wrappedRequest, wrappedResponse) } } // fixedPrefixPath returns the fixed part of the partspec ; it may include template vars {} func (c Container) fixedPrefixPath(pathspec string) string { varBegin := strings.Index(pathspec, "{") if -1 == varBegin { return pathspec } return pathspec[:varBegin] } // ServeHTTP implements net/http.Handler therefore a Container can be a Handler in a http.Server func (c Container) ServeHTTP(httpwriter http.ResponseWriter, httpRequest *http.Request) { c.ServeMux.ServeHTTP(httpwriter, httpRequest) } // Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics. func (c Container) Handle(pattern string, handler http.Handler) { c.ServeMux.Handle(pattern, handler) } // HandleWithFilter registers the handler for the given pattern. // Container's filter chain is applied for handler. // If a handler already exists for pattern, HandleWithFilter panics. func (c *Container) HandleWithFilter(pattern string, handler http.Handler) { f := func(httpResponse http.ResponseWriter, httpRequest *http.Request) { if len(c.containerFilters) == 0 { handler.ServeHTTP(httpResponse, httpRequest) return } chain := FilterChain{Filters: c.containerFilters, Target: func(req *Request, resp *Response) { handler.ServeHTTP(httpResponse, httpRequest) }} chain.ProcessFilter(NewRequest(httpRequest), NewResponse(httpResponse)) } c.Handle(pattern, http.HandlerFunc(f)) } // Filter appends a container FilterFunction. These are called before dispatching // a http.Request to a WebService from the container func (c *Container) Filter(filter FilterFunction) { c.containerFilters = append(c.containerFilters, filter) } // RegisteredWebServices returns the collections of added WebServices func (c Container) RegisteredWebServices() []*WebService { c.webServicesLock.RLock() defer c.webServicesLock.RUnlock() result := make([]*WebService, len(c.webServices)) for ix := range c.webServices { result[ix] = c.webServices[ix] } return result } // computeAllowedMethods returns a list of HTTP methods that are valid for a Request func (c Container) computeAllowedMethods(req *Request) []string { // Go through all RegisteredWebServices() and all its Routes to collect the options methods := []string{} requestPath := req.Request.URL.Path for _, ws := range c.RegisteredWebServices() { matches := ws.pathExpr.Matcher.FindStringSubmatch(requestPath) if matches != nil { finalMatch := matches[len(matches)-1] for _, rt := range ws.Routes() { matches := rt.pathExpr.Matcher.FindStringSubmatch(finalMatch) if matches != nil { lastMatch := matches[len(matches)-1] if lastMatch == "" || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. methods = append(methods, rt.Method) } } } } } // methods = append(methods, "OPTIONS") not sure about this return methods } // newBasicRequestResponse creates a pair of Request,Response from its http versions. // It is basic because no parameter or (produces) content-type information is given. func newBasicRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request) (*Request, *Response) { resp := NewResponse(httpWriter) resp.requestAccept = httpRequest.Header.Get(HEADER_Accept) return NewRequest(httpRequest), resp } ================================================ FILE: vendor/github.com/emicklei/go-restful/container_test.go ================================================ package restful import ( "net/http" "net/http/httptest" "testing" ) // go test -v -test.run TestContainer_computeAllowedMethods ...restful func TestContainer_computeAllowedMethods(t *testing.T) { wc := NewContainer() ws1 := new(WebService).Path("/users") ws1.Route(ws1.GET("{i}").To(dummy)) ws1.Route(ws1.POST("{i}").To(dummy)) wc.Add(ws1) httpRequest, _ := http.NewRequest("GET", "http://api.his.com/users/1", nil) rreq := Request{Request: httpRequest} m := wc.computeAllowedMethods(&rreq) if len(m) != 2 { t.Errorf("got %d expected 2 methods, %v", len(m), m) } } func TestContainer_HandleWithFilter(t *testing.T) { prefilterCalled := false postfilterCalled := false httpHandlerCalled := false wc := NewContainer() wc.Filter(func(request *Request, response *Response, chain *FilterChain) { prefilterCalled = true chain.ProcessFilter(request, response) }) wc.HandleWithFilter("/", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { httpHandlerCalled = true w.Write([]byte("ok")) })) wc.Filter(func(request *Request, response *Response, chain *FilterChain) { postfilterCalled = true chain.ProcessFilter(request, response) }) recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/", nil) wc.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("unexpected code %d", recorder.Code) } if recorder.Body.String() != "ok" { t.Errorf("unexpected body %s", recorder.Body.String()) } if !prefilterCalled { t.Errorf("filter added before calling HandleWithFilter wasn't called") } if !postfilterCalled { t.Errorf("filter added after calling HandleWithFilter wasn't called") } if !httpHandlerCalled { t.Errorf("handler added by calling HandleWithFilter wasn't called") } } ================================================ FILE: vendor/github.com/emicklei/go-restful/cors_filter.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "strconv" "strings" ) // CrossOriginResourceSharing is used to create a Container Filter that implements CORS. // Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page // to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. // // http://en.wikipedia.org/wiki/Cross-origin_resource_sharing // http://enable-cors.org/server.html // http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request type CrossOriginResourceSharing struct { ExposeHeaders []string // list of Header names AllowedHeaders []string // list of Header names AllowedDomains []string // list of allowed values for Http Origin. If empty all are allowed. AllowedMethods []string MaxAge int // number of seconds before requiring new Options request CookiesAllowed bool Container *Container } // Filter is a filter function that implements the CORS flow as documented on http://enable-cors.org/server.html // and http://www.html5rocks.com/static/images/cors_server_flowchart.png func (c CrossOriginResourceSharing) Filter(req *Request, resp *Response, chain *FilterChain) { origin := req.Request.Header.Get(HEADER_Origin) if len(origin) == 0 { if trace { traceLogger.Print("no Http header Origin set") } chain.ProcessFilter(req, resp) return } if len(c.AllowedDomains) > 0 { // if provided then origin must be included included := false for _, each := range c.AllowedDomains { if each == origin { included = true break } } if !included { if trace { traceLogger.Printf("HTTP Origin:%s is not part of %v", origin, c.AllowedDomains) } chain.ProcessFilter(req, resp) return } } if req.Request.Method != "OPTIONS" { c.doActualRequest(req, resp) chain.ProcessFilter(req, resp) return } if acrm := req.Request.Header.Get(HEADER_AccessControlRequestMethod); acrm != "" { c.doPreflightRequest(req, resp) } else { c.doActualRequest(req, resp) chain.ProcessFilter(req, resp) return } } func (c CrossOriginResourceSharing) doActualRequest(req *Request, resp *Response) { c.setOptionsHeaders(req, resp) // continue processing the response } func (c *CrossOriginResourceSharing) doPreflightRequest(req *Request, resp *Response) { if len(c.AllowedMethods) == 0 { c.AllowedMethods = c.Container.computeAllowedMethods(req) } acrm := req.Request.Header.Get(HEADER_AccessControlRequestMethod) if !c.isValidAccessControlRequestMethod(acrm, c.AllowedMethods) { if trace { traceLogger.Printf("Http header %s:%s is not in %v", HEADER_AccessControlRequestMethod, acrm, c.AllowedMethods) } return } acrhs := req.Request.Header.Get(HEADER_AccessControlRequestHeaders) if len(acrhs) > 0 { for _, each := range strings.Split(acrhs, ",") { if !c.isValidAccessControlRequestHeader(strings.Trim(each, " ")) { if trace { traceLogger.Printf("Http header %s:%s is not in %v", HEADER_AccessControlRequestHeaders, acrhs, c.AllowedHeaders) } return } } } resp.AddHeader(HEADER_AccessControlAllowMethods, strings.Join(c.AllowedMethods, ",")) resp.AddHeader(HEADER_AccessControlAllowHeaders, acrhs) c.setOptionsHeaders(req, resp) // return http 200 response, no body } func (c CrossOriginResourceSharing) setOptionsHeaders(req *Request, resp *Response) { c.checkAndSetExposeHeaders(resp) c.setAllowOriginHeader(req, resp) c.checkAndSetAllowCredentials(resp) if c.MaxAge > 0 { resp.AddHeader(HEADER_AccessControlMaxAge, strconv.Itoa(c.MaxAge)) } } func (c CrossOriginResourceSharing) isOriginAllowed(origin string) bool { if len(origin) == 0 { return false } if len(c.AllowedDomains) == 0 { return true } allowed := false for _, each := range c.AllowedDomains { if each == origin { allowed = true break } } return allowed } func (c CrossOriginResourceSharing) setAllowOriginHeader(req *Request, resp *Response) { origin := req.Request.Header.Get(HEADER_Origin) if c.isOriginAllowed(origin) { resp.AddHeader(HEADER_AccessControlAllowOrigin, origin) } } func (c CrossOriginResourceSharing) checkAndSetExposeHeaders(resp *Response) { if len(c.ExposeHeaders) > 0 { resp.AddHeader(HEADER_AccessControlExposeHeaders, strings.Join(c.ExposeHeaders, ",")) } } func (c CrossOriginResourceSharing) checkAndSetAllowCredentials(resp *Response) { if c.CookiesAllowed { resp.AddHeader(HEADER_AccessControlAllowCredentials, "true") } } func (c CrossOriginResourceSharing) isValidAccessControlRequestMethod(method string, allowedMethods []string) bool { for _, each := range allowedMethods { if each == method { return true } } return false } func (c CrossOriginResourceSharing) isValidAccessControlRequestHeader(header string) bool { for _, each := range c.AllowedHeaders { if strings.ToLower(each) == strings.ToLower(header) { return true } } return false } ================================================ FILE: vendor/github.com/emicklei/go-restful/cors_filter_test.go ================================================ package restful import ( "net/http" "net/http/httptest" "testing" ) // go test -v -test.run TestCORSFilter_Preflight ...restful // http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request func TestCORSFilter_Preflight(t *testing.T) { tearDown() ws := new(WebService) ws.Route(ws.PUT("/cors").To(dummy)) Add(ws) cors := CrossOriginResourceSharing{ ExposeHeaders: []string{"X-Custom-Header"}, AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, CookiesAllowed: true, Container: DefaultContainer} Filter(cors.Filter) // Preflight httpRequest, _ := http.NewRequest("OPTIONS", "http://api.alice.com/cors", nil) httpRequest.Method = "OPTIONS" httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") httpRequest.Header.Set(HEADER_AccessControlRequestMethod, "PUT") httpRequest.Header.Set(HEADER_AccessControlRequestHeaders, "X-Custom-Header, X-Additional-Header") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) if "http://api.bob.com" != actual { t.Fatal("expected: http://api.bob.com but got:" + actual) } actual = httpWriter.Header().Get(HEADER_AccessControlAllowMethods) if "PUT" != actual { t.Fatal("expected: PUT but got:" + actual) } actual = httpWriter.Header().Get(HEADER_AccessControlAllowHeaders) if "X-Custom-Header, X-Additional-Header" != actual { t.Fatal("expected: X-Custom-Header, X-Additional-Header but got:" + actual) } if !cors.isOriginAllowed("somewhere") { t.Fatal("origin expected to be allowed") } cors.AllowedDomains = []string{"overthere.com"} if cors.isOriginAllowed("somewhere") { t.Fatal("origin [somewhere] expected NOT to be allowed") } if !cors.isOriginAllowed("overthere.com") { t.Fatal("origin [overthere] expected to be allowed") } } // go test -v -test.run TestCORSFilter_Actual ...restful // http://www.html5rocks.com/en/tutorials/cors/#toc-handling-a-not-so-simple-request func TestCORSFilter_Actual(t *testing.T) { tearDown() ws := new(WebService) ws.Route(ws.PUT("/cors").To(dummy)) Add(ws) cors := CrossOriginResourceSharing{ ExposeHeaders: []string{"X-Custom-Header"}, AllowedHeaders: []string{"X-Custom-Header", "X-Additional-Header"}, CookiesAllowed: true, Container: DefaultContainer} Filter(cors.Filter) // Actual httpRequest, _ := http.NewRequest("PUT", "http://api.alice.com/cors", nil) httpRequest.Header.Set(HEADER_Origin, "http://api.bob.com") httpRequest.Header.Set("X-Custom-Header", "value") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) if "http://api.bob.com" != actual { t.Fatal("expected: http://api.bob.com but got:" + actual) } if httpWriter.Body.String() != "dummy" { t.Fatal("expected: dummy but got:" + httpWriter.Body.String()) } } var allowedDomainInput = []struct { domains []string origin string accepted bool }{ {[]string{}, "http://anything.com", true}, } // go test -v -test.run TestCORSFilter_AllowedDomains ...restful func TestCORSFilter_AllowedDomains(t *testing.T) { for _, each := range allowedDomainInput { tearDown() ws := new(WebService) ws.Route(ws.PUT("/cors").To(dummy)) Add(ws) cors := CrossOriginResourceSharing{ AllowedDomains: each.domains, CookiesAllowed: true, Container: DefaultContainer} Filter(cors.Filter) httpRequest, _ := http.NewRequest("PUT", "http://api.his.com/cors", nil) httpRequest.Header.Set(HEADER_Origin, each.origin) httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) actual := httpWriter.Header().Get(HEADER_AccessControlAllowOrigin) if actual != each.origin && each.accepted { t.Fatal("expected to be accepted") } if actual == each.origin && !each.accepted { t.Fatal("did not expect to be accepted") } } } ================================================ FILE: vendor/github.com/emicklei/go-restful/coverage.sh ================================================ go test -coverprofile=coverage.out go tool cover -html=coverage.out ================================================ FILE: vendor/github.com/emicklei/go-restful/curly.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "net/http" "regexp" "sort" "strings" ) // CurlyRouter expects Routes with paths that contain zero or more parameters in curly brackets. type CurlyRouter struct{} // SelectRoute is part of the Router interface and returns the best match // for the WebService and its Route for the given Request. func (c CurlyRouter) SelectRoute( webServices []*WebService, httpRequest *http.Request) (selectedService *WebService, selected *Route, err error) { requestTokens := tokenizePath(httpRequest.URL.Path) detectedService := c.detectWebService(requestTokens, webServices) if detectedService == nil { if trace { traceLogger.Printf("no WebService was found to match URL path:%s\n", httpRequest.URL.Path) } return nil, nil, NewError(http.StatusNotFound, "404: Page Not Found") } candidateRoutes := c.selectRoutes(detectedService, requestTokens) if len(candidateRoutes) == 0 { if trace { traceLogger.Printf("no Route in WebService with path %s was found to match URL path:%s\n", detectedService.rootPath, httpRequest.URL.Path) } return detectedService, nil, NewError(http.StatusNotFound, "404: Page Not Found") } selectedRoute, err := c.detectRoute(candidateRoutes, httpRequest) if selectedRoute == nil { return detectedService, nil, err } return detectedService, selectedRoute, nil } // selectRoutes return a collection of Route from a WebService that matches the path tokens from the request. func (c CurlyRouter) selectRoutes(ws *WebService, requestTokens []string) []Route { candidates := &sortableCurlyRoutes{[]*curlyRoute{}} for _, each := range ws.routes { matches, paramCount, staticCount := c.matchesRouteByPathTokens(each.pathParts, requestTokens) if matches { candidates.add(&curlyRoute{each, paramCount, staticCount}) // TODO make sure Routes() return pointers? } } sort.Sort(sort.Reverse(candidates)) return candidates.routes() } // matchesRouteByPathTokens computes whether it matches, howmany parameters do match and what the number of static path elements are. func (c CurlyRouter) matchesRouteByPathTokens(routeTokens, requestTokens []string) (matches bool, paramCount int, staticCount int) { if len(routeTokens) < len(requestTokens) { // proceed in matching only if last routeToken is wildcard count := len(routeTokens) if count == 0 || !strings.HasSuffix(routeTokens[count-1], "*}") { return false, 0, 0 } // proceed } for i, routeToken := range routeTokens { if i == len(requestTokens) { // reached end of request path return false, 0, 0 } requestToken := requestTokens[i] if strings.HasPrefix(routeToken, "{") { paramCount++ if colon := strings.Index(routeToken, ":"); colon != -1 { // match by regex matchesToken, matchesRemainder := c.regularMatchesPathToken(routeToken, colon, requestToken) if !matchesToken { return false, 0, 0 } if matchesRemainder { break } } } else { // no { prefix if requestToken != routeToken { return false, 0, 0 } staticCount++ } } return true, paramCount, staticCount } // regularMatchesPathToken tests whether the regular expression part of routeToken matches the requestToken or all remaining tokens // format routeToken is {someVar:someExpression}, e.g. {zipcode:[\d][\d][\d][\d][A-Z][A-Z]} func (c CurlyRouter) regularMatchesPathToken(routeToken string, colon int, requestToken string) (matchesToken bool, matchesRemainder bool) { regPart := routeToken[colon+1 : len(routeToken)-1] if regPart == "*" { if trace { traceLogger.Printf("wildcard parameter detected in route token %s that matches %s\n", routeToken, requestToken) } return true, true } matched, err := regexp.MatchString(regPart, requestToken) return (matched && err == nil), false } // detectRoute selectes from a list of Route the first match by inspecting both the Accept and Content-Type // headers of the Request. See also RouterJSR311 in jsr311.go func (c CurlyRouter) detectRoute(candidateRoutes []Route, httpRequest *http.Request) (*Route, error) { // tracing is done inside detectRoute return RouterJSR311{}.detectRoute(candidateRoutes, httpRequest) } // detectWebService returns the best matching webService given the list of path tokens. // see also computeWebserviceScore func (c CurlyRouter) detectWebService(requestTokens []string, webServices []*WebService) *WebService { var best *WebService score := -1 for _, each := range webServices { matches, eachScore := c.computeWebserviceScore(requestTokens, each.pathExpr.tokens) if matches && (eachScore > score) { best = each score = eachScore } } return best } // computeWebserviceScore returns whether tokens match and // the weighted score of the longest matching consecutive tokens from the beginning. func (c CurlyRouter) computeWebserviceScore(requestTokens []string, tokens []string) (bool, int) { if len(tokens) > len(requestTokens) { return false, 0 } score := 0 for i := 0; i < len(tokens); i++ { each := requestTokens[i] other := tokens[i] if len(each) == 0 && len(other) == 0 { score++ continue } if len(other) > 0 && strings.HasPrefix(other, "{") { // no empty match if len(each) == 0 { return false, score } score += 1 } else { // not a parameter if each != other { return false, score } score += (len(tokens) - i) * 10 //fuzzy } } return true, score } ================================================ FILE: vendor/github.com/emicklei/go-restful/curly_route.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. // curlyRoute exits for sorting Routes by the CurlyRouter based on number of parameters and number of static path elements. type curlyRoute struct { route Route paramCount int staticCount int } type sortableCurlyRoutes struct { candidates []*curlyRoute } func (s *sortableCurlyRoutes) add(route *curlyRoute) { s.candidates = append(s.candidates, route) } func (s *sortableCurlyRoutes) routes() (routes []Route) { for _, each := range s.candidates { routes = append(routes, each.route) // TODO change return type } return routes } func (s *sortableCurlyRoutes) Len() int { return len(s.candidates) } func (s *sortableCurlyRoutes) Swap(i, j int) { s.candidates[i], s.candidates[j] = s.candidates[j], s.candidates[i] } func (s *sortableCurlyRoutes) Less(i, j int) bool { ci := s.candidates[i] cj := s.candidates[j] // primary key if ci.staticCount < cj.staticCount { return true } if ci.staticCount > cj.staticCount { return false } // secundary key if ci.paramCount < cj.paramCount { return true } if ci.paramCount > cj.paramCount { return false } return ci.route.Path < cj.route.Path } ================================================ FILE: vendor/github.com/emicklei/go-restful/curly_test.go ================================================ package restful import ( "io" "net/http" "testing" ) var requestPaths = []struct { // url with path (1) is handled by service with root (2) and remainder has value final (3) path, root string }{ {"/", "/"}, {"/p", "/p"}, {"/p/x", "/p/{q}"}, {"/q/x", "/q"}, {"/p/x/", "/p/{q}"}, {"/p/x/y", "/p/{q}"}, {"/q/x/y", "/q"}, {"/z/q", "/{p}/q"}, {"/a/b/c/q", "/"}, } // go test -v -test.run TestCurlyDetectWebService ...restful func TestCurlyDetectWebService(t *testing.T) { ws1 := new(WebService).Path("/") ws2 := new(WebService).Path("/p") ws3 := new(WebService).Path("/q") ws4 := new(WebService).Path("/p/q") ws5 := new(WebService).Path("/p/{q}") ws7 := new(WebService).Path("/{p}/q") var wss = []*WebService{ws1, ws2, ws3, ws4, ws5, ws7} for _, each := range wss { t.Logf("path=%s,toks=%v\n", each.pathExpr.Source, each.pathExpr.tokens) } router := CurlyRouter{} ok := true for i, fixture := range requestPaths { requestTokens := tokenizePath(fixture.path) who := router.detectWebService(requestTokens, wss) if who != nil && who.RootPath() != fixture.root { t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) ok = false } } if !ok { t.Fail() } } var serviceDetects = []struct { path string found bool root string }{ {"/a/b", true, "/{p}/{q}/{r}"}, {"/p/q", true, "/p/q"}, {"/q/p", true, "/q"}, {"/", true, "/"}, {"/p/q/r", true, "/p/q"}, } // go test -v -test.run Test_detectWebService ...restful func Test_detectWebService(t *testing.T) { router := CurlyRouter{} ws1 := new(WebService).Path("/") ws2 := new(WebService).Path("/p") ws3 := new(WebService).Path("/q") ws4 := new(WebService).Path("/p/q") ws5 := new(WebService).Path("/p/{q}") ws6 := new(WebService).Path("/p/{q}/") ws7 := new(WebService).Path("/{p}/q") ws8 := new(WebService).Path("/{p}/{q}/{r}") var wss = []*WebService{ws8, ws7, ws6, ws5, ws4, ws3, ws2, ws1} for _, fix := range serviceDetects { requestPath := fix.path requestTokens := tokenizePath(requestPath) for _, ws := range wss { serviceTokens := ws.pathExpr.tokens matches, score := router.computeWebserviceScore(requestTokens, serviceTokens) t.Logf("req=%s,toks:%v,ws=%s,toks:%v,score=%d,matches=%v", requestPath, requestTokens, ws.RootPath(), serviceTokens, score, matches) } best := router.detectWebService(requestTokens, wss) if best != nil { if fix.found { t.Logf("best=%s", best.RootPath()) } else { t.Fatalf("should have found:%s", fix.root) } } } } var routeMatchers = []struct { route string path string matches bool paramCount int staticCount int }{ // route, request-path {"/a", "/a", true, 0, 1}, {"/a", "/b", false, 0, 0}, {"/a", "/b", false, 0, 0}, {"/a/{b}/c/", "/a/2/c", true, 1, 2}, {"/{a}/{b}/{c}/", "/a/b", false, 0, 0}, {"/{x:*}", "/", false, 0, 0}, {"/{x:*}", "/a", true, 1, 0}, {"/{x:*}", "/a/b", true, 1, 0}, {"/a/{x:*}", "/a/b", true, 1, 1}, {"/a/{x:[A-Z][A-Z]}", "/a/ZX", true, 1, 1}, {"/basepath/{resource:*}", "/basepath/some/other/location/test.xml", true, 1, 1}, } // clear && go test -v -test.run Test_matchesRouteByPathTokens ...restful func Test_matchesRouteByPathTokens(t *testing.T) { router := CurlyRouter{} for i, each := range routeMatchers { routeToks := tokenizePath(each.route) reqToks := tokenizePath(each.path) matches, pCount, sCount := router.matchesRouteByPathTokens(routeToks, reqToks) if matches != each.matches { t.Fatalf("[%d] unexpected matches outcome route:%s, path:%s, matches:%v", i, each.route, each.path, matches) } if pCount != each.paramCount { t.Fatalf("[%d] unexpected paramCount got:%d want:%d ", i, pCount, each.paramCount) } if sCount != each.staticCount { t.Fatalf("[%d] unexpected staticCount got:%d want:%d ", i, sCount, each.staticCount) } } } // clear && go test -v -test.run TestExtractParameters_Wildcard1 ...restful func TestExtractParameters_Wildcard1(t *testing.T) { params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remainder", t) if params["var"] != "remainder" { t.Errorf("parameter mismatch var: %s", params["var"]) } } // clear && go test -v -test.run TestExtractParameters_Wildcard2 ...restful func TestExtractParameters_Wildcard2(t *testing.T) { params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remain/der", t) if params["var"] != "remain/der" { t.Errorf("parameter mismatch var: %s", params["var"]) } } // clear && go test -v -test.run TestExtractParameters_Wildcard3 ...restful func TestExtractParameters_Wildcard3(t *testing.T) { params := doExtractParams("/static/{var:*}", 2, "/static/test/sub/hi.html", t) if params["var"] != "test/sub/hi.html" { t.Errorf("parameter mismatch var: %s", params["var"]) } } // clear && go test -v -test.run TestCurly_ISSUE_34 ...restful func TestCurly_ISSUE_34(t *testing.T) { ws1 := new(WebService).Path("/") ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) if len(routes) != 2 { t.Fatal("expected 2 routes") } if routes[0].Path != "/network/{id}" { t.Error("first is", routes[0].Path) } } // clear && go test -v -test.run TestCurly_ISSUE_34_2 ...restful func TestCurly_ISSUE_34_2(t *testing.T) { ws1 := new(WebService) ws1.Route(ws1.GET("/network/{id}").To(curlyDummy)) ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy)) routes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12")) if len(routes) != 2 { t.Fatal("expected 2 routes") } if routes[0].Path != "/network/{id}" { t.Error("first is", routes[0].Path) } } // clear && go test -v -test.run TestCurly_JsonHtml ...restful func TestCurly_JsonHtml(t *testing.T) { ws1 := new(WebService) ws1.Path("/") ws1.Route(ws1.GET("/some.html").To(curlyDummy).Consumes("*/*").Produces("text/html")) req, _ := http.NewRequest("GET", "/some.html", nil) req.Header.Set("Accept", "application/json") _, route, err := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) if err == nil { t.Error("error expected") } if route != nil { t.Error("no route expected") } } // go test -v -test.run TestCurly_ISSUE_137 ...restful func TestCurly_ISSUE_137(t *testing.T) { ws1 := new(WebService) ws1.Route(ws1.GET("/hello").To(curlyDummy)) ws1.Path("/") req, _ := http.NewRequest("GET", "/", nil) _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) t.Log(route) if route != nil { t.Error("no route expected") } } // go test -v -test.run TestCurly_ISSUE_137_2 ...restful func TestCurly_ISSUE_137_2(t *testing.T) { ws1 := new(WebService) ws1.Route(ws1.GET("/hello").To(curlyDummy)) ws1.Path("/") req, _ := http.NewRequest("GET", "/hello/bob", nil) _, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req) t.Log(route) if route != nil { t.Errorf("no route expected, got %v", route) } } func curlyDummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "curlyDummy") } ================================================ FILE: vendor/github.com/emicklei/go-restful/doc.go ================================================ /* Package restful, a lean package for creating REST-style WebServices without magic. WebServices and Routes A WebService has a collection of Route objects that dispatch incoming Http Requests to a function calls. Typically, a WebService has a root path (e.g. /users) and defines common MIME types for its routes. WebServices must be added to a container (see below) in order to handler Http requests from a server. A Route is defined by a HTTP method, an URL path and (optionally) the MIME types it consumes (Content-Type) and produces (Accept). This package has the logic to find the best matching Route and if found, call its Function. ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_JSON, restful.MIME_XML). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.GET("/{user-id}").To(u.findUser)) // u is a UserResource ... // GET http://localhost:8080/users/1 func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") ... } The (*Request, *Response) arguments provide functions for reading information from the request and writing information back to the response. See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-user-resource.go with a full implementation. Regular expression matching Routes A Route parameter can be specified using the format "uri/{var[:regexp]}" or the special version "uri/{var:*}" for matching the tail of the path. For example, /persons/{name:[A-Z][A-Z]} can be used to restrict values for the parameter "name" to only contain capital alphabetic characters. Regular expressions must use the standard Go syntax as described in the regexp package. (https://code.google.com/p/re2/wiki/Syntax) This feature requires the use of a CurlyRouter. Containers A Container holds a collection of WebServices, Filters and a http.ServeMux for multiplexing http requests. Using the statements "restful.Add(...) and restful.Filter(...)" will register WebServices and Filters to the Default Container. The Default container of go-restful uses the http.DefaultServeMux. You can create your own Container and create a new http.Server for that particular container. container := restful.NewContainer() server := &http.Server{Addr: ":8081", Handler: container} Filters A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. You can use filters to perform generic logging, measurement, authentication, redirect, set response headers etc. In the restful package there are three hooks into the request,response flow where filters can be added. Each filter must define a FilterFunction: func (req *restful.Request, resp *restful.Response, chain *restful.FilterChain) Use the following statement to pass the request,response pair to the next filter or RouteFunction chain.ProcessFilter(req, resp) Container Filters These are processed before any registered WebService. // install a (global) filter for the default container (processed before any webservice) restful.Filter(globalLogging) WebService Filters These are processed before any Route of a WebService. // install a webservice filter (processed before any route) ws.Filter(webserviceLogging).Filter(measureTime) Route Filters These are processed before calling the function associated with the Route. // install 2 chained route filters (processed before calling findUser) ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser)) See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-filters.go with full implementations. Response Encoding Two encodings are supported: gzip and deflate. To enable this for all responses: restful.DefaultContainer.EnableContentEncoding(true) If a Http request includes the Accept-Encoding header then the response content will be compressed using the specified encoding. Alternatively, you can create a Filter that performs the encoding and install it per WebService or Route. See the example https://github.com/emicklei/go-restful/blob/master/examples/restful-encoding-filter.go OPTIONS support By installing a pre-defined container filter, your Webservice(s) can respond to the OPTIONS Http request. Filter(OPTIONSFilter()) CORS By installing the filter of a CrossOriginResourceSharing (CORS), your WebService(s) can handle CORS requests. cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} Filter(cors.Filter) Error Handling Unexpected things happen. If a request cannot be processed because of a failure, your service needs to tell via the response what happened and why. For this reason HTTP status codes exist and it is important to use the correct code in every exceptional situation. 400: Bad Request If path or query parameters are not valid (content or type) then use http.StatusBadRequest. 404: Not Found Despite a valid URI, the resource requested may not be available 500: Internal Server Error If the application logic could not process the request (or write the response) then use http.StatusInternalServerError. 405: Method Not Allowed The request has a valid URL but the method (GET,PUT,POST,...) is not allowed. 406: Not Acceptable The request does not have or has an unknown Accept Header set for this operation. 415: Unsupported Media Type The request does not have or has an unknown Content-Type Header set for this operation. ServiceError In addition to setting the correct (error) Http status code, you can choose to write a ServiceError message on the response. Performance options This package has several options that affect the performance of your service. It is important to understand them and how you can change it. restful.DefaultContainer.Router(CurlyRouter{}) The default router is the RouterJSR311 which is an implementation of its spec (http://jsr311.java.net/nonav/releases/1.1/spec/spec.html). However, it uses regular expressions for all its routes which, depending on your usecase, may consume a significant amount of time. The CurlyRouter implementation is more lightweight that also allows you to use wildcards and expressions, but only if needed. restful.DefaultContainer.DoNotRecover(true) DoNotRecover controls whether panics will be caught to return HTTP 500. If set to true, Route functions are responsible for handling any error situation. Default value is false; it will recover from panics. This has performance implications. restful.SetCacheReadEntity(false) SetCacheReadEntity controls whether the response data ([]byte) is cached such that ReadEntity is repeatable. If you expect to read large amounts of payload data, and you do not use this feature, you should set it to false. restful.SetCompressorProvider(NewBoundedCachedCompressors(20, 20)) If content encoding is enabled then the default strategy for getting new gzip/zlib writers and readers is to use a sync.Pool. Because writers are expensive structures, performance is even more improved when using a preloaded cache. You can also inject your own implementation. Trouble shooting This package has the means to produce detail logging of the complete Http request matching process and filter invocation. Enabling this feature requires you to set an implementation of restful.StdLogger (e.g. log.Logger) instance such as: restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) Logging The restful.SetLogger() method allows you to override the logger used by the package. By default restful uses the standard library `log` package and logs to stdout. Different logging packages are supported as long as they conform to `StdLogger` interface defined in the `log` sub-package, writing an adapter for your preferred package is simple. Resources [project]: https://github.com/emicklei/go-restful [examples]: https://github.com/emicklei/go-restful/blob/master/examples [design]: http://ernestmicklei.com/2012/11/11/go-restful-api-design/ [showcases]: https://github.com/emicklei/mora, https://github.com/emicklei/landskape (c) 2012-2015, http://ernestmicklei.com. MIT License */ package restful ================================================ FILE: vendor/github.com/emicklei/go-restful/doc_examples_test.go ================================================ package restful import "net/http" func ExampleOPTIONSFilter() { // Install the OPTIONS filter on the default Container Filter(OPTIONSFilter()) } func ExampleContainer_OPTIONSFilter() { // Install the OPTIONS filter on a Container myContainer := new(Container) myContainer.Filter(myContainer.OPTIONSFilter) } func ExampleContainer() { // The Default container of go-restful uses the http.DefaultServeMux. // You can create your own Container using restful.NewContainer() and create a new http.Server for that particular container ws := new(WebService) wsContainer := NewContainer() wsContainer.Add(ws) server := &http.Server{Addr: ":8080", Handler: wsContainer} server.ListenAndServe() } func ExampleCrossOriginResourceSharing() { // To install this filter on the Default Container use: cors := CrossOriginResourceSharing{ExposeHeaders: []string{"X-My-Header"}, CookiesAllowed: false, Container: DefaultContainer} Filter(cors.Filter) } func ExampleServiceError() { resp := new(Response) resp.WriteEntity(NewError(http.StatusBadRequest, "Non-integer {id} path parameter")) } func ExampleBoundedCachedCompressors() { // Register a compressor provider (gzip/deflate read/write) that uses // a bounded cache with a maximum of 20 writers and 20 readers. SetCompressorProvider(NewBoundedCachedCompressors(20, 20)) } ================================================ FILE: vendor/github.com/emicklei/go-restful/entity_accessors.go ================================================ package restful // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "encoding/json" "encoding/xml" "strings" "sync" ) // EntityReaderWriter can read and write values using an encoding such as JSON,XML. type EntityReaderWriter interface { // Read a serialized version of the value from the request. // The Request may have a decompressing reader. Depends on Content-Encoding. Read(req *Request, v interface{}) error // Write a serialized version of the value on the response. // The Response may have a compressing writer. Depends on Accept-Encoding. // status should be a valid Http Status code Write(resp *Response, status int, v interface{}) error } // entityAccessRegistry is a singleton var entityAccessRegistry = &entityReaderWriters{ protection: new(sync.RWMutex), accessors: map[string]EntityReaderWriter{}, } // entityReaderWriters associates MIME to an EntityReaderWriter type entityReaderWriters struct { protection *sync.RWMutex accessors map[string]EntityReaderWriter } func init() { RegisterEntityAccessor(MIME_JSON, entityJSONAccess{ContentType: MIME_JSON}) RegisterEntityAccessor(MIME_XML, entityXMLAccess{ContentType: MIME_XML}) } // RegisterEntityAccessor add/overrides the ReaderWriter for encoding content with this MIME type. func RegisterEntityAccessor(mime string, erw EntityReaderWriter) { entityAccessRegistry.protection.Lock() defer entityAccessRegistry.protection.Unlock() entityAccessRegistry.accessors[mime] = erw } // AccessorAt returns the registered ReaderWriter for this MIME type. func (r *entityReaderWriters) AccessorAt(mime string) (EntityReaderWriter, bool) { r.protection.RLock() defer r.protection.RUnlock() er, ok := r.accessors[mime] if !ok { // retry with reverse lookup // more expensive but we are in an exceptional situation anyway for k, v := range r.accessors { if strings.Contains(mime, k) { return v, true } } } return er, ok } // entityXMLAccess is a EntityReaderWriter for XML encoding type entityXMLAccess struct { // This is used for setting the Content-Type header when writing ContentType string } // Read unmarshalls the value from XML func (e entityXMLAccess) Read(req *Request, v interface{}) error { return xml.NewDecoder(req.Request.Body).Decode(v) } // Write marshalls the value to JSON and set the Content-Type Header. func (e entityXMLAccess) Write(resp *Response, status int, v interface{}) error { return writeXML(resp, status, e.ContentType, v) } // writeXML marshalls the value to JSON and set the Content-Type Header. func writeXML(resp *Response, status int, contentType string, v interface{}) error { if v == nil { resp.WriteHeader(status) // do not write a nil representation return nil } if resp.prettyPrint { // pretty output must be created and written explicitly output, err := xml.MarshalIndent(v, " ", " ") if err != nil { return err } resp.Header().Set(HEADER_ContentType, contentType) resp.WriteHeader(status) _, err = resp.Write([]byte(xml.Header)) if err != nil { return err } _, err = resp.Write(output) return err } // not-so-pretty resp.Header().Set(HEADER_ContentType, contentType) resp.WriteHeader(status) return xml.NewEncoder(resp).Encode(v) } // entityJSONAccess is a EntityReaderWriter for JSON encoding type entityJSONAccess struct { // This is used for setting the Content-Type header when writing ContentType string } // Read unmarshalls the value from JSON func (e entityJSONAccess) Read(req *Request, v interface{}) error { decoder := json.NewDecoder(req.Request.Body) decoder.UseNumber() return decoder.Decode(v) } // Write marshalls the value to JSON and set the Content-Type Header. func (e entityJSONAccess) Write(resp *Response, status int, v interface{}) error { return writeJSON(resp, status, e.ContentType, v) } // write marshalls the value to JSON and set the Content-Type Header. func writeJSON(resp *Response, status int, contentType string, v interface{}) error { if v == nil { resp.WriteHeader(status) // do not write a nil representation return nil } if resp.prettyPrint { // pretty output must be created and written explicitly output, err := json.MarshalIndent(v, " ", " ") if err != nil { return err } resp.Header().Set(HEADER_ContentType, contentType) resp.WriteHeader(status) _, err = resp.Write(output) return err } // not-so-pretty resp.Header().Set(HEADER_ContentType, contentType) resp.WriteHeader(status) return json.NewEncoder(resp).Encode(v) } ================================================ FILE: vendor/github.com/emicklei/go-restful/entity_accessors_test.go ================================================ package restful import ( "bytes" "fmt" "io" "net/http" "net/http/httptest" "reflect" "testing" ) type keyvalue struct { readCalled bool writeCalled bool } func (kv *keyvalue) Read(req *Request, v interface{}) error { //t := reflect.TypeOf(v) //rv := reflect.ValueOf(v) kv.readCalled = true return nil } func (kv *keyvalue) Write(resp *Response, status int, v interface{}) error { t := reflect.TypeOf(v) rv := reflect.ValueOf(v) for ix := 0; ix < t.NumField(); ix++ { sf := t.Field(ix) io.WriteString(resp, sf.Name) io.WriteString(resp, "=") io.WriteString(resp, fmt.Sprintf("%v\n", rv.Field(ix).Interface())) } kv.writeCalled = true return nil } // go test -v -test.run TestKeyValueEncoding ...restful func TestKeyValueEncoding(t *testing.T) { type Book struct { Title string Author string PublishedYear int } kv := new(keyvalue) RegisterEntityAccessor("application/kv", kv) b := Book{"Singing for Dummies", "john doe", 2015} // Write httpWriter := httptest.NewRecorder() // Accept Produces resp := Response{httpWriter, "application/kv,*/*;q=0.8", []string{"application/kv"}, 0, 0, true, nil} resp.WriteEntity(b) t.Log(string(httpWriter.Body.Bytes())) if !kv.writeCalled { t.Error("Write never called") } // Read bodyReader := bytes.NewReader(httpWriter.Body.Bytes()) httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/kv; charset=UTF-8") request := NewRequest(httpRequest) var bb Book request.ReadEntity(&bb) if !kv.readCalled { t.Error("Read never called") } } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/.goconvey ================================================ ignore ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/.goconvey ================================================ ignore ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/app.yaml ================================================ # # Include your application ID here # application: version: 1 runtime: go api_version: go1 handlers: # # Regex for all swagger files to make as static content. # You should create the folder static/swagger and copy # swagger-ui into it. # - url: /apidocs/(.*?)/(.*\.(js|html|css)) static_files: static/swagger/\1/\2 upload: static/swagger/(.*?)/(.*\.(js|html|css)) - url: /.* script: _go_app ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/.goconvey ================================================ ignore ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/app.yaml ================================================ application: version: 1 runtime: go api_version: go1 handlers: # Regex for all swagger files to make as static content. # You should create the folder static/swagger and copy # swagger-ui into it. # - url: /apidocs/(.*?)/(.*\.(js|html|css)) static_files: static/swagger/\1/\2 upload: static/swagger/(.*?)/(.*\.(js|html|css)) # Catch all. - url: /.* script: _go_app login: required ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/datastore/main.go ================================================ package main import ( "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger" "google.golang.com/appengine" "google.golang.com/appengine/datastore" "google.golang.com/appengine/user" "net/http" "time" ) // This example demonstrates a reasonably complete suite of RESTful operations backed // by DataStore on Google App Engine. // Our simple example struct. type Profile struct { LastModified time.Time `json:"-" xml:"-"` Email string `json:"-" xml:"-"` FirstName string `json:"first_name" xml:"first-name"` NickName string `json:"nick_name" xml:"nick-name"` LastName string `json:"last_name" xml:"last-name"` } type ProfileApi struct { Path string } func gaeUrl() string { if appengine.IsDevAppServer() { return "http://localhost:8080" } else { // Include your URL on App Engine here. // I found no way to get AppID without appengine.Context and this always // based on a http.Request. return "http://federatedservices.appspot.com" } } func init() { u := ProfileApi{Path: "/profiles"} u.register() // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open .appspot.com/apidocs and enter // Place the Swagger UI files into a folder called static/swagger if you wish to use Swagger // http://.appspot.com/apidocs.json in the api input field. // For testing, you can use http://localhost:8080/apidocs.json config := swagger.Config{ // You control what services are visible WebServices: restful.RegisteredWebServices(), WebServicesUrl: gaeUrl(), ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", // GAE support static content which is configured in your app.yaml. // This example expect the swagger-ui in static/swagger so you should place it there :) SwaggerFilePath: "static/swagger"} swagger.InstallSwaggerService(config) } func (u ProfileApi) register() { ws := new(restful.WebService) ws. Path(u.Path). // You can specify consumes and produces per route as well. Consumes(restful.MIME_JSON, restful.MIME_XML). Produces(restful.MIME_JSON, restful.MIME_XML) ws.Route(ws.POST("").To(u.insert). // Swagger documentation. Doc("insert a new profile"). Param(ws.BodyParameter("Profile", "representation of a profile").DataType("main.Profile")). Reads(Profile{})) ws.Route(ws.GET("/{profile-id}").To(u.read). // Swagger documentation. Doc("read a profile"). Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string")). Writes(Profile{})) ws.Route(ws.PUT("/{profile-id}").To(u.update). // Swagger documentation. Doc("update an existing profile"). Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string")). Param(ws.BodyParameter("Profile", "representation of a profile").DataType("main.Profile")). Reads(Profile{})) ws.Route(ws.DELETE("/{profile-id}").To(u.remove). // Swagger documentation. Doc("remove a profile"). Param(ws.PathParameter("profile-id", "identifier for a profile").DataType("string"))) restful.Add(ws) } // POST http://localhost:8080/profiles // {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} // func (u *ProfileApi) insert(r *restful.Request, w *restful.Response) { c := appengine.NewContext(r.Request) // Marshall the entity from the request into a struct. p := new(Profile) err := r.ReadEntity(&p) if err != nil { w.WriteError(http.StatusNotAcceptable, err) return } // Ensure we start with a sensible value for this field. p.LastModified = time.Now() // The profile belongs to this user. p.Email = user.Current(c).String() k, err := datastore.Put(c, datastore.NewIncompleteKey(c, "profiles", nil), p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Let them know the location of the newly created resource. // TODO: Use a safe Url path append function. w.AddHeader("Location", u.Path+"/"+k.Encode()) // Return the resultant entity. w.WriteHeader(http.StatusCreated) w.WriteEntity(p) } // GET http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM // func (u ProfileApi) read(r *restful.Request, w *restful.Response) { c := appengine.NewContext(r.Request) // Decode the request parameter to determine the key for the entity. k, err := datastore.DecodeKey(r.PathParameter("profile-id")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Retrieve the entity from the datastore. p := Profile{} if err := datastore.Get(c, k, &p); err != nil { if err.Error() == "datastore: no such entity" { http.Error(w, err.Error(), http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } // Check we own the profile before allowing them to view it. // Optionally, return a 404 instead to help prevent guessing ids. // TODO: Allow admins access. if p.Email != user.Current(c).String() { http.Error(w, "You do not have access to this resource", http.StatusForbidden) return } w.WriteEntity(p) } // PUT http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM // {"first_name": "Ivan", "nick_name": "Socks", "last_name": "Hawkes"} // func (u *ProfileApi) update(r *restful.Request, w *restful.Response) { c := appengine.NewContext(r.Request) // Decode the request parameter to determine the key for the entity. k, err := datastore.DecodeKey(r.PathParameter("profile-id")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Marshall the entity from the request into a struct. p := new(Profile) err = r.ReadEntity(&p) if err != nil { w.WriteError(http.StatusNotAcceptable, err) return } // Retrieve the old entity from the datastore. old := Profile{} if err := datastore.Get(c, k, &old); err != nil { if err.Error() == "datastore: no such entity" { http.Error(w, err.Error(), http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } // Check we own the profile before allowing them to update it. // Optionally, return a 404 instead to help prevent guessing ids. // TODO: Allow admins access. if old.Email != user.Current(c).String() { http.Error(w, "You do not have access to this resource", http.StatusForbidden) return } // Since the whole entity is re-written, we need to assign any invariant fields again // e.g. the owner of the entity. p.Email = user.Current(c).String() // Keep track of the last modification date. p.LastModified = time.Now() // Attempt to overwrite the old entity. _, err = datastore.Put(c, k, p) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Let them know it succeeded. w.WriteHeader(http.StatusNoContent) } // DELETE http://localhost:8080/profiles/ahdkZXZ-ZmVkZXJhdGlvbi1zZXJ2aWNlc3IVCxIIcHJvZmlsZXMYgICAgICAgAoM // func (u *ProfileApi) remove(r *restful.Request, w *restful.Response) { c := appengine.NewContext(r.Request) // Decode the request parameter to determine the key for the entity. k, err := datastore.DecodeKey(r.PathParameter("profile-id")) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } // Retrieve the old entity from the datastore. old := Profile{} if err := datastore.Get(c, k, &old); err != nil { if err.Error() == "datastore: no such entity" { http.Error(w, err.Error(), http.StatusNotFound) } else { http.Error(w, err.Error(), http.StatusInternalServerError) } return } // Check we own the profile before allowing them to delete it. // Optionally, return a 404 instead to help prevent guessing ids. // TODO: Allow admins access. if old.Email != user.Current(c).String() { http.Error(w, "You do not have access to this resource", http.StatusForbidden) return } // Delete the entity. if err := datastore.Delete(c, k); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } // Success notification. w.WriteHeader(http.StatusNoContent) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-appstats-integration.go ================================================ package main import ( "github.com/mjibson/appstats" ) func stats(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { c := appstats.NewContext(req.Request) chain.ProcessFilter(req, resp) c.Stats.Status = resp.StatusCode() c.Save() } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/google_app_engine/restful-user-service.go ================================================ package main import ( "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger" "google.golang.com/appengine" "google.golang.com/appengine/memcache" "net/http" ) // This example is functionally the same as ../restful-user-service.go // but it`s supposed to run on Goole App Engine (GAE) // // contributed by ivanhawkes type User struct { Id, Name string } type UserService struct { // normally one would use DAO (data access object) // but in this example we simple use memcache. } func (u UserService) Register() { ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well ws.Route(ws.GET("/{user-id}").To(u.findUser). // docs Doc("get a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) // on the response ws.Route(ws.PATCH("").To(u.updateUser). // docs Doc("update a user"). Reads(User{})) // from the request ws.Route(ws.PUT("/{user-id}").To(u.createUser). // docs Doc("create a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Reads(User{})) // from the request ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). // docs Doc("delete a user"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) restful.Add(ws) } // GET http://localhost:8080/users/1 // func (u UserService) findUser(request *restful.Request, response *restful.Response) { c := appengine.NewContext(request.Request) id := request.PathParameter("user-id") usr := new(User) _, err := memcache.Gob.Get(c, id, &usr) if err != nil || len(usr.Id) == 0 { response.WriteErrorString(http.StatusNotFound, "User could not be found.") } else { response.WriteEntity(usr) } } // PATCH http://localhost:8080/users // 1Melissa Raspberry // func (u *UserService) updateUser(request *restful.Request, response *restful.Response) { c := appengine.NewContext(request.Request) usr := new(User) err := request.ReadEntity(&usr) if err == nil { item := &memcache.Item{ Key: usr.Id, Object: &usr, } err = memcache.Gob.Set(c, item) if err != nil { response.WriteError(http.StatusInternalServerError, err) return } response.WriteEntity(usr) } else { response.WriteError(http.StatusInternalServerError, err) } } // PUT http://localhost:8080/users/1 // 1Melissa // func (u *UserService) createUser(request *restful.Request, response *restful.Response) { c := appengine.NewContext(request.Request) usr := User{Id: request.PathParameter("user-id")} err := request.ReadEntity(&usr) if err == nil { item := &memcache.Item{ Key: usr.Id, Object: &usr, } err = memcache.Gob.Add(c, item) if err != nil { response.WriteError(http.StatusInternalServerError, err) return } response.WriteHeader(http.StatusCreated) response.WriteEntity(usr) } else { response.WriteError(http.StatusInternalServerError, err) } } // DELETE http://localhost:8080/users/1 // func (u *UserService) removeUser(request *restful.Request, response *restful.Response) { c := appengine.NewContext(request.Request) id := request.PathParameter("user-id") err := memcache.Delete(c, id) if err != nil { response.WriteError(http.StatusInternalServerError, err) } } func getGaeURL() string { if appengine.IsDevAppServer() { return "http://localhost:8080" } else { /** * Include your URL on App Engine here. * I found no way to get AppID without appengine.Context and this always * based on a http.Request. */ return "http://.appspot.com" } } func init() { u := UserService{} u.Register() // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open .appspot.com/apidocs and enter http://.appspot.com/apidocs.json in the api input field. config := swagger.Config{ WebServices: restful.RegisteredWebServices(), // you control what services are visible WebServicesUrl: getGaeURL(), ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", // GAE support static content which is configured in your app.yaml. // This example expect the swagger-ui in static/swagger so you should place it there :) SwaggerFilePath: "static/swagger"} swagger.InstallSwaggerService(config) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/home.html ================================================

{{.Text}}

================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-CORS-filter.go ================================================ package main import ( "io" "log" "net/http" "github.com/emicklei/go-restful" ) // Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page // to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. // // http://en.wikipedia.org/wiki/Cross-origin_resource_sharing // http://enable-cors.org/server.html // // GET http://localhost:8080/users // // GET http://localhost:8080/users/1 // // PUT http://localhost:8080/users/1 // // DELETE http://localhost:8080/users/1 // // OPTIONS http://localhost:8080/users/1 with Header "Origin" set to some domain and type UserResource struct{} func (u UserResource) RegisterTo(container *restful.Container) { ws := new(restful.WebService) ws. Path("/users"). Consumes("*/*"). Produces("*/*") ws.Route(ws.GET("/{user-id}").To(u.nop)) ws.Route(ws.POST("").To(u.nop)) ws.Route(ws.PUT("/{user-id}").To(u.nop)) ws.Route(ws.DELETE("/{user-id}").To(u.nop)) container.Add(ws) } func (u UserResource) nop(request *restful.Request, response *restful.Response) { io.WriteString(response.ResponseWriter, "this would be a normal response") } func main() { wsContainer := restful.NewContainer() u := UserResource{} u.RegisterTo(wsContainer) // Add container filter to enable CORS cors := restful.CrossOriginResourceSharing{ ExposeHeaders: []string{"X-My-Header"}, AllowedHeaders: []string{"Content-Type", "Accept"}, CookiesAllowed: false, Container: wsContainer} wsContainer.Filter(cors.Filter) // Add container filter to respond to OPTIONS wsContainer.Filter(wsContainer.OPTIONSFilter) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-NCSA-logging.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "log" "net/http" "os" "strings" "time" ) // This example shows how to create a filter that produces log lines // according to the Common Log Format, also known as the NCSA standard. // // kindly contributed by leehambley // // GET http://localhost:8080/ping var logger *log.Logger = log.New(os.Stdout, "", 0) func NCSACommonLogFormatLogger() restful.FilterFunction { return func(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { var username = "-" if req.Request.URL.User != nil { if name := req.Request.URL.User.Username(); name != "" { username = name } } chain.ProcessFilter(req, resp) logger.Printf("%s - %s [%s] \"%s %s %s\" %d %d", strings.Split(req.Request.RemoteAddr, ":")[0], username, time.Now().Format("02/Jan/2006:15:04:05 -0700"), req.Request.Method, req.Request.URL.RequestURI(), req.Request.Proto, resp.StatusCode(), resp.ContentLength(), ) } } func main() { ws := new(restful.WebService) ws.Filter(NCSACommonLogFormatLogger()) ws.Route(ws.GET("/ping").To(hello)) restful.Add(ws) http.ListenAndServe(":8080", nil) } func hello(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "pong") } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-basic-authentication.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "net/http" ) // This example shows how to create a (Route) Filter that performs Basic Authentication on the Http request. // // GET http://localhost:8080/secret // and use admin,admin for the credentials func main() { ws := new(restful.WebService) ws.Route(ws.GET("/secret").Filter(basicAuthenticate).To(secret)) restful.Add(ws) http.ListenAndServe(":8080", nil) } func basicAuthenticate(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { encoded := req.Request.Header.Get("Authorization") // usr/pwd = admin/admin // real code does some decoding if len(encoded) == 0 || "Basic YWRtaW46YWRtaW4=" != encoded { resp.AddHeader("WWW-Authenticate", "Basic realm=Protected Area") resp.WriteErrorString(401, "401: Not Authorized") return } chain.ProcessFilter(req, resp) } func secret(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "42") } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-cpuprofiler-service.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "log" "os" "runtime/pprof" ) // ProfilingService is a WebService that can start/stop a CPU profile and write results to a file // GET /{rootPath}/start will activate CPU profiling // GET /{rootPath}/stop will stop profiling // // NewProfileService("/profiler", "ace.prof").AddWebServiceTo(restful.DefaultContainer) // type ProfilingService struct { rootPath string // the base (root) of the service, e.g. /profiler cpuprofile string // the output filename to write profile results, e.g. myservice.prof cpufile *os.File // if not nil, then profiling is active } func NewProfileService(rootPath string, outputFilename string) *ProfilingService { ps := new(ProfilingService) ps.rootPath = rootPath ps.cpuprofile = outputFilename return ps } // Add this ProfileService to a restful Container func (p ProfilingService) AddWebServiceTo(container *restful.Container) { ws := new(restful.WebService) ws.Path(p.rootPath).Consumes("*/*").Produces(restful.MIME_JSON) ws.Route(ws.GET("/start").To(p.startProfiler)) ws.Route(ws.GET("/stop").To(p.stopProfiler)) container.Add(ws) } func (p *ProfilingService) startProfiler(req *restful.Request, resp *restful.Response) { if p.cpufile != nil { io.WriteString(resp.ResponseWriter, "[restful] CPU profiling already running") return // error? } cpufile, err := os.Create(p.cpuprofile) if err != nil { log.Fatal(err) } // remember for close p.cpufile = cpufile pprof.StartCPUProfile(cpufile) io.WriteString(resp.ResponseWriter, "[restful] CPU profiling started, writing on:"+p.cpuprofile) } func (p *ProfilingService) stopProfiler(req *restful.Request, resp *restful.Response) { if p.cpufile == nil { io.WriteString(resp.ResponseWriter, "[restful] CPU profiling not active") return // error? } pprof.StopCPUProfile() p.cpufile.Close() p.cpufile = nil io.WriteString(resp.ResponseWriter, "[restful] CPU profiling stopped, closing:"+p.cpuprofile) } func main() {} // exists for example compilation only ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-curly-router.go ================================================ package main import ( "github.com/emicklei/go-restful" "log" "net/http" ) // This example has the same service definition as restful-user-resource // but uses a different router (CurlyRouter) that does not use regular expressions // // POST http://localhost:8080/users // 1Melissa Raspberry // // GET http://localhost:8080/users/1 // // PUT http://localhost:8080/users/1 // 1Melissa // // DELETE http://localhost:8080/users/1 // type User struct { Id, Name string } type UserResource struct { // normally one would use DAO (data access object) users map[string]User } func (u UserResource) Register(container *restful.Container) { ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well ws.Route(ws.GET("/{user-id}").To(u.findUser)) ws.Route(ws.POST("").To(u.updateUser)) ws.Route(ws.PUT("/{user-id}").To(u.createUser)) ws.Route(ws.DELETE("/{user-id}").To(u.removeUser)) container.Add(ws) } // GET http://localhost:8080/users/1 // func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") usr := u.users[id] if len(usr.Id) == 0 { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusNotFound, "User could not be found.") } else { response.WriteEntity(usr) } } // POST http://localhost:8080/users // 1Melissa Raspberry // func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { usr := new(User) err := request.ReadEntity(&usr) if err == nil { u.users[usr.Id] = *usr response.WriteEntity(usr) } else { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) } } // PUT http://localhost:8080/users/1 // 1Melissa // func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { usr := User{Id: request.PathParameter("user-id")} err := request.ReadEntity(&usr) if err == nil { u.users[usr.Id] = usr response.WriteHeader(http.StatusCreated) response.WriteEntity(usr) } else { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) } } // DELETE http://localhost:8080/users/1 // func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") delete(u.users, id) } func main() { wsContainer := restful.NewContainer() wsContainer.Router(restful.CurlyRouter{}) u := UserResource{map[string]User{}} u.Register(wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-encoding-filter.go ================================================ package main import ( "github.com/emicklei/go-restful" "log" "net/http" ) type User struct { Id, Name string } type UserList struct { Users []User } // // This example shows how to use the CompressingResponseWriter by a Filter // such that encoding can be enabled per WebService or per Route (instead of per container) // Using restful.DefaultContainer.EnableContentEncoding(true) will encode all responses served by WebServices in the DefaultContainer. // // Set Accept-Encoding to gzip or deflate // GET http://localhost:8080/users/42 // and look at the response headers func main() { restful.Add(NewUserService()) log.Printf("start listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) } func NewUserService() *restful.WebService { ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // install a response encoding filter ws.Route(ws.GET("/{user-id}").Filter(encodingFilter).To(findUser)) return ws } // Route Filter (defines FilterFunction) func encodingFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("[encoding-filter] %s,%s\n", req.Request.Method, req.Request.URL) // wrap responseWriter into a compressing one compress, _ := restful.NewCompressingResponseWriter(resp.ResponseWriter, restful.ENCODING_GZIP) resp.ResponseWriter = compress defer func() { compress.Close() }() chain.ProcessFilter(req, resp) } // GET http://localhost:8080/users/42 // func findUser(request *restful.Request, response *restful.Response) { log.Printf("findUser") response.WriteEntity(User{"42", "Gandalf"}) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-filters.go ================================================ package main import ( "github.com/emicklei/go-restful" "log" "net/http" "time" ) type User struct { Id, Name string } type UserList struct { Users []User } // This example show how to create and use the three different Filters (Container,WebService and Route) // When applied to the restful.DefaultContainer, we refer to them as a global filter. // // GET http://locahost:8080/users/42 // and see the logging per filter (try repeating this request) func main() { // install a global (=DefaultContainer) filter (processed before any webservice in the DefaultContainer) restful.Filter(globalLogging) restful.Add(NewUserService()) log.Printf("start listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) } func NewUserService() *restful.WebService { ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // install a webservice filter (processed before any route) ws.Filter(webserviceLogging).Filter(measureTime) // install a counter filter ws.Route(ws.GET("").Filter(NewCountFilter().routeCounter).To(getAllUsers)) // install 2 chained route filters (processed before calling findUser) ws.Route(ws.GET("/{user-id}").Filter(routeLogging).Filter(NewCountFilter().routeCounter).To(findUser)) return ws } // Global Filter func globalLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("[global-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) chain.ProcessFilter(req, resp) } // WebService Filter func webserviceLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("[webservice-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) chain.ProcessFilter(req, resp) } // WebService (post-process) Filter (as a struct that defines a FilterFunction) func measureTime(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { now := time.Now() chain.ProcessFilter(req, resp) log.Printf("[webservice-filter (timer)] %v\n", time.Now().Sub(now)) } // Route Filter (defines FilterFunction) func routeLogging(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("[route-filter (logger)] %s,%s\n", req.Request.Method, req.Request.URL) chain.ProcessFilter(req, resp) } // Route Filter (as a struct that defines a FilterFunction) // CountFilter implements a FilterFunction for counting requests. type CountFilter struct { count int counter chan int // for go-routine safe count increments } // NewCountFilter creates and initializes a new CountFilter. func NewCountFilter() *CountFilter { c := new(CountFilter) c.counter = make(chan int) go func() { for { c.count += <-c.counter } }() return c } // routeCounter increments the count of the filter (through a channel) func (c *CountFilter) routeCounter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { c.counter <- 1 log.Printf("[route-filter (counter)] count:%d", c.count) chain.ProcessFilter(req, resp) } // GET http://localhost:8080/users // func getAllUsers(request *restful.Request, response *restful.Response) { log.Printf("getAllUsers") response.WriteEntity(UserList{[]User{User{"42", "Gandalf"}, User{"3.14", "Pi"}}}) } // GET http://localhost:8080/users/42 // func findUser(request *restful.Request, response *restful.Response) { log.Printf("findUser") response.WriteEntity(User{"42", "Gandalf"}) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-form-handling.go ================================================ package main import ( "fmt" "github.com/emicklei/go-restful" "github.com/gorilla/schema" "io" "net/http" ) // This example shows how to handle a POST of a HTML form that uses the standard x-www-form-urlencoded content-type. // It uses the gorilla web tool kit schema package to decode the form data into a struct. // // GET http://localhost:8080/profiles // type Profile struct { Name string Age int } var decoder *schema.Decoder func main() { decoder = schema.NewDecoder() ws := new(restful.WebService) ws.Route(ws.POST("/profiles").Consumes("application/x-www-form-urlencoded").To(postAdddress)) ws.Route(ws.GET("/profiles").To(addresssForm)) restful.Add(ws) http.ListenAndServe(":8080", nil) } func postAdddress(req *restful.Request, resp *restful.Response) { err := req.Request.ParseForm() if err != nil { resp.WriteErrorString(http.StatusBadRequest, err.Error()) return } p := new(Profile) err = decoder.Decode(p, req.Request.PostForm) if err != nil { resp.WriteErrorString(http.StatusBadRequest, err.Error()) return } io.WriteString(resp.ResponseWriter, fmt.Sprintf("Name=%s, Age=%d", p.Name, p.Age)) } func addresssForm(req *restful.Request, resp *restful.Response) { io.WriteString(resp.ResponseWriter, `

Enter Profile

`) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-hello-world.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "net/http" ) // This example shows the minimal code needed to get a restful.WebService working. // // GET http://localhost:8080/hello func main() { ws := new(restful.WebService) ws.Route(ws.GET("/hello").To(hello)) restful.Add(ws) http.ListenAndServe(":8080", nil) } func hello(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "world") } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-html-template.go ================================================ package main import ( "log" "net/http" "text/template" "github.com/emicklei/go-restful" ) // This example shows how to serve a HTML page using the standard Go template engine. // // GET http://localhost:8080/ func main() { ws := new(restful.WebService) ws.Route(ws.GET("/").To(home)) restful.Add(ws) print("open browser on http://localhost:8080/\n") http.ListenAndServe(":8080", nil) } type Message struct { Text string } func home(req *restful.Request, resp *restful.Response) { p := &Message{"restful-html-template demo"} // you might want to cache compiled templates t, err := template.ParseFiles("home.html") if err != nil { log.Fatalf("Template gave: %s", err) } t.Execute(resp.ResponseWriter, p) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-multi-containers.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "log" "net/http" ) // This example shows how to have a program with 2 WebServices containers // each having a http server listening on its own port. // // The first "hello" is added to the restful.DefaultContainer (and uses DefaultServeMux) // For the second "hello", a new container and ServeMux is created // and requires a new http.Server with the container being the Handler. // This first server is spawn in its own go-routine such that the program proceeds to create the second. // // GET http://localhost:8080/hello // GET http://localhost:8081/hello func main() { ws := new(restful.WebService) ws.Route(ws.GET("/hello").To(hello)) restful.Add(ws) go func() { http.ListenAndServe(":8080", nil) }() container2 := restful.NewContainer() ws2 := new(restful.WebService) ws2.Route(ws2.GET("/hello").To(hello2)) container2.Add(ws2) server := &http.Server{Addr: ":8081", Handler: container2} log.Fatal(server.ListenAndServe()) } func hello(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "default world") } func hello2(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "second world") } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-options-filter.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "log" "net/http" ) // This example shows how to use the OPTIONSFilter on a Container // // OPTIONS http://localhost:8080/users // // OPTIONS http://localhost:8080/users/1 type UserResource struct{} func (u UserResource) RegisterTo(container *restful.Container) { ws := new(restful.WebService) ws. Path("/users"). Consumes("*/*"). Produces("*/*") ws.Route(ws.GET("/{user-id}").To(u.nop)) ws.Route(ws.POST("").To(u.nop)) ws.Route(ws.PUT("/{user-id}").To(u.nop)) ws.Route(ws.DELETE("/{user-id}").To(u.nop)) container.Add(ws) } func (u UserResource) nop(request *restful.Request, response *restful.Response) { io.WriteString(response.ResponseWriter, "this would be a normal response") } func main() { wsContainer := restful.NewContainer() u := UserResource{} u.RegisterTo(wsContainer) // Add container filter to respond to OPTIONS wsContainer.Filter(wsContainer.OPTIONSFilter) // For use on the default container, you can write // restful.Filter(restful.OPTIONSFilter()) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-path-tail.go ================================================ package main import ( "io" "net/http" . "github.com/emicklei/go-restful" ) // This example shows how to a Route that matches the "tail" of a path. // Requires the use of a CurlyRouter and the star "*" path parameter pattern. // // GET http://localhost:8080/basepath/some/other/location/test.xml func main() { DefaultContainer.Router(CurlyRouter{}) ws := new(WebService) ws.Route(ws.GET("/basepath/{resource:*}").To(staticFromPathParam)) Add(ws) println("[go-restful] serve path tails from http://localhost:8080/basepath") http.ListenAndServe(":8080", nil) } func staticFromPathParam(req *Request, resp *Response) { io.WriteString(resp, "Tail="+req.PathParameter("resource")) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-pre-post-filters.go ================================================ package main import ( "github.com/emicklei/go-restful" "io" "log" "net/http" ) // This example shows how the different types of filters are called in the request-response flow. // The call chain is logged on the console when sending an http request. // // GET http://localhost:8080/1 // GET http://localhost:8080/2 var indentLevel int func container_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { log.Printf("url path:%v\n", req.Request.URL) trace("container_filter_A: before", 1) chain.ProcessFilter(req, resp) trace("container_filter_A: after", -1) } func container_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { trace("container_filter_B: before", 1) chain.ProcessFilter(req, resp) trace("container_filter_B: after", -1) } func service_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { trace("service_filter_A: before", 1) chain.ProcessFilter(req, resp) trace("service_filter_A: after", -1) } func service_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { trace("service_filter_B: before", 1) chain.ProcessFilter(req, resp) trace("service_filter_B: after", -1) } func route_filter_A(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { trace("route_filter_A: before", 1) chain.ProcessFilter(req, resp) trace("route_filter_A: after", -1) } func route_filter_B(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { trace("route_filter_B: before", 1) chain.ProcessFilter(req, resp) trace("route_filter_B: after", -1) } func trace(what string, delta int) { indented := what if delta < 0 { indentLevel += delta } for t := 0; t < indentLevel; t++ { indented = "." + indented } log.Printf("%s", indented) if delta > 0 { indentLevel += delta } } func main() { restful.Filter(container_filter_A) restful.Filter(container_filter_B) ws1 := new(restful.WebService) ws1.Path("/1") ws1.Filter(service_filter_A) ws1.Filter(service_filter_B) ws1.Route(ws1.GET("").To(doit1).Filter(route_filter_A).Filter(route_filter_B)) ws2 := new(restful.WebService) ws2.Path("/2") ws2.Filter(service_filter_A) ws2.Filter(service_filter_B) ws2.Route(ws2.GET("").To(doit2).Filter(route_filter_A).Filter(route_filter_B)) restful.Add(ws1) restful.Add(ws2) log.Print("go-restful example listing on http://localhost:8080/1 and http://localhost:8080/2") log.Fatal(http.ListenAndServe(":8080", nil)) } func doit1(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "nothing to see in 1") } func doit2(req *restful.Request, resp *restful.Response) { io.WriteString(resp, "nothing to see in 2") } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-resource-functions.go ================================================ package main import ( "github.com/emicklei/go-restful" "log" "net/http" ) // This example shows how to use methods as RouteFunctions for WebServices. // The ProductResource has a Register() method that creates and initializes // a WebService to expose its methods as REST operations. // The WebService is added to the restful.DefaultContainer. // A ProductResource is typically created using some data access object. // // GET http://localhost:8080/products/1 // POST http://localhost:8080/products // 1The First type Product struct { Id, Title string } type ProductResource struct { // typically reference a DAO (data-access-object) } func (p ProductResource) getOne(req *restful.Request, resp *restful.Response) { id := req.PathParameter("id") log.Println("getting product with id:" + id) resp.WriteEntity(Product{Id: id, Title: "test"}) } func (p ProductResource) postOne(req *restful.Request, resp *restful.Response) { updatedProduct := new(Product) err := req.ReadEntity(updatedProduct) if err != nil { // bad request resp.WriteErrorString(http.StatusBadRequest, err.Error()) return } log.Println("updating product with id:" + updatedProduct.Id) } func (p ProductResource) Register() { ws := new(restful.WebService) ws.Path("/products") ws.Consumes(restful.MIME_XML) ws.Produces(restful.MIME_XML) ws.Route(ws.GET("/{id}").To(p.getOne). Doc("get the product by its id"). Param(ws.PathParameter("id", "identifier of the product").DataType("string"))) ws.Route(ws.POST("").To(p.postOne). Doc("update or create a product"). Param(ws.BodyParameter("Product", "a Product (XML)").DataType("main.Product"))) restful.Add(ws) } func main() { ProductResource{}.Register() http.ListenAndServe(":8080", nil) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-route_test.go ================================================ package main import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/emicklei/go-restful" ) var ( Result string ) func TestRouteExtractParameter(t *testing.T) { // setup service ws := new(restful.WebService) ws.Consumes(restful.MIME_XML) ws.Route(ws.GET("/test/{param}").To(DummyHandler)) restful.Add(ws) // setup request + writer bodyReader := strings.NewReader("42") httpRequest, _ := http.NewRequest("GET", "/test/THIS", bodyReader) httpRequest.Header.Set("Content-Type", restful.MIME_XML) httpWriter := httptest.NewRecorder() // run restful.DefaultContainer.ServeHTTP(httpWriter, httpRequest) if Result != "THIS" { t.Fatalf("Result is actually: %s", Result) } } func DummyHandler(rq *restful.Request, rp *restful.Response) { Result = rq.PathParameter("param") } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-routefunction_test.go ================================================ package main import ( "net/http" "net/http/httptest" "testing" "github.com/emicklei/go-restful" ) // This example show how to test one particular RouteFunction (getIt) // It uses the httptest.ResponseRecorder to capture output func getIt(req *restful.Request, resp *restful.Response) { resp.WriteHeader(204) } func TestCallFunction(t *testing.T) { httpReq, _ := http.NewRequest("GET", "/", nil) req := restful.NewRequest(httpReq) recorder := new(httptest.ResponseRecorder) resp := restful.NewResponse(recorder) getIt(req, resp) if recorder.Code != 204 { t.Fatalf("Missing or wrong status code:%d", recorder.Code) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-serve-static.go ================================================ package main import ( "fmt" "net/http" "path" "github.com/emicklei/go-restful" ) // This example shows how to define methods that serve static files // It uses the standard http.ServeFile method // // GET http://localhost:8080/static/test.xml // GET http://localhost:8080/static/ // // GET http://localhost:8080/static?resource=subdir/test.xml var rootdir = "/tmp" func main() { restful.DefaultContainer.Router(restful.CurlyRouter{}) ws := new(restful.WebService) ws.Route(ws.GET("/static/{subpath:*}").To(staticFromPathParam)) ws.Route(ws.GET("/static").To(staticFromQueryParam)) restful.Add(ws) println("[go-restful] serving files on http://localhost:8080/static from local /tmp") http.ListenAndServe(":8080", nil) } func staticFromPathParam(req *restful.Request, resp *restful.Response) { actual := path.Join(rootdir, req.PathParameter("subpath")) fmt.Printf("serving %s ... (from %s)\n", actual, req.PathParameter("subpath")) http.ServeFile( resp.ResponseWriter, req.Request, actual) } func staticFromQueryParam(req *restful.Request, resp *restful.Response) { http.ServeFile( resp.ResponseWriter, req.Request, path.Join(rootdir, req.QueryParameter("resource"))) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-swagger.go ================================================ package main import ( "log" "net/http" "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger" ) type Book struct { Title string Author string } func main() { ws := new(restful.WebService) ws.Path("/books") ws.Consumes(restful.MIME_JSON, restful.MIME_XML) ws.Produces(restful.MIME_JSON, restful.MIME_XML) restful.Add(ws) ws.Route(ws.GET("/{medium}").To(noop). Doc("Search all books"). Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). Param(ws.QueryParameter("language", "en,nl,de").DataType("string")). Param(ws.HeaderParameter("If-Modified-Since", "last known timestamp").DataType("datetime")). Do(returns200, returns500)) ws.Route(ws.PUT("/{medium}").To(noop). Doc("Add a new book"). Param(ws.PathParameter("medium", "digital or paperback").DataType("string")). Reads(Book{})) // You can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. config := swagger.Config{ WebServices: restful.DefaultContainer.RegisteredWebServices(), // you control what services are visible WebServicesUrl: "http://localhost:8080", ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"} swagger.RegisterSwaggerService(config, restful.DefaultContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: restful.DefaultContainer} log.Fatal(server.ListenAndServe()) } func noop(req *restful.Request, resp *restful.Response) {} func returns200(b *restful.RouteBuilder) { b.Returns(http.StatusOK, "OK", Book{}) } func returns500(b *restful.RouteBuilder) { b.Returns(http.StatusInternalServerError, "Bummer, something went wrong", nil) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-user-resource.go ================================================ package main import ( "log" "net/http" "strconv" "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger" ) // This example show a complete (GET,PUT,POST,DELETE) conventional example of // a REST Resource including documentation to be served by e.g. a Swagger UI // It is recommended to create a Resource struct (UserResource) that can encapsulate // an object that provide domain access (a DAO) // It has a Register method including the complete Route mapping to methods together // with all the appropriate documentation // // POST http://localhost:8080/users // 1Melissa Raspberry // // GET http://localhost:8080/users/1 // // PUT http://localhost:8080/users/1 // 1Melissa // // DELETE http://localhost:8080/users/1 // type User struct { Id, Name string } type UserResource struct { // normally one would use DAO (data access object) users map[string]User } func (u UserResource) Register(container *restful.Container) { ws := new(restful.WebService) ws. Path("/users"). Doc("Manage Users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well ws.Route(ws.GET("/{user-id}").To(u.findUser). // docs Doc("get a user"). Operation("findUser"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) // on the response ws.Route(ws.PUT("/{user-id}").To(u.updateUser). // docs Doc("update a user"). Operation("updateUser"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). ReturnsError(409, "duplicate user-id", nil). Reads(User{})) // from the request ws.Route(ws.POST("").To(u.createUser). // docs Doc("create a user"). Operation("createUser"). Reads(User{})) // from the request ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). // docs Doc("delete a user"). Operation("removeUser"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) container.Add(ws) } // GET http://localhost:8080/users/1 // func (u UserResource) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") usr := u.users[id] if len(usr.Id) == 0 { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusNotFound, "404: User could not be found.") return } response.WriteEntity(usr) } // POST http://localhost:8080/users // Melissa // func (u *UserResource) createUser(request *restful.Request, response *restful.Response) { usr := new(User) err := request.ReadEntity(usr) if err != nil { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return } usr.Id = strconv.Itoa(len(u.users) + 1) // simple id generation u.users[usr.Id] = *usr response.WriteHeaderAndEntity(http.StatusCreated, usr) } // PUT http://localhost:8080/users/1 // 1Melissa Raspberry // func (u *UserResource) updateUser(request *restful.Request, response *restful.Response) { usr := new(User) err := request.ReadEntity(&usr) if err != nil { response.AddHeader("Content-Type", "text/plain") response.WriteErrorString(http.StatusInternalServerError, err.Error()) return } u.users[usr.Id] = *usr response.WriteEntity(usr) } // DELETE http://localhost:8080/users/1 // func (u *UserResource) removeUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") delete(u.users, id) } func main() { // to see what happens in the package, uncomment the following //restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile)) wsContainer := restful.NewContainer() u := UserResource{map[string]User{}} u.Register(wsContainer) // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. config := swagger.Config{ WebServices: wsContainer.RegisteredWebServices(), // you control what services are visible WebServicesUrl: "http://localhost:8080", ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", SwaggerFilePath: "/Users/emicklei/xProjects/swagger-ui/dist"} swagger.RegisterSwaggerService(config, wsContainer) log.Printf("start listening on localhost:8080") server := &http.Server{Addr: ":8080", Handler: wsContainer} log.Fatal(server.ListenAndServe()) } ================================================ FILE: vendor/github.com/emicklei/go-restful/examples/restful-user-service.go ================================================ package main import ( "log" "net/http" "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger" ) // This example is functionally the same as the example in restful-user-resource.go // with the only difference that is served using the restful.DefaultContainer type User struct { Id, Name string } type UserService struct { // normally one would use DAO (data access object) users map[string]User } func (u UserService) Register() { ws := new(restful.WebService) ws. Path("/users"). Consumes(restful.MIME_XML, restful.MIME_JSON). Produces(restful.MIME_JSON, restful.MIME_XML) // you can specify this per route as well ws.Route(ws.GET("/").To(u.findAllUsers). // docs Doc("get all users"). Operation("findAllUsers"). Returns(200, "OK", []User{})) ws.Route(ws.GET("/{user-id}").To(u.findUser). // docs Doc("get a user"). Operation("findUser"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Writes(User{})) // on the response ws.Route(ws.PUT("/{user-id}").To(u.updateUser). // docs Doc("update a user"). Operation("updateUser"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")). Reads(User{})) // from the request ws.Route(ws.PUT("").To(u.createUser). // docs Doc("create a user"). Operation("createUser"). Reads(User{})) // from the request ws.Route(ws.DELETE("/{user-id}").To(u.removeUser). // docs Doc("delete a user"). Operation("removeUser"). Param(ws.PathParameter("user-id", "identifier of the user").DataType("string"))) restful.Add(ws) } // GET http://localhost:8080/users // func (u UserService) findAllUsers(request *restful.Request, response *restful.Response) { response.WriteEntity(u.users) } // GET http://localhost:8080/users/1 // func (u UserService) findUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") usr := u.users[id] if len(usr.Id) == 0 { response.WriteErrorString(http.StatusNotFound, "User could not be found.") } else { response.WriteEntity(usr) } } // PUT http://localhost:8080/users/1 // 1Melissa Raspberry // func (u *UserService) updateUser(request *restful.Request, response *restful.Response) { usr := new(User) err := request.ReadEntity(&usr) if err == nil { u.users[usr.Id] = *usr response.WriteEntity(usr) } else { response.WriteError(http.StatusInternalServerError, err) } } // PUT http://localhost:8080/users/1 // 1Melissa // func (u *UserService) createUser(request *restful.Request, response *restful.Response) { usr := User{Id: request.PathParameter("user-id")} err := request.ReadEntity(&usr) if err == nil { u.users[usr.Id] = usr response.WriteHeaderAndEntity(http.StatusCreated, usr) } else { response.WriteError(http.StatusInternalServerError, err) } } // DELETE http://localhost:8080/users/1 // func (u *UserService) removeUser(request *restful.Request, response *restful.Response) { id := request.PathParameter("user-id") delete(u.users, id) } func main() { u := UserService{map[string]User{}} u.Register() // Optionally, you can install the Swagger Service which provides a nice Web UI on your REST API // You need to download the Swagger HTML5 assets and change the FilePath location in the config below. // Open http://localhost:8080/apidocs and enter http://localhost:8080/apidocs.json in the api input field. config := swagger.Config{ WebServices: restful.RegisteredWebServices(), // you control what services are visible WebServicesUrl: "http://localhost:8080", ApiPath: "/apidocs.json", // Optionally, specifiy where the UI is located SwaggerPath: "/apidocs/", SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"} swagger.InstallSwaggerService(config) log.Printf("start listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) } ================================================ FILE: vendor/github.com/emicklei/go-restful/filter.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. // FilterChain is a request scoped object to process one or more filters before calling the target RouteFunction. type FilterChain struct { Filters []FilterFunction // ordered list of FilterFunction Index int // index into filters that is currently in progress Target RouteFunction // function to call after passing all filters } // ProcessFilter passes the request,response pair through the next of Filters. // Each filter can decide to proceed to the next Filter or handle the Response itself. func (f *FilterChain) ProcessFilter(request *Request, response *Response) { if f.Index < len(f.Filters) { f.Index++ f.Filters[f.Index-1](request, response, f) } else { f.Target(request, response) } } // FilterFunction definitions must call ProcessFilter on the FilterChain to pass on the control and eventually call the RouteFunction type FilterFunction func(*Request, *Response, *FilterChain) ================================================ FILE: vendor/github.com/emicklei/go-restful/filter_test.go ================================================ package restful import ( "io" "net/http" "net/http/httptest" "testing" ) func setupServices(addGlobalFilter bool, addServiceFilter bool, addRouteFilter bool) { if addGlobalFilter { Filter(globalFilter) } Add(newTestService(addServiceFilter, addRouteFilter)) } func tearDown() { DefaultContainer.webServices = []*WebService{} DefaultContainer.isRegisteredOnRoot = true // this allows for setupServices multiple times DefaultContainer.containerFilters = []FilterFunction{} } func newTestService(addServiceFilter bool, addRouteFilter bool) *WebService { ws := new(WebService).Path("") if addServiceFilter { ws.Filter(serviceFilter) } rb := ws.GET("/foo").To(foo) if addRouteFilter { rb.Filter(routeFilter) } ws.Route(rb) ws.Route(ws.GET("/bar").To(bar)) return ws } func foo(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "foo") } func bar(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "bar") } func fail(req *Request, resp *Response) { http.Error(resp.ResponseWriter, "something failed", http.StatusInternalServerError) } func globalFilter(req *Request, resp *Response, chain *FilterChain) { io.WriteString(resp.ResponseWriter, "global-") chain.ProcessFilter(req, resp) } func serviceFilter(req *Request, resp *Response, chain *FilterChain) { io.WriteString(resp.ResponseWriter, "service-") chain.ProcessFilter(req, resp) } func routeFilter(req *Request, resp *Response, chain *FilterChain) { io.WriteString(resp.ResponseWriter, "route-") chain.ProcessFilter(req, resp) } func TestNoFilter(t *testing.T) { tearDown() setupServices(false, false, false) actual := sendIt("http://example.com/foo") if "foo" != actual { t.Fatal("expected: foo but got:" + actual) } } func TestGlobalFilter(t *testing.T) { tearDown() setupServices(true, false, false) actual := sendIt("http://example.com/foo") if "global-foo" != actual { t.Fatal("expected: global-foo but got:" + actual) } } func TestWebServiceFilter(t *testing.T) { tearDown() setupServices(true, true, false) actual := sendIt("http://example.com/foo") if "global-service-foo" != actual { t.Fatal("expected: global-service-foo but got:" + actual) } } func TestRouteFilter(t *testing.T) { tearDown() setupServices(true, true, true) actual := sendIt("http://example.com/foo") if "global-service-route-foo" != actual { t.Fatal("expected: global-service-route-foo but got:" + actual) } } func TestRouteFilterOnly(t *testing.T) { tearDown() setupServices(false, false, true) actual := sendIt("http://example.com/foo") if "route-foo" != actual { t.Fatal("expected: route-foo but got:" + actual) } } func TestBar(t *testing.T) { tearDown() setupServices(false, true, false) actual := sendIt("http://example.com/bar") if "service-bar" != actual { t.Fatal("expected: service-bar but got:" + actual) } } func TestAllFiltersBar(t *testing.T) { tearDown() setupServices(true, true, true) actual := sendIt("http://example.com/bar") if "global-service-bar" != actual { t.Fatal("expected: global-service-bar but got:" + actual) } } func sendIt(address string) string { httpRequest, _ := http.NewRequest("GET", address, nil) httpRequest.Header.Set("Accept", "*/*") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) return httpWriter.Body.String() } func sendItTo(address string, container *Container) string { httpRequest, _ := http.NewRequest("GET", address, nil) httpRequest.Header.Set("Accept", "*/*") httpWriter := httptest.NewRecorder() container.dispatch(httpWriter, httpRequest) return httpWriter.Body.String() } ================================================ FILE: vendor/github.com/emicklei/go-restful/install.sh ================================================ cd examples ls *.go | xargs -I {} go build -o /tmp/ignore {} cd .. go fmt ...swagger && \ go test -test.v ...swagger && \ go install ...swagger && \ go fmt ...restful && \ go test -test.v ...restful && \ go install ...restful ================================================ FILE: vendor/github.com/emicklei/go-restful/jsr311.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "errors" "fmt" "net/http" "sort" ) // RouterJSR311 implements the flow for matching Requests to Routes (and consequently Resource Functions) // as specified by the JSR311 http://jsr311.java.net/nonav/releases/1.1/spec/spec.html. // RouterJSR311 implements the Router interface. // Concept of locators is not implemented. type RouterJSR311 struct{} // SelectRoute is part of the Router interface and returns the best match // for the WebService and its Route for the given Request. func (r RouterJSR311) SelectRoute( webServices []*WebService, httpRequest *http.Request) (selectedService *WebService, selectedRoute *Route, err error) { // Identify the root resource class (WebService) dispatcher, finalMatch, err := r.detectDispatcher(httpRequest.URL.Path, webServices) if err != nil { return nil, nil, NewError(http.StatusNotFound, "") } // Obtain the set of candidate methods (Routes) routes := r.selectRoutes(dispatcher, finalMatch) if len(routes) == 0 { return dispatcher, nil, NewError(http.StatusNotFound, "404: Page Not Found") } // Identify the method (Route) that will handle the request route, ok := r.detectRoute(routes, httpRequest) return dispatcher, route, ok } // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 func (r RouterJSR311) detectRoute(routes []Route, httpRequest *http.Request) (*Route, error) { // http method methodOk := []Route{} for _, each := range routes { if httpRequest.Method == each.Method { methodOk = append(methodOk, each) } } if len(methodOk) == 0 { if trace { traceLogger.Printf("no Route found (in %d routes) that matches HTTP method %s\n", len(routes), httpRequest.Method) } return nil, NewError(http.StatusMethodNotAllowed, "405: Method Not Allowed") } inputMediaOk := methodOk // content-type contentType := httpRequest.Header.Get(HEADER_ContentType) inputMediaOk = []Route{} for _, each := range methodOk { if each.matchesContentType(contentType) { inputMediaOk = append(inputMediaOk, each) } } if len(inputMediaOk) == 0 { if trace { traceLogger.Printf("no Route found (from %d) that matches HTTP Content-Type: %s\n", len(methodOk), contentType) } return nil, NewError(http.StatusUnsupportedMediaType, "415: Unsupported Media Type") } // accept outputMediaOk := []Route{} accept := httpRequest.Header.Get(HEADER_Accept) if accept == "" { accept = "*/*" } for _, each := range inputMediaOk { if each.matchesAccept(accept) { outputMediaOk = append(outputMediaOk, each) } } if len(outputMediaOk) == 0 { if trace { traceLogger.Printf("no Route found (from %d) that matches HTTP Accept: %s\n", len(inputMediaOk), accept) } return nil, NewError(http.StatusNotAcceptable, "406: Not Acceptable") } return r.bestMatchByMedia(outputMediaOk, contentType, accept), nil } // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 // n/m > n/* > */* func (r RouterJSR311) bestMatchByMedia(routes []Route, contentType string, accept string) *Route { // TODO return &routes[0] } // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 (step 2) func (r RouterJSR311) selectRoutes(dispatcher *WebService, pathRemainder string) []Route { filtered := &sortableRouteCandidates{} for _, each := range dispatcher.Routes() { pathExpr := each.pathExpr matches := pathExpr.Matcher.FindStringSubmatch(pathRemainder) if matches != nil { lastMatch := matches[len(matches)-1] if len(lastMatch) == 0 || lastMatch == "/" { // do not include if value is neither empty nor ‘/’. filtered.candidates = append(filtered.candidates, routeCandidate{each, len(matches) - 1, pathExpr.LiteralCount, pathExpr.VarCount}) } } } if len(filtered.candidates) == 0 { if trace { traceLogger.Printf("WebService on path %s has no routes that match URL path remainder:%s\n", dispatcher.rootPath, pathRemainder) } return []Route{} } sort.Sort(sort.Reverse(filtered)) // select other routes from candidates whoes expression matches rmatch matchingRoutes := []Route{filtered.candidates[0].route} for c := 1; c < len(filtered.candidates); c++ { each := filtered.candidates[c] if each.route.pathExpr.Matcher.MatchString(pathRemainder) { matchingRoutes = append(matchingRoutes, each.route) } } return matchingRoutes } // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-360003.7.2 (step 1) func (r RouterJSR311) detectDispatcher(requestPath string, dispatchers []*WebService) (*WebService, string, error) { filtered := &sortableDispatcherCandidates{} for _, each := range dispatchers { matches := each.pathExpr.Matcher.FindStringSubmatch(requestPath) if matches != nil { filtered.candidates = append(filtered.candidates, dispatcherCandidate{each, matches[len(matches)-1], len(matches), each.pathExpr.LiteralCount, each.pathExpr.VarCount}) } } if len(filtered.candidates) == 0 { if trace { traceLogger.Printf("no WebService was found to match URL path:%s\n", requestPath) } return nil, "", errors.New("not found") } sort.Sort(sort.Reverse(filtered)) return filtered.candidates[0].dispatcher, filtered.candidates[0].finalMatch, nil } // Types and functions to support the sorting of Routes type routeCandidate struct { route Route matchesCount int // the number of capturing groups literalCount int // the number of literal characters (means those not resulting from template variable substitution) nonDefaultCount int // the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’) } func (r routeCandidate) expressionToMatch() string { return r.route.pathExpr.Source } func (r routeCandidate) String() string { return fmt.Sprintf("(m=%d,l=%d,n=%d)", r.matchesCount, r.literalCount, r.nonDefaultCount) } type sortableRouteCandidates struct { candidates []routeCandidate } func (rcs *sortableRouteCandidates) Len() int { return len(rcs.candidates) } func (rcs *sortableRouteCandidates) Swap(i, j int) { rcs.candidates[i], rcs.candidates[j] = rcs.candidates[j], rcs.candidates[i] } func (rcs *sortableRouteCandidates) Less(i, j int) bool { ci := rcs.candidates[i] cj := rcs.candidates[j] // primary key if ci.literalCount < cj.literalCount { return true } if ci.literalCount > cj.literalCount { return false } // secundary key if ci.matchesCount < cj.matchesCount { return true } if ci.matchesCount > cj.matchesCount { return false } // tertiary key if ci.nonDefaultCount < cj.nonDefaultCount { return true } if ci.nonDefaultCount > cj.nonDefaultCount { return false } // quaternary key ("source" is interpreted as Path) return ci.route.Path < cj.route.Path } // Types and functions to support the sorting of Dispatchers type dispatcherCandidate struct { dispatcher *WebService finalMatch string matchesCount int // the number of capturing groups literalCount int // the number of literal characters (means those not resulting from template variable substitution) nonDefaultCount int // the number of capturing groups with non-default regular expressions (i.e. not ‘([^ /]+?)’) } type sortableDispatcherCandidates struct { candidates []dispatcherCandidate } func (dc *sortableDispatcherCandidates) Len() int { return len(dc.candidates) } func (dc *sortableDispatcherCandidates) Swap(i, j int) { dc.candidates[i], dc.candidates[j] = dc.candidates[j], dc.candidates[i] } func (dc *sortableDispatcherCandidates) Less(i, j int) bool { ci := dc.candidates[i] cj := dc.candidates[j] // primary key if ci.matchesCount < cj.matchesCount { return true } if ci.matchesCount > cj.matchesCount { return false } // secundary key if ci.literalCount < cj.literalCount { return true } if ci.literalCount > cj.literalCount { return false } // tertiary key return ci.nonDefaultCount < cj.nonDefaultCount } ================================================ FILE: vendor/github.com/emicklei/go-restful/jsr311_test.go ================================================ package restful import ( "io" "sort" "testing" ) // // Step 1 tests // var paths = []struct { // url with path (1) is handled by service with root (2) and last capturing group has value final (3) path, root, final string }{ {"/", "/", "/"}, {"/p", "/p", ""}, {"/p/x", "/p/{q}", ""}, {"/q/x", "/q", "/x"}, {"/p/x/", "/p/{q}", "/"}, {"/p/x/y", "/p/{q}", "/y"}, {"/q/x/y", "/q", "/x/y"}, {"/z/q", "/{p}/q", ""}, {"/a/b/c/q", "/", "/a/b/c/q"}, } func TestDetectDispatcher(t *testing.T) { ws1 := new(WebService).Path("/") ws2 := new(WebService).Path("/p") ws3 := new(WebService).Path("/q") ws4 := new(WebService).Path("/p/q") ws5 := new(WebService).Path("/p/{q}") ws6 := new(WebService).Path("/p/{q}/") ws7 := new(WebService).Path("/{p}/q") var dispatchers = []*WebService{ws1, ws2, ws3, ws4, ws5, ws6, ws7} wc := NewContainer() for _, each := range dispatchers { wc.Add(each) } router := RouterJSR311{} ok := true for i, fixture := range paths { who, final, err := router.detectDispatcher(fixture.path, dispatchers) if err != nil { t.Logf("error in detection:%v", err) ok = false } if who.RootPath() != fixture.root { t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath()) ok = false } if final != fixture.final { t.Logf("[line:%v] Unexpected final, expected:%v, actual:%v", i, fixture.final, final) ok = false } } if !ok { t.Fail() } } // // Step 2 tests // // go test -v -test.run TestISSUE_179 ...restful func TestISSUE_179(t *testing.T) { ws1 := new(WebService) ws1.Route(ws1.GET("/v1/category/{param:*}").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/v1/category/sub/sub") t.Logf("%v", routes) } // go test -v -test.run TestISSUE_30 ...restful func TestISSUE_30(t *testing.T) { ws1 := new(WebService).Path("/users") ws1.Route(ws1.GET("/{id}").To(dummy)) ws1.Route(ws1.POST("/login").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/login") if len(routes) != 2 { t.Fatal("expected 2 routes") } if routes[0].Path != "/users/login" { t.Error("first is", routes[0].Path) t.Logf("routes:%v", routes) } } // go test -v -test.run TestISSUE_34 ...restful func TestISSUE_34(t *testing.T) { ws1 := new(WebService).Path("/") ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) ws1.Route(ws1.GET("/network/{id}").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") if len(routes) != 2 { t.Fatal("expected 2 routes") } if routes[0].Path != "/network/{id}" { t.Error("first is", routes[0].Path) t.Logf("routes:%v", routes) } } // go test -v -test.run TestISSUE_34_2 ...restful func TestISSUE_34_2(t *testing.T) { ws1 := new(WebService).Path("/") // change the registration order ws1.Route(ws1.GET("/network/{id}").To(dummy)) ws1.Route(ws1.GET("/{type}/{id}").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/network/12") if len(routes) != 2 { t.Fatal("expected 2 routes") } if routes[0].Path != "/network/{id}" { t.Error("first is", routes[0].Path) } } // go test -v -test.run TestISSUE_137 ...restful func TestISSUE_137(t *testing.T) { ws1 := new(WebService) ws1.Route(ws1.GET("/hello").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/") t.Log(routes) if len(routes) > 0 { t.Error("no route expected") } } func TestSelectRoutesSlash(t *testing.T) { ws1 := new(WebService).Path("/") ws1.Route(ws1.GET("").To(dummy)) ws1.Route(ws1.GET("/").To(dummy)) ws1.Route(ws1.GET("/u").To(dummy)) ws1.Route(ws1.POST("/u").To(dummy)) ws1.Route(ws1.POST("/u/v").To(dummy)) ws1.Route(ws1.POST("/u/{w}").To(dummy)) ws1.Route(ws1.POST("/u/{w}/z").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/u") checkRoutesContains(routes, "/u", t) checkRoutesContainsNo(routes, "/u/v", t) checkRoutesContainsNo(routes, "/", t) checkRoutesContainsNo(routes, "/u/{w}/z", t) } func TestSelectRoutesU(t *testing.T) { ws1 := new(WebService).Path("/u") ws1.Route(ws1.GET("").To(dummy)) ws1.Route(ws1.GET("/").To(dummy)) ws1.Route(ws1.GET("/v").To(dummy)) ws1.Route(ws1.POST("/{w}").To(dummy)) ws1.Route(ws1.POST("/{w}/z").To(dummy)) // so full path = /u/{w}/z routes := RouterJSR311{}.selectRoutes(ws1, "/v") // test against /u/v checkRoutesContains(routes, "/u/{w}", t) } func TestSelectRoutesUsers1(t *testing.T) { ws1 := new(WebService).Path("/users") ws1.Route(ws1.POST("").To(dummy)) ws1.Route(ws1.POST("/").To(dummy)) ws1.Route(ws1.PUT("/{id}").To(dummy)) routes := RouterJSR311{}.selectRoutes(ws1, "/1") checkRoutesContains(routes, "/users/{id}", t) } func checkRoutesContains(routes []Route, path string, t *testing.T) { if !containsRoutePath(routes, path, t) { for _, r := range routes { t.Logf("route %v %v", r.Method, r.Path) } t.Fatalf("routes should include [%v]:", path) } } func checkRoutesContainsNo(routes []Route, path string, t *testing.T) { if containsRoutePath(routes, path, t) { for _, r := range routes { t.Logf("route %v %v", r.Method, r.Path) } t.Fatalf("routes should not include [%v]:", path) } } func containsRoutePath(routes []Route, path string, t *testing.T) bool { for _, each := range routes { if each.Path == path { return true } } return false } // go test -v -test.run TestSortableRouteCandidates ...restful func TestSortableRouteCandidates(t *testing.T) { fixture := &sortableRouteCandidates{} r1 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 0} r2 := routeCandidate{matchesCount: 0, literalCount: 0, nonDefaultCount: 1} r3 := routeCandidate{matchesCount: 0, literalCount: 1, nonDefaultCount: 1} r4 := routeCandidate{matchesCount: 1, literalCount: 1, nonDefaultCount: 0} r5 := routeCandidate{matchesCount: 1, literalCount: 0, nonDefaultCount: 0} fixture.candidates = append(fixture.candidates, r5, r4, r3, r2, r1) sort.Sort(sort.Reverse(fixture)) first := fixture.candidates[0] if first.matchesCount != 1 && first.literalCount != 1 && first.nonDefaultCount != 0 { t.Fatal("expected r4") } last := fixture.candidates[len(fixture.candidates)-1] if last.matchesCount != 0 && last.literalCount != 0 && last.nonDefaultCount != 0 { t.Fatal("expected r1") } } func dummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "dummy") } ================================================ FILE: vendor/github.com/emicklei/go-restful/log/log.go ================================================ package log import ( stdlog "log" "os" ) // Logger corresponds to a minimal subset of the interface satisfied by stdlib log.Logger type StdLogger interface { Print(v ...interface{}) Printf(format string, v ...interface{}) } var Logger StdLogger func init() { // default Logger SetLogger(stdlog.New(os.Stderr, "[restful] ", stdlog.LstdFlags|stdlog.Lshortfile)) } func SetLogger(customLogger StdLogger) { Logger = customLogger } func Print(v ...interface{}) { Logger.Print(v...) } func Printf(format string, v ...interface{}) { Logger.Printf(format, v...) } ================================================ FILE: vendor/github.com/emicklei/go-restful/logger.go ================================================ package restful // Copyright 2014 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "github.com/emicklei/go-restful/log" ) var trace bool = false var traceLogger log.StdLogger func init() { traceLogger = log.Logger // use the package logger by default } // TraceLogger enables detailed logging of Http request matching and filter invocation. Default no logger is set. // You may call EnableTracing() directly to enable trace logging to the package-wide logger. func TraceLogger(logger log.StdLogger) { traceLogger = logger EnableTracing(logger != nil) } // expose the setter for the global logger on the top-level package func SetLogger(customLogger log.StdLogger) { log.SetLogger(customLogger) } // EnableTracing can be used to Trace logging on and off. func EnableTracing(enabled bool) { trace = enabled } ================================================ FILE: vendor/github.com/emicklei/go-restful/options_filter.go ================================================ package restful import "strings" // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. // OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method // and provides the response with a set of allowed methods for the request URL Path. // As for any filter, you can also install it for a particular WebService within a Container. // Note: this filter is not needed when using CrossOriginResourceSharing (for CORS). func (c *Container) OPTIONSFilter(req *Request, resp *Response, chain *FilterChain) { if "OPTIONS" != req.Request.Method { chain.ProcessFilter(req, resp) return } resp.AddHeader(HEADER_Allow, strings.Join(c.computeAllowedMethods(req), ",")) } // OPTIONSFilter is a filter function that inspects the Http Request for the OPTIONS method // and provides the response with a set of allowed methods for the request URL Path. // Note: this filter is not needed when using CrossOriginResourceSharing (for CORS). func OPTIONSFilter() FilterFunction { return DefaultContainer.OPTIONSFilter } ================================================ FILE: vendor/github.com/emicklei/go-restful/options_filter_test.go ================================================ package restful import ( "net/http" "net/http/httptest" "testing" ) // go test -v -test.run TestOptionsFilter ...restful func TestOptionsFilter(t *testing.T) { tearDown() ws := new(WebService) ws.Route(ws.GET("/candy/{kind}").To(dummy)) ws.Route(ws.DELETE("/candy/{kind}").To(dummy)) ws.Route(ws.POST("/candies").To(dummy)) Add(ws) Filter(OPTIONSFilter()) httpRequest, _ := http.NewRequest("OPTIONS", "http://here.io/candy/gum", nil) httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) actual := httpWriter.Header().Get(HEADER_Allow) if "GET,DELETE" != actual { t.Fatal("expected: GET,DELETE but got:" + actual) } httpRequest, _ = http.NewRequest("OPTIONS", "http://here.io/candies", nil) httpWriter = httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) actual = httpWriter.Header().Get(HEADER_Allow) if "POST" != actual { t.Fatal("expected: POST but got:" + actual) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/parameter.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. const ( // PathParameterKind = indicator of Request parameter type "path" PathParameterKind = iota // QueryParameterKind = indicator of Request parameter type "query" QueryParameterKind // BodyParameterKind = indicator of Request parameter type "body" BodyParameterKind // HeaderParameterKind = indicator of Request parameter type "header" HeaderParameterKind // FormParameterKind = indicator of Request parameter type "form" FormParameterKind ) // Parameter is for documententing the parameter used in a Http Request // ParameterData kinds are Path,Query and Body type Parameter struct { data *ParameterData } // ParameterData represents the state of a Parameter. // It is made public to make it accessible to e.g. the Swagger package. type ParameterData struct { Name, Description, DataType, DataFormat string Kind int Required bool AllowableValues map[string]string AllowMultiple bool DefaultValue string } // Data returns the state of the Parameter func (p *Parameter) Data() ParameterData { return *p.data } // Kind returns the parameter type indicator (see const for valid values) func (p *Parameter) Kind() int { return p.data.Kind } func (p *Parameter) bePath() *Parameter { p.data.Kind = PathParameterKind return p } func (p *Parameter) beQuery() *Parameter { p.data.Kind = QueryParameterKind return p } func (p *Parameter) beBody() *Parameter { p.data.Kind = BodyParameterKind return p } func (p *Parameter) beHeader() *Parameter { p.data.Kind = HeaderParameterKind return p } func (p *Parameter) beForm() *Parameter { p.data.Kind = FormParameterKind return p } // Required sets the required field and returns the receiver func (p *Parameter) Required(required bool) *Parameter { p.data.Required = required return p } // AllowMultiple sets the allowMultiple field and returns the receiver func (p *Parameter) AllowMultiple(multiple bool) *Parameter { p.data.AllowMultiple = multiple return p } // AllowableValues sets the allowableValues field and returns the receiver func (p *Parameter) AllowableValues(values map[string]string) *Parameter { p.data.AllowableValues = values return p } // DataType sets the dataType field and returns the receiver func (p *Parameter) DataType(typeName string) *Parameter { p.data.DataType = typeName return p } // DataFormat sets the dataFormat field for Swagger UI func (p *Parameter) DataFormat(formatName string) *Parameter { p.data.DataFormat = formatName return p } // DefaultValue sets the default value field and returns the receiver func (p *Parameter) DefaultValue(stringRepresentation string) *Parameter { p.data.DefaultValue = stringRepresentation return p } // Description sets the description value field and returns the receiver func (p *Parameter) Description(doc string) *Parameter { p.data.Description = doc return p } ================================================ FILE: vendor/github.com/emicklei/go-restful/path_expression.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "fmt" "regexp" "strings" ) // PathExpression holds a compiled path expression (RegExp) needed to match against // Http request paths and to extract path parameter values. type pathExpression struct { LiteralCount int // the number of literal characters (means those not resulting from template variable substitution) VarCount int // the number of named parameters (enclosed by {}) in the path Matcher *regexp.Regexp Source string // Path as defined by the RouteBuilder tokens []string } // NewPathExpression creates a PathExpression from the input URL path. // Returns an error if the path is invalid. func newPathExpression(path string) (*pathExpression, error) { expression, literalCount, varCount, tokens := templateToRegularExpression(path) compiled, err := regexp.Compile(expression) if err != nil { return nil, err } return &pathExpression{literalCount, varCount, compiled, expression, tokens}, nil } // http://jsr311.java.net/nonav/releases/1.1/spec/spec3.html#x3-370003.7.3 func templateToRegularExpression(template string) (expression string, literalCount int, varCount int, tokens []string) { var buffer bytes.Buffer buffer.WriteString("^") //tokens = strings.Split(template, "/") tokens = tokenizePath(template) for _, each := range tokens { if each == "" { continue } buffer.WriteString("/") if strings.HasPrefix(each, "{") { // check for regular expression in variable colon := strings.Index(each, ":") if colon != -1 { // extract expression paramExpr := strings.TrimSpace(each[colon+1 : len(each)-1]) if paramExpr == "*" { // special case buffer.WriteString("(.*)") } else { buffer.WriteString(fmt.Sprintf("(%s)", paramExpr)) // between colon and closing moustache } } else { // plain var buffer.WriteString("([^/]+?)") } varCount += 1 } else { literalCount += len(each) encoded := each // TODO URI encode buffer.WriteString(regexp.QuoteMeta(encoded)) } } return strings.TrimRight(buffer.String(), "/") + "(/.*)?$", literalCount, varCount, tokens } ================================================ FILE: vendor/github.com/emicklei/go-restful/path_expression_test.go ================================================ package restful import "testing" var tempregexs = []struct { template, regex string literalCount, varCount int }{ {"", "^(/.*)?$", 0, 0}, {"/a/{b}/c/", "^/a/([^/]+?)/c(/.*)?$", 2, 1}, {"/{a}/{b}/{c-d-e}/", "^/([^/]+?)/([^/]+?)/([^/]+?)(/.*)?$", 0, 3}, {"/{p}/abcde", "^/([^/]+?)/abcde(/.*)?$", 5, 1}, {"/a/{b:*}", "^/a/(.*)(/.*)?$", 1, 1}, {"/a/{b:[a-z]+}", "^/a/([a-z]+)(/.*)?$", 1, 1}, } func TestTemplateToRegularExpression(t *testing.T) { ok := true for i, fixture := range tempregexs { actual, lCount, vCount, _ := templateToRegularExpression(fixture.template) if actual != fixture.regex { t.Logf("regex mismatch, expected:%v , actual:%v, line:%v\n", fixture.regex, actual, i) // 11 = where the data starts ok = false } if lCount != fixture.literalCount { t.Logf("literal count mismatch, expected:%v , actual:%v, line:%v\n", fixture.literalCount, lCount, i) ok = false } if vCount != fixture.varCount { t.Logf("variable count mismatch, expected:%v , actual:%v, line:%v\n", fixture.varCount, vCount, i) ok = false } } if !ok { t.Fatal("one or more expression did not match") } } ================================================ FILE: vendor/github.com/emicklei/go-restful/request.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "compress/zlib" "io/ioutil" "net/http" ) var defaultRequestContentType string var doCacheReadEntityBytes = true // Request is a wrapper for a http Request that provides convenience methods type Request struct { Request *http.Request bodyContent *[]byte // to cache the request body for multiple reads of ReadEntity pathParameters map[string]string attributes map[string]interface{} // for storing request-scoped values selectedRoutePath string // root path + route path that matched the request, e.g. /meetings/{id}/attendees } func NewRequest(httpRequest *http.Request) *Request { return &Request{ Request: httpRequest, pathParameters: map[string]string{}, attributes: map[string]interface{}{}, } // empty parameters, attributes } // If ContentType is missing or */* is given then fall back to this type, otherwise // a "Unable to unmarshal content of type:" response is returned. // Valid values are restful.MIME_JSON and restful.MIME_XML // Example: // restful.DefaultRequestContentType(restful.MIME_JSON) func DefaultRequestContentType(mime string) { defaultRequestContentType = mime } // SetCacheReadEntity controls whether the response data ([]byte) is cached such that ReadEntity is repeatable. // Default is true (due to backwardcompatibility). For better performance, you should set it to false if you don't need it. func SetCacheReadEntity(doCache bool) { doCacheReadEntityBytes = doCache } // PathParameter accesses the Path parameter value by its name func (r *Request) PathParameter(name string) string { return r.pathParameters[name] } // PathParameters accesses the Path parameter values func (r *Request) PathParameters() map[string]string { return r.pathParameters } // QueryParameter returns the (first) Query parameter value by its name func (r *Request) QueryParameter(name string) string { return r.Request.FormValue(name) } // BodyParameter parses the body of the request (once for typically a POST or a PUT) and returns the value of the given name or an error. func (r *Request) BodyParameter(name string) (string, error) { err := r.Request.ParseForm() if err != nil { return "", err } return r.Request.PostFormValue(name), nil } // HeaderParameter returns the HTTP Header value of a Header name or empty if missing func (r *Request) HeaderParameter(name string) string { return r.Request.Header.Get(name) } // ReadEntity checks the Accept header and reads the content into the entityPointer. func (r *Request) ReadEntity(entityPointer interface{}) (err error) { contentType := r.Request.Header.Get(HEADER_ContentType) contentEncoding := r.Request.Header.Get(HEADER_ContentEncoding) // OLD feature, cache the body for reads if doCacheReadEntityBytes { if r.bodyContent == nil { data, err := ioutil.ReadAll(r.Request.Body) if err != nil { return err } r.bodyContent = &data } r.Request.Body = ioutil.NopCloser(bytes.NewReader(*r.bodyContent)) } // check if the request body needs decompression if ENCODING_GZIP == contentEncoding { gzipReader := currentCompressorProvider.AcquireGzipReader() defer currentCompressorProvider.ReleaseGzipReader(gzipReader) gzipReader.Reset(r.Request.Body) r.Request.Body = gzipReader } else if ENCODING_DEFLATE == contentEncoding { zlibReader, err := zlib.NewReader(r.Request.Body) if err != nil { return err } r.Request.Body = zlibReader } // lookup the EntityReader entityReader, ok := entityAccessRegistry.AccessorAt(contentType) if !ok { return NewError(http.StatusBadRequest, "Unable to unmarshal content of type:"+contentType) } return entityReader.Read(r, entityPointer) } // SetAttribute adds or replaces the attribute with the given value. func (r *Request) SetAttribute(name string, value interface{}) { r.attributes[name] = value } // Attribute returns the value associated to the given name. Returns nil if absent. func (r Request) Attribute(name string) interface{} { return r.attributes[name] } // SelectedRoutePath root path + route path that matched the request, e.g. /meetings/{id}/attendees func (r Request) SelectedRoutePath() string { return r.selectedRoutePath } ================================================ FILE: vendor/github.com/emicklei/go-restful/request_test.go ================================================ package restful import ( "encoding/json" "net/http" "net/url" "strconv" "strings" "testing" ) func TestQueryParameter(t *testing.T) { hreq := http.Request{Method: "GET"} hreq.URL, _ = url.Parse("http://www.google.com/search?q=foo&q=bar") rreq := Request{Request: &hreq} if rreq.QueryParameter("q") != "foo" { t.Errorf("q!=foo %#v", rreq) } } type Anything map[string]interface{} type Number struct { ValueFloat float64 ValueInt int64 } type Sample struct { Value string } func TestReadEntityXmlCached(t *testing.T) { SetCacheReadEntity(true) bodyReader := strings.NewReader("42") httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/xml") request := &Request{Request: httpRequest} sam := new(Sample) request.ReadEntity(sam) if sam.Value != "42" { t.Fatal("read failed") } if request.bodyContent == nil { t.Fatal("no expected cached bytes found") } } func TestReadEntityXmlNonCached(t *testing.T) { SetCacheReadEntity(false) bodyReader := strings.NewReader("42") httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/xml") request := &Request{Request: httpRequest} sam := new(Sample) request.ReadEntity(sam) if sam.Value != "42" { t.Fatal("read failed") } if request.bodyContent != nil { t.Fatal("unexpected cached bytes found") } } func TestReadEntityJson(t *testing.T) { bodyReader := strings.NewReader(`{"Value" : "42"}`) httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/json") request := &Request{Request: httpRequest} sam := new(Sample) request.ReadEntity(sam) if sam.Value != "42" { t.Fatal("read failed") } } func TestReadEntityJsonCharset(t *testing.T) { bodyReader := strings.NewReader(`{"Value" : "42"}`) httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/json; charset=UTF-8") request := NewRequest(httpRequest) sam := new(Sample) request.ReadEntity(sam) if sam.Value != "42" { t.Fatal("read failed") } } func TestReadEntityJsonNumber(t *testing.T) { SetCacheReadEntity(true) bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/json") request := &Request{Request: httpRequest} any := make(Anything) request.ReadEntity(&any) number, ok := any["Value"].(json.Number) if !ok { t.Fatal("read failed") } vint, err := number.Int64() if err != nil { t.Fatal("convert failed") } if vint != 4899710515899924123 { t.Fatal("read failed") } vfloat, err := number.Float64() if err != nil { t.Fatal("convert failed") } // match the default behaviour vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) if vstring != "4.899710515899924e+18" { t.Fatal("convert float64 failed") } } func TestReadEntityJsonNumberNonCached(t *testing.T) { SetCacheReadEntity(false) bodyReader := strings.NewReader(`{"Value" : 4899710515899924123}`) httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/json") request := &Request{Request: httpRequest} any := make(Anything) request.ReadEntity(&any) number, ok := any["Value"].(json.Number) if !ok { t.Fatal("read failed") } vint, err := number.Int64() if err != nil { t.Fatal("convert failed") } if vint != 4899710515899924123 { t.Fatal("read failed") } vfloat, err := number.Float64() if err != nil { t.Fatal("convert failed") } // match the default behaviour vstring := strconv.FormatFloat(vfloat, 'e', 15, 64) if vstring != "4.899710515899924e+18" { t.Fatal("convert float64 failed") } } func TestReadEntityJsonLong(t *testing.T) { bodyReader := strings.NewReader(`{"ValueFloat" : 4899710515899924123, "ValueInt": 4899710515899924123}`) httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/json") request := &Request{Request: httpRequest} number := new(Number) request.ReadEntity(&number) if number.ValueInt != 4899710515899924123 { t.Fatal("read failed") } // match the default behaviour vstring := strconv.FormatFloat(number.ValueFloat, 'e', 15, 64) if vstring != "4.899710515899924e+18" { t.Fatal("convert float64 failed") } } func TestBodyParameter(t *testing.T) { bodyReader := strings.NewReader(`value1=42&value2=43`) httpRequest, _ := http.NewRequest("POST", "/test?value1=44", bodyReader) // POST and PUT body parameters take precedence over URL query string httpRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") request := NewRequest(httpRequest) v1, err := request.BodyParameter("value1") if err != nil { t.Error(err) } v2, err := request.BodyParameter("value2") if err != nil { t.Error(err) } if v1 != "42" || v2 != "43" { t.Fatal("read failed") } } func TestReadEntityUnkown(t *testing.T) { bodyReader := strings.NewReader("?") httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) httpRequest.Header.Set("Content-Type", "application/rubbish") request := NewRequest(httpRequest) sam := new(Sample) err := request.ReadEntity(sam) if err == nil { t.Fatal("read should be in error") } } func TestSetAttribute(t *testing.T) { bodyReader := strings.NewReader("?") httpRequest, _ := http.NewRequest("GET", "/test", bodyReader) request := NewRequest(httpRequest) request.SetAttribute("go", "there") there := request.Attribute("go") if there != "there" { t.Fatalf("missing request attribute:%v", there) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/response.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "errors" "net/http" "strings" ) // DEPRECATED, use DefaultResponseContentType(mime) var DefaultResponseMimeType string //PrettyPrintResponses controls the indentation feature of XML and JSON serialization var PrettyPrintResponses = true // Response is a wrapper on the actual http ResponseWriter // It provides several convenience methods to prepare and write response content. type Response struct { http.ResponseWriter requestAccept string // mime-type what the Http Request says it wants to receive routeProduces []string // mime-types what the Route says it can produce statusCode int // HTTP status code that has been written explicity (if zero then net/http has written 200) contentLength int // number of bytes written for the response body prettyPrint bool // controls the indentation feature of XML and JSON serialization. It is initialized using var PrettyPrintResponses. err error // err property is kept when WriteError is called } // Creates a new response based on a http ResponseWriter. func NewResponse(httpWriter http.ResponseWriter) *Response { return &Response{httpWriter, "", []string{}, http.StatusOK, 0, PrettyPrintResponses, nil} // empty content-types } // If Accept header matching fails, fall back to this type. // Valid values are restful.MIME_JSON and restful.MIME_XML // Example: // restful.DefaultResponseContentType(restful.MIME_JSON) func DefaultResponseContentType(mime string) { DefaultResponseMimeType = mime } // InternalServerError writes the StatusInternalServerError header. // DEPRECATED, use WriteErrorString(http.StatusInternalServerError,reason) func (r Response) InternalServerError() Response { r.WriteHeader(http.StatusInternalServerError) return r } // PrettyPrint changes whether this response must produce pretty (line-by-line, indented) JSON or XML output. func (r *Response) PrettyPrint(bePretty bool) { r.prettyPrint = bePretty } // AddHeader is a shortcut for .Header().Add(header,value) func (r Response) AddHeader(header string, value string) Response { r.Header().Add(header, value) return r } // SetRequestAccepts tells the response what Mime-type(s) the HTTP request said it wants to accept. Exposed for testing. func (r *Response) SetRequestAccepts(mime string) { r.requestAccept = mime } // EntityWriter returns the registered EntityWriter that the entity (requested resource) // can write according to what the request wants (Accept) and what the Route can produce or what the restful defaults say. // If called before WriteEntity and WriteHeader then a false return value can be used to write a 406: Not Acceptable. func (r *Response) EntityWriter() (EntityReaderWriter, bool) { for _, qualifiedMime := range strings.Split(r.requestAccept, ",") { mime := strings.Trim(strings.Split(qualifiedMime, ";")[0], " ") if 0 == len(mime) || mime == "*/*" { for _, each := range r.routeProduces { if MIME_JSON == each { return entityAccessRegistry.AccessorAt(MIME_JSON) } if MIME_XML == each { return entityAccessRegistry.AccessorAt(MIME_XML) } } } else { // mime is not blank; see if we have a match in Produces for _, each := range r.routeProduces { if mime == each { if MIME_JSON == each { return entityAccessRegistry.AccessorAt(MIME_JSON) } if MIME_XML == each { return entityAccessRegistry.AccessorAt(MIME_XML) } } } } } writer, ok := entityAccessRegistry.AccessorAt(r.requestAccept) if !ok { // if not registered then fallback to the defaults (if set) if DefaultResponseMimeType == MIME_JSON { return entityAccessRegistry.AccessorAt(MIME_JSON) } if DefaultResponseMimeType == MIME_XML { return entityAccessRegistry.AccessorAt(MIME_XML) } if trace { traceLogger.Printf("no registered EntityReaderWriter found for %s", r.requestAccept) } } return writer, ok } // WriteEntity calls WriteHeaderAndEntity with Http Status OK (200) func (r *Response) WriteEntity(value interface{}) error { return r.WriteHeaderAndEntity(http.StatusOK, value) } // WriteHeaderAndEntity marshals the value using the representation denoted by the Accept Header and the registered EntityWriters. // If no Accept header is specified (or */*) then respond with the Content-Type as specified by the first in the Route.Produces. // If an Accept header is specified then respond with the Content-Type as specified by the first in the Route.Produces that is matched with the Accept header. // If the value is nil then no response is send except for the Http status. You may want to call WriteHeader(http.StatusNotFound) instead. // If there is no writer available that can represent the value in the requested MIME type then Http Status NotAcceptable is written. // Current implementation ignores any q-parameters in the Accept Header. // Returns an error if the value could not be written on the response. func (r *Response) WriteHeaderAndEntity(status int, value interface{}) error { writer, ok := r.EntityWriter() if !ok { r.WriteHeader(http.StatusNotAcceptable) return nil } return writer.Write(r, status, value) } // WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value) // It uses the standard encoding/xml package for marshalling the valuel ; not using a registered EntityReaderWriter. func (r *Response) WriteAsXml(value interface{}) error { return writeXML(r, http.StatusOK, MIME_XML, value) } // WriteHeaderAndXml is a convenience method for writing a status and value in xml (requires Xml tags on the value) // It uses the standard encoding/xml package for marshalling the valuel ; not using a registered EntityReaderWriter. func (r *Response) WriteHeaderAndXml(status int, value interface{}) error { return writeXML(r, status, MIME_XML, value) } // WriteAsJson is a convenience method for writing a value in json. // It uses the standard encoding/json package for marshalling the valuel ; not using a registered EntityReaderWriter. func (r *Response) WriteAsJson(value interface{}) error { return writeJSON(r, http.StatusOK, MIME_JSON, value) } // WriteJson is a convenience method for writing a value in Json with a given Content-Type. // It uses the standard encoding/json package for marshalling the valuel ; not using a registered EntityReaderWriter. func (r *Response) WriteJson(value interface{}, contentType string) error { return writeJSON(r, http.StatusOK, contentType, value) } // WriteHeaderAndJson is a convenience method for writing the status and a value in Json with a given Content-Type. // It uses the standard encoding/json package for marshalling the value ; not using a registered EntityReaderWriter. func (r *Response) WriteHeaderAndJson(status int, value interface{}, contentType string) error { return writeJSON(r, status, contentType, value) } // WriteError write the http status and the error string on the response. func (r *Response) WriteError(httpStatus int, err error) error { r.err = err return r.WriteErrorString(httpStatus, err.Error()) } // WriteServiceError is a convenience method for a responding with a status and a ServiceError func (r *Response) WriteServiceError(httpStatus int, err ServiceError) error { r.err = err return r.WriteHeaderAndEntity(httpStatus, err) } // WriteErrorString is a convenience method for an error status with the actual error func (r *Response) WriteErrorString(httpStatus int, errorReason string) error { if r.err == nil { // if not called from WriteError r.err = errors.New(errorReason) } r.WriteHeader(httpStatus) if _, err := r.Write([]byte(errorReason)); err != nil { return err } return nil } // WriteHeader is overridden to remember the Status Code that has been written. // Changes to the Header of the response have no effect after this. func (r *Response) WriteHeader(httpStatus int) { r.statusCode = httpStatus r.ResponseWriter.WriteHeader(httpStatus) } // StatusCode returns the code that has been written using WriteHeader. func (r Response) StatusCode() int { if 0 == r.statusCode { // no status code has been written yet; assume OK return http.StatusOK } return r.statusCode } // Write writes the data to the connection as part of an HTTP reply. // Write is part of http.ResponseWriter interface. func (r *Response) Write(bytes []byte) (int, error) { written, err := r.ResponseWriter.Write(bytes) r.contentLength += written return written, err } // ContentLength returns the number of bytes written for the response content. // Note that this value is only correct if all data is written through the Response using its Write* methods. // Data written directly using the underlying http.ResponseWriter is not accounted for. func (r Response) ContentLength() int { return r.contentLength } // CloseNotify is part of http.CloseNotifier interface func (r Response) CloseNotify() <-chan bool { return r.ResponseWriter.(http.CloseNotifier).CloseNotify() } // Error returns the err created by WriteError func (r Response) Error() error { return r.err } ================================================ FILE: vendor/github.com/emicklei/go-restful/response_test.go ================================================ package restful import ( "errors" "net/http" "net/http/httptest" "strings" "testing" ) func TestWriteHeader(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} resp.WriteHeader(123) if resp.StatusCode() != 123 { t.Errorf("Unexpected status code:%d", resp.StatusCode()) } } func TestNoWriteHeader(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} if resp.StatusCode() != http.StatusOK { t.Errorf("Unexpected status code:%d", resp.StatusCode()) } } type food struct { Kind string } // go test -v -test.run TestMeasureContentLengthXml ...restful func TestMeasureContentLengthXml(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} resp.WriteAsXml(food{"apple"}) if resp.ContentLength() != 76 { t.Errorf("Incorrect measured length:%d", resp.ContentLength()) } } // go test -v -test.run TestMeasureContentLengthJson ...restful func TestMeasureContentLengthJson(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} resp.WriteAsJson(food{"apple"}) if resp.ContentLength() != 22 { t.Errorf("Incorrect measured length:%d", resp.ContentLength()) } } // go test -v -test.run TestMeasureContentLengthJsonNotPretty ...restful func TestMeasureContentLengthJsonNotPretty(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, false, nil} resp.WriteAsJson(food{"apple"}) if resp.ContentLength() != 17 { // 16+1 using the Encoder directly yields another /n t.Errorf("Incorrect measured length:%d", resp.ContentLength()) } } // go test -v -test.run TestMeasureContentLengthWriteErrorString ...restful func TestMeasureContentLengthWriteErrorString(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} resp.WriteErrorString(404, "Invalid") if resp.ContentLength() != len("Invalid") { t.Errorf("Incorrect measured length:%d", resp.ContentLength()) } } // go test -v -test.run TestStatusIsPassedToResponse ...restful func TestStatusIsPassedToResponse(t *testing.T) { for _, each := range []struct { write, read int }{ {write: 204, read: 204}, {write: 304, read: 304}, {write: 200, read: 200}, {write: 400, read: 400}, } { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "*/*", []string{"*/*"}, 0, 0, true, nil} resp.WriteHeader(each.write) if got, want := httpWriter.Code, each.read; got != want { t.Errorf("got %v want %v", got, want) } } } // go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue54 ...restful func TestStatusCreatedAndContentTypeJson_Issue54(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} resp.WriteHeader(201) resp.WriteAsJson(food{"Juicy"}) if httpWriter.HeaderMap.Get("Content-Type") != "application/json" { t.Errorf("Expected content type json but got:%d", httpWriter.HeaderMap.Get("Content-Type")) } if httpWriter.Code != 201 { t.Errorf("Expected status 201 but got:%d", httpWriter.Code) } } type errorOnWriteRecorder struct { *httptest.ResponseRecorder } func (e errorOnWriteRecorder) Write(bytes []byte) (int, error) { return 0, errors.New("fail") } // go test -v -test.run TestLastWriteErrorCaught ...restful func TestLastWriteErrorCaught(t *testing.T) { httpWriter := errorOnWriteRecorder{httptest.NewRecorder()} resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} err := resp.WriteAsJson(food{"Juicy"}) if err.Error() != "fail" { t.Errorf("Unexpected error message:%v", err) } } // go test -v -test.run TestAcceptStarStar_Issue83 ...restful func TestAcceptStarStar_Issue83(t *testing.T) { httpWriter := httptest.NewRecorder() // Accept Produces resp := Response{httpWriter, "application/bogus,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} resp.WriteEntity(food{"Juicy"}) ct := httpWriter.Header().Get("Content-Type") if "application/json" != ct { t.Errorf("Unexpected content type:%s", ct) } } // go test -v -test.run TestAcceptSkipStarStar_Issue83 ...restful func TestAcceptSkipStarStar_Issue83(t *testing.T) { httpWriter := httptest.NewRecorder() // Accept Produces resp := Response{httpWriter, " application/xml ,*/* ; q=0.8", []string{"application/json", "application/xml"}, 0, 0, true, nil} resp.WriteEntity(food{"Juicy"}) ct := httpWriter.Header().Get("Content-Type") if "application/xml" != ct { t.Errorf("Unexpected content type:%s", ct) } } // go test -v -test.run TestAcceptXmlBeforeStarStar_Issue83 ...restful func TestAcceptXmlBeforeStarStar_Issue83(t *testing.T) { httpWriter := httptest.NewRecorder() // Accept Produces resp := Response{httpWriter, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", []string{"application/json"}, 0, 0, true, nil} resp.WriteEntity(food{"Juicy"}) ct := httpWriter.Header().Get("Content-Type") if "application/json" != ct { t.Errorf("Unexpected content type:%s", ct) } } // go test -v -test.run TestWriteHeaderNoContent_Issue124 ...restful func TestWriteHeaderNoContent_Issue124(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "text/plain", []string{"text/plain"}, 0, 0, true, nil} resp.WriteHeader(http.StatusNoContent) if httpWriter.Code != http.StatusNoContent { t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) } } // go test -v -test.run TestStatusCreatedAndContentTypeJson_Issue163 ...restful func TestStatusCreatedAndContentTypeJson_Issue163(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} resp.WriteHeader(http.StatusNotModified) if httpWriter.Code != http.StatusNotModified { t.Errorf("Got %d want %d", httpWriter.Code, http.StatusNotModified) } } func TestWriteHeaderAndEntity_Issue235(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "application/json", []string{"application/json"}, 0, 0, true, nil} var pong = struct { Foo string `json:"foo"` }{Foo: "123"} resp.WriteHeaderAndEntity(404, pong) if httpWriter.Code != http.StatusNotFound { t.Errorf("got %d want %d", httpWriter.Code, http.StatusNoContent) } if got, want := httpWriter.Header().Get("Content-Type"), "application/json"; got != want { t.Errorf("got %v want %v", got, want) } if !strings.HasPrefix(httpWriter.Body.String(), "{") { t.Errorf("expected pong struct in json:%s", httpWriter.Body.String()) } } func TestWriteEntityNotAcceptable(t *testing.T) { httpWriter := httptest.NewRecorder() resp := Response{httpWriter, "application/bogus", []string{"application/json"}, 0, 0, true, nil} resp.WriteEntity("done") if httpWriter.Code != http.StatusNotAcceptable { t.Errorf("got %d want %d", httpWriter.Code, http.StatusNotAcceptable) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/route.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "net/http" "strings" ) // RouteFunction declares the signature of a function that can be bound to a Route. type RouteFunction func(*Request, *Response) // Route binds a HTTP Method,Path,Consumes combination to a RouteFunction. type Route struct { Method string Produces []string Consumes []string Path string // webservice root path + described path Function RouteFunction Filters []FilterFunction // cached values for dispatching relativePath string pathParts []string pathExpr *pathExpression // cached compilation of relativePath as RegExp // documentation Doc string Notes string Operation string ParameterDocs []*Parameter ResponseErrors map[int]ResponseError ReadSample, WriteSample interface{} // structs that model an example request or response payload } // Initialize for Route func (r *Route) postBuild() { r.pathParts = tokenizePath(r.Path) } // Create Request and Response from their http versions func (r *Route) wrapRequestResponse(httpWriter http.ResponseWriter, httpRequest *http.Request) (*Request, *Response) { params := r.extractParameters(httpRequest.URL.Path) wrappedRequest := NewRequest(httpRequest) wrappedRequest.pathParameters = params wrappedRequest.selectedRoutePath = r.Path wrappedResponse := NewResponse(httpWriter) wrappedResponse.requestAccept = httpRequest.Header.Get(HEADER_Accept) wrappedResponse.routeProduces = r.Produces return wrappedRequest, wrappedResponse } // dispatchWithFilters call the function after passing through its own filters func (r *Route) dispatchWithFilters(wrappedRequest *Request, wrappedResponse *Response) { if len(r.Filters) > 0 { chain := FilterChain{Filters: r.Filters, Target: r.Function} chain.ProcessFilter(wrappedRequest, wrappedResponse) } else { // unfiltered r.Function(wrappedRequest, wrappedResponse) } } // Return whether the mimeType matches to what this Route can produce. func (r Route) matchesAccept(mimeTypesWithQuality string) bool { parts := strings.Split(mimeTypesWithQuality, ",") for _, each := range parts { var withoutQuality string if strings.Contains(each, ";") { withoutQuality = strings.Split(each, ";")[0] } else { withoutQuality = each } // trim before compare withoutQuality = strings.Trim(withoutQuality, " ") if withoutQuality == "*/*" { return true } for _, producibleType := range r.Produces { if producibleType == "*/*" || producibleType == withoutQuality { return true } } } return false } // Return whether this Route can consume content with a type specified by mimeTypes (can be empty). func (r Route) matchesContentType(mimeTypes string) bool { if len(r.Consumes) == 0 { // did not specify what it can consume ; any media type (“*/*”) is assumed return true } if len(mimeTypes) == 0 { // idempotent methods with (most-likely or garanteed) empty content match missing Content-Type m := r.Method if m == "GET" || m == "HEAD" || m == "OPTIONS" || m == "DELETE" || m == "TRACE" { return true } // proceed with default mimeTypes = MIME_OCTET } parts := strings.Split(mimeTypes, ",") for _, each := range parts { var contentType string if strings.Contains(each, ";") { contentType = strings.Split(each, ";")[0] } else { contentType = each } // trim before compare contentType = strings.Trim(contentType, " ") for _, consumeableType := range r.Consumes { if consumeableType == "*/*" || consumeableType == contentType { return true } } } return false } // Extract the parameters from the request url path func (r Route) extractParameters(urlPath string) map[string]string { urlParts := tokenizePath(urlPath) pathParameters := map[string]string{} for i, key := range r.pathParts { var value string if i >= len(urlParts) { value = "" } else { value = urlParts[i] } if strings.HasPrefix(key, "{") { // path-parameter if colon := strings.Index(key, ":"); colon != -1 { // extract by regex regPart := key[colon+1 : len(key)-1] keyPart := key[1:colon] if regPart == "*" { pathParameters[keyPart] = untokenizePath(i, urlParts) break } else { pathParameters[keyPart] = value } } else { // without enclosing {} pathParameters[key[1:len(key)-1]] = value } } } return pathParameters } // Untokenize back into an URL path using the slash separator func untokenizePath(offset int, parts []string) string { var buffer bytes.Buffer for p := offset; p < len(parts); p++ { buffer.WriteString(parts[p]) // do not end if p < len(parts)-1 { buffer.WriteString("/") } } return buffer.String() } // Tokenize an URL path using the slash separator ; the result does not have empty tokens func tokenizePath(path string) []string { if "/" == path { return []string{} } return strings.Split(strings.Trim(path, "/"), "/") } // for debugging func (r Route) String() string { return r.Method + " " + r.Path } ================================================ FILE: vendor/github.com/emicklei/go-restful/route_builder.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "os" "reflect" "runtime" "strings" "github.com/emicklei/go-restful/log" ) // RouteBuilder is a helper to construct Routes. type RouteBuilder struct { rootPath string currentPath string produces []string consumes []string httpMethod string // required function RouteFunction // required filters []FilterFunction // documentation doc string notes string operation string readSample, writeSample interface{} parameters []*Parameter errorMap map[int]ResponseError } // Do evaluates each argument with the RouteBuilder itself. // This allows you to follow DRY principles without breaking the fluent programming style. // Example: // ws.Route(ws.DELETE("/{name}").To(t.deletePerson).Do(Returns200, Returns500)) // // func Returns500(b *RouteBuilder) { // b.Returns(500, "Internal Server Error", restful.ServiceError{}) // } func (b *RouteBuilder) Do(oneArgBlocks ...func(*RouteBuilder)) *RouteBuilder { for _, each := range oneArgBlocks { each(b) } return b } // To bind the route to a function. // If this route is matched with the incoming Http Request then call this function with the *Request,*Response pair. Required. func (b *RouteBuilder) To(function RouteFunction) *RouteBuilder { b.function = function return b } // Method specifies what HTTP method to match. Required. func (b *RouteBuilder) Method(method string) *RouteBuilder { b.httpMethod = method return b } // Produces specifies what MIME types can be produced ; the matched one will appear in the Content-Type Http header. func (b *RouteBuilder) Produces(mimeTypes ...string) *RouteBuilder { b.produces = mimeTypes return b } // Consumes specifies what MIME types can be consumes ; the Accept Http header must matched any of these func (b *RouteBuilder) Consumes(mimeTypes ...string) *RouteBuilder { b.consumes = mimeTypes return b } // Path specifies the relative (w.r.t WebService root path) URL path to match. Default is "/". func (b *RouteBuilder) Path(subPath string) *RouteBuilder { b.currentPath = subPath return b } // Doc tells what this route is all about. Optional. func (b *RouteBuilder) Doc(documentation string) *RouteBuilder { b.doc = documentation return b } // A verbose explanation of the operation behavior. Optional. func (b *RouteBuilder) Notes(notes string) *RouteBuilder { b.notes = notes return b } // Reads tells what resource type will be read from the request payload. Optional. // A parameter of type "body" is added ,required is set to true and the dataType is set to the qualified name of the sample's type. func (b *RouteBuilder) Reads(sample interface{}) *RouteBuilder { b.readSample = sample typeAsName := reflect.TypeOf(sample).String() bodyParameter := &Parameter{&ParameterData{Name: "body"}} bodyParameter.beBody() bodyParameter.Required(true) bodyParameter.DataType(typeAsName) b.Param(bodyParameter) return b } // ParameterNamed returns a Parameter already known to the RouteBuilder. Returns nil if not. // Use this to modify or extend information for the Parameter (through its Data()). func (b RouteBuilder) ParameterNamed(name string) (p *Parameter) { for _, each := range b.parameters { if each.Data().Name == name { return each } } return p } // Writes tells what resource type will be written as the response payload. Optional. func (b *RouteBuilder) Writes(sample interface{}) *RouteBuilder { b.writeSample = sample return b } // Param allows you to document the parameters of the Route. It adds a new Parameter (does not check for duplicates). func (b *RouteBuilder) Param(parameter *Parameter) *RouteBuilder { if b.parameters == nil { b.parameters = []*Parameter{} } b.parameters = append(b.parameters, parameter) return b } // Operation allows you to document what the acutal method/function call is of the Route. // Unless called, the operation name is derived from the RouteFunction set using To(..). func (b *RouteBuilder) Operation(name string) *RouteBuilder { b.operation = name return b } // ReturnsError is deprecated, use Returns instead. func (b *RouteBuilder) ReturnsError(code int, message string, model interface{}) *RouteBuilder { log.Print("ReturnsError is deprecated, use Returns instead.") return b.Returns(code, message, model) } // Returns allows you to document what responses (errors or regular) can be expected. // The model parameter is optional ; either pass a struct instance or use nil if not applicable. func (b *RouteBuilder) Returns(code int, message string, model interface{}) *RouteBuilder { err := ResponseError{ Code: code, Message: message, Model: model, } // lazy init because there is no NewRouteBuilder (yet) if b.errorMap == nil { b.errorMap = map[int]ResponseError{} } b.errorMap[code] = err return b } type ResponseError struct { Code int Message string Model interface{} } func (b *RouteBuilder) servicePath(path string) *RouteBuilder { b.rootPath = path return b } // Filter appends a FilterFunction to the end of filters for this Route to build. func (b *RouteBuilder) Filter(filter FilterFunction) *RouteBuilder { b.filters = append(b.filters, filter) return b } // If no specific Route path then set to rootPath // If no specific Produces then set to rootProduces // If no specific Consumes then set to rootConsumes func (b *RouteBuilder) copyDefaults(rootProduces, rootConsumes []string) { if len(b.produces) == 0 { b.produces = rootProduces } if len(b.consumes) == 0 { b.consumes = rootConsumes } } // Build creates a new Route using the specification details collected by the RouteBuilder func (b *RouteBuilder) Build() Route { pathExpr, err := newPathExpression(b.currentPath) if err != nil { log.Printf("[restful] Invalid path:%s because:%v", b.currentPath, err) os.Exit(1) } if b.function == nil { log.Printf("[restful] No function specified for route:" + b.currentPath) os.Exit(1) } operationName := b.operation if len(operationName) == 0 && b.function != nil { // extract from definition operationName = nameOfFunction(b.function) } route := Route{ Method: b.httpMethod, Path: concatPath(b.rootPath, b.currentPath), Produces: b.produces, Consumes: b.consumes, Function: b.function, Filters: b.filters, relativePath: b.currentPath, pathExpr: pathExpr, Doc: b.doc, Notes: b.notes, Operation: operationName, ParameterDocs: b.parameters, ResponseErrors: b.errorMap, ReadSample: b.readSample, WriteSample: b.writeSample} route.postBuild() return route } func concatPath(path1, path2 string) string { return strings.TrimRight(path1, "/") + "/" + strings.TrimLeft(path2, "/") } // nameOfFunction returns the short name of the function f for documentation. // It uses a runtime feature for debugging ; its value may change for later Go versions. func nameOfFunction(f interface{}) string { fun := runtime.FuncForPC(reflect.ValueOf(f).Pointer()) tokenized := strings.Split(fun.Name(), ".") last := tokenized[len(tokenized)-1] last = strings.TrimSuffix(last, ")·fm") // < Go 1.5 last = strings.TrimSuffix(last, ")-fm") // Go 1.5 last = strings.TrimSuffix(last, "·fm") // < Go 1.5 last = strings.TrimSuffix(last, "-fm") // Go 1.5 return last } ================================================ FILE: vendor/github.com/emicklei/go-restful/route_builder_test.go ================================================ package restful import ( "testing" ) func TestRouteBuilder_PathParameter(t *testing.T) { p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} p.AllowMultiple(true) p.DataType("int") p.Required(true) values := map[string]string{"a": "b"} p.AllowableValues(values) p.bePath() b := new(RouteBuilder) b.function = dummy b.Param(p) r := b.Build() if !r.ParameterDocs[0].Data().AllowMultiple { t.Error("AllowMultiple invalid") } if r.ParameterDocs[0].Data().DataType != "int" { t.Error("dataType invalid") } if !r.ParameterDocs[0].Data().Required { t.Error("required invalid") } if r.ParameterDocs[0].Data().Kind != PathParameterKind { t.Error("kind invalid") } if r.ParameterDocs[0].Data().AllowableValues["a"] != "b" { t.Error("allowableValues invalid") } if b.ParameterNamed("name") == nil { t.Error("access to parameter failed") } } func TestRouteBuilder(t *testing.T) { json := "application/json" b := new(RouteBuilder) b.To(dummy) b.Path("/routes").Method("HEAD").Consumes(json).Produces(json) r := b.Build() if r.Path != "/routes" { t.Error("path invalid") } if r.Produces[0] != json { t.Error("produces invalid") } if r.Consumes[0] != json { t.Error("consumes invalid") } if r.Operation != "dummy" { t.Error("Operation not set") } } ================================================ FILE: vendor/github.com/emicklei/go-restful/route_test.go ================================================ package restful import ( "testing" ) // accept should match produces func TestMatchesAcceptPlainTextWhenProducePlainTextAsLast(t *testing.T) { r := Route{Produces: []string{"application/json", "text/plain"}} if !r.matchesAccept("text/plain") { t.Errorf("accept should match text/plain") } } // accept should match produces func TestMatchesAcceptStar(t *testing.T) { r := Route{Produces: []string{"application/xml"}} if !r.matchesAccept("*/*") { t.Errorf("accept should match star") } } // accept should match produces func TestMatchesAcceptIE(t *testing.T) { r := Route{Produces: []string{"application/xml"}} if !r.matchesAccept("text/html, application/xhtml+xml, */*") { t.Errorf("accept should match star") } } // accept should match produces func TestMatchesAcceptXml(t *testing.T) { r := Route{Produces: []string{"application/xml"}} if r.matchesAccept("application/json") { t.Errorf("accept should not match json") } if !r.matchesAccept("application/xml") { t.Errorf("accept should match xml") } } // accept should match produces func TestMatchesAcceptAny(t *testing.T) { r := Route{Produces: []string{"*/*"}} if !r.matchesAccept("application/json") { t.Errorf("accept should match json") } if !r.matchesAccept("application/xml") { t.Errorf("accept should match xml") } } // content type should match consumes func TestMatchesContentTypeXml(t *testing.T) { r := Route{Consumes: []string{"application/xml"}} if r.matchesContentType("application/json") { t.Errorf("accept should not match json") } if !r.matchesContentType("application/xml") { t.Errorf("accept should match xml") } } // content type should match consumes func TestMatchesContentTypeCharsetInformation(t *testing.T) { r := Route{Consumes: []string{"application/json"}} if !r.matchesContentType("application/json; charset=UTF-8") { t.Errorf("matchesContentType should ignore charset information") } } func TestMatchesPath_OneParam(t *testing.T) { params := doExtractParams("/from/{source}", 2, "/from/here", t) if params["source"] != "here" { t.Errorf("parameter mismatch here") } } func TestMatchesPath_Slash(t *testing.T) { params := doExtractParams("/", 0, "/", t) if len(params) != 0 { t.Errorf("expected empty parameters") } } func TestMatchesPath_SlashNonVar(t *testing.T) { params := doExtractParams("/any", 1, "/any", t) if len(params) != 0 { t.Errorf("expected empty parameters") } } func TestMatchesPath_TwoVars(t *testing.T) { params := doExtractParams("/from/{source}/to/{destination}", 4, "/from/AMS/to/NY", t) if params["source"] != "AMS" { t.Errorf("parameter mismatch AMS") } } func TestMatchesPath_VarOnFront(t *testing.T) { params := doExtractParams("{what}/from/{source}/", 3, "who/from/SOS/", t) if params["source"] != "SOS" { t.Errorf("parameter mismatch SOS") } } func TestExtractParameters_EmptyValue(t *testing.T) { params := doExtractParams("/fixed/{var}", 2, "/fixed/", t) if params["var"] != "" { t.Errorf("parameter mismatch var") } } func TestTokenizePath(t *testing.T) { if len(tokenizePath("/")) != 0 { t.Errorf("not empty path tokens") } } func doExtractParams(routePath string, size int, urlPath string, t *testing.T) map[string]string { r := Route{Path: routePath} r.postBuild() if len(r.pathParts) != size { t.Fatalf("len not %v %v, but %v", size, r.pathParts, len(r.pathParts)) } return r.extractParameters(urlPath) } ================================================ FILE: vendor/github.com/emicklei/go-restful/router.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import "net/http" // A RouteSelector finds the best matching Route given the input HTTP Request type RouteSelector interface { // SelectRoute finds a Route given the input HTTP Request and a list of WebServices. // It returns a selected Route and its containing WebService or an error indicating // a problem. SelectRoute( webServices []*WebService, httpRequest *http.Request) (selectedService *WebService, selected *Route, err error) } ================================================ FILE: vendor/github.com/emicklei/go-restful/service_error.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import "fmt" // ServiceError is a transport object to pass information about a non-Http error occurred in a WebService while processing a request. type ServiceError struct { Code int Message string } // NewError returns a ServiceError using the code and reason func NewError(code int, message string) ServiceError { return ServiceError{Code: code, Message: message} } // Error returns a text representation of the service error func (s ServiceError) Error() string { return fmt.Sprintf("[ServiceError:%v] %v", s.Code, s.Message) } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/CHANGES.md ================================================ Change history of swagger = 2015-10-16 - add type override mechanism for swagger models (MR 254, nathanejohnson) - replace uses of wildcard in generated apidocs (issue 251) 2015-05-25 - (api break) changed the type of Properties in Model - (api break) changed the type of Models in ApiDeclaration - (api break) changed the parameter type of PostBuildDeclarationMapFunc 2015-04-09 - add ModelBuildable interface for customization of Model 2015-03-17 - preserve order of Routes per WebService in Swagger listing - fix use of $ref and type in Swagger models - add api version to listing 2014-11-14 - operation parameters are now sorted using ordering path,query,form,header,body 2014-11-12 - respect omitempty tag value for embedded structs - expose ApiVersion of WebService to Swagger ApiDeclaration 2014-05-29 - (api add) Ability to define custom http.Handler to serve swagger-ui static files 2014-05-04 - (fix) include model for array element type of response 2014-01-03 - (fix) do not add primitive type to the Api models 2013-11-27 - (fix) make Swagger work for WebServices with root ("/" or "") paths 2013-10-29 - (api add) package variable LogInfo to customize logging function 2013-10-15 - upgraded to spec version 1.2 (https://github.com/wordnik/swagger-core/wiki/1.2-transition) ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/README.md ================================================ How to use Swagger UI with go-restful = Get the Swagger UI sources (version 1.2 only) git clone https://github.com/wordnik/swagger-ui.git The project contains a "dist" folder. Its contents has all the Swagger UI files you need. The `index.html` has an `url` set to `http://petstore.swagger.wordnik.com/api/api-docs`. You need to change that to match your WebService JSON endpoint e.g. `http://localhost:8080/apidocs.json` Now, you can install the Swagger WebService for serving the Swagger specification in JSON. config := swagger.Config{ WebServices: restful.RegisteredWebServices(), ApiPath: "/apidocs.json", SwaggerPath: "/apidocs/", SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"} swagger.InstallSwaggerService(config) Documenting Structs -- Currently there are 2 ways to document your structs in the go-restful Swagger. ###### By using struct tags - Use tag "description" to annotate a struct field with a description to show in the UI - Use tag "modelDescription" to annotate the struct itself with a description to show in the UI. The tag can be added in an field of the struct and in case that there are multiple definition, they will be appended with an empty line. ###### By using the SwaggerDoc method Here is an example with an `Address` struct and the documentation for each of the fields. The `""` is a special entry for **documenting the struct itself**. type Address struct { Country string `json:"country,omitempty"` PostCode int `json:"postcode,omitempty"` } func (Address) SwaggerDoc() map[string]string { return map[string]string{ "": "Address doc", "country": "Country doc", "postcode": "PostCode doc", } } This example will generate a JSON like this { "Address": { "id": "Address", "description": "Address doc", "properties": { "country": { "type": "string", "description": "Country doc" }, "postcode": { "type": "integer", "format": "int32", "description": "PostCode doc" } } } } **Very Important Notes:** - `SwaggerDoc()` is using a **NON-Pointer** receiver (e.g. func (Address) and not func (*Address)) - The returned map should use as key the name of the field as defined in the JSON parameter (e.g. `"postcode"` and not `"PostCode"`) Notes -- - The Nickname of an Operation is automatically set by finding the name of the function. You can override it using RouteBuilder.Operation(..) - The WebServices field of swagger.Config can be used to control which service you want to expose and document ; you can have multiple configs and therefore multiple endpoints. ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/api_declaration_list.go ================================================ package swagger // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "encoding/json" ) // ApiDeclarationList maintains an ordered list of ApiDeclaration. type ApiDeclarationList struct { List []ApiDeclaration } // At returns the ApiDeclaration by its path unless absent, then ok is false func (l *ApiDeclarationList) At(path string) (a ApiDeclaration, ok bool) { for _, each := range l.List { if each.ResourcePath == path { return each, true } } return a, false } // Put adds or replaces a ApiDeclaration with this name func (l *ApiDeclarationList) Put(path string, a ApiDeclaration) { // maybe replace existing for i, each := range l.List { if each.ResourcePath == path { // replace l.List[i] = a return } } // add l.List = append(l.List, a) } // Do enumerates all the properties, each with its assigned name func (l *ApiDeclarationList) Do(block func(path string, decl ApiDeclaration)) { for _, each := range l.List { block(each.ResourcePath, each) } } // MarshalJSON writes the ModelPropertyList as if it was a map[string]ModelProperty func (l ApiDeclarationList) MarshalJSON() ([]byte, error) { var buf bytes.Buffer encoder := json.NewEncoder(&buf) buf.WriteString("{\n") for i, each := range l.List { buf.WriteString("\"") buf.WriteString(each.ResourcePath) buf.WriteString("\": ") encoder.Encode(each) if i < len(l.List)-1 { buf.WriteString(",\n") } } buf.WriteString("}") return buf.Bytes(), nil } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/config.go ================================================ package swagger import ( "net/http" "github.com/emicklei/go-restful" ) // PostBuildDeclarationMapFunc can be used to modify the api declaration map. type PostBuildDeclarationMapFunc func(apiDeclarationMap *ApiDeclarationList) type Config struct { // url where the services are available, e.g. http://localhost:8080 // if left empty then the basePath of Swagger is taken from the actual request WebServicesUrl string // path where the JSON api is avaiable , e.g. /apidocs ApiPath string // [optional] path where the swagger UI will be served, e.g. /swagger SwaggerPath string // [optional] location of folder containing Swagger HTML5 application index.html SwaggerFilePath string // api listing is constructed from this list of restful WebServices. WebServices []*restful.WebService // will serve all static content (scripts,pages,images) StaticHandler http.Handler // [optional] on default CORS (Cross-Origin-Resource-Sharing) is enabled. DisableCORS bool // Top-level API version. Is reflected in the resource listing. ApiVersion string // If set then call this handler after building the complete ApiDeclaration Map PostBuildHandler PostBuildDeclarationMapFunc // Swagger global info struct Info Info } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_builder.go ================================================ package swagger import ( "encoding/json" "reflect" "strings" ) // ModelBuildable is used for extending Structs that need more control over // how the Model appears in the Swagger api declaration. type ModelBuildable interface { PostBuildModel(m *Model) *Model } type modelBuilder struct { Models *ModelList } type documentable interface { SwaggerDoc() map[string]string } // Check if this structure has a method with signature func () SwaggerDoc() map[string]string // If it exists, retrive the documentation and overwrite all struct tag descriptions func getDocFromMethodSwaggerDoc2(model reflect.Type) map[string]string { if docable, ok := reflect.New(model).Elem().Interface().(documentable); ok { return docable.SwaggerDoc() } return make(map[string]string) } // addModelFrom creates and adds a Model to the builder and detects and calls // the post build hook for customizations func (b modelBuilder) addModelFrom(sample interface{}) { if modelOrNil := b.addModel(reflect.TypeOf(sample), ""); modelOrNil != nil { // allow customizations if buildable, ok := sample.(ModelBuildable); ok { modelOrNil = buildable.PostBuildModel(modelOrNil) b.Models.Put(modelOrNil.Id, *modelOrNil) } } } func (b modelBuilder) addModel(st reflect.Type, nameOverride string) *Model { modelName := b.keyFrom(st) if nameOverride != "" { modelName = nameOverride } // no models needed for primitive types if b.isPrimitiveType(modelName) { return nil } // see if we already have visited this model if _, ok := b.Models.At(modelName); ok { return nil } sm := Model{ Id: modelName, Required: []string{}, Properties: ModelPropertyList{}} // reference the model before further initializing (enables recursive structs) b.Models.Put(modelName, sm) // check for slice or array if st.Kind() == reflect.Slice || st.Kind() == reflect.Array { b.addModel(st.Elem(), "") return &sm } // check for structure or primitive type if st.Kind() != reflect.Struct { return &sm } fullDoc := getDocFromMethodSwaggerDoc2(st) modelDescriptions := []string{} for i := 0; i < st.NumField(); i++ { field := st.Field(i) jsonName, modelDescription, prop := b.buildProperty(field, &sm, modelName) if len(modelDescription) > 0 { modelDescriptions = append(modelDescriptions, modelDescription) } // add if not omitted if len(jsonName) != 0 { // update description if fieldDoc, ok := fullDoc[jsonName]; ok { prop.Description = fieldDoc } // update Required if b.isPropertyRequired(field) { sm.Required = append(sm.Required, jsonName) } sm.Properties.Put(jsonName, prop) } } // We always overwrite documentation if SwaggerDoc method exists // "" is special for documenting the struct itself if modelDoc, ok := fullDoc[""]; ok { sm.Description = modelDoc } else if len(modelDescriptions) != 0 { sm.Description = strings.Join(modelDescriptions, "\n") } // update model builder with completed model b.Models.Put(modelName, sm) return &sm } func (b modelBuilder) isPropertyRequired(field reflect.StructField) bool { required := true if jsonTag := field.Tag.Get("json"); jsonTag != "" { s := strings.Split(jsonTag, ",") if len(s) > 1 && s[1] == "omitempty" { return false } } return required } func (b modelBuilder) buildProperty(field reflect.StructField, model *Model, modelName string) (jsonName, modelDescription string, prop ModelProperty) { jsonName = b.jsonNameOfField(field) if len(jsonName) == 0 { // empty name signals skip property return "", "", prop } if tag := field.Tag.Get("modelDescription"); tag != "" { modelDescription = tag } prop.setPropertyMetadata(field) if prop.Type != nil { return jsonName, modelDescription, prop } fieldType := field.Type // check if type is doing its own marshalling marshalerType := reflect.TypeOf((*json.Marshaler)(nil)).Elem() if fieldType.Implements(marshalerType) { var pType = "string" if prop.Type == nil { prop.Type = &pType } if prop.Format == "" { prop.Format = b.jsonSchemaFormat(fieldType.String()) } return jsonName, modelDescription, prop } // check if annotation says it is a string if jsonTag := field.Tag.Get("json"); jsonTag != "" { s := strings.Split(jsonTag, ",") if len(s) > 1 && s[1] == "string" { stringt := "string" prop.Type = &stringt return jsonName, modelDescription, prop } } fieldKind := fieldType.Kind() switch { case fieldKind == reflect.Struct: jsonName, prop := b.buildStructTypeProperty(field, jsonName, model) return jsonName, modelDescription, prop case fieldKind == reflect.Slice || fieldKind == reflect.Array: jsonName, prop := b.buildArrayTypeProperty(field, jsonName, modelName) return jsonName, modelDescription, prop case fieldKind == reflect.Ptr: jsonName, prop := b.buildPointerTypeProperty(field, jsonName, modelName) return jsonName, modelDescription, prop case fieldKind == reflect.String: stringt := "string" prop.Type = &stringt return jsonName, modelDescription, prop case fieldKind == reflect.Map: // if it's a map, it's unstructured, and swagger 1.2 can't handle it anyt := "any" prop.Type = &anyt return jsonName, modelDescription, prop } if b.isPrimitiveType(fieldType.String()) { mapped := b.jsonSchemaType(fieldType.String()) prop.Type = &mapped prop.Format = b.jsonSchemaFormat(fieldType.String()) return jsonName, modelDescription, prop } modelType := fieldType.String() prop.Ref = &modelType if fieldType.Name() == "" { // override type of anonymous structs nestedTypeName := modelName + "." + jsonName prop.Ref = &nestedTypeName b.addModel(fieldType, nestedTypeName) } return jsonName, modelDescription, prop } func hasNamedJSONTag(field reflect.StructField) bool { parts := strings.Split(field.Tag.Get("json"), ",") if len(parts) == 0 { return false } for _, s := range parts[1:] { if s == "inline" { return false } } return len(parts[0]) > 0 } func (b modelBuilder) buildStructTypeProperty(field reflect.StructField, jsonName string, model *Model) (nameJson string, prop ModelProperty) { prop.setPropertyMetadata(field) // Check for type override in tag if prop.Type != nil { return jsonName, prop } fieldType := field.Type // check for anonymous if len(fieldType.Name()) == 0 { // anonymous anonType := model.Id + "." + jsonName b.addModel(fieldType, anonType) prop.Ref = &anonType return jsonName, prop } if field.Name == fieldType.Name() && field.Anonymous && !hasNamedJSONTag(field) { // embedded struct sub := modelBuilder{new(ModelList)} sub.addModel(fieldType, "") subKey := sub.keyFrom(fieldType) // merge properties from sub subModel, _ := sub.Models.At(subKey) subModel.Properties.Do(func(k string, v ModelProperty) { model.Properties.Put(k, v) // if subModel says this property is required then include it required := false for _, each := range subModel.Required { if k == each { required = true break } } if required { model.Required = append(model.Required, k) } }) // add all new referenced models sub.Models.Do(func(key string, sub Model) { if key != subKey { if _, ok := b.Models.At(key); !ok { b.Models.Put(key, sub) } } }) // empty name signals skip property return "", prop } // simple struct b.addModel(fieldType, "") var pType = fieldType.String() prop.Ref = &pType return jsonName, prop } func (b modelBuilder) buildArrayTypeProperty(field reflect.StructField, jsonName, modelName string) (nameJson string, prop ModelProperty) { // check for type override in tags prop.setPropertyMetadata(field) if prop.Type != nil { return jsonName, prop } fieldType := field.Type var pType = "array" prop.Type = &pType elemTypeName := b.getElementTypeName(modelName, jsonName, fieldType.Elem()) prop.Items = new(Item) if b.isPrimitiveType(elemTypeName) { mapped := b.jsonSchemaType(elemTypeName) prop.Items.Type = &mapped } else { prop.Items.Ref = &elemTypeName } // add|overwrite model for element type if fieldType.Elem().Kind() == reflect.Ptr { fieldType = fieldType.Elem() } b.addModel(fieldType.Elem(), elemTypeName) return jsonName, prop } func (b modelBuilder) buildPointerTypeProperty(field reflect.StructField, jsonName, modelName string) (nameJson string, prop ModelProperty) { prop.setPropertyMetadata(field) // Check for type override in tags if prop.Type != nil { return jsonName, prop } fieldType := field.Type // override type of pointer to list-likes if fieldType.Elem().Kind() == reflect.Slice || fieldType.Elem().Kind() == reflect.Array { var pType = "array" prop.Type = &pType elemName := b.getElementTypeName(modelName, jsonName, fieldType.Elem().Elem()) prop.Items = &Item{Ref: &elemName} // add|overwrite model for element type b.addModel(fieldType.Elem().Elem(), elemName) } else { // non-array, pointer type var pType = b.jsonSchemaType(fieldType.String()[1:]) // no star, include pkg path if b.isPrimitiveType(fieldType.String()[1:]) { prop.Type = &pType prop.Format = b.jsonSchemaFormat(fieldType.String()[1:]) return jsonName, prop } prop.Ref = &pType elemName := "" if fieldType.Elem().Name() == "" { elemName = modelName + "." + jsonName prop.Ref = &elemName } b.addModel(fieldType.Elem(), elemName) } return jsonName, prop } func (b modelBuilder) getElementTypeName(modelName, jsonName string, t reflect.Type) string { if t.Kind() == reflect.Ptr { return t.String()[1:] } if t.Name() == "" { return modelName + "." + jsonName } if b.isPrimitiveType(t.Name()) { return b.jsonSchemaType(t.Name()) } return b.keyFrom(t) } func (b modelBuilder) keyFrom(st reflect.Type) string { key := st.String() if len(st.Name()) == 0 { // unnamed type // Swagger UI has special meaning for [ key = strings.Replace(key, "[]", "||", -1) } return key } // see also https://golang.org/ref/spec#Numeric_types func (b modelBuilder) isPrimitiveType(modelName string) bool { return strings.Contains("uint uint8 uint16 uint32 uint64 int int8 int16 int32 int64 float32 float64 bool string byte rune time.Time", modelName) } // jsonNameOfField returns the name of the field as it should appear in JSON format // An empty string indicates that this field is not part of the JSON representation func (b modelBuilder) jsonNameOfField(field reflect.StructField) string { if jsonTag := field.Tag.Get("json"); jsonTag != "" { s := strings.Split(jsonTag, ",") if s[0] == "-" { // empty name signals skip property return "" } else if s[0] != "" { return s[0] } } return field.Name } // see also http://json-schema.org/latest/json-schema-core.html#anchor8 func (b modelBuilder) jsonSchemaType(modelName string) string { schemaMap := map[string]string{ "uint": "integer", "uint8": "integer", "uint16": "integer", "uint32": "integer", "uint64": "integer", "int": "integer", "int8": "integer", "int16": "integer", "int32": "integer", "int64": "integer", "byte": "integer", "float64": "number", "float32": "number", "bool": "boolean", "time.Time": "string", } mapped, ok := schemaMap[modelName] if !ok { return modelName // use as is (custom or struct) } return mapped } func (b modelBuilder) jsonSchemaFormat(modelName string) string { schemaMap := map[string]string{ "int": "int32", "int32": "int32", "int64": "int64", "byte": "byte", "uint": "integer", "uint8": "byte", "float64": "double", "float32": "float", "time.Time": "date-time", "*time.Time": "date-time", } mapped, ok := schemaMap[modelName] if !ok { return "" // no format } return mapped } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_builder_test.go ================================================ package swagger import ( "net" "testing" "time" ) type YesNo bool func (y YesNo) MarshalJSON() ([]byte, error) { if y { return []byte("yes"), nil } return []byte("no"), nil } // clear && go test -v -test.run TestRef_Issue190 ...swagger func TestRef_Issue190(t *testing.T) { type User struct { items []string } testJsonFromStruct(t, User{}, `{ "swagger.User": { "id": "swagger.User", "required": [ "items" ], "properties": { "items": { "type": "array", "items": { "type": "string" } } } } }`) } // clear && go test -v -test.run TestCustomMarshaller_Issue96 ...swagger func TestCustomMarshaller_Issue96(t *testing.T) { type Vote struct { What YesNo } testJsonFromStruct(t, Vote{}, `{ "swagger.Vote": { "id": "swagger.Vote", "required": [ "What" ], "properties": { "What": { "type": "string" } } } }`) } // clear && go test -v -test.run TestPrimitiveTypes ...swagger func TestPrimitiveTypes(t *testing.T) { type Prims struct { f float64 t time.Time } testJsonFromStruct(t, Prims{}, `{ "swagger.Prims": { "id": "swagger.Prims", "required": [ "f", "t" ], "properties": { "f": { "type": "number", "format": "double" }, "t": { "type": "string", "format": "date-time" } } } }`) } // clear && go test -v -test.run TestPrimitivePtrTypes ...swagger func TestPrimitivePtrTypes(t *testing.T) { type Prims struct { f *float64 t *time.Time b *bool s *string i *int } testJsonFromStruct(t, Prims{}, `{ "swagger.Prims": { "id": "swagger.Prims", "required": [ "f", "t", "b", "s", "i" ], "properties": { "b": { "type": "boolean" }, "f": { "type": "number", "format": "double" }, "i": { "type": "integer", "format": "int32" }, "s": { "type": "string" }, "t": { "type": "string", "format": "date-time" } } } }`) } // clear && go test -v -test.run TestS1 ...swagger func TestS1(t *testing.T) { type S1 struct { Id string } testJsonFromStruct(t, S1{}, `{ "swagger.S1": { "id": "swagger.S1", "required": [ "Id" ], "properties": { "Id": { "type": "string" } } } }`) } // clear && go test -v -test.run TestS2 ...swagger func TestS2(t *testing.T) { type S2 struct { Ids []string } testJsonFromStruct(t, S2{}, `{ "swagger.S2": { "id": "swagger.S2", "required": [ "Ids" ], "properties": { "Ids": { "type": "array", "items": { "type": "string" } } } } }`) } // clear && go test -v -test.run TestS3 ...swagger func TestS3(t *testing.T) { type NestedS3 struct { Id string } type S3 struct { Nested NestedS3 } testJsonFromStruct(t, S3{}, `{ "swagger.NestedS3": { "id": "swagger.NestedS3", "required": [ "Id" ], "properties": { "Id": { "type": "string" } } }, "swagger.S3": { "id": "swagger.S3", "required": [ "Nested" ], "properties": { "Nested": { "$ref": "swagger.NestedS3" } } } }`) } type sample struct { id string `swagger:"required"` // TODO items []item rootItem item `json:"root" description:"root desc"` } type item struct { itemName string `json:"name"` } // clear && go test -v -test.run TestSampleToModelAsJson ...swagger func TestSampleToModelAsJson(t *testing.T) { testJsonFromStruct(t, sample{items: []item{}}, `{ "swagger.item": { "id": "swagger.item", "required": [ "name" ], "properties": { "name": { "type": "string" } } }, "swagger.sample": { "id": "swagger.sample", "required": [ "id", "items", "root" ], "properties": { "id": { "type": "string" }, "items": { "type": "array", "items": { "$ref": "swagger.item" } }, "root": { "$ref": "swagger.item", "description": "root desc" } } } }`) } func TestJsonTags(t *testing.T) { type X struct { A string B string `json:"-"` C int `json:",string"` D int `json:","` } expected := `{ "swagger.X": { "id": "swagger.X", "required": [ "A", "C", "D" ], "properties": { "A": { "type": "string" }, "C": { "type": "string" }, "D": { "type": "integer", "format": "int32" } } } }` testJsonFromStruct(t, X{}, expected) } func TestJsonTagOmitempty(t *testing.T) { type X struct { A int `json:",omitempty"` B int `json:"C,omitempty"` } expected := `{ "swagger.X": { "id": "swagger.X", "properties": { "A": { "type": "integer", "format": "int32" }, "C": { "type": "integer", "format": "int32" } } } }` testJsonFromStruct(t, X{}, expected) } func TestJsonTagName(t *testing.T) { type X struct { A string `json:"B"` } expected := `{ "swagger.X": { "id": "swagger.X", "required": [ "B" ], "properties": { "B": { "type": "string" } } } }` testJsonFromStruct(t, X{}, expected) } func TestAnonymousStruct(t *testing.T) { type X struct { A struct { B int } } expected := `{ "swagger.X": { "id": "swagger.X", "required": [ "A" ], "properties": { "A": { "$ref": "swagger.X.A" } } }, "swagger.X.A": { "id": "swagger.X.A", "required": [ "B" ], "properties": { "B": { "type": "integer", "format": "int32" } } } }` testJsonFromStruct(t, X{}, expected) } func TestAnonymousPtrStruct(t *testing.T) { type X struct { A *struct { B int } } expected := `{ "swagger.X": { "id": "swagger.X", "required": [ "A" ], "properties": { "A": { "$ref": "swagger.X.A" } } }, "swagger.X.A": { "id": "swagger.X.A", "required": [ "B" ], "properties": { "B": { "type": "integer", "format": "int32" } } } }` testJsonFromStruct(t, X{}, expected) } func TestAnonymousArrayStruct(t *testing.T) { type X struct { A []struct { B int } } expected := `{ "swagger.X": { "id": "swagger.X", "required": [ "A" ], "properties": { "A": { "type": "array", "items": { "$ref": "swagger.X.A" } } } }, "swagger.X.A": { "id": "swagger.X.A", "required": [ "B" ], "properties": { "B": { "type": "integer", "format": "int32" } } } }` testJsonFromStruct(t, X{}, expected) } func TestAnonymousPtrArrayStruct(t *testing.T) { type X struct { A *[]struct { B int } } expected := `{ "swagger.X": { "id": "swagger.X", "required": [ "A" ], "properties": { "A": { "type": "array", "items": { "$ref": "swagger.X.A" } } } }, "swagger.X.A": { "id": "swagger.X.A", "required": [ "B" ], "properties": { "B": { "type": "integer", "format": "int32" } } } }` testJsonFromStruct(t, X{}, expected) } // go test -v -test.run TestEmbeddedStruct_Issue98 ...swagger func TestEmbeddedStruct_Issue98(t *testing.T) { type Y struct { A int } type X struct { Y } testJsonFromStruct(t, X{}, `{ "swagger.X": { "id": "swagger.X", "required": [ "A" ], "properties": { "A": { "type": "integer", "format": "int32" } } } }`) } type Dataset struct { Names []string } // clear && go test -v -test.run TestIssue85 ...swagger func TestIssue85(t *testing.T) { anon := struct{ Datasets []Dataset }{} testJsonFromStruct(t, anon, `{ "struct { Datasets ||swagger.Dataset }": { "id": "struct { Datasets ||swagger.Dataset }", "required": [ "Datasets" ], "properties": { "Datasets": { "type": "array", "items": { "$ref": "swagger.Dataset" } } } }, "swagger.Dataset": { "id": "swagger.Dataset", "required": [ "Names" ], "properties": { "Names": { "type": "array", "items": { "type": "string" } } } } }`) } type File struct { History []File HistoryPtrs []*File } // go test -v -test.run TestRecursiveStructure ...swagger func TestRecursiveStructure(t *testing.T) { testJsonFromStruct(t, File{}, `{ "swagger.File": { "id": "swagger.File", "required": [ "History", "HistoryPtrs" ], "properties": { "History": { "type": "array", "items": { "$ref": "swagger.File" } }, "HistoryPtrs": { "type": "array", "items": { "$ref": "swagger.File" } } } } }`) } type A1 struct { B struct { Id int Comment string `json:"comment,omitempty"` } } // go test -v -test.run TestEmbeddedStructA1 ...swagger func TestEmbeddedStructA1(t *testing.T) { testJsonFromStruct(t, A1{}, `{ "swagger.A1": { "id": "swagger.A1", "required": [ "B" ], "properties": { "B": { "$ref": "swagger.A1.B" } } }, "swagger.A1.B": { "id": "swagger.A1.B", "required": [ "Id" ], "properties": { "Id": { "type": "integer", "format": "int32" }, "comment": { "type": "string" } } } }`) } type A2 struct { C } type C struct { Id int `json:"B"` Comment string `json:"comment,omitempty"` Secure bool `json:"secure"` } // go test -v -test.run TestEmbeddedStructA2 ...swagger func TestEmbeddedStructA2(t *testing.T) { testJsonFromStruct(t, A2{}, `{ "swagger.A2": { "id": "swagger.A2", "required": [ "B", "secure" ], "properties": { "B": { "type": "integer", "format": "int32" }, "comment": { "type": "string" }, "secure": { "type": "boolean" } } } }`) } type A3 struct { B D } type D struct { Id int } // clear && go test -v -test.run TestStructA3 ...swagger func TestStructA3(t *testing.T) { testJsonFromStruct(t, A3{}, `{ "swagger.A3": { "id": "swagger.A3", "required": [ "B" ], "properties": { "B": { "$ref": "swagger.D" } } }, "swagger.D": { "id": "swagger.D", "required": [ "Id" ], "properties": { "Id": { "type": "integer", "format": "int32" } } } }`) } type A4 struct { D "json:,inline" } // clear && go test -v -test.run TestStructA4 ...swagger func TestEmbeddedStructA4(t *testing.T) { testJsonFromStruct(t, A4{}, `{ "swagger.A4": { "id": "swagger.A4", "required": [ "Id" ], "properties": { "Id": { "type": "integer", "format": "int32" } } } }`) } type A5 struct { D `json:"d"` } // clear && go test -v -test.run TestStructA5 ...swagger func TestEmbeddedStructA5(t *testing.T) { testJsonFromStruct(t, A5{}, `{ "swagger.A5": { "id": "swagger.A5", "required": [ "d" ], "properties": { "d": { "$ref": "swagger.D" } } }, "swagger.D": { "id": "swagger.D", "required": [ "Id" ], "properties": { "Id": { "type": "integer", "format": "int32" } } } }`) } type D2 struct { id int D []D } type A6 struct { D2 "json:,inline" } // clear && go test -v -test.run TestStructA4 ...swagger func TestEmbeddedStructA6(t *testing.T) { testJsonFromStruct(t, A6{}, `{ "swagger.A6": { "id": "swagger.A6", "required": [ "id", "D" ], "properties": { "D": { "type": "array", "items": { "$ref": "swagger.D" } }, "id": { "type": "integer", "format": "int32" } } }, "swagger.D": { "id": "swagger.D", "required": [ "Id" ], "properties": { "Id": { "type": "integer", "format": "int32" } } } }`) } type ObjectId []byte type Region struct { Id ObjectId `bson:"_id" json:"id"` Name string `bson:"name" json:"name"` Type string `bson:"type" json:"type"` } // clear && go test -v -test.run TestRegion_Issue113 ...swagger func TestRegion_Issue113(t *testing.T) { testJsonFromStruct(t, []Region{}, `{ "integer": { "id": "integer", "properties": {} }, "swagger.Region": { "id": "swagger.Region", "required": [ "id", "name", "type" ], "properties": { "id": { "type": "array", "items": { "$ref": "integer" } }, "name": { "type": "string" }, "type": { "type": "string" } } }, "||swagger.Region": { "id": "||swagger.Region", "properties": {} } }`) } // clear && go test -v -test.run TestIssue158 ...swagger func TestIssue158(t *testing.T) { type Address struct { Country string `json:"country,omitempty"` } type Customer struct { Name string `json:"name"` Address Address `json:"address"` } expected := `{ "swagger.Address": { "id": "swagger.Address", "properties": { "country": { "type": "string" } } }, "swagger.Customer": { "id": "swagger.Customer", "required": [ "name", "address" ], "properties": { "address": { "$ref": "swagger.Address" }, "name": { "type": "string" } } } }` testJsonFromStruct(t, Customer{}, expected) } func TestSlices(t *testing.T) { type Address struct { Country string `json:"country,omitempty"` } expected := `{ "swagger.Address": { "id": "swagger.Address", "properties": { "country": { "type": "string" } } }, "swagger.Customer": { "id": "swagger.Customer", "required": [ "name", "addresses" ], "properties": { "addresses": { "type": "array", "items": { "$ref": "swagger.Address" } }, "name": { "type": "string" } } } }` // both slices (with pointer value and with type value) should have equal swagger representation { type Customer struct { Name string `json:"name"` Addresses []Address `json:"addresses"` } testJsonFromStruct(t, Customer{}, expected) } { type Customer struct { Name string `json:"name"` Addresses []*Address `json:"addresses"` } testJsonFromStruct(t, Customer{}, expected) } } type Name struct { Value string } func (n Name) PostBuildModel(m *Model) *Model { m.Description = "titles must be upcase" return m } type TOC struct { Titles []Name } type Discography struct { Title Name TOC } // clear && go test -v -test.run TestEmbeddedStructPull204 ...swagger func TestEmbeddedStructPull204(t *testing.T) { b := Discography{} testJsonFromStruct(t, b, ` { "swagger.Discography": { "id": "swagger.Discography", "required": [ "Title", "Titles" ], "properties": { "Title": { "$ref": "swagger.Name" }, "Titles": { "type": "array", "items": { "$ref": "swagger.Name" } } } }, "swagger.Name": { "id": "swagger.Name", "required": [ "Value" ], "properties": { "Value": { "type": "string" } } } } `) } type AddressWithMethod struct { Country string `json:"country,omitempty"` PostCode int `json:"postcode,omitempty"` } func (AddressWithMethod) SwaggerDoc() map[string]string { return map[string]string{ "": "Address doc", "country": "Country doc", "postcode": "PostCode doc", } } func TestDocInMethodSwaggerDoc(t *testing.T) { expected := `{ "swagger.AddressWithMethod": { "id": "swagger.AddressWithMethod", "description": "Address doc", "properties": { "country": { "type": "string", "description": "Country doc" }, "postcode": { "type": "integer", "format": "int32", "description": "PostCode doc" } } } }` testJsonFromStruct(t, AddressWithMethod{}, expected) } type RefDesc struct { f1 *int64 `description:"desc"` } func TestPtrDescription(t *testing.T) { b := RefDesc{} expected := `{ "swagger.RefDesc": { "id": "swagger.RefDesc", "required": [ "f1" ], "properties": { "f1": { "type": "integer", "format": "int64", "description": "desc" } } } }` testJsonFromStruct(t, b, expected) } type A struct { B `json:",inline"` C1 `json:"metadata,omitempty"` } type B struct { SB string } type C1 struct { SC string } func (A) SwaggerDoc() map[string]string { return map[string]string{ "": "A struct", "B": "B field", // We should not get anything from this "metadata": "C1 field", } } func (B) SwaggerDoc() map[string]string { return map[string]string{ "": "B struct", "SB": "SB field", } } func (C1) SwaggerDoc() map[string]string { return map[string]string{ "": "C1 struct", "SC": "SC field", } } func TestNestedStructDescription(t *testing.T) { expected := ` { "swagger.A": { "id": "swagger.A", "description": "A struct", "required": [ "SB" ], "properties": { "SB": { "type": "string", "description": "SB field" }, "metadata": { "$ref": "swagger.C1", "description": "C1 field" } } }, "swagger.C1": { "id": "swagger.C1", "description": "C1 struct", "required": [ "SC" ], "properties": { "SC": { "type": "string", "description": "SC field" } } } } ` testJsonFromStruct(t, A{}, expected) } // This tests a primitive with type overrides in the struct tags type FakeInt int type E struct { Id FakeInt `type:"integer"` IP net.IP `type:"string"` } func TestOverridenTypeTagE1(t *testing.T) { expected := ` { "swagger.E": { "id": "swagger.E", "required": [ "Id", "IP" ], "properties": { "Id": { "type": "integer" }, "IP": { "type": "string" } } } } ` testJsonFromStruct(t, E{}, expected) } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_list.go ================================================ package swagger // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "encoding/json" ) // NamedModel associates a name with a Model (not using its Id) type NamedModel struct { Name string Model Model } // ModelList encapsulates a list of NamedModel (association) type ModelList struct { List []NamedModel } // Put adds or replaces a Model by its name func (l *ModelList) Put(name string, model Model) { for i, each := range l.List { if each.Name == name { // replace l.List[i] = NamedModel{name, model} return } } // add l.List = append(l.List, NamedModel{name, model}) } // At returns a Model by its name, ok is false if absent func (l *ModelList) At(name string) (m Model, ok bool) { for _, each := range l.List { if each.Name == name { return each.Model, true } } return m, false } // Do enumerates all the models, each with its assigned name func (l *ModelList) Do(block func(name string, value Model)) { for _, each := range l.List { block(each.Name, each.Model) } } // MarshalJSON writes the ModelList as if it was a map[string]Model func (l ModelList) MarshalJSON() ([]byte, error) { var buf bytes.Buffer encoder := json.NewEncoder(&buf) buf.WriteString("{\n") for i, each := range l.List { buf.WriteString("\"") buf.WriteString(each.Name) buf.WriteString("\": ") encoder.Encode(each.Model) if i < len(l.List)-1 { buf.WriteString(",\n") } } buf.WriteString("}") return buf.Bytes(), nil } // UnmarshalJSON reads back a ModelList. This is an expensive operation. func (l *ModelList) UnmarshalJSON(data []byte) error { raw := map[string]interface{}{} json.NewDecoder(bytes.NewReader(data)).Decode(&raw) for k, v := range raw { // produces JSON bytes for each value data, err := json.Marshal(v) if err != nil { return err } var m Model json.NewDecoder(bytes.NewReader(data)).Decode(&m) l.Put(k, m) } return nil } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_list_test.go ================================================ package swagger import ( "encoding/json" "testing" ) func TestModelList(t *testing.T) { m := Model{} m.Id = "m" l := ModelList{} l.Put("m", m) k, ok := l.At("m") if !ok { t.Error("want model back") } if got, want := k.Id, "m"; got != want { t.Errorf("got %v want %v", got, want) } } func TestModelList_Marshal(t *testing.T) { l := ModelList{} m := Model{Id: "myid"} l.Put("myid", m) data, err := json.Marshal(l) if err != nil { t.Error(err) } if got, want := string(data), `{"myid":{"id":"myid","properties":{}}}`; got != want { t.Errorf("got %v want %v", got, want) } } func TestModelList_Unmarshal(t *testing.T) { data := `{"myid":{"id":"myid","properties":{}}}` l := ModelList{} if err := json.Unmarshal([]byte(data), &l); err != nil { t.Error(err) } m, ok := l.At("myid") if !ok { t.Error("expected myid") } if got, want := m.Id, "myid"; got != want { t.Errorf("got %v want %v", got, want) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_property_ext.go ================================================ package swagger import ( "reflect" "strings" ) func (prop *ModelProperty) setDescription(field reflect.StructField) { if tag := field.Tag.Get("description"); tag != "" { prop.Description = tag } } func (prop *ModelProperty) setDefaultValue(field reflect.StructField) { if tag := field.Tag.Get("default"); tag != "" { prop.DefaultValue = Special(tag) } } func (prop *ModelProperty) setEnumValues(field reflect.StructField) { // We use | to separate the enum values. This value is chosen // since its unlikely to be useful in actual enumeration values. if tag := field.Tag.Get("enum"); tag != "" { prop.Enum = strings.Split(tag, "|") } } func (prop *ModelProperty) setMaximum(field reflect.StructField) { if tag := field.Tag.Get("maximum"); tag != "" { prop.Maximum = tag } } func (prop *ModelProperty) setType(field reflect.StructField) { if tag := field.Tag.Get("type"); tag != "" { prop.Type = &tag } } func (prop *ModelProperty) setMinimum(field reflect.StructField) { if tag := field.Tag.Get("minimum"); tag != "" { prop.Minimum = tag } } func (prop *ModelProperty) setUniqueItems(field reflect.StructField) { tag := field.Tag.Get("unique") switch tag { case "true": v := true prop.UniqueItems = &v case "false": v := false prop.UniqueItems = &v } } func (prop *ModelProperty) setPropertyMetadata(field reflect.StructField) { prop.setDescription(field) prop.setEnumValues(field) prop.setMinimum(field) prop.setMaximum(field) prop.setUniqueItems(field) prop.setDefaultValue(field) prop.setType(field) } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_property_ext_test.go ================================================ package swagger import ( "net" "testing" ) // clear && go test -v -test.run TestThatExtraTagsAreReadIntoModel ...swagger func TestThatExtraTagsAreReadIntoModel(t *testing.T) { type fakeint int type Anything struct { Name string `description:"name" modelDescription:"a test"` Size int `minimum:"0" maximum:"10"` Stati string `enum:"off|on" default:"on" modelDescription:"more description"` ID string `unique:"true"` FakeInt fakeint `type:"integer"` IP net.IP `type:"string"` Password string } m := modelsFromStruct(Anything{}) props, _ := m.At("swagger.Anything") p1, _ := props.Properties.At("Name") if got, want := p1.Description, "name"; got != want { t.Errorf("got %v want %v", got, want) } p2, _ := props.Properties.At("Size") if got, want := p2.Minimum, "0"; got != want { t.Errorf("got %v want %v", got, want) } if got, want := p2.Maximum, "10"; got != want { t.Errorf("got %v want %v", got, want) } p3, _ := props.Properties.At("Stati") if got, want := p3.Enum[0], "off"; got != want { t.Errorf("got %v want %v", got, want) } if got, want := p3.Enum[1], "on"; got != want { t.Errorf("got %v want %v", got, want) } p4, _ := props.Properties.At("ID") if got, want := *p4.UniqueItems, true; got != want { t.Errorf("got %v want %v", got, want) } p5, _ := props.Properties.At("Password") if got, want := *p5.Type, "string"; got != want { t.Errorf("got %v want %v", got, want) } p6, _ := props.Properties.At("FakeInt") if got, want := *p6.Type, "integer"; got != want { t.Errorf("got %v want %v", got, want) } p7, _ := props.Properties.At("IP") if got, want := *p7.Type, "string"; got != want { t.Errorf("got %v want %v", got, want) } if got, want := props.Description, "a test\nmore description"; got != want { t.Errorf("got %v want %v", got, want) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_property_list.go ================================================ package swagger // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "bytes" "encoding/json" ) // NamedModelProperty associates a name to a ModelProperty type NamedModelProperty struct { Name string Property ModelProperty } // ModelPropertyList encapsulates a list of NamedModelProperty (association) type ModelPropertyList struct { List []NamedModelProperty } // At returns the ModelPropety by its name unless absent, then ok is false func (l *ModelPropertyList) At(name string) (p ModelProperty, ok bool) { for _, each := range l.List { if each.Name == name { return each.Property, true } } return p, false } // Put adds or replaces a ModelProperty with this name func (l *ModelPropertyList) Put(name string, prop ModelProperty) { // maybe replace existing for i, each := range l.List { if each.Name == name { // replace l.List[i] = NamedModelProperty{Name: name, Property: prop} return } } // add l.List = append(l.List, NamedModelProperty{Name: name, Property: prop}) } // Do enumerates all the properties, each with its assigned name func (l *ModelPropertyList) Do(block func(name string, value ModelProperty)) { for _, each := range l.List { block(each.Name, each.Property) } } // MarshalJSON writes the ModelPropertyList as if it was a map[string]ModelProperty func (l ModelPropertyList) MarshalJSON() ([]byte, error) { var buf bytes.Buffer encoder := json.NewEncoder(&buf) buf.WriteString("{\n") for i, each := range l.List { buf.WriteString("\"") buf.WriteString(each.Name) buf.WriteString("\": ") encoder.Encode(each.Property) if i < len(l.List)-1 { buf.WriteString(",\n") } } buf.WriteString("}") return buf.Bytes(), nil } // UnmarshalJSON reads back a ModelPropertyList. This is an expensive operation. func (l *ModelPropertyList) UnmarshalJSON(data []byte) error { raw := map[string]interface{}{} json.NewDecoder(bytes.NewReader(data)).Decode(&raw) for k, v := range raw { // produces JSON bytes for each value data, err := json.Marshal(v) if err != nil { return err } var m ModelProperty json.NewDecoder(bytes.NewReader(data)).Decode(&m) l.Put(k, m) } return nil } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/model_property_list_test.go ================================================ package swagger import ( "encoding/json" "testing" ) func TestModelPropertyList(t *testing.T) { l := ModelPropertyList{} p := ModelProperty{Description: "d"} l.Put("p", p) q, ok := l.At("p") if !ok { t.Error("expected p") } if got, want := q.Description, "d"; got != want { t.Errorf("got %v want %v", got, want) } } func TestModelPropertyList_Marshal(t *testing.T) { l := ModelPropertyList{} p := ModelProperty{Description: "d"} l.Put("p", p) data, err := json.Marshal(l) if err != nil { t.Error(err) } if got, want := string(data), `{"p":{"description":"d"}}`; got != want { t.Errorf("got %v want %v", got, want) } } func TestModelPropertyList_Unmarshal(t *testing.T) { data := `{"p":{"description":"d"}}` l := ModelPropertyList{} if err := json.Unmarshal([]byte(data), &l); err != nil { t.Error(err) } m, ok := l.At("p") if !ok { t.Error("expected p") } if got, want := m.Description, "d"; got != want { t.Errorf("got %v want %v", got, want) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/ordered_route_map.go ================================================ package swagger // Copyright 2015 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import "github.com/emicklei/go-restful" type orderedRouteMap struct { elements map[string][]restful.Route keys []string } func newOrderedRouteMap() *orderedRouteMap { return &orderedRouteMap{ elements: map[string][]restful.Route{}, keys: []string{}, } } func (o *orderedRouteMap) Add(key string, route restful.Route) { routes, ok := o.elements[key] if ok { routes = append(routes, route) o.elements[key] = routes return } o.elements[key] = []restful.Route{route} o.keys = append(o.keys, key) } func (o *orderedRouteMap) Do(block func(key string, routes []restful.Route)) { for _, k := range o.keys { block(k, o.elements[k]) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/ordered_route_map_test.go ================================================ package swagger import ( "testing" "github.com/emicklei/go-restful" ) // go test -v -test.run TestOrderedRouteMap ...swagger func TestOrderedRouteMap(t *testing.T) { m := newOrderedRouteMap() r1 := restful.Route{Path: "/r1"} r2 := restful.Route{Path: "/r2"} m.Add("a", r1) m.Add("b", r2) m.Add("b", r1) m.Add("d", r2) m.Add("c", r2) order := "" m.Do(func(k string, routes []restful.Route) { order += k if len(routes) == 0 { t.Fail() } }) if order != "abdc" { t.Fail() } } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/postbuild_model_test.go ================================================ package swagger import "testing" type Boat struct { Length int `json:"-"` // on default, this makes the fields not required Weight int `json:"-"` } // PostBuildModel is from swagger.ModelBuildable func (b Boat) PostBuildModel(m *Model) *Model { // override required m.Required = []string{"Length", "Weight"} // add model property (just to test is can be added; is this a real usecase?) extraType := "string" m.Properties.Put("extra", ModelProperty{ Description: "extra description", DataTypeFields: DataTypeFields{ Type: &extraType, }, }) return m } func TestCustomPostModelBuilde(t *testing.T) { testJsonFromStruct(t, Boat{}, `{ "swagger.Boat": { "id": "swagger.Boat", "required": [ "Length", "Weight" ], "properties": { "extra": { "type": "string", "description": "extra description" } } } }`) } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/swagger.go ================================================ // Package swagger implements the structures of the Swagger // https://github.com/wordnik/swagger-spec/blob/master/versions/1.2.md package swagger const swaggerVersion = "1.2" // 4.3.3 Data Type Fields type DataTypeFields struct { Type *string `json:"type,omitempty"` // if Ref not used Ref *string `json:"$ref,omitempty"` // if Type not used Format string `json:"format,omitempty"` DefaultValue Special `json:"defaultValue,omitempty"` Enum []string `json:"enum,omitempty"` Minimum string `json:"minimum,omitempty"` Maximum string `json:"maximum,omitempty"` Items *Item `json:"items,omitempty"` UniqueItems *bool `json:"uniqueItems,omitempty"` } type Special string // 4.3.4 Items Object type Item struct { Type *string `json:"type,omitempty"` Ref *string `json:"$ref,omitempty"` Format string `json:"format,omitempty"` } // 5.1 Resource Listing type ResourceListing struct { SwaggerVersion string `json:"swaggerVersion"` // e.g 1.2 Apis []Resource `json:"apis"` ApiVersion string `json:"apiVersion"` Info Info `json:"info"` Authorizations []Authorization `json:"authorizations,omitempty"` } // 5.1.2 Resource Object type Resource struct { Path string `json:"path"` // relative or absolute, must start with / Description string `json:"description"` } // 5.1.3 Info Object type Info struct { Title string `json:"title"` Description string `json:"description"` TermsOfServiceUrl string `json:"termsOfServiceUrl,omitempty"` Contact string `json:"contact,omitempty"` License string `json:"license,omitempty"` LicenseUrl string `json:"licenseUrl,omitempty"` } // 5.1.5 type Authorization struct { Type string `json:"type"` PassAs string `json:"passAs"` Keyname string `json:"keyname"` Scopes []Scope `json:"scopes"` GrantTypes []GrantType `json:"grandTypes"` } // 5.1.6, 5.2.11 type Scope struct { // Required. The name of the scope. Scope string `json:"scope"` // Recommended. A short description of the scope. Description string `json:"description"` } // 5.1.7 type GrantType struct { Implicit Implicit `json:"implicit"` AuthorizationCode AuthorizationCode `json:"authorization_code"` } // 5.1.8 Implicit Object type Implicit struct { // Required. The login endpoint definition. loginEndpoint LoginEndpoint `json:"loginEndpoint"` // An optional alternative name to standard "access_token" OAuth2 parameter. TokenName string `json:"tokenName"` } // 5.1.9 Authorization Code Object type AuthorizationCode struct { TokenRequestEndpoint TokenRequestEndpoint `json:"tokenRequestEndpoint"` TokenEndpoint TokenEndpoint `json:"tokenEndpoint"` } // 5.1.10 Login Endpoint Object type LoginEndpoint struct { // Required. The URL of the authorization endpoint for the implicit grant flow. The value SHOULD be in a URL format. Url string `json:"url"` } // 5.1.11 Token Request Endpoint Object type TokenRequestEndpoint struct { // Required. The URL of the authorization endpoint for the authentication code grant flow. The value SHOULD be in a URL format. Url string `json:"url"` // An optional alternative name to standard "client_id" OAuth2 parameter. ClientIdName string `json:"clientIdName"` // An optional alternative name to the standard "client_secret" OAuth2 parameter. ClientSecretName string `json:"clientSecretName"` } // 5.1.12 Token Endpoint Object type TokenEndpoint struct { // Required. The URL of the token endpoint for the authentication code grant flow. The value SHOULD be in a URL format. Url string `json:"url"` // An optional alternative name to standard "access_token" OAuth2 parameter. TokenName string `json:"tokenName"` } // 5.2 API Declaration type ApiDeclaration struct { SwaggerVersion string `json:"swaggerVersion"` ApiVersion string `json:"apiVersion"` BasePath string `json:"basePath"` ResourcePath string `json:"resourcePath"` // must start with / Apis []Api `json:"apis,omitempty"` Models ModelList `json:"models,omitempty"` Produces []string `json:"produces,omitempty"` Consumes []string `json:"consumes,omitempty"` Authorizations []Authorization `json:"authorizations,omitempty"` } // 5.2.2 API Object type Api struct { Path string `json:"path"` // relative or absolute, must start with / Description string `json:"description"` Operations []Operation `json:"operations,omitempty"` } // 5.2.3 Operation Object type Operation struct { DataTypeFields Method string `json:"method"` Summary string `json:"summary,omitempty"` Notes string `json:"notes,omitempty"` Nickname string `json:"nickname"` Authorizations []Authorization `json:"authorizations,omitempty"` Parameters []Parameter `json:"parameters"` ResponseMessages []ResponseMessage `json:"responseMessages,omitempty"` // optional Produces []string `json:"produces,omitempty"` Consumes []string `json:"consumes,omitempty"` Deprecated string `json:"deprecated,omitempty"` } // 5.2.4 Parameter Object type Parameter struct { DataTypeFields ParamType string `json:"paramType"` // path,query,body,header,form Name string `json:"name"` Description string `json:"description"` Required bool `json:"required"` AllowMultiple bool `json:"allowMultiple"` } // 5.2.5 Response Message Object type ResponseMessage struct { Code int `json:"code"` Message string `json:"message"` ResponseModel string `json:"responseModel,omitempty"` } // 5.2.6, 5.2.7 Models Object type Model struct { Id string `json:"id"` Description string `json:"description,omitempty"` Required []string `json:"required,omitempty"` Properties ModelPropertyList `json:"properties"` SubTypes []string `json:"subTypes,omitempty"` Discriminator string `json:"discriminator,omitempty"` } // 5.2.8 Properties Object type ModelProperty struct { DataTypeFields Description string `json:"description,omitempty"` } // 5.2.10 type Authorizations map[string]Authorization ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/swagger_builder.go ================================================ package swagger type SwaggerBuilder struct { SwaggerService } func NewSwaggerBuilder(config Config) *SwaggerBuilder { return &SwaggerBuilder{*newSwaggerService(config)} } func (sb SwaggerBuilder) ProduceListing() ResourceListing { return sb.SwaggerService.produceListing() } func (sb SwaggerBuilder) ProduceAllDeclarations() map[string]ApiDeclaration { return sb.SwaggerService.produceAllDeclarations() } func (sb SwaggerBuilder) ProduceDeclarations(route string) (*ApiDeclaration, bool) { return sb.SwaggerService.produceDeclarations(route) } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/swagger_test.go ================================================ package swagger import ( "encoding/json" "testing" "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger/test_package" ) func TestInfoStruct_Issue231(t *testing.T) { config := Config{ Info: Info{ Title: "Title", Description: "Description", TermsOfServiceUrl: "http://example.com", Contact: "example@example.com", License: "License", LicenseUrl: "http://example.com/license.txt", }, } sws := newSwaggerService(config) str, err := json.MarshalIndent(sws.produceListing(), "", " ") if err != nil { t.Fatal(err) } compareJson(t, string(str), ` { "apiVersion": "", "swaggerVersion": "1.2", "apis": null, "info": { "title": "Title", "description": "Description", "termsOfServiceUrl": "http://example.com", "contact": "example@example.com", "license": "License", "licenseUrl": "http://example.com/license.txt" } } `) } // go test -v -test.run TestThatMultiplePathsOnRootAreHandled ...swagger func TestThatMultiplePathsOnRootAreHandled(t *testing.T) { ws1 := new(restful.WebService) ws1.Route(ws1.GET("/_ping").To(dummy)) ws1.Route(ws1.GET("/version").To(dummy)) cfg := Config{ WebServicesUrl: "http://here.com", ApiPath: "/apipath", WebServices: []*restful.WebService{ws1}, } sws := newSwaggerService(cfg) decl := sws.composeDeclaration(ws1, "/") if got, want := len(decl.Apis), 2; got != want { t.Errorf("got %v want %v", got, want) } } func TestWriteSamples(t *testing.T) { ws1 := new(restful.WebService) ws1.Route(ws1.GET("/object").To(dummy).Writes(test_package.TestStruct{})) ws1.Route(ws1.GET("/array").To(dummy).Writes([]test_package.TestStruct{})) ws1.Route(ws1.GET("/object_and_array").To(dummy).Writes(struct{ Abc test_package.TestStruct }{})) cfg := Config{ WebServicesUrl: "http://here.com", ApiPath: "/apipath", WebServices: []*restful.WebService{ws1}, } sws := newSwaggerService(cfg) decl := sws.composeDeclaration(ws1, "/") str, err := json.MarshalIndent(decl.Apis, "", " ") if err != nil { t.Fatal(err) } compareJson(t, string(str), ` [ { "path": "/object", "description": "", "operations": [ { "type": "test_package.TestStruct", "method": "GET", "nickname": "dummy", "parameters": [] } ] }, { "path": "/array", "description": "", "operations": [ { "type": "array", "items": { "$ref": "test_package.TestStruct" }, "method": "GET", "nickname": "dummy", "parameters": [] } ] }, { "path": "/object_and_array", "description": "", "operations": [ { "type": "struct { Abc test_package.TestStruct }", "method": "GET", "nickname": "dummy", "parameters": [] } ] } ]`) str, err = json.MarshalIndent(decl.Models, "", " ") if err != nil { t.Fatal(err) } compareJson(t, string(str), ` { "test_package.TestStruct": { "id": "test_package.TestStruct", "required": [ "TestField" ], "properties": { "TestField": { "type": "string" } } }, "||test_package.TestStruct": { "id": "||test_package.TestStruct", "properties": {} }, "struct { Abc test_package.TestStruct }": { "id": "struct { Abc test_package.TestStruct }", "required": [ "Abc" ], "properties": { "Abc": { "$ref": "test_package.TestStruct" } } } }`) } // go test -v -test.run TestServiceToApi ...swagger func TestServiceToApi(t *testing.T) { ws := new(restful.WebService) ws.Path("/tests") ws.Consumes(restful.MIME_JSON) ws.Produces(restful.MIME_XML) ws.Route(ws.GET("/a").To(dummy).Writes(sample{})) ws.Route(ws.PUT("/b").To(dummy).Writes(sample{})) ws.Route(ws.POST("/c").To(dummy).Writes(sample{})) ws.Route(ws.DELETE("/d").To(dummy).Writes(sample{})) ws.Route(ws.GET("/d").To(dummy).Writes(sample{})) ws.Route(ws.PUT("/c").To(dummy).Writes(sample{})) ws.Route(ws.POST("/b").To(dummy).Writes(sample{})) ws.Route(ws.DELETE("/a").To(dummy).Writes(sample{})) ws.ApiVersion("1.2.3") cfg := Config{ WebServicesUrl: "http://here.com", ApiPath: "/apipath", WebServices: []*restful.WebService{ws}, PostBuildHandler: func(in *ApiDeclarationList) {}, } sws := newSwaggerService(cfg) decl := sws.composeDeclaration(ws, "/tests") // checks if decl.ApiVersion != "1.2.3" { t.Errorf("got %v want %v", decl.ApiVersion, "1.2.3") } if decl.BasePath != "http://here.com" { t.Errorf("got %v want %v", decl.BasePath, "http://here.com") } if len(decl.Apis) != 4 { t.Errorf("got %v want %v", len(decl.Apis), 4) } pathOrder := "" for _, each := range decl.Apis { pathOrder += each.Path for _, other := range each.Operations { pathOrder += other.Method } } if pathOrder != "/tests/aGETDELETE/tests/bPUTPOST/tests/cPOSTPUT/tests/dDELETEGET" { t.Errorf("got %v want %v", pathOrder, "see test source") } } func dummy(i *restful.Request, o *restful.Response) {} // go test -v -test.run TestIssue78 ...swagger type Response struct { Code int Users *[]User Items *[]TestItem } type User struct { Id, Name string } type TestItem struct { Id, Name string } // clear && go test -v -test.run TestComposeResponseMessages ...swagger func TestComposeResponseMessages(t *testing.T) { responseErrors := map[int]restful.ResponseError{} responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: TestItem{}} route := restful.Route{ResponseErrors: responseErrors} decl := new(ApiDeclaration) decl.Models = ModelList{} msgs := composeResponseMessages(route, decl) if msgs[0].ResponseModel != "swagger.TestItem" { t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) } } // clear && go test -v -test.run TestComposeResponseMessageArray ...swagger func TestComposeResponseMessageArray(t *testing.T) { responseErrors := map[int]restful.ResponseError{} responseErrors[400] = restful.ResponseError{Code: 400, Message: "Bad Request", Model: []TestItem{}} route := restful.Route{ResponseErrors: responseErrors} decl := new(ApiDeclaration) decl.Models = ModelList{} msgs := composeResponseMessages(route, decl) if msgs[0].ResponseModel != "array[swagger.TestItem]" { t.Errorf("got %s want swagger.TestItem", msgs[0].ResponseModel) } } func TestIssue78(t *testing.T) { sws := newSwaggerService(Config{}) models := new(ModelList) sws.addModelFromSampleTo(&Operation{}, true, Response{Items: &[]TestItem{}}, models) model, ok := models.At("swagger.Response") if !ok { t.Fatal("missing response model") } if "swagger.Response" != model.Id { t.Fatal("wrong model id:" + model.Id) } code, ok := model.Properties.At("Code") if !ok { t.Fatal("missing code") } if "integer" != *code.Type { t.Fatal("wrong code type:" + *code.Type) } items, ok := model.Properties.At("Items") if !ok { t.Fatal("missing items") } if "array" != *items.Type { t.Fatal("wrong items type:" + *items.Type) } items_items := items.Items if items_items == nil { t.Fatal("missing items->items") } ref := items_items.Ref if ref == nil { t.Fatal("missing $ref") } if *ref != "swagger.TestItem" { t.Fatal("wrong $ref:" + *ref) } } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/swagger_webservice.go ================================================ package swagger import ( "fmt" "github.com/emicklei/go-restful" // "github.com/emicklei/hopwatch" "net/http" "reflect" "sort" "strings" "github.com/emicklei/go-restful/log" ) type SwaggerService struct { config Config apiDeclarationMap *ApiDeclarationList } func newSwaggerService(config Config) *SwaggerService { sws := &SwaggerService{ config: config, apiDeclarationMap: new(ApiDeclarationList)} // Build all ApiDeclarations for _, each := range config.WebServices { rootPath := each.RootPath() // skip the api service itself if rootPath != config.ApiPath { if rootPath == "" || rootPath == "/" { // use routes for _, route := range each.Routes() { entry := staticPathFromRoute(route) _, exists := sws.apiDeclarationMap.At(entry) if !exists { sws.apiDeclarationMap.Put(entry, sws.composeDeclaration(each, entry)) } } } else { // use root path sws.apiDeclarationMap.Put(each.RootPath(), sws.composeDeclaration(each, each.RootPath())) } } } // if specified then call the PostBuilderHandler if config.PostBuildHandler != nil { config.PostBuildHandler(sws.apiDeclarationMap) } return sws } // LogInfo is the function that is called when this package needs to log. It defaults to log.Printf var LogInfo = func(format string, v ...interface{}) { // use the restful package-wide logger log.Printf(format, v...) } // InstallSwaggerService add the WebService that provides the API documentation of all services // conform the Swagger documentation specifcation. (https://github.com/wordnik/swagger-core/wiki). func InstallSwaggerService(aSwaggerConfig Config) { RegisterSwaggerService(aSwaggerConfig, restful.DefaultContainer) } // RegisterSwaggerService add the WebService that provides the API documentation of all services // conform the Swagger documentation specifcation. (https://github.com/wordnik/swagger-core/wiki). func RegisterSwaggerService(config Config, wsContainer *restful.Container) { sws := newSwaggerService(config) ws := new(restful.WebService) ws.Path(config.ApiPath) ws.Produces(restful.MIME_JSON) if config.DisableCORS { ws.Filter(enableCORS) } ws.Route(ws.GET("/").To(sws.getListing)) ws.Route(ws.GET("/{a}").To(sws.getDeclarations)) ws.Route(ws.GET("/{a}/{b}").To(sws.getDeclarations)) ws.Route(ws.GET("/{a}/{b}/{c}").To(sws.getDeclarations)) ws.Route(ws.GET("/{a}/{b}/{c}/{d}").To(sws.getDeclarations)) ws.Route(ws.GET("/{a}/{b}/{c}/{d}/{e}").To(sws.getDeclarations)) ws.Route(ws.GET("/{a}/{b}/{c}/{d}/{e}/{f}").To(sws.getDeclarations)) ws.Route(ws.GET("/{a}/{b}/{c}/{d}/{e}/{f}/{g}").To(sws.getDeclarations)) LogInfo("[restful/swagger] listing is available at %v%v", config.WebServicesUrl, config.ApiPath) wsContainer.Add(ws) // Check paths for UI serving if config.StaticHandler == nil && config.SwaggerFilePath != "" && config.SwaggerPath != "" { swaggerPathSlash := config.SwaggerPath // path must end with slash / if "/" != config.SwaggerPath[len(config.SwaggerPath)-1:] { LogInfo("[restful/swagger] use corrected SwaggerPath ; must end with slash (/)") swaggerPathSlash += "/" } LogInfo("[restful/swagger] %v%v is mapped to folder %v", config.WebServicesUrl, swaggerPathSlash, config.SwaggerFilePath) wsContainer.Handle(swaggerPathSlash, http.StripPrefix(swaggerPathSlash, http.FileServer(http.Dir(config.SwaggerFilePath)))) //if we define a custom static handler use it } else if config.StaticHandler != nil && config.SwaggerPath != "" { swaggerPathSlash := config.SwaggerPath // path must end with slash / if "/" != config.SwaggerPath[len(config.SwaggerPath)-1:] { LogInfo("[restful/swagger] use corrected SwaggerFilePath ; must end with slash (/)") swaggerPathSlash += "/" } LogInfo("[restful/swagger] %v%v is mapped to custom Handler %T", config.WebServicesUrl, swaggerPathSlash, config.StaticHandler) wsContainer.Handle(swaggerPathSlash, config.StaticHandler) } else { LogInfo("[restful/swagger] Swagger(File)Path is empty ; no UI is served") } } func staticPathFromRoute(r restful.Route) string { static := r.Path bracket := strings.Index(static, "{") if bracket <= 1 { // result cannot be empty return static } if bracket != -1 { static = r.Path[:bracket] } if strings.HasSuffix(static, "/") { return static[:len(static)-1] } else { return static } } func enableCORS(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) { if origin := req.HeaderParameter(restful.HEADER_Origin); origin != "" { // prevent duplicate header if len(resp.Header().Get(restful.HEADER_AccessControlAllowOrigin)) == 0 { resp.AddHeader(restful.HEADER_AccessControlAllowOrigin, origin) } } chain.ProcessFilter(req, resp) } func (sws SwaggerService) getListing(req *restful.Request, resp *restful.Response) { listing := sws.produceListing() resp.WriteAsJson(listing) } func (sws SwaggerService) produceListing() ResourceListing { listing := ResourceListing{SwaggerVersion: swaggerVersion, ApiVersion: sws.config.ApiVersion, Info: sws.config.Info} sws.apiDeclarationMap.Do(func(k string, v ApiDeclaration) { ref := Resource{Path: k} if len(v.Apis) > 0 { // use description of first (could still be empty) ref.Description = v.Apis[0].Description } listing.Apis = append(listing.Apis, ref) }) return listing } func (sws SwaggerService) getDeclarations(req *restful.Request, resp *restful.Response) { decl, ok := sws.produceDeclarations(composeRootPath(req)) if !ok { resp.WriteErrorString(http.StatusNotFound, "ApiDeclaration not found") return } // unless WebServicesUrl is given if len(sws.config.WebServicesUrl) == 0 { // update base path from the actual request // TODO how to detect https? assume http for now var host string // X-Forwarded-Host or Host or Request.Host hostvalues, ok := req.Request.Header["X-Forwarded-Host"] // apache specific? if !ok || len(hostvalues) == 0 { forwarded, ok := req.Request.Header["Host"] // without reverse-proxy if !ok || len(forwarded) == 0 { // fallback to Host field host = req.Request.Host } else { host = forwarded[0] } } else { host = hostvalues[0] } // inspect Referer for the scheme (http vs https) scheme := "http" if referer := req.Request.Header["Referer"]; len(referer) > 0 { if strings.HasPrefix(referer[0], "https") { scheme = "https" } } decl.BasePath = fmt.Sprintf("%s://%s", scheme, host) } resp.WriteAsJson(decl) } func (sws SwaggerService) produceAllDeclarations() map[string]ApiDeclaration { decls := map[string]ApiDeclaration{} sws.apiDeclarationMap.Do(func(k string, v ApiDeclaration) { decls[k] = v }) return decls } func (sws SwaggerService) produceDeclarations(route string) (*ApiDeclaration, bool) { decl, ok := sws.apiDeclarationMap.At(route) if !ok { return nil, false } decl.BasePath = sws.config.WebServicesUrl return &decl, true } // composeDeclaration uses all routes and parameters to create a ApiDeclaration func (sws SwaggerService) composeDeclaration(ws *restful.WebService, pathPrefix string) ApiDeclaration { decl := ApiDeclaration{ SwaggerVersion: swaggerVersion, BasePath: sws.config.WebServicesUrl, ResourcePath: pathPrefix, Models: ModelList{}, ApiVersion: ws.Version()} // collect any path parameters rootParams := []Parameter{} for _, param := range ws.PathParameters() { rootParams = append(rootParams, asSwaggerParameter(param.Data())) } // aggregate by path pathToRoutes := newOrderedRouteMap() for _, other := range ws.Routes() { if strings.HasPrefix(other.Path, pathPrefix) { pathToRoutes.Add(other.Path, other) } } pathToRoutes.Do(func(path string, routes []restful.Route) { api := Api{Path: strings.TrimSuffix(withoutWildcard(path), "/"), Description: ws.Documentation()} voidString := "void" for _, route := range routes { operation := Operation{ Method: route.Method, Summary: route.Doc, Notes: route.Notes, // Type gets overwritten if there is a write sample DataTypeFields: DataTypeFields{Type: &voidString}, Parameters: []Parameter{}, Nickname: route.Operation, ResponseMessages: composeResponseMessages(route, &decl)} operation.Consumes = route.Consumes operation.Produces = route.Produces // share root params if any for _, swparam := range rootParams { operation.Parameters = append(operation.Parameters, swparam) } // route specific params for _, param := range route.ParameterDocs { operation.Parameters = append(operation.Parameters, asSwaggerParameter(param.Data())) } sws.addModelsFromRouteTo(&operation, route, &decl) api.Operations = append(api.Operations, operation) } decl.Apis = append(decl.Apis, api) }) return decl } func withoutWildcard(path string) string { if strings.HasSuffix(path, ":*}") { return path[0:len(path)-3] + "}" } return path } // composeResponseMessages takes the ResponseErrors (if any) and creates ResponseMessages from them. func composeResponseMessages(route restful.Route, decl *ApiDeclaration) (messages []ResponseMessage) { if route.ResponseErrors == nil { return messages } // sort by code codes := sort.IntSlice{} for code, _ := range route.ResponseErrors { codes = append(codes, code) } codes.Sort() for _, code := range codes { each := route.ResponseErrors[code] message := ResponseMessage{ Code: code, Message: each.Message, } if each.Model != nil { st := reflect.TypeOf(each.Model) isCollection, st := detectCollectionType(st) modelName := modelBuilder{}.keyFrom(st) if isCollection { modelName = "array[" + modelName + "]" } modelBuilder{&decl.Models}.addModel(st, "") // reference the model message.ResponseModel = modelName } messages = append(messages, message) } return } // addModelsFromRoute takes any read or write sample from the Route and creates a Swagger model from it. func (sws SwaggerService) addModelsFromRouteTo(operation *Operation, route restful.Route, decl *ApiDeclaration) { if route.ReadSample != nil { sws.addModelFromSampleTo(operation, false, route.ReadSample, &decl.Models) } if route.WriteSample != nil { sws.addModelFromSampleTo(operation, true, route.WriteSample, &decl.Models) } } func detectCollectionType(st reflect.Type) (bool, reflect.Type) { isCollection := false if st.Kind() == reflect.Slice || st.Kind() == reflect.Array { st = st.Elem() isCollection = true } else { if st.Kind() == reflect.Ptr { if st.Elem().Kind() == reflect.Slice || st.Elem().Kind() == reflect.Array { st = st.Elem().Elem() isCollection = true } } } return isCollection, st } // addModelFromSample creates and adds (or overwrites) a Model from a sample resource func (sws SwaggerService) addModelFromSampleTo(operation *Operation, isResponse bool, sample interface{}, models *ModelList) { if isResponse { type_, items := asDataType(sample) operation.Type = type_ operation.Items = items } modelBuilder{models}.addModelFrom(sample) } func asSwaggerParameter(param restful.ParameterData) Parameter { return Parameter{ DataTypeFields: DataTypeFields{ Type: ¶m.DataType, Format: asFormat(param.DataType, param.DataFormat), DefaultValue: Special(param.DefaultValue), }, Name: param.Name, Description: param.Description, ParamType: asParamType(param.Kind), Required: param.Required} } // Between 1..7 path parameters is supported func composeRootPath(req *restful.Request) string { path := "/" + req.PathParameter("a") b := req.PathParameter("b") if b == "" { return path } path = path + "/" + b c := req.PathParameter("c") if c == "" { return path } path = path + "/" + c d := req.PathParameter("d") if d == "" { return path } path = path + "/" + d e := req.PathParameter("e") if e == "" { return path } path = path + "/" + e f := req.PathParameter("f") if f == "" { return path } path = path + "/" + f g := req.PathParameter("g") if g == "" { return path } return path + "/" + g } func asFormat(dataType string, dataFormat string) string { if dataFormat != "" { return dataFormat } return "" // TODO } func asParamType(kind int) string { switch { case kind == restful.PathParameterKind: return "path" case kind == restful.QueryParameterKind: return "query" case kind == restful.BodyParameterKind: return "body" case kind == restful.HeaderParameterKind: return "header" case kind == restful.FormParameterKind: return "form" } return "" } func asDataType(any interface{}) (*string, *Item) { // If it's not a collection, return the suggested model name st := reflect.TypeOf(any) isCollection, st := detectCollectionType(st) modelName := modelBuilder{}.keyFrom(st) // if it's not a collection we are done if !isCollection { return &modelName, nil } // XXX: This is not very elegant // We create an Item object referring to the given model models := ModelList{} mb := modelBuilder{&models} mb.addModelFrom(any) elemTypeName := mb.getElementTypeName(modelName, "", st) item := new(Item) if mb.isPrimitiveType(elemTypeName) { mapped := mb.jsonSchemaType(elemTypeName) item.Type = &mapped } else { item.Ref = &elemTypeName } tmp := "array" return &tmp, item } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/test_package/struct.go ================================================ package test_package type TestStruct struct { TestField string } ================================================ FILE: vendor/github.com/emicklei/go-restful/swagger/utils_test.go ================================================ package swagger import ( "bytes" "encoding/json" "fmt" "reflect" "strings" "testing" ) func testJsonFromStruct(t *testing.T, sample interface{}, expectedJson string) bool { m := modelsFromStruct(sample) data, _ := json.MarshalIndent(m, " ", " ") return compareJson(t, string(data), expectedJson) } func modelsFromStruct(sample interface{}) *ModelList { models := new(ModelList) builder := modelBuilder{models} builder.addModelFrom(sample) return models } func compareJson(t *testing.T, actualJsonAsString string, expectedJsonAsString string) bool { success := false var actualMap map[string]interface{} json.Unmarshal([]byte(actualJsonAsString), &actualMap) var expectedMap map[string]interface{} err := json.Unmarshal([]byte(expectedJsonAsString), &expectedMap) if err != nil { var actualArray []interface{} json.Unmarshal([]byte(actualJsonAsString), &actualArray) var expectedArray []interface{} err := json.Unmarshal([]byte(expectedJsonAsString), &expectedArray) success = reflect.DeepEqual(actualArray, expectedArray) if err != nil { t.Fatalf("Unparsable expected JSON: %s", err) } } else { success = reflect.DeepEqual(actualMap, expectedMap) } if !success { t.Log("---- expected -----") t.Log(withLineNumbers(expectedJsonAsString)) t.Log("---- actual -----") t.Log(withLineNumbers(actualJsonAsString)) t.Log("---- raw -----") t.Log(actualJsonAsString) t.Error("there are differences") return false } return true } func indexOfNonMatchingLine(actual, expected string) int { a := strings.Split(actual, "\n") e := strings.Split(expected, "\n") size := len(a) if len(e) < len(a) { size = len(e) } for i := 0; i < size; i++ { if a[i] != e[i] { return i } } return -1 } func withLineNumbers(content string) string { var buffer bytes.Buffer lines := strings.Split(content, "\n") for i, each := range lines { buffer.WriteString(fmt.Sprintf("%d:%s\n", i, each)) } return buffer.String() } ================================================ FILE: vendor/github.com/emicklei/go-restful/tracer_test.go ================================================ package restful import "testing" // Use like this: // // TraceLogger(testLogger{t}) type testLogger struct { t *testing.T } func (l testLogger) Print(v ...interface{}) { l.t.Log(v...) } func (l testLogger) Printf(format string, v ...interface{}) { l.t.Logf(format, v...) } ================================================ FILE: vendor/github.com/emicklei/go-restful/web_service.go ================================================ package restful import ( "fmt" "os" "sync" "github.com/emicklei/go-restful/log" ) // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. // WebService holds a collection of Route values that bind a Http Method + URL Path to a function. type WebService struct { rootPath string pathExpr *pathExpression // cached compilation of rootPath as RegExp routes []Route produces []string consumes []string pathParameters []*Parameter filters []FilterFunction documentation string apiVersion string dynamicRoutes bool // protects 'routes' if dynamic routes are enabled routesLock sync.RWMutex } func (w *WebService) SetDynamicRoutes(enable bool) { w.dynamicRoutes = enable } // compilePathExpression ensures that the path is compiled into a RegEx for those routers that need it. func (w *WebService) compilePathExpression() { if len(w.rootPath) == 0 { w.Path("/") // lazy initialize path } compiled, err := newPathExpression(w.rootPath) if err != nil { log.Printf("[restful] invalid path:%s because:%v", w.rootPath, err) os.Exit(1) } w.pathExpr = compiled } // ApiVersion sets the API version for documentation purposes. func (w *WebService) ApiVersion(apiVersion string) *WebService { w.apiVersion = apiVersion return w } // Version returns the API version for documentation purposes. func (w WebService) Version() string { return w.apiVersion } // Path specifies the root URL template path of the WebService. // All Routes will be relative to this path. func (w *WebService) Path(root string) *WebService { w.rootPath = root w.compilePathExpression() return w } // Param adds a PathParameter to document parameters used in the root path. func (w *WebService) Param(parameter *Parameter) *WebService { if w.pathParameters == nil { w.pathParameters = []*Parameter{} } w.pathParameters = append(w.pathParameters, parameter) return w } // PathParameter creates a new Parameter of kind Path for documentation purposes. // It is initialized as required with string as its DataType. func (w *WebService) PathParameter(name, description string) *Parameter { return PathParameter(name, description) } // PathParameter creates a new Parameter of kind Path for documentation purposes. // It is initialized as required with string as its DataType. func PathParameter(name, description string) *Parameter { p := &Parameter{&ParameterData{Name: name, Description: description, Required: true, DataType: "string"}} p.bePath() return p } // QueryParameter creates a new Parameter of kind Query for documentation purposes. // It is initialized as not required with string as its DataType. func (w *WebService) QueryParameter(name, description string) *Parameter { return QueryParameter(name, description) } // QueryParameter creates a new Parameter of kind Query for documentation purposes. // It is initialized as not required with string as its DataType. func QueryParameter(name, description string) *Parameter { p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}} p.beQuery() return p } // BodyParameter creates a new Parameter of kind Body for documentation purposes. // It is initialized as required without a DataType. func (w *WebService) BodyParameter(name, description string) *Parameter { return BodyParameter(name, description) } // BodyParameter creates a new Parameter of kind Body for documentation purposes. // It is initialized as required without a DataType. func BodyParameter(name, description string) *Parameter { p := &Parameter{&ParameterData{Name: name, Description: description, Required: true}} p.beBody() return p } // HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes. // It is initialized as not required with string as its DataType. func (w *WebService) HeaderParameter(name, description string) *Parameter { return HeaderParameter(name, description) } // HeaderParameter creates a new Parameter of kind (Http) Header for documentation purposes. // It is initialized as not required with string as its DataType. func HeaderParameter(name, description string) *Parameter { p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}} p.beHeader() return p } // FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes. // It is initialized as required with string as its DataType. func (w *WebService) FormParameter(name, description string) *Parameter { return FormParameter(name, description) } // FormParameter creates a new Parameter of kind Form (using application/x-www-form-urlencoded) for documentation purposes. // It is initialized as required with string as its DataType. func FormParameter(name, description string) *Parameter { p := &Parameter{&ParameterData{Name: name, Description: description, Required: false, DataType: "string"}} p.beForm() return p } // Route creates a new Route using the RouteBuilder and add to the ordered list of Routes. func (w *WebService) Route(builder *RouteBuilder) *WebService { w.routesLock.Lock() defer w.routesLock.Unlock() builder.copyDefaults(w.produces, w.consumes) w.routes = append(w.routes, builder.Build()) return w } // RemoveRoute removes the specified route, looks for something that matches 'path' and 'method' func (w *WebService) RemoveRoute(path, method string) error { if !w.dynamicRoutes { return fmt.Errorf("dynamic routes are not enabled.") } w.routesLock.Lock() defer w.routesLock.Unlock() for ix := range w.routes { if w.routes[ix].Method == method && w.routes[ix].Path == path { w.routes = append(w.routes[:ix], w.routes[ix+1:]...) } } return nil } // Method creates a new RouteBuilder and initialize its http method func (w *WebService) Method(httpMethod string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method(httpMethod) } // Produces specifies that this WebService can produce one or more MIME types. // Http requests must have one of these values set for the Accept header. func (w *WebService) Produces(contentTypes ...string) *WebService { w.produces = contentTypes return w } // Consumes specifies that this WebService can consume one or more MIME types. // Http requests must have one of these values set for the Content-Type header. func (w *WebService) Consumes(accepts ...string) *WebService { w.consumes = accepts return w } // Routes returns the Routes associated with this WebService func (w WebService) Routes() []Route { if !w.dynamicRoutes { return w.routes } // Make a copy of the array to prevent concurrency problems w.routesLock.RLock() defer w.routesLock.RUnlock() result := make([]Route, len(w.routes)) for ix := range w.routes { result[ix] = w.routes[ix] } return result } // RootPath returns the RootPath associated with this WebService. Default "/" func (w WebService) RootPath() string { return w.rootPath } // PathParameters return the path parameter names for (shared amoung its Routes) func (w WebService) PathParameters() []*Parameter { return w.pathParameters } // Filter adds a filter function to the chain of filters applicable to all its Routes func (w *WebService) Filter(filter FilterFunction) *WebService { w.filters = append(w.filters, filter) return w } // Doc is used to set the documentation of this service. func (w *WebService) Doc(plainText string) *WebService { w.documentation = plainText return w } // Documentation returns it. func (w WebService) Documentation() string { return w.documentation } /* Convenience methods */ // HEAD is a shortcut for .Method("HEAD").Path(subPath) func (w *WebService) HEAD(subPath string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method("HEAD").Path(subPath) } // GET is a shortcut for .Method("GET").Path(subPath) func (w *WebService) GET(subPath string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method("GET").Path(subPath) } // POST is a shortcut for .Method("POST").Path(subPath) func (w *WebService) POST(subPath string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method("POST").Path(subPath) } // PUT is a shortcut for .Method("PUT").Path(subPath) func (w *WebService) PUT(subPath string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method("PUT").Path(subPath) } // PATCH is a shortcut for .Method("PATCH").Path(subPath) func (w *WebService) PATCH(subPath string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method("PATCH").Path(subPath) } // DELETE is a shortcut for .Method("DELETE").Path(subPath) func (w *WebService) DELETE(subPath string) *RouteBuilder { return new(RouteBuilder).servicePath(w.rootPath).Method("DELETE").Path(subPath) } ================================================ FILE: vendor/github.com/emicklei/go-restful/web_service_container.go ================================================ package restful // Copyright 2013 Ernest Micklei. All rights reserved. // Use of this source code is governed by a license // that can be found in the LICENSE file. import ( "net/http" ) // DefaultContainer is a restful.Container that uses http.DefaultServeMux var DefaultContainer *Container func init() { DefaultContainer = NewContainer() DefaultContainer.ServeMux = http.DefaultServeMux } // If set the true then panics will not be caught to return HTTP 500. // In that case, Route functions are responsible for handling any error situation. // Default value is false = recover from panics. This has performance implications. // OBSOLETE ; use restful.DefaultContainer.DoNotRecover(true) var DoNotRecover = false // Add registers a new WebService add it to the DefaultContainer. func Add(service *WebService) { DefaultContainer.Add(service) } // Filter appends a container FilterFunction from the DefaultContainer. // These are called before dispatching a http.Request to a WebService. func Filter(filter FilterFunction) { DefaultContainer.Filter(filter) } // RegisteredWebServices returns the collections of WebServices from the DefaultContainer func RegisteredWebServices() []*WebService { return DefaultContainer.RegisteredWebServices() } ================================================ FILE: vendor/github.com/emicklei/go-restful/web_service_test.go ================================================ package restful import ( "net/http" "net/http/httptest" "testing" ) const ( pathGetFriends = "/get/{userId}/friends" ) func TestParameter(t *testing.T) { p := &Parameter{&ParameterData{Name: "name", Description: "desc"}} p.AllowMultiple(true) p.DataType("int") p.Required(true) values := map[string]string{"a": "b"} p.AllowableValues(values) p.bePath() ws := new(WebService) ws.Param(p) if ws.pathParameters[0].Data().Name != "name" { t.Error("path parameter (or name) invalid") } } func TestWebService_CanCreateParameterKinds(t *testing.T) { ws := new(WebService) if ws.BodyParameter("b", "b").Kind() != BodyParameterKind { t.Error("body parameter expected") } if ws.PathParameter("p", "p").Kind() != PathParameterKind { t.Error("path parameter expected") } if ws.QueryParameter("q", "q").Kind() != QueryParameterKind { t.Error("query parameter expected") } } func TestCapturePanic(t *testing.T) { tearDown() Add(newPanicingService()) httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) httpRequest.Header.Set("Accept", "*/*") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 500 != httpWriter.Code { t.Error("500 expected on fire") } } func TestCapturePanicWithEncoded(t *testing.T) { tearDown() Add(newPanicingService()) DefaultContainer.EnableContentEncoding(true) httpRequest, _ := http.NewRequest("GET", "http://here.com/fire", nil) httpRequest.Header.Set("Accept", "*/*") httpRequest.Header.Set("Accept-Encoding", "gzip") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 500 != httpWriter.Code { t.Error("500 expected on fire, got", httpWriter.Code) } } func TestNotFound(t *testing.T) { tearDown() httpRequest, _ := http.NewRequest("GET", "http://here.com/missing", nil) httpRequest.Header.Set("Accept", "*/*") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 404 != httpWriter.Code { t.Error("404 expected on missing") } } func TestMethodNotAllowed(t *testing.T) { tearDown() Add(newGetOnlyService()) httpRequest, _ := http.NewRequest("POST", "http://here.com/get", nil) httpRequest.Header.Set("Accept", "*/*") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 405 != httpWriter.Code { t.Error("405 expected method not allowed") } } func TestSelectedRoutePath_Issue100(t *testing.T) { tearDown() Add(newSelectedRouteTestingService()) httpRequest, _ := http.NewRequest("GET", "http://here.com/get/232452/friends", nil) httpRequest.Header.Set("Accept", "*/*") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if http.StatusOK != httpWriter.Code { t.Error(http.StatusOK, "expected,", httpWriter.Code, "received.") } } func TestContentType415_Issue170(t *testing.T) { tearDown() Add(newGetOnlyJsonOnlyService()) httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 200 != httpWriter.Code { t.Errorf("Expected 200, got %d", httpWriter.Code) } } func TestContentType415_POST_Issue170(t *testing.T) { tearDown() Add(newPostOnlyJsonOnlyService()) httpRequest, _ := http.NewRequest("POST", "http://here.com/post", nil) httpRequest.Header.Set("Content-Type", "application/json") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 200 != httpWriter.Code { t.Errorf("Expected 200, got %d", httpWriter.Code) } } // go test -v -test.run TestContentType406PlainJson ...restful func TestContentType406PlainJson(t *testing.T) { tearDown() TraceLogger(testLogger{t}) Add(newGetPlainTextOrJsonService()) httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) httpRequest.Header.Set("Accept", "text/plain") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if got, want := httpWriter.Code, 200; got != want { t.Errorf("got %v, want %v", got, want) } } func TestRemoveRoute(t *testing.T) { tearDown() TraceLogger(testLogger{t}) ws := newGetPlainTextOrJsonService() Add(ws) httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) httpRequest.Header.Set("Accept", "text/plain") httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if got, want := httpWriter.Code, 200; got != want { t.Errorf("got %v, want %v", got, want) } // dynamic apis are disabled, should error and do nothing if err := ws.RemoveRoute("/get", "GET"); err == nil { t.Error("unexpected non-error") } httpWriter = httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if got, want := httpWriter.Code, 200; got != want { t.Errorf("got %v, want %v", got, want) } ws.SetDynamicRoutes(true) if err := ws.RemoveRoute("/get", "GET"); err != nil { t.Errorf("unexpected error %v", err) } httpWriter = httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if got, want := httpWriter.Code, 404; got != want { t.Errorf("got %v, want %v", got, want) } } // go test -v -test.run TestContentTypeOctet_Issue170 ...restful func TestContentTypeOctet_Issue170(t *testing.T) { tearDown() Add(newGetConsumingOctetStreamService()) // with content-type httpRequest, _ := http.NewRequest("GET", "http://here.com/get", nil) httpRequest.Header.Set("Content-Type", MIME_OCTET) httpWriter := httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 200 != httpWriter.Code { t.Errorf("Expected 200, got %d", httpWriter.Code) } // without content-type httpRequest, _ = http.NewRequest("GET", "http://here.com/get", nil) httpWriter = httptest.NewRecorder() DefaultContainer.dispatch(httpWriter, httpRequest) if 200 != httpWriter.Code { t.Errorf("Expected 200, got %d", httpWriter.Code) } } func newPanicingService() *WebService { ws := new(WebService).Path("") ws.Route(ws.GET("/fire").To(doPanic)) return ws } func newGetOnlyService() *WebService { ws := new(WebService).Path("") ws.Route(ws.GET("/get").To(doPanic)) return ws } func newPostOnlyJsonOnlyService() *WebService { ws := new(WebService).Path("") ws.Consumes("application/json") ws.Route(ws.POST("/post").To(doNothing)) return ws } func newGetOnlyJsonOnlyService() *WebService { ws := new(WebService).Path("") ws.Consumes("application/json") ws.Route(ws.GET("/get").To(doNothing)) return ws } func newGetPlainTextOrJsonService() *WebService { ws := new(WebService).Path("") ws.Produces("text/plain", "application/json") ws.Route(ws.GET("/get").To(doNothing)) return ws } func newGetConsumingOctetStreamService() *WebService { ws := new(WebService).Path("") ws.Consumes("application/octet-stream") ws.Route(ws.GET("/get").To(doNothing)) return ws } func newSelectedRouteTestingService() *WebService { ws := new(WebService).Path("") ws.Route(ws.GET(pathGetFriends).To(selectedRouteChecker)) return ws } func selectedRouteChecker(req *Request, resp *Response) { if req.SelectedRoutePath() != pathGetFriends { resp.InternalServerError() } } func doPanic(req *Request, resp *Response) { println("lightning...") panic("fire") } func doNothing(req *Request, resp *Response) { } ================================================ FILE: vendor/github.com/evanphx/json-patch/.travis.yml ================================================ language: go go: - 1.4 - 1.3 install: - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi script: - go test -cover ./... notifications: email: false ================================================ FILE: vendor/github.com/evanphx/json-patch/LICENSE ================================================ Copyright (c) 2014, Evan Phoenix 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 Evan Phoenix 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. ================================================ FILE: vendor/github.com/evanphx/json-patch/README.md ================================================ ## JSON-Patch Provides the abiilty to modify and test a JSON according to a [RFC6902 JSON patch](http://tools.ietf.org/html/rfc6902) and [RFC7386 JSON Merge Patch](https://tools.ietf.org/html/rfc7386). *Version*: **1.0** [![GoDoc](https://godoc.org/github.com/evanphx/json-patch?status.svg)](http://godoc.org/github.com/evanphx/json-patch) [![Build Status](https://travis-ci.org/evanphx/json-patch.svg?branch=RFC7386)](https://travis-ci.org/evanphx/json-patch) ### API Usage * Given a `[]byte`, obtain a Patch object `obj, err := jsonpatch.DecodePatch(patch)` * Apply the patch and get a new document back `out, err := obj.Apply(doc)` * Create a JSON Merge Patch document based on two json documents (a to b): `mergeDoc, err := jsonpatch.CreateMergePatch(a, b)` * Bonus API: compare documents for structural equality `jsonpatch.Equal(doca, docb)` ================================================ FILE: vendor/github.com/evanphx/json-patch/merge.go ================================================ package jsonpatch import ( "encoding/json" "fmt" "reflect" ) func merge(cur, patch *lazyNode) *lazyNode { curDoc, err := cur.intoDoc() if err != nil { pruneNulls(patch) return patch } patchDoc, err := patch.intoDoc() if err != nil { return patch } mergeDocs(curDoc, patchDoc) return cur } func mergeDocs(doc, patch *partialDoc) { for k, v := range *patch { if v == nil { delete(*doc, k) } else { cur, ok := (*doc)[k] if !ok || cur == nil { pruneNulls(v) (*doc)[k] = v } else { (*doc)[k] = merge(cur, v) } } } } func pruneNulls(n *lazyNode) { sub, err := n.intoDoc() if err == nil { pruneDocNulls(sub) } else { ary, err := n.intoAry() if err == nil { pruneAryNulls(ary) } } } func pruneDocNulls(doc *partialDoc) *partialDoc { for k, v := range *doc { if v == nil { delete(*doc, k) } else { pruneNulls(v) } } return doc } func pruneAryNulls(ary *partialArray) *partialArray { var newAry []*lazyNode for _, v := range *ary { if v != nil { pruneNulls(v) newAry = append(newAry, v) } } *ary = newAry return ary } var errBadJSONDoc = fmt.Errorf("Invalid JSON Document") var errBadJSONPatch = fmt.Errorf("Invalid JSON Patch") // MergePatch merges the patchData into the docData. func MergePatch(docData, patchData []byte) ([]byte, error) { doc := &partialDoc{} docErr := json.Unmarshal(docData, doc) patch := &partialDoc{} patchErr := json.Unmarshal(patchData, patch) if _, ok := docErr.(*json.SyntaxError); ok { return nil, errBadJSONDoc } if _, ok := patchErr.(*json.SyntaxError); ok { return nil, errBadJSONPatch } if docErr == nil && *doc == nil { return nil, errBadJSONDoc } if patchErr == nil && *patch == nil { return nil, errBadJSONPatch } if docErr != nil || patchErr != nil { // Not an error, just not a doc, so we turn straight into the patch if patchErr == nil { doc = pruneDocNulls(patch) } else { patchAry := &partialArray{} patchErr = json.Unmarshal(patchData, patchAry) if patchErr != nil { return nil, errBadJSONPatch } pruneAryNulls(patchAry) out, patchErr := json.Marshal(patchAry) if patchErr != nil { return nil, errBadJSONPatch } return out, nil } } else { mergeDocs(doc, patch) } return json.Marshal(doc) } // CreateMergePatch creates a merge patch as specified in http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 // // 'a' is original, 'b' is the modified document. Both are to be given as json encoded content. // The function will return a mergeable json document with differences from a to b. // // An error will be returned if any of the two documents are invalid. func CreateMergePatch(a, b []byte) ([]byte, error) { aI := map[string]interface{}{} bI := map[string]interface{}{} err := json.Unmarshal(a, &aI) if err != nil { return nil, errBadJSONDoc } err = json.Unmarshal(b, &bI) if err != nil { return nil, errBadJSONDoc } dest, err := getDiff(aI, bI) if err != nil { return nil, err } return json.Marshal(dest) } // Returns true if the array matches (must be json types). // As is idiomatic for go, an empty array is not the same as a nil array. func matchesArray(a, b []interface{}) bool { if len(a) != len(b) { return false } if (a == nil && b != nil) || (a != nil && b == nil) { return false } for i := range a { if !matchesValue(a[i], b[i]) { return false } } return true } // Returns true if the values matches (must be json types) // The types of the values must match, otherwise it will always return false // If two map[string]interface{} are given, all elements must match. func matchesValue(av, bv interface{}) bool { if reflect.TypeOf(av) != reflect.TypeOf(bv) { return false } switch at := av.(type) { case string: bt := bv.(string) if bt == at { return true } case float64: bt := bv.(float64) if bt == at { return true } case bool: bt := bv.(bool) if bt == at { return true } case map[string]interface{}: bt := bv.(map[string]interface{}) for key := range at { if !matchesValue(at[key], bt[key]) { return false } } for key := range bt { if !matchesValue(at[key], bt[key]) { return false } } return true } return false } // getDiff returns the (recursive) difference between a and b as a map[string]interface{}. func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) { into := map[string]interface{}{} for key, bv := range b { av, ok := a[key] // value was added if !ok { into[key] = bv continue } // If types have changed, replace completely if reflect.TypeOf(av) != reflect.TypeOf(bv) { into[key] = bv continue } // Types are the same, compare values switch at := av.(type) { case map[string]interface{}: bt := bv.(map[string]interface{}) dst := make(map[string]interface{}, len(bt)) dst, err := getDiff(at, bt) if err != nil { return nil, err } if len(dst) > 0 { into[key] = dst } case string, float64, bool: if !matchesValue(av, bv) { into[key] = bv } case []interface{}: bt := bv.([]interface{}) if !matchesArray(at, bt) { into[key] = bv } case nil: switch bv.(type) { case nil: // Both nil, fine. default: into[key] = bv } default: panic(fmt.Sprintf("Unknown type:%T in key %s", av, key)) } } // Now add all deleted values as nil for key := range a { _, found := b[key] if !found { into[key] = nil } } return into, nil } ================================================ FILE: vendor/github.com/evanphx/json-patch/merge_test.go ================================================ package jsonpatch import ( "strings" "testing" ) func mergePatch(doc, patch string) string { out, err := MergePatch([]byte(doc), []byte(patch)) if err != nil { panic(err) } return string(out) } func TestMergePatchReplaceKey(t *testing.T) { doc := `{ "title": "hello" }` pat := `{ "title": "goodbye" }` res := mergePatch(doc, pat) if !compareJSON(pat, res) { t.Fatalf("Key was not replaced") } } func TestMergePatchIgnoresOtherValues(t *testing.T) { doc := `{ "title": "hello", "age": 18 }` pat := `{ "title": "goodbye" }` res := mergePatch(doc, pat) exp := `{ "title": "goodbye", "age": 18 }` if !compareJSON(exp, res) { t.Fatalf("Key was not replaced") } } func TestMergePatchNilDoc(t *testing.T) { doc := `{ "title": null }` pat := `{ "title": {"foo": "bar"} }` res := mergePatch(doc, pat) exp := `{ "title": {"foo": "bar"} }` if !compareJSON(exp, res) { t.Fatalf("Key was not replaced") } } func TestMergePatchRecursesIntoObjects(t *testing.T) { doc := `{ "person": { "title": "hello", "age": 18 } }` pat := `{ "person": { "title": "goodbye" } }` res := mergePatch(doc, pat) exp := `{ "person": { "title": "goodbye", "age": 18 } }` if !compareJSON(exp, res) { t.Fatalf("Key was not replaced") } } type nonObjectCases struct { doc, pat, res string } func TestMergePatchReplacesNonObjectsWholesale(t *testing.T) { a1 := `[1]` a2 := `[2]` o1 := `{ "a": 1 }` o2 := `{ "a": 2 }` o3 := `{ "a": 1, "b": 1 }` o4 := `{ "a": 2, "b": 1 }` cases := []nonObjectCases{ {a1, a2, a2}, {o1, a2, a2}, {a1, o1, o1}, {o3, o2, o4}, } for _, c := range cases { act := mergePatch(c.doc, c.pat) if !compareJSON(c.res, act) { t.Errorf("whole object replacement failed") } } } func TestMergePatchReturnsErrorOnBadJSON(t *testing.T) { _, err := MergePatch([]byte(`[[[[`), []byte(`1`)) if err == nil { t.Errorf("Did not return an error for bad json: %s", err) } _, err = MergePatch([]byte(`1`), []byte(`[[[[`)) if err == nil { t.Errorf("Did not return an error for bad json: %s", err) } } var rfcTests = []struct { target string patch string expected string }{ // test cases from https://tools.ietf.org/html/rfc7386#appendix-A {target: `{"a":"b"}`, patch: `{"a":"c"}`, expected: `{"a":"c"}`}, {target: `{"a":"b"}`, patch: `{"b":"c"}`, expected: `{"a":"b","b":"c"}`}, {target: `{"a":"b"}`, patch: `{"a":null}`, expected: `{}`}, {target: `{"a":"b","b":"c"}`, patch: `{"a":null}`, expected: `{"b":"c"}`}, {target: `{"a":["b"]}`, patch: `{"a":"c"}`, expected: `{"a":"c"}`}, {target: `{"a":"c"}`, patch: `{"a":["b"]}`, expected: `{"a":["b"]}`}, {target: `{"a":{"b": "c"}}`, patch: `{"a": {"b": "d","c": null}}`, expected: `{"a":{"b":"d"}}`}, {target: `{"a":[{"b":"c"}]}`, patch: `{"a":[1]}`, expected: `{"a":[1]}`}, {target: `["a","b"]`, patch: `["c","d"]`, expected: `["c","d"]`}, {target: `{"a":"b"}`, patch: `["c"]`, expected: `["c"]`}, // {target: `{"a":"foo"}`, patch: `null`, expected: `null`}, // {target: `{"a":"foo"}`, patch: `"bar"`, expected: `"bar"`}, {target: `{"e":null}`, patch: `{"a":1}`, expected: `{"a":1,"e":null}`}, {target: `[1,2]`, patch: `{"a":"b","c":null}`, expected: `{"a":"b"}`}, {target: `{}`, patch: `{"a":{"bb":{"ccc":null}}}`, expected: `{"a":{"bb":{}}}`}, } func TestMergePatchRFCCases(t *testing.T) { for i, c := range rfcTests { out := mergePatch(c.target, c.patch) if !compareJSON(out, c.expected) { t.Errorf("case[%d], patch '%s' did not apply properly to '%s'. expected:\n'%s'\ngot:\n'%s'", i, c.patch, c.target, c.expected, out) } } } var rfcFailTests = ` {"a":"foo"} | null {"a":"foo"} | "bar" ` func TestMergePatchFailRFCCases(t *testing.T) { tests := strings.Split(rfcFailTests, "\n") for _, c := range tests { if strings.TrimSpace(c) == "" { continue } parts := strings.SplitN(c, "|", 2) doc := strings.TrimSpace(parts[0]) pat := strings.TrimSpace(parts[1]) out, err := MergePatch([]byte(doc), []byte(pat)) if err != errBadJSONPatch { t.Errorf("error not returned properly: %s, %s", err, string(out)) } } } func TestMergeReplaceKey(t *testing.T) { doc := `{ "title": "hello", "nested": {"one": 1, "two": 2} }` pat := `{ "title": "goodbye", "nested": {"one": 2, "two": 2} }` exp := `{ "title": "goodbye", "nested": {"one": 2} }` res, err := CreateMergePatch([]byte(doc), []byte(pat)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } if !compareJSON(exp, string(res)) { t.Fatalf("Key was not replaced") } } func TestMergeGetArray(t *testing.T) { doc := `{ "title": "hello", "array": ["one", "two"], "notmatch": [1, 2, 3] }` pat := `{ "title": "hello", "array": ["one", "two", "three"], "notmatch": [1, 2, 3] }` exp := `{ "array": ["one", "two", "three"] }` res, err := CreateMergePatch([]byte(doc), []byte(pat)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } if !compareJSON(exp, string(res)) { t.Fatalf("Array was not added") } } func TestMergeGetObjArray(t *testing.T) { doc := `{ "title": "hello", "array": [{"banana": true}, {"evil": false}], "notmatch": [{"one":1}, {"two":2}, {"three":3}] }` pat := `{ "title": "hello", "array": [{"banana": false}, {"evil": true}], "notmatch": [{"one":1}, {"two":2}, {"three":3}] }` exp := `{ "array": [{"banana": false}, {"evil": true}] }` res, err := CreateMergePatch([]byte(doc), []byte(pat)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } if !compareJSON(exp, string(res)) { t.Fatalf("Object array was not added") } } func TestMergeDeleteKey(t *testing.T) { doc := `{ "title": "hello", "nested": {"one": 1, "two": 2} }` pat := `{ "title": "hello", "nested": {"one": 1} }` exp := `{"nested":{"two":null}}` res, err := CreateMergePatch([]byte(doc), []byte(pat)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } // We cannot use "compareJSON", since Equals does not report a difference if the value is null if exp != string(res) { t.Fatalf("Key was not removed") } } func TestMergeEmptyArray(t *testing.T) { doc := `{ "array": null }` pat := `{ "array": [] }` exp := `{"array":[]}` res, err := CreateMergePatch([]byte(doc), []byte(pat)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } // We cannot use "compareJSON", since Equals does not report a difference if the value is null if exp != string(res) { t.Fatalf("Key was not removed") } } func TestMergeObjArray(t *testing.T) { doc := `{ "array": [ {"a": {"b": 2}}, {"a": {"b": 3}} ]}` exp := `{}` res, err := CreateMergePatch([]byte(doc), []byte(doc)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } // We cannot use "compareJSON", since Equals does not report a difference if the value is null if exp != string(res) { t.Fatalf("Array was not empty, was " + string(res)) } } func TestMergeComplexMatch(t *testing.T) { doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` empty := `{}` res, err := CreateMergePatch([]byte(doc), []byte(doc)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } // We cannot use "compareJSON", since Equals does not report a difference if the value is null if empty != string(res) { t.Fatalf("Did not get empty result, was:%s", string(res)) } } func TestMergeComplexAddAll(t *testing.T) { doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` empty := `{}` res, err := CreateMergePatch([]byte(empty), []byte(doc)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } if !compareJSON(doc, string(res)) { t.Fatalf("Did not get everything as, it was:\n%s", string(res)) } } func TestMergeComplexRemoveAll(t *testing.T) { doc := `{"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4], "nested": {"hello": "world","t": true ,"f": false, "n": null,"i": 123,"pi": 3.1416,"a": [1, 2, 3, 4]} }` exp := `{"a":null,"f":null,"hello":null,"i":null,"n":null,"nested":null,"pi":null,"t":null}` empty := `{}` res, err := CreateMergePatch([]byte(doc), []byte(empty)) if err != nil { t.Errorf("Unexpected error: %s, %s", err, string(res)) } if exp != string(res) { t.Fatalf("Did not get result, was:%s", string(res)) } // FIXME: Crashes if using compareJSON like this: /* if !compareJSON(doc, string(res)) { t.Fatalf("Did not get everything as, it was:\n%s", string(res)) } */ } ================================================ FILE: vendor/github.com/evanphx/json-patch/patch.go ================================================ package jsonpatch import ( "bytes" "encoding/json" "fmt" "strconv" "strings" ) const ( eRaw = iota eDoc eAry ) type lazyNode struct { raw *json.RawMessage doc partialDoc ary partialArray which int } type operation map[string]*json.RawMessage // Patch is an ordered collection of operations. type Patch []operation type partialDoc map[string]*lazyNode type partialArray []*lazyNode type container interface { get(key string) (*lazyNode, error) set(key string, val *lazyNode) error remove(key string) error } func newLazyNode(raw *json.RawMessage) *lazyNode { return &lazyNode{raw: raw, doc: nil, ary: nil, which: eRaw} } func (n *lazyNode) MarshalJSON() ([]byte, error) { switch n.which { case eRaw: return *n.raw, nil case eDoc: return json.Marshal(n.doc) case eAry: return json.Marshal(n.ary) default: return nil, fmt.Errorf("Unknown type") } } func (n *lazyNode) UnmarshalJSON(data []byte) error { dest := make(json.RawMessage, len(data)) copy(dest, data) n.raw = &dest n.which = eRaw return nil } func (n *lazyNode) intoDoc() (*partialDoc, error) { if n.which == eDoc { return &n.doc, nil } err := json.Unmarshal(*n.raw, &n.doc) if err != nil { return nil, err } n.which = eDoc return &n.doc, nil } func (n *lazyNode) intoAry() (*partialArray, error) { if n.which == eAry { return &n.ary, nil } err := json.Unmarshal(*n.raw, &n.ary) if err != nil { return nil, err } n.which = eAry return &n.ary, nil } func (n *lazyNode) compact() []byte { buf := &bytes.Buffer{} err := json.Compact(buf, *n.raw) if err != nil { return *n.raw } return buf.Bytes() } func (n *lazyNode) tryDoc() bool { err := json.Unmarshal(*n.raw, &n.doc) if err != nil { return false } n.which = eDoc return true } func (n *lazyNode) tryAry() bool { err := json.Unmarshal(*n.raw, &n.ary) if err != nil { return false } n.which = eAry return true } func (n *lazyNode) equal(o *lazyNode) bool { if n.which == eRaw { if !n.tryDoc() && !n.tryAry() { if o.which != eRaw { return false } return bytes.Equal(n.compact(), o.compact()) } } if n.which == eDoc { if o.which == eRaw { if !o.tryDoc() { return false } } if o.which != eDoc { return false } for k, v := range n.doc { ov, ok := o.doc[k] if !ok { return false } if v == nil && ov == nil { continue } if !v.equal(ov) { return false } } return true } if o.which != eAry && !o.tryAry() { return false } if len(n.ary) != len(o.ary) { return false } for idx, val := range n.ary { if !val.equal(o.ary[idx]) { return false } } return true } func (o operation) kind() string { if obj, ok := o["op"]; ok { var op string err := json.Unmarshal(*obj, &op) if err != nil { return "unknown" } return op } return "unknown" } func (o operation) path() string { if obj, ok := o["path"]; ok { var op string err := json.Unmarshal(*obj, &op) if err != nil { return "unknown" } return op } return "unknown" } func (o operation) from() string { if obj, ok := o["from"]; ok { var op string err := json.Unmarshal(*obj, &op) if err != nil { return "unknown" } return op } return "unknown" } func (o operation) value() *lazyNode { if obj, ok := o["value"]; ok { return newLazyNode(obj) } return nil } func isArray(buf []byte) bool { Loop: for _, c := range buf { switch c { case ' ': case '\n': case '\t': continue case '[': return true default: break Loop } } return false } func findObject(pd *partialDoc, path string) (container, string) { doc := container(pd) split := strings.Split(path, "/") parts := split[1 : len(split)-1] key := split[len(split)-1] var err error for _, part := range parts { next, ok := doc.get(part) if next == nil || ok != nil { return nil, "" } if isArray(*next.raw) { doc, err = next.intoAry() if err != nil { return nil, "" } } else { doc, err = next.intoDoc() if err != nil { return nil, "" } } } return doc, key } func (d *partialDoc) set(key string, val *lazyNode) error { (*d)[key] = val return nil } func (d *partialDoc) get(key string) (*lazyNode, error) { return (*d)[key], nil } func (d *partialDoc) remove(key string) error { delete(*d, key) return nil } func (d *partialArray) set(key string, val *lazyNode) error { if key == "-" { *d = append(*d, val) return nil } idx, err := strconv.Atoi(key) if err != nil { return err } ary := make([]*lazyNode, len(*d)+1) cur := *d copy(ary[0:idx], cur[0:idx]) ary[idx] = val copy(ary[idx+1:], cur[idx:]) *d = ary return nil } func (d *partialArray) get(key string) (*lazyNode, error) { idx, err := strconv.Atoi(key) if err != nil { return nil, err } return (*d)[idx], nil } func (d *partialArray) remove(key string) error { idx, err := strconv.Atoi(key) if err != nil { return err } cur := *d ary := make([]*lazyNode, len(cur)-1) copy(ary[0:idx], cur[0:idx]) copy(ary[idx:], cur[idx+1:]) *d = ary return nil } func (p Patch) add(doc *partialDoc, op operation) error { path := op.path() con, key := findObject(doc, path) if con == nil { return fmt.Errorf("Missing container: %s", path) } con.set(key, op.value()) return nil } func (p Patch) remove(doc *partialDoc, op operation) error { path := op.path() con, key := findObject(doc, path) return con.remove(key) } func (p Patch) replace(doc *partialDoc, op operation) error { path := op.path() con, key := findObject(doc, path) con.set(key, op.value()) return nil } func (p Patch) move(doc *partialDoc, op operation) error { from := op.from() con, key := findObject(doc, from) val, err := con.get(key) if err != nil { return err } con.remove(key) path := op.path() con, key = findObject(doc, path) con.set(key, val) return nil } func (p Patch) test(doc *partialDoc, op operation) error { path := op.path() con, key := findObject(doc, path) val, err := con.get(key) if err != nil { return err } if val.equal(op.value()) { return nil } return fmt.Errorf("Testing value %s failed", path) } // Equal indicates if 2 JSON documents have the same structural equality. func Equal(a, b []byte) bool { ra := make(json.RawMessage, len(a)) copy(ra, a) la := newLazyNode(&ra) rb := make(json.RawMessage, len(b)) copy(rb, b) lb := newLazyNode(&rb) return la.equal(lb) } // DecodePatch decodes the passed JSON document as an RFC 6902 patch. func DecodePatch(buf []byte) (Patch, error) { var p Patch err := json.Unmarshal(buf, &p) if err != nil { return nil, err } return p, nil } // Apply mutates a JSON document according to the patch, and returns the new // document. func (p Patch) Apply(doc []byte) ([]byte, error) { pd := &partialDoc{} err := json.Unmarshal(doc, pd) if err != nil { return nil, err } err = nil for _, op := range p { switch op.kind() { case "add": err = p.add(pd, op) case "remove": err = p.remove(pd, op) case "replace": err = p.replace(pd, op) case "move": err = p.move(pd, op) case "test": err = p.test(pd, op) default: err = fmt.Errorf("Unexpected kind: %s", op.kind()) } if err != nil { return nil, err } } return json.Marshal(pd) } ================================================ FILE: vendor/github.com/evanphx/json-patch/patch_test.go ================================================ package jsonpatch import ( "bytes" "encoding/json" "fmt" "reflect" "testing" ) func reformatJSON(j string) string { buf := new(bytes.Buffer) json.Indent(buf, []byte(j), "", " ") return buf.String() } func compareJSON(a, b string) bool { // return Equal([]byte(a), []byte(b)) var obj_a, obj_b map[string]interface{} json.Unmarshal([]byte(a), &obj_a) json.Unmarshal([]byte(b), &obj_b) // fmt.Printf("Comparing %#v\nagainst %#v\n", obj_a, obj_b) return reflect.DeepEqual(obj_a, obj_b) } func applyPatch(doc, patch string) (string, error) { obj, err := DecodePatch([]byte(patch)) if err != nil { panic(err) } out, err := obj.Apply([]byte(doc)) if err != nil { return "", err } return string(out), nil } type Case struct { doc, patch, result string } var Cases = []Case{ { `{ "foo": "bar"}`, `[ { "op": "add", "path": "/baz", "value": "qux" } ]`, `{ "baz": "qux", "foo": "bar" }`, }, { `{ "foo": [ "bar", "baz" ] }`, `[ { "op": "add", "path": "/foo/1", "value": "qux" } ]`, `{ "foo": [ "bar", "qux", "baz" ] }`, }, { `{ "baz": "qux", "foo": "bar" }`, `[ { "op": "remove", "path": "/baz" } ]`, `{ "foo": "bar" }`, }, { `{ "foo": [ "bar", "qux", "baz" ] }`, `[ { "op": "remove", "path": "/foo/1" } ]`, `{ "foo": [ "bar", "baz" ] }`, }, { `{ "baz": "qux", "foo": "bar" }`, `[ { "op": "replace", "path": "/baz", "value": "boo" } ]`, `{ "baz": "boo", "foo": "bar" }`, }, { `{ "foo": { "bar": "baz", "waldo": "fred" }, "qux": { "corge": "grault" } }`, `[ { "op": "move", "from": "/foo/waldo", "path": "/qux/thud" } ]`, `{ "foo": { "bar": "baz" }, "qux": { "corge": "grault", "thud": "fred" } }`, }, { `{ "foo": [ "all", "grass", "cows", "eat" ] }`, `[ { "op": "move", "from": "/foo/1", "path": "/foo/3" } ]`, `{ "foo": [ "all", "cows", "eat", "grass" ] }`, }, { `{ "foo": "bar" }`, `[ { "op": "add", "path": "/child", "value": { "grandchild": { } } } ]`, `{ "foo": "bar", "child": { "grandchild": { } } }`, }, { `{ "foo": ["bar"] }`, `[ { "op": "add", "path": "/foo/-", "value": ["abc", "def"] } ]`, `{ "foo": ["bar", ["abc", "def"]] }`, }, { `{ "foo": "bar", "qux": { "baz": 1, "bar": null } }`, `[ { "op": "remove", "path": "/qux/bar" } ]`, `{ "foo": "bar", "qux": { "baz": 1 } }`, }, } type BadCase struct { doc, patch string } var MutationTestCases = []BadCase{ { `{ "foo": "bar", "qux": { "baz": 1, "bar": null } }`, `[ { "op": "remove", "path": "/qux/bar" } ]`, }, } var BadCases = []BadCase{ { `{ "foo": "bar" }`, `[ { "op": "add", "path": "/baz/bat", "value": "qux" } ]`, }, } func TestAllCases(t *testing.T) { for _, c := range Cases { out, err := applyPatch(c.doc, c.patch) if err != nil { t.Errorf("Unable to apply patch: %s", err) } if !compareJSON(out, c.result) { t.Errorf("Patch did not apply. Expected:\n%s\n\nActual:\n%s", reformatJSON(c.result), reformatJSON(out)) } } for _, c := range MutationTestCases { out, err := applyPatch(c.doc, c.patch) if err != nil { t.Errorf("Unable to apply patch: %s", err) } if compareJSON(out, c.doc) { t.Errorf("Patch did not apply. Original:\n%s\n\nPatched:\n%s", reformatJSON(c.doc), reformatJSON(out)) } } for _, c := range BadCases { _, err := applyPatch(c.doc, c.patch) if err == nil { t.Errorf("Patch should have failed to apply but it did not") } } } type TestCase struct { doc, patch string result bool failedPath string } var TestCases = []TestCase{ { `{ "baz": "qux", "foo": [ "a", 2, "c" ] }`, `[ { "op": "test", "path": "/baz", "value": "qux" }, { "op": "test", "path": "/foo/1", "value": 2 } ]`, true, "", }, { `{ "baz": "qux" }`, `[ { "op": "test", "path": "/baz", "value": "bar" } ]`, false, "/baz", }, { `{ "baz": "qux", "foo": ["a", 2, "c"] }`, `[ { "op": "test", "path": "/baz", "value": "qux" }, { "op": "test", "path": "/foo/1", "value": "c" } ]`, false, "/foo/1", }, } func TestAllTest(t *testing.T) { for _, c := range TestCases { _, err := applyPatch(c.doc, c.patch) if c.result && err != nil { t.Errorf("Testing failed when it should have passed: %s", err) } else if !c.result && err == nil { t.Errorf("Testing passed when it should have faild: %s", err) } else if !c.result { expected := fmt.Sprintf("Testing value %s failed", c.failedPath) if err.Error() != expected { t.Errorf("Testing failed as expected but invalid message: expected [%s], got [%s]", expected, err) } } } } ================================================ FILE: vendor/github.com/fatih/color/.travis.yml ================================================ language: go go: - 1.6 - tip ================================================ FILE: vendor/github.com/fatih/color/LICENSE.md ================================================ The MIT License (MIT) Copyright (c) 2013 Fatih Arslan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: vendor/github.com/fatih/color/README.md ================================================ # Color [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/color) [![Build Status](http://img.shields.io/travis/fatih/color.svg?style=flat-square)](https://travis-ci.org/fatih/color) Color lets you use colorized outputs in terms of [ANSI Escape Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It has support for Windows too! The API can be used in several ways, pick one that suits you. ![Color](http://i.imgur.com/c1JI0lA.png) ## Install ```bash go get github.com/fatih/color ``` ## Examples ### Standard colors ```go // Print with default helper functions color.Cyan("Prints text in cyan.") // A newline will be appended automatically color.Blue("Prints %s in blue.", "text") // These are using the default foreground colors color.Red("We have red") color.Magenta("And many others ..") ``` ### Mix and reuse colors ```go // Create a new color object c := color.New(color.FgCyan).Add(color.Underline) c.Println("Prints cyan text with an underline.") // Or just add them to New() d := color.New(color.FgCyan, color.Bold) d.Printf("This prints bold cyan %s\n", "too!.") // Mix up foreground and background colors, create new mixes! red := color.New(color.FgRed) boldRed := red.Add(color.Bold) boldRed.Println("This will print text in bold red.") whiteBackground := red.Add(color.BgWhite) whiteBackground.Println("Red text with white background.") ``` ### Custom print functions (PrintFunc) ```go // Create a custom print function for convenience red := color.New(color.FgRed).PrintfFunc() red("Warning") red("Error: %s", err) // Mix up multiple attributes notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() notice("Don't forget this...") ``` ### Insert into noncolor strings (SprintFunc) ```go // Create SprintXxx functions to mix strings with other non-colorized strings: yellow := color.New(color.FgYellow).SprintFunc() red := color.New(color.FgRed).SprintFunc() fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error")) info := color.New(color.FgWhite, color.BgGreen).SprintFunc() fmt.Printf("This %s rocks!\n", info("package")) // Use helper functions fmt.Printf("This", color.RedString("warning"), "should be not neglected.") fmt.Printf(color.GreenString("Info:"), "an important message." ) // Windows supported too! Just don't forget to change the output to color.Output fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) ``` ### Plug into existing code ```go // Use handy standard colors color.Set(color.FgYellow) fmt.Println("Existing text will now be in yellow") fmt.Printf("This one %s\n", "too") color.Unset() // Don't forget to unset // You can mix up parameters color.Set(color.FgMagenta, color.Bold) defer color.Unset() // Use it in your function fmt.Println("All text will now be bold magenta.") ``` ### Disable color There might be a case where you want to disable color output (for example to pipe the standard output of your app to somewhere else). `Color` has support to disable colors both globally and for single color definition. For example suppose you have a CLI app and a `--no-color` bool flag. You can easily disable the color output with: ```go var flagNoColor = flag.Bool("no-color", false, "Disable color output") if *flagNoColor { color.NoColor = true // disables colorized output } ``` It also has support for single color definitions (local). You can disable/enable color output on the fly: ```go c := color.New(color.FgCyan) c.Println("Prints cyan text") c.DisableColor() c.Println("This is printed without any color") c.EnableColor() c.Println("This prints again cyan...") ``` ## Todo * Save/Return previous values * Evaluate fmt.Formatter interface ## Credits * [Fatih Arslan](https://github.com/fatih) * Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable) ## License The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details ================================================ FILE: vendor/github.com/fatih/color/color.go ================================================ package color import ( "fmt" "os" "strconv" "strings" "github.com/mattn/go-colorable" "github.com/mattn/go-isatty" ) // NoColor defines if the output is colorized or not. It's dynamically set to // false or true based on the stdout's file descriptor referring to a terminal // or not. This is a global option and affects all colors. For more control // over each color block use the methods DisableColor() individually. var NoColor = !isatty.IsTerminal(os.Stdout.Fd()) // Color defines a custom color object which is defined by SGR parameters. type Color struct { params []Attribute noColor *bool } // Attribute defines a single SGR Code type Attribute int const escape = "\x1b" // Base attributes const ( Reset Attribute = iota Bold Faint Italic Underline BlinkSlow BlinkRapid ReverseVideo Concealed CrossedOut ) // Foreground text colors const ( FgBlack Attribute = iota + 30 FgRed FgGreen FgYellow FgBlue FgMagenta FgCyan FgWhite ) // Foreground Hi-Intensity text colors const ( FgHiBlack Attribute = iota + 90 FgHiRed FgHiGreen FgHiYellow FgHiBlue FgHiMagenta FgHiCyan FgHiWhite ) // Background text colors const ( BgBlack Attribute = iota + 40 BgRed BgGreen BgYellow BgBlue BgMagenta BgCyan BgWhite ) // Background Hi-Intensity text colors const ( BgHiBlack Attribute = iota + 100 BgHiRed BgHiGreen BgHiYellow BgHiBlue BgHiMagenta BgHiCyan BgHiWhite ) // New returns a newly created color object. func New(value ...Attribute) *Color { c := &Color{params: make([]Attribute, 0)} c.Add(value...) return c } // Set sets the given parameters immediately. It will change the color of // output with the given SGR parameters until color.Unset() is called. func Set(p ...Attribute) *Color { c := New(p...) c.Set() return c } // Unset resets all escape attributes and clears the output. Usually should // be called after Set(). func Unset() { if NoColor { return } fmt.Fprintf(Output, "%s[%dm", escape, Reset) } // Set sets the SGR sequence. func (c *Color) Set() *Color { if c.isNoColorSet() { return c } fmt.Fprintf(Output, c.format()) return c } func (c *Color) unset() { if c.isNoColorSet() { return } Unset() } // Add is used to chain SGR parameters. Use as many as parameters to combine // and create custom color objects. Example: Add(color.FgRed, color.Underline). func (c *Color) Add(value ...Attribute) *Color { c.params = append(c.params, value...) return c } func (c *Color) prepend(value Attribute) { c.params = append(c.params, 0) copy(c.params[1:], c.params[0:]) c.params[0] = value } // Output defines the standard output of the print functions. By default // os.Stdout is used. var Output = colorable.NewColorableStdout() // Print formats using the default formats for its operands and writes to // standard output. Spaces are added between operands when neither is a // string. It returns the number of bytes written and any write error // encountered. This is the standard fmt.Print() method wrapped with the given // color. func (c *Color) Print(a ...interface{}) (n int, err error) { c.Set() defer c.unset() return fmt.Fprint(Output, a...) } // Printf formats according to a format specifier and writes to standard output. // It returns the number of bytes written and any write error encountered. // This is the standard fmt.Printf() method wrapped with the given color. func (c *Color) Printf(format string, a ...interface{}) (n int, err error) { c.Set() defer c.unset() return fmt.Fprintf(Output, format, a...) } // Println formats using the default formats for its operands and writes to // standard output. Spaces are always added between operands and a newline is // appended. It returns the number of bytes written and any write error // encountered. This is the standard fmt.Print() method wrapped with the given // color. func (c *Color) Println(a ...interface{}) (n int, err error) { c.Set() defer c.unset() return fmt.Fprintln(Output, a...) } // PrintFunc returns a new function that prints the passed arguments as // colorized with color.Print(). func (c *Color) PrintFunc() func(a ...interface{}) { return func(a ...interface{}) { c.Print(a...) } } // PrintfFunc returns a new function that prints the passed arguments as // colorized with color.Printf(). func (c *Color) PrintfFunc() func(format string, a ...interface{}) { return func(format string, a ...interface{}) { c.Printf(format, a...) } } // PrintlnFunc returns a new function that prints the passed arguments as // colorized with color.Println(). func (c *Color) PrintlnFunc() func(a ...interface{}) { return func(a ...interface{}) { c.Println(a...) } } // SprintFunc returns a new function that returns colorized strings for the // given arguments with fmt.Sprint(). Useful to put into or mix into other // string. Windows users should use this in conjuction with color.Output, example: // // put := New(FgYellow).SprintFunc() // fmt.Fprintf(color.Output, "This is a %s", put("warning")) func (c *Color) SprintFunc() func(a ...interface{}) string { return func(a ...interface{}) string { return c.wrap(fmt.Sprint(a...)) } } // SprintfFunc returns a new function that returns colorized strings for the // given arguments with fmt.Sprintf(). Useful to put into or mix into other // string. Windows users should use this in conjuction with color.Output. func (c *Color) SprintfFunc() func(format string, a ...interface{}) string { return func(format string, a ...interface{}) string { return c.wrap(fmt.Sprintf(format, a...)) } } // SprintlnFunc returns a new function that returns colorized strings for the // given arguments with fmt.Sprintln(). Useful to put into or mix into other // string. Windows users should use this in conjuction with color.Output. func (c *Color) SprintlnFunc() func(a ...interface{}) string { return func(a ...interface{}) string { return c.wrap(fmt.Sprintln(a...)) } } // sequence returns a formated SGR sequence to be plugged into a "\x1b[...m" // an example output might be: "1;36" -> bold cyan func (c *Color) sequence() string { format := make([]string, len(c.params)) for i, v := range c.params { format[i] = strconv.Itoa(int(v)) } return strings.Join(format, ";") } // wrap wraps the s string with the colors attributes. The string is ready to // be printed. func (c *Color) wrap(s string) string { if c.isNoColorSet() { return s } return c.format() + s + c.unformat() } func (c *Color) format() string { return fmt.Sprintf("%s[%sm", escape, c.sequence()) } func (c *Color) unformat() string { return fmt.Sprintf("%s[%dm", escape, Reset) } // DisableColor disables the color output. Useful to not change any existing // code and still being able to output. Can be used for flags like // "--no-color". To enable back use EnableColor() method. func (c *Color) DisableColor() { c.noColor = boolPtr(true) } // EnableColor enables the color output. Use it in conjuction with // DisableColor(). Otherwise this method has no side effects. func (c *Color) EnableColor() { c.noColor = boolPtr(false) } func (c *Color) isNoColorSet() bool { // check first if we have user setted action if c.noColor != nil { return *c.noColor } // if not return the global option, which is disabled by default return NoColor } // Equals returns a boolean value indicating whether two colors are equal. func (c *Color) Equals(c2 *Color) bool { if len(c.params) != len(c2.params) { return false } for _, attr := range c.params { if !c2.attrExists(attr) { return false } } return true } func (c *Color) attrExists(a Attribute) bool { for _, attr := range c.params { if attr == a { return true } } return false } func boolPtr(v bool) *bool { return &v } // Black is an convenient helper function to print with black foreground. A // newline is appended to format by default. func Black(format string, a ...interface{}) { printColor(format, FgBlack, a...) } // Red is an convenient helper function to print with red foreground. A // newline is appended to format by default. func Red(format string, a ...interface{}) { printColor(format, FgRed, a...) } // Green is an convenient helper function to print with green foreground. A // newline is appended to format by default. func Green(format string, a ...interface{}) { printColor(format, FgGreen, a...) } // Yellow is an convenient helper function to print with yellow foreground. // A newline is appended to format by default. func Yellow(format string, a ...interface{}) { printColor(format, FgYellow, a...) } // Blue is an convenient helper function to print with blue foreground. A // newline is appended to format by default. func Blue(format string, a ...interface{}) { printColor(format, FgBlue, a...) } // Magenta is an convenient helper function to print with magenta foreground. // A newline is appended to format by default. func Magenta(format string, a ...interface{}) { printColor(format, FgMagenta, a...) } // Cyan is an convenient helper function to print with cyan foreground. A // newline is appended to format by default. func Cyan(format string, a ...interface{}) { printColor(format, FgCyan, a...) } // White is an convenient helper function to print with white foreground. A // newline is appended to format by default. func White(format string, a ...interface{}) { printColor(format, FgWhite, a...) } func printColor(format string, p Attribute, a ...interface{}) { if !strings.HasSuffix(format, "\n") { format += "\n" } c := &Color{params: []Attribute{p}} c.Printf(format, a...) } // BlackString is an convenient helper function to return a string with black // foreground. func BlackString(format string, a ...interface{}) string { return New(FgBlack).SprintfFunc()(format, a...) } // RedString is an convenient helper function to return a string with red // foreground. func RedString(format string, a ...interface{}) string { return New(FgRed).SprintfFunc()(format, a...) } // GreenString is an convenient helper function to return a string with green // foreground. func GreenString(format string, a ...interface{}) string { return New(FgGreen).SprintfFunc()(format, a...) } // YellowString is an convenient helper function to return a string with yellow // foreground. func YellowString(format string, a ...interface{}) string { return New(FgYellow).SprintfFunc()(format, a...) } // BlueString is an convenient helper function to return a string with blue // foreground. func BlueString(format string, a ...interface{}) string { return New(FgBlue).SprintfFunc()(format, a...) } // MagentaString is an convenient helper function to return a string with magenta // foreground. func MagentaString(format string, a ...interface{}) string { return New(FgMagenta).SprintfFunc()(format, a...) } // CyanString is an convenient helper function to return a string with cyan // foreground. func CyanString(format string, a ...interface{}) string { return New(FgCyan).SprintfFunc()(format, a...) } // WhiteString is an convenient helper function to return a string with white // foreground. func WhiteString(format string, a ...interface{}) string { return New(FgWhite).SprintfFunc()(format, a...) } ================================================ FILE: vendor/github.com/fatih/color/color_test.go ================================================ package color import ( "bytes" "fmt" "testing" "github.com/mattn/go-colorable" ) // Testing colors is kinda different. First we test for given colors and their // escaped formatted results. Next we create some visual tests to be tested. // Each visual test includes the color name to be compared. func TestColor(t *testing.T) { rb := new(bytes.Buffer) Output = rb NoColor = false testColors := []struct { text string code Attribute }{ {text: "black", code: FgBlack}, {text: "red", code: FgRed}, {text: "green", code: FgGreen}, {text: "yellow", code: FgYellow}, {text: "blue", code: FgBlue}, {text: "magent", code: FgMagenta}, {text: "cyan", code: FgCyan}, {text: "white", code: FgWhite}, {text: "hblack", code: FgHiBlack}, {text: "hred", code: FgHiRed}, {text: "hgreen", code: FgHiGreen}, {text: "hyellow", code: FgHiYellow}, {text: "hblue", code: FgHiBlue}, {text: "hmagent", code: FgHiMagenta}, {text: "hcyan", code: FgHiCyan}, {text: "hwhite", code: FgHiWhite}, } for _, c := range testColors { New(c.code).Print(c.text) line, _ := rb.ReadString('\n') scannedLine := fmt.Sprintf("%q", line) colored := fmt.Sprintf("\x1b[%dm%s\x1b[0m", c.code, c.text) escapedForm := fmt.Sprintf("%q", colored) fmt.Printf("%s\t: %s\n", c.text, line) if scannedLine != escapedForm { t.Errorf("Expecting %s, got '%s'\n", escapedForm, scannedLine) } } } func TestColorEquals(t *testing.T) { fgblack1 := New(FgBlack) fgblack2 := New(FgBlack) bgblack := New(BgBlack) fgbgblack := New(FgBlack, BgBlack) fgblackbgred := New(FgBlack, BgRed) fgred := New(FgRed) bgred := New(BgRed) if !fgblack1.Equals(fgblack2) { t.Error("Two black colors are not equal") } if fgblack1.Equals(bgblack) { t.Error("Fg and bg black colors are equal") } if fgblack1.Equals(fgbgblack) { t.Error("Fg black equals fg/bg black color") } if fgblack1.Equals(fgred) { t.Error("Fg black equals Fg red") } if fgblack1.Equals(bgred) { t.Error("Fg black equals Bg red") } if fgblack1.Equals(fgblackbgred) { t.Error("Fg black equals fg black bg red") } } func TestNoColor(t *testing.T) { rb := new(bytes.Buffer) Output = rb testColors := []struct { text string code Attribute }{ {text: "black", code: FgBlack}, {text: "red", code: FgRed}, {text: "green", code: FgGreen}, {text: "yellow", code: FgYellow}, {text: "blue", code: FgBlue}, {text: "magent", code: FgMagenta}, {text: "cyan", code: FgCyan}, {text: "white", code: FgWhite}, {text: "hblack", code: FgHiBlack}, {text: "hred", code: FgHiRed}, {text: "hgreen", code: FgHiGreen}, {text: "hyellow", code: FgHiYellow}, {text: "hblue", code: FgHiBlue}, {text: "hmagent", code: FgHiMagenta}, {text: "hcyan", code: FgHiCyan}, {text: "hwhite", code: FgHiWhite}, } for _, c := range testColors { p := New(c.code) p.DisableColor() p.Print(c.text) line, _ := rb.ReadString('\n') if line != c.text { t.Errorf("Expecting %s, got '%s'\n", c.text, line) } } // global check NoColor = true defer func() { NoColor = false }() for _, c := range testColors { p := New(c.code) p.Print(c.text) line, _ := rb.ReadString('\n') if line != c.text { t.Errorf("Expecting %s, got '%s'\n", c.text, line) } } } func TestColorVisual(t *testing.T) { // First Visual Test Output = colorable.NewColorableStdout() New(FgRed).Printf("red\t") New(BgRed).Print(" ") New(FgRed, Bold).Println(" red") New(FgGreen).Printf("green\t") New(BgGreen).Print(" ") New(FgGreen, Bold).Println(" green") New(FgYellow).Printf("yellow\t") New(BgYellow).Print(" ") New(FgYellow, Bold).Println(" yellow") New(FgBlue).Printf("blue\t") New(BgBlue).Print(" ") New(FgBlue, Bold).Println(" blue") New(FgMagenta).Printf("magenta\t") New(BgMagenta).Print(" ") New(FgMagenta, Bold).Println(" magenta") New(FgCyan).Printf("cyan\t") New(BgCyan).Print(" ") New(FgCyan, Bold).Println(" cyan") New(FgWhite).Printf("white\t") New(BgWhite).Print(" ") New(FgWhite, Bold).Println(" white") fmt.Println("") // Second Visual test Black("black") Red("red") Green("green") Yellow("yellow") Blue("blue") Magenta("magenta") Cyan("cyan") White("white") // Third visual test fmt.Println() Set(FgBlue) fmt.Println("is this blue?") Unset() Set(FgMagenta) fmt.Println("and this magenta?") Unset() // Fourth Visual test fmt.Println() blue := New(FgBlue).PrintlnFunc() blue("blue text with custom print func") red := New(FgRed).PrintfFunc() red("red text with a printf func: %d\n", 123) put := New(FgYellow).SprintFunc() warn := New(FgRed).SprintFunc() fmt.Fprintf(Output, "this is a %s and this is %s.\n", put("warning"), warn("error")) info := New(FgWhite, BgGreen).SprintFunc() fmt.Fprintf(Output, "this %s rocks!\n", info("package")) // Fifth Visual Test fmt.Println() fmt.Fprintln(Output, BlackString("black")) fmt.Fprintln(Output, RedString("red")) fmt.Fprintln(Output, GreenString("green")) fmt.Fprintln(Output, YellowString("yellow")) fmt.Fprintln(Output, BlueString("blue")) fmt.Fprintln(Output, MagentaString("magenta")) fmt.Fprintln(Output, CyanString("cyan")) fmt.Fprintln(Output, WhiteString("white")) } ================================================ FILE: vendor/github.com/fatih/color/doc.go ================================================ /* Package color is an ANSI color package to output colorized or SGR defined output to the standard output. The API can be used in several way, pick one that suits you. Use simple and default helper functions with predefined foreground colors: color.Cyan("Prints text in cyan.") // a newline will be appended automatically color.Blue("Prints %s in blue.", "text") // More default foreground colors.. color.Red("We have red") color.Yellow("Yellow color too!") color.Magenta("And many others ..") However there are times where custom color mixes are required. Below are some examples to create custom color objects and use the print functions of each separate color object. // Create a new color object c := color.New(color.FgCyan).Add(color.Underline) c.Println("Prints cyan text with an underline.") // Or just add them to New() d := color.New(color.FgCyan, color.Bold) d.Printf("This prints bold cyan %s\n", "too!.") // Mix up foreground and background colors, create new mixes! red := color.New(color.FgRed) boldRed := red.Add(color.Bold) boldRed.Println("This will print text in bold red.") whiteBackground := red.Add(color.BgWhite) whiteBackground.Println("Red text with White background.") You can create PrintXxx functions to simplify even more: // Create a custom print function for convenient red := color.New(color.FgRed).PrintfFunc() red("warning") red("error: %s", err) // Mix up multiple attributes notice := color.New(color.Bold, color.FgGreen).PrintlnFunc() notice("don't forget this...") Or create SprintXxx functions to mix strings with other non-colorized strings: yellow := New(FgYellow).SprintFunc() red := New(FgRed).SprintFunc() fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error")) info := New(FgWhite, BgGreen).SprintFunc() fmt.Printf("this %s rocks!\n", info("package")) Windows support is enabled by default. All Print functions works as intended. However only for color.SprintXXX functions, user should use fmt.FprintXXX and set the output to color.Output: fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS")) info := New(FgWhite, BgGreen).SprintFunc() fmt.Fprintf(color.Output, "this %s rocks!\n", info("package")) Using with existing code is possible. Just use the Set() method to set the standard output to the given parameters. That way a rewrite of an existing code is not required. // Use handy standard colors. color.Set(color.FgYellow) fmt.Println("Existing text will be now in Yellow") fmt.Printf("This one %s\n", "too") color.Unset() // don't forget to unset // You can mix up parameters color.Set(color.FgMagenta, color.Bold) defer color.Unset() // use it in your function fmt.Println("All text will be now bold magenta.") There might be a case where you want to disable color output (for example to pipe the standard output of your app to somewhere else). `Color` has support to disable colors both globally and for single color definition. For example suppose you have a CLI app and a `--no-color` bool flag. You can easily disable the color output with: var flagNoColor = flag.Bool("no-color", false, "Disable color output") if *flagNoColor { color.NoColor = true // disables colorized output } It also has support for single color definitions (local). You can disable/enable color output on the fly: c := color.New(color.FgCyan) c.Println("Prints cyan text") c.DisableColor() c.Println("This is printed without any color") c.EnableColor() c.Println("This prints again cyan...") */ package color ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/.gitignore ================================================ # temporary symlink for testing testing/data/symlink ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/.travis.yml ================================================ language: go sudo: required go: - 1.3.3 - 1.4.2 - 1.5.3 - 1.6rc2 - tip env: - GOARCH=amd64 DOCKER_VERSION=1.7.1 - GOARCH=386 DOCKER_VERSION=1.7.1 - GOARCH=amd64 DOCKER_VERSION=1.8.3 - GOARCH=386 DOCKER_VERSION=1.8.3 - GOARCH=amd64 DOCKER_VERSION=1.9.1 - GOARCH=386 DOCKER_VERSION=1.9.1 - GOARCH=amd64 DOCKER_VERSION=1.10.0 - GOARCH=386 DOCKER_VERSION=1.10.0 install: - make prepare_docker script: - make test - DOCKER_HOST=tcp://127.0.0.1:2375 make integration services: - docker ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/AUTHORS ================================================ # This is the official list of go-dockerclient authors for copyright purposes. Abhishek Chanda Adam Bell-Hanssen Adrien Kohlbecker Aldrin Leal Andreas Jaekle Andrews Medina Andrey Sibiryov Andy Goldstein Antonio Murdaca Artem Sidorenko Ben Marini Ben McCann Ben Parees Benno van den Berg Brendan Fosberry Brian Lalor Brian P. Hamachek Brian Palmer Bryan Boreham Burke Libbey Carlos Diaz-Padron Cesar Wong Cezar Sa Espinola Cheah Chu Yeow cheneydeng Chris Bednarski CMGS Colin Hebert Craig Jellick Dan Williams Daniel, Dao Quang Minh Daniel Garcia Daniel Hiltgen Darren Shepherd Dave Choi David Huie Dawn Chen Dinesh Subhraveti Drew Wells Ed Elias G. Schneevoigt Erez Horev Eric Anderson Ewout Prangsma Fabio Rehm Fatih Arslan Flavia Missi Francisco Souza Grégoire Delattre Guillermo Álvarez Fernández Harry Zhang He Simei Ivan Mikushin James Bardin James Nugent Jari Kolehmainen Jason Wilder Jawher Moussa Jean-Baptiste Dalido Jeff Mitchell Jeffrey Hulten Jen Andre Jérôme Laurens Johan Euphrosine John Hughes Kamil Domanski Karan Misra Ken Herner Kim, Hirokuni Kyle Allan Liron Levin Lior Yankovich Liu Peng Lorenz Leutgeb Lucas Clemente Lucas Weiblen Lyon Hill Mantas Matelis Martin Sweeney Máximo Cuadros Ortiz Michael Schmatz Michal Fojtik Mike Dillon Mrunal Patel Nguyen Sy Thanh Son Nick Ethier Omeid Matten Orivej Desh Paul Bellamy Paul Morie Paul Weil Peter Edge Peter Jihoon Kim Phil Lu Philippe Lafoucrière Rafe Colton Rob Miller Robert Williamson Salvador Gironès Sam Rijs Sami Wagiaalla Samuel Karp Silas Sewell Simon Eskildsen Simon Menke Skolos Soulou Sridhar Ratnakumar Summer Mousa Sunjin Lee Tarsis Azevedo Tim Schindler Timothy St. Clair Tobi Knaup Tom Wilkie Tonic ttyh061 Victor Marmol Vincenzo Prignano Wiliam Souza Ye Yin Yu, Zou Yuriy Bogdanov ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/DOCKER-LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ You can find the Docker license at the following link: https://raw.githubusercontent.com/docker/docker/master/LICENSE ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/LICENSE ================================================ Copyright (c) 2015, go-dockerclient 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. 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/Makefile ================================================ .PHONY: \ all \ vendor \ lint \ vet \ fmt \ fmtcheck \ pretest \ test \ integration \ cov \ clean SRCS = $(shell git ls-files '*.go' | grep -v '^external/') PKGS = ./. ./testing all: test vendor: @ go get -v github.com/mjibson/party party -d external -c -u lint: @ go get -v github.com/golang/lint/golint $(foreach file,$(SRCS),golint $(file) || exit;) vet: @-go get -v golang.org/x/tools/cmd/vet $(foreach pkg,$(PKGS),go vet $(pkg);) fmt: gofmt -w $(SRCS) fmtcheck: $(foreach file,$(SRCS),gofmt -d $(file);) prepare_docker: sudo stop docker sudo rm -rf /var/lib/docker sudo rm -f `which docker` sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D echo "deb https://apt.dockerproject.org/repo ubuntu-trusty main" | sudo tee /etc/apt/sources.list.d/docker.list sudo apt-get update sudo apt-get install docker-engine=$(DOCKER_VERSION)-0~$(shell lsb_release -cs) -y --force-yes -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" pretest: lint vet fmtcheck test: pretest $(foreach pkg,$(PKGS),go test $(pkg) || exit;) integration: go test -tags docker_integration -run TestIntegration -v cov: @ go get -v github.com/axw/gocov/gocov @ go get golang.org/x/tools/cmd/cover gocov test | gocov report clean: $(foreach pkg,$(PKGS),go clean $(pkg) || exit;) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/README.markdown ================================================ # go-dockerclient [![Travis](https://img.shields.io/travis/fsouza/go-dockerclient.svg?style=flat-square)](https://travis-ci.org/fsouza/go-dockerclient) [![GoDoc](https://img.shields.io/badge/api-Godoc-blue.svg?style=flat-square)](https://godoc.org/github.com/fsouza/go-dockerclient) This package presents a client for the Docker remote API. It also provides support for the extensions in the [Swarm API](https://docs.docker.com/swarm/api/swarm-api/). This package also provides support for docker's network API, which is a simple passthrough to the libnetwork remote API. Note that docker's network API is only available in docker 1.8 and above, and only enabled in docker if DOCKER_EXPERIMENTAL is defined during the docker build process. For more details, check the [remote API documentation](http://docs.docker.com/engine/reference/api/docker_remote_api/). ## Vendoring If you are having issues with Go 1.5 and have `GO15VENDOREXPERIMENT` set with an application that has go-dockerclient vendored, please update your vendoring of go-dockerclient :) We recently moved the `vendor` directory to `external` so that go-dockerclient is compatible with this configuration. See [338](https://github.com/fsouza/go-dockerclient/issues/338) and [339](https://github.com/fsouza/go-dockerclient/pull/339) for details. ## Example ```go package main import ( "fmt" "github.com/fsouza/go-dockerclient" ) func main() { endpoint := "unix:///var/run/docker.sock" client, _ := docker.NewClient(endpoint) imgs, _ := client.ListImages(docker.ListImagesOptions{All: false}) for _, img := range imgs { fmt.Println("ID: ", img.ID) fmt.Println("RepoTags: ", img.RepoTags) fmt.Println("Created: ", img.Created) fmt.Println("Size: ", img.Size) fmt.Println("VirtualSize: ", img.VirtualSize) fmt.Println("ParentId: ", img.ParentID) } } ``` ## Using with TLS In order to instantiate the client for a TLS-enabled daemon, you should use NewTLSClient, passing the endpoint and path for key and certificates as parameters. ```go package main import ( "fmt" "github.com/fsouza/go-dockerclient" ) func main() { endpoint := "tcp://[ip]:[port]" path := os.Getenv("DOCKER_CERT_PATH") ca := fmt.Sprintf("%s/ca.pem", path) cert := fmt.Sprintf("%s/cert.pem", path) key := fmt.Sprintf("%s/key.pem", path) client, _ := docker.NewTLSClient(endpoint, cert, key, ca) // use client } ``` If using [docker-machine](https://docs.docker.com/machine/), or another application that exports environment variables `DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH`, you can use NewClientFromEnv. ```go package main import ( "fmt" "github.com/fsouza/go-dockerclient" ) func main() { client, _ := docker.NewClientFromEnv() // use client } ``` See the documentation for more details. ## Developing All development commands can be seen in the [Makefile](Makefile). Commited code must pass: * [golint](https://github.com/golang/lint) * [go vet](https://godoc.org/golang.org/x/tools/cmd/vet) * [gofmt](https://golang.org/cmd/gofmt) * [go test](https://golang.org/cmd/go/#hdr-Test_packages) Running `make test` will check all of these. If your editor does not automatically call gofmt, `make fmt` will format all go files in this repository. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/auth.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io" "os" "path" "strings" ) // ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed. var ErrCannotParseDockercfg = errors.New("Failed to read authentication from dockercfg") // AuthConfiguration represents authentication options to use in the PushImage // method. It represents the authentication in the Docker index server. type AuthConfiguration struct { Username string `json:"username,omitempty"` Password string `json:"password,omitempty"` Email string `json:"email,omitempty"` ServerAddress string `json:"serveraddress,omitempty"` } // AuthConfigurations represents authentication options to use for the // PushImage method accommodating the new X-Registry-Config header type AuthConfigurations struct { Configs map[string]AuthConfiguration `json:"configs"` } // AuthConfigurations119 is used to serialize a set of AuthConfigurations // for Docker API >= 1.19. type AuthConfigurations119 map[string]AuthConfiguration // dockerConfig represents a registry authentation configuration from the // .dockercfg file. type dockerConfig struct { Auth string `json:"auth"` Email string `json:"email"` } // NewAuthConfigurationsFromDockerCfg returns AuthConfigurations from the // ~/.dockercfg file. func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) { var r io.Reader var err error p := path.Join(os.Getenv("HOME"), ".docker", "config.json") r, err = os.Open(p) if err != nil { p := path.Join(os.Getenv("HOME"), ".dockercfg") r, err = os.Open(p) if err != nil { return nil, err } } return NewAuthConfigurations(r) } // NewAuthConfigurations returns AuthConfigurations from a JSON encoded string in the // same format as the .dockercfg file. func NewAuthConfigurations(r io.Reader) (*AuthConfigurations, error) { var auth *AuthConfigurations confs, err := parseDockerConfig(r) if err != nil { return nil, err } auth, err = authConfigs(confs) if err != nil { return nil, err } return auth, nil } func parseDockerConfig(r io.Reader) (map[string]dockerConfig, error) { buf := new(bytes.Buffer) buf.ReadFrom(r) byteData := buf.Bytes() var confsWrapper map[string]map[string]dockerConfig if err := json.Unmarshal(byteData, &confsWrapper); err == nil { if confs, ok := confsWrapper["auths"]; ok { return confs, nil } } var confs map[string]dockerConfig if err := json.Unmarshal(byteData, &confs); err != nil { return nil, err } return confs, nil } // authConfigs converts a dockerConfigs map to a AuthConfigurations object. func authConfigs(confs map[string]dockerConfig) (*AuthConfigurations, error) { c := &AuthConfigurations{ Configs: make(map[string]AuthConfiguration), } for reg, conf := range confs { data, err := base64.StdEncoding.DecodeString(conf.Auth) if err != nil { return nil, err } userpass := strings.SplitN(string(data), ":", 2) if len(userpass) != 2 { return nil, ErrCannotParseDockercfg } c.Configs[reg] = AuthConfiguration{ Email: conf.Email, Username: userpass[0], Password: userpass[1], ServerAddress: reg, } } return c, nil } // AuthCheck validates the given credentials. It returns nil if successful. // // See https://goo.gl/m2SleN for more details. func (c *Client) AuthCheck(conf *AuthConfiguration) error { if conf == nil { return fmt.Errorf("conf is nil") } resp, err := c.do("POST", "/auth", doOptions{data: conf}) if err != nil { return err } resp.Body.Close() return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/auth_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/base64" "fmt" "net/http" "strings" "testing" ) func TestAuthLegacyConfig(t *testing.T) { auth := base64.StdEncoding.EncodeToString([]byte("user:pa:ss")) read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth)) ac, err := NewAuthConfigurations(read) if err != nil { t.Error(err) } c, ok := ac.Configs["docker.io"] if !ok { t.Error("NewAuthConfigurations: Expected Configs to contain docker.io") } if got, want := c.Email, "user@example.com"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got) } if got, want := c.Username, "user"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got) } if got, want := c.Password, "pa:ss"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got) } if got, want := c.ServerAddress, "docker.io"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got) } } func TestAuthBadConfig(t *testing.T) { auth := base64.StdEncoding.EncodeToString([]byte("userpass")) read := strings.NewReader(fmt.Sprintf(`{"docker.io":{"auth":"%s","email":"user@example.com"}}`, auth)) ac, err := NewAuthConfigurations(read) if err != ErrCannotParseDockercfg { t.Errorf("Incorrect error returned %v\n", err) } if ac != nil { t.Errorf("Invalid auth configuration returned, should be nil %v\n", ac) } } func TestAuthConfig(t *testing.T) { auth := base64.StdEncoding.EncodeToString([]byte("user:pass")) read := strings.NewReader(fmt.Sprintf(`{"auths":{"docker.io":{"auth":"%s","email":"user@example.com"}}}`, auth)) ac, err := NewAuthConfigurations(read) if err != nil { t.Error(err) } c, ok := ac.Configs["docker.io"] if !ok { t.Error("NewAuthConfigurations: Expected Configs to contain docker.io") } if got, want := c.Email, "user@example.com"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].Email: wrong result. Want %q. Got %q`, want, got) } if got, want := c.Username, "user"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].Username: wrong result. Want %q. Got %q`, want, got) } if got, want := c.Password, "pass"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].Password: wrong result. Want %q. Got %q`, want, got) } if got, want := c.ServerAddress, "docker.io"; got != want { t.Errorf(`AuthConfigurations.Configs["docker.io"].ServerAddress: wrong result. Want %q. Got %q`, want, got) } } func TestAuthCheck(t *testing.T) { fakeRT := &FakeRoundTripper{status: http.StatusOK} client := newTestClient(fakeRT) if err := client.AuthCheck(nil); err == nil { t.Fatalf("expected error on nil auth config") } // test good auth if err := client.AuthCheck(&AuthConfiguration{}); err != nil { t.Fatal(err) } *fakeRT = FakeRoundTripper{status: http.StatusUnauthorized} if err := client.AuthCheck(&AuthConfiguration{}); err == nil { t.Fatal("expected failure from unauthorized auth") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/build_test.go ================================================ package docker import ( "bytes" "io" "io/ioutil" "net/http" "os" "reflect" "testing" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive" ) func TestBuildImageMultipleContextsError(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", NoCache: true, SuppressOutput: true, RmTmpContainer: true, ForceRmTmpContainer: true, InputStream: &buf, OutputStream: &buf, ContextDir: "testing/data", } err := client.BuildImage(opts) if err != ErrMultipleContexts { t.Errorf("BuildImage: providing both InputStream and ContextDir should produce an error") } } func TestBuildImageContextDirDockerignoreParsing(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) if err := os.Symlink("doesnotexist", "testing/data/symlink"); err != nil { t.Errorf("error creating symlink on demand: %s", err) } defer func() { if err := os.Remove("testing/data/symlink"); err != nil { t.Errorf("error removing symlink on demand: %s", err) } }() var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", NoCache: true, SuppressOutput: true, RmTmpContainer: true, ForceRmTmpContainer: true, OutputStream: &buf, ContextDir: "testing/data", } err := client.BuildImage(opts) if err != nil { t.Fatal(err) } reqBody := fakeRT.requests[0].Body tmpdir, err := unpackBodyTarball(reqBody) if err != nil { t.Fatal(err) } defer func() { if err := os.RemoveAll(tmpdir); err != nil { t.Fatal(err) } }() files, err := ioutil.ReadDir(tmpdir) if err != nil { t.Fatal(err) } foundFiles := []string{} for _, file := range files { foundFiles = append(foundFiles, file.Name()) } expectedFiles := []string{ ".dockerignore", "Dockerfile", "barfile", "ca.pem", "cert.pem", "key.pem", "server.pem", "serverkey.pem", "symlink", } if !reflect.DeepEqual(expectedFiles, foundFiles) { t.Errorf( "BuildImage: incorrect files sent in tarball to docker server\nexpected %+v, found %+v", expectedFiles, foundFiles, ) } } func TestBuildImageSendXRegistryConfig(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", NoCache: true, SuppressOutput: true, RmTmpContainer: true, ForceRmTmpContainer: true, OutputStream: &buf, ContextDir: "testing/data", AuthConfigs: AuthConfigurations{ Configs: map[string]AuthConfiguration{ "quay.io": { Username: "foo", Password: "bar", Email: "baz", ServerAddress: "quay.io", }, }, }, } encodedConfig := "eyJjb25maWdzIjp7InF1YXkuaW8iOnsidXNlcm5hbWUiOiJmb28iLCJwYXNzd29yZCI6ImJhciIsImVtYWlsIjoiYmF6Iiwic2VydmVyYWRkcmVzcyI6InF1YXkuaW8ifX19Cg==" if err := client.BuildImage(opts); err != nil { t.Fatal(err) } xRegistryConfig := fakeRT.requests[0].Header["X-Registry-Config"][0] if xRegistryConfig != encodedConfig { t.Errorf( "BuildImage: X-Registry-Config not set currectly: expected %q, got %q", encodedConfig, xRegistryConfig, ) } } func unpackBodyTarball(req io.ReadCloser) (tmpdir string, err error) { tmpdir, err = ioutil.TempDir("", "go-dockerclient-test") if err != nil { return } err = archive.Untar(req, tmpdir, &archive.TarOptions{ Compression: archive.Uncompressed, NoLchown: true, }) return } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/change.go ================================================ // Copyright 2014 go-dockerclient 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 docker import "fmt" // ChangeType is a type for constants indicating the type of change // in a container type ChangeType int const ( // ChangeModify is the ChangeType for container modifications ChangeModify ChangeType = iota // ChangeAdd is the ChangeType for additions to a container ChangeAdd // ChangeDelete is the ChangeType for deletions from a container ChangeDelete ) // Change represents a change in a container. // // See https://goo.gl/9GsTIF for more details. type Change struct { Path string Kind ChangeType } func (change *Change) String() string { var kind string switch change.Kind { case ChangeModify: kind = "C" case ChangeAdd: kind = "A" case ChangeDelete: kind = "D" } return fmt.Sprintf("%s %s", kind, change.Path) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/change_test.go ================================================ // Copyright 2014 go-dockerclient 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 docker import "testing" func TestChangeString(t *testing.T) { var tests = []struct { change Change expected string }{ {Change{"/etc/passwd", ChangeModify}, "C /etc/passwd"}, {Change{"/etc/passwd", ChangeAdd}, "A /etc/passwd"}, {Change{"/etc/passwd", ChangeDelete}, "D /etc/passwd"}, {Change{"/etc/passwd", 33}, " /etc/passwd"}, } for _, tt := range tests { if got := tt.change.String(); got != tt.expected { t.Errorf("Change.String(): want %q. Got %q.", tt.expected, got) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/client.go ================================================ // Copyright 2015 go-dockerclient 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 docker provides a client for the Docker remote API. // // See https://goo.gl/G3plxW for more details on the remote API. package docker import ( "bufio" "bytes" "crypto/tls" "crypto/x509" "encoding/json" "errors" "fmt" "io" "io/ioutil" "net" "net/http" "net/http/httputil" "net/url" "os" "path/filepath" "reflect" "runtime" "strconv" "strings" "time" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy" "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp" ) const userAgent = "go-dockerclient" var ( // ErrInvalidEndpoint is returned when the endpoint is not a valid HTTP URL. ErrInvalidEndpoint = errors.New("invalid endpoint") // ErrConnectionRefused is returned when the client cannot connect to the given endpoint. ErrConnectionRefused = errors.New("cannot connect to Docker endpoint") apiVersion112, _ = NewAPIVersion("1.12") apiVersion119, _ = NewAPIVersion("1.19") ) // APIVersion is an internal representation of a version of the Remote API. type APIVersion []int // NewAPIVersion returns an instance of APIVersion for the given string. // // The given string must be in the form .., where , // and are integer numbers. func NewAPIVersion(input string) (APIVersion, error) { if !strings.Contains(input, ".") { return nil, fmt.Errorf("Unable to parse version %q", input) } raw := strings.Split(input, "-") arr := strings.Split(raw[0], ".") ret := make(APIVersion, len(arr)) var err error for i, val := range arr { ret[i], err = strconv.Atoi(val) if err != nil { return nil, fmt.Errorf("Unable to parse version %q: %q is not an integer", input, val) } } return ret, nil } func (version APIVersion) String() string { var str string for i, val := range version { str += strconv.Itoa(val) if i < len(version)-1 { str += "." } } return str } // LessThan is a function for comparing APIVersion structs func (version APIVersion) LessThan(other APIVersion) bool { return version.compare(other) < 0 } // LessThanOrEqualTo is a function for comparing APIVersion structs func (version APIVersion) LessThanOrEqualTo(other APIVersion) bool { return version.compare(other) <= 0 } // GreaterThan is a function for comparing APIVersion structs func (version APIVersion) GreaterThan(other APIVersion) bool { return version.compare(other) > 0 } // GreaterThanOrEqualTo is a function for comparing APIVersion structs func (version APIVersion) GreaterThanOrEqualTo(other APIVersion) bool { return version.compare(other) >= 0 } func (version APIVersion) compare(other APIVersion) int { for i, v := range version { if i <= len(other)-1 { otherVersion := other[i] if v < otherVersion { return -1 } else if v > otherVersion { return 1 } } } if len(version) > len(other) { return 1 } if len(version) < len(other) { return -1 } return 0 } // Client is the basic type of this package. It provides methods for // interaction with the API. type Client struct { SkipServerVersionCheck bool HTTPClient *http.Client TLSConfig *tls.Config Dialer *net.Dialer endpoint string endpointURL *url.URL eventMonitor *eventMonitoringState requestedAPIVersion APIVersion serverAPIVersion APIVersion expectedAPIVersion APIVersion unixHTTPClient *http.Client } // NewClient returns a Client instance ready for communication with the given // server endpoint. It will use the latest remote API version available in the // server. func NewClient(endpoint string) (*Client, error) { client, err := NewVersionedClient(endpoint, "") if err != nil { return nil, err } client.SkipServerVersionCheck = true return client, nil } // NewTLSClient returns a Client instance ready for TLS communications with the givens // server endpoint, key and certificates . It will use the latest remote API version // available in the server. func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) { client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "") if err != nil { return nil, err } client.SkipServerVersionCheck = true return client, nil } // NewTLSClientFromBytes returns a Client instance ready for TLS communications with the givens // server endpoint, key and certificates (passed inline to the function as opposed to being // read from a local file). It will use the latest remote API version available in the server. func NewTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte) (*Client, error) { client, err := NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, "") if err != nil { return nil, err } client.SkipServerVersionCheck = true return client, nil } // NewVersionedClient returns a Client instance ready for communication with // the given server endpoint, using a specific remote API version. func NewVersionedClient(endpoint string, apiVersionString string) (*Client, error) { u, err := parseEndpoint(endpoint, false) if err != nil { return nil, err } var requestedAPIVersion APIVersion if strings.Contains(apiVersionString, ".") { requestedAPIVersion, err = NewAPIVersion(apiVersionString) if err != nil { return nil, err } } return &Client{ HTTPClient: cleanhttp.DefaultClient(), Dialer: &net.Dialer{}, endpoint: endpoint, endpointURL: u, eventMonitor: new(eventMonitoringState), requestedAPIVersion: requestedAPIVersion, }, nil } // NewVersionnedTLSClient has been DEPRECATED, please use NewVersionedTLSClient. func NewVersionnedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) { return NewVersionedTLSClient(endpoint, cert, key, ca, apiVersionString) } // NewVersionedTLSClient returns a Client instance ready for TLS communications with the givens // server endpoint, key and certificates, using a specific remote API version. func NewVersionedTLSClient(endpoint string, cert, key, ca, apiVersionString string) (*Client, error) { certPEMBlock, err := ioutil.ReadFile(cert) if err != nil { return nil, err } keyPEMBlock, err := ioutil.ReadFile(key) if err != nil { return nil, err } caPEMCert, err := ioutil.ReadFile(ca) if err != nil { return nil, err } return NewVersionedTLSClientFromBytes(endpoint, certPEMBlock, keyPEMBlock, caPEMCert, apiVersionString) } // NewClientFromEnv returns a Client instance ready for communication created from // Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH. // // See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68. // See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7. func NewClientFromEnv() (*Client, error) { client, err := NewVersionedClientFromEnv("") if err != nil { return nil, err } client.SkipServerVersionCheck = true return client, nil } // NewVersionedClientFromEnv returns a Client instance ready for TLS communications created from // Docker's default logic for the environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT_PATH, // and using a specific remote API version. // // See https://github.com/docker/docker/blob/1f963af697e8df3a78217f6fdbf67b8123a7db94/docker/docker.go#L68. // See https://github.com/docker/compose/blob/81707ef1ad94403789166d2fe042c8a718a4c748/compose/cli/docker_client.py#L7. func NewVersionedClientFromEnv(apiVersionString string) (*Client, error) { dockerEnv, err := getDockerEnv() if err != nil { return nil, err } dockerHost := dockerEnv.dockerHost if dockerEnv.dockerTLSVerify { parts := strings.SplitN(dockerEnv.dockerHost, "://", 2) if len(parts) != 2 { return nil, fmt.Errorf("could not split %s into two parts by ://", dockerHost) } cert := filepath.Join(dockerEnv.dockerCertPath, "cert.pem") key := filepath.Join(dockerEnv.dockerCertPath, "key.pem") ca := filepath.Join(dockerEnv.dockerCertPath, "ca.pem") return NewVersionedTLSClient(dockerEnv.dockerHost, cert, key, ca, apiVersionString) } return NewVersionedClient(dockerEnv.dockerHost, apiVersionString) } // NewVersionedTLSClientFromBytes returns a Client instance ready for TLS communications with the givens // server endpoint, key and certificates (passed inline to the function as opposed to being // read from a local file), using a specific remote API version. func NewVersionedTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock, caPEMCert []byte, apiVersionString string) (*Client, error) { u, err := parseEndpoint(endpoint, true) if err != nil { return nil, err } var requestedAPIVersion APIVersion if strings.Contains(apiVersionString, ".") { requestedAPIVersion, err = NewAPIVersion(apiVersionString) if err != nil { return nil, err } } if certPEMBlock == nil || keyPEMBlock == nil { return nil, errors.New("Both cert and key are required") } tlsCert, err := tls.X509KeyPair(certPEMBlock, keyPEMBlock) if err != nil { return nil, err } tlsConfig := &tls.Config{Certificates: []tls.Certificate{tlsCert}} if caPEMCert == nil { tlsConfig.InsecureSkipVerify = true } else { caPool := x509.NewCertPool() if !caPool.AppendCertsFromPEM(caPEMCert) { return nil, errors.New("Could not add RootCA pem") } tlsConfig.RootCAs = caPool } tr := cleanhttp.DefaultTransport() tr.TLSClientConfig = tlsConfig if err != nil { return nil, err } return &Client{ HTTPClient: &http.Client{Transport: tr}, TLSConfig: tlsConfig, Dialer: &net.Dialer{}, endpoint: endpoint, endpointURL: u, eventMonitor: new(eventMonitoringState), requestedAPIVersion: requestedAPIVersion, }, nil } func (c *Client) checkAPIVersion() error { serverAPIVersionString, err := c.getServerAPIVersionString() if err != nil { return err } c.serverAPIVersion, err = NewAPIVersion(serverAPIVersionString) if err != nil { return err } if c.requestedAPIVersion == nil { c.expectedAPIVersion = c.serverAPIVersion } else { c.expectedAPIVersion = c.requestedAPIVersion } return nil } // Endpoint returns the current endpoint. It's useful for getting the endpoint // when using functions that get this data from the environment (like // NewClientFromEnv. func (c *Client) Endpoint() string { return c.endpoint } // Ping pings the docker server // // See https://goo.gl/kQCfJj for more details. func (c *Client) Ping() error { path := "/_ping" resp, err := c.do("GET", path, doOptions{}) if err != nil { return err } if resp.StatusCode != http.StatusOK { return newError(resp) } resp.Body.Close() return nil } func (c *Client) getServerAPIVersionString() (version string, err error) { resp, err := c.do("GET", "/version", doOptions{}) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("Received unexpected status %d while trying to retrieve the server version", resp.StatusCode) } var versionResponse map[string]interface{} if err := json.NewDecoder(resp.Body).Decode(&versionResponse); err != nil { return "", err } if version, ok := (versionResponse["ApiVersion"]).(string); ok { return version, nil } return "", nil } type doOptions struct { data interface{} forceJSON bool headers map[string]string } func (c *Client) do(method, path string, doOptions doOptions) (*http.Response, error) { var params io.Reader if doOptions.data != nil || doOptions.forceJSON { buf, err := json.Marshal(doOptions.data) if err != nil { return nil, err } params = bytes.NewBuffer(buf) } if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { err := c.checkAPIVersion() if err != nil { return nil, err } } httpClient := c.HTTPClient protocol := c.endpointURL.Scheme var u string if protocol == "unix" { httpClient = c.unixClient() u = c.getFakeUnixURL(path) } else { u = c.getURL(path) } req, err := http.NewRequest(method, u, params) if err != nil { return nil, err } req.Header.Set("User-Agent", userAgent) if doOptions.data != nil { req.Header.Set("Content-Type", "application/json") } else if method == "POST" { req.Header.Set("Content-Type", "plain/text") } for k, v := range doOptions.headers { req.Header.Set(k, v) } resp, err := httpClient.Do(req) if err != nil { if strings.Contains(err.Error(), "connection refused") { return nil, ErrConnectionRefused } return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 400 { return nil, newError(resp) } return resp, nil } type streamOptions struct { setRawTerminal bool rawJSONStream bool useJSONDecoder bool headers map[string]string in io.Reader stdout io.Writer stderr io.Writer // timeout is the inital connection timeout timeout time.Duration } func (c *Client) stream(method, path string, streamOptions streamOptions) error { if (method == "POST" || method == "PUT") && streamOptions.in == nil { streamOptions.in = bytes.NewReader(nil) } if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { err := c.checkAPIVersion() if err != nil { return err } } req, err := http.NewRequest(method, c.getURL(path), streamOptions.in) if err != nil { return err } req.Header.Set("User-Agent", userAgent) if method == "POST" { req.Header.Set("Content-Type", "plain/text") } for key, val := range streamOptions.headers { req.Header.Set(key, val) } var resp *http.Response protocol := c.endpointURL.Scheme address := c.endpointURL.Path if streamOptions.stdout == nil { streamOptions.stdout = ioutil.Discard } if streamOptions.stderr == nil { streamOptions.stderr = ioutil.Discard } if protocol == "unix" { dial, err := c.Dialer.Dial(protocol, address) if err != nil { return err } defer dial.Close() breader := bufio.NewReader(dial) err = req.Write(dial) if err != nil { return err } // ReadResponse may hang if server does not replay if streamOptions.timeout > 0 { dial.SetDeadline(time.Now().Add(streamOptions.timeout)) } if resp, err = http.ReadResponse(breader, req); err != nil { // Cancel timeout for future I/O operations if streamOptions.timeout > 0 { dial.SetDeadline(time.Time{}) } if strings.Contains(err.Error(), "connection refused") { return ErrConnectionRefused } return err } } else { if resp, err = c.HTTPClient.Do(req); err != nil { if strings.Contains(err.Error(), "connection refused") { return ErrConnectionRefused } return err } } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 400 { return newError(resp) } if streamOptions.useJSONDecoder || resp.Header.Get("Content-Type") == "application/json" { // if we want to get raw json stream, just copy it back to output // without decoding it if streamOptions.rawJSONStream { _, err = io.Copy(streamOptions.stdout, resp.Body) return err } dec := json.NewDecoder(resp.Body) for { var m jsonMessage if err := dec.Decode(&m); err == io.EOF { break } else if err != nil { return err } if m.Stream != "" { fmt.Fprint(streamOptions.stdout, m.Stream) } else if m.Progress != "" { fmt.Fprintf(streamOptions.stdout, "%s %s\r", m.Status, m.Progress) } else if m.Error != "" { return errors.New(m.Error) } if m.Status != "" { fmt.Fprintln(streamOptions.stdout, m.Status) } } } else { if streamOptions.setRawTerminal { _, err = io.Copy(streamOptions.stdout, resp.Body) } else { _, err = stdcopy.StdCopy(streamOptions.stdout, streamOptions.stderr, resp.Body) } return err } return nil } type hijackOptions struct { success chan struct{} setRawTerminal bool in io.Reader stdout io.Writer stderr io.Writer data interface{} } type CloseWaiter interface { io.Closer Wait() error } type waiterFunc func() error func (w waiterFunc) Wait() error { return w() } type closerFunc func() error func (c closerFunc) Close() error { return c() } func (c *Client) hijack(method, path string, hijackOptions hijackOptions) (CloseWaiter, error) { if path != "/version" && !c.SkipServerVersionCheck && c.expectedAPIVersion == nil { err := c.checkAPIVersion() if err != nil { return nil, err } } var params io.Reader if hijackOptions.data != nil { buf, err := json.Marshal(hijackOptions.data) if err != nil { return nil, err } params = bytes.NewBuffer(buf) } req, err := http.NewRequest(method, c.getURL(path), params) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", "tcp") protocol := c.endpointURL.Scheme address := c.endpointURL.Path if protocol != "unix" { protocol = "tcp" address = c.endpointURL.Host } var dial net.Conn if c.TLSConfig != nil && protocol != "unix" { dial, err = tlsDialWithDialer(c.Dialer, protocol, address, c.TLSConfig) if err != nil { return nil, err } } else { dial, err = c.Dialer.Dial(protocol, address) if err != nil { return nil, err } } errs := make(chan error) quit := make(chan struct{}) go func() { clientconn := httputil.NewClientConn(dial, nil) defer clientconn.Close() clientconn.Do(req) if hijackOptions.success != nil { hijackOptions.success <- struct{}{} <-hijackOptions.success } rwc, br := clientconn.Hijack() defer rwc.Close() errChanOut := make(chan error, 1) errChanIn := make(chan error, 1) if hijackOptions.stdout == nil && hijackOptions.stderr == nil { close(errChanOut) } else { // Only copy if hijackOptions.stdout and/or hijackOptions.stderr is actually set. // Otherwise, if the only stream you care about is stdin, your attach session // will "hang" until the container terminates, even though you're not reading // stdout/stderr if hijackOptions.stdout == nil { hijackOptions.stdout = ioutil.Discard } if hijackOptions.stderr == nil { hijackOptions.stderr = ioutil.Discard } go func() { defer func() { if hijackOptions.in != nil { if closer, ok := hijackOptions.in.(io.Closer); ok { closer.Close() } errChanIn <- nil } }() var err error if hijackOptions.setRawTerminal { _, err = io.Copy(hijackOptions.stdout, br) } else { _, err = stdcopy.StdCopy(hijackOptions.stdout, hijackOptions.stderr, br) } errChanOut <- err }() } go func() { var err error if hijackOptions.in != nil { _, err = io.Copy(rwc, hijackOptions.in) } errChanIn <- err rwc.(interface { CloseWrite() error }).CloseWrite() }() var errIn error select { case errIn = <-errChanIn: case <-quit: return } var errOut error select { case errOut = <-errChanOut: case <-quit: return } if errIn != nil { errs <- errIn } else { errs <- errOut } }() return struct { closerFunc waiterFunc }{ closerFunc(func() error { close(quit); return nil }), waiterFunc(func() error { return <-errs }), }, nil } func (c *Client) getURL(path string) string { urlStr := strings.TrimRight(c.endpointURL.String(), "/") if c.endpointURL.Scheme == "unix" { urlStr = "" } if c.requestedAPIVersion != nil { return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path) } return fmt.Sprintf("%s%s", urlStr, path) } // getFakeUnixURL returns the URL needed to make an HTTP request over a UNIX // domain socket to the given path. func (c *Client) getFakeUnixURL(path string) string { u := *c.endpointURL // Copy. // Override URL so that net/http will not complain. u.Scheme = "http" u.Host = "unix.sock" // Doesn't matter what this is - it's not used. u.Path = "" urlStr := strings.TrimRight(u.String(), "/") if c.requestedAPIVersion != nil { return fmt.Sprintf("%s/v%s%s", urlStr, c.requestedAPIVersion, path) } return fmt.Sprintf("%s%s", urlStr, path) } func (c *Client) unixClient() *http.Client { if c.unixHTTPClient != nil { return c.unixHTTPClient } socketPath := c.endpointURL.Path tr := &http.Transport{ Dial: func(network, addr string) (net.Conn, error) { return c.Dialer.Dial("unix", socketPath) }, } cleanhttp.SetTransportFinalizer(tr) c.unixHTTPClient = &http.Client{Transport: tr} return c.unixHTTPClient } type jsonMessage struct { Status string `json:"status,omitempty"` Progress string `json:"progress,omitempty"` Error string `json:"error,omitempty"` Stream string `json:"stream,omitempty"` } func queryString(opts interface{}) string { if opts == nil { return "" } value := reflect.ValueOf(opts) if value.Kind() == reflect.Ptr { value = value.Elem() } if value.Kind() != reflect.Struct { return "" } items := url.Values(map[string][]string{}) for i := 0; i < value.NumField(); i++ { field := value.Type().Field(i) if field.PkgPath != "" { continue } key := field.Tag.Get("qs") if key == "" { key = strings.ToLower(field.Name) } else if key == "-" { continue } addQueryStringValue(items, key, value.Field(i)) } return items.Encode() } func addQueryStringValue(items url.Values, key string, v reflect.Value) { switch v.Kind() { case reflect.Bool: if v.Bool() { items.Add(key, "1") } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if v.Int() > 0 { items.Add(key, strconv.FormatInt(v.Int(), 10)) } case reflect.Float32, reflect.Float64: if v.Float() > 0 { items.Add(key, strconv.FormatFloat(v.Float(), 'f', -1, 64)) } case reflect.String: if v.String() != "" { items.Add(key, v.String()) } case reflect.Ptr: if !v.IsNil() { if b, err := json.Marshal(v.Interface()); err == nil { items.Add(key, string(b)) } } case reflect.Map: if len(v.MapKeys()) > 0 { if b, err := json.Marshal(v.Interface()); err == nil { items.Add(key, string(b)) } } case reflect.Array, reflect.Slice: vLen := v.Len() if vLen > 0 { for i := 0; i < vLen; i++ { addQueryStringValue(items, key, v.Index(i)) } } } } // Error represents failures in the API. It represents a failure from the API. type Error struct { Status int Message string } func newError(resp *http.Response) *Error { defer resp.Body.Close() data, err := ioutil.ReadAll(resp.Body) if err != nil { return &Error{Status: resp.StatusCode, Message: fmt.Sprintf("cannot read body, err: %v", err)} } return &Error{Status: resp.StatusCode, Message: string(data)} } func (e *Error) Error() string { return fmt.Sprintf("API error (%d): %s", e.Status, e.Message) } func parseEndpoint(endpoint string, tls bool) (*url.URL, error) { if endpoint != "" && !strings.Contains(endpoint, "://") { endpoint = "tcp://" + endpoint } u, err := url.Parse(endpoint) if err != nil { return nil, ErrInvalidEndpoint } if tls { u.Scheme = "https" } switch u.Scheme { case "unix": return u, nil case "http", "https", "tcp": _, port, err := net.SplitHostPort(u.Host) if err != nil { if e, ok := err.(*net.AddrError); ok { if e.Err == "missing port in address" { return u, nil } } return nil, ErrInvalidEndpoint } number, err := strconv.ParseInt(port, 10, 64) if err == nil && number > 0 && number < 65536 { if u.Scheme == "tcp" { if tls { u.Scheme = "https" } else { u.Scheme = "http" } } return u, nil } return nil, ErrInvalidEndpoint default: return nil, ErrInvalidEndpoint } } type dockerEnv struct { dockerHost string dockerTLSVerify bool dockerCertPath string } func getDockerEnv() (*dockerEnv, error) { dockerHost := os.Getenv("DOCKER_HOST") var err error if dockerHost == "" { dockerHost, err = DefaultDockerHost() if err != nil { return nil, err } } dockerTLSVerify := os.Getenv("DOCKER_TLS_VERIFY") != "" var dockerCertPath string if dockerTLSVerify { dockerCertPath = os.Getenv("DOCKER_CERT_PATH") if dockerCertPath == "" { home := homedir.Get() if home == "" { return nil, errors.New("environment variable HOME must be set if DOCKER_CERT_PATH is not set") } dockerCertPath = filepath.Join(home, ".docker") dockerCertPath, err = filepath.Abs(dockerCertPath) if err != nil { return nil, err } } } return &dockerEnv{ dockerHost: dockerHost, dockerTLSVerify: dockerTLSVerify, dockerCertPath: dockerCertPath, }, nil } // DefaultDockerHost returns the default docker socket for the current OS func DefaultDockerHost() (string, error) { var defaultHost string if runtime.GOOS == "windows" { // If we do not have a host, default to TCP socket on Windows defaultHost = fmt.Sprintf("tcp://%s:%d", opts.DefaultHTTPHost, opts.DefaultHTTPPort) } else { // If we do not have a host, default to unix socket defaultHost = fmt.Sprintf("unix://%s", opts.DefaultUnixSocket) } return opts.ValidateHost(defaultHost) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/client_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "bytes" "fmt" "io/ioutil" "net" "net/http" "net/url" "os" "path/filepath" "reflect" "strconv" "strings" "testing" "time" "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp" ) func TestNewAPIClient(t *testing.T) { endpoint := "http://localhost:4243" client, err := NewClient(endpoint) if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } // test unix socket endpoints endpoint = "unix:///var/run/docker.sock" client, err = NewClient(endpoint) if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } if !client.SkipServerVersionCheck { t.Error("Expected SkipServerVersionCheck to be true, got false") } if client.requestedAPIVersion != nil { t.Errorf("Expected requestedAPIVersion to be nil, got %#v.", client.requestedAPIVersion) } } func newTLSClient(endpoint string) (*Client, error) { return NewTLSClient(endpoint, "testing/data/cert.pem", "testing/data/key.pem", "testing/data/ca.pem") } func TestNewTSLAPIClient(t *testing.T) { endpoint := "https://localhost:4243" client, err := newTLSClient(endpoint) if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } if !client.SkipServerVersionCheck { t.Error("Expected SkipServerVersionCheck to be true, got false") } if client.requestedAPIVersion != nil { t.Errorf("Expected requestedAPIVersion to be nil, got %#v.", client.requestedAPIVersion) } } func TestNewVersionedClient(t *testing.T) { endpoint := "http://localhost:4243" client, err := NewVersionedClient(endpoint, "1.12") if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) } if client.SkipServerVersionCheck { t.Error("Expected SkipServerVersionCheck to be false, got true") } } func TestNewVersionedClientFromEnv(t *testing.T) { endpoint := "tcp://localhost:2376" endpointURL := "http://localhost:2376" os.Setenv("DOCKER_HOST", endpoint) os.Setenv("DOCKER_TLS_VERIFY", "") client, err := NewVersionedClientFromEnv("1.12") if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } if client.endpointURL.String() != endpointURL { t.Errorf("Expected endpointURL %s. Got %s.", endpoint, client.endpoint) } if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) } if client.SkipServerVersionCheck { t.Error("Expected SkipServerVersionCheck to be false, got true") } } func TestNewVersionedClientFromEnvTLS(t *testing.T) { endpoint := "tcp://localhost:2376" endpointURL := "https://localhost:2376" base, _ := os.Getwd() os.Setenv("DOCKER_CERT_PATH", filepath.Join(base, "/testing/data/")) os.Setenv("DOCKER_HOST", endpoint) os.Setenv("DOCKER_TLS_VERIFY", "1") client, err := NewVersionedClientFromEnv("1.12") if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } if client.endpointURL.String() != endpointURL { t.Errorf("Expected endpointURL %s. Got %s.", endpoint, client.endpoint) } if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.12" { t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.12", reqVersion) } if client.SkipServerVersionCheck { t.Error("Expected SkipServerVersionCheck to be false, got true") } } func TestNewTLSVersionedClient(t *testing.T) { certPath := "testing/data/cert.pem" keyPath := "testing/data/key.pem" caPath := "testing/data/ca.pem" endpoint := "https://localhost:4243" client, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14") if err != nil { t.Fatal(err) } if client.endpoint != endpoint { t.Errorf("Expected endpoint %s. Got %s.", endpoint, client.endpoint) } if reqVersion := client.requestedAPIVersion.String(); reqVersion != "1.14" { t.Errorf("Wrong requestAPIVersion. Want %q. Got %q.", "1.14", reqVersion) } if client.SkipServerVersionCheck { t.Error("Expected SkipServerVersionCheck to be false, got true") } } func TestNewTLSVersionedClientInvalidCA(t *testing.T) { certPath := "testing/data/cert.pem" keyPath := "testing/data/key.pem" caPath := "testing/data/key.pem" endpoint := "https://localhost:4243" _, err := NewVersionedTLSClient(endpoint, certPath, keyPath, caPath, "1.14") if err == nil { t.Errorf("Expected invalid ca at %s", caPath) } } func TestNewClientInvalidEndpoint(t *testing.T) { cases := []string{ "htp://localhost:3243", "http://localhost:a", "", "http://localhost:8080:8383", "http://localhost:65536", "https://localhost:-20", } for _, c := range cases { client, err := NewClient(c) if client != nil { t.Errorf("Want client for invalid endpoint, got %#v.", client) } if !reflect.DeepEqual(err, ErrInvalidEndpoint) { t.Errorf("NewClient(%q): Got invalid error for invalid endpoint. Want %#v. Got %#v.", c, ErrInvalidEndpoint, err) } } } func TestNewClientNoSchemeEndpoint(t *testing.T) { cases := []string{"localhost", "localhost:8080"} for _, c := range cases { client, err := NewClient(c) if client == nil { t.Errorf("Want client for scheme-less endpoint, got ") } if err != nil { t.Errorf("Got unexpected error scheme-less endpoint: %q", err) } } } func TestNewTLSClient(t *testing.T) { var tests = []struct { endpoint string expected string }{ {"tcp://localhost:2376", "https"}, {"tcp://localhost:2375", "https"}, {"tcp://localhost:4000", "https"}, {"http://localhost:4000", "https"}, } for _, tt := range tests { client, err := newTLSClient(tt.endpoint) if err != nil { t.Error(err) } got := client.endpointURL.Scheme if got != tt.expected { t.Errorf("endpointURL.Scheme: Got %s. Want %s.", got, tt.expected) } } } func TestEndpoint(t *testing.T) { client, err := NewVersionedClient("http://localhost:4243", "1.12") if err != nil { t.Fatal(err) } if endpoint := client.Endpoint(); endpoint != client.endpoint { t.Errorf("Client.Endpoint(): want %q. Got %q", client.endpoint, endpoint) } } func TestGetURL(t *testing.T) { var tests = []struct { endpoint string path string expected string }{ {"http://localhost:4243/", "/", "http://localhost:4243/"}, {"http://localhost:4243", "/", "http://localhost:4243/"}, {"http://localhost:4243", "/containers/ps", "http://localhost:4243/containers/ps"}, {"tcp://localhost:4243", "/containers/ps", "http://localhost:4243/containers/ps"}, {"http://localhost:4243/////", "/", "http://localhost:4243/"}, {"unix:///var/run/docker.socket", "/containers", "/containers"}, } for _, tt := range tests { client, _ := NewClient(tt.endpoint) client.endpoint = tt.endpoint client.SkipServerVersionCheck = true got := client.getURL(tt.path) if got != tt.expected { t.Errorf("getURL(%q): Got %s. Want %s.", tt.path, got, tt.expected) } } } func TestGetFakeUnixURL(t *testing.T) { var tests = []struct { endpoint string path string expected string }{ {"unix://var/run/docker.sock", "/", "http://unix.sock/"}, {"unix://var/run/docker.socket", "/", "http://unix.sock/"}, {"unix://var/run/docker.sock", "/containers/ps", "http://unix.sock/containers/ps"}, } for _, tt := range tests { client, _ := NewClient(tt.endpoint) client.endpoint = tt.endpoint client.SkipServerVersionCheck = true got := client.getFakeUnixURL(tt.path) if got != tt.expected { t.Errorf("getURL(%q): Got %s. Want %s.", tt.path, got, tt.expected) } } } func TestError(t *testing.T) { fakeBody := ioutil.NopCloser(bytes.NewBufferString("bad parameter")) resp := &http.Response{ StatusCode: 400, Body: fakeBody, } err := newError(resp) expected := Error{Status: 400, Message: "bad parameter"} if !reflect.DeepEqual(expected, *err) { t.Errorf("Wrong error type. Want %#v. Got %#v.", expected, *err) } message := "API error (400): bad parameter" if err.Error() != message { t.Errorf("Wrong error message. Want %q. Got %q.", message, err.Error()) } } func TestQueryString(t *testing.T) { v := float32(2.4) f32QueryString := fmt.Sprintf("w=%s&x=10&y=10.35", strconv.FormatFloat(float64(v), 'f', -1, 64)) jsonPerson := url.QueryEscape(`{"Name":"gopher","age":4}`) var tests = []struct { input interface{} want string }{ {&ListContainersOptions{All: true}, "all=1"}, {ListContainersOptions{All: true}, "all=1"}, {ListContainersOptions{Before: "something"}, "before=something"}, {ListContainersOptions{Before: "something", Since: "other"}, "before=something&since=other"}, {ListContainersOptions{Filters: map[string][]string{"status": {"paused", "running"}}}, "filters=%7B%22status%22%3A%5B%22paused%22%2C%22running%22%5D%7D"}, {dumb{X: 10, Y: 10.35000}, "x=10&y=10.35"}, {dumb{W: v, X: 10, Y: 10.35000}, f32QueryString}, {dumb{X: 10, Y: 10.35000, Z: 10}, "x=10&y=10.35&zee=10"}, {dumb{v: 4, X: 10, Y: 10.35000}, "x=10&y=10.35"}, {dumb{T: 10, Y: 10.35000}, "y=10.35"}, {dumb{Person: &person{Name: "gopher", Age: 4}}, "p=" + jsonPerson}, {nil, ""}, {10, ""}, {"not_a_struct", ""}, } for _, tt := range tests { got := queryString(tt.input) if got != tt.want { t.Errorf("queryString(%v). Want %q. Got %q.", tt.input, tt.want, got) } } } func TestAPIVersions(t *testing.T) { var tests = []struct { a string b string expectedALessThanB bool expectedALessThanOrEqualToB bool expectedAGreaterThanB bool expectedAGreaterThanOrEqualToB bool }{ {"1.11", "1.11", false, true, false, true}, {"1.10", "1.11", true, true, false, false}, {"1.11", "1.10", false, false, true, true}, {"1.11-ubuntu0", "1.11", false, true, false, true}, {"1.10", "1.11-el7", true, true, false, false}, {"1.9", "1.11", true, true, false, false}, {"1.11", "1.9", false, false, true, true}, {"1.1.1", "1.1", false, false, true, true}, {"1.1", "1.1.1", true, true, false, false}, {"2.1", "1.1.1", false, false, true, true}, {"2.1", "1.3.1", false, false, true, true}, {"1.1.1", "2.1", true, true, false, false}, {"1.3.1", "2.1", true, true, false, false}, } for _, tt := range tests { a, _ := NewAPIVersion(tt.a) b, _ := NewAPIVersion(tt.b) if tt.expectedALessThanB && !a.LessThan(b) { t.Errorf("Expected %#v < %#v", a, b) } if tt.expectedALessThanOrEqualToB && !a.LessThanOrEqualTo(b) { t.Errorf("Expected %#v <= %#v", a, b) } if tt.expectedAGreaterThanB && !a.GreaterThan(b) { t.Errorf("Expected %#v > %#v", a, b) } if tt.expectedAGreaterThanOrEqualToB && !a.GreaterThanOrEqualTo(b) { t.Errorf("Expected %#v >= %#v", a, b) } } } func TestPing(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) err := client.Ping() if err != nil { t.Fatal(err) } } func TestPingFailing(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusInternalServerError} client := newTestClient(fakeRT) err := client.Ping() if err == nil { t.Fatal("Expected non nil error, got nil") } expectedErrMsg := "API error (500): " if err.Error() != expectedErrMsg { t.Fatalf("Expected error to be %q, got: %q", expectedErrMsg, err.Error()) } } func TestPingFailingWrongStatus(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusAccepted} client := newTestClient(fakeRT) err := client.Ping() if err == nil { t.Fatal("Expected non nil error, got nil") } expectedErrMsg := "API error (202): " if err.Error() != expectedErrMsg { t.Fatalf("Expected error to be %q, got: %q", expectedErrMsg, err.Error()) } } func TestPingErrorWithUnixSocket(t *testing.T) { go func() { li, err := net.Listen("unix", "/tmp/echo.sock") if err != nil { t.Fatal(err) } defer li.Close() if err != nil { t.Fatalf("Expected to get listener, but failed: %#v", err) } fd, err := li.Accept() if err != nil { t.Fatalf("Expected to accept connection, but failed: %#v", err) } buf := make([]byte, 512) nr, err := fd.Read(buf) // Create invalid response message to trigger error. data := buf[0:nr] for i := 0; i < 10; i++ { data[i] = 63 } _, err = fd.Write(data) if err != nil { t.Fatalf("Expected to write to socket, but failed: %#v", err) } return }() // Wait for unix socket to listen time.Sleep(10 * time.Millisecond) endpoint := "unix:///tmp/echo.sock" u, _ := parseEndpoint(endpoint, false) client := Client{ HTTPClient: cleanhttp.DefaultClient(), Dialer: &net.Dialer{}, endpoint: endpoint, endpointURL: u, SkipServerVersionCheck: true, } err := client.Ping() if err == nil { t.Fatal("Expected non nil error, got nil") } } type FakeRoundTripper struct { message string status int header map[string]string requests []*http.Request } func (rt *FakeRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) { body := strings.NewReader(rt.message) rt.requests = append(rt.requests, r) res := &http.Response{ StatusCode: rt.status, Body: ioutil.NopCloser(body), Header: make(http.Header), } for k, v := range rt.header { res.Header.Set(k, v) } return res, nil } func (rt *FakeRoundTripper) Reset() { rt.requests = nil } type person struct { Name string Age int `json:"age"` } type dumb struct { T int `qs:"-"` v int W float32 X int Y float64 Z int `qs:"zee"` Person *person `qs:"p"` } type fakeEndpointURL struct { Scheme string } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/container.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" "time" ) // ErrContainerAlreadyExists is the error returned by CreateContainer when the // container already exists. var ErrContainerAlreadyExists = errors.New("container already exists") // ListContainersOptions specify parameters to the ListContainers function. // // See https://goo.gl/47a6tO for more details. type ListContainersOptions struct { All bool Size bool Limit int Since string Before string Filters map[string][]string } // APIPort is a type that represents a port mapping returned by the Docker API type APIPort struct { PrivatePort int64 `json:"PrivatePort,omitempty" yaml:"PrivatePort,omitempty"` PublicPort int64 `json:"PublicPort,omitempty" yaml:"PublicPort,omitempty"` Type string `json:"Type,omitempty" yaml:"Type,omitempty"` IP string `json:"IP,omitempty" yaml:"IP,omitempty"` } // APIContainers represents each container in the list returned by // ListContainers. type APIContainers struct { ID string `json:"Id" yaml:"Id"` Image string `json:"Image,omitempty" yaml:"Image,omitempty"` Command string `json:"Command,omitempty" yaml:"Command,omitempty"` Created int64 `json:"Created,omitempty" yaml:"Created,omitempty"` Status string `json:"Status,omitempty" yaml:"Status,omitempty"` Ports []APIPort `json:"Ports,omitempty" yaml:"Ports,omitempty"` SizeRw int64 `json:"SizeRw,omitempty" yaml:"SizeRw,omitempty"` SizeRootFs int64 `json:"SizeRootFs,omitempty" yaml:"SizeRootFs,omitempty"` Names []string `json:"Names,omitempty" yaml:"Names,omitempty"` Labels map[string]string `json:"Labels,omitempty" yaml:"Labels, omitempty"` } // ListContainers returns a slice of containers matching the given criteria. // // See https://goo.gl/47a6tO for more details. func (c *Client) ListContainers(opts ListContainersOptions) ([]APIContainers, error) { path := "/containers/json?" + queryString(opts) resp, err := c.do("GET", path, doOptions{}) if err != nil { return nil, err } defer resp.Body.Close() var containers []APIContainers if err := json.NewDecoder(resp.Body).Decode(&containers); err != nil { return nil, err } return containers, nil } // Port represents the port number and the protocol, in the form // /. For example: 80/tcp. type Port string // Port returns the number of the port. func (p Port) Port() string { return strings.Split(string(p), "/")[0] } // Proto returns the name of the protocol. func (p Port) Proto() string { parts := strings.Split(string(p), "/") if len(parts) == 1 { return "tcp" } return parts[1] } // State represents the state of a container. type State struct { Running bool `json:"Running,omitempty" yaml:"Running,omitempty"` Paused bool `json:"Paused,omitempty" yaml:"Paused,omitempty"` Restarting bool `json:"Restarting,omitempty" yaml:"Restarting,omitempty"` OOMKilled bool `json:"OOMKilled,omitempty" yaml:"OOMKilled,omitempty"` Pid int `json:"Pid,omitempty" yaml:"Pid,omitempty"` ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty"` Error string `json:"Error,omitempty" yaml:"Error,omitempty"` StartedAt time.Time `json:"StartedAt,omitempty" yaml:"StartedAt,omitempty"` FinishedAt time.Time `json:"FinishedAt,omitempty" yaml:"FinishedAt,omitempty"` } // String returns the string representation of a state. func (s *State) String() string { if s.Running { if s.Paused { return "paused" } return fmt.Sprintf("Up %s", time.Now().UTC().Sub(s.StartedAt)) } return fmt.Sprintf("Exit %d", s.ExitCode) } // PortBinding represents the host/container port mapping as returned in the // `docker inspect` json type PortBinding struct { HostIP string `json:"HostIP,omitempty" yaml:"HostIP,omitempty"` HostPort string `json:"HostPort,omitempty" yaml:"HostPort,omitempty"` } // PortMapping represents a deprecated field in the `docker inspect` output, // and its value as found in NetworkSettings should always be nil type PortMapping map[string]string // ContainerNetwork represents the networking settings of a container per network. type ContainerNetwork struct { MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"` GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty"` GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty"` IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty"` IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty"` IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty"` Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty"` EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty"` } // NetworkSettings contains network-related information about a container type NetworkSettings struct { Networks map[string]ContainerNetwork `json:"Networks,omitempty" yaml:"Networks,omitempty"` IPAddress string `json:"IPAddress,omitempty" yaml:"IPAddress,omitempty"` IPPrefixLen int `json:"IPPrefixLen,omitempty" yaml:"IPPrefixLen,omitempty"` MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"` Gateway string `json:"Gateway,omitempty" yaml:"Gateway,omitempty"` Bridge string `json:"Bridge,omitempty" yaml:"Bridge,omitempty"` PortMapping map[string]PortMapping `json:"PortMapping,omitempty" yaml:"PortMapping,omitempty"` Ports map[Port][]PortBinding `json:"Ports,omitempty" yaml:"Ports,omitempty"` NetworkID string `json:"NetworkID,omitempty" yaml:"NetworkID,omitempty"` EndpointID string `json:"EndpointID,omitempty" yaml:"EndpointID,omitempty"` SandboxKey string `json:"SandboxKey,omitempty" yaml:"SandboxKey,omitempty"` GlobalIPv6Address string `json:"GlobalIPv6Address,omitempty" yaml:"GlobalIPv6Address,omitempty"` GlobalIPv6PrefixLen int `json:"GlobalIPv6PrefixLen,omitempty" yaml:"GlobalIPv6PrefixLen,omitempty"` IPv6Gateway string `json:"IPv6Gateway,omitempty" yaml:"IPv6Gateway,omitempty"` LinkLocalIPv6Address string `json:"LinkLocalIPv6Address,omitempty" yaml:"LinkLocalIPv6Address,omitempty"` LinkLocalIPv6PrefixLen int `json:"LinkLocalIPv6PrefixLen,omitempty" yaml:"LinkLocalIPv6PrefixLen,omitempty"` SecondaryIPAddresses []string `json:"SecondaryIPAddresses,omitempty" yaml:"SecondaryIPAddresses,omitempty"` SecondaryIPv6Addresses []string `json:"SecondaryIPv6Addresses,omitempty" yaml:"SecondaryIPv6Addresses,omitempty"` } // PortMappingAPI translates the port mappings as contained in NetworkSettings // into the format in which they would appear when returned by the API func (settings *NetworkSettings) PortMappingAPI() []APIPort { var mapping []APIPort for port, bindings := range settings.Ports { p, _ := parsePort(port.Port()) if len(bindings) == 0 { mapping = append(mapping, APIPort{ PrivatePort: int64(p), Type: port.Proto(), }) continue } for _, binding := range bindings { p, _ := parsePort(port.Port()) h, _ := parsePort(binding.HostPort) mapping = append(mapping, APIPort{ PrivatePort: int64(p), PublicPort: int64(h), Type: port.Proto(), IP: binding.HostIP, }) } } return mapping } func parsePort(rawPort string) (int, error) { port, err := strconv.ParseUint(rawPort, 10, 16) if err != nil { return 0, err } return int(port), nil } // Config is the list of configuration options used when creating a container. // Config does not contain the options that are specific to starting a container on a // given host. Those are contained in HostConfig type Config struct { Hostname string `json:"Hostname,omitempty" yaml:"Hostname,omitempty"` Domainname string `json:"Domainname,omitempty" yaml:"Domainname,omitempty"` User string `json:"User,omitempty" yaml:"User,omitempty"` Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty"` MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty"` MemoryReservation int64 `json:"MemoryReservation,omitempty" yaml:"MemoryReservation,omitempty"` KernelMemory int64 `json:"KernelMemory,omitempty" yaml:"KernelMemory,omitempty"` CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty"` CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty"` AttachStdin bool `json:"AttachStdin,omitempty" yaml:"AttachStdin,omitempty"` AttachStdout bool `json:"AttachStdout,omitempty" yaml:"AttachStdout,omitempty"` AttachStderr bool `json:"AttachStderr,omitempty" yaml:"AttachStderr,omitempty"` PortSpecs []string `json:"PortSpecs,omitempty" yaml:"PortSpecs,omitempty"` ExposedPorts map[Port]struct{} `json:"ExposedPorts,omitempty" yaml:"ExposedPorts,omitempty"` StopSignal string `json:"StopSignal,omitempty" yaml:"StopSignal,omitempty"` Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty"` OpenStdin bool `json:"OpenStdin,omitempty" yaml:"OpenStdin,omitempty"` StdinOnce bool `json:"StdinOnce,omitempty" yaml:"StdinOnce,omitempty"` Env []string `json:"Env,omitempty" yaml:"Env,omitempty"` Cmd []string `json:"Cmd" yaml:"Cmd"` DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty"` // For Docker API v1.9 and below only Image string `json:"Image,omitempty" yaml:"Image,omitempty"` Volumes map[string]struct{} `json:"Volumes,omitempty" yaml:"Volumes,omitempty"` VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty"` VolumesFrom string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty"` WorkingDir string `json:"WorkingDir,omitempty" yaml:"WorkingDir,omitempty"` MacAddress string `json:"MacAddress,omitempty" yaml:"MacAddress,omitempty"` Entrypoint []string `json:"Entrypoint" yaml:"Entrypoint"` NetworkDisabled bool `json:"NetworkDisabled,omitempty" yaml:"NetworkDisabled,omitempty"` SecurityOpts []string `json:"SecurityOpts,omitempty" yaml:"SecurityOpts,omitempty"` OnBuild []string `json:"OnBuild,omitempty" yaml:"OnBuild,omitempty"` Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty"` Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` } // Mount represents a mount point in the container. // // It has been added in the version 1.20 of the Docker API, available since // Docker 1.8. type Mount struct { Name string Source string Destination string Driver string Mode string RW bool } // LogConfig defines the log driver type and the configuration for it. type LogConfig struct { Type string `json:"Type,omitempty" yaml:"Type,omitempty"` Config map[string]string `json:"Config,omitempty" yaml:"Config,omitempty"` } // ULimit defines system-wide resource limitations // This can help a lot in system administration, e.g. when a user starts too many processes and therefore makes the system unresponsive for other users. type ULimit struct { Name string `json:"Name,omitempty" yaml:"Name,omitempty"` Soft int64 `json:"Soft,omitempty" yaml:"Soft,omitempty"` Hard int64 `json:"Hard,omitempty" yaml:"Hard,omitempty"` } // SwarmNode containers information about which Swarm node the container is on type SwarmNode struct { ID string `json:"ID,omitempty" yaml:"ID,omitempty"` IP string `json:"IP,omitempty" yaml:"IP,omitempty"` Addr string `json:"Addr,omitempty" yaml:"Addr,omitempty"` Name string `json:"Name,omitempty" yaml:"Name,omitempty"` CPUs int64 `json:"CPUs,omitempty" yaml:"CPUs,omitempty"` Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty"` Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` } // Container is the type encompasing everything about a container - its config, // hostconfig, etc. type Container struct { ID string `json:"Id" yaml:"Id"` Created time.Time `json:"Created,omitempty" yaml:"Created,omitempty"` Path string `json:"Path,omitempty" yaml:"Path,omitempty"` Args []string `json:"Args,omitempty" yaml:"Args,omitempty"` Config *Config `json:"Config,omitempty" yaml:"Config,omitempty"` State State `json:"State,omitempty" yaml:"State,omitempty"` Image string `json:"Image,omitempty" yaml:"Image,omitempty"` Node *SwarmNode `json:"Node,omitempty" yaml:"Node,omitempty"` NetworkSettings *NetworkSettings `json:"NetworkSettings,omitempty" yaml:"NetworkSettings,omitempty"` SysInitPath string `json:"SysInitPath,omitempty" yaml:"SysInitPath,omitempty"` ResolvConfPath string `json:"ResolvConfPath,omitempty" yaml:"ResolvConfPath,omitempty"` HostnamePath string `json:"HostnamePath,omitempty" yaml:"HostnamePath,omitempty"` HostsPath string `json:"HostsPath,omitempty" yaml:"HostsPath,omitempty"` LogPath string `json:"LogPath,omitempty" yaml:"LogPath,omitempty"` Name string `json:"Name,omitempty" yaml:"Name,omitempty"` Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty"` Mounts []Mount `json:"Mounts,omitempty" yaml:"Mounts,omitempty"` Volumes map[string]string `json:"Volumes,omitempty" yaml:"Volumes,omitempty"` VolumesRW map[string]bool `json:"VolumesRW,omitempty" yaml:"VolumesRW,omitempty"` HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty"` ExecIDs []string `json:"ExecIDs,omitempty" yaml:"ExecIDs,omitempty"` RestartCount int `json:"RestartCount,omitempty" yaml:"RestartCount,omitempty"` AppArmorProfile string `json:"AppArmorProfile,omitempty" yaml:"AppArmorProfile,omitempty"` } // RenameContainerOptions specify parameters to the RenameContainer function. // // See https://goo.gl/laSOIy for more details. type RenameContainerOptions struct { // ID of container to rename ID string `qs:"-"` // New name Name string `json:"name,omitempty" yaml:"name,omitempty"` } // RenameContainer updates and existing containers name // // See https://goo.gl/laSOIy for more details. func (c *Client) RenameContainer(opts RenameContainerOptions) error { resp, err := c.do("POST", fmt.Sprintf("/containers/"+opts.ID+"/rename?%s", queryString(opts)), doOptions{}) if err != nil { return err } resp.Body.Close() return nil } // InspectContainer returns information about a container by its ID. // // See https://goo.gl/RdIq0b for more details. func (c *Client) InspectContainer(id string) (*Container, error) { path := "/containers/" + id + "/json" resp, err := c.do("GET", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchContainer{ID: id} } return nil, err } defer resp.Body.Close() var container Container if err := json.NewDecoder(resp.Body).Decode(&container); err != nil { return nil, err } return &container, nil } // ContainerChanges returns changes in the filesystem of the given container. // // See https://goo.gl/9GsTIF for more details. func (c *Client) ContainerChanges(id string) ([]Change, error) { path := "/containers/" + id + "/changes" resp, err := c.do("GET", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchContainer{ID: id} } return nil, err } defer resp.Body.Close() var changes []Change if err := json.NewDecoder(resp.Body).Decode(&changes); err != nil { return nil, err } return changes, nil } // CreateContainerOptions specify parameters to the CreateContainer function. // // See https://goo.gl/WxQzrr for more details. type CreateContainerOptions struct { Name string Config *Config `qs:"-"` HostConfig *HostConfig `qs:"-"` } // CreateContainer creates a new container, returning the container instance, // or an error in case of failure. // // See https://goo.gl/WxQzrr for more details. func (c *Client) CreateContainer(opts CreateContainerOptions) (*Container, error) { path := "/containers/create?" + queryString(opts) resp, err := c.do( "POST", path, doOptions{ data: struct { *Config HostConfig *HostConfig `json:"HostConfig,omitempty" yaml:"HostConfig,omitempty"` }{ opts.Config, opts.HostConfig, }, }, ) if e, ok := err.(*Error); ok { if e.Status == http.StatusNotFound { return nil, ErrNoSuchImage } if e.Status == http.StatusConflict { return nil, ErrContainerAlreadyExists } } if err != nil { return nil, err } defer resp.Body.Close() var container Container if err := json.NewDecoder(resp.Body).Decode(&container); err != nil { return nil, err } container.Name = opts.Name return &container, nil } // KeyValuePair is a type for generic key/value pairs as used in the Lxc // configuration type KeyValuePair struct { Key string `json:"Key,omitempty" yaml:"Key,omitempty"` Value string `json:"Value,omitempty" yaml:"Value,omitempty"` } // RestartPolicy represents the policy for automatically restarting a container. // // Possible values are: // // - always: the docker daemon will always restart the container // - on-failure: the docker daemon will restart the container on failures, at // most MaximumRetryCount times // - no: the docker daemon will not restart the container automatically type RestartPolicy struct { Name string `json:"Name,omitempty" yaml:"Name,omitempty"` MaximumRetryCount int `json:"MaximumRetryCount,omitempty" yaml:"MaximumRetryCount,omitempty"` } // AlwaysRestart returns a restart policy that tells the Docker daemon to // always restart the container. func AlwaysRestart() RestartPolicy { return RestartPolicy{Name: "always"} } // RestartOnFailure returns a restart policy that tells the Docker daemon to // restart the container on failures, trying at most maxRetry times. func RestartOnFailure(maxRetry int) RestartPolicy { return RestartPolicy{Name: "on-failure", MaximumRetryCount: maxRetry} } // NeverRestart returns a restart policy that tells the Docker daemon to never // restart the container on failures. func NeverRestart() RestartPolicy { return RestartPolicy{Name: "no"} } // Device represents a device mapping between the Docker host and the // container. type Device struct { PathOnHost string `json:"PathOnHost,omitempty" yaml:"PathOnHost,omitempty"` PathInContainer string `json:"PathInContainer,omitempty" yaml:"PathInContainer,omitempty"` CgroupPermissions string `json:"CgroupPermissions,omitempty" yaml:"CgroupPermissions,omitempty"` } // HostConfig contains the container options related to starting a container on // a given host type HostConfig struct { Binds []string `json:"Binds,omitempty" yaml:"Binds,omitempty"` CapAdd []string `json:"CapAdd,omitempty" yaml:"CapAdd,omitempty"` CapDrop []string `json:"CapDrop,omitempty" yaml:"CapDrop,omitempty"` GroupAdd []string `json:"GroupAdd,omitempty" yaml:"GroupAdd,omitempty"` ContainerIDFile string `json:"ContainerIDFile,omitempty" yaml:"ContainerIDFile,omitempty"` LxcConf []KeyValuePair `json:"LxcConf,omitempty" yaml:"LxcConf,omitempty"` Privileged bool `json:"Privileged,omitempty" yaml:"Privileged,omitempty"` PortBindings map[Port][]PortBinding `json:"PortBindings,omitempty" yaml:"PortBindings,omitempty"` Links []string `json:"Links,omitempty" yaml:"Links,omitempty"` PublishAllPorts bool `json:"PublishAllPorts,omitempty" yaml:"PublishAllPorts,omitempty"` DNS []string `json:"Dns,omitempty" yaml:"Dns,omitempty"` // For Docker API v1.10 and above only DNSOptions []string `json:"DnsOptions,omitempty" yaml:"DnsOptions,omitempty"` DNSSearch []string `json:"DnsSearch,omitempty" yaml:"DnsSearch,omitempty"` ExtraHosts []string `json:"ExtraHosts,omitempty" yaml:"ExtraHosts,omitempty"` VolumesFrom []string `json:"VolumesFrom,omitempty" yaml:"VolumesFrom,omitempty"` NetworkMode string `json:"NetworkMode,omitempty" yaml:"NetworkMode,omitempty"` IpcMode string `json:"IpcMode,omitempty" yaml:"IpcMode,omitempty"` PidMode string `json:"PidMode,omitempty" yaml:"PidMode,omitempty"` UTSMode string `json:"UTSMode,omitempty" yaml:"UTSMode,omitempty"` RestartPolicy RestartPolicy `json:"RestartPolicy,omitempty" yaml:"RestartPolicy,omitempty"` Devices []Device `json:"Devices,omitempty" yaml:"Devices,omitempty"` LogConfig LogConfig `json:"LogConfig,omitempty" yaml:"LogConfig,omitempty"` ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty" yaml:"ReadonlyRootfs,omitempty"` SecurityOpt []string `json:"SecurityOpt,omitempty" yaml:"SecurityOpt,omitempty"` CgroupParent string `json:"CgroupParent,omitempty" yaml:"CgroupParent,omitempty"` Memory int64 `json:"Memory,omitempty" yaml:"Memory,omitempty"` MemorySwap int64 `json:"MemorySwap,omitempty" yaml:"MemorySwap,omitempty"` MemorySwappiness int64 `json:"MemorySwappiness,omitempty" yaml:"MemorySwappiness,omitempty"` OOMKillDisable bool `json:"OomKillDisable,omitempty" yaml:"OomKillDisable"` CPUShares int64 `json:"CpuShares,omitempty" yaml:"CpuShares,omitempty"` CPUSet string `json:"Cpuset,omitempty" yaml:"Cpuset,omitempty"` CPUSetCPUs string `json:"CpusetCpus,omitempty" yaml:"CpusetCpus,omitempty"` CPUSetMEMs string `json:"CpusetMems,omitempty" yaml:"CpusetMems,omitempty"` CPUQuota int64 `json:"CpuQuota,omitempty" yaml:"CpuQuota,omitempty"` CPUPeriod int64 `json:"CpuPeriod,omitempty" yaml:"CpuPeriod,omitempty"` BlkioWeight int64 `json:"BlkioWeight,omitempty" yaml:"BlkioWeight"` Ulimits []ULimit `json:"Ulimits,omitempty" yaml:"Ulimits,omitempty"` VolumeDriver string `json:"VolumeDriver,omitempty" yaml:"VolumeDriver,omitempty"` OomScoreAdj int `json:"OomScoreAdj,omitempty" yaml:"OomScoreAdj,omitempty"` } // StartContainer starts a container, returning an error in case of failure. // // See https://goo.gl/MrBAJv for more details. func (c *Client) StartContainer(id string, hostConfig *HostConfig) error { path := "/containers/" + id + "/start" resp, err := c.do("POST", path, doOptions{data: hostConfig, forceJSON: true}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: id, Err: err} } return err } if resp.StatusCode == http.StatusNotModified { return &ContainerAlreadyRunning{ID: id} } resp.Body.Close() return nil } // StopContainer stops a container, killing it after the given timeout (in // seconds). // // See https://goo.gl/USqsFt for more details. func (c *Client) StopContainer(id string, timeout uint) error { path := fmt.Sprintf("/containers/%s/stop?t=%d", id, timeout) resp, err := c.do("POST", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: id} } return err } if resp.StatusCode == http.StatusNotModified { return &ContainerNotRunning{ID: id} } resp.Body.Close() return nil } // RestartContainer stops a container, killing it after the given timeout (in // seconds), during the stop process. // // See https://goo.gl/QzsDnz for more details. func (c *Client) RestartContainer(id string, timeout uint) error { path := fmt.Sprintf("/containers/%s/restart?t=%d", id, timeout) resp, err := c.do("POST", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: id} } return err } resp.Body.Close() return nil } // PauseContainer pauses the given container. // // See https://goo.gl/OF7W9X for more details. func (c *Client) PauseContainer(id string) error { path := fmt.Sprintf("/containers/%s/pause", id) resp, err := c.do("POST", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: id} } return err } resp.Body.Close() return nil } // UnpauseContainer unpauses the given container. // // See https://goo.gl/7dwyPA for more details. func (c *Client) UnpauseContainer(id string) error { path := fmt.Sprintf("/containers/%s/unpause", id) resp, err := c.do("POST", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: id} } return err } resp.Body.Close() return nil } // TopResult represents the list of processes running in a container, as // returned by /containers//top. // // See https://goo.gl/Rb46aY for more details. type TopResult struct { Titles []string Processes [][]string } // TopContainer returns processes running inside a container // // See https://goo.gl/Rb46aY for more details. func (c *Client) TopContainer(id string, psArgs string) (TopResult, error) { var args string var result TopResult if psArgs != "" { args = fmt.Sprintf("?ps_args=%s", psArgs) } path := fmt.Sprintf("/containers/%s/top%s", id, args) resp, err := c.do("GET", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return result, &NoSuchContainer{ID: id} } return result, err } defer resp.Body.Close() if err := json.NewDecoder(resp.Body).Decode(&result); err != nil { return result, err } return result, nil } // Stats represents container statistics, returned by /containers//stats. // // See https://goo.gl/GNmLHb for more details. type Stats struct { Read time.Time `json:"read,omitempty" yaml:"read,omitempty"` Network NetworkStats `json:"network,omitempty" yaml:"network,omitempty"` Networks map[string]NetworkStats `json:"networks,omitempty" yaml:"networks,omitempty"` MemoryStats struct { Stats struct { TotalPgmafault uint64 `json:"total_pgmafault,omitempty" yaml:"total_pgmafault,omitempty"` Cache uint64 `json:"cache,omitempty" yaml:"cache,omitempty"` MappedFile uint64 `json:"mapped_file,omitempty" yaml:"mapped_file,omitempty"` TotalInactiveFile uint64 `json:"total_inactive_file,omitempty" yaml:"total_inactive_file,omitempty"` Pgpgout uint64 `json:"pgpgout,omitempty" yaml:"pgpgout,omitempty"` Rss uint64 `json:"rss,omitempty" yaml:"rss,omitempty"` TotalMappedFile uint64 `json:"total_mapped_file,omitempty" yaml:"total_mapped_file,omitempty"` Writeback uint64 `json:"writeback,omitempty" yaml:"writeback,omitempty"` Unevictable uint64 `json:"unevictable,omitempty" yaml:"unevictable,omitempty"` Pgpgin uint64 `json:"pgpgin,omitempty" yaml:"pgpgin,omitempty"` TotalUnevictable uint64 `json:"total_unevictable,omitempty" yaml:"total_unevictable,omitempty"` Pgmajfault uint64 `json:"pgmajfault,omitempty" yaml:"pgmajfault,omitempty"` TotalRss uint64 `json:"total_rss,omitempty" yaml:"total_rss,omitempty"` TotalRssHuge uint64 `json:"total_rss_huge,omitempty" yaml:"total_rss_huge,omitempty"` TotalWriteback uint64 `json:"total_writeback,omitempty" yaml:"total_writeback,omitempty"` TotalInactiveAnon uint64 `json:"total_inactive_anon,omitempty" yaml:"total_inactive_anon,omitempty"` RssHuge uint64 `json:"rss_huge,omitempty" yaml:"rss_huge,omitempty"` HierarchicalMemoryLimit uint64 `json:"hierarchical_memory_limit,omitempty" yaml:"hierarchical_memory_limit,omitempty"` TotalPgfault uint64 `json:"total_pgfault,omitempty" yaml:"total_pgfault,omitempty"` TotalActiveFile uint64 `json:"total_active_file,omitempty" yaml:"total_active_file,omitempty"` ActiveAnon uint64 `json:"active_anon,omitempty" yaml:"active_anon,omitempty"` TotalActiveAnon uint64 `json:"total_active_anon,omitempty" yaml:"total_active_anon,omitempty"` TotalPgpgout uint64 `json:"total_pgpgout,omitempty" yaml:"total_pgpgout,omitempty"` TotalCache uint64 `json:"total_cache,omitempty" yaml:"total_cache,omitempty"` InactiveAnon uint64 `json:"inactive_anon,omitempty" yaml:"inactive_anon,omitempty"` ActiveFile uint64 `json:"active_file,omitempty" yaml:"active_file,omitempty"` Pgfault uint64 `json:"pgfault,omitempty" yaml:"pgfault,omitempty"` InactiveFile uint64 `json:"inactive_file,omitempty" yaml:"inactive_file,omitempty"` TotalPgpgin uint64 `json:"total_pgpgin,omitempty" yaml:"total_pgpgin,omitempty"` HierarchicalMemswLimit uint64 `json:"hierarchical_memsw_limit,omitempty" yaml:"hierarchical_memsw_limit,omitempty"` Swap uint64 `json:"swap,omitempty" yaml:"swap,omitempty"` } `json:"stats,omitempty" yaml:"stats,omitempty"` MaxUsage uint64 `json:"max_usage,omitempty" yaml:"max_usage,omitempty"` Usage uint64 `json:"usage,omitempty" yaml:"usage,omitempty"` Failcnt uint64 `json:"failcnt,omitempty" yaml:"failcnt,omitempty"` Limit uint64 `json:"limit,omitempty" yaml:"limit,omitempty"` } `json:"memory_stats,omitempty" yaml:"memory_stats,omitempty"` BlkioStats struct { IOServiceBytesRecursive []BlkioStatsEntry `json:"io_service_bytes_recursive,omitempty" yaml:"io_service_bytes_recursive,omitempty"` IOServicedRecursive []BlkioStatsEntry `json:"io_serviced_recursive,omitempty" yaml:"io_serviced_recursive,omitempty"` IOQueueRecursive []BlkioStatsEntry `json:"io_queue_recursive,omitempty" yaml:"io_queue_recursive,omitempty"` IOServiceTimeRecursive []BlkioStatsEntry `json:"io_service_time_recursive,omitempty" yaml:"io_service_time_recursive,omitempty"` IOWaitTimeRecursive []BlkioStatsEntry `json:"io_wait_time_recursive,omitempty" yaml:"io_wait_time_recursive,omitempty"` IOMergedRecursive []BlkioStatsEntry `json:"io_merged_recursive,omitempty" yaml:"io_merged_recursive,omitempty"` IOTimeRecursive []BlkioStatsEntry `json:"io_time_recursive,omitempty" yaml:"io_time_recursive,omitempty"` SectorsRecursive []BlkioStatsEntry `json:"sectors_recursive,omitempty" yaml:"sectors_recursive,omitempty"` } `json:"blkio_stats,omitempty" yaml:"blkio_stats,omitempty"` CPUStats CPUStats `json:"cpu_stats,omitempty" yaml:"cpu_stats,omitempty"` PreCPUStats CPUStats `json:"precpu_stats,omitempty"` } // NetworkStats is a stats entry for network stats type NetworkStats struct { RxDropped uint64 `json:"rx_dropped,omitempty" yaml:"rx_dropped,omitempty"` RxBytes uint64 `json:"rx_bytes,omitempty" yaml:"rx_bytes,omitempty"` RxErrors uint64 `json:"rx_errors,omitempty" yaml:"rx_errors,omitempty"` TxPackets uint64 `json:"tx_packets,omitempty" yaml:"tx_packets,omitempty"` TxDropped uint64 `json:"tx_dropped,omitempty" yaml:"tx_dropped,omitempty"` RxPackets uint64 `json:"rx_packets,omitempty" yaml:"rx_packets,omitempty"` TxErrors uint64 `json:"tx_errors,omitempty" yaml:"tx_errors,omitempty"` TxBytes uint64 `json:"tx_bytes,omitempty" yaml:"tx_bytes,omitempty"` } // CPUStats is a stats entry for cpu stats type CPUStats struct { CPUUsage struct { PercpuUsage []uint64 `json:"percpu_usage,omitempty" yaml:"percpu_usage,omitempty"` UsageInUsermode uint64 `json:"usage_in_usermode,omitempty" yaml:"usage_in_usermode,omitempty"` TotalUsage uint64 `json:"total_usage,omitempty" yaml:"total_usage,omitempty"` UsageInKernelmode uint64 `json:"usage_in_kernelmode,omitempty" yaml:"usage_in_kernelmode,omitempty"` } `json:"cpu_usage,omitempty" yaml:"cpu_usage,omitempty"` SystemCPUUsage uint64 `json:"system_cpu_usage,omitempty" yaml:"system_cpu_usage,omitempty"` ThrottlingData struct { Periods uint64 `json:"periods,omitempty"` ThrottledPeriods uint64 `json:"throttled_periods,omitempty"` ThrottledTime uint64 `json:"throttled_time,omitempty"` } `json:"throttling_data,omitempty" yaml:"throttling_data,omitempty"` } // BlkioStatsEntry is a stats entry for blkio_stats type BlkioStatsEntry struct { Major uint64 `json:"major,omitempty" yaml:"major,omitempty"` Minor uint64 `json:"minor,omitempty" yaml:"minor,omitempty"` Op string `json:"op,omitempty" yaml:"op,omitempty"` Value uint64 `json:"value,omitempty" yaml:"value,omitempty"` } // StatsOptions specify parameters to the Stats function. // // See https://goo.gl/GNmLHb for more details. type StatsOptions struct { ID string Stats chan<- *Stats Stream bool // A flag that enables stopping the stats operation Done <-chan bool // Initial connection timeout Timeout time.Duration } // Stats sends container statistics for the given container to the given channel. // // This function is blocking, similar to a streaming call for logs, and should be run // on a separate goroutine from the caller. Note that this function will block until // the given container is removed, not just exited. When finished, this function // will close the given channel. Alternatively, function can be stopped by // signaling on the Done channel. // // See https://goo.gl/GNmLHb for more details. func (c *Client) Stats(opts StatsOptions) (retErr error) { errC := make(chan error, 1) readCloser, writeCloser := io.Pipe() defer func() { close(opts.Stats) select { case err := <-errC: if err != nil && retErr == nil { retErr = err } default: // No errors } if err := readCloser.Close(); err != nil && retErr == nil { retErr = err } }() go func() { err := c.stream("GET", fmt.Sprintf("/containers/%s/stats?stream=%v", opts.ID, opts.Stream), streamOptions{ rawJSONStream: true, useJSONDecoder: true, stdout: writeCloser, timeout: opts.Timeout, }) if err != nil { dockerError, ok := err.(*Error) if ok { if dockerError.Status == http.StatusNotFound { err = &NoSuchContainer{ID: opts.ID} } } } if closeErr := writeCloser.Close(); closeErr != nil && err == nil { err = closeErr } errC <- err close(errC) }() quit := make(chan struct{}) defer close(quit) go func() { // block here waiting for the signal to stop function select { case <-opts.Done: readCloser.Close() case <-quit: return } }() decoder := json.NewDecoder(readCloser) stats := new(Stats) for err := decoder.Decode(stats); err != io.EOF; err = decoder.Decode(stats) { if err != nil { return err } opts.Stats <- stats stats = new(Stats) } return nil } // KillContainerOptions represents the set of options that can be used in a // call to KillContainer. // // See https://goo.gl/hkS9i8 for more details. type KillContainerOptions struct { // The ID of the container. ID string `qs:"-"` // The signal to send to the container. When omitted, Docker server // will assume SIGKILL. Signal Signal } // KillContainer sends a signal to a container, returning an error in case of // failure. // // See https://goo.gl/hkS9i8 for more details. func (c *Client) KillContainer(opts KillContainerOptions) error { path := "/containers/" + opts.ID + "/kill" + "?" + queryString(opts) resp, err := c.do("POST", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: opts.ID} } return err } resp.Body.Close() return nil } // RemoveContainerOptions encapsulates options to remove a container. // // See https://goo.gl/RQyX62 for more details. type RemoveContainerOptions struct { // The ID of the container. ID string `qs:"-"` // A flag that indicates whether Docker should remove the volumes // associated to the container. RemoveVolumes bool `qs:"v"` // A flag that indicates whether Docker should remove the container // even if it is currently running. Force bool } // RemoveContainer removes a container, returning an error in case of failure. // // See https://goo.gl/RQyX62 for more details. func (c *Client) RemoveContainer(opts RemoveContainerOptions) error { path := "/containers/" + opts.ID + "?" + queryString(opts) resp, err := c.do("DELETE", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: opts.ID} } return err } resp.Body.Close() return nil } // UploadToContainerOptions is the set of options that can be used when // uploading an archive into a container. // // See https://goo.gl/Ss97HW for more details. type UploadToContainerOptions struct { InputStream io.Reader `json:"-" qs:"-"` Path string `qs:"path"` NoOverwriteDirNonDir bool `qs:"noOverwriteDirNonDir"` } // UploadToContainer uploads a tar archive to be extracted to a path in the // filesystem of the container. // // See https://goo.gl/Ss97HW for more details. func (c *Client) UploadToContainer(id string, opts UploadToContainerOptions) error { url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts) return c.stream("PUT", url, streamOptions{ in: opts.InputStream, }) } // DownloadFromContainerOptions is the set of options that can be used when // downloading resources from a container. // // See https://goo.gl/KnZJDX for more details. type DownloadFromContainerOptions struct { OutputStream io.Writer `json:"-" qs:"-"` Path string `qs:"path"` } // DownloadFromContainer downloads a tar archive of files or folders in a container. // // See https://goo.gl/KnZJDX for more details. func (c *Client) DownloadFromContainer(id string, opts DownloadFromContainerOptions) error { url := fmt.Sprintf("/containers/%s/archive?", id) + queryString(opts) return c.stream("GET", url, streamOptions{ setRawTerminal: true, stdout: opts.OutputStream, }) } // CopyFromContainerOptions has been DEPRECATED, please use DownloadFromContainerOptions along with DownloadFromContainer. // // See https://goo.gl/R2jevW for more details. type CopyFromContainerOptions struct { OutputStream io.Writer `json:"-"` Container string `json:"-"` Resource string } // CopyFromContainer has been DEPRECATED, please use DownloadFromContainerOptions along with DownloadFromContainer. // // See https://goo.gl/R2jevW for more details. func (c *Client) CopyFromContainer(opts CopyFromContainerOptions) error { if opts.Container == "" { return &NoSuchContainer{ID: opts.Container} } url := fmt.Sprintf("/containers/%s/copy", opts.Container) resp, err := c.do("POST", url, doOptions{data: opts}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchContainer{ID: opts.Container} } return err } defer resp.Body.Close() _, err = io.Copy(opts.OutputStream, resp.Body) return err } // WaitContainer blocks until the given container stops, return the exit code // of the container status. // // See https://goo.gl/Gc1rge for more details. func (c *Client) WaitContainer(id string) (int, error) { resp, err := c.do("POST", "/containers/"+id+"/wait", doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return 0, &NoSuchContainer{ID: id} } return 0, err } defer resp.Body.Close() var r struct{ StatusCode int } if err := json.NewDecoder(resp.Body).Decode(&r); err != nil { return 0, err } return r.StatusCode, nil } // CommitContainerOptions aggregates parameters to the CommitContainer method. // // See https://goo.gl/mqfoCw for more details. type CommitContainerOptions struct { Container string Repository string `qs:"repo"` Tag string Message string `qs:"comment"` Author string Run *Config `qs:"-"` } // CommitContainer creates a new image from a container's changes. // // See https://goo.gl/mqfoCw for more details. func (c *Client) CommitContainer(opts CommitContainerOptions) (*Image, error) { path := "/commit?" + queryString(opts) resp, err := c.do("POST", path, doOptions{data: opts.Run}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchContainer{ID: opts.Container} } return nil, err } defer resp.Body.Close() var image Image if err := json.NewDecoder(resp.Body).Decode(&image); err != nil { return nil, err } return &image, nil } // AttachToContainerOptions is the set of options that can be used when // attaching to a container. // // See https://goo.gl/NKpkFk for more details. type AttachToContainerOptions struct { Container string `qs:"-"` InputStream io.Reader `qs:"-"` OutputStream io.Writer `qs:"-"` ErrorStream io.Writer `qs:"-"` // Get container logs, sending it to OutputStream. Logs bool // Stream the response? Stream bool // Attach to stdin, and use InputStream. Stdin bool // Attach to stdout, and use OutputStream. Stdout bool // Attach to stderr, and use ErrorStream. Stderr bool // If set, after a successful connect, a sentinel will be sent and then the // client will block on receive before continuing. // // It must be an unbuffered channel. Using a buffered channel can lead // to unexpected behavior. Success chan struct{} // Use raw terminal? Usually true when the container contains a TTY. RawTerminal bool `qs:"-"` } // AttachToContainer attaches to a container, using the given options. // // See https://goo.gl/NKpkFk for more details. func (c *Client) AttachToContainer(opts AttachToContainerOptions) error { cw, err := c.AttachToContainerNonBlocking(opts) if err != nil { return err } return cw.Wait() } // AttachToContainerNonBlocking attaches to a container, using the given options. // This function does not block. // // See https://goo.gl/NKpkFk for more details. func (c *Client) AttachToContainerNonBlocking(opts AttachToContainerOptions) (CloseWaiter, error) { if opts.Container == "" { return nil, &NoSuchContainer{ID: opts.Container} } path := "/containers/" + opts.Container + "/attach?" + queryString(opts) return c.hijack("POST", path, hijackOptions{ success: opts.Success, setRawTerminal: opts.RawTerminal, in: opts.InputStream, stdout: opts.OutputStream, stderr: opts.ErrorStream, }) } // LogsOptions represents the set of options used when getting logs from a // container. // // See https://goo.gl/yl8PGm for more details. type LogsOptions struct { Container string `qs:"-"` OutputStream io.Writer `qs:"-"` ErrorStream io.Writer `qs:"-"` Follow bool Stdout bool Stderr bool Since int64 Timestamps bool Tail string // Use raw terminal? Usually true when the container contains a TTY. RawTerminal bool `qs:"-"` } // Logs gets stdout and stderr logs from the specified container. // // See https://goo.gl/yl8PGm for more details. func (c *Client) Logs(opts LogsOptions) error { if opts.Container == "" { return &NoSuchContainer{ID: opts.Container} } if opts.Tail == "" { opts.Tail = "all" } path := "/containers/" + opts.Container + "/logs?" + queryString(opts) return c.stream("GET", path, streamOptions{ setRawTerminal: opts.RawTerminal, stdout: opts.OutputStream, stderr: opts.ErrorStream, }) } // ResizeContainerTTY resizes the terminal to the given height and width. // // See https://goo.gl/xERhCc for more details. func (c *Client) ResizeContainerTTY(id string, height, width int) error { params := make(url.Values) params.Set("h", strconv.Itoa(height)) params.Set("w", strconv.Itoa(width)) resp, err := c.do("POST", "/containers/"+id+"/resize?"+params.Encode(), doOptions{}) if err != nil { return err } resp.Body.Close() return nil } // ExportContainerOptions is the set of parameters to the ExportContainer // method. // // See https://goo.gl/dOkTyk for more details. type ExportContainerOptions struct { ID string OutputStream io.Writer } // ExportContainer export the contents of container id as tar archive // and prints the exported contents to stdout. // // See https://goo.gl/dOkTyk for more details. func (c *Client) ExportContainer(opts ExportContainerOptions) error { if opts.ID == "" { return &NoSuchContainer{ID: opts.ID} } url := fmt.Sprintf("/containers/%s/export", opts.ID) return c.stream("GET", url, streamOptions{ setRawTerminal: true, stdout: opts.OutputStream, }) } // NoSuchContainer is the error returned when a given container does not exist. type NoSuchContainer struct { ID string Err error } func (err *NoSuchContainer) Error() string { if err.Err != nil { return err.Err.Error() } return "No such container: " + err.ID } // ContainerAlreadyRunning is the error returned when a given container is // already running. type ContainerAlreadyRunning struct { ID string } func (err *ContainerAlreadyRunning) Error() string { return "Container already running: " + err.ID } // ContainerNotRunning is the error returned when a given container is not // running. type ContainerNotRunning struct { ID string } func (err *ContainerNotRunning) Error() string { return "Container not running: " + err.ID } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/container_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "bytes" "encoding/json" "errors" "fmt" "io/ioutil" "net" "net/http" "net/http/httptest" "net/url" "os" "reflect" "regexp" "runtime" "strconv" "strings" "testing" "time" "github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp" ) func TestStateString(t *testing.T) { started := time.Now().Add(-3 * time.Hour) var tests = []struct { input State expected string }{ {State{Running: true, Paused: true}, "^paused$"}, {State{Running: true, StartedAt: started}, "^Up 3h.*$"}, {State{Running: false, ExitCode: 7}, "^Exit 7$"}, } for _, tt := range tests { re := regexp.MustCompile(tt.expected) if got := tt.input.String(); !re.MatchString(got) { t.Errorf("State.String(): wrong result. Want %q. Got %q.", tt.expected, got) } } } func TestListContainers(t *testing.T) { jsonContainers := `[ { "Id": "8dfafdbc3a40", "Image": "base:latest", "Command": "echo 1", "Created": 1367854155, "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "Status": "Exit 0" }, { "Id": "9cd87474be90", "Image": "base:latest", "Command": "echo 222222", "Created": 1367854155, "Ports":[{"PrivatePort": 2222, "PublicPort": 3333, "Type": "tcp"}], "Status": "Exit 0" }, { "Id": "3176a2479c92", "Image": "base:latest", "Command": "echo 3333333333333333", "Created": 1367854154, "Ports":[{"PrivatePort": 2221, "PublicPort": 3331, "Type": "tcp"}], "Status": "Exit 0" }, { "Id": "4cb07b47f9fb", "Image": "base:latest", "Command": "echo 444444444444444444444444444444444", "Ports":[{"PrivatePort": 2223, "PublicPort": 3332, "Type": "tcp"}], "Created": 1367854152, "Status": "Exit 0" } ]` var expected []APIContainers err := json.Unmarshal([]byte(jsonContainers), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: jsonContainers, status: http.StatusOK}) containers, err := client.ListContainers(ListContainersOptions{}) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(containers, expected) { t.Errorf("ListContainers: Expected %#v. Got %#v.", expected, containers) } } func TestListContainersParams(t *testing.T) { var tests = []struct { input ListContainersOptions params map[string][]string }{ {ListContainersOptions{}, map[string][]string{}}, {ListContainersOptions{All: true}, map[string][]string{"all": {"1"}}}, {ListContainersOptions{All: true, Limit: 10}, map[string][]string{"all": {"1"}, "limit": {"10"}}}, { ListContainersOptions{All: true, Limit: 10, Since: "adf9983", Before: "abdeef"}, map[string][]string{"all": {"1"}, "limit": {"10"}, "since": {"adf9983"}, "before": {"abdeef"}}, }, { ListContainersOptions{Filters: map[string][]string{"status": {"paused", "running"}}}, map[string][]string{"filters": {"{\"status\":[\"paused\",\"running\"]}"}}, }, { ListContainersOptions{All: true, Filters: map[string][]string{"exited": {"0"}, "status": {"exited"}}}, map[string][]string{"all": {"1"}, "filters": {"{\"exited\":[\"0\"],\"status\":[\"exited\"]}"}}, }, } fakeRT := &FakeRoundTripper{message: "[]", status: http.StatusOK} client := newTestClient(fakeRT) u, _ := url.Parse(client.getURL("/containers/json")) for _, tt := range tests { if _, err := client.ListContainers(tt.input); err != nil { t.Error(err) } got := map[string][]string(fakeRT.requests[0].URL.Query()) if !reflect.DeepEqual(got, tt.params) { t.Errorf("Expected %#v, got %#v.", tt.params, got) } if path := fakeRT.requests[0].URL.Path; path != u.Path { t.Errorf("Wrong path on request. Want %q. Got %q.", u.Path, path) } if meth := fakeRT.requests[0].Method; meth != "GET" { t.Errorf("Wrong HTTP method. Want GET. Got %s.", meth) } fakeRT.Reset() } } func TestListContainersFailure(t *testing.T) { var tests = []struct { status int message string }{ {400, "bad parameter"}, {500, "internal server error"}, } for _, tt := range tests { client := newTestClient(&FakeRoundTripper{message: tt.message, status: tt.status}) expected := Error{Status: tt.status, Message: tt.message} containers, err := client.ListContainers(ListContainersOptions{}) if !reflect.DeepEqual(expected, *err.(*Error)) { t.Errorf("Wrong error in ListContainers. Want %#v. Got %#v.", expected, err) } if len(containers) > 0 { t.Errorf("ListContainers failure. Expected empty list. Got %#v.", containers) } } } func TestInspectContainer(t *testing.T) { jsonContainer := `{ "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "AppArmorProfile": "Profile", "Created": "2013-05-07T14:51:42.087658+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 17179869184, "MemorySwap": 34359738368, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Image": "base", "Volumes": {}, "VolumesFrom": "", "SecurityOpt": [ "label:user:USER" ], "Ulimits": [ { "Name": "nofile", "Soft": 1024, "Hard": 2048 } ] }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:00", "Ghost": false }, "Node": { "ID": "4I4E:QR4I:Z733:QEZK:5X44:Q4T7:W2DD:JRDY:KB2O:PODO:Z5SR:XRB6", "IP": "192.168.99.105", "Addra": "192.168.99.105:2376", "Name": "node-01", "Cpus": 4, "Memory": 1048436736, "Labels": { "executiondriver": "native-0.2", "kernelversion": "3.18.5-tinycore64", "operatingsystem": "Boot2Docker 1.5.0 (TCL 5.4); master : a66bce5 - Tue Feb 10 23:31:27 UTC 2015", "provider": "virtualbox", "storagedriver": "aufs" } }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false, "CgroupParent": "/mesos", "Memory": 17179869184, "MemorySwap": 34359738368, "GroupAdd": ["fake", "12345"], "OomScoreAdj": 642 } }` var expected Container err := json.Unmarshal([]byte(jsonContainer), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c678" container, err := client.InspectContainer(id) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(*container, expected) { t.Errorf("InspectContainer(%q): Expected %#v. Got %#v.", id, expected, container) } expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/json")) if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { t.Errorf("InspectContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestInspectContainerNetwork(t *testing.T) { jsonContainer := `{ "Id": "81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c", "Created": "2015-11-12T14:54:04.791485659Z", "Path": "consul-template", "Args": [ "-config=/tmp/haproxy.json", "-consul=192.168.99.120:8500" ], "State": { "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 3196, "ExitCode": 0, "Error": "", "StartedAt": "2015-11-12T14:54:05.026747471Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "Image": "4921c5917fc117df3dec32f4c1976635dc6c56ccd3336fe1db3477f950e78bf7", "ResolvConfPath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/resolv.conf", "HostnamePath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/hostname", "HostsPath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/hosts", "LogPath": "/mnt/sda1/var/lib/docker/containers/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c/81e1bbe20b5508349e1c804eb08b7b6ca8366751dbea9f578b3ea0773fa66c1c-json.log", "Node": { "ID": "AUIB:LFOT:3LSF:SCFS:OYDQ:NLXD:JZNE:4INI:3DRC:ZFBB:GWCY:DWJK", "IP": "192.168.99.121", "Addr": "192.168.99.121:2376", "Name": "swl-demo1", "Cpus": 1, "Memory": 2099945472, "Labels": { "executiondriver": "native-0.2", "kernelversion": "4.1.12-boot2docker", "operatingsystem": "Boot2Docker 1.9.0 (TCL 6.4); master : 16e4a2a - Tue Nov 3 19:49:22 UTC 2015", "provider": "virtualbox", "storagedriver": "aufs" } }, "Name": "/docker-proxy.swl-demo1", "RestartCount": 0, "Driver": "aufs", "ExecDriver": "native-0.2", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "", "ExecIDs": null, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Memory": 0, "MemoryReservation": 0, "MemorySwap": 0, "KernelMemory": 0, "CpuShares": 0, "CpuPeriod": 0, "CpusetCpus": "", "CpusetMems": "", "CpuQuota": 0, "BlkioWeight": 0, "OomKillDisable": false, "MemorySwappiness": -1, "Privileged": false, "PortBindings": { "443/tcp": [ { "HostIp": "", "HostPort": "443" } ] }, "Links": null, "PublishAllPorts": false, "Dns": null, "DnsOptions": null, "DnsSearch": null, "ExtraHosts": null, "VolumesFrom": null, "Devices": [], "NetworkMode": "swl-net", "IpcMode": "", "PidMode": "", "UTSMode": "", "CapAdd": null, "CapDrop": null, "GroupAdd": null, "RestartPolicy": { "Name": "no", "MaximumRetryCount": 0 }, "SecurityOpt": null, "ReadonlyRootfs": false, "Ulimits": null, "LogConfig": { "Type": "json-file", "Config": {} }, "CgroupParent": "", "ConsoleSize": [ 0, 0 ], "VolumeDriver": "" }, "GraphDriver": { "Name": "aufs", "Data": null }, "Mounts": [], "Config": { "Hostname": "81e1bbe20b55", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "ExposedPorts": { "443/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "DOMAIN=local.auto", "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "CONSUL_TEMPLATE_VERSION=0.11.1" ], "Cmd": [ "-consul=192.168.99.120:8500" ], "Image": "docker-proxy:latest", "Volumes": null, "WorkingDir": "", "Entrypoint": [ "consul-template", "-config=/tmp/haproxy.json" ], "OnBuild": null, "Labels": {}, "StopSignal": "SIGTERM" }, "NetworkSettings": { "Bridge": "", "SandboxID": "c6b903dc5c1a96113a22dbc44709e30194079bd2d262eea1eb4f38d85821f6e1", "HairpinMode": false, "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "Ports": { "443/tcp": [ { "HostIp": "192.168.99.121", "HostPort": "443" } ] }, "SandboxKey": "/var/run/docker/netns/c6b903dc5c1a", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null, "EndpointID": "", "Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAddress": "", "IPPrefixLen": 0, "IPv6Gateway": "", "MacAddress": "", "Networks": { "swl-net": { "EndpointID": "683e3092275782a53c3b0968cc7e3a10f23264022ded9cb20490902f96fc5981", "Gateway": "", "IPAddress": "10.0.0.3", "IPPrefixLen": 24, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:0a:00:00:03" } } } }` fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} client := newTestClient(fakeRT) id := "81e1bbe20b55" exp := "10.0.0.3" container, err := client.InspectContainer(id) if err != nil { t.Fatal(err) } s := reflect.Indirect(reflect.ValueOf(container.NetworkSettings)) networks := s.FieldByName("Networks") if networks.IsValid() { var ip string for _, net := range networks.MapKeys() { if net.Interface().(string) == container.HostConfig.NetworkMode { ip = networks.MapIndex(net).FieldByName("IPAddress").Interface().(string) t.Logf("%s %v", net, ip) } } if ip != exp { t.Errorf("InspectContainerNetworks(%q): Expected %#v. Got %#v.", id, exp, ip) } } else { t.Errorf("InspectContainerNetworks(%q): No method Networks for NetworkSettings", id) } } func TestInspectContainerNegativeSwap(t *testing.T) { jsonContainer := `{ "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Created": "2013-05-07T14:51:42.087658+02:00", "Path": "date", "Args": [], "Config": { "Hostname": "4fa6e0f0c678", "User": "", "Memory": 17179869184, "MemorySwap": -1, "AttachStdin": false, "AttachStdout": true, "AttachStderr": true, "PortSpecs": null, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": null, "Cmd": [ "date" ], "Image": "base", "Volumes": {}, "VolumesFrom": "" }, "State": { "Running": false, "Pid": 0, "ExitCode": 0, "StartedAt": "2013-05-07T14:51:42.087658+02:00", "Ghost": false }, "Image": "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "NetworkSettings": { "IpAddress": "", "IpPrefixLen": 0, "Gateway": "", "Bridge": "", "PortMapping": null }, "SysInitPath": "/home/kitty/go/src/github.com/dotcloud/docker/bin/docker", "ResolvConfPath": "/etc/resolv.conf", "Volumes": {}, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LxcConf": [], "Privileged": false, "PortBindings": { "80/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49153" } ] }, "Links": null, "PublishAllPorts": false } }` var expected Container err := json.Unmarshal([]byte(jsonContainer), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c678" container, err := client.InspectContainer(id) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(*container, expected) { t.Errorf("InspectContainer(%q): Expected %#v. Got %#v.", id, expected, container) } expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/json")) if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { t.Errorf("InspectContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestInspectContainerFailure(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "server error", status: 500}) expected := Error{Status: 500, Message: "server error"} container, err := client.InspectContainer("abe033") if container != nil { t.Errorf("InspectContainer: Expected container, got %#v", container) } if !reflect.DeepEqual(expected, *err.(*Error)) { t.Errorf("InspectContainer: Wrong error information. Want %#v. Got %#v.", expected, err) } } func TestInspectContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: 404}) container, err := client.InspectContainer("abe033") if container != nil { t.Errorf("InspectContainer: Expected container, got %#v", container) } expected := &NoSuchContainer{ID: "abe033"} if !reflect.DeepEqual(err, expected) { t.Errorf("InspectContainer: Wrong error information. Want %#v. Got %#v.", expected, err) } } func TestContainerChanges(t *testing.T) { jsonChanges := `[ { "Path":"/dev", "Kind":0 }, { "Path":"/dev/kmsg", "Kind":1 }, { "Path":"/test", "Kind":1 } ]` var expected []Change err := json.Unmarshal([]byte(jsonChanges), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonChanges, status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c678" changes, err := client.ContainerChanges(id) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(changes, expected) { t.Errorf("ContainerChanges(%q): Expected %#v. Got %#v.", id, expected, changes) } expectedURL, _ := url.Parse(client.getURL("/containers/4fa6e0f0c678/changes")) if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { t.Errorf("ContainerChanges(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestContainerChangesFailure(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "server error", status: 500}) expected := Error{Status: 500, Message: "server error"} changes, err := client.ContainerChanges("abe033") if changes != nil { t.Errorf("ContainerChanges: Expected changes, got %#v", changes) } if !reflect.DeepEqual(expected, *err.(*Error)) { t.Errorf("ContainerChanges: Wrong error information. Want %#v. Got %#v.", expected, err) } } func TestContainerChangesNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: 404}) changes, err := client.ContainerChanges("abe033") if changes != nil { t.Errorf("ContainerChanges: Expected changes, got %#v", changes) } expected := &NoSuchContainer{ID: "abe033"} if !reflect.DeepEqual(err, expected) { t.Errorf("ContainerChanges: Wrong error information. Want %#v. Got %#v.", expected, err) } } func TestCreateContainer(t *testing.T) { jsonContainer := `{ "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Warnings": [] }` var expected Container err := json.Unmarshal([]byte(jsonContainer), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} client := newTestClient(fakeRT) config := Config{AttachStdout: true, AttachStdin: true} opts := CreateContainerOptions{Name: "TestCreateContainer", Config: &config} container, err := client.CreateContainer(opts) if err != nil { t.Fatal(err) } id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" if container.ID != id { t.Errorf("CreateContainer: wrong ID. Want %q. Got %q.", id, container.ID) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("CreateContainer: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/create")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("CreateContainer: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) } var gotBody Config err = json.NewDecoder(req.Body).Decode(&gotBody) if err != nil { t.Fatal(err) } } func TestCreateContainerImageNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "No such image", status: http.StatusNotFound}) config := Config{AttachStdout: true, AttachStdin: true} container, err := client.CreateContainer(CreateContainerOptions{Config: &config}) if container != nil { t.Errorf("CreateContainer: expected container, got %#v.", container) } if !reflect.DeepEqual(err, ErrNoSuchImage) { t.Errorf("CreateContainer: Wrong error type. Want %#v. Got %#v.", ErrNoSuchImage, err) } } func TestCreateContainerDuplicateName(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "No such image", status: http.StatusConflict}) config := Config{AttachStdout: true, AttachStdin: true} container, err := client.CreateContainer(CreateContainerOptions{Config: &config}) if container != nil { t.Errorf("CreateContainer: expected container, got %#v.", container) } if err != ErrContainerAlreadyExists { t.Errorf("CreateContainer: Wrong error type. Want %#v. Got %#v.", ErrContainerAlreadyExists, err) } } func TestCreateContainerWithHostConfig(t *testing.T) { fakeRT := &FakeRoundTripper{message: "{}", status: http.StatusOK} client := newTestClient(fakeRT) config := Config{} hostConfig := HostConfig{PublishAllPorts: true} opts := CreateContainerOptions{Name: "TestCreateContainerWithHostConfig", Config: &config, HostConfig: &hostConfig} _, err := client.CreateContainer(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] var gotBody map[string]interface{} err = json.NewDecoder(req.Body).Decode(&gotBody) if err != nil { t.Fatal(err) } if _, ok := gotBody["HostConfig"]; !ok { t.Errorf("CreateContainer: wrong body. HostConfig was not serialized") } } func TestStartContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.StartContainer(id, &HostConfig{}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("StartContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/start")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("StartContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } expectedContentType := "application/json" if contentType := req.Header.Get("Content-Type"); contentType != expectedContentType { t.Errorf("StartContainer(%q): Wrong content-type in request. Want %q. Got %q.", id, expectedContentType, contentType) } } func TestStartContainerNilHostConfig(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.StartContainer(id, nil) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("StartContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/start")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("StartContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } expectedContentType := "application/json" if contentType := req.Header.Get("Content-Type"); contentType != expectedContentType { t.Errorf("StartContainer(%q): Wrong content-type in request. Want %q. Got %q.", id, expectedContentType, contentType) } var buf [4]byte req.Body.Read(buf[:]) if string(buf[:]) != "null" { t.Errorf("Startcontainer(%q): Wrong body. Want null. Got %s", id, buf[:]) } } func TestStartContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.StartContainer("a2344", &HostConfig{}) expected := &NoSuchContainer{ID: "a2344", Err: err.(*NoSuchContainer).Err} if !reflect.DeepEqual(err, expected) { t.Errorf("StartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestStartContainerAlreadyRunning(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "container already running", status: http.StatusNotModified}) err := client.StartContainer("a2334", &HostConfig{}) expected := &ContainerAlreadyRunning{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("StartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestStopContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.StopContainer(id, 10) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("StopContainer(%q, 10): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/stop")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("StopContainer(%q, 10): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestStopContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.StopContainer("a2334", 10) expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestStopContainerNotRunning(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "container not running", status: http.StatusNotModified}) err := client.StopContainer("a2334", 10) expected := &ContainerNotRunning{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestRestartContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.RestartContainer(id, 10) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("RestartContainer(%q, 10): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/restart")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("RestartContainer(%q, 10): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestRestartContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.RestartContainer("a2334", 10) expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("RestartContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestPauseContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.PauseContainer(id) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("PauseContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/pause")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("PauseContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestPauseContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.PauseContainer("a2334") expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("PauseContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestUnpauseContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.UnpauseContainer(id) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("PauseContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/unpause")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("PauseContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestUnpauseContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.UnpauseContainer("a2334") expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("PauseContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestKillContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.KillContainer(KillContainerOptions{ID: id}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("KillContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/kill")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("KillContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestKillContainerSignal(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.KillContainer(KillContainerOptions{ID: id, Signal: SIGTERM}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("KillContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } if signal := req.URL.Query().Get("signal"); signal != "15" { t.Errorf("KillContainer(%q): Wrong query string in request. Want %q. Got %q.", id, "15", signal) } } func TestKillContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.KillContainer(KillContainerOptions{ID: "a2334"}) expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("KillContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestRemoveContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" opts := RemoveContainerOptions{ID: id} err := client.RemoveContainer(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "DELETE" { t.Errorf("RemoveContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "DELETE", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id)) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("RemoveContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestRemoveContainerRemoveVolumes(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" opts := RemoveContainerOptions{ID: id, RemoveVolumes: true} err := client.RemoveContainer(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] params := map[string][]string(req.URL.Query()) expected := map[string][]string{"v": {"1"}} if !reflect.DeepEqual(params, expected) { t.Errorf("RemoveContainer(%q): wrong parameters. Want %#v. Got %#v.", id, expected, params) } } func TestRemoveContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) err := client.RemoveContainer(RemoveContainerOptions{ID: "a2334"}) expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("RemoveContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestResizeContainerTTY(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" err := client.ResizeContainerTTY(id, 40, 80) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("ResizeContainerTTY(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/resize")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("ResizeContainerTTY(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } got := map[string][]string(req.URL.Query()) expectedParams := map[string][]string{ "w": {"80"}, "h": {"40"}, } if !reflect.DeepEqual(got, expectedParams) { t.Errorf("Expected %#v, got %#v.", expectedParams, got) } } func TestWaitContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: `{"StatusCode": 56}`, status: http.StatusOK} client := newTestClient(fakeRT) id := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" status, err := client.WaitContainer(id) if err != nil { t.Fatal(err) } if status != 56 { t.Errorf("WaitContainer(%q): wrong return. Want 56. Got %d.", id, status) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("WaitContainer(%q): wrong HTTP method. Want %q. Got %q.", id, "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/" + id + "/wait")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("WaitContainer(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestWaitContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) _, err := client.WaitContainer("a2334") expected := &NoSuchContainer{ID: "a2334"} if !reflect.DeepEqual(err, expected) { t.Errorf("WaitContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestCommitContainer(t *testing.T) { response := `{"Id":"596069db4bf5"}` client := newTestClient(&FakeRoundTripper{message: response, status: http.StatusOK}) id := "596069db4bf5" image, err := client.CommitContainer(CommitContainerOptions{}) if err != nil { t.Fatal(err) } if image.ID != id { t.Errorf("CommitContainer: Wrong image id. Want %q. Got %q.", id, image.ID) } } func TestCommitContainerParams(t *testing.T) { cfg := Config{Memory: 67108864} json, _ := json.Marshal(&cfg) var tests = []struct { input CommitContainerOptions params map[string][]string body []byte }{ {CommitContainerOptions{}, map[string][]string{}, nil}, {CommitContainerOptions{Container: "44c004db4b17"}, map[string][]string{"container": {"44c004db4b17"}}, nil}, { CommitContainerOptions{Container: "44c004db4b17", Repository: "tsuru/python", Message: "something"}, map[string][]string{"container": {"44c004db4b17"}, "repo": {"tsuru/python"}, "comment": {"something"}}, nil, }, { CommitContainerOptions{Container: "44c004db4b17", Run: &cfg}, map[string][]string{"container": {"44c004db4b17"}}, json, }, } fakeRT := &FakeRoundTripper{message: "{}", status: http.StatusOK} client := newTestClient(fakeRT) u, _ := url.Parse(client.getURL("/commit")) for _, tt := range tests { if _, err := client.CommitContainer(tt.input); err != nil { t.Error(err) } got := map[string][]string(fakeRT.requests[0].URL.Query()) if !reflect.DeepEqual(got, tt.params) { t.Errorf("Expected %#v, got %#v.", tt.params, got) } if path := fakeRT.requests[0].URL.Path; path != u.Path { t.Errorf("Wrong path on request. Want %q. Got %q.", u.Path, path) } if meth := fakeRT.requests[0].Method; meth != "POST" { t.Errorf("Wrong HTTP method. Want POST. Got %s.", meth) } if tt.body != nil { if requestBody, err := ioutil.ReadAll(fakeRT.requests[0].Body); err == nil { if bytes.Compare(requestBody, tt.body) != 0 { t.Errorf("Expected body %#v, got %#v", tt.body, requestBody) } } else { t.Errorf("Error reading request body: %#v", err) } } fakeRT.Reset() } } func TestCommitContainerFailure(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusInternalServerError}) _, err := client.CommitContainer(CommitContainerOptions{}) if err == nil { t.Error("Expected non-nil error, got .") } } func TestCommitContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) _, err := client.CommitContainer(CommitContainerOptions{}) expected := &NoSuchContainer{ID: ""} if !reflect.DeepEqual(err, expected) { t.Errorf("CommitContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestAttachToContainerLogs(t *testing.T) { var req http.Request server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 19}) w.Write([]byte("something happened!")) req = *r })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var buf bytes.Buffer opts := AttachToContainerOptions{ Container: "a123456", OutputStream: &buf, Stdout: true, Stderr: true, Logs: true, } err := client.AttachToContainer(opts) if err != nil { t.Fatal(err) } expected := "something happened!" if buf.String() != expected { t.Errorf("AttachToContainer for logs: wrong output. Want %q. Got %q.", expected, buf.String()) } if req.Method != "POST" { t.Errorf("AttachToContainer: wrong HTTP method. Want POST. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/containers/a123456/attach")) if req.URL.Path != u.Path { t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) } expectedQs := map[string][]string{ "logs": {"1"}, "stdout": {"1"}, "stderr": {"1"}, } got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expectedQs) { t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expectedQs, got) } } func TestAttachToContainer(t *testing.T) { var reader = strings.NewReader("send value") var req http.Request server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) w.Write([]byte("hello")) req = *r })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var stdout, stderr bytes.Buffer opts := AttachToContainerOptions{ Container: "a123456", OutputStream: &stdout, ErrorStream: &stderr, InputStream: reader, Stdin: true, Stdout: true, Stderr: true, Stream: true, RawTerminal: true, } err := client.AttachToContainer(opts) if err != nil { t.Fatal(err) } expected := map[string][]string{ "stdin": {"1"}, "stdout": {"1"}, "stderr": {"1"}, "stream": {"1"}, } got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestAttachToContainerSentinel(t *testing.T) { var reader = strings.NewReader("send value") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) w.Write([]byte("hello")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var stdout, stderr bytes.Buffer success := make(chan struct{}) opts := AttachToContainerOptions{ Container: "a123456", OutputStream: &stdout, ErrorStream: &stderr, InputStream: reader, Stdin: true, Stdout: true, Stderr: true, Stream: true, RawTerminal: true, Success: success, } go func() { if err := client.AttachToContainer(opts); err != nil { t.Error(err) } }() success <- <-success } func TestAttachToContainerNilStdout(t *testing.T) { var reader = strings.NewReader("send value") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) w.Write([]byte("hello")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var stderr bytes.Buffer opts := AttachToContainerOptions{ Container: "a123456", OutputStream: nil, ErrorStream: &stderr, InputStream: reader, Stdin: true, Stdout: true, Stderr: true, Stream: true, RawTerminal: true, } err := client.AttachToContainer(opts) if err != nil { t.Fatal(err) } } func TestAttachToContainerNilStderr(t *testing.T) { var reader = strings.NewReader("send value") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) w.Write([]byte("hello")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var stdout bytes.Buffer opts := AttachToContainerOptions{ Container: "a123456", OutputStream: &stdout, InputStream: reader, Stdin: true, Stdout: true, Stderr: true, Stream: true, RawTerminal: true, } err := client.AttachToContainer(opts) if err != nil { t.Fatal(err) } } func TestAttachToContainerStdinOnly(t *testing.T) { var reader = strings.NewReader("send value") serverFinished := make(chan struct{}) clientFinished := make(chan struct{}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) hj, ok := w.(http.Hijacker) if !ok { t.Fatal("cannot hijack server connection") } conn, _, err := hj.Hijack() if err != nil { t.Fatal(err) } // wait for client to indicate it's finished <-clientFinished // inform test that the server has finished close(serverFinished) conn.Close() })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true success := make(chan struct{}) opts := AttachToContainerOptions{ Container: "a123456", InputStream: reader, Stdin: true, Stdout: false, Stderr: false, Stream: true, RawTerminal: false, Success: success, } go func() { if err := client.AttachToContainer(opts); err != nil { t.Error(err) } // client's attach session is over close(clientFinished) }() success <- <-success // wait for server to finish handling attach <-serverFinished } func TestAttachToContainerRawTerminalFalse(t *testing.T) { input := strings.NewReader("send value") var req http.Request server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { req = *r w.WriteHeader(http.StatusOK) hj, ok := w.(http.Hijacker) if !ok { t.Fatal("cannot hijack server connection") } conn, _, err := hj.Hijack() if err != nil { t.Fatal(err) } conn.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) conn.Write([]byte("hello")) conn.Write([]byte{2, 0, 0, 0, 0, 0, 0, 6}) conn.Write([]byte("hello!")) conn.Close() })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var stdout, stderr bytes.Buffer opts := AttachToContainerOptions{ Container: "a123456", OutputStream: &stdout, ErrorStream: &stderr, InputStream: input, Stdin: true, Stdout: true, Stderr: true, Stream: true, RawTerminal: false, } client.AttachToContainer(opts) expected := map[string][]string{ "stdin": {"1"}, "stdout": {"1"}, "stderr": {"1"}, "stream": {"1"}, } got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("AttachToContainer: wrong query string. Want %#v. Got %#v.", expected, got) } if stdout.String() != "hello" { t.Errorf("AttachToContainer: wrong content written to stdout. Want %q. Got %q.", "hello", stdout.String()) } if stderr.String() != "hello!" { t.Errorf("AttachToContainer: wrong content written to stderr. Want %q. Got %q.", "hello!", stderr.String()) } } func TestAttachToContainerWithoutContainer(t *testing.T) { var client Client err := client.AttachToContainer(AttachToContainerOptions{}) expected := &NoSuchContainer{ID: ""} if !reflect.DeepEqual(err, expected) { t.Errorf("AttachToContainer: wrong error. Want %#v. Got %#v.", expected, err) } } func TestLogs(t *testing.T) { var req http.Request server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} w.Write(prefix) w.Write([]byte("something happened!")) req = *r })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var buf bytes.Buffer opts := LogsOptions{ Container: "a123456", OutputStream: &buf, Follow: true, Stdout: true, Stderr: true, Timestamps: true, } err := client.Logs(opts) if err != nil { t.Fatal(err) } expected := "something happened!" if buf.String() != expected { t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) } if req.Method != "GET" { t.Errorf("Logs: wrong HTTP method. Want GET. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/containers/a123456/logs")) if req.URL.Path != u.Path { t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) } expectedQs := map[string][]string{ "follow": {"1"}, "stdout": {"1"}, "stderr": {"1"}, "timestamps": {"1"}, "tail": {"all"}, } got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expectedQs) { t.Errorf("Logs: wrong query string. Want %#v. Got %#v.", expectedQs, got) } } func TestLogsNilStdoutDoesntFail(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} w.Write(prefix) w.Write([]byte("something happened!")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true opts := LogsOptions{ Container: "a123456", Follow: true, Stdout: true, Stderr: true, Timestamps: true, } err := client.Logs(opts) if err != nil { t.Fatal(err) } } func TestLogsNilStderrDoesntFail(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { prefix := []byte{2, 0, 0, 0, 0, 0, 0, 19} w.Write(prefix) w.Write([]byte("something happened!")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true opts := LogsOptions{ Container: "a123456", Follow: true, Stdout: true, Stderr: true, Timestamps: true, } err := client.Logs(opts) if err != nil { t.Fatal(err) } } func TestLogsSpecifyingTail(t *testing.T) { var req http.Request server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19} w.Write(prefix) w.Write([]byte("something happened!")) req = *r })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var buf bytes.Buffer opts := LogsOptions{ Container: "a123456", OutputStream: &buf, Follow: true, Stdout: true, Stderr: true, Timestamps: true, Tail: "100", } err := client.Logs(opts) if err != nil { t.Fatal(err) } expected := "something happened!" if buf.String() != expected { t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) } if req.Method != "GET" { t.Errorf("Logs: wrong HTTP method. Want GET. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/containers/a123456/logs")) if req.URL.Path != u.Path { t.Errorf("AttachToContainer for logs: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) } expectedQs := map[string][]string{ "follow": {"1"}, "stdout": {"1"}, "stderr": {"1"}, "timestamps": {"1"}, "tail": {"100"}, } got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expectedQs) { t.Errorf("Logs: wrong query string. Want %#v. Got %#v.", expectedQs, got) } } func TestLogsRawTerminal(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("something happened!")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var buf bytes.Buffer opts := LogsOptions{ Container: "a123456", OutputStream: &buf, Follow: true, RawTerminal: true, Stdout: true, Stderr: true, Timestamps: true, Tail: "100", } err := client.Logs(opts) if err != nil { t.Fatal(err) } expected := "something happened!" if buf.String() != expected { t.Errorf("Logs: wrong output. Want %q. Got %q.", expected, buf.String()) } } func TestLogsNoContainer(t *testing.T) { var client Client err := client.Logs(LogsOptions{}) expected := &NoSuchContainer{ID: ""} if !reflect.DeepEqual(err, expected) { t.Errorf("AttachToContainer: wrong error. Want %#v. Got %#v.", expected, err) } } func TestNoSuchContainerError(t *testing.T) { var err = &NoSuchContainer{ID: "i345"} expected := "No such container: i345" if got := err.Error(); got != expected { t.Errorf("NoSuchContainer: wrong message. Want %q. Got %q.", expected, got) } } func TestNoSuchContainerErrorMessage(t *testing.T) { var err = &NoSuchContainer{ID: "i345", Err: errors.New("some advanced error info")} expected := "some advanced error info" if got := err.Error(); got != expected { t.Errorf("NoSuchContainer: wrong message. Want %q. Got %q.", expected, got) } } func TestExportContainer(t *testing.T) { content := "exported container tar content" out := stdoutMock{bytes.NewBufferString(content)} client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) opts := ExportContainerOptions{ID: "4fa6e0f0c678", OutputStream: out} err := client.ExportContainer(opts) if err != nil { t.Errorf("ExportContainer: caugh error %#v while exporting container, expected nil", err.Error()) } if out.String() != content { t.Errorf("ExportContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) } } func TestExportContainerViaUnixSocket(t *testing.T) { if runtime.GOOS != "darwin" { t.Skip(fmt.Sprintf("skipping test on %s", runtime.GOOS)) } content := "exported container tar content" var buf []byte out := bytes.NewBuffer(buf) tempSocket := tempfile("export_socket") defer os.Remove(tempSocket) endpoint := "unix://" + tempSocket u, _ := parseEndpoint(endpoint, false) client := Client{ HTTPClient: cleanhttp.DefaultClient(), Dialer: &net.Dialer{}, endpoint: endpoint, endpointURL: u, SkipServerVersionCheck: true, } listening := make(chan string) done := make(chan int) go runStreamConnServer(t, "unix", tempSocket, listening, done) <-listening // wait for server to start opts := ExportContainerOptions{ID: "4fa6e0f0c678", OutputStream: out} err := client.ExportContainer(opts) <-done // make sure server stopped if err != nil { t.Errorf("ExportContainer: caugh error %#v while exporting container, expected nil", err.Error()) } if out.String() != content { t.Errorf("ExportContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) } } func runStreamConnServer(t *testing.T, network, laddr string, listening chan<- string, done chan<- int) { defer close(done) l, err := net.Listen(network, laddr) if err != nil { t.Errorf("Listen(%q, %q) failed: %v", network, laddr, err) listening <- "" return } defer l.Close() listening <- l.Addr().String() c, err := l.Accept() if err != nil { t.Logf("Accept failed: %v", err) return } c.Write([]byte("HTTP/1.1 200 OK\n\nexported container tar content")) c.Close() } func tempfile(filename string) string { return os.TempDir() + "/" + filename + "." + strconv.Itoa(os.Getpid()) } func TestExportContainerNoId(t *testing.T) { client := Client{} out := stdoutMock{bytes.NewBufferString("")} err := client.ExportContainer(ExportContainerOptions{OutputStream: out}) e, ok := err.(*NoSuchContainer) if !ok { t.Errorf("ExportContainer: wrong error. Want NoSuchContainer. Got %#v.", e) } if e.ID != "" { t.Errorf("ExportContainer: wrong ID. Want %q. Got %q", "", e.ID) } } func TestUploadToContainer(t *testing.T) { content := "File content" in := stdinMock{bytes.NewBufferString(content)} fakeRT := &FakeRoundTripper{status: http.StatusOK} client := newTestClient(fakeRT) opts := UploadToContainerOptions{ Path: "abc", InputStream: in, } err := client.UploadToContainer("a123456", opts) if err != nil { t.Errorf("UploadToContainer: caught error %#v while uploading archive to container, expected nil", err) } req := fakeRT.requests[0] if req.Method != "PUT" { t.Errorf("UploadToContainer{Path:abc}: Wrong HTTP method. Want PUT. Got %s", req.Method) } if pathParam := req.URL.Query().Get("path"); pathParam != "abc" { t.Errorf("ListImages({Path:abc}): Wrong parameter. Want path=abc. Got path=%s", pathParam) } } func TestDownloadFromContainer(t *testing.T) { filecontent := "File content" client := newTestClient(&FakeRoundTripper{message: filecontent, status: http.StatusOK}) var out bytes.Buffer opts := DownloadFromContainerOptions{ OutputStream: &out, } err := client.DownloadFromContainer("a123456", opts) if err != nil { t.Errorf("DownloadFromContainer: caught error %#v while downloading from container, expected nil", err.Error()) } if out.String() != filecontent { t.Errorf("DownloadFromContainer: wrong stdout. Want %#v. Got %#v.", filecontent, out.String()) } } func TestCopyFromContainer(t *testing.T) { content := "File content" out := stdoutMock{bytes.NewBufferString(content)} client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) opts := CopyFromContainerOptions{ Container: "a123456", OutputStream: &out, } err := client.CopyFromContainer(opts) if err != nil { t.Errorf("CopyFromContainer: caught error %#v while copying from container, expected nil", err.Error()) } if out.String() != content { t.Errorf("CopyFromContainer: wrong stdout. Want %#v. Got %#v.", content, out.String()) } } func TestCopyFromContainerEmptyContainer(t *testing.T) { client := newTestClient(&FakeRoundTripper{status: http.StatusOK}) err := client.CopyFromContainer(CopyFromContainerOptions{}) _, ok := err.(*NoSuchContainer) if !ok { t.Errorf("CopyFromContainer: invalid error returned. Want NoSuchContainer, got %#v.", err) } } func TestPassingNameOptToCreateContainerReturnsItInContainer(t *testing.T) { jsonContainer := `{ "Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2", "Warnings": [] }` fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} client := newTestClient(fakeRT) config := Config{AttachStdout: true, AttachStdin: true} opts := CreateContainerOptions{Name: "TestCreateContainer", Config: &config} container, err := client.CreateContainer(opts) if err != nil { t.Fatal(err) } if container.Name != "TestCreateContainer" { t.Errorf("Container name expected to be TestCreateContainer, was %s", container.Name) } } func TestAlwaysRestart(t *testing.T) { policy := AlwaysRestart() if policy.Name != "always" { t.Errorf("AlwaysRestart(): wrong policy name. Want %q. Got %q", "always", policy.Name) } if policy.MaximumRetryCount != 0 { t.Errorf("AlwaysRestart(): wrong MaximumRetryCount. Want 0. Got %d", policy.MaximumRetryCount) } } func TestRestartOnFailure(t *testing.T) { const retry = 5 policy := RestartOnFailure(retry) if policy.Name != "on-failure" { t.Errorf("RestartOnFailure(%d): wrong policy name. Want %q. Got %q", retry, "on-failure", policy.Name) } if policy.MaximumRetryCount != retry { t.Errorf("RestartOnFailure(%d): wrong MaximumRetryCount. Want %d. Got %d", retry, retry, policy.MaximumRetryCount) } } func TestNeverRestart(t *testing.T) { policy := NeverRestart() if policy.Name != "no" { t.Errorf("NeverRestart(): wrong policy name. Want %q. Got %q", "always", policy.Name) } if policy.MaximumRetryCount != 0 { t.Errorf("NeverRestart(): wrong MaximumRetryCount. Want 0. Got %d", policy.MaximumRetryCount) } } func TestTopContainer(t *testing.T) { jsonTop := `{ "Processes": [ [ "ubuntu", "3087", "815", "0", "01:44", "?", "00:00:00", "cmd1" ], [ "root", "3158", "3087", "0", "01:44", "?", "00:00:01", "cmd2" ] ], "Titles": [ "UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD" ] }` var expected TopResult err := json.Unmarshal([]byte(jsonTop), &expected) if err != nil { t.Fatal(err) } id := "4fa6e0f0" fakeRT := &FakeRoundTripper{message: jsonTop, status: http.StatusOK} client := newTestClient(fakeRT) processes, err := client.TopContainer(id, "") if err != nil { t.Fatal(err) } if !reflect.DeepEqual(processes, expected) { t.Errorf("TopContainer: Expected %#v. Got %#v.", expected, processes) } if len(processes.Processes) != 2 || len(processes.Processes[0]) != 8 || processes.Processes[0][7] != "cmd1" { t.Errorf("TopContainer: Process list to include cmd1. Got %#v.", processes) } expectedURI := "/containers/" + id + "/top" if !strings.HasSuffix(fakeRT.requests[0].URL.String(), expectedURI) { t.Errorf("TopContainer: Expected URI to have %q. Got %q.", expectedURI, fakeRT.requests[0].URL.String()) } } func TestTopContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) _, err := client.TopContainer("abef348", "") expected := &NoSuchContainer{ID: "abef348"} if !reflect.DeepEqual(err, expected) { t.Errorf("StopContainer: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestTopContainerWithPsArgs(t *testing.T) { fakeRT := &FakeRoundTripper{message: "no such container", status: http.StatusNotFound} client := newTestClient(fakeRT) expectedErr := &NoSuchContainer{ID: "abef348"} if _, err := client.TopContainer("abef348", "aux"); !reflect.DeepEqual(expectedErr, err) { t.Errorf("TopContainer: Expected %v. Got %v.", expectedErr, err) } expectedURI := "/containers/abef348/top?ps_args=aux" if !strings.HasSuffix(fakeRT.requests[0].URL.String(), expectedURI) { t.Errorf("TopContainer: Expected URI to have %q. Got %q.", expectedURI, fakeRT.requests[0].URL.String()) } } func TestStatsTimeout(t *testing.T) { l, err := net.Listen("unix", "/tmp/docker_test.sock") if err != nil { t.Fatal(err) } received := false defer l.Close() go func() { l.Accept() received = true time.Sleep(time.Second) }() client, _ := NewClient("unix:///tmp/docker_test.sock") client.SkipServerVersionCheck = true errC := make(chan error, 1) statsC := make(chan *Stats) done := make(chan bool) go func() { errC <- client.Stats(StatsOptions{"c", statsC, true, done, time.Millisecond * 100}) close(errC) }() err = <-errC e, ok := err.(net.Error) if !ok || !e.Timeout() { t.Error("Failed to receive timeout exception") } if !received { t.Fatal("Failed to receive message") } } func TestStats(t *testing.T) { jsonStats1 := `{ "read" : "2015-01-08T22:57:31.547920715Z", "network" : { "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 }, "networks" : { "eth0":{ "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 } }, "memory_stats" : { "stats" : { "total_pgmajfault" : 0, "cache" : 0, "mapped_file" : 0, "total_inactive_file" : 0, "pgpgout" : 414, "rss" : 6537216, "total_mapped_file" : 0, "writeback" : 0, "unevictable" : 0, "pgpgin" : 477, "total_unevictable" : 0, "pgmajfault" : 0, "total_rss" : 6537216, "total_rss_huge" : 6291456, "total_writeback" : 0, "total_inactive_anon" : 0, "rss_huge" : 6291456, "hierarchical_memory_limit": 189204833, "total_pgfault" : 964, "total_active_file" : 0, "active_anon" : 6537216, "total_active_anon" : 6537216, "total_pgpgout" : 414, "total_cache" : 0, "inactive_anon" : 0, "active_file" : 0, "pgfault" : 964, "inactive_file" : 0, "total_pgpgin" : 477, "swap" : 47312896, "hierarchical_memsw_limit" : 1610612736 }, "max_usage" : 6651904, "usage" : 6537216, "failcnt" : 0, "limit" : 67108864 }, "blkio_stats": { "io_service_bytes_recursive": [ { "major": 8, "minor": 0, "op": "Read", "value": 428795731968 }, { "major": 8, "minor": 0, "op": "Write", "value": 388177920 } ], "io_serviced_recursive": [ { "major": 8, "minor": 0, "op": "Read", "value": 25994442 }, { "major": 8, "minor": 0, "op": "Write", "value": 1734 } ], "io_queue_recursive": [], "io_service_time_recursive": [], "io_wait_time_recursive": [], "io_merged_recursive": [], "io_time_recursive": [], "sectors_recursive": [] }, "cpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000 }, "precpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000 } }` // 1 second later, cache is 100 jsonStats2 := `{ "read" : "2015-01-08T22:57:32.547920715Z", "networks" : { "eth0":{ "rx_dropped" : 0, "rx_bytes" : 648, "rx_errors" : 0, "tx_packets" : 8, "tx_dropped" : 0, "rx_packets" : 8, "tx_errors" : 0, "tx_bytes" : 648 } }, "memory_stats" : { "stats" : { "total_pgmajfault" : 0, "cache" : 100, "mapped_file" : 0, "total_inactive_file" : 0, "pgpgout" : 414, "rss" : 6537216, "total_mapped_file" : 0, "writeback" : 0, "unevictable" : 0, "pgpgin" : 477, "total_unevictable" : 0, "pgmajfault" : 0, "total_rss" : 6537216, "total_rss_huge" : 6291456, "total_writeback" : 0, "total_inactive_anon" : 0, "rss_huge" : 6291456, "total_pgfault" : 964, "total_active_file" : 0, "active_anon" : 6537216, "total_active_anon" : 6537216, "total_pgpgout" : 414, "total_cache" : 0, "inactive_anon" : 0, "active_file" : 0, "pgfault" : 964, "inactive_file" : 0, "total_pgpgin" : 477, "swap" : 47312896, "hierarchical_memsw_limit" : 1610612736 }, "max_usage" : 6651904, "usage" : 6537216, "failcnt" : 0, "limit" : 67108864 }, "blkio_stats": { "io_service_bytes_recursive": [ { "major": 8, "minor": 0, "op": "Read", "value": 428795731968 }, { "major": 8, "minor": 0, "op": "Write", "value": 388177920 } ], "io_serviced_recursive": [ { "major": 8, "minor": 0, "op": "Read", "value": 25994442 }, { "major": 8, "minor": 0, "op": "Write", "value": 1734 } ], "io_queue_recursive": [], "io_service_time_recursive": [], "io_wait_time_recursive": [], "io_merged_recursive": [], "io_time_recursive": [], "sectors_recursive": [] }, "cpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000 }, "precpu_stats" : { "cpu_usage" : { "percpu_usage" : [ 16970827, 1839451, 7107380, 10571290 ], "usage_in_usermode" : 10000000, "total_usage" : 36488948, "usage_in_kernelmode" : 20000000 }, "system_cpu_usage" : 20091722000000000 } }` var expected1 Stats var expected2 Stats err := json.Unmarshal([]byte(jsonStats1), &expected1) if err != nil { t.Fatal(err) } err = json.Unmarshal([]byte(jsonStats2), &expected2) if err != nil { t.Fatal(err) } id := "4fa6e0f0" var req http.Request server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Write([]byte(jsonStats1)) w.Write([]byte(jsonStats2)) req = *r })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true errC := make(chan error, 1) statsC := make(chan *Stats) done := make(chan bool) go func() { errC <- client.Stats(StatsOptions{id, statsC, true, done, 0}) close(errC) }() var resultStats []*Stats for { stats, ok := <-statsC if !ok { break } resultStats = append(resultStats, stats) } err = <-errC if err != nil { t.Fatal(err) } if len(resultStats) != 2 { t.Fatalf("Stats: Expected 2 results. Got %d.", len(resultStats)) } if !reflect.DeepEqual(resultStats[0], &expected1) { t.Errorf("Stats: Expected:\n%+v\nGot:\n%+v", expected1, resultStats[0]) } if !reflect.DeepEqual(resultStats[1], &expected2) { t.Errorf("Stats: Expected:\n%+v\nGot:\n%+v", expected2, resultStats[1]) } if req.Method != "GET" { t.Errorf("Stats: wrong HTTP method. Want GET. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/containers/" + id + "/stats")) if req.URL.Path != u.Path { t.Errorf("Stats: wrong HTTP path. Want %q. Got %q.", u.Path, req.URL.Path) } } func TestStatsContainerNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such container", status: http.StatusNotFound}) statsC := make(chan *Stats) done := make(chan bool) err := client.Stats(StatsOptions{"abef348", statsC, true, done, 0}) expected := &NoSuchContainer{ID: "abef348"} if !reflect.DeepEqual(err, expected) { t.Errorf("Stats: Wrong error returned. Want %#v. Got %#v.", expected, err) } } func TestRenameContainer(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := RenameContainerOptions{ID: "something_old", Name: "something_new"} err := client.RenameContainer(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("RenameContainer: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/something_old/rename?name=something_new")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("RenameContainer: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) } expectedValues := expectedURL.Query()["name"] actualValues := req.URL.Query()["name"] if len(actualValues) != 1 || expectedValues[0] != actualValues[0] { t.Errorf("RenameContainer: Wrong params in request. Want %q. Got %q.", expectedValues, actualValues) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/env.go ================================================ // Copyright 2014 Docker authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the DOCKER-LICENSE file. package docker import ( "encoding/json" "fmt" "io" "strconv" "strings" ) // Env represents a list of key-pair represented in the form KEY=VALUE. type Env []string // Get returns the string value of the given key. func (env *Env) Get(key string) (value string) { return env.Map()[key] } // Exists checks whether the given key is defined in the internal Env // representation. func (env *Env) Exists(key string) bool { _, exists := env.Map()[key] return exists } // GetBool returns a boolean representation of the given key. The key is false // whenever its value if 0, no, false, none or an empty string. Any other value // will be interpreted as true. func (env *Env) GetBool(key string) (value bool) { s := strings.ToLower(strings.Trim(env.Get(key), " \t")) if s == "" || s == "0" || s == "no" || s == "false" || s == "none" { return false } return true } // SetBool defines a boolean value to the given key. func (env *Env) SetBool(key string, value bool) { if value { env.Set(key, "1") } else { env.Set(key, "0") } } // GetInt returns the value of the provided key, converted to int. // // It the value cannot be represented as an integer, it returns -1. func (env *Env) GetInt(key string) int { return int(env.GetInt64(key)) } // SetInt defines an integer value to the given key. func (env *Env) SetInt(key string, value int) { env.Set(key, strconv.Itoa(value)) } // GetInt64 returns the value of the provided key, converted to int64. // // It the value cannot be represented as an integer, it returns -1. func (env *Env) GetInt64(key string) int64 { s := strings.Trim(env.Get(key), " \t") val, err := strconv.ParseInt(s, 10, 64) if err != nil { return -1 } return val } // SetInt64 defines an integer (64-bit wide) value to the given key. func (env *Env) SetInt64(key string, value int64) { env.Set(key, strconv.FormatInt(value, 10)) } // GetJSON unmarshals the value of the provided key in the provided iface. // // iface is a value that can be provided to the json.Unmarshal function. func (env *Env) GetJSON(key string, iface interface{}) error { sval := env.Get(key) if sval == "" { return nil } return json.Unmarshal([]byte(sval), iface) } // SetJSON marshals the given value to JSON format and stores it using the // provided key. func (env *Env) SetJSON(key string, value interface{}) error { sval, err := json.Marshal(value) if err != nil { return err } env.Set(key, string(sval)) return nil } // GetList returns a list of strings matching the provided key. It handles the // list as a JSON representation of a list of strings. // // If the given key matches to a single string, it will return a list // containing only the value that matches the key. func (env *Env) GetList(key string) []string { sval := env.Get(key) if sval == "" { return nil } var l []string if err := json.Unmarshal([]byte(sval), &l); err != nil { l = append(l, sval) } return l } // SetList stores the given list in the provided key, after serializing it to // JSON format. func (env *Env) SetList(key string, value []string) error { return env.SetJSON(key, value) } // Set defines the value of a key to the given string. func (env *Env) Set(key, value string) { *env = append(*env, key+"="+value) } // Decode decodes `src` as a json dictionary, and adds each decoded key-value // pair to the environment. // // If `src` cannot be decoded as a json dictionary, an error is returned. func (env *Env) Decode(src io.Reader) error { m := make(map[string]interface{}) if err := json.NewDecoder(src).Decode(&m); err != nil { return err } for k, v := range m { env.SetAuto(k, v) } return nil } // SetAuto will try to define the Set* method to call based on the given value. func (env *Env) SetAuto(key string, value interface{}) { if fval, ok := value.(float64); ok { env.SetInt64(key, int64(fval)) } else if sval, ok := value.(string); ok { env.Set(key, sval) } else if val, err := json.Marshal(value); err == nil { env.Set(key, string(val)) } else { env.Set(key, fmt.Sprintf("%v", value)) } } // Map returns the map representation of the env. func (env *Env) Map() map[string]string { if len(*env) == 0 { return nil } m := make(map[string]string) for _, kv := range *env { parts := strings.SplitN(kv, "=", 2) m[parts[0]] = parts[1] } return m } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/env_test.go ================================================ // Copyright 2014 go-dockerclient authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the DOCKER-LICENSE file. package docker import ( "bytes" "errors" "reflect" "sort" "testing" ) func TestGet(t *testing.T) { var tests = []struct { input []string query string expected string }{ {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PATH", "/usr/bin:/bin"}, {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATH", "/usr/local"}, {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATHI", ""}, {[]string{"WAT="}, "WAT", ""}, } for _, tt := range tests { env := Env(tt.input) got := env.Get(tt.query) if got != tt.expected { t.Errorf("Env.Get(%q): wrong result. Want %q. Got %q", tt.query, tt.expected, got) } } } func TestExists(t *testing.T) { var tests = []struct { input []string query string expected bool }{ {[]string{"WAT=", "PYTHONPATH=/usr/local"}, "WAT", true}, {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATH", true}, {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, "PYTHONPATHI", false}, } for _, tt := range tests { env := Env(tt.input) got := env.Exists(tt.query) if got != tt.expected { t.Errorf("Env.Exists(%q): wrong result. Want %v. Got %v", tt.query, tt.expected, got) } } } func TestGetBool(t *testing.T) { var tests = []struct { input string expected bool }{ {"EMTPY_VAR", false}, {"ZERO_VAR", false}, {"NO_VAR", false}, {"FALSE_VAR", false}, {"NONE_VAR", false}, {"TRUE_VAR", true}, {"WAT", true}, {"PATH", true}, {"ONE_VAR", true}, {"NO_VAR_TAB", false}, } env := Env([]string{ "EMPTY_VAR=", "ZERO_VAR=0", "NO_VAR=no", "FALSE_VAR=false", "NONE_VAR=none", "TRUE_VAR=true", "WAT=wat", "PATH=/usr/bin:/bin", "ONE_VAR=1", "NO_VAR_TAB=0 \t\t\t", }) for _, tt := range tests { got := env.GetBool(tt.input) if got != tt.expected { t.Errorf("Env.GetBool(%q): wrong result. Want %v. Got %v.", tt.input, tt.expected, got) } } } func TestSetBool(t *testing.T) { var tests = []struct { input bool expected string }{ {true, "1"}, {false, "0"}, } for _, tt := range tests { var env Env env.SetBool("SOME", tt.input) if got := env.Get("SOME"); got != tt.expected { t.Errorf("Env.SetBool(%v): wrong result. Want %q. Got %q", tt.input, tt.expected, got) } } } func TestGetInt(t *testing.T) { var tests = []struct { input string expected int }{ {"NEGATIVE_INTEGER", -10}, {"NON_INTEGER", -1}, {"ONE", 1}, {"TWO", 2}, } env := Env([]string{"NEGATIVE_INTEGER=-10", "NON_INTEGER=wat", "ONE=1", "TWO=2"}) for _, tt := range tests { got := env.GetInt(tt.input) if got != tt.expected { t.Errorf("Env.GetInt(%q): wrong result. Want %d. Got %d", tt.input, tt.expected, got) } } } func TestSetInt(t *testing.T) { var tests = []struct { input int expected string }{ {10, "10"}, {13, "13"}, {7, "7"}, {33, "33"}, {0, "0"}, {-34, "-34"}, } for _, tt := range tests { var env Env env.SetInt("SOME", tt.input) if got := env.Get("SOME"); got != tt.expected { t.Errorf("Env.SetBool(%d): wrong result. Want %q. Got %q", tt.input, tt.expected, got) } } } func TestGetInt64(t *testing.T) { var tests = []struct { input string expected int64 }{ {"NEGATIVE_INTEGER", -10}, {"NON_INTEGER", -1}, {"ONE", 1}, {"TWO", 2}, } env := Env([]string{"NEGATIVE_INTEGER=-10", "NON_INTEGER=wat", "ONE=1", "TWO=2"}) for _, tt := range tests { got := env.GetInt64(tt.input) if got != tt.expected { t.Errorf("Env.GetInt64(%q): wrong result. Want %d. Got %d", tt.input, tt.expected, got) } } } func TestSetInt64(t *testing.T) { var tests = []struct { input int64 expected string }{ {10, "10"}, {13, "13"}, {7, "7"}, {33, "33"}, {0, "0"}, {-34, "-34"}, } for _, tt := range tests { var env Env env.SetInt64("SOME", tt.input) if got := env.Get("SOME"); got != tt.expected { t.Errorf("Env.SetBool(%d): wrong result. Want %q. Got %q", tt.input, tt.expected, got) } } } func TestGetJSON(t *testing.T) { var p struct { Name string `json:"name"` Age int `json:"age"` } var env Env env.Set("person", `{"name":"Gopher","age":5}`) err := env.GetJSON("person", &p) if err != nil { t.Error(err) } if p.Name != "Gopher" { t.Errorf("Env.GetJSON(%q): wrong name. Want %q. Got %q", "person", "Gopher", p.Name) } if p.Age != 5 { t.Errorf("Env.GetJSON(%q): wrong age. Want %d. Got %d", "person", 5, p.Age) } } func TestGetJSONAbsent(t *testing.T) { var l []string var env Env err := env.GetJSON("person", &l) if err != nil { t.Error(err) } if l != nil { t.Errorf("Env.GetJSON(): get unexpected list %v", l) } } func TestGetJSONFailure(t *testing.T) { var p []string var env Env env.Set("list-person", `{"name":"Gopher","age":5}`) err := env.GetJSON("list-person", &p) if err == nil { t.Errorf("Env.GetJSON(%q): got unexpected error.", "list-person") } } func TestSetJSON(t *testing.T) { var p1 = struct { Name string `json:"name"` Age int `json:"age"` }{Name: "Gopher", Age: 5} var env Env err := env.SetJSON("person", p1) if err != nil { t.Error(err) } var p2 struct { Name string `json:"name"` Age int `json:"age"` } err = env.GetJSON("person", &p2) if err != nil { t.Error(err) } if !reflect.DeepEqual(p1, p2) { t.Errorf("Env.SetJSON(%q): wrong result. Want %v. Got %v", "person", p1, p2) } } func TestSetJSONFailure(t *testing.T) { var env Env err := env.SetJSON("person", unmarshable{}) if err == nil { t.Error("Env.SetJSON(): got unexpected error") } if env.Exists("person") { t.Errorf("Env.SetJSON(): should not define the key %q, but did", "person") } } func TestGetList(t *testing.T) { var tests = []struct { input string expected []string }{ {"WAT=wat", []string{"wat"}}, {`WAT=["wat","wet","wit","wot","wut"]`, []string{"wat", "wet", "wit", "wot", "wut"}}, {"WAT=", nil}, } for _, tt := range tests { env := Env([]string{tt.input}) got := env.GetList("WAT") if !reflect.DeepEqual(got, tt.expected) { t.Errorf("Env.GetList(%q): wrong result. Want %v. Got %v", "WAT", tt.expected, got) } } } func TestSetList(t *testing.T) { list := []string{"a", "b", "c"} var env Env if err := env.SetList("SOME", list); err != nil { t.Error(err) } if got := env.GetList("SOME"); !reflect.DeepEqual(got, list) { t.Errorf("Env.SetList(%v): wrong result. Got %v", list, got) } } func TestSet(t *testing.T) { var env Env env.Set("PATH", "/home/bin:/bin") env.Set("SOMETHING", "/usr/bin") env.Set("PATH", "/bin") if expected, got := "/usr/bin", env.Get("SOMETHING"); got != expected { t.Errorf("Env.Set(%q): wrong result. Want %q. Got %q", expected, expected, got) } if expected, got := "/bin", env.Get("PATH"); got != expected { t.Errorf("Env.Set(%q): wrong result. Want %q. Got %q", expected, expected, got) } } func TestDecode(t *testing.T) { var tests = []struct { input string expectedOut []string expectedErr string }{ { `{"PATH":"/usr/bin:/bin","containers":54,"wat":["123","345"]}`, []string{"PATH=/usr/bin:/bin", "containers=54", `wat=["123","345"]`}, "", }, {"}}", nil, "invalid character '}' looking for beginning of value"}, {`{}`, nil, ""}, } for _, tt := range tests { var env Env err := env.Decode(bytes.NewBufferString(tt.input)) if tt.expectedErr == "" { if err != nil { t.Error(err) } } else if tt.expectedErr != err.Error() { t.Errorf("Env.Decode(): invalid error. Want %q. Got %q.", tt.expectedErr, err) } got := []string(env) sort.Strings(got) sort.Strings(tt.expectedOut) if !reflect.DeepEqual(got, tt.expectedOut) { t.Errorf("Env.Decode(): wrong result. Want %v. Got %v.", tt.expectedOut, got) } } } func TestSetAuto(t *testing.T) { buf := bytes.NewBufferString("oi") var tests = []struct { input interface{} expected string }{ {10, "10"}, {10.3, "10"}, {"oi", "oi"}, {buf, "{}"}, {unmarshable{}, "{}"}, } for _, tt := range tests { var env Env env.SetAuto("SOME", tt.input) if got := env.Get("SOME"); got != tt.expected { t.Errorf("Env.SetAuto(%v): wrong result. Want %q. Got %q", tt.input, tt.expected, got) } } } func TestMap(t *testing.T) { var tests = []struct { input []string expected map[string]string }{ {[]string{"PATH=/usr/bin:/bin", "PYTHONPATH=/usr/local"}, map[string]string{"PATH": "/usr/bin:/bin", "PYTHONPATH": "/usr/local"}}, {nil, nil}, } for _, tt := range tests { env := Env(tt.input) got := env.Map() if !reflect.DeepEqual(got, tt.expected) { t.Errorf("Env.Map(): wrong result. Want %v. Got %v", tt.expected, got) } } } type unmarshable struct { } func (unmarshable) MarshalJSON() ([]byte, error) { return nil, errors.New("cannot marshal") } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/event.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "errors" "fmt" "io" "math" "net" "net/http" "net/http/httputil" "sync" "sync/atomic" "time" ) // APIEvents represents an event returned by the API. type APIEvents struct { Status string `json:"Status,omitempty" yaml:"Status,omitempty"` ID string `json:"ID,omitempty" yaml:"ID,omitempty"` From string `json:"From,omitempty" yaml:"From,omitempty"` Time int64 `json:"Time,omitempty" yaml:"Time,omitempty"` } type eventMonitoringState struct { sync.RWMutex sync.WaitGroup enabled bool lastSeen *int64 C chan *APIEvents errC chan error listeners []chan<- *APIEvents } const ( maxMonitorConnRetries = 5 retryInitialWaitTime = 10. ) var ( // ErrNoListeners is the error returned when no listeners are available // to receive an event. ErrNoListeners = errors.New("no listeners present to receive event") // ErrListenerAlreadyExists is the error returned when the listerner already // exists. ErrListenerAlreadyExists = errors.New("listener already exists for docker events") // EOFEvent is sent when the event listener receives an EOF error. EOFEvent = &APIEvents{ Status: "EOF", } ) // AddEventListener adds a new listener to container events in the Docker API. // // The parameter is a channel through which events will be sent. func (c *Client) AddEventListener(listener chan<- *APIEvents) error { var err error if !c.eventMonitor.isEnabled() { err = c.eventMonitor.enableEventMonitoring(c) if err != nil { return err } } err = c.eventMonitor.addListener(listener) if err != nil { return err } return nil } // RemoveEventListener removes a listener from the monitor. func (c *Client) RemoveEventListener(listener chan *APIEvents) error { err := c.eventMonitor.removeListener(listener) if err != nil { return err } if len(c.eventMonitor.listeners) == 0 { c.eventMonitor.disableEventMonitoring() } return nil } func (eventState *eventMonitoringState) addListener(listener chan<- *APIEvents) error { eventState.Lock() defer eventState.Unlock() if listenerExists(listener, &eventState.listeners) { return ErrListenerAlreadyExists } eventState.Add(1) eventState.listeners = append(eventState.listeners, listener) return nil } func (eventState *eventMonitoringState) removeListener(listener chan<- *APIEvents) error { eventState.Lock() defer eventState.Unlock() if listenerExists(listener, &eventState.listeners) { var newListeners []chan<- *APIEvents for _, l := range eventState.listeners { if l != listener { newListeners = append(newListeners, l) } } eventState.listeners = newListeners eventState.Add(-1) } return nil } func (eventState *eventMonitoringState) closeListeners() { for _, l := range eventState.listeners { close(l) eventState.Add(-1) } eventState.listeners = nil } func listenerExists(a chan<- *APIEvents, list *[]chan<- *APIEvents) bool { for _, b := range *list { if b == a { return true } } return false } func (eventState *eventMonitoringState) enableEventMonitoring(c *Client) error { eventState.Lock() defer eventState.Unlock() if !eventState.enabled { eventState.enabled = true var lastSeenDefault = int64(0) eventState.lastSeen = &lastSeenDefault eventState.C = make(chan *APIEvents, 100) eventState.errC = make(chan error, 1) go eventState.monitorEvents(c) } return nil } func (eventState *eventMonitoringState) disableEventMonitoring() error { eventState.Lock() defer eventState.Unlock() eventState.closeListeners() eventState.Wait() if eventState.enabled { eventState.enabled = false close(eventState.C) close(eventState.errC) } return nil } func (eventState *eventMonitoringState) monitorEvents(c *Client) { var err error for eventState.noListeners() { time.Sleep(10 * time.Millisecond) } if err = eventState.connectWithRetry(c); err != nil { // terminate if connect failed eventState.disableEventMonitoring() return } for eventState.isEnabled() { timeout := time.After(100 * time.Millisecond) select { case ev, ok := <-eventState.C: if !ok { return } if ev == EOFEvent { eventState.disableEventMonitoring() return } eventState.updateLastSeen(ev) go eventState.sendEvent(ev) case err = <-eventState.errC: if err == ErrNoListeners { eventState.disableEventMonitoring() return } else if err != nil { defer func() { go eventState.monitorEvents(c) }() return } case <-timeout: continue } } } func (eventState *eventMonitoringState) connectWithRetry(c *Client) error { var retries int var err error for err = c.eventHijack(atomic.LoadInt64(eventState.lastSeen), eventState.C, eventState.errC); err != nil && retries < maxMonitorConnRetries; retries++ { waitTime := int64(retryInitialWaitTime * math.Pow(2, float64(retries))) time.Sleep(time.Duration(waitTime) * time.Millisecond) err = c.eventHijack(atomic.LoadInt64(eventState.lastSeen), eventState.C, eventState.errC) } return err } func (eventState *eventMonitoringState) noListeners() bool { eventState.RLock() defer eventState.RUnlock() return len(eventState.listeners) == 0 } func (eventState *eventMonitoringState) isEnabled() bool { eventState.RLock() defer eventState.RUnlock() return eventState.enabled } func (eventState *eventMonitoringState) sendEvent(event *APIEvents) { eventState.RLock() defer eventState.RUnlock() eventState.Add(1) defer eventState.Done() if eventState.enabled { if len(eventState.listeners) == 0 { eventState.errC <- ErrNoListeners return } for _, listener := range eventState.listeners { listener <- event } } } func (eventState *eventMonitoringState) updateLastSeen(e *APIEvents) { eventState.Lock() defer eventState.Unlock() if atomic.LoadInt64(eventState.lastSeen) < e.Time { atomic.StoreInt64(eventState.lastSeen, e.Time) } } func (c *Client) eventHijack(startTime int64, eventChan chan *APIEvents, errChan chan error) error { uri := "/events" if startTime != 0 { uri += fmt.Sprintf("?since=%d", startTime) } protocol := c.endpointURL.Scheme address := c.endpointURL.Path if protocol != "unix" { protocol = "tcp" address = c.endpointURL.Host } var dial net.Conn var err error if c.TLSConfig == nil { dial, err = c.Dialer.Dial(protocol, address) } else { dial, err = tlsDialWithDialer(c.Dialer, protocol, address, c.TLSConfig) } if err != nil { return err } conn := httputil.NewClientConn(dial, nil) req, err := http.NewRequest("GET", uri, nil) if err != nil { return err } res, err := conn.Do(req) if err != nil { return err } go func(res *http.Response, conn *httputil.ClientConn) { defer conn.Close() defer res.Body.Close() decoder := json.NewDecoder(res.Body) for { var event APIEvents if err = decoder.Decode(&event); err != nil { if err == io.EOF || err == io.ErrUnexpectedEOF { if c.eventMonitor.isEnabled() { // Signal that we're exiting. eventChan <- EOFEvent } break } errChan <- err } if event.Time == 0 { continue } if !c.eventMonitor.isEnabled() { return } eventChan <- &event } }(res, conn) return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/event_test.go ================================================ // Copyright 2014 go-dockerclient 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 docker import ( "bufio" "crypto/tls" "crypto/x509" "fmt" "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestEventListeners(t *testing.T) { testEventListeners("TestEventListeners", t, httptest.NewServer, NewClient) } func TestTLSEventListeners(t *testing.T) { testEventListeners("TestTLSEventListeners", t, func(handler http.Handler) *httptest.Server { server := httptest.NewUnstartedServer(handler) cert, err := tls.LoadX509KeyPair("testing/data/server.pem", "testing/data/serverkey.pem") if err != nil { t.Fatalf("Error loading server key pair: %s", err) } caCert, err := ioutil.ReadFile("testing/data/ca.pem") if err != nil { t.Fatalf("Error loading ca certificate: %s", err) } caPool := x509.NewCertPool() if !caPool.AppendCertsFromPEM(caCert) { t.Fatalf("Could not add ca certificate") } server.TLS = &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caPool, } server.StartTLS() return server }, func(url string) (*Client, error) { return NewTLSClient(url, "testing/data/cert.pem", "testing/data/key.pem", "testing/data/ca.pem") }) } func testEventListeners(testName string, t *testing.T, buildServer func(http.Handler) *httptest.Server, buildClient func(string) (*Client, error)) { response := `{"status":"create","id":"dfdf82bd3881","from":"base:latest","time":1374067924} {"status":"start","id":"dfdf82bd3881","from":"base:latest","time":1374067924} {"status":"stop","id":"dfdf82bd3881","from":"base:latest","time":1374067966} {"status":"destroy","id":"dfdf82bd3881","from":"base:latest","time":1374067970} ` server := buildServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { rsc := bufio.NewScanner(strings.NewReader(response)) for rsc.Scan() { w.Write([]byte(rsc.Text())) w.(http.Flusher).Flush() time.Sleep(10 * time.Millisecond) } })) defer server.Close() client, err := buildClient(server.URL) if err != nil { t.Errorf("Failed to create client: %s", err) } client.SkipServerVersionCheck = true listener := make(chan *APIEvents, 10) defer func() { time.Sleep(10 * time.Millisecond) if err := client.RemoveEventListener(listener); err != nil { t.Error(err) } }() err = client.AddEventListener(listener) if err != nil { t.Errorf("Failed to add event listener: %s", err) } timeout := time.After(1 * time.Second) var count int for { select { case msg := <-listener: t.Logf("Received: %v", *msg) count++ err = checkEvent(count, msg) if err != nil { t.Fatalf("Check event failed: %s", err) } if count == 4 { return } case <-timeout: t.Fatalf("%s timed out waiting on events", testName) } } } func checkEvent(index int, event *APIEvents) error { if event.ID != "dfdf82bd3881" { return fmt.Errorf("event ID did not match. Expected dfdf82bd3881 got %s", event.ID) } if event.From != "base:latest" { return fmt.Errorf("event from did not match. Expected base:latest got %s", event.From) } var status string switch index { case 1: status = "create" case 2: status = "start" case 3: status = "stop" case 4: status = "destroy" } if event.Status != status { return fmt.Errorf("event status did not match. Expected %s got %s", status, event.Status) } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/example_test.go ================================================ // Copyright 2014 go-dockerclient 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 docker_test import ( "archive/tar" "bytes" "fmt" "io" "log" "time" "github.com/fsouza/go-dockerclient" ) func ExampleClient_AttachToContainer() { client, err := docker.NewClient("http://localhost:4243") if err != nil { log.Fatal(err) } client.SkipServerVersionCheck = true // Reading logs from container a84849 and sending them to buf. var buf bytes.Buffer err = client.AttachToContainer(docker.AttachToContainerOptions{ Container: "a84849", OutputStream: &buf, Logs: true, Stdout: true, Stderr: true, }) if err != nil { log.Fatal(err) } log.Println(buf.String()) buf.Reset() err = client.AttachToContainer(docker.AttachToContainerOptions{ Container: "a84849", OutputStream: &buf, Stdout: true, Stream: true, }) if err != nil { log.Fatal(err) } log.Println(buf.String()) } func ExampleClient_CopyFromContainer() { client, err := docker.NewClient("http://localhost:4243") if err != nil { log.Fatal(err) } cid := "a84849" var buf bytes.Buffer filename := "/tmp/output.txt" err = client.CopyFromContainer(docker.CopyFromContainerOptions{ Container: cid, Resource: filename, OutputStream: &buf, }) if err != nil { log.Fatalf("Error while copying from %s: %s\n", cid, err) } content := new(bytes.Buffer) r := bytes.NewReader(buf.Bytes()) tr := tar.NewReader(r) tr.Next() if err != nil && err != io.EOF { log.Fatal(err) } if _, err := io.Copy(content, tr); err != nil { log.Fatal(err) } log.Println(buf.String()) } func ExampleClient_BuildImage() { client, err := docker.NewClient("http://localhost:4243") if err != nil { log.Fatal(err) } t := time.Now() inputbuf, outputbuf := bytes.NewBuffer(nil), bytes.NewBuffer(nil) tr := tar.NewWriter(inputbuf) tr.WriteHeader(&tar.Header{Name: "Dockerfile", Size: 10, ModTime: t, AccessTime: t, ChangeTime: t}) tr.Write([]byte("FROM base\n")) tr.Close() opts := docker.BuildImageOptions{ Name: "test", InputStream: inputbuf, OutputStream: outputbuf, } if err := client.BuildImage(opts); err != nil { log.Fatal(err) } } func ExampleClient_ListenEvents() { client, err := docker.NewClient("http://localhost:4243") if err != nil { log.Fatal(err) } listener := make(chan *docker.APIEvents) err = client.AddEventListener(listener) if err != nil { log.Fatal(err) } defer func() { err = client.RemoveEventListener(listener) if err != nil { log.Fatal(err) } }() timeout := time.After(1 * time.Second) for { select { case msg := <-listener: log.Println(msg) case <-timeout: break } } } func ExampleEnv_Map() { e := docker.Env([]string{"A=1", "B=2", "C=3"}) envs := e.Map() for k, v := range envs { fmt.Printf("%s=%q\n", k, v) } } func ExampleEnv_SetJSON() { type Person struct { Name string Age int } p := Person{Name: "Gopher", Age: 4} var e docker.Env err := e.SetJSON("person", p) if err != nil { log.Fatal(err) } } func ExampleEnv_GetJSON() { type Person struct { Name string Age int } p := Person{Name: "Gopher", Age: 4} var e docker.Env e.Set("person", `{"name":"Gopher","age":4}`) err := e.GetJSON("person", &p) if err != nil { log.Fatal(err) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/exec.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "fmt" "io" "net/http" "net/url" "strconv" ) // Exec is the type representing a `docker exec` instance and containing the // instance ID type Exec struct { ID string `json:"Id,omitempty" yaml:"Id,omitempty"` } // CreateExecOptions specify parameters to the CreateExecContainer function. // // See https://goo.gl/1KSIb7 for more details type CreateExecOptions struct { AttachStdin bool `json:"AttachStdin,omitempty" yaml:"AttachStdin,omitempty"` AttachStdout bool `json:"AttachStdout,omitempty" yaml:"AttachStdout,omitempty"` AttachStderr bool `json:"AttachStderr,omitempty" yaml:"AttachStderr,omitempty"` Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty"` Cmd []string `json:"Cmd,omitempty" yaml:"Cmd,omitempty"` Container string `json:"Container,omitempty" yaml:"Container,omitempty"` User string `json:"User,omitempty" yaml:"User,omitempty"` } // CreateExec sets up an exec instance in a running container `id`, returning the exec // instance, or an error in case of failure. // // See https://goo.gl/1KSIb7 for more details func (c *Client) CreateExec(opts CreateExecOptions) (*Exec, error) { path := fmt.Sprintf("/containers/%s/exec", opts.Container) resp, err := c.do("POST", path, doOptions{data: opts}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchContainer{ID: opts.Container} } return nil, err } defer resp.Body.Close() var exec Exec if err := json.NewDecoder(resp.Body).Decode(&exec); err != nil { return nil, err } return &exec, nil } // StartExecOptions specify parameters to the StartExecContainer function. // // See https://goo.gl/iQCnto for more details type StartExecOptions struct { Detach bool `json:"Detach,omitempty" yaml:"Detach,omitempty"` Tty bool `json:"Tty,omitempty" yaml:"Tty,omitempty"` InputStream io.Reader `qs:"-"` OutputStream io.Writer `qs:"-"` ErrorStream io.Writer `qs:"-"` // Use raw terminal? Usually true when the container contains a TTY. RawTerminal bool `qs:"-"` // If set, after a successful connect, a sentinel will be sent and then the // client will block on receive before continuing. // // It must be an unbuffered channel. Using a buffered channel can lead // to unexpected behavior. Success chan struct{} `json:"-"` } // StartExec starts a previously set up exec instance id. If opts.Detach is // true, it returns after starting the exec command. Otherwise, it sets up an // interactive session with the exec command. // // See https://goo.gl/iQCnto for more details func (c *Client) StartExec(id string, opts StartExecOptions) error { cw, err := c.StartExecNonBlocking(id, opts) if err != nil { return err } if cw != nil { return cw.Wait() } return nil } // StartExecNonBlocking starts a previously set up exec instance id. If opts.Detach is // true, it returns after starting the exec command. Otherwise, it sets up an // interactive session with the exec command. // // See https://goo.gl/iQCnto for more details func (c *Client) StartExecNonBlocking(id string, opts StartExecOptions) (CloseWaiter, error) { if id == "" { return nil, &NoSuchExec{ID: id} } path := fmt.Sprintf("/exec/%s/start", id) if opts.Detach { resp, err := c.do("POST", path, doOptions{data: opts}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchExec{ID: id} } return nil, err } defer resp.Body.Close() return nil, nil } return c.hijack("POST", path, hijackOptions{ success: opts.Success, setRawTerminal: opts.RawTerminal, in: opts.InputStream, stdout: opts.OutputStream, stderr: opts.ErrorStream, data: opts, }) } // ResizeExecTTY resizes the tty session used by the exec command id. This API // is valid only if Tty was specified as part of creating and starting the exec // command. // // See https://goo.gl/e1JpsA for more details func (c *Client) ResizeExecTTY(id string, height, width int) error { params := make(url.Values) params.Set("h", strconv.Itoa(height)) params.Set("w", strconv.Itoa(width)) path := fmt.Sprintf("/exec/%s/resize?%s", id, params.Encode()) resp, err := c.do("POST", path, doOptions{}) if err != nil { return err } resp.Body.Close() return nil } // ExecProcessConfig is a type describing the command associated to a Exec // instance. It's used in the ExecInspect type. type ExecProcessConfig struct { Privileged bool `json:"privileged,omitempty" yaml:"privileged,omitempty"` User string `json:"user,omitempty" yaml:"user,omitempty"` Tty bool `json:"tty,omitempty" yaml:"tty,omitempty"` EntryPoint string `json:"entrypoint,omitempty" yaml:"entrypoint,omitempty"` Arguments []string `json:"arguments,omitempty" yaml:"arguments,omitempty"` } // ExecInspect is a type with details about a exec instance, including the // exit code if the command has finished running. It's returned by a api // call to /exec/(id)/json // // See https://goo.gl/gPtX9R for more details type ExecInspect struct { ID string `json:"ID,omitempty" yaml:"ID,omitempty"` Running bool `json:"Running,omitempty" yaml:"Running,omitempty"` ExitCode int `json:"ExitCode,omitempty" yaml:"ExitCode,omitempty"` OpenStdin bool `json:"OpenStdin,omitempty" yaml:"OpenStdin,omitempty"` OpenStderr bool `json:"OpenStderr,omitempty" yaml:"OpenStderr,omitempty"` OpenStdout bool `json:"OpenStdout,omitempty" yaml:"OpenStdout,omitempty"` ProcessConfig ExecProcessConfig `json:"ProcessConfig,omitempty" yaml:"ProcessConfig,omitempty"` Container Container `json:"Container,omitempty" yaml:"Container,omitempty"` } // InspectExec returns low-level information about the exec command id. // // See https://goo.gl/gPtX9R for more details func (c *Client) InspectExec(id string) (*ExecInspect, error) { path := fmt.Sprintf("/exec/%s/json", id) resp, err := c.do("GET", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchExec{ID: id} } return nil, err } defer resp.Body.Close() var exec ExecInspect if err := json.NewDecoder(resp.Body).Decode(&exec); err != nil { return nil, err } return &exec, nil } // NoSuchExec is the error returned when a given exec instance does not exist. type NoSuchExec struct { ID string } func (err *NoSuchExec) Error() string { return "No such exec instance: " + err.ID } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/exec_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "bytes" "encoding/json" "net/http" "net/http/httptest" "net/url" "reflect" "strings" "testing" ) func TestExecCreate(t *testing.T) { jsonContainer := `{"Id": "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2"}` var expected struct{ ID string } err := json.Unmarshal([]byte(jsonContainer), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonContainer, status: http.StatusOK} client := newTestClient(fakeRT) config := CreateExecOptions{ Container: "test", AttachStdin: true, AttachStdout: true, AttachStderr: false, Tty: false, Cmd: []string{"touch", "/tmp/file"}, User: "a-user", } execObj, err := client.CreateExec(config) if err != nil { t.Fatal(err) } expectedID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" if execObj.ID != expectedID { t.Errorf("ExecCreate: wrong ID. Want %q. Got %q.", expectedID, execObj.ID) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("ExecCreate: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/containers/test/exec")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) } var gotBody struct{ ID string } err = json.NewDecoder(req.Body).Decode(&gotBody) if err != nil { t.Fatal(err) } } func TestExecStartDetached(t *testing.T) { execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" fakeRT := &FakeRoundTripper{status: http.StatusOK} client := newTestClient(fakeRT) config := StartExecOptions{ Detach: true, } err := client.StartExec(execID, config) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("ExecStart: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/exec/" + execID + "/start")) if gotPath := req.URL.Path; gotPath != expectedURL.Path { t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) } t.Log(req.Body) var gotBody struct{ Detach bool } err = json.NewDecoder(req.Body).Decode(&gotBody) if err != nil { t.Fatal(err) } if !gotBody.Detach { t.Fatal("Expected Detach in StartExecOptions to be true") } } func TestExecStartAndAttach(t *testing.T) { var reader = strings.NewReader("send value") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte{1, 0, 0, 0, 0, 0, 0, 5}) w.Write([]byte("hello")) })) defer server.Close() client, _ := NewClient(server.URL) client.SkipServerVersionCheck = true var stdout, stderr bytes.Buffer success := make(chan struct{}) execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" opts := StartExecOptions{ OutputStream: &stdout, ErrorStream: &stderr, InputStream: reader, RawTerminal: true, Success: success, } go func() { if err := client.StartExec(execID, opts); err != nil { t.Error(err) } }() <-success } func TestExecResize(t *testing.T) { execID := "4fa6e0f0c6786287e131c3852c58a2e01cc697a68231826813597e4994f1d6e2" fakeRT := &FakeRoundTripper{status: http.StatusOK} client := newTestClient(fakeRT) err := client.ResizeExecTTY(execID, 10, 20) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("ExecStart: wrong HTTP method. Want %q. Got %q.", "POST", req.Method) } expectedURL, _ := url.Parse(client.getURL("/exec/" + execID + "/resize?h=10&w=20")) if gotPath := req.URL.RequestURI(); gotPath != expectedURL.RequestURI() { t.Errorf("ExecCreate: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) } } func TestExecInspect(t *testing.T) { jsonExec := `{ "ID": "32adfeeec34250f9530ce1dafd40c6233832315e065ea6b362d745e2f63cde0e", "Running": true, "ExitCode": 0, "ProcessConfig": { "privileged": false, "user": "", "tty": true, "entrypoint": "bash", "arguments": [] }, "OpenStdin": true, "OpenStderr": true, "OpenStdout": true, "Container": { "State": { "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Pid": 29392, "ExitCode": 0, "Error": "", "StartedAt": "2015-01-21T17:08:59.634662178Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "ID": "922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521", "Created": "2015-01-21T17:08:59.46407212Z", "Path": "/bin/bash", "Args": [ "-lc", "tsuru_unit_agent http://192.168.50.4:8080 689b30e0ab3adce374346de2e72512138e0e8b75 gtest /var/lib/tsuru/start && tail -f /dev/null" ], "Config": { "Hostname": "922cd0568714", "Domainname": "", "User": "ubuntu", "Memory": 0, "MemorySwap": 0, "CpuShares": 100, "Cpuset": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "PortSpecs": null, "ExposedPorts": { "8888/tcp": {} }, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/bash", "-lc", "tsuru_unit_agent http://192.168.50.4:8080 689b30e0ab3adce374346de2e72512138e0e8b75 gtest /var/lib/tsuru/start && tail -f /dev/null" ], "Image": "tsuru/app-gtest", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "NetworkDisabled": false, "MacAddress": "", "OnBuild": null }, "Image": "a88060b8b54fde0f7168c86742d0ce83b80f3f10925d85c98fdad9ed00bef544", "NetworkSettings": { "IPAddress": "172.17.0.8", "IPPrefixLen": 16, "MacAddress": "02:42:ac:11:00:08", "LinkLocalIPv6Address": "fe80::42:acff:fe11:8", "LinkLocalIPv6PrefixLen": 64, "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "Gateway": "172.17.42.1", "IPv6Gateway": "", "Bridge": "docker0", "PortMapping": null, "Ports": { "8888/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "49156" } ] } }, "ResolvConfPath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/resolv.conf", "HostnamePath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/hostname", "HostsPath": "/var/lib/docker/containers/922cd0568714763dc725b24b7c9801016b2a3de68e2a1dc989bf5abf07740521/hosts", "Name": "/c7e43b72288ee9d0270a", "Driver": "aufs", "ExecDriver": "native-0.2", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "", "RestartCount": 0, "UpdateDns": false, "Volumes": {}, "VolumesRW": {} } }` var expected ExecInspect err := json.Unmarshal([]byte(jsonExec), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonExec, status: http.StatusOK} client := newTestClient(fakeRT) expectedID := "32adfeeec34250f9530ce1dafd40c6233832315e065ea6b362d745e2f63cde0e" execObj, err := client.InspectExec(expectedID) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(*execObj, expected) { t.Errorf("ExecInspect: Expected %#v. Got %#v.", expected, *execObj) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("ExecInspect: wrong HTTP method. Want %q. Got %q.", "GET", req.Method) } expectedURL, _ := url.Parse(client.getURL("/exec/" + expectedID + "/json")) if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { t.Errorf("ExecInspect: Wrong path in request. Want %q. Got %q.", expectedURL.Path, gotPath) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/CHANGELOG.md ================================================ # 0.9.0 (Unreleased) * logrus/text_formatter: don't emit empty msg * logrus/hooks/airbrake: move out of main repository * logrus/hooks/sentry: move out of main repository * logrus/hooks/papertrail: move out of main repository * logrus/hooks/bugsnag: move out of main repository # 0.8.7 * logrus/core: fix possible race (#216) * logrus/doc: small typo fixes and doc improvements # 0.8.6 * hooks/raven: allow passing an initialized client # 0.8.5 * logrus/core: revert #208 # 0.8.4 * formatter/text: fix data race (#218) # 0.8.3 * logrus/core: fix entry log level (#208) * logrus/core: improve performance of text formatter by 40% * logrus/core: expose `LevelHooks` type * logrus/core: add support for DragonflyBSD and NetBSD * formatter/text: print structs more verbosely # 0.8.2 * logrus: fix more Fatal family functions # 0.8.1 * logrus: fix not exiting on `Fatalf` and `Fatalln` # 0.8.0 * logrus: defaults to stderr instead of stdout * hooks/sentry: add special field for `*http.Request` * formatter/text: ignore Windows for colors # 0.7.3 * formatter/\*: allow configuration of timestamp layout # 0.7.2 * formatter/text: Add configuration option for time format (#158) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/README.md ================================================ # Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![godoc reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc] 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.Formatter = new(logrus.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.Formatter = new(&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 | | [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 | #### 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. * `logrus/formatters/logstash.LogstashFormatter`. Logs fields as [Logstash](http://logstash.net) Events. ```go logrus.SetFormatter(&logstash.LogstashFormatter{Type: "application_name"}) ``` Third party logging formatters: * [`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.| [godoc]: https://godoc.org/github.com/Sirupsen/logrus ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/doc.go ================================================ /* 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry.go ================================================ package logrus import ( "bytes" "fmt" "io" "os" "time" ) // 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 } func NewEntry(logger *Logger) *Entry { return &Entry{ Logger: logger, // Default is three fields, give a little extra room Data: make(Fields, 5), } } // Returns a reader for the entry, which is a proxy to the formatter. func (entry *Entry) Reader() (*bytes.Buffer, error) { serialized, err := entry.Logger.Formatter.Format(entry) return bytes.NewBuffer(serialized), err } // Returns the string representation from the reader and ultimately the // formatter. func (entry *Entry) String() (string, error) { reader, err := entry.Reader() if err != nil { return "", err } return reader.String(), err } // 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 := 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) { 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() } reader, err := entry.Reader() if err != nil { entry.Logger.mu.Lock() fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) entry.Logger.mu.Unlock() } entry.Logger.mu.Lock() defer entry.Logger.mu.Unlock() _, err = io.Copy(entry.Logger.Out, reader) if err != nil { fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) } // 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...)) } os.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...)) } os.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...)) } os.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] } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/entry_test.go ================================================ package logrus import ( "bytes" "fmt" "testing" "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" ) func TestEntryWithError(t *testing.T) { assert := assert.New(t) defer func() { ErrorKey = "error" }() err := fmt.Errorf("kaboom at layer %d", 4711) assert.Equal(err, WithError(err).Data["error"]) logger := New() logger.Out = &bytes.Buffer{} entry := NewEntry(logger) assert.Equal(err, entry.WithError(err).Data["error"]) ErrorKey = "err" assert.Equal(err, entry.WithError(err).Data["err"]) } func TestEntryPanicln(t *testing.T) { errBoom := fmt.Errorf("boom time") defer func() { p := recover() assert.NotNil(t, p) switch pVal := p.(type) { case *Entry: assert.Equal(t, "kaboom", pVal.Message) assert.Equal(t, errBoom, pVal.Data["err"]) default: t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) } }() logger := New() logger.Out = &bytes.Buffer{} entry := NewEntry(logger) entry.WithField("err", errBoom).Panicln("kaboom") } func TestEntryPanicf(t *testing.T) { errBoom := fmt.Errorf("boom again") defer func() { p := recover() assert.NotNil(t, p) switch pVal := p.(type) { case *Entry: assert.Equal(t, "kaboom true", pVal.Message) assert.Equal(t, errBoom, pVal.Data["err"]) default: t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal) } }() logger := New() logger.Out = &bytes.Buffer{} entry := NewEntry(logger) entry.WithField("err", errBoom).Panicf("kaboom %v", true) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/exported.go ================================================ 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...) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter.go ================================================ 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) { _, ok := data["time"] if ok { data["fields.time"] = data["time"] } _, ok = data["msg"] if ok { data["fields.msg"] = data["msg"] } _, ok = data["level"] if ok { data["fields.level"] = data["level"] } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/formatter_bench_test.go ================================================ package logrus import ( "fmt" "testing" "time" ) // smallFields is a small size data set for benchmarking var smallFields = Fields{ "foo": "bar", "baz": "qux", "one": "two", "three": "four", } // largeFields is a large size data set for benchmarking var largeFields = Fields{ "foo": "bar", "baz": "qux", "one": "two", "three": "four", "five": "six", "seven": "eight", "nine": "ten", "eleven": "twelve", "thirteen": "fourteen", "fifteen": "sixteen", "seventeen": "eighteen", "nineteen": "twenty", "a": "b", "c": "d", "e": "f", "g": "h", "i": "j", "k": "l", "m": "n", "o": "p", "q": "r", "s": "t", "u": "v", "w": "x", "y": "z", "this": "will", "make": "thirty", "entries": "yeah", } var errorFields = Fields{ "foo": fmt.Errorf("bar"), "baz": fmt.Errorf("qux"), } func BenchmarkErrorTextFormatter(b *testing.B) { doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields) } func BenchmarkSmallTextFormatter(b *testing.B) { doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields) } func BenchmarkLargeTextFormatter(b *testing.B) { doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields) } func BenchmarkSmallColoredTextFormatter(b *testing.B) { doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields) } func BenchmarkLargeColoredTextFormatter(b *testing.B) { doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields) } func BenchmarkSmallJSONFormatter(b *testing.B) { doBenchmark(b, &JSONFormatter{}, smallFields) } func BenchmarkLargeJSONFormatter(b *testing.B) { doBenchmark(b, &JSONFormatter{}, largeFields) } func doBenchmark(b *testing.B, formatter Formatter, fields Fields) { entry := &Entry{ Time: time.Time{}, Level: InfoLevel, Message: "message", Data: fields, } var d []byte var err error for i := 0; i < b.N; i++ { d, err = formatter.Format(entry) if err != nil { b.Fatal(err) } b.SetBytes(int64(len(d))) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hook_test.go ================================================ package logrus import ( "testing" "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" ) type TestHook struct { Fired bool } func (hook *TestHook) Fire(entry *Entry) error { hook.Fired = true return nil } func (hook *TestHook) Levels() []Level { return []Level{ DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel, } } func TestHookFires(t *testing.T) { hook := new(TestHook) LogAndAssertJSON(t, func(log *Logger) { log.Hooks.Add(hook) assert.Equal(t, hook.Fired, false) log.Print("test") }, func(fields Fields) { assert.Equal(t, hook.Fired, true) }) } type ModifyHook struct { } func (hook *ModifyHook) Fire(entry *Entry) error { entry.Data["wow"] = "whale" return nil } func (hook *ModifyHook) Levels() []Level { return []Level{ DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, PanicLevel, } } func TestHookCanModifyEntry(t *testing.T) { hook := new(ModifyHook) LogAndAssertJSON(t, func(log *Logger) { log.Hooks.Add(hook) log.WithField("wow", "elephant").Print("test") }, func(fields Fields) { assert.Equal(t, fields["wow"], "whale") }) } func TestCanFireMultipleHooks(t *testing.T) { hook1 := new(ModifyHook) hook2 := new(TestHook) LogAndAssertJSON(t, func(log *Logger) { log.Hooks.Add(hook1) log.Hooks.Add(hook2) log.WithField("wow", "elephant").Print("test") }, func(fields Fields) { assert.Equal(t, fields["wow"], "whale") assert.Equal(t, hook2.Fired, true) }) } type ErrorHook struct { Fired bool } func (hook *ErrorHook) Fire(entry *Entry) error { hook.Fired = true return nil } func (hook *ErrorHook) Levels() []Level { return []Level{ ErrorLevel, } } func TestErrorHookShouldntFireOnInfo(t *testing.T) { hook := new(ErrorHook) LogAndAssertJSON(t, func(log *Logger) { log.Hooks.Add(hook) log.Info("test") }, func(fields Fields) { assert.Equal(t, hook.Fired, false) }) } func TestErrorHookShouldFireOnError(t *testing.T) { hook := new(ErrorHook) LogAndAssertJSON(t, func(log *Logger) { log.Hooks.Add(hook) log.Error("test") }, func(fields Fields) { assert.Equal(t, hook.Fired, true) }) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/hooks.go ================================================ 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter.go ================================================ 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/json_formatter_test.go ================================================ package logrus import ( "encoding/json" "errors" "testing" ) func TestErrorNotLost(t *testing.T) { formatter := &JSONFormatter{} b, err := formatter.Format(WithField("error", errors.New("wild walrus"))) if err != nil { t.Fatal("Unable to format entry: ", err) } entry := make(map[string]interface{}) err = json.Unmarshal(b, &entry) if err != nil { t.Fatal("Unable to unmarshal formatted entry: ", err) } if entry["error"] != "wild walrus" { t.Fatal("Error field not set") } } func TestErrorNotLostOnFieldNotNamedError(t *testing.T) { formatter := &JSONFormatter{} b, err := formatter.Format(WithField("omg", errors.New("wild walrus"))) if err != nil { t.Fatal("Unable to format entry: ", err) } entry := make(map[string]interface{}) err = json.Unmarshal(b, &entry) if err != nil { t.Fatal("Unable to unmarshal formatted entry: ", err) } if entry["omg"] != "wild walrus" { t.Fatal("Error field not set") } } func TestFieldClashWithTime(t *testing.T) { formatter := &JSONFormatter{} b, err := formatter.Format(WithField("time", "right now!")) if err != nil { t.Fatal("Unable to format entry: ", err) } entry := make(map[string]interface{}) err = json.Unmarshal(b, &entry) if err != nil { t.Fatal("Unable to unmarshal formatted entry: ", err) } if entry["fields.time"] != "right now!" { t.Fatal("fields.time not set to original time field") } if entry["time"] != "0001-01-01T00:00:00Z" { t.Fatal("time field not set to current time, was: ", entry["time"]) } } func TestFieldClashWithMsg(t *testing.T) { formatter := &JSONFormatter{} b, err := formatter.Format(WithField("msg", "something")) if err != nil { t.Fatal("Unable to format entry: ", err) } entry := make(map[string]interface{}) err = json.Unmarshal(b, &entry) if err != nil { t.Fatal("Unable to unmarshal formatted entry: ", err) } if entry["fields.msg"] != "something" { t.Fatal("fields.msg not set to original msg field") } } func TestFieldClashWithLevel(t *testing.T) { formatter := &JSONFormatter{} b, err := formatter.Format(WithField("level", "something")) if err != nil { t.Fatal("Unable to format entry: ", err) } entry := make(map[string]interface{}) err = json.Unmarshal(b, &entry) if err != nil { t.Fatal("Unable to unmarshal formatted entry: ", err) } if entry["fields.level"] != "something" { t.Fatal("fields.level not set to original level field") } } func TestJSONEntryEndsWithNewline(t *testing.T) { formatter := &JSONFormatter{} b, err := formatter.Format(WithField("level", "something")) if err != nil { t.Fatal("Unable to format entry: ", err) } if b[len(b)-1] != '\n' { t.Fatal("Expected JSON log entry to end with a newline") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logger.go ================================================ 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. mu sync.Mutex } // 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, } } // Adds a field to the log entry, note that you 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 { return NewEntry(logger).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 { return NewEntry(logger).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 { return NewEntry(logger).WithError(err) } func (logger *Logger) Debugf(format string, args ...interface{}) { if logger.Level >= DebugLevel { NewEntry(logger).Debugf(format, args...) } } func (logger *Logger) Infof(format string, args ...interface{}) { if logger.Level >= InfoLevel { NewEntry(logger).Infof(format, args...) } } func (logger *Logger) Printf(format string, args ...interface{}) { NewEntry(logger).Printf(format, args...) } func (logger *Logger) Warnf(format string, args ...interface{}) { if logger.Level >= WarnLevel { NewEntry(logger).Warnf(format, args...) } } func (logger *Logger) Warningf(format string, args ...interface{}) { if logger.Level >= WarnLevel { NewEntry(logger).Warnf(format, args...) } } func (logger *Logger) Errorf(format string, args ...interface{}) { if logger.Level >= ErrorLevel { NewEntry(logger).Errorf(format, args...) } } func (logger *Logger) Fatalf(format string, args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatalf(format, args...) } os.Exit(1) } func (logger *Logger) Panicf(format string, args ...interface{}) { if logger.Level >= PanicLevel { NewEntry(logger).Panicf(format, args...) } } func (logger *Logger) Debug(args ...interface{}) { if logger.Level >= DebugLevel { NewEntry(logger).Debug(args...) } } func (logger *Logger) Info(args ...interface{}) { if logger.Level >= InfoLevel { NewEntry(logger).Info(args...) } } func (logger *Logger) Print(args ...interface{}) { NewEntry(logger).Info(args...) } func (logger *Logger) Warn(args ...interface{}) { if logger.Level >= WarnLevel { NewEntry(logger).Warn(args...) } } func (logger *Logger) Warning(args ...interface{}) { if logger.Level >= WarnLevel { NewEntry(logger).Warn(args...) } } func (logger *Logger) Error(args ...interface{}) { if logger.Level >= ErrorLevel { NewEntry(logger).Error(args...) } } func (logger *Logger) Fatal(args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatal(args...) } os.Exit(1) } func (logger *Logger) Panic(args ...interface{}) { if logger.Level >= PanicLevel { NewEntry(logger).Panic(args...) } } func (logger *Logger) Debugln(args ...interface{}) { if logger.Level >= DebugLevel { NewEntry(logger).Debugln(args...) } } func (logger *Logger) Infoln(args ...interface{}) { if logger.Level >= InfoLevel { NewEntry(logger).Infoln(args...) } } func (logger *Logger) Println(args ...interface{}) { NewEntry(logger).Println(args...) } func (logger *Logger) Warnln(args ...interface{}) { if logger.Level >= WarnLevel { NewEntry(logger).Warnln(args...) } } func (logger *Logger) Warningln(args ...interface{}) { if logger.Level >= WarnLevel { NewEntry(logger).Warnln(args...) } } func (logger *Logger) Errorln(args ...interface{}) { if logger.Level >= ErrorLevel { NewEntry(logger).Errorln(args...) } } func (logger *Logger) Fatalln(args ...interface{}) { if logger.Level >= FatalLevel { NewEntry(logger).Fatalln(args...) } os.Exit(1) } func (logger *Logger) Panicln(args ...interface{}) { if logger.Level >= PanicLevel { NewEntry(logger).Panicln(args...) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus.go ================================================ package logrus import ( "fmt" "log" ) // 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 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) } // 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{}) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/logrus_test.go ================================================ package logrus import ( "bytes" "encoding/json" "strconv" "strings" "sync" "testing" "github.com/fsouza/go-dockerclient/external/github.com/stretchr/testify/assert" ) func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) { var buffer bytes.Buffer var fields Fields logger := New() logger.Out = &buffer logger.Formatter = new(JSONFormatter) log(logger) err := json.Unmarshal(buffer.Bytes(), &fields) assert.Nil(t, err) assertions(fields) } func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) { var buffer bytes.Buffer logger := New() logger.Out = &buffer logger.Formatter = &TextFormatter{ DisableColors: true, } log(logger) fields := make(map[string]string) for _, kv := range strings.Split(buffer.String(), " ") { if !strings.Contains(kv, "=") { continue } kvArr := strings.Split(kv, "=") key := strings.TrimSpace(kvArr[0]) val := kvArr[1] if kvArr[1][0] == '"' { var err error val, err = strconv.Unquote(val) assert.NoError(t, err) } fields[key] = val } assertions(fields) } func TestPrint(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Print("test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "test") assert.Equal(t, fields["level"], "info") }) } func TestInfo(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Info("test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "test") assert.Equal(t, fields["level"], "info") }) } func TestWarn(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Warn("test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "test") assert.Equal(t, fields["level"], "warning") }) } func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Infoln("test", "test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "test test") }) } func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Infoln("test", 10) }, func(fields Fields) { assert.Equal(t, fields["msg"], "test 10") }) } func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Infoln(10, 10) }, func(fields Fields) { assert.Equal(t, fields["msg"], "10 10") }) } func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Infoln(10, 10) }, func(fields Fields) { assert.Equal(t, fields["msg"], "10 10") }) } func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Info("test", 10) }, func(fields Fields) { assert.Equal(t, fields["msg"], "test10") }) } func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.Info("test", "test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "testtest") }) } func TestWithFieldsShouldAllowAssignments(t *testing.T) { var buffer bytes.Buffer var fields Fields logger := New() logger.Out = &buffer logger.Formatter = new(JSONFormatter) localLog := logger.WithFields(Fields{ "key1": "value1", }) localLog.WithField("key2", "value2").Info("test") err := json.Unmarshal(buffer.Bytes(), &fields) assert.Nil(t, err) assert.Equal(t, "value2", fields["key2"]) assert.Equal(t, "value1", fields["key1"]) buffer = bytes.Buffer{} fields = Fields{} localLog.Info("test") err = json.Unmarshal(buffer.Bytes(), &fields) assert.Nil(t, err) _, ok := fields["key2"] assert.Equal(t, false, ok) assert.Equal(t, "value1", fields["key1"]) } func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.WithField("msg", "hello").Info("test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "test") }) } func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.WithField("msg", "hello").Info("test") }, func(fields Fields) { assert.Equal(t, fields["msg"], "test") assert.Equal(t, fields["fields.msg"], "hello") }) } func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.WithField("time", "hello").Info("test") }, func(fields Fields) { assert.Equal(t, fields["fields.time"], "hello") }) } func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) { LogAndAssertJSON(t, func(log *Logger) { log.WithField("level", 1).Info("test") }, func(fields Fields) { assert.Equal(t, fields["level"], "info") assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only }) } func TestDefaultFieldsAreNotPrefixed(t *testing.T) { LogAndAssertText(t, func(log *Logger) { ll := log.WithField("herp", "derp") ll.Info("hello") ll.Info("bye") }, func(fields map[string]string) { for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} { if _, ok := fields[fieldName]; ok { t.Fatalf("should not have prefixed %q: %v", fieldName, fields) } } }) } func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) { var buffer bytes.Buffer var fields Fields logger := New() logger.Out = &buffer logger.Formatter = new(JSONFormatter) llog := logger.WithField("context", "eating raw fish") llog.Info("looks delicious") err := json.Unmarshal(buffer.Bytes(), &fields) assert.NoError(t, err, "should have decoded first message") assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") assert.Equal(t, fields["msg"], "looks delicious") assert.Equal(t, fields["context"], "eating raw fish") buffer.Reset() llog.Warn("omg it is!") err = json.Unmarshal(buffer.Bytes(), &fields) assert.NoError(t, err, "should have decoded second message") assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields") assert.Equal(t, fields["msg"], "omg it is!") assert.Equal(t, fields["context"], "eating raw fish") assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry") } func TestConvertLevelToString(t *testing.T) { assert.Equal(t, "debug", DebugLevel.String()) assert.Equal(t, "info", InfoLevel.String()) assert.Equal(t, "warning", WarnLevel.String()) assert.Equal(t, "error", ErrorLevel.String()) assert.Equal(t, "fatal", FatalLevel.String()) assert.Equal(t, "panic", PanicLevel.String()) } func TestParseLevel(t *testing.T) { l, err := ParseLevel("panic") assert.Nil(t, err) assert.Equal(t, PanicLevel, l) l, err = ParseLevel("fatal") assert.Nil(t, err) assert.Equal(t, FatalLevel, l) l, err = ParseLevel("error") assert.Nil(t, err) assert.Equal(t, ErrorLevel, l) l, err = ParseLevel("warn") assert.Nil(t, err) assert.Equal(t, WarnLevel, l) l, err = ParseLevel("warning") assert.Nil(t, err) assert.Equal(t, WarnLevel, l) l, err = ParseLevel("info") assert.Nil(t, err) assert.Equal(t, InfoLevel, l) l, err = ParseLevel("debug") assert.Nil(t, err) assert.Equal(t, DebugLevel, l) l, err = ParseLevel("invalid") assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error()) } func TestGetSetLevelRace(t *testing.T) { wg := sync.WaitGroup{} for i := 0; i < 100; i++ { wg.Add(1) go func(i int) { defer wg.Done() if i%2 == 0 { SetLevel(InfoLevel) } else { GetLevel() } }(i) } wg.Wait() } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_bsd.go ================================================ // +build darwin freebsd openbsd netbsd dragonfly package logrus import "syscall" const ioctlReadTermios = syscall.TIOCGETA type Termios syscall.Termios ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_linux.go ================================================ // 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. package logrus import "syscall" const ioctlReadTermios = syscall.TCGETS type Termios syscall.Termios ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_notwindows.go ================================================ // 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_solaris.go ================================================ // +build solaris package logrus import ( "os" "github.com/fsouza/go-dockerclient/external/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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/terminal_windows.go ================================================ // 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter.go ================================================ 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 keys []string = make([]string, 0, len(entry.Data)) for k := range entry.Data { keys = append(keys, k) } if !f.DisableSorting { sort.Strings(keys) } 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=%+v", levelColor, k, 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 false } } return true } func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { b.WriteString(key) b.WriteByte('=') 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", value) } default: fmt.Fprint(b, value) } b.WriteByte(' ') } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/text_formatter_test.go ================================================ package logrus import ( "bytes" "errors" "testing" "time" ) func TestQuoting(t *testing.T) { tf := &TextFormatter{DisableColors: true} checkQuoting := func(q bool, value interface{}) { b, _ := tf.Format(WithField("test", value)) idx := bytes.Index(b, ([]byte)("test=")) cont := bytes.Contains(b[idx+5:], []byte{'"'}) if cont != q { if q { t.Errorf("quoting expected for: %#v", value) } else { t.Errorf("quoting not expected for: %#v", value) } } } checkQuoting(false, "abcd") checkQuoting(false, "v1.0") checkQuoting(false, "1234567890") checkQuoting(true, "/foobar") checkQuoting(true, "x y") checkQuoting(true, "x,y") checkQuoting(false, errors.New("invalid")) checkQuoting(true, errors.New("invalid argument")) } func TestTimestampFormat(t *testing.T) { checkTimeStr := func(format string) { customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format} customStr, _ := customFormatter.Format(WithField("test", "test")) timeStart := bytes.Index(customStr, ([]byte)("time=")) timeEnd := bytes.Index(customStr, ([]byte)("level=")) timeStr := customStr[timeStart+5 : timeEnd-1] if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' { timeStr = timeStr[1 : len(timeStr)-1] } if format == "" { format = time.RFC3339 } _, e := time.Parse(format, (string)(timeStr)) if e != nil { t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e) } } checkTimeStr("2006-01-02T15:04:05.000000000Z07:00") checkTimeStr("Mon Jan _2 15:04:05 2006") checkTimeStr("") } // TODO add tests for sorting etc., this requires a parser for the text // formatter output. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus/writer.go ================================================ package logrus import ( "bufio" "io" "runtime" ) func (logger *Logger) Writer() *io.PipeWriter { reader, writer := io.Pipe() go logger.writerScanner(reader) runtime.SetFinalizer(writer, writerFinalizer) return writer } func (logger *Logger) writerScanner(reader *io.PipeReader) { scanner := bufio.NewScanner(reader) for scanner.Scan() { logger.Print(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() } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile.go ================================================ package opts import ( "bufio" "fmt" "os" "strings" ) // 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) for scanner.Scan() { // trim the line from all leading whitespace first line := strings.TrimLeft(scanner.Text(), whiteSpaces) // 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/envfile_test.go ================================================ package opts import ( "bufio" "fmt" "io/ioutil" "os" "reflect" "strings" "testing" ) func tmpFileWithContent(content string, t *testing.T) string { tmpFile, err := ioutil.TempFile("", "envfile-test") if err != nil { t.Fatal(err) } defer tmpFile.Close() tmpFile.WriteString(content) return tmpFile.Name() } // Test ParseEnvFile for a file with a few well formatted lines func TestParseEnvFileGoodFile(t *testing.T) { content := `foo=bar baz=quux # comment _foobar=foobaz with.dots=working and_underscore=working too ` // Adding a newline + a line with pure whitespace. // This is being done like this instead of the block above // because it's common for editors to trim trailing whitespace // from lines, which becomes annoying since that's the // exact thing we need to test. content += "\n \t " tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) lines, err := ParseEnvFile(tmpFile) if err != nil { t.Fatal(err) } expectedLines := []string{ "foo=bar", "baz=quux", "_foobar=foobaz", "with.dots=working", "and_underscore=working too", } if !reflect.DeepEqual(lines, expectedLines) { t.Fatal("lines not equal to expected_lines") } } // Test ParseEnvFile for an empty file func TestParseEnvFileEmptyFile(t *testing.T) { tmpFile := tmpFileWithContent("", t) defer os.Remove(tmpFile) lines, err := ParseEnvFile(tmpFile) if err != nil { t.Fatal(err) } if len(lines) != 0 { t.Fatal("lines not empty; expected empty") } } // Test ParseEnvFile for a non existent file func TestParseEnvFileNonExistentFile(t *testing.T) { _, err := ParseEnvFile("foo_bar_baz") if err == nil { t.Fatal("ParseEnvFile succeeded; expected failure") } if _, ok := err.(*os.PathError); !ok { t.Fatalf("Expected a PathError, got [%v]", err) } } // Test ParseEnvFile for a badly formatted file func TestParseEnvFileBadlyFormattedFile(t *testing.T) { content := `foo=bar f =quux ` tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) _, err := ParseEnvFile(tmpFile) if err == nil { t.Fatalf("Expected a ErrBadEnvVariable, got nothing") } if _, ok := err.(ErrBadEnvVariable); !ok { t.Fatalf("Expected a ErrBadEnvVariable, got [%v]", err) } expectedMessage := "poorly formatted environment: variable 'f ' has white spaces" if err.Error() != expectedMessage { t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) } } // Test ParseEnvFile for a file with a line exceeding bufio.MaxScanTokenSize func TestParseEnvFileLineTooLongFile(t *testing.T) { content := strings.Repeat("a", bufio.MaxScanTokenSize+42) content = fmt.Sprint("foo=", content) tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) _, err := ParseEnvFile(tmpFile) if err == nil { t.Fatal("ParseEnvFile succeeded; expected failure") } } // ParseEnvFile with a random file, pass through func TestParseEnvFileRandomFile(t *testing.T) { content := `first line another invalid line` tmpFile := tmpFileWithContent(content, t) defer os.Remove(tmpFile) _, err := ParseEnvFile(tmpFile) if err == nil { t.Fatalf("Expected a ErrBadEnvVariable, got nothing") } if _, ok := err.(ErrBadEnvVariable); !ok { t.Fatalf("Expected a ErrBadEnvvariable, got [%v]", err) } expectedMessage := "poorly formatted environment: variable 'first line' has white spaces" if err.Error() != expectedMessage { t.Fatalf("Expected [%v], got [%v]", expectedMessage, err.Error()) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts.go ================================================ package opts import ( "fmt" "net" "net/url" "runtime" "strconv" "strings" ) var ( // DefaultHTTPPort Default HTTP Port used if only the protocol is provided to -H flag e.g. docker daemon -H tcp:// // TODO Windows. DefaultHTTPPort is only used on Windows if a -H parameter // is not supplied. A better longer term solution would be to use a named // pipe as the default on the Windows daemon. // 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) ) // ValidateHost validates that the specified string is a valid host and returns it. func ValidateHost(val string) (string, error) { _, err := parseDockerDaemonHost(DefaultTCPHost, DefaultTLSHost, DefaultUnixSocket, "", val) 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(defaultHost, val string) (string, error) { host, err := parseDockerDaemonHost(DefaultTCPHost, DefaultTLSHost, DefaultUnixSocket, defaultHost, val) 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, will use the defaultTCPAddr or defaultUnixAddr // defaultUnixAddr must be a absolute file path (no `unix://` prefix) // defaultTCPAddr must be the full `tcp://host:port` form func parseDockerDaemonHost(defaultTCPAddr, defaultTLSHost, defaultUnixAddr, defaultAddr, addr string) (string, error) { addr = strings.TrimSpace(addr) if addr == "" { if defaultAddr == defaultTLSHost { return defaultTLSHost, nil } if runtime.GOOS != "windows" { return fmt.Sprintf("unix://%s", defaultUnixAddr), nil } return defaultTCPAddr, nil } addrParts := strings.Split(addr, "://") if len(addrParts) == 1 { addrParts = []string{"tcp", addrParts[0]} } switch addrParts[0] { case "tcp": return parseTCPAddr(addrParts[1], defaultTCPAddr) case "unix": return parseUnixAddr(addrParts[1], defaultUnixAddr) case "fd": return addr, nil default: return "", fmt.Errorf("Invalid bind address format: %s", addr) } } // parseUnixAddr parses and validates that the specified address is a valid UNIX // socket address. It returns a formatted UNIX socket address, either using the // address parsed from addr, or the contents of defaultAddr if addr is a blank // string. func parseUnixAddr(addr string, defaultAddr string) (string, error) { addr = strings.TrimPrefix(addr, "unix://") if strings.Contains(addr, "://") { return "", fmt.Errorf("Invalid proto, expected unix: %s", addr) } if addr == "" { addr = defaultAddr } return fmt.Sprintf("unix://%s", 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 { 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_test.go ================================================ package opts import ( "runtime" "testing" ) func TestParseHost(t *testing.T) { invalid := map[string]string{ "anything": "Invalid bind address format: anything", "something with spaces": "Invalid bind address format: something with spaces", "://": "Invalid bind address format: ://", "unknown://": "Invalid bind address format: unknown://", "tcp://:port": "Invalid bind address format: :port", "tcp://invalid": "Invalid bind address format: invalid", "tcp://invalid:port": "Invalid bind address format: invalid:port", } const defaultHTTPHost = "tcp://127.0.0.1:2375" var defaultHOST = "unix:///var/run/docker.sock" if runtime.GOOS == "windows" { defaultHOST = defaultHTTPHost } valid := map[string]string{ "": defaultHOST, "fd://": "fd://", "fd://something": "fd://something", "tcp://host:": "tcp://host:2375", "tcp://": "tcp://localhost:2375", "tcp://:2375": "tcp://localhost:2375", // default ip address "tcp://:2376": "tcp://localhost:2376", // default ip address "tcp://0.0.0.0:8080": "tcp://0.0.0.0:8080", "tcp://192.168.0.0:12000": "tcp://192.168.0.0:12000", "tcp://192.168:8080": "tcp://192.168:8080", "tcp://0.0.0.0:1234567890": "tcp://0.0.0.0:1234567890", // yeah it's valid :P "tcp://docker.com:2375": "tcp://docker.com:2375", "unix://": "unix:///var/run/docker.sock", // default unix:// value "unix://path/to/socket": "unix://path/to/socket", } for value, errorMessage := range invalid { if _, err := ParseHost(defaultHTTPHost, value); err == nil || err.Error() != errorMessage { t.Fatalf("Expected an error for %v with [%v], got [%v]", value, errorMessage, err) } } for value, expected := range valid { if actual, err := ParseHost(defaultHTTPHost, value); err != nil || actual != expected { t.Fatalf("Expected for %v [%v], got [%v, %v]", value, expected, actual, err) } } } func TestParseDockerDaemonHost(t *testing.T) { var ( defaultHTTPHost = "tcp://localhost:2375" defaultHTTPSHost = "tcp://localhost:2376" defaultUnix = "/var/run/docker.sock" defaultHOST = "unix:///var/run/docker.sock" ) if runtime.GOOS == "windows" { defaultHOST = defaultHTTPHost } invalids := map[string]string{ "0.0.0.0": "Invalid bind address format: 0.0.0.0", "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", "udp://127.0.0.1": "Invalid bind address format: udp://127.0.0.1", "udp://127.0.0.1:2375": "Invalid bind address format: udp://127.0.0.1:2375", "tcp://unix:///run/docker.sock": "Invalid bind address format: unix", "tcp": "Invalid bind address format: tcp", "unix": "Invalid bind address format: unix", "fd": "Invalid bind address format: fd", } valids := map[string]string{ "0.0.0.1:": "tcp://0.0.0.1:2375", "0.0.0.1:5555": "tcp://0.0.0.1:5555", "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", "[::1]:": "tcp://[::1]:2375", "[::1]:5555/path": "tcp://[::1]:5555/path", "[0:0:0:0:0:0:0:1]:": "tcp://[0:0:0:0:0:0:0:1]:2375", "[0:0:0:0:0:0:0:1]:5555/path": "tcp://[0:0:0:0:0:0:0:1]:5555/path", ":6666": "tcp://localhost:6666", ":6666/path": "tcp://localhost:6666/path", "": defaultHOST, " ": defaultHOST, " ": defaultHOST, "tcp://": defaultHTTPHost, "tcp://:7777": "tcp://localhost:7777", "tcp://:7777/path": "tcp://localhost:7777/path", " tcp://:7777/path ": "tcp://localhost:7777/path", "unix:///run/docker.sock": "unix:///run/docker.sock", "unix://": "unix:///var/run/docker.sock", "fd://": "fd://", "fd://something": "fd://something", "localhost:": "tcp://localhost:2375", "localhost:5555": "tcp://localhost:5555", "localhost:5555/path": "tcp://localhost:5555/path", } for invalidAddr, expectedError := range invalids { if addr, err := parseDockerDaemonHost(defaultHTTPHost, defaultHTTPSHost, defaultUnix, "", invalidAddr); err == nil || err.Error() != expectedError { t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) } } for validAddr, expectedAddr := range valids { if addr, err := parseDockerDaemonHost(defaultHTTPHost, defaultHTTPSHost, defaultUnix, "", validAddr); err != nil || addr != expectedAddr { t.Errorf("%v -> expected %v, got (%v) addr (%v)", validAddr, expectedAddr, err, addr) } } } func TestParseTCP(t *testing.T) { var ( defaultHTTPHost = "tcp://127.0.0.1:2376" ) invalids := map[string]string{ "0.0.0.0": "Invalid bind address format: 0.0.0.0", "tcp:a.b.c.d": "Invalid bind address format: tcp:a.b.c.d", "tcp:a.b.c.d/path": "Invalid bind address format: tcp:a.b.c.d/path", "udp://127.0.0.1": "Invalid proto, expected tcp: udp://127.0.0.1", "udp://127.0.0.1:2375": "Invalid proto, expected tcp: udp://127.0.0.1:2375", } valids := map[string]string{ "": defaultHTTPHost, "tcp://": defaultHTTPHost, "0.0.0.1:": "tcp://0.0.0.1:2376", "0.0.0.1:5555": "tcp://0.0.0.1:5555", "0.0.0.1:5555/path": "tcp://0.0.0.1:5555/path", ":6666": "tcp://127.0.0.1:6666", ":6666/path": "tcp://127.0.0.1:6666/path", "tcp://:7777": "tcp://127.0.0.1:7777", "tcp://:7777/path": "tcp://127.0.0.1:7777/path", "[::1]:": "tcp://[::1]:2376", "[::1]:5555": "tcp://[::1]:5555", "[::1]:5555/path": "tcp://[::1]:5555/path", "[0:0:0:0:0:0:0:1]:": "tcp://[0:0:0:0:0:0:0:1]:2376", "[0:0:0:0:0:0:0:1]:5555": "tcp://[0:0:0:0:0:0:0:1]:5555", "[0:0:0:0:0:0:0:1]:5555/path": "tcp://[0:0:0:0:0:0:0:1]:5555/path", "localhost:": "tcp://localhost:2376", "localhost:5555": "tcp://localhost:5555", "localhost:5555/path": "tcp://localhost:5555/path", } for invalidAddr, expectedError := range invalids { if addr, err := parseTCPAddr(invalidAddr, defaultHTTPHost); err == nil || err.Error() != expectedError { t.Errorf("tcp %v address expected error %v return, got %s and addr %v", invalidAddr, expectedError, err, addr) } } for validAddr, expectedAddr := range valids { if addr, err := parseTCPAddr(validAddr, defaultHTTPHost); err != nil || addr != expectedAddr { t.Errorf("%v -> expected %v, got %v and addr %v", validAddr, expectedAddr, err, addr) } } } func TestParseInvalidUnixAddrInvalid(t *testing.T) { if _, err := parseUnixAddr("tcp://127.0.0.1", "unix:///var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { t.Fatalf("Expected an error, got %v", err) } if _, err := parseUnixAddr("unix://tcp://127.0.0.1", "/var/run/docker.sock"); err == nil || err.Error() != "Invalid proto, expected unix: tcp://127.0.0.1" { t.Fatalf("Expected an error, got %v", err) } if v, err := parseUnixAddr("", "/var/run/docker.sock"); err != nil || v != "unix:///var/run/docker.sock" { t.Fatalf("Expected an %v, got %v", v, "unix:///var/run/docker.sock") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_unix.go ================================================ // +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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/hosts_windows.go ================================================ // +build windows package opts // DefaultHost constant defines the default host string used by docker on Windows var DefaultHost = DefaultTCPHost ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip.go ================================================ 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() } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/ip_test.go ================================================ package opts import ( "net" "testing" ) func TestIpOptString(t *testing.T) { addresses := []string{"", "0.0.0.0"} var ip net.IP for _, address := range addresses { stringAddress := NewIPOpt(&ip, address).String() if stringAddress != address { t.Fatalf("IpOpt string should be `%s`, not `%s`", address, stringAddress) } } } func TestNewIpOptInvalidDefaultVal(t *testing.T) { ip := net.IPv4(127, 0, 0, 1) defaultVal := "Not an ip" ipOpt := NewIPOpt(&ip, defaultVal) expected := "127.0.0.1" if ipOpt.String() != expected { t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) } } func TestNewIpOptValidDefaultVal(t *testing.T) { ip := net.IPv4(127, 0, 0, 1) defaultVal := "192.168.1.1" ipOpt := NewIPOpt(&ip, defaultVal) expected := "192.168.1.1" if ipOpt.String() != expected { t.Fatalf("Expected [%v], got [%v]", expected, ipOpt.String()) } } func TestIpOptSetInvalidVal(t *testing.T) { ip := net.IPv4(127, 0, 0, 1) ipOpt := &IPOpt{IP: &ip} invalidIP := "invalid ip" expectedError := "invalid ip is not an ip address" err := ipOpt.Set(invalidIP) if err == nil || err.Error() != expectedError { t.Fatalf("Expected an Error with [%v], got [%v]", expectedError, err.Error()) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts.go ================================================ package opts import ( "fmt" "net" "os" "regexp" "strings" ) 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 { return fmt.Sprintf("%v", []string((*opts.values))) } // Set validates if needed the input value and add 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)) } //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", map[string]string((opts.values))) } // 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, } } // 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) // 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, fmt.Errorf("valid streams are STDIN, STDOUT and STDERR") } // 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. func ValidateEnv(val string) (string, error) { arr := strings.Split(val, "=") if len(arr) > 1 { return val, nil } if !doesEnvExist(val) { return val, nil } return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil } // 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) } // ValidateExtraHost validates that the specified string is a valid extrahost and returns it. // ExtraHost are 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 } // 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 } func doesEnvExist(name string) bool { for _, entry := range os.Environ() { parts := strings.SplitN(entry, "=", 2) if parts[0] == name { return true } } return false } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_test.go ================================================ package opts import ( "fmt" "os" "strings" "testing" ) func TestValidateIPAddress(t *testing.T) { if ret, err := ValidateIPAddress(`1.2.3.4`); err != nil || ret == "" { t.Fatalf("ValidateIPAddress(`1.2.3.4`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`127.0.0.1`); err != nil || ret == "" { t.Fatalf("ValidateIPAddress(`127.0.0.1`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`::1`); err != nil || ret == "" { t.Fatalf("ValidateIPAddress(`::1`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`127`); err == nil || ret != "" { t.Fatalf("ValidateIPAddress(`127`) got %s %s", ret, err) } if ret, err := ValidateIPAddress(`random invalid string`); err == nil || ret != "" { t.Fatalf("ValidateIPAddress(`random invalid string`) got %s %s", ret, err) } } func TestMapOpts(t *testing.T) { tmpMap := make(map[string]string) o := NewMapOpts(tmpMap, logOptsValidator) o.Set("max-size=1") if o.String() != "map[max-size:1]" { t.Errorf("%s != [map[max-size:1]", o.String()) } o.Set("max-file=2") if len(tmpMap) != 2 { t.Errorf("map length %d != 2", len(tmpMap)) } if tmpMap["max-file"] != "2" { t.Errorf("max-file = %s != 2", tmpMap["max-file"]) } if tmpMap["max-size"] != "1" { t.Errorf("max-size = %s != 1", tmpMap["max-size"]) } if o.Set("dummy-val=3") == nil { t.Errorf("validator is not being called") } } func TestValidateMACAddress(t *testing.T) { if _, err := ValidateMACAddress(`92:d0:c6:0a:29:33`); err != nil { t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:29:33`) got %s", err) } if _, err := ValidateMACAddress(`92:d0:c6:0a:33`); err == nil { t.Fatalf("ValidateMACAddress(`92:d0:c6:0a:33`) succeeded; expected failure on invalid MAC") } if _, err := ValidateMACAddress(`random invalid string`); err == nil { t.Fatalf("ValidateMACAddress(`random invalid string`) succeeded; expected failure on invalid MAC") } } func TestListOptsWithoutValidator(t *testing.T) { o := NewListOpts(nil) o.Set("foo") if o.String() != "[foo]" { t.Errorf("%s != [foo]", o.String()) } o.Set("bar") if o.Len() != 2 { t.Errorf("%d != 2", o.Len()) } o.Set("bar") if o.Len() != 3 { t.Errorf("%d != 3", o.Len()) } if !o.Get("bar") { t.Error("o.Get(\"bar\") == false") } if o.Get("baz") { t.Error("o.Get(\"baz\") == true") } o.Delete("foo") if o.String() != "[bar bar]" { t.Errorf("%s != [bar bar]", o.String()) } listOpts := o.GetAll() if len(listOpts) != 2 || listOpts[0] != "bar" || listOpts[1] != "bar" { t.Errorf("Expected [[bar bar]], got [%v]", listOpts) } mapListOpts := o.GetMap() if len(mapListOpts) != 1 { t.Errorf("Expected [map[bar:{}]], got [%v]", mapListOpts) } } func TestListOptsWithValidator(t *testing.T) { // Re-using logOptsvalidator (used by MapOpts) o := NewListOpts(logOptsValidator) o.Set("foo") if o.String() != "[]" { t.Errorf("%s != []", o.String()) } o.Set("foo=bar") if o.String() != "[]" { t.Errorf("%s != []", o.String()) } o.Set("max-file=2") if o.Len() != 1 { t.Errorf("%d != 1", o.Len()) } if !o.Get("max-file=2") { t.Error("o.Get(\"max-file=2\") == false") } if o.Get("baz") { t.Error("o.Get(\"baz\") == true") } o.Delete("max-file=2") if o.String() != "[]" { t.Errorf("%s != []", o.String()) } } func TestValidateDNSSearch(t *testing.T) { valid := []string{ `.`, `a`, `a.`, `1.foo`, `17.foo`, `foo.bar`, `foo.bar.baz`, `foo.bar.`, `foo.bar.baz`, `foo1.bar2`, `foo1.bar2.baz`, `1foo.2bar.`, `1foo.2bar.baz`, `foo-1.bar-2`, `foo-1.bar-2.baz`, `foo-1.bar-2.`, `foo-1.bar-2.baz`, `1-foo.2-bar`, `1-foo.2-bar.baz`, `1-foo.2-bar.`, `1-foo.2-bar.baz`, } invalid := []string{ ``, ` `, ` `, `17`, `17.`, `.17`, `17-.`, `17-.foo`, `.foo`, `foo-.bar`, `-foo.bar`, `foo.bar-`, `foo.bar-.baz`, `foo.-bar`, `foo.-bar.baz`, `foo.bar.baz.this.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbethis.should.fail.on.long.name.beause.it.is.longer.thanisshouldbe`, } for _, domain := range valid { if ret, err := ValidateDNSSearch(domain); err != nil || ret == "" { t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) } } for _, domain := range invalid { if ret, err := ValidateDNSSearch(domain); err == nil || ret != "" { t.Fatalf("ValidateDNSSearch(`"+domain+"`) got %s %s", ret, err) } } } func TestValidateExtraHosts(t *testing.T) { valid := []string{ `myhost:192.168.0.1`, `thathost:10.0.2.1`, `anipv6host:2003:ab34:e::1`, `ipv6local:::1`, } invalid := map[string]string{ `myhost:192.notanipaddress.1`: `invalid IP`, `thathost-nosemicolon10.0.0.1`: `bad format`, `anipv6host:::::1`: `invalid IP`, `ipv6local:::0::`: `invalid IP`, } for _, extrahost := range valid { if _, err := ValidateExtraHost(extrahost); err != nil { t.Fatalf("ValidateExtraHost(`"+extrahost+"`) should succeed: error %v", err) } } for extraHost, expectedError := range invalid { if _, err := ValidateExtraHost(extraHost); err == nil { t.Fatalf("ValidateExtraHost(`%q`) should have failed validation", extraHost) } else { if !strings.Contains(err.Error(), expectedError) { t.Fatalf("ValidateExtraHost(`%q`) error should contain %q", extraHost, expectedError) } } } } func TestValidateAttach(t *testing.T) { valid := []string{ "stdin", "stdout", "stderr", "STDIN", "STDOUT", "STDERR", } if _, err := ValidateAttach("invalid"); err == nil { t.Fatalf("Expected error with [valid streams are STDIN, STDOUT and STDERR], got nothing") } for _, attach := range valid { value, err := ValidateAttach(attach) if err != nil { t.Fatal(err) } if value != strings.ToLower(attach) { t.Fatalf("Expected [%v], got [%v]", attach, value) } } } func TestValidateEnv(t *testing.T) { valids := map[string]string{ "a": "a", "something": "something", "_=a": "_=a", "env1=value1": "env1=value1", "_env1=value1": "_env1=value1", "env2=value2=value3": "env2=value2=value3", "env3=abc!qwe": "env3=abc!qwe", "env_4=value 4": "env_4=value 4", "PATH": fmt.Sprintf("PATH=%v", os.Getenv("PATH")), "PATH=something": "PATH=something", "asd!qwe": "asd!qwe", "1asd": "1asd", "123": "123", "some space": "some space", " some space before": " some space before", "some space after ": "some space after ", } for value, expected := range valids { actual, err := ValidateEnv(value) if err != nil { t.Fatal(err) } if actual != expected { t.Fatalf("Expected [%v], got [%v]", expected, actual) } } } func TestValidateLabel(t *testing.T) { if _, err := ValidateLabel("label"); err == nil || err.Error() != "bad attribute format: label" { t.Fatalf("Expected an error [bad attribute format: label], go %v", err) } if actual, err := ValidateLabel("key1=value1"); err != nil || actual != "key1=value1" { t.Fatalf("Expected [key1=value1], got [%v,%v]", actual, err) } // Validate it's working with more than one = if actual, err := ValidateLabel("key1=value1=value2"); err != nil { t.Fatalf("Expected [key1=value1=value2], got [%v,%v]", actual, err) } // Validate it's working with one more if actual, err := ValidateLabel("key1=value1=value2=value3"); err != nil { t.Fatalf("Expected [key1=value1=value2=value2], got [%v,%v]", actual, err) } } func logOptsValidator(val string) (string, error) { allowedKeys := map[string]string{"max-size": "1", "max-file": "2"} vals := strings.Split(val, "=") if allowedKeys[vals[0]] != "" { return val, nil } return "", fmt.Errorf("invalid key %s", vals[0]) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_unix.go ================================================ // +build !windows package opts // DefaultHTTPHost Default HTTP Host used if only port is provided to -H flag e.g. docker daemon -H tcp://:8080 const DefaultHTTPHost = "localhost" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/opts/opts_windows.go ================================================ package opts // TODO Windows. Identify bug in GOLang 1.5.1 and/or Windows Server 2016 TP4. // @jhowardmsft, @swernli. // // On Windows, this mitigates a problem with the default options of running // a docker client against a local docker daemon on TP4. // // 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 TP4. 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 TP4 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 in TP4 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. docker daemon -H tcp://:8080 const DefaultHTTPHost = "127.0.0.1" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/README.md ================================================ This code provides helper functions for dealing with archive files. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive.go ================================================ package archive import ( "archive/tar" "bufio" "bytes" "compress/bzip2" "compress/gzip" "errors" "fmt" "io" "io/ioutil" "os" "os/exec" "path/filepath" "runtime" "strings" "syscall" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) type ( // Archive is a type of io.ReadCloser which has two interfaces Read and Closer. Archive io.ReadCloser // Reader is a type of io.Reader. Reader io.Reader // Compression is the state represents if compressed or not. Compression int // TarChownOptions wraps the chown options UID and GID. TarChownOptions struct { UID, GID int } // TarOptions wraps the tar options. TarOptions struct { IncludeFiles []string ExcludePatterns []string Compression Compression NoLchown bool UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap ChownOpts *TarChownOptions IncludeSourceDir bool // When unpacking, specifies whether overwriting a directory with a // non-directory is allowed and vice versa. NoOverwriteDirNonDir bool // For each include when creating an archive, the included name will be // replaced with the matching name from this map. RebaseNames map[string]string } // Archiver allows the reuse of most utility functions of this package // with a pluggable Untar function. Also, to facilitate the passing of // specific id mappings for untar, an archiver can be created with maps // which will then be passed to Untar operations Archiver struct { Untar func(io.Reader, string, *TarOptions) error UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap } // breakoutError is used to differentiate errors related to breaking out // When testing archive breakout in the unit tests, this error is expected // in order for the test to pass. breakoutError error ) var ( // ErrNotImplemented is the error message of function not implemented. ErrNotImplemented = errors.New("Function not implemented") defaultArchiver = &Archiver{Untar: Untar, UIDMaps: nil, GIDMaps: nil} ) const ( // HeaderSize is the size in bytes of a tar header HeaderSize = 512 ) const ( // Uncompressed represents the uncompressed. Uncompressed Compression = iota // Bzip2 is bzip2 compression algorithm. Bzip2 // Gzip is gzip compression algorithm. Gzip // Xz is xz compression algorithm. Xz ) // IsArchive checks for the magic bytes of a tar or any supported compression // algorithm. func IsArchive(header []byte) bool { compression := DetectCompression(header) if compression != Uncompressed { return true } r := tar.NewReader(bytes.NewBuffer(header)) _, err := r.Next() return err == nil } // IsArchivePath checks if the (possibly compressed) file at the given path // starts with a tar file header. func IsArchivePath(path string) bool { file, err := os.Open(path) if err != nil { return false } defer file.Close() rdr, err := DecompressStream(file) if err != nil { return false } r := tar.NewReader(rdr) _, err = r.Next() return err == nil } // DetectCompression detects the compression algorithm of the source. func DetectCompression(source []byte) Compression { for compression, m := range map[Compression][]byte{ Bzip2: {0x42, 0x5A, 0x68}, Gzip: {0x1F, 0x8B, 0x08}, Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, } { if len(source) < len(m) { logrus.Debugf("Len too short") continue } if bytes.Compare(m, source[:len(m)]) == 0 { return compression } } return Uncompressed } func xzDecompress(archive io.Reader) (io.ReadCloser, <-chan struct{}, error) { args := []string{"xz", "-d", "-c", "-q"} return cmdStream(exec.Command(args[0], args[1:]...), archive) } // DecompressStream decompress the archive and returns a ReaderCloser with the decompressed archive. func DecompressStream(archive io.Reader) (io.ReadCloser, error) { p := pools.BufioReader32KPool buf := p.Get(archive) bs, err := buf.Peek(10) if err != nil && err != io.EOF { // Note: we'll ignore any io.EOF error because there are some odd // cases where the layer.tar file will be empty (zero bytes) and // that results in an io.EOF from the Peek() call. So, in those // cases we'll just treat it as a non-compressed stream and // that means just create an empty layer. // See Issue 18170 return nil, err } compression := DetectCompression(bs) switch compression { case Uncompressed: readBufWrapper := p.NewReadCloserWrapper(buf, buf) return readBufWrapper, nil case Gzip: gzReader, err := gzip.NewReader(buf) if err != nil { return nil, err } readBufWrapper := p.NewReadCloserWrapper(buf, gzReader) return readBufWrapper, nil case Bzip2: bz2Reader := bzip2.NewReader(buf) readBufWrapper := p.NewReadCloserWrapper(buf, bz2Reader) return readBufWrapper, nil case Xz: xzReader, chdone, err := xzDecompress(buf) if err != nil { return nil, err } readBufWrapper := p.NewReadCloserWrapper(buf, xzReader) return ioutils.NewReadCloserWrapper(readBufWrapper, func() error { <-chdone return readBufWrapper.Close() }), nil default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } // CompressStream compresses the dest with specified compression algorithm. func CompressStream(dest io.WriteCloser, compression Compression) (io.WriteCloser, error) { p := pools.BufioWriter32KPool buf := p.Get(dest) switch compression { case Uncompressed: writeBufWrapper := p.NewWriteCloserWrapper(buf, buf) return writeBufWrapper, nil case Gzip: gzWriter := gzip.NewWriter(dest) writeBufWrapper := p.NewWriteCloserWrapper(buf, gzWriter) return writeBufWrapper, nil case Bzip2, Xz: // archive/bzip2 does not support writing, and there is no xz support at all // However, this is not a problem as docker only currently generates gzipped tars return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) default: return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) } } // Extension returns the extension of a file that uses the specified compression algorithm. func (compression *Compression) Extension() string { switch *compression { case Uncompressed: return "tar" case Bzip2: return "tar.bz2" case Gzip: return "tar.gz" case Xz: return "tar.xz" } return "" } type tarAppender struct { TarWriter *tar.Writer Buffer *bufio.Writer // for hardlink mapping SeenFiles map[uint64]string UIDMaps []idtools.IDMap GIDMaps []idtools.IDMap } // canonicalTarName provides a platform-independent and consistent posix-style //path for files and directories to be archived regardless of the platform. func canonicalTarName(name string, isDir bool) (string, error) { name, err := CanonicalTarNameForPath(name) if err != nil { return "", err } // suffix with '/' for directories if isDir && !strings.HasSuffix(name, "/") { name += "/" } return name, nil } func (ta *tarAppender) addTarFile(path, name string) error { fi, err := os.Lstat(path) if err != nil { return err } link := "" if fi.Mode()&os.ModeSymlink != 0 { if link, err = os.Readlink(path); err != nil { return err } } hdr, err := tar.FileInfoHeader(fi, link) if err != nil { return err } hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) name, err = canonicalTarName(name, fi.IsDir()) if err != nil { return fmt.Errorf("tar: cannot canonicalize path: %v", err) } hdr.Name = name inode, err := setHeaderForSpecialDevice(hdr, ta, name, fi.Sys()) if err != nil { return err } // if it's not a directory and has more than 1 link, // it's hardlinked, so set the type flag accordingly if !fi.IsDir() && hasHardlinks(fi) { // a link should have a name that it links too // and that linked name should be first in the tar archive if oldpath, ok := ta.SeenFiles[inode]; ok { hdr.Typeflag = tar.TypeLink hdr.Linkname = oldpath hdr.Size = 0 // This Must be here for the writer math to add up! } else { ta.SeenFiles[inode] = name } } capability, _ := system.Lgetxattr(path, "security.capability") if capability != nil { hdr.Xattrs = make(map[string]string) hdr.Xattrs["security.capability"] = string(capability) } //handle re-mapping container ID mappings back to host ID mappings before //writing tar headers/files. We skip whiteout files because they were written //by the kernel and already have proper ownership relative to the host if !strings.HasPrefix(filepath.Base(hdr.Name), WhiteoutPrefix) && (ta.UIDMaps != nil || ta.GIDMaps != nil) { uid, gid, err := getFileUIDGID(fi.Sys()) if err != nil { return err } xUID, err := idtools.ToContainer(uid, ta.UIDMaps) if err != nil { return err } xGID, err := idtools.ToContainer(gid, ta.GIDMaps) if err != nil { return err } hdr.Uid = xUID hdr.Gid = xGID } if err := ta.TarWriter.WriteHeader(hdr); err != nil { return err } if hdr.Typeflag == tar.TypeReg { file, err := os.Open(path) if err != nil { return err } ta.Buffer.Reset(ta.TarWriter) defer ta.Buffer.Reset(nil) _, err = io.Copy(ta.Buffer, file) file.Close() if err != nil { return err } err = ta.Buffer.Flush() if err != nil { return err } } return nil } func createTarFile(path, extractDir string, hdr *tar.Header, reader io.Reader, Lchown bool, chownOpts *TarChownOptions) error { // hdr.Mode is in linux format, which we can use for sycalls, // but for os.Foo() calls we need the mode converted to os.FileMode, // so use hdrInfo.Mode() (they differ for e.g. setuid bits) hdrInfo := hdr.FileInfo() switch hdr.Typeflag { case tar.TypeDir: // Create directory unless it exists as a directory already. // In that case we just want to merge the two if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) { if err := os.Mkdir(path, hdrInfo.Mode()); err != nil { return err } } case tar.TypeReg, tar.TypeRegA: // Source is regular file file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode()) if err != nil { return err } if _, err := io.Copy(file, reader); err != nil { file.Close() return err } file.Close() case tar.TypeBlock, tar.TypeChar, tar.TypeFifo: // Handle this is an OS-specific way if err := handleTarTypeBlockCharFifo(hdr, path); err != nil { return err } case tar.TypeLink: targetPath := filepath.Join(extractDir, hdr.Linkname) // check for hardlink breakout if !strings.HasPrefix(targetPath, extractDir) { return breakoutError(fmt.Errorf("invalid hardlink %q -> %q", targetPath, hdr.Linkname)) } if err := os.Link(targetPath, path); err != nil { return err } case tar.TypeSymlink: // path -> hdr.Linkname = targetPath // e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname) // the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because // that symlink would first have to be created, which would be caught earlier, at this very check: if !strings.HasPrefix(targetPath, extractDir) { return breakoutError(fmt.Errorf("invalid symlink %q -> %q", path, hdr.Linkname)) } if err := os.Symlink(hdr.Linkname, path); err != nil { return err } case tar.TypeXGlobalHeader: logrus.Debugf("PAX Global Extended Headers found and ignored") return nil default: return fmt.Errorf("Unhandled tar header type %d\n", hdr.Typeflag) } // Lchown is not supported on Windows. if Lchown && runtime.GOOS != "windows" { if chownOpts == nil { chownOpts = &TarChownOptions{UID: hdr.Uid, GID: hdr.Gid} } if err := os.Lchown(path, chownOpts.UID, chownOpts.GID); err != nil { return err } } for key, value := range hdr.Xattrs { if err := system.Lsetxattr(path, key, []byte(value), 0); err != nil { return err } } // There is no LChmod, so ignore mode for symlink. Also, this // must happen after chown, as that can modify the file mode if err := handleLChmod(hdr, path, hdrInfo); err != nil { return err } aTime := hdr.AccessTime if aTime.Before(hdr.ModTime) { // Last access time should never be before last modified time. aTime = hdr.ModTime } // system.Chtimes doesn't support a NOFOLLOW flag atm if hdr.Typeflag == tar.TypeLink { if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { return err } } } else if hdr.Typeflag != tar.TypeSymlink { if err := system.Chtimes(path, aTime, hdr.ModTime); err != nil { return err } } else { ts := []syscall.Timespec{timeToTimespec(aTime), timeToTimespec(hdr.ModTime)} if err := system.LUtimesNano(path, ts); err != nil && err != system.ErrNotSupportedPlatform { return err } } return nil } // Tar creates an archive from the directory at `path`, and returns it as a // stream of bytes. func Tar(path string, compression Compression) (io.ReadCloser, error) { return TarWithOptions(path, &TarOptions{Compression: compression}) } // TarWithOptions creates an archive from the directory at `path`, only including files whose relative // paths are included in `options.IncludeFiles` (if non-nil) or not in `options.ExcludePatterns`. func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error) { // Fix the source path to work with long path names. This is a no-op // on platforms other than Windows. srcPath = fixVolumePathPrefix(srcPath) patterns, patDirs, exceptions, err := fileutils.CleanPatterns(options.ExcludePatterns) if err != nil { return nil, err } pipeReader, pipeWriter := io.Pipe() compressWriter, err := CompressStream(pipeWriter, options.Compression) if err != nil { return nil, err } go func() { ta := &tarAppender{ TarWriter: tar.NewWriter(compressWriter), Buffer: pools.BufioWriter32KPool.Get(nil), SeenFiles: make(map[uint64]string), UIDMaps: options.UIDMaps, GIDMaps: options.GIDMaps, } defer func() { // Make sure to check the error on Close. if err := ta.TarWriter.Close(); err != nil { logrus.Debugf("Can't close tar writer: %s", err) } if err := compressWriter.Close(); err != nil { logrus.Debugf("Can't close compress writer: %s", err) } if err := pipeWriter.Close(); err != nil { logrus.Debugf("Can't close pipe writer: %s", err) } }() // this buffer is needed for the duration of this piped stream defer pools.BufioWriter32KPool.Put(ta.Buffer) // In general we log errors here but ignore them because // during e.g. a diff operation the container can continue // mutating the filesystem and we can see transient errors // from this stat, err := os.Lstat(srcPath) if err != nil { return } if !stat.IsDir() { // We can't later join a non-dir with any includes because the // 'walk' will error if "file/." is stat-ed and "file" is not a // directory. So, we must split the source path and use the // basename as the include. if len(options.IncludeFiles) > 0 { logrus.Warn("Tar: Can't archive a file with includes") } dir, base := SplitPathDirEntry(srcPath) srcPath = dir options.IncludeFiles = []string{base} } if len(options.IncludeFiles) == 0 { options.IncludeFiles = []string{"."} } seen := make(map[string]bool) for _, include := range options.IncludeFiles { rebaseName := options.RebaseNames[include] walkRoot := getWalkRoot(srcPath, include) filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { if err != nil { logrus.Debugf("Tar: Can't stat file %s to tar: %s", srcPath, err) return nil } relFilePath, err := filepath.Rel(srcPath, filePath) if err != nil || (!options.IncludeSourceDir && relFilePath == "." && f.IsDir()) { // Error getting relative path OR we are looking // at the source directory path. Skip in both situations. return nil } if options.IncludeSourceDir && include == "." && relFilePath != "." { relFilePath = strings.Join([]string{".", relFilePath}, string(filepath.Separator)) } skip := false // If "include" is an exact match for the current file // then even if there's an "excludePatterns" pattern that // matches it, don't skip it. IOW, assume an explicit 'include' // is asking for that file no matter what - which is true // for some files, like .dockerignore and Dockerfile (sometimes) if include != relFilePath { skip, err = fileutils.OptimizedMatches(relFilePath, patterns, patDirs) if err != nil { logrus.Debugf("Error matching %s: %v", relFilePath, err) return err } } if skip { if !exceptions && f.IsDir() { return filepath.SkipDir } return nil } if seen[relFilePath] { return nil } seen[relFilePath] = true // Rename the base resource. if rebaseName != "" { var replacement string if rebaseName != string(filepath.Separator) { // Special case the root directory to replace with an // empty string instead so that we don't end up with // double slashes in the paths. replacement = rebaseName } relFilePath = strings.Replace(relFilePath, include, replacement, 1) } if err := ta.addTarFile(filePath, relFilePath); err != nil { logrus.Debugf("Can't add file %s to tar: %s", filePath, err) } return nil }) } }() return pipeReader, nil } // Unpack unpacks the decompressedArchive to dest with options. func Unpack(decompressedArchive io.Reader, dest string, options *TarOptions) error { tr := tar.NewReader(decompressedArchive) trBuf := pools.BufioReader32KPool.Get(nil) defer pools.BufioReader32KPool.Put(trBuf) var dirs []*tar.Header remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps) if err != nil { return err } // Iterate through the files in the archive. loop: for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return err } // Normalize name, for safety and for a simple is-root check // This keeps "../" as-is, but normalizes "/../" to "/". Or Windows: // This keeps "..\" as-is, but normalizes "\..\" to "\". hdr.Name = filepath.Clean(hdr.Name) for _, exclude := range options.ExcludePatterns { if strings.HasPrefix(hdr.Name, exclude) { continue loop } } // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in // the filepath format for the OS on which the daemon is running. Hence // the check for a slash-suffix MUST be done in an OS-agnostic way. if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { // Not the root directory, ensure that the parent directory exists parent := filepath.Dir(hdr.Name) parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { err = system.MkdirAll(parentPath, 0777) if err != nil { return err } } } path := filepath.Join(dest, hdr.Name) rel, err := filepath.Rel(dest, path) if err != nil { return err } if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { return breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) } // If path exits we almost always just want to remove and replace it // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). if fi, err := os.Lstat(path); err == nil { if options.NoOverwriteDirNonDir && fi.IsDir() && hdr.Typeflag != tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing directory with a non-directory from the archive. return fmt.Errorf("cannot overwrite directory %q with non-directory %q", path, dest) } if options.NoOverwriteDirNonDir && !fi.IsDir() && hdr.Typeflag == tar.TypeDir { // If NoOverwriteDirNonDir is true then we cannot replace // an existing non-directory with a directory from the archive. return fmt.Errorf("cannot overwrite non-directory %q with directory %q", path, dest) } if fi.IsDir() && hdr.Name == "." { continue } if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { if err := os.RemoveAll(path); err != nil { return err } } } trBuf.Reset(tr) // if the options contain a uid & gid maps, convert header uid/gid // entries using the maps such that lchown sets the proper mapped // uid/gid after writing the file. We only perform this mapping if // the file isn't already owned by the remapped root UID or GID, as // that specific uid/gid has no mapping from container -> host, and // those files already have the proper ownership for inside the // container. if hdr.Uid != remappedRootUID { xUID, err := idtools.ToHost(hdr.Uid, options.UIDMaps) if err != nil { return err } hdr.Uid = xUID } if hdr.Gid != remappedRootGID { xGID, err := idtools.ToHost(hdr.Gid, options.GIDMaps) if err != nil { return err } hdr.Gid = xGID } if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown, options.ChownOpts); err != nil { return err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { dirs = append(dirs, hdr) } } for _, hdr := range dirs { path := filepath.Join(dest, hdr.Name) if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { return err } } return nil } // Untar reads a stream of bytes from `archive`, parses it as a tar archive, // and unpacks it into the directory at `dest`. // The archive may be compressed with one of the following algorithms: // identity (uncompressed), gzip, bzip2, xz. // FIXME: specify behavior when target path exists vs. doesn't exist. func Untar(tarArchive io.Reader, dest string, options *TarOptions) error { return untarHandler(tarArchive, dest, options, true) } // UntarUncompressed reads a stream of bytes from `archive`, parses it as a tar archive, // and unpacks it into the directory at `dest`. // The archive must be an uncompressed stream. func UntarUncompressed(tarArchive io.Reader, dest string, options *TarOptions) error { return untarHandler(tarArchive, dest, options, false) } // Handler for teasing out the automatic decompression func untarHandler(tarArchive io.Reader, dest string, options *TarOptions, decompress bool) error { if tarArchive == nil { return fmt.Errorf("Empty archive") } dest = filepath.Clean(dest) if options == nil { options = &TarOptions{} } if options.ExcludePatterns == nil { options.ExcludePatterns = []string{} } r := tarArchive if decompress { decompressedArchive, err := DecompressStream(tarArchive) if err != nil { return err } defer decompressedArchive.Close() r = decompressedArchive } return Unpack(r, dest, options) } // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. // If either Tar or Untar fails, TarUntar aborts and returns the error. func (archiver *Archiver) TarUntar(src, dst string) error { logrus.Debugf("TarUntar(%s %s)", src, dst) archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) if err != nil { return err } defer archive.Close() var options *TarOptions if archiver.UIDMaps != nil || archiver.GIDMaps != nil { options = &TarOptions{ UIDMaps: archiver.UIDMaps, GIDMaps: archiver.GIDMaps, } } return archiver.Untar(archive, dst, options) } // TarUntar is a convenience function which calls Tar and Untar, with the output of one piped into the other. // If either Tar or Untar fails, TarUntar aborts and returns the error. func TarUntar(src, dst string) error { return defaultArchiver.TarUntar(src, dst) } // UntarPath untar a file from path to a destination, src is the source tar file path. func (archiver *Archiver) UntarPath(src, dst string) error { archive, err := os.Open(src) if err != nil { return err } defer archive.Close() var options *TarOptions if archiver.UIDMaps != nil || archiver.GIDMaps != nil { options = &TarOptions{ UIDMaps: archiver.UIDMaps, GIDMaps: archiver.GIDMaps, } } return archiver.Untar(archive, dst, options) } // UntarPath is a convenience function which looks for an archive // at filesystem path `src`, and unpacks it at `dst`. func UntarPath(src, dst string) error { return defaultArchiver.UntarPath(src, dst) } // CopyWithTar creates a tar archive of filesystem path `src`, and // unpacks it at filesystem path `dst`. // The archive is streamed directly with fixed buffering and no // intermediary disk IO. func (archiver *Archiver) CopyWithTar(src, dst string) error { srcSt, err := os.Stat(src) if err != nil { return err } if !srcSt.IsDir() { return archiver.CopyFileWithTar(src, dst) } // Create dst, copy src's content into it logrus.Debugf("Creating dest directory: %s", dst) if err := system.MkdirAll(dst, 0755); err != nil { return err } logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) return archiver.TarUntar(src, dst) } // CopyWithTar creates a tar archive of filesystem path `src`, and // unpacks it at filesystem path `dst`. // The archive is streamed directly with fixed buffering and no // intermediary disk IO. func CopyWithTar(src, dst string) error { return defaultArchiver.CopyWithTar(src, dst) } // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) srcSt, err := os.Stat(src) if err != nil { return err } if srcSt.IsDir() { return fmt.Errorf("Can't copy a directory") } // Clean up the trailing slash. This must be done in an operating // system specific manner. if dst[len(dst)-1] == os.PathSeparator { dst = filepath.Join(dst, filepath.Base(src)) } // Create the holding directory if necessary if err := system.MkdirAll(filepath.Dir(dst), 0700); err != nil { return err } r, w := io.Pipe() errC := promise.Go(func() error { defer w.Close() srcF, err := os.Open(src) if err != nil { return err } defer srcF.Close() hdr, err := tar.FileInfoHeader(srcSt, "") if err != nil { return err } hdr.Name = filepath.Base(dst) hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode))) remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(archiver.UIDMaps, archiver.GIDMaps) if err != nil { return err } // only perform mapping if the file being copied isn't already owned by the // uid or gid of the remapped root in the container if remappedRootUID != hdr.Uid { xUID, err := idtools.ToHost(hdr.Uid, archiver.UIDMaps) if err != nil { return err } hdr.Uid = xUID } if remappedRootGID != hdr.Gid { xGID, err := idtools.ToHost(hdr.Gid, archiver.GIDMaps) if err != nil { return err } hdr.Gid = xGID } tw := tar.NewWriter(w) defer tw.Close() if err := tw.WriteHeader(hdr); err != nil { return err } if _, err := io.Copy(tw, srcF); err != nil { return err } return nil }) defer func() { if er := <-errC; err != nil { err = er } }() err = archiver.Untar(r, filepath.Dir(dst), nil) if err != nil { r.CloseWithError(err) } return err } // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. // // Destination handling is in an operating specific manner depending // where the daemon is running. If `dst` ends with a trailing slash // the final destination path will be `dst/base(src)` (Linux) or // `dst\base(src)` (Windows). func CopyFileWithTar(src, dst string) (err error) { return defaultArchiver.CopyFileWithTar(src, dst) } // cmdStream executes a command, and returns its stdout as a stream. // If the command fails to run or doesn't complete successfully, an error // will be returned, including anything written on stderr. func cmdStream(cmd *exec.Cmd, input io.Reader) (io.ReadCloser, <-chan struct{}, error) { chdone := make(chan struct{}) cmd.Stdin = input pipeR, pipeW := io.Pipe() cmd.Stdout = pipeW var errBuf bytes.Buffer cmd.Stderr = &errBuf // Run the command and return the pipe if err := cmd.Start(); err != nil { return nil, nil, err } // Copy stdout to the returned pipe go func() { if err := cmd.Wait(); err != nil { pipeW.CloseWithError(fmt.Errorf("%s: %s", err, errBuf.String())) } else { pipeW.Close() } close(chdone) }() return pipeR, chdone, nil } // NewTempArchive reads the content of src into a temporary file, and returns the contents // of that file as an archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. func NewTempArchive(src Archive, dir string) (*TempArchive, error) { f, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } if _, err := io.Copy(f, src); err != nil { return nil, err } if _, err := f.Seek(0, 0); err != nil { return nil, err } st, err := f.Stat() if err != nil { return nil, err } size := st.Size() return &TempArchive{File: f, Size: size}, nil } // TempArchive is a temporary archive. The archive can only be read once - as soon as reading completes, // the file will be deleted. type TempArchive struct { *os.File Size int64 // Pre-computed from Stat().Size() as a convenience read int64 closed bool } // Close closes the underlying file if it's still open, or does a no-op // to allow callers to try to close the TempArchive multiple times safely. func (archive *TempArchive) Close() error { if archive.closed { return nil } archive.closed = true return archive.File.Close() } func (archive *TempArchive) Read(data []byte) (int, error) { n, err := archive.File.Read(data) archive.read += int64(n) if err != nil || archive.read == archive.Size { archive.Close() os.Remove(archive.File.Name()) } return n, err } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_test.go ================================================ package archive import ( "archive/tar" "bytes" "fmt" "io" "io/ioutil" "os" "os/exec" "path" "path/filepath" "strings" "syscall" "testing" "time" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) func TestIsArchiveNilHeader(t *testing.T) { out := IsArchive(nil) if out { t.Fatalf("isArchive should return false as nil is not a valid archive header") } } func TestIsArchiveInvalidHeader(t *testing.T) { header := []byte{0x00, 0x01, 0x02} out := IsArchive(header) if out { t.Fatalf("isArchive should return false as %s is not a valid archive header", header) } } func TestIsArchiveBzip2(t *testing.T) { header := []byte{0x42, 0x5A, 0x68} out := IsArchive(header) if !out { t.Fatalf("isArchive should return true as %s is a bz2 header", header) } } func TestIsArchive7zip(t *testing.T) { header := []byte{0x50, 0x4b, 0x03, 0x04} out := IsArchive(header) if out { t.Fatalf("isArchive should return false as %s is a 7z header and it is not supported", header) } } func TestIsArchivePathDir(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "mkdir -p /tmp/archivedir") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } if IsArchivePath("/tmp/archivedir") { t.Fatalf("Incorrectly recognised directory as an archive") } } func TestIsArchivePathInvalidFile(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1K count=1 of=/tmp/archive && gzip --stdout /tmp/archive > /tmp/archive.gz") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } if IsArchivePath("/tmp/archive") { t.Fatalf("Incorrectly recognised invalid tar path as archive") } if IsArchivePath("/tmp/archive.gz") { t.Fatalf("Incorrectly recognised invalid compressed tar path as archive") } } func TestIsArchivePathTar(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archivedata && tar -cf /tmp/archive /tmp/archivedata && gzip --stdout /tmp/archive > /tmp/archive.gz") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } if !IsArchivePath("/tmp/archive") { t.Fatalf("Did not recognise valid tar path as archive") } if !IsArchivePath("/tmp/archive.gz") { t.Fatalf("Did not recognise valid compressed tar path as archive") } } func TestDecompressStreamGzip(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && gzip -f /tmp/archive") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } archive, err := os.Open("/tmp/archive.gz") _, err = DecompressStream(archive) if err != nil { t.Fatalf("Failed to decompress a gzip file.") } } func TestDecompressStreamBzip2(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && bzip2 -f /tmp/archive") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } archive, err := os.Open("/tmp/archive.bz2") _, err = DecompressStream(archive) if err != nil { t.Fatalf("Failed to decompress a bzip2 file.") } } func TestDecompressStreamXz(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "touch /tmp/archive && xz -f /tmp/archive") output, err := cmd.CombinedOutput() if err != nil { t.Fatalf("Fail to create an archive file for test : %s.", output) } archive, err := os.Open("/tmp/archive.xz") _, err = DecompressStream(archive) if err != nil { t.Fatalf("Failed to decompress a xz file.") } } func TestCompressStreamXzUnsuported(t *testing.T) { dest, err := os.Create("/tmp/dest") if err != nil { t.Fatalf("Fail to create the destination file") } _, err = CompressStream(dest, Xz) if err == nil { t.Fatalf("Should fail as xz is unsupported for compression format.") } } func TestCompressStreamBzip2Unsupported(t *testing.T) { dest, err := os.Create("/tmp/dest") if err != nil { t.Fatalf("Fail to create the destination file") } _, err = CompressStream(dest, Xz) if err == nil { t.Fatalf("Should fail as xz is unsupported for compression format.") } } func TestCompressStreamInvalid(t *testing.T) { dest, err := os.Create("/tmp/dest") if err != nil { t.Fatalf("Fail to create the destination file") } _, err = CompressStream(dest, -1) if err == nil { t.Fatalf("Should fail as xz is unsupported for compression format.") } } func TestExtensionInvalid(t *testing.T) { compression := Compression(-1) output := compression.Extension() if output != "" { t.Fatalf("The extension of an invalid compression should be an empty string.") } } func TestExtensionUncompressed(t *testing.T) { compression := Uncompressed output := compression.Extension() if output != "tar" { t.Fatalf("The extension of a uncompressed archive should be 'tar'.") } } func TestExtensionBzip2(t *testing.T) { compression := Bzip2 output := compression.Extension() if output != "tar.bz2" { t.Fatalf("The extension of a bzip2 archive should be 'tar.bz2'") } } func TestExtensionGzip(t *testing.T) { compression := Gzip output := compression.Extension() if output != "tar.gz" { t.Fatalf("The extension of a bzip2 archive should be 'tar.gz'") } } func TestExtensionXz(t *testing.T) { compression := Xz output := compression.Extension() if output != "tar.xz" { t.Fatalf("The extension of a bzip2 archive should be 'tar.xz'") } } func TestCmdStreamLargeStderr(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "dd if=/dev/zero bs=1k count=1000 of=/dev/stderr; echo hello") out, _, err := cmdStream(cmd, nil) if err != nil { t.Fatalf("Failed to start command: %s", err) } errCh := make(chan error) go func() { _, err := io.Copy(ioutil.Discard, out) errCh <- err }() select { case err := <-errCh: if err != nil { t.Fatalf("Command should not have failed (err=%.100s...)", err) } case <-time.After(5 * time.Second): t.Fatalf("Command did not complete in 5 seconds; probable deadlock") } } func TestCmdStreamBad(t *testing.T) { badCmd := exec.Command("/bin/sh", "-c", "echo hello; echo >&2 error couldn\\'t reverse the phase pulser; exit 1") out, _, err := cmdStream(badCmd, nil) if err != nil { t.Fatalf("Failed to start command: %s", err) } if output, err := ioutil.ReadAll(out); err == nil { t.Fatalf("Command should have failed") } else if err.Error() != "exit status 1: error couldn't reverse the phase pulser\n" { t.Fatalf("Wrong error value (%s)", err) } else if s := string(output); s != "hello\n" { t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) } } func TestCmdStreamGood(t *testing.T) { cmd := exec.Command("/bin/sh", "-c", "echo hello; exit 0") out, _, err := cmdStream(cmd, nil) if err != nil { t.Fatal(err) } if output, err := ioutil.ReadAll(out); err != nil { t.Fatalf("Command should not have failed (err=%s)", err) } else if s := string(output); s != "hello\n" { t.Fatalf("Command output should be '%s', not '%s'", "hello\\n", output) } } func TestUntarPathWithInvalidDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) invalidDestFolder := path.Join(tempFolder, "invalidDest") // Create a src file srcFile := path.Join(tempFolder, "src") tarFile := path.Join(tempFolder, "src.tar") os.Create(srcFile) os.Create(invalidDestFolder) // being a file (not dir) should cause an error cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } err = UntarPath(tarFile, invalidDestFolder) if err == nil { t.Fatalf("UntarPath with invalid destination path should throw an error.") } } func TestUntarPathWithInvalidSrc(t *testing.T) { dest, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatalf("Fail to create the destination file") } defer os.RemoveAll(dest) err = UntarPath("/invalid/path", dest) if err == nil { t.Fatalf("UntarPath with invalid src path should throw an error.") } } func TestUntarPath(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := path.Join(tmpFolder, "src") tarFile := path.Join(tmpFolder, "src.tar") os.Create(path.Join(tmpFolder, "src")) cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFolder := path.Join(tmpFolder, "dest") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatalf("Fail to create the destination file") } err = UntarPath(tarFile, destFolder) if err != nil { t.Fatalf("UntarPath shouldn't throw an error, %s.", err) } expectedFile := path.Join(destFolder, srcFile) _, err = os.Stat(expectedFile) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } } // Do the same test as above but with the destination as file, it should fail func TestUntarPathWithDestinationFile(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := path.Join(tmpFolder, "src") tarFile := path.Join(tmpFolder, "src.tar") os.Create(path.Join(tmpFolder, "src")) cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFile := path.Join(tmpFolder, "dest") _, err = os.Create(destFile) if err != nil { t.Fatalf("Fail to create the destination file") } err = UntarPath(tarFile, destFile) if err == nil { t.Fatalf("UntarPath should throw an error if the destination if a file") } } // Do the same test as above but with the destination folder already exists // and the destination file is a directory // It's working, see https://github.com/docker/docker/issues/10040 func TestUntarPathWithDestinationSrcFileAsFolder(t *testing.T) { tmpFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) srcFile := path.Join(tmpFolder, "src") tarFile := path.Join(tmpFolder, "src.tar") os.Create(srcFile) cmd := exec.Command("/bin/sh", "-c", "tar cf "+tarFile+" "+srcFile) _, err = cmd.CombinedOutput() if err != nil { t.Fatal(err) } destFolder := path.Join(tmpFolder, "dest") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatalf("Fail to create the destination folder") } // Let's create a folder that will has the same path as the extracted file (from tar) destSrcFileAsFolder := path.Join(destFolder, srcFile) err = os.MkdirAll(destSrcFileAsFolder, 0740) if err != nil { t.Fatal(err) } err = UntarPath(tarFile, destFolder) if err != nil { t.Fatalf("UntarPath should throw not throw an error if the extracted file already exists and is a folder") } } func TestCopyWithTarInvalidSrc(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(nil) } destFolder := path.Join(tempFolder, "dest") invalidSrc := path.Join(tempFolder, "doesnotexists") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatal(err) } err = CopyWithTar(invalidSrc, destFolder) if err == nil { t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") } } func TestCopyWithTarInexistentDestWillCreateIt(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(nil) } srcFolder := path.Join(tempFolder, "src") inexistentDestFolder := path.Join(tempFolder, "doesnotexists") err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = CopyWithTar(srcFolder, inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") } _, err = os.Stat(inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder should create it.") } } // Test CopyWithTar with a file as src func TestCopyWithTarSrcFile(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") srcFolder := path.Join(folder, "src") src := path.Join(folder, path.Join("src", "src")) err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(src, []byte("content"), 0777) err = CopyWithTar(src, dest) if err != nil { t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) // FIXME Check the content if err != nil { t.Fatalf("Destination file should be the same as the source.") } } // Test CopyWithTar with a folder as src func TestCopyWithTarSrcFolder(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") src := path.Join(folder, path.Join("src", "folder")) err = os.MkdirAll(src, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(path.Join(src, "file"), []byte("content"), 0777) err = CopyWithTar(src, dest) if err != nil { t.Fatalf("archiver.CopyWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) // FIXME Check the content (the file inside) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } } func TestCopyFileWithTarInvalidSrc(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) destFolder := path.Join(tempFolder, "dest") err = os.MkdirAll(destFolder, 0740) if err != nil { t.Fatal(err) } invalidFile := path.Join(tempFolder, "doesnotexists") err = CopyFileWithTar(invalidFile, destFolder) if err == nil { t.Fatalf("archiver.CopyWithTar with invalid src path should throw an error.") } } func TestCopyFileWithTarInexistentDestWillCreateIt(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(nil) } defer os.RemoveAll(tempFolder) srcFile := path.Join(tempFolder, "src") inexistentDestFolder := path.Join(tempFolder, "doesnotexists") _, err = os.Create(srcFile) if err != nil { t.Fatal(err) } err = CopyFileWithTar(srcFile, inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder shouldn't fail.") } _, err = os.Stat(inexistentDestFolder) if err != nil { t.Fatalf("CopyWithTar with an inexistent folder should create it.") } // FIXME Test the src file and content } func TestCopyFileWithTarSrcFolder(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-copyfilewithtar-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") src := path.Join(folder, "srcfolder") err = os.MkdirAll(src, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } err = CopyFileWithTar(src, dest) if err == nil { t.Fatalf("CopyFileWithTar should throw an error with a folder.") } } func TestCopyFileWithTarSrcFile(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := path.Join(folder, "dest") srcFolder := path.Join(folder, "src") src := path.Join(folder, path.Join("src", "src")) err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } err = os.MkdirAll(dest, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(src, []byte("content"), 0777) err = CopyWithTar(src, dest+"/") if err != nil { t.Fatalf("archiver.CopyFileWithTar shouldn't throw an error, %s.", err) } _, err = os.Stat(dest) if err != nil { t.Fatalf("Destination folder should contain the source file but did not.") } } func TestTarFiles(t *testing.T) { // try without hardlinks if err := checkNoChanges(1000, false); err != nil { t.Fatal(err) } // try with hardlinks if err := checkNoChanges(1000, true); err != nil { t.Fatal(err) } } func checkNoChanges(fileNum int, hardlinks bool) error { srcDir, err := ioutil.TempDir("", "docker-test-srcDir") if err != nil { return err } defer os.RemoveAll(srcDir) destDir, err := ioutil.TempDir("", "docker-test-destDir") if err != nil { return err } defer os.RemoveAll(destDir) _, err = prepareUntarSourceDirectory(fileNum, srcDir, hardlinks) if err != nil { return err } err = TarUntar(srcDir, destDir) if err != nil { return err } changes, err := ChangesDirs(destDir, srcDir) if err != nil { return err } if len(changes) > 0 { return fmt.Errorf("with %d files and %v hardlinks: expected 0 changes, got %d", fileNum, hardlinks, len(changes)) } return nil } func tarUntar(t *testing.T, origin string, options *TarOptions) ([]Change, error) { archive, err := TarWithOptions(origin, options) if err != nil { t.Fatal(err) } defer archive.Close() buf := make([]byte, 10) if _, err := archive.Read(buf); err != nil { return nil, err } wrap := io.MultiReader(bytes.NewReader(buf), archive) detectedCompression := DetectCompression(buf) compression := options.Compression if detectedCompression.Extension() != compression.Extension() { return nil, fmt.Errorf("Wrong compression detected. Actual compression: %s, found %s", compression.Extension(), detectedCompression.Extension()) } tmp, err := ioutil.TempDir("", "docker-test-untar") if err != nil { return nil, err } defer os.RemoveAll(tmp) if err := Untar(wrap, tmp, nil); err != nil { return nil, err } if _, err := os.Stat(tmp); err != nil { return nil, err } return ChangesDirs(origin, tmp) } func TestTarUntar(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { t.Fatal(err) } for _, c := range []Compression{ Uncompressed, Gzip, } { changes, err := tarUntar(t, origin, &TarOptions{ Compression: c, ExcludePatterns: []string{"3"}, }) if err != nil { t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) } if len(changes) != 1 || changes[0].Path != "/3" { t.Fatalf("Unexpected differences after tarUntar: %v", changes) } } } func TestTarUntarWithXattr(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil { t.Fatal(err) } if err := system.Lsetxattr(path.Join(origin, "2"), "security.capability", []byte{0x00}, 0); err != nil { t.Fatal(err) } for _, c := range []Compression{ Uncompressed, Gzip, } { changes, err := tarUntar(t, origin, &TarOptions{ Compression: c, ExcludePatterns: []string{"3"}, }) if err != nil { t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err) } if len(changes) != 1 || changes[0].Path != "/3" { t.Fatalf("Unexpected differences after tarUntar: %v", changes) } capability, _ := system.Lgetxattr(path.Join(origin, "2"), "security.capability") if capability == nil && capability[0] != 0x00 { t.Fatalf("Untar should have kept the 'security.capability' xattr.") } } } func TestTarWithOptions(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { t.Fatal(err) } if _, err := ioutil.TempDir(origin, "folder"); err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil { t.Fatal(err) } cases := []struct { opts *TarOptions numChanges int }{ {&TarOptions{IncludeFiles: []string{"1"}}, 2}, {&TarOptions{ExcludePatterns: []string{"2"}}, 1}, {&TarOptions{ExcludePatterns: []string{"1", "folder*"}}, 2}, {&TarOptions{IncludeFiles: []string{"1", "1"}}, 2}, {&TarOptions{IncludeFiles: []string{"1"}, RebaseNames: map[string]string{"1": "test"}}, 4}, } for _, testCase := range cases { changes, err := tarUntar(t, origin, testCase.opts) if err != nil { t.Fatalf("Error tar/untar when testing inclusion/exclusion: %s", err) } if len(changes) != testCase.numChanges { t.Errorf("Expected %d changes, got %d for %+v:", testCase.numChanges, len(changes), testCase.opts) } } } // Some tar archives such as http://haproxy.1wt.eu/download/1.5/src/devel/haproxy-1.5-dev21.tar.gz // use PAX Global Extended Headers. // Failing prevents the archives from being uncompressed during ADD func TestTypeXGlobalHeaderDoesNotFail(t *testing.T) { hdr := tar.Header{Typeflag: tar.TypeXGlobalHeader} tmpDir, err := ioutil.TempDir("", "docker-test-archive-pax-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpDir) err = createTarFile(filepath.Join(tmpDir, "pax_global_header"), tmpDir, &hdr, nil, true, nil) if err != nil { t.Fatal(err) } } // Some tar have both GNU specific (huge uid) and Ustar specific (long name) things. // Not supposed to happen (should use PAX instead of Ustar for long name) but it does and it should still work. func TestUntarUstarGnuConflict(t *testing.T) { f, err := os.Open("testdata/broken.tar") if err != nil { t.Fatal(err) } found := false tr := tar.NewReader(f) // Iterate through the files in the archive. for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { t.Fatal(err) } if hdr.Name == "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm" { found = true break } } if !found { t.Fatalf("%s not found in the archive", "root/.cpanm/work/1395823785.24209/Plack-1.0030/blib/man3/Plack::Middleware::LighttpdScriptNameFix.3pm") } } func TestTarWithBlockCharFifo(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := system.Mknod(path.Join(origin, "2"), syscall.S_IFBLK, int(system.Mkdev(int64(12), int64(5)))); err != nil { t.Fatal(err) } if err := system.Mknod(path.Join(origin, "3"), syscall.S_IFCHR, int(system.Mkdev(int64(12), int64(5)))); err != nil { t.Fatal(err) } if err := system.Mknod(path.Join(origin, "4"), syscall.S_IFIFO, int(system.Mkdev(int64(12), int64(5)))); err != nil { t.Fatal(err) } dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") if err != nil { t.Fatal(err) } defer os.RemoveAll(dest) // we'll do this in two steps to separate failure fh, err := Tar(origin, Uncompressed) if err != nil { t.Fatal(err) } // ensure we can read the whole thing with no error, before writing back out buf, err := ioutil.ReadAll(fh) if err != nil { t.Fatal(err) } bRdr := bytes.NewReader(buf) err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) if err != nil { t.Fatal(err) } changes, err := ChangesDirs(origin, dest) if err != nil { t.Fatal(err) } if len(changes) > 0 { t.Fatalf("Tar with special device (block, char, fifo) should keep them (recreate them when untar) : %v", changes) } } func TestTarWithHardLink(t *testing.T) { origin, err := ioutil.TempDir("", "docker-test-tar-hardlink") if err != nil { t.Fatal(err) } defer os.RemoveAll(origin) if err := ioutil.WriteFile(path.Join(origin, "1"), []byte("hello world"), 0700); err != nil { t.Fatal(err) } if err := os.Link(path.Join(origin, "1"), path.Join(origin, "2")); err != nil { t.Fatal(err) } var i1, i2 uint64 if i1, err = getNlink(path.Join(origin, "1")); err != nil { t.Fatal(err) } // sanity check that we can hardlink if i1 != 2 { t.Skipf("skipping since hardlinks don't work here; expected 2 links, got %d", i1) } dest, err := ioutil.TempDir("", "docker-test-tar-hardlink-dest") if err != nil { t.Fatal(err) } defer os.RemoveAll(dest) // we'll do this in two steps to separate failure fh, err := Tar(origin, Uncompressed) if err != nil { t.Fatal(err) } // ensure we can read the whole thing with no error, before writing back out buf, err := ioutil.ReadAll(fh) if err != nil { t.Fatal(err) } bRdr := bytes.NewReader(buf) err = Untar(bRdr, dest, &TarOptions{Compression: Uncompressed}) if err != nil { t.Fatal(err) } if i1, err = getInode(path.Join(dest, "1")); err != nil { t.Fatal(err) } if i2, err = getInode(path.Join(dest, "2")); err != nil { t.Fatal(err) } if i1 != i2 { t.Errorf("expected matching inodes, but got %d and %d", i1, i2) } } func getNlink(path string) (uint64, error) { stat, err := os.Stat(path) if err != nil { return 0, err } statT, ok := stat.Sys().(*syscall.Stat_t) if !ok { return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) } // We need this conversion on ARM64 return uint64(statT.Nlink), nil } func getInode(path string) (uint64, error) { stat, err := os.Stat(path) if err != nil { return 0, err } statT, ok := stat.Sys().(*syscall.Stat_t) if !ok { return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) } return statT.Ino, nil } func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { return 0, err } if makeLinks { if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { return 0, err } } } totalSize := numberOfFiles * len(fileData) return totalSize, nil } func BenchmarkTarUntar(b *testing.B) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { b.Fatal(err) } tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") if err != nil { b.Fatal(err) } target := path.Join(tempDir, "dest") n, err := prepareUntarSourceDirectory(100, origin, false) if err != nil { b.Fatal(err) } defer os.RemoveAll(origin) defer os.RemoveAll(tempDir) b.ResetTimer() b.SetBytes(int64(n)) for n := 0; n < b.N; n++ { err := TarUntar(origin, target) if err != nil { b.Fatal(err) } os.RemoveAll(target) } } func BenchmarkTarUntarWithLinks(b *testing.B) { origin, err := ioutil.TempDir("", "docker-test-untar-origin") if err != nil { b.Fatal(err) } tempDir, err := ioutil.TempDir("", "docker-test-untar-destination") if err != nil { b.Fatal(err) } target := path.Join(tempDir, "dest") n, err := prepareUntarSourceDirectory(100, origin, true) if err != nil { b.Fatal(err) } defer os.RemoveAll(origin) defer os.RemoveAll(tempDir) b.ResetTimer() b.SetBytes(int64(n)) for n := 0; n < b.N; n++ { err := TarUntar(origin, target) if err != nil { b.Fatal(err) } os.RemoveAll(target) } } func TestUntarInvalidFilenames(t *testing.T) { for i, headers := range [][]*tar.Header{ { { Name: "../victim/dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, { { // Note the leading slash Name: "/../victim/slash-dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarInvalidFilenames", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestUntarHardlinkToSymlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { { Name: "symlink1", Typeflag: tar.TypeSymlink, Linkname: "regfile", Mode: 0644, }, { Name: "symlink2", Typeflag: tar.TypeLink, Linkname: "symlink1", Mode: 0644, }, { Name: "regfile", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarHardlinkToSymlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestUntarInvalidHardlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeLink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeLink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (hardlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try reading victim/hello (hardlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try removing victim directory (hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarInvalidHardlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestUntarInvalidSymlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeSymlink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeSymlink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (symlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try reading victim/hello (symlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try removing victim directory (symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try writing to victim/newdir/newfile with a symlink in the path { // this header needs to be before the next one, or else there is an error Name: "dir/loophole", Typeflag: tar.TypeSymlink, Linkname: "../../victim", Mode: 0755, }, { Name: "dir/loophole/newdir/newfile", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("untar", "docker-TestUntarInvalidSymlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestTempArchiveCloseMultipleTimes(t *testing.T) { reader := ioutil.NopCloser(strings.NewReader("hello")) tempArchive, err := NewTempArchive(reader, "") buf := make([]byte, 10) n, err := tempArchive.Read(buf) if n != 5 { t.Fatalf("Expected to read 5 bytes. Read %d instead", n) } for i := 0; i < 3; i++ { if err = tempArchive.Close(); err != nil { t.Fatalf("i=%d. Unexpected error closing temp archive: %v", i, err) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix.go ================================================ // +build !windows package archive import ( "archive/tar" "errors" "os" "path/filepath" "syscall" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) // fixVolumePathPrefix does platform specific processing to ensure that if // the path being passed in is not in a volume path format, convert it to one. func fixVolumePathPrefix(srcPath string) string { return srcPath } // getWalkRoot calculates the root path when performing a TarWithOptions. // We use a separate function as this is platform specific. On Linux, we // can't use filepath.Join(srcPath,include) because this will clean away // a trailing "." or "/" which may be important. func getWalkRoot(srcPath string, include string) string { return srcPath + string(filepath.Separator) + include } // CanonicalTarNameForPath returns platform-specific filepath // to canonical posix-style path for tar archival. p is relative // path. func CanonicalTarNameForPath(p string) (string, error) { return p, nil // already unix-style } // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. func chmodTarEntry(perm os.FileMode) os.FileMode { return perm // noop for unix as golang APIs provide perm bits correctly } func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (inode uint64, err error) { s, ok := stat.(*syscall.Stat_t) if !ok { err = errors.New("cannot convert stat value to syscall.Stat_t") return } inode = uint64(s.Ino) // Currently go does not fill in the major/minors if s.Mode&syscall.S_IFBLK != 0 || s.Mode&syscall.S_IFCHR != 0 { hdr.Devmajor = int64(major(uint64(s.Rdev))) hdr.Devminor = int64(minor(uint64(s.Rdev))) } return } func getFileUIDGID(stat interface{}) (int, int, error) { s, ok := stat.(*syscall.Stat_t) if !ok { return -1, -1, errors.New("cannot convert stat value to syscall.Stat_t") } return int(s.Uid), int(s.Gid), nil } func major(device uint64) uint64 { return (device >> 8) & 0xfff } func minor(device uint64) uint64 { return (device & 0xff) | ((device >> 12) & 0xfff00) } // handleTarTypeBlockCharFifo is an OS-specific helper function used by // createTarFile to handle the following types of header: Block; Char; Fifo func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { mode := uint32(hdr.Mode & 07777) switch hdr.Typeflag { case tar.TypeBlock: mode |= syscall.S_IFBLK case tar.TypeChar: mode |= syscall.S_IFCHR case tar.TypeFifo: mode |= syscall.S_IFIFO } if err := system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))); err != nil { return err } return nil } func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { if hdr.Typeflag == tar.TypeLink { if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) { if err := os.Chmod(path, hdrInfo.Mode()); err != nil { return err } } } else if hdr.Typeflag != tar.TypeSymlink { if err := os.Chmod(path, hdrInfo.Mode()); err != nil { return err } } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_unix_test.go ================================================ // +build !windows package archive import ( "os" "testing" ) func TestCanonicalTarNameForPath(t *testing.T) { cases := []struct{ in, expected string }{ {"foo", "foo"}, {"foo/bar", "foo/bar"}, {"foo/dir/", "foo/dir/"}, } for _, v := range cases { if out, err := CanonicalTarNameForPath(v.in); err != nil { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestCanonicalTarName(t *testing.T) { cases := []struct { in string isDir bool expected string }{ {"foo", false, "foo"}, {"foo", true, "foo/"}, {"foo/bar", false, "foo/bar"}, {"foo/bar", true, "foo/bar/"}, } for _, v := range cases { if out, err := canonicalTarName(v.in, v.isDir); err != nil { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestChmodTarEntry(t *testing.T) { cases := []struct { in, expected os.FileMode }{ {0000, 0000}, {0777, 0777}, {0644, 0644}, {0755, 0755}, {0444, 0444}, } for _, v := range cases { if out := chmodTarEntry(v.in); out != v.expected { t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows.go ================================================ // +build windows package archive import ( "archive/tar" "fmt" "os" "path/filepath" "strings" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath" ) // fixVolumePathPrefix does platform specific processing to ensure that if // the path being passed in is not in a volume path format, convert it to one. func fixVolumePathPrefix(srcPath string) string { return longpath.AddPrefix(srcPath) } // getWalkRoot calculates the root path when performing a TarWithOptions. // We use a separate function as this is platform specific. func getWalkRoot(srcPath string, include string) string { return filepath.Join(srcPath, include) } // CanonicalTarNameForPath returns platform-specific filepath // to canonical posix-style path for tar archival. p is relative // path. func CanonicalTarNameForPath(p string) (string, error) { // windows: convert windows style relative path with backslashes // into forward slashes. Since windows does not allow '/' or '\' // in file names, it is mostly safe to replace however we must // check just in case if strings.Contains(p, "/") { return "", fmt.Errorf("Windows path contains forward slash: %s", p) } return strings.Replace(p, string(os.PathSeparator), "/", -1), nil } // chmodTarEntry is used to adjust the file permissions used in tar header based // on the platform the archival is done. func chmodTarEntry(perm os.FileMode) os.FileMode { perm &= 0755 // Add the x bit: make everything +x from windows perm |= 0111 return perm } func setHeaderForSpecialDevice(hdr *tar.Header, ta *tarAppender, name string, stat interface{}) (inode uint64, err error) { // do nothing. no notion of Rdev, Inode, Nlink in stat on Windows return } // handleTarTypeBlockCharFifo is an OS-specific helper function used by // createTarFile to handle the following types of header: Block; Char; Fifo func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error { return nil } func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error { return nil } func getFileUIDGID(stat interface{}) (int, int, error) { // no notion of file ownership mapping yet on Windows return 0, 0, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/archive_windows_test.go ================================================ // +build windows package archive import ( "io/ioutil" "os" "path/filepath" "testing" ) func TestCopyFileWithInvalidDest(t *testing.T) { folder, err := ioutil.TempDir("", "docker-archive-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(folder) dest := "c:dest" srcFolder := filepath.Join(folder, "src") src := filepath.Join(folder, "src", "src") err = os.MkdirAll(srcFolder, 0740) if err != nil { t.Fatal(err) } ioutil.WriteFile(src, []byte("content"), 0777) err = CopyWithTar(src, dest) if err == nil { t.Fatalf("archiver.CopyWithTar should throw an error on invalid dest.") } } func TestCanonicalTarNameForPath(t *testing.T) { cases := []struct { in, expected string shouldFail bool }{ {"foo", "foo", false}, {"foo/bar", "___", true}, // unix-styled windows path must fail {`foo\bar`, "foo/bar", false}, } for _, v := range cases { if out, err := CanonicalTarNameForPath(v.in); err != nil && !v.shouldFail { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if v.shouldFail && err == nil { t.Fatalf("canonical path call should have failed with error. in=%s out=%s", v.in, out) } else if !v.shouldFail && out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestCanonicalTarName(t *testing.T) { cases := []struct { in string isDir bool expected string }{ {"foo", false, "foo"}, {"foo", true, "foo/"}, {`foo\bar`, false, "foo/bar"}, {`foo\bar`, true, "foo/bar/"}, } for _, v := range cases { if out, err := canonicalTarName(v.in, v.isDir); err != nil { t.Fatalf("cannot get canonical name for path: %s: %v", v.in, err) } else if out != v.expected { t.Fatalf("wrong canonical tar name. expected:%s got:%s", v.expected, out) } } } func TestChmodTarEntry(t *testing.T) { cases := []struct { in, expected os.FileMode }{ {0000, 0111}, {0777, 0755}, {0644, 0755}, {0755, 0755}, {0444, 0555}, } for _, v := range cases { if out := chmodTarEntry(v.in); out != v.expected { t.Fatalf("wrong chmod. expected:%v got:%v", v.expected, out) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes.go ================================================ package archive import ( "archive/tar" "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "sort" "strings" "syscall" "time" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) // ChangeType represents the change type. type ChangeType int const ( // ChangeModify represents the modify operation. ChangeModify = iota // ChangeAdd represents the add operation. ChangeAdd // ChangeDelete represents the delete operation. ChangeDelete ) func (c ChangeType) String() string { switch c { case ChangeModify: return "C" case ChangeAdd: return "A" case ChangeDelete: return "D" } return "" } // Change represents a change, it wraps the change type and path. // It describes changes of the files in the path respect to the // parent layers. The change could be modify, add, delete. // This is used for layer diff. type Change struct { Path string Kind ChangeType } func (change *Change) String() string { return fmt.Sprintf("%s %s", change.Kind, change.Path) } // for sort.Sort type changesByPath []Change func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path } func (c changesByPath) Len() int { return len(c) } func (c changesByPath) Swap(i, j int) { c[j], c[i] = c[i], c[j] } // Gnu tar and the go tar writer don't have sub-second mtime // precision, which is problematic when we apply changes via tar // files, we handle this by comparing for exact times, *or* same // second count and either a or b having exactly 0 nanoseconds func sameFsTime(a, b time.Time) bool { return a == b || (a.Unix() == b.Unix() && (a.Nanosecond() == 0 || b.Nanosecond() == 0)) } func sameFsTimeSpec(a, b syscall.Timespec) bool { return a.Sec == b.Sec && (a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0) } // Changes walks the path rw and determines changes for the files in the path, // with respect to the parent layers func Changes(layers []string, rw string) ([]Change, error) { var ( changes []Change changedDirs = make(map[string]struct{}) ) err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path path, err = filepath.Rel(rw, path) if err != nil { return err } // As this runs on the daemon side, file paths are OS specific. path = filepath.Join(string(os.PathSeparator), path) // Skip root if path == string(os.PathSeparator) { return nil } // Skip AUFS metadata if matched, err := filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path); err != nil || matched { return err } change := Change{ Path: path, } // Find out what kind of modification happened file := filepath.Base(path) // If there is a whiteout, then the file was removed if strings.HasPrefix(file, WhiteoutPrefix) { originalFile := file[len(WhiteoutPrefix):] change.Path = filepath.Join(filepath.Dir(path), originalFile) change.Kind = ChangeDelete } else { // Otherwise, the file was added change.Kind = ChangeAdd // ...Unless it already existed in a top layer, in which case, it's a modification for _, layer := range layers { stat, err := os.Stat(filepath.Join(layer, path)) if err != nil && !os.IsNotExist(err) { return err } if err == nil { // The file existed in the top layer, so that's a modification // However, if it's a directory, maybe it wasn't actually modified. // If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar if stat.IsDir() && f.IsDir() { if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) { // Both directories are the same, don't record the change return nil } } change.Kind = ChangeModify break } } } // If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files. // This block is here to ensure the change is recorded even if the // modify time, mode and size of the parent directory in the rw and ro layers are all equal. // Check https://github.com/docker/docker/pull/13590 for details. if f.IsDir() { changedDirs[path] = struct{}{} } if change.Kind == ChangeAdd || change.Kind == ChangeDelete { parent := filepath.Dir(path) if _, ok := changedDirs[parent]; !ok && parent != "/" { changes = append(changes, Change{Path: parent, Kind: ChangeModify}) changedDirs[parent] = struct{}{} } } // Record change changes = append(changes, change) return nil }) if err != nil && !os.IsNotExist(err) { return nil, err } return changes, nil } // FileInfo describes the information of a file. type FileInfo struct { parent *FileInfo name string stat *system.StatT children map[string]*FileInfo capability []byte added bool } // LookUp looks up the file information of a file. func (info *FileInfo) LookUp(path string) *FileInfo { // As this runs on the daemon side, file paths are OS specific. parent := info if path == string(os.PathSeparator) { return info } pathElements := strings.Split(path, string(os.PathSeparator)) for _, elem := range pathElements { if elem != "" { child := parent.children[elem] if child == nil { return nil } parent = child } } return parent } func (info *FileInfo) path() string { if info.parent == nil { // As this runs on the daemon side, file paths are OS specific. return string(os.PathSeparator) } return filepath.Join(info.parent.path(), info.name) } func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) { sizeAtEntry := len(*changes) if oldInfo == nil { // add change := Change{ Path: info.path(), Kind: ChangeAdd, } *changes = append(*changes, change) info.added = true } // We make a copy so we can modify it to detect additions // also, we only recurse on the old dir if the new info is a directory // otherwise any previous delete/change is considered recursive oldChildren := make(map[string]*FileInfo) if oldInfo != nil && info.isDir() { for k, v := range oldInfo.children { oldChildren[k] = v } } for name, newChild := range info.children { oldChild, _ := oldChildren[name] if oldChild != nil { // change? oldStat := oldChild.stat newStat := newChild.stat // Note: We can't compare inode or ctime or blocksize here, because these change // when copying a file into a container. However, that is not generally a problem // because any content change will change mtime, and any status change should // be visible when actually comparing the stat fields. The only time this // breaks down is if some code intentionally hides a change by setting // back mtime if statDifferent(oldStat, newStat) || bytes.Compare(oldChild.capability, newChild.capability) != 0 { change := Change{ Path: newChild.path(), Kind: ChangeModify, } *changes = append(*changes, change) newChild.added = true } // Remove from copy so we can detect deletions delete(oldChildren, name) } newChild.addChanges(oldChild, changes) } for _, oldChild := range oldChildren { // delete change := Change{ Path: oldChild.path(), Kind: ChangeDelete, } *changes = append(*changes, change) } // If there were changes inside this directory, we need to add it, even if the directory // itself wasn't changed. This is needed to properly save and restore filesystem permissions. // As this runs on the daemon side, file paths are OS specific. if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != string(os.PathSeparator) { change := Change{ Path: info.path(), Kind: ChangeModify, } // Let's insert the directory entry before the recently added entries located inside this dir *changes = append(*changes, change) // just to resize the slice, will be overwritten copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:]) (*changes)[sizeAtEntry] = change } } // Changes add changes to file information. func (info *FileInfo) Changes(oldInfo *FileInfo) []Change { var changes []Change info.addChanges(oldInfo, &changes) return changes } func newRootFileInfo() *FileInfo { // As this runs on the daemon side, file paths are OS specific. root := &FileInfo{ name: string(os.PathSeparator), children: make(map[string]*FileInfo), } return root } // ChangesDirs compares two directories and generates an array of Change objects describing the changes. // If oldDir is "", then all files in newDir will be Add-Changes. func ChangesDirs(newDir, oldDir string) ([]Change, error) { var ( oldRoot, newRoot *FileInfo ) if oldDir == "" { emptyDir, err := ioutil.TempDir("", "empty") if err != nil { return nil, err } defer os.Remove(emptyDir) oldDir = emptyDir } oldRoot, newRoot, err := collectFileInfoForChanges(oldDir, newDir) if err != nil { return nil, err } return newRoot.Changes(oldRoot), nil } // ChangesSize calculates the size in bytes of the provided changes, based on newDir. func ChangesSize(newDir string, changes []Change) int64 { var ( size int64 sf = make(map[uint64]struct{}) ) for _, change := range changes { if change.Kind == ChangeModify || change.Kind == ChangeAdd { file := filepath.Join(newDir, change.Path) fileInfo, err := os.Lstat(file) if err != nil { logrus.Errorf("Can not stat %q: %s", file, err) continue } if fileInfo != nil && !fileInfo.IsDir() { if hasHardlinks(fileInfo) { inode := getIno(fileInfo) if _, ok := sf[inode]; !ok { size += fileInfo.Size() sf[inode] = struct{}{} } } else { size += fileInfo.Size() } } } } return size } // ExportChanges produces an Archive from the provided changes, relative to dir. func ExportChanges(dir string, changes []Change, uidMaps, gidMaps []idtools.IDMap) (Archive, error) { reader, writer := io.Pipe() go func() { ta := &tarAppender{ TarWriter: tar.NewWriter(writer), Buffer: pools.BufioWriter32KPool.Get(nil), SeenFiles: make(map[uint64]string), UIDMaps: uidMaps, GIDMaps: gidMaps, } // this buffer is needed for the duration of this piped stream defer pools.BufioWriter32KPool.Put(ta.Buffer) sort.Sort(changesByPath(changes)) // In general we log errors here but ignore them because // during e.g. a diff operation the container can continue // mutating the filesystem and we can see transient errors // from this for _, change := range changes { if change.Kind == ChangeDelete { whiteOutDir := filepath.Dir(change.Path) whiteOutBase := filepath.Base(change.Path) whiteOut := filepath.Join(whiteOutDir, WhiteoutPrefix+whiteOutBase) timestamp := time.Now() hdr := &tar.Header{ Name: whiteOut[1:], Size: 0, ModTime: timestamp, AccessTime: timestamp, ChangeTime: timestamp, } if err := ta.TarWriter.WriteHeader(hdr); err != nil { logrus.Debugf("Can't write whiteout header: %s", err) } } else { path := filepath.Join(dir, change.Path) if err := ta.addTarFile(path, change.Path[1:]); err != nil { logrus.Debugf("Can't add file %s to tar: %s", path, err) } } } // Make sure to check the error on Close. if err := ta.TarWriter.Close(); err != nil { logrus.Debugf("Can't close layer: %s", err) } if err := writer.Close(); err != nil { logrus.Debugf("failed close Changes writer: %s", err) } }() return reader, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_linux.go ================================================ package archive import ( "bytes" "fmt" "os" "path/filepath" "sort" "syscall" "unsafe" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) // walker is used to implement collectFileInfoForChanges on linux. Where this // method in general returns the entire contents of two directory trees, we // optimize some FS calls out on linux. In particular, we take advantage of the // fact that getdents(2) returns the inode of each file in the directory being // walked, which, when walking two trees in parallel to generate a list of // changes, can be used to prune subtrees without ever having to lstat(2) them // directly. Eliminating stat calls in this way can save up to seconds on large // images. type walker struct { dir1 string dir2 string root1 *FileInfo root2 *FileInfo } // collectFileInfoForChanges returns a complete representation of the trees // rooted at dir1 and dir2, with one important exception: any subtree or // leaf where the inode and device numbers are an exact match between dir1 // and dir2 will be pruned from the results. This method is *only* to be used // to generating a list of changes between the two directories, as it does not // reflect the full contents. func collectFileInfoForChanges(dir1, dir2 string) (*FileInfo, *FileInfo, error) { w := &walker{ dir1: dir1, dir2: dir2, root1: newRootFileInfo(), root2: newRootFileInfo(), } i1, err := os.Lstat(w.dir1) if err != nil { return nil, nil, err } i2, err := os.Lstat(w.dir2) if err != nil { return nil, nil, err } if err := w.walk("/", i1, i2); err != nil { return nil, nil, err } return w.root1, w.root2, nil } // Given a FileInfo, its path info, and a reference to the root of the tree // being constructed, register this file with the tree. func walkchunk(path string, fi os.FileInfo, dir string, root *FileInfo) error { if fi == nil { return nil } parent := root.LookUp(filepath.Dir(path)) if parent == nil { return fmt.Errorf("collectFileInfoForChanges: Unexpectedly no parent for %s", path) } info := &FileInfo{ name: filepath.Base(path), children: make(map[string]*FileInfo), parent: parent, } cpath := filepath.Join(dir, path) stat, err := system.FromStatT(fi.Sys().(*syscall.Stat_t)) if err != nil { return err } info.stat = stat info.capability, _ = system.Lgetxattr(cpath, "security.capability") // lgetxattr(2): fs access parent.children[info.name] = info return nil } // Walk a subtree rooted at the same path in both trees being iterated. For // example, /docker/overlay/1234/a/b/c/d and /docker/overlay/8888/a/b/c/d func (w *walker) walk(path string, i1, i2 os.FileInfo) (err error) { // Register these nodes with the return trees, unless we're still at the // (already-created) roots: if path != "/" { if err := walkchunk(path, i1, w.dir1, w.root1); err != nil { return err } if err := walkchunk(path, i2, w.dir2, w.root2); err != nil { return err } } is1Dir := i1 != nil && i1.IsDir() is2Dir := i2 != nil && i2.IsDir() sameDevice := false if i1 != nil && i2 != nil { si1 := i1.Sys().(*syscall.Stat_t) si2 := i2.Sys().(*syscall.Stat_t) if si1.Dev == si2.Dev { sameDevice = true } } // If these files are both non-existent, or leaves (non-dirs), we are done. if !is1Dir && !is2Dir { return nil } // Fetch the names of all the files contained in both directories being walked: var names1, names2 []nameIno if is1Dir { names1, err = readdirnames(filepath.Join(w.dir1, path)) // getdents(2): fs access if err != nil { return err } } if is2Dir { names2, err = readdirnames(filepath.Join(w.dir2, path)) // getdents(2): fs access if err != nil { return err } } // We have lists of the files contained in both parallel directories, sorted // in the same order. Walk them in parallel, generating a unique merged list // of all items present in either or both directories. var names []string ix1 := 0 ix2 := 0 for { if ix1 >= len(names1) { break } if ix2 >= len(names2) { break } ni1 := names1[ix1] ni2 := names2[ix2] switch bytes.Compare([]byte(ni1.name), []byte(ni2.name)) { case -1: // ni1 < ni2 -- advance ni1 // we will not encounter ni1 in names2 names = append(names, ni1.name) ix1++ case 0: // ni1 == ni2 if ni1.ino != ni2.ino || !sameDevice { names = append(names, ni1.name) } ix1++ ix2++ case 1: // ni1 > ni2 -- advance ni2 // we will not encounter ni2 in names1 names = append(names, ni2.name) ix2++ } } for ix1 < len(names1) { names = append(names, names1[ix1].name) ix1++ } for ix2 < len(names2) { names = append(names, names2[ix2].name) ix2++ } // For each of the names present in either or both of the directories being // iterated, stat the name under each root, and recurse the pair of them: for _, name := range names { fname := filepath.Join(path, name) var cInfo1, cInfo2 os.FileInfo if is1Dir { cInfo1, err = os.Lstat(filepath.Join(w.dir1, fname)) // lstat(2): fs access if err != nil && !os.IsNotExist(err) { return err } } if is2Dir { cInfo2, err = os.Lstat(filepath.Join(w.dir2, fname)) // lstat(2): fs access if err != nil && !os.IsNotExist(err) { return err } } if err = w.walk(fname, cInfo1, cInfo2); err != nil { return err } } return nil } // {name,inode} pairs used to support the early-pruning logic of the walker type type nameIno struct { name string ino uint64 } type nameInoSlice []nameIno func (s nameInoSlice) Len() int { return len(s) } func (s nameInoSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s nameInoSlice) Less(i, j int) bool { return s[i].name < s[j].name } // readdirnames is a hacked-apart version of the Go stdlib code, exposing inode // numbers further up the stack when reading directory contents. Unlike // os.Readdirnames, which returns a list of filenames, this function returns a // list of {filename,inode} pairs. func readdirnames(dirname string) (names []nameIno, err error) { var ( size = 100 buf = make([]byte, 4096) nbuf int bufp int nb int ) f, err := os.Open(dirname) if err != nil { return nil, err } defer f.Close() names = make([]nameIno, 0, size) // Empty with room to grow. for { // Refill the buffer if necessary if bufp >= nbuf { bufp = 0 nbuf, err = syscall.ReadDirent(int(f.Fd()), buf) // getdents on linux if nbuf < 0 { nbuf = 0 } if err != nil { return nil, os.NewSyscallError("readdirent", err) } if nbuf <= 0 { break // EOF } } // Drain the buffer nb, names = parseDirent(buf[bufp:nbuf], names) bufp += nb } sl := nameInoSlice(names) sort.Sort(sl) return sl, nil } // parseDirent is a minor modification of syscall.ParseDirent (linux version) // which returns {name,inode} pairs instead of just names. func parseDirent(buf []byte, names []nameIno) (consumed int, newnames []nameIno) { origlen := len(buf) for len(buf) > 0 { dirent := (*syscall.Dirent)(unsafe.Pointer(&buf[0])) buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } names = append(names, nameIno{name, dirent.Ino}) } return origlen - len(buf), names } func clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_other.go ================================================ // +build !linux package archive import ( "fmt" "os" "path/filepath" "runtime" "strings" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) func collectFileInfoForChanges(oldDir, newDir string) (*FileInfo, *FileInfo, error) { var ( oldRoot, newRoot *FileInfo err1, err2 error errs = make(chan error, 2) ) go func() { oldRoot, err1 = collectFileInfo(oldDir) errs <- err1 }() go func() { newRoot, err2 = collectFileInfo(newDir) errs <- err2 }() // block until both routines have returned for i := 0; i < 2; i++ { if err := <-errs; err != nil { return nil, nil, err } } return oldRoot, newRoot, nil } func collectFileInfo(sourceDir string) (*FileInfo, error) { root := newRootFileInfo() err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error { if err != nil { return err } // Rebase path relPath, err := filepath.Rel(sourceDir, path) if err != nil { return err } // As this runs on the daemon side, file paths are OS specific. relPath = filepath.Join(string(os.PathSeparator), relPath) // See https://github.com/golang/go/issues/9168 - bug in filepath.Join. // Temporary workaround. If the returned path starts with two backslashes, // trim it down to a single backslash. Only relevant on Windows. if runtime.GOOS == "windows" { if strings.HasPrefix(relPath, `\\`) { relPath = relPath[1:] } } if relPath == string(os.PathSeparator) { return nil } parent := root.LookUp(filepath.Dir(relPath)) if parent == nil { return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath) } info := &FileInfo{ name: filepath.Base(relPath), children: make(map[string]*FileInfo), parent: parent, } s, err := system.Lstat(path) if err != nil { return err } info.stat = s info.capability, _ = system.Lgetxattr(path, "security.capability") parent.children[info.name] = info return nil }) if err != nil { return nil, err } return root, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_posix_test.go ================================================ package archive import ( "archive/tar" "fmt" "io" "io/ioutil" "os" "path" "sort" "testing" ) func TestHardLinkOrder(t *testing.T) { names := []string{"file1.txt", "file2.txt", "file3.txt"} msg := []byte("Hey y'all") // Create dir src, err := ioutil.TempDir("", "docker-hardlink-test-src-") if err != nil { t.Fatal(err) } //defer os.RemoveAll(src) for _, name := range names { func() { fh, err := os.Create(path.Join(src, name)) if err != nil { t.Fatal(err) } defer fh.Close() if _, err = fh.Write(msg); err != nil { t.Fatal(err) } }() } // Create dest, with changes that includes hardlinks dest, err := ioutil.TempDir("", "docker-hardlink-test-dest-") if err != nil { t.Fatal(err) } os.RemoveAll(dest) // we just want the name, at first if err := copyDir(src, dest); err != nil { t.Fatal(err) } defer os.RemoveAll(dest) for _, name := range names { for i := 0; i < 5; i++ { if err := os.Link(path.Join(dest, name), path.Join(dest, fmt.Sprintf("%s.link%d", name, i))); err != nil { t.Fatal(err) } } } // get changes changes, err := ChangesDirs(dest, src) if err != nil { t.Fatal(err) } // sort sort.Sort(changesByPath(changes)) // ExportChanges ar, err := ExportChanges(dest, changes, nil, nil) if err != nil { t.Fatal(err) } hdrs, err := walkHeaders(ar) if err != nil { t.Fatal(err) } // reverse sort sort.Sort(sort.Reverse(changesByPath(changes))) // ExportChanges arRev, err := ExportChanges(dest, changes, nil, nil) if err != nil { t.Fatal(err) } hdrsRev, err := walkHeaders(arRev) if err != nil { t.Fatal(err) } // line up the two sets sort.Sort(tarHeaders(hdrs)) sort.Sort(tarHeaders(hdrsRev)) // compare Size and LinkName for i := range hdrs { if hdrs[i].Name != hdrsRev[i].Name { t.Errorf("headers - expected name %q; but got %q", hdrs[i].Name, hdrsRev[i].Name) } if hdrs[i].Size != hdrsRev[i].Size { t.Errorf("headers - %q expected size %d; but got %d", hdrs[i].Name, hdrs[i].Size, hdrsRev[i].Size) } if hdrs[i].Typeflag != hdrsRev[i].Typeflag { t.Errorf("headers - %q expected type %d; but got %d", hdrs[i].Name, hdrs[i].Typeflag, hdrsRev[i].Typeflag) } if hdrs[i].Linkname != hdrsRev[i].Linkname { t.Errorf("headers - %q expected linkname %q; but got %q", hdrs[i].Name, hdrs[i].Linkname, hdrsRev[i].Linkname) } } } type tarHeaders []tar.Header func (th tarHeaders) Len() int { return len(th) } func (th tarHeaders) Swap(i, j int) { th[j], th[i] = th[i], th[j] } func (th tarHeaders) Less(i, j int) bool { return th[i].Name < th[j].Name } func walkHeaders(r io.Reader) ([]tar.Header, error) { t := tar.NewReader(r) headers := []tar.Header{} for { hdr, err := t.Next() if err != nil { if err == io.EOF { break } return headers, err } headers = append(headers, *hdr) } return headers, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_test.go ================================================ package archive import ( "io/ioutil" "os" "os/exec" "path" "sort" "testing" "time" ) func max(x, y int) int { if x >= y { return x } return y } func copyDir(src, dst string) error { cmd := exec.Command("cp", "-a", src, dst) if err := cmd.Run(); err != nil { return err } return nil } type FileType uint32 const ( Regular FileType = iota Dir Symlink ) type FileData struct { filetype FileType path string contents string permissions os.FileMode } func createSampleDir(t *testing.T, root string) { files := []FileData{ {Regular, "file1", "file1\n", 0600}, {Regular, "file2", "file2\n", 0666}, {Regular, "file3", "file3\n", 0404}, {Regular, "file4", "file4\n", 0600}, {Regular, "file5", "file5\n", 0600}, {Regular, "file6", "file6\n", 0600}, {Regular, "file7", "file7\n", 0600}, {Dir, "dir1", "", 0740}, {Regular, "dir1/file1-1", "file1-1\n", 01444}, {Regular, "dir1/file1-2", "file1-2\n", 0666}, {Dir, "dir2", "", 0700}, {Regular, "dir2/file2-1", "file2-1\n", 0666}, {Regular, "dir2/file2-2", "file2-2\n", 0666}, {Dir, "dir3", "", 0700}, {Regular, "dir3/file3-1", "file3-1\n", 0666}, {Regular, "dir3/file3-2", "file3-2\n", 0666}, {Dir, "dir4", "", 0700}, {Regular, "dir4/file3-1", "file4-1\n", 0666}, {Regular, "dir4/file3-2", "file4-2\n", 0666}, {Symlink, "symlink1", "target1", 0666}, {Symlink, "symlink2", "target2", 0666}, {Symlink, "symlink3", root + "/file1", 0666}, {Symlink, "symlink4", root + "/symlink3", 0666}, {Symlink, "dirSymlink", root + "/dir1", 0740}, } now := time.Now() for _, info := range files { p := path.Join(root, info.path) if info.filetype == Dir { if err := os.MkdirAll(p, info.permissions); err != nil { t.Fatal(err) } } else if info.filetype == Regular { if err := ioutil.WriteFile(p, []byte(info.contents), info.permissions); err != nil { t.Fatal(err) } } else if info.filetype == Symlink { if err := os.Symlink(info.contents, p); err != nil { t.Fatal(err) } } if info.filetype != Symlink { // Set a consistent ctime, atime for all files and dirs if err := os.Chtimes(p, now, now); err != nil { t.Fatal(err) } } } } func TestChangeString(t *testing.T) { modifiyChange := Change{"change", ChangeModify} toString := modifiyChange.String() if toString != "C change" { t.Fatalf("String() of a change with ChangeModifiy Kind should have been %s but was %s", "C change", toString) } addChange := Change{"change", ChangeAdd} toString = addChange.String() if toString != "A change" { t.Fatalf("String() of a change with ChangeAdd Kind should have been %s but was %s", "A change", toString) } deleteChange := Change{"change", ChangeDelete} toString = deleteChange.String() if toString != "D change" { t.Fatalf("String() of a change with ChangeDelete Kind should have been %s but was %s", "D change", toString) } } func TestChangesWithNoChanges(t *testing.T) { rwLayer, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(rwLayer) layer, err := ioutil.TempDir("", "docker-changes-test-layer") if err != nil { t.Fatal(err) } defer os.RemoveAll(layer) createSampleDir(t, layer) changes, err := Changes([]string{layer}, rwLayer) if err != nil { t.Fatal(err) } if len(changes) != 0 { t.Fatalf("Changes with no difference should have detect no changes, but detected %d", len(changes)) } } func TestChangesWithChanges(t *testing.T) { // Mock the readonly layer layer, err := ioutil.TempDir("", "docker-changes-test-layer") if err != nil { t.Fatal(err) } defer os.RemoveAll(layer) createSampleDir(t, layer) os.MkdirAll(path.Join(layer, "dir1/subfolder"), 0740) // Mock the RW layer rwLayer, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(rwLayer) // Create a folder in RW layer dir1 := path.Join(rwLayer, "dir1") os.MkdirAll(dir1, 0740) deletedFile := path.Join(dir1, ".wh.file1-2") ioutil.WriteFile(deletedFile, []byte{}, 0600) modifiedFile := path.Join(dir1, "file1-1") ioutil.WriteFile(modifiedFile, []byte{0x00}, 01444) // Let's add a subfolder for a newFile subfolder := path.Join(dir1, "subfolder") os.MkdirAll(subfolder, 0740) newFile := path.Join(subfolder, "newFile") ioutil.WriteFile(newFile, []byte{}, 0740) changes, err := Changes([]string{layer}, rwLayer) if err != nil { t.Fatal(err) } expectedChanges := []Change{ {"/dir1", ChangeModify}, {"/dir1/file1-1", ChangeModify}, {"/dir1/file1-2", ChangeDelete}, {"/dir1/subfolder", ChangeModify}, {"/dir1/subfolder/newFile", ChangeAdd}, } checkChanges(expectedChanges, changes, t) } // See https://github.com/docker/docker/pull/13590 func TestChangesWithChangesGH13590(t *testing.T) { baseLayer, err := ioutil.TempDir("", "docker-changes-test.") defer os.RemoveAll(baseLayer) dir3 := path.Join(baseLayer, "dir1/dir2/dir3") os.MkdirAll(dir3, 07400) file := path.Join(dir3, "file.txt") ioutil.WriteFile(file, []byte("hello"), 0666) layer, err := ioutil.TempDir("", "docker-changes-test2.") defer os.RemoveAll(layer) // Test creating a new file if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { t.Fatalf("Cmd failed: %q", err) } os.Remove(path.Join(layer, "dir1/dir2/dir3/file.txt")) file = path.Join(layer, "dir1/dir2/dir3/file1.txt") ioutil.WriteFile(file, []byte("bye"), 0666) changes, err := Changes([]string{baseLayer}, layer) if err != nil { t.Fatal(err) } expectedChanges := []Change{ {"/dir1/dir2/dir3", ChangeModify}, {"/dir1/dir2/dir3/file1.txt", ChangeAdd}, } checkChanges(expectedChanges, changes, t) // Now test changing a file layer, err = ioutil.TempDir("", "docker-changes-test3.") defer os.RemoveAll(layer) if err := copyDir(baseLayer+"/dir1", layer+"/"); err != nil { t.Fatalf("Cmd failed: %q", err) } file = path.Join(layer, "dir1/dir2/dir3/file.txt") ioutil.WriteFile(file, []byte("bye"), 0666) changes, err = Changes([]string{baseLayer}, layer) if err != nil { t.Fatal(err) } expectedChanges = []Change{ {"/dir1/dir2/dir3/file.txt", ChangeModify}, } checkChanges(expectedChanges, changes, t) } // Create an directory, copy it, make sure we report no changes between the two func TestChangesDirsEmpty(t *testing.T) { src, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(src) createSampleDir(t, src) dst := src + "-copy" if err := copyDir(src, dst); err != nil { t.Fatal(err) } defer os.RemoveAll(dst) changes, err := ChangesDirs(dst, src) if err != nil { t.Fatal(err) } if len(changes) != 0 { t.Fatalf("Reported changes for identical dirs: %v", changes) } os.RemoveAll(src) os.RemoveAll(dst) } func mutateSampleDir(t *testing.T, root string) { // Remove a regular file if err := os.RemoveAll(path.Join(root, "file1")); err != nil { t.Fatal(err) } // Remove a directory if err := os.RemoveAll(path.Join(root, "dir1")); err != nil { t.Fatal(err) } // Remove a symlink if err := os.RemoveAll(path.Join(root, "symlink1")); err != nil { t.Fatal(err) } // Rewrite a file if err := ioutil.WriteFile(path.Join(root, "file2"), []byte("fileNN\n"), 0777); err != nil { t.Fatal(err) } // Replace a file if err := os.RemoveAll(path.Join(root, "file3")); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(root, "file3"), []byte("fileMM\n"), 0404); err != nil { t.Fatal(err) } // Touch file if err := os.Chtimes(path.Join(root, "file4"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { t.Fatal(err) } // Replace file with dir if err := os.RemoveAll(path.Join(root, "file5")); err != nil { t.Fatal(err) } if err := os.MkdirAll(path.Join(root, "file5"), 0666); err != nil { t.Fatal(err) } // Create new file if err := ioutil.WriteFile(path.Join(root, "filenew"), []byte("filenew\n"), 0777); err != nil { t.Fatal(err) } // Create new dir if err := os.MkdirAll(path.Join(root, "dirnew"), 0766); err != nil { t.Fatal(err) } // Create a new symlink if err := os.Symlink("targetnew", path.Join(root, "symlinknew")); err != nil { t.Fatal(err) } // Change a symlink if err := os.RemoveAll(path.Join(root, "symlink2")); err != nil { t.Fatal(err) } if err := os.Symlink("target2change", path.Join(root, "symlink2")); err != nil { t.Fatal(err) } // Replace dir with file if err := os.RemoveAll(path.Join(root, "dir2")); err != nil { t.Fatal(err) } if err := ioutil.WriteFile(path.Join(root, "dir2"), []byte("dir2\n"), 0777); err != nil { t.Fatal(err) } // Touch dir if err := os.Chtimes(path.Join(root, "dir3"), time.Now().Add(time.Second), time.Now().Add(time.Second)); err != nil { t.Fatal(err) } } func TestChangesDirsMutated(t *testing.T) { src, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } createSampleDir(t, src) dst := src + "-copy" if err := copyDir(src, dst); err != nil { t.Fatal(err) } defer os.RemoveAll(src) defer os.RemoveAll(dst) mutateSampleDir(t, dst) changes, err := ChangesDirs(dst, src) if err != nil { t.Fatal(err) } sort.Sort(changesByPath(changes)) expectedChanges := []Change{ {"/dir1", ChangeDelete}, {"/dir2", ChangeModify}, {"/dirnew", ChangeAdd}, {"/file1", ChangeDelete}, {"/file2", ChangeModify}, {"/file3", ChangeModify}, {"/file4", ChangeModify}, {"/file5", ChangeModify}, {"/filenew", ChangeAdd}, {"/symlink1", ChangeDelete}, {"/symlink2", ChangeModify}, {"/symlinknew", ChangeAdd}, } for i := 0; i < max(len(changes), len(expectedChanges)); i++ { if i >= len(expectedChanges) { t.Fatalf("unexpected change %s\n", changes[i].String()) } if i >= len(changes) { t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) } if changes[i].Path == expectedChanges[i].Path { if changes[i] != expectedChanges[i] { t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) } } else if changes[i].Path < expectedChanges[i].Path { t.Fatalf("unexpected change %s\n", changes[i].String()) } else { t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) } } } func TestApplyLayer(t *testing.T) { src, err := ioutil.TempDir("", "docker-changes-test") if err != nil { t.Fatal(err) } createSampleDir(t, src) defer os.RemoveAll(src) dst := src + "-copy" if err := copyDir(src, dst); err != nil { t.Fatal(err) } mutateSampleDir(t, dst) defer os.RemoveAll(dst) changes, err := ChangesDirs(dst, src) if err != nil { t.Fatal(err) } layer, err := ExportChanges(dst, changes, nil, nil) if err != nil { t.Fatal(err) } layerCopy, err := NewTempArchive(layer, "") if err != nil { t.Fatal(err) } if _, err := ApplyLayer(src, layerCopy); err != nil { t.Fatal(err) } changes2, err := ChangesDirs(src, dst) if err != nil { t.Fatal(err) } if len(changes2) != 0 { t.Fatalf("Unexpected differences after reapplying mutation: %v", changes2) } } func TestChangesSizeWithHardlinks(t *testing.T) { srcDir, err := ioutil.TempDir("", "docker-test-srcDir") if err != nil { t.Fatal(err) } defer os.RemoveAll(srcDir) destDir, err := ioutil.TempDir("", "docker-test-destDir") if err != nil { t.Fatal(err) } defer os.RemoveAll(destDir) creationSize, err := prepareUntarSourceDirectory(100, destDir, true) if err != nil { t.Fatal(err) } changes, err := ChangesDirs(destDir, srcDir) if err != nil { t.Fatal(err) } got := ChangesSize(destDir, changes) if got != int64(creationSize) { t.Errorf("Expected %d bytes of changes, got %d", creationSize, got) } } func TestChangesSizeWithNoChanges(t *testing.T) { size := ChangesSize("/tmp", nil) if size != 0 { t.Fatalf("ChangesSizes with no changes should be 0, was %d", size) } } func TestChangesSizeWithOnlyDeleteChanges(t *testing.T) { changes := []Change{ {Path: "deletedPath", Kind: ChangeDelete}, } size := ChangesSize("/tmp", changes) if size != 0 { t.Fatalf("ChangesSizes with only delete changes should be 0, was %d", size) } } func TestChangesSize(t *testing.T) { parentPath, err := ioutil.TempDir("", "docker-changes-test") defer os.RemoveAll(parentPath) addition := path.Join(parentPath, "addition") if err := ioutil.WriteFile(addition, []byte{0x01, 0x01, 0x01}, 0744); err != nil { t.Fatal(err) } modification := path.Join(parentPath, "modification") if err = ioutil.WriteFile(modification, []byte{0x01, 0x01, 0x01}, 0744); err != nil { t.Fatal(err) } changes := []Change{ {Path: "addition", Kind: ChangeAdd}, {Path: "modification", Kind: ChangeModify}, } size := ChangesSize(parentPath, changes) if size != 6 { t.Fatalf("Expected 6 bytes of changes, got %d", size) } } func checkChanges(expectedChanges, changes []Change, t *testing.T) { sort.Sort(changesByPath(expectedChanges)) sort.Sort(changesByPath(changes)) for i := 0; i < max(len(changes), len(expectedChanges)); i++ { if i >= len(expectedChanges) { t.Fatalf("unexpected change %s\n", changes[i].String()) } if i >= len(changes) { t.Fatalf("no change for expected change %s\n", expectedChanges[i].String()) } if changes[i].Path == expectedChanges[i].Path { if changes[i] != expectedChanges[i] { t.Fatalf("Wrong change for %s, expected %s, got %s\n", changes[i].Path, changes[i].String(), expectedChanges[i].String()) } } else if changes[i].Path < expectedChanges[i].Path { t.Fatalf("unexpected change %s\n", changes[i].String()) } else { t.Fatalf("no change for expected change %s != %s\n", expectedChanges[i].String(), changes[i].String()) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_unix.go ================================================ // +build !windows package archive import ( "os" "syscall" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { // Don't look at size for dirs, its not a good measure of change if oldStat.Mode() != newStat.Mode() || oldStat.UID() != newStat.UID() || oldStat.GID() != newStat.GID() || oldStat.Rdev() != newStat.Rdev() || // Don't look at size for dirs, its not a good measure of change (oldStat.Mode()&syscall.S_IFDIR != syscall.S_IFDIR && (!sameFsTimeSpec(oldStat.Mtim(), newStat.Mtim()) || (oldStat.Size() != newStat.Size()))) { return true } return false } func (info *FileInfo) isDir() bool { return info.parent == nil || info.stat.Mode()&syscall.S_IFDIR != 0 } func getIno(fi os.FileInfo) uint64 { return uint64(fi.Sys().(*syscall.Stat_t).Ino) } func hasHardlinks(fi os.FileInfo) bool { return fi.Sys().(*syscall.Stat_t).Nlink > 1 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/changes_windows.go ================================================ package archive import ( "os" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) func statDifferent(oldStat *system.StatT, newStat *system.StatT) bool { // Don't look at size for dirs, its not a good measure of change if oldStat.ModTime() != newStat.ModTime() || oldStat.Mode() != newStat.Mode() || oldStat.Size() != newStat.Size() && !oldStat.IsDir() { return true } return false } func (info *FileInfo) isDir() bool { return info.parent == nil || info.stat.IsDir() } func getIno(fi os.FileInfo) (inode uint64) { return } func hasHardlinks(fi os.FileInfo) bool { return false } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy.go ================================================ package archive import ( "archive/tar" "errors" "io" "io/ioutil" "os" "path/filepath" "strings" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) // Errors used or returned by this file. var ( ErrNotDirectory = errors.New("not a directory") ErrDirNotExists = errors.New("no such directory") ErrCannotCopyDir = errors.New("cannot copy directory") ErrInvalidCopySource = errors.New("invalid copy source content") ) // PreserveTrailingDotOrSeparator returns the given cleaned path (after // processing using any utility functions from the path or filepath stdlib // packages) and appends a trailing `/.` or `/` if its corresponding original // path (from before being processed by utility functions from the path or // filepath stdlib packages) ends with a trailing `/.` or `/`. If the cleaned // path already ends in a `.` path segment, then another is not added. If the // clean path already ends in a path separator, then another is not added. func PreserveTrailingDotOrSeparator(cleanedPath, originalPath string) string { // Ensure paths are in platform semantics cleanedPath = normalizePath(cleanedPath) originalPath = normalizePath(originalPath) if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { if !hasTrailingPathSeparator(cleanedPath) { // Add a separator if it doesn't already end with one (a cleaned // path would only end in a separator if it is the root). cleanedPath += string(filepath.Separator) } cleanedPath += "." } if !hasTrailingPathSeparator(cleanedPath) && hasTrailingPathSeparator(originalPath) { cleanedPath += string(filepath.Separator) } return cleanedPath } // assertsDirectory returns whether the given path is // asserted to be a directory, i.e., the path ends with // a trailing '/' or `/.`, assuming a path separator of `/`. func assertsDirectory(path string) bool { return hasTrailingPathSeparator(path) || specifiesCurrentDir(path) } // hasTrailingPathSeparator returns whether the given // path ends with the system's path separator character. func hasTrailingPathSeparator(path string) bool { return len(path) > 0 && os.IsPathSeparator(path[len(path)-1]) } // specifiesCurrentDir returns whether the given path specifies // a "current directory", i.e., the last path segment is `.`. func specifiesCurrentDir(path string) bool { return filepath.Base(path) == "." } // SplitPathDirEntry splits the given path between its directory name and its // basename by first cleaning the path but preserves a trailing "." if the // original path specified the current directory. func SplitPathDirEntry(path string) (dir, base string) { cleanedPath := filepath.Clean(normalizePath(path)) if specifiesCurrentDir(path) { cleanedPath += string(filepath.Separator) + "." } return filepath.Dir(cleanedPath), filepath.Base(cleanedPath) } // TarResource archives the resource described by the given CopyInfo to a Tar // archive. A non-nil error is returned if sourcePath does not exist or is // asserted to be a directory but exists as another type of file. // // This function acts as a convenient wrapper around TarWithOptions, which // requires a directory as the source path. TarResource accepts either a // directory or a file path and correctly sets the Tar options. func TarResource(sourceInfo CopyInfo) (content Archive, err error) { return TarResourceRebase(sourceInfo.Path, sourceInfo.RebaseName) } // TarResourceRebase is like TarResource but renames the first path element of // items in the resulting tar archive to match the given rebaseName if not "". func TarResourceRebase(sourcePath, rebaseName string) (content Archive, err error) { sourcePath = normalizePath(sourcePath) if _, err = os.Lstat(sourcePath); err != nil { // Catches the case where the source does not exist or is not a // directory if asserted to be a directory, as this also causes an // error. return } // Separate the source path between it's directory and // the entry in that directory which we are archiving. sourceDir, sourceBase := SplitPathDirEntry(sourcePath) filter := []string{sourceBase} logrus.Debugf("copying %q from %q", sourceBase, sourceDir) return TarWithOptions(sourceDir, &TarOptions{ Compression: Uncompressed, IncludeFiles: filter, IncludeSourceDir: true, RebaseNames: map[string]string{ sourceBase: rebaseName, }, }) } // CopyInfo holds basic info about the source // or destination path of a copy operation. type CopyInfo struct { Path string Exists bool IsDir bool RebaseName string } // CopyInfoSourcePath stats the given path to create a CopyInfo // struct representing that resource for the source of an archive copy // operation. The given path should be an absolute local path. A source path // has all symlinks evaluated that appear before the last path separator ("/" // on Unix). As it is to be a copy source, the path must exist. func CopyInfoSourcePath(path string, followLink bool) (CopyInfo, error) { // normalize the file path and then evaluate the symbol link // we will use the target file instead of the symbol link if // followLink is set path = normalizePath(path) resolvedPath, rebaseName, err := ResolveHostSourcePath(path, followLink) if err != nil { return CopyInfo{}, err } stat, err := os.Lstat(resolvedPath) if err != nil { return CopyInfo{}, err } return CopyInfo{ Path: resolvedPath, Exists: true, IsDir: stat.IsDir(), RebaseName: rebaseName, }, nil } // CopyInfoDestinationPath stats the given path to create a CopyInfo // struct representing that resource for the destination of an archive copy // operation. The given path should be an absolute local path. func CopyInfoDestinationPath(path string) (info CopyInfo, err error) { maxSymlinkIter := 10 // filepath.EvalSymlinks uses 255, but 10 already seems like a lot. path = normalizePath(path) originalPath := path stat, err := os.Lstat(path) if err == nil && stat.Mode()&os.ModeSymlink == 0 { // The path exists and is not a symlink. return CopyInfo{ Path: path, Exists: true, IsDir: stat.IsDir(), }, nil } // While the path is a symlink. for n := 0; err == nil && stat.Mode()&os.ModeSymlink != 0; n++ { if n > maxSymlinkIter { // Don't follow symlinks more than this arbitrary number of times. return CopyInfo{}, errors.New("too many symlinks in " + originalPath) } // The path is a symbolic link. We need to evaluate it so that the // destination of the copy operation is the link target and not the // link itself. This is notably different than CopyInfoSourcePath which // only evaluates symlinks before the last appearing path separator. // Also note that it is okay if the last path element is a broken // symlink as the copy operation should create the target. var linkTarget string linkTarget, err = os.Readlink(path) if err != nil { return CopyInfo{}, err } if !system.IsAbs(linkTarget) { // Join with the parent directory. dstParent, _ := SplitPathDirEntry(path) linkTarget = filepath.Join(dstParent, linkTarget) } path = linkTarget stat, err = os.Lstat(path) } if err != nil { // It's okay if the destination path doesn't exist. We can still // continue the copy operation if the parent directory exists. if !os.IsNotExist(err) { return CopyInfo{}, err } // Ensure destination parent dir exists. dstParent, _ := SplitPathDirEntry(path) parentDirStat, err := os.Lstat(dstParent) if err != nil { return CopyInfo{}, err } if !parentDirStat.IsDir() { return CopyInfo{}, ErrNotDirectory } return CopyInfo{Path: path}, nil } // The path exists after resolving symlinks. return CopyInfo{ Path: path, Exists: true, IsDir: stat.IsDir(), }, nil } // PrepareArchiveCopy prepares the given srcContent archive, which should // contain the archived resource described by srcInfo, to the destination // described by dstInfo. Returns the possibly modified content archive along // with the path to the destination directory which it should be extracted to. func PrepareArchiveCopy(srcContent Reader, srcInfo, dstInfo CopyInfo) (dstDir string, content Archive, err error) { // Ensure in platform semantics srcInfo.Path = normalizePath(srcInfo.Path) dstInfo.Path = normalizePath(dstInfo.Path) // Separate the destination path between its directory and base // components in case the source archive contents need to be rebased. dstDir, dstBase := SplitPathDirEntry(dstInfo.Path) _, srcBase := SplitPathDirEntry(srcInfo.Path) switch { case dstInfo.Exists && dstInfo.IsDir: // The destination exists as a directory. No alteration // to srcContent is needed as its contents can be // simply extracted to the destination directory. return dstInfo.Path, ioutil.NopCloser(srcContent), nil case dstInfo.Exists && srcInfo.IsDir: // The destination exists as some type of file and the source // content is a directory. This is an error condition since // you cannot copy a directory to an existing file location. return "", nil, ErrCannotCopyDir case dstInfo.Exists: // The destination exists as some type of file and the source content // is also a file. The source content entry will have to be renamed to // have a basename which matches the destination path's basename. if len(srcInfo.RebaseName) != 0 { srcBase = srcInfo.RebaseName } return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil case srcInfo.IsDir: // The destination does not exist and the source content is an archive // of a directory. The archive should be extracted to the parent of // the destination path instead, and when it is, the directory that is // created as a result should take the name of the destination path. // The source content entries will have to be renamed to have a // basename which matches the destination path's basename. if len(srcInfo.RebaseName) != 0 { srcBase = srcInfo.RebaseName } return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil case assertsDirectory(dstInfo.Path): // The destination does not exist and is asserted to be created as a // directory, but the source content is not a directory. This is an // error condition since you cannot create a directory from a file // source. return "", nil, ErrDirNotExists default: // The last remaining case is when the destination does not exist, is // not asserted to be a directory, and the source content is not an // archive of a directory. It this case, the destination file will need // to be created when the archive is extracted and the source content // entry will have to be renamed to have a basename which matches the // destination path's basename. if len(srcInfo.RebaseName) != 0 { srcBase = srcInfo.RebaseName } return dstDir, RebaseArchiveEntries(srcContent, srcBase, dstBase), nil } } // RebaseArchiveEntries rewrites the given srcContent archive replacing // an occurrence of oldBase with newBase at the beginning of entry names. func RebaseArchiveEntries(srcContent Reader, oldBase, newBase string) Archive { if oldBase == string(os.PathSeparator) { // If oldBase specifies the root directory, use an empty string as // oldBase instead so that newBase doesn't replace the path separator // that all paths will start with. oldBase = "" } rebased, w := io.Pipe() go func() { srcTar := tar.NewReader(srcContent) rebasedTar := tar.NewWriter(w) for { hdr, err := srcTar.Next() if err == io.EOF { // Signals end of archive. rebasedTar.Close() w.Close() return } if err != nil { w.CloseWithError(err) return } hdr.Name = strings.Replace(hdr.Name, oldBase, newBase, 1) if err = rebasedTar.WriteHeader(hdr); err != nil { w.CloseWithError(err) return } if _, err = io.Copy(rebasedTar, srcTar); err != nil { w.CloseWithError(err) return } } }() return rebased } // CopyResource performs an archive copy from the given source path to the // given destination path. The source path MUST exist and the destination // path's parent directory must exist. func CopyResource(srcPath, dstPath string, followLink bool) error { var ( srcInfo CopyInfo err error ) // Ensure in platform semantics srcPath = normalizePath(srcPath) dstPath = normalizePath(dstPath) // Clean the source and destination paths. srcPath = PreserveTrailingDotOrSeparator(filepath.Clean(srcPath), srcPath) dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath) if srcInfo, err = CopyInfoSourcePath(srcPath, followLink); err != nil { return err } content, err := TarResource(srcInfo) if err != nil { return err } defer content.Close() return CopyTo(content, srcInfo, dstPath) } // CopyTo handles extracting the given content whose // entries should be sourced from srcInfo to dstPath. func CopyTo(content Reader, srcInfo CopyInfo, dstPath string) error { // The destination path need not exist, but CopyInfoDestinationPath will // ensure that at least the parent directory exists. dstInfo, err := CopyInfoDestinationPath(normalizePath(dstPath)) if err != nil { return err } dstDir, copyArchive, err := PrepareArchiveCopy(content, srcInfo, dstInfo) if err != nil { return err } defer copyArchive.Close() options := &TarOptions{ NoLchown: true, NoOverwriteDirNonDir: true, } return Untar(copyArchive, dstDir, options) } // ResolveHostSourcePath decides real path need to be copied with parameters such as // whether to follow symbol link or not, if followLink is true, resolvedPath will return // link target of any symbol link file, else it will only resolve symlink of directory // but return symbol link file itself without resolving. func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseName string, err error) { if followLink { resolvedPath, err = filepath.EvalSymlinks(path) if err != nil { return } resolvedPath, rebaseName = GetRebaseName(path, resolvedPath) } else { dirPath, basePath := filepath.Split(path) // if not follow symbol link, then resolve symbol link of parent dir var resolvedDirPath string resolvedDirPath, err = filepath.EvalSymlinks(dirPath) if err != nil { return } // resolvedDirPath will have been cleaned (no trailing path separators) so // we can manually join it with the base path element. resolvedPath = resolvedDirPath + string(filepath.Separator) + basePath if hasTrailingPathSeparator(path) && filepath.Base(path) != filepath.Base(resolvedPath) { rebaseName = filepath.Base(path) } } return resolvedPath, rebaseName, nil } // GetRebaseName normalizes and compares path and resolvedPath, // return completed resolved path and rebased file name func GetRebaseName(path, resolvedPath string) (string, string) { // linkTarget will have been cleaned (no trailing path separators and dot) so // we can manually join it with them var rebaseName string if specifiesCurrentDir(path) && !specifiesCurrentDir(resolvedPath) { resolvedPath += string(filepath.Separator) + "." } if hasTrailingPathSeparator(path) && !hasTrailingPathSeparator(resolvedPath) { resolvedPath += string(filepath.Separator) } if filepath.Base(path) != filepath.Base(resolvedPath) { // In the case where the path had a trailing separator and a symlink // evaluation has changed the last path component, we will need to // rebase the name in the archive that is being copied to match the // originally requested name. rebaseName = filepath.Base(path) } return resolvedPath, rebaseName } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_test.go ================================================ package archive import ( "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "os" "path/filepath" "strings" "testing" ) func removeAllPaths(paths ...string) { for _, path := range paths { os.RemoveAll(path) } } func getTestTempDirs(t *testing.T) (tmpDirA, tmpDirB string) { var err error if tmpDirA, err = ioutil.TempDir("", "archive-copy-test"); err != nil { t.Fatal(err) } if tmpDirB, err = ioutil.TempDir("", "archive-copy-test"); err != nil { t.Fatal(err) } return } func isNotDir(err error) bool { return strings.Contains(err.Error(), "not a directory") } func joinTrailingSep(pathElements ...string) string { joined := filepath.Join(pathElements...) return fmt.Sprintf("%s%c", joined, filepath.Separator) } func fileContentsEqual(t *testing.T, filenameA, filenameB string) (err error) { t.Logf("checking for equal file contents: %q and %q\n", filenameA, filenameB) fileA, err := os.Open(filenameA) if err != nil { return } defer fileA.Close() fileB, err := os.Open(filenameB) if err != nil { return } defer fileB.Close() hasher := sha256.New() if _, err = io.Copy(hasher, fileA); err != nil { return } hashA := hasher.Sum(nil) hasher.Reset() if _, err = io.Copy(hasher, fileB); err != nil { return } hashB := hasher.Sum(nil) if !bytes.Equal(hashA, hashB) { err = fmt.Errorf("file content hashes not equal - expected %s, got %s", hex.EncodeToString(hashA), hex.EncodeToString(hashB)) } return } func dirContentsEqual(t *testing.T, newDir, oldDir string) (err error) { t.Logf("checking for equal directory contents: %q and %q\n", newDir, oldDir) var changes []Change if changes, err = ChangesDirs(newDir, oldDir); err != nil { return } if len(changes) != 0 { err = fmt.Errorf("expected no changes between directories, but got: %v", changes) } return } func logDirContents(t *testing.T, dirPath string) { logWalkedPaths := filepath.WalkFunc(func(path string, info os.FileInfo, err error) error { if err != nil { t.Errorf("stat error for path %q: %s", path, err) return nil } if info.IsDir() { path = joinTrailingSep(path) } t.Logf("\t%s", path) return nil }) t.Logf("logging directory contents: %q", dirPath) if err := filepath.Walk(dirPath, logWalkedPaths); err != nil { t.Fatal(err) } } func testCopyHelper(t *testing.T, srcPath, dstPath string) (err error) { t.Logf("copying from %q to %q (not follow symbol link)", srcPath, dstPath) return CopyResource(srcPath, dstPath, false) } func testCopyHelperFSym(t *testing.T, srcPath, dstPath string) (err error) { t.Logf("copying from %q to %q (follow symbol link)", srcPath, dstPath) return CopyResource(srcPath, dstPath, true) } // Basic assumptions about SRC and DST: // 1. SRC must exist. // 2. If SRC ends with a trailing separator, it must be a directory. // 3. DST parent directory must exist. // 4. If DST exists as a file, it must not end with a trailing separator. // First get these easy error cases out of the way. // Test for error when SRC does not exist. func TestCopyErrSrcNotExists(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) if _, err := CopyInfoSourcePath(filepath.Join(tmpDirA, "file1"), false); !os.IsNotExist(err) { t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when SRC ends in a trailing // path separator but it exists as a file. func TestCopyErrSrcNotDir(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) if _, err := CopyInfoSourcePath(joinTrailingSep(tmpDirA, "file1"), false); !isNotDir(err) { t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Test for error when SRC is a valid file or directory, // but the DST parent directory does not exist. func TestCopyErrDstParentNotExists(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} // Try with a file source. content, err := TarResource(srcInfo) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() // Copy to a file whose parent does not exist. if err = CopyTo(content, srcInfo, filepath.Join(tmpDirB, "fakeParentDir", "file1")); err == nil { t.Fatal("expected IsNotExist error, but got nil instead") } if !os.IsNotExist(err) { t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } // Try with a directory source. srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} content, err = TarResource(srcInfo) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() // Copy to a directory whose parent does not exist. if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "fakeParentDir", "fakeDstDir")); err == nil { t.Fatal("expected IsNotExist error, but got nil instead") } if !os.IsNotExist(err) { t.Fatalf("expected IsNotExist error, but got %T: %s", err, err) } } // Test for error when DST ends in a trailing // path separator but exists as a file. func TestCopyErrDstNotDir(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) // Try with a file source. srcInfo := CopyInfo{Path: filepath.Join(tmpDirA, "file1"), Exists: true, IsDir: false} content, err := TarResource(srcInfo) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { t.Fatal("expected IsNotDir error, but got nil instead") } if !isNotDir(err) { t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } // Try with a directory source. srcInfo = CopyInfo{Path: filepath.Join(tmpDirA, "dir1"), Exists: true, IsDir: true} content, err = TarResource(srcInfo) if err != nil { t.Fatalf("unexpected error %T: %s", err, err) } defer content.Close() if err = CopyTo(content, srcInfo, joinTrailingSep(tmpDirB, "file1")); err == nil { t.Fatal("expected IsNotDir error, but got nil instead") } if !isNotDir(err) { t.Fatalf("expected IsNotDir error, but got %T: %s", err, err) } } // Possibilities are reduced to the remaining 10 cases: // // case | srcIsDir | onlyDirContents | dstExists | dstIsDir | dstTrSep | action // =================================================================================================== // A | no | - | no | - | no | create file // B | no | - | no | - | yes | error // C | no | - | yes | no | - | overwrite file // D | no | - | yes | yes | - | create file in dst dir // E | yes | no | no | - | - | create dir, copy contents // F | yes | no | yes | no | - | error // G | yes | no | yes | yes | - | copy dir and contents // H | yes | yes | no | - | - | create dir, copy contents // I | yes | yes | yes | no | - | error // J | yes | yes | yes | yes | - | copy dir contents // // A. SRC specifies a file and DST (no trailing path separator) doesn't // exist. This should create a file with the name DST and copy the // contents of the source file into it. func TestCopyCaseA(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcPath := filepath.Join(tmpDirA, "file1") dstPath := filepath.Join(tmpDirB, "itWorks.txt") var err error if err = testCopyHelper(t, srcPath, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } os.Remove(dstPath) symlinkPath := filepath.Join(tmpDirA, "symlink3") symlinkPath1 := filepath.Join(tmpDirA, "symlink4") linkTarget := filepath.Join(tmpDirA, "file1") if err = testCopyHelperFSym(t, symlinkPath, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { t.Fatal(err) } os.Remove(dstPath) if err = testCopyHelperFSym(t, symlinkPath1, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { t.Fatal(err) } } // B. SRC specifies a file and DST (with trailing path separator) doesn't // exist. This should cause an error because the copy operation cannot // create a directory when copying a single file. func TestCopyCaseB(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcPath := filepath.Join(tmpDirA, "file1") dstDir := joinTrailingSep(tmpDirB, "testDir") var err error if err = testCopyHelper(t, srcPath, dstDir); err == nil { t.Fatal("expected ErrDirNotExists error, but got nil instead") } if err != ErrDirNotExists { t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) } symlinkPath := filepath.Join(tmpDirA, "symlink3") if err = testCopyHelperFSym(t, symlinkPath, dstDir); err == nil { t.Fatal("expected ErrDirNotExists error, but got nil instead") } if err != ErrDirNotExists { t.Fatalf("expected ErrDirNotExists error, but got %T: %s", err, err) } } // C. SRC specifies a file and DST exists as a file. This should overwrite // the file at DST with the contents of the source file. func TestCopyCaseC(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcPath := filepath.Join(tmpDirA, "file1") dstPath := filepath.Join(tmpDirB, "file2") var err error // Ensure they start out different. if err = fileContentsEqual(t, srcPath, dstPath); err == nil { t.Fatal("expected different file contents") } if err = testCopyHelper(t, srcPath, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } } // C. Symbol link following version: // SRC specifies a file and DST exists as a file. This should overwrite // the file at DST with the contents of the source file. func TestCopyCaseCFSym(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) symlinkPathBad := filepath.Join(tmpDirA, "symlink1") symlinkPath := filepath.Join(tmpDirA, "symlink3") linkTarget := filepath.Join(tmpDirA, "file1") dstPath := filepath.Join(tmpDirB, "file2") var err error // first to test broken link if err = testCopyHelperFSym(t, symlinkPathBad, dstPath); err == nil { t.Fatalf("unexpected error %T: %s", err, err) } // test symbol link -> symbol link -> target // Ensure they start out different. if err = fileContentsEqual(t, linkTarget, dstPath); err == nil { t.Fatal("expected different file contents") } if err = testCopyHelperFSym(t, symlinkPath, dstPath); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { t.Fatal(err) } } // D. SRC specifies a file and DST exists as a directory. This should place // a copy of the source file inside it using the basename from SRC. Ensure // this works whether DST has a trailing path separator or not. func TestCopyCaseD(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcPath := filepath.Join(tmpDirA, "file1") dstDir := filepath.Join(tmpDirB, "dir1") dstPath := filepath.Join(dstDir, "file1") var err error // Ensure that dstPath doesn't exist. if _, err = os.Stat(dstPath); !os.IsNotExist(err) { t.Fatalf("did not expect dstPath %q to exist", dstPath) } if err = testCopyHelper(t, srcPath, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir1") if err = testCopyHelper(t, srcPath, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, srcPath, dstPath); err != nil { t.Fatal(err) } } // D. Symbol link following version: // SRC specifies a file and DST exists as a directory. This should place // a copy of the source file inside it using the basename from SRC. Ensure // this works whether DST has a trailing path separator or not. func TestCopyCaseDFSym(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcPath := filepath.Join(tmpDirA, "symlink4") linkTarget := filepath.Join(tmpDirA, "file1") dstDir := filepath.Join(tmpDirB, "dir1") dstPath := filepath.Join(dstDir, "symlink4") var err error // Ensure that dstPath doesn't exist. if _, err = os.Stat(dstPath); !os.IsNotExist(err) { t.Fatalf("did not expect dstPath %q to exist", dstPath) } if err = testCopyHelperFSym(t, srcPath, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir1") if err = testCopyHelperFSym(t, srcPath, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = fileContentsEqual(t, linkTarget, dstPath); err != nil { t.Fatal(err) } } // E. SRC specifies a directory and DST does not exist. This should create a // directory at DST and copy the contents of the SRC directory into the DST // directory. Ensure this works whether DST has a trailing path separator or // not. func TestCopyCaseE(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcDir := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "testDir") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "testDir") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Fatal(err) } } // E. Symbol link following version: // SRC specifies a directory and DST does not exist. This should create a // directory at DST and copy the contents of the SRC directory into the DST // directory. Ensure this works whether DST has a trailing path separator or // not. func TestCopyCaseEFSym(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcDir := filepath.Join(tmpDirA, "dirSymlink") linkTarget := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "testDir") var err error if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "testDir") if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { t.Fatal(err) } } // F. SRC specifies a directory and DST exists as a file. This should cause an // error as it is not possible to overwrite a file with a directory. func TestCopyCaseF(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := filepath.Join(tmpDirA, "dir1") symSrcDir := filepath.Join(tmpDirA, "dirSymlink") dstFile := filepath.Join(tmpDirB, "file1") var err error if err = testCopyHelper(t, srcDir, dstFile); err == nil { t.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if err != ErrCannotCopyDir { t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } // now test with symbol link if err = testCopyHelperFSym(t, symSrcDir, dstFile); err == nil { t.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if err != ErrCannotCopyDir { t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // G. SRC specifies a directory and DST exists as a directory. This should copy // the SRC directory and all its contents to the DST directory. Ensure this // works whether DST has a trailing path separator or not. func TestCopyCaseG(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "dir2") resultDir := filepath.Join(dstDir, "dir1") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, resultDir, srcDir); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir2") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, resultDir, srcDir); err != nil { t.Fatal(err) } } // G. Symbol link version: // SRC specifies a directory and DST exists as a directory. This should copy // the SRC directory and all its contents to the DST directory. Ensure this // works whether DST has a trailing path separator or not. func TestCopyCaseGFSym(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := filepath.Join(tmpDirA, "dirSymlink") linkTarget := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "dir2") resultDir := filepath.Join(dstDir, "dirSymlink") var err error if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, resultDir, linkTarget); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir2") if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, resultDir, linkTarget); err != nil { t.Fatal(err) } } // H. SRC specifies a directory's contents only and DST does not exist. This // should create a directory at DST and copy the contents of the SRC // directory (but not the directory itself) into the DST directory. Ensure // this works whether DST has a trailing path separator or not. func TestCopyCaseH(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcDir := joinTrailingSep(tmpDirA, "dir1") + "." dstDir := filepath.Join(tmpDirB, "testDir") var err error if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "testDir") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } } // H. Symbol link following version: // SRC specifies a directory's contents only and DST does not exist. This // should create a directory at DST and copy the contents of the SRC // directory (but not the directory itself) into the DST directory. Ensure // this works whether DST has a trailing path separator or not. func TestCopyCaseHFSym(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A with some sample files and directories. createSampleDir(t, tmpDirA) srcDir := joinTrailingSep(tmpDirA, "dirSymlink") + "." linkTarget := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "testDir") var err error if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "testDir") if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { t.Log("dir contents not equal") logDirContents(t, tmpDirA) logDirContents(t, tmpDirB) t.Fatal(err) } } // I. SRC specifies a directory's contents only and DST exists as a file. This // should cause an error as it is not possible to overwrite a file with a // directory. func TestCopyCaseI(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := joinTrailingSep(tmpDirA, "dir1") + "." symSrcDir := filepath.Join(tmpDirB, "dirSymlink") dstFile := filepath.Join(tmpDirB, "file1") var err error if err = testCopyHelper(t, srcDir, dstFile); err == nil { t.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if err != ErrCannotCopyDir { t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } // now try with symbol link of dir if err = testCopyHelperFSym(t, symSrcDir, dstFile); err == nil { t.Fatal("expected ErrCannotCopyDir error, but got nil instead") } if err != ErrCannotCopyDir { t.Fatalf("expected ErrCannotCopyDir error, but got %T: %s", err, err) } } // J. SRC specifies a directory's contents only and DST exists as a directory. // This should copy the contents of the SRC directory (but not the directory // itself) into the DST directory. Ensure this works whether DST has a // trailing path separator or not. func TestCopyCaseJ(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := joinTrailingSep(tmpDirA, "dir1") + "." dstDir := filepath.Join(tmpDirB, "dir5") var err error // first to create an empty dir if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir5") if err = testCopyHelper(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, srcDir); err != nil { t.Fatal(err) } } // J. Symbol link following version: // SRC specifies a directory's contents only and DST exists as a directory. // This should copy the contents of the SRC directory (but not the directory // itself) into the DST directory. Ensure this works whether DST has a // trailing path separator or not. func TestCopyCaseJFSym(t *testing.T) { tmpDirA, tmpDirB := getTestTempDirs(t) defer removeAllPaths(tmpDirA, tmpDirB) // Load A and B with some sample files and directories. createSampleDir(t, tmpDirA) createSampleDir(t, tmpDirB) srcDir := joinTrailingSep(tmpDirA, "dirSymlink") + "." linkTarget := filepath.Join(tmpDirA, "dir1") dstDir := filepath.Join(tmpDirB, "dir5") var err error // first to create an empty dir if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { t.Fatal(err) } // Now try again but using a trailing path separator for dstDir. if err = os.RemoveAll(dstDir); err != nil { t.Fatalf("unable to remove dstDir: %s", err) } if err = os.MkdirAll(dstDir, os.FileMode(0755)); err != nil { t.Fatalf("unable to make dstDir: %s", err) } dstDir = joinTrailingSep(tmpDirB, "dir5") if err = testCopyHelperFSym(t, srcDir, dstDir); err != nil { t.Fatalf("unexpected error %T: %s", err, err) } if err = dirContentsEqual(t, dstDir, linkTarget); err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_unix.go ================================================ // +build !windows package archive import ( "path/filepath" ) func normalizePath(path string) string { return filepath.ToSlash(path) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/copy_windows.go ================================================ package archive import ( "path/filepath" ) func normalizePath(path string) string { return filepath.FromSlash(path) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff.go ================================================ package archive import ( "archive/tar" "fmt" "io" "io/ioutil" "os" "path/filepath" "runtime" "strings" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) // UnpackLayer unpack `layer` to a `dest`. The stream `layer` can be // compressed or uncompressed. // Returns the size in bytes of the contents of the layer. func UnpackLayer(dest string, layer Reader, options *TarOptions) (size int64, err error) { tr := tar.NewReader(layer) trBuf := pools.BufioReader32KPool.Get(tr) defer pools.BufioReader32KPool.Put(trBuf) var dirs []*tar.Header unpackedPaths := make(map[string]struct{}) if options == nil { options = &TarOptions{} } if options.ExcludePatterns == nil { options.ExcludePatterns = []string{} } remappedRootUID, remappedRootGID, err := idtools.GetRootUIDGID(options.UIDMaps, options.GIDMaps) if err != nil { return 0, err } aufsTempdir := "" aufsHardlinks := make(map[string]*tar.Header) if options == nil { options = &TarOptions{} } // Iterate through the files in the archive. for { hdr, err := tr.Next() if err == io.EOF { // end of tar archive break } if err != nil { return 0, err } size += hdr.Size // Normalize name, for safety and for a simple is-root check hdr.Name = filepath.Clean(hdr.Name) // Windows does not support filenames with colons in them. Ignore // these files. This is not a problem though (although it might // appear that it is). Let's suppose a client is running docker pull. // The daemon it points to is Windows. Would it make sense for the // client to be doing a docker pull Ubuntu for example (which has files // with colons in the name under /usr/share/man/man3)? No, absolutely // not as it would really only make sense that they were pulling a // Windows image. However, for development, it is necessary to be able // to pull Linux images which are in the repository. // // TODO Windows. Once the registry is aware of what images are Windows- // specific or Linux-specific, this warning should be changed to an error // to cater for the situation where someone does manage to upload a Linux // image but have it tagged as Windows inadvertently. if runtime.GOOS == "windows" { if strings.Contains(hdr.Name, ":") { logrus.Warnf("Windows: Ignoring %s (is this a Linux image?)", hdr.Name) continue } } // Note as these operations are platform specific, so must the slash be. if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { // Not the root directory, ensure that the parent directory exists. // This happened in some tests where an image had a tarfile without any // parent directories. parent := filepath.Dir(hdr.Name) parentPath := filepath.Join(dest, parent) if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { err = system.MkdirAll(parentPath, 0600) if err != nil { return 0, err } } } // Skip AUFS metadata dirs if strings.HasPrefix(hdr.Name, WhiteoutMetaPrefix) { // Regular files inside /.wh..wh.plnk can be used as hardlink targets // We don't want this directory, but we need the files in them so that // such hardlinks can be resolved. if strings.HasPrefix(hdr.Name, WhiteoutLinkDir) && hdr.Typeflag == tar.TypeReg { basename := filepath.Base(hdr.Name) aufsHardlinks[basename] = hdr if aufsTempdir == "" { if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil { return 0, err } defer os.RemoveAll(aufsTempdir) } if err := createTarFile(filepath.Join(aufsTempdir, basename), dest, hdr, tr, true, nil); err != nil { return 0, err } } if hdr.Name != WhiteoutOpaqueDir { continue } } path := filepath.Join(dest, hdr.Name) rel, err := filepath.Rel(dest, path) if err != nil { return 0, err } // Note as these operations are platform specific, so must the slash be. if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { return 0, breakoutError(fmt.Errorf("%q is outside of %q", hdr.Name, dest)) } base := filepath.Base(path) if strings.HasPrefix(base, WhiteoutPrefix) { dir := filepath.Dir(path) if base == WhiteoutOpaqueDir { _, err := os.Lstat(dir) if err != nil { return 0, err } err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { if os.IsNotExist(err) { err = nil // parent was deleted } return err } if path == dir { return nil } if _, exists := unpackedPaths[path]; !exists { err := os.RemoveAll(path) return err } return nil }) if err != nil { return 0, err } } else { originalBase := base[len(WhiteoutPrefix):] originalPath := filepath.Join(dir, originalBase) if err := os.RemoveAll(originalPath); err != nil { return 0, err } } } else { // If path exits we almost always just want to remove and replace it. // The only exception is when it is a directory *and* the file from // the layer is also a directory. Then we want to merge them (i.e. // just apply the metadata from the layer). if fi, err := os.Lstat(path); err == nil { if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) { if err := os.RemoveAll(path); err != nil { return 0, err } } } trBuf.Reset(tr) srcData := io.Reader(trBuf) srcHdr := hdr // Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so // we manually retarget these into the temporary files we extracted them into if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), WhiteoutLinkDir) { linkBasename := filepath.Base(hdr.Linkname) srcHdr = aufsHardlinks[linkBasename] if srcHdr == nil { return 0, fmt.Errorf("Invalid aufs hardlink") } tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename)) if err != nil { return 0, err } defer tmpFile.Close() srcData = tmpFile } // if the options contain a uid & gid maps, convert header uid/gid // entries using the maps such that lchown sets the proper mapped // uid/gid after writing the file. We only perform this mapping if // the file isn't already owned by the remapped root UID or GID, as // that specific uid/gid has no mapping from container -> host, and // those files already have the proper ownership for inside the // container. if srcHdr.Uid != remappedRootUID { xUID, err := idtools.ToHost(srcHdr.Uid, options.UIDMaps) if err != nil { return 0, err } srcHdr.Uid = xUID } if srcHdr.Gid != remappedRootGID { xGID, err := idtools.ToHost(srcHdr.Gid, options.GIDMaps) if err != nil { return 0, err } srcHdr.Gid = xGID } if err := createTarFile(path, dest, srcHdr, srcData, true, nil); err != nil { return 0, err } // Directory mtimes must be handled at the end to avoid further // file creation in them to modify the directory mtime if hdr.Typeflag == tar.TypeDir { dirs = append(dirs, hdr) } unpackedPaths[path] = struct{}{} } } for _, hdr := range dirs { path := filepath.Join(dest, hdr.Name) if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); err != nil { return 0, err } } return size, nil } // ApplyLayer parses a diff in the standard layer format from `layer`, // and applies it to the directory `dest`. The stream `layer` can be // compressed or uncompressed. // Returns the size in bytes of the contents of the layer. func ApplyLayer(dest string, layer Reader) (int64, error) { return applyLayerHandler(dest, layer, &TarOptions{}, true) } // ApplyUncompressedLayer parses a diff in the standard layer format from // `layer`, and applies it to the directory `dest`. The stream `layer` // can only be uncompressed. // Returns the size in bytes of the contents of the layer. func ApplyUncompressedLayer(dest string, layer Reader, options *TarOptions) (int64, error) { return applyLayerHandler(dest, layer, options, false) } // do the bulk load of ApplyLayer, but allow for not calling DecompressStream func applyLayerHandler(dest string, layer Reader, options *TarOptions, decompress bool) (int64, error) { dest = filepath.Clean(dest) // We need to be able to set any perms oldmask, err := system.Umask(0) if err != nil { return 0, err } defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform if decompress { layer, err = DecompressStream(layer) if err != nil { return 0, err } } return UnpackLayer(dest, layer, options) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/diff_test.go ================================================ package archive import ( "archive/tar" "io" "io/ioutil" "os" "path/filepath" "reflect" "testing" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" ) func TestApplyLayerInvalidFilenames(t *testing.T) { for i, headers := range [][]*tar.Header{ { { Name: "../victim/dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, { { // Note the leading slash Name: "/../victim/slash-dotdot", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidFilenames", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestApplyLayerInvalidHardlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeLink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeLink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (hardlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try reading victim/hello (hardlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // Try removing victim directory (hardlink) { Name: "loophole-victim", Typeflag: tar.TypeLink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidHardlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestApplyLayerInvalidSymlink(t *testing.T) { for i, headers := range [][]*tar.Header{ { // try reading victim/hello (../) { Name: "dotdot", Typeflag: tar.TypeSymlink, Linkname: "../victim/hello", Mode: 0644, }, }, { // try reading victim/hello (/../) { Name: "slash-dotdot", Typeflag: tar.TypeSymlink, // Note the leading slash Linkname: "/../victim/hello", Mode: 0644, }, }, { // try writing victim/file { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim/file", Typeflag: tar.TypeReg, Mode: 0644, }, }, { // try reading victim/hello (symlink, symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "symlink", Typeflag: tar.TypeSymlink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try reading victim/hello (symlink, hardlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "hardlink", Typeflag: tar.TypeLink, Linkname: "loophole-victim/hello", Mode: 0644, }, }, { // try removing victim directory (symlink) { Name: "loophole-victim", Typeflag: tar.TypeSymlink, Linkname: "../victim", Mode: 0755, }, { Name: "loophole-victim", Typeflag: tar.TypeReg, Mode: 0644, }, }, } { if err := testBreakout("applylayer", "docker-TestApplyLayerInvalidSymlink", headers); err != nil { t.Fatalf("i=%d. %v", i, err) } } } func TestApplyLayerWhiteouts(t *testing.T) { wd, err := ioutil.TempDir("", "graphdriver-test-whiteouts") if err != nil { return } defer os.RemoveAll(wd) base := []string{ ".baz", "bar/", "bar/bax", "bar/bay/", "baz", "foo/", "foo/.abc", "foo/.bcd/", "foo/.bcd/a", "foo/cde/", "foo/cde/def", "foo/cde/efg", "foo/fgh", "foobar", } type tcase struct { change, expected []string } tcases := []tcase{ { base, base, }, { []string{ ".bay", ".wh.baz", "foo/", "foo/.bce", "foo/.wh..wh..opq", "foo/cde/", "foo/cde/efg", }, []string{ ".bay", ".baz", "bar/", "bar/bax", "bar/bay/", "foo/", "foo/.bce", "foo/cde/", "foo/cde/efg", "foobar", }, }, { []string{ ".bay", ".wh..baz", ".wh.foobar", "foo/", "foo/.abc", "foo/.wh.cde", "bar/", }, []string{ ".bay", "bar/", "bar/bax", "bar/bay/", "foo/", "foo/.abc", "foo/.bce", }, }, { []string{ ".abc", ".wh..wh..opq", "foobar", }, []string{ ".abc", "foobar", }, }, } for i, tc := range tcases { l, err := makeTestLayer(tc.change) if err != nil { t.Fatal(err) } _, err = UnpackLayer(wd, l, nil) if err != nil { t.Fatal(err) } err = l.Close() if err != nil { t.Fatal(err) } paths, err := readDirContents(wd) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tc.expected, paths) { t.Fatalf("invalid files for layer %d: expected %q, got %q", i, tc.expected, paths) } } } func makeTestLayer(paths []string) (rc io.ReadCloser, err error) { tmpDir, err := ioutil.TempDir("", "graphdriver-test-mklayer") if err != nil { return } defer func() { if err != nil { os.RemoveAll(tmpDir) } }() for _, p := range paths { if p[len(p)-1] == filepath.Separator { if err = os.MkdirAll(filepath.Join(tmpDir, p), 0700); err != nil { return } } else { if err = ioutil.WriteFile(filepath.Join(tmpDir, p), nil, 0600); err != nil { return } } } archive, err := Tar(tmpDir, Uncompressed) if err != nil { return } return ioutils.NewReadCloserWrapper(archive, func() error { err := archive.Close() os.RemoveAll(tmpDir) return err }), nil } func readDirContents(root string) ([]string, error) { var files []string err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if path == root { return nil } rel, err := filepath.Rel(root, path) if err != nil { return err } if info.IsDir() { rel = rel + "/" } files = append(files, rel) return nil }) if err != nil { return nil, err } return files, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/example_changes.go ================================================ // +build ignore // Simple tool to create an archive stream from an old and new directory // // By default it will stream the comparison of two temporary directories with junk files package main import ( "flag" "fmt" "io" "io/ioutil" "os" "path" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive" ) var ( flDebug = flag.Bool("D", false, "debugging output") flNewDir = flag.String("newdir", "", "") flOldDir = flag.String("olddir", "", "") log = logrus.New() ) func main() { flag.Usage = func() { fmt.Println("Produce a tar from comparing two directory paths. By default a demo tar is created of around 200 files (including hardlinks)") fmt.Printf("%s [OPTIONS]\n", os.Args[0]) flag.PrintDefaults() } flag.Parse() log.Out = os.Stderr if (len(os.Getenv("DEBUG")) > 0) || *flDebug { logrus.SetLevel(logrus.DebugLevel) } var newDir, oldDir string if len(*flNewDir) == 0 { var err error newDir, err = ioutil.TempDir("", "docker-test-newDir") if err != nil { log.Fatal(err) } defer os.RemoveAll(newDir) if _, err := prepareUntarSourceDirectory(100, newDir, true); err != nil { log.Fatal(err) } } else { newDir = *flNewDir } if len(*flOldDir) == 0 { oldDir, err := ioutil.TempDir("", "docker-test-oldDir") if err != nil { log.Fatal(err) } defer os.RemoveAll(oldDir) } else { oldDir = *flOldDir } changes, err := archive.ChangesDirs(newDir, oldDir) if err != nil { log.Fatal(err) } a, err := archive.ExportChanges(newDir, changes) if err != nil { log.Fatal(err) } defer a.Close() i, err := io.Copy(os.Stdout, a) if err != nil && err != io.EOF { log.Fatal(err) } fmt.Fprintf(os.Stderr, "wrote archive of %d bytes", i) } func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { fileData := []byte("fooo") for n := 0; n < numberOfFiles; n++ { fileName := fmt.Sprintf("file-%d", n) if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { return 0, err } if makeLinks { if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { return 0, err } } } totalSize := numberOfFiles * len(fileData) return totalSize, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_linux.go ================================================ package archive import ( "syscall" "time" ) func timeToTimespec(time time.Time) (ts syscall.Timespec) { if time.IsZero() { // Return UTIME_OMIT special value ts.Sec = 0 ts.Nsec = ((1 << 30) - 2) return } return syscall.NsecToTimespec(time.UnixNano()) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/time_unsupported.go ================================================ // +build !linux package archive import ( "syscall" "time" ) func timeToTimespec(time time.Time) (ts syscall.Timespec) { nsec := int64(0) if !time.IsZero() { nsec = time.UnixNano() } return syscall.NsecToTimespec(nsec) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/utils_test.go ================================================ package archive import ( "archive/tar" "bytes" "fmt" "io" "io/ioutil" "os" "path/filepath" "time" ) var testUntarFns = map[string]func(string, io.Reader) error{ "untar": func(dest string, r io.Reader) error { return Untar(r, dest, nil) }, "applylayer": func(dest string, r io.Reader) error { _, err := ApplyLayer(dest, Reader(r)) return err }, } // testBreakout is a helper function that, within the provided `tmpdir` directory, // creates a `victim` folder with a generated `hello` file in it. // `untar` extracts to a directory named `dest`, the tar file created from `headers`. // // Here are the tested scenarios: // - removed `victim` folder (write) // - removed files from `victim` folder (write) // - new files in `victim` folder (write) // - modified files in `victim` folder (write) // - file in `dest` with same content as `victim/hello` (read) // // When using testBreakout make sure you cover one of the scenarios listed above. func testBreakout(untarFn string, tmpdir string, headers []*tar.Header) error { tmpdir, err := ioutil.TempDir("", tmpdir) if err != nil { return err } defer os.RemoveAll(tmpdir) dest := filepath.Join(tmpdir, "dest") if err := os.Mkdir(dest, 0755); err != nil { return err } victim := filepath.Join(tmpdir, "victim") if err := os.Mkdir(victim, 0755); err != nil { return err } hello := filepath.Join(victim, "hello") helloData, err := time.Now().MarshalText() if err != nil { return err } if err := ioutil.WriteFile(hello, helloData, 0644); err != nil { return err } helloStat, err := os.Stat(hello) if err != nil { return err } reader, writer := io.Pipe() go func() { t := tar.NewWriter(writer) for _, hdr := range headers { t.WriteHeader(hdr) } t.Close() }() untar := testUntarFns[untarFn] if untar == nil { return fmt.Errorf("could not find untar function %q in testUntarFns", untarFn) } if err := untar(dest, reader); err != nil { if _, ok := err.(breakoutError); !ok { // If untar returns an error unrelated to an archive breakout, // then consider this an unexpected error and abort. return err } // Here, untar detected the breakout. // Let's move on verifying that indeed there was no breakout. fmt.Printf("breakoutError: %v\n", err) } // Check victim folder f, err := os.Open(victim) if err != nil { // codepath taken if victim folder was removed return fmt.Errorf("archive breakout: error reading %q: %v", victim, err) } defer f.Close() // Check contents of victim folder // // We are only interested in getting 2 files from the victim folder, because if all is well // we expect only one result, the `hello` file. If there is a second result, it cannot // hold the same name `hello` and we assume that a new file got created in the victim folder. // That is enough to detect an archive breakout. names, err := f.Readdirnames(2) if err != nil { // codepath taken if victim is not a folder return fmt.Errorf("archive breakout: error reading directory content of %q: %v", victim, err) } for _, name := range names { if name != "hello" { // codepath taken if new file was created in victim folder return fmt.Errorf("archive breakout: new file %q", name) } } // Check victim/hello f, err = os.Open(hello) if err != nil { // codepath taken if read permissions were removed return fmt.Errorf("archive breakout: could not lstat %q: %v", hello, err) } defer f.Close() b, err := ioutil.ReadAll(f) if err != nil { return err } fi, err := f.Stat() if err != nil { return err } if helloStat.IsDir() != fi.IsDir() || // TODO: cannot check for fi.ModTime() change helloStat.Mode() != fi.Mode() || helloStat.Size() != fi.Size() || !bytes.Equal(helloData, b) { // codepath taken if hello has been modified return fmt.Errorf("archive breakout: file %q has been modified. Contents: expected=%q, got=%q. FileInfo: expected=%#v, got=%#v", hello, helloData, b, helloStat, fi) } // Check that nothing in dest/ has the same content as victim/hello. // Since victim/hello was generated with time.Now(), it is safe to assume // that any file whose content matches exactly victim/hello, managed somehow // to access victim/hello. return filepath.Walk(dest, func(path string, info os.FileInfo, err error) error { if info.IsDir() { if err != nil { // skip directory if error return filepath.SkipDir } // enter directory return nil } if err != nil { // skip file if error return nil } b, err := ioutil.ReadFile(path) if err != nil { // Houston, we have a problem. Aborting (space)walk. return err } if bytes.Equal(helloData, b) { return fmt.Errorf("archive breakout: file %q has been accessed via %q", hello, path) } return nil }) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/whiteouts.go ================================================ package archive // Whiteouts are files with a special meaning for the layered filesystem. // Docker uses AUFS whiteout files inside exported archives. In other // filesystems these files are generated/handled on tar creation/extraction. // WhiteoutPrefix prefix means file is a whiteout. If this is followed by a // filename this means that file has been removed from the base layer. const WhiteoutPrefix = ".wh." // WhiteoutMetaPrefix prefix means whiteout has a special meaning and is not // for removing an actual file. Normally these files are excluded from exported // archives. const WhiteoutMetaPrefix = WhiteoutPrefix + WhiteoutPrefix // WhiteoutLinkDir is a directory AUFS uses for storing hardlink links to other // layers. Normally these should not go into exported archives and all changed // hardlinks should be copied to the top layer. const WhiteoutLinkDir = WhiteoutMetaPrefix + "plnk" // WhiteoutOpaqueDir file means directory has been made opaque - meaning // readdir calls to this directory do not follow to lower layers. const WhiteoutOpaqueDir = WhiteoutMetaPrefix + ".opq" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap.go ================================================ package archive import ( "archive/tar" "bytes" "io/ioutil" ) // Generate generates a new archive from the content provided // as input. // // `files` is a sequence of path/content pairs. A new file is // added to the archive for each pair. // If the last pair is incomplete, the file is created with an // empty content. For example: // // Generate("foo.txt", "hello world", "emptyfile") // // The above call will return an archive with 2 files: // * ./foo.txt with content "hello world" // * ./empty with empty content // // FIXME: stream content instead of buffering // FIXME: specify permissions and other archive metadata func Generate(input ...string) (Archive, error) { files := parseStringPairs(input...) buf := new(bytes.Buffer) tw := tar.NewWriter(buf) for _, file := range files { name, content := file[0], file[1] hdr := &tar.Header{ Name: name, Size: int64(len(content)), } if err := tw.WriteHeader(hdr); err != nil { return nil, err } if _, err := tw.Write([]byte(content)); err != nil { return nil, err } } if err := tw.Close(); err != nil { return nil, err } return ioutil.NopCloser(buf), nil } func parseStringPairs(input ...string) (output [][2]string) { output = make([][2]string, 0, len(input)/2+1) for i := 0; i < len(input); i += 2 { var pair [2]string pair[0] = input[i] if i+1 < len(input) { pair[1] = input[i+1] } output = append(output, pair) } return } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive/wrap_test.go ================================================ package archive import ( "archive/tar" "bytes" "io" "testing" ) func TestGenerateEmptyFile(t *testing.T) { archive, err := Generate("emptyFile") if err != nil { t.Fatal(err) } if archive == nil { t.Fatal("The generated archive should not be nil.") } expectedFiles := [][]string{ {"emptyFile", ""}, } tr := tar.NewReader(archive) actualFiles := make([][]string, 0, 10) i := 0 for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } buf := new(bytes.Buffer) buf.ReadFrom(tr) content := buf.String() actualFiles = append(actualFiles, []string{hdr.Name, content}) i++ } if len(actualFiles) != len(expectedFiles) { t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) } for i := 0; i < len(expectedFiles); i++ { actual := actualFiles[i] expected := expectedFiles[i] if actual[0] != expected[0] { t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) } if actual[1] != expected[1] { t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) } } } func TestGenerateWithContent(t *testing.T) { archive, err := Generate("file", "content") if err != nil { t.Fatal(err) } if archive == nil { t.Fatal("The generated archive should not be nil.") } expectedFiles := [][]string{ {"file", "content"}, } tr := tar.NewReader(archive) actualFiles := make([][]string, 0, 10) i := 0 for { hdr, err := tr.Next() if err == io.EOF { break } if err != nil { t.Fatal(err) } buf := new(bytes.Buffer) buf.ReadFrom(tr) content := buf.String() actualFiles = append(actualFiles, []string{hdr.Name, content}) i++ } if len(actualFiles) != len(expectedFiles) { t.Fatalf("Number of expected file %d, got %d.", len(expectedFiles), len(actualFiles)) } for i := 0; i < len(expectedFiles); i++ { actual := actualFiles[i] expected := expectedFiles[i] if actual[0] != expected[0] { t.Fatalf("Expected name '%s', Actual name '%s'", expected[0], actual[0]) } if actual[1] != expected[1] { t.Fatalf("Expected content '%s', Actual content '%s'", expected[1], actual[1]) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils.go ================================================ package fileutils import ( "errors" "fmt" "io" "os" "path/filepath" "regexp" "strings" "text/scanner" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" ) // exclusion return true if the specified pattern is an exclusion func exclusion(pattern string) bool { return pattern[0] == '!' } // empty return true if the specified pattern is empty func empty(pattern string) bool { return pattern == "" } // CleanPatterns takes a slice of patterns returns a new // slice of patterns cleaned with filepath.Clean, stripped // of any empty patterns and lets the caller know whether the // slice contains any exception patterns (prefixed with !). func CleanPatterns(patterns []string) ([]string, [][]string, bool, error) { // Loop over exclusion patterns and: // 1. Clean them up. // 2. Indicate whether we are dealing with any exception rules. // 3. Error if we see a single exclusion marker on it's own (!). cleanedPatterns := []string{} patternDirs := [][]string{} exceptions := false for _, pattern := range patterns { // Eliminate leading and trailing whitespace. pattern = strings.TrimSpace(pattern) if empty(pattern) { continue } if exclusion(pattern) { if len(pattern) == 1 { return nil, nil, false, errors.New("Illegal exclusion pattern: !") } exceptions = true } pattern = filepath.Clean(pattern) cleanedPatterns = append(cleanedPatterns, pattern) if exclusion(pattern) { pattern = pattern[1:] } patternDirs = append(patternDirs, strings.Split(pattern, "/")) } return cleanedPatterns, patternDirs, exceptions, nil } // Matches returns true if file matches any of the patterns // and isn't excluded by any of the subsequent patterns. func Matches(file string, patterns []string) (bool, error) { file = filepath.Clean(file) if file == "." { // Don't let them exclude everything, kind of silly. return false, nil } patterns, patDirs, _, err := CleanPatterns(patterns) if err != nil { return false, err } return OptimizedMatches(file, patterns, patDirs) } // OptimizedMatches is basically the same as fileutils.Matches() but optimized for archive.go. // It will assume that the inputs have been preprocessed and therefore the function // doesn't need to do as much error checking and clean-up. This was done to avoid // repeating these steps on each file being checked during the archive process. // The more generic fileutils.Matches() can't make these assumptions. func OptimizedMatches(file string, patterns []string, patDirs [][]string) (bool, error) { matched := false parentPath := filepath.Dir(file) parentPathDirs := strings.Split(parentPath, "/") for i, pattern := range patterns { negative := false if exclusion(pattern) { negative = true pattern = pattern[1:] } match, err := regexpMatch(pattern, file) if err != nil { return false, fmt.Errorf("Error in pattern (%s): %s", pattern, err) } if !match && parentPath != "." { // Check to see if the pattern matches one of our parent dirs. if len(patDirs[i]) <= len(parentPathDirs) { match, _ = regexpMatch(strings.Join(patDirs[i], "/"), strings.Join(parentPathDirs[:len(patDirs[i])], "/")) } } if match { matched = !negative } } if matched { logrus.Debugf("Skipping excluded path: %s", file) } return matched, nil } // regexpMatch tries to match the logic of filepath.Match but // does so using regexp logic. We do this so that we can expand the // wildcard set to include other things, like "**" to mean any number // of directories. This means that we should be backwards compatible // with filepath.Match(). We'll end up supporting more stuff, due to // the fact that we're using regexp, but that's ok - it does no harm. func regexpMatch(pattern, path string) (bool, error) { regStr := "^" // Do some syntax checking on the pattern. // filepath's Match() has some really weird rules that are inconsistent // so instead of trying to dup their logic, just call Match() for its // error state and if there is an error in the pattern return it. // If this becomes an issue we can remove this since its really only // needed in the error (syntax) case - which isn't really critical. if _, err := filepath.Match(pattern, path); err != nil { return false, err } // Go through the pattern and convert it to a regexp. // We use a scanner so we can support utf-8 chars. var scan scanner.Scanner scan.Init(strings.NewReader(pattern)) sl := string(os.PathSeparator) escSL := sl if sl == `\` { escSL += `\` } for scan.Peek() != scanner.EOF { ch := scan.Next() if ch == '*' { if scan.Peek() == '*' { // is some flavor of "**" scan.Next() if scan.Peek() == scanner.EOF { // is "**EOF" - to align with .gitignore just accept all regStr += ".*" } else { // is "**" regStr += "((.*" + escSL + ")|([^" + escSL + "]*))" } // Treat **/ as ** so eat the "/" if string(scan.Peek()) == sl { scan.Next() } } else { // is "*" so map it to anything but "/" regStr += "[^" + escSL + "]*" } } else if ch == '?' { // "?" is any char except "/" regStr += "[^" + escSL + "]" } else if strings.Index(".$", string(ch)) != -1 { // Escape some regexp special chars that have no meaning // in golang's filepath.Match regStr += `\` + string(ch) } else if ch == '\\' { // escape next char. Note that a trailing \ in the pattern // will be left alone (but need to escape it) if sl == `\` { // On windows map "\" to "\\", meaning an escaped backslash, // and then just continue because filepath.Match on // Windows doesn't allow escaping at all regStr += escSL continue } if scan.Peek() != scanner.EOF { regStr += `\` + string(scan.Next()) } else { regStr += `\` } } else { regStr += string(ch) } } regStr += "$" res, err := regexp.MatchString(regStr, path) // Map regexp's error to filepath's so no one knows we're not using filepath if err != nil { err = filepath.ErrBadPattern } return res, err } // CopyFile copies from src to dst until either EOF is reached // on src or an error occurs. It verifies src exists and remove // the dst if it exists. func CopyFile(src, dst string) (int64, error) { cleanSrc := filepath.Clean(src) cleanDst := filepath.Clean(dst) if cleanSrc == cleanDst { return 0, nil } sf, err := os.Open(cleanSrc) if err != nil { return 0, err } defer sf.Close() if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { return 0, err } df, err := os.Create(cleanDst) if err != nil { return 0, err } defer df.Close() return io.Copy(df, sf) } // ReadSymlinkedDirectory returns the target directory of a symlink. // The target of the symbolic link may not be a file. func ReadSymlinkedDirectory(path string) (string, error) { var realPath string var err error if realPath, err = filepath.Abs(path); err != nil { return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) } if realPath, err = filepath.EvalSymlinks(realPath); err != nil { return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) } realPathInfo, err := os.Stat(realPath) if err != nil { return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) } if !realPathInfo.Mode().IsDir() { return "", fmt.Errorf("canonical path points to a file '%s'", realPath) } return realPath, nil } // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_test.go ================================================ package fileutils import ( "io/ioutil" "os" "path" "path/filepath" "runtime" "strings" "testing" ) // CopyFile with invalid src func TestCopyFileWithInvalidSrc(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } bytes, err := CopyFile("/invalid/file/path", path.Join(tempFolder, "dest")) if err == nil { t.Fatal("Should have fail to copy an invalid src file") } if bytes != 0 { t.Fatal("Should have written 0 bytes") } } // CopyFile with invalid dest func TestCopyFileWithInvalidDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } src := path.Join(tempFolder, "file") err = ioutil.WriteFile(src, []byte("content"), 0740) if err != nil { t.Fatal(err) } bytes, err := CopyFile(src, path.Join(tempFolder, "/invalid/dest/path")) if err == nil { t.Fatal("Should have fail to copy an invalid src file") } if bytes != 0 { t.Fatal("Should have written 0 bytes") } } // CopyFile with same src and dest func TestCopyFileWithSameSrcAndDest(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } file := path.Join(tempFolder, "file") err = ioutil.WriteFile(file, []byte("content"), 0740) if err != nil { t.Fatal(err) } bytes, err := CopyFile(file, file) if err != nil { t.Fatal(err) } if bytes != 0 { t.Fatal("Should have written 0 bytes as it is the same file.") } } // CopyFile with same src and dest but path is different and not clean func TestCopyFileWithSameSrcAndDestWithPathNameDifferent(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } testFolder := path.Join(tempFolder, "test") err = os.MkdirAll(testFolder, 0740) if err != nil { t.Fatal(err) } file := path.Join(testFolder, "file") sameFile := testFolder + "/../test/file" err = ioutil.WriteFile(file, []byte("content"), 0740) if err != nil { t.Fatal(err) } bytes, err := CopyFile(file, sameFile) if err != nil { t.Fatal(err) } if bytes != 0 { t.Fatal("Should have written 0 bytes as it is the same file.") } } func TestCopyFile(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) } src := path.Join(tempFolder, "src") dest := path.Join(tempFolder, "dest") ioutil.WriteFile(src, []byte("content"), 0777) ioutil.WriteFile(dest, []byte("destContent"), 0777) bytes, err := CopyFile(src, dest) if err != nil { t.Fatal(err) } if bytes != 7 { t.Fatalf("Should have written %d bytes but wrote %d", 7, bytes) } actual, err := ioutil.ReadFile(dest) if err != nil { t.Fatal(err) } if string(actual) != "content" { t.Fatalf("Dest content was '%s', expected '%s'", string(actual), "content") } } // Reading a symlink to a directory must return the directory func TestReadSymlinkedDirectoryExistingDirectory(t *testing.T) { var err error if err = os.Mkdir("/tmp/testReadSymlinkToExistingDirectory", 0777); err != nil { t.Errorf("failed to create directory: %s", err) } if err = os.Symlink("/tmp/testReadSymlinkToExistingDirectory", "/tmp/dirLinkTest"); err != nil { t.Errorf("failed to create symlink: %s", err) } var path string if path, err = ReadSymlinkedDirectory("/tmp/dirLinkTest"); err != nil { t.Fatalf("failed to read symlink to directory: %s", err) } if path != "/tmp/testReadSymlinkToExistingDirectory" { t.Fatalf("symlink returned unexpected directory: %s", path) } if err = os.Remove("/tmp/testReadSymlinkToExistingDirectory"); err != nil { t.Errorf("failed to remove temporary directory: %s", err) } if err = os.Remove("/tmp/dirLinkTest"); err != nil { t.Errorf("failed to remove symlink: %s", err) } } // Reading a non-existing symlink must fail func TestReadSymlinkedDirectoryNonExistingSymlink(t *testing.T) { var path string var err error if path, err = ReadSymlinkedDirectory("/tmp/test/foo/Non/ExistingPath"); err == nil { t.Fatalf("error expected for non-existing symlink") } if path != "" { t.Fatalf("expected empty path, but '%s' was returned", path) } } // Reading a symlink to a file must fail func TestReadSymlinkedDirectoryToFile(t *testing.T) { var err error var file *os.File if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil { t.Fatalf("failed to create file: %s", err) } file.Close() if err = os.Symlink("/tmp/testReadSymlinkToFile", "/tmp/fileLinkTest"); err != nil { t.Errorf("failed to create symlink: %s", err) } var path string if path, err = ReadSymlinkedDirectory("/tmp/fileLinkTest"); err == nil { t.Fatalf("ReadSymlinkedDirectory on a symlink to a file should've failed") } if path != "" { t.Fatalf("path should've been empty: %s", path) } if err = os.Remove("/tmp/testReadSymlinkToFile"); err != nil { t.Errorf("failed to remove file: %s", err) } if err = os.Remove("/tmp/fileLinkTest"); err != nil { t.Errorf("failed to remove symlink: %s", err) } } func TestWildcardMatches(t *testing.T) { match, _ := Matches("fileutils.go", []string{"*"}) if match != true { t.Errorf("failed to get a wildcard match, got %v", match) } } // A simple pattern match should return true. func TestPatternMatches(t *testing.T) { match, _ := Matches("fileutils.go", []string{"*.go"}) if match != true { t.Errorf("failed to get a match, got %v", match) } } // An exclusion followed by an inclusion should return true. func TestExclusionPatternMatchesPatternBefore(t *testing.T) { match, _ := Matches("fileutils.go", []string{"!fileutils.go", "*.go"}) if match != true { t.Errorf("failed to get true match on exclusion pattern, got %v", match) } } // A folder pattern followed by an exception should return false. func TestPatternMatchesFolderExclusions(t *testing.T) { match, _ := Matches("docs/README.md", []string{"docs", "!docs/README.md"}) if match != false { t.Errorf("failed to get a false match on exclusion pattern, got %v", match) } } // A folder pattern followed by an exception should return false. func TestPatternMatchesFolderWithSlashExclusions(t *testing.T) { match, _ := Matches("docs/README.md", []string{"docs/", "!docs/README.md"}) if match != false { t.Errorf("failed to get a false match on exclusion pattern, got %v", match) } } // A folder pattern followed by an exception should return false. func TestPatternMatchesFolderWildcardExclusions(t *testing.T) { match, _ := Matches("docs/README.md", []string{"docs/*", "!docs/README.md"}) if match != false { t.Errorf("failed to get a false match on exclusion pattern, got %v", match) } } // A pattern followed by an exclusion should return false. func TestExclusionPatternMatchesPatternAfter(t *testing.T) { match, _ := Matches("fileutils.go", []string{"*.go", "!fileutils.go"}) if match != false { t.Errorf("failed to get false match on exclusion pattern, got %v", match) } } // A filename evaluating to . should return false. func TestExclusionPatternMatchesWholeDirectory(t *testing.T) { match, _ := Matches(".", []string{"*.go"}) if match != false { t.Errorf("failed to get false match on ., got %v", match) } } // A single ! pattern should return an error. func TestSingleExclamationError(t *testing.T) { _, err := Matches("fileutils.go", []string{"!"}) if err == nil { t.Errorf("failed to get an error for a single exclamation point, got %v", err) } } // A string preceded with a ! should return true from Exclusion. func TestExclusion(t *testing.T) { exclusion := exclusion("!") if !exclusion { t.Errorf("failed to get true for a single !, got %v", exclusion) } } // Matches with no patterns func TestMatchesWithNoPatterns(t *testing.T) { matches, err := Matches("/any/path/there", []string{}) if err != nil { t.Fatal(err) } if matches { t.Fatalf("Should not have match anything") } } // Matches with malformed patterns func TestMatchesWithMalformedPatterns(t *testing.T) { matches, err := Matches("/any/path/there", []string{"["}) if err == nil { t.Fatal("Should have failed because of a malformed syntax in the pattern") } if matches { t.Fatalf("Should not have match anything") } } // Test lots of variants of patterns & strings func TestMatches(t *testing.T) { tests := []struct { pattern string text string pass bool }{ {"**", "file", true}, {"**", "file/", true}, {"**/", "file", true}, // weird one {"**/", "file/", true}, {"**", "/", true}, {"**/", "/", true}, {"**", "dir/file", true}, {"**/", "dir/file", false}, {"**", "dir/file/", true}, {"**/", "dir/file/", true}, {"**/**", "dir/file", true}, {"**/**", "dir/file/", true}, {"dir/**", "dir/file", true}, {"dir/**", "dir/file/", true}, {"dir/**", "dir/dir2/file", true}, {"dir/**", "dir/dir2/file/", true}, {"**/dir2/*", "dir/dir2/file", true}, {"**/dir2/*", "dir/dir2/file/", false}, {"**/dir2/**", "dir/dir2/dir3/file", true}, {"**/dir2/**", "dir/dir2/dir3/file/", true}, {"**file", "file", true}, {"**file", "dir/file", true}, {"**/file", "dir/file", true}, {"**file", "dir/dir/file", true}, {"**/file", "dir/dir/file", true}, {"**/file*", "dir/dir/file", true}, {"**/file*", "dir/dir/file.txt", true}, {"**/file*txt", "dir/dir/file.txt", true}, {"**/file*.txt", "dir/dir/file.txt", true}, {"**/file*.txt*", "dir/dir/file.txt", true}, {"**/**/*.txt", "dir/dir/file.txt", true}, {"**/**/*.txt2", "dir/dir/file.txt", false}, {"**/*.txt", "file.txt", true}, {"**/**/*.txt", "file.txt", true}, {"a**/*.txt", "a/file.txt", true}, {"a**/*.txt", "a/dir/file.txt", true}, {"a**/*.txt", "a/dir/dir/file.txt", true}, {"a/*.txt", "a/dir/file.txt", false}, {"a/*.txt", "a/file.txt", true}, {"a/*.txt**", "a/file.txt", true}, {"a[b-d]e", "ae", false}, {"a[b-d]e", "ace", true}, {"a[b-d]e", "aae", false}, {"a[^b-d]e", "aze", true}, {".*", ".foo", true}, {".*", "foo", false}, {"abc.def", "abcdef", false}, {"abc.def", "abc.def", true}, {"abc.def", "abcZdef", false}, {"abc?def", "abcZdef", true}, {"abc?def", "abcdef", false}, {"a\\*b", "a*b", true}, {"a\\", "a", false}, {"a\\", "a\\", false}, {"a\\\\", "a\\", true}, {"**/foo/bar", "foo/bar", true}, {"**/foo/bar", "dir/foo/bar", true}, {"**/foo/bar", "dir/dir2/foo/bar", true}, {"abc/**", "abc", false}, {"abc/**", "abc/def", true}, {"abc/**", "abc/def/ghi", true}, } for _, test := range tests { res, _ := regexpMatch(test.pattern, test.text) if res != test.pass { t.Fatalf("Failed: %v - res:%v", test, res) } } } // An empty string should return true from Empty. func TestEmpty(t *testing.T) { empty := empty("") if !empty { t.Errorf("failed to get true for an empty string, got %v", empty) } } func TestCleanPatterns(t *testing.T) { cleaned, _, _, _ := CleanPatterns([]string{"docs", "config"}) if len(cleaned) != 2 { t.Errorf("expected 2 element slice, got %v", len(cleaned)) } } func TestCleanPatternsStripEmptyPatterns(t *testing.T) { cleaned, _, _, _ := CleanPatterns([]string{"docs", "config", ""}) if len(cleaned) != 2 { t.Errorf("expected 2 element slice, got %v", len(cleaned)) } } func TestCleanPatternsExceptionFlag(t *testing.T) { _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md"}) if !exceptions { t.Errorf("expected exceptions to be true, got %v", exceptions) } } func TestCleanPatternsLeadingSpaceTrimmed(t *testing.T) { _, _, exceptions, _ := CleanPatterns([]string{"docs", " !docs/README.md"}) if !exceptions { t.Errorf("expected exceptions to be true, got %v", exceptions) } } func TestCleanPatternsTrailingSpaceTrimmed(t *testing.T) { _, _, exceptions, _ := CleanPatterns([]string{"docs", "!docs/README.md "}) if !exceptions { t.Errorf("expected exceptions to be true, got %v", exceptions) } } func TestCleanPatternsErrorSingleException(t *testing.T) { _, _, _, err := CleanPatterns([]string{"!"}) if err == nil { t.Errorf("expected error on single exclamation point, got %v", err) } } func TestCleanPatternsFolderSplit(t *testing.T) { _, dirs, _, _ := CleanPatterns([]string{"docs/config/CONFIG.md"}) if dirs[0][0] != "docs" { t.Errorf("expected first element in dirs slice to be docs, got %v", dirs[0][1]) } if dirs[0][1] != "config" { t.Errorf("expected first element in dirs slice to be config, got %v", dirs[0][1]) } } func TestCreateIfNotExistsDir(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) folderToCreate := filepath.Join(tempFolder, "tocreate") if err := CreateIfNotExists(folderToCreate, true); err != nil { t.Fatal(err) } fileinfo, err := os.Stat(folderToCreate) if err != nil { t.Fatalf("Should have create a folder, got %v", err) } if !fileinfo.IsDir() { t.Fatalf("Should have been a dir, seems it's not") } } func TestCreateIfNotExistsFile(t *testing.T) { tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempFolder) fileToCreate := filepath.Join(tempFolder, "file/to/create") if err := CreateIfNotExists(fileToCreate, false); err != nil { t.Fatal(err) } fileinfo, err := os.Stat(fileToCreate) if err != nil { t.Fatalf("Should have create a file, got %v", err) } if fileinfo.IsDir() { t.Fatalf("Should have been a file, seems it's not") } } // These matchTests are stolen from go's filepath Match tests. type matchTest struct { pattern, s string match bool err error } var matchTests = []matchTest{ {"abc", "abc", true, nil}, {"*", "abc", true, nil}, {"*c", "abc", true, nil}, {"a*", "a", true, nil}, {"a*", "abc", true, nil}, {"a*", "ab/c", false, nil}, {"a*/b", "abc/b", true, nil}, {"a*/b", "a/c/b", false, nil}, {"a*b*c*d*e*/f", "axbxcxdxe/f", true, nil}, {"a*b*c*d*e*/f", "axbxcxdxexxx/f", true, nil}, {"a*b*c*d*e*/f", "axbxcxdxe/xxx/f", false, nil}, {"a*b*c*d*e*/f", "axbxcxdxexxx/fff", false, nil}, {"a*b?c*x", "abxbbxdbxebxczzx", true, nil}, {"a*b?c*x", "abxbbxdbxebxczzy", false, nil}, {"ab[c]", "abc", true, nil}, {"ab[b-d]", "abc", true, nil}, {"ab[e-g]", "abc", false, nil}, {"ab[^c]", "abc", false, nil}, {"ab[^b-d]", "abc", false, nil}, {"ab[^e-g]", "abc", true, nil}, {"a\\*b", "a*b", true, nil}, {"a\\*b", "ab", false, nil}, {"a?b", "a☺b", true, nil}, {"a[^a]b", "a☺b", true, nil}, {"a???b", "a☺b", false, nil}, {"a[^a][^a][^a]b", "a☺b", false, nil}, {"[a-ζ]*", "α", true, nil}, {"*[a-ζ]", "A", false, nil}, {"a?b", "a/b", false, nil}, {"a*b", "a/b", false, nil}, {"[\\]a]", "]", true, nil}, {"[\\-]", "-", true, nil}, {"[x\\-]", "x", true, nil}, {"[x\\-]", "-", true, nil}, {"[x\\-]", "z", false, nil}, {"[\\-x]", "x", true, nil}, {"[\\-x]", "-", true, nil}, {"[\\-x]", "a", false, nil}, {"[]a]", "]", false, filepath.ErrBadPattern}, {"[-]", "-", false, filepath.ErrBadPattern}, {"[x-]", "x", false, filepath.ErrBadPattern}, {"[x-]", "-", false, filepath.ErrBadPattern}, {"[x-]", "z", false, filepath.ErrBadPattern}, {"[-x]", "x", false, filepath.ErrBadPattern}, {"[-x]", "-", false, filepath.ErrBadPattern}, {"[-x]", "a", false, filepath.ErrBadPattern}, {"\\", "a", false, filepath.ErrBadPattern}, {"[a-b-c]", "a", false, filepath.ErrBadPattern}, {"[", "a", false, filepath.ErrBadPattern}, {"[^", "a", false, filepath.ErrBadPattern}, {"[^bc", "a", false, filepath.ErrBadPattern}, {"a[", "a", false, filepath.ErrBadPattern}, // was nil but IMO its wrong {"a[", "ab", false, filepath.ErrBadPattern}, {"*x", "xxx", true, nil}, } func errp(e error) string { if e == nil { return "" } return e.Error() } // TestMatch test's our version of filepath.Match, called regexpMatch. func TestMatch(t *testing.T) { for _, tt := range matchTests { pattern := tt.pattern s := tt.s if runtime.GOOS == "windows" { if strings.Index(pattern, "\\") >= 0 { // no escape allowed on windows. continue } pattern = filepath.Clean(pattern) s = filepath.Clean(s) } ok, err := regexpMatch(pattern, s) if ok != tt.match || err != tt.err { t.Fatalf("Match(%#q, %#q) = %v, %q want %v, %q", pattern, s, ok, errp(err), tt.match, errp(tt.err)) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_unix.go ================================================ // +build linux freebsd package fileutils import ( "fmt" "io/ioutil" "os" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" ) // GetTotalUsedFds Returns the number of used File Descriptors by // reading it via /proc filesystem. func GetTotalUsedFds() int { if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) } else { return len(fds) } return -1 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils/fileutils_windows.go ================================================ package fileutils // GetTotalUsedFds Returns the number of used File Descriptors. Not supported // on Windows. func GetTotalUsedFds() int { return -1 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir.go ================================================ package homedir import ( "os" "runtime" "github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user" ) // Key returns the env var name for the user's home dir based on // the platform being run on func Key() string { if runtime.GOOS == "windows" { return "USERPROFILE" } return "HOME" } // Get returns the home directory of the current user with the help of // environment variables depending on the target operating system. // Returned path should be used with "path/filepath" to form new paths. func Get() string { home := os.Getenv(Key()) if home == "" && runtime.GOOS != "windows" { if u, err := user.CurrentUser(); err == nil { return u.Home } } return home } // GetShortcutString returns the string that is shortcut to user's home directory // in the native shell of the platform running on. func GetShortcutString() string { if runtime.GOOS == "windows" { return "%USERPROFILE%" // be careful while using in format functions } return "~" } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/homedir/homedir_test.go ================================================ package homedir import ( "path/filepath" "testing" ) func TestGet(t *testing.T) { home := Get() if home == "" { t.Fatal("returned home directory is empty") } if !filepath.IsAbs(home) { t.Fatalf("returned path is not absolute: %s", home) } } func TestGetShortcutString(t *testing.T) { shortcut := GetShortcutString() if shortcut == "" { t.Fatal("returned shortcut string is empty") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools.go ================================================ package idtools import ( "bufio" "fmt" "os" "sort" "strconv" "strings" ) // IDMap contains a single entry for user namespace range remapping. An array // of IDMap entries represents the structure that will be provided to the Linux // kernel for creating a user namespace. type IDMap struct { ContainerID int `json:"container_id"` HostID int `json:"host_id"` Size int `json:"size"` } type subIDRange struct { Start int Length int } type ranges []subIDRange func (e ranges) Len() int { return len(e) } func (e ranges) Swap(i, j int) { e[i], e[j] = e[j], e[i] } func (e ranges) Less(i, j int) bool { return e[i].Start < e[j].Start } const ( subuidFileName string = "/etc/subuid" subgidFileName string = "/etc/subgid" ) // MkdirAllAs creates a directory (include any along the path) and then modifies // ownership to the requested uid/gid. If the directory already exists, this // function will still change ownership to the requested uid/gid pair. func MkdirAllAs(path string, mode os.FileMode, ownerUID, ownerGID int) error { return mkdirAs(path, mode, ownerUID, ownerGID, true, true) } // 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 { return mkdirAs(path, mode, ownerUID, ownerGID, true, false) } // MkdirAs creates a directory and then modifies ownership to the requested uid/gid. // If the directory already exists, this function still changes ownership func MkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int) error { return mkdirAs(path, mode, ownerUID, ownerGID, false, true) } // GetRootUIDGID retrieves the remapped root uid/gid pair from the set of maps. // If the maps are empty, then the root uid/gid will default to "real" 0/0 func GetRootUIDGID(uidMap, gidMap []IDMap) (int, int, error) { var uid, gid int if uidMap != nil { xUID, err := ToHost(0, uidMap) if err != nil { return -1, -1, err } uid = xUID } if gidMap != nil { xGID, err := ToHost(0, gidMap) if err != nil { return -1, -1, err } gid = xGID } return uid, gid, nil } // ToContainer takes an id mapping, and uses it to translate a // host ID to the remapped ID. If no map is provided, then the translation // assumes a 1-to-1 mapping and returns the passed in id func ToContainer(hostID int, idMap []IDMap) (int, error) { if idMap == nil { return hostID, nil } for _, m := range idMap { if (hostID >= m.HostID) && (hostID <= (m.HostID + m.Size - 1)) { contID := m.ContainerID + (hostID - m.HostID) return contID, nil } } return -1, fmt.Errorf("Host ID %d cannot be mapped to a container ID", hostID) } // ToHost takes an id mapping and a remapped ID, and translates the // ID to the mapped host ID. If no map is provided, then the translation // assumes a 1-to-1 mapping and returns the passed in id # func ToHost(contID int, idMap []IDMap) (int, error) { if idMap == nil { return contID, nil } for _, m := range idMap { if (contID >= m.ContainerID) && (contID <= (m.ContainerID + m.Size - 1)) { hostID := m.HostID + (contID - m.ContainerID) return hostID, nil } } return -1, fmt.Errorf("Container ID %d cannot be mapped to a host ID", contID) } // CreateIDMappings takes a requested user and group name and // using the data from /etc/sub{uid,gid} ranges, creates the // proper uid and gid remapping ranges for that user/group pair func CreateIDMappings(username, groupname string) ([]IDMap, []IDMap, error) { subuidRanges, err := parseSubuid(username) if err != nil { return nil, nil, err } subgidRanges, err := parseSubgid(groupname) if err != nil { return nil, nil, err } if len(subuidRanges) == 0 { return nil, nil, fmt.Errorf("No subuid ranges found for user %q", username) } if len(subgidRanges) == 0 { return nil, nil, fmt.Errorf("No subgid ranges found for group %q", groupname) } return createIDMap(subuidRanges), createIDMap(subgidRanges), nil } func createIDMap(subidRanges ranges) []IDMap { idMap := []IDMap{} // sort the ranges by lowest ID first sort.Sort(subidRanges) containerID := 0 for _, idrange := range subidRanges { idMap = append(idMap, IDMap{ ContainerID: containerID, HostID: idrange.Start, Size: idrange.Length, }) containerID = containerID + idrange.Length } return idMap } func parseSubuid(username string) (ranges, error) { return parseSubidFile(subuidFileName, username) } func parseSubgid(username string) (ranges, error) { return parseSubidFile(subgidFileName, username) } func parseSubidFile(path, username string) (ranges, error) { var rangeList ranges subidFile, err := os.Open(path) if err != nil { return rangeList, err } defer subidFile.Close() s := bufio.NewScanner(subidFile) for s.Scan() { if err := s.Err(); err != nil { return rangeList, err } text := strings.TrimSpace(s.Text()) if text == "" { continue } parts := strings.Split(text, ":") if len(parts) != 3 { return rangeList, fmt.Errorf("Cannot parse subuid/gid information: Format not correct for %s file", path) } if parts[0] == username { // return the first entry for a user; ignores potential for multiple ranges per user startid, err := strconv.Atoi(parts[1]) if err != nil { return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) } length, err := strconv.Atoi(parts[2]) if err != nil { return rangeList, fmt.Errorf("String to int conversion failed during subuid/gid parsing of %s: %v", path, err) } rangeList = append(rangeList, subIDRange{startid, length}) } } return rangeList, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix.go ================================================ // +build !windows package idtools import ( "os" "path/filepath" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) 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 && chownExisting { if err := os.Chown(path, ownerUID, ownerGID); err != nil { return err } // short-circuit--we were called with an existing directory and chown was requested return nil } else if err == nil { // nothing to do; directory path fully exists already and chown was NOT requested return nil } if mkAll { // 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 := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) { return err } } else { if err := os.Mkdir(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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_unix_test.go ================================================ // +build !windows package idtools import ( "fmt" "io/ioutil" "os" "path/filepath" "syscall" "testing" ) type node struct { uid int gid int } func TestMkdirAllAs(t *testing.T) { dirName, err := ioutil.TempDir("", "mkdirall") if err != nil { t.Fatalf("Couldn't create temp dir: %v", err) } defer os.RemoveAll(dirName) testTree := map[string]node{ "usr": {0, 0}, "usr/bin": {0, 0}, "lib": {33, 33}, "lib/x86_64": {45, 45}, "lib/x86_64/share": {1, 1}, } if err := buildTree(dirName, testTree); err != nil { t.Fatal(err) } // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid if err := MkdirAllAs(filepath.Join(dirName, "usr", "share"), 0755, 99, 99); err != nil { t.Fatal(err) } testTree["usr/share"] = node{99, 99} verifyTree, err := readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } // test 2-deep new directories--both should be owned by the uid/gid pair if err := MkdirAllAs(filepath.Join(dirName, "lib", "some", "other"), 0755, 101, 101); err != nil { t.Fatal(err) } testTree["lib/some"] = node{101, 101} testTree["lib/some/other"] = node{101, 101} verifyTree, err = readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } // test a directory that already exists; should be chowned, but nothing else if err := MkdirAllAs(filepath.Join(dirName, "usr"), 0755, 102, 102); err != nil { t.Fatal(err) } testTree["usr"] = node{102, 102} verifyTree, err = readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } } func TestMkdirAllNewAs(t *testing.T) { dirName, err := ioutil.TempDir("", "mkdirnew") if err != nil { t.Fatalf("Couldn't create temp dir: %v", err) } defer os.RemoveAll(dirName) testTree := map[string]node{ "usr": {0, 0}, "usr/bin": {0, 0}, "lib": {33, 33}, "lib/x86_64": {45, 45}, "lib/x86_64/share": {1, 1}, } if err := buildTree(dirName, testTree); err != nil { t.Fatal(err) } // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid if err := MkdirAllNewAs(filepath.Join(dirName, "usr", "share"), 0755, 99, 99); err != nil { t.Fatal(err) } testTree["usr/share"] = node{99, 99} verifyTree, err := readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } // test 2-deep new directories--both should be owned by the uid/gid pair if err := MkdirAllNewAs(filepath.Join(dirName, "lib", "some", "other"), 0755, 101, 101); err != nil { t.Fatal(err) } testTree["lib/some"] = node{101, 101} testTree["lib/some/other"] = node{101, 101} verifyTree, err = readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } // test a directory that already exists; should NOT be chowned if err := MkdirAllNewAs(filepath.Join(dirName, "usr"), 0755, 102, 102); err != nil { t.Fatal(err) } verifyTree, err = readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } } func TestMkdirAs(t *testing.T) { dirName, err := ioutil.TempDir("", "mkdir") if err != nil { t.Fatalf("Couldn't create temp dir: %v", err) } defer os.RemoveAll(dirName) testTree := map[string]node{ "usr": {0, 0}, } if err := buildTree(dirName, testTree); err != nil { t.Fatal(err) } // test a directory that already exists; should just chown to the requested uid/gid if err := MkdirAs(filepath.Join(dirName, "usr"), 0755, 99, 99); err != nil { t.Fatal(err) } testTree["usr"] = node{99, 99} verifyTree, err := readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } // create a subdir under a dir which doesn't exist--should fail if err := MkdirAs(filepath.Join(dirName, "usr", "bin", "subdir"), 0755, 102, 102); err == nil { t.Fatalf("Trying to create a directory with Mkdir where the parent doesn't exist should have failed") } // create a subdir under an existing dir; should only change the ownership of the new subdir if err := MkdirAs(filepath.Join(dirName, "usr", "bin"), 0755, 102, 102); err != nil { t.Fatal(err) } testTree["usr/bin"] = node{102, 102} verifyTree, err = readTree(dirName, "") if err != nil { t.Fatal(err) } if err := compareTrees(testTree, verifyTree); err != nil { t.Fatal(err) } } func buildTree(base string, tree map[string]node) error { for path, node := range tree { fullPath := filepath.Join(base, path) if err := os.MkdirAll(fullPath, 0755); err != nil { return fmt.Errorf("Couldn't create path: %s; error: %v", fullPath, err) } if err := os.Chown(fullPath, node.uid, node.gid); err != nil { return fmt.Errorf("Couldn't chown path: %s; error: %v", fullPath, err) } } return nil } func readTree(base, root string) (map[string]node, error) { tree := make(map[string]node) dirInfos, err := ioutil.ReadDir(base) if err != nil { return nil, fmt.Errorf("Couldn't read directory entries for %q: %v", base, err) } for _, info := range dirInfos { s := &syscall.Stat_t{} if err := syscall.Stat(filepath.Join(base, info.Name()), s); err != nil { return nil, fmt.Errorf("Can't stat file %q: %v", filepath.Join(base, info.Name()), err) } tree[filepath.Join(root, info.Name())] = node{int(s.Uid), int(s.Gid)} if info.IsDir() { // read the subdirectory subtree, err := readTree(filepath.Join(base, info.Name()), filepath.Join(root, info.Name())) if err != nil { return nil, err } for path, nodeinfo := range subtree { tree[path] = nodeinfo } } } return tree, nil } func compareTrees(left, right map[string]node) error { if len(left) != len(right) { return fmt.Errorf("Trees aren't the same size") } for path, nodeLeft := range left { if nodeRight, ok := right[path]; ok { if nodeRight.uid != nodeLeft.uid || nodeRight.gid != nodeLeft.gid { // mismatch return fmt.Errorf("mismatched ownership for %q: expected: %d:%d, got: %d:%d", path, nodeLeft.uid, nodeLeft.gid, nodeRight.uid, nodeRight.gid) } continue } return fmt.Errorf("right tree didn't contain path %q", path) } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/idtools_windows.go ================================================ // +build windows package idtools import ( "os" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system" ) // Platforms such as Windows do not support the UID/GID concept. So make this // just a wrapper around system.MkdirAll. func mkdirAs(path string, mode os.FileMode, ownerUID, ownerGID int, mkAll, chownExisting bool) error { if err := system.MkdirAll(path, mode); err != nil && !os.IsExist(err) { return err } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go ================================================ package idtools import ( "fmt" "os/exec" "path/filepath" "strings" "syscall" ) // add a user and/or group to Linux /etc/passwd, /etc/group using standard // Linux distribution commands: // adduser --uid --shell /bin/login --no-create-home --disabled-login --ingroup // useradd -M -u -s /bin/nologin -N -g // addgroup --gid // groupadd -g const baseUID int = 10000 const baseGID int = 10000 const idMAX int = 65534 var ( userCommand string groupCommand string cmdTemplates = map[string]string{ "adduser": "--uid %d --shell /bin/false --no-create-home --disabled-login --ingroup %s %s", "useradd": "-M -u %d -s /bin/false -N -g %s %s", "addgroup": "--gid %d %s", "groupadd": "-g %d %s", } ) func init() { // set up which commands are used for adding users/groups dependent on distro if _, err := resolveBinary("adduser"); err == nil { userCommand = "adduser" } else if _, err := resolveBinary("useradd"); err == nil { userCommand = "useradd" } if _, err := resolveBinary("addgroup"); err == nil { groupCommand = "addgroup" } else if _, err := resolveBinary("groupadd"); err == nil { groupCommand = "groupadd" } } func resolveBinary(binname string) (string, error) { binaryPath, err := exec.LookPath(binname) if err != nil { return "", err } resolvedPath, err := filepath.EvalSymlinks(binaryPath) if err != nil { return "", err } //only return no error if the final resolved binary basename //matches what was searched for if filepath.Base(resolvedPath) == binname { return resolvedPath, nil } return "", fmt.Errorf("Binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) } // AddNamespaceRangesUser takes a name and finds an unused uid, gid pair // and calls the appropriate helper function to add the group and then // the user to the group in /etc/group and /etc/passwd respectively. // This new user's /etc/sub{uid,gid} ranges will be used for user namespace // mapping ranges in containers. func AddNamespaceRangesUser(name string) (int, int, error) { // Find unused uid, gid pair uid, err := findUnusedUID(baseUID) if err != nil { return -1, -1, fmt.Errorf("Unable to find unused UID: %v", err) } gid, err := findUnusedGID(baseGID) if err != nil { return -1, -1, fmt.Errorf("Unable to find unused GID: %v", err) } // First add the group that we will use if err := addGroup(name, gid); err != nil { return -1, -1, fmt.Errorf("Error adding group %q: %v", name, err) } // Add the user as a member of the group if err := addUser(name, uid, name); err != nil { return -1, -1, fmt.Errorf("Error adding user %q: %v", name, err) } return uid, gid, nil } func addUser(userName string, uid int, groupName string) error { if userCommand == "" { return fmt.Errorf("Cannot add user; no useradd/adduser binary found") } args := fmt.Sprintf(cmdTemplates[userCommand], uid, groupName, userName) return execAddCmd(userCommand, args) } func addGroup(groupName string, gid int) error { if groupCommand == "" { return fmt.Errorf("Cannot add group; no groupadd/addgroup binary found") } args := fmt.Sprintf(cmdTemplates[groupCommand], gid, groupName) // only error out if the error isn't that the group already exists // if the group exists then our needs are already met if err := execAddCmd(groupCommand, args); err != nil && !strings.Contains(err.Error(), "already exists") { return err } return nil } func execAddCmd(cmd, args string) error { execCmd := exec.Command(cmd, strings.Split(args, " ")...) out, err := execCmd.CombinedOutput() if err != nil { return fmt.Errorf("Failed to add user/group with error: %v; output: %q", err, string(out)) } return nil } func findUnusedUID(startUID int) (int, error) { return findUnused("passwd", startUID) } func findUnusedGID(startGID int) (int, error) { return findUnused("group", startGID) } func findUnused(file string, id int) (int, error) { for { cmdStr := fmt.Sprintf("cat /etc/%s | cut -d: -f3 | grep '^%d$'", file, id) cmd := exec.Command("sh", "-c", cmdStr) if err := cmd.Run(); err != nil { // if a non-zero return code occurs, then we know the ID was not found // and is usable if exiterr, ok := err.(*exec.ExitError); ok { // The program has exited with an exit code != 0 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { if status.ExitStatus() == 1 { //no match, we can use this ID return id, nil } } } return -1, fmt.Errorf("Error looking in /etc/%s for unused ID: %v", file, err) } id++ if id > idMAX { return -1, fmt.Errorf("Maximum id in %q reached with finding unused numeric ID", file) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go ================================================ // +build !linux package idtools import "fmt" // AddNamespaceRangesUser takes a name and finds an unused uid, gid pair // and calls the appropriate helper function to add the group and then // the user to the group in /etc/group and /etc/passwd respectively. func AddNamespaceRangesUser(name string) (int, int, error) { return -1, -1, fmt.Errorf("No support for adding users or groups on this OS") } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe.go ================================================ package ioutils import ( "errors" "io" "sync" ) // maxCap is the highest capacity to use in byte slices that buffer data. const maxCap = 1e6 // blockThreshold is the minimum number of bytes in the buffer which will cause // a write to BytesPipe to block when allocating a new slice. const blockThreshold = 1e6 // ErrClosed is returned when Write is called on a closed BytesPipe. var ErrClosed = errors.New("write to closed BytesPipe") // BytesPipe is io.ReadWriteCloser which works similarly to pipe(queue). // All written data may be read at most once. Also, BytesPipe allocates // and releases new byte slices to adjust to current needs, so the buffer // won't be overgrown after peak loads. type BytesPipe struct { mu sync.Mutex wait *sync.Cond buf [][]byte // slice of byte-slices of buffered data lastRead int // index in the first slice to a read point bufLen int // length of data buffered over the slices closeErr error // error to return from next Read. set to nil if not closed. } // NewBytesPipe creates new BytesPipe, initialized by specified slice. // If buf is nil, then it will be initialized with slice which cap is 64. // buf will be adjusted in a way that len(buf) == 0, cap(buf) == cap(buf). func NewBytesPipe(buf []byte) *BytesPipe { if cap(buf) == 0 { buf = make([]byte, 0, 64) } bp := &BytesPipe{ buf: [][]byte{buf[:0]}, } bp.wait = sync.NewCond(&bp.mu) return bp } // Write writes p to BytesPipe. // It can allocate new []byte slices in a process of writing. func (bp *BytesPipe) Write(p []byte) (int, error) { bp.mu.Lock() defer bp.mu.Unlock() written := 0 for { if bp.closeErr != nil { return written, ErrClosed } // write data to the last buffer b := bp.buf[len(bp.buf)-1] // copy data to the current empty allocated area n := copy(b[len(b):cap(b)], p) // increment buffered data length bp.bufLen += n // include written data in last buffer bp.buf[len(bp.buf)-1] = b[:len(b)+n] written += n // if there was enough room to write all then break if len(p) == n { break } // more data: write to the next slice p = p[n:] // block if too much data is still in the buffer for bp.bufLen >= blockThreshold { bp.wait.Wait() } // allocate slice that has twice the size of the last unless maximum reached nextCap := 2 * cap(bp.buf[len(bp.buf)-1]) if nextCap > maxCap { nextCap = maxCap } // add new byte slice to the buffers slice and continue writing bp.buf = append(bp.buf, make([]byte, 0, nextCap)) } bp.wait.Broadcast() return written, nil } // CloseWithError causes further reads from a BytesPipe to return immediately. func (bp *BytesPipe) CloseWithError(err error) error { bp.mu.Lock() if err != nil { bp.closeErr = err } else { bp.closeErr = io.EOF } bp.wait.Broadcast() bp.mu.Unlock() return nil } // Close causes further reads from a BytesPipe to return immediately. func (bp *BytesPipe) Close() error { return bp.CloseWithError(nil) } func (bp *BytesPipe) len() int { return bp.bufLen - bp.lastRead } // Read reads bytes from BytesPipe. // Data could be read only once. func (bp *BytesPipe) Read(p []byte) (n int, err error) { bp.mu.Lock() defer bp.mu.Unlock() if bp.len() == 0 { if bp.closeErr != nil { return 0, bp.closeErr } bp.wait.Wait() if bp.len() == 0 && bp.closeErr != nil { return 0, bp.closeErr } } for { read := copy(p, bp.buf[0][bp.lastRead:]) n += read bp.lastRead += read if bp.len() == 0 { // we have read everything. reset to the beginning. bp.lastRead = 0 bp.bufLen -= len(bp.buf[0]) bp.buf[0] = bp.buf[0][:0] break } // break if everything was read if len(p) == read { break } // more buffered data and more asked. read from next slice. p = p[read:] bp.lastRead = 0 bp.bufLen -= len(bp.buf[0]) bp.buf[0] = nil // throw away old slice bp.buf = bp.buf[1:] // switch to next } bp.wait.Broadcast() return } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/bytespipe_test.go ================================================ package ioutils import ( "crypto/sha1" "encoding/hex" "math/rand" "testing" "time" ) func TestBytesPipeRead(t *testing.T) { buf := NewBytesPipe(nil) buf.Write([]byte("12")) buf.Write([]byte("34")) buf.Write([]byte("56")) buf.Write([]byte("78")) buf.Write([]byte("90")) rd := make([]byte, 4) n, err := buf.Read(rd) if err != nil { t.Fatal(err) } if n != 4 { t.Fatalf("Wrong number of bytes read: %d, should be %d", n, 4) } if string(rd) != "1234" { t.Fatalf("Read %s, but must be %s", rd, "1234") } n, err = buf.Read(rd) if err != nil { t.Fatal(err) } if n != 4 { t.Fatalf("Wrong number of bytes read: %d, should be %d", n, 4) } if string(rd) != "5678" { t.Fatalf("Read %s, but must be %s", rd, "5679") } n, err = buf.Read(rd) if err != nil { t.Fatal(err) } if n != 2 { t.Fatalf("Wrong number of bytes read: %d, should be %d", n, 2) } if string(rd[:n]) != "90" { t.Fatalf("Read %s, but must be %s", rd, "90") } } func TestBytesPipeWrite(t *testing.T) { buf := NewBytesPipe(nil) buf.Write([]byte("12")) buf.Write([]byte("34")) buf.Write([]byte("56")) buf.Write([]byte("78")) buf.Write([]byte("90")) if string(buf.buf[0]) != "1234567890" { t.Fatalf("Buffer %s, must be %s", buf.buf, "1234567890") } } // Write and read in different speeds/chunk sizes and check valid data is read. func TestBytesPipeWriteRandomChunks(t *testing.T) { cases := []struct{ iterations, writesPerLoop, readsPerLoop int }{ {100, 10, 1}, {1000, 10, 5}, {1000, 100, 0}, {1000, 5, 6}, {10000, 50, 25}, } testMessage := []byte("this is a random string for testing") // random slice sizes to read and write writeChunks := []int{25, 35, 15, 20} readChunks := []int{5, 45, 20, 25} for _, c := range cases { // first pass: write directly to hash hash := sha1.New() for i := 0; i < c.iterations*c.writesPerLoop; i++ { if _, err := hash.Write(testMessage[:writeChunks[i%len(writeChunks)]]); err != nil { t.Fatal(err) } } expected := hex.EncodeToString(hash.Sum(nil)) // write/read through buffer buf := NewBytesPipe(nil) hash.Reset() done := make(chan struct{}) go func() { // random delay before read starts <-time.After(time.Duration(rand.Intn(10)) * time.Millisecond) for i := 0; ; i++ { p := make([]byte, readChunks[(c.iterations*c.readsPerLoop+i)%len(readChunks)]) n, _ := buf.Read(p) if n == 0 { break } hash.Write(p[:n]) } close(done) }() for i := 0; i < c.iterations; i++ { for w := 0; w < c.writesPerLoop; w++ { buf.Write(testMessage[:writeChunks[(i*c.writesPerLoop+w)%len(writeChunks)]]) } } buf.Close() <-done actual := hex.EncodeToString(hash.Sum(nil)) if expected != actual { t.Fatalf("BytesPipe returned invalid data. Expected checksum %v, got %v", expected, actual) } } } func BenchmarkBytesPipeWrite(b *testing.B) { for i := 0; i < b.N; i++ { readBuf := make([]byte, 1024) buf := NewBytesPipe(nil) go func() { var err error for err == nil { _, err = buf.Read(readBuf) } }() for j := 0; j < 1000; j++ { buf.Write([]byte("pretty short line, because why not?")) } buf.Close() } } func BenchmarkBytesPipeRead(b *testing.B) { rd := make([]byte, 512) for i := 0; i < b.N; i++ { b.StopTimer() buf := NewBytesPipe(nil) for j := 0; j < 500; j++ { buf.Write(make([]byte, 1024)) } b.StartTimer() for j := 0; j < 1000; j++ { if n, _ := buf.Read(rd); n != 512 { b.Fatalf("Wrong number of bytes: %d", n) } } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt.go ================================================ package ioutils import ( "fmt" "io" ) // FprintfIfNotEmpty prints the string value if it's not empty func FprintfIfNotEmpty(w io.Writer, format, value string) (int, error) { if value != "" { return fmt.Fprintf(w, format, value) } return 0, nil } // FprintfIfTrue prints the boolean value if it's true func FprintfIfTrue(w io.Writer, format string, ok bool) (int, error) { if ok { return fmt.Fprintf(w, format, ok) } return 0, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/fmt_test.go ================================================ package ioutils import "testing" func TestFprintfIfNotEmpty(t *testing.T) { wc := NewWriteCounter(&NopWriter{}) n, _ := FprintfIfNotEmpty(wc, "foo%s", "") if wc.Count != 0 || n != 0 { t.Errorf("Wrong count: %v vs. %v vs. 0", wc.Count, n) } n, _ = FprintfIfNotEmpty(wc, "foo%s", "bar") if wc.Count != 6 || n != 6 { t.Errorf("Wrong count: %v vs. %v vs. 6", wc.Count, n) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader.go ================================================ package ioutils import ( "bytes" "fmt" "io" "os" ) type pos struct { idx int offset int64 } type multiReadSeeker struct { readers []io.ReadSeeker pos *pos posIdx map[io.ReadSeeker]int } func (r *multiReadSeeker) Seek(offset int64, whence int) (int64, error) { var tmpOffset int64 switch whence { case os.SEEK_SET: for i, rdr := range r.readers { // get size of the current reader s, err := rdr.Seek(0, os.SEEK_END) if err != nil { return -1, err } if offset > tmpOffset+s { if i == len(r.readers)-1 { rdrOffset := s + (offset - tmpOffset) if _, err := rdr.Seek(rdrOffset, os.SEEK_SET); err != nil { return -1, err } r.pos = &pos{i, rdrOffset} return offset, nil } tmpOffset += s continue } rdrOffset := offset - tmpOffset idx := i rdr.Seek(rdrOffset, os.SEEK_SET) // make sure all following readers are at 0 for _, rdr := range r.readers[i+1:] { rdr.Seek(0, os.SEEK_SET) } if rdrOffset == s && i != len(r.readers)-1 { idx++ rdrOffset = 0 } r.pos = &pos{idx, rdrOffset} return offset, nil } case os.SEEK_END: for _, rdr := range r.readers { s, err := rdr.Seek(0, os.SEEK_END) if err != nil { return -1, err } tmpOffset += s } r.Seek(tmpOffset+offset, os.SEEK_SET) return tmpOffset + offset, nil case os.SEEK_CUR: if r.pos == nil { return r.Seek(offset, os.SEEK_SET) } // Just return the current offset if offset == 0 { return r.getCurOffset() } curOffset, err := r.getCurOffset() if err != nil { return -1, err } rdr, rdrOffset, err := r.getReaderForOffset(curOffset + offset) if err != nil { return -1, err } r.pos = &pos{r.posIdx[rdr], rdrOffset} return curOffset + offset, nil default: return -1, fmt.Errorf("Invalid whence: %d", whence) } return -1, fmt.Errorf("Error seeking for whence: %d, offset: %d", whence, offset) } func (r *multiReadSeeker) getReaderForOffset(offset int64) (io.ReadSeeker, int64, error) { var rdr io.ReadSeeker var rdrOffset int64 for i, rdr := range r.readers { offsetTo, err := r.getOffsetToReader(rdr) if err != nil { return nil, -1, err } if offsetTo > offset { rdr = r.readers[i-1] rdrOffset = offsetTo - offset break } if rdr == r.readers[len(r.readers)-1] { rdrOffset = offsetTo + offset break } } return rdr, rdrOffset, nil } func (r *multiReadSeeker) getCurOffset() (int64, error) { var totalSize int64 for _, rdr := range r.readers[:r.pos.idx+1] { if r.posIdx[rdr] == r.pos.idx { totalSize += r.pos.offset break } size, err := getReadSeekerSize(rdr) if err != nil { return -1, fmt.Errorf("error getting seeker size: %v", err) } totalSize += size } return totalSize, nil } func (r *multiReadSeeker) getOffsetToReader(rdr io.ReadSeeker) (int64, error) { var offset int64 for _, r := range r.readers { if r == rdr { break } size, err := getReadSeekerSize(rdr) if err != nil { return -1, err } offset += size } return offset, nil } func (r *multiReadSeeker) Read(b []byte) (int, error) { if r.pos == nil { r.pos = &pos{0, 0} } bCap := int64(cap(b)) buf := bytes.NewBuffer(nil) var rdr io.ReadSeeker for _, rdr = range r.readers[r.pos.idx:] { readBytes, err := io.CopyN(buf, rdr, bCap) if err != nil && err != io.EOF { return -1, err } bCap -= readBytes if bCap == 0 { break } } rdrPos, err := rdr.Seek(0, os.SEEK_CUR) if err != nil { return -1, err } r.pos = &pos{r.posIdx[rdr], rdrPos} return buf.Read(b) } func getReadSeekerSize(rdr io.ReadSeeker) (int64, error) { // save the current position pos, err := rdr.Seek(0, os.SEEK_CUR) if err != nil { return -1, err } // get the size size, err := rdr.Seek(0, os.SEEK_END) if err != nil { return -1, err } // reset the position if _, err := rdr.Seek(pos, os.SEEK_SET); err != nil { return -1, err } return size, nil } // MultiReadSeeker returns a ReadSeeker that's the logical concatenation of the provided // input readseekers. After calling this method the initial position is set to the // beginning of the first ReadSeeker. At the end of a ReadSeeker, Read always advances // to the beginning of the next ReadSeeker and returns EOF at the end of the last ReadSeeker. // Seek can be used over the sum of lengths of all readseekers. // // When a MultiReadSeeker is used, no Read and Seek operations should be made on // its ReadSeeker components. Also, users should make no assumption on the state // of individual readseekers while the MultiReadSeeker is used. func MultiReadSeeker(readers ...io.ReadSeeker) io.ReadSeeker { if len(readers) == 1 { return readers[0] } idx := make(map[io.ReadSeeker]int) for i, rdr := range readers { idx[rdr] = i } return &multiReadSeeker{ readers: readers, posIdx: idx, } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/multireader_test.go ================================================ package ioutils import ( "bytes" "fmt" "io" "io/ioutil" "os" "strings" "testing" ) func TestMultiReadSeekerReadAll(t *testing.T) { str := "hello world" s1 := strings.NewReader(str + " 1") s2 := strings.NewReader(str + " 2") s3 := strings.NewReader(str + " 3") mr := MultiReadSeeker(s1, s2, s3) expectedSize := int64(s1.Len() + s2.Len() + s3.Len()) b, err := ioutil.ReadAll(mr) if err != nil { t.Fatal(err) } expected := "hello world 1hello world 2hello world 3" if string(b) != expected { t.Fatalf("ReadAll failed, got: %q, expected %q", string(b), expected) } size, err := mr.Seek(0, os.SEEK_END) if err != nil { t.Fatal(err) } if size != expectedSize { t.Fatalf("reader size does not match, got %d, expected %d", size, expectedSize) } // Reset the position and read again pos, err := mr.Seek(0, os.SEEK_SET) if err != nil { t.Fatal(err) } if pos != 0 { t.Fatalf("expected position to be set to 0, got %d", pos) } b, err = ioutil.ReadAll(mr) if err != nil { t.Fatal(err) } if string(b) != expected { t.Fatalf("ReadAll failed, got: %q, expected %q", string(b), expected) } } func TestMultiReadSeekerReadEach(t *testing.T) { str := "hello world" s1 := strings.NewReader(str + " 1") s2 := strings.NewReader(str + " 2") s3 := strings.NewReader(str + " 3") mr := MultiReadSeeker(s1, s2, s3) var totalBytes int64 for i, s := range []*strings.Reader{s1, s2, s3} { sLen := int64(s.Len()) buf := make([]byte, s.Len()) expected := []byte(fmt.Sprintf("%s %d", str, i+1)) if _, err := mr.Read(buf); err != nil && err != io.EOF { t.Fatal(err) } if !bytes.Equal(buf, expected) { t.Fatalf("expected %q to be %q", string(buf), string(expected)) } pos, err := mr.Seek(0, os.SEEK_CUR) if err != nil { t.Fatalf("iteration: %d, error: %v", i+1, err) } // check that the total bytes read is the current position of the seeker totalBytes += sLen if pos != totalBytes { t.Fatalf("expected current position to be: %d, got: %d, iteration: %d", totalBytes, pos, i+1) } // This tests not only that SEEK_SET and SEEK_CUR give the same values, but that the next iteration is in the expected position as well newPos, err := mr.Seek(pos, os.SEEK_SET) if err != nil { t.Fatal(err) } if newPos != pos { t.Fatalf("expected to get same position when calling SEEK_SET with value from SEEK_CUR, cur: %d, set: %d", pos, newPos) } } } func TestMultiReadSeekerReadSpanningChunks(t *testing.T) { str := "hello world" s1 := strings.NewReader(str + " 1") s2 := strings.NewReader(str + " 2") s3 := strings.NewReader(str + " 3") mr := MultiReadSeeker(s1, s2, s3) buf := make([]byte, s1.Len()+3) _, err := mr.Read(buf) if err != nil { t.Fatal(err) } // expected is the contents of s1 + 3 bytes from s2, ie, the `hel` at the end of this string expected := "hello world 1hel" if string(buf) != expected { t.Fatalf("expected %s to be %s", string(buf), expected) } } func TestMultiReadSeekerNegativeSeek(t *testing.T) { str := "hello world" s1 := strings.NewReader(str + " 1") s2 := strings.NewReader(str + " 2") s3 := strings.NewReader(str + " 3") mr := MultiReadSeeker(s1, s2, s3) s1Len := s1.Len() s2Len := s2.Len() s3Len := s3.Len() s, err := mr.Seek(int64(-1*s3.Len()), os.SEEK_END) if err != nil { t.Fatal(err) } if s != int64(s1Len+s2Len) { t.Fatalf("expected %d to be %d", s, s1.Len()+s2.Len()) } buf := make([]byte, s3Len) if _, err := mr.Read(buf); err != nil && err != io.EOF { t.Fatal(err) } expected := fmt.Sprintf("%s %d", str, 3) if string(buf) != fmt.Sprintf("%s %d", str, 3) { t.Fatalf("expected %q to be %q", string(buf), expected) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers.go ================================================ package ioutils import ( "crypto/sha256" "encoding/hex" "io" "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" ) type readCloserWrapper struct { io.Reader closer func() error } func (r *readCloserWrapper) Close() error { return r.closer() } // NewReadCloserWrapper returns a new io.ReadCloser. func NewReadCloserWrapper(r io.Reader, closer func() error) io.ReadCloser { return &readCloserWrapper{ Reader: r, closer: closer, } } type readerErrWrapper struct { reader io.Reader closer func() } func (r *readerErrWrapper) Read(p []byte) (int, error) { n, err := r.reader.Read(p) if err != nil { r.closer() } return n, err } // NewReaderErrWrapper returns a new io.Reader. func NewReaderErrWrapper(r io.Reader, closer func()) io.Reader { return &readerErrWrapper{ reader: r, closer: closer, } } // HashData returns the sha256 sum of src. func HashData(src io.Reader) (string, error) { h := sha256.New() if _, err := io.Copy(h, src); err != nil { return "", err } return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil } // OnEOFReader wraps a io.ReadCloser and a function // the function will run at the end of file or close the file. 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 } // Close closes the file and run the function. 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 } } // cancelReadCloser wraps an io.ReadCloser with a context for cancelling read // operations. type cancelReadCloser struct { cancel func() pR *io.PipeReader // Stream to read from pW *io.PipeWriter } // NewCancelReadCloser creates a wrapper that closes the ReadCloser when the // context is cancelled. The returned io.ReadCloser must be closed when it is // no longer needed. func NewCancelReadCloser(ctx context.Context, in io.ReadCloser) io.ReadCloser { pR, pW := io.Pipe() // Create a context used to signal when the pipe is closed doneCtx, cancel := context.WithCancel(context.Background()) p := &cancelReadCloser{ cancel: cancel, pR: pR, pW: pW, } go func() { _, err := io.Copy(pW, in) select { case <-ctx.Done(): // If the context was closed, p.closeWithError // was already called. Calling it again would // change the error that Read returns. default: p.closeWithError(err) } in.Close() }() go func() { for { select { case <-ctx.Done(): p.closeWithError(ctx.Err()) case <-doneCtx.Done(): return } } }() return p } // Read wraps the Read method of the pipe that provides data from the wrapped // ReadCloser. func (p *cancelReadCloser) Read(buf []byte) (n int, err error) { return p.pR.Read(buf) } // closeWithError closes the wrapper and its underlying reader. It will // cause future calls to Read to return err. func (p *cancelReadCloser) closeWithError(err error) { p.pW.CloseWithError(err) p.cancel() } // Close closes the wrapper its underlying reader. It will cause // future calls to Read to return io.EOF. func (p *cancelReadCloser) Close() error { p.closeWithError(io.EOF) return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/readers_test.go ================================================ package ioutils import ( "fmt" "io/ioutil" "strings" "testing" "time" "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" ) // Implement io.Reader type errorReader struct{} func (r *errorReader) Read(p []byte) (int, error) { return 0, fmt.Errorf("Error reader always fail.") } func TestReadCloserWrapperClose(t *testing.T) { reader := strings.NewReader("A string reader") wrapper := NewReadCloserWrapper(reader, func() error { return fmt.Errorf("This will be called when closing") }) err := wrapper.Close() if err == nil || !strings.Contains(err.Error(), "This will be called when closing") { t.Fatalf("readCloserWrapper should have call the anonymous func and thus, fail.") } } func TestReaderErrWrapperReadOnError(t *testing.T) { called := false reader := &errorReader{} wrapper := NewReaderErrWrapper(reader, func() { called = true }) _, err := wrapper.Read([]byte{}) if err == nil || !strings.Contains(err.Error(), "Error reader always fail.") { t.Fatalf("readErrWrapper should returned an error") } if !called { t.Fatalf("readErrWrapper should have call the anonymous function on failure") } } func TestReaderErrWrapperRead(t *testing.T) { reader := strings.NewReader("a string reader.") wrapper := NewReaderErrWrapper(reader, func() { t.Fatalf("readErrWrapper should not have called the anonymous function") }) // Read 20 byte (should be ok with the string above) num, err := wrapper.Read(make([]byte, 20)) if err != nil { t.Fatal(err) } if num != 16 { t.Fatalf("readerErrWrapper should have read 16 byte, but read %d", num) } } func TestHashData(t *testing.T) { reader := strings.NewReader("hash-me") actual, err := HashData(reader) if err != nil { t.Fatal(err) } expected := "sha256:4d11186aed035cc624d553e10db358492c84a7cd6b9670d92123c144930450aa" if actual != expected { t.Fatalf("Expecting %s, got %s", expected, actual) } } type perpetualReader struct{} func (p *perpetualReader) Read(buf []byte) (n int, err error) { for i := 0; i != len(buf); i++ { buf[i] = 'a' } return len(buf), nil } func TestCancelReadCloser(t *testing.T) { ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) cancelReadCloser := NewCancelReadCloser(ctx, ioutil.NopCloser(&perpetualReader{})) for { var buf [128]byte _, err := cancelReadCloser.Read(buf[:]) if err == context.DeadlineExceeded { break } else if err != nil { t.Fatalf("got unexpected error: %v", err) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler.go ================================================ // +build !gccgo package ioutils func callSchedulerIfNecessary() { } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/scheduler_gccgo.go ================================================ // +build gccgo package ioutils import ( "runtime" ) func callSchedulerIfNecessary() { //allow or force Go scheduler to switch context, without explicitly //forcing this will make it hang when using gccgo implementation runtime.Gosched() } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_unix.go ================================================ // +build !windows package ioutils import "io/ioutil" // TempDir on Unix systems is equivalent to ioutil.TempDir. func TempDir(dir, prefix string) (string, error) { return ioutil.TempDir(dir, prefix) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/temp_windows.go ================================================ // +build windows package ioutils import ( "io/ioutil" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath" ) // TempDir is the equivalent of ioutil.TempDir, except that the result is in Windows longpath format. func TempDir(dir, prefix string) (string, error) { tempDir, err := ioutil.TempDir(dir, prefix) if err != nil { return "", err } return longpath.AddPrefix(tempDir), nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writeflusher.go ================================================ package ioutils import ( "errors" "io" "net/http" "sync" ) // WriteFlusher wraps the Write and Flush operation ensuring that every write // is a flush. In addition, the Close method can be called to intercept // Read/Write calls if the targets lifecycle has already ended. type WriteFlusher struct { mu sync.Mutex w io.Writer flusher http.Flusher flushed bool closed error // TODO(stevvooe): Use channel for closed instead, remove mutex. Using a // channel will allow one to properly order the operations. } var errWriteFlusherClosed = errors.New("writeflusher: closed") func (wf *WriteFlusher) Write(b []byte) (n int, err error) { wf.mu.Lock() defer wf.mu.Unlock() if wf.closed != nil { return 0, wf.closed } n, err = wf.w.Write(b) wf.flush() // every write is a flush. return n, err } // Flush the stream immediately. func (wf *WriteFlusher) Flush() { wf.mu.Lock() defer wf.mu.Unlock() wf.flush() } // flush the stream immediately without taking a lock. Used internally. func (wf *WriteFlusher) flush() { if wf.closed != nil { return } wf.flushed = true wf.flusher.Flush() } // Flushed returns the state of flushed. // If it's flushed, return true, or else it return false. func (wf *WriteFlusher) Flushed() bool { // BUG(stevvooe): Remove this method. Its use is inherently racy. Seems to // be used to detect whether or a response code has been issued or not. // Another hook should be used instead. wf.mu.Lock() defer wf.mu.Unlock() return wf.flushed } // Close closes the write flusher, disallowing any further writes to the // target. After the flusher is closed, all calls to write or flush will // result in an error. func (wf *WriteFlusher) Close() error { wf.mu.Lock() defer wf.mu.Unlock() if wf.closed != nil { return wf.closed } wf.closed = errWriteFlusherClosed return nil } // NewWriteFlusher returns a new WriteFlusher. func NewWriteFlusher(w io.Writer) *WriteFlusher { var flusher http.Flusher if f, ok := w.(http.Flusher); ok { flusher = f } else { flusher = &NopFlusher{} } return &WriteFlusher{w: w, flusher: flusher} } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers.go ================================================ package ioutils import "io" // NopWriter represents a type which write operation is nop. type NopWriter struct{} func (*NopWriter) Write(buf []byte) (int, error) { return len(buf), nil } type nopWriteCloser struct { io.Writer } func (w *nopWriteCloser) Close() error { return nil } // NopWriteCloser returns a nopWriteCloser. func NopWriteCloser(w io.Writer) io.WriteCloser { return &nopWriteCloser{w} } // NopFlusher represents a type which flush operation is nop. type NopFlusher struct{} // Flush is a nop operation. func (f *NopFlusher) Flush() {} type writeCloserWrapper struct { io.Writer closer func() error } func (r *writeCloserWrapper) Close() error { return r.closer() } // NewWriteCloserWrapper returns a new io.WriteCloser. func NewWriteCloserWrapper(r io.Writer, closer func() error) io.WriteCloser { return &writeCloserWrapper{ Writer: r, closer: closer, } } // WriteCounter wraps a concrete io.Writer and hold a count of the number // of bytes written to the writer during a "session". // This can be convenient when write return is masked // (e.g., json.Encoder.Encode()) type WriteCounter struct { Count int64 Writer io.Writer } // NewWriteCounter returns a new WriteCounter. func NewWriteCounter(w io.Writer) *WriteCounter { return &WriteCounter{ Writer: w, } } func (wc *WriteCounter) Write(p []byte) (count int, err error) { count, err = wc.Writer.Write(p) wc.Count += int64(count) return } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils/writers_test.go ================================================ package ioutils import ( "bytes" "strings" "testing" ) func TestWriteCloserWrapperClose(t *testing.T) { called := false writer := bytes.NewBuffer([]byte{}) wrapper := NewWriteCloserWrapper(writer, func() error { called = true return nil }) if err := wrapper.Close(); err != nil { t.Fatal(err) } if !called { t.Fatalf("writeCloserWrapper should have call the anonymous function.") } } func TestNopWriteCloser(t *testing.T) { writer := bytes.NewBuffer([]byte{}) wrapper := NopWriteCloser(writer) if err := wrapper.Close(); err != nil { t.Fatal("NopWriteCloser always return nil on Close.") } } func TestNopWriter(t *testing.T) { nw := &NopWriter{} l, err := nw.Write([]byte{'c'}) if err != nil { t.Fatal(err) } if l != 1 { t.Fatalf("Expected 1 got %d", l) } } func TestWriteCounter(t *testing.T) { dummy1 := "This is a dummy string." dummy2 := "This is another dummy string." totalLength := int64(len(dummy1) + len(dummy2)) reader1 := strings.NewReader(dummy1) reader2 := strings.NewReader(dummy2) var buffer bytes.Buffer wc := NewWriteCounter(&buffer) reader1.WriteTo(wc) reader2.WriteTo(wc) if wc.Count != totalLength { t.Errorf("Wrong count: %d vs. %d", wc.Count, totalLength) } if buffer.String() != dummy1+dummy2 { t.Error("Wrong message written") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath.go ================================================ // longpath introduces some constants and helper functions for handling long paths // in Windows, which are expected to be prepended with `\\?\` and followed by either // a drive letter, a UNC server\share, or a volume identifier. package longpath import ( "strings" ) // Prefix is the longpath prefix for Windows file paths. const Prefix = `\\?\` // AddPrefix will add the Windows long path prefix to the path provided if // it does not already have it. func AddPrefix(path string) string { if !strings.HasPrefix(path, Prefix) { if strings.HasPrefix(path, `\\`) { // This is a UNC path, so we need to add 'UNC' to the path as well. path = Prefix + `UNC` + path[1:] } else { path = Prefix + path } } return path } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/longpath/longpath_test.go ================================================ package longpath import ( "strings" "testing" ) func TestStandardLongPath(t *testing.T) { c := `C:\simple\path` longC := AddPrefix(c) if !strings.EqualFold(longC, `\\?\C:\simple\path`) { t.Errorf("Wrong long path returned. Original = %s ; Long = %s", c, longC) } } func TestUNCLongPath(t *testing.T) { c := `\\server\share\path` longC := AddPrefix(c) if !strings.EqualFold(longC, `\\?\UNC\server\share\path`) { t.Errorf("Wrong UNC long path returned. Original = %s ; Long = %s", c, longC) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools.go ================================================ // Package pools provides a collection of pools which provide various // data types with buffers. These can be used to lower the number of // memory allocations and reuse buffers. // // New pools should be added to this package to allow them to be // shared across packages. // // Utility functions which operate on pools should be added to this // package to allow them to be reused. package pools import ( "bufio" "io" "sync" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/ioutils" ) var ( // BufioReader32KPool is a pool which returns bufio.Reader with a 32K buffer. BufioReader32KPool *BufioReaderPool // BufioWriter32KPool is a pool which returns bufio.Writer with a 32K buffer. BufioWriter32KPool *BufioWriterPool ) const buffer32K = 32 * 1024 // BufioReaderPool is a bufio reader that uses sync.Pool. type BufioReaderPool struct { pool sync.Pool } func init() { BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K) BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K) } // newBufioReaderPoolWithSize is unexported because new pools should be // added here to be shared where required. func newBufioReaderPoolWithSize(size int) *BufioReaderPool { pool := sync.Pool{ New: func() interface{} { return bufio.NewReaderSize(nil, size) }, } return &BufioReaderPool{pool: pool} } // Get returns a bufio.Reader which reads from r. The buffer size is that of the pool. func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader { buf := bufPool.pool.Get().(*bufio.Reader) buf.Reset(r) return buf } // Put puts the bufio.Reader back into the pool. func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { b.Reset(nil) bufPool.pool.Put(b) } // Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy. func Copy(dst io.Writer, src io.Reader) (written int64, err error) { buf := BufioReader32KPool.Get(src) written, err = io.Copy(dst, buf) BufioReader32KPool.Put(buf) return } // NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back // into the pool and closes the reader if it's an io.ReadCloser. func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser { return ioutils.NewReadCloserWrapper(r, func() error { if readCloser, ok := r.(io.ReadCloser); ok { readCloser.Close() } bufPool.Put(buf) return nil }) } // BufioWriterPool is a bufio writer that uses sync.Pool. type BufioWriterPool struct { pool sync.Pool } // newBufioWriterPoolWithSize is unexported because new pools should be // added here to be shared where required. func newBufioWriterPoolWithSize(size int) *BufioWriterPool { pool := sync.Pool{ New: func() interface{} { return bufio.NewWriterSize(nil, size) }, } return &BufioWriterPool{pool: pool} } // Get returns a bufio.Writer which writes to w. The buffer size is that of the pool. func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer { buf := bufPool.pool.Get().(*bufio.Writer) buf.Reset(w) return buf } // Put puts the bufio.Writer back into the pool. func (bufPool *BufioWriterPool) Put(b *bufio.Writer) { b.Reset(nil) bufPool.pool.Put(b) } // NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back // into the pool and closes the writer if it's an io.Writecloser. func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser { return ioutils.NewWriteCloserWrapper(w, func() error { buf.Flush() if writeCloser, ok := w.(io.WriteCloser); ok { writeCloser.Close() } bufPool.Put(buf) return nil }) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/pools/pools_test.go ================================================ package pools import ( "bufio" "bytes" "io" "strings" "testing" ) func TestBufioReaderPoolGetWithNoReaderShouldCreateOne(t *testing.T) { reader := BufioReader32KPool.Get(nil) if reader == nil { t.Fatalf("BufioReaderPool should have create a bufio.Reader but did not.") } } func TestBufioReaderPoolPutAndGet(t *testing.T) { sr := bufio.NewReader(strings.NewReader("foobar")) reader := BufioReader32KPool.Get(sr) if reader == nil { t.Fatalf("BufioReaderPool should not return a nil reader.") } // verify the first 3 byte buf1 := make([]byte, 3) _, err := reader.Read(buf1) if err != nil { t.Fatal(err) } if actual := string(buf1); actual != "foo" { t.Fatalf("The first letter should have been 'foo' but was %v", actual) } BufioReader32KPool.Put(reader) // Try to read the next 3 bytes _, err = sr.Read(make([]byte, 3)) if err == nil || err != io.EOF { t.Fatalf("The buffer should have been empty, issue an EOF error.") } } type simpleReaderCloser struct { io.Reader closed bool } func (r *simpleReaderCloser) Close() error { r.closed = true return nil } func TestNewReadCloserWrapperWithAReadCloser(t *testing.T) { br := bufio.NewReader(strings.NewReader("")) sr := &simpleReaderCloser{ Reader: strings.NewReader("foobar"), closed: false, } reader := BufioReader32KPool.NewReadCloserWrapper(br, sr) if reader == nil { t.Fatalf("NewReadCloserWrapper should not return a nil reader.") } // Verify the content of reader buf := make([]byte, 3) _, err := reader.Read(buf) if err != nil { t.Fatal(err) } if actual := string(buf); actual != "foo" { t.Fatalf("The first 3 letter should have been 'foo' but were %v", actual) } reader.Close() // Read 3 more bytes "bar" _, err = reader.Read(buf) if err != nil { t.Fatal(err) } if actual := string(buf); actual != "bar" { t.Fatalf("The first 3 letter should have been 'bar' but were %v", actual) } if !sr.closed { t.Fatalf("The ReaderCloser should have been closed, it is not.") } } func TestBufioWriterPoolGetWithNoReaderShouldCreateOne(t *testing.T) { writer := BufioWriter32KPool.Get(nil) if writer == nil { t.Fatalf("BufioWriterPool should have create a bufio.Writer but did not.") } } func TestBufioWriterPoolPutAndGet(t *testing.T) { buf := new(bytes.Buffer) bw := bufio.NewWriter(buf) writer := BufioWriter32KPool.Get(bw) if writer == nil { t.Fatalf("BufioReaderPool should not return a nil writer.") } written, err := writer.Write([]byte("foobar")) if err != nil { t.Fatal(err) } if written != 6 { t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) } // Make sure we Flush all the way ? writer.Flush() bw.Flush() if len(buf.Bytes()) != 6 { t.Fatalf("The buffer should contain 6 bytes ('foobar') but contains %v ('%v')", buf.Bytes(), string(buf.Bytes())) } // Reset the buffer buf.Reset() BufioWriter32KPool.Put(writer) // Try to write something written, err = writer.Write([]byte("barfoo")) if err != nil { t.Fatal(err) } // If we now try to flush it, it should panic (the writer is nil) // recover it defer func() { if r := recover(); r == nil { t.Fatal("Trying to flush the writter should have 'paniced', did not.") } }() writer.Flush() } type simpleWriterCloser struct { io.Writer closed bool } func (r *simpleWriterCloser) Close() error { r.closed = true return nil } func TestNewWriteCloserWrapperWithAWriteCloser(t *testing.T) { buf := new(bytes.Buffer) bw := bufio.NewWriter(buf) sw := &simpleWriterCloser{ Writer: new(bytes.Buffer), closed: false, } bw.Flush() writer := BufioWriter32KPool.NewWriteCloserWrapper(bw, sw) if writer == nil { t.Fatalf("BufioReaderPool should not return a nil writer.") } written, err := writer.Write([]byte("foobar")) if err != nil { t.Fatal(err) } if written != 6 { t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) } writer.Close() if !sw.closed { t.Fatalf("The ReaderCloser should have been closed, it is not.") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/promise/promise.go ================================================ package promise // Go is a basic promise implementation: it wraps calls a function in a goroutine, // and returns a channel which will later return the function's return value. func Go(f func() error) chan error { ch := make(chan error, 1) go func() { ch <- f() }() return ch } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy.go ================================================ package stdcopy import ( "encoding/binary" "errors" "io" "github.com/fsouza/go-dockerclient/external/github.com/Sirupsen/logrus" ) const ( stdWriterPrefixLen = 8 stdWriterFdIndex = 0 stdWriterSizeIndex = 4 startingBufLen = 32*1024 + stdWriterPrefixLen + 1 ) // StdType prefixes type and length to standard stream. type StdType [stdWriterPrefixLen]byte var ( // Stdin represents standard input stream type. Stdin = StdType{0: 0} // Stdout represents standard output stream type. Stdout = StdType{0: 1} // Stderr represents standard error steam type. Stderr = StdType{0: 2} ) // StdWriter is wrapper of io.Writer with extra customized info. type StdWriter struct { io.Writer prefix StdType sizeBuf []byte } func (w *StdWriter) Write(buf []byte) (n int, err error) { var n1, n2 int if w == nil || w.Writer == nil { return 0, errors.New("Writer not instantiated") } binary.BigEndian.PutUint32(w.prefix[4:], uint32(len(buf))) n1, err = w.Writer.Write(w.prefix[:]) if err != nil { n = n1 - stdWriterPrefixLen } else { n2, err = w.Writer.Write(buf) n = n1 + n2 - stdWriterPrefixLen } if n < 0 { n = 0 } return } // NewStdWriter instantiates a new Writer. // Everything written to it will be encapsulated using a custom format, // and written to the underlying `w` stream. // This allows multiple write streams (e.g. stdout and stderr) to be muxed into a single connection. // `t` indicates the id of the stream to encapsulate. // It can be stdcopy.Stdin, stdcopy.Stdout, stdcopy.Stderr. func NewStdWriter(w io.Writer, t StdType) *StdWriter { return &StdWriter{ Writer: w, prefix: t, sizeBuf: make([]byte, 4), } } var errInvalidStdHeader = errors.New("Unrecognized input header") // StdCopy is a modified version of io.Copy. // // StdCopy will demultiplex `src`, assuming that it contains two streams, // previously multiplexed together using a StdWriter instance. // As it reads from `src`, StdCopy will write to `dstout` and `dsterr`. // // StdCopy will read until it hits EOF on `src`. It will then return a nil error. // In other words: if `err` is non nil, it indicates a real underlying error. // // `written` will hold the total number of bytes written to `dstout` and `dsterr`. func StdCopy(dstout, dsterr io.Writer, src io.Reader) (written int64, err error) { var ( buf = make([]byte, startingBufLen) bufLen = len(buf) nr, nw int er, ew error out io.Writer frameSize int ) for { // Make sure we have at least a full header for nr < stdWriterPrefixLen { var nr2 int nr2, er = src.Read(buf[nr:]) nr += nr2 if er == io.EOF { if nr < stdWriterPrefixLen { logrus.Debugf("Corrupted prefix: %v", buf[:nr]) return written, nil } break } if er != nil { logrus.Debugf("Error reading header: %s", er) return 0, er } } // Check the first byte to know where to write switch buf[stdWriterFdIndex] { case 0: fallthrough case 1: // Write on stdout out = dstout case 2: // Write on stderr out = dsterr default: logrus.Debugf("Error selecting output fd: (%d)", buf[stdWriterFdIndex]) return 0, errInvalidStdHeader } // Retrieve the size of the frame frameSize = int(binary.BigEndian.Uint32(buf[stdWriterSizeIndex : stdWriterSizeIndex+4])) logrus.Debugf("framesize: %d", frameSize) // Check if the buffer is big enough to read the frame. // Extend it if necessary. if frameSize+stdWriterPrefixLen > bufLen { logrus.Debugf("Extending buffer cap by %d (was %d)", frameSize+stdWriterPrefixLen-bufLen+1, len(buf)) buf = append(buf, make([]byte, frameSize+stdWriterPrefixLen-bufLen+1)...) bufLen = len(buf) } // While the amount of bytes read is less than the size of the frame + header, we keep reading for nr < frameSize+stdWriterPrefixLen { var nr2 int nr2, er = src.Read(buf[nr:]) nr += nr2 if er == io.EOF { if nr < frameSize+stdWriterPrefixLen { logrus.Debugf("Corrupted frame: %v", buf[stdWriterPrefixLen:nr]) return written, nil } break } if er != nil { logrus.Debugf("Error reading frame: %s", er) return 0, er } } // Write the retrieved frame (without header) nw, ew = out.Write(buf[stdWriterPrefixLen : frameSize+stdWriterPrefixLen]) if ew != nil { logrus.Debugf("Error writing frame: %s", ew) return 0, ew } // If the frame has not been fully written: error if nw != frameSize { logrus.Debugf("Error Short Write: (%d on %d)", nw, frameSize) return 0, io.ErrShortWrite } written += int64(nw) // Move the rest of the buffer to the beginning copy(buf, buf[frameSize+stdWriterPrefixLen:]) // Move the index nr -= frameSize + stdWriterPrefixLen } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy/stdcopy_test.go ================================================ package stdcopy import ( "bytes" "errors" "io" "io/ioutil" "strings" "testing" ) func TestNewStdWriter(t *testing.T) { writer := NewStdWriter(ioutil.Discard, Stdout) if writer == nil { t.Fatalf("NewStdWriter with an invalid StdType should not return nil.") } } func TestWriteWithUnitializedStdWriter(t *testing.T) { writer := StdWriter{ Writer: nil, prefix: Stdout, sizeBuf: make([]byte, 4), } n, err := writer.Write([]byte("Something here")) if n != 0 || err == nil { t.Fatalf("Should fail when given an uncomplete or uninitialized StdWriter") } } func TestWriteWithNilBytes(t *testing.T) { writer := NewStdWriter(ioutil.Discard, Stdout) n, err := writer.Write(nil) if err != nil { t.Fatalf("Shouldn't have fail when given no data") } if n > 0 { t.Fatalf("Write should have written 0 byte, but has written %d", n) } } func TestWrite(t *testing.T) { writer := NewStdWriter(ioutil.Discard, Stdout) data := []byte("Test StdWrite.Write") n, err := writer.Write(data) if err != nil { t.Fatalf("Error while writing with StdWrite") } if n != len(data) { t.Fatalf("Write should have written %d byte but wrote %d.", len(data), n) } } type errWriter struct { n int err error } func (f *errWriter) Write(buf []byte) (int, error) { return f.n, f.err } func TestWriteWithWriterError(t *testing.T) { expectedError := errors.New("expected") expectedReturnedBytes := 10 writer := NewStdWriter(&errWriter{ n: stdWriterPrefixLen + expectedReturnedBytes, err: expectedError}, Stdout) data := []byte("This won't get written, sigh") n, err := writer.Write(data) if err != expectedError { t.Fatalf("Didn't get expected error.") } if n != expectedReturnedBytes { t.Fatalf("Didn't get expected writen bytes %d, got %d.", expectedReturnedBytes, n) } } func TestWriteDoesNotReturnNegativeWrittenBytes(t *testing.T) { writer := NewStdWriter(&errWriter{n: -1}, Stdout) data := []byte("This won't get written, sigh") actual, _ := writer.Write(data) if actual != 0 { t.Fatalf("Expected returned written bytes equal to 0, got %d", actual) } } func getSrcBuffer(stdOutBytes, stdErrBytes []byte) (buffer *bytes.Buffer, err error) { buffer = new(bytes.Buffer) dstOut := NewStdWriter(buffer, Stdout) _, err = dstOut.Write(stdOutBytes) if err != nil { return } dstErr := NewStdWriter(buffer, Stderr) _, err = dstErr.Write(stdErrBytes) return } func TestStdCopyWriteAndRead(t *testing.T) { stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) if err != nil { t.Fatal(err) } written, err := StdCopy(ioutil.Discard, ioutil.Discard, buffer) if err != nil { t.Fatal(err) } expectedTotalWritten := len(stdOutBytes) + len(stdErrBytes) if written != int64(expectedTotalWritten) { t.Fatalf("Expected to have total of %d bytes written, got %d", expectedTotalWritten, written) } } type customReader struct { n int err error totalCalls int correctCalls int src *bytes.Buffer } func (f *customReader) Read(buf []byte) (int, error) { f.totalCalls++ if f.totalCalls <= f.correctCalls { return f.src.Read(buf) } return f.n, f.err } func TestStdCopyReturnsErrorReadingHeader(t *testing.T) { expectedError := errors.New("error") reader := &customReader{ err: expectedError} written, err := StdCopy(ioutil.Discard, ioutil.Discard, reader) if written != 0 { t.Fatalf("Expected 0 bytes read, got %d", written) } if err != expectedError { t.Fatalf("Didn't get expected error") } } func TestStdCopyReturnsErrorReadingFrame(t *testing.T) { expectedError := errors.New("error") stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) if err != nil { t.Fatal(err) } reader := &customReader{ correctCalls: 1, n: stdWriterPrefixLen + 1, err: expectedError, src: buffer} written, err := StdCopy(ioutil.Discard, ioutil.Discard, reader) if written != 0 { t.Fatalf("Expected 0 bytes read, got %d", written) } if err != expectedError { t.Fatalf("Didn't get expected error") } } func TestStdCopyDetectsCorruptedFrame(t *testing.T) { stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) if err != nil { t.Fatal(err) } reader := &customReader{ correctCalls: 1, n: stdWriterPrefixLen + 1, err: io.EOF, src: buffer} written, err := StdCopy(ioutil.Discard, ioutil.Discard, reader) if written != startingBufLen { t.Fatalf("Expected 0 bytes read, got %d", written) } if err != nil { t.Fatal("Didn't get nil error") } } func TestStdCopyWithInvalidInputHeader(t *testing.T) { dstOut := NewStdWriter(ioutil.Discard, Stdout) dstErr := NewStdWriter(ioutil.Discard, Stderr) src := strings.NewReader("Invalid input") _, err := StdCopy(dstOut, dstErr, src) if err == nil { t.Fatal("StdCopy with invalid input header should fail.") } } func TestStdCopyWithCorruptedPrefix(t *testing.T) { data := []byte{0x01, 0x02, 0x03} src := bytes.NewReader(data) written, err := StdCopy(nil, nil, src) if err != nil { t.Fatalf("StdCopy should not return an error with corrupted prefix.") } if written != 0 { t.Fatalf("StdCopy should have written 0, but has written %d", written) } } func TestStdCopyReturnsWriteErrors(t *testing.T) { stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) if err != nil { t.Fatal(err) } expectedError := errors.New("expected") dstOut := &errWriter{err: expectedError} written, err := StdCopy(dstOut, ioutil.Discard, buffer) if written != 0 { t.Fatalf("StdCopy should have written 0, but has written %d", written) } if err != expectedError { t.Fatalf("Didn't get expected error, got %v", err) } } func TestStdCopyDetectsNotFullyWrittenFrames(t *testing.T) { stdOutBytes := []byte(strings.Repeat("o", startingBufLen)) stdErrBytes := []byte(strings.Repeat("e", startingBufLen)) buffer, err := getSrcBuffer(stdOutBytes, stdErrBytes) if err != nil { t.Fatal(err) } dstOut := &errWriter{n: startingBufLen - 10} written, err := StdCopy(dstOut, ioutil.Discard, buffer) if written != 0 { t.Fatalf("StdCopy should have return 0 written bytes, but returned %d", written) } if err != io.ErrShortWrite { t.Fatalf("Didn't get expected io.ErrShortWrite error") } } func BenchmarkWrite(b *testing.B) { w := NewStdWriter(ioutil.Discard, Stdout) data := []byte("Test line for testing stdwriter performance\n") data = bytes.Repeat(data, 100) b.SetBytes(int64(len(data))) b.ResetTimer() for i := 0; i < b.N; i++ { if _, err := w.Write(data); err != nil { b.Fatal(err) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes.go ================================================ package system import ( "os" "syscall" "time" "unsafe" ) var ( maxTime time.Time ) func init() { if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { // This is a 64 bit timespec // os.Chtimes limits time to the following maxTime = time.Unix(0, 1<<63-1) } else { // This is a 32 bit timespec maxTime = time.Unix(1<<31-1, 0) } } // Chtimes changes the access time and modified time of a file at the given path func Chtimes(name string, atime time.Time, mtime time.Time) error { unixMinTime := time.Unix(0, 0) unixMaxTime := maxTime // If the modified time is prior to the Unix Epoch, or after the // end of Unix Time, os.Chtimes has undefined behavior // default to Unix Epoch in this case, just in case if atime.Before(unixMinTime) || atime.After(unixMaxTime) { atime = unixMinTime } if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { mtime = unixMinTime } if err := os.Chtimes(name, atime, mtime); err != nil { return err } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_test.go ================================================ package system import ( "io/ioutil" "os" "path/filepath" "testing" "time" ) // prepareTempFile creates a temporary file in a temporary directory. func prepareTempFile(t *testing.T) (string, string) { dir, err := ioutil.TempDir("", "docker-system-test") if err != nil { t.Fatal(err) } file := filepath.Join(dir, "exist") if err := ioutil.WriteFile(file, []byte("hello"), 0644); err != nil { t.Fatal(err) } return file, dir } // TestChtimes tests Chtimes on a tempfile. Test only mTime, because aTime is OS dependent func TestChtimes(t *testing.T) { file, dir := prepareTempFile(t) defer os.RemoveAll(dir) beforeUnixEpochTime := time.Unix(0, 0).Add(-100 * time.Second) unixEpochTime := time.Unix(0, 0) afterUnixEpochTime := time.Unix(100, 0) unixMaxTime := maxTime // Test both aTime and mTime set to Unix Epoch Chtimes(file, unixEpochTime, unixEpochTime) f, err := os.Stat(file) if err != nil { t.Fatal(err) } if f.ModTime() != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, f.ModTime()) } // Test aTime before Unix Epoch and mTime set to Unix Epoch Chtimes(file, beforeUnixEpochTime, unixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } if f.ModTime() != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, f.ModTime()) } // Test aTime set to Unix Epoch and mTime before Unix Epoch Chtimes(file, unixEpochTime, beforeUnixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } if f.ModTime() != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, f.ModTime()) } // Test both aTime and mTime set to after Unix Epoch (valid time) Chtimes(file, afterUnixEpochTime, afterUnixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } if f.ModTime() != afterUnixEpochTime { t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, f.ModTime()) } // Test both aTime and mTime set to Unix max time Chtimes(file, unixMaxTime, unixMaxTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } if f.ModTime().Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), f.ModTime().Truncate(time.Second)) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_unix_test.go ================================================ // +build linux freebsd package system import ( "os" "syscall" "testing" "time" ) // TestChtimes tests Chtimes access time on a tempfile on Linux func TestChtimesLinux(t *testing.T) { file, dir := prepareTempFile(t) defer os.RemoveAll(dir) beforeUnixEpochTime := time.Unix(0, 0).Add(-100 * time.Second) unixEpochTime := time.Unix(0, 0) afterUnixEpochTime := time.Unix(100, 0) unixMaxTime := maxTime // Test both aTime and mTime set to Unix Epoch Chtimes(file, unixEpochTime, unixEpochTime) f, err := os.Stat(file) if err != nil { t.Fatal(err) } stat := f.Sys().(*syscall.Stat_t) aTime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } // Test aTime before Unix Epoch and mTime set to Unix Epoch Chtimes(file, beforeUnixEpochTime, unixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } stat = f.Sys().(*syscall.Stat_t) aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } // Test aTime set to Unix Epoch and mTime before Unix Epoch Chtimes(file, unixEpochTime, beforeUnixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } stat = f.Sys().(*syscall.Stat_t) aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } // Test both aTime and mTime set to after Unix Epoch (valid time) Chtimes(file, afterUnixEpochTime, afterUnixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } stat = f.Sys().(*syscall.Stat_t) aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) if aTime != afterUnixEpochTime { t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, aTime) } // Test both aTime and mTime set to Unix max time Chtimes(file, unixMaxTime, unixMaxTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } stat = f.Sys().(*syscall.Stat_t) aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) if aTime.Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), aTime.Truncate(time.Second)) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/chtimes_windows_test.go ================================================ // +build windows package system import ( "os" "syscall" "testing" "time" ) // TestChtimes tests Chtimes access time on a tempfile on Windows func TestChtimesWindows(t *testing.T) { file, dir := prepareTempFile(t) defer os.RemoveAll(dir) beforeUnixEpochTime := time.Unix(0, 0).Add(-100 * time.Second) unixEpochTime := time.Unix(0, 0) afterUnixEpochTime := time.Unix(100, 0) unixMaxTime := maxTime // Test both aTime and mTime set to Unix Epoch Chtimes(file, unixEpochTime, unixEpochTime) f, err := os.Stat(file) if err != nil { t.Fatal(err) } aTime := time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } // Test aTime before Unix Epoch and mTime set to Unix Epoch Chtimes(file, beforeUnixEpochTime, unixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } // Test aTime set to Unix Epoch and mTime before Unix Epoch Chtimes(file, unixEpochTime, beforeUnixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } // Test both aTime and mTime set to after Unix Epoch (valid time) Chtimes(file, afterUnixEpochTime, afterUnixEpochTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) if aTime != afterUnixEpochTime { t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, aTime) } // Test both aTime and mTime set to Unix max time Chtimes(file, unixMaxTime, unixMaxTime) f, err = os.Stat(file) if err != nil { t.Fatal(err) } aTime = time.Unix(0, f.Sys().(*syscall.Win32FileAttributeData).LastAccessTime.Nanoseconds()) if aTime.Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), aTime.Truncate(time.Second)) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/errors.go ================================================ package system import ( "errors" ) var ( // ErrNotSupportedPlatform means the platform is not supported. ErrNotSupportedPlatform = errors.New("platform and architecture is not supported") ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/events_windows.go ================================================ package system // This file implements syscalls for Win32 events which are not implemented // in golang. import ( "syscall" "unsafe" ) var ( procCreateEvent = modkernel32.NewProc("CreateEventW") procOpenEvent = modkernel32.NewProc("OpenEventW") procSetEvent = modkernel32.NewProc("SetEvent") procResetEvent = modkernel32.NewProc("ResetEvent") procPulseEvent = modkernel32.NewProc("PulseEvent") ) // CreateEvent implements win32 CreateEventW func in golang. It will create an event object. func CreateEvent(eventAttributes *syscall.SecurityAttributes, manualReset bool, initialState bool, name string) (handle syscall.Handle, err error) { namep, _ := syscall.UTF16PtrFromString(name) var _p1 uint32 if manualReset { _p1 = 1 } var _p2 uint32 if initialState { _p2 = 1 } r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep))) use(unsafe.Pointer(namep)) handle = syscall.Handle(r0) if handle == syscall.InvalidHandle { err = e1 } return } // OpenEvent implements win32 OpenEventW func in golang. It opens an event object. func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle syscall.Handle, err error) { namep, _ := syscall.UTF16PtrFromString(name) var _p1 uint32 if inheritHandle { _p1 = 1 } r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep))) use(unsafe.Pointer(namep)) handle = syscall.Handle(r0) if handle == syscall.InvalidHandle { err = e1 } return } // SetEvent implements win32 SetEvent func in golang. func SetEvent(handle syscall.Handle) (err error) { return setResetPulse(handle, procSetEvent) } // ResetEvent implements win32 ResetEvent func in golang. func ResetEvent(handle syscall.Handle) (err error) { return setResetPulse(handle, procResetEvent) } // PulseEvent implements win32 PulseEvent func in golang. func PulseEvent(handle syscall.Handle) (err error) { return setResetPulse(handle, procPulseEvent) } func setResetPulse(handle syscall.Handle, proc *syscall.LazyProc) (err error) { r0, _, _ := proc.Call(uintptr(handle)) if r0 != 0 { err = syscall.Errno(r0) } return } var temp unsafe.Pointer // use ensures a variable is kept alive without the GC freeing while still needed func use(p unsafe.Pointer) { temp = p } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys.go ================================================ // +build !windows package system import ( "os" "path/filepath" ) // MkdirAll creates a directory named path along with any necessary parents, // with permission specified by attribute perm for all dir created. func MkdirAll(path string, perm os.FileMode) error { return os.MkdirAll(path, perm) } // IsAbs is a platform-specific wrapper for filepath.IsAbs. func IsAbs(path string) bool { return filepath.IsAbs(path) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/filesys_windows.go ================================================ // +build windows package system import ( "os" "path/filepath" "regexp" "strings" "syscall" ) // MkdirAll implementation that is volume path aware for Windows. func MkdirAll(path string, perm os.FileMode) error { if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) { return nil } // The rest of this method is copied from os.MkdirAll and should be kept // as-is to ensure compatibility. // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := os.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{ Op: "mkdir", Path: path, Err: syscall.ENOTDIR, } } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = MkdirAll(path[0:j-1], perm) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = os.Mkdir(path, perm) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := os.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil } // IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows, // golang filepath.IsAbs does not consider a path \windows\system32 as absolute // as it doesn't start with a drive-letter/colon combination. However, in // docker we need to verify things such as WORKDIR /windows/system32 in // a Dockerfile (which gets translated to \windows\system32 when being processed // by the daemon. This SHOULD be treated as absolute from a docker processing // perspective. func IsAbs(path string) bool { if !filepath.IsAbs(path) { if !strings.HasPrefix(path, string(os.PathSeparator)) { return false } } return true } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat.go ================================================ // +build !windows package system import ( "syscall" ) // Lstat takes a path to a file and returns // a system.StatT type pertaining to that file. // // Throws an error if the file does not exist func Lstat(path string) (*StatT, error) { s := &syscall.Stat_t{} if err := syscall.Lstat(path, s); err != nil { return nil, err } return fromStatT(s) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_unix_test.go ================================================ // +build linux freebsd package system import ( "os" "testing" ) // TestLstat tests Lstat for existing and non existing files func TestLstat(t *testing.T) { file, invalid, _, dir := prepareFiles(t) defer os.RemoveAll(dir) statFile, err := Lstat(file) if err != nil { t.Fatal(err) } if statFile == nil { t.Fatal("returned empty stat for existing file") } statInvalid, err := Lstat(invalid) if err == nil { t.Fatal("did not return error for non-existing file") } if statInvalid != nil { t.Fatal("returned non-nil stat for non-existing file") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/lstat_windows.go ================================================ // +build windows package system import ( "os" ) // Lstat calls os.Lstat to get a fileinfo interface back. // This is then copied into our own locally defined structure. // Note the Linux version uses fromStatT to do the copy back, // but that not strictly necessary when already in an OS specific module. func Lstat(path string) (*StatT, error) { fi, err := os.Lstat(path) if err != nil { return nil, err } return &StatT{ name: fi.Name(), size: fi.Size(), mode: fi.Mode(), modTime: fi.ModTime(), isDir: fi.IsDir()}, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo.go ================================================ package system // MemInfo contains memory statistics of the host system. type MemInfo struct { // Total usable RAM (i.e. physical RAM minus a few reserved bits and the // kernel binary code). MemTotal int64 // Amount of free memory. MemFree int64 // Total amount of swap space available. SwapTotal int64 // Amount of swap space that is currently unused. SwapFree int64 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_linux.go ================================================ package system import ( "bufio" "io" "os" "strconv" "strings" "github.com/fsouza/go-dockerclient/external/github.com/docker/go-units" ) // ReadMemInfo retrieves memory statistics of the host system and returns a // MemInfo type. func ReadMemInfo() (*MemInfo, error) { file, err := os.Open("/proc/meminfo") if err != nil { return nil, err } defer file.Close() return parseMemInfo(file) } // parseMemInfo parses the /proc/meminfo file into // a MemInfo object given a io.Reader to the file. // // Throws error if there are problems reading from the file func parseMemInfo(reader io.Reader) (*MemInfo, error) { meminfo := &MemInfo{} scanner := bufio.NewScanner(reader) for scanner.Scan() { // Expected format: ["MemTotal:", "1234", "kB"] parts := strings.Fields(scanner.Text()) // Sanity checks: Skip malformed entries. if len(parts) < 3 || parts[2] != "kB" { continue } // Convert to bytes. size, err := strconv.Atoi(parts[1]) if err != nil { continue } bytes := int64(size) * units.KiB switch parts[0] { case "MemTotal:": meminfo.MemTotal = bytes case "MemFree:": meminfo.MemFree = bytes case "SwapTotal:": meminfo.SwapTotal = bytes case "SwapFree:": meminfo.SwapFree = bytes } } // Handle errors that may have occurred during the reading of the file. if err := scanner.Err(); err != nil { return nil, err } return meminfo, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unix_test.go ================================================ // +build linux freebsd package system import ( "strings" "testing" "github.com/fsouza/go-dockerclient/external/github.com/docker/go-units" ) // TestMemInfo tests parseMemInfo with a static meminfo string func TestMemInfo(t *testing.T) { const input = ` MemTotal: 1 kB MemFree: 2 kB SwapTotal: 3 kB SwapFree: 4 kB Malformed1: Malformed2: 1 Malformed3: 2 MB Malformed4: X kB ` meminfo, err := parseMemInfo(strings.NewReader(input)) if err != nil { t.Fatal(err) } if meminfo.MemTotal != 1*units.KiB { t.Fatalf("Unexpected MemTotal: %d", meminfo.MemTotal) } if meminfo.MemFree != 2*units.KiB { t.Fatalf("Unexpected MemFree: %d", meminfo.MemFree) } if meminfo.SwapTotal != 3*units.KiB { t.Fatalf("Unexpected SwapTotal: %d", meminfo.SwapTotal) } if meminfo.SwapFree != 4*units.KiB { t.Fatalf("Unexpected SwapFree: %d", meminfo.SwapFree) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_unsupported.go ================================================ // +build !linux,!windows package system // ReadMemInfo is not supported on platforms other than linux and windows. func ReadMemInfo() (*MemInfo, error) { return nil, ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/meminfo_windows.go ================================================ package system import ( "syscall" "unsafe" ) var ( modkernel32 = syscall.NewLazyDLL("kernel32.dll") procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx") ) // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx type memorystatusex struct { dwLength uint32 dwMemoryLoad uint32 ullTotalPhys uint64 ullAvailPhys uint64 ullTotalPageFile uint64 ullAvailPageFile uint64 ullTotalVirtual uint64 ullAvailVirtual uint64 ullAvailExtendedVirtual uint64 } // ReadMemInfo retrieves memory statistics of the host system and returns a // MemInfo type. func ReadMemInfo() (*MemInfo, error) { msi := &memorystatusex{ dwLength: 64, } r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) if r1 == 0 { return &MemInfo{}, nil } return &MemInfo{ MemTotal: int64(msi.ullTotalPhys), MemFree: int64(msi.ullAvailPhys), SwapTotal: int64(msi.ullTotalPageFile), SwapFree: int64(msi.ullAvailPageFile), }, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod.go ================================================ // +build !windows package system import ( "syscall" ) // Mknod creates a filesystem node (file, device special file or named pipe) named path // with attributes specified by mode and dev. func Mknod(path string, mode uint32, dev int) error { return syscall.Mknod(path, mode, dev) } // Mkdev is used to build the value of linux devices (in /dev/) which specifies major // and minor number of the newly created device special file. // Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes. // They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major, // then the top 12 bits of the minor. func Mkdev(major int64, minor int64) uint32 { return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff)) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/mknod_windows.go ================================================ // +build windows package system // Mknod is not implemented on Windows. func Mknod(path string, mode uint32, dev int) error { return ErrNotSupportedPlatform } // Mkdev is not implemented on Windows. func Mkdev(major int64, minor int64) uint32 { panic("Mkdev not implemented on Windows.") } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_unix.go ================================================ // +build !windows package system // DefaultPathEnv is unix style list of directories to search for // executables. Each directory is separated from the next by a colon // ':' character . const DefaultPathEnv = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/path_windows.go ================================================ // +build windows package system // DefaultPathEnv is deliberately empty on Windows as the default path will be set by // the container. Docker has no context of what the default path should be. const DefaultPathEnv = "" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat.go ================================================ // +build !windows package system import ( "syscall" ) // StatT type contains status of a file. It contains metadata // like permission, owner, group, size, etc about a file. type StatT struct { mode uint32 uid uint32 gid uint32 rdev uint64 size int64 mtim syscall.Timespec } // Mode returns file's permission mode. func (s StatT) Mode() uint32 { return s.mode } // UID returns file's user id of owner. func (s StatT) UID() uint32 { return s.uid } // GID returns file's group id of owner. func (s StatT) GID() uint32 { return s.gid } // Rdev returns file's device ID (if it's special file). func (s StatT) Rdev() uint64 { return s.rdev } // Size returns file's size. func (s StatT) Size() int64 { return s.size } // Mtim returns file's last modification time. func (s StatT) Mtim() syscall.Timespec { return s.mtim } // GetLastModification returns file's last modification time. func (s StatT) GetLastModification() syscall.Timespec { return s.Mtim() } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_freebsd.go ================================================ package system import ( "syscall" ) // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { return &StatT{size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtimespec}, nil } // Stat takes a path to a file and returns // a system.Stat_t type pertaining to that file. // // Throws an error if the file does not exist func Stat(path string) (*StatT, error) { s := &syscall.Stat_t{} if err := syscall.Stat(path, s); err != nil { return nil, err } return fromStatT(s) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_linux.go ================================================ package system import ( "syscall" ) // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { return &StatT{size: s.Size, mode: s.Mode, uid: s.Uid, gid: s.Gid, rdev: s.Rdev, mtim: s.Mtim}, nil } // FromStatT exists only on linux, and loads a system.StatT from a // syscal.Stat_t. func FromStatT(s *syscall.Stat_t) (*StatT, error) { return fromStatT(s) } // Stat takes a path to a file and returns // a system.StatT type pertaining to that file. // // Throws an error if the file does not exist func Stat(path string) (*StatT, error) { s := &syscall.Stat_t{} if err := syscall.Stat(path, s); err != nil { return nil, err } return fromStatT(s) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_solaris.go ================================================ // +build solaris package system import ( "syscall" ) // fromStatT creates a system.StatT type from a syscall.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { return &StatT{size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtim}, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unix_test.go ================================================ // +build linux freebsd package system import ( "os" "syscall" "testing" ) // TestFromStatT tests fromStatT for a tempfile func TestFromStatT(t *testing.T) { file, _, _, dir := prepareFiles(t) defer os.RemoveAll(dir) stat := &syscall.Stat_t{} err := syscall.Lstat(file, stat) s, err := fromStatT(stat) if err != nil { t.Fatal(err) } if stat.Mode != s.Mode() { t.Fatal("got invalid mode") } if stat.Uid != s.UID() { t.Fatal("got invalid uid") } if stat.Gid != s.GID() { t.Fatal("got invalid gid") } if stat.Rdev != s.Rdev() { t.Fatal("got invalid rdev") } if stat.Mtim != s.Mtim() { t.Fatal("got invalid mtim") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_unsupported.go ================================================ // +build !linux,!windows,!freebsd,!solaris package system import ( "syscall" ) // fromStatT creates a system.StatT type from a syscall.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { return &StatT{size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), mtim: s.Mtimespec}, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/stat_windows.go ================================================ // +build windows package system import ( "os" "time" ) // StatT type contains status of a file. It contains metadata // like name, permission, size, etc about a file. type StatT struct { name string size int64 mode os.FileMode modTime time.Time isDir bool } // Name returns file's name. func (s StatT) Name() string { return s.name } // Size returns file's size. func (s StatT) Size() int64 { return s.size } // Mode returns file's permission mode. func (s StatT) Mode() os.FileMode { return s.mode } // ModTime returns file's last modification time. func (s StatT) ModTime() time.Time { return s.modTime } // IsDir returns whether file is actually a directory. func (s StatT) IsDir() bool { return s.isDir } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_unix.go ================================================ // +build linux freebsd package system import "syscall" // Unmount is a platform-specific helper function to call // the unmount syscall. func Unmount(dest string) error { return syscall.Unmount(dest, 0) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/syscall_windows.go ================================================ package system import ( "fmt" "syscall" ) // OSVersion is a wrapper for Windows version information // https://msdn.microsoft.com/en-us/library/windows/desktop/ms724439(v=vs.85).aspx type OSVersion struct { Version uint32 MajorVersion uint8 MinorVersion uint8 Build uint16 } // GetOSVersion gets the operating system version on Windows. Note that // docker.exe must be manifested to get the correct version information. func GetOSVersion() (OSVersion, error) { var err error osv := OSVersion{} osv.Version, err = syscall.GetVersion() if err != nil { return osv, fmt.Errorf("Failed to call GetVersion()") } osv.MajorVersion = uint8(osv.Version & 0xFF) osv.MinorVersion = uint8(osv.Version >> 8 & 0xFF) osv.Build = uint16(osv.Version >> 16) return osv, nil } // Unmount is a platform-specific helper function to call // the unmount syscall. Not supported on Windows func Unmount(dest string) error { return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask.go ================================================ // +build !windows package system import ( "syscall" ) // Umask sets current process's file mode creation mask to newmask // and return oldmask. func Umask(newmask int) (oldmask int, err error) { return syscall.Umask(newmask), nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/umask_windows.go ================================================ // +build windows package system // Umask is not supported on the windows platform. func Umask(newmask int) (oldmask int, err error) { // should not be called on cli code path return 0, ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_darwin.go ================================================ package system import "syscall" // LUtimesNano is not supported by darwin platform. func LUtimesNano(path string, ts []syscall.Timespec) error { return ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_freebsd.go ================================================ package system import ( "syscall" "unsafe" ) // LUtimesNano is used to change access and modification time of the specified path. // It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. func LUtimesNano(path string, ts []syscall.Timespec) error { var _path *byte _path, err := syscall.BytePtrFromString(path) if err != nil { return err } if _, _, err := syscall.Syscall(syscall.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != syscall.ENOSYS { return err } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_linux.go ================================================ package system import ( "syscall" "unsafe" ) // LUtimesNano is used to change access and modification time of the specified path. // It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm. func LUtimesNano(path string, ts []syscall.Timespec) error { // These are not currently available in syscall atFdCwd := -100 atSymLinkNoFollow := 0x100 var _path *byte _path, err := syscall.BytePtrFromString(path) if err != nil { return err } if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(atSymLinkNoFollow), 0, 0); err != 0 && err != syscall.ENOSYS { return err } return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unix_test.go ================================================ // +build linux freebsd package system import ( "io/ioutil" "os" "path/filepath" "syscall" "testing" ) // prepareFiles creates files for testing in the temp directory func prepareFiles(t *testing.T) (string, string, string, string) { dir, err := ioutil.TempDir("", "docker-system-test") if err != nil { t.Fatal(err) } file := filepath.Join(dir, "exist") if err := ioutil.WriteFile(file, []byte("hello"), 0644); err != nil { t.Fatal(err) } invalid := filepath.Join(dir, "doesnt-exist") symlink := filepath.Join(dir, "symlink") if err := os.Symlink(file, symlink); err != nil { t.Fatal(err) } return file, invalid, symlink, dir } func TestLUtimesNano(t *testing.T) { file, invalid, symlink, dir := prepareFiles(t) defer os.RemoveAll(dir) before, err := os.Stat(file) if err != nil { t.Fatal(err) } ts := []syscall.Timespec{{0, 0}, {0, 0}} if err := LUtimesNano(symlink, ts); err != nil { t.Fatal(err) } symlinkInfo, err := os.Lstat(symlink) if err != nil { t.Fatal(err) } if before.ModTime().Unix() == symlinkInfo.ModTime().Unix() { t.Fatal("The modification time of the symlink should be different") } fileInfo, err := os.Stat(file) if err != nil { t.Fatal(err) } if before.ModTime().Unix() != fileInfo.ModTime().Unix() { t.Fatal("The modification time of the file should be same") } if err := LUtimesNano(invalid, ts); err == nil { t.Fatal("Doesn't return an error on a non-existing file") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/utimes_unsupported.go ================================================ // +build !linux,!freebsd,!darwin package system import "syscall" // LUtimesNano is not supported on platforms other than linux, freebsd and darwin. func LUtimesNano(path string, ts []syscall.Timespec) error { return ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_linux.go ================================================ package system import ( "syscall" "unsafe" ) // Lgetxattr retrieves the value of the extended attribute identified by attr // and associated with the given path in the file system. // It will returns a nil slice and nil error if the xattr is not set. func Lgetxattr(path string, attr string) ([]byte, error) { pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) 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 == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { 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 } return dest[:sz], nil } var _zero uintptr // Lsetxattr sets the value of the extended attribute identified by attr // and associated with the given path in the file system. 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/system/xattrs_unsupported.go ================================================ // +build !linux package system // Lgetxattr is not supported on platforms other than linux. func Lgetxattr(path string, attr string) ([]byte, error) { return nil, ErrNotSupportedPlatform } // Lsetxattr is not supported on platforms other than linux. func Lsetxattr(path string, attr string, data []byte, flags int) error { return ErrNotSupportedPlatform } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/CONTRIBUTING.md ================================================ # Contributing to go-units Want to hack on go-units? Awesome! Here are instructions to get you started. go-units is a part of the [Docker](https://www.docker.com) project, and follows the same rules and principles. If you're already familiar with the way Docker does things, you'll feel right at home. Otherwise, go read Docker's [contributions guidelines](https://github.com/docker/docker/blob/master/CONTRIBUTING.md), [issue triaging](https://github.com/docker/docker/blob/master/project/ISSUE-TRIAGE.md), [review process](https://github.com/docker/docker/blob/master/project/REVIEWING.md) and [branches and tags](https://github.com/docker/docker/blob/master/project/BRANCHES-AND-TAGS.md). ### Sign your work The sign-off is a simple line at the end of the explanation for the patch. Your signature certifies that you wrote the patch 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 Use your real name (sorry, no pseudonyms or anonymous contributions.) If you set your `user.name` and `user.email` git configs, you can sign your commit automatically with `git commit -s`. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.code ================================================ 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/LICENSE.docs ================================================ 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/MAINTAINERS ================================================ # go-connections maintainers file # # This file describes who runs the docker/go-connections project and how. # This is a living document - if you see something out of date or missing, speak up! # # It is structured to be consumable by both humans and programs. # To extract its contents programmatically, use any TOML-compliant parser. # # This file is compiled into the MAINTAINERS file in docker/opensource. # [Org] [Org."Core maintainers"] people = [ "calavera", ] [people] # A reference list of all people associated with the project. # All other sections should refer to people by their canonical key # in the people section. # ADD YOURSELF HERE IN ALPHABETICAL ORDER [people.calavera] Name = "David Calavera" Email = "david.calavera@gmail.com" GitHub = "calavera" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/README.md ================================================ [![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. 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/. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/circle.yml ================================================ dependencies: post: # install golint - go get github.com/golang/lint/golint test: pre: # run analysis before tests - go vet ./... - test -z "$(golint ./... | tee /dev/stderr)" - test -z "$(gofmt -s -l . | tee /dev/stderr)" ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration.go ================================================ // 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 < 60 { return fmt.Sprintf("%d seconds", seconds) } else if minutes := int(d.Minutes()); minutes == 1 { return "About a minute" } else if minutes < 60 { return fmt.Sprintf("%d minutes", minutes) } else if hours := int(d.Hours()); 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*3 { 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/duration_test.go ================================================ package units import ( "fmt" "testing" "time" ) func ExampleHumanDuration() { fmt.Println(HumanDuration(450 * time.Millisecond)) fmt.Println(HumanDuration(47 * time.Second)) fmt.Println(HumanDuration(1 * time.Minute)) fmt.Println(HumanDuration(3 * time.Minute)) fmt.Println(HumanDuration(35 * time.Minute)) fmt.Println(HumanDuration(35*time.Minute + 40*time.Second)) fmt.Println(HumanDuration(1 * time.Hour)) fmt.Println(HumanDuration(1*time.Hour + 45*time.Minute)) fmt.Println(HumanDuration(3 * time.Hour)) fmt.Println(HumanDuration(3*time.Hour + 59*time.Minute)) fmt.Println(HumanDuration(3*time.Hour + 60*time.Minute)) fmt.Println(HumanDuration(24 * time.Hour)) fmt.Println(HumanDuration(24*time.Hour + 12*time.Hour)) fmt.Println(HumanDuration(2 * 24 * time.Hour)) fmt.Println(HumanDuration(7 * 24 * time.Hour)) fmt.Println(HumanDuration(13*24*time.Hour + 5*time.Hour)) fmt.Println(HumanDuration(2 * 7 * 24 * time.Hour)) fmt.Println(HumanDuration(2*7*24*time.Hour + 4*24*time.Hour)) fmt.Println(HumanDuration(3 * 7 * 24 * time.Hour)) fmt.Println(HumanDuration(4 * 7 * 24 * time.Hour)) fmt.Println(HumanDuration(4*7*24*time.Hour + 3*24*time.Hour)) fmt.Println(HumanDuration(1 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(1*30*24*time.Hour + 2*7*24*time.Hour)) fmt.Println(HumanDuration(2 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(3*30*24*time.Hour + 1*7*24*time.Hour)) fmt.Println(HumanDuration(5*30*24*time.Hour + 2*7*24*time.Hour)) fmt.Println(HumanDuration(13 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(23 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(24 * 30 * 24 * time.Hour)) fmt.Println(HumanDuration(24*30*24*time.Hour + 2*7*24*time.Hour)) fmt.Println(HumanDuration(3*365*24*time.Hour + 2*30*24*time.Hour)) } func TestHumanDuration(t *testing.T) { // Useful duration abstractions day := 24 * time.Hour week := 7 * day month := 30 * day year := 365 * day assertEquals(t, "Less than a second", HumanDuration(450*time.Millisecond)) assertEquals(t, "47 seconds", HumanDuration(47*time.Second)) assertEquals(t, "About a minute", HumanDuration(1*time.Minute)) assertEquals(t, "3 minutes", HumanDuration(3*time.Minute)) assertEquals(t, "35 minutes", HumanDuration(35*time.Minute)) assertEquals(t, "35 minutes", HumanDuration(35*time.Minute+40*time.Second)) assertEquals(t, "About an hour", HumanDuration(1*time.Hour)) assertEquals(t, "About an hour", HumanDuration(1*time.Hour+45*time.Minute)) assertEquals(t, "3 hours", HumanDuration(3*time.Hour)) assertEquals(t, "3 hours", HumanDuration(3*time.Hour+59*time.Minute)) assertEquals(t, "4 hours", HumanDuration(3*time.Hour+60*time.Minute)) assertEquals(t, "24 hours", HumanDuration(24*time.Hour)) assertEquals(t, "36 hours", HumanDuration(1*day+12*time.Hour)) assertEquals(t, "2 days", HumanDuration(2*day)) assertEquals(t, "7 days", HumanDuration(7*day)) assertEquals(t, "13 days", HumanDuration(13*day+5*time.Hour)) assertEquals(t, "2 weeks", HumanDuration(2*week)) assertEquals(t, "2 weeks", HumanDuration(2*week+4*day)) assertEquals(t, "3 weeks", HumanDuration(3*week)) assertEquals(t, "4 weeks", HumanDuration(4*week)) assertEquals(t, "4 weeks", HumanDuration(4*week+3*day)) assertEquals(t, "4 weeks", HumanDuration(1*month)) assertEquals(t, "6 weeks", HumanDuration(1*month+2*week)) assertEquals(t, "8 weeks", HumanDuration(2*month)) assertEquals(t, "3 months", HumanDuration(3*month+1*week)) assertEquals(t, "5 months", HumanDuration(5*month+2*week)) assertEquals(t, "13 months", HumanDuration(13*month)) assertEquals(t, "23 months", HumanDuration(23*month)) assertEquals(t, "24 months", HumanDuration(24*month)) assertEquals(t, "2 years", HumanDuration(24*month+2*week)) assertEquals(t, "3 years", HumanDuration(3*year+2*month)) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size.go ================================================ 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+)([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"} // CustomSize returns a human-readable approximation of a size // using custom format. func CustomSize(format string, size float64, base float64, _map []string) string { i := 0 for size >= base { size = size / base i++ } return fmt.Sprintf(format, size, _map[i]) } // 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 CustomSize("%.4g %s", size, 1000.0, decimapAbbrs) } // 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) != 3 { return -1, fmt.Errorf("invalid size: '%s'", sizeStr) } size, err := strconv.ParseInt(matches[1], 10, 0) if err != nil { return -1, err } unitPrefix := strings.ToLower(matches[2]) if mul, ok := uMap[unitPrefix]; ok { size *= mul } return size, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/size_test.go ================================================ package units import ( "fmt" "reflect" "runtime" "strings" "testing" ) func ExampleBytesSize() { fmt.Println(BytesSize(1024)) fmt.Println(BytesSize(1024 * 1024)) fmt.Println(BytesSize(1048576)) fmt.Println(BytesSize(2 * MiB)) fmt.Println(BytesSize(3.42 * GiB)) fmt.Println(BytesSize(5.372 * TiB)) fmt.Println(BytesSize(2.22 * PiB)) } func ExampleHumanSize() { fmt.Println(HumanSize(1000)) fmt.Println(HumanSize(1024)) fmt.Println(HumanSize(1000000)) fmt.Println(HumanSize(1048576)) fmt.Println(HumanSize(2 * MB)) fmt.Println(HumanSize(float64(3.42 * GB))) fmt.Println(HumanSize(float64(5.372 * TB))) fmt.Println(HumanSize(float64(2.22 * PB))) } func ExampleFromHumanSize() { fmt.Println(FromHumanSize("32")) fmt.Println(FromHumanSize("32b")) fmt.Println(FromHumanSize("32B")) fmt.Println(FromHumanSize("32k")) fmt.Println(FromHumanSize("32K")) fmt.Println(FromHumanSize("32kb")) fmt.Println(FromHumanSize("32Kb")) fmt.Println(FromHumanSize("32Mb")) fmt.Println(FromHumanSize("32Gb")) fmt.Println(FromHumanSize("32Tb")) fmt.Println(FromHumanSize("32Pb")) } func ExampleRAMInBytes() { fmt.Println(RAMInBytes("32")) fmt.Println(RAMInBytes("32b")) fmt.Println(RAMInBytes("32B")) fmt.Println(RAMInBytes("32k")) fmt.Println(RAMInBytes("32K")) fmt.Println(RAMInBytes("32kb")) fmt.Println(RAMInBytes("32Kb")) fmt.Println(RAMInBytes("32Mb")) fmt.Println(RAMInBytes("32Gb")) fmt.Println(RAMInBytes("32Tb")) fmt.Println(RAMInBytes("32Pb")) fmt.Println(RAMInBytes("32PB")) fmt.Println(RAMInBytes("32P")) } func TestBytesSize(t *testing.T) { assertEquals(t, "1 KiB", BytesSize(1024)) assertEquals(t, "1 MiB", BytesSize(1024*1024)) assertEquals(t, "1 MiB", BytesSize(1048576)) assertEquals(t, "2 MiB", BytesSize(2*MiB)) assertEquals(t, "3.42 GiB", BytesSize(3.42*GiB)) assertEquals(t, "5.372 TiB", BytesSize(5.372*TiB)) assertEquals(t, "2.22 PiB", BytesSize(2.22*PiB)) } func TestHumanSize(t *testing.T) { assertEquals(t, "1 kB", HumanSize(1000)) assertEquals(t, "1.024 kB", HumanSize(1024)) assertEquals(t, "1 MB", HumanSize(1000000)) assertEquals(t, "1.049 MB", HumanSize(1048576)) assertEquals(t, "2 MB", HumanSize(2*MB)) assertEquals(t, "3.42 GB", HumanSize(float64(3.42*GB))) assertEquals(t, "5.372 TB", HumanSize(float64(5.372*TB))) assertEquals(t, "2.22 PB", HumanSize(float64(2.22*PB))) } func TestFromHumanSize(t *testing.T) { assertSuccessEquals(t, 32, FromHumanSize, "32") assertSuccessEquals(t, 32, FromHumanSize, "32b") assertSuccessEquals(t, 32, FromHumanSize, "32B") assertSuccessEquals(t, 32*KB, FromHumanSize, "32k") assertSuccessEquals(t, 32*KB, FromHumanSize, "32K") assertSuccessEquals(t, 32*KB, FromHumanSize, "32kb") assertSuccessEquals(t, 32*KB, FromHumanSize, "32Kb") assertSuccessEquals(t, 32*MB, FromHumanSize, "32Mb") assertSuccessEquals(t, 32*GB, FromHumanSize, "32Gb") assertSuccessEquals(t, 32*TB, FromHumanSize, "32Tb") assertSuccessEquals(t, 32*PB, FromHumanSize, "32Pb") assertError(t, FromHumanSize, "") assertError(t, FromHumanSize, "hello") assertError(t, FromHumanSize, "-32") assertError(t, FromHumanSize, "32.3") assertError(t, FromHumanSize, " 32 ") assertError(t, FromHumanSize, "32.3Kb") assertError(t, FromHumanSize, "32 mb") assertError(t, FromHumanSize, "32m b") assertError(t, FromHumanSize, "32bm") } func TestRAMInBytes(t *testing.T) { assertSuccessEquals(t, 32, RAMInBytes, "32") assertSuccessEquals(t, 32, RAMInBytes, "32b") assertSuccessEquals(t, 32, RAMInBytes, "32B") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32k") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32K") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32kb") assertSuccessEquals(t, 32*KiB, RAMInBytes, "32Kb") assertSuccessEquals(t, 32*MiB, RAMInBytes, "32Mb") assertSuccessEquals(t, 32*GiB, RAMInBytes, "32Gb") assertSuccessEquals(t, 32*TiB, RAMInBytes, "32Tb") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32Pb") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32PB") assertSuccessEquals(t, 32*PiB, RAMInBytes, "32P") assertError(t, RAMInBytes, "") assertError(t, RAMInBytes, "hello") assertError(t, RAMInBytes, "-32") assertError(t, RAMInBytes, "32.3") assertError(t, RAMInBytes, " 32 ") assertError(t, RAMInBytes, "32.3Kb") assertError(t, RAMInBytes, "32 mb") assertError(t, RAMInBytes, "32m b") assertError(t, RAMInBytes, "32bm") } func assertEquals(t *testing.T, expected, actual interface{}) { if expected != actual { t.Errorf("Expected '%v' but got '%v'", expected, actual) } } // func that maps to the parse function signatures as testing abstraction type parseFn func(string) (int64, error) // Define 'String()' for pretty-print func (fn parseFn) String() string { fnName := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name() return fnName[strings.LastIndex(fnName, ".")+1:] } func assertSuccessEquals(t *testing.T, expected int64, fn parseFn, arg string) { res, err := fn(arg) if err != nil || res != expected { t.Errorf("%s(\"%s\") -> expected '%d' but got '%d' with error '%v'", fn, arg, expected, res, err) } } func assertError(t *testing.T, fn parseFn, arg string) { res, err := fn(arg) if err == nil && res != -1 { t.Errorf("%s(\"%s\") -> expected error but got '%d'", fn, arg, res) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit.go ================================================ 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/docker/go-units/ulimit_test.go ================================================ package units import ( "fmt" "strconv" "testing" ) func ExampleParseUlimit() { fmt.Println(ParseUlimit("nofile=512:1024")) fmt.Println(ParseUlimit("nofile=1024")) fmt.Println(ParseUlimit("cpu=2:4")) fmt.Println(ParseUlimit("cpu=6")) } func TestParseUlimitValid(t *testing.T) { u1 := &Ulimit{"nofile", 1024, 512} if u2, _ := ParseUlimit("nofile=512:1024"); *u1 != *u2 { t.Fatalf("expected %q, but got %q", u1, u2) } } func TestParseUlimitInvalidLimitType(t *testing.T) { if _, err := ParseUlimit("notarealtype=1024:1024"); err == nil { t.Fatalf("expected error on invalid ulimit type") } } func TestParseUlimitBadFormat(t *testing.T) { if _, err := ParseUlimit("nofile:1024:1024"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile="); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile=:"); err == nil { t.Fatal("expected error on bad syntax") } if _, err := ParseUlimit("nofile=:1024"); err == nil { t.Fatal("expected error on bad syntax") } } func TestParseUlimitHardLessThanSoft(t *testing.T) { if _, err := ParseUlimit("nofile=1024:1"); err == nil { t.Fatal("expected error on hard limit less than soft limit") } } func TestParseUlimitInvalidValueType(t *testing.T) { if _, err := ParseUlimit("nofile=asdf"); err == nil { t.Fatal("expected error on bad value type, but got no error") } else if _, ok := err.(*strconv.NumError); !ok { t.Fatalf("expected error on bad value type, but got `%s`", err) } if _, err := ParseUlimit("nofile=1024:asdf"); err == nil { t.Fatal("expected error on bad value type, but got no error") } else if _, ok := err.(*strconv.NumError); !ok { t.Fatalf("expected error on bad value type, but got `%s`", err) } } func TestUlimitStringOutput(t *testing.T) { u := &Ulimit{"nofile", 1024, 512} if s := u.String(); s != "nofile=512:1024" { t.Fatal("expected String to return nofile=512:1024, but got", s) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/README.md ================================================ 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context.go ================================================ // 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) }) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/context_test.go ================================================ // 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" "testing" ) type keyType int const ( key1 keyType = iota key2 ) func TestContext(t *testing.T) { assertEqual := func(val interface{}, exp interface{}) { if val != exp { t.Errorf("Expected %v, got %v.", exp, val) } } r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) // Get() assertEqual(Get(r, key1), nil) // Set() Set(r, key1, "1") assertEqual(Get(r, key1), "1") assertEqual(len(data[r]), 1) Set(r, key2, "2") assertEqual(Get(r, key2), "2") assertEqual(len(data[r]), 2) //GetOk value, ok := GetOk(r, key1) assertEqual(value, "1") assertEqual(ok, true) value, ok = GetOk(r, "not exists") assertEqual(value, nil) assertEqual(ok, false) Set(r, "nil value", nil) value, ok = GetOk(r, "nil value") assertEqual(value, nil) assertEqual(ok, true) // GetAll() values := GetAll(r) assertEqual(len(values), 3) // GetAll() for empty request values = GetAll(emptyR) if values != nil { t.Error("GetAll didn't return nil value for invalid request") } // GetAllOk() values, ok = GetAllOk(r) assertEqual(len(values), 3) assertEqual(ok, true) // GetAllOk() for empty request values, ok = GetAllOk(emptyR) assertEqual(value, nil) assertEqual(ok, false) // Delete() Delete(r, key1) assertEqual(Get(r, key1), nil) assertEqual(len(data[r]), 2) Delete(r, key2) assertEqual(Get(r, key2), nil) assertEqual(len(data[r]), 1) // Clear() Clear(r) assertEqual(len(data), 0) } func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { <-wait for i := 0; i < iterations; i++ { Get(r, key) } done <- struct{}{} } func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { <-wait for i := 0; i < iterations; i++ { Set(r, key, value) } done <- struct{}{} } func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { b.StopTimer() r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) done := make(chan struct{}) b.StartTimer() for i := 0; i < b.N; i++ { wait := make(chan struct{}) for i := 0; i < numReaders; i++ { go parallelReader(r, "test", iterations, wait, done) } for i := 0; i < numWriters; i++ { go parallelWriter(r, "test", "123", iterations, wait, done) } close(wait) for i := 0; i < numReaders+numWriters; i++ { <-done } } } func BenchmarkMutexSameReadWrite1(b *testing.B) { benchmarkMutex(b, 1, 1, 32) } func BenchmarkMutexSameReadWrite2(b *testing.B) { benchmarkMutex(b, 2, 2, 32) } func BenchmarkMutexSameReadWrite4(b *testing.B) { benchmarkMutex(b, 4, 4, 32) } func BenchmarkMutex1(b *testing.B) { benchmarkMutex(b, 2, 8, 32) } func BenchmarkMutex2(b *testing.B) { benchmarkMutex(b, 16, 4, 64) } func BenchmarkMutex3(b *testing.B) { benchmarkMutex(b, 1, 2, 128) } func BenchmarkMutex4(b *testing.B) { benchmarkMutex(b, 128, 32, 256) } func BenchmarkMutex5(b *testing.B) { benchmarkMutex(b, 1024, 2048, 64) } func BenchmarkMutex6(b *testing.B) { benchmarkMutex(b, 2048, 1024, 512) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/context/doc.go ================================================ // 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/README.md ================================================ 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) 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/bench_test.go ================================================ // 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 ( "net/http" "testing" ) func BenchmarkMux(b *testing.B) { router := new(Router) handler := func(w http.ResponseWriter, r *http.Request) {} router.HandleFunc("/v1/{v1}", handler) request, _ := http.NewRequest("GET", "/v1/anything", nil) for i := 0; i < b.N; i++ { router.ServeHTTP(nil, request) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/doc.go ================================================ // 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 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: 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux.go ================================================ // 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/fsouza/go-dockerclient/external/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...) } // BuildVars 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/mux_test.go ================================================ // 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 ( "fmt" "net/http" "strings" "testing" "github.com/fsouza/go-dockerclient/external/github.com/gorilla/context" ) func (r *Route) GoString() string { matchers := make([]string, len(r.matchers)) for i, m := range r.matchers { matchers[i] = fmt.Sprintf("%#v", m) } return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", ")) } func (r *routeRegexp) GoString() string { return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR) } type routeTest struct { title string // title of the test route *Route // the route being tested request *http.Request // a request to test the route vars map[string]string // the expected vars of the match host string // the expected host of the match path string // the expected path of the match shouldMatch bool // whether the request is expected to match the route at all shouldRedirect bool // whether the request should result in a redirect } func TestHost(t *testing.T) { // newRequestHost a new request with a method, url, and host header newRequestHost := func(method, url, host string) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { panic(err) } req.Host = host return req } tests := []routeTest{ { title: "Host route match", route: new(Route).Host("aaa.bbb.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route, wrong host in request URL", route: new(Route).Host("aaa.bbb.ccc"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: false, }, { title: "Host route with port, match", route: new(Route).Host("aaa.bbb.ccc:1234"), request: newRequest("GET", "http://aaa.bbb.ccc:1234/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc:1234", path: "", shouldMatch: true, }, { title: "Host route with port, wrong port in request URL", route: new(Route).Host("aaa.bbb.ccc:1234"), request: newRequest("GET", "http://aaa.bbb.ccc:9999/111/222/333"), vars: map[string]string{}, host: "aaa.bbb.ccc:1234", path: "", shouldMatch: false, }, { title: "Host route, match with host in request header", route: new(Route).Host("aaa.bbb.ccc"), request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route, wrong host in request header", route: new(Route).Host("aaa.bbb.ccc"), request: newRequestHost("GET", "/111/222/333", "aaa.222.ccc"), vars: map[string]string{}, host: "aaa.bbb.ccc", path: "", shouldMatch: false, }, // BUG {new(Route).Host("aaa.bbb.ccc:1234"), newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:1234"), map[string]string{}, "aaa.bbb.ccc:1234", "", true}, { title: "Host route with port, wrong host in request header", route: new(Route).Host("aaa.bbb.ccc:1234"), request: newRequestHost("GET", "/111/222/333", "aaa.bbb.ccc:9999"), vars: map[string]string{}, host: "aaa.bbb.ccc:1234", path: "", shouldMatch: false, }, { title: "Host route with pattern, match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb"}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route with pattern, additional capturing group, match", route: new(Route).Host("aaa.{v1:[a-z]{2}(b|c)}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb"}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route with pattern, wrong host in request URL", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "bbb"}, host: "aaa.bbb.ccc", path: "", shouldMatch: false, }, { title: "Host route with multiple patterns, match", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route with multiple patterns, wrong host in request URL", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"}, host: "aaa.bbb.ccc", path: "", shouldMatch: false, }, { title: "Host route with hyphenated name and pattern, match", route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v-1": "bbb"}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route with hyphenated name and pattern, additional capturing group, match", route: new(Route).Host("aaa.{v-1:[a-z]{2}(b|c)}.ccc"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v-1": "bbb"}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Host route with multiple hyphenated names and patterns, match", route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"}, host: "aaa.bbb.ccc", path: "", shouldMatch: true, }, { title: "Path route with single pattern with pipe, match", route: new(Route).Path("/{category:a|b/c}"), request: newRequest("GET", "http://localhost/a"), vars: map[string]string{"category": "a"}, host: "", path: "/a", shouldMatch: true, }, { title: "Path route with single pattern with pipe, match", route: new(Route).Path("/{category:a|b/c}"), request: newRequest("GET", "http://localhost/b/c"), vars: map[string]string{"category": "b/c"}, host: "", path: "/b/c", shouldMatch: true, }, { title: "Path route with multiple patterns with pipe, match", route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), request: newRequest("GET", "http://localhost/a/product_name/1"), vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, host: "", path: "/a/product_name/1", shouldMatch: true, }, { title: "Path route with multiple patterns with pipe, match", route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"), request: newRequest("GET", "http://localhost/b/c/product_name/1"), vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"}, host: "", path: "/b/c/product_name/1", shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) } } func TestPath(t *testing.T) { tests := []routeTest{ { title: "Path route, match", route: new(Route).Path("/111/222/333"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{}, host: "", path: "/111/222/333", shouldMatch: true, }, { title: "Path route, match with trailing slash in request and path", route: new(Route).Path("/111/"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: true, }, { title: "Path route, do not match with trailing slash in path", route: new(Route).Path("/111/"), request: newRequest("GET", "http://localhost/111"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: false, }, { title: "Path route, do not match with trailing slash in request", route: new(Route).Path("/111"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: false, }, { title: "Path route, wrong path in request in request URL", route: new(Route).Path("/111/222/333"), request: newRequest("GET", "http://localhost/1/2/3"), vars: map[string]string{}, host: "", path: "/111/222/333", shouldMatch: false, }, { title: "Path route with pattern, match", route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222/333", shouldMatch: true, }, { title: "Path route with pattern, URL in request does not match", route: new(Route).Path("/111/{v1:[0-9]{3}}/333"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222/333", shouldMatch: false, }, { title: "Path route with multiple patterns, match", route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, host: "", path: "/111/222/333", shouldMatch: true, }, { title: "Path route with multiple patterns, URL in request does not match", route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"}, host: "", path: "/111/222/333", shouldMatch: false, }, { title: "Path route with multiple patterns with pipe, match", route: new(Route).Path("/{category:a|(b/c)}/{product}/{id:[0-9]+}"), request: newRequest("GET", "http://localhost/a/product_name/1"), vars: map[string]string{"category": "a", "product": "product_name", "id": "1"}, host: "", path: "/a/product_name/1", shouldMatch: true, }, { title: "Path route with hyphenated name and pattern, match", route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v-1": "222"}, host: "", path: "/111/222/333", shouldMatch: true, }, { title: "Path route with multiple hyphenated names and patterns, match", route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"}, host: "", path: "/111/222/333", shouldMatch: true, }, { title: "Path route with multiple hyphenated names and patterns with pipe, match", route: new(Route).Path("/{product-category:a|(b/c)}/{product-name}/{product-id:[0-9]+}"), request: newRequest("GET", "http://localhost/a/product_name/1"), vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"}, host: "", path: "/a/product_name/1", shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) } } func TestPathPrefix(t *testing.T) { tests := []routeTest{ { title: "PathPrefix route, match", route: new(Route).PathPrefix("/111"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: true, }, { title: "PathPrefix route, match substring", route: new(Route).PathPrefix("/1"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{}, host: "", path: "/1", shouldMatch: true, }, { title: "PathPrefix route, URL prefix in request does not match", route: new(Route).PathPrefix("/111"), request: newRequest("GET", "http://localhost/1/2/3"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: false, }, { title: "PathPrefix route with pattern, match", route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222", shouldMatch: true, }, { title: "PathPrefix route with pattern, URL prefix in request does not match", route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "222"}, host: "", path: "/111/222", shouldMatch: false, }, { title: "PathPrefix route with multiple patterns, match", route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/222/333"), vars: map[string]string{"v1": "111", "v2": "222"}, host: "", path: "/111/222", shouldMatch: true, }, { title: "PathPrefix route with multiple patterns, URL prefix in request does not match", route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"), request: newRequest("GET", "http://localhost/111/aaa/333"), vars: map[string]string{"v1": "111", "v2": "222"}, host: "", path: "/111/222", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestHostPath(t *testing.T) { tests := []routeTest{ { title: "Host and Path route, match", route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Host and Path route, wrong host in request URL", route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Host and Path route with pattern, match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "bbb", "v2": "222"}, host: "aaa.bbb.ccc", path: "/111/222/333", shouldMatch: true, }, { title: "Host and Path route with pattern, URL in request does not match", route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "bbb", "v2": "222"}, host: "aaa.bbb.ccc", path: "/111/222/333", shouldMatch: false, }, { title: "Host and Path route with multiple patterns, match", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, host: "aaa.bbb.ccc", path: "/111/222/333", shouldMatch: true, }, { title: "Host and Path route with multiple patterns, URL in request does not match", route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"), request: newRequest("GET", "http://aaa.222.ccc/111/222/333"), vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"}, host: "aaa.bbb.ccc", path: "/111/222/333", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestHeaders(t *testing.T) { // newRequestHeaders creates a new request with a method, url, and headers newRequestHeaders := func(method, url string, headers map[string]string) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { panic(err) } for k, v := range headers { req.Header.Add(k, v) } return req } tests := []routeTest{ { title: "Headers route, match", route: new(Route).Headers("foo", "bar", "baz", "ding"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "ding"}), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Headers route, bad header values", route: new(Route).Headers("foo", "bar", "baz", "ding"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar", "baz": "dong"}), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Headers route, regex header values to match", route: new(Route).Headers("foo", "ba[zr]"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Headers route, regex header values to match", route: new(Route).HeadersRegexp("foo", "ba[zr]"), request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) } } func TestMethods(t *testing.T) { tests := []routeTest{ { title: "Methods route, match GET", route: new(Route).Methods("GET", "POST"), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Methods route, match POST", route: new(Route).Methods("GET", "POST"), request: newRequest("POST", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Methods route, bad method", route: new(Route).Methods("GET", "POST"), request: newRequest("PUT", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestQueries(t *testing.T) { tests := []routeTest{ { title: "Queries route, match", route: new(Route).Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Queries route, match with a query string", route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Queries route, match with a query string out of order", route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Queries route, bad query", route: new(Route).Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://localhost?foo=bar&baz=dong"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with pattern, match", route: new(Route).Queries("foo", "{v1}"), request: newRequest("GET", "http://localhost?foo=bar"), vars: map[string]string{"v1": "bar"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with multiple patterns, match", route: new(Route).Queries("foo", "{v1}", "baz", "{v2}"), request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), vars: map[string]string{"v1": "bar", "v2": "ding"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with regexp pattern, match", route: new(Route).Queries("foo", "{v1:[0-9]+}"), request: newRequest("GET", "http://localhost?foo=10"), vars: map[string]string{"v1": "10"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with regexp pattern, regexp does not match", route: new(Route).Queries("foo", "{v1:[0-9]+}"), request: newRequest("GET", "http://localhost?foo=a"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with regexp pattern with quantifier, match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?foo=1"), vars: map[string]string{"v1": "1"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with regexp pattern with quantifier, additional variable in query string, match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?bar=2&foo=1"), vars: map[string]string{"v1": "1"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with regexp pattern with quantifier, regexp does not match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?foo=12"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with regexp pattern with quantifier, additional capturing group", route: new(Route).Queries("foo", "{v1:[0-9]{1}(a|b)}"), request: newRequest("GET", "http://localhost?foo=1a"), vars: map[string]string{"v1": "1a"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match", route: new(Route).Queries("foo", "{v1:[0-9]{1}}"), request: newRequest("GET", "http://localhost?foo=12"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with hyphenated name, match", route: new(Route).Queries("foo", "{v-1}"), request: newRequest("GET", "http://localhost?foo=bar"), vars: map[string]string{"v-1": "bar"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with multiple hyphenated names, match", route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"), request: newRequest("GET", "http://localhost?foo=bar&baz=ding"), vars: map[string]string{"v-1": "bar", "v-2": "ding"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with hyphenate name and pattern, match", route: new(Route).Queries("foo", "{v-1:[0-9]+}"), request: newRequest("GET", "http://localhost?foo=10"), vars: map[string]string{"v-1": "10"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group", route: new(Route).Queries("foo", "{v-1:[0-9]{1}(a|b)}"), request: newRequest("GET", "http://localhost?foo=1a"), vars: map[string]string{"v-1": "1a"}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with empty value, should match", route: new(Route).Queries("foo", ""), request: newRequest("GET", "http://localhost?foo=bar"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with empty value and no parameter in request, should not match", route: new(Route).Queries("foo", ""), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with empty value and empty parameter in request, should match", route: new(Route).Queries("foo", ""), request: newRequest("GET", "http://localhost?foo="), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Queries route with overlapping value, should not match", route: new(Route).Queries("foo", "bar"), request: newRequest("GET", "http://localhost?foo=barfoo"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with no parameter in request, should not match", route: new(Route).Queries("foo", "{bar}"), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, { title: "Queries route with empty parameter in request, should match", route: new(Route).Queries("foo", "{bar}"), request: newRequest("GET", "http://localhost?foo="), vars: map[string]string{"foo": ""}, host: "", path: "", shouldMatch: true, }, { title: "Queries route, bad submatch", route: new(Route).Queries("foo", "bar", "baz", "ding"), request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestSchemes(t *testing.T) { tests := []routeTest{ // Schemes { title: "Schemes route, match https", route: new(Route).Schemes("https", "ftp"), request: newRequest("GET", "https://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Schemes route, match ftp", route: new(Route).Schemes("https", "ftp"), request: newRequest("GET", "ftp://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "Schemes route, bad scheme", route: new(Route).Schemes("https", "ftp"), request: newRequest("GET", "http://localhost"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestMatcherFunc(t *testing.T) { m := func(r *http.Request, m *RouteMatch) bool { if r.URL.Host == "aaa.bbb.ccc" { return true } return false } tests := []routeTest{ { title: "MatchFunc route, match", route: new(Route).MatcherFunc(m), request: newRequest("GET", "http://aaa.bbb.ccc"), vars: map[string]string{}, host: "", path: "", shouldMatch: true, }, { title: "MatchFunc route, non-match", route: new(Route).MatcherFunc(m), request: newRequest("GET", "http://aaa.222.ccc"), vars: map[string]string{}, host: "", path: "", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestBuildVarsFunc(t *testing.T) { tests := []routeTest{ { title: "BuildVarsFunc set on route", route: new(Route).Path(`/111/{v1:\d}{v2:.*}`).BuildVarsFunc(func(vars map[string]string) map[string]string { vars["v1"] = "3" vars["v2"] = "a" return vars }), request: newRequest("GET", "http://localhost/111/2"), path: "/111/3a", shouldMatch: true, }, { title: "BuildVarsFunc set on route and parent route", route: new(Route).PathPrefix(`/{v1:\d}`).BuildVarsFunc(func(vars map[string]string) map[string]string { vars["v1"] = "2" return vars }).Subrouter().Path(`/{v2:\w}`).BuildVarsFunc(func(vars map[string]string) map[string]string { vars["v2"] = "b" return vars }), request: newRequest("GET", "http://localhost/1/a"), path: "/2/b", shouldMatch: true, }, } for _, test := range tests { testRoute(t, test) } } func TestSubRouter(t *testing.T) { subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter() subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter() tests := []routeTest{ { route: subrouter1.Path("/{v2:[a-z]+}"), request: newRequest("GET", "http://aaa.google.com/bbb"), vars: map[string]string{"v1": "aaa", "v2": "bbb"}, host: "aaa.google.com", path: "/bbb", shouldMatch: true, }, { route: subrouter1.Path("/{v2:[a-z]+}"), request: newRequest("GET", "http://111.google.com/111"), vars: map[string]string{"v1": "aaa", "v2": "bbb"}, host: "aaa.google.com", path: "/bbb", shouldMatch: false, }, { route: subrouter2.Path("/baz/{v2}"), request: newRequest("GET", "http://localhost/foo/bar/baz/ding"), vars: map[string]string{"v1": "bar", "v2": "ding"}, host: "", path: "/foo/bar/baz/ding", shouldMatch: true, }, { route: subrouter2.Path("/baz/{v2}"), request: newRequest("GET", "http://localhost/foo/bar"), vars: map[string]string{"v1": "bar", "v2": "ding"}, host: "", path: "/foo/bar/baz/ding", shouldMatch: false, }, } for _, test := range tests { testRoute(t, test) } } func TestNamedRoutes(t *testing.T) { r1 := NewRouter() r1.NewRoute().Name("a") r1.NewRoute().Name("b") r1.NewRoute().Name("c") r2 := r1.NewRoute().Subrouter() r2.NewRoute().Name("d") r2.NewRoute().Name("e") r2.NewRoute().Name("f") r3 := r2.NewRoute().Subrouter() r3.NewRoute().Name("g") r3.NewRoute().Name("h") r3.NewRoute().Name("i") if r1.namedRoutes == nil || len(r1.namedRoutes) != 9 { t.Errorf("Expected 9 named routes, got %v", r1.namedRoutes) } else if r1.Get("i") == nil { t.Errorf("Subroute name not registered") } } func TestStrictSlash(t *testing.T) { r := NewRouter() r.StrictSlash(true) tests := []routeTest{ { title: "Redirect path without slash", route: r.NewRoute().Path("/111/"), request: newRequest("GET", "http://localhost/111"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: true, shouldRedirect: true, }, { title: "Do not redirect path with slash", route: r.NewRoute().Path("/111/"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111/", shouldMatch: true, shouldRedirect: false, }, { title: "Redirect path with slash", route: r.NewRoute().Path("/111"), request: newRequest("GET", "http://localhost/111/"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: true, shouldRedirect: true, }, { title: "Do not redirect path without slash", route: r.NewRoute().Path("/111"), request: newRequest("GET", "http://localhost/111"), vars: map[string]string{}, host: "", path: "/111", shouldMatch: true, shouldRedirect: false, }, { title: "Propagate StrictSlash to subrouters", route: r.NewRoute().PathPrefix("/static/").Subrouter().Path("/images/"), request: newRequest("GET", "http://localhost/static/images"), vars: map[string]string{}, host: "", path: "/static/images/", shouldMatch: true, shouldRedirect: true, }, { title: "Ignore StrictSlash for path prefix", route: r.NewRoute().PathPrefix("/static/"), request: newRequest("GET", "http://localhost/static/logo.png"), vars: map[string]string{}, host: "", path: "/static/", shouldMatch: true, shouldRedirect: false, }, } for _, test := range tests { testRoute(t, test) } } func TestWalkSingleDepth(t *testing.T) { r0 := NewRouter() r1 := NewRouter() r2 := NewRouter() r0.Path("/g") r0.Path("/o") r0.Path("/d").Handler(r1) r0.Path("/r").Handler(r2) r0.Path("/a") r1.Path("/z") r1.Path("/i") r1.Path("/l") r1.Path("/l") r2.Path("/i") r2.Path("/l") r2.Path("/l") paths := []string{"g", "o", "r", "i", "l", "l", "a"} depths := []int{0, 0, 0, 1, 1, 1, 0} i := 0 err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error { matcher := route.matchers[0].(*routeRegexp) if matcher.template == "/d" { return SkipRouter } if len(ancestors) != depths[i] { t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors)) } if matcher.template != "/"+paths[i] { t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template) } i++ return nil }) if err != nil { panic(err) } if i != len(paths) { t.Errorf("Expected %d routes, found %d", len(paths), i) } } func TestWalkNested(t *testing.T) { router := NewRouter() g := router.Path("/g").Subrouter() o := g.PathPrefix("/o").Subrouter() r := o.PathPrefix("/r").Subrouter() i := r.PathPrefix("/i").Subrouter() l1 := i.PathPrefix("/l").Subrouter() l2 := l1.PathPrefix("/l").Subrouter() l2.Path("/a") paths := []string{"/g", "/g/o", "/g/o/r", "/g/o/r/i", "/g/o/r/i/l", "/g/o/r/i/l/l", "/g/o/r/i/l/l/a"} idx := 0 err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error { path := paths[idx] tpl := route.regexp.path.template if tpl != path { t.Errorf(`Expected %s got %s`, path, tpl) } idx++ return nil }) if err != nil { panic(err) } if idx != len(paths) { t.Errorf("Expected %d routes, found %d", len(paths), idx) } } func TestSubrouterErrorHandling(t *testing.T) { superRouterCalled := false subRouterCalled := false router := NewRouter() router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { superRouterCalled = true }) subRouter := router.PathPrefix("/bign8").Subrouter() subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { subRouterCalled = true }) req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil) router.ServeHTTP(NewRecorder(), req) if superRouterCalled { t.Error("Super router 404 handler called when sub-router 404 handler is available.") } if !subRouterCalled { t.Error("Sub-router 404 handler was not called.") } } // ---------------------------------------------------------------------------- // Helpers // ---------------------------------------------------------------------------- func getRouteTemplate(route *Route) string { host, path := "none", "none" if route.regexp != nil { if route.regexp.host != nil { host = route.regexp.host.template } if route.regexp.path != nil { path = route.regexp.path.template } } return fmt.Sprintf("Host: %v, Path: %v", host, path) } func testRoute(t *testing.T, test routeTest) { request := test.request route := test.route vars := test.vars shouldMatch := test.shouldMatch host := test.host path := test.path url := test.host + test.path shouldRedirect := test.shouldRedirect var match RouteMatch ok := route.Match(request, &match) if ok != shouldMatch { msg := "Should match" if !shouldMatch { msg = "Should not match" } t.Errorf("(%v) %v:\nRoute: %#v\nRequest: %#v\nVars: %v\n", test.title, msg, route, request, vars) return } if shouldMatch { if test.vars != nil && !stringMapEqual(test.vars, match.Vars) { t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars) return } if host != "" { u, _ := test.route.URLHost(mapToPairs(match.Vars)...) if host != u.Host { t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route)) return } } if path != "" { u, _ := route.URLPath(mapToPairs(match.Vars)...) if path != u.Path { t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route)) return } } if url != "" { u, _ := route.URL(mapToPairs(match.Vars)...) if url != u.Host+u.Path { t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route)) return } } if shouldRedirect && match.Handler == nil { t.Errorf("(%v) Did not redirect", test.title) return } if !shouldRedirect && match.Handler != nil { t.Errorf("(%v) Unexpected redirect", test.title) return } } } // Tests that the context is cleared or not cleared properly depending on // the configuration of the router func TestKeepContext(t *testing.T) { func1 := func(w http.ResponseWriter, r *http.Request) {} r := NewRouter() r.HandleFunc("/", func1).Name("func1") req, _ := http.NewRequest("GET", "http://localhost/", nil) context.Set(req, "t", 1) res := new(http.ResponseWriter) r.ServeHTTP(*res, req) if _, ok := context.GetOk(req, "t"); ok { t.Error("Context should have been cleared at end of request") } r.KeepContext = true req, _ = http.NewRequest("GET", "http://localhost/", nil) context.Set(req, "t", 1) r.ServeHTTP(*res, req) if _, ok := context.GetOk(req, "t"); !ok { t.Error("Context should NOT have been cleared at end of request") } } type TestA301ResponseWriter struct { hh http.Header status int } func (ho TestA301ResponseWriter) Header() http.Header { return http.Header(ho.hh) } func (ho TestA301ResponseWriter) Write(b []byte) (int, error) { return 0, nil } func (ho TestA301ResponseWriter) WriteHeader(code int) { ho.status = code } func Test301Redirect(t *testing.T) { m := make(http.Header) func1 := func(w http.ResponseWriter, r *http.Request) {} func2 := func(w http.ResponseWriter, r *http.Request) {} r := NewRouter() r.HandleFunc("/api/", func2).Name("func2") r.HandleFunc("/", func1).Name("func1") req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil) res := TestA301ResponseWriter{ hh: m, status: 0, } r.ServeHTTP(&res, req) if "http://localhost/api/?abc=def" != res.hh["Location"][0] { t.Errorf("Should have complete URL with query string") } } // https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW func TestSubrouterHeader(t *testing.T) { expected := "func1 response" func1 := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, expected) } func2 := func(http.ResponseWriter, *http.Request) {} r := NewRouter() s := r.Headers("SomeSpecialHeader", "").Subrouter() s.HandleFunc("/", func1).Name("func1") r.HandleFunc("/", func2).Name("func2") req, _ := http.NewRequest("GET", "http://localhost/", nil) req.Header.Add("SomeSpecialHeader", "foo") match := new(RouteMatch) matched := r.Match(req, match) if !matched { t.Errorf("Should match request") } if match.Route.GetName() != "func1" { t.Errorf("Expecting func1 handler, got %s", match.Route.GetName()) } resp := NewRecorder() match.Handler.ServeHTTP(resp, req) if resp.Body.String() != expected { t.Errorf("Expecting %q", expected) } } // mapToPairs converts a string map to a slice of string pairs func mapToPairs(m map[string]string) []string { var i int p := make([]string, len(m)*2) for k, v := range m { p[i] = k p[i+1] = v i += 2 } return p } // stringMapEqual checks the equality of two string maps func stringMapEqual(m1, m2 map[string]string) bool { nil1 := m1 == nil nil2 := m2 == nil if nil1 != nil2 || len(m1) != len(m2) { return false } for k, v := range m1 { if v != m2[k] { return false } } return true } // newRequest is a helper function to create a new request with a method and url func newRequest(method, url string) *http.Request { req, err := http.NewRequest(method, url, nil) if err != nil { panic(err) } return req } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/old_test.go ================================================ // Old tests ported to Go1. This is a mess. Want to drop it one day. // Copyright 2011 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" "net/http" "testing" ) // ---------------------------------------------------------------------------- // ResponseRecorder // ---------------------------------------------------------------------------- // 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. // ResponseRecorder is an implementation of http.ResponseWriter that // records its mutations for later inspection in tests. type ResponseRecorder struct { Code int // the HTTP response code from WriteHeader HeaderMap http.Header // the HTTP response headers Body *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to Flushed bool } // NewRecorder returns an initialized ResponseRecorder. func NewRecorder() *ResponseRecorder { return &ResponseRecorder{ HeaderMap: make(http.Header), Body: new(bytes.Buffer), } } // DefaultRemoteAddr is the default remote address to return in RemoteAddr if // an explicit DefaultRemoteAddr isn't set on ResponseRecorder. const DefaultRemoteAddr = "1.2.3.4" // Header returns the response headers. func (rw *ResponseRecorder) Header() http.Header { return rw.HeaderMap } // Write always succeeds and writes to rw.Body, if not nil. func (rw *ResponseRecorder) Write(buf []byte) (int, error) { if rw.Body != nil { rw.Body.Write(buf) } if rw.Code == 0 { rw.Code = http.StatusOK } return len(buf), nil } // WriteHeader sets rw.Code. func (rw *ResponseRecorder) WriteHeader(code int) { rw.Code = code } // Flush sets rw.Flushed to true. func (rw *ResponseRecorder) Flush() { rw.Flushed = true } // ---------------------------------------------------------------------------- func TestRouteMatchers(t *testing.T) { var scheme, host, path, query, method string var headers map[string]string var resultVars map[bool]map[string]string router := NewRouter() router.NewRoute().Host("{var1}.google.com"). Path("/{var2:[a-z]+}/{var3:[0-9]+}"). Queries("foo", "bar"). Methods("GET"). Schemes("https"). Headers("x-requested-with", "XMLHttpRequest") router.NewRoute().Host("www.{var4}.com"). PathPrefix("/foo/{var5:[a-z]+}/{var6:[0-9]+}"). Queries("baz", "ding"). Methods("POST"). Schemes("http"). Headers("Content-Type", "application/json") reset := func() { // Everything match. scheme = "https" host = "www.google.com" path = "/product/42" query = "?foo=bar" method = "GET" headers = map[string]string{"X-Requested-With": "XMLHttpRequest"} resultVars = map[bool]map[string]string{ true: {"var1": "www", "var2": "product", "var3": "42"}, false: {}, } } reset2 := func() { // Everything match. scheme = "http" host = "www.google.com" path = "/foo/product/42/path/that/is/ignored" query = "?baz=ding" method = "POST" headers = map[string]string{"Content-Type": "application/json"} resultVars = map[bool]map[string]string{ true: {"var4": "google", "var5": "product", "var6": "42"}, false: {}, } } match := func(shouldMatch bool) { url := scheme + "://" + host + path + query request, _ := http.NewRequest(method, url, nil) for key, value := range headers { request.Header.Add(key, value) } var routeMatch RouteMatch matched := router.Match(request, &routeMatch) if matched != shouldMatch { // Need better messages. :) if matched { t.Errorf("Should match.") } else { t.Errorf("Should not match.") } } if matched { currentRoute := routeMatch.Route if currentRoute == nil { t.Errorf("Expected a current route.") } vars := routeMatch.Vars expectedVars := resultVars[shouldMatch] if len(vars) != len(expectedVars) { t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) } for name, value := range vars { if expectedVars[name] != value { t.Errorf("Expected vars: %v Got: %v.", expectedVars, vars) } } } } // 1st route -------------------------------------------------------------- // Everything match. reset() match(true) // Scheme doesn't match. reset() scheme = "http" match(false) // Host doesn't match. reset() host = "www.mygoogle.com" match(false) // Path doesn't match. reset() path = "/product/notdigits" match(false) // Query doesn't match. reset() query = "?foo=baz" match(false) // Method doesn't match. reset() method = "POST" match(false) // Header doesn't match. reset() headers = map[string]string{} match(false) // Everything match, again. reset() match(true) // 2nd route -------------------------------------------------------------- // Everything match. reset2() match(true) // Scheme doesn't match. reset2() scheme = "https" match(false) // Host doesn't match. reset2() host = "sub.google.com" match(false) // Path doesn't match. reset2() path = "/bar/product/42" match(false) // Query doesn't match. reset2() query = "?foo=baz" match(false) // Method doesn't match. reset2() method = "GET" match(false) // Header doesn't match. reset2() headers = map[string]string{} match(false) // Everything match, again. reset2() match(true) } type headerMatcherTest struct { matcher headerMatcher headers map[string]string result bool } var headerMatcherTests = []headerMatcherTest{ { matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), headers: map[string]string{"X-Requested-With": "XMLHttpRequest"}, result: true, }, { matcher: headerMatcher(map[string]string{"x-requested-with": ""}), headers: map[string]string{"X-Requested-With": "anything"}, result: true, }, { matcher: headerMatcher(map[string]string{"x-requested-with": "XMLHttpRequest"}), headers: map[string]string{}, result: false, }, } type hostMatcherTest struct { matcher *Route url string vars map[string]string result bool } var hostMatcherTests = []hostMatcherTest{ { matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), url: "http://abc.def.ghi/", vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, result: true, }, { matcher: NewRouter().NewRoute().Host("{foo:[a-z][a-z][a-z]}.{bar:[a-z][a-z][a-z]}.{baz:[a-z][a-z][a-z]}"), url: "http://a.b.c/", vars: map[string]string{"foo": "abc", "bar": "def", "baz": "ghi"}, result: false, }, } type methodMatcherTest struct { matcher methodMatcher method string result bool } var methodMatcherTests = []methodMatcherTest{ { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "GET", result: true, }, { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "POST", result: true, }, { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "PUT", result: true, }, { matcher: methodMatcher([]string{"GET", "POST", "PUT"}), method: "DELETE", result: false, }, } type pathMatcherTest struct { matcher *Route url string vars map[string]string result bool } var pathMatcherTests = []pathMatcherTest{ { matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), url: "http://localhost:8080/123/456/789", vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, result: true, }, { matcher: NewRouter().NewRoute().Path("/{foo:[0-9][0-9][0-9]}/{bar:[0-9][0-9][0-9]}/{baz:[0-9][0-9][0-9]}"), url: "http://localhost:8080/1/2/3", vars: map[string]string{"foo": "123", "bar": "456", "baz": "789"}, result: false, }, } type schemeMatcherTest struct { matcher schemeMatcher url string result bool } var schemeMatcherTests = []schemeMatcherTest{ { matcher: schemeMatcher([]string{"http", "https"}), url: "http://localhost:8080/", result: true, }, { matcher: schemeMatcher([]string{"http", "https"}), url: "https://localhost:8080/", result: true, }, { matcher: schemeMatcher([]string{"https"}), url: "http://localhost:8080/", result: false, }, { matcher: schemeMatcher([]string{"http"}), url: "https://localhost:8080/", result: false, }, } type urlBuildingTest struct { route *Route vars []string url string } var urlBuildingTests = []urlBuildingTest{ { route: new(Route).Host("foo.domain.com"), vars: []string{}, url: "http://foo.domain.com", }, { route: new(Route).Host("{subdomain}.domain.com"), vars: []string{"subdomain", "bar"}, url: "http://bar.domain.com", }, { route: new(Route).Host("foo.domain.com").Path("/articles"), vars: []string{}, url: "http://foo.domain.com/articles", }, { route: new(Route).Path("/articles"), vars: []string{}, url: "/articles", }, { route: new(Route).Path("/articles/{category}/{id:[0-9]+}"), vars: []string{"category", "technology", "id", "42"}, url: "/articles/technology/42", }, { route: new(Route).Host("{subdomain}.domain.com").Path("/articles/{category}/{id:[0-9]+}"), vars: []string{"subdomain", "foo", "category", "technology", "id", "42"}, url: "http://foo.domain.com/articles/technology/42", }, } func TestHeaderMatcher(t *testing.T) { for _, v := range headerMatcherTests { request, _ := http.NewRequest("GET", "http://localhost:8080/", nil) for key, value := range v.headers { request.Header.Add(key, value) } var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, request.Header) } else { t.Errorf("%#v: should not match %v.", v.matcher, request.Header) } } } } func TestHostMatcher(t *testing.T) { for _, v := range hostMatcherTests { request, _ := http.NewRequest("GET", v.url, nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) vars := routeMatch.Vars if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.url) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.url) } } if result { if len(vars) != len(v.vars) { t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) } for name, value := range vars { if v.vars[name] != value { t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) } } } else { if len(vars) != 0 { t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) } } } } func TestMethodMatcher(t *testing.T) { for _, v := range methodMatcherTests { request, _ := http.NewRequest(v.method, "http://localhost:8080/", nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.method) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.method) } } } } func TestPathMatcher(t *testing.T) { for _, v := range pathMatcherTests { request, _ := http.NewRequest("GET", v.url, nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) vars := routeMatch.Vars if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.url) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.url) } } if result { if len(vars) != len(v.vars) { t.Errorf("%#v: vars length should be %v, got %v.", v.matcher, len(v.vars), len(vars)) } for name, value := range vars { if v.vars[name] != value { t.Errorf("%#v: expected value %v for key %v, got %v.", v.matcher, v.vars[name], name, value) } } } else { if len(vars) != 0 { t.Errorf("%#v: vars length should be 0, got %v.", v.matcher, len(vars)) } } } } func TestSchemeMatcher(t *testing.T) { for _, v := range schemeMatcherTests { request, _ := http.NewRequest("GET", v.url, nil) var routeMatch RouteMatch result := v.matcher.Match(request, &routeMatch) if result != v.result { if v.result { t.Errorf("%#v: should match %v.", v.matcher, v.url) } else { t.Errorf("%#v: should not match %v.", v.matcher, v.url) } } } } func TestUrlBuilding(t *testing.T) { for _, v := range urlBuildingTests { u, _ := v.route.URL(v.vars...) url := u.String() if url != v.url { t.Errorf("expected %v, got %v", v.url, url) /* reversePath := "" reverseHost := "" if v.route.pathTemplate != nil { reversePath = v.route.pathTemplate.Reverse } if v.route.hostTemplate != nil { reverseHost = v.route.hostTemplate.Reverse } t.Errorf("%#v:\nexpected: %q\ngot: %q\nreverse path: %q\nreverse host: %q", v.route, v.url, url, reversePath, reverseHost) */ } } ArticleHandler := func(w http.ResponseWriter, r *http.Request) { } router := NewRouter() router.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).Name("article") url, _ := router.Get("article").URL("category", "technology", "id", "42") expected := "/articles/technology/42" if url.String() != expected { t.Errorf("Expected %v, got %v", expected, url.String()) } } func TestMatchedRouteName(t *testing.T) { routeName := "stock" router := NewRouter() route := router.NewRoute().Path("/products/").Name(routeName) url := "http://www.example.com/products/" request, _ := http.NewRequest("GET", url, nil) var rv RouteMatch ok := router.Match(request, &rv) if !ok || rv.Route != route { t.Errorf("Expected same route, got %+v.", rv.Route) } retName := rv.Route.GetName() if retName != routeName { t.Errorf("Expected %q, got %q.", routeName, retName) } } func TestSubRouting(t *testing.T) { // Example from docs. router := NewRouter() subrouter := router.NewRoute().Host("www.example.com").Subrouter() route := subrouter.NewRoute().Path("/products/").Name("products") url := "http://www.example.com/products/" request, _ := http.NewRequest("GET", url, nil) var rv RouteMatch ok := router.Match(request, &rv) if !ok || rv.Route != route { t.Errorf("Expected same route, got %+v.", rv.Route) } u, _ := router.Get("products").URL() builtUrl := u.String() // Yay, subroute aware of the domain when building! if builtUrl != url { t.Errorf("Expected %q, got %q.", url, builtUrl) } } func TestVariableNames(t *testing.T) { route := new(Route).Host("{arg1}.domain.com").Path("/{arg1}/{arg2:[0-9]+}") if route.err == nil { t.Errorf("Expected error for duplicated variable names") } } func TestRedirectSlash(t *testing.T) { var route *Route var routeMatch RouteMatch r := NewRouter() r.StrictSlash(false) route = r.NewRoute() if route.strictSlash != false { t.Errorf("Expected false redirectSlash.") } r.StrictSlash(true) route = r.NewRoute() if route.strictSlash != true { t.Errorf("Expected true redirectSlash.") } route = new(Route) route.strictSlash = true route.Path("/{arg1}/{arg2:[0-9]+}/") request, _ := http.NewRequest("GET", "http://localhost/foo/123", nil) routeMatch = RouteMatch{} _ = route.Match(request, &routeMatch) vars := routeMatch.Vars if vars["arg1"] != "foo" { t.Errorf("Expected foo.") } if vars["arg2"] != "123" { t.Errorf("Expected 123.") } rsp := NewRecorder() routeMatch.Handler.ServeHTTP(rsp, request) if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123/" { t.Errorf("Expected redirect header.") } route = new(Route) route.strictSlash = true route.Path("/{arg1}/{arg2:[0-9]+}") request, _ = http.NewRequest("GET", "http://localhost/foo/123/", nil) routeMatch = RouteMatch{} _ = route.Match(request, &routeMatch) vars = routeMatch.Vars if vars["arg1"] != "foo" { t.Errorf("Expected foo.") } if vars["arg2"] != "123" { t.Errorf("Expected 123.") } rsp = NewRecorder() routeMatch.Handler.ServeHTTP(rsp, request) if rsp.HeaderMap.Get("Location") != "http://localhost/foo/123" { t.Errorf("Expected redirect header.") } } // Test for the new regexp library, still not available in stable Go. func TestNewRegexp(t *testing.T) { var p *routeRegexp var matches []string tests := map[string]map[string][]string{ "/{foo:a{2}}": { "/a": nil, "/aa": {"aa"}, "/aaa": nil, "/aaaa": nil, }, "/{foo:a{2,}}": { "/a": nil, "/aa": {"aa"}, "/aaa": {"aaa"}, "/aaaa": {"aaaa"}, }, "/{foo:a{2,3}}": { "/a": nil, "/aa": {"aa"}, "/aaa": {"aaa"}, "/aaaa": nil, }, "/{foo:[a-z]{3}}/{bar:[a-z]{2}}": { "/a": nil, "/ab": nil, "/abc": nil, "/abcd": nil, "/abc/ab": {"abc", "ab"}, "/abc/abc": nil, "/abcd/ab": nil, }, `/{foo:\w{3,}}/{bar:\d{2,}}`: { "/a": nil, "/ab": nil, "/abc": nil, "/abc/1": nil, "/abc/12": {"abc", "12"}, "/abcd/12": {"abcd", "12"}, "/abcd/123": {"abcd", "123"}, }, } for pattern, paths := range tests { p, _ = newRouteRegexp(pattern, false, false, false, false) for path, result := range paths { matches = p.regexp.FindStringSubmatch(path) if result == nil { if matches != nil { t.Errorf("%v should not match %v.", pattern, path) } } else { if len(matches) != len(result)+1 { t.Errorf("Expected %v matches, got %v.", len(result)+1, len(matches)) } else { for k, v := range result { if matches[k+1] != v { t.Errorf("Expected %v, got %v.", v, matches[k+1]) } } } } } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/regexp.go ================================================ // 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. varIdx := i / 2 fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(varIdx), patt) // Build the reverse template. fmt.Fprintf(reverse, "%s%%s", raw) // Append variable name and compiled pattern. varsN[varIdx] = name varsR[varIdx], 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) } else { 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 idxs := make([]int, 0) 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 { hostVars := v.host.regexp.FindStringSubmatch(getHost(req)) if hostVars != nil { subexpNames := v.host.regexp.SubexpNames() varName := 0 for i, name := range subexpNames[1:] { if name != "" && name == varGroupName(varName) { m.Vars[v.host.varsN[varName]] = hostVars[i+1] varName++ } } } } // Store path variables. if v.path != nil { pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path) if pathVars != nil { subexpNames := v.path.regexp.SubexpNames() varName := 0 for i, name := range subexpNames[1:] { if name != "" && name == varGroupName(varName) { m.Vars[v.path.varsN[varName]] = pathVars[i+1] varName++ } } // 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 { queryVars := q.regexp.FindStringSubmatch(q.getUrlQuery(req)) if queryVars != nil { subexpNames := q.regexp.SubexpNames() varName := 0 for i, name := range subexpNames[1:] { if name != "" && name == varGroupName(varName) { m.Vars[q.varsN[varName]] = queryVars[i+1] varName++ } } } } } // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux/route.go ================================================ // 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) } // Regular expressions can be used with headers as well. // It 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 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 } // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/README.md ================================================ # cleanhttp Functions for accessing "clean" Go http.Client values ------------- The Go standard library contains a default `http.Client` called `http.DefaultClient`. It is a common idiom in Go code to start with `http.DefaultClient` and tweak it as necessary, and in fact, this is encouraged; from the `http` package documentation: > The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines. Unfortunately, this is a shared value, and it is not uncommon for libraries to assume that they are free to modify it at will. With enough dependencies, it can be very easy to encounter strange problems and race conditions due to manipulation of this shared value across libraries and goroutines (clients are safe for concurrent use, but writing values to the client struct itself is not protected). Making things worse is the fact that a bare `http.Client` will use a default `http.Transport` called `http.DefaultTransport`, which is another global value that behaves the same way. So it is not simply enough to replace `http.DefaultClient` with `&http.Client{}`. This repository provides some simple functions to get a "clean" `http.Client` -- one that uses the same default values as the Go standard library, but returns a client that does not share any state with other clients. ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/hashicorp/go-cleanhttp/cleanhttp.go ================================================ package cleanhttp import ( "net" "net/http" "runtime" "time" ) // DefaultTransport returns a new http.Transport with the same default values // as http.DefaultTransport func DefaultTransport() *http.Transport { transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } SetTransportFinalizer(transport) return transport } // DefaultClient returns a new http.Client with the same default values as // http.Client, but with a non-shared Transport func DefaultClient() *http.Client { return &http.Client{ Transport: DefaultTransport(), } } // SetTransportFinalizer sets a finalizer on the transport to ensure that // idle connections are closed prior to garbage collection; otherwise // these may leak func SetTransportFinalizer(transport *http.Transport) { runtime.SetFinalizer(&transport, func(t **http.Transport) { (*t).CloseIdleConnections() }) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS ================================================ Tianon Gravi (@tianon) Aleksa Sarai (@cyphar) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup.go ================================================ package user import ( "errors" "fmt" "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") ) 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{}, fmt.Errorf("no matching entries in passwd file") } // 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{}, fmt.Errorf("no matching entries in group file") } // 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 }) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go ================================================ // +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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go ================================================ // +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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user.go ================================================ 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 { if len(v) <= i { // if we have more "parts" than we have places to put them, bail for great "tolerance" of naughty configuration files break } switch e := v[i].(type) { case *string: // "root", "adm", "/bin/bash" *e = p case *int: // "0", "4", "1000" // ignore string to int conversion errors, for great "tolerance" of naughty configuration files *e, _ = strconv.Atoi(p) case *[]string: // "", "root", "root,adm,daemon" if p != "" { *e = strings.Split(p, ",") } else { *e = []string{} } default: // panic, because this is a programming/logic error, not a runtime one panic("parseLine expects only pointers! argument " + strconv.Itoa(i) + " is not a pointer!") } } } 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 } text := strings.TrimSpace(s.Text()) if text == "" { 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( text, &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, 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) { passwd, err := os.Open(passwdPath) if err != nil { passwd = nil } else { defer passwd.Close() } group, err := os.Open(groupPath) if err != nil { group = nil } else { defer group.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" func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) { var ( userArg, groupArg string name string ) 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 parseLine(userSpec, &userArg, &groupArg) users, err := ParsePasswdFilter(passwd, func(u User) bool { if userArg == "" { return u.Uid == user.Uid } return u.Name == userArg || strconv.Itoa(u.Uid) == userArg }) if err != nil && passwd != nil { if userArg == "" { userArg = strconv.Itoa(user.Uid) } return nil, fmt.Errorf("Unable to find user %v: %v", userArg, err) } haveUser := users != nil && len(users) > 0 if haveUser { // if we found any user entries that matched our filter, let's take the first one as "correct" name = users[0].Name user.Uid = users[0].Uid user.Gid = users[0].Gid user.Home = users[0].Home } else if userArg != "" { // we asked for a user but didn't find them... let's check to see if we wanted a numeric user user.Uid, err = strconv.Atoi(userArg) if err != nil { // not numeric - we have to bail return nil, fmt.Errorf("Unable to find user %v", userArg) } // Must be inside valid uid range. if user.Uid < minId || user.Uid > maxId { return nil, ErrRange } // if userArg couldn't be found in /etc/passwd but is numeric, just roll with it - this is legit } if groupArg != "" || name != "" { groups, err := ParseGroupFilter(group, func(g Group) bool { // Explicit group format takes precedence. if groupArg != "" { return g.Name == groupArg || strconv.Itoa(g.Gid) == groupArg } // Check if user is a member. for _, u := range g.List { if u == name { return true } } return false }) if err != nil && group != nil { return nil, fmt.Errorf("Unable to find groups for user %v: %v", users[0].Name, err) } haveGroup := groups != nil && len(groups) > 0 if groupArg != "" { if haveGroup { // if we found any group entries that matched our filter, let's take the first one as "correct" user.Gid = groups[0].Gid } else { // we asked for a group but didn't find id... let's check to see if we wanted a numeric group user.Gid, err = strconv.Atoi(groupArg) if err != nil { // not numeric - we have to bail return nil, fmt.Errorf("Unable to find group %v", groupArg) } // Ensure gid is inside gid range. if user.Gid < minId || user.Gid > maxId { return nil, ErrRange } // if groupArg couldn't be found in /etc/group but is numeric, just roll with it - this is legit } } else if haveGroup { // If implicit group format, fill supplementary gids. 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) { group, err := os.Open(groupPath) if err == nil { defer group.Close() } return GetAdditionalGroups(additionalGroups, group) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/github.com/opencontainers/runc/libcontainer/user/user_test.go ================================================ package user import ( "io" "reflect" "sort" "strconv" "strings" "testing" ) func TestUserParseLine(t *testing.T) { var ( a, b string c []string d int ) parseLine("", &a, &b) if a != "" || b != "" { t.Fatalf("a and b should be empty ('%v', '%v')", a, b) } parseLine("a", &a, &b) if a != "a" || b != "" { t.Fatalf("a should be 'a' and b should be empty ('%v', '%v')", a, b) } parseLine("bad boys:corny cows", &a, &b) if a != "bad boys" || b != "corny cows" { t.Fatalf("a should be 'bad boys' and b should be 'corny cows' ('%v', '%v')", a, b) } parseLine("", &c) if len(c) != 0 { t.Fatalf("c should be empty (%#v)", c) } parseLine("d,e,f:g:h:i,j,k", &c, &a, &b, &c) if a != "g" || b != "h" || len(c) != 3 || c[0] != "i" || c[1] != "j" || c[2] != "k" { t.Fatalf("a should be 'g', b should be 'h', and c should be ['i','j','k'] ('%v', '%v', '%#v')", a, b, c) } parseLine("::::::::::", &a, &b, &c) if a != "" || b != "" || len(c) != 0 { t.Fatalf("a, b, and c should all be empty ('%v', '%v', '%#v')", a, b, c) } parseLine("not a number", &d) if d != 0 { t.Fatalf("d should be 0 (%v)", d) } parseLine("b:12:c", &a, &d, &b) if a != "b" || b != "c" || d != 12 { t.Fatalf("a should be 'b' and b should be 'c', and d should be 12 ('%v', '%v', %v)", a, b, d) } } func TestUserParsePasswd(t *testing.T) { users, err := ParsePasswdFilter(strings.NewReader(` root:x:0:0:root:/root:/bin/bash adm:x:3:4:adm:/var/adm:/bin/false this is just some garbage data `), nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if len(users) != 3 { t.Fatalf("Expected 3 users, got %v", len(users)) } if users[0].Uid != 0 || users[0].Name != "root" { t.Fatalf("Expected users[0] to be 0 - root, got %v - %v", users[0].Uid, users[0].Name) } if users[1].Uid != 3 || users[1].Name != "adm" { t.Fatalf("Expected users[1] to be 3 - adm, got %v - %v", users[1].Uid, users[1].Name) } } func TestUserParseGroup(t *testing.T) { groups, err := ParseGroupFilter(strings.NewReader(` root:x:0:root adm:x:4:root,adm,daemon this is just some garbage data `), nil) if err != nil { t.Fatalf("Unexpected error: %v", err) } if len(groups) != 3 { t.Fatalf("Expected 3 groups, got %v", len(groups)) } if groups[0].Gid != 0 || groups[0].Name != "root" || len(groups[0].List) != 1 { t.Fatalf("Expected groups[0] to be 0 - root - 1 member, got %v - %v - %v", groups[0].Gid, groups[0].Name, len(groups[0].List)) } if groups[1].Gid != 4 || groups[1].Name != "adm" || len(groups[1].List) != 3 { t.Fatalf("Expected groups[1] to be 4 - adm - 3 members, got %v - %v - %v", groups[1].Gid, groups[1].Name, len(groups[1].List)) } } func TestValidGetExecUser(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash adm:x:42:43:adm:/var/adm:/bin/false this is just some garbage data ` const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm this is just some garbage data ` defaultExecUser := ExecUser{ Uid: 8888, Gid: 8888, Sgids: []int{8888}, Home: "/8888", } tests := []struct { ref string expected ExecUser }{ { ref: "root", expected: ExecUser{ Uid: 0, Gid: 0, Sgids: []int{0, 1234}, Home: "/root", }, }, { ref: "adm", expected: ExecUser{ Uid: 42, Gid: 43, Sgids: []int{1234}, Home: "/var/adm", }, }, { ref: "root:adm", expected: ExecUser{ Uid: 0, Gid: 43, Sgids: defaultExecUser.Sgids, Home: "/root", }, }, { ref: "adm:1234", expected: ExecUser{ Uid: 42, Gid: 1234, Sgids: defaultExecUser.Sgids, Home: "/var/adm", }, }, { ref: "42:1234", expected: ExecUser{ Uid: 42, Gid: 1234, Sgids: defaultExecUser.Sgids, Home: "/var/adm", }, }, { ref: "1337:1234", expected: ExecUser{ Uid: 1337, Gid: 1234, Sgids: defaultExecUser.Sgids, Home: defaultExecUser.Home, }, }, { ref: "1337", expected: ExecUser{ Uid: 1337, Gid: defaultExecUser.Gid, Sgids: defaultExecUser.Sgids, Home: defaultExecUser.Home, }, }, { ref: "", expected: ExecUser{ Uid: defaultExecUser.Uid, Gid: defaultExecUser.Gid, Sgids: defaultExecUser.Sgids, Home: defaultExecUser.Home, }, }, } for _, test := range tests { passwd := strings.NewReader(passwdContent) group := strings.NewReader(groupContent) execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) if err != nil { t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) t.Fail() continue } if !reflect.DeepEqual(test.expected, *execUser) { t.Logf("got: %#v", execUser) t.Logf("expected: %#v", test.expected) t.Fail() continue } } } func TestInvalidGetExecUser(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash adm:x:42:43:adm:/var/adm:/bin/false this is just some garbage data ` const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm this is just some garbage data ` tests := []string{ // No such user/group. "notuser", "notuser:notgroup", "root:notgroup", "notuser:adm", "8888:notgroup", "notuser:8888", // Invalid user/group values. "-1:0", "0:-3", "-5:-2", } for _, test := range tests { passwd := strings.NewReader(passwdContent) group := strings.NewReader(groupContent) execUser, err := GetExecUser(test, nil, passwd, group) if err == nil { t.Logf("got unexpected success when parsing '%s': %#v", test, execUser) t.Fail() continue } } } func TestGetExecUserNilSources(t *testing.T) { const passwdContent = ` root:x:0:0:root user:/root:/bin/bash adm:x:42:43:adm:/var/adm:/bin/false this is just some garbage data ` const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm this is just some garbage data ` defaultExecUser := ExecUser{ Uid: 8888, Gid: 8888, Sgids: []int{8888}, Home: "/8888", } tests := []struct { ref string passwd, group bool expected ExecUser }{ { ref: "", passwd: false, group: false, expected: ExecUser{ Uid: 8888, Gid: 8888, Sgids: []int{8888}, Home: "/8888", }, }, { ref: "root", passwd: true, group: false, expected: ExecUser{ Uid: 0, Gid: 0, Sgids: []int{8888}, Home: "/root", }, }, { ref: "0", passwd: false, group: false, expected: ExecUser{ Uid: 0, Gid: 8888, Sgids: []int{8888}, Home: "/8888", }, }, { ref: "0:0", passwd: false, group: false, expected: ExecUser{ Uid: 0, Gid: 0, Sgids: []int{8888}, Home: "/8888", }, }, } for _, test := range tests { var passwd, group io.Reader if test.passwd { passwd = strings.NewReader(passwdContent) } if test.group { group = strings.NewReader(groupContent) } execUser, err := GetExecUser(test.ref, &defaultExecUser, passwd, group) if err != nil { t.Logf("got unexpected error when parsing '%s': %s", test.ref, err.Error()) t.Fail() continue } if !reflect.DeepEqual(test.expected, *execUser) { t.Logf("got: %#v", execUser) t.Logf("expected: %#v", test.expected) t.Fail() continue } } } func TestGetAdditionalGroups(t *testing.T) { const groupContent = ` root:x:0:root adm:x:43: grp:x:1234:root,adm adm:x:4343:root,adm-duplicate this is just some garbage data ` tests := []struct { groups []string expected []int hasError bool }{ { // empty group groups: []string{}, expected: []int{}, }, { // single group groups: []string{"adm"}, expected: []int{43}, }, { // multiple groups groups: []string{"adm", "grp"}, expected: []int{43, 1234}, }, { // invalid group groups: []string{"adm", "grp", "not-exist"}, expected: nil, hasError: true, }, { // group with numeric id groups: []string{"43"}, expected: []int{43}, }, { // group with unknown numeric id groups: []string{"adm", "10001"}, expected: []int{43, 10001}, }, { // groups specified twice with numeric and name groups: []string{"adm", "43"}, expected: []int{43}, }, { // groups with too small id groups: []string{"-1"}, expected: nil, hasError: true, }, { // groups with too large id groups: []string{strconv.Itoa(1 << 31)}, expected: nil, hasError: true, }, } for _, test := range tests { group := strings.NewReader(groupContent) gids, err := GetAdditionalGroups(test.groups, group) if test.hasError && err == nil { t.Errorf("Parse(%#v) expects error but has none", test) continue } if !test.hasError && err != nil { t.Errorf("Parse(%#v) has error %v", test, err) continue } sort.Sort(sort.IntSlice(gids)) if !reflect.DeepEqual(gids, test.expected) { t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) } } } func TestGetAdditionalGroupsNumeric(t *testing.T) { tests := []struct { groups []string expected []int hasError bool }{ { // numeric groups only groups: []string{"1234", "5678"}, expected: []int{1234, 5678}, }, { // numeric and alphabetic groups: []string{"1234", "fake"}, expected: nil, hasError: true, }, } for _, test := range tests { gids, err := GetAdditionalGroups(test.groups, nil) if test.hasError && err == nil { t.Errorf("Parse(%#v) expects error but has none", test) continue } if !test.hasError && err != nil { t.Errorf("Parse(%#v) has error %v", test, err) continue } sort.Sort(sort.IntSlice(gids)) if !reflect.DeepEqual(gids, test.expected) { t.Errorf("Gids(%v), expect %v from groups %v", gids, test.expected, test.groups) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context.go ================================================ // 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 "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" import ( "errors" "fmt" "sync" "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{} } // 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") // 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) ) // 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() // 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/context_test.go ================================================ // 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 import ( "fmt" "math/rand" "runtime" "strings" "sync" "testing" "time" ) // otherContext is a Context that's not one of the types defined in context.go. // This lets us test code paths that differ based on the underlying type of the // Context. type otherContext struct { Context } func TestBackground(t *testing.T) { c := Background() if c == nil { t.Fatalf("Background returned nil") } select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } if got, want := fmt.Sprint(c), "context.Background"; got != want { t.Errorf("Background().String() = %q want %q", got, want) } } func TestTODO(t *testing.T) { c := TODO() if c == nil { t.Fatalf("TODO returned nil") } select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } if got, want := fmt.Sprint(c), "context.TODO"; got != want { t.Errorf("TODO().String() = %q want %q", got, want) } } func TestWithCancel(t *testing.T) { c1, cancel := WithCancel(Background()) if got, want := fmt.Sprint(c1), "context.Background.WithCancel"; got != want { t.Errorf("c1.String() = %q want %q", got, want) } o := otherContext{c1} c2, _ := WithCancel(o) contexts := []Context{c1, o, c2} for i, c := range contexts { if d := c.Done(); d == nil { t.Errorf("c[%d].Done() == %v want non-nil", i, d) } if e := c.Err(); e != nil { t.Errorf("c[%d].Err() == %v want nil", i, e) } select { case x := <-c.Done(): t.Errorf("<-c.Done() == %v want nothing (it should block)", x) default: } } cancel() time.Sleep(100 * time.Millisecond) // let cancelation propagate for i, c := range contexts { select { case <-c.Done(): default: t.Errorf("<-c[%d].Done() blocked, but shouldn't have", i) } if e := c.Err(); e != Canceled { t.Errorf("c[%d].Err() == %v want %v", i, e, Canceled) } } } func TestParentFinishesChild(t *testing.T) { // Context tree: // parent -> cancelChild // parent -> valueChild -> timerChild parent, cancel := WithCancel(Background()) cancelChild, stop := WithCancel(parent) defer stop() valueChild := WithValue(parent, "key", "value") timerChild, stop := WithTimeout(valueChild, 10000*time.Hour) defer stop() select { case x := <-parent.Done(): t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) case x := <-cancelChild.Done(): t.Errorf("<-cancelChild.Done() == %v want nothing (it should block)", x) case x := <-timerChild.Done(): t.Errorf("<-timerChild.Done() == %v want nothing (it should block)", x) case x := <-valueChild.Done(): t.Errorf("<-valueChild.Done() == %v want nothing (it should block)", x) default: } // The parent's children should contain the two cancelable children. pc := parent.(*cancelCtx) cc := cancelChild.(*cancelCtx) tc := timerChild.(*timerCtx) pc.mu.Lock() if len(pc.children) != 2 || !pc.children[cc] || !pc.children[tc] { t.Errorf("bad linkage: pc.children = %v, want %v and %v", pc.children, cc, tc) } pc.mu.Unlock() if p, ok := parentCancelCtx(cc.Context); !ok || p != pc { t.Errorf("bad linkage: parentCancelCtx(cancelChild.Context) = %v, %v want %v, true", p, ok, pc) } if p, ok := parentCancelCtx(tc.Context); !ok || p != pc { t.Errorf("bad linkage: parentCancelCtx(timerChild.Context) = %v, %v want %v, true", p, ok, pc) } cancel() pc.mu.Lock() if len(pc.children) != 0 { t.Errorf("pc.cancel didn't clear pc.children = %v", pc.children) } pc.mu.Unlock() // parent and children should all be finished. check := func(ctx Context, name string) { select { case <-ctx.Done(): default: t.Errorf("<-%s.Done() blocked, but shouldn't have", name) } if e := ctx.Err(); e != Canceled { t.Errorf("%s.Err() == %v want %v", name, e, Canceled) } } check(parent, "parent") check(cancelChild, "cancelChild") check(valueChild, "valueChild") check(timerChild, "timerChild") // WithCancel should return a canceled context on a canceled parent. precanceledChild := WithValue(parent, "key", "value") select { case <-precanceledChild.Done(): default: t.Errorf("<-precanceledChild.Done() blocked, but shouldn't have") } if e := precanceledChild.Err(); e != Canceled { t.Errorf("precanceledChild.Err() == %v want %v", e, Canceled) } } func TestChildFinishesFirst(t *testing.T) { cancelable, stop := WithCancel(Background()) defer stop() for _, parent := range []Context{Background(), cancelable} { child, cancel := WithCancel(parent) select { case x := <-parent.Done(): t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) case x := <-child.Done(): t.Errorf("<-child.Done() == %v want nothing (it should block)", x) default: } cc := child.(*cancelCtx) pc, pcok := parent.(*cancelCtx) // pcok == false when parent == Background() if p, ok := parentCancelCtx(cc.Context); ok != pcok || (ok && pc != p) { t.Errorf("bad linkage: parentCancelCtx(cc.Context) = %v, %v want %v, %v", p, ok, pc, pcok) } if pcok { pc.mu.Lock() if len(pc.children) != 1 || !pc.children[cc] { t.Errorf("bad linkage: pc.children = %v, cc = %v", pc.children, cc) } pc.mu.Unlock() } cancel() if pcok { pc.mu.Lock() if len(pc.children) != 0 { t.Errorf("child's cancel didn't remove self from pc.children = %v", pc.children) } pc.mu.Unlock() } // child should be finished. select { case <-child.Done(): default: t.Errorf("<-child.Done() blocked, but shouldn't have") } if e := child.Err(); e != Canceled { t.Errorf("child.Err() == %v want %v", e, Canceled) } // parent should not be finished. select { case x := <-parent.Done(): t.Errorf("<-parent.Done() == %v want nothing (it should block)", x) default: } if e := parent.Err(); e != nil { t.Errorf("parent.Err() == %v want nil", e) } } } func testDeadline(c Context, wait time.Duration, t *testing.T) { select { case <-time.After(wait): t.Fatalf("context should have timed out") case <-c.Done(): } if e := c.Err(); e != DeadlineExceeded { t.Errorf("c.Err() == %v want %v", e, DeadlineExceeded) } } func TestDeadline(t *testing.T) { c, _ := WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { t.Errorf("c.String() = %q want prefix %q", got, prefix) } testDeadline(c, 200*time.Millisecond, t) c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) o := otherContext{c} testDeadline(o, 200*time.Millisecond, t) c, _ = WithDeadline(Background(), time.Now().Add(100*time.Millisecond)) o = otherContext{c} c, _ = WithDeadline(o, time.Now().Add(300*time.Millisecond)) testDeadline(c, 200*time.Millisecond, t) } func TestTimeout(t *testing.T) { c, _ := WithTimeout(Background(), 100*time.Millisecond) if got, prefix := fmt.Sprint(c), "context.Background.WithDeadline("; !strings.HasPrefix(got, prefix) { t.Errorf("c.String() = %q want prefix %q", got, prefix) } testDeadline(c, 200*time.Millisecond, t) c, _ = WithTimeout(Background(), 100*time.Millisecond) o := otherContext{c} testDeadline(o, 200*time.Millisecond, t) c, _ = WithTimeout(Background(), 100*time.Millisecond) o = otherContext{c} c, _ = WithTimeout(o, 300*time.Millisecond) testDeadline(c, 200*time.Millisecond, t) } func TestCanceledTimeout(t *testing.T) { c, _ := WithTimeout(Background(), 200*time.Millisecond) o := otherContext{c} c, cancel := WithTimeout(o, 400*time.Millisecond) cancel() time.Sleep(100 * time.Millisecond) // let cancelation propagate select { case <-c.Done(): default: t.Errorf("<-c.Done() blocked, but shouldn't have") } if e := c.Err(); e != Canceled { t.Errorf("c.Err() == %v want %v", e, Canceled) } } type key1 int type key2 int var k1 = key1(1) var k2 = key2(1) // same int as k1, different type var k3 = key2(3) // same type as k2, different int func TestValues(t *testing.T) { check := func(c Context, nm, v1, v2, v3 string) { if v, ok := c.Value(k1).(string); ok == (len(v1) == 0) || v != v1 { t.Errorf(`%s.Value(k1).(string) = %q, %t want %q, %t`, nm, v, ok, v1, len(v1) != 0) } if v, ok := c.Value(k2).(string); ok == (len(v2) == 0) || v != v2 { t.Errorf(`%s.Value(k2).(string) = %q, %t want %q, %t`, nm, v, ok, v2, len(v2) != 0) } if v, ok := c.Value(k3).(string); ok == (len(v3) == 0) || v != v3 { t.Errorf(`%s.Value(k3).(string) = %q, %t want %q, %t`, nm, v, ok, v3, len(v3) != 0) } } c0 := Background() check(c0, "c0", "", "", "") c1 := WithValue(Background(), k1, "c1k1") check(c1, "c1", "c1k1", "", "") if got, want := fmt.Sprint(c1), `context.Background.WithValue(1, "c1k1")`; got != want { t.Errorf("c.String() = %q want %q", got, want) } c2 := WithValue(c1, k2, "c2k2") check(c2, "c2", "c1k1", "c2k2", "") c3 := WithValue(c2, k3, "c3k3") check(c3, "c2", "c1k1", "c2k2", "c3k3") c4 := WithValue(c3, k1, nil) check(c4, "c4", "", "c2k2", "c3k3") o0 := otherContext{Background()} check(o0, "o0", "", "", "") o1 := otherContext{WithValue(Background(), k1, "c1k1")} check(o1, "o1", "c1k1", "", "") o2 := WithValue(o1, k2, "o2k2") check(o2, "o2", "c1k1", "o2k2", "") o3 := otherContext{c4} check(o3, "o3", "", "c2k2", "c3k3") o4 := WithValue(o3, k3, nil) check(o4, "o4", "", "c2k2", "") } func TestAllocs(t *testing.T) { bg := Background() for _, test := range []struct { desc string f func() limit float64 gccgoLimit float64 }{ { desc: "Background()", f: func() { Background() }, limit: 0, gccgoLimit: 0, }, { desc: fmt.Sprintf("WithValue(bg, %v, nil)", k1), f: func() { c := WithValue(bg, k1, nil) c.Value(k1) }, limit: 3, gccgoLimit: 3, }, { desc: "WithTimeout(bg, 15*time.Millisecond)", f: func() { c, _ := WithTimeout(bg, 15*time.Millisecond) <-c.Done() }, limit: 8, gccgoLimit: 15, }, { desc: "WithCancel(bg)", f: func() { c, cancel := WithCancel(bg) cancel() <-c.Done() }, limit: 5, gccgoLimit: 8, }, { desc: "WithTimeout(bg, 100*time.Millisecond)", f: func() { c, cancel := WithTimeout(bg, 100*time.Millisecond) cancel() <-c.Done() }, limit: 8, gccgoLimit: 25, }, } { limit := test.limit if runtime.Compiler == "gccgo" { // gccgo does not yet do escape analysis. // TOOD(iant): Remove this when gccgo does do escape analysis. limit = test.gccgoLimit } if n := testing.AllocsPerRun(100, test.f); n > limit { t.Errorf("%s allocs = %f want %d", test.desc, n, int(limit)) } } } func TestSimultaneousCancels(t *testing.T) { root, cancel := WithCancel(Background()) m := map[Context]CancelFunc{root: cancel} q := []Context{root} // Create a tree of contexts. for len(q) != 0 && len(m) < 100 { parent := q[0] q = q[1:] for i := 0; i < 4; i++ { ctx, cancel := WithCancel(parent) m[ctx] = cancel q = append(q, ctx) } } // Start all the cancels in a random order. var wg sync.WaitGroup wg.Add(len(m)) for _, cancel := range m { go func(cancel CancelFunc) { cancel() wg.Done() }(cancel) } // Wait on all the contexts in a random order. for ctx := range m { select { case <-ctx.Done(): case <-time.After(1 * time.Second): buf := make([]byte, 10<<10) n := runtime.Stack(buf, true) t.Fatalf("timed out waiting for <-ctx.Done(); stacks:\n%s", buf[:n]) } } // Wait for all the cancel functions to return. done := make(chan struct{}) go func() { wg.Wait() close(done) }() select { case <-done: case <-time.After(1 * time.Second): buf := make([]byte, 10<<10) n := runtime.Stack(buf, true) t.Fatalf("timed out waiting for cancel functions; stacks:\n%s", buf[:n]) } } func TestInterlockedCancels(t *testing.T) { parent, cancelParent := WithCancel(Background()) child, cancelChild := WithCancel(parent) go func() { parent.Done() cancelChild() }() cancelParent() select { case <-child.Done(): case <-time.After(1 * time.Second): buf := make([]byte, 10<<10) n := runtime.Stack(buf, true) t.Fatalf("timed out waiting for child.Done(); stacks:\n%s", buf[:n]) } } func TestLayersCancel(t *testing.T) { testLayers(t, time.Now().UnixNano(), false) } func TestLayersTimeout(t *testing.T) { testLayers(t, time.Now().UnixNano(), true) } func testLayers(t *testing.T, seed int64, testTimeout bool) { rand.Seed(seed) errorf := func(format string, a ...interface{}) { t.Errorf(fmt.Sprintf("seed=%d: %s", seed, format), a...) } const ( timeout = 200 * time.Millisecond minLayers = 30 ) type value int var ( vals []*value cancels []CancelFunc numTimers int ctx = Background() ) for i := 0; i < minLayers || numTimers == 0 || len(cancels) == 0 || len(vals) == 0; i++ { switch rand.Intn(3) { case 0: v := new(value) ctx = WithValue(ctx, v, v) vals = append(vals, v) case 1: var cancel CancelFunc ctx, cancel = WithCancel(ctx) cancels = append(cancels, cancel) case 2: var cancel CancelFunc ctx, cancel = WithTimeout(ctx, timeout) cancels = append(cancels, cancel) numTimers++ } } checkValues := func(when string) { for _, key := range vals { if val := ctx.Value(key).(*value); key != val { errorf("%s: ctx.Value(%p) = %p want %p", when, key, val, key) } } } select { case <-ctx.Done(): errorf("ctx should not be canceled yet") default: } if s, prefix := fmt.Sprint(ctx), "context.Background."; !strings.HasPrefix(s, prefix) { t.Errorf("ctx.String() = %q want prefix %q", s, prefix) } t.Log(ctx) checkValues("before cancel") if testTimeout { select { case <-ctx.Done(): case <-time.After(timeout + 100*time.Millisecond): errorf("ctx should have timed out") } checkValues("after timeout") } else { cancel := cancels[rand.Intn(len(cancels))] cancel() select { case <-ctx.Done(): default: errorf("ctx should be canceled") } checkValues("after cancel") } } func TestCancelRemoves(t *testing.T) { checkChildren := func(when string, ctx Context, want int) { if got := len(ctx.(*cancelCtx).children); got != want { t.Errorf("%s: context has %d children, want %d", when, got, want) } } ctx, _ := WithCancel(Background()) checkChildren("after creation", ctx, 0) _, cancel := WithCancel(ctx) checkChildren("with WithCancel child ", ctx, 1) cancel() checkChildren("after cancelling WithCancel child", ctx, 0) ctx, _ = WithCancel(Background()) checkChildren("after creation", ctx, 0) _, cancel = WithTimeout(ctx, 60*time.Minute) checkChildren("with WithTimeout child ", ctx, 1) cancel() checkChildren("after cancelling WithTimeout child", ctx, 0) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/net/context/withtimeout_test.go ================================================ // 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_test import ( "fmt" "time" "github.com/fsouza/go-dockerclient/external/golang.org/x/net/context" ) func ExampleWithTimeout() { // Pass a context with a timeout to tell a blocking function that it // should abandon its work after the timeout elapses. ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) select { case <-time.After(200 * time.Millisecond): fmt.Println("overslept") case <-ctx.Done(): fmt.Println(ctx.Err()) // prints "context deadline exceeded" } // Output: // context deadline exceeded } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm.s ================================================ // 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_386.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_amd64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_darwin_arm64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_386.s ================================================ // 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-32 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-44 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-56 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-32 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-44 JMP syscall·RawSyscall6(SB) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_dragonfly_amd64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_386.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_amd64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_freebsd_arm.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_386.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_amd64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_arm64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_linux_ppc64x.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_386.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_amd64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_netbsd_arm.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_386.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_openbsd_amd64.s ================================================ // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/asm_solaris_amd64.s ================================================ // 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-64 JMP syscall·sysvicall6(SB) TEXT ·rawSysvicall6(SB),NOSPLIT,$0-64 JMP syscall·rawSysvicall6(SB) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/constants.go ================================================ // 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/creds_test.go ================================================ // 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 package unix_test import ( "bytes" "net" "os" "syscall" "testing" "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" ) // TestSCMCredentials tests the sending and receiving of credentials // (PID, UID, GID) in an ancillary message between two UNIX // sockets. The SO_PASSCRED socket option is enabled on the sending // socket for this to work. func TestSCMCredentials(t *testing.T) { fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer unix.Close(fds[0]) defer unix.Close(fds[1]) err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) if err != nil { t.Fatalf("SetsockoptInt: %v", err) } srvFile := os.NewFile(uintptr(fds[0]), "server") defer srvFile.Close() srv, err := net.FileConn(srvFile) if err != nil { t.Errorf("FileConn: %v", err) return } defer srv.Close() cliFile := os.NewFile(uintptr(fds[1]), "client") defer cliFile.Close() cli, err := net.FileConn(cliFile) if err != nil { t.Errorf("FileConn: %v", err) return } defer cli.Close() var ucred unix.Ucred if os.Getuid() != 0 { ucred.Pid = int32(os.Getpid()) ucred.Uid = 0 ucred.Gid = 0 oob := unix.UnixCredentials(&ucred) _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) if op, ok := err.(*net.OpError); ok { err = op.Err } if sys, ok := err.(*os.SyscallError); ok { err = sys.Err } if err != syscall.EPERM { t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) } } ucred.Pid = int32(os.Getpid()) ucred.Uid = uint32(os.Getuid()) ucred.Gid = uint32(os.Getgid()) oob := unix.UnixCredentials(&ucred) // this is going to send a dummy byte n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) if err != nil { t.Fatalf("WriteMsgUnix: %v", err) } if n != 0 { t.Fatalf("WriteMsgUnix n = %d, want 0", n) } if oobn != len(oob) { t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) } oob2 := make([]byte, 10*len(oob)) n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) if err != nil { t.Fatalf("ReadMsgUnix: %v", err) } if flags != 0 { t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) } if n != 1 { t.Fatalf("ReadMsgUnix n = %d, want 1 (dummy byte)", n) } if oobn2 != oobn { // without SO_PASSCRED set on the socket, ReadMsgUnix will // return zero oob bytes t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) } oob2 = oob2[:oobn2] if !bytes.Equal(oob, oob2) { t.Fatal("ReadMsgUnix oob bytes don't match") } scm, err := unix.ParseSocketControlMessage(oob2) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } newUcred, err := unix.ParseUnixCredentials(&scm[0]) if err != nil { t.Fatalf("ParseUnixCredentials: %v", err) } if *newUcred != ucred { t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unix.go ================================================ // 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() } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/env_unset.go ================================================ // 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/export_test.go ================================================ // 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 var Itoa = itoa ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock.go ================================================ // +build linux darwin freebsd openbsd netbsd dragonfly // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/flock_linux_32bit.go ================================================ // +build linux,386 linux,arm // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo.go ================================================ // 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_c.c ================================================ // 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 #include #include #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))) { } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/gccgo_linux_amd64.go ================================================ // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkall.sh ================================================ #!/usr/bin/env bash # 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. # The unix package provides access to the raw system call # interface of the underlying operating system. Porting Go to # a new architecture/operating system combination requires # some manual effort, though there are tools that automate # much of the process. The auto-generated files have names # beginning with z. # # This script runs or (given -n) prints suggested commands to generate z files # for the current system. Running those commands is not automatic. # This script is documentation more than anything else. # # * asm_${GOOS}_${GOARCH}.s # # This hand-written assembly file 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. # # * syscall_${GOOS}.go # # This hand-written Go file implements system calls that need # special handling and lists "//sys" comments giving prototypes # for ones that can be auto-generated. Mksyscall reads those # comments to generate the stubs. # # * syscall_${GOOS}_${GOARCH}.go # # Same as syscall_${GOOS}.go except that it contains code specific # to ${GOOS} on one particular architecture. # # * types_${GOOS}.c # # This hand-written C file includes standard C headers and then # creates typedef or enum names beginning with a dollar sign # (use of $ in variable names is a gcc extension). The hardest # part about preparing this file is figuring out which headers to # include and which symbols need to be #defined to get the # actual data structures that pass through to the kernel system calls. # Some C libraries present 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.c and types_linux.c for examples. # # * zerror_${GOOS}_${GOARCH}.go # # This machine-generated file defines the system's error numbers, # error strings, and signal numbers. The generator is "mkerrors.sh". # Usually no arguments are needed, but mkerrors.sh will pass its # arguments on to godefs. # # * zsyscall_${GOOS}_${GOARCH}.go # # Generated by mksyscall.pl; see syscall_${GOOS}.go above. # # * zsysnum_${GOOS}_${GOARCH}.go # # Generated by mksysnum_${GOOS}. # # * ztypes_${GOOS}_${GOARCH}.go # # Generated by godefs; see types_${GOOS}.c above. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="./mksyscall.pl" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= run="sh" case "$1" in -syscalls) for i in zsyscall*go do sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac GOOSARCH_in=syscall_$GOOSARCH.go case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; darwin_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_amd64) mkerrors="$mkerrors -m64" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_arm) mkerrors="$mkerrors" mksysnum="./mksysnum_darwin.pl /usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_arm64) mkerrors="$mkerrors -m64" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; dragonfly_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -dragonfly" mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; dragonfly_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -dragonfly" mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_amd64) mkerrors="$mkerrors -m64" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -arm" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" # Let the type of C char be singed for making the bare syscall # API consistent across over platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; linux_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="./mksysnum_linux.pl /usr/include/asm/unistd_32.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_amd64) unistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1) if [ "$unistd_h" = "" ]; then echo >&2 cannot find unistd_64.h exit 1 fi mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -arm" mksysnum="curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_arm64) unistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1) if [ "$unistd_h" = "" ]; then echo >&2 cannot find unistd_64.h exit 1 fi mksysnum="./mksysnum_linux.pl $unistd_h" # Let the type of C char be singed for making the bare syscall # API consistent across over platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; linux_ppc64) GOOSARCH_in=syscall_linux_ppc64x.go unistd_h=/usr/include/asm/unistd.h mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_ppc64le) GOOSARCH_in=syscall_linux_ppc64x.go unistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -netbsd" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -netbsd" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -openbsd" mksysctl="./mksysctl_openbsd.pl" zsysctl="zsysctl_openbsd.go" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -openbsd" mksysctl="./mksysctl_openbsd.pl" zsysctl="zsysctl_openbsd.go" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; solaris_amd64) mksyscall="./mksyscall_solaris.pl" mkerrors="$mkerrors -m64" mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in *) syscall_goos="syscall_$GOOS.go" case "$GOOS" in darwin | dragonfly | freebsd | netbsd | openbsd) syscall_goos="syscall_bsd.go $syscall_goos" ;; esac if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi ;; esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go"; echo "$mktypes types_$GOOS.go | gofmt >>ztypes_$GOOSARCH.go"; fi ) | $run ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mkerrors.sh ================================================ #!/usr/bin/env bash # 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. # Generate Go code listing errors and other #defined constant # values (ENAMETOOLONG etc.), by asking the preprocessor # about the definitions. unset LANG export LC_ALL=C export LC_CTYPE=C if test -z "$GOARCH" -o -z "$GOOS"; then echo 1>&2 "GOARCH or GOOS not defined in environment" exit 1 fi CC=${CC:-cc} if [[ "$GOOS" -eq "solaris" ]]; then # Assumes GNU versions of utilities in PATH. export PATH=/usr/gnu/bin:$PATH fi uname=$(uname) includes_Darwin=' #define _DARWIN_C_SOURCE #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes_DragonFly=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes_FreeBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __FreeBSD__ >= 10 #define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10 #undef SIOCAIFADDR #define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data #undef SIOCSIFPHYADDR #define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data #endif ' includes_Linux=' #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #ifndef __LP64__ #define _FILE_OFFSET_BITS 64 #endif #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef MSG_FASTOPEN #define MSG_FASTOPEN 0x20000000 #endif #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc #endif #ifndef PTRACE_SETREGS #define PTRACE_SETREGS 0xd #endif ' includes_NetBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Needed since refers to it... #define schedppq 1 ' includes_OpenBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // We keep some constants not supported in OpenBSD 5.5 and beyond for // the promise of compatibility. #define EMUL_ENABLED 0x1 #define EMUL_NATIVE 0x2 #define IPV6_FAITH 0x1d #define IPV6_OPTIONS 0x1 #define IPV6_RTHDR_STRICT 0x1 #define IPV6_SOCKOPT_RESERVED1 0x3 #define SIOCGIFGENERIC 0xc020693a #define SIOCSIFGENERIC 0x80206939 #define WALTSIG 0x4 ' includes_SunOS=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' ccflags="$@" # Write go tool cgo -godefs input. ( echo package unix echo echo '/*' indirect="includes_$(uname)" echo "${!indirect} $includes" echo '*/' echo 'import "C"' echo 'import "syscall"' echo echo 'const (' # The gcc command line prints all the #defines # it encounters while processing the input echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | awk ' $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} $2 ~ /^(SCM_SRCRT)$/ {next} $2 ~ /^(MAP_FAILED)$/ {next} $2 ~ /^ELF_.*$/ {next}# contains ELF_ARCH, etc. $2 ~ /^EXTATTR_NAMESPACE_NAMES/ || $2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next} $2 !~ /^ETH_/ && $2 !~ /^EPROC_/ && $2 !~ /^EQUIV_/ && $2 !~ /^EXPR_/ && $2 ~ /^E[A-Z0-9_]+$/ || $2 ~ /^B[0-9_]+$/ || $2 == "BOTHER" || $2 ~ /^CI?BAUD(EX)?$/ || $2 == "IBSHIFT" || $2 ~ /^V[A-Z0-9]+$/ || $2 ~ /^CS[A-Z0-9]/ || $2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ || $2 ~ /^IGN/ || $2 ~ /^IX(ON|ANY|OFF)$/ || $2 ~ /^IN(LCR|PCK)$/ || $2 ~ /(^FLU?SH)|(FLU?SH$)/ || $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || $2 == "BRKINT" || $2 == "HUPCL" || $2 == "PENDIN" || $2 == "TOSTOP" || $2 == "XCASE" || $2 == "ALTWERASE" || $2 == "NOKERNINFO" || $2 ~ /^PAR/ || $2 ~ /^SIG[^_]/ || $2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ || $2 ~ /^O?XTABS$/ || $2 ~ /^TC[IO](ON|OFF)$/ || $2 ~ /^IN_/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || $2 == "ICMPV6_FILTER" || $2 == "SOMAXCONN" || $2 == "NAME_MAX" || $2 == "IFNAMSIZ" || $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || $2 ~ /^SYSCTL_VERS/ || $2 ~ /^(MS|MNT)_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || $2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ || $2 ~ /^LINUX_REBOOT_CMD_/ || $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 !~ "NLA_TYPE_MASK" && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || $2 ~ /^TCGET/ || $2 ~ /^TCSET/ || $2 ~ /^TC(FLSH|SBRKP?|XONC)$/ || $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^CLOCK_/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} {next} ' | sort echo ')' ) >_const.go # Pull out the error names for later. errors=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | sort ) # Pull out the signal names for later. signals=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort ) # Again, writing regexps to a file. echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT' echo echo "// +build ${GOARCH},${GOOS}" echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep echo echo '// Errors' echo 'const (' cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/' echo ')' echo echo '// Signals' echo 'const (' cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/' echo ')' # Run C program to print error and syscall strings. ( echo -E " #include #include #include #include #include #include #define nelem(x) (sizeof(x)/sizeof((x)[0])) enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below int errors[] = { " for i in $errors do echo -E ' '$i, done echo -E " }; int signals[] = { " for i in $signals do echo -E ' '$i, done # Use -E because on some systems bash builtin interprets \n itself. echo -E ' }; static int intcmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main(void) { int i, j, e; char buf[1024], *p; printf("\n\n// Error table\n"); printf("var errors = [...]string {\n"); qsort(errors, nelem(errors), sizeof errors[0], intcmp); for(i=0; i 0 && errors[i-1] == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); printf("var signals = [...]string {\n"); qsort(signals, nelem(signals), sizeof signals[0], intcmp); for(i=0; i 0 && signals[i-1] == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; // cut trailing : number. p = strrchr(buf, ":"[0]); if(p) *p = '\0'; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); return 0; } ' ) >_errors.c $CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/mksyscall.pl ================================================ #!/usr/bin/env perl # 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. # This program reads a file containing function prototypes # (like syscall_darwin.go) and generates system call bodies. # The prototypes are marked by lines beginning with "//sys" # and read like func declarations if //sys is replaced by func, but: # * The parameter lists must give a name for each argument. # This includes return parameters. # * The parameter lists must give a type for each argument: # the (x, y, z int) shorthand is not allowed. # * If the return parameter is an error number, it must be named errno. # A line beginning with //sysnb is like //sys, except that the # goroutine will not be suspended during the execution of the system # call. This must only be used for system calls which can never # block, as otherwise the system call could cause all goroutines to # hang. use strict; my $cmdline = "mksyscall.pl " . join(' ', @ARGV); my $errors = 0; my $_32bit = ""; my $plan9 = 0; my $openbsd = 0; my $netbsd = 0; my $dragonfly = 0; my $arm = 0; # 64-bit value should use (even, odd)-pair if($ARGV[0] eq "-b32") { $_32bit = "big-endian"; shift; } elsif($ARGV[0] eq "-l32") { $_32bit = "little-endian"; shift; } if($ARGV[0] eq "-plan9") { $plan9 = 1; shift; } if($ARGV[0] eq "-openbsd") { $openbsd = 1; shift; } if($ARGV[0] eq "-netbsd") { $netbsd = 1; shift; } if($ARGV[0] eq "-dragonfly") { $dragonfly = 1; shift; } if($ARGV[0] eq "-arm") { $arm = 1; shift; } if($ARGV[0] =~ /^-/) { print STDERR "usage: mksyscall.pl [-b32 | -l32] [file ...]\n"; exit 1; } if($ENV{'GOARCH'} eq "" || $ENV{'GOOS'} eq "") { print STDERR "GOARCH or GOOS not defined in environment\n"; exit 1; } sub parseparamlist($) { my ($list) = @_; $list =~ s/^\s*//; $list =~ s/\s*$//; if($list eq "") { return (); } return split(/\s*,\s*/, $list); } sub parseparam($) { my ($p) = @_; if($p !~ /^(\S*) (\S*)$/) { print STDERR "$ARGV:$.: malformed parameter: $p\n"; $errors = 1; return ("xx", "int"); } return ($1, $2); } my $text = ""; while(<>) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, errno error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # Try in vain to keep people from editing this file. # The theory is that they jump into the middle of the file # without reading the header. $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; # Go function header. my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass dummy pointer in that case. # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). $text .= "\tvar _p$n unsafe.Pointer\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; $text .= "\n"; push @args, "uintptr(_p$n)", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && ($openbsd || $netbsd)) { push @args, "0"; if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $dragonfly) { if ($func !~ /^extp(read|write)/i) { push @args, "0"; } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $_32bit ne "") { if(@args % 2 && $arm) { # arm abi specifies 64-bit argument uses # (even, odd) pair push @args, "0" } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name>>32)"; } } else { push @args, "uintptr($name)"; } } # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { $asm = "RawSyscall"; } if(@args <= 3) { while(@args < 3) { push @args, "0"; } } elsif(@args <= 6) { $asm .= "6"; while(@args < 6) { push @args, "0"; } } elsif(@args <= 9) { $asm .= "9"; while(@args < 9) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # System call number. if($sysname eq "") { $sysname = "SYS_$func"; $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar $sysname =~ y/a-z/A-Z/; } # Actual call. my $args = join(', ', @args); my $call = "$asm($sysname, $args)"; # Assign return values. my $body = ""; my @ret = ("_", "_", "_"); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err" && !$plan9) { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } elsif($name eq "err" && $plan9) { $ret[0] = "r0"; $ret[2] = "e1"; next; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1" || $plan9) { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($plan9 && $ret[2] eq "e1") { $text .= "\tif int32(r0) == -1 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } elsif ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = errnoErr(e1)\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n\n"; } chomp $text; chomp $text; if($errors) { exit 1; } print <) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; $package = $1 if !$package && /^package (\S+)$/; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, err error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # So file name. if($modname eq "") { $modname = "libc"; } # System call name. if($sysname eq "") { $sysname = "$func"; } # System call pointer variable name. my $sysvarname = "proc$sysname"; my $strconvfunc = "BytePtrFromString"; my $strconvtype = "*byte"; $sysname =~ y/A-Z/a-z/; # All libc functions are lowercase. # Runtime import of function to allow cross-platform builds. $dynimports .= "//go:cgo_import_dynamic libc_${sysname} ${sysname} \"$modname.so\"\n"; # Link symbol to proc address variable. $linknames .= "//go:linkname ${sysvarname} libc_${sysname}\n"; # Library proc address variable. push @vars, $sysvarname; # Go function header. $out = join(', ', @out); if($out ne "") { $out = " ($out)"; } if($text ne "") { $text .= "\n" } $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n $strconvtype\n"; $text .= "\t_p$n, $errvar = $strconvfunc($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n $strconvtype\n"; $text .= "\t_p$n, _ = $strconvfunc($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass nil in that case. $text .= "\tvar _p$n *$1\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && $_32bit ne "") { if($_32bit eq "big-endian") { push @args, "uintptr($name >> 32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name >> 32)"; } } elsif($type eq "bool") { $text .= "\tvar _p$n uint32\n"; $text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n"; push @args, "uintptr(_p$n)"; $n++; } else { push @args, "uintptr($name)"; } } my $nargs = @args; # Determine which form to use; pad args with zeros. my $asm = "sysvicall6"; if ($nonblock) { $asm = "rawSysvicall6"; } if(@args <= 6) { while(@args < 6) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # Actual call. my $args = join(', ', @args); my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)"; # Assign return values. my $body = ""; my $failexpr = ""; my @ret = ("_", "_", "_"); my @pout= (); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err") { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1") { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n"; } if($errors) { exit 1; } print < "net.inet", "net.inet.ipproto" => "net.inet", "net.inet6.ipv6proto" => "net.inet6", "net.inet6.ipv6" => "net.inet6.ip6", "net.inet.icmpv6" => "net.inet6.icmp6", "net.inet6.divert6" => "net.inet6.divert", "net.inet6.tcp6" => "net.inet.tcp", "net.inet6.udp6" => "net.inet.udp", "mpls" => "net.mpls", "swpenc" => "vm.swapencrypt" ); # Node mappings my %node_map = ( "net.inet.ip.ifq" => "net.ifq", "net.inet.pfsync" => "net.pfsync", "net.mpls.ifq" => "net.ifq" ); my $ctlname; my %mib = (); my %sysctl = (); my $node; sub debug() { print STDERR "$_[0]\n" if $debug; } # Walk the MIB and build a sysctl name to OID mapping. sub build_sysctl() { my ($node, $name, $oid) = @_; my %node = %{$node}; my @oid = @{$oid}; foreach my $key (sort keys %node) { my @node = @{$node{$key}}; my $nodename = $name.($name ne '' ? '.' : '').$key; my @nodeoid = (@oid, $node[0]); if ($node[1] eq 'CTLTYPE_NODE') { if (exists $node_map{$nodename}) { $node = \%mib; $ctlname = $node_map{$nodename}; foreach my $part (split /\./, $ctlname) { $node = \%{@{$$node{$part}}[2]}; } } else { $node = $node[2]; } &build_sysctl($node, $nodename, \@nodeoid); } elsif ($node[1] ne '') { $sysctl{$nodename} = \@nodeoid; } } } foreach my $ctl (@ctls) { $ctls{$ctl} = $ctl; } # Build MIB foreach my $header (@headers) { &debug("Processing $header..."); open HEADER, "/usr/include/$header" || print STDERR "Failed to open $header\n"; while (
) { if ($_ =~ /^#define\s+(CTL_NAMES)\s+{/ || $_ =~ /^#define\s+(CTL_(.*)_NAMES)\s+{/ || $_ =~ /^#define\s+((.*)CTL_NAMES)\s+{/) { if ($1 eq 'CTL_NAMES') { # Top level. $node = \%mib; } else { # Node. my $nodename = lc($2); if ($header =~ /^netinet\//) { $ctlname = "net.inet.$nodename"; } elsif ($header =~ /^netinet6\//) { $ctlname = "net.inet6.$nodename"; } elsif ($header =~ /^net\//) { $ctlname = "net.$nodename"; } else { $ctlname = "$nodename"; $ctlname =~ s/^(fs|net|kern)_/$1\./; } if (exists $ctl_map{$ctlname}) { $ctlname = $ctl_map{$ctlname}; } if (not exists $ctls{$ctlname}) { &debug("Ignoring $ctlname..."); next; } # Walk down from the top of the MIB. $node = \%mib; foreach my $part (split /\./, $ctlname) { if (not exists $$node{$part}) { &debug("Missing node $part"); $$node{$part} = [ 0, '', {} ]; } $node = \%{@{$$node{$part}}[2]}; } } # Populate current node with entries. my $i = -1; while (defined($_) && $_ !~ /^}/) { $_ =
; $i++ if $_ =~ /{.*}/; next if $_ !~ /{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}/; $$node{$1} = [ $i, $2, {} ]; } } } close HEADER; } &build_sysctl(\%mib, "", []); print <){ if(/^#define\s+SYS_(\w+)\s+([0-9]+)/){ my $name = $1; my $num = $2; $name =~ y/a-z/A-Z/; print " SYS_$name = $num;" } } print <){ if(/^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$/){ my $num = $1; my $proto = $2; my $name = "SYS_$3"; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print <){ if(/^([0-9]+)\s+\S+\s+STD\s+({ \S+\s+(\w+).*)$/){ my $num = $1; my $proto = $2; my $name = "SYS_$3"; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } if($name =~ /^SYS_CAP_+/ || $name =~ /^SYS___CAP_+/){ next } print " $name = $num; // $proto\n"; # We keep Capsicum syscall numbers for FreeBSD # 9-STABLE here because we are not sure whether they # are mature and stable. if($num == 513){ print " SYS_CAP_NEW = 514 // { int cap_new(int fd, uint64_t rights); }\n"; print " SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \\\n"; print " SYS_CAP_ENTER = 516 // { int cap_enter(void); }\n"; print " SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }\n"; } } } print < 999){ # ignore deprecated syscalls that are no longer implemented # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/asm-generic/unistd.h?id=refs/heads/master#n716 return; } $name =~ y/a-z/A-Z/; print " SYS_$name = $num;\n"; } my $prev; open(GCC, "gcc -E -dD $ARGV[0] |") || die "can't run gcc"; while(){ if(/^#define __NR_syscalls\s+/) { # ignore redefinitions of __NR_syscalls } elsif(/^#define __NR_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR3264_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){ fmt($1, $prev+$2) } } print <){ if($line =~ /^(.*)\\$/) { # Handle continuation $line = $1; $_ =~ s/^\s+//; $line .= $_; } else { # New line $line = $_; } next if $line =~ /\\$/; if($line =~ /^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$/) { my $num = $1; my $proto = $6; my $compat = $8; my $name = "$7_$9"; $name = "$7_$11" if $11 ne ''; $name =~ y/a-z/A-Z/; if($compat eq '' || $compat eq '30' || $compat eq '50') { print " $name = $num; // $proto\n"; } } } print <){ if(/^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$/){ my $num = $1; my $proto = $3; my $name = $4; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print < 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/str.go ================================================ // 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:]) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall.go ================================================ // 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 "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" import "unsafe" // 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 } // 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd.go ================================================ // 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) { mib, err := sysctlmib(name, args...) if err != nil { return "", err } // Find size. n := uintptr(0) if err := sysctl(mib, nil, &n, nil, 0); err != nil { return "", err } if n == 0 { return "", nil } // Read into buffer of that size. buf := make([]byte, n) if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { return "", err } // 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 { return utimes(path, nil) } // TODO: The BSDs can do utimensat with SYS_UTIMENSAT but it // isn't supported by darwin so this uses utimes instead if len(ts) != 2 { return EINVAL } // 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]))) } //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) // Madvise(addr *byte, len int, behav int) (err error) // Mprotect(addr *byte, len int, prot int) (err error) // Msync(addr *byte, len int, flags int) (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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_bsd_test.go ================================================ // 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 openbsd package unix_test import ( "testing" "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" ) const MNT_WAIT = 1 func TestGetfsstat(t *testing.T) { n, err := unix.Getfsstat(nil, MNT_WAIT) if err != nil { t.Fatal(err) } data := make([]unix.Statfs_t, n) n, err = unix.Getfsstat(data, MNT_WAIT) if err != nil { t.Fatal(err) } empty := unix.Statfs_t{} for _, stat := range data { if stat == empty { t.Fatal("an empty Statfs_t struct was returned") } } } func TestSysctlRaw(t *testing.T) { _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid()) if err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 } /* * 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) } /* * 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 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_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 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 Mkfifo(path string, mode uint32) (err error) //sys Mknod(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 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) //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 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 /* * 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 // Mmap // Mlock // Munlock // 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 // Mlockall // Munlockall // __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 // Msync_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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_amd64.go ================================================ // 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" ) //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_darwin_arm64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly.go ================================================ // 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 [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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) reclen := int(16+dirent.Namlen+1+7) & ^7 buf = buf[reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 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 /* * 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 // Mmap // 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 // Msync_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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_386.go ================================================ // 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,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 = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_dragonfly_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 } /* * 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 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 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 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 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 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) /* * 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 // Mmap // Mlock // Munlock // 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 // Mlockall // Munlockall // __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 // Msync_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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_arm.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return tv.Sec*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_freebsd_test.go ================================================ // 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 freebsd package unix_test import ( "testing" "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" ) func TestSysctUint64(t *testing.T) { _, err := unix.SysctlUint64("vm.max_kernel_address") if err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux.go ================================================ // 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 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 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) func Unlinkat(dirfd int, path string) error { return unlinkat(dirfd, path, 0) } //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(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].Sec = ts[i].Sec tv[i].Usec = ts[i].Nsec / 1000 } 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) (err error) { return Mknod(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 } 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 } 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 SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) } 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 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 clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } func ReadDirent(fd int, buf []byte) (n int, err error) { return Getdents(fd, buf) } 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 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //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 Fchmodat(dirfd int, path string, mode uint32, flags int) (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) //sysnb Getrusage(who int, rusage *Rusage) (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 Listxattr(path string, dest []byte) (sz 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 Pause() (err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sysnb prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) = SYS_PRLIMIT64 //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 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) // 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() //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 Utime(path string, buf *Utimbuf) (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 Munlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Munlockall() (err error) /* * Unimplemented */ // AddKey // AfsSyscall // Alarm // ArchPrctl // Brk // Capget // Capset // ClockGetres // ClockNanosleep // ClockSettime // Clone // CreateModule // DeleteModule // EpollCtlOld // EpollPwait // EpollWaitOld // Eventfd // Execve // Fgetxattr // Flistxattr // Fork // Fremovexattr // Fsetxattr // Futex // GetKernelSyms // GetMempolicy // GetRobustList // GetThreadArea // Getitimer // Getpmsg // IoCancel // IoDestroy // IoGetevents // IoSetup // IoSubmit // Ioctl // IoprioGet // IoprioSet // KexecLoad // Keyctl // Lgetxattr // Llistxattr // LookupDcookie // Lremovexattr // Lsetxattr // Mbind // MigratePages // Mincore // ModifyLdt // Mount // MovePages // Mprotect // MqGetsetattr // MqNotify // MqOpen // MqTimedreceive // MqTimedsend // MqUnlink // Mremap // Msgctl // Msgget // Msgrcv // Msgsnd // Msync // Newfstatat // Nfsservctl // Personality // Poll // Ppoll // Pselect6 // Ptrace // Putpmsg // QueryModule // Quotactl // Readahead // Readv // RemapFilePages // RequestKey // 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 // Vmsplice // Vserver // Waitid // _Sysctl ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) 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) // 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_amd64.go ================================================ // 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 import "syscall" //sys Dup2(oldfd int, newfd 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 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) //go:noescape func gettimeofday(tv *Timeval) (err syscall.Errno) 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 } 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm.go ================================================ // 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) //sysnb Time(t *Time_t) (tt Time_t, 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 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_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) } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_arm64.go ================================================ // 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 const _SYS_dup = SYS_DUP3 //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) //sysnb Time(t *Time_t) (tt Time_t, 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 (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) } // 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_linux_ppc64x.go ================================================ // 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 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) //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 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) 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 /* * 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 ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_netbsd_arm.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_no_getwd.go ================================================ // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 /* * 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 // utimensat // vfork // writev ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_openbsd_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris.go ================================================ // 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) } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } func pipe() (r uintptr, w uintptr, err uintptr) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } r0, w0, e1 := pipe() if e1 != 0 { err = syscall.Errno(e1) } p[0], p[1] = int(r0), int(w0) return } 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 } func wait4(pid uintptr, wstatus *WaitStatus, options uintptr, rusage *Rusage) (wpid uintptr, err uintptr) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { r0, e1 := wait4(uintptr(pid), wstatus, uintptr(options), rusage) if e1 != 0 { err = syscall.Errno(e1) } return int(r0), err } func gethostname() (name string, err uintptr) func Gethostname() (name string, err error) { name, e1 := gethostname() if e1 != 0 { err = syscall.Errno(e1) } return name, err } //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.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.Accrights = (*int8)(unsafe.Pointer(&oob[0])) } 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.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.Accrights = (*int8)(unsafe.Pointer(&oob[0])) } 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 int, arg uintptr) (err error) func IoctlSetInt(fd int, req int, value int) (err error) { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req int, value *Winsize) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req int, value *Termios) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermio(fd int, req int, value *Termio) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlGetInt(fd int, req int) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req int) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req int) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermio(fd int, req int) (*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 Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_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.listen //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 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) (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.bind //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.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.sendto //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.socket //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.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.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) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_solaris_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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") } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_test.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "fmt" "testing" "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" ) func testSetGetenv(t *testing.T, key, value string) { err := unix.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := unix.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } func TestItoa(t *testing.T) { // Make most negative integer: 0x8000... i := 1 for i<<1 != 0 { i <<= 1 } if i >= 0 { t.Fatal("bad math") } s := unix.Itoa(i) f := fmt.Sprint(i) if s != f { t.Fatalf("itoa(%d) = %s, want %s", i, s, f) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix.go ================================================ // 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 ) // 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 } func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) // Mmap manager, for use by operating system-specific implementations. type mmapper struct { 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/syscall_unix_test.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "flag" "fmt" "io/ioutil" "net" "os" "os/exec" "path/filepath" "runtime" "testing" "time" "github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix" ) // Tests that below functions, structures and constants are consistent // on all Unix-like systems. func _() { // program scheduling priority functions and constants var ( _ func(int, int, int) error = unix.Setpriority _ func(int, int) (int, error) = unix.Getpriority ) const ( _ int = unix.PRIO_USER _ int = unix.PRIO_PROCESS _ int = unix.PRIO_PGRP ) // termios constants const ( _ int = unix.TCIFLUSH _ int = unix.TCIOFLUSH _ int = unix.TCOFLUSH ) // fcntl file locking structure and constants var ( _ = unix.Flock_t{ Type: int16(0), Whence: int16(0), Start: int64(0), Len: int64(0), Pid: int32(0), } ) const ( _ = unix.F_GETLK _ = unix.F_SETLK _ = unix.F_SETLKW ) } // TestFcntlFlock tests whether the file locking structure matches // the calling convention of each kernel. func TestFcntlFlock(t *testing.T) { name := filepath.Join(os.TempDir(), "TestFcntlFlock") fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) if err != nil { t.Fatalf("Open failed: %v", err) } defer unix.Unlink(name) defer unix.Close(fd) flock := unix.Flock_t{ Type: unix.F_RDLCK, Start: 0, Len: 0, Whence: 1, } if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { t.Fatalf("FcntlFlock failed: %v", err) } } // TestPassFD tests passing a file descriptor over a Unix socket. // // This test involved both a parent and child process. The parent // process is invoked as a normal test, with "go test", which then // runs the child process by running the current test binary with args // "-test.run=^TestPassFD$" and an environment variable used to signal // that the test should become the child process instead. func TestPassFD(t *testing.T) { switch runtime.GOOS { case "dragonfly": // TODO(jsing): Figure out why sendmsg is returning EINVAL. t.Skip("skipping test on dragonfly") case "solaris": // TODO(aram): Figure out why ReadMsgUnix is returning empty message. t.Skip("skipping test on solaris, see issue 7402") } if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { passFDChild() return } tempDir, err := ioutil.TempDir("", "TestPassFD") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer unix.Close(fds[0]) defer unix.Close(fds[1]) writeFile := os.NewFile(uintptr(fds[0]), "child-writes") readFile := os.NewFile(uintptr(fds[1]), "parent-reads") defer writeFile.Close() defer readFile.Close() cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) } cmd.ExtraFiles = []*os.File{writeFile} out, err := cmd.CombinedOutput() if len(out) > 0 || err != nil { t.Fatalf("child process: %q, %v", out, err) } c, err := net.FileConn(readFile) if err != nil { t.Fatalf("FileConn: %v", err) } defer c.Close() uc, ok := c.(*net.UnixConn) if !ok { t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) } buf := make([]byte, 32) // expect 1 byte oob := make([]byte, 32) // expect 24 bytes closeUnix := time.AfterFunc(5*time.Second, func() { t.Logf("timeout reading from unix socket") uc.Close() }) _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) closeUnix.Stop() scms, err := unix.ParseSocketControlMessage(oob[:oobn]) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != 1 { t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) } scm := scms[0] gotFds, err := unix.ParseUnixRights(&scm) if err != nil { t.Fatalf("unix.ParseUnixRights: %v", err) } if len(gotFds) != 1 { t.Fatalf("wanted 1 fd; got %#v", gotFds) } f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") defer f.Close() got, err := ioutil.ReadAll(f) want := "Hello from child process!\n" if string(got) != want { t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) } } // passFDChild is the child process used by TestPassFD. func passFDChild() { defer os.Exit(0) // Look for our fd. It should be fd 3, but we work around an fd leak // bug here (http://golang.org/issue/2603) to let it be elsewhere. var uc *net.UnixConn for fd := uintptr(3); fd <= 10; fd++ { f := os.NewFile(fd, "unix-conn") var ok bool netc, _ := net.FileConn(f) uc, ok = netc.(*net.UnixConn) if ok { break } } if uc == nil { fmt.Println("failed to find unix fd") return } // Make a file f to send to our parent process on uc. // We make it in tempDir, which our parent will clean up. flag.Parse() tempDir := flag.Arg(0) f, err := ioutil.TempFile(tempDir, "") if err != nil { fmt.Printf("TempFile: %v", err) return } f.Write([]byte("Hello from child process!\n")) f.Seek(0, 0) rights := unix.UnixRights(int(f.Fd())) dummyByte := []byte("x") n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) if err != nil { fmt.Printf("WriteMsgUnix: %v", err) return } if n != 1 || oobn != len(rights) { fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) return } } // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, // and ParseUnixRights are able to successfully round-trip lists of file descriptors. func TestUnixRightsRoundtrip(t *testing.T) { testCases := [...][][]int{ {{42}}, {{1, 2}}, {{3, 4, 5}}, {{}}, {{1, 2}, {3, 4, 5}, {}, {7}}, } for _, testCase := range testCases { b := []byte{} var n int for _, fds := range testCase { // Last assignment to n wins n = len(b) + unix.CmsgLen(4*len(fds)) b = append(b, unix.UnixRights(fds...)...) } // Truncate b b = b[:n] scms, err := unix.ParseSocketControlMessage(b) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != len(testCase) { t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) } for i, scm := range scms { gotFds, err := unix.ParseUnixRights(&scm) if err != nil { t.Fatalf("ParseUnixRights: %v", err) } wantFds := testCase[i] if len(gotFds) != len(wantFds) { t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) } for j, fd := range gotFds { if fd != wantFds[j] { t.Fatalf("expected fd %v, got %v", wantFds[j], fd) } } } } } func TestRlimit(t *testing.T) { var rlimit, zero unix.Rlimit err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Getrlimit: save failed: %v", err) } if zero == rlimit { t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) } set := rlimit set.Cur = set.Max - 1 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) if err != nil { t.Fatalf("Setrlimit: set failed: %#v %v", set, err) } var get unix.Rlimit err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) if err != nil { t.Fatalf("Getrlimit: get failed: %v", err) } set = rlimit set.Cur = set.Max - 1 if set != get { // Seems like Darwin requires some privilege to // increase the soft limit of rlimit sandbox, though // Setrlimit never reports an error. switch runtime.GOOS { case "darwin": default: t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) } } err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) } } func TestSeekFailure(t *testing.T) { _, err := unix.Seek(-1, 0, 0) if err == nil { t.Fatalf("Seek(-1, 0, 0) did not fail") } str := err.Error() // used to crash on Linux t.Logf("Seek: %v", str) if str == "" { t.Fatalf("Seek(-1, 0, 0) return error with empty message") } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_darwin.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define __DARWIN_UNIX03 0 #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat64 type Statfs_t C.struct_statfs64 type Flock_t C.struct_flock type Fstore_t C.struct_fstore type Radvisory_t C.struct_radvisory type Fbootstraptransfer_t C.struct_fbootstraptransfer type Log2phys_t C.struct_log2phys type Fsid C.struct_fsid type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfmaMsghdr2 C.struct_ifma_msghdr2 type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_dragonfly.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.struct_fsid // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_freebsd.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; // This structure is a duplicate of stat on FreeBSD 8-STABLE. // See /usr/include/sys/stat.h. struct stat8 { #undef st_atimespec st_atim #undef st_mtimespec st_mtim #undef st_ctimespec st_ctim #undef st_birthtimespec st_birthtim __dev_t st_dev; ino_t st_ino; mode_t st_mode; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; __dev_t st_rdev; #if __BSD_VISIBLE struct timespec st_atimespec; struct timespec st_mtimespec; struct timespec st_ctimespec; #else time_t st_atime; long __st_atimensec; time_t st_mtime; long __st_mtimensec; time_t st_ctime; long __st_ctimensec; #endif off_t st_size; blkcnt_t st_blocks; blksize_t st_blksize; fflags_t st_flags; __uint32_t st_gen; __int32_t st_lspare; #if __BSD_VISIBLE struct timespec st_birthtimespec; unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); #else time_t st_birthtime; long st_birthtimensec; unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); #endif }; // This structure is a duplicate of if_data on FreeBSD 8-STABLE. // See /usr/include/net/if.h. struct if_data8 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_spare_char1; u_char ifi_spare_char2; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; u_long ifi_hwassist; time_t ifi_epoch; struct timeval ifi_lastchange; }; // This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE. // See /usr/include/net/if.h. struct if_msghdr8 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data8 ifm_data; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat8 type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.struct_fsid // Advice to Fadvise const ( FADV_NORMAL = C.POSIX_FADV_NORMAL FADV_RANDOM = C.POSIX_FADV_RANDOM FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL FADV_WILLNEED = C.POSIX_FADV_WILLNEED FADV_DONTNEED = C.POSIX_FADV_DONTNEED FADV_NOREUSE = C.POSIX_FADV_NOREUSE ) // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPMreqn C.struct_ip_mreqn type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( sizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfMsghdr = C.sizeof_struct_if_msghdr8 sizeofIfData = C.sizeof_struct_if_data SizeofIfData = C.sizeof_struct_if_data8 SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type ifMsghdr C.struct_if_msghdr type IfMsghdr C.struct_if_msghdr8 type ifData C.struct_if_data type IfData C.struct_if_data8 type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfZbuf C.struct_bpf_zbuf type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfZbufHeader C.struct_bpf_zbuf_header // Terminal handling type Termios C.struct_termios ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_linux.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #define _FILE_OFFSET_BITS 64 #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef TCSETS2 // On systems that have "struct termios2" use this as type Termios. typedef struct termios2 termios_t; #else typedef struct termios termios_t; #endif enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_ll s5; struct sockaddr_nl s6; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; // copied from /usr/include/linux/un.h struct my_sockaddr_un { sa_family_t sun_family; #if defined(__ARM_EABI__) || defined(__powerpc64__) // on ARM char is by default unsigned signed char sun_path[108]; #else char sun_path[108]; #endif }; #ifdef __ARM_EABI__ typedef struct user_regs PtraceRegs; #elif defined(__aarch64__) typedef struct user_pt_regs PtraceRegs; #elif defined(__powerpc64__) typedef struct pt_regs PtraceRegs; #else typedef struct user_regs_struct PtraceRegs; #endif // The real epoll_event is a union, and godefs doesn't handle it well. struct my_epoll_event { uint32_t events; #ifdef __ARM_EABI__ // padding is not specified in linux/eventpoll.h but added to conform to the // alignment requirements of EABI int32_t padFd; #endif int32_t fd; int32_t pad; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timex C.struct_timex type Time_t C.time_t type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Dirent C.struct_dirent type Fsid C.fsid_t type Flock_t C.struct_flock // Advice to Fadvise const ( FADV_NORMAL = C.POSIX_FADV_NORMAL FADV_RANDOM = C.POSIX_FADV_RANDOM FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL FADV_WILLNEED = C.POSIX_FADV_WILLNEED FADV_DONTNEED = C.POSIX_FADV_DONTNEED FADV_NOREUSE = C.POSIX_FADV_NOREUSE ) // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_my_sockaddr_un type RawSockaddrLinklayer C.struct_sockaddr_ll type RawSockaddrNetlink C.struct_sockaddr_nl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPMreqn C.struct_ip_mreqn type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter type Ucred C.struct_ucred type TCPInfo C.struct_tcp_info const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrLinklayer = C.sizeof_struct_sockaddr_ll SizeofSockaddrNetlink = C.sizeof_struct_sockaddr_nl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter SizeofUcred = C.sizeof_struct_ucred SizeofTCPInfo = C.sizeof_struct_tcp_info ) // Netlink routing and interface messages const ( IFA_UNSPEC = C.IFA_UNSPEC IFA_ADDRESS = C.IFA_ADDRESS IFA_LOCAL = C.IFA_LOCAL IFA_LABEL = C.IFA_LABEL IFA_BROADCAST = C.IFA_BROADCAST IFA_ANYCAST = C.IFA_ANYCAST IFA_CACHEINFO = C.IFA_CACHEINFO IFA_MULTICAST = C.IFA_MULTICAST IFLA_UNSPEC = C.IFLA_UNSPEC IFLA_ADDRESS = C.IFLA_ADDRESS IFLA_BROADCAST = C.IFLA_BROADCAST IFLA_IFNAME = C.IFLA_IFNAME IFLA_MTU = C.IFLA_MTU IFLA_LINK = C.IFLA_LINK IFLA_QDISC = C.IFLA_QDISC IFLA_STATS = C.IFLA_STATS IFLA_COST = C.IFLA_COST IFLA_PRIORITY = C.IFLA_PRIORITY IFLA_MASTER = C.IFLA_MASTER IFLA_WIRELESS = C.IFLA_WIRELESS IFLA_PROTINFO = C.IFLA_PROTINFO IFLA_TXQLEN = C.IFLA_TXQLEN IFLA_MAP = C.IFLA_MAP IFLA_WEIGHT = C.IFLA_WEIGHT IFLA_OPERSTATE = C.IFLA_OPERSTATE IFLA_LINKMODE = C.IFLA_LINKMODE IFLA_LINKINFO = C.IFLA_LINKINFO IFLA_NET_NS_PID = C.IFLA_NET_NS_PID IFLA_IFALIAS = C.IFLA_IFALIAS IFLA_MAX = C.IFLA_MAX RT_SCOPE_UNIVERSE = C.RT_SCOPE_UNIVERSE RT_SCOPE_SITE = C.RT_SCOPE_SITE RT_SCOPE_LINK = C.RT_SCOPE_LINK RT_SCOPE_HOST = C.RT_SCOPE_HOST RT_SCOPE_NOWHERE = C.RT_SCOPE_NOWHERE RT_TABLE_UNSPEC = C.RT_TABLE_UNSPEC RT_TABLE_COMPAT = C.RT_TABLE_COMPAT RT_TABLE_DEFAULT = C.RT_TABLE_DEFAULT RT_TABLE_MAIN = C.RT_TABLE_MAIN RT_TABLE_LOCAL = C.RT_TABLE_LOCAL RT_TABLE_MAX = C.RT_TABLE_MAX RTA_UNSPEC = C.RTA_UNSPEC RTA_DST = C.RTA_DST RTA_SRC = C.RTA_SRC RTA_IIF = C.RTA_IIF RTA_OIF = C.RTA_OIF RTA_GATEWAY = C.RTA_GATEWAY RTA_PRIORITY = C.RTA_PRIORITY RTA_PREFSRC = C.RTA_PREFSRC RTA_METRICS = C.RTA_METRICS RTA_MULTIPATH = C.RTA_MULTIPATH RTA_FLOW = C.RTA_FLOW RTA_CACHEINFO = C.RTA_CACHEINFO RTA_TABLE = C.RTA_TABLE RTN_UNSPEC = C.RTN_UNSPEC RTN_UNICAST = C.RTN_UNICAST RTN_LOCAL = C.RTN_LOCAL RTN_BROADCAST = C.RTN_BROADCAST RTN_ANYCAST = C.RTN_ANYCAST RTN_MULTICAST = C.RTN_MULTICAST RTN_BLACKHOLE = C.RTN_BLACKHOLE RTN_UNREACHABLE = C.RTN_UNREACHABLE RTN_PROHIBIT = C.RTN_PROHIBIT RTN_THROW = C.RTN_THROW RTN_NAT = C.RTN_NAT RTN_XRESOLVE = C.RTN_XRESOLVE RTNLGRP_NONE = C.RTNLGRP_NONE RTNLGRP_LINK = C.RTNLGRP_LINK RTNLGRP_NOTIFY = C.RTNLGRP_NOTIFY RTNLGRP_NEIGH = C.RTNLGRP_NEIGH RTNLGRP_TC = C.RTNLGRP_TC RTNLGRP_IPV4_IFADDR = C.RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_MROUTE = C.RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_ROUTE = C.RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_RULE = C.RTNLGRP_IPV4_RULE RTNLGRP_IPV6_IFADDR = C.RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_MROUTE = C.RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_ROUTE = C.RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_IFINFO = C.RTNLGRP_IPV6_IFINFO RTNLGRP_IPV6_PREFIX = C.RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_RULE = C.RTNLGRP_IPV6_RULE RTNLGRP_ND_USEROPT = C.RTNLGRP_ND_USEROPT SizeofNlMsghdr = C.sizeof_struct_nlmsghdr SizeofNlMsgerr = C.sizeof_struct_nlmsgerr SizeofRtGenmsg = C.sizeof_struct_rtgenmsg SizeofNlAttr = C.sizeof_struct_nlattr SizeofRtAttr = C.sizeof_struct_rtattr SizeofIfInfomsg = C.sizeof_struct_ifinfomsg SizeofIfAddrmsg = C.sizeof_struct_ifaddrmsg SizeofRtMsg = C.sizeof_struct_rtmsg SizeofRtNexthop = C.sizeof_struct_rtnexthop ) type NlMsghdr C.struct_nlmsghdr type NlMsgerr C.struct_nlmsgerr type RtGenmsg C.struct_rtgenmsg type NlAttr C.struct_nlattr type RtAttr C.struct_rtattr type IfInfomsg C.struct_ifinfomsg type IfAddrmsg C.struct_ifaddrmsg type RtMsg C.struct_rtmsg type RtNexthop C.struct_rtnexthop // Linux socket filter const ( SizeofSockFilter = C.sizeof_struct_sock_filter SizeofSockFprog = C.sizeof_struct_sock_fprog ) type SockFilter C.struct_sock_filter type SockFprog C.struct_sock_fprog // Inotify type InotifyEvent C.struct_inotify_event const SizeofInotifyEvent = C.sizeof_struct_inotify_event // Ptrace // Register structures type PtraceRegs C.PtraceRegs // Misc type FdSet C.fd_set type Sysinfo_t C.struct_sysinfo type Utsname C.struct_utsname type Ustat_t C.struct_ustat type EpollEvent C.struct_my_epoll_event const ( AT_FDCWD = C.AT_FDCWD AT_REMOVEDIR = C.AT_REMOVEDIR AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) // Terminal handling type Termios C.termios_t ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_netbsd.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.fsid_t // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics type Mclpool C.struct_mclpool // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfTimeval C.struct_bpf_timeval // Terminal handling type Termios C.struct_termios // Sysctl type Sysctlnode C.struct_sysctlnode ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_openbsd.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.fsid_t // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics type Mclpool C.struct_mclpool // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfTimeval C.struct_bpf_timeval // Terminal handling type Termios C.struct_termios ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/types_solaris.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL // These defines ensure that builds done on newer versions of Solaris are // backwards-compatible with older versions of Solaris and // OpenSolaris-based derivatives. #define __USE_SUNOS_SOCKETS__ // msghdr #define __USE_LEGACY_PROTOTYPES__ // iovec #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Flock_t C.struct_flock type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Select type FdSet C.fd_set // Misc type Utsname C.struct_utsname type Ustat_t C.struct_ustat const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_REMOVEDIR = C.AT_REMOVEDIR AT_EACCESS = C.AT_EACCESS ) // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfTimeval C.struct_bpf_timeval type BpfHdr C.struct_bpf_hdr // sysconf information const _SC_PAGESIZE = C._SC_PAGESIZE // Terminal handling type Termios C.struct_termios type Termio C.struct_termio type Winsize C.struct_winsize ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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 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 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_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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 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 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_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go // +build arm,darwin 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 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 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 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 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xc 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 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_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 = 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_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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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) ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_darwin_arm64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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 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 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_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,dragonfly // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m32 _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_NETGRAPH = 0x20 AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 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 = 0xc0084279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4008426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80084267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8008427b 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_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 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 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_MARKER = 0xf EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x8 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_NODATA = 0x1000 EV_ONESHOT = 0x10 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_SCTP = 0x84 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_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_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_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_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_NOTIFICATION = 0x200 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_SYNC = 0x800 MSG_TRUNC = 0x10 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 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_OOB = 0x2 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 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_FBUFFERED = 0x2000000 O_FMASK = 0x7fc0000 O_FNONBLOCKING = 0x80000 O_FOFFSET = 0x200000 O_FSYNC = 0x80 O_FSYNCWRITE = 0x400000 O_FUNBUFFERED = 0x1000000 O_MAPONREAD = 0x4000000 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 = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0086924 SIOCGIFDATA = 0xc0206926 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFINDEX = 0xc0206920 SIOCGIFMEDIA = 0xc0286938 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 = 0xc00c6978 SIOCSDRVSPEC = 0x801c697b 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_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_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 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 TCIOFLUSH = 0x3 TCOFLUSH = 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 = 0x40087458 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 = 0x40087459 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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_NETGRAPH = 0x20 AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 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 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 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_MARKER = 0xf EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x8 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_NODATA = 0x1000 EV_ONESHOT = 0x10 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_SCTP = 0x84 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_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_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_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_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_NOTIFICATION = 0x200 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_SYNC = 0x800 MSG_TRUNC = 0x10 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 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_OOB = 0x2 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 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_FBUFFERED = 0x2000000 O_FMASK = 0x7fc0000 O_FNONBLOCKING = 0x80000 O_FOFFSET = 0x200000 O_FSYNC = 0x80 O_FSYNCWRITE = 0x400000 O_FUNBUFFERED = 0x1000000 O_MAPONREAD = 0x4000000 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_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_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 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 TCIOFLUSH = 0x3 TCOFLUSH = 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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_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 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 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_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 = 0xf6 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 = 0x79 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_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xb 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_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 = 0x218f72 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_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_INFINIBAND = 0xc7 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_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 = 0xf6 IFT_PFSYNC = 0xf7 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 = 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 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_MAXID = 0x34 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_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_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_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_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 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_FAITH = 0x16 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_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTOS = 0x44 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_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_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 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 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 NET_RT_MAXID = 0x6 NOFLSH = 0x80000000 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_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 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_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 = 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_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_PRCLONING = 0x10000 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_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 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_NORTREF = 0x2 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 SIOCADDRT = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 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 SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 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 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CONGESTION = 0x40 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_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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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_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 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 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_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 = 0xf6 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 = 0x79 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_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xb 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_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 = 0x218f72 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_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_INFINIBAND = 0xc7 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_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 = 0xf6 IFT_PFSYNC = 0xf7 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 = 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 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_MAXID = 0x34 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_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_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_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_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 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_FAITH = 0x16 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_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTOS = 0x44 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_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_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 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 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 NET_RT_MAXID = 0x6 NOFLSH = 0x80000000 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_MSECONDS = 0x2 NOTE_NSECONDS = 0x8 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff 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 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_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 = 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_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_PRCLONING = 0x10000 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_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 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_NORTREF = 0x2 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 SIOCADDRT = 0x8040720a SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8040720b SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc028697b SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 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 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 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 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CONGESTION = 0x40 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_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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_freebsd_arm.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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_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 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 = 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_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 = 0xf6 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 = 0x79 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_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xb 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_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 = 0x218f72 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_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_INFINIBAND = 0xc7 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_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 = 0xf6 IFT_PFSYNC = 0xf7 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 = 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 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_MAXID = 0x34 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_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_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_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_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 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_FAITH = 0x16 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_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTOS = 0x44 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_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_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 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 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 NET_RT_MAXID = 0x6 NOFLSH = 0x80000000 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_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 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_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 = 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_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_PRCLONING = 0x10000 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_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 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_NORTREF = 0x2 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 SIOCADDRT = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 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 SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 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 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CONGESTION = 0x40 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_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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x28 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_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 EPOLL_NONBLOCK = 0x800 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 IFF_MULTICAST = 0x1000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_OVS_DATAPATH = 0x8000 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DOFORK = 0xb MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 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_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 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_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_GET_THREAD_AREA = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_MASK = 0xff 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_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SEIZE = 0x4206 PTRACE_SEIZE_DEVEL = 0x80000000 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xe RTAX_MTU = 0x2 RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x10 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELNEIGH = 0x1d RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x4f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x10 RTM_NR_MSGTYPES = 0x40 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_MARK = 0x24 SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 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_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 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 = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CONGESTION = 0xd TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_QUICKACK = 0xc TCP_SYNCNT = 0x7 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 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 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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 NFS 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: "unknown error 133", } // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x28 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_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 EPOLL_NONBLOCK = 0x800 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 IFF_MULTICAST = 0x1000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_OVS_DATAPATH = 0x8000 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DOFORK = 0xb MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 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_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 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_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_GET_THREAD_AREA = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_MASK = 0xff 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_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SEIZE = 0x4206 PTRACE_SEIZE_DEVEL = 0x80000000 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xe RTAX_MTU = 0x2 RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x10 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELNEIGH = 0x1d RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x4f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x10 RTM_NR_MSGTYPES = 0x40 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_MARK = 0x24 SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 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_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 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 = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CONGESTION = 0xd TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_QUICKACK = 0xc TCP_SYNCNT = 0x7 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 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 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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 NFS 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: "unknown error 133", } // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x27 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_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_PHY = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ELF_NGREG = 0x12 ELF_PRARGSZ = 0x50 ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EPOLLERR = 0x8 EPOLLET = -0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 EPOLL_NONBLOCK = 0x800 ETH_P_1588 = 0x88f7 ETH_P_8021Q = 0x8100 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_AARP = 0x80f3 ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_ALLMULTI = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DYNAMIC = 0x8000 IFF_LOOPBACK = 0x8 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 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 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_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DOFORK = 0xb MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_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 = 0x1000 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 = 0x1000 O_SYNC = 0x1000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_BROADCAST = 0x1 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FASTROUTE = 0x6 PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MULTICAST = 0x2 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PARENB = 0x100 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_CLEAR_SECCOMP_FILTER = 0x25 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECCOMP_FILTER = 0x23 PR_GET_SECUREBITS = 0x1b PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_SECCOMP_FILTER_EVENT = 0x1 PR_SECCOMP_FILTER_SYSCALL = 0x0 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_KEEPCAPS = 0x8 PR_SET_NAME = 0xf PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_SECCOMP = 0x16 PR_SET_SECCOMP_FILTER = 0x24 PR_SET_SECUREBITS = 0x1c PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_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_GETVFPREGS = 0x1b PTRACE_GETWMMXREGS = 0x12 PTRACE_GET_THREAD_AREA = 0x16 PTRACE_KILL = 0x8 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_MASK = 0x7f PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SETCRUNCHREGS = 0x1a PTRACE_SETFPREGS = 0xf PTRACE_SETHBPREGS = 0x1e PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xe RTAX_MTU = 0x2 RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x10 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELNEIGH = 0x1d RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x4f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x10 RTM_NR_MSGTYPES = 0x40 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_MARK = 0x24 SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 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_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 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 = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CONGESTION = 0xd TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_QUICKACK = 0xc TCP_SYNCNT = 0x7 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 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 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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 NFS 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: "unknown error 133", } // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_arm64.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x29 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_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_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 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 ELF_NGREG = 0x22 ELF_PRARGSZ = 0x50 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 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_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_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_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_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LIVE_ADDR_CHANGE = 0x100000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN = 0x200000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 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_OVS_DATAPATH = 0x8000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_SUPP_NOFCS = 0x80000 IFF_TAP = 0x2 IFF_TEAM_PORT = 0x40000 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 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_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_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_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 = 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_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b 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_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc 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_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_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 = 0x1000ff 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_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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xf 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 = 0x11 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_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x57 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_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x12 RTM_NR_MSGTYPES = 0x48 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a 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_WIFI_STATUS = 0x29 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 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_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 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 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x801054db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64,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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x29 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 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 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_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_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 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 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 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 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_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_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_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 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 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_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 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_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_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_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_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 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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_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_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 = 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_CPU = 0x2 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_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 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_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_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_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc 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 = 0x1000ff 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_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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xf 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 = 0x11 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_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x57 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_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x12 RTM_NR_MSGTYPES = 0x48 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a 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_WIFI_STATUS = 0x29 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 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_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 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 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETHDRSZ = 0x400454d7 TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETHDRSZ = 0x800454d8 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 VEOL2 = 0x8 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x5 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_linux_ppc64le.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64le,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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x29 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_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 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_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_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 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 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 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 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_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_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_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_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LIVE_ADDR_CHANGE = 0x100000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN = 0x200000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 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_OVS_DATAPATH = 0x8000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_SUPP_NOFCS = 0x80000 IFF_TAP = 0x2 IFF_TEAM_PORT = 0x40000 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 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_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x80 ISTRIP = 0x20 IUCLC = 0x1000 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_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_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 = 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_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 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 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_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b 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_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc 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_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_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 = 0x1000ff 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_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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xf 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 = 0x11 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_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x57 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_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x12 RTM_NR_MSGTYPES = 0x48 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a 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_WIFI_STATUS = 0x29 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 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_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 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 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETHDRSZ = 0x400454d7 TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETHDRSZ = 0x800454d8 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 VEOL2 = 0x8 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x5 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_386.go ================================================ // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_amd64.go ================================================ // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_netbsd_arm.go ================================================ // 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 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_386.go ================================================ // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_openbsd_amd64.go ================================================ // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zerrors_solaris_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 CFLUSH = 0xf 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 CREAD = 0x80 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 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_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_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 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 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 MADV_ACCESS_DEFAULT = 0x6 MADV_ACCESS_LWP = 0x7 MADV_ACCESS_MANY = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_32BIT = 0x80 MAP_ALIGN = 0x200 MAP_ANON = 0x100 MAP_ANONYMOUS = 0x100 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 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 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 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCIFLUSH = 0x0 TCIOFLUSH = 0x2 TCOFLUSH = 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 ) // 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", } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_386.go ================================================ // mksyscall.pl -l32 syscall_bsd.go syscall_darwin.go syscall_darwin_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_amd64.go ================================================ // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm.go ================================================ // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_darwin_arm64.go ================================================ // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm64,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_386.go ================================================ // mksyscall.pl -l32 -dragonfly syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,dragonfly 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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), 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 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), 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go ================================================ // mksyscall.pl -dragonfly syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,dragonfly 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_freebsd_386.go ================================================ // mksyscall.pl -l32 syscall_bsd.go syscall_freebsd.go syscall_freebsd_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,freebsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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 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), 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go ================================================ // mksyscall.pl syscall_bsd.go syscall_freebsd.go syscall_freebsd_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,freebsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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 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), 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_freebsd_arm.go ================================================ // mksyscall.pl -l32 -arm syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,freebsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_386.go ================================================ // mksyscall.pl -l32 syscall_linux.go syscall_linux_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_amd64.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm.go ================================================ // mksyscall.pl -l32 -arm syscall_linux.go syscall_linux_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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_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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_arm64.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_arm64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm64,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_ppc64x.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_ppc64x.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64le,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_386.go ================================================ // mksyscall.pl -l32 -netbsd syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,netbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go ================================================ // mksyscall.pl -netbsd syscall_bsd.go syscall_netbsd.go syscall_netbsd_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,netbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_netbsd_arm.go ================================================ // mksyscall.pl -l32 -arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,netbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_386.go ================================================ // mksyscall.pl -l32 -openbsd syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,openbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go ================================================ // mksyscall.pl -openbsd syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,openbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsyscall_solaris_amd64.go ================================================ // mksyscall_solaris.pl syscall_solaris.go syscall_solaris_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,solaris package unix import ( "syscall" "unsafe" ) //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_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_recvmsg recvmsg "libsocket.so" //go:cgo_import_dynamic libc_sendmsg 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_fpathconf fpathconf "libc.so" //go:cgo_import_dynamic libc_fstat fstat "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_listen listen "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_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_bind bind "libsocket.so" //go:cgo_import_dynamic libc_connect 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_sendto sendto "libsocket.so" //go:cgo_import_dynamic libc_socket socket "libsocket.so" //go:cgo_import_dynamic libc_socketpair socketpair "libsocket.so" //go:cgo_import_dynamic libc_write write "libc.so" //go:cgo_import_dynamic libc_getsockopt 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 procgetsockname libc_getsockname //go:linkname procGetcwd libc_getcwd //go:linkname procgetgroups libc_getgroups //go:linkname procsetgroups libc_setgroups //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 procrecvmsg libc_recvmsg //go:linkname procsendmsg libc_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 procFpathconf libc_fpathconf //go:linkname procFstat libc_fstat //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 proclisten libc_listen //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 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 procbind libc_bind //go:linkname procconnect libc_connect //go:linkname procmmap libc_mmap //go:linkname procmunmap libc_munmap //go:linkname procsendto libc_sendto //go:linkname procsocket libc_socket //go:linkname procsocketpair libc_socketpair //go:linkname procwrite libc_write //go:linkname procgetsockopt libc_getsockopt //go:linkname procgetpeername libc_getpeername //go:linkname procsetsockopt libc_setsockopt //go:linkname procrecvfrom libc_recvfrom //go:linkname procsysconf libc_sysconf var ( procgetsockname, procGetcwd, procgetgroups, procsetgroups, procutimes, procutimensat, procfcntl, procfutimesat, procaccept, procrecvmsg, procsendmsg, procacct, procioctl, procAccess, procAdjtime, procChdir, procChmod, procChown, procChroot, procClose, procCreat, procDup, procDup2, procExit, procFchdir, procFchmod, procFchmodat, procFchown, procFchownat, procFdatasync, procFpathconf, procFstat, procGetdents, procGetgid, procGetpid, procGetpgid, procGetpgrp, procGeteuid, procGetegid, procGetppid, procGetpriority, procGetrlimit, procGetrusage, procGettimeofday, procGetuid, procKill, procLchown, procLink, proclisten, 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, procSymlink, procSync, procTimes, procTruncate, procFsync, procFtruncate, procUmask, procUname, procumount, procUnlink, procUnlinkat, procUstat, procUtime, procbind, procconnect, procmmap, procmunmap, procsendto, procsocket, procsocketpair, procwrite, procgetsockopt, procgetpeername, procsetsockopt, procrecvfrom, procsysconf syscallFunc ) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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(&procrecvmsg)), 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(&procsendmsg)), 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 int, 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = e1 } return } func Listen(s int, backlog int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclisten)), 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = e1 } return } func Unlinkat(dirfd int, path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = e1 } return } func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procbind)), 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(&procconnect)), 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(&procsendto)), 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(&procsocket)), 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(&procsocketpair)), 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(&procgetsockopt)), 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysctl_openbsd.go ================================================ // 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}}, } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_386.go ================================================ // 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_amd64.go ================================================ // 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm.go ================================================ // mksysnum_darwin.pl /usr/include/sys/syscall.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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_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_ATSOCKET = 206 SYS_ATGETMSG = 207 SYS_ATPUTMSG = 208 SYS_ATPSNDREQ = 209 SYS_ATPSNDRSP = 210 SYS_ATPGETREQ = 211 SYS_ATPGETRSP = 212 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_SEM_GETVALUE = 274 SYS_SEM_INIT = 275 SYS_SEM_DESTROY = 276 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_MAXSYSCALL = 440 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_darwin_arm64.go ================================================ // mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/include/sys/syscall.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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_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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_386.go ================================================ // mksysnum_dragonfly.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build 386,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(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, 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(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, 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, 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_SCTP_PEELOFF = 364 // { int sctp_peeloff(int sd, caddr_t name ); } 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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go ================================================ // mksysnum_dragonfly.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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(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, 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(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, 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, 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_SCTP_PEELOFF = 364 // { int sctp_peeloff(int sd, caddr_t name ); } 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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_386.go ================================================ // mksysnum_freebsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ 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_NEW = 514 // { int cap_new(int fd, uint64_t rights); } SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ 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_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, \ ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go ================================================ // mksysnum_freebsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ 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_NEW = 514 // { int cap_new(int fd, uint64_t rights); } SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ 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_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, \ ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_freebsd_arm.go ================================================ // mksysnum_freebsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ 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_NEW = 514 // { int cap_new(int fd, uint64_t rights); } SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ 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_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, \ ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_386.go ================================================ // mksysnum_linux.pl /usr/include/asm/unistd_32.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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_MADVISE1 = 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_amd64.go ================================================ // mksysnum_linux.pl /usr/include/asm/unistd_64.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm.go ================================================ // mksysnum_linux.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build arm,linux package unix const ( SYS_OABI_SYSCALL_BASE = 0 SYS_SYSCALL_BASE = 0 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_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 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_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_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_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 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_FCHOWN = 95 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_VHANGUP = 111 SYS_SYSCALL = 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_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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_arm64.go ================================================ // mksysnum_linux.pl /usr/include/asm-generic/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64.go ================================================ // mksysnum_linux.pl /usr/include/asm/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go ================================================ // mksysnum_linux.pl /usr/include/powerpc64le-linux-gnu/asm/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_386.go ================================================ // 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___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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go ================================================ // 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___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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_netbsd_arm.go ================================================ // 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___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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_386.go ================================================ // 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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go ================================================ // 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); } ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/zsysnum_solaris_amd64.go ================================================ // 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 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_386.go ================================================ // +build 386,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_darwin.go 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_amd64.go ================================================ // +build amd64,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 } const ( AT_FDCWD = -0x2 AT_SYMLINK_NOFOLLOW = 0x20 ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm.go ================================================ // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_darwin_arm64.go ================================================ // +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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_386.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_dragonfly.go // +build 386,dragonfly 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 { 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 int32 Bsize int32 Iosize int32 Blocks int32 Bfree int32 Bavail int32 Files int32 Ffree int32 Fsid Fsid Owner uint32 Type int32 Flags int32 Syncwrites int32 Asyncwrites int32 Fstypename [16]int8 Mntonname [80]int8 Syncreads int32 Asyncreads int32 Spares1 int16 Mntfromname [80]int8 Spares2 int16 Spare [2]int32 } 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 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 = 0x36 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 int32 Udata *byte } type FdSet struct { Bits [32]uint32 } const ( SizeofIfMsghdr = 0x68 SizeofIfData = 0x58 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 IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Pad_cgo_0 [2]byte Mtu uint32 Metric uint32 Link_state uint32 Baudrate uint64 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Hwassist uint32 Unused uint32 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 uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Pksent uint32 Expire uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Recvpipe uint32 Hopcount uint32 Mssopt uint16 Pad uint16 Msl uint32 Iwmaxsegs uint32 Iwcapsegs 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_dragonfly.go // +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 Unused 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_386.go ================================================ // +build 386,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.go 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 uint32 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 = 0x64 SizeofIfMsghdr = 0x60 sizeofIfData = 0x54 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 Baudrate_pf 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 uint64 Epoch int32 Lastchange Timeval } 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_amd64.go ================================================ // +build amd64,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.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 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 uint32 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 Baudrate_pf 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_freebsd_arm.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -fsigned-char types_freebsd.go // +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 uint32 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 } 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 = 0x70 SizeofIfMsghdr = 0x70 sizeofIfData = 0x60 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 Baudrate_pf 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 uint64 Epoch int64 Lastchange Timeval } 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_386.go ================================================ // +build 386,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev 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 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 RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 X__cmsg_data [0]uint8 } 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 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x1d RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 Name [0]int8 } 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_SYMLINK_NOFOLLOW = 0x100 AT_REMOVEDIR = 0x200 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_amd64.go ================================================ // +build amd64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.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 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 X__unused [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 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x1d RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 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 Name [0]int8 } 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_SYMLINK_NOFOLLOW = 0x100 AT_REMOVEDIR = 0x200 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm.go ================================================ // +build arm,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev 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 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 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 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 X__cmsg_data [0]uint8 } 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 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x1d RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 Name [0]uint8 } 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_SYMLINK_NOFOLLOW = 0x100 AT_REMOVEDIR = 0x200 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_arm64.go ================================================ // +build arm64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -fsigned-char types_linux.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 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 X__glibc_reserved [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 } 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x22 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 Name [0]int8 } 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 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_NOFOLLOW = 0x100 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64.go ================================================ // +build ppc64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.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 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 X__glibc_reserved4 uint64 X__glibc_reserved5 uint64 X__glibc_reserved6 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 } 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 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x23 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 Name [0]uint8 } 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 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_NOFOLLOW = 0x100 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Line uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_linux_ppc64le.go ================================================ // +build ppc64le,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.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 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 X__glibc_reserved4 uint64 X__glibc_reserved5 uint64 X__glibc_reserved6 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 } 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 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x22 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 Name [0]uint8 } 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 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_NOFOLLOW = 0x100 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Line uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_386.go ================================================ // 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 } 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_amd64.go ================================================ // 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 } 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_netbsd_arm.go ================================================ // 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 } 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_386.go ================================================ // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_openbsd_amd64.go ================================================ // 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/external/golang.org/x/sys/unix/ztypes_solaris_amd64.go ================================================ // +build amd64,solaris // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_solaris.go package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x400 ) 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 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 } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/image.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "bytes" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "os" "time" ) // APIImages represent an image returned in the ListImages call. type APIImages struct { ID string `json:"Id" yaml:"Id"` RepoTags []string `json:"RepoTags,omitempty" yaml:"RepoTags,omitempty"` Created int64 `json:"Created,omitempty" yaml:"Created,omitempty"` Size int64 `json:"Size,omitempty" yaml:"Size,omitempty"` VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty"` ParentID string `json:"ParentId,omitempty" yaml:"ParentId,omitempty"` RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty"` Labels map[string]string `json:"Labels,omitempty" yaml:"Labels,omitempty"` } // Image is the type representing a docker image and its various properties type Image struct { ID string `json:"Id" yaml:"Id"` Parent string `json:"Parent,omitempty" yaml:"Parent,omitempty"` Comment string `json:"Comment,omitempty" yaml:"Comment,omitempty"` Created time.Time `json:"Created,omitempty" yaml:"Created,omitempty"` Container string `json:"Container,omitempty" yaml:"Container,omitempty"` ContainerConfig Config `json:"ContainerConfig,omitempty" yaml:"ContainerConfig,omitempty"` DockerVersion string `json:"DockerVersion,omitempty" yaml:"DockerVersion,omitempty"` Author string `json:"Author,omitempty" yaml:"Author,omitempty"` Config *Config `json:"Config,omitempty" yaml:"Config,omitempty"` Architecture string `json:"Architecture,omitempty" yaml:"Architecture,omitempty"` Size int64 `json:"Size,omitempty" yaml:"Size,omitempty"` VirtualSize int64 `json:"VirtualSize,omitempty" yaml:"VirtualSize,omitempty"` RepoDigests []string `json:"RepoDigests,omitempty" yaml:"RepoDigests,omitempty"` } // ImagePre012 serves the same purpose as the Image type except that it is for // earlier versions of the Docker API (pre-012 to be specific) type ImagePre012 struct { ID string `json:"id"` Parent string `json:"parent,omitempty"` Comment string `json:"comment,omitempty"` Created time.Time `json:"created"` Container string `json:"container,omitempty"` ContainerConfig Config `json:"container_config,omitempty"` DockerVersion string `json:"docker_version,omitempty"` Author string `json:"author,omitempty"` Config *Config `json:"config,omitempty"` Architecture string `json:"architecture,omitempty"` Size int64 `json:"size,omitempty"` } var ( // ErrNoSuchImage is the error returned when the image does not exist. ErrNoSuchImage = errors.New("no such image") // ErrMissingRepo is the error returned when the remote repository is // missing. ErrMissingRepo = errors.New("missing remote repository e.g. 'github.com/user/repo'") // ErrMissingOutputStream is the error returned when no output stream // is provided to some calls, like BuildImage. ErrMissingOutputStream = errors.New("missing output stream") // ErrMultipleContexts is the error returned when both a ContextDir and // InputStream are provided in BuildImageOptions ErrMultipleContexts = errors.New("image build may not be provided BOTH context dir and input stream") // ErrMustSpecifyNames is the error rreturned when the Names field on // ExportImagesOptions is nil or empty ErrMustSpecifyNames = errors.New("must specify at least one name to export") ) // ListImagesOptions specify parameters to the ListImages function. // // See https://goo.gl/xBe1u3 for more details. type ListImagesOptions struct { All bool Filters map[string][]string Digests bool Filter string } // ListImages returns the list of available images in the server. // // See https://goo.gl/xBe1u3 for more details. func (c *Client) ListImages(opts ListImagesOptions) ([]APIImages, error) { path := "/images/json?" + queryString(opts) resp, err := c.do("GET", path, doOptions{}) if err != nil { return nil, err } defer resp.Body.Close() var images []APIImages if err := json.NewDecoder(resp.Body).Decode(&images); err != nil { return nil, err } return images, nil } // ImageHistory represent a layer in an image's history returned by the // ImageHistory call. type ImageHistory struct { ID string `json:"Id" yaml:"Id"` Tags []string `json:"Tags,omitempty" yaml:"Tags,omitempty"` Created int64 `json:"Created,omitempty" yaml:"Created,omitempty"` CreatedBy string `json:"CreatedBy,omitempty" yaml:"CreatedBy,omitempty"` Size int64 `json:"Size,omitempty" yaml:"Size,omitempty"` } // ImageHistory returns the history of the image by its name or ID. // // See https://goo.gl/8bnTId for more details. func (c *Client) ImageHistory(name string) ([]ImageHistory, error) { resp, err := c.do("GET", "/images/"+name+"/history", doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, ErrNoSuchImage } return nil, err } defer resp.Body.Close() var history []ImageHistory if err := json.NewDecoder(resp.Body).Decode(&history); err != nil { return nil, err } return history, nil } // RemoveImage removes an image by its name or ID. // // See https://goo.gl/V3ZWnK for more details. func (c *Client) RemoveImage(name string) error { resp, err := c.do("DELETE", "/images/"+name, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return ErrNoSuchImage } return err } resp.Body.Close() return nil } // RemoveImageOptions present the set of options available for removing an image // from a registry. // // See https://goo.gl/V3ZWnK for more details. type RemoveImageOptions struct { Force bool `qs:"force"` NoPrune bool `qs:"noprune"` } // RemoveImageExtended removes an image by its name or ID. // Extra params can be passed, see RemoveImageOptions // // See https://goo.gl/V3ZWnK for more details. func (c *Client) RemoveImageExtended(name string, opts RemoveImageOptions) error { uri := fmt.Sprintf("/images/%s?%s", name, queryString(&opts)) resp, err := c.do("DELETE", uri, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return ErrNoSuchImage } return err } resp.Body.Close() return nil } // InspectImage returns an image by its name or ID. // // See https://goo.gl/jHPcg6 for more details. func (c *Client) InspectImage(name string) (*Image, error) { resp, err := c.do("GET", "/images/"+name+"/json", doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, ErrNoSuchImage } return nil, err } defer resp.Body.Close() var image Image // if the caller elected to skip checking the server's version, assume it's the latest if c.SkipServerVersionCheck || c.expectedAPIVersion.GreaterThanOrEqualTo(apiVersion112) { if err := json.NewDecoder(resp.Body).Decode(&image); err != nil { return nil, err } } else { var imagePre012 ImagePre012 if err := json.NewDecoder(resp.Body).Decode(&imagePre012); err != nil { return nil, err } image.ID = imagePre012.ID image.Parent = imagePre012.Parent image.Comment = imagePre012.Comment image.Created = imagePre012.Created image.Container = imagePre012.Container image.ContainerConfig = imagePre012.ContainerConfig image.DockerVersion = imagePre012.DockerVersion image.Author = imagePre012.Author image.Config = imagePre012.Config image.Architecture = imagePre012.Architecture image.Size = imagePre012.Size } return &image, nil } // PushImageOptions represents options to use in the PushImage method. // // See https://goo.gl/zPtZaT for more details. type PushImageOptions struct { // Name of the image Name string // Tag of the image Tag string // Registry server to push the image Registry string OutputStream io.Writer `qs:"-"` RawJSONStream bool `qs:"-"` } // PushImage pushes an image to a remote registry, logging progress to w. // // An empty instance of AuthConfiguration may be used for unauthenticated // pushes. // // See https://goo.gl/zPtZaT for more details. func (c *Client) PushImage(opts PushImageOptions, auth AuthConfiguration) error { if opts.Name == "" { return ErrNoSuchImage } headers, err := headersWithAuth(auth) if err != nil { return err } name := opts.Name opts.Name = "" path := "/images/" + name + "/push?" + queryString(&opts) return c.stream("POST", path, streamOptions{ setRawTerminal: true, rawJSONStream: opts.RawJSONStream, headers: headers, stdout: opts.OutputStream, }) } // PullImageOptions present the set of options available for pulling an image // from a registry. // // See https://goo.gl/iJkZjD for more details. type PullImageOptions struct { Repository string `qs:"fromImage"` Registry string Tag string OutputStream io.Writer `qs:"-"` RawJSONStream bool `qs:"-"` } // PullImage pulls an image from a remote registry, logging progress to // opts.OutputStream. // // See https://goo.gl/iJkZjD for more details. func (c *Client) PullImage(opts PullImageOptions, auth AuthConfiguration) error { if opts.Repository == "" { return ErrNoSuchImage } headers, err := headersWithAuth(auth) if err != nil { return err } return c.createImage(queryString(&opts), headers, nil, opts.OutputStream, opts.RawJSONStream) } func (c *Client) createImage(qs string, headers map[string]string, in io.Reader, w io.Writer, rawJSONStream bool) error { path := "/images/create?" + qs return c.stream("POST", path, streamOptions{ setRawTerminal: true, rawJSONStream: rawJSONStream, headers: headers, in: in, stdout: w, }) } // LoadImageOptions represents the options for LoadImage Docker API Call // // See https://goo.gl/JyClMX for more details. type LoadImageOptions struct { InputStream io.Reader } // LoadImage imports a tarball docker image // // See https://goo.gl/JyClMX for more details. func (c *Client) LoadImage(opts LoadImageOptions) error { return c.stream("POST", "/images/load", streamOptions{ setRawTerminal: true, in: opts.InputStream, }) } // ExportImageOptions represent the options for ExportImage Docker API call. // // See https://goo.gl/le7vK8 for more details. type ExportImageOptions struct { Name string OutputStream io.Writer } // ExportImage exports an image (as a tar file) into the stream. // // See https://goo.gl/le7vK8 for more details. func (c *Client) ExportImage(opts ExportImageOptions) error { return c.stream("GET", fmt.Sprintf("/images/%s/get", opts.Name), streamOptions{ setRawTerminal: true, stdout: opts.OutputStream, }) } // ExportImagesOptions represent the options for ExportImages Docker API call // // See https://goo.gl/huC7HA for more details. type ExportImagesOptions struct { Names []string OutputStream io.Writer `qs:"-"` } // ExportImages exports one or more images (as a tar file) into the stream // // See https://goo.gl/huC7HA for more details. func (c *Client) ExportImages(opts ExportImagesOptions) error { if opts.Names == nil || len(opts.Names) == 0 { return ErrMustSpecifyNames } return c.stream("GET", "/images/get?"+queryString(&opts), streamOptions{ setRawTerminal: true, stdout: opts.OutputStream, }) } // ImportImageOptions present the set of informations available for importing // an image from a source file or the stdin. // // See https://goo.gl/iJkZjD for more details. type ImportImageOptions struct { Repository string `qs:"repo"` Source string `qs:"fromSrc"` Tag string `qs:"tag"` InputStream io.Reader `qs:"-"` OutputStream io.Writer `qs:"-"` RawJSONStream bool `qs:"-"` } // ImportImage imports an image from a url, a file or stdin // // See https://goo.gl/iJkZjD for more details. func (c *Client) ImportImage(opts ImportImageOptions) error { if opts.Repository == "" { return ErrNoSuchImage } if opts.Source != "-" { opts.InputStream = nil } if opts.Source != "-" && !isURL(opts.Source) { f, err := os.Open(opts.Source) if err != nil { return err } opts.InputStream = f opts.Source = "-" } return c.createImage(queryString(&opts), nil, opts.InputStream, opts.OutputStream, opts.RawJSONStream) } // BuildImageOptions present the set of informations available for building an // image from a tarfile with a Dockerfile in it. // // For more details about the Docker building process, see // http://goo.gl/tlPXPu. type BuildImageOptions struct { Name string `qs:"t"` Dockerfile string `qs:"dockerfile"` NoCache bool `qs:"nocache"` SuppressOutput bool `qs:"q"` Pull bool `qs:"pull"` RmTmpContainer bool `qs:"rm"` ForceRmTmpContainer bool `qs:"forcerm"` Memory int64 `qs:"memory"` Memswap int64 `qs:"memswap"` CPUShares int64 `qs:"cpushares"` CPUQuota int64 `qs:"cpuquota"` CPUPeriod int64 `qs:"cpuperiod"` CPUSetCPUs string `qs:"cpusetcpus"` InputStream io.Reader `qs:"-"` OutputStream io.Writer `qs:"-"` RawJSONStream bool `qs:"-"` Remote string `qs:"remote"` Auth AuthConfiguration `qs:"-"` // for older docker X-Registry-Auth header AuthConfigs AuthConfigurations `qs:"-"` // for newer docker X-Registry-Config header ContextDir string `qs:"-"` Ulimits []ULimit `qs:"-"` } // BuildImage builds an image from a tarball's url or a Dockerfile in the input // stream. // // See https://goo.gl/xySxCe for more details. func (c *Client) BuildImage(opts BuildImageOptions) error { if opts.OutputStream == nil { return ErrMissingOutputStream } headers, err := headersWithAuth(opts.Auth, c.versionedAuthConfigs(opts.AuthConfigs)) if err != nil { return err } if opts.Remote != "" && opts.Name == "" { opts.Name = opts.Remote } if opts.InputStream != nil || opts.ContextDir != "" { headers["Content-Type"] = "application/tar" } else if opts.Remote == "" { return ErrMissingRepo } if opts.ContextDir != "" { if opts.InputStream != nil { return ErrMultipleContexts } var err error if opts.InputStream, err = createTarStream(opts.ContextDir, opts.Dockerfile); err != nil { return err } } qs := queryString(&opts) if len(opts.Ulimits) > 0 { if b, err := json.Marshal(opts.Ulimits); err == nil { item := url.Values(map[string][]string{}) item.Add("ulimits", string(b)) qs = fmt.Sprintf("%s&%s", qs, item.Encode()) } } return c.stream("POST", fmt.Sprintf("/build?%s", qs), streamOptions{ setRawTerminal: true, rawJSONStream: opts.RawJSONStream, headers: headers, in: opts.InputStream, stdout: opts.OutputStream, }) } func (c *Client) versionedAuthConfigs(authConfigs AuthConfigurations) interface{} { if c.serverAPIVersion == nil { c.checkAPIVersion() } if c.serverAPIVersion != nil && c.serverAPIVersion.GreaterThanOrEqualTo(apiVersion119) { return AuthConfigurations119(authConfigs.Configs) } return authConfigs } // TagImageOptions present the set of options to tag an image. // // See https://goo.gl/98ZzkU for more details. type TagImageOptions struct { Repo string Tag string Force bool } // TagImage adds a tag to the image identified by the given name. // // See https://goo.gl/98ZzkU for more details. func (c *Client) TagImage(name string, opts TagImageOptions) error { if name == "" { return ErrNoSuchImage } resp, err := c.do("POST", fmt.Sprintf("/images/"+name+"/tag?%s", queryString(&opts)), doOptions{}) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode == http.StatusNotFound { return ErrNoSuchImage } return err } func isURL(u string) bool { p, err := url.Parse(u) if err != nil { return false } return p.Scheme == "http" || p.Scheme == "https" } func headersWithAuth(auths ...interface{}) (map[string]string, error) { var headers = make(map[string]string) for _, auth := range auths { switch auth.(type) { case AuthConfiguration: var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(auth); err != nil { return nil, err } headers["X-Registry-Auth"] = base64.URLEncoding.EncodeToString(buf.Bytes()) case AuthConfigurations, AuthConfigurations119: var buf bytes.Buffer if err := json.NewEncoder(&buf).Encode(auth); err != nil { return nil, err } headers["X-Registry-Config"] = base64.URLEncoding.EncodeToString(buf.Bytes()) } } return headers, nil } // APIImageSearch reflect the result of a search on the Docker Hub. // // See https://goo.gl/AYjyrF for more details. type APIImageSearch struct { Description string `json:"description,omitempty" yaml:"description,omitempty"` IsOfficial bool `json:"is_official,omitempty" yaml:"is_official,omitempty"` IsAutomated bool `json:"is_automated,omitempty" yaml:"is_automated,omitempty"` Name string `json:"name,omitempty" yaml:"name,omitempty"` StarCount int `json:"star_count,omitempty" yaml:"star_count,omitempty"` } // SearchImages search the docker hub with a specific given term. // // See https://goo.gl/AYjyrF for more details. func (c *Client) SearchImages(term string) ([]APIImageSearch, error) { resp, err := c.do("GET", "/images/search?term="+term, doOptions{}) defer resp.Body.Close() if err != nil { return nil, err } var searchResult []APIImageSearch if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { return nil, err } return searchResult, nil } // SearchImagesEx search the docker hub with a specific given term and authentication. // // See https://goo.gl/AYjyrF for more details. func (c *Client) SearchImagesEx(term string, auth AuthConfiguration) ([]APIImageSearch, error) { headers, err := headersWithAuth(auth) if err != nil { return nil, err } resp, err := c.do("GET", "/images/search?term="+term, doOptions{ headers: headers, }) if err != nil { return nil, err } defer resp.Body.Close() var searchResult []APIImageSearch if err := json.NewDecoder(resp.Body).Decode(&searchResult); err != nil { return nil, err } return searchResult, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/image_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "bytes" "encoding/base64" "encoding/json" "io/ioutil" "net" "net/http" "net/url" "os" "reflect" "strings" "testing" "time" ) func newTestClient(rt *FakeRoundTripper) Client { endpoint := "http://localhost:4243" u, _ := parseEndpoint("http://localhost:4243", false) testAPIVersion, _ := NewAPIVersion("1.17") client := Client{ HTTPClient: &http.Client{Transport: rt}, Dialer: &net.Dialer{}, endpoint: endpoint, endpointURL: u, SkipServerVersionCheck: true, serverAPIVersion: testAPIVersion, } return client } type stdoutMock struct { *bytes.Buffer } func (m stdoutMock) Close() error { return nil } type stdinMock struct { *bytes.Buffer } func (m stdinMock) Close() error { return nil } func TestListImages(t *testing.T) { body := `[ { "Repository":"base", "Tag":"ubuntu-12.10", "Id":"b750fe79269d", "Created":1364102658 }, { "Repository":"base", "Tag":"ubuntu-quantal", "Id":"b750fe79269d", "Created":1364102658 }, { "RepoTag": [ "ubuntu:12.04", "ubuntu:precise", "ubuntu:latest" ], "Id": "8dbd9e392a964c", "Created": 1365714795, "Size": 131506275, "VirtualSize": 131506275 }, { "RepoTag": [ "ubuntu:12.10", "ubuntu:quantal" ], "ParentId": "27cf784147099545", "Id": "b750fe79269d2e", "Created": 1364102658, "Size": 24653, "VirtualSize": 180116135 } ]` var expected []APIImages err := json.Unmarshal([]byte(body), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) images, err := client.ListImages(ListImagesOptions{}) if err != nil { t.Error(err) } if !reflect.DeepEqual(images, expected) { t.Errorf("ListImages: Wrong return value. Want %#v. Got %#v.", expected, images) } } func TestListImagesParameters(t *testing.T) { fakeRT := &FakeRoundTripper{message: "null", status: http.StatusOK} client := newTestClient(fakeRT) _, err := client.ListImages(ListImagesOptions{All: false}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("ListImages({All: false}: Wrong HTTP method. Want GET. Got %s.", req.Method) } if all := req.URL.Query().Get("all"); all != "0" && all != "" { t.Errorf("ListImages({All: false}): Wrong parameter. Want all=0 or not present at all. Got all=%s", all) } fakeRT.Reset() _, err = client.ListImages(ListImagesOptions{All: true}) if err != nil { t.Fatal(err) } req = fakeRT.requests[0] if all := req.URL.Query().Get("all"); all != "1" { t.Errorf("ListImages({All: true}): Wrong parameter. Want all=1. Got all=%s", all) } fakeRT.Reset() _, err = client.ListImages(ListImagesOptions{Filters: map[string][]string{ "dangling": {"true"}, }}) if err != nil { t.Fatal(err) } req = fakeRT.requests[0] body := req.URL.Query().Get("filters") var filters map[string][]string err = json.Unmarshal([]byte(body), &filters) if err != nil { t.Fatal(err) } if len(filters["dangling"]) != 1 || filters["dangling"][0] != "true" { t.Errorf("ListImages(dangling=[true]): Wrong filter map. Want dangling=[true], got dangling=%v", filters["dangling"]) } } func TestImageHistory(t *testing.T) { body := `[ { "Id": "25daec02219d2d852f7526137213a9b199926b4b24e732eab5b8bc6c49bd470e", "Tags": [ "debian:7.6", "debian:latest", "debian:7", "debian:wheezy" ], "Created": 1409856216, "CreatedBy": "/bin/sh -c #(nop) CMD [/bin/bash]" }, { "Id": "41026a5347fb5be6ed16115bf22df8569697139f246186de9ae8d4f67c335dce", "Created": 1409856213, "CreatedBy": "/bin/sh -c #(nop) ADD file:1ee9e97209d00e3416a4543b23574cc7259684741a46bbcbc755909b8a053a38 in /", "Size": 85178663 }, { "Id": "511136ea3c5a64f264b78b5433614aec563103b4d4702f3ba7d4d2698e22c158", "Tags": [ "scratch:latest" ], "Created": 1371157430 } ]` var expected []ImageHistory err := json.Unmarshal([]byte(body), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) history, err := client.ImageHistory("debian:latest") if err != nil { t.Error(err) } if !reflect.DeepEqual(history, expected) { t.Errorf("ImageHistory: Wrong return value. Want %#v. Got %#v.", expected, history) } } func TestRemoveImage(t *testing.T) { name := "test" fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) err := client.RemoveImage(name) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedMethod := "DELETE" if req.Method != expectedMethod { t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/images/" + name)) if req.URL.Path != u.Path { t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) } } func TestRemoveImageNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound}) err := client.RemoveImage("test:") if err != ErrNoSuchImage { t.Errorf("RemoveImage: wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) } } func TestRemoveImageExtended(t *testing.T) { name := "test" fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) err := client.RemoveImageExtended(name, RemoveImageOptions{Force: true, NoPrune: true}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedMethod := "DELETE" if req.Method != expectedMethod { t.Errorf("RemoveImage(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/images/" + name)) if req.URL.Path != u.Path { t.Errorf("RemoveImage(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) } expectedQuery := "force=1&noprune=1" if query := req.URL.Query().Encode(); query != expectedQuery { t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query) } } func TestInspectImage(t *testing.T) { body := `{ "Id":"b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", "Parent":"27cf784147099545", "Created":"2013-03-23T22:24:18.818426Z", "Container":"3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", "ContainerConfig":{"Memory":1}, "VirtualSize":12345 }` created, err := time.Parse(time.RFC3339Nano, "2013-03-23T22:24:18.818426Z") if err != nil { t.Fatal(err) } expected := Image{ ID: "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", Parent: "27cf784147099545", Created: created, Container: "3d67245a8d72ecf13f33dffac9f79dcdf70f75acb84d308770391510e0c23ad0", ContainerConfig: Config{ Memory: 1, }, VirtualSize: 12345, } fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} client := newTestClient(fakeRT) image, err := client.InspectImage(expected.ID) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(*image, expected) { t.Errorf("InspectImage(%q): Wrong image returned. Want %#v. Got %#v.", expected.ID, expected, *image) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("InspectImage(%q): Wrong HTTP method. Want GET. Got %s.", expected.ID, req.Method) } u, _ := url.Parse(client.getURL("/images/" + expected.ID + "/json")) if req.URL.Path != u.Path { t.Errorf("InspectImage(%q): Wrong request URL. Want %q. Got %q.", expected.ID, u.Path, req.URL.Path) } } func TestInspectImageNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such image", status: http.StatusNotFound}) name := "test" image, err := client.InspectImage(name) if image != nil { t.Errorf("InspectImage(%q): expected image, got %#v.", name, image) } if err != ErrNoSuchImage { t.Errorf("InspectImage(%q): wrong error. Want %#v. Got %#v.", name, ErrNoSuchImage, err) } } func TestPushImage(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, AuthConfiguration{}) if err != nil { t.Fatal(err) } expected := "Pushing 1/100" if buf.String() != expected { t.Errorf("PushImage: Wrong output. Want %q. Got %q.", expected, buf.String()) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("PushImage: Wrong HTTP method. Want POST. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/images/test/push")) if req.URL.Path != u.Path { t.Errorf("PushImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) } if query := req.URL.Query().Encode(); query != "" { t.Errorf("PushImage: Wrong query string. Want no parameters, got %q.", query) } auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth")) if err != nil { t.Errorf("PushImage: caught error decoding auth. %#v", err.Error()) } if strings.TrimSpace(string(auth)) != "{}" { t.Errorf("PushImage: wrong body. Want %q. Got %q.", base64.URLEncoding.EncodeToString([]byte("{}")), req.Header.Get("X-Registry-Auth")) } } func TestPushImageWithRawJSON(t *testing.T) { body := ` {"status":"Pushing..."} {"status":"Pushing", "progress":"1/? (n/a)", "progressDetail":{"current":1}}} {"status":"Image successfully pushed"} ` fakeRT := &FakeRoundTripper{ message: body, status: http.StatusOK, header: map[string]string{ "Content-Type": "application/json", }, } client := newTestClient(fakeRT) var buf bytes.Buffer err := client.PushImage(PushImageOptions{ Name: "test", OutputStream: &buf, RawJSONStream: true, }, AuthConfiguration{}) if err != nil { t.Fatal(err) } if buf.String() != body { t.Errorf("PushImage: Wrong raw output. Want %q. Got %q.", body, buf.String()) } } func TestPushImageWithAuthentication(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer inputAuth := AuthConfiguration{ Username: "gopher", Password: "gopher123", Email: "gopher@tsuru.io", } err := client.PushImage(PushImageOptions{Name: "test", OutputStream: &buf}, inputAuth) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] var gotAuth AuthConfiguration auth, err := base64.URLEncoding.DecodeString(req.Header.Get("X-Registry-Auth")) if err != nil { t.Errorf("PushImage: caught error decoding auth. %#v", err.Error()) } err = json.Unmarshal(auth, &gotAuth) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(gotAuth, inputAuth) { t.Errorf("PushImage: wrong auth configuration. Want %#v. Got %#v.", inputAuth, gotAuth) } } func TestPushImageCustomRegistry(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pushing 1/100", status: http.StatusOK} client := newTestClient(fakeRT) var authConfig AuthConfiguration var buf bytes.Buffer opts := PushImageOptions{ Name: "test", Registry: "docker.tsuru.io", OutputStream: &buf, } err := client.PushImage(opts, authConfig) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedQuery := "registry=docker.tsuru.io" if query := req.URL.Query().Encode(); query != expectedQuery { t.Errorf("PushImage: Wrong query string. Want %q. Got %q.", expectedQuery, query) } } func TestPushImageNoName(t *testing.T) { client := Client{} err := client.PushImage(PushImageOptions{}, AuthConfiguration{}) if err != ErrNoSuchImage { t.Errorf("PushImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) } } func TestPullImage(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer err := client.PullImage(PullImageOptions{Repository: "base", OutputStream: &buf}, AuthConfiguration{}) if err != nil { t.Fatal(err) } expected := "Pulling 1/100" if buf.String() != expected { t.Errorf("PullImage: Wrong output. Want %q. Got %q.", expected, buf.String()) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("PullImage: Wrong HTTP method. Want POST. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/images/create")) if req.URL.Path != u.Path { t.Errorf("PullImage: Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) } expectedQuery := "fromImage=base" if query := req.URL.Query().Encode(); query != expectedQuery { t.Errorf("PullImage: Wrong query strin. Want %q. Got %q.", expectedQuery, query) } } func TestPullImageWithRawJSON(t *testing.T) { body := ` {"status":"Pulling..."} {"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}} ` fakeRT := &FakeRoundTripper{ message: body, status: http.StatusOK, header: map[string]string{ "Content-Type": "application/json", }, } client := newTestClient(fakeRT) var buf bytes.Buffer err := client.PullImage(PullImageOptions{ Repository: "base", OutputStream: &buf, RawJSONStream: true, }, AuthConfiguration{}) if err != nil { t.Fatal(err) } if buf.String() != body { t.Errorf("PullImage: Wrong raw output. Want %q. Got %q", body, buf.String()) } } func TestPullImageWithoutOutputStream(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} client := newTestClient(fakeRT) opts := PullImageOptions{ Repository: "base", Registry: "docker.tsuru.io", } err := client.PullImage(opts, AuthConfiguration{}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestPullImageCustomRegistry(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := PullImageOptions{ Repository: "base", Registry: "docker.tsuru.io", OutputStream: &buf, } err := client.PullImage(opts, AuthConfiguration{}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestPullImageTag(t *testing.T) { fakeRT := &FakeRoundTripper{message: "Pulling 1/100", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := PullImageOptions{ Repository: "base", Registry: "docker.tsuru.io", Tag: "latest", OutputStream: &buf, } err := client.PullImage(opts, AuthConfiguration{}) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromImage": {"base"}, "registry": {"docker.tsuru.io"}, "tag": {"latest"}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("PullImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestPullImageNoRepository(t *testing.T) { var opts PullImageOptions client := Client{} err := client.PullImage(opts, AuthConfiguration{}) if err != ErrNoSuchImage { t.Errorf("PullImage: got wrong error. Want %#v. Got %#v.", ErrNoSuchImage, err) } } func TestImportImageFromUrl(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := ImportImageOptions{ Source: "http://mycompany.com/file.tar", Repository: "testimage", Tag: "tag", OutputStream: &buf, } err := client.ImportImage(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestImportImageFromInput(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) in := bytes.NewBufferString("tar content") var buf bytes.Buffer opts := ImportImageOptions{ Source: "-", Repository: "testimage", InputStream: in, OutputStream: &buf, Tag: "tag", } err := client.ImportImage(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}, "tag": {opts.Tag}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) } body, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("ImportImage: caugth error while reading body %#v", err.Error()) } e := "tar content" if string(body) != e { t.Errorf("ImportImage: wrong body. Want %#v. Got %#v.", e, string(body)) } } func TestImportImageDoesNotPassesInputIfSourceIsNotDash(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer in := bytes.NewBufferString("foo") opts := ImportImageOptions{ Source: "http://test.com/container.tar", Repository: "testimage", InputStream: in, OutputStream: &buf, } err := client.ImportImage(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromSrc": {opts.Source}, "repo": {opts.Repository}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) } body, err := ioutil.ReadAll(req.Body) if err != nil { t.Errorf("ImportImage: caugth error while reading body %#v", err.Error()) } if string(body) != "" { t.Errorf("ImportImage: wrong body. Want nothing. Got %#v.", string(body)) } } func TestImportImageShouldPassTarContentToBodyWhenSourceIsFilePath(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer tarPath := "testing/data/container.tar" opts := ImportImageOptions{ Source: tarPath, Repository: "testimage", OutputStream: &buf, } err := client.ImportImage(opts) if err != nil { t.Fatal(err) } tar, err := os.Open(tarPath) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] tarContent, err := ioutil.ReadAll(tar) body, err := ioutil.ReadAll(req.Body) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(tarContent, body) { t.Errorf("ImportImage: wrong body. Want %#v content. Got %#v.", tarPath, body) } } func TestImportImageShouldChangeSourceToDashWhenItsAFilePath(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer tarPath := "testing/data/container.tar" opts := ImportImageOptions{ Source: tarPath, Repository: "testimage", OutputStream: &buf, } err := client.ImportImage(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"fromSrc": {"-"}, "repo": {opts.Repository}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("ImportImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestBuildImageParameters(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", NoCache: true, SuppressOutput: true, Pull: true, RmTmpContainer: true, ForceRmTmpContainer: true, Memory: 1024, Memswap: 2048, CPUShares: 10, CPUQuota: 7500, CPUPeriod: 100000, CPUSetCPUs: "0-3", Ulimits: []ULimit{{Name: "nofile", Soft: 100, Hard: 200}}, InputStream: &buf, OutputStream: &buf, } err := client.BuildImage(opts) if err != nil && strings.Index(err.Error(), "build image fail") == -1 { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{ "t": {opts.Name}, "nocache": {"1"}, "q": {"1"}, "pull": {"1"}, "rm": {"1"}, "forcerm": {"1"}, "memory": {"1024"}, "memswap": {"2048"}, "cpushares": {"10"}, "cpuquota": {"7500"}, "cpuperiod": {"100000"}, "cpusetcpus": {"0-3"}, "ulimits": {"[{\"Name\":\"nofile\",\"Soft\":100,\"Hard\":200}]"}, } got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestBuildImageParametersForRemoteBuild(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", Remote: "testing/data/container.tar", SuppressOutput: true, OutputStream: &buf, } err := client.BuildImage(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"t": {opts.Name}, "remote": {opts.Remote}, "q": {"1"}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestBuildImageMissingRepoAndNilInput(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", SuppressOutput: true, OutputStream: &buf, } err := client.BuildImage(opts) if err != ErrMissingRepo { t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingRepo, err) } } func TestBuildImageMissingOutputStream(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := BuildImageOptions{Name: "testImage"} err := client.BuildImage(opts) if err != ErrMissingOutputStream { t.Errorf("BuildImage: wrong error returned. Want %#v. Got %#v.", ErrMissingOutputStream, err) } } func TestBuildImageWithRawJSON(t *testing.T) { body := ` {"stream":"Step 0 : FROM ubuntu:latest\n"} {"stream":" ---\u003e 4300eb9d3c8d\n"} {"stream":"Step 1 : MAINTAINER docker \n"} {"stream":" ---\u003e Using cache\n"} {"stream":" ---\u003e 3a3ed758c370\n"} {"stream":"Step 2 : CMD /usr/bin/top\n"} {"stream":" ---\u003e Running in 36b1479cc2e4\n"} {"stream":" ---\u003e 4b6188aebe39\n"} {"stream":"Removing intermediate container 36b1479cc2e4\n"} {"stream":"Successfully built 4b6188aebe39\n"} ` fakeRT := &FakeRoundTripper{ message: body, status: http.StatusOK, header: map[string]string{ "Content-Type": "application/json", }, } client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Name: "testImage", RmTmpContainer: true, InputStream: &buf, OutputStream: &buf, RawJSONStream: true, } err := client.BuildImage(opts) if err != nil { t.Fatal(err) } if buf.String() != body { t.Errorf("BuildImage: Wrong raw output. Want %q. Got %q.", body, buf.String()) } } func TestBuildImageRemoteWithoutName(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) var buf bytes.Buffer opts := BuildImageOptions{ Remote: "testing/data/container.tar", SuppressOutput: true, OutputStream: &buf, } err := client.BuildImage(opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expected := map[string][]string{"t": {opts.Remote}, "remote": {opts.Remote}, "q": {"1"}} got := map[string][]string(req.URL.Query()) if !reflect.DeepEqual(got, expected) { t.Errorf("BuildImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestTagImageParameters(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := TagImageOptions{Repo: "testImage"} err := client.TagImage("base", opts) if err != nil && strings.Index(err.Error(), "tag image fail") == -1 { t.Fatal(err) } req := fakeRT.requests[0] expected := "http://localhost:4243/images/base/tag?repo=testImage" got := req.URL.String() if !reflect.DeepEqual(got, expected) { t.Errorf("TagImage: wrong query string. Want %#v. Got %#v.", expected, got) } } func TestTagImageMissingRepo(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := TagImageOptions{Repo: "testImage"} err := client.TagImage("", opts) if err != ErrNoSuchImage { t.Errorf("TestTag: wrong error returned. Want %#v. Got %#v.", ErrNoSuchImage, err) } } func TestIsUrl(t *testing.T) { url := "http://foo.bar/" result := isURL(url) if !result { t.Errorf("isURL: wrong match. Expected %#v to be a url. Got %#v.", url, result) } url = "/foo/bar.tar" result = isURL(url) if result { t.Errorf("isURL: wrong match. Expected %#v to not be a url. Got %#v", url, result) } } func TestLoadImage(t *testing.T) { fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) tar, err := os.Open("testing/data/container.tar") if err != nil { t.Fatal(err) } else { defer tar.Close() } opts := LoadImageOptions{InputStream: tar} err = client.LoadImage(opts) if nil != err { t.Error(err) } req := fakeRT.requests[0] if req.Method != "POST" { t.Errorf("LoadImage: wrong method. Expected %q. Got %q.", "POST", req.Method) } if req.URL.Path != "/images/load" { t.Errorf("LoadImage: wrong URL. Expected %q. Got %q.", "/images/load", req.URL.Path) } } func TestExportImage(t *testing.T) { var buf bytes.Buffer fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := ExportImageOptions{Name: "testimage", OutputStream: &buf} err := client.ExportImage(opts) if nil != err { t.Error(err) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method) } expectedPath := "/images/testimage/get" if req.URL.Path != expectedPath { t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expectedPath, req.URL.Path) } } func TestExportImages(t *testing.T) { var buf bytes.Buffer fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := ExportImagesOptions{Names: []string{"testimage1", "testimage2:latest"}, OutputStream: &buf} err := client.ExportImages(opts) if nil != err { t.Error(err) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("ExportImage: wrong method. Expected %q. Got %q.", "GET", req.Method) } expected := "http://localhost:4243/images/get?names=testimage1&names=testimage2%3Alatest" got := req.URL.String() if !reflect.DeepEqual(got, expected) { t.Errorf("ExportIMage: wrong path. Expected %q. Got %q.", expected, got) } } func TestExportImagesNoNames(t *testing.T) { var buf bytes.Buffer fakeRT := &FakeRoundTripper{message: "", status: http.StatusOK} client := newTestClient(fakeRT) opts := ExportImagesOptions{Names: []string{}, OutputStream: &buf} err := client.ExportImages(opts) if err == nil { t.Error("Expected an error") } if err != ErrMustSpecifyNames { t.Error(err) } } func TestSearchImages(t *testing.T) { body := `[ { "description":"A container with Cassandra 2.0.3", "is_official":true, "is_automated":true, "name":"poklet/cassandra", "star_count":17 }, { "description":"A container with Cassandra 2.0.3", "is_official":true, "is_automated":false, "name":"poklet/cassandra", "star_count":17 } , { "description":"A container with Cassandra 2.0.3", "is_official":false, "is_automated":true, "name":"poklet/cassandra", "star_count":17 } ]` var expected []APIImageSearch err := json.Unmarshal([]byte(body), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) result, err := client.SearchImages("cassandra") if err != nil { t.Error(err) } if !reflect.DeepEqual(result, expected) { t.Errorf("SearchImages: Wrong return value. Want %#v. Got %#v.", expected, result) } } func TestSearchImagesEx(t *testing.T) { body := `[ { "description":"A container with Cassandra 2.0.3", "is_official":true, "is_automated":true, "name":"poklet/cassandra", "star_count":17 }, { "description":"A container with Cassandra 2.0.3", "is_official":true, "is_automated":false, "name":"poklet/cassandra", "star_count":17 } , { "description":"A container with Cassandra 2.0.3", "is_official":false, "is_automated":true, "name":"poklet/cassandra", "star_count":17 } ]` var expected []APIImageSearch err := json.Unmarshal([]byte(body), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) auth := AuthConfiguration{} result, err := client.SearchImagesEx("cassandra", auth) if err != nil { t.Error(err) } if !reflect.DeepEqual(result, expected) { t.Errorf("SearchImages: Wrong return value. Want %#v. Got %#v.", expected, result) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/integration_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker_integration package docker import ( "bytes" "os" "testing" ) var dockerEndpoint string func init() { dockerEndpoint = os.Getenv("DOCKER_HOST") if dockerEndpoint == "" { dockerEndpoint = "unix:///var/run/docker.sock" } } func TestIntegrationPullCreateStartLogs(t *testing.T) { imageName := pullImage(t) client := getClient() hostConfig := HostConfig{PublishAllPorts: true} createOpts := CreateContainerOptions{ Config: &Config{ Image: imageName, Cmd: []string{"cat", "/home/gopher/file.txt"}, User: "gopher", }, HostConfig: &hostConfig, } container, err := client.CreateContainer(createOpts) if err != nil { t.Fatal(err) } err = client.StartContainer(container.ID, &hostConfig) if err != nil { t.Fatal(err) } status, err := client.WaitContainer(container.ID) if err != nil { t.Error(err) } if status != 0 { t.Error("WaitContainer(%q): wrong status. Want 0. Got %d", container.ID, status) } var stdout, stderr bytes.Buffer logsOpts := LogsOptions{ Container: container.ID, OutputStream: &stdout, ErrorStream: &stderr, Stdout: true, Stderr: true, } err = client.Logs(logsOpts) if err != nil { t.Error(err) } if stderr.String() != "" { t.Errorf("Got unexpected stderr from logs: %q", stderr.String()) } expected := `Welcome to reality, wake up and rejoice Welcome to reality, you've made the right choice Welcome to reality, and let them hear your voice, shout it out! ` if stdout.String() != expected { t.Errorf("Got wrong stdout from logs.\nWant:\n%#v.\n\nGot:\n%#v.", expected, stdout.String()) } } func pullImage(t *testing.T) string { imageName := "fsouza/go-dockerclient-integration" var buf bytes.Buffer pullOpts := PullImageOptions{ Repository: imageName, OutputStream: &buf, } client := getClient() err := client.PullImage(pullOpts, AuthConfiguration{}) if err != nil { t.Logf("Pull output: %s", buf.String()) t.Fatal(err) } return imageName } func getClient() *Client { client, _ := NewClient(dockerEndpoint) return client } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/misc.go ================================================ // Copyright 2015 go-dockerclient 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 docker import "strings" // Version returns version information about the docker server. // // See https://goo.gl/ND9R8L for more details. func (c *Client) Version() (*Env, error) { resp, err := c.do("GET", "/version", doOptions{}) if err != nil { return nil, err } defer resp.Body.Close() var env Env if err := env.Decode(resp.Body); err != nil { return nil, err } return &env, nil } // Info returns system-wide information about the Docker server. // // See https://goo.gl/ElTHi2 for more details. func (c *Client) Info() (*Env, error) { resp, err := c.do("GET", "/info", doOptions{}) if err != nil { return nil, err } defer resp.Body.Close() var info Env if err := info.Decode(resp.Body); err != nil { return nil, err } return &info, nil } // ParseRepositoryTag gets the name of the repository and returns it splitted // in two parts: the repository and the tag. // // Some examples: // // localhost.localdomain:5000/samalba/hipache:latest -> localhost.localdomain:5000/samalba/hipache, latest // localhost.localdomain:5000/samalba/hipache -> localhost.localdomain:5000/samalba/hipache, "" func ParseRepositoryTag(repoTag string) (repository string, tag string) { n := strings.LastIndex(repoTag, ":") if n < 0 { return repoTag, "" } if tag := repoTag[n+1:]; !strings.Contains(tag, "/") { return repoTag[:n], tag } return repoTag, "" } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/misc_test.go ================================================ // Copyright 2014 go-dockerclient 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 docker import ( "net/http" "net/url" "reflect" "sort" "testing" ) type DockerVersion struct { Version string GitCommit string GoVersion string } func TestVersion(t *testing.T) { body := `{ "Version":"0.2.2", "GitCommit":"5a2a5cc+CHANGES", "GoVersion":"go1.0.3" }` fakeRT := FakeRoundTripper{message: body, status: http.StatusOK} client := newTestClient(&fakeRT) expected := DockerVersion{ Version: "0.2.2", GitCommit: "5a2a5cc+CHANGES", GoVersion: "go1.0.3", } version, err := client.Version() if err != nil { t.Fatal(err) } if result := version.Get("Version"); result != expected.Version { t.Errorf("Version(): Wrong result. Want %#v. Got %#v.", expected.Version, version.Get("Version")) } if result := version.Get("GitCommit"); result != expected.GitCommit { t.Errorf("GitCommit(): Wrong result. Want %#v. Got %#v.", expected.GitCommit, version.Get("GitCommit")) } if result := version.Get("GoVersion"); result != expected.GoVersion { t.Errorf("GoVersion(): Wrong result. Want %#v. Got %#v.", expected.GoVersion, version.Get("GoVersion")) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("Version(): wrong request method. Want GET. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/version")) if req.URL.Path != u.Path { t.Errorf("Version(): wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) } } func TestVersionError(t *testing.T) { fakeRT := &FakeRoundTripper{message: "internal error", status: http.StatusInternalServerError} client := newTestClient(fakeRT) version, err := client.Version() if version != nil { t.Errorf("Version(): expected value, got %#v.", version) } if err == nil { t.Error("Version(): unexpected error") } } func TestInfo(t *testing.T) { body := `{ "Containers":11, "Images":16, "Debug":0, "NFd":11, "NGoroutines":21, "MemoryLimit":1, "SwapLimit":0 }` fakeRT := FakeRoundTripper{message: body, status: http.StatusOK} client := newTestClient(&fakeRT) expected := Env{} expected.SetInt("Containers", 11) expected.SetInt("Images", 16) expected.SetBool("Debug", false) expected.SetInt("NFd", 11) expected.SetInt("NGoroutines", 21) expected.SetBool("MemoryLimit", true) expected.SetBool("SwapLimit", false) info, err := client.Info() if err != nil { t.Fatal(err) } infoSlice := []string(*info) expectedSlice := []string(expected) sort.Strings(infoSlice) sort.Strings(expectedSlice) if !reflect.DeepEqual(expectedSlice, infoSlice) { t.Errorf("Info(): Wrong result.\nWant %#v.\nGot %#v.", expected, *info) } req := fakeRT.requests[0] if req.Method != "GET" { t.Errorf("Info(): Wrong HTTP method. Want GET. Got %s.", req.Method) } u, _ := url.Parse(client.getURL("/info")) if req.URL.Path != u.Path { t.Errorf("Info(): Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) } } func TestInfoError(t *testing.T) { fakeRT := &FakeRoundTripper{message: "internal error", status: http.StatusInternalServerError} client := newTestClient(fakeRT) version, err := client.Info() if version != nil { t.Errorf("Info(): expected value, got %#v.", version) } if err == nil { t.Error("Info(): unexpected error") } } func TestParseRepositoryTag(t *testing.T) { var tests = []struct { input string expectedRepo string expectedTag string }{ { "localhost.localdomain:5000/samalba/hipache:latest", "localhost.localdomain:5000/samalba/hipache", "latest", }, { "localhost.localdomain:5000/samalba/hipache", "localhost.localdomain:5000/samalba/hipache", "", }, { "tsuru/python", "tsuru/python", "", }, { "tsuru/python:2.7", "tsuru/python", "2.7", }, } for _, tt := range tests { repo, tag := ParseRepositoryTag(tt.input) if repo != tt.expectedRepo { t.Errorf("ParseRepositoryTag(%q): wrong repository. Want %q. Got %q", tt.input, tt.expectedRepo, repo) } if tag != tt.expectedTag { t.Errorf("ParseRepositoryTag(%q): wrong tag. Want %q. Got %q", tt.input, tt.expectedTag, tag) } } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/network.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "errors" "fmt" "net/http" ) // ErrNetworkAlreadyExists is the error returned by CreateNetwork when the // network already exists. var ErrNetworkAlreadyExists = errors.New("network already exists") // Network represents a network. // // See https://goo.gl/6GugX3 for more details. type Network struct { Name string ID string `json:"Id"` Scope string Driver string IPAM IPAMOptions Containers map[string]Endpoint Options map[string]string } // Endpoint contains network resources allocated and used for a container in a network // // See https://goo.gl/6GugX3 for more details. type Endpoint struct { Name string ID string `json:"EndpointID"` MacAddress string IPv4Address string IPv6Address string } // ListNetworks returns all networks. // // See https://goo.gl/6GugX3 for more details. func (c *Client) ListNetworks() ([]Network, error) { resp, err := c.do("GET", "/networks", doOptions{}) if err != nil { return nil, err } defer resp.Body.Close() var networks []Network if err := json.NewDecoder(resp.Body).Decode(&networks); err != nil { return nil, err } return networks, nil } // NetworkInfo returns information about a network by its ID. // // See https://goo.gl/6GugX3 for more details. func (c *Client) NetworkInfo(id string) (*Network, error) { path := "/networks/" + id resp, err := c.do("GET", path, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, &NoSuchNetwork{ID: id} } return nil, err } defer resp.Body.Close() var network Network if err := json.NewDecoder(resp.Body).Decode(&network); err != nil { return nil, err } return &network, nil } // CreateNetworkOptions specify parameters to the CreateNetwork function and // (for now) is the expected body of the "create network" http request message // // See https://goo.gl/6GugX3 for more details. type CreateNetworkOptions struct { Name string `json:"Name"` CheckDuplicate bool `json:"CheckDuplicate"` Driver string `json:"Driver"` IPAM IPAMOptions `json:"IPAM"` Options map[string]interface{} `json:"options"` } // IPAMOptions controls IP Address Management when creating a network // // See https://goo.gl/T8kRVH for more details. type IPAMOptions struct { Driver string `json:"Driver"` Config []IPAMConfig `json:"IPAMConfig"` } // IPAMConfig represents IPAM configurations // // See https://goo.gl/T8kRVH for more details. type IPAMConfig struct { Subnet string `json:",omitempty"` IPRange string `json:",omitempty"` Gateway string `json:",omitempty"` AuxAddress map[string]string `json:"AuxiliaryAddresses,omitempty"` } // CreateNetwork creates a new network, returning the network instance, // or an error in case of failure. // // See https://goo.gl/6GugX3 for more details. func (c *Client) CreateNetwork(opts CreateNetworkOptions) (*Network, error) { resp, err := c.do( "POST", "/networks/create", doOptions{ data: opts, }, ) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusConflict { return nil, ErrNetworkAlreadyExists } return nil, err } defer resp.Body.Close() type createNetworkResponse struct { ID string } var ( network Network cnr createNetworkResponse ) if err := json.NewDecoder(resp.Body).Decode(&cnr); err != nil { return nil, err } network.Name = opts.Name network.ID = cnr.ID network.Driver = opts.Driver return &network, nil } // RemoveNetwork removes a network or returns an error in case of failure. // // See https://goo.gl/6GugX3 for more details. func (c *Client) RemoveNetwork(id string) error { resp, err := c.do("DELETE", "/networks/"+id, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchNetwork{ID: id} } return err } resp.Body.Close() return nil } // NetworkConnectionOptions specify parameters to the ConnectNetwork and DisconnectNetwork function. // // See https://goo.gl/6GugX3 for more details. type NetworkConnectionOptions struct { Container string } // ConnectNetwork adds a container to a network or returns an error in case of failure. // // See https://goo.gl/6GugX3 for more details. func (c *Client) ConnectNetwork(id string, opts NetworkConnectionOptions) error { resp, err := c.do("POST", "/networks/"+id+"/connect", doOptions{data: opts}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchNetworkOrContainer{NetworkID: id, ContainerID: opts.Container} } return err } resp.Body.Close() return nil } // DisconnectNetwork removes a container from a network or returns an error in case of failure. // // See https://goo.gl/6GugX3 for more details. func (c *Client) DisconnectNetwork(id string, opts NetworkConnectionOptions) error { resp, err := c.do("POST", "/networks/"+id+"/disconnect", doOptions{data: opts}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return &NoSuchNetworkOrContainer{NetworkID: id, ContainerID: opts.Container} } return err } resp.Body.Close() return nil } // NoSuchNetwork is the error returned when a given network does not exist. type NoSuchNetwork struct { ID string } func (err *NoSuchNetwork) Error() string { return fmt.Sprintf("No such network: %s", err.ID) } // NoSuchNetwork is the error returned when a given network or container does not exist. type NoSuchNetworkOrContainer struct { NetworkID string ContainerID string } func (err *NoSuchNetworkOrContainer) Error() string { return fmt.Sprintf("No such network (%s) or container (%s)", err.NetworkID, err.ContainerID) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/network_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "net/http" "net/url" "reflect" "testing" ) func TestListNetworks(t *testing.T) { jsonNetworks := `[ { "ID": "8dfafdbc3a40", "Name": "blah", "Type": "bridge", "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}] }, { "ID": "9fb1e39c", "Name": "foo", "Type": "bridge", "Endpoints":[{"ID": "c080be979dda", "Name": "lllll2222", "Network": "9fb1e39c"}] } ]` var expected []Network err := json.Unmarshal([]byte(jsonNetworks), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: jsonNetworks, status: http.StatusOK}) containers, err := client.ListNetworks() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(containers, expected) { t.Errorf("ListNetworks: Expected %#v. Got %#v.", expected, containers) } } func TestNetworkInfo(t *testing.T) { jsonNetwork := `{ "ID": "8dfafdbc3a40", "Name": "blah", "Type": "bridge", "Endpoints":[{"ID": "918c11c8288a", "Name": "dsafdsaf", "Network": "8dfafdbc3a40"}] }` var expected Network err := json.Unmarshal([]byte(jsonNetwork), &expected) if err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: jsonNetwork, status: http.StatusOK} client := newTestClient(fakeRT) id := "8dfafdbc3a40" network, err := client.NetworkInfo(id) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(*network, expected) { t.Errorf("NetworkInfo(%q): Expected %#v. Got %#v.", id, expected, network) } expectedURL, _ := url.Parse(client.getURL("/networks/8dfafdbc3a40")) if gotPath := fakeRT.requests[0].URL.Path; gotPath != expectedURL.Path { t.Errorf("NetworkInfo(%q): Wrong path in request. Want %q. Got %q.", id, expectedURL.Path, gotPath) } } func TestNetworkCreate(t *testing.T) { jsonID := `{"ID": "8dfafdbc3a40"}` jsonNetwork := `{ "ID": "8dfafdbc3a40", "Name": "foobar", "Driver": "bridge" }` var expected Network err := json.Unmarshal([]byte(jsonNetwork), &expected) if err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: jsonID, status: http.StatusOK}) opts := CreateNetworkOptions{"foobar", false, "bridge", IPAMOptions{}, nil} network, err := client.CreateNetwork(opts) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(*network, expected) { t.Errorf("CreateNetwork: Expected %#v. Got %#v.", expected, network) } } func TestNetworkRemove(t *testing.T) { id := "8dfafdbc3a40" fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) err := client.RemoveNetwork(id) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedMethod := "DELETE" if req.Method != expectedMethod { t.Errorf("RemoveNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/networks/" + id)) if req.URL.Path != u.Path { t.Errorf("RemoveNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path) } } func TestNetworkConnect(t *testing.T) { id := "8dfafdbc3a40" fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) opts := NetworkConnectionOptions{"foobar"} err := client.ConnectNetwork(id, opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedMethod := "POST" if req.Method != expectedMethod { t.Errorf("ConnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/networks/" + id + "/connect")) if req.URL.Path != u.Path { t.Errorf("ConnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path) } } func TestNetworkConnectNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound}) opts := NetworkConnectionOptions{"foobar"} err := client.ConnectNetwork("8dfafdbc3a40", opts) if serr, ok := err.(*NoSuchNetworkOrContainer); !ok { t.Errorf("ConnectNetwork: wrong error type: %s.", serr) } } func TestNetworkDisconnect(t *testing.T) { id := "8dfafdbc3a40" fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) opts := NetworkConnectionOptions{"foobar"} err := client.DisconnectNetwork(id, opts) if err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedMethod := "POST" if req.Method != expectedMethod { t.Errorf("DisconnectNetwork(%q): Wrong HTTP method. Want %s. Got %s.", id, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/networks/" + id + "/disconnect")) if req.URL.Path != u.Path { t.Errorf("DisconnectNetwork(%q): Wrong request path. Want %q. Got %q.", id, u.Path, req.URL.Path) } } func TestNetworkDisconnectNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such network container", status: http.StatusNotFound}) opts := NetworkConnectionOptions{"foobar"} err := client.DisconnectNetwork("8dfafdbc3a40", opts) if serr, ok := err.(*NoSuchNetworkOrContainer); !ok { t.Errorf("DisconnectNetwork: wrong error type: %s.", serr) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/signal.go ================================================ // Copyright 2014 go-dockerclient 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 docker // Signal represents a signal that can be send to the container on // KillContainer call. type Signal int // These values represent all signals available on Linux, where containers will // be running. const ( SIGABRT = Signal(0x6) SIGALRM = Signal(0xe) SIGBUS = Signal(0x7) SIGCHLD = Signal(0x11) SIGCLD = Signal(0x11) SIGCONT = Signal(0x12) SIGFPE = Signal(0x8) SIGHUP = Signal(0x1) SIGILL = Signal(0x4) SIGINT = Signal(0x2) SIGIO = Signal(0x1d) SIGIOT = Signal(0x6) SIGKILL = Signal(0x9) SIGPIPE = Signal(0xd) SIGPOLL = Signal(0x1d) SIGPROF = Signal(0x1b) SIGPWR = Signal(0x1e) SIGQUIT = Signal(0x3) SIGSEGV = Signal(0xb) SIGSTKFLT = Signal(0x10) SIGSTOP = Signal(0x13) SIGSYS = Signal(0x1f) SIGTERM = Signal(0xf) SIGTRAP = Signal(0x5) SIGTSTP = Signal(0x14) SIGTTIN = Signal(0x15) SIGTTOU = Signal(0x16) SIGUNUSED = Signal(0x1f) SIGURG = Signal(0x17) SIGUSR1 = Signal(0xa) SIGUSR2 = Signal(0xc) SIGVTALRM = Signal(0x1a) SIGWINCH = Signal(0x1c) SIGXCPU = Signal(0x18) SIGXFSZ = Signal(0x19) ) ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/tar.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strings" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/archive" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/fileutils" ) func createTarStream(srcPath, dockerfilePath string) (io.ReadCloser, error) { excludes, err := parseDockerignore(srcPath) if err != nil { return nil, err } includes := []string{"."} // If .dockerignore mentions .dockerignore or the Dockerfile // then make sure we send both files over to the daemon // because Dockerfile is, obviously, needed no matter what, and // .dockerignore is needed to know if either one needs to be // removed. The deamon will remove them for us, if needed, after it // parses the Dockerfile. // // https://github.com/docker/docker/issues/8330 // forceIncludeFiles := []string{".dockerignore", dockerfilePath} for _, includeFile := range forceIncludeFiles { if includeFile == "" { continue } keepThem, err := fileutils.Matches(includeFile, excludes) if err != nil { return nil, fmt.Errorf("cannot match .dockerfile: '%s', error: %s", includeFile, err) } if keepThem { includes = append(includes, includeFile) } } if err := validateContextDirectory(srcPath, excludes); err != nil { return nil, err } tarOpts := &archive.TarOptions{ ExcludePatterns: excludes, IncludeFiles: includes, Compression: archive.Uncompressed, NoLchown: true, } return archive.TarWithOptions(srcPath, tarOpts) } // 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 { return filepath.Walk(filepath.Join(srcPath, "."), func(filePath string, f os.FileInfo, err error) error { // skip this directory/file if it's not in the path, it won't get added to the context if relFilePath, err := filepath.Rel(srcPath, 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 } if err != nil { if os.IsPermission(err) { return fmt.Errorf("can't stat '%s'", filePath) } if os.IsNotExist(err) { return nil } return err } // 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 fmt.Errorf("no permission to read from '%s'", filePath) } currentFile.Close() } return nil }) } func parseDockerignore(root string) ([]string, error) { var excludes []string ignore, err := ioutil.ReadFile(path.Join(root, ".dockerignore")) if err != nil && !os.IsNotExist(err) { return excludes, fmt.Errorf("error reading .dockerignore: '%s'", err) } excludes = strings.Split(string(ignore), "\n") return excludes, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/.dockerignore ================================================ container.tar dockerfile.tar foofile ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/Dockerfile ================================================ # this file describes how to build tsuru python image # to run it: # 1- install docker # 2- run: $ docker build -t tsuru/python https://raw.github.com/tsuru/basebuilder/master/python/Dockerfile from base:ubuntu-quantal run apt-get install wget -y --force-yes run wget http://github.com/tsuru/basebuilder/tarball/master -O basebuilder.tar.gz --no-check-certificate run mkdir /var/lib/tsuru run tar -xvf basebuilder.tar.gz -C /var/lib/tsuru --strip 1 run cp /var/lib/tsuru/python/deploy /var/lib/tsuru run cp /var/lib/tsuru/base/restart /var/lib/tsuru run cp /var/lib/tsuru/base/start /var/lib/tsuru run /var/lib/tsuru/base/install run /var/lib/tsuru/base/setup ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/barfile ================================================ ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/ca.pem ================================================ -----BEGIN CERTIFICATE----- MIIC1TCCAb+gAwIBAgIQJ9MsNxrUxumNbAytGi3GEDALBgkqhkiG9w0BAQswFjEU MBIGA1UEChMLQm9vdDJEb2NrZXIwHhcNMTQxMDE2MjAyMTM4WhcNMTcwOTMwMjAy MTM4WjAWMRQwEgYDVQQKEwtCb290MkRvY2tlcjCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBALpFCSARjG+5yXoqr7UMzuE0df7RRZfeRZI06lJ02ZqV4Iii rgL7ML9yPxX50NbLnjiilSDTUhnyocYFItokzUzz8qpX/nlYhuN2Iqwh4d0aWS8z f5y248F+H1z+HY2W8NPl/6DVlVwYaNW1/k+RPMlHS0INLR6j+3Ievew7RNE0NnM2 znELW6NetekDt3GUcz0Z95vDUDfdPnIk1eIFMmYvLxZh23xOca4Q37a3S8F3d+dN +OOpwjdgY9Qme0NQUaXpgp58jWuQfB8q7mZrdnLlLqRa8gx1HeDSotX7UmWtWPkb vd9EdlKLYw5PVpxMV1rkwf2t4TdgD5NfkpXlXkkCAwEAAaMjMCEwDgYDVR0PAQH/ BAQDAgCkMA8GA1UdEwEB/wQFMAMBAf8wCwYJKoZIhvcNAQELA4IBAQBxYjHVSKqE MJw7CW0GddesULtXXVWGJuZdWJLQlPvPMfIfjIvlcZyS4cdVNiQ3sREFIZz8TpII CT0/Pg3sgv/FcOQe1CN0xZYZcyiAZHK1z0fJQq2qVpdv7+tJcjI2vvU6NI24iQCo W1wz25trJz9QbdB2MRLMjyz7TSWuafztIvcfEzaIdQ0Whqund/cSuPGQx5IwF83F rvlkOyJSH2+VIEBTCIuykJeL0DLTt8cePBQR5L1ISXb4RUMK9ZtqRscBRv8sn7o2 ixG3wtL0gYF4xLtsQWVxI3iFVrU3WzOH/3c5shVRkWBd+AQRSwCJI4mKH7penJCF i3/zzlkvOnjV -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/cert.pem ================================================ -----BEGIN CERTIFICATE----- MIIC6DCCAdKgAwIBAgIRANO6ymxQAjp66KmEka1G6b0wCwYJKoZIhvcNAQELMBYx FDASBgNVBAoTC0Jvb3QyRG9ja2VyMB4XDTE0MTAxNjIwMjE1MloXDTE3MDkzMDIw MjE1MlowFjEUMBIGA1UEChMLQm9vdDJEb2NrZXIwggEiMA0GCSqGSIb3DQEBAQUA A4IBDwAwggEKAoIBAQDGA1mAhSOpZspD1dpZ7qVEQrIJw4Xo8252jHaORnEdDiFm b6brEmr6jw8t4P3IGxbqBc/TqRV+SSXxwYEVvfpeQKH+SmqStoMNtD3Ura161az4 V0BcxMtSlsUGpoz+//QCAq8qiaxMwgiyc5253mkQm88anj2cNt7xbewiu/KFWuf7 BVpNK1+ltpJmlukfcj/G+I1bw7j1KxBjDrFqe5cyDuuZcDL2tmUXP/ZWDyXwSv+H AOckqn44z6aXlBkVvOXDBZJqY76d/vWVDNCuZeXRnqlhP3t1kH4V0RQXo+JD2tgt JgdU0unzyoFOSWNUBPm73tqmjUGGAmGHBmeegJr/AgMBAAGjNTAzMA4GA1UdDwEB /wQEAwIAgDATBgNVHSUEDDAKBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMAsGCSqG SIb3DQEBCwOCAQEABVTWl5SmBP+j5He5bQsgnIXjviSKqe40/10V4LJAOmilycRF zLrzM+YMwfjg6PLIs8CldAMWHw9y9ktZY4MxkgCktaiaN/QmMTMwFWEcN4wy5IpM U5l93eAg7xsnY430h3QBBADujX4wdF3fs8rSL8zAAQFL0ihurwU124K3yXKsrwpb CiVUGfIN4sPwjy8Ws9oxHFDC9/P8lgjHZ1nBIf8KSHnMzlxDGj7isQfhtH+7mcCL cM1qO2NirS2v7uaEPPY+MJstAz+W7EJCW9dfMSmHna2SDC37Xkin7uEY9z+qaKFL 8d/XxOB/L8Ucy8VZhdsv0dsBq5KfJntITM0ksQ== -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/foofile ================================================ ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/key.pem ================================================ -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAxgNZgIUjqWbKQ9XaWe6lREKyCcOF6PNudox2jkZxHQ4hZm+m 6xJq+o8PLeD9yBsW6gXP06kVfkkl8cGBFb36XkCh/kpqkraDDbQ91K2tetWs+FdA XMTLUpbFBqaM/v/0AgKvKomsTMIIsnOdud5pEJvPGp49nDbe8W3sIrvyhVrn+wVa TStfpbaSZpbpH3I/xviNW8O49SsQYw6xanuXMg7rmXAy9rZlFz/2Vg8l8Er/hwDn JKp+OM+ml5QZFbzlwwWSamO+nf71lQzQrmXl0Z6pYT97dZB+FdEUF6PiQ9rYLSYH VNLp88qBTkljVAT5u97apo1BhgJhhwZnnoCa/wIDAQABAoIBAQCaGy9EC9pmU95l DwGh7k5nIrUnTilg1FwLHWSDdCVCZKXv8ENrPelOWZqJrUo1u4eI2L8XTsewgkNq tJu/DRzWz9yDaO0qg6rZNobMh+K076lvmZA44twOydJLS8H+D7ua+PXU2FLlZjmY kMyXRJZmW6zCXZc7haTbJx6ZJccoquk/DkS4FcFurJP177u1YrWS9TTw9kensUtU jQ63uf56UTN1i+0+Rxl7OW1TZlqwlri5I4njg5249+FxwwHzIq8+l7zD7K9pl8c/ nG1HuulvU2bVlDlRdyslMPAH34vw9Sku1BD8furrJLr1na5lRSLKJODEaIPEsLwv CdEUwP9JAoGBAO76ZW80RyNB2fA+wbTq70Sr8CwrXxYemXrez5LKDC7SsohKFCPE IedpO/n+nmymiiJvMm874EExoG6BVrbkWkeb+2vinEfOQNlDMsDx7WLjPekP3t6i rXHO3CjFooVFq2z3mZa/Nc5NZqu8fNWNCKJxZDJphdoj6sORNJIUvZVjAoGBANQd ++J+ITcu3/+A6JrGcgLunBFQYPqkiItk0J4QKYKuX5ik9rWcQDN8TTtfW2mDuiQ4 NrCwuVPq1V1kB16JzH017SsYLo9g8I20YjnBZge9pKTeUaLVTb3C50LW8FBylop0 Bnm597dNbtSjphjoTMg0XyC19o3Esf2YeWG0QNS1AoGAWWDfFRNJU99qIldmXULM 0DM6NVrXSk+ReYnhunXEzrJQwXZrR+EwCPurydk36Uz0NuK9yypquhdUeF/5TZfk SAoHo5byekyipl9imRUigqyY2BTudvgCxKDoaHtaSFwBPFTyZZYICquaLbrmOXxw 8UhVgCFFRYvPXuts7QHC0h8CgYBWEvy9gfU0kV7wLX02IUTuj6jhFb7ktpN6DSTi nyhZES1VoctDEu6ydcRZTW6ouH12aSE4Pd5WgTqntQmQgVZrkNB25k8ue2Xh+srJ KQOgLIJ9LIHwE6KCWG7DnrjRzE3uTPq7to0g4tkQjH/AJ7PQof/gJDayfJjFkXPg A+cy6QKBgEPbKpiqscm03gT2QanBut5pg4dqPOxp0SlErA3kSFNTRK3oYBQPC+LH qA5nD5brdkeNBB58Rll8Zpzxiff50bcvLP/7/Sb3NjaXFTEY0gVbdRof3n6N0YP3 Hu5XDNJ9RNkNzE5RIG1g86KE+aKlcrKMaigqAiuIy2PSnjkQeGk8 -----END RSA PRIVATE KEY----- ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/server.pem ================================================ -----BEGIN CERTIFICATE----- MIIC/DCCAeagAwIBAgIQMUILcXtvmSOK63zEBo0VXzALBgkqhkiG9w0BAQswFjEU MBIGA1UEChMLQm9vdDJEb2NrZXIwHhcNMTQxMDE2MjAyMTQ2WhcNMTcwOTMwMjAy MTQ2WjAWMRQwEgYDVQQKEwtCb290MkRvY2tlcjCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBANxUOUhNnqFnrTlLsBYzfFRZWQo268l+4K4lOJCVbfDonP3g Mz0vGi9fcyFqEWSA8Y+ShXna625HTnReCwFdsu0861qCIq7v95hFFCyOe0iIxpd0 AKLnl90d+1vonE7andgFgoobbTiMly4UK4H6z8D148fFNIihoteOG3PIF89TFxP7 CJ/3wXnx/IKpdlO8PAnub3tBPJHvGDj7KORLy4IBxRX5VBAdfGNybE66fcrehEva rLA4m9pgiaR/Nnr9FdKhPyqYdjflLNvzydxNvMIV4M0hFlhXmYvpMjA5/XsTnsyV t9JHJa5Upwqsbne08t7rsm7liZNxZlko8xPOTQcCAwEAAaNKMEgwDgYDVR0PAQH/ BAQDAgCgMAwGA1UdEwEB/wQCMAAwKAYDVR0RBCEwH4ILYm9vdDJkb2NrZXKHBH8A AAGHBAoAAg+HBMCoO2cwCwYJKoZIhvcNAQELA4IBAQAYoYcDkDWkl73FZ0WnPmAj LiF7HU95Qg3KyEpFsAJeShSLPPbQntmwhdekEzY4tQ3eKQB/+zHFjzsCr/lmDUmH Ea/ryQ17C+jyH+Ykg0IWW6L6veZhvRDg6Z9focVtPVBRxPTqC/Qhb54blWRASV+W UreMuXQ5+1dQptAM7ixOeLVHjBi/bd9TL3jvwBVCr9QedteMjjK4TCF9Tbcou+MF 2w3OJJZMDhcD+YwoK9uJDqlKmcTm/vVMbSsp/pTMcnQ7jxCeR8/XyX+VwTZwaHAa o92Q/eg3THAiWhvyT/SzyH9dHHBAyXynUwGCggKawHktfvW4QXRPuLxLrJ7iB5cy -----END CERTIFICATE----- ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/data/serverkey.pem ================================================ -----BEGIN RSA PRIVATE KEY----- MIIEoAIBAAKCAQEA3FQ5SE2eoWetOUuwFjN8VFlZCjbryX7griU4kJVt8Oic/eAz PS8aL19zIWoRZIDxj5KFedrrbkdOdF4LAV2y7TzrWoIiru/3mEUULI57SIjGl3QA oueX3R37W+icTtqd2AWCihttOIyXLhQrgfrPwPXjx8U0iKGi144bc8gXz1MXE/sI n/fBefH8gql2U7w8Ce5ve0E8ke8YOPso5EvLggHFFflUEB18Y3JsTrp9yt6ES9qs sDib2mCJpH82ev0V0qE/Kph2N+Us2/PJ3E28whXgzSEWWFeZi+kyMDn9exOezJW3 0kclrlSnCqxud7Ty3uuybuWJk3FmWSjzE85NBwIDAQABAoIBAG0ak+cW8LeShHf7 3+2Of0GxoOLrAWWdG5uAuPr31CJYve0FybnBimDtDjD8ujIfm/7xmoEWBEFutA3x x9dcU88gvJbsHEqub9gKVQwfXjMz78tt2SbSMiR/xUnk7QorPcCMMfE71aEMFYzu 1gCed6Rg3vO81t/V0rKVH0j9S7UQz5v/oX15eVDV5LOqyCHwAi6K0eXXbqnbI0TH SOQ/nexM2msVXWbO9t6ra6f5V7FXziDK5Xi+rPxRbX9mkrDzxDAevfuRqYBx5vtL W2Q2hKjUAHFgXFniNSZBS7dCdAtz0el/3ct+cNmpuTMhhs7M6wC1CuYiZ/DxLiFh Si73VckCgYEA+/ceh3+VjtQ0rgEw8sD9bqYEA8IaBiObjneIoFnKBYRG7yZd8JMm HD4M/aQ1qhcRLPN7GR03YQULgQJURbKSjJHnhfTXHyeHC3NN4gMVHQXewu2MHCh6 7FCQ9CfK0KcYLgegVVvL3PrF3hyWGnmTu+G0UkDQRYVnaNrB7snrW6UCgYEA39tq +MCQdu0moJ5szSZf02undg9EeW6isk9qzi7TId3/MLci2eH7PEnipipPUK3+DERq aba0y0TKgBR2EXvXLFJA/+kfdo2loIEHOfox85HVfxgUaFRti63ZI0uF8D0QT2Yy oJal+RFghVoSnv4LjhRKEPbIkScTXGjdK+7wFjsCfz79iKRXQQx0ALd/lL0bgkAn QNmvrNHcFQeI2p8700WNzC39aX67SsvEt3qxkrjzC1gxhpTAuReIK1gVPPwvqHN8 BmV20FD5kMlMCix2mNCopwgUWvKvLAvoGFTxncKMA39+aJbuXAjiqJTekKgNvOE7 i9kEWw0GTNPp3JHV6QECgYAPwb0M11kT1euDIMOdyRazpf86kyaJuZzgGjD1ZFxe JOcigbGFTp/FhZnbglzk2+pm6KXo3QBq0mPCki4hWusxZnTGzpz1VlETNCHTFeZQ M7KoaIR/N3oie9Et59H8r/+m5xWnMhNqratyl316DX24uXrhKM3DUdHODl+LCR2D IwKBgE1MbHuwolUPEw3HeO4R7NMFVTFei7E/fpUsimPfArGg8UydwvloNT1myJos N2JzfGGjN2KPVcBk9fOs71mJ6VcK3C3g5JIccplk6h9VNaw55+zdQvKPTzoBoTvy A+Fwx2AlF61KeRF87DL2YTRJ6B9MHmWgf7+GVZOxomLgEAcZ -----END RSA PRIVATE KEY----- ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/server.go ================================================ // Copyright 2015 go-dockerclient 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 testing provides a fake implementation of the Docker API, useful for // testing purpose. package testing import ( "archive/tar" "crypto/rand" "encoding/json" "errors" "fmt" "io/ioutil" mathrand "math/rand" "net" "net/http" "regexp" "strconv" "strings" "sync" "time" "github.com/fsouza/go-dockerclient" "github.com/fsouza/go-dockerclient/external/github.com/docker/docker/pkg/stdcopy" "github.com/fsouza/go-dockerclient/external/github.com/gorilla/mux" ) var nameRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]+$`) // DockerServer represents a programmable, concurrent (not much), HTTP server // implementing a fake version of the Docker remote API. // // It can used in standalone mode, listening for connections or as an arbitrary // HTTP handler. // // For more details on the remote API, check http://goo.gl/G3plxW. type DockerServer struct { containers []*docker.Container uploadedFiles map[string]string execs []*docker.ExecInspect execMut sync.RWMutex cMut sync.RWMutex images []docker.Image iMut sync.RWMutex imgIDs map[string]string networks []*docker.Network netMut sync.RWMutex listener net.Listener mux *mux.Router hook func(*http.Request) failures map[string]string multiFailures []map[string]string execCallbacks map[string]func() statsCallbacks map[string]func(string) docker.Stats customHandlers map[string]http.Handler handlerMutex sync.RWMutex cChan chan<- *docker.Container volStore map[string]*volumeCounter volMut sync.RWMutex } type volumeCounter struct { volume docker.Volume count int } // NewServer returns a new instance of the fake server, in standalone mode. Use // the method URL to get the URL of the server. // // It receives the bind address (use 127.0.0.1:0 for getting an available port // on the host), a channel of containers and a hook function, that will be // called on every request. // // The fake server will send containers in the channel whenever the container // changes its state, via the HTTP API (i.e.: create, start and stop). This // channel may be nil, which means that the server won't notify on state // changes. func NewServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request)) (*DockerServer, error) { listener, err := net.Listen("tcp", bind) if err != nil { return nil, err } server := DockerServer{ listener: listener, imgIDs: make(map[string]string), hook: hook, failures: make(map[string]string), execCallbacks: make(map[string]func()), statsCallbacks: make(map[string]func(string) docker.Stats), customHandlers: make(map[string]http.Handler), uploadedFiles: make(map[string]string), cChan: containerChan, } server.buildMuxer() go http.Serve(listener, &server) return &server, nil } func (s *DockerServer) notify(container *docker.Container) { if s.cChan != nil { s.cChan <- container } } func (s *DockerServer) buildMuxer() { s.mux = mux.NewRouter() s.mux.Path("/commit").Methods("POST").HandlerFunc(s.handlerWrapper(s.commitContainer)) s.mux.Path("/containers/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.listContainers)) s.mux.Path("/containers/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.createContainer)) s.mux.Path("/containers/{id:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectContainer)) s.mux.Path("/containers/{id:.*}/rename").Methods("POST").HandlerFunc(s.handlerWrapper(s.renameContainer)) s.mux.Path("/containers/{id:.*}/top").Methods("GET").HandlerFunc(s.handlerWrapper(s.topContainer)) s.mux.Path("/containers/{id:.*}/start").Methods("POST").HandlerFunc(s.handlerWrapper(s.startContainer)) s.mux.Path("/containers/{id:.*}/kill").Methods("POST").HandlerFunc(s.handlerWrapper(s.stopContainer)) s.mux.Path("/containers/{id:.*}/stop").Methods("POST").HandlerFunc(s.handlerWrapper(s.stopContainer)) s.mux.Path("/containers/{id:.*}/pause").Methods("POST").HandlerFunc(s.handlerWrapper(s.pauseContainer)) s.mux.Path("/containers/{id:.*}/unpause").Methods("POST").HandlerFunc(s.handlerWrapper(s.unpauseContainer)) s.mux.Path("/containers/{id:.*}/wait").Methods("POST").HandlerFunc(s.handlerWrapper(s.waitContainer)) s.mux.Path("/containers/{id:.*}/attach").Methods("POST").HandlerFunc(s.handlerWrapper(s.attachContainer)) s.mux.Path("/containers/{id:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeContainer)) s.mux.Path("/containers/{id:.*}/exec").Methods("POST").HandlerFunc(s.handlerWrapper(s.createExecContainer)) s.mux.Path("/containers/{id:.*}/stats").Methods("GET").HandlerFunc(s.handlerWrapper(s.statsContainer)) s.mux.Path("/containers/{id:.*}/archive").Methods("PUT").HandlerFunc(s.handlerWrapper(s.uploadToContainer)) s.mux.Path("/exec/{id:.*}/resize").Methods("POST").HandlerFunc(s.handlerWrapper(s.resizeExecContainer)) s.mux.Path("/exec/{id:.*}/start").Methods("POST").HandlerFunc(s.handlerWrapper(s.startExecContainer)) s.mux.Path("/exec/{id:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectExecContainer)) s.mux.Path("/images/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.pullImage)) s.mux.Path("/build").Methods("POST").HandlerFunc(s.handlerWrapper(s.buildImage)) s.mux.Path("/images/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.listImages)) s.mux.Path("/images/{id:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeImage)) s.mux.Path("/images/{name:.*}/json").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectImage)) s.mux.Path("/images/{name:.*}/push").Methods("POST").HandlerFunc(s.handlerWrapper(s.pushImage)) s.mux.Path("/images/{name:.*}/tag").Methods("POST").HandlerFunc(s.handlerWrapper(s.tagImage)) s.mux.Path("/events").Methods("GET").HandlerFunc(s.listEvents) s.mux.Path("/_ping").Methods("GET").HandlerFunc(s.handlerWrapper(s.pingDocker)) s.mux.Path("/images/load").Methods("POST").HandlerFunc(s.handlerWrapper(s.loadImage)) s.mux.Path("/images/{id:.*}/get").Methods("GET").HandlerFunc(s.handlerWrapper(s.getImage)) s.mux.Path("/networks").Methods("GET").HandlerFunc(s.handlerWrapper(s.listNetworks)) s.mux.Path("/networks/{id:.*}").Methods("GET").HandlerFunc(s.handlerWrapper(s.networkInfo)) s.mux.Path("/networks").Methods("POST").HandlerFunc(s.handlerWrapper(s.createNetwork)) s.mux.Path("/volumes").Methods("GET").HandlerFunc(s.handlerWrapper(s.listVolumes)) s.mux.Path("/volumes/create").Methods("POST").HandlerFunc(s.handlerWrapper(s.createVolume)) s.mux.Path("/volumes/{name:.*}").Methods("GET").HandlerFunc(s.handlerWrapper(s.inspectVolume)) s.mux.Path("/volumes/{name:.*}").Methods("DELETE").HandlerFunc(s.handlerWrapper(s.removeVolume)) } // SetHook changes the hook function used by the server. // // The hook function is a function called on every request. func (s *DockerServer) SetHook(hook func(*http.Request)) { s.hook = hook } // PrepareExec adds a callback to a container exec in the fake server. // // This function will be called whenever the given exec id is started, and the // given exec id will remain in the "Running" start while the function is // running, so it's useful for emulating an exec that runs for two seconds, for // example: // // opts := docker.CreateExecOptions{ // AttachStdin: true, // AttachStdout: true, // AttachStderr: true, // Tty: true, // Cmd: []string{"/bin/bash", "-l"}, // } // // Client points to a fake server. // exec, err := client.CreateExec(opts) // // handle error // server.PrepareExec(exec.ID, func() {time.Sleep(2 * time.Second)}) // err = client.StartExec(exec.ID, docker.StartExecOptions{Tty: true}) // will block for 2 seconds // // handle error func (s *DockerServer) PrepareExec(id string, callback func()) { s.execCallbacks[id] = callback } // PrepareStats adds a callback that will be called for each container stats // call. // // This callback function will be called multiple times if stream is set to // true when stats is called. func (s *DockerServer) PrepareStats(id string, callback func(string) docker.Stats) { s.statsCallbacks[id] = callback } // PrepareFailure adds a new expected failure based on a URL regexp it receives // an id for the failure. func (s *DockerServer) PrepareFailure(id string, urlRegexp string) { s.failures[id] = urlRegexp } // PrepareMultiFailures enqueues a new expected failure based on a URL regexp // it receives an id for the failure. func (s *DockerServer) PrepareMultiFailures(id string, urlRegexp string) { s.multiFailures = append(s.multiFailures, map[string]string{"error": id, "url": urlRegexp}) } // ResetFailure removes an expected failure identified by the given id. func (s *DockerServer) ResetFailure(id string) { delete(s.failures, id) } // ResetMultiFailures removes all enqueued failures. func (s *DockerServer) ResetMultiFailures() { s.multiFailures = []map[string]string{} } // CustomHandler registers a custom handler for a specific path. // // For example: // // server.CustomHandler("/containers/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // http.Error(w, "Something wrong is not right", http.StatusInternalServerError) // })) func (s *DockerServer) CustomHandler(path string, handler http.Handler) { s.handlerMutex.Lock() s.customHandlers[path] = handler s.handlerMutex.Unlock() } // MutateContainer changes the state of a container, returning an error if the // given id does not match to any container "running" in the server. func (s *DockerServer) MutateContainer(id string, state docker.State) error { for _, container := range s.containers { if container.ID == id { container.State = state return nil } } return errors.New("container not found") } // Stop stops the server. func (s *DockerServer) Stop() { if s.listener != nil { s.listener.Close() } } // URL returns the HTTP URL of the server. func (s *DockerServer) URL() string { if s.listener == nil { return "" } return "http://" + s.listener.Addr().String() + "/" } // ServeHTTP handles HTTP requests sent to the server. func (s *DockerServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { s.handlerMutex.RLock() defer s.handlerMutex.RUnlock() for re, handler := range s.customHandlers { if m, _ := regexp.MatchString(re, r.URL.Path); m { handler.ServeHTTP(w, r) return } } s.mux.ServeHTTP(w, r) if s.hook != nil { s.hook(r) } } // DefaultHandler returns default http.Handler mux, it allows customHandlers to // call the default behavior if wanted. func (s *DockerServer) DefaultHandler() http.Handler { return s.mux } func (s *DockerServer) handlerWrapper(f func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { for errorID, urlRegexp := range s.failures { matched, err := regexp.MatchString(urlRegexp, r.URL.Path) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if !matched { continue } http.Error(w, errorID, http.StatusBadRequest) return } for i, failure := range s.multiFailures { matched, err := regexp.MatchString(failure["url"], r.URL.Path) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if !matched { continue } http.Error(w, failure["error"], http.StatusBadRequest) s.multiFailures = append(s.multiFailures[:i], s.multiFailures[i+1:]...) return } f(w, r) } } func (s *DockerServer) listContainers(w http.ResponseWriter, r *http.Request) { all := r.URL.Query().Get("all") s.cMut.RLock() result := make([]docker.APIContainers, 0, len(s.containers)) for _, container := range s.containers { if all == "1" || container.State.Running { result = append(result, docker.APIContainers{ ID: container.ID, Image: container.Image, Command: fmt.Sprintf("%s %s", container.Path, strings.Join(container.Args, " ")), Created: container.Created.Unix(), Status: container.State.String(), Ports: container.NetworkSettings.PortMappingAPI(), Names: []string{fmt.Sprintf("/%s", container.Name)}, }) } } s.cMut.RUnlock() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(result) } func (s *DockerServer) listImages(w http.ResponseWriter, r *http.Request) { s.cMut.RLock() result := make([]docker.APIImages, len(s.images)) for i, image := range s.images { result[i] = docker.APIImages{ ID: image.ID, Created: image.Created.Unix(), } for tag, id := range s.imgIDs { if id == image.ID { result[i].RepoTags = append(result[i].RepoTags, tag) } } } s.cMut.RUnlock() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(result) } func (s *DockerServer) findImage(id string) (string, error) { s.iMut.RLock() defer s.iMut.RUnlock() image, ok := s.imgIDs[id] if ok { return image, nil } image, _, err := s.findImageByID(id) return image, err } func (s *DockerServer) findImageByID(id string) (string, int, error) { s.iMut.RLock() defer s.iMut.RUnlock() for i, image := range s.images { if image.ID == id { return image.ID, i, nil } } return "", -1, errors.New("No such image") } func (s *DockerServer) createContainer(w http.ResponseWriter, r *http.Request) { var config struct { *docker.Config HostConfig *docker.HostConfig } defer r.Body.Close() err := json.NewDecoder(r.Body).Decode(&config) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } name := r.URL.Query().Get("name") if name != "" && !nameRegexp.MatchString(name) { http.Error(w, "Invalid container name", http.StatusInternalServerError) return } if _, err := s.findImage(config.Image); err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } ports := map[docker.Port][]docker.PortBinding{} for port := range config.ExposedPorts { ports[port] = []docker.PortBinding{{ HostIP: "0.0.0.0", HostPort: strconv.Itoa(mathrand.Int() % 0xffff), }} } //the container may not have cmd when using a Dockerfile var path string var args []string if len(config.Cmd) == 1 { path = config.Cmd[0] } else if len(config.Cmd) > 1 { path = config.Cmd[0] args = config.Cmd[1:] } generatedID := s.generateID() config.Config.Hostname = generatedID[:12] container := docker.Container{ Name: name, ID: generatedID, Created: time.Now(), Path: path, Args: args, Config: config.Config, HostConfig: config.HostConfig, State: docker.State{ Running: false, Pid: mathrand.Int() % 50000, ExitCode: 0, StartedAt: time.Now(), }, Image: config.Image, NetworkSettings: &docker.NetworkSettings{ IPAddress: fmt.Sprintf("172.16.42.%d", mathrand.Int()%250+2), IPPrefixLen: 24, Gateway: "172.16.42.1", Bridge: "docker0", Ports: ports, }, } s.cMut.Lock() if container.Name != "" { for _, c := range s.containers { if c.Name == container.Name { defer s.cMut.Unlock() http.Error(w, "there's already a container with this name", http.StatusConflict) return } } } s.containers = append(s.containers, &container) s.cMut.Unlock() w.WriteHeader(http.StatusCreated) s.notify(&container) json.NewEncoder(w).Encode(container) } func (s *DockerServer) generateID() string { var buf [16]byte rand.Read(buf[:]) return fmt.Sprintf("%x", buf) } func (s *DockerServer) renameContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, index, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } copy := *container copy.Name = r.URL.Query().Get("name") s.cMut.Lock() defer s.cMut.Unlock() if s.containers[index].ID == copy.ID { s.containers[index] = © } w.WriteHeader(http.StatusNoContent) } func (s *DockerServer) inspectContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(container) } func (s *DockerServer) statsContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] _, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } stream, _ := strconv.ParseBool(r.URL.Query().Get("stream")) callback := s.statsCallbacks[id] w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) encoder := json.NewEncoder(w) for { var stats docker.Stats if callback != nil { stats = callback(id) } encoder.Encode(stats) if !stream { break } } } func (s *DockerServer) uploadToContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } if !container.State.Running { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Container %s is not running", id) return } path := r.URL.Query().Get("path") s.uploadedFiles[id] = path w.WriteHeader(http.StatusOK) } func (s *DockerServer) topContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } if !container.State.Running { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Container %s is not running", id) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) result := docker.TopResult{ Titles: []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}, Processes: [][]string{ {"root", "7535", "7516", "0", "03:20", "?", "00:00:00", container.Path + " " + strings.Join(container.Args, " ")}, }, } json.NewEncoder(w).Encode(result) } func (s *DockerServer) startContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } s.cMut.Lock() defer s.cMut.Unlock() defer r.Body.Close() var hostConfig docker.HostConfig err = json.NewDecoder(r.Body).Decode(&hostConfig) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } container.HostConfig = &hostConfig if len(hostConfig.PortBindings) > 0 { ports := map[docker.Port][]docker.PortBinding{} for key, items := range hostConfig.PortBindings { bindings := make([]docker.PortBinding, len(items)) for i := range items { binding := docker.PortBinding{ HostIP: items[i].HostIP, HostPort: items[i].HostPort, } if binding.HostIP == "" { binding.HostIP = "0.0.0.0" } if binding.HostPort == "" { binding.HostPort = strconv.Itoa(mathrand.Int() % 0xffff) } bindings[i] = binding } ports[key] = bindings } container.NetworkSettings.Ports = ports } if container.State.Running { http.Error(w, "", http.StatusNotModified) return } container.State.Running = true s.notify(container) } func (s *DockerServer) stopContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } s.cMut.Lock() defer s.cMut.Unlock() if !container.State.Running { http.Error(w, "Container not running", http.StatusBadRequest) return } w.WriteHeader(http.StatusNoContent) container.State.Running = false s.notify(container) } func (s *DockerServer) pauseContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } s.cMut.Lock() defer s.cMut.Unlock() if container.State.Paused { http.Error(w, "Container already paused", http.StatusBadRequest) return } w.WriteHeader(http.StatusNoContent) container.State.Paused = true } func (s *DockerServer) unpauseContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } s.cMut.Lock() defer s.cMut.Unlock() if !container.State.Paused { http.Error(w, "Container not paused", http.StatusBadRequest) return } w.WriteHeader(http.StatusNoContent) container.State.Paused = false } func (s *DockerServer) attachContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } hijacker, ok := w.(http.Hijacker) if !ok { http.Error(w, "cannot hijack connection", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/vnd.docker.raw-stream") w.WriteHeader(http.StatusOK) conn, _, err := hijacker.Hijack() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } wg := sync.WaitGroup{} if r.URL.Query().Get("stdin") == "1" { wg.Add(1) go func() { ioutil.ReadAll(conn) wg.Done() }() } outStream := stdcopy.NewStdWriter(conn, stdcopy.Stdout) if container.State.Running { fmt.Fprintf(outStream, "Container is running\n") } else { fmt.Fprintf(outStream, "Container is not running\n") } fmt.Fprintln(outStream, "What happened?") fmt.Fprintln(outStream, "Something happened") wg.Wait() if r.URL.Query().Get("stream") == "1" { for { time.Sleep(1e6) s.cMut.RLock() if !container.State.Running { s.cMut.RUnlock() break } s.cMut.RUnlock() } } conn.Close() } func (s *DockerServer) waitContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } for { time.Sleep(1e6) s.cMut.RLock() if !container.State.Running { s.cMut.RUnlock() break } s.cMut.RUnlock() } result := map[string]int{"StatusCode": container.State.ExitCode} json.NewEncoder(w).Encode(result) } func (s *DockerServer) removeContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] force := r.URL.Query().Get("force") container, index, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } if container.State.Running && force != "1" { msg := "Error: API error (406): Impossible to remove a running container, please stop it first" http.Error(w, msg, http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) s.cMut.Lock() defer s.cMut.Unlock() if s.containers[index].ID == id || s.containers[index].Name == id { s.containers[index] = s.containers[len(s.containers)-1] s.containers = s.containers[:len(s.containers)-1] } } func (s *DockerServer) commitContainer(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("container") container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } var config *docker.Config runConfig := r.URL.Query().Get("run") if runConfig != "" { config = new(docker.Config) err = json.Unmarshal([]byte(runConfig), config) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } } w.WriteHeader(http.StatusOK) image := docker.Image{ ID: "img-" + container.ID, Parent: container.Image, Container: container.ID, Comment: r.URL.Query().Get("m"), Author: r.URL.Query().Get("author"), Config: config, } repository := r.URL.Query().Get("repo") tag := r.URL.Query().Get("tag") s.iMut.Lock() s.images = append(s.images, image) if repository != "" { if tag != "" { repository += ":" + tag } s.imgIDs[repository] = image.ID } s.iMut.Unlock() fmt.Fprintf(w, `{"ID":%q}`, image.ID) } func (s *DockerServer) findContainer(idOrName string) (*docker.Container, int, error) { s.cMut.RLock() defer s.cMut.RUnlock() for i, container := range s.containers { if container.ID == idOrName || container.Name == idOrName { return container, i, nil } } return nil, -1, errors.New("No such container") } func (s *DockerServer) buildImage(w http.ResponseWriter, r *http.Request) { if ct := r.Header.Get("Content-Type"); ct == "application/tar" { gotDockerFile := false tr := tar.NewReader(r.Body) for { header, err := tr.Next() if err != nil { break } if header.Name == "Dockerfile" { gotDockerFile = true } } if !gotDockerFile { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("miss Dockerfile")) return } } //we did not use that Dockerfile to build image cause we are a fake Docker daemon image := docker.Image{ ID: s.generateID(), Created: time.Now(), } query := r.URL.Query() repository := image.ID if t := query.Get("t"); t != "" { repository = t } s.iMut.Lock() s.images = append(s.images, image) s.imgIDs[repository] = image.ID s.iMut.Unlock() w.Write([]byte(fmt.Sprintf("Successfully built %s", image.ID))) } func (s *DockerServer) pullImage(w http.ResponseWriter, r *http.Request) { fromImageName := r.URL.Query().Get("fromImage") tag := r.URL.Query().Get("tag") image := docker.Image{ ID: s.generateID(), } s.iMut.Lock() s.images = append(s.images, image) if fromImageName != "" { if tag != "" { fromImageName = fmt.Sprintf("%s:%s", fromImageName, tag) } s.imgIDs[fromImageName] = image.ID } s.iMut.Unlock() } func (s *DockerServer) pushImage(w http.ResponseWriter, r *http.Request) { name := mux.Vars(r)["name"] tag := r.URL.Query().Get("tag") if tag != "" { name += ":" + tag } s.iMut.RLock() if _, ok := s.imgIDs[name]; !ok { s.iMut.RUnlock() http.Error(w, "No such image", http.StatusNotFound) return } s.iMut.RUnlock() fmt.Fprintln(w, "Pushing...") fmt.Fprintln(w, "Pushed") } func (s *DockerServer) tagImage(w http.ResponseWriter, r *http.Request) { name := mux.Vars(r)["name"] s.iMut.RLock() if _, ok := s.imgIDs[name]; !ok { s.iMut.RUnlock() http.Error(w, "No such image", http.StatusNotFound) return } s.iMut.RUnlock() s.iMut.Lock() defer s.iMut.Unlock() newRepo := r.URL.Query().Get("repo") newTag := r.URL.Query().Get("tag") if newTag != "" { newRepo += ":" + newTag } s.imgIDs[newRepo] = s.imgIDs[name] w.WriteHeader(http.StatusCreated) } func (s *DockerServer) removeImage(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] s.iMut.RLock() var tag string if img, ok := s.imgIDs[id]; ok { id, tag = img, id } var tags []string for tag, taggedID := range s.imgIDs { if taggedID == id { tags = append(tags, tag) } } s.iMut.RUnlock() _, index, err := s.findImageByID(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.WriteHeader(http.StatusNoContent) s.iMut.Lock() defer s.iMut.Unlock() if len(tags) < 2 { s.images[index] = s.images[len(s.images)-1] s.images = s.images[:len(s.images)-1] } if tag != "" { delete(s.imgIDs, tag) } } func (s *DockerServer) inspectImage(w http.ResponseWriter, r *http.Request) { name := mux.Vars(r)["name"] s.iMut.RLock() defer s.iMut.RUnlock() if id, ok := s.imgIDs[name]; ok { for _, img := range s.images { if img.ID == id { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(img) return } } } http.Error(w, "not found", http.StatusNotFound) } func (s *DockerServer) listEvents(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") var events [][]byte count := mathrand.Intn(20) for i := 0; i < count; i++ { data, err := json.Marshal(s.generateEvent()) if err != nil { w.WriteHeader(http.StatusInternalServerError) return } events = append(events, data) } w.WriteHeader(http.StatusOK) for _, d := range events { fmt.Fprintln(w, d) time.Sleep(time.Duration(mathrand.Intn(200)) * time.Millisecond) } } func (s *DockerServer) pingDocker(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func (s *DockerServer) generateEvent() *docker.APIEvents { var eventType string switch mathrand.Intn(4) { case 0: eventType = "create" case 1: eventType = "start" case 2: eventType = "stop" case 3: eventType = "destroy" } return &docker.APIEvents{ ID: s.generateID(), Status: eventType, From: "mybase:latest", Time: time.Now().Unix(), } } func (s *DockerServer) loadImage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } func (s *DockerServer) getImage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/tar") } func (s *DockerServer) createExecContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] container, _, err := s.findContainer(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } execID := s.generateID() container.ExecIDs = append(container.ExecIDs, execID) exec := docker.ExecInspect{ ID: execID, Container: *container, } var params docker.CreateExecOptions err = json.NewDecoder(r.Body).Decode(¶ms) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if len(params.Cmd) > 0 { exec.ProcessConfig.EntryPoint = params.Cmd[0] if len(params.Cmd) > 1 { exec.ProcessConfig.Arguments = params.Cmd[1:] } } exec.ProcessConfig.User = params.User exec.ProcessConfig.Tty = params.Tty s.execMut.Lock() s.execs = append(s.execs, &exec) s.execMut.Unlock() w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"Id": exec.ID}) } func (s *DockerServer) startExecContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] if exec, err := s.getExec(id, false); err == nil { s.execMut.Lock() exec.Running = true s.execMut.Unlock() if callback, ok := s.execCallbacks[id]; ok { callback() delete(s.execCallbacks, id) } else if callback, ok := s.execCallbacks["*"]; ok { callback() delete(s.execCallbacks, "*") } s.execMut.Lock() exec.Running = false s.execMut.Unlock() w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusNotFound) } func (s *DockerServer) resizeExecContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] if _, err := s.getExec(id, false); err == nil { w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusNotFound) } func (s *DockerServer) inspectExecContainer(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] if exec, err := s.getExec(id, true); err == nil { w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(exec) return } w.WriteHeader(http.StatusNotFound) } func (s *DockerServer) getExec(id string, copy bool) (*docker.ExecInspect, error) { s.execMut.RLock() defer s.execMut.RUnlock() for _, exec := range s.execs { if exec.ID == id { if copy { cp := *exec exec = &cp } return exec, nil } } return nil, errors.New("exec not found") } func (s *DockerServer) findNetwork(idOrName string) (*docker.Network, int, error) { s.netMut.RLock() defer s.netMut.RUnlock() for i, network := range s.networks { if network.ID == idOrName || network.Name == idOrName { return network, i, nil } } return nil, -1, errors.New("No such network") } func (s *DockerServer) listNetworks(w http.ResponseWriter, r *http.Request) { s.netMut.RLock() result := make([]docker.Network, 0, len(s.networks)) for _, network := range s.networks { result = append(result, *network) } s.netMut.RUnlock() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(result) } func (s *DockerServer) networkInfo(w http.ResponseWriter, r *http.Request) { id := mux.Vars(r)["id"] network, _, err := s.findNetwork(id) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(network) } // isValidName validates configuration objects supported by libnetwork func isValidName(name string) bool { if name == "" || strings.Contains(name, ".") { return false } return true } func (s *DockerServer) createNetwork(w http.ResponseWriter, r *http.Request) { var config *docker.CreateNetworkOptions defer r.Body.Close() err := json.NewDecoder(r.Body).Decode(&config) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if !isValidName(config.Name) { http.Error(w, "Invalid network name", http.StatusBadRequest) return } if n, _, _ := s.findNetwork(config.Name); n != nil { http.Error(w, "network already exists", http.StatusForbidden) return } generatedID := s.generateID() network := docker.Network{ Name: config.Name, ID: generatedID, Driver: config.Driver, } s.netMut.Lock() s.networks = append(s.networks, &network) s.netMut.Unlock() w.WriteHeader(http.StatusCreated) var c = struct{ ID string }{ID: network.ID} json.NewEncoder(w).Encode(c) } func (s *DockerServer) listVolumes(w http.ResponseWriter, r *http.Request) { s.volMut.RLock() result := make([]docker.Volume, 0, len(s.volStore)) for _, volumeCounter := range s.volStore { result = append(result, volumeCounter.volume) } s.volMut.RUnlock() w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(result) } func (s *DockerServer) createVolume(w http.ResponseWriter, r *http.Request) { var data struct { *docker.CreateVolumeOptions } defer r.Body.Close() err := json.NewDecoder(r.Body).Decode(&data) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } volume := &docker.Volume{ Name: data.CreateVolumeOptions.Name, Driver: data.CreateVolumeOptions.Driver, } // If the name is not specified, generate one. Just using generateID for now if len(volume.Name) == 0 { volume.Name = s.generateID() } // If driver is not specified, use local if len(volume.Driver) == 0 { volume.Driver = "local" } // Mount point is a default one with name volume.Mountpoint = "/var/lib/docker/volumes/" + volume.Name // If the volume already exists, don't re-add it. exists := false s.volMut.Lock() if s.volStore != nil { _, exists = s.volStore[volume.Name] } else { // No volumes, create volStore s.volStore = make(map[string]*volumeCounter) } if !exists { s.volStore[volume.Name] = &volumeCounter{ volume: *volume, count: 0, } } s.volMut.Unlock() w.WriteHeader(http.StatusCreated) json.NewEncoder(w).Encode(volume) } func (s *DockerServer) inspectVolume(w http.ResponseWriter, r *http.Request) { s.volMut.RLock() defer s.volMut.RUnlock() name := mux.Vars(r)["name"] vol, err := s.findVolume(name) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(vol.volume) } func (s *DockerServer) findVolume(name string) (*volumeCounter, error) { vol, ok := s.volStore[name] if !ok { return nil, errors.New("no such volume") } return vol, nil } func (s *DockerServer) removeVolume(w http.ResponseWriter, r *http.Request) { s.volMut.Lock() defer s.volMut.Unlock() name := mux.Vars(r)["name"] vol, err := s.findVolume(name) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } if vol.count != 0 { http.Error(w, "volume in use and cannot be removed", http.StatusConflict) return } s.volStore[vol.volume.Name] = nil w.WriteHeader(http.StatusNoContent) } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/testing/server_test.go ================================================ // Copyright 2015 go-dockerclient 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 testing import ( "bufio" "bytes" "encoding/json" "fmt" "io/ioutil" "math/rand" "net" "net/http" "net/http/httptest" "os" "reflect" "strings" "sync" "testing" "time" "github.com/fsouza/go-dockerclient" ) func TestNewServer(t *testing.T) { server, err := NewServer("127.0.0.1:0", nil, nil) if err != nil { t.Fatal(err) } defer server.listener.Close() conn, err := net.Dial("tcp", server.listener.Addr().String()) if err != nil { t.Fatal(err) } conn.Close() } func TestServerStop(t *testing.T) { server, err := NewServer("127.0.0.1:0", nil, nil) if err != nil { t.Fatal(err) } server.Stop() _, err = net.Dial("tcp", server.listener.Addr().String()) if err == nil { t.Error("Unexpected error when dialing to stopped server") } } func TestServerStopNoListener(t *testing.T) { server := DockerServer{} server.Stop() } func TestServerURL(t *testing.T) { server, err := NewServer("127.0.0.1:0", nil, nil) if err != nil { t.Fatal(err) } defer server.Stop() url := server.URL() if expected := "http://" + server.listener.Addr().String() + "/"; url != expected { t.Errorf("DockerServer.URL(): Want %q. Got %q.", expected, url) } } func TestServerURLNoListener(t *testing.T) { server := DockerServer{} url := server.URL() if url != "" { t.Errorf("DockerServer.URL(): Expected empty URL on handler mode, got %q.", url) } } func TestHandleWithHook(t *testing.T) { var called bool server, _ := NewServer("127.0.0.1:0", nil, func(*http.Request) { called = true }) defer server.Stop() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if !called { t.Error("ServeHTTP did not call the hook function.") } } func TestSetHook(t *testing.T) { var called bool server, _ := NewServer("127.0.0.1:0", nil, nil) defer server.Stop() server.SetHook(func(*http.Request) { called = true }) recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if !called { t.Error("ServeHTTP did not call the hook function.") } } func TestCustomHandler(t *testing.T) { var called bool server, _ := NewServer("127.0.0.1:0", nil, nil) addContainers(server, 2) server.CustomHandler("/containers/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true fmt.Fprint(w, "Hello world") })) recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if !called { t.Error("Did not call the custom handler") } if got := recorder.Body.String(); got != "Hello world" { t.Errorf("Wrong output for custom handler: want %q. Got %q.", "Hello world", got) } } func TestCustomHandlerRegexp(t *testing.T) { var called bool server, _ := NewServer("127.0.0.1:0", nil, nil) addContainers(server, 2) server.CustomHandler("/containers/.*/json", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true fmt.Fprint(w, "Hello world") })) recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/.*/json?all=1", nil) server.ServeHTTP(recorder, request) if !called { t.Error("Did not call the custom handler") } if got := recorder.Body.String(); got != "Hello world" { t.Errorf("Wrong output for custom handler: want %q. Got %q.", "Hello world", got) } } func TestListContainers(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := make([]docker.APIContainers, 2) for i, container := range server.containers { expected[i] = docker.APIContainers{ ID: container.ID, Image: container.Image, Command: strings.Join(container.Config.Cmd, " "), Created: container.Created.Unix(), Status: container.State.String(), Ports: container.NetworkSettings.PortMappingAPI(), Names: []string{"/" + container.Name}, } } var got []docker.APIContainers err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, expected) { t.Errorf("ListContainers. Want %#v. Got %#v.", expected, got) } } func TestListRunningContainers(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=0", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListRunningContainers: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } var got []docker.APIContainers err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if len(got) != 0 { t.Errorf("ListRunningContainers: Want 0. Got %d.", len(got)) } } func TestCreateContainer(t *testing.T) { server := DockerServer{} server.imgIDs = map[string]string{"base": "a1234"} server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } var returned docker.Container err := json.NewDecoder(recorder.Body).Decode(&returned) if err != nil { t.Fatal(err) } stored := server.containers[0] if returned.ID != stored.ID { t.Errorf("CreateContainer: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned.ID) } if stored.State.Running { t.Errorf("CreateContainer should not set container to running state.") } if stored.Config.User != "ubuntu" { t.Errorf("CreateContainer: wrong config. Expected: %q. Returned: %q.", "ubuntu", stored.Config.User) } if stored.Config.Hostname != returned.ID[:12] { t.Errorf("CreateContainer: wrong hostname. Expected: %q. Returned: %q.", returned.ID[:12], stored.Config.Hostname) } expectedBind := []string{"/var/run/docker.sock:/var/run/docker.sock:rw"} if !reflect.DeepEqual(stored.HostConfig.Binds, expectedBind) { t.Errorf("CreateContainer: wrong host config. Expected: %v. Returned %v.", expectedBind, stored.HostConfig.Binds) } } func TestCreateContainerWithNotifyChannel(t *testing.T) { ch := make(chan *docker.Container, 1) server := DockerServer{} server.imgIDs = map[string]string{"base": "a1234"} server.cChan = ch server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":""}` request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } if notified := <-ch; notified != server.containers[0] { t.Errorf("CreateContainer: did not notify the proper container. Want %q. Got %q.", server.containers[0].ID, notified.ID) } } func TestCreateContainerInvalidBody(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader("whaaaaaat---")) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } } func TestCreateContainerDuplicateName(t *testing.T) { server := DockerServer{} server.buildMuxer() server.imgIDs = map[string]string{"base": "a1234"} addContainers(&server, 1) server.containers[0].Name = "mycontainer" recorder := httptest.NewRecorder() body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` request, _ := http.NewRequest("POST", "/containers/create?name=mycontainer", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusConflict { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusConflict, recorder.Code) } } func TestCreateMultipleContainersEmptyName(t *testing.T) { server := DockerServer{} server.buildMuxer() server.imgIDs = map[string]string{"base": "a1234"} addContainers(&server, 1) server.containers[0].Name = "" recorder := httptest.NewRecorder() body := `{"Hostname":"", "User":"ubuntu", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":"","HostConfig":{"Binds":["/var/run/docker.sock:/var/run/docker.sock:rw"]}}` request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } var returned docker.Container err := json.NewDecoder(recorder.Body).Decode(&returned) if err != nil { t.Fatal(err) } stored := server.containers[1] if returned.ID != stored.ID { t.Errorf("CreateContainer: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned.ID) } if stored.State.Running { t.Errorf("CreateContainer should not set container to running state.") } if stored.Config.User != "ubuntu" { t.Errorf("CreateContainer: wrong config. Expected: %q. Returned: %q.", "ubuntu", stored.Config.User) } expectedBind := []string{"/var/run/docker.sock:/var/run/docker.sock:rw"} if !reflect.DeepEqual(stored.HostConfig.Binds, expectedBind) { t.Errorf("CreateContainer: wrong host config. Expected: %v. Returned %v.", expectedBind, stored.HostConfig.Binds) } } func TestCreateContainerInvalidName(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":""}` request, _ := http.NewRequest("POST", "/containers/create?name=myapp/container1", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusInternalServerError { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) } expectedBody := "Invalid container name\n" if got := recorder.Body.String(); got != expectedBody { t.Errorf("CreateContainer: wrong body. Want %q. Got %q.", expectedBody, got) } } func TestCreateContainerImageNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Hostname":"", "User":"", "Memory":0, "MemorySwap":0, "AttachStdin":false, "AttachStdout":true, "AttachStderr":true, "PortSpecs":null, "Tty":false, "OpenStdin":false, "StdinOnce":false, "Env":null, "Cmd":["date"], "Image":"base", "Volumes":{}, "VolumesFrom":""}` request, _ := http.NewRequest("POST", "/containers/create", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("CreateContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestRenameContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() newName := server.containers[0].Name + "abc" path := fmt.Sprintf("/containers/%s/rename?name=%s", server.containers[0].ID, newName) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RenameContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } container := server.containers[0] if container.Name != newName { t.Errorf("RenameContainer: did not rename the container. Want %q. Got %q.", newName, container.Name) } } func TestRenameContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/containers/blabla/rename?name=something", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("RenameContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestCommitContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/commit?container="+server.containers[0].ID, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("CommitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := fmt.Sprintf(`{"ID":"%s"}`, server.images[0].ID) if got := recorder.Body.String(); got != expected { t.Errorf("CommitContainer: wrong response body. Want %q. Got %q.", expected, got) } } func TestCommitContainerComplete(t *testing.T) { server := DockerServer{} server.imgIDs = make(map[string]string) addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() queryString := "container=" + server.containers[0].ID + "&repo=tsuru/python&m=saving&author=developers" queryString += `&run={"Cmd": ["cat", "/world"],"PortSpecs":["22"]}` request, _ := http.NewRequest("POST", "/commit?"+queryString, nil) server.ServeHTTP(recorder, request) image := server.images[0] if image.Parent != server.containers[0].Image { t.Errorf("CommitContainer: wrong parent image. Want %q. Got %q.", server.containers[0].Image, image.Parent) } if image.Container != server.containers[0].ID { t.Errorf("CommitContainer: wrong container. Want %q. Got %q.", server.containers[0].ID, image.Container) } message := "saving" if image.Comment != message { t.Errorf("CommitContainer: wrong comment (commit message). Want %q. Got %q.", message, image.Comment) } author := "developers" if image.Author != author { t.Errorf("CommitContainer: wrong author. Want %q. Got %q.", author, image.Author) } if id := server.imgIDs["tsuru/python"]; id != image.ID { t.Errorf("CommitContainer: wrong ID saved for repository. Want %q. Got %q.", image.ID, id) } portSpecs := []string{"22"} if !reflect.DeepEqual(image.Config.PortSpecs, portSpecs) { t.Errorf("CommitContainer: wrong port spec in config. Want %#v. Got %#v.", portSpecs, image.Config.PortSpecs) } cmd := []string{"cat", "/world"} if !reflect.DeepEqual(image.Config.Cmd, cmd) { t.Errorf("CommitContainer: wrong cmd in config. Want %#v. Got %#v.", cmd, image.Config.Cmd) } } func TestCommitContainerWithTag(t *testing.T) { server := DockerServer{} server.imgIDs = make(map[string]string) addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() queryString := "container=" + server.containers[0].ID + "&repo=tsuru/python&tag=v1" request, _ := http.NewRequest("POST", "/commit?"+queryString, nil) server.ServeHTTP(recorder, request) image := server.images[0] if image.Parent != server.containers[0].Image { t.Errorf("CommitContainer: wrong parent image. Want %q. Got %q.", server.containers[0].Image, image.Parent) } if image.Container != server.containers[0].ID { t.Errorf("CommitContainer: wrong container. Want %q. Got %q.", server.containers[0].ID, image.Container) } if id := server.imgIDs["tsuru/python:v1"]; id != image.ID { t.Errorf("CommitContainer: wrong ID saved for repository. Want %q. Got %q.", image.ID, id) } } func TestCommitContainerInvalidRun(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/commit?container="+server.containers[0].ID+"&run=abc---", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("CommitContainer. Wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } } func TestCommitContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/commit?container=abc123", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("CommitContainer. Wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestInspectContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/json", server.containers[0].ID) request, _ := http.NewRequest("GET", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("InspectContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := server.containers[0] var got docker.Container err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got.Config, expected.Config) { t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) } if !reflect.DeepEqual(got.NetworkSettings, expected.NetworkSettings) { t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) } got.State.StartedAt = expected.State.StartedAt got.State.FinishedAt = expected.State.FinishedAt got.Config = expected.Config got.Created = expected.Created got.NetworkSettings = expected.NetworkSettings if !reflect.DeepEqual(got, *expected) { t.Errorf("InspectContainer: wrong value. Want %#v. Got %#v.", *expected, got) } } func TestInspectContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/abc123/json", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("InspectContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestTopContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) request, _ := http.NewRequest("GET", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } var got docker.TopResult err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got.Titles, []string{"UID", "PID", "PPID", "C", "STIME", "TTY", "TIME", "CMD"}) { t.Fatalf("TopContainer: Unexpected titles, got: %#v", got.Titles) } if len(got.Processes) != 1 { t.Fatalf("TopContainer: Unexpected process len, got: %d", len(got.Processes)) } if got.Processes[0][len(got.Processes[0])-1] != "ls -la .." { t.Fatalf("TopContainer: Unexpected command name, got: %s", got.Processes[0][len(got.Processes[0])-1]) } } func TestTopContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/xyz/top", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestTopContainerStopped(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/top", server.containers[0].ID) request, _ := http.NewRequest("GET", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusInternalServerError { t.Errorf("TopContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) } } func TestStartContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() memory := int64(536870912) hostConfig := docker.HostConfig{Memory: memory} configBytes, err := json.Marshal(hostConfig) if err != nil { t.Fatal(err) } recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) request, _ := http.NewRequest("POST", path, bytes.NewBuffer(configBytes)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) } if !server.containers[0].State.Running { t.Error("StartContainer: did not set the container to running state") } if gotMemory := server.containers[0].HostConfig.Memory; gotMemory != memory { t.Errorf("StartContainer: wrong HostConfig. Wants %d of memory. Got %d", memory, gotMemory) } } func TestStartContainerChangeNetwork(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() hostConfig := docker.HostConfig{ PortBindings: map[docker.Port][]docker.PortBinding{ "8888/tcp": {{HostIP: "", HostPort: "12345"}}, }, } configBytes, err := json.Marshal(hostConfig) if err != nil { t.Fatal(err) } recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) request, _ := http.NewRequest("POST", path, bytes.NewBuffer(configBytes)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) } if !server.containers[0].State.Running { t.Error("StartContainer: did not set the container to running state") } portMapping := server.containers[0].NetworkSettings.Ports["8888/tcp"] expected := []docker.PortBinding{{HostIP: "0.0.0.0", HostPort: "12345"}} if !reflect.DeepEqual(portMapping, expected) { t.Errorf("StartContainer: network not updated. Wants %#v ports. Got %#v", expected, portMapping) } } func TestStartContainerWithNotifyChannel(t *testing.T) { ch := make(chan *docker.Container, 1) server := DockerServer{} server.cChan = ch addContainers(&server, 1) addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/start", server.containers[1].ID) request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("{}"))) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusOK, recorder.Code) } if notified := <-ch; notified != server.containers[1] { t.Errorf("StartContainer: did not notify the proper container. Want %q. Got %q.", server.containers[1].ID, notified.ID) } } func TestStartContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() path := "/containers/abc123/start" request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("null"))) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestStartContainerAlreadyRunning(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/start", server.containers[0].ID) request, _ := http.NewRequest("POST", path, bytes.NewBuffer([]byte("null"))) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotModified { t.Errorf("StartContainer: wrong status code. Want %d. Got %d.", http.StatusNotModified, recorder.Code) } } func TestStopContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/stop", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if server.containers[0].State.Running { t.Error("StopContainer: did not stop the container") } } func TestKillContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/kill", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("KillContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if server.containers[0].State.Running { t.Error("KillContainer: did not stop the container") } } func TestStopContainerWithNotifyChannel(t *testing.T) { ch := make(chan *docker.Container, 1) server := DockerServer{} server.cChan = ch addContainers(&server, 1) addContainers(&server, 1) server.containers[1].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/stop", server.containers[1].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if notified := <-ch; notified != server.containers[1] { t.Errorf("StopContainer: did not notify the proper container. Want %q. Got %q.", server.containers[1].ID, notified.ID) } } func TestStopContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() path := "/containers/abc123/stop" request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestStopContainerNotRunning(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/stop", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("StopContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } } func TestPauseContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/pause", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if !server.containers[0].State.Paused { t.Error("PauseContainer: did not pause the container") } } func TestPauseContainerAlreadyPaused(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Paused = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/pause", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } } func TestPauseContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() path := "/containers/abc123/pause" request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("PauseContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestUnpauseContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Paused = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/unpause", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if server.containers[0].State.Paused { t.Error("UnpauseContainer: did not unpause the container") } } func TestUnpauseContainerNotPaused(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/unpause", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } } func TestUnpauseContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() path := "/containers/abc123/unpause" request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("UnpauseContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestWaitContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/wait", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) go func() { server.cMut.Lock() server.containers[0].State.Running = false server.cMut.Unlock() }() server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("WaitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := `{"StatusCode":0}` + "\n" if body := recorder.Body.String(); body != expected { t.Errorf("WaitContainer: wrong body. Want %q. Got %q.", expected, body) } } func TestWaitContainerStatus(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() server.containers[0].State.ExitCode = 63 recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/wait", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("WaitContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := `{"StatusCode":63}` + "\n" if body := recorder.Body.String(); body != expected { t.Errorf("WaitContainer: wrong body. Want %q. Got %q.", expected, body) } } func TestWaitContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() path := "/containers/abc123/wait" request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("WaitContainer: wrong status code. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } type HijackableResponseRecorder struct { httptest.ResponseRecorder readCh chan []byte } func (r *HijackableResponseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { myConn, otherConn := net.Pipe() r.readCh = make(chan []byte) go func() { data, _ := ioutil.ReadAll(myConn) r.readCh <- data }() return otherConn, nil, nil } func (r *HijackableResponseRecorder) HijackBuffer() string { return string(<-r.readCh) } func TestAttachContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := &HijackableResponseRecorder{} path := fmt.Sprintf("/containers/%s/attach?logs=1", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) lines := []string{ "\x01\x00\x00\x00\x00\x00\x00\x15Container is running", "\x01\x00\x00\x00\x00\x00\x00\x0fWhat happened?", "\x01\x00\x00\x00\x00\x00\x00\x13Something happened", } expected := strings.Join(lines, "\n") + "\n" if body := recorder.HijackBuffer(); body != expected { t.Errorf("AttachContainer: wrong body. Want %q. Got %q.", expected, body) } } func TestAttachContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := &HijackableResponseRecorder{} path := "/containers/abc123/attach?logs=1" request, _ := http.NewRequest("POST", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("AttachContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestAttachContainerWithStreamBlocks(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() path := fmt.Sprintf("/containers/%s/attach?logs=1&stdout=1&stream=1", server.containers[0].ID) request, _ := http.NewRequest("POST", path, nil) done := make(chan string) go func() { recorder := &HijackableResponseRecorder{} server.ServeHTTP(recorder, request) done <- recorder.HijackBuffer() }() select { case <-done: t.Fatalf("attach stream returned before container is stopped") case <-time.After(500 * time.Millisecond): } server.cMut.Lock() server.containers[0].State.Running = false server.cMut.Unlock() var body string select { case body = <-done: case <-time.After(5 * time.Second): t.Fatalf("timed out waiting for attach to finish") } lines := []string{ "\x01\x00\x00\x00\x00\x00\x00\x15Container is running", "\x01\x00\x00\x00\x00\x00\x00\x0fWhat happened?", "\x01\x00\x00\x00\x00\x00\x00\x13Something happened", } expected := strings.Join(lines, "\n") + "\n" if body != expected { t.Errorf("AttachContainer: wrong body. Want %q. Got %q.", expected, body) } } func TestRemoveContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s", server.containers[0].ID) request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if len(server.containers) > 0 { t.Error("RemoveContainer: did not remove the container.") } } func TestRemoveContainerByName(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s", server.containers[0].Name) request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if len(server.containers) > 0 { t.Error("RemoveContainer: did not remove the container.") } } func TestRemoveContainerNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/abc123") request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestRemoveContainerRunning(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s", server.containers[0].ID) request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusInternalServerError { t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusInternalServerError, recorder.Code) } if len(server.containers) < 1 { t.Error("RemoveContainer: should not remove the container.") } } func TestRemoveContainerRunningForce(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.containers[0].State.Running = true server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s?%s", server.containers[0].ID, "force=1") request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RemoveContainer: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if len(server.containers) > 0 { t.Error("RemoveContainer: did not remove the container.") } } func TestPullImage(t *testing.T) { server := DockerServer{imgIDs: make(map[string]string)} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/create?fromImage=base", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("PullImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } if len(server.images) != 1 { t.Errorf("PullImage: Want 1 image. Got %d.", len(server.images)) } if _, ok := server.imgIDs["base"]; !ok { t.Error("PullImage: Repository should not be empty.") } } func TestPullImageWithTag(t *testing.T) { server := DockerServer{imgIDs: make(map[string]string)} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/create?fromImage=base&tag=tag", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("PullImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } if len(server.images) != 1 { t.Errorf("PullImage: Want 1 image. Got %d.", len(server.images)) } if _, ok := server.imgIDs["base:tag"]; !ok { t.Error("PullImage: Repository should not be empty.") } } func TestPushImage(t *testing.T) { server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/tsuru/python/push", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } } func TestPushImageWithTag(t *testing.T) { server := DockerServer{imgIDs: map[string]string{"tsuru/python:v1": "a123"}} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/tsuru/python/push?tag=v1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } } func TestPushImageNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/tsuru/python/push", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("PushImage: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestTagImage(t *testing.T) { server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/tsuru/python/tag?repo=tsuru/new-python", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } if server.imgIDs["tsuru/python"] != server.imgIDs["tsuru/new-python"] { t.Errorf("TagImage: did not tag the image") } } func TestTagImageWithRepoAndTag(t *testing.T) { server := DockerServer{imgIDs: map[string]string{"tsuru/python": "a123"}} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/tsuru/python/tag?repo=tsuru/new-python&tag=v1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } if server.imgIDs["tsuru/python"] != server.imgIDs["tsuru/new-python:v1"] { t.Errorf("TagImage: did not tag the image") } } func TestTagImageNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/images/tsuru/python/tag", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("TagImage: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func addContainers(server *DockerServer, n int) { server.cMut.Lock() defer server.cMut.Unlock() for i := 0; i < n; i++ { date := time.Now().Add(time.Duration((rand.Int() % (i + 1))) * time.Hour) container := docker.Container{ Name: fmt.Sprintf("%x", rand.Int()%10000), ID: fmt.Sprintf("%x", rand.Int()%10000), Created: date, Path: "ls", Args: []string{"-la", ".."}, Config: &docker.Config{ Hostname: fmt.Sprintf("docker-%d", i), AttachStdout: true, AttachStderr: true, Env: []string{"ME=you", fmt.Sprintf("NUMBER=%d", i)}, Cmd: []string{"ls", "-la", ".."}, Image: "base", }, State: docker.State{ Running: false, Pid: 400 + i, ExitCode: 0, StartedAt: date, }, Image: "b750fe79269d2ec9a3c593ef05b4332b1d1a02a62b4accb2c21d589ff2f5f2dc", NetworkSettings: &docker.NetworkSettings{ IPAddress: fmt.Sprintf("10.10.10.%d", i+2), IPPrefixLen: 24, Gateway: "10.10.10.1", Bridge: "docker0", PortMapping: map[string]docker.PortMapping{ "Tcp": {"8888": fmt.Sprintf("%d", 49600+i)}, }, Ports: map[docker.Port][]docker.PortBinding{ "8888/tcp": { {HostIP: "0.0.0.0", HostPort: fmt.Sprintf("%d", 49600+i)}, }, }, }, ResolvConfPath: "/etc/resolv.conf", } server.containers = append(server.containers, &container) } } func addImages(server *DockerServer, n int, repo bool) { server.iMut.Lock() defer server.iMut.Unlock() if server.imgIDs == nil { server.imgIDs = make(map[string]string) } for i := 0; i < n; i++ { date := time.Now().Add(time.Duration((rand.Int() % (i + 1))) * time.Hour) image := docker.Image{ ID: fmt.Sprintf("%x", rand.Int()%10000), Created: date, } server.images = append(server.images, image) if repo { repo := "docker/python-" + image.ID server.imgIDs[repo] = image.ID } } } func TestListImages(t *testing.T) { server := DockerServer{} addImages(&server, 2, true) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/images/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListImages: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := make([]docker.APIImages, 2) for i, image := range server.images { expected[i] = docker.APIImages{ ID: image.ID, Created: image.Created.Unix(), RepoTags: []string{"docker/python-" + image.ID}, } } var got []docker.APIImages err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, expected) { t.Errorf("ListImages. Want %#v. Got %#v.", expected, got) } } func TestRemoveImage(t *testing.T) { server := DockerServer{} addImages(&server, 1, false) server.buildMuxer() recorder := httptest.NewRecorder() path := fmt.Sprintf("/images/%s", server.images[0].ID) request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RemoveImage: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if len(server.images) > 0 { t.Error("RemoveImage: did not remove the image.") } } func TestRemoveImageByName(t *testing.T) { server := DockerServer{} addImages(&server, 1, true) server.buildMuxer() recorder := httptest.NewRecorder() imgName := "docker/python-" + server.images[0].ID path := "/images/" + imgName request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RemoveImage: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } if len(server.images) > 0 { t.Error("RemoveImage: did not remove the image.") } _, ok := server.imgIDs[imgName] if ok { t.Error("RemoveImage: did not remove image tag name.") } } func TestRemoveImageWithMultipleTags(t *testing.T) { server := DockerServer{} addImages(&server, 1, true) server.buildMuxer() imgID := server.images[0].ID imgName := "docker/python-" + imgID server.imgIDs["docker/python-wat"] = imgID recorder := httptest.NewRecorder() path := fmt.Sprintf("/images/%s", imgName) request, _ := http.NewRequest("DELETE", path, nil) server.ServeHTTP(recorder, request) _, ok := server.imgIDs[imgName] if ok { t.Error("RemoveImage: did not remove image tag name.") } id, ok := server.imgIDs["docker/python-wat"] if !ok { t.Error("RemoveImage: removed the wrong tag name.") } if id != imgID { t.Error("RemoveImage: disassociated the wrong ID from the tag") } if len(server.images) < 1 { t.Fatal("RemoveImage: removed the image, but should keep it") } if server.images[0].ID != imgID { t.Error("RemoveImage: changed the ID of the image!") } } func TestPrepareFailure(t *testing.T) { server := DockerServer{failures: make(map[string]string)} server.buildMuxer() errorID := "my_error" server.PrepareFailure(errorID, "containers/json") recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } if recorder.Body.String() != errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } } func TestPrepareMultiFailures(t *testing.T) { server := DockerServer{multiFailures: []map[string]string{}} server.buildMuxer() errorID := "multi error" server.PrepareMultiFailures(errorID, "containers/json") server.PrepareMultiFailures(errorID, "containers/json") recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } if recorder.Body.String() != errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } recorder = httptest.NewRecorder() request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } if recorder.Body.String() != errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } recorder = httptest.NewRecorder() request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } if recorder.Body.String() == errorID+"\n" { t.Errorf("PrepareFailure: wrong message. Want %s. Got %s.", errorID, recorder.Body.String()) } } func TestRemoveFailure(t *testing.T) { server := DockerServer{failures: make(map[string]string)} server.buildMuxer() errorID := "my_error" server.PrepareFailure(errorID, "containers/json") recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("PrepareFailure: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } server.ResetFailure(errorID) recorder = httptest.NewRecorder() request, _ = http.NewRequest("GET", "/containers/json?all=1", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("RemoveFailure: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } } func TestResetMultiFailures(t *testing.T) { server := DockerServer{multiFailures: []map[string]string{}} server.buildMuxer() errorID := "multi error" server.PrepareMultiFailures(errorID, "containers/json") server.PrepareMultiFailures(errorID, "containers/json") if len(server.multiFailures) != 2 { t.Errorf("PrepareMultiFailures: error adding multi failures.") } server.ResetMultiFailures() if len(server.multiFailures) != 0 { t.Errorf("ResetMultiFailures: error reseting multi failures.") } } func TestMutateContainer(t *testing.T) { server := DockerServer{failures: make(map[string]string)} server.buildMuxer() server.containers = append(server.containers, &docker.Container{ID: "id123"}) state := docker.State{Running: false, ExitCode: 1} err := server.MutateContainer("id123", state) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(server.containers[0].State, state) { t.Errorf("Wrong state after mutation.\nWant %#v.\nGot %#v.", state, server.containers[0].State) } } func TestMutateContainerNotFound(t *testing.T) { server := DockerServer{failures: make(map[string]string)} server.buildMuxer() state := docker.State{Running: false, ExitCode: 1} err := server.MutateContainer("id123", state) if err == nil { t.Error("Unexpected error") } if err.Error() != "container not found" { t.Errorf("wrong error message. Want %q. Got %q.", "container not found", err) } } func TestBuildImageWithContentTypeTar(t *testing.T) { server := DockerServer{imgIDs: make(map[string]string)} imageName := "teste" recorder := httptest.NewRecorder() tarFile, err := os.Open("data/dockerfile.tar") if err != nil { t.Fatal(err) } defer tarFile.Close() request, _ := http.NewRequest("POST", "/build?t=teste", tarFile) request.Header.Add("Content-Type", "application/tar") server.buildImage(recorder, request) if recorder.Body.String() == "miss Dockerfile" { t.Errorf("BuildImage: miss Dockerfile") return } if _, ok := server.imgIDs[imageName]; ok == false { t.Errorf("BuildImage: image %s not builded", imageName) } } func TestBuildImageWithRemoteDockerfile(t *testing.T) { server := DockerServer{imgIDs: make(map[string]string)} imageName := "teste" recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/build?t=teste&remote=http://localhost/Dockerfile", nil) server.buildImage(recorder, request) if _, ok := server.imgIDs[imageName]; ok == false { t.Errorf("BuildImage: image %s not builded", imageName) } } func TestPing(t *testing.T) { server := DockerServer{} recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/_ping", nil) server.pingDocker(recorder, request) if recorder.Body.String() != "" { t.Errorf("Ping: Unexpected body: %s", recorder.Body.String()) } if recorder.Code != http.StatusOK { t.Errorf("Ping: Expected code %d, got: %d", http.StatusOK, recorder.Code) } } func TestDefaultHandler(t *testing.T) { server, err := NewServer("127.0.0.1:0", nil, nil) if err != nil { t.Fatal(err) } defer server.listener.Close() if server.mux != server.DefaultHandler() { t.Fatalf("DefaultHandler: Expected to return server.mux, got: %#v", server.DefaultHandler()) } } func TestCreateExecContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Cmd": ["bash", "-c", "ls"]}` path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) request, _ := http.NewRequest("POST", path, strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } serverExec := server.execs[0] var got docker.Exec err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if got.ID != serverExec.ID { t.Errorf("CreateExec: wrong value. Want %#v. Got %#v.", serverExec.ID, got.ID) } expected := docker.ExecInspect{ ID: got.ID, ProcessConfig: docker.ExecProcessConfig{ EntryPoint: "bash", Arguments: []string{"-c", "ls"}, }, Container: *server.containers[0], } if !reflect.DeepEqual(*serverExec, expected) { t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, *serverExec) } } func TestInspectExecContainer(t *testing.T) { server := DockerServer{} addContainers(&server, 1) server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Cmd": ["bash", "-c", "ls"]}` path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) request, _ := http.NewRequest("POST", path, strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } var got docker.Exec err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } path = fmt.Sprintf("/exec/%s/json", got.ID) request, _ = http.NewRequest("GET", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } var got2 docker.ExecInspect err = json.NewDecoder(recorder.Body).Decode(&got2) if err != nil { t.Fatal(err) } expected := docker.ExecInspect{ ID: got.ID, ProcessConfig: docker.ExecProcessConfig{ EntryPoint: "bash", Arguments: []string{"-c", "ls"}, }, Container: *server.containers[0], } got2.Container.State.StartedAt = expected.Container.State.StartedAt got2.Container.State.FinishedAt = expected.Container.State.FinishedAt got2.Container.Config = expected.Container.Config got2.Container.Created = expected.Container.Created got2.Container.NetworkSettings = expected.Container.NetworkSettings got2.Container.ExecIDs = expected.Container.ExecIDs if !reflect.DeepEqual(got2, expected) { t.Errorf("InspectContainer: wrong value. Want:\n%#v\nGot:\n%#v\n", expected, got2) } } func TestStartExecContainer(t *testing.T) { server, _ := NewServer("127.0.0.1:0", nil, nil) addContainers(server, 1) server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Cmd": ["bash", "-c", "ls"]}` path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) request, _ := http.NewRequest("POST", path, strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } var exec docker.Exec err := json.NewDecoder(recorder.Body).Decode(&exec) if err != nil { t.Fatal(err) } unleash := make(chan bool) server.PrepareExec(exec.ID, func() { <-unleash }) codes := make(chan int, 1) sent := make(chan bool) go func() { recorder := httptest.NewRecorder() path := fmt.Sprintf("/exec/%s/start", exec.ID) body := `{"Tty":true}` request, _ := http.NewRequest("POST", path, strings.NewReader(body)) close(sent) server.ServeHTTP(recorder, request) codes <- recorder.Code }() <-sent execInfo, err := waitExec(server.URL(), exec.ID, true, 5) if err != nil { t.Fatal(err) } if !execInfo.Running { t.Error("StartExec: expected exec to be running, but it's not running") } close(unleash) if code := <-codes; code != http.StatusOK { t.Errorf("StartExec: wrong status. Want %d. Got %d.", http.StatusOK, code) } execInfo, err = waitExec(server.URL(), exec.ID, false, 5) if err != nil { t.Fatal(err) } if execInfo.Running { t.Error("StartExec: expected exec to be not running after start returns, but it's running") } } func TestStartExecContainerWildcardCallback(t *testing.T) { server, _ := NewServer("127.0.0.1:0", nil, nil) addContainers(server, 1) server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Cmd": ["bash", "-c", "ls"]}` path := fmt.Sprintf("/containers/%s/exec", server.containers[0].ID) request, _ := http.NewRequest("POST", path, strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Fatalf("CreateExec: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } unleash := make(chan bool) server.PrepareExec("*", func() { <-unleash }) var exec docker.Exec err := json.NewDecoder(recorder.Body).Decode(&exec) if err != nil { t.Fatal(err) } codes := make(chan int, 1) sent := make(chan bool) go func() { recorder := httptest.NewRecorder() path := fmt.Sprintf("/exec/%s/start", exec.ID) body := `{"Tty":true}` request, _ := http.NewRequest("POST", path, strings.NewReader(body)) close(sent) server.ServeHTTP(recorder, request) codes <- recorder.Code }() <-sent execInfo, err := waitExec(server.URL(), exec.ID, true, 5) if err != nil { t.Fatal(err) } if !execInfo.Running { t.Error("StartExec: expected exec to be running, but it's not running") } close(unleash) if code := <-codes; code != http.StatusOK { t.Errorf("StartExec: wrong status. Want %d. Got %d.", http.StatusOK, code) } execInfo, err = waitExec(server.URL(), exec.ID, false, 5) if err != nil { t.Fatal(err) } if execInfo.Running { t.Error("StartExec: expected exec to be not running after start returns, but it's running") } } func TestStartExecContainerNotFound(t *testing.T) { server, _ := NewServer("127.0.0.1:0", nil, nil) addContainers(server, 1) server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Tty":true}` request, _ := http.NewRequest("POST", "/exec/something-wat/start", strings.NewReader(body)) server.ServeHTTP(recorder, request) } func waitExec(url, execID string, running bool, maxTry int) (*docker.ExecInspect, error) { client, err := docker.NewClient(url) if err != nil { return nil, err } exec, err := client.InspectExec(execID) for i := 0; i < maxTry && exec.Running != running && err == nil; i++ { time.Sleep(100e6) exec, err = client.InspectExec(exec.ID) } return exec, err } func TestStatsContainer(t *testing.T) { server, err := NewServer("127.0.0.1:0", nil, nil) if err != nil { t.Fatal(err) } defer server.Stop() addContainers(server, 2) server.buildMuxer() expected := docker.Stats{} expected.CPUStats.CPUUsage.TotalUsage = 20 server.PrepareStats(server.containers[0].ID, func(id string) docker.Stats { return expected }) recorder := httptest.NewRecorder() path := fmt.Sprintf("/containers/%s/stats?stream=false", server.containers[0].ID) request, _ := http.NewRequest("GET", path, nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("StatsContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } body := recorder.Body.Bytes() var got docker.Stats err = json.Unmarshal(body, &got) if err != nil { t.Fatal(err) } got.Read = time.Time{} if !reflect.DeepEqual(got, expected) { t.Errorf("StatsContainer: wrong value. Want %#v. Got %#v.", expected, got) } } type safeWriter struct { sync.Mutex *httptest.ResponseRecorder } func (w *safeWriter) Write(buf []byte) (int, error) { w.Lock() defer w.Unlock() return w.ResponseRecorder.Write(buf) } func TestStatsContainerStream(t *testing.T) { server, err := NewServer("127.0.0.1:0", nil, nil) if err != nil { t.Fatal(err) } defer server.Stop() addContainers(server, 2) server.buildMuxer() expected := docker.Stats{} expected.CPUStats.CPUUsage.TotalUsage = 20 server.PrepareStats(server.containers[0].ID, func(id string) docker.Stats { time.Sleep(50 * time.Millisecond) return expected }) recorder := &safeWriter{ ResponseRecorder: httptest.NewRecorder(), } path := fmt.Sprintf("/containers/%s/stats?stream=true", server.containers[0].ID) request, _ := http.NewRequest("GET", path, nil) go func() { server.ServeHTTP(recorder, request) }() time.Sleep(200 * time.Millisecond) recorder.Lock() defer recorder.Unlock() body := recorder.Body.Bytes() parts := bytes.Split(body, []byte("\n")) if len(parts) < 2 { t.Errorf("StatsContainer: wrong number of parts. Want at least 2. Got %#v.", len(parts)) } var got docker.Stats err = json.Unmarshal(parts[0], &got) if err != nil { t.Fatal(err) } got.Read = time.Time{} if !reflect.DeepEqual(got, expected) { t.Errorf("StatsContainer: wrong value. Want %#v. Got %#v.", expected, got) } } func addNetworks(server *DockerServer, n int) { server.netMut.Lock() defer server.netMut.Unlock() for i := 0; i < n; i++ { netid := fmt.Sprintf("%x", rand.Int()%10000) network := docker.Network{ Name: netid, ID: fmt.Sprintf("%x", rand.Int()%10000), Driver: "bridge", Containers: map[string]docker.Endpoint{ "blah": { Name: "blah", ID: fmt.Sprintf("%x", rand.Int()%10000), }, }, } server.networks = append(server.networks, &network) } } func TestListNetworks(t *testing.T) { server := DockerServer{} addNetworks(&server, 2) server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/networks", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListNetworks: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } expected := make([]docker.Network, 2) for i, network := range server.networks { expected[i] = docker.Network{ ID: network.ID, Name: network.Name, Driver: network.Driver, Containers: network.Containers, } } var got []docker.Network err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, expected) { t.Errorf("ListNetworks. Want %#v. Got %#v.", expected, got) } } type createNetworkResponse struct { ID string `json:"ID"` } func TestCreateNetwork(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() netid := fmt.Sprintf("%x", rand.Int()%10000) netname := fmt.Sprintf("%x", rand.Int()%10000) body := fmt.Sprintf(`{"ID": "%s", "Name": "%s", "Type": "bridge" }`, netid, netname) request, _ := http.NewRequest("POST", "/networks", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } var returned createNetworkResponse err := json.NewDecoder(recorder.Body).Decode(&returned) if err != nil { t.Fatal(err) } stored := server.networks[0] if returned.ID != stored.ID { t.Errorf("CreateNetwork: ID mismatch. Stored: %q. Returned: %q.", stored.ID, returned) } } func TestCreateNetworkInvalidBody(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/networks", strings.NewReader("whaaaaaat---")) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusBadRequest { t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusBadRequest, recorder.Code) } } func TestCreateNetworkDuplicateName(t *testing.T) { server := DockerServer{} server.buildMuxer() addNetworks(&server, 1) server.networks[0].Name = "mynetwork" recorder := httptest.NewRecorder() body := fmt.Sprintf(`{"ID": "%s", "Name": "mynetwork", "Type": "bridge" }`, fmt.Sprintf("%x", rand.Int()%10000)) request, _ := http.NewRequest("POST", "/networks", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusForbidden { t.Errorf("CreateNetwork: wrong status. Want %d. Got %d.", http.StatusForbidden, recorder.Code) } } func TestListVolumes(t *testing.T) { server := DockerServer{} server.buildMuxer() expected := []docker.Volume{{ Name: "test-vol-1", Driver: "local", Mountpoint: "/var/lib/docker/volumes/test-vol-1", }} server.volStore = make(map[string]*volumeCounter) for _, vol := range expected { server.volStore[vol.Name] = &volumeCounter{ volume: vol, count: 0, } } recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/volumes", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("ListVolumes: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } var got []docker.Volume err := json.NewDecoder(recorder.Body).Decode(&got) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(got, expected) { t.Errorf("ListVolumes. Want %#v. Got %#v.", expected, got) } } func TestCreateVolume(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() body := `{"Name":"test-volume"}` request, _ := http.NewRequest("POST", "/volumes/create", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("CreateVolume: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } var returned docker.Volume err := json.NewDecoder(recorder.Body).Decode(&returned) if err != nil { t.Error(err) } if returned.Name != "test-volume" { t.Errorf("CreateVolume: Name mismatch. Expected: test-volume. Returned %q.", returned.Name) } if returned.Driver != "local" { t.Errorf("CreateVolume: Driver mismatch. Expected: local. Returned: %q", returned.Driver) } if returned.Mountpoint != "/var/lib/docker/volumes/test-volume" { t.Errorf("CreateVolume: Mountpoint mismatch. Expected: /var/lib/docker/volumes/test-volume. Returned: %q.", returned.Mountpoint) } } func TestCreateVolumeAlreadExists(t *testing.T) { server := DockerServer{} server.buildMuxer() server.volStore = make(map[string]*volumeCounter) server.volStore["test-volume"] = &volumeCounter{ volume: docker.Volume{ Name: "test-volume", Driver: "local", Mountpoint: "/var/lib/docker/volumes/test-volume", }, count: 0, } body := `{"Name":"test-volume"}` recorder := httptest.NewRecorder() request, _ := http.NewRequest("POST", "/volumes/create", strings.NewReader(body)) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusCreated { t.Errorf("CreateVolumeAlreadExists: wrong status. Want %d. Got %d.", http.StatusCreated, recorder.Code) } var returned docker.Volume err := json.NewDecoder(recorder.Body).Decode(&returned) if err != nil { t.Error(err) } if returned.Name != "test-volume" { t.Errorf("CreateVolumeAlreadExists: Name mismatch. Expected: test-volume. Returned %q.", returned.Name) } if returned.Driver != "local" { t.Errorf("CreateVolumeAlreadExists: Driver mismatch. Expected: local. Returned: %q", returned.Driver) } if returned.Mountpoint != "/var/lib/docker/volumes/test-volume" { t.Errorf("CreateVolumeAlreadExists: Mountpoint mismatch. Expected: /var/lib/docker/volumes/test-volume. Returned: %q.", returned.Mountpoint) } } func TestInspectVolume(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() expected := docker.Volume{ Name: "test-volume", Driver: "local", Mountpoint: "/var/lib/docker/volumes/test-volume", } volC := &volumeCounter{ volume: expected, count: 0, } volStore := make(map[string]*volumeCounter) volStore["test-volume"] = volC server.volStore = volStore request, _ := http.NewRequest("GET", "/volumes/test-volume", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("InspectVolume: wrong status. Want %d. God %d.", http.StatusOK, recorder.Code) } var returned docker.Volume err := json.NewDecoder(recorder.Body).Decode(&returned) if err != nil { t.Error(err) } if returned.Name != "test-volume" { t.Errorf("InspectVolume: Name mismatch. Expected: test-volume. Returned %q.", returned.Name) } if returned.Driver != "local" { t.Errorf("InspectVolume: Driver mismatch. Expected: local. Returned: %q", returned.Driver) } if returned.Mountpoint != "/var/lib/docker/volumes/test-volume" { t.Errorf("InspectVolume: Mountpoint mismatch. Expected: /var/lib/docker/volumes/test-volume. Returned: %q.", returned.Mountpoint) } } func TestInspectVolumeNotFound(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("GET", "/volumes/test-volume", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("RemoveMissingVolume: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestRemoveVolume(t *testing.T) { server := DockerServer{} server.buildMuxer() server.volStore = make(map[string]*volumeCounter) server.volStore["test-volume"] = &volumeCounter{ volume: docker.Volume{ Name: "test-volume", Driver: "local", Mountpoint: "/var/lib/docker/volumes/test-volume", }, count: 0, } recorder := httptest.NewRecorder() request, _ := http.NewRequest("DELETE", "/volumes/test-volume", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Errorf("RemoveVolume: wrong status. Want %d. Got %d.", http.StatusNoContent, recorder.Code) } } func TestRemoveMissingVolume(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("DELETE", "/volumes/test-volume", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("RemoveMissingVolume: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } func TestRemoveVolumeInuse(t *testing.T) { server := DockerServer{} server.buildMuxer() server.volStore = make(map[string]*volumeCounter) server.volStore["test-volume"] = &volumeCounter{ volume: docker.Volume{ Name: "test-volume", Driver: "local", Mountpoint: "/var/lib/docker/volumes/test-volume", }, count: 1, } recorder := httptest.NewRecorder() request, _ := http.NewRequest("DELETE", "/volumes/test-volume", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusConflict { t.Errorf("RemoveVolume: wrong status. Want %d. Got %d.", http.StatusConflict, recorder.Code) } } func TestUploadToContainer(t *testing.T) { server := DockerServer{} server.buildMuxer() cont := &docker.Container{ ID: "id123", State: docker.State{ Running: true, ExitCode: 0, }, } server.containers = append(server.containers, cont) server.uploadedFiles = make(map[string]string) recorder := httptest.NewRecorder() request, _ := http.NewRequest("PUT", fmt.Sprintf("/containers/%s/archive?path=abcd", cont.ID), nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusOK { t.Errorf("UploadToContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code) } } func TestUploadToContainerMissingContainer(t *testing.T) { server := DockerServer{} server.buildMuxer() recorder := httptest.NewRecorder() request, _ := http.NewRequest("PUT", "/containers/missing-container/archive?path=abcd", nil) server.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotFound { t.Errorf("UploadToContainer: wrong status. Want %d. Got %d.", http.StatusNotFound, recorder.Code) } } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/tls.go ================================================ // Copyright 2014 go-dockerclient authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // // The content is borrowed from Docker's own source code to provide a simple // tls based dialer package docker import ( "crypto/tls" "errors" "net" "strings" "time" ) type tlsClientCon struct { *tls.Conn rawConn net.Conn } func (c *tlsClientCon) CloseWrite() error { // Go standard tls.Conn doesn't provide the CloseWrite() method so we do it // on its underlying connection. if cwc, ok := c.rawConn.(interface { CloseWrite() error }); ok { return cwc.CloseWrite() } return nil } func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Config) (net.Conn, error) { // We want the Timeout and Deadline values from dialer to cover the // whole process: TCP connection and TLS handshake. This means that we // also need to start our own timers now. timeout := dialer.Timeout if !dialer.Deadline.IsZero() { deadlineTimeout := dialer.Deadline.Sub(time.Now()) if timeout == 0 || deadlineTimeout < timeout { timeout = deadlineTimeout } } var errChannel chan error if timeout != 0 { errChannel = make(chan error, 2) time.AfterFunc(timeout, func() { errChannel <- errors.New("") }) } rawConn, err := dialer.Dial(network, addr) if err != nil { return nil, err } colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } hostname := addr[:colonPos] // If no ServerName is set, infer the ServerName // from the hostname we're connecting to. if config.ServerName == "" { // Make a copy to avoid polluting argument or default. c := *config c.ServerName = hostname config = &c } conn := tls.Client(rawConn, config) if timeout == 0 { err = conn.Handshake() } else { go func() { errChannel <- conn.Handshake() }() err = <-errChannel } if err != nil { rawConn.Close() return nil, err } // This is Docker difference with standard's crypto/tls package: returned a // wrapper which holds both the TLS and raw connections. return &tlsClientCon{conn, rawConn}, nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/volume.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "errors" "net/http" ) var ( // ErrNoSuchVolume is the error returned when the volume does not exist. ErrNoSuchVolume = errors.New("no such volume") // ErrVolumeInUse is the error returned when the volume requested to be removed is still in use. ErrVolumeInUse = errors.New("volume in use and cannot be removed") ) // Volume represents a volume. // // See https://goo.gl/FZA4BK for more details. type Volume struct { Name string `json:"Name" yaml:"Name"` Driver string `json:"Driver,omitempty" yaml:"Driver,omitempty"` Mountpoint string `json:"Mountpoint,omitempty" yaml:"Mountpoint,omitempty"` } // ListVolumesOptions specify parameters to the ListVolumes function. // // See https://goo.gl/FZA4BK for more details. type ListVolumesOptions struct { Filters map[string][]string } // ListVolumes returns a list of available volumes in the server. // // See https://goo.gl/FZA4BK for more details. func (c *Client) ListVolumes(opts ListVolumesOptions) ([]Volume, error) { resp, err := c.do("GET", "/volumes?"+queryString(opts), doOptions{}) if err != nil { return nil, err } defer resp.Body.Close() m := make(map[string]interface{}) if err := json.NewDecoder(resp.Body).Decode(&m); err != nil { return nil, err } var volumes []Volume volumesJSON, ok := m["Volumes"] if !ok { return volumes, nil } data, err := json.Marshal(volumesJSON) if err != nil { return nil, err } if err := json.Unmarshal(data, &volumes); err != nil { return nil, err } return volumes, nil } // CreateVolumeOptions specify parameters to the CreateVolume function. // // See https://goo.gl/pBUbZ9 for more details. type CreateVolumeOptions struct { Name string Driver string DriverOpts map[string]string } // CreateVolume creates a volume on the server. // // See https://goo.gl/pBUbZ9 for more details. func (c *Client) CreateVolume(opts CreateVolumeOptions) (*Volume, error) { resp, err := c.do("POST", "/volumes/create", doOptions{data: opts}) if err != nil { return nil, err } defer resp.Body.Close() var volume Volume if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil { return nil, err } return &volume, nil } // InspectVolume returns a volume by its name. // // See https://goo.gl/0g9A6i for more details. func (c *Client) InspectVolume(name string) (*Volume, error) { resp, err := c.do("GET", "/volumes/"+name, doOptions{}) if err != nil { if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound { return nil, ErrNoSuchVolume } return nil, err } defer resp.Body.Close() var volume Volume if err := json.NewDecoder(resp.Body).Decode(&volume); err != nil { return nil, err } return &volume, nil } // RemoveVolume removes a volume by its name. // // See https://goo.gl/79GNQz for more details. func (c *Client) RemoveVolume(name string) error { resp, err := c.do("DELETE", "/volumes/"+name, doOptions{}) if err != nil { if e, ok := err.(*Error); ok { if e.Status == http.StatusNotFound { return ErrNoSuchVolume } if e.Status == http.StatusConflict { return ErrVolumeInUse } } return nil } defer resp.Body.Close() return nil } ================================================ FILE: vendor/github.com/fsouza/go-dockerclient/volume_test.go ================================================ // Copyright 2015 go-dockerclient 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 docker import ( "encoding/json" "net/http" "net/url" "reflect" "testing" ) func TestListVolumes(t *testing.T) { volumesData := `[ { "Name": "tardis", "Driver": "local", "Mountpoint": "/var/lib/docker/volumes/tardis" }, { "Name": "foo", "Driver": "bar", "Mountpoint": "/var/lib/docker/volumes/bar" } ]` body := `{ "Volumes": ` + volumesData + ` }` var expected []Volume if err := json.Unmarshal([]byte(volumesData), &expected); err != nil { t.Fatal(err) } client := newTestClient(&FakeRoundTripper{message: body, status: http.StatusOK}) volumes, err := client.ListVolumes(ListVolumesOptions{}) if err != nil { t.Error(err) } if !reflect.DeepEqual(volumes, expected) { t.Errorf("ListVolumes: Wrong return value. Want %#v. Got %#v.", expected, volumes) } } func TestCreateVolume(t *testing.T) { body := `{ "Name": "tardis", "Driver": "local", "Mountpoint": "/var/lib/docker/volumes/tardis" }` var expected Volume if err := json.Unmarshal([]byte(body), &expected); err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} client := newTestClient(fakeRT) volume, err := client.CreateVolume( CreateVolumeOptions{ Name: "tardis", Driver: "local", DriverOpts: map[string]string{ "foo": "bar", }, }, ) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(volume, &expected) { t.Errorf("CreateVolume: Wrong return value. Want %#v. Got %#v.", expected, volume) } req := fakeRT.requests[0] expectedMethod := "POST" if req.Method != expectedMethod { t.Errorf("CreateVolume(): Wrong HTTP method. Want %s. Got %s.", expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/volumes/create")) if req.URL.Path != u.Path { t.Errorf("CreateVolume(): Wrong request path. Want %q. Got %q.", u.Path, req.URL.Path) } } func TestInspectVolume(t *testing.T) { body := `{ "Name": "tardis", "Driver": "local", "Mountpoint": "/var/lib/docker/volumes/tardis" }` var expected Volume if err := json.Unmarshal([]byte(body), &expected); err != nil { t.Fatal(err) } fakeRT := &FakeRoundTripper{message: body, status: http.StatusOK} client := newTestClient(fakeRT) name := "tardis" volume, err := client.InspectVolume(name) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(volume, &expected) { t.Errorf("InspectVolume: Wrong return value. Want %#v. Got %#v.", expected, volume) } req := fakeRT.requests[0] expectedMethod := "GET" if req.Method != expectedMethod { t.Errorf("InspectVolume(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/volumes/" + name)) if req.URL.Path != u.Path { t.Errorf("CreateVolume(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) } } func TestRemoveVolume(t *testing.T) { name := "test" fakeRT := &FakeRoundTripper{message: "", status: http.StatusNoContent} client := newTestClient(fakeRT) if err := client.RemoveVolume(name); err != nil { t.Fatal(err) } req := fakeRT.requests[0] expectedMethod := "DELETE" if req.Method != expectedMethod { t.Errorf("RemoveVolume(%q): Wrong HTTP method. Want %s. Got %s.", name, expectedMethod, req.Method) } u, _ := url.Parse(client.getURL("/volumes/" + name)) if req.URL.Path != u.Path { t.Errorf("RemoveVolume(%q): Wrong request path. Want %q. Got %q.", name, u.Path, req.URL.Path) } } func TestRemoveVolumeNotFound(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "no such volume", status: http.StatusNotFound}) if err := client.RemoveVolume("test:"); err != ErrNoSuchVolume { t.Errorf("RemoveVolume: wrong error. Want %#v. Got %#v.", ErrNoSuchVolume, err) } } func TestRemoveVolumeInUse(t *testing.T) { client := newTestClient(&FakeRoundTripper{message: "volume in use and cannot be removed", status: http.StatusConflict}) if err := client.RemoveVolume("test:"); err != ErrVolumeInUse { t.Errorf("RemoveVolume: wrong error. Want %#v. Got %#v.", ErrVolumeInUse, err) } } ================================================ FILE: vendor/github.com/ghodss/yaml/.gitignore ================================================ # OSX leaves these everywhere on SMB shares ._* # Eclipse files .classpath .project .settings/** # Emacs save files *~ # Vim-related files [._]*.s[a-w][a-z] [._]s[a-w][a-z] *.un~ Session.vim .netrwhist # Go test binaries *.test ================================================ FILE: vendor/github.com/ghodss/yaml/.travis.yml ================================================ language: go go: - 1.3 - 1.4 script: - go test - go build ================================================ FILE: vendor/github.com/ghodss/yaml/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2014 Sam Ghods 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. 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. ================================================ FILE: vendor/github.com/ghodss/yaml/README.md ================================================ # YAML marshaling and unmarshaling support for Go [![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml) ## Introduction A wrapper around [candiedyaml](https://github.com/cloudfoundry-incubator/candiedyaml) designed to enable a better way of handling YAML when marshaling to and from structs. In short, this library first converts YAML to JSON using candiedyaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike candiedyaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/). ## Compatibility This package uses [candiedyaml](https://github.com/cloudfoundry-incubator/candiedyaml) and therefore supports [everything candiedyaml supports](https://github.com/cloudfoundry-incubator/candiedyaml#candiedyaml). ## Caveats **Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, candiedyaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example: ``` BAD: exampleKey: !!binary gIGC GOOD: exampleKey: gIGC ... and decode the base64 data in your code. ``` **Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys. ## Installation and usage To install, run: ``` $ go get github.com/ghodss/yaml ``` And import using: ``` import "github.com/ghodss/yaml" ``` Usage is very similar to the JSON library: ```go import ( "fmt" "github.com/ghodss/yaml" ) type Person struct { Name string `json:"name"` // Affects YAML field names too. Age int `json:"name"` } func main() { // Marshal a Person struct to YAML. p := Person{"John", 30} y, err := yaml.Marshal(p) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: name: John age: 30 */ // Unmarshal the YAML back into a Person struct. var p2 Person err := yaml.Unmarshal(y, &p2) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(p2) /* Output: {John 30} */ } ``` `yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available: ```go import ( "fmt" "github.com/ghodss/yaml" ) func main() { j := []byte(`{"name": "John", "age": 30}`) y, err := yaml.JSONToYAML(j) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(y)) /* Output: name: John age: 30 */ j2, err := yaml.YAMLToJSON(y) if err != nil { fmt.Printf("err: %v\n", err) return } fmt.Println(string(j2)) /* Output: {"age":30,"name":"John"} */ } ``` ================================================ FILE: vendor/github.com/ghodss/yaml/fields.go ================================================ // 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 yaml import ( "bytes" "encoding" "encoding/json" "reflect" "sort" "strings" "sync" "unicode" "unicode/utf8" ) // 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 indirect(v reflect.Value, decodingNull bool) (json.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().(json.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 } // 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 != "" { // 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() } // 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: opts.Contains("string"), })) 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) } } 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 // 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 } 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 } 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 } 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 http://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 } // 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 } ================================================ FILE: vendor/github.com/ghodss/yaml/yaml.go ================================================ package yaml import ( "bytes" "encoding/json" "fmt" "reflect" "strconv" yaml "github.com/cloudfoundry-incubator/candiedyaml" ) // Marshals the object into JSON then converts JSON to YAML and returns the // YAML. func Marshal(o interface{}) ([]byte, error) { j, err := json.Marshal(o) if err != nil { return nil, fmt.Errorf("error marshaling into JSON: ", err) } y, err := JSONToYAML(j) if err != nil { return nil, fmt.Errorf("error converting JSON to YAML: ", err) } return y, nil } // Converts YAML to JSON then uses JSON to unmarshal into an object. func Unmarshal(y []byte, o interface{}) error { vo := reflect.ValueOf(o) j, err := yamlToJSON(y, &vo) if err != nil { return fmt.Errorf("error converting YAML to JSON: %v", err) } err = json.Unmarshal(j, o) if err != nil { return fmt.Errorf("error unmarshaling JSON: %v", err) } return nil } // Convert JSON to YAML. func JSONToYAML(j []byte) ([]byte, error) { // Convert the JSON to an object. var jsonObj interface{} // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the // Go JSON library doesn't try to pick the right number type (int, float, // etc.) when unmarshling to interface{}, it just picks float64 // universally. go-yaml does go through the effort of picking the right // number type, so we can preserve number type throughout this process. err := yaml.Unmarshal(j, &jsonObj) if err != nil { return nil, err } // Marshal this object into YAML. return yaml.Marshal(jsonObj) } // Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through // this method should be a no-op. // // Things YAML can do that are not supported by JSON: // * In YAML you can have binary and null keys in your maps. These are invalid // in JSON. (int and float keys are converted to strings.) // * Binary data in YAML with the !!binary tag is not supported. If you want to // use binary data with this library, encode the data as base64 as usual but do // not use the !!binary tag in your YAML. This will ensure the original base64 // encoded data makes it all the way through to the JSON. func YAMLToJSON(y []byte) ([]byte, error) { return yamlToJSON(y, nil) } func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) { // Convert the YAML to an object. var yamlObj interface{} err := yaml.Unmarshal(y, &yamlObj) if err != nil { return nil, err } // YAML objects are not completely compatible with JSON objects (e.g. you // can have non-string keys in YAML). So, convert the YAML-compatible object // to a JSON-compatible object, failing with an error if irrecoverable // incompatibilties happen along the way. jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget) if err != nil { return nil, err } // Convert this object to JSON and return the data. return json.Marshal(jsonObj) } func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) { var err error // Resolve jsonTarget to a concrete value (i.e. not a pointer or an // interface). We pass decodingNull as false because we're not actually // decoding into the value, we're just checking if the ultimate target is a // string. if jsonTarget != nil { ju, tu, pv := indirect(*jsonTarget, false) // We have a JSON or Text Umarshaler at this level, so we can't be trying // to decode into a string. if ju != nil || tu != nil { jsonTarget = nil } else { jsonTarget = &pv } } // If yamlObj is a number or a boolean, check if jsonTarget is a string - // if so, coerce. Else return normal. // If yamlObj is a map or array, find the field that each key is // unmarshaling to, and when you recurse pass the reflect.Value for that // field back into this function. switch typedYAMLObj := yamlObj.(type) { case map[interface{}]interface{}: // JSON does not support arbitrary keys in a map, so we must convert // these keys to strings. // // From my reading of go-yaml v2 (specifically the resolve function), // keys can only have the types string, int, int64, float64, binary // (unsupported), or null (unsupported). strMap := make(map[string]interface{}) for k, v := range typedYAMLObj { // Resolve the key to a string first. var keyString string switch typedKey := k.(type) { case string: keyString = typedKey case int: keyString = strconv.Itoa(typedKey) case int64: // go-yaml will only return an int64 as a key if the system // architecture is 32-bit and the key's value is between 32-bit // and 64-bit. Otherwise the key type will simply be int. keyString = strconv.FormatInt(typedKey, 10) case float64: // Stolen from go-yaml to use the same conversion to string as // the go-yaml library uses to convert float to string when // Marshaling. s := strconv.FormatFloat(typedKey, 'g', -1, 32) switch s { case "+Inf": s = ".inf" case "-Inf": s = "-.inf" case "NaN": s = ".nan" } keyString = s case bool: if typedKey { keyString = "true" } else { keyString = "false" } default: return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v", reflect.TypeOf(k), k, v) } // jsonTarget should be a struct or a map. If it's a struct, find // the field it's going to map to and pass its reflect.Value. If // it's a map, find the element type of the map and pass the // reflect.Value created from that type. If it's neither, just pass // nil - JSON conversion will error for us if it's a real issue. if jsonTarget != nil { t := *jsonTarget if t.Kind() == reflect.Struct { keyBytes := []byte(keyString) // Find the field that the JSON library would use. var f *field fields := cachedTypeFields(t.Type()) for i := range fields { ff := &fields[i] if bytes.Equal(ff.nameBytes, keyBytes) { f = ff break } // Do case-insensitive comparison. if f == nil && ff.equalFold(ff.nameBytes, keyBytes) { f = ff } } if f != nil { // Find the reflect.Value of the most preferential // struct field. jtf := t.Field(f.index[0]) strMap[keyString], err = convertToJSONableObject(v, &jtf) if err != nil { return nil, err } continue } } else if t.Kind() == reflect.Map { // Create a zero value of the map's element type to use as // the JSON target. jtv := reflect.Zero(t.Type().Elem()) strMap[keyString], err = convertToJSONableObject(v, &jtv) if err != nil { return nil, err } continue } } strMap[keyString], err = convertToJSONableObject(v, nil) if err != nil { return nil, err } } return strMap, nil case []interface{}: // We need to recurse into arrays in case there are any // map[interface{}]interface{}'s inside and to convert any // numbers to strings. // If jsonTarget is a slice (which it really should be), find the // thing it's going to map to. If it's not a slice, just pass nil // - JSON conversion will error for us if it's a real issue. var jsonSliceElemValue *reflect.Value if jsonTarget != nil { t := *jsonTarget if t.Kind() == reflect.Slice { // By default slices point to nil, but we need a reflect.Value // pointing to a value of the slice type, so we create one here. ev := reflect.Indirect(reflect.New(t.Type().Elem())) jsonSliceElemValue = &ev } } // Make and use a new array. arr := make([]interface{}, len(typedYAMLObj)) for i, v := range typedYAMLObj { arr[i], err = convertToJSONableObject(v, jsonSliceElemValue) if err != nil { return nil, err } } return arr, nil default: // If the target type is a string and the YAML type is a number, // convert the YAML type to a string. if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String { // Based on my reading of go-yaml, it may return int, int64, // float64, or uint64. var s string switch typedVal := typedYAMLObj.(type) { case int: s = strconv.FormatInt(int64(typedVal), 10) case int64: s = strconv.FormatInt(typedVal, 10) case float64: s = strconv.FormatFloat(typedVal, 'g', -1, 32) case uint64: s = strconv.FormatUint(typedVal, 10) case bool: if typedVal { s = "true" } else { s = "false" } } if len(s) > 0 { yamlObj = interface{}(s) } } return yamlObj, nil } return nil, nil } ================================================ FILE: vendor/github.com/ghodss/yaml/yaml_test.go ================================================ package yaml import ( "fmt" "math" "reflect" "strconv" "testing" ) type MarshalTest struct { A string B int64 // Would like to test float64, but it's not supported in go-yaml. // (See https://github.com/go-yaml/yaml/issues/83.) C float32 } func TestMarshal(t *testing.T) { f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32) s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32} e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", math.MaxInt64, f32String)) y, err := Marshal(s) if err != nil { t.Errorf("error marshaling YAML: %v", err) } if !reflect.DeepEqual(y, e) { t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v", string(e), string(y)) } } type UnmarshalString struct { A string True string } type UnmarshalStringMap struct { A map[string]string } type UnmarshalNestedString struct { A NestedString } type NestedString struct { A string } type UnmarshalSlice struct { A []NestedSlice } type NestedSlice struct { B string C *string } func TestUnmarshal(t *testing.T) { y := []byte("a: 1") s1 := UnmarshalString{} e1 := UnmarshalString{A: "1"} unmarshal(t, y, &s1, &e1) y = []byte("a: true") s1 = UnmarshalString{} e1 = UnmarshalString{A: "true"} unmarshal(t, y, &s1, &e1) y = []byte("true: 1") s1 = UnmarshalString{} e1 = UnmarshalString{True: "1"} unmarshal(t, y, &s1, &e1) y = []byte("a:\n a: 1") s2 := UnmarshalNestedString{} e2 := UnmarshalNestedString{NestedString{"1"}} unmarshal(t, y, &s2, &e2) y = []byte("a:\n - b: abc\n c: def\n - b: 123\n c: 456\n") s3 := UnmarshalSlice{} e3 := UnmarshalSlice{[]NestedSlice{NestedSlice{"abc", strPtr("def")}, NestedSlice{"123", strPtr("456")}}} unmarshal(t, y, &s3, &e3) y = []byte("a:\n b: 1") s4 := UnmarshalStringMap{} e4 := UnmarshalStringMap{map[string]string{"b": "1"}} unmarshal(t, y, &s4, &e4) } func unmarshal(t *testing.T, y []byte, s, e interface{}) { err := Unmarshal(y, s) if err != nil { t.Errorf("error unmarshaling YAML: %v", err) } if !reflect.DeepEqual(s, e) { t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", e, s) } } type Case struct { input string output string // By default we test that reversing the output == input. But if there is a // difference in the reversed output, you can optionally specify it here. reverse *string } type RunType int const ( RunTypeJSONToYAML RunType = iota RunTypeYAMLToJSON ) func TestJSONToYAML(t *testing.T) { cases := []Case{ { `{"t":"a"}`, "t: a\n", nil, }, { `{"t":null}`, "t: null\n", nil, }, } runCases(t, RunTypeJSONToYAML, cases) } func TestYAMLToJSON(t *testing.T) { cases := []Case{ { "t: a\n", `{"t":"a"}`, nil, }, { "t: \n", `{"t":null}`, strPtr("t: null\n"), }, { "t: null\n", `{"t":null}`, nil, }, { "1: a\n", `{"1":"a"}`, strPtr("\"1\": a\n"), }, { "1000000000000000000000000000000000000: a\n", `{"1e+36":"a"}`, strPtr("\"1e+36\": a\n"), }, { "1e+36: a\n", `{"1e+36":"a"}`, strPtr("\"1e+36\": a\n"), }, { "\"1e+36\": a\n", `{"1e+36":"a"}`, nil, }, { "\"1.2\": a\n", `{"1.2":"a"}`, nil, }, { "- t: a\n", `[{"t":"a"}]`, nil, }, { "- t: a\n" + "- t:\n" + " b: 1\n" + " c: 2\n", `[{"t":"a"},{"t":{"b":1,"c":2}}]`, nil, }, { `[{t: a}, {t: {b: 1, c: 2}}]`, `[{"t":"a"},{"t":{"b":1,"c":2}}]`, strPtr("- t: a\n" + "- t:\n" + " b: 1\n" + " c: 2\n"), }, { "- t: \n", `[{"t":null}]`, strPtr("- t: null\n"), }, { "- t: null\n", `[{"t":null}]`, nil, }, } // Cases that should produce errors. _ = []Case{ { "~: a", `{"null":"a"}`, nil, }, { "a: !!binary gIGC\n", "{\"a\":\"\x80\x81\x82\"}", nil, }, } runCases(t, RunTypeYAMLToJSON, cases) } func runCases(t *testing.T, runType RunType, cases []Case) { var f func([]byte) ([]byte, error) var invF func([]byte) ([]byte, error) var msg string var invMsg string if runType == RunTypeJSONToYAML { f = JSONToYAML invF = YAMLToJSON msg = "JSON to YAML" invMsg = "YAML back to JSON" } else { f = YAMLToJSON invF = JSONToYAML msg = "YAML to JSON" invMsg = "JSON back to YAML" } for _, c := range cases { // Convert the string. t.Logf("converting %s\n", c.input) output, err := f([]byte(c.input)) if err != nil { t.Errorf("Failed to convert %s, input: `%s`, err: %v", msg, c.input, err) } // Check it against the expected output. if string(output) != c.output { t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", msg, c.input, c.output, string(output)) } // Set the string that we will compare the reversed output to. reverse := c.input // If a special reverse string was specified, use that instead. if c.reverse != nil { reverse = *c.reverse } // Reverse the output. input, err := invF(output) if err != nil { t.Errorf("Failed to convert %s, input: `%s`, err: %v", invMsg, string(output), err) } // Check the reverse is equal to the input (or to *c.reverse). if string(input) != reverse { t.Errorf("Failed to convert %s, input: `%s`, expected `%s`, got `%s`", invMsg, string(output), reverse, string(input)) } } } // To be able to easily fill in the *Case.reverse string above. func strPtr(s string) *string { return &s } ================================================ FILE: vendor/github.com/golang/glog/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/golang/glog/README ================================================ glog ==== Leveled execution logs for Go. This is an efficient pure Go implementation of leveled logs in the manner of the open source C++ package http://code.google.com/p/google-glog By binding methods to booleans it is possible to use the log package without paying the expense of evaluating the arguments to the log. Through the -vmodule flag, the package also provides fine-grained control over logging at the file level. The comment from glog.go introduces the ideas: Package glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. It provides functions Info, Warning, Error, Fatal, plus formatting variants such as Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. Basic examples: glog.Info("Prepare to repel boarders") glog.Fatalf("Initialization failed: %s", err) See the documentation for the V function for an explanation of these examples: if glog.V(2) { glog.Info("Starting transaction...") } glog.V(2).Infoln("Processed", nItems, "elements") The repository contains an open source version of the log package used inside Google. The master copy of the source lives inside Google, not here. The code in this repo is for export only and is not itself under development. Feature requests will be ignored. Send bug reports to golang-nuts@googlegroups.com. ================================================ FILE: vendor/github.com/golang/glog/glog.go ================================================ // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 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 glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup. // It provides functions Info, Warning, Error, Fatal, plus formatting variants such as // Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags. // // Basic examples: // // glog.Info("Prepare to repel boarders") // // glog.Fatalf("Initialization failed: %s", err) // // See the documentation for the V function for an explanation of these examples: // // if glog.V(2) { // glog.Info("Starting transaction...") // } // // glog.V(2).Infoln("Processed", nItems, "elements") // // Log output is buffered and written periodically using Flush. Programs // should call Flush before exiting to guarantee all log output is written. // // By default, all log statements write to files in a temporary directory. // This package provides several flags that modify this behavior. // As a result, flag.Parse must be called before any logging is done. // // -logtostderr=false // Logs are written to standard error instead of to files. // -alsologtostderr=false // Logs are written to standard error as well as to files. // -stderrthreshold=ERROR // Log events at or above this severity are logged to standard // error as well as to files. // -log_dir="" // Log files will be written to this directory instead of the // default temporary directory. // // Other flags provide aids to debugging. // // -log_backtrace_at="" // When set to a file and line number holding a logging statement, // such as // -log_backtrace_at=gopherflakes.go:234 // a stack trace will be written to the Info log whenever execution // hits that statement. (Unlike with -vmodule, the ".go" must be // present.) // -v=0 // Enable V-leveled logging at the specified level. // -vmodule="" // The syntax of the argument is a comma-separated list of pattern=N, // where pattern is a literal file name (minus the ".go" suffix) or // "glob" pattern and N is a V level. For instance, // -vmodule=gopher*=3 // sets the V level to 3 in all Go files whose names begin "gopher". // package glog import ( "bufio" "bytes" "errors" "flag" "fmt" "io" stdLog "log" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "sync/atomic" "time" ) // severity identifies the sort of log: info, warning etc. It also implements // the flag.Value interface. The -stderrthreshold flag is of type severity and // should be modified only through the flag.Value interface. The values match // the corresponding constants in C++. type severity int32 // sync/atomic int32 // These constants identify the log levels in order of increasing severity. // A message written to a high-severity log file is also written to each // lower-severity log file. const ( infoLog severity = iota warningLog errorLog fatalLog numSeverity = 4 ) const severityChar = "IWEF" var severityName = []string{ infoLog: "INFO", warningLog: "WARNING", errorLog: "ERROR", fatalLog: "FATAL", } // get returns the value of the severity. func (s *severity) get() severity { return severity(atomic.LoadInt32((*int32)(s))) } // set sets the value of the severity. func (s *severity) set(val severity) { atomic.StoreInt32((*int32)(s), int32(val)) } // String is part of the flag.Value interface. func (s *severity) String() string { return strconv.FormatInt(int64(*s), 10) } // Get is part of the flag.Value interface. func (s *severity) Get() interface{} { return *s } // Set is part of the flag.Value interface. func (s *severity) Set(value string) error { var threshold severity // Is it a known name? if v, ok := severityByName(value); ok { threshold = v } else { v, err := strconv.Atoi(value) if err != nil { return err } threshold = severity(v) } logging.stderrThreshold.set(threshold) return nil } func severityByName(s string) (severity, bool) { s = strings.ToUpper(s) for i, name := range severityName { if name == s { return severity(i), true } } return 0, false } // OutputStats tracks the number of output lines and bytes written. type OutputStats struct { lines int64 bytes int64 } // Lines returns the number of lines written. func (s *OutputStats) Lines() int64 { return atomic.LoadInt64(&s.lines) } // Bytes returns the number of bytes written. func (s *OutputStats) Bytes() int64 { return atomic.LoadInt64(&s.bytes) } // Stats tracks the number of lines of output and number of bytes // per severity level. Values must be read with atomic.LoadInt64. var Stats struct { Info, Warning, Error OutputStats } var severityStats = [numSeverity]*OutputStats{ infoLog: &Stats.Info, warningLog: &Stats.Warning, errorLog: &Stats.Error, } // Level is exported because it appears in the arguments to V and is // the type of the v flag, which can be set programmatically. // It's a distinct type because we want to discriminate it from logType. // Variables of type level are only changed under logging.mu. // The -v flag is read only with atomic ops, so the state of the logging // module is consistent. // Level is treated as a sync/atomic int32. // Level specifies a level of verbosity for V logs. *Level implements // flag.Value; the -v flag is of type Level and should be modified // only through the flag.Value interface. type Level int32 // get returns the value of the Level. func (l *Level) get() Level { return Level(atomic.LoadInt32((*int32)(l))) } // set sets the value of the Level. func (l *Level) set(val Level) { atomic.StoreInt32((*int32)(l), int32(val)) } // String is part of the flag.Value interface. func (l *Level) String() string { return strconv.FormatInt(int64(*l), 10) } // Get is part of the flag.Value interface. func (l *Level) Get() interface{} { return *l } // Set is part of the flag.Value interface. func (l *Level) Set(value string) error { v, err := strconv.Atoi(value) if err != nil { return err } logging.mu.Lock() defer logging.mu.Unlock() logging.setVState(Level(v), logging.vmodule.filter, false) return nil } // moduleSpec represents the setting of the -vmodule flag. type moduleSpec struct { filter []modulePat } // modulePat contains a filter for the -vmodule flag. // It holds a verbosity level and a file pattern to match. type modulePat struct { pattern string literal bool // The pattern is a literal string level Level } // match reports whether the file matches the pattern. It uses a string // comparison if the pattern contains no metacharacters. func (m *modulePat) match(file string) bool { if m.literal { return file == m.pattern } match, _ := filepath.Match(m.pattern, file) return match } func (m *moduleSpec) String() string { // Lock because the type is not atomic. TODO: clean this up. logging.mu.Lock() defer logging.mu.Unlock() var b bytes.Buffer for i, f := range m.filter { if i > 0 { b.WriteRune(',') } fmt.Fprintf(&b, "%s=%d", f.pattern, f.level) } return b.String() } // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the // struct is not exported. func (m *moduleSpec) Get() interface{} { return nil } var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N") // Syntax: -vmodule=recordio=2,file=1,gfs*=3 func (m *moduleSpec) Set(value string) error { var filter []modulePat for _, pat := range strings.Split(value, ",") { if len(pat) == 0 { // Empty strings such as from a trailing comma can be ignored. continue } patLev := strings.Split(pat, "=") if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 { return errVmoduleSyntax } pattern := patLev[0] v, err := strconv.Atoi(patLev[1]) if err != nil { return errors.New("syntax error: expect comma-separated list of filename=N") } if v < 0 { return errors.New("negative value for vmodule level") } if v == 0 { continue // Ignore. It's harmless but no point in paying the overhead. } // TODO: check syntax of filter? filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)}) } logging.mu.Lock() defer logging.mu.Unlock() logging.setVState(logging.verbosity, filter, true) return nil } // isLiteral reports whether the pattern is a literal string, that is, has no metacharacters // that require filepath.Match to be called to match the pattern. func isLiteral(pattern string) bool { return !strings.ContainsAny(pattern, `\*?[]`) } // traceLocation represents the setting of the -log_backtrace_at flag. type traceLocation struct { file string line int } // isSet reports whether the trace location has been specified. // logging.mu is held. func (t *traceLocation) isSet() bool { return t.line > 0 } // match reports whether the specified file and line matches the trace location. // The argument file name is the full path, not the basename specified in the flag. // logging.mu is held. func (t *traceLocation) match(file string, line int) bool { if t.line != line { return false } if i := strings.LastIndex(file, "/"); i >= 0 { file = file[i+1:] } return t.file == file } func (t *traceLocation) String() string { // Lock because the type is not atomic. TODO: clean this up. logging.mu.Lock() defer logging.mu.Unlock() return fmt.Sprintf("%s:%d", t.file, t.line) } // Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the // struct is not exported func (t *traceLocation) Get() interface{} { return nil } var errTraceSyntax = errors.New("syntax error: expect file.go:234") // Syntax: -log_backtrace_at=gopherflakes.go:234 // Note that unlike vmodule the file extension is included here. func (t *traceLocation) Set(value string) error { if value == "" { // Unset. t.line = 0 t.file = "" } fields := strings.Split(value, ":") if len(fields) != 2 { return errTraceSyntax } file, line := fields[0], fields[1] if !strings.Contains(file, ".") { return errTraceSyntax } v, err := strconv.Atoi(line) if err != nil { return errTraceSyntax } if v <= 0 { return errors.New("negative or zero value for level") } logging.mu.Lock() defer logging.mu.Unlock() t.line = v t.file = file return nil } // flushSyncWriter is the interface satisfied by logging destinations. type flushSyncWriter interface { Flush() error Sync() error io.Writer } func init() { flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files") flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files") flag.Var(&logging.verbosity, "v", "log level for V logs") flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr") flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging") flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace") // Default stderrThreshold is ERROR. logging.stderrThreshold = errorLog logging.setVState(0, nil, false) go logging.flushDaemon() } // Flush flushes all pending log I/O. func Flush() { logging.lockAndFlushAll() } // loggingT collects all the global state of the logging setup. type loggingT struct { // Boolean flags. Not handled atomically because the flag.Value interface // does not let us avoid the =true, and that shorthand is necessary for // compatibility. TODO: does this matter enough to fix? Seems unlikely. toStderr bool // The -logtostderr flag. alsoToStderr bool // The -alsologtostderr flag. // Level flag. Handled atomically. stderrThreshold severity // The -stderrthreshold flag. // freeList is a list of byte buffers, maintained under freeListMu. freeList *buffer // freeListMu maintains the free list. It is separate from the main mutex // so buffers can be grabbed and printed to without holding the main lock, // for better parallelization. freeListMu sync.Mutex // mu protects the remaining elements of this structure and is // used to synchronize logging. mu sync.Mutex // file holds writer for each of the log types. file [numSeverity]flushSyncWriter // pcs is used in V to avoid an allocation when computing the caller's PC. pcs [1]uintptr // vmap is a cache of the V Level for each V() call site, identified by PC. // It is wiped whenever the vmodule flag changes state. vmap map[uintptr]Level // filterLength stores the length of the vmodule filter chain. If greater // than zero, it means vmodule is enabled. It may be read safely // using sync.LoadInt32, but is only modified under mu. filterLength int32 // traceLocation is the state of the -log_backtrace_at flag. traceLocation traceLocation // These flags are modified only under lock, although verbosity may be fetched // safely using atomic.LoadInt32. vmodule moduleSpec // The state of the -vmodule flag. verbosity Level // V logging level, the value of the -v flag/ } // buffer holds a byte Buffer for reuse. The zero value is ready for use. type buffer struct { bytes.Buffer tmp [64]byte // temporary byte array for creating headers. next *buffer } var logging loggingT // setVState sets a consistent state for V logging. // l.mu is held. func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) { // Turn verbosity off so V will not fire while we are in transition. logging.verbosity.set(0) // Ditto for filter length. atomic.StoreInt32(&logging.filterLength, 0) // Set the new filters and wipe the pc->Level map if the filter has changed. if setFilter { logging.vmodule.filter = filter logging.vmap = make(map[uintptr]Level) } // Things are consistent now, so enable filtering and verbosity. // They are enabled in order opposite to that in V. atomic.StoreInt32(&logging.filterLength, int32(len(filter))) logging.verbosity.set(verbosity) } // getBuffer returns a new, ready-to-use buffer. func (l *loggingT) getBuffer() *buffer { l.freeListMu.Lock() b := l.freeList if b != nil { l.freeList = b.next } l.freeListMu.Unlock() if b == nil { b = new(buffer) } else { b.next = nil b.Reset() } return b } // putBuffer returns a buffer to the free list. func (l *loggingT) putBuffer(b *buffer) { if b.Len() >= 256 { // Let big buffers die a natural death. return } l.freeListMu.Lock() b.next = l.freeList l.freeList = b l.freeListMu.Unlock() } var timeNow = time.Now // Stubbed out for testing. /* header formats a log header as defined by the C++ implementation. It returns a buffer containing the formatted header and the user's file and line number. The depth specifies how many stack frames above lives the source line to be identified in the log message. Log lines have this form: Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg... where the fields are defined as follows: L A single character, representing the log level (eg 'I' for INFO) mm The month (zero padded; ie May is '05') dd The day (zero padded) hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds threadid The space-padded thread ID as returned by GetTID() file The file name line The line number msg The user-supplied message */ func (l *loggingT) header(s severity, depth int) (*buffer, string, int) { _, file, line, ok := runtime.Caller(3 + depth) if !ok { file = "???" line = 1 } else { slash := strings.LastIndex(file, "/") if slash >= 0 { file = file[slash+1:] } } return l.formatHeader(s, file, line), file, line } // formatHeader formats a log header using the provided file name and line number. func (l *loggingT) formatHeader(s severity, file string, line int) *buffer { now := timeNow() if line < 0 { line = 0 // not a real line number, but acceptable to someDigits } if s > fatalLog { s = infoLog // for safety. } buf := l.getBuffer() // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand. // It's worth about 3X. Fprintf is hard. _, month, day := now.Date() hour, minute, second := now.Clock() // Lmmdd hh:mm:ss.uuuuuu threadid file:line] buf.tmp[0] = severityChar[s] buf.twoDigits(1, int(month)) buf.twoDigits(3, day) buf.tmp[5] = ' ' buf.twoDigits(6, hour) buf.tmp[8] = ':' buf.twoDigits(9, minute) buf.tmp[11] = ':' buf.twoDigits(12, second) buf.tmp[14] = '.' buf.nDigits(6, 15, now.Nanosecond()/1000, '0') buf.tmp[21] = ' ' buf.nDigits(7, 22, pid, ' ') // TODO: should be TID buf.tmp[29] = ' ' buf.Write(buf.tmp[:30]) buf.WriteString(file) buf.tmp[0] = ':' n := buf.someDigits(1, line) buf.tmp[n+1] = ']' buf.tmp[n+2] = ' ' buf.Write(buf.tmp[:n+3]) return buf } // Some custom tiny helper functions to print the log header efficiently. const digits = "0123456789" // twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i]. func (buf *buffer) twoDigits(i, d int) { buf.tmp[i+1] = digits[d%10] d /= 10 buf.tmp[i] = digits[d%10] } // nDigits formats an n-digit integer at buf.tmp[i], // padding with pad on the left. // It assumes d >= 0. func (buf *buffer) nDigits(n, i, d int, pad byte) { j := n - 1 for ; j >= 0 && d > 0; j-- { buf.tmp[i+j] = digits[d%10] d /= 10 } for ; j >= 0; j-- { buf.tmp[i+j] = pad } } // someDigits formats a zero-prefixed variable-width integer at buf.tmp[i]. func (buf *buffer) someDigits(i, d int) int { // Print into the top, then copy down. We know there's space for at least // a 10-digit number. j := len(buf.tmp) for { j-- buf.tmp[j] = digits[d%10] d /= 10 if d == 0 { break } } return copy(buf.tmp[i:], buf.tmp[j:]) } func (l *loggingT) println(s severity, args ...interface{}) { buf, file, line := l.header(s, 0) fmt.Fprintln(buf, args...) l.output(s, buf, file, line, false) } func (l *loggingT) print(s severity, args ...interface{}) { l.printDepth(s, 1, args...) } func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) { buf, file, line := l.header(s, depth) fmt.Fprint(buf, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, buf, file, line, false) } func (l *loggingT) printf(s severity, format string, args ...interface{}) { buf, file, line := l.header(s, 0) fmt.Fprintf(buf, format, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, buf, file, line, false) } // printWithFileLine behaves like print but uses the provided file and line number. If // alsoLogToStderr is true, the log message always appears on standard error; it // will also appear in the log file unless --logtostderr is set. func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) { buf := l.formatHeader(s, file, line) fmt.Fprint(buf, args...) if buf.Bytes()[buf.Len()-1] != '\n' { buf.WriteByte('\n') } l.output(s, buf, file, line, alsoToStderr) } // output writes the data to the log files and releases the buffer. func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) { l.mu.Lock() if l.traceLocation.isSet() { if l.traceLocation.match(file, line) { buf.Write(stacks(false)) } } data := buf.Bytes() if l.toStderr { os.Stderr.Write(data) } else { if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() { os.Stderr.Write(data) } if l.file[s] == nil { if err := l.createFiles(s); err != nil { os.Stderr.Write(data) // Make sure the message appears somewhere. l.exit(err) } } switch s { case fatalLog: l.file[fatalLog].Write(data) fallthrough case errorLog: l.file[errorLog].Write(data) fallthrough case warningLog: l.file[warningLog].Write(data) fallthrough case infoLog: l.file[infoLog].Write(data) } } if s == fatalLog { // If we got here via Exit rather than Fatal, print no stacks. if atomic.LoadUint32(&fatalNoStacks) > 0 { l.mu.Unlock() timeoutFlush(10 * time.Second) os.Exit(1) } // Dump all goroutine stacks before exiting. // First, make sure we see the trace for the current goroutine on standard error. // If -logtostderr has been specified, the loop below will do that anyway // as the first stack in the full dump. if !l.toStderr { os.Stderr.Write(stacks(false)) } // Write the stack trace for all goroutines to the files. trace := stacks(true) logExitFunc = func(error) {} // If we get a write error, we'll still exit below. for log := fatalLog; log >= infoLog; log-- { if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set. f.Write(trace) } } l.mu.Unlock() timeoutFlush(10 * time.Second) os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway. } l.putBuffer(buf) l.mu.Unlock() if stats := severityStats[s]; stats != nil { atomic.AddInt64(&stats.lines, 1) atomic.AddInt64(&stats.bytes, int64(len(data))) } } // timeoutFlush calls Flush and returns when it completes or after timeout // elapses, whichever happens first. This is needed because the hooks invoked // by Flush may deadlock when glog.Fatal is called from a hook that holds // a lock. func timeoutFlush(timeout time.Duration) { done := make(chan bool, 1) go func() { Flush() // calls logging.lockAndFlushAll() done <- true }() select { case <-done: case <-time.After(timeout): fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout) } } // stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines. func stacks(all bool) []byte { // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though. n := 10000 if all { n = 100000 } var trace []byte for i := 0; i < 5; i++ { trace = make([]byte, n) nbytes := runtime.Stack(trace, all) if nbytes < len(trace) { return trace[:nbytes] } n *= 2 } return trace } // logExitFunc provides a simple mechanism to override the default behavior // of exiting on error. Used in testing and to guarantee we reach a required exit // for fatal logs. Instead, exit could be a function rather than a method but that // would make its use clumsier. var logExitFunc func(error) // exit is called if there is trouble creating or writing log files. // It flushes the logs and exits the program; there's no point in hanging around. // l.mu is held. func (l *loggingT) exit(err error) { fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err) // If logExitFunc is set, we do that instead of exiting. if logExitFunc != nil { logExitFunc(err) return } l.flushAll() os.Exit(2) } // syncBuffer joins a bufio.Writer to its underlying file, providing access to the // file's Sync method and providing a wrapper for the Write method that provides log // file rotation. There are conflicting methods, so the file cannot be embedded. // l.mu is held for all its methods. type syncBuffer struct { logger *loggingT *bufio.Writer file *os.File sev severity nbytes uint64 // The number of bytes written to this file } func (sb *syncBuffer) Sync() error { return sb.file.Sync() } func (sb *syncBuffer) Write(p []byte) (n int, err error) { if sb.nbytes+uint64(len(p)) >= MaxSize { if err := sb.rotateFile(time.Now()); err != nil { sb.logger.exit(err) } } n, err = sb.Writer.Write(p) sb.nbytes += uint64(n) if err != nil { sb.logger.exit(err) } return } // rotateFile closes the syncBuffer's file and starts a new one. func (sb *syncBuffer) rotateFile(now time.Time) error { if sb.file != nil { sb.Flush() sb.file.Close() } var err error sb.file, _, err = create(severityName[sb.sev], now) sb.nbytes = 0 if err != nil { return err } sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) // Write header. var buf bytes.Buffer fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) fmt.Fprintf(&buf, "Running on machine: %s\n", host) fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n") n, err := sb.file.Write(buf.Bytes()) sb.nbytes += uint64(n) return err } // bufferSize sizes the buffer associated with each log file. It's large // so that log records can accumulate without the logging thread blocking // on disk I/O. The flushDaemon will block instead. const bufferSize = 256 * 1024 // createFiles creates all the log files for severity from sev down to infoLog. // l.mu is held. func (l *loggingT) createFiles(sev severity) error { now := time.Now() // Files are created in decreasing severity order, so as soon as we find one // has already been created, we can stop. for s := sev; s >= infoLog && l.file[s] == nil; s-- { sb := &syncBuffer{ logger: l, sev: s, } if err := sb.rotateFile(now); err != nil { return err } l.file[s] = sb } return nil } const flushInterval = 30 * time.Second // flushDaemon periodically flushes the log file buffers. func (l *loggingT) flushDaemon() { for _ = range time.NewTicker(flushInterval).C { l.lockAndFlushAll() } } // lockAndFlushAll is like flushAll but locks l.mu first. func (l *loggingT) lockAndFlushAll() { l.mu.Lock() l.flushAll() l.mu.Unlock() } // flushAll flushes all the logs and attempts to "sync" their data to disk. // l.mu is held. func (l *loggingT) flushAll() { // Flush from fatal down, in case there's trouble flushing. for s := fatalLog; s >= infoLog; s-- { file := l.file[s] if file != nil { file.Flush() // ignore error file.Sync() // ignore error } } } // CopyStandardLogTo arranges for messages written to the Go "log" package's // default logs to also appear in the Google logs for the named and lower // severities. Subsequent changes to the standard log's default output location // or format may break this behavior. // // Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not // recognized, CopyStandardLogTo panics. func CopyStandardLogTo(name string) { sev, ok := severityByName(name) if !ok { panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name)) } // Set a log format that captures the user's file and line: // d.go:23: message stdLog.SetFlags(stdLog.Lshortfile) stdLog.SetOutput(logBridge(sev)) } // logBridge provides the Write method that enables CopyStandardLogTo to connect // Go's standard logs to the logs provided by this package. type logBridge severity // Write parses the standard logging line and passes its components to the // logger for severity(lb). func (lb logBridge) Write(b []byte) (n int, err error) { var ( file = "???" line = 1 text string ) // Split "d.go:23: message" into "d.go", "23", and "message". if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 { text = fmt.Sprintf("bad log format: %s", b) } else { file = string(parts[0]) text = string(parts[2][1:]) // skip leading space line, err = strconv.Atoi(string(parts[1])) if err != nil { text = fmt.Sprintf("bad line number: %s", b) line = 1 } } // printWithFileLine with alsoToStderr=true, so standard log messages // always appear on standard error. logging.printWithFileLine(severity(lb), file, line, true, text) return len(b), nil } // setV computes and remembers the V level for a given PC // when vmodule is enabled. // File pattern matching takes the basename of the file, stripped // of its .go suffix, and uses filepath.Match, which is a little more // general than the *? matching used in C++. // l.mu is held. func (l *loggingT) setV(pc uintptr) Level { fn := runtime.FuncForPC(pc) file, _ := fn.FileLine(pc) // The file is something like /a/b/c/d.go. We want just the d. if strings.HasSuffix(file, ".go") { file = file[:len(file)-3] } if slash := strings.LastIndex(file, "/"); slash >= 0 { file = file[slash+1:] } for _, filter := range l.vmodule.filter { if filter.match(file) { l.vmap[pc] = filter.level return filter.level } } l.vmap[pc] = 0 return 0 } // Verbose is a boolean type that implements Infof (like Printf) etc. // See the documentation of V for more information. type Verbose bool // V reports whether verbosity at the call site is at least the requested level. // The returned value is a boolean of type Verbose, which implements Info, Infoln // and Infof. These methods will write to the Info log if called. // Thus, one may write either // if glog.V(2) { glog.Info("log this") } // or // glog.V(2).Info("log this") // The second form is shorter but the first is cheaper if logging is off because it does // not evaluate its arguments. // // Whether an individual call to V generates a log record depends on the setting of // the -v and --vmodule flags; both are off by default. If the level in the call to // V is at least the value of -v, or of -vmodule for the source file containing the // call, the V call will log. func V(level Level) Verbose { // This function tries hard to be cheap unless there's work to do. // The fast path is two atomic loads and compares. // Here is a cheap but safe test to see if V logging is enabled globally. if logging.verbosity.get() >= level { return Verbose(true) } // It's off globally but it vmodule may still be set. // Here is another cheap but safe test to see if vmodule is enabled. if atomic.LoadInt32(&logging.filterLength) > 0 { // Now we need a proper lock to use the logging structure. The pcs field // is shared so we must lock before accessing it. This is fairly expensive, // but if V logging is enabled we're slow anyway. logging.mu.Lock() defer logging.mu.Unlock() if runtime.Callers(2, logging.pcs[:]) == 0 { return Verbose(false) } v, ok := logging.vmap[logging.pcs[0]] if !ok { v = logging.setV(logging.pcs[0]) } return Verbose(v >= level) } return Verbose(false) } // Info is equivalent to the global Info function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Info(args ...interface{}) { if v { logging.print(infoLog, args...) } } // Infoln is equivalent to the global Infoln function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Infoln(args ...interface{}) { if v { logging.println(infoLog, args...) } } // Infof is equivalent to the global Infof function, guarded by the value of v. // See the documentation of V for usage. func (v Verbose) Infof(format string, args ...interface{}) { if v { logging.printf(infoLog, format, args...) } } // Info logs to the INFO log. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Info(args ...interface{}) { logging.print(infoLog, args...) } // InfoDepth acts as Info but uses depth to determine which call frame to log. // InfoDepth(0, "msg") is the same as Info("msg"). func InfoDepth(depth int, args ...interface{}) { logging.printDepth(infoLog, depth, args...) } // Infoln logs to the INFO log. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Infoln(args ...interface{}) { logging.println(infoLog, args...) } // Infof logs to the INFO log. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Infof(format string, args ...interface{}) { logging.printf(infoLog, format, args...) } // Warning logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Warning(args ...interface{}) { logging.print(warningLog, args...) } // WarningDepth acts as Warning but uses depth to determine which call frame to log. // WarningDepth(0, "msg") is the same as Warning("msg"). func WarningDepth(depth int, args ...interface{}) { logging.printDepth(warningLog, depth, args...) } // Warningln logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Warningln(args ...interface{}) { logging.println(warningLog, args...) } // Warningf logs to the WARNING and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Warningf(format string, args ...interface{}) { logging.printf(warningLog, format, args...) } // Error logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Error(args ...interface{}) { logging.print(errorLog, args...) } // ErrorDepth acts as Error but uses depth to determine which call frame to log. // ErrorDepth(0, "msg") is the same as Error("msg"). func ErrorDepth(depth int, args ...interface{}) { logging.printDepth(errorLog, depth, args...) } // Errorln logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Errorln(args ...interface{}) { logging.println(errorLog, args...) } // Errorf logs to the ERROR, WARNING, and INFO logs. // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Errorf(format string, args ...interface{}) { logging.printf(errorLog, format, args...) } // Fatal logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Fatal(args ...interface{}) { logging.print(fatalLog, args...) } // FatalDepth acts as Fatal but uses depth to determine which call frame to log. // FatalDepth(0, "msg") is the same as Fatal("msg"). func FatalDepth(depth int, args ...interface{}) { logging.printDepth(fatalLog, depth, args...) } // Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Println; a newline is appended if missing. func Fatalln(args ...interface{}) { logging.println(fatalLog, args...) } // Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs, // including a stack trace of all running goroutines, then calls os.Exit(255). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Fatalf(format string, args ...interface{}) { logging.printf(fatalLog, format, args...) } // fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks. // It allows Exit and relatives to use the Fatal logs. var fatalNoStacks uint32 // Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Print; a newline is appended if missing. func Exit(args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.print(fatalLog, args...) } // ExitDepth acts as Exit but uses depth to determine which call frame to log. // ExitDepth(0, "msg") is the same as Exit("msg"). func ExitDepth(depth int, args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.printDepth(fatalLog, depth, args...) } // Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). func Exitln(args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.println(fatalLog, args...) } // Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1). // Arguments are handled in the manner of fmt.Printf; a newline is appended if missing. func Exitf(format string, args ...interface{}) { atomic.StoreUint32(&fatalNoStacks, 1) logging.printf(fatalLog, format, args...) } ================================================ FILE: vendor/github.com/golang/glog/glog_file.go ================================================ // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 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. // File I/O for logs. package glog import ( "errors" "flag" "fmt" "os" "os/user" "path/filepath" "strings" "sync" "time" ) // MaxSize is the maximum size of a log file in bytes. var MaxSize uint64 = 1024 * 1024 * 1800 // logDirs lists the candidate directories for new log files. var logDirs []string // If non-empty, overrides the choice of directory in which to write logs. // See createLogDirs for the full list of possible destinations. var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") func createLogDirs() { if *logDir != "" { logDirs = append(logDirs, *logDir) } logDirs = append(logDirs, os.TempDir()) } var ( pid = os.Getpid() program = filepath.Base(os.Args[0]) host = "unknownhost" userName = "unknownuser" ) func init() { h, err := os.Hostname() if err == nil { host = shortHostname(h) } current, err := user.Current() if err == nil { userName = current.Username } // Sanitize userName since it may contain filepath separators on Windows. userName = strings.Replace(userName, `\`, "_", -1) } // shortHostname returns its argument, truncating at the first period. // For instance, given "www.google.com" it returns "www". func shortHostname(hostname string) string { if i := strings.Index(hostname, "."); i >= 0 { return hostname[:i] } return hostname } // logName returns a new log file name containing tag, with start time t, and // the name for the symlink for tag. func logName(tag string, t time.Time) (name, link string) { name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", program, host, userName, tag, t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), pid) return name, program + "." + tag } var onceLogDirs sync.Once // create creates a new log file and returns the file and its filename, which // contains tag ("INFO", "FATAL", etc.) and t. If the file is created // successfully, create also attempts to update the symlink for that tag, ignoring // errors. func create(tag string, t time.Time) (f *os.File, filename string, err error) { onceLogDirs.Do(createLogDirs) if len(logDirs) == 0 { return nil, "", errors.New("log: no log dirs") } name, link := logName(tag, t) var lastErr error for _, dir := range logDirs { fname := filepath.Join(dir, name) f, err := os.Create(fname) if err == nil { symlink := filepath.Join(dir, link) os.Remove(symlink) // ignore err os.Symlink(name, symlink) // ignore err return f, fname, nil } lastErr = err } return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) } ================================================ FILE: vendor/github.com/golang/glog/glog_test.go ================================================ // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ // // Copyright 2013 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 glog import ( "bytes" "fmt" stdLog "log" "path/filepath" "runtime" "strconv" "strings" "testing" "time" ) // Test that shortHostname works as advertised. func TestShortHostname(t *testing.T) { for hostname, expect := range map[string]string{ "": "", "host": "host", "host.google.com": "host", } { if got := shortHostname(hostname); expect != got { t.Errorf("shortHostname(%q): expected %q, got %q", hostname, expect, got) } } } // flushBuffer wraps a bytes.Buffer to satisfy flushSyncWriter. type flushBuffer struct { bytes.Buffer } func (f *flushBuffer) Flush() error { return nil } func (f *flushBuffer) Sync() error { return nil } // swap sets the log writers and returns the old array. func (l *loggingT) swap(writers [numSeverity]flushSyncWriter) (old [numSeverity]flushSyncWriter) { l.mu.Lock() defer l.mu.Unlock() old = l.file for i, w := range writers { logging.file[i] = w } return } // newBuffers sets the log writers to all new byte buffers and returns the old array. func (l *loggingT) newBuffers() [numSeverity]flushSyncWriter { return l.swap([numSeverity]flushSyncWriter{new(flushBuffer), new(flushBuffer), new(flushBuffer), new(flushBuffer)}) } // contents returns the specified log value as a string. func contents(s severity) string { return logging.file[s].(*flushBuffer).String() } // contains reports whether the string is contained in the log. func contains(s severity, str string, t *testing.T) bool { return strings.Contains(contents(s), str) } // setFlags configures the logging flags how the test expects them. func setFlags() { logging.toStderr = false } // Test that Info works as advertised. func TestInfo(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) Info("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } func TestInfoDepth(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) f := func() { InfoDepth(1, "depth-test1") } // The next three lines must stay together _, _, wantLine, _ := runtime.Caller(0) InfoDepth(0, "depth-test0") f() msgs := strings.Split(strings.TrimSuffix(contents(infoLog), "\n"), "\n") if len(msgs) != 2 { t.Fatalf("Got %d lines, expected 2", len(msgs)) } for i, m := range msgs { if !strings.HasPrefix(m, "I") { t.Errorf("InfoDepth[%d] has wrong character: %q", i, m) } w := fmt.Sprintf("depth-test%d", i) if !strings.Contains(m, w) { t.Errorf("InfoDepth[%d] missing %q: %q", i, w, m) } // pull out the line number (between : and ]) msg := m[strings.LastIndex(m, ":")+1:] x := strings.Index(msg, "]") if x < 0 { t.Errorf("InfoDepth[%d]: missing ']': %q", i, m) continue } line, err := strconv.Atoi(msg[:x]) if err != nil { t.Errorf("InfoDepth[%d]: bad line number: %q", i, m) continue } wantLine++ if wantLine != line { t.Errorf("InfoDepth[%d]: got line %d, want %d", i, line, wantLine) } } } func init() { CopyStandardLogTo("INFO") } // Test that CopyStandardLogTo panics on bad input. func TestCopyStandardLogToPanic(t *testing.T) { defer func() { if s, ok := recover().(string); !ok || !strings.Contains(s, "LOG") { t.Errorf(`CopyStandardLogTo("LOG") should have panicked: %v`, s) } }() CopyStandardLogTo("LOG") } // Test that using the standard log package logs to INFO. func TestStandardLog(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) stdLog.Print("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } // Test that the header has the correct format. func TestHeader(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) defer func(previous func() time.Time) { timeNow = previous }(timeNow) timeNow = func() time.Time { return time.Date(2006, 1, 2, 15, 4, 5, .067890e9, time.Local) } pid = 1234 Info("test") var line int format := "I0102 15:04:05.067890 1234 glog_test.go:%d] test\n" n, err := fmt.Sscanf(contents(infoLog), format, &line) if n != 1 || err != nil { t.Errorf("log format error: %d elements, error %s:\n%s", n, err, contents(infoLog)) } // Scanf treats multiple spaces as equivalent to a single space, // so check for correct space-padding also. want := fmt.Sprintf(format, line) if contents(infoLog) != want { t.Errorf("log format error: got:\n\t%q\nwant:\t%q", contents(infoLog), want) } } // Test that an Error log goes to Warning and Info. // Even in the Info log, the source character will be E, so the data should // all be identical. func TestError(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) Error("test") if !contains(errorLog, "E", t) { t.Errorf("Error has wrong character: %q", contents(errorLog)) } if !contains(errorLog, "test", t) { t.Error("Error failed") } str := contents(errorLog) if !contains(warningLog, str, t) { t.Error("Warning failed") } if !contains(infoLog, str, t) { t.Error("Info failed") } } // Test that a Warning log goes to Info. // Even in the Info log, the source character will be W, so the data should // all be identical. func TestWarning(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) Warning("test") if !contains(warningLog, "W", t) { t.Errorf("Warning has wrong character: %q", contents(warningLog)) } if !contains(warningLog, "test", t) { t.Error("Warning failed") } str := contents(warningLog) if !contains(infoLog, str, t) { t.Error("Info failed") } } // Test that a V log goes to Info. func TestV(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) logging.verbosity.Set("2") defer logging.verbosity.Set("0") V(2).Info("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } // Test that a vmodule enables a log in this file. func TestVmoduleOn(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) logging.vmodule.Set("glog_test=2") defer logging.vmodule.Set("") if !V(1) { t.Error("V not enabled for 1") } if !V(2) { t.Error("V not enabled for 2") } if V(3) { t.Error("V enabled for 3") } V(2).Info("test") if !contains(infoLog, "I", t) { t.Errorf("Info has wrong character: %q", contents(infoLog)) } if !contains(infoLog, "test", t) { t.Error("Info failed") } } // Test that a vmodule of another file does not enable a log in this file. func TestVmoduleOff(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) logging.vmodule.Set("notthisfile=2") defer logging.vmodule.Set("") for i := 1; i <= 3; i++ { if V(Level(i)) { t.Errorf("V enabled for %d", i) } } V(2).Info("test") if contents(infoLog) != "" { t.Error("V logged incorrectly") } } // vGlobs are patterns that match/don't match this file at V=2. var vGlobs = map[string]bool{ // Easy to test the numeric match here. "glog_test=1": false, // If -vmodule sets V to 1, V(2) will fail. "glog_test=2": true, "glog_test=3": true, // If -vmodule sets V to 1, V(3) will succeed. // These all use 2 and check the patterns. All are true. "*=2": true, "?l*=2": true, "????_*=2": true, "??[mno]?_*t=2": true, // These all use 2 and check the patterns. All are false. "*x=2": false, "m*=2": false, "??_*=2": false, "?[abc]?_*t=2": false, } // Test that vmodule globbing works as advertised. func testVmoduleGlob(pat string, match bool, t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) defer logging.vmodule.Set("") logging.vmodule.Set(pat) if V(2) != Verbose(match) { t.Errorf("incorrect match for %q: got %t expected %t", pat, V(2), match) } } // Test that a vmodule globbing works as advertised. func TestVmoduleGlob(t *testing.T) { for glob, match := range vGlobs { testVmoduleGlob(glob, match, t) } } func TestRollover(t *testing.T) { setFlags() var err error defer func(previous func(error)) { logExitFunc = previous }(logExitFunc) logExitFunc = func(e error) { err = e } defer func(previous uint64) { MaxSize = previous }(MaxSize) MaxSize = 512 Info("x") // Be sure we have a file. info, ok := logging.file[infoLog].(*syncBuffer) if !ok { t.Fatal("info wasn't created") } if err != nil { t.Fatalf("info has initial error: %v", err) } fname0 := info.file.Name() Info(strings.Repeat("x", int(MaxSize))) // force a rollover if err != nil { t.Fatalf("info has error after big write: %v", err) } // Make sure the next log file gets a file name with a different // time stamp. // // TODO: determine whether we need to support subsecond log // rotation. C++ does not appear to handle this case (nor does it // handle Daylight Savings Time properly). time.Sleep(1 * time.Second) Info("x") // create a new file if err != nil { t.Fatalf("error after rotation: %v", err) } fname1 := info.file.Name() if fname0 == fname1 { t.Errorf("info.f.Name did not change: %v", fname0) } if info.nbytes >= MaxSize { t.Errorf("file size was not reset: %d", info.nbytes) } } func TestLogBacktraceAt(t *testing.T) { setFlags() defer logging.swap(logging.newBuffers()) // The peculiar style of this code simplifies line counting and maintenance of the // tracing block below. var infoLine string setTraceLocation := func(file string, line int, ok bool, delta int) { if !ok { t.Fatal("could not get file:line") } _, file = filepath.Split(file) infoLine = fmt.Sprintf("%s:%d", file, line+delta) err := logging.traceLocation.Set(infoLine) if err != nil { t.Fatal("error setting log_backtrace_at: ", err) } } { // Start of tracing block. These lines know about each other's relative position. _, file, line, ok := runtime.Caller(0) setTraceLocation(file, line, ok, +2) // Two lines between Caller and Info calls. Info("we want a stack trace here") } numAppearances := strings.Count(contents(infoLog), infoLine) if numAppearances < 2 { // Need 2 appearances, one in the log header and one in the trace: // log_test.go:281: I0511 16:36:06.952398 02238 log_test.go:280] we want a stack trace here // ... // github.com/glog/glog_test.go:280 (0x41ba91) // ... // We could be more precise but that would require knowing the details // of the traceback format, which may not be dependable. t.Fatal("got no trace back; log is ", contents(infoLog)) } } func BenchmarkHeader(b *testing.B) { for i := 0; i < b.N; i++ { buf, _, _ := logging.header(infoLog, 0) logging.putBuffer(buf) } } ================================================ FILE: vendor/github.com/golang/groupcache/.gitignore ================================================ *~ ================================================ FILE: vendor/github.com/golang/groupcache/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/golang/groupcache/README.md ================================================ # groupcache ## Summary groupcache is a caching and cache-filling library, intended as a replacement for memcached in many cases. For API docs and examples, see http://godoc.org/github.com/golang/groupcache ## Comparison to memcached ### **Like memcached**, groupcache: * shards by key to select which peer is responsible for that key ### **Unlike memcached**, groupcache: * does not require running a separate set of servers, thus massively reducing deployment/configuration pain. groupcache is a client library as well as a server. It connects to its own peers. * comes with a cache filling mechanism. Whereas memcached just says "Sorry, cache miss", often resulting in a thundering herd of database (or whatever) loads from an unbounded number of clients (which has resulted in several fun outages), groupcache coordinates cache fills such that only one load in one process of an entire replicated set of processes populates the cache, then multiplexes the loaded value to all callers. * does not support versioned values. If key "foo" is value "bar", key "foo" must always be "bar". There are neither cache expiration times, nor explicit cache evictions. Thus there is also no CAS, nor Increment/Decrement. This also means that groupcache.... * ... supports automatic mirroring of super-hot items to multiple processes. This prevents memcached hot spotting where a machine's CPU and/or NIC are overloaded by very popular keys/values. * is currently only available for Go. It's very unlikely that I (bradfitz@) will port the code to any other language. ## Loading process In a nutshell, a groupcache lookup of **Get("foo")** looks like: (On machine #5 of a set of N machines running the same code) 1. Is the value of "foo" in local memory because it's super hot? If so, use it. 2. Is the value of "foo" in local memory because peer #5 (the current peer) is the owner of it? If so, use it. 3. Amongst all the peers in my set of N, am I the owner of the key "foo"? (e.g. does it consistent hash to 5?) If so, load it. If other callers come in, via the same process or via RPC requests from peers, they block waiting for the load to finish and get the same answer. If not, RPC to the peer that's the owner and get the answer. If the RPC fails, just load it locally (still with local dup suppression). ## Users groupcache is in production use by dl.google.com (its original user), parts of Blogger, parts of Google Code, parts of Google Fiber, parts of Google production monitoring systems, etc. ## Presentations See http://talks.golang.org/2013/oscon-dl.slide ## Help Use the golang-nuts mailing list for any discussion or questions. ================================================ FILE: vendor/github.com/golang/groupcache/byteview.go ================================================ /* Copyright 2012 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. */ package groupcache import ( "bytes" "errors" "io" "strings" ) // A ByteView holds an immutable view of bytes. // Internally it wraps either a []byte or a string, // but that detail is invisible to callers. // // A ByteView is meant to be used as a value type, not // a pointer (like a time.Time). type ByteView struct { // If b is non-nil, b is used, else s is used. b []byte s string } // Len returns the view's length. func (v ByteView) Len() int { if v.b != nil { return len(v.b) } return len(v.s) } // ByteSlice returns a copy of the data as a byte slice. func (v ByteView) ByteSlice() []byte { if v.b != nil { return cloneBytes(v.b) } return []byte(v.s) } // String returns the data as a string, making a copy if necessary. func (v ByteView) String() string { if v.b != nil { return string(v.b) } return v.s } // At returns the byte at index i. func (v ByteView) At(i int) byte { if v.b != nil { return v.b[i] } return v.s[i] } // Slice slices the view between the provided from and to indices. func (v ByteView) Slice(from, to int) ByteView { if v.b != nil { return ByteView{b: v.b[from:to]} } return ByteView{s: v.s[from:to]} } // SliceFrom slices the view from the provided index until the end. func (v ByteView) SliceFrom(from int) ByteView { if v.b != nil { return ByteView{b: v.b[from:]} } return ByteView{s: v.s[from:]} } // Copy copies b into dest and returns the number of bytes copied. func (v ByteView) Copy(dest []byte) int { if v.b != nil { return copy(dest, v.b) } return copy(dest, v.s) } // Equal returns whether the bytes in b are the same as the bytes in // b2. func (v ByteView) Equal(b2 ByteView) bool { if b2.b == nil { return v.EqualString(b2.s) } return v.EqualBytes(b2.b) } // EqualString returns whether the bytes in b are the same as the bytes // in s. func (v ByteView) EqualString(s string) bool { if v.b == nil { return v.s == s } l := v.Len() if len(s) != l { return false } for i, bi := range v.b { if bi != s[i] { return false } } return true } // EqualBytes returns whether the bytes in b are the same as the bytes // in b2. func (v ByteView) EqualBytes(b2 []byte) bool { if v.b != nil { return bytes.Equal(v.b, b2) } l := v.Len() if len(b2) != l { return false } for i, bi := range b2 { if bi != v.s[i] { return false } } return true } // Reader returns an io.ReadSeeker for the bytes in v. func (v ByteView) Reader() io.ReadSeeker { if v.b != nil { return bytes.NewReader(v.b) } return strings.NewReader(v.s) } // ReadAt implements io.ReaderAt on the bytes in v. func (v ByteView) ReadAt(p []byte, off int64) (n int, err error) { if off < 0 { return 0, errors.New("view: invalid offset") } if off >= int64(v.Len()) { return 0, io.EOF } n = v.SliceFrom(int(off)).Copy(p) if n < len(p) { err = io.EOF } return } ================================================ FILE: vendor/github.com/golang/groupcache/byteview_test.go ================================================ /* Copyright 2012 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. */ package groupcache import ( "fmt" "io" "io/ioutil" "testing" ) func TestByteView(t *testing.T) { for _, s := range []string{"", "x", "yy"} { for _, v := range []ByteView{of([]byte(s)), of(s)} { name := fmt.Sprintf("string %q, view %+v", s, v) if v.Len() != len(s) { t.Errorf("%s: Len = %d; want %d", name, v.Len(), len(s)) } if v.String() != s { t.Errorf("%s: String = %q; want %q", name, v.String(), s) } var longDest [3]byte if n := v.Copy(longDest[:]); n != len(s) { t.Errorf("%s: long Copy = %d; want %d", name, n, len(s)) } var shortDest [1]byte if n := v.Copy(shortDest[:]); n != min(len(s), 1) { t.Errorf("%s: short Copy = %d; want %d", name, n, min(len(s), 1)) } if got, err := ioutil.ReadAll(v.Reader()); err != nil || string(got) != s { t.Errorf("%s: Reader = %q, %v; want %q", name, got, err, s) } if got, err := ioutil.ReadAll(io.NewSectionReader(v, 0, int64(len(s)))); err != nil || string(got) != s { t.Errorf("%s: SectionReader of ReaderAt = %q, %v; want %q", name, got, err, s) } } } } // of returns a byte view of the []byte or string in x. func of(x interface{}) ByteView { if bytes, ok := x.([]byte); ok { return ByteView{b: bytes} } return ByteView{s: x.(string)} } func TestByteViewEqual(t *testing.T) { tests := []struct { a interface{} // string or []byte b interface{} // string or []byte want bool }{ {"x", "x", true}, {"x", "y", false}, {"x", "yy", false}, {[]byte("x"), []byte("x"), true}, {[]byte("x"), []byte("y"), false}, {[]byte("x"), []byte("yy"), false}, {[]byte("x"), "x", true}, {[]byte("x"), "y", false}, {[]byte("x"), "yy", false}, {"x", []byte("x"), true}, {"x", []byte("y"), false}, {"x", []byte("yy"), false}, } for i, tt := range tests { va := of(tt.a) if bytes, ok := tt.b.([]byte); ok { if got := va.EqualBytes(bytes); got != tt.want { t.Errorf("%d. EqualBytes = %v; want %v", i, got, tt.want) } } else { if got := va.EqualString(tt.b.(string)); got != tt.want { t.Errorf("%d. EqualString = %v; want %v", i, got, tt.want) } } if got := va.Equal(of(tt.b)); got != tt.want { t.Errorf("%d. Equal = %v; want %v", i, got, tt.want) } } } func TestByteViewSlice(t *testing.T) { tests := []struct { in string from int to interface{} // nil to mean the end (SliceFrom); else int want string }{ { in: "abc", from: 1, to: 2, want: "b", }, { in: "abc", from: 1, want: "bc", }, { in: "abc", to: 2, want: "ab", }, } for i, tt := range tests { for _, v := range []ByteView{of([]byte(tt.in)), of(tt.in)} { name := fmt.Sprintf("test %d, view %+v", i, v) if tt.to != nil { v = v.Slice(tt.from, tt.to.(int)) } else { v = v.SliceFrom(tt.from) } if v.String() != tt.want { t.Errorf("%s: got %q; want %q", name, v.String(), tt.want) } } } } func min(a, b int) int { if a < b { return a } return b } ================================================ FILE: vendor/github.com/golang/groupcache/consistenthash/consistenthash.go ================================================ /* Copyright 2013 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. */ // Package consistenthash provides an implementation of a ring hash. package consistenthash import ( "hash/crc32" "sort" "strconv" ) type Hash func(data []byte) uint32 type Map struct { hash Hash replicas int keys []int // Sorted hashMap map[int]string } func New(replicas int, fn Hash) *Map { m := &Map{ replicas: replicas, hash: fn, hashMap: make(map[int]string), } if m.hash == nil { m.hash = crc32.ChecksumIEEE } return m } // Returns true if there are no items available. func (m *Map) IsEmpty() bool { return len(m.keys) == 0 } // Adds some keys to the hash. func (m *Map) Add(keys ...string) { for _, key := range keys { for i := 0; i < m.replicas; i++ { hash := int(m.hash([]byte(strconv.Itoa(i) + key))) m.keys = append(m.keys, hash) m.hashMap[hash] = key } } sort.Ints(m.keys) } // Gets the closest item in the hash to the provided key. func (m *Map) Get(key string) string { if m.IsEmpty() { return "" } hash := int(m.hash([]byte(key))) // Binary search for appropriate replica. idx := sort.Search(len(m.keys), func(i int) bool { return m.keys[i] >= hash }) // Means we have cycled back to the first replica. if idx == len(m.keys) { idx = 0 } return m.hashMap[m.keys[idx]] } ================================================ FILE: vendor/github.com/golang/groupcache/consistenthash/consistenthash_test.go ================================================ /* Copyright 2013 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. */ package consistenthash import ( "fmt" "strconv" "testing" ) func TestHashing(t *testing.T) { // Override the hash function to return easier to reason about values. Assumes // the keys can be converted to an integer. hash := New(3, func(key []byte) uint32 { i, err := strconv.Atoi(string(key)) if err != nil { panic(err) } return uint32(i) }) // Given the above hash function, this will give replicas with "hashes": // 2, 4, 6, 12, 14, 16, 22, 24, 26 hash.Add("6", "4", "2") testCases := map[string]string{ "2": "2", "11": "2", "23": "4", "27": "2", } for k, v := range testCases { if hash.Get(k) != v { t.Errorf("Asking for %s, should have yielded %s", k, v) } } // Adds 8, 18, 28 hash.Add("8") // 27 should now map to 8. testCases["27"] = "8" for k, v := range testCases { if hash.Get(k) != v { t.Errorf("Asking for %s, should have yielded %s", k, v) } } } func TestConsistency(t *testing.T) { hash1 := New(1, nil) hash2 := New(1, nil) hash1.Add("Bill", "Bob", "Bonny") hash2.Add("Bob", "Bonny", "Bill") if hash1.Get("Ben") != hash2.Get("Ben") { t.Errorf("Fetching 'Ben' from both hashes should be the same") } hash2.Add("Becky", "Ben", "Bobby") if hash1.Get("Ben") != hash2.Get("Ben") || hash1.Get("Bob") != hash2.Get("Bob") || hash1.Get("Bonny") != hash2.Get("Bonny") { t.Errorf("Direct matches should always return the same entry") } } func BenchmarkGet8(b *testing.B) { benchmarkGet(b, 8) } func BenchmarkGet32(b *testing.B) { benchmarkGet(b, 32) } func BenchmarkGet128(b *testing.B) { benchmarkGet(b, 128) } func BenchmarkGet512(b *testing.B) { benchmarkGet(b, 512) } func benchmarkGet(b *testing.B, shards int) { hash := New(50, nil) var buckets []string for i := 0; i < shards; i++ { buckets = append(buckets, fmt.Sprintf("shard-%d", i)) } hash.Add(buckets...) b.ResetTimer() for i := 0; i < b.N; i++ { hash.Get(buckets[i&(shards-1)]) } } ================================================ FILE: vendor/github.com/golang/groupcache/groupcache.go ================================================ /* Copyright 2012 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. */ // Package groupcache provides a data loading mechanism with caching // and de-duplication that works across a set of peer processes. // // Each data Get first consults its local cache, otherwise delegates // to the requested key's canonical owner, which then checks its cache // or finally gets the data. In the common case, many concurrent // cache misses across a set of peers for the same key result in just // one cache fill. package groupcache import ( "errors" "math/rand" "strconv" "sync" "sync/atomic" pb "github.com/golang/groupcache/groupcachepb" "github.com/golang/groupcache/lru" "github.com/golang/groupcache/singleflight" ) // A Getter loads data for a key. type Getter interface { // Get returns the value identified by key, populating dest. // // The returned data must be unversioned. That is, key must // uniquely describe the loaded data, without an implicit // current time, and without relying on cache expiration // mechanisms. Get(ctx Context, key string, dest Sink) error } // A GetterFunc implements Getter with a function. type GetterFunc func(ctx Context, key string, dest Sink) error func (f GetterFunc) Get(ctx Context, key string, dest Sink) error { return f(ctx, key, dest) } var ( mu sync.RWMutex groups = make(map[string]*Group) initPeerServerOnce sync.Once initPeerServer func() ) // GetGroup returns the named group previously created with NewGroup, or // nil if there's no such group. func GetGroup(name string) *Group { mu.RLock() g := groups[name] mu.RUnlock() return g } // NewGroup creates a coordinated group-aware Getter from a Getter. // // The returned Getter tries (but does not guarantee) to run only one // Get call at once for a given key across an entire set of peer // processes. Concurrent callers both in the local process and in // other processes receive copies of the answer once the original Get // completes. // // The group name must be unique for each getter. func NewGroup(name string, cacheBytes int64, getter Getter) *Group { return newGroup(name, cacheBytes, getter, nil) } // If peers is nil, the peerPicker is called via a sync.Once to initialize it. func newGroup(name string, cacheBytes int64, getter Getter, peers PeerPicker) *Group { if getter == nil { panic("nil Getter") } mu.Lock() defer mu.Unlock() initPeerServerOnce.Do(callInitPeerServer) if _, dup := groups[name]; dup { panic("duplicate registration of group " + name) } g := &Group{ name: name, getter: getter, peers: peers, cacheBytes: cacheBytes, } if fn := newGroupHook; fn != nil { fn(g) } groups[name] = g return g } // newGroupHook, if non-nil, is called right after a new group is created. var newGroupHook func(*Group) // RegisterNewGroupHook registers a hook that is run each time // a group is created. func RegisterNewGroupHook(fn func(*Group)) { if newGroupHook != nil { panic("RegisterNewGroupHook called more than once") } newGroupHook = fn } // RegisterServerStart registers a hook that is run when the first // group is created. func RegisterServerStart(fn func()) { if initPeerServer != nil { panic("RegisterServerStart called more than once") } initPeerServer = fn } func callInitPeerServer() { if initPeerServer != nil { initPeerServer() } } // A Group is a cache namespace and associated data loaded spread over // a group of 1 or more machines. type Group struct { name string getter Getter peersOnce sync.Once peers PeerPicker cacheBytes int64 // limit for sum of mainCache and hotCache size // mainCache is a cache of the keys for which this process // (amongst its peers) is authorative. That is, this cache // contains keys which consistent hash on to this process's // peer number. mainCache cache // hotCache contains keys/values for which this peer is not // authorative (otherwise they would be in mainCache), but // are popular enough to warrant mirroring in this process to // avoid going over the network to fetch from a peer. Having // a hotCache avoids network hotspotting, where a peer's // network card could become the bottleneck on a popular key. // This cache is used sparingly to maximize the total number // of key/value pairs that can be stored globally. hotCache cache // loadGroup ensures that each key is only fetched once // (either locally or remotely), regardless of the number of // concurrent callers. loadGroup singleflight.Group // Stats are statistics on the group. Stats Stats } // Stats are per-group statistics. type Stats struct { Gets AtomicInt // any Get request, including from peers CacheHits AtomicInt // either cache was good PeerLoads AtomicInt // either remote load or remote cache hit (not an error) PeerErrors AtomicInt Loads AtomicInt // (gets - cacheHits) LoadsDeduped AtomicInt // after singleflight LocalLoads AtomicInt // total good local loads LocalLoadErrs AtomicInt // total bad local loads ServerRequests AtomicInt // gets that came over the network from peers } // Name returns the name of the group. func (g *Group) Name() string { return g.name } func (g *Group) initPeers() { if g.peers == nil { g.peers = getPeers() } } func (g *Group) Get(ctx Context, key string, dest Sink) error { g.peersOnce.Do(g.initPeers) g.Stats.Gets.Add(1) if dest == nil { return errors.New("groupcache: nil dest Sink") } value, cacheHit := g.lookupCache(key) if cacheHit { g.Stats.CacheHits.Add(1) return setSinkView(dest, value) } // Optimization to avoid double unmarshalling or copying: keep // track of whether the dest was already populated. One caller // (if local) will set this; the losers will not. The common // case will likely be one caller. destPopulated := false value, destPopulated, err := g.load(ctx, key, dest) if err != nil { return err } if destPopulated { return nil } return setSinkView(dest, value) } // load loads key either by invoking the getter locally or by sending it to another machine. func (g *Group) load(ctx Context, key string, dest Sink) (value ByteView, destPopulated bool, err error) { g.Stats.Loads.Add(1) viewi, err := g.loadGroup.Do(key, func() (interface{}, error) { g.Stats.LoadsDeduped.Add(1) var value ByteView var err error if peer, ok := g.peers.PickPeer(key); ok { value, err = g.getFromPeer(ctx, peer, key) if err == nil { g.Stats.PeerLoads.Add(1) return value, nil } g.Stats.PeerErrors.Add(1) // TODO(bradfitz): log the peer's error? keep // log of the past few for /groupcachez? It's // probably boring (normal task movement), so not // worth logging I imagine. } value, err = g.getLocally(ctx, key, dest) if err != nil { g.Stats.LocalLoadErrs.Add(1) return nil, err } g.Stats.LocalLoads.Add(1) destPopulated = true // only one caller of load gets this return value g.populateCache(key, value, &g.mainCache) return value, nil }) if err == nil { value = viewi.(ByteView) } return } func (g *Group) getLocally(ctx Context, key string, dest Sink) (ByteView, error) { err := g.getter.Get(ctx, key, dest) if err != nil { return ByteView{}, err } return dest.view() } func (g *Group) getFromPeer(ctx Context, peer ProtoGetter, key string) (ByteView, error) { req := &pb.GetRequest{ Group: &g.name, Key: &key, } res := &pb.GetResponse{} err := peer.Get(ctx, req, res) if err != nil { return ByteView{}, err } value := ByteView{b: res.Value} // TODO(bradfitz): use res.MinuteQps or something smart to // conditionally populate hotCache. For now just do it some // percentage of the time. if rand.Intn(10) == 0 { g.populateCache(key, value, &g.hotCache) } return value, nil } func (g *Group) lookupCache(key string) (value ByteView, ok bool) { if g.cacheBytes <= 0 { return } value, ok = g.mainCache.get(key) if ok { return } value, ok = g.hotCache.get(key) return } func (g *Group) populateCache(key string, value ByteView, cache *cache) { if g.cacheBytes <= 0 { return } cache.add(key, value) // Evict items from cache(s) if necessary. for { mainBytes := g.mainCache.bytes() hotBytes := g.hotCache.bytes() if mainBytes+hotBytes <= g.cacheBytes { return } // TODO(bradfitz): this is good-enough-for-now logic. // It should be something based on measurements and/or // respecting the costs of different resources. victim := &g.mainCache if hotBytes > mainBytes/8 { victim = &g.hotCache } victim.removeOldest() } } // CacheType represents a type of cache. type CacheType int const ( // The MainCache is the cache for items that this peer is the // owner for. MainCache CacheType = iota + 1 // The HotCache is the cache for items that seem popular // enough to replicate to this node, even though it's not the // owner. HotCache ) // CacheStats returns stats about the provided cache within the group. func (g *Group) CacheStats(which CacheType) CacheStats { switch which { case MainCache: return g.mainCache.stats() case HotCache: return g.hotCache.stats() default: return CacheStats{} } } // cache is a wrapper around an *lru.Cache that adds synchronization, // makes values always be ByteView, and counts the size of all keys and // values. type cache struct { mu sync.RWMutex nbytes int64 // of all keys and values lru *lru.Cache nhit, nget int64 nevict int64 // number of evictions } func (c *cache) stats() CacheStats { c.mu.RLock() defer c.mu.RUnlock() return CacheStats{ Bytes: c.nbytes, Items: c.itemsLocked(), Gets: c.nget, Hits: c.nhit, Evictions: c.nevict, } } func (c *cache) add(key string, value ByteView) { c.mu.Lock() defer c.mu.Unlock() if c.lru == nil { c.lru = &lru.Cache{ OnEvicted: func(key lru.Key, value interface{}) { val := value.(ByteView) c.nbytes -= int64(len(key.(string))) + int64(val.Len()) c.nevict++ }, } } c.lru.Add(key, value) c.nbytes += int64(len(key)) + int64(value.Len()) } func (c *cache) get(key string) (value ByteView, ok bool) { c.mu.Lock() defer c.mu.Unlock() c.nget++ if c.lru == nil { return } vi, ok := c.lru.Get(key) if !ok { return } c.nhit++ return vi.(ByteView), true } func (c *cache) removeOldest() { c.mu.Lock() defer c.mu.Unlock() if c.lru != nil { c.lru.RemoveOldest() } } func (c *cache) bytes() int64 { c.mu.RLock() defer c.mu.RUnlock() return c.nbytes } func (c *cache) items() int64 { c.mu.RLock() defer c.mu.RUnlock() return c.itemsLocked() } func (c *cache) itemsLocked() int64 { if c.lru == nil { return 0 } return int64(c.lru.Len()) } // An AtomicInt is an int64 to be accessed atomically. type AtomicInt int64 // Add atomically adds n to i. func (i *AtomicInt) Add(n int64) { atomic.AddInt64((*int64)(i), n) } // Get atomically gets the value of i. func (i *AtomicInt) Get() int64 { return atomic.LoadInt64((*int64)(i)) } func (i *AtomicInt) String() string { return strconv.FormatInt(i.Get(), 10) } // CacheStats are returned by stats accessors on Group. type CacheStats struct { Bytes int64 Items int64 Gets int64 Hits int64 Evictions int64 } ================================================ FILE: vendor/github.com/golang/groupcache/groupcache_test.go ================================================ /* Copyright 2012 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. */ // Tests for groupcache. package groupcache import ( "errors" "fmt" "hash/crc32" "math/rand" "reflect" "sync" "testing" "time" "github.com/golang/protobuf/proto" pb "github.com/golang/groupcache/groupcachepb" testpb "github.com/golang/groupcache/testpb" ) var ( once sync.Once stringGroup, protoGroup Getter stringc = make(chan string) dummyCtx Context // cacheFills is the number of times stringGroup or // protoGroup's Getter have been called. Read using the // cacheFills function. cacheFills AtomicInt ) const ( stringGroupName = "string-group" protoGroupName = "proto-group" testMessageType = "google3/net/groupcache/go/test_proto.TestMessage" fromChan = "from-chan" cacheSize = 1 << 20 ) func testSetup() { stringGroup = NewGroup(stringGroupName, cacheSize, GetterFunc(func(_ Context, key string, dest Sink) error { if key == fromChan { key = <-stringc } cacheFills.Add(1) return dest.SetString("ECHO:" + key) })) protoGroup = NewGroup(protoGroupName, cacheSize, GetterFunc(func(_ Context, key string, dest Sink) error { if key == fromChan { key = <-stringc } cacheFills.Add(1) return dest.SetProto(&testpb.TestMessage{ Name: proto.String("ECHO:" + key), City: proto.String("SOME-CITY"), }) })) } // tests that a Getter's Get method is only called once with two // outstanding callers. This is the string variant. func TestGetDupSuppressString(t *testing.T) { once.Do(testSetup) // Start two getters. The first should block (waiting reading // from stringc) and the second should latch on to the first // one. resc := make(chan string, 2) for i := 0; i < 2; i++ { go func() { var s string if err := stringGroup.Get(dummyCtx, fromChan, StringSink(&s)); err != nil { resc <- "ERROR:" + err.Error() return } resc <- s }() } // Wait a bit so both goroutines get merged together via // singleflight. // TODO(bradfitz): decide whether there are any non-offensive // debug/test hooks that could be added to singleflight to // make a sleep here unnecessary. time.Sleep(250 * time.Millisecond) // Unblock the first getter, which should unblock the second // as well. stringc <- "foo" for i := 0; i < 2; i++ { select { case v := <-resc: if v != "ECHO:foo" { t.Errorf("got %q; want %q", v, "ECHO:foo") } case <-time.After(5 * time.Second): t.Errorf("timeout waiting on getter #%d of 2", i+1) } } } // tests that a Getter's Get method is only called once with two // outstanding callers. This is the proto variant. func TestGetDupSuppressProto(t *testing.T) { once.Do(testSetup) // Start two getters. The first should block (waiting reading // from stringc) and the second should latch on to the first // one. resc := make(chan *testpb.TestMessage, 2) for i := 0; i < 2; i++ { go func() { tm := new(testpb.TestMessage) if err := protoGroup.Get(dummyCtx, fromChan, ProtoSink(tm)); err != nil { tm.Name = proto.String("ERROR:" + err.Error()) } resc <- tm }() } // Wait a bit so both goroutines get merged together via // singleflight. // TODO(bradfitz): decide whether there are any non-offensive // debug/test hooks that could be added to singleflight to // make a sleep here unnecessary. time.Sleep(250 * time.Millisecond) // Unblock the first getter, which should unblock the second // as well. stringc <- "Fluffy" want := &testpb.TestMessage{ Name: proto.String("ECHO:Fluffy"), City: proto.String("SOME-CITY"), } for i := 0; i < 2; i++ { select { case v := <-resc: if !reflect.DeepEqual(v, want) { t.Errorf(" Got: %v\nWant: %v", proto.CompactTextString(v), proto.CompactTextString(want)) } case <-time.After(5 * time.Second): t.Errorf("timeout waiting on getter #%d of 2", i+1) } } } func countFills(f func()) int64 { fills0 := cacheFills.Get() f() return cacheFills.Get() - fills0 } func TestCaching(t *testing.T) { once.Do(testSetup) fills := countFills(func() { for i := 0; i < 10; i++ { var s string if err := stringGroup.Get(dummyCtx, "TestCaching-key", StringSink(&s)); err != nil { t.Fatal(err) } } }) if fills != 1 { t.Errorf("expected 1 cache fill; got %d", fills) } } func TestCacheEviction(t *testing.T) { once.Do(testSetup) testKey := "TestCacheEviction-key" getTestKey := func() { var res string for i := 0; i < 10; i++ { if err := stringGroup.Get(dummyCtx, testKey, StringSink(&res)); err != nil { t.Fatal(err) } } } fills := countFills(getTestKey) if fills != 1 { t.Fatalf("expected 1 cache fill; got %d", fills) } g := stringGroup.(*Group) evict0 := g.mainCache.nevict // Trash the cache with other keys. var bytesFlooded int64 // cacheSize/len(testKey) is approximate for bytesFlooded < cacheSize+1024 { var res string key := fmt.Sprintf("dummy-key-%d", bytesFlooded) stringGroup.Get(dummyCtx, key, StringSink(&res)) bytesFlooded += int64(len(key) + len(res)) } evicts := g.mainCache.nevict - evict0 if evicts <= 0 { t.Errorf("evicts = %v; want more than 0", evicts) } // Test that the key is gone. fills = countFills(getTestKey) if fills != 1 { t.Fatalf("expected 1 cache fill after cache trashing; got %d", fills) } } type fakePeer struct { hits int fail bool } func (p *fakePeer) Get(_ Context, in *pb.GetRequest, out *pb.GetResponse) error { p.hits++ if p.fail { return errors.New("simulated error from peer") } out.Value = []byte("got:" + in.GetKey()) return nil } type fakePeers []ProtoGetter func (p fakePeers) PickPeer(key string) (peer ProtoGetter, ok bool) { if len(p) == 0 { return } n := crc32.Checksum([]byte(key), crc32.IEEETable) % uint32(len(p)) return p[n], p[n] != nil } // tests that peers (virtual, in-process) are hit, and how much. func TestPeers(t *testing.T) { once.Do(testSetup) rand.Seed(123) peer0 := &fakePeer{} peer1 := &fakePeer{} peer2 := &fakePeer{} peerList := fakePeers([]ProtoGetter{peer0, peer1, peer2, nil}) const cacheSize = 0 // disabled localHits := 0 getter := func(_ Context, key string, dest Sink) error { localHits++ return dest.SetString("got:" + key) } testGroup := newGroup("TestPeers-group", cacheSize, GetterFunc(getter), peerList) run := func(name string, n int, wantSummary string) { // Reset counters localHits = 0 for _, p := range []*fakePeer{peer0, peer1, peer2} { p.hits = 0 } for i := 0; i < n; i++ { key := fmt.Sprintf("key-%d", i) want := "got:" + key var got string err := testGroup.Get(dummyCtx, key, StringSink(&got)) if err != nil { t.Errorf("%s: error on key %q: %v", name, key, err) continue } if got != want { t.Errorf("%s: for key %q, got %q; want %q", name, key, got, want) } } summary := func() string { return fmt.Sprintf("localHits = %d, peers = %d %d %d", localHits, peer0.hits, peer1.hits, peer2.hits) } if got := summary(); got != wantSummary { t.Errorf("%s: got %q; want %q", name, got, wantSummary) } } resetCacheSize := func(maxBytes int64) { g := testGroup g.cacheBytes = maxBytes g.mainCache = cache{} g.hotCache = cache{} } // Base case; peers all up, with no problems. resetCacheSize(1 << 20) run("base", 200, "localHits = 49, peers = 51 49 51") // Verify cache was hit. All localHits are gone, and some of // the peer hits (the ones randomly selected to be maybe hot) run("cached_base", 200, "localHits = 0, peers = 49 47 48") resetCacheSize(0) // With one of the peers being down. // TODO(bradfitz): on a peer number being unavailable, the // consistent hashing should maybe keep trying others to // spread the load out. Currently it fails back to local // execution if the first consistent-hash slot is unavailable. peerList[0] = nil run("one_peer_down", 200, "localHits = 100, peers = 0 49 51") // Failing peer peerList[0] = peer0 peer0.fail = true run("peer0_failing", 200, "localHits = 100, peers = 51 49 51") } func TestTruncatingByteSliceTarget(t *testing.T) { var buf [100]byte s := buf[:] if err := stringGroup.Get(dummyCtx, "short", TruncatingByteSliceSink(&s)); err != nil { t.Fatal(err) } if want := "ECHO:short"; string(s) != want { t.Errorf("short key got %q; want %q", s, want) } s = buf[:6] if err := stringGroup.Get(dummyCtx, "truncated", TruncatingByteSliceSink(&s)); err != nil { t.Fatal(err) } if want := "ECHO:t"; string(s) != want { t.Errorf("truncated key got %q; want %q", s, want) } } func TestAllocatingByteSliceTarget(t *testing.T) { var dst []byte sink := AllocatingByteSliceSink(&dst) inBytes := []byte("some bytes") sink.SetBytes(inBytes) if want := "some bytes"; string(dst) != want { t.Errorf("SetBytes resulted in %q; want %q", dst, want) } v, err := sink.view() if err != nil { t.Fatalf("view after SetBytes failed: %v", err) } if &inBytes[0] == &dst[0] { t.Error("inBytes and dst share memory") } if &inBytes[0] == &v.b[0] { t.Error("inBytes and view share memory") } if &dst[0] == &v.b[0] { t.Error("dst and view share memory") } } // TODO(bradfitz): port the Google-internal full integration test into here, // using HTTP requests instead of our RPC system. ================================================ FILE: vendor/github.com/golang/groupcache/groupcachepb/groupcache.pb.go ================================================ // Code generated by protoc-gen-go. // source: groupcache.proto // DO NOT EDIT! package groupcachepb import proto "github.com/golang/protobuf/proto" import json "encoding/json" import math "math" // Reference proto, json, and math imports to suppress error if they are not otherwise used. var _ = proto.Marshal var _ = &json.SyntaxError{} var _ = math.Inf type GetRequest struct { Group *string `protobuf:"bytes,1,req,name=group" json:"group,omitempty"` Key *string `protobuf:"bytes,2,req,name=key" json:"key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetRequest) Reset() { *m = GetRequest{} } func (m *GetRequest) String() string { return proto.CompactTextString(m) } func (*GetRequest) ProtoMessage() {} func (m *GetRequest) GetGroup() string { if m != nil && m.Group != nil { return *m.Group } return "" } func (m *GetRequest) GetKey() string { if m != nil && m.Key != nil { return *m.Key } return "" } type GetResponse struct { Value []byte `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` MinuteQps *float64 `protobuf:"fixed64,2,opt,name=minute_qps" json:"minute_qps,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *GetResponse) Reset() { *m = GetResponse{} } func (m *GetResponse) String() string { return proto.CompactTextString(m) } func (*GetResponse) ProtoMessage() {} func (m *GetResponse) GetValue() []byte { if m != nil { return m.Value } return nil } func (m *GetResponse) GetMinuteQps() float64 { if m != nil && m.MinuteQps != nil { return *m.MinuteQps } return 0 } func init() { } ================================================ FILE: vendor/github.com/golang/groupcache/groupcachepb/groupcache.proto ================================================ /* Copyright 2012 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. */ package groupcachepb; message GetRequest { required string group = 1; required string key = 2; // not actually required/guaranteed to be UTF-8 } message GetResponse { optional bytes value = 1; optional double minute_qps = 2; } service GroupCache { rpc Get(GetRequest) returns (GetResponse) { }; } ================================================ FILE: vendor/github.com/golang/groupcache/http.go ================================================ /* Copyright 2013 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. */ package groupcache import ( "bytes" "fmt" "io" "net/http" "net/url" "strings" "sync" "github.com/golang/groupcache/consistenthash" pb "github.com/golang/groupcache/groupcachepb" "github.com/golang/protobuf/proto" ) const defaultBasePath = "/_groupcache/" const defaultReplicas = 50 // HTTPPool implements PeerPicker for a pool of HTTP peers. type HTTPPool struct { // Context optionally specifies a context for the server to use when it // receives a request. // If nil, the server uses a nil Context. Context func(*http.Request) Context // Transport optionally specifies an http.RoundTripper for the client // to use when it makes a request. // If nil, the client uses http.DefaultTransport. Transport func(Context) http.RoundTripper // base path including leading and trailing slash, e.g. "/_groupcache/" basePath string // this peer's base URL, e.g. "https://example.net:8000" self string mu sync.Mutex // guards peers and httpGetters peers *consistenthash.Map httpGetters map[string]*httpGetter // keyed by e.g. "http://10.0.0.2:8008" } // HTTPPoolOptions are the configurations of a HTTPPool. type HTTPPoolOptions struct { // BasePath specifies the HTTP path that will serve groupcache requests. // If blank, it defaults to "/_groupcache/". BasePath string // Replicas specifies the number of key replicas on the consistent hash. // If blank, it defaults to 50. Replicas int // HashFn specifies the hash function of the consistent hash. // If blank, it defaults to crc32.ChecksumIEEE. HashFn consistenthash.Hash } // NewHTTPPool initializes an HTTP pool of peers, and registers itself as a PeerPicker. // For convenience, it also registers itself as an http.Handler with http.DefaultServeMux. // The self argument be a valid base URL that points to the current server, // for example "http://example.net:8000". func NewHTTPPool(self string) *HTTPPool { p := NewHTTPPoolOpts(self, nil) http.Handle(p.basePath, p) return p } var httpPoolMade bool // NewHTTPPoolOpts initializes an HTTP pool of peers with the given options. // Unlike NewHTTPPool, this function does not register the created pool as an HTTP handler. // The returned *HTTPPool implements http.Handler and must be registered using http.Handle. func NewHTTPPoolOpts(self string, o *HTTPPoolOptions) *HTTPPool { if httpPoolMade { panic("groupcache: NewHTTPPool must be called only once") } httpPoolMade = true opts := HTTPPoolOptions{} if o != nil { opts = *o } if opts.BasePath == "" { opts.BasePath = defaultBasePath } if opts.Replicas == 0 { opts.Replicas = defaultReplicas } p := &HTTPPool{ basePath: opts.BasePath, self: self, peers: consistenthash.New(opts.Replicas, opts.HashFn), httpGetters: make(map[string]*httpGetter), } RegisterPeerPicker(func() PeerPicker { return p }) return p } // Set updates the pool's list of peers. // Each peer value should be a valid base URL, // for example "http://example.net:8000". func (p *HTTPPool) Set(peers ...string) { p.mu.Lock() defer p.mu.Unlock() p.peers = consistenthash.New(defaultReplicas, nil) p.peers.Add(peers...) p.httpGetters = make(map[string]*httpGetter, len(peers)) for _, peer := range peers { p.httpGetters[peer] = &httpGetter{transport: p.Transport, baseURL: peer + p.basePath} } } func (p *HTTPPool) PickPeer(key string) (ProtoGetter, bool) { p.mu.Lock() defer p.mu.Unlock() if p.peers.IsEmpty() { return nil, false } if peer := p.peers.Get(key); peer != p.self { return p.httpGetters[peer], true } return nil, false } func (p *HTTPPool) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Parse request. if !strings.HasPrefix(r.URL.Path, p.basePath) { panic("HTTPPool serving unexpected path: " + r.URL.Path) } parts := strings.SplitN(r.URL.Path[len(p.basePath):], "/", 2) if len(parts) != 2 { http.Error(w, "bad request", http.StatusBadRequest) return } groupName := parts[0] key := parts[1] // Fetch the value for this group/key. group := GetGroup(groupName) if group == nil { http.Error(w, "no such group: "+groupName, http.StatusNotFound) return } var ctx Context if p.Context != nil { ctx = p.Context(r) } group.Stats.ServerRequests.Add(1) var value []byte err := group.Get(ctx, key, AllocatingByteSliceSink(&value)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } // Write the value to the response body as a proto message. body, err := proto.Marshal(&pb.GetResponse{Value: value}) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/x-protobuf") w.Write(body) } type httpGetter struct { transport func(Context) http.RoundTripper baseURL string } var bufferPool = sync.Pool{ New: func() interface{} { return new(bytes.Buffer) }, } func (h *httpGetter) Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error { u := fmt.Sprintf( "%v%v/%v", h.baseURL, url.QueryEscape(in.GetGroup()), url.QueryEscape(in.GetKey()), ) req, err := http.NewRequest("GET", u, nil) if err != nil { return err } tr := http.DefaultTransport if h.transport != nil { tr = h.transport(context) } res, err := tr.RoundTrip(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return fmt.Errorf("server returned: %v", res.Status) } b := bufferPool.Get().(*bytes.Buffer) b.Reset() defer bufferPool.Put(b) _, err = io.Copy(b, res.Body) if err != nil { return fmt.Errorf("reading response body: %v", err) } err = proto.Unmarshal(b.Bytes(), out) if err != nil { return fmt.Errorf("decoding response body: %v", err) } return nil } ================================================ FILE: vendor/github.com/golang/groupcache/http_test.go ================================================ /* Copyright 2013 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. */ package groupcache import ( "errors" "flag" "log" "net" "net/http" "os" "os/exec" "strconv" "strings" "sync" "testing" "time" ) var ( peerAddrs = flag.String("test_peer_addrs", "", "Comma-separated list of peer addresses; used by TestHTTPPool") peerIndex = flag.Int("test_peer_index", -1, "Index of which peer this child is; used by TestHTTPPool") peerChild = flag.Bool("test_peer_child", false, "True if running as a child process; used by TestHTTPPool") ) func TestHTTPPool(t *testing.T) { if *peerChild { beChildForTestHTTPPool() os.Exit(0) } const ( nChild = 4 nGets = 100 ) var childAddr []string for i := 0; i < nChild; i++ { childAddr = append(childAddr, pickFreeAddr(t)) } var cmds []*exec.Cmd var wg sync.WaitGroup for i := 0; i < nChild; i++ { cmd := exec.Command(os.Args[0], "--test.run=TestHTTPPool", "--test_peer_child", "--test_peer_addrs="+strings.Join(childAddr, ","), "--test_peer_index="+strconv.Itoa(i), ) cmds = append(cmds, cmd) wg.Add(1) if err := cmd.Start(); err != nil { t.Fatal("failed to start child process: ", err) } go awaitAddrReady(t, childAddr[i], &wg) } defer func() { for i := 0; i < nChild; i++ { if cmds[i].Process != nil { cmds[i].Process.Kill() } } }() wg.Wait() // Use a dummy self address so that we don't handle gets in-process. p := NewHTTPPool("should-be-ignored") p.Set(addrToURL(childAddr)...) // Dummy getter function. Gets should go to children only. // The only time this process will handle a get is when the // children can't be contacted for some reason. getter := GetterFunc(func(ctx Context, key string, dest Sink) error { return errors.New("parent getter called; something's wrong") }) g := NewGroup("httpPoolTest", 1<<20, getter) for _, key := range testKeys(nGets) { var value string if err := g.Get(nil, key, StringSink(&value)); err != nil { t.Fatal(err) } if suffix := ":" + key; !strings.HasSuffix(value, suffix) { t.Errorf("Get(%q) = %q, want value ending in %q", key, value, suffix) } t.Logf("Get key=%q, value=%q (peer:key)", key, value) } } func testKeys(n int) (keys []string) { keys = make([]string, n) for i := range keys { keys[i] = strconv.Itoa(i) } return } func beChildForTestHTTPPool() { addrs := strings.Split(*peerAddrs, ",") p := NewHTTPPool("http://" + addrs[*peerIndex]) p.Set(addrToURL(addrs)...) getter := GetterFunc(func(ctx Context, key string, dest Sink) error { dest.SetString(strconv.Itoa(*peerIndex) + ":" + key) return nil }) NewGroup("httpPoolTest", 1<<20, getter) log.Fatal(http.ListenAndServe(addrs[*peerIndex], p)) } // This is racy. Another process could swoop in and steal the port between the // call to this function and the next listen call. Should be okay though. // The proper way would be to pass the l.File() as ExtraFiles to the child // process, and then close your copy once the child starts. func pickFreeAddr(t *testing.T) string { l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer l.Close() return l.Addr().String() } func addrToURL(addr []string) []string { url := make([]string, len(addr)) for i := range addr { url[i] = "http://" + addr[i] } return url } func awaitAddrReady(t *testing.T, addr string, wg *sync.WaitGroup) { defer wg.Done() const max = 1 * time.Second tries := 0 for { tries++ c, err := net.Dial("tcp", addr) if err == nil { c.Close() return } delay := time.Duration(tries) * 25 * time.Millisecond if delay > max { delay = max } time.Sleep(delay) } } ================================================ FILE: vendor/github.com/golang/groupcache/lru/lru.go ================================================ /* Copyright 2013 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. */ // Package lru implements an LRU cache. package lru import "container/list" // Cache is an LRU cache. It is not safe for concurrent access. type Cache struct { // MaxEntries is the maximum number of cache entries before // an item is evicted. Zero means no limit. MaxEntries int // OnEvicted optionally specificies a callback function to be // executed when an entry is purged from the cache. OnEvicted func(key Key, value interface{}) ll *list.List cache map[interface{}]*list.Element } // A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators type Key interface{} type entry struct { key Key value interface{} } // New creates a new Cache. // If maxEntries is zero, the cache has no limit and it's assumed // that eviction is done by the caller. func New(maxEntries int) *Cache { return &Cache{ MaxEntries: maxEntries, ll: list.New(), cache: make(map[interface{}]*list.Element), } } // Add adds a value to the cache. func (c *Cache) Add(key Key, value interface{}) { if c.cache == nil { c.cache = make(map[interface{}]*list.Element) c.ll = list.New() } if ee, ok := c.cache[key]; ok { c.ll.MoveToFront(ee) ee.Value.(*entry).value = value return } ele := c.ll.PushFront(&entry{key, value}) c.cache[key] = ele if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { c.RemoveOldest() } } // Get looks up a key's value from the cache. func (c *Cache) Get(key Key) (value interface{}, ok bool) { if c.cache == nil { return } if ele, hit := c.cache[key]; hit { c.ll.MoveToFront(ele) return ele.Value.(*entry).value, true } return } // Remove removes the provided key from the cache. func (c *Cache) Remove(key Key) { if c.cache == nil { return } if ele, hit := c.cache[key]; hit { c.removeElement(ele) } } // RemoveOldest removes the oldest item from the cache. func (c *Cache) RemoveOldest() { if c.cache == nil { return } ele := c.ll.Back() if ele != nil { c.removeElement(ele) } } func (c *Cache) removeElement(e *list.Element) { c.ll.Remove(e) kv := e.Value.(*entry) delete(c.cache, kv.key) if c.OnEvicted != nil { c.OnEvicted(kv.key, kv.value) } } // Len returns the number of items in the cache. func (c *Cache) Len() int { if c.cache == nil { return 0 } return c.ll.Len() } ================================================ FILE: vendor/github.com/golang/groupcache/lru/lru_test.go ================================================ /* Copyright 2013 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. */ package lru import ( "testing" ) type simpleStruct struct { int string } type complexStruct struct { int simpleStruct } var getTests = []struct { name string keyToAdd interface{} keyToGet interface{} expectedOk bool }{ {"string_hit", "myKey", "myKey", true}, {"string_miss", "myKey", "nonsense", false}, {"simple_struct_hit", simpleStruct{1, "two"}, simpleStruct{1, "two"}, true}, {"simeple_struct_miss", simpleStruct{1, "two"}, simpleStruct{0, "noway"}, false}, {"complex_struct_hit", complexStruct{1, simpleStruct{2, "three"}}, complexStruct{1, simpleStruct{2, "three"}}, true}, } func TestGet(t *testing.T) { for _, tt := range getTests { lru := New(0) lru.Add(tt.keyToAdd, 1234) val, ok := lru.Get(tt.keyToGet) if ok != tt.expectedOk { t.Fatalf("%s: cache hit = %v; want %v", tt.name, ok, !ok) } else if ok && val != 1234 { t.Fatalf("%s expected get to return 1234 but got %v", tt.name, val) } } } func TestRemove(t *testing.T) { lru := New(0) lru.Add("myKey", 1234) if val, ok := lru.Get("myKey"); !ok { t.Fatal("TestRemove returned no match") } else if val != 1234 { t.Fatalf("TestRemove failed. Expected %d, got %v", 1234, val) } lru.Remove("myKey") if _, ok := lru.Get("myKey"); ok { t.Fatal("TestRemove returned a removed entry") } } ================================================ FILE: vendor/github.com/golang/groupcache/peers.go ================================================ /* Copyright 2012 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. */ // peers.go defines how processes find and communicate with their peers. package groupcache import ( pb "github.com/golang/groupcache/groupcachepb" ) // Context is an opaque value passed through calls to the // ProtoGetter. It may be nil if your ProtoGetter implementation does // not require a context. type Context interface{} // ProtoGetter is the interface that must be implemented by a peer. type ProtoGetter interface { Get(context Context, in *pb.GetRequest, out *pb.GetResponse) error } // PeerPicker is the interface that must be implemented to locate // the peer that owns a specific key. type PeerPicker interface { // PickPeer returns the peer that owns the specific key // and true to indicate that a remote peer was nominated. // It returns nil, false if the key owner is the current peer. PickPeer(key string) (peer ProtoGetter, ok bool) } // NoPeers is an implementation of PeerPicker that never finds a peer. type NoPeers struct{} func (NoPeers) PickPeer(key string) (peer ProtoGetter, ok bool) { return } var ( portPicker func() PeerPicker ) // RegisterPeerPicker registers the peer initialization function. // It is called once, when the first group is created. func RegisterPeerPicker(fn func() PeerPicker) { if portPicker != nil { panic("RegisterPeerPicker called more than once") } portPicker = fn } func getPeers() PeerPicker { if portPicker == nil { return NoPeers{} } pk := portPicker() if pk == nil { pk = NoPeers{} } return pk } ================================================ FILE: vendor/github.com/golang/groupcache/singleflight/singleflight.go ================================================ /* Copyright 2012 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. */ // Package singleflight provides a duplicate function call suppression // mechanism. package singleflight import "sync" // call is an in-flight or completed Do call type call struct { wg sync.WaitGroup val interface{} err error } // 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 } // 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. func (g *Group) Do(key string, fn func() (interface{}, error)) (interface{}, error) { g.mu.Lock() if g.m == nil { g.m = make(map[string]*call) } if c, ok := g.m[key]; ok { g.mu.Unlock() c.wg.Wait() return c.val, c.err } c := new(call) c.wg.Add(1) g.m[key] = c g.mu.Unlock() c.val, c.err = fn() c.wg.Done() g.mu.Lock() delete(g.m, key) g.mu.Unlock() return c.val, c.err } ================================================ FILE: vendor/github.com/golang/groupcache/singleflight/singleflight_test.go ================================================ /* Copyright 2012 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. */ package singleflight import ( "errors" "fmt" "sync" "sync/atomic" "testing" "time" ) func TestDo(t *testing.T) { var g Group v, err := g.Do("key", func() (interface{}, error) { return "bar", nil }) if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { t.Errorf("Do = %v; want %v", got, want) } if err != nil { t.Errorf("Do error = %v", err) } } func TestDoErr(t *testing.T) { var g Group someErr := errors.New("Some error") v, err := g.Do("key", func() (interface{}, error) { return nil, someErr }) if err != someErr { t.Errorf("Do error = %v; want someErr", err) } if v != nil { t.Errorf("unexpected non-nil value %#v", v) } } func TestDoDupSuppress(t *testing.T) { var g Group c := make(chan string) var calls int32 fn := func() (interface{}, error) { atomic.AddInt32(&calls, 1) return <-c, nil } const n = 10 var wg sync.WaitGroup for i := 0; i < n; i++ { wg.Add(1) go func() { v, err := g.Do("key", fn) if err != nil { t.Errorf("Do error: %v", err) } if v.(string) != "bar" { t.Errorf("got %q; want %q", v, "bar") } wg.Done() }() } time.Sleep(100 * time.Millisecond) // let goroutines above block c <- "bar" wg.Wait() if got := atomic.LoadInt32(&calls); got != 1 { t.Errorf("number of calls = %d; want 1", got) } } ================================================ FILE: vendor/github.com/golang/groupcache/sinks.go ================================================ /* Copyright 2012 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. */ package groupcache import ( "errors" "github.com/golang/protobuf/proto" ) // A Sink receives data from a Get call. // // Implementation of Getter must call exactly one of the Set methods // on success. type Sink interface { // SetString sets the value to s. SetString(s string) error // SetBytes sets the value to the contents of v. // The caller retains ownership of v. SetBytes(v []byte) error // SetProto sets the value to the encoded version of m. // The caller retains ownership of m. SetProto(m proto.Message) error // view returns a frozen view of the bytes for caching. view() (ByteView, error) } func cloneBytes(b []byte) []byte { c := make([]byte, len(b)) copy(c, b) return c } func setSinkView(s Sink, v ByteView) error { // A viewSetter is a Sink that can also receive its value from // a ByteView. This is a fast path to minimize copies when the // item was already cached locally in memory (where it's // cached as a ByteView) type viewSetter interface { setView(v ByteView) error } if vs, ok := s.(viewSetter); ok { return vs.setView(v) } if v.b != nil { return s.SetBytes(v.b) } return s.SetString(v.s) } // StringSink returns a Sink that populates the provided string pointer. func StringSink(sp *string) Sink { return &stringSink{sp: sp} } type stringSink struct { sp *string v ByteView // TODO(bradfitz): track whether any Sets were called. } func (s *stringSink) view() (ByteView, error) { // TODO(bradfitz): return an error if no Set was called return s.v, nil } func (s *stringSink) SetString(v string) error { s.v.b = nil s.v.s = v *s.sp = v return nil } func (s *stringSink) SetBytes(v []byte) error { return s.SetString(string(v)) } func (s *stringSink) SetProto(m proto.Message) error { b, err := proto.Marshal(m) if err != nil { return err } s.v.b = b *s.sp = string(b) return nil } // ByteViewSink returns a Sink that populates a ByteView. func ByteViewSink(dst *ByteView) Sink { if dst == nil { panic("nil dst") } return &byteViewSink{dst: dst} } type byteViewSink struct { dst *ByteView // if this code ever ends up tracking that at least one set* // method was called, don't make it an error to call set // methods multiple times. Lorry's payload.go does that, and // it makes sense. The comment at the top of this file about // "exactly one of the Set methods" is overly strict. We // really care about at least once (in a handler), but if // multiple handlers fail (or multiple functions in a program // using a Sink), it's okay to re-use the same one. } func (s *byteViewSink) setView(v ByteView) error { *s.dst = v return nil } func (s *byteViewSink) view() (ByteView, error) { return *s.dst, nil } func (s *byteViewSink) SetProto(m proto.Message) error { b, err := proto.Marshal(m) if err != nil { return err } *s.dst = ByteView{b: b} return nil } func (s *byteViewSink) SetBytes(b []byte) error { *s.dst = ByteView{b: cloneBytes(b)} return nil } func (s *byteViewSink) SetString(v string) error { *s.dst = ByteView{s: v} return nil } // ProtoSink returns a sink that unmarshals binary proto values into m. func ProtoSink(m proto.Message) Sink { return &protoSink{ dst: m, } } type protoSink struct { dst proto.Message // authorative value typ string v ByteView // encoded } func (s *protoSink) view() (ByteView, error) { return s.v, nil } func (s *protoSink) SetBytes(b []byte) error { err := proto.Unmarshal(b, s.dst) if err != nil { return err } s.v.b = cloneBytes(b) s.v.s = "" return nil } func (s *protoSink) SetString(v string) error { b := []byte(v) err := proto.Unmarshal(b, s.dst) if err != nil { return err } s.v.b = b s.v.s = "" return nil } func (s *protoSink) SetProto(m proto.Message) error { b, err := proto.Marshal(m) if err != nil { return err } // TODO(bradfitz): optimize for same-task case more and write // right through? would need to document ownership rules at // the same time. but then we could just assign *dst = *m // here. This works for now: err = proto.Unmarshal(b, s.dst) if err != nil { return err } s.v.b = b s.v.s = "" return nil } // AllocatingByteSliceSink returns a Sink that allocates // a byte slice to hold the received value and assigns // it to *dst. The memory is not retained by groupcache. func AllocatingByteSliceSink(dst *[]byte) Sink { return &allocBytesSink{dst: dst} } type allocBytesSink struct { dst *[]byte v ByteView } func (s *allocBytesSink) view() (ByteView, error) { return s.v, nil } func (s *allocBytesSink) setView(v ByteView) error { if v.b != nil { *s.dst = cloneBytes(v.b) } else { *s.dst = []byte(v.s) } s.v = v return nil } func (s *allocBytesSink) SetProto(m proto.Message) error { b, err := proto.Marshal(m) if err != nil { return err } return s.setBytesOwned(b) } func (s *allocBytesSink) SetBytes(b []byte) error { return s.setBytesOwned(cloneBytes(b)) } func (s *allocBytesSink) setBytesOwned(b []byte) error { if s.dst == nil { return errors.New("nil AllocatingByteSliceSink *[]byte dst") } *s.dst = cloneBytes(b) // another copy, protecting the read-only s.v.b view s.v.b = b s.v.s = "" return nil } func (s *allocBytesSink) SetString(v string) error { if s.dst == nil { return errors.New("nil AllocatingByteSliceSink *[]byte dst") } *s.dst = []byte(v) s.v.b = nil s.v.s = v return nil } // TruncatingByteSliceSink returns a Sink that writes up to len(*dst) // bytes to *dst. If more bytes are available, they're silently // truncated. If fewer bytes are available than len(*dst), *dst // is shrunk to fit the number of bytes available. func TruncatingByteSliceSink(dst *[]byte) Sink { return &truncBytesSink{dst: dst} } type truncBytesSink struct { dst *[]byte v ByteView } func (s *truncBytesSink) view() (ByteView, error) { return s.v, nil } func (s *truncBytesSink) SetProto(m proto.Message) error { b, err := proto.Marshal(m) if err != nil { return err } return s.setBytesOwned(b) } func (s *truncBytesSink) SetBytes(b []byte) error { return s.setBytesOwned(cloneBytes(b)) } func (s *truncBytesSink) setBytesOwned(b []byte) error { if s.dst == nil { return errors.New("nil TruncatingByteSliceSink *[]byte dst") } n := copy(*s.dst, b) if n < len(*s.dst) { *s.dst = (*s.dst)[:n] } s.v.b = b s.v.s = "" return nil } func (s *truncBytesSink) SetString(v string) error { if s.dst == nil { return errors.New("nil TruncatingByteSliceSink *[]byte dst") } n := copy(*s.dst, v) if n < len(*s.dst) { *s.dst = (*s.dst)[:n] } s.v.b = nil s.v.s = v return nil } ================================================ FILE: vendor/github.com/golang/groupcache/testpb/test.pb.go ================================================ // Code generated by protoc-gen-go. // source: test.proto // DO NOT EDIT! package testpb import proto "github.com/golang/protobuf/proto" import json "encoding/json" import math "math" // Reference proto, json, and math imports to suppress error if they are not otherwise used. var _ = proto.Marshal var _ = &json.SyntaxError{} var _ = math.Inf type TestMessage struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` City *string `protobuf:"bytes,2,opt,name=city" json:"city,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *TestMessage) Reset() { *m = TestMessage{} } func (m *TestMessage) String() string { return proto.CompactTextString(m) } func (*TestMessage) ProtoMessage() {} func (m *TestMessage) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } func (m *TestMessage) GetCity() string { if m != nil && m.City != nil { return *m.City } return "" } type TestRequest struct { Lower *string `protobuf:"bytes,1,req,name=lower" json:"lower,omitempty"` RepeatCount *int32 `protobuf:"varint,2,opt,name=repeat_count,def=1" json:"repeat_count,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *TestRequest) Reset() { *m = TestRequest{} } func (m *TestRequest) String() string { return proto.CompactTextString(m) } func (*TestRequest) ProtoMessage() {} const Default_TestRequest_RepeatCount int32 = 1 func (m *TestRequest) GetLower() string { if m != nil && m.Lower != nil { return *m.Lower } return "" } func (m *TestRequest) GetRepeatCount() int32 { if m != nil && m.RepeatCount != nil { return *m.RepeatCount } return Default_TestRequest_RepeatCount } type TestResponse struct { Value *string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *TestResponse) Reset() { *m = TestResponse{} } func (m *TestResponse) String() string { return proto.CompactTextString(m) } func (*TestResponse) ProtoMessage() {} func (m *TestResponse) GetValue() string { if m != nil && m.Value != nil { return *m.Value } return "" } type CacheStats struct { Items *int64 `protobuf:"varint,1,opt,name=items" json:"items,omitempty"` Bytes *int64 `protobuf:"varint,2,opt,name=bytes" json:"bytes,omitempty"` Gets *int64 `protobuf:"varint,3,opt,name=gets" json:"gets,omitempty"` Hits *int64 `protobuf:"varint,4,opt,name=hits" json:"hits,omitempty"` Evicts *int64 `protobuf:"varint,5,opt,name=evicts" json:"evicts,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *CacheStats) Reset() { *m = CacheStats{} } func (m *CacheStats) String() string { return proto.CompactTextString(m) } func (*CacheStats) ProtoMessage() {} func (m *CacheStats) GetItems() int64 { if m != nil && m.Items != nil { return *m.Items } return 0 } func (m *CacheStats) GetBytes() int64 { if m != nil && m.Bytes != nil { return *m.Bytes } return 0 } func (m *CacheStats) GetGets() int64 { if m != nil && m.Gets != nil { return *m.Gets } return 0 } func (m *CacheStats) GetHits() int64 { if m != nil && m.Hits != nil { return *m.Hits } return 0 } func (m *CacheStats) GetEvicts() int64 { if m != nil && m.Evicts != nil { return *m.Evicts } return 0 } type StatsResponse struct { Gets *int64 `protobuf:"varint,1,opt,name=gets" json:"gets,omitempty"` CacheHits *int64 `protobuf:"varint,12,opt,name=cache_hits" json:"cache_hits,omitempty"` Fills *int64 `protobuf:"varint,2,opt,name=fills" json:"fills,omitempty"` TotalAlloc *uint64 `protobuf:"varint,3,opt,name=total_alloc" json:"total_alloc,omitempty"` MainCache *CacheStats `protobuf:"bytes,4,opt,name=main_cache" json:"main_cache,omitempty"` HotCache *CacheStats `protobuf:"bytes,5,opt,name=hot_cache" json:"hot_cache,omitempty"` ServerIn *int64 `protobuf:"varint,6,opt,name=server_in" json:"server_in,omitempty"` Loads *int64 `protobuf:"varint,8,opt,name=loads" json:"loads,omitempty"` PeerLoads *int64 `protobuf:"varint,9,opt,name=peer_loads" json:"peer_loads,omitempty"` PeerErrors *int64 `protobuf:"varint,10,opt,name=peer_errors" json:"peer_errors,omitempty"` LocalLoads *int64 `protobuf:"varint,11,opt,name=local_loads" json:"local_loads,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *StatsResponse) Reset() { *m = StatsResponse{} } func (m *StatsResponse) String() string { return proto.CompactTextString(m) } func (*StatsResponse) ProtoMessage() {} func (m *StatsResponse) GetGets() int64 { if m != nil && m.Gets != nil { return *m.Gets } return 0 } func (m *StatsResponse) GetCacheHits() int64 { if m != nil && m.CacheHits != nil { return *m.CacheHits } return 0 } func (m *StatsResponse) GetFills() int64 { if m != nil && m.Fills != nil { return *m.Fills } return 0 } func (m *StatsResponse) GetTotalAlloc() uint64 { if m != nil && m.TotalAlloc != nil { return *m.TotalAlloc } return 0 } func (m *StatsResponse) GetMainCache() *CacheStats { if m != nil { return m.MainCache } return nil } func (m *StatsResponse) GetHotCache() *CacheStats { if m != nil { return m.HotCache } return nil } func (m *StatsResponse) GetServerIn() int64 { if m != nil && m.ServerIn != nil { return *m.ServerIn } return 0 } func (m *StatsResponse) GetLoads() int64 { if m != nil && m.Loads != nil { return *m.Loads } return 0 } func (m *StatsResponse) GetPeerLoads() int64 { if m != nil && m.PeerLoads != nil { return *m.PeerLoads } return 0 } func (m *StatsResponse) GetPeerErrors() int64 { if m != nil && m.PeerErrors != nil { return *m.PeerErrors } return 0 } func (m *StatsResponse) GetLocalLoads() int64 { if m != nil && m.LocalLoads != nil { return *m.LocalLoads } return 0 } type Empty struct { XXX_unrecognized []byte `json:"-"` } func (m *Empty) Reset() { *m = Empty{} } func (m *Empty) String() string { return proto.CompactTextString(m) } func (*Empty) ProtoMessage() {} func init() { } ================================================ FILE: vendor/github.com/golang/groupcache/testpb/test.proto ================================================ /* Copyright 2012 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. */ package testpb; message TestMessage { optional string name = 1; optional string city = 2; } message TestRequest { required string lower = 1; // to be returned upper case optional int32 repeat_count = 2 [default = 1]; // .. this many times } message TestResponse { optional string value = 1; } message CacheStats { optional int64 items = 1; optional int64 bytes = 2; optional int64 gets = 3; optional int64 hits = 4; optional int64 evicts = 5; } message StatsResponse { optional int64 gets = 1; optional int64 cache_hits = 12; optional int64 fills = 2; optional uint64 total_alloc = 3; optional CacheStats main_cache = 4; optional CacheStats hot_cache = 5; optional int64 server_in = 6; optional int64 loads = 8; optional int64 peer_loads = 9; optional int64 peer_errors = 10; optional int64 local_loads = 11; } message Empty {} service GroupCacheTest { rpc InitPeers(Empty) returns (Empty) {}; rpc Get(TestRequest) returns (TestResponse) {}; rpc GetStats(Empty) returns (StatsResponse) {}; } ================================================ FILE: vendor/github.com/golang/protobuf/.gitignore ================================================ .DS_Store *.[568ao] *.pb.go *.ao *.so *.pyc ._* .nfs.* [568a].out *~ *.orig core _obj _test _testmain.go compiler/protoc-gen-go compiler/testdata/extension_test ================================================ FILE: vendor/github.com/golang/protobuf/AUTHORS ================================================ # This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. ================================================ FILE: vendor/github.com/golang/protobuf/CONTRIBUTORS ================================================ # This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. ================================================ FILE: vendor/github.com/golang/protobuf/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/golang/protobuf/Make.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. # Includable Makefile to add a rule for generating .pb.go files from .proto files # (Google protocol buffer descriptions). # Typical use if myproto.proto is a file in package mypackage in this directory: # # include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf %.pb.go: %.proto protoc --go_out=. $< ================================================ FILE: vendor/github.com/golang/protobuf/Makefile ================================================ # 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. all: install install: go install ./proto go install ./jsonpb go install ./protoc-gen-go test: go test ./proto go test ./jsonpb make -C protoc-gen-go/testdata test clean: go clean ./... nuke: go clean -i ./... regenerate: make -C protoc-gen-go/descriptor regenerate make -C protoc-gen-go/plugin regenerate make -C protoc-gen-go/testdata regenerate make -C proto/testdata regenerate make -C jsonpb/jsonpb_test_proto regenerate ================================================ FILE: vendor/github.com/golang/protobuf/README.md ================================================ # 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. ## 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 ================================================ FILE: vendor/github.com/golang/protobuf/jsonpb/jsonpb.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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 jsonpb provides marshaling and unmarshaling between protocol buffers and JSON. It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json. This package produces a different output than the standard "encoding/json" package, which does not operate correctly on protocol buffers. */ package jsonpb import ( "bytes" "encoding/json" "fmt" "io" "reflect" "sort" "strconv" "strings" "github.com/golang/protobuf/proto" ) var ( byteArrayType = reflect.TypeOf([]byte{}) ) // Marshaler is a configurable object for converting between // protocol buffer objects and a JSON representation for them. type Marshaler struct { // Whether to render enum values as integers, as opposed to string values. EnumsAsInts bool // Whether to render fields with zero values. EmitDefaults bool // A string to indent each level by. The presence of this field will // also cause a space to appear between the field separator and // value, and for newlines to be appear between fields and array // elements. Indent string } // Marshal marshals a protocol buffer into JSON. func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error { writer := &errWriter{writer: out} return m.marshalObject(writer, pb, "") } // MarshalToString converts a protocol buffer object to JSON string. func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) { var buf bytes.Buffer if err := m.Marshal(&buf, pb); err != nil { return "", err } return buf.String(), nil } type int32Slice []int32 // For sorting extensions ids to ensure stable output. 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] } // marshalObject writes a struct to the Writer. func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent string) error { out.write("{") if m.Indent != "" { out.write("\n") } s := reflect.ValueOf(v).Elem() firstField := true for i := 0; i < s.NumField(); i++ { value := s.Field(i) valueField := s.Type().Field(i) if strings.HasPrefix(valueField.Name, "XXX_") { continue } // IsNil will panic on most value kinds. switch value.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: if value.IsNil() { continue } } if !m.EmitDefaults { switch value.Kind() { case reflect.Bool: if !value.Bool() { continue } case reflect.Int32, reflect.Int64: if value.Int() == 0 { continue } case reflect.Uint32, reflect.Uint64: if value.Uint() == 0 { continue } case reflect.Float32, reflect.Float64: if value.Float() == 0 { continue } case reflect.String: if value.Len() == 0 { continue } } } // Oneof fields need special handling. if valueField.Tag.Get("protobuf_oneof") != "" { // value is an interface containing &T{real_value}. sv := value.Elem().Elem() // interface -> *T -> T value = sv.Field(0) valueField = sv.Type().Field(0) } prop := jsonProperties(valueField) if !firstField { m.writeSep(out) } if err := m.marshalField(out, prop, value, indent); err != nil { return err } firstField = false } // Handle proto2 extensions. if ep, ok := v.(extendableProto); ok { extensions := proto.RegisteredExtensions(v) extensionMap := ep.ExtensionMap() // Sort extensions for stable output. ids := make([]int32, 0, len(extensionMap)) for id := range extensionMap { ids = append(ids, id) } sort.Sort(int32Slice(ids)) for _, id := range ids { desc := extensions[id] if desc == nil { // unknown extension continue } ext, extErr := proto.GetExtension(ep, desc) if extErr != nil { return extErr } value := reflect.ValueOf(ext) var prop proto.Properties prop.Parse(desc.Tag) prop.OrigName = fmt.Sprintf("[%s]", desc.Name) if !firstField { m.writeSep(out) } if err := m.marshalField(out, &prop, value, indent); err != nil { return err } firstField = false } } if m.Indent != "" { out.write("\n") out.write(indent) } out.write("}") return out.err } func (m *Marshaler) writeSep(out *errWriter) { if m.Indent != "" { out.write(",\n") } else { out.write(",") } } // marshalField writes field description and value to the Writer. func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { if m.Indent != "" { out.write(indent) out.write(m.Indent) } out.write(`"`) out.write(prop.OrigName) out.write(`":`) if m.Indent != "" { out.write(" ") } if err := m.marshalValue(out, prop, v, indent); err != nil { return err } return nil } // marshalValue writes the value to the Writer. func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error { var err error v = reflect.Indirect(v) // Handle repeated elements. if v.Type() != byteArrayType && v.Kind() == reflect.Slice { out.write("[") comma := "" for i := 0; i < v.Len(); i++ { sliceVal := v.Index(i) out.write(comma) if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } m.marshalValue(out, prop, sliceVal, indent+m.Indent) comma = "," } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write("]") return out.err } // Handle enumerations. if !m.EnumsAsInts && prop.Enum != "" { // Unknown enum values will are stringified by the proto library as their // value. Such values should _not_ be quoted or they will be interpreted // as an enum string instead of their value. enumStr := v.Interface().(fmt.Stringer).String() var valStr string if v.Kind() == reflect.Ptr { valStr = strconv.Itoa(int(v.Elem().Int())) } else { valStr = strconv.Itoa(int(v.Int())) } isKnownEnum := enumStr != valStr if isKnownEnum { out.write(`"`) } out.write(enumStr) if isKnownEnum { out.write(`"`) } return out.err } // Handle nested messages. if v.Kind() == reflect.Struct { return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent) } // Handle maps. // Since Go randomizes map iteration, we sort keys for stable output. if v.Kind() == reflect.Map { out.write(`{`) keys := v.MapKeys() sort.Sort(mapKeys(keys)) for i, k := range keys { if i > 0 { out.write(`,`) } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) out.write(m.Indent) } b, err := json.Marshal(k.Interface()) if err != nil { return err } s := string(b) // If the JSON is not a string value, encode it again to make it one. if !strings.HasPrefix(s, `"`) { b, err := json.Marshal(s) if err != nil { return err } s = string(b) } out.write(s) out.write(`:`) if m.Indent != "" { out.write(` `) } if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil { return err } } if m.Indent != "" { out.write("\n") out.write(indent) out.write(m.Indent) } out.write(`}`) return out.err } // Default handling defers to the encoding/json library. b, err := json.Marshal(v.Interface()) if err != nil { return err } needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64) if needToQuote { out.write(`"`) } out.write(string(b)) if needToQuote { out.write(`"`) } return out.err } // Unmarshal unmarshals a JSON object stream into a protocol // buffer. This function is lenient and will decode any options // permutations of the related Marshaler. func Unmarshal(r io.Reader, pb proto.Message) error { inputValue := json.RawMessage{} if err := json.NewDecoder(r).Decode(&inputValue); err != nil { return err } return unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue) } // UnmarshalString will populate the fields of a protocol buffer based // on a JSON string. This function is lenient and will decode any options // permutations of the related Marshaler. func UnmarshalString(str string, pb proto.Message) error { return Unmarshal(strings.NewReader(str), pb) } // unmarshalValue converts/copies a value into the target. func unmarshalValue(target reflect.Value, inputValue json.RawMessage) error { targetType := target.Type() // Allocate memory for pointer fields. if targetType.Kind() == reflect.Ptr { target.Set(reflect.New(targetType.Elem())) return unmarshalValue(target.Elem(), inputValue) } // Handle nested messages. if targetType.Kind() == reflect.Struct { var jsonFields map[string]json.RawMessage if err := json.Unmarshal(inputValue, &jsonFields); err != nil { return err } sprops := proto.GetProperties(targetType) for i := 0; i < target.NumField(); i++ { ft := target.Type().Field(i) if strings.HasPrefix(ft.Name, "XXX_") { continue } fieldName := jsonProperties(ft).OrigName valueForField, ok := jsonFields[fieldName] if !ok { continue } delete(jsonFields, fieldName) // Handle enums, which have an underlying type of int32, // and may appear as strings. We do this while handling // the struct so we have access to the enum info. // The case of an enum appearing as a number is handled // by the recursive call to unmarshalValue. if enum := sprops.Prop[i].Enum; valueForField[0] == '"' && enum != "" { vmap := proto.EnumValueMap(enum) // Don't need to do unquoting; valid enum names // are from a limited character set. s := valueForField[1 : len(valueForField)-1] n, ok := vmap[string(s)] if !ok { return fmt.Errorf("unknown value %q for enum %s", s, enum) } f := target.Field(i) if f.Kind() == reflect.Ptr { // proto2 f.Set(reflect.New(f.Type().Elem())) f = f.Elem() } f.SetInt(int64(n)) continue } if err := unmarshalValue(target.Field(i), valueForField); err != nil { return err } } // Check for any oneof fields. for fname, raw := range jsonFields { if oop, ok := sprops.OneofTypes[fname]; ok { nv := reflect.New(oop.Type.Elem()) target.Field(oop.Field).Set(nv) if err := unmarshalValue(nv.Elem().Field(0), raw); err != nil { return err } delete(jsonFields, fname) } } if len(jsonFields) > 0 { // Pick any field to be the scapegoat. var f string for fname := range jsonFields { f = fname break } return fmt.Errorf("unknown field %q in %v", f, targetType) } return nil } // Handle arrays (which aren't encoded bytes) if targetType != byteArrayType && targetType.Kind() == reflect.Slice { var slc []json.RawMessage if err := json.Unmarshal(inputValue, &slc); err != nil { return err } len := len(slc) target.Set(reflect.MakeSlice(targetType, len, len)) for i := 0; i < len; i++ { if err := unmarshalValue(target.Index(i), slc[i]); err != nil { return err } } return nil } // Handle maps (whose keys are always strings) if targetType.Kind() == reflect.Map { var mp map[string]json.RawMessage if err := json.Unmarshal(inputValue, &mp); err != nil { return err } target.Set(reflect.MakeMap(targetType)) for ks, raw := range mp { // Unmarshal map key. The core json library already decoded the key into a // string, so we handle that specially. Other types were quoted post-serialization. var k reflect.Value if targetType.Key().Kind() == reflect.String { k = reflect.ValueOf(ks) } else { k = reflect.New(targetType.Key()).Elem() if err := unmarshalValue(k, json.RawMessage(ks)); err != nil { return err } } // Unmarshal map value. v := reflect.New(targetType.Elem()).Elem() if err := unmarshalValue(v, raw); err != nil { return err } target.SetMapIndex(k, v) } return nil } // 64-bit integers can be encoded as strings. In this case we drop // the quotes and proceed as normal. isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64 if isNum && strings.HasPrefix(string(inputValue), `"`) { inputValue = inputValue[1 : len(inputValue)-1] } // Use the encoding/json for parsing other value types. return json.Unmarshal(inputValue, target.Addr().Interface()) } // jsonProperties returns parsed proto.Properties for the field. func jsonProperties(f reflect.StructField) *proto.Properties { var prop proto.Properties prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f) return &prop } // extendableProto is an interface implemented by any protocol buffer that may be extended. type extendableProto interface { proto.Message ExtensionRangeArray() []proto.ExtensionRange ExtensionMap() map[int32]proto.Extension } // Writer wrapper inspired by https://blog.golang.org/errors-are-values type errWriter struct { writer io.Writer err error } func (w *errWriter) write(str string) { if w.err != nil { return } _, w.err = w.writer.Write([]byte(str)) } // 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. type mapKeys []reflect.Value func (s mapKeys) Len() int { return len(s) } func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s mapKeys) Less(i, j int) bool { return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface()) } ================================================ FILE: vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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 jsonpb import ( "reflect" "testing" pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" ) var ( marshaler = Marshaler{} marshalerAllOptions = Marshaler{ Indent: " ", } simpleObject = &pb.Simple{ OInt32: proto.Int32(-32), OInt64: proto.Int64(-6400000000), OUint32: proto.Uint32(32), OUint64: proto.Uint64(6400000000), OSint32: proto.Int32(-13), OSint64: proto.Int64(-2600000000), OFloat: proto.Float32(3.14), ODouble: proto.Float64(6.02214179e23), OBool: proto.Bool(true), OString: proto.String("hello \"there\""), OBytes: []byte("beep boop"), } simpleObjectJSON = `{` + `"o_bool":true,` + `"o_int32":-32,` + `"o_int64":"-6400000000",` + `"o_uint32":32,` + `"o_uint64":"6400000000",` + `"o_sint32":-13,` + `"o_sint64":"-2600000000",` + `"o_float":3.14,` + `"o_double":6.02214179e+23,` + `"o_string":"hello \"there\"",` + `"o_bytes":"YmVlcCBib29w"` + `}` simpleObjectPrettyJSON = `{ "o_bool": true, "o_int32": -32, "o_int64": "-6400000000", "o_uint32": 32, "o_uint64": "6400000000", "o_sint32": -13, "o_sint64": "-2600000000", "o_float": 3.14, "o_double": 6.02214179e+23, "o_string": "hello \"there\"", "o_bytes": "YmVlcCBib29w" }` repeatsObject = &pb.Repeats{ RBool: []bool{true, false, true}, RInt32: []int32{-3, -4, -5}, RInt64: []int64{-123456789, -987654321}, RUint32: []uint32{1, 2, 3}, RUint64: []uint64{6789012345, 3456789012}, RSint32: []int32{-1, -2, -3}, RSint64: []int64{-6789012345, -3456789012}, RFloat: []float32{3.14, 6.28}, RDouble: []float64{299792458, 6.62606957e-34}, RString: []string{"happy", "days"}, RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")}, } repeatsObjectJSON = `{` + `"r_bool":[true,false,true],` + `"r_int32":[-3,-4,-5],` + `"r_int64":["-123456789","-987654321"],` + `"r_uint32":[1,2,3],` + `"r_uint64":["6789012345","3456789012"],` + `"r_sint32":[-1,-2,-3],` + `"r_sint64":["-6789012345","-3456789012"],` + `"r_float":[3.14,6.28],` + `"r_double":[2.99792458e+08,6.62606957e-34],` + `"r_string":["happy","days"],` + `"r_bytes":["c2tpdHRsZXM=","bSZtJ3M="]` + `}` repeatsObjectPrettyJSON = `{ "r_bool": [ true, false, true ], "r_int32": [ -3, -4, -5 ], "r_int64": [ "-123456789", "-987654321" ], "r_uint32": [ 1, 2, 3 ], "r_uint64": [ "6789012345", "3456789012" ], "r_sint32": [ -1, -2, -3 ], "r_sint64": [ "-6789012345", "-3456789012" ], "r_float": [ 3.14, 6.28 ], "r_double": [ 2.99792458e+08, 6.62606957e-34 ], "r_string": [ "happy", "days" ], "r_bytes": [ "c2tpdHRsZXM=", "bSZtJ3M=" ] }` innerSimple = &pb.Simple{OInt32: proto.Int32(-32)} innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)} innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}} innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}} complexObject = &pb.Widget{ Color: pb.Widget_GREEN.Enum(), RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE}, Simple: innerSimple, RSimple: []*pb.Simple{innerSimple, innerSimple2}, Repeats: innerRepeats, RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2}, } complexObjectJSON = `{"color":"GREEN",` + `"r_color":["RED","GREEN","BLUE"],` + `"simple":{"o_int32":-32},` + `"r_simple":[{"o_int32":-32},{"o_int64":"25"}],` + `"repeats":{"r_string":["roses","red"]},` + `"r_repeats":[{"r_string":["roses","red"]},{"r_string":["violets","blue"]}]` + `}` complexObjectPrettyJSON = `{ "color": "GREEN", "r_color": [ "RED", "GREEN", "BLUE" ], "simple": { "o_int32": -32 }, "r_simple": [ { "o_int32": -32 }, { "o_int64": "25" } ], "repeats": { "r_string": [ "roses", "red" ] }, "r_repeats": [ { "r_string": [ "roses", "red" ] }, { "r_string": [ "violets", "blue" ] } ] }` colorPrettyJSON = `{ "color": 2 }` colorListPrettyJSON = `{ "color": 1000, "r_color": [ "RED" ] }` nummyPrettyJSON = `{ "nummy": { "1": 2, "3": 4 } }` objjyPrettyJSON = `{ "objjy": { "1": { "dub": 1 } } }` realNumber = &pb.Real{Value: proto.Float64(3.14159265359)} realNumberName = "Pi" complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)} realNumberJSON = `{` + `"value":3.14159265359,` + `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` + `"[jsonpb.name]":"Pi"` + `}` ) func init() { if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil { panic(err) } if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil { panic(err) } } var marshalingTests = []struct { desc string marshaler Marshaler pb proto.Message json string }{ {"simple flat object", marshaler, simpleObject, simpleObjectJSON}, {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON}, {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON}, {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON}, {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON}, {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON}, {"enum-string flat object", Marshaler{}, &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`}, {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "}, &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON}, {"unknown enum value object", marshalerAllOptions, &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON}, {"empty value", marshaler, &pb.Simple3{}, `{}`}, {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`}, {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`}, {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON}, {"map", marshaler, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}, `{"strry":{"\"one\"":"two","three":"four"}}`}, {"map", marshaler, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`}, {"map", marshalerAllOptions, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}, objjyPrettyJSON}, {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}}, `{"buggy":{"1234":"yup"}}`}, {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`}, {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}}, `{"m_int64_str":{"213":"cat"}}`}, {"proto2 map", marshaler, &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: &pb.Simple{OInt32: proto.Int32(1)}}}, `{"m_bool_simple":{"true":{"o_int32":1}}}`}, {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`}, {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`}, {"proto2 extension", marshaler, realNumber, realNumberJSON}, } func TestMarshaling(t *testing.T) { for _, tt := range marshalingTests { json, err := tt.marshaler.MarshalToString(tt.pb) if err != nil { t.Errorf("%s: marshaling error: %v", tt.desc, err) } else if tt.json != json { t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json) } } } var unmarshalingTests = []struct { desc string json string pb proto.Message }{ {"simple flat object", simpleObjectJSON, simpleObject}, {"simple pretty object", simpleObjectPrettyJSON, simpleObject}, {"repeated fields flat object", repeatsObjectJSON, repeatsObject}, {"repeated fields pretty object", repeatsObjectPrettyJSON, repeatsObject}, {"nested message/enum flat object", complexObjectJSON, complexObject}, {"nested message/enum pretty object", complexObjectPrettyJSON, complexObject}, {"enum-string object", `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, {"enum-value object", "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}}, {"proto3 enum string", `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"proto3 enum value", `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"unknown enum value object", "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}", &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}}, {"unquoted int64 object", `{"o_int64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}}, {"unquoted uint64 object", `{"o_uint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}}, {"map", `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}}, {"map", `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}}, {"map", `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: &pb.Simple3{Dub: 1}}}}, {"oneof", `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}}, } func TestUnmarshaling(t *testing.T) { for _, tt := range unmarshalingTests { // Make a new instance of the type of our expected object. p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message) err := UnmarshalString(tt.json, p) if err != nil { t.Error(err) continue } // For easier diffs, compare text strings of the protos. exp := proto.MarshalTextString(tt.pb) act := proto.MarshalTextString(p) if string(exp) != string(act) { t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp) } } } var unmarshalingShouldError = []struct { desc string in string pb proto.Message }{ {"a value", "666", new(pb.Simple)}, {"gibberish", "{adskja123;l23=-=", new(pb.Simple)}, {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)}, } func TestUnmarshalingBadInput(t *testing.T) { for _, tt := range unmarshalingShouldError { err := UnmarshalString(tt.in, tt.pb) if err == nil { t.Errorf("an error was expected when parsing %q instead of an object", tt.desc) } } } ================================================ FILE: vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/Makefile ================================================ # Go support for Protocol Buffers - Google's data interchange format # # Copyright 2015 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. regenerate: protoc --go_out=. *.proto ================================================ FILE: vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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. syntax = "proto3"; package jsonpb; message Simple3 { double dub = 1; } message Mappy { map nummy = 1; map strry = 2; map objjy = 3; map buggy = 4; map booly = 5; } ================================================ FILE: vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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. syntax = "proto2"; package jsonpb; // Test message for holding primitive types. message Simple { optional bool o_bool = 1; optional int32 o_int32 = 2; optional int64 o_int64 = 3; optional uint32 o_uint32 = 4; optional uint64 o_uint64 = 5; optional sint32 o_sint32 = 6; optional sint64 o_sint64 = 7; optional float o_float = 8; optional double o_double = 9; optional string o_string = 10; optional bytes o_bytes = 11; } // Test message for holding repeated primitives. message Repeats { repeated bool r_bool = 1; repeated int32 r_int32 = 2; repeated int64 r_int64 = 3; repeated uint32 r_uint32 = 4; repeated uint64 r_uint64 = 5; repeated sint32 r_sint32 = 6; repeated sint64 r_sint64 = 7; repeated float r_float = 8; repeated double r_double = 9; repeated string r_string = 10; repeated bytes r_bytes = 11; } // Test message for holding enums and nested messages. message Widget { enum Color { RED = 0; GREEN = 1; BLUE = 2; }; optional Color color = 1; repeated Color r_color = 2; optional Simple simple = 10; repeated Simple r_simple = 11; optional Repeats repeats = 20; repeated Repeats r_repeats = 21; } message Maps { map m_int64_str = 1; map m_bool_simple = 2; } message MsgWithOneof { oneof union { string title = 1; int64 salary = 2; } } message Real { optional double value = 1; extensions 100 to max; } extend Real { optional string name = 124; } message Complex { extend Real { optional Complex real_extension = 123; } optional double imaginary = 1; extensions 100 to max; } ================================================ FILE: vendor/github.com/golang/protobuf/proto/Makefile ================================================ # 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. install: go install test: install generate-test-pbs go test generate-test-pbs: make install make -C testdata protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto make ================================================ FILE: vendor/github.com/golang/protobuf/proto/all_test.go ================================================ // 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_test import ( "bytes" "encoding/json" "errors" "fmt" "math" "math/rand" "reflect" "runtime/debug" "strings" "testing" "time" . "github.com/golang/protobuf/proto" . "github.com/golang/protobuf/proto/testdata" ) var globalO *Buffer func old() *Buffer { if globalO == nil { globalO = NewBuffer(nil) } globalO.Reset() return globalO } func equalbytes(b1, b2 []byte, t *testing.T) { if len(b1) != len(b2) { t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2)) return } for i := 0; i < len(b1); i++ { if b1[i] != b2[i] { t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2) } } } func initGoTestField() *GoTestField { f := new(GoTestField) f.Label = String("label") f.Type = String("type") return f } // These are all structurally equivalent but the tag numbers differ. // (It's remarkable that required, optional, and repeated all have // 8 letters.) func initGoTest_RequiredGroup() *GoTest_RequiredGroup { return &GoTest_RequiredGroup{ RequiredField: String("required"), } } func initGoTest_OptionalGroup() *GoTest_OptionalGroup { return &GoTest_OptionalGroup{ RequiredField: String("optional"), } } func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { return &GoTest_RepeatedGroup{ RequiredField: String("repeated"), } } func initGoTest(setdefaults bool) *GoTest { pb := new(GoTest) if setdefaults { pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) } pb.Kind = GoTest_TIME.Enum() pb.RequiredField = initGoTestField() pb.F_BoolRequired = Bool(true) pb.F_Int32Required = Int32(3) pb.F_Int64Required = Int64(6) pb.F_Fixed32Required = Uint32(32) pb.F_Fixed64Required = Uint64(64) pb.F_Uint32Required = Uint32(3232) pb.F_Uint64Required = Uint64(6464) pb.F_FloatRequired = Float32(3232) pb.F_DoubleRequired = Float64(6464) pb.F_StringRequired = String("string") pb.F_BytesRequired = []byte("bytes") pb.F_Sint32Required = Int32(-32) pb.F_Sint64Required = Int64(-64) pb.Requiredgroup = initGoTest_RequiredGroup() return pb } func fail(msg string, b *bytes.Buffer, s string, t *testing.T) { data := b.Bytes() ld := len(data) ls := len(s) / 2 fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls) // find the interesting spot - n n := ls if ld < ls { n = ld } j := 0 for i := 0; i < n; i++ { bs := hex(s[j])*16 + hex(s[j+1]) j += 2 if data[i] == bs { continue } n = i break } l := n - 10 if l < 0 { l = 0 } h := n + 10 // find the interesting spot - n fmt.Printf("is[%d]:", l) for i := l; i < h; i++ { if i >= ld { fmt.Printf(" --") continue } fmt.Printf(" %.2x", data[i]) } fmt.Printf("\n") fmt.Printf("sb[%d]:", l) for i := l; i < h; i++ { if i >= ls { fmt.Printf(" --") continue } bs := hex(s[j])*16 + hex(s[j+1]) j += 2 fmt.Printf(" %.2x", bs) } fmt.Printf("\n") t.Fail() // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes()) // Print the output in a partially-decoded format; can // be helpful when updating the test. It produces the output // that is pasted, with minor edits, into the argument to verify(). // data := b.Bytes() // nesting := 0 // for b.Len() > 0 { // start := len(data) - b.Len() // var u uint64 // u, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on varint:", err) // return // } // wire := u & 0x7 // tag := u >> 3 // switch wire { // case WireVarint: // v, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on varint:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireFixed32: // v, err := DecodeFixed32(b) // if err != nil { // fmt.Printf("decode error on fixed32:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireFixed64: // v, err := DecodeFixed64(b) // if err != nil { // fmt.Printf("decode error on fixed64:", err) // return // } // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n", // data[start:len(data)-b.Len()], tag, wire, v) // case WireBytes: // nb, err := DecodeVarint(b) // if err != nil { // fmt.Printf("decode error on bytes:", err) // return // } // after_tag := len(data) - b.Len() // str := make([]byte, nb) // _, err = b.Read(str) // if err != nil { // fmt.Printf("decode error on bytes:", err) // return // } // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n", // data[start:after_tag], str, tag, wire) // case WireStartGroup: // nesting++ // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n", // data[start:len(data)-b.Len()], tag, nesting) // case WireEndGroup: // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n", // data[start:len(data)-b.Len()], tag, nesting) // nesting-- // default: // fmt.Printf("unrecognized wire type %d\n", wire) // return // } // } } func hex(c uint8) uint8 { if '0' <= c && c <= '9' { return c - '0' } if 'a' <= c && c <= 'f' { return 10 + c - 'a' } if 'A' <= c && c <= 'F' { return 10 + c - 'A' } return 0 } func equal(b []byte, s string, t *testing.T) bool { if 2*len(b) != len(s) { // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t) fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s)) return false } for i, j := 0, 0; i < len(b); i, j = i+1, j+2 { x := hex(s[j])*16 + hex(s[j+1]) if b[i] != x { // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t) fmt.Printf("bad byte[%d]:%x %x", i, b[i], x) return false } } return true } func overify(t *testing.T, pb *GoTest, expected string) { o := old() err := o.Marshal(pb) if err != nil { fmt.Printf("overify marshal-1 err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("expected = %s", expected) } if !equal(o.Bytes(), expected, t) { o.DebugPrint("overify neq 1", o.Bytes()) t.Fatalf("expected = %s", expected) } // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) err = o.Unmarshal(pbd) if err != nil { t.Fatalf("overify unmarshal err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("string = %s", expected) } o.Reset() err = o.Marshal(pbd) if err != nil { t.Errorf("overify marshal-2 err = %v", err) o.DebugPrint("", o.Bytes()) t.Fatalf("string = %s", expected) } if !equal(o.Bytes(), expected, t) { o.DebugPrint("overify neq 2", o.Bytes()) t.Fatalf("string = %s", expected) } } // Simple tests for numeric encode/decode primitives (varint, etc.) func TestNumericPrimitives(t *testing.T) { for i := uint64(0); i < 1e6; i += 111 { o := old() if o.EncodeVarint(i) != nil { t.Error("EncodeVarint") break } x, e := o.DecodeVarint() if e != nil { t.Fatal("DecodeVarint") } if x != i { t.Fatal("varint decode fail:", i, x) } o = old() if o.EncodeFixed32(i) != nil { t.Fatal("encFixed32") } x, e = o.DecodeFixed32() if e != nil { t.Fatal("decFixed32") } if x != i { t.Fatal("fixed32 decode fail:", i, x) } o = old() if o.EncodeFixed64(i*1234567) != nil { t.Error("encFixed64") break } x, e = o.DecodeFixed64() if e != nil { t.Error("decFixed64") break } if x != i*1234567 { t.Error("fixed64 decode fail:", i*1234567, x) break } o = old() i32 := int32(i - 12345) if o.EncodeZigzag32(uint64(i32)) != nil { t.Fatal("EncodeZigzag32") } x, e = o.DecodeZigzag32() if e != nil { t.Fatal("DecodeZigzag32") } if x != uint64(uint32(i32)) { t.Fatal("zigzag32 decode fail:", i32, x) } o = old() i64 := int64(i - 12345) if o.EncodeZigzag64(uint64(i64)) != nil { t.Fatal("EncodeZigzag64") } x, e = o.DecodeZigzag64() if e != nil { t.Fatal("DecodeZigzag64") } if x != uint64(i64) { t.Fatal("zigzag64 decode fail:", i64, x) } } } // fakeMarshaler is a simple struct implementing Marshaler and Message interfaces. type fakeMarshaler struct { b []byte err error } func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err } func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) } func (f *fakeMarshaler) ProtoMessage() {} func (f *fakeMarshaler) Reset() {} type msgWithFakeMarshaler struct { M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"` } func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) } func (m *msgWithFakeMarshaler) ProtoMessage() {} func (m *msgWithFakeMarshaler) Reset() {} // Simple tests for proto messages that implement the Marshaler interface. func TestMarshalerEncoding(t *testing.T) { tests := []struct { name string m Message want []byte wantErr error }{ { name: "Marshaler that fails", m: &fakeMarshaler{ err: errors.New("some marshal err"), b: []byte{5, 6, 7}, }, // Since there's an error, nothing should be written to buffer. want: nil, wantErr: errors.New("some marshal err"), }, { name: "Marshaler that fails with RequiredNotSetError", m: &msgWithFakeMarshaler{ M: &fakeMarshaler{ err: &RequiredNotSetError{}, b: []byte{5, 6, 7}, }, }, // Since there's an error that can be continued after, // the buffer should be written. want: []byte{ 10, 3, // for &msgWithFakeMarshaler 5, 6, 7, // for &fakeMarshaler }, wantErr: &RequiredNotSetError{}, }, { name: "Marshaler that succeeds", m: &fakeMarshaler{ b: []byte{0, 1, 2, 3, 4, 127, 255}, }, want: []byte{0, 1, 2, 3, 4, 127, 255}, wantErr: nil, }, } for _, test := range tests { b := NewBuffer(nil) err := b.Marshal(test.m) if _, ok := err.(*RequiredNotSetError); ok { // We're not in package proto, so we can only assert the type in this case. err = &RequiredNotSetError{} } if !reflect.DeepEqual(test.wantErr, err) { t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr) } if !reflect.DeepEqual(test.want, b.Bytes()) { t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want) } } } // Simple tests for bytes func TestBytesPrimitives(t *testing.T) { o := old() bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'} if o.EncodeRawBytes(bytes) != nil { t.Error("EncodeRawBytes") } decb, e := o.DecodeRawBytes(false) if e != nil { t.Error("DecodeRawBytes") } equalbytes(bytes, decb, t) } // Simple tests for strings func TestStringPrimitives(t *testing.T) { o := old() s := "now is the time" if o.EncodeStringBytes(s) != nil { t.Error("enc_string") } decs, e := o.DecodeStringBytes() if e != nil { t.Error("dec_string") } if s != decs { t.Error("string encode/decode fail:", s, decs) } } // Do we catch the "required bit not set" case? func TestRequiredBit(t *testing.T) { o := old() pb := new(GoTest) err := o.Marshal(pb) if err == nil { t.Error("did not catch missing required fields") } else if strings.Index(err.Error(), "Kind") < 0 { t.Error("wrong error type:", err) } } // Check that all fields are nil. // Clearly silly, and a residue from a more interesting test with an earlier, // different initialization property, but it once caught a compiler bug so // it lives. func checkInitialized(pb *GoTest, t *testing.T) { if pb.F_BoolDefaulted != nil { t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted) } if pb.F_Int32Defaulted != nil { t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted) } if pb.F_Int64Defaulted != nil { t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted) } if pb.F_Fixed32Defaulted != nil { t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted) } if pb.F_Fixed64Defaulted != nil { t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted) } if pb.F_Uint32Defaulted != nil { t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted) } if pb.F_Uint64Defaulted != nil { t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted) } if pb.F_FloatDefaulted != nil { t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted) } if pb.F_DoubleDefaulted != nil { t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted) } if pb.F_StringDefaulted != nil { t.Error("New or Reset did not set string:", *pb.F_StringDefaulted) } if pb.F_BytesDefaulted != nil { t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted)) } if pb.F_Sint32Defaulted != nil { t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted) } if pb.F_Sint64Defaulted != nil { t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted) } } // Does Reset() reset? func TestReset(t *testing.T) { pb := initGoTest(true) // muck with some values pb.F_BoolDefaulted = Bool(false) pb.F_Int32Defaulted = Int32(237) pb.F_Int64Defaulted = Int64(12346) pb.F_Fixed32Defaulted = Uint32(32000) pb.F_Fixed64Defaulted = Uint64(666) pb.F_Uint32Defaulted = Uint32(323232) pb.F_Uint64Defaulted = nil pb.F_FloatDefaulted = nil pb.F_DoubleDefaulted = Float64(0) pb.F_StringDefaulted = String("gotcha") pb.F_BytesDefaulted = []byte("asdfasdf") pb.F_Sint32Defaulted = Int32(123) pb.F_Sint64Defaulted = Int64(789) pb.Reset() checkInitialized(pb, t) } // All required fields set, no defaults provided. func TestEncodeDecode1(t *testing.T) { pb := initGoTest(false) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 0x20 "714000000000000000"+ // field 14, encoding 1, value 0x40 "78a019"+ // field 15, encoding 0, value 0xca0 = 3232 "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string" "b304"+ // field 70, encoding 3, start group "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // field 70, encoding 4, end group "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f") // field 103, encoding 0, 0x7f zigzag64 } // All required fields set, defaults provided. func TestEncodeDecode2(t *testing.T) { pb := initGoTest(true) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All default fields set to their default value by hand func TestEncodeDecode3(t *testing.T) { pb := initGoTest(false) pb.F_BoolDefaulted = Bool(true) pb.F_Int32Defaulted = Int32(32) pb.F_Int64Defaulted = Int64(64) pb.F_Fixed32Defaulted = Uint32(320) pb.F_Fixed64Defaulted = Uint64(640) pb.F_Uint32Defaulted = Uint32(3200) pb.F_Uint64Defaulted = Uint64(6400) pb.F_FloatDefaulted = Float32(314159) pb.F_DoubleDefaulted = Float64(271828) pb.F_StringDefaulted = String("hello, \"world!\"\n") pb.F_BytesDefaulted = []byte("Bignose") pb.F_Sint32Defaulted = Int32(-32) pb.F_Sint64Defaulted = Int64(-64) overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, defaults provided, all non-defaulted optional fields have values. func TestEncodeDecode4(t *testing.T) { pb := initGoTest(true) pb.Table = String("hello") pb.Param = Int32(7) pb.OptionalField = initGoTestField() pb.F_BoolOptional = Bool(true) pb.F_Int32Optional = Int32(32) pb.F_Int64Optional = Int64(64) pb.F_Fixed32Optional = Uint32(3232) pb.F_Fixed64Optional = Uint64(6464) pb.F_Uint32Optional = Uint32(323232) pb.F_Uint64Optional = Uint64(646464) pb.F_FloatOptional = Float32(32.) pb.F_DoubleOptional = Float64(64.) pb.F_StringOptional = String("hello") pb.F_BytesOptional = []byte("Bignose") pb.F_Sint32Optional = Int32(-32) pb.F_Sint64Optional = Int64(-64) pb.Optionalgroup = initGoTest_OptionalGroup() overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello" "1807"+ // field 3, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "f00101"+ // field 30, encoding 0, value 1 "f80120"+ // field 31, encoding 0, value 32 "800240"+ // field 32, encoding 0, value 64 "8d02a00c0000"+ // field 33, encoding 5, value 3232 "91024019000000000000"+ // field 34, encoding 1, value 6464 "9802a0dd13"+ // field 35, encoding 0, value 323232 "a002c0ba27"+ // field 36, encoding 0, value 646464 "ad0200000042"+ // field 37, encoding 5, value 32.0 "b1020000000000005040"+ // field 38, encoding 1, value 64.0 "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "d305"+ // start group field 90 level 1 "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional" "d405"+ // end group field 90 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose" "f0123f"+ // field 302, encoding 0, value 63 "f8127f"+ // field 303, encoding 0, value 127 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, defaults provided, all repeated fields given two values. func TestEncodeDecode5(t *testing.T) { pb := initGoTest(true) pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()} pb.F_BoolRepeated = []bool{false, true} pb.F_Int32Repeated = []int32{32, 33} pb.F_Int64Repeated = []int64{64, 65} pb.F_Fixed32Repeated = []uint32{3232, 3333} pb.F_Fixed64Repeated = []uint64{6464, 6565} pb.F_Uint32Repeated = []uint32{323232, 333333} pb.F_Uint64Repeated = []uint64{646464, 656565} pb.F_FloatRepeated = []float32{32., 33.} pb.F_DoubleRepeated = []float64{64., 65.} pb.F_StringRepeated = []string{"hello", "sailor"} pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")} pb.F_Sint32Repeated = []int32{32, -32} pb.F_Sint64Repeated = []int64{64, -64} pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()} overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "a00100"+ // field 20, encoding 0, value 0 "a00101"+ // field 20, encoding 0, value 1 "a80120"+ // field 21, encoding 0, value 32 "a80121"+ // field 21, encoding 0, value 33 "b00140"+ // field 22, encoding 0, value 64 "b00141"+ // field 22, encoding 0, value 65 "bd01a00c0000"+ // field 23, encoding 5, value 3232 "bd01050d0000"+ // field 23, encoding 5, value 3333 "c1014019000000000000"+ // field 24, encoding 1, value 6464 "c101a519000000000000"+ // field 24, encoding 1, value 6565 "c801a0dd13"+ // field 25, encoding 0, value 323232 "c80195ac14"+ // field 25, encoding 0, value 333333 "d001c0ba27"+ // field 26, encoding 0, value 646464 "d001b58928"+ // field 26, encoding 0, value 656565 "dd0100000042"+ // field 27, encoding 5, value 32.0 "dd0100000442"+ // field 27, encoding 5, value 33.0 "e1010000000000005040"+ // field 28, encoding 1, value 64.0 "e1010000000000405040"+ // field 28, encoding 1, value 65.0 "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello" "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor" "c00201"+ // field 40, encoding 0, value 1 "c80220"+ // field 41, encoding 0, value 32 "d00240"+ // field 42, encoding 0, value 64 "dd0240010000"+ // field 43, encoding 5, value 320 "e1028002000000000000"+ // field 44, encoding 1, value 640 "e8028019"+ // field 45, encoding 0, value 3200 "f0028032"+ // field 46, encoding 0, value 6400 "fd02e0659948"+ // field 47, encoding 5, value 314159.0 "81030000000050971041"+ // field 48, encoding 1, value 271828.0 "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n" "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "8305"+ // start group field 80 level 1 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" "8405"+ // end group field 80 level 1 "8305"+ // start group field 80 level 1 "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated" "8405"+ // end group field 80 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "ca0c03"+"626967"+ // field 201, encoding 2, string "big" "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose" "d00c40"+ // field 202, encoding 0, value 32 "d00c3f"+ // field 202, encoding 0, value -32 "d80c8001"+ // field 203, encoding 0, value 64 "d80c7f"+ // field 203, encoding 0, value -64 "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose" "90193f"+ // field 402, encoding 0, value 63 "98197f") // field 403, encoding 0, value 127 } // All required fields set, all packed repeated fields given two values. func TestEncodeDecode6(t *testing.T) { pb := initGoTest(false) pb.F_BoolRepeatedPacked = []bool{false, true} pb.F_Int32RepeatedPacked = []int32{32, 33} pb.F_Int64RepeatedPacked = []int64{64, 65} pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333} pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565} pb.F_Uint32RepeatedPacked = []uint32{323232, 333333} pb.F_Uint64RepeatedPacked = []uint64{646464, 656565} pb.F_FloatRepeatedPacked = []float32{32., 33.} pb.F_DoubleRepeatedPacked = []float64{64., 65.} pb.F_Sint32RepeatedPacked = []int32{32, -32} pb.F_Sint64RepeatedPacked = []int64{64, -64} overify(t, pb, "0807"+ // field 1, encoding 0, value 7 "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField) "5001"+ // field 10, encoding 0, value 1 "5803"+ // field 11, encoding 0, value 3 "6006"+ // field 12, encoding 0, value 6 "6d20000000"+ // field 13, encoding 5, value 32 "714000000000000000"+ // field 14, encoding 1, value 64 "78a019"+ // field 15, encoding 0, value 3232 "8001c032"+ // field 16, encoding 0, value 6464 "8d0100004a45"+ // field 17, encoding 5, value 3232.0 "9101000000000040b940"+ // field 18, encoding 1, value 6464.0 "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string" "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1 "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33 "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65 "aa0308"+ // field 53, encoding 2, 8 bytes "a00c0000050d0000"+ // value 3232, value 3333 "b20310"+ // field 54, encoding 2, 16 bytes "4019000000000000a519000000000000"+ // value 6464, value 6565 "ba0306"+ // field 55, encoding 2, 6 bytes "a0dd1395ac14"+ // value 323232, value 333333 "c20306"+ // field 56, encoding 2, 6 bytes "c0ba27b58928"+ // value 646464, value 656565 "ca0308"+ // field 57, encoding 2, 8 bytes "0000004200000442"+ // value 32.0, value 33.0 "d20310"+ // field 58, encoding 2, 16 bytes "00000000000050400000000000405040"+ // value 64.0, value 65.0 "b304"+ // start group field 70 level 1 "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required" "b404"+ // end group field 70 level 1 "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes" "b0063f"+ // field 102, encoding 0, 0x3f zigzag32 "b8067f"+ // field 103, encoding 0, 0x7f zigzag64 "b21f02"+ // field 502, encoding 2, 2 bytes "403f"+ // value 32, value -32 "ba1f03"+ // field 503, encoding 2, 3 bytes "80017f") // value 64, value -64 } // Test that we can encode empty bytes fields. func TestEncodeDecodeBytes1(t *testing.T) { pb := initGoTest(false) // Create our bytes pb.F_BytesRequired = []byte{} pb.F_BytesRepeated = [][]byte{{}} pb.F_BytesOptional = []byte{} d, err := Marshal(pb) if err != nil { t.Error(err) } pbd := new(GoTest) if err := Unmarshal(d, pbd); err != nil { t.Error(err) } if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 { t.Error("required empty bytes field is incorrect") } if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil { t.Error("repeated empty bytes field is incorrect") } if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 { t.Error("optional empty bytes field is incorrect") } } // Test that we encode nil-valued fields of a repeated bytes field correctly. // Since entries in a repeated field cannot be nil, nil must mean empty value. func TestEncodeDecodeBytes2(t *testing.T) { pb := initGoTest(false) // Create our bytes pb.F_BytesRepeated = [][]byte{nil} d, err := Marshal(pb) if err != nil { t.Error(err) } pbd := new(GoTest) if err := Unmarshal(d, pbd); err != nil { t.Error(err) } if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil { t.Error("Unexpected value for repeated bytes field") } } // All required fields set, defaults provided, all repeated fields given two values. func TestSkippingUnrecognizedFields(t *testing.T) { o := old() pb := initGoTestField() // Marshal it normally. o.Marshal(pb) // Now new a GoSkipTest record. skip := &GoSkipTest{ SkipInt32: Int32(32), SkipFixed32: Uint32(3232), SkipFixed64: Uint64(6464), SkipString: String("skipper"), Skipgroup: &GoSkipTest_SkipGroup{ GroupInt32: Int32(75), GroupString: String("wxyz"), }, } // Marshal it into same buffer. o.Marshal(skip) pbd := new(GoTestField) o.Unmarshal(pbd) // The __unrecognized field should be a marshaling of GoSkipTest skipd := new(GoSkipTest) o.SetBuf(pbd.XXX_unrecognized) o.Unmarshal(skipd) if *skipd.SkipInt32 != *skip.SkipInt32 { t.Error("skip int32", skipd.SkipInt32) } if *skipd.SkipFixed32 != *skip.SkipFixed32 { t.Error("skip fixed32", skipd.SkipFixed32) } if *skipd.SkipFixed64 != *skip.SkipFixed64 { t.Error("skip fixed64", skipd.SkipFixed64) } if *skipd.SkipString != *skip.SkipString { t.Error("skip string", *skipd.SkipString) } if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 { t.Error("skip group int32", skipd.Skipgroup.GroupInt32) } if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString { t.Error("skip group string", *skipd.Skipgroup.GroupString) } } // Check that unrecognized fields of a submessage are preserved. func TestSubmessageUnrecognizedFields(t *testing.T) { nm := &NewMessage{ Nested: &NewMessage_Nested{ Name: String("Nigel"), FoodGroup: String("carbs"), }, } b, err := Marshal(nm) if err != nil { t.Fatalf("Marshal of NewMessage: %v", err) } // Unmarshal into an OldMessage. om := new(OldMessage) if err := Unmarshal(b, om); err != nil { t.Fatalf("Unmarshal to OldMessage: %v", err) } exp := &OldMessage{ Nested: &OldMessage_Nested{ Name: String("Nigel"), // normal protocol buffer users should not do this XXX_unrecognized: []byte("\x12\x05carbs"), }, } if !Equal(om, exp) { t.Errorf("om = %v, want %v", om, exp) } // Clone the OldMessage. om = Clone(om).(*OldMessage) if !Equal(om, exp) { t.Errorf("Clone(om) = %v, want %v", om, exp) } // Marshal the OldMessage, then unmarshal it into an empty NewMessage. if b, err = Marshal(om); err != nil { t.Fatalf("Marshal of OldMessage: %v", err) } t.Logf("Marshal(%v) -> %q", om, b) nm2 := new(NewMessage) if err := Unmarshal(b, nm2); err != nil { t.Fatalf("Unmarshal to NewMessage: %v", err) } if !Equal(nm, nm2) { t.Errorf("NewMessage round-trip: %v => %v", nm, nm2) } } // Check that an int32 field can be upgraded to an int64 field. func TestNegativeInt32(t *testing.T) { om := &OldMessage{ Num: Int32(-1), } b, err := Marshal(om) if err != nil { t.Fatalf("Marshal of OldMessage: %v", err) } // Check the size. It should be 11 bytes; // 1 for the field/wire type, and 10 for the negative number. if len(b) != 11 { t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b) } // Unmarshal into a NewMessage. nm := new(NewMessage) if err := Unmarshal(b, nm); err != nil { t.Fatalf("Unmarshal to NewMessage: %v", err) } want := &NewMessage{ Num: Int64(-1), } if !Equal(nm, want) { t.Errorf("nm = %v, want %v", nm, want) } } // Check that we can grow an array (repeated field) to have many elements. // This test doesn't depend only on our encoding; for variety, it makes sure // we create, encode, and decode the correct contents explicitly. It's therefore // a bit messier. // This test also uses (and hence tests) the Marshal/Unmarshal functions // instead of the methods. func TestBigRepeated(t *testing.T) { pb := initGoTest(true) // Create the arrays const N = 50 // Internally the library starts much smaller. pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N) pb.F_Sint64Repeated = make([]int64, N) pb.F_Sint32Repeated = make([]int32, N) pb.F_BytesRepeated = make([][]byte, N) pb.F_StringRepeated = make([]string, N) pb.F_DoubleRepeated = make([]float64, N) pb.F_FloatRepeated = make([]float32, N) pb.F_Uint64Repeated = make([]uint64, N) pb.F_Uint32Repeated = make([]uint32, N) pb.F_Fixed64Repeated = make([]uint64, N) pb.F_Fixed32Repeated = make([]uint32, N) pb.F_Int64Repeated = make([]int64, N) pb.F_Int32Repeated = make([]int32, N) pb.F_BoolRepeated = make([]bool, N) pb.RepeatedField = make([]*GoTestField, N) // Fill in the arrays with checkable values. igtf := initGoTestField() igtrg := initGoTest_RepeatedGroup() for i := 0; i < N; i++ { pb.Repeatedgroup[i] = igtrg pb.F_Sint64Repeated[i] = int64(i) pb.F_Sint32Repeated[i] = int32(i) s := fmt.Sprint(i) pb.F_BytesRepeated[i] = []byte(s) pb.F_StringRepeated[i] = s pb.F_DoubleRepeated[i] = float64(i) pb.F_FloatRepeated[i] = float32(i) pb.F_Uint64Repeated[i] = uint64(i) pb.F_Uint32Repeated[i] = uint32(i) pb.F_Fixed64Repeated[i] = uint64(i) pb.F_Fixed32Repeated[i] = uint32(i) pb.F_Int64Repeated[i] = int64(i) pb.F_Int32Repeated[i] = int32(i) pb.F_BoolRepeated[i] = i%2 == 0 pb.RepeatedField[i] = igtf } // Marshal. buf, _ := Marshal(pb) // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) Unmarshal(buf, pbd) // Check the checkable values for i := uint64(0); i < N; i++ { if pbd.Repeatedgroup[i] == nil { // TODO: more checking? t.Error("pbd.Repeatedgroup bad") } var x uint64 x = uint64(pbd.F_Sint64Repeated[i]) if x != i { t.Error("pbd.F_Sint64Repeated bad", x, i) } x = uint64(pbd.F_Sint32Repeated[i]) if x != i { t.Error("pbd.F_Sint32Repeated bad", x, i) } s := fmt.Sprint(i) equalbytes(pbd.F_BytesRepeated[i], []byte(s), t) if pbd.F_StringRepeated[i] != s { t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i) } x = uint64(pbd.F_DoubleRepeated[i]) if x != i { t.Error("pbd.F_DoubleRepeated bad", x, i) } x = uint64(pbd.F_FloatRepeated[i]) if x != i { t.Error("pbd.F_FloatRepeated bad", x, i) } x = pbd.F_Uint64Repeated[i] if x != i { t.Error("pbd.F_Uint64Repeated bad", x, i) } x = uint64(pbd.F_Uint32Repeated[i]) if x != i { t.Error("pbd.F_Uint32Repeated bad", x, i) } x = pbd.F_Fixed64Repeated[i] if x != i { t.Error("pbd.F_Fixed64Repeated bad", x, i) } x = uint64(pbd.F_Fixed32Repeated[i]) if x != i { t.Error("pbd.F_Fixed32Repeated bad", x, i) } x = uint64(pbd.F_Int64Repeated[i]) if x != i { t.Error("pbd.F_Int64Repeated bad", x, i) } x = uint64(pbd.F_Int32Repeated[i]) if x != i { t.Error("pbd.F_Int32Repeated bad", x, i) } if pbd.F_BoolRepeated[i] != (i%2 == 0) { t.Error("pbd.F_BoolRepeated bad", x, i) } if pbd.RepeatedField[i] == nil { // TODO: more checking? t.Error("pbd.RepeatedField bad") } } } // Verify we give a useful message when decoding to the wrong structure type. func TestTypeMismatch(t *testing.T) { pb1 := initGoTest(true) // Marshal o := old() o.Marshal(pb1) // Now Unmarshal it to the wrong type. pb2 := initGoTestField() err := o.Unmarshal(pb2) if err == nil { t.Error("expected error, got no error") } else if !strings.Contains(err.Error(), "bad wiretype") { t.Error("expected bad wiretype error, got", err) } } func encodeDecode(t *testing.T, in, out Message, msg string) { buf, err := Marshal(in) if err != nil { t.Fatalf("failed marshaling %v: %v", msg, err) } if err := Unmarshal(buf, out); err != nil { t.Fatalf("failed unmarshaling %v: %v", msg, err) } } func TestPackedNonPackedDecoderSwitching(t *testing.T) { np, p := new(NonPackedTest), new(PackedTest) // non-packed -> packed np.A = []int32{0, 1, 1, 2, 3, 5} encodeDecode(t, np, p, "non-packed -> packed") if !reflect.DeepEqual(np.A, p.B) { t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B) } // packed -> non-packed np.Reset() p.B = []int32{3, 1, 4, 1, 5, 9} encodeDecode(t, p, np, "packed -> non-packed") if !reflect.DeepEqual(p.B, np.A) { t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A) } } func TestProto1RepeatedGroup(t *testing.T) { pb := &MessageList{ Message: []*MessageList_Message{ { Name: String("blah"), Count: Int32(7), }, // NOTE: pb.Message[1] is a nil nil, }, } o := old() err := o.Marshal(pb) if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") { t.Fatalf("unexpected or no error when marshaling: %v", err) } } // Test that enums work. Checks for a bug introduced by making enums // named types instead of int32: newInt32FromUint64 would crash with // a type mismatch in reflect.PointTo. func TestEnum(t *testing.T) { pb := new(GoEnum) pb.Foo = FOO_FOO1.Enum() o := old() if err := o.Marshal(pb); err != nil { t.Fatal("error encoding enum:", err) } pb1 := new(GoEnum) if err := o.Unmarshal(pb1); err != nil { t.Fatal("error decoding enum:", err) } if *pb1.Foo != FOO_FOO1 { t.Error("expected 7 but got ", *pb1.Foo) } } // Enum types have String methods. Check that enum fields can be printed. // We don't care what the value actually is, just as long as it doesn't crash. func TestPrintingNilEnumFields(t *testing.T) { pb := new(GoEnum) fmt.Sprintf("%+v", pb) } // Verify that absent required fields cause Marshal/Unmarshal to return errors. func TestRequiredFieldEnforcement(t *testing.T) { pb := new(GoTestField) _, err := Marshal(pb) if err == nil { t.Error("marshal: expected error, got nil") } else if strings.Index(err.Error(), "Label") < 0 { t.Errorf("marshal: bad error type: %v", err) } // A slightly sneaky, yet valid, proto. It encodes the same required field twice, // so simply counting the required fields is insufficient. // field 1, encoding 2, value "hi" buf := []byte("\x0A\x02hi\x0A\x02hi") err = Unmarshal(buf, pb) if err == nil { t.Error("unmarshal: expected error, got nil") } else if strings.Index(err.Error(), "{Unknown}") < 0 { t.Errorf("unmarshal: bad error type: %v", err) } } func TestTypedNilMarshal(t *testing.T) { // A typed nil should return ErrNil and not crash. _, err := Marshal((*GoEnum)(nil)) if err != ErrNil { t.Errorf("Marshal: got err %v, want ErrNil", err) } } // A type that implements the Marshaler interface, but is not nillable. type nonNillableInt uint64 func (nni nonNillableInt) Marshal() ([]byte, error) { return EncodeVarint(uint64(nni)), nil } type NNIMessage struct { nni nonNillableInt } func (*NNIMessage) Reset() {} func (*NNIMessage) String() string { return "" } func (*NNIMessage) ProtoMessage() {} // A type that implements the Marshaler interface and is nillable. type nillableMessage struct { x uint64 } func (nm *nillableMessage) Marshal() ([]byte, error) { return EncodeVarint(nm.x), nil } type NMMessage struct { nm *nillableMessage } func (*NMMessage) Reset() {} func (*NMMessage) String() string { return "" } func (*NMMessage) ProtoMessage() {} // Verify a type that uses the Marshaler interface, but has a nil pointer. func TestNilMarshaler(t *testing.T) { // Try a struct with a Marshaler field that is nil. // It should be directly marshable. nmm := new(NMMessage) if _, err := Marshal(nmm); err != nil { t.Error("unexpected error marshaling nmm: ", err) } // Try a struct with a Marshaler field that is not nillable. nnim := new(NNIMessage) nnim.nni = 7 var _ Marshaler = nnim.nni // verify it is truly a Marshaler if _, err := Marshal(nnim); err != nil { t.Error("unexpected error marshaling nnim: ", err) } } func TestAllSetDefaults(t *testing.T) { // Exercise SetDefaults with all scalar field types. m := &Defaults{ // NaN != NaN, so override that here. F_Nan: Float32(1.7), } expected := &Defaults{ F_Bool: Bool(true), F_Int32: Int32(32), F_Int64: Int64(64), F_Fixed32: Uint32(320), F_Fixed64: Uint64(640), F_Uint32: Uint32(3200), F_Uint64: Uint64(6400), F_Float: Float32(314159), F_Double: Float64(271828), F_String: String(`hello, "world!"` + "\n"), F_Bytes: []byte("Bignose"), F_Sint32: Int32(-32), F_Sint64: Int64(-64), F_Enum: Defaults_GREEN.Enum(), F_Pinf: Float32(float32(math.Inf(1))), F_Ninf: Float32(float32(math.Inf(-1))), F_Nan: Float32(1.7), StrZero: String(""), } SetDefaults(m) if !Equal(m, expected) { t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected) } } func TestSetDefaultsWithSetField(t *testing.T) { // Check that a set value is not overridden. m := &Defaults{ F_Int32: Int32(12), } SetDefaults(m) if v := m.GetF_Int32(); v != 12 { t.Errorf("m.FInt32 = %v, want 12", v) } } func TestSetDefaultsWithSubMessage(t *testing.T) { m := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("gopher"), }, } expected := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("gopher"), Port: Int32(4000), }, } SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) { m := &MyMessage{ RepInner: []*InnerMessage{{}}, } expected := &MyMessage{ RepInner: []*InnerMessage{{ Port: Int32(4000), }}, } SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestSetDefaultWithRepeatedNonMessage(t *testing.T) { m := &MyMessage{ Pet: []string{"turtle", "wombat"}, } expected := Clone(m) SetDefaults(m) if !Equal(m, expected) { t.Errorf("\n got %v\nwant %v", m, expected) } } func TestMaximumTagNumber(t *testing.T) { m := &MaxTag{ LastField: String("natural goat essence"), } buf, err := Marshal(m) if err != nil { t.Fatalf("proto.Marshal failed: %v", err) } m2 := new(MaxTag) if err := Unmarshal(buf, m2); err != nil { t.Fatalf("proto.Unmarshal failed: %v", err) } if got, want := m2.GetLastField(), *m.LastField; got != want { t.Errorf("got %q, want %q", got, want) } } func TestJSON(t *testing.T) { m := &MyMessage{ Count: Int32(4), Pet: []string{"bunny", "kitty"}, Inner: &InnerMessage{ Host: String("cauchy"), }, Bikeshed: MyMessage_GREEN.Enum(), } const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}` b, err := json.Marshal(m) if err != nil { t.Fatalf("json.Marshal failed: %v", err) } s := string(b) if s != expected { t.Errorf("got %s\nwant %s", s, expected) } received := new(MyMessage) if err := json.Unmarshal(b, received); err != nil { t.Fatalf("json.Unmarshal failed: %v", err) } if !Equal(received, m) { t.Fatalf("got %s, want %s", received, m) } // Test unmarshalling of JSON with symbolic enum name. const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}` received.Reset() if err := json.Unmarshal([]byte(old), received); err != nil { t.Fatalf("json.Unmarshal failed: %v", err) } if !Equal(received, m) { t.Fatalf("got %s, want %s", received, m) } } func TestBadWireType(t *testing.T) { b := []byte{7<<3 | 6} // field 7, wire type 6 pb := new(OtherMessage) if err := Unmarshal(b, pb); err == nil { t.Errorf("Unmarshal did not fail") } else if !strings.Contains(err.Error(), "unknown wire type") { t.Errorf("wrong error: %v", err) } } func TestBytesWithInvalidLength(t *testing.T) { // If a byte sequence has an invalid (negative) length, Unmarshal should not panic. b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0} Unmarshal(b, new(MyMessage)) } func TestLengthOverflow(t *testing.T) { // Overflowing a length should not panic. b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01} Unmarshal(b, new(MyMessage)) } func TestVarintOverflow(t *testing.T) { // Overflowing a 64-bit length should not be allowed. b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01} if err := Unmarshal(b, new(MyMessage)); err == nil { t.Fatalf("Overflowed uint64 length without error") } } func TestUnmarshalFuzz(t *testing.T) { const N = 1000 seed := time.Now().UnixNano() t.Logf("RNG seed is %d", seed) rng := rand.New(rand.NewSource(seed)) buf := make([]byte, 20) for i := 0; i < N; i++ { for j := range buf { buf[j] = byte(rng.Intn(256)) } fuzzUnmarshal(t, buf) } } func TestMergeMessages(t *testing.T) { pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}} data, err := Marshal(pb) if err != nil { t.Fatalf("Marshal: %v", err) } pb1 := new(MessageList) if err := Unmarshal(data, pb1); err != nil { t.Fatalf("first Unmarshal: %v", err) } if err := Unmarshal(data, pb1); err != nil { t.Fatalf("second Unmarshal: %v", err) } if len(pb1.Message) != 1 { t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message)) } pb2 := new(MessageList) if err := UnmarshalMerge(data, pb2); err != nil { t.Fatalf("first UnmarshalMerge: %v", err) } if err := UnmarshalMerge(data, pb2); err != nil { t.Fatalf("second UnmarshalMerge: %v", err) } if len(pb2.Message) != 2 { t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message)) } } func TestExtensionMarshalOrder(t *testing.T) { m := &MyMessage{Count: Int(123)} if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil { t.Fatalf("SetExtension: %v", err) } if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil { t.Fatalf("SetExtension: %v", err) } if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil { t.Fatalf("SetExtension: %v", err) } // Serialize m several times, and check we get the same bytes each time. var orig []byte for i := 0; i < 100; i++ { b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } if i == 0 { orig = b continue } if !bytes.Equal(b, orig) { t.Errorf("Bytes differ on attempt #%d", i) } } } // Many extensions, because small maps might not iterate differently on each iteration. var exts = []*ExtensionDesc{ E_X201, E_X202, E_X203, E_X204, E_X205, E_X206, E_X207, E_X208, E_X209, E_X210, E_X211, E_X212, E_X213, E_X214, E_X215, E_X216, E_X217, E_X218, E_X219, E_X220, E_X221, E_X222, E_X223, E_X224, E_X225, E_X226, E_X227, E_X228, E_X229, E_X230, E_X231, E_X232, E_X233, E_X234, E_X235, E_X236, E_X237, E_X238, E_X239, E_X240, E_X241, E_X242, E_X243, E_X244, E_X245, E_X246, E_X247, E_X248, E_X249, E_X250, } func TestMessageSetMarshalOrder(t *testing.T) { m := &MyMessageSet{} for _, x := range exts { if err := SetExtension(m, x, &Empty{}); err != nil { t.Fatalf("SetExtension: %v", err) } } buf, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } // Serialize m several times, and check we get the same bytes each time. for i := 0; i < 10; i++ { b1, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } if !bytes.Equal(b1, buf) { t.Errorf("Bytes differ on re-Marshal #%d", i) } m2 := &MyMessageSet{} if err := Unmarshal(buf, m2); err != nil { t.Errorf("Unmarshal: %v", err) } b2, err := Marshal(m2) if err != nil { t.Errorf("re-Marshal: %v", err) } if !bytes.Equal(b2, buf) { t.Errorf("Bytes differ on round-trip #%d", i) } } } func TestUnmarshalMergesMessages(t *testing.T) { // If a nested message occurs twice in the input, // the fields should be merged when decoding. a := &OtherMessage{ Key: Int64(123), Inner: &InnerMessage{ Host: String("polhode"), Port: Int32(1234), }, } aData, err := Marshal(a) if err != nil { t.Fatalf("Marshal(a): %v", err) } b := &OtherMessage{ Weight: Float32(1.2), Inner: &InnerMessage{ Host: String("herpolhode"), Connected: Bool(true), }, } bData, err := Marshal(b) if err != nil { t.Fatalf("Marshal(b): %v", err) } want := &OtherMessage{ Key: Int64(123), Weight: Float32(1.2), Inner: &InnerMessage{ Host: String("herpolhode"), Port: Int32(1234), Connected: Bool(true), }, } got := new(OtherMessage) if err := Unmarshal(append(aData, bData...), got); err != nil { t.Fatalf("Unmarshal: %v", err) } if !Equal(got, want) { t.Errorf("\n got %v\nwant %v", got, want) } } func TestEncodingSizes(t *testing.T) { tests := []struct { m Message n int }{ {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6}, {&Defaults{F_Int32: Int32(math.MinInt32)}, 11}, {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6}, {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6}, } for _, test := range tests { b, err := Marshal(test.m) if err != nil { t.Errorf("Marshal(%v): %v", test.m, err) continue } if len(b) != test.n { t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n) } } } func TestRequiredNotSetError(t *testing.T) { pb := initGoTest(false) pb.RequiredField.Label = nil pb.F_Int32Required = nil pb.F_Int64Required = nil expected := "0807" + // field 1, encoding 0, value 7 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField) "5001" + // field 10, encoding 0, value 1 "6d20000000" + // field 13, encoding 5, value 0x20 "714000000000000000" + // field 14, encoding 1, value 0x40 "78a019" + // field 15, encoding 0, value 0xca0 = 3232 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464 "8d0100004a45" + // field 17, encoding 5, value 3232.0 "9101000000000040b940" + // field 18, encoding 1, value 6464.0 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string" "b304" + // field 70, encoding 3, start group "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required" "b404" + // field 70, encoding 4, end group "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes" "b0063f" + // field 102, encoding 0, 0x3f zigzag32 "b8067f" // field 103, encoding 0, 0x7f zigzag64 o := old() bytes, err := Marshal(pb) if _, ok := err.(*RequiredNotSetError); !ok { fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("expected = %s", expected) } if strings.Index(err.Error(), "RequiredField.Label") < 0 { t.Errorf("marshal-1 wrong err msg: %v", err) } if !equal(bytes, expected, t) { o.DebugPrint("neq 1", bytes) t.Fatalf("expected = %s", expected) } // Now test Unmarshal by recreating the original buffer. pbd := new(GoTest) err = Unmarshal(bytes, pbd) if _, ok := err.(*RequiredNotSetError); !ok { t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("string = %s", expected) } if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 { t.Errorf("unmarshal wrong err msg: %v", err) } bytes, err = Marshal(pbd) if _, ok := err.(*RequiredNotSetError); !ok { t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err) o.DebugPrint("", bytes) t.Fatalf("string = %s", expected) } if strings.Index(err.Error(), "RequiredField.Label") < 0 { t.Errorf("marshal-2 wrong err msg: %v", err) } if !equal(bytes, expected, t) { o.DebugPrint("neq 2", bytes) t.Fatalf("string = %s", expected) } } func fuzzUnmarshal(t *testing.T, data []byte) { defer func() { if e := recover(); e != nil { t.Errorf("These bytes caused a panic: %+v", data) t.Logf("Stack:\n%s", debug.Stack()) t.FailNow() } }() pb := new(MyMessage) Unmarshal(data, pb) } func TestMapFieldMarshal(t *testing.T) { m := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Rob", 4: "Ian", 8: "Dave", }, } b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } // b should be the concatenation of these three byte sequences in some order. parts := []string{ "\n\a\b\x01\x12\x03Rob", "\n\a\b\x04\x12\x03Ian", "\n\b\b\x08\x12\x04Dave", } ok := false for i := range parts { for j := range parts { if j == i { continue } for k := range parts { if k == i || k == j { continue } try := parts[i] + parts[j] + parts[k] if bytes.Equal(b, []byte(try)) { ok = true break } } } } if !ok { t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2]) } t.Logf("FYI b: %q", b) (new(Buffer)).DebugPrint("Dump of b", b) } func TestMapFieldRoundTrips(t *testing.T) { m := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Rob", 4: "Ian", 8: "Dave", }, MsgMapping: map[int64]*FloatingPoint{ 0x7001: &FloatingPoint{F: Float64(2.0)}, }, ByteMapping: map[bool][]byte{ false: []byte("that's not right!"), true: []byte("aye, 'tis true!"), }, } b, err := Marshal(m) if err != nil { t.Fatalf("Marshal: %v", err) } t.Logf("FYI b: %q", b) m2 := new(MessageWithMap) if err := Unmarshal(b, m2); err != nil { t.Fatalf("Unmarshal: %v", err) } for _, pair := range [][2]interface{}{ {m.NameMapping, m2.NameMapping}, {m.MsgMapping, m2.MsgMapping}, {m.ByteMapping, m2.ByteMapping}, } { if !reflect.DeepEqual(pair[0], pair[1]) { t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1]) } } } func TestMapFieldWithNil(t *testing.T) { m := &MessageWithMap{ MsgMapping: map[int64]*FloatingPoint{ 1: nil, }, } b, err := Marshal(m) if err == nil { t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b) } } func TestOneof(t *testing.T) { m := &Communique{} b, err := Marshal(m) if err != nil { t.Fatalf("Marshal of empty message with oneof: %v", err) } if len(b) != 0 { t.Errorf("Marshal of empty message yielded too many bytes: %v", b) } m = &Communique{ Union: &Communique_Name{"Barry"}, } // Round-trip. b, err = Marshal(m) if err != nil { t.Fatalf("Marshal of message with oneof: %v", err) } if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5) t.Errorf("Incorrect marshal of message with oneof: %v", b) } m.Reset() if err := Unmarshal(b, m); err != nil { t.Fatalf("Unmarshal of message with oneof: %v", err) } if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" { t.Errorf("After round trip, Union = %+v", m.Union) } if name := m.GetName(); name != "Barry" { t.Errorf("After round trip, GetName = %q, want %q", name, "Barry") } // Let's try with a message in the oneof. m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}} b, err = Marshal(m) if err != nil { t.Fatalf("Marshal of message with oneof set to message: %v", err) } if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16) t.Errorf("Incorrect marshal of message with oneof set to message: %v", b) } m.Reset() if err := Unmarshal(b, m); err != nil { t.Fatalf("Unmarshal of message with oneof set to message: %v", err) } ss, ok := m.Union.(*Communique_Msg) if !ok || ss.Msg.GetStringField() != "deep deep string" { t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union) } } func TestInefficientPackedBool(t *testing.T) { // https://github.com/golang/protobuf/issues/76 inp := []byte{ 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes // Usually a bool should take a single byte, // but it is permitted to be any varint. 0xb9, 0x30, } if err := Unmarshal(inp, new(MoreRepeated)); err != nil { t.Error(err) } } // Benchmarks func testMsg() *GoTest { pb := initGoTest(true) const N = 1000 // Internally the library starts much smaller. pb.F_Int32Repeated = make([]int32, N) pb.F_DoubleRepeated = make([]float64, N) for i := 0; i < N; i++ { pb.F_Int32Repeated[i] = int32(i) pb.F_DoubleRepeated[i] = float64(i) } return pb } func bytesMsg() *GoTest { pb := initGoTest(true) buf := make([]byte, 4000) for i := range buf { buf[i] = byte(i) } pb.F_BytesDefaulted = buf return pb } func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) { d, _ := marshal(pb) b.SetBytes(int64(len(d))) b.ResetTimer() for i := 0; i < b.N; i++ { marshal(pb) } } func benchmarkBufferMarshal(b *testing.B, pb Message) { p := NewBuffer(nil) benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { p.Reset() err := p.Marshal(pb0) return p.Bytes(), err }) } func benchmarkSize(b *testing.B, pb Message) { benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) { Size(pb) return nil, nil }) } func newOf(pb Message) Message { in := reflect.ValueOf(pb) if in.IsNil() { return pb } return reflect.New(in.Type().Elem()).Interface().(Message) } func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) { d, _ := Marshal(pb) b.SetBytes(int64(len(d))) pbd := newOf(pb) b.ResetTimer() for i := 0; i < b.N; i++ { unmarshal(d, pbd) } } func benchmarkBufferUnmarshal(b *testing.B, pb Message) { p := NewBuffer(nil) benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error { p.SetBuf(d) return p.Unmarshal(pb0) }) } // Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes} func BenchmarkMarshal(b *testing.B) { benchmarkMarshal(b, testMsg(), Marshal) } func BenchmarkBufferMarshal(b *testing.B) { benchmarkBufferMarshal(b, testMsg()) } func BenchmarkSize(b *testing.B) { benchmarkSize(b, testMsg()) } func BenchmarkUnmarshal(b *testing.B) { benchmarkUnmarshal(b, testMsg(), Unmarshal) } func BenchmarkBufferUnmarshal(b *testing.B) { benchmarkBufferUnmarshal(b, testMsg()) } func BenchmarkMarshalBytes(b *testing.B) { benchmarkMarshal(b, bytesMsg(), Marshal) } func BenchmarkBufferMarshalBytes(b *testing.B) { benchmarkBufferMarshal(b, bytesMsg()) } func BenchmarkSizeBytes(b *testing.B) { benchmarkSize(b, bytesMsg()) } func BenchmarkUnmarshalBytes(b *testing.B) { benchmarkUnmarshal(b, bytesMsg(), Unmarshal) } func BenchmarkBufferUnmarshalBytes(b *testing.B) { benchmarkBufferUnmarshal(b, bytesMsg()) } func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) { b.StopTimer() pb := initGoTestField() skip := &GoSkipTest{ SkipInt32: Int32(32), SkipFixed32: Uint32(3232), SkipFixed64: Uint64(6464), SkipString: String("skipper"), Skipgroup: &GoSkipTest_SkipGroup{ GroupInt32: Int32(75), GroupString: String("wxyz"), }, } pbd := new(GoTestField) p := NewBuffer(nil) p.Marshal(pb) p.Marshal(skip) p2 := NewBuffer(nil) b.StartTimer() for i := 0; i < b.N; i++ { p2.SetBuf(p.Bytes()) p2.Unmarshal(pbd) } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/clone.go ================================================ // 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().(extendableProto); ok { emOut := out.Addr().Interface().(extendableProto) mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap()) } 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 } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/clone_test.go ================================================ // 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. package proto_test import ( "testing" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) var cloneTestMessage = &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &pb.InnerMessage{ Host: proto.String("niles"), Port: proto.Int32(9099), Connected: proto.Bool(true), }, Others: []*pb.OtherMessage{ { Value: []byte("some bytes"), }, }, Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, } func init() { ext := &pb.Ext{ Data: proto.String("extension"), } if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil { panic("SetExtension: " + err.Error()) } } func TestClone(t *testing.T) { m := proto.Clone(cloneTestMessage).(*pb.MyMessage) if !proto.Equal(m, cloneTestMessage) { t.Errorf("Clone(%v) = %v", cloneTestMessage, m) } // Verify it was a deep copy. *m.Inner.Port++ if proto.Equal(m, cloneTestMessage) { t.Error("Mutating clone changed the original") } // Byte fields and repeated fields should be copied. if &m.Pet[0] == &cloneTestMessage.Pet[0] { t.Error("Pet: repeated field not copied") } if &m.Others[0] == &cloneTestMessage.Others[0] { t.Error("Others: repeated field not copied") } if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] { t.Error("Others[0].Value: bytes field not copied") } if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] { t.Error("RepBytes: repeated field not copied") } if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] { t.Error("RepBytes[0]: bytes field not copied") } } func TestCloneNil(t *testing.T) { var m *pb.MyMessage if c := proto.Clone(m); !proto.Equal(m, c) { t.Errorf("Clone(%v) = %v", m, c) } } var mergeTests = []struct { src, dst, want proto.Message }{ { src: &pb.MyMessage{ Count: proto.Int32(42), }, dst: &pb.MyMessage{ Name: proto.String("Dave"), }, want: &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), }, }, { src: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("hey"), Connected: proto.Bool(true), }, Pet: []string{"horsey"}, Others: []*pb.OtherMessage{ { Value: []byte("some bytes"), }, }, }, dst: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("niles"), Port: proto.Int32(9099), }, Pet: []string{"bunny", "kitty"}, Others: []*pb.OtherMessage{ { Key: proto.Int64(31415926535), }, { // Explicitly test a src=nil field Inner: nil, }, }, }, want: &pb.MyMessage{ Inner: &pb.InnerMessage{ Host: proto.String("hey"), Connected: proto.Bool(true), Port: proto.Int32(9099), }, Pet: []string{"bunny", "kitty", "horsey"}, Others: []*pb.OtherMessage{ { Key: proto.Int64(31415926535), }, {}, { Value: []byte("some bytes"), }, }, }, }, { src: &pb.MyMessage{ RepBytes: [][]byte{[]byte("wow")}, }, dst: &pb.MyMessage{ Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham")}, }, want: &pb.MyMessage{ Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(6), }, RepBytes: [][]byte{[]byte("sham"), []byte("wow")}, }, }, // Check that a scalar bytes field replaces rather than appends. { src: &pb.OtherMessage{Value: []byte("foo")}, dst: &pb.OtherMessage{Value: []byte("bar")}, want: &pb.OtherMessage{Value: []byte("foo")}, }, { src: &pb.MessageWithMap{ NameMapping: map[int32]string{6: "Nigel"}, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, }, ByteMapping: map[bool][]byte{true: []byte("wowsa")}, }, dst: &pb.MessageWithMap{ NameMapping: map[int32]string{ 6: "Bruce", // should be overwritten 7: "Andrew", }, }, want: &pb.MessageWithMap{ NameMapping: map[int32]string{ 6: "Nigel", 7: "Andrew", }, MsgMapping: map[int64]*pb.FloatingPoint{ 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)}, }, ByteMapping: map[bool][]byte{true: []byte("wowsa")}, }, }, // proto3 shouldn't merge zero values, // in the same way that proto2 shouldn't merge nils. { src: &proto3pb.Message{ Name: "Aaron", Data: []byte(""), // zero value, but not nil }, dst: &proto3pb.Message{ HeightInCm: 176, Data: []byte("texas!"), }, want: &proto3pb.Message{ Name: "Aaron", HeightInCm: 176, Data: []byte("texas!"), }, }, // Oneof fields should merge by assignment. { src: &pb.Communique{ Union: &pb.Communique_Number{41}, }, dst: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, want: &pb.Communique{ Union: &pb.Communique_Number{41}, }, }, // Oneof nil is the same as not set. { src: &pb.Communique{}, dst: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, want: &pb.Communique{ Union: &pb.Communique_Name{"Bobby Tables"}, }, }, } func TestMerge(t *testing.T) { for _, m := range mergeTests { got := proto.Clone(m.dst) proto.Merge(got, m.src) if !proto.Equal(got, m.want) { t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want) } } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/decode.go ================================================ // 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) { // x, n already 0 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 } // DecodeVarint reads a varint-encoded integer from the Buffer. // This is the format for the // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func (p *Buffer) DecodeVarint() (x uint64, err error) { // x, err already 0 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 } // 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. 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 { 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 := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) { if err = o.skip(st, tag, wire); err == nil { ext := e.ExtensionMap()[int32(tag)] // may be missing ext.enc = append(ext.enc, o.buf[oi:o.index]...) e.ExtensionMap()[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() || !valelem.IsValid() { // We did not decode the key or the value in the map entry. // Either way, it's an invalid map entry. return fmt.Errorf("proto: bad map data: missing key/val") } 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 } ================================================ FILE: vendor/github.com/golang/protobuf/proto/encode.go ================================================ // 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") // ErrNil is the error returned if Marshal is called with nil. ErrNil = errors.New("proto: Marshal called with nil") ) // 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 // 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) var state errorState if err != nil && !state.shouldContinue(err, nil) { return nil, err } if p.buf == nil && err == nil { // Return a non-nil slice on success. return []byte{}, nil } 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() if err != nil { return err } p.buf = append(p.buf, data...) return nil } 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++ } 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++ } 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 += 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 } // 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 { v := *structPointer_ExtMap(base, p.field) if err := encodeExtensionMap(v); err != nil { return err } // 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 sizeExtensionMap(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 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 { 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) // The only illegal map entry values are nil message pointers. if val.Kind() == reflect.Ptr && val.IsNil() { return errors.New("proto: map has nil element") } 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 } } } } // Do oneof fields. if prop.oneofMarshaler != nil { m := structPointer_Interface(base, prop.stype).(Message) if err := prop.oneofMarshaler(m, o); err != nil { return err } } // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) 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 } ================================================ FILE: vendor/github.com/golang/protobuf/proto/equal.go ================================================ // 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 (a "bytes" field, although represented by []byte, is not a repeated field) - 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. - 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_extensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_extensions") if !equalExtensions(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: 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. // em1 and em2 are extension maps. func equalExtensions(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 } ================================================ FILE: vendor/github.com/golang/protobuf/proto/equal_test.go ================================================ // 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. package proto_test import ( "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) // Four identical base messages. // The init function adds extensions to some of them. var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)} var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)} var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)} var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)} // Two messages with non-message extensions. var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)} var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)} func init() { ext1 := &pb.Ext{Data: String("Kirk")} ext2 := &pb.Ext{Data: String("Picard")} // messageWithExtension1a has ext1, but never marshals it. if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil { panic("SetExtension on 1a failed: " + err.Error()) } // messageWithExtension1b is the unmarshaled form of messageWithExtension1a. if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil { panic("SetExtension on 1b failed: " + err.Error()) } buf, err := Marshal(messageWithExtension1b) if err != nil { panic("Marshal of 1b failed: " + err.Error()) } messageWithExtension1b.Reset() if err := Unmarshal(buf, messageWithExtension1b); err != nil { panic("Unmarshal of 1b failed: " + err.Error()) } // messageWithExtension2 has ext2. if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil { panic("SetExtension on 2 failed: " + err.Error()) } if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil { panic("SetExtension on Int32-1 failed: " + err.Error()) } if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil { panic("SetExtension on Int32-2 failed: " + err.Error()) } } var EqualTests = []struct { desc string a, b Message exp bool }{ {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false}, {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true}, {"nil vs nil", nil, nil, true}, {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true}, {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false}, {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false}, {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false}, {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false}, {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false}, {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true}, {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false}, {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false}, {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false}, {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true}, {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true}, {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true}, {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true}, { "nested, different", &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}}, &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}}, false, }, { "nested, equal", &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}}, true, }, {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true}, {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true}, {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false}, { "repeated bytes", &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}}, true, }, // In proto3, []byte{} and []byte(nil) are equal. {"proto3 bytes, empty vs nil", &proto3pb.Message{Data: []byte{}}, &proto3pb.Message{Data: nil}, true}, {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false}, {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true}, {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false}, {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true}, {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false}, { "message with group", &pb.MyMessage{ Count: Int32(1), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: Int32(5), }, }, &pb.MyMessage{ Count: Int32(1), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: Int32(5), }, }, true, }, { "map same", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, true, }, { "map different entry", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}}, false, }, { "map different key only", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}}, false, }, { "map different value only", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}}, &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}}, false, }, { "oneof same", &pb.Communique{Union: &pb.Communique_Number{41}}, &pb.Communique{Union: &pb.Communique_Number{41}}, true, }, { "oneof one nil", &pb.Communique{Union: &pb.Communique_Number{41}}, &pb.Communique{}, false, }, { "oneof different", &pb.Communique{Union: &pb.Communique_Number{41}}, &pb.Communique{Union: &pb.Communique_Name{"Bobby Tables"}}, false, }, } func TestEqual(t *testing.T) { for _, tc := range EqualTests { if res := Equal(tc.a, tc.b); res != tc.exp { t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp) } } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/extensions.go ================================================ // 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 that may be extended. type extendableProto interface { Message ExtensionRangeArray() []ExtensionRange ExtensionMap() map[int32]Extension } var extendableProtoType = reflect.TypeOf((*extendableProto)(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 } 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 extendableProto, id int32, b []byte) { base.ExtensionMap()[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 { // Check the extended type. if a, b := reflect.TypeOf(pb), 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 } // encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m. func encodeExtensionMap(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 sizeExtensionMap(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 extendableProto, extension *ExtensionDesc) bool { // TODO: Check types, field numbers, etc.? _, ok := pb.ExtensionMap()[extension.Field] return ok } // ClearExtension removes the given extension from pb. func ClearExtension(pb extendableProto, extension *ExtensionDesc) { // TODO: Check types, field numbers, etc.? delete(pb.ExtensionMap(), 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 extendableProto, extension *ExtensionDesc) (interface{}, error) { if err := checkExtensionTypes(pb, extension); err != nil { return nil, err } emap := pb.ExtensionMap() 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 := pb.(extendableProto) if !ok { err = errors.New("proto: not an extendable proto") return } 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 } // SetExtension sets the specified extension of pb to the specified value. func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error { if err := checkExtensionTypes(pb, 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) } pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value} return nil } // 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()] } ================================================ FILE: vendor/github.com/golang/protobuf/proto/extensions_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 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_test import ( "bytes" "fmt" "reflect" "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/testdata" ) func TestGetExtensionsWithMissingExtensions(t *testing.T) { msg := &pb.MyMessage{} ext1 := &pb.Ext{} if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { t.Fatalf("Could not set ext1: %s", ext1) } exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{ pb.E_Ext_More, pb.E_Ext_Text, }) if err != nil { t.Fatalf("GetExtensions() failed: %s", err) } if exts[0] != ext1 { t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0]) } if exts[1] != nil { t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1]) } } func TestGetExtensionStability(t *testing.T) { check := func(m *pb.MyMessage) bool { ext1, err := proto.GetExtension(m, pb.E_Ext_More) if err != nil { t.Fatalf("GetExtension() failed: %s", err) } ext2, err := proto.GetExtension(m, pb.E_Ext_More) if err != nil { t.Fatalf("GetExtension() failed: %s", err) } return ext1 == ext2 } msg := &pb.MyMessage{Count: proto.Int32(4)} ext0 := &pb.Ext{} if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil { t.Fatalf("Could not set ext1: %s", ext0) } if !check(msg) { t.Errorf("GetExtension() not stable before marshaling") } bb, err := proto.Marshal(msg) if err != nil { t.Fatalf("Marshal() failed: %s", err) } msg1 := &pb.MyMessage{} err = proto.Unmarshal(bb, msg1) if err != nil { t.Fatalf("Unmarshal() failed: %s", err) } if !check(msg1) { t.Errorf("GetExtension() not stable after unmarshaling") } } func TestGetExtensionDefaults(t *testing.T) { var setFloat64 float64 = 1 var setFloat32 float32 = 2 var setInt32 int32 = 3 var setInt64 int64 = 4 var setUint32 uint32 = 5 var setUint64 uint64 = 6 var setBool = true var setBool2 = false var setString = "Goodnight string" var setBytes = []byte("Goodnight bytes") var setEnum = pb.DefaultsMessage_TWO type testcase struct { ext *proto.ExtensionDesc // Extension we are testing. want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail). def interface{} // Expected value of extension after ClearExtension(). } tests := []testcase{ {pb.E_NoDefaultDouble, setFloat64, nil}, {pb.E_NoDefaultFloat, setFloat32, nil}, {pb.E_NoDefaultInt32, setInt32, nil}, {pb.E_NoDefaultInt64, setInt64, nil}, {pb.E_NoDefaultUint32, setUint32, nil}, {pb.E_NoDefaultUint64, setUint64, nil}, {pb.E_NoDefaultSint32, setInt32, nil}, {pb.E_NoDefaultSint64, setInt64, nil}, {pb.E_NoDefaultFixed32, setUint32, nil}, {pb.E_NoDefaultFixed64, setUint64, nil}, {pb.E_NoDefaultSfixed32, setInt32, nil}, {pb.E_NoDefaultSfixed64, setInt64, nil}, {pb.E_NoDefaultBool, setBool, nil}, {pb.E_NoDefaultBool, setBool2, nil}, {pb.E_NoDefaultString, setString, nil}, {pb.E_NoDefaultBytes, setBytes, nil}, {pb.E_NoDefaultEnum, setEnum, nil}, {pb.E_DefaultDouble, setFloat64, float64(3.1415)}, {pb.E_DefaultFloat, setFloat32, float32(3.14)}, {pb.E_DefaultInt32, setInt32, int32(42)}, {pb.E_DefaultInt64, setInt64, int64(43)}, {pb.E_DefaultUint32, setUint32, uint32(44)}, {pb.E_DefaultUint64, setUint64, uint64(45)}, {pb.E_DefaultSint32, setInt32, int32(46)}, {pb.E_DefaultSint64, setInt64, int64(47)}, {pb.E_DefaultFixed32, setUint32, uint32(48)}, {pb.E_DefaultFixed64, setUint64, uint64(49)}, {pb.E_DefaultSfixed32, setInt32, int32(50)}, {pb.E_DefaultSfixed64, setInt64, int64(51)}, {pb.E_DefaultBool, setBool, true}, {pb.E_DefaultBool, setBool2, true}, {pb.E_DefaultString, setString, "Hello, string"}, {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")}, {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE}, } checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error { val, err := proto.GetExtension(msg, test.ext) if err != nil { if valWant != nil { return fmt.Errorf("GetExtension(): %s", err) } if want := proto.ErrMissingExtension; err != want { return fmt.Errorf("Unexpected error: got %v, want %v", err, want) } return nil } // All proto2 extension values are either a pointer to a value or a slice of values. ty := reflect.TypeOf(val) tyWant := reflect.TypeOf(test.ext.ExtensionType) if got, want := ty, tyWant; got != want { return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want) } tye := ty.Elem() tyeWant := tyWant.Elem() if got, want := tye, tyeWant; got != want { return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want) } // Check the name of the type of the value. // If it is an enum it will be type int32 with the name of the enum. if got, want := tye.Name(), tye.Name(); got != want { return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want) } // Check that value is what we expect. // If we have a pointer in val, get the value it points to. valExp := val if ty.Kind() == reflect.Ptr { valExp = reflect.ValueOf(val).Elem().Interface() } if got, want := valExp, valWant; !reflect.DeepEqual(got, want) { return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want) } return nil } setTo := func(test testcase) interface{} { setTo := reflect.ValueOf(test.want) if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr { setTo = reflect.New(typ).Elem() setTo.Set(reflect.New(setTo.Type().Elem())) setTo.Elem().Set(reflect.ValueOf(test.want)) } return setTo.Interface() } for _, test := range tests { msg := &pb.DefaultsMessage{} name := test.ext.Name // Check the initial value. if err := checkVal(test, msg, test.def); err != nil { t.Errorf("%s: %v", name, err) } // Set the per-type value and check value. name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want) if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil { t.Errorf("%s: SetExtension(): %v", name, err) continue } if err := checkVal(test, msg, test.want); err != nil { t.Errorf("%s: %v", name, err) continue } // Set and check the value. name += " (cleared)" proto.ClearExtension(msg, test.ext) if err := checkVal(test, msg, test.def); err != nil { t.Errorf("%s: %v", name, err) } } } func TestExtensionsRoundTrip(t *testing.T) { msg := &pb.MyMessage{} ext1 := &pb.Ext{ Data: proto.String("hi"), } ext2 := &pb.Ext{ Data: proto.String("there"), } exists := proto.HasExtension(msg, pb.E_Ext_More) if exists { t.Error("Extension More present unexpectedly") } if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil { t.Error(err) } if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil { t.Error(err) } e, err := proto.GetExtension(msg, pb.E_Ext_More) if err != nil { t.Error(err) } x, ok := e.(*pb.Ext) if !ok { t.Errorf("e has type %T, expected testdata.Ext", e) } else if *x.Data != "there" { t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x) } proto.ClearExtension(msg, pb.E_Ext_More) if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension { t.Errorf("got %v, expected ErrMissingExtension", e) } if _, err := proto.GetExtension(msg, pb.E_X215); err == nil { t.Error("expected bad extension error, got nil") } if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil { t.Error("expected extension err") } if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil { t.Error("expected some sort of type mismatch error, got nil") } } func TestNilExtension(t *testing.T) { msg := &pb.MyMessage{ Count: proto.Int32(1), } if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil { t.Fatal(err) } if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil { t.Error("expected SetExtension to fail due to a nil extension") } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want { t.Errorf("expected error %v, got %v", want, err) } // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal. } func TestMarshalUnmarshalRepeatedExtension(t *testing.T) { // Add a repeated extension to the result. tests := []struct { name string ext []*pb.ComplexExtension }{ { "two fields", []*pb.ComplexExtension{ {First: proto.Int32(7)}, {Second: proto.Int32(11)}, }, }, { "repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {Third: []int32{2000}}, }, }, { "two fields and repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {First: proto.Int32(9)}, {Second: proto.Int32(21)}, {Third: []int32{2000}}, }, }, } for _, test := range tests { // Marshal message with a repeated extension. msg1 := new(pb.OtherMessage) err := proto.SetExtension(msg1, pb.E_RComplex, test.ext) if err != nil { t.Fatalf("[%s] Error setting extension: %v", test.name, err) } b, err := proto.Marshal(msg1) if err != nil { t.Fatalf("[%s] Error marshaling message: %v", test.name, err) } // Unmarshal and read the merged proto. msg2 := new(pb.OtherMessage) err = proto.Unmarshal(b, msg2) if err != nil { t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) } e, err := proto.GetExtension(msg2, pb.E_RComplex) if err != nil { t.Fatalf("[%s] Error getting extension: %v", test.name, err) } ext := e.([]*pb.ComplexExtension) if ext == nil { t.Fatalf("[%s] Invalid extension", test.name) } if !reflect.DeepEqual(ext, test.ext) { t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext) } } } func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) { // We may see multiple instances of the same extension in the wire // format. For example, the proto compiler may encode custom options in // this way. Here, we verify that we merge the extensions together. tests := []struct { name string ext []*pb.ComplexExtension }{ { "two fields", []*pb.ComplexExtension{ {First: proto.Int32(7)}, {Second: proto.Int32(11)}, }, }, { "repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {Third: []int32{2000}}, }, }, { "two fields and repeated field", []*pb.ComplexExtension{ {Third: []int32{1000}}, {First: proto.Int32(9)}, {Second: proto.Int32(21)}, {Third: []int32{2000}}, }, }, } for _, test := range tests { var buf bytes.Buffer var want pb.ComplexExtension // Generate a serialized representation of a repeated extension // by catenating bytes together. for i, e := range test.ext { // Merge to create the wanted proto. proto.Merge(&want, e) // serialize the message msg := new(pb.OtherMessage) err := proto.SetExtension(msg, pb.E_Complex, e) if err != nil { t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err) } b, err := proto.Marshal(msg) if err != nil { t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err) } buf.Write(b) } // Unmarshal and read the merged proto. msg2 := new(pb.OtherMessage) err := proto.Unmarshal(buf.Bytes(), msg2) if err != nil { t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err) } e, err := proto.GetExtension(msg2, pb.E_Complex) if err != nil { t.Fatalf("[%s] Error getting extension: %v", test.name, err) } ext := e.(*pb.ComplexExtension) if ext == nil { t.Fatalf("[%s] Invalid extension", test.name) } if !reflect.DeepEqual(*ext, want) { t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want) } } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/lib.go ================================================ // 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 // write 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 } // 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 ================================================ FILE: vendor/github.com/golang/protobuf/proto/message_set.go ================================================ // 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(m map[int32]Extension) ([]byte, error) { if err := encodeExtensionMap(m); err != nil { return nil, err } // 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, m map[int32]Extension) error { 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(m map[int32]Extension) ([]byte, error) { 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, m map[int32]Extension) 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, } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/message_set_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 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 import ( "bytes" "testing" ) func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { // Check that a repeated message set entry will be concatenated. in := &messageSet{ Item: []*_MessageSet_Item{ {TypeId: Int32(12345), Message: []byte("hoo")}, {TypeId: Int32(12345), Message: []byte("hah")}, }, } b, err := Marshal(in) if err != nil { t.Fatalf("Marshal: %v", err) } t.Logf("Marshaled bytes: %q", b) m := make(map[int32]Extension) if err := UnmarshalMessageSet(b, m); err != nil { t.Fatalf("UnmarshalMessageSet: %v", err) } ext, ok := m[12345] if !ok { t.Fatalf("Didn't retrieve extension 12345; map is %v", m) } // Skip wire type/field number and length varints. got := skipVarint(skipVarint(ext.enc)) if want := []byte("hoohah"); !bytes.Equal(got, want) { t.Errorf("Combined extension is %q, want %q", got, want) } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/pointer_reflect.go ================================================ // 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 // 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) } // 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)} } ================================================ FILE: vendor/github.com/golang/protobuf/proto/pointer_unsafe.go ================================================ // 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 // 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_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))) } ================================================ FILE: vendor/github.com/golang/protobuf/proto/properties.go ================================================ // 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) 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" } if p.OrigName != p.Name { s += ",name=" + p.OrigName } 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, "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.enc = (*Buffer).enc_slice_byte p.dec = (*Buffer).dec_slice_byte p.size = size_slice_byte // This is a []byte, which is either a bytes field, // or the value of a map field. In the latter case, // we always encode an empty []byte, so we should not // use the proto3 enc/size funcs. // f == nil iff this is the key/value of a map field. if p.proto3 && f != nil { p.enc = (*Buffer).enc_proto3_slice_byte p.size = size_proto3_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) 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_extensions" { // special case p.enc = (*Buffer).enc_map p.dec = nil // not needed p.size = size_map } if f.Name == "XXX_unrecognized" { // special case prop.unrecField = toField(&f) } oneof := f.Tag.Get("protobuf_oneof") != "" // special case 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 { 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] } ================================================ FILE: vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 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. syntax = "proto3"; import "testdata/test.proto"; package proto3_proto; message Message { enum Humour { UNKNOWN = 0; PUNS = 1; SLAPSTICK = 2; BILL_BAILEY = 3; } string name = 1; Humour hilarity = 2; uint32 height_in_cm = 3; bytes data = 4; int64 result_count = 7; bool true_scotsman = 8; float score = 9; repeated uint64 key = 5; Nested nested = 6; map terrain = 10; testdata.SubDefaults proto2_field = 11; map proto2_value = 13; } message Nested { string bunny = 1; } message MessageWithMap { map byte_mapping = 1; } ================================================ FILE: vendor/github.com/golang/protobuf/proto/proto3_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 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_test import ( "testing" "github.com/golang/protobuf/proto" pb "github.com/golang/protobuf/proto/proto3_proto" tpb "github.com/golang/protobuf/proto/testdata" ) func TestProto3ZeroValues(t *testing.T) { tests := []struct { desc string m proto.Message }{ {"zero message", &pb.Message{}}, {"empty bytes field", &pb.Message{Data: []byte{}}}, } for _, test := range tests { b, err := proto.Marshal(test.m) if err != nil { t.Errorf("%s: proto.Marshal: %v", test.desc, err) continue } if len(b) > 0 { t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) } } } func TestRoundTripProto3(t *testing.T) { m := &pb.Message{ Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" ResultCount: 47, // (0 | 7<<3): 0x38 0x2f TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 Score: 8.1, // (5 | 9<<3): 0x4d <8.1> Key: []uint64{1, 0xdeadbeef}, Nested: &pb.Nested{ Bunny: "Monty", }, } t.Logf(" m: %v", m) b, err := proto.Marshal(m) if err != nil { t.Fatalf("proto.Marshal: %v", err) } t.Logf(" b: %q", b) m2 := new(pb.Message) if err := proto.Unmarshal(b, m2); err != nil { t.Fatalf("proto.Unmarshal: %v", err) } t.Logf("m2: %v", m2) if !proto.Equal(m, m2) { t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) } } func TestProto3SetDefaults(t *testing.T) { in := &pb.Message{ Terrain: map[string]*pb.Nested{ "meadow": new(pb.Nested), }, Proto2Field: new(tpb.SubDefaults), Proto2Value: map[string]*tpb.SubDefaults{ "badlands": new(tpb.SubDefaults), }, } got := proto.Clone(in).(*pb.Message) proto.SetDefaults(got) // There are no defaults in proto3. Everything should be the zero value, but // we need to remember to set defaults for nested proto2 messages. want := &pb.Message{ Terrain: map[string]*pb.Nested{ "meadow": new(pb.Nested), }, Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, Proto2Value: map[string]*tpb.SubDefaults{ "badlands": &tpb.SubDefaults{N: proto.Int64(7)}, }, } if !proto.Equal(got, want) { t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/size2_test.go ================================================ // 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. package proto import ( "testing" ) // This is a separate file and package from size_test.go because that one uses // generated messages and thus may not be in package proto without having a circular // dependency, whereas this file tests unexported details of size.go. func TestVarintSize(t *testing.T) { // Check the edge cases carefully. testCases := []struct { n uint64 size int }{ {0, 1}, {1, 1}, {127, 1}, {128, 2}, {16383, 2}, {16384, 3}, {1<<63 - 1, 9}, {1 << 63, 10}, } for _, tc := range testCases { size := sizeVarint(tc.n) if size != tc.size { t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) } } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/size_test.go ================================================ // 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. package proto_test import ( "log" "strings" "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)} // messageWithExtension2 is in equal_test.go. var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)} func init() { if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil { log.Panicf("SetExtension: %v", err) } if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil { log.Panicf("SetExtension: %v", err) } // Force messageWithExtension3 to have the extension encoded. Marshal(messageWithExtension3) } var SizeTests = []struct { desc string pb Message }{ {"empty", &pb.OtherMessage{}}, // Basic types. {"bool", &pb.Defaults{F_Bool: Bool(true)}}, {"int32", &pb.Defaults{F_Int32: Int32(12)}}, {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}}, {"small int64", &pb.Defaults{F_Int64: Int64(1)}}, {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}}, {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}}, {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}}, {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}}, {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}}, {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}}, {"float", &pb.Defaults{F_Float: Float32(12.6)}}, {"double", &pb.Defaults{F_Double: Float64(13.9)}}, {"string", &pb.Defaults{F_String: String("niles")}}, {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}}, {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}}, {"sint32", &pb.Defaults{F_Sint32: Int32(65)}}, {"sint64", &pb.Defaults{F_Sint64: Int64(67)}}, {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}}, // Repeated. {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}}, {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}}, {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}}, {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}}, {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}}, {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{ // Need enough large numbers to verify that the header is counting the number of bytes // for the field, not the number of elements. 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, }}}, {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}}, {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}}, // Nested. {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}}, {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}}, // Other things. {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}}, {"extension (unencoded)", messageWithExtension1}, {"extension (encoded)", messageWithExtension3}, // proto3 message {"proto3 empty", &proto3pb.Message{}}, {"proto3 bool", &proto3pb.Message{TrueScotsman: true}}, {"proto3 int64", &proto3pb.Message{ResultCount: 1}}, {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}}, {"proto3 float", &proto3pb.Message{Score: 12.6}}, {"proto3 string", &proto3pb.Message{Name: "Snezana"}}, {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}}, {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}}, {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}}, {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}}, {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}}, {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}}, {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}}, {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}}, {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}}, {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}}, {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}}, {"oneof not set", &pb.Oneof{}}, {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}}, {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}}, {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}}, {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}}, {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}}, {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}}, {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}}, {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}}, {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}}, {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}}, {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}}, {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}}, {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}}, {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}}, {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}}, {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}}, {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}}, {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}}, {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}}, {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}}, } func TestSize(t *testing.T) { for _, tc := range SizeTests { size := Size(tc.pb) b, err := Marshal(tc.pb) if err != nil { t.Errorf("%v: Marshal failed: %v", tc.desc, err) continue } if size != len(b) { t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b)) t.Logf("%v: bytes: %#v", tc.desc, b) } } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/testdata/Makefile ================================================ # 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. include ../../Make.protobuf all: regenerate regenerate: rm -f test.pb.go make test.pb.go # The following rules are just aids to development. Not needed for typical testing. diff: regenerate git diff test.pb.go restore: cp test.pb.go.golden test.pb.go preserve: cp test.pb.go test.pb.go.golden ================================================ FILE: vendor/github.com/golang/protobuf/proto/testdata/golden_test.go ================================================ // 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. // Verify that the compiler output for test.proto is unchanged. package testdata import ( "crypto/sha1" "fmt" "io/ioutil" "os" "os/exec" "path/filepath" "testing" ) // sum returns in string form (for easy comparison) the SHA-1 hash of the named file. func sum(t *testing.T, name string) string { data, err := ioutil.ReadFile(name) if err != nil { t.Fatal(err) } t.Logf("sum(%q): length is %d", name, len(data)) hash := sha1.New() _, err = hash.Write(data) if err != nil { t.Fatal(err) } return fmt.Sprintf("% x", hash.Sum(nil)) } func run(t *testing.T, name string, args ...string) { cmd := exec.Command(name, args...) cmd.Stdin = os.Stdin cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { t.Fatal(err) } } func TestGolden(t *testing.T) { // Compute the original checksum. goldenSum := sum(t, "test.pb.go") // Run the proto compiler. run(t, "protoc", "--go_out="+os.TempDir(), "test.proto") newFile := filepath.Join(os.TempDir(), "test.pb.go") defer os.Remove(newFile) // Compute the new checksum. newSum := sum(t, newFile) // Verify if newSum != goldenSum { run(t, "diff", "-u", "test.pb.go", newFile) t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/testdata/test.proto ================================================ // 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. // A feature-rich test file for the protocol compiler and libraries. syntax = "proto2"; package testdata; enum FOO { FOO1 = 1; }; message GoEnum { required FOO foo = 1; } message GoTestField { required string Label = 1; required string Type = 2; } message GoTest { // An enum, for completeness. enum KIND { VOID = 0; // Basic types BOOL = 1; BYTES = 2; FINGERPRINT = 3; FLOAT = 4; INT = 5; STRING = 6; TIME = 7; // Groupings TUPLE = 8; ARRAY = 9; MAP = 10; // Table types TABLE = 11; // Functions FUNCTION = 12; // last tag }; // Some typical parameters required KIND Kind = 1; optional string Table = 2; optional int32 Param = 3; // Required, repeated and optional foreign fields. required GoTestField RequiredField = 4; repeated GoTestField RepeatedField = 5; optional GoTestField OptionalField = 6; // Required fields of all basic types required bool F_Bool_required = 10; required int32 F_Int32_required = 11; required int64 F_Int64_required = 12; required fixed32 F_Fixed32_required = 13; required fixed64 F_Fixed64_required = 14; required uint32 F_Uint32_required = 15; required uint64 F_Uint64_required = 16; required float F_Float_required = 17; required double F_Double_required = 18; required string F_String_required = 19; required bytes F_Bytes_required = 101; required sint32 F_Sint32_required = 102; required sint64 F_Sint64_required = 103; // Repeated fields of all basic types repeated bool F_Bool_repeated = 20; repeated int32 F_Int32_repeated = 21; repeated int64 F_Int64_repeated = 22; repeated fixed32 F_Fixed32_repeated = 23; repeated fixed64 F_Fixed64_repeated = 24; repeated uint32 F_Uint32_repeated = 25; repeated uint64 F_Uint64_repeated = 26; repeated float F_Float_repeated = 27; repeated double F_Double_repeated = 28; repeated string F_String_repeated = 29; repeated bytes F_Bytes_repeated = 201; repeated sint32 F_Sint32_repeated = 202; repeated sint64 F_Sint64_repeated = 203; // Optional fields of all basic types optional bool F_Bool_optional = 30; optional int32 F_Int32_optional = 31; optional int64 F_Int64_optional = 32; optional fixed32 F_Fixed32_optional = 33; optional fixed64 F_Fixed64_optional = 34; optional uint32 F_Uint32_optional = 35; optional uint64 F_Uint64_optional = 36; optional float F_Float_optional = 37; optional double F_Double_optional = 38; optional string F_String_optional = 39; optional bytes F_Bytes_optional = 301; optional sint32 F_Sint32_optional = 302; optional sint64 F_Sint64_optional = 303; // Default-valued fields of all basic types optional bool F_Bool_defaulted = 40 [default=true]; optional int32 F_Int32_defaulted = 41 [default=32]; optional int64 F_Int64_defaulted = 42 [default=64]; optional fixed32 F_Fixed32_defaulted = 43 [default=320]; optional fixed64 F_Fixed64_defaulted = 44 [default=640]; optional uint32 F_Uint32_defaulted = 45 [default=3200]; optional uint64 F_Uint64_defaulted = 46 [default=6400]; optional float F_Float_defaulted = 47 [default=314159.]; optional double F_Double_defaulted = 48 [default=271828.]; optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"]; optional bytes F_Bytes_defaulted = 401 [default="Bignose"]; optional sint32 F_Sint32_defaulted = 402 [default = -32]; optional sint64 F_Sint64_defaulted = 403 [default = -64]; // Packed repeated fields (no string or bytes). repeated bool F_Bool_repeated_packed = 50 [packed=true]; repeated int32 F_Int32_repeated_packed = 51 [packed=true]; repeated int64 F_Int64_repeated_packed = 52 [packed=true]; repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true]; repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true]; repeated uint32 F_Uint32_repeated_packed = 55 [packed=true]; repeated uint64 F_Uint64_repeated_packed = 56 [packed=true]; repeated float F_Float_repeated_packed = 57 [packed=true]; repeated double F_Double_repeated_packed = 58 [packed=true]; repeated sint32 F_Sint32_repeated_packed = 502 [packed=true]; repeated sint64 F_Sint64_repeated_packed = 503 [packed=true]; // Required, repeated, and optional groups. required group RequiredGroup = 70 { required string RequiredField = 71; }; repeated group RepeatedGroup = 80 { required string RequiredField = 81; }; optional group OptionalGroup = 90 { required string RequiredField = 91; }; } // For testing skipping of unrecognized fields. // Numbers are all big, larger than tag numbers in GoTestField, // the message used in the corresponding test. message GoSkipTest { required int32 skip_int32 = 11; required fixed32 skip_fixed32 = 12; required fixed64 skip_fixed64 = 13; required string skip_string = 14; required group SkipGroup = 15 { required int32 group_int32 = 16; required string group_string = 17; } } // For testing packed/non-packed decoder switching. // A serialized instance of one should be deserializable as the other. message NonPackedTest { repeated int32 a = 1; } message PackedTest { repeated int32 b = 1 [packed=true]; } message MaxTag { // Maximum possible tag number. optional string last_field = 536870911; } message OldMessage { message Nested { optional string name = 1; } optional Nested nested = 1; optional int32 num = 2; } // NewMessage is wire compatible with OldMessage; // imagine it as a future version. message NewMessage { message Nested { optional string name = 1; optional string food_group = 2; } optional Nested nested = 1; // This is an int32 in OldMessage. optional int64 num = 2; } // Smaller tests for ASCII formatting. message InnerMessage { required string host = 1; optional int32 port = 2 [default=4000]; optional bool connected = 3; } message OtherMessage { optional int64 key = 1; optional bytes value = 2; optional float weight = 3; optional InnerMessage inner = 4; extensions 100 to max; } message MyMessage { required int32 count = 1; optional string name = 2; optional string quote = 3; repeated string pet = 4; optional InnerMessage inner = 5; repeated OtherMessage others = 6; repeated InnerMessage rep_inner = 12; enum Color { RED = 0; GREEN = 1; BLUE = 2; }; optional Color bikeshed = 7; optional group SomeGroup = 8 { optional int32 group_field = 9; } // This field becomes [][]byte in the generated code. repeated bytes rep_bytes = 10; optional double bigfloat = 11; extensions 100 to max; } message Ext { extend MyMessage { optional Ext more = 103; optional string text = 104; optional int32 number = 105; } optional string data = 1; } extend MyMessage { repeated string greeting = 106; } message ComplexExtension { optional int32 first = 1; optional int32 second = 2; repeated int32 third = 3; } extend OtherMessage { optional ComplexExtension complex = 200; repeated ComplexExtension r_complex = 201; } message DefaultsMessage { enum DefaultsEnum { ZERO = 0; ONE = 1; TWO = 2; }; extensions 100 to max; } extend DefaultsMessage { optional double no_default_double = 101; optional float no_default_float = 102; optional int32 no_default_int32 = 103; optional int64 no_default_int64 = 104; optional uint32 no_default_uint32 = 105; optional uint64 no_default_uint64 = 106; optional sint32 no_default_sint32 = 107; optional sint64 no_default_sint64 = 108; optional fixed32 no_default_fixed32 = 109; optional fixed64 no_default_fixed64 = 110; optional sfixed32 no_default_sfixed32 = 111; optional sfixed64 no_default_sfixed64 = 112; optional bool no_default_bool = 113; optional string no_default_string = 114; optional bytes no_default_bytes = 115; optional DefaultsMessage.DefaultsEnum no_default_enum = 116; optional double default_double = 201 [default = 3.1415]; optional float default_float = 202 [default = 3.14]; optional int32 default_int32 = 203 [default = 42]; optional int64 default_int64 = 204 [default = 43]; optional uint32 default_uint32 = 205 [default = 44]; optional uint64 default_uint64 = 206 [default = 45]; optional sint32 default_sint32 = 207 [default = 46]; optional sint64 default_sint64 = 208 [default = 47]; optional fixed32 default_fixed32 = 209 [default = 48]; optional fixed64 default_fixed64 = 210 [default = 49]; optional sfixed32 default_sfixed32 = 211 [default = 50]; optional sfixed64 default_sfixed64 = 212 [default = 51]; optional bool default_bool = 213 [default = true]; optional string default_string = 214 [default = "Hello, string"]; optional bytes default_bytes = 215 [default = "Hello, bytes"]; optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE]; } message MyMessageSet { option message_set_wire_format = true; extensions 100 to max; } message Empty { } extend MyMessageSet { optional Empty x201 = 201; optional Empty x202 = 202; optional Empty x203 = 203; optional Empty x204 = 204; optional Empty x205 = 205; optional Empty x206 = 206; optional Empty x207 = 207; optional Empty x208 = 208; optional Empty x209 = 209; optional Empty x210 = 210; optional Empty x211 = 211; optional Empty x212 = 212; optional Empty x213 = 213; optional Empty x214 = 214; optional Empty x215 = 215; optional Empty x216 = 216; optional Empty x217 = 217; optional Empty x218 = 218; optional Empty x219 = 219; optional Empty x220 = 220; optional Empty x221 = 221; optional Empty x222 = 222; optional Empty x223 = 223; optional Empty x224 = 224; optional Empty x225 = 225; optional Empty x226 = 226; optional Empty x227 = 227; optional Empty x228 = 228; optional Empty x229 = 229; optional Empty x230 = 230; optional Empty x231 = 231; optional Empty x232 = 232; optional Empty x233 = 233; optional Empty x234 = 234; optional Empty x235 = 235; optional Empty x236 = 236; optional Empty x237 = 237; optional Empty x238 = 238; optional Empty x239 = 239; optional Empty x240 = 240; optional Empty x241 = 241; optional Empty x242 = 242; optional Empty x243 = 243; optional Empty x244 = 244; optional Empty x245 = 245; optional Empty x246 = 246; optional Empty x247 = 247; optional Empty x248 = 248; optional Empty x249 = 249; optional Empty x250 = 250; } message MessageList { repeated group Message = 1 { required string name = 2; required int32 count = 3; } } message Strings { optional string string_field = 1; optional bytes bytes_field = 2; } message Defaults { enum Color { RED = 0; GREEN = 1; BLUE = 2; } // Default-valued fields of all basic types. // Same as GoTest, but copied here to make testing easier. optional bool F_Bool = 1 [default=true]; optional int32 F_Int32 = 2 [default=32]; optional int64 F_Int64 = 3 [default=64]; optional fixed32 F_Fixed32 = 4 [default=320]; optional fixed64 F_Fixed64 = 5 [default=640]; optional uint32 F_Uint32 = 6 [default=3200]; optional uint64 F_Uint64 = 7 [default=6400]; optional float F_Float = 8 [default=314159.]; optional double F_Double = 9 [default=271828.]; optional string F_String = 10 [default="hello, \"world!\"\n"]; optional bytes F_Bytes = 11 [default="Bignose"]; optional sint32 F_Sint32 = 12 [default=-32]; optional sint64 F_Sint64 = 13 [default=-64]; optional Color F_Enum = 14 [default=GREEN]; // More fields with crazy defaults. optional float F_Pinf = 15 [default=inf]; optional float F_Ninf = 16 [default=-inf]; optional float F_Nan = 17 [default=nan]; // Sub-message. optional SubDefaults sub = 18; // Redundant but explicit defaults. optional string str_zero = 19 [default=""]; } message SubDefaults { optional int64 n = 1 [default=7]; } message RepeatedEnum { enum Color { RED = 1; } repeated Color color = 1; } message MoreRepeated { repeated bool bools = 1; repeated bool bools_packed = 2 [packed=true]; repeated int32 ints = 3; repeated int32 ints_packed = 4 [packed=true]; repeated int64 int64s_packed = 7 [packed=true]; repeated string strings = 5; repeated fixed32 fixeds = 6; } // GroupOld and GroupNew have the same wire format. // GroupNew has a new field inside a group. message GroupOld { optional group G = 101 { optional int32 x = 2; } } message GroupNew { optional group G = 101 { optional int32 x = 2; optional int32 y = 3; } } message FloatingPoint { required double f = 1; } message MessageWithMap { map name_mapping = 1; map msg_mapping = 2; map byte_mapping = 3; map str_to_str = 4; } message Oneof { oneof union { bool F_Bool = 1; int32 F_Int32 = 2; int64 F_Int64 = 3; fixed32 F_Fixed32 = 4; fixed64 F_Fixed64 = 5; uint32 F_Uint32 = 6; uint64 F_Uint64 = 7; float F_Float = 8; double F_Double = 9; string F_String = 10; bytes F_Bytes = 11; sint32 F_Sint32 = 12; sint64 F_Sint64 = 13; MyMessage.Color F_Enum = 14; GoTestField F_Message = 15; group F_Group = 16 { optional int32 x = 17; } int32 F_Largest_Tag = 536870911; } oneof tormato { int32 value = 100; } } message Communique { optional bool make_me_cry = 1; // This is a oneof, called "union". oneof union { int32 number = 5; string name = 6; bytes data = 7; double temp_c = 8; MyMessage.Color col = 9; Strings msg = 10; } } ================================================ FILE: vendor/github.com/golang/protobuf/proto/text.go ================================================ // 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.Printf("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 writeStruct(w *textWriter, sv reflect.Value) error { 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("\n")); err != nil { return err } continue } if err := 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 := 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 := 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 := 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 pv.Type().Implements(extendableProtoType) { if err := 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 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.Interface().([]byte))); 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 tm, ok := v.Interface().(encoding.TextMarshaler); ok { text, err := tm.MarshalText() if err != nil { return err } if _, err = w.Write(text); err != nil { return err } } else if err := 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 writeExtensions(w *textWriter, pv reflect.Value) error { emap := extensionMaps[pv.Type().Elem()] ep := pv.Interface().(extendableProto) // Order the extensions by ID. // This isn't strictly necessary, but it will give us // canonical output, which will also make testing easier. m := ep.ExtensionMap() ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) 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 := writeExtension(w, desc.Name, pb); err != nil { return err } } else { v := reflect.ValueOf(pb) for i := 0; i < v.Len(); i++ { if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { return err } } } } return nil } func 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 := 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 } func marshalText(w io.Writer, pb Message, compact bool) error { val := reflect.ValueOf(pb) if pb == nil || val.IsNil() { w.Write([]byte("")) 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: compact, } if tm, ok := pb.(encoding.TextMarshaler); ok { text, err := tm.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 := writeStruct(aw, v); err != nil { return err } if bw != nil { return bw.Flush() } return nil } // 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 marshalText(w, pb, false) } // MarshalTextString is the same as MarshalText, but returns the string directly. func MarshalTextString(pb Message) string { var buf bytes.Buffer marshalText(&buf, pb, false) return buf.String() } // CompactText writes a given protocol buffer in compact text format (one line). func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) } // CompactTextString is the same as CompactText, but returns the string directly. func CompactTextString(pb Message) string { var buf bytes.Buffer marshalText(&buf, pb, true) return buf.String() } ================================================ FILE: vendor/github.com/golang/protobuf/proto/text_parser.go ================================================ // 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" ) 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.", 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]". for { tok := p.next() if tok.err != nil { return tok.err } if tok.value == terminator { break } if tok.value == "[" { // Looks like an extension. // // TODO: Check whether we need to handle // namespace rooted names (e.g. ".something.Foo"). tok = p.next() if tok.err != nil { return tok.err } 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 == tok.value { desc = d break } } if desc == nil { return p.errorf("unrecognized extension %q", tok.value) } // Check the extension terminator. tok = p.next() if tok.err != nil { return tok.err } if tok.value != "]" { return p.errorf("unrecognized extension terminator %q", tok.value) } 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().(extendableProto) 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) sv.Field(oop.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 > // Technically the "key" and "value" could come in any order, // but in practice they won't. tok := p.next() var terminator string switch tok.value { case "<": terminator = ">" case "{": terminator = "}" default: return p.errorf("expected '{' or '<', found %q", tok.value) } if err := p.consumeToken("key"); err != nil { return err } 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 } if err := p.consumeToken("value"); err != nil { return err } 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 } if err := p.consumeToken(terminator); err != nil { return err } 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 } else if props.Required { reqCount-- } if err := p.consumeOptionalSeparator(); err != nil { return err } } if reqCount > 0 { return p.missingRequiredFieldError(sv) } return reqFieldErr } // 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: // Either "true", "false", 1 or 0. switch tok.value { case "true", "1": fv.SetBool(true) return nil case "false", "0": 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 } ================================================ FILE: vendor/github.com/golang/protobuf/proto/text_parser_test.go ================================================ // 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_test import ( "math" "reflect" "testing" . "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" . "github.com/golang/protobuf/proto/testdata" ) type UnmarshalTextTest struct { in string err string // if "", no error expected out *MyMessage } func buildExtStructTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_More, &Ext{ Data: String("Hello, world!"), }) return UnmarshalTextTest{in: text, out: msg} } func buildExtDataTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } SetExtension(msg, E_Ext_Text, String("Hello, world!")) SetExtension(msg, E_Ext_Number, Int32(1729)) return UnmarshalTextTest{in: text, out: msg} } func buildExtRepStringTest(text string) UnmarshalTextTest { msg := &MyMessage{ Count: Int32(42), } if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil { panic(err) } return UnmarshalTextTest{in: text, out: msg} } var unMarshalTextTests = []UnmarshalTextTest{ // Basic { in: " count:42\n name:\"Dave\" ", out: &MyMessage{ Count: Int32(42), Name: String("Dave"), }, }, // Empty quoted string { in: `count:42 name:""`, out: &MyMessage{ Count: Int32(42), Name: String(""), }, }, // Quoted string concatenation with double quotes { in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`, out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string concatenation with single quotes { in: "count:42 name: 'My name is '\n'elsewhere'", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string concatenations with mixed quotes { in: "count:42 name: 'My name is '\n\"elsewhere\"", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, { in: "count:42 name: \"My name is \"\n'elsewhere'", out: &MyMessage{ Count: Int32(42), Name: String("My name is elsewhere"), }, }, // Quoted string with escaped apostrophe { in: `count:42 name: "HOLIDAY - New Year\'s Day"`, out: &MyMessage{ Count: Int32(42), Name: String("HOLIDAY - New Year's Day"), }, }, // Quoted string with single quote { in: `count:42 name: 'Roger "The Ramster" Ramjet'`, out: &MyMessage{ Count: Int32(42), Name: String(`Roger "The Ramster" Ramjet`), }, }, // Quoted string with all the accepted special characters from the C++ test { in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"", out: &MyMessage{ Count: Int32(42), Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"), }, }, // Quoted string with quoted backslash { in: `count:42 name: "\\'xyz"`, out: &MyMessage{ Count: Int32(42), Name: String(`\'xyz`), }, }, // Quoted string with UTF-8 bytes. { in: "count:42 name: '\303\277\302\201\xAB'", out: &MyMessage{ Count: Int32(42), Name: String("\303\277\302\201\xAB"), }, }, // Bad quoted string { in: `inner: < host: "\0" >` + "\n", err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`, }, // Number too large for int64 { in: "count: 1 others { key: 123456789012345678901 }", err: "line 1.23: invalid int64: 123456789012345678901", }, // Number too large for int32 { in: "count: 1234567890123", err: "line 1.7: invalid int32: 1234567890123", }, // Number in hexadecimal { in: "count: 0x2beef", out: &MyMessage{ Count: Int32(0x2beef), }, }, // Number in octal { in: "count: 024601", out: &MyMessage{ Count: Int32(024601), }, }, // Floating point number with "f" suffix { in: "count: 4 others:< weight: 17.0f >", out: &MyMessage{ Count: Int32(4), Others: []*OtherMessage{ { Weight: Float32(17), }, }, }, }, // Floating point positive infinity { in: "count: 4 bigfloat: inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(1)), }, }, // Floating point negative infinity { in: "count: 4 bigfloat: -inf", out: &MyMessage{ Count: Int32(4), Bigfloat: Float64(math.Inf(-1)), }, }, // Number too large for float32 { in: "others:< weight: 12345678901234567890123456789012345678901234567890 >", err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890", }, // Number posing as a quoted string { in: `inner: < host: 12 >` + "\n", err: `line 1.15: invalid string: 12`, }, // Quoted string posing as int32 { in: `count: "12"`, err: `line 1.7: invalid int32: "12"`, }, // Quoted string posing a float32 { in: `others:< weight: "17.4" >`, err: `line 1.17: invalid float32: "17.4"`, }, // Enum { in: `count:42 bikeshed: BLUE`, out: &MyMessage{ Count: Int32(42), Bikeshed: MyMessage_BLUE.Enum(), }, }, // Repeated field { in: `count:42 pet: "horsey" pet:"bunny"`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated field with list notation { in: `count:42 pet: ["horsey", "bunny"]`, out: &MyMessage{ Count: Int32(42), Pet: []string{"horsey", "bunny"}, }, }, // Repeated message with/without colon and <>/{} { in: `count:42 others:{} others{} others:<> others:{}`, out: &MyMessage{ Count: Int32(42), Others: []*OtherMessage{ {}, {}, {}, {}, }, }, }, // Missing colon for inner message { in: `count:42 inner < host: "cauchy.syd" >`, out: &MyMessage{ Count: Int32(42), Inner: &InnerMessage{ Host: String("cauchy.syd"), }, }, }, // Missing colon for string field { in: `name "Dave"`, err: `line 1.5: expected ':', found "\"Dave\""`, }, // Missing colon for int32 field { in: `count 42`, err: `line 1.6: expected ':', found "42"`, }, // Missing required field { in: `name: "Pawel"`, err: `proto: required field "testdata.MyMessage.count" not set`, out: &MyMessage{ Name: String("Pawel"), }, }, // Repeated non-repeated field { in: `name: "Rob" name: "Russ"`, err: `line 1.12: non-repeated field "name" was repeated`, }, // Group { in: `count: 17 SomeGroup { group_field: 12 }`, out: &MyMessage{ Count: Int32(17), Somegroup: &MyMessage_SomeGroup{ GroupField: Int32(12), }, }, }, // Semicolon between fields { in: `count:3;name:"Calvin"`, out: &MyMessage{ Count: Int32(3), Name: String("Calvin"), }, }, // Comma between fields { in: `count:4,name:"Ezekiel"`, out: &MyMessage{ Count: Int32(4), Name: String("Ezekiel"), }, }, // Extension buildExtStructTest(`count: 42 [testdata.Ext.more]:`), buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`), buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`), buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`), // Big all-in-one { in: "count:42 # Meaning\n" + `name:"Dave" ` + `quote:"\"I didn't want to go.\"" ` + `pet:"bunny" ` + `pet:"kitty" ` + `pet:"horsey" ` + `inner:<` + ` host:"footrest.syd" ` + ` port:7001 ` + ` connected:true ` + `> ` + `others:<` + ` key:3735928559 ` + ` value:"\x01A\a\f" ` + `> ` + `others:<` + " weight:58.9 # Atomic weight of Co\n" + ` inner:<` + ` host:"lesha.mtv" ` + ` port:8002 ` + ` >` + `>`, out: &MyMessage{ Count: Int32(42), Name: String("Dave"), Quote: String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &InnerMessage{ Host: String("footrest.syd"), Port: Int32(7001), Connected: Bool(true), }, Others: []*OtherMessage{ { Key: Int64(3735928559), Value: []byte{0x1, 'A', '\a', '\f'}, }, { Weight: Float32(58.9), Inner: &InnerMessage{ Host: String("lesha.mtv"), Port: Int32(8002), }, }, }, }, }, } func TestUnmarshalText(t *testing.T) { for i, test := range unMarshalTextTests { pb := new(MyMessage) err := UnmarshalText(test.in, pb) if test.err == "" { // We don't expect failure. if err != nil { t.Errorf("Test %d: Unexpected error: %v", i, err) } else if !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } else { // We do expect failure. if err == nil { t.Errorf("Test %d: Didn't get expected error: %v", i, test.err) } else if err.Error() != test.err { t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v", i, err.Error(), test.err) } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) { t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v", i, pb, test.out) } } } } func TestUnmarshalTextCustomMessage(t *testing.T) { msg := &textMessage{} if err := UnmarshalText("custom", msg); err != nil { t.Errorf("Unexpected error from custom unmarshal: %v", err) } if UnmarshalText("not custom", msg) == nil { t.Errorf("Didn't get expected error from custom unmarshal") } } // Regression test; this caused a panic. func TestRepeatedEnum(t *testing.T) { pb := new(RepeatedEnum) if err := UnmarshalText("color: RED", pb); err != nil { t.Fatal(err) } exp := &RepeatedEnum{ Color: []RepeatedEnum_Color{RepeatedEnum_RED}, } if !Equal(pb, exp) { t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp) } } func TestProto3TextParsing(t *testing.T) { m := new(proto3pb.Message) const in = `name: "Wallace" true_scotsman: true` want := &proto3pb.Message{ Name: "Wallace", TrueScotsman: true, } if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } func TestMapParsing(t *testing.T) { m := new(MessageWithMap) const in = `name_mapping: name_mapping:` + `msg_mapping:,>` + // separating commas are okay `msg_mapping>` + // no colon after "value" `byte_mapping:` want := &MessageWithMap{ NameMapping: map[int32]string{ 1: "Beatles", 1234: "Feist", }, MsgMapping: map[int64]*FloatingPoint{ -4: {F: Float64(2.0)}, -2: {F: Float64(4.0)}, }, ByteMapping: map[bool][]byte{ true: []byte("so be it"), }, } if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } func TestOneofParsing(t *testing.T) { const in = `name:"Shrek"` m := new(Communique) want := &Communique{Union: &Communique_Name{"Shrek"}} if err := UnmarshalText(in, m); err != nil { t.Fatal(err) } if !Equal(m, want) { t.Errorf("\n got %v\nwant %v", m, want) } } var benchInput string func init() { benchInput = "count: 4\n" for i := 0; i < 1000; i++ { benchInput += "pet: \"fido\"\n" } // Check it is valid input. pb := new(MyMessage) err := UnmarshalText(benchInput, pb) if err != nil { panic("Bad benchmark input: " + err.Error()) } } func BenchmarkUnmarshalText(b *testing.B) { pb := new(MyMessage) for i := 0; i < b.N; i++ { UnmarshalText(benchInput, pb) } b.SetBytes(int64(len(benchInput))) } ================================================ FILE: vendor/github.com/golang/protobuf/proto/text_test.go ================================================ // 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_test import ( "bytes" "errors" "io/ioutil" "math" "strings" "testing" "github.com/golang/protobuf/proto" proto3pb "github.com/golang/protobuf/proto/proto3_proto" pb "github.com/golang/protobuf/proto/testdata" ) // textMessage implements the methods that allow it to marshal and unmarshal // itself as text. type textMessage struct { } func (*textMessage) MarshalText() ([]byte, error) { return []byte("custom"), nil } func (*textMessage) UnmarshalText(bytes []byte) error { if string(bytes) != "custom" { return errors.New("expected 'custom'") } return nil } func (*textMessage) Reset() {} func (*textMessage) String() string { return "" } func (*textMessage) ProtoMessage() {} func newTestMessage() *pb.MyMessage { msg := &pb.MyMessage{ Count: proto.Int32(42), Name: proto.String("Dave"), Quote: proto.String(`"I didn't want to go."`), Pet: []string{"bunny", "kitty", "horsey"}, Inner: &pb.InnerMessage{ Host: proto.String("footrest.syd"), Port: proto.Int32(7001), Connected: proto.Bool(true), }, Others: []*pb.OtherMessage{ { Key: proto.Int64(0xdeadbeef), Value: []byte{1, 65, 7, 12}, }, { Weight: proto.Float32(6.022), Inner: &pb.InnerMessage{ Host: proto.String("lesha.mtv"), Port: proto.Int32(8002), }, }, }, Bikeshed: pb.MyMessage_BLUE.Enum(), Somegroup: &pb.MyMessage_SomeGroup{ GroupField: proto.Int32(8), }, // One normally wouldn't do this. // This is an undeclared tag 13, as a varint (wire type 0) with value 4. XXX_unrecognized: []byte{13<<3 | 0, 4}, } ext := &pb.Ext{ Data: proto.String("Big gobs for big rats"), } if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil { panic(err) } greetings := []string{"adg", "easy", "cow"} if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil { panic(err) } // Add an unknown extension. We marshal a pb.Ext, and fake the ID. b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")}) if err != nil { panic(err) } b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...) proto.SetRawExtension(msg, 201, b) // Extensions can be plain fields, too, so let's test that. b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19) proto.SetRawExtension(msg, 202, b) return msg } const text = `count: 42 name: "Dave" quote: "\"I didn't want to go.\"" pet: "bunny" pet: "kitty" pet: "horsey" inner: < host: "footrest.syd" port: 7001 connected: true > others: < key: 3735928559 value: "\001A\007\014" > others: < weight: 6.022 inner: < host: "lesha.mtv" port: 8002 > > bikeshed: BLUE SomeGroup { group_field: 8 } /* 2 unknown bytes */ 13: 4 [testdata.Ext.more]: < data: "Big gobs for big rats" > [testdata.greeting]: "adg" [testdata.greeting]: "easy" [testdata.greeting]: "cow" /* 13 unknown bytes */ 201: "\t3G skiing" /* 3 unknown bytes */ 202: 19 ` func TestMarshalText(t *testing.T) { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, newTestMessage()); err != nil { t.Fatalf("proto.MarshalText: %v", err) } s := buf.String() if s != text { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text) } } func TestMarshalTextCustomMessage(t *testing.T) { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, &textMessage{}); err != nil { t.Fatalf("proto.MarshalText: %v", err) } s := buf.String() if s != "custom" { t.Errorf("Got %q, expected %q", s, "custom") } } func TestMarshalTextNil(t *testing.T) { want := "" tests := []proto.Message{nil, (*pb.MyMessage)(nil)} for i, test := range tests { buf := new(bytes.Buffer) if err := proto.MarshalText(buf, test); err != nil { t.Fatal(err) } if got := buf.String(); got != want { t.Errorf("%d: got %q want %q", i, got, want) } } } func TestMarshalTextUnknownEnum(t *testing.T) { // The Color enum only specifies values 0-2. m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()} got := m.String() const want = `bikeshed:3 ` if got != want { t.Errorf("\n got %q\nwant %q", got, want) } } func TestTextOneof(t *testing.T) { tests := []struct { m proto.Message want string }{ // zero message {&pb.Communique{}, ``}, // scalar field {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`}, // message field {&pb.Communique{Union: &pb.Communique_Msg{ &pb.Strings{StringField: proto.String("why hello!")}, }}, `msg:`}, // bad oneof (should not panic) {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`}, } for _, test := range tests { got := strings.TrimSpace(test.m.String()) if got != test.want { t.Errorf("\n got %s\nwant %s", got, test.want) } } } func BenchmarkMarshalTextBuffered(b *testing.B) { buf := new(bytes.Buffer) m := newTestMessage() for i := 0; i < b.N; i++ { buf.Reset() proto.MarshalText(buf, m) } } func BenchmarkMarshalTextUnbuffered(b *testing.B) { w := ioutil.Discard m := newTestMessage() for i := 0; i < b.N; i++ { proto.MarshalText(w, m) } } func compact(src string) string { // s/[ \n]+/ /g; s/ $//; dst := make([]byte, len(src)) space, comment := false, false j := 0 for i := 0; i < len(src); i++ { if strings.HasPrefix(src[i:], "/*") { comment = true i++ continue } if comment && strings.HasPrefix(src[i:], "*/") { comment = false i++ continue } if comment { continue } c := src[i] if c == ' ' || c == '\n' { space = true continue } if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') { space = false } if c == '{' { space = false } if space { dst[j] = ' ' j++ space = false } dst[j] = c j++ } if space { dst[j] = ' ' j++ } return string(dst[0:j]) } var compactText = compact(text) func TestCompactText(t *testing.T) { s := proto.CompactTextString(newTestMessage()) if s != compactText { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText) } } func TestStringEscaping(t *testing.T) { testCases := []struct { in *pb.Strings out string }{ { // Test data from C++ test (TextFormatTest.StringEscape). // Single divergence: we don't escape apostrophes. &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")}, "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n", }, { // Test data from the same C++ test. &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")}, "string_field: \"\\350\\260\\267\\346\\255\\214\"\n", }, { // Some UTF-8. &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")}, `string_field: "\000\001\377\201"` + "\n", }, } for i, tc := range testCases { var buf bytes.Buffer if err := proto.MarshalText(&buf, tc.in); err != nil { t.Errorf("proto.MarsalText: %v", err) continue } s := buf.String() if s != tc.out { t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out) continue } // Check round-trip. pb := new(pb.Strings) if err := proto.UnmarshalText(s, pb); err != nil { t.Errorf("#%d: UnmarshalText: %v", i, err) continue } if !proto.Equal(pb, tc.in) { t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb) } } } // A limitedWriter accepts some output before it fails. // This is a proxy for something like a nearly-full or imminently-failing disk, // or a network connection that is about to die. type limitedWriter struct { b bytes.Buffer limit int } var outOfSpace = errors.New("proto: insufficient space") func (w *limitedWriter) Write(p []byte) (n int, err error) { var avail = w.limit - w.b.Len() if avail <= 0 { return 0, outOfSpace } if len(p) <= avail { return w.b.Write(p) } n, _ = w.b.Write(p[:avail]) return n, outOfSpace } func TestMarshalTextFailing(t *testing.T) { // Try lots of different sizes to exercise more error code-paths. for lim := 0; lim < len(text); lim++ { buf := new(limitedWriter) buf.limit = lim err := proto.MarshalText(buf, newTestMessage()) // We expect a certain error, but also some partial results in the buffer. if err != outOfSpace { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace) } s := buf.b.String() x := text[:buf.limit] if s != x { t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x) } } } func TestFloats(t *testing.T) { tests := []struct { f float64 want string }{ {0, "0"}, {4.7, "4.7"}, {math.Inf(1), "inf"}, {math.Inf(-1), "-inf"}, {math.NaN(), "nan"}, } for _, test := range tests { msg := &pb.FloatingPoint{F: &test.f} got := strings.TrimSpace(msg.String()) want := `f:` + test.want if got != want { t.Errorf("f=%f: got %q, want %q", test.f, got, want) } } } func TestRepeatedNilText(t *testing.T) { m := &pb.MessageList{ Message: []*pb.MessageList_Message{ nil, &pb.MessageList_Message{ Name: proto.String("Horse"), }, nil, }, } want := `Message Message { name: "Horse" } Message ` if s := proto.MarshalTextString(m); s != want { t.Errorf(" got: %s\nwant: %s", s, want) } } func TestProto3Text(t *testing.T) { tests := []struct { m proto.Message want string }{ // zero message {&proto3pb.Message{}, ``}, // zero message except for an empty byte slice {&proto3pb.Message{Data: []byte{}}, ``}, // trivial case {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`}, // empty map {&pb.MessageWithMap{}, ``}, // non-empty map; map format is the same as a repeated struct, // and they are sorted by key (numerically for numeric keys). { &pb.MessageWithMap{NameMapping: map[int32]string{ -1: "Negatory", 7: "Lucky", 1234: "Feist", 6345789: "Otis", }}, `name_mapping: ` + `name_mapping: ` + `name_mapping: ` + `name_mapping:`, }, // map with nil value; not well-defined, but we shouldn't crash { &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}}, `msg_mapping:`, }, } for _, test := range tests { got := strings.TrimSpace(test.m.String()) if got != test.want { t.Errorf("\n got %s\nwant %s", got, test.want) } } } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/Makefile ================================================ # 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. test: cd testdata && make test ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile ================================================ # 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. # Not stored here, but descriptor.proto is in https://github.com/google/protobuf/ # at src/google/protobuf/descriptor.proto regenerate: echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION protoc --go_out=. -I$(HOME)/src/protobuf/src $(HOME)/src/protobuf/src/google/protobuf/descriptor.proto && \ sed 's,^package google_protobuf,package descriptor,' google/protobuf/descriptor.pb.go > \ $(GOPATH)/src/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go && \ rm -f google/protobuf/descriptor.pb.go ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/doc.go ================================================ // 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. /* A plugin for the Google protocol buffer compiler to generate Go code. Run it by building this program and putting it in your path with the name protoc-gen-go That word 'go' at the end becomes part of the option string set for the protocol compiler, so once the protocol compiler (protoc) is installed you can run protoc --go_out=output_directory input_directory/file.proto to generate Go bindings for the protocol defined by file.proto. With that input, the output will be written to output_directory/file.pb.go The generated code is documented in the package comment for the library. See the README and documentation for protocol buffers to learn more: https://developers.google.com/protocol-buffers/ */ package documentation ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/generator/Makefile ================================================ # 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. include $(GOROOT)/src/Make.inc TARG=github.com/golang/protobuf/compiler/generator GOFILES=\ generator.go\ DEPS=../descriptor ../plugin ../../proto include $(GOROOT)/src/Make.pkg ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go ================================================ // 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. /* The code generator for the plugin for the Google protocol buffer compiler. It generates Go code from the protocol buffer description files read by the main routine. */ package generator import ( "bufio" "bytes" "compress/gzip" "fmt" "go/parser" "go/printer" "go/token" "log" "os" "path" "strconv" "strings" "unicode" "unicode/utf8" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/descriptor" plugin "github.com/golang/protobuf/protoc-gen-go/plugin" ) // generatedCodeVersion indicates a version of the generated code. // It is incremented whenever an incompatibility between the generated code and // proto package is introduced; the generated code references // a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion). const generatedCodeVersion = 1 // A Plugin provides functionality to add to the output during Go code generation, // such as to produce RPC stubs. type Plugin interface { // Name identifies the plugin. Name() string // Init is called once after data structures are built but before // code generation begins. Init(g *Generator) // Generate produces the code generated by the plugin for this file, // except for the imports, by calling the generator's methods P, In, and Out. Generate(file *FileDescriptor) // GenerateImports produces the import declarations for this file. // It is called after Generate. GenerateImports(file *FileDescriptor) } var plugins []Plugin // RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated. // It is typically called during initialization. func RegisterPlugin(p Plugin) { plugins = append(plugins, p) } // Each type we import as a protocol buffer (other than FileDescriptorProto) needs // a pointer to the FileDescriptorProto that represents it. These types achieve that // wrapping by placing each Proto inside a struct with the pointer to its File. The // structs have the same names as their contents, with "Proto" removed. // FileDescriptor is used to store the things that it points to. // The file and package name method are common to messages and enums. type common struct { file *descriptor.FileDescriptorProto // File this object comes from. } // PackageName is name in the package clause in the generated file. func (c *common) PackageName() string { return uniquePackageOf(c.file) } func (c *common) File() *descriptor.FileDescriptorProto { return c.file } func fileIsProto3(file *descriptor.FileDescriptorProto) bool { return file.GetSyntax() == "proto3" } func (c *common) proto3() bool { return fileIsProto3(c.file) } // Descriptor represents a protocol buffer message. type Descriptor struct { common *descriptor.DescriptorProto parent *Descriptor // The containing message, if any. nested []*Descriptor // Inner messages, if any. enums []*EnumDescriptor // Inner enums, if any. ext []*ExtensionDescriptor // Extensions, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or another message. path string // The SourceCodeInfo path as comma-separated integers. group bool } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (d *Descriptor) TypeName() []string { if d.typename != nil { return d.typename } n := 0 for parent := d; parent != nil; parent = parent.parent { n++ } s := make([]string, n, n) for parent := d; parent != nil; parent = parent.parent { n-- s[n] = parent.GetName() } d.typename = s return s } // EnumDescriptor describes an enum. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type EnumDescriptor struct { common *descriptor.EnumDescriptorProto parent *Descriptor // The containing message, if any. typename []string // Cached typename vector. index int // The index into the container, whether the file or a message. path string // The SourceCodeInfo path as comma-separated integers. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *EnumDescriptor) TypeName() (s []string) { if e.typename != nil { return e.typename } name := e.GetName() if e.parent == nil { s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name e.typename = s return s } // Everything but the last element of the full type name, CamelCased. // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... . func (e *EnumDescriptor) prefix() string { if e.parent == nil { // If the enum is not part of a message, the prefix is just the type name. return CamelCase(*e.Name) + "_" } typeName := e.TypeName() return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_" } // The integer value of the named constant in this enumerated type. func (e *EnumDescriptor) integerValueAsString(name string) string { for _, c := range e.Value { if c.GetName() == name { return fmt.Sprint(c.GetNumber()) } } log.Fatal("cannot find value for enum constant") return "" } // ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil. // Otherwise it will be the descriptor of the message in which it is defined. type ExtensionDescriptor struct { common *descriptor.FieldDescriptorProto parent *Descriptor // The containing message, if any. } // TypeName returns the elements of the dotted type name. // The package name is not part of this name. func (e *ExtensionDescriptor) TypeName() (s []string) { name := e.GetName() if e.parent == nil { // top-level extension s = make([]string, 1) } else { pname := e.parent.TypeName() s = make([]string, len(pname)+1) copy(s, pname) } s[len(s)-1] = name return s } // DescName returns the variable name used for the generated descriptor. func (e *ExtensionDescriptor) DescName() string { // The full type name. typeName := e.TypeName() // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix. for i, s := range typeName { typeName[i] = CamelCase(s) } return "E_" + strings.Join(typeName, "_") } // ImportedDescriptor describes a type that has been publicly imported from another file. type ImportedDescriptor struct { common o Object } func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() } // FileDescriptor describes an protocol buffer descriptor file (.proto). // It includes slices of all the messages and enums defined within it. // Those slices are constructed by WrapTypes. type FileDescriptor struct { *descriptor.FileDescriptorProto desc []*Descriptor // All the messages defined in this file. enum []*EnumDescriptor // All the enums defined in this file. ext []*ExtensionDescriptor // All the top-level extensions defined in this file. imp []*ImportedDescriptor // All types defined in files publicly imported by this file. // Comments, stored as a map of path (comma-separated integers) to the comment. comments map[string]*descriptor.SourceCodeInfo_Location // The full list of symbols that are exported, // as a map from the exported object to its symbols. // This is used for supporting public imports. exported map[Object][]symbol index int // The index of this file in the list of files to generate code for proto3 bool // whether to generate proto3 code for this file } // PackageName is the package name we'll use in the generated code to refer to this file. func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) } // goPackageName returns the Go package name to use in the // generated Go file. The result explicit reports whether the name // came from an option go_package statement. If explicit is false, // the name was derived from the protocol buffer's package statement // or the input file name. func (d *FileDescriptor) goPackageName() (name string, explicit bool) { // Does the file have a "go_package" option? if opts := d.Options; opts != nil { if pkg := opts.GetGoPackage(); pkg != "" { return pkg, true } } // Does the file have a package clause? if pkg := d.GetPackage(); pkg != "" { return pkg, false } // Use the file base name. return baseName(d.GetName()), false } func (d *FileDescriptor) addExport(obj Object, sym symbol) { d.exported[obj] = append(d.exported[obj], sym) } // symbol is an interface representing an exported Go symbol. type symbol interface { // GenerateAlias should generate an appropriate alias // for the symbol from the named package. GenerateAlias(g *Generator, pkg string) } type messageSymbol struct { sym string hasExtensions, isMessageSet bool hasOneof bool getters []getterSymbol } type getterSymbol struct { name string typ string typeName string // canonical name in proto world; empty for proto.Message and similar genType bool // whether typ contains a generated type (message/group/enum) } func (ms *messageSymbol) GenerateAlias(g *Generator, pkg string) { remoteSym := pkg + "." + ms.sym g.P("type ", ms.sym, " ", remoteSym) g.P("func (m *", ms.sym, ") Reset() { (*", remoteSym, ")(m).Reset() }") g.P("func (m *", ms.sym, ") String() string { return (*", remoteSym, ")(m).String() }") g.P("func (*", ms.sym, ") ProtoMessage() {}") if ms.hasExtensions { g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange ", "{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }") g.P("func (m *", ms.sym, ") ExtensionMap() map[int32]", g.Pkg["proto"], ".Extension ", "{ return (*", remoteSym, ")(m).ExtensionMap() }") if ms.isMessageSet { g.P("func (m *", ms.sym, ") Marshal() ([]byte, error) ", "{ return (*", remoteSym, ")(m).Marshal() }") g.P("func (m *", ms.sym, ") Unmarshal(buf []byte) error ", "{ return (*", remoteSym, ")(m).Unmarshal(buf) }") } } if ms.hasOneof { // Oneofs and public imports do not mix well. // We can make them work okay for the binary format, // but they're going to break weirdly for text/JSON. enc := "_" + ms.sym + "_OneofMarshaler" dec := "_" + ms.sym + "_OneofUnmarshaler" size := "_" + ms.sym + "_OneofSizer" encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" sizeSig := "(msg " + g.Pkg["proto"] + ".Message) int" g.P("func (m *", ms.sym, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") g.P("return ", enc, ", ", dec, ", ", size, ", nil") g.P("}") g.P("func ", enc, encSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("enc, _, _, _ := m0.XXX_OneofFuncs()") g.P("return enc(m0, b)") g.P("}") g.P("func ", dec, decSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("_, dec, _, _ := m0.XXX_OneofFuncs()") g.P("return dec(m0, tag, wire, b)") g.P("}") g.P("func ", size, sizeSig, " {") g.P("m := msg.(*", ms.sym, ")") g.P("m0 := (*", remoteSym, ")(m)") g.P("_, _, size, _ := m0.XXX_OneofFuncs()") g.P("return size(m0)") g.P("}") } for _, get := range ms.getters { if get.typeName != "" { g.RecordTypeUse(get.typeName) } typ := get.typ val := "(*" + remoteSym + ")(m)." + get.name + "()" if get.genType { // typ will be "*pkg.T" (message/group) or "pkg.T" (enum) // or "map[t]*pkg.T" (map to message/enum). // The first two of those might have a "[]" prefix if it is repeated. // Drop any package qualifier since we have hoisted the type into this package. rep := strings.HasPrefix(typ, "[]") if rep { typ = typ[2:] } isMap := strings.HasPrefix(typ, "map[") star := typ[0] == '*' if !isMap { // map types handled lower down typ = typ[strings.Index(typ, ".")+1:] } if star { typ = "*" + typ } if rep { // Go does not permit conversion between slice types where both // element types are named. That means we need to generate a bit // of code in this situation. // typ is the element type. // val is the expression to get the slice from the imported type. ctyp := typ // conversion type expression; "Foo" or "(*Foo)" if star { ctyp = "(" + typ + ")" } g.P("func (m *", ms.sym, ") ", get.name, "() []", typ, " {") g.In() g.P("o := ", val) g.P("if o == nil {") g.In() g.P("return nil") g.Out() g.P("}") g.P("s := make([]", typ, ", len(o))") g.P("for i, x := range o {") g.In() g.P("s[i] = ", ctyp, "(x)") g.Out() g.P("}") g.P("return s") g.Out() g.P("}") continue } if isMap { // Split map[keyTyp]valTyp. bra, ket := strings.Index(typ, "["), strings.Index(typ, "]") keyTyp, valTyp := typ[bra+1:ket], typ[ket+1:] // Drop any package qualifier. // Only the value type may be foreign. star := valTyp[0] == '*' valTyp = valTyp[strings.Index(valTyp, ".")+1:] if star { valTyp = "*" + valTyp } typ := "map[" + keyTyp + "]" + valTyp g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " {") g.P("o := ", val) g.P("if o == nil { return nil }") g.P("s := make(", typ, ", len(o))") g.P("for k, v := range o {") g.P("s[k] = (", valTyp, ")(v)") g.P("}") g.P("return s") g.P("}") continue } // Convert imported type into the forwarding type. val = "(" + typ + ")(" + val + ")" } g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " { return ", val, " }") } } type enumSymbol struct { name string proto3 bool // Whether this came from a proto3 file. } func (es enumSymbol) GenerateAlias(g *Generator, pkg string) { s := es.name g.P("type ", s, " ", pkg, ".", s) g.P("var ", s, "_name = ", pkg, ".", s, "_name") g.P("var ", s, "_value = ", pkg, ".", s, "_value") g.P("func (x ", s, ") String() string { return (", pkg, ".", s, ")(x).String() }") if !es.proto3 { g.P("func (x ", s, ") Enum() *", s, "{ return (*", s, ")((", pkg, ".", s, ")(x).Enum()) }") g.P("func (x *", s, ") UnmarshalJSON(data []byte) error { return (*", pkg, ".", s, ")(x).UnmarshalJSON(data) }") } } type constOrVarSymbol struct { sym string typ string // either "const" or "var" cast string // if non-empty, a type cast is required (used for enums) } func (cs constOrVarSymbol) GenerateAlias(g *Generator, pkg string) { v := pkg + "." + cs.sym if cs.cast != "" { v = cs.cast + "(" + v + ")" } g.P(cs.typ, " ", cs.sym, " = ", v) } // Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects. type Object interface { PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness. TypeName() []string File() *descriptor.FileDescriptorProto } // Each package name we generate must be unique. The package we're generating // gets its own name but every other package must have a unique name that does // not conflict in the code we generate. These names are chosen globally (although // they don't have to be, it simplifies things to do them globally). func uniquePackageOf(fd *descriptor.FileDescriptorProto) string { s, ok := uniquePackageName[fd] if !ok { log.Fatal("internal error: no package name defined for " + fd.GetName()) } return s } // Generator is the type whose methods generate the output, stored in the associated response structure. type Generator struct { *bytes.Buffer Request *plugin.CodeGeneratorRequest // The input. Response *plugin.CodeGeneratorResponse // The output. Param map[string]string // Command-line parameters. PackageImportPath string // Go import path of the package we're generating code for ImportPrefix string // String to prefix to imported package file names. ImportMap map[string]string // Mapping from import name to generated name Pkg map[string]string // The names under which we import support packages packageName string // What we're calling ourselves. allFiles []*FileDescriptor // All files in the tree allFilesByName map[string]*FileDescriptor // All files by filename. genFiles []*FileDescriptor // Those files we will generate output for. file *FileDescriptor // The file we are compiling now. usedPackages map[string]bool // Names of packages used in current file. typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax. init []string // Lines to emit in the init function. indent string writeOutput bool } // New creates a new generator and allocates the request and response protobufs. func New() *Generator { g := new(Generator) g.Buffer = new(bytes.Buffer) g.Request = new(plugin.CodeGeneratorRequest) g.Response = new(plugin.CodeGeneratorResponse) return g } // Error reports a problem, including an error, and exits the program. func (g *Generator) Error(err error, msgs ...string) { s := strings.Join(msgs, " ") + ":" + err.Error() log.Print("protoc-gen-go: error:", s) os.Exit(1) } // Fail reports a problem and exits the program. func (g *Generator) Fail(msgs ...string) { s := strings.Join(msgs, " ") log.Print("protoc-gen-go: error:", s) os.Exit(1) } // CommandLineParameters breaks the comma-separated list of key=value pairs // in the parameter (a member of the request protobuf) into a key/value map. // It then sets file name mappings defined by those entries. func (g *Generator) CommandLineParameters(parameter string) { g.Param = make(map[string]string) for _, p := range strings.Split(parameter, ",") { if i := strings.Index(p, "="); i < 0 { g.Param[p] = "" } else { g.Param[p[0:i]] = p[i+1:] } } g.ImportMap = make(map[string]string) pluginList := "none" // Default list of plugin names to enable (empty means all). for k, v := range g.Param { switch k { case "import_prefix": g.ImportPrefix = v case "import_path": g.PackageImportPath = v case "plugins": pluginList = v default: if len(k) > 0 && k[0] == 'M' { g.ImportMap[k[1:]] = v } } } if pluginList != "" { // Amend the set of plugins. enabled := make(map[string]bool) for _, name := range strings.Split(pluginList, "+") { enabled[name] = true } var nplugins []Plugin for _, p := range plugins { if enabled[p.Name()] { nplugins = append(nplugins, p) } } plugins = nplugins } } // DefaultPackageName returns the package name printed for the object. // If its file is in a different package, it returns the package name we're using for this file, plus ".". // Otherwise it returns the empty string. func (g *Generator) DefaultPackageName(obj Object) string { pkg := obj.PackageName() if pkg == g.packageName { return "" } return pkg + "." } // For each input file, the unique package name to use, underscored. var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string) // Package names already registered. Key is the name from the .proto file; // value is the name that appears in the generated code. var pkgNamesInUse = make(map[string]bool) // Create and remember a guaranteed unique package name for this file descriptor. // Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and // has no file descriptor. func RegisterUniquePackageName(pkg string, f *FileDescriptor) string { // Convert dots to underscores before finding a unique alias. pkg = strings.Map(badToUnderscore, pkg) for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ { // It's a duplicate; must rename. pkg = orig + strconv.Itoa(i) } // Install it. pkgNamesInUse[pkg] = true if f != nil { uniquePackageName[f.FileDescriptorProto] = pkg } return pkg } var isGoKeyword = map[string]bool{ "break": true, "case": true, "chan": true, "const": true, "continue": true, "default": true, "else": true, "defer": true, "fallthrough": true, "for": true, "func": true, "go": true, "goto": true, "if": true, "import": true, "interface": true, "map": true, "package": true, "range": true, "return": true, "select": true, "struct": true, "switch": true, "type": true, "var": true, } // defaultGoPackage returns the package name to use, // derived from the import path of the package we're building code for. func (g *Generator) defaultGoPackage() string { p := g.PackageImportPath if i := strings.LastIndex(p, "/"); i >= 0 { p = p[i+1:] } if p == "" { return "" } p = strings.Map(badToUnderscore, p) // Identifier must not be keyword: insert _. if isGoKeyword[p] { p = "_" + p } // Identifier must not begin with digit: insert _. if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) { p = "_" + p } return p } // SetPackageNames sets the package name for this run. // The package name must agree across all files being generated. // It also defines unique package names for all imported files. func (g *Generator) SetPackageNames() { // Register the name for this package. It will be the first name // registered so is guaranteed to be unmodified. pkg, explicit := g.genFiles[0].goPackageName() // Check all files for an explicit go_package option. for _, f := range g.genFiles { thisPkg, thisExplicit := f.goPackageName() if thisExplicit { if !explicit { // Let this file's go_package option serve for all input files. pkg, explicit = thisPkg, true } else if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } // If we don't have an explicit go_package option but we have an // import path, use that. if !explicit { p := g.defaultGoPackage() if p != "" { pkg, explicit = p, true } } // If there was no go_package and no import path to use, // double-check that all the inputs have the same implicit // Go package name. if !explicit { for _, f := range g.genFiles { thisPkg, _ := f.goPackageName() if thisPkg != pkg { g.Fail("inconsistent package names:", thisPkg, pkg) } } } g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0]) // Register the support package names. They might collide with the // name of a package we import. g.Pkg = map[string]string{ "fmt": RegisterUniquePackageName("fmt", nil), "math": RegisterUniquePackageName("math", nil), "proto": RegisterUniquePackageName("proto", nil), } AllFiles: for _, f := range g.allFiles { for _, genf := range g.genFiles { if f == genf { // In this package already. uniquePackageName[f.FileDescriptorProto] = g.packageName continue AllFiles } } // The file is a dependency, so we want to ignore its go_package option // because that is only relevant for its specific generated output. pkg := f.GetPackage() if pkg == "" { pkg = baseName(*f.Name) } RegisterUniquePackageName(pkg, f) } } // WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos // and FileDescriptorProtos into file-referenced objects within the Generator. // It also creates the list of files to generate and so should be called before GenerateAllFiles. func (g *Generator) WrapTypes() { g.allFiles = make([]*FileDescriptor, len(g.Request.ProtoFile)) g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles)) for i, f := range g.Request.ProtoFile { // We must wrap the descriptors before we wrap the enums descs := wrapDescriptors(f) g.buildNestedDescriptors(descs) enums := wrapEnumDescriptors(f, descs) g.buildNestedEnums(descs, enums) exts := wrapExtensions(f) fd := &FileDescriptor{ FileDescriptorProto: f, desc: descs, enum: enums, ext: exts, exported: make(map[Object][]symbol), proto3: fileIsProto3(f), } extractComments(fd) g.allFiles[i] = fd g.allFilesByName[f.GetName()] = fd } for _, fd := range g.allFiles { fd.imp = wrapImported(fd.FileDescriptorProto, g) } g.genFiles = make([]*FileDescriptor, len(g.Request.FileToGenerate)) for i, fileName := range g.Request.FileToGenerate { g.genFiles[i] = g.allFilesByName[fileName] if g.genFiles[i] == nil { g.Fail("could not find file named", fileName) } g.genFiles[i].index = i } g.Response.File = make([]*plugin.CodeGeneratorResponse_File, len(g.genFiles)) } // Scan the descriptors in this file. For each one, build the slice of nested descriptors func (g *Generator) buildNestedDescriptors(descs []*Descriptor) { for _, desc := range descs { if len(desc.NestedType) != 0 { for _, nest := range descs { if nest.parent == desc { desc.nested = append(desc.nested, nest) } } if len(desc.nested) != len(desc.NestedType) { g.Fail("internal error: nesting failure for", desc.GetName()) } } } } func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) { for _, desc := range descs { if len(desc.EnumType) != 0 { for _, enum := range enums { if enum.parent == desc { desc.enums = append(desc.enums, enum) } } if len(desc.enums) != len(desc.EnumType) { g.Fail("internal error: enum nesting failure for", desc.GetName()) } } } } // Construct the Descriptor func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *Descriptor { d := &Descriptor{ common: common{file}, DescriptorProto: desc, parent: parent, index: index, } if parent == nil { d.path = fmt.Sprintf("%d,%d", messagePath, index) } else { d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index) } // The only way to distinguish a group from a message is whether // the containing message has a TYPE_GROUP field that matches. if parent != nil { parts := d.TypeName() if file.Package != nil { parts = append([]string{*file.Package}, parts...) } exp := "." + strings.Join(parts, ".") for _, field := range parent.Field { if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp { d.group = true break } } } d.ext = make([]*ExtensionDescriptor, len(desc.Extension)) for i, field := range desc.Extension { d.ext[i] = &ExtensionDescriptor{common{file}, field, d} } return d } // Return a slice of all the Descriptors defined within this file func wrapDescriptors(file *descriptor.FileDescriptorProto) []*Descriptor { sl := make([]*Descriptor, 0, len(file.MessageType)+10) for i, desc := range file.MessageType { sl = wrapThisDescriptor(sl, desc, nil, file, i) } return sl } // Wrap this Descriptor, recursively func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) []*Descriptor { sl = append(sl, newDescriptor(desc, parent, file, index)) me := sl[len(sl)-1] for i, nested := range desc.NestedType { sl = wrapThisDescriptor(sl, nested, me, file, i) } return sl } // Construct the EnumDescriptor func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *descriptor.FileDescriptorProto, index int) *EnumDescriptor { ed := &EnumDescriptor{ common: common{file}, EnumDescriptorProto: desc, parent: parent, index: index, } if parent == nil { ed.path = fmt.Sprintf("%d,%d", enumPath, index) } else { ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index) } return ed } // Return a slice of all the EnumDescriptors defined within this file func wrapEnumDescriptors(file *descriptor.FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor { sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) // Top-level enums. for i, enum := range file.EnumType { sl = append(sl, newEnumDescriptor(enum, nil, file, i)) } // Enums within messages. Enums within embedded messages appear in the outer-most message. for _, nested := range descs { for i, enum := range nested.EnumType { sl = append(sl, newEnumDescriptor(enum, nested, file, i)) } } return sl } // Return a slice of all the top-level ExtensionDescriptors defined within this file. func wrapExtensions(file *descriptor.FileDescriptorProto) []*ExtensionDescriptor { sl := make([]*ExtensionDescriptor, len(file.Extension)) for i, field := range file.Extension { sl[i] = &ExtensionDescriptor{common{file}, field, nil} } return sl } // Return a slice of all the types that are publicly imported into this file. func wrapImported(file *descriptor.FileDescriptorProto, g *Generator) (sl []*ImportedDescriptor) { for _, index := range file.PublicDependency { df := g.fileByName(file.Dependency[index]) for _, d := range df.desc { if d.GetOptions().GetMapEntry() { continue } sl = append(sl, &ImportedDescriptor{common{file}, d}) } for _, e := range df.enum { sl = append(sl, &ImportedDescriptor{common{file}, e}) } for _, ext := range df.ext { sl = append(sl, &ImportedDescriptor{common{file}, ext}) } } return } func extractComments(file *FileDescriptor) { file.comments = make(map[string]*descriptor.SourceCodeInfo_Location) for _, loc := range file.GetSourceCodeInfo().GetLocation() { if loc.LeadingComments == nil { continue } var p []string for _, n := range loc.Path { p = append(p, strconv.Itoa(int(n))) } file.comments[strings.Join(p, ",")] = loc } } // BuildTypeNameMap builds the map from fully qualified type names to objects. // The key names for the map come from the input data, which puts a period at the beginning. // It should be called after SetPackageNames and before GenerateAllFiles. func (g *Generator) BuildTypeNameMap() { g.typeNameToObject = make(map[string]Object) for _, f := range g.allFiles { // The names in this loop are defined by the proto world, not us, so the // package name may be empty. If so, the dotted package name of X will // be ".X"; otherwise it will be ".pkg.X". dottedPkg := "." + f.GetPackage() if dottedPkg != "." { dottedPkg += "." } for _, enum := range f.enum { name := dottedPkg + dottedSlice(enum.TypeName()) g.typeNameToObject[name] = enum } for _, desc := range f.desc { name := dottedPkg + dottedSlice(desc.TypeName()) g.typeNameToObject[name] = desc } } } // ObjectNamed, given a fully-qualified input type name as it appears in the input data, // returns the descriptor for the message or enum with that name. func (g *Generator) ObjectNamed(typeName string) Object { o, ok := g.typeNameToObject[typeName] if !ok { g.Fail("can't find object with type", typeName) } // If the file of this object isn't a direct dependency of the current file, // or in the current file, then this object has been publicly imported into // a dependency of the current file. // We should return the ImportedDescriptor object for it instead. direct := *o.File().Name == *g.file.Name if !direct { for _, dep := range g.file.Dependency { if *g.fileByName(dep).Name == *o.File().Name { direct = true break } } } if !direct { found := false Loop: for _, dep := range g.file.Dependency { df := g.fileByName(*g.fileByName(dep).Name) for _, td := range df.imp { if td.o == o { // Found it! o = td found = true break Loop } } } if !found { log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name) } } return o } // P prints the arguments to the generated output. It handles strings and int32s, plus // handling indirections because they may be *string, etc. func (g *Generator) P(str ...interface{}) { if !g.writeOutput { return } g.WriteString(g.indent) for _, v := range str { switch s := v.(type) { case string: g.WriteString(s) case *string: g.WriteString(*s) case bool: fmt.Fprintf(g, "%t", s) case *bool: fmt.Fprintf(g, "%t", *s) case int: fmt.Fprintf(g, "%d", s) case *int32: fmt.Fprintf(g, "%d", *s) case *int64: fmt.Fprintf(g, "%d", *s) case float64: fmt.Fprintf(g, "%g", s) case *float64: fmt.Fprintf(g, "%g", *s) default: g.Fail(fmt.Sprintf("unknown type in printer: %T", v)) } } g.WriteByte('\n') } // addInitf stores the given statement to be printed inside the file's init function. // The statement is given as a format specifier and arguments. func (g *Generator) addInitf(stmt string, a ...interface{}) { g.init = append(g.init, fmt.Sprintf(stmt, a...)) } // In Indents the output one tab stop. func (g *Generator) In() { g.indent += "\t" } // Out unindents the output one tab stop. func (g *Generator) Out() { if len(g.indent) > 0 { g.indent = g.indent[1:] } } // GenerateAllFiles generates the output for all the files we're outputting. func (g *Generator) GenerateAllFiles() { // Initialize the plugins for _, p := range plugins { p.Init(g) } // Generate the output. The generator runs for every file, even the files // that we don't generate output for, so that we can collate the full list // of exported symbols to support public imports. genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles)) for _, file := range g.genFiles { genFileMap[file] = true } i := 0 for _, file := range g.allFiles { g.Reset() g.writeOutput = genFileMap[file] g.generate(file) if !g.writeOutput { continue } g.Response.File[i] = new(plugin.CodeGeneratorResponse_File) g.Response.File[i].Name = proto.String(goFileName(*file.Name)) g.Response.File[i].Content = proto.String(g.String()) i++ } } // Run all the plugins associated with the file. func (g *Generator) runPlugins(file *FileDescriptor) { for _, p := range plugins { p.Generate(file) } } // FileOf return the FileDescriptor for this FileDescriptorProto. func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor { for _, file := range g.allFiles { if file.FileDescriptorProto == fd { return file } } g.Fail("could not find file in table:", fd.GetName()) return nil } // Fill the response protocol buffer with the generated output for all the files we're // supposed to generate. func (g *Generator) generate(file *FileDescriptor) { g.file = g.FileOf(file.FileDescriptorProto) g.usedPackages = make(map[string]bool) if g.file.index == 0 { // For one file in the package, assert version compatibility. g.P("// This is a compile-time assertion to ensure that this generated file") g.P("// is compatible with the proto package it is being compiled against.") g.P("const _ = ", g.Pkg["proto"], ".ProtoPackageIsVersion", generatedCodeVersion) g.P() } for _, td := range g.file.imp { g.generateImported(td) } for _, enum := range g.file.enum { g.generateEnum(enum) } for _, desc := range g.file.desc { // Don't generate virtual messages for maps. if desc.GetOptions().GetMapEntry() { continue } g.generateMessage(desc) } for _, ext := range g.file.ext { g.generateExtension(ext) } g.generateInitFunction() // Run the plugins before the imports so we know which imports are necessary. g.runPlugins(file) g.generateFileDescriptor(file) // Generate header and imports last, though they appear first in the output. rem := g.Buffer g.Buffer = new(bytes.Buffer) g.generateHeader() g.generateImports() if !g.writeOutput { return } g.Write(rem.Bytes()) // Reformat generated code. fset := token.NewFileSet() raw := g.Bytes() ast, err := parser.ParseFile(fset, "", g, parser.ParseComments) if err != nil { // Print out the bad code with line numbers. // This should never happen in practice, but it can while changing generated code, // so consider this a debugging aid. var src bytes.Buffer s := bufio.NewScanner(bytes.NewReader(raw)) for line := 1; s.Scan(); line++ { fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes()) } g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String()) } g.Reset() err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast) if err != nil { g.Fail("generated Go source code could not be reformatted:", err.Error()) } } // Generate the header, including package definition func (g *Generator) generateHeader() { g.P("// Code generated by protoc-gen-go.") g.P("// source: ", g.file.Name) g.P("// DO NOT EDIT!") g.P() name := g.file.PackageName() if g.file.index == 0 { // Generate package docs for the first file in the package. g.P("/*") g.P("Package ", name, " is a generated protocol buffer package.") g.P() if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok { // not using g.PrintComments because this is a /* */ comment block. text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { line = strings.TrimPrefix(line, " ") // ensure we don't escape from the block comment line = strings.Replace(line, "*/", "* /", -1) g.P(line) } g.P() } var topMsgs []string g.P("It is generated from these files:") for _, f := range g.genFiles { g.P("\t", f.Name) for _, msg := range f.desc { if msg.parent != nil { continue } topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName())) } } g.P() g.P("It has these top-level messages:") for _, msg := range topMsgs { g.P("\t", msg) } g.P("*/") } g.P("package ", name) g.P() } // PrintComments prints any comments from the source .proto file. // The path is a comma-separated list of integers. // It returns an indication of whether any comments were printed. // See descriptor.proto for its format. func (g *Generator) PrintComments(path string) bool { if !g.writeOutput { return false } if loc, ok := g.file.comments[path]; ok { text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") for _, line := range strings.Split(text, "\n") { g.P("// ", strings.TrimPrefix(line, " ")) } return true } return false } func (g *Generator) fileByName(filename string) *FileDescriptor { return g.allFilesByName[filename] } // weak returns whether the ith import of the current file is a weak import. func (g *Generator) weak(i int32) bool { for _, j := range g.file.WeakDependency { if j == i { return true } } return false } // Generate the imports func (g *Generator) generateImports() { // We almost always need a proto import. Rather than computing when we // do, which is tricky when there's a plugin, just import it and // reference it later. The same argument applies to the fmt and math packages. g.P("import " + g.Pkg["proto"] + " " + strconv.Quote(g.ImportPrefix+"github.com/golang/protobuf/proto")) g.P("import " + g.Pkg["fmt"] + ` "fmt"`) g.P("import " + g.Pkg["math"] + ` "math"`) for i, s := range g.file.Dependency { fd := g.fileByName(s) // Do not import our own package. if fd.PackageName() == g.packageName { continue } filename := goFileName(s) // By default, import path is the dirname of the Go filename. importPath := path.Dir(filename) if substitution, ok := g.ImportMap[s]; ok { importPath = substitution } importPath = g.ImportPrefix + importPath // Skip weak imports. if g.weak(int32(i)) { g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath)) continue } // We need to import all the dependencies, even if we don't reference them, // because other code and tools depend on having the full transitive closure // of protocol buffer types in the binary. pname := fd.PackageName() if _, ok := g.usedPackages[pname]; !ok { pname = "_" } g.P("import ", pname, " ", strconv.Quote(importPath)) } g.P() // TODO: may need to worry about uniqueness across plugins for _, p := range plugins { p.GenerateImports(g.file) g.P() } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ = ", g.Pkg["proto"], ".Marshal") g.P("var _ = ", g.Pkg["fmt"], ".Errorf") g.P("var _ = ", g.Pkg["math"], ".Inf") g.P() } func (g *Generator) generateImported(id *ImportedDescriptor) { // Don't generate public import symbols for files that we are generating // code for, since those symbols will already be in this package. // We can't simply avoid creating the ImportedDescriptor objects, // because g.genFiles isn't populated at that stage. tn := id.TypeName() sn := tn[len(tn)-1] df := g.FileOf(id.o.File()) filename := *df.Name for _, fd := range g.genFiles { if *fd.Name == filename { g.P("// Ignoring public import of ", sn, " from ", filename) g.P() return } } g.P("// ", sn, " from public import ", filename) g.usedPackages[df.PackageName()] = true for _, sym := range df.exported[id.o] { sym.GenerateAlias(g, df.PackageName()) } g.P() } // Generate the enum definitions for this EnumDescriptor. func (g *Generator) generateEnum(enum *EnumDescriptor) { // The full type name typeName := enum.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) ccPrefix := enum.prefix() g.PrintComments(enum.path) g.P("type ", ccTypeName, " int32") g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()}) g.P("const (") g.In() for i, e := range enum.Value { g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)) name := ccPrefix + *e.Name g.P(name, " ", ccTypeName, " = ", e.Number) g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName}) } g.Out() g.P(")") g.P("var ", ccTypeName, "_name = map[int32]string{") g.In() generated := make(map[int32]bool) // avoid duplicate values for _, e := range enum.Value { duplicate := "" if _, present := generated[*e.Number]; present { duplicate = "// Duplicate value: " } g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",") generated[*e.Number] = true } g.Out() g.P("}") g.P("var ", ccTypeName, "_value = map[string]int32{") g.In() for _, e := range enum.Value { g.P(strconv.Quote(*e.Name), ": ", e.Number, ",") } g.Out() g.P("}") if !enum.proto3() { g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {") g.In() g.P("p := new(", ccTypeName, ")") g.P("*p = x") g.P("return p") g.Out() g.P("}") } g.P("func (x ", ccTypeName, ") String() string {") g.In() g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))") g.Out() g.P("}") if !enum.proto3() { g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {") g.In() g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`) g.P("if err != nil {") g.In() g.P("return err") g.Out() g.P("}") g.P("*x = ", ccTypeName, "(value)") g.P("return nil") g.Out() g.P("}") } var indexes []string for m := enum.parent; m != nil; m = m.parent { // XXX: skip groups? indexes = append([]string{strconv.Itoa(m.index)}, indexes...) } indexes = append(indexes, strconv.Itoa(enum.index)) g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) { return fileDescriptor", g.file.index, ", []int{", strings.Join(indexes, ", "), "} }") g.P() } // The tag is a string like "varint,2,opt,name=fieldname,def=7" that // identifies details of the field for the protocol buffer marshaling and unmarshaling // code. The fields are: // wire encoding // protocol tag number // opt,req,rep for optional, required, or repeated // packed whether the encoding is "packed" (optional; repeated primitives only) // name= the original declared name // enum= the name of the enum type if it is an enum-typed field. // proto3 if this field is in a proto3 message // def= string representation of the default value, if any. // The default value must be in a representation that can be used at run-time // to generate the default value. Thus bools become 0 and 1, for instance. func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string { optrepreq := "" switch { case isOptional(field): optrepreq = "opt" case isRequired(field): optrepreq = "req" case isRepeated(field): optrepreq = "rep" } var defaultValue string if dv := field.DefaultValue; dv != nil { // set means an explicit default defaultValue = *dv // Some types need tweaking. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: if defaultValue == "true" { defaultValue = "1" } else { defaultValue = "0" } case descriptor.FieldDescriptorProto_TYPE_STRING, descriptor.FieldDescriptorProto_TYPE_BYTES: // Nothing to do. Quoting is done for the whole tag. case descriptor.FieldDescriptorProto_TYPE_ENUM: // For enums we need to provide the integer constant. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { // It is an enum that was publicly imported. // We need the underlying type. obj = id.o } enum, ok := obj.(*EnumDescriptor) if !ok { log.Printf("obj is a %T", obj) if id, ok := obj.(*ImportedDescriptor); ok { log.Printf("id.o is a %T", id.o) } g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName())) } defaultValue = enum.integerValueAsString(defaultValue) } defaultValue = ",def=" + defaultValue } enum := "" if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM { // We avoid using obj.PackageName(), because we want to use the // original (proto-world) package name. obj := g.ObjectNamed(field.GetTypeName()) if id, ok := obj.(*ImportedDescriptor); ok { obj = id.o } enum = ",enum=" if pkg := obj.File().GetPackage(); pkg != "" { enum += pkg + "." } enum += CamelCaseSlice(obj.TypeName()) } packed := "" if field.Options != nil && field.Options.GetPacked() { packed = ",packed" } fieldName := field.GetName() name := fieldName if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { // We must use the type name for groups instead of // the field name to preserve capitalization. // type_name in FieldDescriptorProto is fully-qualified, // but we only want the local part. name = *field.TypeName if i := strings.LastIndex(name, "."); i >= 0 { name = name[i+1:] } } name = ",name=" + name if message.proto3() { // We only need the extra tag for []byte fields; // no need to add noise for the others. if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES { name += ",proto3" } } oneof := "" if field.OneofIndex != nil { oneof = ",oneof" } return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s", wiretype, field.GetNumber(), optrepreq, packed, name, enum, oneof, defaultValue)) } func needsStar(typ descriptor.FieldDescriptorProto_Type) bool { switch typ { case descriptor.FieldDescriptorProto_TYPE_GROUP: return false case descriptor.FieldDescriptorProto_TYPE_MESSAGE: return false case descriptor.FieldDescriptorProto_TYPE_BYTES: return false } return true } // TypeName is the printed name appropriate for an item. If the object is in the current file, // TypeName drops the package name and underscores the rest. // Otherwise the object is from another package; and the result is the underscored // package name followed by the item name. // The result always has an initial capital. func (g *Generator) TypeName(obj Object) string { return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName()) } // TypeNameWithPackage is like TypeName, but always includes the package // name even if the object is in our own package. func (g *Generator) TypeNameWithPackage(obj Object) string { return obj.PackageName() + CamelCaseSlice(obj.TypeName()) } // GoType returns a string representing the type name, and the wire type func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) { // TODO: Options. switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: typ, wire = "float64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FLOAT: typ, wire = "float32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_INT64: typ, wire = "int64", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT64: typ, wire = "uint64", "varint" case descriptor.FieldDescriptorProto_TYPE_INT32: typ, wire = "int32", "varint" case descriptor.FieldDescriptorProto_TYPE_UINT32: typ, wire = "uint32", "varint" case descriptor.FieldDescriptorProto_TYPE_FIXED64: typ, wire = "uint64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_FIXED32: typ, wire = "uint32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_BOOL: typ, wire = "bool", "varint" case descriptor.FieldDescriptorProto_TYPE_STRING: typ, wire = "string", "bytes" case descriptor.FieldDescriptorProto_TYPE_GROUP: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = "*"+g.TypeName(desc), "group" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = "*"+g.TypeName(desc), "bytes" case descriptor.FieldDescriptorProto_TYPE_BYTES: typ, wire = "[]byte", "bytes" case descriptor.FieldDescriptorProto_TYPE_ENUM: desc := g.ObjectNamed(field.GetTypeName()) typ, wire = g.TypeName(desc), "varint" case descriptor.FieldDescriptorProto_TYPE_SFIXED32: typ, wire = "int32", "fixed32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: typ, wire = "int64", "fixed64" case descriptor.FieldDescriptorProto_TYPE_SINT32: typ, wire = "int32", "zigzag32" case descriptor.FieldDescriptorProto_TYPE_SINT64: typ, wire = "int64", "zigzag64" default: g.Fail("unknown type for", field.GetName()) } if isRepeated(field) { typ = "[]" + typ } else if message != nil && message.proto3() { return } else if field.OneofIndex != nil && message != nil { return } else if needsStar(*field.Type) { typ = "*" + typ } return } func (g *Generator) RecordTypeUse(t string) { if obj, ok := g.typeNameToObject[t]; ok { // Call ObjectNamed to get the true object to record the use. obj = g.ObjectNamed(t) g.usedPackages[obj.PackageName()] = true } } // Method names that may be generated. Fields with these names get an // underscore appended. var methodNames = [...]string{ "Reset", "String", "ProtoMessage", "Marshal", "Unmarshal", "ExtensionRangeArray", "ExtensionMap", "Descriptor", } // Generate the type and default constant definitions for this Descriptor. func (g *Generator) generateMessage(message *Descriptor) { // The full type name typeName := message.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) usedNames := make(map[string]bool) for _, n := range methodNames { usedNames[n] = true } fieldNames := make(map[*descriptor.FieldDescriptorProto]string) fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string) fieldTypes := make(map[*descriptor.FieldDescriptorProto]string) mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) oneofFieldName := make(map[int32]string) // indexed by oneof_index field of FieldDescriptorProto oneofDisc := make(map[int32]string) // name of discriminator method oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star oneofInsertPoints := make(map[int32]int) // oneof_index => offset of g.Buffer g.PrintComments(message.path) g.P("type ", ccTypeName, " struct {") g.In() // allocNames finds a conflict-free variation of the given strings, // consistently mutating their suffixes. // It returns the same number of strings. allocNames := func(ns ...string) []string { Loop: for { for _, n := range ns { if usedNames[n] { for i := range ns { ns[i] += "_" } continue Loop } } for _, n := range ns { usedNames[n] = true } return ns } } for i, field := range message.Field { // Allocate the getter and the field at the same time so name // collisions create field/method consistent names. // TODO: This allocation occurs based on the order of the fields // in the proto file, meaning that a change in the field // ordering can change generated Method/Field names. base := CamelCase(*field.Name) ns := allocNames(base, "Get"+base) fieldName, fieldGetterName := ns[0], ns[1] typename, wiretype := g.GoType(message, field) jsonName := *field.Name tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty") fieldNames[field] = fieldName fieldGetterNames[field] = fieldGetterName oneof := field.OneofIndex != nil if oneof && oneofFieldName[*field.OneofIndex] == "" { odp := message.OneofDecl[int(*field.OneofIndex)] fname := allocNames(CamelCase(odp.GetName()))[0] // This is the first field of a oneof we haven't seen before. // Generate the union field. com := g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)) if com { g.P("//") } g.P("// Types that are valid to be assigned to ", fname, ":") // Generate the rest of this comment later, // when we've computed any disambiguation. oneofInsertPoints[*field.OneofIndex] = g.Buffer.Len() dname := "is" + ccTypeName + "_" + fname oneofFieldName[*field.OneofIndex] = fname oneofDisc[*field.OneofIndex] = dname tag := `protobuf_oneof:"` + odp.GetName() + `"` g.P(fname, " ", dname, " `", tag, "`") } if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE { desc := g.ObjectNamed(field.GetTypeName()) if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() { // Figure out the Go types and tags for the key and value types. keyField, valField := d.Field[0], d.Field[1] keyType, keyWire := g.GoType(d, keyField) valType, valWire := g.GoType(d, valField) keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire) // We don't use stars, except for message-typed values. // Message and enum types are the only two possibly foreign types used in maps, // so record their use. They are not permitted as map keys. keyType = strings.TrimPrefix(keyType, "*") switch *valField.Type { case descriptor.FieldDescriptorProto_TYPE_ENUM: valType = strings.TrimPrefix(valType, "*") g.RecordTypeUse(valField.GetTypeName()) case descriptor.FieldDescriptorProto_TYPE_MESSAGE: g.RecordTypeUse(valField.GetTypeName()) default: valType = strings.TrimPrefix(valType, "*") } typename = fmt.Sprintf("map[%s]%s", keyType, valType) mapFieldTypes[field] = typename // record for the getter generation tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag) } } fieldTypes[field] = typename if oneof { tname := ccTypeName + "_" + fieldName // It is possible for this to collide with a message or enum // nested in this message. Check for collisions. for { ok := true for _, desc := range message.nested { if CamelCaseSlice(desc.TypeName()) == tname { ok = false break } } for _, enum := range message.enums { if CamelCaseSlice(enum.TypeName()) == tname { ok = false break } } if !ok { tname += "_" continue } break } oneofTypeName[field] = tname continue } g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)) g.P(fieldName, "\t", typename, "\t`", tag, "`") g.RecordTypeUse(field.GetTypeName()) } if len(message.ExtensionRange) > 0 { g.P("XXX_extensions\t\tmap[int32]", g.Pkg["proto"], ".Extension `json:\"-\"`") } if !message.proto3() { g.P("XXX_unrecognized\t[]byte `json:\"-\"`") } g.Out() g.P("}") // Update g.Buffer to list valid oneof types. // We do this down here, after we've disambiguated the oneof type names. // We go in reverse order of insertion point to avoid invalidating offsets. for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- { ip := oneofInsertPoints[oi] all := g.Buffer.Bytes() rem := all[ip:] g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem for _, field := range message.Field { if field.OneofIndex == nil || *field.OneofIndex != oi { continue } g.P("//\t*", oneofTypeName[field]) } g.Buffer.Write(rem) } // Reset, String and ProtoMessage methods. g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }") g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }") g.P("func (*", ccTypeName, ") ProtoMessage() {}") if !message.group { var indexes []string for m := message; m != nil; m = m.parent { // XXX: skip groups? indexes = append([]string{strconv.Itoa(m.index)}, indexes...) } g.P("func (*", ccTypeName, ") Descriptor() ([]byte, []int) { return fileDescriptor", g.file.index, ", []int{", strings.Join(indexes, ", "), "} }") } // Extension support methods var hasExtensions, isMessageSet bool if len(message.ExtensionRange) > 0 { hasExtensions = true // message_set_wire_format only makes sense when extensions are defined. if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() { isMessageSet = true g.P() g.P("func (m *", ccTypeName, ") Marshal() ([]byte, error) {") g.In() g.P("return ", g.Pkg["proto"], ".MarshalMessageSet(m.ExtensionMap())") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") Unmarshal(buf []byte) error {") g.In() g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSet(buf, m.ExtensionMap())") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {") g.In() g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(m.XXX_extensions)") g.Out() g.P("}") g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {") g.In() g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, m.XXX_extensions)") g.Out() g.P("}") g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler") g.P("var _ ", g.Pkg["proto"], ".Marshaler = (*", ccTypeName, ")(nil)") g.P("var _ ", g.Pkg["proto"], ".Unmarshaler = (*", ccTypeName, ")(nil)") } g.P() g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{") g.In() for _, r := range message.ExtensionRange { end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends g.P("{", r.Start, ", ", end, "},") } g.Out() g.P("}") g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {") g.In() g.P("return extRange_", ccTypeName) g.Out() g.P("}") g.P("func (m *", ccTypeName, ") ExtensionMap() map[int32]", g.Pkg["proto"], ".Extension {") g.In() g.P("if m.XXX_extensions == nil {") g.In() g.P("m.XXX_extensions = make(map[int32]", g.Pkg["proto"], ".Extension)") g.Out() g.P("}") g.P("return m.XXX_extensions") g.Out() g.P("}") } // Default constants defNames := make(map[*descriptor.FieldDescriptorProto]string) for _, field := range message.Field { def := field.GetDefaultValue() if def == "" { continue } fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name) defNames[field] = fieldname typename, _ := g.GoType(message, field) if typename[0] == '*' { typename = typename[1:] } kind := "const " switch { case typename == "bool": case typename == "string": def = strconv.Quote(def) case typename == "[]byte": def = "[]byte(" + strconv.Quote(def) + ")" kind = "var " case def == "inf", def == "-inf", def == "nan": // These names are known to, and defined by, the protocol language. switch def { case "inf": def = "math.Inf(1)" case "-inf": def = "math.Inf(-1)" case "nan": def = "math.NaN()" } if *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT { def = "float32(" + def + ")" } kind = "var " case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM: // Must be an enum. Need to construct the prefixed name. obj := g.ObjectNamed(field.GetTypeName()) var enum *EnumDescriptor if id, ok := obj.(*ImportedDescriptor); ok { // The enum type has been publicly imported. enum, _ = id.o.(*EnumDescriptor) } else { enum, _ = obj.(*EnumDescriptor) } if enum == nil { log.Printf("don't know how to generate constant for %s", fieldname) continue } def = g.DefaultPackageName(obj) + enum.prefix() + def } g.P(kind, fieldname, " ", typename, " = ", def) g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""}) } g.P() // Oneof per-field types, discriminants and getters. // // Generate unexported named types for the discriminant interfaces. // We shouldn't have to do this, but there was (~19 Aug 2015) a compiler/linker bug // that was triggered by using anonymous interfaces here. // TODO: Revisit this and consider reverting back to anonymous interfaces. for oi := range message.OneofDecl { dname := oneofDisc[int32(oi)] g.P("type ", dname, " interface { ", dname, "() }") } g.P() for _, field := range message.Field { if field.OneofIndex == nil { continue } _, wiretype := g.GoType(message, field) tag := "protobuf:" + g.goTag(message, field, wiretype) g.P("type ", oneofTypeName[field], " struct{ ", fieldNames[field], " ", fieldTypes[field], " `", tag, "` }") g.RecordTypeUse(field.GetTypeName()) } g.P() for _, field := range message.Field { if field.OneofIndex == nil { continue } g.P("func (*", oneofTypeName[field], ") ", oneofDisc[*field.OneofIndex], "() {}") } g.P() for oi := range message.OneofDecl { fname := oneofFieldName[int32(oi)] g.P("func (m *", ccTypeName, ") Get", fname, "() ", oneofDisc[int32(oi)], " {") g.P("if m != nil { return m.", fname, " }") g.P("return nil") g.P("}") } g.P() // Field getters var getters []getterSymbol for _, field := range message.Field { oneof := field.OneofIndex != nil fname := fieldNames[field] typename, _ := g.GoType(message, field) if t, ok := mapFieldTypes[field]; ok { typename = t } mname := fieldGetterNames[field] star := "" if needsStar(*field.Type) && typename[0] == '*' { typename = typename[1:] star = "*" } // In proto3, only generate getters for message fields and oneof fields. if message.proto3() && *field.Type != descriptor.FieldDescriptorProto_TYPE_MESSAGE && !oneof { continue } // Only export getter symbols for basic types, // and for messages and enums in the same package. // Groups are not exported. // Foreign types can't be hoisted through a public import because // the importer may not already be importing the defining .proto. // As an example, imagine we have an import tree like this: // A.proto -> B.proto -> C.proto // If A publicly imports B, we need to generate the getters from B in A's output, // but if one such getter returns something from C then we cannot do that // because A is not importing C already. var getter, genType bool switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_GROUP: getter = false case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_ENUM: // Only export getter if its return type is in this package. getter = g.ObjectNamed(field.GetTypeName()).PackageName() == message.PackageName() genType = true default: getter = true } if getter { getters = append(getters, getterSymbol{ name: mname, typ: typename, typeName: field.GetTypeName(), genType: genType, }) } g.P("func (m *", ccTypeName, ") "+mname+"() "+typename+" {") g.In() def, hasDef := defNames[field] typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BYTES: typeDefaultIsNil = !hasDef case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: typeDefaultIsNil = true } if isRepeated(field) { typeDefaultIsNil = true } if typeDefaultIsNil && !oneof { // A bytes field with no explicit default needs less generated code, // as does a message or group field, or a repeated field. g.P("if m != nil {") g.In() g.P("return m." + fname) g.Out() g.P("}") g.P("return nil") g.Out() g.P("}") g.P() continue } if !oneof { g.P("if m != nil && m." + fname + " != nil {") g.In() g.P("return " + star + "m." + fname) g.Out() g.P("}") } else { uname := oneofFieldName[*field.OneofIndex] tname := oneofTypeName[field] g.P("if x, ok := m.Get", uname, "().(*", tname, "); ok {") g.P("return x.", fname) g.P("}") } if hasDef { if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES { g.P("return " + def) } else { // The default is a []byte var. // Make a copy when returning it to be safe. g.P("return append([]byte(nil), ", def, "...)") } } else { switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: g.P("return false") case descriptor.FieldDescriptorProto_TYPE_STRING: g.P(`return ""`) case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_BYTES: // This is only possible for oneof fields. g.P("return nil") case descriptor.FieldDescriptorProto_TYPE_ENUM: // The default default for an enum is the first value in the enum, // not zero. obj := g.ObjectNamed(field.GetTypeName()) var enum *EnumDescriptor if id, ok := obj.(*ImportedDescriptor); ok { // The enum type has been publicly imported. enum, _ = id.o.(*EnumDescriptor) } else { enum, _ = obj.(*EnumDescriptor) } if enum == nil { log.Printf("don't know how to generate getter for %s", field.GetName()) continue } if len(enum.Value) == 0 { g.P("return 0 // empty enum") } else { first := enum.Value[0].GetName() g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first) } default: g.P("return 0") } } g.Out() g.P("}") g.P() } if !message.group { ms := &messageSymbol{ sym: ccTypeName, hasExtensions: hasExtensions, isMessageSet: isMessageSet, hasOneof: len(message.OneofDecl) > 0, getters: getters, } g.file.addExport(message, ms) } // Oneof functions if len(message.OneofDecl) > 0 { fieldWire := make(map[*descriptor.FieldDescriptorProto]string) // method enc := "_" + ccTypeName + "_OneofMarshaler" dec := "_" + ccTypeName + "_OneofUnmarshaler" size := "_" + ccTypeName + "_OneofSizer" encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error" decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)" sizeSig := "(msg " + g.Pkg["proto"] + ".Message) (n int)" g.P("// XXX_OneofFuncs is for the internal use of the proto package.") g.P("func (*", ccTypeName, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {") g.P("return ", enc, ", ", dec, ", ", size, ", []interface{}{") for _, field := range message.Field { if field.OneofIndex == nil { continue } g.P("(*", oneofTypeName[field], ")(nil),") } g.P("}") g.P("}") g.P() // marshaler g.P("func ", enc, encSig, " {") g.P("m := msg.(*", ccTypeName, ")") for oi, odp := range message.OneofDecl { g.P("// ", odp.GetName()) fname := oneofFieldName[int32(oi)] g.P("switch x := m.", fname, ".(type) {") for _, field := range message.Field { if field.OneofIndex == nil || int(*field.OneofIndex) != oi { continue } g.P("case *", oneofTypeName[field], ":") var wire, pre, post string val := "x." + fieldNames[field] // overridden for TYPE_BOOL canFail := false // only TYPE_MESSAGE and TYPE_GROUP can fail switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: wire = "WireFixed64" pre = "b.EncodeFixed64(" + g.Pkg["math"] + ".Float64bits(" post = "))" case descriptor.FieldDescriptorProto_TYPE_FLOAT: wire = "WireFixed32" pre = "b.EncodeFixed32(uint64(" + g.Pkg["math"] + ".Float32bits(" post = ")))" case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64: wire = "WireVarint" pre, post = "b.EncodeVarint(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: wire = "WireVarint" pre, post = "b.EncodeVarint(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: wire = "WireFixed64" pre, post = "b.EncodeFixed64(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: wire = "WireFixed32" pre, post = "b.EncodeFixed32(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_BOOL: // bool needs special handling. g.P("t := uint64(0)") g.P("if ", val, " { t = 1 }") val = "t" wire = "WireVarint" pre, post = "b.EncodeVarint(", ")" case descriptor.FieldDescriptorProto_TYPE_STRING: wire = "WireBytes" pre, post = "b.EncodeStringBytes(", ")" case descriptor.FieldDescriptorProto_TYPE_GROUP: wire = "WireStartGroup" pre, post = "b.Marshal(", ")" canFail = true case descriptor.FieldDescriptorProto_TYPE_MESSAGE: wire = "WireBytes" pre, post = "b.EncodeMessage(", ")" canFail = true case descriptor.FieldDescriptorProto_TYPE_BYTES: wire = "WireBytes" pre, post = "b.EncodeRawBytes(", ")" case descriptor.FieldDescriptorProto_TYPE_SINT32: wire = "WireVarint" pre, post = "b.EncodeZigzag32(uint64(", "))" case descriptor.FieldDescriptorProto_TYPE_SINT64: wire = "WireVarint" pre, post = "b.EncodeZigzag64(uint64(", "))" default: g.Fail("unhandled oneof field type ", field.Type.String()) } fieldWire[field] = wire g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") if !canFail { g.P(pre, val, post) } else { g.P("if err := ", pre, val, post, "; err != nil {") g.P("return err") g.P("}") } if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") } } g.P("case nil:") g.P("default: return ", g.Pkg["fmt"], `.Errorf("`, ccTypeName, ".", fname, ` has unexpected type %T", x)`) g.P("}") } g.P("return nil") g.P("}") g.P() // unmarshaler g.P("func ", dec, decSig, " {") g.P("m := msg.(*", ccTypeName, ")") g.P("switch tag {") for _, field := range message.Field { if field.OneofIndex == nil { continue } odp := message.OneofDecl[int(*field.OneofIndex)] g.P("case ", field.Number, ": // ", odp.GetName(), ".", *field.Name) g.P("if wire != ", g.Pkg["proto"], ".", fieldWire[field], " {") g.P("return true, ", g.Pkg["proto"], ".ErrInternalBadWireType") g.P("}") lhs := "x, err" // overridden for TYPE_MESSAGE and TYPE_GROUP var dec, cast, cast2 string switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: dec, cast = "b.DecodeFixed64()", g.Pkg["math"]+".Float64frombits" case descriptor.FieldDescriptorProto_TYPE_FLOAT: dec, cast, cast2 = "b.DecodeFixed32()", "uint32", g.Pkg["math"]+".Float32frombits" case descriptor.FieldDescriptorProto_TYPE_INT64: dec, cast = "b.DecodeVarint()", "int64" case descriptor.FieldDescriptorProto_TYPE_UINT64: dec = "b.DecodeVarint()" case descriptor.FieldDescriptorProto_TYPE_INT32: dec, cast = "b.DecodeVarint()", "int32" case descriptor.FieldDescriptorProto_TYPE_FIXED64: dec = "b.DecodeFixed64()" case descriptor.FieldDescriptorProto_TYPE_FIXED32: dec, cast = "b.DecodeFixed32()", "uint32" case descriptor.FieldDescriptorProto_TYPE_BOOL: dec = "b.DecodeVarint()" // handled specially below case descriptor.FieldDescriptorProto_TYPE_STRING: dec = "b.DecodeStringBytes()" case descriptor.FieldDescriptorProto_TYPE_GROUP: g.P("msg := new(", fieldTypes[field][1:], ")") // drop star lhs = "err" dec = "b.DecodeGroup(msg)" // handled specially below case descriptor.FieldDescriptorProto_TYPE_MESSAGE: g.P("msg := new(", fieldTypes[field][1:], ")") // drop star lhs = "err" dec = "b.DecodeMessage(msg)" // handled specially below case descriptor.FieldDescriptorProto_TYPE_BYTES: dec = "b.DecodeRawBytes(true)" case descriptor.FieldDescriptorProto_TYPE_UINT32: dec, cast = "b.DecodeVarint()", "uint32" case descriptor.FieldDescriptorProto_TYPE_ENUM: dec, cast = "b.DecodeVarint()", fieldTypes[field] case descriptor.FieldDescriptorProto_TYPE_SFIXED32: dec, cast = "b.DecodeFixed32()", "int32" case descriptor.FieldDescriptorProto_TYPE_SFIXED64: dec, cast = "b.DecodeFixed64()", "int64" case descriptor.FieldDescriptorProto_TYPE_SINT32: dec, cast = "b.DecodeZigzag32()", "int32" case descriptor.FieldDescriptorProto_TYPE_SINT64: dec, cast = "b.DecodeZigzag64()", "int64" default: g.Fail("unhandled oneof field type ", field.Type.String()) } g.P(lhs, " := ", dec) val := "x" if cast != "" { val = cast + "(" + val + ")" } if cast2 != "" { val = cast2 + "(" + val + ")" } switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_BOOL: val += " != 0" case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE: val = "msg" } g.P("m.", oneofFieldName[*field.OneofIndex], " = &", oneofTypeName[field], "{", val, "}") g.P("return true, err") } g.P("default: return false, nil") g.P("}") g.P("}") g.P() // sizer g.P("func ", size, sizeSig, " {") g.P("m := msg.(*", ccTypeName, ")") for oi, odp := range message.OneofDecl { g.P("// ", odp.GetName()) fname := oneofFieldName[int32(oi)] g.P("switch x := m.", fname, ".(type) {") for _, field := range message.Field { if field.OneofIndex == nil || int(*field.OneofIndex) != oi { continue } g.P("case *", oneofTypeName[field], ":") val := "x." + fieldNames[field] var wire, varint, fixed string switch *field.Type { case descriptor.FieldDescriptorProto_TYPE_DOUBLE: wire = "WireFixed64" fixed = "8" case descriptor.FieldDescriptorProto_TYPE_FLOAT: wire = "WireFixed32" fixed = "4" case descriptor.FieldDescriptorProto_TYPE_INT64, descriptor.FieldDescriptorProto_TYPE_UINT64, descriptor.FieldDescriptorProto_TYPE_INT32, descriptor.FieldDescriptorProto_TYPE_UINT32, descriptor.FieldDescriptorProto_TYPE_ENUM: wire = "WireVarint" varint = val case descriptor.FieldDescriptorProto_TYPE_FIXED64, descriptor.FieldDescriptorProto_TYPE_SFIXED64: wire = "WireFixed64" fixed = "8" case descriptor.FieldDescriptorProto_TYPE_FIXED32, descriptor.FieldDescriptorProto_TYPE_SFIXED32: wire = "WireFixed32" fixed = "4" case descriptor.FieldDescriptorProto_TYPE_BOOL: wire = "WireVarint" fixed = "1" case descriptor.FieldDescriptorProto_TYPE_STRING: wire = "WireBytes" fixed = "len(" + val + ")" varint = fixed case descriptor.FieldDescriptorProto_TYPE_GROUP: wire = "WireStartGroup" fixed = g.Pkg["proto"] + ".Size(" + val + ")" case descriptor.FieldDescriptorProto_TYPE_MESSAGE: wire = "WireBytes" g.P("s := ", g.Pkg["proto"], ".Size(", val, ")") fixed = "s" varint = fixed case descriptor.FieldDescriptorProto_TYPE_BYTES: wire = "WireBytes" fixed = "len(" + val + ")" varint = fixed case descriptor.FieldDescriptorProto_TYPE_SINT32: wire = "WireVarint" varint = "(uint32(" + val + ") << 1) ^ uint32((int32(" + val + ") >> 31))" case descriptor.FieldDescriptorProto_TYPE_SINT64: wire = "WireVarint" varint = "uint64(" + val + " << 1) ^ uint64((int64(" + val + ") >> 63))" default: g.Fail("unhandled oneof field type ", field.Type.String()) } g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")") if varint != "" { g.P("n += ", g.Pkg["proto"], ".SizeVarint(uint64(", varint, "))") } if fixed != "" { g.P("n += ", fixed) } if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP { g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)") } } g.P("case nil:") g.P("default:") g.P("panic(", g.Pkg["fmt"], ".Sprintf(\"proto: unexpected type %T in oneof\", x))") g.P("}") } g.P("return n") g.P("}") g.P() } for _, ext := range message.ext { g.generateExtension(ext) } fullName := strings.Join(message.TypeName(), ".") if g.file.Package != nil { fullName = *g.file.Package + "." + fullName } g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], ccTypeName, fullName) } func (g *Generator) generateExtension(ext *ExtensionDescriptor) { ccTypeName := ext.DescName() extObj := g.ObjectNamed(*ext.Extendee) var extDesc *Descriptor if id, ok := extObj.(*ImportedDescriptor); ok { // This is extending a publicly imported message. // We need the underlying type for goTag. extDesc = id.o.(*Descriptor) } else { extDesc = extObj.(*Descriptor) } extendedType := "*" + g.TypeName(extObj) // always use the original field := ext.FieldDescriptorProto fieldType, wireType := g.GoType(ext.parent, field) tag := g.goTag(extDesc, field, wireType) g.RecordTypeUse(*ext.Extendee) if n := ext.FieldDescriptorProto.TypeName; n != nil { // foreign extension type g.RecordTypeUse(*n) } typeName := ext.TypeName() // Special case for proto2 message sets: If this extension is extending // proto2_bridge.MessageSet, and its final name component is "message_set_extension", // then drop that last component. mset := false if extendedType == "*proto2_bridge.MessageSet" && typeName[len(typeName)-1] == "message_set_extension" { typeName = typeName[:len(typeName)-1] mset = true } // For text formatting, the package must be exactly what the .proto file declares, // ignoring overrides such as the go_package option, and with no dot/underscore mapping. extName := strings.Join(typeName, ".") if g.file.Package != nil { extName = *g.file.Package + "." + extName } g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{") g.In() g.P("ExtendedType: (", extendedType, ")(nil),") g.P("ExtensionType: (", fieldType, ")(nil),") g.P("Field: ", field.Number, ",") g.P(`Name: "`, extName, `",`) g.P("Tag: ", tag, ",") g.Out() g.P("}") g.P() if mset { // Generate a bit more code to register with message_set.go. g.addInitf("%s.RegisterMessageSetType((%s)(nil), %d, %q)", g.Pkg["proto"], fieldType, *field.Number, extName) } g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""}) } func (g *Generator) generateInitFunction() { for _, enum := range g.file.enum { g.generateEnumRegistration(enum) } for _, d := range g.file.desc { for _, ext := range d.ext { g.generateExtensionRegistration(ext) } } for _, ext := range g.file.ext { g.generateExtensionRegistration(ext) } if len(g.init) == 0 { return } g.P("func init() {") g.In() for _, l := range g.init { g.P(l) } g.Out() g.P("}") g.init = nil } func (g *Generator) generateFileDescriptor(file *FileDescriptor) { // Make a copy and trim source_code_info data. // TODO: Trim this more when we know exactly what we need. pb := proto.Clone(file.FileDescriptorProto).(*descriptor.FileDescriptorProto) pb.SourceCodeInfo = nil b, err := proto.Marshal(pb) if err != nil { g.Fail(err.Error()) } var buf bytes.Buffer w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression) w.Write(b) w.Close() b = buf.Bytes() v := fmt.Sprintf("fileDescriptor%d", file.index) g.P() g.P("var ", v, " = []byte{") g.In() g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto") for len(b) > 0 { n := 16 if n > len(b) { n = len(b) } s := "" for _, c := range b[:n] { s += fmt.Sprintf("0x%02x,", c) } g.P(s) b = b[n:] } g.Out() g.P("}") } func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) { // // We always print the full (proto-world) package name here. pkg := enum.File().GetPackage() if pkg != "" { pkg += "." } // The full type name typeName := enum.TypeName() // The full type name, CamelCased. ccTypeName := CamelCaseSlice(typeName) g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName) } func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) { g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName()) } // And now lots of helper functions. // Is c an ASCII lower-case letter? func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } // Is c an ASCII digit? func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' } // CamelCase returns the CamelCased name. // If there is an interior underscore followed by a lower case letter, // drop the underscore and convert the letter to upper case. // There is a remote possibility of this rewrite causing a name collision, // but it's so remote we're prepared to pretend it's nonexistent - since the // C++ generator lowercases names, it's extremely unlikely to have two fields // with different capitalizations. // In short, _my_field_name_2 becomes XMyFieldName_2. func CamelCase(s string) string { if s == "" { return "" } t := make([]byte, 0, 32) i := 0 if s[0] == '_' { // Need a capital letter; drop the '_'. t = append(t, 'X') i++ } // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. for ; i < len(s); i++ { c := s[i] if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { continue // Skip the underscore in s. } if isASCIIDigit(c) { t = append(t, c) continue } // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c ^= ' ' // Make it a capital letter. } t = append(t, c) // Guaranteed not lower case. // Accept lower case sequence that follows. for i+1 < len(s) && isASCIILower(s[i+1]) { i++ t = append(t, s[i]) } } return string(t) } // CamelCaseSlice is like CamelCase, but the argument is a slice of strings to // be joined with "_". func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) } // dottedSlice turns a sliced name into a dotted name. func dottedSlice(elem []string) string { return strings.Join(elem, ".") } // Given a .proto file name, return the output name for the generated Go program. func goFileName(name string) string { ext := path.Ext(name) if ext == ".proto" || ext == ".protodevel" { name = name[0 : len(name)-len(ext)] } return name + ".pb.go" } // Is this field optional? func isOptional(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL } // Is this field required? func isRequired(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED } // Is this field repeated? func isRepeated(field *descriptor.FieldDescriptorProto) bool { return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED } // badToUnderscore is the mapping function used to generate Go names from package names, // which can be dotted in the input .proto file. It replaces non-identifier characters such as // dot or dash with underscore. func badToUnderscore(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { return r } return '_' } // baseName returns the last path element of the name, with the last dotted suffix removed. func baseName(name string) string { // First, find the last element if i := strings.LastIndex(name, "/"); i >= 0 { name = name[i+1:] } // Now drop the suffix if i := strings.LastIndex(name, "."); i >= 0 { name = name[0:i] } return name } // The SourceCodeInfo message describes the location of elements of a parsed // .proto file by way of a "path", which is a sequence of integers that // describe the route from a FileDescriptorProto to the relevant submessage. // The path alternates between a field number of a repeated field, and an index // into that repeated field. The constants below define the field numbers that // are used. // // See descriptor.proto for more information about this. const ( // tag numbers in FileDescriptorProto packagePath = 2 // package messagePath = 4 // message_type enumPath = 5 // enum_type // tag numbers in DescriptorProto messageFieldPath = 2 // field messageMessagePath = 3 // nested_type messageEnumPath = 4 // enum_type messageOneofPath = 8 // oneof_decl // tag numbers in EnumDescriptorProto enumValuePath = 2 // value ) ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2013 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 generator import ( "testing" ) func TestCamelCase(t *testing.T) { tests := []struct { in, want string }{ {"one", "One"}, {"one_two", "OneTwo"}, {"_my_field_name_2", "XMyFieldName_2"}, {"Something_Capped", "Something_Capped"}, {"my_Name", "My_Name"}, {"OneTwo", "OneTwo"}, {"_", "X"}, {"_a_", "XA_"}, } for _, tc := range tests { if got := CamelCase(tc.in); got != tc.want { t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want) } } } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/internal/grpc/grpc.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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 grpc outputs gRPC service descriptions in Go code. // It runs as a plugin for the Go protocol buffer compiler plugin. // It is linked in to protoc-gen-go. package grpc import ( "fmt" "path" "strconv" "strings" pb "github.com/golang/protobuf/protoc-gen-go/descriptor" "github.com/golang/protobuf/protoc-gen-go/generator" ) // Paths for packages used by code generated in this file, // relative to the import_prefix of the generator.Generator. const ( contextPkgPath = "golang.org/x/net/context" grpcPkgPath = "google.golang.org/grpc" ) func init() { generator.RegisterPlugin(new(grpc)) } // grpc is an implementation of the Go protocol buffer compiler's // plugin architecture. It generates bindings for gRPC support. type grpc struct { gen *generator.Generator } // Name returns the name of this plugin, "grpc". func (g *grpc) Name() string { return "grpc" } // The names for packages imported in the generated code. // They may vary from the final path component of the import path // if the name is used by other packages. var ( contextPkg string grpcPkg string ) // Init initializes the plugin. func (g *grpc) Init(gen *generator.Generator) { g.gen = gen contextPkg = generator.RegisterUniquePackageName("context", nil) grpcPkg = generator.RegisterUniquePackageName("grpc", nil) } // Given a type name defined in a .proto, return its object. // Also record that we're using it, to guarantee the associated import. func (g *grpc) objectNamed(name string) generator.Object { g.gen.RecordTypeUse(name) return g.gen.ObjectNamed(name) } // Given a type name defined in a .proto, return its name as we will print it. func (g *grpc) typeName(str string) string { return g.gen.TypeName(g.objectNamed(str)) } // P forwards to g.gen.P. func (g *grpc) P(args ...interface{}) { g.gen.P(args...) } // Generate generates code for the services in the given file. func (g *grpc) Generate(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("// Reference imports to suppress errors if they are not otherwise used.") g.P("var _ ", contextPkg, ".Context") g.P("var _ ", grpcPkg, ".ClientConn") g.P() for i, service := range file.FileDescriptorProto.Service { g.generateService(file, service, i) } } // GenerateImports generates the import declaration for this file. func (g *grpc) GenerateImports(file *generator.FileDescriptor) { if len(file.FileDescriptorProto.Service) == 0 { return } g.P("import (") g.P(contextPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, contextPkgPath))) g.P(grpcPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, grpcPkgPath))) g.P(")") g.P() } // reservedClientName records whether a client name is reserved on the client side. var reservedClientName = map[string]bool{ // TODO: do we need any in gRPC? } func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } // generateService generates all the code for the named service. func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) { path := fmt.Sprintf("6,%d", index) // 6 means service. origServName := service.GetName() fullServName := origServName if pkg := file.GetPackage(); pkg != "" { fullServName = pkg + "." + fullServName } servName := generator.CamelCase(origServName) g.P() g.P("// Client API for ", servName, " service") g.P() // Client interface. g.P("type ", servName, "Client interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateClientSignature(servName, method)) } g.P("}") g.P() // Client structure. g.P("type ", unexport(servName), "Client struct {") g.P("cc *", grpcPkg, ".ClientConn") g.P("}") g.P() // NewClient factory. g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {") g.P("return &", unexport(servName), "Client{cc}") g.P("}") g.P() var methodIndex, streamIndex int serviceDescVar := "_" + servName + "_serviceDesc" // Client method implementations. for _, method := range service.Method { var descExpr string if !method.GetServerStreaming() && !method.GetClientStreaming() { // Unary RPC method descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex) methodIndex++ } else { // Streaming RPC method descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex) streamIndex++ } g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr) } g.P("// Server API for ", servName, " service") g.P() // Server interface. serverType := servName + "Server" g.P("type ", serverType, " interface {") for i, method := range service.Method { g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service. g.P(g.generateServerSignature(servName, method)) } g.P("}") g.P() // Server registration. g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {") g.P("s.RegisterService(&", serviceDescVar, `, srv)`) g.P("}") g.P() // Server handler implementations. var handlerNames []string for _, method := range service.Method { hname := g.generateServerMethod(servName, method) handlerNames = append(handlerNames, hname) } // Service descriptor. g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {") g.P("ServiceName: ", strconv.Quote(fullServName), ",") g.P("HandlerType: (*", serverType, ")(nil),") g.P("Methods: []", grpcPkg, ".MethodDesc{") for i, method := range service.Method { if method.GetServerStreaming() || method.GetClientStreaming() { continue } g.P("{") g.P("MethodName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") g.P("},") } g.P("},") g.P("Streams: []", grpcPkg, ".StreamDesc{") for i, method := range service.Method { if !method.GetServerStreaming() && !method.GetClientStreaming() { continue } g.P("{") g.P("StreamName: ", strconv.Quote(method.GetName()), ",") g.P("Handler: ", handlerNames[i], ",") if method.GetServerStreaming() { g.P("ServerStreams: true,") } if method.GetClientStreaming() { g.P("ClientStreams: true,") } g.P("},") } g.P("},") g.P("}") g.P() } // generateClientSignature returns the client-side signature for a method. func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } reqArg := ", in *" + g.typeName(method.GetInputType()) if method.GetClientStreaming() { reqArg = "" } respName := "*" + g.typeName(method.GetOutputType()) if method.GetServerStreaming() || method.GetClientStreaming() { respName = servName + "_" + generator.CamelCase(origMethName) + "Client" } return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName) } func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) { sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName()) methName := generator.CamelCase(method.GetName()) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{") if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("out := new(", outType, ")") // TODO: Pass descExpr to Invoke. g.P("err := ", grpcPkg, `.Invoke(ctx, "`, sname, `", in, out, c.cc, opts...)`) g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return } streamType := unexport(servName) + methName + "Client" g.P("stream, err := ", grpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, "`, sname, `", opts...)`) g.P("if err != nil { return nil, err }") g.P("x := &", streamType, "{stream}") if !method.GetClientStreaming() { g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") } g.P("return x, nil") g.P("}") g.P() genSend := method.GetClientStreaming() genRecv := method.GetServerStreaming() genCloseAndRecv := !method.GetServerStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Client interface {") if genSend { g.P("Send(*", inType, ") error") } if genRecv { g.P("Recv() (*", outType, ", error)") } if genCloseAndRecv { g.P("CloseAndRecv() (*", outType, ", error)") } g.P(grpcPkg, ".ClientStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ClientStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", inType, ") error {") g.P("return x.ClientStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } if genCloseAndRecv { g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {") g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") g.P("m := new(", outType, ")") g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } } // generateServerSignature returns the server-side signature for a method. func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string { origMethName := method.GetName() methName := generator.CamelCase(origMethName) if reservedClientName[methName] { methName += "_" } var reqArgs []string ret := "error" if !method.GetServerStreaming() && !method.GetClientStreaming() { reqArgs = append(reqArgs, contextPkg+".Context") ret = "(*" + g.typeName(method.GetOutputType()) + ", error)" } if !method.GetClientStreaming() { reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType())) } if method.GetServerStreaming() || method.GetClientStreaming() { reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server") } return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret } func (g *grpc) generateServerMethod(servName string, method *pb.MethodDescriptorProto) string { methName := generator.CamelCase(method.GetName()) hname := fmt.Sprintf("_%s_%s_Handler", servName, methName) inType := g.typeName(method.GetInputType()) outType := g.typeName(method.GetOutputType()) if !method.GetServerStreaming() && !method.GetClientStreaming() { g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error) (interface{}, error) {") g.P("in := new(", inType, ")") g.P("if err := dec(in); err != nil { return nil, err }") g.P("out, err := srv.(", servName, "Server).", methName, "(ctx, in)") g.P("if err != nil { return nil, err }") g.P("return out, nil") g.P("}") g.P() return hname } streamType := unexport(servName) + methName + "Server" g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {") if !method.GetClientStreaming() { g.P("m := new(", inType, ")") g.P("if err := stream.RecvMsg(m); err != nil { return err }") g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})") } else { g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})") } g.P("}") g.P() genSend := method.GetServerStreaming() genSendAndClose := !method.GetServerStreaming() genRecv := method.GetClientStreaming() // Stream auxiliary types and methods. g.P("type ", servName, "_", methName, "Server interface {") if genSend { g.P("Send(*", outType, ") error") } if genSendAndClose { g.P("SendAndClose(*", outType, ") error") } if genRecv { g.P("Recv() (*", inType, ", error)") } g.P(grpcPkg, ".ServerStream") g.P("}") g.P() g.P("type ", streamType, " struct {") g.P(grpcPkg, ".ServerStream") g.P("}") g.P() if genSend { g.P("func (x *", streamType, ") Send(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genSendAndClose { g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {") g.P("return x.ServerStream.SendMsg(m)") g.P("}") g.P() } if genRecv { g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {") g.P("m := new(", inType, ")") g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") g.P("return m, nil") g.P("}") g.P() } return hname } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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 main import _ "github.com/golang/protobuf/protoc-gen-go/internal/grpc" ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/main.go ================================================ // 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. // protoc-gen-go is a plugin for the Google protocol buffer compiler to generate // Go code. Run it by building this program and putting it in your path with // the name // protoc-gen-go // That word 'go' at the end becomes part of the option string set for the // protocol compiler, so once the protocol compiler (protoc) is installed // you can run // protoc --go_out=output_directory input_directory/file.proto // to generate Go bindings for the protocol defined by file.proto. // With that input, the output will be written to // output_directory/file.pb.go // // The generated code is documented in the package comment for // the library. // // See the README and documentation for protocol buffers to learn more: // https://developers.google.com/protocol-buffers/ package main import ( "io/ioutil" "os" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/generator" ) func main() { // Begin by allocating a generator. The request and response structures are stored there // so we can do error handling easily - the response structure contains the field to // report failure. g := generator.New() data, err := ioutil.ReadAll(os.Stdin) if err != nil { g.Error(err, "reading input") } if err := proto.Unmarshal(data, g.Request); err != nil { g.Error(err, "parsing input proto") } if len(g.Request.FileToGenerate) == 0 { g.Fail("no files to generate") } g.CommandLineParameters(g.Request.GetParameter()) // Create a wrapped version of the Descriptors and EnumDescriptors that // point to the file that defines them. g.WrapTypes() g.SetPackageNames() g.BuildTypeNameMap() g.GenerateAllFiles() // Send back the results. data, err = proto.Marshal(g.Response) if err != nil { g.Error(err, "failed to marshal output proto") } _, err = os.Stdout.Write(data) if err != nil { g.Error(err, "failed to write output proto") } } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/plugin/Makefile ================================================ # 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. # Not stored here, but plugin.proto is in https://github.com/google/protobuf/ # at src/google/protobuf/compiler/plugin.proto # Also we need to fix an import. regenerate: echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION protoc --go_out=Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor:. \ -I$(HOME)/src/protobuf/src $(HOME)/src/protobuf/src/google/protobuf/compiler/plugin.proto && \ mv google/protobuf/compiler/plugin.pb.go $(GOPATH)/src/github.com/golang/protobuf/protoc-gen-go/plugin restore: cp plugin.pb.golden plugin.pb.go preserve: cp plugin.pb.go plugin.pb.golden ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden ================================================ // Code generated by protoc-gen-go. // source: google/protobuf/compiler/plugin.proto // DO NOT EDIT! package google_protobuf_compiler import proto "github.com/golang/protobuf/proto" import "math" import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor" // Reference proto and math imports to suppress error if they are not otherwise used. var _ = proto.GetString var _ = math.Inf type CodeGeneratorRequest struct { FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"` Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"` ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} } func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorRequest) ProtoMessage() {} func (this *CodeGeneratorRequest) GetParameter() string { if this != nil && this.Parameter != nil { return *this.Parameter } return "" } type CodeGeneratorResponse struct { Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"` File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} } func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorResponse) ProtoMessage() {} func (this *CodeGeneratorResponse) GetError() string { if this != nil && this.Error != nil { return *this.Error } return "" } type CodeGeneratorResponse_File struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"` Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"` XXX_unrecognized []byte `json:"-"` } func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} } func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) } func (*CodeGeneratorResponse_File) ProtoMessage() {} func (this *CodeGeneratorResponse_File) GetName() string { if this != nil && this.Name != nil { return *this.Name } return "" } func (this *CodeGeneratorResponse_File) GetInsertionPoint() string { if this != nil && this.InsertionPoint != nil { return *this.InsertionPoint } return "" } func (this *CodeGeneratorResponse_File) GetContent() string { if this != nil && this.Content != nil { return *this.Content } return "" } func init() { } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/Makefile ================================================ # 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. all: @echo run make test include ../../Make.protobuf test: golden testbuild #test: golden testbuild extension_test # ./extension_test # @echo PASS my_test/test.pb.go: my_test/test.proto protoc --go_out=Mmulti/multi1.proto=github.com/golang/protobuf/protoc-gen-go/testdata/multi:. $< golden: make -B my_test/test.pb.go sed -i '/return.*fileDescriptor/d' my_test/test.pb.go sed -i '/^var fileDescriptor/,/^}/d' my_test/test.pb.go gofmt -w my_test/test.pb.go diff -w my_test/test.pb.go my_test/test.pb.go.golden nuke: clean testbuild: regenerate go test regenerate: # Invoke protoc once to generate three independent .pb.go files in the same package. protoc --go_out=. multi/multi{1,2,3}.proto #extension_test: extension_test.$O # $(LD) -L. -o $@ $< #multi.a: multi3.pb.$O multi2.pb.$O multi1.pb.$O # rm -f multi.a # $(QUOTED_GOBIN)/gopack grc $@ $< #test.pb.go: imp.pb.go #multi1.pb.go: multi2.pb.go multi3.pb.go #main.$O: imp.pb.$O test.pb.$O multi.a #extension_test.$O: extension_base.pb.$O extension_extra.pb.$O extension_user.pb.$O ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base.proto ================================================ // 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. syntax = "proto2"; package extension_base; message BaseMessage { optional int32 height = 1; extensions 4 to 9; extensions 16 to max; } // Another message that may be extended, using message_set_wire_format. message OldStyleMessage { option message_set_wire_format = true; extensions 100 to max; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra.proto ================================================ // 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. syntax = "proto2"; package extension_extra; message ExtraMessage { optional int32 width = 1; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go ================================================ // 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. // Test that we can use protocol buffers that use extensions. package testdata /* import ( "bytes" "regexp" "testing" "github.com/golang/protobuf/proto" base "extension_base.pb" user "extension_user.pb" ) func TestSingleFieldExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(178), } // Use extension within scope of another type. vol := proto.Uint32(11) err := proto.SetExtension(bm, user.E_LoudMessage_Volume, vol) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { t.Fatal("Decoded message didn't contain extension.") } vol_out, err := proto.GetExtension(bm_new, user.E_LoudMessage_Volume) if err != nil { t.Fatal("Failed getting extension:", err) } if v := vol_out.(*uint32); *v != *vol { t.Errorf("vol_out = %v, expected %v", *v, *vol) } proto.ClearExtension(bm_new, user.E_LoudMessage_Volume) if proto.HasExtension(bm_new, user.E_LoudMessage_Volume) { t.Fatal("Failed clearing extension.") } } func TestMessageExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(179), } // Use extension that is itself a message. um := &user.UserMessage{ Name: proto.String("Dave"), Rank: proto.String("Major"), } err := proto.SetExtension(bm, user.E_LoginMessage_UserMessage, um) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { t.Fatal("Decoded message didn't contain extension.") } um_out, err := proto.GetExtension(bm_new, user.E_LoginMessage_UserMessage) if err != nil { t.Fatal("Failed getting extension:", err) } if n := um_out.(*user.UserMessage).Name; *n != *um.Name { t.Errorf("um_out.Name = %q, expected %q", *n, *um.Name) } if r := um_out.(*user.UserMessage).Rank; *r != *um.Rank { t.Errorf("um_out.Rank = %q, expected %q", *r, *um.Rank) } proto.ClearExtension(bm_new, user.E_LoginMessage_UserMessage) if proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) { t.Fatal("Failed clearing extension.") } } func TestTopLevelExtension(t *testing.T) { bm := &base.BaseMessage{ Height: proto.Int32(179), } width := proto.Int32(17) err := proto.SetExtension(bm, user.E_Width, width) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(bm) if err != nil { t.Fatal("Failed encoding message with extension:", err) } bm_new := new(base.BaseMessage) if err := proto.Unmarshal(buf, bm_new); err != nil { t.Fatal("Failed decoding message with extension:", err) } if !proto.HasExtension(bm_new, user.E_Width) { t.Fatal("Decoded message didn't contain extension.") } width_out, err := proto.GetExtension(bm_new, user.E_Width) if err != nil { t.Fatal("Failed getting extension:", err) } if w := width_out.(*int32); *w != *width { t.Errorf("width_out = %v, expected %v", *w, *width) } proto.ClearExtension(bm_new, user.E_Width) if proto.HasExtension(bm_new, user.E_Width) { t.Fatal("Failed clearing extension.") } } func TestMessageSetWireFormat(t *testing.T) { osm := new(base.OldStyleMessage) osp := &user.OldStyleParcel{ Name: proto.String("Dave"), Height: proto.Int32(178), } err := proto.SetExtension(osm, user.E_OldStyleParcel_MessageSetExtension, osp) if err != nil { t.Fatal("Failed setting extension:", err) } buf, err := proto.Marshal(osm) if err != nil { t.Fatal("Failed encoding message:", err) } // Data generated from Python implementation. expected := []byte{ 11, 16, 209, 15, 26, 9, 10, 4, 68, 97, 118, 101, 16, 178, 1, 12, } if !bytes.Equal(expected, buf) { t.Errorf("Encoding mismatch.\nwant %+v\n got %+v", expected, buf) } // Check that it is restored correctly. osm = new(base.OldStyleMessage) if err := proto.Unmarshal(buf, osm); err != nil { t.Fatal("Failed decoding message:", err) } osp_out, err := proto.GetExtension(osm, user.E_OldStyleParcel_MessageSetExtension) if err != nil { t.Fatal("Failed getting extension:", err) } osp = osp_out.(*user.OldStyleParcel) if *osp.Name != "Dave" || *osp.Height != 178 { t.Errorf("Retrieved extension from decoded message is not correct: %+v", osp) } } func main() { // simpler than rigging up gotest testing.Main(regexp.MatchString, []testing.InternalTest{ {"TestSingleFieldExtension", TestSingleFieldExtension}, {"TestMessageExtension", TestMessageExtension}, {"TestTopLevelExtension", TestTopLevelExtension}, }, []testing.InternalBenchmark{}, []testing.InternalExample{}) } */ ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user.proto ================================================ // 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. syntax = "proto2"; import "extension_base.proto"; import "extension_extra.proto"; package extension_user; message UserMessage { optional string name = 1; optional string rank = 2; } // Extend with a message extend extension_base.BaseMessage { optional UserMessage user_message = 5; } // Extend with a foreign message extend extension_base.BaseMessage { optional extension_extra.ExtraMessage extra_message = 9; } // Extend with some primitive types extend extension_base.BaseMessage { optional int32 width = 6; optional int64 area = 7; } // Extend inside the scope of another type message LoudMessage { extend extension_base.BaseMessage { optional uint32 volume = 8; } extensions 100 to max; } // Extend inside the scope of another type, using a message. message LoginMessage { extend extension_base.BaseMessage { optional UserMessage user_message = 16; } } // Extend with a repeated field extend extension_base.BaseMessage { repeated Detail detail = 17; } message Detail { optional string color = 1; } // An extension of an extension message Announcement { optional string words = 1; extend LoudMessage { optional Announcement loud_ext = 100; } } // Something that can be put in a message set. message OldStyleParcel { extend extension_base.OldStyleMessage { optional OldStyleParcel message_set_extension = 2001; } required string name = 1; optional int32 height = 2; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2015 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. syntax = "proto3"; package grpc.testing; message SimpleRequest { } message SimpleResponse { } message StreamMsg { } message StreamMsg2 { } service Test { rpc UnaryCall(SimpleRequest) returns (SimpleResponse); // This RPC streams from the server only. rpc Downstream(SimpleRequest) returns (stream StreamMsg); // This RPC streams from the client. rpc Upstream(stream StreamMsg) returns (SimpleResponse); // This one streams in both directions. rpc Bidi(stream StreamMsg) returns (stream StreamMsg2); } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.pb.go.golden ================================================ // Code generated by protoc-gen-go. // source: imp.proto // DO NOT EDIT! package imp import proto "github.com/golang/protobuf/proto" import "math" import "os" import imp1 "imp2.pb" // Reference proto & math imports to suppress error if they are not otherwise used. var _ = proto.GetString var _ = math.Inf // Types from public import imp2.proto type PubliclyImportedMessage imp1.PubliclyImportedMessage func (this *PubliclyImportedMessage) Reset() { (*imp1.PubliclyImportedMessage)(this).Reset() } func (this *PubliclyImportedMessage) String() string { return (*imp1.PubliclyImportedMessage)(this).String() } // PubliclyImportedMessage from public import imp.proto type ImportedMessage_Owner int32 const ( ImportedMessage_DAVE ImportedMessage_Owner = 1 ImportedMessage_MIKE ImportedMessage_Owner = 2 ) var ImportedMessage_Owner_name = map[int32]string{ 1: "DAVE", 2: "MIKE", } var ImportedMessage_Owner_value = map[string]int32{ "DAVE": 1, "MIKE": 2, } // NewImportedMessage_Owner is deprecated. Use x.Enum() instead. func NewImportedMessage_Owner(x ImportedMessage_Owner) *ImportedMessage_Owner { e := ImportedMessage_Owner(x) return &e } func (x ImportedMessage_Owner) Enum() *ImportedMessage_Owner { p := new(ImportedMessage_Owner) *p = x return p } func (x ImportedMessage_Owner) String() string { return proto.EnumName(ImportedMessage_Owner_name, int32(x)) } type ImportedMessage struct { Field *int64 `protobuf:"varint,1,req,name=field" json:"field,omitempty"` XXX_extensions map[int32][]byte `json:",omitempty"` XXX_unrecognized []byte `json:",omitempty"` } func (this *ImportedMessage) Reset() { *this = ImportedMessage{} } func (this *ImportedMessage) String() string { return proto.CompactTextString(this) } var extRange_ImportedMessage = []proto.ExtensionRange{ proto.ExtensionRange{90, 100}, } func (*ImportedMessage) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ImportedMessage } func (this *ImportedMessage) ExtensionMap() map[int32][]byte { if this.XXX_extensions == nil { this.XXX_extensions = make(map[int32][]byte) } return this.XXX_extensions } type ImportedExtendable struct { XXX_extensions map[int32][]byte `json:",omitempty"` XXX_unrecognized []byte `json:",omitempty"` } func (this *ImportedExtendable) Reset() { *this = ImportedExtendable{} } func (this *ImportedExtendable) String() string { return proto.CompactTextString(this) } func (this *ImportedExtendable) Marshal() ([]byte, error) { return proto.MarshalMessageSet(this.ExtensionMap()) } func (this *ImportedExtendable) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, this.ExtensionMap()) } // ensure ImportedExtendable satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*ImportedExtendable)(nil) var _ proto.Unmarshaler = (*ImportedExtendable)(nil) var extRange_ImportedExtendable = []proto.ExtensionRange{ proto.ExtensionRange{100, 536870911}, } func (*ImportedExtendable) ExtensionRangeArray() []proto.ExtensionRange { return extRange_ImportedExtendable } func (this *ImportedExtendable) ExtensionMap() map[int32][]byte { if this.XXX_extensions == nil { this.XXX_extensions = make(map[int32][]byte) } return this.XXX_extensions } func init() { proto.RegisterEnum("imp.ImportedMessage_Owner", ImportedMessage_Owner_name, ImportedMessage_Owner_value) } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.proto ================================================ // 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. syntax = "proto2"; package imp; import "imp2.proto"; import "imp3.proto"; message ImportedMessage { required int64 field = 1; // The forwarded getters for these fields are fiddly to get right. optional ImportedMessage2 local_msg = 2; optional ForeignImportedMessage foreign_msg = 3; // in imp3.proto optional Owner enum_field = 4; oneof union { int32 state = 9; } repeated string name = 5; repeated Owner boss = 6; repeated ImportedMessage2 memo = 7; map msg_map = 8; enum Owner { DAVE = 1; MIKE = 2; } extensions 90 to 100; } message ImportedMessage2 { } message ImportedExtendable { option message_set_wire_format = true; extensions 100 to max; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp2.proto ================================================ // 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. syntax = "proto2"; package imp; message PubliclyImportedMessage { optional int64 field = 1; } enum PubliclyImportedEnum { GLASSES = 1; HAIR = 2; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp3.proto ================================================ // 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. syntax = "proto2"; package imp; message ForeignImportedMessage { optional string tuber = 1; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go ================================================ // 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. // A simple binary to link together the protocol buffers in this test. package testdata import ( "testing" mytestpb "./my_test" multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi" ) func TestLink(t *testing.T) { _ = &multipb.Multi1{} _ = &mytestpb.Request{} } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto ================================================ // 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. syntax = "proto2"; import "multi/multi2.proto"; import "multi/multi3.proto"; package multitest; message Multi1 { required Multi2 multi2 = 1; optional Multi2.Color color = 2; optional Multi3.HatType hat_type = 3; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto ================================================ // 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. syntax = "proto2"; package multitest; message Multi2 { required int32 required_value = 1; enum Color { BLUE = 1; GREEN = 2; RED = 3; }; optional Color color = 2; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto ================================================ // 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. syntax = "proto2"; package multitest; message Multi3 { enum HatType { FEDORA = 1; FEZ = 2; }; optional HatType hat_type = 1; } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden ================================================ // Code generated by protoc-gen-go. // source: my_test/test.proto // DO NOT EDIT! /* Package my_test is a generated protocol buffer package. This package holds interesting messages. It is generated from these files: my_test/test.proto It has these top-level messages: Request Reply OtherBase ReplyExtensions OtherReplyExtensions OldReply Communique */ package my_test import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi" // 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.ProtoPackageIsVersion1 type HatType int32 const ( // deliberately skipping 0 HatType_FEDORA HatType = 1 HatType_FEZ HatType = 2 ) var HatType_name = map[int32]string{ 1: "FEDORA", 2: "FEZ", } var HatType_value = map[string]int32{ "FEDORA": 1, "FEZ": 2, } func (x HatType) Enum() *HatType { p := new(HatType) *p = x return p } func (x HatType) String() string { return proto.EnumName(HatType_name, int32(x)) } func (x *HatType) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType") if err != nil { return err } *x = HatType(value) return nil } // This enum represents days of the week. type Days int32 const ( Days_MONDAY Days = 1 Days_TUESDAY Days = 2 Days_LUNDI Days = 1 ) var Days_name = map[int32]string{ 1: "MONDAY", 2: "TUESDAY", // Duplicate value: 1: "LUNDI", } var Days_value = map[string]int32{ "MONDAY": 1, "TUESDAY": 2, "LUNDI": 1, } func (x Days) Enum() *Days { p := new(Days) *p = x return p } func (x Days) String() string { return proto.EnumName(Days_name, int32(x)) } func (x *Days) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days") if err != nil { return err } *x = Days(value) return nil } type Request_Color int32 const ( Request_RED Request_Color = 0 Request_GREEN Request_Color = 1 Request_BLUE Request_Color = 2 ) var Request_Color_name = map[int32]string{ 0: "RED", 1: "GREEN", 2: "BLUE", } var Request_Color_value = map[string]int32{ "RED": 0, "GREEN": 1, "BLUE": 2, } func (x Request_Color) Enum() *Request_Color { p := new(Request_Color) *p = x return p } func (x Request_Color) String() string { return proto.EnumName(Request_Color_name, int32(x)) } func (x *Request_Color) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color") if err != nil { return err } *x = Request_Color(value) return nil } type Reply_Entry_Game int32 const ( Reply_Entry_FOOTBALL Reply_Entry_Game = 1 Reply_Entry_TENNIS Reply_Entry_Game = 2 ) var Reply_Entry_Game_name = map[int32]string{ 1: "FOOTBALL", 2: "TENNIS", } var Reply_Entry_Game_value = map[string]int32{ "FOOTBALL": 1, "TENNIS": 2, } func (x Reply_Entry_Game) Enum() *Reply_Entry_Game { p := new(Reply_Entry_Game) *p = x return p } func (x Reply_Entry_Game) String() string { return proto.EnumName(Reply_Entry_Game_name, int32(x)) } func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error { value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game") if err != nil { return err } *x = Reply_Entry_Game(value) return nil } // This is a message that might be sent somewhere. type Request struct { Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"` // optional imp.ImportedMessage imported_message = 2; Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"` Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"` // optional imp.ImportedMessage.Owner owner = 6; Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"` Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"` // This is a map field. It will generate map[int32]string. NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // This is a map field whose value type is a message. MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"` // This field should not conflict with any getters. GetKey_ *string `protobuf:"bytes,16,opt,name=get_key" json:"get_key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request) Reset() { *m = Request{} } func (m *Request) String() string { return proto.CompactTextString(m) } func (*Request) ProtoMessage() {} const Default_Request_Hat HatType = HatType_FEDORA var Default_Request_Deadline float32 = float32(math.Inf(1)) func (m *Request) GetKey() []int64 { if m != nil { return m.Key } return nil } func (m *Request) GetHue() Request_Color { if m != nil && m.Hue != nil { return *m.Hue } return Request_RED } func (m *Request) GetHat() HatType { if m != nil && m.Hat != nil { return *m.Hat } return Default_Request_Hat } func (m *Request) GetDeadline() float32 { if m != nil && m.Deadline != nil { return *m.Deadline } return Default_Request_Deadline } func (m *Request) GetSomegroup() *Request_SomeGroup { if m != nil { return m.Somegroup } return nil } func (m *Request) GetNameMapping() map[int32]string { if m != nil { return m.NameMapping } return nil } func (m *Request) GetMsgMapping() map[int64]*Reply { if m != nil { return m.MsgMapping } return nil } func (m *Request) GetReset_() int32 { if m != nil && m.Reset_ != nil { return *m.Reset_ } return 0 } func (m *Request) GetGetKey_() string { if m != nil && m.GetKey_ != nil { return *m.GetKey_ } return "" } type Request_SomeGroup struct { GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} } func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Request_SomeGroup) ProtoMessage() {} func (m *Request_SomeGroup) GetGroupField() int32 { if m != nil && m.GroupField != nil { return *m.GroupField } return 0 } type Reply struct { Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"` CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys" json:"compact_keys,omitempty"` XXX_extensions map[int32]proto.Extension `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *Reply) Reset() { *m = Reply{} } func (m *Reply) String() string { return proto.CompactTextString(m) } func (*Reply) ProtoMessage() {} var extRange_Reply = []proto.ExtensionRange{ {100, 536870911}, } func (*Reply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_Reply } func (m *Reply) ExtensionMap() map[int32]proto.Extension { if m.XXX_extensions == nil { m.XXX_extensions = make(map[int32]proto.Extension) } return m.XXX_extensions } func (m *Reply) GetFound() []*Reply_Entry { if m != nil { return m.Found } return nil } func (m *Reply) GetCompactKeys() []int32 { if m != nil { return m.CompactKeys } return nil } type Reply_Entry struct { KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng" json:"key_that_needs_1234camel_CasIng,omitempty"` Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"` XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2" json:"_my_field_name_2,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Reply_Entry) Reset() { *m = Reply_Entry{} } func (m *Reply_Entry) String() string { return proto.CompactTextString(m) } func (*Reply_Entry) ProtoMessage() {} const Default_Reply_Entry_Value int64 = 7 func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 { if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil { return *m.KeyThatNeeds_1234Camel_CasIng } return 0 } func (m *Reply_Entry) GetValue() int64 { if m != nil && m.Value != nil { return *m.Value } return Default_Reply_Entry_Value } func (m *Reply_Entry) GetXMyFieldName_2() int64 { if m != nil && m.XMyFieldName_2 != nil { return *m.XMyFieldName_2 } return 0 } type OtherBase struct { Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` XXX_extensions map[int32]proto.Extension `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OtherBase) Reset() { *m = OtherBase{} } func (m *OtherBase) String() string { return proto.CompactTextString(m) } func (*OtherBase) ProtoMessage() {} var extRange_OtherBase = []proto.ExtensionRange{ {100, 536870911}, } func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OtherBase } func (m *OtherBase) ExtensionMap() map[int32]proto.Extension { if m.XXX_extensions == nil { m.XXX_extensions = make(map[int32]proto.Extension) } return m.XXX_extensions } func (m *OtherBase) GetName() string { if m != nil && m.Name != nil { return *m.Name } return "" } type ReplyExtensions struct { XXX_unrecognized []byte `json:"-"` } func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} } func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) } func (*ReplyExtensions) ProtoMessage() {} var E_ReplyExtensions_Time = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*float64)(nil), Field: 101, Name: "my.test.ReplyExtensions.time", Tag: "fixed64,101,opt,name=time", } var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 105, Name: "my.test.ReplyExtensions.carrot", Tag: "bytes,105,opt,name=carrot", } var E_ReplyExtensions_Donut = &proto.ExtensionDesc{ ExtendedType: (*OtherBase)(nil), ExtensionType: (*ReplyExtensions)(nil), Field: 101, Name: "my.test.ReplyExtensions.donut", Tag: "bytes,101,opt,name=donut", } type OtherReplyExtensions struct { Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} } func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) } func (*OtherReplyExtensions) ProtoMessage() {} func (m *OtherReplyExtensions) GetKey() int32 { if m != nil && m.Key != nil { return *m.Key } return 0 } type OldReply struct { XXX_extensions map[int32]proto.Extension `json:"-"` XXX_unrecognized []byte `json:"-"` } func (m *OldReply) Reset() { *m = OldReply{} } func (m *OldReply) String() string { return proto.CompactTextString(m) } func (*OldReply) ProtoMessage() {} func (m *OldReply) Marshal() ([]byte, error) { return proto.MarshalMessageSet(m.ExtensionMap()) } func (m *OldReply) Unmarshal(buf []byte) error { return proto.UnmarshalMessageSet(buf, m.ExtensionMap()) } func (m *OldReply) MarshalJSON() ([]byte, error) { return proto.MarshalMessageSetJSON(m.XXX_extensions) } func (m *OldReply) UnmarshalJSON(buf []byte) error { return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions) } // ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler var _ proto.Marshaler = (*OldReply)(nil) var _ proto.Unmarshaler = (*OldReply)(nil) var extRange_OldReply = []proto.ExtensionRange{ {100, 2147483646}, } func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange { return extRange_OldReply } func (m *OldReply) ExtensionMap() map[int32]proto.Extension { if m.XXX_extensions == nil { m.XXX_extensions = make(map[int32]proto.Extension) } return m.XXX_extensions } type Communique struct { MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry" json:"make_me_cry,omitempty"` // This is a oneof, called "union". // // Types that are valid to be assigned to Union: // *Communique_Number // *Communique_Name // *Communique_Data // *Communique_TempC // *Communique_Height // *Communique_Today // *Communique_Maybe // *Communique_Delta_ // *Communique_Msg // *Communique_Somegroup Union isCommunique_Union `protobuf_oneof:"union"` XXX_unrecognized []byte `json:"-"` } func (m *Communique) Reset() { *m = Communique{} } func (m *Communique) String() string { return proto.CompactTextString(m) } func (*Communique) ProtoMessage() {} type isCommunique_Union interface { isCommunique_Union() } type Communique_Number struct { Number int32 `protobuf:"varint,5,opt,name=number,oneof"` } type Communique_Name struct { Name string `protobuf:"bytes,6,opt,name=name,oneof"` } type Communique_Data struct { Data []byte `protobuf:"bytes,7,opt,name=data,oneof"` } type Communique_TempC struct { TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,oneof"` } type Communique_Height struct { Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"` } type Communique_Today struct { Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"` } type Communique_Maybe struct { Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"` } type Communique_Delta_ struct { Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"` } type Communique_Msg struct { Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"` } type Communique_Somegroup struct { Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,oneof"` } func (*Communique_Number) isCommunique_Union() {} func (*Communique_Name) isCommunique_Union() {} func (*Communique_Data) isCommunique_Union() {} func (*Communique_TempC) isCommunique_Union() {} func (*Communique_Height) isCommunique_Union() {} func (*Communique_Today) isCommunique_Union() {} func (*Communique_Maybe) isCommunique_Union() {} func (*Communique_Delta_) isCommunique_Union() {} func (*Communique_Msg) isCommunique_Union() {} func (*Communique_Somegroup) isCommunique_Union() {} func (m *Communique) GetUnion() isCommunique_Union { if m != nil { return m.Union } return nil } func (m *Communique) GetMakeMeCry() bool { if m != nil && m.MakeMeCry != nil { return *m.MakeMeCry } return false } func (m *Communique) GetNumber() int32 { if x, ok := m.GetUnion().(*Communique_Number); ok { return x.Number } return 0 } func (m *Communique) GetName() string { if x, ok := m.GetUnion().(*Communique_Name); ok { return x.Name } return "" } func (m *Communique) GetData() []byte { if x, ok := m.GetUnion().(*Communique_Data); ok { return x.Data } return nil } func (m *Communique) GetTempC() float64 { if x, ok := m.GetUnion().(*Communique_TempC); ok { return x.TempC } return 0 } func (m *Communique) GetHeight() float32 { if x, ok := m.GetUnion().(*Communique_Height); ok { return x.Height } return 0 } func (m *Communique) GetToday() Days { if x, ok := m.GetUnion().(*Communique_Today); ok { return x.Today } return Days_MONDAY } func (m *Communique) GetMaybe() bool { if x, ok := m.GetUnion().(*Communique_Maybe); ok { return x.Maybe } return false } func (m *Communique) GetDelta() int32 { if x, ok := m.GetUnion().(*Communique_Delta_); ok { return x.Delta } return 0 } func (m *Communique) GetMsg() *Reply { if x, ok := m.GetUnion().(*Communique_Msg); ok { return x.Msg } return nil } func (m *Communique) GetSomegroup() *Communique_SomeGroup { if x, ok := m.GetUnion().(*Communique_Somegroup); ok { return x.Somegroup } return nil } // XXX_OneofFuncs is for the internal use of the proto package. func (*Communique) 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 _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{ (*Communique_Number)(nil), (*Communique_Name)(nil), (*Communique_Data)(nil), (*Communique_TempC)(nil), (*Communique_Height)(nil), (*Communique_Today)(nil), (*Communique_Maybe)(nil), (*Communique_Delta_)(nil), (*Communique_Msg)(nil), (*Communique_Somegroup)(nil), } } func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: b.EncodeVarint(5<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Number)) case *Communique_Name: b.EncodeVarint(6<<3 | proto.WireBytes) b.EncodeStringBytes(x.Name) case *Communique_Data: b.EncodeVarint(7<<3 | proto.WireBytes) b.EncodeRawBytes(x.Data) case *Communique_TempC: b.EncodeVarint(8<<3 | proto.WireFixed64) b.EncodeFixed64(math.Float64bits(x.TempC)) case *Communique_Height: b.EncodeVarint(9<<3 | proto.WireFixed32) b.EncodeFixed32(uint64(math.Float32bits(x.Height))) case *Communique_Today: b.EncodeVarint(10<<3 | proto.WireVarint) b.EncodeVarint(uint64(x.Today)) case *Communique_Maybe: t := uint64(0) if x.Maybe { t = 1 } b.EncodeVarint(11<<3 | proto.WireVarint) b.EncodeVarint(t) case *Communique_Delta_: b.EncodeVarint(12<<3 | proto.WireVarint) b.EncodeZigzag32(uint64(x.Delta)) case *Communique_Msg: b.EncodeVarint(13<<3 | proto.WireBytes) if err := b.EncodeMessage(x.Msg); err != nil { return err } case *Communique_Somegroup: b.EncodeVarint(14<<3 | proto.WireStartGroup) if err := b.Marshal(x.Somegroup); err != nil { return err } b.EncodeVarint(14<<3 | proto.WireEndGroup) case nil: default: return fmt.Errorf("Communique.Union has unexpected type %T", x) } return nil } func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) { m := msg.(*Communique) switch tag { case 5: // union.number if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Number{int32(x)} return true, err case 6: // union.name if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeStringBytes() m.Union = &Communique_Name{x} return true, err case 7: // union.data if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } x, err := b.DecodeRawBytes(true) m.Union = &Communique_Data{x} return true, err case 8: // union.temp_c if wire != proto.WireFixed64 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed64() m.Union = &Communique_TempC{math.Float64frombits(x)} return true, err case 9: // union.height if wire != proto.WireFixed32 { return true, proto.ErrInternalBadWireType } x, err := b.DecodeFixed32() m.Union = &Communique_Height{math.Float32frombits(uint32(x))} return true, err case 10: // union.today if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Today{Days(x)} return true, err case 11: // union.maybe if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeVarint() m.Union = &Communique_Maybe{x != 0} return true, err case 12: // union.delta if wire != proto.WireVarint { return true, proto.ErrInternalBadWireType } x, err := b.DecodeZigzag32() m.Union = &Communique_Delta_{int32(x)} return true, err case 13: // union.msg if wire != proto.WireBytes { return true, proto.ErrInternalBadWireType } msg := new(Reply) err := b.DecodeMessage(msg) m.Union = &Communique_Msg{msg} return true, err case 14: // union.somegroup if wire != proto.WireStartGroup { return true, proto.ErrInternalBadWireType } msg := new(Communique_SomeGroup) err := b.DecodeGroup(msg) m.Union = &Communique_Somegroup{msg} return true, err default: return false, nil } } func _Communique_OneofSizer(msg proto.Message) (n int) { m := msg.(*Communique) // union switch x := m.Union.(type) { case *Communique_Number: n += proto.SizeVarint(5<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Number)) case *Communique_Name: n += proto.SizeVarint(6<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Name))) n += len(x.Name) case *Communique_Data: n += proto.SizeVarint(7<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(len(x.Data))) n += len(x.Data) case *Communique_TempC: n += proto.SizeVarint(8<<3 | proto.WireFixed64) n += 8 case *Communique_Height: n += proto.SizeVarint(9<<3 | proto.WireFixed32) n += 4 case *Communique_Today: n += proto.SizeVarint(10<<3 | proto.WireVarint) n += proto.SizeVarint(uint64(x.Today)) case *Communique_Maybe: n += proto.SizeVarint(11<<3 | proto.WireVarint) n += 1 case *Communique_Delta_: n += proto.SizeVarint(12<<3 | proto.WireVarint) n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31)))) case *Communique_Msg: s := proto.Size(x.Msg) n += proto.SizeVarint(13<<3 | proto.WireBytes) n += proto.SizeVarint(uint64(s)) n += s case *Communique_Somegroup: n += proto.SizeVarint(14<<3 | proto.WireStartGroup) n += proto.Size(x.Somegroup) n += proto.SizeVarint(14<<3 | proto.WireEndGroup) case nil: default: panic(fmt.Sprintf("proto: unexpected type %T in oneof", x)) } return n } type Communique_SomeGroup struct { Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"` XXX_unrecognized []byte `json:"-"` } func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} } func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) } func (*Communique_SomeGroup) ProtoMessage() {} func (m *Communique_SomeGroup) GetMember() string { if m != nil && m.Member != nil { return *m.Member } return "" } type Communique_Delta struct { XXX_unrecognized []byte `json:"-"` } func (m *Communique_Delta) Reset() { *m = Communique_Delta{} } func (m *Communique_Delta) String() string { return proto.CompactTextString(m) } func (*Communique_Delta) ProtoMessage() {} var E_Tag = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*string)(nil), Field: 103, Name: "my.test.tag", Tag: "bytes,103,opt,name=tag", } var E_Donut = &proto.ExtensionDesc{ ExtendedType: (*Reply)(nil), ExtensionType: (*OtherReplyExtensions)(nil), Field: 106, Name: "my.test.donut", Tag: "bytes,106,opt,name=donut", } func init() { proto.RegisterType((*Request)(nil), "my.test.Request") proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup") proto.RegisterType((*Reply)(nil), "my.test.Reply") proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry") proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase") proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions") proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions") proto.RegisterType((*OldReply)(nil), "my.test.OldReply") proto.RegisterType((*Communique)(nil), "my.test.Communique") proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup") proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta") proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value) proto.RegisterEnum("my.test.Days", Days_name, Days_value) proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value) proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value) proto.RegisterExtension(E_ReplyExtensions_Time) proto.RegisterExtension(E_ReplyExtensions_Carrot) proto.RegisterExtension(E_ReplyExtensions_Donut) proto.RegisterExtension(E_Tag) proto.RegisterExtension(E_Donut) } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto ================================================ // 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. syntax = "proto2"; // This package holds interesting messages. package my.test; // dotted package name //import "imp.proto"; import "multi/multi1.proto"; // unused import enum HatType { // deliberately skipping 0 FEDORA = 1; FEZ = 2; } // This enum represents days of the week. enum Days { option allow_alias = true; MONDAY = 1; TUESDAY = 2; LUNDI = 1; // same value as MONDAY } // This is a message that might be sent somewhere. message Request { enum Color { RED = 0; GREEN = 1; BLUE = 2; } repeated int64 key = 1; // optional imp.ImportedMessage imported_message = 2; optional Color hue = 3; // no default optional HatType hat = 4 [default=FEDORA]; // optional imp.ImportedMessage.Owner owner = 6; optional float deadline = 7 [default=inf]; optional group SomeGroup = 8 { optional int32 group_field = 9; } // These foreign types are in imp2.proto, // which is publicly imported by imp.proto. // optional imp.PubliclyImportedMessage pub = 10; // optional imp.PubliclyImportedEnum pub_enum = 13 [default=HAIR]; // This is a map field. It will generate map[int32]string. map name_mapping = 14; // This is a map field whose value type is a message. map msg_mapping = 15; optional int32 reset = 12; // This field should not conflict with any getters. optional string get_key = 16; } message Reply { message Entry { required int64 key_that_needs_1234camel_CasIng = 1; optional int64 value = 2 [default=7]; optional int64 _my_field_name_2 = 3; enum Game { FOOTBALL = 1; TENNIS = 2; } } repeated Entry found = 1; repeated int32 compact_keys = 2 [packed=true]; extensions 100 to max; } message OtherBase { optional string name = 1; extensions 100 to max; } message ReplyExtensions { extend Reply { optional double time = 101; optional ReplyExtensions carrot = 105; } extend OtherBase { optional ReplyExtensions donut = 101; } } message OtherReplyExtensions { optional int32 key = 1; } // top-level extension extend Reply { optional string tag = 103; optional OtherReplyExtensions donut = 106; // optional imp.ImportedMessage elephant = 107; // extend with message from another file. } message OldReply { // Extensions will be encoded in MessageSet wire format. option message_set_wire_format = true; extensions 100 to max; } message Communique { optional bool make_me_cry = 1; // This is a oneof, called "union". oneof union { int32 number = 5; string name = 6; bytes data = 7; double temp_c = 8; float height = 9; Days today = 10; bool maybe = 11; sint32 delta = 12; // name will conflict with Delta below Reply msg = 13; group SomeGroup = 14 { optional string member = 15; } } message Delta {} } ================================================ FILE: vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3.proto ================================================ // Go support for Protocol Buffers - Google's data interchange format // // Copyright 2014 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. syntax = "proto3"; package proto3; message Request { enum Flavour { SWEET = 0; SOUR = 1; UMAMI = 2; GOPHERLICIOUS = 3; } string name = 1; repeated int64 key = 2; Flavour taste = 3; Book book = 4; } message Book { string title = 1; bytes raw_data = 2; } ================================================ FILE: vendor/github.com/google/gofuzz/.travis.yml ================================================ language: go go: - 1.4 - 1.3 - 1.2 - tip install: - if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi script: - go test -cover ================================================ FILE: vendor/github.com/google/gofuzz/CONTRIBUTING.md ================================================ # How to contribute # We'd love to accept your patches and contributions to this project. There are a just a few small guidelines you need to follow. ## Contributor License Agreement ## Contributions to any Google project must be accompanied by a Contributor License Agreement. This is not a copyright **assignment**, it simply gives Google permission to use and redistribute your contributions as part of the project. * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA][]. * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA][]. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. [individual CLA]: https://developers.google.com/open-source/cla/individual [corporate CLA]: https://developers.google.com/open-source/cla/corporate ## Submitting a patch ## 1. It's generally best to start by opening a new issue describing the bug or feature you're intending to fix. Even if you think it's relatively minor, it's helpful to know what people are working on. Mention in the initial issue that you are planning to work on that bug or feature so that it can be assigned to you. 1. Follow the normal process of [forking][] the project, and setup a new branch to work in. It's important that each group of changes be done in separate branches in order to ensure that a pull request only includes the commits related to that bug or feature. 1. Go makes it very simple to ensure properly formatted code, so always run `go fmt` on your code before committing it. You should also run [golint][] over your code. As noted in the [golint readme][], it's not strictly necessary that your code be completely "lint-free", but this will help you find common style issues. 1. Any significant changes should almost always be accompanied by tests. The project already has good test coverage, so look at some of the existing tests if you're unsure how to go about it. [gocov][] and [gocov-html][] are invaluable tools for seeing which parts of your code aren't being exercised by your tests. 1. Do your best to have [well-formed commit messages][] for each change. This provides consistency throughout the project, and ensures that commit messages are able to be formatted properly by various git tools. 1. Finally, push the commits to your fork and submit a [pull request][]. [forking]: https://help.github.com/articles/fork-a-repo [golint]: https://github.com/golang/lint [golint readme]: https://github.com/golang/lint/blob/master/README [gocov]: https://github.com/axw/gocov [gocov-html]: https://github.com/matm/gocov-html [well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html [squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits [pull request]: https://help.github.com/articles/creating-a-pull-request ================================================ FILE: vendor/github.com/google/gofuzz/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/google/gofuzz/README.md ================================================ gofuzz ====== gofuzz is a library for populating go objects with random values. [![GoDoc](https://godoc.org/github.com/google/gofuzz?status.png)](https://godoc.org/github.com/google/gofuzz) [![Travis](https://travis-ci.org/google/gofuzz.svg?branch=master)](https://travis-ci.org/google/gofuzz) This is useful for testing: * Do your project's objects really serialize/unserialize correctly in all cases? * Is there an incorrectly formatted object that will cause your project to panic? Import with ```import "github.com/google/gofuzz"``` You can use it on single variables: ``` f := fuzz.New() var myInt int f.Fuzz(&myInt) // myInt gets a random value. ``` You can use it on maps: ``` f := fuzz.New().NilChance(0).NumElements(1, 1) var myMap map[ComplexKeyType]string f.Fuzz(&myMap) // myMap will have exactly one element. ``` Customize the chance of getting a nil pointer: ``` f := fuzz.New().NilChance(.5) var fancyStruct struct { A, B, C, D *string } f.Fuzz(&fancyStruct) // About half the pointers should be set. ``` You can even customize the randomization completely if needed: ``` type MyEnum string const ( A MyEnum = "A" B MyEnum = "B" ) type MyInfo struct { Type MyEnum AInfo *string BInfo *string } f := fuzz.New().NilChance(0).Funcs( func(e *MyInfo, c fuzz.Continue) { switch c.Intn(2) { case 0: e.Type = A c.Fuzz(&e.AInfo) case 1: e.Type = B c.Fuzz(&e.BInfo) } }, ) var myObject MyInfo f.Fuzz(&myObject) // Type will correspond to whether A or B info is set. ``` See more examples in ```example_test.go```. Happy testing! ================================================ FILE: vendor/github.com/google/gofuzz/doc.go ================================================ /* 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 fuzz is a library for populating go objects with random values. package fuzz ================================================ FILE: vendor/github.com/google/gofuzz/example_test.go ================================================ /* 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 fuzz_test import ( "encoding/json" "fmt" "math/rand" "github.com/google/gofuzz" ) func ExampleSimple() { type MyType struct { A string B string C int D struct { E float64 } } f := fuzz.New() object := MyType{} uniqueObjects := map[MyType]int{} for i := 0; i < 1000; i++ { f.Fuzz(&object) uniqueObjects[object]++ } fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) // Output: // Got 1000 unique objects. } func ExampleCustom() { type MyType struct { A int B string } counter := 0 f := fuzz.New().Funcs( func(i *int, c fuzz.Continue) { *i = counter counter++ }, ) object := MyType{} uniqueObjects := map[MyType]int{} for i := 0; i < 100; i++ { f.Fuzz(&object) if object.A != i { fmt.Printf("Unexpected value: %#v\n", object) } uniqueObjects[object]++ } fmt.Printf("Got %v unique objects.\n", len(uniqueObjects)) // Output: // Got 100 unique objects. } func ExampleComplex() { type OtherType struct { A string B string } type MyType struct { Pointer *OtherType Map map[string]OtherType PointerMap *map[string]OtherType Slice []OtherType SlicePointer []*OtherType PointerSlicePointer *[]*OtherType } f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs( func(o *OtherType, c fuzz.Continue) { o.A = "Foo" o.B = "Bar" }, func(op **OtherType, c fuzz.Continue) { *op = &OtherType{"A", "B"} }, func(m map[string]OtherType, c fuzz.Continue) { m["Works Because"] = OtherType{ "Fuzzer", "Preallocated", } }, ) object := MyType{} f.Fuzz(&object) bytes, err := json.MarshalIndent(&object, "", " ") if err != nil { fmt.Printf("error: %v\n", err) } fmt.Printf("%s\n", string(bytes)) // Output: // { // "Pointer": { // "A": "A", // "B": "B" // }, // "Map": { // "Works Because": { // "A": "Fuzzer", // "B": "Preallocated" // } // }, // "PointerMap": { // "Works Because": { // "A": "Fuzzer", // "B": "Preallocated" // } // }, // "Slice": [ // { // "A": "Foo", // "B": "Bar" // } // ], // "SlicePointer": [ // { // "A": "A", // "B": "B" // } // ], // "PointerSlicePointer": [ // { // "A": "A", // "B": "B" // } // ] // } } func ExampleMap() { f := fuzz.New().NilChance(0).NumElements(1, 1) var myMap map[struct{ A, B, C int }]string f.Fuzz(&myMap) fmt.Printf("myMap has %v element(s).\n", len(myMap)) // Output: // myMap has 1 element(s). } func ExampleSingle() { f := fuzz.New() var i int f.Fuzz(&i) // Technically, we'd expect this to fail one out of 2 billion attempts... fmt.Printf("(i == 0) == %v", i == 0) // Output: // (i == 0) == false } func ExampleEnum() { type MyEnum string const ( A MyEnum = "A" B MyEnum = "B" ) type MyInfo struct { Type MyEnum AInfo *string BInfo *string } f := fuzz.New().NilChance(0).Funcs( func(e *MyInfo, c fuzz.Continue) { // Note c's embedded Rand allows for direct use. // We could also use c.RandBool() here. switch c.Intn(2) { case 0: e.Type = A c.Fuzz(&e.AInfo) case 1: e.Type = B c.Fuzz(&e.BInfo) } }, ) for i := 0; i < 100; i++ { var myObject MyInfo f.Fuzz(&myObject) switch myObject.Type { case A: if myObject.AInfo == nil { fmt.Println("AInfo should have been set!") } if myObject.BInfo != nil { fmt.Println("BInfo should NOT have been set!") } case B: if myObject.BInfo == nil { fmt.Println("BInfo should have been set!") } if myObject.AInfo != nil { fmt.Println("AInfo should NOT have been set!") } default: fmt.Println("Invalid enum value!") } } // Output: } ================================================ FILE: vendor/github.com/google/gofuzz/fuzz.go ================================================ /* 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 fuzz import ( "fmt" "math/rand" "reflect" "time" ) // fuzzFuncMap is a map from a type to a fuzzFunc that handles that type. type fuzzFuncMap map[reflect.Type]reflect.Value // Fuzzer knows how to fill any object with random fields. type Fuzzer struct { fuzzFuncs fuzzFuncMap defaultFuzzFuncs fuzzFuncMap r *rand.Rand nilChance float64 minElements int maxElements int } // New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs, // RandSource, NilChance, or NumElements in any order. func New() *Fuzzer { f := &Fuzzer{ defaultFuzzFuncs: fuzzFuncMap{ reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime), }, fuzzFuncs: fuzzFuncMap{}, r: rand.New(rand.NewSource(time.Now().UnixNano())), nilChance: .2, minElements: 1, maxElements: 10, } return f } // Funcs adds each entry in fuzzFuncs as a custom fuzzing function. // // Each entry in fuzzFuncs must be a function taking two parameters. // The first parameter must be a pointer or map. It is the variable that // function will fill with random data. The second parameter must be a // fuzz.Continue, which will provide a source of randomness and a way // to automatically continue fuzzing smaller pieces of the first parameter. // // These functions are called sensibly, e.g., if you wanted custom string // fuzzing, the function `func(s *string, c fuzz.Continue)` would get // called and passed the address of strings. Maps and pointers will always // be made/new'd for you, ignoring the NilChange option. For slices, it // doesn't make much sense to pre-create them--Fuzzer doesn't know how // long you want your slice--so take a pointer to a slice, and make it // yourself. (If you don't want your map/pointer type pre-made, take a // pointer to it, and make it yourself.) See the examples for a range of // custom functions. func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer { for i := range fuzzFuncs { v := reflect.ValueOf(fuzzFuncs[i]) if v.Kind() != reflect.Func { panic("Need only funcs!") } t := v.Type() if t.NumIn() != 2 || t.NumOut() != 0 { panic("Need 2 in and 0 out params!") } argT := t.In(0) switch argT.Kind() { case reflect.Ptr, reflect.Map: default: panic("fuzzFunc must take pointer or map type") } if t.In(1) != reflect.TypeOf(Continue{}) { panic("fuzzFunc's second parameter must be type fuzz.Continue") } f.fuzzFuncs[argT] = v } return f } // RandSource causes f to get values from the given source of randomness. // Use if you want deterministic fuzzing. func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer { f.r = rand.New(s) return f } // NilChance sets the probability of creating a nil pointer, map, or slice to // 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive. func (f *Fuzzer) NilChance(p float64) *Fuzzer { if p < 0 || p > 1 { panic("p should be between 0 and 1, inclusive.") } f.nilChance = p return f } // NumElements sets the minimum and maximum number of elements that will be // added to a non-nil map or slice. func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer { if atLeast > atMost { panic("atLeast must be <= atMost") } if atLeast < 0 { panic("atLeast must be >= 0") } f.minElements = atLeast f.maxElements = atMost return f } func (f *Fuzzer) genElementCount() int { if f.minElements == f.maxElements { return f.minElements } return f.minElements + f.r.Intn(f.maxElements-f.minElements) } func (f *Fuzzer) genShouldFill() bool { return f.r.Float64() > f.nilChance } // Fuzz recursively fills all of obj's fields with something random. First // this tries to find a custom fuzz function (see Funcs). If there is no // custom function this tests whether the object implements fuzz.Interface and, // if so, calls Fuzz on it to fuzz itself. If that fails, this will see if // there is a default fuzz function provided by this package. If all of that // fails, this will generate random values for all primitive fields and then // recurse for all non-primitives. // // Not safe for cyclic or tree-like structs! // // obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) // Intended for tests, so will panic on bad input or unimplemented fields. func (f *Fuzzer) Fuzz(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() f.doFuzz(v, 0) } // FuzzNoCustom is just like Fuzz, except that any custom fuzz function for // obj's type will not be called and obj will not be tested for fuzz.Interface // conformance. This applies only to obj and not other instances of obj's // type. // Not safe for cyclic or tree-like structs! // obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ ) // Intended for tests, so will panic on bad input or unimplemented fields. func (f *Fuzzer) FuzzNoCustom(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() f.doFuzz(v, flagNoCustomFuzz) } const ( // Do not try to find a custom fuzz function. Does not apply recursively. flagNoCustomFuzz uint64 = 1 << iota ) func (f *Fuzzer) doFuzz(v reflect.Value, flags uint64) { if !v.CanSet() { return } if flags&flagNoCustomFuzz == 0 { // Check for both pointer and non-pointer custom functions. if v.CanAddr() && f.tryCustom(v.Addr()) { return } if f.tryCustom(v) { return } } if fn, ok := fillFuncMap[v.Kind()]; ok { fn(v, f.r) return } switch v.Kind() { case reflect.Map: if f.genShouldFill() { v.Set(reflect.MakeMap(v.Type())) n := f.genElementCount() for i := 0; i < n; i++ { key := reflect.New(v.Type().Key()).Elem() f.doFuzz(key, 0) val := reflect.New(v.Type().Elem()).Elem() f.doFuzz(val, 0) v.SetMapIndex(key, val) } return } v.Set(reflect.Zero(v.Type())) case reflect.Ptr: if f.genShouldFill() { v.Set(reflect.New(v.Type().Elem())) f.doFuzz(v.Elem(), 0) return } v.Set(reflect.Zero(v.Type())) case reflect.Slice: if f.genShouldFill() { n := f.genElementCount() v.Set(reflect.MakeSlice(v.Type(), n, n)) for i := 0; i < n; i++ { f.doFuzz(v.Index(i), 0) } return } v.Set(reflect.Zero(v.Type())) case reflect.Struct: for i := 0; i < v.NumField(); i++ { f.doFuzz(v.Field(i), 0) } case reflect.Array: fallthrough case reflect.Chan: fallthrough case reflect.Func: fallthrough case reflect.Interface: fallthrough default: panic(fmt.Sprintf("Can't handle %#v", v.Interface())) } } // tryCustom searches for custom handlers, and returns true iff it finds a match // and successfully randomizes v. func (f *Fuzzer) tryCustom(v reflect.Value) bool { // First: see if we have a fuzz function for it. doCustom, ok := f.fuzzFuncs[v.Type()] if !ok { // Second: see if it can fuzz itself. if v.CanInterface() { intf := v.Interface() if fuzzable, ok := intf.(Interface); ok { fuzzable.Fuzz(Continue{f: f, Rand: f.r}) return true } } // Finally: see if there is a default fuzz function. doCustom, ok = f.defaultFuzzFuncs[v.Type()] if !ok { return false } } switch v.Kind() { case reflect.Ptr: if v.IsNil() { if !v.CanSet() { return false } v.Set(reflect.New(v.Type().Elem())) } case reflect.Map: if v.IsNil() { if !v.CanSet() { return false } v.Set(reflect.MakeMap(v.Type())) } default: return false } doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{ f: f, Rand: f.r, })}) return true } // Interface represents an object that knows how to fuzz itself. Any time we // find a type that implements this interface we will delegate the act of // fuzzing itself. type Interface interface { Fuzz(c Continue) } // Continue can be passed to custom fuzzing functions to allow them to use // the correct source of randomness and to continue fuzzing their members. type Continue struct { f *Fuzzer // For convenience, Continue implements rand.Rand via embedding. // Use this for generating any randomness if you want your fuzzing // to be repeatable for a given seed. *rand.Rand } // Fuzz continues fuzzing obj. obj must be a pointer. func (c Continue) Fuzz(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() c.f.doFuzz(v, 0) } // FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for // obj's type will not be called and obj will not be tested for fuzz.Interface // conformance. This applies only to obj and not other instances of obj's // type. func (c Continue) FuzzNoCustom(obj interface{}) { v := reflect.ValueOf(obj) if v.Kind() != reflect.Ptr { panic("needed ptr!") } v = v.Elem() c.f.doFuzz(v, flagNoCustomFuzz) } // RandString makes a random string up to 20 characters long. The returned string // may include a variety of (valid) UTF-8 encodings. func (c Continue) RandString() string { return randString(c.Rand) } // RandUint64 makes random 64 bit numbers. // Weirdly, rand doesn't have a function that gives you 64 random bits. func (c Continue) RandUint64() uint64 { return randUint64(c.Rand) } // RandBool returns true or false randomly. func (c Continue) RandBool() bool { return randBool(c.Rand) } func fuzzInt(v reflect.Value, r *rand.Rand) { v.SetInt(int64(randUint64(r))) } func fuzzUint(v reflect.Value, r *rand.Rand) { v.SetUint(randUint64(r)) } func fuzzTime(t *time.Time, c Continue) { var sec, nsec int64 // Allow for about 1000 years of random time values, which keeps things // like JSON parsing reasonably happy. sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60) c.Fuzz(&nsec) *t = time.Unix(sec, nsec) } var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){ reflect.Bool: func(v reflect.Value, r *rand.Rand) { v.SetBool(randBool(r)) }, reflect.Int: fuzzInt, reflect.Int8: fuzzInt, reflect.Int16: fuzzInt, reflect.Int32: fuzzInt, reflect.Int64: fuzzInt, reflect.Uint: fuzzUint, reflect.Uint8: fuzzUint, reflect.Uint16: fuzzUint, reflect.Uint32: fuzzUint, reflect.Uint64: fuzzUint, reflect.Uintptr: fuzzUint, reflect.Float32: func(v reflect.Value, r *rand.Rand) { v.SetFloat(float64(r.Float32())) }, reflect.Float64: func(v reflect.Value, r *rand.Rand) { v.SetFloat(r.Float64()) }, reflect.Complex64: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, reflect.Complex128: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, reflect.String: func(v reflect.Value, r *rand.Rand) { v.SetString(randString(r)) }, reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) { panic("unimplemented") }, } // randBool returns true or false randomly. func randBool(r *rand.Rand) bool { if r.Int()&1 == 1 { return true } return false } type charRange struct { first, last rune } // choose returns a random unicode character from the given range, using the // given randomness source. func (r *charRange) choose(rand *rand.Rand) rune { count := int64(r.last - r.first) return r.first + rune(rand.Int63n(count)) } var unicodeRanges = []charRange{ {' ', '~'}, // ASCII characters {'\u00a0', '\u02af'}, // Multi-byte encoded characters {'\u4e00', '\u9fff'}, // Common CJK (even longer encodings) } // randString makes a random string up to 20 characters long. The returned string // may include a variety of (valid) UTF-8 encodings. func randString(r *rand.Rand) string { n := r.Intn(20) runes := make([]rune, n) for i := range runes { runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r) } return string(runes) } // randUint64 makes random 64 bit numbers. // Weirdly, rand doesn't have a function that gives you 64 random bits. func randUint64(r *rand.Rand) uint64 { return uint64(r.Uint32())<<32 | uint64(r.Uint32()) } ================================================ FILE: vendor/github.com/google/gofuzz/fuzz_test.go ================================================ /* 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 fuzz import ( "reflect" "testing" "time" ) func TestFuzz_basic(t *testing.T) { obj := &struct { I int I8 int8 I16 int16 I32 int32 I64 int64 U uint U8 uint8 U16 uint16 U32 uint32 U64 uint64 Uptr uintptr S string B bool T time.Time }{} failed := map[string]int{} for i := 0; i < 10; i++ { New().Fuzz(obj) if n, v := "i", obj.I; v == 0 { failed[n] = failed[n] + 1 } if n, v := "i8", obj.I8; v == 0 { failed[n] = failed[n] + 1 } if n, v := "i16", obj.I16; v == 0 { failed[n] = failed[n] + 1 } if n, v := "i32", obj.I32; v == 0 { failed[n] = failed[n] + 1 } if n, v := "i64", obj.I64; v == 0 { failed[n] = failed[n] + 1 } if n, v := "u", obj.U; v == 0 { failed[n] = failed[n] + 1 } if n, v := "u8", obj.U8; v == 0 { failed[n] = failed[n] + 1 } if n, v := "u16", obj.U16; v == 0 { failed[n] = failed[n] + 1 } if n, v := "u32", obj.U32; v == 0 { failed[n] = failed[n] + 1 } if n, v := "u64", obj.U64; v == 0 { failed[n] = failed[n] + 1 } if n, v := "uptr", obj.Uptr; v == 0 { failed[n] = failed[n] + 1 } if n, v := "s", obj.S; v == "" { failed[n] = failed[n] + 1 } if n, v := "b", obj.B; v == false { failed[n] = failed[n] + 1 } if n, v := "t", obj.T; v.IsZero() { failed[n] = failed[n] + 1 } } checkFailed(t, failed) } func checkFailed(t *testing.T, failed map[string]int) { for k, v := range failed { if v > 8 { t.Errorf("%v seems to not be getting set, was zero value %v times", k, v) } } } func TestFuzz_structptr(t *testing.T) { obj := &struct { A *struct { S string } }{} f := New().NilChance(.5) failed := map[string]int{} for i := 0; i < 10; i++ { f.Fuzz(obj) if n, v := "a not nil", obj.A; v == nil { failed[n] = failed[n] + 1 } if n, v := "a nil", obj.A; v != nil { failed[n] = failed[n] + 1 } if n, v := "as", obj.A; v == nil || v.S == "" { failed[n] = failed[n] + 1 } } checkFailed(t, failed) } // tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest // stage it ever got to. func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) { maxStage := 0 for i := 0; i < 20; i++ { f.Fuzz(obj) stage, passed := check() if stage > maxStage { maxStage = stage } if passed { return } } t.Errorf("Only ever got to stage %v", maxStage) } func TestFuzz_structmap(t *testing.T) { obj := &struct { A map[struct { S string }]struct { S2 string } B map[string]string }{} tryFuzz(t, New(), obj, func() (int, bool) { if obj.A == nil { return 1, false } if len(obj.A) == 0 { return 2, false } for k, v := range obj.A { if k.S == "" { return 3, false } if v.S2 == "" { return 4, false } } if obj.B == nil { return 5, false } if len(obj.B) == 0 { return 6, false } for k, v := range obj.B { if k == "" { return 7, false } if v == "" { return 8, false } } return 9, true }) } func TestFuzz_structslice(t *testing.T) { obj := &struct { A []struct { S string } B []string }{} tryFuzz(t, New(), obj, func() (int, bool) { if obj.A == nil { return 1, false } if len(obj.A) == 0 { return 2, false } for _, v := range obj.A { if v.S == "" { return 3, false } } if obj.B == nil { return 4, false } if len(obj.B) == 0 { return 5, false } for _, v := range obj.B { if v == "" { return 6, false } } return 7, true }) } func TestFuzz_custom(t *testing.T) { obj := &struct { A string B *string C map[string]string D *map[string]string }{} testPhrase := "gotcalled" testMap := map[string]string{"C": "D"} f := New().Funcs( func(s *string, c Continue) { *s = testPhrase }, func(m map[string]string, c Continue) { m["C"] = "D" }, ) tryFuzz(t, f, obj, func() (int, bool) { if obj.A != testPhrase { return 1, false } if obj.B == nil { return 2, false } if *obj.B != testPhrase { return 3, false } if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) { return 4, false } if obj.D == nil { return 5, false } if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) { return 6, false } return 7, true }) } type SelfFuzzer string // Implement fuzz.Interface. func (sf *SelfFuzzer) Fuzz(c Continue) { *sf = selfFuzzerTestPhrase } const selfFuzzerTestPhrase = "was fuzzed" func TestFuzz_interface(t *testing.T) { f := New() var obj1 SelfFuzzer tryFuzz(t, f, &obj1, func() (int, bool) { if obj1 != selfFuzzerTestPhrase { return 1, false } return 1, true }) var obj2 map[int]SelfFuzzer tryFuzz(t, f, &obj2, func() (int, bool) { for _, v := range obj2 { if v != selfFuzzerTestPhrase { return 1, false } } return 1, true }) } func TestFuzz_interfaceAndFunc(t *testing.T) { const privateTestPhrase = "private phrase" f := New().Funcs( // This should take precedence over SelfFuzzer.Fuzz(). func(s *SelfFuzzer, c Continue) { *s = privateTestPhrase }, ) var obj1 SelfFuzzer tryFuzz(t, f, &obj1, func() (int, bool) { if obj1 != privateTestPhrase { return 1, false } return 1, true }) var obj2 map[int]SelfFuzzer tryFuzz(t, f, &obj2, func() (int, bool) { for _, v := range obj2 { if v != privateTestPhrase { return 1, false } } return 1, true }) } func TestFuzz_noCustom(t *testing.T) { type Inner struct { Str string } type Outer struct { Str string In Inner } testPhrase := "gotcalled" f := New().Funcs( func(outer *Outer, c Continue) { outer.Str = testPhrase c.Fuzz(&outer.In) }, func(inner *Inner, c Continue) { inner.Str = testPhrase }, ) c := Continue{f: f, Rand: f.r} // Fuzzer.Fuzz() obj1 := Outer{} f.Fuzz(&obj1) if obj1.Str != testPhrase { t.Errorf("expected Outer custom function to have been called") } if obj1.In.Str != testPhrase { t.Errorf("expected Inner custom function to have been called") } // Continue.Fuzz() obj2 := Outer{} c.Fuzz(&obj2) if obj2.Str != testPhrase { t.Errorf("expected Outer custom function to have been called") } if obj2.In.Str != testPhrase { t.Errorf("expected Inner custom function to have been called") } // Fuzzer.FuzzNoCustom() obj3 := Outer{} f.FuzzNoCustom(&obj3) if obj3.Str == testPhrase { t.Errorf("expected Outer custom function to not have been called") } if obj3.In.Str != testPhrase { t.Errorf("expected Inner custom function to have been called") } // Continue.FuzzNoCustom() obj4 := Outer{} c.FuzzNoCustom(&obj4) if obj4.Str == testPhrase { t.Errorf("expected Outer custom function to not have been called") } if obj4.In.Str != testPhrase { t.Errorf("expected Inner custom function to have been called") } } ================================================ FILE: vendor/github.com/imdario/mergo/.travis.yml ================================================ language: go install: go get -t ================================================ FILE: vendor/github.com/imdario/mergo/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/imdario/mergo/README.md ================================================ # 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 although it may use more of testing. Here some projects in the wild using Mergo: - [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) [![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 ## 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). 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). ================================================ FILE: vendor/github.com/imdario/mergo/doc.go ================================================ // 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 ================================================ FILE: vendor/github.com/imdario/mergo/map.go ================================================ // 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) (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)) { 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); err != nil { return } } else { if srcKind == reflect.Map { if err = deepMap(dstElement, srcElement, visited, depth+1); 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 { 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) } 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) } ================================================ FILE: vendor/github.com/imdario/mergo/merge.go ================================================ // 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) (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); err != nil { return } } case reflect.Map: for _, key := range src.MapKeys() { srcElement := src.MapIndex(key) if !srcElement.IsValid() { continue } dstElement := dst.MapIndex(key) switch reflect.TypeOf(srcElement.Interface()).Kind() { case reflect.Struct: fallthrough case reflect.Map: if err = deepMerge(dstElement, srcElement, visited, depth+1); err != nil { return } } if !dstElement.IsValid() { dst.SetMapIndex(key, srcElement) } } case reflect.Ptr: fallthrough case reflect.Interface: if src.IsNil() { break } else if dst.IsNil() { if dst.CanSet() && isEmptyValue(dst) { dst.Set(src) } } else if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1); err != nil { return } default: if dst.CanSet() && !isEmptyValue(src) { 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 { 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) } ================================================ FILE: vendor/github.com/imdario/mergo/mergo.go ================================================ // 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 } ================================================ FILE: vendor/github.com/imdario/mergo/mergo_test.go ================================================ // 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 import ( "gopkg.in/yaml.v1" "io/ioutil" "reflect" "testing" ) type simpleTest struct { Value int } type complexTest struct { St simpleTest sz int Id string } type moreComplextText struct { Ct complexTest St simpleTest Nt simpleTest } type pointerTest struct { C *simpleTest } type sliceTest struct { S []int } func TestNil(t *testing.T) { if err := Merge(nil, nil); err != ErrNilArguments { t.Fail() } } func TestDifferentTypes(t *testing.T) { a := simpleTest{42} b := 42 if err := Merge(&a, b); err != ErrDifferentArgumentsTypes { t.Fail() } } func TestSimpleStruct(t *testing.T) { a := simpleTest{} b := simpleTest{42} if err := Merge(&a, b); err != nil { t.FailNow() } if a.Value != 42 { t.Fatalf("b not merged in a properly: a.Value(%d) != b.Value(%d)", a.Value, b.Value) } if !reflect.DeepEqual(a, b) { t.FailNow() } } func TestComplexStruct(t *testing.T) { a := complexTest{} a.Id = "athing" b := complexTest{simpleTest{42}, 1, "bthing"} if err := Merge(&a, b); err != nil { t.FailNow() } if a.St.Value != 42 { t.Fatalf("b not merged in a properly: a.St.Value(%d) != b.St.Value(%d)", a.St.Value, b.St.Value) } if a.sz == 1 { t.Fatalf("a's private field sz not preserved from merge: a.sz(%d) == b.sz(%d)", a.sz, b.sz) } if a.Id != b.Id { t.Fatalf("a's field Id not merged properly: a.Id(%s) != b.Id(%s)", a.Id, b.Id) } } func TestPointerStruct(t *testing.T) { s1 := simpleTest{} s2 := simpleTest{19} a := pointerTest{&s1} b := pointerTest{&s2} if err := Merge(&a, b); err != nil { t.FailNow() } if a.C.Value != b.C.Value { //t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) } } func TestPointerStructNil(t *testing.T) { a := pointerTest{nil} b := pointerTest{&simpleTest{19}} if err := Merge(&a, b); err != nil { t.FailNow() } if a.C.Value != b.C.Value { t.Fatalf("b not merged in a properly: a.C.Value(%d) != b.C.Value(%d)", a.C.Value, b.C.Value) } } func TestSliceStruct(t *testing.T) { a := sliceTest{} b := sliceTest{[]int{1, 2, 3}} if err := Merge(&a, b); err != nil { t.FailNow() } if len(b.S) != 3 { t.FailNow() } if len(a.S) != len(b.S) { t.Fatalf("b not merged in a properly %d != %d", len(a.S), len(b.S)) } a = sliceTest{[]int{1}} b = sliceTest{[]int{1, 2, 3}} if err := Merge(&a, b); err != nil { t.FailNow() } if len(b.S) != 3 { t.FailNow() } if len(a.S) != len(b.S) { t.Fatalf("b not merged in a properly %d != %d", len(a.S), len(b.S)) } } func TestMaps(t *testing.T) { m := map[string]simpleTest{ "a": simpleTest{}, "b": simpleTest{42}, } n := map[string]simpleTest{ "a": simpleTest{16}, "b": simpleTest{}, "c": simpleTest{12}, } if err := Merge(&m, n); err != nil { t.Fatalf(err.Error()) } if len(m) != 3 { t.Fatalf(`n not merged in m properly, m must have 3 elements instead of %d`, len(m)) } if m["a"].Value != 0 { t.Fatalf(`n merged in m because I solved non-addressable map values TODO: m["a"].Value(%d) != n["a"].Value(%d)`, m["a"].Value, n["a"].Value) } if m["b"].Value != 42 { t.Fatalf(`n wrongly merged in m: m["b"].Value(%d) != n["b"].Value(%d)`, m["b"].Value, n["b"].Value) } if m["c"].Value != 12 { t.Fatalf(`n not merged in m: m["c"].Value(%d) != n["c"].Value(%d)`, m["c"].Value, n["c"].Value) } } func TestYAMLMaps(t *testing.T) { thing := loadYAML("testdata/thing.yml") license := loadYAML("testdata/license.yml") ft := thing["fields"].(map[interface{}]interface{}) fl := license["fields"].(map[interface{}]interface{}) expectedLength := len(ft) + len(fl) if err := Merge(&license, thing); err != nil { t.Fatal(err.Error()) } currentLength := len(license["fields"].(map[interface{}]interface{})) if currentLength != expectedLength { t.Fatalf(`thing not merged in license properly, license must have %d elements instead of %d`, expectedLength, currentLength) } fields := license["fields"].(map[interface{}]interface{}) if _, ok := fields["id"]; !ok { t.Fatalf(`thing not merged in license properly, license must have a new id field from thing`) } } func TestTwoPointerValues(t *testing.T) { a := &simpleTest{} b := &simpleTest{42} if err := Merge(a, b); err != nil { t.Fatalf(`Boom. You crossed the streams: %s`, err) } } func TestMap(t *testing.T) { a := complexTest{} a.Id = "athing" c := moreComplextText{a, simpleTest{}, simpleTest{}} b := map[string]interface{}{ "ct": map[string]interface{}{ "st": map[string]interface{}{ "value": 42, }, "sz": 1, "id": "bthing", }, "st": &simpleTest{144}, // Mapping a reference "zt": simpleTest{299}, // Mapping a missing field (zt doesn't exist) "nt": simpleTest{3}, } if err := Map(&c, b); err != nil { t.FailNow() } m := b["ct"].(map[string]interface{}) n := m["st"].(map[string]interface{}) o := b["st"].(*simpleTest) p := b["nt"].(simpleTest) if c.Ct.St.Value != 42 { t.Fatalf("b not merged in a properly: c.Ct.St.Value(%d) != b.Ct.St.Value(%d)", c.Ct.St.Value, n["value"]) } if c.St.Value != 144 { t.Fatalf("b not merged in a properly: c.St.Value(%d) != b.St.Value(%d)", c.St.Value, o.Value) } if c.Nt.Value != 3 { t.Fatalf("b not merged in a properly: c.Nt.Value(%d) != b.Nt.Value(%d)", c.St.Value, p.Value) } if c.Ct.sz == 1 { t.Fatalf("a's private field sz not preserved from merge: c.Ct.sz(%d) == b.Ct.sz(%d)", c.Ct.sz, m["sz"]) } if c.Ct.Id != m["id"] { t.Fatalf("a's field Id not merged properly: c.Ct.Id(%s) != b.Ct.Id(%s)", c.Ct.Id, m["id"]) } } func TestSimpleMap(t *testing.T) { a := simpleTest{} b := map[string]interface{}{ "value": 42, } if err := Map(&a, b); err != nil { t.FailNow() } if a.Value != 42 { t.Fatalf("b not merged in a properly: a.Value(%d) != b.Value(%v)", a.Value, b["value"]) } } type pointerMapTest struct { A int hidden int B *simpleTest } func TestBackAndForth(t *testing.T) { pt := pointerMapTest{42, 1, &simpleTest{66}} m := make(map[string]interface{}) if err := Map(&m, pt); err != nil { t.FailNow() } var ( v interface{} ok bool ) if v, ok = m["a"]; v.(int) != pt.A || !ok { t.Fatalf("pt not merged properly: m[`a`](%d) != pt.A(%d)", v, pt.A) } if v, ok = m["b"]; !ok { t.Fatalf("pt not merged properly: B is missing in m") } var st *simpleTest if st = v.(*simpleTest); st.Value != 66 { t.Fatalf("something went wrong while mapping pt on m, B wasn't copied") } bpt := pointerMapTest{} if err := Map(&bpt, m); err != nil { t.Fatal(err) } if bpt.A != pt.A { t.Fatalf("pt not merged properly: bpt.A(%d) != pt.A(%d)", bpt.A, pt.A) } if bpt.hidden == pt.hidden { t.Fatalf("pt unexpectedly merged: bpt.hidden(%d) == pt.hidden(%d)", bpt.hidden, pt.hidden) } if bpt.B.Value != pt.B.Value { t.Fatalf("pt not merged properly: bpt.B.Value(%d) != pt.B.Value(%d)", bpt.B.Value, pt.B.Value) } } func loadYAML(path string) (m map[string]interface{}) { m = make(map[string]interface{}) raw, _ := ioutil.ReadFile(path) _ = yaml.Unmarshal(raw, &m) return } ================================================ FILE: vendor/github.com/imdario/mergo/testdata/license.yml ================================================ import: ../../../../fossene/db/schema/thing.yml fields: site: string ================================================ FILE: vendor/github.com/imdario/mergo/testdata/thing.yml ================================================ fields: id: int name: string parent: ref "datu:thing" status: enum(draft, public, private) ================================================ FILE: vendor/github.com/inconshreveable/mousetrap/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/inconshreveable/mousetrap/README.md ================================================ # 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) ================================================ FILE: vendor/github.com/inconshreveable/mousetrap/trap_others.go ================================================ // +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 } ================================================ FILE: vendor/github.com/inconshreveable/mousetrap/trap_windows.go ================================================ // +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" } ================================================ FILE: vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go ================================================ // +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[:]) } ================================================ FILE: vendor/github.com/juju/ratelimit/LICENSE ================================================ All files in this repository are licensed as follows. If you contribute to this repository, it is assumed that you license your contribution under the same license unless you state otherwise. All files Copyright (C) 2015 Canonical Ltd. unless otherwise specified in the file. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: vendor/github.com/juju/ratelimit/README.md ================================================ # ratelimit -- import "github.com/juju/ratelimit" The ratelimit package provides an efficient token bucket implementation. See http://en.wikipedia.org/wiki/Token_bucket. ## Usage #### func Reader ```go func Reader(r io.Reader, bucket *Bucket) io.Reader ``` Reader returns a reader that is rate limited by the given token bucket. Each token in the bucket represents one byte. #### func Writer ```go func Writer(w io.Writer, bucket *Bucket) io.Writer ``` Writer returns a writer that is rate limited by the given token bucket. Each token in the bucket represents one byte. #### type Bucket ```go type Bucket struct { } ``` Bucket represents a token bucket that fills at a predetermined rate. Methods on Bucket may be called concurrently. #### func NewBucket ```go func NewBucket(fillInterval time.Duration, capacity int64) *Bucket ``` NewBucket returns a new token bucket that fills at the rate of one token every fillInterval, up to the given maximum capacity. Both arguments must be positive. The bucket is initially full. #### func NewBucketWithQuantum ```go func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket ``` NewBucketWithQuantum is similar to NewBucket, but allows the specification of the quantum size - quantum tokens are added every fillInterval. #### func NewBucketWithRate ```go func NewBucketWithRate(rate float64, capacity int64) *Bucket ``` NewBucketWithRate returns a token bucket that fills the bucket at the rate of rate tokens per second up to the given maximum capacity. Because of limited clock resolution, at high rates, the actual rate may be up to 1% different from the specified rate. #### func (*Bucket) Rate ```go func (tb *Bucket) Rate() float64 ``` Rate returns the fill rate of the bucket, in tokens per second. #### func (*Bucket) Take ```go func (tb *Bucket) Take(count int64) time.Duration ``` Take takes count tokens from the bucket without blocking. It returns the time that the caller should wait until the tokens are actually available. Note that if the request is irrevocable - there is no way to return tokens to the bucket once this method commits us to taking them. #### func (*Bucket) TakeAvailable ```go func (tb *Bucket) TakeAvailable(count int64) int64 ``` TakeAvailable takes up to count immediately available tokens from the bucket. It returns the number of tokens removed, or zero if there are no available tokens. It does not block. #### func (*Bucket) TakeMaxDuration ```go func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) ``` TakeMaxDuration is like Take, except that it will only take tokens from the bucket if the wait time for the tokens is no greater than maxWait. If it would take longer than maxWait for the tokens to become available, it does nothing and reports false, otherwise it returns the time that the caller should wait until the tokens are actually available, and reports true. #### func (*Bucket) Wait ```go func (tb *Bucket) Wait(count int64) ``` Wait takes count tokens from the bucket, waiting until they are available. #### func (*Bucket) WaitMaxDuration ```go func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool ``` WaitMaxDuration is like Wait except that it will only take tokens from the bucket if it needs to wait for no greater than maxWait. It reports whether any tokens have been removed from the bucket If no tokens have been removed, it returns immediately. ================================================ FILE: vendor/github.com/juju/ratelimit/ratelimit.go ================================================ // Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3 with static-linking exception. // See LICENCE file for details. // The ratelimit package provides an efficient token bucket implementation // that can be used to limit the rate of arbitrary things. // See http://en.wikipedia.org/wiki/Token_bucket. package ratelimit import ( "math" "strconv" "sync" "time" ) // Bucket represents a token bucket that fills at a predetermined rate. // Methods on Bucket may be called concurrently. type Bucket struct { startTime time.Time capacity int64 quantum int64 fillInterval time.Duration // The mutex guards the fields following it. mu sync.Mutex // avail holds the number of available tokens // in the bucket, as of availTick ticks from startTime. // It will be negative when there are consumers // waiting for tokens. avail int64 availTick int64 } // NewBucket returns a new token bucket that fills at the // rate of one token every fillInterval, up to the given // maximum capacity. Both arguments must be // positive. The bucket is initially full. func NewBucket(fillInterval time.Duration, capacity int64) *Bucket { return NewBucketWithQuantum(fillInterval, capacity, 1) } // rateMargin specifes the allowed variance of actual // rate from specified rate. 1% seems reasonable. const rateMargin = 0.01 // NewBucketWithRate returns a token bucket that fills the bucket // at the rate of rate tokens per second up to the given // maximum capacity. Because of limited clock resolution, // at high rates, the actual rate may be up to 1% different from the // specified rate. func NewBucketWithRate(rate float64, capacity int64) *Bucket { for quantum := int64(1); quantum < 1<<50; quantum = nextQuantum(quantum) { fillInterval := time.Duration(1e9 * float64(quantum) / rate) if fillInterval <= 0 { continue } tb := NewBucketWithQuantum(fillInterval, capacity, quantum) if diff := math.Abs(tb.Rate() - rate); diff/rate <= rateMargin { return tb } } panic("cannot find suitable quantum for " + strconv.FormatFloat(rate, 'g', -1, 64)) } // nextQuantum returns the next quantum to try after q. // We grow the quantum exponentially, but slowly, so we // get a good fit in the lower numbers. func nextQuantum(q int64) int64 { q1 := q * 11 / 10 if q1 == q { q1++ } return q1 } // NewBucketWithQuantum is similar to NewBucket, but allows // the specification of the quantum size - quantum tokens // are added every fillInterval. func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket { if fillInterval <= 0 { panic("token bucket fill interval is not > 0") } if capacity <= 0 { panic("token bucket capacity is not > 0") } if quantum <= 0 { panic("token bucket quantum is not > 0") } return &Bucket{ startTime: time.Now(), capacity: capacity, quantum: quantum, avail: capacity, fillInterval: fillInterval, } } // Wait takes count tokens from the bucket, waiting until they are // available. func (tb *Bucket) Wait(count int64) { if d := tb.Take(count); d > 0 { time.Sleep(d) } } // WaitMaxDuration is like Wait except that it will // only take tokens from the bucket if it needs to wait // for no greater than maxWait. It reports whether // any tokens have been removed from the bucket // If no tokens have been removed, it returns immediately. func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool { d, ok := tb.TakeMaxDuration(count, maxWait) if d > 0 { time.Sleep(d) } return ok } const infinityDuration time.Duration = 0x7fffffffffffffff // Take takes count tokens from the bucket without blocking. It returns // the time that the caller should wait until the tokens are actually // available. // // Note that if the request is irrevocable - there is no way to return // tokens to the bucket once this method commits us to taking them. func (tb *Bucket) Take(count int64) time.Duration { d, _ := tb.take(time.Now(), count, infinityDuration) return d } // TakeMaxDuration is like Take, except that // it will only take tokens from the bucket if the wait // time for the tokens is no greater than maxWait. // // If it would take longer than maxWait for the tokens // to become available, it does nothing and reports false, // otherwise it returns the time that the caller should // wait until the tokens are actually available, and reports // true. func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool) { return tb.take(time.Now(), count, maxWait) } // TakeAvailable takes up to count immediately available tokens from the // bucket. It returns the number of tokens removed, or zero if there are // no available tokens. It does not block. func (tb *Bucket) TakeAvailable(count int64) int64 { return tb.takeAvailable(time.Now(), count) } // takeAvailable is the internal version of TakeAvailable - it takes the // current time as an argument to enable easy testing. func (tb *Bucket) takeAvailable(now time.Time, count int64) int64 { if count <= 0 { return 0 } tb.mu.Lock() defer tb.mu.Unlock() tb.adjust(now) if tb.avail <= 0 { return 0 } if count > tb.avail { count = tb.avail } tb.avail -= count return count } // Available returns the number of available tokens. It will be negative // when there are consumers waiting for tokens. Note that if this // returns greater than zero, it does not guarantee that calls that take // tokens from the buffer will succeed, as the number of available // tokens could have changed in the meantime. This method is intended // primarily for metrics reporting and debugging. func (tb *Bucket) Available() int64 { return tb.available(time.Now()) } // available is the internal version of available - it takes the current time as // an argument to enable easy testing. func (tb *Bucket) available(now time.Time) int64 { tb.mu.Lock() defer tb.mu.Unlock() tb.adjust(now) return tb.avail } // Capacity returns the capacity that the bucket was created with. func (tb *Bucket) Capacity() int64 { return tb.capacity } // Rate returns the fill rate of the bucket, in tokens per second. func (tb *Bucket) Rate() float64 { return 1e9 * float64(tb.quantum) / float64(tb.fillInterval) } // take is the internal version of Take - it takes the current time as // an argument to enable easy testing. func (tb *Bucket) take(now time.Time, count int64, maxWait time.Duration) (time.Duration, bool) { if count <= 0 { return 0, true } tb.mu.Lock() defer tb.mu.Unlock() currentTick := tb.adjust(now) avail := tb.avail - count if avail >= 0 { tb.avail = avail return 0, true } // Round up the missing tokens to the nearest multiple // of quantum - the tokens won't be available until // that tick. endTick := currentTick + (-avail+tb.quantum-1)/tb.quantum endTime := tb.startTime.Add(time.Duration(endTick) * tb.fillInterval) waitTime := endTime.Sub(now) if waitTime > maxWait { return 0, false } tb.avail = avail return waitTime, true } // adjust adjusts the current bucket capacity based on the current time. // It returns the current tick. func (tb *Bucket) adjust(now time.Time) (currentTick int64) { currentTick = int64(now.Sub(tb.startTime) / tb.fillInterval) if tb.avail >= tb.capacity { return } tb.avail += (currentTick - tb.availTick) * tb.quantum if tb.avail > tb.capacity { tb.avail = tb.capacity } tb.availTick = currentTick return } ================================================ FILE: vendor/github.com/juju/ratelimit/ratelimit_test.go ================================================ // Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3 with static-linking exception. // See LICENCE file for details. package ratelimit import ( "math" "testing" "time" gc "gopkg.in/check.v1" ) func TestPackage(t *testing.T) { gc.TestingT(t) } type rateLimitSuite struct{} var _ = gc.Suite(rateLimitSuite{}) type takeReq struct { time time.Duration count int64 expectWait time.Duration } var takeTests = []struct { about string fillInterval time.Duration capacity int64 reqs []takeReq }{{ about: "serial requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 0, expectWait: 0, }, { time: 0, count: 10, expectWait: 0, }, { time: 0, count: 1, expectWait: 250 * time.Millisecond, }, { time: 250 * time.Millisecond, count: 1, expectWait: 250 * time.Millisecond, }}, }, { about: "concurrent requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 10, expectWait: 0, }, { time: 0, count: 2, expectWait: 500 * time.Millisecond, }, { time: 0, count: 2, expectWait: 1000 * time.Millisecond, }, { time: 0, count: 1, expectWait: 1250 * time.Millisecond, }}, }, { about: "more than capacity", fillInterval: 1 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 10, expectWait: 0, }, { time: 20 * time.Millisecond, count: 15, expectWait: 5 * time.Millisecond, }}, }, { about: "sub-quantum time", fillInterval: 10 * time.Millisecond, capacity: 10, reqs: []takeReq{{ time: 0, count: 10, expectWait: 0, }, { time: 7 * time.Millisecond, count: 1, expectWait: 3 * time.Millisecond, }, { time: 8 * time.Millisecond, count: 1, expectWait: 12 * time.Millisecond, }}, }, { about: "within capacity", fillInterval: 10 * time.Millisecond, capacity: 5, reqs: []takeReq{{ time: 0, count: 5, expectWait: 0, }, { time: 60 * time.Millisecond, count: 5, expectWait: 0, }, { time: 60 * time.Millisecond, count: 1, expectWait: 10 * time.Millisecond, }, { time: 80 * time.Millisecond, count: 2, expectWait: 10 * time.Millisecond, }}, }} var availTests = []struct { about string capacity int64 fillInterval time.Duration take int64 sleep time.Duration expectCountAfterTake int64 expectCountAfterSleep int64 }{{ about: "should fill tokens after interval", capacity: 5, fillInterval: time.Second, take: 5, sleep: time.Second, expectCountAfterTake: 0, expectCountAfterSleep: 1, }, { about: "should fill tokens plus existing count", capacity: 2, fillInterval: time.Second, take: 1, sleep: time.Second, expectCountAfterTake: 1, expectCountAfterSleep: 2, }, { about: "shouldn't fill before interval", capacity: 2, fillInterval: 2 * time.Second, take: 1, sleep: time.Second, expectCountAfterTake: 1, expectCountAfterSleep: 1, }, { about: "should fill only once after 1*interval before 2*interval", capacity: 2, fillInterval: 2 * time.Second, take: 1, sleep: 3 * time.Second, expectCountAfterTake: 1, expectCountAfterSleep: 2, }} func (rateLimitSuite) TestTake(c *gc.C) { for i, test := range takeTests { tb := NewBucket(test.fillInterval, test.capacity) for j, req := range test.reqs { d, ok := tb.take(tb.startTime.Add(req.time), req.count, infinityDuration) c.Assert(ok, gc.Equals, true) if d != req.expectWait { c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) } } } } func (rateLimitSuite) TestTakeMaxDuration(c *gc.C) { for i, test := range takeTests { tb := NewBucket(test.fillInterval, test.capacity) for j, req := range test.reqs { if req.expectWait > 0 { d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait-1) c.Assert(ok, gc.Equals, false) c.Assert(d, gc.Equals, time.Duration(0)) } d, ok := tb.take(tb.startTime.Add(req.time), req.count, req.expectWait) c.Assert(ok, gc.Equals, true) if d != req.expectWait { c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expectWait) } } } } type takeAvailableReq struct { time time.Duration count int64 expect int64 } var takeAvailableTests = []struct { about string fillInterval time.Duration capacity int64 reqs []takeAvailableReq }{{ about: "serial requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeAvailableReq{{ time: 0, count: 0, expect: 0, }, { time: 0, count: 10, expect: 10, }, { time: 0, count: 1, expect: 0, }, { time: 250 * time.Millisecond, count: 1, expect: 1, }}, }, { about: "concurrent requests", fillInterval: 250 * time.Millisecond, capacity: 10, reqs: []takeAvailableReq{{ time: 0, count: 5, expect: 5, }, { time: 0, count: 2, expect: 2, }, { time: 0, count: 5, expect: 3, }, { time: 0, count: 1, expect: 0, }}, }, { about: "more than capacity", fillInterval: 1 * time.Millisecond, capacity: 10, reqs: []takeAvailableReq{{ time: 0, count: 10, expect: 10, }, { time: 20 * time.Millisecond, count: 15, expect: 10, }}, }, { about: "within capacity", fillInterval: 10 * time.Millisecond, capacity: 5, reqs: []takeAvailableReq{{ time: 0, count: 5, expect: 5, }, { time: 60 * time.Millisecond, count: 5, expect: 5, }, { time: 70 * time.Millisecond, count: 1, expect: 1, }}, }} func (rateLimitSuite) TestTakeAvailable(c *gc.C) { for i, test := range takeAvailableTests { tb := NewBucket(test.fillInterval, test.capacity) for j, req := range test.reqs { d := tb.takeAvailable(tb.startTime.Add(req.time), req.count) if d != req.expect { c.Fatalf("test %d.%d, %s, got %v want %v", i, j, test.about, d, req.expect) } } } } func (rateLimitSuite) TestPanics(c *gc.C) { c.Assert(func() { NewBucket(0, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") c.Assert(func() { NewBucket(-2, 1) }, gc.PanicMatches, "token bucket fill interval is not > 0") c.Assert(func() { NewBucket(1, 0) }, gc.PanicMatches, "token bucket capacity is not > 0") c.Assert(func() { NewBucket(1, -2) }, gc.PanicMatches, "token bucket capacity is not > 0") } func isCloseTo(x, y, tolerance float64) bool { return math.Abs(x-y)/y < tolerance } func (rateLimitSuite) TestRate(c *gc.C) { tb := NewBucket(1, 1) if !isCloseTo(tb.Rate(), 1e9, 0.00001) { c.Fatalf("got %v want 1e9", tb.Rate()) } tb = NewBucket(2*time.Second, 1) if !isCloseTo(tb.Rate(), 0.5, 0.00001) { c.Fatalf("got %v want 0.5", tb.Rate()) } tb = NewBucketWithQuantum(100*time.Millisecond, 1, 5) if !isCloseTo(tb.Rate(), 50, 0.00001) { c.Fatalf("got %v want 50", tb.Rate()) } } func checkRate(c *gc.C, rate float64) { tb := NewBucketWithRate(rate, 1<<62) if !isCloseTo(tb.Rate(), rate, rateMargin) { c.Fatalf("got %g want %v", tb.Rate(), rate) } d, ok := tb.take(tb.startTime, 1<<62, infinityDuration) c.Assert(ok, gc.Equals, true) c.Assert(d, gc.Equals, time.Duration(0)) // Check that the actual rate is as expected by // asking for a not-quite multiple of the bucket's // quantum and checking that the wait time // correct. d, ok = tb.take(tb.startTime, tb.quantum*2-tb.quantum/2, infinityDuration) c.Assert(ok, gc.Equals, true) expectTime := 1e9 * float64(tb.quantum) * 2 / rate if !isCloseTo(float64(d), expectTime, rateMargin) { c.Fatalf("rate %g: got %g want %v", rate, float64(d), expectTime) } } func (rateLimitSuite) TestNewWithRate(c *gc.C) { for rate := float64(1); rate < 1e6; rate += 7 { checkRate(c, rate) } for _, rate := range []float64{ 1024 * 1024 * 1024, 1e-5, 0.9e-5, 0.5, 0.9, 0.9e8, 3e12, 4e18, } { checkRate(c, rate) checkRate(c, rate/3) checkRate(c, rate*1.3) } } func TestAvailable(t *testing.T) { for i, tt := range availTests { tb := NewBucket(tt.fillInterval, tt.capacity) if c := tb.takeAvailable(tb.startTime, tt.take); c != tt.take { t.Fatalf("#%d: %s, take = %d, want = %d", i, tt.about, c, tt.take) } if c := tb.available(tb.startTime); c != tt.expectCountAfterTake { t.Fatalf("#%d: %s, after take, available = %d, want = %d", i, tt.about, c, tt.expectCountAfterTake) } if c := tb.available(tb.startTime.Add(tt.sleep)); c != tt.expectCountAfterSleep { t.Fatalf("#%d: %s, after some time it should fill in new tokens, available = %d, want = %d", i, tt.about, c, tt.expectCountAfterSleep) } } } func BenchmarkWait(b *testing.B) { tb := NewBucket(1, 16*1024) for i := b.N - 1; i >= 0; i-- { tb.Wait(1) } } ================================================ FILE: vendor/github.com/juju/ratelimit/reader.go ================================================ // Copyright 2014 Canonical Ltd. // Licensed under the LGPLv3 with static-linking exception. // See LICENCE file for details. package ratelimit import "io" type reader struct { r io.Reader bucket *Bucket } // Reader returns a reader that is rate limited by // the given token bucket. Each token in the bucket // represents one byte. func Reader(r io.Reader, bucket *Bucket) io.Reader { return &reader{ r: r, bucket: bucket, } } func (r *reader) Read(buf []byte) (int, error) { n, err := r.r.Read(buf) if n <= 0 { return n, err } r.bucket.Wait(int64(n)) return n, err } type writer struct { w io.Writer bucket *Bucket } // Writer returns a reader that is rate limited by // the given token bucket. Each token in the bucket // represents one byte. func Writer(w io.Writer, bucket *Bucket) io.Writer { return &writer{ w: w, bucket: bucket, } } func (w *writer) Write(buf []byte) (int, error) { w.bucket.Wait(int64(len(buf))) return w.w.Write(buf) } ================================================ FILE: vendor/github.com/masterzen/simplexml/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/masterzen/simplexml/README.md ================================================ # Simplexml Dom library for Go This is a naive and simple Go library to build a XML DOM to be able to produce XML content. This is mainly used by the "WinRM Go library":[http://github.com/masterzen/winrm] ## Contact - Bugs: https://github.com/masterzen/simplexml/issues ### Building You can build the library from source: ```sh git clone https://github.com/masterzen/simplexml cd simplexml go build ``` ## Usage ================================================ FILE: vendor/github.com/masterzen/simplexml/dom/document.go ================================================ package dom import ( "bytes" "fmt" ) type Document struct { root *Element PrettyPrint bool Indentation string DocType bool } func CreateDocument() *Document { return &Document{ PrettyPrint: false, Indentation: " ", DocType: true } } func (doc *Document) SetRoot(node *Element) { node.parent = nil doc.root = node } func (doc *Document) String() string { var b bytes.Buffer if doc.DocType { fmt.Fprintln(&b, ``) } if doc.root != nil { doc.root.Bytes(&b, doc.PrettyPrint, doc.Indentation, 0) } return string(b.Bytes()) } ================================================ FILE: vendor/github.com/masterzen/simplexml/dom/dom_test.go ================================================ package dom import ( . "launchpad.net/gocheck" "testing" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } type DomSuite struct{} var _ = Suite(&DomSuite{}) func (s *DomSuite) TestEmptyDocument(c *C) { doc := CreateDocument() doc.PrettyPrint = true c.Assert(doc.String(), Equals, "\n") } func (s *DomSuite) TestOneEmptyNode(c *C) { doc := CreateDocument() doc.PrettyPrint = true root := CreateElement("root") doc.SetRoot(root) c.Assert(doc.String(), Equals, "\n\n") } func (s *DomSuite) TestMoreNodes(c *C) { doc := CreateDocument() doc.PrettyPrint = true root := CreateElement("root") node1 := CreateElement("node1") root.AddChild(node1) subnode := CreateElement("sub") node1.AddChild(subnode) node2 := CreateElement("node2") root.AddChild(node2) doc.SetRoot(root) expected := ` ` c.Assert(doc.String(), Equals, expected) } func (s *DomSuite) TestAttributes(c *C) { doc := CreateDocument() doc.PrettyPrint = true root := CreateElement("root") node1 := CreateElement("node1") node1.SetAttr("attr1", "pouet") root.AddChild(node1) doc.SetRoot(root) expected := ` ` c.Assert(doc.String(), Equals, expected) } func (s *DomSuite) TestContent(c *C) { doc := CreateDocument() doc.PrettyPrint = true root := CreateElement("root") node1 := CreateElement("node1") node1.SetContent("this is a text content") root.AddChild(node1) doc.SetRoot(root) expected := ` this is a text content ` c.Assert(doc.String(), Equals, expected) } func (s *DomSuite) TestNamespace(c *C) { doc := CreateDocument() doc.PrettyPrint = true root := CreateElement("root") root.DeclareNamespace(Namespace { Prefix: "a", Uri: "http://schemas.xmlsoap.org/ws/2004/08/addressing"}) node1 := CreateElement("node1") root.AddChild(node1) node1.SetNamespace("a", "http://schemas.xmlsoap.org/ws/2004/08/addressing") node1.SetContent("this is a text content") doc.SetRoot(root) expected := ` this is a text content ` c.Assert(doc.String(), Equals, expected) } ================================================ FILE: vendor/github.com/masterzen/simplexml/dom/element.go ================================================ package dom import ( "encoding/xml" "fmt" "bytes" ) type Attr struct { Name xml.Name // Attribute namespace and name. Value string // Attribute value. } type Element struct { name xml.Name children []*Element parent *Element content string attributes []*Attr namespaces []*Namespace document *Document } func CreateElement(n string) *Element { element := &Element { name: xml.Name { Local: n } } element.children = make([]*Element, 0, 5) element.attributes = make([]*Attr, 0, 10) element.namespaces = make([]*Namespace, 0, 10) return element } func (node *Element) AddChild(child *Element) *Element { if child.parent != nil { child.parent.RemoveChild(child) } child.SetParent(node) node.children = append(node.children, child) return node } func (node *Element) RemoveChild(child *Element) *Element { p := -1 for i, v := range node.children { if v == child { p = i break } } if p == -1 { return node } copy(node.children[p:], node.children[p+1:]) node.children = node.children[0 : len(node.children)-1] child.parent = nil return node } func (node *Element) SetAttr(name string, value string) *Element { // namespaces? attr := &Attr{ Name: xml.Name { Local: name }, Value: value } node.attributes = append(node.attributes, attr) return node } func (node *Element) SetParent(parent *Element) *Element { node.parent = parent return node } func (node *Element) SetContent(content string) *Element { node.content = content return node } // Add a namespace declaration to this node func (node *Element) DeclareNamespace(ns Namespace) *Element { // check if we already have it prefix := node.namespacePrefix(ns.Uri) if prefix == ns.Prefix { return node } // add it node.namespaces = append(node.namespaces, &ns) return node } func (node *Element) DeclaredNamespaces() []*Namespace { return node.namespaces } func (node *Element) SetNamespace(prefix string, uri string) { resolved := node.namespacePrefix(uri) if resolved == "" { // we couldn't find the namespace, let's declare it at this node node.namespaces = append(node.namespaces, &Namespace { Prefix: prefix, Uri: uri }) } node.name.Space = uri } func (node *Element) Bytes(out *bytes.Buffer, indent bool, indentType string, level int) { empty := len(node.children) == 0 && node.content == "" content := node.content != "" // children := len(node.children) > 0 // ns := len(node.namespaces) > 0 // attrs := len(node.attributes) > 0 indentStr := "" nextLine := "" if indent { nextLine = "\n" for i := 0; i < level; i++ { indentStr += indentType } } if node.name.Local != "" { if len(node.name.Space) > 0 { // first find if ns has been declared, otherwise prefix := node.namespacePrefix(node.name.Space) fmt.Fprintf(out, "%s<%s:%s", indentStr, prefix, node.name.Local) } else { fmt.Fprintf(out, "%s<%s", indentStr, node.name.Local) } } // declared namespaces for _, v := range node.namespaces { prefix := node.namespacePrefix(v.Uri) fmt.Fprintf(out, ` xmlns:%s="%s"`, prefix, v.Uri) } // attributes for _, v := range node.attributes { if len(v.Name.Space) > 0 { prefix := node.namespacePrefix(v.Name.Space) fmt.Fprintf(out, ` %s:%s="%s"`, prefix, v.Name.Local, v.Value) } else { fmt.Fprintf(out, ` %s="%s"`, v.Name.Local, v.Value) } } // close tag if empty { fmt.Fprintf(out, "/>%s", nextLine) } else { if content { out.WriteRune('>') } else { fmt.Fprintf(out, ">%s", nextLine) } } if len(node.children) > 0 { for _, child := range node.children { child.Bytes(out, indent, indentType, level + 1) } } else if node.content != "" { //val := []byte(node.content) //xml.EscapeText(out, val) out.WriteString(node.content) } if !empty && len(node.name.Local) > 0 { var indentation string if content { indentation = "" } else { indentation = indentStr } if len(node.name.Space) > 0 { prefix := node.namespacePrefix(node.name.Space) fmt.Fprintf(out, "%s\n", indentation, prefix, node.name.Local) } else { fmt.Fprintf(out, "%s\n", indentation, node.name.Local) } } } // Finds the prefix of the given namespace if it has been declared // in this node or in one of its parent func (node *Element) namespacePrefix(uri string) string { for _, ns := range node.namespaces { if ns.Uri == uri { return ns.Prefix } } if node.parent == nil { return "" } return node.parent.namespacePrefix(uri) } func (node *Element) String() string { var b bytes.Buffer node.Bytes(&b, false, "", 0) return string(b.Bytes()) } ================================================ FILE: vendor/github.com/masterzen/simplexml/dom/namespace.go ================================================ package dom type Namespace struct { Prefix string Uri string } func (ns *Namespace) SetTo(node *Element) { node.SetNamespace(ns.Prefix, ns.Uri) } ================================================ FILE: vendor/github.com/masterzen/winrm/.gitignore ================================================ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *.test *.prof *.coverprofile *.cov ================================================ FILE: vendor/github.com/masterzen/winrm/.travis.yml ================================================ sudo: false language: go go: - 1.2 - 1.3 - 1.4 - tip install: - make deps - go build -o winrm-cli before_install: - go get github.com/axw/gocov/gocov - go get github.com/mattn/goveralls - go get golang.org/x/tools/cmd/cover - go get github.com/modocache/gover - go get gopkg.in/check.v1 script: - make ci after_script: - $HOME/gopath/bin/goveralls -service="travis-ci" -coverprofile=profile.cov -repotoken $COVERALLS_TOKEN matrix: allow_failures: - go: tip env: global: secure: "GTrEtbp3sq14Jjz34pgIO0/Zv19YaDOOUJay4qnzGxs527HkW7YdsWENz0/yGHet+0jMOPatfP3uLaQHVFCNFZLfMYVmD5apMl7hPFrCaDZVvI9+ZwngIZ8gHzcf2Q+L6LxUT523ypjmRR+T1qYfbOy4UXlfGCyHFBbRB7AbMDk=" ================================================ FILE: vendor/github.com/masterzen/winrm/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/masterzen/winrm/Makefile ================================================ NO_COLOR=\033[0m OK_COLOR=\033[32;01m ERROR_COLOR=\033[31;01m WARN_COLOR=\033[33;01m DEPS = $(go list -f '{{range .TestImports}}{{.}} {{end}}' ./... | fgrep -v 'winrm') all: deps @mkdir -p bin/ @echo -e "$(OK_COLOR)==> Building$(NO_COLOR)" @go build -o $(GOPATH)/bin/winrm github.com/masterzen/winrm deps: @echo -e "$(OK_COLOR)==> Installing dependencies$(NO_COLOR)" @go get -d -v ./... @echo $(DEPS) | xargs -n1 go get -d updatedeps: go list ./... | xargs go list -f '{{join .Deps "\n"}}' | grep -v github.com/masterzen/winrm | sort -u | xargs go get -f -u -v clean: @rm -rf bin/ pkg/ src/ format: go fmt ./... ci: deps @echo -e "$(OK_COLOR)==> Testing with Coveralls...$(NO_COLOR)" "$(CURDIR)/scripts/test.sh" test: deps @echo -e "$(OK_COLOR)==> Testing...$(NO_COLOR)" go test ./... .PHONY: all clean deps format test updatedeps ================================================ FILE: vendor/github.com/masterzen/winrm/README.md ================================================ # WinRM for Go This is a Go library (and command-line executable) to execute remote commands on Windows machines through the use of WinRM/WinRS. _Note_: this library doesn't support domain users (it doesn't support GSSAPI nor Kerberos). It's primary target is to execute remote commands on EC2 windows machines. [![Build Status](https://travis-ci.org/masterzen/winrm.svg?branch=master)](https://travis-ci.org/masterzen/winrm) [![Coverage Status](https://coveralls.io/repos/masterzen/winrm/badge.png)](https://coveralls.io/r/masterzen/winrm) ## Contact - Bugs: https://github.com/masterzen/winrm/issues ## Getting Started WinRM is available on Windows Server 2008 and up. This project natively supports basic authentication for local accounts, see the steps in the next section on how to prepare the remote Windows machine for this scenario. The authentication model is pluggable, see below for an example on using Negotiate/NTLM authentication (e.g. for connecting to vanilla Azure VMs). ### Preparing the remote Windows machine for Basic authentication This project supports only basic authentication for local accounts (domain users are not supported). The remote windows system must be prepared for winrm: _For a PowerShell script to do what is described below in one go, check [Richard Downer's blog](http://www.frontiertown.co.uk/2011/12/overthere-control-windows-from-java/)_ On the remote host, open a Command Prompt (not a PowerShell prompt!) using the __Run as Administrator__ option and paste in the following lines: winrm quickconfig y winrm set winrm/config/service/Auth @{Basic="true"} winrm set winrm/config/service @{AllowUnencrypted="true"} winrm set winrm/config/winrs @{MaxMemoryPerShellMB="1024"} __N.B.:__ The Windows Firewall needs to be running to run this command. See [Microsoft Knowledge Base article #2004640](http://support.microsoft.com/kb/2004640). __N.B.:__ Do not disable Negotiate authentication as the `winrm` command itself uses this for internal authentication, and you risk getting a system where `winrm` doesn't work anymore. __N.B.:__ The `MaxMemoryPerShellMB` option has no effects on some Windows 2008R2 systems because of a WinRM bug. Make sure to install the hotfix described [Microsoft Knowledge Base article #2842230](http://support.microsoft.com/kb/2842230) if you need to run commands that uses more than 150MB of memory. For more information on WinRM, please refer to the online documentation at Microsoft's DevCenter. ### Building the winrm go and executable You can build winrm from source: ```sh git clone https://github.com/masterzen/winrm cd winrm make ``` This will generate a binary in the base directory called `./winrm`. _Note_: this winrm code doesn't depend anymore on [Gokogiri](https://github.com/moovweb/gokogiri) which means it is now in pure Go. _Note_: you need go 1.1+. Please check your installation with ``` go version ``` ## Command-line usage Once built, you can run remote commands like this: ```sh ./winrm -hostname remote.domain.com -username "Administrator" -password "secret" "ipconfig /all" ``` ## Library Usage **Warning the API might be subject to change.** For the fast version (this doesn't allow to send input to the command): ```go import "github.com/masterzen/winrm/winrm" client := winrm.NewClient("localhost", "Administrator", "secret") client.Run("ipconfig /all", os.Stdout, os.Stderr) ``` or ```go import ( "github.com/masterzen/winrm/winrm" "fmt" "os" ) client, err := winrm.NewClient(&winrm.Endpoint{Host: "localhost", Port: 5985, HTTPS: false, Insecure: false}, "Administrator", "secret") if err != nil { fmt.Println(err) } run, err := client.RunWithInput("ipconfig /all", os.Stdout, os.Stderr, os.Stdin) if err != nil { fmt.Println(err) } fmt.Println(run) ``` For a more complex example, it is possible to call the various functions directly: ```go import ( "github.com/masterzen/winrm/winrm" "fmt" "bytes" "os" ) stdin := bytes.NewBufferString("ipconfig /all") client := winrm.NewClient(&winrm.Endpoint{Host: "localhost", Port: 5985, HTTPS: false, Insecure: false}, "Administrator", "secret") shell, err := client.CreateShell() if err != nil { fmt.Printf("Impossible to create shell %s\n", err) os.Exit(1) } var cmd *Command cmd, err = shell.Execute("cmd.exe") if err != nil { fmt.Printf("Impossible to create Command %s\n", err) os.Exit(1) } go io.Copy(cmd.Stdin, &stdin) go io.Copy(os.Stdout, cmd.Stdout) go io.Copy(os.Stderr, cmd.Stderr) cmd.Wait() shell.Close() ``` ### Pluggable authentication example: Negotiate/NTLM authentication Using the winrm.Parameters.TransportDecorator, it is possible to wrap or completely replace the outgoing http.RoundTripper. For example, use github.com/paulmey/go-ntlmssp to plug in Negotiate/NTLM authentication : ```go import ( "github.com/masterzen/winrm/winrm" "github.com/paulmey/go-ntlmssp" ) params := winrm.DefaultParameters() params.TransportDecorator = func(t *http.Transport) http.RoundTripper { return ntlmssp.Negotiator{t} } client, err := winrm.NewClientWithParameters(..., params) ``` ## Developing on WinRM If you wish to work on `winrm` itself, you'll first need [Go](http://golang.org) installed (version 1.1+ is _required_). Make sure you have Go properly installed, including setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH). For some additional dependencies, Go needs [Mercurial](http://mercurial.selenic.com/) and [Bazaar](http://bazaar.canonical.com/en/) to be installed. Winrm itself doesn't require these, but a dependency of a dependency does. Next, clone this repository into `$GOPATH/src/github.com/masterzen/winrm` and then just type `make`. In a few moments, you'll have a working `winrm` executable: ``` $ make ... $ bin/winrm ... ``` 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. When new dependencies are added to winrm you can use `make updatedeps` to get the latest and subsequently use `make` to compile and generate the `winrm` binary. ================================================ FILE: vendor/github.com/masterzen/winrm/development/Vagrantfile ================================================ # -*- mode: ruby -*- # vi: set ft=ruby : # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # All Vagrant configuration is done here. The most common configuration # options are documented and commented below. For a complete reference, # please see the online documentation at vagrantup.com. # Every Vagrant virtual environment requires a box to build off of. config.vm.box = "kensykora/windows_2012_r2_standard" config.vm.guest = :windows config.vm.communicator = "winrm" config.vm.network :forwarded_port, guest: 5985, host: 5985, id: "winrm", auto_correct: true config.vm.provider "virtualbox" do |v| v.customize ["modifyvm", :id, "--vram", "128"] v.gui = true end end ================================================ FILE: vendor/github.com/masterzen/winrm/development/sample_requests.txt ================================================ http://localhost:5985/wsman http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 153600 PT60S uuid:c0fb2e4a-b066-4649-618b-5897f91acafd http://schemas.xmlsoap.org/ws/2004/09/transfer/Create http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd FALSE 65001 stdin stdout stderr http://localhost:5985/wsman http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 153600 PT60S uuid:05ea1914-c6dd-423d-5dac-c0e3b1ba056f http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command 0179DFE0-5409-4F07-946E-54635608A269 http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd TRUE FALSE "powershell.exe -EncodedCommand ZGly" http://localhost:5985/wsman http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 153600 PT60S uuid:eccb3559-1a6e-44fc-5cfb-ab2e2a95300b http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive C64C758B-1A01-447D-A7BB-F85FD1E88148 http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd stdout stderr http://localhost:5985/wsman http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 153600 PT60S uuid:ff1fcd4b-3f7a-4732-62e1-2afa9fbfd344 http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete D24CE524-7FDD-481F-8824-87A2CC6A80AE http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd http://localhost:5985/wsman http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 153600 uuid:BE57E710-1E58-4955-AD2B-FF841ED3F52B PT5M0S http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signal 0179DFE0-5409-4F07-946E-54635608A269 http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate ================================================ FILE: vendor/github.com/masterzen/winrm/development/winrm-tests.sh ================================================ #!/bin/bash echo "==> Running commands using WinRM against a Vagrant machine:" echo echo "==> What's my execution policy?" winrm "powershell -command \"get-executionpolicy\"" echo "==> Whoami?" winrm "whoami" ================================================ FILE: vendor/github.com/masterzen/winrm/scripts/test.sh ================================================ #!/bin/bash set -e go test -v ./... mkdir -p .cover go list ./... | xargs -I% bash -c 'name="%"; go test -covermode=count % --coverprofile=.cover/${name//\//_} ' echo "mode: count" > profile.cov cat .cover/* | grep -v mode >> profile.cov rm -rf .cover go tool cover -func=profile.cov ================================================ FILE: vendor/github.com/masterzen/winrm/soap/header.go ================================================ package soap import ( "github.com/masterzen/simplexml/dom" "strconv" ) type HeaderOption struct { key string value string } func NewHeaderOption(name string, value string) *HeaderOption { return &HeaderOption{key: name, value: value} } type SoapHeader struct { to string replyTo string maxEnvelopeSize string timeout string locale string id string action string shellId string resourceURI string options []HeaderOption message *SoapMessage } type HeaderBuilder interface { To(string) *SoapHeader ReplyTo(string) *SoapHeader MaxEnvelopeSize(int) *SoapHeader Timeout(string) *SoapHeader Locale(string) *SoapHeader Id(string) *SoapHeader Action(string) *SoapHeader ShellId(string) *SoapHeader resourceURI(string) *SoapHeader AddOption(*HeaderOption) *SoapHeader Options([]HeaderOption) *SoapHeader Build(*SoapMessage) *SoapMessage } func (self *SoapHeader) To(uri string) *SoapHeader { self.to = uri return self } func (self *SoapHeader) ReplyTo(uri string) *SoapHeader { self.replyTo = uri return self } func (self *SoapHeader) MaxEnvelopeSize(size int) *SoapHeader { self.maxEnvelopeSize = strconv.Itoa(size) return self } func (self *SoapHeader) Timeout(timeout string) *SoapHeader { self.timeout = timeout return self } func (self *SoapHeader) Id(id string) *SoapHeader { self.id = id return self } func (self *SoapHeader) Action(action string) *SoapHeader { self.action = action return self } func (self *SoapHeader) Locale(locale string) *SoapHeader { self.locale = locale return self } func (self *SoapHeader) ShellId(shellId string) *SoapHeader { self.shellId = shellId return self } func (self *SoapHeader) ResourceURI(resourceURI string) *SoapHeader { self.resourceURI = resourceURI return self } func (self *SoapHeader) AddOption(option *HeaderOption) *SoapHeader { self.options = append(self.options, *option) return self } func (self *SoapHeader) Options(options []HeaderOption) *SoapHeader { self.options = options return self } func (self *SoapHeader) Build() *SoapMessage { header := self.createElement(self.message.envelope, "Header", NS_SOAP_ENV) if self.to != "" { to := self.createElement(header, "To", NS_ADDRESSING) to.SetContent(self.to) } if self.replyTo != "" { replyTo := self.createElement(header, "ReplyTo", NS_ADDRESSING) a := self.createMUElement(replyTo, "Address", NS_ADDRESSING, true) a.SetContent(self.replyTo) } if self.maxEnvelopeSize != "" { envelope := self.createMUElement(header, "MaxEnvelopeSize", NS_WSMAN_DMTF, true) envelope.SetContent(self.maxEnvelopeSize) } if self.timeout != "" { timeout := self.createElement(header, "OperationTimeout", NS_WSMAN_DMTF) timeout.SetContent(self.timeout) } if self.id != "" { id := self.createElement(header, "MessageID", NS_ADDRESSING) id.SetContent(self.id) } if self.locale != "" { locale := self.createMUElement(header, "Locale", NS_WSMAN_DMTF, false) locale.SetAttr("xml:lang", self.locale) datalocale := self.createMUElement(header, "DataLocale", NS_WSMAN_MSFT, false) datalocale.SetAttr("xml:lang", self.locale) } if self.action != "" { action := self.createMUElement(header, "Action", NS_ADDRESSING, true) action.SetContent(self.action) } if self.shellId != "" { selectorSet := self.createElement(header, "SelectorSet", NS_WSMAN_DMTF) selector := self.createElement(selectorSet, "Selector", NS_WSMAN_DMTF) selector.SetAttr("Name", "ShellId") selector.SetContent(self.shellId) } if self.resourceURI != "" { resource := self.createMUElement(header, "ResourceURI", NS_WSMAN_DMTF, true) resource.SetContent(self.resourceURI) } if len(self.options) > 0 { set := self.createElement(header, "OptionSet", NS_WSMAN_DMTF) for _, option := range self.options { e := self.createElement(set, "Option", NS_WSMAN_DMTF) e.SetAttr("Name", option.key) e.SetContent(option.value) } } return self.message } func (self *SoapHeader) createElement(parent *dom.Element, name string, ns dom.Namespace) (element *dom.Element) { element = dom.CreateElement(name) parent.AddChild(element) ns.SetTo(element) return } func (self *SoapHeader) createMUElement(parent *dom.Element, name string, ns dom.Namespace, mustUnderstand bool) (element *dom.Element) { element = self.createElement(parent, name, ns) value := "false" if mustUnderstand { value = "true" } element.SetAttr("mustUnderstand", value) return } ================================================ FILE: vendor/github.com/masterzen/winrm/soap/header_test.go ================================================ package soap import ( "github.com/masterzen/simplexml/dom" . "gopkg.in/check.v1" "testing" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } type MySuite struct{} var _ = Suite(&MySuite{}) func initDocument() (h *SoapHeader) { doc := dom.CreateDocument() doc.PrettyPrint = true e := dom.CreateElement("Envelope") doc.SetRoot(e) AddUsualNamespaces(e) NS_SOAP_ENV.SetTo(e) h = &SoapHeader{message: &SoapMessage{document: doc, envelope: e}} return } func (s *MySuite) TestHeaderBuild(c *C) { h := initDocument() msg := h.To("http://winrm:5985/wsman").ReplyTo("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous").MaxEnvelopeSize(153600).Id("1-2-3-4").Locale("en_US").Timeout("PT60S").Build() expected := ` http://winrm:5985/wsman http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous 153600 PT60S 1-2-3-4 ` c.Check(msg.String(), Equals, expected) } ================================================ FILE: vendor/github.com/masterzen/winrm/soap/message.go ================================================ package soap import ( "github.com/masterzen/simplexml/dom" ) type SoapMessage struct { document *dom.Document envelope *dom.Element header *SoapHeader body *dom.Element } type MessageBuilder interface { SetBody(*dom.Element) NewBody() *dom.Element CreateElement(*dom.Element, string, dom.Namespace) *dom.Element CreateBodyElement(string, dom.Namespace) *dom.Element Header() *SoapHeader Doc() *dom.Document Free() String() string } func NewMessage() (message *SoapMessage) { doc := dom.CreateDocument() e := dom.CreateElement("Envelope") doc.SetRoot(e) AddUsualNamespaces(e) NS_SOAP_ENV.SetTo(e) message = &SoapMessage{document: doc, envelope: e} return } func (message *SoapMessage) NewBody() (body *dom.Element) { body = dom.CreateElement("Body") message.envelope.AddChild(body) NS_SOAP_ENV.SetTo(body) return } func (message *SoapMessage) String() string { return message.document.String() } func (message *SoapMessage) Doc() *dom.Document { return message.document } func (message *SoapMessage) Free() { } func (message *SoapMessage) CreateElement(parent *dom.Element, name string, ns dom.Namespace) (element *dom.Element) { element = dom.CreateElement(name) parent.AddChild(element) ns.SetTo(element) return } func (message *SoapMessage) CreateBodyElement(name string, ns dom.Namespace) (element *dom.Element) { if message.body == nil { message.body = message.NewBody() } return message.CreateElement(message.body, name, ns) } func (message *SoapMessage) Header() *SoapHeader { if message.header == nil { message.header = &SoapHeader{message: message} } return message.header } ================================================ FILE: vendor/github.com/masterzen/winrm/soap/namespaces.go ================================================ package soap import ( "github.com/masterzen/simplexml/dom" "github.com/masterzen/xmlpath" ) var ( NS_SOAP_ENV = dom.Namespace{"env", "http://www.w3.org/2003/05/soap-envelope"} NS_ADDRESSING = dom.Namespace{"a", "http://schemas.xmlsoap.org/ws/2004/08/addressing"} NS_CIMBINDING = dom.Namespace{"b", "http://schemas.dmtf.org/wbem/wsman/1/cimbinding.xsd"} NS_ENUM = dom.Namespace{"n", "http://schemas.xmlsoap.org/ws/2004/09/enumeration"} NS_TRANSFER = dom.Namespace{"x", "http://schemas.xmlsoap.org/ws/2004/09/transfer"} NS_WSMAN_DMTF = dom.Namespace{"w", "http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd"} NS_WSMAN_MSFT = dom.Namespace{"p", "http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd"} NS_SCHEMA_INST = dom.Namespace{"xsi", "http://www.w3.org/2001/XMLSchema-instance"} NS_WIN_SHELL = dom.Namespace{"rsp", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell"} NS_WSMAN_FAULT = dom.Namespace{"f", "http://schemas.microsoft.com/wbem/wsman/1/wsmanfault"} ) var MostUsed = [...]dom.Namespace{NS_SOAP_ENV, NS_ADDRESSING, NS_WIN_SHELL, NS_WSMAN_DMTF, NS_WSMAN_MSFT} func AddUsualNamespaces(node *dom.Element) { for _, ns := range MostUsed { node.DeclareNamespace(ns) } } func GetAllNamespaces() []xmlpath.Namespace { var ns = []dom.Namespace{NS_WIN_SHELL, NS_ADDRESSING, NS_WSMAN_DMTF, NS_WSMAN_MSFT, NS_SOAP_ENV} var xmlpathNs = make([]xmlpath.Namespace, 0, 4) for _, namespace := range ns { xmlpathNs = append(xmlpathNs, xmlpath.Namespace{Prefix: namespace.Prefix, Uri: namespace.Uri}) } return xmlpathNs } ================================================ FILE: vendor/github.com/masterzen/winrm/soap/namespaces_test.go ================================================ package soap import ( "github.com/masterzen/simplexml/dom" "testing" ) func TestAddUsualNamespaces(t *testing.T) { doc := dom.CreateDocument() root := dom.CreateElement("root") doc.SetRoot(root) AddUsualNamespaces(root) for ns := range root.DeclaredNamespaces() { found := false for ns2 := range MostUsed { if ns2 == ns { found = true } } if !found { t.Errorf("Test failed - Namespace %s not found", ns) } } } func TestSetTo(t *testing.T) { doc := dom.CreateDocument() root := dom.CreateElement("root") doc.SetRoot(root) NS_SOAP_ENV.SetTo(root) if root.String() != `` { t.Errorf("Test failed - root has not the correct NS: %s", root.String()) } } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/client.go ================================================ package winrm import ( "bytes" "crypto/tls" "crypto/x509" "fmt" "io" "net/http" "github.com/masterzen/winrm/soap" ) type Client struct { Parameters username string password string useHTTPS bool url string http HttpPost transport http.RoundTripper } // NewClient will create a new remote client on url, connecting with user and password // This function doesn't connect (connection happens only when CreateShell is called) func NewClient(endpoint *Endpoint, user, password string) (client *Client, err error) { params := DefaultParameters() client, err = NewClientWithParameters(endpoint, user, password, params) return } // NewClient will create a new remote client on url, connecting with user and password // This function doesn't connect (connection happens only when CreateShell is called) func NewClientWithParameters(endpoint *Endpoint, user, password string, params *Parameters) (client *Client, err error) { transport, err := newTransport(endpoint) client = &Client{ Parameters: *params, username: user, password: password, url: endpoint.url(), http: Http_post, useHTTPS: endpoint.HTTPS, transport: transport, } if params.TransportDecorator != nil { client.transport = params.TransportDecorator(transport) } return } // newTransport will create a new HTTP Transport, with options specified within the endpoint configuration func newTransport(endpoint *Endpoint) (*http.Transport, error) { transport := &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: endpoint.Insecure, }, } if endpoint.CACert != nil && len(*endpoint.CACert) > 0 { certPool, err := readCACerts(endpoint.CACert) if err != nil { return nil, err } transport.TLSClientConfig.RootCAs = certPool } return transport, nil } func readCACerts(certs *[]byte) (*x509.CertPool, error) { certPool := x509.NewCertPool() if !certPool.AppendCertsFromPEM(*certs) { return nil, fmt.Errorf("Unable to read certificates") } return certPool, nil } // CreateShell will create a WinRM Shell, which is the prealable for running // commands. func (client *Client) CreateShell() (shell *Shell, err error) { request := NewOpenShellRequest(client.url, &client.Parameters) defer request.Free() response, err := client.sendRequest(request) if err == nil { var shellId string if shellId, err = ParseOpenShellResponse(response); err == nil { shell = &Shell{client: client, ShellId: shellId} } } return } // NewShell will create a new WinRM Shell for the given shellID func (client *Client) NewShell(shellID string) *Shell { return &Shell{client: client, ShellId: shellID} } func (client *Client) sendRequest(request *soap.SoapMessage) (response string, err error) { return client.http(client, request) } // Run will run command on the the remote host, writing the process stdout and stderr to // the given writers. Note with this method it isn't possible to inject stdin. func (client *Client) Run(command string, stdout io.Writer, stderr io.Writer) (exitCode int, err error) { shell, err := client.CreateShell() if err != nil { return 0, err } var cmd *Command cmd, err = shell.Execute(command) if err != nil { return 0, err } go io.Copy(stdout, cmd.Stdout) go io.Copy(stderr, cmd.Stderr) cmd.Wait() shell.Close() return cmd.ExitCode(), cmd.err } // Run will run command on the the remote host, returning the process stdout and stderr // as strings, and using the input stdin string as the process input func (client *Client) RunWithString(command string, stdin string) (stdout string, stderr string, exitCode int, err error) { shell, err := client.CreateShell() if err != nil { return "", "", 0, err } defer shell.Close() var cmd *Command cmd, err = shell.Execute(command) if err != nil { return "", "", 0, err } if len(stdin) > 0 { cmd.Stdin.Write([]byte(stdin)) } var outWriter, errWriter bytes.Buffer go io.Copy(&outWriter, cmd.Stdout) go io.Copy(&errWriter, cmd.Stderr) cmd.Wait() return outWriter.String(), errWriter.String(), cmd.ExitCode(), cmd.err } // Run will run command on the the remote host, writing the process stdout and stderr to // the given writers, and injecting the process stdin with the stdin reader. // Warning stdin (not stdout/stderr) are bufferized, which means reading only one byte in stdin will // send a winrm http packet to the remote host. If stdin is a pipe, it might be better for // performance reasons to buffer it. func (client *Client) RunWithInput(command string, stdout io.Writer, stderr io.Writer, stdin io.Reader) (exitCode int, err error) { shell, err := client.CreateShell() if err != nil { return 0, err } defer shell.Close() var cmd *Command cmd, err = shell.Execute(command) if err != nil { return 0, err } go io.Copy(cmd.Stdin, stdin) go io.Copy(stdout, cmd.Stdout) go io.Copy(stderr, cmd.Stderr) cmd.Wait() return cmd.ExitCode(), cmd.err } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/client_test.go ================================================ package winrm import ( "github.com/masterzen/winrm/soap" . "gopkg.in/check.v1" "io/ioutil" "net/http" "strings" ) func (s *WinRMSuite) TestNewClient(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) c.Assert(client.url, Equals, "http://localhost:5985/wsman") c.Assert(client.username, Equals, "Administrator") c.Assert(client.password, Equals, "v3r1S3cre7") } func (s *WinRMSuite) TestClientCreateShell(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) client.http = func(client *Client, message *soap.SoapMessage) (string, error) { c.Assert(message.String(), Contains, "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create") return createShellResponse, nil } shell, _ := client.CreateShell() c.Assert(shell.ShellId, Equals, "67A74734-DD32-4F10-89DE-49A060483810") } func (s *WinRMSuite) TestReplaceTransportWithDecorator(c *C) { var myrt rtfunc = func(req *http.Request) (*http.Response, error) { req.Body.Close() return &http.Response{StatusCode: 500, Body: ioutil.NopCloser(strings.NewReader("yeehaw"))}, nil } params := DefaultParameters() params.TransportDecorator = func(*http.Transport) http.RoundTripper { return myrt } client, err := NewClientWithParameters(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "password", params) c.Assert(err, IsNil) _, err = client.http(client, soap.NewMessage()) c.Assert(err.Error(), Equals, "http error: 500 - yeehaw") } type rtfunc func(*http.Request) (*http.Response, error) func (f rtfunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/command.go ================================================ package winrm import ( "bytes" "errors" "io" "strings" ) type commandWriter struct { *Command eof bool } type commandReader struct { *Command write *io.PipeWriter read *io.PipeReader stream string } // Command represents a given command running on a Shell. This structure allows to get access // to the various stdout, stderr and stdin pipes. type Command struct { client *Client shell *Shell commandId string exitCode int finished bool err error Stdin *commandWriter Stdout *commandReader Stderr *commandReader done chan struct{} cancel chan struct{} } func newCommand(shell *Shell, commandId string) *Command { command := &Command{shell: shell, client: shell.client, commandId: commandId, exitCode: 1, err: nil, done: make(chan struct{}), cancel: make(chan struct{})} command.Stdin = &commandWriter{Command: command, eof: false} command.Stdout = newCommandReader("stdout", command) command.Stderr = newCommandReader("stderr", command) go fetchOutput(command) return command } func newCommandReader(stream string, command *Command) *commandReader { read, write := io.Pipe() return &commandReader{Command: command, stream: stream, write: write, read: read} } func fetchOutput(command *Command) { for { select { case <-command.cancel: close(command.done) return default: finished, err := command.slurpAllOutput() if finished { command.err = err close(command.done) return } } } } func (command *Command) check() (err error) { if command.commandId == "" { return errors.New("Command has already been closed") } if command.shell == nil { return errors.New("Command has no associated shell") } if command.client == nil { return errors.New("Command has no associated client") } return } // Close will terminate the running command func (command *Command) Close() (err error) { if err = command.check(); err != nil { return err } select { // close cancel channel if it's still open case <-command.cancel: default: close(command.cancel) } request := NewSignalRequest(command.client.url, command.shell.ShellId, command.commandId, &command.client.Parameters) defer request.Free() _, err = command.client.sendRequest(request) return err } func (command *Command) slurpAllOutput() (finished bool, err error) { if err = command.check(); err != nil { command.Stderr.write.CloseWithError(err) command.Stdout.write.CloseWithError(err) return true, err } request := NewGetOutputRequest(command.client.url, command.shell.ShellId, command.commandId, "stdout stderr", &command.client.Parameters) defer request.Free() response, err := command.client.sendRequest(request) if err != nil { if strings.Contains(err.Error(), "OperationTimeout") { // Operation timeout because there was no command output return } command.Stderr.write.CloseWithError(err) command.Stdout.write.CloseWithError(err) return true, err } var exitCode int var stdout, stderr bytes.Buffer finished, exitCode, err = ParseSlurpOutputErrResponse(response, &stdout, &stderr) if err != nil { command.Stderr.write.CloseWithError(err) command.Stdout.write.CloseWithError(err) return true, err } if stdout.Len() > 0 { command.Stdout.write.Write(stdout.Bytes()) } if stderr.Len() > 0 { command.Stderr.write.Write(stderr.Bytes()) } if finished { command.exitCode = exitCode command.Stderr.write.Close() command.Stdout.write.Close() } return } func (command *Command) sendInput(data []byte) (err error) { if err = command.check(); err != nil { return err } request := NewSendInputRequest(command.client.url, command.shell.ShellId, command.commandId, data, &command.client.Parameters) defer request.Free() _, err = command.client.sendRequest(request) return } // ExitCode returns command exit code when it is finished. Before that the result is always 0. func (command *Command) ExitCode() int { return command.exitCode } // Calling this function will block the current goroutine until the remote command terminates. func (command *Command) Wait() { // block until finished <-command.done } // Write data to this Pipe func (w *commandWriter) Write(data []byte) (written int, err error) { for len(data) > 0 { if w.eof { err = io.EOF return } // never send more data than our EnvelopeSize. n := min(w.client.Parameters.EnvelopeSize-1000, len(data)) if err = w.sendInput(data[:n]); err != nil { break } data = data[n:] written += int(n) } return } func min(a int, b int) int { if a < b { return a } return b } func (w *commandWriter) Close() error { w.eof = true return w.Close() } // Read data from this Pipe func (r *commandReader) Read(buf []byte) (int, error) { n, err := r.read.Read(buf) if err != nil && err != io.EOF { return 0, err } return n, err } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/command_test.go ================================================ package winrm import ( "bytes" "io" "io/ioutil" "strings" "sync" "time" "github.com/masterzen/winrm/soap" . "gopkg.in/check.v1" ) func (s *WinRMSuite) TestExecuteCommand(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) shell := &Shell{client: client, ShellId: "67A74734-DD32-4F10-89DE-49A060483810"} count := 0 client.http = func(client *Client, message *soap.SoapMessage) (string, error) { switch count { case 0: { c.Assert(message.String(), Contains, "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command") count = 1 return executeCommandResponse, nil } case 1: { c.Assert(message.String(), Contains, "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive") count = 2 return outputResponse, nil } default: { return doneCommandResponse, nil } } } command, _ := shell.Execute("ipconfig /all") var stdout, stderr bytes.Buffer var wg sync.WaitGroup f := func(b *bytes.Buffer, r *commandReader) { wg.Add(1) defer wg.Done() io.Copy(b, r) } go f(&stdout, command.Stdout) go f(&stderr, command.Stderr) command.Wait() wg.Wait() c.Assert(stdout.String(), Equals, "That's all folks!!!") c.Assert(stderr.String(), Equals, "This is stderr, I'm pretty sure!") } func (s *WinRMSuite) TestStdinCommand(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) shell := &Shell{client: client, ShellId: "67A74734-DD32-4F10-89DE-49A060483810"} count := 0 client.http = func(client *Client, message *soap.SoapMessage) (string, error) { if strings.Contains(message.String(), "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send") { c.Assert(message.String(), Contains, "c3RhbmRhcmQgaW5wdXQ=") return "", nil } else { if strings.Contains(message.String(), "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command") { return executeCommandResponse, nil } else if count != 1 && strings.Contains(message.String(), "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive") { count = 1 return outputResponse, nil } else { return doneCommandResponse, nil } } } command, _ := shell.Execute("ipconfig /all") command.Stdin.Write([]byte("standard input")) // slurp output from command var outWriter, errWriter bytes.Buffer go io.Copy(&outWriter, command.Stdout) go io.Copy(&errWriter, command.Stderr) command.Wait() } func (s *WinRMSuite) TestCommandExitCode(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) shell := &Shell{client: client, ShellId: "67A74734-DD32-4F10-89DE-49A060483810"} count := 0 client.http = func(client *Client, message *soap.SoapMessage) (string, error) { defer func() { count += 1 }() switch count { case 0: return executeCommandResponse, nil case 1: return doneCommandResponse, nil default: c.Log("Mimicking some observed Windows behavior where only the first 'done' response has the actual exit code and 0 afterwards") return doneCommandExitCode0Response, nil } } command, _ := shell.Execute("ipconfig /all") command.Wait() <-time.After(time.Second) // to make the test fail if fetchOutput races to re-set the exit code c.Assert(command.ExitCode(), Equals, 123) } func (s *WinRMSuite) TestCloseCommandStopsFetch(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) shell := &Shell{client: client, ShellId: "67A74734-DD32-4F10-89DE-49A060483810"} http := make(chan string) client.http = func(client *Client, message *soap.SoapMessage) (string, error) { switch { case strings.Contains(message.String(), "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive"): c.Log("Request for command output received by server") r := <-http c.Log("Returning command output") return r, nil case strings.Contains(message.String(), "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command"): return executeCommandResponse, nil case strings.Contains(message.String(), "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signal"): c.Log("Signal message received by server") return "", nil // response is not used default: c.Logf("Unexpected message: %s", message) return "", nil } } command, _ := shell.Execute("ipconfig /all") // need to be reading Stdout/Stderr, otherwise, the writes to these are blocking... go ioutil.ReadAll(command.Stdout) go ioutil.ReadAll(command.Stderr) http <- outputResponse // wait for command to enter fetch/slurp command.Close() select { case http <- outputResponse: // return to fetch from slurp c.Log("Fetch loop 'drained' one last reponse before realizing that the command is now closed") case <-time.After(1 * time.Second): c.Log("no poll within one second, fetch may have stopped") } select { case http <- outputResponse: c.Log("Fetch loop is still polling after command.Close()") c.FailNow() case <-time.After(1 * time.Second): c.Log("no poll within one second, assuming fetch has stopped") } } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/endpoint.go ================================================ package winrm import "fmt" type Endpoint struct { Host string Port int HTTPS bool Insecure bool CACert *[]byte } func (ep *Endpoint) url() string { var scheme string if ep.HTTPS { scheme = "https" } else { scheme = "http" } return fmt.Sprintf("%s://%s:%d/wsman", scheme, ep.Host, ep.Port) } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/endpoint_test.go ================================================ package winrm import ( . "gopkg.in/check.v1" ) func (s *WinRMSuite) TestEndpointUrlHttp(c *C) { endpoint := &Endpoint{Host: "abc", Port: 123} c.Assert(endpoint.url(), Equals, "http://abc:123/wsman") } func (s *WinRMSuite) TestEndpointUrlHttps(c *C) { endpoint := &Endpoint{Host: "abc", Port: 123, HTTPS: true} c.Assert(endpoint.url(), Equals, "https://abc:123/wsman") } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/fixture_test.go ================================================ package winrm import ( "fmt" . "gopkg.in/check.v1" "strings" ) var ( createShellResponse = ` http://schemas.xmlsoap.org/ws/2004/09/transfer/CreateResponse uuid:195078CF-804B-41F7-A246-9CB3C1A41A9A http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous uuid:D00059E8-57D6-4035-AD8D-3EDC495DA163 http://107.20.128.235:5985/wsman http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd 67A74734-DD32-4F10-89DE-49A060483810 67A74734-DD32-4F10-89DE-49A060483810 http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd Administrator 213.41.177.193 PT7200.000S stdin stdout stderr P0DT0H0M1S P0DT0H0M1S ` executeCommandResponse = `http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandResponseuuid:D9E108AA-E32B-45E3-8601-E9C70999D3BAhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousuuid:F530804C-6D02-4FA9-AE78-1997750594BA1A6DEE6B-EC68-4DD6-87E9-030C0048ECC4` outputResponse = `http://schemas.microsoft.com/wbem/wsman/1/windows/shell/ReceiveResponseuuid:AAD46BD4-6315-4C3C-93D4-94A55773287Dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousuuid:18A52A06-9027-41DC-8850-3F244595AF62VGhhdCdzIGFsbCBmb2xrcyEhIQ==VGhpcyBpcyBzdGRlcnIsIEknbSBwcmV0dHkgc3VyZSE=` singleOutputResponse = `http://schemas.microsoft.com/wbem/wsman/1/windows/shell/ReceiveResponseuuid:AAD46BD4-6315-4C3C-93D4-94A55773287Dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousuuid:18A52A06-9027-41DC-8850-3F244595AF62VGhhdCdzIGFsbCBmb2xrcyEhIQ==` doneCommandResponse = `http://schemas.microsoft.com/wbem/wsman/1/windows/shell/ReceiveResponseuuid:206F8145-683D-4987-949B-E099F999F088http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousuuid:6c68191c-8385-4816-506a-0769cb9f3f4e123 ` doneCommandExitCode0Response = `http://schemas.microsoft.com/wbem/wsman/1/windows/shell/ReceiveResponseuuid:206F8145-683D-4987-949B-E099F999F088http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousuuid:6c68191c-8385-4816-506a-0769cb9f3f4e0` ) type containsChecker struct { *CheckerInfo } // The Contains checker verifies that the obtained value contains // the expected value, according to usual Go semantics for strings.Contains. // // For example: // // c.Assert(haystack, Contains, "needle") // var Contains Checker = &containsChecker{ &CheckerInfo{Name: "contains", Params: []string{"obtained", "expected"}}, } func (checker *containsChecker) Check(params []interface{}, names []string) (result bool, error string) { return matches(params[0], params[1]) } func matches(haystack, needle interface{}) (result bool, error string) { neStr, ok := needle.(string) if !ok { return false, "Expected value must be a string" } valueStr, valueIsStr := haystack.(string) if !valueIsStr { if valueWithStr, valueHasStr := haystack.(fmt.Stringer); valueHasStr { valueStr, valueIsStr = valueWithStr.String(), true } } if valueIsStr { return strings.Contains(valueStr, neStr), "" } return false, "Obtained value is not a string and has no .String()" } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/http.go ================================================ package winrm import ( "fmt" "io/ioutil" "net/http" "strings" "github.com/masterzen/winrm/soap" ) var soapXML string = "application/soap+xml" type HttpPost func(*Client, *soap.SoapMessage) (string, error) func body(response *http.Response) (content string, err error) { contentType := response.Header.Get("Content-Type") if strings.HasPrefix(contentType, soapXML) { var body []byte body, err = ioutil.ReadAll(response.Body) response.Body.Close() if err != nil { err = fmt.Errorf("error while reading request body %s", err) return } content = string(body) return } else { err = fmt.Errorf("invalid content-type: %s", contentType) return } return } func Http_post(client *Client, request *soap.SoapMessage) (response string, err error) { httpClient := &http.Client{Transport: client.transport} req, err := http.NewRequest("POST", client.url, strings.NewReader(request.String())) if err != nil { err = fmt.Errorf("impossible to create http request %s", err) return } req.Header.Set("Content-Type", soapXML+";charset=UTF-8") req.SetBasicAuth(client.username, client.password) resp, err := httpClient.Do(req) if err != nil { err = fmt.Errorf("unknown error %s", err) return } if resp.StatusCode == 200 { response, err = body(resp) } else { body, _ := ioutil.ReadAll(resp.Body) err = fmt.Errorf("http error: %d - %s", resp.StatusCode, body) } return } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/http_test.go ================================================ package winrm import ( "net" "net/http" "net/http/httptest" . "gopkg.in/check.v1" ) var response = ` http://schemas.xmlsoap.org/ws/2004/09/transfer/CreateResponse uuid:195078CF-804B-41F7-A246-9CB3C1A41A9A http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous uuid:D00059E8-57D6-4035-AD8D-3EDC495DA163 http://107.20.128.235:15985/wsman http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd 67A74734-DD32-4F10-89DE-49A060483810 67A74734-DD32-4F10-89DE-49A060483810 http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd Administrator 213.41.177.193 PT7200.000S stdin stdout stderr P0DT0H0M1S P0DT0H0M1S ` func (s *WinRMSuite) TestHttpRequest(c *C) { ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/soap+xml") w.Write([]byte(response)) })) l, err := net.Listen("tcp", "127.0.0.1:15985") if err != nil { c.Fatalf("Can't listen %s", err) } ts.Listener = l ts.Start() defer ts.Close() client, err := NewClient(&Endpoint{Host: "localhost", Port: 15985}, "test", "test") c.Assert(err, IsNil) shell, err := client.CreateShell() if err != nil { c.Fatalf("Can't create shell %s", err) } c.Assert(shell.ShellId, Equals, "67A74734-DD32-4F10-89DE-49A060483810") } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/parameters.go ================================================ package winrm import ( "net/http" ) type Parameters struct { Timeout string Locale string EnvelopeSize int TransportDecorator func(*http.Transport) http.RoundTripper } func DefaultParameters() *Parameters { return NewParameters("PT60S", "en-US", 153600) } func NewParameters(timeout string, locale string, envelopeSize int) *Parameters { return &Parameters{Timeout: timeout, Locale: locale, EnvelopeSize: envelopeSize} } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/parameters_test.go ================================================ package winrm import ( . "gopkg.in/check.v1" ) func (s *WinRMSuite) TestDefaultParameters(c *C) { params := DefaultParameters() c.Assert(params.Locale, Equals, "en-US") c.Assert(params.Timeout, Equals, "PT60S") c.Assert(params.EnvelopeSize, Equals, 153600) } func (s *WinRMSuite) TestParameters(c *C) { params := NewParameters("PT120S", "fr-FR", 128) c.Assert(params.Locale, Equals, "fr-FR") c.Assert(params.Timeout, Equals, "PT120S") c.Assert(params.EnvelopeSize, Equals, 128) } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/powershell.go ================================================ package winrm import ( "encoding/base64" "fmt" ) // Wraps a PowerShell script and prepares it for execution by the winrm client func Powershell(psCmd string) string { // 2 byte chars to make PowerShell happy wideCmd := "" for _, b := range []byte(psCmd) { wideCmd += string(b) + "\x00" } // Base64 encode the command input := []uint8(wideCmd) encodedCmd := base64.StdEncoding.EncodeToString(input) // Create the powershell.exe command line to execute the script return fmt.Sprintf("powershell.exe -EncodedCommand %s", encodedCmd) } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/powershell_test.go ================================================ package winrm import ( . "gopkg.in/check.v1" ) func (s *WinRMSuite) TestPowershell(c *C) { psCmd := Powershell("dir") c.Assert(psCmd, Equals, "powershell.exe -EncodedCommand ZABpAHIA") } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/request.go ================================================ package winrm import ( "encoding/base64" "github.com/masterzen/winrm/soap" "github.com/nu7hatch/gouuid" ) func genUUID() string { uuid, _ := uuid.NewV4() return "uuid:" + uuid.String() } func defaultHeaders(message *soap.SoapMessage, url string, params *Parameters) (h *soap.SoapHeader) { h = message.Header() h.To(url).ReplyTo("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous").MaxEnvelopeSize(params.EnvelopeSize).Id(genUUID()).Locale(params.Locale).Timeout(params.Timeout) return } func NewOpenShellRequest(uri string, params *Parameters) (message *soap.SoapMessage) { if params == nil { params = DefaultParameters() } message = soap.NewMessage() defaultHeaders(message, uri, params).Action("http://schemas.xmlsoap.org/ws/2004/09/transfer/Create").ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd").AddOption(soap.NewHeaderOption("WINRS_NOPROFILE", "FALSE")).AddOption(soap.NewHeaderOption("WINRS_CODEPAGE", "65001")).Build() body := message.CreateBodyElement("Shell", soap.NS_WIN_SHELL) input := message.CreateElement(body, "InputStreams", soap.NS_WIN_SHELL) input.SetContent("stdin") output := message.CreateElement(body, "OutputStreams", soap.NS_WIN_SHELL) output.SetContent("stdout stderr") return } func NewDeleteShellRequest(uri string, shellId string, params *Parameters) (message *soap.SoapMessage) { if params == nil { params = DefaultParameters() } message = soap.NewMessage() defaultHeaders(message, uri, params).Action("http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete").ShellId(shellId).ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd").Build() message.NewBody() return } func NewExecuteCommandRequest(uri, shellId, command string, arguments []string, params *Parameters) (message *soap.SoapMessage) { if params == nil { params = DefaultParameters() } message = soap.NewMessage() defaultHeaders(message, uri, params).Action("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command").ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd").ShellId(shellId).AddOption(soap.NewHeaderOption("WINRS_CONSOLEMODE_STDIN", "TRUE")).AddOption(soap.NewHeaderOption("WINRS_SKIP_CMD_SHELL", "FALSE")).Build() body := message.CreateBodyElement("CommandLine", soap.NS_WIN_SHELL) // ensure special characters like & don't mangle the request XML command = "" commandElement := message.CreateElement(body, "Command", soap.NS_WIN_SHELL) commandElement.SetContent(command) for _, arg := range arguments { arg = "" argumentsElement := message.CreateElement(body, "Arguments", soap.NS_WIN_SHELL) argumentsElement.SetContent(arg) } return } func NewGetOutputRequest(uri string, shellId string, commandId string, streams string, params *Parameters) (message *soap.SoapMessage) { if params == nil { params = DefaultParameters() } message = soap.NewMessage() defaultHeaders(message, uri, params).Action("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive").ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd").ShellId(shellId).Build() receive := message.CreateBodyElement("Receive", soap.NS_WIN_SHELL) desiredStreams := message.CreateElement(receive, "DesiredStream", soap.NS_WIN_SHELL) desiredStreams.SetAttr("CommandId", commandId) desiredStreams.SetContent(streams) return } func NewSendInputRequest(uri string, shellId string, commandId string, input []byte, params *Parameters) (message *soap.SoapMessage) { if params == nil { params = DefaultParameters() } message = soap.NewMessage() defaultHeaders(message, uri, params).Action("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send").ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd").ShellId(shellId).Build() content := base64.StdEncoding.EncodeToString(input) send := message.CreateBodyElement("Send", soap.NS_WIN_SHELL) streams := message.CreateElement(send, "Stream", soap.NS_WIN_SHELL) streams.SetAttr("Name", "stdin") streams.SetAttr("CommandId", commandId) streams.SetContent(content) return } func NewSignalRequest(uri string, shellId string, commandId string, params *Parameters) (message *soap.SoapMessage) { if params == nil { params = DefaultParameters() } message = soap.NewMessage() defaultHeaders(message, uri, params).Action("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signal").ResourceURI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd").ShellId(shellId).Build() signal := message.CreateBodyElement("Signal", soap.NS_WIN_SHELL) signal.SetAttr("CommandId", commandId) code := message.CreateElement(signal, "Code", soap.NS_WIN_SHELL) code.SetContent("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate") return } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/request_test.go ================================================ package winrm import ( "strings" "testing" "github.com/masterzen/simplexml/dom" "github.com/masterzen/winrm/soap" "github.com/masterzen/xmlpath" . "gopkg.in/check.v1" ) // Hook up gocheck into the "go test" runner. func Test(t *testing.T) { TestingT(t) } type WinRMSuite struct{} var _ = Suite(&WinRMSuite{}) func (s *WinRMSuite) TestOpenShellRequest(c *C) { openShell := NewOpenShellRequest("http://localhost", nil) defer openShell.Free() assertXPath(c, openShell.Doc(), "//a:Action", "http://schemas.xmlsoap.org/ws/2004/09/transfer/Create") assertXPath(c, openShell.Doc(), "//a:To", "http://localhost") assertXPath(c, openShell.Doc(), "//env:Body/rsp:Shell/rsp:InputStreams", "stdin") assertXPath(c, openShell.Doc(), "//env:Body/rsp:Shell/rsp:OutputStreams", "stdout stderr") } func (s *WinRMSuite) TestDeleteShellRequest(c *C) { request := NewDeleteShellRequest("http://localhost", "SHELLID", nil) defer request.Free() assertXPath(c, request.Doc(), "//a:Action", "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete") assertXPath(c, request.Doc(), "//a:To", "http://localhost") assertXPath(c, request.Doc(), "//w:Selector[@Name=\"ShellId\"]", "SHELLID") } func (s *WinRMSuite) TestExecuteCommandRequest(c *C) { request := NewExecuteCommandRequest("http://localhost", "SHELLID", "ipconfig /all", []string{}, nil) defer request.Free() assertXPath(c, request.Doc(), "//a:Action", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command") assertXPath(c, request.Doc(), "//a:To", "http://localhost") assertXPath(c, request.Doc(), "//w:Selector[@Name=\"ShellId\"]", "SHELLID") assertXPath(c, request.Doc(), "//w:Option[@Name=\"WINRS_CONSOLEMODE_STDIN\"]", "TRUE") assertXPath(c, request.Doc(), "//rsp:CommandLine/rsp:Command", "ipconfig /all") assertXPathNil(c, request.Doc(), "//rsp:CommandLine/rsp:Arguments") } func (s *WinRMSuite) TestExecuteCommandWithArgumentsRequest(c *C) { args := []string{"/p", "C:\\test.txt"} request := NewExecuteCommandRequest("http://localhost", "SHELLID", "del", args, nil) defer request.Free() assertXPath(c, request.Doc(), "//a:Action", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command") assertXPath(c, request.Doc(), "//a:To", "http://localhost") assertXPath(c, request.Doc(), "//w:Selector[@Name=\"ShellId\"]", "SHELLID") assertXPath(c, request.Doc(), "//w:Option[@Name=\"WINRS_CONSOLEMODE_STDIN\"]", "TRUE") assertXPath(c, request.Doc(), "//rsp:CommandLine/rsp:Command", "del") assertXPath(c, request.Doc(), "//rsp:CommandLine/rsp:Arguments", "/p") assertXPath(c, request.Doc(), "//rsp:CommandLine/rsp:Arguments", "C:\\test.txt") } func (s *WinRMSuite) TestGetOutputRequest(c *C) { request := NewGetOutputRequest("http://localhost", "SHELLID", "COMMANDID", "stdout stderr", nil) defer request.Free() assertXPath(c, request.Doc(), "//a:Action", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive") assertXPath(c, request.Doc(), "//a:To", "http://localhost") assertXPath(c, request.Doc(), "//w:Selector[@Name=\"ShellId\"]", "SHELLID") assertXPath(c, request.Doc(), "//rsp:Receive/rsp:DesiredStream[@CommandId=\"COMMANDID\"]", "stdout stderr") } func (s *WinRMSuite) TestSendInputRequest(c *C) { request := NewSendInputRequest("http://localhost", "SHELLID", "COMMANDID", []byte{31, 32}, nil) defer request.Free() assertXPath(c, request.Doc(), "//a:Action", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send") assertXPath(c, request.Doc(), "//a:To", "http://localhost") assertXPath(c, request.Doc(), "//w:Selector[@Name=\"ShellId\"]", "SHELLID") assertXPath(c, request.Doc(), "//rsp:Send/rsp:Stream[@CommandId=\"COMMANDID\"]", "HyA=") } func (s *WinRMSuite) TestSignalRequest(c *C) { request := NewSignalRequest("http://localhost", "SHELLID", "COMMANDID", nil) defer request.Free() assertXPath(c, request.Doc(), "//a:Action", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Signal") assertXPath(c, request.Doc(), "//a:To", "http://localhost") assertXPath(c, request.Doc(), "//w:Selector[@Name=\"ShellId\"]", "SHELLID") assertXPath(c, request.Doc(), "//rsp:Signal[@CommandId=\"COMMANDID\"]/rsp:Code", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate") } func assertXPath(c *C, doc *dom.Document, request string, expected string) { root, path, err := parseXPath(doc, request) if err != nil { c.Fatalf("Xpath %s gives error %s", request, err) } ok := path.Exists(root) c.Assert(ok, Equals, true) var foundValue string iter := path.Iter(root) for iter.Next() { foundValue = iter.Node().String() if foundValue == expected { break } } if foundValue != expected { c.Errorf("Should have found '%s', but found '%s' instead", expected, foundValue) } } func assertXPathNil(c *C, doc *dom.Document, request string) { root, path, err := parseXPath(doc, request) if err != nil { c.Fatalf("Xpath %s gives error %s", request, err) } ok := path.Exists(root) c.Assert(ok, Equals, false) } func parseXPath(doc *dom.Document, request string) (*xmlpath.Node, *xmlpath.Path, error) { content := strings.NewReader(doc.String()) node, err := xmlpath.Parse(content) if err != nil { return nil, nil, err } path, err := xmlpath.CompileWithNamespace(request, soap.GetAllNamespaces()) if err != nil { return nil, nil, err } return node, path, nil } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/response.go ================================================ package winrm import ( "encoding/base64" "fmt" "github.com/masterzen/winrm/soap" "github.com/masterzen/xmlpath" "io" "strconv" "strings" ) func first(node *xmlpath.Node, xpath string) (content string, err error) { path, err := xmlpath.CompileWithNamespace(xpath, soap.GetAllNamespaces()) if err != nil { return } content, _ = path.String(node) return } func any(node *xmlpath.Node, xpath string) (found bool, err error) { path, err := xmlpath.CompileWithNamespace(xpath, soap.GetAllNamespaces()) if err != nil { return } found = path.Exists(node) return } func xpath(node *xmlpath.Node, xpath string) (nodes []xmlpath.Node, err error) { path, err := xmlpath.CompileWithNamespace(xpath, soap.GetAllNamespaces()) if err != nil { return } nodes = make([]xmlpath.Node, 0, 1) iter := path.Iter(node) for iter.Next() { nodes = append(nodes, *(iter.Node())) } return } func ParseOpenShellResponse(response string) (shellId string, err error) { doc, err := xmlpath.Parse(strings.NewReader(response)) shellId, err = first(doc, "//w:Selector[@Name='ShellId']") return } func ParseExecuteCommandResponse(response string) (commandId string, err error) { doc, err := xmlpath.Parse(strings.NewReader(response)) commandId, err = first(doc, "//rsp:CommandId") return } func ParseSlurpOutputErrResponse(response string, stdout io.Writer, stderr io.Writer) (finished bool, exitCode int, err error) { doc, err := xmlpath.Parse(strings.NewReader(response)) stdouts, _ := xpath(doc, "//rsp:Stream[@Name='stdout']") for _, node := range stdouts { content, _ := base64.StdEncoding.DecodeString(node.String()) stdout.Write(content) } stderrs, _ := xpath(doc, "//rsp:Stream[@Name='stderr']") for _, node := range stderrs { content, _ := base64.StdEncoding.DecodeString(node.String()) stderr.Write(content) } ended, _ := any(doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']") if ended { finished = ended if exitBool, _ := any(doc, "//rsp:ExitCode"); exitBool { exit, _ := first(doc, "//rsp:ExitCode") exitCode, _ = strconv.Atoi(exit) } } else { finished = false } return } func ParseSlurpOutputResponse(response string, stream io.Writer, streamType string) (finished bool, exitCode int, err error) { doc, err := xmlpath.Parse(strings.NewReader(response)) nodes, _ := xpath(doc, fmt.Sprintf("//rsp:Stream[@Name='%s']", streamType)) for _, node := range nodes { content, _ := base64.StdEncoding.DecodeString(node.String()) stream.Write(content) } ended, _ := any(doc, "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']") if ended { finished = ended if exitBool, _ := any(doc, "//rsp:ExitCode"); exitBool { exit, _ := first(doc, "//rsp:ExitCode") exitCode, _ = strconv.Atoi(exit) } } else { finished = false } return } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/response_test.go ================================================ package winrm import ( "bytes" . "gopkg.in/check.v1" ) func (s *WinRMSuite) TestOpenShellResponse(c *C) { response := createShellResponse shellId, err := ParseOpenShellResponse(response) if err != nil { c.Fatalf("response didn't parse: %s", err) } c.Assert("67A74734-DD32-4F10-89DE-49A060483810", Equals, shellId) } func (s *WinRMSuite) TestExecuteCommandResponse(c *C) { response := executeCommandResponse commandId, err := ParseExecuteCommandResponse(response) if err != nil { c.Fatalf("response didn't parse: %s", err) } c.Assert("1A6DEE6B-EC68-4DD6-87E9-030C0048ECC4", Equals, commandId) } func (s *WinRMSuite) TestSlurpOutputResponse(c *C) { response := outputResponse var stdout, stderr bytes.Buffer finished, _, err := ParseSlurpOutputErrResponse(response, &stdout, &stderr) if err != nil { c.Fatalf("response didn't parse: %s", err) } c.Assert(finished, Equals, false) c.Assert("That's all folks!!!", Equals, stdout.String()) c.Assert("This is stderr, I'm pretty sure!", Equals, stderr.String()) } func (s *WinRMSuite) TestSlurpOutputSingleResponse(c *C) { response := singleOutputResponse var stream bytes.Buffer finished, _, err := ParseSlurpOutputResponse(response, &stream, "stdout") if err != nil { c.Fatalf("response didn't parse: %s", err) } c.Assert(finished, Equals, false) c.Assert("That's all folks!!!", Equals, stream.String()) } func (s *WinRMSuite) TestDoneSlurpOutputResponse(c *C) { response := doneCommandResponse var stdout, stderr bytes.Buffer finished, code, err := ParseSlurpOutputErrResponse(response, &stdout, &stderr) if err != nil { c.Fatalf("response didn't parse: %s", err) } c.Assert(finished, Equals, true) c.Assert(code, Equals, 123) c.Assert("", Equals, stdout.String()) c.Assert("", Equals, stderr.String()) } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/shell.go ================================================ package winrm // Shell is the local view of a WinRM Shell of a given Client type Shell struct { client *Client ShellId string } // Execute command on the given Shell, returning either an error or a Command func (shell *Shell) Execute(command string, arguments ...string) (cmd *Command, err error) { request := NewExecuteCommandRequest(shell.client.url, shell.ShellId, command, arguments, &shell.client.Parameters) defer request.Free() response, err := shell.client.sendRequest(request) if err == nil { var commandId string if commandId, err = ParseExecuteCommandResponse(response); err == nil { cmd = newCommand(shell, commandId) } } return } // Close will terminate this shell. No commands can be issued once the shell is closed. func (shell *Shell) Close() (err error) { request := NewDeleteShellRequest(shell.client.url, shell.ShellId, &shell.client.Parameters) defer request.Free() _, err = shell.client.sendRequest(request) return } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm/shell_test.go ================================================ package winrm import ( "github.com/masterzen/winrm/soap" . "gopkg.in/check.v1" ) func (s *WinRMSuite) TestShellExecuteResponse(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) shell := &Shell{client: client, ShellId: "67A74734-DD32-4F10-89DE-49A060483810"} first := true client.http = func(client *Client, message *soap.SoapMessage) (string, error) { if first { c.Assert(message.String(), Contains, "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command") first = false return executeCommandResponse, nil } else { c.Assert(message.String(), Contains, "http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive") return outputResponse, nil } } command, _ := shell.Execute("ipconfig /all") c.Assert(command.commandId, Equals, "1A6DEE6B-EC68-4DD6-87E9-030C0048ECC4") } func (s *WinRMSuite) TestShellCloseResponse(c *C) { client, err := NewClient(&Endpoint{Host: "localhost", Port: 5985}, "Administrator", "v3r1S3cre7") c.Assert(err, IsNil) shell := &Shell{client: client, ShellId: "67A74734-DD32-4F10-89DE-49A060483810"} client.http = func(client *Client, message *soap.SoapMessage) (string, error) { c.Assert(message.String(), Contains, "http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete") return "", nil } shell.Close() } ================================================ FILE: vendor/github.com/masterzen/winrm/winrm.go ================================================ /* Copyright 2013 Brice Figureau 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 main import ( "flag" "fmt" "io/ioutil" "os" "github.com/masterzen/winrm/winrm" ) func main() { var ( hostname string user string pass string cmd string port int https bool insecure bool cacert string ) flag.StringVar(&hostname, "hostname", "localhost", "winrm host") flag.StringVar(&user, "username", "vagrant", "winrm admin username") flag.StringVar(&pass, "password", "vagrant", "winrm admin password") flag.IntVar(&port, "port", 5985, "winrm port") flag.BoolVar(&https, "https", false, "use https") flag.BoolVar(&insecure, "insecure", false, "skip SSL validation") flag.StringVar(&cacert, "cacert", "", "CA certificate to use") flag.Parse() var certBytes []byte var err error if cacert != "" { certBytes, err = ioutil.ReadFile(cacert) if err != nil { fmt.Println(err) os.Exit(1) } } else { certBytes = nil } cmd = flag.Arg(0) client, err := winrm.NewClient(&winrm.Endpoint{Host: hostname, Port: port, HTTPS: https, Insecure: insecure, CACert: &certBytes}, user, pass) if err != nil { fmt.Println(err) os.Exit(1) } exitCode, err := client.RunWithInput(cmd, os.Stdout, os.Stderr, os.Stdin) if err != nil { fmt.Println(err) os.Exit(1) } os.Exit(exitCode) } ================================================ FILE: vendor/github.com/masterzen/xmlpath/LICENSE ================================================ This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: vendor/github.com/masterzen/xmlpath/all_test.go ================================================ package xmlpath_test import ( "bytes" "encoding/xml" . "launchpad.net/gocheck" "launchpad.net/xmlpath" "testing" ) func Test(t *testing.T) { TestingT(t) } var _ = Suite(&BasicSuite{}) type BasicSuite struct{} var trivialXml = []byte(`abcdefg`) func (s *BasicSuite) TestRootText(c *C) { node, err := xmlpath.Parse(bytes.NewBuffer(trivialXml)) c.Assert(err, IsNil) path := xmlpath.MustCompile("/") result, ok := path.String(node) c.Assert(ok, Equals, true) c.Assert(result, Equals, "abcdefg") } var trivialHtml = []byte(`<a>`) func (s *BasicSuite) TestHTML(c *C) { node, err := xmlpath.ParseHTML(bytes.NewBuffer(trivialHtml)) c.Assert(err, IsNil) path := xmlpath.MustCompile("/root/foo") result, ok := path.String(node) c.Assert(ok, Equals, true) c.Assert(result, Equals, "") } func (s *BasicSuite) TestLibraryTable(c *C) { node, err := xmlpath.Parse(bytes.NewBuffer(libraryXml)) c.Assert(err, IsNil) for _, test := range libraryTable { cmt := Commentf("xml path: %s", test.path) path, err := xmlpath.Compile(test.path) if want, ok := test.result.(cerror); ok { c.Assert(err, ErrorMatches, string(want), cmt) c.Assert(path, IsNil, cmt) continue } c.Assert(err, IsNil) switch want := test.result.(type) { case string: got, ok := path.String(node) c.Assert(ok, Equals, true, cmt) c.Assert(got, Equals, want, cmt) c.Assert(path.Exists(node), Equals, true, cmt) iter := path.Iter(node) iter.Next() node := iter.Node() c.Assert(node.String(), Equals, want, cmt) c.Assert(string(node.Bytes()), Equals, want, cmt) case []string: var alls []string var allb []string iter := path.Iter(node) for iter.Next() { alls = append(alls, iter.Node().String()) allb = append(allb, string(iter.Node().Bytes())) } c.Assert(alls, DeepEquals, want, cmt) c.Assert(allb, DeepEquals, want, cmt) s, sok := path.String(node) b, bok := path.Bytes(node) if len(want) == 0 { c.Assert(sok, Equals, false, cmt) c.Assert(bok, Equals, false, cmt) c.Assert(s, Equals, "") c.Assert(b, IsNil) } else { c.Assert(sok, Equals, true, cmt) c.Assert(bok, Equals, true, cmt) c.Assert(s, Equals, alls[0], cmt) c.Assert(string(b), Equals, alls[0], cmt) c.Assert(path.Exists(node), Equals, true, cmt) } case exists: wantb := bool(want) ok := path.Exists(node) c.Assert(ok, Equals, wantb, cmt) _, ok = path.String(node) c.Assert(ok, Equals, wantb, cmt) } } } type cerror string type exists bool var libraryTable = []struct{ path string; result interface{} }{ // These are the examples in the package documentation: {"/library/book/isbn", "0836217462"}, {"library/*/isbn", "0836217462"}, {"/library/book/../book/./isbn", "0836217462"}, {"/library/book/character[2]/name", "Snoopy"}, {"/library/book/character[born='1950-10-04']/name", "Snoopy"}, {"/library/book//node()[@id='PP']/name", "Peppermint Patty"}, {"//book[author/@id='CMS']/title", "Being a Dog Is a Full-Time Job"}, {"/library/book/preceding::comment()", " Great book. "}, // A few simple {"/library/book/isbn", exists(true)}, {"/library/isbn", exists(false)}, {"/library/book/isbn/bad", exists(false)}, {"/library/book/bad", exists(false)}, {"/library/bad/isbn", exists(false)}, {"/bad/book/isbn", exists(false)}, // Simple paths. {"/library/book/isbn", "0836217462"}, {"/library/book/author/name", "Charles M Schulz"}, {"/library/book/author/born", "1922-11-26"}, {"/library/book/character/name", "Peppermint Patty"}, {"/library/book/character/qualification", "bold, brash and tomboyish"}, // Unrooted path with root node as context. {"library/book/isbn", "0836217462"}, // Multiple entries from simple paths. {"/library/book/isbn", []string{"0836217462", "0883556316"}}, {"/library/book/character/name", []string{"Peppermint Patty", "Snoopy", "Schroeder", "Lucy", "Barney Google", "Spark Plug", "Snuffy Smith"}}, // Handling of wildcards. {"/library/book/author/*", []string{"Charles M Schulz", "1922-11-26", "2000-02-12", "Charles M Schulz", "1922-11-26", "2000-02-12"}}, // Unsupported axis and note test. {"/foo()", cerror(`compiling xml path "/foo\(\)":5: unsupported expression: foo\(\)`)}, {"/foo::node()", cerror(`compiling xml path "/foo::node\(\)":6: unsupported axis: "foo"`)}, // The attribute axis. {"/library/book/title/attribute::lang", "en"}, {"/library/book/title/@lang", "en"}, {"/library/book/@available/parent::node()/@id", "b0836217462"}, {"/library/book/attribute::*", []string{"b0836217462", "true", "b0883556316", "true"}}, {"/library/book/attribute::text()", cerror(`.*: text\(\) cannot succeed on axis "attribute"`)}, // The self axis. {"/library/book/isbn/./self::node()", "0836217462"}, // The descendant axis. {"/library/book/isbn/descendant::isbn", exists(false)}, {"/library/descendant::isbn", []string{"0836217462", "0883556316"}}, {"/descendant::*/isbn", []string{"0836217462", "0883556316"}}, {"/descendant::isbn", []string{"0836217462", "0883556316"}}, // The descendant-or-self axis. {"/library/book/isbn/descendant-or-self::isbn", "0836217462"}, {"/library//isbn", []string{"0836217462", "0883556316"}}, {"//isbn", []string{"0836217462", "0883556316"}}, {"/descendant-or-self::node()/child::book/child::*", "0836217462"}, // The parent axis. {"/library/book/isbn/../isbn/parent::node()//title", "Being a Dog Is a Full-Time Job"}, // The ancestor axis. {"/library/book/isbn/ancestor::book/title", "Being a Dog Is a Full-Time Job"}, {"/library/book/ancestor::book/title", exists(false)}, // The ancestor-or-self axis. {"/library/book/isbn/ancestor-or-self::book/title", "Being a Dog Is a Full-Time Job"}, {"/library/book/ancestor-or-self::book/title", "Being a Dog Is a Full-Time Job"}, // The following axis. // The first author name must not be included, as it's within the context // node (author) rather than following it. These queries exercise de-duping // of nodes, since the following axis runs to the end multiple times. {"/library/book/author/following::name", []string{"Peppermint Patty", "Snoopy", "Schroeder", "Lucy", "Charles M Schulz", "Barney Google", "Spark Plug", "Snuffy Smith"}}, {"//following::book/author/name", []string{"Charles M Schulz", "Charles M Schulz"}}, // The following-sibling axis. {"/library/book/quote/following-sibling::node()/name", []string{"Charles M Schulz", "Peppermint Patty", "Snoopy", "Schroeder", "Lucy"}}, // The preceding axis. {"/library/book/author/born/preceding::name", []string{"Charles M Schulz", "Charles M Schulz", "Lucy", "Schroeder", "Snoopy", "Peppermint Patty"}}, {"/library/book/author/born/preceding::author/name", []string{"Charles M Schulz"}}, {"/library/book/author/born/preceding::library", exists(false)}, // The preceding-sibling axis. {"/library/book/author/born/preceding-sibling::name", []string{"Charles M Schulz", "Charles M Schulz"}}, {"/library/book/author/born/preceding::author/name", []string{"Charles M Schulz"}}, // Comments. {"/library/comment()", []string{" Great book. ", " Another great book. "}}, {"//self::comment()", []string{" Great book. ", " Another great book. "}}, {`comment("")`, cerror(`.*: comment\(\) has no arguments`)}, // Processing instructions. {`/library/book/author/processing-instruction()`, `"go rocks"`}, {`/library/book/author/processing-instruction("echo")`, `"go rocks"`}, {`/library//processing-instruction("echo")`, `"go rocks"`}, {`/library/book/author/processing-instruction("foo")`, exists(false)}, {`/library/book/author/processing-instruction(")`, cerror(`.*: missing '"'`)}, // Predicates. {"library/book[@id='b0883556316']/isbn", []string{"0883556316"}}, {"library/book[isbn='0836217462']/character[born='1950-10-04']/name", []string{"Snoopy"}}, {"library/book[quote]/@id", []string{"b0836217462"}}, {"library/book[./character/born='1922-07-17']/@id", []string{"b0883556316"}}, {"library/book[2]/isbn", []string{"0883556316"}}, {"library/book[0]/isbn", cerror(".*: positions start at 1")}, {"library/book[-1]/isbn", cerror(".*: positions must be positive")}, // Bogus expressions. {"/foo)", cerror(`compiling xml path "/foo\)":4: unexpected '\)'`)}, } var libraryXml = []byte( ` 0836217462 Being a Dog Is a Full-Time Job I'd dog paddle the deepest ocean. Charles M Schulz 1922-11-26 2000-02-12 Peppermint Patty 1966-08-22 bold, brash and tomboyish Snoopy 1950-10-04 extroverted beagle Schroeder 1951-05-30 brought classical music to the Peanuts strip Lucy 1952-03-03 bossy, crabby and selfish 0883556316 Barney Google and Snuffy Smith Charles M Schulz 1922-11-26 2000-02-12 Barney Google 1919-01-01 goggle-eyed, moustached, gloved and top-hatted, bulbous-nosed, cigar-chomping shrimp Spark Plug 1922-07-17 brown-eyed, bow-legged nag, seldom races, patched blanket Snuffy Smith 1934-01-01 volatile and diminutive moonshiner, ornery little cuss, sawed-off and shiftless `) func (s *BasicSuite) TestNamespace(c *C) { node, err := xmlpath.Parse(bytes.NewBuffer(namespaceXml)) c.Assert(err, IsNil) for _, test := range namespaceTable { cmt := Commentf("xml path: %s", test.path) path, err := xmlpath.CompileWithNamespace(test.path, namespaces) if want, ok := test.result.(cerror); ok { c.Assert(err, ErrorMatches, string(want), cmt) c.Assert(path, IsNil, cmt) continue } c.Assert(err, IsNil) switch want := test.result.(type) { case string: got, ok := path.String(node) c.Assert(ok, Equals, true, cmt) c.Assert(got, Equals, want, cmt) c.Assert(path.Exists(node), Equals, true, cmt) iter := path.Iter(node) iter.Next() node := iter.Node() c.Assert(node.String(), Equals, want, cmt) c.Assert(string(node.Bytes()), Equals, want, cmt) case []string: var alls []string var allb []string iter := path.Iter(node) for iter.Next() { alls = append(alls, iter.Node().String()) allb = append(allb, string(iter.Node().Bytes())) } c.Assert(alls, DeepEquals, want, cmt) c.Assert(allb, DeepEquals, want, cmt) s, sok := path.String(node) b, bok := path.Bytes(node) if len(want) == 0 { c.Assert(sok, Equals, false, cmt) c.Assert(bok, Equals, false, cmt) c.Assert(s, Equals, "") c.Assert(b, IsNil) } else { c.Assert(sok, Equals, true, cmt) c.Assert(bok, Equals, true, cmt) c.Assert(s, Equals, alls[0], cmt) c.Assert(string(b), Equals, alls[0], cmt) c.Assert(path.Exists(node), Equals, true, cmt) } case exists: wantb := bool(want) ok := path.Exists(node) c.Assert(ok, Equals, wantb, cmt) _, ok = path.String(node) c.Assert(ok, Equals, wantb, cmt) } } } var namespaceXml = []byte(`http://schemas.microsoft.com/wbem/wsman/1/windows/shell/ReceiveResponseuuid:AAD46BD4-6315-4C3C-93D4-94A55773287Dhttp://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymousuuid:18A52A06-9027-41DC-8850-3F244595AF62VGhhdCdzIGFsbCBmb2xrcyEhIQ==VGhpcyBpcyBzdGRlcnIsIEknbSBwcmV0dHkgc3VyZSE=`) var namespaces = []xmlpath.Namespace { { "a", "http://schemas.xmlsoap.org/ws/2004/08/addressing" }, { "rsp", "http://schemas.microsoft.com/wbem/wsman/1/windows/shell" }, } var namespaceTable = []struct{ path string; result interface{} }{ { "//a:To", "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous" }, { "//rsp:Stream[@Name='stdout']", "VGhhdCdzIGFsbCBmb2xrcyEhIQ==" }, { "//rsp:CommandState/@CommandId", "1A6DEE6B-EC68-4DD6-87E9-030C0048ECC4" }, { "//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']", exists(false) }, { "//rsp:Stream", []string{ "VGhhdCdzIGFsbCBmb2xrcyEhIQ==", "VGhpcyBpcyBzdGRlcnIsIEknbSBwcmV0dHkgc3VyZSE=" }}, { "//s:Header", cerror(`.*: unknown namespace prefix: s`) }, } func (s *BasicSuite) BenchmarkParse(c *C) { for i := 0; i < c.N; i++ { _, err := xmlpath.Parse(bytes.NewBuffer(instancesXml)) c.Assert(err, IsNil) } } func (s *BasicSuite) BenchmarkSimplePathCompile(c *C) { var err error c.ResetTimer() for i := 0; i < c.N; i++ { _, err = xmlpath.Compile("/DescribeInstancesResponse/reservationSet/item/groupSet/item/groupId") } c.StopTimer() c.Assert(err, IsNil) } func (s *BasicSuite) BenchmarkSimplePathString(c *C) { node, err := xmlpath.Parse(bytes.NewBuffer(instancesXml)) c.Assert(err, IsNil) path := xmlpath.MustCompile("/DescribeInstancesResponse/reservationSet/item/instancesSet/item/instanceType") var str string c.ResetTimer() for i := 0; i < c.N; i++ { str, _ = path.String(node) } c.StopTimer() c.Assert(str, Equals, "m1.small") } func (s *BasicSuite) BenchmarkSimplePathStringUnmarshal(c *C) { // For a vague comparison. var result struct{ Str string `xml:"reservationSet>item>instancesSet>item>instanceType"` } for i := 0; i < c.N; i++ { xml.Unmarshal(instancesXml, &result) } c.StopTimer() c.Assert(result.Str, Equals, "m1.large") } func (s *BasicSuite) BenchmarkSimplePathExists(c *C) { node, err := xmlpath.Parse(bytes.NewBuffer(instancesXml)) c.Assert(err, IsNil) path := xmlpath.MustCompile("/DescribeInstancesResponse/reservationSet/item/instancesSet/item/instanceType") var exists bool c.ResetTimer() for i := 0; i < c.N; i++ { exists = path.Exists(node) } c.StopTimer() c.Assert(exists, Equals, true) } var instancesXml = []byte( ` 98e3c9a4-848c-4d6d-8e8a-b1bdEXAMPLE r-b27e30d9 999988887777 sg-67ad940e default i-c5cd56af ami-1a2b3c4d 16 running domU-12-31-39-10-56-34.compute-1.internal ec2-174-129-165-232.compute-1.amazonaws.com GSG_Keypair 0 m1.small 2010-08-17T01:15:18.000Z us-east-1b aki-94c527fd ari-96c527ff disabled 10.198.85.190 174.129.165.232 i386 ebs /dev/sda1 /dev/sda1 vol-a082c1c9 attached 2010-08-17T01:15:21.000Z false spot sir-7a688402 paravirtual xen 854251627541 r-b67e30dd 999988887777 sg-67ad940e default i-d9cd56b3 ami-1a2b3c4d 16 running domU-12-31-39-10-54-E5.compute-1.internal ec2-184-73-58-78.compute-1.amazonaws.com GSG_Keypair 0 m1.large 2010-08-17T01:15:19.000Z us-east-1b aki-94c527fd ari-96c527ff disabled 10.198.87.19 184.73.58.78 i386 ebs /dev/sda1 /dev/sda1 vol-a282c1cb attached 2010-08-17T01:15:23.000Z false spot sir-55a3aa02 paravirtual xen 854251627541 `) ================================================ FILE: vendor/github.com/masterzen/xmlpath/doc.go ================================================ // Package xmlpath implements a strict subset of the XPath specification for the Go language. // // The XPath specification is available at: // // http://www.w3.org/TR/xpath // // Path expressions supported by this package are in the following format, // with all components being optional: // // /axis-name::node-test[predicate]/axis-name::node-test[predicate] // // At the moment, xmlpath is compatible with the XPath specification // to the following extent: // // - All axes are supported ("child", "following-sibling", etc) // - All abbreviated forms are supported (".", "//", etc) // - All node types except for namespace are supported // - Predicates are restricted to [N], [path], and [path=literal] forms // - Only a single predicate is supported per path step // - Namespaces are experimentally supported // - Richer expressions // // For example, assuming the following document: // // // // // 0836217462 // Being a Dog Is a Full-Time Job // I'd dog paddle the deepest ocean. // // // Charles M Schulz // 1922-11-26 // 2000-02-12 // // // Peppermint Patty // 1966-08-22 // bold, brash and tomboyish // // // Snoopy // 1950-10-04 // extroverted beagle // // // // // The following examples are valid path expressions, and the first // match has the indicated value: // // /library/book/isbn => "0836217462" // library/*/isbn => "0836217462" // /library/book/../book/./isbn => "0836217462" // /library/book/character[2]/name => "Snoopy" // /library/book/character[born='1950-10-04']/name => "Snoopy" // /library/book//node()[@id='PP']/name => "Peppermint Patty" // //book[author/@id='CMS']/title => "Being a Dog Is a Full-Time Job"}, // /library/book/preceding::comment() => " Great book. " // // To run an expression, compile it, and then apply the compiled path to any // number of context nodes, from one or more parsed xml documents: // // path := xmlpath.MustCompile("/library/book/isbn") // root, err := xmlpath.Parse(file) // if err != nil { // log.Fatal(err) // } // if value, ok := path.String(root); ok { // fmt.Println("Found:", value) // } // // To use xmlpath with namespaces, it is required to give the supported set of namespace // when compiling: // // // var namespaces = []xmlpath.Namespace { // { "s", "http://www.w3.org/2003/05/soap-envelope" }, // { "a", "http://schemas.xmlsoap.org/ws/2004/08/addressing" }, // } // path, err := xmlpath.CompileWithNamespace("/s:Header/a:To", namespaces) // if err != nil { // log.Fatal(err) // } // root, err := xmlpath.Parse(file) // if err != nil { // log.Fatal(err) // } // if value, ok := path.String(root); ok { // fmt.Println("Found:", value) // } // package xmlpath ================================================ FILE: vendor/github.com/masterzen/xmlpath/parser.go ================================================ package xmlpath import ( "encoding/xml" "io" ) // Node is an item in an xml tree that was compiled to // be processed via xml paths. A node may represent: // // - An element in the xml document () // - An attribute of an element in the xml document (href="...") // - A comment in the xml document () // - A processing instruction in the xml document () // - Some text within the xml document // type Node struct { kind nodeKind name xml.Name attr string text []byte nodes []Node pos int end int up *Node down []*Node } type nodeKind int const ( anyNode nodeKind = iota startNode endNode attrNode textNode commentNode procInstNode ) // String returns the string value of node. // // The string value of a node is: // // - For element nodes, the concatenation of all text nodes within the element. // - For text nodes, the text itself. // - For attribute nodes, the attribute value. // - For comment nodes, the text within the comment delimiters. // - For processing instruction nodes, the content of the instruction. // func (node *Node) String() string { if node.kind == attrNode { return node.attr } return string(node.Bytes()) } // Bytes returns the string value of node as a byte slice. // See Node.String for a description of what the string value of a node is. func (node *Node) Bytes() []byte { if node.kind == attrNode { return []byte(node.attr) } if node.kind != startNode { return node.text } var text []byte for i := node.pos; i < node.end; i++ { if node.nodes[i].kind == textNode { text = append(text, node.nodes[i].text...) } } return text } // equals returns whether the string value of node is equal to s, // without allocating memory. func (node *Node) equals(s string) bool { if node.kind == attrNode { return s == node.attr } if node.kind != startNode { if len(s) != len(node.text) { return false } for i := range s { if s[i] != node.text[i] { return false } } return true } si := 0 for i := node.pos; i < node.end; i++ { if node.nodes[i].kind == textNode { for _, c := range node.nodes[i].text { if si > len(s) { return false } if s[si] != c { return false } si++ } } } return si == len(s) } // Parse reads an xml document from r, parses it, and returns its root node. func Parse(r io.Reader) (*Node, error) { return ParseDecoder(xml.NewDecoder(r)) } // ParseHTML reads an HTML-like document from r, parses it, and returns // its root node. func ParseHTML(r io.Reader) (*Node, error) { d := xml.NewDecoder(r) d.Strict = false d.AutoClose = xml.HTMLAutoClose d.Entity = xml.HTMLEntity return ParseDecoder(d) } // ParseDecoder parses the xml document being decoded by d and returns // its root node. func ParseDecoder(d *xml.Decoder) (*Node, error) { var nodes []Node var text []byte // The root node. nodes = append(nodes, Node{kind: startNode}) for { t, err := d.Token() if err == io.EOF { break } if err != nil { return nil, err } switch t := t.(type) { case xml.EndElement: nodes = append(nodes, Node{ kind: endNode, }) case xml.StartElement: nodes = append(nodes, Node{ kind: startNode, name: t.Name, }) for _, attr := range t.Attr { nodes = append(nodes, Node{ kind: attrNode, name: attr.Name, attr: attr.Value, }) } case xml.CharData: texti := len(text) text = append(text, t...) nodes = append(nodes, Node{ kind: textNode, text: text[texti : texti+len(t)], }) case xml.Comment: texti := len(text) text = append(text, t...) nodes = append(nodes, Node{ kind: commentNode, text: text[texti : texti+len(t)], }) case xml.ProcInst: texti := len(text) text = append(text, t.Inst...) nodes = append(nodes, Node{ kind: procInstNode, name: xml.Name{Local: t.Target}, text: text[texti : texti+len(t.Inst)], }) } } // Close the root node. nodes = append(nodes, Node{kind: endNode}) stack := make([]*Node, 0, len(nodes)) downs := make([]*Node, len(nodes)) downCount := 0 for pos := range nodes { switch nodes[pos].kind { case startNode, attrNode, textNode, commentNode, procInstNode: node := &nodes[pos] node.nodes = nodes node.pos = pos if len(stack) > 0 { node.up = stack[len(stack)-1] } if node.kind == startNode { stack = append(stack, node) } else { node.end = pos + 1 } case endNode: node := stack[len(stack)-1] node.end = pos stack = stack[:len(stack)-1] // Compute downs. Doing that here is what enables the // use of a slice of a contiguous pre-allocated block. node.down = downs[downCount:downCount] for i := node.pos + 1; i < node.end; i++ { if nodes[i].up == node { switch nodes[i].kind { case startNode, textNode, commentNode, procInstNode: node.down = append(node.down, &nodes[i]) downCount++ } } } if len(stack) == 0 { return node, nil } } } return nil, io.EOF } ================================================ FILE: vendor/github.com/masterzen/xmlpath/path.go ================================================ package xmlpath import ( "fmt" "strconv" "unicode/utf8" ) // Namespace represents a given XML Namespace type Namespace struct { Prefix string Uri string } // Path is a compiled path that can be applied to a context // node to obtain a matching node set. // A single Path can be applied concurrently to any number // of context nodes. type Path struct { path string steps []pathStep } // Iter returns an iterator that goes over the list of nodes // that p matches on the given context. func (p *Path) Iter(context *Node) *Iter { iter := Iter{ make([]pathStepState, len(p.steps)), make([]bool, len(context.nodes)), } for i := range p.steps { iter.state[i].step = &p.steps[i] } iter.state[0].init(context) return &iter } // Exists returns whether any nodes match p on the given context. func (p *Path) Exists(context *Node) bool { return p.Iter(context).Next() } // String returns the string value of the first node matched // by p on the given context. // // See the documentation of Node.String. func (p *Path) String(context *Node) (s string, ok bool) { iter := p.Iter(context) if iter.Next() { return iter.Node().String(), true } return "", false } // Bytes returns as a byte slice the string value of the first // node matched by p on the given context. // // See the documentation of Node.String. func (p *Path) Bytes(node *Node) (b []byte, ok bool) { iter := p.Iter(node) if iter.Next() { return iter.Node().Bytes(), true } return nil, false } // Iter iterates over node sets. type Iter struct { state []pathStepState seen []bool } // Node returns the current node. // Must only be called after Iter.Next returns true. func (iter *Iter) Node() *Node { state := iter.state[len(iter.state)-1] if state.pos == 0 { panic("Iter.Node called before Iter.Next") } if state.node == nil { panic("Iter.Node called after Iter.Next false") } return state.node } // Next iterates to the next node in the set, if any, and // returns whether there is a node available. func (iter *Iter) Next() bool { tip := len(iter.state) - 1 outer: for { for !iter.state[tip].next() { tip-- if tip == -1 { return false } } for tip < len(iter.state)-1 { tip++ iter.state[tip].init(iter.state[tip-1].node) if !iter.state[tip].next() { tip-- continue outer } } if iter.seen[iter.state[tip].node.pos] { continue } iter.seen[iter.state[tip].node.pos] = true return true } panic("unreachable") } type pathStepState struct { step *pathStep node *Node pos int idx int aux int } func (s *pathStepState) init(node *Node) { s.node = node s.pos = 0 s.idx = 0 s.aux = 0 } func (s *pathStepState) next() bool { for s._next() { s.pos++ if s.step.pred == nil { return true } if s.step.pred.bval { if s.step.pred.path.Exists(s.node) { return true } } else if s.step.pred.path != nil { iter := s.step.pred.path.Iter(s.node) for iter.Next() { if iter.Node().equals(s.step.pred.sval) { return true } } } else { if s.step.pred.ival == s.pos { return true } } } return false } func (s *pathStepState) _next() bool { if s.node == nil { return false } if s.step.root && s.idx == 0 { for s.node.up != nil { s.node = s.node.up } } switch s.step.axis { case "self": if s.idx == 0 && s.step.match(s.node) { s.idx++ return true } case "parent": if s.idx == 0 && s.node.up != nil && s.step.match(s.node.up) { s.idx++ s.node = s.node.up return true } case "ancestor", "ancestor-or-self": if s.idx == 0 && s.step.axis == "ancestor-or-self" { s.idx++ if s.step.match(s.node) { return true } } for s.node.up != nil { s.node = s.node.up s.idx++ if s.step.match(s.node) { return true } } case "child": var down []*Node if s.idx == 0 { down = s.node.down } else { down = s.node.up.down } for s.idx < len(down) { node := down[s.idx] s.idx++ if s.step.match(node) { s.node = node return true } } case "descendant", "descendant-or-self": if s.idx == 0 { s.idx = s.node.pos s.aux = s.node.end if s.step.axis == "descendant" { s.idx++ } } for s.idx < s.aux { node := &s.node.nodes[s.idx] s.idx++ if node.kind == attrNode { continue } if s.step.match(node) { s.node = node return true } } case "following": if s.idx == 0 { s.idx = s.node.end } for s.idx < len(s.node.nodes) { node := &s.node.nodes[s.idx] s.idx++ if node.kind == attrNode { continue } if s.step.match(node) { s.node = node return true } } case "following-sibling": var down []*Node if s.node.up != nil { down = s.node.up.down if s.idx == 0 { for s.idx < len(down) { node := down[s.idx] s.idx++ if node == s.node { break } } } } for s.idx < len(down) { node := down[s.idx] s.idx++ if s.step.match(node) { s.node = node return true } } case "preceding": if s.idx == 0 { s.aux = s.node.pos // Detect ancestors. s.idx = s.node.pos - 1 } for s.idx >= 0 { node := &s.node.nodes[s.idx] s.idx-- if node.kind == attrNode { continue } if node == s.node.nodes[s.aux].up { s.aux = s.node.nodes[s.aux].up.pos continue } if s.step.match(node) { s.node = node return true } } case "preceding-sibling": var down []*Node if s.node.up != nil { down = s.node.up.down if s.aux == 0 { s.aux = 1 for s.idx < len(down) { node := down[s.idx] s.idx++ if node == s.node { s.idx-- break } } } } for s.idx >= 0 { node := down[s.idx] s.idx-- if s.step.match(node) { s.node = node return true } } case "attribute": if s.idx == 0 { s.idx = s.node.pos + 1 s.aux = s.node.end } for s.idx < s.aux { node := &s.node.nodes[s.idx] s.idx++ if node.kind != attrNode { break } if s.step.match(node) { s.node = node return true } } } s.node = nil return false } type pathPredicate struct { path *Path sval string ival int bval bool } type pathStep struct { root bool axis string name string prefix string uri string kind nodeKind pred *pathPredicate } func (step *pathStep) match(node *Node) bool { return node.kind != endNode && (step.kind == anyNode || step.kind == node.kind) && (step.name == "*" || (node.name.Local == step.name && (node.name.Space != "" && node.name.Space == step.uri || node.name.Space == ""))) } // MustCompile returns the compiled path, and panics if // there are any errors. func MustCompile(path string) *Path { e, err := Compile(path) if err != nil { panic(err) } return e } // Compile returns the compiled path. func Compile(path string) (*Path, error) { c := pathCompiler{path, 0, []Namespace{} } if path == "" { return nil, c.errorf("empty path") } p, err := c.parsePath() if err != nil { return nil, err } return p, nil } // Compile the path with the knowledge of the given namespaces func CompileWithNamespace(path string, ns []Namespace) (*Path, error) { c := pathCompiler{path, 0, ns} if path == "" { return nil, c.errorf("empty path") } p, err := c.parsePath() if err != nil { return nil, err } return p, nil } type pathCompiler struct { path string i int ns []Namespace } func (c *pathCompiler) errorf(format string, args ...interface{}) error { return fmt.Errorf("compiling xml path %q:%d: %s", c.path, c.i, fmt.Sprintf(format, args...)) } func (c *pathCompiler) parsePath() (path *Path, err error) { var steps []pathStep var start = c.i for { step := pathStep{axis: "child"} if c.i == 0 && c.skipByte('/') { step.root = true if len(c.path) == 1 { step.name = "*" } } if c.peekByte('/') { step.axis = "descendant-or-self" step.name = "*" } else if c.skipByte('@') { mark := c.i if !c.skipName() { return nil, c.errorf("missing name after @") } step.axis = "attribute" step.name = c.path[mark:c.i] step.kind = attrNode } else { mark := c.i if c.skipName() { step.name = c.path[mark:c.i] } if step.name == "" { return nil, c.errorf("missing name") } else if step.name == "*" { step.kind = startNode } else if step.name == "." { step.axis = "self" step.name = "*" } else if step.name == ".." { step.axis = "parent" step.name = "*" } else { if c.skipByte(':') { if !c.skipByte(':') { mark = c.i if c.skipName() { step.prefix = step.name step.name = c.path[mark:c.i] // check prefix found := false for _, ns := range c.ns { if ns.Prefix == step.prefix { step.uri = ns.Uri found = true break } } if !found { return nil, c.errorf("unknown namespace prefix: %s", step.prefix) } } else { return nil, c.errorf("missing name after namespace prefix") } } else { switch step.name { case "attribute": step.kind = attrNode case "self", "child", "parent": case "descendant", "descendant-or-self": case "ancestor", "ancestor-or-self": case "following", "following-sibling": case "preceding", "preceding-sibling": default: return nil, c.errorf("unsupported axis: %q", step.name) } step.axis = step.name mark = c.i if !c.skipName() { return nil, c.errorf("missing name") } step.name = c.path[mark:c.i] } } if c.skipByte('(') { conflict := step.kind != anyNode switch step.name { case "node": // must be anyNode case "text": step.kind = textNode case "comment": step.kind = commentNode case "processing-instruction": step.kind = procInstNode default: return nil, c.errorf("unsupported expression: %s()", step.name) } if conflict { return nil, c.errorf("%s() cannot succeed on axis %q", step.name, step.axis) } literal, err := c.parseLiteral() if err == errNoLiteral { step.name = "*" } else if err != nil { return nil, c.errorf("%v", err) } else if step.kind == procInstNode { step.name = literal } else { return nil, c.errorf("%s() has no arguments", step.name) } if !c.skipByte(')') { return nil, c.errorf("missing )") } } else if step.name == "*" && step.kind == anyNode { step.kind = startNode } } } if c.skipByte('[') { step.pred = &pathPredicate{} if ival, ok := c.parseInt(); ok { if ival == 0 { return nil, c.errorf("positions start at 1") } step.pred.ival = ival } else { path, err := c.parsePath() if err != nil { return nil, err } if path.path[0] == '-' { if _, err = strconv.Atoi(path.path); err == nil { return nil, c.errorf("positions must be positive") } } step.pred.path = path if c.skipByte('=') { sval, err := c.parseLiteral() if err != nil { return nil, c.errorf("%v", err) } step.pred.sval = sval } else { step.pred.bval = true } } if !c.skipByte(']') { return nil, c.errorf("expected ']'") } } steps = append(steps, step) //fmt.Printf("step: %#v\n", step) if !c.skipByte('/') { if (start == 0 || start == c.i) && c.i < len(c.path) { return nil, c.errorf("unexpected %q", c.path[c.i]) } return &Path{steps: steps, path: c.path[start:c.i]}, nil } } panic("unreachable") } var errNoLiteral = fmt.Errorf("expected a literal string") func (c *pathCompiler) parseLiteral() (string, error) { if c.skipByte('"') { mark := c.i if !c.skipByteFind('"') { return "", fmt.Errorf(`missing '"'`) } return c.path[mark:c.i-1], nil } if c.skipByte('\'') { mark := c.i if !c.skipByteFind('\'') { return "", fmt.Errorf(`missing "'"`) } return c.path[mark:c.i-1], nil } return "", errNoLiteral } func (c *pathCompiler) parseInt() (v int, ok bool) { mark := c.i for c.i < len(c.path) && c.path[c.i] >= '0' && c.path[c.i] <= '9' { v *= 10 v += int(c.path[c.i]) - '0' c.i++ } if c.i == mark { return 0, false } return v, true } func (c *pathCompiler) skipByte(b byte) bool { if c.i < len(c.path) && c.path[c.i] == b { c.i++ return true } return false } func (c *pathCompiler) skipByteFind(b byte) bool { for i := c.i; i < len(c.path); i++ { if c.path[i] == b { c.i = i+1 return true } } return false } func (c *pathCompiler) peekByte(b byte) bool { return c.i < len(c.path) && c.path[c.i] == b } func (c *pathCompiler) skipName() bool { if c.i >= len(c.path) { return false } if c.path[c.i] == '*' { c.i++ return true } start := c.i for c.i < len(c.path) && (c.path[c.i] >= utf8.RuneSelf || isNameByte(c.path[c.i])) { c.i++ } return c.i > start } func isNameByte(c byte) bool { return 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' || c == '_' || c == '.' || c == '-' } ================================================ FILE: vendor/github.com/mattn/go-colorable/LICENSE ================================================ The MIT License (MIT) Copyright (c) 2016 Yasuhiro Matsumoto Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: vendor/github.com/mattn/go-colorable/README.md ================================================ # go-colorable Colorable writer for windows. For example, most of logger packages doesn't show colors on windows. (I know we can do it with ansicon. But I don't want.) This package is possible to handle escape sequence for ansi color on windows. ## Too Bad! ![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/bad.png) ## So Good! ![](https://raw.githubusercontent.com/mattn/go-colorable/gh-pages/good.png) ## Usage ```go logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) logrus.SetOutput(colorable.NewColorableStdout()) logrus.Info("succeeded") logrus.Warn("not correct") logrus.Error("something error") logrus.Fatal("panic") ``` You can compile above code on non-windows OSs. ## Installation ``` $ go get github.com/mattn/go-colorable ``` # License MIT # Author Yasuhiro Matsumoto (a.k.a mattn) ================================================ FILE: vendor/github.com/mattn/go-colorable/_example/main.go ================================================ package main import ( "github.com/Sirupsen/logrus" "github.com/mattn/go-colorable" ) func main() { logrus.SetFormatter(&logrus.TextFormatter{ForceColors: true}) logrus.SetOutput(colorable.NewColorableStdout()) logrus.Info("succeeded") logrus.Warn("not correct") logrus.Error("something error") logrus.Fatal("panic") } ================================================ FILE: vendor/github.com/mattn/go-colorable/colorable_others.go ================================================ // +build !windows package colorable import ( "io" "os" ) func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") } return file } func NewColorableStdout() io.Writer { return os.Stdout } func NewColorableStderr() io.Writer { return os.Stderr } ================================================ FILE: vendor/github.com/mattn/go-colorable/colorable_windows.go ================================================ package colorable import ( "bytes" "fmt" "io" "math" "os" "strconv" "strings" "syscall" "unsafe" "github.com/mattn/go-isatty" ) const ( foregroundBlue = 0x1 foregroundGreen = 0x2 foregroundRed = 0x4 foregroundIntensity = 0x8 foregroundMask = (foregroundRed | foregroundBlue | foregroundGreen | foregroundIntensity) backgroundBlue = 0x10 backgroundGreen = 0x20 backgroundRed = 0x40 backgroundIntensity = 0x80 backgroundMask = (backgroundRed | backgroundBlue | backgroundGreen | backgroundIntensity) ) type wchar uint16 type short int16 type dword uint32 type word uint16 type coord struct { x short y short } type smallRect struct { left short top short right short bottom short } type consoleScreenBufferInfo struct { size coord cursorPosition coord attributes word window smallRect maximumWindowSize coord } var ( kernel32 = syscall.NewLazyDLL("kernel32.dll") procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo") procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute") procSetConsoleCursorPosition = kernel32.NewProc("SetConsoleCursorPosition") procFillConsoleOutputCharacter = kernel32.NewProc("FillConsoleOutputCharacterW") procFillConsoleOutputAttribute = kernel32.NewProc("FillConsoleOutputAttribute") ) type Writer struct { out io.Writer handle syscall.Handle lastbuf bytes.Buffer oldattr word } func NewColorable(file *os.File) io.Writer { if file == nil { panic("nil passed instead of *os.File to NewColorable()") } if isatty.IsTerminal(file.Fd()) { var csbi consoleScreenBufferInfo handle := syscall.Handle(file.Fd()) procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi))) return &Writer{out: file, handle: handle, oldattr: csbi.attributes} } else { return file } } func NewColorableStdout() io.Writer { return NewColorable(os.Stdout) } func NewColorableStderr() io.Writer { return NewColorable(os.Stderr) } var color256 = map[int]int{ 0: 0x000000, 1: 0x800000, 2: 0x008000, 3: 0x808000, 4: 0x000080, 5: 0x800080, 6: 0x008080, 7: 0xc0c0c0, 8: 0x808080, 9: 0xff0000, 10: 0x00ff00, 11: 0xffff00, 12: 0x0000ff, 13: 0xff00ff, 14: 0x00ffff, 15: 0xffffff, 16: 0x000000, 17: 0x00005f, 18: 0x000087, 19: 0x0000af, 20: 0x0000d7, 21: 0x0000ff, 22: 0x005f00, 23: 0x005f5f, 24: 0x005f87, 25: 0x005faf, 26: 0x005fd7, 27: 0x005fff, 28: 0x008700, 29: 0x00875f, 30: 0x008787, 31: 0x0087af, 32: 0x0087d7, 33: 0x0087ff, 34: 0x00af00, 35: 0x00af5f, 36: 0x00af87, 37: 0x00afaf, 38: 0x00afd7, 39: 0x00afff, 40: 0x00d700, 41: 0x00d75f, 42: 0x00d787, 43: 0x00d7af, 44: 0x00d7d7, 45: 0x00d7ff, 46: 0x00ff00, 47: 0x00ff5f, 48: 0x00ff87, 49: 0x00ffaf, 50: 0x00ffd7, 51: 0x00ffff, 52: 0x5f0000, 53: 0x5f005f, 54: 0x5f0087, 55: 0x5f00af, 56: 0x5f00d7, 57: 0x5f00ff, 58: 0x5f5f00, 59: 0x5f5f5f, 60: 0x5f5f87, 61: 0x5f5faf, 62: 0x5f5fd7, 63: 0x5f5fff, 64: 0x5f8700, 65: 0x5f875f, 66: 0x5f8787, 67: 0x5f87af, 68: 0x5f87d7, 69: 0x5f87ff, 70: 0x5faf00, 71: 0x5faf5f, 72: 0x5faf87, 73: 0x5fafaf, 74: 0x5fafd7, 75: 0x5fafff, 76: 0x5fd700, 77: 0x5fd75f, 78: 0x5fd787, 79: 0x5fd7af, 80: 0x5fd7d7, 81: 0x5fd7ff, 82: 0x5fff00, 83: 0x5fff5f, 84: 0x5fff87, 85: 0x5fffaf, 86: 0x5fffd7, 87: 0x5fffff, 88: 0x870000, 89: 0x87005f, 90: 0x870087, 91: 0x8700af, 92: 0x8700d7, 93: 0x8700ff, 94: 0x875f00, 95: 0x875f5f, 96: 0x875f87, 97: 0x875faf, 98: 0x875fd7, 99: 0x875fff, 100: 0x878700, 101: 0x87875f, 102: 0x878787, 103: 0x8787af, 104: 0x8787d7, 105: 0x8787ff, 106: 0x87af00, 107: 0x87af5f, 108: 0x87af87, 109: 0x87afaf, 110: 0x87afd7, 111: 0x87afff, 112: 0x87d700, 113: 0x87d75f, 114: 0x87d787, 115: 0x87d7af, 116: 0x87d7d7, 117: 0x87d7ff, 118: 0x87ff00, 119: 0x87ff5f, 120: 0x87ff87, 121: 0x87ffaf, 122: 0x87ffd7, 123: 0x87ffff, 124: 0xaf0000, 125: 0xaf005f, 126: 0xaf0087, 127: 0xaf00af, 128: 0xaf00d7, 129: 0xaf00ff, 130: 0xaf5f00, 131: 0xaf5f5f, 132: 0xaf5f87, 133: 0xaf5faf, 134: 0xaf5fd7, 135: 0xaf5fff, 136: 0xaf8700, 137: 0xaf875f, 138: 0xaf8787, 139: 0xaf87af, 140: 0xaf87d7, 141: 0xaf87ff, 142: 0xafaf00, 143: 0xafaf5f, 144: 0xafaf87, 145: 0xafafaf, 146: 0xafafd7, 147: 0xafafff, 148: 0xafd700, 149: 0xafd75f, 150: 0xafd787, 151: 0xafd7af, 152: 0xafd7d7, 153: 0xafd7ff, 154: 0xafff00, 155: 0xafff5f, 156: 0xafff87, 157: 0xafffaf, 158: 0xafffd7, 159: 0xafffff, 160: 0xd70000, 161: 0xd7005f, 162: 0xd70087, 163: 0xd700af, 164: 0xd700d7, 165: 0xd700ff, 166: 0xd75f00, 167: 0xd75f5f, 168: 0xd75f87, 169: 0xd75faf, 170: 0xd75fd7, 171: 0xd75fff, 172: 0xd78700, 173: 0xd7875f, 174: 0xd78787, 175: 0xd787af, 176: 0xd787d7, 177: 0xd787ff, 178: 0xd7af00, 179: 0xd7af5f, 180: 0xd7af87, 181: 0xd7afaf, 182: 0xd7afd7, 183: 0xd7afff, 184: 0xd7d700, 185: 0xd7d75f, 186: 0xd7d787, 187: 0xd7d7af, 188: 0xd7d7d7, 189: 0xd7d7ff, 190: 0xd7ff00, 191: 0xd7ff5f, 192: 0xd7ff87, 193: 0xd7ffaf, 194: 0xd7ffd7, 195: 0xd7ffff, 196: 0xff0000, 197: 0xff005f, 198: 0xff0087, 199: 0xff00af, 200: 0xff00d7, 201: 0xff00ff, 202: 0xff5f00, 203: 0xff5f5f, 204: 0xff5f87, 205: 0xff5faf, 206: 0xff5fd7, 207: 0xff5fff, 208: 0xff8700, 209: 0xff875f, 210: 0xff8787, 211: 0xff87af, 212: 0xff87d7, 213: 0xff87ff, 214: 0xffaf00, 215: 0xffaf5f, 216: 0xffaf87, 217: 0xffafaf, 218: 0xffafd7, 219: 0xffafff, 220: 0xffd700, 221: 0xffd75f, 222: 0xffd787, 223: 0xffd7af, 224: 0xffd7d7, 225: 0xffd7ff, 226: 0xffff00, 227: 0xffff5f, 228: 0xffff87, 229: 0xffffaf, 230: 0xffffd7, 231: 0xffffff, 232: 0x080808, 233: 0x121212, 234: 0x1c1c1c, 235: 0x262626, 236: 0x303030, 237: 0x3a3a3a, 238: 0x444444, 239: 0x4e4e4e, 240: 0x585858, 241: 0x626262, 242: 0x6c6c6c, 243: 0x767676, 244: 0x808080, 245: 0x8a8a8a, 246: 0x949494, 247: 0x9e9e9e, 248: 0xa8a8a8, 249: 0xb2b2b2, 250: 0xbcbcbc, 251: 0xc6c6c6, 252: 0xd0d0d0, 253: 0xdadada, 254: 0xe4e4e4, 255: 0xeeeeee, } func (w *Writer) Write(data []byte) (n int, err error) { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) er := bytes.NewBuffer(data) loop: for { r1, _, err := procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) if r1 == 0 { break loop } c1, _, err := er.ReadRune() if err != nil { break loop } if c1 != 0x1b { fmt.Fprint(w.out, string(c1)) continue } c2, _, err := er.ReadRune() if err != nil { w.lastbuf.WriteRune(c1) break loop } if c2 != 0x5b { w.lastbuf.WriteRune(c1) w.lastbuf.WriteRune(c2) continue } var buf bytes.Buffer var m rune for { c, _, err := er.ReadRune() if err != nil { w.lastbuf.WriteRune(c1) w.lastbuf.WriteRune(c2) w.lastbuf.Write(buf.Bytes()) break loop } if ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '@' { m = c break } buf.Write([]byte(string(c))) } var csbi consoleScreenBufferInfo switch m { case 'A': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'B': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'C': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x -= short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'D': n, err = strconv.Atoi(buf.String()) if err != nil { continue } if n, err = strconv.Atoi(buf.String()); err == nil { var csbi consoleScreenBufferInfo procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x += short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) } case 'E': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y += short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'F': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = 0 csbi.cursorPosition.y -= short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'G': n, err = strconv.Atoi(buf.String()) if err != nil { continue } procGetConsoleScreenBufferInfo.Call(uintptr(w.handle), uintptr(unsafe.Pointer(&csbi))) csbi.cursorPosition.x = short(n) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'H': token := strings.Split(buf.String(), ";") if len(token) != 2 { continue } n1, err := strconv.Atoi(token[0]) if err != nil { continue } n2, err := strconv.Atoi(token[1]) if err != nil { continue } csbi.cursorPosition.x = short(n2) csbi.cursorPosition.x = short(n1) procSetConsoleCursorPosition.Call(uintptr(w.handle), *(*uintptr)(unsafe.Pointer(&csbi.cursorPosition))) case 'J': n, err := strconv.Atoi(buf.String()) if err != nil { continue } var cursor coord switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top} case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top} } var count, written dword count = dword(csbi.size.x - csbi.cursorPosition.x + (csbi.size.y-csbi.cursorPosition.y)*csbi.size.x) procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'K': n, err := strconv.Atoi(buf.String()) if err != nil { continue } var cursor coord switch n { case 0: cursor = coord{x: csbi.cursorPosition.x, y: csbi.cursorPosition.y} case 1: cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} case 2: cursor = coord{x: csbi.window.left, y: csbi.window.top + csbi.cursorPosition.y} } var count, written dword count = dword(csbi.size.x - csbi.cursorPosition.x) procFillConsoleOutputCharacter.Call(uintptr(w.handle), uintptr(' '), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) procFillConsoleOutputAttribute.Call(uintptr(w.handle), uintptr(csbi.attributes), uintptr(count), *(*uintptr)(unsafe.Pointer(&cursor)), uintptr(unsafe.Pointer(&written))) case 'm': attr := csbi.attributes cs := buf.String() if cs == "" { procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(w.oldattr)) continue } token := strings.Split(cs, ";") for i := 0; i < len(token); i += 1 { ns := token[i] if n, err = strconv.Atoi(ns); err == nil { switch { case n == 0 || n == 100: attr = w.oldattr case 1 <= n && n <= 5: attr |= foregroundIntensity case n == 7: attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) case 22 == n || n == 25 || n == 25: attr |= foregroundIntensity case n == 27: attr = ((attr & foregroundMask) << 4) | ((attr & backgroundMask) >> 4) case 30 <= n && n <= 37: attr = (attr & backgroundMask) if (n-30)&1 != 0 { attr |= foregroundRed } if (n-30)&2 != 0 { attr |= foregroundGreen } if (n-30)&4 != 0 { attr |= foregroundBlue } case n == 38: // set foreground color. if i < len(token)-2 && (token[i+1] == "5" || token[i+1] == "05") { if n256, err := strconv.Atoi(token[i+2]); err == nil { if n256foreAttr == nil { n256setup() } attr &= backgroundMask attr |= n256foreAttr[n256] i += 2 } } else { attr = attr & (w.oldattr & backgroundMask) } case n == 39: // reset foreground color. attr &= backgroundMask attr |= w.oldattr & foregroundMask case 40 <= n && n <= 47: attr = (attr & foregroundMask) if (n-40)&1 != 0 { attr |= backgroundRed } if (n-40)&2 != 0 { attr |= backgroundGreen } if (n-40)&4 != 0 { attr |= backgroundBlue } case n == 48: // set background color. if i < len(token)-2 && token[i+1] == "5" { if n256, err := strconv.Atoi(token[i+2]); err == nil { if n256backAttr == nil { n256setup() } attr &= foregroundMask attr |= n256backAttr[n256] i += 2 } } else { attr = attr & (w.oldattr & foregroundMask) } case n == 49: // reset foreground color. attr &= foregroundMask attr |= w.oldattr & backgroundMask case 90 <= n && n <= 97: attr = (attr & backgroundMask) attr |= foregroundIntensity if (n-90)&1 != 0 { attr |= foregroundRed } if (n-90)&2 != 0 { attr |= foregroundGreen } if (n-90)&4 != 0 { attr |= foregroundBlue } case 100 <= n && n <= 107: attr = (attr & foregroundMask) attr |= backgroundIntensity if (n-100)&1 != 0 { attr |= backgroundRed } if (n-100)&2 != 0 { attr |= backgroundGreen } if (n-100)&4 != 0 { attr |= backgroundBlue } } procSetConsoleTextAttribute.Call(uintptr(w.handle), uintptr(attr)) } } } } return len(data) - w.lastbuf.Len(), nil } type consoleColor struct { rgb int red bool green bool blue bool intensity bool } func (c consoleColor) foregroundAttr() (attr word) { if c.red { attr |= foregroundRed } if c.green { attr |= foregroundGreen } if c.blue { attr |= foregroundBlue } if c.intensity { attr |= foregroundIntensity } return } func (c consoleColor) backgroundAttr() (attr word) { if c.red { attr |= backgroundRed } if c.green { attr |= backgroundGreen } if c.blue { attr |= backgroundBlue } if c.intensity { attr |= backgroundIntensity } return } var color16 = []consoleColor{ consoleColor{0x000000, false, false, false, false}, consoleColor{0x000080, false, false, true, false}, consoleColor{0x008000, false, true, false, false}, consoleColor{0x008080, false, true, true, false}, consoleColor{0x800000, true, false, false, false}, consoleColor{0x800080, true, false, true, false}, consoleColor{0x808000, true, true, false, false}, consoleColor{0xc0c0c0, true, true, true, false}, consoleColor{0x808080, false, false, false, true}, consoleColor{0x0000ff, false, false, true, true}, consoleColor{0x00ff00, false, true, false, true}, consoleColor{0x00ffff, false, true, true, true}, consoleColor{0xff0000, true, false, false, true}, consoleColor{0xff00ff, true, false, true, true}, consoleColor{0xffff00, true, true, false, true}, consoleColor{0xffffff, true, true, true, true}, } type hsv struct { h, s, v float32 } func (a hsv) dist(b hsv) float32 { dh := a.h - b.h switch { case dh > 0.5: dh = 1 - dh case dh < -0.5: dh = -1 - dh } ds := a.s - b.s dv := a.v - b.v return float32(math.Sqrt(float64(dh*dh + ds*ds + dv*dv))) } func toHSV(rgb int) hsv { r, g, b := float32((rgb&0xFF0000)>>16)/256.0, float32((rgb&0x00FF00)>>8)/256.0, float32(rgb&0x0000FF)/256.0 min, max := minmax3f(r, g, b) h := max - min if h > 0 { if max == r { h = (g - b) / h if h < 0 { h += 6 } } else if max == g { h = 2 + (b-r)/h } else { h = 4 + (r-g)/h } } h /= 6.0 s := max - min if max != 0 { s /= max } v := max return hsv{h: h, s: s, v: v} } type hsvTable []hsv func toHSVTable(rgbTable []consoleColor) hsvTable { t := make(hsvTable, len(rgbTable)) for i, c := range rgbTable { t[i] = toHSV(c.rgb) } return t } func (t hsvTable) find(rgb int) consoleColor { hsv := toHSV(rgb) n := 7 l := float32(5.0) for i, p := range t { d := hsv.dist(p) if d < l { l, n = d, i } } return color16[n] } func minmax3f(a, b, c float32) (min, max float32) { if a < b { if b < c { return a, c } else if a < c { return a, b } else { return c, b } } else { if a < c { return b, c } else if b < c { return b, a } else { return c, a } } } var n256foreAttr []word var n256backAttr []word func n256setup() { n256foreAttr = make([]word, 256) n256backAttr = make([]word, 256) t := toHSVTable(color16) for i, rgb := range color256 { c := t.find(rgb) n256foreAttr[i] = c.foregroundAttr() n256backAttr[i] = c.backgroundAttr() } } ================================================ FILE: vendor/github.com/mattn/go-isatty/LICENSE ================================================ Copyright (c) Yasuhiro MATSUMOTO MIT License (Expat) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: vendor/github.com/mattn/go-isatty/README.md ================================================ # go-isatty isatty for golang ## Usage ```go package main import ( "fmt" "github.com/mattn/go-isatty" "os" ) func main() { if isatty.IsTerminal(os.Stdout.Fd()) { fmt.Println("Is Terminal") } else { fmt.Println("Is Not Terminal") } } ``` ## Installation ``` $ go get github.com/mattn/go-isatty ``` # License MIT # Author Yasuhiro Matsumoto (a.k.a mattn) ================================================ FILE: vendor/github.com/mattn/go-isatty/_example/example.go ================================================ package main import ( "fmt" "github.com/mattn/go-isatty" "os" ) func main() { if isatty.IsTerminal(int(os.Stdout.Fd())) { fmt.Println("Is Terminal") } else { fmt.Println("Is Not Terminal") } } ================================================ FILE: vendor/github.com/mattn/go-isatty/doc.go ================================================ // Package isatty implements interface to isatty package isatty ================================================ FILE: vendor/github.com/mattn/go-isatty/isatty_appengine.go ================================================ // +build appengine package isatty // IsTerminal returns true if the file descriptor is terminal which // is always false on on appengine classic which is a sandboxed PaaS. func IsTerminal(fd uintptr) bool { return false } ================================================ FILE: vendor/github.com/mattn/go-isatty/isatty_bsd.go ================================================ // +build darwin freebsd openbsd netbsd // +build !appengine package isatty import ( "syscall" "unsafe" ) const ioctlReadTermios = syscall.TIOCGETA // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } ================================================ FILE: vendor/github.com/mattn/go-isatty/isatty_linux.go ================================================ // +build linux // +build !appengine package isatty import ( "syscall" "unsafe" ) const ioctlReadTermios = syscall.TCGETS // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var termios syscall.Termios _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0) return err == 0 } ================================================ FILE: vendor/github.com/mattn/go-isatty/isatty_solaris.go ================================================ // +build solaris // +build !appengine package isatty import ( "golang.org/x/sys/unix" ) // IsTerminal returns true if the given file descriptor is a terminal. // see: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c func IsTerminal(fd uintptr) bool { var termio unix.Termio err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio) return err == nil } ================================================ FILE: vendor/github.com/mattn/go-isatty/isatty_windows.go ================================================ // +build windows // +build !appengine package isatty import ( "syscall" "unsafe" ) var kernel32 = syscall.NewLazyDLL("kernel32.dll") var procGetConsoleMode = kernel32.NewProc("GetConsoleMode") // IsTerminal return true if the file descriptor is terminal. func IsTerminal(fd uintptr) bool { var st uint32 r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0) return r != 0 && e == 0 } ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml ================================================ language: go ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE ================================================ 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 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. ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/README.md ================================================ # 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) ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/ext/moved.go ================================================ // Package ext moved to a new location: github.com/matttproud/golang_protobuf_extensions/pbutil. package ext ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbtest/doc.go ================================================ // Copyright 2015 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 pbtest provides mechanisms to assist with testing of Protocol Buffer messages. package pbtest ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbtest/example_test.go ================================================ // Copyright 2015 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 pbtest import ( "testing" "testing/quick" "github.com/golang/protobuf/proto" ) func Example() { // You would place this in a top-level function, like TestDatastore(t *testing.T). var ( datastore Datastore t *testing.T ) if err := quick.Check(func(rec *CustomerRecord) bool { // testing/quick generated rec using quick.Value. We want to ensure that // semi-internal struct fields are recursively reset to a known value. SanitizeGenerated(rec) // Ensure that any record can be stored, no matter what! if err := datastore.Store(rec); err != nil { return false } return true }, nil); err != nil { t.Fatal(err) } } // Datastore models some system under test. type Datastore struct{} // Store stores a customer record. func (Datastore) Store(*CustomerRecord) error { return nil } // Types below are generated from protoc --go_out=. example.proto, where // example.proto contains // """ // syntax = "proto2"; // message CustomerRecord { // } // """ type CustomerRecord struct { XXX_unrecognized []byte `json:"-"` } func (m *CustomerRecord) Reset() { *m = CustomerRecord{} } func (m *CustomerRecord) String() string { return proto.CompactTextString(m) } func (*CustomerRecord) ProtoMessage() {} ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbtest/quick.go ================================================ // Copyright 2015 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 pbtest import ( "errors" "reflect" "github.com/golang/protobuf/proto" ) var ( errNotPointer = errors.New("pbtest: cannot sanitize non-pointer message") errNotStruct = errors.New("pbtest: cannot sanitize non-struct message") ) // SanitizeGenerated empties the private state fields of Protocol Buffer // messages that have been generated by the testing/quick package or returns // an error indicating a problem it encountered. func SanitizeGenerated(m proto.Message) error { return sanitizeGenerated(m, 0) } func sanitizeGenerated(m proto.Message, l int) error { typ := reflect.TypeOf(m) if typ.Kind() != reflect.Ptr { if l == 0 { // Changes cannot be applied to non-pointers. return errNotPointer } return nil } if elemTyp := typ.Elem(); elemTyp.Kind() != reflect.Struct { if l == 0 { // Protocol Buffer messages are structures; only they can be cleaned. return errNotStruct } return nil } elem := reflect.ValueOf(m).Elem() for i := 0; i < elem.NumField(); i++ { field := elem.Field(i) if field.Type().Implements(reflect.TypeOf((*proto.Message)(nil)).Elem()) { if err := sanitizeGenerated(field.Interface().(proto.Message), l+1); err != nil { return err } } if field.Kind() == reflect.Slice { for i := 0; i < field.Len(); i++ { elem := field.Index(i) if elem.Type().Implements(reflect.TypeOf((*proto.Message)(nil)).Elem()) { if err := sanitizeGenerated(elem.Interface().(proto.Message), l+1); err != nil { return err } } } } } if field := elem.FieldByName("XXX_unrecognized"); field.IsValid() { field.Set(reflect.ValueOf([]byte{})) } if field := elem.FieldByName("XXX_extensions"); field.IsValid() { field.Set(reflect.ValueOf(nil)) } return nil } ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go ================================================ // 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 ( "bytes" "math/rand" "reflect" "testing" "testing/quick" "github.com/matttproud/golang_protobuf_extensions/pbtest" . "github.com/golang/protobuf/proto" . "github.com/golang/protobuf/proto/testdata" ) func TestWriteDelimited(t *testing.T) { for _, test := range []struct { msg Message buf []byte n int err error }{ { msg: &Empty{}, n: 1, buf: []byte{0}, }, { msg: &GoEnum{Foo: FOO_FOO1.Enum()}, n: 3, buf: []byte{2, 8, 1}, }, { msg: &Strings{ StringField: String(`This is my gigantic, unhappy string. It exceeds the encoding size of a single byte varint. We are using it to fuzz test the correctness of the header decoding mechanisms, which may prove problematic. I expect it may. Let's hope you enjoy testing as much as we do.`), }, n: 271, buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, }, } { var buf bytes.Buffer if n, err := WriteDelimited(&buf, test.msg); n != test.n || err != test.err { t.Fatalf("WriteDelimited(buf, %#v) = %v, %v; want %v, %v", test.msg, n, err, test.n, test.err) } if out := buf.Bytes(); !bytes.Equal(out, test.buf) { t.Fatalf("WriteDelimited(buf, %#v); buf = %v; want %v", test.msg, out, test.buf) } } } func TestReadDelimited(t *testing.T) { for _, test := range []struct { buf []byte msg Message n int err error }{ { buf: []byte{0}, msg: &Empty{}, n: 1, }, { n: 3, buf: []byte{2, 8, 1}, msg: &GoEnum{Foo: FOO_FOO1.Enum()}, }, { buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109, 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104, 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73, 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101, 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102, 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32, 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32, 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122, 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114, 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32, 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103, 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104, 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112, 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120, 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101, 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110, 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32, 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46}, msg: &Strings{ StringField: String(`This is my gigantic, unhappy string. It exceeds the encoding size of a single byte varint. We are using it to fuzz test the correctness of the header decoding mechanisms, which may prove problematic. I expect it may. Let's hope you enjoy testing as much as we do.`), }, n: 271, }, } { msg := Clone(test.msg) msg.Reset() if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err { t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err) } if !Equal(msg, test.msg) { t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg) } } } func TestEndToEndValid(t *testing.T) { for _, test := range [][]Message{ {&Empty{}}, {&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}}, {&GoEnum{Foo: FOO_FOO1.Enum()}}, {&Strings{ StringField: String(`This is my gigantic, unhappy string. It exceeds the encoding size of a single byte varint. We are using it to fuzz test the correctness of the header decoding mechanisms, which may prove problematic. I expect it may. Let's hope you enjoy testing as much as we do.`), }}, } { var buf bytes.Buffer var written int for i, msg := range test { n, err := WriteDelimited(&buf, msg) if err != nil { // Assumption: TestReadDelimited and TestWriteDelimited are sufficient // and inputs for this test are explicitly exercised there. t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", test, i, err) } written += n } var read int for i, msg := range test { out := Clone(msg) out.Reset() n, _ := ReadDelimited(&buf, out) // Decide to do EOF checking? read += n if !Equal(out, msg) { t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg) } } if read != written { t.Fatalf("%v read = %d; want %d", test, read, written) } } } // rndMessage generates a random valid Protocol Buffer message. func rndMessage(r *rand.Rand) Message { var t reflect.Type switch v := rand.Intn(23); v { // TODO(br): Uncomment the elements below once fix is incorporated, except // for the elements marked as patently incompatible. // case 0: // t = reflect.TypeOf(&GoEnum{}) // break // case 1: // t = reflect.TypeOf(&GoTestField{}) // break case 2: t = reflect.TypeOf(&GoTest{}) break // case 3: // t = reflect.TypeOf(&GoSkipTest{}) // break // case 4: // t = reflect.TypeOf(&NonPackedTest{}) // break // case 5: // t = reflect.TypeOf(&PackedTest{}) // break case 6: t = reflect.TypeOf(&MaxTag{}) break case 7: t = reflect.TypeOf(&OldMessage{}) break case 8: t = reflect.TypeOf(&NewMessage{}) break case 9: t = reflect.TypeOf(&InnerMessage{}) break case 10: t = reflect.TypeOf(&OtherMessage{}) break case 11: // PATENTLY INVALID FOR FUZZ GENERATION // t = reflect.TypeOf(&MyMessage{}) break // case 12: // t = reflect.TypeOf(&Ext{}) // break case 13: // PATENTLY INVALID FOR FUZZ GENERATION // t = reflect.TypeOf(&MyMessageSet{}) break // case 14: // t = reflect.TypeOf(&Empty{}) // break // case 15: // t = reflect.TypeOf(&MessageList{}) // break // case 16: // t = reflect.TypeOf(&Strings{}) // break // case 17: // t = reflect.TypeOf(&Defaults{}) // break // case 17: // t = reflect.TypeOf(&SubDefaults{}) // break // case 18: // t = reflect.TypeOf(&RepeatedEnum{}) // break case 19: t = reflect.TypeOf(&MoreRepeated{}) break // case 20: // t = reflect.TypeOf(&GroupOld{}) // break // case 21: // t = reflect.TypeOf(&GroupNew{}) // break case 22: t = reflect.TypeOf(&FloatingPoint{}) break default: // TODO(br): Replace with an unreachable once fixed. t = reflect.TypeOf(&GoTest{}) break } if t == nil { t = reflect.TypeOf(&GoTest{}) } v, ok := quick.Value(t, r) if !ok { panic("attempt to generate illegal item; consult item 11") } if err := pbtest.SanitizeGenerated(v.Interface().(Message)); err != nil { panic(err) } return v.Interface().(Message) } // rndMessages generates several random Protocol Buffer messages. func rndMessages(r *rand.Rand) []Message { n := r.Intn(128) out := make([]Message, 0, n) for i := 0; i < n; i++ { out = append(out, rndMessage(r)) } return out } func TestFuzz(t *testing.T) { rnd := rand.New(rand.NewSource(42)) check := func() bool { messages := rndMessages(rnd) var buf bytes.Buffer var written int for i, msg := range messages { n, err := WriteDelimited(&buf, msg) if err != nil { t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err) } written += n } var read int for i, msg := range messages { out := Clone(msg) out.Reset() n, _ := ReadDelimited(&buf, out) read += n if !Equal(out, msg) { t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg) } } if read != written { t.Fatalf("%v read = %d; want %d", messages, read, written) } return true } if err := quick.Check(check, nil); err != nil { t.Fatal(err) } } ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go ================================================ // 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. headerBuf := make([]byte, binary.MaxVarintLen32) 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) } ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go ================================================ // 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 ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go ================================================ // 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 } buf := make([]byte, binary.MaxVarintLen32) 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 } ================================================ FILE: vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go ================================================ // 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 pbutil import ( . "github.com/golang/protobuf/proto" . "github.com/golang/protobuf/proto/testdata" ) // FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go. func initGoTestField() *GoTestField { f := new(GoTestField) f.Label = String("label") f.Type = String("type") return f } // These are all structurally equivalent but the tag numbers differ. // (It's remarkable that required, optional, and repeated all have // 8 letters.) func initGoTest_RequiredGroup() *GoTest_RequiredGroup { return &GoTest_RequiredGroup{ RequiredField: String("required"), } } func initGoTest_OptionalGroup() *GoTest_OptionalGroup { return &GoTest_OptionalGroup{ RequiredField: String("optional"), } } func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup { return &GoTest_RepeatedGroup{ RequiredField: String("repeated"), } } func initGoTest(setdefaults bool) *GoTest { pb := new(GoTest) if setdefaults { pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted) pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted) pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted) pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted) pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted) pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted) pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted) pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted) pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted) pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted) pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted) pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted) } pb.Kind = GoTest_TIME.Enum() pb.RequiredField = initGoTestField() pb.F_BoolRequired = Bool(true) pb.F_Int32Required = Int32(3) pb.F_Int64Required = Int64(6) pb.F_Fixed32Required = Uint32(32) pb.F_Fixed64Required = Uint64(64) pb.F_Uint32Required = Uint32(3232) pb.F_Uint64Required = Uint64(6464) pb.F_FloatRequired = Float32(3232) pb.F_DoubleRequired = Float64(6464) pb.F_StringRequired = String("string") pb.F_BytesRequired = []byte("bytes") pb.F_Sint32Required = Int32(-32) pb.F_Sint64Required = Int64(-64) pb.Requiredgroup = initGoTest_RequiredGroup() return pb } ================================================ FILE: vendor/github.com/nu7hatch/gouuid/.gitignore ================================================ _obj _test *.6 *.out _testmain.go \#* .\#* *.log _cgo* *.o *.a ================================================ FILE: vendor/github.com/nu7hatch/gouuid/COPYING ================================================ Copyright (C) 2011 by Krzysztof Kowalik 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. ================================================ FILE: vendor/github.com/nu7hatch/gouuid/README.md ================================================ # Pure Go UUID implementation This package provides immutable UUID structs and the functions NewV3, NewV4, NewV5 and Parse() for generating versions 3, 4 and 5 UUIDs as specified in [RFC 4122](http://www.ietf.org/rfc/rfc4122.txt). ## Installation Use the `go` tool: $ go get github.com/nu7hatch/gouuid ## Usage See [documentation and examples](http://godoc.org/github.com/nu7hatch/gouuid) for more information. ## Copyright Copyright (C) 2011 by Krzysztof Kowalik . See [COPYING](https://github.com/nu7hatch/gouuid/tree/master/COPYING) file for details. ================================================ FILE: vendor/github.com/nu7hatch/gouuid/example_test.go ================================================ package uuid_test import ( "fmt" "github.com/nu7hatch/gouuid" ) func ExampleNewV4() { u4, err := uuid.NewV4() if err != nil { fmt.Println("error:", err) return } fmt.Println(u4) } func ExampleNewV5() { u5, err := uuid.NewV5(uuid.NamespaceURL, []byte("nu7hat.ch")) if err != nil { fmt.Println("error:", err) return } fmt.Println(u5) } func ExampleParseHex() { u, err := uuid.ParseHex("6ba7b810-9dad-11d1-80b4-00c04fd430c8") if err != nil { fmt.Println("error:", err) return } fmt.Println(u) } ================================================ FILE: vendor/github.com/nu7hatch/gouuid/uuid.go ================================================ // This package provides immutable UUID structs and the functions // NewV3, NewV4, NewV5 and Parse() for generating versions 3, 4 // and 5 UUIDs as specified in RFC 4122. // // Copyright (C) 2011 by Krzysztof Kowalik package uuid import ( "crypto/md5" "crypto/rand" "crypto/sha1" "encoding/hex" "errors" "fmt" "hash" "regexp" ) // The UUID reserved variants. const ( ReservedNCS byte = 0x80 ReservedRFC4122 byte = 0x40 ReservedMicrosoft byte = 0x20 ReservedFuture byte = 0x00 ) // The following standard UUIDs are for use with NewV3() or NewV5(). var ( NamespaceDNS, _ = ParseHex("6ba7b810-9dad-11d1-80b4-00c04fd430c8") NamespaceURL, _ = ParseHex("6ba7b811-9dad-11d1-80b4-00c04fd430c8") NamespaceOID, _ = ParseHex("6ba7b812-9dad-11d1-80b4-00c04fd430c8") NamespaceX500, _ = ParseHex("6ba7b814-9dad-11d1-80b4-00c04fd430c8") ) // Pattern used to parse hex string representation of the UUID. // FIXME: do something to consider both brackets at one time, // current one allows to parse string with only one opening // or closing bracket. const hexPattern = "^(urn\\:uuid\\:)?\\{?([a-z0-9]{8})-([a-z0-9]{4})-" + "([1-5][a-z0-9]{3})-([a-z0-9]{4})-([a-z0-9]{12})\\}?$" var re = regexp.MustCompile(hexPattern) // A UUID representation compliant with specification in // RFC 4122 document. type UUID [16]byte // ParseHex creates a UUID object from given hex string // representation. Function accepts UUID string in following // formats: // // uuid.ParseHex("6ba7b814-9dad-11d1-80b4-00c04fd430c8") // uuid.ParseHex("{6ba7b814-9dad-11d1-80b4-00c04fd430c8}") // uuid.ParseHex("urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8") // func ParseHex(s string) (u *UUID, err error) { md := re.FindStringSubmatch(s) if md == nil { err = errors.New("Invalid UUID string") return } hash := md[2] + md[3] + md[4] + md[5] + md[6] b, err := hex.DecodeString(hash) if err != nil { return } u = new(UUID) copy(u[:], b) return } // Parse creates a UUID object from given bytes slice. func Parse(b []byte) (u *UUID, err error) { if len(b) != 16 { err = errors.New("Given slice is not valid UUID sequence") return } u = new(UUID) copy(u[:], b) return } // Generate a UUID based on the MD5 hash of a namespace identifier // and a name. func NewV3(ns *UUID, name []byte) (u *UUID, err error) { if ns == nil { err = errors.New("Invalid namespace UUID") return } u = new(UUID) // Set all bits to MD5 hash generated from namespace and name. u.setBytesFromHash(md5.New(), ns[:], name) u.setVariant(ReservedRFC4122) u.setVersion(3) return } // Generate a random UUID. func NewV4() (u *UUID, err error) { u = new(UUID) // Set all bits to randomly (or pseudo-randomly) chosen values. _, err = rand.Read(u[:]) if err != nil { return } u.setVariant(ReservedRFC4122) u.setVersion(4) return } // Generate a UUID based on the SHA-1 hash of a namespace identifier // and a name. func NewV5(ns *UUID, name []byte) (u *UUID, err error) { u = new(UUID) // Set all bits to truncated SHA1 hash generated from namespace // and name. u.setBytesFromHash(sha1.New(), ns[:], name) u.setVariant(ReservedRFC4122) u.setVersion(5) return } // Generate a MD5 hash of a namespace and a name, and copy it to the // UUID slice. func (u *UUID) setBytesFromHash(hash hash.Hash, ns, name []byte) { hash.Write(ns[:]) hash.Write(name) copy(u[:], hash.Sum([]byte{})[:16]) } // Set the two most significant bits (bits 6 and 7) of the // clock_seq_hi_and_reserved to zero and one, respectively. func (u *UUID) setVariant(v byte) { switch v { case ReservedNCS: u[8] = (u[8] | ReservedNCS) & 0xBF case ReservedRFC4122: u[8] = (u[8] | ReservedRFC4122) & 0x7F case ReservedMicrosoft: u[8] = (u[8] | ReservedMicrosoft) & 0x3F } } // Variant returns the UUID Variant, which determines the internal // layout of the UUID. This will be one of the constants: RESERVED_NCS, // RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE. func (u *UUID) Variant() byte { if u[8]&ReservedNCS == ReservedNCS { return ReservedNCS } else if u[8]&ReservedRFC4122 == ReservedRFC4122 { return ReservedRFC4122 } else if u[8]&ReservedMicrosoft == ReservedMicrosoft { return ReservedMicrosoft } return ReservedFuture } // Set the four most significant bits (bits 12 through 15) of the // time_hi_and_version field to the 4-bit version number. func (u *UUID) setVersion(v byte) { u[6] = (u[6] & 0xF) | (v << 4) } // Version returns a version number of the algorithm used to // generate the UUID sequence. func (u *UUID) Version() uint { return uint(u[6] >> 4) } // Returns unparsed version of the generated UUID sequence. func (u *UUID) String() string { return fmt.Sprintf("%x-%x-%x-%x-%x", u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) } ================================================ FILE: vendor/github.com/nu7hatch/gouuid/uuid_test.go ================================================ // This package provides immutable UUID structs and the functions // NewV3, NewV4, NewV5 and Parse() for generating versions 3, 4 // and 5 UUIDs as specified in RFC 4122. // // Copyright (C) 2011 by Krzysztof Kowalik package uuid import ( "regexp" "testing" ) const format = "^[a-z0-9]{8}-[a-z0-9]{4}-[1-5][a-z0-9]{3}-[a-z0-9]{4}-[a-z0-9]{12}$" func TestParse(t *testing.T) { _, err := Parse([]byte{1, 2, 3, 4, 5}) if err == nil { t.Errorf("Expected error due to invalid UUID sequence") } base, _ := NewV4() u, err := Parse(base[:]) if err != nil { t.Errorf("Expected to parse UUID sequence without problems") return } if u.String() != base.String() { t.Errorf("Expected parsed UUID to be the same as base, %s != %s", u.String(), base.String()) } } func TestParseString(t *testing.T) { _, err := ParseHex("foo") if err == nil { t.Errorf("Expected error due to invalid UUID string") } base, _ := NewV4() u, err := ParseHex(base.String()) if err != nil { t.Errorf("Expected to parse UUID sequence without problems") return } if u.String() != base.String() { t.Errorf("Expected parsed UUID to be the same as base, %s != %s", u.String(), base.String()) } } func TestNewV3(t *testing.T) { u, err := NewV3(NamespaceURL, []byte("golang.org")) if err != nil { t.Errorf("Expected to generate UUID without problems, error thrown: %d", err.Error()) return } if u.Version() != 3 { t.Errorf("Expected to generate UUIDv3, given %d", u.Version()) } if u.Variant() != ReservedRFC4122 { t.Errorf("Expected to generate UUIDv3 RFC4122 variant, given %x", u.Variant()) } re := regexp.MustCompile(format) if !re.MatchString(u.String()) { t.Errorf("Expected string representation to be valid, given %s", u.String()) } u2, _ := NewV3(NamespaceURL, []byte("golang.org")) if u2.String() != u.String() { t.Errorf("Expected UUIDs generated of the same namespace and name to be the same") } u3, _ := NewV3(NamespaceDNS, []byte("golang.org")) if u3.String() == u.String() { t.Errorf("Expected UUIDs generated of different namespace and the same name to be different") } u4, _ := NewV3(NamespaceURL, []byte("code.google.com")) if u4.String() == u.String() { t.Errorf("Expected UUIDs generated of the same namespace and different names to be different") } } func TestNewV4(t *testing.T) { u, err := NewV4() if err != nil { t.Errorf("Expected to generate UUID without problems, error thrown: %s", err.Error()) return } if u.Version() != 4 { t.Errorf("Expected to generate UUIDv4, given %d", u.Version()) } if u.Variant() != ReservedRFC4122 { t.Errorf("Expected to generate UUIDv4 RFC4122 variant, given %x", u.Variant()) } re := regexp.MustCompile(format) if !re.MatchString(u.String()) { t.Errorf("Expected string representation to be valid, given %s", u.String()) } } func TestNewV5(t *testing.T) { u, err := NewV5(NamespaceURL, []byte("golang.org")) if err != nil { t.Errorf("Expected to generate UUID without problems, error thrown: %d", err.Error()) return } if u.Version() != 5 { t.Errorf("Expected to generate UUIDv5, given %d", u.Version()) } if u.Variant() != ReservedRFC4122 { t.Errorf("Expected to generate UUIDv5 RFC4122 variant, given %x", u.Variant()) } re := regexp.MustCompile(format) if !re.MatchString(u.String()) { t.Errorf("Expected string representation to be valid, given %s", u.String()) } u2, _ := NewV5(NamespaceURL, []byte("golang.org")) if u2.String() != u.String() { t.Errorf("Expected UUIDs generated of the same namespace and name to be the same") } u3, _ := NewV5(NamespaceDNS, []byte("golang.org")) if u3.String() == u.String() { t.Errorf("Expected UUIDs generated of different namespace and the same name to be different") } u4, _ := NewV5(NamespaceURL, []byte("code.google.com")) if u4.String() == u.String() { t.Errorf("Expected UUIDs generated of the same namespace and different names to be different") } } func BenchmarkParseHex(b *testing.B) { s := "f3593cff-ee92-40df-4086-87825b523f13" for i := 0; i < b.N; i++ { _, err := ParseHex(s) if err != nil { b.Fatal(err) } } b.StopTimer() b.ReportAllocs() } ================================================ FILE: vendor/github.com/pborman/uuid/CONTRIBUTORS ================================================ Paul Borman ================================================ FILE: vendor/github.com/pborman/uuid/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/pborman/uuid/dce.go ================================================ // 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)) } ================================================ FILE: vendor/github.com/pborman/uuid/doc.go ================================================ // 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 ================================================ FILE: vendor/github.com/pborman/uuid/hash.go ================================================ // 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 dervied 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) } ================================================ FILE: vendor/github.com/pborman/uuid/json.go ================================================ // 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) == 0 { return []byte(`""`), nil } return []byte(`"` + u.String() + `"`), nil } func (u *UUID) UnmarshalJSON(data []byte) error { if len(data) == 0 || string(data) == `""` { return nil } if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { 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 } ================================================ FILE: vendor/github.com/pborman/uuid/json_test.go ================================================ // 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/json" "reflect" "testing" ) var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") func TestJSON(t *testing.T) { type S struct { ID1 UUID ID2 UUID } s1 := S{ID1: testUUID} data, err := json.Marshal(&s1) if err != nil { t.Fatal(err) } var s2 S if err := json.Unmarshal(data, &s2); err != nil { t.Fatal(err) } if !reflect.DeepEqual(&s1, &s2) { t.Errorf("got %#v, want %#v", s2, s1) } } ================================================ FILE: vendor/github.com/pborman/uuid/node.go ================================================ // 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" var ( 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 { 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 { 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 { 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 { 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 } ================================================ FILE: vendor/github.com/pborman/uuid/seq_test.go ================================================ // 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 ( "flag" "runtime" "testing" "time" ) // This test is only run when --regressions is passed on the go test line. var regressions = flag.Bool("regressions", false, "run uuid regression tests") // TestClockSeqRace tests for a particular race condition of returning two // identical Version1 UUIDs. The duration of 1 minute was chosen as the race // condition, before being fixed, nearly always occured in under 30 seconds. func TestClockSeqRace(t *testing.T) { if !*regressions { t.Skip("skipping regression tests") } duration := time.Minute done := make(chan struct{}) defer close(done) ch := make(chan UUID, 10000) ncpu := runtime.NumCPU() switch ncpu { case 0, 1: // We can't run the test effectively. t.Skip("skipping race test, only one CPU detected") return default: runtime.GOMAXPROCS(ncpu) } for i := 0; i < ncpu; i++ { go func() { for { select { case <-done: return case ch <- NewUUID(): } } }() } uuids := make(map[string]bool) cnt := 0 start := time.Now() for u := range ch { s := u.String() if uuids[s] { t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s) return } uuids[s] = true if time.Since(start) > duration { return } cnt++ } } ================================================ FILE: vendor/github.com/pborman/uuid/time.go ================================================ // 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 ( mu 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 mu.Unlock() mu.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 mu.Unlock() mu.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 mu.Unlock() mu.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 } ================================================ FILE: vendor/github.com/pborman/uuid/util.go ================================================ // 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 = []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 } ================================================ FILE: vendor/github.com/pborman/uuid/uuid.go ================================================ // 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" "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 } uuid := make([]byte, 16) for i, x := range []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 uuid == nil || len(uuid) != 16 { return "" } b := []byte(uuid) return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", b[:4], b[4:6], b[6:8], b[8:10], b[10:]) } // 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 uuid == nil || len(uuid) != 16 { return "" } b := []byte(uuid) return fmt.Sprintf("urn:uuid:%08x-%04x-%04x-%04x-%012x", b[:4], b[4:6], b[6:8], b[8:10], b[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 } panic("unreachable") } // Version returns the verison 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 } ================================================ FILE: vendor/github.com/pborman/uuid/uuid_test.go ================================================ // 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" "fmt" "os" "strings" "testing" "time" ) type test struct { in string version Version variant Variant isuuid bool } var tests = []test{ {"f47ac10b-58cc-0372-8567-0e02b2c3d479", 0, RFC4122, true}, {"f47ac10b-58cc-1372-8567-0e02b2c3d479", 1, RFC4122, true}, {"f47ac10b-58cc-2372-8567-0e02b2c3d479", 2, RFC4122, true}, {"f47ac10b-58cc-3372-8567-0e02b2c3d479", 3, RFC4122, true}, {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-5372-8567-0e02b2c3d479", 5, RFC4122, true}, {"f47ac10b-58cc-6372-8567-0e02b2c3d479", 6, RFC4122, true}, {"f47ac10b-58cc-7372-8567-0e02b2c3d479", 7, RFC4122, true}, {"f47ac10b-58cc-8372-8567-0e02b2c3d479", 8, RFC4122, true}, {"f47ac10b-58cc-9372-8567-0e02b2c3d479", 9, RFC4122, true}, {"f47ac10b-58cc-a372-8567-0e02b2c3d479", 10, RFC4122, true}, {"f47ac10b-58cc-b372-8567-0e02b2c3d479", 11, RFC4122, true}, {"f47ac10b-58cc-c372-8567-0e02b2c3d479", 12, RFC4122, true}, {"f47ac10b-58cc-d372-8567-0e02b2c3d479", 13, RFC4122, true}, {"f47ac10b-58cc-e372-8567-0e02b2c3d479", 14, RFC4122, true}, {"f47ac10b-58cc-f372-8567-0e02b2c3d479", 15, RFC4122, true}, {"urn:uuid:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, {"URN:UUID:f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-0567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-1567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-2567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-3567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-4567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-5567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-6567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-7567-0e02b2c3d479", 4, Reserved, true}, {"f47ac10b-58cc-4372-8567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-9567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-a567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-b567-0e02b2c3d479", 4, RFC4122, true}, {"f47ac10b-58cc-4372-c567-0e02b2c3d479", 4, Microsoft, true}, {"f47ac10b-58cc-4372-d567-0e02b2c3d479", 4, Microsoft, true}, {"f47ac10b-58cc-4372-e567-0e02b2c3d479", 4, Future, true}, {"f47ac10b-58cc-4372-f567-0e02b2c3d479", 4, Future, true}, {"f47ac10b158cc-5372-a567-0e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc25372-a567-0e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc-53723a567-0e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc-5372-a56740e02b2c3d479", 0, Invalid, false}, {"f47ac10b-58cc-5372-a567-0e02-2c3d479", 0, Invalid, false}, {"g47ac10b-58cc-4372-a567-0e02b2c3d479", 0, Invalid, false}, } var constants = []struct { c interface{} name string }{ {Person, "Person"}, {Group, "Group"}, {Org, "Org"}, {Invalid, "Invalid"}, {RFC4122, "RFC4122"}, {Reserved, "Reserved"}, {Microsoft, "Microsoft"}, {Future, "Future"}, {Domain(17), "Domain17"}, {Variant(42), "BadVariant42"}, } func testTest(t *testing.T, in string, tt test) { uuid := Parse(in) if ok := (uuid != nil); ok != tt.isuuid { t.Errorf("Parse(%s) got %v expected %v\b", in, ok, tt.isuuid) } if uuid == nil { return } if v := uuid.Variant(); v != tt.variant { t.Errorf("Variant(%s) got %d expected %d\b", in, v, tt.variant) } if v, _ := uuid.Version(); v != tt.version { t.Errorf("Version(%s) got %d expected %d\b", in, v, tt.version) } } func TestUUID(t *testing.T) { for _, tt := range tests { testTest(t, tt.in, tt) testTest(t, strings.ToUpper(tt.in), tt) } } func TestConstants(t *testing.T) { for x, tt := range constants { v, ok := tt.c.(fmt.Stringer) if !ok { t.Errorf("%x: %v: not a stringer", x, v) } else if s := v.String(); s != tt.name { v, _ := tt.c.(int) t.Errorf("%x: Constant %T:%d gives %q, expected %q\n", x, tt.c, v, s, tt.name) } } } func TestRandomUUID(t *testing.T) { m := make(map[string]bool) for x := 1; x < 32; x++ { uuid := NewRandom() s := uuid.String() if m[s] { t.Errorf("NewRandom returned duplicated UUID %s\n", s) } m[s] = true if v, _ := uuid.Version(); v != 4 { t.Errorf("Random UUID of version %s\n", v) } if uuid.Variant() != RFC4122 { t.Errorf("Random UUID is variant %d\n", uuid.Variant()) } } } func TestNew(t *testing.T) { m := make(map[string]bool) for x := 1; x < 32; x++ { s := New() if m[s] { t.Errorf("New returned duplicated UUID %s\n", s) } m[s] = true uuid := Parse(s) if uuid == nil { t.Errorf("New returned %q which does not decode\n", s) continue } if v, _ := uuid.Version(); v != 4 { t.Errorf("Random UUID of version %s\n", v) } if uuid.Variant() != RFC4122 { t.Errorf("Random UUID is variant %d\n", uuid.Variant()) } } } func clockSeq(t *testing.T, uuid UUID) int { seq, ok := uuid.ClockSequence() if !ok { t.Fatalf("%s: invalid clock sequence\n", uuid) } return seq } func TestClockSeq(t *testing.T) { // Fake time.Now for this test to return a monotonically advancing time; restore it at end. defer func(orig func() time.Time) { timeNow = orig }(timeNow) monTime := time.Now() timeNow = func() time.Time { monTime = monTime.Add(1 * time.Second) return monTime } SetClockSequence(-1) uuid1 := NewUUID() uuid2 := NewUUID() if clockSeq(t, uuid1) != clockSeq(t, uuid2) { t.Errorf("clock sequence %d != %d\n", clockSeq(t, uuid1), clockSeq(t, uuid2)) } SetClockSequence(-1) uuid2 = NewUUID() // Just on the very off chance we generated the same sequence // two times we try again. if clockSeq(t, uuid1) == clockSeq(t, uuid2) { SetClockSequence(-1) uuid2 = NewUUID() } if clockSeq(t, uuid1) == clockSeq(t, uuid2) { t.Errorf("Duplicate clock sequence %d\n", clockSeq(t, uuid1)) } SetClockSequence(0x1234) uuid1 = NewUUID() if seq := clockSeq(t, uuid1); seq != 0x1234 { t.Errorf("%s: expected seq 0x1234 got 0x%04x\n", uuid1, seq) } } func TestCoding(t *testing.T) { text := "7d444840-9dc0-11d1-b245-5ffdce74fad2" urn := "urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2" data := UUID{ 0x7d, 0x44, 0x48, 0x40, 0x9d, 0xc0, 0x11, 0xd1, 0xb2, 0x45, 0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2, } if v := data.String(); v != text { t.Errorf("%x: encoded to %s, expected %s\n", data, v, text) } if v := data.URN(); v != urn { t.Errorf("%x: urn is %s, expected %s\n", data, v, urn) } uuid := Parse(text) if !Equal(uuid, data) { t.Errorf("%s: decoded to %s, expected %s\n", text, uuid, data) } } func TestVersion1(t *testing.T) { uuid1 := NewUUID() uuid2 := NewUUID() if Equal(uuid1, uuid2) { t.Errorf("%s:duplicate uuid\n", uuid1) } if v, _ := uuid1.Version(); v != 1 { t.Errorf("%s: version %s expected 1\n", uuid1, v) } if v, _ := uuid2.Version(); v != 1 { t.Errorf("%s: version %s expected 1\n", uuid2, v) } n1 := uuid1.NodeID() n2 := uuid2.NodeID() if !bytes.Equal(n1, n2) { t.Errorf("Different nodes %x != %x\n", n1, n2) } t1, ok := uuid1.Time() if !ok { t.Errorf("%s: invalid time\n", uuid1) } t2, ok := uuid2.Time() if !ok { t.Errorf("%s: invalid time\n", uuid2) } q1, ok := uuid1.ClockSequence() if !ok { t.Errorf("%s: invalid clock sequence\n", uuid1) } q2, ok := uuid2.ClockSequence() if !ok { t.Errorf("%s: invalid clock sequence", uuid2) } switch { case t1 == t2 && q1 == q2: t.Errorf("time stopped\n") case t1 > t2 && q1 == q2: t.Errorf("time reversed\n") case t1 < t2 && q1 != q2: t.Errorf("clock sequence chaned unexpectedly\n") } } func TestNodeAndTime(t *testing.T) { // Time is February 5, 1998 12:30:23.136364800 AM GMT uuid := Parse("7d444840-9dc0-11d1-b245-5ffdce74fad2") node := []byte{0x5f, 0xfd, 0xce, 0x74, 0xfa, 0xd2} ts, ok := uuid.Time() if ok { c := time.Unix(ts.UnixTime()) want := time.Date(1998, 2, 5, 0, 30, 23, 136364800, time.UTC) if !c.Equal(want) { t.Errorf("Got time %v, want %v", c, want) } } else { t.Errorf("%s: bad time\n", uuid) } if !bytes.Equal(node, uuid.NodeID()) { t.Errorf("Expected node %v got %v\n", node, uuid.NodeID()) } } func TestMD5(t *testing.T) { uuid := NewMD5(NameSpace_DNS, []byte("python.org")).String() want := "6fa459ea-ee8a-3ca4-894e-db77e160355e" if uuid != want { t.Errorf("MD5: got %q expected %q\n", uuid, want) } } func TestSHA1(t *testing.T) { uuid := NewSHA1(NameSpace_DNS, []byte("python.org")).String() want := "886313e1-3b8a-5372-9b90-0c9aee199e5d" if uuid != want { t.Errorf("SHA1: got %q expected %q\n", uuid, want) } } func TestNodeID(t *testing.T) { nid := []byte{1, 2, 3, 4, 5, 6} SetNodeInterface("") s := NodeInterface() if s == "" || s == "user" { t.Errorf("NodeInterface %q after SetInteface\n", s) } node1 := NodeID() if node1 == nil { t.Errorf("NodeID nil after SetNodeInterface\n", s) } SetNodeID(nid) s = NodeInterface() if s != "user" { t.Errorf("Expected NodeInterface %q got %q\n", "user", s) } node2 := NodeID() if node2 == nil { t.Errorf("NodeID nil after SetNodeID\n", s) } if bytes.Equal(node1, node2) { t.Errorf("NodeID not changed after SetNodeID\n", s) } else if !bytes.Equal(nid, node2) { t.Errorf("NodeID is %x, expected %x\n", node2, nid) } } func testDCE(t *testing.T, name string, uuid UUID, domain Domain, id uint32) { if uuid == nil { t.Errorf("%s failed\n", name) return } if v, _ := uuid.Version(); v != 2 { t.Errorf("%s: %s: expected version 2, got %s\n", name, uuid, v) return } if v, ok := uuid.Domain(); !ok || v != domain { if !ok { t.Errorf("%s: %d: Domain failed\n", name, uuid) } else { t.Errorf("%s: %s: expected domain %d, got %d\n", name, uuid, domain, v) } } if v, ok := uuid.Id(); !ok || v != id { if !ok { t.Errorf("%s: %d: Id failed\n", name, uuid) } else { t.Errorf("%s: %s: expected id %d, got %d\n", name, uuid, id, v) } } } func TestDCE(t *testing.T) { testDCE(t, "NewDCESecurity", NewDCESecurity(42, 12345678), 42, 12345678) testDCE(t, "NewDCEPerson", NewDCEPerson(), Person, uint32(os.Getuid())) testDCE(t, "NewDCEGroup", NewDCEGroup(), Group, uint32(os.Getgid())) } type badRand struct{} func (r badRand) Read(buf []byte) (int, error) { for i, _ := range buf { buf[i] = byte(i) } return len(buf), nil } func TestBadRand(t *testing.T) { SetRand(badRand{}) uuid1 := New() uuid2 := New() if uuid1 != uuid2 { t.Errorf("execpted duplicates, got %q and %q\n", uuid1, uuid2) } SetRand(nil) uuid1 = New() uuid2 = New() if uuid1 == uuid2 { t.Errorf("unexecpted duplicates, got %q\n", uuid1) } } ================================================ FILE: vendor/github.com/pborman/uuid/version1.go ================================================ // 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 } ================================================ FILE: vendor/github.com/pborman/uuid/version4.go ================================================ // 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 } ================================================ FILE: vendor/github.com/prometheus/client_golang/.gitignore ================================================ # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a *.so # Folders _obj _test # Architecture specific extensions/prefixes *.[568vq] [568vq].out *.cgo1.go *.cgo2.c _cgo_defun.c _cgo_gotypes.go _cgo_export.* _testmain.go *.exe *~ *# .build ================================================ FILE: vendor/github.com/prometheus/client_golang/.travis.yml ================================================ sudo: false language: go go: - 1.4 script: - go test -short ./... ================================================ FILE: vendor/github.com/prometheus/client_golang/AUTHORS.md ================================================ The Prometheus project was started by Matt T. Proud (emeritus) and Julius Volz in 2012. Maintainers of this repository: * Björn Rabenstein The following individuals have contributed code to this repository (listed in alphabetical order): * Bernerd Schaefer * Björn Rabenstein * Daniel Bornkessel * Jeff Younker * Julius Volz * Matt T. Proud * Tobias Schmidt ================================================ FILE: vendor/github.com/prometheus/client_golang/CHANGELOG.md ================================================ ## 0.7.0 / 2015-07-27 * [CHANGE] Rename ExporterLabelPrefix to ExportedLabelPrefix. * [BUGFIX] Closed gaps in metric consistency check. * [BUGFIX] Validate LabelName/LabelSet on JSON unmarshaling. * [ENHANCEMENT] Document the possibility to create "empty" metrics in a metric vector. * [ENHANCEMENT] Fix and clarify various doc comments and the README.md. * [ENHANCEMENT] (Kind of) solve "The Proxy Problem" of http.InstrumentHandler. * [ENHANCEMENT] Change responseWriterDelegator.written to int64. ## 0.6.0 / 2015-06-01 * [CHANGE] Rename process_goroutines to go_goroutines. * [ENHANCEMENT] Validate label names during YAML decoding. * [ENHANCEMENT] Add LabelName regular expression. * [BUGFIX] Ensure alignment of struct members for 32-bit systems. ## 0.5.0 / 2015-05-06 * [BUGFIX] Removed a weakness in the fingerprinting aka signature code. This makes fingerprinting slower and more allocation-heavy, but the weakness was too severe to be tolerated. * [CHANGE] As a result of the above, Metric.Fingerprint is now returning a different fingerprint. To keep the same fingerprint, the new method Metric.FastFingerprint was introduced, which will be used by the Prometheus server for storage purposes (implying that a collision detection has to be added, too). * [ENHANCEMENT] The Metric.Equal and Metric.Before do not depend on fingerprinting anymore, removing the possibility of an undetected fingerprint collision. * [FEATURE] The Go collector in the exposition library includes garbage collection stats. * [FEATURE] The exposition library allows to create constant "throw-away" summaries and histograms. * [CHANGE] A number of new reserved labels and prefixes. ## 0.4.0 / 2015-04-08 * [CHANGE] Return NaN when Summaries have no observations yet. * [BUGFIX] Properly handle Summary decay upon Write(). * [BUGFIX] Fix the documentation link to the consumption library. * [FEATURE] Allow the metric family injection hook to merge with existing metric families. * [ENHANCEMENT] Removed cgo dependency and conditional compilation of procfs. * [MAINTENANCE] Adjusted to changes in matttproud/golang_protobuf_extensions. ## 0.3.2 / 2015-03-11 * [BUGFIX] Fixed the receiver type of COWMetric.Set(). This method is only used by the Prometheus server internally. * [CLEANUP] Added licenses of vendored code left out by godep. ## 0.3.1 / 2015-03-04 * [ENHANCEMENT] Switched fingerprinting functions from own free list to sync.Pool. * [CHANGE] Makefile uses Go 1.4.2 now (only relevant for examples and tests). ## 0.3.0 / 2015-03-03 * [CHANGE] Changed the fingerprinting for metrics. THIS WILL INVALIDATE ALL PERSISTED FINGERPRINTS. IF YOU COMPILE THE PROMETHEUS SERVER WITH THIS VERSION, YOU HAVE TO WIPE THE PREVIOUSLY CREATED STORAGE. * [CHANGE] LabelValuesToSignature removed. (Nobody had used it, and it was arguably broken.) * [CHANGE] Vendored dependencies. Those are only used by the Makefile. If client_golang is used as a library, the vendoring will stay out of your way. * [BUGFIX] Remove a weakness in the fingerprinting for metrics. (This made the fingerprinting change above necessary.) * [FEATURE] Added new fingerprinting functions SignatureForLabels and SignatureWithoutLabels to be used by the Prometheus server. These functions require fewer allocations than the ones currently used by the server. ## 0.2.0 / 2015-02-23 * [FEATURE] Introduce new Histagram metric type. * [CHANGE] Ignore process collector errors for now (better error handling pending). * [CHANGE] Use clear error interface for process pidFn. * [BUGFIX] Fix Go download links for several archs and OSes. * [ENHANCEMENT] Massively improve Gauge and Counter performance. * [ENHANCEMENT] Catch illegal label names for summaries in histograms. * [ENHANCEMENT] Reduce allocations during fingerprinting. * [ENHANCEMENT] Remove cgo dependency. procfs package will only be included if both cgo is available and the build is for an OS with procfs. * [CLEANUP] Clean up code style issues. * [CLEANUP] Mark slow test as such and exclude them from travis. * [CLEANUP] Update protobuf library package name. * [CLEANUP] Updated vendoring of beorn7/perks. ## 0.1.0 / 2015-02-02 * [CLEANUP] Introduced semantic versioning and changelog. From now on, changes will be reported in this file. ================================================ FILE: vendor/github.com/prometheus/client_golang/CONTRIBUTING.md ================================================ # Contributing Prometheus uses GitHub to manage reviews of pull requests. * If you have a trivial fix or improvement, go ahead and create a pull request, addressing (with `@...`) one or more of the maintainers (see [AUTHORS.md](AUTHORS.md)) in the description of the pull request. * If you plan to do something more involved, first discuss your ideas on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). This will avoid unnecessary work and surely give you and us a good deal of inspiration. * Relevant coding style guidelines are the [Go Code Review Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) and the _Formatting and style_ section of Peter Bourgon's [Go: Best Practices for Production Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). ================================================ FILE: vendor/github.com/prometheus/client_golang/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/prometheus/client_golang/NOTICE ================================================ 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 ================================================ FILE: vendor/github.com/prometheus/client_golang/README.md ================================================ # 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. ================================================ FILE: vendor/github.com/prometheus/client_golang/VERSION ================================================ 0.7.0 ================================================ FILE: vendor/github.com/prometheus/client_golang/api/prometheus/api.go ================================================ // 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 provides bindings to the Prometheus HTTP API: // http://prometheus.io/docs/querying/api/ package prometheus import ( "encoding/json" "fmt" "io/ioutil" "net" "net/http" "net/url" "path" "strconv" "strings" "time" "github.com/prometheus/common/model" "golang.org/x/net/context" ) const ( statusAPIError = 422 apiPrefix = "/api/v1" epQuery = "/query" epQueryRange = "/query_range" epLabelValues = "/label/:name/values" epSeries = "/series" ) type ErrorType string const ( // The different API error types. ErrBadData ErrorType = "bad_data" ErrTimeout = "timeout" ErrCanceled = "canceled" ErrExec = "execution" ErrBadResponse = "bad_response" ) // Error is an error returned by the API. type Error struct { Type ErrorType Msg string } func (e *Error) Error() string { return fmt.Sprintf("%s: %s", e.Type, e.Msg) } // CancelableTransport is like net.Transport but provides // per-request cancelation functionality. type CancelableTransport interface { http.RoundTripper CancelRequest(req *http.Request) } var DefaultTransport CancelableTransport = &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).Dial, TLSHandshakeTimeout: 10 * time.Second, } // Config defines configuration parameters for a new client. type Config struct { // The address of the Prometheus to connect to. Address string // Transport is used by the Client to drive HTTP requests. If not // provided, DefaultTransport will be used. Transport CancelableTransport } func (cfg *Config) transport() CancelableTransport { if cfg.Transport == nil { return DefaultTransport } return cfg.Transport } type Client interface { url(ep string, args map[string]string) *url.URL do(context.Context, *http.Request) (*http.Response, []byte, error) } // New returns a new Client. func New(cfg Config) (Client, error) { u, err := url.Parse(cfg.Address) if err != nil { return nil, err } u.Path = apiPrefix return &httpClient{ endpoint: u, transport: cfg.transport(), }, nil } type httpClient struct { endpoint *url.URL transport CancelableTransport } func (c *httpClient) url(ep string, args map[string]string) *url.URL { p := path.Join(c.endpoint.Path, ep) for arg, val := range args { arg = ":" + arg p = strings.Replace(p, arg, val, -1) } u := *c.endpoint u.Path = p return &u } func (c *httpClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { type roundTripResponse struct { resp *http.Response err error } rtchan := make(chan roundTripResponse, 1) go func() { resp, err := c.transport.RoundTrip(req) rtchan <- roundTripResponse{resp: resp, err: err} close(rtchan) }() var resp *http.Response var err error select { case rtresp := <-rtchan: resp, err = rtresp.resp, rtresp.err case <-ctx.Done(): // Cancel request and wait until it terminated. c.transport.CancelRequest(req) resp, err = (<-rtchan).resp, ctx.Err() } defer func() { if resp != nil { resp.Body.Close() } }() if err != nil { return nil, nil, err } var body []byte done := make(chan struct{}) go func() { body, err = ioutil.ReadAll(resp.Body) close(done) }() select { case <-ctx.Done(): err = resp.Body.Close() <-done if err == nil { err = ctx.Err() } case <-done: } return resp, body, err } // apiClient wraps a regular client and processes successful API responses. // Successful also includes responses that errored at the API level. type apiClient struct { Client } type apiResponse struct { Status string `json:"status"` Data json.RawMessage `json:"data"` ErrorType ErrorType `json:"errorType"` Error string `json:"error"` } func (c apiClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { resp, body, err := c.Client.do(ctx, req) if err != nil { return resp, body, err } code := resp.StatusCode if code/100 != 2 && code != statusAPIError { return resp, body, &Error{ Type: ErrBadResponse, Msg: fmt.Sprintf("bad response code %d", resp.StatusCode), } } var result apiResponse if err = json.Unmarshal(body, &result); err != nil { return resp, body, &Error{ Type: ErrBadResponse, Msg: err.Error(), } } if (code == statusAPIError) != (result.Status == "error") { err = &Error{ Type: ErrBadResponse, Msg: "inconsistent body for response code", } } if code == statusAPIError && result.Status == "error" { err = &Error{ Type: result.ErrorType, Msg: result.Error, } } return resp, []byte(result.Data), err } // Range represents a sliced time range. type Range struct { // The boundaries of the time range. Start, End time.Time // The maximum time between two slices within the boundaries. Step time.Duration } // queryResult contains result data for a query. type queryResult struct { Type model.ValueType `json:"resultType"` Result interface{} `json:"result"` // The decoded value. v model.Value } func (qr *queryResult) UnmarshalJSON(b []byte) error { v := struct { Type model.ValueType `json:"resultType"` Result json.RawMessage `json:"result"` }{} err := json.Unmarshal(b, &v) if err != nil { return err } switch v.Type { case model.ValScalar: var sv model.Scalar err = json.Unmarshal(v.Result, &sv) qr.v = &sv case model.ValVector: var vv model.Vector err = json.Unmarshal(v.Result, &vv) qr.v = vv case model.ValMatrix: var mv model.Matrix err = json.Unmarshal(v.Result, &mv) qr.v = mv default: err = fmt.Errorf("unexpected value type %q", v.Type) } return err } // QueryAPI provides bindings the Prometheus's query API. type QueryAPI interface { // Query performs a query for the given time. Query(ctx context.Context, query string, ts time.Time) (model.Value, error) // Query performs a query for the given range. QueryRange(ctx context.Context, query string, r Range) (model.Value, error) } // NewQueryAPI returns a new QueryAPI for the client. func NewQueryAPI(c Client) QueryAPI { return &httpQueryAPI{client: apiClient{c}} } type httpQueryAPI struct { client Client } func (h *httpQueryAPI) Query(ctx context.Context, query string, ts time.Time) (model.Value, error) { u := h.client.url(epQuery, nil) q := u.Query() q.Set("query", query) q.Set("time", ts.Format(time.RFC3339Nano)) u.RawQuery = q.Encode() req, _ := http.NewRequest("GET", u.String(), nil) _, body, err := h.client.do(ctx, req) if err != nil { return nil, err } var qres queryResult err = json.Unmarshal(body, &qres) return model.Value(qres.v), err } func (h *httpQueryAPI) QueryRange(ctx context.Context, query string, r Range) (model.Value, error) { u := h.client.url(epQueryRange, nil) q := u.Query() var ( start = r.Start.Format(time.RFC3339Nano) end = r.End.Format(time.RFC3339Nano) step = strconv.FormatFloat(r.Step.Seconds(), 'f', 3, 64) ) q.Set("query", query) q.Set("start", start) q.Set("end", end) q.Set("step", step) u.RawQuery = q.Encode() req, _ := http.NewRequest("GET", u.String(), nil) _, body, err := h.client.do(ctx, req) if err != nil { return nil, err } var qres queryResult err = json.Unmarshal(body, &qres) return model.Value(qres.v), err } ================================================ FILE: vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go ================================================ // 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 ( "encoding/json" "fmt" "net/http" "net/url" "reflect" "testing" "time" "github.com/prometheus/common/model" "golang.org/x/net/context" ) func TestConfig(t *testing.T) { c := Config{} if c.transport() != DefaultTransport { t.Fatalf("expected default transport for nil Transport field") } } func TestClientURL(t *testing.T) { tests := []struct { address string endpoint string args map[string]string expected string }{ { address: "http://localhost:9090", endpoint: "/test", expected: "http://localhost:9090/test", }, { address: "http://localhost", endpoint: "/test", expected: "http://localhost/test", }, { address: "http://localhost:9090", endpoint: "test", expected: "http://localhost:9090/test", }, { address: "http://localhost:9090/prefix", endpoint: "/test", expected: "http://localhost:9090/prefix/test", }, { address: "https://localhost:9090/", endpoint: "/test/", expected: "https://localhost:9090/test", }, { address: "http://localhost:9090", endpoint: "/test/:param", args: map[string]string{ "param": "content", }, expected: "http://localhost:9090/test/content", }, { address: "http://localhost:9090", endpoint: "/test/:param/more/:param", args: map[string]string{ "param": "content", }, expected: "http://localhost:9090/test/content/more/content", }, { address: "http://localhost:9090", endpoint: "/test/:param/more/:foo", args: map[string]string{ "param": "content", "foo": "bar", }, expected: "http://localhost:9090/test/content/more/bar", }, { address: "http://localhost:9090", endpoint: "/test/:param", args: map[string]string{ "nonexistant": "content", }, expected: "http://localhost:9090/test/:param", }, } for _, test := range tests { ep, err := url.Parse(test.address) if err != nil { t.Fatal(err) } hclient := &httpClient{ endpoint: ep, transport: DefaultTransport, } u := hclient.url(test.endpoint, test.args) if u.String() != test.expected { t.Errorf("unexpected result: got %s, want %s", u, test.expected) continue } // The apiClient must return exactly the same result as the httpClient. aclient := &apiClient{hclient} u = aclient.url(test.endpoint, test.args) if u.String() != test.expected { t.Errorf("unexpected result: got %s, want %s", u, test.expected) } } } type testClient struct { *testing.T ch chan apiClientTest req *http.Request } type apiClientTest struct { code int response interface{} expected string err *Error } func (c *testClient) url(ep string, args map[string]string) *url.URL { return nil } func (c *testClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { if ctx == nil { c.Fatalf("context was not passed down") } if req != c.req { c.Fatalf("request was not passed down") } test := <-c.ch var b []byte var err error switch v := test.response.(type) { case string: b = []byte(v) default: b, err = json.Marshal(v) if err != nil { c.Fatal(err) } } resp := &http.Response{ StatusCode: test.code, } return resp, b, nil } func TestAPIClientDo(t *testing.T) { tests := []apiClientTest{ { response: &apiResponse{ Status: "error", Data: json.RawMessage(`null`), ErrorType: ErrBadData, Error: "failed", }, err: &Error{ Type: ErrBadData, Msg: "failed", }, code: statusAPIError, expected: `null`, }, { response: &apiResponse{ Status: "error", Data: json.RawMessage(`"test"`), ErrorType: ErrTimeout, Error: "timed out", }, err: &Error{ Type: ErrTimeout, Msg: "timed out", }, code: statusAPIError, expected: `test`, }, { response: "bad json", err: &Error{ Type: ErrBadResponse, Msg: "bad response code 400", }, code: http.StatusBadRequest, }, { response: "bad json", err: &Error{ Type: ErrBadResponse, Msg: "invalid character 'b' looking for beginning of value", }, code: statusAPIError, }, { response: &apiResponse{ Status: "success", Data: json.RawMessage(`"test"`), }, err: &Error{ Type: ErrBadResponse, Msg: "inconsistent body for response code", }, code: statusAPIError, }, { response: &apiResponse{ Status: "success", Data: json.RawMessage(`"test"`), ErrorType: ErrTimeout, Error: "timed out", }, err: &Error{ Type: ErrBadResponse, Msg: "inconsistent body for response code", }, code: statusAPIError, }, { response: &apiResponse{ Status: "error", Data: json.RawMessage(`"test"`), ErrorType: ErrTimeout, Error: "timed out", }, err: &Error{ Type: ErrBadResponse, Msg: "inconsistent body for response code", }, code: http.StatusOK, }, } tc := &testClient{ T: t, ch: make(chan apiClientTest, 1), req: &http.Request{}, } client := &apiClient{tc} for _, test := range tests { tc.ch <- test _, body, err := client.do(context.Background(), tc.req) if test.err != nil { if err == nil { t.Errorf("expected error %q but got none", test.err) continue } if test.err.Error() != err.Error() { t.Errorf("unexpected error: want %q, got %q", test.err, err) } continue } if err != nil { t.Errorf("unexpeceted error %s", err) continue } want, got := test.expected, string(body) if want != got { t.Errorf("unexpected body: want %q, got %q", want, got) } } } type apiTestClient struct { *testing.T curTest apiTest } type apiTest struct { do func() (interface{}, error) inErr error inRes interface{} reqPath string reqParam url.Values reqMethod string res interface{} err error } func (c *apiTestClient) url(ep string, args map[string]string) *url.URL { u := &url.URL{ Host: "test:9090", Path: apiPrefix + ep, } return u } func (c *apiTestClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) { test := c.curTest if req.URL.Path != test.reqPath { c.Errorf("unexpected request path: want %s, got %s", test.reqPath, req.URL.Path) } if req.Method != test.reqMethod { c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method) } b, err := json.Marshal(test.inRes) if err != nil { c.Fatal(err) } resp := &http.Response{} if test.inErr != nil { resp.StatusCode = statusAPIError } else { resp.StatusCode = http.StatusOK } return resp, b, test.inErr } func TestAPIs(t *testing.T) { testTime := time.Now() client := &apiTestClient{T: t} queryApi := &httpQueryAPI{ client: client, } doQuery := func(q string, ts time.Time) func() (interface{}, error) { return func() (interface{}, error) { return queryApi.Query(context.Background(), q, ts) } } doQueryRange := func(q string, rng Range) func() (interface{}, error) { return func() (interface{}, error) { return queryApi.QueryRange(context.Background(), q, rng) } } queryTests := []apiTest{ { do: doQuery("2", testTime), inRes: &queryResult{ Type: model.ValScalar, Result: &model.Scalar{ Value: 2, Timestamp: model.TimeFromUnix(testTime.Unix()), }, }, reqMethod: "GET", reqPath: "/api/v1/query", reqParam: url.Values{ "query": []string{"2"}, "time": []string{testTime.Format(time.RFC3339Nano)}, }, res: &model.Scalar{ Value: 2, Timestamp: model.TimeFromUnix(testTime.Unix()), }, }, { do: doQuery("2", testTime), inErr: fmt.Errorf("some error"), reqMethod: "GET", reqPath: "/api/v1/query", reqParam: url.Values{ "query": []string{"2"}, "time": []string{testTime.Format(time.RFC3339Nano)}, }, err: fmt.Errorf("some error"), }, { do: doQueryRange("2", Range{ Start: testTime.Add(-time.Minute), End: testTime, Step: time.Minute, }), inErr: fmt.Errorf("some error"), reqMethod: "GET", reqPath: "/api/v1/query_range", reqParam: url.Values{ "query": []string{"2"}, "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)}, "end": []string{testTime.Format(time.RFC3339Nano)}, "step": []string{time.Minute.String()}, }, err: fmt.Errorf("some error"), }, } var tests []apiTest tests = append(tests, queryTests...) for _, test := range tests { client.curTest = test res, err := test.do() if test.err != nil { if err == nil { t.Errorf("expected error %q but got none", test.err) continue } if err.Error() != test.err.Error() { t.Errorf("unexpected error: want %s, got %s", test.err, err) } continue } if err != nil { t.Errorf("unexpected error: %s", err) continue } if !reflect.DeepEqual(res, test.res) { t.Errorf("unexpected result: want %v, got %v", test.res, res) } } } ================================================ FILE: vendor/github.com/prometheus/client_golang/examples/random/main.go ================================================ // 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 simple example exposing fictional RPC latencies with different types of // random distributions (uniform, normal, and exponential) as Prometheus // metrics. package main import ( "flag" "math" "math/rand" "net/http" "time" "github.com/prometheus/client_golang/prometheus" ) var ( addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") uniformDomain = flag.Float64("uniform.domain", 200, "The domain for the uniform distribution.") normDomain = flag.Float64("normal.domain", 200, "The domain for the normal distribution.") normMean = flag.Float64("normal.mean", 10, "The mean for the normal distribution.") oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.") ) var ( // Create a summary to track fictional interservice RPC latencies for three // distinct services with different latency distributions. These services are // differentiated via a "service" label. rpcDurations = prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "rpc_durations_microseconds", Help: "RPC latency distributions.", }, []string{"service"}, ) // The same as above, but now as a histogram, and only for the normal // distribution. The buckets are targeted to the parameters of the // normal distribution, with 20 buckets centered on the mean, each // half-sigma wide. rpcDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{ Name: "rpc_durations_histogram_microseconds", Help: "RPC latency distributions.", Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20), }) ) func init() { // Register the summary and the histogram with Prometheus's default registry. prometheus.MustRegister(rpcDurations) prometheus.MustRegister(rpcDurationsHistogram) } func main() { flag.Parse() start := time.Now() oscillationFactor := func() float64 { return 2 + math.Sin(math.Sin(2*math.Pi*float64(time.Since(start))/float64(*oscillationPeriod))) } // Periodically record some sample latencies for the three services. go func() { for { v := rand.Float64() * *uniformDomain rpcDurations.WithLabelValues("uniform").Observe(v) time.Sleep(time.Duration(100*oscillationFactor()) * time.Millisecond) } }() go func() { for { v := (rand.NormFloat64() * *normDomain) + *normMean rpcDurations.WithLabelValues("normal").Observe(v) rpcDurationsHistogram.Observe(v) time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond) } }() go func() { for { v := rand.ExpFloat64() rpcDurations.WithLabelValues("exponential").Observe(v) time.Sleep(time.Duration(50*oscillationFactor()) * time.Millisecond) } }() // Expose the registered metrics via HTTP. http.Handle("/metrics", prometheus.Handler()) http.ListenAndServe(*addr, nil) } ================================================ FILE: vendor/github.com/prometheus/client_golang/examples/simple/main.go ================================================ // 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 minimal example of how to include Prometheus instrumentation. package main import ( "flag" "net/http" "github.com/prometheus/client_golang/prometheus" ) var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.") func main() { flag.Parse() http.Handle("/metrics", prometheus.Handler()) http.ListenAndServe(*addr, nil) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/.gitignore ================================================ command-line-arguments.test ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/README.md ================================================ # 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) ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go ================================================ // 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 ( "testing" ) func BenchmarkCounterWithLabelValues(b *testing.B) { m := NewCounterVec( CounterOpts{ Name: "benchmark_counter", Help: "A counter to benchmark it.", }, []string{"one", "two", "three"}, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.WithLabelValues("eins", "zwei", "drei").Inc() } } func BenchmarkCounterWithMappedLabels(b *testing.B) { m := NewCounterVec( CounterOpts{ Name: "benchmark_counter", Help: "A counter to benchmark it.", }, []string{"one", "two", "three"}, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.With(Labels{"two": "zwei", "one": "eins", "three": "drei"}).Inc() } } func BenchmarkCounterWithPreparedMappedLabels(b *testing.B) { m := NewCounterVec( CounterOpts{ Name: "benchmark_counter", Help: "A counter to benchmark it.", }, []string{"one", "two", "three"}, ) b.ReportAllocs() b.ResetTimer() labels := Labels{"two": "zwei", "one": "eins", "three": "drei"} for i := 0; i < b.N; i++ { m.With(labels).Inc() } } func BenchmarkCounterNoLabels(b *testing.B) { m := NewCounter(CounterOpts{ Name: "benchmark_counter", Help: "A counter to benchmark it.", }) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.Inc() } } func BenchmarkGaugeWithLabelValues(b *testing.B) { m := NewGaugeVec( GaugeOpts{ Name: "benchmark_gauge", Help: "A gauge to benchmark it.", }, []string{"one", "two", "three"}, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.WithLabelValues("eins", "zwei", "drei").Set(3.1415) } } func BenchmarkGaugeNoLabels(b *testing.B) { m := NewGauge(GaugeOpts{ Name: "benchmark_gauge", Help: "A gauge to benchmark it.", }) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.Set(3.1415) } } func BenchmarkSummaryWithLabelValues(b *testing.B) { m := NewSummaryVec( SummaryOpts{ Name: "benchmark_summary", Help: "A summary to benchmark it.", }, []string{"one", "two", "three"}, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) } } func BenchmarkSummaryNoLabels(b *testing.B) { m := NewSummary(SummaryOpts{ Name: "benchmark_summary", Help: "A summary to benchmark it.", }, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.Observe(3.1415) } } func BenchmarkHistogramWithLabelValues(b *testing.B) { m := NewHistogramVec( HistogramOpts{ Name: "benchmark_histogram", Help: "A histogram to benchmark it.", }, []string{"one", "two", "three"}, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.WithLabelValues("eins", "zwei", "drei").Observe(3.1415) } } func BenchmarkHistogramNoLabels(b *testing.B) { m := NewHistogram(HistogramOpts{ Name: "benchmark_histogram", Help: "A histogram to benchmark it.", }, ) b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { m.Observe(3.1415) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/collector.go ================================================ // 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 } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/counter.go ================================================ // 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" "hash/fnv" ) // 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, hash: fnv.New64a(), 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) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/counter_test.go ================================================ // 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 ( "math" "testing" dto "github.com/prometheus/client_model/go" ) func TestCounterAdd(t *testing.T) { counter := NewCounter(CounterOpts{ Name: "test", Help: "test help", ConstLabels: Labels{"a": "1", "b": "2"}, }).(*counter) counter.Inc() if expected, got := 1., math.Float64frombits(counter.valBits); expected != got { t.Errorf("Expected %f, got %f.", expected, got) } counter.Add(42) if expected, got := 43., math.Float64frombits(counter.valBits); expected != got { t.Errorf("Expected %f, got %f.", expected, got) } if expected, got := "counter cannot decrease in value", decreaseCounter(counter).Error(); expected != got { t.Errorf("Expected error %q, got %q.", expected, got) } m := &dto.Metric{} counter.Write(m) if expected, got := `label: label: counter: `, m.String(); expected != got { t.Errorf("expected %q, got %q", expected, got) } } func decreaseCounter(c *counter) (err error) { defer func() { if e := recover(); e != nil { err = e.(error) } }() c.Add(-1) return nil } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/desc.go ================================================ package prometheus import ( "bytes" "errors" "fmt" "hash/fnv" "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 } h := fnv.New64a() var b bytes.Buffer // To copy string contents into, avoiding []byte allocations. for _, val := range labelValues { b.Reset() b.WriteString(val) b.WriteByte(separatorByte) h.Write(b.Bytes()) } d.id = h.Sum64() // 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. h.Reset() b.Reset() b.WriteString(help) b.WriteByte(separatorByte) h.Write(b.Bytes()) for _, labelName := range labelNames { b.Reset() b.WriteString(labelName) b.WriteByte(separatorByte) h.Write(b.Bytes()) } d.dimHash = h.Sum64() 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) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/doc.go ================================================ // 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. // // 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 ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go ================================================ // 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_test import ( "sync" "github.com/prometheus/client_golang/prometheus" ) // ClusterManager is an example for a system that might have been built without // Prometheus in mind. It models a central manager of jobs running in a // cluster. To turn it into something that collects Prometheus metrics, we // simply add the two methods required for the Collector interface. // // An additional challenge is that multiple instances of the ClusterManager are // run within the same binary, each in charge of a different zone. We need to // make use of ConstLabels to be able to register each ClusterManager instance // with Prometheus. type ClusterManager struct { Zone string OOMCount *prometheus.CounterVec RAMUsage *prometheus.GaugeVec mtx sync.Mutex // Protects OOMCount and RAMUsage. // ... many more fields } // ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a // real cluster manager would have to do. Since it may actually be really // expensive, it must only be called once per collection. This implementation, // obviously, only returns some made-up data. func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( oomCountByHost map[string]int, ramUsageByHost map[string]float64, ) { // Just example fake data. oomCountByHost = map[string]int{ "foo.example.org": 42, "bar.example.org": 2001, } ramUsageByHost = map[string]float64{ "foo.example.org": 6.023e23, "bar.example.org": 3.14, } return } // Describe faces the interesting challenge that the two metric vectors that are // used in this example are already Collectors themselves. However, thanks to // the use of channels, it is really easy to "chain" Collectors. Here we simply // call the Describe methods of the two metric vectors. func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { c.OOMCount.Describe(ch) c.RAMUsage.Describe(ch) } // Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it // sets the retrieved values in the two metric vectors and then sends all their // metrics to the channel (again using a chaining technique as in the Describe // method). Since Collect could be called multiple times concurrently, that part // is protected by a mutex. func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState() c.mtx.Lock() defer c.mtx.Unlock() for host, oomCount := range oomCountByHost { c.OOMCount.WithLabelValues(host).Set(float64(oomCount)) } for host, ramUsage := range ramUsageByHost { c.RAMUsage.WithLabelValues(host).Set(ramUsage) } c.OOMCount.Collect(ch) c.RAMUsage.Collect(ch) // All metrics in OOMCount and RAMUsage are sent to the channel now. We // can safely reset the two metric vectors now, so that we can start // fresh in the next Collect cycle. (Imagine a host disappears from the // cluster. If we did not reset here, its Metric would stay in the // metric vectors forever.) c.OOMCount.Reset() c.RAMUsage.Reset() } // NewClusterManager creates the two metric vectors OOMCount and RAMUsage. Note // that the zone is set as a ConstLabel. (It's different in each instance of the // ClusterManager, but constant over the lifetime of an instance.) The reported // values are partitioned by host, which is therefore a variable label. func NewClusterManager(zone string) *ClusterManager { return &ClusterManager{ Zone: zone, OOMCount: prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: "clustermanager", Name: "oom_count", Help: "number of OOM crashes", ConstLabels: prometheus.Labels{"zone": zone}, }, []string{"host"}, ), RAMUsage: prometheus.NewGaugeVec( prometheus.GaugeOpts{ Subsystem: "clustermanager", Name: "ram_usage_bytes", Help: "RAM usage as reported to the cluster manager", ConstLabels: prometheus.Labels{"zone": zone}, }, []string{"host"}, ), } } func ExampleCollector_clustermanager() { workerDB := NewClusterManager("db") workerCA := NewClusterManager("ca") prometheus.MustRegister(workerDB) prometheus.MustRegister(workerCA) // Since we are dealing with custom Collector implementations, it might // be a good idea to enable the collect checks in the registry. prometheus.EnableCollectChecks(true) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/example_memstats_test.go ================================================ // 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_test import ( "runtime" "github.com/prometheus/client_golang/prometheus" ) var ( allocDesc = prometheus.NewDesc( prometheus.BuildFQName("", "memstats", "alloc_bytes"), "bytes allocated and still in use", nil, nil, ) totalAllocDesc = prometheus.NewDesc( prometheus.BuildFQName("", "memstats", "total_alloc_bytes"), "bytes allocated (even if freed)", nil, nil, ) numGCDesc = prometheus.NewDesc( prometheus.BuildFQName("", "memstats", "num_gc_total"), "number of GCs run", nil, nil, ) ) // MemStatsCollector is an example for a custom Collector that solves the // problem of feeding into multiple metrics at the same time. The // runtime.ReadMemStats should happen only once, and then the results need to be // fed into a number of separate Metrics. In this example, only a few of the // values reported by ReadMemStats are used. For each, there is a Desc provided // as a var, so the MemStatsCollector itself needs nothing else in the // struct. Only the methods need to be implemented. type MemStatsCollector struct{} // Describe just sends the three Desc objects for the Metrics we intend to // collect. func (_ MemStatsCollector) Describe(ch chan<- *prometheus.Desc) { ch <- allocDesc ch <- totalAllocDesc ch <- numGCDesc } // Collect does the trick by calling ReadMemStats once and then constructing // three different Metrics on the fly. func (_ MemStatsCollector) Collect(ch chan<- prometheus.Metric) { var ms runtime.MemStats runtime.ReadMemStats(&ms) ch <- prometheus.MustNewConstMetric( allocDesc, prometheus.GaugeValue, float64(ms.Alloc), ) ch <- prometheus.MustNewConstMetric( totalAllocDesc, prometheus.GaugeValue, float64(ms.TotalAlloc), ) ch <- prometheus.MustNewConstMetric( numGCDesc, prometheus.CounterValue, float64(ms.NumGC), ) // To avoid new allocations on each collection, you could also keep // metric objects around and return the same objects each time, just // with new values set. } func ExampleCollector_memstats() { prometheus.MustRegister(&MemStatsCollector{}) // Since we are dealing with custom Collector implementations, it might // be a good idea to enable the collect checks in the registry. prometheus.EnableCollectChecks(true) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go ================================================ // 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_test import ( "runtime" "github.com/golang/protobuf/proto" dto "github.com/prometheus/client_model/go" "github.com/prometheus/client_golang/prometheus" ) func NewCallbackMetric(desc *prometheus.Desc, callback func() float64) *CallbackMetric { result := &CallbackMetric{desc: desc, callback: callback} result.Init(result) // Initialize the SelfCollector. return result } // TODO: Come up with a better example. // CallbackMetric is an example for a user-defined Metric that exports the // result of a function call as a metric of type "untyped" without any // labels. It uses SelfCollector to turn the Metric into a Collector so that it // can be registered with Prometheus. // // Note that this example is pretty much academic as the prometheus package // already provides an UntypedFunc type. type CallbackMetric struct { prometheus.SelfCollector desc *prometheus.Desc callback func() float64 } func (cm *CallbackMetric) Desc() *prometheus.Desc { return cm.desc } func (cm *CallbackMetric) Write(m *dto.Metric) error { m.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())} return nil } func ExampleSelfCollector() { m := NewCallbackMetric( prometheus.NewDesc( "runtime_goroutines_count", "Total number of goroutines that currently exist.", nil, nil, // No labels, these must be nil. ), func() float64 { return float64(runtime.NumGoroutine()) }, ) prometheus.MustRegister(m) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/examples_test.go ================================================ // 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_test import ( "flag" "fmt" "math" "net/http" "os" "runtime" "sort" "time" dto "github.com/prometheus/client_model/go" "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" ) func ExampleGauge() { opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{ Namespace: "our_company", Subsystem: "blob_storage", Name: "ops_queued", Help: "Number of blob storage operations waiting to be processed.", }) prometheus.MustRegister(opsQueued) // 10 operations queued by the goroutine managing incoming requests. opsQueued.Add(10) // A worker goroutine has picked up a waiting operation. opsQueued.Dec() // And once more... opsQueued.Dec() } func ExampleGaugeVec() { binaryVersion := flag.String("binary_version", "debug", "Version of the binary: debug, canary, production.") flag.Parse() opsQueued := prometheus.NewGaugeVec( prometheus.GaugeOpts{ Namespace: "our_company", Subsystem: "blob_storage", Name: "ops_queued", Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.", ConstLabels: prometheus.Labels{"binary_version": *binaryVersion}, }, []string{ // Which user has requested the operation? "user", // Of what type is the operation? "type", }, ) prometheus.MustRegister(opsQueued) // Increase a value using compact (but order-sensitive!) WithLabelValues(). opsQueued.WithLabelValues("bob", "put").Add(4) // Increase a value with a map using WithLabels. More verbose, but order // doesn't matter anymore. opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc() } func ExampleGaugeFunc() { if err := prometheus.Register(prometheus.NewGaugeFunc( prometheus.GaugeOpts{ Subsystem: "runtime", Name: "goroutines_count", Help: "Number of goroutines that currently exist.", }, func() float64 { return float64(runtime.NumGoroutine()) }, )); err == nil { fmt.Println("GaugeFunc 'goroutines_count' registered.") } // Note that the count of goroutines is a gauge (and not a counter) as // it can go up and down. // Output: // GaugeFunc 'goroutines_count' registered. } func ExampleCounter() { pushCounter := prometheus.NewCounter(prometheus.CounterOpts{ Name: "repository_pushes", // Note: No help string... }) err := prometheus.Register(pushCounter) // ... so this will return an error. if err != nil { fmt.Println("Push counter couldn't be registered, no counting will happen:", err) return } // Try it once more, this time with a help string. pushCounter = prometheus.NewCounter(prometheus.CounterOpts{ Name: "repository_pushes", Help: "Number of pushes to external repository.", }) err = prometheus.Register(pushCounter) if err != nil { fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err) return } pushComplete := make(chan struct{}) // TODO: Start a goroutine that performs repository pushes and reports // each completion via the channel. for _ = range pushComplete { pushCounter.Inc() } // Output: // Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string } func ExampleCounterVec() { binaryVersion := flag.String("environment", "test", "Execution environment: test, staging, production.") flag.Parse() httpReqs := prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "http_requests_total", Help: "How many HTTP requests processed, partitioned by status code and HTTP method.", ConstLabels: prometheus.Labels{"env": *binaryVersion}, }, []string{"code", "method"}, ) prometheus.MustRegister(httpReqs) httpReqs.WithLabelValues("404", "POST").Add(42) // If you have to access the same set of labels very frequently, it // might be good to retrieve the metric only once and keep a handle to // it. But beware of deletion of that metric, see below! m := httpReqs.WithLabelValues("200", "GET") for i := 0; i < 1000000; i++ { m.Inc() } // Delete a metric from the vector. If you have previously kept a handle // to that metric (as above), future updates via that handle will go // unseen (even if you re-create a metric with the same label set // later). httpReqs.DeleteLabelValues("200", "GET") // Same thing with the more verbose Labels syntax. httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"}) } func ExampleInstrumentHandler() { // Handle the "/doc" endpoint with the standard http.FileServer handler. // By wrapping the handler with InstrumentHandler, request count, // request and response sizes, and request latency are automatically // exported to Prometheus, partitioned by HTTP status code and method // and by the handler name (here "fileserver"). http.Handle("/doc", prometheus.InstrumentHandler( "fileserver", http.FileServer(http.Dir("/usr/share/doc")), )) // The Prometheus handler still has to be registered to handle the // "/metrics" endpoint. The handler returned by prometheus.Handler() is // already instrumented - with "prometheus" as the handler name. In this // example, we want the handler name to be "metrics", so we instrument // the uninstrumented Prometheus handler ourselves. http.Handle("/metrics", prometheus.InstrumentHandler( "metrics", prometheus.UninstrumentedHandler(), )) } func ExampleLabelPairSorter() { labelPairs := []*dto.LabelPair{ &dto.LabelPair{Name: proto.String("status"), Value: proto.String("404")}, &dto.LabelPair{Name: proto.String("method"), Value: proto.String("get")}, } sort.Sort(prometheus.LabelPairSorter(labelPairs)) fmt.Println(labelPairs) // Output: // [name:"method" value:"get" name:"status" value:"404" ] } func ExampleRegister() { // Imagine you have a worker pool and want to count the tasks completed. taskCounter := prometheus.NewCounter(prometheus.CounterOpts{ Subsystem: "worker_pool", Name: "completed_tasks_total", Help: "Total number of tasks completed.", }) // This will register fine. if err := prometheus.Register(taskCounter); err != nil { fmt.Println(err) } else { fmt.Println("taskCounter registered.") } // Don't forget to tell the HTTP server about the Prometheus handler. // (In a real program, you still need to start the HTTP server...) http.Handle("/metrics", prometheus.Handler()) // Now you can start workers and give every one of them a pointer to // taskCounter and let it increment it whenever it completes a task. taskCounter.Inc() // This has to happen somewhere in the worker code. // But wait, you want to see how individual workers perform. So you need // a vector of counters, with one element for each worker. taskCounterVec := prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: "worker_pool", Name: "completed_tasks_total", Help: "Total number of tasks completed.", }, []string{"worker_id"}, ) // Registering will fail because we already have a metric of that name. if err := prometheus.Register(taskCounterVec); err != nil { fmt.Println("taskCounterVec not registered:", err) } else { fmt.Println("taskCounterVec registered.") } // To fix, first unregister the old taskCounter. if prometheus.Unregister(taskCounter) { fmt.Println("taskCounter unregistered.") } // Try registering taskCounterVec again. if err := prometheus.Register(taskCounterVec); err != nil { fmt.Println("taskCounterVec not registered:", err) } else { fmt.Println("taskCounterVec registered.") } // Bummer! Still doesn't work. // Prometheus will not allow you to ever export metrics with // inconsistent help strings or label names. After unregistering, the // unregistered metrics will cease to show up in the /metrics HTTP // response, but the registry still remembers that those metrics had // been exported before. For this example, we will now choose a // different name. (In a real program, you would obviously not export // the obsolete metric in the first place.) taskCounterVec = prometheus.NewCounterVec( prometheus.CounterOpts{ Subsystem: "worker_pool", Name: "completed_tasks_by_id", Help: "Total number of tasks completed.", }, []string{"worker_id"}, ) if err := prometheus.Register(taskCounterVec); err != nil { fmt.Println("taskCounterVec not registered:", err) } else { fmt.Println("taskCounterVec registered.") } // Finally it worked! // The workers have to tell taskCounterVec their id to increment the // right element in the metric vector. taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42. // Each worker could also keep a reference to their own counter element // around. Pick the counter at initialization time of the worker. myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code. myCounter.Inc() // Somewhere in the code of that worker. // Note that something like WithLabelValues("42", "spurious arg") would // panic (because you have provided too many label values). If you want // to get an error instead, use GetMetricWithLabelValues(...) instead. notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg") if err != nil { fmt.Println("Worker initialization failed:", err) } if notMyCounter == nil { fmt.Println("notMyCounter is nil.") } // A different (and somewhat tricky) approach is to use // ConstLabels. ConstLabels are pairs of label names and label values // that never change. You might ask what those labels are good for (and // rightfully so - if they never change, they could as well be part of // the metric name). There are essentially two use-cases: The first is // if labels are constant throughout the lifetime of a binary execution, // but they vary over time or between different instances of a running // binary. The second is what we have here: Each worker creates and // registers an own Counter instance where the only difference is in the // value of the ConstLabels. Those Counters can all be registered // because the different ConstLabel values guarantee that each worker // will increment a different Counter metric. counterOpts := prometheus.CounterOpts{ Subsystem: "worker_pool", Name: "completed_tasks", Help: "Total number of tasks completed.", ConstLabels: prometheus.Labels{"worker_id": "42"}, } taskCounterForWorker42 := prometheus.NewCounter(counterOpts) if err := prometheus.Register(taskCounterForWorker42); err != nil { fmt.Println("taskCounterVForWorker42 not registered:", err) } else { fmt.Println("taskCounterForWorker42 registered.") } // Obviously, in real code, taskCounterForWorker42 would be a member // variable of a worker struct, and the "42" would be retrieved with a // GetId() method or something. The Counter would be created and // registered in the initialization code of the worker. // For the creation of the next Counter, we can recycle // counterOpts. Just change the ConstLabels. counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"} taskCounterForWorker2001 := prometheus.NewCounter(counterOpts) if err := prometheus.Register(taskCounterForWorker2001); err != nil { fmt.Println("taskCounterVForWorker2001 not registered:", err) } else { fmt.Println("taskCounterForWorker2001 registered.") } taskCounterForWorker2001.Inc() taskCounterForWorker42.Inc() taskCounterForWorker2001.Inc() // Yet another approach would be to turn the workers themselves into // Collectors and register them. See the Collector example for details. // Output: // taskCounter registered. // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string // taskCounter unregistered. // taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string // taskCounterVec registered. // Worker initialization failed: inconsistent label cardinality // notMyCounter is nil. // taskCounterForWorker42 registered. // taskCounterForWorker2001 registered. } func ExampleSummary() { temps := prometheus.NewSummary(prometheus.SummaryOpts{ Name: "pond_temperature_celsius", Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. }) // Simulate some observations. for i := 0; i < 1000; i++ { temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) } // Just for demonstration, let's check the state of the summary by // (ab)using its Write method (which is usually only used by Prometheus // internally). metric := &dto.Metric{} temps.Write(metric) fmt.Println(proto.MarshalTextString(metric)) // Output: // summary: < // sample_count: 1000 // sample_sum: 29969.50000000001 // quantile: < // quantile: 0.5 // value: 31.1 // > // quantile: < // quantile: 0.9 // value: 41.3 // > // quantile: < // quantile: 0.99 // value: 41.9 // > // > } func ExampleSummaryVec() { temps := prometheus.NewSummaryVec( prometheus.SummaryOpts{ Name: "pond_temperature_celsius", Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. }, []string{"species"}, ) // Simulate some observations. for i := 0; i < 1000; i++ { temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10) } // Create a Summary without any observations. temps.WithLabelValues("leiopelma-hochstetteri") // Just for demonstration, let's check the state of the summary vector // by (ab)using its Collect method and the Write method of its elements // (which is usually only used by Prometheus internally - code like the // following will never appear in your own code). metricChan := make(chan prometheus.Metric) go func() { defer close(metricChan) temps.Collect(metricChan) }() metricStrings := []string{} for metric := range metricChan { dtoMetric := &dto.Metric{} metric.Write(dtoMetric) metricStrings = append(metricStrings, proto.MarshalTextString(dtoMetric)) } sort.Strings(metricStrings) // For reproducible print order. fmt.Println(metricStrings) // Output: // [label: < // name: "species" // value: "leiopelma-hochstetteri" // > // summary: < // sample_count: 0 // sample_sum: 0 // quantile: < // quantile: 0.5 // value: nan // > // quantile: < // quantile: 0.9 // value: nan // > // quantile: < // quantile: 0.99 // value: nan // > // > // label: < // name: "species" // value: "lithobates-catesbeianus" // > // summary: < // sample_count: 1000 // sample_sum: 31956.100000000017 // quantile: < // quantile: 0.5 // value: 32.4 // > // quantile: < // quantile: 0.9 // value: 41.4 // > // quantile: < // quantile: 0.99 // value: 41.9 // > // > // label: < // name: "species" // value: "litoria-caerulea" // > // summary: < // sample_count: 1000 // sample_sum: 29969.50000000001 // quantile: < // quantile: 0.5 // value: 31.1 // > // quantile: < // quantile: 0.9 // value: 41.3 // > // quantile: < // quantile: 0.99 // value: 41.9 // > // > // ] } func ExampleConstSummary() { desc := prometheus.NewDesc( "http_request_duration_seconds", "A summary of the HTTP request durations.", []string{"code", "method"}, prometheus.Labels{"owner": "example"}, ) // Create a constant summary from values we got from a 3rd party telemetry system. s := prometheus.MustNewConstSummary( desc, 4711, 403.34, map[float64]float64{0.5: 42.3, 0.9: 323.3}, "200", "get", ) // Just for demonstration, let's check the state of the summary by // (ab)using its Write method (which is usually only used by Prometheus // internally). metric := &dto.Metric{} s.Write(metric) fmt.Println(proto.MarshalTextString(metric)) // Output: // label: < // name: "code" // value: "200" // > // label: < // name: "method" // value: "get" // > // label: < // name: "owner" // value: "example" // > // summary: < // sample_count: 4711 // sample_sum: 403.34 // quantile: < // quantile: 0.5 // value: 42.3 // > // quantile: < // quantile: 0.9 // value: 323.3 // > // > } func ExampleHistogram() { temps := prometheus.NewHistogram(prometheus.HistogramOpts{ Name: "pond_temperature_celsius", Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells. Buckets: prometheus.LinearBuckets(20, 5, 5), // 5 buckets, each 5 centigrade wide. }) // Simulate some observations. for i := 0; i < 1000; i++ { temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10) } // Just for demonstration, let's check the state of the histogram by // (ab)using its Write method (which is usually only used by Prometheus // internally). metric := &dto.Metric{} temps.Write(metric) fmt.Println(proto.MarshalTextString(metric)) // Output: // histogram: < // sample_count: 1000 // sample_sum: 29969.50000000001 // bucket: < // cumulative_count: 192 // upper_bound: 20 // > // bucket: < // cumulative_count: 366 // upper_bound: 25 // > // bucket: < // cumulative_count: 501 // upper_bound: 30 // > // bucket: < // cumulative_count: 638 // upper_bound: 35 // > // bucket: < // cumulative_count: 816 // upper_bound: 40 // > // > } func ExampleConstHistogram() { desc := prometheus.NewDesc( "http_request_duration_seconds", "A histogram of the HTTP request durations.", []string{"code", "method"}, prometheus.Labels{"owner": "example"}, ) // Create a constant histogram from values we got from a 3rd party telemetry system. h := prometheus.MustNewConstHistogram( desc, 4711, 403.34, map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233}, "200", "get", ) // Just for demonstration, let's check the state of the histogram by // (ab)using its Write method (which is usually only used by Prometheus // internally). metric := &dto.Metric{} h.Write(metric) fmt.Println(proto.MarshalTextString(metric)) // Output: // label: < // name: "code" // value: "200" // > // label: < // name: "method" // value: "get" // > // label: < // name: "owner" // value: "example" // > // histogram: < // sample_count: 4711 // sample_sum: 403.34 // bucket: < // cumulative_count: 121 // upper_bound: 25 // > // bucket: < // cumulative_count: 2403 // upper_bound: 50 // > // bucket: < // cumulative_count: 3221 // upper_bound: 100 // > // bucket: < // cumulative_count: 4233 // upper_bound: 200 // > // > } func ExamplePushCollectors() { hostname, _ := os.Hostname() completionTime := prometheus.NewGauge(prometheus.GaugeOpts{ Name: "db_backup_last_completion_time", Help: "The timestamp of the last succesful completion of a DB backup.", }) completionTime.Set(float64(time.Now().Unix())) if err := prometheus.PushCollectors( "db_backup", hostname, "http://pushgateway:9091", completionTime, ); err != nil { fmt.Println("Could not push completion time to Pushgateway:", err) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/expvar.go ================================================ // 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) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/expvar_test.go ================================================ // 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_test import ( "expvar" "fmt" "sort" "strings" dto "github.com/prometheus/client_model/go" "github.com/prometheus/client_golang/prometheus" ) func ExampleExpvarCollector() { expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{ "memstats": prometheus.NewDesc( "expvar_memstats", "All numeric memstats as one metric family. Not a good role-model, actually... ;-)", []string{"type"}, nil, ), "lone-int": prometheus.NewDesc( "expvar_lone_int", "Just an expvar int as an example.", nil, nil, ), "http-request-map": prometheus.NewDesc( "expvar_http_request_total", "How many http requests processed, partitioned by status code and http method.", []string{"code", "method"}, nil, ), }) prometheus.MustRegister(expvarCollector) // The Prometheus part is done here. But to show that this example is // doing anything, we have to manually export something via expvar. In // real-life use-cases, some library would already have exported via // expvar what we want to re-export as Prometheus metrics. expvar.NewInt("lone-int").Set(42) expvarMap := expvar.NewMap("http-request-map") var ( expvarMap1, expvarMap2 expvar.Map expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int ) expvarMap1.Init() expvarMap2.Init() expvarInt11.Set(3) expvarInt12.Set(13) expvarInt21.Set(11) expvarInt22.Set(212) expvarMap1.Set("POST", &expvarInt11) expvarMap1.Set("GET", &expvarInt12) expvarMap2.Set("POST", &expvarInt21) expvarMap2.Set("GET", &expvarInt22) expvarMap.Set("404", &expvarMap1) expvarMap.Set("200", &expvarMap2) // Results in the following expvar map: // "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}} // Let's see what the scrape would yield, but exclude the memstats metrics. metricStrings := []string{} metric := dto.Metric{} metricChan := make(chan prometheus.Metric) go func() { expvarCollector.Collect(metricChan) close(metricChan) }() for m := range metricChan { if strings.Index(m.Desc().String(), "expvar_memstats") == -1 { metric.Reset() m.Write(&metric) metricStrings = append(metricStrings, metric.String()) } } sort.Strings(metricStrings) for _, s := range metricStrings { fmt.Println(strings.TrimRight(s, " ")) } // Output: // label: label: untyped: // label: label: untyped: // label: label: untyped: // label: label: untyped: // untyped: } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/gauge.go ================================================ // 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 "hash/fnv" // 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, hash: fnv.New64a(), 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) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/gauge_test.go ================================================ // 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 ( "math" "math/rand" "sync" "testing" "testing/quick" dto "github.com/prometheus/client_model/go" ) func listenGaugeStream(vals, result chan float64, done chan struct{}) { var sum float64 outer: for { select { case <-done: close(vals) for v := range vals { sum += v } break outer case v := <-vals: sum += v } } result <- sum close(result) } func TestGaugeConcurrency(t *testing.T) { it := func(n uint32) bool { mutations := int(n % 10000) concLevel := int(n%15 + 1) var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) sStream := make(chan float64, mutations*concLevel) result := make(chan float64) done := make(chan struct{}) go listenGaugeStream(sStream, result, done) go func() { end.Wait() close(done) }() gge := NewGauge(GaugeOpts{ Name: "test_gauge", Help: "no help can be found here", }) for i := 0; i < concLevel; i++ { vals := make([]float64, mutations) for j := 0; j < mutations; j++ { vals[j] = rand.Float64() - 0.5 } go func(vals []float64) { start.Wait() for _, v := range vals { sStream <- v gge.Add(v) } end.Done() }(vals) } start.Done() if expected, got := <-result, math.Float64frombits(gge.(*value).valBits); math.Abs(expected-got) > 0.000001 { t.Fatalf("expected approx. %f, got %f", expected, got) return false } return true } if err := quick.Check(it, nil); err != nil { t.Fatal(err) } } func TestGaugeVecConcurrency(t *testing.T) { it := func(n uint32) bool { mutations := int(n % 10000) concLevel := int(n%15 + 1) vecLength := int(n%5 + 1) var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) sStreams := make([]chan float64, vecLength) results := make([]chan float64, vecLength) done := make(chan struct{}) for i := 0; i < vecLength; i++ { sStreams[i] = make(chan float64, mutations*concLevel) results[i] = make(chan float64) go listenGaugeStream(sStreams[i], results[i], done) } go func() { end.Wait() close(done) }() gge := NewGaugeVec( GaugeOpts{ Name: "test_gauge", Help: "no help can be found here", }, []string{"label"}, ) for i := 0; i < concLevel; i++ { vals := make([]float64, mutations) pick := make([]int, mutations) for j := 0; j < mutations; j++ { vals[j] = rand.Float64() - 0.5 pick[j] = rand.Intn(vecLength) } go func(vals []float64) { start.Wait() for i, v := range vals { sStreams[pick[i]] <- v gge.WithLabelValues(string('A' + pick[i])).Add(v) } end.Done() }(vals) } start.Done() for i := range sStreams { if expected, got := <-results[i], math.Float64frombits(gge.WithLabelValues(string('A'+i)).(*value).valBits); math.Abs(expected-got) > 0.000001 { t.Fatalf("expected approx. %f, got %f", expected, got) return false } } return true } if err := quick.Check(it, nil); err != nil { t.Fatal(err) } } func TestGaugeFunc(t *testing.T) { gf := NewGaugeFunc( GaugeOpts{ Name: "test_name", Help: "test help", ConstLabels: Labels{"a": "1", "b": "2"}, }, func() float64 { return 3.1415 }, ) if expected, got := `Desc{fqName: "test_name", help: "test help", constLabels: {a="1",b="2"}, variableLabels: []}`, gf.Desc().String(); expected != got { t.Errorf("expected %q, got %q", expected, got) } m := &dto.Metric{} gf.Write(m) if expected, got := `label: label: gauge: `, m.String(); expected != got { t.Errorf("expected %q, got %q", expected, got) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/go_collector.go ================================================ package prometheus import ( "runtime" "runtime/debug" "time" ) type goCollector struct { goroutines Gauge gcDesc *Desc } // NewGoCollector returns a collector which exports metrics about the current // go process. func NewGoCollector() *goCollector { return &goCollector{ goroutines: NewGauge(GaugeOpts{ Name: "go_goroutines", Help: "Number of goroutines that currently exist.", }), gcDesc: NewDesc( "go_gc_duration_seconds", "A summary of the GC invocation durations.", nil, nil), } } // Describe returns all descriptions of the collector. func (c *goCollector) Describe(ch chan<- *Desc) { ch <- c.goroutines.Desc() ch <- c.gcDesc } // 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) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go ================================================ package prometheus import ( "runtime" "testing" "time" dto "github.com/prometheus/client_model/go" ) func TestGoCollector(t *testing.T) { var ( c = NewGoCollector() ch = make(chan Metric) waitc = make(chan struct{}) closec = make(chan struct{}) old = -1 ) defer close(closec) go func() { c.Collect(ch) go func(c <-chan struct{}) { <-c }(closec) <-waitc c.Collect(ch) }() for { select { case metric := <-ch: switch m := metric.(type) { // Attention, this also catches Counter... case Gauge: pb := &dto.Metric{} m.Write(pb) if pb.GetGauge() == nil { continue } if old == -1 { old = int(pb.GetGauge().GetValue()) close(waitc) continue } if diff := int(pb.GetGauge().GetValue()) - old; diff != 1 { // TODO: This is flaky in highly concurrent situations. t.Errorf("want 1 new goroutine, got %d", diff) } // GoCollector performs two sends per call. // On line 27 we need to receive the second send // to shut down cleanly. <-ch return } case <-time.After(1 * time.Second): t.Fatalf("expected collect timed out") } } } func TestGCCollector(t *testing.T) { var ( c = NewGoCollector() ch = make(chan Metric) waitc = make(chan struct{}) closec = make(chan struct{}) oldGC uint64 oldPause float64 ) defer close(closec) go func() { c.Collect(ch) // force GC runtime.GC() <-waitc c.Collect(ch) }() first := true for { select { case metric := <-ch: switch m := metric.(type) { case *constSummary, *value: pb := &dto.Metric{} m.Write(pb) if pb.GetSummary() == nil { continue } if len(pb.GetSummary().Quantile) != 5 { t.Errorf("expected 4 buckets, got %d", len(pb.GetSummary().Quantile)) } for idx, want := range []float64{0.0, 0.25, 0.5, 0.75, 1.0} { if *pb.GetSummary().Quantile[idx].Quantile != want { t.Errorf("bucket #%d is off, got %f, want %f", idx, *pb.GetSummary().Quantile[idx].Quantile, want) } } if first { first = false oldGC = *pb.GetSummary().SampleCount oldPause = *pb.GetSummary().SampleSum close(waitc) continue } if diff := *pb.GetSummary().SampleCount - oldGC; diff != 1 { t.Errorf("want 1 new garbage collection run, got %d", diff) } if diff := *pb.GetSummary().SampleSum - oldPause; diff <= 0 { t.Errorf("want moar pause, got %f", diff) } return } case <-time.After(1 * time.Second): t.Fatalf("expected collect timed out") } } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/histogram.go ================================================ // 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" "hash/fnv" "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, hash: fnv.New64a(), 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() } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go ================================================ // 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 ( "math" "math/rand" "reflect" "sort" "sync" "testing" "testing/quick" dto "github.com/prometheus/client_model/go" ) func benchmarkHistogramObserve(w int, b *testing.B) { b.StopTimer() wg := new(sync.WaitGroup) wg.Add(w) g := new(sync.WaitGroup) g.Add(1) s := NewHistogram(HistogramOpts{}) for i := 0; i < w; i++ { go func() { g.Wait() for i := 0; i < b.N; i++ { s.Observe(float64(i)) } wg.Done() }() } b.StartTimer() g.Done() wg.Wait() } func BenchmarkHistogramObserve1(b *testing.B) { benchmarkHistogramObserve(1, b) } func BenchmarkHistogramObserve2(b *testing.B) { benchmarkHistogramObserve(2, b) } func BenchmarkHistogramObserve4(b *testing.B) { benchmarkHistogramObserve(4, b) } func BenchmarkHistogramObserve8(b *testing.B) { benchmarkHistogramObserve(8, b) } func benchmarkHistogramWrite(w int, b *testing.B) { b.StopTimer() wg := new(sync.WaitGroup) wg.Add(w) g := new(sync.WaitGroup) g.Add(1) s := NewHistogram(HistogramOpts{}) for i := 0; i < 1000000; i++ { s.Observe(float64(i)) } for j := 0; j < w; j++ { outs := make([]dto.Metric, b.N) go func(o []dto.Metric) { g.Wait() for i := 0; i < b.N; i++ { s.Write(&o[i]) } wg.Done() }(outs) } b.StartTimer() g.Done() wg.Wait() } func BenchmarkHistogramWrite1(b *testing.B) { benchmarkHistogramWrite(1, b) } func BenchmarkHistogramWrite2(b *testing.B) { benchmarkHistogramWrite(2, b) } func BenchmarkHistogramWrite4(b *testing.B) { benchmarkHistogramWrite(4, b) } func BenchmarkHistogramWrite8(b *testing.B) { benchmarkHistogramWrite(8, b) } // Intentionally adding +Inf here to test if that case is handled correctly. // Also, getCumulativeCounts depends on it. var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)} func TestHistogramConcurrency(t *testing.T) { if testing.Short() { t.Skip("Skipping test in short mode.") } rand.Seed(42) it := func(n uint32) bool { mutations := int(n%1e4 + 1e4) concLevel := int(n%5 + 1) total := mutations * concLevel var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) sum := NewHistogram(HistogramOpts{ Name: "test_histogram", Help: "helpless", Buckets: testBuckets, }) allVars := make([]float64, total) var sampleSum float64 for i := 0; i < concLevel; i++ { vals := make([]float64, mutations) for j := 0; j < mutations; j++ { v := rand.NormFloat64() vals[j] = v allVars[i*mutations+j] = v sampleSum += v } go func(vals []float64) { start.Wait() for _, v := range vals { sum.Observe(v) } end.Done() }(vals) } sort.Float64s(allVars) start.Done() end.Wait() m := &dto.Metric{} sum.Write(m) if got, want := int(*m.Histogram.SampleCount), total; got != want { t.Errorf("got sample count %d, want %d", got, want) } if got, want := *m.Histogram.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { t.Errorf("got sample sum %f, want %f", got, want) } wantCounts := getCumulativeCounts(allVars) if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { t.Errorf("got %d buckets in protobuf, want %d", got, want) } for i, wantBound := range testBuckets { if i == len(testBuckets)-1 { break // No +Inf bucket in protobuf. } if gotBound := *m.Histogram.Bucket[i].UpperBound; gotBound != wantBound { t.Errorf("got bound %f, want %f", gotBound, wantBound) } if gotCount, wantCount := *m.Histogram.Bucket[i].CumulativeCount, wantCounts[i]; gotCount != wantCount { t.Errorf("got count %d, want %d", gotCount, wantCount) } } return true } if err := quick.Check(it, nil); err != nil { t.Error(err) } } func TestHistogramVecConcurrency(t *testing.T) { if testing.Short() { t.Skip("Skipping test in short mode.") } rand.Seed(42) objectives := make([]float64, 0, len(DefObjectives)) for qu := range DefObjectives { objectives = append(objectives, qu) } sort.Float64s(objectives) it := func(n uint32) bool { mutations := int(n%1e4 + 1e4) concLevel := int(n%7 + 1) vecLength := int(n%3 + 1) var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) his := NewHistogramVec( HistogramOpts{ Name: "test_histogram", Help: "helpless", Buckets: []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}, }, []string{"label"}, ) allVars := make([][]float64, vecLength) sampleSums := make([]float64, vecLength) for i := 0; i < concLevel; i++ { vals := make([]float64, mutations) picks := make([]int, mutations) for j := 0; j < mutations; j++ { v := rand.NormFloat64() vals[j] = v pick := rand.Intn(vecLength) picks[j] = pick allVars[pick] = append(allVars[pick], v) sampleSums[pick] += v } go func(vals []float64) { start.Wait() for i, v := range vals { his.WithLabelValues(string('A' + picks[i])).Observe(v) } end.Done() }(vals) } for _, vars := range allVars { sort.Float64s(vars) } start.Done() end.Wait() for i := 0; i < vecLength; i++ { m := &dto.Metric{} s := his.WithLabelValues(string('A' + i)) s.Write(m) if got, want := len(m.Histogram.Bucket), len(testBuckets)-1; got != want { t.Errorf("got %d buckets in protobuf, want %d", got, want) } if got, want := int(*m.Histogram.SampleCount), len(allVars[i]); got != want { t.Errorf("got sample count %d, want %d", got, want) } if got, want := *m.Histogram.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { t.Errorf("got sample sum %f, want %f", got, want) } wantCounts := getCumulativeCounts(allVars[i]) for j, wantBound := range testBuckets { if j == len(testBuckets)-1 { break // No +Inf bucket in protobuf. } if gotBound := *m.Histogram.Bucket[j].UpperBound; gotBound != wantBound { t.Errorf("got bound %f, want %f", gotBound, wantBound) } if gotCount, wantCount := *m.Histogram.Bucket[j].CumulativeCount, wantCounts[j]; gotCount != wantCount { t.Errorf("got count %d, want %d", gotCount, wantCount) } } } return true } if err := quick.Check(it, nil); err != nil { t.Error(err) } } func getCumulativeCounts(vars []float64) []uint64 { counts := make([]uint64, len(testBuckets)) for _, v := range vars { for i := len(testBuckets) - 1; i >= 0; i-- { if v > testBuckets[i] { break } counts[i]++ } } return counts } func TestBuckets(t *testing.T) { got := LinearBuckets(-15, 5, 6) want := []float64{-15, -10, -5, 0, 5, 10} if !reflect.DeepEqual(got, want) { t.Errorf("linear buckets: got %v, want %v", got, want) } got = ExponentialBuckets(100, 1.2, 3) want = []float64{100, 120, 144} if !reflect.DeepEqual(got, want) { t.Errorf("linear buckets: got %v, want %v", got, want) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/http.go ================================================ // 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"). 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. 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 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 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) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/http_test.go ================================================ // 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 ( "net/http" "net/http/httptest" "testing" "time" dto "github.com/prometheus/client_model/go" ) type respBody string func (b respBody) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) w.Write([]byte(b)) } func TestInstrumentHandler(t *testing.T) { defer func(n nower) { now = n.(nower) }(now) instant := time.Now() end := instant.Add(30 * time.Second) now = nowSeries(instant, end) respBody := respBody("Howdy there!") hndlr := InstrumentHandler("test-handler", respBody) opts := SummaryOpts{ Subsystem: "http", ConstLabels: Labels{"handler": "test-handler"}, } reqCnt := MustRegisterOrGet(NewCounterVec( CounterOpts{ Namespace: opts.Namespace, Subsystem: opts.Subsystem, Name: "requests_total", Help: "Total number of HTTP requests made.", ConstLabels: opts.ConstLabels, }, instLabels, )).(*CounterVec) opts.Name = "request_duration_microseconds" opts.Help = "The HTTP request latencies in microseconds." reqDur := MustRegisterOrGet(NewSummary(opts)).(Summary) opts.Name = "request_size_bytes" opts.Help = "The HTTP request sizes in bytes." MustRegisterOrGet(NewSummary(opts)) opts.Name = "response_size_bytes" opts.Help = "The HTTP response sizes in bytes." MustRegisterOrGet(NewSummary(opts)) reqCnt.Reset() resp := httptest.NewRecorder() req := &http.Request{ Method: "GET", } hndlr.ServeHTTP(resp, req) if resp.Code != http.StatusTeapot { t.Fatalf("expected status %d, got %d", http.StatusTeapot, resp.Code) } if string(resp.Body.Bytes()) != "Howdy there!" { t.Fatalf("expected body %s, got %s", "Howdy there!", string(resp.Body.Bytes())) } out := &dto.Metric{} reqDur.Write(out) if want, got := "test-handler", out.Label[0].GetValue(); want != got { t.Errorf("want label value %q in reqDur, got %q", want, got) } if want, got := uint64(1), out.Summary.GetSampleCount(); want != got { t.Errorf("want sample count %d in reqDur, got %d", want, got) } out.Reset() if want, got := 1, len(reqCnt.children); want != got { t.Errorf("want %d children in reqCnt, got %d", want, got) } cnt, err := reqCnt.GetMetricWithLabelValues("get", "418") if err != nil { t.Fatal(err) } cnt.Write(out) if want, got := "418", out.Label[0].GetValue(); want != got { t.Errorf("want label value %q in reqCnt, got %q", want, got) } if want, got := "test-handler", out.Label[1].GetValue(); want != got { t.Errorf("want label value %q in reqCnt, got %q", want, got) } if want, got := "get", out.Label[2].GetValue(); want != got { t.Errorf("want label value %q in reqCnt, got %q", want, got) } if out.Counter == nil { t.Fatal("expected non-nil counter in reqCnt") } if want, got := 1., out.Counter.GetValue(); want != got { t.Errorf("want reqCnt of %f, got %f", want, got) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/metric.go ================================================ // 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 } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/metric_test.go ================================================ // 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 "testing" func TestBuildFQName(t *testing.T) { scenarios := []struct{ namespace, subsystem, name, result string }{ {"a", "b", "c", "a_b_c"}, {"", "b", "c", "b_c"}, {"a", "", "c", "a_c"}, {"", "", "c", "c"}, {"a", "b", "", ""}, {"a", "", "", ""}, {"", "b", "", ""}, {" ", "", "", ""}, } for i, s := range scenarios { if want, got := s.result, BuildFQName(s.namespace, s.subsystem, s.name); want != got { t.Errorf("%d. want %s, got %s", i, want, got) } } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/process_collector.go ================================================ // 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 } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go ================================================ package prometheus import ( "io/ioutil" "net/http" "net/http/httptest" "os" "regexp" "testing" "github.com/prometheus/procfs" ) func TestProcessCollector(t *testing.T) { if _, err := procfs.Self(); err != nil { t.Skipf("skipping TestProcessCollector, procfs not available: %s", err) } registry := newRegistry() registry.Register(NewProcessCollector(os.Getpid(), "")) registry.Register(NewProcessCollectorPIDFn( func() (int, error) { return os.Getpid(), nil }, "foobar")) s := httptest.NewServer(InstrumentHandler("prometheus", registry)) defer s.Close() r, err := http.Get(s.URL) if err != nil { t.Fatal(err) } defer r.Body.Close() body, err := ioutil.ReadAll(r.Body) if err != nil { t.Fatal(err) } for _, re := range []*regexp.Regexp{ regexp.MustCompile("process_cpu_seconds_total [0-9]"), regexp.MustCompile("process_max_fds [0-9]{2,}"), regexp.MustCompile("process_open_fds [1-9]"), regexp.MustCompile("process_virtual_memory_bytes [1-9]"), regexp.MustCompile("process_resident_memory_bytes [1-9]"), regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"), regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"), regexp.MustCompile("foobar_process_max_fds [0-9]{2,}"), regexp.MustCompile("foobar_process_open_fds [1-9]"), regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"), regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"), regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"), } { if !re.Match(body) { t.Errorf("want body to match %s\n%s", re, body) } } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/push.go ================================================ // 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 addr. 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) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/registry.go ================================================ // 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" "hash/fnv" "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. 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. func MustRegister(m Collector) { err := Register(m) if 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 Register 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 } 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 := fnv.New64a() var buf bytes.Buffer buf.WriteString(metricFamily.GetName()) buf.WriteByte(separatorByte) h.Write(buf.Bytes()) // 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 { buf.Reset() buf.WriteString(lp.GetValue()) buf.WriteByte(separatorByte) h.Write(buf.Bytes()) } metricHash := h.Sum64() if _, exists := metricHashes[metricHash]; exists { return fmt.Errorf( "collected metric %s %s was collected before with the same name and label values", metricFamily.GetName(), dtoMetric, ) } metricHashes[metricHash] = 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 ®istry{ 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 } } return true } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/registry_test.go ================================================ // 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" "encoding/binary" "net/http" "testing" "github.com/golang/protobuf/proto" dto "github.com/prometheus/client_model/go" ) type fakeResponseWriter struct { header http.Header body bytes.Buffer } func (r *fakeResponseWriter) Header() http.Header { return r.header } func (r *fakeResponseWriter) Write(d []byte) (l int, err error) { return r.body.Write(d) } func (r *fakeResponseWriter) WriteHeader(c int) { } func testHandler(t testing.TB) { metricVec := NewCounterVec( CounterOpts{ Name: "name", Help: "docstring", ConstLabels: Labels{"constname": "constvalue"}, }, []string{"labelname"}, ) metricVec.WithLabelValues("val1").Inc() metricVec.WithLabelValues("val2").Inc() varintBuf := make([]byte, binary.MaxVarintLen32) externalMetricFamily := &dto.MetricFamily{ Name: proto.String("externalname"), Help: proto.String("externaldocstring"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("externalconstname"), Value: proto.String("externalconstvalue"), }, { Name: proto.String("externallabelname"), Value: proto.String("externalval1"), }, }, Counter: &dto.Counter{ Value: proto.Float64(1), }, }, }, } marshaledExternalMetricFamily, err := proto.Marshal(externalMetricFamily) if err != nil { t.Fatal(err) } var externalBuf bytes.Buffer l := binary.PutUvarint(varintBuf, uint64(len(marshaledExternalMetricFamily))) _, err = externalBuf.Write(varintBuf[:l]) if err != nil { t.Fatal(err) } _, err = externalBuf.Write(marshaledExternalMetricFamily) if err != nil { t.Fatal(err) } externalMetricFamilyAsBytes := externalBuf.Bytes() externalMetricFamilyAsText := []byte(`# HELP externalname externaldocstring # TYPE externalname counter externalname{externalconstname="externalconstvalue",externallabelname="externalval1"} 1 `) externalMetricFamilyAsProtoText := []byte(`name: "externalname" help: "externaldocstring" type: COUNTER metric: < label: < name: "externalconstname" value: "externalconstvalue" > label: < name: "externallabelname" value: "externalval1" > counter: < value: 1 > > `) externalMetricFamilyAsProtoCompactText := []byte(`name:"externalname" help:"externaldocstring" type:COUNTER metric: label: counter: > `) expectedMetricFamily := &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("docstring"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("constname"), Value: proto.String("constvalue"), }, { Name: proto.String("labelname"), Value: proto.String("val1"), }, }, Counter: &dto.Counter{ Value: proto.Float64(1), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("constname"), Value: proto.String("constvalue"), }, { Name: proto.String("labelname"), Value: proto.String("val2"), }, }, Counter: &dto.Counter{ Value: proto.Float64(1), }, }, }, } marshaledExpectedMetricFamily, err := proto.Marshal(expectedMetricFamily) if err != nil { t.Fatal(err) } var buf bytes.Buffer l = binary.PutUvarint(varintBuf, uint64(len(marshaledExpectedMetricFamily))) _, err = buf.Write(varintBuf[:l]) if err != nil { t.Fatal(err) } _, err = buf.Write(marshaledExpectedMetricFamily) if err != nil { t.Fatal(err) } expectedMetricFamilyAsBytes := buf.Bytes() expectedMetricFamilyAsText := []byte(`# HELP name docstring # TYPE name counter name{constname="constvalue",labelname="val1"} 1 name{constname="constvalue",labelname="val2"} 1 `) expectedMetricFamilyAsProtoText := []byte(`name: "name" help: "docstring" type: COUNTER metric: < label: < name: "constname" value: "constvalue" > label: < name: "labelname" value: "val1" > counter: < value: 1 > > metric: < label: < name: "constname" value: "constvalue" > label: < name: "labelname" value: "val2" > counter: < value: 1 > > `) expectedMetricFamilyAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > `) externalMetricFamilyWithSameName := &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("inconsistent help string does not matter here"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("constname"), Value: proto.String("constvalue"), }, { Name: proto.String("labelname"), Value: proto.String("different_val"), }, }, Counter: &dto.Counter{ Value: proto.Float64(42), }, }, }, } expectedMetricFamilyMergedWithExternalAsProtoCompactText := []byte(`name:"name" help:"docstring" type:COUNTER metric: label: counter: > metric: label: counter: > metric: label: counter: > `) type output struct { headers map[string]string body []byte } var scenarios = []struct { headers map[string]string out output collector Collector externalMF []*dto.MetricFamily }{ { // 0 headers: map[string]string{ "Accept": "foo/bar;q=0.2, dings/bums;q=0.8", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: []byte{}, }, }, { // 1 headers: map[string]string{ "Accept": "foo/bar;q=0.2, application/quark;q=0.8", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: []byte{}, }, }, { // 2 headers: map[string]string{ "Accept": "foo/bar;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.8", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: []byte{}, }, }, { // 3 headers: map[string]string{ "Accept": "text/plain;q=0.2, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.8", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, }, body: []byte{}, }, }, { // 4 headers: map[string]string{ "Accept": "application/json", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: expectedMetricFamilyAsText, }, collector: metricVec, }, { // 5 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, }, body: expectedMetricFamilyAsBytes, }, collector: metricVec, }, { // 6 headers: map[string]string{ "Accept": "application/json", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: externalMetricFamilyAsText, }, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 7 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, }, body: externalMetricFamilyAsBytes, }, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 8 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, }, body: bytes.Join( [][]byte{ externalMetricFamilyAsBytes, expectedMetricFamilyAsBytes, }, []byte{}, ), }, collector: metricVec, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 9 headers: map[string]string{ "Accept": "text/plain", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: []byte{}, }, }, { // 10 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: expectedMetricFamilyAsText, }, collector: metricVec, }, { // 11 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=bla;q=0.2, text/plain;q=0.5;version=0.0.4", }, out: output{ headers: map[string]string{ "Content-Type": `text/plain; version=0.0.4`, }, body: bytes.Join( [][]byte{ externalMetricFamilyAsText, expectedMetricFamilyAsText, }, []byte{}, ), }, collector: metricVec, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 12 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.2, text/plain;q=0.5;version=0.0.2", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`, }, body: bytes.Join( [][]byte{ externalMetricFamilyAsBytes, expectedMetricFamilyAsBytes, }, []byte{}, ), }, collector: metricVec, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 13 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=text;q=0.5, application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=delimited;q=0.4", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`, }, body: bytes.Join( [][]byte{ externalMetricFamilyAsProtoText, expectedMetricFamilyAsProtoText, }, []byte{}, ), }, collector: metricVec, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 14 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, }, body: bytes.Join( [][]byte{ externalMetricFamilyAsProtoCompactText, expectedMetricFamilyAsProtoCompactText, }, []byte{}, ), }, collector: metricVec, externalMF: []*dto.MetricFamily{externalMetricFamily}, }, { // 15 headers: map[string]string{ "Accept": "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text", }, out: output{ headers: map[string]string{ "Content-Type": `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`, }, body: bytes.Join( [][]byte{ externalMetricFamilyAsProtoCompactText, expectedMetricFamilyMergedWithExternalAsProtoCompactText, }, []byte{}, ), }, collector: metricVec, externalMF: []*dto.MetricFamily{ externalMetricFamily, externalMetricFamilyWithSameName, }, }, } for i, scenario := range scenarios { registry := newRegistry() registry.collectChecksEnabled = true if scenario.collector != nil { registry.Register(scenario.collector) } if scenario.externalMF != nil { registry.metricFamilyInjectionHook = func() []*dto.MetricFamily { return scenario.externalMF } } writer := &fakeResponseWriter{ header: http.Header{}, } handler := InstrumentHandler("prometheus", registry) request, _ := http.NewRequest("GET", "/", nil) for key, value := range scenario.headers { request.Header.Add(key, value) } handler(writer, request) for key, value := range scenario.out.headers { if writer.Header().Get(key) != value { t.Errorf( "%d. expected %q for header %q, got %q", i, value, key, writer.Header().Get(key), ) } } if !bytes.Equal(scenario.out.body, writer.body.Bytes()) { t.Errorf( "%d. expected %q for body, got %q", i, scenario.out.body, writer.body.Bytes(), ) } } } func TestHandler(t *testing.T) { testHandler(t) } func BenchmarkHandler(b *testing.B) { for i := 0; i < b.N; i++ { testHandler(b) } } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/summary.go ================================================ // 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" "hash/fnv" "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, hash: fnv.New64a(), 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 } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/summary_test.go ================================================ // 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 ( "math" "math/rand" "sort" "sync" "testing" "testing/quick" "time" dto "github.com/prometheus/client_model/go" ) func benchmarkSummaryObserve(w int, b *testing.B) { b.StopTimer() wg := new(sync.WaitGroup) wg.Add(w) g := new(sync.WaitGroup) g.Add(1) s := NewSummary(SummaryOpts{}) for i := 0; i < w; i++ { go func() { g.Wait() for i := 0; i < b.N; i++ { s.Observe(float64(i)) } wg.Done() }() } b.StartTimer() g.Done() wg.Wait() } func BenchmarkSummaryObserve1(b *testing.B) { benchmarkSummaryObserve(1, b) } func BenchmarkSummaryObserve2(b *testing.B) { benchmarkSummaryObserve(2, b) } func BenchmarkSummaryObserve4(b *testing.B) { benchmarkSummaryObserve(4, b) } func BenchmarkSummaryObserve8(b *testing.B) { benchmarkSummaryObserve(8, b) } func benchmarkSummaryWrite(w int, b *testing.B) { b.StopTimer() wg := new(sync.WaitGroup) wg.Add(w) g := new(sync.WaitGroup) g.Add(1) s := NewSummary(SummaryOpts{}) for i := 0; i < 1000000; i++ { s.Observe(float64(i)) } for j := 0; j < w; j++ { outs := make([]dto.Metric, b.N) go func(o []dto.Metric) { g.Wait() for i := 0; i < b.N; i++ { s.Write(&o[i]) } wg.Done() }(outs) } b.StartTimer() g.Done() wg.Wait() } func BenchmarkSummaryWrite1(b *testing.B) { benchmarkSummaryWrite(1, b) } func BenchmarkSummaryWrite2(b *testing.B) { benchmarkSummaryWrite(2, b) } func BenchmarkSummaryWrite4(b *testing.B) { benchmarkSummaryWrite(4, b) } func BenchmarkSummaryWrite8(b *testing.B) { benchmarkSummaryWrite(8, b) } func TestSummaryConcurrency(t *testing.T) { if testing.Short() { t.Skip("Skipping test in short mode.") } rand.Seed(42) it := func(n uint32) bool { mutations := int(n%1e4 + 1e4) concLevel := int(n%5 + 1) total := mutations * concLevel var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) sum := NewSummary(SummaryOpts{ Name: "test_summary", Help: "helpless", }) allVars := make([]float64, total) var sampleSum float64 for i := 0; i < concLevel; i++ { vals := make([]float64, mutations) for j := 0; j < mutations; j++ { v := rand.NormFloat64() vals[j] = v allVars[i*mutations+j] = v sampleSum += v } go func(vals []float64) { start.Wait() for _, v := range vals { sum.Observe(v) } end.Done() }(vals) } sort.Float64s(allVars) start.Done() end.Wait() m := &dto.Metric{} sum.Write(m) if got, want := int(*m.Summary.SampleCount), total; got != want { t.Errorf("got sample count %d, want %d", got, want) } if got, want := *m.Summary.SampleSum, sampleSum; math.Abs((got-want)/want) > 0.001 { t.Errorf("got sample sum %f, want %f", got, want) } objectives := make([]float64, 0, len(DefObjectives)) for qu := range DefObjectives { objectives = append(objectives, qu) } sort.Float64s(objectives) for i, wantQ := range objectives { ε := DefObjectives[wantQ] gotQ := *m.Summary.Quantile[i].Quantile gotV := *m.Summary.Quantile[i].Value min, max := getBounds(allVars, wantQ, ε) if gotQ != wantQ { t.Errorf("got quantile %f, want %f", gotQ, wantQ) } if gotV < min || gotV > max { t.Errorf("got %f for quantile %f, want [%f,%f]", gotV, gotQ, min, max) } } return true } if err := quick.Check(it, nil); err != nil { t.Error(err) } } func TestSummaryVecConcurrency(t *testing.T) { if testing.Short() { t.Skip("Skipping test in short mode.") } rand.Seed(42) objectives := make([]float64, 0, len(DefObjectives)) for qu := range DefObjectives { objectives = append(objectives, qu) } sort.Float64s(objectives) it := func(n uint32) bool { mutations := int(n%1e4 + 1e4) concLevel := int(n%7 + 1) vecLength := int(n%3 + 1) var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) sum := NewSummaryVec( SummaryOpts{ Name: "test_summary", Help: "helpless", }, []string{"label"}, ) allVars := make([][]float64, vecLength) sampleSums := make([]float64, vecLength) for i := 0; i < concLevel; i++ { vals := make([]float64, mutations) picks := make([]int, mutations) for j := 0; j < mutations; j++ { v := rand.NormFloat64() vals[j] = v pick := rand.Intn(vecLength) picks[j] = pick allVars[pick] = append(allVars[pick], v) sampleSums[pick] += v } go func(vals []float64) { start.Wait() for i, v := range vals { sum.WithLabelValues(string('A' + picks[i])).Observe(v) } end.Done() }(vals) } for _, vars := range allVars { sort.Float64s(vars) } start.Done() end.Wait() for i := 0; i < vecLength; i++ { m := &dto.Metric{} s := sum.WithLabelValues(string('A' + i)) s.Write(m) if got, want := int(*m.Summary.SampleCount), len(allVars[i]); got != want { t.Errorf("got sample count %d for label %c, want %d", got, 'A'+i, want) } if got, want := *m.Summary.SampleSum, sampleSums[i]; math.Abs((got-want)/want) > 0.001 { t.Errorf("got sample sum %f for label %c, want %f", got, 'A'+i, want) } for j, wantQ := range objectives { ε := DefObjectives[wantQ] gotQ := *m.Summary.Quantile[j].Quantile gotV := *m.Summary.Quantile[j].Value min, max := getBounds(allVars[i], wantQ, ε) if gotQ != wantQ { t.Errorf("got quantile %f for label %c, want %f", gotQ, 'A'+i, wantQ) } if gotV < min || gotV > max { t.Errorf("got %f for quantile %f for label %c, want [%f,%f]", gotV, gotQ, 'A'+i, min, max) } } } return true } if err := quick.Check(it, nil); err != nil { t.Error(err) } } func TestSummaryDecay(t *testing.T) { if testing.Short() { t.Skip("Skipping test in short mode.") // More because it depends on timing than because it is particularly long... } sum := NewSummary(SummaryOpts{ Name: "test_summary", Help: "helpless", MaxAge: 100 * time.Millisecond, Objectives: map[float64]float64{0.1: 0.001}, AgeBuckets: 10, }) m := &dto.Metric{} i := 0 tick := time.NewTicker(time.Millisecond) for _ = range tick.C { i++ sum.Observe(float64(i)) if i%10 == 0 { sum.Write(m) if got, want := *m.Summary.Quantile[0].Value, math.Max(float64(i)/10, float64(i-90)); math.Abs(got-want) > 20 { t.Errorf("%d. got %f, want %f", i, got, want) } m.Reset() } if i >= 1000 { break } } tick.Stop() // Wait for MaxAge without observations and make sure quantiles are NaN. time.Sleep(100 * time.Millisecond) sum.Write(m) if got := *m.Summary.Quantile[0].Value; !math.IsNaN(got) { t.Errorf("got %f, want NaN after expiration", got) } } func getBounds(vars []float64, q, ε float64) (min, max float64) { // TODO: This currently tolerates an error of up to 2*ε. The error must // be at most ε, but for some reason, it's sometimes slightly // higher. That's a bug. n := float64(len(vars)) lower := int((q - 2*ε) * n) upper := int(math.Ceil((q + 2*ε) * n)) min = vars[0] if lower > 1 { min = vars[lower-1] } max = vars[len(vars)-1] if upper < len(vars) { max = vars[upper-1] } return } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/untyped.go ================================================ // 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 "hash/fnv" // 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, hash: fnv.New64a(), 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) } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/value.go ================================================ // 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 } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/vec.go ================================================ // 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 ( "bytes" "fmt" "hash" "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 not only children, but also hash and buf. children map[uint64]Metric desc *Desc // hash is our own hash instance to avoid repeated allocations. hash hash.Hash64 // buf is used to copy string contents into it for hashing, // again to avoid allocations. buf bytes.Buffer 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) { m.mtx.Lock() defer m.mtx.Unlock() h, err := m.hashLabelValues(lvs) if err != nil { return nil, err } 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) { m.mtx.Lock() defer m.mtx.Unlock() h, err := m.hashLabels(labels) if err != nil { return nil, err } lvs := make([]string, len(labels)) for i, label := range m.desc.variableLabels { lvs[i] = labels[label] } 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 _, has := m.children[h]; !has { 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 _, has := m.children[h]; !has { 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 } m.hash.Reset() for _, val := range vals { m.buf.Reset() m.buf.WriteString(val) m.hash.Write(m.buf.Bytes()) } return m.hash.Sum64(), nil } func (m *MetricVec) hashLabels(labels Labels) (uint64, error) { if len(labels) != len(m.desc.variableLabels) { return 0, errInconsistentCardinality } m.hash.Reset() for _, label := range m.desc.variableLabels { val, ok := labels[label] if !ok { return 0, fmt.Errorf("label name %q missing in label map", label) } m.buf.Reset() m.buf.WriteString(val) m.hash.Write(m.buf.Bytes()) } return m.hash.Sum64(), 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 } ================================================ FILE: vendor/github.com/prometheus/client_golang/prometheus/vec_test.go ================================================ // 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 ( "hash/fnv" "testing" ) func TestDelete(t *testing.T) { desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil) vec := MetricVec{ children: map[uint64]Metric{}, desc: desc, hash: fnv.New64a(), newMetric: func(lvs ...string) Metric { return newValue(desc, UntypedValue, 0, lvs...) }, } if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { t.Errorf("got %v, want %v", got, want) } vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), true; got != want { t.Errorf("got %v, want %v", got, want) } if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want { t.Errorf("got %v, want %v", got, want) } vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), true; got != want { t.Errorf("got %v, want %v", got, want) } if got, want := vec.Delete(Labels{"l2": "v2", "l1": "v1"}), false; got != want { t.Errorf("got %v, want %v", got, want) } vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) if got, want := vec.Delete(Labels{"l2": "v1", "l1": "v2"}), false; got != want { t.Errorf("got %v, want %v", got, want) } if got, want := vec.Delete(Labels{"l1": "v1"}), false; got != want { t.Errorf("got %v, want %v", got, want) } } func TestDeleteLabelValues(t *testing.T) { desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil) vec := MetricVec{ children: map[uint64]Metric{}, desc: desc, hash: fnv.New64a(), newMetric: func(lvs ...string) Metric { return newValue(desc, UntypedValue, 0, lvs...) }, } if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { t.Errorf("got %v, want %v", got, want) } vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want { t.Errorf("got %v, want %v", got, want) } if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want { t.Errorf("got %v, want %v", got, want) } vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42) if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want { t.Errorf("got %v, want %v", got, want) } if got, want := vec.DeleteLabelValues("v1"), false; got != want { t.Errorf("got %v, want %v", got, want) } } ================================================ FILE: vendor/github.com/prometheus/client_model/.gitignore ================================================ target/ ================================================ FILE: vendor/github.com/prometheus/client_model/AUTHORS.md ================================================ The Prometheus project was started by Matt T. Proud (emeritus) and Julius Volz in 2012. Maintainers of this repository: * Björn Rabenstein The following individuals have contributed code to this repository (listed in alphabetical order): * Björn Rabenstein * Matt T. Proud * Tobias Schmidt ================================================ FILE: vendor/github.com/prometheus/client_model/CONTRIBUTING.md ================================================ # Contributing Prometheus uses GitHub to manage reviews of pull requests. * If you have a trivial fix or improvement, go ahead and create a pull request, addressing (with `@...`) one or more of the maintainers (see [AUTHORS.md](AUTHORS.md)) in the description of the pull request. * If you plan to do something more involved, first discuss your ideas on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). This will avoid unnecessary work and surely give you and us a good deal of inspiration. * Relevant coding style guidelines for the Go parts are the [Go Code Review Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) and the _Formatting and style_ section of Peter Bourgon's [Go: Best Practices for Production Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). ================================================ FILE: vendor/github.com/prometheus/client_model/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/prometheus/client_model/Makefile ================================================ # Copyright 2013 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. KEY_ID ?= _DEFINE_ME_ all: cpp go java python ruby SUFFIXES: cpp: cpp/metrics.pb.cc cpp/metrics.pb.h cpp/metrics.pb.cc: metrics.proto protoc $< --cpp_out=cpp/ cpp/metrics.pb.h: metrics.proto protoc $< --cpp_out=cpp/ go: go/metrics.pb.go go/metrics.pb.go: metrics.proto protoc $< --go_out=go/ java: src/main/java/io/prometheus/client/Metrics.java pom.xml mvn clean compile package src/main/java/io/prometheus/client/Metrics.java: metrics.proto protoc $< --java_out=src/main/java python: python/prometheus/client/model/metrics_pb2.py python/prometheus/client/model/metrics_pb2.py: metrics.proto protoc $< --python_out=python/prometheus/client/model ruby: $(MAKE) -C ruby build clean: -rm -rf cpp/* -rm -rf go/* -rm -rf java/* -rm -rf python/* -$(MAKE) -C ruby clean -mvn clean maven-deploy-snapshot: java mvn clean deploy -Dgpg.keyname=$(KEY_ID) -DperformRelease=true maven-deploy-release: java mvn clean release:clean release:prepare release:perform -Dgpg.keyname=$(KEY_ID) -DperformRelease=true .PHONY: all clean cpp go java maven-deploy-snapshot maven-deploy-release python ruby ================================================ FILE: vendor/github.com/prometheus/client_model/NOTICE ================================================ Data model artifacts for Prometheus. Copyright 2012-2015 The Prometheus Authors This product includes software developed at SoundCloud Ltd. (http://soundcloud.com/). ================================================ FILE: vendor/github.com/prometheus/client_model/README.md ================================================ # 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). ================================================ FILE: vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: metrics.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "metrics.pb.h" #include #include #include #include #include #include #include #include #include // @@protoc_insertion_point(includes) namespace io { namespace prometheus { namespace client { namespace { const ::google::protobuf::Descriptor* LabelPair_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* LabelPair_reflection_ = NULL; const ::google::protobuf::Descriptor* Gauge_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Gauge_reflection_ = NULL; const ::google::protobuf::Descriptor* Counter_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Counter_reflection_ = NULL; const ::google::protobuf::Descriptor* Quantile_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Quantile_reflection_ = NULL; const ::google::protobuf::Descriptor* Summary_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Summary_reflection_ = NULL; const ::google::protobuf::Descriptor* Untyped_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Untyped_reflection_ = NULL; const ::google::protobuf::Descriptor* Histogram_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Histogram_reflection_ = NULL; const ::google::protobuf::Descriptor* Bucket_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Bucket_reflection_ = NULL; const ::google::protobuf::Descriptor* Metric_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* Metric_reflection_ = NULL; const ::google::protobuf::Descriptor* MetricFamily_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* MetricFamily_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* MetricType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_metrics_2eproto() { protobuf_AddDesc_metrics_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "metrics.proto"); GOOGLE_CHECK(file != NULL); LabelPair_descriptor_ = file->message_type(0); static const int LabelPair_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, value_), }; LabelPair_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( LabelPair_descriptor_, LabelPair::default_instance_, LabelPair_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(LabelPair)); Gauge_descriptor_ = file->message_type(1); static const int Gauge_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, value_), }; Gauge_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Gauge_descriptor_, Gauge::default_instance_, Gauge_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Gauge)); Counter_descriptor_ = file->message_type(2); static const int Counter_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, value_), }; Counter_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Counter_descriptor_, Counter::default_instance_, Counter_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Counter)); Quantile_descriptor_ = file->message_type(3); static const int Quantile_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, quantile_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, value_), }; Quantile_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Quantile_descriptor_, Quantile::default_instance_, Quantile_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Quantile)); Summary_descriptor_ = file->message_type(4); static const int Summary_offsets_[3] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, sample_count_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, sample_sum_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, quantile_), }; Summary_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Summary_descriptor_, Summary::default_instance_, Summary_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Summary)); Untyped_descriptor_ = file->message_type(5); static const int Untyped_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, value_), }; Untyped_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Untyped_descriptor_, Untyped::default_instance_, Untyped_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Untyped)); Histogram_descriptor_ = file->message_type(6); static const int Histogram_offsets_[3] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, sample_count_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, sample_sum_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, bucket_), }; Histogram_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Histogram_descriptor_, Histogram::default_instance_, Histogram_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Histogram)); Bucket_descriptor_ = file->message_type(7); static const int Bucket_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, cumulative_count_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, upper_bound_), }; Bucket_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Bucket_descriptor_, Bucket::default_instance_, Bucket_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Bucket)); Metric_descriptor_ = file->message_type(8); static const int Metric_offsets_[7] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, label_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, gauge_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, counter_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, summary_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, untyped_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, histogram_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, timestamp_ms_), }; Metric_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( Metric_descriptor_, Metric::default_instance_, Metric_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(Metric)); MetricFamily_descriptor_ = file->message_type(9); static const int MetricFamily_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, name_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, help_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, type_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, metric_), }; MetricFamily_reflection_ = new ::google::protobuf::internal::GeneratedMessageReflection( MetricFamily_descriptor_, MetricFamily::default_instance_, MetricFamily_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, _has_bits_[0]), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, _unknown_fields_), -1, ::google::protobuf::DescriptorPool::generated_pool(), ::google::protobuf::MessageFactory::generated_factory(), sizeof(MetricFamily)); MetricType_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_metrics_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( LabelPair_descriptor_, &LabelPair::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Gauge_descriptor_, &Gauge::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Counter_descriptor_, &Counter::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Quantile_descriptor_, &Quantile::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Summary_descriptor_, &Summary::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Untyped_descriptor_, &Untyped::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Histogram_descriptor_, &Histogram::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Bucket_descriptor_, &Bucket::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( Metric_descriptor_, &Metric::default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( MetricFamily_descriptor_, &MetricFamily::default_instance()); } } // namespace void protobuf_ShutdownFile_metrics_2eproto() { delete LabelPair::default_instance_; delete LabelPair_reflection_; delete Gauge::default_instance_; delete Gauge_reflection_; delete Counter::default_instance_; delete Counter_reflection_; delete Quantile::default_instance_; delete Quantile_reflection_; delete Summary::default_instance_; delete Summary_reflection_; delete Untyped::default_instance_; delete Untyped_reflection_; delete Histogram::default_instance_; delete Histogram_reflection_; delete Bucket::default_instance_; delete Bucket_reflection_; delete Metric::default_instance_; delete Metric_reflection_; delete MetricFamily::default_instance_; delete MetricFamily_reflection_; } void protobuf_AddDesc_metrics_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\rmetrics.proto\022\024io.prometheus.client\"(\n" "\tLabelPair\022\014\n\004name\030\001 \001(\t\022\r\n\005value\030\002 \001(\t\"" "\026\n\005Gauge\022\r\n\005value\030\001 \001(\001\"\030\n\007Counter\022\r\n\005va" "lue\030\001 \001(\001\"+\n\010Quantile\022\020\n\010quantile\030\001 \001(\001\022" "\r\n\005value\030\002 \001(\001\"e\n\007Summary\022\024\n\014sample_coun" "t\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\0220\n\010quantile\030" "\003 \003(\0132\036.io.prometheus.client.Quantile\"\030\n" "\007Untyped\022\r\n\005value\030\001 \001(\001\"c\n\tHistogram\022\024\n\014" "sample_count\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\022," "\n\006bucket\030\003 \003(\0132\034.io.prometheus.client.Bu" "cket\"7\n\006Bucket\022\030\n\020cumulative_count\030\001 \001(\004" "\022\023\n\013upper_bound\030\002 \001(\001\"\276\002\n\006Metric\022.\n\005labe" "l\030\001 \003(\0132\037.io.prometheus.client.LabelPair" "\022*\n\005gauge\030\002 \001(\0132\033.io.prometheus.client.G" "auge\022.\n\007counter\030\003 \001(\0132\035.io.prometheus.cl" "ient.Counter\022.\n\007summary\030\004 \001(\0132\035.io.prome" "theus.client.Summary\022.\n\007untyped\030\005 \001(\0132\035." "io.prometheus.client.Untyped\0222\n\thistogra" "m\030\007 \001(\0132\037.io.prometheus.client.Histogram" "\022\024\n\014timestamp_ms\030\006 \001(\003\"\210\001\n\014MetricFamily\022" "\014\n\004name\030\001 \001(\t\022\014\n\004help\030\002 \001(\t\022.\n\004type\030\003 \001(" "\0162 .io.prometheus.client.MetricType\022,\n\006m" "etric\030\004 \003(\0132\034.io.prometheus.client.Metri" "c*M\n\nMetricType\022\013\n\007COUNTER\020\000\022\t\n\005GAUGE\020\001\022" "\013\n\007SUMMARY\020\002\022\013\n\007UNTYPED\020\003\022\r\n\tHISTOGRAM\020\004" "B\026\n\024io.prometheus.client", 1024); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "metrics.proto", &protobuf_RegisterTypes); LabelPair::default_instance_ = new LabelPair(); Gauge::default_instance_ = new Gauge(); Counter::default_instance_ = new Counter(); Quantile::default_instance_ = new Quantile(); Summary::default_instance_ = new Summary(); Untyped::default_instance_ = new Untyped(); Histogram::default_instance_ = new Histogram(); Bucket::default_instance_ = new Bucket(); Metric::default_instance_ = new Metric(); MetricFamily::default_instance_ = new MetricFamily(); LabelPair::default_instance_->InitAsDefaultInstance(); Gauge::default_instance_->InitAsDefaultInstance(); Counter::default_instance_->InitAsDefaultInstance(); Quantile::default_instance_->InitAsDefaultInstance(); Summary::default_instance_->InitAsDefaultInstance(); Untyped::default_instance_->InitAsDefaultInstance(); Histogram::default_instance_->InitAsDefaultInstance(); Bucket::default_instance_->InitAsDefaultInstance(); Metric::default_instance_->InitAsDefaultInstance(); MetricFamily::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_metrics_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_metrics_2eproto { StaticDescriptorInitializer_metrics_2eproto() { protobuf_AddDesc_metrics_2eproto(); } } static_descriptor_initializer_metrics_2eproto_; const ::google::protobuf::EnumDescriptor* MetricType_descriptor() { protobuf_AssignDescriptorsOnce(); return MetricType_descriptor_; } bool MetricType_IsValid(int value) { switch(value) { case 0: case 1: case 2: case 3: case 4: return true; default: return false; } } // =================================================================== #ifndef _MSC_VER const int LabelPair::kNameFieldNumber; const int LabelPair::kValueFieldNumber; #endif // !_MSC_VER LabelPair::LabelPair() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.LabelPair) } void LabelPair::InitAsDefaultInstance() { } LabelPair::LabelPair(const LabelPair& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.LabelPair) } void LabelPair::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } LabelPair::~LabelPair() { // @@protoc_insertion_point(destructor:io.prometheus.client.LabelPair) SharedDtor(); } void LabelPair::SharedDtor() { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete name_; } if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete value_; } if (this != default_instance_) { } } void LabelPair::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* LabelPair::descriptor() { protobuf_AssignDescriptorsOnce(); return LabelPair_descriptor_; } const LabelPair& LabelPair::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } LabelPair* LabelPair::default_instance_ = NULL; LabelPair* LabelPair::New() const { return new LabelPair; } void LabelPair::Clear() { if (_has_bits_[0 / 32] & 3) { if (has_name()) { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_->clear(); } } if (has_value()) { if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { value_->clear(); } } } ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool LabelPair::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.LabelPair) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormat::PARSE, "name"); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_value; break; } // optional string value = 2; case 2: { if (tag == 18) { parse_value: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_value())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->value().data(), this->value().length(), ::google::protobuf::internal::WireFormat::PARSE, "value"); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.LabelPair) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.LabelPair) return false; #undef DO_ } void LabelPair::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.LabelPair) // optional string name = 1; if (has_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string value = 2; if (has_value()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->value().data(), this->value().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "value"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->value(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.LabelPair) } ::google::protobuf::uint8* LabelPair::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.LabelPair) // optional string name = 1; if (has_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string value = 2; if (has_value()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->value().data(), this->value().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "value"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->value(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.LabelPair) return target; } int LabelPair::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional string name = 1; if (has_name()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // optional string value = 2; if (has_value()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->value()); } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void LabelPair::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const LabelPair* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void LabelPair::MergeFrom(const LabelPair& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_name()) { set_name(from.name()); } if (from.has_value()) { set_value(from.value()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void LabelPair::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void LabelPair::CopyFrom(const LabelPair& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool LabelPair::IsInitialized() const { return true; } void LabelPair::Swap(LabelPair* other) { if (other != this) { std::swap(name_, other->name_); std::swap(value_, other->value_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata LabelPair::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = LabelPair_descriptor_; metadata.reflection = LabelPair_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Gauge::kValueFieldNumber; #endif // !_MSC_VER Gauge::Gauge() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Gauge) } void Gauge::InitAsDefaultInstance() { } Gauge::Gauge(const Gauge& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Gauge) } void Gauge::SharedCtor() { _cached_size_ = 0; value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Gauge::~Gauge() { // @@protoc_insertion_point(destructor:io.prometheus.client.Gauge) SharedDtor(); } void Gauge::SharedDtor() { if (this != default_instance_) { } } void Gauge::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Gauge::descriptor() { protobuf_AssignDescriptorsOnce(); return Gauge_descriptor_; } const Gauge& Gauge::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Gauge* Gauge::default_instance_ = NULL; Gauge* Gauge::New() const { return new Gauge; } void Gauge::Clear() { value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Gauge::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Gauge) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double value = 1; case 1: { if (tag == 9) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); set_has_value(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Gauge) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Gauge) return false; #undef DO_ } void Gauge::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Gauge) // optional double value = 1; if (has_value()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Gauge) } ::google::protobuf::uint8* Gauge::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Gauge) // optional double value = 1; if (has_value()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Gauge) return target; } int Gauge::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional double value = 1; if (has_value()) { total_size += 1 + 8; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Gauge::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Gauge* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Gauge::MergeFrom(const Gauge& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_value()) { set_value(from.value()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Gauge::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Gauge::CopyFrom(const Gauge& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Gauge::IsInitialized() const { return true; } void Gauge::Swap(Gauge* other) { if (other != this) { std::swap(value_, other->value_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Gauge::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Gauge_descriptor_; metadata.reflection = Gauge_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Counter::kValueFieldNumber; #endif // !_MSC_VER Counter::Counter() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Counter) } void Counter::InitAsDefaultInstance() { } Counter::Counter(const Counter& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Counter) } void Counter::SharedCtor() { _cached_size_ = 0; value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Counter::~Counter() { // @@protoc_insertion_point(destructor:io.prometheus.client.Counter) SharedDtor(); } void Counter::SharedDtor() { if (this != default_instance_) { } } void Counter::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Counter::descriptor() { protobuf_AssignDescriptorsOnce(); return Counter_descriptor_; } const Counter& Counter::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Counter* Counter::default_instance_ = NULL; Counter* Counter::New() const { return new Counter; } void Counter::Clear() { value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Counter::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Counter) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double value = 1; case 1: { if (tag == 9) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); set_has_value(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Counter) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Counter) return false; #undef DO_ } void Counter::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Counter) // optional double value = 1; if (has_value()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Counter) } ::google::protobuf::uint8* Counter::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Counter) // optional double value = 1; if (has_value()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Counter) return target; } int Counter::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional double value = 1; if (has_value()) { total_size += 1 + 8; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Counter::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Counter* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Counter::MergeFrom(const Counter& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_value()) { set_value(from.value()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Counter::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Counter::CopyFrom(const Counter& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Counter::IsInitialized() const { return true; } void Counter::Swap(Counter* other) { if (other != this) { std::swap(value_, other->value_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Counter::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Counter_descriptor_; metadata.reflection = Counter_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Quantile::kQuantileFieldNumber; const int Quantile::kValueFieldNumber; #endif // !_MSC_VER Quantile::Quantile() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Quantile) } void Quantile::InitAsDefaultInstance() { } Quantile::Quantile(const Quantile& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Quantile) } void Quantile::SharedCtor() { _cached_size_ = 0; quantile_ = 0; value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Quantile::~Quantile() { // @@protoc_insertion_point(destructor:io.prometheus.client.Quantile) SharedDtor(); } void Quantile::SharedDtor() { if (this != default_instance_) { } } void Quantile::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Quantile::descriptor() { protobuf_AssignDescriptorsOnce(); return Quantile_descriptor_; } const Quantile& Quantile::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Quantile* Quantile::default_instance_ = NULL; Quantile* Quantile::New() const { return new Quantile; } void Quantile::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ &reinterpret_cast(16)->f) - \ reinterpret_cast(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(quantile_, value_); #undef OFFSET_OF_FIELD_ #undef ZR_ ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Quantile::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Quantile) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double quantile = 1; case 1: { if (tag == 9) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &quantile_))); set_has_quantile(); } else { goto handle_unusual; } if (input->ExpectTag(17)) goto parse_value; break; } // optional double value = 2; case 2: { if (tag == 17) { parse_value: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); set_has_value(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Quantile) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Quantile) return false; #undef DO_ } void Quantile::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Quantile) // optional double quantile = 1; if (has_quantile()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->quantile(), output); } // optional double value = 2; if (has_value()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Quantile) } ::google::protobuf::uint8* Quantile::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Quantile) // optional double quantile = 1; if (has_quantile()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->quantile(), target); } // optional double value = 2; if (has_value()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Quantile) return target; } int Quantile::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional double quantile = 1; if (has_quantile()) { total_size += 1 + 8; } // optional double value = 2; if (has_value()) { total_size += 1 + 8; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Quantile::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Quantile* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Quantile::MergeFrom(const Quantile& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_quantile()) { set_quantile(from.quantile()); } if (from.has_value()) { set_value(from.value()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Quantile::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Quantile::CopyFrom(const Quantile& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Quantile::IsInitialized() const { return true; } void Quantile::Swap(Quantile* other) { if (other != this) { std::swap(quantile_, other->quantile_); std::swap(value_, other->value_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Quantile::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Quantile_descriptor_; metadata.reflection = Quantile_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Summary::kSampleCountFieldNumber; const int Summary::kSampleSumFieldNumber; const int Summary::kQuantileFieldNumber; #endif // !_MSC_VER Summary::Summary() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Summary) } void Summary::InitAsDefaultInstance() { } Summary::Summary(const Summary& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Summary) } void Summary::SharedCtor() { _cached_size_ = 0; sample_count_ = GOOGLE_ULONGLONG(0); sample_sum_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Summary::~Summary() { // @@protoc_insertion_point(destructor:io.prometheus.client.Summary) SharedDtor(); } void Summary::SharedDtor() { if (this != default_instance_) { } } void Summary::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Summary::descriptor() { protobuf_AssignDescriptorsOnce(); return Summary_descriptor_; } const Summary& Summary::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Summary* Summary::default_instance_ = NULL; Summary* Summary::New() const { return new Summary; } void Summary::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ &reinterpret_cast(16)->f) - \ reinterpret_cast(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(sample_count_, sample_sum_); #undef OFFSET_OF_FIELD_ #undef ZR_ quantile_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Summary::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Summary) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional uint64 sample_count = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( input, &sample_count_))); set_has_sample_count(); } else { goto handle_unusual; } if (input->ExpectTag(17)) goto parse_sample_sum; break; } // optional double sample_sum = 2; case 2: { if (tag == 17) { parse_sample_sum: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &sample_sum_))); set_has_sample_sum(); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_quantile; break; } // repeated .io.prometheus.client.Quantile quantile = 3; case 3: { if (tag == 26) { parse_quantile: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_quantile())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_quantile; if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Summary) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Summary) return false; #undef DO_ } void Summary::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Summary) // optional uint64 sample_count = 1; if (has_sample_count()) { ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sample_count(), output); } // optional double sample_sum = 2; if (has_sample_sum()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->sample_sum(), output); } // repeated .io.prometheus.client.Quantile quantile = 3; for (int i = 0; i < this->quantile_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->quantile(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Summary) } ::google::protobuf::uint8* Summary::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Summary) // optional uint64 sample_count = 1; if (has_sample_count()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->sample_count(), target); } // optional double sample_sum = 2; if (has_sample_sum()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->sample_sum(), target); } // repeated .io.prometheus.client.Quantile quantile = 3; for (int i = 0; i < this->quantile_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->quantile(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Summary) return target; } int Summary::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional uint64 sample_count = 1; if (has_sample_count()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt64Size( this->sample_count()); } // optional double sample_sum = 2; if (has_sample_sum()) { total_size += 1 + 8; } } // repeated .io.prometheus.client.Quantile quantile = 3; total_size += 1 * this->quantile_size(); for (int i = 0; i < this->quantile_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->quantile(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Summary::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Summary* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Summary::MergeFrom(const Summary& from) { GOOGLE_CHECK_NE(&from, this); quantile_.MergeFrom(from.quantile_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_sample_count()) { set_sample_count(from.sample_count()); } if (from.has_sample_sum()) { set_sample_sum(from.sample_sum()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Summary::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Summary::CopyFrom(const Summary& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Summary::IsInitialized() const { return true; } void Summary::Swap(Summary* other) { if (other != this) { std::swap(sample_count_, other->sample_count_); std::swap(sample_sum_, other->sample_sum_); quantile_.Swap(&other->quantile_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Summary::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Summary_descriptor_; metadata.reflection = Summary_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Untyped::kValueFieldNumber; #endif // !_MSC_VER Untyped::Untyped() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Untyped) } void Untyped::InitAsDefaultInstance() { } Untyped::Untyped(const Untyped& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Untyped) } void Untyped::SharedCtor() { _cached_size_ = 0; value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Untyped::~Untyped() { // @@protoc_insertion_point(destructor:io.prometheus.client.Untyped) SharedDtor(); } void Untyped::SharedDtor() { if (this != default_instance_) { } } void Untyped::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Untyped::descriptor() { protobuf_AssignDescriptorsOnce(); return Untyped_descriptor_; } const Untyped& Untyped::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Untyped* Untyped::default_instance_ = NULL; Untyped* Untyped::New() const { return new Untyped; } void Untyped::Clear() { value_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Untyped::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Untyped) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double value = 1; case 1: { if (tag == 9) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &value_))); set_has_value(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Untyped) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Untyped) return false; #undef DO_ } void Untyped::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Untyped) // optional double value = 1; if (has_value()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Untyped) } ::google::protobuf::uint8* Untyped::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Untyped) // optional double value = 1; if (has_value()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Untyped) return target; } int Untyped::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional double value = 1; if (has_value()) { total_size += 1 + 8; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Untyped::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Untyped* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Untyped::MergeFrom(const Untyped& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_value()) { set_value(from.value()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Untyped::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Untyped::CopyFrom(const Untyped& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Untyped::IsInitialized() const { return true; } void Untyped::Swap(Untyped* other) { if (other != this) { std::swap(value_, other->value_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Untyped::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Untyped_descriptor_; metadata.reflection = Untyped_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Histogram::kSampleCountFieldNumber; const int Histogram::kSampleSumFieldNumber; const int Histogram::kBucketFieldNumber; #endif // !_MSC_VER Histogram::Histogram() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Histogram) } void Histogram::InitAsDefaultInstance() { } Histogram::Histogram(const Histogram& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Histogram) } void Histogram::SharedCtor() { _cached_size_ = 0; sample_count_ = GOOGLE_ULONGLONG(0); sample_sum_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Histogram::~Histogram() { // @@protoc_insertion_point(destructor:io.prometheus.client.Histogram) SharedDtor(); } void Histogram::SharedDtor() { if (this != default_instance_) { } } void Histogram::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Histogram::descriptor() { protobuf_AssignDescriptorsOnce(); return Histogram_descriptor_; } const Histogram& Histogram::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Histogram* Histogram::default_instance_ = NULL; Histogram* Histogram::New() const { return new Histogram; } void Histogram::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ &reinterpret_cast(16)->f) - \ reinterpret_cast(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(sample_count_, sample_sum_); #undef OFFSET_OF_FIELD_ #undef ZR_ bucket_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Histogram::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Histogram) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional uint64 sample_count = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( input, &sample_count_))); set_has_sample_count(); } else { goto handle_unusual; } if (input->ExpectTag(17)) goto parse_sample_sum; break; } // optional double sample_sum = 2; case 2: { if (tag == 17) { parse_sample_sum: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &sample_sum_))); set_has_sample_sum(); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_bucket; break; } // repeated .io.prometheus.client.Bucket bucket = 3; case 3: { if (tag == 26) { parse_bucket: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_bucket())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_bucket; if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Histogram) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Histogram) return false; #undef DO_ } void Histogram::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Histogram) // optional uint64 sample_count = 1; if (has_sample_count()) { ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sample_count(), output); } // optional double sample_sum = 2; if (has_sample_sum()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->sample_sum(), output); } // repeated .io.prometheus.client.Bucket bucket = 3; for (int i = 0; i < this->bucket_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->bucket(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Histogram) } ::google::protobuf::uint8* Histogram::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Histogram) // optional uint64 sample_count = 1; if (has_sample_count()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->sample_count(), target); } // optional double sample_sum = 2; if (has_sample_sum()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->sample_sum(), target); } // repeated .io.prometheus.client.Bucket bucket = 3; for (int i = 0; i < this->bucket_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->bucket(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Histogram) return target; } int Histogram::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional uint64 sample_count = 1; if (has_sample_count()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt64Size( this->sample_count()); } // optional double sample_sum = 2; if (has_sample_sum()) { total_size += 1 + 8; } } // repeated .io.prometheus.client.Bucket bucket = 3; total_size += 1 * this->bucket_size(); for (int i = 0; i < this->bucket_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->bucket(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Histogram::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Histogram* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Histogram::MergeFrom(const Histogram& from) { GOOGLE_CHECK_NE(&from, this); bucket_.MergeFrom(from.bucket_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_sample_count()) { set_sample_count(from.sample_count()); } if (from.has_sample_sum()) { set_sample_sum(from.sample_sum()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Histogram::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Histogram::CopyFrom(const Histogram& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Histogram::IsInitialized() const { return true; } void Histogram::Swap(Histogram* other) { if (other != this) { std::swap(sample_count_, other->sample_count_); std::swap(sample_sum_, other->sample_sum_); bucket_.Swap(&other->bucket_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Histogram::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Histogram_descriptor_; metadata.reflection = Histogram_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Bucket::kCumulativeCountFieldNumber; const int Bucket::kUpperBoundFieldNumber; #endif // !_MSC_VER Bucket::Bucket() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Bucket) } void Bucket::InitAsDefaultInstance() { } Bucket::Bucket(const Bucket& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Bucket) } void Bucket::SharedCtor() { _cached_size_ = 0; cumulative_count_ = GOOGLE_ULONGLONG(0); upper_bound_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Bucket::~Bucket() { // @@protoc_insertion_point(destructor:io.prometheus.client.Bucket) SharedDtor(); } void Bucket::SharedDtor() { if (this != default_instance_) { } } void Bucket::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Bucket::descriptor() { protobuf_AssignDescriptorsOnce(); return Bucket_descriptor_; } const Bucket& Bucket::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Bucket* Bucket::default_instance_ = NULL; Bucket* Bucket::New() const { return new Bucket; } void Bucket::Clear() { #define OFFSET_OF_FIELD_(f) (reinterpret_cast( \ &reinterpret_cast(16)->f) - \ reinterpret_cast(16)) #define ZR_(first, last) do { \ size_t f = OFFSET_OF_FIELD_(first); \ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \ ::memset(&first, 0, n); \ } while (0) ZR_(cumulative_count_, upper_bound_); #undef OFFSET_OF_FIELD_ #undef ZR_ ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Bucket::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Bucket) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional uint64 cumulative_count = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>( input, &cumulative_count_))); set_has_cumulative_count(); } else { goto handle_unusual; } if (input->ExpectTag(17)) goto parse_upper_bound; break; } // optional double upper_bound = 2; case 2: { if (tag == 17) { parse_upper_bound: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &upper_bound_))); set_has_upper_bound(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Bucket) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Bucket) return false; #undef DO_ } void Bucket::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Bucket) // optional uint64 cumulative_count = 1; if (has_cumulative_count()) { ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->cumulative_count(), output); } // optional double upper_bound = 2; if (has_upper_bound()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->upper_bound(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Bucket) } ::google::protobuf::uint8* Bucket::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Bucket) // optional uint64 cumulative_count = 1; if (has_cumulative_count()) { target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->cumulative_count(), target); } // optional double upper_bound = 2; if (has_upper_bound()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->upper_bound(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Bucket) return target; } int Bucket::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional uint64 cumulative_count = 1; if (has_cumulative_count()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::UInt64Size( this->cumulative_count()); } // optional double upper_bound = 2; if (has_upper_bound()) { total_size += 1 + 8; } } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Bucket::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Bucket* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Bucket::MergeFrom(const Bucket& from) { GOOGLE_CHECK_NE(&from, this); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_cumulative_count()) { set_cumulative_count(from.cumulative_count()); } if (from.has_upper_bound()) { set_upper_bound(from.upper_bound()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Bucket::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Bucket::CopyFrom(const Bucket& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Bucket::IsInitialized() const { return true; } void Bucket::Swap(Bucket* other) { if (other != this) { std::swap(cumulative_count_, other->cumulative_count_); std::swap(upper_bound_, other->upper_bound_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Bucket::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Bucket_descriptor_; metadata.reflection = Bucket_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int Metric::kLabelFieldNumber; const int Metric::kGaugeFieldNumber; const int Metric::kCounterFieldNumber; const int Metric::kSummaryFieldNumber; const int Metric::kUntypedFieldNumber; const int Metric::kHistogramFieldNumber; const int Metric::kTimestampMsFieldNumber; #endif // !_MSC_VER Metric::Metric() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.Metric) } void Metric::InitAsDefaultInstance() { gauge_ = const_cast< ::io::prometheus::client::Gauge*>(&::io::prometheus::client::Gauge::default_instance()); counter_ = const_cast< ::io::prometheus::client::Counter*>(&::io::prometheus::client::Counter::default_instance()); summary_ = const_cast< ::io::prometheus::client::Summary*>(&::io::prometheus::client::Summary::default_instance()); untyped_ = const_cast< ::io::prometheus::client::Untyped*>(&::io::prometheus::client::Untyped::default_instance()); histogram_ = const_cast< ::io::prometheus::client::Histogram*>(&::io::prometheus::client::Histogram::default_instance()); } Metric::Metric(const Metric& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Metric) } void Metric::SharedCtor() { _cached_size_ = 0; gauge_ = NULL; counter_ = NULL; summary_ = NULL; untyped_ = NULL; histogram_ = NULL; timestamp_ms_ = GOOGLE_LONGLONG(0); ::memset(_has_bits_, 0, sizeof(_has_bits_)); } Metric::~Metric() { // @@protoc_insertion_point(destructor:io.prometheus.client.Metric) SharedDtor(); } void Metric::SharedDtor() { if (this != default_instance_) { delete gauge_; delete counter_; delete summary_; delete untyped_; delete histogram_; } } void Metric::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* Metric::descriptor() { protobuf_AssignDescriptorsOnce(); return Metric_descriptor_; } const Metric& Metric::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } Metric* Metric::default_instance_ = NULL; Metric* Metric::New() const { return new Metric; } void Metric::Clear() { if (_has_bits_[0 / 32] & 126) { if (has_gauge()) { if (gauge_ != NULL) gauge_->::io::prometheus::client::Gauge::Clear(); } if (has_counter()) { if (counter_ != NULL) counter_->::io::prometheus::client::Counter::Clear(); } if (has_summary()) { if (summary_ != NULL) summary_->::io::prometheus::client::Summary::Clear(); } if (has_untyped()) { if (untyped_ != NULL) untyped_->::io::prometheus::client::Untyped::Clear(); } if (has_histogram()) { if (histogram_ != NULL) histogram_->::io::prometheus::client::Histogram::Clear(); } timestamp_ms_ = GOOGLE_LONGLONG(0); } label_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool Metric::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.Metric) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .io.prometheus.client.LabelPair label = 1; case 1: { if (tag == 10) { parse_label: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_label())); } else { goto handle_unusual; } if (input->ExpectTag(10)) goto parse_label; if (input->ExpectTag(18)) goto parse_gauge; break; } // optional .io.prometheus.client.Gauge gauge = 2; case 2: { if (tag == 18) { parse_gauge: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_gauge())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_counter; break; } // optional .io.prometheus.client.Counter counter = 3; case 3: { if (tag == 26) { parse_counter: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_counter())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_summary; break; } // optional .io.prometheus.client.Summary summary = 4; case 4: { if (tag == 34) { parse_summary: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_summary())); } else { goto handle_unusual; } if (input->ExpectTag(42)) goto parse_untyped; break; } // optional .io.prometheus.client.Untyped untyped = 5; case 5: { if (tag == 42) { parse_untyped: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_untyped())); } else { goto handle_unusual; } if (input->ExpectTag(48)) goto parse_timestamp_ms; break; } // optional int64 timestamp_ms = 6; case 6: { if (tag == 48) { parse_timestamp_ms: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, ×tamp_ms_))); set_has_timestamp_ms(); } else { goto handle_unusual; } if (input->ExpectTag(58)) goto parse_histogram; break; } // optional .io.prometheus.client.Histogram histogram = 7; case 7: { if (tag == 58) { parse_histogram: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_histogram())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.Metric) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.Metric) return false; #undef DO_ } void Metric::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.Metric) // repeated .io.prometheus.client.LabelPair label = 1; for (int i = 0; i < this->label_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->label(i), output); } // optional .io.prometheus.client.Gauge gauge = 2; if (has_gauge()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->gauge(), output); } // optional .io.prometheus.client.Counter counter = 3; if (has_counter()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->counter(), output); } // optional .io.prometheus.client.Summary summary = 4; if (has_summary()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->summary(), output); } // optional .io.prometheus.client.Untyped untyped = 5; if (has_untyped()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->untyped(), output); } // optional int64 timestamp_ms = 6; if (has_timestamp_ms()) { ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->timestamp_ms(), output); } // optional .io.prometheus.client.Histogram histogram = 7; if (has_histogram()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->histogram(), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.Metric) } ::google::protobuf::uint8* Metric::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Metric) // repeated .io.prometheus.client.LabelPair label = 1; for (int i = 0; i < this->label_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 1, this->label(i), target); } // optional .io.prometheus.client.Gauge gauge = 2; if (has_gauge()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 2, this->gauge(), target); } // optional .io.prometheus.client.Counter counter = 3; if (has_counter()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 3, this->counter(), target); } // optional .io.prometheus.client.Summary summary = 4; if (has_summary()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->summary(), target); } // optional .io.prometheus.client.Untyped untyped = 5; if (has_untyped()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 5, this->untyped(), target); } // optional int64 timestamp_ms = 6; if (has_timestamp_ms()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->timestamp_ms(), target); } // optional .io.prometheus.client.Histogram histogram = 7; if (has_histogram()) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 7, this->histogram(), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Metric) return target; } int Metric::ByteSize() const { int total_size = 0; if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) { // optional .io.prometheus.client.Gauge gauge = 2; if (has_gauge()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->gauge()); } // optional .io.prometheus.client.Counter counter = 3; if (has_counter()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->counter()); } // optional .io.prometheus.client.Summary summary = 4; if (has_summary()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->summary()); } // optional .io.prometheus.client.Untyped untyped = 5; if (has_untyped()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->untyped()); } // optional .io.prometheus.client.Histogram histogram = 7; if (has_histogram()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->histogram()); } // optional int64 timestamp_ms = 6; if (has_timestamp_ms()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->timestamp_ms()); } } // repeated .io.prometheus.client.LabelPair label = 1; total_size += 1 * this->label_size(); for (int i = 0; i < this->label_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->label(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void Metric::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const Metric* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void Metric::MergeFrom(const Metric& from) { GOOGLE_CHECK_NE(&from, this); label_.MergeFrom(from.label_); if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) { if (from.has_gauge()) { mutable_gauge()->::io::prometheus::client::Gauge::MergeFrom(from.gauge()); } if (from.has_counter()) { mutable_counter()->::io::prometheus::client::Counter::MergeFrom(from.counter()); } if (from.has_summary()) { mutable_summary()->::io::prometheus::client::Summary::MergeFrom(from.summary()); } if (from.has_untyped()) { mutable_untyped()->::io::prometheus::client::Untyped::MergeFrom(from.untyped()); } if (from.has_histogram()) { mutable_histogram()->::io::prometheus::client::Histogram::MergeFrom(from.histogram()); } if (from.has_timestamp_ms()) { set_timestamp_ms(from.timestamp_ms()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void Metric::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void Metric::CopyFrom(const Metric& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool Metric::IsInitialized() const { return true; } void Metric::Swap(Metric* other) { if (other != this) { label_.Swap(&other->label_); std::swap(gauge_, other->gauge_); std::swap(counter_, other->counter_); std::swap(summary_, other->summary_); std::swap(untyped_, other->untyped_); std::swap(histogram_, other->histogram_); std::swap(timestamp_ms_, other->timestamp_ms_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata Metric::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = Metric_descriptor_; metadata.reflection = Metric_reflection_; return metadata; } // =================================================================== #ifndef _MSC_VER const int MetricFamily::kNameFieldNumber; const int MetricFamily::kHelpFieldNumber; const int MetricFamily::kTypeFieldNumber; const int MetricFamily::kMetricFieldNumber; #endif // !_MSC_VER MetricFamily::MetricFamily() : ::google::protobuf::Message() { SharedCtor(); // @@protoc_insertion_point(constructor:io.prometheus.client.MetricFamily) } void MetricFamily::InitAsDefaultInstance() { } MetricFamily::MetricFamily(const MetricFamily& from) : ::google::protobuf::Message() { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:io.prometheus.client.MetricFamily) } void MetricFamily::SharedCtor() { ::google::protobuf::internal::GetEmptyString(); _cached_size_ = 0; name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); type_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } MetricFamily::~MetricFamily() { // @@protoc_insertion_point(destructor:io.prometheus.client.MetricFamily) SharedDtor(); } void MetricFamily::SharedDtor() { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete name_; } if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete help_; } if (this != default_instance_) { } } void MetricFamily::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MetricFamily::descriptor() { protobuf_AssignDescriptorsOnce(); return MetricFamily_descriptor_; } const MetricFamily& MetricFamily::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto(); return *default_instance_; } MetricFamily* MetricFamily::default_instance_ = NULL; MetricFamily* MetricFamily::New() const { return new MetricFamily; } void MetricFamily::Clear() { if (_has_bits_[0 / 32] & 7) { if (has_name()) { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_->clear(); } } if (has_help()) { if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { help_->clear(); } } type_ = 0; } metric_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); mutable_unknown_fields()->Clear(); } bool MetricFamily::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:io.prometheus.client.MetricFamily) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string name = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_name())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormat::PARSE, "name"); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_help; break; } // optional string help = 2; case 2: { if (tag == 18) { parse_help: DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_help())); ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->help().data(), this->help().length(), ::google::protobuf::internal::WireFormat::PARSE, "help"); } else { goto handle_unusual; } if (input->ExpectTag(24)) goto parse_type; break; } // optional .io.prometheus.client.MetricType type = 3; case 3: { if (tag == 24) { parse_type: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::io::prometheus::client::MetricType_IsValid(value)) { set_type(static_cast< ::io::prometheus::client::MetricType >(value)); } else { mutable_unknown_fields()->AddVarint(3, value); } } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_metric; break; } // repeated .io.prometheus.client.Metric metric = 4; case 4: { if (tag == 34) { parse_metric: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, add_metric())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_metric; if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:io.prometheus.client.MetricFamily) return true; failure: // @@protoc_insertion_point(parse_failure:io.prometheus.client.MetricFamily) return false; #undef DO_ } void MetricFamily::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:io.prometheus.client.MetricFamily) // optional string name = 1; if (has_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // optional string help = 2; if (has_help()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->help().data(), this->help().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "help"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->help(), output); } // optional .io.prometheus.client.MetricType type = 3; if (has_type()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 3, this->type(), output); } // repeated .io.prometheus.client.Metric metric = 4; for (int i = 0; i < this->metric_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, this->metric(i), output); } if (!unknown_fields().empty()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:io.prometheus.client.MetricFamily) } ::google::protobuf::uint8* MetricFamily::SerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.MetricFamily) // optional string name = 1; if (has_name()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->name().data(), this->name().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // optional string help = 2; if (has_help()) { ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField( this->help().data(), this->help().length(), ::google::protobuf::internal::WireFormat::SERIALIZE, "help"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->help(), target); } // optional .io.prometheus.client.MetricType type = 3; if (has_type()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 3, this->type(), target); } // repeated .io.prometheus.client.Metric metric = 4; for (int i = 0; i < this->metric_size(); i++) { target = ::google::protobuf::internal::WireFormatLite:: WriteMessageNoVirtualToArray( 4, this->metric(i), target); } if (!unknown_fields().empty()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.MetricFamily) return target; } int MetricFamily::ByteSize() const { int total_size = 0; if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) { // optional string name = 1; if (has_name()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // optional string help = 2; if (has_help()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->help()); } // optional .io.prometheus.client.MetricType type = 3; if (has_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->type()); } } // repeated .io.prometheus.client.Metric metric = 4; total_size += 1 * this->metric_size(); for (int i = 0; i < this->metric_size(); i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->metric(i)); } if (!unknown_fields().empty()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MetricFamily::MergeFrom(const ::google::protobuf::Message& from) { GOOGLE_CHECK_NE(&from, this); const MetricFamily* source = ::google::protobuf::internal::dynamic_cast_if_available( &from); if (source == NULL) { ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { MergeFrom(*source); } } void MetricFamily::MergeFrom(const MetricFamily& from) { GOOGLE_CHECK_NE(&from, this); metric_.MergeFrom(from.metric_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_name()) { set_name(from.name()); } if (from.has_help()) { set_help(from.help()); } if (from.has_type()) { set_type(from.type()); } } mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } void MetricFamily::CopyFrom(const ::google::protobuf::Message& from) { if (&from == this) return; Clear(); MergeFrom(from); } void MetricFamily::CopyFrom(const MetricFamily& from) { if (&from == this) return; Clear(); MergeFrom(from); } bool MetricFamily::IsInitialized() const { return true; } void MetricFamily::Swap(MetricFamily* other) { if (other != this) { std::swap(name_, other->name_); std::swap(help_, other->help_); std::swap(type_, other->type_); metric_.Swap(&other->metric_); std::swap(_has_bits_[0], other->_has_bits_[0]); _unknown_fields_.Swap(&other->_unknown_fields_); std::swap(_cached_size_, other->_cached_size_); } } ::google::protobuf::Metadata MetricFamily::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = MetricFamily_descriptor_; metadata.reflection = MetricFamily_reflection_; return metadata; } // @@protoc_insertion_point(namespace_scope) } // namespace client } // namespace prometheus } // namespace io // @@protoc_insertion_point(global_scope) ================================================ FILE: vendor/github.com/prometheus/client_model/cpp/metrics.pb.h ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: metrics.proto #ifndef PROTOBUF_metrics_2eproto__INCLUDED #define PROTOBUF_metrics_2eproto__INCLUDED #include #include #if GOOGLE_PROTOBUF_VERSION < 2006000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include #include #include #include #include #include // @@protoc_insertion_point(includes) namespace io { namespace prometheus { namespace client { // Internal implementation detail -- do not call these. void protobuf_AddDesc_metrics_2eproto(); void protobuf_AssignDesc_metrics_2eproto(); void protobuf_ShutdownFile_metrics_2eproto(); class LabelPair; class Gauge; class Counter; class Quantile; class Summary; class Untyped; class Histogram; class Bucket; class Metric; class MetricFamily; enum MetricType { COUNTER = 0, GAUGE = 1, SUMMARY = 2, UNTYPED = 3, HISTOGRAM = 4 }; bool MetricType_IsValid(int value); const MetricType MetricType_MIN = COUNTER; const MetricType MetricType_MAX = HISTOGRAM; const int MetricType_ARRAYSIZE = MetricType_MAX + 1; const ::google::protobuf::EnumDescriptor* MetricType_descriptor(); inline const ::std::string& MetricType_Name(MetricType value) { return ::google::protobuf::internal::NameOfEnum( MetricType_descriptor(), value); } inline bool MetricType_Parse( const ::std::string& name, MetricType* value) { return ::google::protobuf::internal::ParseNamedEnum( MetricType_descriptor(), name, value); } // =================================================================== class LabelPair : public ::google::protobuf::Message { public: LabelPair(); virtual ~LabelPair(); LabelPair(const LabelPair& from); inline LabelPair& operator=(const LabelPair& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const LabelPair& default_instance(); void Swap(LabelPair* other); // implements Message ---------------------------------------------- LabelPair* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const LabelPair& from); void MergeFrom(const LabelPair& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string name = 1; inline bool has_name() const; inline void clear_name(); static const int kNameFieldNumber = 1; inline const ::std::string& name() const; inline void set_name(const ::std::string& value); inline void set_name(const char* value); inline void set_name(const char* value, size_t size); inline ::std::string* mutable_name(); inline ::std::string* release_name(); inline void set_allocated_name(::std::string* name); // optional string value = 2; inline bool has_value() const; inline void clear_value(); static const int kValueFieldNumber = 2; inline const ::std::string& value() const; inline void set_value(const ::std::string& value); inline void set_value(const char* value); inline void set_value(const char* value, size_t size); inline ::std::string* mutable_value(); inline ::std::string* release_value(); inline void set_allocated_value(::std::string* value); // @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair) private: inline void set_has_name(); inline void clear_has_name(); inline void set_has_value(); inline void clear_has_value(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; ::std::string* name_; ::std::string* value_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static LabelPair* default_instance_; }; // ------------------------------------------------------------------- class Gauge : public ::google::protobuf::Message { public: Gauge(); virtual ~Gauge(); Gauge(const Gauge& from); inline Gauge& operator=(const Gauge& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Gauge& default_instance(); void Swap(Gauge* other); // implements Message ---------------------------------------------- Gauge* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Gauge& from); void MergeFrom(const Gauge& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional double value = 1; inline bool has_value() const; inline void clear_value(); static const int kValueFieldNumber = 1; inline double value() const; inline void set_value(double value); // @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge) private: inline void set_has_value(); inline void clear_has_value(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; double value_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Gauge* default_instance_; }; // ------------------------------------------------------------------- class Counter : public ::google::protobuf::Message { public: Counter(); virtual ~Counter(); Counter(const Counter& from); inline Counter& operator=(const Counter& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Counter& default_instance(); void Swap(Counter* other); // implements Message ---------------------------------------------- Counter* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Counter& from); void MergeFrom(const Counter& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional double value = 1; inline bool has_value() const; inline void clear_value(); static const int kValueFieldNumber = 1; inline double value() const; inline void set_value(double value); // @@protoc_insertion_point(class_scope:io.prometheus.client.Counter) private: inline void set_has_value(); inline void clear_has_value(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; double value_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Counter* default_instance_; }; // ------------------------------------------------------------------- class Quantile : public ::google::protobuf::Message { public: Quantile(); virtual ~Quantile(); Quantile(const Quantile& from); inline Quantile& operator=(const Quantile& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Quantile& default_instance(); void Swap(Quantile* other); // implements Message ---------------------------------------------- Quantile* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Quantile& from); void MergeFrom(const Quantile& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional double quantile = 1; inline bool has_quantile() const; inline void clear_quantile(); static const int kQuantileFieldNumber = 1; inline double quantile() const; inline void set_quantile(double value); // optional double value = 2; inline bool has_value() const; inline void clear_value(); static const int kValueFieldNumber = 2; inline double value() const; inline void set_value(double value); // @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile) private: inline void set_has_quantile(); inline void clear_has_quantile(); inline void set_has_value(); inline void clear_has_value(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; double quantile_; double value_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Quantile* default_instance_; }; // ------------------------------------------------------------------- class Summary : public ::google::protobuf::Message { public: Summary(); virtual ~Summary(); Summary(const Summary& from); inline Summary& operator=(const Summary& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Summary& default_instance(); void Swap(Summary* other); // implements Message ---------------------------------------------- Summary* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Summary& from); void MergeFrom(const Summary& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional uint64 sample_count = 1; inline bool has_sample_count() const; inline void clear_sample_count(); static const int kSampleCountFieldNumber = 1; inline ::google::protobuf::uint64 sample_count() const; inline void set_sample_count(::google::protobuf::uint64 value); // optional double sample_sum = 2; inline bool has_sample_sum() const; inline void clear_sample_sum(); static const int kSampleSumFieldNumber = 2; inline double sample_sum() const; inline void set_sample_sum(double value); // repeated .io.prometheus.client.Quantile quantile = 3; inline int quantile_size() const; inline void clear_quantile(); static const int kQuantileFieldNumber = 3; inline const ::io::prometheus::client::Quantile& quantile(int index) const; inline ::io::prometheus::client::Quantile* mutable_quantile(int index); inline ::io::prometheus::client::Quantile* add_quantile(); inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >& quantile() const; inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >* mutable_quantile(); // @@protoc_insertion_point(class_scope:io.prometheus.client.Summary) private: inline void set_has_sample_count(); inline void clear_has_sample_count(); inline void set_has_sample_sum(); inline void clear_has_sample_sum(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; ::google::protobuf::uint64 sample_count_; double sample_sum_; ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile > quantile_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Summary* default_instance_; }; // ------------------------------------------------------------------- class Untyped : public ::google::protobuf::Message { public: Untyped(); virtual ~Untyped(); Untyped(const Untyped& from); inline Untyped& operator=(const Untyped& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Untyped& default_instance(); void Swap(Untyped* other); // implements Message ---------------------------------------------- Untyped* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Untyped& from); void MergeFrom(const Untyped& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional double value = 1; inline bool has_value() const; inline void clear_value(); static const int kValueFieldNumber = 1; inline double value() const; inline void set_value(double value); // @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped) private: inline void set_has_value(); inline void clear_has_value(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; double value_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Untyped* default_instance_; }; // ------------------------------------------------------------------- class Histogram : public ::google::protobuf::Message { public: Histogram(); virtual ~Histogram(); Histogram(const Histogram& from); inline Histogram& operator=(const Histogram& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Histogram& default_instance(); void Swap(Histogram* other); // implements Message ---------------------------------------------- Histogram* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Histogram& from); void MergeFrom(const Histogram& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional uint64 sample_count = 1; inline bool has_sample_count() const; inline void clear_sample_count(); static const int kSampleCountFieldNumber = 1; inline ::google::protobuf::uint64 sample_count() const; inline void set_sample_count(::google::protobuf::uint64 value); // optional double sample_sum = 2; inline bool has_sample_sum() const; inline void clear_sample_sum(); static const int kSampleSumFieldNumber = 2; inline double sample_sum() const; inline void set_sample_sum(double value); // repeated .io.prometheus.client.Bucket bucket = 3; inline int bucket_size() const; inline void clear_bucket(); static const int kBucketFieldNumber = 3; inline const ::io::prometheus::client::Bucket& bucket(int index) const; inline ::io::prometheus::client::Bucket* mutable_bucket(int index); inline ::io::prometheus::client::Bucket* add_bucket(); inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >& bucket() const; inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >* mutable_bucket(); // @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram) private: inline void set_has_sample_count(); inline void clear_has_sample_count(); inline void set_has_sample_sum(); inline void clear_has_sample_sum(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; ::google::protobuf::uint64 sample_count_; double sample_sum_; ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket > bucket_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Histogram* default_instance_; }; // ------------------------------------------------------------------- class Bucket : public ::google::protobuf::Message { public: Bucket(); virtual ~Bucket(); Bucket(const Bucket& from); inline Bucket& operator=(const Bucket& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Bucket& default_instance(); void Swap(Bucket* other); // implements Message ---------------------------------------------- Bucket* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Bucket& from); void MergeFrom(const Bucket& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional uint64 cumulative_count = 1; inline bool has_cumulative_count() const; inline void clear_cumulative_count(); static const int kCumulativeCountFieldNumber = 1; inline ::google::protobuf::uint64 cumulative_count() const; inline void set_cumulative_count(::google::protobuf::uint64 value); // optional double upper_bound = 2; inline bool has_upper_bound() const; inline void clear_upper_bound(); static const int kUpperBoundFieldNumber = 2; inline double upper_bound() const; inline void set_upper_bound(double value); // @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket) private: inline void set_has_cumulative_count(); inline void clear_has_cumulative_count(); inline void set_has_upper_bound(); inline void clear_has_upper_bound(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; ::google::protobuf::uint64 cumulative_count_; double upper_bound_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Bucket* default_instance_; }; // ------------------------------------------------------------------- class Metric : public ::google::protobuf::Message { public: Metric(); virtual ~Metric(); Metric(const Metric& from); inline Metric& operator=(const Metric& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const Metric& default_instance(); void Swap(Metric* other); // implements Message ---------------------------------------------- Metric* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const Metric& from); void MergeFrom(const Metric& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // repeated .io.prometheus.client.LabelPair label = 1; inline int label_size() const; inline void clear_label(); static const int kLabelFieldNumber = 1; inline const ::io::prometheus::client::LabelPair& label(int index) const; inline ::io::prometheus::client::LabelPair* mutable_label(int index); inline ::io::prometheus::client::LabelPair* add_label(); inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >& label() const; inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >* mutable_label(); // optional .io.prometheus.client.Gauge gauge = 2; inline bool has_gauge() const; inline void clear_gauge(); static const int kGaugeFieldNumber = 2; inline const ::io::prometheus::client::Gauge& gauge() const; inline ::io::prometheus::client::Gauge* mutable_gauge(); inline ::io::prometheus::client::Gauge* release_gauge(); inline void set_allocated_gauge(::io::prometheus::client::Gauge* gauge); // optional .io.prometheus.client.Counter counter = 3; inline bool has_counter() const; inline void clear_counter(); static const int kCounterFieldNumber = 3; inline const ::io::prometheus::client::Counter& counter() const; inline ::io::prometheus::client::Counter* mutable_counter(); inline ::io::prometheus::client::Counter* release_counter(); inline void set_allocated_counter(::io::prometheus::client::Counter* counter); // optional .io.prometheus.client.Summary summary = 4; inline bool has_summary() const; inline void clear_summary(); static const int kSummaryFieldNumber = 4; inline const ::io::prometheus::client::Summary& summary() const; inline ::io::prometheus::client::Summary* mutable_summary(); inline ::io::prometheus::client::Summary* release_summary(); inline void set_allocated_summary(::io::prometheus::client::Summary* summary); // optional .io.prometheus.client.Untyped untyped = 5; inline bool has_untyped() const; inline void clear_untyped(); static const int kUntypedFieldNumber = 5; inline const ::io::prometheus::client::Untyped& untyped() const; inline ::io::prometheus::client::Untyped* mutable_untyped(); inline ::io::prometheus::client::Untyped* release_untyped(); inline void set_allocated_untyped(::io::prometheus::client::Untyped* untyped); // optional .io.prometheus.client.Histogram histogram = 7; inline bool has_histogram() const; inline void clear_histogram(); static const int kHistogramFieldNumber = 7; inline const ::io::prometheus::client::Histogram& histogram() const; inline ::io::prometheus::client::Histogram* mutable_histogram(); inline ::io::prometheus::client::Histogram* release_histogram(); inline void set_allocated_histogram(::io::prometheus::client::Histogram* histogram); // optional int64 timestamp_ms = 6; inline bool has_timestamp_ms() const; inline void clear_timestamp_ms(); static const int kTimestampMsFieldNumber = 6; inline ::google::protobuf::int64 timestamp_ms() const; inline void set_timestamp_ms(::google::protobuf::int64 value); // @@protoc_insertion_point(class_scope:io.prometheus.client.Metric) private: inline void set_has_gauge(); inline void clear_has_gauge(); inline void set_has_counter(); inline void clear_has_counter(); inline void set_has_summary(); inline void clear_has_summary(); inline void set_has_untyped(); inline void clear_has_untyped(); inline void set_has_histogram(); inline void clear_has_histogram(); inline void set_has_timestamp_ms(); inline void clear_has_timestamp_ms(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair > label_; ::io::prometheus::client::Gauge* gauge_; ::io::prometheus::client::Counter* counter_; ::io::prometheus::client::Summary* summary_; ::io::prometheus::client::Untyped* untyped_; ::io::prometheus::client::Histogram* histogram_; ::google::protobuf::int64 timestamp_ms_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static Metric* default_instance_; }; // ------------------------------------------------------------------- class MetricFamily : public ::google::protobuf::Message { public: MetricFamily(); virtual ~MetricFamily(); MetricFamily(const MetricFamily& from); inline MetricFamily& operator=(const MetricFamily& from) { CopyFrom(from); return *this; } inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const { return _unknown_fields_; } inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() { return &_unknown_fields_; } static const ::google::protobuf::Descriptor* descriptor(); static const MetricFamily& default_instance(); void Swap(MetricFamily* other); // implements Message ---------------------------------------------- MetricFamily* New() const; void CopyFrom(const ::google::protobuf::Message& from); void MergeFrom(const ::google::protobuf::Message& from); void CopyFrom(const MetricFamily& from); void MergeFrom(const MetricFamily& from); void Clear(); bool IsInitialized() const; int ByteSize() const; bool MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input); void SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const; ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const; int GetCachedSize() const { return _cached_size_; } private: void SharedCtor(); void SharedDtor(); void SetCachedSize(int size) const; public: ::google::protobuf::Metadata GetMetadata() const; // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- // optional string name = 1; inline bool has_name() const; inline void clear_name(); static const int kNameFieldNumber = 1; inline const ::std::string& name() const; inline void set_name(const ::std::string& value); inline void set_name(const char* value); inline void set_name(const char* value, size_t size); inline ::std::string* mutable_name(); inline ::std::string* release_name(); inline void set_allocated_name(::std::string* name); // optional string help = 2; inline bool has_help() const; inline void clear_help(); static const int kHelpFieldNumber = 2; inline const ::std::string& help() const; inline void set_help(const ::std::string& value); inline void set_help(const char* value); inline void set_help(const char* value, size_t size); inline ::std::string* mutable_help(); inline ::std::string* release_help(); inline void set_allocated_help(::std::string* help); // optional .io.prometheus.client.MetricType type = 3; inline bool has_type() const; inline void clear_type(); static const int kTypeFieldNumber = 3; inline ::io::prometheus::client::MetricType type() const; inline void set_type(::io::prometheus::client::MetricType value); // repeated .io.prometheus.client.Metric metric = 4; inline int metric_size() const; inline void clear_metric(); static const int kMetricFieldNumber = 4; inline const ::io::prometheus::client::Metric& metric(int index) const; inline ::io::prometheus::client::Metric* mutable_metric(int index); inline ::io::prometheus::client::Metric* add_metric(); inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >& metric() const; inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >* mutable_metric(); // @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily) private: inline void set_has_name(); inline void clear_has_name(); inline void set_has_help(); inline void clear_has_help(); inline void set_has_type(); inline void clear_has_type(); ::google::protobuf::UnknownFieldSet _unknown_fields_; ::google::protobuf::uint32 _has_bits_[1]; mutable int _cached_size_; ::std::string* name_; ::std::string* help_; ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric > metric_; int type_; friend void protobuf_AddDesc_metrics_2eproto(); friend void protobuf_AssignDesc_metrics_2eproto(); friend void protobuf_ShutdownFile_metrics_2eproto(); void InitAsDefaultInstance(); static MetricFamily* default_instance_; }; // =================================================================== // =================================================================== // LabelPair // optional string name = 1; inline bool LabelPair::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void LabelPair::set_has_name() { _has_bits_[0] |= 0x00000001u; } inline void LabelPair::clear_has_name() { _has_bits_[0] &= ~0x00000001u; } inline void LabelPair::clear_name() { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_->clear(); } clear_has_name(); } inline const ::std::string& LabelPair::name() const { // @@protoc_insertion_point(field_get:io.prometheus.client.LabelPair.name) return *name_; } inline void LabelPair::set_name(const ::std::string& value) { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } name_->assign(value); // @@protoc_insertion_point(field_set:io.prometheus.client.LabelPair.name) } inline void LabelPair::set_name(const char* value) { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } name_->assign(value); // @@protoc_insertion_point(field_set_char:io.prometheus.client.LabelPair.name) } inline void LabelPair::set_name(const char* value, size_t size) { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } name_->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.LabelPair.name) } inline ::std::string* LabelPair::mutable_name() { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } // @@protoc_insertion_point(field_mutable:io.prometheus.client.LabelPair.name) return name_; } inline ::std::string* LabelPair::release_name() { clear_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { return NULL; } else { ::std::string* temp = name_; name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); return temp; } } inline void LabelPair::set_allocated_name(::std::string* name) { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete name_; } if (name) { set_has_name(); name_ = name; } else { clear_has_name(); name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.LabelPair.name) } // optional string value = 2; inline bool LabelPair::has_value() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void LabelPair::set_has_value() { _has_bits_[0] |= 0x00000002u; } inline void LabelPair::clear_has_value() { _has_bits_[0] &= ~0x00000002u; } inline void LabelPair::clear_value() { if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { value_->clear(); } clear_has_value(); } inline const ::std::string& LabelPair::value() const { // @@protoc_insertion_point(field_get:io.prometheus.client.LabelPair.value) return *value_; } inline void LabelPair::set_value(const ::std::string& value) { set_has_value(); if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { value_ = new ::std::string; } value_->assign(value); // @@protoc_insertion_point(field_set:io.prometheus.client.LabelPair.value) } inline void LabelPair::set_value(const char* value) { set_has_value(); if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { value_ = new ::std::string; } value_->assign(value); // @@protoc_insertion_point(field_set_char:io.prometheus.client.LabelPair.value) } inline void LabelPair::set_value(const char* value, size_t size) { set_has_value(); if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { value_ = new ::std::string; } value_->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.LabelPair.value) } inline ::std::string* LabelPair::mutable_value() { set_has_value(); if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { value_ = new ::std::string; } // @@protoc_insertion_point(field_mutable:io.prometheus.client.LabelPair.value) return value_; } inline ::std::string* LabelPair::release_value() { clear_has_value(); if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { return NULL; } else { ::std::string* temp = value_; value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); return temp; } } inline void LabelPair::set_allocated_value(::std::string* value) { if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete value_; } if (value) { set_has_value(); value_ = value; } else { clear_has_value(); value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.LabelPair.value) } // ------------------------------------------------------------------- // Gauge // optional double value = 1; inline bool Gauge::has_value() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Gauge::set_has_value() { _has_bits_[0] |= 0x00000001u; } inline void Gauge::clear_has_value() { _has_bits_[0] &= ~0x00000001u; } inline void Gauge::clear_value() { value_ = 0; clear_has_value(); } inline double Gauge::value() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Gauge.value) return value_; } inline void Gauge::set_value(double value) { set_has_value(); value_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Gauge.value) } // ------------------------------------------------------------------- // Counter // optional double value = 1; inline bool Counter::has_value() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Counter::set_has_value() { _has_bits_[0] |= 0x00000001u; } inline void Counter::clear_has_value() { _has_bits_[0] &= ~0x00000001u; } inline void Counter::clear_value() { value_ = 0; clear_has_value(); } inline double Counter::value() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Counter.value) return value_; } inline void Counter::set_value(double value) { set_has_value(); value_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Counter.value) } // ------------------------------------------------------------------- // Quantile // optional double quantile = 1; inline bool Quantile::has_quantile() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Quantile::set_has_quantile() { _has_bits_[0] |= 0x00000001u; } inline void Quantile::clear_has_quantile() { _has_bits_[0] &= ~0x00000001u; } inline void Quantile::clear_quantile() { quantile_ = 0; clear_has_quantile(); } inline double Quantile::quantile() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Quantile.quantile) return quantile_; } inline void Quantile::set_quantile(double value) { set_has_quantile(); quantile_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Quantile.quantile) } // optional double value = 2; inline bool Quantile::has_value() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Quantile::set_has_value() { _has_bits_[0] |= 0x00000002u; } inline void Quantile::clear_has_value() { _has_bits_[0] &= ~0x00000002u; } inline void Quantile::clear_value() { value_ = 0; clear_has_value(); } inline double Quantile::value() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Quantile.value) return value_; } inline void Quantile::set_value(double value) { set_has_value(); value_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Quantile.value) } // ------------------------------------------------------------------- // Summary // optional uint64 sample_count = 1; inline bool Summary::has_sample_count() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Summary::set_has_sample_count() { _has_bits_[0] |= 0x00000001u; } inline void Summary::clear_has_sample_count() { _has_bits_[0] &= ~0x00000001u; } inline void Summary::clear_sample_count() { sample_count_ = GOOGLE_ULONGLONG(0); clear_has_sample_count(); } inline ::google::protobuf::uint64 Summary::sample_count() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.sample_count) return sample_count_; } inline void Summary::set_sample_count(::google::protobuf::uint64 value) { set_has_sample_count(); sample_count_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Summary.sample_count) } // optional double sample_sum = 2; inline bool Summary::has_sample_sum() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Summary::set_has_sample_sum() { _has_bits_[0] |= 0x00000002u; } inline void Summary::clear_has_sample_sum() { _has_bits_[0] &= ~0x00000002u; } inline void Summary::clear_sample_sum() { sample_sum_ = 0; clear_has_sample_sum(); } inline double Summary::sample_sum() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.sample_sum) return sample_sum_; } inline void Summary::set_sample_sum(double value) { set_has_sample_sum(); sample_sum_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Summary.sample_sum) } // repeated .io.prometheus.client.Quantile quantile = 3; inline int Summary::quantile_size() const { return quantile_.size(); } inline void Summary::clear_quantile() { quantile_.Clear(); } inline const ::io::prometheus::client::Quantile& Summary::quantile(int index) const { // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.quantile) return quantile_.Get(index); } inline ::io::prometheus::client::Quantile* Summary::mutable_quantile(int index) { // @@protoc_insertion_point(field_mutable:io.prometheus.client.Summary.quantile) return quantile_.Mutable(index); } inline ::io::prometheus::client::Quantile* Summary::add_quantile() { // @@protoc_insertion_point(field_add:io.prometheus.client.Summary.quantile) return quantile_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >& Summary::quantile() const { // @@protoc_insertion_point(field_list:io.prometheus.client.Summary.quantile) return quantile_; } inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >* Summary::mutable_quantile() { // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Summary.quantile) return &quantile_; } // ------------------------------------------------------------------- // Untyped // optional double value = 1; inline bool Untyped::has_value() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Untyped::set_has_value() { _has_bits_[0] |= 0x00000001u; } inline void Untyped::clear_has_value() { _has_bits_[0] &= ~0x00000001u; } inline void Untyped::clear_value() { value_ = 0; clear_has_value(); } inline double Untyped::value() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Untyped.value) return value_; } inline void Untyped::set_value(double value) { set_has_value(); value_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Untyped.value) } // ------------------------------------------------------------------- // Histogram // optional uint64 sample_count = 1; inline bool Histogram::has_sample_count() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Histogram::set_has_sample_count() { _has_bits_[0] |= 0x00000001u; } inline void Histogram::clear_has_sample_count() { _has_bits_[0] &= ~0x00000001u; } inline void Histogram::clear_sample_count() { sample_count_ = GOOGLE_ULONGLONG(0); clear_has_sample_count(); } inline ::google::protobuf::uint64 Histogram::sample_count() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.sample_count) return sample_count_; } inline void Histogram::set_sample_count(::google::protobuf::uint64 value) { set_has_sample_count(); sample_count_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Histogram.sample_count) } // optional double sample_sum = 2; inline bool Histogram::has_sample_sum() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Histogram::set_has_sample_sum() { _has_bits_[0] |= 0x00000002u; } inline void Histogram::clear_has_sample_sum() { _has_bits_[0] &= ~0x00000002u; } inline void Histogram::clear_sample_sum() { sample_sum_ = 0; clear_has_sample_sum(); } inline double Histogram::sample_sum() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.sample_sum) return sample_sum_; } inline void Histogram::set_sample_sum(double value) { set_has_sample_sum(); sample_sum_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Histogram.sample_sum) } // repeated .io.prometheus.client.Bucket bucket = 3; inline int Histogram::bucket_size() const { return bucket_.size(); } inline void Histogram::clear_bucket() { bucket_.Clear(); } inline const ::io::prometheus::client::Bucket& Histogram::bucket(int index) const { // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.bucket) return bucket_.Get(index); } inline ::io::prometheus::client::Bucket* Histogram::mutable_bucket(int index) { // @@protoc_insertion_point(field_mutable:io.prometheus.client.Histogram.bucket) return bucket_.Mutable(index); } inline ::io::prometheus::client::Bucket* Histogram::add_bucket() { // @@protoc_insertion_point(field_add:io.prometheus.client.Histogram.bucket) return bucket_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >& Histogram::bucket() const { // @@protoc_insertion_point(field_list:io.prometheus.client.Histogram.bucket) return bucket_; } inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >* Histogram::mutable_bucket() { // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Histogram.bucket) return &bucket_; } // ------------------------------------------------------------------- // Bucket // optional uint64 cumulative_count = 1; inline bool Bucket::has_cumulative_count() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void Bucket::set_has_cumulative_count() { _has_bits_[0] |= 0x00000001u; } inline void Bucket::clear_has_cumulative_count() { _has_bits_[0] &= ~0x00000001u; } inline void Bucket::clear_cumulative_count() { cumulative_count_ = GOOGLE_ULONGLONG(0); clear_has_cumulative_count(); } inline ::google::protobuf::uint64 Bucket::cumulative_count() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Bucket.cumulative_count) return cumulative_count_; } inline void Bucket::set_cumulative_count(::google::protobuf::uint64 value) { set_has_cumulative_count(); cumulative_count_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Bucket.cumulative_count) } // optional double upper_bound = 2; inline bool Bucket::has_upper_bound() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Bucket::set_has_upper_bound() { _has_bits_[0] |= 0x00000002u; } inline void Bucket::clear_has_upper_bound() { _has_bits_[0] &= ~0x00000002u; } inline void Bucket::clear_upper_bound() { upper_bound_ = 0; clear_has_upper_bound(); } inline double Bucket::upper_bound() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Bucket.upper_bound) return upper_bound_; } inline void Bucket::set_upper_bound(double value) { set_has_upper_bound(); upper_bound_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Bucket.upper_bound) } // ------------------------------------------------------------------- // Metric // repeated .io.prometheus.client.LabelPair label = 1; inline int Metric::label_size() const { return label_.size(); } inline void Metric::clear_label() { label_.Clear(); } inline const ::io::prometheus::client::LabelPair& Metric::label(int index) const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.label) return label_.Get(index); } inline ::io::prometheus::client::LabelPair* Metric::mutable_label(int index) { // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.label) return label_.Mutable(index); } inline ::io::prometheus::client::LabelPair* Metric::add_label() { // @@protoc_insertion_point(field_add:io.prometheus.client.Metric.label) return label_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >& Metric::label() const { // @@protoc_insertion_point(field_list:io.prometheus.client.Metric.label) return label_; } inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >* Metric::mutable_label() { // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Metric.label) return &label_; } // optional .io.prometheus.client.Gauge gauge = 2; inline bool Metric::has_gauge() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void Metric::set_has_gauge() { _has_bits_[0] |= 0x00000002u; } inline void Metric::clear_has_gauge() { _has_bits_[0] &= ~0x00000002u; } inline void Metric::clear_gauge() { if (gauge_ != NULL) gauge_->::io::prometheus::client::Gauge::Clear(); clear_has_gauge(); } inline const ::io::prometheus::client::Gauge& Metric::gauge() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.gauge) return gauge_ != NULL ? *gauge_ : *default_instance_->gauge_; } inline ::io::prometheus::client::Gauge* Metric::mutable_gauge() { set_has_gauge(); if (gauge_ == NULL) gauge_ = new ::io::prometheus::client::Gauge; // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.gauge) return gauge_; } inline ::io::prometheus::client::Gauge* Metric::release_gauge() { clear_has_gauge(); ::io::prometheus::client::Gauge* temp = gauge_; gauge_ = NULL; return temp; } inline void Metric::set_allocated_gauge(::io::prometheus::client::Gauge* gauge) { delete gauge_; gauge_ = gauge; if (gauge) { set_has_gauge(); } else { clear_has_gauge(); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.gauge) } // optional .io.prometheus.client.Counter counter = 3; inline bool Metric::has_counter() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void Metric::set_has_counter() { _has_bits_[0] |= 0x00000004u; } inline void Metric::clear_has_counter() { _has_bits_[0] &= ~0x00000004u; } inline void Metric::clear_counter() { if (counter_ != NULL) counter_->::io::prometheus::client::Counter::Clear(); clear_has_counter(); } inline const ::io::prometheus::client::Counter& Metric::counter() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.counter) return counter_ != NULL ? *counter_ : *default_instance_->counter_; } inline ::io::prometheus::client::Counter* Metric::mutable_counter() { set_has_counter(); if (counter_ == NULL) counter_ = new ::io::prometheus::client::Counter; // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.counter) return counter_; } inline ::io::prometheus::client::Counter* Metric::release_counter() { clear_has_counter(); ::io::prometheus::client::Counter* temp = counter_; counter_ = NULL; return temp; } inline void Metric::set_allocated_counter(::io::prometheus::client::Counter* counter) { delete counter_; counter_ = counter; if (counter) { set_has_counter(); } else { clear_has_counter(); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.counter) } // optional .io.prometheus.client.Summary summary = 4; inline bool Metric::has_summary() const { return (_has_bits_[0] & 0x00000008u) != 0; } inline void Metric::set_has_summary() { _has_bits_[0] |= 0x00000008u; } inline void Metric::clear_has_summary() { _has_bits_[0] &= ~0x00000008u; } inline void Metric::clear_summary() { if (summary_ != NULL) summary_->::io::prometheus::client::Summary::Clear(); clear_has_summary(); } inline const ::io::prometheus::client::Summary& Metric::summary() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.summary) return summary_ != NULL ? *summary_ : *default_instance_->summary_; } inline ::io::prometheus::client::Summary* Metric::mutable_summary() { set_has_summary(); if (summary_ == NULL) summary_ = new ::io::prometheus::client::Summary; // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.summary) return summary_; } inline ::io::prometheus::client::Summary* Metric::release_summary() { clear_has_summary(); ::io::prometheus::client::Summary* temp = summary_; summary_ = NULL; return temp; } inline void Metric::set_allocated_summary(::io::prometheus::client::Summary* summary) { delete summary_; summary_ = summary; if (summary) { set_has_summary(); } else { clear_has_summary(); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.summary) } // optional .io.prometheus.client.Untyped untyped = 5; inline bool Metric::has_untyped() const { return (_has_bits_[0] & 0x00000010u) != 0; } inline void Metric::set_has_untyped() { _has_bits_[0] |= 0x00000010u; } inline void Metric::clear_has_untyped() { _has_bits_[0] &= ~0x00000010u; } inline void Metric::clear_untyped() { if (untyped_ != NULL) untyped_->::io::prometheus::client::Untyped::Clear(); clear_has_untyped(); } inline const ::io::prometheus::client::Untyped& Metric::untyped() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.untyped) return untyped_ != NULL ? *untyped_ : *default_instance_->untyped_; } inline ::io::prometheus::client::Untyped* Metric::mutable_untyped() { set_has_untyped(); if (untyped_ == NULL) untyped_ = new ::io::prometheus::client::Untyped; // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.untyped) return untyped_; } inline ::io::prometheus::client::Untyped* Metric::release_untyped() { clear_has_untyped(); ::io::prometheus::client::Untyped* temp = untyped_; untyped_ = NULL; return temp; } inline void Metric::set_allocated_untyped(::io::prometheus::client::Untyped* untyped) { delete untyped_; untyped_ = untyped; if (untyped) { set_has_untyped(); } else { clear_has_untyped(); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.untyped) } // optional .io.prometheus.client.Histogram histogram = 7; inline bool Metric::has_histogram() const { return (_has_bits_[0] & 0x00000020u) != 0; } inline void Metric::set_has_histogram() { _has_bits_[0] |= 0x00000020u; } inline void Metric::clear_has_histogram() { _has_bits_[0] &= ~0x00000020u; } inline void Metric::clear_histogram() { if (histogram_ != NULL) histogram_->::io::prometheus::client::Histogram::Clear(); clear_has_histogram(); } inline const ::io::prometheus::client::Histogram& Metric::histogram() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.histogram) return histogram_ != NULL ? *histogram_ : *default_instance_->histogram_; } inline ::io::prometheus::client::Histogram* Metric::mutable_histogram() { set_has_histogram(); if (histogram_ == NULL) histogram_ = new ::io::prometheus::client::Histogram; // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.histogram) return histogram_; } inline ::io::prometheus::client::Histogram* Metric::release_histogram() { clear_has_histogram(); ::io::prometheus::client::Histogram* temp = histogram_; histogram_ = NULL; return temp; } inline void Metric::set_allocated_histogram(::io::prometheus::client::Histogram* histogram) { delete histogram_; histogram_ = histogram; if (histogram) { set_has_histogram(); } else { clear_has_histogram(); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.histogram) } // optional int64 timestamp_ms = 6; inline bool Metric::has_timestamp_ms() const { return (_has_bits_[0] & 0x00000040u) != 0; } inline void Metric::set_has_timestamp_ms() { _has_bits_[0] |= 0x00000040u; } inline void Metric::clear_has_timestamp_ms() { _has_bits_[0] &= ~0x00000040u; } inline void Metric::clear_timestamp_ms() { timestamp_ms_ = GOOGLE_LONGLONG(0); clear_has_timestamp_ms(); } inline ::google::protobuf::int64 Metric::timestamp_ms() const { // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.timestamp_ms) return timestamp_ms_; } inline void Metric::set_timestamp_ms(::google::protobuf::int64 value) { set_has_timestamp_ms(); timestamp_ms_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.Metric.timestamp_ms) } // ------------------------------------------------------------------- // MetricFamily // optional string name = 1; inline bool MetricFamily::has_name() const { return (_has_bits_[0] & 0x00000001u) != 0; } inline void MetricFamily::set_has_name() { _has_bits_[0] |= 0x00000001u; } inline void MetricFamily::clear_has_name() { _has_bits_[0] &= ~0x00000001u; } inline void MetricFamily::clear_name() { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_->clear(); } clear_has_name(); } inline const ::std::string& MetricFamily::name() const { // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.name) return *name_; } inline void MetricFamily::set_name(const ::std::string& value) { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } name_->assign(value); // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.name) } inline void MetricFamily::set_name(const char* value) { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } name_->assign(value); // @@protoc_insertion_point(field_set_char:io.prometheus.client.MetricFamily.name) } inline void MetricFamily::set_name(const char* value, size_t size) { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } name_->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.MetricFamily.name) } inline ::std::string* MetricFamily::mutable_name() { set_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { name_ = new ::std::string; } // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.name) return name_; } inline ::std::string* MetricFamily::release_name() { clear_has_name(); if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { return NULL; } else { ::std::string* temp = name_; name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); return temp; } } inline void MetricFamily::set_allocated_name(::std::string* name) { if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete name_; } if (name) { set_has_name(); name_ = name; } else { clear_has_name(); name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.MetricFamily.name) } // optional string help = 2; inline bool MetricFamily::has_help() const { return (_has_bits_[0] & 0x00000002u) != 0; } inline void MetricFamily::set_has_help() { _has_bits_[0] |= 0x00000002u; } inline void MetricFamily::clear_has_help() { _has_bits_[0] &= ~0x00000002u; } inline void MetricFamily::clear_help() { if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { help_->clear(); } clear_has_help(); } inline const ::std::string& MetricFamily::help() const { // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.help) return *help_; } inline void MetricFamily::set_help(const ::std::string& value) { set_has_help(); if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { help_ = new ::std::string; } help_->assign(value); // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.help) } inline void MetricFamily::set_help(const char* value) { set_has_help(); if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { help_ = new ::std::string; } help_->assign(value); // @@protoc_insertion_point(field_set_char:io.prometheus.client.MetricFamily.help) } inline void MetricFamily::set_help(const char* value, size_t size) { set_has_help(); if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { help_ = new ::std::string; } help_->assign(reinterpret_cast(value), size); // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.MetricFamily.help) } inline ::std::string* MetricFamily::mutable_help() { set_has_help(); if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { help_ = new ::std::string; } // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.help) return help_; } inline ::std::string* MetricFamily::release_help() { clear_has_help(); if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { return NULL; } else { ::std::string* temp = help_; help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); return temp; } } inline void MetricFamily::set_allocated_help(::std::string* help) { if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) { delete help_; } if (help) { set_has_help(); help_ = help; } else { clear_has_help(); help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.MetricFamily.help) } // optional .io.prometheus.client.MetricType type = 3; inline bool MetricFamily::has_type() const { return (_has_bits_[0] & 0x00000004u) != 0; } inline void MetricFamily::set_has_type() { _has_bits_[0] |= 0x00000004u; } inline void MetricFamily::clear_has_type() { _has_bits_[0] &= ~0x00000004u; } inline void MetricFamily::clear_type() { type_ = 0; clear_has_type(); } inline ::io::prometheus::client::MetricType MetricFamily::type() const { // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.type) return static_cast< ::io::prometheus::client::MetricType >(type_); } inline void MetricFamily::set_type(::io::prometheus::client::MetricType value) { assert(::io::prometheus::client::MetricType_IsValid(value)); set_has_type(); type_ = value; // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.type) } // repeated .io.prometheus.client.Metric metric = 4; inline int MetricFamily::metric_size() const { return metric_.size(); } inline void MetricFamily::clear_metric() { metric_.Clear(); } inline const ::io::prometheus::client::Metric& MetricFamily::metric(int index) const { // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.metric) return metric_.Get(index); } inline ::io::prometheus::client::Metric* MetricFamily::mutable_metric(int index) { // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.metric) return metric_.Mutable(index); } inline ::io::prometheus::client::Metric* MetricFamily::add_metric() { // @@protoc_insertion_point(field_add:io.prometheus.client.MetricFamily.metric) return metric_.Add(); } inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >& MetricFamily::metric() const { // @@protoc_insertion_point(field_list:io.prometheus.client.MetricFamily.metric) return metric_; } inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >* MetricFamily::mutable_metric() { // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.MetricFamily.metric) return &metric_; } // @@protoc_insertion_point(namespace_scope) } // namespace client } // namespace prometheus } // namespace io #ifndef SWIG namespace google { namespace protobuf { template <> struct is_proto_enum< ::io::prometheus::client::MetricType> : ::google::protobuf::internal::true_type {}; template <> inline const EnumDescriptor* GetEnumDescriptor< ::io::prometheus::client::MetricType>() { return ::io::prometheus::client::MetricType_descriptor(); } } // namespace google } // namespace protobuf #endif // SWIG // @@protoc_insertion_point(global_scope) #endif // PROTOBUF_metrics_2eproto__INCLUDED ================================================ FILE: vendor/github.com/prometheus/client_model/go/metrics.pb.go ================================================ // 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) } ================================================ FILE: vendor/github.com/prometheus/client_model/metrics.proto ================================================ // Copyright 2013 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. syntax = "proto2"; package io.prometheus.client; option java_package = "io.prometheus.client"; message LabelPair { optional string name = 1; optional string value = 2; } enum MetricType { COUNTER = 0; GAUGE = 1; SUMMARY = 2; UNTYPED = 3; HISTOGRAM = 4; } message Gauge { optional double value = 1; } message Counter { optional double value = 1; } message Quantile { optional double quantile = 1; optional double value = 2; } message Summary { optional uint64 sample_count = 1; optional double sample_sum = 2; repeated Quantile quantile = 3; } message Untyped { optional double value = 1; } message Histogram { optional uint64 sample_count = 1; optional double sample_sum = 2; repeated Bucket bucket = 3; // Ordered in increasing order of upper_bound, +Inf bucket is optional. } message Bucket { optional uint64 cumulative_count = 1; // Cumulative in increasing order. optional double upper_bound = 2; // Inclusive. } message Metric { repeated LabelPair label = 1; optional Gauge gauge = 2; optional Counter counter = 3; optional Summary summary = 4; optional Untyped untyped = 5; optional Histogram histogram = 7; optional int64 timestamp_ms = 6; } message MetricFamily { optional string name = 1; optional string help = 2; optional MetricType type = 3; repeated Metric metric = 4; } ================================================ FILE: vendor/github.com/prometheus/client_model/pom.xml ================================================ 4.0.0 io.prometheus.client model 0.0.3-SNAPSHOT org.sonatype.oss oss-parent 7 Prometheus Client Data Model http://github.com/prometheus/client_model Prometheus Client Data Model: Generated Protocol Buffer Assets The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo scm:git:git@github.com:prometheus/client_model.git scm:git:git@github.com:prometheus/client_model.git git@github.com:prometheus/client_model.git mtp Matt T. Proud matt.proud@gmail.com com.google.protobuf protobuf-java 2.5.0 org.apache.maven.plugins maven-javadoc-plugin 2.8 UTF-8 UTF-8 true generate-javadoc-site-report site javadoc attach-javadocs jar maven-compiler-plugin 1.6 1.6 3.1 org.apache.maven.plugins maven-source-plugin 2.2.1 attach-sources jar release-sign-artifacts performRelease true org.apache.maven.plugins maven-gpg-plugin 1.4 sign-artifacts verify sign ================================================ FILE: vendor/github.com/prometheus/client_model/python/prometheus/__init__.py ================================================ # Copyright 2013 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. ================================================ FILE: vendor/github.com/prometheus/client_model/python/prometheus/client/__init__.py ================================================ # Copyright 2013 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. ================================================ FILE: vendor/github.com/prometheus/client_model/python/prometheus/client/model/__init__.py ================================================ # Copyright 2013 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. __all__ = ['metrics_pb2'] ================================================ FILE: vendor/github.com/prometheus/client_model/python/prometheus/client/model/metrics_pb2.py ================================================ # Generated by the protocol buffer compiler. DO NOT EDIT! # source: metrics.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='metrics.proto', package='io.prometheus.client', serialized_pb=_b('\n\rmetrics.proto\x12\x14io.prometheus.client\"(\n\tLabelPair\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\"\x16\n\x05Gauge\x12\r\n\x05value\x18\x01 \x01(\x01\"\x18\n\x07\x43ounter\x12\r\n\x05value\x18\x01 \x01(\x01\"+\n\x08Quantile\x12\x10\n\x08quantile\x18\x01 \x01(\x01\x12\r\n\x05value\x18\x02 \x01(\x01\"e\n\x07Summary\x12\x14\n\x0csample_count\x18\x01 \x01(\x04\x12\x12\n\nsample_sum\x18\x02 \x01(\x01\x12\x30\n\x08quantile\x18\x03 \x03(\x0b\x32\x1e.io.prometheus.client.Quantile\"\x18\n\x07Untyped\x12\r\n\x05value\x18\x01 \x01(\x01\"c\n\tHistogram\x12\x14\n\x0csample_count\x18\x01 \x01(\x04\x12\x12\n\nsample_sum\x18\x02 \x01(\x01\x12,\n\x06\x62ucket\x18\x03 \x03(\x0b\x32\x1c.io.prometheus.client.Bucket\"7\n\x06\x42ucket\x12\x18\n\x10\x63umulative_count\x18\x01 \x01(\x04\x12\x13\n\x0bupper_bound\x18\x02 \x01(\x01\"\xbe\x02\n\x06Metric\x12.\n\x05label\x18\x01 \x03(\x0b\x32\x1f.io.prometheus.client.LabelPair\x12*\n\x05gauge\x18\x02 \x01(\x0b\x32\x1b.io.prometheus.client.Gauge\x12.\n\x07\x63ounter\x18\x03 \x01(\x0b\x32\x1d.io.prometheus.client.Counter\x12.\n\x07summary\x18\x04 \x01(\x0b\x32\x1d.io.prometheus.client.Summary\x12.\n\x07untyped\x18\x05 \x01(\x0b\x32\x1d.io.prometheus.client.Untyped\x12\x32\n\thistogram\x18\x07 \x01(\x0b\x32\x1f.io.prometheus.client.Histogram\x12\x14\n\x0ctimestamp_ms\x18\x06 \x01(\x03\"\x88\x01\n\x0cMetricFamily\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04help\x18\x02 \x01(\t\x12.\n\x04type\x18\x03 \x01(\x0e\x32 .io.prometheus.client.MetricType\x12,\n\x06metric\x18\x04 \x03(\x0b\x32\x1c.io.prometheus.client.Metric*M\n\nMetricType\x12\x0b\n\x07\x43OUNTER\x10\x00\x12\t\n\x05GAUGE\x10\x01\x12\x0b\n\x07SUMMARY\x10\x02\x12\x0b\n\x07UNTYPED\x10\x03\x12\r\n\tHISTOGRAM\x10\x04\x42\x16\n\x14io.prometheus.client') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _METRICTYPE = _descriptor.EnumDescriptor( name='MetricType', full_name='io.prometheus.client.MetricType', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='COUNTER', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='GAUGE', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='SUMMARY', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='UNTYPED', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='HISTOGRAM', index=4, number=4, options=None, type=None), ], containing_type=None, options=None, serialized_start=923, serialized_end=1000, ) _sym_db.RegisterEnumDescriptor(_METRICTYPE) MetricType = enum_type_wrapper.EnumTypeWrapper(_METRICTYPE) COUNTER = 0 GAUGE = 1 SUMMARY = 2 UNTYPED = 3 HISTOGRAM = 4 _LABELPAIR = _descriptor.Descriptor( name='LabelPair', full_name='io.prometheus.client.LabelPair', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='io.prometheus.client.LabelPair.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='value', full_name='io.prometheus.client.LabelPair.value', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=39, serialized_end=79, ) _GAUGE = _descriptor.Descriptor( name='Gauge', full_name='io.prometheus.client.Gauge', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='value', full_name='io.prometheus.client.Gauge.value', index=0, number=1, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=81, serialized_end=103, ) _COUNTER = _descriptor.Descriptor( name='Counter', full_name='io.prometheus.client.Counter', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='value', full_name='io.prometheus.client.Counter.value', index=0, number=1, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=105, serialized_end=129, ) _QUANTILE = _descriptor.Descriptor( name='Quantile', full_name='io.prometheus.client.Quantile', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='quantile', full_name='io.prometheus.client.Quantile.quantile', index=0, number=1, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='value', full_name='io.prometheus.client.Quantile.value', index=1, number=2, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=131, serialized_end=174, ) _SUMMARY = _descriptor.Descriptor( name='Summary', full_name='io.prometheus.client.Summary', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='sample_count', full_name='io.prometheus.client.Summary.sample_count', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='sample_sum', full_name='io.prometheus.client.Summary.sample_sum', index=1, number=2, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='quantile', full_name='io.prometheus.client.Summary.quantile', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=176, serialized_end=277, ) _UNTYPED = _descriptor.Descriptor( name='Untyped', full_name='io.prometheus.client.Untyped', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='value', full_name='io.prometheus.client.Untyped.value', index=0, number=1, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=279, serialized_end=303, ) _HISTOGRAM = _descriptor.Descriptor( name='Histogram', full_name='io.prometheus.client.Histogram', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='sample_count', full_name='io.prometheus.client.Histogram.sample_count', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='sample_sum', full_name='io.prometheus.client.Histogram.sample_sum', index=1, number=2, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='bucket', full_name='io.prometheus.client.Histogram.bucket', index=2, number=3, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=305, serialized_end=404, ) _BUCKET = _descriptor.Descriptor( name='Bucket', full_name='io.prometheus.client.Bucket', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='cumulative_count', full_name='io.prometheus.client.Bucket.cumulative_count', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='upper_bound', full_name='io.prometheus.client.Bucket.upper_bound', index=1, number=2, type=1, cpp_type=5, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=406, serialized_end=461, ) _METRIC = _descriptor.Descriptor( name='Metric', full_name='io.prometheus.client.Metric', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='label', full_name='io.prometheus.client.Metric.label', index=0, number=1, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='gauge', full_name='io.prometheus.client.Metric.gauge', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='counter', full_name='io.prometheus.client.Metric.counter', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='summary', full_name='io.prometheus.client.Metric.summary', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='untyped', full_name='io.prometheus.client.Metric.untyped', index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='histogram', full_name='io.prometheus.client.Metric.histogram', index=5, number=7, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='timestamp_ms', full_name='io.prometheus.client.Metric.timestamp_ms', index=6, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=464, serialized_end=782, ) _METRICFAMILY = _descriptor.Descriptor( name='MetricFamily', full_name='io.prometheus.client.MetricFamily', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='name', full_name='io.prometheus.client.MetricFamily.name', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='help', full_name='io.prometheus.client.MetricFamily.help', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='type', full_name='io.prometheus.client.MetricFamily.type', index=2, number=3, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='metric', full_name='io.prometheus.client.MetricFamily.metric', index=3, number=4, type=11, cpp_type=10, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, extension_ranges=[], oneofs=[ ], serialized_start=785, serialized_end=921, ) _SUMMARY.fields_by_name['quantile'].message_type = _QUANTILE _HISTOGRAM.fields_by_name['bucket'].message_type = _BUCKET _METRIC.fields_by_name['label'].message_type = _LABELPAIR _METRIC.fields_by_name['gauge'].message_type = _GAUGE _METRIC.fields_by_name['counter'].message_type = _COUNTER _METRIC.fields_by_name['summary'].message_type = _SUMMARY _METRIC.fields_by_name['untyped'].message_type = _UNTYPED _METRIC.fields_by_name['histogram'].message_type = _HISTOGRAM _METRICFAMILY.fields_by_name['type'].enum_type = _METRICTYPE _METRICFAMILY.fields_by_name['metric'].message_type = _METRIC DESCRIPTOR.message_types_by_name['LabelPair'] = _LABELPAIR DESCRIPTOR.message_types_by_name['Gauge'] = _GAUGE DESCRIPTOR.message_types_by_name['Counter'] = _COUNTER DESCRIPTOR.message_types_by_name['Quantile'] = _QUANTILE DESCRIPTOR.message_types_by_name['Summary'] = _SUMMARY DESCRIPTOR.message_types_by_name['Untyped'] = _UNTYPED DESCRIPTOR.message_types_by_name['Histogram'] = _HISTOGRAM DESCRIPTOR.message_types_by_name['Bucket'] = _BUCKET DESCRIPTOR.message_types_by_name['Metric'] = _METRIC DESCRIPTOR.message_types_by_name['MetricFamily'] = _METRICFAMILY DESCRIPTOR.enum_types_by_name['MetricType'] = _METRICTYPE LabelPair = _reflection.GeneratedProtocolMessageType('LabelPair', (_message.Message,), dict( DESCRIPTOR = _LABELPAIR, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair) )) _sym_db.RegisterMessage(LabelPair) Gauge = _reflection.GeneratedProtocolMessageType('Gauge', (_message.Message,), dict( DESCRIPTOR = _GAUGE, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge) )) _sym_db.RegisterMessage(Gauge) Counter = _reflection.GeneratedProtocolMessageType('Counter', (_message.Message,), dict( DESCRIPTOR = _COUNTER, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Counter) )) _sym_db.RegisterMessage(Counter) Quantile = _reflection.GeneratedProtocolMessageType('Quantile', (_message.Message,), dict( DESCRIPTOR = _QUANTILE, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile) )) _sym_db.RegisterMessage(Quantile) Summary = _reflection.GeneratedProtocolMessageType('Summary', (_message.Message,), dict( DESCRIPTOR = _SUMMARY, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Summary) )) _sym_db.RegisterMessage(Summary) Untyped = _reflection.GeneratedProtocolMessageType('Untyped', (_message.Message,), dict( DESCRIPTOR = _UNTYPED, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped) )) _sym_db.RegisterMessage(Untyped) Histogram = _reflection.GeneratedProtocolMessageType('Histogram', (_message.Message,), dict( DESCRIPTOR = _HISTOGRAM, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram) )) _sym_db.RegisterMessage(Histogram) Bucket = _reflection.GeneratedProtocolMessageType('Bucket', (_message.Message,), dict( DESCRIPTOR = _BUCKET, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket) )) _sym_db.RegisterMessage(Bucket) Metric = _reflection.GeneratedProtocolMessageType('Metric', (_message.Message,), dict( DESCRIPTOR = _METRIC, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.Metric) )) _sym_db.RegisterMessage(Metric) MetricFamily = _reflection.GeneratedProtocolMessageType('MetricFamily', (_message.Message,), dict( DESCRIPTOR = _METRICFAMILY, __module__ = 'metrics_pb2' # @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily) )) _sym_db.RegisterMessage(MetricFamily) DESCRIPTOR.has_options = True DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\024io.prometheus.client')) # @@protoc_insertion_point(module_scope) ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/.gitignore ================================================ *.gem .bundle Gemfile.lock pkg vendor/bundle ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/Gemfile ================================================ source 'https://rubygems.org' # Specify your gem's dependencies in prometheus-client-model.gemspec gemspec ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/Makefile ================================================ VENDOR_BUNDLE = vendor/bundle build: $(VENDOR_BUNDLE)/.bundled BEEFCAKE_NAMESPACE=Prometheus::Client protoc --beefcake_out lib/prometheus/client/model -I .. ../metrics.proto $(VENDOR_BUNDLE): mkdir -p $@ $(VENDOR_BUNDLE)/.bundled: $(VENDOR_BUNDLE) Gemfile bundle install --quiet --path $< @touch $@ clean: -rm -f lib/prometheus/client/model/metrics.pb.rb -rm -rf $(VENDOR_BUNDLE) .PHONY: build clean ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/README.md ================================================ # Prometheus Ruby client model Data model artifacts for the [Prometheus Ruby client][1]. ## Installation gem install prometheus-client-model ## Usage Build the artifacts from the protobuf specification: make build While this Gem's main purpose is to define the Prometheus data types for the [client][1], it's possible to use it without the client to decode a stream of delimited protobuf messages: ```ruby require 'open-uri' require 'prometheus/client/model' CONTENT_TYPE = 'application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited' stream = open('http://localhost:9090/metrics', 'Accept' => CONTENT_TYPE).read while family = Prometheus::Client::MetricFamily.read_delimited(stream) puts family end ``` [1]: https://github.com/prometheus/client_ruby ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/Rakefile ================================================ require "bundler/gem_tasks" ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/metrics.pb.rb ================================================ ## Generated from metrics.proto for io.prometheus.client require "beefcake" module Prometheus module Client module MetricType COUNTER = 0 GAUGE = 1 SUMMARY = 2 UNTYPED = 3 HISTOGRAM = 4 end class LabelPair include Beefcake::Message end class Gauge include Beefcake::Message end class Counter include Beefcake::Message end class Quantile include Beefcake::Message end class Summary include Beefcake::Message end class Untyped include Beefcake::Message end class Histogram include Beefcake::Message end class Bucket include Beefcake::Message end class Metric include Beefcake::Message end class MetricFamily include Beefcake::Message end class LabelPair optional :name, :string, 1 optional :value, :string, 2 end class Gauge optional :value, :double, 1 end class Counter optional :value, :double, 1 end class Quantile optional :quantile, :double, 1 optional :value, :double, 2 end class Summary optional :sample_count, :uint64, 1 optional :sample_sum, :double, 2 repeated :quantile, Quantile, 3 end class Untyped optional :value, :double, 1 end class Histogram optional :sample_count, :uint64, 1 optional :sample_sum, :double, 2 repeated :bucket, Bucket, 3 end class Bucket optional :cumulative_count, :uint64, 1 optional :upper_bound, :double, 2 end class Metric repeated :label, LabelPair, 1 optional :gauge, Gauge, 2 optional :counter, Counter, 3 optional :summary, Summary, 4 optional :untyped, Untyped, 5 optional :histogram, Histogram, 7 optional :timestamp_ms, :int64, 6 end class MetricFamily optional :name, :string, 1 optional :help, :string, 2 optional :type, MetricType, 3 repeated :metric, Metric, 4 end end end ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/version.rb ================================================ module Prometheus module Client module Model VERSION = '0.1.0' end end end ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model.rb ================================================ require 'prometheus/client/model/metrics.pb' require 'prometheus/client/model/version' ================================================ FILE: vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec ================================================ # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'prometheus/client/model/version' Gem::Specification.new do |spec| spec.name = 'prometheus-client-model' spec.version = Prometheus::Client::Model::VERSION spec.authors = ['Tobias Schmidt'] spec.email = ['tobidt@gmail.com'] spec.summary = 'Data model artifacts for the Prometheus Ruby client' spec.homepage = 'https://github.com/prometheus/client_model/tree/master/ruby' spec.license = 'Apache 2.0' spec.files = %w[README.md LICENSE] + Dir.glob('{lib/**/*}') spec.require_paths = ['lib'] spec.add_dependency 'beefcake', '>= 0.4.0' spec.add_development_dependency 'bundler', '~> 1.3' spec.add_development_dependency 'rake' end ================================================ FILE: vendor/github.com/prometheus/client_model/setup.py ================================================ #!/usr/bin/python from setuptools import setup setup( name = 'prometheus_client_model', version = '0.0.1', author = 'Matt T. Proud', author_email = 'matt.proud@gmail.com', description = 'Data model artifacts for the Prometheus client.', license = 'Apache License 2.0', url = 'http://github.com/prometheus/client_model', packages = ['prometheus', 'prometheus/client', 'prometheus/client/model'], package_dir = {'': 'python'}, requires = ['protobuf(==2.4.1)'], platforms = 'Platform Independent', classifiers = ['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Testing', 'Topic :: System :: Monitoring']) ================================================ FILE: vendor/github.com/prometheus/client_model/src/main/java/io/prometheus/client/Metrics.java ================================================ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: metrics.proto package io.prometheus.client; public final class Metrics { private Metrics() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } /** * Protobuf enum {@code io.prometheus.client.MetricType} */ public enum MetricType implements com.google.protobuf.ProtocolMessageEnum { /** * COUNTER = 0; */ COUNTER(0, 0), /** * GAUGE = 1; */ GAUGE(1, 1), /** * SUMMARY = 2; */ SUMMARY(2, 2), /** * UNTYPED = 3; */ UNTYPED(3, 3), /** * HISTOGRAM = 4; */ HISTOGRAM(4, 4), ; /** * COUNTER = 0; */ public static final int COUNTER_VALUE = 0; /** * GAUGE = 1; */ public static final int GAUGE_VALUE = 1; /** * SUMMARY = 2; */ public static final int SUMMARY_VALUE = 2; /** * UNTYPED = 3; */ public static final int UNTYPED_VALUE = 3; /** * HISTOGRAM = 4; */ public static final int HISTOGRAM_VALUE = 4; public final int getNumber() { return value; } public static MetricType valueOf(int value) { switch (value) { case 0: return COUNTER; case 1: return GAUGE; case 2: return SUMMARY; case 3: return UNTYPED; case 4: return HISTOGRAM; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { return internalValueMap; } private static com.google.protobuf.Internal.EnumLiteMap internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { public MetricType findValueByNumber(int number) { return MetricType.valueOf(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return io.prometheus.client.Metrics.getDescriptor().getEnumTypes().get(0); } private static final MetricType[] VALUES = values(); public static MetricType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private MetricType(int index, int value) { this.index = index; this.value = value; } // @@protoc_insertion_point(enum_scope:io.prometheus.client.MetricType) } public interface LabelPairOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.LabelPair) com.google.protobuf.MessageOrBuilder { /** * optional string name = 1; */ boolean hasName(); /** * optional string name = 1; */ java.lang.String getName(); /** * optional string name = 1; */ com.google.protobuf.ByteString getNameBytes(); /** * optional string value = 2; */ boolean hasValue(); /** * optional string value = 2; */ java.lang.String getValue(); /** * optional string value = 2; */ com.google.protobuf.ByteString getValueBytes(); } /** * Protobuf type {@code io.prometheus.client.LabelPair} */ public static final class LabelPair extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.LabelPair) LabelPairOrBuilder { // Use LabelPair.newBuilder() to construct. private LabelPair(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private LabelPair(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final LabelPair defaultInstance; public static LabelPair getDefaultInstance() { return defaultInstance; } public LabelPair getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private LabelPair( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000001; name_ = bs; break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; value_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.LabelPair.class, io.prometheus.client.Metrics.LabelPair.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public LabelPair parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new LabelPair(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private java.lang.Object name_; /** * optional string name = 1; */ public boolean hasName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional string name = 1; */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * optional string name = 1; */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int VALUE_FIELD_NUMBER = 2; private java.lang.Object value_; /** * optional string value = 2; */ public boolean hasValue() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional string value = 2; */ public java.lang.String getValue() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { value_ = s; } return s; } } /** * optional string value = 2; */ public com.google.protobuf.ByteString getValueBytes() { java.lang.Object ref = value_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { name_ = ""; value_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getValueBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getValueBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.LabelPair parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.LabelPair parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.LabelPair parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.LabelPair parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.LabelPair parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.LabelPair parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.LabelPair parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.LabelPair parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.LabelPair parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.LabelPair parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.LabelPair prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.LabelPair} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.LabelPair) io.prometheus.client.Metrics.LabelPairOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.LabelPair.class, io.prometheus.client.Metrics.LabelPair.Builder.class); } // Construct using io.prometheus.client.Metrics.LabelPair.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); name_ = ""; bitField0_ = (bitField0_ & ~0x00000001); value_ = ""; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_descriptor; } public io.prometheus.client.Metrics.LabelPair getDefaultInstanceForType() { return io.prometheus.client.Metrics.LabelPair.getDefaultInstance(); } public io.prometheus.client.Metrics.LabelPair build() { io.prometheus.client.Metrics.LabelPair result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.LabelPair buildPartial() { io.prometheus.client.Metrics.LabelPair result = new io.prometheus.client.Metrics.LabelPair(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.name_ = name_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.value_ = value_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.LabelPair) { return mergeFrom((io.prometheus.client.Metrics.LabelPair)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.LabelPair other) { if (other == io.prometheus.client.Metrics.LabelPair.getDefaultInstance()) return this; if (other.hasName()) { bitField0_ |= 0x00000001; name_ = other.name_; onChanged(); } if (other.hasValue()) { bitField0_ |= 0x00000002; value_ = other.value_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.LabelPair parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.LabelPair) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * optional string name = 1; */ public boolean hasName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional string name = 1; */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } else { return (java.lang.String) ref; } } /** * optional string name = 1; */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string name = 1; */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; name_ = value; onChanged(); return this; } /** * optional string name = 1; */ public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000001); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * optional string name = 1; */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; name_ = value; onChanged(); return this; } private java.lang.Object value_ = ""; /** * optional string value = 2; */ public boolean hasValue() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional string value = 2; */ public java.lang.String getValue() { java.lang.Object ref = value_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { value_ = s; } return s; } else { return (java.lang.String) ref; } } /** * optional string value = 2; */ public com.google.protobuf.ByteString getValueBytes() { java.lang.Object ref = value_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); value_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string value = 2; */ public Builder setValue( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; value_ = value; onChanged(); return this; } /** * optional string value = 2; */ public Builder clearValue() { bitField0_ = (bitField0_ & ~0x00000002); value_ = getDefaultInstance().getValue(); onChanged(); return this; } /** * optional string value = 2; */ public Builder setValueBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; value_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.LabelPair) } static { defaultInstance = new LabelPair(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair) } public interface GaugeOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Gauge) com.google.protobuf.MessageOrBuilder { /** * optional double value = 1; */ boolean hasValue(); /** * optional double value = 1; */ double getValue(); } /** * Protobuf type {@code io.prometheus.client.Gauge} */ public static final class Gauge extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Gauge) GaugeOrBuilder { // Use Gauge.newBuilder() to construct. private Gauge(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Gauge(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Gauge defaultInstance; public static Gauge getDefaultInstance() { return defaultInstance; } public Gauge getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Gauge( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 9: { bitField0_ |= 0x00000001; value_ = input.readDouble(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Gauge.class, io.prometheus.client.Metrics.Gauge.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Gauge parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Gauge(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int VALUE_FIELD_NUMBER = 1; private double value_; /** * optional double value = 1; */ public boolean hasValue() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double value = 1; */ public double getValue() { return value_; } private void initFields() { value_ = 0D; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeDouble(1, value_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(1, value_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Gauge parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Gauge parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Gauge parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Gauge parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Gauge parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Gauge parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Gauge parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Gauge parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Gauge parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Gauge parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Gauge prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Gauge} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Gauge) io.prometheus.client.Metrics.GaugeOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Gauge.class, io.prometheus.client.Metrics.Gauge.Builder.class); } // Construct using io.prometheus.client.Metrics.Gauge.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); value_ = 0D; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_descriptor; } public io.prometheus.client.Metrics.Gauge getDefaultInstanceForType() { return io.prometheus.client.Metrics.Gauge.getDefaultInstance(); } public io.prometheus.client.Metrics.Gauge build() { io.prometheus.client.Metrics.Gauge result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Gauge buildPartial() { io.prometheus.client.Metrics.Gauge result = new io.prometheus.client.Metrics.Gauge(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.value_ = value_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Gauge) { return mergeFrom((io.prometheus.client.Metrics.Gauge)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Gauge other) { if (other == io.prometheus.client.Metrics.Gauge.getDefaultInstance()) return this; if (other.hasValue()) { setValue(other.getValue()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Gauge parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Gauge) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private double value_ ; /** * optional double value = 1; */ public boolean hasValue() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double value = 1; */ public double getValue() { return value_; } /** * optional double value = 1; */ public Builder setValue(double value) { bitField0_ |= 0x00000001; value_ = value; onChanged(); return this; } /** * optional double value = 1; */ public Builder clearValue() { bitField0_ = (bitField0_ & ~0x00000001); value_ = 0D; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Gauge) } static { defaultInstance = new Gauge(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge) } public interface CounterOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Counter) com.google.protobuf.MessageOrBuilder { /** * optional double value = 1; */ boolean hasValue(); /** * optional double value = 1; */ double getValue(); } /** * Protobuf type {@code io.prometheus.client.Counter} */ public static final class Counter extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Counter) CounterOrBuilder { // Use Counter.newBuilder() to construct. private Counter(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Counter(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Counter defaultInstance; public static Counter getDefaultInstance() { return defaultInstance; } public Counter getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Counter( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 9: { bitField0_ |= 0x00000001; value_ = input.readDouble(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Counter.class, io.prometheus.client.Metrics.Counter.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Counter parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Counter(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int VALUE_FIELD_NUMBER = 1; private double value_; /** * optional double value = 1; */ public boolean hasValue() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double value = 1; */ public double getValue() { return value_; } private void initFields() { value_ = 0D; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeDouble(1, value_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(1, value_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Counter parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Counter parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Counter parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Counter parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Counter parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Counter parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Counter parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Counter parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Counter parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Counter parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Counter prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Counter} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Counter) io.prometheus.client.Metrics.CounterOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Counter.class, io.prometheus.client.Metrics.Counter.Builder.class); } // Construct using io.prometheus.client.Metrics.Counter.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); value_ = 0D; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_descriptor; } public io.prometheus.client.Metrics.Counter getDefaultInstanceForType() { return io.prometheus.client.Metrics.Counter.getDefaultInstance(); } public io.prometheus.client.Metrics.Counter build() { io.prometheus.client.Metrics.Counter result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Counter buildPartial() { io.prometheus.client.Metrics.Counter result = new io.prometheus.client.Metrics.Counter(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.value_ = value_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Counter) { return mergeFrom((io.prometheus.client.Metrics.Counter)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Counter other) { if (other == io.prometheus.client.Metrics.Counter.getDefaultInstance()) return this; if (other.hasValue()) { setValue(other.getValue()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Counter parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Counter) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private double value_ ; /** * optional double value = 1; */ public boolean hasValue() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double value = 1; */ public double getValue() { return value_; } /** * optional double value = 1; */ public Builder setValue(double value) { bitField0_ |= 0x00000001; value_ = value; onChanged(); return this; } /** * optional double value = 1; */ public Builder clearValue() { bitField0_ = (bitField0_ & ~0x00000001); value_ = 0D; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Counter) } static { defaultInstance = new Counter(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Counter) } public interface QuantileOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Quantile) com.google.protobuf.MessageOrBuilder { /** * optional double quantile = 1; */ boolean hasQuantile(); /** * optional double quantile = 1; */ double getQuantile(); /** * optional double value = 2; */ boolean hasValue(); /** * optional double value = 2; */ double getValue(); } /** * Protobuf type {@code io.prometheus.client.Quantile} */ public static final class Quantile extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Quantile) QuantileOrBuilder { // Use Quantile.newBuilder() to construct. private Quantile(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Quantile(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Quantile defaultInstance; public static Quantile getDefaultInstance() { return defaultInstance; } public Quantile getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Quantile( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 9: { bitField0_ |= 0x00000001; quantile_ = input.readDouble(); break; } case 17: { bitField0_ |= 0x00000002; value_ = input.readDouble(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Quantile.class, io.prometheus.client.Metrics.Quantile.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Quantile parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Quantile(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int QUANTILE_FIELD_NUMBER = 1; private double quantile_; /** * optional double quantile = 1; */ public boolean hasQuantile() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double quantile = 1; */ public double getQuantile() { return quantile_; } public static final int VALUE_FIELD_NUMBER = 2; private double value_; /** * optional double value = 2; */ public boolean hasValue() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double value = 2; */ public double getValue() { return value_; } private void initFields() { quantile_ = 0D; value_ = 0D; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeDouble(1, quantile_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeDouble(2, value_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(1, quantile_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(2, value_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Quantile parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Quantile parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Quantile parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Quantile parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Quantile parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Quantile parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Quantile parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Quantile parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Quantile parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Quantile parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Quantile prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Quantile} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Quantile) io.prometheus.client.Metrics.QuantileOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Quantile.class, io.prometheus.client.Metrics.Quantile.Builder.class); } // Construct using io.prometheus.client.Metrics.Quantile.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); quantile_ = 0D; bitField0_ = (bitField0_ & ~0x00000001); value_ = 0D; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_descriptor; } public io.prometheus.client.Metrics.Quantile getDefaultInstanceForType() { return io.prometheus.client.Metrics.Quantile.getDefaultInstance(); } public io.prometheus.client.Metrics.Quantile build() { io.prometheus.client.Metrics.Quantile result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Quantile buildPartial() { io.prometheus.client.Metrics.Quantile result = new io.prometheus.client.Metrics.Quantile(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.quantile_ = quantile_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.value_ = value_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Quantile) { return mergeFrom((io.prometheus.client.Metrics.Quantile)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Quantile other) { if (other == io.prometheus.client.Metrics.Quantile.getDefaultInstance()) return this; if (other.hasQuantile()) { setQuantile(other.getQuantile()); } if (other.hasValue()) { setValue(other.getValue()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Quantile parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Quantile) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private double quantile_ ; /** * optional double quantile = 1; */ public boolean hasQuantile() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double quantile = 1; */ public double getQuantile() { return quantile_; } /** * optional double quantile = 1; */ public Builder setQuantile(double value) { bitField0_ |= 0x00000001; quantile_ = value; onChanged(); return this; } /** * optional double quantile = 1; */ public Builder clearQuantile() { bitField0_ = (bitField0_ & ~0x00000001); quantile_ = 0D; onChanged(); return this; } private double value_ ; /** * optional double value = 2; */ public boolean hasValue() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double value = 2; */ public double getValue() { return value_; } /** * optional double value = 2; */ public Builder setValue(double value) { bitField0_ |= 0x00000002; value_ = value; onChanged(); return this; } /** * optional double value = 2; */ public Builder clearValue() { bitField0_ = (bitField0_ & ~0x00000002); value_ = 0D; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Quantile) } static { defaultInstance = new Quantile(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile) } public interface SummaryOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Summary) com.google.protobuf.MessageOrBuilder { /** * optional uint64 sample_count = 1; */ boolean hasSampleCount(); /** * optional uint64 sample_count = 1; */ long getSampleCount(); /** * optional double sample_sum = 2; */ boolean hasSampleSum(); /** * optional double sample_sum = 2; */ double getSampleSum(); /** * repeated .io.prometheus.client.Quantile quantile = 3; */ java.util.List getQuantileList(); /** * repeated .io.prometheus.client.Quantile quantile = 3; */ io.prometheus.client.Metrics.Quantile getQuantile(int index); /** * repeated .io.prometheus.client.Quantile quantile = 3; */ int getQuantileCount(); /** * repeated .io.prometheus.client.Quantile quantile = 3; */ java.util.List getQuantileOrBuilderList(); /** * repeated .io.prometheus.client.Quantile quantile = 3; */ io.prometheus.client.Metrics.QuantileOrBuilder getQuantileOrBuilder( int index); } /** * Protobuf type {@code io.prometheus.client.Summary} */ public static final class Summary extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Summary) SummaryOrBuilder { // Use Summary.newBuilder() to construct. private Summary(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Summary(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Summary defaultInstance; public static Summary getDefaultInstance() { return defaultInstance; } public Summary getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Summary( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; sampleCount_ = input.readUInt64(); break; } case 17: { bitField0_ |= 0x00000002; sampleSum_ = input.readDouble(); break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { quantile_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000004; } quantile_.add(input.readMessage(io.prometheus.client.Metrics.Quantile.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { quantile_ = java.util.Collections.unmodifiableList(quantile_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Summary.class, io.prometheus.client.Metrics.Summary.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Summary parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Summary(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int SAMPLE_COUNT_FIELD_NUMBER = 1; private long sampleCount_; /** * optional uint64 sample_count = 1; */ public boolean hasSampleCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional uint64 sample_count = 1; */ public long getSampleCount() { return sampleCount_; } public static final int SAMPLE_SUM_FIELD_NUMBER = 2; private double sampleSum_; /** * optional double sample_sum = 2; */ public boolean hasSampleSum() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double sample_sum = 2; */ public double getSampleSum() { return sampleSum_; } public static final int QUANTILE_FIELD_NUMBER = 3; private java.util.List quantile_; /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public java.util.List getQuantileList() { return quantile_; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public java.util.List getQuantileOrBuilderList() { return quantile_; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public int getQuantileCount() { return quantile_.size(); } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.Quantile getQuantile(int index) { return quantile_.get(index); } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.QuantileOrBuilder getQuantileOrBuilder( int index) { return quantile_.get(index); } private void initFields() { sampleCount_ = 0L; sampleSum_ = 0D; quantile_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeUInt64(1, sampleCount_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeDouble(2, sampleSum_); } for (int i = 0; i < quantile_.size(); i++) { output.writeMessage(3, quantile_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, sampleCount_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(2, sampleSum_); } for (int i = 0; i < quantile_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, quantile_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Summary parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Summary parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Summary parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Summary parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Summary parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Summary parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Summary parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Summary parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Summary parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Summary parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Summary prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Summary} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Summary) io.prometheus.client.Metrics.SummaryOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Summary.class, io.prometheus.client.Metrics.Summary.Builder.class); } // Construct using io.prometheus.client.Metrics.Summary.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getQuantileFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); sampleCount_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); sampleSum_ = 0D; bitField0_ = (bitField0_ & ~0x00000002); if (quantileBuilder_ == null) { quantile_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { quantileBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_descriptor; } public io.prometheus.client.Metrics.Summary getDefaultInstanceForType() { return io.prometheus.client.Metrics.Summary.getDefaultInstance(); } public io.prometheus.client.Metrics.Summary build() { io.prometheus.client.Metrics.Summary result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Summary buildPartial() { io.prometheus.client.Metrics.Summary result = new io.prometheus.client.Metrics.Summary(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.sampleCount_ = sampleCount_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sampleSum_ = sampleSum_; if (quantileBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004)) { quantile_ = java.util.Collections.unmodifiableList(quantile_); bitField0_ = (bitField0_ & ~0x00000004); } result.quantile_ = quantile_; } else { result.quantile_ = quantileBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Summary) { return mergeFrom((io.prometheus.client.Metrics.Summary)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Summary other) { if (other == io.prometheus.client.Metrics.Summary.getDefaultInstance()) return this; if (other.hasSampleCount()) { setSampleCount(other.getSampleCount()); } if (other.hasSampleSum()) { setSampleSum(other.getSampleSum()); } if (quantileBuilder_ == null) { if (!other.quantile_.isEmpty()) { if (quantile_.isEmpty()) { quantile_ = other.quantile_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureQuantileIsMutable(); quantile_.addAll(other.quantile_); } onChanged(); } } else { if (!other.quantile_.isEmpty()) { if (quantileBuilder_.isEmpty()) { quantileBuilder_.dispose(); quantileBuilder_ = null; quantile_ = other.quantile_; bitField0_ = (bitField0_ & ~0x00000004); quantileBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getQuantileFieldBuilder() : null; } else { quantileBuilder_.addAllMessages(other.quantile_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Summary parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Summary) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long sampleCount_ ; /** * optional uint64 sample_count = 1; */ public boolean hasSampleCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional uint64 sample_count = 1; */ public long getSampleCount() { return sampleCount_; } /** * optional uint64 sample_count = 1; */ public Builder setSampleCount(long value) { bitField0_ |= 0x00000001; sampleCount_ = value; onChanged(); return this; } /** * optional uint64 sample_count = 1; */ public Builder clearSampleCount() { bitField0_ = (bitField0_ & ~0x00000001); sampleCount_ = 0L; onChanged(); return this; } private double sampleSum_ ; /** * optional double sample_sum = 2; */ public boolean hasSampleSum() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double sample_sum = 2; */ public double getSampleSum() { return sampleSum_; } /** * optional double sample_sum = 2; */ public Builder setSampleSum(double value) { bitField0_ |= 0x00000002; sampleSum_ = value; onChanged(); return this; } /** * optional double sample_sum = 2; */ public Builder clearSampleSum() { bitField0_ = (bitField0_ & ~0x00000002); sampleSum_ = 0D; onChanged(); return this; } private java.util.List quantile_ = java.util.Collections.emptyList(); private void ensureQuantileIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { quantile_ = new java.util.ArrayList(quantile_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Quantile, io.prometheus.client.Metrics.Quantile.Builder, io.prometheus.client.Metrics.QuantileOrBuilder> quantileBuilder_; /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public java.util.List getQuantileList() { if (quantileBuilder_ == null) { return java.util.Collections.unmodifiableList(quantile_); } else { return quantileBuilder_.getMessageList(); } } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public int getQuantileCount() { if (quantileBuilder_ == null) { return quantile_.size(); } else { return quantileBuilder_.getCount(); } } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.Quantile getQuantile(int index) { if (quantileBuilder_ == null) { return quantile_.get(index); } else { return quantileBuilder_.getMessage(index); } } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder setQuantile( int index, io.prometheus.client.Metrics.Quantile value) { if (quantileBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQuantileIsMutable(); quantile_.set(index, value); onChanged(); } else { quantileBuilder_.setMessage(index, value); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder setQuantile( int index, io.prometheus.client.Metrics.Quantile.Builder builderForValue) { if (quantileBuilder_ == null) { ensureQuantileIsMutable(); quantile_.set(index, builderForValue.build()); onChanged(); } else { quantileBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder addQuantile(io.prometheus.client.Metrics.Quantile value) { if (quantileBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQuantileIsMutable(); quantile_.add(value); onChanged(); } else { quantileBuilder_.addMessage(value); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder addQuantile( int index, io.prometheus.client.Metrics.Quantile value) { if (quantileBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureQuantileIsMutable(); quantile_.add(index, value); onChanged(); } else { quantileBuilder_.addMessage(index, value); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder addQuantile( io.prometheus.client.Metrics.Quantile.Builder builderForValue) { if (quantileBuilder_ == null) { ensureQuantileIsMutable(); quantile_.add(builderForValue.build()); onChanged(); } else { quantileBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder addQuantile( int index, io.prometheus.client.Metrics.Quantile.Builder builderForValue) { if (quantileBuilder_ == null) { ensureQuantileIsMutable(); quantile_.add(index, builderForValue.build()); onChanged(); } else { quantileBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder addAllQuantile( java.lang.Iterable values) { if (quantileBuilder_ == null) { ensureQuantileIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, quantile_); onChanged(); } else { quantileBuilder_.addAllMessages(values); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder clearQuantile() { if (quantileBuilder_ == null) { quantile_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { quantileBuilder_.clear(); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public Builder removeQuantile(int index) { if (quantileBuilder_ == null) { ensureQuantileIsMutable(); quantile_.remove(index); onChanged(); } else { quantileBuilder_.remove(index); } return this; } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.Quantile.Builder getQuantileBuilder( int index) { return getQuantileFieldBuilder().getBuilder(index); } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.QuantileOrBuilder getQuantileOrBuilder( int index) { if (quantileBuilder_ == null) { return quantile_.get(index); } else { return quantileBuilder_.getMessageOrBuilder(index); } } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public java.util.List getQuantileOrBuilderList() { if (quantileBuilder_ != null) { return quantileBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(quantile_); } } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.Quantile.Builder addQuantileBuilder() { return getQuantileFieldBuilder().addBuilder( io.prometheus.client.Metrics.Quantile.getDefaultInstance()); } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public io.prometheus.client.Metrics.Quantile.Builder addQuantileBuilder( int index) { return getQuantileFieldBuilder().addBuilder( index, io.prometheus.client.Metrics.Quantile.getDefaultInstance()); } /** * repeated .io.prometheus.client.Quantile quantile = 3; */ public java.util.List getQuantileBuilderList() { return getQuantileFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Quantile, io.prometheus.client.Metrics.Quantile.Builder, io.prometheus.client.Metrics.QuantileOrBuilder> getQuantileFieldBuilder() { if (quantileBuilder_ == null) { quantileBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Quantile, io.prometheus.client.Metrics.Quantile.Builder, io.prometheus.client.Metrics.QuantileOrBuilder>( quantile_, ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); quantile_ = null; } return quantileBuilder_; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Summary) } static { defaultInstance = new Summary(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Summary) } public interface UntypedOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Untyped) com.google.protobuf.MessageOrBuilder { /** * optional double value = 1; */ boolean hasValue(); /** * optional double value = 1; */ double getValue(); } /** * Protobuf type {@code io.prometheus.client.Untyped} */ public static final class Untyped extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Untyped) UntypedOrBuilder { // Use Untyped.newBuilder() to construct. private Untyped(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Untyped(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Untyped defaultInstance; public static Untyped getDefaultInstance() { return defaultInstance; } public Untyped getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Untyped( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 9: { bitField0_ |= 0x00000001; value_ = input.readDouble(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Untyped.class, io.prometheus.client.Metrics.Untyped.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Untyped parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Untyped(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int VALUE_FIELD_NUMBER = 1; private double value_; /** * optional double value = 1; */ public boolean hasValue() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double value = 1; */ public double getValue() { return value_; } private void initFields() { value_ = 0D; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeDouble(1, value_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(1, value_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Untyped parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Untyped parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Untyped parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Untyped parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Untyped parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Untyped parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Untyped parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Untyped parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Untyped parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Untyped parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Untyped prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Untyped} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Untyped) io.prometheus.client.Metrics.UntypedOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Untyped.class, io.prometheus.client.Metrics.Untyped.Builder.class); } // Construct using io.prometheus.client.Metrics.Untyped.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); value_ = 0D; bitField0_ = (bitField0_ & ~0x00000001); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_descriptor; } public io.prometheus.client.Metrics.Untyped getDefaultInstanceForType() { return io.prometheus.client.Metrics.Untyped.getDefaultInstance(); } public io.prometheus.client.Metrics.Untyped build() { io.prometheus.client.Metrics.Untyped result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Untyped buildPartial() { io.prometheus.client.Metrics.Untyped result = new io.prometheus.client.Metrics.Untyped(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.value_ = value_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Untyped) { return mergeFrom((io.prometheus.client.Metrics.Untyped)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Untyped other) { if (other == io.prometheus.client.Metrics.Untyped.getDefaultInstance()) return this; if (other.hasValue()) { setValue(other.getValue()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Untyped parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Untyped) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private double value_ ; /** * optional double value = 1; */ public boolean hasValue() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional double value = 1; */ public double getValue() { return value_; } /** * optional double value = 1; */ public Builder setValue(double value) { bitField0_ |= 0x00000001; value_ = value; onChanged(); return this; } /** * optional double value = 1; */ public Builder clearValue() { bitField0_ = (bitField0_ & ~0x00000001); value_ = 0D; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Untyped) } static { defaultInstance = new Untyped(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped) } public interface HistogramOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Histogram) com.google.protobuf.MessageOrBuilder { /** * optional uint64 sample_count = 1; */ boolean hasSampleCount(); /** * optional uint64 sample_count = 1; */ long getSampleCount(); /** * optional double sample_sum = 2; */ boolean hasSampleSum(); /** * optional double sample_sum = 2; */ double getSampleSum(); /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ java.util.List getBucketList(); /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ io.prometheus.client.Metrics.Bucket getBucket(int index); /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ int getBucketCount(); /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ java.util.List getBucketOrBuilderList(); /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ io.prometheus.client.Metrics.BucketOrBuilder getBucketOrBuilder( int index); } /** * Protobuf type {@code io.prometheus.client.Histogram} */ public static final class Histogram extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Histogram) HistogramOrBuilder { // Use Histogram.newBuilder() to construct. private Histogram(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Histogram(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Histogram defaultInstance; public static Histogram getDefaultInstance() { return defaultInstance; } public Histogram getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Histogram( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; sampleCount_ = input.readUInt64(); break; } case 17: { bitField0_ |= 0x00000002; sampleSum_ = input.readDouble(); break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { bucket_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000004; } bucket_.add(input.readMessage(io.prometheus.client.Metrics.Bucket.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { bucket_ = java.util.Collections.unmodifiableList(bucket_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Histogram.class, io.prometheus.client.Metrics.Histogram.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Histogram parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Histogram(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int SAMPLE_COUNT_FIELD_NUMBER = 1; private long sampleCount_; /** * optional uint64 sample_count = 1; */ public boolean hasSampleCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional uint64 sample_count = 1; */ public long getSampleCount() { return sampleCount_; } public static final int SAMPLE_SUM_FIELD_NUMBER = 2; private double sampleSum_; /** * optional double sample_sum = 2; */ public boolean hasSampleSum() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double sample_sum = 2; */ public double getSampleSum() { return sampleSum_; } public static final int BUCKET_FIELD_NUMBER = 3; private java.util.List bucket_; /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ public java.util.List getBucketList() { return bucket_; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ public java.util.List getBucketOrBuilderList() { return bucket_; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ public int getBucketCount() { return bucket_.size(); } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ public io.prometheus.client.Metrics.Bucket getBucket(int index) { return bucket_.get(index); } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
     * Ordered in increasing order of upper_bound, +Inf bucket is optional.
     * 
*/ public io.prometheus.client.Metrics.BucketOrBuilder getBucketOrBuilder( int index) { return bucket_.get(index); } private void initFields() { sampleCount_ = 0L; sampleSum_ = 0D; bucket_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeUInt64(1, sampleCount_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeDouble(2, sampleSum_); } for (int i = 0; i < bucket_.size(); i++) { output.writeMessage(3, bucket_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, sampleCount_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(2, sampleSum_); } for (int i = 0; i < bucket_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, bucket_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Histogram parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Histogram parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Histogram parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Histogram parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Histogram parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Histogram parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Histogram parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Histogram parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Histogram parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Histogram parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Histogram prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Histogram} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Histogram) io.prometheus.client.Metrics.HistogramOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Histogram.class, io.prometheus.client.Metrics.Histogram.Builder.class); } // Construct using io.prometheus.client.Metrics.Histogram.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getBucketFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); sampleCount_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); sampleSum_ = 0D; bitField0_ = (bitField0_ & ~0x00000002); if (bucketBuilder_ == null) { bucket_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { bucketBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_descriptor; } public io.prometheus.client.Metrics.Histogram getDefaultInstanceForType() { return io.prometheus.client.Metrics.Histogram.getDefaultInstance(); } public io.prometheus.client.Metrics.Histogram build() { io.prometheus.client.Metrics.Histogram result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Histogram buildPartial() { io.prometheus.client.Metrics.Histogram result = new io.prometheus.client.Metrics.Histogram(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.sampleCount_ = sampleCount_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.sampleSum_ = sampleSum_; if (bucketBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004)) { bucket_ = java.util.Collections.unmodifiableList(bucket_); bitField0_ = (bitField0_ & ~0x00000004); } result.bucket_ = bucket_; } else { result.bucket_ = bucketBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Histogram) { return mergeFrom((io.prometheus.client.Metrics.Histogram)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Histogram other) { if (other == io.prometheus.client.Metrics.Histogram.getDefaultInstance()) return this; if (other.hasSampleCount()) { setSampleCount(other.getSampleCount()); } if (other.hasSampleSum()) { setSampleSum(other.getSampleSum()); } if (bucketBuilder_ == null) { if (!other.bucket_.isEmpty()) { if (bucket_.isEmpty()) { bucket_ = other.bucket_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureBucketIsMutable(); bucket_.addAll(other.bucket_); } onChanged(); } } else { if (!other.bucket_.isEmpty()) { if (bucketBuilder_.isEmpty()) { bucketBuilder_.dispose(); bucketBuilder_ = null; bucket_ = other.bucket_; bitField0_ = (bitField0_ & ~0x00000004); bucketBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getBucketFieldBuilder() : null; } else { bucketBuilder_.addAllMessages(other.bucket_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Histogram parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Histogram) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long sampleCount_ ; /** * optional uint64 sample_count = 1; */ public boolean hasSampleCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional uint64 sample_count = 1; */ public long getSampleCount() { return sampleCount_; } /** * optional uint64 sample_count = 1; */ public Builder setSampleCount(long value) { bitField0_ |= 0x00000001; sampleCount_ = value; onChanged(); return this; } /** * optional uint64 sample_count = 1; */ public Builder clearSampleCount() { bitField0_ = (bitField0_ & ~0x00000001); sampleCount_ = 0L; onChanged(); return this; } private double sampleSum_ ; /** * optional double sample_sum = 2; */ public boolean hasSampleSum() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double sample_sum = 2; */ public double getSampleSum() { return sampleSum_; } /** * optional double sample_sum = 2; */ public Builder setSampleSum(double value) { bitField0_ |= 0x00000002; sampleSum_ = value; onChanged(); return this; } /** * optional double sample_sum = 2; */ public Builder clearSampleSum() { bitField0_ = (bitField0_ & ~0x00000002); sampleSum_ = 0D; onChanged(); return this; } private java.util.List bucket_ = java.util.Collections.emptyList(); private void ensureBucketIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { bucket_ = new java.util.ArrayList(bucket_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Bucket, io.prometheus.client.Metrics.Bucket.Builder, io.prometheus.client.Metrics.BucketOrBuilder> bucketBuilder_; /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public java.util.List getBucketList() { if (bucketBuilder_ == null) { return java.util.Collections.unmodifiableList(bucket_); } else { return bucketBuilder_.getMessageList(); } } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public int getBucketCount() { if (bucketBuilder_ == null) { return bucket_.size(); } else { return bucketBuilder_.getCount(); } } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public io.prometheus.client.Metrics.Bucket getBucket(int index) { if (bucketBuilder_ == null) { return bucket_.get(index); } else { return bucketBuilder_.getMessage(index); } } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder setBucket( int index, io.prometheus.client.Metrics.Bucket value) { if (bucketBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBucketIsMutable(); bucket_.set(index, value); onChanged(); } else { bucketBuilder_.setMessage(index, value); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder setBucket( int index, io.prometheus.client.Metrics.Bucket.Builder builderForValue) { if (bucketBuilder_ == null) { ensureBucketIsMutable(); bucket_.set(index, builderForValue.build()); onChanged(); } else { bucketBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder addBucket(io.prometheus.client.Metrics.Bucket value) { if (bucketBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBucketIsMutable(); bucket_.add(value); onChanged(); } else { bucketBuilder_.addMessage(value); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder addBucket( int index, io.prometheus.client.Metrics.Bucket value) { if (bucketBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureBucketIsMutable(); bucket_.add(index, value); onChanged(); } else { bucketBuilder_.addMessage(index, value); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder addBucket( io.prometheus.client.Metrics.Bucket.Builder builderForValue) { if (bucketBuilder_ == null) { ensureBucketIsMutable(); bucket_.add(builderForValue.build()); onChanged(); } else { bucketBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder addBucket( int index, io.prometheus.client.Metrics.Bucket.Builder builderForValue) { if (bucketBuilder_ == null) { ensureBucketIsMutable(); bucket_.add(index, builderForValue.build()); onChanged(); } else { bucketBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder addAllBucket( java.lang.Iterable values) { if (bucketBuilder_ == null) { ensureBucketIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, bucket_); onChanged(); } else { bucketBuilder_.addAllMessages(values); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder clearBucket() { if (bucketBuilder_ == null) { bucket_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { bucketBuilder_.clear(); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public Builder removeBucket(int index) { if (bucketBuilder_ == null) { ensureBucketIsMutable(); bucket_.remove(index); onChanged(); } else { bucketBuilder_.remove(index); } return this; } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public io.prometheus.client.Metrics.Bucket.Builder getBucketBuilder( int index) { return getBucketFieldBuilder().getBuilder(index); } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public io.prometheus.client.Metrics.BucketOrBuilder getBucketOrBuilder( int index) { if (bucketBuilder_ == null) { return bucket_.get(index); } else { return bucketBuilder_.getMessageOrBuilder(index); } } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public java.util.List getBucketOrBuilderList() { if (bucketBuilder_ != null) { return bucketBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(bucket_); } } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public io.prometheus.client.Metrics.Bucket.Builder addBucketBuilder() { return getBucketFieldBuilder().addBuilder( io.prometheus.client.Metrics.Bucket.getDefaultInstance()); } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public io.prometheus.client.Metrics.Bucket.Builder addBucketBuilder( int index) { return getBucketFieldBuilder().addBuilder( index, io.prometheus.client.Metrics.Bucket.getDefaultInstance()); } /** * repeated .io.prometheus.client.Bucket bucket = 3; * *
       * Ordered in increasing order of upper_bound, +Inf bucket is optional.
       * 
*/ public java.util.List getBucketBuilderList() { return getBucketFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Bucket, io.prometheus.client.Metrics.Bucket.Builder, io.prometheus.client.Metrics.BucketOrBuilder> getBucketFieldBuilder() { if (bucketBuilder_ == null) { bucketBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Bucket, io.prometheus.client.Metrics.Bucket.Builder, io.prometheus.client.Metrics.BucketOrBuilder>( bucket_, ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); bucket_ = null; } return bucketBuilder_; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Histogram) } static { defaultInstance = new Histogram(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram) } public interface BucketOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Bucket) com.google.protobuf.MessageOrBuilder { /** * optional uint64 cumulative_count = 1; * *
     * Cumulative in increasing order.
     * 
*/ boolean hasCumulativeCount(); /** * optional uint64 cumulative_count = 1; * *
     * Cumulative in increasing order.
     * 
*/ long getCumulativeCount(); /** * optional double upper_bound = 2; * *
     * Inclusive.
     * 
*/ boolean hasUpperBound(); /** * optional double upper_bound = 2; * *
     * Inclusive.
     * 
*/ double getUpperBound(); } /** * Protobuf type {@code io.prometheus.client.Bucket} */ public static final class Bucket extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Bucket) BucketOrBuilder { // Use Bucket.newBuilder() to construct. private Bucket(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Bucket(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Bucket defaultInstance; public static Bucket getDefaultInstance() { return defaultInstance; } public Bucket getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Bucket( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 8: { bitField0_ |= 0x00000001; cumulativeCount_ = input.readUInt64(); break; } case 17: { bitField0_ |= 0x00000002; upperBound_ = input.readDouble(); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Bucket.class, io.prometheus.client.Metrics.Bucket.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Bucket parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Bucket(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int CUMULATIVE_COUNT_FIELD_NUMBER = 1; private long cumulativeCount_; /** * optional uint64 cumulative_count = 1; * *
     * Cumulative in increasing order.
     * 
*/ public boolean hasCumulativeCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional uint64 cumulative_count = 1; * *
     * Cumulative in increasing order.
     * 
*/ public long getCumulativeCount() { return cumulativeCount_; } public static final int UPPER_BOUND_FIELD_NUMBER = 2; private double upperBound_; /** * optional double upper_bound = 2; * *
     * Inclusive.
     * 
*/ public boolean hasUpperBound() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double upper_bound = 2; * *
     * Inclusive.
     * 
*/ public double getUpperBound() { return upperBound_; } private void initFields() { cumulativeCount_ = 0L; upperBound_ = 0D; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeUInt64(1, cumulativeCount_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeDouble(2, upperBound_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeUInt64Size(1, cumulativeCount_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeDoubleSize(2, upperBound_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Bucket parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Bucket parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Bucket parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Bucket parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Bucket parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Bucket parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Bucket parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Bucket parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Bucket parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Bucket parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Bucket prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Bucket} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Bucket) io.prometheus.client.Metrics.BucketOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Bucket.class, io.prometheus.client.Metrics.Bucket.Builder.class); } // Construct using io.prometheus.client.Metrics.Bucket.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); cumulativeCount_ = 0L; bitField0_ = (bitField0_ & ~0x00000001); upperBound_ = 0D; bitField0_ = (bitField0_ & ~0x00000002); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_descriptor; } public io.prometheus.client.Metrics.Bucket getDefaultInstanceForType() { return io.prometheus.client.Metrics.Bucket.getDefaultInstance(); } public io.prometheus.client.Metrics.Bucket build() { io.prometheus.client.Metrics.Bucket result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Bucket buildPartial() { io.prometheus.client.Metrics.Bucket result = new io.prometheus.client.Metrics.Bucket(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.cumulativeCount_ = cumulativeCount_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.upperBound_ = upperBound_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Bucket) { return mergeFrom((io.prometheus.client.Metrics.Bucket)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Bucket other) { if (other == io.prometheus.client.Metrics.Bucket.getDefaultInstance()) return this; if (other.hasCumulativeCount()) { setCumulativeCount(other.getCumulativeCount()); } if (other.hasUpperBound()) { setUpperBound(other.getUpperBound()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Bucket parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Bucket) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private long cumulativeCount_ ; /** * optional uint64 cumulative_count = 1; * *
       * Cumulative in increasing order.
       * 
*/ public boolean hasCumulativeCount() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional uint64 cumulative_count = 1; * *
       * Cumulative in increasing order.
       * 
*/ public long getCumulativeCount() { return cumulativeCount_; } /** * optional uint64 cumulative_count = 1; * *
       * Cumulative in increasing order.
       * 
*/ public Builder setCumulativeCount(long value) { bitField0_ |= 0x00000001; cumulativeCount_ = value; onChanged(); return this; } /** * optional uint64 cumulative_count = 1; * *
       * Cumulative in increasing order.
       * 
*/ public Builder clearCumulativeCount() { bitField0_ = (bitField0_ & ~0x00000001); cumulativeCount_ = 0L; onChanged(); return this; } private double upperBound_ ; /** * optional double upper_bound = 2; * *
       * Inclusive.
       * 
*/ public boolean hasUpperBound() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional double upper_bound = 2; * *
       * Inclusive.
       * 
*/ public double getUpperBound() { return upperBound_; } /** * optional double upper_bound = 2; * *
       * Inclusive.
       * 
*/ public Builder setUpperBound(double value) { bitField0_ |= 0x00000002; upperBound_ = value; onChanged(); return this; } /** * optional double upper_bound = 2; * *
       * Inclusive.
       * 
*/ public Builder clearUpperBound() { bitField0_ = (bitField0_ & ~0x00000002); upperBound_ = 0D; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Bucket) } static { defaultInstance = new Bucket(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket) } public interface MetricOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.Metric) com.google.protobuf.MessageOrBuilder { /** * repeated .io.prometheus.client.LabelPair label = 1; */ java.util.List getLabelList(); /** * repeated .io.prometheus.client.LabelPair label = 1; */ io.prometheus.client.Metrics.LabelPair getLabel(int index); /** * repeated .io.prometheus.client.LabelPair label = 1; */ int getLabelCount(); /** * repeated .io.prometheus.client.LabelPair label = 1; */ java.util.List getLabelOrBuilderList(); /** * repeated .io.prometheus.client.LabelPair label = 1; */ io.prometheus.client.Metrics.LabelPairOrBuilder getLabelOrBuilder( int index); /** * optional .io.prometheus.client.Gauge gauge = 2; */ boolean hasGauge(); /** * optional .io.prometheus.client.Gauge gauge = 2; */ io.prometheus.client.Metrics.Gauge getGauge(); /** * optional .io.prometheus.client.Gauge gauge = 2; */ io.prometheus.client.Metrics.GaugeOrBuilder getGaugeOrBuilder(); /** * optional .io.prometheus.client.Counter counter = 3; */ boolean hasCounter(); /** * optional .io.prometheus.client.Counter counter = 3; */ io.prometheus.client.Metrics.Counter getCounter(); /** * optional .io.prometheus.client.Counter counter = 3; */ io.prometheus.client.Metrics.CounterOrBuilder getCounterOrBuilder(); /** * optional .io.prometheus.client.Summary summary = 4; */ boolean hasSummary(); /** * optional .io.prometheus.client.Summary summary = 4; */ io.prometheus.client.Metrics.Summary getSummary(); /** * optional .io.prometheus.client.Summary summary = 4; */ io.prometheus.client.Metrics.SummaryOrBuilder getSummaryOrBuilder(); /** * optional .io.prometheus.client.Untyped untyped = 5; */ boolean hasUntyped(); /** * optional .io.prometheus.client.Untyped untyped = 5; */ io.prometheus.client.Metrics.Untyped getUntyped(); /** * optional .io.prometheus.client.Untyped untyped = 5; */ io.prometheus.client.Metrics.UntypedOrBuilder getUntypedOrBuilder(); /** * optional .io.prometheus.client.Histogram histogram = 7; */ boolean hasHistogram(); /** * optional .io.prometheus.client.Histogram histogram = 7; */ io.prometheus.client.Metrics.Histogram getHistogram(); /** * optional .io.prometheus.client.Histogram histogram = 7; */ io.prometheus.client.Metrics.HistogramOrBuilder getHistogramOrBuilder(); /** * optional int64 timestamp_ms = 6; */ boolean hasTimestampMs(); /** * optional int64 timestamp_ms = 6; */ long getTimestampMs(); } /** * Protobuf type {@code io.prometheus.client.Metric} */ public static final class Metric extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.Metric) MetricOrBuilder { // Use Metric.newBuilder() to construct. private Metric(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Metric(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Metric defaultInstance; public static Metric getDefaultInstance() { return defaultInstance; } public Metric getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Metric( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { label_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000001; } label_.add(input.readMessage(io.prometheus.client.Metrics.LabelPair.PARSER, extensionRegistry)); break; } case 18: { io.prometheus.client.Metrics.Gauge.Builder subBuilder = null; if (((bitField0_ & 0x00000001) == 0x00000001)) { subBuilder = gauge_.toBuilder(); } gauge_ = input.readMessage(io.prometheus.client.Metrics.Gauge.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(gauge_); gauge_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 26: { io.prometheus.client.Metrics.Counter.Builder subBuilder = null; if (((bitField0_ & 0x00000002) == 0x00000002)) { subBuilder = counter_.toBuilder(); } counter_ = input.readMessage(io.prometheus.client.Metrics.Counter.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(counter_); counter_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000002; break; } case 34: { io.prometheus.client.Metrics.Summary.Builder subBuilder = null; if (((bitField0_ & 0x00000004) == 0x00000004)) { subBuilder = summary_.toBuilder(); } summary_ = input.readMessage(io.prometheus.client.Metrics.Summary.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(summary_); summary_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000004; break; } case 42: { io.prometheus.client.Metrics.Untyped.Builder subBuilder = null; if (((bitField0_ & 0x00000008) == 0x00000008)) { subBuilder = untyped_.toBuilder(); } untyped_ = input.readMessage(io.prometheus.client.Metrics.Untyped.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(untyped_); untyped_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000008; break; } case 48: { bitField0_ |= 0x00000020; timestampMs_ = input.readInt64(); break; } case 58: { io.prometheus.client.Metrics.Histogram.Builder subBuilder = null; if (((bitField0_ & 0x00000010) == 0x00000010)) { subBuilder = histogram_.toBuilder(); } histogram_ = input.readMessage(io.prometheus.client.Metrics.Histogram.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(histogram_); histogram_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000010; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { label_ = java.util.Collections.unmodifiableList(label_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Metric.class, io.prometheus.client.Metrics.Metric.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public Metric parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Metric(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int LABEL_FIELD_NUMBER = 1; private java.util.List label_; /** * repeated .io.prometheus.client.LabelPair label = 1; */ public java.util.List getLabelList() { return label_; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public java.util.List getLabelOrBuilderList() { return label_; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public int getLabelCount() { return label_.size(); } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPair getLabel(int index) { return label_.get(index); } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPairOrBuilder getLabelOrBuilder( int index) { return label_.get(index); } public static final int GAUGE_FIELD_NUMBER = 2; private io.prometheus.client.Metrics.Gauge gauge_; /** * optional .io.prometheus.client.Gauge gauge = 2; */ public boolean hasGauge() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public io.prometheus.client.Metrics.Gauge getGauge() { return gauge_; } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public io.prometheus.client.Metrics.GaugeOrBuilder getGaugeOrBuilder() { return gauge_; } public static final int COUNTER_FIELD_NUMBER = 3; private io.prometheus.client.Metrics.Counter counter_; /** * optional .io.prometheus.client.Counter counter = 3; */ public boolean hasCounter() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .io.prometheus.client.Counter counter = 3; */ public io.prometheus.client.Metrics.Counter getCounter() { return counter_; } /** * optional .io.prometheus.client.Counter counter = 3; */ public io.prometheus.client.Metrics.CounterOrBuilder getCounterOrBuilder() { return counter_; } public static final int SUMMARY_FIELD_NUMBER = 4; private io.prometheus.client.Metrics.Summary summary_; /** * optional .io.prometheus.client.Summary summary = 4; */ public boolean hasSummary() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional .io.prometheus.client.Summary summary = 4; */ public io.prometheus.client.Metrics.Summary getSummary() { return summary_; } /** * optional .io.prometheus.client.Summary summary = 4; */ public io.prometheus.client.Metrics.SummaryOrBuilder getSummaryOrBuilder() { return summary_; } public static final int UNTYPED_FIELD_NUMBER = 5; private io.prometheus.client.Metrics.Untyped untyped_; /** * optional .io.prometheus.client.Untyped untyped = 5; */ public boolean hasUntyped() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public io.prometheus.client.Metrics.Untyped getUntyped() { return untyped_; } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public io.prometheus.client.Metrics.UntypedOrBuilder getUntypedOrBuilder() { return untyped_; } public static final int HISTOGRAM_FIELD_NUMBER = 7; private io.prometheus.client.Metrics.Histogram histogram_; /** * optional .io.prometheus.client.Histogram histogram = 7; */ public boolean hasHistogram() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public io.prometheus.client.Metrics.Histogram getHistogram() { return histogram_; } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public io.prometheus.client.Metrics.HistogramOrBuilder getHistogramOrBuilder() { return histogram_; } public static final int TIMESTAMP_MS_FIELD_NUMBER = 6; private long timestampMs_; /** * optional int64 timestamp_ms = 6; */ public boolean hasTimestampMs() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * optional int64 timestamp_ms = 6; */ public long getTimestampMs() { return timestampMs_; } private void initFields() { label_ = java.util.Collections.emptyList(); gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance(); counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance(); summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance(); untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance(); histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance(); timestampMs_ = 0L; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (int i = 0; i < label_.size(); i++) { output.writeMessage(1, label_.get(i)); } if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(2, gauge_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeMessage(3, counter_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeMessage(4, summary_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { output.writeMessage(5, untyped_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { output.writeInt64(6, timestampMs_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { output.writeMessage(7, histogram_); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < label_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, label_.get(i)); } if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, gauge_); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, counter_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, summary_); } if (((bitField0_ & 0x00000008) == 0x00000008)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(5, untyped_); } if (((bitField0_ & 0x00000020) == 0x00000020)) { size += com.google.protobuf.CodedOutputStream .computeInt64Size(6, timestampMs_); } if (((bitField0_ & 0x00000010) == 0x00000010)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(7, histogram_); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.Metric parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Metric parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Metric parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.Metric parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.Metric parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Metric parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Metric parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.Metric parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.Metric parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.Metric parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.Metric prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.Metric} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.Metric) io.prometheus.client.Metrics.MetricOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.Metric.class, io.prometheus.client.Metrics.Metric.Builder.class); } // Construct using io.prometheus.client.Metrics.Metric.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getLabelFieldBuilder(); getGaugeFieldBuilder(); getCounterFieldBuilder(); getSummaryFieldBuilder(); getUntypedFieldBuilder(); getHistogramFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (labelBuilder_ == null) { label_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { labelBuilder_.clear(); } if (gaugeBuilder_ == null) { gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance(); } else { gaugeBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); if (counterBuilder_ == null) { counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance(); } else { counterBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); if (summaryBuilder_ == null) { summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance(); } else { summaryBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000008); if (untypedBuilder_ == null) { untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance(); } else { untypedBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000010); if (histogramBuilder_ == null) { histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance(); } else { histogramBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000020); timestampMs_ = 0L; bitField0_ = (bitField0_ & ~0x00000040); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_descriptor; } public io.prometheus.client.Metrics.Metric getDefaultInstanceForType() { return io.prometheus.client.Metrics.Metric.getDefaultInstance(); } public io.prometheus.client.Metrics.Metric build() { io.prometheus.client.Metrics.Metric result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.Metric buildPartial() { io.prometheus.client.Metrics.Metric result = new io.prometheus.client.Metrics.Metric(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (labelBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { label_ = java.util.Collections.unmodifiableList(label_); bitField0_ = (bitField0_ & ~0x00000001); } result.label_ = label_; } else { result.label_ = labelBuilder_.build(); } if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000001; } if (gaugeBuilder_ == null) { result.gauge_ = gauge_; } else { result.gauge_ = gaugeBuilder_.build(); } if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000002; } if (counterBuilder_ == null) { result.counter_ = counter_; } else { result.counter_ = counterBuilder_.build(); } if (((from_bitField0_ & 0x00000008) == 0x00000008)) { to_bitField0_ |= 0x00000004; } if (summaryBuilder_ == null) { result.summary_ = summary_; } else { result.summary_ = summaryBuilder_.build(); } if (((from_bitField0_ & 0x00000010) == 0x00000010)) { to_bitField0_ |= 0x00000008; } if (untypedBuilder_ == null) { result.untyped_ = untyped_; } else { result.untyped_ = untypedBuilder_.build(); } if (((from_bitField0_ & 0x00000020) == 0x00000020)) { to_bitField0_ |= 0x00000010; } if (histogramBuilder_ == null) { result.histogram_ = histogram_; } else { result.histogram_ = histogramBuilder_.build(); } if (((from_bitField0_ & 0x00000040) == 0x00000040)) { to_bitField0_ |= 0x00000020; } result.timestampMs_ = timestampMs_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.Metric) { return mergeFrom((io.prometheus.client.Metrics.Metric)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.Metric other) { if (other == io.prometheus.client.Metrics.Metric.getDefaultInstance()) return this; if (labelBuilder_ == null) { if (!other.label_.isEmpty()) { if (label_.isEmpty()) { label_ = other.label_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureLabelIsMutable(); label_.addAll(other.label_); } onChanged(); } } else { if (!other.label_.isEmpty()) { if (labelBuilder_.isEmpty()) { labelBuilder_.dispose(); labelBuilder_ = null; label_ = other.label_; bitField0_ = (bitField0_ & ~0x00000001); labelBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getLabelFieldBuilder() : null; } else { labelBuilder_.addAllMessages(other.label_); } } } if (other.hasGauge()) { mergeGauge(other.getGauge()); } if (other.hasCounter()) { mergeCounter(other.getCounter()); } if (other.hasSummary()) { mergeSummary(other.getSummary()); } if (other.hasUntyped()) { mergeUntyped(other.getUntyped()); } if (other.hasHistogram()) { mergeHistogram(other.getHistogram()); } if (other.hasTimestampMs()) { setTimestampMs(other.getTimestampMs()); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.Metric parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.Metric) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List label_ = java.util.Collections.emptyList(); private void ensureLabelIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { label_ = new java.util.ArrayList(label_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.LabelPair, io.prometheus.client.Metrics.LabelPair.Builder, io.prometheus.client.Metrics.LabelPairOrBuilder> labelBuilder_; /** * repeated .io.prometheus.client.LabelPair label = 1; */ public java.util.List getLabelList() { if (labelBuilder_ == null) { return java.util.Collections.unmodifiableList(label_); } else { return labelBuilder_.getMessageList(); } } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public int getLabelCount() { if (labelBuilder_ == null) { return label_.size(); } else { return labelBuilder_.getCount(); } } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPair getLabel(int index) { if (labelBuilder_ == null) { return label_.get(index); } else { return labelBuilder_.getMessage(index); } } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder setLabel( int index, io.prometheus.client.Metrics.LabelPair value) { if (labelBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLabelIsMutable(); label_.set(index, value); onChanged(); } else { labelBuilder_.setMessage(index, value); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder setLabel( int index, io.prometheus.client.Metrics.LabelPair.Builder builderForValue) { if (labelBuilder_ == null) { ensureLabelIsMutable(); label_.set(index, builderForValue.build()); onChanged(); } else { labelBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder addLabel(io.prometheus.client.Metrics.LabelPair value) { if (labelBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLabelIsMutable(); label_.add(value); onChanged(); } else { labelBuilder_.addMessage(value); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder addLabel( int index, io.prometheus.client.Metrics.LabelPair value) { if (labelBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLabelIsMutable(); label_.add(index, value); onChanged(); } else { labelBuilder_.addMessage(index, value); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder addLabel( io.prometheus.client.Metrics.LabelPair.Builder builderForValue) { if (labelBuilder_ == null) { ensureLabelIsMutable(); label_.add(builderForValue.build()); onChanged(); } else { labelBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder addLabel( int index, io.prometheus.client.Metrics.LabelPair.Builder builderForValue) { if (labelBuilder_ == null) { ensureLabelIsMutable(); label_.add(index, builderForValue.build()); onChanged(); } else { labelBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder addAllLabel( java.lang.Iterable values) { if (labelBuilder_ == null) { ensureLabelIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, label_); onChanged(); } else { labelBuilder_.addAllMessages(values); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder clearLabel() { if (labelBuilder_ == null) { label_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { labelBuilder_.clear(); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public Builder removeLabel(int index) { if (labelBuilder_ == null) { ensureLabelIsMutable(); label_.remove(index); onChanged(); } else { labelBuilder_.remove(index); } return this; } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPair.Builder getLabelBuilder( int index) { return getLabelFieldBuilder().getBuilder(index); } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPairOrBuilder getLabelOrBuilder( int index) { if (labelBuilder_ == null) { return label_.get(index); } else { return labelBuilder_.getMessageOrBuilder(index); } } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public java.util.List getLabelOrBuilderList() { if (labelBuilder_ != null) { return labelBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(label_); } } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPair.Builder addLabelBuilder() { return getLabelFieldBuilder().addBuilder( io.prometheus.client.Metrics.LabelPair.getDefaultInstance()); } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public io.prometheus.client.Metrics.LabelPair.Builder addLabelBuilder( int index) { return getLabelFieldBuilder().addBuilder( index, io.prometheus.client.Metrics.LabelPair.getDefaultInstance()); } /** * repeated .io.prometheus.client.LabelPair label = 1; */ public java.util.List getLabelBuilderList() { return getLabelFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.LabelPair, io.prometheus.client.Metrics.LabelPair.Builder, io.prometheus.client.Metrics.LabelPairOrBuilder> getLabelFieldBuilder() { if (labelBuilder_ == null) { labelBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.LabelPair, io.prometheus.client.Metrics.LabelPair.Builder, io.prometheus.client.Metrics.LabelPairOrBuilder>( label_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); label_ = null; } return labelBuilder_; } private io.prometheus.client.Metrics.Gauge gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Gauge, io.prometheus.client.Metrics.Gauge.Builder, io.prometheus.client.Metrics.GaugeOrBuilder> gaugeBuilder_; /** * optional .io.prometheus.client.Gauge gauge = 2; */ public boolean hasGauge() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public io.prometheus.client.Metrics.Gauge getGauge() { if (gaugeBuilder_ == null) { return gauge_; } else { return gaugeBuilder_.getMessage(); } } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public Builder setGauge(io.prometheus.client.Metrics.Gauge value) { if (gaugeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } gauge_ = value; onChanged(); } else { gaugeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; return this; } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public Builder setGauge( io.prometheus.client.Metrics.Gauge.Builder builderForValue) { if (gaugeBuilder_ == null) { gauge_ = builderForValue.build(); onChanged(); } else { gaugeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; return this; } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public Builder mergeGauge(io.prometheus.client.Metrics.Gauge value) { if (gaugeBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002) && gauge_ != io.prometheus.client.Metrics.Gauge.getDefaultInstance()) { gauge_ = io.prometheus.client.Metrics.Gauge.newBuilder(gauge_).mergeFrom(value).buildPartial(); } else { gauge_ = value; } onChanged(); } else { gaugeBuilder_.mergeFrom(value); } bitField0_ |= 0x00000002; return this; } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public Builder clearGauge() { if (gaugeBuilder_ == null) { gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance(); onChanged(); } else { gaugeBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public io.prometheus.client.Metrics.Gauge.Builder getGaugeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getGaugeFieldBuilder().getBuilder(); } /** * optional .io.prometheus.client.Gauge gauge = 2; */ public io.prometheus.client.Metrics.GaugeOrBuilder getGaugeOrBuilder() { if (gaugeBuilder_ != null) { return gaugeBuilder_.getMessageOrBuilder(); } else { return gauge_; } } /** * optional .io.prometheus.client.Gauge gauge = 2; */ private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Gauge, io.prometheus.client.Metrics.Gauge.Builder, io.prometheus.client.Metrics.GaugeOrBuilder> getGaugeFieldBuilder() { if (gaugeBuilder_ == null) { gaugeBuilder_ = new com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Gauge, io.prometheus.client.Metrics.Gauge.Builder, io.prometheus.client.Metrics.GaugeOrBuilder>( getGauge(), getParentForChildren(), isClean()); gauge_ = null; } return gaugeBuilder_; } private io.prometheus.client.Metrics.Counter counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Counter, io.prometheus.client.Metrics.Counter.Builder, io.prometheus.client.Metrics.CounterOrBuilder> counterBuilder_; /** * optional .io.prometheus.client.Counter counter = 3; */ public boolean hasCounter() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional .io.prometheus.client.Counter counter = 3; */ public io.prometheus.client.Metrics.Counter getCounter() { if (counterBuilder_ == null) { return counter_; } else { return counterBuilder_.getMessage(); } } /** * optional .io.prometheus.client.Counter counter = 3; */ public Builder setCounter(io.prometheus.client.Metrics.Counter value) { if (counterBuilder_ == null) { if (value == null) { throw new NullPointerException(); } counter_ = value; onChanged(); } else { counterBuilder_.setMessage(value); } bitField0_ |= 0x00000004; return this; } /** * optional .io.prometheus.client.Counter counter = 3; */ public Builder setCounter( io.prometheus.client.Metrics.Counter.Builder builderForValue) { if (counterBuilder_ == null) { counter_ = builderForValue.build(); onChanged(); } else { counterBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000004; return this; } /** * optional .io.prometheus.client.Counter counter = 3; */ public Builder mergeCounter(io.prometheus.client.Metrics.Counter value) { if (counterBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004) && counter_ != io.prometheus.client.Metrics.Counter.getDefaultInstance()) { counter_ = io.prometheus.client.Metrics.Counter.newBuilder(counter_).mergeFrom(value).buildPartial(); } else { counter_ = value; } onChanged(); } else { counterBuilder_.mergeFrom(value); } bitField0_ |= 0x00000004; return this; } /** * optional .io.prometheus.client.Counter counter = 3; */ public Builder clearCounter() { if (counterBuilder_ == null) { counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance(); onChanged(); } else { counterBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000004); return this; } /** * optional .io.prometheus.client.Counter counter = 3; */ public io.prometheus.client.Metrics.Counter.Builder getCounterBuilder() { bitField0_ |= 0x00000004; onChanged(); return getCounterFieldBuilder().getBuilder(); } /** * optional .io.prometheus.client.Counter counter = 3; */ public io.prometheus.client.Metrics.CounterOrBuilder getCounterOrBuilder() { if (counterBuilder_ != null) { return counterBuilder_.getMessageOrBuilder(); } else { return counter_; } } /** * optional .io.prometheus.client.Counter counter = 3; */ private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Counter, io.prometheus.client.Metrics.Counter.Builder, io.prometheus.client.Metrics.CounterOrBuilder> getCounterFieldBuilder() { if (counterBuilder_ == null) { counterBuilder_ = new com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Counter, io.prometheus.client.Metrics.Counter.Builder, io.prometheus.client.Metrics.CounterOrBuilder>( getCounter(), getParentForChildren(), isClean()); counter_ = null; } return counterBuilder_; } private io.prometheus.client.Metrics.Summary summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Summary, io.prometheus.client.Metrics.Summary.Builder, io.prometheus.client.Metrics.SummaryOrBuilder> summaryBuilder_; /** * optional .io.prometheus.client.Summary summary = 4; */ public boolean hasSummary() { return ((bitField0_ & 0x00000008) == 0x00000008); } /** * optional .io.prometheus.client.Summary summary = 4; */ public io.prometheus.client.Metrics.Summary getSummary() { if (summaryBuilder_ == null) { return summary_; } else { return summaryBuilder_.getMessage(); } } /** * optional .io.prometheus.client.Summary summary = 4; */ public Builder setSummary(io.prometheus.client.Metrics.Summary value) { if (summaryBuilder_ == null) { if (value == null) { throw new NullPointerException(); } summary_ = value; onChanged(); } else { summaryBuilder_.setMessage(value); } bitField0_ |= 0x00000008; return this; } /** * optional .io.prometheus.client.Summary summary = 4; */ public Builder setSummary( io.prometheus.client.Metrics.Summary.Builder builderForValue) { if (summaryBuilder_ == null) { summary_ = builderForValue.build(); onChanged(); } else { summaryBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000008; return this; } /** * optional .io.prometheus.client.Summary summary = 4; */ public Builder mergeSummary(io.prometheus.client.Metrics.Summary value) { if (summaryBuilder_ == null) { if (((bitField0_ & 0x00000008) == 0x00000008) && summary_ != io.prometheus.client.Metrics.Summary.getDefaultInstance()) { summary_ = io.prometheus.client.Metrics.Summary.newBuilder(summary_).mergeFrom(value).buildPartial(); } else { summary_ = value; } onChanged(); } else { summaryBuilder_.mergeFrom(value); } bitField0_ |= 0x00000008; return this; } /** * optional .io.prometheus.client.Summary summary = 4; */ public Builder clearSummary() { if (summaryBuilder_ == null) { summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance(); onChanged(); } else { summaryBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000008); return this; } /** * optional .io.prometheus.client.Summary summary = 4; */ public io.prometheus.client.Metrics.Summary.Builder getSummaryBuilder() { bitField0_ |= 0x00000008; onChanged(); return getSummaryFieldBuilder().getBuilder(); } /** * optional .io.prometheus.client.Summary summary = 4; */ public io.prometheus.client.Metrics.SummaryOrBuilder getSummaryOrBuilder() { if (summaryBuilder_ != null) { return summaryBuilder_.getMessageOrBuilder(); } else { return summary_; } } /** * optional .io.prometheus.client.Summary summary = 4; */ private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Summary, io.prometheus.client.Metrics.Summary.Builder, io.prometheus.client.Metrics.SummaryOrBuilder> getSummaryFieldBuilder() { if (summaryBuilder_ == null) { summaryBuilder_ = new com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Summary, io.prometheus.client.Metrics.Summary.Builder, io.prometheus.client.Metrics.SummaryOrBuilder>( getSummary(), getParentForChildren(), isClean()); summary_ = null; } return summaryBuilder_; } private io.prometheus.client.Metrics.Untyped untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Untyped, io.prometheus.client.Metrics.Untyped.Builder, io.prometheus.client.Metrics.UntypedOrBuilder> untypedBuilder_; /** * optional .io.prometheus.client.Untyped untyped = 5; */ public boolean hasUntyped() { return ((bitField0_ & 0x00000010) == 0x00000010); } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public io.prometheus.client.Metrics.Untyped getUntyped() { if (untypedBuilder_ == null) { return untyped_; } else { return untypedBuilder_.getMessage(); } } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public Builder setUntyped(io.prometheus.client.Metrics.Untyped value) { if (untypedBuilder_ == null) { if (value == null) { throw new NullPointerException(); } untyped_ = value; onChanged(); } else { untypedBuilder_.setMessage(value); } bitField0_ |= 0x00000010; return this; } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public Builder setUntyped( io.prometheus.client.Metrics.Untyped.Builder builderForValue) { if (untypedBuilder_ == null) { untyped_ = builderForValue.build(); onChanged(); } else { untypedBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000010; return this; } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public Builder mergeUntyped(io.prometheus.client.Metrics.Untyped value) { if (untypedBuilder_ == null) { if (((bitField0_ & 0x00000010) == 0x00000010) && untyped_ != io.prometheus.client.Metrics.Untyped.getDefaultInstance()) { untyped_ = io.prometheus.client.Metrics.Untyped.newBuilder(untyped_).mergeFrom(value).buildPartial(); } else { untyped_ = value; } onChanged(); } else { untypedBuilder_.mergeFrom(value); } bitField0_ |= 0x00000010; return this; } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public Builder clearUntyped() { if (untypedBuilder_ == null) { untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance(); onChanged(); } else { untypedBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000010); return this; } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public io.prometheus.client.Metrics.Untyped.Builder getUntypedBuilder() { bitField0_ |= 0x00000010; onChanged(); return getUntypedFieldBuilder().getBuilder(); } /** * optional .io.prometheus.client.Untyped untyped = 5; */ public io.prometheus.client.Metrics.UntypedOrBuilder getUntypedOrBuilder() { if (untypedBuilder_ != null) { return untypedBuilder_.getMessageOrBuilder(); } else { return untyped_; } } /** * optional .io.prometheus.client.Untyped untyped = 5; */ private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Untyped, io.prometheus.client.Metrics.Untyped.Builder, io.prometheus.client.Metrics.UntypedOrBuilder> getUntypedFieldBuilder() { if (untypedBuilder_ == null) { untypedBuilder_ = new com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Untyped, io.prometheus.client.Metrics.Untyped.Builder, io.prometheus.client.Metrics.UntypedOrBuilder>( getUntyped(), getParentForChildren(), isClean()); untyped_ = null; } return untypedBuilder_; } private io.prometheus.client.Metrics.Histogram histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Histogram, io.prometheus.client.Metrics.Histogram.Builder, io.prometheus.client.Metrics.HistogramOrBuilder> histogramBuilder_; /** * optional .io.prometheus.client.Histogram histogram = 7; */ public boolean hasHistogram() { return ((bitField0_ & 0x00000020) == 0x00000020); } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public io.prometheus.client.Metrics.Histogram getHistogram() { if (histogramBuilder_ == null) { return histogram_; } else { return histogramBuilder_.getMessage(); } } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public Builder setHistogram(io.prometheus.client.Metrics.Histogram value) { if (histogramBuilder_ == null) { if (value == null) { throw new NullPointerException(); } histogram_ = value; onChanged(); } else { histogramBuilder_.setMessage(value); } bitField0_ |= 0x00000020; return this; } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public Builder setHistogram( io.prometheus.client.Metrics.Histogram.Builder builderForValue) { if (histogramBuilder_ == null) { histogram_ = builderForValue.build(); onChanged(); } else { histogramBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000020; return this; } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public Builder mergeHistogram(io.prometheus.client.Metrics.Histogram value) { if (histogramBuilder_ == null) { if (((bitField0_ & 0x00000020) == 0x00000020) && histogram_ != io.prometheus.client.Metrics.Histogram.getDefaultInstance()) { histogram_ = io.prometheus.client.Metrics.Histogram.newBuilder(histogram_).mergeFrom(value).buildPartial(); } else { histogram_ = value; } onChanged(); } else { histogramBuilder_.mergeFrom(value); } bitField0_ |= 0x00000020; return this; } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public Builder clearHistogram() { if (histogramBuilder_ == null) { histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance(); onChanged(); } else { histogramBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000020); return this; } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public io.prometheus.client.Metrics.Histogram.Builder getHistogramBuilder() { bitField0_ |= 0x00000020; onChanged(); return getHistogramFieldBuilder().getBuilder(); } /** * optional .io.prometheus.client.Histogram histogram = 7; */ public io.prometheus.client.Metrics.HistogramOrBuilder getHistogramOrBuilder() { if (histogramBuilder_ != null) { return histogramBuilder_.getMessageOrBuilder(); } else { return histogram_; } } /** * optional .io.prometheus.client.Histogram histogram = 7; */ private com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Histogram, io.prometheus.client.Metrics.Histogram.Builder, io.prometheus.client.Metrics.HistogramOrBuilder> getHistogramFieldBuilder() { if (histogramBuilder_ == null) { histogramBuilder_ = new com.google.protobuf.SingleFieldBuilder< io.prometheus.client.Metrics.Histogram, io.prometheus.client.Metrics.Histogram.Builder, io.prometheus.client.Metrics.HistogramOrBuilder>( getHistogram(), getParentForChildren(), isClean()); histogram_ = null; } return histogramBuilder_; } private long timestampMs_ ; /** * optional int64 timestamp_ms = 6; */ public boolean hasTimestampMs() { return ((bitField0_ & 0x00000040) == 0x00000040); } /** * optional int64 timestamp_ms = 6; */ public long getTimestampMs() { return timestampMs_; } /** * optional int64 timestamp_ms = 6; */ public Builder setTimestampMs(long value) { bitField0_ |= 0x00000040; timestampMs_ = value; onChanged(); return this; } /** * optional int64 timestamp_ms = 6; */ public Builder clearTimestampMs() { bitField0_ = (bitField0_ & ~0x00000040); timestampMs_ = 0L; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.Metric) } static { defaultInstance = new Metric(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.Metric) } public interface MetricFamilyOrBuilder extends // @@protoc_insertion_point(interface_extends:io.prometheus.client.MetricFamily) com.google.protobuf.MessageOrBuilder { /** * optional string name = 1; */ boolean hasName(); /** * optional string name = 1; */ java.lang.String getName(); /** * optional string name = 1; */ com.google.protobuf.ByteString getNameBytes(); /** * optional string help = 2; */ boolean hasHelp(); /** * optional string help = 2; */ java.lang.String getHelp(); /** * optional string help = 2; */ com.google.protobuf.ByteString getHelpBytes(); /** * optional .io.prometheus.client.MetricType type = 3; */ boolean hasType(); /** * optional .io.prometheus.client.MetricType type = 3; */ io.prometheus.client.Metrics.MetricType getType(); /** * repeated .io.prometheus.client.Metric metric = 4; */ java.util.List getMetricList(); /** * repeated .io.prometheus.client.Metric metric = 4; */ io.prometheus.client.Metrics.Metric getMetric(int index); /** * repeated .io.prometheus.client.Metric metric = 4; */ int getMetricCount(); /** * repeated .io.prometheus.client.Metric metric = 4; */ java.util.List getMetricOrBuilderList(); /** * repeated .io.prometheus.client.Metric metric = 4; */ io.prometheus.client.Metrics.MetricOrBuilder getMetricOrBuilder( int index); } /** * Protobuf type {@code io.prometheus.client.MetricFamily} */ public static final class MetricFamily extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:io.prometheus.client.MetricFamily) MetricFamilyOrBuilder { // Use MetricFamily.newBuilder() to construct. private MetricFamily(com.google.protobuf.GeneratedMessage.Builder builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private MetricFamily(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final MetricFamily defaultInstance; public static MetricFamily getDefaultInstance() { return defaultInstance; } public MetricFamily getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private MetricFamily( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000001; name_ = bs; break; } case 18: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000002; help_ = bs; break; } case 24: { int rawValue = input.readEnum(); io.prometheus.client.Metrics.MetricType value = io.prometheus.client.Metrics.MetricType.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(3, rawValue); } else { bitField0_ |= 0x00000004; type_ = value; } break; } case 34: { if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { metric_ = new java.util.ArrayList(); mutable_bitField0_ |= 0x00000008; } metric_.add(input.readMessage(io.prometheus.client.Metrics.Metric.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { metric_ = java.util.Collections.unmodifiableList(metric_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.MetricFamily.class, io.prometheus.client.Metrics.MetricFamily.Builder.class); } public static com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { public MetricFamily parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new MetricFamily(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser getParserForType() { return PARSER; } private int bitField0_; public static final int NAME_FIELD_NUMBER = 1; private java.lang.Object name_; /** * optional string name = 1; */ public boolean hasName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional string name = 1; */ public java.lang.String getName() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } } /** * optional string name = 1; */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int HELP_FIELD_NUMBER = 2; private java.lang.Object help_; /** * optional string help = 2; */ public boolean hasHelp() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional string help = 2; */ public java.lang.String getHelp() { java.lang.Object ref = help_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { help_ = s; } return s; } } /** * optional string help = 2; */ public com.google.protobuf.ByteString getHelpBytes() { java.lang.Object ref = help_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); help_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TYPE_FIELD_NUMBER = 3; private io.prometheus.client.Metrics.MetricType type_; /** * optional .io.prometheus.client.MetricType type = 3; */ public boolean hasType() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional .io.prometheus.client.MetricType type = 3; */ public io.prometheus.client.Metrics.MetricType getType() { return type_; } public static final int METRIC_FIELD_NUMBER = 4; private java.util.List metric_; /** * repeated .io.prometheus.client.Metric metric = 4; */ public java.util.List getMetricList() { return metric_; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public java.util.List getMetricOrBuilderList() { return metric_; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public int getMetricCount() { return metric_.size(); } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.Metric getMetric(int index) { return metric_.get(index); } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.MetricOrBuilder getMetricOrBuilder( int index) { return metric_.get(index); } private void initFields() { name_ = ""; help_ = ""; type_ = io.prometheus.client.Metrics.MetricType.COUNTER; metric_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeBytes(2, getHelpBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeEnum(3, type_.getNumber()); } for (int i = 0; i < metric_.size(); i++) { output.writeMessage(4, metric_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getNameBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(2, getHelpBytes()); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(3, type_.getNumber()); } for (int i = 0; i < metric_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(4, metric_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static io.prometheus.client.Metrics.MetricFamily parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.MetricFamily parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.MetricFamily parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static io.prometheus.client.Metrics.MetricFamily parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static io.prometheus.client.Metrics.MetricFamily parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.MetricFamily parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.MetricFamily parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static io.prometheus.client.Metrics.MetricFamily parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static io.prometheus.client.Metrics.MetricFamily parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static io.prometheus.client.Metrics.MetricFamily parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(io.prometheus.client.Metrics.MetricFamily prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code io.prometheus.client.MetricFamily} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder implements // @@protoc_insertion_point(builder_implements:io.prometheus.client.MetricFamily) io.prometheus.client.Metrics.MetricFamilyOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable .ensureFieldAccessorsInitialized( io.prometheus.client.Metrics.MetricFamily.class, io.prometheus.client.Metrics.MetricFamily.Builder.class); } // Construct using io.prometheus.client.Metrics.MetricFamily.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getMetricFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); name_ = ""; bitField0_ = (bitField0_ & ~0x00000001); help_ = ""; bitField0_ = (bitField0_ & ~0x00000002); type_ = io.prometheus.client.Metrics.MetricType.COUNTER; bitField0_ = (bitField0_ & ~0x00000004); if (metricBuilder_ == null) { metric_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); } else { metricBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_descriptor; } public io.prometheus.client.Metrics.MetricFamily getDefaultInstanceForType() { return io.prometheus.client.Metrics.MetricFamily.getDefaultInstance(); } public io.prometheus.client.Metrics.MetricFamily build() { io.prometheus.client.Metrics.MetricFamily result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public io.prometheus.client.Metrics.MetricFamily buildPartial() { io.prometheus.client.Metrics.MetricFamily result = new io.prometheus.client.Metrics.MetricFamily(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.name_ = name_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } result.help_ = help_; if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.type_ = type_; if (metricBuilder_ == null) { if (((bitField0_ & 0x00000008) == 0x00000008)) { metric_ = java.util.Collections.unmodifiableList(metric_); bitField0_ = (bitField0_ & ~0x00000008); } result.metric_ = metric_; } else { result.metric_ = metricBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof io.prometheus.client.Metrics.MetricFamily) { return mergeFrom((io.prometheus.client.Metrics.MetricFamily)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(io.prometheus.client.Metrics.MetricFamily other) { if (other == io.prometheus.client.Metrics.MetricFamily.getDefaultInstance()) return this; if (other.hasName()) { bitField0_ |= 0x00000001; name_ = other.name_; onChanged(); } if (other.hasHelp()) { bitField0_ |= 0x00000002; help_ = other.help_; onChanged(); } if (other.hasType()) { setType(other.getType()); } if (metricBuilder_ == null) { if (!other.metric_.isEmpty()) { if (metric_.isEmpty()) { metric_ = other.metric_; bitField0_ = (bitField0_ & ~0x00000008); } else { ensureMetricIsMutable(); metric_.addAll(other.metric_); } onChanged(); } } else { if (!other.metric_.isEmpty()) { if (metricBuilder_.isEmpty()) { metricBuilder_.dispose(); metricBuilder_ = null; metric_ = other.metric_; bitField0_ = (bitField0_ & ~0x00000008); metricBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getMetricFieldBuilder() : null; } else { metricBuilder_.addAllMessages(other.metric_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { io.prometheus.client.Metrics.MetricFamily parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (io.prometheus.client.Metrics.MetricFamily) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object name_ = ""; /** * optional string name = 1; */ public boolean hasName() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * optional string name = 1; */ public java.lang.String getName() { java.lang.Object ref = name_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { name_ = s; } return s; } else { return (java.lang.String) ref; } } /** * optional string name = 1; */ public com.google.protobuf.ByteString getNameBytes() { java.lang.Object ref = name_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); name_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string name = 1; */ public Builder setName( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; name_ = value; onChanged(); return this; } /** * optional string name = 1; */ public Builder clearName() { bitField0_ = (bitField0_ & ~0x00000001); name_ = getDefaultInstance().getName(); onChanged(); return this; } /** * optional string name = 1; */ public Builder setNameBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; name_ = value; onChanged(); return this; } private java.lang.Object help_ = ""; /** * optional string help = 2; */ public boolean hasHelp() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * optional string help = 2; */ public java.lang.String getHelp() { java.lang.Object ref = help_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { help_ = s; } return s; } else { return (java.lang.String) ref; } } /** * optional string help = 2; */ public com.google.protobuf.ByteString getHelpBytes() { java.lang.Object ref = help_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); help_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * optional string help = 2; */ public Builder setHelp( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; help_ = value; onChanged(); return this; } /** * optional string help = 2; */ public Builder clearHelp() { bitField0_ = (bitField0_ & ~0x00000002); help_ = getDefaultInstance().getHelp(); onChanged(); return this; } /** * optional string help = 2; */ public Builder setHelpBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; help_ = value; onChanged(); return this; } private io.prometheus.client.Metrics.MetricType type_ = io.prometheus.client.Metrics.MetricType.COUNTER; /** * optional .io.prometheus.client.MetricType type = 3; */ public boolean hasType() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * optional .io.prometheus.client.MetricType type = 3; */ public io.prometheus.client.Metrics.MetricType getType() { return type_; } /** * optional .io.prometheus.client.MetricType type = 3; */ public Builder setType(io.prometheus.client.Metrics.MetricType value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; type_ = value; onChanged(); return this; } /** * optional .io.prometheus.client.MetricType type = 3; */ public Builder clearType() { bitField0_ = (bitField0_ & ~0x00000004); type_ = io.prometheus.client.Metrics.MetricType.COUNTER; onChanged(); return this; } private java.util.List metric_ = java.util.Collections.emptyList(); private void ensureMetricIsMutable() { if (!((bitField0_ & 0x00000008) == 0x00000008)) { metric_ = new java.util.ArrayList(metric_); bitField0_ |= 0x00000008; } } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Metric, io.prometheus.client.Metrics.Metric.Builder, io.prometheus.client.Metrics.MetricOrBuilder> metricBuilder_; /** * repeated .io.prometheus.client.Metric metric = 4; */ public java.util.List getMetricList() { if (metricBuilder_ == null) { return java.util.Collections.unmodifiableList(metric_); } else { return metricBuilder_.getMessageList(); } } /** * repeated .io.prometheus.client.Metric metric = 4; */ public int getMetricCount() { if (metricBuilder_ == null) { return metric_.size(); } else { return metricBuilder_.getCount(); } } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.Metric getMetric(int index) { if (metricBuilder_ == null) { return metric_.get(index); } else { return metricBuilder_.getMessage(index); } } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder setMetric( int index, io.prometheus.client.Metrics.Metric value) { if (metricBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMetricIsMutable(); metric_.set(index, value); onChanged(); } else { metricBuilder_.setMessage(index, value); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder setMetric( int index, io.prometheus.client.Metrics.Metric.Builder builderForValue) { if (metricBuilder_ == null) { ensureMetricIsMutable(); metric_.set(index, builderForValue.build()); onChanged(); } else { metricBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder addMetric(io.prometheus.client.Metrics.Metric value) { if (metricBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMetricIsMutable(); metric_.add(value); onChanged(); } else { metricBuilder_.addMessage(value); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder addMetric( int index, io.prometheus.client.Metrics.Metric value) { if (metricBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureMetricIsMutable(); metric_.add(index, value); onChanged(); } else { metricBuilder_.addMessage(index, value); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder addMetric( io.prometheus.client.Metrics.Metric.Builder builderForValue) { if (metricBuilder_ == null) { ensureMetricIsMutable(); metric_.add(builderForValue.build()); onChanged(); } else { metricBuilder_.addMessage(builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder addMetric( int index, io.prometheus.client.Metrics.Metric.Builder builderForValue) { if (metricBuilder_ == null) { ensureMetricIsMutable(); metric_.add(index, builderForValue.build()); onChanged(); } else { metricBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder addAllMetric( java.lang.Iterable values) { if (metricBuilder_ == null) { ensureMetricIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, metric_); onChanged(); } else { metricBuilder_.addAllMessages(values); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder clearMetric() { if (metricBuilder_ == null) { metric_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000008); onChanged(); } else { metricBuilder_.clear(); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public Builder removeMetric(int index) { if (metricBuilder_ == null) { ensureMetricIsMutable(); metric_.remove(index); onChanged(); } else { metricBuilder_.remove(index); } return this; } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.Metric.Builder getMetricBuilder( int index) { return getMetricFieldBuilder().getBuilder(index); } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.MetricOrBuilder getMetricOrBuilder( int index) { if (metricBuilder_ == null) { return metric_.get(index); } else { return metricBuilder_.getMessageOrBuilder(index); } } /** * repeated .io.prometheus.client.Metric metric = 4; */ public java.util.List getMetricOrBuilderList() { if (metricBuilder_ != null) { return metricBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(metric_); } } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.Metric.Builder addMetricBuilder() { return getMetricFieldBuilder().addBuilder( io.prometheus.client.Metrics.Metric.getDefaultInstance()); } /** * repeated .io.prometheus.client.Metric metric = 4; */ public io.prometheus.client.Metrics.Metric.Builder addMetricBuilder( int index) { return getMetricFieldBuilder().addBuilder( index, io.prometheus.client.Metrics.Metric.getDefaultInstance()); } /** * repeated .io.prometheus.client.Metric metric = 4; */ public java.util.List getMetricBuilderList() { return getMetricFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Metric, io.prometheus.client.Metrics.Metric.Builder, io.prometheus.client.Metrics.MetricOrBuilder> getMetricFieldBuilder() { if (metricBuilder_ == null) { metricBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< io.prometheus.client.Metrics.Metric, io.prometheus.client.Metrics.Metric.Builder, io.prometheus.client.Metrics.MetricOrBuilder>( metric_, ((bitField0_ & 0x00000008) == 0x00000008), getParentForChildren(), isClean()); metric_ = null; } return metricBuilder_; } // @@protoc_insertion_point(builder_scope:io.prometheus.client.MetricFamily) } static { defaultInstance = new MetricFamily(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_LabelPair_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_LabelPair_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Gauge_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Gauge_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Counter_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Counter_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Quantile_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Quantile_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Summary_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Summary_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Untyped_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Untyped_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Histogram_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Histogram_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Bucket_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Bucket_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_Metric_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_Metric_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_io_prometheus_client_MetricFamily_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\rmetrics.proto\022\024io.prometheus.client\"(\n" + "\tLabelPair\022\014\n\004name\030\001 \001(\t\022\r\n\005value\030\002 \001(\t\"" + "\026\n\005Gauge\022\r\n\005value\030\001 \001(\001\"\030\n\007Counter\022\r\n\005va" + "lue\030\001 \001(\001\"+\n\010Quantile\022\020\n\010quantile\030\001 \001(\001\022" + "\r\n\005value\030\002 \001(\001\"e\n\007Summary\022\024\n\014sample_coun" + "t\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\0220\n\010quantile\030" + "\003 \003(\0132\036.io.prometheus.client.Quantile\"\030\n" + "\007Untyped\022\r\n\005value\030\001 \001(\001\"c\n\tHistogram\022\024\n\014" + "sample_count\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\022," + "\n\006bucket\030\003 \003(\0132\034.io.prometheus.client.Bu", "cket\"7\n\006Bucket\022\030\n\020cumulative_count\030\001 \001(\004" + "\022\023\n\013upper_bound\030\002 \001(\001\"\276\002\n\006Metric\022.\n\005labe" + "l\030\001 \003(\0132\037.io.prometheus.client.LabelPair" + "\022*\n\005gauge\030\002 \001(\0132\033.io.prometheus.client.G" + "auge\022.\n\007counter\030\003 \001(\0132\035.io.prometheus.cl" + "ient.Counter\022.\n\007summary\030\004 \001(\0132\035.io.prome" + "theus.client.Summary\022.\n\007untyped\030\005 \001(\0132\035." + "io.prometheus.client.Untyped\0222\n\thistogra" + "m\030\007 \001(\0132\037.io.prometheus.client.Histogram" + "\022\024\n\014timestamp_ms\030\006 \001(\003\"\210\001\n\014MetricFamily\022", "\014\n\004name\030\001 \001(\t\022\014\n\004help\030\002 \001(\t\022.\n\004type\030\003 \001(" + "\0162 .io.prometheus.client.MetricType\022,\n\006m" + "etric\030\004 \003(\0132\034.io.prometheus.client.Metri" + "c*M\n\nMetricType\022\013\n\007COUNTER\020\000\022\t\n\005GAUGE\020\001\022" + "\013\n\007SUMMARY\020\002\022\013\n\007UNTYPED\020\003\022\r\n\tHISTOGRAM\020\004" + "B\026\n\024io.prometheus.client" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); internal_static_io_prometheus_client_LabelPair_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_io_prometheus_client_LabelPair_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_LabelPair_descriptor, new java.lang.String[] { "Name", "Value", }); internal_static_io_prometheus_client_Gauge_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_io_prometheus_client_Gauge_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Gauge_descriptor, new java.lang.String[] { "Value", }); internal_static_io_prometheus_client_Counter_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_io_prometheus_client_Counter_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Counter_descriptor, new java.lang.String[] { "Value", }); internal_static_io_prometheus_client_Quantile_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_io_prometheus_client_Quantile_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Quantile_descriptor, new java.lang.String[] { "Quantile", "Value", }); internal_static_io_prometheus_client_Summary_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_io_prometheus_client_Summary_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Summary_descriptor, new java.lang.String[] { "SampleCount", "SampleSum", "Quantile", }); internal_static_io_prometheus_client_Untyped_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_io_prometheus_client_Untyped_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Untyped_descriptor, new java.lang.String[] { "Value", }); internal_static_io_prometheus_client_Histogram_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_io_prometheus_client_Histogram_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Histogram_descriptor, new java.lang.String[] { "SampleCount", "SampleSum", "Bucket", }); internal_static_io_prometheus_client_Bucket_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_io_prometheus_client_Bucket_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Bucket_descriptor, new java.lang.String[] { "CumulativeCount", "UpperBound", }); internal_static_io_prometheus_client_Metric_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_io_prometheus_client_Metric_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_Metric_descriptor, new java.lang.String[] { "Label", "Gauge", "Counter", "Summary", "Untyped", "Histogram", "TimestampMs", }); internal_static_io_prometheus_client_MetricFamily_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_io_prometheus_client_MetricFamily_descriptor, new java.lang.String[] { "Name", "Help", "Type", "Metric", }); } // @@protoc_insertion_point(outer_class_scope) } ================================================ FILE: vendor/github.com/prometheus/common/README.md ================================================ # Common This repository contains Go libraries that are shared across Prometheus components and libraries. * **model**: Shared data structures * **expfmt**: Decoding and encoding for the exposition format ================================================ FILE: vendor/github.com/prometheus/common/expfmt/bench_test.go ================================================ // 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 ( "bytes" "compress/gzip" "io" "io/ioutil" "testing" "github.com/matttproud/golang_protobuf_extensions/pbutil" dto "github.com/prometheus/client_model/go" ) var parser TextParser // Benchmarks to show how much penalty text format parsing actually inflicts. // // Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4. // // BenchmarkParseText 1000 1188535 ns/op 205085 B/op 6135 allocs/op // BenchmarkParseTextGzip 1000 1376567 ns/op 246224 B/op 6151 allocs/op // BenchmarkParseProto 10000 172790 ns/op 52258 B/op 1160 allocs/op // BenchmarkParseProtoGzip 5000 324021 ns/op 94931 B/op 1211 allocs/op // BenchmarkParseProtoMap 10000 187946 ns/op 58714 B/op 1203 allocs/op // // CONCLUSION: The overhead for the map is negligible. Text format needs ~5x more allocations. // Without compression, it needs ~7x longer, but with compression (the more relevant scenario), // the difference becomes less relevant, only ~4x. // // The test data contains 248 samples. // // BenchmarkProcessor002ParseOnly in the extraction package is not quite // comparable to the benchmarks here, but it gives an idea: JSON parsing is even // slower than text parsing and needs a comparable amount of allocs. // BenchmarkParseText benchmarks the parsing of a text-format scrape into metric // family DTOs. func BenchmarkParseText(b *testing.B) { b.StopTimer() data, err := ioutil.ReadFile("testdata/text") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { if _, err := parser.TextToMetricFamilies(bytes.NewReader(data)); err != nil { b.Fatal(err) } } } // BenchmarkParseTextGzip benchmarks the parsing of a gzipped text-format scrape // into metric family DTOs. func BenchmarkParseTextGzip(b *testing.B) { b.StopTimer() data, err := ioutil.ReadFile("testdata/text.gz") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { in, err := gzip.NewReader(bytes.NewReader(data)) if err != nil { b.Fatal(err) } if _, err := parser.TextToMetricFamilies(in); err != nil { b.Fatal(err) } } } // BenchmarkParseProto benchmarks the parsing of a protobuf-format scrape into // metric family DTOs. Note that this does not build a map of metric families // (as the text version does), because it is not required for Prometheus // ingestion either. (However, it is required for the text-format parsing, as // the metric family might be sprinkled all over the text, while the // protobuf-format guarantees bundling at one place.) func BenchmarkParseProto(b *testing.B) { b.StopTimer() data, err := ioutil.ReadFile("testdata/protobuf") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { family := &dto.MetricFamily{} in := bytes.NewReader(data) for { family.Reset() if _, err := pbutil.ReadDelimited(in, family); err != nil { if err == io.EOF { break } b.Fatal(err) } } } } // BenchmarkParseProtoGzip is like BenchmarkParseProto above, but parses gzipped // protobuf format. func BenchmarkParseProtoGzip(b *testing.B) { b.StopTimer() data, err := ioutil.ReadFile("testdata/protobuf.gz") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { family := &dto.MetricFamily{} in, err := gzip.NewReader(bytes.NewReader(data)) if err != nil { b.Fatal(err) } for { family.Reset() if _, err := pbutil.ReadDelimited(in, family); err != nil { if err == io.EOF { break } b.Fatal(err) } } } } // BenchmarkParseProtoMap is like BenchmarkParseProto but DOES put the parsed // metric family DTOs into a map. This is not happening during Prometheus // ingestion. It is just here to measure the overhead of that map creation and // separate it from the overhead of the text format parsing. func BenchmarkParseProtoMap(b *testing.B) { b.StopTimer() data, err := ioutil.ReadFile("testdata/protobuf") if err != nil { b.Fatal(err) } b.StartTimer() for i := 0; i < b.N; i++ { families := map[string]*dto.MetricFamily{} in := bytes.NewReader(data) for { family := &dto.MetricFamily{} if _, err := pbutil.ReadDelimited(in, family); err != nil { if err == io.EOF { break } b.Fatal(err) } families[family.GetName()] = family } } } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/decode.go ================================================ // 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. func ResponseFormat(h http.Header) (Format, error) { ct := h.Get(hdrContentType) mediatype, params, err := mime.ParseMediaType(ct) if err != nil { return "", fmt.Errorf("invalid Content-Type header %q: %s", ct, err) } const ( textType = "text/plain" jsonType = "application/json" ) switch mediatype { case ProtoType: if p := params["proto"]; p != ProtoProtocol { return "", fmt.Errorf("unrecognized protocol message %s", p) } if e := params["encoding"]; e != "delimited" { return "", fmt.Errorf("unsupported encoding %s", e) } return FmtProtoDelim, nil case textType: if v, ok := params["version"]; ok && v != TextVersion { return "", fmt.Errorf("unrecognized protocol version %s", v) } return FmtText, nil case jsonType: var prometheusAPIVersion string if params["schema"] == "prometheus/telemetry" && params["version"] != "" { prometheusAPIVersion = params["version"] } else { prometheusAPIVersion = h.Get("X-Prometheus-API-Version") } switch prometheusAPIVersion { case "0.0.2": return FmtJSON2, nil default: return "", fmt.Errorf("unrecognized API version %s", prometheusAPIVersion) } } return "", fmt.Errorf("unsupported media type %q, expected %q or %q", mediatype, ProtoType, textType) } // NewDecoder returns a new decoder based on the HTTP header. func NewDecoder(r io.Reader, format Format) (Decoder, error) { switch format { case FmtProtoDelim: return &protoDecoder{r: r}, nil case FmtText: return &textDecoder{r: r}, nil case FmtJSON2: return newJSON2Decoder(r), nil } return nil, fmt.Errorf("unsupported decoding format %q", format) } // 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) return err } // textDecoder implements the Decoder interface for the text protcol. 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 } for _, f := range fams { d.fams = append(d.fams, f) } } *v = *d.fams[len(d.fams)-1] d.fams = d.fams[:len(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 } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/decode_test.go ================================================ // 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 ( "errors" "io" "net/http" "reflect" "sort" "strings" "testing" "github.com/prometheus/common/model" ) func TestTextDecoder(t *testing.T) { var ( ts = model.Now() in = ` # Only a quite simple scenario with two metric families. # More complicated tests of the parser itself can be found in the text package. # TYPE mf2 counter mf2 3 mf1{label="value1"} -3.14 123456 mf1{label="value2"} 42 mf2 4 ` out = model.Vector{ &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "mf1", "label": "value1", }, Value: -3.14, Timestamp: 123456, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "mf1", "label": "value2", }, Value: 42, Timestamp: ts, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "mf2", }, Value: 3, Timestamp: ts, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "mf2", }, Value: 4, Timestamp: ts, }, } ) dec := &SampleDecoder{ Dec: &textDecoder{r: strings.NewReader(in)}, Opts: &DecodeOptions{ Timestamp: ts, }, } var all model.Vector for { var smpls model.Vector err := dec.Decode(&smpls) if err == io.EOF { break } if err != nil { t.Fatal(err) } all = append(all, smpls...) } sort.Sort(all) sort.Sort(out) if !reflect.DeepEqual(all, out) { t.Fatalf("output does not match") } } func TestProtoDecoder(t *testing.T) { var testTime = model.Now() scenarios := []struct { in string expected model.Vector }{ { in: "", }, { in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@", expected: model.Vector{ &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count", "some_label_name": "some_label_value", }, Value: -42, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count", "another_label_name": "another_label_value", }, Value: 84, Timestamp: testTime, }, }, }, { in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@", expected: model.Vector{ &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count_count", "some_label_name": "some_label_value", }, Value: 0, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count_sum", "some_label_name": "some_label_value", }, Value: 0, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count", "some_label_name": "some_label_value", "quantile": "0.99", }, Value: -42, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count", "some_label_name": "some_label_value", "quantile": "0.999", }, Value: -84, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count_count", "another_label_name": "another_label_value", }, Value: 0, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count_sum", "another_label_name": "another_label_value", }, Value: 0, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count", "another_label_name": "another_label_value", "quantile": "0.5", }, Value: 10, Timestamp: testTime, }, }, }, { in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f", expected: model.Vector{ &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_bucket", "le": "100", }, Value: 123, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_bucket", "le": "120", }, Value: 412, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_bucket", "le": "144", }, Value: 592, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_bucket", "le": "172.8", }, Value: 1524, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_bucket", "le": "+Inf", }, Value: 2693, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_sum", }, Value: 1756047.3, Timestamp: testTime, }, &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_duration_microseconds_count", }, Value: 2693, Timestamp: testTime, }, }, }, { // The metric type is unset in this protobuf, which needs to be handled // correctly by the decoder. in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?", expected: model.Vector{ &model.Sample{ Metric: model.Metric{ model.MetricNameLabel: "request_count", }, Value: 1, Timestamp: testTime, }, }, }, } for i, scenario := range scenarios { dec := &SampleDecoder{ Dec: &protoDecoder{r: strings.NewReader(scenario.in)}, Opts: &DecodeOptions{ Timestamp: testTime, }, } var all model.Vector for { var smpls model.Vector err := dec.Decode(&smpls) if err == io.EOF { break } if err != nil { t.Fatal(err) } all = append(all, smpls...) } sort.Sort(all) sort.Sort(scenario.expected) if !reflect.DeepEqual(all, scenario.expected) { t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all) } } } func testDiscriminatorHTTPHeader(t testing.TB) { var scenarios = []struct { input map[string]string output Format err error }{ { input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`}, output: FmtProtoDelim, err: nil, }, { input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`}, output: "", err: errors.New("unrecognized protocol message illegal"), }, { input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`}, output: "", err: errors.New("unsupported encoding illegal"), }, { input: map[string]string{"Content-Type": `text/plain; version=0.0.4`}, output: FmtText, err: nil, }, { input: map[string]string{"Content-Type": `text/plain`}, output: FmtText, err: nil, }, { input: map[string]string{"Content-Type": `text/plain; version=0.0.3`}, output: "", err: errors.New("unrecognized protocol version 0.0.3"), }, } for i, scenario := range scenarios { var header http.Header if len(scenario.input) > 0 { header = http.Header{} } for key, value := range scenario.input { header.Add(key, value) } actual, err := ResponseFormat(header) if scenario.err != err { if scenario.err != nil && err != nil { if scenario.err.Error() != err.Error() { t.Errorf("%d. expected %s, got %s", i, scenario.err, err) } } else if scenario.err != nil || err != nil { t.Errorf("%d. expected %s, got %s", i, scenario.err, err) } } if !reflect.DeepEqual(scenario.output, actual) { t.Errorf("%d. expected %s, got %s", i, scenario.output, actual) } } } func TestDiscriminatorHTTPHeader(t *testing.T) { testDiscriminatorHTTPHeader(t) } func BenchmarkDiscriminatorHTTPHeader(b *testing.B) { for i := 0; i < b.N; i++ { testDiscriminatorHTTPHeader(b) } } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/encode.go ================================================ // 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" "bitbucket.org/ww/goautoneg" "github.com/golang/protobuf/proto" "github.com/matttproud/golang_protobuf_extensions/pbutil" 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") } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/expfmt.go ================================================ // 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. FmtText Format = `text/plain; version=` + TextVersion FmtProtoDelim Format = ProtoFmt + ` encoding=delimited` FmtProtoText Format = ProtoFmt + ` encoding=text` FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text` FmtJSON2 Format = `application/json; version=0.0.2` ) const ( hdrContentType = "Content-Type" hdrAccept = "Accept" ) ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 ================================================ ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 ================================================ minimal_metric 1.234 another_metric -3e3 103948 # Even that: no_labels{} 3 # HELP line for non-existing metric will be ignored. ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 ================================================ # A normal comment. # # TYPE name counter name{labelname="val1",basename="basevalue"} NaN name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 # HELP name two-line\n doc str\\ing # HELP name2 doc str"ing 2 # TYPE name2 gauge name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 name2{ labelname = "val1" , }-Inf ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 ================================================ # TYPE my_summary summary my_summary{n1="val1",quantile="0.5"} 110 decoy -1 -2 my_summary{n1="val1",quantile="0.9"} 140 1 my_summary_count{n1="val1"} 42 # Latest timestamp wins in case of a summary. my_summary_sum{n1="val1"} 4711 2 fake_sum{n1="val1"} 2001 # TYPE another_summary summary another_summary_count{n2="val2",n1="val1"} 20 my_summary_count{n2="val2",n1="val1"} 5 5 another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 my_summary_sum{n1="val2"} 08 15 my_summary{n1="val3", quantile="0.2"} 4711 my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN # some # funny comments # HELP # HELP # HELP my_summary # HELP my_summary ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 ================================================ # HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100"} 123 request_duration_microseconds_bucket{le="120"} 412 request_duration_microseconds_bucket{le="144"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 ================================================ bla 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 ================================================ metric{label="\t"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 ================================================ metric{label="bla"} 3.14 2 3 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 ================================================ metric{label="bla"} blubb ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 ================================================ # HELP metric one # HELP metric two ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 ================================================ # TYPE metric counter # TYPE metric untyped ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 ================================================ metric 4.12 # TYPE metric counter ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 ================================================ # TYPE metric bla ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 ================================================ # TYPE met-ric ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 ================================================ @invalidmetric{label="bla"} 3.14 2 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 ================================================ {label="bla"} 3.14 2 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 ================================================ # TYPE metric histogram metric_bucket{le="bla"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 ================================================ metric{label="new line"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 ================================================ metric{@="bla"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 ================================================ metric{__name__="bla"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 ================================================ metric{label+="bla"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 ================================================ metric{label=bla} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 ================================================ # TYPE metric summary metric{quantile="bla"} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 ================================================ metric{label="bla"+} 3.14 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 ================================================ metric{label="bla"} 3.14 2.72 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal ================================================ m{} 0 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/fuzz.go ================================================ // 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/client_golang/text // go-fuzz -bin text-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 } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/json_decode.go ================================================ // 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 ( "encoding/json" "fmt" "io" "sort" "github.com/golang/protobuf/proto" dto "github.com/prometheus/client_model/go" "github.com/prometheus/common/model" ) type json2Decoder struct { dec *json.Decoder fams []*dto.MetricFamily } func newJSON2Decoder(r io.Reader) Decoder { return &json2Decoder{ dec: json.NewDecoder(r), } } type histogram002 struct { Labels model.LabelSet `json:"labels"` Values map[string]float64 `json:"value"` } type counter002 struct { Labels model.LabelSet `json:"labels"` Value float64 `json:"value"` } func protoLabelSet(base, ext model.LabelSet) []*dto.LabelPair { labels := base.Clone().Merge(ext) delete(labels, model.MetricNameLabel) names := make([]string, 0, len(labels)) for ln := range labels { names = append(names, string(ln)) } sort.Strings(names) pairs := make([]*dto.LabelPair, 0, len(labels)) for _, ln := range names { lv := labels[model.LabelName(ln)] pairs = append(pairs, &dto.LabelPair{ Name: proto.String(ln), Value: proto.String(string(lv)), }) } return pairs } func (d *json2Decoder) more() error { var entities []struct { BaseLabels model.LabelSet `json:"baseLabels"` Docstring string `json:"docstring"` Metric struct { Type string `json:"type"` Values json.RawMessage `json:"value"` } `json:"metric"` } if err := d.dec.Decode(&entities); err != nil { return err } for _, e := range entities { f := &dto.MetricFamily{ Name: proto.String(string(e.BaseLabels[model.MetricNameLabel])), Help: proto.String(e.Docstring), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{}, } d.fams = append(d.fams, f) switch e.Metric.Type { case "counter", "gauge": var values []counter002 if err := json.Unmarshal(e.Metric.Values, &values); err != nil { return fmt.Errorf("could not extract %s value: %s", e.Metric.Type, err) } for _, ctr := range values { f.Metric = append(f.Metric, &dto.Metric{ Label: protoLabelSet(e.BaseLabels, ctr.Labels), Untyped: &dto.Untyped{ Value: proto.Float64(ctr.Value), }, }) } case "histogram": var values []histogram002 if err := json.Unmarshal(e.Metric.Values, &values); err != nil { return fmt.Errorf("could not extract %s value: %s", e.Metric.Type, err) } for _, hist := range values { quants := make([]string, 0, len(values)) for q := range hist.Values { quants = append(quants, q) } sort.Strings(quants) for _, q := range quants { value := hist.Values[q] // The correct label is "quantile" but to not break old expressions // this remains "percentile" hist.Labels["percentile"] = model.LabelValue(q) f.Metric = append(f.Metric, &dto.Metric{ Label: protoLabelSet(e.BaseLabels, hist.Labels), Untyped: &dto.Untyped{ Value: proto.Float64(value), }, }) } } default: return fmt.Errorf("unknown metric type %q", e.Metric.Type) } } return nil } // Decode implements the Decoder interface. func (d *json2Decoder) Decode(v *dto.MetricFamily) error { if len(d.fams) == 0 { if err := d.more(); err != nil { return err } } *v = *d.fams[0] d.fams = d.fams[1:] return nil } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/json_decode_test.go ================================================ // 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 ( "os" "reflect" "testing" "github.com/golang/protobuf/proto" dto "github.com/prometheus/client_model/go" ) func TestJSON2Decode(t *testing.T) { f, err := os.Open("testdata/json2") if err != nil { t.Fatal(err) } defer f.Close() dec := newJSON2Decoder(f) var v1 dto.MetricFamily if err := dec.Decode(&v1); err != nil { t.Fatal(err) } exp1 := dto.MetricFamily{ Type: dto.MetricType_UNTYPED.Enum(), Help: proto.String("RPC calls."), Name: proto.String("rpc_calls_total"), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("job"), Value: proto.String("batch_job"), }, { Name: proto.String("service"), Value: proto.String("zed"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(25), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("job"), Value: proto.String("batch_job"), }, { Name: proto.String("service"), Value: proto.String("bar"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(24), }, }, }, } if !reflect.DeepEqual(v1, exp1) { t.Fatalf("Expected %v, got %v", exp1, v1) } var v2 dto.MetricFamily if err := dec.Decode(&v2); err != nil { t.Fatal(err) } exp2 := dto.MetricFamily{ Type: dto.MetricType_UNTYPED.Enum(), Help: proto.String("RPC latency."), Name: proto.String("rpc_latency_microseconds"), Metric: []*dto.Metric{ { Label: []*dto.LabelPair{ { Name: proto.String("percentile"), Value: proto.String("0.010000"), }, { Name: proto.String("service"), Value: proto.String("foo"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(15), }, }, { Label: []*dto.LabelPair{ { Name: proto.String("percentile"), Value: proto.String("0.990000"), }, { Name: proto.String("service"), Value: proto.String("foo"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(17), }, }, }, } if !reflect.DeepEqual(v2, exp2) { t.Fatalf("Expected %v, got %v", exp2, v2) } } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/testdata/json2 ================================================ [ { "baseLabels": { "__name__": "rpc_calls_total", "job": "batch_job" }, "docstring": "RPC calls.", "metric": { "type": "counter", "value": [ { "labels": { "service": "zed" }, "value": 25 }, { "labels": { "service": "bar" }, "value": 24 } ] } }, { "baseLabels": { "__name__": "rpc_latency_microseconds" }, "docstring": "RPC latency.", "metric": { "type": "histogram", "value": [ { "labels": { "service": "foo" }, "value": { "0.010000": 15, "0.990000": 17 } } ] } } ] ================================================ FILE: vendor/github.com/prometheus/common/expfmt/testdata/protobuf ================================================ fc08 0a22 6874 7470 5f72 6571 7565 7374 5f64 7572 6174 696f 6e5f 6d69 6372 6f73 6563 6f6e 6473 122b 5468 6520 4854 5450 2072 6571 7565 7374 206c 6174 656e 6369 6573 2069 6e20 6d69 6372 6f73 6563 6f6e 6473 2e18 0222 570a 0c0a 0768 616e 646c 6572 1201 2f22 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 225d 0a12 0a07 6861 6e64 6c65 7212 072f 616c 6572 7473 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 620a 170a 0768 616e 646c 6572 120c 2f61 7069 2f6d 6574 7269 6373 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 600a 150a 0768 616e 646c 6572 120a 2f61 7069 2f71 7565 7279 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 660a 1b0a 0768 616e 646c 6572 1210 2f61 7069 2f71 7565 7279 5f72 616e 6765 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 620a 170a 0768 616e 646c 6572 120c 2f61 7069 2f74 6172 6765 7473 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 600a 150a 0768 616e 646c 6572 120a 2f63 6f6e 736f 6c65 732f 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 5c0a 110a 0768 616e 646c 6572 1206 2f67 7261 7068 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 5b0a 100a 0768 616e 646c 6572 1205 2f68 6561 7022 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 225e 0a13 0a07 6861 6e64 6c65 7212 082f 7374 6174 6963 2f22 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2260 0a15 0a07 6861 6e64 6c65 7212 0a70 726f 6d65 7468 6575 7322 4708 3b11 5b8f c2f5 083f f440 1a12 0900 0000 0000 00e0 3f11 e17a 14ae c7af 9340 1a12 09cd cccc cccc ccec 3f11 2fdd 2406 81f0 9640 1a12 09ae 47e1 7a14 aeef 3f11 3d0a d7a3 b095 a740 e608 0a17 6874 7470 5f72 6571 7565 7374 5f73 697a 655f 6279 7465 7312 2054 6865 2048 5454 5020 7265 7175 6573 7420 7369 7a65 7320 696e 2062 7974 6573 2e18 0222 570a 0c0a 0768 616e 646c 6572 1201 2f22 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 225d 0a12 0a07 6861 6e64 6c65 7212 072f 616c 6572 7473 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 620a 170a 0768 616e 646c 6572 120c 2f61 7069 2f6d 6574 7269 6373 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 600a 150a 0768 616e 646c 6572 120a 2f61 7069 2f71 7565 7279 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 660a 1b0a 0768 616e 646c 6572 1210 2f61 7069 2f71 7565 7279 5f72 616e 6765 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 620a 170a 0768 616e 646c 6572 120c 2f61 7069 2f74 6172 6765 7473 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 600a 150a 0768 616e 646c 6572 120a 2f63 6f6e 736f 6c65 732f 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 5c0a 110a 0768 616e 646c 6572 1206 2f67 7261 7068 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 5b0a 100a 0768 616e 646c 6572 1205 2f68 6561 7022 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 225e 0a13 0a07 6861 6e64 6c65 7212 082f 7374 6174 6963 2f22 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2260 0a15 0a07 6861 6e64 6c65 7212 0a70 726f 6d65 7468 6575 7322 4708 3b11 0000 0000 40c4 d040 1a12 0900 0000 0000 00e0 3f11 0000 0000 0030 7240 1a12 09cd cccc cccc ccec 3f11 0000 0000 0030 7240 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0030 7240 7c0a 1368 7474 705f 7265 7175 6573 7473 5f74 6f74 616c 1223 546f 7461 6c20 6e75 6d62 6572 206f 6620 4854 5450 2072 6571 7565 7374 7320 6d61 6465 2e18 0022 3e0a 0b0a 0463 6f64 6512 0332 3030 0a15 0a07 6861 6e64 6c65 7212 0a70 726f 6d65 7468 6575 730a 0d0a 066d 6574 686f 6412 0367 6574 1a09 0900 0000 0000 804d 40e8 080a 1868 7474 705f 7265 7370 6f6e 7365 5f73 697a 655f 6279 7465 7312 2154 6865 2048 5454 5020 7265 7370 6f6e 7365 2073 697a 6573 2069 6e20 6279 7465 732e 1802 2257 0a0c 0a07 6861 6e64 6c65 7212 012f 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 5d0a 120a 0768 616e 646c 6572 1207 2f61 6c65 7274 7322 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2262 0a17 0a07 6861 6e64 6c65 7212 0c2f 6170 692f 6d65 7472 6963 7322 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2260 0a15 0a07 6861 6e64 6c65 7212 0a2f 6170 692f 7175 6572 7922 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2266 0a1b 0a07 6861 6e64 6c65 7212 102f 6170 692f 7175 6572 795f 7261 6e67 6522 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2262 0a17 0a07 6861 6e64 6c65 7212 0c2f 6170 692f 7461 7267 6574 7322 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 2260 0a15 0a07 6861 6e64 6c65 7212 0a2f 636f 6e73 6f6c 6573 2f22 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 225c 0a11 0a07 6861 6e64 6c65 7212 062f 6772 6170 6822 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 225b 0a10 0a07 6861 6e64 6c65 7212 052f 6865 6170 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 5e0a 130a 0768 616e 646c 6572 1208 2f73 7461 7469 632f 2247 0800 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 0022 600a 150a 0768 616e 646c 6572 120a 7072 6f6d 6574 6865 7573 2247 083b 1100 0000 00e0 b4fc 401a 1209 0000 0000 0000 e03f 1100 0000 0000 349f 401a 1209 cdcc cccc cccc ec3f 1100 0000 0000 08a0 401a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0aa0 405c 0a19 7072 6f63 6573 735f 6370 755f 7365 636f 6e64 735f 746f 7461 6c12 3054 6f74 616c 2075 7365 7220 616e 6420 7379 7374 656d 2043 5055 2074 696d 6520 7370 656e 7420 696e 2073 6563 6f6e 6473 2e18 0022 0b1a 0909 a470 3d0a d7a3 d03f 4f0a 1270 726f 6365 7373 5f67 6f72 6f75 7469 6e65 7312 2a4e 756d 6265 7220 6f66 2067 6f72 6f75 7469 6e65 7320 7468 6174 2063 7572 7265 6e74 6c79 2065 7869 7374 2e18 0122 0b12 0909 0000 0000 0000 5140 4a0a 0f70 726f 6365 7373 5f6d 6178 5f66 6473 1228 4d61 7869 6d75 6d20 6e75 6d62 6572 206f 6620 6f70 656e 2066 696c 6520 6465 7363 7269 7074 6f72 732e 1801 220b 1209 0900 0000 0000 00c0 4043 0a10 7072 6f63 6573 735f 6f70 656e 5f66 6473 1220 4e75 6d62 6572 206f 6620 6f70 656e 2066 696c 6520 6465 7363 7269 7074 6f72 732e 1801 220b 1209 0900 0000 0000 003d 404e 0a1d 7072 6f63 6573 735f 7265 7369 6465 6e74 5f6d 656d 6f72 795f 6279 7465 7312 1e52 6573 6964 656e 7420 6d65 6d6f 7279 2073 697a 6520 696e 2062 7974 6573 2e18 0122 0b12 0909 0000 0000 004b 8841 630a 1a70 726f 6365 7373 5f73 7461 7274 5f74 696d 655f 7365 636f 6e64 7312 3653 7461 7274 2074 696d 6520 6f66 2074 6865 2070 726f 6365 7373 2073 696e 6365 2075 6e69 7820 6570 6f63 6820 696e 2073 6563 6f6e 6473 2e18 0122 0b12 0909 3d0a 172d e831 d541 4c0a 1c70 726f 6365 7373 5f76 6972 7475 616c 5f6d 656d 6f72 795f 6279 7465 7312 1d56 6972 7475 616c 206d 656d 6f72 7920 7369 7a65 2069 6e20 6279 7465 732e 1801 220b 1209 0900 0000 0020 12c0 415f 0a27 7072 6f6d 6574 6865 7573 5f64 6e73 5f73 645f 6c6f 6f6b 7570 5f66 6169 6c75 7265 735f 746f 7461 6c12 2554 6865 206e 756d 6265 7220 6f66 2044 4e53 2d53 4420 6c6f 6f6b 7570 2066 6169 6c75 7265 732e 1800 220b 1a09 0900 0000 0000 0000 004f 0a1f 7072 6f6d 6574 6865 7573 5f64 6e73 5f73 645f 6c6f 6f6b 7570 735f 746f 7461 6c12 1d54 6865 206e 756d 6265 7220 6f66 2044 4e53 2d53 4420 6c6f 6f6b 7570 732e 1800 220b 1a09 0900 0000 0000 0008 40cf 010a 2a70 726f 6d65 7468 6575 735f 6576 616c 7561 746f 725f 6475 7261 7469 6f6e 5f6d 696c 6c69 7365 636f 6e64 7312 2c54 6865 2064 7572 6174 696f 6e20 666f 7220 616c 6c20 6576 616c 7561 7469 6f6e 7320 746f 2065 7865 6375 7465 2e18 0222 7122 6f08 0b11 0000 0000 0000 2240 1a12 097b 14ae 47e1 7a84 3f11 0000 0000 0000 0000 1a12 099a 9999 9999 99a9 3f11 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 f03f 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 f03f a301 0a39 7072 6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 746f 7261 6765 5f63 6865 636b 706f 696e 745f 6475 7261 7469 6f6e 5f6d 696c 6c69 7365 636f 6e64 7312 5754 6865 2064 7572 6174 696f 6e20 2869 6e20 6d69 6c6c 6973 6563 6f6e 6473 2920 6974 2074 6f6f 6b20 746f 2063 6865 636b 706f 696e 7420 696e 2d6d 656d 6f72 7920 6d65 7472 6963 7320 616e 6420 6865 6164 2063 6875 6e6b 732e 1801 220b 1209 0900 0000 0000 0000 00f2 010a 2870 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 6368 756e 6b5f 6f70 735f 746f 7461 6c12 3354 6865 2074 6f74 616c 206e 756d 6265 7220 6f66 2063 6875 6e6b 206f 7065 7261 7469 6f6e 7320 6279 2074 6865 6972 2074 7970 652e 1800 221b 0a0e 0a04 7479 7065 1206 6372 6561 7465 1a09 0900 0000 0000 b880 4022 1c0a 0f0a 0474 7970 6512 0770 6572 7369 7374 1a09 0900 0000 0000 c05b 4022 180a 0b0a 0474 7970 6512 0370 696e 1a09 0900 0000 0000 807b 4022 1e0a 110a 0474 7970 6512 0974 7261 6e73 636f 6465 1a09 0900 0000 0000 a06b 4022 1a0a 0d0a 0474 7970 6512 0575 6e70 696e 1a09 0900 0000 0000 807b 40c4 010a 3c70 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 696e 6465 7869 6e67 5f62 6174 6368 5f6c 6174 656e 6379 5f6d 696c 6c69 7365 636f 6e64 7312 3751 7561 6e74 696c 6573 2066 6f72 2062 6174 6368 2069 6e64 6578 696e 6720 6c61 7465 6e63 6965 7320 696e 206d 696c 6c69 7365 636f 6e64 732e 1802 2249 2247 0801 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0000 00bf 010a 2d70 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 696e 6465 7869 6e67 5f62 6174 6368 5f73 697a 6573 1241 5175 616e 7469 6c65 7320 666f 7220 696e 6465 7869 6e67 2062 6174 6368 2073 697a 6573 2028 6e75 6d62 6572 206f 6620 6d65 7472 6963 7320 7065 7220 6261 7463 6829 2e18 0222 4922 4708 0111 0000 0000 0000 0040 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0040 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0040 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0040 660a 3070 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 696e 6465 7869 6e67 5f71 7565 7565 5f63 6170 6163 6974 7912 2354 6865 2063 6170 6163 6974 7920 6f66 2074 6865 2069 6e64 6578 696e 6720 7175 6575 652e 1801 220b 1209 0900 0000 0000 00d0 406d 0a2e 7072 6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 746f 7261 6765 5f69 6e64 6578 696e 675f 7175 6575 655f 6c65 6e67 7468 122c 5468 6520 6e75 6d62 6572 206f 6620 6d65 7472 6963 7320 7761 6974 696e 6720 746f 2062 6520 696e 6465 7865 642e 1801 220b 1209 0900 0000 0000 0000 0067 0a2f 7072 6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 746f 7261 6765 5f69 6e67 6573 7465 645f 7361 6d70 6c65 735f 746f 7461 6c12 2554 6865 2074 6f74 616c 206e 756d 6265 7220 6f66 2073 616d 706c 6573 2069 6e67 6573 7465 642e 1800 220b 1a09 0900 0000 0080 27cd 40c3 010a 3770 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 696e 7661 6c69 645f 7072 656c 6f61 645f 7265 7175 6573 7473 5f74 6f74 616c 1279 5468 6520 746f 7461 6c20 6e75 6d62 6572 206f 6620 7072 656c 6f61 6420 7265 7175 6573 7473 2072 6566 6572 7269 6e67 2074 6f20 6120 6e6f 6e2d 6578 6973 7465 6e74 2073 6572 6965 732e 2054 6869 7320 6973 2061 6e20 696e 6469 6361 7469 6f6e 206f 6620 6f75 7464 6174 6564 206c 6162 656c 2069 6e64 6578 6573 2e18 0022 0b1a 0909 0000 0000 0000 0000 6f0a 2a70 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 6d65 6d6f 7279 5f63 6875 6e6b 6465 7363 7312 3254 6865 2063 7572 7265 6e74 206e 756d 6265 7220 6f66 2063 6875 6e6b 2064 6573 6372 6970 746f 7273 2069 6e20 6d65 6d6f 7279 2e18 0122 0b12 0909 0000 0000 0020 8f40 9c01 0a26 7072 6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 746f 7261 6765 5f6d 656d 6f72 795f 6368 756e 6b73 1263 5468 6520 6375 7272 656e 7420 6e75 6d62 6572 206f 6620 6368 756e 6b73 2069 6e20 6d65 6d6f 7279 2c20 6578 636c 7564 696e 6720 636c 6f6e 6564 2063 6875 6e6b 7320 2869 2e65 2e20 6368 756e 6b73 2077 6974 686f 7574 2061 2064 6573 6372 6970 746f 7229 2e18 0122 0b12 0909 0000 0000 00e8 8d40 600a 2670 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 6d65 6d6f 7279 5f73 6572 6965 7312 2754 6865 2063 7572 7265 6e74 206e 756d 6265 7220 6f66 2073 6572 6965 7320 696e 206d 656d 6f72 792e 1801 220b 1209 0900 0000 0000 807a 40b7 010a 3570 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 7065 7273 6973 745f 6c61 7465 6e63 795f 6d69 6372 6f73 6563 6f6e 6473 1231 4120 7375 6d6d 6172 7920 6f66 206c 6174 656e 6369 6573 2066 6f72 2070 6572 7369 7374 696e 6720 6561 6368 2063 6875 6e6b 2e18 0222 4922 4708 6f11 1c2f dd24 e68c cc40 1a12 0900 0000 0000 00e0 3f11 8d97 6e12 8360 3e40 1a12 09cd cccc cccc ccec 3f11 0ad7 a370 3d62 6b40 1a12 09ae 47e1 7a14 aeef 3f11 7b14 ae47 e1b6 7240 6a0a 2f70 726f 6d65 7468 6575 735f 6c6f 6361 6c5f 7374 6f72 6167 655f 7065 7273 6973 745f 7175 6575 655f 6361 7061 6369 7479 1228 5468 6520 746f 7461 6c20 6361 7061 6369 7479 206f 6620 7468 6520 7065 7273 6973 7420 7175 6575 652e 1801 220b 1209 0900 0000 0000 0090 407a 0a2d 7072 6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 746f 7261 6765 5f70 6572 7369 7374 5f71 7565 7565 5f6c 656e 6774 6812 3a54 6865 2063 7572 7265 6e74 206e 756d 6265 7220 6f66 2063 6875 6e6b 7320 7761 6974 696e 6720 696e 2074 6865 2070 6572 7369 7374 2071 7565 7565 2e18 0122 0b12 0909 0000 0000 0000 0000 ac01 0a29 7072 6f6d 6574 6865 7573 5f6c 6f63 616c 5f73 746f 7261 6765 5f73 6572 6965 735f 6f70 735f 746f 7461 6c12 3454 6865 2074 6f74 616c 206e 756d 6265 7220 6f66 2073 6572 6965 7320 6f70 6572 6174 696f 6e73 2062 7920 7468 6569 7220 7479 7065 2e18 0022 1b0a 0e0a 0474 7970 6512 0663 7265 6174 651a 0909 0000 0000 0000 0040 222a 0a1d 0a04 7479 7065 1215 6d61 696e 7465 6e61 6e63 655f 696e 5f6d 656d 6f72 791a 0909 0000 0000 0000 1440 d601 0a2d 7072 6f6d 6574 6865 7573 5f6e 6f74 6966 6963 6174 696f 6e73 5f6c 6174 656e 6379 5f6d 696c 6c69 7365 636f 6e64 7312 584c 6174 656e 6379 2071 7561 6e74 696c 6573 2066 6f72 2073 656e 6469 6e67 2061 6c65 7274 206e 6f74 6966 6963 6174 696f 6e73 2028 6e6f 7420 696e 636c 7564 696e 6720 6472 6f70 7065 6420 6e6f 7469 6669 6361 7469 6f6e 7329 2e18 0222 4922 4708 0011 0000 0000 0000 0000 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0000 680a 2770 726f 6d65 7468 6575 735f 6e6f 7469 6669 6361 7469 6f6e 735f 7175 6575 655f 6361 7061 6369 7479 122e 5468 6520 6361 7061 6369 7479 206f 6620 7468 6520 616c 6572 7420 6e6f 7469 6669 6361 7469 6f6e 7320 7175 6575 652e 1801 220b 1209 0900 0000 0000 0059 4067 0a25 7072 6f6d 6574 6865 7573 5f6e 6f74 6966 6963 6174 696f 6e73 5f71 7565 7565 5f6c 656e 6774 6812 2f54 6865 206e 756d 6265 7220 6f66 2061 6c65 7274 206e 6f74 6966 6963 6174 696f 6e73 2069 6e20 7468 6520 7175 6575 652e 1801 220b 1209 0900 0000 0000 0000 009e 020a 3070 726f 6d65 7468 6575 735f 7275 6c65 5f65 7661 6c75 6174 696f 6e5f 6475 7261 7469 6f6e 5f6d 696c 6c69 7365 636f 6e64 7312 2354 6865 2064 7572 6174 696f 6e20 666f 7220 6120 7275 6c65 2074 6f20 6578 6563 7574 652e 1802 2260 0a15 0a09 7275 6c65 5f74 7970 6512 0861 6c65 7274 696e 6722 4708 3711 0000 0000 0000 2840 1a12 0900 0000 0000 00e0 3f11 0000 0000 0000 0000 1a12 09cd cccc cccc ccec 3f11 0000 0000 0000 0000 1a12 09ae 47e1 7a14 aeef 3f11 0000 0000 0000 0840 2261 0a16 0a09 7275 6c65 5f74 7970 6512 0972 6563 6f72 6469 6e67 2247 0837 1100 0000 0000 002e 401a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 0000 001a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 0008 4069 0a29 7072 6f6d 6574 6865 7573 5f72 756c 655f 6576 616c 7561 7469 6f6e 5f66 6169 6c75 7265 735f 746f 7461 6c12 2d54 6865 2074 6f74 616c 206e 756d 6265 7220 6f66 2072 756c 6520 6576 616c 7561 7469 6f6e 2066 6169 6c75 7265 732e 1800 220b 1a09 0900 0000 0000 0000 0060 0a21 7072 6f6d 6574 6865 7573 5f73 616d 706c 6573 5f71 7565 7565 5f63 6170 6163 6974 7912 2c43 6170 6163 6974 7920 6f66 2074 6865 2071 7565 7565 2066 6f72 2075 6e77 7269 7474 656e 2073 616d 706c 6573 2e18 0122 0b12 0909 0000 0000 0000 b040 da01 0a1f 7072 6f6d 6574 6865 7573 5f73 616d 706c 6573 5f71 7565 7565 5f6c 656e 6774 6812 a701 4375 7272 656e 7420 6e75 6d62 6572 206f 6620 6974 656d 7320 696e 2074 6865 2071 7565 7565 2066 6f72 2075 6e77 7269 7474 656e 2073 616d 706c 6573 2e20 4561 6368 2069 7465 6d20 636f 6d70 7269 7365 7320 616c 6c20 7361 6d70 6c65 7320 6578 706f 7365 6420 6279 206f 6e65 2074 6172 6765 7420 6173 206f 6e65 206d 6574 7269 6320 6661 6d69 6c79 2028 692e 652e 206d 6574 7269 6373 206f 6620 7468 6520 7361 6d65 206e 616d 6529 2e18 0122 0b12 0909 0000 0000 0000 0000 d902 0a29 7072 6f6d 6574 6865 7573 5f74 6172 6765 745f 696e 7465 7276 616c 5f6c 656e 6774 685f 7365 636f 6e64 7312 2141 6374 7561 6c20 696e 7465 7276 616c 7320 6265 7477 6565 6e20 7363 7261 7065 732e 1802 2282 010a 0f0a 0869 6e74 6572 7661 6c12 0331 3573 226f 0804 1100 0000 0000 804d 401a 1209 7b14 ae47 e17a 843f 1100 0000 0000 002c 401a 1209 9a99 9999 9999 a93f 1100 0000 0000 002c 401a 1209 0000 0000 0000 e03f 1100 0000 0000 002e 401a 1209 cdcc cccc cccc ec3f 1100 0000 0000 002e 401a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 002e 4022 8101 0a0e 0a08 696e 7465 7276 616c 1202 3173 226f 083a 1100 0000 0000 003c 401a 1209 7b14 ae47 e17a 843f 1100 0000 0000 0000 001a 1209 9a99 9999 9999 a93f 1100 0000 0000 0000 001a 1209 0000 0000 0000 e03f 1100 0000 0000 0000 001a 1209 cdcc cccc cccc ec3f 1100 0000 0000 00f0 3f1a 1209 ae47 e17a 14ae ef3f 1100 0000 0000 00f0 3f ================================================ FILE: vendor/github.com/prometheus/common/expfmt/testdata/text ================================================ # HELP http_request_duration_microseconds The HTTP request latencies in microseconds. # TYPE http_request_duration_microseconds summary http_request_duration_microseconds{handler="/",quantile="0.5"} 0 http_request_duration_microseconds{handler="/",quantile="0.9"} 0 http_request_duration_microseconds{handler="/",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/"} 0 http_request_duration_microseconds_count{handler="/"} 0 http_request_duration_microseconds{handler="/alerts",quantile="0.5"} 0 http_request_duration_microseconds{handler="/alerts",quantile="0.9"} 0 http_request_duration_microseconds{handler="/alerts",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/alerts"} 0 http_request_duration_microseconds_count{handler="/alerts"} 0 http_request_duration_microseconds{handler="/api/metrics",quantile="0.5"} 0 http_request_duration_microseconds{handler="/api/metrics",quantile="0.9"} 0 http_request_duration_microseconds{handler="/api/metrics",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/api/metrics"} 0 http_request_duration_microseconds_count{handler="/api/metrics"} 0 http_request_duration_microseconds{handler="/api/query",quantile="0.5"} 0 http_request_duration_microseconds{handler="/api/query",quantile="0.9"} 0 http_request_duration_microseconds{handler="/api/query",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/api/query"} 0 http_request_duration_microseconds_count{handler="/api/query"} 0 http_request_duration_microseconds{handler="/api/query_range",quantile="0.5"} 0 http_request_duration_microseconds{handler="/api/query_range",quantile="0.9"} 0 http_request_duration_microseconds{handler="/api/query_range",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/api/query_range"} 0 http_request_duration_microseconds_count{handler="/api/query_range"} 0 http_request_duration_microseconds{handler="/api/targets",quantile="0.5"} 0 http_request_duration_microseconds{handler="/api/targets",quantile="0.9"} 0 http_request_duration_microseconds{handler="/api/targets",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/api/targets"} 0 http_request_duration_microseconds_count{handler="/api/targets"} 0 http_request_duration_microseconds{handler="/consoles/",quantile="0.5"} 0 http_request_duration_microseconds{handler="/consoles/",quantile="0.9"} 0 http_request_duration_microseconds{handler="/consoles/",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/consoles/"} 0 http_request_duration_microseconds_count{handler="/consoles/"} 0 http_request_duration_microseconds{handler="/graph",quantile="0.5"} 0 http_request_duration_microseconds{handler="/graph",quantile="0.9"} 0 http_request_duration_microseconds{handler="/graph",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/graph"} 0 http_request_duration_microseconds_count{handler="/graph"} 0 http_request_duration_microseconds{handler="/heap",quantile="0.5"} 0 http_request_duration_microseconds{handler="/heap",quantile="0.9"} 0 http_request_duration_microseconds{handler="/heap",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/heap"} 0 http_request_duration_microseconds_count{handler="/heap"} 0 http_request_duration_microseconds{handler="/static/",quantile="0.5"} 0 http_request_duration_microseconds{handler="/static/",quantile="0.9"} 0 http_request_duration_microseconds{handler="/static/",quantile="0.99"} 0 http_request_duration_microseconds_sum{handler="/static/"} 0 http_request_duration_microseconds_count{handler="/static/"} 0 http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 1307.275 http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 1858.632 http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 3087.384 http_request_duration_microseconds_sum{handler="prometheus"} 179886.5000000001 http_request_duration_microseconds_count{handler="prometheus"} 119 # HELP http_request_size_bytes The HTTP request sizes in bytes. # TYPE http_request_size_bytes summary http_request_size_bytes{handler="/",quantile="0.5"} 0 http_request_size_bytes{handler="/",quantile="0.9"} 0 http_request_size_bytes{handler="/",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/"} 0 http_request_size_bytes_count{handler="/"} 0 http_request_size_bytes{handler="/alerts",quantile="0.5"} 0 http_request_size_bytes{handler="/alerts",quantile="0.9"} 0 http_request_size_bytes{handler="/alerts",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/alerts"} 0 http_request_size_bytes_count{handler="/alerts"} 0 http_request_size_bytes{handler="/api/metrics",quantile="0.5"} 0 http_request_size_bytes{handler="/api/metrics",quantile="0.9"} 0 http_request_size_bytes{handler="/api/metrics",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/api/metrics"} 0 http_request_size_bytes_count{handler="/api/metrics"} 0 http_request_size_bytes{handler="/api/query",quantile="0.5"} 0 http_request_size_bytes{handler="/api/query",quantile="0.9"} 0 http_request_size_bytes{handler="/api/query",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/api/query"} 0 http_request_size_bytes_count{handler="/api/query"} 0 http_request_size_bytes{handler="/api/query_range",quantile="0.5"} 0 http_request_size_bytes{handler="/api/query_range",quantile="0.9"} 0 http_request_size_bytes{handler="/api/query_range",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/api/query_range"} 0 http_request_size_bytes_count{handler="/api/query_range"} 0 http_request_size_bytes{handler="/api/targets",quantile="0.5"} 0 http_request_size_bytes{handler="/api/targets",quantile="0.9"} 0 http_request_size_bytes{handler="/api/targets",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/api/targets"} 0 http_request_size_bytes_count{handler="/api/targets"} 0 http_request_size_bytes{handler="/consoles/",quantile="0.5"} 0 http_request_size_bytes{handler="/consoles/",quantile="0.9"} 0 http_request_size_bytes{handler="/consoles/",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/consoles/"} 0 http_request_size_bytes_count{handler="/consoles/"} 0 http_request_size_bytes{handler="/graph",quantile="0.5"} 0 http_request_size_bytes{handler="/graph",quantile="0.9"} 0 http_request_size_bytes{handler="/graph",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/graph"} 0 http_request_size_bytes_count{handler="/graph"} 0 http_request_size_bytes{handler="/heap",quantile="0.5"} 0 http_request_size_bytes{handler="/heap",quantile="0.9"} 0 http_request_size_bytes{handler="/heap",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/heap"} 0 http_request_size_bytes_count{handler="/heap"} 0 http_request_size_bytes{handler="/static/",quantile="0.5"} 0 http_request_size_bytes{handler="/static/",quantile="0.9"} 0 http_request_size_bytes{handler="/static/",quantile="0.99"} 0 http_request_size_bytes_sum{handler="/static/"} 0 http_request_size_bytes_count{handler="/static/"} 0 http_request_size_bytes{handler="prometheus",quantile="0.5"} 291 http_request_size_bytes{handler="prometheus",quantile="0.9"} 291 http_request_size_bytes{handler="prometheus",quantile="0.99"} 291 http_request_size_bytes_sum{handler="prometheus"} 34488 http_request_size_bytes_count{handler="prometheus"} 119 # HELP http_requests_total Total number of HTTP requests made. # TYPE http_requests_total counter http_requests_total{code="200",handler="prometheus",method="get"} 119 # HELP http_response_size_bytes The HTTP response sizes in bytes. # TYPE http_response_size_bytes summary http_response_size_bytes{handler="/",quantile="0.5"} 0 http_response_size_bytes{handler="/",quantile="0.9"} 0 http_response_size_bytes{handler="/",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/"} 0 http_response_size_bytes_count{handler="/"} 0 http_response_size_bytes{handler="/alerts",quantile="0.5"} 0 http_response_size_bytes{handler="/alerts",quantile="0.9"} 0 http_response_size_bytes{handler="/alerts",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/alerts"} 0 http_response_size_bytes_count{handler="/alerts"} 0 http_response_size_bytes{handler="/api/metrics",quantile="0.5"} 0 http_response_size_bytes{handler="/api/metrics",quantile="0.9"} 0 http_response_size_bytes{handler="/api/metrics",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/api/metrics"} 0 http_response_size_bytes_count{handler="/api/metrics"} 0 http_response_size_bytes{handler="/api/query",quantile="0.5"} 0 http_response_size_bytes{handler="/api/query",quantile="0.9"} 0 http_response_size_bytes{handler="/api/query",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/api/query"} 0 http_response_size_bytes_count{handler="/api/query"} 0 http_response_size_bytes{handler="/api/query_range",quantile="0.5"} 0 http_response_size_bytes{handler="/api/query_range",quantile="0.9"} 0 http_response_size_bytes{handler="/api/query_range",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/api/query_range"} 0 http_response_size_bytes_count{handler="/api/query_range"} 0 http_response_size_bytes{handler="/api/targets",quantile="0.5"} 0 http_response_size_bytes{handler="/api/targets",quantile="0.9"} 0 http_response_size_bytes{handler="/api/targets",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/api/targets"} 0 http_response_size_bytes_count{handler="/api/targets"} 0 http_response_size_bytes{handler="/consoles/",quantile="0.5"} 0 http_response_size_bytes{handler="/consoles/",quantile="0.9"} 0 http_response_size_bytes{handler="/consoles/",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/consoles/"} 0 http_response_size_bytes_count{handler="/consoles/"} 0 http_response_size_bytes{handler="/graph",quantile="0.5"} 0 http_response_size_bytes{handler="/graph",quantile="0.9"} 0 http_response_size_bytes{handler="/graph",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/graph"} 0 http_response_size_bytes_count{handler="/graph"} 0 http_response_size_bytes{handler="/heap",quantile="0.5"} 0 http_response_size_bytes{handler="/heap",quantile="0.9"} 0 http_response_size_bytes{handler="/heap",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/heap"} 0 http_response_size_bytes_count{handler="/heap"} 0 http_response_size_bytes{handler="/static/",quantile="0.5"} 0 http_response_size_bytes{handler="/static/",quantile="0.9"} 0 http_response_size_bytes{handler="/static/",quantile="0.99"} 0 http_response_size_bytes_sum{handler="/static/"} 0 http_response_size_bytes_count{handler="/static/"} 0 http_response_size_bytes{handler="prometheus",quantile="0.5"} 2049 http_response_size_bytes{handler="prometheus",quantile="0.9"} 2058 http_response_size_bytes{handler="prometheus",quantile="0.99"} 2064 http_response_size_bytes_sum{handler="prometheus"} 247001 http_response_size_bytes_count{handler="prometheus"} 119 # HELP process_cpu_seconds_total Total user and system CPU time spent in seconds. # TYPE process_cpu_seconds_total counter process_cpu_seconds_total 0.55 # HELP go_goroutines Number of goroutines that currently exist. # TYPE go_goroutines gauge go_goroutines 70 # HELP process_max_fds Maximum number of open file descriptors. # TYPE process_max_fds gauge process_max_fds 8192 # HELP process_open_fds Number of open file descriptors. # TYPE process_open_fds gauge process_open_fds 29 # HELP process_resident_memory_bytes Resident memory size in bytes. # TYPE process_resident_memory_bytes gauge process_resident_memory_bytes 5.3870592e+07 # HELP process_start_time_seconds Start time of the process since unix epoch in seconds. # TYPE process_start_time_seconds gauge process_start_time_seconds 1.42236894836e+09 # HELP process_virtual_memory_bytes Virtual memory size in bytes. # TYPE process_virtual_memory_bytes gauge process_virtual_memory_bytes 5.41478912e+08 # HELP prometheus_dns_sd_lookup_failures_total The number of DNS-SD lookup failures. # TYPE prometheus_dns_sd_lookup_failures_total counter prometheus_dns_sd_lookup_failures_total 0 # HELP prometheus_dns_sd_lookups_total The number of DNS-SD lookups. # TYPE prometheus_dns_sd_lookups_total counter prometheus_dns_sd_lookups_total 7 # HELP prometheus_evaluator_duration_milliseconds The duration for all evaluations to execute. # TYPE prometheus_evaluator_duration_milliseconds summary prometheus_evaluator_duration_milliseconds{quantile="0.01"} 0 prometheus_evaluator_duration_milliseconds{quantile="0.05"} 0 prometheus_evaluator_duration_milliseconds{quantile="0.5"} 0 prometheus_evaluator_duration_milliseconds{quantile="0.9"} 1 prometheus_evaluator_duration_milliseconds{quantile="0.99"} 1 prometheus_evaluator_duration_milliseconds_sum 12 prometheus_evaluator_duration_milliseconds_count 23 # HELP prometheus_local_storage_checkpoint_duration_milliseconds The duration (in milliseconds) it took to checkpoint in-memory metrics and head chunks. # TYPE prometheus_local_storage_checkpoint_duration_milliseconds gauge prometheus_local_storage_checkpoint_duration_milliseconds 0 # HELP prometheus_local_storage_chunk_ops_total The total number of chunk operations by their type. # TYPE prometheus_local_storage_chunk_ops_total counter prometheus_local_storage_chunk_ops_total{type="create"} 598 prometheus_local_storage_chunk_ops_total{type="persist"} 174 prometheus_local_storage_chunk_ops_total{type="pin"} 920 prometheus_local_storage_chunk_ops_total{type="transcode"} 415 prometheus_local_storage_chunk_ops_total{type="unpin"} 920 # HELP prometheus_local_storage_indexing_batch_latency_milliseconds Quantiles for batch indexing latencies in milliseconds. # TYPE prometheus_local_storage_indexing_batch_latency_milliseconds summary prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.5"} 0 prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.9"} 0 prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.99"} 0 prometheus_local_storage_indexing_batch_latency_milliseconds_sum 0 prometheus_local_storage_indexing_batch_latency_milliseconds_count 1 # HELP prometheus_local_storage_indexing_batch_sizes Quantiles for indexing batch sizes (number of metrics per batch). # TYPE prometheus_local_storage_indexing_batch_sizes summary prometheus_local_storage_indexing_batch_sizes{quantile="0.5"} 2 prometheus_local_storage_indexing_batch_sizes{quantile="0.9"} 2 prometheus_local_storage_indexing_batch_sizes{quantile="0.99"} 2 prometheus_local_storage_indexing_batch_sizes_sum 2 prometheus_local_storage_indexing_batch_sizes_count 1 # HELP prometheus_local_storage_indexing_queue_capacity The capacity of the indexing queue. # TYPE prometheus_local_storage_indexing_queue_capacity gauge prometheus_local_storage_indexing_queue_capacity 16384 # HELP prometheus_local_storage_indexing_queue_length The number of metrics waiting to be indexed. # TYPE prometheus_local_storage_indexing_queue_length gauge prometheus_local_storage_indexing_queue_length 0 # HELP prometheus_local_storage_ingested_samples_total The total number of samples ingested. # TYPE prometheus_local_storage_ingested_samples_total counter prometheus_local_storage_ingested_samples_total 30473 # HELP prometheus_local_storage_invalid_preload_requests_total The total number of preload requests referring to a non-existent series. This is an indication of outdated label indexes. # TYPE prometheus_local_storage_invalid_preload_requests_total counter prometheus_local_storage_invalid_preload_requests_total 0 # HELP prometheus_local_storage_memory_chunkdescs The current number of chunk descriptors in memory. # TYPE prometheus_local_storage_memory_chunkdescs gauge prometheus_local_storage_memory_chunkdescs 1059 # HELP prometheus_local_storage_memory_chunks The current number of chunks in memory, excluding cloned chunks (i.e. chunks without a descriptor). # TYPE prometheus_local_storage_memory_chunks gauge prometheus_local_storage_memory_chunks 1020 # HELP prometheus_local_storage_memory_series The current number of series in memory. # TYPE prometheus_local_storage_memory_series gauge prometheus_local_storage_memory_series 424 # HELP prometheus_local_storage_persist_latency_microseconds A summary of latencies for persisting each chunk. # TYPE prometheus_local_storage_persist_latency_microseconds summary prometheus_local_storage_persist_latency_microseconds{quantile="0.5"} 30.377 prometheus_local_storage_persist_latency_microseconds{quantile="0.9"} 203.539 prometheus_local_storage_persist_latency_microseconds{quantile="0.99"} 2626.463 prometheus_local_storage_persist_latency_microseconds_sum 20424.415 prometheus_local_storage_persist_latency_microseconds_count 174 # HELP prometheus_local_storage_persist_queue_capacity The total capacity of the persist queue. # TYPE prometheus_local_storage_persist_queue_capacity gauge prometheus_local_storage_persist_queue_capacity 1024 # HELP prometheus_local_storage_persist_queue_length The current number of chunks waiting in the persist queue. # TYPE prometheus_local_storage_persist_queue_length gauge prometheus_local_storage_persist_queue_length 0 # HELP prometheus_local_storage_series_ops_total The total number of series operations by their type. # TYPE prometheus_local_storage_series_ops_total counter prometheus_local_storage_series_ops_total{type="create"} 2 prometheus_local_storage_series_ops_total{type="maintenance_in_memory"} 11 # HELP prometheus_notifications_latency_milliseconds Latency quantiles for sending alert notifications (not including dropped notifications). # TYPE prometheus_notifications_latency_milliseconds summary prometheus_notifications_latency_milliseconds{quantile="0.5"} 0 prometheus_notifications_latency_milliseconds{quantile="0.9"} 0 prometheus_notifications_latency_milliseconds{quantile="0.99"} 0 prometheus_notifications_latency_milliseconds_sum 0 prometheus_notifications_latency_milliseconds_count 0 # HELP prometheus_notifications_queue_capacity The capacity of the alert notifications queue. # TYPE prometheus_notifications_queue_capacity gauge prometheus_notifications_queue_capacity 100 # HELP prometheus_notifications_queue_length The number of alert notifications in the queue. # TYPE prometheus_notifications_queue_length gauge prometheus_notifications_queue_length 0 # HELP prometheus_rule_evaluation_duration_milliseconds The duration for a rule to execute. # TYPE prometheus_rule_evaluation_duration_milliseconds summary prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.5"} 0 prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.9"} 0 prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.99"} 2 prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="alerting"} 12 prometheus_rule_evaluation_duration_milliseconds_count{rule_type="alerting"} 115 prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.5"} 0 prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.9"} 0 prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.99"} 3 prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="recording"} 15 prometheus_rule_evaluation_duration_milliseconds_count{rule_type="recording"} 115 # HELP prometheus_rule_evaluation_failures_total The total number of rule evaluation failures. # TYPE prometheus_rule_evaluation_failures_total counter prometheus_rule_evaluation_failures_total 0 # HELP prometheus_samples_queue_capacity Capacity of the queue for unwritten samples. # TYPE prometheus_samples_queue_capacity gauge prometheus_samples_queue_capacity 4096 # HELP prometheus_samples_queue_length Current number of items in the queue for unwritten samples. Each item comprises all samples exposed by one target as one metric family (i.e. metrics of the same name). # TYPE prometheus_samples_queue_length gauge prometheus_samples_queue_length 0 # HELP prometheus_target_interval_length_seconds Actual intervals between scrapes. # TYPE prometheus_target_interval_length_seconds summary prometheus_target_interval_length_seconds{interval="15s",quantile="0.01"} 14 prometheus_target_interval_length_seconds{interval="15s",quantile="0.05"} 14 prometheus_target_interval_length_seconds{interval="15s",quantile="0.5"} 15 prometheus_target_interval_length_seconds{interval="15s",quantile="0.9"} 15 prometheus_target_interval_length_seconds{interval="15s",quantile="0.99"} 15 prometheus_target_interval_length_seconds_sum{interval="15s"} 175 prometheus_target_interval_length_seconds_count{interval="15s"} 12 prometheus_target_interval_length_seconds{interval="1s",quantile="0.01"} 0 prometheus_target_interval_length_seconds{interval="1s",quantile="0.05"} 0 prometheus_target_interval_length_seconds{interval="1s",quantile="0.5"} 0 prometheus_target_interval_length_seconds{interval="1s",quantile="0.9"} 1 prometheus_target_interval_length_seconds{interval="1s",quantile="0.99"} 1 prometheus_target_interval_length_seconds_sum{interval="1s"} 55 prometheus_target_interval_length_seconds_count{interval="1s"} 117 ================================================ FILE: vendor/github.com/prometheus/common/expfmt/text_create.go ================================================ // 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 ( "bytes" "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 } // escapeString replaces '\' by '\\', new line character by '\n', and - if // includeDoubleQuote is true - '"' by '\"'. func escapeString(v string, includeDoubleQuote bool) string { result := bytes.NewBuffer(make([]byte, 0, len(v))) for _, c := range v { switch { case c == '\\': result.WriteString(`\\`) case includeDoubleQuote && c == '"': result.WriteString(`\"`) case c == '\n': result.WriteString(`\n`) default: result.WriteRune(c) } } return result.String() } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/text_create_test.go ================================================ // 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 ( "bytes" "math" "strings" "testing" "github.com/golang/protobuf/proto" dto "github.com/prometheus/client_model/go" ) func testCreate(t testing.TB) { var scenarios = []struct { in *dto.MetricFamily out string }{ // 0: Counter, NaN as value, timestamp given. { in: &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("two-line\n doc str\\ing"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("labelname"), Value: proto.String("val1"), }, &dto.LabelPair{ Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(math.NaN()), }, }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("labelname"), Value: proto.String("val2"), }, &dto.LabelPair{ Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(.23), }, TimestampMs: proto.Int64(1234567890), }, }, }, out: `# HELP name two-line\n doc str\\ing # TYPE name counter name{labelname="val1",basename="basevalue"} NaN name{labelname="val2",basename="basevalue"} 0.23 1234567890 `, }, // 1: Gauge, some escaping required, +Inf as value, multi-byte characters in label values. { in: &dto.MetricFamily{ Name: proto.String("gauge_name"), Help: proto.String("gauge\ndoc\nstr\"ing"), Type: dto.MetricType_GAUGE.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("name_1"), Value: proto.String("val with\nnew line"), }, &dto.LabelPair{ Name: proto.String("name_2"), Value: proto.String("val with \\backslash and \"quotes\""), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(math.Inf(+1)), }, }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("name_1"), Value: proto.String("Björn"), }, &dto.LabelPair{ Name: proto.String("name_2"), Value: proto.String("佖佥"), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(3.14E42), }, }, }, }, out: `# HELP gauge_name gauge\ndoc\nstr"ing # TYPE gauge_name gauge gauge_name{name_1="val with\nnew line",name_2="val with \\backslash and \"quotes\""} +Inf gauge_name{name_1="Björn",name_2="佖佥"} 3.14e+42 `, }, // 2: Untyped, no help, one sample with no labels and -Inf as value, another sample with one label. { in: &dto.MetricFamily{ Name: proto.String("untyped_name"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(math.Inf(-1)), }, }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("name_1"), Value: proto.String("value 1"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(-1.23e-45), }, }, }, }, out: `# TYPE untyped_name untyped untyped_name -Inf untyped_name{name_1="value 1"} -1.23e-45 `, }, // 3: Summary. { in: &dto.MetricFamily{ Name: proto.String("summary_name"), Help: proto.String("summary docstring"), Type: dto.MetricType_SUMMARY.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Summary: &dto.Summary{ SampleCount: proto.Uint64(42), SampleSum: proto.Float64(-3.4567), Quantile: []*dto.Quantile{ &dto.Quantile{ Quantile: proto.Float64(0.5), Value: proto.Float64(-1.23), }, &dto.Quantile{ Quantile: proto.Float64(0.9), Value: proto.Float64(.2342354), }, &dto.Quantile{ Quantile: proto.Float64(0.99), Value: proto.Float64(0), }, }, }, }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("name_1"), Value: proto.String("value 1"), }, &dto.LabelPair{ Name: proto.String("name_2"), Value: proto.String("value 2"), }, }, Summary: &dto.Summary{ SampleCount: proto.Uint64(4711), SampleSum: proto.Float64(2010.1971), Quantile: []*dto.Quantile{ &dto.Quantile{ Quantile: proto.Float64(0.5), Value: proto.Float64(1), }, &dto.Quantile{ Quantile: proto.Float64(0.9), Value: proto.Float64(2), }, &dto.Quantile{ Quantile: proto.Float64(0.99), Value: proto.Float64(3), }, }, }, }, }, }, out: `# HELP summary_name summary docstring # TYPE summary_name summary summary_name{quantile="0.5"} -1.23 summary_name{quantile="0.9"} 0.2342354 summary_name{quantile="0.99"} 0 summary_name_sum -3.4567 summary_name_count 42 summary_name{name_1="value 1",name_2="value 2",quantile="0.5"} 1 summary_name{name_1="value 1",name_2="value 2",quantile="0.9"} 2 summary_name{name_1="value 1",name_2="value 2",quantile="0.99"} 3 summary_name_sum{name_1="value 1",name_2="value 2"} 2010.1971 summary_name_count{name_1="value 1",name_2="value 2"} 4711 `, }, // 4: Histogram { in: &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ &dto.Bucket{ UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, &dto.Bucket{ UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, &dto.Bucket{ UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, &dto.Bucket{ UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, &dto.Bucket{ UpperBound: proto.Float64(math.Inf(+1)), CumulativeCount: proto.Uint64(2693), }, }, }, }, }, }, out: `# HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100"} 123 request_duration_microseconds_bucket{le="120"} 412 request_duration_microseconds_bucket{le="144"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 `, }, // 5: Histogram with missing +Inf bucket. { in: &dto.MetricFamily{ Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ &dto.Bucket{ UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, &dto.Bucket{ UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, &dto.Bucket{ UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, &dto.Bucket{ UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, }, }, }, }, }, out: `# HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100"} 123 request_duration_microseconds_bucket{le="120"} 412 request_duration_microseconds_bucket{le="144"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 `, }, // 6: No metric type, should result in default type Counter. { in: &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("doc string"), Metric: []*dto.Metric{ &dto.Metric{ Counter: &dto.Counter{ Value: proto.Float64(math.Inf(-1)), }, }, }, }, out: `# HELP name doc string # TYPE name counter name -Inf `, }, } for i, scenario := range scenarios { out := bytes.NewBuffer(make([]byte, 0, len(scenario.out))) n, err := MetricFamilyToText(out, scenario.in) if err != nil { t.Errorf("%d. error: %s", i, err) continue } if expected, got := len(scenario.out), n; expected != got { t.Errorf( "%d. expected %d bytes written, got %d", i, expected, got, ) } if expected, got := scenario.out, out.String(); expected != got { t.Errorf( "%d. expected out=%q, got %q", i, expected, got, ) } } } func TestCreate(t *testing.T) { testCreate(t) } func BenchmarkCreate(b *testing.B) { for i := 0; i < b.N; i++ { testCreate(b) } } func testCreateError(t testing.TB) { var scenarios = []struct { in *dto.MetricFamily err string }{ // 0: No metric. { in: &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{}, }, err: "MetricFamily has no metrics", }, // 1: No metric name. { in: &dto.MetricFamily{ Help: proto.String("doc string"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(math.Inf(-1)), }, }, }, }, err: "MetricFamily has no name", }, // 2: Wrong type. { in: &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("doc string"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(math.Inf(-1)), }, }, }, }, err: "expected counter in metric", }, } for i, scenario := range scenarios { var out bytes.Buffer _, err := MetricFamilyToText(&out, scenario.in) if err == nil { t.Errorf("%d. expected error, got nil", i) continue } if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { t.Errorf( "%d. expected error starting with %q, got %q", i, expected, got, ) } } } func TestCreateError(t *testing.T) { testCreateError(t) } func BenchmarkCreateError(b *testing.B) { for i := 0; i < b.N; i++ { testCreateError(b) } } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/text_parse.go ================================================ // 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) } } 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 } } ================================================ FILE: vendor/github.com/prometheus/common/expfmt/text_parse_test.go ================================================ // 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 ( "math" "strings" "testing" "github.com/golang/protobuf/proto" dto "github.com/prometheus/client_model/go" ) func testTextParse(t testing.TB) { var scenarios = []struct { in string out []*dto.MetricFamily }{ // 0: Empty lines as input. { in: ` `, out: []*dto.MetricFamily{}, }, // 1: Minimal case. { in: ` minimal_metric 1.234 another_metric -3e3 103948 # Even that: no_labels{} 3 # HELP line for non-existing metric will be ignored. `, out: []*dto.MetricFamily{ &dto.MetricFamily{ Name: proto.String("minimal_metric"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(1.234), }, }, }, }, &dto.MetricFamily{ Name: proto.String("another_metric"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(-3e3), }, TimestampMs: proto.Int64(103948), }, }, }, &dto.MetricFamily{ Name: proto.String("no_labels"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(3), }, }, }, }, }, }, // 2: Counters & gauges, docstrings, various whitespace, escape sequences. { in: ` # A normal comment. # # TYPE name counter name{labelname="val1",basename="basevalue"} NaN name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890 # HELP name two-line\n doc str\\ing # HELP name2 doc str"ing 2 # TYPE name2 gauge name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321 name2{ labelname = "val1" , }-Inf `, out: []*dto.MetricFamily{ &dto.MetricFamily{ Name: proto.String("name"), Help: proto.String("two-line\n doc str\\ing"), Type: dto.MetricType_COUNTER.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("labelname"), Value: proto.String("val1"), }, &dto.LabelPair{ Name: proto.String("basename"), Value: proto.String("basevalue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(math.NaN()), }, }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("labelname"), Value: proto.String("val2"), }, &dto.LabelPair{ Name: proto.String("basename"), Value: proto.String("base\"v\\al\nue"), }, }, Counter: &dto.Counter{ Value: proto.Float64(.23), }, TimestampMs: proto.Int64(1234567890), }, }, }, &dto.MetricFamily{ Name: proto.String("name2"), Help: proto.String("doc str\"ing 2"), Type: dto.MetricType_GAUGE.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("labelname"), Value: proto.String("val2"), }, &dto.LabelPair{ Name: proto.String("basename"), Value: proto.String("basevalue2"), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(math.Inf(+1)), }, TimestampMs: proto.Int64(54321), }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("labelname"), Value: proto.String("val1"), }, }, Gauge: &dto.Gauge{ Value: proto.Float64(math.Inf(-1)), }, }, }, }, }, }, // 3: The evil summary, mixed with other types and funny comments. { in: ` # TYPE my_summary summary my_summary{n1="val1",quantile="0.5"} 110 decoy -1 -2 my_summary{n1="val1",quantile="0.9"} 140 1 my_summary_count{n1="val1"} 42 # Latest timestamp wins in case of a summary. my_summary_sum{n1="val1"} 4711 2 fake_sum{n1="val1"} 2001 # TYPE another_summary summary another_summary_count{n2="val2",n1="val1"} 20 my_summary_count{n2="val2",n1="val1"} 5 5 another_summary{n1="val1",n2="val2",quantile=".3"} -1.2 my_summary_sum{n1="val2"} 08 15 my_summary{n1="val3", quantile="0.2"} 4711 my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN # some # funny comments # HELP # HELP # HELP my_summary # HELP my_summary `, out: []*dto.MetricFamily{ &dto.MetricFamily{ Name: proto.String("fake_sum"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("n1"), Value: proto.String("val1"), }, }, Untyped: &dto.Untyped{ Value: proto.Float64(2001), }, }, }, }, &dto.MetricFamily{ Name: proto.String("decoy"), Type: dto.MetricType_UNTYPED.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Untyped: &dto.Untyped{ Value: proto.Float64(-1), }, TimestampMs: proto.Int64(-2), }, }, }, &dto.MetricFamily{ Name: proto.String("my_summary"), Type: dto.MetricType_SUMMARY.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("n1"), Value: proto.String("val1"), }, }, Summary: &dto.Summary{ SampleCount: proto.Uint64(42), SampleSum: proto.Float64(4711), Quantile: []*dto.Quantile{ &dto.Quantile{ Quantile: proto.Float64(0.5), Value: proto.Float64(110), }, &dto.Quantile{ Quantile: proto.Float64(0.9), Value: proto.Float64(140), }, }, }, TimestampMs: proto.Int64(2), }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("n2"), Value: proto.String("val2"), }, &dto.LabelPair{ Name: proto.String("n1"), Value: proto.String("val1"), }, }, Summary: &dto.Summary{ SampleCount: proto.Uint64(5), Quantile: []*dto.Quantile{ &dto.Quantile{ Quantile: proto.Float64(-12.34), Value: proto.Float64(math.NaN()), }, }, }, TimestampMs: proto.Int64(5), }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("n1"), Value: proto.String("val2"), }, }, Summary: &dto.Summary{ SampleSum: proto.Float64(8), }, TimestampMs: proto.Int64(15), }, &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("n1"), Value: proto.String("val3"), }, }, Summary: &dto.Summary{ Quantile: []*dto.Quantile{ &dto.Quantile{ Quantile: proto.Float64(0.2), Value: proto.Float64(4711), }, }, }, }, }, }, &dto.MetricFamily{ Name: proto.String("another_summary"), Type: dto.MetricType_SUMMARY.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Label: []*dto.LabelPair{ &dto.LabelPair{ Name: proto.String("n2"), Value: proto.String("val2"), }, &dto.LabelPair{ Name: proto.String("n1"), Value: proto.String("val1"), }, }, Summary: &dto.Summary{ SampleCount: proto.Uint64(20), Quantile: []*dto.Quantile{ &dto.Quantile{ Quantile: proto.Float64(0.3), Value: proto.Float64(-1.2), }, }, }, }, }, }, }, }, // 4: The histogram. { in: ` # HELP request_duration_microseconds The response latency. # TYPE request_duration_microseconds histogram request_duration_microseconds_bucket{le="100"} 123 request_duration_microseconds_bucket{le="120"} 412 request_duration_microseconds_bucket{le="144"} 592 request_duration_microseconds_bucket{le="172.8"} 1524 request_duration_microseconds_bucket{le="+Inf"} 2693 request_duration_microseconds_sum 1.7560473e+06 request_duration_microseconds_count 2693 `, out: []*dto.MetricFamily{ { Name: proto.String("request_duration_microseconds"), Help: proto.String("The response latency."), Type: dto.MetricType_HISTOGRAM.Enum(), Metric: []*dto.Metric{ &dto.Metric{ Histogram: &dto.Histogram{ SampleCount: proto.Uint64(2693), SampleSum: proto.Float64(1756047.3), Bucket: []*dto.Bucket{ &dto.Bucket{ UpperBound: proto.Float64(100), CumulativeCount: proto.Uint64(123), }, &dto.Bucket{ UpperBound: proto.Float64(120), CumulativeCount: proto.Uint64(412), }, &dto.Bucket{ UpperBound: proto.Float64(144), CumulativeCount: proto.Uint64(592), }, &dto.Bucket{ UpperBound: proto.Float64(172.8), CumulativeCount: proto.Uint64(1524), }, &dto.Bucket{ UpperBound: proto.Float64(math.Inf(+1)), CumulativeCount: proto.Uint64(2693), }, }, }, }, }, }, }, }, } for i, scenario := range scenarios { out, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) if err != nil { t.Errorf("%d. error: %s", i, err) continue } if expected, got := len(scenario.out), len(out); expected != got { t.Errorf( "%d. expected %d MetricFamilies, got %d", i, expected, got, ) } for _, expected := range scenario.out { got, ok := out[expected.GetName()] if !ok { t.Errorf( "%d. expected MetricFamily %q, found none", i, expected.GetName(), ) continue } if expected.String() != got.String() { t.Errorf( "%d. expected MetricFamily %s, got %s", i, expected, got, ) } } } } func TestTextParse(t *testing.T) { testTextParse(t) } func BenchmarkTextParse(b *testing.B) { for i := 0; i < b.N; i++ { testTextParse(b) } } func testTextParseError(t testing.TB) { var scenarios = []struct { in string err string }{ // 0: No new-line at end of input. { in: `bla 3.14`, err: "EOF", }, // 1: Invalid escape sequence in label value. { in: `metric{label="\t"} 3.14`, err: "text format parsing error in line 1: invalid escape sequence", }, // 2: Newline in label value. { in: ` metric{label="new line"} 3.14 `, err: `text format parsing error in line 2: label value "new" contains unescaped new-line`, }, // 3: { in: `metric{@="bla"} 3.14`, err: "text format parsing error in line 1: invalid label name for metric", }, // 4: { in: `metric{__name__="bla"} 3.14`, err: `text format parsing error in line 1: label name "__name__" is reserved`, }, // 5: { in: `metric{label+="bla"} 3.14`, err: "text format parsing error in line 1: expected '=' after label name", }, // 6: { in: `metric{label=bla} 3.14`, err: "text format parsing error in line 1: expected '\"' at start of label value", }, // 7: { in: ` # TYPE metric summary metric{quantile="bla"} 3.14 `, err: "text format parsing error in line 3: expected float as value for 'quantile' label", }, // 8: { in: `metric{label="bla"+} 3.14`, err: "text format parsing error in line 1: unexpected end of label value", }, // 9: { in: `metric{label="bla"} 3.14 2.72 `, err: "text format parsing error in line 1: expected integer as timestamp", }, // 10: { in: `metric{label="bla"} 3.14 2 3 `, err: "text format parsing error in line 1: spurious string after timestamp", }, // 11: { in: `metric{label="bla"} blubb `, err: "text format parsing error in line 1: expected float as value", }, // 12: { in: ` # HELP metric one # HELP metric two `, err: "text format parsing error in line 3: second HELP line for metric name", }, // 13: { in: ` # TYPE metric counter # TYPE metric untyped `, err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, }, // 14: { in: ` metric 4.12 # TYPE metric counter `, err: `text format parsing error in line 3: second TYPE line for metric name "metric", or TYPE reported after samples`, }, // 14: { in: ` # TYPE metric bla `, err: "text format parsing error in line 2: unknown metric type", }, // 15: { in: ` # TYPE met-ric `, err: "text format parsing error in line 2: invalid metric name in comment", }, // 16: { in: `@invalidmetric{label="bla"} 3.14 2`, err: "text format parsing error in line 1: invalid metric name", }, // 17: { in: `{label="bla"} 3.14 2`, err: "text format parsing error in line 1: invalid metric name", }, // 18: { in: ` # TYPE metric histogram metric_bucket{le="bla"} 3.14 `, err: "text format parsing error in line 3: expected float as value for 'le' label", }, } for i, scenario := range scenarios { _, err := parser.TextToMetricFamilies(strings.NewReader(scenario.in)) if err == nil { t.Errorf("%d. expected error, got nil", i) continue } if expected, got := scenario.err, err.Error(); strings.Index(got, expected) != 0 { t.Errorf( "%d. expected error starting with %q, got %q", i, expected, got, ) } } } func TestTextParseError(t *testing.T) { testTextParseError(t) } func BenchmarkParseError(b *testing.B) { for i := 0; i < b.N; i++ { testTextParseError(b) } } ================================================ FILE: vendor/github.com/prometheus/common/model/fingerprinting.go ================================================ // 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 } ================================================ FILE: vendor/github.com/prometheus/common/model/labels.go ================================================ // 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" "sort" "strings" ) 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 // 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 // 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 sort.StringsAreSorted([]string{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] } ================================================ FILE: vendor/github.com/prometheus/common/model/labels_test.go ================================================ // 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 ( "sort" "testing" ) func testLabelNames(t testing.TB) { var scenarios = []struct { in LabelNames out LabelNames }{ { in: LabelNames{"ZZZ", "zzz"}, out: LabelNames{"ZZZ", "zzz"}, }, { in: LabelNames{"aaa", "AAA"}, out: LabelNames{"AAA", "aaa"}, }, } for i, scenario := range scenarios { sort.Sort(scenario.in) for j, expected := range scenario.out { if expected != scenario.in[j] { t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) } } } } func TestLabelNames(t *testing.T) { testLabelNames(t) } func BenchmarkLabelNames(b *testing.B) { for i := 0; i < b.N; i++ { testLabelNames(b) } } func testLabelValues(t testing.TB) { var scenarios = []struct { in LabelValues out LabelValues }{ { in: LabelValues{"ZZZ", "zzz"}, out: LabelValues{"ZZZ", "zzz"}, }, { in: LabelValues{"aaa", "AAA"}, out: LabelValues{"AAA", "aaa"}, }, } for i, scenario := range scenarios { sort.Sort(scenario.in) for j, expected := range scenario.out { if expected != scenario.in[j] { t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j]) } } } } func TestLabelValues(t *testing.T) { testLabelValues(t) } func BenchmarkLabelValues(b *testing.B) { for i := 0; i < b.N; i++ { testLabelValues(b) } } ================================================ FILE: vendor/github.com/prometheus/common/model/labelset.go ================================================ // 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 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 } 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 } ================================================ FILE: vendor/github.com/prometheus/common/model/metric.go ================================================ // 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" "sort" "strings" ) var separator = []byte{0} // 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() } ================================================ FILE: vendor/github.com/prometheus/common/model/metric_test.go ================================================ // 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 "testing" func testMetric(t testing.TB) { var scenarios = []struct { input LabelSet fingerprint Fingerprint fastFingerprint Fingerprint }{ { input: LabelSet{}, fingerprint: 14695981039346656037, fastFingerprint: 14695981039346656037, }, { input: LabelSet{ "first_name": "electro", "occupation": "robot", "manufacturer": "westinghouse", }, fingerprint: 5911716720268894962, fastFingerprint: 11310079640881077873, }, { input: LabelSet{ "x": "y", }, fingerprint: 8241431561484471700, fastFingerprint: 13948396922932177635, }, { input: LabelSet{ "a": "bb", "b": "c", }, fingerprint: 3016285359649981711, fastFingerprint: 3198632812309449502, }, { input: LabelSet{ "a": "b", "bb": "c", }, fingerprint: 7122421792099404749, fastFingerprint: 5774953389407657638, }, } for i, scenario := range scenarios { input := Metric(scenario.input) if scenario.fingerprint != input.Fingerprint() { t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint()) } if scenario.fastFingerprint != input.FastFingerprint() { t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint()) } } } func TestMetric(t *testing.T) { testMetric(t) } func BenchmarkMetric(b *testing.B) { for i := 0; i < b.N; i++ { testMetric(b) } } ================================================ FILE: vendor/github.com/prometheus/common/model/model.go ================================================ // 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 componenets and libraries. package model ================================================ FILE: vendor/github.com/prometheus/common/model/signature.go ================================================ // 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 ( "bytes" "hash" "hash/fnv" "sort" "sync" ) // 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 = fnv.New64a().Sum64() hashAndBufPool sync.Pool ) type hashAndBuf struct { h hash.Hash64 b bytes.Buffer } func getHashAndBuf() *hashAndBuf { hb := hashAndBufPool.Get() if hb == nil { return &hashAndBuf{h: fnv.New64a()} } return hb.(*hashAndBuf) } func putHashAndBuf(hb *hashAndBuf) { hb.h.Reset() hb.b.Reset() hashAndBufPool.Put(hb) } // 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) hb := getHashAndBuf() defer putHashAndBuf(hb) for _, labelName := range labelNames { hb.b.WriteString(labelName) hb.b.WriteByte(SeparatorByte) hb.b.WriteString(labels[labelName]) hb.b.WriteByte(SeparatorByte) hb.h.Write(hb.b.Bytes()) hb.b.Reset() } return hb.h.Sum64() } // 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) hb := getHashAndBuf() defer putHashAndBuf(hb) for _, labelName := range labelNames { hb.b.WriteString(string(labelName)) hb.b.WriteByte(SeparatorByte) hb.b.WriteString(string(ls[labelName])) hb.b.WriteByte(SeparatorByte) hb.h.Write(hb.b.Bytes()) hb.b.Reset() } return Fingerprint(hb.h.Sum64()) } // 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 hb := getHashAndBuf() defer putHashAndBuf(hb) for labelName, labelValue := range ls { hb.b.WriteString(string(labelName)) hb.b.WriteByte(SeparatorByte) hb.b.WriteString(string(labelValue)) hb.h.Write(hb.b.Bytes()) result ^= hb.h.Sum64() hb.h.Reset() hb.b.Reset() } 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(m) == 0 || len(labels) == 0 { return emptyLabelSignature } sort.Sort(LabelNames(labels)) hb := getHashAndBuf() defer putHashAndBuf(hb) for _, label := range labels { hb.b.WriteString(string(label)) hb.b.WriteByte(SeparatorByte) hb.b.WriteString(string(m[label])) hb.b.WriteByte(SeparatorByte) hb.h.Write(hb.b.Bytes()) hb.b.Reset() } return hb.h.Sum64() } // 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) hb := getHashAndBuf() defer putHashAndBuf(hb) for _, labelName := range labelNames { hb.b.WriteString(string(labelName)) hb.b.WriteByte(SeparatorByte) hb.b.WriteString(string(m[labelName])) hb.b.WriteByte(SeparatorByte) hb.h.Write(hb.b.Bytes()) hb.b.Reset() } return hb.h.Sum64() } ================================================ FILE: vendor/github.com/prometheus/common/model/signature_test.go ================================================ // 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 ( "runtime" "sync" "testing" ) func TestLabelsToSignature(t *testing.T) { var scenarios = []struct { in map[string]string out uint64 }{ { in: map[string]string{}, out: 14695981039346656037, }, { in: map[string]string{"name": "garland, briggs", "fear": "love is not enough"}, out: 5799056148416392346, }, } for i, scenario := range scenarios { actual := LabelsToSignature(scenario.in) if actual != scenario.out { t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) } } } func TestMetricToFingerprint(t *testing.T) { var scenarios = []struct { in LabelSet out Fingerprint }{ { in: LabelSet{}, out: 14695981039346656037, }, { in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, out: 5799056148416392346, }, } for i, scenario := range scenarios { actual := labelSetToFingerprint(scenario.in) if actual != scenario.out { t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) } } } func TestMetricToFastFingerprint(t *testing.T) { var scenarios = []struct { in LabelSet out Fingerprint }{ { in: LabelSet{}, out: 14695981039346656037, }, { in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"}, out: 12952432476264840823, }, } for i, scenario := range scenarios { actual := labelSetToFastFingerprint(scenario.in) if actual != scenario.out { t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) } } } func TestSignatureForLabels(t *testing.T) { var scenarios = []struct { in Metric labels LabelNames out uint64 }{ { in: Metric{}, labels: nil, out: 14695981039346656037, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, labels: LabelNames{"fear", "name"}, out: 5799056148416392346, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, labels: LabelNames{"fear", "name"}, out: 5799056148416392346, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, labels: LabelNames{}, out: 14695981039346656037, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, labels: nil, out: 14695981039346656037, }, } for i, scenario := range scenarios { actual := SignatureForLabels(scenario.in, scenario.labels...) if actual != scenario.out { t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) } } } func TestSignatureWithoutLabels(t *testing.T) { var scenarios = []struct { in Metric labels map[LabelName]struct{} out uint64 }{ { in: Metric{}, labels: nil, out: 14695981039346656037, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, labels: map[LabelName]struct{}{"fear": struct{}{}, "name": struct{}{}}, out: 14695981039346656037, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough", "foo": "bar"}, labels: map[LabelName]struct{}{"foo": struct{}{}}, out: 5799056148416392346, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, labels: map[LabelName]struct{}{}, out: 5799056148416392346, }, { in: Metric{"name": "garland, briggs", "fear": "love is not enough"}, labels: nil, out: 5799056148416392346, }, } for i, scenario := range scenarios { actual := SignatureWithoutLabels(scenario.in, scenario.labels) if actual != scenario.out { t.Errorf("%d. expected %d, got %d", i, scenario.out, actual) } } } func benchmarkLabelToSignature(b *testing.B, l map[string]string, e uint64) { for i := 0; i < b.N; i++ { if a := LabelsToSignature(l); a != e { b.Fatalf("expected signature of %d for %s, got %d", e, l, a) } } } func BenchmarkLabelToSignatureScalar(b *testing.B) { benchmarkLabelToSignature(b, nil, 14695981039346656037) } func BenchmarkLabelToSignatureSingle(b *testing.B) { benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value"}, 5146282821936882169) } func BenchmarkLabelToSignatureDouble(b *testing.B) { benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) } func BenchmarkLabelToSignatureTriple(b *testing.B) { benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) } func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { for i := 0; i < b.N; i++ { if a := labelSetToFingerprint(ls); a != e { b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) } } } func BenchmarkMetricToFingerprintScalar(b *testing.B) { benchmarkMetricToFingerprint(b, nil, 14695981039346656037) } func BenchmarkMetricToFingerprintSingle(b *testing.B) { benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169) } func BenchmarkMetricToFingerprintDouble(b *testing.B) { benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717) } func BenchmarkMetricToFingerprintTriple(b *testing.B) { benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121) } func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) { for i := 0; i < b.N; i++ { if a := labelSetToFastFingerprint(ls); a != e { b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) } } } func BenchmarkMetricToFastFingerprintScalar(b *testing.B) { benchmarkMetricToFastFingerprint(b, nil, 14695981039346656037) } func BenchmarkMetricToFastFingerprintSingle(b *testing.B) { benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964) } func BenchmarkMetricToFastFingerprintDouble(b *testing.B) { benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528) } func BenchmarkMetricToFastFingerprintTriple(b *testing.B) { benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676) } func BenchmarkEmptyLabelSignature(b *testing.B) { input := []map[string]string{nil, {}} var ms runtime.MemStats runtime.ReadMemStats(&ms) alloc := ms.Alloc for _, labels := range input { LabelsToSignature(labels) } runtime.ReadMemStats(&ms) if got := ms.Alloc; alloc != got { b.Fatal("expected LabelsToSignature with empty labels not to perform allocations") } } func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) { var start, end sync.WaitGroup start.Add(1) end.Add(concLevel) for i := 0; i < concLevel; i++ { go func() { start.Wait() for j := b.N / concLevel; j >= 0; j-- { if a := labelSetToFastFingerprint(ls); a != e { b.Fatalf("expected signature of %d for %s, got %d", e, ls, a) } } end.Done() }() } b.ResetTimer() start.Done() end.Wait() } func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) { benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1) } func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) { benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2) } func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) { benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4) } func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) { benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8) } ================================================ FILE: vendor/github.com/prometheus/common/model/time.go ================================================ // 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 // StringToDuration parses a string into a time.Duration, assuming that a year // 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) } durSeconds, _ := strconv.Atoi(matches[1]) dur := time.Duration(durSeconds) * time.Second unit := matches[2] switch unit { case "d": dur *= 60 * 60 * 24 case "h": dur *= 60 * 60 case "m": dur *= 60 case "s": dur *= 1 default: return 0, fmt.Errorf("invalid time unit in duration string: %q", unit) } return Duration(dur), nil } var durationRE = regexp.MustCompile("^([0-9]+)([ywdhms]+)$") func (d Duration) String() string { seconds := int64(time.Duration(d) / time.Second) factors := map[string]int64{ "d": 60 * 60 * 24, "h": 60 * 60, "m": 60, "s": 1, } unit := "s" switch int64(0) { case seconds % factors["d"]: unit = "d" case seconds % factors["h"]: unit = "h" case seconds % factors["m"]: unit = "m" } return fmt.Sprintf("%v%v", seconds/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 } ================================================ FILE: vendor/github.com/prometheus/common/model/time_test.go ================================================ // 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 ( "testing" "time" ) func TestComparators(t *testing.T) { t1a := TimeFromUnix(0) t1b := TimeFromUnix(0) t2 := TimeFromUnix(2*second - 1) if !t1a.Equal(t1b) { t.Fatalf("Expected %s to be equal to %s", t1a, t1b) } if t1a.Equal(t2) { t.Fatalf("Expected %s to not be equal to %s", t1a, t2) } if !t1a.Before(t2) { t.Fatalf("Expected %s to be before %s", t1a, t2) } if t1a.Before(t1b) { t.Fatalf("Expected %s to not be before %s", t1a, t1b) } if !t2.After(t1a) { t.Fatalf("Expected %s to be after %s", t2, t1a) } if t1b.After(t1a) { t.Fatalf("Expected %s to not be after %s", t1b, t1a) } } func TestTimeConversions(t *testing.T) { unixSecs := int64(1136239445) unixNsecs := int64(123456789) unixNano := unixSecs*1e9 + unixNsecs t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick) t2 := time.Unix(unixSecs, unixNsecs) ts := TimeFromUnixNano(unixNano) if !ts.Time().Equal(t1) { t.Fatalf("Expected %s, got %s", t1, ts.Time()) } // Test available precision. ts = TimeFromUnixNano(t2.UnixNano()) if !ts.Time().Equal(t1) { t.Fatalf("Expected %s, got %s", t1, ts.Time()) } if ts.UnixNano() != unixNano-unixNano%nanosPerTick { t.Fatalf("Expected %d, got %d", unixNano, ts.UnixNano()) } } func TestDuration(t *testing.T) { duration := time.Second + time.Minute + time.Hour goTime := time.Unix(1136239445, 0) ts := TimeFromUnix(goTime.Unix()) if !goTime.Add(duration).Equal(ts.Add(duration).Time()) { t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration)) } earlier := ts.Add(-duration) delta := ts.Sub(earlier) if delta != duration { t.Fatalf("Expected %s to be equal to %s", delta, duration) } } ================================================ FILE: vendor/github.com/prometheus/common/model/value.go ================================================ // 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" "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 } func (v SampleValue) Equal(o SampleValue) bool { return v == 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. func (s *SamplePair) Equal(o *SamplePair) bool { return s == o || (s.Value == 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. 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 != 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 "": *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 "" 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") } ================================================ FILE: vendor/github.com/prometheus/common/model/value_test.go ================================================ // 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" "math" "reflect" "sort" "testing" ) func TestSamplePairJSON(t *testing.T) { input := []struct { plain string value SamplePair }{ { plain: `[1234.567,"123.1"]`, value: SamplePair{ Value: 123.1, Timestamp: 1234567, }, }, } for _, test := range input { b, err := json.Marshal(test.value) if err != nil { t.Error(err) continue } if string(b) != test.plain { t.Errorf("encoding error: expected %q, got %q", test.plain, b) continue } var sp SamplePair err = json.Unmarshal(b, &sp) if err != nil { t.Error(err) continue } if sp != test.value { t.Errorf("decoding error: expected %v, got %v", test.value, sp) } } } func TestSampleJSON(t *testing.T) { input := []struct { plain string value Sample }{ { plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`, value: Sample{ Metric: Metric{ MetricNameLabel: "test_metric", }, Value: 123.1, Timestamp: 1234567, }, }, } for _, test := range input { b, err := json.Marshal(test.value) if err != nil { t.Error(err) continue } if string(b) != test.plain { t.Errorf("encoding error: expected %q, got %q", test.plain, b) continue } var sv Sample err = json.Unmarshal(b, &sv) if err != nil { t.Error(err) continue } if !reflect.DeepEqual(sv, test.value) { t.Errorf("decoding error: expected %v, got %v", test.value, sv) } } } func TestVectorJSON(t *testing.T) { input := []struct { plain string value Vector }{ { plain: `[]`, value: Vector{}, }, { plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`, value: Vector{&Sample{ Metric: Metric{ MetricNameLabel: "test_metric", }, Value: 123.1, Timestamp: 1234567, }}, }, { plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`, value: Vector{ &Sample{ Metric: Metric{ MetricNameLabel: "test_metric", }, Value: 123.1, Timestamp: 1234567, }, &Sample{ Metric: Metric{ "foo": "bar", }, Value: SampleValue(math.Inf(1)), Timestamp: 1234, }, }, }, } for _, test := range input { b, err := json.Marshal(test.value) if err != nil { t.Error(err) continue } if string(b) != test.plain { t.Errorf("encoding error: expected %q, got %q", test.plain, b) continue } var vec Vector err = json.Unmarshal(b, &vec) if err != nil { t.Error(err) continue } if !reflect.DeepEqual(vec, test.value) { t.Errorf("decoding error: expected %v, got %v", test.value, vec) } } } func TestScalarJSON(t *testing.T) { input := []struct { plain string value Scalar }{ { plain: `[123.456,"456"]`, value: Scalar{ Timestamp: 123456, Value: 456, }, }, { plain: `[123123.456,"+Inf"]`, value: Scalar{ Timestamp: 123123456, Value: SampleValue(math.Inf(1)), }, }, { plain: `[123123.456,"-Inf"]`, value: Scalar{ Timestamp: 123123456, Value: SampleValue(math.Inf(-1)), }, }, } for _, test := range input { b, err := json.Marshal(test.value) if err != nil { t.Error(err) continue } if string(b) != test.plain { t.Errorf("encoding error: expected %q, got %q", test.plain, b) continue } var sv Scalar err = json.Unmarshal(b, &sv) if err != nil { t.Error(err) continue } if sv != test.value { t.Errorf("decoding error: expected %v, got %v", test.value, sv) } } } func TestStringJSON(t *testing.T) { input := []struct { plain string value String }{ { plain: `[123.456,"test"]`, value: String{ Timestamp: 123456, Value: "test", }, }, { plain: `[123123.456,"台北"]`, value: String{ Timestamp: 123123456, Value: "台北", }, }, } for _, test := range input { b, err := json.Marshal(test.value) if err != nil { t.Error(err) continue } if string(b) != test.plain { t.Errorf("encoding error: expected %q, got %q", test.plain, b) continue } var sv String err = json.Unmarshal(b, &sv) if err != nil { t.Error(err) continue } if sv != test.value { t.Errorf("decoding error: expected %v, got %v", test.value, sv) } } } func TestVectorSort(t *testing.T) { input := Vector{ &Sample{ Metric: Metric{ MetricNameLabel: "A", }, Timestamp: 1, }, &Sample{ Metric: Metric{ MetricNameLabel: "A", }, Timestamp: 2, }, &Sample{ Metric: Metric{ MetricNameLabel: "C", }, Timestamp: 1, }, &Sample{ Metric: Metric{ MetricNameLabel: "C", }, Timestamp: 2, }, &Sample{ Metric: Metric{ MetricNameLabel: "B", }, Timestamp: 1, }, &Sample{ Metric: Metric{ MetricNameLabel: "B", }, Timestamp: 2, }, } expected := Vector{ &Sample{ Metric: Metric{ MetricNameLabel: "A", }, Timestamp: 1, }, &Sample{ Metric: Metric{ MetricNameLabel: "A", }, Timestamp: 2, }, &Sample{ Metric: Metric{ MetricNameLabel: "B", }, Timestamp: 1, }, &Sample{ Metric: Metric{ MetricNameLabel: "B", }, Timestamp: 2, }, &Sample{ Metric: Metric{ MetricNameLabel: "C", }, Timestamp: 1, }, &Sample{ Metric: Metric{ MetricNameLabel: "C", }, Timestamp: 2, }, } sort.Sort(input) for i, actual := range input { actualFp := actual.Metric.Fingerprint() expectedFp := expected[i].Metric.Fingerprint() if actualFp != expectedFp { t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String()) } if actual.Timestamp != expected[i].Timestamp { t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp) } } } ================================================ FILE: vendor/github.com/prometheus/common/route/route.go ================================================ package route import ( "net/http" "sync" "github.com/julienschmidt/httprouter" "golang.org/x/net/context" ) var ( mtx = sync.RWMutex{} ctxts = map[*http.Request]context.Context{} ) // Context returns the context for the request. func Context(r *http.Request) context.Context { mtx.RLock() defer mtx.RUnlock() return ctxts[r] } type param string // Param returns param p for the context. func Param(ctx context.Context, p string) string { return ctx.Value(param(p)).(string) } // WithParam returns a new context with param p set to v. func WithParam(ctx context.Context, p, v string) context.Context { return context.WithValue(ctx, param(p), v) } // handle turns a Handle into httprouter.Handle func handle(h http.HandlerFunc) httprouter.Handle { return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() for _, p := range params { ctx = context.WithValue(ctx, param(p.Key), p.Value) } mtx.Lock() ctxts[r] = ctx mtx.Unlock() h(w, r) mtx.Lock() delete(ctxts, r) mtx.Unlock() } } // Router wraps httprouter.Router and adds support for prefixed sub-routers. type Router struct { rtr *httprouter.Router prefix string } // New returns a new Router. func New() *Router { return &Router{rtr: httprouter.New()} } // WithPrefix returns a router that prefixes all registered routes with prefix. func (r *Router) WithPrefix(prefix string) *Router { return &Router{rtr: r.rtr, prefix: r.prefix + prefix} } // Get registers a new GET route. func (r *Router) Get(path string, h http.HandlerFunc) { r.rtr.GET(r.prefix+path, handle(h)) } // Del registers a new DELETE route. func (r *Router) Del(path string, h http.HandlerFunc) { r.rtr.DELETE(r.prefix+path, handle(h)) } // Put registers a new PUT route. func (r *Router) Put(path string, h http.HandlerFunc) { r.rtr.PUT(r.prefix+path, handle(h)) } // Post registers a new POST route. func (r *Router) Post(path string, h http.HandlerFunc) { r.rtr.POST(r.prefix+path, handle(h)) } // ServeHTTP implements http.Handler. func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { r.rtr.ServeHTTP(w, req) } // FileServe returns a new http.HandlerFunc that serves files from dir. // Using routes must provide the *filepath parameter. func FileServe(dir string) http.HandlerFunc { fs := http.FileServer(http.Dir(dir)) return func(w http.ResponseWriter, r *http.Request) { r.URL.Path = Param(Context(r), "filepath") fs.ServeHTTP(w, r) } } ================================================ FILE: vendor/github.com/prometheus/procfs/.travis.yml ================================================ language: go go: - 1.3 - 1.4 - tip ================================================ FILE: vendor/github.com/prometheus/procfs/AUTHORS.md ================================================ The Prometheus project was started by Matt T. Proud (emeritus) and Julius Volz in 2012. Maintainers of this repository: * Tobias Schmidt The following individuals have contributed code to this repository (listed in alphabetical order): * Tobias Schmidt ================================================ FILE: vendor/github.com/prometheus/procfs/CONTRIBUTING.md ================================================ # Contributing Prometheus uses GitHub to manage reviews of pull requests. * If you have a trivial fix or improvement, go ahead and create a pull request, addressing (with `@...`) one or more of the maintainers (see [AUTHORS.md](AUTHORS.md)) in the description of the pull request. * If you plan to do something more involved, first discuss your ideas on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). This will avoid unnecessary work and surely give you and us a good deal of inspiration. * Relevant coding style guidelines are the [Go Code Review Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments) and the _Formatting and style_ section of Peter Bourgon's [Go: Best Practices for Production Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style). ================================================ FILE: vendor/github.com/prometheus/procfs/LICENSE ================================================ 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. ================================================ FILE: vendor/github.com/prometheus/procfs/NOTICE ================================================ 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/). ================================================ FILE: vendor/github.com/prometheus/procfs/README.md ================================================ # procfs This procfs package provides functions to retrieve system, kernel and process metrics from the pseudo-filesystem proc. [![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) ================================================ FILE: vendor/github.com/prometheus/procfs/doc.go ================================================ // 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 ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/fd/0 ================================================ ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/fd/1 ================================================ ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/fd/2 ================================================ ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/fd/3 ================================================ ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/fd/4 ================================================ ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/limits ================================================ Limit Soft Limit Hard Limit Units Max cpu time unlimited unlimited seconds Max file size unlimited unlimited bytes Max data size unlimited unlimited bytes Max stack size 8388608 unlimited bytes Max core file size 0 unlimited bytes Max resident set unlimited unlimited bytes Max processes 62898 62898 processes Max open files 2048 4096 files Max locked memory 65536 65536 bytes Max address space unlimited unlimited bytes Max file locks unlimited unlimited locks Max pending signals 62898 62898 signals Max msgqueue size 819200 819200 bytes Max nice priority 0 0 Max realtime priority 0 0 Max realtime timeout unlimited unlimited us ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/26231/stat ================================================ 26231 (vim) R 5392 7446 5392 34835 7446 4218880 32533 309516 26 82 1677 44 158 99 20 0 1 0 82375 56274944 1981 18446744073709551615 4194304 6294284 140736914091744 140736914087944 139965136429984 0 0 12288 1870679807 0 0 0 17 0 0 0 31 0 0 8391624 8481048 16420864 140736914093252 140736914093279 140736914093279 140736914096107 0 ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/584/stat ================================================ 1020 ((a b ) ( c d) ) R 28378 1020 28378 34842 1020 4218880 286 0 0 0 0 0 0 0 20 0 1 0 10839175 10395648 155 18446744073709551615 4194304 4238788 140736466511168 140736466511168 140609271124624 0 0 0 0 0 0 0 17 5 0 0 0 0 0 6336016 6337300 25579520 140736466515030 140736466515061 140736466515061 140736466518002 0 #!/bin/cat /proc/self/stat ================================================ FILE: vendor/github.com/prometheus/procfs/fixtures/stat ================================================ cpu 301854 612 111922 8979004 3552 2 3944 0 0 0 cpu0 44490 19 21045 1087069 220 1 3410 0 0 0 cpu1 47869 23 16474 1110787 591 0 46 0 0 0 cpu2 46504 36 15916 1112321 441 0 326 0 0 0 cpu3 47054 102 15683 1113230 533 0 60 0 0 0 cpu4 28413 25 10776 1140321 217 0 8 0 0 0 cpu5 29271 101 11586 1136270 672 0 30 0 0 0 cpu6 29152 36 10276 1139721 319 0 29 0 0 0 cpu7 29098 268 10164 1139282 555 0 31 0 0 0 intr 8885917 17 0 0 0 0 0 0 0 1 79281 0 0 0 0 0 0 0 231237 0 0 0 0 250586 103 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 223424 190745 13 906 1283803 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 0 0 0 0 0 0 0 0 0 0 0 0 ctxt 38014093 btime 1418183276 processes 26442 procs_running 2 procs_blocked 0 softirq 5057579 250191 1481983 1647 211099 186066 0 1783454 622196 12499 508444 ================================================ FILE: vendor/github.com/prometheus/procfs/fs.go ================================================ 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 } func (fs FS) stat(p string) (os.FileInfo, error) { return os.Stat(path.Join(string(fs), p)) } func (fs FS) open(p string) (*os.File, error) { return os.Open(path.Join(string(fs), p)) } ================================================ FILE: vendor/github.com/prometheus/procfs/fs_test.go ================================================ package procfs import "testing" func TestNewFS(t *testing.T) { if _, err := NewFS("foobar"); err == nil { t.Error("want NewFS to fail for non-existing mount point") } if _, err := NewFS("procfs.go"); err == nil { t.Error("want NewFS to fail if mount point is not a directory") } } ================================================ FILE: vendor/github.com/prometheus/procfs/proc.go ================================================ package procfs import ( "fmt" "io/ioutil" "os" "path" "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. func Self() (Proc, error) { return NewProc(os.Getpid()) } // 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 avaible processes under /proc. func AllProcs() (Procs, error) { fs, err := NewFS(DefaultMountPoint) if err != nil { return Procs{}, err } return fs.AllProcs() } // NewProc returns a process for the given pid. func (fs FS) NewProc(pid int) (Proc, error) { if _, err := fs.stat(strconv.Itoa(pid)); err != nil { return Proc{}, err } return Proc{PID: pid, fs: fs}, nil } // AllProcs returns a list of all currently avaible processes. func (fs FS) AllProcs() (Procs, error) { d, err := fs.open("") 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 := p.open("cmdline") if err != nil { return nil, err } defer f.Close() data, err := ioutil.ReadAll(f) if err != nil { return nil, err } return strings.Split(string(data[:len(data)-1]), string(byte(0))), nil } // 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 } // 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 := p.open("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) open(pa string) (*os.File, error) { return p.fs.open(path.Join(strconv.Itoa(p.PID), pa)) } ================================================ FILE: vendor/github.com/prometheus/procfs/proc_limits.go ================================================ package procfs import ( "bufio" "fmt" "regexp" "strconv" ) // ProcLimits represents the soft limits for each of the process's resource // limits. type ProcLimits struct { CPUTime int FileSize int DataSize int StackSize int CoreFileSize int ResidentSet int Processes int OpenFiles int LockedMemory int AddressSpace int FileLocks int PendingSignals int MsqqueueSize int NicePriority int RealtimePriority int 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 := p.open("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.FileLocks, 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 } ================================================ FILE: vendor/github.com/prometheus/procfs/proc_limits_test.go ================================================ package procfs import "testing" func TestNewLimits(t *testing.T) { fs, err := NewFS("fixtures") if err != nil { t.Fatal(err) } p, err := fs.NewProc(26231) if err != nil { t.Fatal(err) } l, err := p.NewLimits() if err != nil { t.Fatal(err) } for _, test := range []struct { name string want int got int }{ {name: "cpu time", want: -1, got: l.CPUTime}, {name: "open files", want: 2048, got: l.OpenFiles}, {name: "msgqueue size", want: 819200, got: l.MsqqueueSize}, {name: "nice priority", want: 0, got: l.NicePriority}, {name: "address space", want: -1, got: l.AddressSpace}, } { if test.want != test.got { t.Errorf("want %s %d, got %d", test.name, test.want, test.got) } } } ================================================ FILE: vendor/github.com/prometheus/procfs/proc_stat.go ================================================ 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 := p.open("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 } ================================================ FILE: vendor/github.com/prometheus/procfs/proc_stat_test.go ================================================ package procfs import "testing" func TestProcStat(t *testing.T) { fs, err := NewFS("fixtures") if err != nil { t.Fatal(err) } p, err := fs.NewProc(26231) if err != nil { t.Fatal(err) } s, err := p.NewStat() if err != nil { t.Fatal(err) } for _, test := range []struct { name string want int got int }{ {name: "pid", want: 26231, got: s.PID}, {name: "user time", want: 1677, got: int(s.UTime)}, {name: "system time", want: 44, got: int(s.STime)}, {name: "start time", want: 82375, got: int(s.Starttime)}, {name: "virtual memory size", want: 56274944, got: s.VSize}, {name: "resident set size", want: 1981, got: s.RSS}, } { if test.want != test.got { t.Errorf("want %s %d, got %d", test.name, test.want, test.got) } } } func TestProcStatComm(t *testing.T) { s1, err := testProcStat(26231) if err != nil { t.Fatal(err) } if want, got := "vim", s1.Comm; want != got { t.Errorf("want comm %s, got %s", want, got) } s2, err := testProcStat(584) if err != nil { t.Fatal(err) } if want, got := "(a b ) ( c d) ", s2.Comm; want != got { t.Errorf("want comm %s, got %s", want, got) } } func TestProcStatVirtualMemory(t *testing.T) { s, err := testProcStat(26231) if err != nil { t.Fatal(err) } if want, got := 56274944, s.VirtualMemory(); want != got { t.Errorf("want virtual memory %d, got %d", want, got) } } func TestProcStatResidentMemory(t *testing.T) { s, err := testProcStat(26231) if err != nil { t.Fatal(err) } if want, got := 1981*4096, s.ResidentMemory(); want != got { t.Errorf("want resident memory %d, got %d", want, got) } } func TestProcStatStartTime(t *testing.T) { s, err := testProcStat(26231) if err != nil { t.Fatal(err) } time, err := s.StartTime() if err != nil { t.Fatal(err) } if want, got := 1418184099.75, time; want != got { t.Errorf("want start time %f, got %f", want, got) } } func TestProcStatCPUTime(t *testing.T) { s, err := testProcStat(26231) if err != nil { t.Fatal(err) } if want, got := 17.21, s.CPUTime(); want != got { t.Errorf("want cpu time %f, got %f", want, got) } } func testProcStat(pid int) (ProcStat, error) { p, err := testProcess(pid) if err != nil { return ProcStat{}, err } return p.NewStat() } ================================================ FILE: vendor/github.com/prometheus/procfs/proc_test.go ================================================ package procfs import ( "os" "reflect" "sort" "testing" ) func TestSelf(t *testing.T) { p1, err := NewProc(os.Getpid()) if err != nil { t.Fatal(err) } p2, err := Self() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(p1, p2) { t.Errorf("want process %v to equal %v", p1, p2) } } func TestAllProcs(t *testing.T) { fs, err := NewFS("fixtures") if err != nil { t.Fatal(err) } procs, err := fs.AllProcs() if err != nil { t.Fatal(err) } sort.Sort(procs) for i, p := range []*Proc{{PID: 584}, {PID: 26231}} { if want, got := p.PID, procs[i].PID; want != got { t.Errorf("want processes %d, got %d", want, got) } } } func TestCmdLine(t *testing.T) { p1, err := testProcess(26231) if err != nil { t.Fatal(err) } c, err := p1.CmdLine() if err != nil { t.Fatal(err) } if want := []string{"vim", "test.go", "+10"}; !reflect.DeepEqual(want, c) { t.Errorf("want cmdline %v, got %v", want, c) } } func TestFileDescriptors(t *testing.T) { p1, err := testProcess(26231) if err != nil { t.Fatal(err) } fds, err := p1.FileDescriptors() if err != nil { t.Fatal(err) } sort.Sort(byUintptr(fds)) if want := []uintptr{0, 1, 2, 3, 4}; !reflect.DeepEqual(want, fds) { t.Errorf("want fds %v, got %v", want, fds) } p2, err := Self() if err != nil { t.Fatal(err) } fdsBefore, err := p2.FileDescriptors() if err != nil { t.Fatal(err) } s, err := os.Open("fixtures") if err != nil { t.Fatal(err) } defer s.Close() fdsAfter, err := p2.FileDescriptors() if err != nil { t.Fatal(err) } if len(fdsBefore)+1 != len(fdsAfter) { t.Errorf("want fds %v+1 to equal %v", fdsBefore, fdsAfter) } } func TestFileDescriptorsLen(t *testing.T) { p1, err := testProcess(26231) if err != nil { t.Fatal(err) } l, err := p1.FileDescriptorsLen() if err != nil { t.Fatal(err) } if want, got := 5, l; want != got { t.Errorf("want fds %d, got %d", want, got) } } func testProcess(pid int) (Proc, error) { fs, err := NewFS("fixtures") if err != nil { return Proc{}, err } return fs.NewProc(pid) } type byUintptr []uintptr func (a byUintptr) Len() int { return len(a) } func (a byUintptr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byUintptr) Less(i, j int) bool { return a[i] < a[j] } ================================================ FILE: vendor/github.com/prometheus/procfs/stat.go ================================================ package procfs import ( "bufio" "fmt" "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 := fs.open("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()) } ================================================ FILE: vendor/github.com/prometheus/procfs/stat_test.go ================================================ package procfs import "testing" func TestStat(t *testing.T) { fs, err := NewFS("fixtures") if err != nil { t.Fatal(err) } s, err := fs.NewStat() if err != nil { t.Fatal(err) } if want, got := int64(1418183276), s.BootTime; want != got { t.Errorf("want boot time %d, got %d", want, got) } } ================================================ FILE: vendor/github.com/russross/blackfriday/.gitignore ================================================ *.out *.swp *.8 *.6 _obj _test* markdown tags ================================================ FILE: vendor/github.com/russross/blackfriday/.travis.yml ================================================ # Travis CI (http://travis-ci.org/) is a continuous integration service for # open source projects. This file configures it to run unit tests for # blackfriday. language: go go: - 1.2 - 1.3 install: - go get -d -t -v ./... - go build -v ./... script: - go test -v ./... ================================================ FILE: vendor/github.com/russross/blackfriday/LICENSE.txt ================================================ Blackfriday is distributed under the Simplified BSD License: > Copyright © 2011 Russ Ross > 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. ================================================ FILE: vendor/github.com/russross/blackfriday/README.md ================================================ Blackfriday [![Build Status](https://travis-ci.org/russross/blackfriday.svg?branch=master)](https://travis-ci.org/russross/blackfriday) =========== Blackfriday is a [Markdown][1] processor implemented in [Go][2]. It is paranoid about its input (so you can safely feed it user-supplied data), it is fast, it supports common extensions (tables, smart punctuation substitutions, etc.), and it is safe for all utf-8 (unicode) input. HTML output is currently supported, along with Smartypants extensions. An experimental LaTeX output engine is also included. It started as a translation from C of [upskirt][3]. Installation ------------ Blackfriday is compatible with Go 1. If you are using an older release of Go, consider using v1.1 of blackfriday, which was based on the last stable release of Go prior to Go 1. You can find it as a tagged commit on github. With Go 1 and git installed: go get github.com/russross/blackfriday will download, compile, and install the package into your `$GOPATH` directory hierarchy. Alternatively, you can achieve the same if you import it into a project: import "github.com/russross/blackfriday" and `go get` without parameters. Usage ----- For basic usage, it is as simple as getting your input into a byte slice and calling: output := blackfriday.MarkdownBasic(input) This renders it with no extensions enabled. To get a more useful feature set, use this instead: output := blackfriday.MarkdownCommon(input) ### Sanitize untrusted content Blackfriday itself does nothing to protect against malicious content. If you are dealing with user-supplied markdown, we recommend running blackfriday's output through HTML sanitizer such as [Bluemonday](https://github.com/microcosm-cc/bluemonday). Here's an example of simple usage of blackfriday together with bluemonday: ``` go import ( "github.com/microcosm-cc/bluemonday" "github.com/russross/blackfriday" ) // ... unsafe := blackfriday.MarkdownCommon(input) html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) ``` ### Custom options If you want to customize the set of options, first get a renderer (currently either the HTML or LaTeX output engines), then use it to call the more general `Markdown` function. For examples, see the implementations of `MarkdownBasic` and `MarkdownCommon` in `markdown.go`. You can also check out `blackfriday-tool` for a more complete example of how to use it. Download and install it using: go get github.com/russross/blackfriday-tool This is a simple command-line tool that allows you to process a markdown file using a standalone program. You can also browse the source directly on github if you are just looking for some example code: * Note that if you have not already done so, installing `blackfriday-tool` will be sufficient to download and install blackfriday in addition to the tool itself. The tool binary will be installed in `$GOPATH/bin`. This is a statically-linked binary that can be copied to wherever you need it without worrying about dependencies and library versions. Features -------- All features of upskirt are supported, including: * **Compatibility**. The Markdown v1.0.3 test suite passes with the `--tidy` option. Without `--tidy`, the differences are mostly in whitespace and entity escaping, where blackfriday is more consistent and cleaner. * **Common extensions**, including table support, fenced code blocks, autolinks, strikethroughs, non-strict emphasis, etc. * **Safety**. Blackfriday is paranoid when parsing, making it safe to feed untrusted user input without fear of bad things happening. The test suite stress tests this and there are no known inputs that make it crash. If you find one, please let me know and send me the input that does it. NOTE: "safety" in this context means *runtime safety only*. In order to protect yourself agains JavaScript injection in untrusted content, see [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content). * **Fast processing**. It is fast enough to render on-demand in most web applications without having to cache the output. * **Thread safety**. You can run multiple parsers in different goroutines without ill effect. There is no dependence on global shared state. * **Minimal dependencies**. Blackfriday only depends on standard library packages in Go. The source code is pretty self-contained, so it is easy to add to any project, including Google App Engine projects. * **Standards compliant**. Output successfully validates using the W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional. Extensions ---------- In addition to the standard markdown syntax, this package implements the following extensions: * **Intra-word emphasis supression**. The `_` character is commonly used inside words when discussing code, so having markdown interpret it as an emphasis command is usually the wrong thing. Blackfriday lets you treat all emphasis markers as normal characters when they occur inside a word. * **Tables**. Tables can be created by drawing them in the input using a simple syntax: ``` Name | Age --------|------ Bob | 27 Alice | 23 ``` * **Fenced code blocks**. In addition to the normal 4-space indentation to mark code blocks, you can explicitly mark them and supply a language (to make syntax highlighting simple). Just mark it like this: ``` go func getTrue() bool { return true } ``` You can use 3 or more backticks to mark the beginning of the block, and the same number to mark the end of the block. * **Autolinking**. Blackfriday can find URLs that have not been explicitly marked as links and turn them into links. * **Strikethrough**. Use two tildes (`~~`) to mark text that should be crossed out. * **Hard line breaks**. With this extension enabled (it is off by default in the `MarkdownBasic` and `MarkdownCommon` convenience functions), newlines in the input translate into line breaks in the output. * **Smart quotes**. Smartypants-style punctuation substitution is supported, turning normal double- and single-quote marks into curly quotes, etc. * **LaTeX-style dash parsing** is an additional option, where `--` is translated into `–`, and `---` is translated into `—`. This differs from most smartypants processors, which turn a single hyphen into an ndash and a double hyphen into an mdash. * **Smart fractions**, where anything that looks like a fraction is translated into suitable HTML (instead of just a few special cases like most smartypant processors). For example, `4/5` becomes `45`, which renders as 45. Other renderers --------------- Blackfriday is structured to allow alternative rendering engines. Here are a few of note: * [github_flavored_markdown](https://godoc.org/github.com/shurcooL/go/github_flavored_markdown): provides a GitHub Flavored Markdown renderer with fenced code block highlighting, clickable header anchor links. It's not customizable, and its goal is to produce HTML output equivalent to the [GitHub Markdown API endpoint](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode), except the rendering is performed locally. * [markdownfmt](https://github.com/shurcooL/markdownfmt): like gofmt, but for markdown. * LaTeX output: renders output as LaTeX. This is currently part of the main Blackfriday repository, but may be split into its own project in the future. If you are interested in owning and maintaining the LaTeX output component, please be in touch. It renders some basic documents, but is only experimental at this point. In particular, it does not do any inline escaping, so input that happens to look like LaTeX code will be passed through without modification. Todo ---- * More unit testing * Improve unicode support. It does not understand all unicode rules (about what constitutes a letter, a punctuation symbol, etc.), so it may fail to detect word boundaries correctly in some instances. It is safe on all utf-8 input. License ------- [Blackfriday is distributed under the Simplified BSD License](LICENSE.txt) [1]: http://daringfireball.net/projects/markdown/ "Markdown" [2]: http://golang.org/ "Go Language" [3]: http://github.com/tanoku/upskirt "Upskirt" ================================================ FILE: vendor/github.com/russross/blackfriday/block.go ================================================ // // Blackfriday Markdown Processor // Available at http://github.com/russross/blackfriday // // Copyright © 2011 Russ Ross . // Distributed under the Simplified BSD License. // See README.md for details. // // // Functions to parse block-level elements. // package blackfriday import ( "bytes" "github.com/shurcooL/sanitized_anchor_name" ) // Parse block-level data. // Note: this function and many that it calls assume that // the input buffer ends with a newline. func (p *parser) block(out *bytes.Buffer, data []byte) { if len(data) == 0 || data[len(data)-1] != '\n' { panic("block input is missing terminating newline") } // this is called recursively: enforce a maximum depth if p.nesting >= p.maxNesting { return } p.nesting++ // parse out one block-level construct at a time for len(data) > 0 { // prefixed header: // // # Header 1 // ## Header 2 // ... // ###### Header 6 if p.isPrefixHeader(data) { data = data[p.prefixHeader(out, data):] continue } // block of preformatted HTML: // //
// ... //
if data[0] == '<' { if i := p.html(out, data, true); i > 0 { data = data[i:] continue } } // title block // // % stuff // % more stuff // % even more stuff if p.flags&EXTENSION_TITLEBLOCK != 0 { if data[0] == '%' { if i := p.titleBlock(out, data, true); i > 0 { data = data[i:] continue } } } // blank lines. note: returns the # of bytes to skip if i := p.isEmpty(data); i > 0 { data = data[i:] continue } // indented code block: // // func max(a, b int) int { // if a > b { // return a // } // return b // } if p.codePrefix(data) > 0 { data = data[p.code(out, data):] continue } // fenced code block: // // ``` go // func fact(n int) int { // if n <= 1 { // return n // } // return n * fact(n-1) // } // ``` if p.flags&EXTENSION_FENCED_CODE != 0 { if i := p.fencedCode(out, data, true); i > 0 { data = data[i:] continue } } // horizontal rule: // // ------ // or // ****** // or // ______ if p.isHRule(data) { p.r.HRule(out) var i int for i = 0; data[i] != '\n'; i++ { } data = data[i:] continue } // block quote: // // > A big quote I found somewhere // > on the web if p.quotePrefix(data) > 0 { data = data[p.quote(out, data):] continue } // table: // // Name | Age | Phone // ------|-----|--------- // Bob | 31 | 555-1234 // Alice | 27 | 555-4321 if p.flags&EXTENSION_TABLES != 0 { if i := p.table(out, data); i > 0 { data = data[i:] continue } } // an itemized/unordered list: // // * Item 1 // * Item 2 // // also works with + or - if p.uliPrefix(data) > 0 { data = data[p.list(out, data, 0):] continue } // a numbered/ordered list: // // 1. Item 1 // 2. Item 2 if p.oliPrefix(data) > 0 { data = data[p.list(out, data, LIST_TYPE_ORDERED):] continue } // anything else must look like a normal paragraph // note: this finds underlined headers, too data = data[p.paragraph(out, data):] } p.nesting-- } func (p *parser) isPrefixHeader(data []byte) bool { if data[0] != '#' { return false } if p.flags&EXTENSION_SPACE_HEADERS != 0 { level := 0 for level < 6 && data[level] == '#' { level++ } if data[level] != ' ' { return false } } return true } func (p *parser) prefixHeader(out *bytes.Buffer, data []byte) int { level := 0 for level < 6 && data[level] == '#' { level++ } i, end := 0, 0 for i = level; data[i] == ' '; i++ { } for end = i; data[end] != '\n'; end++ { } skip := end id := "" if p.flags&EXTENSION_HEADER_IDS != 0 { j, k := 0, 0 // find start/end of header id for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ { } for k = j + 1; k < end && data[k] != '}'; k++ { } // extract header id iff found if j < end && k < end { id = string(data[j+2 : k]) end = j skip = k + 1 for end > 0 && data[end-1] == ' ' { end-- } } } for end > 0 && data[end-1] == '#' { end-- } for end > 0 && data[end-1] == ' ' { end-- } if end > i { if id == "" && p.flags&EXTENSION_AUTO_HEADER_IDS != 0 { id = sanitized_anchor_name.Create(string(data[i:end])) } work := func() bool { p.inline(out, data[i:end]) return true } p.r.Header(out, work, level, id) } return skip } func (p *parser) isUnderlinedHeader(data []byte) int { // test of level 1 header if data[0] == '=' { i := 1 for data[i] == '=' { i++ } for data[i] == ' ' { i++ } if data[i] == '\n' { return 1 } else { return 0 } } // test of level 2 header if data[0] == '-' { i := 1 for data[i] == '-' { i++ } for data[i] == ' ' { i++ } if data[i] == '\n' { return 2 } else { return 0 } } return 0 } func (p *parser) titleBlock(out *bytes.Buffer, data []byte, doRender bool) int { if data[0] != '%' { return 0 } splitData := bytes.Split(data, []byte("\n")) var i int for idx, b := range splitData { if !bytes.HasPrefix(b, []byte("%")) { i = idx // - 1 break } } data = bytes.Join(splitData[0:i], []byte("\n")) p.r.TitleBlock(out, data) return len(data) } func (p *parser) html(out *bytes.Buffer, data []byte, doRender bool) int { var i, j int // identify the opening tag if data[0] != '<' { return 0 } curtag, tagfound := p.htmlFindTag(data[1:]) // handle special cases if !tagfound { // check for an HTML comment if size := p.htmlComment(out, data, doRender); size > 0 { return size } // check for an
tag if size := p.htmlHr(out, data, doRender); size > 0 { return size } // no special case recognized return 0 } // look for an unindented matching closing tag // followed by a blank line found := false /* closetag := []byte("\n") j = len(curtag) + 1 for !found { // scan for a closing tag at the beginning of a line if skip := bytes.Index(data[j:], closetag); skip >= 0 { j += skip + len(closetag) } else { break } // see if it is the only thing on the line if skip := p.isEmpty(data[j:]); skip > 0 { // see if it is followed by a blank line/eof j += skip if j >= len(data) { found = true i = j } else { if skip := p.isEmpty(data[j:]); skip > 0 { j += skip found = true i = j } } } } */ // if not found, try a second pass looking for indented match // but not if tag is "ins" or "del" (following original Markdown.pl) if !found && curtag != "ins" && curtag != "del" { i = 1 for i < len(data) { i++ for i < len(data) && !(data[i-1] == '<' && data[i] == '/') { i++ } if i+2+len(curtag) >= len(data) { break } j = p.htmlFindEnd(curtag, data[i-1:]) if j > 0 { i += j - 1 found = true break } } } if !found { return 0 } // the end of the block has been found if doRender { // trim newlines end := i for end > 0 && data[end-1] == '\n' { end-- } p.r.BlockHtml(out, data[:end]) } return i } // HTML comment, lax form func (p *parser) htmlComment(out *bytes.Buffer, data []byte, doRender bool) int { if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' { return 0 } i := 5 // scan for an end-of-comment marker, across lines if necessary for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') { i++ } i++ // no end-of-comment marker if i >= len(data) { return 0 } // needs to end with a blank line if j := p.isEmpty(data[i:]); j > 0 { size := i + j if doRender { // trim trailing newlines end := size for end > 0 && data[end-1] == '\n' { end-- } p.r.BlockHtml(out, data[:end]) } return size } return 0 } // HR, which is the only self-closing block tag considered func (p *parser) htmlHr(out *bytes.Buffer, data []byte, doRender bool) int { if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') { return 0 } if data[3] != ' ' && data[3] != '/' && data[3] != '>' { // not an
tag after all; at least not a valid one return 0 } i := 3 for data[i] != '>' && data[i] != '\n' { i++ } if data[i] == '>' { i++ if j := p.isEmpty(data[i:]); j > 0 { size := i + j if doRender { // trim newlines end := size for end > 0 && data[end-1] == '\n' { end-- } p.r.BlockHtml(out, data[:end]) } return size } } return 0 } func (p *parser) htmlFindTag(data []byte) (string, bool) { i := 0 for isalnum(data[i]) { i++ } key := string(data[:i]) if blockTags[key] { return key, true } return "", false } func (p *parser) htmlFindEnd(tag string, data []byte) int { // assume data[0] == '<' && data[1] == '/' already tested // check if tag is a match closetag := []byte("") if !bytes.HasPrefix(data, closetag) { return 0 } i := len(closetag) // check that the rest of the line is blank skip := 0 if skip = p.isEmpty(data[i:]); skip == 0 { return 0 } i += skip skip = 0 if i >= len(data) { return i } if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 { return i } if skip = p.isEmpty(data[i:]); skip == 0 { // following line must be blank return 0 } return i + skip } func (p *parser) isEmpty(data []byte) int { // it is okay to call isEmpty on an empty buffer if len(data) == 0 { return 0 } var i int for i = 0; i < len(data) && data[i] != '\n'; i++ { if data[i] != ' ' && data[i] != '\t' { return 0 } } return i + 1 } func (p *parser) isHRule(data []byte) bool { i := 0 // skip up to three spaces for i < 3 && data[i] == ' ' { i++ } // look at the hrule char if data[i] != '*' && data[i] != '-' && data[i] != '_' { return false } c := data[i] // the whole line must be the char or whitespace n := 0 for data[i] != '\n' { switch { case data[i] == c: n++ case data[i] != ' ': return false } i++ } return n >= 3 } func (p *parser) isFencedCode(data []byte, syntax **string, oldmarker string) (skip int, marker string) { i, size := 0, 0 skip = 0 // skip up to three spaces for i < len(data) && i < 3 && data[i] == ' ' { i++ } if i >= len(data) { return } // check for the marker characters: ~ or ` if data[i] != '~' && data[i] != '`' { return } c := data[i] // the whole line must be the same char or whitespace for i < len(data) && data[i] == c { size++ i++ } if i >= len(data) { return } // the marker char must occur at least 3 times if size < 3 { return } marker = string(data[i-size : i]) // if this is the end marker, it must match the beginning marker if oldmarker != "" && marker != oldmarker { return } if syntax != nil { syn := 0 for i < len(data) && data[i] == ' ' { i++ } if i >= len(data) { return } syntaxStart := i if data[i] == '{' { i++ syntaxStart++ for i < len(data) && data[i] != '}' && data[i] != '\n' { syn++ i++ } if i >= len(data) || data[i] != '}' { return } // strip all whitespace at the beginning and the end // of the {} block for syn > 0 && isspace(data[syntaxStart]) { syntaxStart++ syn-- } for syn > 0 && isspace(data[syntaxStart+syn-1]) { syn-- } i++ } else { for i < len(data) && !isspace(data[i]) { syn++ i++ } } language := string(data[syntaxStart : syntaxStart+syn]) *syntax = &language } for i < len(data) && data[i] == ' ' { i++ } if i >= len(data) || data[i] != '\n' { return } skip = i + 1 return } func (p *parser) fencedCode(out *bytes.Buffer, data []byte, doRender bool) int { var lang *string beg, marker := p.isFencedCode(data, &lang, "") if beg == 0 || beg >= len(data) { return 0 } var work bytes.Buffer for { // safe to assume beg < len(data) // check for the end of the code block fenceEnd, _ := p.isFencedCode(data[beg:], nil, marker) if fenceEnd != 0 { beg += fenceEnd break } // copy the current line end := beg for end < len(data) && data[end] != '\n' { end++ } end++ // did we reach the end of the buffer without a closing marker? if end >= len(data) { return 0 } // verbatim copy to the working buffer if doRender { work.Write(data[beg:end]) } beg = end } syntax := "" if lang != nil { syntax = *lang } if doRender { p.r.BlockCode(out, work.Bytes(), syntax) } return beg } func (p *parser) table(out *bytes.Buffer, data []byte) int { var header bytes.Buffer i, columns := p.tableHeader(&header, data) if i == 0 { return 0 } var body bytes.Buffer for i < len(data) { pipes, rowStart := 0, i for ; data[i] != '\n'; i++ { if data[i] == '|' { pipes++ } } if pipes == 0 { i = rowStart break } // include the newline in data sent to tableRow i++ p.tableRow(&body, data[rowStart:i], columns, false) } p.r.Table(out, header.Bytes(), body.Bytes(), columns) return i } // check if the specified position is preceeded by an odd number of backslashes func isBackslashEscaped(data []byte, i int) bool { backslashes := 0 for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' { backslashes++ } return backslashes&1 == 1 } func (p *parser) tableHeader(out *bytes.Buffer, data []byte) (size int, columns []int) { i := 0 colCount := 1 for i = 0; data[i] != '\n'; i++ { if data[i] == '|' && !isBackslashEscaped(data, i) { colCount++ } } // doesn't look like a table header if colCount == 1 { return } // include the newline in the data sent to tableRow header := data[:i+1] // column count ignores pipes at beginning or end of line if data[0] == '|' { colCount-- } if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) { colCount-- } columns = make([]int, colCount) // move on to the header underline i++ if i >= len(data) { return } if data[i] == '|' && !isBackslashEscaped(data, i) { i++ } for data[i] == ' ' { i++ } // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3 // and trailing | optional on last column col := 0 for data[i] != '\n' { dashes := 0 if data[i] == ':' { i++ columns[col] |= TABLE_ALIGNMENT_LEFT dashes++ } for data[i] == '-' { i++ dashes++ } if data[i] == ':' { i++ columns[col] |= TABLE_ALIGNMENT_RIGHT dashes++ } for data[i] == ' ' { i++ } // end of column test is messy switch { case dashes < 3: // not a valid column return case data[i] == '|' && !isBackslashEscaped(data, i): // marker found, now skip past trailing whitespace col++ i++ for data[i] == ' ' { i++ } // trailing junk found after last column if col >= colCount && data[i] != '\n' { return } case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount: // something else found where marker was required return case data[i] == '\n': // marker is optional for the last column col++ default: // trailing junk found after last column return } } if col != colCount { return } p.tableRow(out, header, columns, true) size = i + 1 return } func (p *parser) tableRow(out *bytes.Buffer, data []byte, columns []int, header bool) { i, col := 0, 0 var rowWork bytes.Buffer if data[i] == '|' && !isBackslashEscaped(data, i) { i++ } for col = 0; col < len(columns) && i < len(data); col++ { for data[i] == ' ' { i++ } cellStart := i for (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' { i++ } cellEnd := i // skip the end-of-cell marker, possibly taking us past end of buffer i++ for cellEnd > cellStart && data[cellEnd-1] == ' ' { cellEnd-- } var cellWork bytes.Buffer p.inline(&cellWork, data[cellStart:cellEnd]) if header { p.r.TableHeaderCell(&rowWork, cellWork.Bytes(), columns[col]) } else { p.r.TableCell(&rowWork, cellWork.Bytes(), columns[col]) } } // pad it out with empty columns to get the right number for ; col < len(columns); col++ { if header { p.r.TableHeaderCell(&rowWork, nil, columns[col]) } else { p.r.TableCell(&rowWork, nil, columns[col]) } } // silently ignore rows with too many cells p.r.TableRow(out, rowWork.Bytes()) } // returns blockquote prefix length func (p *parser) quotePrefix(data []byte) int { i := 0 for i < 3 && data[i] == ' ' { i++ } if data[i] == '>' { if data[i+1] == ' ' { return i + 2 } return i + 1 } return 0 } // parse a blockquote fragment func (p *parser) quote(out *bytes.Buffer, data []byte) int { var raw bytes.Buffer beg, end := 0, 0 for beg < len(data) { end = beg for data[end] != '\n' { end++ } end++ if pre := p.quotePrefix(data[beg:]); pre > 0 { // skip the prefix beg += pre } else if p.isEmpty(data[beg:]) > 0 && (end >= len(data) || (p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0)) { // blockquote ends with at least one blank line // followed by something without a blockquote prefix break } // this line is part of the blockquote raw.Write(data[beg:end]) beg = end } var cooked bytes.Buffer p.block(&cooked, raw.Bytes()) p.r.BlockQuote(out, cooked.Bytes()) return end } // returns prefix length for block code func (p *parser) codePrefix(data []byte) int { if data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' { return 4 } return 0 } func (p *parser) code(out *bytes.Buffer, data []byte) int { var work bytes.Buffer i := 0 for i < len(data) { beg := i for data[i] != '\n' { i++ } i++ blankline := p.isEmpty(data[beg:i]) > 0 if pre := p.codePrefix(data[beg:i]); pre > 0 { beg += pre } else if !blankline { // non-empty, non-prefixed line breaks the pre i = beg break } // verbatim copy to the working buffeu if blankline { work.WriteByte('\n') } else { work.Write(data[beg:i]) } } // trim all the \n off the end of work workbytes := work.Bytes() eol := len(workbytes) for eol > 0 && workbytes[eol-1] == '\n' { eol-- } if eol != len(workbytes) { work.Truncate(eol) } work.WriteByte('\n') p.r.BlockCode(out, work.Bytes(), "") return i } // returns unordered list item prefix func (p *parser) uliPrefix(data []byte) int { i := 0 // start with up to 3 spaces for i < 3 && data[i] == ' ' { i++ } // need a *, +, or - followed by a space if (data[i] != '*' && data[i] != '+' && data[i] != '-') || data[i+1] != ' ' { return 0 } return i + 2 } // returns ordered list item prefix func (p *parser) oliPrefix(data []byte) int { i := 0 // start with up to 3 spaces for i < 3 && data[i] == ' ' { i++ } // count the digits start := i for data[i] >= '0' && data[i] <= '9' { i++ } // we need >= 1 digits followed by a dot and a space if start == i || data[i] != '.' || data[i+1] != ' ' { return 0 } return i + 2 } // parse ordered or unordered list block func (p *parser) list(out *bytes.Buffer, data []byte, flags int) int { i := 0 flags |= LIST_ITEM_BEGINNING_OF_LIST work := func() bool { for i < len(data) { skip := p.listItem(out, data[i:], &flags) i += skip if skip == 0 || flags&LIST_ITEM_END_OF_LIST != 0 { break } flags &= ^LIST_ITEM_BEGINNING_OF_LIST } return true } p.r.List(out, work, flags) return i } // Parse a single list item. // Assumes initial prefix is already removed if this is a sublist. func (p *parser) listItem(out *bytes.Buffer, data []byte, flags *int) int { // keep track of the indentation of the first line itemIndent := 0 for itemIndent < 3 && data[itemIndent] == ' ' { itemIndent++ } i := p.uliPrefix(data) if i == 0 { i = p.oliPrefix(data) } if i == 0 { return 0 } // skip leading whitespace on first line for data[i] == ' ' { i++ } // find the end of the line line := i for data[i-1] != '\n' { i++ } // get working buffer var raw bytes.Buffer // put the first line into the working buffer raw.Write(data[line:i]) line = i // process the following lines containsBlankLine := false sublist := 0 gatherlines: for line < len(data) { i++ // find the end of this line for data[i-1] != '\n' { i++ } // if it is an empty line, guess that it is part of this item // and move on to the next line if p.isEmpty(data[line:i]) > 0 { containsBlankLine = true line = i continue } // calculate the indentation indent := 0 for indent < 4 && line+indent < i && data[line+indent] == ' ' { indent++ } chunk := data[line+indent : i] // evaluate how this line fits in switch { // is this a nested list item? case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) || p.oliPrefix(chunk) > 0: if containsBlankLine { *flags |= LIST_ITEM_CONTAINS_BLOCK } // to be a nested list, it must be indented more // if not, it is the next item in the same list if indent <= itemIndent { break gatherlines } // is this the first item in the the nested list? if sublist == 0 { sublist = raw.Len() } // is this a nested prefix header? case p.isPrefixHeader(chunk): // if the header is not indented, it is not nested in the list // and thus ends the list if containsBlankLine && indent < 4 { *flags |= LIST_ITEM_END_OF_LIST break gatherlines } *flags |= LIST_ITEM_CONTAINS_BLOCK // anything following an empty line is only part // of this item if it is indented 4 spaces // (regardless of the indentation of the beginning of the item) case containsBlankLine && indent < 4: *flags |= LIST_ITEM_END_OF_LIST break gatherlines // a blank line means this should be parsed as a block case containsBlankLine: raw.WriteByte('\n') *flags |= LIST_ITEM_CONTAINS_BLOCK } // if this line was preceeded by one or more blanks, // re-introduce the blank into the buffer if containsBlankLine { containsBlankLine = false raw.WriteByte('\n') } // add the line into the working buffer without prefix raw.Write(data[line+indent : i]) line = i } rawBytes := raw.Bytes() // render the contents of the list item var cooked bytes.Buffer if *flags&LIST_ITEM_CONTAINS_BLOCK != 0 { // intermediate render of block li if sublist > 0 { p.block(&cooked, rawBytes[:sublist]) p.block(&cooked, rawBytes[sublist:]) } else { p.block(&cooked, rawBytes) } } else { // intermediate render of inline li if sublist > 0 { p.inline(&cooked, rawBytes[:sublist]) p.block(&cooked, rawBytes[sublist:]) } else { p.inline(&cooked, rawBytes) } } // render the actual list item cookedBytes := cooked.Bytes() parsedEnd := len(cookedBytes) // strip trailing newlines for parsedEnd > 0 && cookedBytes[parsedEnd-1] == '\n' { parsedEnd-- } p.r.ListItem(out, cookedBytes[:parsedEnd], *flags) return line } // render a single paragraph that has already been parsed out func (p *parser) renderParagraph(out *bytes.Buffer, data []byte) { if len(data) == 0 { return } // trim leading spaces beg := 0 for data[beg] == ' ' { beg++ } // trim trailing newline end := len(data) - 1 // trim trailing spaces for end > beg && data[end-1] == ' ' { end-- } work := func() bool { p.inline(out, data[beg:end]) return true } p.r.Paragraph(out, work) } func (p *parser) paragraph(out *bytes.Buffer, data []byte) int { // prev: index of 1st char of previous line // line: index of 1st char of current line // i: index of cursor/end of current line var prev, line, i int // keep going until we find something to mark the end of the paragraph for i < len(data) { // mark the beginning of the current line prev = line current := data[i:] line = i // did we find a blank line marking the end of the paragraph? if n := p.isEmpty(current); n > 0 { p.renderParagraph(out, data[:i]) return i + n } // an underline under some text marks a header, so our paragraph ended on prev line if i > 0 { if level := p.isUnderlinedHeader(current); level > 0 { // render the paragraph p.renderParagraph(out, data[:prev]) // ignore leading and trailing whitespace eol := i - 1 for prev < eol && data[prev] == ' ' { prev++ } for eol > prev && data[eol-1] == ' ' { eol-- } // render the header // this ugly double closure avoids forcing variables onto the heap work := func(o *bytes.Buffer, pp *parser, d []byte) func() bool { return func() bool { pp.inline(o, d) return true } }(out, p, data[prev:eol]) id := "" if p.flags&EXTENSION_AUTO_HEADER_IDS != 0 { id = sanitized_anchor_name.Create(string(data[prev:eol])) } p.r.Header(out, work, level, id) // find the end of the underline for data[i] != '\n' { i++ } return i } } // if the next line starts a block of HTML, then the paragraph ends here if p.flags&EXTENSION_LAX_HTML_BLOCKS != 0 { if data[i] == '<' && p.html(out, current, false) > 0 { // rewind to before the HTML block p.renderParagraph(out, data[:i]) return i } } // if there's a prefixed header or a horizontal rule after this, paragraph is over if p.isPrefixHeader(current) || p.isHRule(current) { p.renderParagraph(out, data[:i]) return i } // if there's a list after this, paragraph is over if p.flags&EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK != 0 { if p.uliPrefix(current) != 0 || p.oliPrefix(current) != 0 || p.quotePrefix(current) != 0 || p.codePrefix(current) != 0 { p.renderParagraph(out, data[:i]) return i } } // otherwise, scan to the beginning of the next line for data[i] != '\n' { i++ } i++ } p.renderParagraph(out, data[:i]) return i } ================================================ FILE: vendor/github.com/russross/blackfriday/block_test.go ================================================ // // Blackfriday Markdown Processor // Available at http://github.com/russross/blackfriday // // Copyright © 2011 Russ Ross . // Distributed under the Simplified BSD License. // See README.md for details. // // // Unit tests for block parsing // package blackfriday import ( "testing" ) func runMarkdownBlockWithRenderer(input string, extensions int, renderer Renderer) string { return string(Markdown([]byte(input), renderer, extensions)) } func runMarkdownBlock(input string, extensions int) string { htmlFlags := 0 htmlFlags |= HTML_USE_XHTML renderer := HtmlRenderer(htmlFlags, "", "") return runMarkdownBlockWithRenderer(input, extensions, renderer) } func runnerWithRendererParameters(parameters HtmlRendererParameters) func(string, int) string { return func(input string, extensions int) string { htmlFlags := 0 htmlFlags |= HTML_USE_XHTML renderer := HtmlRendererWithParameters(htmlFlags, "", "", parameters) return runMarkdownBlockWithRenderer(input, extensions, renderer) } } func doTestsBlock(t *testing.T, tests []string, extensions int) { doTestsBlockWithRunner(t, tests, extensions, runMarkdownBlock) } func doTestsBlockWithRunner(t *testing.T, tests []string, extensions int, runner func(string, int) string) { // catch and report panics var candidate string defer func() { if err := recover(); err != nil { t.Errorf("\npanic while processing [%#v]: %s\n", candidate, err) } }() for i := 0; i+1 < len(tests); i += 2 { input := tests[i] candidate = input expected := tests[i+1] actual := runner(candidate, extensions) if actual != expected { t.Errorf("\nInput [%#v]\nExpected[%#v]\nActual [%#v]", candidate, expected, actual) } // now test every substring to stress test bounds checking if !testing.Short() { for start := 0; start < len(input); start++ { for end := start + 1; end <= len(input); end++ { candidate = input[start:end] _ = runMarkdownBlock(candidate, extensions) } } } } } func TestPrefixHeaderNoExtensions(t *testing.T) { var tests = []string{ "# Header 1\n", "

Header 1

\n", "## Header 2\n", "

Header 2

\n", "### Header 3\n", "

Header 3

\n", "#### Header 4\n", "

Header 4

\n", "##### Header 5\n", "
Header 5
\n", "###### Header 6\n", "
Header 6
\n", "####### Header 7\n", "
# Header 7
\n", "#Header 1\n", "

Header 1

\n", "##Header 2\n", "

Header 2

\n", "###Header 3\n", "

Header 3

\n", "####Header 4\n", "

Header 4

\n", "#####Header 5\n", "
Header 5
\n", "######Header 6\n", "
Header 6
\n", "#######Header 7\n", "
#Header 7
\n", "Hello\n# Header 1\nGoodbye\n", "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", "* List\n# Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n#Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n * Nested list\n # Nested header\n", "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + "

      Nested header

    • \n
  • \n
\n", } doTestsBlock(t, tests, 0) } func TestPrefixHeaderSpaceExtension(t *testing.T) { var tests = []string{ "# Header 1\n", "

Header 1

\n", "## Header 2\n", "

Header 2

\n", "### Header 3\n", "

Header 3

\n", "#### Header 4\n", "

Header 4

\n", "##### Header 5\n", "
Header 5
\n", "###### Header 6\n", "
Header 6
\n", "####### Header 7\n", "

####### Header 7

\n", "#Header 1\n", "

#Header 1

\n", "##Header 2\n", "

##Header 2

\n", "###Header 3\n", "

###Header 3

\n", "####Header 4\n", "

####Header 4

\n", "#####Header 5\n", "

#####Header 5

\n", "######Header 6\n", "

######Header 6

\n", "#######Header 7\n", "

#######Header 7

\n", "Hello\n# Header 1\nGoodbye\n", "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", "* List\n# Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n#Header\n* List\n", "
    \n
  • List\n#Header
  • \n
  • List
  • \n
\n", "* List\n * Nested list\n # Nested header\n", "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + "

      Nested header

    • \n
  • \n
\n", } doTestsBlock(t, tests, EXTENSION_SPACE_HEADERS) } func TestPrefixHeaderIdExtension(t *testing.T) { var tests = []string{ "# Header 1 {#someid}\n", "

Header 1

\n", "# Header 1 {#someid} \n", "

Header 1

\n", "# Header 1 {#someid}\n", "

Header 1

\n", "# Header 1 {#someid\n", "

Header 1 {#someid

\n", "# Header 1 {#someid\n", "

Header 1 {#someid

\n", "# Header 1 {#someid}}\n", "

Header 1

\n\n

}

\n", "## Header 2 {#someid}\n", "

Header 2

\n", "### Header 3 {#someid}\n", "

Header 3

\n", "#### Header 4 {#someid}\n", "

Header 4

\n", "##### Header 5 {#someid}\n", "
Header 5
\n", "###### Header 6 {#someid}\n", "
Header 6
\n", "####### Header 7 {#someid}\n", "
# Header 7
\n", "# Header 1 # {#someid}\n", "

Header 1

\n", "## Header 2 ## {#someid}\n", "

Header 2

\n", "Hello\n# Header 1\nGoodbye\n", "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", "* List\n# Header {#someid}\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n#Header {#someid}\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n * Nested list\n # Nested header {#someid}\n", "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + "

      Nested header

    • \n
  • \n
\n", } doTestsBlock(t, tests, EXTENSION_HEADER_IDS) } func TestPrefixHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) { var tests = []string{ "# header 1 {#someid}\n", "

header 1

\n", "## header 2 {#someid}\n", "

header 2

\n", "### header 3 {#someid}\n", "

header 3

\n", "#### header 4 {#someid}\n", "

header 4

\n", "##### header 5 {#someid}\n", "
header 5
\n", "###### header 6 {#someid}\n", "
header 6
\n", "####### header 7 {#someid}\n", "
# header 7
\n", "# header 1 # {#someid}\n", "

header 1

\n", "## header 2 ## {#someid}\n", "

header 2

\n", "* List\n# Header {#someid}\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n#Header {#someid}\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n * Nested list\n # Nested header {#someid}\n", "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + "

      Nested header

    • \n
  • \n
\n", } parameters := HtmlRendererParameters{ HeaderIDPrefix: "PRE:", HeaderIDSuffix: ":POST", } doTestsBlockWithRunner(t, tests, EXTENSION_HEADER_IDS, runnerWithRendererParameters(parameters)) } func TestPrefixAutoHeaderIdExtension(t *testing.T) { var tests = []string{ "# Header 1\n", "

Header 1

\n", "# Header 1 \n", "

Header 1

\n", "## Header 2\n", "

Header 2

\n", "### Header 3\n", "

Header 3

\n", "#### Header 4\n", "

Header 4

\n", "##### Header 5\n", "
Header 5
\n", "###### Header 6\n", "
Header 6
\n", "####### Header 7\n", "
# Header 7
\n", "Hello\n# Header 1\nGoodbye\n", "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", "* List\n# Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n#Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n * Nested list\n # Nested header\n", "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + "

      Nested header

    • \n
  • \n
\n", "# Header\n\n# Header\n", "

Header

\n\n

Header

\n", "# Header 1\n\n# Header 1", "

Header 1

\n\n

Header 1

\n", "# Header\n\n# Header 1\n\n# Header\n\n# Header", "

Header

\n\n

Header 1

\n\n

Header

\n\n

Header

\n", } doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS) } func TestPrefixAutoHeaderIdExtensionWithPrefixAndSuffix(t *testing.T) { var tests = []string{ "# Header 1\n", "

Header 1

\n", "# Header 1 \n", "

Header 1

\n", "## Header 2\n", "

Header 2

\n", "### Header 3\n", "

Header 3

\n", "#### Header 4\n", "

Header 4

\n", "##### Header 5\n", "
Header 5
\n", "###### Header 6\n", "
Header 6
\n", "####### Header 7\n", "
# Header 7
\n", "Hello\n# Header 1\nGoodbye\n", "

Hello

\n\n

Header 1

\n\n

Goodbye

\n", "* List\n# Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n#Header\n* List\n", "
    \n
  • List

    \n\n

    Header

  • \n\n
  • List

  • \n
\n", "* List\n * Nested list\n # Nested header\n", "
    \n
  • List

    \n\n
      \n
    • Nested list

      \n\n" + "

      Nested header

    • \n
  • \n
\n", "# Header\n\n# Header\n", "

Header

\n\n

Header

\n", "# Header 1\n\n# Header 1", "

Header 1

\n\n

Header 1

\n", "# Header\n\n# Header 1\n\n# Header\n\n# Header", "

Header

\n\n

Header 1

\n\n

Header

\n\n

Header

\n", } parameters := HtmlRendererParameters{ HeaderIDPrefix: "PRE:", HeaderIDSuffix: ":POST", } doTestsBlockWithRunner(t, tests, EXTENSION_AUTO_HEADER_IDS, runnerWithRendererParameters(parameters)) } func TestPrefixMultipleHeaderExtensions(t *testing.T) { var tests = []string{ "# Header\n\n# Header {#header}\n\n# Header 1", "

Header

\n\n

Header

\n\n

Header 1

\n", } doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS|EXTENSION_HEADER_IDS) } func TestUnderlineHeaders(t *testing.T) { var tests = []string{ "Header 1\n========\n", "

Header 1

\n", "Header 2\n--------\n", "

Header 2

\n", "A\n=\n", "

A

\n", "B\n-\n", "

B

\n", "Paragraph\nHeader\n=\n", "

Paragraph

\n\n

Header

\n", "Header\n===\nParagraph\n", "

Header

\n\n

Paragraph

\n", "Header\n===\nAnother header\n---\n", "

Header

\n\n

Another header

\n", " Header\n======\n", "

Header

\n", " Code\n========\n", "
Code\n
\n\n

========

\n", "Header with *inline*\n=====\n", "

Header with inline

\n", "* List\n * Sublist\n Not a header\n ------\n", "
    \n
  • List\n\n
      \n
    • Sublist\nNot a header\n------
    • \n
  • \n
\n", "Paragraph\n\n\n\n\nHeader\n===\n", "

Paragraph

\n\n

Header

\n", "Trailing space \n==== \n\n", "

Trailing space

\n", "Trailing spaces\n==== \n\n", "

Trailing spaces

\n", "Double underline\n=====\n=====\n", "

Double underline

\n\n

=====

\n", } doTestsBlock(t, tests, 0) } func TestUnderlineHeadersAutoIDs(t *testing.T) { var tests = []string{ "Header 1\n========\n", "

Header 1

\n", "Header 2\n--------\n", "

Header 2

\n", "A\n=\n", "

A

\n", "B\n-\n", "

B

\n", "Paragraph\nHeader\n=\n", "

Paragraph

\n\n

Header

\n", "Header\n===\nParagraph\n", "

Header

\n\n

Paragraph

\n", "Header\n===\nAnother header\n---\n", "

Header

\n\n

Another header

\n", " Header\n======\n", "

Header

\n", "Header with *inline*\n=====\n", "

Header with inline

\n", "Paragraph\n\n\n\n\nHeader\n===\n", "

Paragraph

\n\n

Header

\n", "Trailing space \n==== \n\n", "

Trailing space

\n", "Trailing spaces\n==== \n\n", "

Trailing spaces

\n", "Double underline\n=====\n=====\n", "

Double underline

\n\n

=====

\n", "Header\n======\n\nHeader\n======\n", "

Header

\n\n

Header

\n", "Header 1\n========\n\nHeader 1\n========\n", "

Header 1

\n\n

Header 1

\n", } doTestsBlock(t, tests, EXTENSION_AUTO_HEADER_IDS) } func TestHorizontalRule(t *testing.T) { var tests = []string{ "-\n", "

-

\n", "--\n", "

--

\n", "---\n", "
\n", "----\n", "
\n", "*\n", "

*

\n", "**\n", "

**

\n", "***\n", "
\n", "****\n", "
\n", "_\n", "

_

\n", "__\n", "

__

\n", "___\n", "
\n", "____\n", "
\n", "-*-\n", "

-*-

\n", "- - -\n", "
\n", "* * *\n", "
\n", "_ _ _\n", "
\n", "-----*\n", "

-----*

\n", " ------ \n", "
\n", "Hello\n***\n", "

Hello

\n\n
\n", "---\n***\n___\n", "
\n\n
\n\n
\n", } doTestsBlock(t, tests, 0) } func TestUnorderedList(t *testing.T) { var tests = []string{ "* Hello\n", "
    \n
  • Hello
  • \n
\n", "* Yin\n* Yang\n", "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", "* Ting\n* Bong\n* Goo\n", "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", "* Yin\n\n* Yang\n", "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", "* Ting\n\n* Bong\n* Goo\n", "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", "+ Hello\n", "
    \n
  • Hello
  • \n
\n", "+ Yin\n+ Yang\n", "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", "+ Ting\n+ Bong\n+ Goo\n", "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", "+ Yin\n\n+ Yang\n", "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", "+ Ting\n\n+ Bong\n+ Goo\n", "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", "- Hello\n", "
    \n
  • Hello
  • \n
\n", "- Yin\n- Yang\n", "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", "- Ting\n- Bong\n- Goo\n", "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", "- Yin\n\n- Yang\n", "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", "- Ting\n\n- Bong\n- Goo\n", "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", "*Hello\n", "

*Hello

\n", "* Hello \n", "
    \n
  • Hello
  • \n
\n", "* Hello \n Next line \n", "
    \n
  • Hello\nNext line
  • \n
\n", "Paragraph\n* No linebreak\n", "

Paragraph\n* No linebreak

\n", "Paragraph\n\n* Linebreak\n", "

Paragraph

\n\n
    \n
  • Linebreak
  • \n
\n", "* List\n * Nested list\n", "
    \n
  • List\n\n
      \n
    • Nested list
    • \n
  • \n
\n", "* List\n\n * Nested list\n", "
    \n
  • List

    \n\n
      \n
    • Nested list
    • \n
  • \n
\n", "* List\n Second line\n\n + Nested\n", "
    \n
  • List\nSecond line

    \n\n
      \n
    • Nested
    • \n
  • \n
\n", "* List\n + Nested\n\n Continued\n", "
    \n
  • List

    \n\n
      \n
    • Nested
    • \n
    \n\n

    Continued

  • \n
\n", "* List\n * shallow indent\n", "
    \n
  • List\n\n
      \n
    • shallow indent
    • \n
  • \n
\n", "* List\n" + " * shallow indent\n" + " * part of second list\n" + " * still second\n" + " * almost there\n" + " * third level\n", "
    \n" + "
  • List\n\n" + "
      \n" + "
    • shallow indent
    • \n" + "
    • part of second list
    • \n" + "
    • still second
    • \n" + "
    • almost there\n\n" + "
        \n" + "
      • third level
      • \n" + "
    • \n" + "
  • \n" + "
\n", "* List\n extra indent, same paragraph\n", "
    \n
  • List\n extra indent, same paragraph
  • \n
\n", "* List\n\n code block\n", "
    \n
  • List

    \n\n
    code block\n
  • \n
\n", "* List\n\n code block with spaces\n", "
    \n
  • List

    \n\n
      code block with spaces\n
  • \n
\n", "* List\n\n * sublist\n\n normal text\n\n * another sublist\n", "
    \n
  • List

    \n\n
      \n
    • sublist
    • \n
    \n\n

    normal text

    \n\n
      \n
    • another sublist
    • \n
  • \n
\n", } doTestsBlock(t, tests, 0) } func TestOrderedList(t *testing.T) { var tests = []string{ "1. Hello\n", "
    \n
  1. Hello
  2. \n
\n", "1. Yin\n2. Yang\n", "
    \n
  1. Yin
  2. \n
  3. Yang
  4. \n
\n", "1. Ting\n2. Bong\n3. Goo\n", "
    \n
  1. Ting
  2. \n
  3. Bong
  4. \n
  5. Goo
  6. \n
\n", "1. Yin\n\n2. Yang\n", "
    \n
  1. Yin

  2. \n\n
  3. Yang

  4. \n
\n", "1. Ting\n\n2. Bong\n3. Goo\n", "
    \n
  1. Ting

  2. \n\n
  3. Bong

  4. \n\n
  5. Goo

  6. \n
\n", "1 Hello\n", "

1 Hello

\n", "1.Hello\n", "

1.Hello

\n", "1. Hello \n", "
    \n
  1. Hello
  2. \n
\n", "1. Hello \n Next line \n", "
    \n
  1. Hello\nNext line
  2. \n
\n", "Paragraph\n1. No linebreak\n", "

Paragraph\n1. No linebreak

\n", "Paragraph\n\n1. Linebreak\n", "

Paragraph

\n\n
    \n
  1. Linebreak
  2. \n
\n", "1. List\n 1. Nested list\n", "
    \n
  1. List\n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", "1. List\n\n 1. Nested list\n", "
    \n
  1. List

    \n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", "1. List\n Second line\n\n 1. Nested\n", "
    \n
  1. List\nSecond line

    \n\n
      \n
    1. Nested
    2. \n
  2. \n
\n", "1. List\n 1. Nested\n\n Continued\n", "
    \n
  1. List

    \n\n
      \n
    1. Nested
    2. \n
    \n\n

    Continued

  2. \n
\n", "1. List\n 1. shallow indent\n", "
    \n
  1. List\n\n
      \n
    1. shallow indent
    2. \n
  2. \n
\n", "1. List\n" + " 1. shallow indent\n" + " 2. part of second list\n" + " 3. still second\n" + " 4. almost there\n" + " 1. third level\n", "
    \n" + "
  1. List\n\n" + "
      \n" + "
    1. shallow indent
    2. \n" + "
    3. part of second list
    4. \n" + "
    5. still second
    6. \n" + "
    7. almost there\n\n" + "
        \n" + "
      1. third level
      2. \n" + "
    8. \n" + "
  2. \n" + "
\n", "1. List\n extra indent, same paragraph\n", "
    \n
  1. List\n extra indent, same paragraph
  2. \n
\n", "1. List\n\n code block\n", "
    \n
  1. List

    \n\n
    code block\n
  2. \n
\n", "1. List\n\n code block with spaces\n", "
    \n
  1. List

    \n\n
      code block with spaces\n
  2. \n
\n", "1. List\n * Mixted list\n", "
    \n
  1. List\n\n
      \n
    • Mixted list
    • \n
  2. \n
\n", "1. List\n * Mixed list\n", "
    \n
  1. List\n\n
      \n
    • Mixed list
    • \n
  2. \n
\n", "* Start with unordered\n 1. Ordered\n", "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", "* Start with unordered\n 1. Ordered\n", "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", "1. numbers\n1. are ignored\n", "
    \n
  1. numbers
  2. \n
  3. are ignored
  4. \n
\n", } doTestsBlock(t, tests, 0) } func TestPreformattedHtml(t *testing.T) { var tests = []string{ "
\n", "
\n", "
\n
\n", "
\n
\n", "
\n
\nParagraph\n", "

\n
\nParagraph

\n", "
\n
\n", "
\n
\n", "
\nAnything here\n
\n", "
\nAnything here\n
\n", "
\n Anything here\n
\n", "
\n Anything here\n
\n", "
\nAnything here\n
\n", "
\nAnything here\n
\n", "
\nThis is *not* &proceessed\n
\n", "
\nThis is *not* &proceessed\n
\n", "\n Something\n\n", "

\n Something\n

\n", "
\n Something here\n\n", "

\n Something here\n

\n", "Paragraph\n
\nHere? >&<\n
\n", "

Paragraph\n

\nHere? >&<\n

\n", "Paragraph\n\n
\nHow about here? >&<\n
\n", "

Paragraph

\n\n
\nHow about here? >&<\n
\n", "Paragraph\n
\nHere? >&<\n
\nAnd here?\n", "

Paragraph\n

\nHere? >&<\n
\nAnd here?

\n", "Paragraph\n\n
\nHow about here? >&<\n
\nAnd here?\n", "

Paragraph

\n\n

\nHow about here? >&<\n
\nAnd here?

\n", "Paragraph\n
\nHere? >&<\n
\n\nAnd here?\n", "

Paragraph\n

\nHere? >&<\n

\n\n

And here?

\n", "Paragraph\n\n
\nHow about here? >&<\n
\n\nAnd here?\n", "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", } doTestsBlock(t, tests, 0) } func TestPreformattedHtmlLax(t *testing.T) { var tests = []string{ "Paragraph\n
\nHere? >&<\n
\n", "

Paragraph

\n\n
\nHere? >&<\n
\n", "Paragraph\n\n
\nHow about here? >&<\n
\n", "

Paragraph

\n\n
\nHow about here? >&<\n
\n", "Paragraph\n
\nHere? >&<\n
\nAnd here?\n", "

Paragraph

\n\n
\nHere? >&<\n
\n\n

And here?

\n", "Paragraph\n\n
\nHow about here? >&<\n
\nAnd here?\n", "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", "Paragraph\n
\nHere? >&<\n
\n\nAnd here?\n", "

Paragraph

\n\n
\nHere? >&<\n
\n\n

And here?

\n", "Paragraph\n\n
\nHow about here? >&<\n
\n\nAnd here?\n", "

Paragraph

\n\n
\nHow about here? >&<\n
\n\n

And here?

\n", } doTestsBlock(t, tests, EXTENSION_LAX_HTML_BLOCKS) } func TestFencedCodeBlock(t *testing.T) { var tests = []string{ "``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n", "
func foo() bool {\n\treturn true;\n}\n
\n", "``` c\n/* special & char < > \" escaping */\n```\n", "
/* special & char < > " escaping */\n
\n", "``` c\nno *inline* processing ~~of text~~\n```\n", "
no *inline* processing ~~of text~~\n
\n", "```\nNo language\n```\n", "
No language\n
\n", "``` {ocaml}\nlanguage in braces\n```\n", "
language in braces\n
\n", "``` {ocaml} \nwith extra whitespace\n```\n", "
with extra whitespace\n
\n", "```{ ocaml }\nwith extra whitespace\n```\n", "
with extra whitespace\n
\n", "~ ~~ java\nWith whitespace\n~~~\n", "

~ ~~ java\nWith whitespace\n~~~

\n", "~~\nonly two\n~~\n", "

~~\nonly two\n~~

\n", "```` python\nextra\n````\n", "
extra\n
\n", "~~~ perl\nthree to start, four to end\n~~~~\n", "

~~~ perl\nthree to start, four to end\n~~~~

\n", "~~~~ perl\nfour to start, three to end\n~~~\n", "

~~~~ perl\nfour to start, three to end\n~~~

\n", "~~~ bash\ntildes\n~~~\n", "
tildes\n
\n", "``` lisp\nno ending\n", "

``` lisp\nno ending

\n", "~~~ lisp\nend with language\n~~~ lisp\n", "

~~~ lisp\nend with language\n~~~ lisp

\n", "```\nmismatched begin and end\n~~~\n", "

```\nmismatched begin and end\n~~~

\n", "~~~\nmismatched begin and end\n```\n", "

~~~\nmismatched begin and end\n```

\n", " ``` oz\nleading spaces\n```\n", "
leading spaces\n
\n", " ``` oz\nleading spaces\n ```\n", "
leading spaces\n
\n", " ``` oz\nleading spaces\n ```\n", "
leading spaces\n
\n", "``` oz\nleading spaces\n ```\n", "
leading spaces\n
\n", " ``` oz\nleading spaces\n ```\n", "
``` oz\n
\n\n

leading spaces\n ```

\n", "Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n", "

Bla bla

\n\n
code blocks breakup paragraphs\n
\n\n

Bla Bla

\n", "Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nAnd some text after a fenced code block", "

Some text before a fenced code block

\n\n
code blocks breakup paragraphs\n
\n\n

And some text after a fenced code block

\n", "`", "

`

\n", "Bla bla\n\n``` oz\ncode blocks breakup paragraphs\n```\n\nBla Bla\n\n``` oz\nmultiple code blocks work okay\n```\n\nBla Bla\n", "

Bla bla

\n\n
code blocks breakup paragraphs\n
\n\n

Bla Bla

\n\n
multiple code blocks work okay\n
\n\n

Bla Bla

\n", "Some text before a fenced code block\n``` oz\ncode blocks breakup paragraphs\n```\nSome text in between\n``` oz\nmultiple code blocks work okay\n```\nAnd some text after a fenced code block", "

Some text before a fenced code block

\n\n
code blocks breakup paragraphs\n
\n\n

Some text in between

\n\n
multiple code blocks work okay\n
\n\n

And some text after a fenced code block

\n", } doTestsBlock(t, tests, EXTENSION_FENCED_CODE) } func TestTable(t *testing.T) { var tests = []string{ "a | b\n---|---\nc | d\n", "\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n
ab
cd
\n", "a | b\n---|--\nc | d\n", "

a | b\n---|--\nc | d

\n", "|a|b|c|d|\n|----|----|----|---|\n|e|f|g|h|\n", "\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n
abcd
efgh
\n", "*a*|__b__|[c](C)|d\n---|---|---|---\ne|f|g|h\n", "\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n
abcd
efgh
\n", "a|b|c\n---|---|---\nd|e|f\ng|h\ni|j|k|l|m\nn|o|p\n", "\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n" + "\n\n\n\n\n\n" + "\n\n\n\n\n\n" + "\n\n\n\n\n\n
abc
def
gh
ijk
nop
\n", "a|b|c\n---|---|---\n*d*|__e__|f\n", "\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n
abc
def
\n", "a|b|c|d\n:--|--:|:-:|---\ne|f|g|h\n", "\n\n\n\n\n" + "\n\n\n\n\n" + "\n\n\n\n" + "\n\n\n\n
abcd
efgh
\n", "a|b|c\n---|---|---\n", "\n\n\n\n\n\n\n\n\n\n\n
abc
\n", "a| b|c | d | e\n---|---|---|---|---\nf| g|h | i |j\n", "\n\n\n\n\n\n\n\n\n\n\n" + "\n\n\n\n\n\n\n\n\n
abcde
fghij
\n", "a|b\\|c|d\n---|---|---\nf|g\\|h|i\n", "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ab|cd
fg|hi
\n", } doTestsBlock(t, tests, EXTENSION_TABLES) } func TestUnorderedListWith_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { var tests = []string{ "* Hello\n", "
    \n
  • Hello
  • \n
\n", "* Yin\n* Yang\n", "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", "* Ting\n* Bong\n* Goo\n", "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", "* Yin\n\n* Yang\n", "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", "* Ting\n\n* Bong\n* Goo\n", "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", "+ Hello\n", "
    \n
  • Hello
  • \n
\n", "+ Yin\n+ Yang\n", "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", "+ Ting\n+ Bong\n+ Goo\n", "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", "+ Yin\n\n+ Yang\n", "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", "+ Ting\n\n+ Bong\n+ Goo\n", "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", "- Hello\n", "
    \n
  • Hello
  • \n
\n", "- Yin\n- Yang\n", "
    \n
  • Yin
  • \n
  • Yang
  • \n
\n", "- Ting\n- Bong\n- Goo\n", "
    \n
  • Ting
  • \n
  • Bong
  • \n
  • Goo
  • \n
\n", "- Yin\n\n- Yang\n", "
    \n
  • Yin

  • \n\n
  • Yang

  • \n
\n", "- Ting\n\n- Bong\n- Goo\n", "
    \n
  • Ting

  • \n\n
  • Bong

  • \n\n
  • Goo

  • \n
\n", "*Hello\n", "

*Hello

\n", "* Hello \n", "
    \n
  • Hello
  • \n
\n", "* Hello \n Next line \n", "
    \n
  • Hello\nNext line
  • \n
\n", "Paragraph\n* No linebreak\n", "

Paragraph

\n\n
    \n
  • No linebreak
  • \n
\n", "Paragraph\n\n* Linebreak\n", "

Paragraph

\n\n
    \n
  • Linebreak
  • \n
\n", "* List\n * Nested list\n", "
    \n
  • List\n\n
      \n
    • Nested list
    • \n
  • \n
\n", "* List\n\n * Nested list\n", "
    \n
  • List

    \n\n
      \n
    • Nested list
    • \n
  • \n
\n", "* List\n Second line\n\n + Nested\n", "
    \n
  • List\nSecond line

    \n\n
      \n
    • Nested
    • \n
  • \n
\n", "* List\n + Nested\n\n Continued\n", "
    \n
  • List

    \n\n
      \n
    • Nested
    • \n
    \n\n

    Continued

  • \n
\n", "* List\n * shallow indent\n", "
    \n
  • List\n\n
      \n
    • shallow indent
    • \n
  • \n
\n", "* List\n" + " * shallow indent\n" + " * part of second list\n" + " * still second\n" + " * almost there\n" + " * third level\n", "
    \n" + "
  • List\n\n" + "
      \n" + "
    • shallow indent
    • \n" + "
    • part of second list
    • \n" + "
    • still second
    • \n" + "
    • almost there\n\n" + "
        \n" + "
      • third level
      • \n" + "
    • \n" + "
  • \n" + "
\n", "* List\n extra indent, same paragraph\n", "
    \n
  • List\n extra indent, same paragraph
  • \n
\n", "* List\n\n code block\n", "
    \n
  • List

    \n\n
    code block\n
  • \n
\n", "* List\n\n code block with spaces\n", "
    \n
  • List

    \n\n
      code block with spaces\n
  • \n
\n", "* List\n\n * sublist\n\n normal text\n\n * another sublist\n", "
    \n
  • List

    \n\n
      \n
    • sublist
    • \n
    \n\n

    normal text

    \n\n
      \n
    • another sublist
    • \n
  • \n
\n", } doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) } func TestOrderedList_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { var tests = []string{ "1. Hello\n", "
    \n
  1. Hello
  2. \n
\n", "1. Yin\n2. Yang\n", "
    \n
  1. Yin
  2. \n
  3. Yang
  4. \n
\n", "1. Ting\n2. Bong\n3. Goo\n", "
    \n
  1. Ting
  2. \n
  3. Bong
  4. \n
  5. Goo
  6. \n
\n", "1. Yin\n\n2. Yang\n", "
    \n
  1. Yin

  2. \n\n
  3. Yang

  4. \n
\n", "1. Ting\n\n2. Bong\n3. Goo\n", "
    \n
  1. Ting

  2. \n\n
  3. Bong

  4. \n\n
  5. Goo

  6. \n
\n", "1 Hello\n", "

1 Hello

\n", "1.Hello\n", "

1.Hello

\n", "1. Hello \n", "
    \n
  1. Hello
  2. \n
\n", "1. Hello \n Next line \n", "
    \n
  1. Hello\nNext line
  2. \n
\n", "Paragraph\n1. No linebreak\n", "

Paragraph

\n\n
    \n
  1. No linebreak
  2. \n
\n", "Paragraph\n\n1. Linebreak\n", "

Paragraph

\n\n
    \n
  1. Linebreak
  2. \n
\n", "1. List\n 1. Nested list\n", "
    \n
  1. List\n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", "1. List\n\n 1. Nested list\n", "
    \n
  1. List

    \n\n
      \n
    1. Nested list
    2. \n
  2. \n
\n", "1. List\n Second line\n\n 1. Nested\n", "
    \n
  1. List\nSecond line

    \n\n
      \n
    1. Nested
    2. \n
  2. \n
\n", "1. List\n 1. Nested\n\n Continued\n", "
    \n
  1. List

    \n\n
      \n
    1. Nested
    2. \n
    \n\n

    Continued

  2. \n
\n", "1. List\n 1. shallow indent\n", "
    \n
  1. List\n\n
      \n
    1. shallow indent
    2. \n
  2. \n
\n", "1. List\n" + " 1. shallow indent\n" + " 2. part of second list\n" + " 3. still second\n" + " 4. almost there\n" + " 1. third level\n", "
    \n" + "
  1. List\n\n" + "
      \n" + "
    1. shallow indent
    2. \n" + "
    3. part of second list
    4. \n" + "
    5. still second
    6. \n" + "
    7. almost there\n\n" + "
        \n" + "
      1. third level
      2. \n" + "
    8. \n" + "
  2. \n" + "
\n", "1. List\n extra indent, same paragraph\n", "
    \n
  1. List\n extra indent, same paragraph
  2. \n
\n", "1. List\n\n code block\n", "
    \n
  1. List

    \n\n
    code block\n
  2. \n
\n", "1. List\n\n code block with spaces\n", "
    \n
  1. List

    \n\n
      code block with spaces\n
  2. \n
\n", "1. List\n * Mixted list\n", "
    \n
  1. List\n\n
      \n
    • Mixted list
    • \n
  2. \n
\n", "1. List\n * Mixed list\n", "
    \n
  1. List\n\n
      \n
    • Mixed list
    • \n
  2. \n
\n", "* Start with unordered\n 1. Ordered\n", "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", "* Start with unordered\n 1. Ordered\n", "
    \n
  • Start with unordered\n\n
      \n
    1. Ordered
    2. \n
  • \n
\n", "1. numbers\n1. are ignored\n", "
    \n
  1. numbers
  2. \n
  3. are ignored
  4. \n
\n", } doTestsBlock(t, tests, EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) } func TestFencedCodeBlock_EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK(t *testing.T) { var tests = []string{ "``` go\nfunc foo() bool {\n\treturn true;\n}\n```\n", "
func foo() bool {\n\treturn true;\n}\n
\n", "``` c\n/* special & char < > \" escaping */\n```\n", "
/* special & char < > " escaping */\n
\n", "``` c\nno *inline* processing ~~of text~~\n```\n", "
no *inline* processing ~~of text~~\n
\n", "```\nNo language\n```\n", "
No language\n
\n", "``` {ocaml}\nlanguage in braces\n```\n", "
language in braces\n
\n", "``` {ocaml} \nwith extra whitespace\n```\n", "
with extra whitespace\n
\n", "```{ ocaml }\nwith extra whitespace\n```\n", "
with extra whitespace\n
\n", "~ ~~ java\nWith whitespace\n~~~\n", "

~ ~~ java\nWith whitespace\n~~~

\n", "~~\nonly two\n~~\n", "

~~\nonly two\n~~

\n", "```` python\nextra\n````\n", "
extra\n
\n", "~~~ perl\nthree to start, four to end\n~~~~\n", "

~~~ perl\nthree to start, four to end\n~~~~

\n", "~~~~ perl\nfour to start, three to end\n~~~\n", "

~~~~ perl\nfour to start, three to end\n~~~

\n", "~~~ bash\ntildes\n~~~\n", "
tildes\n
\n", "``` lisp\nno ending\n", "

``` lisp\nno ending

\n", "~~~ lisp\nend with language\n~~~ lisp\n", "

~~~ lisp\nend with language\n~~~ lisp

\n", "```\nmismatched begin and end\n~~~\n", "

```\nmismatched begin and end\n~~~

\n", "~~~\nmismatched begin and end\n```\n", "

~~~\nmismatched begin and end\n```

\n", " ``` oz\nleading spaces\n```\n", "
leading spaces\n
\n", " ``` oz\nleading spaces\n ```\n", "
leading spaces\n
\n", " ``` oz\nleading spaces\n ```\n", "
leading spaces\n
\n", "``` oz\nleading spaces\n ```\n", "
leading spaces\n
\n", " ``` oz\nleading spaces\n ```\n", "
``` oz\n
\n\n

leading spaces

\n\n
```\n
\n", } doTestsBlock(t, tests, EXTENSION_FENCED_CODE|EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK) } func TestTitleBlock_EXTENSION_TITLEBLOCK(t *testing.T) { var tests = []string{ "% Some title\n" + "% Another title line\n" + "% Yep, more here too\n", "

" + "Some title\n" + "Another title line\n" + "Yep, more here too\n" + "

", } doTestsBlock(t, tests, EXTENSION_TITLEBLOCK) } ================================================ FILE: vendor/github.com/russross/blackfriday/html.go ================================================ // // Blackfriday Markdown Processor // Available at http://github.com/russross/blackfriday // // Copyright © 2011 Russ Ross . // Distributed under the Simplified BSD License. // See README.md for details. // // // // HTML rendering backend // // package blackfriday import ( "bytes" "fmt" "regexp" "strconv" "strings" ) // Html renderer configuration options. const ( HTML_SKIP_HTML = 1 << iota // skip preformatted HTML blocks HTML_SKIP_STYLE // skip embedded

HTTP charset

 

The character encoding of a page can be set using the HTTP header charset declaration.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

The only character encoding declaration for this HTML file is in the HTTP header, which sets the encoding to ISO 8859-15.

HTML5

the-input-byte-stream-001
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/HTTP-vs-UTF-8-BOM.html ================================================  HTTP vs UTF-8 BOM

HTTP vs UTF-8 BOM

 

A character encoding set in the HTTP header has lower precedence than the UTF-8 signature.

The HTTP header attempts to set the character encoding to ISO 8859-15. The page starts with a UTF-8 signature.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

If the test is unsuccessful, the characters  should appear at the top of the page. These represent the bytes that make up the UTF-8 signature when encountered in the ISO 8859-15 encoding.

HTML5

the-input-byte-stream-034
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-charset.html ================================================ HTTP vs meta charset

HTTP vs meta charset

 

The HTTP header has a higher precedence than an encoding declaration in a meta charset attribute.

The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-1.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-018
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/HTTP-vs-meta-content.html ================================================ HTTP vs meta content

HTTP vs meta content

 

The HTTP header has a higher precedence than an encoding declaration in a meta content attribute.

The HTTP header attempts to set the character encoding to ISO 8859-15. The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-1.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-016
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/No-encoding-declaration.html ================================================ No encoding declaration

No encoding declaration

 

A page with no encoding information in HTTP, BOM, XML declaration or meta element will be treated as UTF-8.

The test on this page contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-015
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/README ================================================ These test cases come from http://www.w3.org/International/tests/repository/html5/the-input-byte-stream/results-basics Distributed under both the W3C Test Suite License (http://www.w3.org/Consortium/Legal/2008/04-testsuite-license) and the W3C 3-clause BSD License (http://www.w3.org/Consortium/Legal/2008/03-bsd-license). To contribute to a W3C Test Suite, see the policies and contribution forms (http://www.w3.org/2004/10/27-testcases). ================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-charset.html ================================================  UTF-8 BOM vs meta charset

UTF-8 BOM vs meta charset

 

A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta charset attribute declares a different encoding.

The page contains an encoding declaration in a meta charset attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-038
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/UTF-8-BOM-vs-meta-content.html ================================================  UTF-8 BOM vs meta content

UTF-8 BOM vs meta content

 

A page with a UTF-8 BOM will be recognized as UTF-8 even if the meta content attribute declares a different encoding.

The page contains an encoding declaration in a meta content attribute that attempts to set the character encoding to ISO 8859-15, but the file starts with a UTF-8 signature.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ýäè. This matches the sequence of bytes above when they are interpreted as UTF-8. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-037
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/meta-charset-attribute.html ================================================ meta charset attribute

meta charset attribute

 

The character encoding of the page can be set by a meta element with charset attribute.

The only character encoding declaration for this HTML file is in the charset attribute of the meta element, which declares the encoding to be ISO 8859-15.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-009
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/charset/testdata/meta-content-attribute.html ================================================ meta content attribute

meta content attribute

 

The character encoding of the page can be set by a meta element with http-equiv and content attributes.

The only character encoding declaration for this HTML file is in the content attribute of the meta element, which declares the encoding to be ISO 8859-15.

The test contains a div with a class name that contains the following sequence of bytes: 0xC3 0xBD 0xC3 0xA4 0xC3 0xA8. These represent different sequences of characters in ISO 8859-15, ISO 8859-1 and UTF-8. The external, UTF-8-encoded stylesheet contains a selector .test div.ÜÀÚ. This matches the sequence of bytes above when they are interpreted as ISO 8859-15. If the class name matches the selector then the test will pass.

HTML5

the-input-byte-stream-007
Result summary & related tests
Detailed results for this test
Link to spec

Assumptions:
  • The default encoding for the browser you are testing is not set to ISO 8859-15.
  • The test is read from a server that supports HTTP.
================================================ FILE: vendor/golang.org/x/net/html/const.go ================================================ // 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 html // Section 12.2.3.2 of the HTML5 specification says "The following elements // have varying levels of special parsing rules". // https://html.spec.whatwg.org/multipage/syntax.html#the-stack-of-open-elements var isSpecialElementMap = map[string]bool{ "address": true, "applet": true, "area": true, "article": true, "aside": true, "base": true, "basefont": true, "bgsound": true, "blockquote": true, "body": true, "br": true, "button": true, "caption": true, "center": true, "col": true, "colgroup": true, "dd": true, "details": true, "dir": true, "div": true, "dl": true, "dt": true, "embed": true, "fieldset": true, "figcaption": true, "figure": true, "footer": true, "form": true, "frame": true, "frameset": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "head": true, "header": true, "hgroup": true, "hr": true, "html": true, "iframe": true, "img": true, "input": true, "isindex": true, "li": true, "link": true, "listing": true, "marquee": true, "menu": true, "meta": true, "nav": true, "noembed": true, "noframes": true, "noscript": true, "object": true, "ol": true, "p": true, "param": true, "plaintext": true, "pre": true, "script": true, "section": true, "select": true, "source": true, "style": true, "summary": true, "table": true, "tbody": true, "td": true, "template": true, "textarea": true, "tfoot": true, "th": true, "thead": true, "title": true, "tr": true, "track": true, "ul": true, "wbr": true, "xmp": true, } func isSpecialElement(element *Node) bool { switch element.Namespace { case "", "html": return isSpecialElementMap[element.Data] case "svg": return element.Data == "foreignObject" } return false } ================================================ FILE: vendor/golang.org/x/net/html/doc.go ================================================ // 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 html implements an HTML5-compliant tokenizer and parser. Tokenization is done by creating a Tokenizer for an io.Reader r. It is the caller's responsibility to ensure that r provides UTF-8 encoded HTML. z := html.NewTokenizer(r) Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), which parses the next token and returns its type, or an error: for { tt := z.Next() if tt == html.ErrorToken { // ... return ... } // Process the current token. } There are two APIs for retrieving the current token. The high-level API is to call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs allow optionally calling Raw after Next but before Token, Text, TagName, or TagAttr. In EBNF notation, the valid call sequence per token is: Next {Raw} [ Token | Text | TagName {TagAttr} ] Token returns an independent data structure that completely describes a token. Entities (such as "<") are unescaped, tag names and attribute keys are lower-cased, and attributes are collected into a []Attribute. For example: for { if z.Next() == html.ErrorToken { // Returning io.EOF indicates success. return z.Err() } emitToken(z.Token()) } The low-level API performs fewer allocations and copies, but the contents of the []byte values returned by Text, TagName and TagAttr may change on the next call to Next. For example, to extract an HTML page's anchor text: depth := 0 for { tt := z.Next() switch tt { case ErrorToken: return z.Err() case TextToken: if depth > 0 { // emitBytes should copy the []byte it receives, // if it doesn't process it immediately. emitBytes(z.Text()) } case StartTagToken, EndTagToken: tn, _ := z.TagName() if len(tn) == 1 && tn[0] == 'a' { if tt == StartTagToken { depth++ } else { depth-- } } } } Parsing is done by calling Parse with an io.Reader, which returns the root of the parse tree (the document element) as a *Node. It is the caller's responsibility to ensure that the Reader provides UTF-8 encoded HTML. For example, to process each anchor node in depth-first order: doc, err := html.Parse(r) if err != nil { // ... } var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "a" { // Do something with n... } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) The relevant specifications include: https://html.spec.whatwg.org/multipage/syntax.html and https://html.spec.whatwg.org/multipage/syntax.html#tokenization */ package html // import "golang.org/x/net/html" // The tokenization algorithm implemented by this package is not a line-by-line // transliteration of the relatively verbose state-machine in the WHATWG // specification. A more direct approach is used instead, where the program // counter implies the state, such as whether it is tokenizing a tag or a text // node. Specification compliance is verified by checking expected and actual // outputs over a test suite rather than aiming for algorithmic fidelity. // TODO(nigeltao): Does a DOM API belong in this package or a separate one? // TODO(nigeltao): How does parsing interact with a JavaScript engine? ================================================ FILE: vendor/golang.org/x/net/html/doctype.go ================================================ // 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 html import ( "strings" ) // parseDoctype parses the data from a DoctypeToken into a name, // public identifier, and system identifier. It returns a Node whose Type // is DoctypeNode, whose Data is the name, and which has attributes // named "system" and "public" for the two identifiers if they were present. // quirks is whether the document should be parsed in "quirks mode". func parseDoctype(s string) (n *Node, quirks bool) { n = &Node{Type: DoctypeNode} // Find the name. space := strings.IndexAny(s, whitespace) if space == -1 { space = len(s) } n.Data = s[:space] // The comparison to "html" is case-sensitive. if n.Data != "html" { quirks = true } n.Data = strings.ToLower(n.Data) s = strings.TrimLeft(s[space:], whitespace) if len(s) < 6 { // It can't start with "PUBLIC" or "SYSTEM". // Ignore the rest of the string. return n, quirks || s != "" } key := strings.ToLower(s[:6]) s = s[6:] for key == "public" || key == "system" { s = strings.TrimLeft(s, whitespace) if s == "" { break } quote := s[0] if quote != '"' && quote != '\'' { break } s = s[1:] q := strings.IndexRune(s, rune(quote)) var id string if q == -1 { id = s s = "" } else { id = s[:q] s = s[q+1:] } n.Attr = append(n.Attr, Attribute{Key: key, Val: id}) if key == "public" { key = "system" } else { key = "" } } if key != "" || s != "" { quirks = true } else if len(n.Attr) > 0 { if n.Attr[0].Key == "public" { public := strings.ToLower(n.Attr[0].Val) switch public { case "-//w3o//dtd w3 html strict 3.0//en//", "-/w3d/dtd html 4.0 transitional/en", "html": quirks = true default: for _, q := range quirkyIDs { if strings.HasPrefix(public, q) { quirks = true break } } } // The following two public IDs only cause quirks mode if there is no system ID. if len(n.Attr) == 1 && (strings.HasPrefix(public, "-//w3c//dtd html 4.01 frameset//") || strings.HasPrefix(public, "-//w3c//dtd html 4.01 transitional//")) { quirks = true } } if lastAttr := n.Attr[len(n.Attr)-1]; lastAttr.Key == "system" && strings.ToLower(lastAttr.Val) == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" { quirks = true } } return n, quirks } // quirkyIDs is a list of public doctype identifiers that cause a document // to be interpreted in quirks mode. The identifiers should be in lower case. var quirkyIDs = []string{ "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//", } ================================================ FILE: vendor/golang.org/x/net/html/entity.go ================================================ // 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 html // All entities that do not end with ';' are 6 or fewer bytes long. const longestEntityWithoutSemicolon = 6 // entity is a map from HTML entity names to their values. The semicolon matters: // https://html.spec.whatwg.org/multipage/syntax.html#named-character-references // lists both "amp" and "amp;" as two separate entries. // // Note that the HTML5 list is larger than the HTML4 list at // http://www.w3.org/TR/html4/sgml/entities.html var entity = map[string]rune{ "AElig;": '\U000000C6', "AMP;": '\U00000026', "Aacute;": '\U000000C1', "Abreve;": '\U00000102', "Acirc;": '\U000000C2', "Acy;": '\U00000410', "Afr;": '\U0001D504', "Agrave;": '\U000000C0', "Alpha;": '\U00000391', "Amacr;": '\U00000100', "And;": '\U00002A53', "Aogon;": '\U00000104', "Aopf;": '\U0001D538', "ApplyFunction;": '\U00002061', "Aring;": '\U000000C5', "Ascr;": '\U0001D49C', "Assign;": '\U00002254', "Atilde;": '\U000000C3', "Auml;": '\U000000C4', "Backslash;": '\U00002216', "Barv;": '\U00002AE7', "Barwed;": '\U00002306', "Bcy;": '\U00000411', "Because;": '\U00002235', "Bernoullis;": '\U0000212C', "Beta;": '\U00000392', "Bfr;": '\U0001D505', "Bopf;": '\U0001D539', "Breve;": '\U000002D8', "Bscr;": '\U0000212C', "Bumpeq;": '\U0000224E', "CHcy;": '\U00000427', "COPY;": '\U000000A9', "Cacute;": '\U00000106', "Cap;": '\U000022D2', "CapitalDifferentialD;": '\U00002145', "Cayleys;": '\U0000212D', "Ccaron;": '\U0000010C', "Ccedil;": '\U000000C7', "Ccirc;": '\U00000108', "Cconint;": '\U00002230', "Cdot;": '\U0000010A', "Cedilla;": '\U000000B8', "CenterDot;": '\U000000B7', "Cfr;": '\U0000212D', "Chi;": '\U000003A7', "CircleDot;": '\U00002299', "CircleMinus;": '\U00002296', "CirclePlus;": '\U00002295', "CircleTimes;": '\U00002297', "ClockwiseContourIntegral;": '\U00002232', "CloseCurlyDoubleQuote;": '\U0000201D', "CloseCurlyQuote;": '\U00002019', "Colon;": '\U00002237', "Colone;": '\U00002A74', "Congruent;": '\U00002261', "Conint;": '\U0000222F', "ContourIntegral;": '\U0000222E', "Copf;": '\U00002102', "Coproduct;": '\U00002210', "CounterClockwiseContourIntegral;": '\U00002233', "Cross;": '\U00002A2F', "Cscr;": '\U0001D49E', "Cup;": '\U000022D3', "CupCap;": '\U0000224D', "DD;": '\U00002145', "DDotrahd;": '\U00002911', "DJcy;": '\U00000402', "DScy;": '\U00000405', "DZcy;": '\U0000040F', "Dagger;": '\U00002021', "Darr;": '\U000021A1', "Dashv;": '\U00002AE4', "Dcaron;": '\U0000010E', "Dcy;": '\U00000414', "Del;": '\U00002207', "Delta;": '\U00000394', "Dfr;": '\U0001D507', "DiacriticalAcute;": '\U000000B4', "DiacriticalDot;": '\U000002D9', "DiacriticalDoubleAcute;": '\U000002DD', "DiacriticalGrave;": '\U00000060', "DiacriticalTilde;": '\U000002DC', "Diamond;": '\U000022C4', "DifferentialD;": '\U00002146', "Dopf;": '\U0001D53B', "Dot;": '\U000000A8', "DotDot;": '\U000020DC', "DotEqual;": '\U00002250', "DoubleContourIntegral;": '\U0000222F', "DoubleDot;": '\U000000A8', "DoubleDownArrow;": '\U000021D3', "DoubleLeftArrow;": '\U000021D0', "DoubleLeftRightArrow;": '\U000021D4', "DoubleLeftTee;": '\U00002AE4', "DoubleLongLeftArrow;": '\U000027F8', "DoubleLongLeftRightArrow;": '\U000027FA', "DoubleLongRightArrow;": '\U000027F9', "DoubleRightArrow;": '\U000021D2', "DoubleRightTee;": '\U000022A8', "DoubleUpArrow;": '\U000021D1', "DoubleUpDownArrow;": '\U000021D5', "DoubleVerticalBar;": '\U00002225', "DownArrow;": '\U00002193', "DownArrowBar;": '\U00002913', "DownArrowUpArrow;": '\U000021F5', "DownBreve;": '\U00000311', "DownLeftRightVector;": '\U00002950', "DownLeftTeeVector;": '\U0000295E', "DownLeftVector;": '\U000021BD', "DownLeftVectorBar;": '\U00002956', "DownRightTeeVector;": '\U0000295F', "DownRightVector;": '\U000021C1', "DownRightVectorBar;": '\U00002957', "DownTee;": '\U000022A4', "DownTeeArrow;": '\U000021A7', "Downarrow;": '\U000021D3', "Dscr;": '\U0001D49F', "Dstrok;": '\U00000110', "ENG;": '\U0000014A', "ETH;": '\U000000D0', "Eacute;": '\U000000C9', "Ecaron;": '\U0000011A', "Ecirc;": '\U000000CA', "Ecy;": '\U0000042D', "Edot;": '\U00000116', "Efr;": '\U0001D508', "Egrave;": '\U000000C8', "Element;": '\U00002208', "Emacr;": '\U00000112', "EmptySmallSquare;": '\U000025FB', "EmptyVerySmallSquare;": '\U000025AB', "Eogon;": '\U00000118', "Eopf;": '\U0001D53C', "Epsilon;": '\U00000395', "Equal;": '\U00002A75', "EqualTilde;": '\U00002242', "Equilibrium;": '\U000021CC', "Escr;": '\U00002130', "Esim;": '\U00002A73', "Eta;": '\U00000397', "Euml;": '\U000000CB', "Exists;": '\U00002203', "ExponentialE;": '\U00002147', "Fcy;": '\U00000424', "Ffr;": '\U0001D509', "FilledSmallSquare;": '\U000025FC', "FilledVerySmallSquare;": '\U000025AA', "Fopf;": '\U0001D53D', "ForAll;": '\U00002200', "Fouriertrf;": '\U00002131', "Fscr;": '\U00002131', "GJcy;": '\U00000403', "GT;": '\U0000003E', "Gamma;": '\U00000393', "Gammad;": '\U000003DC', "Gbreve;": '\U0000011E', "Gcedil;": '\U00000122', "Gcirc;": '\U0000011C', "Gcy;": '\U00000413', "Gdot;": '\U00000120', "Gfr;": '\U0001D50A', "Gg;": '\U000022D9', "Gopf;": '\U0001D53E', "GreaterEqual;": '\U00002265', "GreaterEqualLess;": '\U000022DB', "GreaterFullEqual;": '\U00002267', "GreaterGreater;": '\U00002AA2', "GreaterLess;": '\U00002277', "GreaterSlantEqual;": '\U00002A7E', "GreaterTilde;": '\U00002273', "Gscr;": '\U0001D4A2', "Gt;": '\U0000226B', "HARDcy;": '\U0000042A', "Hacek;": '\U000002C7', "Hat;": '\U0000005E', "Hcirc;": '\U00000124', "Hfr;": '\U0000210C', "HilbertSpace;": '\U0000210B', "Hopf;": '\U0000210D', "HorizontalLine;": '\U00002500', "Hscr;": '\U0000210B', "Hstrok;": '\U00000126', "HumpDownHump;": '\U0000224E', "HumpEqual;": '\U0000224F', "IEcy;": '\U00000415', "IJlig;": '\U00000132', "IOcy;": '\U00000401', "Iacute;": '\U000000CD', "Icirc;": '\U000000CE', "Icy;": '\U00000418', "Idot;": '\U00000130', "Ifr;": '\U00002111', "Igrave;": '\U000000CC', "Im;": '\U00002111', "Imacr;": '\U0000012A', "ImaginaryI;": '\U00002148', "Implies;": '\U000021D2', "Int;": '\U0000222C', "Integral;": '\U0000222B', "Intersection;": '\U000022C2', "InvisibleComma;": '\U00002063', "InvisibleTimes;": '\U00002062', "Iogon;": '\U0000012E', "Iopf;": '\U0001D540', "Iota;": '\U00000399', "Iscr;": '\U00002110', "Itilde;": '\U00000128', "Iukcy;": '\U00000406', "Iuml;": '\U000000CF', "Jcirc;": '\U00000134', "Jcy;": '\U00000419', "Jfr;": '\U0001D50D', "Jopf;": '\U0001D541', "Jscr;": '\U0001D4A5', "Jsercy;": '\U00000408', "Jukcy;": '\U00000404', "KHcy;": '\U00000425', "KJcy;": '\U0000040C', "Kappa;": '\U0000039A', "Kcedil;": '\U00000136', "Kcy;": '\U0000041A', "Kfr;": '\U0001D50E', "Kopf;": '\U0001D542', "Kscr;": '\U0001D4A6', "LJcy;": '\U00000409', "LT;": '\U0000003C', "Lacute;": '\U00000139', "Lambda;": '\U0000039B', "Lang;": '\U000027EA', "Laplacetrf;": '\U00002112', "Larr;": '\U0000219E', "Lcaron;": '\U0000013D', "Lcedil;": '\U0000013B', "Lcy;": '\U0000041B', "LeftAngleBracket;": '\U000027E8', "LeftArrow;": '\U00002190', "LeftArrowBar;": '\U000021E4', "LeftArrowRightArrow;": '\U000021C6', "LeftCeiling;": '\U00002308', "LeftDoubleBracket;": '\U000027E6', "LeftDownTeeVector;": '\U00002961', "LeftDownVector;": '\U000021C3', "LeftDownVectorBar;": '\U00002959', "LeftFloor;": '\U0000230A', "LeftRightArrow;": '\U00002194', "LeftRightVector;": '\U0000294E', "LeftTee;": '\U000022A3', "LeftTeeArrow;": '\U000021A4', "LeftTeeVector;": '\U0000295A', "LeftTriangle;": '\U000022B2', "LeftTriangleBar;": '\U000029CF', "LeftTriangleEqual;": '\U000022B4', "LeftUpDownVector;": '\U00002951', "LeftUpTeeVector;": '\U00002960', "LeftUpVector;": '\U000021BF', "LeftUpVectorBar;": '\U00002958', "LeftVector;": '\U000021BC', "LeftVectorBar;": '\U00002952', "Leftarrow;": '\U000021D0', "Leftrightarrow;": '\U000021D4', "LessEqualGreater;": '\U000022DA', "LessFullEqual;": '\U00002266', "LessGreater;": '\U00002276', "LessLess;": '\U00002AA1', "LessSlantEqual;": '\U00002A7D', "LessTilde;": '\U00002272', "Lfr;": '\U0001D50F', "Ll;": '\U000022D8', "Lleftarrow;": '\U000021DA', "Lmidot;": '\U0000013F', "LongLeftArrow;": '\U000027F5', "LongLeftRightArrow;": '\U000027F7', "LongRightArrow;": '\U000027F6', "Longleftarrow;": '\U000027F8', "Longleftrightarrow;": '\U000027FA', "Longrightarrow;": '\U000027F9', "Lopf;": '\U0001D543', "LowerLeftArrow;": '\U00002199', "LowerRightArrow;": '\U00002198', "Lscr;": '\U00002112', "Lsh;": '\U000021B0', "Lstrok;": '\U00000141', "Lt;": '\U0000226A', "Map;": '\U00002905', "Mcy;": '\U0000041C', "MediumSpace;": '\U0000205F', "Mellintrf;": '\U00002133', "Mfr;": '\U0001D510', "MinusPlus;": '\U00002213', "Mopf;": '\U0001D544', "Mscr;": '\U00002133', "Mu;": '\U0000039C', "NJcy;": '\U0000040A', "Nacute;": '\U00000143', "Ncaron;": '\U00000147', "Ncedil;": '\U00000145', "Ncy;": '\U0000041D', "NegativeMediumSpace;": '\U0000200B', "NegativeThickSpace;": '\U0000200B', "NegativeThinSpace;": '\U0000200B', "NegativeVeryThinSpace;": '\U0000200B', "NestedGreaterGreater;": '\U0000226B', "NestedLessLess;": '\U0000226A', "NewLine;": '\U0000000A', "Nfr;": '\U0001D511', "NoBreak;": '\U00002060', "NonBreakingSpace;": '\U000000A0', "Nopf;": '\U00002115', "Not;": '\U00002AEC', "NotCongruent;": '\U00002262', "NotCupCap;": '\U0000226D', "NotDoubleVerticalBar;": '\U00002226', "NotElement;": '\U00002209', "NotEqual;": '\U00002260', "NotExists;": '\U00002204', "NotGreater;": '\U0000226F', "NotGreaterEqual;": '\U00002271', "NotGreaterLess;": '\U00002279', "NotGreaterTilde;": '\U00002275', "NotLeftTriangle;": '\U000022EA', "NotLeftTriangleEqual;": '\U000022EC', "NotLess;": '\U0000226E', "NotLessEqual;": '\U00002270', "NotLessGreater;": '\U00002278', "NotLessTilde;": '\U00002274', "NotPrecedes;": '\U00002280', "NotPrecedesSlantEqual;": '\U000022E0', "NotReverseElement;": '\U0000220C', "NotRightTriangle;": '\U000022EB', "NotRightTriangleEqual;": '\U000022ED', "NotSquareSubsetEqual;": '\U000022E2', "NotSquareSupersetEqual;": '\U000022E3', "NotSubsetEqual;": '\U00002288', "NotSucceeds;": '\U00002281', "NotSucceedsSlantEqual;": '\U000022E1', "NotSupersetEqual;": '\U00002289', "NotTilde;": '\U00002241', "NotTildeEqual;": '\U00002244', "NotTildeFullEqual;": '\U00002247', "NotTildeTilde;": '\U00002249', "NotVerticalBar;": '\U00002224', "Nscr;": '\U0001D4A9', "Ntilde;": '\U000000D1', "Nu;": '\U0000039D', "OElig;": '\U00000152', "Oacute;": '\U000000D3', "Ocirc;": '\U000000D4', "Ocy;": '\U0000041E', "Odblac;": '\U00000150', "Ofr;": '\U0001D512', "Ograve;": '\U000000D2', "Omacr;": '\U0000014C', "Omega;": '\U000003A9', "Omicron;": '\U0000039F', "Oopf;": '\U0001D546', "OpenCurlyDoubleQuote;": '\U0000201C', "OpenCurlyQuote;": '\U00002018', "Or;": '\U00002A54', "Oscr;": '\U0001D4AA', "Oslash;": '\U000000D8', "Otilde;": '\U000000D5', "Otimes;": '\U00002A37', "Ouml;": '\U000000D6', "OverBar;": '\U0000203E', "OverBrace;": '\U000023DE', "OverBracket;": '\U000023B4', "OverParenthesis;": '\U000023DC', "PartialD;": '\U00002202', "Pcy;": '\U0000041F', "Pfr;": '\U0001D513', "Phi;": '\U000003A6', "Pi;": '\U000003A0', "PlusMinus;": '\U000000B1', "Poincareplane;": '\U0000210C', "Popf;": '\U00002119', "Pr;": '\U00002ABB', "Precedes;": '\U0000227A', "PrecedesEqual;": '\U00002AAF', "PrecedesSlantEqual;": '\U0000227C', "PrecedesTilde;": '\U0000227E', "Prime;": '\U00002033', "Product;": '\U0000220F', "Proportion;": '\U00002237', "Proportional;": '\U0000221D', "Pscr;": '\U0001D4AB', "Psi;": '\U000003A8', "QUOT;": '\U00000022', "Qfr;": '\U0001D514', "Qopf;": '\U0000211A', "Qscr;": '\U0001D4AC', "RBarr;": '\U00002910', "REG;": '\U000000AE', "Racute;": '\U00000154', "Rang;": '\U000027EB', "Rarr;": '\U000021A0', "Rarrtl;": '\U00002916', "Rcaron;": '\U00000158', "Rcedil;": '\U00000156', "Rcy;": '\U00000420', "Re;": '\U0000211C', "ReverseElement;": '\U0000220B', "ReverseEquilibrium;": '\U000021CB', "ReverseUpEquilibrium;": '\U0000296F', "Rfr;": '\U0000211C', "Rho;": '\U000003A1', "RightAngleBracket;": '\U000027E9', "RightArrow;": '\U00002192', "RightArrowBar;": '\U000021E5', "RightArrowLeftArrow;": '\U000021C4', "RightCeiling;": '\U00002309', "RightDoubleBracket;": '\U000027E7', "RightDownTeeVector;": '\U0000295D', "RightDownVector;": '\U000021C2', "RightDownVectorBar;": '\U00002955', "RightFloor;": '\U0000230B', "RightTee;": '\U000022A2', "RightTeeArrow;": '\U000021A6', "RightTeeVector;": '\U0000295B', "RightTriangle;": '\U000022B3', "RightTriangleBar;": '\U000029D0', "RightTriangleEqual;": '\U000022B5', "RightUpDownVector;": '\U0000294F', "RightUpTeeVector;": '\U0000295C', "RightUpVector;": '\U000021BE', "RightUpVectorBar;": '\U00002954', "RightVector;": '\U000021C0', "RightVectorBar;": '\U00002953', "Rightarrow;": '\U000021D2', "Ropf;": '\U0000211D', "RoundImplies;": '\U00002970', "Rrightarrow;": '\U000021DB', "Rscr;": '\U0000211B', "Rsh;": '\U000021B1', "RuleDelayed;": '\U000029F4', "SHCHcy;": '\U00000429', "SHcy;": '\U00000428', "SOFTcy;": '\U0000042C', "Sacute;": '\U0000015A', "Sc;": '\U00002ABC', "Scaron;": '\U00000160', "Scedil;": '\U0000015E', "Scirc;": '\U0000015C', "Scy;": '\U00000421', "Sfr;": '\U0001D516', "ShortDownArrow;": '\U00002193', "ShortLeftArrow;": '\U00002190', "ShortRightArrow;": '\U00002192', "ShortUpArrow;": '\U00002191', "Sigma;": '\U000003A3', "SmallCircle;": '\U00002218', "Sopf;": '\U0001D54A', "Sqrt;": '\U0000221A', "Square;": '\U000025A1', "SquareIntersection;": '\U00002293', "SquareSubset;": '\U0000228F', "SquareSubsetEqual;": '\U00002291', "SquareSuperset;": '\U00002290', "SquareSupersetEqual;": '\U00002292', "SquareUnion;": '\U00002294', "Sscr;": '\U0001D4AE', "Star;": '\U000022C6', "Sub;": '\U000022D0', "Subset;": '\U000022D0', "SubsetEqual;": '\U00002286', "Succeeds;": '\U0000227B', "SucceedsEqual;": '\U00002AB0', "SucceedsSlantEqual;": '\U0000227D', "SucceedsTilde;": '\U0000227F', "SuchThat;": '\U0000220B', "Sum;": '\U00002211', "Sup;": '\U000022D1', "Superset;": '\U00002283', "SupersetEqual;": '\U00002287', "Supset;": '\U000022D1', "THORN;": '\U000000DE', "TRADE;": '\U00002122', "TSHcy;": '\U0000040B', "TScy;": '\U00000426', "Tab;": '\U00000009', "Tau;": '\U000003A4', "Tcaron;": '\U00000164', "Tcedil;": '\U00000162', "Tcy;": '\U00000422', "Tfr;": '\U0001D517', "Therefore;": '\U00002234', "Theta;": '\U00000398', "ThinSpace;": '\U00002009', "Tilde;": '\U0000223C', "TildeEqual;": '\U00002243', "TildeFullEqual;": '\U00002245', "TildeTilde;": '\U00002248', "Topf;": '\U0001D54B', "TripleDot;": '\U000020DB', "Tscr;": '\U0001D4AF', "Tstrok;": '\U00000166', "Uacute;": '\U000000DA', "Uarr;": '\U0000219F', "Uarrocir;": '\U00002949', "Ubrcy;": '\U0000040E', "Ubreve;": '\U0000016C', "Ucirc;": '\U000000DB', "Ucy;": '\U00000423', "Udblac;": '\U00000170', "Ufr;": '\U0001D518', "Ugrave;": '\U000000D9', "Umacr;": '\U0000016A', "UnderBar;": '\U0000005F', "UnderBrace;": '\U000023DF', "UnderBracket;": '\U000023B5', "UnderParenthesis;": '\U000023DD', "Union;": '\U000022C3', "UnionPlus;": '\U0000228E', "Uogon;": '\U00000172', "Uopf;": '\U0001D54C', "UpArrow;": '\U00002191', "UpArrowBar;": '\U00002912', "UpArrowDownArrow;": '\U000021C5', "UpDownArrow;": '\U00002195', "UpEquilibrium;": '\U0000296E', "UpTee;": '\U000022A5', "UpTeeArrow;": '\U000021A5', "Uparrow;": '\U000021D1', "Updownarrow;": '\U000021D5', "UpperLeftArrow;": '\U00002196', "UpperRightArrow;": '\U00002197', "Upsi;": '\U000003D2', "Upsilon;": '\U000003A5', "Uring;": '\U0000016E', "Uscr;": '\U0001D4B0', "Utilde;": '\U00000168', "Uuml;": '\U000000DC', "VDash;": '\U000022AB', "Vbar;": '\U00002AEB', "Vcy;": '\U00000412', "Vdash;": '\U000022A9', "Vdashl;": '\U00002AE6', "Vee;": '\U000022C1', "Verbar;": '\U00002016', "Vert;": '\U00002016', "VerticalBar;": '\U00002223', "VerticalLine;": '\U0000007C', "VerticalSeparator;": '\U00002758', "VerticalTilde;": '\U00002240', "VeryThinSpace;": '\U0000200A', "Vfr;": '\U0001D519', "Vopf;": '\U0001D54D', "Vscr;": '\U0001D4B1', "Vvdash;": '\U000022AA', "Wcirc;": '\U00000174', "Wedge;": '\U000022C0', "Wfr;": '\U0001D51A', "Wopf;": '\U0001D54E', "Wscr;": '\U0001D4B2', "Xfr;": '\U0001D51B', "Xi;": '\U0000039E', "Xopf;": '\U0001D54F', "Xscr;": '\U0001D4B3', "YAcy;": '\U0000042F', "YIcy;": '\U00000407', "YUcy;": '\U0000042E', "Yacute;": '\U000000DD', "Ycirc;": '\U00000176', "Ycy;": '\U0000042B', "Yfr;": '\U0001D51C', "Yopf;": '\U0001D550', "Yscr;": '\U0001D4B4', "Yuml;": '\U00000178', "ZHcy;": '\U00000416', "Zacute;": '\U00000179', "Zcaron;": '\U0000017D', "Zcy;": '\U00000417', "Zdot;": '\U0000017B', "ZeroWidthSpace;": '\U0000200B', "Zeta;": '\U00000396', "Zfr;": '\U00002128', "Zopf;": '\U00002124', "Zscr;": '\U0001D4B5', "aacute;": '\U000000E1', "abreve;": '\U00000103', "ac;": '\U0000223E', "acd;": '\U0000223F', "acirc;": '\U000000E2', "acute;": '\U000000B4', "acy;": '\U00000430', "aelig;": '\U000000E6', "af;": '\U00002061', "afr;": '\U0001D51E', "agrave;": '\U000000E0', "alefsym;": '\U00002135', "aleph;": '\U00002135', "alpha;": '\U000003B1', "amacr;": '\U00000101', "amalg;": '\U00002A3F', "amp;": '\U00000026', "and;": '\U00002227', "andand;": '\U00002A55', "andd;": '\U00002A5C', "andslope;": '\U00002A58', "andv;": '\U00002A5A', "ang;": '\U00002220', "ange;": '\U000029A4', "angle;": '\U00002220', "angmsd;": '\U00002221', "angmsdaa;": '\U000029A8', "angmsdab;": '\U000029A9', "angmsdac;": '\U000029AA', "angmsdad;": '\U000029AB', "angmsdae;": '\U000029AC', "angmsdaf;": '\U000029AD', "angmsdag;": '\U000029AE', "angmsdah;": '\U000029AF', "angrt;": '\U0000221F', "angrtvb;": '\U000022BE', "angrtvbd;": '\U0000299D', "angsph;": '\U00002222', "angst;": '\U000000C5', "angzarr;": '\U0000237C', "aogon;": '\U00000105', "aopf;": '\U0001D552', "ap;": '\U00002248', "apE;": '\U00002A70', "apacir;": '\U00002A6F', "ape;": '\U0000224A', "apid;": '\U0000224B', "apos;": '\U00000027', "approx;": '\U00002248', "approxeq;": '\U0000224A', "aring;": '\U000000E5', "ascr;": '\U0001D4B6', "ast;": '\U0000002A', "asymp;": '\U00002248', "asympeq;": '\U0000224D', "atilde;": '\U000000E3', "auml;": '\U000000E4', "awconint;": '\U00002233', "awint;": '\U00002A11', "bNot;": '\U00002AED', "backcong;": '\U0000224C', "backepsilon;": '\U000003F6', "backprime;": '\U00002035', "backsim;": '\U0000223D', "backsimeq;": '\U000022CD', "barvee;": '\U000022BD', "barwed;": '\U00002305', "barwedge;": '\U00002305', "bbrk;": '\U000023B5', "bbrktbrk;": '\U000023B6', "bcong;": '\U0000224C', "bcy;": '\U00000431', "bdquo;": '\U0000201E', "becaus;": '\U00002235', "because;": '\U00002235', "bemptyv;": '\U000029B0', "bepsi;": '\U000003F6', "bernou;": '\U0000212C', "beta;": '\U000003B2', "beth;": '\U00002136', "between;": '\U0000226C', "bfr;": '\U0001D51F', "bigcap;": '\U000022C2', "bigcirc;": '\U000025EF', "bigcup;": '\U000022C3', "bigodot;": '\U00002A00', "bigoplus;": '\U00002A01', "bigotimes;": '\U00002A02', "bigsqcup;": '\U00002A06', "bigstar;": '\U00002605', "bigtriangledown;": '\U000025BD', "bigtriangleup;": '\U000025B3', "biguplus;": '\U00002A04', "bigvee;": '\U000022C1', "bigwedge;": '\U000022C0', "bkarow;": '\U0000290D', "blacklozenge;": '\U000029EB', "blacksquare;": '\U000025AA', "blacktriangle;": '\U000025B4', "blacktriangledown;": '\U000025BE', "blacktriangleleft;": '\U000025C2', "blacktriangleright;": '\U000025B8', "blank;": '\U00002423', "blk12;": '\U00002592', "blk14;": '\U00002591', "blk34;": '\U00002593', "block;": '\U00002588', "bnot;": '\U00002310', "bopf;": '\U0001D553', "bot;": '\U000022A5', "bottom;": '\U000022A5', "bowtie;": '\U000022C8', "boxDL;": '\U00002557', "boxDR;": '\U00002554', "boxDl;": '\U00002556', "boxDr;": '\U00002553', "boxH;": '\U00002550', "boxHD;": '\U00002566', "boxHU;": '\U00002569', "boxHd;": '\U00002564', "boxHu;": '\U00002567', "boxUL;": '\U0000255D', "boxUR;": '\U0000255A', "boxUl;": '\U0000255C', "boxUr;": '\U00002559', "boxV;": '\U00002551', "boxVH;": '\U0000256C', "boxVL;": '\U00002563', "boxVR;": '\U00002560', "boxVh;": '\U0000256B', "boxVl;": '\U00002562', "boxVr;": '\U0000255F', "boxbox;": '\U000029C9', "boxdL;": '\U00002555', "boxdR;": '\U00002552', "boxdl;": '\U00002510', "boxdr;": '\U0000250C', "boxh;": '\U00002500', "boxhD;": '\U00002565', "boxhU;": '\U00002568', "boxhd;": '\U0000252C', "boxhu;": '\U00002534', "boxminus;": '\U0000229F', "boxplus;": '\U0000229E', "boxtimes;": '\U000022A0', "boxuL;": '\U0000255B', "boxuR;": '\U00002558', "boxul;": '\U00002518', "boxur;": '\U00002514', "boxv;": '\U00002502', "boxvH;": '\U0000256A', "boxvL;": '\U00002561', "boxvR;": '\U0000255E', "boxvh;": '\U0000253C', "boxvl;": '\U00002524', "boxvr;": '\U0000251C', "bprime;": '\U00002035', "breve;": '\U000002D8', "brvbar;": '\U000000A6', "bscr;": '\U0001D4B7', "bsemi;": '\U0000204F', "bsim;": '\U0000223D', "bsime;": '\U000022CD', "bsol;": '\U0000005C', "bsolb;": '\U000029C5', "bsolhsub;": '\U000027C8', "bull;": '\U00002022', "bullet;": '\U00002022', "bump;": '\U0000224E', "bumpE;": '\U00002AAE', "bumpe;": '\U0000224F', "bumpeq;": '\U0000224F', "cacute;": '\U00000107', "cap;": '\U00002229', "capand;": '\U00002A44', "capbrcup;": '\U00002A49', "capcap;": '\U00002A4B', "capcup;": '\U00002A47', "capdot;": '\U00002A40', "caret;": '\U00002041', "caron;": '\U000002C7', "ccaps;": '\U00002A4D', "ccaron;": '\U0000010D', "ccedil;": '\U000000E7', "ccirc;": '\U00000109', "ccups;": '\U00002A4C', "ccupssm;": '\U00002A50', "cdot;": '\U0000010B', "cedil;": '\U000000B8', "cemptyv;": '\U000029B2', "cent;": '\U000000A2', "centerdot;": '\U000000B7', "cfr;": '\U0001D520', "chcy;": '\U00000447', "check;": '\U00002713', "checkmark;": '\U00002713', "chi;": '\U000003C7', "cir;": '\U000025CB', "cirE;": '\U000029C3', "circ;": '\U000002C6', "circeq;": '\U00002257', "circlearrowleft;": '\U000021BA', "circlearrowright;": '\U000021BB', "circledR;": '\U000000AE', "circledS;": '\U000024C8', "circledast;": '\U0000229B', "circledcirc;": '\U0000229A', "circleddash;": '\U0000229D', "cire;": '\U00002257', "cirfnint;": '\U00002A10', "cirmid;": '\U00002AEF', "cirscir;": '\U000029C2', "clubs;": '\U00002663', "clubsuit;": '\U00002663', "colon;": '\U0000003A', "colone;": '\U00002254', "coloneq;": '\U00002254', "comma;": '\U0000002C', "commat;": '\U00000040', "comp;": '\U00002201', "compfn;": '\U00002218', "complement;": '\U00002201', "complexes;": '\U00002102', "cong;": '\U00002245', "congdot;": '\U00002A6D', "conint;": '\U0000222E', "copf;": '\U0001D554', "coprod;": '\U00002210', "copy;": '\U000000A9', "copysr;": '\U00002117', "crarr;": '\U000021B5', "cross;": '\U00002717', "cscr;": '\U0001D4B8', "csub;": '\U00002ACF', "csube;": '\U00002AD1', "csup;": '\U00002AD0', "csupe;": '\U00002AD2', "ctdot;": '\U000022EF', "cudarrl;": '\U00002938', "cudarrr;": '\U00002935', "cuepr;": '\U000022DE', "cuesc;": '\U000022DF', "cularr;": '\U000021B6', "cularrp;": '\U0000293D', "cup;": '\U0000222A', "cupbrcap;": '\U00002A48', "cupcap;": '\U00002A46', "cupcup;": '\U00002A4A', "cupdot;": '\U0000228D', "cupor;": '\U00002A45', "curarr;": '\U000021B7', "curarrm;": '\U0000293C', "curlyeqprec;": '\U000022DE', "curlyeqsucc;": '\U000022DF', "curlyvee;": '\U000022CE', "curlywedge;": '\U000022CF', "curren;": '\U000000A4', "curvearrowleft;": '\U000021B6', "curvearrowright;": '\U000021B7', "cuvee;": '\U000022CE', "cuwed;": '\U000022CF', "cwconint;": '\U00002232', "cwint;": '\U00002231', "cylcty;": '\U0000232D', "dArr;": '\U000021D3', "dHar;": '\U00002965', "dagger;": '\U00002020', "daleth;": '\U00002138', "darr;": '\U00002193', "dash;": '\U00002010', "dashv;": '\U000022A3', "dbkarow;": '\U0000290F', "dblac;": '\U000002DD', "dcaron;": '\U0000010F', "dcy;": '\U00000434', "dd;": '\U00002146', "ddagger;": '\U00002021', "ddarr;": '\U000021CA', "ddotseq;": '\U00002A77', "deg;": '\U000000B0', "delta;": '\U000003B4', "demptyv;": '\U000029B1', "dfisht;": '\U0000297F', "dfr;": '\U0001D521', "dharl;": '\U000021C3', "dharr;": '\U000021C2', "diam;": '\U000022C4', "diamond;": '\U000022C4', "diamondsuit;": '\U00002666', "diams;": '\U00002666', "die;": '\U000000A8', "digamma;": '\U000003DD', "disin;": '\U000022F2', "div;": '\U000000F7', "divide;": '\U000000F7', "divideontimes;": '\U000022C7', "divonx;": '\U000022C7', "djcy;": '\U00000452', "dlcorn;": '\U0000231E', "dlcrop;": '\U0000230D', "dollar;": '\U00000024', "dopf;": '\U0001D555', "dot;": '\U000002D9', "doteq;": '\U00002250', "doteqdot;": '\U00002251', "dotminus;": '\U00002238', "dotplus;": '\U00002214', "dotsquare;": '\U000022A1', "doublebarwedge;": '\U00002306', "downarrow;": '\U00002193', "downdownarrows;": '\U000021CA', "downharpoonleft;": '\U000021C3', "downharpoonright;": '\U000021C2', "drbkarow;": '\U00002910', "drcorn;": '\U0000231F', "drcrop;": '\U0000230C', "dscr;": '\U0001D4B9', "dscy;": '\U00000455', "dsol;": '\U000029F6', "dstrok;": '\U00000111', "dtdot;": '\U000022F1', "dtri;": '\U000025BF', "dtrif;": '\U000025BE', "duarr;": '\U000021F5', "duhar;": '\U0000296F', "dwangle;": '\U000029A6', "dzcy;": '\U0000045F', "dzigrarr;": '\U000027FF', "eDDot;": '\U00002A77', "eDot;": '\U00002251', "eacute;": '\U000000E9', "easter;": '\U00002A6E', "ecaron;": '\U0000011B', "ecir;": '\U00002256', "ecirc;": '\U000000EA', "ecolon;": '\U00002255', "ecy;": '\U0000044D', "edot;": '\U00000117', "ee;": '\U00002147', "efDot;": '\U00002252', "efr;": '\U0001D522', "eg;": '\U00002A9A', "egrave;": '\U000000E8', "egs;": '\U00002A96', "egsdot;": '\U00002A98', "el;": '\U00002A99', "elinters;": '\U000023E7', "ell;": '\U00002113', "els;": '\U00002A95', "elsdot;": '\U00002A97', "emacr;": '\U00000113', "empty;": '\U00002205', "emptyset;": '\U00002205', "emptyv;": '\U00002205', "emsp;": '\U00002003', "emsp13;": '\U00002004', "emsp14;": '\U00002005', "eng;": '\U0000014B', "ensp;": '\U00002002', "eogon;": '\U00000119', "eopf;": '\U0001D556', "epar;": '\U000022D5', "eparsl;": '\U000029E3', "eplus;": '\U00002A71', "epsi;": '\U000003B5', "epsilon;": '\U000003B5', "epsiv;": '\U000003F5', "eqcirc;": '\U00002256', "eqcolon;": '\U00002255', "eqsim;": '\U00002242', "eqslantgtr;": '\U00002A96', "eqslantless;": '\U00002A95', "equals;": '\U0000003D', "equest;": '\U0000225F', "equiv;": '\U00002261', "equivDD;": '\U00002A78', "eqvparsl;": '\U000029E5', "erDot;": '\U00002253', "erarr;": '\U00002971', "escr;": '\U0000212F', "esdot;": '\U00002250', "esim;": '\U00002242', "eta;": '\U000003B7', "eth;": '\U000000F0', "euml;": '\U000000EB', "euro;": '\U000020AC', "excl;": '\U00000021', "exist;": '\U00002203', "expectation;": '\U00002130', "exponentiale;": '\U00002147', "fallingdotseq;": '\U00002252', "fcy;": '\U00000444', "female;": '\U00002640', "ffilig;": '\U0000FB03', "fflig;": '\U0000FB00', "ffllig;": '\U0000FB04', "ffr;": '\U0001D523', "filig;": '\U0000FB01', "flat;": '\U0000266D', "fllig;": '\U0000FB02', "fltns;": '\U000025B1', "fnof;": '\U00000192', "fopf;": '\U0001D557', "forall;": '\U00002200', "fork;": '\U000022D4', "forkv;": '\U00002AD9', "fpartint;": '\U00002A0D', "frac12;": '\U000000BD', "frac13;": '\U00002153', "frac14;": '\U000000BC', "frac15;": '\U00002155', "frac16;": '\U00002159', "frac18;": '\U0000215B', "frac23;": '\U00002154', "frac25;": '\U00002156', "frac34;": '\U000000BE', "frac35;": '\U00002157', "frac38;": '\U0000215C', "frac45;": '\U00002158', "frac56;": '\U0000215A', "frac58;": '\U0000215D', "frac78;": '\U0000215E', "frasl;": '\U00002044', "frown;": '\U00002322', "fscr;": '\U0001D4BB', "gE;": '\U00002267', "gEl;": '\U00002A8C', "gacute;": '\U000001F5', "gamma;": '\U000003B3', "gammad;": '\U000003DD', "gap;": '\U00002A86', "gbreve;": '\U0000011F', "gcirc;": '\U0000011D', "gcy;": '\U00000433', "gdot;": '\U00000121', "ge;": '\U00002265', "gel;": '\U000022DB', "geq;": '\U00002265', "geqq;": '\U00002267', "geqslant;": '\U00002A7E', "ges;": '\U00002A7E', "gescc;": '\U00002AA9', "gesdot;": '\U00002A80', "gesdoto;": '\U00002A82', "gesdotol;": '\U00002A84', "gesles;": '\U00002A94', "gfr;": '\U0001D524', "gg;": '\U0000226B', "ggg;": '\U000022D9', "gimel;": '\U00002137', "gjcy;": '\U00000453', "gl;": '\U00002277', "glE;": '\U00002A92', "gla;": '\U00002AA5', "glj;": '\U00002AA4', "gnE;": '\U00002269', "gnap;": '\U00002A8A', "gnapprox;": '\U00002A8A', "gne;": '\U00002A88', "gneq;": '\U00002A88', "gneqq;": '\U00002269', "gnsim;": '\U000022E7', "gopf;": '\U0001D558', "grave;": '\U00000060', "gscr;": '\U0000210A', "gsim;": '\U00002273', "gsime;": '\U00002A8E', "gsiml;": '\U00002A90', "gt;": '\U0000003E', "gtcc;": '\U00002AA7', "gtcir;": '\U00002A7A', "gtdot;": '\U000022D7', "gtlPar;": '\U00002995', "gtquest;": '\U00002A7C', "gtrapprox;": '\U00002A86', "gtrarr;": '\U00002978', "gtrdot;": '\U000022D7', "gtreqless;": '\U000022DB', "gtreqqless;": '\U00002A8C', "gtrless;": '\U00002277', "gtrsim;": '\U00002273', "hArr;": '\U000021D4', "hairsp;": '\U0000200A', "half;": '\U000000BD', "hamilt;": '\U0000210B', "hardcy;": '\U0000044A', "harr;": '\U00002194', "harrcir;": '\U00002948', "harrw;": '\U000021AD', "hbar;": '\U0000210F', "hcirc;": '\U00000125', "hearts;": '\U00002665', "heartsuit;": '\U00002665', "hellip;": '\U00002026', "hercon;": '\U000022B9', "hfr;": '\U0001D525', "hksearow;": '\U00002925', "hkswarow;": '\U00002926', "hoarr;": '\U000021FF', "homtht;": '\U0000223B', "hookleftarrow;": '\U000021A9', "hookrightarrow;": '\U000021AA', "hopf;": '\U0001D559', "horbar;": '\U00002015', "hscr;": '\U0001D4BD', "hslash;": '\U0000210F', "hstrok;": '\U00000127', "hybull;": '\U00002043', "hyphen;": '\U00002010', "iacute;": '\U000000ED', "ic;": '\U00002063', "icirc;": '\U000000EE', "icy;": '\U00000438', "iecy;": '\U00000435', "iexcl;": '\U000000A1', "iff;": '\U000021D4', "ifr;": '\U0001D526', "igrave;": '\U000000EC', "ii;": '\U00002148', "iiiint;": '\U00002A0C', "iiint;": '\U0000222D', "iinfin;": '\U000029DC', "iiota;": '\U00002129', "ijlig;": '\U00000133', "imacr;": '\U0000012B', "image;": '\U00002111', "imagline;": '\U00002110', "imagpart;": '\U00002111', "imath;": '\U00000131', "imof;": '\U000022B7', "imped;": '\U000001B5', "in;": '\U00002208', "incare;": '\U00002105', "infin;": '\U0000221E', "infintie;": '\U000029DD', "inodot;": '\U00000131', "int;": '\U0000222B', "intcal;": '\U000022BA', "integers;": '\U00002124', "intercal;": '\U000022BA', "intlarhk;": '\U00002A17', "intprod;": '\U00002A3C', "iocy;": '\U00000451', "iogon;": '\U0000012F', "iopf;": '\U0001D55A', "iota;": '\U000003B9', "iprod;": '\U00002A3C', "iquest;": '\U000000BF', "iscr;": '\U0001D4BE', "isin;": '\U00002208', "isinE;": '\U000022F9', "isindot;": '\U000022F5', "isins;": '\U000022F4', "isinsv;": '\U000022F3', "isinv;": '\U00002208', "it;": '\U00002062', "itilde;": '\U00000129', "iukcy;": '\U00000456', "iuml;": '\U000000EF', "jcirc;": '\U00000135', "jcy;": '\U00000439', "jfr;": '\U0001D527', "jmath;": '\U00000237', "jopf;": '\U0001D55B', "jscr;": '\U0001D4BF', "jsercy;": '\U00000458', "jukcy;": '\U00000454', "kappa;": '\U000003BA', "kappav;": '\U000003F0', "kcedil;": '\U00000137', "kcy;": '\U0000043A', "kfr;": '\U0001D528', "kgreen;": '\U00000138', "khcy;": '\U00000445', "kjcy;": '\U0000045C', "kopf;": '\U0001D55C', "kscr;": '\U0001D4C0', "lAarr;": '\U000021DA', "lArr;": '\U000021D0', "lAtail;": '\U0000291B', "lBarr;": '\U0000290E', "lE;": '\U00002266', "lEg;": '\U00002A8B', "lHar;": '\U00002962', "lacute;": '\U0000013A', "laemptyv;": '\U000029B4', "lagran;": '\U00002112', "lambda;": '\U000003BB', "lang;": '\U000027E8', "langd;": '\U00002991', "langle;": '\U000027E8', "lap;": '\U00002A85', "laquo;": '\U000000AB', "larr;": '\U00002190', "larrb;": '\U000021E4', "larrbfs;": '\U0000291F', "larrfs;": '\U0000291D', "larrhk;": '\U000021A9', "larrlp;": '\U000021AB', "larrpl;": '\U00002939', "larrsim;": '\U00002973', "larrtl;": '\U000021A2', "lat;": '\U00002AAB', "latail;": '\U00002919', "late;": '\U00002AAD', "lbarr;": '\U0000290C', "lbbrk;": '\U00002772', "lbrace;": '\U0000007B', "lbrack;": '\U0000005B', "lbrke;": '\U0000298B', "lbrksld;": '\U0000298F', "lbrkslu;": '\U0000298D', "lcaron;": '\U0000013E', "lcedil;": '\U0000013C', "lceil;": '\U00002308', "lcub;": '\U0000007B', "lcy;": '\U0000043B', "ldca;": '\U00002936', "ldquo;": '\U0000201C', "ldquor;": '\U0000201E', "ldrdhar;": '\U00002967', "ldrushar;": '\U0000294B', "ldsh;": '\U000021B2', "le;": '\U00002264', "leftarrow;": '\U00002190', "leftarrowtail;": '\U000021A2', "leftharpoondown;": '\U000021BD', "leftharpoonup;": '\U000021BC', "leftleftarrows;": '\U000021C7', "leftrightarrow;": '\U00002194', "leftrightarrows;": '\U000021C6', "leftrightharpoons;": '\U000021CB', "leftrightsquigarrow;": '\U000021AD', "leftthreetimes;": '\U000022CB', "leg;": '\U000022DA', "leq;": '\U00002264', "leqq;": '\U00002266', "leqslant;": '\U00002A7D', "les;": '\U00002A7D', "lescc;": '\U00002AA8', "lesdot;": '\U00002A7F', "lesdoto;": '\U00002A81', "lesdotor;": '\U00002A83', "lesges;": '\U00002A93', "lessapprox;": '\U00002A85', "lessdot;": '\U000022D6', "lesseqgtr;": '\U000022DA', "lesseqqgtr;": '\U00002A8B', "lessgtr;": '\U00002276', "lesssim;": '\U00002272', "lfisht;": '\U0000297C', "lfloor;": '\U0000230A', "lfr;": '\U0001D529', "lg;": '\U00002276', "lgE;": '\U00002A91', "lhard;": '\U000021BD', "lharu;": '\U000021BC', "lharul;": '\U0000296A', "lhblk;": '\U00002584', "ljcy;": '\U00000459', "ll;": '\U0000226A', "llarr;": '\U000021C7', "llcorner;": '\U0000231E', "llhard;": '\U0000296B', "lltri;": '\U000025FA', "lmidot;": '\U00000140', "lmoust;": '\U000023B0', "lmoustache;": '\U000023B0', "lnE;": '\U00002268', "lnap;": '\U00002A89', "lnapprox;": '\U00002A89', "lne;": '\U00002A87', "lneq;": '\U00002A87', "lneqq;": '\U00002268', "lnsim;": '\U000022E6', "loang;": '\U000027EC', "loarr;": '\U000021FD', "lobrk;": '\U000027E6', "longleftarrow;": '\U000027F5', "longleftrightarrow;": '\U000027F7', "longmapsto;": '\U000027FC', "longrightarrow;": '\U000027F6', "looparrowleft;": '\U000021AB', "looparrowright;": '\U000021AC', "lopar;": '\U00002985', "lopf;": '\U0001D55D', "loplus;": '\U00002A2D', "lotimes;": '\U00002A34', "lowast;": '\U00002217', "lowbar;": '\U0000005F', "loz;": '\U000025CA', "lozenge;": '\U000025CA', "lozf;": '\U000029EB', "lpar;": '\U00000028', "lparlt;": '\U00002993', "lrarr;": '\U000021C6', "lrcorner;": '\U0000231F', "lrhar;": '\U000021CB', "lrhard;": '\U0000296D', "lrm;": '\U0000200E', "lrtri;": '\U000022BF', "lsaquo;": '\U00002039', "lscr;": '\U0001D4C1', "lsh;": '\U000021B0', "lsim;": '\U00002272', "lsime;": '\U00002A8D', "lsimg;": '\U00002A8F', "lsqb;": '\U0000005B', "lsquo;": '\U00002018', "lsquor;": '\U0000201A', "lstrok;": '\U00000142', "lt;": '\U0000003C', "ltcc;": '\U00002AA6', "ltcir;": '\U00002A79', "ltdot;": '\U000022D6', "lthree;": '\U000022CB', "ltimes;": '\U000022C9', "ltlarr;": '\U00002976', "ltquest;": '\U00002A7B', "ltrPar;": '\U00002996', "ltri;": '\U000025C3', "ltrie;": '\U000022B4', "ltrif;": '\U000025C2', "lurdshar;": '\U0000294A', "luruhar;": '\U00002966', "mDDot;": '\U0000223A', "macr;": '\U000000AF', "male;": '\U00002642', "malt;": '\U00002720', "maltese;": '\U00002720', "map;": '\U000021A6', "mapsto;": '\U000021A6', "mapstodown;": '\U000021A7', "mapstoleft;": '\U000021A4', "mapstoup;": '\U000021A5', "marker;": '\U000025AE', "mcomma;": '\U00002A29', "mcy;": '\U0000043C', "mdash;": '\U00002014', "measuredangle;": '\U00002221', "mfr;": '\U0001D52A', "mho;": '\U00002127', "micro;": '\U000000B5', "mid;": '\U00002223', "midast;": '\U0000002A', "midcir;": '\U00002AF0', "middot;": '\U000000B7', "minus;": '\U00002212', "minusb;": '\U0000229F', "minusd;": '\U00002238', "minusdu;": '\U00002A2A', "mlcp;": '\U00002ADB', "mldr;": '\U00002026', "mnplus;": '\U00002213', "models;": '\U000022A7', "mopf;": '\U0001D55E', "mp;": '\U00002213', "mscr;": '\U0001D4C2', "mstpos;": '\U0000223E', "mu;": '\U000003BC', "multimap;": '\U000022B8', "mumap;": '\U000022B8', "nLeftarrow;": '\U000021CD', "nLeftrightarrow;": '\U000021CE', "nRightarrow;": '\U000021CF', "nVDash;": '\U000022AF', "nVdash;": '\U000022AE', "nabla;": '\U00002207', "nacute;": '\U00000144', "nap;": '\U00002249', "napos;": '\U00000149', "napprox;": '\U00002249', "natur;": '\U0000266E', "natural;": '\U0000266E', "naturals;": '\U00002115', "nbsp;": '\U000000A0', "ncap;": '\U00002A43', "ncaron;": '\U00000148', "ncedil;": '\U00000146', "ncong;": '\U00002247', "ncup;": '\U00002A42', "ncy;": '\U0000043D', "ndash;": '\U00002013', "ne;": '\U00002260', "neArr;": '\U000021D7', "nearhk;": '\U00002924', "nearr;": '\U00002197', "nearrow;": '\U00002197', "nequiv;": '\U00002262', "nesear;": '\U00002928', "nexist;": '\U00002204', "nexists;": '\U00002204', "nfr;": '\U0001D52B', "nge;": '\U00002271', "ngeq;": '\U00002271', "ngsim;": '\U00002275', "ngt;": '\U0000226F', "ngtr;": '\U0000226F', "nhArr;": '\U000021CE', "nharr;": '\U000021AE', "nhpar;": '\U00002AF2', "ni;": '\U0000220B', "nis;": '\U000022FC', "nisd;": '\U000022FA', "niv;": '\U0000220B', "njcy;": '\U0000045A', "nlArr;": '\U000021CD', "nlarr;": '\U0000219A', "nldr;": '\U00002025', "nle;": '\U00002270', "nleftarrow;": '\U0000219A', "nleftrightarrow;": '\U000021AE', "nleq;": '\U00002270', "nless;": '\U0000226E', "nlsim;": '\U00002274', "nlt;": '\U0000226E', "nltri;": '\U000022EA', "nltrie;": '\U000022EC', "nmid;": '\U00002224', "nopf;": '\U0001D55F', "not;": '\U000000AC', "notin;": '\U00002209', "notinva;": '\U00002209', "notinvb;": '\U000022F7', "notinvc;": '\U000022F6', "notni;": '\U0000220C', "notniva;": '\U0000220C', "notnivb;": '\U000022FE', "notnivc;": '\U000022FD', "npar;": '\U00002226', "nparallel;": '\U00002226', "npolint;": '\U00002A14', "npr;": '\U00002280', "nprcue;": '\U000022E0', "nprec;": '\U00002280', "nrArr;": '\U000021CF', "nrarr;": '\U0000219B', "nrightarrow;": '\U0000219B', "nrtri;": '\U000022EB', "nrtrie;": '\U000022ED', "nsc;": '\U00002281', "nsccue;": '\U000022E1', "nscr;": '\U0001D4C3', "nshortmid;": '\U00002224', "nshortparallel;": '\U00002226', "nsim;": '\U00002241', "nsime;": '\U00002244', "nsimeq;": '\U00002244', "nsmid;": '\U00002224', "nspar;": '\U00002226', "nsqsube;": '\U000022E2', "nsqsupe;": '\U000022E3', "nsub;": '\U00002284', "nsube;": '\U00002288', "nsubseteq;": '\U00002288', "nsucc;": '\U00002281', "nsup;": '\U00002285', "nsupe;": '\U00002289', "nsupseteq;": '\U00002289', "ntgl;": '\U00002279', "ntilde;": '\U000000F1', "ntlg;": '\U00002278', "ntriangleleft;": '\U000022EA', "ntrianglelefteq;": '\U000022EC', "ntriangleright;": '\U000022EB', "ntrianglerighteq;": '\U000022ED', "nu;": '\U000003BD', "num;": '\U00000023', "numero;": '\U00002116', "numsp;": '\U00002007', "nvDash;": '\U000022AD', "nvHarr;": '\U00002904', "nvdash;": '\U000022AC', "nvinfin;": '\U000029DE', "nvlArr;": '\U00002902', "nvrArr;": '\U00002903', "nwArr;": '\U000021D6', "nwarhk;": '\U00002923', "nwarr;": '\U00002196', "nwarrow;": '\U00002196', "nwnear;": '\U00002927', "oS;": '\U000024C8', "oacute;": '\U000000F3', "oast;": '\U0000229B', "ocir;": '\U0000229A', "ocirc;": '\U000000F4', "ocy;": '\U0000043E', "odash;": '\U0000229D', "odblac;": '\U00000151', "odiv;": '\U00002A38', "odot;": '\U00002299', "odsold;": '\U000029BC', "oelig;": '\U00000153', "ofcir;": '\U000029BF', "ofr;": '\U0001D52C', "ogon;": '\U000002DB', "ograve;": '\U000000F2', "ogt;": '\U000029C1', "ohbar;": '\U000029B5', "ohm;": '\U000003A9', "oint;": '\U0000222E', "olarr;": '\U000021BA', "olcir;": '\U000029BE', "olcross;": '\U000029BB', "oline;": '\U0000203E', "olt;": '\U000029C0', "omacr;": '\U0000014D', "omega;": '\U000003C9', "omicron;": '\U000003BF', "omid;": '\U000029B6', "ominus;": '\U00002296', "oopf;": '\U0001D560', "opar;": '\U000029B7', "operp;": '\U000029B9', "oplus;": '\U00002295', "or;": '\U00002228', "orarr;": '\U000021BB', "ord;": '\U00002A5D', "order;": '\U00002134', "orderof;": '\U00002134', "ordf;": '\U000000AA', "ordm;": '\U000000BA', "origof;": '\U000022B6', "oror;": '\U00002A56', "orslope;": '\U00002A57', "orv;": '\U00002A5B', "oscr;": '\U00002134', "oslash;": '\U000000F8', "osol;": '\U00002298', "otilde;": '\U000000F5', "otimes;": '\U00002297', "otimesas;": '\U00002A36', "ouml;": '\U000000F6', "ovbar;": '\U0000233D', "par;": '\U00002225', "para;": '\U000000B6', "parallel;": '\U00002225', "parsim;": '\U00002AF3', "parsl;": '\U00002AFD', "part;": '\U00002202', "pcy;": '\U0000043F', "percnt;": '\U00000025', "period;": '\U0000002E', "permil;": '\U00002030', "perp;": '\U000022A5', "pertenk;": '\U00002031', "pfr;": '\U0001D52D', "phi;": '\U000003C6', "phiv;": '\U000003D5', "phmmat;": '\U00002133', "phone;": '\U0000260E', "pi;": '\U000003C0', "pitchfork;": '\U000022D4', "piv;": '\U000003D6', "planck;": '\U0000210F', "planckh;": '\U0000210E', "plankv;": '\U0000210F', "plus;": '\U0000002B', "plusacir;": '\U00002A23', "plusb;": '\U0000229E', "pluscir;": '\U00002A22', "plusdo;": '\U00002214', "plusdu;": '\U00002A25', "pluse;": '\U00002A72', "plusmn;": '\U000000B1', "plussim;": '\U00002A26', "plustwo;": '\U00002A27', "pm;": '\U000000B1', "pointint;": '\U00002A15', "popf;": '\U0001D561', "pound;": '\U000000A3', "pr;": '\U0000227A', "prE;": '\U00002AB3', "prap;": '\U00002AB7', "prcue;": '\U0000227C', "pre;": '\U00002AAF', "prec;": '\U0000227A', "precapprox;": '\U00002AB7', "preccurlyeq;": '\U0000227C', "preceq;": '\U00002AAF', "precnapprox;": '\U00002AB9', "precneqq;": '\U00002AB5', "precnsim;": '\U000022E8', "precsim;": '\U0000227E', "prime;": '\U00002032', "primes;": '\U00002119', "prnE;": '\U00002AB5', "prnap;": '\U00002AB9', "prnsim;": '\U000022E8', "prod;": '\U0000220F', "profalar;": '\U0000232E', "profline;": '\U00002312', "profsurf;": '\U00002313', "prop;": '\U0000221D', "propto;": '\U0000221D', "prsim;": '\U0000227E', "prurel;": '\U000022B0', "pscr;": '\U0001D4C5', "psi;": '\U000003C8', "puncsp;": '\U00002008', "qfr;": '\U0001D52E', "qint;": '\U00002A0C', "qopf;": '\U0001D562', "qprime;": '\U00002057', "qscr;": '\U0001D4C6', "quaternions;": '\U0000210D', "quatint;": '\U00002A16', "quest;": '\U0000003F', "questeq;": '\U0000225F', "quot;": '\U00000022', "rAarr;": '\U000021DB', "rArr;": '\U000021D2', "rAtail;": '\U0000291C', "rBarr;": '\U0000290F', "rHar;": '\U00002964', "racute;": '\U00000155', "radic;": '\U0000221A', "raemptyv;": '\U000029B3', "rang;": '\U000027E9', "rangd;": '\U00002992', "range;": '\U000029A5', "rangle;": '\U000027E9', "raquo;": '\U000000BB', "rarr;": '\U00002192', "rarrap;": '\U00002975', "rarrb;": '\U000021E5', "rarrbfs;": '\U00002920', "rarrc;": '\U00002933', "rarrfs;": '\U0000291E', "rarrhk;": '\U000021AA', "rarrlp;": '\U000021AC', "rarrpl;": '\U00002945', "rarrsim;": '\U00002974', "rarrtl;": '\U000021A3', "rarrw;": '\U0000219D', "ratail;": '\U0000291A', "ratio;": '\U00002236', "rationals;": '\U0000211A', "rbarr;": '\U0000290D', "rbbrk;": '\U00002773', "rbrace;": '\U0000007D', "rbrack;": '\U0000005D', "rbrke;": '\U0000298C', "rbrksld;": '\U0000298E', "rbrkslu;": '\U00002990', "rcaron;": '\U00000159', "rcedil;": '\U00000157', "rceil;": '\U00002309', "rcub;": '\U0000007D', "rcy;": '\U00000440', "rdca;": '\U00002937', "rdldhar;": '\U00002969', "rdquo;": '\U0000201D', "rdquor;": '\U0000201D', "rdsh;": '\U000021B3', "real;": '\U0000211C', "realine;": '\U0000211B', "realpart;": '\U0000211C', "reals;": '\U0000211D', "rect;": '\U000025AD', "reg;": '\U000000AE', "rfisht;": '\U0000297D', "rfloor;": '\U0000230B', "rfr;": '\U0001D52F', "rhard;": '\U000021C1', "rharu;": '\U000021C0', "rharul;": '\U0000296C', "rho;": '\U000003C1', "rhov;": '\U000003F1', "rightarrow;": '\U00002192', "rightarrowtail;": '\U000021A3', "rightharpoondown;": '\U000021C1', "rightharpoonup;": '\U000021C0', "rightleftarrows;": '\U000021C4', "rightleftharpoons;": '\U000021CC', "rightrightarrows;": '\U000021C9', "rightsquigarrow;": '\U0000219D', "rightthreetimes;": '\U000022CC', "ring;": '\U000002DA', "risingdotseq;": '\U00002253', "rlarr;": '\U000021C4', "rlhar;": '\U000021CC', "rlm;": '\U0000200F', "rmoust;": '\U000023B1', "rmoustache;": '\U000023B1', "rnmid;": '\U00002AEE', "roang;": '\U000027ED', "roarr;": '\U000021FE', "robrk;": '\U000027E7', "ropar;": '\U00002986', "ropf;": '\U0001D563', "roplus;": '\U00002A2E', "rotimes;": '\U00002A35', "rpar;": '\U00000029', "rpargt;": '\U00002994', "rppolint;": '\U00002A12', "rrarr;": '\U000021C9', "rsaquo;": '\U0000203A', "rscr;": '\U0001D4C7', "rsh;": '\U000021B1', "rsqb;": '\U0000005D', "rsquo;": '\U00002019', "rsquor;": '\U00002019', "rthree;": '\U000022CC', "rtimes;": '\U000022CA', "rtri;": '\U000025B9', "rtrie;": '\U000022B5', "rtrif;": '\U000025B8', "rtriltri;": '\U000029CE', "ruluhar;": '\U00002968', "rx;": '\U0000211E', "sacute;": '\U0000015B', "sbquo;": '\U0000201A', "sc;": '\U0000227B', "scE;": '\U00002AB4', "scap;": '\U00002AB8', "scaron;": '\U00000161', "sccue;": '\U0000227D', "sce;": '\U00002AB0', "scedil;": '\U0000015F', "scirc;": '\U0000015D', "scnE;": '\U00002AB6', "scnap;": '\U00002ABA', "scnsim;": '\U000022E9', "scpolint;": '\U00002A13', "scsim;": '\U0000227F', "scy;": '\U00000441', "sdot;": '\U000022C5', "sdotb;": '\U000022A1', "sdote;": '\U00002A66', "seArr;": '\U000021D8', "searhk;": '\U00002925', "searr;": '\U00002198', "searrow;": '\U00002198', "sect;": '\U000000A7', "semi;": '\U0000003B', "seswar;": '\U00002929', "setminus;": '\U00002216', "setmn;": '\U00002216', "sext;": '\U00002736', "sfr;": '\U0001D530', "sfrown;": '\U00002322', "sharp;": '\U0000266F', "shchcy;": '\U00000449', "shcy;": '\U00000448', "shortmid;": '\U00002223', "shortparallel;": '\U00002225', "shy;": '\U000000AD', "sigma;": '\U000003C3', "sigmaf;": '\U000003C2', "sigmav;": '\U000003C2', "sim;": '\U0000223C', "simdot;": '\U00002A6A', "sime;": '\U00002243', "simeq;": '\U00002243', "simg;": '\U00002A9E', "simgE;": '\U00002AA0', "siml;": '\U00002A9D', "simlE;": '\U00002A9F', "simne;": '\U00002246', "simplus;": '\U00002A24', "simrarr;": '\U00002972', "slarr;": '\U00002190', "smallsetminus;": '\U00002216', "smashp;": '\U00002A33', "smeparsl;": '\U000029E4', "smid;": '\U00002223', "smile;": '\U00002323', "smt;": '\U00002AAA', "smte;": '\U00002AAC', "softcy;": '\U0000044C', "sol;": '\U0000002F', "solb;": '\U000029C4', "solbar;": '\U0000233F', "sopf;": '\U0001D564', "spades;": '\U00002660', "spadesuit;": '\U00002660', "spar;": '\U00002225', "sqcap;": '\U00002293', "sqcup;": '\U00002294', "sqsub;": '\U0000228F', "sqsube;": '\U00002291', "sqsubset;": '\U0000228F', "sqsubseteq;": '\U00002291', "sqsup;": '\U00002290', "sqsupe;": '\U00002292', "sqsupset;": '\U00002290', "sqsupseteq;": '\U00002292', "squ;": '\U000025A1', "square;": '\U000025A1', "squarf;": '\U000025AA', "squf;": '\U000025AA', "srarr;": '\U00002192', "sscr;": '\U0001D4C8', "ssetmn;": '\U00002216', "ssmile;": '\U00002323', "sstarf;": '\U000022C6', "star;": '\U00002606', "starf;": '\U00002605', "straightepsilon;": '\U000003F5', "straightphi;": '\U000003D5', "strns;": '\U000000AF', "sub;": '\U00002282', "subE;": '\U00002AC5', "subdot;": '\U00002ABD', "sube;": '\U00002286', "subedot;": '\U00002AC3', "submult;": '\U00002AC1', "subnE;": '\U00002ACB', "subne;": '\U0000228A', "subplus;": '\U00002ABF', "subrarr;": '\U00002979', "subset;": '\U00002282', "subseteq;": '\U00002286', "subseteqq;": '\U00002AC5', "subsetneq;": '\U0000228A', "subsetneqq;": '\U00002ACB', "subsim;": '\U00002AC7', "subsub;": '\U00002AD5', "subsup;": '\U00002AD3', "succ;": '\U0000227B', "succapprox;": '\U00002AB8', "succcurlyeq;": '\U0000227D', "succeq;": '\U00002AB0', "succnapprox;": '\U00002ABA', "succneqq;": '\U00002AB6', "succnsim;": '\U000022E9', "succsim;": '\U0000227F', "sum;": '\U00002211', "sung;": '\U0000266A', "sup;": '\U00002283', "sup1;": '\U000000B9', "sup2;": '\U000000B2', "sup3;": '\U000000B3', "supE;": '\U00002AC6', "supdot;": '\U00002ABE', "supdsub;": '\U00002AD8', "supe;": '\U00002287', "supedot;": '\U00002AC4', "suphsol;": '\U000027C9', "suphsub;": '\U00002AD7', "suplarr;": '\U0000297B', "supmult;": '\U00002AC2', "supnE;": '\U00002ACC', "supne;": '\U0000228B', "supplus;": '\U00002AC0', "supset;": '\U00002283', "supseteq;": '\U00002287', "supseteqq;": '\U00002AC6', "supsetneq;": '\U0000228B', "supsetneqq;": '\U00002ACC', "supsim;": '\U00002AC8', "supsub;": '\U00002AD4', "supsup;": '\U00002AD6', "swArr;": '\U000021D9', "swarhk;": '\U00002926', "swarr;": '\U00002199', "swarrow;": '\U00002199', "swnwar;": '\U0000292A', "szlig;": '\U000000DF', "target;": '\U00002316', "tau;": '\U000003C4', "tbrk;": '\U000023B4', "tcaron;": '\U00000165', "tcedil;": '\U00000163', "tcy;": '\U00000442', "tdot;": '\U000020DB', "telrec;": '\U00002315', "tfr;": '\U0001D531', "there4;": '\U00002234', "therefore;": '\U00002234', "theta;": '\U000003B8', "thetasym;": '\U000003D1', "thetav;": '\U000003D1', "thickapprox;": '\U00002248', "thicksim;": '\U0000223C', "thinsp;": '\U00002009', "thkap;": '\U00002248', "thksim;": '\U0000223C', "thorn;": '\U000000FE', "tilde;": '\U000002DC', "times;": '\U000000D7', "timesb;": '\U000022A0', "timesbar;": '\U00002A31', "timesd;": '\U00002A30', "tint;": '\U0000222D', "toea;": '\U00002928', "top;": '\U000022A4', "topbot;": '\U00002336', "topcir;": '\U00002AF1', "topf;": '\U0001D565', "topfork;": '\U00002ADA', "tosa;": '\U00002929', "tprime;": '\U00002034', "trade;": '\U00002122', "triangle;": '\U000025B5', "triangledown;": '\U000025BF', "triangleleft;": '\U000025C3', "trianglelefteq;": '\U000022B4', "triangleq;": '\U0000225C', "triangleright;": '\U000025B9', "trianglerighteq;": '\U000022B5', "tridot;": '\U000025EC', "trie;": '\U0000225C', "triminus;": '\U00002A3A', "triplus;": '\U00002A39', "trisb;": '\U000029CD', "tritime;": '\U00002A3B', "trpezium;": '\U000023E2', "tscr;": '\U0001D4C9', "tscy;": '\U00000446', "tshcy;": '\U0000045B', "tstrok;": '\U00000167', "twixt;": '\U0000226C', "twoheadleftarrow;": '\U0000219E', "twoheadrightarrow;": '\U000021A0', "uArr;": '\U000021D1', "uHar;": '\U00002963', "uacute;": '\U000000FA', "uarr;": '\U00002191', "ubrcy;": '\U0000045E', "ubreve;": '\U0000016D', "ucirc;": '\U000000FB', "ucy;": '\U00000443', "udarr;": '\U000021C5', "udblac;": '\U00000171', "udhar;": '\U0000296E', "ufisht;": '\U0000297E', "ufr;": '\U0001D532', "ugrave;": '\U000000F9', "uharl;": '\U000021BF', "uharr;": '\U000021BE', "uhblk;": '\U00002580', "ulcorn;": '\U0000231C', "ulcorner;": '\U0000231C', "ulcrop;": '\U0000230F', "ultri;": '\U000025F8', "umacr;": '\U0000016B', "uml;": '\U000000A8', "uogon;": '\U00000173', "uopf;": '\U0001D566', "uparrow;": '\U00002191', "updownarrow;": '\U00002195', "upharpoonleft;": '\U000021BF', "upharpoonright;": '\U000021BE', "uplus;": '\U0000228E', "upsi;": '\U000003C5', "upsih;": '\U000003D2', "upsilon;": '\U000003C5', "upuparrows;": '\U000021C8', "urcorn;": '\U0000231D', "urcorner;": '\U0000231D', "urcrop;": '\U0000230E', "uring;": '\U0000016F', "urtri;": '\U000025F9', "uscr;": '\U0001D4CA', "utdot;": '\U000022F0', "utilde;": '\U00000169', "utri;": '\U000025B5', "utrif;": '\U000025B4', "uuarr;": '\U000021C8', "uuml;": '\U000000FC', "uwangle;": '\U000029A7', "vArr;": '\U000021D5', "vBar;": '\U00002AE8', "vBarv;": '\U00002AE9', "vDash;": '\U000022A8', "vangrt;": '\U0000299C', "varepsilon;": '\U000003F5', "varkappa;": '\U000003F0', "varnothing;": '\U00002205', "varphi;": '\U000003D5', "varpi;": '\U000003D6', "varpropto;": '\U0000221D', "varr;": '\U00002195', "varrho;": '\U000003F1', "varsigma;": '\U000003C2', "vartheta;": '\U000003D1', "vartriangleleft;": '\U000022B2', "vartriangleright;": '\U000022B3', "vcy;": '\U00000432', "vdash;": '\U000022A2', "vee;": '\U00002228', "veebar;": '\U000022BB', "veeeq;": '\U0000225A', "vellip;": '\U000022EE', "verbar;": '\U0000007C', "vert;": '\U0000007C', "vfr;": '\U0001D533', "vltri;": '\U000022B2', "vopf;": '\U0001D567', "vprop;": '\U0000221D', "vrtri;": '\U000022B3', "vscr;": '\U0001D4CB', "vzigzag;": '\U0000299A', "wcirc;": '\U00000175', "wedbar;": '\U00002A5F', "wedge;": '\U00002227', "wedgeq;": '\U00002259', "weierp;": '\U00002118', "wfr;": '\U0001D534', "wopf;": '\U0001D568', "wp;": '\U00002118', "wr;": '\U00002240', "wreath;": '\U00002240', "wscr;": '\U0001D4CC', "xcap;": '\U000022C2', "xcirc;": '\U000025EF', "xcup;": '\U000022C3', "xdtri;": '\U000025BD', "xfr;": '\U0001D535', "xhArr;": '\U000027FA', "xharr;": '\U000027F7', "xi;": '\U000003BE', "xlArr;": '\U000027F8', "xlarr;": '\U000027F5', "xmap;": '\U000027FC', "xnis;": '\U000022FB', "xodot;": '\U00002A00', "xopf;": '\U0001D569', "xoplus;": '\U00002A01', "xotime;": '\U00002A02', "xrArr;": '\U000027F9', "xrarr;": '\U000027F6', "xscr;": '\U0001D4CD', "xsqcup;": '\U00002A06', "xuplus;": '\U00002A04', "xutri;": '\U000025B3', "xvee;": '\U000022C1', "xwedge;": '\U000022C0', "yacute;": '\U000000FD', "yacy;": '\U0000044F', "ycirc;": '\U00000177', "ycy;": '\U0000044B', "yen;": '\U000000A5', "yfr;": '\U0001D536', "yicy;": '\U00000457', "yopf;": '\U0001D56A', "yscr;": '\U0001D4CE', "yucy;": '\U0000044E', "yuml;": '\U000000FF', "zacute;": '\U0000017A', "zcaron;": '\U0000017E', "zcy;": '\U00000437', "zdot;": '\U0000017C', "zeetrf;": '\U00002128', "zeta;": '\U000003B6', "zfr;": '\U0001D537', "zhcy;": '\U00000436', "zigrarr;": '\U000021DD', "zopf;": '\U0001D56B', "zscr;": '\U0001D4CF', "zwj;": '\U0000200D', "zwnj;": '\U0000200C', "AElig": '\U000000C6', "AMP": '\U00000026', "Aacute": '\U000000C1', "Acirc": '\U000000C2', "Agrave": '\U000000C0', "Aring": '\U000000C5', "Atilde": '\U000000C3', "Auml": '\U000000C4', "COPY": '\U000000A9', "Ccedil": '\U000000C7', "ETH": '\U000000D0', "Eacute": '\U000000C9', "Ecirc": '\U000000CA', "Egrave": '\U000000C8', "Euml": '\U000000CB', "GT": '\U0000003E', "Iacute": '\U000000CD', "Icirc": '\U000000CE', "Igrave": '\U000000CC', "Iuml": '\U000000CF', "LT": '\U0000003C', "Ntilde": '\U000000D1', "Oacute": '\U000000D3', "Ocirc": '\U000000D4', "Ograve": '\U000000D2', "Oslash": '\U000000D8', "Otilde": '\U000000D5', "Ouml": '\U000000D6', "QUOT": '\U00000022', "REG": '\U000000AE', "THORN": '\U000000DE', "Uacute": '\U000000DA', "Ucirc": '\U000000DB', "Ugrave": '\U000000D9', "Uuml": '\U000000DC', "Yacute": '\U000000DD', "aacute": '\U000000E1', "acirc": '\U000000E2', "acute": '\U000000B4', "aelig": '\U000000E6', "agrave": '\U000000E0', "amp": '\U00000026', "aring": '\U000000E5', "atilde": '\U000000E3', "auml": '\U000000E4', "brvbar": '\U000000A6', "ccedil": '\U000000E7', "cedil": '\U000000B8', "cent": '\U000000A2', "copy": '\U000000A9', "curren": '\U000000A4', "deg": '\U000000B0', "divide": '\U000000F7', "eacute": '\U000000E9', "ecirc": '\U000000EA', "egrave": '\U000000E8', "eth": '\U000000F0', "euml": '\U000000EB', "frac12": '\U000000BD', "frac14": '\U000000BC', "frac34": '\U000000BE', "gt": '\U0000003E', "iacute": '\U000000ED', "icirc": '\U000000EE', "iexcl": '\U000000A1', "igrave": '\U000000EC', "iquest": '\U000000BF', "iuml": '\U000000EF', "laquo": '\U000000AB', "lt": '\U0000003C', "macr": '\U000000AF', "micro": '\U000000B5', "middot": '\U000000B7', "nbsp": '\U000000A0', "not": '\U000000AC', "ntilde": '\U000000F1', "oacute": '\U000000F3', "ocirc": '\U000000F4', "ograve": '\U000000F2', "ordf": '\U000000AA', "ordm": '\U000000BA', "oslash": '\U000000F8', "otilde": '\U000000F5', "ouml": '\U000000F6', "para": '\U000000B6', "plusmn": '\U000000B1', "pound": '\U000000A3', "quot": '\U00000022', "raquo": '\U000000BB', "reg": '\U000000AE', "sect": '\U000000A7', "shy": '\U000000AD', "sup1": '\U000000B9', "sup2": '\U000000B2', "sup3": '\U000000B3', "szlig": '\U000000DF', "thorn": '\U000000FE', "times": '\U000000D7', "uacute": '\U000000FA', "ucirc": '\U000000FB', "ugrave": '\U000000F9', "uml": '\U000000A8', "uuml": '\U000000FC', "yacute": '\U000000FD', "yen": '\U000000A5', "yuml": '\U000000FF', } // HTML entities that are two unicode codepoints. var entity2 = map[string][2]rune{ // TODO(nigeltao): Handle replacements that are wider than their names. // "nLt;": {'\u226A', '\u20D2'}, // "nGt;": {'\u226B', '\u20D2'}, "NotEqualTilde;": {'\u2242', '\u0338'}, "NotGreaterFullEqual;": {'\u2267', '\u0338'}, "NotGreaterGreater;": {'\u226B', '\u0338'}, "NotGreaterSlantEqual;": {'\u2A7E', '\u0338'}, "NotHumpDownHump;": {'\u224E', '\u0338'}, "NotHumpEqual;": {'\u224F', '\u0338'}, "NotLeftTriangleBar;": {'\u29CF', '\u0338'}, "NotLessLess;": {'\u226A', '\u0338'}, "NotLessSlantEqual;": {'\u2A7D', '\u0338'}, "NotNestedGreaterGreater;": {'\u2AA2', '\u0338'}, "NotNestedLessLess;": {'\u2AA1', '\u0338'}, "NotPrecedesEqual;": {'\u2AAF', '\u0338'}, "NotRightTriangleBar;": {'\u29D0', '\u0338'}, "NotSquareSubset;": {'\u228F', '\u0338'}, "NotSquareSuperset;": {'\u2290', '\u0338'}, "NotSubset;": {'\u2282', '\u20D2'}, "NotSucceedsEqual;": {'\u2AB0', '\u0338'}, "NotSucceedsTilde;": {'\u227F', '\u0338'}, "NotSuperset;": {'\u2283', '\u20D2'}, "ThickSpace;": {'\u205F', '\u200A'}, "acE;": {'\u223E', '\u0333'}, "bne;": {'\u003D', '\u20E5'}, "bnequiv;": {'\u2261', '\u20E5'}, "caps;": {'\u2229', '\uFE00'}, "cups;": {'\u222A', '\uFE00'}, "fjlig;": {'\u0066', '\u006A'}, "gesl;": {'\u22DB', '\uFE00'}, "gvertneqq;": {'\u2269', '\uFE00'}, "gvnE;": {'\u2269', '\uFE00'}, "lates;": {'\u2AAD', '\uFE00'}, "lesg;": {'\u22DA', '\uFE00'}, "lvertneqq;": {'\u2268', '\uFE00'}, "lvnE;": {'\u2268', '\uFE00'}, "nGg;": {'\u22D9', '\u0338'}, "nGtv;": {'\u226B', '\u0338'}, "nLl;": {'\u22D8', '\u0338'}, "nLtv;": {'\u226A', '\u0338'}, "nang;": {'\u2220', '\u20D2'}, "napE;": {'\u2A70', '\u0338'}, "napid;": {'\u224B', '\u0338'}, "nbump;": {'\u224E', '\u0338'}, "nbumpe;": {'\u224F', '\u0338'}, "ncongdot;": {'\u2A6D', '\u0338'}, "nedot;": {'\u2250', '\u0338'}, "nesim;": {'\u2242', '\u0338'}, "ngE;": {'\u2267', '\u0338'}, "ngeqq;": {'\u2267', '\u0338'}, "ngeqslant;": {'\u2A7E', '\u0338'}, "nges;": {'\u2A7E', '\u0338'}, "nlE;": {'\u2266', '\u0338'}, "nleqq;": {'\u2266', '\u0338'}, "nleqslant;": {'\u2A7D', '\u0338'}, "nles;": {'\u2A7D', '\u0338'}, "notinE;": {'\u22F9', '\u0338'}, "notindot;": {'\u22F5', '\u0338'}, "nparsl;": {'\u2AFD', '\u20E5'}, "npart;": {'\u2202', '\u0338'}, "npre;": {'\u2AAF', '\u0338'}, "npreceq;": {'\u2AAF', '\u0338'}, "nrarrc;": {'\u2933', '\u0338'}, "nrarrw;": {'\u219D', '\u0338'}, "nsce;": {'\u2AB0', '\u0338'}, "nsubE;": {'\u2AC5', '\u0338'}, "nsubset;": {'\u2282', '\u20D2'}, "nsubseteqq;": {'\u2AC5', '\u0338'}, "nsucceq;": {'\u2AB0', '\u0338'}, "nsupE;": {'\u2AC6', '\u0338'}, "nsupset;": {'\u2283', '\u20D2'}, "nsupseteqq;": {'\u2AC6', '\u0338'}, "nvap;": {'\u224D', '\u20D2'}, "nvge;": {'\u2265', '\u20D2'}, "nvgt;": {'\u003E', '\u20D2'}, "nvle;": {'\u2264', '\u20D2'}, "nvlt;": {'\u003C', '\u20D2'}, "nvltrie;": {'\u22B4', '\u20D2'}, "nvrtrie;": {'\u22B5', '\u20D2'}, "nvsim;": {'\u223C', '\u20D2'}, "race;": {'\u223D', '\u0331'}, "smtes;": {'\u2AAC', '\uFE00'}, "sqcaps;": {'\u2293', '\uFE00'}, "sqcups;": {'\u2294', '\uFE00'}, "varsubsetneq;": {'\u228A', '\uFE00'}, "varsubsetneqq;": {'\u2ACB', '\uFE00'}, "varsupsetneq;": {'\u228B', '\uFE00'}, "varsupsetneqq;": {'\u2ACC', '\uFE00'}, "vnsub;": {'\u2282', '\u20D2'}, "vnsup;": {'\u2283', '\u20D2'}, "vsubnE;": {'\u2ACB', '\uFE00'}, "vsubne;": {'\u228A', '\uFE00'}, "vsupnE;": {'\u2ACC', '\uFE00'}, "vsupne;": {'\u228B', '\uFE00'}, } ================================================ FILE: vendor/golang.org/x/net/html/entity_test.go ================================================ // 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 html import ( "testing" "unicode/utf8" ) func TestEntityLength(t *testing.T) { // We verify that the length of UTF-8 encoding of each value is <= 1 + len(key). // The +1 comes from the leading "&". This property implies that the length of // unescaped text is <= the length of escaped text. for k, v := range entity { if 1+len(k) < utf8.RuneLen(v) { t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v)) } if len(k) > longestEntityWithoutSemicolon && k[len(k)-1] != ';' { t.Errorf("entity name %s is %d characters, but longestEntityWithoutSemicolon=%d", k, len(k), longestEntityWithoutSemicolon) } } for k, v := range entity2 { if 1+len(k) < utf8.RuneLen(v[0])+utf8.RuneLen(v[1]) { t.Error("escaped entity &" + k + " is shorter than its UTF-8 encoding " + string(v[0]) + string(v[1])) } } } ================================================ FILE: vendor/golang.org/x/net/html/escape.go ================================================ // 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 html import ( "bytes" "strings" "unicode/utf8" ) // These replacements permit compatibility with old numeric entities that // assumed Windows-1252 encoding. // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference var replacementTable = [...]rune{ '\u20AC', // First entry is what 0x80 should be replaced with. '\u0081', '\u201A', '\u0192', '\u201E', '\u2026', '\u2020', '\u2021', '\u02C6', '\u2030', '\u0160', '\u2039', '\u0152', '\u008D', '\u017D', '\u008F', '\u0090', '\u2018', '\u2019', '\u201C', '\u201D', '\u2022', '\u2013', '\u2014', '\u02DC', '\u2122', '\u0161', '\u203A', '\u0153', '\u009D', '\u017E', '\u0178', // Last entry is 0x9F. // 0x00->'\uFFFD' is handled programmatically. // 0x0D->'\u000D' is a no-op. } // unescapeEntity reads an entity like "<" from b[src:] and writes the // corresponding "<" to b[dst:], returning the incremented dst and src cursors. // Precondition: b[src] == '&' && dst <= src. // attribute should be true if parsing an attribute value. func unescapeEntity(b []byte, dst, src int, attribute bool) (dst1, src1 int) { // https://html.spec.whatwg.org/multipage/syntax.html#consume-a-character-reference // i starts at 1 because we already know that s[0] == '&'. i, s := 1, b[src:] if len(s) <= 1 { b[dst] = b[src] return dst + 1, src + 1 } if s[i] == '#' { if len(s) <= 3 { // We need to have at least "&#.". b[dst] = b[src] return dst + 1, src + 1 } i++ c := s[i] hex := false if c == 'x' || c == 'X' { hex = true i++ } x := '\x00' for i < len(s) { c = s[i] i++ if hex { if '0' <= c && c <= '9' { x = 16*x + rune(c) - '0' continue } else if 'a' <= c && c <= 'f' { x = 16*x + rune(c) - 'a' + 10 continue } else if 'A' <= c && c <= 'F' { x = 16*x + rune(c) - 'A' + 10 continue } } else if '0' <= c && c <= '9' { x = 10*x + rune(c) - '0' continue } if c != ';' { i-- } break } if i <= 3 { // No characters matched. b[dst] = b[src] return dst + 1, src + 1 } if 0x80 <= x && x <= 0x9F { // Replace characters from Windows-1252 with UTF-8 equivalents. x = replacementTable[x-0x80] } else if x == 0 || (0xD800 <= x && x <= 0xDFFF) || x > 0x10FFFF { // Replace invalid characters with the replacement character. x = '\uFFFD' } return dst + utf8.EncodeRune(b[dst:], x), src + i } // Consume the maximum number of characters possible, with the // consumed characters matching one of the named references. for i < len(s) { c := s[i] i++ // Lower-cased characters are more common in entities, so we check for them first. if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { continue } if c != ';' { i-- } break } entityName := string(s[1:i]) if entityName == "" { // No-op. } else if attribute && entityName[len(entityName)-1] != ';' && len(s) > i && s[i] == '=' { // No-op. } else if x := entity[entityName]; x != 0 { return dst + utf8.EncodeRune(b[dst:], x), src + i } else if x := entity2[entityName]; x[0] != 0 { dst1 := dst + utf8.EncodeRune(b[dst:], x[0]) return dst1 + utf8.EncodeRune(b[dst1:], x[1]), src + i } else if !attribute { maxLen := len(entityName) - 1 if maxLen > longestEntityWithoutSemicolon { maxLen = longestEntityWithoutSemicolon } for j := maxLen; j > 1; j-- { if x := entity[entityName[:j]]; x != 0 { return dst + utf8.EncodeRune(b[dst:], x), src + j + 1 } } } dst1, src1 = dst+i, src+i copy(b[dst:dst1], b[src:src1]) return dst1, src1 } // unescape unescapes b's entities in-place, so that "a<b" becomes "a': esc = ">" case '"': // """ is shorter than """. esc = """ case '\r': esc = " " default: panic("unrecognized escape character") } s = s[i+1:] if _, err := w.WriteString(esc); err != nil { return err } i = strings.IndexAny(s, escapedChars) } _, err := w.WriteString(s) return err } // EscapeString escapes special characters like "<" to become "<". It // escapes only five such characters: <, >, &, ' and ". // UnescapeString(EscapeString(s)) == s always holds, but the converse isn't // always true. func EscapeString(s string) string { if strings.IndexAny(s, escapedChars) == -1 { return s } var buf bytes.Buffer escape(&buf, s) return buf.String() } // UnescapeString unescapes entities like "<" to become "<". It unescapes a // larger range of entities than EscapeString escapes. For example, "á" // unescapes to "á", as does "á" and "&xE1;". // UnescapeString(EscapeString(s)) == s always holds, but the converse isn't // always true. func UnescapeString(s string) string { for _, c := range s { if c == '&' { return string(unescape([]byte(s), false)) } } return s } ================================================ FILE: vendor/golang.org/x/net/html/escape_test.go ================================================ // 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 html import "testing" type unescapeTest struct { // A short description of the test case. desc string // The HTML text. html string // The unescaped text. unescaped string } var unescapeTests = []unescapeTest{ // Handle no entities. { "copy", "A\ttext\nstring", "A\ttext\nstring", }, // Handle simple named entities. { "simple", "& > <", "& > <", }, // Handle hitting the end of the string. { "stringEnd", "& &", "& &", }, // Handle entities with two codepoints. { "multiCodepoint", "text ⋛︀ blah", "text \u22db\ufe00 blah", }, // Handle decimal numeric entities. { "decimalEntity", "Delta = Δ ", "Delta = Δ ", }, // Handle hexadecimal numeric entities. { "hexadecimalEntity", "Lambda = λ = λ ", "Lambda = λ = λ ", }, // Handle numeric early termination. { "numericEnds", "&# &#x €43 © = ©f = ©", "&# &#x €43 © = ©f = ©", }, // Handle numeric ISO-8859-1 entity replacements. { "numericReplacements", "Footnote‡", "Footnote‡", }, } func TestUnescape(t *testing.T) { for _, tt := range unescapeTests { unescaped := UnescapeString(tt.html) if unescaped != tt.unescaped { t.Errorf("TestUnescape %s: want %q, got %q", tt.desc, tt.unescaped, unescaped) } } } func TestUnescapeEscape(t *testing.T) { ss := []string{ ``, `abc def`, `a & b`, `a&b`, `a & b`, `"`, `"`, `"<&>"`, `"<&>"`, `3&5==1 && 0<1, "0<1", a+acute=á`, `The special characters are: <, >, &, ' and "`, } for _, s := range ss { if got := UnescapeString(EscapeString(s)); got != s { t.Errorf("got %q want %q", got, s) } } } ================================================ FILE: vendor/golang.org/x/net/html/example_test.go ================================================ // 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 example demonstrates parsing HTML data and walking the resulting tree. package html_test import ( "fmt" "log" "strings" "golang.org/x/net/html" ) func ExampleParse() { s := `

Links:

` doc, err := html.Parse(strings.NewReader(s)) if err != nil { log.Fatal(err) } var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "a" { for _, a := range n.Attr { if a.Key == "href" { fmt.Println(a.Val) break } } } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) // Output: // foo // /bar/baz } ================================================ FILE: vendor/golang.org/x/net/html/foreign.go ================================================ // 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 html import ( "strings" ) func adjustAttributeNames(aa []Attribute, nameMap map[string]string) { for i := range aa { if newName, ok := nameMap[aa[i].Key]; ok { aa[i].Key = newName } } } func adjustForeignAttributes(aa []Attribute) { for i, a := range aa { if a.Key == "" || a.Key[0] != 'x' { continue } switch a.Key { case "xlink:actuate", "xlink:arcrole", "xlink:href", "xlink:role", "xlink:show", "xlink:title", "xlink:type", "xml:base", "xml:lang", "xml:space", "xmlns:xlink": j := strings.Index(a.Key, ":") aa[i].Namespace = a.Key[:j] aa[i].Key = a.Key[j+1:] } } } func htmlIntegrationPoint(n *Node) bool { if n.Type != ElementNode { return false } switch n.Namespace { case "math": if n.Data == "annotation-xml" { for _, a := range n.Attr { if a.Key == "encoding" { val := strings.ToLower(a.Val) if val == "text/html" || val == "application/xhtml+xml" { return true } } } } case "svg": switch n.Data { case "desc", "foreignObject", "title": return true } } return false } func mathMLTextIntegrationPoint(n *Node) bool { if n.Namespace != "math" { return false } switch n.Data { case "mi", "mo", "mn", "ms", "mtext": return true } return false } // Section 12.2.5.5. var breakout = map[string]bool{ "b": true, "big": true, "blockquote": true, "body": true, "br": true, "center": true, "code": true, "dd": true, "div": true, "dl": true, "dt": true, "em": true, "embed": true, "h1": true, "h2": true, "h3": true, "h4": true, "h5": true, "h6": true, "head": true, "hr": true, "i": true, "img": true, "li": true, "listing": true, "menu": true, "meta": true, "nobr": true, "ol": true, "p": true, "pre": true, "ruby": true, "s": true, "small": true, "span": true, "strong": true, "strike": true, "sub": true, "sup": true, "table": true, "tt": true, "u": true, "ul": true, "var": true, } // Section 12.2.5.5. var svgTagNameAdjustments = map[string]string{ "altglyph": "altGlyph", "altglyphdef": "altGlyphDef", "altglyphitem": "altGlyphItem", "animatecolor": "animateColor", "animatemotion": "animateMotion", "animatetransform": "animateTransform", "clippath": "clipPath", "feblend": "feBlend", "fecolormatrix": "feColorMatrix", "fecomponenttransfer": "feComponentTransfer", "fecomposite": "feComposite", "feconvolvematrix": "feConvolveMatrix", "fediffuselighting": "feDiffuseLighting", "fedisplacementmap": "feDisplacementMap", "fedistantlight": "feDistantLight", "feflood": "feFlood", "fefunca": "feFuncA", "fefuncb": "feFuncB", "fefuncg": "feFuncG", "fefuncr": "feFuncR", "fegaussianblur": "feGaussianBlur", "feimage": "feImage", "femerge": "feMerge", "femergenode": "feMergeNode", "femorphology": "feMorphology", "feoffset": "feOffset", "fepointlight": "fePointLight", "fespecularlighting": "feSpecularLighting", "fespotlight": "feSpotLight", "fetile": "feTile", "feturbulence": "feTurbulence", "foreignobject": "foreignObject", "glyphref": "glyphRef", "lineargradient": "linearGradient", "radialgradient": "radialGradient", "textpath": "textPath", } // Section 12.2.5.1 var mathMLAttributeAdjustments = map[string]string{ "definitionurl": "definitionURL", } var svgAttributeAdjustments = map[string]string{ "attributename": "attributeName", "attributetype": "attributeType", "basefrequency": "baseFrequency", "baseprofile": "baseProfile", "calcmode": "calcMode", "clippathunits": "clipPathUnits", "contentscripttype": "contentScriptType", "contentstyletype": "contentStyleType", "diffuseconstant": "diffuseConstant", "edgemode": "edgeMode", "externalresourcesrequired": "externalResourcesRequired", "filterres": "filterRes", "filterunits": "filterUnits", "glyphref": "glyphRef", "gradienttransform": "gradientTransform", "gradientunits": "gradientUnits", "kernelmatrix": "kernelMatrix", "kernelunitlength": "kernelUnitLength", "keypoints": "keyPoints", "keysplines": "keySplines", "keytimes": "keyTimes", "lengthadjust": "lengthAdjust", "limitingconeangle": "limitingConeAngle", "markerheight": "markerHeight", "markerunits": "markerUnits", "markerwidth": "markerWidth", "maskcontentunits": "maskContentUnits", "maskunits": "maskUnits", "numoctaves": "numOctaves", "pathlength": "pathLength", "patterncontentunits": "patternContentUnits", "patterntransform": "patternTransform", "patternunits": "patternUnits", "pointsatx": "pointsAtX", "pointsaty": "pointsAtY", "pointsatz": "pointsAtZ", "preservealpha": "preserveAlpha", "preserveaspectratio": "preserveAspectRatio", "primitiveunits": "primitiveUnits", "refx": "refX", "refy": "refY", "repeatcount": "repeatCount", "repeatdur": "repeatDur", "requiredextensions": "requiredExtensions", "requiredfeatures": "requiredFeatures", "specularconstant": "specularConstant", "specularexponent": "specularExponent", "spreadmethod": "spreadMethod", "startoffset": "startOffset", "stddeviation": "stdDeviation", "stitchtiles": "stitchTiles", "surfacescale": "surfaceScale", "systemlanguage": "systemLanguage", "tablevalues": "tableValues", "targetx": "targetX", "targety": "targetY", "textlength": "textLength", "viewbox": "viewBox", "viewtarget": "viewTarget", "xchannelselector": "xChannelSelector", "ychannelselector": "yChannelSelector", "zoomandpan": "zoomAndPan", } ================================================ FILE: vendor/golang.org/x/net/html/node.go ================================================ // 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 html import ( "golang.org/x/net/html/atom" ) // A NodeType is the type of a Node. type NodeType uint32 const ( ErrorNode NodeType = iota TextNode DocumentNode ElementNode CommentNode DoctypeNode scopeMarkerNode ) // Section 12.2.3.3 says "scope markers are inserted when entering applet // elements, buttons, object elements, marquees, table cells, and table // captions, and are used to prevent formatting from 'leaking'". var scopeMarker = Node{Type: scopeMarkerNode} // A Node consists of a NodeType and some Data (tag name for element nodes, // content for text) and are part of a tree of Nodes. Element nodes may also // have a Namespace and contain a slice of Attributes. Data is unescaped, so // that it looks like "a 0 { return (*s)[i-1] } return nil } // index returns the index of the top-most occurrence of n in the stack, or -1 // if n is not present. func (s *nodeStack) index(n *Node) int { for i := len(*s) - 1; i >= 0; i-- { if (*s)[i] == n { return i } } return -1 } // insert inserts a node at the given index. func (s *nodeStack) insert(i int, n *Node) { (*s) = append(*s, nil) copy((*s)[i+1:], (*s)[i:]) (*s)[i] = n } // remove removes a node from the stack. It is a no-op if n is not present. func (s *nodeStack) remove(n *Node) { i := s.index(n) if i == -1 { return } copy((*s)[i:], (*s)[i+1:]) j := len(*s) - 1 (*s)[j] = nil *s = (*s)[:j] } ================================================ FILE: vendor/golang.org/x/net/html/node_test.go ================================================ // 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 html import ( "fmt" ) // checkTreeConsistency checks that a node and its descendants are all // consistent in their parent/child/sibling relationships. func checkTreeConsistency(n *Node) error { return checkTreeConsistency1(n, 0) } func checkTreeConsistency1(n *Node, depth int) error { if depth == 1e4 { return fmt.Errorf("html: tree looks like it contains a cycle") } if err := checkNodeConsistency(n); err != nil { return err } for c := n.FirstChild; c != nil; c = c.NextSibling { if err := checkTreeConsistency1(c, depth+1); err != nil { return err } } return nil } // checkNodeConsistency checks that a node's parent/child/sibling relationships // are consistent. func checkNodeConsistency(n *Node) error { if n == nil { return nil } nParent := 0 for p := n.Parent; p != nil; p = p.Parent { nParent++ if nParent == 1e4 { return fmt.Errorf("html: parent list looks like an infinite loop") } } nForward := 0 for c := n.FirstChild; c != nil; c = c.NextSibling { nForward++ if nForward == 1e6 { return fmt.Errorf("html: forward list of children looks like an infinite loop") } if c.Parent != n { return fmt.Errorf("html: inconsistent child/parent relationship") } } nBackward := 0 for c := n.LastChild; c != nil; c = c.PrevSibling { nBackward++ if nBackward == 1e6 { return fmt.Errorf("html: backward list of children looks like an infinite loop") } if c.Parent != n { return fmt.Errorf("html: inconsistent child/parent relationship") } } if n.Parent != nil { if n.Parent == n { return fmt.Errorf("html: inconsistent parent relationship") } if n.Parent == n.FirstChild { return fmt.Errorf("html: inconsistent parent/first relationship") } if n.Parent == n.LastChild { return fmt.Errorf("html: inconsistent parent/last relationship") } if n.Parent == n.PrevSibling { return fmt.Errorf("html: inconsistent parent/prev relationship") } if n.Parent == n.NextSibling { return fmt.Errorf("html: inconsistent parent/next relationship") } parentHasNAsAChild := false for c := n.Parent.FirstChild; c != nil; c = c.NextSibling { if c == n { parentHasNAsAChild = true break } } if !parentHasNAsAChild { return fmt.Errorf("html: inconsistent parent/child relationship") } } if n.PrevSibling != nil && n.PrevSibling.NextSibling != n { return fmt.Errorf("html: inconsistent prev/next relationship") } if n.NextSibling != nil && n.NextSibling.PrevSibling != n { return fmt.Errorf("html: inconsistent next/prev relationship") } if (n.FirstChild == nil) != (n.LastChild == nil) { return fmt.Errorf("html: inconsistent first/last relationship") } if n.FirstChild != nil && n.FirstChild == n.LastChild { // We have a sole child. if n.FirstChild.PrevSibling != nil || n.FirstChild.NextSibling != nil { return fmt.Errorf("html: inconsistent sole child's sibling relationship") } } seen := map[*Node]bool{} var last *Node for c := n.FirstChild; c != nil; c = c.NextSibling { if seen[c] { return fmt.Errorf("html: inconsistent repeated child") } seen[c] = true last = c } if last != n.LastChild { return fmt.Errorf("html: inconsistent last relationship") } var first *Node for c := n.LastChild; c != nil; c = c.PrevSibling { if !seen[c] { return fmt.Errorf("html: inconsistent missing child") } delete(seen, c) first = c } if first != n.FirstChild { return fmt.Errorf("html: inconsistent first relationship") } if len(seen) != 0 { return fmt.Errorf("html: inconsistent forwards/backwards child list") } return nil } ================================================ FILE: vendor/golang.org/x/net/html/parse.go ================================================ // 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 html import ( "errors" "fmt" "io" "strings" a "golang.org/x/net/html/atom" ) // A parser implements the HTML5 parsing algorithm: // https://html.spec.whatwg.org/multipage/syntax.html#tree-construction type parser struct { // tokenizer provides the tokens for the parser. tokenizer *Tokenizer // tok is the most recently read token. tok Token // Self-closing tags like
are treated as start tags, except that // hasSelfClosingToken is set while they are being processed. hasSelfClosingToken bool // doc is the document root element. doc *Node // The stack of open elements (section 12.2.3.2) and active formatting // elements (section 12.2.3.3). oe, afe nodeStack // Element pointers (section 12.2.3.4). head, form *Node // Other parsing state flags (section 12.2.3.5). scripting, framesetOK bool // im is the current insertion mode. im insertionMode // originalIM is the insertion mode to go back to after completing a text // or inTableText insertion mode. originalIM insertionMode // fosterParenting is whether new elements should be inserted according to // the foster parenting rules (section 12.2.5.3). fosterParenting bool // quirks is whether the parser is operating in "quirks mode." quirks bool // fragment is whether the parser is parsing an HTML fragment. fragment bool // context is the context element when parsing an HTML fragment // (section 12.4). context *Node } func (p *parser) top() *Node { if n := p.oe.top(); n != nil { return n } return p.doc } // Stop tags for use in popUntil. These come from section 12.2.3.2. var ( defaultScopeStopTags = map[string][]a.Atom{ "": {a.Applet, a.Caption, a.Html, a.Table, a.Td, a.Th, a.Marquee, a.Object, a.Template}, "math": {a.AnnotationXml, a.Mi, a.Mn, a.Mo, a.Ms, a.Mtext}, "svg": {a.Desc, a.ForeignObject, a.Title}, } ) type scope int const ( defaultScope scope = iota listItemScope buttonScope tableScope tableRowScope tableBodyScope selectScope ) // popUntil pops the stack of open elements at the highest element whose tag // is in matchTags, provided there is no higher element in the scope's stop // tags (as defined in section 12.2.3.2). It returns whether or not there was // such an element. If there was not, popUntil leaves the stack unchanged. // // For example, the set of stop tags for table scope is: "html", "table". If // the stack was: // ["html", "body", "font", "table", "b", "i", "u"] // then popUntil(tableScope, "font") would return false, but // popUntil(tableScope, "i") would return true and the stack would become: // ["html", "body", "font", "table", "b"] // // If an element's tag is in both the stop tags and matchTags, then the stack // will be popped and the function returns true (provided, of course, there was // no higher element in the stack that was also in the stop tags). For example, // popUntil(tableScope, "table") returns true and leaves: // ["html", "body", "font"] func (p *parser) popUntil(s scope, matchTags ...a.Atom) bool { if i := p.indexOfElementInScope(s, matchTags...); i != -1 { p.oe = p.oe[:i] return true } return false } // indexOfElementInScope returns the index in p.oe of the highest element whose // tag is in matchTags that is in scope. If no matching element is in scope, it // returns -1. func (p *parser) indexOfElementInScope(s scope, matchTags ...a.Atom) int { for i := len(p.oe) - 1; i >= 0; i-- { tagAtom := p.oe[i].DataAtom if p.oe[i].Namespace == "" { for _, t := range matchTags { if t == tagAtom { return i } } switch s { case defaultScope: // No-op. case listItemScope: if tagAtom == a.Ol || tagAtom == a.Ul { return -1 } case buttonScope: if tagAtom == a.Button { return -1 } case tableScope: if tagAtom == a.Html || tagAtom == a.Table { return -1 } case selectScope: if tagAtom != a.Optgroup && tagAtom != a.Option { return -1 } default: panic("unreachable") } } switch s { case defaultScope, listItemScope, buttonScope: for _, t := range defaultScopeStopTags[p.oe[i].Namespace] { if t == tagAtom { return -1 } } } } return -1 } // elementInScope is like popUntil, except that it doesn't modify the stack of // open elements. func (p *parser) elementInScope(s scope, matchTags ...a.Atom) bool { return p.indexOfElementInScope(s, matchTags...) != -1 } // clearStackToContext pops elements off the stack of open elements until a // scope-defined element is found. func (p *parser) clearStackToContext(s scope) { for i := len(p.oe) - 1; i >= 0; i-- { tagAtom := p.oe[i].DataAtom switch s { case tableScope: if tagAtom == a.Html || tagAtom == a.Table { p.oe = p.oe[:i+1] return } case tableRowScope: if tagAtom == a.Html || tagAtom == a.Tr { p.oe = p.oe[:i+1] return } case tableBodyScope: if tagAtom == a.Html || tagAtom == a.Tbody || tagAtom == a.Tfoot || tagAtom == a.Thead { p.oe = p.oe[:i+1] return } default: panic("unreachable") } } } // generateImpliedEndTags pops nodes off the stack of open elements as long as // the top node has a tag name of dd, dt, li, option, optgroup, p, rp, or rt. // If exceptions are specified, nodes with that name will not be popped off. func (p *parser) generateImpliedEndTags(exceptions ...string) { var i int loop: for i = len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if n.Type == ElementNode { switch n.DataAtom { case a.Dd, a.Dt, a.Li, a.Option, a.Optgroup, a.P, a.Rp, a.Rt: for _, except := range exceptions { if n.Data == except { break loop } } continue } } break } p.oe = p.oe[:i+1] } // addChild adds a child node n to the top element, and pushes n onto the stack // of open elements if it is an element node. func (p *parser) addChild(n *Node) { if p.shouldFosterParent() { p.fosterParent(n) } else { p.top().AppendChild(n) } if n.Type == ElementNode { p.oe = append(p.oe, n) } } // shouldFosterParent returns whether the next node to be added should be // foster parented. func (p *parser) shouldFosterParent() bool { if p.fosterParenting { switch p.top().DataAtom { case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr: return true } } return false } // fosterParent adds a child node according to the foster parenting rules. // Section 12.2.5.3, "foster parenting". func (p *parser) fosterParent(n *Node) { var table, parent, prev *Node var i int for i = len(p.oe) - 1; i >= 0; i-- { if p.oe[i].DataAtom == a.Table { table = p.oe[i] break } } if table == nil { // The foster parent is the html element. parent = p.oe[0] } else { parent = table.Parent } if parent == nil { parent = p.oe[i-1] } if table != nil { prev = table.PrevSibling } else { prev = parent.LastChild } if prev != nil && prev.Type == TextNode && n.Type == TextNode { prev.Data += n.Data return } parent.InsertBefore(n, table) } // addText adds text to the preceding node if it is a text node, or else it // calls addChild with a new text node. func (p *parser) addText(text string) { if text == "" { return } if p.shouldFosterParent() { p.fosterParent(&Node{ Type: TextNode, Data: text, }) return } t := p.top() if n := t.LastChild; n != nil && n.Type == TextNode { n.Data += text return } p.addChild(&Node{ Type: TextNode, Data: text, }) } // addElement adds a child element based on the current token. func (p *parser) addElement() { p.addChild(&Node{ Type: ElementNode, DataAtom: p.tok.DataAtom, Data: p.tok.Data, Attr: p.tok.Attr, }) } // Section 12.2.3.3. func (p *parser) addFormattingElement() { tagAtom, attr := p.tok.DataAtom, p.tok.Attr p.addElement() // Implement the Noah's Ark clause, but with three per family instead of two. identicalElements := 0 findIdenticalElements: for i := len(p.afe) - 1; i >= 0; i-- { n := p.afe[i] if n.Type == scopeMarkerNode { break } if n.Type != ElementNode { continue } if n.Namespace != "" { continue } if n.DataAtom != tagAtom { continue } if len(n.Attr) != len(attr) { continue } compareAttributes: for _, t0 := range n.Attr { for _, t1 := range attr { if t0.Key == t1.Key && t0.Namespace == t1.Namespace && t0.Val == t1.Val { // Found a match for this attribute, continue with the next attribute. continue compareAttributes } } // If we get here, there is no attribute that matches a. // Therefore the element is not identical to the new one. continue findIdenticalElements } identicalElements++ if identicalElements >= 3 { p.afe.remove(n) } } p.afe = append(p.afe, p.top()) } // Section 12.2.3.3. func (p *parser) clearActiveFormattingElements() { for { n := p.afe.pop() if len(p.afe) == 0 || n.Type == scopeMarkerNode { return } } } // Section 12.2.3.3. func (p *parser) reconstructActiveFormattingElements() { n := p.afe.top() if n == nil { return } if n.Type == scopeMarkerNode || p.oe.index(n) != -1 { return } i := len(p.afe) - 1 for n.Type != scopeMarkerNode && p.oe.index(n) == -1 { if i == 0 { i = -1 break } i-- n = p.afe[i] } for { i++ clone := p.afe[i].clone() p.addChild(clone) p.afe[i] = clone if i == len(p.afe)-1 { break } } } // Section 12.2.4. func (p *parser) acknowledgeSelfClosingTag() { p.hasSelfClosingToken = false } // An insertion mode (section 12.2.3.1) is the state transition function from // a particular state in the HTML5 parser's state machine. It updates the // parser's fields depending on parser.tok (where ErrorToken means EOF). // It returns whether the token was consumed. type insertionMode func(*parser) bool // setOriginalIM sets the insertion mode to return to after completing a text or // inTableText insertion mode. // Section 12.2.3.1, "using the rules for". func (p *parser) setOriginalIM() { if p.originalIM != nil { panic("html: bad parser state: originalIM was set twice") } p.originalIM = p.im } // Section 12.2.3.1, "reset the insertion mode". func (p *parser) resetInsertionMode() { for i := len(p.oe) - 1; i >= 0; i-- { n := p.oe[i] if i == 0 && p.context != nil { n = p.context } switch n.DataAtom { case a.Select: p.im = inSelectIM case a.Td, a.Th: p.im = inCellIM case a.Tr: p.im = inRowIM case a.Tbody, a.Thead, a.Tfoot: p.im = inTableBodyIM case a.Caption: p.im = inCaptionIM case a.Colgroup: p.im = inColumnGroupIM case a.Table: p.im = inTableIM case a.Head: p.im = inBodyIM case a.Body: p.im = inBodyIM case a.Frameset: p.im = inFramesetIM case a.Html: p.im = beforeHeadIM default: continue } return } p.im = inBodyIM } const whitespace = " \t\r\n\f" // Section 12.2.5.4.1. func initialIM(p *parser) bool { switch p.tok.Type { case TextToken: p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) if len(p.tok.Data) == 0 { // It was all whitespace, so ignore it. return true } case CommentToken: p.doc.AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: n, quirks := parseDoctype(p.tok.Data) p.doc.AppendChild(n) p.quirks = quirks p.im = beforeHTMLIM return true } p.quirks = true p.im = beforeHTMLIM return false } // Section 12.2.5.4.2. func beforeHTMLIM(p *parser) bool { switch p.tok.Type { case DoctypeToken: // Ignore the token. return true case TextToken: p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) if len(p.tok.Data) == 0 { // It was all whitespace, so ignore it. return true } case StartTagToken: if p.tok.DataAtom == a.Html { p.addElement() p.im = beforeHeadIM return true } case EndTagToken: switch p.tok.DataAtom { case a.Head, a.Body, a.Html, a.Br: p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) return false default: // Ignore the token. return true } case CommentToken: p.doc.AppendChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true } p.parseImpliedToken(StartTagToken, a.Html, a.Html.String()) return false } // Section 12.2.5.4.3. func beforeHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: p.tok.Data = strings.TrimLeft(p.tok.Data, whitespace) if len(p.tok.Data) == 0 { // It was all whitespace, so ignore it. return true } case StartTagToken: switch p.tok.DataAtom { case a.Head: p.addElement() p.head = p.top() p.im = inHeadIM return true case a.Html: return inBodyIM(p) } case EndTagToken: switch p.tok.DataAtom { case a.Head, a.Body, a.Html, a.Br: p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) return false default: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.parseImpliedToken(StartTagToken, a.Head, a.Head.String()) return false } // Section 12.2.5.4.4. func inHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) < len(p.tok.Data) { // Add the initial whitespace to the current node. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) if s == "" { return true } p.tok.Data = s } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta: p.addElement() p.oe.pop() p.acknowledgeSelfClosingTag() return true case a.Script, a.Title, a.Noscript, a.Noframes, a.Style: p.addElement() p.setOriginalIM() p.im = textIM return true case a.Head: // Ignore the token. return true } case EndTagToken: switch p.tok.DataAtom { case a.Head: n := p.oe.pop() if n.DataAtom != a.Head { panic("html: bad parser state: element not found, in the in-head insertion mode") } p.im = afterHeadIM return true case a.Body, a.Html, a.Br: p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) return false default: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.parseImpliedToken(EndTagToken, a.Head, a.Head.String()) return false } // Section 12.2.5.4.6. func afterHeadIM(p *parser) bool { switch p.tok.Type { case TextToken: s := strings.TrimLeft(p.tok.Data, whitespace) if len(s) < len(p.tok.Data) { // Add the initial whitespace to the current node. p.addText(p.tok.Data[:len(p.tok.Data)-len(s)]) if s == "" { return true } p.tok.Data = s } case StartTagToken: switch p.tok.DataAtom { case a.Html: return inBodyIM(p) case a.Body: p.addElement() p.framesetOK = false p.im = inBodyIM return true case a.Frameset: p.addElement() p.im = inFramesetIM return true case a.Base, a.Basefont, a.Bgsound, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title: p.oe = append(p.oe, p.head) defer p.oe.remove(p.head) return inHeadIM(p) case a.Head: // Ignore the token. return true } case EndTagToken: switch p.tok.DataAtom { case a.Body, a.Html, a.Br: // Drop down to creating an implied tag. default: // Ignore the token. return true } case CommentToken: p.addChild(&Node{ Type: CommentNode, Data: p.tok.Data, }) return true case DoctypeToken: // Ignore the token. return true } p.parseImpliedToken(StartTagToken, a.Body, a.Body.String()) p.framesetOK = true return false } // copyAttributes copies attributes of src not found on dst to dst. func copyAttributes(dst *Node, src Token) { if len(src.Attr) == 0 { return } attr := map[string]string{} for _, t := range dst.Attr { attr[t.Key] = t.Val } for _, t := range src.Attr { if _, ok := attr[t.Key]; !ok { dst.Attr = append(dst.Attr, t) attr[t.Key] = t.Val } } } // Section 12.2.5.4.7. func inBodyIM(p *parser) bool { switch p.tok.Type { case TextToken: d := p.tok.Data switch n := p.oe.top(); n.DataAtom { case a.Pre, a.Listing: if n.FirstChild == nil { // Ignore a newline at the start of a
 block.
				if d != "" && d[0] == '\r' {
					d = d[1:]
				}
				if d != "" && d[0] == '\n' {
					d = d[1:]
				}
			}
		}
		d = strings.Replace(d, "\x00", "", -1)
		if d == "" {
			return true
		}
		p.reconstructActiveFormattingElements()
		p.addText(d)
		if p.framesetOK && strings.TrimLeft(d, whitespace) != "" {
			// There were non-whitespace characters inserted.
			p.framesetOK = false
		}
	case StartTagToken:
		switch p.tok.DataAtom {
		case a.Html:
			copyAttributes(p.oe[0], p.tok)
		case a.Base, a.Basefont, a.Bgsound, a.Command, a.Link, a.Meta, a.Noframes, a.Script, a.Style, a.Title:
			return inHeadIM(p)
		case a.Body:
			if len(p.oe) >= 2 {
				body := p.oe[1]
				if body.Type == ElementNode && body.DataAtom == a.Body {
					p.framesetOK = false
					copyAttributes(body, p.tok)
				}
			}
		case a.Frameset:
			if !p.framesetOK || len(p.oe) < 2 || p.oe[1].DataAtom != a.Body {
				// Ignore the token.
				return true
			}
			body := p.oe[1]
			if body.Parent != nil {
				body.Parent.RemoveChild(body)
			}
			p.oe = p.oe[:1]
			p.addElement()
			p.im = inFramesetIM
			return true
		case a.Address, a.Article, a.Aside, a.Blockquote, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Menu, a.Nav, a.Ol, a.P, a.Section, a.Summary, a.Ul:
			p.popUntil(buttonScope, a.P)
			p.addElement()
		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
			p.popUntil(buttonScope, a.P)
			switch n := p.top(); n.DataAtom {
			case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
				p.oe.pop()
			}
			p.addElement()
		case a.Pre, a.Listing:
			p.popUntil(buttonScope, a.P)
			p.addElement()
			// The newline, if any, will be dealt with by the TextToken case.
			p.framesetOK = false
		case a.Form:
			if p.form == nil {
				p.popUntil(buttonScope, a.P)
				p.addElement()
				p.form = p.top()
			}
		case a.Li:
			p.framesetOK = false
			for i := len(p.oe) - 1; i >= 0; i-- {
				node := p.oe[i]
				switch node.DataAtom {
				case a.Li:
					p.oe = p.oe[:i]
				case a.Address, a.Div, a.P:
					continue
				default:
					if !isSpecialElement(node) {
						continue
					}
				}
				break
			}
			p.popUntil(buttonScope, a.P)
			p.addElement()
		case a.Dd, a.Dt:
			p.framesetOK = false
			for i := len(p.oe) - 1; i >= 0; i-- {
				node := p.oe[i]
				switch node.DataAtom {
				case a.Dd, a.Dt:
					p.oe = p.oe[:i]
				case a.Address, a.Div, a.P:
					continue
				default:
					if !isSpecialElement(node) {
						continue
					}
				}
				break
			}
			p.popUntil(buttonScope, a.P)
			p.addElement()
		case a.Plaintext:
			p.popUntil(buttonScope, a.P)
			p.addElement()
		case a.Button:
			p.popUntil(defaultScope, a.Button)
			p.reconstructActiveFormattingElements()
			p.addElement()
			p.framesetOK = false
		case a.A:
			for i := len(p.afe) - 1; i >= 0 && p.afe[i].Type != scopeMarkerNode; i-- {
				if n := p.afe[i]; n.Type == ElementNode && n.DataAtom == a.A {
					p.inBodyEndTagFormatting(a.A)
					p.oe.remove(n)
					p.afe.remove(n)
					break
				}
			}
			p.reconstructActiveFormattingElements()
			p.addFormattingElement()
		case a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
			p.reconstructActiveFormattingElements()
			p.addFormattingElement()
		case a.Nobr:
			p.reconstructActiveFormattingElements()
			if p.elementInScope(defaultScope, a.Nobr) {
				p.inBodyEndTagFormatting(a.Nobr)
				p.reconstructActiveFormattingElements()
			}
			p.addFormattingElement()
		case a.Applet, a.Marquee, a.Object:
			p.reconstructActiveFormattingElements()
			p.addElement()
			p.afe = append(p.afe, &scopeMarker)
			p.framesetOK = false
		case a.Table:
			if !p.quirks {
				p.popUntil(buttonScope, a.P)
			}
			p.addElement()
			p.framesetOK = false
			p.im = inTableIM
			return true
		case a.Area, a.Br, a.Embed, a.Img, a.Input, a.Keygen, a.Wbr:
			p.reconstructActiveFormattingElements()
			p.addElement()
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
			if p.tok.DataAtom == a.Input {
				for _, t := range p.tok.Attr {
					if t.Key == "type" {
						if strings.ToLower(t.Val) == "hidden" {
							// Skip setting framesetOK = false
							return true
						}
					}
				}
			}
			p.framesetOK = false
		case a.Param, a.Source, a.Track:
			p.addElement()
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
		case a.Hr:
			p.popUntil(buttonScope, a.P)
			p.addElement()
			p.oe.pop()
			p.acknowledgeSelfClosingTag()
			p.framesetOK = false
		case a.Image:
			p.tok.DataAtom = a.Img
			p.tok.Data = a.Img.String()
			return false
		case a.Isindex:
			if p.form != nil {
				// Ignore the token.
				return true
			}
			action := ""
			prompt := "This is a searchable index. Enter search keywords: "
			attr := []Attribute{{Key: "name", Val: "isindex"}}
			for _, t := range p.tok.Attr {
				switch t.Key {
				case "action":
					action = t.Val
				case "name":
					// Ignore the attribute.
				case "prompt":
					prompt = t.Val
				default:
					attr = append(attr, t)
				}
			}
			p.acknowledgeSelfClosingTag()
			p.popUntil(buttonScope, a.P)
			p.parseImpliedToken(StartTagToken, a.Form, a.Form.String())
			if action != "" {
				p.form.Attr = []Attribute{{Key: "action", Val: action}}
			}
			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
			p.parseImpliedToken(StartTagToken, a.Label, a.Label.String())
			p.addText(prompt)
			p.addChild(&Node{
				Type:     ElementNode,
				DataAtom: a.Input,
				Data:     a.Input.String(),
				Attr:     attr,
			})
			p.oe.pop()
			p.parseImpliedToken(EndTagToken, a.Label, a.Label.String())
			p.parseImpliedToken(StartTagToken, a.Hr, a.Hr.String())
			p.parseImpliedToken(EndTagToken, a.Form, a.Form.String())
		case a.Textarea:
			p.addElement()
			p.setOriginalIM()
			p.framesetOK = false
			p.im = textIM
		case a.Xmp:
			p.popUntil(buttonScope, a.P)
			p.reconstructActiveFormattingElements()
			p.framesetOK = false
			p.addElement()
			p.setOriginalIM()
			p.im = textIM
		case a.Iframe:
			p.framesetOK = false
			p.addElement()
			p.setOriginalIM()
			p.im = textIM
		case a.Noembed, a.Noscript:
			p.addElement()
			p.setOriginalIM()
			p.im = textIM
		case a.Select:
			p.reconstructActiveFormattingElements()
			p.addElement()
			p.framesetOK = false
			p.im = inSelectIM
			return true
		case a.Optgroup, a.Option:
			if p.top().DataAtom == a.Option {
				p.oe.pop()
			}
			p.reconstructActiveFormattingElements()
			p.addElement()
		case a.Rp, a.Rt:
			if p.elementInScope(defaultScope, a.Ruby) {
				p.generateImpliedEndTags()
			}
			p.addElement()
		case a.Math, a.Svg:
			p.reconstructActiveFormattingElements()
			if p.tok.DataAtom == a.Math {
				adjustAttributeNames(p.tok.Attr, mathMLAttributeAdjustments)
			} else {
				adjustAttributeNames(p.tok.Attr, svgAttributeAdjustments)
			}
			adjustForeignAttributes(p.tok.Attr)
			p.addElement()
			p.top().Namespace = p.tok.Data
			if p.hasSelfClosingToken {
				p.oe.pop()
				p.acknowledgeSelfClosingTag()
			}
			return true
		case a.Caption, a.Col, a.Colgroup, a.Frame, a.Head, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr:
			// Ignore the token.
		default:
			p.reconstructActiveFormattingElements()
			p.addElement()
		}
	case EndTagToken:
		switch p.tok.DataAtom {
		case a.Body:
			if p.elementInScope(defaultScope, a.Body) {
				p.im = afterBodyIM
			}
		case a.Html:
			if p.elementInScope(defaultScope, a.Body) {
				p.parseImpliedToken(EndTagToken, a.Body, a.Body.String())
				return false
			}
			return true
		case a.Address, a.Article, a.Aside, a.Blockquote, a.Button, a.Center, a.Details, a.Dir, a.Div, a.Dl, a.Fieldset, a.Figcaption, a.Figure, a.Footer, a.Header, a.Hgroup, a.Listing, a.Menu, a.Nav, a.Ol, a.Pre, a.Section, a.Summary, a.Ul:
			p.popUntil(defaultScope, p.tok.DataAtom)
		case a.Form:
			node := p.form
			p.form = nil
			i := p.indexOfElementInScope(defaultScope, a.Form)
			if node == nil || i == -1 || p.oe[i] != node {
				// Ignore the token.
				return true
			}
			p.generateImpliedEndTags()
			p.oe.remove(node)
		case a.P:
			if !p.elementInScope(buttonScope, a.P) {
				p.parseImpliedToken(StartTagToken, a.P, a.P.String())
			}
			p.popUntil(buttonScope, a.P)
		case a.Li:
			p.popUntil(listItemScope, a.Li)
		case a.Dd, a.Dt:
			p.popUntil(defaultScope, p.tok.DataAtom)
		case a.H1, a.H2, a.H3, a.H4, a.H5, a.H6:
			p.popUntil(defaultScope, a.H1, a.H2, a.H3, a.H4, a.H5, a.H6)
		case a.A, a.B, a.Big, a.Code, a.Em, a.Font, a.I, a.Nobr, a.S, a.Small, a.Strike, a.Strong, a.Tt, a.U:
			p.inBodyEndTagFormatting(p.tok.DataAtom)
		case a.Applet, a.Marquee, a.Object:
			if p.popUntil(defaultScope, p.tok.DataAtom) {
				p.clearActiveFormattingElements()
			}
		case a.Br:
			p.tok.Type = StartTagToken
			return false
		default:
			p.inBodyEndTagOther(p.tok.DataAtom)
		}
	case CommentToken:
		p.addChild(&Node{
			Type: CommentNode,
			Data: p.tok.Data,
		})
	}

	return true
}

func (p *parser) inBodyEndTagFormatting(tagAtom a.Atom) {
	// This is the "adoption agency" algorithm, described at
	// https://html.spec.whatwg.org/multipage/syntax.html#adoptionAgency

	// TODO: this is a fairly literal line-by-line translation of that algorithm.
	// Once the code successfully parses the comprehensive test suite, we should
	// refactor this code to be more idiomatic.

	// Steps 1-4. The outer loop.
	for i := 0; i < 8; i++ {
		// Step 5. Find the formatting element.
		var formattingElement *Node
		for j := len(p.afe) - 1; j >= 0; j-- {
			if p.afe[j].Type == scopeMarkerNode {
				break
			}
			if p.afe[j].DataAtom == tagAtom {
				formattingElement = p.afe[j]
				break
			}
		}
		if formattingElement == nil {
			p.inBodyEndTagOther(tagAtom)
			return
		}
		feIndex := p.oe.index(formattingElement)
		if feIndex == -1 {
			p.afe.remove(formattingElement)
			return
		}
		if !p.elementInScope(defaultScope, tagAtom) {
			// Ignore the tag.
			return
		}

		// Steps 9-10. Find the furthest block.
		var furthestBlock *Node
		for _, e := range p.oe[feIndex:] {
			if isSpecialElement(e) {
				furthestBlock = e
				break
			}
		}
		if furthestBlock == nil {
			e := p.oe.pop()
			for e != formattingElement {
				e = p.oe.pop()
			}
			p.afe.remove(e)
			return
		}

		// Steps 11-12. Find the common ancestor and bookmark node.
		commonAncestor := p.oe[feIndex-1]
		bookmark := p.afe.index(formattingElement)

		// Step 13. The inner loop. Find the lastNode to reparent.
		lastNode := furthestBlock
		node := furthestBlock
		x := p.oe.index(node)
		// Steps 13.1-13.2
		for j := 0; j < 3; j++ {
			// Step 13.3.
			x--
			node = p.oe[x]
			// Step 13.4 - 13.5.
			if p.afe.index(node) == -1 {
				p.oe.remove(node)
				continue
			}
			// Step 13.6.
			if node == formattingElement {
				break
			}
			// Step 13.7.
			clone := node.clone()
			p.afe[p.afe.index(node)] = clone
			p.oe[p.oe.index(node)] = clone
			node = clone
			// Step 13.8.
			if lastNode == furthestBlock {
				bookmark = p.afe.index(node) + 1
			}
			// Step 13.9.
			if lastNode.Parent != nil {
				lastNode.Parent.RemoveChild(lastNode)
			}
			node.AppendChild(lastNode)
			// Step 13.10.
			lastNode = node
		}

		// Step 14. Reparent lastNode to the common ancestor,
		// or for misnested table nodes, to the foster parent.
		if lastNode.Parent != nil {
			lastNode.Parent.RemoveChild(lastNode)
		}
		switch commonAncestor.DataAtom {
		case a.Table, a.Tbody, a.Tfoot, a.Thead, a.Tr:
			p.fosterParent(lastNode)
		default:
			commonAncestor.AppendChild(lastNode)
		}

		// Steps 15-17. Reparent nodes from the furthest block's children
		// to a clone of the formatting element.
		clone := formattingElement.clone()
		reparentChildren(clone, furthestBlock)
		furthestBlock.AppendChild(clone)

		// Step 18. Fix up the list of active formatting elements.
		if oldLoc := p.afe.index(formattingElement); oldLoc != -1 && oldLoc < bookmark {
			// Move the bookmark with the rest of the list.
			bookmark--
		}
		p.afe.remove(formattingElement)
		p.afe.insert(bookmark, clone)

		// Step 19. Fix up the stack of open elements.
		p.oe.remove(formattingElement)
		p.oe.insert(p.oe.index(furthestBlock)+1, clone)
	}
}

// inBodyEndTagOther performs the "any other end tag" algorithm for inBodyIM.
// "Any other end tag" handling from 12.2.5.5 The rules for parsing tokens in foreign content
// https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inforeign
func (p *parser) inBodyEndTagOther(tagAtom a.Atom) {
	for i := len(p.oe) - 1; i >= 0; i-- {
		if p.oe[i].DataAtom == tagAtom {
			p.oe = p.oe[:i]
			break
		}
		if isSpecialElement(p.oe[i]) {
			break
		}
	}
}

// Section 12.2.5.4.8.
func textIM(p *parser) bool {
	switch p.tok.Type {
	case ErrorToken:
		p.oe.pop()
	case TextToken:
		d := p.tok.Data
		if n := p.oe.top(); n.DataAtom == a.Textarea && n.FirstChild == nil {
			// Ignore a newline at the start of a ",
		"",
	},
	{
		"title with tag and entity",
		"<b>K&R C</b>",
		"$<b>K&R C</b>$",
	},
	// DOCTYPE tests.
	{
		"Proper DOCTYPE",
		"",
		"",
	},
	{
		"DOCTYPE with no space",
		"",
		"",
	},
	{
		"DOCTYPE with two spaces",
		"",
		"",
	},
	{
		"looks like DOCTYPE but isn't",
		"",
		"",
	},
	{
		"DOCTYPE at EOF",
		"",
	},
	// XML processing instructions.
	{
		"XML processing instruction",
		"",
		"",
	},
	// Comments.
	{
		"comment0",
		"abcdef",
		"abc$$$$def",
	},
	{
		"comment1",
		"az",
		"a$$z",
	},
	{
		"comment2",
		"az",
		"a$$z",
	},
	{
		"comment3",
		"az",
		"a$$z",
	},
	{
		"comment4",
		"az",
		"a$$z",
	},
	{
		"comment5",
		"az",
		"a$$z",
	},
	{
		"comment6",
		"az",
		"a$$z",
	},
	{
		"comment7",
		"a",
	},
	{
		"comment8",
		"a",
	},
	{
		"comment9",
		"a",
	},
	{
		"comment10",
		"a",
	},
	{
		"comment11",
		"a",
	},
	{
		"comment12",
		"a",
	},
	{
		"comment13",
		"az",
		"a$$z",
	},
	// An attribute with a backslash.
	{
		"backslash",
		`

`, `

`, }, // Entities, tag name and attribute key lower-casing, and whitespace // normalization within a tag. { "tricky", "

te<&;xt

", `

$$te<&;xt$$

`, }, // A nonexistent entity. Tokenizing and converting back to a string should // escape the "&" to become "&". { "noSuchEntity", `<&alsoDoesntExist;&`, `$<&alsoDoesntExist;&`, }, { "entity without semicolon", `¬it;∉`, `¬it;∉$`, }, { "entity with digits", "½", "½", }, // Attribute tests: // http://dev.w3.org/html5/pf-summary/Overview.html#attributes { "Empty attribute", ``, ``, }, { "Empty attribute, whitespace", ``, ``, }, { "Unquoted attribute value", ``, ``, }, { "Unquoted attribute value, spaces", ``, ``, }, { "Unquoted attribute value, trailing space", ``, ``, }, { "Single-quoted attribute value", ``, ``, }, { "Single-quoted attribute value, trailing space", ``, ``, }, { "Double-quoted attribute value", ``, ``, }, { "Attribute name characters", ``, ``, }, { "Mixed attributes", `a

z`, `a$

$z`, }, { "Attributes with a solitary single quote", `

`, `

$

`, }, } func TestTokenizer(t *testing.T) { loop: for _, tt := range tokenTests { z := NewTokenizer(strings.NewReader(tt.html)) if tt.golden != "" { for i, s := range strings.Split(tt.golden, "$") { if z.Next() == ErrorToken { t.Errorf("%s token %d: want %q got error %v", tt.desc, i, s, z.Err()) continue loop } actual := z.Token().String() if s != actual { t.Errorf("%s token %d: want %q got %q", tt.desc, i, s, actual) continue loop } } } z.Next() if z.Err() != io.EOF { t.Errorf("%s: want EOF got %q", tt.desc, z.Err()) } } } func TestMaxBuffer(t *testing.T) { // Exceeding the maximum buffer size generates ErrBufferExceeded. z := NewTokenizer(strings.NewReader("<" + strings.Repeat("t", 10))) z.SetMaxBuf(5) tt := z.Next() if got, want := tt, ErrorToken; got != want { t.Fatalf("token type: got: %v want: %v", got, want) } if got, want := z.Err(), ErrBufferExceeded; got != want { t.Errorf("error type: got: %v want: %v", got, want) } if got, want := string(z.Raw()), " 0 { result.Write(z.Text()) } case StartTagToken, EndTagToken: tn, _ := z.TagName() if len(tn) == 1 && tn[0] == 'a' { if tt == StartTagToken { depth++ } else { depth-- } } } } u := "14567" v := string(result.Bytes()) if u != v { t.Errorf("TestBufAPI: want %q got %q", u, v) } } func TestConvertNewlines(t *testing.T) { testCases := map[string]string{ "Mac\rDOS\r\nUnix\n": "Mac\nDOS\nUnix\n", "Unix\nMac\rDOS\r\n": "Unix\nMac\nDOS\n", "DOS\r\nDOS\r\nDOS\r\n": "DOS\nDOS\nDOS\n", "": "", "\n": "\n", "\n\r": "\n\n", "\r": "\n", "\r\n": "\n", "\r\n\n": "\n\n", "\r\n\r": "\n\n", "\r\n\r\n": "\n\n", "\r\r": "\n\n", "\r\r\n": "\n\n", "\r\r\n\n": "\n\n\n", "\r\r\r\n": "\n\n\n", "\r \n": "\n \n", "xyz": "xyz", } for in, want := range testCases { if got := string(convertNewlines([]byte(in))); got != want { t.Errorf("input %q: got %q, want %q", in, got, want) } } } func TestReaderEdgeCases(t *testing.T) { const s = "

An io.Reader can return (0, nil) or (n, io.EOF).

" testCases := []io.Reader{ &zeroOneByteReader{s: s}, &eofStringsReader{s: s}, &stuckReader{}, } for i, tc := range testCases { got := []TokenType{} z := NewTokenizer(tc) for { tt := z.Next() if tt == ErrorToken { break } got = append(got, tt) } if err := z.Err(); err != nil && err != io.EOF { if err != io.ErrNoProgress { t.Errorf("i=%d: %v", i, err) } continue } want := []TokenType{ StartTagToken, TextToken, EndTagToken, } if !reflect.DeepEqual(got, want) { t.Errorf("i=%d: got %v, want %v", i, got, want) continue } } } // zeroOneByteReader is like a strings.Reader that alternates between // returning 0 bytes and 1 byte at a time. type zeroOneByteReader struct { s string n int } func (r *zeroOneByteReader) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } if len(r.s) == 0 { return 0, io.EOF } r.n++ if r.n%2 != 0 { return 0, nil } p[0], r.s = r.s[0], r.s[1:] return 1, nil } // eofStringsReader is like a strings.Reader but can return an (n, err) where // n > 0 && err != nil. type eofStringsReader struct { s string } func (r *eofStringsReader) Read(p []byte) (int, error) { n := copy(p, r.s) r.s = r.s[n:] if r.s != "" { return n, nil } return n, io.EOF } // stuckReader is an io.Reader that always returns no data and no error. type stuckReader struct{} func (*stuckReader) Read(p []byte) (int, error) { return 0, nil } const ( rawLevel = iota lowLevel highLevel ) func benchmarkTokenizer(b *testing.B, level int) { buf, err := ioutil.ReadFile("testdata/go1.html") if err != nil { b.Fatalf("could not read testdata/go1.html: %v", err) } b.SetBytes(int64(len(buf))) runtime.GC() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { z := NewTokenizer(bytes.NewBuffer(buf)) for { tt := z.Next() if tt == ErrorToken { if err := z.Err(); err != nil && err != io.EOF { b.Fatalf("tokenizer error: %v", err) } break } switch level { case rawLevel: // Calling z.Raw just returns the raw bytes of the token. It does // not unescape < to <, or lower-case tag names and attribute keys. z.Raw() case lowLevel: // Caling z.Text, z.TagName and z.TagAttr returns []byte values // whose contents may change on the next call to z.Next. switch tt { case TextToken, CommentToken, DoctypeToken: z.Text() case StartTagToken, SelfClosingTagToken: _, more := z.TagName() for more { _, _, more = z.TagAttr() } case EndTagToken: z.TagName() } case highLevel: // Calling z.Token converts []byte values to strings whose validity // extend beyond the next call to z.Next. z.Token() } } } } func BenchmarkRawLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, rawLevel) } func BenchmarkLowLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, lowLevel) } func BenchmarkHighLevelTokenizer(b *testing.B) { benchmarkTokenizer(b, highLevel) } ================================================ FILE: vendor/golang.org/x/net/http2/.gitignore ================================================ *~ h2i/h2i ================================================ FILE: vendor/golang.org/x/net/http2/Dockerfile ================================================ # # This Dockerfile builds a recent curl with HTTP/2 client support, using # a recent nghttp2 build. # # See the Makefile for how to tag it. If Docker and that image is found, the # Go tests use this curl binary for integration tests. # FROM ubuntu:trusty RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y git-core build-essential wget RUN apt-get install -y --no-install-recommends \ autotools-dev libtool pkg-config zlib1g-dev \ libcunit1-dev libssl-dev libxml2-dev libevent-dev \ automake autoconf # Note: setting NGHTTP2_VER before the git clone, so an old git clone isn't cached: ENV NGHTTP2_VER af24f8394e43f4 RUN cd /root && git clone https://github.com/tatsuhiro-t/nghttp2.git WORKDIR /root/nghttp2 RUN git reset --hard $NGHTTP2_VER RUN autoreconf -i RUN automake RUN autoconf RUN ./configure RUN make RUN make install WORKDIR /root RUN wget http://curl.haxx.se/download/curl-7.40.0.tar.gz RUN tar -zxvf curl-7.40.0.tar.gz WORKDIR /root/curl-7.40.0 RUN ./configure --with-ssl --with-nghttp2=/usr/local RUN make RUN make install RUN ldconfig CMD ["-h"] ENTRYPOINT ["/usr/local/bin/curl"] ================================================ FILE: vendor/golang.org/x/net/http2/Makefile ================================================ curlimage: docker build -t gohttp2/curl . ================================================ FILE: vendor/golang.org/x/net/http2/README ================================================ 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://github.com/golang/go/issues/new?title=x/net/http2:+ ================================================ FILE: vendor/golang.org/x/net/http2/buffer.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "errors" ) // buffer is an io.ReadWriteCloser backed by a fixed size buffer. // It never allocates, but moves old data as new data is written. type buffer struct { buf []byte r, w int closed bool err error // err to return to reader } var ( errReadEmpty = errors.New("read from empty buffer") errWriteClosed = errors.New("write on closed buffer") errWriteFull = errors.New("write on full buffer") ) // Read copies bytes from the buffer into p. // It is an error to read when no data is available. func (b *buffer) Read(p []byte) (n int, err error) { n = copy(p, b.buf[b.r:b.w]) b.r += n if b.closed && b.r == b.w { err = b.err } else if b.r == b.w && n == 0 { err = errReadEmpty } return n, err } // Len returns the number of bytes of the unread portion of the buffer. func (b *buffer) Len() int { return b.w - b.r } // Write copies bytes from p into the buffer. // It is an error to write more data than the buffer can hold. func (b *buffer) Write(p []byte) (n int, err error) { if b.closed { return 0, errWriteClosed } // Slide existing data to beginning. if b.r > 0 && len(p) > len(b.buf)-b.w { copy(b.buf, b.buf[b.r:b.w]) b.w -= b.r b.r = 0 } // Write new data. n = copy(b.buf[b.w:], p) b.w += n if n < len(p) { err = errWriteFull } return n, err } // Close marks the buffer as closed. Future calls to Write will // return an error. Future calls to Read, once the buffer is // empty, will return err. func (b *buffer) Close(err error) { if !b.closed { b.closed = true b.err = err } } ================================================ FILE: vendor/golang.org/x/net/http2/buffer_test.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "io" "reflect" "testing" ) var bufferReadTests = []struct { buf buffer read, wn int werr error wp []byte wbuf buffer }{ { buffer{[]byte{'a', 0}, 0, 1, false, nil}, 5, 1, nil, []byte{'a'}, buffer{[]byte{'a', 0}, 1, 1, false, nil}, }, { buffer{[]byte{'a', 0}, 0, 1, true, io.EOF}, 5, 1, io.EOF, []byte{'a'}, buffer{[]byte{'a', 0}, 1, 1, true, io.EOF}, }, { buffer{[]byte{0, 'a'}, 1, 2, false, nil}, 5, 1, nil, []byte{'a'}, buffer{[]byte{0, 'a'}, 2, 2, false, nil}, }, { buffer{[]byte{0, 'a'}, 1, 2, true, io.EOF}, 5, 1, io.EOF, []byte{'a'}, buffer{[]byte{0, 'a'}, 2, 2, true, io.EOF}, }, { buffer{[]byte{}, 0, 0, false, nil}, 5, 0, errReadEmpty, []byte{}, buffer{[]byte{}, 0, 0, false, nil}, }, { buffer{[]byte{}, 0, 0, true, io.EOF}, 5, 0, io.EOF, []byte{}, buffer{[]byte{}, 0, 0, true, io.EOF}, }, } func TestBufferRead(t *testing.T) { for i, tt := range bufferReadTests { read := make([]byte, tt.read) n, err := tt.buf.Read(read) if n != tt.wn { t.Errorf("#%d: wn = %d want %d", i, n, tt.wn) continue } if err != tt.werr { t.Errorf("#%d: werr = %v want %v", i, err, tt.werr) continue } read = read[:n] if !reflect.DeepEqual(read, tt.wp) { t.Errorf("#%d: read = %+v want %+v", i, read, tt.wp) } if !reflect.DeepEqual(tt.buf, tt.wbuf) { t.Errorf("#%d: buf = %+v want %+v", i, tt.buf, tt.wbuf) } } } var bufferWriteTests = []struct { buf buffer write, wn int werr error wbuf buffer }{ { buf: buffer{ buf: []byte{}, }, wbuf: buffer{ buf: []byte{}, }, }, { buf: buffer{ buf: []byte{1, 'a'}, }, write: 1, wn: 1, wbuf: buffer{ buf: []byte{0, 'a'}, w: 1, }, }, { buf: buffer{ buf: []byte{'a', 1}, r: 1, w: 1, }, write: 2, wn: 2, wbuf: buffer{ buf: []byte{0, 0}, w: 2, }, }, { buf: buffer{ buf: []byte{}, r: 1, closed: true, }, write: 5, werr: errWriteClosed, wbuf: buffer{ buf: []byte{}, r: 1, closed: true, }, }, { buf: buffer{ buf: []byte{}, }, write: 5, werr: errWriteFull, wbuf: buffer{ buf: []byte{}, }, }, } func TestBufferWrite(t *testing.T) { for i, tt := range bufferWriteTests { n, err := tt.buf.Write(make([]byte, tt.write)) if n != tt.wn { t.Errorf("#%d: wrote %d bytes; want %d", i, n, tt.wn) continue } if err != tt.werr { t.Errorf("#%d: error = %v; want %v", i, err, tt.werr) continue } if !reflect.DeepEqual(tt.buf, tt.wbuf) { t.Errorf("#%d: buf = %+v; want %+v", i, tt.buf, tt.wbuf) } } } ================================================ FILE: vendor/golang.org/x/net/http2/errors.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import "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 } func (e StreamError) Error() string { 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" } ================================================ FILE: vendor/golang.org/x/net/http2/errors_test.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import "testing" func TestErrCodeString(t *testing.T) { tests := []struct { err ErrCode want string }{ {ErrCodeProtocol, "PROTOCOL_ERROR"}, {0xd, "HTTP_1_1_REQUIRED"}, {0xf, "unknown error code 0xf"}, } for i, tt := range tests { got := tt.err.String() if got != tt.want { t.Errorf("%d. Error = %q; want %q", i, got, tt.want) } } } ================================================ FILE: vendor/golang.org/x/net/http2/flow.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE // 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 } ================================================ FILE: vendor/golang.org/x/net/http2/flow_test.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import "testing" func TestFlow(t *testing.T) { var st flow var conn flow st.add(3) conn.add(2) if got, want := st.available(), int32(3); got != want { t.Errorf("available = %d; want %d", got, want) } st.setConnFlow(&conn) if got, want := st.available(), int32(2); got != want { t.Errorf("after parent setup, available = %d; want %d", got, want) } st.take(2) if got, want := conn.available(), int32(0); got != want { t.Errorf("after taking 2, conn = %d; want %d", got, want) } if got, want := st.available(), int32(0); got != want { t.Errorf("after taking 2, stream = %d; want %d", got, want) } } func TestFlowAdd(t *testing.T) { var f flow if !f.add(1) { t.Fatal("failed to add 1") } if !f.add(-1) { t.Fatal("failed to add -1") } if got, want := f.available(), int32(0); got != want { t.Fatalf("size = %d; want %d", got, want) } if !f.add(1<<31 - 1) { t.Fatal("failed to add 2^31-1") } if got, want := f.available(), int32(1<<31-1); got != want { t.Fatalf("size = %d; want %d", got, want) } if f.add(1) { t.Fatal("adding 1 to max shouldn't be allowed") } } ================================================ FILE: vendor/golang.org/x/net/http2/frame.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "bytes" "encoding/binary" "errors" "fmt" "io" "sync" ) 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(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 ") 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< 1 { buf.WriteByte('|') } name := flagName[h.Type][Flags(1<>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)) n, err := f.w.Write(f.wbuf) if err == nil && n != len(f.wbuf) { err = io.ErrShortWrite } return err } 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 ) // 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, } 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 } // 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") // 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. func (fr *Framer) ReadFrame() (Frame, error) { 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)(fh, payload) if err != nil { return nil, err } fr.lastFrame = f return f, 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(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, ConnectionError(ErrCodeProtocol) } f := &DataFrame{ 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, ConnectionError(ErrCodeProtocol) } f.data = payload[:len(payload)-int(padSize)] return f, nil } var errStreamID = errors.New("invalid streamid") 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 to not call other Write methods concurrently. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error { // TODO: ignoring padding for now. will add when somebody cares. if !validStreamID(streamID) && !f.AllowIllegalWrites { return errStreamID } var flags Flags if endStream { flags |= FlagDataEndStream } f.startWrite(FrameData, flags, streamID) f.wbuf = append(f.wbuf, data...) 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(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() } // WriteSettings 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 parsePingFrame(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(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(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 } func parseWindowUpdateFrame(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(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, ConnectionError(ErrCodeProtocol) } 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 !validStreamID(v) && !f.AllowIllegalWrites { return errors.New("invalid dependent stream id") } 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(fh FrameHeader, payload []byte) (Frame, error) { if fh.StreamID == 0 { return nil, ConnectionError(ErrCodeProtocol) } if len(payload) != 5 { return nil, ConnectionError(ErrCodeFrameSize) } 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 } 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(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(fh FrameHeader, p []byte) (Frame, error) { return &ContinuationFrame{fh, p}, nil } func (f *ContinuationFrame) StreamEnded() bool { return f.FrameHeader.Flags.Has(FlagDataEndStream) } 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(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 } ================================================ FILE: vendor/golang.org/x/net/http2/frame_test.go ================================================ // 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" "reflect" "strings" "testing" "unsafe" ) func testFramer() (*Framer, *bytes.Buffer) { buf := new(bytes.Buffer) return NewFramer(buf, buf), buf } func TestFrameSizes(t *testing.T) { // Catch people rearranging the FrameHeader fields. if got, want := int(unsafe.Sizeof(FrameHeader{})), 12; got != want { t.Errorf("FrameHeader size = %d; want %d", got, want) } } func TestFrameTypeString(t *testing.T) { tests := []struct { ft FrameType want string }{ {FrameData, "DATA"}, {FramePing, "PING"}, {FrameGoAway, "GOAWAY"}, {0xf, "UNKNOWN_FRAME_TYPE_15"}, } for i, tt := range tests { got := tt.ft.String() if got != tt.want { t.Errorf("%d. String(FrameType %d) = %q; want %q", i, int(tt.ft), got, tt.want) } } } func TestWriteRST(t *testing.T) { fr, buf := testFramer() var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 var errCode uint32 = 7<<24 + 6<<16 + 5<<8 + 4 fr.WriteRSTStream(streamID, ErrCode(errCode)) const wantEnc = "\x00\x00\x04\x03\x00\x01\x02\x03\x04\x07\x06\x05\x04" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &RSTStreamFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x3, Flags: 0x0, Length: 0x4, StreamID: 0x1020304, }, ErrCode: 0x7060504, } if !reflect.DeepEqual(f, want) { t.Errorf("parsed back %#v; want %#v", f, want) } } func TestWriteData(t *testing.T) { fr, buf := testFramer() var streamID uint32 = 1<<24 + 2<<16 + 3<<8 + 4 data := []byte("ABC") fr.WriteData(streamID, true, data) const wantEnc = "\x00\x00\x03\x00\x01\x01\x02\x03\x04ABC" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } df, ok := f.(*DataFrame) if !ok { t.Fatalf("got %T; want *DataFrame", f) } if !bytes.Equal(df.Data(), data) { t.Errorf("got %q; want %q", df.Data(), data) } if f.Header().Flags&1 == 0 { t.Errorf("didn't see END_STREAM flag") } } func TestWriteHeaders(t *testing.T) { tests := []struct { name string p HeadersFrameParam wantEnc string wantFrame *HeadersFrame }{ { "basic", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), Priority: PriorityParam{}, }, "\x00\x00\x03\x01\x00\x00\x00\x00*abc", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Length: uint32(len("abc")), }, Priority: PriorityParam{}, headerFragBuf: []byte("abc"), }, }, { "basic + end flags", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, Priority: PriorityParam{}, }, "\x00\x00\x03\x01\x05\x00\x00\x00*abc", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders, Length: uint32(len("abc")), }, Priority: PriorityParam{}, headerFragBuf: []byte("abc"), }, }, { "with padding", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, PadLength: 5, Priority: PriorityParam{}, }, "\x00\x00\t\x01\r\x00\x00\x00*\x05abc\x00\x00\x00\x00\x00", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded, Length: uint32(1 + len("abc") + 5), // pad length + contents + padding }, Priority: PriorityParam{}, headerFragBuf: []byte("abc"), }, }, { "with priority", HeadersFrameParam{ StreamID: 42, BlockFragment: []byte("abc"), EndStream: true, EndHeaders: true, PadLength: 2, Priority: PriorityParam{ StreamDep: 15, Exclusive: true, Weight: 127, }, }, "\x00\x00\v\x01-\x00\x00\x00*\x02\x80\x00\x00\x0f\u007fabc\x00\x00", &HeadersFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: 42, Type: FrameHeaders, Flags: FlagHeadersEndStream | FlagHeadersEndHeaders | FlagHeadersPadded | FlagHeadersPriority, Length: uint32(1 + 5 + len("abc") + 2), // pad length + priority + contents + padding }, Priority: PriorityParam{ StreamDep: 15, Exclusive: true, Weight: 127, }, headerFragBuf: []byte("abc"), }, }, } for _, tt := range tests { fr, buf := testFramer() if err := fr.WriteHeaders(tt.p); err != nil { t.Errorf("test %q: %v", tt.name, err) continue } if buf.String() != tt.wantEnc { t.Errorf("test %q: encoded %q; want %q", tt.name, buf.Bytes(), tt.wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) continue } if !reflect.DeepEqual(f, tt.wantFrame) { t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) } } } func TestWriteContinuation(t *testing.T) { const streamID = 42 tests := []struct { name string end bool frag []byte wantFrame *ContinuationFrame }{ { "not end", false, []byte("abc"), &ContinuationFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: streamID, Type: FrameContinuation, Length: uint32(len("abc")), }, headerFragBuf: []byte("abc"), }, }, { "end", true, []byte("def"), &ContinuationFrame{ FrameHeader: FrameHeader{ valid: true, StreamID: streamID, Type: FrameContinuation, Flags: FlagContinuationEndHeaders, Length: uint32(len("def")), }, headerFragBuf: []byte("def"), }, }, } for _, tt := range tests { fr, _ := testFramer() if err := fr.WriteContinuation(streamID, tt.end, tt.frag); err != nil { t.Errorf("test %q: %v", tt.name, err) continue } f, err := fr.ReadFrame() if err != nil { t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) continue } if !reflect.DeepEqual(f, tt.wantFrame) { t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) } } } func TestWritePriority(t *testing.T) { const streamID = 42 tests := []struct { name string priority PriorityParam wantFrame *PriorityFrame }{ { "not exclusive", PriorityParam{ StreamDep: 2, Exclusive: false, Weight: 127, }, &PriorityFrame{ FrameHeader{ valid: true, StreamID: streamID, Type: FramePriority, Length: 5, }, PriorityParam{ StreamDep: 2, Exclusive: false, Weight: 127, }, }, }, { "exclusive", PriorityParam{ StreamDep: 3, Exclusive: true, Weight: 77, }, &PriorityFrame{ FrameHeader{ valid: true, StreamID: streamID, Type: FramePriority, Length: 5, }, PriorityParam{ StreamDep: 3, Exclusive: true, Weight: 77, }, }, }, } for _, tt := range tests { fr, _ := testFramer() if err := fr.WritePriority(streamID, tt.priority); err != nil { t.Errorf("test %q: %v", tt.name, err) continue } f, err := fr.ReadFrame() if err != nil { t.Errorf("test %q: failed to read the frame back: %v", tt.name, err) continue } if !reflect.DeepEqual(f, tt.wantFrame) { t.Errorf("test %q: mismatch.\n got: %#v\nwant: %#v\n", tt.name, f, tt.wantFrame) } } } func TestWriteSettings(t *testing.T) { fr, buf := testFramer() settings := []Setting{{1, 2}, {3, 4}} fr.WriteSettings(settings...) const wantEnc = "\x00\x00\f\x04\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00\x00\x04" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } sf, ok := f.(*SettingsFrame) if !ok { t.Fatalf("Got a %T; want a SettingsFrame", f) } var got []Setting sf.ForeachSetting(func(s Setting) error { got = append(got, s) valBack, ok := sf.Value(s.ID) if !ok || valBack != s.Val { t.Errorf("Value(%d) = %v, %v; want %v, true", s.ID, valBack, ok, s.Val) } return nil }) if !reflect.DeepEqual(settings, got) { t.Errorf("Read settings %+v != written settings %+v", got, settings) } } func TestWriteSettingsAck(t *testing.T) { fr, buf := testFramer() fr.WriteSettingsAck() const wantEnc = "\x00\x00\x00\x04\x01\x00\x00\x00\x00" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } } func TestWriteWindowUpdate(t *testing.T) { fr, buf := testFramer() const streamID = 1<<24 + 2<<16 + 3<<8 + 4 const incr = 7<<24 + 6<<16 + 5<<8 + 4 if err := fr.WriteWindowUpdate(streamID, incr); err != nil { t.Fatal(err) } const wantEnc = "\x00\x00\x04\x08\x00\x01\x02\x03\x04\x07\x06\x05\x04" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &WindowUpdateFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x8, Flags: 0x0, Length: 0x4, StreamID: 0x1020304, }, Increment: 0x7060504, } if !reflect.DeepEqual(f, want) { t.Errorf("parsed back %#v; want %#v", f, want) } } func TestWritePing(t *testing.T) { testWritePing(t, false) } func TestWritePingAck(t *testing.T) { testWritePing(t, true) } func testWritePing(t *testing.T, ack bool) { fr, buf := testFramer() if err := fr.WritePing(ack, [8]byte{1, 2, 3, 4, 5, 6, 7, 8}); err != nil { t.Fatal(err) } var wantFlags Flags if ack { wantFlags = FlagPingAck } var wantEnc = "\x00\x00\x08\x06" + string(wantFlags) + "\x00\x00\x00\x00" + "\x01\x02\x03\x04\x05\x06\x07\x08" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &PingFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x6, Flags: wantFlags, Length: 0x8, StreamID: 0, }, Data: [8]byte{1, 2, 3, 4, 5, 6, 7, 8}, } if !reflect.DeepEqual(f, want) { t.Errorf("parsed back %#v; want %#v", f, want) } } func TestReadFrameHeader(t *testing.T) { tests := []struct { in string want FrameHeader }{ {in: "\x00\x00\x00" + "\x00" + "\x00" + "\x00\x00\x00\x00", want: FrameHeader{}}, {in: "\x01\x02\x03" + "\x04" + "\x05" + "\x06\x07\x08\x09", want: FrameHeader{ Length: 66051, Type: 4, Flags: 5, StreamID: 101124105, }}, // Ignore high bit: {in: "\xff\xff\xff" + "\xff" + "\xff" + "\xff\xff\xff\xff", want: FrameHeader{ Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, {in: "\xff\xff\xff" + "\xff" + "\xff" + "\x7f\xff\xff\xff", want: FrameHeader{ Length: 16777215, Type: 255, Flags: 255, StreamID: 2147483647}}, } for i, tt := range tests { got, err := readFrameHeader(make([]byte, 9), strings.NewReader(tt.in)) if err != nil { t.Errorf("%d. readFrameHeader(%q) = %v", i, tt.in, err) continue } tt.want.valid = true if got != tt.want { t.Errorf("%d. readFrameHeader(%q) = %+v; want %+v", i, tt.in, got, tt.want) } } } func TestReadWriteFrameHeader(t *testing.T) { tests := []struct { len uint32 typ FrameType flags Flags streamID uint32 }{ {len: 0, typ: 255, flags: 1, streamID: 0}, {len: 0, typ: 255, flags: 1, streamID: 1}, {len: 0, typ: 255, flags: 1, streamID: 255}, {len: 0, typ: 255, flags: 1, streamID: 256}, {len: 0, typ: 255, flags: 1, streamID: 65535}, {len: 0, typ: 255, flags: 1, streamID: 65536}, {len: 0, typ: 1, flags: 255, streamID: 1}, {len: 255, typ: 1, flags: 255, streamID: 1}, {len: 256, typ: 1, flags: 255, streamID: 1}, {len: 65535, typ: 1, flags: 255, streamID: 1}, {len: 65536, typ: 1, flags: 255, streamID: 1}, {len: 16777215, typ: 1, flags: 255, streamID: 1}, } for _, tt := range tests { fr, buf := testFramer() fr.startWrite(tt.typ, tt.flags, tt.streamID) fr.writeBytes(make([]byte, tt.len)) fr.endWrite() fh, err := ReadFrameHeader(buf) if err != nil { t.Errorf("ReadFrameHeader(%+v) = %v", tt, err) continue } if fh.Type != tt.typ || fh.Flags != tt.flags || fh.Length != tt.len || fh.StreamID != tt.streamID { t.Errorf("ReadFrameHeader(%+v) = %+v; mismatch", tt, fh) } } } func TestWriteTooLargeFrame(t *testing.T) { fr, _ := testFramer() fr.startWrite(0, 1, 1) fr.writeBytes(make([]byte, 1<<24)) err := fr.endWrite() if err != ErrFrameTooLarge { t.Errorf("endWrite = %v; want errFrameTooLarge", err) } } func TestWriteGoAway(t *testing.T) { const debug = "foo" fr, buf := testFramer() if err := fr.WriteGoAway(0x01020304, 0x05060708, []byte(debug)); err != nil { t.Fatal(err) } const wantEnc = "\x00\x00\v\a\x00\x00\x00\x00\x00\x01\x02\x03\x04\x05\x06\x07\x08" + debug if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } want := &GoAwayFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x7, Flags: 0, Length: uint32(4 + 4 + len(debug)), StreamID: 0, }, LastStreamID: 0x01020304, ErrCode: 0x05060708, debugData: []byte(debug), } if !reflect.DeepEqual(f, want) { t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) } if got := string(f.(*GoAwayFrame).DebugData()); got != debug { t.Errorf("debug data = %q; want %q", got, debug) } } func TestWritePushPromise(t *testing.T) { pp := PushPromiseParam{ StreamID: 42, PromiseID: 42, BlockFragment: []byte("abc"), } fr, buf := testFramer() if err := fr.WritePushPromise(pp); err != nil { t.Fatal(err) } const wantEnc = "\x00\x00\x07\x05\x00\x00\x00\x00*\x00\x00\x00*abc" if buf.String() != wantEnc { t.Errorf("encoded as %q; want %q", buf.Bytes(), wantEnc) } f, err := fr.ReadFrame() if err != nil { t.Fatal(err) } _, ok := f.(*PushPromiseFrame) if !ok { t.Fatalf("got %T; want *PushPromiseFrame", f) } want := &PushPromiseFrame{ FrameHeader: FrameHeader{ valid: true, Type: 0x5, Flags: 0x0, Length: 0x7, StreamID: 42, }, PromiseID: 42, headerFragBuf: []byte("abc"), } if !reflect.DeepEqual(f, want) { t.Fatalf("parsed back:\n%#v\nwant:\n%#v", f, want) } } ================================================ FILE: vendor/golang.org/x/net/http2/gotrack.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE // 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<= 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 } ================================================ FILE: vendor/golang.org/x/net/http2/gotrack_test.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "fmt" "strings" "testing" ) func TestGoroutineLock(t *testing.T) { DebugGoroutines = true g := newGoroutineLock() g.check() sawPanic := make(chan interface{}) go func() { defer func() { sawPanic <- recover() }() g.check() // should panic }() e := <-sawPanic if e == nil { t.Fatal("did not see panic from check in other goroutine") } if !strings.Contains(fmt.Sprint(e), "wrong goroutine") { t.Errorf("expected on see panic about running on the wrong goroutine; got %v", e) } } ================================================ FILE: vendor/golang.org/x/net/http2/h2i/README.md ================================================ # h2i **h2i** is an interactive HTTP/2 ("h2") console debugger. Miss the good ol' days of telnetting to your HTTP/1.n servers? We're bringing you back. Features: - send raw HTTP/2 frames - PING - SETTINGS - HEADERS - etc - type in HTTP/1.n and have it auto-HPACK/frame-ify it for HTTP/2 - pretty print all received HTTP/2 frames from the peer (including HPACK decoding) - tab completion of commands, options Not yet features, but soon: - unnecessary CONTINUATION frames on short boundaries, to test peer implementations - request bodies (DATA frames) - send invalid frames for testing server implementations (supported by underlying Framer) Later: - act like a server ## Installation ``` $ go get golang.org/x/net/http2/h2i $ h2i ``` ## Demo ``` $ h2i Usage: h2i -insecure Whether to skip TLS cert validation -nextproto string Comma-separated list of NPN/ALPN protocol names to negotiate. (default "h2,h2-14") $ h2i google.com Connecting to google.com:443 ... Connected to 74.125.224.41:443 Negotiated protocol "h2-14" [FrameHeader SETTINGS len=18] [MAX_CONCURRENT_STREAMS = 100] [INITIAL_WINDOW_SIZE = 1048576] [MAX_FRAME_SIZE = 16384] [FrameHeader WINDOW_UPDATE len=4] Window-Increment = 983041 h2i> PING h2iSayHI [FrameHeader PING flags=ACK len=8] Data = "h2iSayHI" h2i> headers (as HTTP/1.1)> GET / HTTP/1.1 (as HTTP/1.1)> Host: ip.appspot.com (as HTTP/1.1)> User-Agent: h2i/brad-n-blake (as HTTP/1.1)> Opening Stream-ID 1: :authority = ip.appspot.com :method = GET :path = / :scheme = https user-agent = h2i/brad-n-blake [FrameHeader HEADERS flags=END_HEADERS stream=1 len=77] :status = "200" alternate-protocol = "443:quic,p=1" content-length = "15" content-type = "text/html" date = "Fri, 01 May 2015 23:06:56 GMT" server = "Google Frontend" [FrameHeader DATA flags=END_STREAM stream=1 len=15] "173.164.155.78\n" [FrameHeader PING len=8] Data = "\x00\x00\x00\x00\x00\x00\x00\x00" h2i> ping [FrameHeader PING flags=ACK len=8] Data = "h2i_ping" h2i> ping [FrameHeader PING flags=ACK len=8] Data = "h2i_ping" h2i> ping [FrameHeader GOAWAY len=22] Last-Stream-ID = 1; Error-Code = PROTOCOL_ERROR (1) ReadFrame: EOF ``` ## Status Quick few hour hack. So much yet to do. Feel free to file issues for bugs or wishlist items, but [@bmizerany](https://github.com/bmizerany/) and I aren't yet accepting pull requests until things settle down. ================================================ FILE: vendor/golang.org/x/net/http2/h2i/h2i.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE /* The h2i command is an interactive HTTP/2 console. Usage: $ h2i [flags] Interactive commands in the console: (all parts case-insensitive) ping [data] settings ack settings FOO=n BAR=z headers (open a new stream by typing HTTP/1.1) */ package main import ( "bufio" "bytes" "crypto/tls" "errors" "flag" "fmt" "io" "log" "net" "net/http" "os" "regexp" "strconv" "strings" "golang.org/x/crypto/ssh/terminal" "golang.org/x/net/http2" "golang.org/x/net/http2/hpack" ) // Flags var ( flagNextProto = flag.String("nextproto", "h2,h2-14", "Comma-separated list of NPN/ALPN protocol names to negotiate.") flagInsecure = flag.Bool("insecure", false, "Whether to skip TLS cert validation") ) type command struct { run func(*h2i, []string) error // required // complete optionally specifies tokens (case-insensitive) which are // valid for this subcommand. complete func() []string } var commands = map[string]command{ "ping": command{run: (*h2i).cmdPing}, "settings": command{ run: (*h2i).cmdSettings, complete: func() []string { return []string{ "ACK", http2.SettingHeaderTableSize.String(), http2.SettingEnablePush.String(), http2.SettingMaxConcurrentStreams.String(), http2.SettingInitialWindowSize.String(), http2.SettingMaxFrameSize.String(), http2.SettingMaxHeaderListSize.String(), } }, }, "quit": command{run: (*h2i).cmdQuit}, "headers": command{run: (*h2i).cmdHeaders}, } func usage() { fmt.Fprintf(os.Stderr, "Usage: h2i \n\n") flag.PrintDefaults() os.Exit(1) } // withPort adds ":443" if another port isn't already present. func withPort(host string) string { if _, _, err := net.SplitHostPort(host); err != nil { return net.JoinHostPort(host, "443") } return host } // h2i is the app's state. type h2i struct { host string tc *tls.Conn framer *http2.Framer term *terminal.Terminal // owned by the command loop: streamID uint32 hbuf bytes.Buffer henc *hpack.Encoder // owned by the readFrames loop: peerSetting map[http2.SettingID]uint32 hdec *hpack.Decoder } func main() { flag.Usage = usage flag.Parse() if flag.NArg() != 1 { usage() } log.SetFlags(0) host := flag.Arg(0) app := &h2i{ host: host, peerSetting: make(map[http2.SettingID]uint32), } app.henc = hpack.NewEncoder(&app.hbuf) if err := app.Main(); err != nil { if app.term != nil { app.logf("%v\n", err) } else { fmt.Fprintf(os.Stderr, "%v\n", err) } os.Exit(1) } fmt.Fprintf(os.Stdout, "\n") } func (app *h2i) Main() error { cfg := &tls.Config{ ServerName: app.host, NextProtos: strings.Split(*flagNextProto, ","), InsecureSkipVerify: *flagInsecure, } hostAndPort := withPort(app.host) log.Printf("Connecting to %s ...", hostAndPort) tc, err := tls.Dial("tcp", hostAndPort, cfg) if err != nil { return fmt.Errorf("Error dialing %s: %v", withPort(app.host), err) } log.Printf("Connected to %v", tc.RemoteAddr()) defer tc.Close() if err := tc.Handshake(); err != nil { return fmt.Errorf("TLS handshake: %v", err) } if !*flagInsecure { if err := tc.VerifyHostname(app.host); err != nil { return fmt.Errorf("VerifyHostname: %v", err) } } state := tc.ConnectionState() log.Printf("Negotiated protocol %q", state.NegotiatedProtocol) if !state.NegotiatedProtocolIsMutual || state.NegotiatedProtocol == "" { return fmt.Errorf("Could not negotiate protocol mutually") } if _, err := io.WriteString(tc, http2.ClientPreface); err != nil { return err } app.framer = http2.NewFramer(tc, tc) oldState, err := terminal.MakeRaw(0) if err != nil { return err } defer terminal.Restore(0, oldState) var screen = struct { io.Reader io.Writer }{os.Stdin, os.Stdout} app.term = terminal.NewTerminal(screen, "h2i> ") lastWord := regexp.MustCompile(`.+\W(\w+)$`) app.term.AutoCompleteCallback = func(line string, pos int, key rune) (newLine string, newPos int, ok bool) { if key != '\t' { return } if pos != len(line) { // TODO: we're being lazy for now, only supporting tab completion at the end. return } // Auto-complete for the command itself. if !strings.Contains(line, " ") { var name string name, _, ok = lookupCommand(line) if !ok { return } return name, len(name), true } _, c, ok := lookupCommand(line[:strings.IndexByte(line, ' ')]) if !ok || c.complete == nil { return } if strings.HasSuffix(line, " ") { app.logf("%s", strings.Join(c.complete(), " ")) return line, pos, true } m := lastWord.FindStringSubmatch(line) if m == nil { return line, len(line), true } soFar := m[1] var match []string for _, cand := range c.complete() { if len(soFar) > len(cand) || !strings.EqualFold(cand[:len(soFar)], soFar) { continue } match = append(match, cand) } if len(match) == 0 { return } if len(match) > 1 { // TODO: auto-complete any common prefix app.logf("%s", strings.Join(match, " ")) return line, pos, true } newLine = line[:len(line)-len(soFar)] + match[0] return newLine, len(newLine), true } errc := make(chan error, 2) go func() { errc <- app.readFrames() }() go func() { errc <- app.readConsole() }() return <-errc } func (app *h2i) logf(format string, args ...interface{}) { fmt.Fprintf(app.term, format+"\n", args...) } func (app *h2i) readConsole() error { for { line, err := app.term.ReadLine() if err == io.EOF { return nil } if err != nil { return fmt.Errorf("terminal.ReadLine: %v", err) } f := strings.Fields(line) if len(f) == 0 { continue } cmd, args := f[0], f[1:] if _, c, ok := lookupCommand(cmd); ok { err = c.run(app, args) } else { app.logf("Unknown command %q", line) } if err == errExitApp { return nil } if err != nil { return err } } } func lookupCommand(prefix string) (name string, c command, ok bool) { prefix = strings.ToLower(prefix) if c, ok = commands[prefix]; ok { return prefix, c, ok } for full, candidate := range commands { if strings.HasPrefix(full, prefix) { if c.run != nil { return "", command{}, false // ambiguous } c = candidate name = full } } return name, c, c.run != nil } var errExitApp = errors.New("internal sentinel error value to quit the console reading loop") func (a *h2i) cmdQuit(args []string) error { if len(args) > 0 { a.logf("the QUIT command takes no argument") return nil } return errExitApp } func (a *h2i) cmdSettings(args []string) error { if len(args) == 1 && strings.EqualFold(args[0], "ACK") { return a.framer.WriteSettingsAck() } var settings []http2.Setting for _, arg := range args { if strings.EqualFold(arg, "ACK") { a.logf("Error: ACK must be only argument with the SETTINGS command") return nil } eq := strings.Index(arg, "=") if eq == -1 { a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) return nil } sid, ok := settingByName(arg[:eq]) if !ok { a.logf("Error: unknown setting name %q", arg[:eq]) return nil } val, err := strconv.ParseUint(arg[eq+1:], 10, 32) if err != nil { a.logf("Error: invalid argument %q (expected SETTING_NAME=nnnn)", arg) return nil } settings = append(settings, http2.Setting{ ID: sid, Val: uint32(val), }) } a.logf("Sending: %v", settings) return a.framer.WriteSettings(settings...) } func settingByName(name string) (http2.SettingID, bool) { for _, sid := range [...]http2.SettingID{ http2.SettingHeaderTableSize, http2.SettingEnablePush, http2.SettingMaxConcurrentStreams, http2.SettingInitialWindowSize, http2.SettingMaxFrameSize, http2.SettingMaxHeaderListSize, } { if strings.EqualFold(sid.String(), name) { return sid, true } } return 0, false } func (app *h2i) cmdPing(args []string) error { if len(args) > 1 { app.logf("invalid PING usage: only accepts 0 or 1 args") return nil // nil means don't end the program } var data [8]byte if len(args) == 1 { copy(data[:], args[0]) } else { copy(data[:], "h2i_ping") } return app.framer.WritePing(false, data) } func (app *h2i) cmdHeaders(args []string) error { if len(args) > 0 { app.logf("Error: HEADERS doesn't yet take arguments.") // TODO: flags for restricting window size, to force CONTINUATION // frames. return nil } var h1req bytes.Buffer app.term.SetPrompt("(as HTTP/1.1)> ") defer app.term.SetPrompt("h2i> ") for { line, err := app.term.ReadLine() if err != nil { return err } h1req.WriteString(line) h1req.WriteString("\r\n") if line == "" { break } } req, err := http.ReadRequest(bufio.NewReader(&h1req)) if err != nil { app.logf("Invalid HTTP/1.1 request: %v", err) return nil } if app.streamID == 0 { app.streamID = 1 } else { app.streamID += 2 } app.logf("Opening Stream-ID %d:", app.streamID) hbf := app.encodeHeaders(req) if len(hbf) > 16<<10 { app.logf("TODO: h2i doesn't yet write CONTINUATION frames. Copy it from transport.go") return nil } return app.framer.WriteHeaders(http2.HeadersFrameParam{ StreamID: app.streamID, BlockFragment: hbf, EndStream: req.Method == "GET" || req.Method == "HEAD", // good enough for now EndHeaders: true, // for now }) } func (app *h2i) readFrames() error { for { f, err := app.framer.ReadFrame() if err != nil { return fmt.Errorf("ReadFrame: %v", err) } app.logf("%v", f) switch f := f.(type) { case *http2.PingFrame: app.logf(" Data = %q", f.Data) case *http2.SettingsFrame: f.ForeachSetting(func(s http2.Setting) error { app.logf(" %v", s) app.peerSetting[s.ID] = s.Val return nil }) case *http2.WindowUpdateFrame: app.logf(" Window-Increment = %v\n", f.Increment) case *http2.GoAwayFrame: app.logf(" Last-Stream-ID = %d; Error-Code = %v (%d)\n", f.LastStreamID, f.ErrCode, f.ErrCode) case *http2.DataFrame: app.logf(" %q", f.Data()) case *http2.HeadersFrame: if f.HasPriority() { app.logf(" PRIORITY = %v", f.Priority) } if app.hdec == nil { // TODO: if the user uses h2i to send a SETTINGS frame advertising // something larger, we'll need to respect SETTINGS_HEADER_TABLE_SIZE // and stuff here instead of using the 4k default. But for now: tableSize := uint32(4 << 10) app.hdec = hpack.NewDecoder(tableSize, app.onNewHeaderField) } app.hdec.Write(f.HeaderBlockFragment()) } } } // called from readLoop func (app *h2i) onNewHeaderField(f hpack.HeaderField) { if f.Sensitive { app.logf(" %s = %q (SENSITIVE)", f.Name, f.Value) } app.logf(" %s = %q", f.Name, f.Value) } func (app *h2i) encodeHeaders(req *http.Request) []byte { app.hbuf.Reset() // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go host := req.Host if host == "" { host = req.URL.Host } path := req.URL.Path if path == "" { path = "/" } app.writeHeader(":authority", host) // probably not right for all sites app.writeHeader(":method", req.Method) app.writeHeader(":path", path) app.writeHeader(":scheme", "https") for k, vv := range req.Header { lowKey := strings.ToLower(k) if lowKey == "host" { continue } for _, v := range vv { app.writeHeader(lowKey, v) } } return app.hbuf.Bytes() } func (app *h2i) writeHeader(name, value string) { app.henc.WriteField(hpack.HeaderField{Name: name, Value: value}) app.logf(" %s = %s", name, value) } ================================================ FILE: vendor/golang.org/x/net/http2/headermap.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE 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", "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) } ================================================ FILE: vendor/golang.org/x/net/http2/hpack/encode.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE 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.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) { for idx, hf := range staticTable { if !constantTimeStringCompare(hf.Name, f.Name) { continue } if i == 0 { i = uint64(idx + 1) } if f.Sensitive { continue } if !constantTimeStringCompare(hf.Value, f.Value) { continue } i = uint64(idx + 1) nameValueMatch = true return } j, nameValueMatch := e.dynTab.search(f) if nameValueMatch || (i == 0 && j != 0) { i = j + uint64(len(staticTable)) } return } // 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 } ================================================ FILE: vendor/golang.org/x/net/http2/hpack/encode_test.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package hpack import ( "bytes" "encoding/hex" "reflect" "strings" "testing" ) func TestEncoderTableSizeUpdate(t *testing.T) { tests := []struct { size1, size2 uint32 wantHex string }{ // Should emit 2 table size updates (2048 and 4096) {2048, 4096, "3fe10f 3fe11f 82"}, // Should emit 1 table size update (2048) {16384, 2048, "3fe10f 82"}, } for _, tt := range tests { var buf bytes.Buffer e := NewEncoder(&buf) e.SetMaxDynamicTableSize(tt.size1) e.SetMaxDynamicTableSize(tt.size2) if err := e.WriteField(pair(":method", "GET")); err != nil { t.Fatal(err) } want := removeSpace(tt.wantHex) if got := hex.EncodeToString(buf.Bytes()); got != want { t.Errorf("e.SetDynamicTableSize %v, %v = %q; want %q", tt.size1, tt.size2, got, want) } } } func TestEncoderWriteField(t *testing.T) { var buf bytes.Buffer e := NewEncoder(&buf) var got []HeaderField d := NewDecoder(4<<10, func(f HeaderField) { got = append(got, f) }) tests := []struct { hdrs []HeaderField }{ {[]HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), }}, {[]HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), pair("cache-control", "no-cache"), }}, {[]HeaderField{ pair(":method", "GET"), pair(":scheme", "https"), pair(":path", "/index.html"), pair(":authority", "www.example.com"), pair("custom-key", "custom-value"), }}, } for i, tt := range tests { buf.Reset() got = got[:0] for _, hf := range tt.hdrs { if err := e.WriteField(hf); err != nil { t.Fatal(err) } } _, err := d.Write(buf.Bytes()) if err != nil { t.Errorf("%d. Decoder Write = %v", i, err) } if !reflect.DeepEqual(got, tt.hdrs) { t.Errorf("%d. Decoded %+v; want %+v", i, got, tt.hdrs) } } } func TestEncoderSearchTable(t *testing.T) { e := NewEncoder(nil) e.dynTab.add(pair("foo", "bar")) e.dynTab.add(pair("blake", "miz")) e.dynTab.add(pair(":method", "GET")) tests := []struct { hf HeaderField wantI uint64 wantMatch bool }{ // Name and Value match {pair("foo", "bar"), uint64(len(staticTable) + 3), true}, {pair("blake", "miz"), uint64(len(staticTable) + 2), true}, {pair(":method", "GET"), 2, true}, // Only name match because Sensitive == true {HeaderField{":method", "GET", true}, 2, false}, // Only Name matches {pair("foo", "..."), uint64(len(staticTable) + 3), false}, {pair("blake", "..."), uint64(len(staticTable) + 2), false}, {pair(":method", "..."), 2, false}, // None match {pair("foo-", "bar"), 0, false}, } for _, tt := range tests { if gotI, gotMatch := e.searchTable(tt.hf); gotI != tt.wantI || gotMatch != tt.wantMatch { t.Errorf("d.search(%+v) = %v, %v; want %v, %v", tt.hf, gotI, gotMatch, tt.wantI, tt.wantMatch) } } } func TestAppendVarInt(t *testing.T) { tests := []struct { n byte i uint64 want []byte }{ // Fits in a byte: {1, 0, []byte{0}}, {2, 2, []byte{2}}, {3, 6, []byte{6}}, {4, 14, []byte{14}}, {5, 30, []byte{30}}, {6, 62, []byte{62}}, {7, 126, []byte{126}}, {8, 254, []byte{254}}, // Multiple bytes: {5, 1337, []byte{31, 154, 10}}, } for _, tt := range tests { got := appendVarInt(nil, tt.n, tt.i) if !bytes.Equal(got, tt.want) { t.Errorf("appendVarInt(nil, %v, %v) = %v; want %v", tt.n, tt.i, got, tt.want) } } } func TestAppendHpackString(t *testing.T) { tests := []struct { s, wantHex string }{ // Huffman encoded {"www.example.com", "8c f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, // Not Huffman encoded {"a", "01 61"}, // zero length {"", "00"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendHpackString(nil, tt.s) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendHpackString(nil, %q) = %q; want %q", tt.s, got, want) } } } func TestAppendIndexed(t *testing.T) { tests := []struct { i uint64 wantHex string }{ // 1 byte {1, "81"}, {126, "fe"}, // 2 bytes {127, "ff00"}, {128, "ff01"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendIndexed(nil, tt.i) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendIndex(nil, %v) = %q; want %q", tt.i, got, want) } } } func TestAppendNewName(t *testing.T) { tests := []struct { f HeaderField indexing bool wantHex string }{ // Incremental indexing {HeaderField{"custom-key", "custom-value", false}, true, "40 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, // Without indexing {HeaderField{"custom-key", "custom-value", false}, false, "00 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, // Never indexed {HeaderField{"custom-key", "custom-value", true}, true, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, {HeaderField{"custom-key", "custom-value", true}, false, "10 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendNewName(nil, tt.f, tt.indexing) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendNewName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) } } } func TestAppendIndexedName(t *testing.T) { tests := []struct { f HeaderField i uint64 indexing bool wantHex string }{ // Incremental indexing {HeaderField{":status", "302", false}, 8, true, "48 82 6402"}, // Without indexing {HeaderField{":status", "302", false}, 8, false, "08 82 6402"}, // Never indexed {HeaderField{":status", "302", true}, 8, true, "18 82 6402"}, {HeaderField{":status", "302", true}, 8, false, "18 82 6402"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendIndexedName(nil, tt.f, tt.i, tt.indexing) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendIndexedName(nil, %+v, %v) = %q; want %q", tt.f, tt.indexing, got, want) } } } func TestAppendTableSize(t *testing.T) { tests := []struct { i uint32 wantHex string }{ // Fits into 1 byte {30, "3e"}, // Extra byte {31, "3f00"}, {32, "3f01"}, } for _, tt := range tests { want := removeSpace(tt.wantHex) buf := appendTableSize(nil, tt.i) if got := hex.EncodeToString(buf); want != got { t.Errorf("appendTableSize(nil, %v) = %q; want %q", tt.i, got, want) } } } func TestEncoderSetMaxDynamicTableSize(t *testing.T) { var buf bytes.Buffer e := NewEncoder(&buf) tests := []struct { v uint32 wantUpdate bool wantMinSize uint32 wantMaxSize uint32 }{ // Set new table size to 2048 {2048, true, 2048, 2048}, // Set new table size to 16384, but still limited to // 4096 {16384, true, 2048, 4096}, } for _, tt := range tests { e.SetMaxDynamicTableSize(tt.v) if got := e.tableSizeUpdate; tt.wantUpdate != got { t.Errorf("e.tableSizeUpdate = %v; want %v", got, tt.wantUpdate) } if got := e.minSize; tt.wantMinSize != got { t.Errorf("e.minSize = %v; want %v", got, tt.wantMinSize) } if got := e.dynTab.maxSize; tt.wantMaxSize != got { t.Errorf("e.maxSize = %v; want %v", got, tt.wantMaxSize) } } } func TestEncoderSetMaxDynamicTableSizeLimit(t *testing.T) { e := NewEncoder(nil) // 4095 < initialHeaderTableSize means maxSize is truncated to // 4095. e.SetMaxDynamicTableSizeLimit(4095) if got, want := e.dynTab.maxSize, uint32(4095); got != want { t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) } if got, want := e.maxSizeLimit, uint32(4095); got != want { t.Errorf("e.maxSizeLimit = %v; want %v", got, want) } if got, want := e.tableSizeUpdate, true; got != want { t.Errorf("e.tableSizeUpdate = %v; want %v", got, want) } // maxSize will be truncated to maxSizeLimit e.SetMaxDynamicTableSize(16384) if got, want := e.dynTab.maxSize, uint32(4095); got != want { t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) } // 8192 > current maxSizeLimit, so maxSize does not change. e.SetMaxDynamicTableSizeLimit(8192) if got, want := e.dynTab.maxSize, uint32(4095); got != want { t.Errorf("e.dynTab.maxSize = %v; want %v", got, want) } if got, want := e.maxSizeLimit, uint32(8192); got != want { t.Errorf("e.maxSizeLimit = %v; want %v", got, want) } } func removeSpace(s string) string { return strings.Replace(s, " ", "", -1) } ================================================ FILE: vendor/golang.org/x/net/http2/hpack/hpack.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE // 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 } 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) // 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 // usually not owned saveBuf bytes.Buffer } func NewDecoder(maxSize uint32, emitFunc func(f HeaderField)) *Decoder { d := &Decoder{ emit: emitFunc, } d.dynTab.allowedMaxSize = maxSize d.dynTab.setMaxSize(maxSize) return d } // 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 { // ents is the FIFO described at // http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2 // The newest (low index) is append at the end, and items are // evicted from the front. ents []HeaderField size uint32 maxSize uint32 // current maxSize allowedMaxSize uint32 // maxSize may go up to this, inclusive } func (dt *dynamicTable) setMaxSize(v uint32) { dt.maxSize = v dt.evict() } // TODO: change dynamicTable to be a struct with a slice and a size int field, // per http://http2.github.io/http2-spec/compression.html#rfc.section.4.1: // // // Then make add increment the size. maybe the max size should move from Decoder to // dynamicTable and add should return an ok bool if there was enough space. // // Later we'll need a remove operation on dynamicTable. func (dt *dynamicTable) add(f HeaderField) { dt.ents = append(dt.ents, f) dt.size += f.size() dt.evict() } // If we're too big, evict old stuff (front of the slice) func (dt *dynamicTable) evict() { base := dt.ents // keep base pointer of slice for dt.size > dt.maxSize { dt.size -= dt.ents[0].size() dt.ents = dt.ents[1:] } // Shift slice contents down if we evicted things. if len(dt.ents) != len(base) { copy(base, dt.ents) dt.ents = base[:len(dt.ents)] } } // constantTimeStringCompare compares string a and b in a constant // time manner. func constantTimeStringCompare(a, b string) bool { if len(a) != len(b) { return false } c := byte(0) for i := 0; i < len(a); i++ { c |= a[i] ^ b[i] } return c == 0 } // Search searches f in the table. The return value i is 0 if there is // no name match. If there is name match or name/value match, i is the // index of that entry (1-based). If both name and value match, // nameValueMatch becomes true. func (dt *dynamicTable) search(f HeaderField) (i uint64, nameValueMatch bool) { l := len(dt.ents) for j := l - 1; j >= 0; j-- { ent := dt.ents[j] if !constantTimeStringCompare(ent.Name, f.Name) { continue } if i == 0 { i = uint64(l - j) } if f.Sensitive { continue } if !constantTimeStringCompare(ent.Value, f.Value) { continue } i = uint64(l - j) nameValueMatch = true return } return } func (d *Decoder) maxTableIndex() int { return len(d.dynTab.ents) + len(staticTable) } func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) { if i < 1 { return } if i > uint64(d.maxTableIndex()) { return } if i <= uint64(len(staticTable)) { return staticTable[i-1], true } dents := d.dynTab.ents return dents[len(dents)-(int(i)-len(staticTable))], 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 != nil { if err == errNeedMore { err = nil d.saveBuf.Write(d.buf) } 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.emit(HeaderField{Name: hf.Name, Value: hf.Value}) d.buf = buf return nil } // (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 if nameIdx > 0 { ihf, ok := d.at(nameIdx) if !ok { return DecodingError{InvalidIndexError(nameIdx)} } hf.Name = ihf.Name } else { hf.Name, buf, err = readString(buf) if err != nil { return err } } hf.Value, buf, err = readString(buf) if err != nil { return err } d.buf = buf if it.indexed() { d.dynTab.add(hf) } hf.Sensitive = it.sensitive() 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< 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 } func readString(p []byte) (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 uint64(len(p)) < strLen { return "", p, errNeedMore } if !isHuff { return string(p[:strLen]), p[strLen:], nil } // TODO: optimize this garbage: var buf bytes.Buffer if _, err := HuffmanDecode(&buf, p[:strLen]); err != nil { return "", nil, err } return buf.String(), p[strLen:], nil } ================================================ FILE: vendor/golang.org/x/net/http2/hpack/hpack_test.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package hpack import ( "bufio" "bytes" "encoding/hex" "fmt" "reflect" "regexp" "strconv" "strings" "testing" ) func TestStaticTable(t *testing.T) { fromSpec := ` +-------+-----------------------------+---------------+ | 1 | :authority | | | 2 | :method | GET | | 3 | :method | POST | | 4 | :path | / | | 5 | :path | /index.html | | 6 | :scheme | http | | 7 | :scheme | https | | 8 | :status | 200 | | 9 | :status | 204 | | 10 | :status | 206 | | 11 | :status | 304 | | 12 | :status | 400 | | 13 | :status | 404 | | 14 | :status | 500 | | 15 | accept-charset | | | 16 | accept-encoding | gzip, deflate | | 17 | accept-language | | | 18 | accept-ranges | | | 19 | accept | | | 20 | access-control-allow-origin | | | 21 | age | | | 22 | allow | | | 23 | authorization | | | 24 | cache-control | | | 25 | content-disposition | | | 26 | content-encoding | | | 27 | content-language | | | 28 | content-length | | | 29 | content-location | | | 30 | content-range | | | 31 | content-type | | | 32 | cookie | | | 33 | date | | | 34 | etag | | | 35 | expect | | | 36 | expires | | | 37 | from | | | 38 | host | | | 39 | if-match | | | 40 | if-modified-since | | | 41 | if-none-match | | | 42 | if-range | | | 43 | if-unmodified-since | | | 44 | last-modified | | | 45 | link | | | 46 | location | | | 47 | max-forwards | | | 48 | proxy-authenticate | | | 49 | proxy-authorization | | | 50 | range | | | 51 | referer | | | 52 | refresh | | | 53 | retry-after | | | 54 | server | | | 55 | set-cookie | | | 56 | strict-transport-security | | | 57 | transfer-encoding | | | 58 | user-agent | | | 59 | vary | | | 60 | via | | | 61 | www-authenticate | | +-------+-----------------------------+---------------+ ` bs := bufio.NewScanner(strings.NewReader(fromSpec)) re := regexp.MustCompile(`\| (\d+)\s+\| (\S+)\s*\| (\S(.*\S)?)?\s+\|`) for bs.Scan() { l := bs.Text() if !strings.Contains(l, "|") { continue } m := re.FindStringSubmatch(l) if m == nil { continue } i, err := strconv.Atoi(m[1]) if err != nil { t.Errorf("Bogus integer on line %q", l) continue } if i < 1 || i > len(staticTable) { t.Errorf("Bogus index %d on line %q", i, l) continue } if got, want := staticTable[i-1].Name, m[2]; got != want { t.Errorf("header index %d name = %q; want %q", i, got, want) } if got, want := staticTable[i-1].Value, m[3]; got != want { t.Errorf("header index %d value = %q; want %q", i, got, want) } } if err := bs.Err(); err != nil { t.Error(err) } } func (d *Decoder) mustAt(idx int) HeaderField { if hf, ok := d.at(uint64(idx)); !ok { panic(fmt.Sprintf("bogus index %d", idx)) } else { return hf } } func TestDynamicTableAt(t *testing.T) { d := NewDecoder(4096, nil) at := d.mustAt if got, want := at(2), (pair(":method", "GET")); got != want { t.Errorf("at(2) = %v; want %v", got, want) } d.dynTab.add(pair("foo", "bar")) d.dynTab.add(pair("blake", "miz")) if got, want := at(len(staticTable)+1), (pair("blake", "miz")); got != want { t.Errorf("at(dyn 1) = %v; want %v", got, want) } if got, want := at(len(staticTable)+2), (pair("foo", "bar")); got != want { t.Errorf("at(dyn 2) = %v; want %v", got, want) } if got, want := at(3), (pair(":method", "POST")); got != want { t.Errorf("at(3) = %v; want %v", got, want) } } func TestDynamicTableSearch(t *testing.T) { dt := dynamicTable{} dt.setMaxSize(4096) dt.add(pair("foo", "bar")) dt.add(pair("blake", "miz")) dt.add(pair(":method", "GET")) tests := []struct { hf HeaderField wantI uint64 wantMatch bool }{ // Name and Value match {pair("foo", "bar"), 3, true}, {pair(":method", "GET"), 1, true}, // Only name match because of Sensitive == true {HeaderField{"blake", "miz", true}, 2, false}, // Only Name matches {pair("foo", "..."), 3, false}, {pair("blake", "..."), 2, false}, {pair(":method", "..."), 1, false}, // None match {pair("foo-", "bar"), 0, false}, } for _, tt := range tests { if gotI, gotMatch := dt.search(tt.hf); gotI != tt.wantI || gotMatch != tt.wantMatch { t.Errorf("d.search(%+v) = %v, %v; want %v, %v", tt.hf, gotI, gotMatch, tt.wantI, tt.wantMatch) } } } func TestDynamicTableSizeEvict(t *testing.T) { d := NewDecoder(4096, nil) if want := uint32(0); d.dynTab.size != want { t.Fatalf("size = %d; want %d", d.dynTab.size, want) } add := d.dynTab.add add(pair("blake", "eats pizza")) if want := uint32(15 + 32); d.dynTab.size != want { t.Fatalf("after pizza, size = %d; want %d", d.dynTab.size, want) } add(pair("foo", "bar")) if want := uint32(15 + 32 + 6 + 32); d.dynTab.size != want { t.Fatalf("after foo bar, size = %d; want %d", d.dynTab.size, want) } d.dynTab.setMaxSize(15 + 32 + 1 /* slop */) if want := uint32(6 + 32); d.dynTab.size != want { t.Fatalf("after setMaxSize, size = %d; want %d", d.dynTab.size, want) } if got, want := d.mustAt(len(staticTable)+1), (pair("foo", "bar")); got != want { t.Errorf("at(dyn 1) = %v; want %v", got, want) } add(pair("long", strings.Repeat("x", 500))) if want := uint32(0); d.dynTab.size != want { t.Fatalf("after big one, size = %d; want %d", d.dynTab.size, want) } } func TestDecoderDecode(t *testing.T) { tests := []struct { name string in []byte want []HeaderField wantDynTab []HeaderField // newest entry first }{ // C.2.1 Literal Header Field with Indexing // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.1 {"C.2.1", dehex("400a 6375 7374 6f6d 2d6b 6579 0d63 7573 746f 6d2d 6865 6164 6572"), []HeaderField{pair("custom-key", "custom-header")}, []HeaderField{pair("custom-key", "custom-header")}, }, // C.2.2 Literal Header Field without Indexing // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.2 {"C.2.2", dehex("040c 2f73 616d 706c 652f 7061 7468"), []HeaderField{pair(":path", "/sample/path")}, []HeaderField{}}, // C.2.3 Literal Header Field never Indexed // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.3 {"C.2.3", dehex("1008 7061 7373 776f 7264 0673 6563 7265 74"), []HeaderField{{"password", "secret", true}}, []HeaderField{}}, // C.2.4 Indexed Header Field // http://http2.github.io/http2-spec/compression.html#rfc.section.C.2.4 {"C.2.4", []byte("\x82"), []HeaderField{pair(":method", "GET")}, []HeaderField{}}, } for _, tt := range tests { d := NewDecoder(4096, nil) hf, err := d.DecodeFull(tt.in) if err != nil { t.Errorf("%s: %v", tt.name, err) continue } if !reflect.DeepEqual(hf, tt.want) { t.Errorf("%s: Got %v; want %v", tt.name, hf, tt.want) } gotDynTab := d.dynTab.reverseCopy() if !reflect.DeepEqual(gotDynTab, tt.wantDynTab) { t.Errorf("%s: dynamic table after = %v; want %v", tt.name, gotDynTab, tt.wantDynTab) } } } func (dt *dynamicTable) reverseCopy() (hf []HeaderField) { hf = make([]HeaderField, len(dt.ents)) for i := range hf { hf[i] = dt.ents[len(dt.ents)-1-i] } return } type encAndWant struct { enc []byte want []HeaderField wantDynTab []HeaderField wantDynSize uint32 } // C.3 Request Examples without Huffman Coding // http://http2.github.io/http2-spec/compression.html#rfc.section.C.3 func TestDecodeC3_NoHuffman(t *testing.T) { testDecodeSeries(t, 4096, []encAndWant{ {dehex("8286 8441 0f77 7777 2e65 7861 6d70 6c65 2e63 6f6d"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), }, []HeaderField{ pair(":authority", "www.example.com"), }, 57, }, {dehex("8286 84be 5808 6e6f 2d63 6163 6865"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), pair("cache-control", "no-cache"), }, []HeaderField{ pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 110, }, {dehex("8287 85bf 400a 6375 7374 6f6d 2d6b 6579 0c63 7573 746f 6d2d 7661 6c75 65"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "https"), pair(":path", "/index.html"), pair(":authority", "www.example.com"), pair("custom-key", "custom-value"), }, []HeaderField{ pair("custom-key", "custom-value"), pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 164, }, }) } // C.4 Request Examples with Huffman Coding // http://http2.github.io/http2-spec/compression.html#rfc.section.C.4 func TestDecodeC4_Huffman(t *testing.T) { testDecodeSeries(t, 4096, []encAndWant{ {dehex("8286 8441 8cf1 e3c2 e5f2 3a6b a0ab 90f4 ff"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), }, []HeaderField{ pair(":authority", "www.example.com"), }, 57, }, {dehex("8286 84be 5886 a8eb 1064 9cbf"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "http"), pair(":path", "/"), pair(":authority", "www.example.com"), pair("cache-control", "no-cache"), }, []HeaderField{ pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 110, }, {dehex("8287 85bf 4088 25a8 49e9 5ba9 7d7f 8925 a849 e95b b8e8 b4bf"), []HeaderField{ pair(":method", "GET"), pair(":scheme", "https"), pair(":path", "/index.html"), pair(":authority", "www.example.com"), pair("custom-key", "custom-value"), }, []HeaderField{ pair("custom-key", "custom-value"), pair("cache-control", "no-cache"), pair(":authority", "www.example.com"), }, 164, }, }) } // http://http2.github.io/http2-spec/compression.html#rfc.section.C.5 // "This section shows several consecutive header lists, corresponding // to HTTP responses, on the same connection. The HTTP/2 setting // parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 // octets, causing some evictions to occur." func TestDecodeC5_ResponsesNoHuff(t *testing.T) { testDecodeSeries(t, 256, []encAndWant{ {dehex(` 4803 3330 3258 0770 7269 7661 7465 611d 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 2032 303a 3133 3a32 3120 474d 546e 1768 7474 7073 3a2f 2f77 7777 2e65 7861 6d70 6c65 2e63 6f6d `), []HeaderField{ pair(":status", "302"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), pair(":status", "302"), }, 222, }, {dehex("4803 3330 37c1 c0bf"), []HeaderField{ pair(":status", "307"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair(":status", "307"), pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), }, 222, }, {dehex(` 88c1 611d 4d6f 6e2c 2032 3120 4f63 7420 3230 3133 2032 303a 3133 3a32 3220 474d 54c0 5a04 677a 6970 7738 666f 6f3d 4153 444a 4b48 514b 425a 584f 5157 454f 5049 5541 5851 5745 4f49 553b 206d 6178 2d61 6765 3d33 3630 303b 2076 6572 7369 6f6e 3d31 `), []HeaderField{ pair(":status", "200"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), pair("location", "https://www.example.com"), pair("content-encoding", "gzip"), pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), }, []HeaderField{ pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), pair("content-encoding", "gzip"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), }, 215, }, }) } // http://http2.github.io/http2-spec/compression.html#rfc.section.C.6 // "This section shows the same examples as the previous section, but // using Huffman encoding for the literal values. The HTTP/2 setting // parameter SETTINGS_HEADER_TABLE_SIZE is set to the value of 256 // octets, causing some evictions to occur. The eviction mechanism // uses the length of the decoded literal values, so the same // evictions occurs as in the previous section." func TestDecodeC6_ResponsesHuffman(t *testing.T) { testDecodeSeries(t, 256, []encAndWant{ {dehex(` 4882 6402 5885 aec3 771a 4b61 96d0 7abe 9410 54d4 44a8 2005 9504 0b81 66e0 82a6 2d1b ff6e 919d 29ad 1718 63c7 8f0b 97c8 e9ae 82ae 43d3 `), []HeaderField{ pair(":status", "302"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), pair(":status", "302"), }, 222, }, {dehex("4883 640e ffc1 c0bf"), []HeaderField{ pair(":status", "307"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("location", "https://www.example.com"), }, []HeaderField{ pair(":status", "307"), pair("location", "https://www.example.com"), pair("date", "Mon, 21 Oct 2013 20:13:21 GMT"), pair("cache-control", "private"), }, 222, }, {dehex(` 88c1 6196 d07a be94 1054 d444 a820 0595 040b 8166 e084 a62d 1bff c05a 839b d9ab 77ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07 `), []HeaderField{ pair(":status", "200"), pair("cache-control", "private"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), pair("location", "https://www.example.com"), pair("content-encoding", "gzip"), pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), }, []HeaderField{ pair("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), pair("content-encoding", "gzip"), pair("date", "Mon, 21 Oct 2013 20:13:22 GMT"), }, 215, }, }) } func testDecodeSeries(t *testing.T, size uint32, steps []encAndWant) { d := NewDecoder(size, nil) for i, step := range steps { hf, err := d.DecodeFull(step.enc) if err != nil { t.Fatalf("Error at step index %d: %v", i, err) } if !reflect.DeepEqual(hf, step.want) { t.Fatalf("At step index %d: Got headers %v; want %v", i, hf, step.want) } gotDynTab := d.dynTab.reverseCopy() if !reflect.DeepEqual(gotDynTab, step.wantDynTab) { t.Errorf("After step index %d, dynamic table = %v; want %v", i, gotDynTab, step.wantDynTab) } if d.dynTab.size != step.wantDynSize { t.Errorf("After step index %d, dynamic table size = %v; want %v", i, d.dynTab.size, step.wantDynSize) } } } func TestHuffmanDecode(t *testing.T) { tests := []struct { inHex, want string }{ {"f1e3 c2e5 f23a 6ba0 ab90 f4ff", "www.example.com"}, {"a8eb 1064 9cbf", "no-cache"}, {"25a8 49e9 5ba9 7d7f", "custom-key"}, {"25a8 49e9 5bb8 e8b4 bf", "custom-value"}, {"6402", "302"}, {"aec3 771a 4b", "private"}, {"d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3", "https://www.example.com"}, {"9bd9 ab", "gzip"}, {"94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}, } for i, tt := range tests { var buf bytes.Buffer in, err := hex.DecodeString(strings.Replace(tt.inHex, " ", "", -1)) if err != nil { t.Errorf("%d. hex input error: %v", i, err) continue } if _, err := HuffmanDecode(&buf, in); err != nil { t.Errorf("%d. decode error: %v", i, err) continue } if got := buf.String(); tt.want != got { t.Errorf("%d. decode = %q; want %q", i, got, tt.want) } } } func TestAppendHuffmanString(t *testing.T) { tests := []struct { in, want string }{ {"www.example.com", "f1e3 c2e5 f23a 6ba0 ab90 f4ff"}, {"no-cache", "a8eb 1064 9cbf"}, {"custom-key", "25a8 49e9 5ba9 7d7f"}, {"custom-value", "25a8 49e9 5bb8 e8b4 bf"}, {"302", "6402"}, {"private", "aec3 771a 4b"}, {"Mon, 21 Oct 2013 20:13:21 GMT", "d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff"}, {"https://www.example.com", "9d29 ad17 1863 c78f 0b97 c8e9 ae82 ae43 d3"}, {"gzip", "9bd9 ab"}, {"foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", "94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07"}, } for i, tt := range tests { buf := []byte{} want := strings.Replace(tt.want, " ", "", -1) buf = AppendHuffmanString(buf, tt.in) if got := hex.EncodeToString(buf); want != got { t.Errorf("%d. encode = %q; want %q", i, got, want) } } } func TestReadVarInt(t *testing.T) { type res struct { i uint64 consumed int err error } tests := []struct { n byte p []byte want res }{ // Fits in a byte: {1, []byte{0}, res{0, 1, nil}}, {2, []byte{2}, res{2, 1, nil}}, {3, []byte{6}, res{6, 1, nil}}, {4, []byte{14}, res{14, 1, nil}}, {5, []byte{30}, res{30, 1, nil}}, {6, []byte{62}, res{62, 1, nil}}, {7, []byte{126}, res{126, 1, nil}}, {8, []byte{254}, res{254, 1, nil}}, // Doesn't fit in a byte: {1, []byte{1}, res{0, 0, errNeedMore}}, {2, []byte{3}, res{0, 0, errNeedMore}}, {3, []byte{7}, res{0, 0, errNeedMore}}, {4, []byte{15}, res{0, 0, errNeedMore}}, {5, []byte{31}, res{0, 0, errNeedMore}}, {6, []byte{63}, res{0, 0, errNeedMore}}, {7, []byte{127}, res{0, 0, errNeedMore}}, {8, []byte{255}, res{0, 0, errNeedMore}}, // Ignoring top bits: {5, []byte{255, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 111 {5, []byte{159, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 100 {5, []byte{191, 154, 10}, res{1337, 3, nil}}, // high dummy three bits: 101 // Extra byte: {5, []byte{191, 154, 10, 2}, res{1337, 3, nil}}, // extra byte // Short a byte: {5, []byte{191, 154}, res{0, 0, errNeedMore}}, // integer overflow: {1, []byte{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}, res{0, 0, errVarintOverflow}}, } for _, tt := range tests { i, remain, err := readVarInt(tt.n, tt.p) consumed := len(tt.p) - len(remain) got := res{i, consumed, err} if got != tt.want { t.Errorf("readVarInt(%d, %v ~ %x) = %+v; want %+v", tt.n, tt.p, tt.p, got, tt.want) } } } func dehex(s string) []byte { s = strings.Replace(s, " ", "", -1) s = strings.Replace(s, "\n", "", -1) b, err := hex.DecodeString(s) if err != nil { panic(err) } return b } ================================================ FILE: vendor/golang.org/x/net/http2/hpack/huffman.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package hpack import ( "bytes" "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) n := rootHuffmanNode cur, nbits := uint(0), uint8(0) for _, b := range v { cur = cur<<8 | uint(b) nbits += 8 for nbits >= 8 { n = n.children[byte(cur>>(nbits-8))] if n.children == nil { buf.WriteByte(n.sym) nbits -= n.codeLen n = rootHuffmanNode } else { nbits -= 8 } } } for nbits > 0 { n = n.children[byte(cur<<(8-nbits))] if n.children != nil || n.codeLen > nbits { break } buf.WriteByte(n.sym) nbits -= n.codeLen n = rootHuffmanNode } return w.Write(buf.Bytes()) } 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() { for i, code := range huffmanCodes { if i > 255 { panic("too many huffman codes") } 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<> (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 } ================================================ FILE: vendor/golang.org/x/net/http2/hpack/tables.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package hpack func pair(name, value string) HeaderField { return HeaderField{Name: name, Value: value} } // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-07#appendix-B var staticTable = []HeaderField{ pair(":authority", ""), // index 1 (1-based) pair(":method", "GET"), pair(":method", "POST"), pair(":path", "/"), pair(":path", "/index.html"), pair(":scheme", "http"), pair(":scheme", "https"), pair(":status", "200"), pair(":status", "204"), pair(":status", "206"), pair(":status", "304"), pair(":status", "400"), pair(":status", "404"), pair(":status", "500"), pair("accept-charset", ""), pair("accept-encoding", "gzip, deflate"), pair("accept-language", ""), pair("accept-ranges", ""), pair("accept", ""), pair("access-control-allow-origin", ""), pair("age", ""), pair("allow", ""), pair("authorization", ""), pair("cache-control", ""), pair("content-disposition", ""), pair("content-encoding", ""), pair("content-language", ""), pair("content-length", ""), pair("content-location", ""), pair("content-range", ""), pair("content-type", ""), pair("cookie", ""), pair("date", ""), pair("etag", ""), pair("expect", ""), pair("expires", ""), pair("from", ""), pair("host", ""), pair("if-match", ""), pair("if-modified-since", ""), pair("if-none-match", ""), pair("if-range", ""), pair("if-unmodified-since", ""), pair("last-modified", ""), pair("link", ""), pair("location", ""), pair("max-forwards", ""), pair("proxy-authenticate", ""), pair("proxy-authorization", ""), pair("range", ""), pair("referer", ""), pair("refresh", ""), pair("retry-after", ""), pair("server", ""), pair("set-cookie", ""), pair("strict-transport-security", ""), pair("transfer-encoding", ""), pair("user-agent", ""), pair("vary", ""), pair("via", ""), pair("www-authenticate", ""), } var huffmanCodes = []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 = []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, } ================================================ FILE: vendor/golang.org/x/net/http2/http2.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE // Package http2 implements the HTTP/2 protocol. // // This is a work in progress. This package is low-level and intended // to be used directly by very few people. Most users will use it // indirectly through integration with the net/http package. See // ConfigureServer. That ConfigureServer call will likely be automatic // or available via an empty import in the future. // // See http://http2.github.io/ package http2 import ( "bufio" "fmt" "io" "net/http" "strconv" "sync" ) var VerboseLogs = false 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 const ( stateIdle streamState = iota stateOpen stateHalfClosedLocal stateHalfClosedRemote stateResvLocal stateResvRemote stateClosed ) var stateName = [...]string{ stateIdle: "Idle", stateOpen: "Open", stateHalfClosedLocal: "HalfClosedLocal", stateHalfClosedRemote: "HalfClosedRemote", stateResvLocal: "ResvLocal", stateResvRemote: "ResvRemote", 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)) } func validHeader(v string) bool { if len(v) == 0 { return false } for _, r := range v { // "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. " if r >= 127 || ('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} } var bufWriterPool = sync.Pool{ New: func() interface{} { // TODO: pick something better? this is a bit under // (3 x typical 1500 byte MTU) at least. return bufio.NewWriterSize(nil, 4<<10) }, } 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 } ================================================ FILE: vendor/golang.org/x/net/http2/http2_test.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "bytes" "errors" "flag" "fmt" "net/http" "os/exec" "strconv" "strings" "testing" "golang.org/x/net/http2/hpack" ) var knownFailing = flag.Bool("known_failing", false, "Run known-failing tests.") func condSkipFailingTest(t *testing.T) { if !*knownFailing { t.Skip("Skipping known-failing test without --known_failing") } } func init() { DebugGoroutines = true flag.BoolVar(&VerboseLogs, "verboseh2", false, "Verbose HTTP/2 debug logging") } func TestSettingString(t *testing.T) { tests := []struct { s Setting want string }{ {Setting{SettingMaxFrameSize, 123}, "[MAX_FRAME_SIZE = 123]"}, {Setting{1<<16 - 1, 123}, "[UNKNOWN_SETTING_65535 = 123]"}, } for i, tt := range tests { got := fmt.Sprint(tt.s) if got != tt.want { t.Errorf("%d. for %#v, string = %q; want %q", i, tt.s, got, tt.want) } } } type twriter struct { t testing.TB st *serverTester // optional } func (w twriter) Write(p []byte) (n int, err error) { if w.st != nil { ps := string(p) for _, phrase := range w.st.logFilter { if strings.Contains(ps, phrase) { return len(p), nil // no logging } } } w.t.Logf("%s", p) return len(p), nil } // like encodeHeader, but don't add implicit psuedo headers. func encodeHeaderNoImplicit(t *testing.T, headers ...string) []byte { var buf bytes.Buffer enc := hpack.NewEncoder(&buf) for len(headers) > 0 { k, v := headers[0], headers[1] headers = headers[2:] if err := enc.WriteField(hpack.HeaderField{Name: k, Value: v}); err != nil { t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) } } return buf.Bytes() } // Verify that curl has http2. func requireCurl(t *testing.T) { out, err := dockerLogs(curl(t, "--version")) if err != nil { t.Skipf("failed to determine curl features; skipping test") } if !strings.Contains(string(out), "HTTP2") { t.Skip("curl doesn't support HTTP2; skipping test") } } func curl(t *testing.T, args ...string) (container string) { out, err := exec.Command("docker", append([]string{"run", "-d", "--net=host", "gohttp2/curl"}, args...)...).CombinedOutput() if err != nil { t.Skipf("Failed to run curl in docker: %v, %s", err, out) } return strings.TrimSpace(string(out)) } type puppetCommand struct { fn func(w http.ResponseWriter, r *http.Request) done chan<- bool } type handlerPuppet struct { ch chan puppetCommand } func newHandlerPuppet() *handlerPuppet { return &handlerPuppet{ ch: make(chan puppetCommand), } } func (p *handlerPuppet) act(w http.ResponseWriter, r *http.Request) { for cmd := range p.ch { cmd.fn(w, r) cmd.done <- true } } func (p *handlerPuppet) done() { close(p.ch) } func (p *handlerPuppet) do(fn func(http.ResponseWriter, *http.Request)) { done := make(chan bool) p.ch <- puppetCommand{fn, done} <-done } func dockerLogs(container string) ([]byte, error) { out, err := exec.Command("docker", "wait", container).CombinedOutput() if err != nil { return out, err } exitStatus, err := strconv.Atoi(strings.TrimSpace(string(out))) if err != nil { return out, errors.New("unexpected exit status from docker wait") } out, err = exec.Command("docker", "logs", container).CombinedOutput() exec.Command("docker", "rm", container).Run() if err == nil && exitStatus != 0 { err = fmt.Errorf("exit status %d: %s", exitStatus, out) } return out, err } func kill(container string) { exec.Command("docker", "kill", container).Run() exec.Command("docker", "rm", container).Run() } ================================================ FILE: vendor/golang.org/x/net/http2/pipe.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "sync" ) type pipe struct { b buffer c sync.Cond m sync.Mutex } // Read waits until data is available and copies bytes // from the buffer into p. func (r *pipe) Read(p []byte) (n int, err error) { r.c.L.Lock() defer r.c.L.Unlock() for r.b.Len() == 0 && !r.b.closed { r.c.Wait() } return r.b.Read(p) } // 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 (w *pipe) Write(p []byte) (n int, err error) { w.c.L.Lock() defer w.c.L.Unlock() defer w.c.Signal() return w.b.Write(p) } func (c *pipe) Close(err error) { c.c.L.Lock() defer c.c.L.Unlock() defer c.c.Signal() c.b.Close(err) } ================================================ FILE: vendor/golang.org/x/net/http2/pipe_test.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "errors" "testing" ) func TestPipeClose(t *testing.T) { var p pipe p.c.L = &p.m a := errors.New("a") b := errors.New("b") p.Close(a) p.Close(b) _, err := p.Read(make([]byte, 1)) if err != a { t.Errorf("err = %v want %v", err, a) } } ================================================ FILE: vendor/golang.org/x/net/http2/priority_test.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "testing" ) func TestPriority(t *testing.T) { // A -> B // move A's parent to B streams := make(map[uint32]*stream) a := &stream{ parent: nil, weight: 16, } streams[1] = a b := &stream{ parent: a, weight: 16, } streams[2] = b adjustStreamPriority(streams, 1, PriorityParam{ Weight: 20, StreamDep: 2, }) if a.parent != b { t.Errorf("Expected A's parent to be B") } if a.weight != 20 { t.Errorf("Expected A's weight to be 20; got %d", a.weight) } if b.parent != nil { t.Errorf("Expected B to have no parent") } if b.weight != 16 { t.Errorf("Expected B's weight to be 16; got %d", b.weight) } } func TestPriorityExclusiveZero(t *testing.T) { // A B and C are all children of the 0 stream. // Exclusive reprioritization to any of the streams // should bring the rest of the streams under the // reprioritized stream streams := make(map[uint32]*stream) a := &stream{ parent: nil, weight: 16, } streams[1] = a b := &stream{ parent: nil, weight: 16, } streams[2] = b c := &stream{ parent: nil, weight: 16, } streams[3] = c adjustStreamPriority(streams, 3, PriorityParam{ Weight: 20, StreamDep: 0, Exclusive: true, }) if a.parent != c { t.Errorf("Expected A's parent to be C") } if a.weight != 16 { t.Errorf("Expected A's weight to be 16; got %d", a.weight) } if b.parent != c { t.Errorf("Expected B's parent to be C") } if b.weight != 16 { t.Errorf("Expected B's weight to be 16; got %d", b.weight) } if c.parent != nil { t.Errorf("Expected C to have no parent") } if c.weight != 20 { t.Errorf("Expected C's weight to be 20; got %d", b.weight) } } func TestPriorityOwnParent(t *testing.T) { streams := make(map[uint32]*stream) a := &stream{ parent: nil, weight: 16, } streams[1] = a b := &stream{ parent: a, weight: 16, } streams[2] = b adjustStreamPriority(streams, 1, PriorityParam{ Weight: 20, StreamDep: 1, }) if a.parent != nil { t.Errorf("Expected A's parent to be nil") } if a.weight != 20 { t.Errorf("Expected A's weight to be 20; got %d", a.weight) } if b.parent != a { t.Errorf("Expected B's parent to be A") } if b.weight != 16 { t.Errorf("Expected B's weight to be 16; got %d", b.weight) } } ================================================ FILE: vendor/golang.org/x/net/http2/server.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE // TODO: replace all <-sc.doneServing with reads from the stream's cw // instead, and make sure that on close we close all open // streams. then remove doneServing? // TODO: finish GOAWAY support. Consider each incoming frame type and // whether it should be ignored during a shutdown race. // TODO: disconnect idle clients. GFE seems to do 4 minutes. make // configurable? or maximum number of idle clients and remove the // oldest? // 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" "net" "net/http" "net/url" "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") errStreamBroken = errors.New("http2: stream broken") ) 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 } 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 } // 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) { if conf == nil { conf = new(Server) } if s.TLSConfig == nil { s.TLSConfig = new(tls.Config) } // 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. // Be sure we advertise tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 // at least. // TODO: enable PreferServerCipherSuites? if s.TLSConfig.CipherSuites != nil { const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 haveRequired := false for _, v := range s.TLSConfig.CipherSuites { if v == requiredCipher { haveRequired = true break } } if !haveRequired { s.TLSConfig.CipherSuites = append(s.TLSConfig.CipherSuites, requiredCipher) } } haveNPN := false for _, p := range s.TLSConfig.NextProtos { if p == NextProtoTLS { haveNPN = true break } } if !haveNPN { s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS) } // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers // to switch to "h2". s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14") 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.handleConn(hs, c, h) } s.TLSNextProto[NextProtoTLS] = protoHandler s.TLSNextProto["h2-14"] = protoHandler // temporary; see above. } func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) { sc := &serverConn{ srv: srv, hs: hs, conn: c, remoteAddrStr: c.RemoteAddr().String(), bw: newBufferedWriter(c), handler: h, streams: make(map[uint32]*stream), readFrameCh: make(chan frameAndGate), readFrameErrCh: make(chan error, 1), // must be buffered for 1 wantWriteFrameCh: make(chan frameWriteMsg, 8), wroteFrameCh: make(chan struct{}, 1), // buffered; one send in reading goroutine bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way doneServing: make(chan struct{}), advMaxStreams: srv.maxConcurrentStreams(), writeSched: writeScheduler{ maxFrameSize: initialMaxFrameSize, }, initialWindowSize: initialWindowSize, headerTableSize: initialHeaderTableSize, serveG: newGoroutineLock(), pushEnabled: true, } sc.flow.add(initialWindowSize) sc.inflow.add(initialWindowSize) sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf) sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField) fr := NewFramer(sc.bw, c) fr.SetMaxReadFrameSize(srv.maxReadFrameSize()) sc.framer = fr if tc, ok := c.(*tls.Conn); 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 !srv.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() } // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec. func isBadCipher(cipher uint16) bool { switch cipher { case tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: // 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" return true default: return false } } func (sc *serverConn) rejectConn(err ErrCode, debug string) { log.Printf("REJECTING conn: %v, %s", err, debug) // ignoring errors. hanging up anyway. sc.framer.WriteGoAway(0, err, []byte(debug)) sc.bw.Flush() sc.conn.Close() } // frameAndGates coordinates the readFrames and serve // goroutines. Because the Framer interface only permits the most // recently-read Frame from being accessed, the readFrames goroutine // blocks until it has a frame, passes it to serve, and then waits for // serve to be done with it before reading the next one. type frameAndGate struct { f Frame g gate } type serverConn struct { // Immutable: srv *Server hs *http.Server conn net.Conn bw *bufferedWriter // writing to conn handler http.Handler framer *Framer hpackDecoder *hpack.Decoder doneServing chan struct{} // closed when serverConn.serve ends readFrameCh chan frameAndGate // written by serverConn.readFrames readFrameErrCh chan error wantWriteFrameCh chan frameWriteMsg // from handlers -> serve wroteFrameCh chan struct{} // from writeFrameAsync -> serve, tickles more frame writes bodyReadCh chan bodyReadMsg // from handlers -> serve testHookCh chan func() // code 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 // 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 curOpenStreams uint32 // client's number of open streams maxStreamID uint32 // max ever seen streams map[uint32]*stream initialWindowSize int32 headerTableSize uint32 maxHeaderListSize uint32 // zero means unknown (default) canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case req requestParam // non-zero while reading request headers writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh needsFrameFlush bool // last frame write wasn't a flush writeSched writeScheduler inGoAway bool // we've started to or sent GOAWAY needToSendGoAway bool // we need to schedule a GOAWAY frame write goAwayCode ErrCode shutdownTimerCh <-chan time.Time // nil until used shutdownTimer *time.Timer // nil until used // Owned by the writeFrameAsync goroutine: headerWriteBuf bytes.Buffer hpackEncoder *hpack.Encoder } // requestParam is the state of the next request, initialized over // potentially several frames HEADERS + zero or more CONTINUATION // frames. type requestParam struct { // stream is non-nil if we're reading (HEADER or CONTINUATION) // frames for a request (but not DATA). stream *stream header http.Header method, path string scheme, authority string sawRegularHeader bool // saw a non-pseudo header already invalidHeader bool // an invalid header was seen } // 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: id uint32 body *pipe // non-nil if expecting DATA frames cw closeWaiter // closed wait stream transitions to closed state // 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 weight uint8 state streamState sentReset bool // only true once detached from streams map gotReset bool // only true once detacted from streams map } 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://http2.github.io/http2-spec/#rfc.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 <= sc.maxStreamID { return stateClosed, nil } return stateIdle, nil } 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...) } } func (sc *serverConn) condlogf(err error, format string, args ...interface{}) { if err == nil { return } str := err.Error() if err == io.EOF || strings.Contains(str, "use of closed network connection") { // Boring, expected errors. sc.vlogf(format, args...) } else { sc.logf(format, args...) } } func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) { sc.serveG.check() sc.vlogf("got header field %+v", f) switch { case !validHeader(f.Name): sc.req.invalidHeader = true case strings.HasPrefix(f.Name, ":"): if sc.req.sawRegularHeader { sc.logf("pseudo-header after regular header") sc.req.invalidHeader = true return } var dst *string switch f.Name { case ":method": dst = &sc.req.method case ":path": dst = &sc.req.path case ":scheme": dst = &sc.req.scheme case ":authority": dst = &sc.req.authority default: // 8.1.2.1 Pseudo-Header Fields // "Endpoints MUST treat a request or response // that contains undefined or invalid // pseudo-header fields as malformed (Section // 8.1.2.6)." sc.logf("invalid pseudo-header %q", f.Name) sc.req.invalidHeader = true return } if *dst != "" { sc.logf("duplicate pseudo-header %q sent", f.Name) sc.req.invalidHeader = true return } *dst = f.Value case f.Name == "cookie": sc.req.sawRegularHeader = true if s, ok := sc.req.header["Cookie"]; ok && len(s) == 1 { s[0] = s[0] + "; " + f.Value } else { sc.req.header.Add("Cookie", f.Value) } default: sc.req.sawRegularHeader = true sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value) } } 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 } // readFrames is the loop that reads incoming frames. // It's run on its own goroutine. func (sc *serverConn) readFrames() { g := make(gate, 1) for { f, err := sc.framer.ReadFrame() if err != nil { sc.readFrameErrCh <- err close(sc.readFrameCh) return } sc.readFrameCh <- frameAndGate{f, g} // We can't read another frame until this one is // processed, as the ReadFrame interface doesn't copy // memory. The Frame accessor methods access the last // frame's (shared) buffer. So we wait for the // serve goroutine to tell us it's done: g.Wait() } } // 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(wm frameWriteMsg) { err := wm.write.writeFrame(sc) if ch := wm.done; ch != nil { select { case ch <- err: default: panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write)) } } sc.wroteFrameCh <- struct{}{} // tickle frame selection scheduler } 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() { 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 sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs) sc.writeFrame(frameWriteMsg{ write: writeSettings{ {SettingMaxFrameSize, sc.srv.maxReadFrameSize()}, {SettingMaxConcurrentStreams, sc.advMaxStreams}, // TODO: more actual settings, notably // SettingInitialWindowSize, but then we also // want to bump up the conn window size the // same amount here right after the settings }, }) sc.unackedSettings++ if err := sc.readPreface(); err != nil { sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err) return } go sc.readFrames() // closed by defer sc.conn.Close above settingsTimer := time.NewTimer(firstSettingsTimeout) for { select { case wm := <-sc.wantWriteFrameCh: sc.writeFrame(wm) case <-sc.wroteFrameCh: if sc.writingFrame != true { panic("internal error: expected to be already writing a frame") } sc.writingFrame = false sc.scheduleFrameWrite() case fg, ok := <-sc.readFrameCh: if !ok { sc.readFrameCh = nil } if !sc.processFrameFromReader(fg, ok) { return } if settingsTimer.C != nil { settingsTimer.Stop() settingsTimer.C = nil } case m := <-sc.bodyReadCh: sc.noteBodyRead(m.st, m.n) case <-settingsTimer.C: sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr()) return case <-sc.shutdownTimerCh: sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr()) return case fn := <-sc.testHookCh: fn() } } } // 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 { sc.vlogf("client %v said hello", sc.conn.RemoteAddr()) } return err } } // writeDataFromHandler writes the data described in req to stream.id. // // The provided ch is used to avoid allocating new channels for each // write operation. It's expected that the caller reuses writeData and ch // over time. // // The flow control currently happens in the Handler where it waits // for 1 or more bytes to be available to then write here. So at this // point we know that we have flow control. But this might have to // change when priority is implemented, so the serve goroutine knows // the total amount of bytes waiting to be sent and can can have more // scheduling decisions available. func (sc *serverConn) writeDataFromHandler(stream *stream, writeData *writeData, ch chan error) error { sc.writeFrameFromHandler(frameWriteMsg{ write: writeData, stream: stream, done: ch, }) select { case err := <-ch: return err case <-sc.doneServing: return errClientDisconnected case <-stream.cw: return errStreamBroken } } // writeFrameFromHandler sends wm 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(wm frameWriteMsg) { sc.serveG.checkNotOn() // NOT select { case sc.wantWriteFrameCh <- wm: case <-sc.doneServing: // Client has closed their connection to the server. } } // 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(wm frameWriteMsg) { sc.serveG.check() sc.writeSched.add(wm) sc.scheduleFrameWrite() } // startFrameWrite starts a goroutine to write wm (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 wm. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) { sc.serveG.check() if sc.writingFrame { panic("internal error: can only be writing one frame at a time") } sc.writingFrame = true st := wm.stream if st != nil { switch st.state { case stateHalfClosedLocal: panic("internal error: attempt to send frame on half-closed-local stream") case stateClosed: if st.sentReset || st.gotReset { // Skip this frame. But fake the frame write to reschedule: sc.wroteFrameCh <- struct{}{} return } panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm)) } } sc.needsFrameFlush = true if endsStream(wm.write) { 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 finishing writing to 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. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream errCancel := StreamError{st.id, ErrCodeCancel} sc.resetStream(errCancel) case stateHalfClosedRemote: sc.closeStream(st, nil) } } go sc.writeFrameAsync(wm) } // 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 { return } if sc.needToSendGoAway { sc.needToSendGoAway = false sc.startFrameWrite(frameWriteMsg{ write: &writeGoAway{ maxStreamID: sc.maxStreamID, code: sc.goAwayCode, }, }) return } if sc.needToSendSettingsAck { sc.needToSendSettingsAck = false sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}}) return } if !sc.inGoAway { if wm, ok := sc.writeSched.take(); ok { sc.startFrameWrite(wm) return } } if sc.needsFrameFlush { sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}}) sc.needsFrameFlush = false // after startFrameWrite, since it sets this true return } } func (sc *serverConn) goAway(code ErrCode) { sc.serveG.check() if sc.inGoAway { return } if code != ErrCodeNo { sc.shutDownIn(250 * time.Millisecond) } else { // TODO: configurable sc.shutDownIn(1 * time.Second) } sc.inGoAway = true sc.needToSendGoAway = true sc.goAwayCode = code sc.scheduleFrameWrite() } func (sc *serverConn) shutDownIn(d time.Duration) { sc.serveG.check() sc.shutdownTimer = time.NewTimer(d) sc.shutdownTimerCh = sc.shutdownTimer.C } func (sc *serverConn) resetStream(se StreamError) { sc.serveG.check() sc.writeFrame(frameWriteMsg{write: se}) if st, ok := sc.streams[se.StreamID]; ok { st.sentReset = true sc.closeStream(st, se) } } // curHeaderStreamID returns the stream ID of the header block we're // currently in the middle of reading. If this returns non-zero, the // next frame must be a CONTINUATION with this stream id. func (sc *serverConn) curHeaderStreamID() uint32 { sc.serveG.check() st := sc.req.stream if st == nil { return 0 } return st.id } // 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(fg frameAndGate, fgValid bool) bool { sc.serveG.check() var clientGone bool var err error if !fgValid { err = <-sc.readFrameErrCh if err == ErrFrameTooLarge { sc.goAway(ErrCodeFrameSize) return true // goAway will close the loop } clientGone = err == io.EOF || strings.Contains(err.Error(), "use of closed network connection") 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 } } if fgValid { f := fg.f sc.vlogf("got %v: %#v", f.Header(), f) err = sc.processFrame(f) fg.g.Done() // unblock the readFrames goroutine 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("%v: %v", sc.conn.RemoteAddr(), ev) sc.goAway(ErrCode(ev)) return true // goAway will handle shutdown default: if !fgValid { sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err) } else { sc.logf("disconnection due to other error: %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 } if s := sc.curHeaderStreamID(); s != 0 { if cf, ok := f.(*ContinuationFrame); !ok { return ConnectionError(ErrCodeProtocol) } else if cf.Header().StreamID != s { return ConnectionError(ErrCodeProtocol) } } switch f := f.(type) { case *SettingsFrame: return sc.processSettings(f) case *HeadersFrame: return sc.processHeaders(f) case *ContinuationFrame: return sc.processContinuation(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 *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: log.Printf("Ignoring frame: %v", f.Header()) return nil } } func (sc *serverConn) processPing(f *PingFrame) error { sc.serveG.check() if f.Flags.Has(FlagSettingsAck) { // 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) } sc.writeFrame(frameWriteMsg{write: writePingAck{f}}) return nil } func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error { sc.serveG.check() switch { case f.StreamID != 0: // stream-level flow control st := sc.streams[f.StreamID] 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.gotReset = true 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 sc.curOpenStreams-- delete(sc.streams, st.id) if p := st.body; p != nil { p.Close(err) } st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc sc.writeSched.forgetStream(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 } sc.vlogf("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.writeSched.maxFrameSize = s.Val case SettingMaxHeaderListSize: sc.maxHeaderListSize = s.Val default: // Unknown setting: "An endpoint that receives a SETTINGS // frame with any unknown or unsupported identifier MUST // ignore that setting." } 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.initialWindowSize sc.initialWindowSize = int32(val) growth := sc.initialWindowSize - 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 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 st, ok := sc.streams[id] if !ok || st.state != stateOpen { // 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. return StreamError{id, ErrCodeStreamClosed} } if st.body == nil { panic("internal error: should have a body in this state") } data := f.Data() // Sender sending more than they'd declared? if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes { st.body.Close(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes)) return StreamError{id, ErrCodeStreamClosed} } if len(data) > 0 { // Check whether the client has flow control quota. if int(st.inflow.available()) < len(data) { return StreamError{id, ErrCodeFlowControl} } st.inflow.take(int32(len(data))) 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)) } if f.StreamEnded() { if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes { st.body.Close(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes", st.declBodyBytes, st.bodyBytes)) } else { st.body.Close(io.EOF) } st.state = stateHalfClosedRemote } return nil } func (sc *serverConn) processHeaders(f *HeadersFrame) error { sc.serveG.check() id := f.Header().StreamID if sc.inGoAway { // Ignore. return nil } // http://http2.github.io/http2-spec/#rfc.section.5.1.1 if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil { // Streams initiated by a client MUST use odd-numbered // stream identifiers. [...] 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. return ConnectionError(ErrCodeProtocol) } if id > sc.maxStreamID { sc.maxStreamID = id } st := &stream{ id: id, state: stateOpen, } if f.StreamEnded() { st.state = stateHalfClosedRemote } st.cw.Init() st.flow.conn = &sc.flow // link to conn-level counter st.flow.add(sc.initialWindowSize) st.inflow.conn = &sc.inflow // link to conn-level counter st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings sc.streams[id] = st if f.HasPriority() { adjustStreamPriority(sc.streams, st.id, f.Priority) } sc.curOpenStreams++ sc.req = requestParam{ stream: st, header: make(http.Header), } return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded()) } func (sc *serverConn) processContinuation(f *ContinuationFrame) error { sc.serveG.check() st := sc.streams[f.Header().StreamID] if st == nil || sc.curHeaderStreamID() != st.id { return ConnectionError(ErrCodeProtocol) } return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded()) } func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error { sc.serveG.check() if _, err := sc.hpackDecoder.Write(frag); err != nil { // TODO: convert to stream error I assume? return err } if !end { return nil } if err := sc.hpackDecoder.Close(); err != nil { // TODO: convert to stream error I assume? return err } defer sc.resetPendingRequest() if sc.curOpenStreams > sc.advMaxStreams { // "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.unackedSettings == 0 { // They should know better. return StreamError{st.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{st.id, ErrCodeRefusedStream} } rw, req, err := sc.newWriterAndRequest() if err != nil { return err } st.body = req.Body.(*requestBody).pipe // may be nil st.declBodyBytes = req.ContentLength go sc.runHandler(rw, req) return nil } func (sc *serverConn) processPriority(f *PriorityFrame) error { adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam) return nil } func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) { st, ok := streams[streamID] if !ok { // TODO: not quite correct (this streamID might // already exist in the dep tree, but be closed), but // close enough for now. return } st.weight = priority.Weight parent := streams[priority.StreamDep] // might be nil if parent == st { // if client tries to set this stream to be the parent of itself // ignore and keep going 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. for piter := parent; piter != nil; piter = piter.parent { if piter == st { parent.parent = st.parent break } } st.parent = parent if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) { for _, openStream := range streams { if openStream != st && openStream.parent == st.parent { openStream.parent = st } } } } // resetPendingRequest zeros out all state related to a HEADERS frame // and its zero or more CONTINUATION frames sent to start a new // request. func (sc *serverConn) resetPendingRequest() { sc.serveG.check() sc.req = requestParam{} } func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) { sc.serveG.check() rp := &sc.req if rp.invalidHeader || 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{rp.stream.id, ErrCodeProtocol} } var tlsState *tls.ConnectionState // nil if not scheme https if rp.scheme == "https" { tlsState = sc.tlsState } authority := rp.authority if authority == "" { authority = rp.header.Get("Host") } needsContinue := rp.header.Get("Expect") == "100-continue" if needsContinue { rp.header.Del("Expect") } bodyOpen := rp.stream.state == stateOpen body := &requestBody{ conn: sc, stream: rp.stream, needsContinue: needsContinue, } // TODO: handle asterisk '*' requests + test url, err := url.ParseRequestURI(rp.path) if err != nil { // TODO: find the right error code? return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol} } req := &http.Request{ Method: rp.method, URL: url, RemoteAddr: sc.remoteAddrStr, Header: rp.header, RequestURI: rp.path, Proto: "HTTP/2.0", ProtoMajor: 2, ProtoMinor: 0, TLS: tlsState, Host: authority, Body: body, } if bodyOpen { body.pipe = &pipe{ b: buffer{buf: make([]byte, initialWindowSize)}, // TODO: share/remove XXX } body.pipe.c.L = &body.pipe.m if vv, ok := rp.header["Content-Length"]; ok { req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64) } else { req.ContentLength = -1 } } 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 = rp.stream rws.req = req rws.body = body rws.frameWriteCh = make(chan error, 1) rw := &responseWriter{rws: rws} return rw, req, nil } // Run on its own goroutine. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) { defer rw.handlerDone() // TODO: catch panics like net/http.Server sc.handler.ServeHTTP(rw, req) } // called from handler goroutines. // h may be nil. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders, tempCh chan 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 = tempCh } sc.writeFrameFromHandler(frameWriteMsg{ write: headerData, stream: st, done: errc, }) if errc != nil { select { case <-errc: // Ignore. Just for synchronization. // Any error will be handled in the writing goroutine. case <-sc.doneServing: // Client has closed the connection. } } } // called from handler goroutines. func (sc *serverConn) write100ContinueHeaders(st *stream) { sc.writeFrameFromHandler(frameWriteMsg{ 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) { sc.serveG.checkNotOn() // NOT on sc.bodyReadCh <- bodyReadMsg{st, n} } 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(frameWriteMsg{ 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?") } } type requestBody struct { stream *stream conn *serverConn closed bool 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.pipe.Close(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 { return 0, io.EOF } n, err = b.pipe.Read(p) if n > 0 { b.conn.noteBodyReadFromHandler(b.stream, n) } 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 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 curWrite writeData frameWriteCh chan error // re-used whenever we need to block on a frame being written 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) } // 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) } if !rws.sentHeader { rws.sentHeader = true var ctype, clen string // implicit ones, if we can calculate it if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" { clen = strconv.Itoa(len(p)) } if rws.snapHeader.Get("Content-Type") == "" { ctype = http.DetectContentType(p) } endStream := rws.handlerDone && len(p) == 0 rws.conn.writeHeaders(rws.stream, &writeResHeaders{ streamID: rws.stream.id, httpResCode: rws.status, h: rws.snapHeader, endStream: endStream, contentType: ctype, contentLength: clen, }, rws.frameWriteCh) if endStream { return 0, nil } } if len(p) == 0 && !rws.handlerDone { return 0, nil } curWrite := &rws.curWrite curWrite.streamID = rws.stream.id curWrite.p = p curWrite.endStream = rws.handlerDone if err := rws.conn.writeDataFromHandler(rws.stream, curWrite, rws.frameWriteCh); err != nil { return 0, err } return len(p), nil } 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 go func() { rws.stream.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 dataB != nil { return rws.bw.Write(dataB) } else { return rws.bw.WriteString(dataS) } } func (w *responseWriter) handlerDone() { rws := w.rws if rws == nil { panic("handlerDone called twice") } rws.handlerDone = true w.Flush() w.rws = nil responseWriterStatePool.Put(rws) } ================================================ FILE: vendor/golang.org/x/net/http2/server_test.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "bytes" "crypto/tls" "errors" "flag" "fmt" "io" "io/ioutil" "log" "net" "net/http" "net/http/httptest" "os" "reflect" "runtime" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "golang.org/x/net/http2/hpack" ) var stderrVerbose = flag.Bool("stderr_verbose", false, "Mirror verbosity to stderr, unbuffered") type serverTester struct { cc net.Conn // client conn t testing.TB ts *httptest.Server fr *Framer logBuf *bytes.Buffer logFilter []string // substrings to filter out scMu sync.Mutex // guards sc sc *serverConn // writing headers: headerBuf bytes.Buffer hpackEnc *hpack.Encoder // reading frames: frc chan Frame frErrc chan error readTimer *time.Timer } func init() { testHookOnPanicMu = new(sync.Mutex) } func resetHooks() { testHookOnPanicMu.Lock() testHookOnPanic = nil testHookOnPanicMu.Unlock() } type serverTesterOpt string var optOnlyServer = serverTesterOpt("only_server") func newServerTester(t testing.TB, handler http.HandlerFunc, opts ...interface{}) *serverTester { resetHooks() logBuf := new(bytes.Buffer) ts := httptest.NewUnstartedServer(handler) tlsConfig := &tls.Config{ InsecureSkipVerify: true, // The h2-14 is temporary, until curl is updated. (as used by unit tests // in Docker) NextProtos: []string{NextProtoTLS, "h2-14"}, } onlyServer := false for _, opt := range opts { switch v := opt.(type) { case func(*tls.Config): v(tlsConfig) case func(*httptest.Server): v(ts) case serverTesterOpt: onlyServer = (v == optOnlyServer) default: t.Fatalf("unknown newServerTester option type %T", v) } } ConfigureServer(ts.Config, &Server{}) st := &serverTester{ t: t, ts: ts, logBuf: logBuf, frc: make(chan Frame, 1), frErrc: make(chan error, 1), } st.hpackEnc = hpack.NewEncoder(&st.headerBuf) var stderrv io.Writer = ioutil.Discard if *stderrVerbose { stderrv = os.Stderr } ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config ts.Config.ErrorLog = log.New(io.MultiWriter(stderrv, twriter{t: t, st: st}, logBuf), "", log.LstdFlags) ts.StartTLS() if VerboseLogs { t.Logf("Running test server at: %s", ts.URL) } testHookGetServerConn = func(v *serverConn) { st.scMu.Lock() defer st.scMu.Unlock() st.sc = v st.sc.testHookCh = make(chan func()) } log.SetOutput(io.MultiWriter(stderrv, twriter{t: t, st: st})) if !onlyServer { cc, err := tls.Dial("tcp", ts.Listener.Addr().String(), tlsConfig) if err != nil { t.Fatal(err) } st.cc = cc st.fr = NewFramer(cc, cc) } return st } func (st *serverTester) closeConn() { st.scMu.Lock() defer st.scMu.Unlock() st.sc.conn.Close() } func (st *serverTester) addLogFilter(phrase string) { st.logFilter = append(st.logFilter, phrase) } func (st *serverTester) stream(id uint32) *stream { ch := make(chan *stream, 1) st.sc.testHookCh <- func() { ch <- st.sc.streams[id] } return <-ch } func (st *serverTester) streamState(id uint32) streamState { ch := make(chan streamState, 1) st.sc.testHookCh <- func() { state, _ := st.sc.state(id) ch <- state } return <-ch } func (st *serverTester) Close() { st.ts.Close() if st.cc != nil { st.cc.Close() } log.SetOutput(os.Stderr) } // greet initiates the client's HTTP/2 connection into a state where // frames may be sent. func (st *serverTester) greet() { st.writePreface() st.writeInitialSettings() st.wantSettings() st.writeSettingsAck() st.wantSettingsAck() } func (st *serverTester) writePreface() { n, err := st.cc.Write(clientPreface) if err != nil { st.t.Fatalf("Error writing client preface: %v", err) } if n != len(clientPreface) { st.t.Fatalf("Writing client preface, wrote %d bytes; want %d", n, len(clientPreface)) } } func (st *serverTester) writeInitialSettings() { if err := st.fr.WriteSettings(); err != nil { st.t.Fatalf("Error writing initial SETTINGS frame from client to server: %v", err) } } func (st *serverTester) writeSettingsAck() { if err := st.fr.WriteSettingsAck(); err != nil { st.t.Fatalf("Error writing ACK of server's SETTINGS: %v", err) } } func (st *serverTester) writeHeaders(p HeadersFrameParam) { if err := st.fr.WriteHeaders(p); err != nil { st.t.Fatalf("Error writing HEADERS: %v", err) } } func (st *serverTester) encodeHeaderField(k, v string) { err := st.hpackEnc.WriteField(hpack.HeaderField{Name: k, Value: v}) if err != nil { st.t.Fatalf("HPACK encoding error for %q/%q: %v", k, v, err) } } // encodeHeader encodes headers and returns their HPACK bytes. headers // must contain an even number of key/value pairs. There may be // multiple pairs for keys (e.g. "cookie"). The :method, :path, and // :scheme headers default to GET, / and https. func (st *serverTester) encodeHeader(headers ...string) []byte { if len(headers)%2 == 1 { panic("odd number of kv args") } st.headerBuf.Reset() if len(headers) == 0 { // Fast path, mostly for benchmarks, so test code doesn't pollute // profiles when we're looking to improve server allocations. st.encodeHeaderField(":method", "GET") st.encodeHeaderField(":path", "/") st.encodeHeaderField(":scheme", "https") return st.headerBuf.Bytes() } if len(headers) == 2 && headers[0] == ":method" { // Another fast path for benchmarks. st.encodeHeaderField(":method", headers[1]) st.encodeHeaderField(":path", "/") st.encodeHeaderField(":scheme", "https") return st.headerBuf.Bytes() } pseudoCount := map[string]int{} keys := []string{":method", ":path", ":scheme"} vals := map[string][]string{ ":method": {"GET"}, ":path": {"/"}, ":scheme": {"https"}, } for len(headers) > 0 { k, v := headers[0], headers[1] headers = headers[2:] if _, ok := vals[k]; !ok { keys = append(keys, k) } if strings.HasPrefix(k, ":") { pseudoCount[k]++ if pseudoCount[k] == 1 { vals[k] = []string{v} } else { // Allows testing of invalid headers w/ dup pseudo fields. vals[k] = append(vals[k], v) } } else { vals[k] = append(vals[k], v) } } st.headerBuf.Reset() for _, k := range keys { for _, v := range vals[k] { st.encodeHeaderField(k, v) } } return st.headerBuf.Bytes() } // bodylessReq1 writes a HEADERS frames with StreamID 1 and EndStream and EndHeaders set. func (st *serverTester) bodylessReq1(headers ...string) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(headers...), EndStream: true, EndHeaders: true, }) } func (st *serverTester) writeData(streamID uint32, endStream bool, data []byte) { if err := st.fr.WriteData(streamID, endStream, data); err != nil { st.t.Fatalf("Error writing DATA: %v", err) } } func (st *serverTester) readFrame() (Frame, error) { go func() { fr, err := st.fr.ReadFrame() if err != nil { st.frErrc <- err } else { st.frc <- fr } }() t := st.readTimer if t == nil { t = time.NewTimer(2 * time.Second) st.readTimer = t } t.Reset(2 * time.Second) defer t.Stop() select { case f := <-st.frc: return f, nil case err := <-st.frErrc: return nil, err case <-t.C: return nil, errors.New("timeout waiting for frame") } } func (st *serverTester) wantHeaders() *HeadersFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a HEADERS frame: %v", err) } hf, ok := f.(*HeadersFrame) if !ok { st.t.Fatalf("got a %T; want *HeadersFrame", f) } return hf } func (st *serverTester) wantContinuation() *ContinuationFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a CONTINUATION frame: %v", err) } cf, ok := f.(*ContinuationFrame) if !ok { st.t.Fatalf("got a %T; want *ContinuationFrame", f) } return cf } func (st *serverTester) wantData() *DataFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a DATA frame: %v", err) } df, ok := f.(*DataFrame) if !ok { st.t.Fatalf("got a %T; want *DataFrame", f) } return df } func (st *serverTester) wantSettings() *SettingsFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a SETTINGS frame: %v", err) } sf, ok := f.(*SettingsFrame) if !ok { st.t.Fatalf("got a %T; want *SettingsFrame", f) } return sf } func (st *serverTester) wantPing() *PingFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a PING frame: %v", err) } pf, ok := f.(*PingFrame) if !ok { st.t.Fatalf("got a %T; want *PingFrame", f) } return pf } func (st *serverTester) wantGoAway() *GoAwayFrame { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a GOAWAY frame: %v", err) } gf, ok := f.(*GoAwayFrame) if !ok { st.t.Fatalf("got a %T; want *GoAwayFrame", f) } return gf } func (st *serverTester) wantRSTStream(streamID uint32, errCode ErrCode) { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting an RSTStream frame: %v", err) } rs, ok := f.(*RSTStreamFrame) if !ok { st.t.Fatalf("got a %T; want *RSTStreamFrame", f) } if rs.FrameHeader.StreamID != streamID { st.t.Fatalf("RSTStream StreamID = %d; want %d", rs.FrameHeader.StreamID, streamID) } if rs.ErrCode != errCode { st.t.Fatalf("RSTStream ErrCode = %d (%s); want %d (%s)", rs.ErrCode, rs.ErrCode, errCode, errCode) } } func (st *serverTester) wantWindowUpdate(streamID, incr uint32) { f, err := st.readFrame() if err != nil { st.t.Fatalf("Error while expecting a WINDOW_UPDATE frame: %v", err) } wu, ok := f.(*WindowUpdateFrame) if !ok { st.t.Fatalf("got a %T; want *WindowUpdateFrame", f) } if wu.FrameHeader.StreamID != streamID { st.t.Fatalf("WindowUpdate StreamID = %d; want %d", wu.FrameHeader.StreamID, streamID) } if wu.Increment != incr { st.t.Fatalf("WindowUpdate increment = %d; want %d", wu.Increment, incr) } } func (st *serverTester) wantSettingsAck() { f, err := st.readFrame() if err != nil { st.t.Fatal(err) } sf, ok := f.(*SettingsFrame) if !ok { st.t.Fatalf("Wanting a settings ACK, received a %T", f) } if !sf.Header().Flags.Has(FlagSettingsAck) { st.t.Fatal("Settings Frame didn't have ACK set") } } func TestServer(t *testing.T) { gotReq := make(chan bool, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Foo", "Bar") gotReq <- true }) defer st.Close() covers("3.5", ` The server connection preface consists of a potentially empty SETTINGS frame ([SETTINGS]) that MUST be the first frame the server sends in the HTTP/2 connection. `) st.writePreface() st.writeInitialSettings() st.wantSettings() st.writeSettingsAck() st.wantSettingsAck() st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(), EndStream: true, // no DATA frames EndHeaders: true, }) select { case <-gotReq: case <-time.After(2 * time.Second): t.Error("timeout waiting for request") } } func TestServer_Request_Get(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader("foo-bar", "some-value"), EndStream: true, // no DATA frames EndHeaders: true, }) }, func(r *http.Request) { if r.Method != "GET" { t.Errorf("Method = %q; want GET", r.Method) } if r.URL.Path != "/" { t.Errorf("URL.Path = %q; want /", r.URL.Path) } if r.ContentLength != 0 { t.Errorf("ContentLength = %v; want 0", r.ContentLength) } if r.Close { t.Error("Close = true; want false") } if !strings.Contains(r.RemoteAddr, ":") { t.Errorf("RemoteAddr = %q; want something with a colon", r.RemoteAddr) } if r.Proto != "HTTP/2.0" || r.ProtoMajor != 2 || r.ProtoMinor != 0 { t.Errorf("Proto = %q Major=%v,Minor=%v; want HTTP/2.0", r.Proto, r.ProtoMajor, r.ProtoMinor) } wantHeader := http.Header{ "Foo-Bar": []string{"some-value"}, } if !reflect.DeepEqual(r.Header, wantHeader) { t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) } if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { t.Errorf("Read = %d, %v; want 0, EOF", n, err) } }) } func TestServer_Request_Get_PathSlashes(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":path", "/%2f/"), EndStream: true, // no DATA frames EndHeaders: true, }) }, func(r *http.Request) { if r.RequestURI != "/%2f/" { t.Errorf("RequestURI = %q; want /%%2f/", r.RequestURI) } if r.URL.Path != "///" { t.Errorf("URL.Path = %q; want ///", r.URL.Path) } }) } // TODO: add a test with EndStream=true on the HEADERS but setting a // Content-Length anyway. Should we just omit it and force it to // zero? func TestServer_Request_Post_NoContentLength_EndStream(t *testing.T) { testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if r.Method != "POST" { t.Errorf("Method = %q; want POST", r.Method) } if r.ContentLength != 0 { t.Errorf("ContentLength = %v; want 0", r.ContentLength) } if n, err := r.Body.Read([]byte(" ")); err != io.EOF || n != 0 { t.Errorf("Read = %d, %v; want 0, EOF", n, err) } }) } func TestServer_Request_Post_Body_ImmediateEOF(t *testing.T) { testBodyContents(t, -1, "", func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, nil) // just kidding. empty body. }) } func TestServer_Request_Post_Body_OneData(t *testing.T) { const content = "Some content" testBodyContents(t, -1, content, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte(content)) }) } func TestServer_Request_Post_Body_TwoData(t *testing.T) { const content = "Some content" testBodyContents(t, -1, content, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, false, []byte(content[:5])) st.writeData(1, true, []byte(content[5:])) }) } func TestServer_Request_Post_Body_ContentLength_Correct(t *testing.T) { const content = "Some content" testBodyContents(t, int64(len(content)), content, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader( ":method", "POST", "content-length", strconv.Itoa(len(content)), ), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte(content)) }) } func TestServer_Request_Post_Body_ContentLength_TooLarge(t *testing.T) { testBodyContentsFail(t, 3, "request declared a Content-Length of 3 but only wrote 2 bytes", func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader( ":method", "POST", "content-length", "3", ), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte("12")) }) } func TestServer_Request_Post_Body_ContentLength_TooSmall(t *testing.T) { testBodyContentsFail(t, 4, "sender tried to send more than declared Content-Length of 4 bytes", func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader( ":method", "POST", "content-length", "4", ), EndStream: false, // to say DATA frames are coming EndHeaders: true, }) st.writeData(1, true, []byte("12345")) }) } func testBodyContents(t *testing.T, wantContentLength int64, wantBody string, write func(st *serverTester)) { testServerRequest(t, write, func(r *http.Request) { if r.Method != "POST" { t.Errorf("Method = %q; want POST", r.Method) } if r.ContentLength != wantContentLength { t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) } all, err := ioutil.ReadAll(r.Body) if err != nil { t.Fatal(err) } if string(all) != wantBody { t.Errorf("Read = %q; want %q", all, wantBody) } if err := r.Body.Close(); err != nil { t.Fatalf("Close: %v", err) } }) } func testBodyContentsFail(t *testing.T, wantContentLength int64, wantReadError string, write func(st *serverTester)) { testServerRequest(t, write, func(r *http.Request) { if r.Method != "POST" { t.Errorf("Method = %q; want POST", r.Method) } if r.ContentLength != wantContentLength { t.Errorf("ContentLength = %v; want %d", r.ContentLength, wantContentLength) } all, err := ioutil.ReadAll(r.Body) if err == nil { t.Fatalf("expected an error (%q) reading from the body. Successfully read %q instead.", wantReadError, all) } if !strings.Contains(err.Error(), wantReadError) { t.Fatalf("Body.Read = %v; want substring %q", err, wantReadError) } if err := r.Body.Close(); err != nil { t.Fatalf("Close: %v", err) } }) } // Using a Host header, instead of :authority func TestServer_Request_Get_Host(t *testing.T) { const host = "example.com" testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader("host", host), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if r.Host != host { t.Errorf("Host = %q; want %q", r.Host, host) } }) } // Using an :authority pseudo-header, instead of Host func TestServer_Request_Get_Authority(t *testing.T) { const host = "example.com" testServerRequest(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":authority", host), EndStream: true, EndHeaders: true, }) }, func(r *http.Request) { if r.Host != host { t.Errorf("Host = %q; want %q", r.Host, host) } }) } func TestServer_Request_WithContinuation(t *testing.T) { wantHeader := http.Header{ "Foo-One": []string{"value-one"}, "Foo-Two": []string{"value-two"}, "Foo-Three": []string{"value-three"}, } testServerRequest(t, func(st *serverTester) { fullHeaders := st.encodeHeader( "foo-one", "value-one", "foo-two", "value-two", "foo-three", "value-three", ) remain := fullHeaders chunks := 0 for len(remain) > 0 { const maxChunkSize = 5 chunk := remain if len(chunk) > maxChunkSize { chunk = chunk[:maxChunkSize] } remain = remain[len(chunk):] if chunks == 0 { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: chunk, EndStream: true, // no DATA frames EndHeaders: false, // we'll have continuation frames }) } else { err := st.fr.WriteContinuation(1, len(remain) == 0, chunk) if err != nil { t.Fatal(err) } } chunks++ } if chunks < 2 { t.Fatal("too few chunks") } }, func(r *http.Request) { if !reflect.DeepEqual(r.Header, wantHeader) { t.Errorf("Header = %#v; want %#v", r.Header, wantHeader) } }) } // Concatenated cookie headers. ("8.1.2.5 Compressing the Cookie Header Field") func TestServer_Request_CookieConcat(t *testing.T) { const host = "example.com" testServerRequest(t, func(st *serverTester) { st.bodylessReq1( ":authority", host, "cookie", "a=b", "cookie", "c=d", "cookie", "e=f", ) }, func(r *http.Request) { const want = "a=b; c=d; e=f" if got := r.Header.Get("Cookie"); got != want { t.Errorf("Cookie = %q; want %q", got, want) } }) } func TestServer_Request_Reject_CapitalHeader(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1("UPPER", "v") }) } func TestServer_Request_Reject_Pseudo_Missing_method(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":method", "") }) } func TestServer_Request_Reject_Pseudo_ExactlyOne(t *testing.T) { // 8.1.2.3 Request Pseudo-Header Fields // "All HTTP/2 requests MUST include exactly one valid value" ... testRejectRequest(t, func(st *serverTester) { st.addLogFilter("duplicate pseudo-header") st.bodylessReq1(":method", "GET", ":method", "POST") }) } func TestServer_Request_Reject_Pseudo_AfterRegular(t *testing.T) { // 8.1.2.3 Request Pseudo-Header Fields // "All pseudo-header fields MUST appear in the header block // before regular header fields. Any request or response that // contains a pseudo-header field that appears in a header // block after a regular header field MUST be treated as // malformed (Section 8.1.2.6)." testRejectRequest(t, func(st *serverTester) { st.addLogFilter("pseudo-header after regular header") var buf bytes.Buffer enc := hpack.NewEncoder(&buf) enc.WriteField(hpack.HeaderField{Name: ":method", Value: "GET"}) enc.WriteField(hpack.HeaderField{Name: "regular", Value: "foobar"}) enc.WriteField(hpack.HeaderField{Name: ":path", Value: "/"}) enc.WriteField(hpack.HeaderField{Name: ":scheme", Value: "https"}) st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: buf.Bytes(), EndStream: true, EndHeaders: true, }) }) } func TestServer_Request_Reject_Pseudo_Missing_path(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":path", "") }) } func TestServer_Request_Reject_Pseudo_Missing_scheme(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "") }) } func TestServer_Request_Reject_Pseudo_scheme_invalid(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.bodylessReq1(":scheme", "bogus") }) } func TestServer_Request_Reject_Pseudo_Unknown(t *testing.T) { testRejectRequest(t, func(st *serverTester) { st.addLogFilter(`invalid pseudo-header ":unknown_thing"`) st.bodylessReq1(":unknown_thing", "") }) } func testRejectRequest(t *testing.T, send func(*serverTester)) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { t.Fatal("server request made it to handler; should've been rejected") }) defer st.Close() st.greet() send(st) st.wantRSTStream(1, ErrCodeProtocol) } func TestServer_Ping(t *testing.T) { st := newServerTester(t, nil) defer st.Close() st.greet() // Server should ignore this one, since it has ACK set. ackPingData := [8]byte{1, 2, 4, 8, 16, 32, 64, 128} if err := st.fr.WritePing(true, ackPingData); err != nil { t.Fatal(err) } // But the server should reply to this one, since ACK is false. pingData := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} if err := st.fr.WritePing(false, pingData); err != nil { t.Fatal(err) } pf := st.wantPing() if !pf.Flags.Has(FlagPingAck) { t.Error("response ping doesn't have ACK set") } if pf.Data != pingData { t.Errorf("response ping has data %q; want %q", pf.Data, pingData) } } func TestServer_RejectsLargeFrames(t *testing.T) { st := newServerTester(t, nil) defer st.Close() st.greet() // Write too large of a frame (too large by one byte) // We ignore the return value because it's expected that the server // will only read the first 9 bytes (the headre) and then disconnect. st.fr.WriteRawFrame(0xff, 0, 0, make([]byte, defaultMaxReadFrameSize+1)) gf := st.wantGoAway() if gf.ErrCode != ErrCodeFrameSize { t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFrameSize) } } func TestServer_Handler_Sends_WindowUpdate(t *testing.T) { puppet := newHandlerPuppet() st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { puppet.act(w, r) }) defer st.Close() defer puppet.done() st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // data coming EndHeaders: true, }) st.writeData(1, false, []byte("abcdef")) puppet.do(readBodyHandler(t, "abc")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(1, 3) puppet.do(readBodyHandler(t, "def")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(1, 3) st.writeData(1, true, []byte("ghijkl")) // END_STREAM here puppet.do(readBodyHandler(t, "ghi")) puppet.do(readBodyHandler(t, "jkl")) st.wantWindowUpdate(0, 3) st.wantWindowUpdate(0, 3) // no more stream-level, since END_STREAM } func TestServer_Send_GoAway_After_Bogus_WindowUpdate(t *testing.T) { st := newServerTester(t, nil) defer st.Close() st.greet() if err := st.fr.WriteWindowUpdate(0, 1<<31-1); err != nil { t.Fatal(err) } gf := st.wantGoAway() if gf.ErrCode != ErrCodeFlowControl { t.Errorf("GOAWAY err = %v; want %v", gf.ErrCode, ErrCodeFlowControl) } if gf.LastStreamID != 0 { t.Errorf("GOAWAY last stream ID = %v; want %v", gf.LastStreamID, 0) } } func TestServer_Send_RstStream_After_Bogus_WindowUpdate(t *testing.T) { inHandler := make(chan bool) blockHandler := make(chan bool) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true <-blockHandler }) defer st.Close() defer close(blockHandler) st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler // Send a bogus window update: if err := st.fr.WriteWindowUpdate(1, 1<<31-1); err != nil { t.Fatal(err) } st.wantRSTStream(1, ErrCodeFlowControl) } // testServerPostUnblock sends a hanging POST with unsent data to handler, // then runs fn once in the handler, and verifies that the error returned from // handler is acceptable. It fails if takes over 5 seconds for handler to exit. func testServerPostUnblock(t *testing.T, handler func(http.ResponseWriter, *http.Request) error, fn func(*serverTester), checkErr func(error), otherHeaders ...string) { inHandler := make(chan bool) errc := make(chan error, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true errc <- handler(w, r) }) st.greet() st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(append([]string{":method", "POST"}, otherHeaders...)...), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler fn(st) select { case err := <-errc: if checkErr != nil { checkErr(err) } case <-time.After(5 * time.Second): t.Fatal("timeout waiting for Handler to return") } st.Close() } func TestServer_RSTStream_Unblocks_Read(t *testing.T) { testServerPostUnblock(t, func(w http.ResponseWriter, r *http.Request) (err error) { _, err = r.Body.Read(make([]byte, 1)) return }, func(st *serverTester) { if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }, func(err error) { if err == nil { t.Error("unexpected nil error from Request.Body.Read") } }, ) } func TestServer_DeadConn_Unblocks_Read(t *testing.T) { testServerPostUnblock(t, func(w http.ResponseWriter, r *http.Request) (err error) { _, err = r.Body.Read(make([]byte, 1)) return }, func(st *serverTester) { st.cc.Close() }, func(err error) { if err == nil { t.Error("unexpected nil error from Request.Body.Read") } }, ) } var blockUntilClosed = func(w http.ResponseWriter, r *http.Request) error { <-w.(http.CloseNotifier).CloseNotify() return nil } func TestServer_CloseNotify_After_RSTStream(t *testing.T) { testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }, nil) } func TestServer_CloseNotify_After_ConnClose(t *testing.T) { testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { st.cc.Close() }, nil) } // that CloseNotify unblocks after a stream error due to the client's // problem that's unrelated to them explicitly canceling it (which is // TestServer_CloseNotify_After_RSTStream above) func TestServer_CloseNotify_After_StreamError(t *testing.T) { testServerPostUnblock(t, blockUntilClosed, func(st *serverTester) { // data longer than declared Content-Length => stream error st.writeData(1, true, []byte("1234")) }, nil, "content-length", "3") } func TestServer_StateTransitions(t *testing.T) { var st *serverTester inHandler := make(chan bool) writeData := make(chan bool) leaveHandler := make(chan bool) st = newServerTester(t, func(w http.ResponseWriter, r *http.Request) { inHandler <- true if st.stream(1) == nil { t.Errorf("nil stream 1 in handler") } if got, want := st.streamState(1), stateOpen; got != want { t.Errorf("in handler, state is %v; want %v", got, want) } writeData <- true if n, err := r.Body.Read(make([]byte, 1)); n != 0 || err != io.EOF { t.Errorf("body read = %d, %v; want 0, EOF", n, err) } if got, want := st.streamState(1), stateHalfClosedRemote; got != want { t.Errorf("in handler, state is %v; want %v", got, want) } <-leaveHandler }) st.greet() if st.stream(1) != nil { t.Fatal("stream 1 should be empty") } if got := st.streamState(1); got != stateIdle { t.Fatalf("stream 1 should be idle; got %v", got) } st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, // keep it open EndHeaders: true, }) <-inHandler <-writeData st.writeData(1, true, nil) leaveHandler <- true hf := st.wantHeaders() if !hf.StreamEnded() { t.Fatal("expected END_STREAM flag") } if got, want := st.streamState(1), stateClosed; got != want { t.Errorf("at end, state is %v; want %v", got, want) } if st.stream(1) != nil { t.Fatal("at end, stream 1 should be gone") } } // test HEADERS w/o EndHeaders + another HEADERS (should get rejected) func TestServer_Rejects_HeadersNoEnd_Then_Headers(t *testing.T) { testServerRejects(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: false, }) st.writeHeaders(HeadersFrameParam{ // Not a continuation. StreamID: 3, // different stream. BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) }) } // test HEADERS w/o EndHeaders + PING (should get rejected) func TestServer_Rejects_HeadersNoEnd_Then_Ping(t *testing.T) { testServerRejects(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: false, }) if err := st.fr.WritePing(false, [8]byte{}); err != nil { t.Fatal(err) } }) } // test HEADERS w/ EndHeaders + a continuation HEADERS (should get rejected) func TestServer_Rejects_HeadersEnd_Then_Continuation(t *testing.T) { testServerRejects(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) st.wantHeaders() if err := st.fr.WriteContinuation(1, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { t.Fatal(err) } }) } // test HEADERS w/o EndHeaders + a continuation HEADERS on wrong stream ID func TestServer_Rejects_HeadersNoEnd_Then_ContinuationWrongStream(t *testing.T) { testServerRejects(t, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: false, }) if err := st.fr.WriteContinuation(3, true, encodeHeaderNoImplicit(t, "foo", "bar")); err != nil { t.Fatal(err) } }) } // No HEADERS on stream 0. func TestServer_Rejects_Headers0(t *testing.T) { testServerRejects(t, func(st *serverTester) { st.fr.AllowIllegalWrites = true st.writeHeaders(HeadersFrameParam{ StreamID: 0, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) }) } // No CONTINUATION on stream 0. func TestServer_Rejects_Continuation0(t *testing.T) { testServerRejects(t, func(st *serverTester) { st.fr.AllowIllegalWrites = true if err := st.fr.WriteContinuation(0, true, st.encodeHeader()); err != nil { t.Fatal(err) } }) } func TestServer_Rejects_PushPromise(t *testing.T) { testServerRejects(t, func(st *serverTester) { pp := PushPromiseParam{ StreamID: 1, PromiseID: 3, } if err := st.fr.WritePushPromise(pp); err != nil { t.Fatal(err) } }) } // testServerRejects tests that the server hangs up with a GOAWAY // frame and a server close after the client does something // deserving a CONNECTION_ERROR. func testServerRejects(t *testing.T, writeReq func(*serverTester)) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) {}) st.addLogFilter("connection error: PROTOCOL_ERROR") defer st.Close() st.greet() writeReq(st) st.wantGoAway() errc := make(chan error, 1) go func() { fr, err := st.fr.ReadFrame() if err == nil { err = fmt.Errorf("got frame of type %T", fr) } errc <- err }() select { case err := <-errc: if err != io.EOF { t.Errorf("ReadFrame = %v; want io.EOF", err) } case <-time.After(2 * time.Second): t.Error("timeout waiting for disconnect") } } // testServerRequest sets up an idle HTTP/2 connection and lets you // write a single request with writeReq, and then verify that the // *http.Request is built correctly in checkReq. func testServerRequest(t *testing.T, writeReq func(*serverTester), checkReq func(*http.Request)) { gotReq := make(chan bool, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { if r.Body == nil { t.Fatal("nil Body") } checkReq(r) gotReq <- true }) defer st.Close() st.greet() writeReq(st) select { case <-gotReq: case <-time.After(2 * time.Second): t.Error("timeout waiting for request") } } func getSlash(st *serverTester) { st.bodylessReq1() } func TestServer_Response_NoData(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { // Nothing. return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if !hf.StreamEnded() { t.Fatal("want END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } }) } func TestServer_Response_NoData_Header_FooBar(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Foo-Bar", "some-value") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if !hf.StreamEnded() { t.Fatal("want END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"foo-bar", "some-value"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", "0"}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } func TestServer_Response_Data_Sniff_DoesntOverride(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Content-Type", "foo/bar") io.WriteString(w, msg) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("don't want END_STREAM, expecting data") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "foo/bar"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } df := st.wantData() if !df.StreamEnded() { t.Error("expected DATA to have END_STREAM flag") } if got := string(df.Data()); got != msg { t.Errorf("got DATA %q; want %q", got, msg) } }) } func TestServer_Response_TransferEncoding_chunked(t *testing.T) { const msg = "hi" testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("Transfer-Encoding", "chunked") // should be stripped io.WriteString(w, msg) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } // Header accessed only after the initial write. func TestServer_Response_Data_IgnoreHeaderAfterWrite_After(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { io.WriteString(w, msg) w.Header().Set("foo", "should be ignored") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } // Header accessed before the initial write and later mutated. func TestServer_Response_Data_IgnoreHeaderAfterWrite_Overwrite(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.Header().Set("foo", "proper value") io.WriteString(w, msg) w.Header().Set("foo", "should be ignored") return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"foo", "proper value"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } }) } func TestServer_Response_Data_SniffLenType(t *testing.T) { const msg = "this is HTML." testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { io.WriteString(w, msg) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("don't want END_STREAM, expecting data") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/html; charset=utf-8"}, {"content-length", strconv.Itoa(len(msg))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } df := st.wantData() if !df.StreamEnded() { t.Error("expected DATA to have END_STREAM flag") } if got := string(df.Data()); got != msg { t.Errorf("got DATA %q; want %q", got, msg) } }) } func TestServer_Response_Header_Flush_MidWrite(t *testing.T) { const msg = "this is HTML" const msg2 = ", and this is the next chunk" testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { io.WriteString(w, msg) w.(http.Flusher).Flush() io.WriteString(w, msg2) return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/html; charset=utf-8"}, // sniffed // and no content-length } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } { df := st.wantData() if df.StreamEnded() { t.Error("unexpected END_STREAM flag") } if got := string(df.Data()); got != msg { t.Errorf("got DATA %q; want %q", got, msg) } } { df := st.wantData() if !df.StreamEnded() { t.Error("wanted END_STREAM flag on last data chunk") } if got := string(df.Data()); got != msg2 { t.Errorf("got DATA %q; want %q", got, msg2) } } }) } func TestServer_Response_LargeWrite(t *testing.T) { const size = 1 << 20 const maxFrameSize = 16 << 10 testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { n, err := w.Write(bytes.Repeat([]byte("a"), size)) if err != nil { return fmt.Errorf("Write error: %v", err) } if n != size { return fmt.Errorf("wrong size %d from Write", n) } return nil }, func(st *serverTester) { if err := st.fr.WriteSettings( Setting{SettingInitialWindowSize, 0}, Setting{SettingMaxFrameSize, maxFrameSize}, ); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request // Give the handler quota to write: if err := st.fr.WriteWindowUpdate(1, size); err != nil { t.Fatal(err) } // Give the handler quota to write to connection-level // window as well if err := st.fr.WriteWindowUpdate(0, size); err != nil { t.Fatal(err) } hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, // sniffed // and no content-length } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } var bytes, frames int for { df := st.wantData() bytes += len(df.Data()) frames++ for _, b := range df.Data() { if b != 'a' { t.Fatal("non-'a' byte seen in DATA") } } if df.StreamEnded() { break } } if bytes != size { t.Errorf("Got %d bytes; want %d", bytes, size) } if want := int(size / maxFrameSize); frames < want || frames > want*2 { t.Errorf("Got %d frames; want %d", frames, size) } }) } // Test that the handler can't write more than the client allows func TestServer_Response_LargeWrite_FlowControlled(t *testing.T) { const size = 1 << 20 const maxFrameSize = 16 << 10 testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.(http.Flusher).Flush() n, err := w.Write(bytes.Repeat([]byte("a"), size)) if err != nil { return fmt.Errorf("Write error: %v", err) } if n != size { return fmt.Errorf("wrong size %d from Write", n) } return nil }, func(st *serverTester) { // Set the window size to something explicit for this test. // It's also how much initial data we expect. const initWindowSize = 123 if err := st.fr.WriteSettings( Setting{SettingInitialWindowSize, initWindowSize}, Setting{SettingMaxFrameSize, maxFrameSize}, ); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request defer func() { st.fr.WriteRSTStream(1, ErrCodeCancel) }() hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } df := st.wantData() if got := len(df.Data()); got != initWindowSize { t.Fatalf("Initial window size = %d but got DATA with %d bytes", initWindowSize, got) } for _, quota := range []int{1, 13, 127} { if err := st.fr.WriteWindowUpdate(1, uint32(quota)); err != nil { t.Fatal(err) } df := st.wantData() if int(quota) != len(df.Data()) { t.Fatalf("read %d bytes after giving %d quota", len(df.Data()), quota) } } if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }) } // Test that the handler blocked in a Write is unblocked if the server sends a RST_STREAM. func TestServer_Response_RST_Unblocks_LargeWrite(t *testing.T) { const size = 1 << 20 const maxFrameSize = 16 << 10 testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.(http.Flusher).Flush() errc := make(chan error, 1) go func() { _, err := w.Write(bytes.Repeat([]byte("a"), size)) errc <- err }() select { case err := <-errc: if err == nil { return errors.New("unexpected nil error from Write in handler") } return nil case <-time.After(2 * time.Second): return errors.New("timeout waiting for Write in handler") } }, func(st *serverTester) { if err := st.fr.WriteSettings( Setting{SettingInitialWindowSize, 0}, Setting{SettingMaxFrameSize, maxFrameSize}, ); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } if err := st.fr.WriteRSTStream(1, ErrCodeCancel); err != nil { t.Fatal(err) } }) } func TestServer_Response_Empty_Data_Not_FlowControlled(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { w.(http.Flusher).Flush() // Nothing; send empty DATA return nil }, func(st *serverTester) { // Handler gets no data quota: if err := st.fr.WriteSettings(Setting{SettingInitialWindowSize, 0}); err != nil { t.Fatal(err) } st.wantSettingsAck() getSlash(st) // make the single request hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } df := st.wantData() if got := len(df.Data()); got != 0 { t.Fatalf("unexpected %d DATA bytes; want 0", got) } if !df.StreamEnded() { t.Fatal("DATA didn't have END_STREAM") } }) } func TestServer_Response_Automatic100Continue(t *testing.T) { const msg = "foo" const reply = "bar" testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { if v := r.Header.Get("Expect"); v != "" { t.Errorf("Expect header = %q; want empty", v) } buf := make([]byte, len(msg)) // This read should trigger the 100-continue being sent. if n, err := io.ReadFull(r.Body, buf); err != nil || n != len(msg) || string(buf) != msg { return fmt.Errorf("ReadFull = %q, %v; want %q, nil", buf[:n], err, msg) } _, err := io.WriteString(w, reply) return err }, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, // clients send odd numbers BlockFragment: st.encodeHeader(":method", "POST", "expect", "100-continue"), EndStream: false, EndHeaders: true, }) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth := decodeHeader(t, hf.HeaderBlockFragment()) wanth := [][2]string{ {":status", "100"}, } if !reflect.DeepEqual(goth, wanth) { t.Fatalf("Got headers %v; want %v", goth, wanth) } // Okay, they sent status 100, so we can send our // gigantic and/or sensitive "foo" payload now. st.writeData(1, true, []byte(msg)) st.wantWindowUpdate(0, uint32(len(msg))) hf = st.wantHeaders() if hf.StreamEnded() { t.Fatal("expected data to follow") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } goth = decodeHeader(t, hf.HeaderBlockFragment()) wanth = [][2]string{ {":status", "200"}, {"content-type", "text/plain; charset=utf-8"}, {"content-length", strconv.Itoa(len(reply))}, } if !reflect.DeepEqual(goth, wanth) { t.Errorf("Got headers %v; want %v", goth, wanth) } df := st.wantData() if string(df.Data()) != reply { t.Errorf("Client read %q; want %q", df.Data(), reply) } if !df.StreamEnded() { t.Errorf("expect data stream end") } }) } func TestServer_HandlerWriteErrorOnDisconnect(t *testing.T) { errc := make(chan error, 1) testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { p := []byte("some data.\n") for { _, err := w.Write(p) if err != nil { errc <- err return nil } } }, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: false, EndHeaders: true, }) hf := st.wantHeaders() if hf.StreamEnded() { t.Fatal("unexpected END_STREAM flag") } if !hf.HeadersEnded() { t.Fatal("want END_HEADERS flag") } // Close the connection and wait for the handler to (hopefully) notice. st.cc.Close() select { case <-errc: case <-time.After(5 * time.Second): t.Error("timeout") } }) } func TestServer_Rejects_Too_Many_Streams(t *testing.T) { const testPath = "/some/path" inHandler := make(chan uint32) leaveHandler := make(chan bool) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { id := w.(*responseWriter).rws.stream.id inHandler <- id if id == 1+(defaultMaxStreams+1)*2 && r.URL.Path != testPath { t.Errorf("decoded final path as %q; want %q", r.URL.Path, testPath) } <-leaveHandler }) defer st.Close() st.greet() nextStreamID := uint32(1) streamID := func() uint32 { defer func() { nextStreamID += 2 }() return nextStreamID } sendReq := func(id uint32, headers ...string) { st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(headers...), EndStream: true, EndHeaders: true, }) } for i := 0; i < defaultMaxStreams; i++ { sendReq(streamID()) <-inHandler } defer func() { for i := 0; i < defaultMaxStreams; i++ { leaveHandler <- true } }() // And this one should cross the limit: // (It's also sent as a CONTINUATION, to verify we still track the decoder context, // even if we're rejecting it) rejectID := streamID() headerBlock := st.encodeHeader(":path", testPath) frag1, frag2 := headerBlock[:3], headerBlock[3:] st.writeHeaders(HeadersFrameParam{ StreamID: rejectID, BlockFragment: frag1, EndStream: true, EndHeaders: false, // CONTINUATION coming }) if err := st.fr.WriteContinuation(rejectID, true, frag2); err != nil { t.Fatal(err) } st.wantRSTStream(rejectID, ErrCodeProtocol) // But let a handler finish: leaveHandler <- true st.wantHeaders() // And now another stream should be able to start: goodID := streamID() sendReq(goodID, ":path", testPath) select { case got := <-inHandler: if got != goodID { t.Errorf("Got stream %d; want %d", got, goodID) } case <-time.After(3 * time.Second): t.Error("timeout waiting for handler") } } // So many response headers that the server needs to use CONTINUATION frames: func TestServer_Response_ManyHeaders_With_Continuation(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { h := w.Header() for i := 0; i < 5000; i++ { h.Set(fmt.Sprintf("x-header-%d", i), fmt.Sprintf("x-value-%d", i)) } return nil }, func(st *serverTester) { getSlash(st) hf := st.wantHeaders() if hf.HeadersEnded() { t.Fatal("got unwanted END_HEADERS flag") } n := 0 for { n++ cf := st.wantContinuation() if cf.HeadersEnded() { break } } if n < 5 { t.Errorf("Only got %d CONTINUATION frames; expected 5+ (currently 6)", n) } }) } // This previously crashed (reported by Mathieu Lonjaret as observed // while using Camlistore) because we got a DATA frame from the client // after the handler exited and our logic at the time was wrong, // keeping a stream in the map in stateClosed, which tickled an // invariant check later when we tried to remove that stream (via // defer sc.closeAllStreamsOnConnClose) when the serverConn serve loop // ended. func TestServer_NoCrash_HandlerClose_Then_ClientClose(t *testing.T) { testServerResponse(t, func(w http.ResponseWriter, r *http.Request) error { // nothing return nil }, func(st *serverTester) { st.writeHeaders(HeadersFrameParam{ StreamID: 1, BlockFragment: st.encodeHeader(), EndStream: false, // DATA is coming EndHeaders: true, }) hf := st.wantHeaders() if !hf.HeadersEnded() || !hf.StreamEnded() { t.Fatalf("want END_HEADERS+END_STREAM, got %v", hf) } // Sent when the a Handler closes while a client has // indicated it's still sending DATA: st.wantRSTStream(1, ErrCodeCancel) // Now the handler has ended, so it's ended its // stream, but the client hasn't closed its side // (stateClosedLocal). So send more data and verify // it doesn't crash with an internal invariant panic, like // it did before. st.writeData(1, true, []byte("foo")) // Sent after a peer sends data anyway (admittedly the // previous RST_STREAM might've still been in-flight), // but they'll get the more friendly 'cancel' code // first. st.wantRSTStream(1, ErrCodeStreamClosed) // Set up a bunch of machinery to record the panic we saw // previously. var ( panMu sync.Mutex panicVal interface{} ) testHookOnPanicMu.Lock() testHookOnPanic = func(sc *serverConn, pv interface{}) bool { panMu.Lock() panicVal = pv panMu.Unlock() return true } testHookOnPanicMu.Unlock() // Now force the serve loop to end, via closing the connection. st.cc.Close() select { case <-st.sc.doneServing: // Loop has exited. panMu.Lock() got := panicVal panMu.Unlock() if got != nil { t.Errorf("Got panic: %v", got) } case <-time.After(5 * time.Second): t.Error("timeout") } }) } func TestServer_Rejects_TLS10(t *testing.T) { testRejectTLS(t, tls.VersionTLS10) } func TestServer_Rejects_TLS11(t *testing.T) { testRejectTLS(t, tls.VersionTLS11) } func testRejectTLS(t *testing.T, max uint16) { st := newServerTester(t, nil, func(c *tls.Config) { c.MaxVersion = max }) defer st.Close() gf := st.wantGoAway() if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { t.Errorf("Got error code %v; want %v", got, want) } } func TestServer_Rejects_TLSBadCipher(t *testing.T) { st := newServerTester(t, nil, func(c *tls.Config) { // Only list bad ones: c.CipherSuites = []uint16{ tls.TLS_RSA_WITH_RC4_128_SHA, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_RSA_WITH_AES_128_CBC_SHA, tls.TLS_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, } }) defer st.Close() gf := st.wantGoAway() if got, want := gf.ErrCode, ErrCodeInadequateSecurity; got != want { t.Errorf("Got error code %v; want %v", got, want) } } func TestServer_Advertises_Common_Cipher(t *testing.T) { const requiredSuite = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 st := newServerTester(t, nil, func(c *tls.Config) { // Have the client only support the one required by the spec. c.CipherSuites = []uint16{requiredSuite} }, func(ts *httptest.Server) { var srv *http.Server = ts.Config // Have the server configured with one specific cipher suite // which is banned. This tests that ConfigureServer ends up // adding the good one to this list. srv.TLSConfig = &tls.Config{ CipherSuites: []uint16{tls.TLS_RSA_WITH_AES_128_CBC_SHA}, // just a banned one } }) defer st.Close() st.greet() } // TODO: move this onto *serverTester, and re-use the same hpack // decoding context throughout. We're just getting lucky here with // creating a new decoder each time. func decodeHeader(t *testing.T, headerBlock []byte) (pairs [][2]string) { d := hpack.NewDecoder(initialHeaderTableSize, func(f hpack.HeaderField) { pairs = append(pairs, [2]string{f.Name, f.Value}) }) if _, err := d.Write(headerBlock); err != nil { t.Fatalf("hpack decoding error: %v", err) } if err := d.Close(); err != nil { t.Fatalf("hpack decoding error: %v", err) } return } // testServerResponse sets up an idle HTTP/2 connection and lets you // write a single request with writeReq, and then reply to it in some way with the provided handler, // and then verify the output with the serverTester again (assuming the handler returns nil) func testServerResponse(t testing.TB, handler func(http.ResponseWriter, *http.Request) error, client func(*serverTester), ) { errc := make(chan error, 1) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { if r.Body == nil { t.Fatal("nil Body") } errc <- handler(w, r) }) defer st.Close() donec := make(chan bool) go func() { defer close(donec) st.greet() client(st) }() select { case <-donec: return case <-time.After(5 * time.Second): t.Fatal("timeout") } select { case err := <-errc: if err != nil { t.Fatalf("Error in handler: %v", err) } case <-time.After(2 * time.Second): t.Error("timeout waiting for handler to finish") } } // readBodyHandler returns an http Handler func that reads len(want) // bytes from r.Body and fails t if the contents read were not // the value of want. func readBodyHandler(t *testing.T, want string) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { buf := make([]byte, len(want)) _, err := io.ReadFull(r.Body, buf) if err != nil { t.Error(err) return } if string(buf) != want { t.Errorf("read %q; want %q", buf, want) } } } // TestServerWithCurl currently fails, hence the LenientCipherSuites test. See: // https://github.com/tatsuhiro-t/nghttp2/issues/140 & // http://sourceforge.net/p/curl/bugs/1472/ func TestServerWithCurl(t *testing.T) { testServerWithCurl(t, false) } func TestServerWithCurl_LenientCipherSuites(t *testing.T) { testServerWithCurl(t, true) } func testServerWithCurl(t *testing.T, permitProhibitedCipherSuites bool) { if runtime.GOOS != "linux" { t.Skip("skipping Docker test when not on Linux; requires --net which won't work with boot2docker anyway") } requireCurl(t) const msg = "Hello from curl!\n" ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Foo", "Bar") w.Header().Set("Client-Proto", r.Proto) io.WriteString(w, msg) })) ConfigureServer(ts.Config, &Server{ PermitProhibitedCipherSuites: permitProhibitedCipherSuites, }) ts.TLS = ts.Config.TLSConfig // the httptest.Server has its own copy of this TLS config ts.StartTLS() defer ts.Close() var gotConn int32 testHookOnConn = func() { atomic.StoreInt32(&gotConn, 1) } t.Logf("Running test server for curl to hit at: %s", ts.URL) container := curl(t, "--silent", "--http2", "--insecure", "-v", ts.URL) defer kill(container) resc := make(chan interface{}, 1) go func() { res, err := dockerLogs(container) if err != nil { resc <- err } else { resc <- res } }() select { case res := <-resc: if err, ok := res.(error); ok { t.Fatal(err) } if !strings.Contains(string(res.([]byte)), "foo: Bar") { t.Errorf("didn't see foo: Bar header") t.Logf("Got: %s", res) } if !strings.Contains(string(res.([]byte)), "client-proto: HTTP/2") { t.Errorf("didn't see client-proto: HTTP/2 header") t.Logf("Got: %s", res) } if !strings.Contains(string(res.([]byte)), msg) { t.Errorf("didn't see %q content", msg) t.Logf("Got: %s", res) } case <-time.After(3 * time.Second): t.Errorf("timeout waiting for curl") } if atomic.LoadInt32(&gotConn) == 0 { t.Error("never saw an http2 connection") } } func BenchmarkServerGets(b *testing.B) { b.ReportAllocs() const msg = "Hello, world" st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) }) defer st.Close() st.greet() // Give the server quota to reply. (plus it has the the 64KB) if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { id := 1 + uint32(i)*2 st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(), EndStream: true, EndHeaders: true, }) st.wantHeaders() df := st.wantData() if !df.StreamEnded() { b.Fatalf("DATA didn't have END_STREAM; got %v", df) } } } func BenchmarkServerPosts(b *testing.B) { b.ReportAllocs() const msg = "Hello, world" st := newServerTester(b, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, msg) }) defer st.Close() st.greet() // Give the server quota to reply. (plus it has the the 64KB) if err := st.fr.WriteWindowUpdate(0, uint32(b.N*len(msg))); err != nil { b.Fatal(err) } for i := 0; i < b.N; i++ { id := 1 + uint32(i)*2 st.writeHeaders(HeadersFrameParam{ StreamID: id, BlockFragment: st.encodeHeader(":method", "POST"), EndStream: false, EndHeaders: true, }) st.writeData(id, true, nil) st.wantHeaders() df := st.wantData() if !df.StreamEnded() { b.Fatalf("DATA didn't have END_STREAM; got %v", df) } } } ================================================ FILE: vendor/golang.org/x/net/http2/testdata/draft-ietf-httpbis-http2.xml ================================================ Hypertext Transfer Protocol version 2 Twist
mbelshe@chromium.org
Google, Inc
fenix@google.com
Mozilla
331 E Evelyn Street Mountain View CA 94041 US martin.thomson@gmail.com
Applications HTTPbis HTTP SPDY Web This specification describes an optimized expression of the semantics of the Hypertext Transfer Protocol (HTTP). HTTP/2 enables a more efficient use of network resources and a reduced perception of latency by introducing header field compression and allowing multiple concurrent messages on the same connection. It also introduces unsolicited push of representations from servers to clients. This specification is an alternative to, but does not obsolete, the HTTP/1.1 message syntax. HTTP's existing semantics remain unchanged. Discussion of this draft takes place on the HTTPBIS working group mailing list (ietf-http-wg@w3.org), which is archived at . Working Group information can be found at ; that specific to HTTP/2 are at . The changes in this draft are summarized in .
The Hypertext Transfer Protocol (HTTP) is a wildly successful protocol. However, the HTTP/1.1 message format () has several characteristics that have a negative overall effect on application performance today. In particular, HTTP/1.0 allowed only one request to be outstanding at a time on a given TCP connection. HTTP/1.1 added request pipelining, but this only partially addressed request concurrency and still suffers from head-of-line blocking. Therefore, HTTP/1.1 clients that need to make many requests typically use multiple connections to a server in order to achieve concurrency and thereby reduce latency. Furthermore, HTTP header fields are often repetitive and verbose, causing unnecessary network traffic, as well as causing the initial TCP congestion window to quickly fill. This can result in excessive latency when multiple requests are made on a new TCP connection. HTTP/2 addresses these issues by defining an optimized mapping of HTTP's semantics to an underlying connection. Specifically, it allows interleaving of request and response messages on the same connection and uses an efficient coding for HTTP header fields. It also allows prioritization of requests, letting more important requests complete more quickly, further improving performance. The resulting protocol is more friendly to the network, because fewer TCP connections can be used in comparison to HTTP/1.x. This means less competition with other flows, and longer-lived connections, which in turn leads to better utilization of available network capacity. Finally, HTTP/2 also enables more efficient processing of messages through use of binary message framing.
HTTP/2 provides an optimized transport for HTTP semantics. HTTP/2 supports all of the core features of HTTP/1.1, but aims to be more efficient in several ways. The basic protocol unit in HTTP/2 is a frame. Each frame type serves a different purpose. For example, HEADERS and DATA frames form the basis of HTTP requests and responses; other frame types like SETTINGS, WINDOW_UPDATE, and PUSH_PROMISE are used in support of other HTTP/2 features. Multiplexing of requests is achieved by having each HTTP request-response exchange associated with its own stream. Streams are largely independent of each other, so a blocked or stalled request or response does not prevent progress on other streams. Flow control and prioritization ensure that it is possible to efficiently use multiplexed streams. Flow control helps to ensure that only data that can be used by a receiver is transmitted. Prioritization ensures that limited resources can be directed to the most important streams first. HTTP/2 adds a new interaction mode, whereby a server can push responses to a client. Server push allows a server to speculatively send a client data that the server anticipates the client will need, trading off some network usage against a potential latency gain. The server does this by synthesizing a request, which it sends as a PUSH_PROMISE frame. The server is then able to send a response to the synthetic request on a separate stream. Frames that contain HTTP header fields are compressed. HTTP requests can be highly redundant, so compression can reduce the size of requests and responses significantly.
The HTTP/2 specification is split into four parts: Starting HTTP/2 covers how an HTTP/2 connection is initiated. The framing and streams layers describe the way HTTP/2 frames are structured and formed into multiplexed streams. Frame and error definitions include details of the frame and error types used in HTTP/2. HTTP mappings and additional requirements describe how HTTP semantics are expressed using frames and streams. While some of the frame and stream layer concepts are isolated from HTTP, this specification does not define a completely generic framing layer. The framing and streams layers are tailored to the needs of the HTTP protocol and server push.
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119. All numeric values are in network byte order. Values are unsigned unless otherwise indicated. Literal values are provided in decimal or hexadecimal as appropriate. Hexadecimal literals are prefixed with 0x to distinguish them from decimal literals. The following terms are used: The endpoint initiating the HTTP/2 connection. A transport-layer connection between two endpoints. An error that affects the entire HTTP/2 connection. Either the client or server of the connection. The smallest unit of communication within an HTTP/2 connection, consisting of a header and a variable-length sequence of octets structured according to the frame type. An endpoint. When discussing a particular endpoint, "peer" refers to the endpoint that is remote to the primary subject of discussion. An endpoint that is receiving frames. An endpoint that is transmitting frames. The endpoint which did not initiate the HTTP/2 connection. A bi-directional flow of frames across a virtual channel within the HTTP/2 connection. An error on the individual HTTP/2 stream. Finally, the terms "gateway", "intermediary", "proxy", and "tunnel" are defined in .
An HTTP/2 connection is an application layer protocol running on top of a TCP connection (). The client is the TCP connection initiator. HTTP/2 uses the same "http" and "https" URI schemes used by HTTP/1.1. HTTP/2 shares the same default port numbers: 80 for "http" URIs and 443 for "https" URIs. As a result, implementations processing requests for target resource URIs like http://example.org/foo or https://example.com/bar are required to first discover whether the upstream server (the immediate peer to which the client wishes to establish a connection) supports HTTP/2. The means by which support for HTTP/2 is determined is different for "http" and "https" URIs. Discovery for "http" URIs is described in . Discovery for "https" URIs is described in .
The protocol defined in this document has two identifiers. The string "h2" identifies the protocol where HTTP/2 uses TLS. This identifier is used in the TLS application layer protocol negotiation extension (ALPN) field and any place that HTTP/2 over TLS is identified. The "h2" string is serialized into an ALPN protocol identifier as the two octet sequence: 0x68, 0x32. The string "h2c" identifies the protocol where HTTP/2 is run over cleartext TCP. This identifier is used in the HTTP/1.1 Upgrade header field and any place that HTTP/2 over TCP is identified. Negotiating "h2" or "h2c" implies the use of the transport, security, framing and message semantics described in this document. RFC Editor's Note: please remove the remainder of this section prior to the publication of a final version of this document. Only implementations of the final, published RFC can identify themselves as "h2" or "h2c". Until such an RFC exists, implementations MUST NOT identify themselves using these strings. Examples and text throughout the rest of this document use "h2" as a matter of editorial convenience only. Implementations of draft versions MUST NOT identify using this string. Implementations of draft versions of the protocol MUST add the string "-" and the corresponding draft number to the identifier. For example, draft-ietf-httpbis-http2-11 over TLS is identified using the string "h2-11". Non-compatible experiments that are based on these draft versions MUST append the string "-" and an experiment name to the identifier. For example, an experimental implementation of packet mood-based encoding based on draft-ietf-httpbis-http2-09 might identify itself as "h2-09-emo". Note that any label MUST conform to the "token" syntax defined in . Experimenters are encouraged to coordinate their experiments on the ietf-http-wg@w3.org mailing list.
A client that makes a request for an "http" URI without prior knowledge about support for HTTP/2 uses the HTTP Upgrade mechanism (). The client makes an HTTP/1.1 request that includes an Upgrade header field identifying HTTP/2 with the "h2c" token. The HTTP/1.1 request MUST include exactly one HTTP2-Settings header field.
For example: ]]>
Requests that contain an entity body MUST be sent in their entirety before the client can send HTTP/2 frames. This means that a large request entity can block the use of the connection until it is completely sent. If concurrency of an initial request with subsequent requests is important, an OPTIONS request can be used to perform the upgrade to HTTP/2, at the cost of an additional round-trip. A server that does not support HTTP/2 can respond to the request as though the Upgrade header field were absent:
HTTP/1.1 200 OK Content-Length: 243 Content-Type: text/html ...
A server MUST ignore a "h2" token in an Upgrade header field. Presence of a token with "h2" implies HTTP/2 over TLS, which is instead negotiated as described in . A server that supports HTTP/2 can accept the upgrade with a 101 (Switching Protocols) response. After the empty line that terminates the 101 response, the server can begin sending HTTP/2 frames. These frames MUST include a response to the request that initiated the Upgrade.
For example: HTTP/1.1 101 Switching Protocols Connection: Upgrade Upgrade: h2c [ HTTP/2 connection ...
The first HTTP/2 frame sent by the server is a SETTINGS frame () as the server connection preface (). Upon receiving the 101 response, the client sends a connection preface, which includes a SETTINGS frame. The HTTP/1.1 request that is sent prior to upgrade is assigned stream identifier 1 and is assigned default priority values. Stream 1 is implicitly half closed from the client toward the server, since the request is completed as an HTTP/1.1 request. After commencing the HTTP/2 connection, stream 1 is used for the response.
A request that upgrades from HTTP/1.1 to HTTP/2 MUST include exactly one HTTP2-Settings header field. The HTTP2-Settings header field is a connection-specific header field that includes parameters that govern the HTTP/2 connection, provided in anticipation of the server accepting the request to upgrade.
A server MUST NOT upgrade the connection to HTTP/2 if this header field is not present, or if more than one is present. A server MUST NOT send this header field. The content of the HTTP2-Settings header field is the payload of a SETTINGS frame (), encoded as a base64url string (that is, the URL- and filename-safe Base64 encoding described in , with any trailing '=' characters omitted). The ABNF production for token68 is defined in . Since the upgrade is only intended to apply to the immediate connection, a client sending HTTP2-Settings MUST also send HTTP2-Settings as a connection option in the Connection header field to prevent it from being forwarded downstream. A server decodes and interprets these values as it would any other SETTINGS frame. Acknowledgement of the SETTINGS parameters is not necessary, since a 101 response serves as implicit acknowledgment. Providing these values in the Upgrade request gives a client an opportunity to provide parameters prior to receiving any frames from the server.
A client that makes a request to an "https" URI uses TLS with the application layer protocol negotiation extension. HTTP/2 over TLS uses the "h2" application token. The "h2c" token MUST NOT be sent by a client or selected by a server. Once TLS negotiation is complete, both the client and the server send a connection preface.
A client can learn that a particular server supports HTTP/2 by other means. For example, describes a mechanism for advertising this capability. A client MAY immediately send HTTP/2 frames to a server that is known to support HTTP/2, after the connection preface; a server can identify such a connection by the presence of the connection preface. This only affects the establishment of HTTP/2 connections over cleartext TCP; implementations that support HTTP/2 over TLS MUST use protocol negotiation in TLS. Without additional information, prior support for HTTP/2 is not a strong signal that a given server will support HTTP/2 for future connections. For example, it is possible for server configurations to change, for configurations to differ between instances in clustered servers, or for network conditions to change.
Upon establishment of a TCP connection and determination that HTTP/2 will be used by both peers, each endpoint MUST send a connection preface as a final confirmation and to establish the initial SETTINGS parameters for the HTTP/2 connection. The client and server each send a different connection preface. The client connection preface starts with a sequence of 24 octets, which in hex notation are:
(the string PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n). This sequence is followed by a SETTINGS frame (). The SETTINGS frame MAY be empty. The client sends the client connection preface immediately upon receipt of a 101 Switching Protocols response (indicating a successful upgrade), or as the first application data octets of a TLS connection. If starting an HTTP/2 connection with prior knowledge of server support for the protocol, the client connection preface is sent upon connection establishment. The client connection preface is selected so that a large proportion of HTTP/1.1 or HTTP/1.0 servers and intermediaries do not attempt to process further frames. Note that this does not address the concerns raised in . The server connection preface consists of a potentially empty SETTINGS frame () that MUST be the first frame the server sends in the HTTP/2 connection. The SETTINGS frames received from a peer as part of the connection preface MUST be acknowledged (see ) after sending the connection preface. To avoid unnecessary latency, clients are permitted to send additional frames to the server immediately after sending the client connection preface, without waiting to receive the server connection preface. It is important to note, however, that the server connection preface SETTINGS frame might include parameters that necessarily alter how a client is expected to communicate with the server. Upon receiving the SETTINGS frame, the client is expected to honor any parameters established. In some configurations, it is possible for the server to transmit SETTINGS before the client sends additional frames, providing an opportunity to avoid this issue. Clients and servers MUST treat an invalid connection preface as a connection error of type PROTOCOL_ERROR. A GOAWAY frame () MAY be omitted in this case, since an invalid preface indicates that the peer is not using HTTP/2.
Once the HTTP/2 connection is established, endpoints can begin exchanging frames.
All frames begin with a fixed 9-octet header followed by a variable-length payload.
The fields of the frame header are defined as: The length of the frame payload expressed as an unsigned 24-bit integer. Values greater than 214 (16,384) MUST NOT be sent unless the receiver has set a larger value for SETTINGS_MAX_FRAME_SIZE. The 9 octets of the frame header are not included in this value. The 8-bit type of the frame. The frame type determines the format and semantics of the frame. Implementations MUST ignore and discard any frame that has a type that is unknown. An 8-bit field reserved for frame-type specific boolean flags. Flags are assigned semantics specific to the indicated frame type. Flags that have no defined semantics for a particular frame type MUST be ignored, and MUST be left unset (0) when sending. A reserved 1-bit field. The semantics of this bit are undefined and the bit MUST remain unset (0) when sending and MUST be ignored when receiving. A 31-bit stream identifier (see ). The value 0 is reserved for frames that are associated with the connection as a whole as opposed to an individual stream. The structure and content of the frame payload is dependent entirely on the frame type.
The size of a frame payload is limited by the maximum size that a receiver advertises in the SETTINGS_MAX_FRAME_SIZE setting. This setting can have any value between 214 (16,384) and 224-1 (16,777,215) octets, inclusive. All implementations MUST be capable of receiving and minimally processing frames up to 214 octets in length, plus the 9 octet frame header. The size of the frame header is not included when describing frame sizes. Certain frame types, such as PING, impose additional limits on the amount of payload data allowed. If a frame size exceeds any defined limit, or is too small to contain mandatory frame data, the endpoint MUST send a FRAME_SIZE_ERROR error. A frame size error in a frame that could alter the state of the entire connection MUST be treated as a connection error; this includes any frame carrying a header block (that is, HEADERS, PUSH_PROMISE, and CONTINUATION), SETTINGS, and any WINDOW_UPDATE frame with a stream identifier of 0. Endpoints are not obligated to use all available space in a frame. Responsiveness can be improved by using frames that are smaller than the permitted maximum size. Sending large frames can result in delays in sending time-sensitive frames (such RST_STREAM, WINDOW_UPDATE, or PRIORITY) which if blocked by the transmission of a large frame, could affect performance.
Just as in HTTP/1, a header field in HTTP/2 is a name with one or more associated values. They are used within HTTP request and response messages as well as server push operations (see ). Header lists are collections of zero or more header fields. When transmitted over a connection, a header list is serialized into a header block using HTTP Header Compression. The serialized header block is then divided into one or more octet sequences, called header block fragments, and transmitted within the payload of HEADERS, PUSH_PROMISE or CONTINUATION frames. The Cookie header field is treated specially by the HTTP mapping (see ). A receiving endpoint reassembles the header block by concatenating its fragments, then decompresses the block to reconstruct the header list. A complete header block consists of either: a single HEADERS or PUSH_PROMISE frame, with the END_HEADERS flag set, or a HEADERS or PUSH_PROMISE frame with the END_HEADERS flag cleared and one or more CONTINUATION frames, where the last CONTINUATION frame has the END_HEADERS flag set. Header compression is stateful. One compression context and one decompression context is used for the entire connection. Each header block is processed as a discrete unit. Header blocks MUST be transmitted as a contiguous sequence of frames, with no interleaved frames of any other type or from any other stream. The last frame in a sequence of HEADERS or CONTINUATION frames MUST have the END_HEADERS flag set. The last frame in a sequence of PUSH_PROMISE or CONTINUATION frames MUST have the END_HEADERS flag set. This allows a header block to be logically equivalent to a single frame. Header block fragments can only be sent as the payload of HEADERS, PUSH_PROMISE or CONTINUATION frames, because these frames carry data that can modify the compression context maintained by a receiver. An endpoint receiving HEADERS, PUSH_PROMISE or CONTINUATION frames MUST reassemble header blocks and perform decompression even if the frames are to be discarded. A receiver MUST terminate the connection with a connection error of type COMPRESSION_ERROR if it does not decompress a header block.
A "stream" is an independent, bi-directional sequence of frames exchanged between the client and server within an HTTP/2 connection. Streams have several important characteristics: A single HTTP/2 connection can contain multiple concurrently open streams, with either endpoint interleaving frames from multiple streams. Streams can be established and used unilaterally or shared by either the client or server. Streams can be closed by either endpoint. The order in which frames are sent on a stream is significant. Recipients process frames in the order they are received. In particular, the order of HEADERS, and DATA frames is semantically significant. Streams are identified by an integer. Stream identifiers are assigned to streams by the endpoint initiating the stream.
The lifecycle of a stream is shown in .
| |<-----------' | | R | closed | R | `-------------------->| |<--------------------' +--------+ H: HEADERS frame (with implied CONTINUATIONs) PP: PUSH_PROMISE frame (with implied CONTINUATIONs) ES: END_STREAM flag R: RST_STREAM frame ]]>
Note that this diagram shows stream state transitions and the frames and flags that affect those transitions only. In this regard, CONTINUATION frames do not result in state transitions; they are effectively part of the HEADERS or PUSH_PROMISE that they follow. For this purpose, the END_STREAM flag is processed as a separate event to the frame that bears it; a HEADERS frame with the END_STREAM flag set can cause two state transitions. Both endpoints have a subjective view of the state of a stream that could be different when frames are in transit. Endpoints do not coordinate the creation of streams; they are created unilaterally by either endpoint. The negative consequences of a mismatch in states are limited to the "closed" state after sending RST_STREAM, where frames might be received for some time after closing. Streams have the following states: All streams start in the "idle" state. In this state, no frames have been exchanged. The following transitions are valid from this state: Sending or receiving a HEADERS frame causes the stream to become "open". The stream identifier is selected as described in . The same HEADERS frame can also cause a stream to immediately become "half closed". Sending a PUSH_PROMISE frame marks the associated stream for later use. The stream state for the reserved stream transitions to "reserved (local)". Receiving a PUSH_PROMISE frame marks the associated stream as reserved by the remote peer. The state of the stream becomes "reserved (remote)". Receiving any frames other than HEADERS or PUSH_PROMISE on a stream in this state MUST be treated as a connection error of type PROTOCOL_ERROR. A stream in the "reserved (local)" state is one that has been promised by sending a PUSH_PROMISE frame. A PUSH_PROMISE frame reserves an idle stream by associating the stream with an open stream that was initiated by the remote peer (see ). In this state, only the following transitions are possible: The endpoint can send a HEADERS frame. This causes the stream to open in a "half closed (remote)" state. Either endpoint can send a RST_STREAM frame to cause the stream to become "closed". This releases the stream reservation. An endpoint MUST NOT send any type of frame other than HEADERS or RST_STREAM in this state. A PRIORITY frame MAY be received in this state. Receiving any type of frame other than RST_STREAM or PRIORITY on a stream in this state MUST be treated as a connection error of type PROTOCOL_ERROR. A stream in the "reserved (remote)" state has been reserved by a remote peer. In this state, only the following transitions are possible: Receiving a HEADERS frame causes the stream to transition to "half closed (local)". Either endpoint can send a RST_STREAM frame to cause the stream to become "closed". This releases the stream reservation. An endpoint MAY send a PRIORITY frame in this state to reprioritize the reserved stream. An endpoint MUST NOT send any type of frame other than RST_STREAM, WINDOW_UPDATE, or PRIORITY in this state. Receiving any type of frame other than HEADERS or RST_STREAM on a stream in this state MUST be treated as a connection error of type PROTOCOL_ERROR. A stream in the "open" state may be used by both peers to send frames of any type. In this state, sending peers observe advertised stream level flow control limits. From this state either endpoint can send a frame with an END_STREAM flag set, which causes the stream to transition into one of the "half closed" states: an endpoint sending an END_STREAM flag causes the stream state to become "half closed (local)"; an endpoint receiving an END_STREAM flag causes the stream state to become "half closed (remote)". Either endpoint can send a RST_STREAM frame from this state, causing it to transition immediately to "closed". A stream that is in the "half closed (local)" state cannot be used for sending frames. Only WINDOW_UPDATE, PRIORITY and RST_STREAM frames can be sent in this state. A stream transitions from this state to "closed" when a frame that contains an END_STREAM flag is received, or when either peer sends a RST_STREAM frame. A receiver can ignore WINDOW_UPDATE frames in this state, which might arrive for a short period after a frame bearing the END_STREAM flag is sent. PRIORITY frames received in this state are used to reprioritize streams that depend on the current stream. A stream that is "half closed (remote)" is no longer being used by the peer to send frames. In this state, an endpoint is no longer obligated to maintain a receiver flow control window if it performs flow control. If an endpoint receives additional frames for a stream that is in this state, other than WINDOW_UPDATE, PRIORITY or RST_STREAM, it MUST respond with a stream error of type STREAM_CLOSED. A stream that is "half closed (remote)" can be used by the endpoint to send frames of any type. In this state, the endpoint continues to observe advertised stream level flow control limits. A stream can transition from this state to "closed" by sending a frame that contains an END_STREAM flag, or when either peer sends a RST_STREAM frame. The "closed" state is the terminal state. An endpoint MUST NOT send frames other than PRIORITY on a closed stream. An endpoint that receives any frame other than PRIORITY after receiving a RST_STREAM MUST treat that as a stream error of type STREAM_CLOSED. Similarly, an endpoint that receives any frames after receiving a frame with the END_STREAM flag set MUST treat that as a connection error of type STREAM_CLOSED, unless the frame is permitted as described below. WINDOW_UPDATE or RST_STREAM frames can be received in this state for a short period after a DATA or HEADERS frame containing an END_STREAM flag is sent. Until the remote peer receives and processes RST_STREAM or the frame bearing the END_STREAM flag, it might send frames of these types. Endpoints MUST ignore WINDOW_UPDATE or RST_STREAM frames received in this state, though endpoints MAY choose to treat frames that arrive a significant time after sending END_STREAM as a connection error of type PROTOCOL_ERROR. PRIORITY frames can be sent on closed streams to prioritize streams that are dependent on the closed stream. Endpoints SHOULD process PRIORITY frame, though they can be ignored if the stream has been removed from the dependency tree (see ). If this state is reached as a result of sending a RST_STREAM frame, the peer that receives the RST_STREAM might have already sent - or enqueued for sending - frames on the stream that cannot be withdrawn. An endpoint MUST ignore frames that it receives on closed streams after it has sent a RST_STREAM frame. An endpoint MAY choose to limit the period over which it ignores frames and treat frames that arrive after this time as being in error. Flow controlled frames (i.e., DATA) received after sending RST_STREAM are counted toward the connection flow control window. Even though these frames might be ignored, because they are sent before the sender receives the RST_STREAM, the sender will consider the frames to count against the flow control window. An endpoint might receive a PUSH_PROMISE frame after it sends RST_STREAM. PUSH_PROMISE causes a stream to become "reserved" even if the associated stream has been reset. Therefore, a RST_STREAM is needed to close an unwanted promised stream. In the absence of more specific guidance elsewhere in this document, implementations SHOULD treat the receipt of a frame that is not expressly permitted in the description of a state as a connection error of type PROTOCOL_ERROR. Frame of unknown types are ignored. An example of the state transitions for an HTTP request/response exchange can be found in . An example of the state transitions for server push can be found in and .
Streams are identified with an unsigned 31-bit integer. Streams initiated by a client MUST use odd-numbered stream identifiers; those initiated by the server MUST use even-numbered stream identifiers. A stream identifier of zero (0x0) is used for connection control messages; the stream identifier zero cannot be used to establish a new stream. HTTP/1.1 requests that are upgraded to HTTP/2 (see ) are responded to with a stream identifier of one (0x1). After the upgrade completes, stream 0x1 is "half closed (local)" to the client. Therefore, stream 0x1 cannot be selected as a new stream identifier by a client that upgrades from HTTP/1.1. The identifier of a newly established stream MUST be numerically greater than all streams that the initiating endpoint has opened or reserved. This governs streams that are opened using a HEADERS frame and streams that are reserved using PUSH_PROMISE. An endpoint that receives an unexpected stream identifier MUST respond with a connection error of type PROTOCOL_ERROR. 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. Stream identifiers cannot be reused. Long-lived connections can result in an endpoint exhausting the available range of stream identifiers. A client that is unable to establish a new stream identifier can establish a new connection for new streams. 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.
A peer can limit the number of concurrently active streams using the SETTINGS_MAX_CONCURRENT_STREAMS parameter (see ) within a SETTINGS frame. The maximum concurrent streams setting is specific to each endpoint and applies only to the peer that receives the setting. That is, clients specify the maximum number of concurrent streams the server can initiate, and servers specify the maximum number of concurrent streams the client can initiate. Streams that are in the "open" state, or either of the "half closed" states count toward the maximum number of streams that an endpoint is permitted to open. Streams in any of these three states count toward the limit advertised in the SETTINGS_MAX_CONCURRENT_STREAMS setting. Streams in either of the "reserved" states do not count toward the stream limit. 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. An endpoint that wishes to reduce the value of SETTINGS_MAX_CONCURRENT_STREAMS to a value that is below the current number of open streams can either close streams that exceed the new value or allow streams to complete.
Using streams for multiplexing introduces contention over use of the TCP connection, resulting in blocked streams. A flow control scheme ensures that streams on the same connection do not destructively interfere with each other. Flow control is used for both individual streams and for the connection as a whole. HTTP/2 provides for flow control through use of the WINDOW_UPDATE frame.
HTTP/2 stream flow control aims to allow a variety of flow control algorithms to be used without requiring protocol changes. Flow control in HTTP/2 has the following characteristics: Flow control is specific to a connection; i.e., it is "hop-by-hop", not "end-to-end". Flow control is based on window update frames. Receivers advertise how many octets they are prepared to receive on a stream and for the entire connection. This is a credit-based scheme. Flow control is directional with overall control provided by the receiver. A receiver MAY choose to set any window size that it desires for each stream and for the entire connection. A sender MUST respect flow control limits imposed by a receiver. Clients, servers and intermediaries all independently advertise their flow control window as a receiver and abide by the flow control limits set by their peer when sending. The initial value for the flow control window is 65,535 octets for both new streams and the overall connection. The frame type determines whether flow control applies to a frame. Of the frames specified in this document, only DATA frames are subject to flow control; all other frame types do not consume space in the advertised flow control window. This ensures that important control frames are not blocked by flow control. Flow control cannot be disabled. HTTP/2 defines only the format and semantics of the WINDOW_UPDATE frame (). This document does not stipulate how a receiver decides when to send this frame or the value that it sends, nor does it specify how a sender chooses to send packets. Implementations are able to select any algorithm that suits their needs. Implementations are also responsible for managing how requests and responses are sent based on priority; choosing how to avoid head of line blocking for requests; and managing the creation of new streams. Algorithm choices for these could interact with any flow control algorithm.
Flow control is defined to protect endpoints that are operating under resource constraints. For example, a proxy needs to share memory between many connections, and also might have a slow upstream connection and a fast downstream one. Flow control addresses cases where the receiver is unable process data on one stream, yet wants to continue to process other streams in the same connection. Deployments that do not require this capability can advertise a flow control window of the maximum size, incrementing the available space when new data is received. This effectively disables flow control for that receiver. Conversely, a sender is always subject to the flow control window advertised by the receiver. Deployments with constrained resources (for example, memory) can employ flow control to limit the amount of memory a peer can consume. Note, however, that this can lead to suboptimal use of available network resources if flow control is enabled without knowledge of the bandwidth-delay product (see ). Even with full awareness of the current bandwidth-delay product, implementation of flow control can be difficult. When using flow control, the receiver MUST read from the TCP receive buffer in a timely fashion. Failure to do so could lead to a deadlock when critical frames, such as WINDOW_UPDATE, are not read and acted upon.
A client can assign a priority for a new stream by including prioritization information in the HEADERS frame that opens the stream. For an existing stream, the PRIORITY frame can be used to change the priority. The purpose of prioritization is to allow an endpoint to express how it would prefer its peer allocate resources when managing concurrent streams. Most importantly, priority can be used to select streams for transmitting frames when there is limited capacity for sending. Streams can be prioritized by marking them as dependent on the completion of other streams (). Each dependency is assigned a relative weight, a number that is used to determine the relative proportion of available resources that are assigned to streams dependent on the same stream. Explicitly setting the priority for a stream is input to a prioritization process. It does not guarantee any particular processing or transmission order for the stream relative to any other stream. An endpoint cannot force a peer to process concurrent streams in a particular order using priority. Expressing priority is therefore only ever a suggestion. Providing prioritization information is optional, so default values are used if no explicit indicator is provided ().
Each stream can be given an explicit dependency on another stream. Including a dependency expresses a preference to allocate resources to the identified stream rather than to the dependent stream. A stream that is not dependent on any other stream is given a stream dependency of 0x0. In other words, the non-existent stream 0 forms the root of the tree. A stream that depends on another stream is a dependent stream. The stream upon which a stream is dependent is a parent stream. A dependency on a stream that is not currently in the tree - such as a stream in the "idle" state - results in that stream being given a default priority. When assigning a dependency on another stream, the stream is added as a new dependency of the parent stream. Dependent streams that share the same parent are not ordered with respect to each other. For example, if streams B and C are dependent on stream A, and if stream D is created with a dependency on stream A, this results in a dependency order of A followed by B, C, and D in any order.
/|\ B C B D C ]]>
An exclusive flag allows for the insertion of a new level of dependencies. 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. In the previous example, if stream D is created with an exclusive dependency on stream A, this results in D becoming the dependency parent of B and C.
D B C / \ B C ]]>
Inside the dependency tree, a dependent stream SHOULD only be allocated resources if all of the streams that it depends on (the chain of parent streams up to 0x0) are either closed, or it is not possible to make progress on them. A stream cannot depend on itself. An endpoint MUST treat this as a stream error of type PROTOCOL_ERROR.
All dependent streams are allocated an integer weight between 1 and 256 (inclusive). Streams with the same parent SHOULD be allocated resources proportionally based on their weight. Thus, if stream B depends on stream A with weight 4, and C depends on stream A with weight 12, and if no progress can be made on A, stream B ideally receives one third of the resources allocated to stream C.
Stream priorities are changed using the PRIORITY frame. Setting a dependency causes a stream to become dependent on the identified parent stream. Dependent streams move with their parent stream if the parent is reprioritized. Setting a dependency with the exclusive flag for a reprioritized stream moves all the dependencies of the new parent stream to become dependent on the reprioritized stream. 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.
For example, consider an original dependency tree where B and C depend on A, D and E depend on C, and F depends on D. If A is made dependent on D, then D takes the place of A. All other dependency relationships stay the same, except for F, which becomes dependent on A if the reprioritization is exclusive. F B C ==> F A OR A / \ | / \ /|\ D E E B C B C F | | | F E E (intermediate) (non-exclusive) (exclusive) ]]>
When a stream is removed from the dependency tree, its dependencies can be moved to become dependent on the parent of the closed stream. The weights of new dependencies are recalculated by distributing the weight of the dependency of the closed stream proportionally based on the weights of its dependencies. Streams that are removed from the dependency tree cause some prioritization information to be lost. Resources are shared between streams with the same parent stream, which means that if a stream in that set closes or becomes blocked, any spare capacity allocated to a stream is distributed to the immediate neighbors of the stream. However, if the common dependency is removed from the tree, those streams share resources with streams at the next highest level. For example, assume streams A and B share a parent, and streams C and D both depend on stream A. Prior to the removal of stream A, if streams A and D are unable to proceed, then stream C receives all the resources dedicated to stream A. If stream A is removed from the tree, the weight of stream A is divided between streams C and D. If stream D is still unable to proceed, this results in stream C receiving a reduced proportion of resources. For equal starting weights, C receives one third, rather than one half, of available resources. It is possible for a stream to become closed while prioritization information that creates a dependency on that stream is in transit. If a stream identified in a dependency has no associated priority information, then the dependent stream is instead assigned a default priority. This potentially creates suboptimal prioritization, since the stream could be given a priority that is different to 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. This could create a large state burden for an endpoint, so this state MAY be limited. An endpoint MAY apply a fixed upper limit on the number of closed streams for which prioritization state is tracked to limit state exposure. The amount of additional state an endpoint maintains could be dependent on load; under high load, prioritization state can be discarded to limit resource commitments. In extreme cases, an endpoint could even discard prioritization state for active or reserved streams. If a fixed limit is applied, endpoints SHOULD maintain state for at least as many streams as allowed by their setting for SETTINGS_MAX_CONCURRENT_STREAMS. An endpoint receiving a PRIORITY frame that changes the priority of a closed stream SHOULD alter the dependencies of the streams that depend on it, if it has retained enough state to do so.
Providing priority information is optional. Streams are assigned a non-exclusive dependency on stream 0x0 by default. Pushed streams initially depend on their associated stream. In both cases, streams are assigned a default weight of 16.
HTTP/2 framing permits two classes of error: An error condition that renders the entire connection unusable is a connection error. An error in an individual stream is a stream error. A list of error codes is included in .
A connection error is any error which prevents further processing of the framing layer, or which corrupts any connection state. An endpoint that encounters a connection error SHOULD first send a GOAWAY frame () with the stream identifier of the last stream that it successfully received from its peer. The GOAWAY frame includes an error code that indicates why the connection is terminating. After sending the GOAWAY frame, the endpoint MUST close the TCP connection. It is possible that the GOAWAY will not be reliably received by the receiving endpoint (see ). In the event of a connection error, GOAWAY only provides a best effort attempt to communicate with the peer about why the connection is being terminated. An endpoint can end a connection at any time. In particular, an endpoint MAY choose to treat a stream error as a connection error. Endpoints SHOULD send a GOAWAY frame when ending a connection, providing that circumstances permit it.
A stream error is an error related to a specific stream that does not affect processing of other streams. An endpoint that detects a stream error sends a RST_STREAM frame () that contains the stream identifier of the stream where the error occurred. The RST_STREAM frame includes an error code that indicates the type of error. A RST_STREAM is the last frame that an endpoint can send on a stream. The peer that sends the RST_STREAM frame MUST be prepared to receive any frames that were sent or enqueued for sending by the remote peer. These frames can be ignored, except where they modify connection state (such as the state maintained for header compression, or flow control). Normally, an endpoint SHOULD NOT send more than one RST_STREAM frame for any stream. However, an endpoint MAY send additional RST_STREAM frames if it receives frames on a closed stream after more than a round-trip time. This behavior is permitted to deal with misbehaving implementations. An endpoint MUST NOT send a RST_STREAM in response to an RST_STREAM frame, to avoid looping.
If the TCP connection is closed or reset while streams remain in open or half closed states, then the endpoint MUST assume that those streams were abnormally interrupted and could be incomplete.
HTTP/2 permits extension of the protocol. Protocol extensions can be used to provide additional services or alter any aspect of the protocol, within the limitations described in this section. Extensions are effective only within the scope of a single HTTP/2 connection. Extensions are permitted to use new frame types, new settings, or new error codes. Registries are established for managing these extension points: frame types, settings and error codes. Implementations MUST ignore unknown or unsupported values in all extensible protocol elements. Implementations MUST discard frames that have unknown or unsupported types. This means that any of these extension points can be safely used by extensions without prior arrangement or negotiation. However, extension frames that appear in the middle of a header block are not permitted; these MUST be treated as a connection error of type PROTOCOL_ERROR. However, extensions that could change the semantics of existing protocol components MUST be negotiated before being used. For example, an extension that changes the layout of the HEADERS frame cannot be used until the peer has given a positive signal that this is acceptable. In this case, it could also be necessary to coordinate when the revised layout comes into effect. Note that treating any frame other than DATA frames as flow controlled is such a change in semantics, and can only be done through negotiation. This document doesn't mandate a specific method for negotiating the use of an extension, but notes that a setting could be used for that purpose. If both peers set a value that indicates willingness to use the extension, then the extension can be used. If a setting is used for extension negotiation, the initial value MUST be defined so that the extension is initially disabled.
This specification defines a number of frame types, each identified by a unique 8-bit type code. Each frame type serves a distinct purpose either in the establishment and management of the connection as a whole, or of individual streams. The transmission of specific frame types can alter the state of a connection. If endpoints fail to maintain a synchronized view of the connection state, successful communication within the connection will no longer be possible. Therefore, it is important that endpoints have a shared comprehension of how the state is affected by the use any given frame.
DATA frames (type=0x0) convey arbitrary, variable-length sequences of octets associated with a stream. One or more DATA frames are used, for instance, to carry HTTP request or response payloads. DATA frames MAY also contain arbitrary padding. Padding can be added to DATA frames to obscure the size of messages.
The DATA frame contains the following fields: An 8-bit field containing the length of the frame padding in units of octets. This field is optional and is only present if the PADDED flag is set. Application data. The amount of data is the remainder of the frame payload after subtracting the length of the other fields that are present. Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending and ignored when receiving. The DATA frame defines the following flags: Bit 1 being set indicates that this frame is the last that the endpoint will send for the identified stream. Setting this flag causes the stream to enter one of the "half closed" states or the "closed" state. Bit 4 being set indicates that the Pad Length field and any padding that it describes is present. 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 of type PROTOCOL_ERROR. DATA frames are subject to flow control and can only be sent when a stream is in the "open" or "half closed (remote)" states. The entire DATA frame payload is included in flow control, including Pad Length and Padding fields if present. 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 of type STREAM_CLOSED. The total number of padding octets is determined by the value of the Pad Length field. If the length of the padding is greater than the length of the frame payload, the recipient MUST treat this as a connection error of type PROTOCOL_ERROR. A frame can be increased in size by one octet by including a Pad Length field with a value of zero. Padding is a security feature; see .
The HEADERS frame (type=0x1) is used to open a stream, and additionally carries a header block fragment. HEADERS frames can be sent on a stream in the "open" or "half closed (remote)" states.
The HEADERS frame payload has the following fields: An 8-bit field containing the length of the frame padding in units of octets. This field is only present if the PADDED flag is set. A single bit flag indicates that the stream dependency is exclusive, see . This field is only present if the PRIORITY flag is set. A 31-bit stream identifier for the stream that this stream depends on, see . This field is only present if the PRIORITY flag is set. An 8-bit weight for the stream, see . Add one to the value to obtain a weight between 1 and 256. This field is only present if the PRIORITY flag is set. A header block fragment. Padding octets that contain no application semantic value. Padding octets MUST be set to zero when sending and ignored when receiving. The HEADERS frame defines the following flags: Bit 1 being set 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. A HEADERS frame carries the END_STREAM flag that signals the end of a stream. However, a HEADERS frame with the END_STREAM flag set can be followed by CONTINUATION frames on the same stream. Logically, the CONTINUATION frames are part of the HEADERS frame. Bit 3 being set indicates that this frame contains an entire header block and is not followed by any CONTINUATION frames. A HEADERS frame without the END_HEADERS flag set MUST be followed by a CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error of type PROTOCOL_ERROR. Bit 4 being set indicates that the Pad Length field and any padding that it describes is present. Bit 6 being set indicates that the Exclusive Flag (E), Stream Dependency, and Weight fields are present; see . The payload of a HEADERS frame contains a header block fragment. A header block that does not fit within a HEADERS frame is continued in a CONTINUATION frame. 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 of type PROTOCOL_ERROR. The HEADERS frame changes the connection state as described in . The HEADERS frame includes optional padding. Padding fields and flags are identical to those defined for DATA frames. Prioritization information in a HEADERS frame is logically equivalent to a separate PRIORITY frame, but inclusion in HEADERS avoids the potential for churn in stream prioritization when new streams are created. Priorization fields in HEADERS frames subsequent to the first on a stream reprioritize the stream.
The PRIORITY frame (type=0x2) specifies the sender-advised priority of a stream. It can be sent at any time for an existing stream, including closed streams. This enables reprioritization of existing streams.
The payload of a PRIORITY frame contains the following fields: A single bit flag indicates that the stream dependency is exclusive, see . A 31-bit stream identifier for the stream that this stream depends on, see . An 8-bit weight for the identified stream dependency, see . Add one to the value to obtain a weight between 1 and 256. The PRIORITY frame does not define any flags. The PRIORITY frame is associated with an existing stream. If a PRIORITY frame is received with a stream identifier of 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. The PRIORITY frame can be sent on a stream in any of the "reserved (remote)", "open", "half closed (local)", "half closed (remote)", or "closed" states, though it cannot be sent between consecutive frames that comprise a single header block. Note that this frame could arrive after processing or frame sending has completed, which would cause it to have no effect on the current stream. For a stream that is in the "half closed (remote)" or "closed" - state, this frame can only affect processing of the current stream and not frame transmission. The PRIORITY frame is the only frame that can be sent for a stream in the "closed" state. This allows for the reprioritization of a group of dependent streams by altering the priority of a parent stream, which might be closed. However, a PRIORITY frame sent on a closed stream risks being ignored due to the peer having discarded priority state information for that stream.
The RST_STREAM frame (type=0x3) allows for abnormal termination of a stream. When sent by the initiator of a stream, it indicates that they wish to cancel the stream or that an error condition has occurred. When sent by the receiver of a stream, it indicates that either the receiver is rejecting the stream, requesting that the stream be cancelled, or that an error condition has occurred.
The RST_STREAM frame contains a single unsigned, 32-bit integer identifying the error code. The error code indicates why the stream is being terminated. The RST_STREAM frame does not define any flags. The RST_STREAM frame fully terminates the referenced stream and causes it to enter the closed state. After receiving a RST_STREAM on a stream, the receiver MUST NOT send additional frames for that stream, with the exception of PRIORITY. However, after sending the RST_STREAM, the sending endpoint MUST be prepared to receive and process additional frames sent on the stream that might have been sent by the peer prior to the arrival of the RST_STREAM. RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame is received with a stream identifier of 0x0, the recipient MUST treat this as a connection error of type PROTOCOL_ERROR. 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 of type PROTOCOL_ERROR.
The SETTINGS frame (type=0x4) conveys configuration parameters that affect how endpoints communicate, such as preferences and constraints on peer behavior. The SETTINGS frame is also used to acknowledge the receipt of those parameters. Individually, a SETTINGS parameter can also be referred to as a "setting". SETTINGS parameters are not negotiated; they describe characteristics of the sending peer, which are used by the receiving peer. Different values for the same parameter can be advertised by each peer. For example, a client might set a high initial flow control window, whereas a server might set a lower value to conserve resources. A SETTINGS frame MUST be sent by both endpoints at the start of a connection, and MAY be sent at any other time by either endpoint over the lifetime of the connection. Implementations MUST support all of the parameters defined by this specification. Each parameter in a SETTINGS frame replaces any existing value for that parameter. Parameters are processed in the order in which they appear, and a receiver of a SETTINGS frame does not need to maintain any state other than the current value of its parameters. Therefore, the value of a SETTINGS parameter is the last value that is seen by a receiver. SETTINGS parameters are acknowledged by the receiving peer. To enable this, the SETTINGS frame defines the following flag: Bit 1 being set indicates that this frame acknowledges receipt and application of the peer's SETTINGS frame. When this 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 of type FRAME_SIZE_ERROR. For more info, see Settings Synchronization. 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 of type PROTOCOL_ERROR. The SETTINGS frame affects connection state. A badly formed or incomplete SETTINGS frame MUST be treated as a connection error of type PROTOCOL_ERROR.
The payload of a SETTINGS frame consists of zero or more parameters, each consisting of an unsigned 16-bit setting identifier and an unsigned 32-bit value.
The following parameters are defined: Allows the sender to inform the remote endpoint of the maximum size of the header compression table used to decode header blocks, in octets. The encoder can select any size equal to or less than this value by using signaling specific to the header compression format inside a header block. The initial value is 4,096 octets. This setting can be use to disable server push. An endpoint MUST NOT send a PUSH_PROMISE frame if it receives this parameter set to a value of 0. An endpoint that has both set this parameter to 0 and had it acknowledged MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR. The initial value is 1, which indicates that server push is permitted. Any value other than 0 or 1 MUST be treated as a connection error of type PROTOCOL_ERROR. Indicates the maximum number of concurrent streams that the sender will allow. This limit is directional: it applies to the number of streams that the sender permits the receiver to create. Initially there is no limit to this value. It is recommended that this value be no smaller than 100, so as to not unnecessarily limit parallelism. A value of 0 for SETTINGS_MAX_CONCURRENT_STREAMS SHOULD NOT be treated as special by endpoints. A zero value does prevent the creation of new streams, however this can also happen for any limit that is exhausted with active streams. Servers SHOULD only set a zero value for short durations; if a server does not wish to accept requests, closing the connection could be preferable. Indicates the sender's initial window size (in octets) for stream level flow control. The initial value is 216-1 (65,535) octets. This setting affects the window size of all streams, including existing streams, see . Values above the maximum flow control window size of 231-1 MUST be treated as a connection error of type FLOW_CONTROL_ERROR. Indicates the size of the largest frame payload that the sender is willing to receive, in octets. The initial value is 214 (16,384) octets. The value advertised by an endpoint MUST be between this initial value and the maximum allowed frame size (224-1 or 16,777,215 octets), inclusive. Values outside this range MUST be treated as a connection error of type PROTOCOL_ERROR. This advisory setting informs a peer of the maximum size of header list that the sender is prepared to accept, in octets. The value is based on the uncompressed size of header fields, including the length of the name and value in octets plus an overhead of 32 octets for each header field. For any given request, a lower limit than what is advertised MAY be enforced. The initial value of this setting is unlimited. An endpoint that receives a SETTINGS frame with any unknown or unsupported identifier MUST ignore that setting.
Most values in SETTINGS benefit from or require an understanding of when the peer has received and applied the changed parameter values. In order to provide such synchronization timepoints, the recipient of a SETTINGS frame in which the ACK flag is not set MUST apply the updated parameters as soon as possible upon receipt. The values in the SETTINGS frame MUST be processed in the order they appear, with no other frame processing between values. Unsupported parameters MUST be ignored. Once all values have been processed, the recipient MUST immediately emit a SETTINGS frame with the ACK flag set. Upon receiving a SETTINGS frame with the ACK flag set, the sender of the altered parameters can rely on the setting having been applied. If the sender of a SETTINGS frame does not receive an acknowledgement within a reasonable amount of time, it MAY issue a connection error of type SETTINGS_TIMEOUT.
The PUSH_PROMISE frame (type=0x5) is used to notify the peer endpoint in advance of streams the sender intends to initiate. The PUSH_PROMISE frame includes the unsigned 31-bit identifier of the stream the endpoint plans to create along with a set of headers that provide additional context for the stream. contains a thorough description of the use of PUSH_PROMISE frames.
The PUSH_PROMISE frame payload has the following fields: An 8-bit field containing the length of the frame padding in units of octets. This field is only present if the PADDED flag is set. A single reserved bit. An unsigned 31-bit integer that identifies the stream that is reserved by the PUSH_PROMISE. The promised stream identifier MUST be a valid choice for the next stream sent by the sender (see new stream identifier). A header block fragment containing request header fields. Padding octets. The PUSH_PROMISE frame defines the following flags: Bit 3 being set indicates that this frame contains an entire header block and is not followed by any CONTINUATION frames. A PUSH_PROMISE frame without the END_HEADERS flag set MUST be followed by a CONTINUATION frame for the same stream. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error of type PROTOCOL_ERROR. Bit 4 being set indicates that the Pad Length field and any padding that it describes is present. 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 of type PROTOCOL_ERROR. Promised streams are not required to be used in the order they are promised. The PUSH_PROMISE only reserves stream identifiers for later use. 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 of type PROTOCOL_ERROR. Recipients of PUSH_PROMISE frames can choose to reject promised streams by returning a RST_STREAM referencing the promised stream identifier back to the sender of the PUSH_PROMISE. A PUSH_PROMISE frame modifies the connection state in two ways. The inclusion of a header block potentially modifies the state maintained for header compression. PUSH_PROMISE also reserves a stream for later use, causing the promised stream to enter the "reserved" state. A sender MUST NOT send a PUSH_PROMISE on a stream unless that stream is either "open" or "half closed (remote)"; the sender MUST ensure that the promised stream is a valid choice for a new stream identifier (that is, the promised stream MUST be in the "idle" state). Since PUSH_PROMISE reserves a stream, ignoring a PUSH_PROMISE frame causes the stream state to become indeterminate. A receiver MUST treat the receipt of a PUSH_PROMISE on a stream that is neither "open" nor "half closed (local)" as a connection error of type PROTOCOL_ERROR. However, an endpoint that has sent RST_STREAM on the associated stream MUST handle PUSH_PROMISE frames that might have been created before the RST_STREAM frame is received and processed. A receiver MUST treat the receipt of a PUSH_PROMISE that promises an illegal stream identifier (that is, an identifier for a stream that is not currently in the "idle" state) as a connection error of type PROTOCOL_ERROR. The PUSH_PROMISE frame includes optional padding. Padding fields and flags are identical to those defined for DATA frames.
The PING frame (type=0x6) is a mechanism for measuring a minimal round trip time from the sender, as well as determining whether an idle connection is still functional. PING frames can be sent from any endpoint.
In addition to the frame header, PING frames MUST contain 8 octets of data in the payload. A sender can include any value it chooses and use those bytes in any fashion. Receivers of a PING frame that does not include an ACK flag MUST send a PING frame with the ACK flag set in response, with an identical payload. PING responses SHOULD be given higher priority than any other frame. The PING frame defines the following flags: Bit 1 being set indicates that this PING frame is a PING response. An endpoint MUST set this flag in PING responses. An endpoint MUST NOT respond to PING frames containing this flag. 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 of type PROTOCOL_ERROR. Receipt of a PING frame with a length field value other than 8 MUST be treated as a connection error of type FRAME_SIZE_ERROR.
The GOAWAY frame (type=0x7) informs the remote peer to stop creating streams on this connection. GOAWAY can be sent by either the client or the server. Once sent, the sender will ignore frames sent on any new streams with identifiers higher than the included last stream identifier. Receivers of a GOAWAY frame MUST NOT open additional streams on the connection, although a new connection can be established for new streams. The purpose of this frame is to allow an endpoint to gracefully stop accepting new streams, while still finishing processing of previously established streams. This enables administrative actions, like server maintainance. There is an inherent race condition between an endpoint starting new streams and the remote sending a GOAWAY frame. To deal with this case, the GOAWAY contains the stream identifier of the last peer-initiated stream which was or might be processed on the sending endpoint in this connection. For instance, if the server sends a GOAWAY frame, the identified stream is the highest numbered stream initiated by the client. If the receiver of the GOAWAY has sent data on streams with a higher stream identifier than what is indicated in the GOAWAY frame, those streams are not or will not be processed. The receiver of the GOAWAY frame can treat the streams as though they had never been created at all, thereby allowing those streams to be retried later on a new connection. Endpoints SHOULD always send a GOAWAY frame before closing a connection so that the remote can know whether a stream has been partially processed or not. For example, if an HTTP client sends a POST at the same time that a server closes a connection, the client cannot know if the server started to process that POST request if the server does not send a GOAWAY frame to indicate what streams it might have acted on. An endpoint might choose to close a connection without sending GOAWAY for misbehaving peers.
The GOAWAY frame does not define any flags. The GOAWAY frame applies to the connection, not a specific stream. An endpoint MUST treat a GOAWAY frame with a stream identifier other than 0x0 as a connection error of type PROTOCOL_ERROR. The last stream identifier in the GOAWAY frame contains the highest numbered stream identifier for which the sender of the GOAWAY frame might have taken some action on, or might yet take action on. All streams up to and including the identified stream might have been processed in some way. The last stream identifier can be set to 0 if no streams were processed. In this context, "processed" means that some data from the stream was passed to some higher layer of software that might have taken some action as a result. If a connection terminates without a GOAWAY frame, the last stream identifier is effectively the highest possible stream identifier. On streams with lower or equal numbered identifiers that were not closed completely prior to the connection being closed, re-attempting requests, transactions, or any protocol activity is not possible, with the exception of idempotent actions like HTTP GET, PUT, or DELETE. Any protocol activity that uses higher numbered streams can be safely retried using a new connection. Activity on streams numbered lower or equal to the last stream identifier might still complete successfully. The sender of a GOAWAY frame might gracefully shut down a connection by sending a GOAWAY frame, maintaining the connection in an open state until all in-progress streams complete. An endpoint MAY send multiple GOAWAY frames if circumstances change. For instance, an endpoint that sends GOAWAY with NO_ERROR during graceful shutdown could subsequently encounter an condition that requires immediate termination of the connection. The last stream identifier from the last GOAWAY frame received indicates which streams could have been acted upon. Endpoints MUST NOT increase the value they send in the last stream identifier, since the peers might already have retried unprocessed requests on another connection. A client that is unable to retry requests loses all requests that are in flight when the server closes the connection. This is especially true for intermediaries that might not be serving clients using HTTP/2. A server that is attempting to gracefully shut down a connection SHOULD send an initial GOAWAY frame with the last stream identifier set to 231-1 and a NO_ERROR code. This signals to the client that a shutdown is imminent and that no further requests can be initiated. After waiting at least one round trip time, the server can send another GOAWAY frame with an updated last stream identifier. This ensures that a connection can be cleanly shut down without losing requests. After sending a GOAWAY frame, the sender can discard frames for streams with identifiers higher than the identified last stream. However, any frames that alter connection state cannot be completely ignored. For instance, HEADERS, PUSH_PROMISE and CONTINUATION frames MUST be minimally processed to ensure the state maintained for header compression is consistent (see ); similarly DATA frames MUST be counted toward the connection flow control window. Failure to process these frames can cause flow control or header compression state to become unsynchronized. The GOAWAY frame also contains a 32-bit error code that contains the reason for closing the connection. Endpoints MAY append opaque data to the payload of any GOAWAY frame. Additional debug data is intended for diagnostic purposes only and carries no semantic value. Debug information could contain security- or privacy-sensitive data. Logged or otherwise persistently stored debug data MUST have adequate safeguards to prevent unauthorized access.
The WINDOW_UPDATE frame (type=0x8) is used to implement flow control; see for an overview. Flow control operates at two levels: on each individual stream and on the entire connection. Both types of flow control are hop-by-hop; that is, only between the two endpoints. Intermediaries do not forward WINDOW_UPDATE frames between dependent connections. However, throttling of data transfer by any receiver can indirectly cause the propagation of flow control information toward the original sender. Flow control only applies to frames that are identified as being subject to flow control. Of the frame types defined in this document, this includes only DATA frames. Frames that are exempt from flow control MUST be accepted and processed, unless the receiver is unable to assign resources to handling the frame. A receiver MAY respond with a stream error or connection error of type FLOW_CONTROL_ERROR if it is unable to accept a frame.
The payload of a WINDOW_UPDATE frame is one reserved bit, plus an unsigned 31-bit integer indicating the number of octets that the sender can transmit in addition to the existing flow control window. The legal range for the increment to the flow control window is 1 to 231-1 (0x7fffffff) octets. The WINDOW_UPDATE frame does not define any flags. The WINDOW_UPDATE frame can be specific to a stream or to the entire connection. In the former case, the frame's stream identifier indicates the affected stream; in the latter, the value "0" indicates that the entire connection is the subject of the frame. A receiver MUST treat the receipt of a WINDOW_UPDATE frame with an flow control window increment of 0 as a stream error of type PROTOCOL_ERROR; errors on the connection flow control window MUST be treated as a connection error. 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 . A receiver that receives a flow controlled frame MUST always account for its contribution against the connection flow control window, unless the receiver treats this as a connection error. This is necessary even if the frame is in error. Since the sender counts the frame toward the flow control window, if the receiver does not, the flow control window at sender and receiver can become different.
Flow control in HTTP/2 is implemented using a window kept by each sender on every stream. The flow control window is a simple integer value that indicates how many octets of data the sender is permitted to transmit; as such, its size is a measure of the buffering capacity of the receiver. Two flow control windows are applicable: the stream flow control window and the connection flow control window. The sender MUST NOT send a flow controlled frame with a length that exceeds the space available in either of the flow control windows advertised by the receiver. Frames with zero length with the END_STREAM flag set (that is, an empty DATA frame) MAY be sent if there is no available space in either flow control window. For flow control calculations, the 9 octet frame header is not counted. After sending a flow controlled frame, the sender reduces the space available in both windows by the length of the transmitted frame. The receiver of a frame sends a WINDOW_UPDATE frame as it consumes data and frees up space in flow control windows. Separate WINDOW_UPDATE frames are sent for the stream and connection level flow control windows. A sender that receives a WINDOW_UPDATE frame updates the corresponding window by the amount specified in the frame. A sender MUST NOT allow a flow control window to exceed 231-1 octets. 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, the sender sends a RST_STREAM with the error code of FLOW_CONTROL_ERROR code; for the connection, a GOAWAY frame with a FLOW_CONTROL_ERROR code. Flow controlled frames from the sender and WINDOW_UPDATE frames from the receiver are completely asynchronous with respect to each other. This property allows a receiver to aggressively update the window size kept by the sender to prevent streams from stalling.
When an HTTP/2 connection is first established, new streams are created with an initial flow control window size of 65,535 octets. The connection flow control window is 65,535 octets. Both endpoints can adjust the initial window size for new streams by including a value for SETTINGS_INITIAL_WINDOW_SIZE in the SETTINGS frame that forms part of the connection preface. The connection flow control window can only be changed using WINDOW_UPDATE frames. Prior to receiving a SETTINGS frame that sets a value for SETTINGS_INITIAL_WINDOW_SIZE, an endpoint can only use the default initial window size when sending flow controlled frames. Similarly, the connection flow control window is set to the default initial window size until a WINDOW_UPDATE frame is received. 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. A change to SETTINGS_INITIAL_WINDOW_SIZE can cause the available space in a flow control window to become negative. A sender MUST track the negative flow control window, and MUST NOT send new flow controlled frames until it receives WINDOW_UPDATE frames that cause the flow control window to become positive. For example, if the client sends 60KB immediately on connection establishment, and the server sets the initial window size to be 16KB, the client will recalculate the available flow control window to be -44KB on receipt of the SETTINGS frame. The client retains a negative flow control window until WINDOW_UPDATE frames restore the window to being positive, after which the client can resume sending. A SETTINGS frame cannot alter the connection flow control window. 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 of type FLOW_CONTROL_ERROR.
A receiver that wishes to use a smaller flow control window than the current size can send a new SETTINGS frame. However, the receiver MUST be prepared to receive data that exceeds this window size, since the sender might send data that exceeds the lower limit prior to processing the SETTINGS frame. After sending a SETTINGS frame that reduces the initial flow control window size, a receiver has two options for handling streams that exceed flow control limits: The receiver can immediately send RST_STREAM with FLOW_CONTROL_ERROR error code for the affected streams. The receiver can accept the streams and tolerate the resulting head of line blocking, sending WINDOW_UPDATE frames as it consumes data.
The CONTINUATION frame (type=0x9) is used to continue a sequence of header block fragments. Any number of CONTINUATION frames can be sent on an existing stream, as long as the preceding frame is on the same stream and is a HEADERS, PUSH_PROMISE or CONTINUATION frame without the END_HEADERS flag set.
The CONTINUATION frame payload contains a header block fragment. The CONTINUATION frame defines the following flag: Bit 3 being set indicates that this frame ends a header block. If the END_HEADERS bit is not set, this frame MUST be followed by another CONTINUATION frame. A receiver MUST treat the receipt of any other type of frame or a frame on a different stream as a connection error of type PROTOCOL_ERROR. The CONTINUATION frame changes the connection state as defined in . CONTINUATION frames MUST be associated with a stream. If a CONTINUATION frame is received whose stream identifier field is 0x0, the recipient MUST respond with a connection error of type PROTOCOL_ERROR. A CONTINUATION frame MUST be preceded by a HEADERS, PUSH_PROMISE or CONTINUATION frame without the END_HEADERS flag set. A recipient that observes violation of this rule MUST respond with a connection error of type PROTOCOL_ERROR.
Error codes are 32-bit fields that are used in RST_STREAM and GOAWAY frames to convey the reasons for the stream or connection error. Error codes share a common code space. Some error codes apply only to either streams or the entire connection and have no defined semantics in the other context. The following error codes are defined: The associated condition is not as a result of an error. For example, a GOAWAY might include this code to indicate graceful shutdown of a connection. The endpoint detected an unspecific protocol error. This error is for use when a more specific error code is not available. The endpoint encountered an unexpected internal error. The endpoint detected that its peer violated the flow control protocol. The endpoint sent a SETTINGS frame, but did not receive a response in a timely manner. See Settings Synchronization. The endpoint received a frame after a stream was half closed. The endpoint received a frame with an invalid size. The endpoint refuses the stream prior to performing any application processing, see for details. Used by the endpoint to indicate that the stream is no longer needed. The endpoint is unable to maintain the header compression context for the connection. The connection established in response to a CONNECT request was reset or abnormally closed. The endpoint detected that its peer is exhibiting a behavior that might be generating excessive load. The underlying transport has properties that do not meet minimum security requirements (see ). Unknown or unsupported error codes MUST NOT trigger any special behavior. These MAY be treated by an implementation as being equivalent to INTERNAL_ERROR.
HTTP/2 is intended to be as compatible as possible with current uses of HTTP. This means that, from the application perspective, the features of the protocol are largely unchanged. To achieve this, all request and response semantics are preserved, although the syntax of conveying those semantics has changed. Thus, the specification and requirements of HTTP/1.1 Semantics and Content , Conditional Requests , Range Requests , Caching and Authentication are applicable to HTTP/2. Selected portions of HTTP/1.1 Message Syntax and Routing , such as the HTTP and HTTPS URI schemes, are also applicable in HTTP/2, but the expression of those semantics for this protocol are defined in the sections below.
A client sends an HTTP request on a new stream, using a previously unused stream identifier. A server sends an HTTP response on the same stream as the request. An HTTP message (request or response) consists of: for a response only, zero or more HEADERS frames (each followed by zero or more CONTINUATION frames) containing the message headers of informational (1xx) HTTP responses (see and ), and one HEADERS frame (followed by zero or more CONTINUATION frames) containing the message headers (see ), and zero or more DATA frames containing the message payload (see ), and optionally, one HEADERS frame, followed by zero or more CONTINUATION frames containing the trailer-part, if present (see ). The last frame in the sequence bears an END_STREAM flag, noting that a HEADERS frame bearing the END_STREAM flag can be followed by CONTINUATION frames that carry any remaining portions of the header block. Other frames (from any stream) MUST NOT occur between either HEADERS frame and any CONTINUATION frames that might follow. Trailing header fields are carried in a header block that also terminates the stream. That is, a sequence starting with a HEADERS frame, followed by zero or more CONTINUATION frames, where the HEADERS frame bears an END_STREAM flag. Header blocks after the first that do not terminate the stream are not part of an HTTP request or response. A HEADERS frame (and associated CONTINUATION frames) can only appear at the start or end of a stream. An endpoint that receives a HEADERS frame without the END_STREAM flag set after receiving a final (non-informational) status code MUST treat the corresponding request or response as malformed. An HTTP request/response exchange fully consumes a single stream. A request starts with the HEADERS frame that puts the stream into an "open" state. The request ends with a frame bearing END_STREAM, which causes the stream to become "half closed (local)" for the client and "half closed (remote)" for the server. A response starts with a HEADERS frame and ends with a frame bearing END_STREAM, which places the stream in the "closed" state.
HTTP/2 removes support for the 101 (Switching Protocols) informational status code (). The semantics of 101 (Switching Protocols) aren't applicable to a multiplexed protocol. Alternative protocols are able to use the same mechanisms that HTTP/2 uses to negotiate their use (see ).
HTTP header fields carry information as a series of key-value pairs. For a listing of registered HTTP headers, see the Message Header Field Registry maintained at .
While HTTP/1.x used the message start-line (see ) to convey the target URI and method of the request, and the status code for the response, HTTP/2 uses special pseudo-header fields beginning with ':' character (ASCII 0x3a) for this purpose. Pseudo-header fields are not HTTP header fields. Endpoints MUST NOT generate pseudo-header fields other than those defined in this document. Pseudo-header fields are only valid in the context in which they are defined. Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header fields defined for responses MUST NOT appear in requests. Pseudo-header fields MUST NOT appear in trailers. Endpoints MUST treat a request or response that contains undefined or invalid pseudo-header fields as malformed. 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. A request or response containing uppercase header field names MUST be treated as malformed. All pseudo-header fields MUST appear in the header block before regular header fields. Any request or response that contains a pseudo-header field that appears in a header block after a regular header field MUST be treated as malformed.
HTTP/2 does not use the Connection header field to indicate connection-specific header fields; in this protocol, connection-specific metadata is conveyed by other means. An endpoint MUST NOT generate a HTTP/2 message containing connection-specific header fields; any message containing connection-specific header fields MUST be treated as malformed. This means that an intermediary transforming an HTTP/1.x message to HTTP/2 will need to remove any header fields nominated by the Connection header field, along with the Connection header field itself. Such intermediaries SHOULD also remove other connection-specific header fields, such as Keep-Alive, Proxy-Connection, Transfer-Encoding and Upgrade, even if they are not nominated by Connection. One exception to this is the TE header field, which MAY be present in an HTTP/2 request, but when it is MUST NOT contain any value other than "trailers". HTTP/2 purposefully does not support upgrade to another protocol. The handshake methods described in are believed sufficient to negotiate the use of alternative protocols.
The following pseudo-header fields are defined for HTTP/2 requests: The :method pseudo-header field includes the HTTP method (). The :scheme pseudo-header field includes the scheme portion of the target URI (). :scheme is not restricted to http and https schemed URIs. A proxy or gateway can translate requests for non-HTTP schemes, enabling the use of HTTP to interact with non-HTTP services. The :authority pseudo-header field includes the authority portion of the target URI (). The authority MUST NOT include the deprecated userinfo subcomponent for http or https schemed URIs. To ensure that the HTTP/1.1 request line can be reproduced accurately, this pseudo-header field MUST be omitted when translating from an HTTP/1.1 request that has a request target in origin or asterisk form (see ). Clients that generate HTTP/2 requests directly SHOULD use the :authority pseudo-header field instead of the Host header field. An intermediary that converts an HTTP/2 request to HTTP/1.1 MUST create a Host header field if one is not present in a request by copying the value of the :authority pseudo-header field. The :path pseudo-header field includes the path and query parts of the target URI (the path-absolute production from and optionally a '?' character followed by the query production, see and ). A request in asterisk form includes the value '*' for the :path pseudo-header field. This pseudo-header field MUST NOT be empty for http or https URIs; http or https URIs that do not contain a path component MUST include a value of '/'. The exception to this rule is an OPTIONS request for an http or https URI that does not include a path component; these MUST include a :path pseudo-header field with a value of '*' (see ). All HTTP/2 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header fields, unless it is a CONNECT request. An HTTP request that omits mandatory pseudo-header fields is malformed. HTTP/2 does not define a way to carry the version identifier that is included in the HTTP/1.1 request line.
For HTTP/2 responses, a single :status pseudo-header field is defined that carries the HTTP status code field (see ). This pseudo-header field MUST be included in all responses, otherwise the response is malformed. HTTP/2 does not define a way to carry the version or reason phrase that is included in an HTTP/1.1 status line.
The Cookie header field can carry a significant amount of redundant data. The Cookie header field uses a semi-colon (";") to delimit cookie-pairs (or "crumbs"). This header field doesn't follow the list construction rules in HTTP (see ), which prevents cookie-pairs from being separated into different name-value pairs. This can significantly reduce compression efficiency as individual cookie-pairs are updated. To allow for better compression efficiency, the Cookie header field MAY be split into separate header fields, each with one or more cookie-pairs. If there are multiple Cookie header fields after decompression, these MUST be concatenated into a single octet string using the two octet delimiter of 0x3B, 0x20 (the ASCII string "; ") before being passed into a non-HTTP/2 context, such as an HTTP/1.1 connection, or a generic HTTP server application.
Therefore, the following two lists of Cookie header fields are semantically equivalent.
A malformed request or response is one that is an otherwise valid sequence of HTTP/2 frames, but is otherwise invalid due to the presence of extraneous frames, prohibited header fields, the absence of mandatory header fields, or the inclusion of uppercase header field names. A request or response that includes an entity body can include a content-length header field. A request or response is also malformed if the value of a content-length header field does not equal the sum of the DATA frame payload lengths that form the body. A response that is defined to have no payload, as described in , can have a non-zero content-length header field, even though no content is included in DATA frames. Intermediaries that process HTTP requests or responses (i.e., any intermediary not acting as a tunnel) MUST NOT forward a malformed request or response. Malformed requests or responses that are detected MUST be treated as a stream error of type PROTOCOL_ERROR. For malformed requests, a server MAY send an HTTP response prior to closing or resetting the stream. Clients MUST NOT accept a malformed response. Note that these requirements are intended to protect against several types of common attacks against HTTP; they are deliberately strict, because being permissive can expose implementations to these vulnerabilities.
This section shows HTTP/1.1 requests and responses, with illustrations of equivalent HTTP/2 requests and responses. An HTTP GET request includes request header fields and no body and is therefore transmitted as a single HEADERS frame, followed by zero or more CONTINUATION frames containing the serialized block of request header fields. The HEADERS frame in the following has both the END_HEADERS and END_STREAM flags set; no CONTINUATION frames are sent:
+ END_STREAM Accept: image/jpeg + END_HEADERS :method = GET :scheme = https :path = /resource host = example.org accept = image/jpeg ]]>
Similarly, a response that includes only response header fields is transmitted as a HEADERS frame (again, followed by zero or more CONTINUATION frames) containing the serialized block of response header fields.
+ END_STREAM Expires: Thu, 23 Jan ... + END_HEADERS :status = 304 etag = "xyzzy" expires = Thu, 23 Jan ... ]]>
An HTTP POST request that includes request header fields and payload data is transmitted as one HEADERS frame, followed by zero or more CONTINUATION frames containing the request header fields, followed by one or more DATA frames, with the last CONTINUATION (or HEADERS) frame having the END_HEADERS flag set and the final DATA frame having the END_STREAM flag set:
- END_STREAM Content-Type: image/jpeg - END_HEADERS Content-Length: 123 :method = POST :path = /resource {binary data} :scheme = https CONTINUATION + END_HEADERS content-type = image/jpeg host = example.org content-length = 123 DATA + END_STREAM {binary data} ]]> Note that data contributing to any given header field could be spread between header block fragments. The allocation of header fields to frames in this example is illustrative only.
A response that includes header fields and payload data is transmitted as a HEADERS frame, followed by zero or more CONTINUATION frames, followed by one or more DATA frames, with the last DATA frame in the sequence having the END_STREAM flag set:
- END_STREAM Content-Length: 123 + END_HEADERS :status = 200 {binary data} content-type = image/jpeg content-length = 123 DATA + END_STREAM {binary data} ]]>
Trailing header fields are sent as a header block after both the request or response header block and all the DATA frames have been sent. The HEADERS frame starting the trailers header block has the END_STREAM flag set.
- END_STREAM Transfer-Encoding: chunked + END_HEADERS Trailer: Foo :status = 200 content-length = 123 123 content-type = image/jpeg {binary data} trailer = Foo 0 Foo: bar DATA - END_STREAM {binary data} HEADERS + END_STREAM + END_HEADERS foo = bar ]]>
An informational response using a 1xx status code other than 101 is transmitted as a HEADERS frame, followed by zero or more CONTINUATION frames: - END_STREAM + END_HEADERS :status = 103 extension-field = bar ]]>
In HTTP/1.1, an HTTP client is unable to retry a non-idempotent request when an error occurs, because there is no means to determine the nature of the error. It is possible that some server processing occurred prior to the error, which could result in undesirable effects if the request were reattempted. HTTP/2 provides two mechanisms for providing a guarantee to a client that a request has not been processed: The GOAWAY frame indicates the highest stream number that might have been processed. Requests on streams with higher numbers are therefore guaranteed to be safe to retry. The REFUSED_STREAM error code can be included in a RST_STREAM frame to indicate that the stream is being closed prior to any processing having occurred. Any request that was sent on the reset stream can be safely retried. Requests that have not been processed have not failed; clients MAY automatically retry them, even those with non-idempotent methods. A server MUST NOT indicate that a stream has not been processed unless it can guarantee that fact. If frames that are on a stream are passed to the application layer for any stream, then REFUSED_STREAM MUST NOT be used for that stream, and a GOAWAY frame MUST include a stream identifier that is greater than or equal to the given stream identifier. In addition to these mechanisms, the PING frame provides a way for a client to easily test a connection. Connections that remain idle can become broken as some middleboxes (for instance, network address translators, or load balancers) silently discard connection bindings. The PING frame allows a client to safely test whether a connection is still active without sending a request.
HTTP/2 allows a server to pre-emptively send (or "push") responses (along with corresponding "promised" requests) to a client in association with a previous client-initiated request. This can be useful when the server knows the client will need to have those responses available in order to fully process the response to the original request. Pushing additional message exchanges in this fashion is optional, and is negotiated between individual endpoints. The SETTINGS_ENABLE_PUSH setting can be set to 0 to indicate that server push is disabled. Promised requests MUST be cacheable (see ), MUST be safe (see ) and MUST NOT include a request body. Clients that receive a promised request that is not cacheable, unsafe or that includes a request body MUST reset the stream with a stream error of type PROTOCOL_ERROR. Pushed responses that are cacheable (see ) can be stored by the client, if it implements a HTTP cache. Pushed responses are considered successfully validated on the origin server (e.g., if the "no-cache" cache response directive is present) while the stream identified by the promised stream ID is still open. Pushed responses that are not cacheable MUST NOT be stored by any HTTP cache. They MAY be made available to the application separately. An intermediary can receive pushes from the server and choose not to forward them on to the client. In other words, how to make use of the pushed information is up to that intermediary. Equally, the intermediary might choose to make additional pushes to the client, without any action taken by the server. A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE frame as a connection error of type PROTOCOL_ERROR. Clients MUST reject any attempt to change the SETTINGS_ENABLE_PUSH setting to a value other than 0 by treating the message as a connection error of type PROTOCOL_ERROR.
Server push is semantically equivalent to a server responding to a request; however, in this case that request is also sent by the server, as a PUSH_PROMISE frame. The PUSH_PROMISE frame includes a header block that contains a complete set of request header fields that the server attributes to the request. It is not possible to push a response to a request that includes a request body. Pushed responses are always associated with an explicit request from the client. The PUSH_PROMISE frames sent by the server are sent on that explicit request's stream. The PUSH_PROMISE frame also includes a promised stream identifier, chosen from the stream identifiers available to the server (see ). The header fields in PUSH_PROMISE and any subsequent CONTINUATION frames MUST be a valid and complete set of request header fields. The server MUST include a method in the :method header field that is safe and cacheable. If a client receives a PUSH_PROMISE that does not include a complete and valid set of header fields, or the :method header field identifies a method that is not safe, it MUST respond with a stream error of type PROTOCOL_ERROR. The server SHOULD send PUSH_PROMISE () frames prior to sending any frames that reference the promised responses. This avoids a race where clients issue requests prior to receiving any PUSH_PROMISE frames. For example, if the server receives a request for a document containing embedded links to multiple image files, and the server chooses to push those additional images to the client, sending push promises before the DATA frames that contain the image links ensures that the client is able to see the promises before discovering embedded links. Similarly, if the server pushes responses referenced by the header block (for instance, in Link header fields), sending the push promises before sending the header block ensures that clients do not request them. PUSH_PROMISE frames MUST NOT be sent by the client. PUSH_PROMISE frames can be sent by the server in response to any client-initiated stream, but the stream MUST be in either the "open" or "half closed (remote)" state with respect to the server. PUSH_PROMISE frames are interspersed with the frames that comprise a response, though they cannot be interspersed with HEADERS and CONTINUATION frames that comprise a single header block. Sending a PUSH_PROMISE frame creates a new stream and puts the stream into the “reserved (local)” state for the server and the “reserved (remote)” state for the client.
After sending the PUSH_PROMISE frame, the server can begin delivering the pushed response as a response on a server-initiated stream that uses the promised stream identifier. The server uses this stream to transmit an HTTP response, using the same sequence of frames as defined in . This stream becomes "half closed" to the client after the initial HEADERS frame is sent. Once a client receives a PUSH_PROMISE frame and chooses to accept the pushed response, the client SHOULD NOT issue any requests for the promised response until after the promised stream has closed. If the client determines, for any reason, that it does not wish to receive the pushed response from the server, or if the server takes too long to begin sending the promised response, the client can send an RST_STREAM frame, using either the CANCEL or REFUSED_STREAM codes, and referencing the pushed stream's identifier. A client can use the SETTINGS_MAX_CONCURRENT_STREAMS setting to limit the number of responses that can be concurrently pushed by a server. Advertising a SETTINGS_MAX_CONCURRENT_STREAMS value of zero disables server push by preventing the server from creating the necessary streams. This does not prohibit a server from sending PUSH_PROMISE frames; clients need to reset any promised streams that are not wanted. Clients receiving a pushed response MUST validate that either the server is authoritative (see ), or the proxy that provided the pushed response is configured for the corresponding request. For example, a server that offers a certificate for only the example.com DNS-ID or Common Name is not permitted to push a response for https://www.example.org/doc. The response for a PUSH_PROMISE stream begins with a HEADERS frame, which immediately puts the stream into the “half closed (remote)” state for the server and “half closed (local)” state for the client, and ends with a frame bearing END_STREAM, which places the stream in the "closed" state. The client never sends a frame with the END_STREAM flag for a server push.
In HTTP/1.x, the pseudo-method CONNECT () is used to convert an HTTP connection into a tunnel to a remote host. CONNECT is primarily used with HTTP proxies to establish a TLS session with an origin server for the purposes of interacting with https resources. In HTTP/2, the CONNECT method is used to establish a tunnel over a single HTTP/2 stream to a remote host, for similar purposes. The HTTP header field mapping works as defined in Request Header Fields, with a few differences. Specifically: The :method header field is set to CONNECT. The :scheme and :path header fields MUST be omitted. The :authority header field contains the host and port to connect to (equivalent to the authority-form of the request-target of CONNECT requests, see ). A proxy that supports CONNECT establishes a TCP connection to the server identified in the :authority header field. Once this connection is successfully established, the proxy sends a HEADERS frame containing a 2xx series status code to the client, as defined in . After the initial HEADERS frame sent by each peer, all subsequent DATA frames correspond to data sent on the TCP connection. The payload of any DATA frames sent by the client is transmitted by the proxy to the TCP server; data received from the TCP server is assembled into DATA frames by the proxy. Frame types other than DATA or stream management frames (RST_STREAM, WINDOW_UPDATE, and PRIORITY) MUST NOT be sent on a connected stream, and MUST be treated as a stream error if received. The TCP connection can be closed by either peer. The END_STREAM flag on a DATA frame is treated as being equivalent to the TCP FIN bit. A client is expected to send a DATA frame with the END_STREAM flag set after receiving a frame bearing the END_STREAM flag. A proxy that receives a DATA frame with the END_STREAM flag set sends the attached data with the FIN bit set on the last TCP segment. A proxy that receives a TCP segment with the FIN bit set sends a DATA frame with the END_STREAM flag set. Note that the final TCP segment or DATA frame could be empty. A TCP connection error is signaled with RST_STREAM. A proxy treats any error in the TCP connection, which includes receiving a TCP segment with the RST bit set, as a stream error of type CONNECT_ERROR. Correspondingly, a proxy MUST send a TCP segment with the RST bit set if it detects an error with the stream or the HTTP/2 connection.
This section outlines attributes of the HTTP protocol that improve interoperability, reduce exposure to known security vulnerabilities, or reduce the potential for implementation variation.
HTTP/2 connections are persistent. For best performance, it is expected clients will not close connections until it is determined that no further communication with a server is necessary (for example, when a user navigates away from a particular web page), or until the server closes the connection. Clients SHOULD NOT open more than one HTTP/2 connection to a given host and port pair, where host is derived from a URI, a selected alternative service, or a configured proxy. A client can create additional connections as replacements, either to replace connections that are near to exhausting the available stream identifier space, to refresh the keying material for a TLS connection, or to replace connections that have encountered errors. A client MAY open multiple connections to the same IP address and TCP port using different Server Name Indication values or to provide different TLS client certificates, but SHOULD avoid creating multiple connections with the same configuration. Servers are encouraged to maintain open connections for as long as possible, but are permitted to terminate idle connections if necessary. When either endpoint chooses to close the transport-layer TCP connection, the terminating endpoint SHOULD first send a GOAWAY () frame so that both endpoints can reliably determine whether previously sent frames have been processed and gracefully complete or terminate any necessary remaining tasks.
Connections that are made to an origin servers, either directly or through a tunnel created using the CONNECT method MAY be reused for requests with multiple different URI authority components. A connection can be reused as long as the origin server is authoritative. For http resources, this depends on the host having resolved to the same IP address. For https resources, connection reuse additionally depends on having a certificate that is valid for the host in the URI. An origin server might offer a certificate with multiple subjectAltName attributes, or names with wildcards, one of which is valid for the authority in the URI. For example, a certificate with a subjectAltName of *.example.com might permit the use of the same connection for requests to URIs starting with https://a.example.com/ and https://b.example.com/. In some deployments, reusing a connection for multiple origins can result in requests being directed to the wrong origin server. For example, TLS termination might be performed by a middlebox that uses the TLS Server Name Indication (SNI) extension to select an origin server. This means that it is possible for clients to send confidential information to servers that might not be the intended target for the request, even though the server is otherwise authoritative. A server that does not wish clients to reuse connections can indicate that it is not authoritative for a request by sending a 421 (Misdirected Request) status code in response to the request (see ). A client that is configured to use a proxy over HTTP/2 directs requests to that proxy through a single connection. That is, all requests sent via a proxy reuse the connection to the proxy.
The 421 (Misdirected Request) status code indicates that the request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI. Clients receiving a 421 (Misdirected Request) response from a server MAY retry the request - whether the request method is idempotent or not - over a different connection. This is possible if a connection is reused () or if an alternative service is selected (). This status code MUST NOT be generated by proxies. A 421 response is cacheable by default; i.e., unless otherwise indicated by the method definition or explicit cache controls (see ).
Implementations of HTTP/2 MUST support TLS 1.2 for HTTP/2 over TLS. The general TLS usage guidance in SHOULD be followed, with some additional restrictions that are specific to HTTP/2. 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 these minimum requirements with a connection error of type INADEQUATE_SECURITY.
The TLS implementation MUST support the Server Name Indication (SNI) extension to TLS. HTTP/2 clients MUST indicate the target domain name when negotiating TLS. The TLS implementation MUST disable compression. TLS compression can lead to the exposure of information that would not otherwise be revealed . Generic compression is unnecessary since HTTP/2 provides compression features that are more aware of context and therefore likely to be more appropriate for use for performance, security or other reasons. The TLS implementation MUST disable renegotiation. An endpoint MUST treat a TLS renegotiation as a connection error of type PROTOCOL_ERROR. Note that disabling renegotiation can result in long-lived connections becoming unusable due to limits on the number of messages the underlying cipher suite can encipher. A client MAY use renegotiation to provide confidentiality protection for client credentials offered in the handshake, but any renegotiation MUST occur prior to sending the connection preface. A server SHOULD request a client certificate if it sees a renegotiation request immediately after establishing a connection. This effectively prevents the use of renegotiation in response to a request for a specific protected resource. A future specification might provide a way to support this use case.
The set of TLS cipher suites that are permitted in HTTP/2 is restricted. HTTP/2 MUST only be used with cipher suites that have ephemeral key exchange, such as the ephemeral Diffie-Hellman (DHE) or the elliptic curve variant (ECDHE). Ephemeral key exchange MUST have a minimum size of 2048 bits for DHE or security level of 128 bits for ECDHE. Clients MUST accept DHE sizes of up to 4096 bits. HTTP MUST NOT be used with cipher suites that use stream or block ciphers. Authenticated Encryption with Additional Data (AEAD) modes, such as the Galois Counter Model (GCM) mode for AES are acceptable. The effect of these restrictions is that TLS 1.2 implementations could have non-intersecting sets of available cipher suites, since these prevent the use of the cipher suite that TLS 1.2 makes mandatory. To avoid this problem, implementations of HTTP/2 that use TLS 1.2 MUST support TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 with P256 . Clients MAY advertise support of cipher suites that are prohibited by the above restrictions in order to allow for connection to servers that do not support HTTP/2. This enables a fallback to protocols without these constraints without the additional latency imposed by using a separate connection for fallback.
HTTP/2 relies on the HTTP/1.1 definition of authority for determining whether a server is authoritative in providing a given response, see . This relies on local name resolution for the "http" URI scheme, and the authenticated server identity for the "https" scheme (see ).
In a cross-protocol attack, an attacker causes a client to initiate a transaction in one protocol toward a server that understands a different protocol. An attacker might be able to cause the transaction to appear as valid transaction in the second protocol. In combination with the capabilities of the web context, this can be used to interact with poorly protected servers in private networks. Completing a TLS handshake with an ALPN identifier for HTTP/2 can be considered sufficient protection against cross protocol attacks. ALPN provides a positive indication that a server is willing to proceed with HTTP/2, which prevents attacks on other TLS-based protocols. The encryption in TLS makes it difficult for attackers to control the data which could be used in a cross-protocol attack on a cleartext protocol. The cleartext version of HTTP/2 has minimal protection against cross-protocol attacks. The connection preface contains a string that is designed to confuse HTTP/1.1 servers, but no special protection is offered for other protocols. A server that is willing to ignore parts of an HTTP/1.1 request containing an Upgrade header field in addition to the client connection preface could be exposed to a cross-protocol attack.
HTTP/2 header field names and values are encoded as sequences of octets with a length prefix. This enables HTTP/2 to carry any string of octets as the name or value of a header field. An intermediary that translates HTTP/2 requests or responses into HTTP/1.1 directly could permit the creation of corrupted HTTP/1.1 messages. An attacker might exploit this behavior to cause the intermediary to create HTTP/1.1 messages with illegal header fields, extra header fields, or even new messages that are entirely falsified. Header field names or values that contain characters not permitted by HTTP/1.1, including carriage return (ASCII 0xd) or line feed (ASCII 0xa) MUST NOT be translated verbatim by an intermediary, as stipulated in . Translation from HTTP/1.x to HTTP/2 does not produce the same opportunity to an attacker. Intermediaries that perform translation to HTTP/2 MUST remove any instances of the obs-fold production from header field values.
Pushed responses do not have an explicit request from the client; the request is provided by the server in the PUSH_PROMISE frame. Caching responses that are pushed is possible based on the guidance provided by the origin server in the Cache-Control header field. However, this can cause issues if a single server hosts more than one tenant. For example, a server might offer multiple users each a small portion of its URI space. Where multiple tenants share space on the same server, that server MUST ensure that tenants are not able to push representations of resources that they do not have authority over. Failure to enforce this would allow a tenant to provide a representation that would be served out of cache, overriding the actual representation that the authoritative tenant provides. Pushed responses for which an origin server is not authoritative (see ) are never cached or used.
An HTTP/2 connection can demand a greater commitment of resources to operate than a HTTP/1.1 connection. The use of header compression and flow control depend on a commitment of resources for storing a greater amount of state. Settings for these features ensure that memory commitments for these features are strictly bounded. The number of PUSH_PROMISE frames is not constrained in the same fashion. A client that accepts server push SHOULD limit the number of streams it allows to be in the "reserved (remote)" state. Excessive number of server push streams can be treated as a stream error of type ENHANCE_YOUR_CALM. Processing capacity cannot be guarded as effectively as state capacity. The SETTINGS frame can be abused to cause a peer to expend additional processing time. This might be done by pointlessly changing SETTINGS parameters, setting multiple undefined parameters, or changing the same setting multiple times in the same frame. WINDOW_UPDATE or PRIORITY frames can be abused to cause an unnecessary waste of resources. Large numbers of small or empty frames can be abused to cause a peer to expend time processing frame headers. Note however that some uses are entirely legitimate, such as the sending of an empty DATA frame to end a stream. Header compression also offers some opportunities to waste processing resources; see for more details on potential abuses. Limits in SETTINGS parameters cannot be reduced instantaneously, which leaves an endpoint exposed to behavior from a peer that could exceed the new limits. In particular, immediately after establishing a connection, limits set by a server are not known to clients and could be exceeded without being an obvious protocol violation. All these features - i.e., SETTINGS changes, small frames, header compression - have legitimate uses. These features become a burden only when they are used unnecessarily or to excess. An endpoint that doesn't monitor this behavior exposes itself to a risk of denial of service attack. Implementations SHOULD track the use of these features and set limits on their use. An endpoint MAY treat activity that is suspicious as a connection error of type ENHANCE_YOUR_CALM.
A large header block can cause an implementation to commit a large amount of state. Header fields that are critical for routing can appear toward the end of a header block, which prevents streaming of header fields to their ultimate destination. For this an other reasons, such as ensuring cache correctness, means that an endpoint might need to buffer the entire header block. Since there is no hard limit to the size of a header block, some endpoints could be forced commit a large amount of available memory for header fields. An endpoint can use the SETTINGS_MAX_HEADER_LIST_SIZE to advise peers of limits that might apply on the size of header blocks. This setting is only advisory, so endpoints MAY choose to send header blocks that exceed this limit and risk having the request or response being treated as malformed. This setting specific to a connection, so any request or response could encounter a hop with a lower, unknown limit. An intermediary can attempt to avoid this problem by passing on values presented by different peers, but they are not obligated to do so. 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 . A client can discard responses that it cannot process. The header block MUST be processed to ensure a consistent connection state, unless the connection is closed.
HTTP/2 enables greater use of compression for both header fields () and entity bodies. Compression can allow an attacker to recover secret data when it is compressed in the same context as data under attacker control. There are demonstrable attacks on compression that exploit the characteristics of the web (e.g., ). The attacker induces multiple requests containing varying plaintext, observing the length of the resulting ciphertext in each, which reveals a shorter length when a guess about the secret is correct. Implementations communicating on a secure channel MUST NOT compress content that includes both confidential and attacker-controlled data unless separate compression dictionaries are used for each source of data. Compression MUST NOT be used if the source of data cannot be reliably determined. Generic stream compression, such as that provided by TLS MUST NOT be used with HTTP/2 (). Further considerations regarding the compression of header fields are described in .
Padding within HTTP/2 is not intended as a replacement for general purpose padding, such as might be provided by TLS. Redundant padding could even be counterproductive. Correct application can depend on having specific knowledge of the data that is being padded. To mitigate attacks that rely on compression, disabling or limiting compression might be preferable to padding as a countermeasure. Padding can be used to obscure the exact size of frame content, and is provided to mitigate specific attacks within HTTP. For example, attacks where compressed content includes both attacker-controlled plaintext and secret data (see for example, ). Use of padding can result in less protection than might seem immediately obvious. At best, padding only makes it more difficult for an attacker to infer length information by increasing the number of frames an attacker has to observe. Incorrectly implemented padding schemes can be easily defeated. In particular, randomized padding with a predictable distribution provides very little protection; similarly, padding payloads to a fixed size exposes information as payload sizes cross the fixed size boundary, which could be possible if an attacker can control plaintext. Intermediaries SHOULD retain padding for DATA frames, but MAY drop padding for HEADERS and PUSH_PROMISE frames. A valid reason for an intermediary to change the amount of padding of frames is to improve the protections that padding provides.
Several characteristics of HTTP/2 provide an observer an opportunity to correlate actions of a single client or server over time. This includes the value of settings, the manner in which flow control windows are managed, the way priorities are allocated to streams, timing of reactions to stimulus, and handling of any optional features. As far as this creates observable differences in behavior, they could be used as a basis for fingerprinting a specific client, as defined in .
A string for identifying HTTP/2 is entered into the "Application Layer Protocol Negotiation (ALPN) Protocol IDs" registry established in . This document establishes a registry for frame types, settings, and error codes. These new registries are entered into a new "Hypertext Transfer Protocol (HTTP) 2 Parameters" section. This document registers the HTTP2-Settings header field for use in HTTP; and the 421 (Misdirected Request) status code. This document registers the PRI method for use in HTTP, to avoid collisions with the connection preface.
This document creates two registrations for the identification of HTTP/2 in the "Application Layer Protocol Negotiation (ALPN) Protocol IDs" registry established in . The "h2" string identifies HTTP/2 when used over TLS: HTTP/2 over TLS 0x68 0x32 ("h2") This document The "h2c" string identifies HTTP/2 when used over cleartext TCP: HTTP/2 over TCP 0x68 0x32 0x63 ("h2c") This document
This document establishes a registry for HTTP/2 frame type codes. The "HTTP/2 Frame Type" registry manages an 8-bit space. The "HTTP/2 Frame Type" registry operates under either of the "IETF Review" or "IESG Approval" policies for values between 0x00 and 0xef, with values between 0xf0 and 0xff being reserved for experimental use. New entries in this registry require the following information: A name or label for the frame type. The 8-bit code assigned to the frame type. A reference to a specification that includes a description of the frame layout, it's semantics and flags that the frame type uses, including any parts of the frame that are conditionally present based on the value of flags. The entries in the following table are registered by this document. Frame Type Code Section DATA0x0 HEADERS0x1 PRIORITY0x2 RST_STREAM0x3 SETTINGS0x4 PUSH_PROMISE0x5 PING0x6 GOAWAY0x7 WINDOW_UPDATE0x8 CONTINUATION0x9
This document establishes a registry for HTTP/2 settings. The "HTTP/2 Settings" registry manages a 16-bit space. The "HTTP/2 Settings" registry operates under the "Expert Review" policy for values in the range from 0x0000 to 0xefff, with values between and 0xf000 and 0xffff being reserved for experimental use. New registrations are advised to provide the following information: A symbolic name for the setting. Specifying a setting name is optional. The 16-bit code assigned to the setting. An initial value for the setting. An optional reference to a specification that describes the use of the setting. An initial set of setting registrations can be found in . Name Code Initial Value Specification HEADER_TABLE_SIZE 0x14096 ENABLE_PUSH 0x21 MAX_CONCURRENT_STREAMS 0x3(infinite) INITIAL_WINDOW_SIZE 0x465535 MAX_FRAME_SIZE 0x516384 MAX_HEADER_LIST_SIZE 0x6(infinite)
This document establishes a registry for HTTP/2 error codes. The "HTTP/2 Error Code" registry manages a 32-bit space. The "HTTP/2 Error Code" registry operates under the "Expert Review" policy. Registrations for error codes are required to include a description of the error code. An expert reviewer is advised to examine new registrations for possible duplication with existing error codes. Use of existing registrations is to be encouraged, but not mandated. New registrations are advised to provide the following information: A name for the error code. Specifying an error code name is optional. The 32-bit error code value. A brief description of the error code semantics, longer if no detailed specification is provided. An optional reference for a specification that defines the error code. The entries in the following table are registered by this document. Name Code Description Specification NO_ERROR0x0 Graceful shutdown PROTOCOL_ERROR0x1 Protocol error detected INTERNAL_ERROR0x2 Implementation fault FLOW_CONTROL_ERROR0x3 Flow control limits exceeded SETTINGS_TIMEOUT0x4 Settings not acknowledged STREAM_CLOSED0x5 Frame received for closed stream FRAME_SIZE_ERROR0x6 Frame size incorrect REFUSED_STREAM0x7 Stream not processed CANCEL0x8 Stream cancelled COMPRESSION_ERROR0x9 Compression state not updated CONNECT_ERROR0xa TCP connection error for CONNECT method ENHANCE_YOUR_CALM0xb Processing capacity exceeded INADEQUATE_SECURITY0xc Negotiated TLS parameters not acceptable
This section registers the HTTP2-Settings header field in the Permanent Message Header Field Registry. HTTP2-Settings http standard IETF of this document This header field is only used by an HTTP/2 client for Upgrade-based negotiation.
This section registers the PRI method in the HTTP Method Registry (). PRI No No of this document This method is never used by an actual client. This method will appear to be used when an HTTP/1.1 server or intermediary attempts to parse an HTTP/2 connection preface.
This document registers the 421 (Misdirected Request) HTTP Status code in the Hypertext Transfer Protocol (HTTP) Status Code Registry (). 421 Misdirected Request of this document
This document includes substantial input from the following individuals: Adam Langley, Wan-Teh Chang, Jim Morrison, Mark Nottingham, Alyssa Wilk, Costin Manolache, William Chan, Vitaliy Lvin, Joe Chan, Adam Barth, Ryan Hamilton, Gavin Peters, Kent Alstad, Kevin Lindsay, Paul Amer, Fan Yang, Jonathan Leighton (SPDY contributors). Gabriel Montenegro and Willy Tarreau (Upgrade mechanism). William Chan, Salvatore Loreto, Osama Mazahir, Gabriel Montenegro, Jitu Padhye, Roberto Peon, Rob Trace (Flow control). Mike Bishop (Extensibility). Mark Nottingham, Julian Reschke, James Snell, Jeff Pinner, Mike Bishop, Herve Ruellan (Substantial editorial contributions). Kari Hurtta, Tatsuhiro Tsujikawa, Greg Wilkins, Poul-Henning Kamp. Alexey Melnikov was an editor of this document during 2013. A substantial proportion of Martin's contribution was supported by Microsoft during his employment there.
HPACK - Header Compression for HTTP/2 Transmission Control Protocol University of Southern California (USC)/Information Sciences Institute Key words for use in RFCs to Indicate Requirement Levels Harvard University
sob@harvard.edu
HTTP Over TLS Uniform Resource Identifier (URI): Generic Syntax The Base16, Base32, and Base64 Data Encodings Guidelines for Writing an IANA Considerations Section in RFCs Augmented BNF for Syntax Specifications: ABNF The Transport Layer Security (TLS) Protocol Version 1.2 Transport Layer Security (TLS) Extensions: Extension Definitions Transport Layer Security (TLS) Application-Layer Protocol Negotiation Extension TLS Elliptic Curve Cipher Suites with SHA-256/384 and AES Galois Counter Mode (GCM) Digital Signature Standard (DSS) NIST Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Range Requests Adobe Systems Incorporated
fielding@gbiv.com
World Wide Web Consortium
ylafon@w3.org
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Caching Adobe Systems Incorporated
fielding@gbiv.com
Akamai
mnot@mnot.net
greenbytes GmbH
julian.reschke@greenbytes.de
Hypertext Transfer Protocol (HTTP/1.1): Authentication Adobe Systems Incorporated
fielding@gbiv.com
greenbytes GmbH
julian.reschke@greenbytes.de
HTTP State Management Mechanism
TCP Extensions for High Performance Transport Layer Security Protocol Compression Methods Additional HTTP Status Codes Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS) AES Galois Counter Mode (GCM) Cipher Suites for TLS HTML5 Latest version available at . Talking to Yourself for Fun and Profit BREACH: Reviving the CRIME Attack Registration Procedures for Message Header Fields Nine by Nine
GK-IETF@ninebynine.org
BEA Systems
mnot@pobox.com
HP Labs
JeffMogul@acm.org
Recommendations for Secure Use of TLS and DTLS HTTP Alternative Services Akamai Mozilla greenbytes
This section is to be removed by RFC Editor before publication.
Renamed Not Authoritative status code to Misdirected Request.
Pseudo-header fields are now required to appear strictly before regular ones. Restored 1xx series status codes, except 101. Changed frame length field 24-bits. Expanded frame header to 9 octets. Added a setting to limit the damage. Added a setting to advise peers of header set size limits. Removed segments. Made non-semantic-bearing HEADERS frames illegal in the HTTP mapping.
Restored extensibility options. Restricting TLS cipher suites to AEAD only. Removing Content-Encoding requirements. Permitting the use of PRIORITY after stream close. Removed ALTSVC frame. Removed BLOCKED frame. Reducing the maximum padding size to 256 octets; removing padding from CONTINUATION frames. Removed per-frame GZIP compression.
Added BLOCKED frame (at risk). Simplified priority scheme. Added DATA per-frame GZIP compression.
Changed "connection header" to "connection preface" to avoid confusion. Added dependency-based stream prioritization. Added "h2c" identifier to distinguish between cleartext and secured HTTP/2. Adding missing padding to PUSH_PROMISE. Integrate ALTSVC frame and supporting text. Dropping requirement on "deflate" Content-Encoding. Improving security considerations around use of compression.
Adding padding for data frames. Renumbering frame types, error codes, and settings. Adding INADEQUATE_SECURITY error code. Updating TLS usage requirements to 1.2; forbidding TLS compression. Removing extensibility for frames and settings. Changing setting identifier size. Removing the ability to disable flow control. Changing the protocol identification token to "h2". Changing the use of :authority to make it optional and to allow userinfo in non-HTTP cases. Allowing split on 0x0 for Cookie. Reserved PRI method in HTTP/1.1 to avoid possible future collisions.
Added cookie crumbling for more efficient header compression. Added header field ordering with the value-concatenation mechanism.
Marked draft for implementation.
Adding definition for CONNECT method. Constraining the use of push to safe, cacheable methods with no request body. Changing from :host to :authority to remove any potential confusion. Adding setting for header compression table size. Adding settings acknowledgement. Removing unnecessary and potentially problematic flags from CONTINUATION. Added denial of service considerations.
Marking the draft ready for implementation. Renumbering END_PUSH_PROMISE flag. Editorial clarifications and changes.
Added CONTINUATION frame for HEADERS and PUSH_PROMISE. PUSH_PROMISE is no longer implicitly prohibited if SETTINGS_MAX_CONCURRENT_STREAMS is zero. Push expanded to allow all safe methods without a request body. Clarified the use of HTTP header fields in requests and responses. Prohibited HTTP/1.1 hop-by-hop header fields. Requiring that intermediaries not forward requests with missing or illegal routing :-headers. Clarified requirements around handling different frames after stream close, stream reset and GOAWAY. Added more specific prohibitions for sending of different frame types in various stream states. Making the last received setting value the effective value. Clarified requirements on TLS version, extension and ciphers.
Committed major restructuring atrocities. Added reference to first header compression draft. Added more formal description of frame lifecycle. Moved END_STREAM (renamed from FINAL) back to HEADERS/DATA. Removed HEADERS+PRIORITY, added optional priority to HEADERS frame. Added PRIORITY frame.
Added continuations to frames carrying header blocks. Replaced use of "session" with "connection" to avoid confusion with other HTTP stateful concepts, like cookies. Removed "message". Switched to TLS ALPN from NPN. Editorial changes.
Added IANA considerations section for frame types, error codes and settings. Removed data frame compression. Added PUSH_PROMISE. Added globally applicable flags to framing. Removed zlib-based header compression mechanism. Updated references. Clarified stream identifier reuse. Removed CREDENTIALS frame and associated mechanisms. Added advice against naive implementation of flow control. Added session header section. Restructured frame header. Removed distinction between data and control frames. Altered flow control properties to include session-level limits. Added note on cacheability of pushed resources and multiple tenant servers. Changed protocol label form based on discussions.
Changed title throughout. Removed section on Incompatibilities with SPDY draft#2. Changed INTERNAL_ERROR on GOAWAY to have a value of 2 . Replaced abstract and introduction. Added section on starting HTTP/2.0, including upgrade mechanism. Removed unused references. Added flow control principles based on .
Adopted as base for draft-ietf-httpbis-http2. Updated authors/editors list. Added status note.
================================================ FILE: vendor/golang.org/x/net/http2/transport.go ================================================ // Copyright 2015 The Go Authors. // See https://go.googlesource.com/go/+/master/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://go.googlesource.com/go/+/master/LICENSE package http2 import ( "bufio" "bytes" "crypto/tls" "errors" "fmt" "io" "log" "net" "net/http" "strconv" "strings" "sync" "golang.org/x/net/http2/hpack" ) type Transport struct { Fallback http.RoundTripper // TODO: remove this and make more general with a TLS dial hook, like http InsecureTLSDial bool connMu sync.Mutex conns map[string][]*clientConn // key is host:port } type clientConn struct { t *Transport tconn *tls.Conn tlsState *tls.ConnectionState connKey []string // key(s) this connection is cached in, in t.conns readerDone chan struct{} // closed on error readerErr error // set before readerDone is closed hdec *hpack.Decoder nextRes *http.Response mu sync.Mutex closed bool goAway *GoAwayFrame // if non-nil, the GoAwayFrame we received streams map[uint32]*clientStream nextStreamID uint32 bw *bufio.Writer werr error // first write error that has occurred br *bufio.Reader fr *Framer // Settings from peer: maxFrameSize uint32 maxConcurrentStreams uint32 initialWindowSize uint32 hbuf bytes.Buffer // HPACK encoder writes into this henc *hpack.Encoder } type clientStream struct { ID uint32 resc chan resAndError pw *io.PipeWriter pr *io.PipeReader } 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 } func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { if req.URL.Scheme != "https" { if t.Fallback == nil { return nil, errors.New("http2: unsupported scheme and no Fallback") } return t.Fallback.RoundTrip(req) } host, port, err := net.SplitHostPort(req.URL.Host) if err != nil { host = req.URL.Host port = "443" } for { cc, err := t.getClientConn(host, port) if err != nil { return nil, err } res, err := cc.roundTrip(req) if shouldRetryRequest(err) { // TODO: or clientconn is overloaded (too many outstanding requests)? continue } if err != nil { 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() { t.connMu.Lock() defer t.connMu.Unlock() for _, vv := range t.conns { for _, cc := range vv { cc.closeIfIdle() } } } var errClientConnClosed = errors.New("http2: client conn is closed") func shouldRetryRequest(err error) bool { // TODO: or GOAWAY graceful shutdown stuff return err == errClientConnClosed } func (t *Transport) removeClientConn(cc *clientConn) { t.connMu.Lock() defer t.connMu.Unlock() for _, key := range cc.connKey { vv, ok := t.conns[key] if !ok { continue } newList := filterOutClientConn(vv, cc) if len(newList) > 0 { t.conns[key] = newList } else { delete(t.conns, key) } } } func filterOutClientConn(in []*clientConn, exclude *clientConn) []*clientConn { out := in[:0] for _, v := range in { if v != exclude { out = append(out, v) } } return out } func (t *Transport) getClientConn(host, port string) (*clientConn, error) { t.connMu.Lock() defer t.connMu.Unlock() key := net.JoinHostPort(host, port) for _, cc := range t.conns[key] { if cc.canTakeNewRequest() { return cc, nil } } if t.conns == nil { t.conns = make(map[string][]*clientConn) } cc, err := t.newClientConn(host, port, key) if err != nil { return nil, err } t.conns[key] = append(t.conns[key], cc) return cc, nil } func (t *Transport) newClientConn(host, port, key string) (*clientConn, error) { cfg := &tls.Config{ ServerName: host, NextProtos: []string{NextProtoTLS}, InsecureSkipVerify: t.InsecureTLSDial, } tconn, err := tls.Dial("tcp", net.JoinHostPort(host, port), cfg) if err != nil { return nil, err } if err := tconn.Handshake(); err != nil { return nil, err } if !t.InsecureTLSDial { if err := tconn.VerifyHostname(cfg.ServerName); err != nil { return nil, err } } state := tconn.ConnectionState() if p := state.NegotiatedProtocol; p != NextProtoTLS { // TODO(bradfitz): fall back to Fallback return nil, fmt.Errorf("bad protocol: %v", p) } if !state.NegotiatedProtocolIsMutual { return nil, errors.New("could not negotiate protocol mutually") } if _, err := tconn.Write(clientPreface); err != nil { return nil, err } cc := &clientConn{ t: t, tconn: tconn, connKey: []string{key}, // TODO: cert's validated hostnames too tlsState: &state, 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), } cc.bw = bufio.NewWriter(stickyErrWriter{tconn, &cc.werr}) cc.br = bufio.NewReader(tconn) cc.fr = NewFramer(cc.bw, cc.br) cc.henc = hpack.NewEncoder(&cc.hbuf) cc.fr.WriteSettings() // TODO: re-send more conn-level flow control tokens when server uses all these. cc.fr.WriteWindowUpdate(0, 1<<30) // um, 0x7fffffff doesn't work to Google? it hangs? cc.bw.Flush() if cc.werr != nil { return nil, cc.werr } // Read the obligatory SETTINGS frame f, err := cc.fr.ReadFrame() if err != nil { return nil, err } sf, ok := f.(*SettingsFrame) if !ok { return nil, fmt.Errorf("expected settings frame, got: %T", f) } cc.fr.WriteSettingsAck() cc.bw.Flush() sf.ForeachSetting(func(s Setting) error { switch s.ID { case SettingMaxFrameSize: cc.maxFrameSize = s.Val case SettingMaxConcurrentStreams: cc.maxConcurrentStreams = s.Val case SettingInitialWindowSize: cc.initialWindowSize = s.Val default: // TODO(bradfitz): handle more log.Printf("Unhandled Setting: %v", s) } return nil }) // TODO: figure out henc size cc.hdec = hpack.NewDecoder(initialHeaderTableSize, cc.onNewHeaderField) go cc.readLoop() return cc, nil } func (cc *clientConn) setGoAway(f *GoAwayFrame) { cc.mu.Lock() defer cc.mu.Unlock() cc.goAway = f } func (cc *clientConn) canTakeNewRequest() bool { cc.mu.Lock() defer cc.mu.Unlock() return cc.goAway == nil && int64(len(cc.streams)+1) < int64(cc.maxConcurrentStreams) && cc.nextStreamID < 2147483647 } func (cc *clientConn) closeIfIdle() { cc.mu.Lock() if len(cc.streams) > 0 { cc.mu.Unlock() return } cc.closed = true // TODO: do clients send GOAWAY too? maybe? Just Close: cc.mu.Unlock() cc.tconn.Close() } func (cc *clientConn) roundTrip(req *http.Request) (*http.Response, error) { cc.mu.Lock() if cc.closed { cc.mu.Unlock() return nil, errClientConnClosed } cs := cc.newStream() hasBody := false // TODO // we send: HEADERS[+CONTINUATION] + (DATA?) hdrs := cc.encodeHeaders(req) first := true for len(hdrs) > 0 { chunk := hdrs if len(chunk) > int(cc.maxFrameSize) { chunk = chunk[:cc.maxFrameSize] } hdrs = hdrs[len(chunk):] endHeaders := len(hdrs) == 0 if first { cc.fr.WriteHeaders(HeadersFrameParam{ StreamID: cs.ID, BlockFragment: chunk, EndStream: !hasBody, EndHeaders: endHeaders, }) first = false } else { cc.fr.WriteContinuation(cs.ID, endHeaders, chunk) } } cc.bw.Flush() werr := cc.werr cc.mu.Unlock() if hasBody { // TODO: write data. and it should probably be interleaved: // go ... io.Copy(dataFrameWriter{cc, cs, ...}, req.Body) ... etc } if werr != nil { return nil, werr } re := <-cs.resc if re.err != nil { return nil, re.err } res := re.res res.Request = req res.TLS = cc.tlsState return res, nil } // requires cc.mu be held. func (cc *clientConn) encodeHeaders(req *http.Request) []byte { cc.hbuf.Reset() // TODO(bradfitz): figure out :authority-vs-Host stuff between http2 and Go host := req.Host if host == "" { host = req.URL.Host } path := req.URL.Path if path == "" { path = "/" } cc.writeHeader(":authority", host) // probably not right for all sites cc.writeHeader(":method", req.Method) cc.writeHeader(":path", path) cc.writeHeader(":scheme", "https") for k, vv := range req.Header { lowKey := strings.ToLower(k) if lowKey == "host" { continue } for _, v := range vv { cc.writeHeader(lowKey, v) } } return cc.hbuf.Bytes() } func (cc *clientConn) writeHeader(name, value string) { log.Printf("sending %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{ ID: cc.nextStreamID, resc: make(chan resAndError, 1), } cc.nextStreamID += 2 cc.streams[cs.ID] = cs return cs } func (cc *clientConn) streamByID(id uint32, andRemove bool) *clientStream { cc.mu.Lock() defer cc.mu.Unlock() cs := cc.streams[id] if andRemove { delete(cc.streams, id) } return cs } // runs in its own goroutine. func (cc *clientConn) readLoop() { defer cc.t.removeClientConn(cc) defer close(cc.readerDone) activeRes := map[uint32]*clientStream{} // keyed by streamID // 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. defer func() { err := cc.readerErr if err == io.EOF { err = io.ErrUnexpectedEOF } for _, cs := range activeRes { cs.pw.CloseWithError(err) } }() // continueStreamID is the stream ID we're waiting for // continuation frames for. var continueStreamID uint32 for { f, err := cc.fr.ReadFrame() if err != nil { cc.readerErr = err return } log.Printf("Transport received %v: %#v", f.Header(), f) streamID := f.Header().StreamID _, isContinue := f.(*ContinuationFrame) if isContinue { if streamID != continueStreamID { log.Printf("Protocol violation: got CONTINUATION with id %d; want %d", streamID, continueStreamID) cc.readerErr = ConnectionError(ErrCodeProtocol) return } } else if continueStreamID != 0 { // Continue frames need to be adjacent in the stream // and we were in the middle of headers. log.Printf("Protocol violation: got %T for stream %d, want CONTINUATION for %d", f, streamID, continueStreamID) cc.readerErr = ConnectionError(ErrCodeProtocol) return } if streamID%2 == 0 { // Ignore streams pushed from the server for now. // These always have an even stream id. continue } streamEnded := false if ff, ok := f.(streamEnder); ok { streamEnded = ff.StreamEnded() } cs := cc.streamByID(streamID, streamEnded) if cs == nil { log.Printf("Received frame for untracked stream ID %d", streamID) continue } switch f := f.(type) { case *HeadersFrame: cc.nextRes = &http.Response{ Proto: "HTTP/2.0", ProtoMajor: 2, Header: make(http.Header), } cs.pr, cs.pw = io.Pipe() cc.hdec.Write(f.HeaderBlockFragment()) case *ContinuationFrame: cc.hdec.Write(f.HeaderBlockFragment()) case *DataFrame: log.Printf("DATA: %q", f.Data()) cs.pw.Write(f.Data()) case *GoAwayFrame: cc.t.removeClientConn(cc) if f.ErrCode != 0 { // TODO: deal with GOAWAY more. particularly the error code log.Printf("transport got GOAWAY with error code = %v", f.ErrCode) } cc.setGoAway(f) default: log.Printf("Transport: unhandled response frame type %T", f) } headersEnded := false if he, ok := f.(headersEnder); ok { headersEnded = he.HeadersEnded() if headersEnded { continueStreamID = 0 } else { continueStreamID = streamID } } if streamEnded { cs.pw.Close() delete(activeRes, streamID) } if headersEnded { if cs == nil { panic("couldn't find stream") // TODO be graceful } // TODO: set the Body to one which notes the // Close and also sends the server a // RST_STREAM cc.nextRes.Body = cs.pr res := cc.nextRes activeRes[streamID] = cs cs.resc <- resAndError{res: res} } } } func (cc *clientConn) onNewHeaderField(f hpack.HeaderField) { // TODO: verifiy pseudo headers come before non-pseudo headers // TODO: verifiy the status is set log.Printf("Header field: %+v", f) if f.Name == ":status" { code, err := strconv.Atoi(f.Value) if err != nil { panic("TODO: be graceful") } cc.nextRes.Status = f.Value + " " + http.StatusText(code) cc.nextRes.StatusCode = code return } if strings.HasPrefix(f.Name, ":") { // "Endpoints MUST NOT generate pseudo-header fields other than those defined in this document." // TODO: treat as invalid? return } cc.nextRes.Header.Add(http.CanonicalHeaderKey(f.Name), f.Value) } ================================================ FILE: vendor/golang.org/x/net/http2/transport_test.go ================================================ // Copyright 2015 The Go Authors. // See https://go.googlesource.com/go/+/master/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://go.googlesource.com/go/+/master/LICENSE package http2 import ( "flag" "io" "io/ioutil" "net/http" "os" "reflect" "strings" "testing" "time" ) var ( extNet = flag.Bool("extnet", false, "do external network tests") transportHost = flag.String("transporthost", "http2.golang.org", "hostname to use for TestTransport") insecure = flag.Bool("insecure", false, "insecure TLS dials") ) func TestTransportExternal(t *testing.T) { if !*extNet { t.Skip("skipping external network test") } req, _ := http.NewRequest("GET", "https://"+*transportHost+"/", nil) rt := &Transport{ InsecureTLSDial: *insecure, } res, err := rt.RoundTrip(req) if err != nil { t.Fatalf("%v", err) } res.Write(os.Stdout) } func TestTransport(t *testing.T) { const body = "sup" st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, body) }) defer st.Close() tr := &Transport{InsecureTLSDial: true} defer tr.CloseIdleConnections() req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() t.Logf("Got res: %+v", res) if g, w := res.StatusCode, 200; g != w { t.Errorf("StatusCode = %v; want %v", g, w) } if g, w := res.Status, "200 OK"; g != w { t.Errorf("Status = %q; want %q", g, w) } wantHeader := http.Header{ "Content-Length": []string{"3"}, "Content-Type": []string{"text/plain; charset=utf-8"}, } if !reflect.DeepEqual(res.Header, wantHeader) { t.Errorf("res Header = %v; want %v", res.Header, wantHeader) } if res.Request != req { t.Errorf("Response.Request = %p; want %p", res.Request, req) } if res.TLS == nil { t.Error("Response.TLS = nil; want non-nil") } slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Errorf("Body read: %v", err) } else if string(slurp) != body { t.Errorf("Body = %q; want %q", slurp, body) } } func TestTransportReusesConns(t *testing.T) { st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, r.RemoteAddr) }, optOnlyServer) defer st.Close() tr := &Transport{InsecureTLSDial: true} defer tr.CloseIdleConnections() get := func() string { req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() slurp, err := ioutil.ReadAll(res.Body) if err != nil { t.Fatalf("Body read: %v", err) } addr := strings.TrimSpace(string(slurp)) if addr == "" { t.Fatalf("didn't get an addr in response") } return addr } first := get() second := get() if first != second { t.Errorf("first and second responses were on different connections: %q vs %q", first, second) } } func TestTransportAbortClosesPipes(t *testing.T) { shutdown := make(chan struct{}) st := newServerTester(t, func(w http.ResponseWriter, r *http.Request) { w.(http.Flusher).Flush() <-shutdown }, optOnlyServer, ) defer st.Close() defer close(shutdown) // we must shutdown before st.Close() to avoid hanging done := make(chan struct{}) requestMade := make(chan struct{}) go func() { defer close(done) tr := &Transport{ InsecureTLSDial: true, } req, err := http.NewRequest("GET", st.ts.URL, nil) if err != nil { t.Fatal(err) } res, err := tr.RoundTrip(req) if err != nil { t.Fatal(err) } defer res.Body.Close() close(requestMade) _, err = ioutil.ReadAll(res.Body) if err == nil { t.Error("expected error from res.Body.Read") } }() <-requestMade // Now force the serve loop to end, via closing the connection. st.closeConn() // deadlock? that's a bug. select { case <-done: case <-time.After(3 * time.Second): t.Fatal("timeout") } } ================================================ FILE: vendor/golang.org/x/net/http2/write.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "bytes" "fmt" "net/http" "time" "golang.org/x/net/http2/hpack" ) // writeFramer is implemented by any type that is used to write frames. type writeFramer interface { writeFrame(writeContext) error } // 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: use it from the client code too, once it exists. 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) } // endsStream reports whether the given frame writer w will locally // close the stream. func endsStream(w writeFramer) bool { switch v := w.(type) { case *writeData: return v.endStream case *writeResHeaders: return v.endStream } return false } type flushFrameWriter struct{} func (flushFrameWriter) writeFrame(ctx writeContext) error { return ctx.Flush() } type writeSettings []Setting 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 } 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 (se StreamError) writeFrame(ctx writeContext) error { return ctx.Framer().WriteRSTStream(se.StreamID, se.Code) } type writePingAck struct{ pf *PingFrame } func (w writePingAck) writeFrame(ctx writeContext) error { return ctx.Framer().WritePing(true, w.pf.Data) } type writeSettingsAck struct{} func (writeSettingsAck) writeFrame(ctx writeContext) error { return ctx.Framer().WriteSettingsAck() } // writeResHeaders is a request to write a HEADERS and 0+ CONTINUATION frames // for HTTP response headers from a server handler. type writeResHeaders struct { streamID uint32 httpResCode int h http.Header // may be nil endStream bool contentType string contentLength string } func (w *writeResHeaders) writeFrame(ctx writeContext) error { enc, buf := ctx.HeaderEncoder() buf.Reset() enc.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(w.httpResCode)}) for k, vv := range w.h { k = lowerHeader(k) for _, v := range vv { // TODO: more of "8.1.2.2 Connection-Specific Header Fields" if k == "transfer-encoding" && v != "trailers" { continue } enc.WriteField(hpack.HeaderField{Name: k, Value: v}) } } if w.contentType != "" { enc.WriteField(hpack.HeaderField{Name: "content-type", Value: w.contentType}) } if w.contentLength != "" { enc.WriteField(hpack.HeaderField{Name: "content-length", Value: w.contentLength}) } headerBlock := buf.Bytes() if len(headerBlock) == 0 { panic("unexpected empty hpack") } // 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):] endHeaders := len(headerBlock) == 0 var err error if first { first = false err = ctx.Framer().WriteHeaders(HeadersFrameParam{ StreamID: w.streamID, BlockFragment: frag, EndStream: w.endStream, EndHeaders: endHeaders, }) } else { err = ctx.Framer().WriteContinuation(w.streamID, endHeaders, frag) } if err != nil { return err } } return nil } type write100ContinueHeadersFrame struct { streamID uint32 } func (w write100ContinueHeadersFrame) writeFrame(ctx writeContext) error { enc, buf := ctx.HeaderEncoder() buf.Reset() enc.WriteField(hpack.HeaderField{Name: ":status", Value: "100"}) return ctx.Framer().WriteHeaders(HeadersFrameParam{ StreamID: w.streamID, BlockFragment: buf.Bytes(), EndStream: false, EndHeaders: true, }) } type writeWindowUpdate struct { streamID uint32 // or 0 for conn-level n uint32 } func (wu writeWindowUpdate) writeFrame(ctx writeContext) error { return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n) } ================================================ FILE: vendor/golang.org/x/net/http2/writesched.go ================================================ // 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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import "fmt" // frameWriteMsg is a request to write a frame. type frameWriteMsg struct { // write is the interface value that does the writing, once the // writeScheduler (below) has decided to select this frame // to write. The write functions are all defined in write.go. write writeFramer stream *stream // used for prioritization. nil for non-stream frames. // 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 } // for debugging only: func (wm frameWriteMsg) String() string { var streamID uint32 if wm.stream != nil { streamID = wm.stream.id } var des string if s, ok := wm.write.(fmt.Stringer); ok { des = s.String() } else { des = fmt.Sprintf("%T", wm.write) } return fmt.Sprintf("[frameWriteMsg stream=%d, ch=%v, type: %v]", streamID, wm.done != nil, des) } // writeScheduler tracks pending frames to write, priorities, and decides // the next one to use. It is not thread-safe. type writeScheduler struct { // zero are frames not associated with a specific stream. // They're sent before any stream-specific freams. zero writeQueue // maxFrameSize is the maximum size of a DATA frame // we'll write. Must be non-zero and between 16K-16M. maxFrameSize uint32 // sq contains the stream-specific queues, keyed by stream ID. // when a stream is idle, it's deleted from the map. sq map[uint32]*writeQueue // canSend is a slice of memory that's reused between frame // scheduling decisions to hold the list of writeQueues (from sq) // which have enough flow control data to send. After canSend is // built, the best is selected. canSend []*writeQueue // pool of empty queues for reuse. queuePool []*writeQueue } func (ws *writeScheduler) putEmptyQueue(q *writeQueue) { if len(q.s) != 0 { panic("queue must be empty") } ws.queuePool = append(ws.queuePool, q) } func (ws *writeScheduler) getEmptyQueue() *writeQueue { ln := len(ws.queuePool) if ln == 0 { return new(writeQueue) } q := ws.queuePool[ln-1] ws.queuePool = ws.queuePool[:ln-1] return q } func (ws *writeScheduler) empty() bool { return ws.zero.empty() && len(ws.sq) == 0 } func (ws *writeScheduler) add(wm frameWriteMsg) { st := wm.stream if st == nil { ws.zero.push(wm) } else { ws.streamQueue(st.id).push(wm) } } func (ws *writeScheduler) streamQueue(streamID uint32) *writeQueue { if q, ok := ws.sq[streamID]; ok { return q } if ws.sq == nil { ws.sq = make(map[uint32]*writeQueue) } q := ws.getEmptyQueue() ws.sq[streamID] = q return q } // take returns the most important frame to write and removes it from the scheduler. // It is illegal to call this if the scheduler is empty or if there are no connection-level // flow control bytes available. func (ws *writeScheduler) take() (wm frameWriteMsg, ok bool) { if ws.maxFrameSize == 0 { panic("internal error: ws.maxFrameSize not initialized or invalid") } // If there any frames not associated with streams, prefer those first. // These are usually SETTINGS, etc. if !ws.zero.empty() { return ws.zero.shift(), true } if len(ws.sq) == 0 { return } // Next, prioritize frames on streams that aren't DATA frames (no cost). for id, q := range ws.sq { if q.firstIsNoCost() { return ws.takeFrom(id, q) } } // Now, all that remains are DATA frames with non-zero bytes to // send. So pick the best one. if len(ws.canSend) != 0 { panic("should be empty") } for _, q := range ws.sq { if n := ws.streamWritableBytes(q); n > 0 { ws.canSend = append(ws.canSend, q) } } if len(ws.canSend) == 0 { return } defer ws.zeroCanSend() // TODO: find the best queue q := ws.canSend[0] return ws.takeFrom(q.streamID(), q) } // zeroCanSend is defered from take. func (ws *writeScheduler) zeroCanSend() { for i := range ws.canSend { ws.canSend[i] = nil } ws.canSend = ws.canSend[:0] } // streamWritableBytes returns the number of DATA bytes we could write // from the given queue's stream, if this stream/queue were // selected. It is an error to call this if q's head isn't a // *writeData. func (ws *writeScheduler) streamWritableBytes(q *writeQueue) int32 { wm := q.head() ret := wm.stream.flow.available() // max we can write if ret == 0 { return 0 } if int32(ws.maxFrameSize) < ret { ret = int32(ws.maxFrameSize) } if ret == 0 { panic("internal error: ws.maxFrameSize not initialized or invalid") } wd := wm.write.(*writeData) if len(wd.p) < int(ret) { ret = int32(len(wd.p)) } return ret } func (ws *writeScheduler) takeFrom(id uint32, q *writeQueue) (wm frameWriteMsg, ok bool) { wm = q.head() // If the first item in this queue costs flow control tokens // and we don't have enough, write as much as we can. if wd, ok := wm.write.(*writeData); ok && len(wd.p) > 0 { allowed := wm.stream.flow.available() // max we can write if allowed == 0 { // No quota available. Caller can try the next stream. return frameWriteMsg{}, false } if int32(ws.maxFrameSize) < allowed { allowed = int32(ws.maxFrameSize) } // TODO: further restrict the allowed size, because even if // the peer says it's okay to write 16MB data frames, we might // want to write smaller ones to properly weight competing // streams' priorities. if len(wd.p) > int(allowed) { wm.stream.flow.take(allowed) chunk := wd.p[:allowed] wd.p = wd.p[allowed:] // Make up a new write message of a valid size, rather // than shifting one off the queue. return frameWriteMsg{ stream: wm.stream, write: &writeData{ streamID: wd.streamID, p: chunk, // even if the original had endStream set, there // arebytes remaining because len(wd.p) > allowed, // so we know endStream is false: endStream: false, }, // our caller is blocking on the final DATA frame, not // these intermediates, so no need to wait: done: nil, }, true } wm.stream.flow.take(int32(len(wd.p))) } q.shift() if q.empty() { ws.putEmptyQueue(q) delete(ws.sq, id) } return wm, true } func (ws *writeScheduler) forgetStream(id uint32) { q, ok := ws.sq[id] if !ok { return } delete(ws.sq, id) // But keep it for others later. for i := range q.s { q.s[i] = frameWriteMsg{} } q.s = q.s[:0] ws.putEmptyQueue(q) } type writeQueue struct { s []frameWriteMsg } // streamID returns the stream ID for a non-empty stream-specific queue. func (q *writeQueue) streamID() uint32 { return q.s[0].stream.id } func (q *writeQueue) empty() bool { return len(q.s) == 0 } func (q *writeQueue) push(wm frameWriteMsg) { q.s = append(q.s, wm) } // head returns the next item that would be removed by shift. func (q *writeQueue) head() frameWriteMsg { if len(q.s) == 0 { panic("invalid use of queue") } return q.s[0] } func (q *writeQueue) shift() frameWriteMsg { if len(q.s) == 0 { panic("invalid use of queue") } wm := q.s[0] // TODO: less copy-happy queue. copy(q.s, q.s[1:]) q.s[len(q.s)-1] = frameWriteMsg{} q.s = q.s[:len(q.s)-1] return wm } func (q *writeQueue) firstIsNoCost() bool { if df, ok := q.s[0].write.(*writeData); ok { return len(df.p) == 0 } return true } ================================================ FILE: vendor/golang.org/x/net/http2/z_spec_test.go ================================================ // Copyright 2014 The Go Authors. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS // Licensed under the same terms as Go itself: // https://code.google.com/p/go/source/browse/LICENSE package http2 import ( "bytes" "encoding/xml" "flag" "fmt" "io" "os" "reflect" "regexp" "sort" "strconv" "strings" "sync" "testing" ) var coverSpec = flag.Bool("coverspec", false, "Run spec coverage tests") // The global map of sentence coverage for the http2 spec. var defaultSpecCoverage specCoverage var loadSpecOnce sync.Once func loadSpec() { if f, err := os.Open("testdata/draft-ietf-httpbis-http2.xml"); err != nil { panic(err) } else { defaultSpecCoverage = readSpecCov(f) f.Close() } } // covers marks all sentences for section sec in defaultSpecCoverage. Sentences not // "covered" will be included in report outputed by TestSpecCoverage. func covers(sec, sentences string) { loadSpecOnce.Do(loadSpec) defaultSpecCoverage.cover(sec, sentences) } type specPart struct { section string sentence string } func (ss specPart) Less(oo specPart) bool { atoi := func(s string) int { n, err := strconv.Atoi(s) if err != nil { panic(err) } return n } a := strings.Split(ss.section, ".") b := strings.Split(oo.section, ".") for len(a) > 0 { if len(b) == 0 { return false } x, y := atoi(a[0]), atoi(b[0]) if x == y { a, b = a[1:], b[1:] continue } return x < y } if len(b) > 0 { return true } return false } type bySpecSection []specPart func (a bySpecSection) Len() int { return len(a) } func (a bySpecSection) Less(i, j int) bool { return a[i].Less(a[j]) } func (a bySpecSection) Swap(i, j int) { a[i], a[j] = a[j], a[i] } type specCoverage struct { coverage map[specPart]bool d *xml.Decoder } func joinSection(sec []int) string { s := fmt.Sprintf("%d", sec[0]) for _, n := range sec[1:] { s = fmt.Sprintf("%s.%d", s, n) } return s } func (sc specCoverage) readSection(sec []int) { var ( buf = new(bytes.Buffer) sub = 0 ) for { tk, err := sc.d.Token() if err != nil { if err == io.EOF { return } panic(err) } switch v := tk.(type) { case xml.StartElement: if skipElement(v) { if err := sc.d.Skip(); err != nil { panic(err) } if v.Name.Local == "section" { sub++ } break } switch v.Name.Local { case "section": sub++ sc.readSection(append(sec, sub)) case "xref": buf.Write(sc.readXRef(v)) } case xml.CharData: if len(sec) == 0 { break } buf.Write(v) case xml.EndElement: if v.Name.Local == "section" { sc.addSentences(joinSection(sec), buf.String()) return } } } } func (sc specCoverage) readXRef(se xml.StartElement) []byte { var b []byte for { tk, err := sc.d.Token() if err != nil { panic(err) } switch v := tk.(type) { case xml.CharData: if b != nil { panic("unexpected CharData") } b = []byte(string(v)) case xml.EndElement: if v.Name.Local != "xref" { panic("expected ") } if b != nil { return b } sig := attrSig(se) switch sig { case "target": return []byte(fmt.Sprintf("[%s]", attrValue(se, "target"))) case "fmt-of,rel,target", "fmt-,,rel,target": return []byte(fmt.Sprintf("[%s, %s]", attrValue(se, "target"), attrValue(se, "rel"))) case "fmt-of,sec,target", "fmt-,,sec,target": return []byte(fmt.Sprintf("[section %s of %s]", attrValue(se, "sec"), attrValue(se, "target"))) case "fmt-of,rel,sec,target": return []byte(fmt.Sprintf("[section %s of %s, %s]", attrValue(se, "sec"), attrValue(se, "target"), attrValue(se, "rel"))) default: panic(fmt.Sprintf("unknown attribute signature %q in %#v", sig, fmt.Sprintf("%#v", se))) } default: panic(fmt.Sprintf("unexpected tag %q", v)) } } } var skipAnchor = map[string]bool{ "intro": true, "Overview": true, } var skipTitle = map[string]bool{ "Acknowledgements": true, "Change Log": true, "Document Organization": true, "Conventions and Terminology": true, } func skipElement(s xml.StartElement) bool { switch s.Name.Local { case "artwork": return true case "section": for _, attr := range s.Attr { switch attr.Name.Local { case "anchor": if skipAnchor[attr.Value] || strings.HasPrefix(attr.Value, "changes.since.") { return true } case "title": if skipTitle[attr.Value] { return true } } } } return false } func readSpecCov(r io.Reader) specCoverage { sc := specCoverage{ coverage: map[specPart]bool{}, d: xml.NewDecoder(r)} sc.readSection(nil) return sc } func (sc specCoverage) addSentences(sec string, sentence string) { for _, s := range parseSentences(sentence) { sc.coverage[specPart{sec, s}] = false } } func (sc specCoverage) cover(sec string, sentence string) { for _, s := range parseSentences(sentence) { p := specPart{sec, s} if _, ok := sc.coverage[p]; !ok { panic(fmt.Sprintf("Not found in spec: %q, %q", sec, s)) } sc.coverage[specPart{sec, s}] = true } } var whitespaceRx = regexp.MustCompile(`\s+`) func parseSentences(sens string) []string { sens = strings.TrimSpace(sens) if sens == "" { return nil } ss := strings.Split(whitespaceRx.ReplaceAllString(sens, " "), ". ") for i, s := range ss { s = strings.TrimSpace(s) if !strings.HasSuffix(s, ".") { s += "." } ss[i] = s } return ss } func TestSpecParseSentences(t *testing.T) { tests := []struct { ss string want []string }{ {"Sentence 1. Sentence 2.", []string{ "Sentence 1.", "Sentence 2.", }}, {"Sentence 1. \nSentence 2.\tSentence 3.", []string{ "Sentence 1.", "Sentence 2.", "Sentence 3.", }}, } for i, tt := range tests { got := parseSentences(tt.ss) if !reflect.DeepEqual(got, tt.want) { t.Errorf("%d: got = %q, want %q", i, got, tt.want) } } } func TestSpecCoverage(t *testing.T) { if !*coverSpec { t.Skip() } loadSpecOnce.Do(loadSpec) var ( list []specPart cv = defaultSpecCoverage.coverage total = len(cv) complete = 0 ) for sp, touched := range defaultSpecCoverage.coverage { if touched { complete++ } else { list = append(list, sp) } } sort.Stable(bySpecSection(list)) if testing.Short() && len(list) > 5 { list = list[:5] } for _, p := range list { t.Errorf("\tSECTION %s: %s", p.section, p.sentence) } t.Logf("%d/%d (%d%%) sentances covered", complete, total, (complete/total)*100) } func attrSig(se xml.StartElement) string { var names []string for _, attr := range se.Attr { if attr.Name.Local == "fmt" { names = append(names, "fmt-"+attr.Value) } else { names = append(names, attr.Name.Local) } } sort.Strings(names) return strings.Join(names, ",") } func attrValue(se xml.StartElement, attr string) string { for _, a := range se.Attr { if a.Name.Local == attr { return a.Value } } panic("unknown attribute " + attr) } func TestSpecPartLess(t *testing.T) { tests := []struct { sec1, sec2 string want bool }{ {"6.2.1", "6.2", false}, {"6.2", "6.2.1", true}, {"6.10", "6.10.1", true}, {"6.10", "6.1.1", false}, // 10, not 1 {"6.1", "6.1", false}, // equal, so not less } for _, tt := range tests { got := (specPart{tt.sec1, "foo"}).Less(specPart{tt.sec2, "foo"}) if got != tt.want { t.Errorf("Less(%q, %q) = %v; want %v", tt.sec1, tt.sec2, got, tt.want) } } } ================================================ FILE: vendor/golang.org/x/net/icmp/dstunreach.go ================================================ // 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 icmp // A DstUnreach represents an ICMP destination unreachable message // body. type DstUnreach struct { Data []byte // data, known as original datagram field Extensions []Extension // extensions } // Len implements the Len method of MessageBody interface. func (p *DstUnreach) Len(proto int) int { if p == nil { return 0 } l, _ := multipartMessageBodyDataLen(proto, p.Data, p.Extensions) return l } // Marshal implements the Marshal method of MessageBody interface. func (p *DstUnreach) Marshal(proto int) ([]byte, error) { return marshalMultipartMessageBody(proto, p.Data, p.Extensions) } // parseDstUnreach parses b as an ICMP destination unreachable message // body. func parseDstUnreach(proto int, b []byte) (MessageBody, error) { if len(b) < 4 { return nil, errMessageTooShort } p := &DstUnreach{} var err error p.Data, p.Extensions, err = parseMultipartMessageBody(proto, b) if err != nil { return nil, err } return p, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/echo.go ================================================ // 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 icmp // An Echo represents an ICMP echo request or reply message body. type Echo struct { ID int // identifier Seq int // sequence number Data []byte // data } // Len implements the Len method of MessageBody interface. func (p *Echo) Len(proto int) int { if p == nil { return 0 } return 4 + len(p.Data) } // Marshal implements the Marshal method of MessageBody interface. func (p *Echo) Marshal(proto int) ([]byte, error) { b := make([]byte, 4+len(p.Data)) b[0], b[1] = byte(p.ID>>8), byte(p.ID) b[2], b[3] = byte(p.Seq>>8), byte(p.Seq) copy(b[4:], p.Data) return b, nil } // parseEcho parses b as an ICMP echo request or reply message body. func parseEcho(proto int, b []byte) (MessageBody, error) { bodyLen := len(b) if bodyLen < 4 { return nil, errMessageTooShort } p := &Echo{ID: int(b[0])<<8 | int(b[1]), Seq: int(b[2])<<8 | int(b[3])} if bodyLen > 4 { p.Data = make([]byte, bodyLen-4) copy(p.Data, b[4:]) } return p, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/endpoint.go ================================================ // 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 icmp import ( "net" "runtime" "syscall" "time" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var _ net.PacketConn = &PacketConn{} type ipc interface{} // A PacketConn represents a packet network endpoint that uses either // ICMPv4 or ICMPv6. type PacketConn struct { c net.PacketConn ipc // either ipv4.PacketConn or ipv6.PacketConn } func (c *PacketConn) ok() bool { return c != nil && c.c != nil } // IPv4PacketConn returns the ipv4.PacketConn of c. // It returns nil when c is not created as the endpoint for ICMPv4. func (c *PacketConn) IPv4PacketConn() *ipv4.PacketConn { if !c.ok() { return nil } p, _ := c.ipc.(*ipv4.PacketConn) return p } // IPv6PacketConn returns the ipv6.PacketConn of c. // It returns nil when c is not created as the endpoint for ICMPv6. func (c *PacketConn) IPv6PacketConn() *ipv6.PacketConn { if !c.ok() { return nil } p, _ := c.ipc.(*ipv6.PacketConn) return p } // ReadFrom reads an ICMP message from the connection. func (c *PacketConn) ReadFrom(b []byte) (int, net.Addr, error) { if !c.ok() { return 0, nil, syscall.EINVAL } // Please be informed that ipv4.NewPacketConn enables // IP_STRIPHDR option by default on Darwin. // See golang.org/issue/9395 for futher information. if runtime.GOOS == "darwin" { if p, _ := c.ipc.(*ipv4.PacketConn); p != nil { n, _, peer, err := p.ReadFrom(b) return n, peer, err } } return c.c.ReadFrom(b) } // WriteTo writes the ICMP message b to dst. // Dst must be net.UDPAddr when c is a non-privileged // datagram-oriented ICMP endpoint. Otherwise it must be net.IPAddr. func (c *PacketConn) WriteTo(b []byte, dst net.Addr) (int, error) { if !c.ok() { return 0, syscall.EINVAL } return c.c.WriteTo(b, dst) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.ok() { return syscall.EINVAL } return c.c.Close() } // LocalAddr returns the local network address. func (c *PacketConn) LocalAddr() net.Addr { if !c.ok() { return nil } return c.c.LocalAddr() } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.ok() { return syscall.EINVAL } return c.c.SetWriteDeadline(t) } ================================================ FILE: vendor/golang.org/x/net/icmp/example_test.go ================================================ // 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 icmp_test import ( "log" "net" "os" "runtime" "golang.org/x/net/icmp" "golang.org/x/net/ipv6" ) func ExamplePacketConn_nonPrivilegedPing() { switch runtime.GOOS { case "darwin": case "linux": log.Println("you may need to adjust the net.ipv4.ping_group_range kernel state") default: log.Println("not supported on", runtime.GOOS) return } c, err := icmp.ListenPacket("udp6", "fe80::1%en0") if err != nil { log.Fatal(err) } defer c.Close() wm := icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: 1, Data: []byte("HELLO-R-U-THERE"), }, } wb, err := wm.Marshal(nil) if err != nil { log.Fatal(err) } if _, err := c.WriteTo(wb, &net.UDPAddr{IP: net.ParseIP("ff02::1"), Zone: "en0"}); err != nil { log.Fatal(err) } rb := make([]byte, 1500) n, peer, err := c.ReadFrom(rb) if err != nil { log.Fatal(err) } rm, err := icmp.ParseMessage(58, rb[:n]) if err != nil { log.Fatal(err) } switch rm.Type { case ipv6.ICMPTypeEchoReply: log.Printf("got reflection from %v", peer) default: log.Printf("got %+v; want echo reply", rm) } } ================================================ FILE: vendor/golang.org/x/net/icmp/extension.go ================================================ // 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 icmp // An Extension represents an ICMP extension. type Extension interface { // Len returns the length of ICMP extension. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Len(proto int) int // Marshal returns the binary enconding of ICMP extension. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Marshal(proto int) ([]byte, error) } const extensionVersion = 2 func validExtensionHeader(b []byte) bool { v := int(b[0]&0xf0) >> 4 s := uint16(b[2])<<8 | uint16(b[3]) if s != 0 { s = checksum(b) } if v != extensionVersion || s != 0 { return false } return true } // parseExtensions parses b as a list of ICMP extensions. // The length attribute l must be the length attribute field in // received icmp messages. // // It will return a list of ICMP extensions and an adjusted length // attribute that represents the length of the padded original // datagram field. Otherwise, it returns an error. func parseExtensions(b []byte, l int) ([]Extension, int, error) { // Still a lot of non-RFC 4884 compliant implementations are // out there. Set the length attribute l to 128 when it looks // inappropriate for backwards compatibility. // // A minimal extension at least requires 8 octets; 4 octets // for an extension header, and 4 octets for a single object // header. // // See RFC 4884 for further information. if 128 > l || l+8 > len(b) { l = 128 } if l+8 > len(b) { return nil, -1, errNoExtension } if !validExtensionHeader(b[l:]) { if l == 128 { return nil, -1, errNoExtension } l = 128 if !validExtensionHeader(b[l:]) { return nil, -1, errNoExtension } } var exts []Extension for b = b[l+4:]; len(b) >= 4; { ol := int(b[0])<<8 | int(b[1]) if 4 > ol || ol > len(b) { break } switch b[2] { case classMPLSLabelStack: ext, err := parseMPLSLabelStack(b[:ol]) if err != nil { return nil, -1, err } exts = append(exts, ext) case classInterfaceInfo: ext, err := parseInterfaceInfo(b[:ol]) if err != nil { return nil, -1, err } exts = append(exts, ext) } b = b[ol:] } return exts, l, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/extension_test.go ================================================ // 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 icmp import ( "net" "reflect" "testing" "golang.org/x/net/internal/iana" ) var marshalAndParseExtensionTests = []struct { proto int hdr []byte obj []byte exts []Extension }{ // MPLS label stack with no label { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x01, 0x01, }, exts: []Extension{ &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, }, }, }, // MPLS label stack with a single label { proto: iana.ProtocolIPv6ICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x08, 0x01, 0x01, 0x03, 0xe8, 0xe9, 0xff, }, exts: []Extension{ &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, }, }, // MPLS label stack with multiple labels { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x0c, 0x01, 0x01, 0x03, 0xe8, 0xde, 0xfe, 0x03, 0xe8, 0xe1, 0xff, }, exts: []Extension{ &MPLSLabelStack{ Class: classMPLSLabelStack, Type: typeIncomingMPLSLabelStack, Labels: []MPLSLabel{ { Label: 16013, TC: 0x7, S: false, TTL: 254, }, { Label: 16014, TC: 0, S: true, TTL: 255, }, }, }, }, }, // Interface information with no attribute { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x04, 0x02, 0x00, }, exts: []Extension{ &InterfaceInfo{ Class: classInterfaceInfo, }, }, }, // Interface information with ifIndex and name { proto: iana.ProtocolICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x10, 0x02, 0x0a, 0x00, 0x00, 0x00, 0x10, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, }, exts: []Extension{ &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0a, Interface: &net.Interface{ Index: 16, Name: "en101", }, }, }, }, // Interface information with ifIndex, IPAddr, name and MTU { proto: iana.ProtocolIPv6ICMP, hdr: []byte{ 0x20, 0x00, 0x00, 0x00, }, obj: []byte{ 0x00, 0x28, 0x02, 0x0f, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x02, 0x00, 0x00, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x08, byte('e'), byte('n'), byte('1'), byte('0'), byte('1'), 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, }, exts: []Extension{ &InterfaceInfo{ Class: classInterfaceInfo, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, }, }, } func TestMarshalAndParseExtension(t *testing.T) { for i, tt := range marshalAndParseExtensionTests { for j, ext := range tt.exts { var err error var b []byte switch ext := ext.(type) { case *MPLSLabelStack: b, err = ext.Marshal(tt.proto) if err != nil { t.Errorf("#%v/%v: %v", i, j, err) continue } case *InterfaceInfo: b, err = ext.Marshal(tt.proto) if err != nil { t.Errorf("#%v/%v: %v", i, j, err) continue } } if !reflect.DeepEqual(b, tt.obj) { t.Errorf("#%v/%v: got %#v; want %#v", i, j, b, tt.obj) continue } } for j, wire := range []struct { data []byte // original datagram inlattr int // length of padded original datagram, a hint outlattr int // length of padded original datagram, a want err error }{ {nil, 0, -1, errNoExtension}, {make([]byte, 127), 128, -1, errNoExtension}, {make([]byte, 128), 127, -1, errNoExtension}, {make([]byte, 128), 128, -1, errNoExtension}, {make([]byte, 128), 129, -1, errNoExtension}, {append(make([]byte, 128), append(tt.hdr, tt.obj...)...), 127, 128, nil}, {append(make([]byte, 128), append(tt.hdr, tt.obj...)...), 128, 128, nil}, {append(make([]byte, 128), append(tt.hdr, tt.obj...)...), 129, 128, nil}, {append(make([]byte, 512), append(tt.hdr, tt.obj...)...), 511, -1, errNoExtension}, {append(make([]byte, 512), append(tt.hdr, tt.obj...)...), 512, 512, nil}, {append(make([]byte, 512), append(tt.hdr, tt.obj...)...), 513, -1, errNoExtension}, } { exts, l, err := parseExtensions(wire.data, wire.inlattr) if err != wire.err { t.Errorf("#%v/%v: got %v; want %v", i, j, err, wire.err) continue } if wire.err != nil { continue } if l != wire.outlattr { t.Errorf("#%v/%v: got %v; want %v", i, j, l, wire.outlattr) } if !reflect.DeepEqual(exts, tt.exts) { for j, ext := range exts { switch ext := ext.(type) { case *MPLSLabelStack: want := tt.exts[j].(*MPLSLabelStack) t.Errorf("#%v/%v: got %#v; want %#v", i, j, ext, want) case *InterfaceInfo: want := tt.exts[j].(*InterfaceInfo) t.Errorf("#%v/%v: got %#v; want %#v", i, j, ext, want) } } continue } } } } var parseInterfaceNameTests = []struct { b []byte error }{ {[]byte{0, 'e', 'n', '0'}, errInvalidExtension}, {[]byte{4, 'e', 'n', '0'}, nil}, {[]byte{7, 'e', 'n', '0', 0xff, 0xff, 0xff, 0xff}, errInvalidExtension}, {[]byte{8, 'e', 'n', '0', 0xff, 0xff, 0xff}, errMessageTooShort}, } func TestParseInterfaceName(t *testing.T) { ifi := InterfaceInfo{Interface: &net.Interface{}} for i, tt := range parseInterfaceNameTests { if _, err := ifi.parseName(tt.b); err != tt.error { t.Errorf("#%d: got %v; want %v", i, err, tt.error) } } } ================================================ FILE: vendor/golang.org/x/net/icmp/helper_posix.go ================================================ // 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 solaris windows package icmp import ( "net" "strconv" "syscall" ) func sockaddr(family int, address string) (syscall.Sockaddr, error) { switch family { case syscall.AF_INET: a, err := net.ResolveIPAddr("ip4", address) if err != nil { return nil, err } if len(a.IP) == 0 { a.IP = net.IPv4zero } if a.IP = a.IP.To4(); a.IP == nil { return nil, net.InvalidAddrError("non-ipv4 address") } sa := &syscall.SockaddrInet4{} copy(sa.Addr[:], a.IP) return sa, nil case syscall.AF_INET6: a, err := net.ResolveIPAddr("ip6", address) if err != nil { return nil, err } if len(a.IP) == 0 { a.IP = net.IPv6unspecified } if a.IP.Equal(net.IPv4zero) { a.IP = net.IPv6unspecified } if a.IP = a.IP.To16(); a.IP == nil || a.IP.To4() != nil { return nil, net.InvalidAddrError("non-ipv6 address") } sa := &syscall.SockaddrInet6{ZoneId: zoneToUint32(a.Zone)} copy(sa.Addr[:], a.IP) return sa, nil default: return nil, net.InvalidAddrError("unexpected family") } } func zoneToUint32(zone string) uint32 { if zone == "" { return 0 } if ifi, err := net.InterfaceByName(zone); err == nil { return uint32(ifi.Index) } n, err := strconv.Atoi(zone) if err != nil { return 0 } return uint32(n) } func last(s string, b byte) int { i := len(s) for i--; i >= 0; i-- { if s[i] == b { break } } return i } ================================================ FILE: vendor/golang.org/x/net/icmp/interface.go ================================================ // 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 icmp import ( "net" "strings" "golang.org/x/net/internal/iana" ) const ( classInterfaceInfo = 2 afiIPv4 = 1 afiIPv6 = 2 ) const ( attrMTU = 1 << iota attrName attrIPAddr attrIfIndex ) // An InterfaceInfo represents interface and next-hop identification. type InterfaceInfo struct { Class int // extension object class number Type int // extension object sub-type Interface *net.Interface Addr *net.IPAddr } func (ifi *InterfaceInfo) nameLen() int { if len(ifi.Interface.Name) > 63 { return 64 } l := 1 + len(ifi.Interface.Name) return (l + 3) &^ 3 } func (ifi *InterfaceInfo) attrsAndLen(proto int) (attrs, l int) { l = 4 if ifi.Interface != nil && ifi.Interface.Index > 0 { attrs |= attrIfIndex l += 4 if len(ifi.Interface.Name) > 0 { attrs |= attrName l += ifi.nameLen() } if ifi.Interface.MTU > 0 { attrs |= attrMTU l += 4 } } if ifi.Addr != nil { switch proto { case iana.ProtocolICMP: if ifi.Addr.IP.To4() != nil { attrs |= attrIPAddr l += 4 + net.IPv4len } case iana.ProtocolIPv6ICMP: if ifi.Addr.IP.To16() != nil && ifi.Addr.IP.To4() == nil { attrs |= attrIPAddr l += 4 + net.IPv6len } } } return } // Len implements the Len method of Extension interface. func (ifi *InterfaceInfo) Len(proto int) int { _, l := ifi.attrsAndLen(proto) return l } // Marshal implements the Marshal method of Extension interface. func (ifi *InterfaceInfo) Marshal(proto int) ([]byte, error) { attrs, l := ifi.attrsAndLen(proto) b := make([]byte, l) if err := ifi.marshal(proto, b, attrs, l); err != nil { return nil, err } return b, nil } func (ifi *InterfaceInfo) marshal(proto int, b []byte, attrs, l int) error { b[0], b[1] = byte(l>>8), byte(l) b[2], b[3] = classInterfaceInfo, byte(ifi.Type) for b = b[4:]; len(b) > 0 && attrs != 0; { switch { case attrs&attrIfIndex != 0: b = ifi.marshalIfIndex(proto, b) attrs &^= attrIfIndex case attrs&attrIPAddr != 0: b = ifi.marshalIPAddr(proto, b) attrs &^= attrIPAddr case attrs&attrName != 0: b = ifi.marshalName(proto, b) attrs &^= attrName case attrs&attrMTU != 0: b = ifi.marshalMTU(proto, b) attrs &^= attrMTU } } return nil } func (ifi *InterfaceInfo) marshalIfIndex(proto int, b []byte) []byte { b[0], b[1], b[2], b[3] = byte(ifi.Interface.Index>>24), byte(ifi.Interface.Index>>16), byte(ifi.Interface.Index>>8), byte(ifi.Interface.Index) return b[4:] } func (ifi *InterfaceInfo) parseIfIndex(b []byte) ([]byte, error) { if len(b) < 4 { return nil, errMessageTooShort } ifi.Interface.Index = int(b[0])<<24 | int(b[1])<<16 | int(b[2])<<8 | int(b[3]) return b[4:], nil } func (ifi *InterfaceInfo) marshalIPAddr(proto int, b []byte) []byte { switch proto { case iana.ProtocolICMP: b[0], b[1] = byte(afiIPv4>>8), byte(afiIPv4) copy(b[4:4+net.IPv4len], ifi.Addr.IP.To4()) b = b[4+net.IPv4len:] case iana.ProtocolIPv6ICMP: b[0], b[1] = byte(afiIPv6>>8), byte(afiIPv6) copy(b[4:4+net.IPv6len], ifi.Addr.IP.To16()) b = b[4+net.IPv6len:] } return b } func (ifi *InterfaceInfo) parseIPAddr(b []byte) ([]byte, error) { if len(b) < 4 { return nil, errMessageTooShort } afi := int(b[0])<<8 | int(b[1]) b = b[4:] switch afi { case afiIPv4: if len(b) < net.IPv4len { return nil, errMessageTooShort } ifi.Addr.IP = make(net.IP, net.IPv4len) copy(ifi.Addr.IP, b[:net.IPv4len]) b = b[net.IPv4len:] case afiIPv6: if len(b) < net.IPv6len { return nil, errMessageTooShort } ifi.Addr.IP = make(net.IP, net.IPv6len) copy(ifi.Addr.IP, b[:net.IPv6len]) b = b[net.IPv6len:] } return b, nil } func (ifi *InterfaceInfo) marshalName(proto int, b []byte) []byte { l := byte(ifi.nameLen()) b[0] = l copy(b[1:], []byte(ifi.Interface.Name)) return b[l:] } func (ifi *InterfaceInfo) parseName(b []byte) ([]byte, error) { if 4 > len(b) || len(b) < int(b[0]) { return nil, errMessageTooShort } l := int(b[0]) if l%4 != 0 || 4 > l || l > 64 { return nil, errInvalidExtension } var name [63]byte copy(name[:], b[1:l]) ifi.Interface.Name = strings.Trim(string(name[:]), "\000") return b[l:], nil } func (ifi *InterfaceInfo) marshalMTU(proto int, b []byte) []byte { b[0], b[1], b[2], b[3] = byte(ifi.Interface.MTU>>24), byte(ifi.Interface.MTU>>16), byte(ifi.Interface.MTU>>8), byte(ifi.Interface.MTU) return b[4:] } func (ifi *InterfaceInfo) parseMTU(b []byte) ([]byte, error) { if len(b) < 4 { return nil, errMessageTooShort } ifi.Interface.MTU = int(b[0])<<24 | int(b[1])<<16 | int(b[2])<<8 | int(b[3]) return b[4:], nil } func parseInterfaceInfo(b []byte) (Extension, error) { ifi := &InterfaceInfo{ Class: int(b[2]), Type: int(b[3]), } if ifi.Type&(attrIfIndex|attrName|attrMTU) != 0 { ifi.Interface = &net.Interface{} } if ifi.Type&attrIPAddr != 0 { ifi.Addr = &net.IPAddr{} } attrs := ifi.Type & (attrIfIndex | attrIPAddr | attrName | attrMTU) for b = b[4:]; len(b) > 0 && attrs != 0; { var err error switch { case attrs&attrIfIndex != 0: b, err = ifi.parseIfIndex(b) attrs &^= attrIfIndex case attrs&attrIPAddr != 0: b, err = ifi.parseIPAddr(b) attrs &^= attrIPAddr case attrs&attrName != 0: b, err = ifi.parseName(b) attrs &^= attrName case attrs&attrMTU != 0: b, err = ifi.parseMTU(b) attrs &^= attrMTU } if err != nil { return nil, err } } if ifi.Interface != nil && ifi.Interface.Name != "" && ifi.Addr != nil && ifi.Addr.IP.To16() != nil && ifi.Addr.IP.To4() == nil { ifi.Addr.Zone = ifi.Interface.Name } return ifi, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/ipv4.go ================================================ // 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 icmp import ( "net" "runtime" "unsafe" "golang.org/x/net/ipv4" ) // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html. var freebsdVersion uint32 // ParseIPv4Header parses b as an IPv4 header of ICMP error message // invoking packet, which is contained in ICMP error message. func ParseIPv4Header(b []byte) (*ipv4.Header, error) { if len(b) < ipv4.HeaderLen { return nil, errHeaderTooShort } hdrlen := int(b[0]&0x0f) << 2 if hdrlen > len(b) { return nil, errBufferTooShort } h := &ipv4.Header{ Version: int(b[0] >> 4), Len: hdrlen, TOS: int(b[1]), ID: int(b[4])<<8 | int(b[5]), FragOff: int(b[6])<<8 | int(b[7]), TTL: int(b[8]), Protocol: int(b[9]), Checksum: int(b[10])<<8 | int(b[11]), Src: net.IPv4(b[12], b[13], b[14], b[15]), Dst: net.IPv4(b[16], b[17], b[18], b[19]), } switch runtime.GOOS { case "darwin": // TODO(mikio): fix potential misaligned memory access h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[2:3][0]))) case "freebsd": if freebsdVersion >= 1000000 { h.TotalLen = int(b[2])<<8 | int(b[3]) } else { // TODO(mikio): fix potential misaligned memory access h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[2:3][0]))) } default: h.TotalLen = int(b[2])<<8 | int(b[3]) } h.Flags = ipv4.HeaderFlags(h.FragOff&0xe000) >> 13 h.FragOff = h.FragOff & 0x1fff if hdrlen-ipv4.HeaderLen > 0 { h.Options = make([]byte, hdrlen-ipv4.HeaderLen) copy(h.Options, b[ipv4.HeaderLen:]) } return h, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/ipv4_test.go ================================================ // 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 icmp import ( "net" "reflect" "runtime" "testing" "golang.org/x/net/ipv4" ) var ( wireHeaderFromKernel = [ipv4.HeaderLen]byte{ 0x45, 0x01, 0xbe, 0xef, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } wireHeaderFromTradBSDKernel = [ipv4.HeaderLen]byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } // TODO(mikio): Add platform dependent wire header formats when // we support new platforms. testHeader = &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: 1, TotalLen: 0xbeef, ID: 0xcafe, Flags: ipv4.DontFragment, FragOff: 1500, TTL: 255, Protocol: 1, Checksum: 0xdead, Src: net.IPv4(172, 16, 254, 254), Dst: net.IPv4(192, 168, 0, 1), } ) func TestParseIPv4Header(t *testing.T) { var wh []byte switch runtime.GOOS { case "darwin": wh = wireHeaderFromTradBSDKernel[:] case "freebsd": if freebsdVersion >= 1000000 { wh = wireHeaderFromKernel[:] } else { wh = wireHeaderFromTradBSDKernel[:] } default: wh = wireHeaderFromKernel[:] } h, err := ParseIPv4Header(wh) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(h, testHeader) { t.Fatalf("got %#v; want %#v", h, testHeader) } } ================================================ FILE: vendor/golang.org/x/net/icmp/ipv6.go ================================================ // 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 icmp import ( "net" "golang.org/x/net/internal/iana" ) const ipv6PseudoHeaderLen = 2*net.IPv6len + 8 // IPv6PseudoHeader returns an IPv6 pseudo header for checkusm // calculation. func IPv6PseudoHeader(src, dst net.IP) []byte { b := make([]byte, ipv6PseudoHeaderLen) copy(b, src.To16()) copy(b[net.IPv6len:], dst.To16()) b[len(b)-1] = byte(iana.ProtocolIPv6ICMP) return b } ================================================ FILE: vendor/golang.org/x/net/icmp/listen_posix.go ================================================ // 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 solaris windows package icmp import ( "net" "os" "runtime" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) const sysIP_STRIPHDR = 0x17 // for now only darwin supports this option // ListenPacket listens for incoming ICMP packets addressed to // address. See net.Dial for the syntax of address. // // For non-privileged datagram-oriented ICMP endpoints, network must // be "udp4" or "udp6". The endpoint allows to read, write a few // limited ICMP messages such as echo request and echo reply. // Currently only Darwin and Linux support this. // // Examples: // ListenPacket("udp4", "192.168.0.1") // ListenPacket("udp4", "0.0.0.0") // ListenPacket("udp6", "fe80::1%en0") // ListenPacket("udp6", "::") // // For privileged raw ICMP endpoints, network must be "ip4" or "ip6" // followed by a colon and an ICMP protocol number or name. // // Examples: // ListenPacket("ip4:icmp", "192.168.0.1") // ListenPacket("ip4:1", "0.0.0.0") // ListenPacket("ip6:ipv6-icmp", "fe80::1%en0") // ListenPacket("ip6:58", "::") func ListenPacket(network, address string) (*PacketConn, error) { var family, proto int switch network { case "udp4": family, proto = syscall.AF_INET, iana.ProtocolICMP case "udp6": family, proto = syscall.AF_INET6, iana.ProtocolIPv6ICMP default: i := last(network, ':') switch network[:i] { case "ip4": proto = iana.ProtocolICMP case "ip6": proto = iana.ProtocolIPv6ICMP } } var cerr error var c net.PacketConn switch family { case syscall.AF_INET, syscall.AF_INET6: s, err := syscall.Socket(family, syscall.SOCK_DGRAM, proto) if err != nil { return nil, os.NewSyscallError("socket", err) } defer syscall.Close(s) if runtime.GOOS == "darwin" && family == syscall.AF_INET { if err := syscall.SetsockoptInt(s, iana.ProtocolIP, sysIP_STRIPHDR, 1); err != nil { return nil, os.NewSyscallError("setsockopt", err) } } sa, err := sockaddr(family, address) if err != nil { return nil, err } if err := syscall.Bind(s, sa); err != nil { return nil, os.NewSyscallError("bind", err) } f := os.NewFile(uintptr(s), "datagram-oriented icmp") defer f.Close() c, cerr = net.FilePacketConn(f) default: c, cerr = net.ListenPacket(network, address) } if cerr != nil { return nil, cerr } switch proto { case iana.ProtocolICMP: return &PacketConn{c: c, ipc: ipv4.NewPacketConn(c)}, nil case iana.ProtocolIPv6ICMP: return &PacketConn{c: c, ipc: ipv6.NewPacketConn(c)}, nil default: return &PacketConn{c: c}, nil } } ================================================ FILE: vendor/golang.org/x/net/icmp/listen_stub.go ================================================ // 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 nacl plan9 package icmp // ListenPacket listens for incoming ICMP packets addressed to // address. See net.Dial for the syntax of address. // // For non-privileged datagram-oriented ICMP endpoints, network must // be "udp4" or "udp6". The endpoint allows to read, write a few // limited ICMP messages such as echo request and echo reply. // Currently only Darwin and Linux support this. // // Examples: // ListenPacket("udp4", "192.168.0.1") // ListenPacket("udp4", "0.0.0.0") // ListenPacket("udp6", "fe80::1%en0") // ListenPacket("udp6", "::") // // For privileged raw ICMP endpoints, network must be "ip4" or "ip6" // followed by a colon and an ICMP protocol number or name. // // Examples: // ListenPacket("ip4:icmp", "192.168.0.1") // ListenPacket("ip4:1", "0.0.0.0") // ListenPacket("ip6:ipv6-icmp", "fe80::1%en0") // ListenPacket("ip6:58", "::") func ListenPacket(network, address string) (*PacketConn, error) { return nil, errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/icmp/message.go ================================================ // 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 icmp provides basic functions for the manipulation of // messages used in the Internet Control Message Protocols, // ICMPv4 and ICMPv6. // // ICMPv4 and ICMPv6 are defined in RFC 792 and RFC 4443. // Multi-part message support for ICMP is defined in RFC 4884. // ICMP extensions for MPLS are defined in RFC 4950. // ICMP extensions for interface and next-hop identification are // defined in RFC 5837. package icmp // import "golang.org/x/net/icmp" import ( "errors" "net" "syscall" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var ( errMessageTooShort = errors.New("message too short") errHeaderTooShort = errors.New("header too short") errBufferTooShort = errors.New("buffer too short") errOpNoSupport = errors.New("operation not supported") errNoExtension = errors.New("no extension") errInvalidExtension = errors.New("invalid extension") ) func checksum(b []byte) uint16 { csumcv := len(b) - 1 // checksum coverage s := uint32(0) for i := 0; i < csumcv; i += 2 { s += uint32(b[i+1])<<8 | uint32(b[i]) } if csumcv&1 == 0 { s += uint32(b[csumcv]) } s = s>>16 + s&0xffff s = s + s>>16 return ^uint16(s) } // A Type represents an ICMP message type. type Type interface { Protocol() int } // A Message represents an ICMP message. type Message struct { Type Type // type, either ipv4.ICMPType or ipv6.ICMPType Code int // code Checksum int // checksum Body MessageBody // body } // Marshal returns the binary enconding of the ICMP message m. // // For an ICMPv4 message, the returned message always contains the // calculated checksum field. // // For an ICMPv6 message, the returned message contains the calculated // checksum field when psh is not nil, otherwise the kernel will // compute the checksum field during the message transmission. // When psh is not nil, it must be the pseudo header for IPv6. func (m *Message) Marshal(psh []byte) ([]byte, error) { var mtype int switch typ := m.Type.(type) { case ipv4.ICMPType: mtype = int(typ) case ipv6.ICMPType: mtype = int(typ) default: return nil, syscall.EINVAL } b := []byte{byte(mtype), byte(m.Code), 0, 0} if m.Type.Protocol() == iana.ProtocolIPv6ICMP && psh != nil { b = append(psh, b...) } if m.Body != nil && m.Body.Len(m.Type.Protocol()) != 0 { mb, err := m.Body.Marshal(m.Type.Protocol()) if err != nil { return nil, err } b = append(b, mb...) } if m.Type.Protocol() == iana.ProtocolIPv6ICMP { if psh == nil { // cannot calculate checksum here return b, nil } off, l := 2*net.IPv6len, len(b)-len(psh) b[off], b[off+1], b[off+2], b[off+3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l) } s := checksum(b) // Place checksum back in header; using ^= avoids the // assumption the checksum bytes are zero. b[len(psh)+2] ^= byte(s) b[len(psh)+3] ^= byte(s >> 8) return b[len(psh):], nil } var parseFns = map[Type]func(int, []byte) (MessageBody, error){ ipv4.ICMPTypeDestinationUnreachable: parseDstUnreach, ipv4.ICMPTypeTimeExceeded: parseTimeExceeded, ipv4.ICMPTypeParameterProblem: parseParamProb, ipv4.ICMPTypeEcho: parseEcho, ipv4.ICMPTypeEchoReply: parseEcho, ipv6.ICMPTypeDestinationUnreachable: parseDstUnreach, ipv6.ICMPTypePacketTooBig: parsePacketTooBig, ipv6.ICMPTypeTimeExceeded: parseTimeExceeded, ipv6.ICMPTypeParameterProblem: parseParamProb, ipv6.ICMPTypeEchoRequest: parseEcho, ipv6.ICMPTypeEchoReply: parseEcho, } // ParseMessage parses b as an ICMP message. // Proto must be either the ICMPv4 or ICMPv6 protocol number. func ParseMessage(proto int, b []byte) (*Message, error) { if len(b) < 4 { return nil, errMessageTooShort } var err error m := &Message{Code: int(b[1]), Checksum: int(b[2])<<8 | int(b[3])} switch proto { case iana.ProtocolICMP: m.Type = ipv4.ICMPType(b[0]) case iana.ProtocolIPv6ICMP: m.Type = ipv6.ICMPType(b[0]) default: return nil, syscall.EINVAL } if fn, ok := parseFns[m.Type]; !ok { m.Body, err = parseDefaultMessageBody(proto, b[4:]) } else { m.Body, err = fn(proto, b[4:]) } if err != nil { return nil, err } return m, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/message_test.go ================================================ // 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 icmp_test import ( "net" "reflect" "testing" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var marshalAndParseMessageForIPv4Tests = []icmp.Message{ { Type: ipv4.ICMPTypeDestinationUnreachable, Code: 15, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv4.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv4.ICMPTypeParameterProblem, Code: 2, Body: &icmp.ParamProb{ Pointer: 8, Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: 1, Seq: 2, Data: []byte("HELLO-R-U-THERE"), }, }, { Type: ipv4.ICMPTypePhoturis, Body: &icmp.DefaultMessageBody{ Data: []byte{0x80, 0x40, 0x20, 0x10}, }, }, } func TestMarshalAndParseMessageForIPv4(t *testing.T) { for i, tt := range marshalAndParseMessageForIPv4Tests { b, err := tt.Marshal(nil) if err != nil { t.Fatal(err) } m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } if !reflect.DeepEqual(m.Body, tt.Body) { t.Errorf("#%v: got %v; want %v", i, m.Body, tt.Body) } } } var marshalAndParseMessageForIPv6Tests = []icmp.Message{ { Type: ipv6.ICMPTypeDestinationUnreachable, Code: 6, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypePacketTooBig, Code: 0, Body: &icmp.PacketTooBig{ MTU: 1<<16 - 1, Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypeParameterProblem, Code: 2, Body: &icmp.ParamProb{ Pointer: 8, Data: []byte("ERROR-INVOKING-PACKET"), }, }, { Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: 1, Seq: 2, Data: []byte("HELLO-R-U-THERE"), }, }, { Type: ipv6.ICMPTypeDuplicateAddressConfirmation, Body: &icmp.DefaultMessageBody{ Data: []byte{0x80, 0x40, 0x20, 0x10}, }, }, } func TestMarshalAndParseMessageForIPv6(t *testing.T) { pshicmp := icmp.IPv6PseudoHeader(net.ParseIP("fe80::1"), net.ParseIP("ff02::1")) for i, tt := range marshalAndParseMessageForIPv6Tests { for _, psh := range [][]byte{pshicmp, nil} { b, err := tt.Marshal(psh) if err != nil { t.Fatal(err) } m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } if !reflect.DeepEqual(m.Body, tt.Body) { t.Errorf("#%v: got %v; want %v", i, m.Body, tt.Body) } } } } ================================================ FILE: vendor/golang.org/x/net/icmp/messagebody.go ================================================ // 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 icmp // A MessageBody represents an ICMP message body. type MessageBody interface { // Len returns the length of ICMP message body. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Len(proto int) int // Marshal returns the binary enconding of ICMP message body. // Proto must be either the ICMPv4 or ICMPv6 protocol number. Marshal(proto int) ([]byte, error) } // A DefaultMessageBody represents the default message body. type DefaultMessageBody struct { Data []byte // data } // Len implements the Len method of MessageBody interface. func (p *DefaultMessageBody) Len(proto int) int { if p == nil { return 0 } return len(p.Data) } // Marshal implements the Marshal method of MessageBody interface. func (p *DefaultMessageBody) Marshal(proto int) ([]byte, error) { return p.Data, nil } // parseDefaultMessageBody parses b as an ICMP message body. func parseDefaultMessageBody(proto int, b []byte) (MessageBody, error) { p := &DefaultMessageBody{Data: make([]byte, len(b))} copy(p.Data, b) return p, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/mpls.go ================================================ // 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 icmp // A MPLSLabel represents a MPLS label stack entry. type MPLSLabel struct { Label int // label value TC int // traffic class; formerly experimental use S bool // bottom of stack TTL int // time to live } const ( classMPLSLabelStack = 1 typeIncomingMPLSLabelStack = 1 ) // A MPLSLabelStack represents a MPLS label stack. type MPLSLabelStack struct { Class int // extension object class number Type int // extension object sub-type Labels []MPLSLabel } // Len implements the Len method of Extension interface. func (ls *MPLSLabelStack) Len(proto int) int { return 4 + (4 * len(ls.Labels)) } // Marshal implements the Marshal method of Extension interface. func (ls *MPLSLabelStack) Marshal(proto int) ([]byte, error) { b := make([]byte, ls.Len(proto)) if err := ls.marshal(proto, b); err != nil { return nil, err } return b, nil } func (ls *MPLSLabelStack) marshal(proto int, b []byte) error { l := ls.Len(proto) b[0], b[1] = byte(l>>8), byte(l) b[2], b[3] = classMPLSLabelStack, typeIncomingMPLSLabelStack off := 4 for _, ll := range ls.Labels { b[off], b[off+1], b[off+2] = byte(ll.Label>>12), byte(ll.Label>>4&0xff), byte(ll.Label<<4&0xf0) b[off+2] |= byte(ll.TC << 1 & 0x0e) if ll.S { b[off+2] |= 0x1 } b[off+3] = byte(ll.TTL) off += 4 } return nil } func parseMPLSLabelStack(b []byte) (Extension, error) { ls := &MPLSLabelStack{ Class: int(b[2]), Type: int(b[3]), } for b = b[4:]; len(b) >= 4; b = b[4:] { ll := MPLSLabel{ Label: int(b[0])<<12 | int(b[1])<<4 | int(b[2])>>4, TC: int(b[2]&0x0e) >> 1, TTL: int(b[3]), } if b[2]&0x1 != 0 { ll.S = true } ls.Labels = append(ls.Labels, ll) } return ls, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/multipart.go ================================================ // 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 icmp import "golang.org/x/net/internal/iana" // multipartMessageBodyDataLen takes b as an original datagram and // exts as extensions, and returns a required length for message body // and a required length for a padded original datagram in wire // format. func multipartMessageBodyDataLen(proto int, b []byte, exts []Extension) (bodyLen, dataLen int) { for _, ext := range exts { bodyLen += ext.Len(proto) } if bodyLen > 0 { dataLen = multipartMessageOrigDatagramLen(proto, b) bodyLen += 4 // length of extension header } else { dataLen = len(b) } bodyLen += dataLen return bodyLen, dataLen } // multipartMessageOrigDatagramLen takes b as an original datagram, // and returns a required length for a padded orignal datagram in wire // format. func multipartMessageOrigDatagramLen(proto int, b []byte) int { roundup := func(b []byte, align int) int { // According to RFC 4884, the padded original datagram // field must contain at least 128 octets. if len(b) < 128 { return 128 } r := len(b) return (r + align) &^ (align - 1) } switch proto { case iana.ProtocolICMP: return roundup(b, 4) case iana.ProtocolIPv6ICMP: return roundup(b, 8) default: return len(b) } } // marshalMultipartMessageBody takes data as an original datagram and // exts as extesnsions, and returns a binary encoding of message body. // It can be used for non-multipart message bodies when exts is nil. func marshalMultipartMessageBody(proto int, data []byte, exts []Extension) ([]byte, error) { bodyLen, dataLen := multipartMessageBodyDataLen(proto, data, exts) b := make([]byte, 4+bodyLen) copy(b[4:], data) off := dataLen + 4 if len(exts) > 0 { b[dataLen+4] = byte(extensionVersion << 4) off += 4 // length of object header for _, ext := range exts { switch ext := ext.(type) { case *MPLSLabelStack: if err := ext.marshal(proto, b[off:]); err != nil { return nil, err } off += ext.Len(proto) case *InterfaceInfo: attrs, l := ext.attrsAndLen(proto) if err := ext.marshal(proto, b[off:], attrs, l); err != nil { return nil, err } off += ext.Len(proto) } } s := checksum(b[dataLen+4:]) b[dataLen+4+2] ^= byte(s) b[dataLen+4+3] ^= byte(s >> 8) switch proto { case iana.ProtocolICMP: b[1] = byte(dataLen / 4) case iana.ProtocolIPv6ICMP: b[0] = byte(dataLen / 8) } } return b, nil } // parseMultipartMessageBody parses b as either a non-multipart // message body or a multipart message body. func parseMultipartMessageBody(proto int, b []byte) ([]byte, []Extension, error) { var l int switch proto { case iana.ProtocolICMP: l = 4 * int(b[1]) case iana.ProtocolIPv6ICMP: l = 8 * int(b[0]) } if len(b) == 4 { return nil, nil, nil } exts, l, err := parseExtensions(b[4:], l) if err != nil { l = len(b) - 4 } data := make([]byte, l) copy(data, b[4:]) return data, exts, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/multipart_test.go ================================================ // 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 icmp_test import ( "fmt" "net" "reflect" "testing" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) var marshalAndParseMultipartMessageForIPv4Tests = []icmp.Message{ { Type: ipv4.ICMPTypeDestinationUnreachable, Code: 15, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 1).To4(), }, }, }, }, }, { Type: ipv4.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 1).To4(), }, }, &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, }, }, }, { Type: ipv4.ICMPTypeParameterProblem, Code: 2, Body: &icmp.ParamProb{ Pointer: 8, Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 1).To4(), }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x2f, Interface: &net.Interface{ Index: 16, Name: "en102", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.IPv4(192, 168, 0, 2).To4(), }, }, }, }, }, } func TestMarshalAndParseMultipartMessageForIPv4(t *testing.T) { for i, tt := range marshalAndParseMultipartMessageForIPv4Tests { b, err := tt.Marshal(nil) if err != nil { t.Fatal(err) } if b[5] != 32 { t.Errorf("#%v: got %v; want 32", i, b[5]) } m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } switch m.Type { case ipv4.ICMPTypeDestinationUnreachable: got, want := m.Body.(*icmp.DstUnreach), tt.Body.(*icmp.DstUnreach) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } case ipv4.ICMPTypeTimeExceeded: got, want := m.Body.(*icmp.TimeExceeded), tt.Body.(*icmp.TimeExceeded) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } case ipv4.ICMPTypeParameterProblem: got, want := m.Body.(*icmp.ParamProb), tt.Body.(*icmp.ParamProb) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } } } } var marshalAndParseMultipartMessageForIPv6Tests = []icmp.Message{ { Type: ipv6.ICMPTypeDestinationUnreachable, Code: 6, Body: &icmp.DstUnreach{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, }, }, }, { Type: ipv6.ICMPTypeTimeExceeded, Code: 1, Body: &icmp.TimeExceeded{ Data: []byte("ERROR-INVOKING-PACKET"), Extensions: []icmp.Extension{ &icmp.InterfaceInfo{ Class: 2, Type: 0x0f, Interface: &net.Interface{ Index: 15, Name: "en101", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en101", }, }, &icmp.MPLSLabelStack{ Class: 1, Type: 1, Labels: []icmp.MPLSLabel{ { Label: 16014, TC: 0x4, S: true, TTL: 255, }, }, }, &icmp.InterfaceInfo{ Class: 2, Type: 0x2f, Interface: &net.Interface{ Index: 16, Name: "en102", MTU: 8192, }, Addr: &net.IPAddr{ IP: net.ParseIP("fe80::1"), Zone: "en102", }, }, }, }, }, } func TestMarshalAndParseMultipartMessageForIPv6(t *testing.T) { pshicmp := icmp.IPv6PseudoHeader(net.ParseIP("fe80::1"), net.ParseIP("ff02::1")) for i, tt := range marshalAndParseMultipartMessageForIPv6Tests { for _, psh := range [][]byte{pshicmp, nil} { b, err := tt.Marshal(psh) if err != nil { t.Fatal(err) } if b[4] != 16 { t.Errorf("#%v: got %v; want 16", i, b[4]) } m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, b) if err != nil { t.Fatal(err) } if m.Type != tt.Type || m.Code != tt.Code { t.Errorf("#%v: got %v; want %v", i, m, &tt) } switch m.Type { case ipv6.ICMPTypeDestinationUnreachable: got, want := m.Body.(*icmp.DstUnreach), tt.Body.(*icmp.DstUnreach) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } case ipv6.ICMPTypeTimeExceeded: got, want := m.Body.(*icmp.TimeExceeded), tt.Body.(*icmp.TimeExceeded) if !reflect.DeepEqual(got.Extensions, want.Extensions) { t.Error(dumpExtensions(i, got.Extensions, want.Extensions)) } if len(got.Data) != 128 { t.Errorf("#%v: got %v; want 128", i, len(got.Data)) } } } } } func dumpExtensions(i int, gotExts, wantExts []icmp.Extension) string { var s string for j, got := range gotExts { switch got := got.(type) { case *icmp.MPLSLabelStack: want := wantExts[j].(*icmp.MPLSLabelStack) if !reflect.DeepEqual(got, want) { s += fmt.Sprintf("#%v/%v: got %#v; want %#v\n", i, j, got, want) } case *icmp.InterfaceInfo: want := wantExts[j].(*icmp.InterfaceInfo) if !reflect.DeepEqual(got, want) { s += fmt.Sprintf("#%v/%v: got %#v, %#v, %#v; want %#v, %#v, %#v\n", i, j, got, got.Interface, got.Addr, want, want.Interface, want.Addr) } } } return s[:len(s)-1] } ================================================ FILE: vendor/golang.org/x/net/icmp/packettoobig.go ================================================ // 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 icmp // A PacketTooBig represents an ICMP packet too big message body. type PacketTooBig struct { MTU int // maximum transmission unit of the nexthop link Data []byte // data, known as original datagram field } // Len implements the Len method of MessageBody interface. func (p *PacketTooBig) Len(proto int) int { if p == nil { return 0 } return 4 + len(p.Data) } // Marshal implements the Marshal method of MessageBody interface. func (p *PacketTooBig) Marshal(proto int) ([]byte, error) { b := make([]byte, 4+len(p.Data)) b[0], b[1], b[2], b[3] = byte(p.MTU>>24), byte(p.MTU>>16), byte(p.MTU>>8), byte(p.MTU) copy(b[4:], p.Data) return b, nil } // parsePacketTooBig parses b as an ICMP packet too big message body. func parsePacketTooBig(proto int, b []byte) (MessageBody, error) { bodyLen := len(b) if bodyLen < 4 { return nil, errMessageTooShort } p := &PacketTooBig{MTU: int(b[0])<<24 | int(b[1])<<16 | int(b[2])<<8 | int(b[3])} if bodyLen > 4 { p.Data = make([]byte, bodyLen-4) copy(p.Data, b[4:]) } return p, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/paramprob.go ================================================ // 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 icmp import "golang.org/x/net/internal/iana" // A ParamProb represents an ICMP parameter problem message body. type ParamProb struct { Pointer uintptr // offset within the data where the error was detected Data []byte // data, known as original datagram field Extensions []Extension // extensions } // Len implements the Len method of MessageBody interface. func (p *ParamProb) Len(proto int) int { if p == nil { return 0 } l, _ := multipartMessageBodyDataLen(proto, p.Data, p.Extensions) return l } // Marshal implements the Marshal method of MessageBody interface. func (p *ParamProb) Marshal(proto int) ([]byte, error) { if proto == iana.ProtocolIPv6ICMP { b := make([]byte, 4+p.Len(proto)) b[0], b[1], b[2], b[3] = byte(p.Pointer>>24), byte(p.Pointer>>16), byte(p.Pointer>>8), byte(p.Pointer) copy(b[4:], p.Data) return b, nil } b, err := marshalMultipartMessageBody(proto, p.Data, p.Extensions) if err != nil { return nil, err } b[0] = byte(p.Pointer) return b, nil } // parseParamProb parses b as an ICMP parameter problem message body. func parseParamProb(proto int, b []byte) (MessageBody, error) { if len(b) < 4 { return nil, errMessageTooShort } p := &ParamProb{} if proto == iana.ProtocolIPv6ICMP { p.Pointer = uintptr(b[0])<<24 | uintptr(b[1])<<16 | uintptr(b[2])<<8 | uintptr(b[3]) p.Data = make([]byte, len(b)-4) copy(p.Data, b[4:]) return p, nil } p.Pointer = uintptr(b[0]) var err error p.Data, p.Extensions, err = parseMultipartMessageBody(proto, b) if err != nil { return nil, err } return p, nil } ================================================ FILE: vendor/golang.org/x/net/icmp/ping_test.go ================================================ // 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 icmp_test import ( "errors" "fmt" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" "golang.org/x/net/ipv6" ) func googleAddr(c *icmp.PacketConn, protocol int) (net.Addr, error) { const host = "www.google.com" ips, err := net.LookupIP(host) if err != nil { return nil, err } netaddr := func(ip net.IP) (net.Addr, error) { switch c.LocalAddr().(type) { case *net.UDPAddr: return &net.UDPAddr{IP: ip}, nil case *net.IPAddr: return &net.IPAddr{IP: ip}, nil default: return nil, errors.New("neither UDPAddr nor IPAddr") } } for _, ip := range ips { switch protocol { case iana.ProtocolICMP: if ip.To4() != nil { return netaddr(ip) } case iana.ProtocolIPv6ICMP: if ip.To16() != nil && ip.To4() == nil { return netaddr(ip) } } } return nil, errors.New("no A or AAAA record") } type pingTest struct { network, address string protocol int mtype icmp.Type } var nonPrivilegedPingTests = []pingTest{ {"udp4", "0.0.0.0", iana.ProtocolICMP, ipv4.ICMPTypeEcho}, {"udp6", "::", iana.ProtocolIPv6ICMP, ipv6.ICMPTypeEchoRequest}, } func TestNonPrivilegedPing(t *testing.T) { if testing.Short() { t.Skip("avoid external network") } switch runtime.GOOS { case "darwin": case "linux": t.Log("you may need to adjust the net.ipv4.ping_group_range kernel state") default: t.Skipf("not supported on %s", runtime.GOOS) } for i, tt := range nonPrivilegedPingTests { if err := doPing(tt, i); err != nil { t.Error(err) } } } var privilegedPingTests = []pingTest{ {"ip4:icmp", "0.0.0.0", iana.ProtocolICMP, ipv4.ICMPTypeEcho}, {"ip6:ipv6-icmp", "::", iana.ProtocolIPv6ICMP, ipv6.ICMPTypeEchoRequest}, } func TestPrivilegedPing(t *testing.T) { if testing.Short() { t.Skip("avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } for i, tt := range privilegedPingTests { if err := doPing(tt, i); err != nil { t.Error(err) } } } func doPing(tt pingTest, seq int) error { c, err := icmp.ListenPacket(tt.network, tt.address) if err != nil { return err } defer c.Close() dst, err := googleAddr(c, tt.protocol) if err != nil { return err } if tt.network != "udp6" && tt.protocol == iana.ProtocolIPv6ICMP { var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeDestinationUnreachable) f.Accept(ipv6.ICMPTypePacketTooBig) f.Accept(ipv6.ICMPTypeTimeExceeded) f.Accept(ipv6.ICMPTypeParameterProblem) f.Accept(ipv6.ICMPTypeEchoReply) if err := c.IPv6PacketConn().SetICMPFilter(&f); err != nil { return err } } wm := icmp.Message{ Type: tt.mtype, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: 1 << uint(seq), Data: []byte("HELLO-R-U-THERE"), }, } wb, err := wm.Marshal(nil) if err != nil { return err } if n, err := c.WriteTo(wb, dst); err != nil { return err } else if n != len(wb) { return fmt.Errorf("got %v; want %v", n, len(wb)) } rb := make([]byte, 1500) if err := c.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { return err } n, peer, err := c.ReadFrom(rb) if err != nil { return err } rm, err := icmp.ParseMessage(tt.protocol, rb[:n]) if err != nil { return err } switch rm.Type { case ipv4.ICMPTypeEchoReply, ipv6.ICMPTypeEchoReply: return nil default: return fmt.Errorf("got %+v from %v; want echo reply", rm, peer) } } ================================================ FILE: vendor/golang.org/x/net/icmp/sys_freebsd.go ================================================ // 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 icmp import "syscall" func init() { freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate") } ================================================ FILE: vendor/golang.org/x/net/icmp/timeexceeded.go ================================================ // 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 icmp // A TimeExceeded represents an ICMP time exceeded message body. type TimeExceeded struct { Data []byte // data, known as original datagram field Extensions []Extension // extensions } // Len implements the Len method of MessageBody interface. func (p *TimeExceeded) Len(proto int) int { if p == nil { return 0 } l, _ := multipartMessageBodyDataLen(proto, p.Data, p.Extensions) return l } // Marshal implements the Marshal method of MessageBody interface. func (p *TimeExceeded) Marshal(proto int) ([]byte, error) { return marshalMultipartMessageBody(proto, p.Data, p.Extensions) } // parseTimeExceeded parses b as an ICMP time exceeded message body. func parseTimeExceeded(proto int, b []byte) (MessageBody, error) { if len(b) < 4 { return nil, errMessageTooShort } p := &TimeExceeded{} var err error p.Data, p.Extensions, err = parseMultipartMessageBody(proto, b) if err != nil { return nil, err } return p, nil } ================================================ FILE: vendor/golang.org/x/net/idna/idna.go ================================================ // 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 idna implements IDNA2008 (Internationalized Domain Names for // Applications), defined in RFC 5890, RFC 5891, RFC 5892, RFC 5893 and // RFC 5894. package idna // import "golang.org/x/net/idna" import ( "strings" "unicode/utf8" ) // TODO(nigeltao): specify when errors occur. For example, is ToASCII(".") or // ToASCII("foo\x00") an error? See also http://www.unicode.org/faq/idn.html#11 // acePrefix is the ASCII Compatible Encoding prefix. const acePrefix = "xn--" // 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". func ToASCII(s string) (string, error) { if ascii(s) { return s, nil } labels := strings.Split(s, ".") for i, label := range labels { if !ascii(label) { a, err := encode(acePrefix, label) if err != nil { return "", err } labels[i] = a } } return strings.Join(labels, "."), nil } // 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". func ToUnicode(s string) (string, error) { if !strings.Contains(s, acePrefix) { return s, nil } labels := strings.Split(s, ".") for i, label := range labels { if strings.HasPrefix(label, acePrefix) { u, err := decode(label[len(acePrefix):]) if err != nil { return "", err } labels[i] = u } } return strings.Join(labels, "."), nil } func ascii(s string) bool { for i := 0; i < len(s); i++ { if s[i] >= utf8.RuneSelf { return false } } return true } ================================================ FILE: vendor/golang.org/x/net/idna/idna_test.go ================================================ // 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 idna import ( "testing" ) var idnaTestCases = [...]struct { ascii, unicode string }{ // Labels. {"books", "books"}, {"xn--bcher-kva", "bücher"}, // Domains. {"foo--xn--bar.org", "foo--xn--bar.org"}, {"golang.org", "golang.org"}, {"example.xn--p1ai", "example.рф"}, {"xn--czrw28b.tw", "商業.tw"}, {"www.xn--mller-kva.de", "www.müller.de"}, } func TestIDNA(t *testing.T) { for _, tc := range idnaTestCases { if a, err := ToASCII(tc.unicode); err != nil { t.Errorf("ToASCII(%q): %v", tc.unicode, err) } else if a != tc.ascii { t.Errorf("ToASCII(%q): got %q, want %q", tc.unicode, a, tc.ascii) } if u, err := ToUnicode(tc.ascii); err != nil { t.Errorf("ToUnicode(%q): %v", tc.ascii, err) } else if u != tc.unicode { t.Errorf("ToUnicode(%q): got %q, want %q", tc.ascii, u, tc.unicode) } } } // TODO(nigeltao): test errors, once we've specified when ToASCII and ToUnicode // return errors. ================================================ FILE: vendor/golang.org/x/net/idna/punycode.go ================================================ // 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 idna // This file implements the Punycode algorithm from RFC 3492. import ( "fmt" "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 ) // 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 "", fmt.Errorf("idna: invalid label %q", 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 "", fmt.Errorf("idna: invalid label %q", encoded) } digit, ok := decodeDigit(encoded[pos]) if !ok { return "", fmt.Errorf("idna: invalid label %q", encoded) } pos++ i += digit * w if i < 0 { return "", fmt.Errorf("idna: invalid label %q", 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 "", fmt.Errorf("idna: invalid label %q", 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 "", fmt.Errorf("idna: invalid label %q", 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 "", fmt.Errorf("idna: invalid label %q", s) } n = m for _, r := range s { if r < n { delta++ if delta < 0 { return "", fmt.Errorf("idna: invalid label %q", 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) } ================================================ FILE: vendor/golang.org/x/net/idna/punycode_test.go ================================================ // 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 idna import ( "strings" "testing" ) var punycodeTestCases = [...]struct { s, encoded string }{ {"", ""}, {"-", "--"}, {"-a", "-a-"}, {"-a-", "-a--"}, {"a", "a-"}, {"a-", "a--"}, {"a-b", "a-b-"}, {"books", "books-"}, {"bücher", "bcher-kva"}, {"Hello世界", "Hello-ck1hg65u"}, {"ü", "tda"}, {"üý", "tdac"}, // The test cases below come from RFC 3492 section 7.1 with Errata 3026. { // (A) Arabic (Egyptian). "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644" + "\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", "egbpdaj6bu4bxfgehfvwxn", }, { // (B) Chinese (simplified). "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye", }, { // (C) Chinese (traditional). "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", "ihqwctvzc91f659drss3x8bo0yb", }, { // (D) Czech. "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074" + "\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D" + "\u0065\u0073\u006B\u0079", "Proprostnemluvesky-uyb24dma41a", }, { // (E) Hebrew. "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8" + "\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2" + "\u05D1\u05E8\u05D9\u05EA", "4dbcagdahymbxekheh6e0a7fei0b", }, { // (F) Hindi (Devanagari). "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D" + "\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939" + "\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947" + "\u0939\u0948\u0902", "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd", }, { // (G) Japanese (kanji and hiragana). "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092" + "\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa", }, { // (H) Korean (Hangul syllables). "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774" + "\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74" + "\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5j" + "psd879ccm6fea98c", }, { // (I) Russian (Cyrillic). "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E" + "\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440" + "\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A" + "\u0438", "b1abfaaepdrnnbgefbadotcwatmq2g4l", }, { // (J) Spanish. "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070" + "\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070" + "\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061" + "\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070" + "\u0061\u00F1\u006F\u006C", "PorqunopuedensimplementehablarenEspaol-fmd56a", }, { // (K) Vietnamese. "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B" + "\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068" + "\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067" + "\u0056\u0069\u1EC7\u0074", "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g", }, { // (L) 3B. "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b", }, { // (M) -with-SUPER-MONKEYS. "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074" + "\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D" + "\u004F\u004E\u004B\u0045\u0059\u0053", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n", }, { // (N) Hello-Another-Way-. "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F" + "\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D" + "\u305D\u308C\u305E\u308C\u306E\u5834\u6240", "Hello-Another-Way--fc4qua05auwb3674vfr0b", }, { // (O) 2. "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", "2-u9tlzr9756bt3uc0v", }, { // (P) MajiKoi5 "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059" + "\u308B\u0035\u79D2\u524D", "MajiKoi5-783gue6qz075azm5e", }, { // (Q) de "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", "de-jg4avhby1noc0d", }, { // (R) "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", "d9juau41awczczp", }, { // (S) -> $1.00 <- "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020" + "\u003C\u002D", "-> $1.00 <--", }, } func TestPunycode(t *testing.T) { for _, tc := range punycodeTestCases { if got, err := decode(tc.encoded); err != nil { t.Errorf("decode(%q): %v", tc.encoded, err) } else if got != tc.s { t.Errorf("decode(%q): got %q, want %q", tc.encoded, got, tc.s) } if got, err := encode("", tc.s); err != nil { t.Errorf(`encode("", %q): %v`, tc.s, err) } else if got != tc.encoded { t.Errorf(`encode("", %q): got %q, want %q`, tc.s, got, tc.encoded) } } } var punycodeErrorTestCases = [...]string{ "decode -", // A sole '-' is invalid. "decode foo\x00bar", // '\x00' is not in [0-9A-Za-z]. "decode foo#bar", // '#' is not in [0-9A-Za-z]. "decode foo\u00A3bar", // '\u00A3' is not in [0-9A-Za-z]. "decode 9", // "9a" decodes to codepoint \u00A3; "9" is truncated. "decode 99999a", // "99999a" decodes to codepoint \U0048A3C1, which is > \U0010FFFF. "decode 9999999999a", // "9999999999a" overflows the int32 calculation. "encode " + strings.Repeat("x", 65536) + "\uff00", // int32 overflow. } func TestPunycodeErrors(t *testing.T) { for _, tc := range punycodeErrorTestCases { var err error switch { case strings.HasPrefix(tc, "decode "): _, err = decode(tc[7:]) case strings.HasPrefix(tc, "encode "): _, err = encode("", tc[7:]) } if err == nil { if len(tc) > 256 { tc = tc[:100] + "..." + tc[len(tc)-100:] } t.Errorf("no error for %s", tc) } } } ================================================ FILE: vendor/golang.org/x/net/internal/iana/const.go ================================================ // go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA). package iana // import "golang.org/x/net/internal/iana" // Differentiated Services Field Codepoints (DSCP), Updated: 2013-06-25 const ( DiffServCS0 = 0x0 // CS0 DiffServCS1 = 0x20 // CS1 DiffServCS2 = 0x40 // CS2 DiffServCS3 = 0x60 // CS3 DiffServCS4 = 0x80 // CS4 DiffServCS5 = 0xa0 // CS5 DiffServCS6 = 0xc0 // CS6 DiffServCS7 = 0xe0 // CS7 DiffServAF11 = 0x28 // AF11 DiffServAF12 = 0x30 // AF12 DiffServAF13 = 0x38 // AF13 DiffServAF21 = 0x48 // AF21 DiffServAF22 = 0x50 // AF22 DiffServAF23 = 0x58 // AF23 DiffServAF31 = 0x68 // AF31 DiffServAF32 = 0x70 // AF32 DiffServAF33 = 0x78 // AF33 DiffServAF41 = 0x88 // AF41 DiffServAF42 = 0x90 // AF42 DiffServAF43 = 0x98 // AF43 DiffServEFPHB = 0xb8 // EF PHB DiffServVOICEADMIT = 0xb0 // VOICE-ADMIT ) // IPv4 TOS Byte and IPv6 Traffic Class Octet, Updated: 2001-09-06 const ( NotECNTransport = 0x0 // Not-ECT (Not ECN-Capable Transport) ECNTransport1 = 0x1 // ECT(1) (ECN-Capable Transport(1)) ECNTransport0 = 0x2 // ECT(0) (ECN-Capable Transport(0)) CongestionExperienced = 0x3 // CE (Congestion Experienced) ) // Protocol Numbers, Updated: 2015-06-23 const ( ProtocolIP = 0 // IPv4 encapsulation, pseudo protocol number ProtocolHOPOPT = 0 // IPv6 Hop-by-Hop Option ProtocolICMP = 1 // Internet Control Message ProtocolIGMP = 2 // Internet Group Management ProtocolGGP = 3 // Gateway-to-Gateway ProtocolIPv4 = 4 // IPv4 encapsulation ProtocolST = 5 // Stream ProtocolTCP = 6 // Transmission Control ProtocolCBT = 7 // CBT ProtocolEGP = 8 // Exterior Gateway Protocol ProtocolIGP = 9 // any private interior gateway (used by Cisco for their IGRP) ProtocolBBNRCCMON = 10 // BBN RCC Monitoring ProtocolNVPII = 11 // Network Voice Protocol ProtocolPUP = 12 // PUP ProtocolARGUS = 13 // ARGUS ProtocolEMCON = 14 // EMCON ProtocolXNET = 15 // Cross Net Debugger ProtocolCHAOS = 16 // Chaos ProtocolUDP = 17 // User Datagram ProtocolMUX = 18 // Multiplexing ProtocolDCNMEAS = 19 // DCN Measurement Subsystems ProtocolHMP = 20 // Host Monitoring ProtocolPRM = 21 // Packet Radio Measurement ProtocolXNSIDP = 22 // XEROX NS IDP ProtocolTRUNK1 = 23 // Trunk-1 ProtocolTRUNK2 = 24 // Trunk-2 ProtocolLEAF1 = 25 // Leaf-1 ProtocolLEAF2 = 26 // Leaf-2 ProtocolRDP = 27 // Reliable Data Protocol ProtocolIRTP = 28 // Internet Reliable Transaction ProtocolISOTP4 = 29 // ISO Transport Protocol Class 4 ProtocolNETBLT = 30 // Bulk Data Transfer Protocol ProtocolMFENSP = 31 // MFE Network Services Protocol ProtocolMERITINP = 32 // MERIT Internodal Protocol ProtocolDCCP = 33 // Datagram Congestion Control Protocol Protocol3PC = 34 // Third Party Connect Protocol ProtocolIDPR = 35 // Inter-Domain Policy Routing Protocol ProtocolXTP = 36 // XTP ProtocolDDP = 37 // Datagram Delivery Protocol ProtocolIDPRCMTP = 38 // IDPR Control Message Transport Proto ProtocolTPPP = 39 // TP++ Transport Protocol ProtocolIL = 40 // IL Transport Protocol ProtocolIPv6 = 41 // IPv6 encapsulation ProtocolSDRP = 42 // Source Demand Routing Protocol ProtocolIPv6Route = 43 // Routing Header for IPv6 ProtocolIPv6Frag = 44 // Fragment Header for IPv6 ProtocolIDRP = 45 // Inter-Domain Routing Protocol ProtocolRSVP = 46 // Reservation Protocol ProtocolGRE = 47 // Generic Routing Encapsulation ProtocolDSR = 48 // Dynamic Source Routing Protocol ProtocolBNA = 49 // BNA ProtocolESP = 50 // Encap Security Payload ProtocolAH = 51 // Authentication Header ProtocolINLSP = 52 // Integrated Net Layer Security TUBA ProtocolNARP = 54 // NBMA Address Resolution Protocol ProtocolMOBILE = 55 // IP Mobility ProtocolTLSP = 56 // Transport Layer Security Protocol using Kryptonet key management ProtocolSKIP = 57 // SKIP ProtocolIPv6ICMP = 58 // ICMP for IPv6 ProtocolIPv6NoNxt = 59 // No Next Header for IPv6 ProtocolIPv6Opts = 60 // Destination Options for IPv6 ProtocolCFTP = 62 // CFTP ProtocolSATEXPAK = 64 // SATNET and Backroom EXPAK ProtocolKRYPTOLAN = 65 // Kryptolan ProtocolRVD = 66 // MIT Remote Virtual Disk Protocol ProtocolIPPC = 67 // Internet Pluribus Packet Core ProtocolSATMON = 69 // SATNET Monitoring ProtocolVISA = 70 // VISA Protocol ProtocolIPCV = 71 // Internet Packet Core Utility ProtocolCPNX = 72 // Computer Protocol Network Executive ProtocolCPHB = 73 // Computer Protocol Heart Beat ProtocolWSN = 74 // Wang Span Network ProtocolPVP = 75 // Packet Video Protocol ProtocolBRSATMON = 76 // Backroom SATNET Monitoring ProtocolSUNND = 77 // SUN ND PROTOCOL-Temporary ProtocolWBMON = 78 // WIDEBAND Monitoring ProtocolWBEXPAK = 79 // WIDEBAND EXPAK ProtocolISOIP = 80 // ISO Internet Protocol ProtocolVMTP = 81 // VMTP ProtocolSECUREVMTP = 82 // SECURE-VMTP ProtocolVINES = 83 // VINES ProtocolTTP = 84 // Transaction Transport Protocol ProtocolIPTM = 84 // Internet Protocol Traffic Manager ProtocolNSFNETIGP = 85 // NSFNET-IGP ProtocolDGP = 86 // Dissimilar Gateway Protocol ProtocolTCF = 87 // TCF ProtocolEIGRP = 88 // EIGRP ProtocolOSPFIGP = 89 // OSPFIGP ProtocolSpriteRPC = 90 // Sprite RPC Protocol ProtocolLARP = 91 // Locus Address Resolution Protocol ProtocolMTP = 92 // Multicast Transport Protocol ProtocolAX25 = 93 // AX.25 Frames ProtocolIPIP = 94 // IP-within-IP Encapsulation Protocol ProtocolSCCSP = 96 // Semaphore Communications Sec. Pro. ProtocolETHERIP = 97 // Ethernet-within-IP Encapsulation ProtocolENCAP = 98 // Encapsulation Header ProtocolGMTP = 100 // GMTP ProtocolIFMP = 101 // Ipsilon Flow Management Protocol ProtocolPNNI = 102 // PNNI over IP ProtocolPIM = 103 // Protocol Independent Multicast ProtocolARIS = 104 // ARIS ProtocolSCPS = 105 // SCPS ProtocolQNX = 106 // QNX ProtocolAN = 107 // Active Networks ProtocolIPComp = 108 // IP Payload Compression Protocol ProtocolSNP = 109 // Sitara Networks Protocol ProtocolCompaqPeer = 110 // Compaq Peer Protocol ProtocolIPXinIP = 111 // IPX in IP ProtocolVRRP = 112 // Virtual Router Redundancy Protocol ProtocolPGM = 113 // PGM Reliable Transport Protocol ProtocolL2TP = 115 // Layer Two Tunneling Protocol ProtocolDDX = 116 // D-II Data Exchange (DDX) ProtocolIATP = 117 // Interactive Agent Transfer Protocol ProtocolSTP = 118 // Schedule Transfer Protocol ProtocolSRP = 119 // SpectraLink Radio Protocol ProtocolUTI = 120 // UTI ProtocolSMP = 121 // Simple Message Protocol ProtocolPTP = 123 // Performance Transparency Protocol ProtocolISIS = 124 // ISIS over IPv4 ProtocolFIRE = 125 // FIRE ProtocolCRTP = 126 // Combat Radio Transport Protocol ProtocolCRUDP = 127 // Combat Radio User Datagram ProtocolSSCOPMCE = 128 // SSCOPMCE ProtocolIPLT = 129 // IPLT ProtocolSPS = 130 // Secure Packet Shield ProtocolPIPE = 131 // Private IP Encapsulation within IP ProtocolSCTP = 132 // Stream Control Transmission Protocol ProtocolFC = 133 // Fibre Channel ProtocolRSVPE2EIGNORE = 134 // RSVP-E2E-IGNORE ProtocolMobilityHeader = 135 // Mobility Header ProtocolUDPLite = 136 // UDPLite ProtocolMPLSinIP = 137 // MPLS-in-IP ProtocolMANET = 138 // MANET Protocols ProtocolHIP = 139 // Host Identity Protocol ProtocolShim6 = 140 // Shim6 Protocol ProtocolWESP = 141 // Wrapped Encapsulating Security Payload ProtocolROHC = 142 // Robust Header Compression ProtocolReserved = 255 // Reserved ) ================================================ FILE: vendor/golang.org/x/net/internal/iana/gen.go ================================================ // 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 ignore //go:generate go run gen.go // This program generates internet protocol constants and tables by // reading IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "strconv" "strings" ) var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/dscp-registry/dscp-registry.xml", parseDSCPRegistry, }, { "http://www.iana.org/assignments/ipv4-tos-byte/ipv4-tos-byte.xml", parseTOSTCByte, }, { "http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml", parseProtocolNumbers, }, } func main() { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "// Package iana provides protocol number resources managed by the Internet Assigned Numbers Authority (IANA).\n") fmt.Fprintf(&bb, `package iana // import "golang.org/x/net/internal/iana"`+"\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { fmt.Fprintf(os.Stderr, "got HTTP status code %v for %v\n", resp.StatusCode, r.url) os.Exit(1) } if err := r.parse(&bb, resp.Body); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := ioutil.WriteFile("const.go", b, 0644); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func parseDSCPRegistry(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var dr dscpRegistry if err := dec.Decode(&dr); err != nil { return err } drs := dr.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", dr.Title, dr.Updated) fmt.Fprintf(w, "const (\n") for _, dr := range drs { fmt.Fprintf(w, "DiffServ%s = %#x", dr.Name, dr.Value) fmt.Fprintf(w, "// %s\n", dr.OrigName) } fmt.Fprintf(w, ")\n") return nil } type dscpRegistry struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` RegTitle string `xml:"registry>title"` PoolRecords []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"registry>record"` Records []struct { Name string `xml:"name"` Space string `xml:"space"` } `xml:"registry>registry>record"` } type canonDSCPRecord struct { OrigName string Name string Value int } func (drr *dscpRegistry) escape() []canonDSCPRecord { drs := make([]canonDSCPRecord, len(drr.Records)) sr := strings.NewReplacer( "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, dr := range drr.Records { s := strings.TrimSpace(dr.Name) drs[i].OrigName = s drs[i].Name = sr.Replace(s) n, err := strconv.ParseUint(dr.Space, 2, 8) if err != nil { continue } drs[i].Value = int(n) << 2 } return drs } func parseTOSTCByte(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var ttb tosTCByte if err := dec.Decode(&ttb); err != nil { return err } trs := ttb.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", ttb.Title, ttb.Updated) fmt.Fprintf(w, "const (\n") for _, tr := range trs { fmt.Fprintf(w, "%s = %#x", tr.Keyword, tr.Value) fmt.Fprintf(w, "// %s\n", tr.OrigKeyword) } fmt.Fprintf(w, ")\n") return nil } type tosTCByte struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Note string `xml:"note"` RegTitle string `xml:"registry>title"` Records []struct { Binary string `xml:"binary"` Keyword string `xml:"keyword"` } `xml:"registry>record"` } type canonTOSTCByteRecord struct { OrigKeyword string Keyword string Value int } func (ttb *tosTCByte) escape() []canonTOSTCByteRecord { trs := make([]canonTOSTCByteRecord, len(ttb.Records)) sr := strings.NewReplacer( "Capable", "", "(", "", ")", "", "+", "", "-", "", "/", "", ".", "", " ", "", ) for i, tr := range ttb.Records { s := strings.TrimSpace(tr.Keyword) trs[i].OrigKeyword = s ss := strings.Split(s, " ") if len(ss) > 1 { trs[i].Keyword = strings.Join(ss[1:], " ") } else { trs[i].Keyword = ss[0] } trs[i].Keyword = sr.Replace(trs[i].Keyword) n, err := strconv.ParseUint(tr.Binary, 2, 8) if err != nil { continue } trs[i].Value = int(n) } return trs } func parseProtocolNumbers(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var pn protocolNumbers if err := dec.Decode(&pn); err != nil { return err } prs := pn.escape() prs = append([]canonProtocolRecord{{ Name: "IP", Descr: "IPv4 encapsulation, pseudo protocol number", Value: 0, }}, prs...) fmt.Fprintf(w, "// %s, Updated: %s\n", pn.Title, pn.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "Protocol%s = %d", pr.Name, pr.Value) s := pr.Descr if s == "" { s = pr.OrigName } fmt.Fprintf(w, "// %s\n", s) } fmt.Fprintf(w, ")\n") return nil } type protocolNumbers struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` RegTitle string `xml:"registry>title"` Note string `xml:"registry>note"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` Descr string `xml:"description"` } `xml:"registry>record"` } type canonProtocolRecord struct { OrigName string Name string Descr string Value int } func (pn *protocolNumbers) escape() []canonProtocolRecord { prs := make([]canonProtocolRecord, len(pn.Records)) sr := strings.NewReplacer( "-in-", "in", "-within-", "within", "-over-", "over", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range pn.Records { if strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "deprecated") { continue } prs[i].OrigName = pr.Name s := strings.TrimSpace(pr.Name) switch pr.Name { case "ISIS over IPv4": prs[i].Name = "ISIS" case "manet": prs[i].Name = "MANET" default: prs[i].Name = sr.Replace(s) } ss := strings.Split(pr.Descr, "\n") for i := range ss { ss[i] = strings.TrimSpace(ss[i]) } if len(ss) > 1 { prs[i].Descr = strings.Join(ss, " ") } else { prs[i].Descr = ss[0] } prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/error_posix.go ================================================ // 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 solaris windows package nettest import ( "os" "syscall" ) func protocolNotSupported(err error) bool { switch err := err.(type) { case syscall.Errno: switch err { case syscall.EPROTONOSUPPORT, syscall.ENOPROTOOPT: return true } case *os.SyscallError: switch err := err.Err.(type) { case syscall.Errno: switch err { case syscall.EPROTONOSUPPORT, syscall.ENOPROTOOPT: return true } } } return false } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/error_stub.go ================================================ // 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 nacl plan9 package nettest func protocolNotSupported(err error) bool { return false } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/interface.go ================================================ // 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 nettest import "net" // IsMulticastCapable reports whether ifi is an IP multicast-capable // network interface. Network must be "ip", "ip4" or "ip6". func IsMulticastCapable(network string, ifi *net.Interface) (net.IP, bool) { switch network { case "ip", "ip4", "ip6": default: return nil, false } if ifi == nil || ifi.Flags&net.FlagUp == 0 || ifi.Flags&net.FlagMulticast == 0 { return nil, false } return hasRoutableIP(network, ifi) } // RoutedInterface returns a network interface that can route IP // traffic and satisfies flags. It returns nil when an appropriate // network interface is not found. Network must be "ip", "ip4" or // "ip6". func RoutedInterface(network string, flags net.Flags) *net.Interface { switch network { case "ip", "ip4", "ip6": default: return nil } ift, err := net.Interfaces() if err != nil { return nil } for _, ifi := range ift { if ifi.Flags&flags != flags { continue } if _, ok := hasRoutableIP(network, &ifi); !ok { continue } return &ifi } return nil } func hasRoutableIP(network string, ifi *net.Interface) (net.IP, bool) { ifat, err := ifi.Addrs() if err != nil { return nil, false } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip := routableIP(network, ifa.IP); ip != nil { return ip, true } case *net.IPNet: if ip := routableIP(network, ifa.IP); ip != nil { return ip, true } } } return nil, false } func routableIP(network string, ip net.IP) net.IP { if !ip.IsLoopback() && !ip.IsLinkLocalUnicast() && !ip.IsGlobalUnicast() { return nil } switch network { case "ip4": if ip := ip.To4(); ip != nil { return ip } case "ip6": if ip.IsLoopback() { // addressing scope of the loopback address depends on each implementation return nil } if ip := ip.To16(); ip != nil && ip.To4() == nil { return ip } default: if ip := ip.To4(); ip != nil { return ip } if ip := ip.To16(); ip != nil { return ip } } return nil } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/rlimit.go ================================================ // 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 nettest const defaultMaxOpenFiles = 256 // MaxOpenFiles returns the maximum number of open files for the // caller's process. func MaxOpenFiles() int { return maxOpenFiles() } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/rlimit_stub.go ================================================ // 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 nacl plan9 package nettest func maxOpenFiles() int { return defaultMaxOpenFiles } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/rlimit_unix.go ================================================ // 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 nettest import "syscall" func maxOpenFiles() int { var rlim syscall.Rlimit if err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rlim); err != nil { return defaultMaxOpenFiles } return int(rlim.Cur) } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/rlimit_windows.go ================================================ // 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 nettest func maxOpenFiles() int { return 4 * defaultMaxOpenFiles /* actually it's 16581375 */ } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/stack.go ================================================ // 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 nettest provides utilities for IP testing. package nettest // import "golang.org/x/net/internal/nettest" import "net" // SupportsIPv4 reports whether the platform supports IPv4 networking // functionality. func SupportsIPv4() bool { ln, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { return false } ln.Close() return true } // SupportsIPv6 reports whether the platform supports IPv6 networking // functionality. func SupportsIPv6() bool { ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { return false } ln.Close() return true } // ProtocolNotSupported reports whether err is a protocol not // supported error. func ProtocolNotSupported(err error) bool { return protocolNotSupported(err) } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/stack_stub.go ================================================ // 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 nacl plan9 package nettest import ( "fmt" "runtime" ) // SupportsRawIPSocket reports whether the platform supports raw IP // sockets. func SupportsRawIPSocket() (string, bool) { return fmt.Sprintf("not supported on %s", runtime.GOOS), false } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/stack_unix.go ================================================ // 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 nettest import ( "fmt" "os" "runtime" ) // SupportsRawIPSocket reports whether the platform supports raw IP // sockets. func SupportsRawIPSocket() (string, bool) { if os.Getuid() != 0 { return fmt.Sprintf("must be root on %s", runtime.GOOS), false } return "", true } ================================================ FILE: vendor/golang.org/x/net/internal/nettest/stack_windows.go ================================================ // 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 nettest import ( "fmt" "runtime" "syscall" ) // SupportsRawIPSocket reports whether the platform supports raw IP // sockets. func SupportsRawIPSocket() (string, bool) { // From http://msdn.microsoft.com/en-us/library/windows/desktop/ms740548.aspx: // Note: To use a socket of type SOCK_RAW requires administrative privileges. // Users running Winsock applications that use raw sockets must be a member of // the Administrators group on the local computer, otherwise raw socket calls // will fail with an error code of WSAEACCES. On Windows Vista and later, access // for raw sockets is enforced at socket creation. In earlier versions of Windows, // access for raw sockets is enforced during other socket operations. s, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, 0) if err == syscall.WSAEACCES { return fmt.Sprintf("no access to raw socket allowed on %s", runtime.GOOS), false } if err != nil { return err.Error(), false } syscall.Closesocket(s) return "", true } ================================================ FILE: vendor/golang.org/x/net/internal/timeseries/timeseries.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/net/internal/timeseries/timeseries_test.go ================================================ // 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 import ( "math" "testing" "time" ) func isNear(x *Float, y float64, tolerance float64) bool { return math.Abs(x.Value()-y) < tolerance } func isApproximate(x *Float, y float64) bool { return isNear(x, y, 1e-2) } func checkApproximate(t *testing.T, o Observable, y float64) { x := o.(*Float) if !isApproximate(x, y) { t.Errorf("Wanted %g, got %g", y, x.Value()) } } func checkNear(t *testing.T, o Observable, y, tolerance float64) { x := o.(*Float) if !isNear(x, y, tolerance) { t.Errorf("Wanted %g +- %g, got %g", y, tolerance, x.Value()) } } var baseTime = time.Date(2013, 1, 1, 0, 0, 0, 0, time.UTC) func tu(s int64) time.Time { return baseTime.Add(time.Duration(s) * time.Second) } func tu2(s int64, ns int64) time.Time { return baseTime.Add(time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond) } func TestBasicTimeSeries(t *testing.T) { ts := NewTimeSeries(NewFloat) fo := new(Float) *fo = Float(10) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) checkApproximate(t, ts.Range(tu(0), tu(1)), 40) checkApproximate(t, ts.Total(), 40) ts.AddWithTime(fo, tu(3)) ts.AddWithTime(fo, tu(3)) ts.AddWithTime(fo, tu(3)) checkApproximate(t, ts.Range(tu(0), tu(2)), 40) checkApproximate(t, ts.Range(tu(2), tu(4)), 30) checkApproximate(t, ts.Total(), 70) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) checkApproximate(t, ts.Range(tu(0), tu(2)), 60) checkApproximate(t, ts.Range(tu(2), tu(4)), 30) checkApproximate(t, ts.Total(), 90) *fo = Float(100) ts.AddWithTime(fo, tu(100)) checkApproximate(t, ts.Range(tu(99), tu(100)), 100) checkApproximate(t, ts.Range(tu(0), tu(4)), 36) checkApproximate(t, ts.Total(), 190) *fo = Float(10) ts.AddWithTime(fo, tu(1)) ts.AddWithTime(fo, tu(1)) checkApproximate(t, ts.Range(tu(0), tu(4)), 44) checkApproximate(t, ts.Range(tu(37), tu2(100, 100e6)), 100) checkApproximate(t, ts.Range(tu(50), tu2(100, 100e6)), 100) checkApproximate(t, ts.Range(tu(99), tu2(100, 100e6)), 100) checkApproximate(t, ts.Total(), 210) for i, l := range ts.ComputeRange(tu(36), tu(100), 64) { if i == 63 { checkApproximate(t, l, 100) } else { checkApproximate(t, l, 0) } } checkApproximate(t, ts.Range(tu(0), tu(100)), 210) checkApproximate(t, ts.Range(tu(10), tu(100)), 100) for i, l := range ts.ComputeRange(tu(0), tu(100), 100) { if i < 10 { checkApproximate(t, l, 11) } else if i >= 90 { checkApproximate(t, l, 10) } else { checkApproximate(t, l, 0) } } } func TestFloat(t *testing.T) { f := Float(1) if g, w := f.String(), "1"; g != w { t.Errorf("Float(1).String = %q; want %q", g, w) } f2 := Float(2) var o Observable = &f2 f.Add(o) if g, w := f.Value(), 3.0; g != w { t.Errorf("Float post-add = %v; want %v", g, w) } f.Multiply(2) if g, w := f.Value(), 6.0; g != w { t.Errorf("Float post-multiply = %v; want %v", g, w) } f.Clear() if g, w := f.Value(), 0.0; g != w { t.Errorf("Float post-clear = %v; want %v", g, w) } f.CopyFrom(&f2) if g, w := f.Value(), 2.0; g != w { t.Errorf("Float post-CopyFrom = %v; want %v", g, w) } } type mockClock struct { time time.Time } func (m *mockClock) Time() time.Time { return m.time } func (m *mockClock) Set(t time.Time) { m.time = t } const buckets = 6 var testResolutions = []time.Duration{ 10 * time.Second, // level holds one minute of observations 100 * time.Second, // level holds ten minutes of observations 10 * time.Minute, // level holds one hour of observations } // TestTimeSeries uses a small number of buckets to force a higher // error rate on approximations from the timeseries. type TestTimeSeries struct { timeSeries } func TestExpectedErrorRate(t *testing.T) { ts := new(TestTimeSeries) fake := new(mockClock) fake.Set(time.Now()) ts.timeSeries.init(testResolutions, NewFloat, buckets, fake) for i := 1; i <= 61*61; i++ { fake.Set(fake.Time().Add(1 * time.Second)) ob := Float(1) ts.AddWithTime(&ob, fake.Time()) // The results should be accurate within one missing bucket (1/6) of the observations recorded. checkNear(t, ts.Latest(0, buckets), min(float64(i), 60), 10) checkNear(t, ts.Latest(1, buckets), min(float64(i), 600), 100) checkNear(t, ts.Latest(2, buckets), min(float64(i), 3600), 600) } } func min(a, b float64) float64 { if a < b { return a } return b } ================================================ FILE: vendor/golang.org/x/net/ipv4/control.go ================================================ // 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 ipv4 import ( "fmt" "net" "sync" ) type rawOpt struct { sync.RWMutex cflags ControlFlags } func (c *rawOpt) set(f ControlFlags) { c.cflags |= f } func (c *rawOpt) clear(f ControlFlags) { c.cflags &^= f } func (c *rawOpt) isset(f ControlFlags) bool { return c.cflags&f != 0 } type ControlFlags uint const ( FlagTTL ControlFlags = 1 << iota // pass the TTL on the received packet FlagSrc // pass the source address on the received packet FlagDst // pass the destination address on the received packet FlagInterface // pass the interface index on the received packet ) // A ControlMessage represents per packet basis IP-level socket options. type ControlMessage struct { // Receiving socket options: SetControlMessage allows to // receive the options from the protocol stack using ReadFrom // method of PacketConn or RawConn. // // Specifying socket options: ControlMessage for WriteTo // method of PacketConn or RawConn allows to send the options // to the protocol stack. // TTL int // time-to-live, receiving only Src net.IP // source address, specifying only Dst net.IP // destination address, receiving only IfIndex int // interface index, must be 1 <= value when specifying } func (cm *ControlMessage) String() string { if cm == nil { return "" } return fmt.Sprintf("ttl: %v, src: %v, dst: %v, ifindex: %v", cm.TTL, cm.Src, cm.Dst, cm.IfIndex) } // Ancillary data socket options const ( ctlTTL = iota // header field ctlSrc // header field ctlDst // header field ctlInterface // inbound or outbound interface ctlPacketInfo // inbound or outbound packet path ctlMax ) // A ctlOpt represents a binding for ancillary data socket option. type ctlOpt struct { name int // option name, must be equal or greater than 1 length int // option length marshal func([]byte, *ControlMessage) []byte parse func(*ControlMessage, []byte) } ================================================ FILE: vendor/golang.org/x/net/ipv4/control_bsd.go ================================================ // 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 dragonfly freebsd netbsd openbsd package ipv4 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func marshalDst(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIP m.Type = sysIP_RECVDSTADDR m.SetLen(syscall.CmsgLen(net.IPv4len)) return b[syscall.CmsgSpace(net.IPv4len):] } func parseDst(cm *ControlMessage, b []byte) { cm.Dst = b[:net.IPv4len] } func marshalInterface(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIP m.Type = sysIP_RECVIF m.SetLen(syscall.CmsgLen(syscall.SizeofSockaddrDatalink)) return b[syscall.CmsgSpace(syscall.SizeofSockaddrDatalink):] } func parseInterface(cm *ControlMessage, b []byte) { sadl := (*syscall.SockaddrDatalink)(unsafe.Pointer(&b[0])) cm.IfIndex = int(sadl.Index) } ================================================ FILE: vendor/golang.org/x/net/ipv4/control_pktinfo.go ================================================ // 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 linux package ipv4 import ( "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIP m.Type = sysIP_PKTINFO m.SetLen(syscall.CmsgLen(sysSizeofInetPktinfo)) if cm != nil { pi := (*sysInetPktinfo)(unsafe.Pointer(&b[syscall.CmsgLen(0)])) if ip := cm.Src.To4(); ip != nil { copy(pi.Spec_dst[:], ip) } if cm.IfIndex > 0 { pi.setIfindex(cm.IfIndex) } } return b[syscall.CmsgSpace(sysSizeofInetPktinfo):] } func parsePacketInfo(cm *ControlMessage, b []byte) { pi := (*sysInetPktinfo)(unsafe.Pointer(&b[0])) cm.IfIndex = int(pi.Ifindex) cm.Dst = pi.Addr[:] } ================================================ FILE: vendor/golang.org/x/net/ipv4/control_stub.go ================================================ // 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 nacl plan9 solaris package ipv4 func setControlMessage(fd int, opt *rawOpt, cf ControlFlags, on bool) error { return errOpNoSupport } func newControlMessage(opt *rawOpt) []byte { return nil } func parseControlMessage(b []byte) (*ControlMessage, error) { return nil, errOpNoSupport } func marshalControlMessage(cm *ControlMessage) []byte { return nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/control_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv4 import ( "os" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func setControlMessage(fd int, opt *rawOpt, cf ControlFlags, on bool) error { opt.Lock() defer opt.Unlock() if cf&FlagTTL != 0 && sockOpts[ssoReceiveTTL].name > 0 { if err := setInt(fd, &sockOpts[ssoReceiveTTL], boolint(on)); err != nil { return err } if on { opt.set(FlagTTL) } else { opt.clear(FlagTTL) } } if sockOpts[ssoPacketInfo].name > 0 { if cf&(FlagSrc|FlagDst|FlagInterface) != 0 { if err := setInt(fd, &sockOpts[ssoPacketInfo], boolint(on)); err != nil { return err } if on { opt.set(cf & (FlagSrc | FlagDst | FlagInterface)) } else { opt.clear(cf & (FlagSrc | FlagDst | FlagInterface)) } } } else { if cf&FlagDst != 0 && sockOpts[ssoReceiveDst].name > 0 { if err := setInt(fd, &sockOpts[ssoReceiveDst], boolint(on)); err != nil { return err } if on { opt.set(FlagDst) } else { opt.clear(FlagDst) } } if cf&FlagInterface != 0 && sockOpts[ssoReceiveInterface].name > 0 { if err := setInt(fd, &sockOpts[ssoReceiveInterface], boolint(on)); err != nil { return err } if on { opt.set(FlagInterface) } else { opt.clear(FlagInterface) } } } return nil } func newControlMessage(opt *rawOpt) (oob []byte) { opt.RLock() var l int if opt.isset(FlagTTL) && ctlOpts[ctlTTL].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlTTL].length) } if ctlOpts[ctlPacketInfo].name > 0 { if opt.isset(FlagSrc | FlagDst | FlagInterface) { l += syscall.CmsgSpace(ctlOpts[ctlPacketInfo].length) } } else { if opt.isset(FlagDst) && ctlOpts[ctlDst].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlDst].length) } if opt.isset(FlagInterface) && ctlOpts[ctlInterface].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlInterface].length) } } if l > 0 { oob = make([]byte, l) b := oob if opt.isset(FlagTTL) && ctlOpts[ctlTTL].name > 0 { b = ctlOpts[ctlTTL].marshal(b, nil) } if ctlOpts[ctlPacketInfo].name > 0 { if opt.isset(FlagSrc | FlagDst | FlagInterface) { b = ctlOpts[ctlPacketInfo].marshal(b, nil) } } else { if opt.isset(FlagDst) && ctlOpts[ctlDst].name > 0 { b = ctlOpts[ctlDst].marshal(b, nil) } if opt.isset(FlagInterface) && ctlOpts[ctlInterface].name > 0 { b = ctlOpts[ctlInterface].marshal(b, nil) } } } opt.RUnlock() return } func parseControlMessage(b []byte) (*ControlMessage, error) { if len(b) == 0 { return nil, nil } cmsgs, err := syscall.ParseSocketControlMessage(b) if err != nil { return nil, os.NewSyscallError("parse socket control message", err) } cm := &ControlMessage{} for _, m := range cmsgs { if m.Header.Level != iana.ProtocolIP { continue } switch int(m.Header.Type) { case ctlOpts[ctlTTL].name: ctlOpts[ctlTTL].parse(cm, m.Data[:]) case ctlOpts[ctlDst].name: ctlOpts[ctlDst].parse(cm, m.Data[:]) case ctlOpts[ctlInterface].name: ctlOpts[ctlInterface].parse(cm, m.Data[:]) case ctlOpts[ctlPacketInfo].name: ctlOpts[ctlPacketInfo].parse(cm, m.Data[:]) } } return cm, nil } func marshalControlMessage(cm *ControlMessage) (oob []byte) { if cm == nil { return nil } var l int pktinfo := false if ctlOpts[ctlPacketInfo].name > 0 && (cm.Src.To4() != nil || cm.IfIndex > 0) { pktinfo = true l += syscall.CmsgSpace(ctlOpts[ctlPacketInfo].length) } if l > 0 { oob = make([]byte, l) b := oob if pktinfo { b = ctlOpts[ctlPacketInfo].marshal(b, cm) } } return } func marshalTTL(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIP m.Type = sysIP_RECVTTL m.SetLen(syscall.CmsgLen(1)) return b[syscall.CmsgSpace(1):] } func parseTTL(cm *ControlMessage, b []byte) { cm.TTL = int(*(*byte)(unsafe.Pointer(&b[:1][0]))) } ================================================ FILE: vendor/golang.org/x/net/ipv4/control_windows.go ================================================ // 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 ipv4 import "syscall" func setControlMessage(fd syscall.Handle, opt *rawOpt, cf ControlFlags, on bool) error { // TODO(mikio): implement this return syscall.EWINDOWS } func newControlMessage(opt *rawOpt) []byte { // TODO(mikio): implement this return nil } func parseControlMessage(b []byte) (*ControlMessage, error) { // TODO(mikio): implement this return nil, syscall.EWINDOWS } func marshalControlMessage(cm *ControlMessage) []byte { // TODO(mikio): implement this return nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_darwin.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_STRIPHDR = C.IP_STRIPHDR sysIP_RECVTTL = C.IP_RECVTTL sysIP_BOUND_IF = C.IP_BOUND_IF sysIP_PKTINFO = C.IP_PKTINFO sysIP_RECVPKTINFO = C.IP_RECVPKTINFO sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF sysIP_MULTICAST_IFINDEX = C.IP_MULTICAST_IFINDEX sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysSizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sysSizeofSockaddrInet = C.sizeof_struct_sockaddr_in sysSizeofInetPktinfo = C.sizeof_struct_in_pktinfo sysSizeofIPMreq = C.sizeof_struct_ip_mreq sysSizeofIPMreqn = C.sizeof_struct_ip_mreqn sysSizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sysSizeofGroupReq = C.sizeof_struct_group_req sysSizeofGroupSourceReq = C.sizeof_struct_group_source_req ) type sysSockaddrStorage C.struct_sockaddr_storage type sysSockaddrInet C.struct_sockaddr_in type sysInetPktinfo C.struct_in_pktinfo type sysIPMreq C.struct_ip_mreq type sysIPMreqn C.struct_ip_mreqn type sysIPMreqSource C.struct_ip_mreq_source type sysGroupReq C.struct_group_req type sysGroupSourceReq C.struct_group_source_req ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_dragonfly.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysSizeofIPMreq = C.sizeof_struct_ip_mreq ) type sysIPMreq C.struct_ip_mreq ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_freebsd.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_SENDSRCADDR = C.IP_SENDSRCADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_ONESBCAST = C.IP_ONESBCAST sysIP_BINDANY = C.IP_BINDANY sysIP_RECVTTL = C.IP_RECVTTL sysIP_MINTTL = C.IP_MINTTL sysIP_DONTFRAG = C.IP_DONTFRAG sysIP_RECVTOS = C.IP_RECVTOS sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_MULTICAST_VIF = C.IP_MULTICAST_VIF sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysSizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sysSizeofSockaddrInet = C.sizeof_struct_sockaddr_in sysSizeofIPMreq = C.sizeof_struct_ip_mreq sysSizeofIPMreqn = C.sizeof_struct_ip_mreqn sysSizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sysSizeofGroupReq = C.sizeof_struct_group_req sysSizeofGroupSourceReq = C.sizeof_struct_group_source_req ) type sysSockaddrStorage C.struct_sockaddr_storage type sysSockaddrInet C.struct_sockaddr_in type sysIPMreq C.struct_ip_mreq type sysIPMreqn C.struct_ip_mreqn type sysIPMreqSource C.struct_ip_mreq_source type sysGroupReq C.struct_group_req type sysGroupSourceReq C.struct_group_source_req ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_linux.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include #include #include #include */ import "C" const ( sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_HDRINCL = C.IP_HDRINCL sysIP_OPTIONS = C.IP_OPTIONS sysIP_ROUTER_ALERT = C.IP_ROUTER_ALERT sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RETOPTS = C.IP_RETOPTS sysIP_PKTINFO = C.IP_PKTINFO sysIP_PKTOPTIONS = C.IP_PKTOPTIONS sysIP_MTU_DISCOVER = C.IP_MTU_DISCOVER sysIP_RECVERR = C.IP_RECVERR sysIP_RECVTTL = C.IP_RECVTTL sysIP_RECVTOS = C.IP_RECVTOS sysIP_MTU = C.IP_MTU sysIP_FREEBIND = C.IP_FREEBIND sysIP_TRANSPARENT = C.IP_TRANSPARENT sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_ORIGDSTADDR = C.IP_ORIGDSTADDR sysIP_RECVORIGDSTADDR = C.IP_RECVORIGDSTADDR sysIP_MINTTL = C.IP_MINTTL sysIP_NODEFRAG = C.IP_NODEFRAG sysIP_UNICAST_IF = C.IP_UNICAST_IF sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysIP_MSFILTER = C.IP_MSFILTER sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysMCAST_MSFILTER = C.MCAST_MSFILTER sysIP_MULTICAST_ALL = C.IP_MULTICAST_ALL //sysIP_PMTUDISC_DONT = C.IP_PMTUDISC_DONT //sysIP_PMTUDISC_WANT = C.IP_PMTUDISC_WANT //sysIP_PMTUDISC_DO = C.IP_PMTUDISC_DO //sysIP_PMTUDISC_PROBE = C.IP_PMTUDISC_PROBE //sysIP_PMTUDISC_INTERFACE = C.IP_PMTUDISC_INTERFACE //sysIP_PMTUDISC_OMIT = C.IP_PMTUDISC_OMIT sysICMP_FILTER = C.ICMP_FILTER sysSO_EE_ORIGIN_NONE = C.SO_EE_ORIGIN_NONE sysSO_EE_ORIGIN_LOCAL = C.SO_EE_ORIGIN_LOCAL sysSO_EE_ORIGIN_ICMP = C.SO_EE_ORIGIN_ICMP sysSO_EE_ORIGIN_ICMP6 = C.SO_EE_ORIGIN_ICMP6 sysSO_EE_ORIGIN_TXSTATUS = C.SO_EE_ORIGIN_TXSTATUS sysSO_EE_ORIGIN_TIMESTAMPING = C.SO_EE_ORIGIN_TIMESTAMPING sysSizeofKernelSockaddrStorage = C.sizeof_struct___kernel_sockaddr_storage sysSizeofSockaddrInet = C.sizeof_struct_sockaddr_in sysSizeofInetPktinfo = C.sizeof_struct_in_pktinfo sysSizeofSockExtendedErr = C.sizeof_struct_sock_extended_err sysSizeofIPMreq = C.sizeof_struct_ip_mreq sysSizeofIPMreqn = C.sizeof_struct_ip_mreqn sysSizeofIPMreqSource = C.sizeof_struct_ip_mreq_source sysSizeofGroupReq = C.sizeof_struct_group_req sysSizeofGroupSourceReq = C.sizeof_struct_group_source_req sysSizeofICMPFilter = C.sizeof_struct_icmp_filter ) type sysKernelSockaddrStorage C.struct___kernel_sockaddr_storage type sysSockaddrInet C.struct_sockaddr_in type sysInetPktinfo C.struct_in_pktinfo type sysSockExtendedErr C.struct_sock_extended_err type sysIPMreq C.struct_ip_mreq type sysIPMreqn C.struct_ip_mreqn type sysIPMreqSource C.struct_ip_mreq_source type sysGroupReq C.struct_group_req type sysGroupSourceReq C.struct_group_source_req type sysICMPFilter C.struct_icmp_filter ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_netbsd.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysSizeofIPMreq = C.sizeof_struct_ip_mreq ) type sysIPMreq C.struct_ip_mreq ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_openbsd.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVTTL = C.IP_RECVTTL sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysSizeofIPMreq = C.sizeof_struct_ip_mreq ) type sysIPMreq C.struct_ip_mreq ================================================ FILE: vendor/golang.org/x/net/ipv4/defs_solaris.go ================================================ // 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 ignore // +godefs map struct_in_addr [4]byte /* in_addr */ package ipv4 /* #include */ import "C" const ( sysIP_OPTIONS = C.IP_OPTIONS sysIP_HDRINCL = C.IP_HDRINCL sysIP_TOS = C.IP_TOS sysIP_TTL = C.IP_TTL sysIP_RECVOPTS = C.IP_RECVOPTS sysIP_RECVRETOPTS = C.IP_RECVRETOPTS sysIP_RECVDSTADDR = C.IP_RECVDSTADDR sysIP_RETOPTS = C.IP_RETOPTS sysIP_RECVIF = C.IP_RECVIF sysIP_RECVSLLA = C.IP_RECVSLLA sysIP_RECVTTL = C.IP_RECVTTL sysIP_NEXTHOP = C.IP_NEXTHOP sysIP_PKTINFO = C.IP_PKTINFO sysIP_RECVPKTINFO = C.IP_RECVPKTINFO sysIP_DONTFRAG = C.IP_DONTFRAG sysIP_BOUND_IF = C.IP_BOUND_IF sysIP_UNSPEC_SRC = C.IP_UNSPEC_SRC sysIP_BROADCAST_TTL = C.IP_BROADCAST_TTL sysIP_DHCPINIT_IF = C.IP_DHCPINIT_IF sysIP_MULTICAST_IF = C.IP_MULTICAST_IF sysIP_MULTICAST_TTL = C.IP_MULTICAST_TTL sysIP_MULTICAST_LOOP = C.IP_MULTICAST_LOOP sysIP_ADD_MEMBERSHIP = C.IP_ADD_MEMBERSHIP sysIP_DROP_MEMBERSHIP = C.IP_DROP_MEMBERSHIP sysIP_BLOCK_SOURCE = C.IP_BLOCK_SOURCE sysIP_UNBLOCK_SOURCE = C.IP_UNBLOCK_SOURCE sysIP_ADD_SOURCE_MEMBERSHIP = C.IP_ADD_SOURCE_MEMBERSHIP sysIP_DROP_SOURCE_MEMBERSHIP = C.IP_DROP_SOURCE_MEMBERSHIP sysSizeofInetPktinfo = C.sizeof_struct_in_pktinfo sysSizeofIPMreq = C.sizeof_struct_ip_mreq sysSizeofIPMreqSource = C.sizeof_struct_ip_mreq_source ) type sysInetPktinfo C.struct_in_pktinfo type sysIPMreq C.struct_ip_mreq type sysIPMreqSource C.struct_ip_mreq_source ================================================ FILE: vendor/golang.org/x/net/ipv4/dgramopt_posix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd windows package ipv4 import ( "net" "syscall" ) // MulticastTTL returns the time-to-live field value for outgoing // multicast packets. func (c *dgramOpt) MulticastTTL() (int, error) { if !c.ok() { return 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return 0, err } return getInt(fd, &sockOpts[ssoMulticastTTL]) } // SetMulticastTTL sets the time-to-live field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastTTL(ttl int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoMulticastTTL], ttl) } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { if !c.ok() { return nil, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return nil, err } return getInterface(fd, &sockOpts[ssoMulticastInterface]) } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInterface(fd, &sockOpts[ssoMulticastInterface], ifi) } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { if !c.ok() { return false, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return false, err } on, err := getInt(fd, &sockOpts[ssoMulticastLoopback]) if err != nil { return false, err } return on == 1, nil } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoMulticastLoopback], boolint(on)) } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } return setGroup(fd, &sockOpts[ssoJoinGroup], ifi, grp) } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } return setGroup(fd, &sockOpts[ssoLeaveGroup], ifi, grp) } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoJoinSourceGroup], ifi, grp, src) } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoLeaveSourceGroup], ifi, grp, src) } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoBlockSourceGroup], ifi, grp, src) } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP4(group) if grp == nil { return errMissingAddress } src := netAddrToIP4(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoUnblockSourceGroup], ifi, grp, src) } // ICMPFilter returns an ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { if !c.ok() { return nil, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return nil, err } return getICMPFilter(fd, &sockOpts[ssoICMPFilter]) } // SetICMPFilter deploys the ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setICMPFilter(fd, &sockOpts[ssoICMPFilter], f) } ================================================ FILE: vendor/golang.org/x/net/ipv4/dgramopt_stub.go ================================================ // 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 nacl plan9 solaris package ipv4 import "net" // MulticastTTL returns the time-to-live field value for outgoing // multicast packets. func (c *dgramOpt) MulticastTTL() (int, error) { return 0, errOpNoSupport } // SetMulticastTTL sets the time-to-live field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastTTL(ttl int) error { return errOpNoSupport } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { return nil, errOpNoSupport } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { return errOpNoSupport } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { return false, errOpNoSupport } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { return errOpNoSupport } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { return errOpNoSupport } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { return errOpNoSupport } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // ICMPFilter returns an ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { return nil, errOpNoSupport } // SetICMPFilter deploys the ICMP filter. // Currently only Linux supports this. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/doc.go ================================================ // 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 ipv4 implements IP-level socket options for the Internet // Protocol version 4. // // The package provides IP-level socket options that allow // manipulation of IPv4 facilities. // // The IPv4 protocol and basic host requirements for IPv4 are defined // in RFC 791 and RFC 1122. // Host extensions for multicasting and socket interface extensions // for multicast source filters are defined in RFC 1112 and RFC 3678. // IGMPv1, IGMPv2 and IGMPv3 are defined in RFC 1112, RFC 2236 and RFC // 3376. // Source-specific multicast is defined in RFC 4607. // // // Unicasting // // The options for unicasting are available for net.TCPConn, // net.UDPConn and net.IPConn which are created as network connections // that use the IPv4 transport. When a single TCP connection carrying // a data flow of multiple packets needs to indicate the flow is // important, ipv4.Conn is used to set the type-of-service field on // the IPv4 header for each packet. // // ln, err := net.Listen("tcp4", "0.0.0.0:1024") // if err != nil { // // error handling // } // defer ln.Close() // for { // c, err := ln.Accept() // if err != nil { // // error handling // } // go func(c net.Conn) { // defer c.Close() // // The outgoing packets will be labeled DiffServ assured forwarding // class 1 low drop precedence, known as AF11 packets. // // if err := ipv4.NewConn(c).SetTOS(0x28); err != nil { // // error handling // } // if _, err := c.Write(data); err != nil { // // error handling // } // }(c) // } // // // Multicasting // // The options for multicasting are available for net.UDPConn and // net.IPconn which are created as network connections that use the // IPv4 transport. A few network facilities must be prepared before // you begin multicasting, at a minimum joining network interfaces and // multicast groups. // // en0, err := net.InterfaceByName("en0") // if err != nil { // // error handling // } // en1, err := net.InterfaceByIndex(911) // if err != nil { // // error handling // } // group := net.IPv4(224, 0, 0, 250) // // First, an application listens to an appropriate address with an // appropriate service port. // // c, err := net.ListenPacket("udp4", "0.0.0.0:1024") // if err != nil { // // error handling // } // defer c.Close() // // Second, the application joins multicast groups, starts listening to // the groups on the specified network interfaces. Note that the // service port for transport layer protocol does not matter with this // operation as joining groups affects only network and link layer // protocols, such as IPv4 and Ethernet. // // p := ipv4.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // // The application might set per packet control message transmissions // between the protocol stack within the kernel. When the application // needs a destination address on an incoming packet, // SetControlMessage of ipv4.PacketConn is used to enable control // message transmissons. // // if err := p.SetControlMessage(ipv4.FlagDst, true); err != nil { // // error handling // } // // The application could identify whether the received packets are // of interest by using the control message that contains the // destination address of the received packet. // // b := make([]byte, 1500) // for { // n, cm, src, err := p.ReadFrom(b) // if err != nil { // // error handling // } // if cm.Dst.IsMulticast() { // if cm.Dst.Equal(group) { // // joined group, do something // } else { // // unknown group, discard // continue // } // } // // The application can also send both unicast and multicast packets. // // p.SetTOS(0x0) // p.SetTTL(16) // if _, err := p.WriteTo(data, nil, src); err != nil { // // error handling // } // dst := &net.UDPAddr{IP: group, Port: 1024} // for _, ifi := range []*net.Interface{en0, en1} { // if err := p.SetMulticastInterface(ifi); err != nil { // // error handling // } // p.SetMulticastTTL(2) // if _, err := p.WriteTo(data, nil, dst); err != nil { // // error handling // } // } // } // // // More multicasting // // An application that uses PacketConn or RawConn may join multiple // multicast groups. For example, a UDP listener with port 1024 might // join two different groups across over two different network // interfaces by using: // // c, err := net.ListenPacket("udp4", "0.0.0.0:1024") // if err != nil { // // error handling // } // defer c.Close() // p := ipv4.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}); err != nil { // // error handling // } // // It is possible for multiple UDP listeners that listen on the same // UDP port to join the same multicast group. The net package will // provide a socket that listens to a wildcard address with reusable // UDP port when an appropriate multicast address prefix is passed to // the net.ListenPacket or net.ListenUDP. // // c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // if err != nil { // // error handling // } // defer c1.Close() // c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // if err != nil { // // error handling // } // defer c2.Close() // p1 := ipv4.NewPacketConn(c1) // if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // p2 := ipv4.NewPacketConn(c2) // if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // // Also it is possible for the application to leave or rejoin a // multicast group on the network interface. // // if err := p.LeaveGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 248)}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 250)}); err != nil { // // error handling // } // // // Source-specific multicasting // // An application that uses PacketConn or RawConn on IGMPv3 supported // platform is able to join source-specific multicast groups. // The application may use JoinSourceSpecificGroup and // LeaveSourceSpecificGroup for the operation known as "include" mode, // // ssmgroup := net.UDPAddr{IP: net.IPv4(232, 7, 8, 9)} // ssmsource := net.UDPAddr{IP: net.IPv4(192, 168, 0, 1)}) // if err := p.JoinSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // if err := p.LeaveSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // // or JoinGroup, ExcludeSourceSpecificGroup, // IncludeSourceSpecificGroup and LeaveGroup for the operation known // as "exclude" mode. // // exclsource := net.UDPAddr{IP: net.IPv4(192, 168, 0, 254)} // if err := p.JoinGroup(en0, &ssmgroup); err != nil { // // error handling // } // if err := p.ExcludeSourceSpecificGroup(en0, &ssmgroup, &exclsource); err != nil { // // error handling // } // if err := p.LeaveGroup(en0, &ssmgroup); err != nil { // // error handling // } // // Note that it depends on each platform implementation what happens // when an application which runs on IGMPv3 unsupported platform uses // JoinSourceSpecificGroup and LeaveSourceSpecificGroup. // In general the platform tries to fall back to conversations using // IGMPv1 or IGMPv2 and starts to listen to multicast traffic. // In the fallback case, ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup may return an error. package ipv4 // import "golang.org/x/net/ipv4" ================================================ FILE: vendor/golang.org/x/net/ipv4/endpoint.go ================================================ // 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 ipv4 import ( "net" "syscall" "time" ) // A Conn represents a network endpoint that uses the IPv4 transport. // It is used to control basic IP-level socket options such as TOS and // TTL. type Conn struct { genericOpt } type genericOpt struct { net.Conn } func (c *genericOpt) ok() bool { return c != nil && c.Conn != nil } // NewConn returns a new Conn. func NewConn(c net.Conn) *Conn { return &Conn{ genericOpt: genericOpt{Conn: c}, } } // A PacketConn represents a packet network endpoint that uses the // IPv4 transport. It is used to control several IP-level socket // options including multicasting. It also provides datagram based // network I/O methods specific to the IPv4 and higher layer protocols // such as UDP. type PacketConn struct { genericOpt dgramOpt payloadHandler } type dgramOpt struct { net.PacketConn } func (c *dgramOpt) ok() bool { return c != nil && c.PacketConn != nil } // SetControlMessage sets the per packet IP-level socket options. func (c *PacketConn) SetControlMessage(cf ControlFlags, on bool) error { if !c.payloadHandler.ok() { return syscall.EINVAL } fd, err := c.payloadHandler.sysfd() if err != nil { return err } return setControlMessage(fd, &c.payloadHandler.rawOpt, cf, on) } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.SetWriteDeadline(t) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.PacketConn.Close() } // NewPacketConn returns a new PacketConn using c as its underlying // transport. func NewPacketConn(c net.PacketConn) *PacketConn { p := &PacketConn{ genericOpt: genericOpt{Conn: c.(net.Conn)}, dgramOpt: dgramOpt{PacketConn: c}, payloadHandler: payloadHandler{PacketConn: c}, } if _, ok := c.(*net.IPConn); ok && sockOpts[ssoStripHeader].name > 0 { if fd, err := p.payloadHandler.sysfd(); err == nil { setInt(fd, &sockOpts[ssoStripHeader], boolint(true)) } } return p } // A RawConn represents a packet network endpoint that uses the IPv4 // transport. It is used to control several IP-level socket options // including IPv4 header manipulation. It also provides datagram // based network I/O methods specific to the IPv4 and higher layer // protocols that handle IPv4 datagram directly such as OSPF, GRE. type RawConn struct { genericOpt dgramOpt packetHandler } // SetControlMessage sets the per packet IP-level socket options. func (c *RawConn) SetControlMessage(cf ControlFlags, on bool) error { if !c.packetHandler.ok() { return syscall.EINVAL } fd, err := c.packetHandler.sysfd() if err != nil { return err } return setControlMessage(fd, &c.packetHandler.rawOpt, cf, on) } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *RawConn) SetDeadline(t time.Time) error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.c.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *RawConn) SetReadDeadline(t time.Time) error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.c.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *RawConn) SetWriteDeadline(t time.Time) error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.c.SetWriteDeadline(t) } // Close closes the endpoint. func (c *RawConn) Close() error { if !c.packetHandler.ok() { return syscall.EINVAL } return c.packetHandler.c.Close() } // NewRawConn returns a new RawConn using c as its underlying // transport. func NewRawConn(c net.PacketConn) (*RawConn, error) { r := &RawConn{ genericOpt: genericOpt{Conn: c.(net.Conn)}, dgramOpt: dgramOpt{PacketConn: c}, packetHandler: packetHandler{c: c.(*net.IPConn)}, } fd, err := r.packetHandler.sysfd() if err != nil { return nil, err } if err := setInt(fd, &sockOpts[ssoHeaderPrepend], boolint(true)); err != nil { return nil, err } return r, nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/example_test.go ================================================ // 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 ipv4_test import ( "fmt" "log" "net" "os" "runtime" "time" "golang.org/x/net/icmp" "golang.org/x/net/ipv4" ) func ExampleConn_markingTCP() { ln, err := net.Listen("tcp4", "0.0.0.0:1024") if err != nil { log.Fatal(err) } defer ln.Close() for { c, err := ln.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { defer c.Close() p := ipv4.NewConn(c) if err := p.SetTOS(0x28); err != nil { // DSCP AF11 log.Fatal(err) } if err := p.SetTTL(128); err != nil { log.Fatal(err) } if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil { log.Fatal(err) } }(c) } } func ExamplePacketConn_servingOneShotMulticastDNS() { c, err := net.ListenPacket("udp4", "0.0.0.0:5353") // mDNS over UDP if err != nil { log.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } mDNSLinkLocal := net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)} if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil { log.Fatal(err) } defer p.LeaveGroup(en0, &mDNSLinkLocal) if err := p.SetControlMessage(ipv4.FlagDst, true); err != nil { log.Fatal(err) } b := make([]byte, 1500) for { _, cm, peer, err := p.ReadFrom(b) if err != nil { log.Fatal(err) } if !cm.Dst.IsMulticast() || !cm.Dst.Equal(mDNSLinkLocal.IP) { continue } answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this if _, err := p.WriteTo(answers, nil, peer); err != nil { log.Fatal(err) } } } func ExamplePacketConn_tracingIPPacketRoute() { // Tracing an IP packet route to www.google.com. const host = "www.google.com" ips, err := net.LookupIP(host) if err != nil { log.Fatal(err) } var dst net.IPAddr for _, ip := range ips { if ip.To4() != nil { dst.IP = ip fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host) break } } if dst.IP == nil { log.Fatal("no A record found") } c, err := net.ListenPacket("ip4:1", "0.0.0.0") // ICMP for IPv4 if err != nil { log.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) if err := p.SetControlMessage(ipv4.FlagTTL|ipv4.FlagSrc|ipv4.FlagDst|ipv4.FlagInterface, true); err != nil { log.Fatal(err) } wm := icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Data: []byte("HELLO-R-U-THERE"), }, } rb := make([]byte, 1500) for i := 1; i <= 64; i++ { // up to 64 hops wm.Body.(*icmp.Echo).Seq = i wb, err := wm.Marshal(nil) if err != nil { log.Fatal(err) } if err := p.SetTTL(i); err != nil { log.Fatal(err) } // In the real world usually there are several // multiple traffic-engineered paths for each hop. // You may need to probe a few times to each hop. begin := time.Now() if _, err := p.WriteTo(wb, nil, &dst); err != nil { log.Fatal(err) } if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { log.Fatal(err) } n, cm, peer, err := p.ReadFrom(rb) if err != nil { if err, ok := err.(net.Error); ok && err.Timeout() { fmt.Printf("%v\t*\n", i) continue } log.Fatal(err) } rm, err := icmp.ParseMessage(1, rb[:n]) if err != nil { log.Fatal(err) } rtt := time.Since(begin) // In the real world you need to determine whether the // received message is yours using ControlMessage.Src, // ControlMessage.Dst, icmp.Echo.ID and icmp.Echo.Seq. switch rm.Type { case ipv4.ICMPTypeTimeExceeded: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm) case ipv4.ICMPTypeEchoReply: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, cm) return default: log.Printf("unknown ICMP message: %+v\n", rm) } } } func ExampleRawConn_advertisingOSPFHello() { c, err := net.ListenPacket("ip4:89", "0.0.0.0") // OSPF for IPv4 if err != nil { log.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { log.Fatal(err) } en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } allSPFRouters := net.IPAddr{IP: net.IPv4(224, 0, 0, 5)} if err := r.JoinGroup(en0, &allSPFRouters); err != nil { log.Fatal(err) } defer r.LeaveGroup(en0, &allSPFRouters) hello := make([]byte, 24) // fake hello data, you need to implement this ospf := make([]byte, 24) // fake ospf header, you need to implement this ospf[0] = 2 // version 2 ospf[1] = 1 // hello packet ospf = append(ospf, hello...) iph := &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: 0xc0, // DSCP CS6 TotalLen: ipv4.HeaderLen + len(ospf), TTL: 1, Protocol: 89, Dst: allSPFRouters.IP.To4(), } var cm *ipv4.ControlMessage switch runtime.GOOS { case "darwin", "linux": cm = &ipv4.ControlMessage{IfIndex: en0.Index} default: if err := r.SetMulticastInterface(en0); err != nil { log.Fatal(err) } } if err := r.WriteTo(iph, ospf, cm); err != nil { log.Fatal(err) } } ================================================ FILE: vendor/golang.org/x/net/ipv4/gen.go ================================================ // 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 ignore //go:generate go run gen.go // This program generates system adaptation constants and types, // internet protocol constants and tables by reading template files // and IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "os/exec" "runtime" "strconv" "strings" ) func main() { if err := genzsys(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := geniana(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func genzsys() error { defs := "defs_" + runtime.GOOS + ".go" f, err := os.Open(defs) if err != nil { if os.IsNotExist(err) { return nil } return err } f.Close() cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) b, err := cmd.Output() if err != nil { return err } // The ipv4 pacakge still supports go1.2, and so we need to // take care of additional platforms in go1.3 and above for // working with go1.2. switch { case runtime.GOOS == "dragonfly" || runtime.GOOS == "solaris": b = bytes.Replace(b, []byte("package ipv4\n"), []byte("// +build "+runtime.GOOS+"\n\npackage ipv4\n"), 1) case runtime.GOOS == "linux" && (runtime.GOARCH == "arm64" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le"): b = bytes.Replace(b, []byte("package ipv4\n"), []byte("// +build "+runtime.GOOS+","+runtime.GOARCH+"\n\npackage ipv4\n"), 1) } b, err = format.Source(b) if err != nil { return err } zsys := "zsys_" + runtime.GOOS + ".go" switch runtime.GOOS { case "freebsd", "linux": zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" } if err := ioutil.WriteFile(zsys, b, 0644); err != nil { return err } return nil } var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/icmp-parameters/icmp-parameters.xml", parseICMPv4Parameters, }, } func geniana() error { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "package ipv4\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) } if err := r.parse(&bb, resp.Body); err != nil { return err } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { return err } if err := ioutil.WriteFile("iana.go", b, 0644); err != nil { return err } return nil } func parseICMPv4Parameters(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var icp icmpv4Parameters if err := dec.Decode(&icp); err != nil { return err } prs := icp.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Descr == "" { continue } fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Descr, pr.Value) fmt.Fprintf(w, "// %s\n", pr.OrigDescr) } fmt.Fprintf(w, ")\n\n") fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") for _, pr := range prs { if pr.Descr == "" { continue } fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigDescr)) } fmt.Fprintf(w, "}\n") return nil } type icmpv4Parameters struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Registries []struct { Title string `xml:"title"` Records []struct { Value string `xml:"value"` Descr string `xml:"description"` } `xml:"record"` } `xml:"registry"` } type canonICMPv4ParamRecord struct { OrigDescr string Descr string Value int } func (icp *icmpv4Parameters) escape() []canonICMPv4ParamRecord { id := -1 for i, r := range icp.Registries { if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { id = i break } } if id < 0 { return nil } prs := make([]canonICMPv4ParamRecord, len(icp.Registries[id].Records)) sr := strings.NewReplacer( "Messages", "", "Message", "", "ICMP", "", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range icp.Registries[id].Records { if strings.Contains(pr.Descr, "Reserved") || strings.Contains(pr.Descr, "Unassigned") || strings.Contains(pr.Descr, "Deprecated") || strings.Contains(pr.Descr, "Experiment") || strings.Contains(pr.Descr, "experiment") { continue } ss := strings.Split(pr.Descr, "\n") if len(ss) > 1 { prs[i].Descr = strings.Join(ss, " ") } else { prs[i].Descr = ss[0] } s := strings.TrimSpace(prs[i].Descr) prs[i].OrigDescr = s prs[i].Descr = sr.Replace(s) prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } ================================================ FILE: vendor/golang.org/x/net/ipv4/genericopt_posix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd windows package ipv4 import "syscall" // TOS returns the type-of-service field value for outgoing packets. func (c *genericOpt) TOS() (int, error) { if !c.ok() { return 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return 0, err } return getInt(fd, &sockOpts[ssoTOS]) } // SetTOS sets the type-of-service field value for future outgoing // packets. func (c *genericOpt) SetTOS(tos int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoTOS], tos) } // TTL returns the time-to-live field value for outgoing packets. func (c *genericOpt) TTL() (int, error) { if !c.ok() { return 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return 0, err } return getInt(fd, &sockOpts[ssoTTL]) } // SetTTL sets the time-to-live field value for future outgoing // packets. func (c *genericOpt) SetTTL(ttl int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoTTL], ttl) } ================================================ FILE: vendor/golang.org/x/net/ipv4/genericopt_stub.go ================================================ // 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 nacl plan9 solaris package ipv4 // TOS returns the type-of-service field value for outgoing packets. func (c *genericOpt) TOS() (int, error) { return 0, errOpNoSupport } // SetTOS sets the type-of-service field value for future outgoing // packets. func (c *genericOpt) SetTOS(tos int) error { return errOpNoSupport } // TTL returns the time-to-live field value for outgoing packets. func (c *genericOpt) TTL() (int, error) { return 0, errOpNoSupport } // SetTTL sets the time-to-live field value for future outgoing // packets. func (c *genericOpt) SetTTL(ttl int) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/header.go ================================================ // 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 ipv4 import ( "errors" "fmt" "net" "runtime" "syscall" "unsafe" ) var ( errMissingAddress = errors.New("missing address") errMissingHeader = errors.New("missing header") errHeaderTooShort = errors.New("header too short") errBufferTooShort = errors.New("buffer too short") errInvalidConnType = errors.New("invalid conn type") ) const ( Version = 4 // protocol version HeaderLen = 20 // header length without extension headers maxHeaderLen = 60 // sensible default, revisit if later RFCs define new usage of version and header length fields ) type HeaderFlags int const ( MoreFragments HeaderFlags = 1 << iota // more fragments flag DontFragment // don't fragment flag ) // A Header represents an IPv4 header. type Header struct { Version int // protocol version Len int // header length TOS int // type-of-service TotalLen int // packet total length ID int // identification Flags HeaderFlags // flags FragOff int // fragment offset TTL int // time-to-live Protocol int // next protocol Checksum int // checksum Src net.IP // source address Dst net.IP // destination address Options []byte // options, extension headers } func (h *Header) String() string { if h == nil { return "" } return fmt.Sprintf("ver: %v, hdrlen: %v, tos: %#x, totallen: %v, id: %#x, flags: %#x, fragoff: %#x, ttl: %v, proto: %v, cksum: %#x, src: %v, dst: %v", h.Version, h.Len, h.TOS, h.TotalLen, h.ID, h.Flags, h.FragOff, h.TTL, h.Protocol, h.Checksum, h.Src, h.Dst) } // Marshal returns the binary encoding of the IPv4 header h. func (h *Header) Marshal() ([]byte, error) { if h == nil { return nil, syscall.EINVAL } if h.Len < HeaderLen { return nil, errHeaderTooShort } hdrlen := HeaderLen + len(h.Options) b := make([]byte, hdrlen) b[0] = byte(Version<<4 | (hdrlen >> 2 & 0x0f)) b[1] = byte(h.TOS) flagsAndFragOff := (h.FragOff & 0x1fff) | int(h.Flags<<13) switch runtime.GOOS { case "darwin", "dragonfly", "freebsd", "netbsd": // TODO(mikio): fix potential misaligned memory access *(*uint16)(unsafe.Pointer(&b[2:3][0])) = uint16(h.TotalLen) *(*uint16)(unsafe.Pointer(&b[6:7][0])) = uint16(flagsAndFragOff) default: b[2], b[3] = byte(h.TotalLen>>8), byte(h.TotalLen) b[6], b[7] = byte(flagsAndFragOff>>8), byte(flagsAndFragOff) } b[4], b[5] = byte(h.ID>>8), byte(h.ID) b[8] = byte(h.TTL) b[9] = byte(h.Protocol) b[10], b[11] = byte(h.Checksum>>8), byte(h.Checksum) if ip := h.Src.To4(); ip != nil { copy(b[12:16], ip[:net.IPv4len]) } if ip := h.Dst.To4(); ip != nil { copy(b[16:20], ip[:net.IPv4len]) } else { return nil, errMissingAddress } if len(h.Options) > 0 { copy(b[HeaderLen:], h.Options) } return b, nil } // See http://www.freebsd.org/doc/en/books/porters-handbook/freebsd-versions.html. var freebsdVersion uint32 // ParseHeader parses b as an IPv4 header. func ParseHeader(b []byte) (*Header, error) { if len(b) < HeaderLen { return nil, errHeaderTooShort } hdrlen := int(b[0]&0x0f) << 2 if hdrlen > len(b) { return nil, errBufferTooShort } h := &Header{ Version: int(b[0] >> 4), Len: hdrlen, TOS: int(b[1]), ID: int(b[4])<<8 | int(b[5]), TTL: int(b[8]), Protocol: int(b[9]), Checksum: int(b[10])<<8 | int(b[11]), Src: net.IPv4(b[12], b[13], b[14], b[15]), Dst: net.IPv4(b[16], b[17], b[18], b[19]), } switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": // TODO(mikio): fix potential misaligned memory access h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[2:3][0]))) + hdrlen // TODO(mikio): fix potential misaligned memory access h.FragOff = int(*(*uint16)(unsafe.Pointer(&b[6:7][0]))) case "freebsd": // TODO(mikio): fix potential misaligned memory access h.TotalLen = int(*(*uint16)(unsafe.Pointer(&b[2:3][0]))) if freebsdVersion < 1000000 { h.TotalLen += hdrlen } // TODO(mikio): fix potential misaligned memory access h.FragOff = int(*(*uint16)(unsafe.Pointer(&b[6:7][0]))) default: h.TotalLen = int(b[2])<<8 | int(b[3]) h.FragOff = int(b[6])<<8 | int(b[7]) } h.Flags = HeaderFlags(h.FragOff&0xe000) >> 13 h.FragOff = h.FragOff & 0x1fff if hdrlen-HeaderLen > 0 { h.Options = make([]byte, hdrlen-HeaderLen) copy(h.Options, b[HeaderLen:]) } return h, nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/header_test.go ================================================ // 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 ipv4 import ( "bytes" "net" "reflect" "runtime" "testing" ) var ( wireHeaderFromKernel = [HeaderLen]byte{ 0x45, 0x01, 0xbe, 0xef, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } wireHeaderToKernel = [HeaderLen]byte{ 0x45, 0x01, 0xbe, 0xef, 0xca, 0xfe, 0x45, 0xdc, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } wireHeaderFromTradBSDKernel = [HeaderLen]byte{ 0x45, 0x01, 0xdb, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } wireHeaderFromFreeBSD10Kernel = [HeaderLen]byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } wireHeaderToTradBSDKernel = [HeaderLen]byte{ 0x45, 0x01, 0xef, 0xbe, 0xca, 0xfe, 0xdc, 0x45, 0xff, 0x01, 0xde, 0xad, 172, 16, 254, 254, 192, 168, 0, 1, } // TODO(mikio): Add platform dependent wire header formats when // we support new platforms. testHeader = &Header{ Version: Version, Len: HeaderLen, TOS: 1, TotalLen: 0xbeef, ID: 0xcafe, Flags: DontFragment, FragOff: 1500, TTL: 255, Protocol: 1, Checksum: 0xdead, Src: net.IPv4(172, 16, 254, 254), Dst: net.IPv4(192, 168, 0, 1), } ) func TestMarshalHeader(t *testing.T) { b, err := testHeader.Marshal() if err != nil { t.Fatal(err) } var wh []byte switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": wh = wireHeaderToTradBSDKernel[:] case "freebsd": if freebsdVersion < 1000000 { wh = wireHeaderToTradBSDKernel[:] } else { wh = wireHeaderFromFreeBSD10Kernel[:] } default: wh = wireHeaderToKernel[:] } if !bytes.Equal(b, wh) { t.Fatalf("got %#v; want %#v", b, wh) } } func TestParseHeader(t *testing.T) { var wh []byte switch runtime.GOOS { case "darwin", "dragonfly", "netbsd": wh = wireHeaderFromTradBSDKernel[:] case "freebsd": if freebsdVersion < 1000000 { wh = wireHeaderFromTradBSDKernel[:] } else { wh = wireHeaderFromFreeBSD10Kernel[:] } default: wh = wireHeaderFromKernel[:] } h, err := ParseHeader(wh) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(h, testHeader) { t.Fatalf("got %#v; want %#v", h, testHeader) } } ================================================ FILE: vendor/golang.org/x/net/ipv4/helper.go ================================================ // 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 ipv4 import ( "errors" "net" ) var ( errOpNoSupport = errors.New("operation not supported") errNoSuchInterface = errors.New("no such interface") errNoSuchMulticastInterface = errors.New("no such multicast interface") ) func boolint(b bool) int { if b { return 1 } return 0 } func netAddrToIP4(a net.Addr) net.IP { switch v := a.(type) { case *net.UDPAddr: if ip := v.IP.To4(); ip != nil { return ip } case *net.IPAddr: if ip := v.IP.To4(); ip != nil { return ip } } return nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/helper_stub.go ================================================ // 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 nacl plan9 solaris package ipv4 func (c *genericOpt) sysfd() (int, error) { return 0, errOpNoSupport } func (c *dgramOpt) sysfd() (int, error) { return 0, errOpNoSupport } func (c *payloadHandler) sysfd() (int, error) { return 0, errOpNoSupport } func (c *packetHandler) sysfd() (int, error) { return 0, errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/helper_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv4 import ( "net" "reflect" ) func (c *genericOpt) sysfd() (int, error) { switch p := c.Conn.(type) { case *net.TCPConn, *net.UDPConn, *net.IPConn: return sysfd(p) } return 0, errInvalidConnType } func (c *dgramOpt) sysfd() (int, error) { switch p := c.PacketConn.(type) { case *net.UDPConn, *net.IPConn: return sysfd(p.(net.Conn)) } return 0, errInvalidConnType } func (c *payloadHandler) sysfd() (int, error) { return sysfd(c.PacketConn.(net.Conn)) } func (c *packetHandler) sysfd() (int, error) { return sysfd(c.c) } func sysfd(c net.Conn) (int, error) { cv := reflect.ValueOf(c) switch ce := cv.Elem(); ce.Kind() { case reflect.Struct: netfd := ce.FieldByName("conn").FieldByName("fd") switch fe := netfd.Elem(); fe.Kind() { case reflect.Struct: fd := fe.FieldByName("sysfd") return int(fd.Int()), nil } } return 0, errInvalidConnType } ================================================ FILE: vendor/golang.org/x/net/ipv4/helper_windows.go ================================================ // 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 ipv4 import ( "net" "reflect" "syscall" ) func (c *genericOpt) sysfd() (syscall.Handle, error) { switch p := c.Conn.(type) { case *net.TCPConn, *net.UDPConn, *net.IPConn: return sysfd(p) } return syscall.InvalidHandle, errInvalidConnType } func (c *dgramOpt) sysfd() (syscall.Handle, error) { switch p := c.PacketConn.(type) { case *net.UDPConn, *net.IPConn: return sysfd(p.(net.Conn)) } return syscall.InvalidHandle, errInvalidConnType } func (c *payloadHandler) sysfd() (syscall.Handle, error) { return sysfd(c.PacketConn.(net.Conn)) } func (c *packetHandler) sysfd() (syscall.Handle, error) { return sysfd(c.c) } func sysfd(c net.Conn) (syscall.Handle, error) { cv := reflect.ValueOf(c) switch ce := cv.Elem(); ce.Kind() { case reflect.Struct: netfd := ce.FieldByName("conn").FieldByName("fd") switch fe := netfd.Elem(); fe.Kind() { case reflect.Struct: fd := fe.FieldByName("sysfd") return syscall.Handle(fd.Uint()), nil } } return syscall.InvalidHandle, errInvalidConnType } ================================================ FILE: vendor/golang.org/x/net/ipv4/iana.go ================================================ // go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package ipv4 // Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19 const ( ICMPTypeEchoReply ICMPType = 0 // Echo Reply ICMPTypeDestinationUnreachable ICMPType = 3 // Destination Unreachable ICMPTypeRedirect ICMPType = 5 // Redirect ICMPTypeEcho ICMPType = 8 // Echo ICMPTypeRouterAdvertisement ICMPType = 9 // Router Advertisement ICMPTypeRouterSolicitation ICMPType = 10 // Router Solicitation ICMPTypeTimeExceeded ICMPType = 11 // Time Exceeded ICMPTypeParameterProblem ICMPType = 12 // Parameter Problem ICMPTypeTimestamp ICMPType = 13 // Timestamp ICMPTypeTimestampReply ICMPType = 14 // Timestamp Reply ICMPTypePhoturis ICMPType = 40 // Photuris ) // Internet Control Message Protocol (ICMP) Parameters, Updated: 2013-04-19 var icmpTypes = map[ICMPType]string{ 0: "echo reply", 3: "destination unreachable", 5: "redirect", 8: "echo", 9: "router advertisement", 10: "router solicitation", 11: "time exceeded", 12: "parameter problem", 13: "timestamp", 14: "timestamp reply", 40: "photuris", } ================================================ FILE: vendor/golang.org/x/net/ipv4/icmp.go ================================================ // 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 ipv4 import "golang.org/x/net/internal/iana" // An ICMPType represents a type of ICMP message. type ICMPType int func (typ ICMPType) String() string { s, ok := icmpTypes[typ] if !ok { return "" } return s } // Protocol returns the ICMPv4 protocol number. func (typ ICMPType) Protocol() int { return iana.ProtocolICMP } // An ICMPFilter represents an ICMP message filter for incoming // packets. The filter belongs to a packet delivery path on a host and // it cannot interact with forwarding packets or tunnel-outer packets. // // Note: RFC 2460 defines a reasonable role model and it works not // only for IPv6 but IPv4. A node means a device that implements IP. // A router means a node that forwards IP packets not explicitly // addressed to itself, and a host means a node that is not a router. type ICMPFilter struct { sysICMPFilter } // Accept accepts incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Accept(typ ICMPType) { f.accept(typ) } // Block blocks incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Block(typ ICMPType) { f.block(typ) } // SetAll sets the filter action to the filter. func (f *ICMPFilter) SetAll(block bool) { f.setAll(block) } // WillBlock reports whether the ICMP type will be blocked. func (f *ICMPFilter) WillBlock(typ ICMPType) bool { return f.willBlock(typ) } ================================================ FILE: vendor/golang.org/x/net/ipv4/icmp_linux.go ================================================ // 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 ipv4 func (f *sysICMPFilter) accept(typ ICMPType) { f.Data &^= 1 << (uint32(typ) & 31) } func (f *sysICMPFilter) block(typ ICMPType) { f.Data |= 1 << (uint32(typ) & 31) } func (f *sysICMPFilter) setAll(block bool) { if block { f.Data = 1<<32 - 1 } else { f.Data = 0 } } func (f *sysICMPFilter) willBlock(typ ICMPType) bool { return f.Data&(1<<(uint32(typ)&31)) != 0 } ================================================ FILE: vendor/golang.org/x/net/ipv4/icmp_stub.go ================================================ // 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 package ipv4 const sysSizeofICMPFilter = 0x0 type sysICMPFilter struct { } func (f *sysICMPFilter) accept(typ ICMPType) { } func (f *sysICMPFilter) block(typ ICMPType) { } func (f *sysICMPFilter) setAll(block bool) { } func (f *sysICMPFilter) willBlock(typ ICMPType) bool { return false } ================================================ FILE: vendor/golang.org/x/net/ipv4/icmp_test.go ================================================ // 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 ipv4_test import ( "net" "reflect" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var icmpStringTests = []struct { in ipv4.ICMPType out string }{ {ipv4.ICMPTypeDestinationUnreachable, "destination unreachable"}, {256, ""}, } func TestICMPString(t *testing.T) { for _, tt := range icmpStringTests { s := tt.in.String() if s != tt.out { t.Errorf("got %s; want %s", s, tt.out) } } } func TestICMPFilter(t *testing.T) { switch runtime.GOOS { case "linux": default: t.Skipf("not supported on %s", runtime.GOOS) } var f ipv4.ICMPFilter for _, toggle := range []bool{false, true} { f.SetAll(toggle) for _, typ := range []ipv4.ICMPType{ ipv4.ICMPTypeDestinationUnreachable, ipv4.ICMPTypeEchoReply, ipv4.ICMPTypeTimeExceeded, ipv4.ICMPTypeParameterProblem, } { f.Accept(typ) if f.WillBlock(typ) { t.Errorf("ipv4.ICMPFilter.Set(%v, false) failed", typ) } f.Block(typ) if !f.WillBlock(typ) { t.Errorf("ipv4.ICMPFilter.Set(%v, true) failed", typ) } } } } func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "linux": default: t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) var f ipv4.ICMPFilter f.SetAll(true) f.Accept(ipv4.ICMPTypeEcho) f.Accept(ipv4.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } kf, err := p.ICMPFilter() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got %#v; want %#v", kf, f) } } ================================================ FILE: vendor/golang.org/x/net/ipv4/mocktransponder_test.go ================================================ // 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 ipv4_test import ( "net" "testing" ) func acceptor(t *testing.T, ln net.Listener, done chan<- bool) { defer func() { done <- true }() c, err := ln.Accept() if err != nil { t.Error(err) return } c.Close() } ================================================ FILE: vendor/golang.org/x/net/ipv4/multicast_test.go ================================================ // 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 ipv4_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var packetConnReadWriteMulticastUDPTests = []struct { addr string grp, src *net.UDPAddr }{ {"224.0.0.0:0", &net.UDPAddr{IP: net.IPv4(224, 0, 0, 254)}, nil}, // see RFC 4727 {"232.0.1.0:0", &net.UDPAddr{IP: net.IPv4(232, 0, 1, 254)}, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastUDPTests { c, err := net.ListenPacket("udp4", tt.addr) if err != nil { t.Fatal(err) } defer c.Close() grp := *tt.grp grp.Port = c.LocalAddr().(*net.UDPAddr).Port p := ipv4.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, &grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, &grp) } else { if err := p.JoinSourceSpecificGroup(ifi, &grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, &grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } p.SetMulticastTTL(i + 1) if n, err := p.WriteTo(wb, nil, &grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } else { t.Logf("rcvd cmsg: %v", cm) } } } } var packetConnReadWriteMulticastICMPTests = []struct { grp, src *net.IPAddr }{ {&net.IPAddr{IP: net.IPv4(224, 0, 0, 254)}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.IPv4(232, 0, 1, 254)}, &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastICMPTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, tt.grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, tt.grp) } else { if err := p.JoinSourceSpecificGroup(ifi, tt.grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, tt.grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } p.SetMulticastTTL(i + 1) if n, err := p.WriteTo(wb, nil, tt.grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else { t.Logf("rcvd cmsg: %v", cm) m, err := icmp.ParseMessage(iana.ProtocolICMP, rb[:n]) if err != nil { t.Fatal(err) } switch { case m.Type == ipv4.ICMPTypeEchoReply && m.Code == 0: // net.inet.icmp.bmcastecho=1 case m.Type == ipv4.ICMPTypeEcho && m.Code == 0: // net.inet.icmp.bmcastecho=0 default: t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } } var rawConnReadWriteMulticastICMPTests = []struct { grp, src *net.IPAddr }{ {&net.IPAddr{IP: net.IPv4(224, 0, 0, 254)}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.IPv4(232, 0, 1, 254)}, &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestRawConnReadWriteMulticastICMP(t *testing.T) { if testing.Short() { t.Skip("to avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range rawConnReadWriteMulticastICMPTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } defer r.Close() if tt.src == nil { if err := r.JoinGroup(ifi, tt.grp); err != nil { t.Fatal(err) } defer r.LeaveGroup(ifi, tt.grp) } else { if err := r.JoinSourceSpecificGroup(ifi, tt.grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer r.LeaveSourceSpecificGroup(ifi, tt.grp, tt.src) } if err := r.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := r.MulticastInterface(); err != nil { t.Fatal(err) } if err := r.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := r.MulticastLoopback(); err != nil { t.Fatal(err) } cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } wh := &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: i + 1, TotalLen: ipv4.HeaderLen + len(wb), Protocol: 1, Dst: tt.grp.IP, } if err := r.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := r.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } r.SetMulticastTTL(i + 1) if err := r.WriteTo(wh, wb, nil); err != nil { t.Fatal(err) } rb := make([]byte, ipv4.HeaderLen+128) if rh, b, cm, err := r.ReadFrom(rb); err != nil { t.Fatal(err) } else { t.Logf("rcvd cmsg: %v", cm) m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } switch { case (rh.Dst.IsLoopback() || rh.Dst.IsLinkLocalUnicast() || rh.Dst.IsGlobalUnicast()) && m.Type == ipv4.ICMPTypeEchoReply && m.Code == 0: // net.inet.icmp.bmcastecho=1 case rh.Dst.IsMulticast() && m.Type == ipv4.ICMPTypeEcho && m.Code == 0: // net.inet.icmp.bmcastecho=0 default: t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } } ================================================ FILE: vendor/golang.org/x/net/ipv4/multicastlistener_test.go ================================================ // 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 ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var udpMultipleGroupListenerTests = []net.Addr{ &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}, // see RFC 4727 &net.UDPAddr{IP: net.IPv4(224, 0, 0, 250)}, &net.UDPAddr{IP: net.IPv4(224, 0, 0, 254)}, } func TestUDPSinglePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c, err := net.ListenPacket("udp4", "0.0.0.0:0") // wildcard address with no reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp4", "224.0.0.0:1024") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c1.Close() c2, err := net.ListenPacket("udp4", "224.0.0.0:1024") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c2.Close() var ps [2]*ipv4.PacketConn ps[0] = ipv4.NewPacketConn(c1) ps[1] = ipv4.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } } func TestUDPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 type ml struct { c *ipv4.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip4", &ifi) if !ok { continue } c, err := net.ListenPacket("udp4", ip.String()+":"+"1024") // unicast address with non-reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPSingleRawConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") // wildcard address if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip4", &ifi); !ok { continue } if err := r.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := r.LeaveGroup(ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPPerInterfaceSingleRawConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if testing.Short() { t.Skip("to avoid external network") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } gaddr := net.IPAddr{IP: net.IPv4(224, 0, 0, 254)} // see RFC 4727 type ml struct { c *ipv4.RawConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip4", &ifi) if !ok { continue } c, err := net.ListenPacket("ip4:253", ip.String()) // unicast address if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } if err := r.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{r, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } ================================================ FILE: vendor/golang.org/x/net/ipv4/multicastsockopt_test.go ================================================ // 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 ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) var packetConnMulticastSocketOptionTests = []struct { net, proto, addr string grp, src net.Addr }{ {"udp4", "", "224.0.0.0:0", &net.UDPAddr{IP: net.IPv4(224, 0, 0, 249)}, nil}, // see RFC 4727 {"ip4", ":icmp", "0.0.0.0", &net.IPAddr{IP: net.IPv4(224, 0, 0, 250)}, nil}, // see RFC 4727 {"udp4", "", "232.0.0.0:0", &net.UDPAddr{IP: net.IPv4(232, 0, 1, 249)}, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 {"ip4", ":icmp", "0.0.0.0", &net.IPAddr{IP: net.IPv4(232, 0, 1, 250)}, &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestPacketConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnMulticastSocketOptionTests { if tt.net == "ip4" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() if tt.src == nil { testMulticastSocketOptions(t, p, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, p, ifi, tt.grp, tt.src) } } } var rawConnMulticastSocketOptionTests = []struct { grp, src net.Addr }{ {&net.IPAddr{IP: net.IPv4(224, 0, 0, 250)}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.IPv4(232, 0, 1, 250)}, &net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}}, // see RFC 5771 } func TestRawConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range rawConnMulticastSocketOptionTests { c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } defer r.Close() if tt.src == nil { testMulticastSocketOptions(t, r, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, r, ifi, tt.grp, tt.src) } } } type testIPv4MulticastConn interface { MulticastTTL() (int, error) SetMulticastTTL(ttl int) error MulticastLoopback() (bool, error) SetMulticastLoopback(bool) error JoinGroup(*net.Interface, net.Addr) error LeaveGroup(*net.Interface, net.Addr) error JoinSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error LeaveSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error ExcludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error IncludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error } func testMulticastSocketOptions(t *testing.T, c testIPv4MulticastConn, ifi *net.Interface, grp net.Addr) { const ttl = 255 if err := c.SetMulticastTTL(ttl); err != nil { t.Error(err) return } if v, err := c.MulticastTTL(); err != nil { t.Error(err) return } else if v != ttl { t.Errorf("got %v; want %v", v, ttl) return } for _, toggle := range []bool{true, false} { if err := c.SetMulticastLoopback(toggle); err != nil { t.Error(err) return } if v, err := c.MulticastLoopback(); err != nil { t.Error(err) return } else if v != toggle { t.Errorf("got %v; want %v", v, toggle) return } } if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } func testSourceSpecificMulticastSocketOptions(t *testing.T, c testIPv4MulticastConn, ifi *net.Interface, grp, src net.Addr) { // MCAST_JOIN_GROUP -> MCAST_BLOCK_SOURCE -> MCAST_UNBLOCK_SOURCE -> MCAST_LEAVE_GROUP if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.ExcludeSourceSpecificGroup(ifi, grp, src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support IGMPv2/3 fail here t.Logf("not supported on %s", runtime.GOOS) return } t.Error(err) return } if err := c.IncludeSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_SOURCE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } ================================================ FILE: vendor/golang.org/x/net/ipv4/packet.go ================================================ // 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 ipv4 import ( "net" "syscall" ) // A packetHandler represents the IPv4 datagram handler. type packetHandler struct { c *net.IPConn rawOpt } func (c *packetHandler) ok() bool { return c != nil && c.c != nil } // ReadFrom reads an IPv4 datagram from the endpoint c, copying the // datagram into b. It returns the received datagram as the IPv4 // header h, the payload p and the control message cm. func (c *packetHandler) ReadFrom(b []byte) (h *Header, p []byte, cm *ControlMessage, err error) { if !c.ok() { return nil, nil, nil, syscall.EINVAL } oob := newControlMessage(&c.rawOpt) n, oobn, _, src, err := c.c.ReadMsgIP(b, oob) if err != nil { return nil, nil, nil, err } var hs []byte if hs, p, err = slicePacket(b[:n]); err != nil { return nil, nil, nil, err } if h, err = ParseHeader(hs); err != nil { return nil, nil, nil, err } if cm, err = parseControlMessage(oob[:oobn]); err != nil { return nil, nil, nil, err } if src != nil && cm != nil { cm.Src = src.IP } return } func slicePacket(b []byte) (h, p []byte, err error) { if len(b) < HeaderLen { return nil, nil, errHeaderTooShort } hdrlen := int(b[0]&0x0f) << 2 return b[:hdrlen], b[hdrlen:], nil } // WriteTo writes an IPv4 datagram through the endpoint c, copying the // datagram from the IPv4 header h and the payload p. The control // message cm allows the datagram path and the outgoing interface to be // specified. Currently only Darwin and Linux support this. The cm // may be nil if control of the outgoing datagram is not required. // // The IPv4 header h must contain appropriate fields that include: // // Version = ipv4.Version // Len = // TOS = // TotalLen = // ID = platform sets an appropriate value if ID is zero // FragOff = // TTL = // Protocol = // Checksum = platform sets an appropriate value if Checksum is zero // Src = platform sets an appropriate value if Src is nil // Dst = // Options = optional func (c *packetHandler) WriteTo(h *Header, p []byte, cm *ControlMessage) error { if !c.ok() { return syscall.EINVAL } oob := marshalControlMessage(cm) wh, err := h.Marshal() if err != nil { return err } dst := &net.IPAddr{} if cm != nil { if ip := cm.Dst.To4(); ip != nil { dst.IP = ip } } if dst.IP == nil { dst.IP = h.Dst } wh = append(wh, p...) _, _, err = c.c.WriteMsgIP(wh, oob, dst) return err } ================================================ FILE: vendor/golang.org/x/net/ipv4/payload.go ================================================ // 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 ipv4 import "net" // A payloadHandler represents the IPv4 datagram payload handler. type payloadHandler struct { net.PacketConn rawOpt } func (c *payloadHandler) ok() bool { return c != nil && c.PacketConn != nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/payload_cmsg.go ================================================ // 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,!solaris,!windows package ipv4 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv4 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } oob := newControlMessage(&c.rawOpt) var oobn int switch c := c.PacketConn.(type) { case *net.UDPConn: if n, oobn, _, src, err = c.ReadMsgUDP(b, oob); err != nil { return 0, nil, nil, err } case *net.IPConn: if sockOpts[ssoStripHeader].name > 0 { if n, oobn, _, src, err = c.ReadMsgIP(b, oob); err != nil { return 0, nil, nil, err } } else { nb := make([]byte, maxHeaderLen+len(b)) if n, oobn, _, src, err = c.ReadMsgIP(nb, oob); err != nil { return 0, nil, nil, err } hdrlen := int(nb[0]&0x0f) << 2 copy(b, nb[hdrlen:]) n -= hdrlen } default: return 0, nil, nil, errInvalidConnType } if cm, err = parseControlMessage(oob[:oobn]); err != nil { return 0, nil, nil, err } if cm != nil { cm.Src = netAddrToIP4(src) } return } // WriteTo writes a payload of the IPv4 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the datagram path and the outgoing interface to be specified. // Currently only Darwin and Linux support this. The cm may be nil if // control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } oob := marshalControlMessage(cm) if dst == nil { return 0, errMissingAddress } switch c := c.PacketConn.(type) { case *net.UDPConn: n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr)) case *net.IPConn: n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) default: return 0, errInvalidConnType } if err != nil { return 0, err } return } ================================================ FILE: vendor/golang.org/x/net/ipv4/payload_nocmsg.go ================================================ // 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 solaris windows package ipv4 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv4 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } if n, src, err = c.PacketConn.ReadFrom(b); err != nil { return 0, nil, nil, err } return } // WriteTo writes a payload of the IPv4 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the datagram path and the outgoing interface to be specified. // Currently only Darwin and Linux support this. The cm may be nil if // control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } if dst == nil { return 0, errMissingAddress } return c.PacketConn.WriteTo(b, dst) } ================================================ FILE: vendor/golang.org/x/net/ipv4/readwrite_test.go ================================================ // 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 ipv4_test import ( "bytes" "net" "runtime" "sync" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func benchmarkUDPListener() (net.PacketConn, net.Addr, error) { c, err := net.ListenPacket("udp4", "127.0.0.1:0") if err != nil { return nil, nil, err } dst, err := net.ResolveUDPAddr("udp4", c.LocalAddr().String()) if err != nil { c.Close() return nil, nil, err } return c, dst, nil } func BenchmarkReadWriteNetUDP(b *testing.B) { c, dst, err := benchmarkUDPListener() if err != nil { b.Fatal(err) } defer c.Close() wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) b.ResetTimer() for i := 0; i < b.N; i++ { benchmarkReadWriteNetUDP(b, c, wb, rb, dst) } } func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, wb, rb []byte, dst net.Addr) { if _, err := c.WriteTo(wb, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(rb); err != nil { b.Fatal(err) } } func BenchmarkReadWriteIPv4UDP(b *testing.B) { c, dst, err := benchmarkUDPListener() if err != nil { b.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() cf := ipv4.FlagTTL | ipv4.FlagInterface if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) b.ResetTimer() for i := 0; i < b.N; i++ { benchmarkReadWriteIPv4UDP(b, p, wb, rb, dst, ifi) } } func benchmarkReadWriteIPv4UDP(b *testing.B, p *ipv4.PacketConn, wb, rb []byte, dst net.Addr, ifi *net.Interface) { cm := ipv4.ControlMessage{TTL: 1} if ifi != nil { cm.IfIndex = ifi.Index } if n, err := p.WriteTo(wb, &cm, dst); err != nil { b.Fatal(err) } else if n != len(wb) { b.Fatalf("got %v; want %v", n, len(wb)) } if _, _, _, err := p.ReadFrom(rb); err != nil { b.Fatal(err) } } func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } c, err := net.ListenPacket("udp4", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer c.Close() p := ipv4.NewPacketConn(c) defer p.Close() dst, err := net.ResolveUDPAddr("udp4", c.LocalAddr().String()) if err != nil { t.Fatal(err) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) cf := ipv4.FlagTTL | ipv4.FlagSrc | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Error(err) return } else if !bytes.Equal(rb[:n], wb) { t.Errorf("got %v; want %v", rb[:n], wb) return } else { t.Logf("rcvd cmsg: %v", cm) } } writer := func(toggle bool) { defer wg.Done() cm := ipv4.ControlMessage{ Src: net.IPv4(127, 0, 0, 1), } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Error(err) return } else if n != len(wb) { t.Errorf("short write: %v", n) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Add(2 * N) for i := 0; i < 2*N; i++ { go writer(i%2 != 0) } wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Wait() } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt.go ================================================ // 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 ipv4 // Sticky socket options const ( ssoTOS = iota // header field for unicast packet ssoTTL // header field for unicast packet ssoMulticastTTL // header field for multicast packet ssoMulticastInterface // outbound interface for multicast packet ssoMulticastLoopback // loopback for multicast packet ssoReceiveTTL // header field on received packet ssoReceiveDst // header field on received packet ssoReceiveInterface // inbound interface on received packet ssoPacketInfo // incbound or outbound packet path ssoHeaderPrepend // ipv4 header prepend ssoStripHeader // strip ipv4 header ssoICMPFilter // icmp filter ssoJoinGroup // any-source multicast ssoLeaveGroup // any-source multicast ssoJoinSourceGroup // source-specific multicast ssoLeaveSourceGroup // source-specific multicast ssoBlockSourceGroup // any-source or source-specific multicast ssoUnblockSourceGroup // any-source or source-specific multicast ssoMax ) // Sticky socket option value types const ( ssoTypeByte = iota + 1 ssoTypeInt ssoTypeInterface ssoTypeICMPFilter ssoTypeIPMreq ssoTypeIPMreqn ssoTypeGroupReq ssoTypeGroupSourceReq ) // A sockOpt represents a binding for sticky socket option. type sockOpt struct { name int // option name, must be equal or greater than 1 typ int // option value type, must be equal or greater than 1 } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_asmreq.go ================================================ // 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 dragonfly freebsd netbsd openbsd windows package ipv4 import "net" func setIPMreqInterface(mreq *sysIPMreq, ifi *net.Interface) error { if ifi == nil { return nil } ifat, err := ifi.Addrs() if err != nil { return err } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip := ifa.IP.To4(); ip != nil { copy(mreq.Interface[:], ip) return nil } case *net.IPNet: if ip := ifa.IP.To4(); ip != nil { copy(mreq.Interface[:], ip) return nil } } } return errNoSuchInterface } func netIP4ToInterface(ip net.IP) (*net.Interface, error) { ift, err := net.Interfaces() if err != nil { return nil, err } for _, ifi := range ift { ifat, err := ifi.Addrs() if err != nil { return nil, err } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip.Equal(ifa.IP) { return &ifi, nil } case *net.IPNet: if ip.Equal(ifa.IP) { return &ifi, nil } } } } return nil, errNoSuchInterface } func netInterfaceToIP4(ifi *net.Interface) (net.IP, error) { if ifi == nil { return net.IPv4zero.To4(), nil } ifat, err := ifi.Addrs() if err != nil { return nil, err } for _, ifa := range ifat { switch ifa := ifa.(type) { case *net.IPAddr: if ip := ifa.IP.To4(); ip != nil { return ip, nil } case *net.IPNet: if ip := ifa.IP.To4(); ip != nil { return ip, nil } } } return nil, errNoSuchInterface } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_asmreq_stub.go ================================================ // 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,!dragonfly,!freebsd,!netbsd,!openbsd,!windows package ipv4 import "net" func setsockoptIPMreq(fd, name int, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func getsockoptInterface(fd, name int) (*net.Interface, error) { return nil, errOpNoSupport } func setsockoptInterface(fd, name int, ifi *net.Interface) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_asmreq_unix.go ================================================ // 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 dragonfly freebsd netbsd openbsd package ipv4 import ( "net" "os" "unsafe" "golang.org/x/net/internal/iana" ) func setsockoptIPMreq(fd, name int, ifi *net.Interface, grp net.IP) error { mreq := sysIPMreq{Multiaddr: [4]byte{grp[0], grp[1], grp[2], grp[3]}} if err := setIPMreqInterface(&mreq, ifi); err != nil { return err } return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolIP, name, unsafe.Pointer(&mreq), sysSizeofIPMreq)) } func getsockoptInterface(fd, name int) (*net.Interface, error) { var b [4]byte l := sysSockoptLen(4) if err := getsockopt(fd, iana.ProtocolIP, name, unsafe.Pointer(&b[0]), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } ifi, err := netIP4ToInterface(net.IPv4(b[0], b[1], b[2], b[3])) if err != nil { return nil, err } return ifi, nil } func setsockoptInterface(fd, name int, ifi *net.Interface) error { ip, err := netInterfaceToIP4(ifi) if err != nil { return err } var b [4]byte copy(b[:], ip) return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolIP, name, unsafe.Pointer(&b[0]), sysSockoptLen(4))) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_asmreq_windows.go ================================================ // 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 ipv4 import ( "net" "os" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func setsockoptIPMreq(fd syscall.Handle, name int, ifi *net.Interface, grp net.IP) error { mreq := sysIPMreq{Multiaddr: [4]byte{grp[0], grp[1], grp[2], grp[3]}} if err := setIPMreqInterface(&mreq, ifi); err != nil { return err } return os.NewSyscallError("setsockopt", syscall.Setsockopt(fd, iana.ProtocolIP, int32(name), (*byte)(unsafe.Pointer(&mreq)), int32(sysSizeofIPMreq))) } func getsockoptInterface(fd syscall.Handle, name int) (*net.Interface, error) { var b [4]byte l := int32(4) if err := syscall.Getsockopt(fd, iana.ProtocolIP, int32(name), (*byte)(unsafe.Pointer(&b[0])), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } ifi, err := netIP4ToInterface(net.IPv4(b[0], b[1], b[2], b[3])) if err != nil { return nil, err } return ifi, nil } func setsockoptInterface(fd syscall.Handle, name int, ifi *net.Interface) error { ip, err := netInterfaceToIP4(ifi) if err != nil { return err } var b [4]byte copy(b[:], ip) return os.NewSyscallError("setsockopt", syscall.Setsockopt(fd, iana.ProtocolIP, int32(name), (*byte)(unsafe.Pointer(&b[0])), 4)) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_asmreqn_stub.go ================================================ // 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,!freebsd,!linux,!windows package ipv4 import "net" func getsockoptIPMreqn(fd, name int) (*net.Interface, error) { return nil, errOpNoSupport } func setsockoptIPMreqn(fd, name int, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_asmreqn_unix.go ================================================ // 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 freebsd linux package ipv4 import ( "net" "os" "unsafe" "golang.org/x/net/internal/iana" ) func getsockoptIPMreqn(fd, name int) (*net.Interface, error) { var mreqn sysIPMreqn l := sysSockoptLen(sysSizeofIPMreqn) if err := getsockopt(fd, iana.ProtocolIP, name, unsafe.Pointer(&mreqn), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } if mreqn.Ifindex == 0 { return nil, nil } ifi, err := net.InterfaceByIndex(int(mreqn.Ifindex)) if err != nil { return nil, err } return ifi, nil } func setsockoptIPMreqn(fd, name int, ifi *net.Interface, grp net.IP) error { var mreqn sysIPMreqn if ifi != nil { mreqn.Ifindex = int32(ifi.Index) } if grp != nil { mreqn.Multiaddr = [4]byte{grp[0], grp[1], grp[2], grp[3]} } return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolIP, name, unsafe.Pointer(&mreqn), sysSizeofIPMreqn)) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_ssmreq_stub.go ================================================ // 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,!freebsd,!linux package ipv4 import "net" func setsockoptGroupReq(fd, name int, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func setsockoptGroupSourceReq(fd, name int, ifi *net.Interface, grp, src net.IP) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_ssmreq_unix.go ================================================ // 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 freebsd linux package ipv4 import ( "net" "os" "unsafe" "golang.org/x/net/internal/iana" ) var freebsd32o64 bool func setsockoptGroupReq(fd, name int, ifi *net.Interface, grp net.IP) error { var gr sysGroupReq if ifi != nil { gr.Interface = uint32(ifi.Index) } gr.setGroup(grp) var p unsafe.Pointer var l sysSockoptLen if freebsd32o64 { var d [sysSizeofGroupReq + 4]byte s := (*[sysSizeofGroupReq]byte)(unsafe.Pointer(&gr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) p = unsafe.Pointer(&d[0]) l = sysSizeofGroupReq + 4 } else { p = unsafe.Pointer(&gr) l = sysSizeofGroupReq } return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolIP, name, p, l)) } func setsockoptGroupSourceReq(fd, name int, ifi *net.Interface, grp, src net.IP) error { var gsr sysGroupSourceReq if ifi != nil { gsr.Interface = uint32(ifi.Index) } gsr.setSourceGroup(grp, src) var p unsafe.Pointer var l sysSockoptLen if freebsd32o64 { var d [sysSizeofGroupSourceReq + 4]byte s := (*[sysSizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) p = unsafe.Pointer(&d[0]) l = sysSizeofGroupSourceReq + 4 } else { p = unsafe.Pointer(&gsr) l = sysSizeofGroupSourceReq } return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolIP, name, p, l)) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_stub.go ================================================ // 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 nacl plan9 solaris package ipv4 func setInt(fd int, opt *sockOpt, v int) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv4 import ( "net" "os" "unsafe" "golang.org/x/net/internal/iana" ) func getInt(fd int, opt *sockOpt) (int, error) { if opt.name < 1 || (opt.typ != ssoTypeByte && opt.typ != ssoTypeInt) { return 0, errOpNoSupport } var i int32 var b byte p := unsafe.Pointer(&i) l := sysSockoptLen(4) if opt.typ == ssoTypeByte { p = unsafe.Pointer(&b) l = sysSockoptLen(1) } if err := getsockopt(fd, iana.ProtocolIP, opt.name, p, &l); err != nil { return 0, os.NewSyscallError("getsockopt", err) } if opt.typ == ssoTypeByte { return int(b), nil } return int(i), nil } func setInt(fd int, opt *sockOpt, v int) error { if opt.name < 1 || (opt.typ != ssoTypeByte && opt.typ != ssoTypeInt) { return errOpNoSupport } i := int32(v) var b byte p := unsafe.Pointer(&i) l := sysSockoptLen(4) if opt.typ == ssoTypeByte { b = byte(v) p = unsafe.Pointer(&b) l = sysSockoptLen(1) } return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolIP, opt.name, p, l)) } func getInterface(fd int, opt *sockOpt) (*net.Interface, error) { if opt.name < 1 { return nil, errOpNoSupport } switch opt.typ { case ssoTypeInterface: return getsockoptInterface(fd, opt.name) case ssoTypeIPMreqn: return getsockoptIPMreqn(fd, opt.name) default: return nil, errOpNoSupport } } func setInterface(fd int, opt *sockOpt, ifi *net.Interface) error { if opt.name < 1 { return errOpNoSupport } switch opt.typ { case ssoTypeInterface: return setsockoptInterface(fd, opt.name, ifi) case ssoTypeIPMreqn: return setsockoptIPMreqn(fd, opt.name, ifi, nil) default: return errOpNoSupport } } func getICMPFilter(fd int, opt *sockOpt) (*ICMPFilter, error) { if opt.name < 1 || opt.typ != ssoTypeICMPFilter { return nil, errOpNoSupport } var f ICMPFilter l := sysSockoptLen(sysSizeofICMPFilter) if err := getsockopt(fd, iana.ProtocolReserved, opt.name, unsafe.Pointer(&f.sysICMPFilter), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } return &f, nil } func setICMPFilter(fd int, opt *sockOpt, f *ICMPFilter) error { if opt.name < 1 || opt.typ != ssoTypeICMPFilter { return errOpNoSupport } return os.NewSyscallError("setsockopt", setsockopt(fd, iana.ProtocolReserved, opt.name, unsafe.Pointer(&f.sysICMPFilter), sysSizeofICMPFilter)) } func setGroup(fd int, opt *sockOpt, ifi *net.Interface, grp net.IP) error { if opt.name < 1 { return errOpNoSupport } switch opt.typ { case ssoTypeIPMreq: return setsockoptIPMreq(fd, opt.name, ifi, grp) case ssoTypeIPMreqn: return setsockoptIPMreqn(fd, opt.name, ifi, grp) case ssoTypeGroupReq: return setsockoptGroupReq(fd, opt.name, ifi, grp) default: return errOpNoSupport } } func setSourceGroup(fd int, opt *sockOpt, ifi *net.Interface, grp, src net.IP) error { if opt.name < 1 || opt.typ != ssoTypeGroupSourceReq { return errOpNoSupport } return setsockoptGroupSourceReq(fd, opt.name, ifi, grp, src) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sockopt_windows.go ================================================ // 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 ipv4 import ( "net" "os" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func getInt(fd syscall.Handle, opt *sockOpt) (int, error) { if opt.name < 1 || opt.typ != ssoTypeInt { return 0, errOpNoSupport } var i int32 l := int32(4) if err := syscall.Getsockopt(fd, iana.ProtocolIP, int32(opt.name), (*byte)(unsafe.Pointer(&i)), &l); err != nil { return 0, os.NewSyscallError("getsockopt", err) } return int(i), nil } func setInt(fd syscall.Handle, opt *sockOpt, v int) error { if opt.name < 1 || opt.typ != ssoTypeInt { return errOpNoSupport } i := int32(v) return os.NewSyscallError("setsockopt", syscall.Setsockopt(fd, iana.ProtocolIP, int32(opt.name), (*byte)(unsafe.Pointer(&i)), 4)) } func getInterface(fd syscall.Handle, opt *sockOpt) (*net.Interface, error) { if opt.name < 1 || opt.typ != ssoTypeInterface { return nil, errOpNoSupport } return getsockoptInterface(fd, opt.name) } func setInterface(fd syscall.Handle, opt *sockOpt, ifi *net.Interface) error { if opt.name < 1 || opt.typ != ssoTypeInterface { return errOpNoSupport } return setsockoptInterface(fd, opt.name, ifi) } func getICMPFilter(fd syscall.Handle, opt *sockOpt) (*ICMPFilter, error) { return nil, errOpNoSupport } func setICMPFilter(fd syscall.Handle, opt *sockOpt, f *ICMPFilter) error { return errOpNoSupport } func setGroup(fd syscall.Handle, opt *sockOpt, ifi *net.Interface, grp net.IP) error { if opt.name < 1 || opt.typ != ssoTypeIPMreq { return errOpNoSupport } return setsockoptIPMreq(fd, opt.name, ifi, grp) } func setSourceGroup(fd syscall.Handle, opt *sockOpt, ifi *net.Interface, grp, src net.IP) error { // TODO(mikio): implement this return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_bsd.go ================================================ // 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 dragonfly netbsd package ipv4 import ( "net" "syscall" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = [ssoMax]sockOpt{ ssoTOS: {sysIP_TOS, ssoTypeInt}, ssoTTL: {sysIP_TTL, ssoTypeInt}, ssoMulticastTTL: {sysIP_MULTICAST_TTL, ssoTypeByte}, ssoMulticastInterface: {sysIP_MULTICAST_IF, ssoTypeInterface}, ssoMulticastLoopback: {sysIP_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTTL: {sysIP_RECVTTL, ssoTypeInt}, ssoReceiveDst: {sysIP_RECVDSTADDR, ssoTypeInt}, ssoReceiveInterface: {sysIP_RECVIF, ssoTypeInt}, ssoHeaderPrepend: {sysIP_HDRINCL, ssoTypeInt}, ssoJoinGroup: {sysIP_ADD_MEMBERSHIP, ssoTypeIPMreq}, ssoLeaveGroup: {sysIP_DROP_MEMBERSHIP, ssoTypeIPMreq}, } ) ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_darwin.go ================================================ // 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 ipv4 import ( "net" "syscall" "unsafe" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = [ssoMax]sockOpt{ ssoTOS: {sysIP_TOS, ssoTypeInt}, ssoTTL: {sysIP_TTL, ssoTypeInt}, ssoMulticastTTL: {sysIP_MULTICAST_TTL, ssoTypeByte}, ssoMulticastInterface: {sysIP_MULTICAST_IF, ssoTypeInterface}, ssoMulticastLoopback: {sysIP_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTTL: {sysIP_RECVTTL, ssoTypeInt}, ssoReceiveDst: {sysIP_RECVDSTADDR, ssoTypeInt}, ssoReceiveInterface: {sysIP_RECVIF, ssoTypeInt}, ssoHeaderPrepend: {sysIP_HDRINCL, ssoTypeInt}, ssoStripHeader: {sysIP_STRIPHDR, ssoTypeInt}, ssoJoinGroup: {sysIP_ADD_MEMBERSHIP, ssoTypeIPMreq}, ssoLeaveGroup: {sysIP_DROP_MEMBERSHIP, ssoTypeIPMreq}, } ) func init() { // Seems like kern.osreldate is veiled on latest OS X. We use // kern.osrelease instead. osver, err := syscall.Sysctl("kern.osrelease") if err != nil { return } var i int for i = range osver { if osver[i] == '.' { break } } // The IP_PKTINFO and protocol-independent multicast API were // introduced in OS X 10.7 (Darwin 11.0.0). But it looks like // those features require OS X 10.8 (Darwin 12.0.0) and above. // See http://support.apple.com/kb/HT1633. if i > 2 || i == 2 && osver[0] >= '1' && osver[1] >= '2' { ctlOpts[ctlPacketInfo].name = sysIP_PKTINFO ctlOpts[ctlPacketInfo].length = sysSizeofInetPktinfo ctlOpts[ctlPacketInfo].marshal = marshalPacketInfo ctlOpts[ctlPacketInfo].parse = parsePacketInfo sockOpts[ssoPacketInfo].name = sysIP_RECVPKTINFO sockOpts[ssoPacketInfo].typ = ssoTypeInt sockOpts[ssoMulticastInterface].typ = ssoTypeIPMreqn sockOpts[ssoJoinGroup].name = sysMCAST_JOIN_GROUP sockOpts[ssoJoinGroup].typ = ssoTypeGroupReq sockOpts[ssoLeaveGroup].name = sysMCAST_LEAVE_GROUP sockOpts[ssoLeaveGroup].typ = ssoTypeGroupReq sockOpts[ssoJoinSourceGroup].name = sysMCAST_JOIN_SOURCE_GROUP sockOpts[ssoJoinSourceGroup].typ = ssoTypeGroupSourceReq sockOpts[ssoLeaveSourceGroup].name = sysMCAST_LEAVE_SOURCE_GROUP sockOpts[ssoLeaveSourceGroup].typ = ssoTypeGroupSourceReq sockOpts[ssoBlockSourceGroup].name = sysMCAST_BLOCK_SOURCE sockOpts[ssoBlockSourceGroup].typ = ssoTypeGroupSourceReq sockOpts[ssoUnblockSourceGroup].name = sysMCAST_UNBLOCK_SOURCE sockOpts[ssoUnblockSourceGroup].typ = ssoTypeGroupSourceReq } } func (pi *sysInetPktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (gr *sysGroupReq) setGroup(grp net.IP) { sa := (*sysSockaddrInet)(unsafe.Pointer(&gr.Pad_cgo_0[0])) sa.Len = sysSizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *sysGroupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sysSockaddrInet)(unsafe.Pointer(&gsr.Pad_cgo_0[0])) sa.Len = sysSizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sysSockaddrInet)(unsafe.Pointer(&gsr.Pad_cgo_1[0])) sa.Len = sysSizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_freebsd.go ================================================ // 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 ipv4 import ( "net" "runtime" "strings" "syscall" "unsafe" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = [ssoMax]sockOpt{ ssoTOS: {sysIP_TOS, ssoTypeInt}, ssoTTL: {sysIP_TTL, ssoTypeInt}, ssoMulticastTTL: {sysIP_MULTICAST_TTL, ssoTypeByte}, ssoMulticastInterface: {sysIP_MULTICAST_IF, ssoTypeInterface}, ssoMulticastLoopback: {sysIP_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTTL: {sysIP_RECVTTL, ssoTypeInt}, ssoReceiveDst: {sysIP_RECVDSTADDR, ssoTypeInt}, ssoReceiveInterface: {sysIP_RECVIF, ssoTypeInt}, ssoHeaderPrepend: {sysIP_HDRINCL, ssoTypeInt}, ssoJoinGroup: {sysMCAST_JOIN_GROUP, ssoTypeGroupReq}, ssoLeaveGroup: {sysMCAST_LEAVE_GROUP, ssoTypeGroupReq}, ssoJoinSourceGroup: {sysMCAST_JOIN_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {sysMCAST_LEAVE_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {sysMCAST_BLOCK_SOURCE, ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {sysMCAST_UNBLOCK_SOURCE, ssoTypeGroupSourceReq}, } ) func init() { freebsdVersion, _ = syscall.SysctlUint32("kern.osreldate") if freebsdVersion >= 1000000 { sockOpts[ssoMulticastInterface].typ = ssoTypeIPMreqn } if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" { archs, _ := syscall.Sysctl("kern.supported_archs") for _, s := range strings.Fields(archs) { if s == "amd64" { freebsd32o64 = true break } } } } func (gr *sysGroupReq) setGroup(grp net.IP) { sa := (*sysSockaddrInet)(unsafe.Pointer(&gr.Group)) sa.Len = sysSizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *sysGroupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sysSockaddrInet)(unsafe.Pointer(&gsr.Group)) sa.Len = sysSizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sysSockaddrInet)(unsafe.Pointer(&gsr.Source)) sa.Len = sysSizeofSockaddrInet sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_linux.go ================================================ // 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 ipv4 import ( "net" "syscall" "unsafe" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_TTL, 1, marshalTTL, parseTTL}, ctlPacketInfo: {sysIP_PKTINFO, sysSizeofInetPktinfo, marshalPacketInfo, parsePacketInfo}, } sockOpts = [ssoMax]sockOpt{ ssoTOS: {sysIP_TOS, ssoTypeInt}, ssoTTL: {sysIP_TTL, ssoTypeInt}, ssoMulticastTTL: {sysIP_MULTICAST_TTL, ssoTypeInt}, ssoMulticastInterface: {sysIP_MULTICAST_IF, ssoTypeIPMreqn}, ssoMulticastLoopback: {sysIP_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTTL: {sysIP_RECVTTL, ssoTypeInt}, ssoPacketInfo: {sysIP_PKTINFO, ssoTypeInt}, ssoHeaderPrepend: {sysIP_HDRINCL, ssoTypeInt}, ssoICMPFilter: {sysICMP_FILTER, ssoTypeICMPFilter}, ssoJoinGroup: {sysMCAST_JOIN_GROUP, ssoTypeGroupReq}, ssoLeaveGroup: {sysMCAST_LEAVE_GROUP, ssoTypeGroupReq}, ssoJoinSourceGroup: {sysMCAST_JOIN_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {sysMCAST_LEAVE_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {sysMCAST_BLOCK_SOURCE, ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {sysMCAST_UNBLOCK_SOURCE, ssoTypeGroupSourceReq}, } ) func (pi *sysInetPktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } func (gr *sysGroupReq) setGroup(grp net.IP) { sa := (*sysSockaddrInet)(unsafe.Pointer(&gr.Group)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) } func (gsr *sysGroupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sysSockaddrInet)(unsafe.Pointer(&gsr.Group)) sa.Family = syscall.AF_INET copy(sa.Addr[:], grp) sa = (*sysSockaddrInet)(unsafe.Pointer(&gsr.Source)) sa.Family = syscall.AF_INET copy(sa.Addr[:], src) } ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_openbsd.go ================================================ // 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 ipv4 import ( "net" "syscall" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTTL: {sysIP_RECVTTL, 1, marshalTTL, parseTTL}, ctlDst: {sysIP_RECVDSTADDR, net.IPv4len, marshalDst, parseDst}, ctlInterface: {sysIP_RECVIF, syscall.SizeofSockaddrDatalink, marshalInterface, parseInterface}, } sockOpts = [ssoMax]sockOpt{ ssoTOS: {sysIP_TOS, ssoTypeInt}, ssoTTL: {sysIP_TTL, ssoTypeInt}, ssoMulticastTTL: {sysIP_MULTICAST_TTL, ssoTypeByte}, ssoMulticastInterface: {sysIP_MULTICAST_IF, ssoTypeInterface}, ssoMulticastLoopback: {sysIP_MULTICAST_LOOP, ssoTypeByte}, ssoReceiveTTL: {sysIP_RECVTTL, ssoTypeInt}, ssoReceiveDst: {sysIP_RECVDSTADDR, ssoTypeInt}, ssoReceiveInterface: {sysIP_RECVIF, ssoTypeInt}, ssoHeaderPrepend: {sysIP_HDRINCL, ssoTypeInt}, ssoJoinGroup: {sysIP_ADD_MEMBERSHIP, ssoTypeIPMreq}, ssoLeaveGroup: {sysIP_DROP_MEMBERSHIP, ssoTypeIPMreq}, } ) ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_stub.go ================================================ // 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 nacl plan9 solaris package ipv4 type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = [ssoMax]sockOpt{} ) ================================================ FILE: vendor/golang.org/x/net/ipv4/sys_windows.go ================================================ // 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 ipv4 const ( // See ws2tcpip.h. sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_DONTFRAGMENT = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0xf sysIP_DROP_SOURCE_MEMBERSHIP = 0x10 sysIP_PKTINFO = 0x13 sysSizeofInetPktinfo = 0x8 sysSizeofIPMreq = 0x8 sysSizeofIPMreqSource = 0xc ) type sysInetPktinfo struct { Addr [4]byte Ifindex int32 } type sysIPMreq struct { Multiaddr [4]byte Interface [4]byte } type sysIPMreqSource struct { Multiaddr [4]byte Sourceaddr [4]byte Interface [4]byte } // See http://msdn.microsoft.com/en-us/library/windows/desktop/ms738586(v=vs.85).aspx var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = [ssoMax]sockOpt{ ssoTOS: {sysIP_TOS, ssoTypeInt}, ssoTTL: {sysIP_TTL, ssoTypeInt}, ssoMulticastTTL: {sysIP_MULTICAST_TTL, ssoTypeInt}, ssoMulticastInterface: {sysIP_MULTICAST_IF, ssoTypeInterface}, ssoMulticastLoopback: {sysIP_MULTICAST_LOOP, ssoTypeInt}, ssoJoinGroup: {sysIP_ADD_MEMBERSHIP, ssoTypeIPMreq}, ssoLeaveGroup: {sysIP_DROP_MEMBERSHIP, ssoTypeIPMreq}, } ) func (pi *sysInetPktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } ================================================ FILE: vendor/golang.org/x/net/ipv4/syscall_linux_386.go ================================================ // 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 ipv4 import ( "syscall" "unsafe" ) const ( sysGETSOCKOPT = 0xf sysSETSOCKOPT = 0xe ) func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (int, syscall.Errno) func getsockopt(fd, level, name int, v unsafe.Pointer, l *sysSockoptLen) error { if _, errno := socketcall(sysGETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(unsafe.Pointer(l)), 0); errno != 0 { return error(errno) } return nil } func setsockopt(fd, level, name int, v unsafe.Pointer, l sysSockoptLen) error { if _, errno := socketcall(sysSETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(l), 0); errno != 0 { return error(errno) } return nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/syscall_unix.go ================================================ // 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,!386 netbsd openbsd package ipv4 import ( "syscall" "unsafe" ) func getsockopt(fd, level, name int, v unsafe.Pointer, l *sysSockoptLen) error { if _, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(unsafe.Pointer(l)), 0); errno != 0 { return error(errno) } return nil } func setsockopt(fd, level, name int, v unsafe.Pointer, l sysSockoptLen) error { if _, _, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(l), 0); errno != 0 { return error(errno) } return nil } ================================================ FILE: vendor/golang.org/x/net/ipv4/thunk_linux_386.s ================================================ // 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.2 TEXT ·socketcall(SB),4,$0-36 JMP syscall·socketcall(SB) ================================================ FILE: vendor/golang.org/x/net/ipv4/unicast_test.go ================================================ // 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 ipv4_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func TestPacketConnReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("udp4", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer c.Close() dst, err := net.ResolveUDPAddr("udp4", c.LocalAddr().String()) if err != nil { t.Fatal(err) } p := ipv4.NewPacketConn(c) defer p.Close() cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } p.SetTTL(i + 1) if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, nil, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } else { t.Logf("rcvd cmsg: %v", cm) } } } func TestPacketConnReadWriteUnicastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() dst, err := net.ResolveIPAddr("ip4", "127.0.0.1") if err != nil { t.Fatal(err) } p := ipv4.NewPacketConn(c) defer p.Close() cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } p.SetTTL(i + 1) if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, nil, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) loop: if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, cm, _, err := p.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { t.Logf("rcvd cmsg: %v", cm) m, err := icmp.ParseMessage(iana.ProtocolICMP, rb[:n]) if err != nil { t.Fatal(err) } if runtime.GOOS == "linux" && m.Type == ipv4.ICMPTypeEcho { // On Linux we must handle own sent packets. goto loop } if m.Type != ipv4.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } func TestRawConnReadWriteUnicastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { t.Fatal(err) } defer c.Close() dst, err := net.ResolveIPAddr("ip4", "127.0.0.1") if err != nil { t.Fatal(err) } r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } defer r.Close() cf := ipv4.FlagTTL | ipv4.FlagDst | ipv4.FlagInterface for i, toggle := range []bool{true, false, true} { wb, err := (&icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(nil) if err != nil { t.Fatal(err) } wh := &ipv4.Header{ Version: ipv4.Version, Len: ipv4.HeaderLen, TOS: i + 1, TotalLen: ipv4.HeaderLen + len(wb), TTL: i + 1, Protocol: 1, Dst: dst.IP, } if err := r.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := r.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if err := r.WriteTo(wh, wb, nil); err != nil { t.Fatal(err) } rb := make([]byte, ipv4.HeaderLen+128) loop: if err := r.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if _, b, cm, err := r.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { t.Logf("rcvd cmsg: %v", cm) m, err := icmp.ParseMessage(iana.ProtocolICMP, b) if err != nil { t.Fatal(err) } if runtime.GOOS == "linux" && m.Type == ipv4.ICMPTypeEcho { // On Linux we must handle own sent packets. goto loop } if m.Type != ipv4.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv4.ICMPTypeEchoReply, 0) } } } } ================================================ FILE: vendor/golang.org/x/net/ipv4/unicastsockopt_test.go ================================================ // 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 ipv4_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv4" ) func TestConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } ln, err := net.Listen("tcp4", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer ln.Close() done := make(chan bool) go acceptor(t, ln, done) c, err := net.Dial("tcp4", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv4.NewConn(c)) <-done } var packetConnUnicastSocketOptionTests = []struct { net, proto, addr string }{ {"udp4", "", "127.0.0.1:0"}, {"ip4", ":icmp", "127.0.0.1"}, } func TestPacketConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris": t.Skipf("not supported on %s", runtime.GOOS) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnUnicastSocketOptionTests { if tt.net == "ip4" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv4.NewPacketConn(c)) } } func TestRawConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris": t.Skipf("not supported on %s", runtime.GOOS) } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip4", net.FlagUp|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } c, err := net.ListenPacket("ip4:icmp", "127.0.0.1") if err != nil { t.Fatal(err) } defer c.Close() r, err := ipv4.NewRawConn(c) if err != nil { t.Fatal(err) } testUnicastSocketOptions(t, r) } type testIPv4UnicastConn interface { TOS() (int, error) SetTOS(int) error TTL() (int, error) SetTTL(int) error } func testUnicastSocketOptions(t *testing.T, c testIPv4UnicastConn) { tos := iana.DiffServCS0 | iana.NotECNTransport switch runtime.GOOS { case "windows": // IP_TOS option is supported on Windows 8 and beyond. t.Skipf("not supported on %s", runtime.GOOS) } if err := c.SetTOS(tos); err != nil { t.Fatal(err) } if v, err := c.TOS(); err != nil { t.Fatal(err) } else if v != tos { t.Fatalf("got %v; want %v", v, tos) } const ttl = 255 if err := c.SetTTL(ttl); err != nil { t.Fatal(err) } if v, err := c.TTL(); err != nil { t.Fatal(err) } else if v != ttl { t.Fatalf("got %v; want %v", v, ttl) } } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_darwin.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_STRIPHDR = 0x17 sysIP_RECVTTL = 0x18 sysIP_BOUND_IF = 0x19 sysIP_PKTINFO = 0x1a sysIP_RECVPKTINFO = 0x1a sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_MULTICAST_IFINDEX = 0x42 sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sysInetPktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [128]byte } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [128]byte Pad_cgo_1 [128]byte } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_dragonfly.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_dragonfly.go // +build dragonfly package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_RECVTTL = 0x41 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_MULTICAST_VIF = 0xe sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysSizeofIPMreq = 0x8 ) type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_freebsd_386.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_SENDSRCADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_ONESBCAST = 0x17 sysIP_BINDANY = 0x18 sysIP_RECVTTL = 0x41 sysIP_MINTTL = 0x42 sysIP_DONTFRAG = 0x43 sysIP_RECVTOS = 0x44 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysGroupReq struct { Interface uint32 Group sysSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Group sysSockaddrStorage Source sysSockaddrStorage } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_freebsd_amd64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_SENDSRCADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_ONESBCAST = 0x17 sysIP_BINDANY = 0x18 sysIP_RECVTTL = 0x41 sysIP_MINTTL = 0x42 sysIP_DONTFRAG = 0x43 sysIP_RECVTOS = 0x44 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage Source sysSockaddrStorage } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_freebsd_arm.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_SENDSRCADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_ONESBCAST = 0x17 sysIP_BINDANY = 0x18 sysIP_RECVTTL = 0x41 sysIP_MINTTL = 0x42 sysIP_DONTFRAG = 0x43 sysIP_RECVTOS = 0x44 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysIP_MULTICAST_VIF = 0xe sysIP_ADD_SOURCE_MEMBERSHIP = 0x46 sysIP_DROP_SOURCE_MEMBERSHIP = 0x47 sysIP_BLOCK_SOURCE = 0x48 sysIP_UNBLOCK_SOURCE = 0x49 sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage Source sysSockaddrStorage } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_linux_386.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofSockExtendedErr = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 sysSizeofICMPFilter = 0x4 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sysInetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysSockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type sysGroupReq struct { Interface uint32 Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPFilter struct { Data uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_linux_amd64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofSockExtendedErr = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPFilter = 0x4 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sysInetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysSockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPFilter struct { Data uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_linux_arm.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofSockExtendedErr = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 sysSizeofICMPFilter = 0x4 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sysInetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysSockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type sysGroupReq struct { Interface uint32 Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPFilter struct { Data uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_linux_arm64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go // +build linux,arm64 package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofSockExtendedErr = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPFilter = 0x4 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sysInetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysSockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPFilter struct { Data uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_linux_ppc64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go // +build linux,ppc64 package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofSockExtendedErr = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPFilter = 0x4 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sysInetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysSockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPFilter struct { Data uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_linux_ppc64le.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go // +build linux,ppc64le package ipv4 const ( sysIP_TOS = 0x1 sysIP_TTL = 0x2 sysIP_HDRINCL = 0x3 sysIP_OPTIONS = 0x4 sysIP_ROUTER_ALERT = 0x5 sysIP_RECVOPTS = 0x6 sysIP_RETOPTS = 0x7 sysIP_PKTINFO = 0x8 sysIP_PKTOPTIONS = 0x9 sysIP_MTU_DISCOVER = 0xa sysIP_RECVERR = 0xb sysIP_RECVTTL = 0xc sysIP_RECVTOS = 0xd sysIP_MTU = 0xe sysIP_FREEBIND = 0xf sysIP_TRANSPARENT = 0x13 sysIP_RECVRETOPTS = 0x7 sysIP_ORIGDSTADDR = 0x14 sysIP_RECVORIGDSTADDR = 0x14 sysIP_MINTTL = 0x15 sysIP_NODEFRAG = 0x16 sysIP_UNICAST_IF = 0x32 sysIP_MULTICAST_IF = 0x20 sysIP_MULTICAST_TTL = 0x21 sysIP_MULTICAST_LOOP = 0x22 sysIP_ADD_MEMBERSHIP = 0x23 sysIP_DROP_MEMBERSHIP = 0x24 sysIP_UNBLOCK_SOURCE = 0x25 sysIP_BLOCK_SOURCE = 0x26 sysIP_ADD_SOURCE_MEMBERSHIP = 0x27 sysIP_DROP_SOURCE_MEMBERSHIP = 0x28 sysIP_MSFILTER = 0x29 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIP_MULTICAST_ALL = 0x31 sysICMP_FILTER = 0x1 sysSO_EE_ORIGIN_NONE = 0x0 sysSO_EE_ORIGIN_LOCAL = 0x1 sysSO_EE_ORIGIN_ICMP = 0x2 sysSO_EE_ORIGIN_ICMP6 = 0x3 sysSO_EE_ORIGIN_TXSTATUS = 0x4 sysSO_EE_ORIGIN_TIMESTAMPING = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet = 0x10 sysSizeofInetPktinfo = 0xc sysSizeofSockExtendedErr = 0x10 sysSizeofIPMreq = 0x8 sysSizeofIPMreqn = 0xc sysSizeofIPMreqSource = 0xc sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPFilter = 0x4 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet struct { Family uint16 Port uint16 Addr [4]byte /* in_addr */ X__pad [8]uint8 } type sysInetPktinfo struct { Ifindex int32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysSockExtendedErr struct { Errno uint32 Origin uint8 Type uint8 Code uint8 Pad uint8 Info uint32 Data uint32 } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type sysIPMreqSource struct { Multiaddr uint32 Interface uint32 Sourceaddr uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPFilter struct { Data uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_netbsd.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x14 sysIP_RECVTTL = 0x17 sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysSizeofIPMreq = 0x8 ) type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_openbsd.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x1e sysIP_RECVTTL = 0x1f sysIP_MULTICAST_IF = 0x9 sysIP_MULTICAST_TTL = 0xa sysIP_MULTICAST_LOOP = 0xb sysIP_ADD_MEMBERSHIP = 0xc sysIP_DROP_MEMBERSHIP = 0xd sysSizeofIPMreq = 0x8 ) type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } ================================================ FILE: vendor/golang.org/x/net/ipv4/zsys_solaris.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_solaris.go // +build solaris package ipv4 const ( sysIP_OPTIONS = 0x1 sysIP_HDRINCL = 0x2 sysIP_TOS = 0x3 sysIP_TTL = 0x4 sysIP_RECVOPTS = 0x5 sysIP_RECVRETOPTS = 0x6 sysIP_RECVDSTADDR = 0x7 sysIP_RETOPTS = 0x8 sysIP_RECVIF = 0x9 sysIP_RECVSLLA = 0xa sysIP_RECVTTL = 0xb sysIP_NEXTHOP = 0x19 sysIP_PKTINFO = 0x1a sysIP_RECVPKTINFO = 0x1a sysIP_DONTFRAG = 0x1b sysIP_BOUND_IF = 0x41 sysIP_UNSPEC_SRC = 0x42 sysIP_BROADCAST_TTL = 0x43 sysIP_DHCPINIT_IF = 0x45 sysIP_MULTICAST_IF = 0x10 sysIP_MULTICAST_TTL = 0x11 sysIP_MULTICAST_LOOP = 0x12 sysIP_ADD_MEMBERSHIP = 0x13 sysIP_DROP_MEMBERSHIP = 0x14 sysIP_BLOCK_SOURCE = 0x15 sysIP_UNBLOCK_SOURCE = 0x16 sysIP_ADD_SOURCE_MEMBERSHIP = 0x17 sysIP_DROP_SOURCE_MEMBERSHIP = 0x18 sysSizeofInetPktinfo = 0xc sysSizeofIPMreq = 0x8 sysSizeofIPMreqSource = 0xc ) type sysInetPktinfo struct { Ifindex uint32 Spec_dst [4]byte /* in_addr */ Addr [4]byte /* in_addr */ } type sysIPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type sysIPMreqSource struct { Multiaddr [4]byte /* in_addr */ Sourceaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } ================================================ FILE: vendor/golang.org/x/net/ipv6/control.go ================================================ // 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 ipv6 import ( "errors" "fmt" "net" "sync" ) var ( errMissingAddress = errors.New("missing address") errInvalidConnType = errors.New("invalid conn type") errNoSuchInterface = errors.New("no such interface") ) // Note that RFC 3542 obsoletes RFC 2292 but OS X Snow Leopard and the // former still support RFC 2292 only. Please be aware that almost // all protocol implementations prohibit using a combination of RFC // 2292 and RFC 3542 for some practical reasons. type rawOpt struct { sync.RWMutex cflags ControlFlags } func (c *rawOpt) set(f ControlFlags) { c.cflags |= f } func (c *rawOpt) clear(f ControlFlags) { c.cflags &^= f } func (c *rawOpt) isset(f ControlFlags) bool { return c.cflags&f != 0 } // A ControlFlags represents per packet basis IP-level socket option // control flags. type ControlFlags uint const ( FlagTrafficClass ControlFlags = 1 << iota // pass the traffic class on the received packet FlagHopLimit // pass the hop limit on the received packet FlagSrc // pass the source address on the received packet FlagDst // pass the destination address on the received packet FlagInterface // pass the interface index on the received packet FlagPathMTU // pass the path MTU on the received packet path ) const flagPacketInfo = FlagDst | FlagInterface // A ControlMessage represents per packet basis IP-level socket // options. type ControlMessage struct { // Receiving socket options: SetControlMessage allows to // receive the options from the protocol stack using ReadFrom // method of PacketConn. // // Specifying socket options: ControlMessage for WriteTo // method of PacketConn allows to send the options to the // protocol stack. // TrafficClass int // traffic class, must be 1 <= value <= 255 when specifying HopLimit int // hop limit, must be 1 <= value <= 255 when specifying Src net.IP // source address, specifying only Dst net.IP // destination address, receiving only IfIndex int // interface index, must be 1 <= value when specifying NextHop net.IP // next hop address, specifying only MTU int // path MTU, receiving only } func (cm *ControlMessage) String() string { if cm == nil { return "" } return fmt.Sprintf("tclass: %#x, hoplim: %v, src: %v, dst: %v, ifindex: %v, nexthop: %v, mtu: %v", cm.TrafficClass, cm.HopLimit, cm.Src, cm.Dst, cm.IfIndex, cm.NextHop, cm.MTU) } // Ancillary data socket options const ( ctlTrafficClass = iota // header field ctlHopLimit // header field ctlPacketInfo // inbound or outbound packet path ctlNextHop // nexthop ctlPathMTU // path mtu ctlMax ) // A ctlOpt represents a binding for ancillary data socket option. type ctlOpt struct { name int // option name, must be equal or greater than 1 length int // option length marshal func([]byte, *ControlMessage) []byte parse func(*ControlMessage, []byte) } ================================================ FILE: vendor/golang.org/x/net/ipv6/control_rfc2292_unix.go ================================================ // 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 ipv6 import ( "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func marshal2292HopLimit(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_2292HOPLIMIT m.SetLen(syscall.CmsgLen(4)) if cm != nil { data := b[syscall.CmsgLen(0):] // TODO(mikio): fix potential misaligned memory access *(*int32)(unsafe.Pointer(&data[:4][0])) = int32(cm.HopLimit) } return b[syscall.CmsgSpace(4):] } func marshal2292PacketInfo(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_2292PKTINFO m.SetLen(syscall.CmsgLen(sysSizeofInet6Pktinfo)) if cm != nil { pi := (*sysInet6Pktinfo)(unsafe.Pointer(&b[syscall.CmsgLen(0)])) if ip := cm.Src.To16(); ip != nil && ip.To4() == nil { copy(pi.Addr[:], ip) } if cm.IfIndex > 0 { pi.setIfindex(cm.IfIndex) } } return b[syscall.CmsgSpace(sysSizeofInet6Pktinfo):] } func marshal2292NextHop(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_2292NEXTHOP m.SetLen(syscall.CmsgLen(sysSizeofSockaddrInet6)) if cm != nil { sa := (*sysSockaddrInet6)(unsafe.Pointer(&b[syscall.CmsgLen(0)])) sa.setSockaddr(cm.NextHop, cm.IfIndex) } return b[syscall.CmsgSpace(sysSizeofSockaddrInet6):] } ================================================ FILE: vendor/golang.org/x/net/ipv6/control_rfc3542_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv6 import ( "syscall" "unsafe" "golang.org/x/net/internal/iana" ) func marshalTrafficClass(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_TCLASS m.SetLen(syscall.CmsgLen(4)) if cm != nil { data := b[syscall.CmsgLen(0):] // TODO(mikio): fix potential misaligned memory access *(*int32)(unsafe.Pointer(&data[:4][0])) = int32(cm.TrafficClass) } return b[syscall.CmsgSpace(4):] } func parseTrafficClass(cm *ControlMessage, b []byte) { // TODO(mikio): fix potential misaligned memory access cm.TrafficClass = int(*(*int32)(unsafe.Pointer(&b[:4][0]))) } func marshalHopLimit(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_HOPLIMIT m.SetLen(syscall.CmsgLen(4)) if cm != nil { data := b[syscall.CmsgLen(0):] // TODO(mikio): fix potential misaligned memory access *(*int32)(unsafe.Pointer(&data[:4][0])) = int32(cm.HopLimit) } return b[syscall.CmsgSpace(4):] } func parseHopLimit(cm *ControlMessage, b []byte) { // TODO(mikio): fix potential misaligned memory access cm.HopLimit = int(*(*int32)(unsafe.Pointer(&b[:4][0]))) } func marshalPacketInfo(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_PKTINFO m.SetLen(syscall.CmsgLen(sysSizeofInet6Pktinfo)) if cm != nil { pi := (*sysInet6Pktinfo)(unsafe.Pointer(&b[syscall.CmsgLen(0)])) if ip := cm.Src.To16(); ip != nil && ip.To4() == nil { copy(pi.Addr[:], ip) } if cm.IfIndex > 0 { pi.setIfindex(cm.IfIndex) } } return b[syscall.CmsgSpace(sysSizeofInet6Pktinfo):] } func parsePacketInfo(cm *ControlMessage, b []byte) { pi := (*sysInet6Pktinfo)(unsafe.Pointer(&b[0])) cm.Dst = pi.Addr[:] cm.IfIndex = int(pi.Ifindex) } func marshalNextHop(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_NEXTHOP m.SetLen(syscall.CmsgLen(sysSizeofSockaddrInet6)) if cm != nil { sa := (*sysSockaddrInet6)(unsafe.Pointer(&b[syscall.CmsgLen(0)])) sa.setSockaddr(cm.NextHop, cm.IfIndex) } return b[syscall.CmsgSpace(sysSizeofSockaddrInet6):] } func parseNextHop(cm *ControlMessage, b []byte) { } func marshalPathMTU(b []byte, cm *ControlMessage) []byte { m := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0])) m.Level = iana.ProtocolIPv6 m.Type = sysIPV6_PATHMTU m.SetLen(syscall.CmsgLen(sysSizeofIPv6Mtuinfo)) return b[syscall.CmsgSpace(sysSizeofIPv6Mtuinfo):] } func parsePathMTU(cm *ControlMessage, b []byte) { mi := (*sysIPv6Mtuinfo)(unsafe.Pointer(&b[0])) cm.Dst = mi.Addr.Addr[:] cm.IfIndex = int(mi.Addr.Scope_id) cm.MTU = int(mi.Mtu) } ================================================ FILE: vendor/golang.org/x/net/ipv6/control_stub.go ================================================ // 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 nacl plan9 solaris package ipv6 func setControlMessage(fd int, opt *rawOpt, cf ControlFlags, on bool) error { return errOpNoSupport } func newControlMessage(opt *rawOpt) (oob []byte) { return nil } func parseControlMessage(b []byte) (*ControlMessage, error) { return nil, errOpNoSupport } func marshalControlMessage(cm *ControlMessage) (oob []byte) { return nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/control_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv6 import ( "os" "syscall" "golang.org/x/net/internal/iana" ) func setControlMessage(fd int, opt *rawOpt, cf ControlFlags, on bool) error { opt.Lock() defer opt.Unlock() if cf&FlagTrafficClass != 0 && sockOpts[ssoReceiveTrafficClass].name > 0 { if err := setInt(fd, &sockOpts[ssoReceiveTrafficClass], boolint(on)); err != nil { return err } if on { opt.set(FlagTrafficClass) } else { opt.clear(FlagTrafficClass) } } if cf&FlagHopLimit != 0 && sockOpts[ssoReceiveHopLimit].name > 0 { if err := setInt(fd, &sockOpts[ssoReceiveHopLimit], boolint(on)); err != nil { return err } if on { opt.set(FlagHopLimit) } else { opt.clear(FlagHopLimit) } } if cf&flagPacketInfo != 0 && sockOpts[ssoReceivePacketInfo].name > 0 { if err := setInt(fd, &sockOpts[ssoReceivePacketInfo], boolint(on)); err != nil { return err } if on { opt.set(cf & flagPacketInfo) } else { opt.clear(cf & flagPacketInfo) } } if cf&FlagPathMTU != 0 && sockOpts[ssoReceivePathMTU].name > 0 { if err := setInt(fd, &sockOpts[ssoReceivePathMTU], boolint(on)); err != nil { return err } if on { opt.set(FlagPathMTU) } else { opt.clear(FlagPathMTU) } } return nil } func newControlMessage(opt *rawOpt) (oob []byte) { opt.RLock() var l int if opt.isset(FlagTrafficClass) && ctlOpts[ctlTrafficClass].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlTrafficClass].length) } if opt.isset(FlagHopLimit) && ctlOpts[ctlHopLimit].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlHopLimit].length) } if opt.isset(flagPacketInfo) && ctlOpts[ctlPacketInfo].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlPacketInfo].length) } if opt.isset(FlagPathMTU) && ctlOpts[ctlPathMTU].name > 0 { l += syscall.CmsgSpace(ctlOpts[ctlPathMTU].length) } if l > 0 { oob = make([]byte, l) b := oob if opt.isset(FlagTrafficClass) && ctlOpts[ctlTrafficClass].name > 0 { b = ctlOpts[ctlTrafficClass].marshal(b, nil) } if opt.isset(FlagHopLimit) && ctlOpts[ctlHopLimit].name > 0 { b = ctlOpts[ctlHopLimit].marshal(b, nil) } if opt.isset(flagPacketInfo) && ctlOpts[ctlPacketInfo].name > 0 { b = ctlOpts[ctlPacketInfo].marshal(b, nil) } if opt.isset(FlagPathMTU) && ctlOpts[ctlPathMTU].name > 0 { b = ctlOpts[ctlPathMTU].marshal(b, nil) } } opt.RUnlock() return } func parseControlMessage(b []byte) (*ControlMessage, error) { if len(b) == 0 { return nil, nil } cmsgs, err := syscall.ParseSocketControlMessage(b) if err != nil { return nil, os.NewSyscallError("parse socket control message", err) } cm := &ControlMessage{} for _, m := range cmsgs { if m.Header.Level != iana.ProtocolIPv6 { continue } switch int(m.Header.Type) { case ctlOpts[ctlTrafficClass].name: ctlOpts[ctlTrafficClass].parse(cm, m.Data[:]) case ctlOpts[ctlHopLimit].name: ctlOpts[ctlHopLimit].parse(cm, m.Data[:]) case ctlOpts[ctlPacketInfo].name: ctlOpts[ctlPacketInfo].parse(cm, m.Data[:]) case ctlOpts[ctlPathMTU].name: ctlOpts[ctlPathMTU].parse(cm, m.Data[:]) } } return cm, nil } func marshalControlMessage(cm *ControlMessage) (oob []byte) { if cm == nil { return } var l int tclass := false if ctlOpts[ctlTrafficClass].name > 0 && cm.TrafficClass > 0 { tclass = true l += syscall.CmsgSpace(ctlOpts[ctlTrafficClass].length) } hoplimit := false if ctlOpts[ctlHopLimit].name > 0 && cm.HopLimit > 0 { hoplimit = true l += syscall.CmsgSpace(ctlOpts[ctlHopLimit].length) } pktinfo := false if ctlOpts[ctlPacketInfo].name > 0 && (cm.Src.To16() != nil && cm.Src.To4() == nil || cm.IfIndex > 0) { pktinfo = true l += syscall.CmsgSpace(ctlOpts[ctlPacketInfo].length) } nexthop := false if ctlOpts[ctlNextHop].name > 0 && cm.NextHop.To16() != nil && cm.NextHop.To4() == nil { nexthop = true l += syscall.CmsgSpace(ctlOpts[ctlNextHop].length) } if l > 0 { oob = make([]byte, l) b := oob if tclass { b = ctlOpts[ctlTrafficClass].marshal(b, cm) } if hoplimit { b = ctlOpts[ctlHopLimit].marshal(b, cm) } if pktinfo { b = ctlOpts[ctlPacketInfo].marshal(b, cm) } if nexthop { b = ctlOpts[ctlNextHop].marshal(b, cm) } } return } ================================================ FILE: vendor/golang.org/x/net/ipv6/control_windows.go ================================================ // 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 ipv6 import "syscall" func setControlMessage(fd syscall.Handle, opt *rawOpt, cf ControlFlags, on bool) error { // TODO(mikio): implement this return syscall.EWINDOWS } func newControlMessage(opt *rawOpt) (oob []byte) { // TODO(mikio): implement this return nil } func parseControlMessage(b []byte) (*ControlMessage, error) { // TODO(mikio): implement this return nil, syscall.EWINDOWS } func marshalControlMessage(cm *ControlMessage) (oob []byte) { // TODO(mikio): implement this return nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_darwin.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #define __APPLE_USE_RFC_3542 #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_2292PKTINFO = C.IPV6_2292PKTINFO sysIPV6_2292HOPLIMIT = C.IPV6_2292HOPLIMIT sysIPV6_2292NEXTHOP = C.IPV6_2292NEXTHOP sysIPV6_2292HOPOPTS = C.IPV6_2292HOPOPTS sysIPV6_2292DSTOPTS = C.IPV6_2292DSTOPTS sysIPV6_2292RTHDR = C.IPV6_2292RTHDR sysIPV6_2292PKTOPTIONS = C.IPV6_2292PKTOPTIONS sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR sysIPV6_MSFILTER = C.IPV6_MSFILTER sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysIPV6_BOUND_IF = C.IPV6_BOUND_IF sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sysSizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofGroupReq = C.sizeof_struct_group_req sysSizeofGroupSourceReq = C.sizeof_struct_group_source_req sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysSockaddrStorage C.struct_sockaddr_storage type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6Mreq C.struct_ipv6_mreq type sysICMPv6Filter C.struct_icmp6_filter type sysGroupReq C.struct_group_req type sysGroupSourceReq C.struct_group_source_req ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_dragonfly.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6Mreq C.struct_ipv6_mreq type sysICMPv6Filter C.struct_icmp6_filter ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_freebsd.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PREFER_TEMPADDR = C.IPV6_PREFER_TEMPADDR sysIPV6_BINDANY = C.IPV6_BINDANY sysIPV6_MSFILTER = C.IPV6_MSFILTER sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sysSizeofSockaddrStorage = C.sizeof_struct_sockaddr_storage sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofGroupReq = C.sizeof_struct_group_req sysSizeofGroupSourceReq = C.sizeof_struct_group_source_req sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysSockaddrStorage C.struct_sockaddr_storage type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6Mreq C.struct_ipv6_mreq type sysGroupReq C.struct_group_req type sysGroupSourceReq C.struct_group_source_req type sysICMPv6Filter C.struct_icmp6_filter ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_linux.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_ADDRFORM = C.IPV6_ADDRFORM sysIPV6_2292PKTINFO = C.IPV6_2292PKTINFO sysIPV6_2292HOPOPTS = C.IPV6_2292HOPOPTS sysIPV6_2292DSTOPTS = C.IPV6_2292DSTOPTS sysIPV6_2292RTHDR = C.IPV6_2292RTHDR sysIPV6_2292PKTOPTIONS = C.IPV6_2292PKTOPTIONS sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_2292HOPLIMIT = C.IPV6_2292HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_FLOWINFO = C.IPV6_FLOWINFO sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_ADD_MEMBERSHIP = C.IPV6_ADD_MEMBERSHIP sysIPV6_DROP_MEMBERSHIP = C.IPV6_DROP_MEMBERSHIP sysMCAST_JOIN_GROUP = C.MCAST_JOIN_GROUP sysMCAST_LEAVE_GROUP = C.MCAST_LEAVE_GROUP sysMCAST_JOIN_SOURCE_GROUP = C.MCAST_JOIN_SOURCE_GROUP sysMCAST_LEAVE_SOURCE_GROUP = C.MCAST_LEAVE_SOURCE_GROUP sysMCAST_BLOCK_SOURCE = C.MCAST_BLOCK_SOURCE sysMCAST_UNBLOCK_SOURCE = C.MCAST_UNBLOCK_SOURCE sysMCAST_MSFILTER = C.MCAST_MSFILTER sysIPV6_ROUTER_ALERT = C.IPV6_ROUTER_ALERT sysIPV6_MTU_DISCOVER = C.IPV6_MTU_DISCOVER sysIPV6_MTU = C.IPV6_MTU sysIPV6_RECVERR = C.IPV6_RECVERR sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_JOIN_ANYCAST = C.IPV6_JOIN_ANYCAST sysIPV6_LEAVE_ANYCAST = C.IPV6_LEAVE_ANYCAST //sysIPV6_PMTUDISC_DONT = C.IPV6_PMTUDISC_DONT //sysIPV6_PMTUDISC_WANT = C.IPV6_PMTUDISC_WANT //sysIPV6_PMTUDISC_DO = C.IPV6_PMTUDISC_DO //sysIPV6_PMTUDISC_PROBE = C.IPV6_PMTUDISC_PROBE //sysIPV6_PMTUDISC_INTERFACE = C.IPV6_PMTUDISC_INTERFACE //sysIPV6_PMTUDISC_OMIT = C.IPV6_PMTUDISC_OMIT sysIPV6_FLOWLABEL_MGR = C.IPV6_FLOWLABEL_MGR sysIPV6_FLOWINFO_SEND = C.IPV6_FLOWINFO_SEND sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_XFRM_POLICY = C.IPV6_XFRM_POLICY sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_ADDR_PREFERENCES = C.IPV6_ADDR_PREFERENCES sysIPV6_PREFER_SRC_TMP = C.IPV6_PREFER_SRC_TMP sysIPV6_PREFER_SRC_PUBLIC = C.IPV6_PREFER_SRC_PUBLIC sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = C.IPV6_PREFER_SRC_PUBTMP_DEFAULT sysIPV6_PREFER_SRC_COA = C.IPV6_PREFER_SRC_COA sysIPV6_PREFER_SRC_HOME = C.IPV6_PREFER_SRC_HOME sysIPV6_PREFER_SRC_CGA = C.IPV6_PREFER_SRC_CGA sysIPV6_PREFER_SRC_NONCGA = C.IPV6_PREFER_SRC_NONCGA sysIPV6_MINHOPCOUNT = C.IPV6_MINHOPCOUNT sysIPV6_ORIGDSTADDR = C.IPV6_ORIGDSTADDR sysIPV6_RECVORIGDSTADDR = C.IPV6_RECVORIGDSTADDR sysIPV6_TRANSPARENT = C.IPV6_TRANSPARENT sysIPV6_UNICAST_IF = C.IPV6_UNICAST_IF sysICMPV6_FILTER = C.ICMPV6_FILTER sysICMPV6_FILTER_BLOCK = C.ICMPV6_FILTER_BLOCK sysICMPV6_FILTER_PASS = C.ICMPV6_FILTER_PASS sysICMPV6_FILTER_BLOCKOTHERS = C.ICMPV6_FILTER_BLOCKOTHERS sysICMPV6_FILTER_PASSONLY = C.ICMPV6_FILTER_PASSONLY sysSizeofKernelSockaddrStorage = C.sizeof_struct___kernel_sockaddr_storage sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6FlowlabelReq = C.sizeof_struct_in6_flowlabel_req sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofGroupReq = C.sizeof_struct_group_req sysSizeofGroupSourceReq = C.sizeof_struct_group_source_req sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysKernelSockaddrStorage C.struct___kernel_sockaddr_storage type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6FlowlabelReq C.struct_in6_flowlabel_req type sysIPv6Mreq C.struct_ipv6_mreq type sysGroupReq C.struct_group_req type sysGroupSourceReq C.struct_group_source_req type sysICMPv6Filter C.struct_icmp6_filter ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_netbsd.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_IPSEC_POLICY = C.IPV6_IPSEC_POLICY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6Mreq C.struct_ipv6_mreq type sysICMPv6Filter C.struct_icmp6_filter ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_openbsd.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PORTRANGE = C.IPV6_PORTRANGE sysICMP6_FILTER = C.ICMP6_FILTER sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_AUTH_LEVEL = C.IPV6_AUTH_LEVEL sysIPV6_ESP_TRANS_LEVEL = C.IPV6_ESP_TRANS_LEVEL sysIPV6_ESP_NETWORK_LEVEL = C.IPV6_ESP_NETWORK_LEVEL sysIPSEC6_OUTSA = C.IPSEC6_OUTSA sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_AUTOFLOWLABEL = C.IPV6_AUTOFLOWLABEL sysIPV6_IPCOMP_LEVEL = C.IPV6_IPCOMP_LEVEL sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_PIPEX = C.IPV6_PIPEX sysIPV6_RTABLE = C.IPV6_RTABLE sysIPV6_PORTRANGE_DEFAULT = C.IPV6_PORTRANGE_DEFAULT sysIPV6_PORTRANGE_HIGH = C.IPV6_PORTRANGE_HIGH sysIPV6_PORTRANGE_LOW = C.IPV6_PORTRANGE_LOW sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6Mreq C.struct_ipv6_mreq type sysICMPv6Filter C.struct_icmp6_filter ================================================ FILE: vendor/golang.org/x/net/ipv6/defs_solaris.go ================================================ // 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 ignore // +godefs map struct_in6_addr [16]byte /* in6_addr */ package ipv6 /* #include #include */ import "C" const ( sysIPV6_UNICAST_HOPS = C.IPV6_UNICAST_HOPS sysIPV6_MULTICAST_IF = C.IPV6_MULTICAST_IF sysIPV6_MULTICAST_HOPS = C.IPV6_MULTICAST_HOPS sysIPV6_MULTICAST_LOOP = C.IPV6_MULTICAST_LOOP sysIPV6_JOIN_GROUP = C.IPV6_JOIN_GROUP sysIPV6_LEAVE_GROUP = C.IPV6_LEAVE_GROUP sysIPV6_PKTINFO = C.IPV6_PKTINFO sysIPV6_HOPLIMIT = C.IPV6_HOPLIMIT sysIPV6_NEXTHOP = C.IPV6_NEXTHOP sysIPV6_HOPOPTS = C.IPV6_HOPOPTS sysIPV6_DSTOPTS = C.IPV6_DSTOPTS sysIPV6_RTHDR = C.IPV6_RTHDR sysIPV6_RTHDRDSTOPTS = C.IPV6_RTHDRDSTOPTS sysIPV6_RECVPKTINFO = C.IPV6_RECVPKTINFO sysIPV6_RECVHOPLIMIT = C.IPV6_RECVHOPLIMIT sysIPV6_RECVHOPOPTS = C.IPV6_RECVHOPOPTS sysIPV6_RECVRTHDR = C.IPV6_RECVRTHDR sysIPV6_RECVRTHDRDSTOPTS = C.IPV6_RECVRTHDRDSTOPTS sysIPV6_CHECKSUM = C.IPV6_CHECKSUM sysIPV6_RECVTCLASS = C.IPV6_RECVTCLASS sysIPV6_USE_MIN_MTU = C.IPV6_USE_MIN_MTU sysIPV6_DONTFRAG = C.IPV6_DONTFRAG sysIPV6_SEC_OPT = C.IPV6_SEC_OPT sysIPV6_SRC_PREFERENCES = C.IPV6_SRC_PREFERENCES sysIPV6_RECVPATHMTU = C.IPV6_RECVPATHMTU sysIPV6_PATHMTU = C.IPV6_PATHMTU sysIPV6_TCLASS = C.IPV6_TCLASS sysIPV6_V6ONLY = C.IPV6_V6ONLY sysIPV6_RECVDSTOPTS = C.IPV6_RECVDSTOPTS sysIPV6_PREFER_SRC_HOME = C.IPV6_PREFER_SRC_HOME sysIPV6_PREFER_SRC_COA = C.IPV6_PREFER_SRC_COA sysIPV6_PREFER_SRC_PUBLIC = C.IPV6_PREFER_SRC_PUBLIC sysIPV6_PREFER_SRC_TMP = C.IPV6_PREFER_SRC_TMP sysIPV6_PREFER_SRC_NONCGA = C.IPV6_PREFER_SRC_NONCGA sysIPV6_PREFER_SRC_CGA = C.IPV6_PREFER_SRC_CGA sysIPV6_PREFER_SRC_MIPMASK = C.IPV6_PREFER_SRC_MIPMASK sysIPV6_PREFER_SRC_MIPDEFAULT = C.IPV6_PREFER_SRC_MIPDEFAULT sysIPV6_PREFER_SRC_TMPMASK = C.IPV6_PREFER_SRC_TMPMASK sysIPV6_PREFER_SRC_TMPDEFAULT = C.IPV6_PREFER_SRC_TMPDEFAULT sysIPV6_PREFER_SRC_CGAMASK = C.IPV6_PREFER_SRC_CGAMASK sysIPV6_PREFER_SRC_CGADEFAULT = C.IPV6_PREFER_SRC_CGADEFAULT sysIPV6_PREFER_SRC_MASK = C.IPV6_PREFER_SRC_MASK sysIPV6_PREFER_SRC_DEFAULT = C.IPV6_PREFER_SRC_DEFAULT sysIPV6_BOUND_IF = C.IPV6_BOUND_IF sysIPV6_UNSPEC_SRC = C.IPV6_UNSPEC_SRC sysICMP6_FILTER = C.ICMP6_FILTER sysSizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 sysSizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo sysSizeofIPv6Mtuinfo = C.sizeof_struct_ip6_mtuinfo sysSizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq sysSizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) type sysSockaddrInet6 C.struct_sockaddr_in6 type sysInet6Pktinfo C.struct_in6_pktinfo type sysIPv6Mtuinfo C.struct_ip6_mtuinfo type sysIPv6Mreq C.struct_ipv6_mreq type sysICMPv6Filter C.struct_icmp6_filter ================================================ FILE: vendor/golang.org/x/net/ipv6/dgramopt_posix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd windows package ipv6 import ( "net" "syscall" ) // MulticastHopLimit returns the hop limit field value for outgoing // multicast packets. func (c *dgramOpt) MulticastHopLimit() (int, error) { if !c.ok() { return 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return 0, err } return getInt(fd, &sockOpts[ssoMulticastHopLimit]) } // SetMulticastHopLimit sets the hop limit field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastHopLimit(hoplim int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoMulticastHopLimit], hoplim) } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { if !c.ok() { return nil, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return nil, err } return getInterface(fd, &sockOpts[ssoMulticastInterface]) } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInterface(fd, &sockOpts[ssoMulticastInterface], ifi) } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { if !c.ok() { return false, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return false, err } on, err := getInt(fd, &sockOpts[ssoMulticastLoopback]) if err != nil { return false, err } return on == 1, nil } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoMulticastLoopback], boolint(on)) } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } return setGroup(fd, &sockOpts[ssoJoinGroup], ifi, grp) } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } return setGroup(fd, &sockOpts[ssoLeaveGroup], ifi, grp) } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoJoinSourceGroup], ifi, grp, src) } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoLeaveSourceGroup], ifi, grp, src) } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoBlockSourceGroup], ifi, grp, src) } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } grp := netAddrToIP16(group) if grp == nil { return errMissingAddress } src := netAddrToIP16(source) if src == nil { return errMissingAddress } return setSourceGroup(fd, &sockOpts[ssoUnblockSourceGroup], ifi, grp, src) } // Checksum reports whether the kernel will compute, store or verify a // checksum for both incoming and outgoing packets. If on is true, it // returns an offset in bytes into the data of where the checksum // field is located. func (c *dgramOpt) Checksum() (on bool, offset int, err error) { if !c.ok() { return false, 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return false, 0, err } offset, err = getInt(fd, &sockOpts[ssoChecksum]) if err != nil { return false, 0, err } if offset < 0 { return false, 0, nil } return true, offset, nil } // SetChecksum enables the kernel checksum processing. If on is ture, // the offset should be an offset in bytes into the data of where the // checksum field is located. func (c *dgramOpt) SetChecksum(on bool, offset int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } if !on { offset = -1 } return setInt(fd, &sockOpts[ssoChecksum], offset) } // ICMPFilter returns an ICMP filter. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { if !c.ok() { return nil, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return nil, err } return getICMPFilter(fd, &sockOpts[ssoICMPFilter]) } // SetICMPFilter deploys the ICMP filter. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setICMPFilter(fd, &sockOpts[ssoICMPFilter], f) } ================================================ FILE: vendor/golang.org/x/net/ipv6/dgramopt_stub.go ================================================ // 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 nacl plan9 solaris package ipv6 import "net" // MulticastHopLimit returns the hop limit field value for outgoing // multicast packets. func (c *dgramOpt) MulticastHopLimit() (int, error) { return 0, errOpNoSupport } // SetMulticastHopLimit sets the hop limit field value for future // outgoing multicast packets. func (c *dgramOpt) SetMulticastHopLimit(hoplim int) error { return errOpNoSupport } // MulticastInterface returns the default interface for multicast // packet transmissions. func (c *dgramOpt) MulticastInterface() (*net.Interface, error) { return nil, errOpNoSupport } // SetMulticastInterface sets the default interface for future // multicast packet transmissions. func (c *dgramOpt) SetMulticastInterface(ifi *net.Interface) error { return errOpNoSupport } // MulticastLoopback reports whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) MulticastLoopback() (bool, error) { return false, errOpNoSupport } // SetMulticastLoopback sets whether transmitted multicast packets // should be copied and send back to the originator. func (c *dgramOpt) SetMulticastLoopback(on bool) error { return errOpNoSupport } // JoinGroup joins the group address group on the interface ifi. // By default all sources that can cast data to group are accepted. // It's possible to mute and unmute data transmission from a specific // source by using ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup. // JoinGroup uses the system assigned multicast interface when ifi is // nil, although this is not recommended because the assignment // depends on platforms and sometimes it might require routing // configuration. func (c *dgramOpt) JoinGroup(ifi *net.Interface, group net.Addr) error { return errOpNoSupport } // LeaveGroup leaves the group address group on the interface ifi // regardless of whether the group is any-source group or // source-specific group. func (c *dgramOpt) LeaveGroup(ifi *net.Interface, group net.Addr) error { return errOpNoSupport } // JoinSourceSpecificGroup joins the source-specific group comprising // group and source on the interface ifi. // JoinSourceSpecificGroup uses the system assigned multicast // interface when ifi is nil, although this is not recommended because // the assignment depends on platforms and sometimes it might require // routing configuration. func (c *dgramOpt) JoinSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // LeaveSourceSpecificGroup leaves the source-specific group on the // interface ifi. func (c *dgramOpt) LeaveSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // ExcludeSourceSpecificGroup excludes the source-specific group from // the already joined any-source groups by JoinGroup on the interface // ifi. func (c *dgramOpt) ExcludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // IncludeSourceSpecificGroup includes the excluded source-specific // group by ExcludeSourceSpecificGroup again on the interface ifi. func (c *dgramOpt) IncludeSourceSpecificGroup(ifi *net.Interface, group, source net.Addr) error { return errOpNoSupport } // Checksum reports whether the kernel will compute, store or verify a // checksum for both incoming and outgoing packets. If on is true, it // returns an offset in bytes into the data of where the checksum // field is located. func (c *dgramOpt) Checksum() (on bool, offset int, err error) { return false, 0, errOpNoSupport } // SetChecksum enables the kernel checksum processing. If on is ture, // the offset should be an offset in bytes into the data of where the // checksum field is located. func (c *dgramOpt) SetChecksum(on bool, offset int) error { return errOpNoSupport } // ICMPFilter returns an ICMP filter. func (c *dgramOpt) ICMPFilter() (*ICMPFilter, error) { return nil, errOpNoSupport } // SetICMPFilter deploys the ICMP filter. func (c *dgramOpt) SetICMPFilter(f *ICMPFilter) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv6/doc.go ================================================ // 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 ipv6 implements IP-level socket options for the Internet // Protocol version 6. // // The package provides IP-level socket options that allow // manipulation of IPv6 facilities. // // The IPv6 protocol is defined in RFC 2460. // Basic and advanced socket interface extensions are defined in RFC // 3493 and RFC 3542. // Socket interface extensions for multicast source filters are // defined in RFC 3678. // MLDv1 and MLDv2 are defined in RFC 2710 and RFC 3810. // Source-specific multicast is defined in RFC 4607. // // // Unicasting // // The options for unicasting are available for net.TCPConn, // net.UDPConn and net.IPConn which are created as network connections // that use the IPv6 transport. When a single TCP connection carrying // a data flow of multiple packets needs to indicate the flow is // important, ipv6.Conn is used to set the traffic class field on the // IPv6 header for each packet. // // ln, err := net.Listen("tcp6", "[::]:1024") // if err != nil { // // error handling // } // defer ln.Close() // for { // c, err := ln.Accept() // if err != nil { // // error handling // } // go func(c net.Conn) { // defer c.Close() // // The outgoing packets will be labeled DiffServ assured forwarding // class 1 low drop precedence, known as AF11 packets. // // if err := ipv6.NewConn(c).SetTrafficClass(DiffServAF11); err != nil { // // error handling // } // if _, err := c.Write(data); err != nil { // // error handling // } // }(c) // } // // // Multicasting // // The options for multicasting are available for net.UDPConn and // net.IPconn which are created as network connections that use the // IPv6 transport. A few network facilities must be prepared before // you begin multicasting, at a minimum joining network interfaces and // multicast groups. // // en0, err := net.InterfaceByName("en0") // if err != nil { // // error handling // } // en1, err := net.InterfaceByIndex(911) // if err != nil { // // error handling // } // group := net.ParseIP("ff02::114") // // First, an application listens to an appropriate address with an // appropriate service port. // // c, err := net.ListenPacket("udp6", "[::]:1024") // if err != nil { // // error handling // } // defer c.Close() // // Second, the application joins multicast groups, starts listening to // the groups on the specified network interfaces. Note that the // service port for transport layer protocol does not matter with this // operation as joining groups affects only network and link layer // protocols, such as IPv6 and Ethernet. // // p := ipv6.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: group}); err != nil { // // error handling // } // // The application might set per packet control message transmissions // between the protocol stack within the kernel. When the application // needs a destination address on an incoming packet, // SetControlMessage of ipv6.PacketConn is used to enable control // message transmissons. // // if err := p.SetControlMessage(ipv6.FlagDst, true); err != nil { // // error handling // } // // The application could identify whether the received packets are // of interest by using the control message that contains the // destination address of the received packet. // // b := make([]byte, 1500) // for { // n, rcm, src, err := p.ReadFrom(b) // if err != nil { // // error handling // } // if rcm.Dst.IsMulticast() { // if rcm.Dst.Equal(group) { // // joined group, do something // } else { // // unknown group, discard // continue // } // } // // The application can also send both unicast and multicast packets. // // p.SetTrafficClass(DiffServCS0) // p.SetHopLimit(16) // if _, err := p.WriteTo(data[:n], nil, src); err != nil { // // error handling // } // dst := &net.UDPAddr{IP: group, Port: 1024} // wcm := ipv6.ControlMessage{TrafficClass: DiffServCS7, HopLimit: 1} // for _, ifi := range []*net.Interface{en0, en1} { // wcm.IfIndex = ifi.Index // if _, err := p.WriteTo(data[:n], &wcm, dst); err != nil { // // error handling // } // } // } // // // More multicasting // // An application that uses PacketConn may join multiple multicast // groups. For example, a UDP listener with port 1024 might join two // different groups across over two different network interfaces by // using: // // c, err := net.ListenPacket("udp6", "[::]:1024") // if err != nil { // // error handling // } // defer c.Close() // p := ipv6.NewPacketConn(c) // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::1:114")}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil { // // error handling // } // if err := p.JoinGroup(en1, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}); err != nil { // // error handling // } // // It is possible for multiple UDP listeners that listen on the same // UDP port to join the same multicast group. The net package will // provide a socket that listens to a wildcard address with reusable // UDP port when an appropriate multicast address prefix is passed to // the net.ListenPacket or net.ListenUDP. // // c1, err := net.ListenPacket("udp6", "[ff02::]:1024") // if err != nil { // // error handling // } // defer c1.Close() // c2, err := net.ListenPacket("udp6", "[ff02::]:1024") // if err != nil { // // error handling // } // defer c2.Close() // p1 := ipv6.NewPacketConn(c1) // if err := p1.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { // // error handling // } // p2 := ipv6.NewPacketConn(c2) // if err := p2.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { // // error handling // } // // Also it is possible for the application to leave or rejoin a // multicast group on the network interface. // // if err := p.LeaveGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff02::114")}); err != nil { // // error handling // } // if err := p.JoinGroup(en0, &net.UDPAddr{IP: net.ParseIP("ff01::114")}); err != nil { // // error handling // } // // // Source-specific multicasting // // An application that uses PacketConn on MLDv2 supported platform is // able to join source-specific multicast groups. // The application may use JoinSourceSpecificGroup and // LeaveSourceSpecificGroup for the operation known as "include" mode, // // ssmgroup := net.UDPAddr{IP: net.ParseIP("ff32::8000:9")} // ssmsource := net.UDPAddr{IP: net.ParseIP("fe80::cafe")} // if err := p.JoinSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // if err := p.LeaveSourceSpecificGroup(en0, &ssmgroup, &ssmsource); err != nil { // // error handling // } // // or JoinGroup, ExcludeSourceSpecificGroup, // IncludeSourceSpecificGroup and LeaveGroup for the operation known // as "exclude" mode. // // exclsource := net.UDPAddr{IP: net.ParseIP("fe80::dead")} // if err := p.JoinGroup(en0, &ssmgroup); err != nil { // // error handling // } // if err := p.ExcludeSourceSpecificGroup(en0, &ssmgroup, &exclsource); err != nil { // // error handling // } // if err := p.LeaveGroup(en0, &ssmgroup); err != nil { // // error handling // } // // Note that it depends on each platform implementation what happens // when an application which runs on MLDv2 unsupported platform uses // JoinSourceSpecificGroup and LeaveSourceSpecificGroup. // In general the platform tries to fall back to conversations using // MLDv1 and starts to listen to multicast traffic. // In the fallback case, ExcludeSourceSpecificGroup and // IncludeSourceSpecificGroup may return an error. package ipv6 // import "golang.org/x/net/ipv6" ================================================ FILE: vendor/golang.org/x/net/ipv6/endpoint.go ================================================ // 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 ipv6 import ( "net" "syscall" "time" ) // A Conn represents a network endpoint that uses IPv6 transport. // It allows to set basic IP-level socket options such as traffic // class and hop limit. type Conn struct { genericOpt } type genericOpt struct { net.Conn } func (c *genericOpt) ok() bool { return c != nil && c.Conn != nil } // PathMTU returns a path MTU value for the destination associated // with the endpoint. func (c *Conn) PathMTU() (int, error) { if !c.genericOpt.ok() { return 0, syscall.EINVAL } fd, err := c.genericOpt.sysfd() if err != nil { return 0, err } _, mtu, err := getMTUInfo(fd, &sockOpts[ssoPathMTU]) if err != nil { return 0, err } return mtu, nil } // NewConn returns a new Conn. func NewConn(c net.Conn) *Conn { return &Conn{ genericOpt: genericOpt{Conn: c}, } } // A PacketConn represents a packet network endpoint that uses IPv6 // transport. It is used to control several IP-level socket options // including IPv6 header manipulation. It also provides datagram // based network I/O methods specific to the IPv6 and higher layer // protocols such as OSPF, GRE, and UDP. type PacketConn struct { genericOpt dgramOpt payloadHandler } type dgramOpt struct { net.PacketConn } func (c *dgramOpt) ok() bool { return c != nil && c.PacketConn != nil } // SetControlMessage allows to receive the per packet basis IP-level // socket options. func (c *PacketConn) SetControlMessage(cf ControlFlags, on bool) error { if !c.payloadHandler.ok() { return syscall.EINVAL } fd, err := c.payloadHandler.sysfd() if err != nil { return err } return setControlMessage(fd, &c.payloadHandler.rawOpt, cf, on) } // SetDeadline sets the read and write deadlines associated with the // endpoint. func (c *PacketConn) SetDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.SetDeadline(t) } // SetReadDeadline sets the read deadline associated with the // endpoint. func (c *PacketConn) SetReadDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.SetReadDeadline(t) } // SetWriteDeadline sets the write deadline associated with the // endpoint. func (c *PacketConn) SetWriteDeadline(t time.Time) error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.SetWriteDeadline(t) } // Close closes the endpoint. func (c *PacketConn) Close() error { if !c.payloadHandler.ok() { return syscall.EINVAL } return c.payloadHandler.Close() } // NewPacketConn returns a new PacketConn using c as its underlying // transport. func NewPacketConn(c net.PacketConn) *PacketConn { return &PacketConn{ genericOpt: genericOpt{Conn: c.(net.Conn)}, dgramOpt: dgramOpt{PacketConn: c}, payloadHandler: payloadHandler{PacketConn: c}, } } ================================================ FILE: vendor/golang.org/x/net/ipv6/example_test.go ================================================ // 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 ipv6_test import ( "fmt" "log" "net" "os" "time" "golang.org/x/net/icmp" "golang.org/x/net/ipv6" ) func ExampleConn_markingTCP() { ln, err := net.Listen("tcp6", "[::]:1024") if err != nil { log.Fatal(err) } defer ln.Close() for { c, err := ln.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { defer c.Close() p := ipv6.NewConn(c) if err := p.SetTrafficClass(0x28); err != nil { // DSCP AF11 log.Fatal(err) } if err := p.SetHopLimit(128); err != nil { log.Fatal(err) } if _, err := c.Write([]byte("HELLO-R-U-THERE-ACK")); err != nil { log.Fatal(err) } }(c) } } func ExamplePacketConn_servingOneShotMulticastDNS() { c, err := net.ListenPacket("udp6", "[::]:5353") // mDNS over UDP if err != nil { log.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } mDNSLinkLocal := net.UDPAddr{IP: net.ParseIP("ff02::fb")} if err := p.JoinGroup(en0, &mDNSLinkLocal); err != nil { log.Fatal(err) } defer p.LeaveGroup(en0, &mDNSLinkLocal) if err := p.SetControlMessage(ipv6.FlagDst|ipv6.FlagInterface, true); err != nil { log.Fatal(err) } var wcm ipv6.ControlMessage b := make([]byte, 1500) for { _, rcm, peer, err := p.ReadFrom(b) if err != nil { log.Fatal(err) } if !rcm.Dst.IsMulticast() || !rcm.Dst.Equal(mDNSLinkLocal.IP) { continue } wcm.IfIndex = rcm.IfIndex answers := []byte("FAKE-MDNS-ANSWERS") // fake mDNS answers, you need to implement this if _, err := p.WriteTo(answers, &wcm, peer); err != nil { log.Fatal(err) } } } func ExamplePacketConn_tracingIPPacketRoute() { // Tracing an IP packet route to www.google.com. const host = "www.google.com" ips, err := net.LookupIP(host) if err != nil { log.Fatal(err) } var dst net.IPAddr for _, ip := range ips { if ip.To16() != nil && ip.To4() == nil { dst.IP = ip fmt.Printf("using %v for tracing an IP packet route to %s\n", dst.IP, host) break } } if dst.IP == nil { log.Fatal("no AAAA record found") } c, err := net.ListenPacket("ip6:58", "::") // ICMP for IPv6 if err != nil { log.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) if err := p.SetControlMessage(ipv6.FlagHopLimit|ipv6.FlagSrc|ipv6.FlagDst|ipv6.FlagInterface, true); err != nil { log.Fatal(err) } wm := icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Data: []byte("HELLO-R-U-THERE"), }, } var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeTimeExceeded) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { log.Fatal(err) } var wcm ipv6.ControlMessage rb := make([]byte, 1500) for i := 1; i <= 64; i++ { // up to 64 hops wm.Body.(*icmp.Echo).Seq = i wb, err := wm.Marshal(nil) if err != nil { log.Fatal(err) } // In the real world usually there are several // multiple traffic-engineered paths for each hop. // You may need to probe a few times to each hop. begin := time.Now() wcm.HopLimit = i if _, err := p.WriteTo(wb, &wcm, &dst); err != nil { log.Fatal(err) } if err := p.SetReadDeadline(time.Now().Add(3 * time.Second)); err != nil { log.Fatal(err) } n, rcm, peer, err := p.ReadFrom(rb) if err != nil { if err, ok := err.(net.Error); ok && err.Timeout() { fmt.Printf("%v\t*\n", i) continue } log.Fatal(err) } rm, err := icmp.ParseMessage(58, rb[:n]) if err != nil { log.Fatal(err) } rtt := time.Since(begin) // In the real world you need to determine whether the // received message is yours using ControlMessage.Src, // ControlMesage.Dst, icmp.Echo.ID and icmp.Echo.Seq. switch rm.Type { case ipv6.ICMPTypeTimeExceeded: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm) case ipv6.ICMPTypeEchoReply: names, _ := net.LookupAddr(peer.String()) fmt.Printf("%d\t%v %+v %v\n\t%+v\n", i, peer, names, rtt, rcm) return } } } func ExamplePacketConn_advertisingOSPFHello() { c, err := net.ListenPacket("ip6:89", "::") // OSPF for IPv6 if err != nil { log.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) en0, err := net.InterfaceByName("en0") if err != nil { log.Fatal(err) } allSPFRouters := net.IPAddr{IP: net.ParseIP("ff02::5")} if err := p.JoinGroup(en0, &allSPFRouters); err != nil { log.Fatal(err) } defer p.LeaveGroup(en0, &allSPFRouters) hello := make([]byte, 24) // fake hello data, you need to implement this ospf := make([]byte, 16) // fake ospf header, you need to implement this ospf[0] = 3 // version 3 ospf[1] = 1 // hello packet ospf = append(ospf, hello...) if err := p.SetChecksum(true, 12); err != nil { log.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: 0xc0, // DSCP CS6 HopLimit: 1, IfIndex: en0.Index, } if _, err := p.WriteTo(ospf, &cm, &allSPFRouters); err != nil { log.Fatal(err) } } ================================================ FILE: vendor/golang.org/x/net/ipv6/gen.go ================================================ // 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 ignore //go:generate go run gen.go // This program generates system adaptation constants and types, // internet protocol constants and tables by reading template files // and IANA protocol registries. package main import ( "bytes" "encoding/xml" "fmt" "go/format" "io" "io/ioutil" "net/http" "os" "os/exec" "runtime" "strconv" "strings" ) func main() { if err := genzsys(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } if err := geniana(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func genzsys() error { defs := "defs_" + runtime.GOOS + ".go" f, err := os.Open(defs) if err != nil { if os.IsNotExist(err) { return nil } return err } f.Close() cmd := exec.Command("go", "tool", "cgo", "-godefs", defs) b, err := cmd.Output() if err != nil { return err } // The ipv6 pacakge still supports go1.2, and so we need to // take care of additional platforms in go1.3 and above for // working with go1.2. switch { case runtime.GOOS == "dragonfly" || runtime.GOOS == "solaris": b = bytes.Replace(b, []byte("package ipv6\n"), []byte("// +build "+runtime.GOOS+"\n\npackage ipv6\n"), 1) case runtime.GOOS == "linux" && (runtime.GOARCH == "arm64" || runtime.GOARCH == "ppc64" || runtime.GOARCH == "ppc64le"): b = bytes.Replace(b, []byte("package ipv6\n"), []byte("// +build "+runtime.GOOS+","+runtime.GOARCH+"\n\npackage ipv6\n"), 1) } b, err = format.Source(b) if err != nil { return err } zsys := "zsys_" + runtime.GOOS + ".go" switch runtime.GOOS { case "freebsd", "linux": zsys = "zsys_" + runtime.GOOS + "_" + runtime.GOARCH + ".go" } if err := ioutil.WriteFile(zsys, b, 0644); err != nil { return err } return nil } var registries = []struct { url string parse func(io.Writer, io.Reader) error }{ { "http://www.iana.org/assignments/icmpv6-parameters/icmpv6-parameters.xml", parseICMPv6Parameters, }, } func geniana() error { var bb bytes.Buffer fmt.Fprintf(&bb, "// go generate gen.go\n") fmt.Fprintf(&bb, "// GENERATED BY THE COMMAND ABOVE; DO NOT EDIT\n\n") fmt.Fprintf(&bb, "package ipv6\n\n") for _, r := range registries { resp, err := http.Get(r.url) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("got HTTP status code %v for %v\n", resp.StatusCode, r.url) } if err := r.parse(&bb, resp.Body); err != nil { return err } fmt.Fprintf(&bb, "\n") } b, err := format.Source(bb.Bytes()) if err != nil { return err } if err := ioutil.WriteFile("iana.go", b, 0644); err != nil { return err } return nil } func parseICMPv6Parameters(w io.Writer, r io.Reader) error { dec := xml.NewDecoder(r) var icp icmpv6Parameters if err := dec.Decode(&icp); err != nil { return err } prs := icp.escape() fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "const (\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "ICMPType%s ICMPType = %d", pr.Name, pr.Value) fmt.Fprintf(w, "// %s\n", pr.OrigName) } fmt.Fprintf(w, ")\n\n") fmt.Fprintf(w, "// %s, Updated: %s\n", icp.Title, icp.Updated) fmt.Fprintf(w, "var icmpTypes = map[ICMPType]string{\n") for _, pr := range prs { if pr.Name == "" { continue } fmt.Fprintf(w, "%d: %q,\n", pr.Value, strings.ToLower(pr.OrigName)) } fmt.Fprintf(w, "}\n") return nil } type icmpv6Parameters struct { XMLName xml.Name `xml:"registry"` Title string `xml:"title"` Updated string `xml:"updated"` Registries []struct { Title string `xml:"title"` Records []struct { Value string `xml:"value"` Name string `xml:"name"` } `xml:"record"` } `xml:"registry"` } type canonICMPv6ParamRecord struct { OrigName string Name string Value int } func (icp *icmpv6Parameters) escape() []canonICMPv6ParamRecord { id := -1 for i, r := range icp.Registries { if strings.Contains(r.Title, "Type") || strings.Contains(r.Title, "type") { id = i break } } if id < 0 { return nil } prs := make([]canonICMPv6ParamRecord, len(icp.Registries[id].Records)) sr := strings.NewReplacer( "Messages", "", "Message", "", "ICMP", "", "+", "P", "-", "", "/", "", ".", "", " ", "", ) for i, pr := range icp.Registries[id].Records { if strings.Contains(pr.Name, "Reserved") || strings.Contains(pr.Name, "Unassigned") || strings.Contains(pr.Name, "Deprecated") || strings.Contains(pr.Name, "Experiment") || strings.Contains(pr.Name, "experiment") { continue } ss := strings.Split(pr.Name, "\n") if len(ss) > 1 { prs[i].Name = strings.Join(ss, " ") } else { prs[i].Name = ss[0] } s := strings.TrimSpace(prs[i].Name) prs[i].OrigName = s prs[i].Name = sr.Replace(s) prs[i].Value, _ = strconv.Atoi(pr.Value) } return prs } ================================================ FILE: vendor/golang.org/x/net/ipv6/genericopt_posix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd windows package ipv6 import "syscall" // TrafficClass returns the traffic class field value for outgoing // packets. func (c *genericOpt) TrafficClass() (int, error) { if !c.ok() { return 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return 0, err } return getInt(fd, &sockOpts[ssoTrafficClass]) } // SetTrafficClass sets the traffic class field value for future // outgoing packets. func (c *genericOpt) SetTrafficClass(tclass int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoTrafficClass], tclass) } // HopLimit returns the hop limit field value for outgoing packets. func (c *genericOpt) HopLimit() (int, error) { if !c.ok() { return 0, syscall.EINVAL } fd, err := c.sysfd() if err != nil { return 0, err } return getInt(fd, &sockOpts[ssoHopLimit]) } // SetHopLimit sets the hop limit field value for future outgoing // packets. func (c *genericOpt) SetHopLimit(hoplim int) error { if !c.ok() { return syscall.EINVAL } fd, err := c.sysfd() if err != nil { return err } return setInt(fd, &sockOpts[ssoHopLimit], hoplim) } ================================================ FILE: vendor/golang.org/x/net/ipv6/genericopt_stub.go ================================================ // 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 nacl plan9 solaris package ipv6 // TrafficClass returns the traffic class field value for outgoing // packets. func (c *genericOpt) TrafficClass() (int, error) { return 0, errOpNoSupport } // SetTrafficClass sets the traffic class field value for future // outgoing packets. func (c *genericOpt) SetTrafficClass(tclass int) error { return errOpNoSupport } // HopLimit returns the hop limit field value for outgoing packets. func (c *genericOpt) HopLimit() (int, error) { return 0, errOpNoSupport } // SetHopLimit sets the hop limit field value for future outgoing // packets. func (c *genericOpt) SetHopLimit(hoplim int) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv6/header.go ================================================ // 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 ipv6 import ( "errors" "fmt" "net" ) const ( Version = 6 // protocol version HeaderLen = 40 // header length ) // A Header represents an IPv6 base header. type Header struct { Version int // protocol version TrafficClass int // traffic class FlowLabel int // flow label PayloadLen int // payload length NextHeader int // next header HopLimit int // hop limit Src net.IP // source address Dst net.IP // destination address } func (h *Header) String() string { if h == nil { return "" } return fmt.Sprintf("ver: %v, tclass: %#x, flowlbl: %#x, payloadlen: %v, nxthdr: %v, hoplim: %v, src: %v, dst: %v", h.Version, h.TrafficClass, h.FlowLabel, h.PayloadLen, h.NextHeader, h.HopLimit, h.Src, h.Dst) } // ParseHeader parses b as an IPv6 base header. func ParseHeader(b []byte) (*Header, error) { if len(b) < HeaderLen { return nil, errors.New("header too short") } h := &Header{ Version: int(b[0]) >> 4, TrafficClass: int(b[0]&0x0f)<<4 | int(b[1])>>4, FlowLabel: int(b[1]&0x0f)<<16 | int(b[2])<<8 | int(b[3]), PayloadLen: int(b[4])<<8 | int(b[5]), NextHeader: int(b[6]), HopLimit: int(b[7]), } h.Src = make(net.IP, net.IPv6len) copy(h.Src, b[8:24]) h.Dst = make(net.IP, net.IPv6len) copy(h.Dst, b[24:40]) return h, nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/header_test.go ================================================ // 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 ipv6_test import ( "net" "reflect" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/ipv6" ) var ( wireHeaderFromKernel = [ipv6.HeaderLen]byte{ 0x69, 0x8b, 0xee, 0xf1, 0xca, 0xfe, 0x2c, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, } testHeader = &ipv6.Header{ Version: ipv6.Version, TrafficClass: iana.DiffServAF43, FlowLabel: 0xbeef1, PayloadLen: 0xcafe, NextHeader: iana.ProtocolIPv6Frag, HopLimit: 1, Src: net.ParseIP("2001:db8:1::1"), Dst: net.ParseIP("2001:db8:2::1"), } ) func TestParseHeader(t *testing.T) { h, err := ipv6.ParseHeader(wireHeaderFromKernel[:]) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(h, testHeader) { t.Fatalf("got %#v; want %#v", h, testHeader) } } ================================================ FILE: vendor/golang.org/x/net/ipv6/helper.go ================================================ // 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 ipv6 import ( "errors" "net" ) var errOpNoSupport = errors.New("operation not supported") func boolint(b bool) int { if b { return 1 } return 0 } func netAddrToIP16(a net.Addr) net.IP { switch v := a.(type) { case *net.UDPAddr: if ip := v.IP.To16(); ip != nil && ip.To4() == nil { return ip } case *net.IPAddr: if ip := v.IP.To16(); ip != nil && ip.To4() == nil { return ip } } return nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/helper_stub.go ================================================ // 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 nacl plan9 solaris package ipv6 func (c *genericOpt) sysfd() (int, error) { return 0, errOpNoSupport } func (c *dgramOpt) sysfd() (int, error) { return 0, errOpNoSupport } func (c *payloadHandler) sysfd() (int, error) { return 0, errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv6/helper_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv6 import ( "net" "reflect" ) func (c *genericOpt) sysfd() (int, error) { switch p := c.Conn.(type) { case *net.TCPConn, *net.UDPConn, *net.IPConn: return sysfd(p) } return 0, errInvalidConnType } func (c *dgramOpt) sysfd() (int, error) { switch p := c.PacketConn.(type) { case *net.UDPConn, *net.IPConn: return sysfd(p.(net.Conn)) } return 0, errInvalidConnType } func (c *payloadHandler) sysfd() (int, error) { return sysfd(c.PacketConn.(net.Conn)) } func sysfd(c net.Conn) (int, error) { cv := reflect.ValueOf(c) switch ce := cv.Elem(); ce.Kind() { case reflect.Struct: nfd := ce.FieldByName("conn").FieldByName("fd") switch fe := nfd.Elem(); fe.Kind() { case reflect.Struct: fd := fe.FieldByName("sysfd") return int(fd.Int()), nil } } return 0, errInvalidConnType } ================================================ FILE: vendor/golang.org/x/net/ipv6/helper_windows.go ================================================ // 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 ipv6 import ( "net" "reflect" "syscall" ) func (c *genericOpt) sysfd() (syscall.Handle, error) { switch p := c.Conn.(type) { case *net.TCPConn, *net.UDPConn, *net.IPConn: return sysfd(p) } return syscall.InvalidHandle, errInvalidConnType } func (c *dgramOpt) sysfd() (syscall.Handle, error) { switch p := c.PacketConn.(type) { case *net.UDPConn, *net.IPConn: return sysfd(p.(net.Conn)) } return syscall.InvalidHandle, errInvalidConnType } func (c *payloadHandler) sysfd() (syscall.Handle, error) { return sysfd(c.PacketConn.(net.Conn)) } func sysfd(c net.Conn) (syscall.Handle, error) { cv := reflect.ValueOf(c) switch ce := cv.Elem(); ce.Kind() { case reflect.Struct: netfd := ce.FieldByName("conn").FieldByName("fd") switch fe := netfd.Elem(); fe.Kind() { case reflect.Struct: fd := fe.FieldByName("sysfd") return syscall.Handle(fd.Uint()), nil } } return syscall.InvalidHandle, errInvalidConnType } ================================================ FILE: vendor/golang.org/x/net/ipv6/iana.go ================================================ // go generate gen.go // GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package ipv6 // Internet Control Message Protocol version 6 (ICMPv6) Parameters, Updated: 2015-07-07 const ( ICMPTypeDestinationUnreachable ICMPType = 1 // Destination Unreachable ICMPTypePacketTooBig ICMPType = 2 // Packet Too Big ICMPTypeTimeExceeded ICMPType = 3 // Time Exceeded ICMPTypeParameterProblem ICMPType = 4 // Parameter Problem ICMPTypeEchoRequest ICMPType = 128 // Echo Request ICMPTypeEchoReply ICMPType = 129 // Echo Reply ICMPTypeMulticastListenerQuery ICMPType = 130 // Multicast Listener Query ICMPTypeMulticastListenerReport ICMPType = 131 // Multicast Listener Report ICMPTypeMulticastListenerDone ICMPType = 132 // Multicast Listener Done ICMPTypeRouterSolicitation ICMPType = 133 // Router Solicitation ICMPTypeRouterAdvertisement ICMPType = 134 // Router Advertisement ICMPTypeNeighborSolicitation ICMPType = 135 // Neighbor Solicitation ICMPTypeNeighborAdvertisement ICMPType = 136 // Neighbor Advertisement ICMPTypeRedirect ICMPType = 137 // Redirect Message ICMPTypeRouterRenumbering ICMPType = 138 // Router Renumbering ICMPTypeNodeInformationQuery ICMPType = 139 // ICMP Node Information Query ICMPTypeNodeInformationResponse ICMPType = 140 // ICMP Node Information Response ICMPTypeInverseNeighborDiscoverySolicitation ICMPType = 141 // Inverse Neighbor Discovery Solicitation Message ICMPTypeInverseNeighborDiscoveryAdvertisement ICMPType = 142 // Inverse Neighbor Discovery Advertisement Message ICMPTypeVersion2MulticastListenerReport ICMPType = 143 // Version 2 Multicast Listener Report ICMPTypeHomeAgentAddressDiscoveryRequest ICMPType = 144 // Home Agent Address Discovery Request Message ICMPTypeHomeAgentAddressDiscoveryReply ICMPType = 145 // Home Agent Address Discovery Reply Message ICMPTypeMobilePrefixSolicitation ICMPType = 146 // Mobile Prefix Solicitation ICMPTypeMobilePrefixAdvertisement ICMPType = 147 // Mobile Prefix Advertisement ICMPTypeCertificationPathSolicitation ICMPType = 148 // Certification Path Solicitation Message ICMPTypeCertificationPathAdvertisement ICMPType = 149 // Certification Path Advertisement Message ICMPTypeMulticastRouterAdvertisement ICMPType = 151 // Multicast Router Advertisement ICMPTypeMulticastRouterSolicitation ICMPType = 152 // Multicast Router Solicitation ICMPTypeMulticastRouterTermination ICMPType = 153 // Multicast Router Termination ICMPTypeFMIPv6 ICMPType = 154 // FMIPv6 Messages ICMPTypeRPLControl ICMPType = 155 // RPL Control Message ICMPTypeILNPv6LocatorUpdate ICMPType = 156 // ILNPv6 Locator Update Message ICMPTypeDuplicateAddressRequest ICMPType = 157 // Duplicate Address Request ICMPTypeDuplicateAddressConfirmation ICMPType = 158 // Duplicate Address Confirmation ICMPTypeMPLControl ICMPType = 159 // MPL Control Message ) // Internet Control Message Protocol version 6 (ICMPv6) Parameters, Updated: 2015-07-07 var icmpTypes = map[ICMPType]string{ 1: "destination unreachable", 2: "packet too big", 3: "time exceeded", 4: "parameter problem", 128: "echo request", 129: "echo reply", 130: "multicast listener query", 131: "multicast listener report", 132: "multicast listener done", 133: "router solicitation", 134: "router advertisement", 135: "neighbor solicitation", 136: "neighbor advertisement", 137: "redirect message", 138: "router renumbering", 139: "icmp node information query", 140: "icmp node information response", 141: "inverse neighbor discovery solicitation message", 142: "inverse neighbor discovery advertisement message", 143: "version 2 multicast listener report", 144: "home agent address discovery request message", 145: "home agent address discovery reply message", 146: "mobile prefix solicitation", 147: "mobile prefix advertisement", 148: "certification path solicitation message", 149: "certification path advertisement message", 151: "multicast router advertisement", 152: "multicast router solicitation", 153: "multicast router termination", 154: "fmipv6 messages", 155: "rpl control message", 156: "ilnpv6 locator update message", 157: "duplicate address request", 158: "duplicate address confirmation", 159: "mpl control message", } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp.go ================================================ // 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 ipv6 import "golang.org/x/net/internal/iana" // An ICMPType represents a type of ICMP message. type ICMPType int func (typ ICMPType) String() string { s, ok := icmpTypes[typ] if !ok { return "" } return s } // Protocol returns the ICMPv6 protocol number. func (typ ICMPType) Protocol() int { return iana.ProtocolIPv6ICMP } // An ICMPFilter represents an ICMP message filter for incoming // packets. The filter belongs to a packet delivery path on a host and // it cannot interact with forwarding packets or tunnel-outer packets. // // Note: RFC 2460 defines a reasonable role model. A node means a // device that implements IP. A router means a node that forwards IP // packets not explicitly addressed to itself, and a host means a node // that is not a router. type ICMPFilter struct { sysICMPv6Filter } // Accept accepts incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Accept(typ ICMPType) { f.accept(typ) } // Block blocks incoming ICMP packets including the type field value // typ. func (f *ICMPFilter) Block(typ ICMPType) { f.block(typ) } // SetAll sets the filter action to the filter. func (f *ICMPFilter) SetAll(block bool) { f.setAll(block) } // WillBlock reports whether the ICMP type will be blocked. func (f *ICMPFilter) WillBlock(typ ICMPType) bool { return f.willBlock(typ) } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp_bsd.go ================================================ // 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 dragonfly freebsd netbsd openbsd package ipv6 func (f *sysICMPv6Filter) accept(typ ICMPType) { f.Filt[typ>>5] |= 1 << (uint32(typ) & 31) } func (f *sysICMPv6Filter) block(typ ICMPType) { f.Filt[typ>>5] &^= 1 << (uint32(typ) & 31) } func (f *sysICMPv6Filter) setAll(block bool) { for i := range f.Filt { if block { f.Filt[i] = 0 } else { f.Filt[i] = 1<<32 - 1 } } } func (f *sysICMPv6Filter) willBlock(typ ICMPType) bool { return f.Filt[typ>>5]&(1<<(uint32(typ)&31)) == 0 } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp_linux.go ================================================ // 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 ipv6 func (f *sysICMPv6Filter) accept(typ ICMPType) { f.Data[typ>>5] &^= 1 << (uint32(typ) & 31) } func (f *sysICMPv6Filter) block(typ ICMPType) { f.Data[typ>>5] |= 1 << (uint32(typ) & 31) } func (f *sysICMPv6Filter) setAll(block bool) { for i := range f.Data { if block { f.Data[i] = 1<<32 - 1 } else { f.Data[i] = 0 } } } func (f *sysICMPv6Filter) willBlock(typ ICMPType) bool { return f.Data[typ>>5]&(1<<(uint32(typ)&31)) != 0 } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp_solaris.go ================================================ // 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 solaris package ipv6 func (f *sysICMPv6Filter) accept(typ ICMPType) { // TODO(mikio): implement this } func (f *sysICMPv6Filter) block(typ ICMPType) { // TODO(mikio): implement this } func (f *sysICMPv6Filter) setAll(block bool) { // TODO(mikio): implement this } func (f *sysICMPv6Filter) willBlock(typ ICMPType) bool { // TODO(mikio): implement this return false } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp_stub.go ================================================ // 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 nacl plan9 package ipv6 type sysICMPv6Filter struct { } func (f *sysICMPv6Filter) accept(typ ICMPType) { } func (f *sysICMPv6Filter) block(typ ICMPType) { } func (f *sysICMPv6Filter) setAll(block bool) { } func (f *sysICMPv6Filter) willBlock(typ ICMPType) bool { return false } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp_test.go ================================================ // 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 ipv6_test import ( "net" "reflect" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var icmpStringTests = []struct { in ipv6.ICMPType out string }{ {ipv6.ICMPTypeDestinationUnreachable, "destination unreachable"}, {256, ""}, } func TestICMPString(t *testing.T) { for _, tt := range icmpStringTests { s := tt.in.String() if s != tt.out { t.Errorf("got %s; want %s", s, tt.out) } } } func TestICMPFilter(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } var f ipv6.ICMPFilter for _, toggle := range []bool{false, true} { f.SetAll(toggle) for _, typ := range []ipv6.ICMPType{ ipv6.ICMPTypeDestinationUnreachable, ipv6.ICMPTypeEchoReply, ipv6.ICMPTypeNeighborSolicitation, ipv6.ICMPTypeDuplicateAddressConfirmation, } { f.Accept(typ) if f.WillBlock(typ) { t.Errorf("ipv6.ICMPFilter.Set(%v, false) failed", typ) } f.Block(typ) if !f.WillBlock(typ) { t.Errorf("ipv6.ICMPFilter.Set(%v, true) failed", typ) } } } } func TestSetICMPFilter(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoRequest) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } kf, err := p.ICMPFilter() if err != nil { t.Fatal(err) } if !reflect.DeepEqual(kf, &f) { t.Fatalf("got %#v; want %#v", kf, f) } } ================================================ FILE: vendor/golang.org/x/net/ipv6/icmp_windows.go ================================================ // 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 ipv6 type sysICMPv6Filter struct { // TODO(mikio): implement this } func (f *sysICMPv6Filter) accept(typ ICMPType) { // TODO(mikio): implement this } func (f *sysICMPv6Filter) block(typ ICMPType) { // TODO(mikio): implement this } func (f *sysICMPv6Filter) setAll(block bool) { // TODO(mikio): implement this } func (f *sysICMPv6Filter) willBlock(typ ICMPType) bool { // TODO(mikio): implement this return false } ================================================ FILE: vendor/golang.org/x/net/ipv6/mocktransponder_test.go ================================================ // 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 ipv6_test import ( "net" "testing" ) func connector(t *testing.T, network, addr string, done chan<- bool) { defer func() { done <- true }() c, err := net.Dial(network, addr) if err != nil { t.Error(err) return } c.Close() } func acceptor(t *testing.T, ln net.Listener, done chan<- bool) { defer func() { done <- true }() c, err := ln.Accept() if err != nil { t.Error(err) return } c.Close() } ================================================ FILE: vendor/golang.org/x/net/ipv6/multicast_test.go ================================================ // 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 ipv6_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var packetConnReadWriteMulticastUDPTests = []struct { addr string grp, src *net.UDPAddr }{ {"[ff02::]:0", &net.UDPAddr{IP: net.ParseIP("ff02::114")}, nil}, // see RFC 4727 {"[ff30::8000:0]:0", &net.UDPAddr{IP: net.ParseIP("ff30::8000:1")}, &net.UDPAddr{IP: net.IPv6loopback}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastUDP(t *testing.T) { switch runtime.GOOS { case "freebsd": // due to a bug on loopback marking // See http://www.freebsd.org/cgi/query-pr.cgi?pr=180065. t.Skipf("not supported on %s", runtime.GOOS) case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastUDPTests { c, err := net.ListenPacket("udp6", tt.addr) if err != nil { t.Fatal(err) } defer c.Close() grp := *tt.grp grp.Port = c.LocalAddr().(*net.UDPAddr).Port p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, &grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, &grp) } else { if err := p.JoinSourceSpecificGroup(ifi, &grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support MLDv2 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, &grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, IfIndex: ifi.Index, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } cm.HopLimit = i + 1 if n, err := p.WriteTo(wb, &cm, &grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatal(err) } rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } else { t.Logf("rcvd cmsg: %v", cm) } } } } var packetConnReadWriteMulticastICMPTests = []struct { grp, src *net.IPAddr }{ {&net.IPAddr{IP: net.ParseIP("ff02::114")}, nil}, // see RFC 4727 {&net.IPAddr{IP: net.ParseIP("ff30::8000:1")}, &net.IPAddr{IP: net.IPv6loopback}}, // see RFC 5771 } func TestPacketConnReadWriteMulticastICMP(t *testing.T) { switch runtime.GOOS { case "freebsd": // due to a bug on loopback marking // See http://www.freebsd.org/cgi/query-pr.cgi?pr=180065. t.Skipf("not supported on %s", runtime.GOOS) case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } for _, tt := range packetConnReadWriteMulticastICMPTests { c, err := net.ListenPacket("ip6:ipv6-icmp", "::") if err != nil { t.Fatal(err) } defer c.Close() pshicmp := icmp.IPv6PseudoHeader(c.LocalAddr().(*net.IPAddr).IP, tt.grp.IP) p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { if err := p.JoinGroup(ifi, tt.grp); err != nil { t.Fatal(err) } defer p.LeaveGroup(ifi, tt.grp) } else { if err := p.JoinSourceSpecificGroup(ifi, tt.grp, tt.src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support MLDv2 fail here t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } defer p.LeaveSourceSpecificGroup(ifi, tt.grp, tt.src) } if err := p.SetMulticastInterface(ifi); err != nil { t.Fatal(err) } if _, err := p.MulticastInterface(); err != nil { t.Fatal(err) } if err := p.SetMulticastLoopback(true); err != nil { t.Fatal(err) } if _, err := p.MulticastLoopback(); err != nil { t.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, IfIndex: ifi.Index, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } var psh []byte for i, toggle := range []bool{true, false, true} { if toggle { psh = nil if err := p.SetChecksum(true, 2); err != nil { t.Fatal(err) } } else { psh = pshicmp // Some platforms never allow to // disable the kernel checksum // processing. p.SetChecksum(false, -1) } wb, err := (&icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(psh) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } if err := p.SetDeadline(time.Now().Add(200 * time.Millisecond)); err != nil { t.Fatal(err) } cm.HopLimit = i + 1 if n, err := p.WriteTo(wb, &cm, tt.grp); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { t.Logf("rcvd cmsg: %v", cm) if m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, rb[:n]); err != nil { t.Fatal(err) } else if m.Type != ipv6.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv6.ICMPTypeEchoReply, 0) } } } } } ================================================ FILE: vendor/golang.org/x/net/ipv6/multicastlistener_test.go ================================================ // 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 ipv6_test import ( "fmt" "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var udpMultipleGroupListenerTests = []net.Addr{ &net.UDPAddr{IP: net.ParseIP("ff02::114")}, // see RFC 4727 &net.UDPAddr{IP: net.ParseIP("ff02::1:114")}, &net.UDPAddr{IP: net.ParseIP("ff02::2:114")}, } func TestUDPSinglePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } for _, gaddr := range udpMultipleGroupListenerTests { c, err := net.ListenPacket("udp6", "[::]:0") // wildcard address with non-reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip6", &ifi); !ok { continue } if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } func TestUDPMultiplePacketConnWithMultipleGroupListeners(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } for _, gaddr := range udpMultipleGroupListenerTests { c1, err := net.ListenPacket("udp6", "[ff02::]:1024") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c1.Close() c2, err := net.ListenPacket("udp6", "[ff02::]:1024") // wildcard address with reusable port if err != nil { t.Fatal(err) } defer c2.Close() var ps [2]*ipv6.PacketConn ps[0] = ipv6.NewPacketConn(c1) ps[1] = ipv6.NewPacketConn(c2) var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip6", &ifi); !ok { continue } for _, p := range ps { if err := p.JoinGroup(&ifi, gaddr); err != nil { t.Fatal(err) } } mift = append(mift, &ift[i]) } for _, ifi := range mift { for _, p := range ps { if err := p.LeaveGroup(ifi, gaddr); err != nil { t.Fatal(err) } } } } } func TestUDPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } gaddr := net.IPAddr{IP: net.ParseIP("ff02::114")} // see RFC 4727 type ml struct { c *ipv6.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip6", &ifi) if !ok { continue } c, err := net.ListenPacket("udp6", fmt.Sprintf("[%s%%%s]:1024", ip.String(), ifi.Name)) // unicast address with non-reusable port if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::") // wildcard address if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) gaddr := net.IPAddr{IP: net.ParseIP("ff02::114")} // see RFC 4727 var mift []*net.Interface ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { if _, ok := nettest.IsMulticastCapable("ip6", &ifi); !ok { continue } if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mift = append(mift, &ift[i]) } for _, ifi := range mift { if err := p.LeaveGroup(ifi, &gaddr); err != nil { t.Fatal(err) } } } func TestIPPerInterfaceSinglePacketConnWithSingleGroupListener(t *testing.T) { switch runtime.GOOS { case "darwin", "dragonfly", "openbsd": // platforms that return fe80::1%lo0: bind: can't assign requested address t.Skipf("not supported on %s", runtime.GOOS) case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } gaddr := net.IPAddr{IP: net.ParseIP("ff02::114")} // see RFC 4727 type ml struct { c *ipv6.PacketConn ifi *net.Interface } var mlt []*ml ift, err := net.Interfaces() if err != nil { t.Fatal(err) } for i, ifi := range ift { ip, ok := nettest.IsMulticastCapable("ip6", &ifi) if !ok { continue } c, err := net.ListenPacket("ip6:ipv6-icmp", fmt.Sprintf("%s%%%s", ip.String(), ifi.Name)) // unicast address if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) if err := p.JoinGroup(&ifi, &gaddr); err != nil { t.Fatal(err) } mlt = append(mlt, &ml{p, &ift[i]}) } for _, m := range mlt { if err := m.c.LeaveGroup(m.ifi, &gaddr); err != nil { t.Fatal(err) } } } ================================================ FILE: vendor/golang.org/x/net/ipv6/multicastsockopt_test.go ================================================ // 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 ipv6_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var packetConnMulticastSocketOptionTests = []struct { net, proto, addr string grp, src net.Addr }{ {"udp6", "", "[ff02::]:0", &net.UDPAddr{IP: net.ParseIP("ff02::114")}, nil}, // see RFC 4727 {"ip6", ":ipv6-icmp", "::", &net.IPAddr{IP: net.ParseIP("ff02::115")}, nil}, // see RFC 4727 {"udp6", "", "[ff30::8000:0]:0", &net.UDPAddr{IP: net.ParseIP("ff30::8000:1")}, &net.UDPAddr{IP: net.IPv6loopback}}, // see RFC 5771 {"ip6", ":ipv6-icmp", "::", &net.IPAddr{IP: net.ParseIP("ff30::8000:2")}, &net.IPAddr{IP: net.IPv6loopback}}, // see RFC 5771 } func TestPacketConnMulticastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagMulticast|net.FlagLoopback) if ifi == nil { t.Skipf("not available on %s", runtime.GOOS) } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnMulticastSocketOptionTests { if tt.net == "ip6" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() if tt.src == nil { testMulticastSocketOptions(t, p, ifi, tt.grp) } else { testSourceSpecificMulticastSocketOptions(t, p, ifi, tt.grp, tt.src) } } } type testIPv6MulticastConn interface { MulticastHopLimit() (int, error) SetMulticastHopLimit(ttl int) error MulticastLoopback() (bool, error) SetMulticastLoopback(bool) error JoinGroup(*net.Interface, net.Addr) error LeaveGroup(*net.Interface, net.Addr) error JoinSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error LeaveSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error ExcludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error IncludeSourceSpecificGroup(*net.Interface, net.Addr, net.Addr) error } func testMulticastSocketOptions(t *testing.T, c testIPv6MulticastConn, ifi *net.Interface, grp net.Addr) { const hoplim = 255 if err := c.SetMulticastHopLimit(hoplim); err != nil { t.Error(err) return } if v, err := c.MulticastHopLimit(); err != nil { t.Error(err) return } else if v != hoplim { t.Errorf("got %v; want %v", v, hoplim) return } for _, toggle := range []bool{true, false} { if err := c.SetMulticastLoopback(toggle); err != nil { t.Error(err) return } if v, err := c.MulticastLoopback(); err != nil { t.Error(err) return } else if v != toggle { t.Errorf("got %v; want %v", v, toggle) return } } if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } func testSourceSpecificMulticastSocketOptions(t *testing.T, c testIPv6MulticastConn, ifi *net.Interface, grp, src net.Addr) { // MCAST_JOIN_GROUP -> MCAST_BLOCK_SOURCE -> MCAST_UNBLOCK_SOURCE -> MCAST_LEAVE_GROUP if err := c.JoinGroup(ifi, grp); err != nil { t.Error(err) return } if err := c.ExcludeSourceSpecificGroup(ifi, grp, src); err != nil { switch runtime.GOOS { case "freebsd", "linux": default: // platforms that don't support MLDv2 fail here t.Logf("not supported on %s", runtime.GOOS) return } t.Error(err) return } if err := c.IncludeSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_SOURCE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } // MCAST_JOIN_SOURCE_GROUP -> MCAST_LEAVE_GROUP if err := c.JoinSourceSpecificGroup(ifi, grp, src); err != nil { t.Error(err) return } if err := c.LeaveGroup(ifi, grp); err != nil { t.Error(err) return } } ================================================ FILE: vendor/golang.org/x/net/ipv6/payload.go ================================================ // 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 ipv6 import "net" // A payloadHandler represents the IPv6 datagram payload handler. type payloadHandler struct { net.PacketConn rawOpt } func (c *payloadHandler) ok() bool { return c != nil && c.PacketConn != nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/payload_cmsg.go ================================================ // 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 !nacl,!plan9,!windows package ipv6 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv6 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } oob := newControlMessage(&c.rawOpt) var oobn int switch c := c.PacketConn.(type) { case *net.UDPConn: if n, oobn, _, src, err = c.ReadMsgUDP(b, oob); err != nil { return 0, nil, nil, err } case *net.IPConn: if n, oobn, _, src, err = c.ReadMsgIP(b, oob); err != nil { return 0, nil, nil, err } default: return 0, nil, nil, errInvalidConnType } if cm, err = parseControlMessage(oob[:oobn]); err != nil { return 0, nil, nil, err } if cm != nil { cm.Src = netAddrToIP16(src) } return } // WriteTo writes a payload of the IPv6 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the IPv6 header fields and the datagram path to be specified. The // cm may be nil if control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } oob := marshalControlMessage(cm) if dst == nil { return 0, errMissingAddress } switch c := c.PacketConn.(type) { case *net.UDPConn: n, _, err = c.WriteMsgUDP(b, oob, dst.(*net.UDPAddr)) case *net.IPConn: n, _, err = c.WriteMsgIP(b, oob, dst.(*net.IPAddr)) default: return 0, errInvalidConnType } if err != nil { return 0, err } return } ================================================ FILE: vendor/golang.org/x/net/ipv6/payload_nocmsg.go ================================================ // 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 nacl plan9 windows package ipv6 import ( "net" "syscall" ) // ReadFrom reads a payload of the received IPv6 datagram, from the // endpoint c, copying the payload into b. It returns the number of // bytes copied into b, the control message cm and the source address // src of the received datagram. func (c *payloadHandler) ReadFrom(b []byte) (n int, cm *ControlMessage, src net.Addr, err error) { if !c.ok() { return 0, nil, nil, syscall.EINVAL } if n, src, err = c.PacketConn.ReadFrom(b); err != nil { return 0, nil, nil, err } return } // WriteTo writes a payload of the IPv6 datagram, to the destination // address dst through the endpoint c, copying the payload from b. It // returns the number of bytes written. The control message cm allows // the IPv6 header fields and the datagram path to be specified. The // cm may be nil if control of the outgoing datagram is not required. func (c *payloadHandler) WriteTo(b []byte, cm *ControlMessage, dst net.Addr) (n int, err error) { if !c.ok() { return 0, syscall.EINVAL } if dst == nil { return 0, errMissingAddress } return c.PacketConn.WriteTo(b, dst) } ================================================ FILE: vendor/golang.org/x/net/ipv6/readwrite_test.go ================================================ // 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 ipv6_test import ( "bytes" "net" "runtime" "sync" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func benchmarkUDPListener() (net.PacketConn, net.Addr, error) { c, err := net.ListenPacket("udp6", "[::1]:0") if err != nil { return nil, nil, err } dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) if err != nil { c.Close() return nil, nil, err } return c, dst, nil } func BenchmarkReadWriteNetUDP(b *testing.B) { if !supportsIPv6 { b.Skip("ipv6 is not supported") } c, dst, err := benchmarkUDPListener() if err != nil { b.Fatal(err) } defer c.Close() wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) b.ResetTimer() for i := 0; i < b.N; i++ { benchmarkReadWriteNetUDP(b, c, wb, rb, dst) } } func benchmarkReadWriteNetUDP(b *testing.B, c net.PacketConn, wb, rb []byte, dst net.Addr) { if _, err := c.WriteTo(wb, dst); err != nil { b.Fatal(err) } if _, _, err := c.ReadFrom(rb); err != nil { b.Fatal(err) } } func BenchmarkReadWriteIPv6UDP(b *testing.B) { if !supportsIPv6 { b.Skip("ipv6 is not supported") } c, dst, err := benchmarkUDPListener() if err != nil { b.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU if err := p.SetControlMessage(cf, true); err != nil { b.Fatal(err) } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) wb, rb := []byte("HELLO-R-U-THERE"), make([]byte, 128) b.ResetTimer() for i := 0; i < b.N; i++ { benchmarkReadWriteIPv6UDP(b, p, wb, rb, dst, ifi) } } func benchmarkReadWriteIPv6UDP(b *testing.B, p *ipv6.PacketConn, wb, rb []byte, dst net.Addr, ifi *net.Interface) { cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, HopLimit: 1, } if ifi != nil { cm.IfIndex = ifi.Index } if n, err := p.WriteTo(wb, &cm, dst); err != nil { b.Fatal(err) } else if n != len(wb) { b.Fatalf("got %v; want %v", n, len(wb)) } if _, _, _, err := p.ReadFrom(rb); err != nil { b.Fatal(err) } } func TestPacketConnConcurrentReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } c, err := net.ListenPacket("udp6", "[::1]:0") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) if err != nil { t.Fatal(err) } ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU wb := []byte("HELLO-R-U-THERE") if err := p.SetControlMessage(cf, true); err != nil { // probe before test if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } var wg sync.WaitGroup reader := func() { defer wg.Done() rb := make([]byte, 128) if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Error(err) return } else if !bytes.Equal(rb[:n], wb) { t.Errorf("got %v; want %v", rb[:n], wb) return } else { t.Logf("rcvd cmsg: %v", cm) } } writer := func(toggle bool) { defer wg.Done() cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, } if ifi != nil { cm.IfIndex = ifi.Index } if err := p.SetControlMessage(cf, toggle); err != nil { t.Error(err) return } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Error(err) return } else if n != len(wb) { t.Errorf("got %v; want %v", n, len(wb)) return } } const N = 10 wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Add(2 * N) for i := 0; i < 2*N; i++ { go writer(i%2 != 0) } wg.Add(N) for i := 0; i < N; i++ { go reader() } wg.Wait() } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt.go ================================================ // 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 ipv6 // Sticky socket options const ( ssoTrafficClass = iota // header field for unicast packet, RFC 3542 ssoHopLimit // header field for unicast packet, RFC 3493 ssoMulticastInterface // outbound interface for multicast packet, RFC 3493 ssoMulticastHopLimit // header field for multicast packet, RFC 3493 ssoMulticastLoopback // loopback for multicast packet, RFC 3493 ssoReceiveTrafficClass // header field on received packet, RFC 3542 ssoReceiveHopLimit // header field on received packet, RFC 2292 or 3542 ssoReceivePacketInfo // incbound or outbound packet path, RFC 2292 or 3542 ssoReceivePathMTU // path mtu, RFC 3542 ssoPathMTU // path mtu, RFC 3542 ssoChecksum // packet checksum, RFC 2292 or 3542 ssoICMPFilter // icmp filter, RFC 2292 or 3542 ssoJoinGroup // any-source multicast, RFC 3493 ssoLeaveGroup // any-source multicast, RFC 3493 ssoJoinSourceGroup // source-specific multicast ssoLeaveSourceGroup // source-specific multicast ssoBlockSourceGroup // any-source or source-specific multicast ssoUnblockSourceGroup // any-source or source-specific multicast ssoMax ) // Sticky socket option value types const ( ssoTypeInt = iota + 1 ssoTypeInterface ssoTypeICMPFilter ssoTypeMTUInfo ssoTypeIPMreq ssoTypeGroupReq ssoTypeGroupSourceReq ) // A sockOpt represents a binding for sticky socket option. type sockOpt struct { level int // option level name int // option name, must be equal or greater than 1 typ int // option value type, must be equal or greater than 1 } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_asmreq_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv6 import ( "net" "os" "unsafe" ) func setsockoptIPMreq(fd int, opt *sockOpt, ifi *net.Interface, grp net.IP) error { var mreq sysIPv6Mreq copy(mreq.Multiaddr[:], grp) if ifi != nil { mreq.setIfindex(ifi.Index) } return os.NewSyscallError("setsockopt", setsockopt(fd, opt.level, opt.name, unsafe.Pointer(&mreq), sysSizeofIPv6Mreq)) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_asmreq_windows.go ================================================ // 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 ipv6 import ( "net" "os" "syscall" "unsafe" ) func setsockoptIPMreq(fd syscall.Handle, opt *sockOpt, ifi *net.Interface, grp net.IP) error { var mreq sysIPv6Mreq copy(mreq.Multiaddr[:], grp) if ifi != nil { mreq.setIfindex(ifi.Index) } return os.NewSyscallError("setsockopt", syscall.Setsockopt(fd, int32(opt.level), int32(opt.name), (*byte)(unsafe.Pointer(&mreq)), sysSizeofIPv6Mreq)) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_ssmreq_stub.go ================================================ // 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,!freebsd,!linux package ipv6 import "net" func setsockoptGroupReq(fd int, opt *sockOpt, ifi *net.Interface, grp net.IP) error { return errOpNoSupport } func setsockoptGroupSourceReq(fd int, opt *sockOpt, ifi *net.Interface, grp, src net.IP) error { return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_ssmreq_unix.go ================================================ // 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 freebsd linux package ipv6 import ( "net" "os" "unsafe" ) var freebsd32o64 bool func setsockoptGroupReq(fd int, opt *sockOpt, ifi *net.Interface, grp net.IP) error { var gr sysGroupReq if ifi != nil { gr.Interface = uint32(ifi.Index) } gr.setGroup(grp) var p unsafe.Pointer var l sysSockoptLen if freebsd32o64 { var d [sysSizeofGroupReq + 4]byte s := (*[sysSizeofGroupReq]byte)(unsafe.Pointer(&gr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) p = unsafe.Pointer(&d[0]) l = sysSizeofGroupReq + 4 } else { p = unsafe.Pointer(&gr) l = sysSizeofGroupReq } return os.NewSyscallError("setsockopt", setsockopt(fd, opt.level, opt.name, p, l)) } func setsockoptGroupSourceReq(fd int, opt *sockOpt, ifi *net.Interface, grp, src net.IP) error { var gsr sysGroupSourceReq if ifi != nil { gsr.Interface = uint32(ifi.Index) } gsr.setSourceGroup(grp, src) var p unsafe.Pointer var l sysSockoptLen if freebsd32o64 { var d [sysSizeofGroupSourceReq + 4]byte s := (*[sysSizeofGroupSourceReq]byte)(unsafe.Pointer(&gsr)) copy(d[:4], s[:4]) copy(d[8:], s[4:]) p = unsafe.Pointer(&d[0]) l = sysSizeofGroupSourceReq + 4 } else { p = unsafe.Pointer(&gsr) l = sysSizeofGroupSourceReq } return os.NewSyscallError("setsockopt", setsockopt(fd, opt.level, opt.name, p, l)) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_stub.go ================================================ // 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 nacl plan9 solaris package ipv6 import "net" func getMTUInfo(fd int, opt *sockOpt) (*net.Interface, int, error) { return nil, 0, errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_test.go ================================================ // 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 ipv6_test import ( "fmt" "net" "runtime" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) var supportsIPv6 bool = nettest.SupportsIPv6() func TestConnInitiatorPathMTU(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } defer ln.Close() done := make(chan bool) go acceptor(t, ln, done) c, err := net.Dial("tcp6", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() if pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels don't support IPV6_PATHMTU option t.Logf("not supported on %s", runtime.GOOS) default: t.Fatal(err) } } else { t.Logf("path mtu for %v: %v", c.RemoteAddr(), pmtu) } <-done } func TestConnResponderPathMTU(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } defer ln.Close() done := make(chan bool) go connector(t, "tcp6", ln.Addr().String(), done) c, err := ln.Accept() if err != nil { t.Fatal(err) } defer c.Close() if pmtu, err := ipv6.NewConn(c).PathMTU(); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels don't support IPV6_PATHMTU option t.Logf("not supported on %s", runtime.GOOS) default: t.Fatal(err) } } else { t.Logf("path mtu for %v: %v", c.RemoteAddr(), pmtu) } <-done } func TestPacketConnChecksum(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket(fmt.Sprintf("ip6:%d", iana.ProtocolOSPFIGP), "::") // OSPF for IPv6 if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) offset := 12 // see RFC 5340 for _, toggle := range []bool{false, true} { if err := p.SetChecksum(toggle, offset); err != nil { if toggle { t.Fatalf("ipv6.PacketConn.SetChecksum(%v, %v) failed: %v", toggle, offset, err) } else { // Some platforms never allow to disable the kernel // checksum processing. t.Logf("ipv6.PacketConn.SetChecksum(%v, %v) failed: %v", toggle, offset, err) } } if on, offset, err := p.Checksum(); err != nil { t.Fatal(err) } else { t.Logf("kernel checksum processing enabled=%v, offset=%v", on, offset) } } } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_unix.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd package ipv6 import ( "net" "os" "unsafe" ) func getInt(fd int, opt *sockOpt) (int, error) { if opt.name < 1 || opt.typ != ssoTypeInt { return 0, errOpNoSupport } var i int32 l := sysSockoptLen(4) if err := getsockopt(fd, opt.level, opt.name, unsafe.Pointer(&i), &l); err != nil { return 0, os.NewSyscallError("getsockopt", err) } return int(i), nil } func setInt(fd int, opt *sockOpt, v int) error { if opt.name < 1 || opt.typ != ssoTypeInt { return errOpNoSupport } i := int32(v) return os.NewSyscallError("setsockopt", setsockopt(fd, opt.level, opt.name, unsafe.Pointer(&i), sysSockoptLen(4))) } func getInterface(fd int, opt *sockOpt) (*net.Interface, error) { if opt.name < 1 || opt.typ != ssoTypeInterface { return nil, errOpNoSupport } var i int32 l := sysSockoptLen(4) if err := getsockopt(fd, opt.level, opt.name, unsafe.Pointer(&i), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } if i == 0 { return nil, nil } ifi, err := net.InterfaceByIndex(int(i)) if err != nil { return nil, err } return ifi, nil } func setInterface(fd int, opt *sockOpt, ifi *net.Interface) error { if opt.name < 1 || opt.typ != ssoTypeInterface { return errOpNoSupport } var i int32 if ifi != nil { i = int32(ifi.Index) } return os.NewSyscallError("setsockopt", setsockopt(fd, opt.level, opt.name, unsafe.Pointer(&i), sysSockoptLen(4))) } func getICMPFilter(fd int, opt *sockOpt) (*ICMPFilter, error) { if opt.name < 1 || opt.typ != ssoTypeICMPFilter { return nil, errOpNoSupport } var f ICMPFilter l := sysSockoptLen(sysSizeofICMPv6Filter) if err := getsockopt(fd, opt.level, opt.name, unsafe.Pointer(&f.sysICMPv6Filter), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } return &f, nil } func setICMPFilter(fd int, opt *sockOpt, f *ICMPFilter) error { if opt.name < 1 || opt.typ != ssoTypeICMPFilter { return errOpNoSupport } return os.NewSyscallError("setsockopt", setsockopt(fd, opt.level, opt.name, unsafe.Pointer(&f.sysICMPv6Filter), sysSizeofICMPv6Filter)) } func getMTUInfo(fd int, opt *sockOpt) (*net.Interface, int, error) { if opt.name < 1 || opt.typ != ssoTypeMTUInfo { return nil, 0, errOpNoSupport } var mi sysIPv6Mtuinfo l := sysSockoptLen(sysSizeofIPv6Mtuinfo) if err := getsockopt(fd, opt.level, opt.name, unsafe.Pointer(&mi), &l); err != nil { return nil, 0, os.NewSyscallError("getsockopt", err) } if mi.Addr.Scope_id == 0 { return nil, int(mi.Mtu), nil } ifi, err := net.InterfaceByIndex(int(mi.Addr.Scope_id)) if err != nil { return nil, 0, err } return ifi, int(mi.Mtu), nil } func setGroup(fd int, opt *sockOpt, ifi *net.Interface, grp net.IP) error { if opt.name < 1 { return errOpNoSupport } switch opt.typ { case ssoTypeIPMreq: return setsockoptIPMreq(fd, opt, ifi, grp) case ssoTypeGroupReq: return setsockoptGroupReq(fd, opt, ifi, grp) default: return errOpNoSupport } } func setSourceGroup(fd int, opt *sockOpt, ifi *net.Interface, grp, src net.IP) error { if opt.name < 1 || opt.typ != ssoTypeGroupSourceReq { return errOpNoSupport } return setsockoptGroupSourceReq(fd, opt, ifi, grp, src) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sockopt_windows.go ================================================ // 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 ipv6 import ( "net" "os" "syscall" "unsafe" ) func getInt(fd syscall.Handle, opt *sockOpt) (int, error) { if opt.name < 1 || opt.typ != ssoTypeInt { return 0, errOpNoSupport } var i int32 l := int32(4) if err := syscall.Getsockopt(fd, int32(opt.level), int32(opt.name), (*byte)(unsafe.Pointer(&i)), &l); err != nil { return 0, os.NewSyscallError("getsockopt", err) } return int(i), nil } func setInt(fd syscall.Handle, opt *sockOpt, v int) error { if opt.name < 1 || opt.typ != ssoTypeInt { return errOpNoSupport } i := int32(v) return os.NewSyscallError("setsockopt", syscall.Setsockopt(fd, int32(opt.level), int32(opt.name), (*byte)(unsafe.Pointer(&i)), 4)) } func getInterface(fd syscall.Handle, opt *sockOpt) (*net.Interface, error) { if opt.name < 1 || opt.typ != ssoTypeInterface { return nil, errOpNoSupport } var i int32 l := int32(4) if err := syscall.Getsockopt(fd, int32(opt.level), int32(opt.name), (*byte)(unsafe.Pointer(&i)), &l); err != nil { return nil, os.NewSyscallError("getsockopt", err) } if i == 0 { return nil, nil } ifi, err := net.InterfaceByIndex(int(i)) if err != nil { return nil, err } return ifi, nil } func setInterface(fd syscall.Handle, opt *sockOpt, ifi *net.Interface) error { if opt.name < 1 || opt.typ != ssoTypeInterface { return errOpNoSupport } var i int32 if ifi != nil { i = int32(ifi.Index) } return os.NewSyscallError("setsockopt", syscall.Setsockopt(fd, int32(opt.level), int32(opt.name), (*byte)(unsafe.Pointer(&i)), 4)) } func getICMPFilter(fd syscall.Handle, opt *sockOpt) (*ICMPFilter, error) { return nil, errOpNoSupport } func setICMPFilter(fd syscall.Handle, opt *sockOpt, f *ICMPFilter) error { return errOpNoSupport } func getMTUInfo(fd syscall.Handle, opt *sockOpt) (*net.Interface, int, error) { return nil, 0, errOpNoSupport } func setGroup(fd syscall.Handle, opt *sockOpt, ifi *net.Interface, grp net.IP) error { if opt.name < 1 || opt.typ != ssoTypeIPMreq { return errOpNoSupport } return setsockoptIPMreq(fd, opt, ifi, grp) } func setSourceGroup(fd syscall.Handle, opt *sockOpt, ifi *net.Interface, grp, src net.IP) error { // TODO(mikio): implement this return errOpNoSupport } ================================================ FILE: vendor/golang.org/x/net/ipv6/sys_bsd.go ================================================ // 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 netbsd openbsd package ipv6 import ( "net" "syscall" "golang.org/x/net/internal/iana" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sysSizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlNextHop: {sysIPV6_NEXTHOP, sysSizeofSockaddrInet6, marshalNextHop, parseNextHop}, ctlPathMTU: {sysIPV6_PATHMTU, sysSizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = [ssoMax]sockOpt{ ssoTrafficClass: {iana.ProtocolIPv6, sysIPV6_TCLASS, ssoTypeInt}, ssoHopLimit: {iana.ProtocolIPv6, sysIPV6_UNICAST_HOPS, ssoTypeInt}, ssoMulticastInterface: {iana.ProtocolIPv6, sysIPV6_MULTICAST_IF, ssoTypeInterface}, ssoMulticastHopLimit: {iana.ProtocolIPv6, sysIPV6_MULTICAST_HOPS, ssoTypeInt}, ssoMulticastLoopback: {iana.ProtocolIPv6, sysIPV6_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTrafficClass: {iana.ProtocolIPv6, sysIPV6_RECVTCLASS, ssoTypeInt}, ssoReceiveHopLimit: {iana.ProtocolIPv6, sysIPV6_RECVHOPLIMIT, ssoTypeInt}, ssoReceivePacketInfo: {iana.ProtocolIPv6, sysIPV6_RECVPKTINFO, ssoTypeInt}, ssoReceivePathMTU: {iana.ProtocolIPv6, sysIPV6_RECVPATHMTU, ssoTypeInt}, ssoPathMTU: {iana.ProtocolIPv6, sysIPV6_PATHMTU, ssoTypeMTUInfo}, ssoChecksum: {iana.ProtocolIPv6, sysIPV6_CHECKSUM, ssoTypeInt}, ssoICMPFilter: {iana.ProtocolIPv6ICMP, sysICMP6_FILTER, ssoTypeICMPFilter}, ssoJoinGroup: {iana.ProtocolIPv6, sysIPV6_JOIN_GROUP, ssoTypeIPMreq}, ssoLeaveGroup: {iana.ProtocolIPv6, sysIPV6_LEAVE_GROUP, ssoTypeIPMreq}, } ) func (sa *sysSockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *sysInet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *sysIPv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sys_darwin.go ================================================ // 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 ipv6 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlHopLimit: {sysIPV6_2292HOPLIMIT, 4, marshal2292HopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_2292PKTINFO, sysSizeofInet6Pktinfo, marshal2292PacketInfo, parsePacketInfo}, } sockOpts = [ssoMax]sockOpt{ ssoHopLimit: {iana.ProtocolIPv6, sysIPV6_UNICAST_HOPS, ssoTypeInt}, ssoMulticastInterface: {iana.ProtocolIPv6, sysIPV6_MULTICAST_IF, ssoTypeInterface}, ssoMulticastHopLimit: {iana.ProtocolIPv6, sysIPV6_MULTICAST_HOPS, ssoTypeInt}, ssoMulticastLoopback: {iana.ProtocolIPv6, sysIPV6_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveHopLimit: {iana.ProtocolIPv6, sysIPV6_2292HOPLIMIT, ssoTypeInt}, ssoReceivePacketInfo: {iana.ProtocolIPv6, sysIPV6_2292PKTINFO, ssoTypeInt}, ssoChecksum: {iana.ProtocolIPv6, sysIPV6_CHECKSUM, ssoTypeInt}, ssoICMPFilter: {iana.ProtocolIPv6ICMP, sysICMP6_FILTER, ssoTypeICMPFilter}, ssoJoinGroup: {iana.ProtocolIPv6, sysIPV6_JOIN_GROUP, ssoTypeIPMreq}, ssoLeaveGroup: {iana.ProtocolIPv6, sysIPV6_LEAVE_GROUP, ssoTypeIPMreq}, } ) func init() { // Seems like kern.osreldate is veiled on latest OS X. We use // kern.osrelease instead. osver, err := syscall.Sysctl("kern.osrelease") if err != nil { return } var i int for i = range osver { if osver[i] == '.' { break } } // The IP_PKTINFO and protocol-independent multicast API were // introduced in OS X 10.7 (Darwin 11.0.0). But it looks like // those features require OS X 10.8 (Darwin 12.0.0) and above. // See http://support.apple.com/kb/HT1633. if i > 2 || i == 2 && osver[0] >= '1' && osver[1] >= '2' { ctlOpts[ctlTrafficClass].name = sysIPV6_TCLASS ctlOpts[ctlTrafficClass].length = 4 ctlOpts[ctlTrafficClass].marshal = marshalTrafficClass ctlOpts[ctlTrafficClass].parse = parseTrafficClass ctlOpts[ctlHopLimit].name = sysIPV6_HOPLIMIT ctlOpts[ctlHopLimit].marshal = marshalHopLimit ctlOpts[ctlPacketInfo].name = sysIPV6_PKTINFO ctlOpts[ctlPacketInfo].marshal = marshalPacketInfo ctlOpts[ctlNextHop].name = sysIPV6_NEXTHOP ctlOpts[ctlNextHop].length = sysSizeofSockaddrInet6 ctlOpts[ctlNextHop].marshal = marshalNextHop ctlOpts[ctlNextHop].parse = parseNextHop ctlOpts[ctlPathMTU].name = sysIPV6_PATHMTU ctlOpts[ctlPathMTU].length = sysSizeofIPv6Mtuinfo ctlOpts[ctlPathMTU].marshal = marshalPathMTU ctlOpts[ctlPathMTU].parse = parsePathMTU sockOpts[ssoTrafficClass].level = iana.ProtocolIPv6 sockOpts[ssoTrafficClass].name = sysIPV6_TCLASS sockOpts[ssoTrafficClass].typ = ssoTypeInt sockOpts[ssoReceiveTrafficClass].level = iana.ProtocolIPv6 sockOpts[ssoReceiveTrafficClass].name = sysIPV6_RECVTCLASS sockOpts[ssoReceiveTrafficClass].typ = ssoTypeInt sockOpts[ssoReceiveHopLimit].name = sysIPV6_RECVHOPLIMIT sockOpts[ssoReceivePacketInfo].name = sysIPV6_RECVPKTINFO sockOpts[ssoReceivePathMTU].level = iana.ProtocolIPv6 sockOpts[ssoReceivePathMTU].name = sysIPV6_RECVPATHMTU sockOpts[ssoReceivePathMTU].typ = ssoTypeInt sockOpts[ssoPathMTU].level = iana.ProtocolIPv6 sockOpts[ssoPathMTU].name = sysIPV6_PATHMTU sockOpts[ssoPathMTU].typ = ssoTypeMTUInfo sockOpts[ssoJoinGroup].name = sysMCAST_JOIN_GROUP sockOpts[ssoJoinGroup].typ = ssoTypeGroupReq sockOpts[ssoLeaveGroup].name = sysMCAST_LEAVE_GROUP sockOpts[ssoLeaveGroup].typ = ssoTypeGroupReq sockOpts[ssoJoinSourceGroup].level = iana.ProtocolIPv6 sockOpts[ssoJoinSourceGroup].name = sysMCAST_JOIN_SOURCE_GROUP sockOpts[ssoJoinSourceGroup].typ = ssoTypeGroupSourceReq sockOpts[ssoLeaveSourceGroup].level = iana.ProtocolIPv6 sockOpts[ssoLeaveSourceGroup].name = sysMCAST_LEAVE_SOURCE_GROUP sockOpts[ssoLeaveSourceGroup].typ = ssoTypeGroupSourceReq sockOpts[ssoBlockSourceGroup].level = iana.ProtocolIPv6 sockOpts[ssoBlockSourceGroup].name = sysMCAST_BLOCK_SOURCE sockOpts[ssoBlockSourceGroup].typ = ssoTypeGroupSourceReq sockOpts[ssoUnblockSourceGroup].level = iana.ProtocolIPv6 sockOpts[ssoUnblockSourceGroup].name = sysMCAST_UNBLOCK_SOURCE sockOpts[ssoUnblockSourceGroup].typ = ssoTypeGroupSourceReq } } func (sa *sysSockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *sysInet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *sysIPv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } func (gr *sysGroupReq) setGroup(grp net.IP) { sa := (*sysSockaddrInet6)(unsafe.Pointer(&gr.Pad_cgo_0[0])) sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *sysGroupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sysSockaddrInet6)(unsafe.Pointer(&gsr.Pad_cgo_0[0])) sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sysSockaddrInet6)(unsafe.Pointer(&gsr.Pad_cgo_1[0])) sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sys_freebsd.go ================================================ // 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 ipv6 import ( "net" "runtime" "strings" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sysSizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlNextHop: {sysIPV6_NEXTHOP, sysSizeofSockaddrInet6, marshalNextHop, parseNextHop}, ctlPathMTU: {sysIPV6_PATHMTU, sysSizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = [ssoMax]sockOpt{ ssoTrafficClass: {iana.ProtocolIPv6, sysIPV6_TCLASS, ssoTypeInt}, ssoHopLimit: {iana.ProtocolIPv6, sysIPV6_UNICAST_HOPS, ssoTypeInt}, ssoMulticastInterface: {iana.ProtocolIPv6, sysIPV6_MULTICAST_IF, ssoTypeInterface}, ssoMulticastHopLimit: {iana.ProtocolIPv6, sysIPV6_MULTICAST_HOPS, ssoTypeInt}, ssoMulticastLoopback: {iana.ProtocolIPv6, sysIPV6_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTrafficClass: {iana.ProtocolIPv6, sysIPV6_RECVTCLASS, ssoTypeInt}, ssoReceiveHopLimit: {iana.ProtocolIPv6, sysIPV6_RECVHOPLIMIT, ssoTypeInt}, ssoReceivePacketInfo: {iana.ProtocolIPv6, sysIPV6_RECVPKTINFO, ssoTypeInt}, ssoReceivePathMTU: {iana.ProtocolIPv6, sysIPV6_RECVPATHMTU, ssoTypeInt}, ssoPathMTU: {iana.ProtocolIPv6, sysIPV6_PATHMTU, ssoTypeMTUInfo}, ssoChecksum: {iana.ProtocolIPv6, sysIPV6_CHECKSUM, ssoTypeInt}, ssoICMPFilter: {iana.ProtocolIPv6ICMP, sysICMP6_FILTER, ssoTypeICMPFilter}, ssoJoinGroup: {iana.ProtocolIPv6, sysMCAST_JOIN_GROUP, ssoTypeGroupReq}, ssoLeaveGroup: {iana.ProtocolIPv6, sysMCAST_LEAVE_GROUP, ssoTypeGroupReq}, ssoJoinSourceGroup: {iana.ProtocolIPv6, sysMCAST_JOIN_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {iana.ProtocolIPv6, sysMCAST_LEAVE_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {iana.ProtocolIPv6, sysMCAST_BLOCK_SOURCE, ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {iana.ProtocolIPv6, sysMCAST_UNBLOCK_SOURCE, ssoTypeGroupSourceReq}, } ) func init() { if runtime.GOOS == "freebsd" && runtime.GOARCH == "386" { archs, _ := syscall.Sysctl("kern.supported_archs") for _, s := range strings.Fields(archs) { if s == "amd64" { freebsd32o64 = true break } } } } func (sa *sysSockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *sysInet6Pktinfo) setIfindex(i int) { pi.Ifindex = uint32(i) } func (mreq *sysIPv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } func (gr *sysGroupReq) setGroup(grp net.IP) { sa := (*sysSockaddrInet6)(unsafe.Pointer(&gr.Group)) sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *sysGroupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sysSockaddrInet6)(unsafe.Pointer(&gsr.Group)) sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sysSockaddrInet6)(unsafe.Pointer(&gsr.Source)) sa.Len = sysSizeofSockaddrInet6 sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sys_linux.go ================================================ // 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 ipv6 import ( "net" "syscall" "unsafe" "golang.org/x/net/internal/iana" ) type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{ ctlTrafficClass: {sysIPV6_TCLASS, 4, marshalTrafficClass, parseTrafficClass}, ctlHopLimit: {sysIPV6_HOPLIMIT, 4, marshalHopLimit, parseHopLimit}, ctlPacketInfo: {sysIPV6_PKTINFO, sysSizeofInet6Pktinfo, marshalPacketInfo, parsePacketInfo}, ctlPathMTU: {sysIPV6_PATHMTU, sysSizeofIPv6Mtuinfo, marshalPathMTU, parsePathMTU}, } sockOpts = [ssoMax]sockOpt{ ssoTrafficClass: {iana.ProtocolIPv6, sysIPV6_TCLASS, ssoTypeInt}, ssoHopLimit: {iana.ProtocolIPv6, sysIPV6_UNICAST_HOPS, ssoTypeInt}, ssoMulticastInterface: {iana.ProtocolIPv6, sysIPV6_MULTICAST_IF, ssoTypeInterface}, ssoMulticastHopLimit: {iana.ProtocolIPv6, sysIPV6_MULTICAST_HOPS, ssoTypeInt}, ssoMulticastLoopback: {iana.ProtocolIPv6, sysIPV6_MULTICAST_LOOP, ssoTypeInt}, ssoReceiveTrafficClass: {iana.ProtocolIPv6, sysIPV6_RECVTCLASS, ssoTypeInt}, ssoReceiveHopLimit: {iana.ProtocolIPv6, sysIPV6_RECVHOPLIMIT, ssoTypeInt}, ssoReceivePacketInfo: {iana.ProtocolIPv6, sysIPV6_RECVPKTINFO, ssoTypeInt}, ssoReceivePathMTU: {iana.ProtocolIPv6, sysIPV6_RECVPATHMTU, ssoTypeInt}, ssoPathMTU: {iana.ProtocolIPv6, sysIPV6_PATHMTU, ssoTypeMTUInfo}, ssoChecksum: {iana.ProtocolReserved, sysIPV6_CHECKSUM, ssoTypeInt}, ssoICMPFilter: {iana.ProtocolIPv6ICMP, sysICMPV6_FILTER, ssoTypeICMPFilter}, ssoJoinGroup: {iana.ProtocolIPv6, sysMCAST_JOIN_GROUP, ssoTypeGroupReq}, ssoLeaveGroup: {iana.ProtocolIPv6, sysMCAST_LEAVE_GROUP, ssoTypeGroupReq}, ssoJoinSourceGroup: {iana.ProtocolIPv6, sysMCAST_JOIN_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoLeaveSourceGroup: {iana.ProtocolIPv6, sysMCAST_LEAVE_SOURCE_GROUP, ssoTypeGroupSourceReq}, ssoBlockSourceGroup: {iana.ProtocolIPv6, sysMCAST_BLOCK_SOURCE, ssoTypeGroupSourceReq}, ssoUnblockSourceGroup: {iana.ProtocolIPv6, sysMCAST_UNBLOCK_SOURCE, ssoTypeGroupSourceReq}, } ) func (sa *sysSockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (pi *sysInet6Pktinfo) setIfindex(i int) { pi.Ifindex = int32(i) } func (mreq *sysIPv6Mreq) setIfindex(i int) { mreq.Ifindex = int32(i) } func (gr *sysGroupReq) setGroup(grp net.IP) { sa := (*sysSockaddrInet6)(unsafe.Pointer(&gr.Group)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) } func (gsr *sysGroupSourceReq) setSourceGroup(grp, src net.IP) { sa := (*sysSockaddrInet6)(unsafe.Pointer(&gsr.Group)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], grp) sa = (*sysSockaddrInet6)(unsafe.Pointer(&gsr.Source)) sa.Family = syscall.AF_INET6 copy(sa.Addr[:], src) } ================================================ FILE: vendor/golang.org/x/net/ipv6/sys_stub.go ================================================ // 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 nacl plan9 solaris package ipv6 type sysSockoptLen int32 var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = [ssoMax]sockOpt{} ) ================================================ FILE: vendor/golang.org/x/net/ipv6/sys_windows.go ================================================ // 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 ipv6 import ( "net" "syscall" "golang.org/x/net/internal/iana" ) const ( // See ws2tcpip.h. sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PKTINFO = 0x13 sysSizeofSockaddrInet6 = 0x1c sysSizeofIPv6Mreq = 0x14 ) type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } var ( ctlOpts = [ctlMax]ctlOpt{} sockOpts = [ssoMax]sockOpt{ ssoHopLimit: {iana.ProtocolIPv6, sysIPV6_UNICAST_HOPS, ssoTypeInt}, ssoMulticastInterface: {iana.ProtocolIPv6, sysIPV6_MULTICAST_IF, ssoTypeInterface}, ssoMulticastHopLimit: {iana.ProtocolIPv6, sysIPV6_MULTICAST_HOPS, ssoTypeInt}, ssoMulticastLoopback: {iana.ProtocolIPv6, sysIPV6_MULTICAST_LOOP, ssoTypeInt}, ssoJoinGroup: {iana.ProtocolIPv6, sysIPV6_JOIN_GROUP, ssoTypeIPMreq}, ssoLeaveGroup: {iana.ProtocolIPv6, sysIPV6_LEAVE_GROUP, ssoTypeIPMreq}, } ) func (sa *sysSockaddrInet6) setSockaddr(ip net.IP, i int) { sa.Family = syscall.AF_INET6 copy(sa.Addr[:], ip) sa.Scope_id = uint32(i) } func (mreq *sysIPv6Mreq) setIfindex(i int) { mreq.Interface = uint32(i) } ================================================ FILE: vendor/golang.org/x/net/ipv6/syscall_linux_386.go ================================================ // 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 ipv6 import ( "syscall" "unsafe" ) const ( sysGETSOCKOPT = 0xf sysSETSOCKOPT = 0xe ) func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (int, syscall.Errno) func getsockopt(fd, level, name int, v unsafe.Pointer, l *sysSockoptLen) error { if _, errno := socketcall(sysGETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(unsafe.Pointer(l)), 0); errno != 0 { return error(errno) } return nil } func setsockopt(fd, level, name int, v unsafe.Pointer, l sysSockoptLen) error { if _, errno := socketcall(sysSETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(l), 0); errno != 0 { return error(errno) } return nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/syscall_unix.go ================================================ // 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 dragonfly freebsd linux,!386 netbsd openbsd package ipv6 import ( "syscall" "unsafe" ) func getsockopt(fd, level, name int, v unsafe.Pointer, l *sysSockoptLen) error { if _, _, errno := syscall.Syscall6(syscall.SYS_GETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(unsafe.Pointer(l)), 0); errno != 0 { return error(errno) } return nil } func setsockopt(fd, level, name int, v unsafe.Pointer, l sysSockoptLen) error { if _, _, errno := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(fd), uintptr(level), uintptr(name), uintptr(v), uintptr(l), 0); errno != 0 { return error(errno) } return nil } ================================================ FILE: vendor/golang.org/x/net/ipv6/thunk_linux_386.s ================================================ // 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.2 TEXT ·socketcall(SB),4,$0-36 JMP syscall·socketcall(SB) ================================================ FILE: vendor/golang.org/x/net/ipv6/unicast_test.go ================================================ // 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 ipv6_test import ( "bytes" "net" "os" "runtime" "testing" "time" "golang.org/x/net/icmp" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func TestPacketConnReadWriteUnicastUDP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } c, err := net.ListenPacket("udp6", "[::1]:0") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst, err := net.ResolveUDPAddr("udp6", c.LocalAddr().String()) if err != nil { t.Fatal(err) } cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) if ifi != nil { cm.IfIndex = ifi.Index } wb := []byte("HELLO-R-U-THERE") for i, toggle := range []bool{true, false, true} { if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } cm.HopLimit = i + 1 if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, cm, _, err := p.ReadFrom(rb); err != nil { t.Fatal(err) } else if !bytes.Equal(rb[:n], wb) { t.Fatalf("got %v; want %v", rb[:n], wb) } else { t.Logf("rcvd cmsg: %v", cm) } } } func TestPacketConnReadWriteUnicastICMP(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } if m, ok := nettest.SupportsRawIPSocket(); !ok { t.Skip(m) } c, err := net.ListenPacket("ip6:ipv6-icmp", "::1") if err != nil { t.Fatal(err) } defer c.Close() p := ipv6.NewPacketConn(c) defer p.Close() dst, err := net.ResolveIPAddr("ip6", "::1") if err != nil { t.Fatal(err) } pshicmp := icmp.IPv6PseudoHeader(c.LocalAddr().(*net.IPAddr).IP, dst.IP) cm := ipv6.ControlMessage{ TrafficClass: iana.DiffServAF11 | iana.CongestionExperienced, Src: net.IPv6loopback, } cf := ipv6.FlagTrafficClass | ipv6.FlagHopLimit | ipv6.FlagSrc | ipv6.FlagDst | ipv6.FlagInterface | ipv6.FlagPathMTU ifi := nettest.RoutedInterface("ip6", net.FlagUp|net.FlagLoopback) if ifi != nil { cm.IfIndex = ifi.Index } var f ipv6.ICMPFilter f.SetAll(true) f.Accept(ipv6.ICMPTypeEchoReply) if err := p.SetICMPFilter(&f); err != nil { t.Fatal(err) } var psh []byte for i, toggle := range []bool{true, false, true} { if toggle { psh = nil if err := p.SetChecksum(true, 2); err != nil { t.Fatal(err) } } else { psh = pshicmp // Some platforms never allow to disable the // kernel checksum processing. p.SetChecksum(false, -1) } wb, err := (&icmp.Message{ Type: ipv6.ICMPTypeEchoRequest, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Seq: i + 1, Data: []byte("HELLO-R-U-THERE"), }, }).Marshal(psh) if err != nil { t.Fatal(err) } if err := p.SetControlMessage(cf, toggle); err != nil { if nettest.ProtocolNotSupported(err) { t.Skipf("not supported on %s", runtime.GOOS) } t.Fatal(err) } cm.HopLimit = i + 1 if err := p.SetWriteDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, err := p.WriteTo(wb, &cm, dst); err != nil { t.Fatal(err) } else if n != len(wb) { t.Fatalf("got %v; want %v", n, len(wb)) } rb := make([]byte, 128) if err := p.SetReadDeadline(time.Now().Add(100 * time.Millisecond)); err != nil { t.Fatal(err) } if n, cm, _, err := p.ReadFrom(rb); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels have some limitation on receiving icmp packet through raw socket t.Logf("not supported on %s", runtime.GOOS) continue } t.Fatal(err) } else { t.Logf("rcvd cmsg: %v", cm) if m, err := icmp.ParseMessage(iana.ProtocolIPv6ICMP, rb[:n]); err != nil { t.Fatal(err) } else if m.Type != ipv6.ICMPTypeEchoReply || m.Code != 0 { t.Fatalf("got type=%v, code=%v; want type=%v, code=%v", m.Type, m.Code, ipv6.ICMPTypeEchoReply, 0) } } } } ================================================ FILE: vendor/golang.org/x/net/ipv6/unicastsockopt_test.go ================================================ // 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 ipv6_test import ( "net" "runtime" "testing" "golang.org/x/net/internal/iana" "golang.org/x/net/internal/nettest" "golang.org/x/net/ipv6" ) func TestConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } ln, err := net.Listen("tcp6", "[::1]:0") if err != nil { t.Fatal(err) } defer ln.Close() done := make(chan bool) go acceptor(t, ln, done) c, err := net.Dial("tcp6", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv6.NewConn(c)) <-done } var packetConnUnicastSocketOptionTests = []struct { net, proto, addr string }{ {"udp6", "", "[::1]:0"}, {"ip6", ":ipv6-icmp", "::1"}, } func TestPacketConnUnicastSocketOptions(t *testing.T) { switch runtime.GOOS { case "nacl", "plan9", "solaris", "windows": t.Skipf("not supported on %s", runtime.GOOS) } if !supportsIPv6 { t.Skip("ipv6 is not supported") } m, ok := nettest.SupportsRawIPSocket() for _, tt := range packetConnUnicastSocketOptionTests { if tt.net == "ip6" && !ok { t.Log(m) continue } c, err := net.ListenPacket(tt.net+tt.proto, tt.addr) if err != nil { t.Fatal(err) } defer c.Close() testUnicastSocketOptions(t, ipv6.NewPacketConn(c)) } } type testIPv6UnicastConn interface { TrafficClass() (int, error) SetTrafficClass(int) error HopLimit() (int, error) SetHopLimit(int) error } func testUnicastSocketOptions(t *testing.T, c testIPv6UnicastConn) { tclass := iana.DiffServCS0 | iana.NotECNTransport if err := c.SetTrafficClass(tclass); err != nil { switch runtime.GOOS { case "darwin": // older darwin kernels don't support IPV6_TCLASS option t.Logf("not supported on %s", runtime.GOOS) goto next } t.Fatal(err) } if v, err := c.TrafficClass(); err != nil { t.Fatal(err) } else if v != tclass { t.Fatalf("got %v; want %v", v, tclass) } next: hoplim := 255 if err := c.SetHopLimit(hoplim); err != nil { t.Fatal(err) } if v, err := c.HopLimit(); err != nil { t.Fatal(err) } else if v != hoplim { t.Fatalf("got %v; want %v", v, hoplim) } } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_darwin.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_darwin.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_2292PKTINFO = 0x13 sysIPV6_2292HOPLIMIT = 0x14 sysIPV6_2292NEXTHOP = 0x15 sysIPV6_2292HOPOPTS = 0x16 sysIPV6_2292DSTOPTS = 0x17 sysIPV6_2292RTHDR = 0x18 sysIPV6_2292PKTOPTIONS = 0x19 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RECVTCLASS = 0x23 sysIPV6_TCLASS = 0x24 sysIPV6_RTHDRDSTOPTS = 0x39 sysIPV6_RECVPKTINFO = 0x3d sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_BOUND_IF = 0x7d sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysICMPv6Filter struct { Filt [8]uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [128]byte } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [128]byte Pad_cgo_1 [128]byte } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_dragonfly.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_dragonfly.go // +build dragonfly package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysICMPv6Filter struct { Filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_freebsd_386.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_BINDANY = 0x40 sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysGroupReq struct { Interface uint32 Group sysSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Group sysSockaddrStorage Source sysSockaddrStorage } type sysICMPv6Filter struct { Filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_freebsd_amd64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_BINDANY = 0x40 sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage Source sysSockaddrStorage } type sysICMPv6Filter struct { Filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_freebsd_arm.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_freebsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PREFER_TEMPADDR = 0x3f sysIPV6_BINDANY = 0x40 sysIPV6_MSFILTER = 0x4a sysMCAST_JOIN_GROUP = 0x50 sysMCAST_LEAVE_GROUP = 0x51 sysMCAST_JOIN_SOURCE_GROUP = 0x52 sysMCAST_LEAVE_SOURCE_GROUP = 0x53 sysMCAST_BLOCK_SOURCE = 0x54 sysMCAST_UNBLOCK_SOURCE = 0x55 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrStorage struct { Len uint8 Family uint8 X__ss_pad1 [6]int8 X__ss_align int64 X__ss_pad2 [112]int8 } type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysSockaddrStorage Source sysSockaddrStorage } type sysICMPv6Filter struct { Filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_linux_386.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6FlowlabelReq = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 sysSizeofICMPv6Filter = 0x20 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type sysGroupReq struct { Interface uint32 Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPv6Filter struct { Data [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_linux_amd64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6FlowlabelReq = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPv6Filter = 0x20 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPv6Filter struct { Data [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_linux_arm.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6FlowlabelReq = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x84 sysSizeofGroupSourceReq = 0x104 sysSizeofICMPv6Filter = 0x20 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type sysGroupReq struct { Interface uint32 Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPv6Filter struct { Data [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_linux_arm64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go // +build linux,arm64 package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6FlowlabelReq = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPv6Filter = 0x20 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPv6Filter struct { Data [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_linux_ppc64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go // +build linux,ppc64 package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6FlowlabelReq = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPv6Filter = 0x20 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPv6Filter struct { Data [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_linux_ppc64le.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_linux.go // +build linux,ppc64le package ipv6 const ( sysIPV6_ADDRFORM = 0x1 sysIPV6_2292PKTINFO = 0x2 sysIPV6_2292HOPOPTS = 0x3 sysIPV6_2292DSTOPTS = 0x4 sysIPV6_2292RTHDR = 0x5 sysIPV6_2292PKTOPTIONS = 0x6 sysIPV6_CHECKSUM = 0x7 sysIPV6_2292HOPLIMIT = 0x8 sysIPV6_NEXTHOP = 0x9 sysIPV6_FLOWINFO = 0xb sysIPV6_UNICAST_HOPS = 0x10 sysIPV6_MULTICAST_IF = 0x11 sysIPV6_MULTICAST_HOPS = 0x12 sysIPV6_MULTICAST_LOOP = 0x13 sysIPV6_ADD_MEMBERSHIP = 0x14 sysIPV6_DROP_MEMBERSHIP = 0x15 sysMCAST_JOIN_GROUP = 0x2a sysMCAST_LEAVE_GROUP = 0x2d sysMCAST_JOIN_SOURCE_GROUP = 0x2e sysMCAST_LEAVE_SOURCE_GROUP = 0x2f sysMCAST_BLOCK_SOURCE = 0x2b sysMCAST_UNBLOCK_SOURCE = 0x2c sysMCAST_MSFILTER = 0x30 sysIPV6_ROUTER_ALERT = 0x16 sysIPV6_MTU_DISCOVER = 0x17 sysIPV6_MTU = 0x18 sysIPV6_RECVERR = 0x19 sysIPV6_V6ONLY = 0x1a sysIPV6_JOIN_ANYCAST = 0x1b sysIPV6_LEAVE_ANYCAST = 0x1c sysIPV6_FLOWLABEL_MGR = 0x20 sysIPV6_FLOWINFO_SEND = 0x21 sysIPV6_IPSEC_POLICY = 0x22 sysIPV6_XFRM_POLICY = 0x23 sysIPV6_RECVPKTINFO = 0x31 sysIPV6_PKTINFO = 0x32 sysIPV6_RECVHOPLIMIT = 0x33 sysIPV6_HOPLIMIT = 0x34 sysIPV6_RECVHOPOPTS = 0x35 sysIPV6_HOPOPTS = 0x36 sysIPV6_RTHDRDSTOPTS = 0x37 sysIPV6_RECVRTHDR = 0x38 sysIPV6_RTHDR = 0x39 sysIPV6_RECVDSTOPTS = 0x3a sysIPV6_DSTOPTS = 0x3b sysIPV6_RECVPATHMTU = 0x3c sysIPV6_PATHMTU = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_RECVTCLASS = 0x42 sysIPV6_TCLASS = 0x43 sysIPV6_ADDR_PREFERENCES = 0x48 sysIPV6_PREFER_SRC_TMP = 0x1 sysIPV6_PREFER_SRC_PUBLIC = 0x2 sysIPV6_PREFER_SRC_PUBTMP_DEFAULT = 0x100 sysIPV6_PREFER_SRC_COA = 0x4 sysIPV6_PREFER_SRC_HOME = 0x400 sysIPV6_PREFER_SRC_CGA = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x800 sysIPV6_MINHOPCOUNT = 0x49 sysIPV6_ORIGDSTADDR = 0x4a sysIPV6_RECVORIGDSTADDR = 0x4a sysIPV6_TRANSPARENT = 0x4b sysIPV6_UNICAST_IF = 0x4c sysICMPV6_FILTER = 0x1 sysICMPV6_FILTER_BLOCK = 0x1 sysICMPV6_FILTER_PASS = 0x2 sysICMPV6_FILTER_BLOCKOTHERS = 0x3 sysICMPV6_FILTER_PASSONLY = 0x4 sysSizeofKernelSockaddrStorage = 0x80 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6FlowlabelReq = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofGroupReq = 0x88 sysSizeofGroupSourceReq = 0x108 sysSizeofICMPv6Filter = 0x20 ) type sysKernelSockaddrStorage struct { Family uint16 X__data [126]int8 } type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex int32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6FlowlabelReq struct { Dst [16]byte /* in6_addr */ Label uint32 Action uint8 Share uint8 Flags uint16 Expires uint16 Linger uint16 X__flr_pad uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Ifindex int32 } type sysGroupReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage } type sysGroupSourceReq struct { Interface uint32 Pad_cgo_0 [4]byte Group sysKernelSockaddrStorage Source sysKernelSockaddrStorage } type sysICMPv6Filter struct { Data [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_netbsd.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_netbsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_IPSEC_POLICY = 0x1c sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_RECVTCLASS = 0x39 sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysICMPv6Filter struct { Filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_openbsd.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_openbsd.go package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x4 sysIPV6_MULTICAST_IF = 0x9 sysIPV6_MULTICAST_HOPS = 0xa sysIPV6_MULTICAST_LOOP = 0xb sysIPV6_JOIN_GROUP = 0xc sysIPV6_LEAVE_GROUP = 0xd sysIPV6_PORTRANGE = 0xe sysICMP6_FILTER = 0x12 sysIPV6_CHECKSUM = 0x1a sysIPV6_V6ONLY = 0x1b sysIPV6_RTHDRDSTOPTS = 0x23 sysIPV6_RECVPKTINFO = 0x24 sysIPV6_RECVHOPLIMIT = 0x25 sysIPV6_RECVRTHDR = 0x26 sysIPV6_RECVHOPOPTS = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_USE_MIN_MTU = 0x2a sysIPV6_RECVPATHMTU = 0x2b sysIPV6_PATHMTU = 0x2c sysIPV6_PKTINFO = 0x2e sysIPV6_HOPLIMIT = 0x2f sysIPV6_NEXTHOP = 0x30 sysIPV6_HOPOPTS = 0x31 sysIPV6_DSTOPTS = 0x32 sysIPV6_RTHDR = 0x33 sysIPV6_AUTH_LEVEL = 0x35 sysIPV6_ESP_TRANS_LEVEL = 0x36 sysIPV6_ESP_NETWORK_LEVEL = 0x37 sysIPSEC6_OUTSA = 0x38 sysIPV6_RECVTCLASS = 0x39 sysIPV6_AUTOFLOWLABEL = 0x3b sysIPV6_IPCOMP_LEVEL = 0x3c sysIPV6_TCLASS = 0x3d sysIPV6_DONTFRAG = 0x3e sysIPV6_PIPEX = 0x3f sysIPV6_RTABLE = 0x1021 sysIPV6_PORTRANGE_DEFAULT = 0x0 sysIPV6_PORTRANGE_HIGH = 0x1 sysIPV6_PORTRANGE_LOW = 0x2 sysSizeofSockaddrInet6 = 0x1c sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x20 sysSizeofIPv6Mreq = 0x14 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysICMPv6Filter struct { Filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/ipv6/zsys_solaris.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs defs_solaris.go // +build solaris package ipv6 const ( sysIPV6_UNICAST_HOPS = 0x5 sysIPV6_MULTICAST_IF = 0x6 sysIPV6_MULTICAST_HOPS = 0x7 sysIPV6_MULTICAST_LOOP = 0x8 sysIPV6_JOIN_GROUP = 0x9 sysIPV6_LEAVE_GROUP = 0xa sysIPV6_PKTINFO = 0xb sysIPV6_HOPLIMIT = 0xc sysIPV6_NEXTHOP = 0xd sysIPV6_HOPOPTS = 0xe sysIPV6_DSTOPTS = 0xf sysIPV6_RTHDR = 0x10 sysIPV6_RTHDRDSTOPTS = 0x11 sysIPV6_RECVPKTINFO = 0x12 sysIPV6_RECVHOPLIMIT = 0x13 sysIPV6_RECVHOPOPTS = 0x14 sysIPV6_RECVRTHDR = 0x16 sysIPV6_RECVRTHDRDSTOPTS = 0x17 sysIPV6_CHECKSUM = 0x18 sysIPV6_RECVTCLASS = 0x19 sysIPV6_USE_MIN_MTU = 0x20 sysIPV6_DONTFRAG = 0x21 sysIPV6_SEC_OPT = 0x22 sysIPV6_SRC_PREFERENCES = 0x23 sysIPV6_RECVPATHMTU = 0x24 sysIPV6_PATHMTU = 0x25 sysIPV6_TCLASS = 0x26 sysIPV6_V6ONLY = 0x27 sysIPV6_RECVDSTOPTS = 0x28 sysIPV6_PREFER_SRC_HOME = 0x1 sysIPV6_PREFER_SRC_COA = 0x2 sysIPV6_PREFER_SRC_PUBLIC = 0x4 sysIPV6_PREFER_SRC_TMP = 0x8 sysIPV6_PREFER_SRC_NONCGA = 0x10 sysIPV6_PREFER_SRC_CGA = 0x20 sysIPV6_PREFER_SRC_MIPMASK = 0x3 sysIPV6_PREFER_SRC_MIPDEFAULT = 0x1 sysIPV6_PREFER_SRC_TMPMASK = 0xc sysIPV6_PREFER_SRC_TMPDEFAULT = 0x4 sysIPV6_PREFER_SRC_CGAMASK = 0x30 sysIPV6_PREFER_SRC_CGADEFAULT = 0x10 sysIPV6_PREFER_SRC_MASK = 0x3f sysIPV6_PREFER_SRC_DEFAULT = 0x15 sysIPV6_BOUND_IF = 0x41 sysIPV6_UNSPEC_SRC = 0x42 sysICMP6_FILTER = 0x1 sysSizeofSockaddrInet6 = 0x20 sysSizeofInet6Pktinfo = 0x14 sysSizeofIPv6Mtuinfo = 0x24 sysSizeofIPv6Mreq = 0x14 sysSizeofICMPv6Filter = 0x20 ) type sysSockaddrInet6 struct { Family uint16 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 X__sin6_src_id uint32 } type sysInet6Pktinfo struct { Addr [16]byte /* in6_addr */ Ifindex uint32 } type sysIPv6Mtuinfo struct { Addr sysSockaddrInet6 Mtu uint32 } type sysIPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type sysICMPv6Filter struct { X__icmp6_filt [8]uint32 } ================================================ FILE: vendor/golang.org/x/net/netutil/listen.go ================================================ // 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 netutil provides network utility functions, complementing the more // common ones in the net package. package netutil // import "golang.org/x/net/netutil" import ( "net" "sync" ) // LimitListener returns a Listener that accepts at most n simultaneous // connections from the provided Listener. func LimitListener(l net.Listener, n int) net.Listener { return &limitListener{l, make(chan struct{}, n)} } type limitListener struct { net.Listener sem chan struct{} } func (l *limitListener) acquire() { l.sem <- struct{}{} } func (l *limitListener) release() { <-l.sem } func (l *limitListener) Accept() (net.Conn, error) { l.acquire() c, err := l.Listener.Accept() if err != nil { l.release() return nil, err } return &limitListenerConn{Conn: c, release: l.release}, nil } type limitListenerConn struct { net.Conn releaseOnce sync.Once release func() } func (l *limitListenerConn) Close() error { err := l.Conn.Close() l.releaseOnce.Do(l.release) return err } ================================================ FILE: vendor/golang.org/x/net/netutil/listen_test.go ================================================ // 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 go1.3 // (We only run this test on Go 1.3 because the HTTP client timeout behavior // was bad in previous releases, causing occasional deadlocks.) package netutil import ( "errors" "fmt" "io" "io/ioutil" "net" "net/http" "sync" "sync/atomic" "testing" "time" "golang.org/x/net/internal/nettest" ) func TestLimitListener(t *testing.T) { const max = 5 attempts := (nettest.MaxOpenFiles() - max) / 2 if attempts > 256 { // maximum length of accept queue is 128 by default attempts = 256 } l, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } defer l.Close() l = LimitListener(l, max) var open int32 go http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if n := atomic.AddInt32(&open, 1); n > max { t.Errorf("%d open connections, want <= %d", n, max) } defer atomic.AddInt32(&open, -1) time.Sleep(10 * time.Millisecond) fmt.Fprint(w, "some body") })) var wg sync.WaitGroup var failed int32 for i := 0; i < attempts; i++ { wg.Add(1) go func() { defer wg.Done() c := http.Client{Timeout: 3 * time.Second} r, err := c.Get("http://" + l.Addr().String()) if err != nil { t.Log(err) atomic.AddInt32(&failed, 1) return } defer r.Body.Close() io.Copy(ioutil.Discard, r.Body) }() } wg.Wait() // We expect some Gets to fail as the kernel's accept queue is filled, // but most should succeed. if int(failed) >= attempts/2 { t.Errorf("%d requests failed within %d attempts", failed, attempts) } } type errorListener struct { net.Listener } func (errorListener) Accept() (net.Conn, error) { return nil, errFake } var errFake = errors.New("fake error from errorListener") // This used to hang. func TestLimitListenerError(t *testing.T) { donec := make(chan bool, 1) go func() { const n = 2 ll := LimitListener(errorListener{}, n) for i := 0; i < n+1; i++ { _, err := ll.Accept() if err != errFake { t.Fatalf("Accept error = %v; want errFake", err) } } donec <- true }() select { case <-donec: case <-time.After(5 * time.Second): t.Fatal("timeout. deadlock?") } } ================================================ FILE: vendor/golang.org/x/net/proxy/direct.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/net/proxy/per_host.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/net/proxy/per_host_test.go ================================================ // 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" "net" "reflect" "testing" ) type recordingProxy struct { addrs []string } func (r *recordingProxy) Dial(network, addr string) (net.Conn, error) { r.addrs = append(r.addrs, addr) return nil, errors.New("recordingProxy") } func TestPerHost(t *testing.T) { var def, bypass recordingProxy perHost := NewPerHost(&def, &bypass) perHost.AddFromString("localhost,*.zone,127.0.0.1,10.0.0.1/8,1000::/16") expectedDef := []string{ "example.com:123", "1.2.3.4:123", "[1001::]:123", } expectedBypass := []string{ "localhost:123", "zone:123", "foo.zone:123", "127.0.0.1:123", "10.1.2.3:123", "[1000::]:123", } for _, addr := range expectedDef { perHost.Dial("tcp", addr) } for _, addr := range expectedBypass { perHost.Dial("tcp", addr) } if !reflect.DeepEqual(expectedDef, def.addrs) { t.Errorf("Hosts which went to the default proxy didn't match. Got %v, want %v", def.addrs, expectedDef) } if !reflect.DeepEqual(expectedBypass, bypass.addrs) { t.Errorf("Hosts which went to the bypass proxy didn't match. Got %v, want %v", bypass.addrs, expectedBypass) } } ================================================ FILE: vendor/golang.org/x/net/proxy/proxy.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/net/proxy/proxy_test.go ================================================ // 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 ( "io" "net" "net/url" "strconv" "sync" "testing" ) func TestFromURL(t *testing.T) { endSystem, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer endSystem.Close() gateway, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer gateway.Close() var wg sync.WaitGroup wg.Add(1) go socks5Gateway(t, gateway, endSystem, socks5Domain, &wg) url, err := url.Parse("socks5://user:password@" + gateway.Addr().String()) if err != nil { t.Fatalf("url.Parse failed: %v", err) } proxy, err := FromURL(url, Direct) if err != nil { t.Fatalf("FromURL failed: %v", err) } _, port, err := net.SplitHostPort(endSystem.Addr().String()) if err != nil { t.Fatalf("net.SplitHostPort failed: %v", err) } if c, err := proxy.Dial("tcp", "localhost:"+port); err != nil { t.Fatalf("FromURL.Dial failed: %v", err) } else { c.Close() } wg.Wait() } func TestSOCKS5(t *testing.T) { endSystem, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer endSystem.Close() gateway, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("net.Listen failed: %v", err) } defer gateway.Close() var wg sync.WaitGroup wg.Add(1) go socks5Gateway(t, gateway, endSystem, socks5IP4, &wg) proxy, err := SOCKS5("tcp", gateway.Addr().String(), nil, Direct) if err != nil { t.Fatalf("SOCKS5 failed: %v", err) } if c, err := proxy.Dial("tcp", endSystem.Addr().String()); err != nil { t.Fatalf("SOCKS5.Dial failed: %v", err) } else { c.Close() } wg.Wait() } func socks5Gateway(t *testing.T, gateway, endSystem net.Listener, typ byte, wg *sync.WaitGroup) { defer wg.Done() c, err := gateway.Accept() if err != nil { t.Errorf("net.Listener.Accept failed: %v", err) return } defer c.Close() b := make([]byte, 32) var n int if typ == socks5Domain { n = 4 } else { n = 3 } if _, err := io.ReadFull(c, b[:n]); err != nil { t.Errorf("io.ReadFull failed: %v", err) return } if _, err := c.Write([]byte{socks5Version, socks5AuthNone}); err != nil { t.Errorf("net.Conn.Write failed: %v", err) return } if typ == socks5Domain { n = 16 } else { n = 10 } if _, err := io.ReadFull(c, b[:n]); err != nil { t.Errorf("io.ReadFull failed: %v", err) return } if b[0] != socks5Version || b[1] != socks5Connect || b[2] != 0x00 || b[3] != typ { t.Errorf("got an unexpected packet: %#02x %#02x %#02x %#02x", b[0], b[1], b[2], b[3]) return } if typ == socks5Domain { copy(b[:5], []byte{socks5Version, 0x00, 0x00, socks5Domain, 9}) b = append(b, []byte("localhost")...) } else { copy(b[:4], []byte{socks5Version, 0x00, 0x00, socks5IP4}) } host, port, err := net.SplitHostPort(endSystem.Addr().String()) if err != nil { t.Errorf("net.SplitHostPort failed: %v", err) return } b = append(b, []byte(net.ParseIP(host).To4())...) p, err := strconv.Atoi(port) if err != nil { t.Errorf("strconv.Atoi failed: %v", err) return } b = append(b, []byte{byte(p >> 8), byte(p)}...) if _, err := c.Write(b); err != nil { t.Errorf("net.Conn.Write failed: %v", err) return } } ================================================ FILE: vendor/golang.org/x/net/proxy/socks5.go ================================================ // 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 } closeConn := &conn defer func() { if closeConn != nil { (*closeConn).Close() } }() host, portStr, err := net.SplitHostPort(addr) if err != nil { return nil, err } port, err := strconv.Atoi(portStr) if err != nil { return nil, errors.New("proxy: failed to parse port number: " + portStr) } if port < 1 || port > 0xffff { return nil, 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 nil, 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 nil, errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if buf[0] != 5 { return nil, errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0]))) } if buf[1] == 0xff { return nil, 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 nil, 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 nil, errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } if buf[1] != 0 { return nil, 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 nil, 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 nil, 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 nil, 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 nil, 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 nil, errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } bytesToDiscard = int(buf[0]) default: return nil, 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 nil, 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 nil, errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error()) } closeConn = nil return conn, nil } ================================================ FILE: vendor/golang.org/x/net/publicsuffix/gen.go ================================================ // 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 ignore package main // This program generates table.go and table_test.go. // Invoke as: // // go run gen.go -version "xxx" >table.go // go run gen.go -version "xxx" -test >table_test.go // // The version is derived from information found at // https://github.com/publicsuffix/list/commits/master/public_suffix_list.dat // // To fetch a particular git revision, such as 5c70ccd250, pass // -url "https://raw.githubusercontent.com/publicsuffix/list/5c70ccd250/public_suffix_list.dat" import ( "bufio" "bytes" "flag" "fmt" "go/format" "io" "net/http" "os" "regexp" "sort" "strings" "golang.org/x/net/idna" ) const ( nodesBitsChildren = 9 nodesBitsICANN = 1 nodesBitsTextOffset = 15 nodesBitsTextLength = 6 childrenBitsWildcard = 1 childrenBitsNodeType = 2 childrenBitsHi = 14 childrenBitsLo = 14 ) var ( maxChildren int maxTextOffset int maxTextLength int maxHi uint32 maxLo uint32 ) func max(a, b int) int { if a < b { return b } return a } func u32max(a, b uint32) uint32 { if a < b { return b } return a } const ( nodeTypeNormal = 0 nodeTypeException = 1 nodeTypeParentOnly = 2 numNodeType = 3 ) func nodeTypeStr(n int) string { switch n { case nodeTypeNormal: return "+" case nodeTypeException: return "!" case nodeTypeParentOnly: return "o" } panic("unreachable") } var ( labelEncoding = map[string]uint32{} labelsList = []string{} labelsMap = map[string]bool{} rules = []string{} // validSuffix is used to check that the entries in the public suffix list // are in canonical form (after Punycode encoding). Specifically, capital // letters are not allowed. validSuffix = regexp.MustCompile(`^[a-z0-9_\!\*\-\.]+$`) crush = flag.Bool("crush", true, "make the generated node text as small as possible") subset = flag.Bool("subset", false, "generate only a subset of the full table, for debugging") url = flag.String("url", "https://publicsuffix.org/list/effective_tld_names.dat", "URL of the publicsuffix.org list. If empty, stdin is read instead") v = flag.Bool("v", false, "verbose output (to stderr)") version = flag.String("version", "", "the effective_tld_names.dat version") test = flag.Bool("test", false, "generate table_test.go") ) func main() { if err := main1(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } func main1() error { flag.Parse() if nodesBitsTextLength+nodesBitsTextOffset+nodesBitsICANN+nodesBitsChildren > 32 { return fmt.Errorf("not enough bits to encode the nodes table") } if childrenBitsLo+childrenBitsHi+childrenBitsNodeType+childrenBitsWildcard > 32 { return fmt.Errorf("not enough bits to encode the children table") } if *version == "" { return fmt.Errorf("-version was not specified") } var r io.Reader = os.Stdin if *url != "" { res, err := http.Get(*url) if err != nil { return err } if res.StatusCode != http.StatusOK { return fmt.Errorf("bad GET status for %s: %d", *url, res.Status) } r = res.Body defer res.Body.Close() } var root node icann := false buf := new(bytes.Buffer) br := bufio.NewReader(r) for { s, err := br.ReadString('\n') if err != nil { if err == io.EOF { break } return err } s = strings.TrimSpace(s) if strings.Contains(s, "BEGIN ICANN DOMAINS") { icann = true continue } if strings.Contains(s, "END ICANN DOMAINS") { icann = false continue } if s == "" || strings.HasPrefix(s, "//") { continue } s, err = idna.ToASCII(s) if err != nil { return err } if !validSuffix.MatchString(s) { return fmt.Errorf("bad publicsuffix.org list data: %q", s) } if *subset { switch { case s == "ac.jp" || strings.HasSuffix(s, ".ac.jp"): case s == "ak.us" || strings.HasSuffix(s, ".ak.us"): case s == "ao" || strings.HasSuffix(s, ".ao"): case s == "ar" || strings.HasSuffix(s, ".ar"): case s == "arpa" || strings.HasSuffix(s, ".arpa"): case s == "cy" || strings.HasSuffix(s, ".cy"): case s == "dyndns.org" || strings.HasSuffix(s, ".dyndns.org"): case s == "jp": case s == "kobe.jp" || strings.HasSuffix(s, ".kobe.jp"): case s == "kyoto.jp" || strings.HasSuffix(s, ".kyoto.jp"): case s == "om" || strings.HasSuffix(s, ".om"): case s == "uk" || strings.HasSuffix(s, ".uk"): case s == "uk.com" || strings.HasSuffix(s, ".uk.com"): case s == "tw" || strings.HasSuffix(s, ".tw"): case s == "zw" || strings.HasSuffix(s, ".zw"): case s == "xn--p1ai" || strings.HasSuffix(s, ".xn--p1ai"): // xn--p1ai is Russian-Cyrillic "рф". default: continue } } rules = append(rules, s) nt, wildcard := nodeTypeNormal, false switch { case strings.HasPrefix(s, "*."): s, nt = s[2:], nodeTypeParentOnly wildcard = true case strings.HasPrefix(s, "!"): s, nt = s[1:], nodeTypeException } labels := strings.Split(s, ".") for n, i := &root, len(labels)-1; i >= 0; i-- { label := labels[i] n = n.child(label) if i == 0 { if nt != nodeTypeParentOnly && n.nodeType == nodeTypeParentOnly { n.nodeType = nt } n.icann = n.icann && icann n.wildcard = n.wildcard || wildcard } labelsMap[label] = true } } labelsList = make([]string, 0, len(labelsMap)) for label := range labelsMap { labelsList = append(labelsList, label) } sort.Strings(labelsList) p := printReal if *test { p = printTest } if err := p(buf, &root); err != nil { return err } b, err := format.Source(buf.Bytes()) if err != nil { return err } _, err = os.Stdout.Write(b) return err } func printTest(w io.Writer, n *node) error { fmt.Fprintf(w, "// generated by go run gen.go; DO NOT EDIT\n\n") fmt.Fprintf(w, "package publicsuffix\n\nvar rules = [...]string{\n") for _, rule := range rules { fmt.Fprintf(w, "%q,\n", rule) } fmt.Fprintf(w, "}\n\nvar nodeLabels = [...]string{\n") if err := n.walk(w, printNodeLabel); err != nil { return err } fmt.Fprintf(w, "}\n") return nil } func printReal(w io.Writer, n *node) error { const header = `// generated by go run gen.go; DO NOT EDIT package publicsuffix const version = %q const ( nodesBitsChildren = %d nodesBitsICANN = %d nodesBitsTextOffset = %d nodesBitsTextLength = %d childrenBitsWildcard = %d childrenBitsNodeType = %d childrenBitsHi = %d childrenBitsLo = %d ) const ( nodeTypeNormal = %d nodeTypeException = %d nodeTypeParentOnly = %d ) // numTLD is the number of top level domains. const numTLD = %d ` fmt.Fprintf(w, header, *version, nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength, childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo, nodeTypeNormal, nodeTypeException, nodeTypeParentOnly, len(n.children)) text := makeText() if text == "" { return fmt.Errorf("internal error: makeText returned no text") } for _, label := range labelsList { offset, length := strings.Index(text, label), len(label) if offset < 0 { return fmt.Errorf("internal error: could not find %q in text %q", label, text) } maxTextOffset, maxTextLength = max(maxTextOffset, offset), max(maxTextLength, length) if offset >= 1<= 1< 64 { n, plus = 64, " +" } fmt.Fprintf(w, "%q%s\n", text[:n], plus) text = text[n:] } n.walk(w, assignIndexes) fmt.Fprintf(w, ` // nodes is the list of nodes. Each node is represented as a uint32, which // encodes the node's children, wildcard bit and node type (as an index into // the children array), ICANN bit and text. // // In the //-comment after each node's data, the nodes indexes of the children // are formatted as (n0x1234-n0x1256), with * denoting the wildcard bit. The // nodeType is printed as + for normal, ! for exception, and o for parent-only // nodes that have children but don't match a domain label in their own right. // An I denotes an ICANN domain. // // The layout within the uint32, from MSB to LSB, is: // [%2d bits] unused // [%2d bits] children index // [%2d bits] ICANN bit // [%2d bits] text index // [%2d bits] text length var nodes = [...]uint32{ `, 32-nodesBitsChildren-nodesBitsICANN-nodesBitsTextOffset-nodesBitsTextLength, nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength) if err := n.walk(w, printNode); err != nil { return err } fmt.Fprintf(w, `} // children is the list of nodes' children, the parent's wildcard bit and the // parent's node type. If a node has no children then their children index // will be in the range [0, 6), depending on the wildcard bit and node type. // // The layout within the uint32, from MSB to LSB, is: // [%2d bits] unused // [%2d bits] wildcard bit // [%2d bits] node type // [%2d bits] high nodes index (exclusive) of children // [%2d bits] low nodes index (inclusive) of children var children=[...]uint32{ `, 32-childrenBitsWildcard-childrenBitsNodeType-childrenBitsHi-childrenBitsLo, childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo) for i, c := range childrenEncoding { s := "---------------" lo := c & (1<> childrenBitsLo) & (1<>(childrenBitsLo+childrenBitsHi)) & (1<>(childrenBitsLo+childrenBitsHi+childrenBitsNodeType) != 0 fmt.Fprintf(w, "0x%08x, // c0x%04x (%s)%s %s\n", c, i, s, wildcardStr(wildcard), nodeTypeStr(nodeType)) } fmt.Fprintf(w, "}\n\n") fmt.Fprintf(w, "// max children %d (capacity %d)\n", maxChildren, 1<= 1<= 1<= 1< 0 && ss[0] == "" { ss = ss[1:] } // Join strings where one suffix matches another prefix. for { // Find best i, j, k such that ss[i][len-k:] == ss[j][:k], // maximizing overlap length k. besti := -1 bestj := -1 bestk := 0 for i, s := range ss { if s == "" { continue } for j, t := range ss { if i == j { continue } for k := bestk + 1; k <= len(s) && k <= len(t); k++ { if s[len(s)-k:] == t[:k] { besti = i bestj = j bestk = k } } } } if bestk > 0 { if *v { fmt.Fprintf(os.Stderr, "%d-length overlap at (%4d,%4d) out of (%4d,%4d): %q and %q\n", bestk, besti, bestj, len(ss), len(ss), ss[besti], ss[bestj]) } ss[besti] += ss[bestj][bestk:] ss[bestj] = "" continue } break } text := strings.Join(ss, "") if *v { fmt.Fprintf(os.Stderr, "crushed %d bytes to become %d bytes\n", beforeLength, len(text)) } return text } ================================================ FILE: vendor/golang.org/x/net/publicsuffix/list.go ================================================ // 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 publicsuffix provides a public suffix list based on data from // http://publicsuffix.org/. A public suffix is one under which Internet users // can directly register names. package publicsuffix // import "golang.org/x/net/publicsuffix" // TODO: specify case sensitivity and leading/trailing dot behavior for // func PublicSuffix and func EffectiveTLDPlusOne. import ( "fmt" "net/http/cookiejar" "strings" ) // List implements the cookiejar.PublicSuffixList interface by calling the // PublicSuffix function. var List cookiejar.PublicSuffixList = list{} type list struct{} func (list) PublicSuffix(domain string) string { ps, _ := PublicSuffix(domain) return ps } func (list) String() string { return version } // PublicSuffix returns the public suffix of the domain using a copy of the // publicsuffix.org database compiled into the library. // // icann is whether the public suffix is managed by the Internet Corporation // for Assigned Names and Numbers. If not, the public suffix is privately // managed. For example, foo.org and foo.co.uk are ICANN domains, // foo.dyndns.org and foo.blogspot.co.uk are private domains. // // Use cases for distinguishing ICANN domains like foo.com from private // domains like foo.appspot.com can be found at // https://wiki.mozilla.org/Public_Suffix_List/Use_Cases func PublicSuffix(domain string) (publicSuffix string, icann bool) { lo, hi := uint32(0), uint32(numTLD) s, suffix, wildcard := domain, len(domain), false loop: for { dot := strings.LastIndex(s, ".") if wildcard { suffix = 1 + dot } if lo == hi { break } f := find(s[1+dot:], lo, hi) if f == notFound { break } u := nodes[f] >> (nodesBitsTextOffset + nodesBitsTextLength) icann = u&(1<>= nodesBitsICANN u = children[u&(1<>= childrenBitsLo hi = u & (1<>= childrenBitsHi switch u & (1<>= childrenBitsNodeType wildcard = u&(1<>= nodesBitsTextLength offset := x & (1< len(b[j]) } // eTLDPlusOneTestCases come from // https://github.com/publicsuffix/list/blob/master/tests/test_psl.txt var eTLDPlusOneTestCases = []struct { domain, want string }{ // Empty input. {"", ""}, // Unlisted TLD. {"example", ""}, {"example.example", "example.example"}, {"b.example.example", "example.example"}, {"a.b.example.example", "example.example"}, // TLD with only 1 rule. {"biz", ""}, {"domain.biz", "domain.biz"}, {"b.domain.biz", "domain.biz"}, {"a.b.domain.biz", "domain.biz"}, // TLD with some 2-level rules. {"com", ""}, {"example.com", "example.com"}, {"b.example.com", "example.com"}, {"a.b.example.com", "example.com"}, {"uk.com", ""}, {"example.uk.com", "example.uk.com"}, {"b.example.uk.com", "example.uk.com"}, {"a.b.example.uk.com", "example.uk.com"}, {"test.ac", "test.ac"}, // TLD with only 1 (wildcard) rule. {"il", ""}, {"c.il", ""}, {"b.c.il", "b.c.il"}, {"a.b.c.il", "b.c.il"}, // More complex TLD. {"jp", ""}, {"test.jp", "test.jp"}, {"www.test.jp", "test.jp"}, {"ac.jp", ""}, {"test.ac.jp", "test.ac.jp"}, {"www.test.ac.jp", "test.ac.jp"}, {"kyoto.jp", ""}, {"test.kyoto.jp", "test.kyoto.jp"}, {"ide.kyoto.jp", ""}, {"b.ide.kyoto.jp", "b.ide.kyoto.jp"}, {"a.b.ide.kyoto.jp", "b.ide.kyoto.jp"}, {"c.kobe.jp", ""}, {"b.c.kobe.jp", "b.c.kobe.jp"}, {"a.b.c.kobe.jp", "b.c.kobe.jp"}, {"city.kobe.jp", "city.kobe.jp"}, {"www.city.kobe.jp", "city.kobe.jp"}, // TLD with a wildcard rule and exceptions. {"ck", ""}, {"test.ck", ""}, {"b.test.ck", "b.test.ck"}, {"a.b.test.ck", "b.test.ck"}, {"www.ck", "www.ck"}, {"www.www.ck", "www.ck"}, // US K12. {"us", ""}, {"test.us", "test.us"}, {"www.test.us", "test.us"}, {"ak.us", ""}, {"test.ak.us", "test.ak.us"}, {"www.test.ak.us", "test.ak.us"}, {"k12.ak.us", ""}, {"test.k12.ak.us", "test.k12.ak.us"}, {"www.test.k12.ak.us", "test.k12.ak.us"}, // Punycoded IDN labels {"xn--85x722f.com.cn", "xn--85x722f.com.cn"}, {"xn--85x722f.xn--55qx5d.cn", "xn--85x722f.xn--55qx5d.cn"}, {"www.xn--85x722f.xn--55qx5d.cn", "xn--85x722f.xn--55qx5d.cn"}, {"shishi.xn--55qx5d.cn", "shishi.xn--55qx5d.cn"}, {"xn--55qx5d.cn", ""}, {"xn--85x722f.xn--fiqs8s", "xn--85x722f.xn--fiqs8s"}, {"www.xn--85x722f.xn--fiqs8s", "xn--85x722f.xn--fiqs8s"}, {"shishi.xn--fiqs8s", "shishi.xn--fiqs8s"}, {"xn--fiqs8s", ""}, } func TestEffectiveTLDPlusOne(t *testing.T) { for _, tc := range eTLDPlusOneTestCases { got, _ := EffectiveTLDPlusOne(tc.domain) if got != tc.want { t.Errorf("%q: got %q, want %q", tc.domain, got, tc.want) } } } ================================================ FILE: vendor/golang.org/x/net/publicsuffix/table.go ================================================ // generated by go run gen.go; DO NOT EDIT package publicsuffix const version = "publicsuffix.org's public_suffix_list.dat, git revision 0de6f8e (2015-07-15)" const ( nodesBitsChildren = 9 nodesBitsICANN = 1 nodesBitsTextOffset = 15 nodesBitsTextLength = 6 childrenBitsWildcard = 1 childrenBitsNodeType = 2 childrenBitsHi = 14 childrenBitsLo = 14 ) const ( nodeTypeNormal = 0 nodeTypeException = 1 nodeTypeParentOnly = 2 ) // numTLD is the number of top level domains. const numTLD = 1337 // Text is the combined text of all labels. const text = "biomutashinainfoggiabirdartdecodynaliascoli-picenord-frontierbir" + "kenesoddtangenovaravennagatorockartuzyunsakakinokiabirthplacevje" + "-og-hornnesangostrodawarabjarkoyurihonjournalistjordalshalsenfsh" + "ostre-totenkawabjerkreimmobilienhsanjotatsunostrolekaniepcexpose" + "dogawarabikomaezakirunortonsbergminakamichigangwonikonantananger" + "bjugninohelpaleostrowiecasertairabloombergbauernuorokunohealthca" + "reerschmidtre-gauldalottokashikinuyamanouchikuhokuryugasakitaura" + "yasudabluedatsunanjogaszkolahppiacenzachpomorskieninomiyakonojos" + "oyrovnostrowwlkpmgmodalenirasakinvestmentsannanishiazais-a-candi" + "datexasiabmsannohelsinkitakamiizumisanofieldyndns-freemasonryusu" + "harabmweirbnpparibaselburgmxboxeroxjaworznobomloanswatch-and-clo" + "ckerbondyndns-homednsanokasumigaurawa-mazowszexeterbonnishigotvs" + "antabarbarabootsantacruzsantafedjelenia-goraboschlesischesanukis" + "-a-catererbostikasuyakutiabostonakijinsekikogentingretajimakaneg" + "asakitagawabotanicalgardenishiharabotanicgardenishiizunazukis-a-" + "celticsfanishikatakayamatta-varjjatattoolsztynsettlersaotomelbou" + "rnextraspace-to-rentalsapodhalebotanynysadoesntexistanbullensake" + "rboutiquebecasinore-og-uvdalouvrepair-traffic-controlleyusuisser" + "vegame-serverdalovenneslaskerrylogisticsapporobozentsujiiebrades" + "corporationishikatsuragivingrimstadyndns-ip6brandywinevalleyuulm" + "inamibosogndalowiczest-le-patrondheimperiabrasiljan-mayenishikaw" + "azukaneyamaxunjargabresciabrindisiciliabristolgalsacebritishcolu" + "mbialowiezagannakadomari-elasticbeanstalkaszubyuzawabroadcastleb" + "timnetzgorabroadwayuzhno-sakhalinskatowicebroke-itaxihuanishimer" + "abrokerrypropertiesaratovalleaostavropolicebronnoysundyndns-mail" + "ubindalucaniabrothermesaverdealstahaugesundyndns-office-on-the-w" + "ebcambridgestonewportlligatewaybrumunddaluccapetownishinomiyashi" + "ronobrunelblagdenesnaaseralingenkainanaejrietiendaburyatiabrusse" + "lsardegnamsosnowiecastresistancebruxellesardiniabryanskleppalerm" + "omasvuotnakatsugawabryneuesarlucernebuyshousesarpsborgripebuzeni" + "shinoomotegovtgorybuzzgorzeleccollegersundyndns-picsarufutsunomi" + "yawakasaikaitakoelnishinoshimabwfarmequipmentjeldsundyndns-remot" + "egildeskalmykiabzhitomirkutskodjeffersonishiokoppegardyndns-serv" + "erbaniacntoyonezawacolognewjerseycolonialwilliamsburgrpanamacolo" + "radoplateaudiocolumbusantiquest-a-la-masioncommunitydaluxembourg" + "ruecomobaracompanycompute-1computerhistoryofscience-fictioncomse" + "curitysfjordcondoshichikashukujitawaraconferenceconstructioncons" + "uladollsatxn--0trq7p7nnconsultanthropologyconsultingvolluxurycon" + "tactoyonocontemporaryartgallerybnikahokutogitsuldaluzerncontract" + "orskenconventureshinodesashibetsuikindleikangercookingchannelver" + "uminamiechizencoolbia-tempio-olbiatempioolbialystokkecoopocznori" + "lskypescaravantaarparachutinguidellogliastradercopenhagencyclope" + "dicdn77-sslattuminamidaitomangotsukisosakitagatakamoriokamikitay" + "amatotakadacorsicamerakershus-east-1corvettelemarkazunocosenzako" + "panerairguardcostumedio-campidano-mediocampidanomediocouncilviva" + "no-frankivskchristiansburguitarsaudacouponsauheradcoursesavannah" + "gacqhachinoheguris-a-democratoyookarasjohkamiokaminokawanishiaiz" + "ubangecranbrookuwanalyticsaves-the-whalessandria-trani-barletta-" + "andriatranibarlettaandriacreditcardcreditunioncremonashorokanaie" + "crewiiheyaizuwakamatsubushikusakadogawacricketrzyncrimeacrotonew" + "mexicoldwarmiamiastarnbergujolstercrowncrsavonamsskoganeis-a-des" + "ignercruisesaxocuisinellancasterculturalcentertainmentoyosatomsk" + "ddielddanuorrikuzentakatajirissafetysnesayokkaichirurgiens-denti" + "stesbscholarshipschoolcuneocupcakecxn--11b4c3dcyouthdfcbankfhskh" + "abarovskhakassiafinlandfinnoyfirebaseappspotenzamamicrolightingu" + "nmaritimodellinguovdageaidnulsanfranciscotlandfirenzefirestonewy" + "orkshireggio-calabriafirmdaleirfjordfishingoldpointelligencefitj" + "arfitnessettlementoyotsukaidovre-eikerfjalerflesbergushikamifura" + "noshiroomuraflickragerotikamchatkameokameyamashinatsukigatakahar" + "ussiaflightschweizippodlasiellakasamatsudoosandnessjoenfloguchik" + "uzenfloraflorencefloridafloristanohatakahashimamakirkenesciencec" + "entersciencehistoryfloromskogxn--1ck2e1balestrandabergamoarekepn" + "ordlandivtasvuodnakaiwamizawaugustowadaejeonbukarlsoyokote12flow" + "erscientistor-elvdalflsmidthruhereggio-emilia-romagnakanotoddenf" + "lynnhubalsanagochihayaakasakawagoebinagisoccertificationaturalsc" + "iencesnaturelles3-sa-east-1fndfolldalfoodnetworkangerfor-better-" + "thandafor-ourfor-somedizinhistorischescrapper-sitefor-theatreefo" + "rexrothachiojiyahikobeatscrappingzjcbnlforgotdnservicesettsuppor" + "toyouraforli-cesena-forlicesenaforliguriaforsaleirvikharkivalled" + "-aostakinoueforsandasuolodingenfortmissoulan-udefenseljordfortwo" + "rthachirogatakanabeauxartsandcraftsevastopoleforuminamiizukamito" + "ndabayashiogamagoriziafosnesewildlifestylefotoystre-slidrettozaw" + "afredrikstadtveronakamuratakahamaniwakuratelevisionfreiburgfreig" + "htcmwilliamhillfribourgfriuli-v-giuliafriuli-ve-giuliafriuli-veg" + "iuliafriuli-venezia-giuliafriuli-veneziagiuliafriuli-vgiuliafriu" + "liv-giuliafriulive-giuliafriulivegiuliafriulivenezia-giuliafriul" + "iveneziagiuliafriulivgiuliafrlfroganshakotankharkovalledaostakko" + "fuelfrognfrolandfrom-akrehamnfrom-alfrom-arfrom-azlgfrom-capebre" + "tonamiasakuchinotsuchiurakawassamukawataricohdavvesiidazaifudaig" + "odoharuhrfrom-collectionfrom-ctozsdeltajimibungotakadavvenjargam" + "vikhersonfrom-dcheltenham-radio-operaunitelefonicagliaridagawars" + "zawashingtondclkatsushikabelaudiblebesbyglandyndns-weberlincolni" + "shitosashimizunaminamiashigarafrom-degreefrom-flandersharis-a-ge" + "ekhmelnitskiyamashikiyosatohoboleslawiechelyabinskydivingriwatar" + "ailwayfrom-gausdalfrom-higashiagatsumagoizumizakirovogradoyfrom-" + "iafrom-idfrom-ilfrom-in-the-bandaiwafunexusdecorativeartsharpara" + "glidingfrom-kshawaiijimarylandfrom-kyknetnedalfrom-langevagrarbo" + "retumbriafrom-mannosegawafrom-mdfrom-meereshellaspeziafrom-micro" + "softbankhmelnytskyivallee-aosteroyfrom-mnfrom-mochizukiryuohkura" + "from-msherbrookegawafrom-mtnfrom-nchernigovernmentjomeloyalistoc" + "kholmestrandyndns-wikirafrom-ndfrom-nefrom-nhktranaritakurashiki" + "s-a-greenfrom-njcparisor-fronfrom-nminamimakis-a-gurulvikhvallee" + "aosteigenfrom-nvanylvenicefrom-nyfrom-ohtawaramotoineppugliafrom" + "-oketogolfashionfrom-orfrom-paderbornfrom-praxis-a-anarchistoire" + "ggiocalabriafrom-rittogurafrom-schokoladenfrom-sdnipropetrovskla" + "businessebykleclerchernihivgucciprianiigataishinomakikugawatchan" + "dclockatsuyamashikefrom-tnfrom-txn--1ctwolominamatamayukis-a-har" + "d-workerfrom-utazuerichardlikes-piedmontblancashireggioemiliarom" + "agnakasatsunairlinebraskaunbieidsvollfrom-vadsochildrensgardenfr" + "om-vtranbyfrom-wafrom-wielunnerfrom-wvaofrom-wyfrosinonefrostalo" + "wa-wolawafroyahabaghdadfstcgrouparliamentrani-andria-barletta-tr" + "ani-andriafujiiderafujikawaguchikonefujiminohadanotaireshimojis-" + "a-hunterfujinomiyadafujiokayamansionshimokawafujisatoshonairport" + "land-4-salernogiessengerdalaskanittedallasalleaseeklogeshimokita" + "yamafujisawafujishiroishidakabiratorideliveryggeelvinckmpspbalsf" + "jordivttasvuotnakamagayachts3-us-gov-west-1fujiyoshidafukayabear" + "dubaiduckdnsdojoetsurutaharaumakeupowiatmallorcafederationfukuch" + "iyamadafukudominichernivtsicilyfukuis-a-knightraniandriabarletta" + "traniandriafukumitsukefukuokazakisarazure-mobileitungsenfukurois" + "higakishiwadafukusakisofukushimanxn--1lqs03nfukuyamagatakahataka" + "ishimogosenfunabashiriuchinadafunagatakamatsukawafunahashikamiam" + "akusatsumasendaisennangonohejis-a-landscaperugiafundaciofuoiskuj" + "ukuriyamaoris-a-lawyerfuosskoczowinbaltimore-og-romsdalillesandi" + "egotembaixadaukraanghkemerovodkagoshimagnitkakamigaharaholtaleni" + "waizumiotsukumiyamazonawsaarlandgcampobassociates3-eu-west-1furn" + "iturehabikinokawairtelecityeatshimonitayanagis-a-liberalfurubira" + "quarelleasingleshimonosekikawafurudonostiafurukawaharafusodegaur" + "afussagaeroclubmedecincinnativeamericanantiquesquarendalenugfuta" + "bayamaguchinomigawafutboldlygoingnowhere-for-moregontrailroadfut" + "tsurugashimarburgfvgfyis-a-libertarianfylkesbiblackfridayfyresda" + "lhannanmokuizumodenakatombetsulikescandynathomebuiltranoyhannova" + "reservebbshimotsukehanyuzenhapmirumarnardalhappounzenhareidsberg" + "enharstadharvestcelebrationhasamarahasaminami-alpssells-for-ustk" + "arasuyamazoehasudahasvikokonoehatogayahoooshikamaishimodatenris-" + "a-nurseminehatoyamazakitahiroshimarriottransportrapaniimimatakas" + "ugais-a-painteractivegaskimitsubatamicadaqueshimotsumahatsukaich" + "iharahattfjelldalhayashimamotobunkyonanaoshimabariakehazuminobus" + "ells-itravelchannelhembygdsforbundhemneshinichinanhemsedalheroku" + "ssldheroyhgtvarggatravelersinsurancehigashichichibusheyhigashihi" + "roshimanehigashiizumozakitakatakaokamikoaniikappulawyhigashikaga" + "wahigashikagurasoedahigashikawakitaaikitakyushuaiahigashikurumee" + "trdhigashimatsushimarugame-hostinghigashimatsuyamakitaakitadaito" + "igawahigashimurayamalatvuopmidoris-a-patsfanhigashinarusellsyour" + "homeftpaccesshinjournalismolanshinjukumanohigashinehigashiomihac" + "himanchesterhigashiosakasayamamotorcycleshinkamigotoyohashimotok" + "uyamahigashishirakawamatakarazukamiminershinshinotsurfastlyhigas" + "hisumiyoshikawaminamiaikitamidsundhigashitsunotteroyhigashiuraus" + "ukitamotosumidatlantichiryukyuragifuefukihabmerhigashiyamatokori" + "yamanakakogawahigashiyodogawahigashiyoshinogaris-a-personaltrain" + "erhiraizumisatohmarumorimachidahirakatashinagawahiranairtrafficb" + "cghirarahiratsukagawahirayaitakasagooglecodespotrentino-a-adigeh" + "istorichouseshinshirohitachiomiyaginowaniihamatamakawajimarcheap" + "artmentshintokushimahitachiotagoparocherkasyzrankoshigayaltaikis" + "-a-photographerokuapparshintomikasaharahitoyoshimifunehitradingh" + "jartdalhjelmelandholeckobierzyceholidayhomeipartis-a-playerhomel" + "inuxn--1lqs71dhomessinashikitanakagusukumodernhomeunixn--1qqw23a" + "hondahonefosshinyoshitomiokanmakiwakunigamihamadahongorgehonjyoi" + "chiropractichitachinakagawatchesasayamahornindalhorsembokukitash" + "iobarahortendofinternetrentino-aadigehoteleshiojirishirifujiedah" + "otmailhoyangerhoylandetroitskolobrzegyptianquanconagawakeisenbah" + "nhurdalhurumajis-a-republicancerresearchaeologicaliforniahyogori" + "s-a-rockstarachowicehyugawarajfkomakiyosemitejgorajlchloejlljmpa" + "rtnershiraokanonjis-a-studentaljnjeonnamerikawauejoyoitakasakitc" + "henjpmorganichocolatelekommunikationishiwakis-a-conservativegars" + "heis-a-cpadoval-daostavalleyjpnchofunatorientexpressexyzgradyndn" + "s-workshoppdalukowhalingroks-thisayamanashichinohedmarketsasebok" + "nowsitallyngenissandvikcoromantovalle-aostatoiluroyjprshiratakah" + "agis-a-teacherkassymantechnologyjurkredstonekristiansandefjordkr" + "istiansundkrodsheradkrokstadelvaldaostathellewismillerkryminamio" + "guniversitykumatorinokumejimateramoldelmenhorstalbanshisuifuette" + "rtdasnetzwindmillkumenanyokaichibahccavuotnagareyamaintenancekun" + "isakis-an-actresshirahamatonbetsurgeonshalloffamelhuslivinghisto" + "rykunitachiaraisaijoshkar-olayangroupartykunitomigusukumamotoyam" + "asudakunneppupasadenaklodzkodairakunstsammlungkunstunddesignkuok" + "groupassagenshitaramakureitrentino-sudtirolkurgankurobellevuelos" + "angelesjaguarchitecturebungoonomichinomiyakembuchikujobservercel" + "liernemurorangemologicallfinanzkurogimilitarykuroisoftwaremarker" + "ryhotelshizukuishimofusaikis-an-anarchistoricalsocietyumenkuroma" + "tsunais-an-artistjohnkurotakikawasakis-an-engineeringerikekursko" + "mmunalforbundkushirogawakustanais-an-entertainerkusunndalkutchan" + "elkutnokuzbassnillfjordkuzumakis-bykvafjordkvalsundkvamlidlugole" + "kagaminord-aurdalvdalipayufuchukotkafjordkvanangenkvinesdalkvinn" + "heradkviteseidskogkvitsoykwpspjelkavikommunekyotobetsupersportre" + "ntino-sued-tirolkyowariasahikawamissilexusgardenmisugitokigawami" + "takeharamitourismolenskomorotsukamisunagawamitoyoakemiuramiyazur" + "ewebsiteshikagamiishikarikaturindalmiyotamanomjondalenmlbarclays" + "3-us-west-2monmouthaebaruminamiminowamonticellombardiamondshouji" + "s-into-animegurovigorlicemontrealestatebankomvuxn--2m4a15emonza-" + "brianzaporizhzhekinannestadmonza-e-della-brianzaporizhzhiamonzab" + "rianzapposts-and-telecommunicationshowamonzaebrianzaramonzaedell" + "abrianzamordoviajessheiminamisanrikubetsupplieshizuokanoyakagemo" + "riyamatsusakahogithubusercontentrentino-suedtirolmoriyoshiokamit" + "suemormoneymoroyamatsushigemortgagemoscowindowshriramsterdamberk" + "eleymoseushistorymosjoenmoskenesienaplesigdalmossimbirskongsberg" + "mosvikongsvingermoviemovistargardmtpccwioslombardyndns-at-homede" + "potaruis-into-carshirakoenigmtrainingmuenstermugivestbytomakomai" + "baramuikamogawamukochikushinonsenergymulhouseoullensvangmulticho" + "icemunakatanemuncieszynmuosattemupassenger-associationmurmanskon" + "injamisonymurotorcraftrentinoa-adigemusashimurayamatsuuramusashi" + "noharamuseetrentinoaadigemuseumverenigingmutsuzawamutuellezajsko" + "nskowolapyatigorskomatsushimashikokuchuomyphotoshibaikaliszczytn" + "ordkappgmytis-a-bookkeeperminamitanephilatelyphilipsyphoenixn--3" + "0rr7yphotographysiopiagetmyipaviancapitalpictetrentinoaltoadigep" + "icturesirdalpiemontepilotslupskonsulatrobelgorodeopinkonyvelolku" + "szpartshishikuis-a-techietis-a-socialistmeincheonpippupiszpittsb" + "urghofauskedsmokorsetagayasells-for-lesschulepiwatepizzapkooris-" + "a-therapistoiaplanetariuminamiuonumatsumotofukeplantationplantsn" + "oasaintlouis-a-bruinsfansnzplatforminamiyamashirokawanabellunord" + "re-landplaystationplazaplchonanbuildingrondarplomzansimagichosei" + "kakegawawhoswhokksundyroyrvikingrongaplumbingoplusterpmnpodzonep" + "ohlpokerpokrovskopervikomforbambleborkarpaczeladz-2polkowicepolt" + "avalle-d-aostavangerpomorzeszowitdkoryolasitepordenonepornporsan" + "gerporsangugeporsgrunnanpoznanprdpreservationpresidioprimeiwamat" + "sumaebashikshacknetrentinos-tirolprincipeprivneprochowiceproduct" + "ionsokanraprofermobilyprojectrentinostirolpromombetsupplypropert" + "yprotectionpruszkowithgoogleapisa-hockeynutrentinosud-tirolprzew" + "orskogptzpvtrentinosudtirolpzqldqponqslgbtrentinosued-tirolsrlsr" + "varoystoragestordalstorenburgstorfjordstpetersburgstudiostudyndn" + "s-blogdnsolarssonstuff-4-salestuttgartrentoshimasurgutsiracusait" + "amatsukuris-into-cartoonshiranukannamiharusurnadalsurreysusakis-" + "into-gameshiraois-a-soxfansusonosuzakanumazurysuzukanzakiwiensuz" + "ukis-leetrentino-alto-adigesvalbardudinkamakurazakinkobayashikao" + "irmincommbankomonosveiosvelvikosaigawasvizzeraswedenswidnicarbon" + "ia-iglesias-carboniaiglesiascarboniaswiebodzindianapolis-a-blogg" + "erswinoujscienceandhistoryswisshikis-lostfoldsxn--32vp30hagakhan" + "amigawatuis-not-certifiedunetflixiltulaquilarvikoseis-an-account" + "antshioyameldaltunesologneturystykarasjoksnesolundtuscanytushuma" + "nitiesolutionsokndaltuvalle-daostavernversicherungvestfoldvestne" + "somnarashinovestre-slidreamhostersoovestre-totennishiawakuravest" + "vagoyvevelstadvibo-valentiavibovalentiavideovillaskvolloabathsbc" + "ngvinnicargojomediavinnytsiavipsinaappharmacymruovatrentinoalto-" + "adigevirginiavirtualvirtuelvistaprinternationalfirearmsopotrenti" + "nosuedtirolviterboltrevisohuissier-justicevladikavkazanvladimirv" + "ladivostokaizukaratevlogvoldavolgogradvolkenkunderseaportroandin" + "osaurepbodyndns-at-workinggroupharmaciensimple-urlvolkswagentsor" + "-odalvologdanskoshunantokamachippubetsubetsugaruvolyngdalvoronez" + "hytomyrvossevangenvotevotingvotottoris-savedvrnwroclawloclawekos" + "tromahabororoskolelwtchoyodobashibuyachiyodawtferrarawuozuwwwrit" + "esthisblogspotrogstadwzmiuwajimaxn--3pxu8kosugexn--42c2d9axn--45" + "brj9christmasakimobetsuwanouchikuseihichisobetsuitaitogakushimot" + "oganewhampshirecreationissedalutskaufenisshinguernseyxn--45q11ch" + "romedicaltanissettaiwanairforceoxn--4gbriminingxn--4it168dxn--4i" + "t797kotohiradomainsureisenxn--4pvxsor-varangerxn--54b7fta0cchtra" + "eumtgeradeatnurembergrossetouchijiwadell-ogliastrakhanawaxn--55q" + "w42gxn--55qx5dxn--5js045dxn--5rtp49chungbukautokeinoxn--5rtq34ko" + "touraxn--5tzm5gxn--6btw5axn--6frz82gxn--6orx2rxn--6qq986b3xlxn--" + "7t0a264chungnamdalseidfjordxn--80adxhksorfoldxn--80ao21axn--80as" + "ehdbargainstituteledatabaseballooningjerdrumemorialimitedownload" + "rangedalimoliserniaustraliaisondre-landebudejjuedischesapeakebay" + "erndigitalillehammerfest-mon-blogueurovisionasushiobaragrinetban" + "kz-1kappleangaviikadenaamesjevuemielnoboribetsucks3-ap-northeast" + "-1xn--80aswgxn--80audnedalnxn--8ltr62kouhokutamakizunokunimilano" + "xn--8pvr4uxn--8y0a063axn--90a3academykolaivanovosibirskiervaapst" + "eiermarkhangelskinderoyerimo-i-ranadexchangeiseiroumuenchendofth" + "einternetcimdbarreauctionaturbruksgymnaturhistorischesakuraibiga" + "waustrheimatunduhrennesoyokoze164xn--90aishobaraxn--90azhagebost" + "adxn--9dbhblg6diethnologyxn--9dbq2axn--9et52uxn--9krt00axn--andy" + "-iraxn--aroport-byanagawaxn--asky-iraxn--aurskog-hland-jnbarrel-" + "of-knowledgeorgiauthordalandroidiscountysvardonnaharimamurogawag" + "roks-theaternidds3-ap-southeast-1xn--avery-yuasakatakazakis-slic" + "komaganexn--b-5gaxn--b4w605ferdxn--bck1b9a5dre4churchaseljejuego" + "shikiminokamoenaircraftmpamperedchefarmsteadxn--bdddj-mrabdxn--b" + "earalvhki-y4axn--berlevg-jxaxn--bhcavuotna-s4axn--bhccavuotna-k7" + "axn--bidr-5nachikatsuuraxn--bievt-0qaxn--bjarky-fyanaizuxn--bjdd" + "ar-ptambovdonskoshimizumakiyosumitakaginozawaonsenxn--blt-elabor" + "xn--bmlo-graingerxn--bod-2naroyxn--brnny-wuaccident-investigatio" + "njukudoyamaceratabuseat-band-campaniamallamadridvagsoygardenebak" + "keshibechambagricaaarborteaches-yogasawaracingxn--brnnysund-m8ac" + "cident-preventionlineat-urlxn--brum-voagatromsaitokorozawaxn--bt" + "sfjord-9zaxn--c1avgxn--c2br7gxn--c3s14misakis-foundationxn--cck2" + "b3barrell-of-knowledgets-itarumizusawautomotivelandiscoveryokami" + "kawanehonbetsuruokaluganskarmoyomitanobihirosakikamijimakunecn-n" + "orth-1xn--cg4bkis-uberleetrentino-altoadigexn--ciqpnxn--clchc0ea" + "0b2g2a9gcdn77-securecipesaro-urbino-pesarourbinopesaromalvikouno" + "sumypetshisognexn--comunicaes-v6a2oxn--correios-e-telecomunicaes" + "-ghc29axn--czr694bashkiriautoscanadagestangeologyonabarudmurtiam" + "usementargibestadevenes3-ap-southeast-2xn--czrs0tromsojavald-aos" + "tarostwodzislawiwatsukiyonowtvbarefootballangenoamishirasatobish" + "imaizurubtsovskjervoyageometre-experts-comptablesakuragawaustinn" + "aspers3-external-1xn--czru2dxn--czrw28basilicataniaveroykenviron" + "mentalconservationaturalhistorymuseumcentereportarnobrzegjemnes3" + "-external-2xn--d1acj3batochigiftsakyotanabeneventochiokinoshimal" + "opolskanlandrivefsncfagebizenakaniikawatanaguravocatanzarowebhop" + "agespeedmobilizerobirasnesoddenmarketplace-burggfamilyokosukariy" + "akumodumemerck-uralsk12xn--d1alferreroticanonoichikawamisatodayx" + "n--d1atrusteexn--d5qv7z876chuvashiaxn--davvenjrga-y4axn--djrs72d" + "6uyxn--djty4kouyamasoyxn--dnna-grajeworldxn--drbak-wuaxn--dyry-i" + "raxn--eckvdtc9dxn--efvn9sorreisahayakawakamiichikaiseiyokoshibah" + "ikariwanumataketomisatokyotangoxn--efvy88haibarakitahatakanezawa" + "xn--ehqz56nxn--elqq16hakatanotogawaxn--estv75gxn--eveni-0qa01gax" + "n--f6qx53axn--fct429kouzushimassa-carrara-massacarraramassabuske" + "rudineustarhubarclaycards3-us-west-1xn--fhbeiarnxn--finny-yuaxn-" + "-fiq228c5hsortlandxn--fiq64batsfjordrobaknoluoktainaibetsubameri" + "canartanddesignieznogatagajobojibmdunloppacificarriereviewskrako" + "weddingjerstadotsurugimetlifeinsurancehimejiinetatamotorsalangen" + "atuurwetenschappenaumburgjesdalindaskoyabenorddalindesnesalatata" + "rstanaustdalinkaruizawavoues3-fips-us-gov-west-1xn--fiqs8sorumin" + "anoxn--fiqz9southcarolinazawaxn--fjord-lraxn--fjq720axn--fl-ziax" + "n--flor-jraxn--flw351exn--fpcrj9c3dxn--frde-grandrapidsouthwestf" + "alenxn--frna-woarais-very-badaddjamalborkdalxn--frya-hraxn--fzc2" + "c9e2circlegnicahcesuolocalhistoryazannefrankfurtoyokawaxn--fzys8" + "d69uvgmailxn--g2xx48circusculturedumbrellajollanbibaidarq-axn--g" + "ckr3f0fetsundxn--gecrj9citicateringebuildersvpalmspringsakerxn--" + "ggaviika-8ya47hakodatemasekmshimosuwalkis-a-linux-useranishiarit" + "abashijonawatextilevangerxn--gildeskl-g0axn--givuotna-8yandexhib" + "itionxn--gjvik-wuaxn--gls-elacaixaxn--gmq050is-very-evillagexn--" + "gmqw5axn--h-2failxn--h1aeghakonexn--h2brj9civilaviationiyodogawa" + "xn--hbmer-xqaxn--hcesuolo-7ya35bauhaustevollinzaiitatebayashiiba" + "hcavuotnagarakkestadupontariobninskarumaifareastcoastaldefencemb" + "roideryonagoyaxastronomyokohamamatsudaegubs3-eu-central-1xn--her" + "y-iraxn--hgebostad-g3axn--hmmrfeasta-s4acoachampionshiphopenair-" + "surveillancebetsukubabia-goracleaningatlantachikawakayamagadance" + "chirealtorlandxn--hnefoss-q1axn--hobl-iraxn--holtlen-hxaxn--hpmi" + "r-xqaxn--hxt814exn--hyanger-q1axn--hylandet-54axn--i1b6b1a6a2exn" + "--imr513nxn--indery-fyaotsurgeryxn--io0a7is-very-goodyearthadsel" + "fipirangaxn--j1aefgulenxn--j1amhakubanxn--j6w193gxn--jlq61u9w7bb" + "cartierhcloudcontrolappalanakhodkanagawaxn--jlster-byaroslavlaan" + "derenxn--jrpeland-54axn--jvr189misasaguris-gonexn--k7yn95exn--ka" + "rmy-yuaxn--kbrq7oxn--kcrx77d1x4axn--kfjord-iuaxn--klbu-woaxn--kl" + "t787dxn--kltp7dxn--kltx9axn--klty5xn--3bst00minnesotaketakatoris" + "-certifieducatorahimeshimageandsoundandvisionxn--koluokta-7ya57h" + "akuis-a-llamarylhursteinkjerusalembetsukuis-a-musicianxn--kprw13" + "dxn--kpry57dxn--kpu716figuerestaurantoyotaris-a-doctorayxn--kput" + "3is-very-nicexn--krager-gyasakaiminatoursowaxn--kranghke-b0axn--" + "krdsherad-m8axn--krehamn-dxaxn--krjohka-hwab49jetztrentino-stiro" + "lxn--ksnes-uuaxn--kvfjord-nxaxn--kvitsy-fyasugis-very-sweetrenti" + "no-s-tirollagriculturennebudapest-a-la-maisondriodejaneirocheste" + "rxn--kvnangen-k0axn--l-1fairwindspreadbettingxn--l1accentureklam" + "borghinikkoebenhavnxn--laheadju-7yasuokaratsuginamikatagamihobby" + "-sitevaksdalxn--langevg-jxaxn--lcvr32dxn--ldingen-q1axn--leagavi" + "ika-52bbvacationsnasabaerobaticketsalondonetskasaokamisatohnosho" + "oceanographicsaltdalipetskashibatakashimasfjordenaval-d-aosta-va" + "lleyonagunikolaeventsalvadordalibabajddarchaeologyeongnamegawakk" + "anaikawababydgoszczecinemailivornoceanographiquemergencyberlevag" + "angaviikarugaulardalorenskogjovikashiharaxn--lesund-huaxn--lgbba" + "t1ad8jevnakerxn--lgrd-poacivilisationrwifarsundxn--lhppi-xqaxn--" + "linds-pratoyakokamishihoronobeokaminoyamatsuris-with-thebandoomd" + "nsaliascolipicenord-odalxn--lns-qlavagiskexn--loabt-0qaxn--lrdal" + "-sraxn--lrenskog-54axn--lt-liacivilizationxn--lten-granexn--lury" + "-iraxn--mely-iraxn--merker-kuaxn--mgb2ddespydebergxn--mgb9awbfil" + "ateliaxn--mgba3a3ejtrvchoshibukawaxn--mgba3a4f16axn--mgba3a4fran" + "amizuholdingsmileksvikozagawaxn--mgba7c0bbn0axn--mgbaam7a8hakusa" + "ndoyxn--mgbab2bdxn--mgbai9a5eva00beppubolognagasukesennumalselve" + "ndrelloteneiiyamanobedzin-addrammenuernberglassassinationalherit" + "agematsubarakawachinaganoharaogashimadachicagoboatsalzburgliwice" + "mrxn--mgbai9azgqp6jewelryxn--mgbayh7gpaduaxn--mgbb9fbpobanazawax" + "n--mgbbh1a71exn--mgbc0a9azcgxn--mgberp4a5d4a87gxn--mgberp4a5d4ar" + "xn--mgbpl2fhvalerxn--mgbqly7c0a67fbcivilwarmanagementoyonakagyok" + "utomobentleyxn--mgbqly7cvafranziskanerimarinextdirectoryxn--mgbt" + "3dhdxn--mgbtf8flatangerxn--mgbtx2bernrtateshinanomachintaijindus" + "triesteambulancepilepsykkylvenetogliattipschoenbrunnavigationavu" + "otnakayamatsuzakinfinitiresamegawaxn--mgbx4cd0abogadocscbgxn--mi" + "x082filminamifuranoxn--mix891finalxn--mjndalen-64axn--mk0axindia" + "nmarketingxn--mk1bu44claimsaskatchewanggouvicenzaxn--mkru45isleo" + "fmandalxn--mlatvuopmi-s4axn--mli-tlavangenxn--mlselv-iuaxn--more" + "ke-juaxn--mori-qsakegawaxn--mosjen-eyatominamiawajikissmartertha" + "nyoutubeeldengeluidxn--mot-tlazioxn--mre-og-romsdal-qqbeskidyn-o" + "-saurlandesamnangerxn--msy-ula0haldenxn--mtta-vrjjat-k7aflakstad" + "aokagakibichuoxn--muost-0qaxn--mxtq1misawaxn--ngbc5azdxn--ngbe9e" + "0axn--nit225kozakis-an-actorxn--nmesjevuemie-tcbalatinabearalvah" + "kikonaioirasebastopologyeonggiehtavuoatnagaivuotnagaokakyotambad" + "ajozorahkkeravjudygarlandxn--nnx388axn--nodessakuhokkaidontexist" + "eingeekpnxn--nqv7fs00emaxn--nry-yla5gxn--ntso0iqx3axn--ntsq17gxn" + "--nttery-byaeserveftphiladelphiaareadmyblogsitexn--nvuotna-hwaxn" + "--nyqy26axn--o1achattanooganorfolkebiblegallocuscountryestateofd" + "elawarezzoologyxn--o3cw4halsagamiharaxn--od0algxn--od0aq3betaina" + "boxfordealerdalottepsongdalenviknakanojohanamakinoharaxn--ogbpf8" + "flekkefjordxn--oppegrd-ixaxn--ostery-fyatsukareliancexn--osyro-w" + "uaxn--p1acfdxn--p1aiwchitosetoeiheijis-a-chefarmerseinewspaperxn" + "--pbt977clickazimierz-dolnyxn--pgbs0dhammarfeastafricamagicherno" + "vtsydneyxn--porsgu-sta26financexn--pssu33lxn--pssy2uxn--q9jyb4cl" + "inicoffeedbackazoxn--qcka1pmclintonoshoesassaris-a-cubicle-slave" + "llinowruzhgorodoyxn--qqqt11misconfusedxn--qxamurskjakdnepropetro" + "vskiptveterinairealtychyllestadultrysilkosakaerodromegallupinbar" + "celonagasakikuchikumagayagawalbrzycharternopilawalesundnpalacebi" + "northwesternmutualimanowarudaurskog-holandroverhalla-speziaetnag" + "ahamaroyekaterinburgdyniaeroportalaheadjudaicabbottarantomaritim" + "ekeeping12000xn--rady-iraxn--rdal-poaxn--rde-ulaxn--rdy-0nabarix" + "n--rennesy-v1axn--rhkkervju-01afineartschwarzgwangjuifminamiisel" + "ectoyotomiyazakis-a-financialadvisor-aurdalxn--rholt-mragoworse-" + "thandsoniizaxn--rhqv96gxn--rht27zxn--rht3dxn--rht61exn--risa-5na" + "rusawaxn--risr-iraxn--rland-uuaxn--rlingen-mxaxn--rmskog-byatsus" + "hiroxn--rny31hamurakamigoriginankokubunjis-a-nascarfanxn--rovu88" + "bhartiffanycartoonarteducationalchikugokasejnyoriikashiwaraxn--r" + "ros-granvindafjordxn--rskog-uuaxn--rst-0narutokonamegatakatsukix" + "n--rsta-francaiseharaxn--ryken-vuaxn--ryrvik-byawaraxn--s-1faith" + "eguardianxn--s9brj9clothingroundhandlingroznyxn--sandnessjen-ogb" + "izhevskppspiegelxn--sandy-yuaxn--seral-lraxn--ses554gxn--sgne-gr" + "atangenxn--skierv-utazasmatartcenterprisesakievenassisibenikihok" + "umakogenglandxn--skjervy-v1axn--skjk-soaxn--sknit-yqaxn--sknland" + "-fxaxn--slat-5narviikananporoxn--slt-elabourxn--smla-hraxn--smna" + "-gratis-a-bulls-fanxn--snase-nraxn--sndre-land-0cbremangerxn--sn" + "es-poaxn--snsa-roaxn--sr-aurdal-l8axn--sr-fron-q1axn--sr-odal-q1" + "axn--sr-varanger-ggbielawallonieruchomoscienceandindustrynavyatk" + "anazawaxn--srfold-byawatahamaxn--srreisa-q1axn--srum-grazxn--stf" + "old-9xaxn--stjrdal-s1axn--stjrdalshalsen-sqbiellaakesvuemielecce" + "verbankashiwazakiyokawaraxn--stre-toten-zcbieszczadygeyachimatai" + "peigersundurbanpachigasakicks-assedicasadelamonedaxn--t60b56axn-" + "-tckweatherchannelxn--tjme-hraxn--tn0agrigentomologyeongbukrasno" + "darxn--tnsberg-q1axn--tor131oxn--trany-yuaxn--trgstad-r1axn--trn" + "a-woaxn--troms-zuaxn--tysvr-vraxn--uc0atverranzanxn--uc0ay4axn--" + "uist22hangglidingxn--uisz3gxn--unjrga-rtaobaomoriguchiharamcoalx" + "n--unup4yxn--uuwu58axn--vads-jraxn--vard-jraxn--vegrshei-c0axn--" + "vermgensberater-ctbievattorneyagawakuyabukijoburglobalashovhachi" + "jorpelandurhamburglobodoes-itateyamaxn--vermgensberatung-pwbifuk" + "agawalterxn--vestvgy-ixa6oxn--vg-yiabruzzoologicalabamagasakishi" + "mabaragusartsaritsynxn--vgan-qoaxn--vgsy-qoa0jewishartrentino-su" + "d-tirolxn--vgu402cloudcontrolledekakudamatsuenoharaxn--vhquversa" + "illesomaxn--vler-qoaxn--vre-eiker-k8axn--vrggt-xqadxn--vry-yla5g" + "xn--vuq861bihorologyukuhashimoichinosekigaharaxn--w4r85el8fhu5dn" + "raxn--wcvs22dxn--wgbh1cloudfrontdoorxn--wgbl6axn--xhq521bikedati" + "nglogowegroweibolzanordreisa-geekasukabeerxn--xkc2al3hye2axn--xk" + "c2dl3a5ee0hangoutsystemscloudapparmaxn--y9a3aquariumishimatsunox" + "n--yer-znarvikrasnoyarskomitamamuraxn--yfro4i67oxn--ygarden-p1ax" + "n--ygbi2ammxn--3ds443gxn--ystre-slidre-ujbilbaogakidstvedestrand" + "vrdnsamsungloppenzaokinawashirosatobamagazinedre-eikerxn--zbx025" + "dxn--zf0ao64axn--zf0avxn--3e0b707exn--zfr164billustrationayorodd" + "axperiaxxxn--3oq18vl8pn36axz" // nodes is the list of nodes. Each node is represented as a uint32, which // encodes the node's children, wildcard bit and node type (as an index into // the children array), ICANN bit and text. // // In the //-comment after each node's data, the nodes indexes of the children // are formatted as (n0x1234-n0x1256), with * denoting the wildcard bit. The // nodeType is printed as + for normal, ! for exception, and o for parent-only // nodes that have children but don't match a domain label in their own right. // An I denotes an ICANN domain. // // The layout within the uint32, from MSB to LSB, is: // [ 1 bits] unused // [ 9 bits] children index // [ 1 bits] ICANN bit // [15 bits] text index // [ 6 bits] text length var nodes = [...]uint32{ 0x00301443, // n0x0000 c0x0000 (---------------) + I aaa 0x002293c4, // n0x0001 c0x0000 (---------------) + I aarp 0x0036eb43, // n0x0002 c0x0000 (---------------) + I abb 0x0036eb46, // n0x0003 c0x0000 (---------------) + I abbott 0x0030cb04, // n0x0004 c0x0000 (---------------) + I able 0x00355b87, // n0x0005 c0x0000 (---------------) + I abogado 0x01a01e82, // n0x0006 c0x0006 (n0x0539-n0x053f) + I ac 0x002f2787, // n0x0007 c0x0000 (---------------) + I academy 0x0033dcc9, // n0x0008 c0x0000 (---------------) + I accenture 0x002d7e4a, // n0x0009 c0x0000 (---------------) + I accountant 0x002d7e4b, // n0x000a c0x0000 (---------------) + I accountants 0x00221483, // n0x000b c0x0000 (---------------) + I aco 0x0027d3c6, // n0x000c c0x0000 (---------------) + I active 0x00226f45, // n0x000d c0x0000 (---------------) + I actor 0x01e10a02, // n0x000e c0x0007 (n0x053f-n0x0540) + I ad 0x00262ac3, // n0x000f c0x0000 (---------------) + I ads 0x0036b745, // n0x0010 c0x0000 (---------------) + I adult 0x02204342, // n0x0011 c0x0008 (n0x0540-n0x0548) + I ae 0x003285c3, // n0x0012 c0x0000 (---------------) + I aeg 0x026751c4, // n0x0013 c0x0009 (n0x0548-n0x05a1) + I aero 0x0036de85, // n0x0014 c0x0000 (---------------) + I aetna 0x02a0c702, // n0x0015 c0x000a (n0x05a1-n0x05a6) + I af 0x0023a2c3, // n0x0016 c0x0000 (---------------) + I afl 0x00367c06, // n0x0017 c0x0000 (---------------) + I africa 0x00367c0b, // n0x0018 c0x0000 (---------------) + I africamagic 0x02e015c2, // n0x0019 c0x000b (n0x05a6-n0x05ab) + I ag 0x002d6e47, // n0x001a c0x0000 (---------------) + I agakhan 0x00229d46, // n0x001b c0x0000 (---------------) + I agency 0x032002c2, // n0x001c c0x000c (n0x05ab-n0x05af) + I ai 0x0024ef43, // n0x001d c0x0000 (---------------) + I aig 0x002e75c8, // n0x001e c0x0000 (---------------) + I airforce 0x00273406, // n0x001f c0x0000 (---------------) + I airtel 0x0036acc4, // n0x0020 c0x0000 (---------------) + I akdn 0x03600882, // n0x0021 c0x000d (n0x05af-n0x05b6) + I al 0x00342747, // n0x0022 c0x0000 (---------------) + I alibaba 0x002ab4c6, // n0x0023 c0x0000 (---------------) + I alipay 0x002a6589, // n0x0024 c0x0000 (---------------) + I allfinanz 0x0029c184, // n0x0025 c0x0000 (---------------) + I ally 0x00215bc6, // n0x0026 c0x0000 (---------------) + I alsace 0x03a04942, // n0x0027 c0x000e (n0x05b6-n0x05b7) + I am 0x0027d885, // n0x0028 c0x0000 (---------------) + I amica 0x002b6cc9, // n0x0029 c0x0000 (---------------) + I amsterdam 0x03e01242, // n0x002a c0x000f (n0x05b7-n0x05bb) + I an 0x0022f449, // n0x002b c0x0000 (---------------) + I analytics 0x002f8647, // n0x002c c0x0000 (---------------) + I android 0x00295a46, // n0x002d c0x0000 (---------------) + I anquan 0x0420fd82, // n0x002e c0x0010 (n0x05bb-n0x05c1) + I ao 0x0028df8a, // n0x002f c0x0000 (---------------) + I apartments 0x00212a03, // n0x0030 c0x0000 (---------------) + I app 0x002f0145, // n0x0031 c0x0000 (---------------) + I apple 0x00273fc2, // n0x0032 c0x0000 (---------------) + I aq 0x00273fc9, // n0x0033 c0x0000 (---------------) + I aquarelle 0x04600602, // n0x0034 c0x0011 (n0x05c1-n0x05ca) + I ar 0x00387dc6, // n0x0035 c0x0000 (---------------) + I aramco 0x0025dd45, // n0x0036 c0x0000 (---------------) + I archi 0x00333fc4, // n0x0037 c0x0000 (---------------) + I army 0x04e29404, // n0x0038 c0x0013 (n0x05cb-n0x05d1) + I arpa 0x00359e04, // n0x0039 c0x0000 (---------------) + I arte 0x05200182, // n0x003a c0x0014 (n0x05d1-n0x05d2) + I as 0x00209144, // n0x003b c0x0000 (---------------) + I asia 0x002729ca, // n0x003c c0x0000 (---------------) + I associates 0x05601642, // n0x003d c0x0015 (n0x05d2-n0x05d9) + I at 0x00389588, // n0x003e c0x0000 (---------------) + I attorney 0x05e05ac2, // n0x003f c0x0017 (n0x05da-n0x05ec) + I au 0x002f4487, // n0x0040 c0x0000 (---------------) + I auction 0x00222244, // n0x0041 c0x0000 (---------------) + I audi 0x00251707, // n0x0042 c0x0000 (---------------) + I audible 0x00222245, // n0x0043 c0x0000 (---------------) + I audio 0x002f8406, // n0x0044 c0x0000 (---------------) + I author 0x002eaac4, // n0x0045 c0x0000 (---------------) + I auto 0x00309645, // n0x0046 c0x0000 (---------------) + I autos 0x002c0747, // n0x0047 c0x0000 (---------------) + I avianca 0x06e02502, // n0x0048 c0x001b (n0x05fa-n0x05fb) + I aw 0x00272583, // n0x0049 c0x0000 (---------------) + I aws 0x00215282, // n0x004a c0x0000 (---------------) + I ax 0x0032b343, // n0x004b c0x0000 (---------------) + I axa 0x07208cc2, // n0x004c c0x001c (n0x05fb-n0x0607) + I az 0x0026c905, // n0x004d c0x0000 (---------------) + I azure 0x07605a82, // n0x004e c0x001d (n0x0607-n0x0612) + I ba 0x00343204, // n0x004f c0x0000 (---------------) + I baby 0x0026a085, // n0x0050 c0x0000 (---------------) + I baidu 0x00255704, // n0x0051 c0x0000 (---------------) + I band 0x00235dc4, // n0x0052 c0x0000 (---------------) + I bank 0x0020c103, // n0x0053 c0x0000 (---------------) + I bar 0x0036bf49, // n0x0054 c0x0000 (---------------) + I barcelona 0x0031934b, // n0x0055 c0x0000 (---------------) + I barclaycard 0x002afe08, // n0x0056 c0x0000 (---------------) + I barclays 0x0030b788, // n0x0057 c0x0000 (---------------) + I barefoot 0x002ed0c8, // n0x0058 c0x0000 (---------------) + I bargains 0x003297c7, // n0x0059 c0x0000 (---------------) + I bauhaus 0x002eef46, // n0x005a c0x0000 (---------------) + I bayern 0x07a791c2, // n0x005b c0x001e (n0x0612-n0x061c) + I bb 0x00331f83, // n0x005c c0x0000 (---------------) + I bbc 0x00340184, // n0x005d c0x0000 (---------------) + I bbva 0x0028bfc3, // n0x005e c0x0000 (---------------) + I bcg 0x002dbf83, // n0x005f c0x0000 (---------------) + I bcn 0x016fbc02, // n0x0060 c0x0005 (---------------)* o I bd 0x07e04702, // n0x0061 c0x001f (n0x061c-n0x061e) + I be 0x00243505, // n0x0062 c0x0000 (---------------) + I beats 0x00391984, // n0x0063 c0x0000 (---------------) + I beer 0x00352147, // n0x0064 c0x0000 (---------------) + I bentley 0x00251d46, // n0x0065 c0x0000 (---------------) + I berlin 0x0030a2c4, // n0x0066 c0x0000 (---------------) + I best 0x00227703, // n0x0067 c0x0000 (---------------) + I bet 0x08349f02, // n0x0068 c0x0020 (n0x061e-n0x061f) + I bf 0x08755e02, // n0x0069 c0x0021 (n0x061f-n0x0644) + I bg 0x08af6202, // n0x006a c0x0022 (n0x0644-n0x0649) + I bh 0x00375006, // n0x006b c0x0000 (---------------) + I bharti 0x08e00002, // n0x006c c0x0023 (n0x0649-n0x064e) + I bi 0x003628c5, // n0x006d c0x0000 (---------------) + I bible 0x002fd143, // n0x006e c0x0000 (---------------) + I bid 0x00390e04, // n0x006f c0x0000 (---------------) + I bike 0x002c7a44, // n0x0070 c0x0000 (---------------) + I bing 0x002c7a45, // n0x0071 c0x0000 (---------------) + I bingo 0x00200003, // n0x0072 c0x0000 (---------------) + I bio 0x09310603, // n0x0073 c0x0024 (n0x064e-n0x0655) + I biz 0x09602642, // n0x0074 c0x0025 (n0x0655-n0x0659) + I bj 0x00277b85, // n0x0075 c0x0000 (---------------) + I black 0x00277b8b, // n0x0076 c0x0000 (---------------) + I blackfriday 0x002d0084, // n0x0077 c0x0000 (---------------) + I blog 0x00205849, // n0x0078 c0x0000 (---------------) + I bloomberg 0x00207184, // n0x0079 c0x0000 (---------------) + I blue 0x09a09242, // n0x007a c0x0026 (n0x0659-n0x065e) + I bm 0x00209243, // n0x007b c0x0000 (---------------) + I bms 0x0020a103, // n0x007c c0x0000 (---------------) + I bmw 0x0160a282, // n0x007d c0x0005 (---------------)* o I bn 0x00243903, // n0x007e c0x0000 (---------------) + I bnl 0x0020a28a, // n0x007f c0x0000 (---------------) + I bnpparibas 0x09e0a702, // n0x0080 c0x0027 (n0x065e-n0x0667) + I bo 0x0034eb85, // n0x0081 c0x0000 (---------------) + I boats 0x0020aac3, // n0x0082 c0x0000 (---------------) + I bom 0x0020b104, // n0x0083 c0x0000 (---------------) + I bond 0x0020c2c3, // n0x0084 c0x0000 (---------------) + I boo 0x0020c2c5, // n0x0085 c0x0000 (---------------) + I boots 0x0020cb05, // n0x0086 c0x0000 (---------------) + I bosch 0x0020d286, // n0x0087 c0x0000 (---------------) + I bostik 0x0020e2c3, // n0x0088 c0x0000 (---------------) + I bot 0x00211048, // n0x0089 c0x0000 (---------------) + I boutique 0x0a212e82, // n0x008a c0x0028 (n0x0667-n0x06ad) + I br 0x00212e88, // n0x008b c0x0000 (---------------) + I bradesco 0x0021a14b, // n0x008c c0x0000 (---------------) + I bridgestone 0x002172c8, // n0x008d c0x0000 (---------------) + I broadway 0x00218046, // n0x008e c0x0000 (---------------) + I broker 0x00219347, // n0x008f c0x0000 (---------------) + I brother 0x0021be88, // n0x0090 c0x0000 (---------------) + I brussels 0x0aa35102, // n0x0091 c0x002a (n0x06ae-n0x06b3) + I bs 0x0ae16fc2, // n0x0092 c0x002b (n0x06b3-n0x06b8) + I bt 0x0033c648, // n0x0093 c0x0000 (---------------) + I budapest 0x002c67c5, // n0x0094 c0x0000 (---------------) + I build 0x00324908, // n0x0095 c0x0000 (---------------) + I builders 0x0025f008, // n0x0096 c0x0000 (---------------) + I business 0x0021d903, // n0x0097 c0x0000 (---------------) + I buy 0x0021e484, // n0x0098 c0x0000 (---------------) + I buzz 0x003401c2, // n0x0099 c0x0000 (---------------) + I bv 0x0b21f782, // n0x009a c0x002c (n0x06b8-n0x06ba) + I bw 0x0b616b42, // n0x009b c0x002d (n0x06ba-n0x06be) + I by 0x0be203c2, // n0x009c c0x002f (n0x06bf-n0x06c5) + I bz 0x002203c3, // n0x009d c0x0000 (---------------) + I bzh 0x0c2055c2, // n0x009e c0x0030 (n0x06c5-n0x06d6) + I ca 0x0036eb03, // n0x009f c0x0000 (---------------) + I cab 0x0026ab84, // n0x00a0 c0x0000 (---------------) + I cafe 0x0020e443, // n0x00a1 c0x0000 (---------------) + I cal 0x002a6544, // n0x00a2 c0x0000 (---------------) + I call 0x0022b406, // n0x00a3 c0x0000 (---------------) + I camera 0x0022c604, // n0x00a4 c0x0000 (---------------) + I camp 0x0029668e, // n0x00a5 c0x0000 (---------------) + I cancerresearch 0x00312a05, // n0x00a6 c0x0000 (---------------) + I canon 0x0021aac8, // n0x00a7 c0x0000 (---------------) + I capetown 0x002c0887, // n0x00a8 c0x0000 (---------------) + I capital 0x00205f83, // n0x00a9 c0x0000 (---------------) + I car 0x002291c7, // n0x00aa c0x0000 (---------------) + I caravan 0x00319505, // n0x00ab c0x0000 (---------------) + I cards 0x00205f84, // n0x00ac c0x0000 (---------------) + I care 0x00205f86, // n0x00ad c0x0000 (---------------) + I career 0x00205f87, // n0x00ae c0x0000 (---------------) + I careers 0x002b9384, // n0x00af c0x0000 (---------------) + I cars 0x00332007, // n0x00b0 c0x0000 (---------------) + I cartier 0x00383904, // n0x00b1 c0x0000 (---------------) + I casa 0x00261b04, // n0x00b2 c0x0000 (---------------) + I cash 0x002112c6, // n0x00b3 c0x0000 (---------------) + I casino 0x0020d0c3, // n0x00b4 c0x0000 (---------------) + I cat 0x003246c8, // n0x00b5 c0x0000 (---------------) + I catering 0x00235d83, // n0x00b6 c0x0000 (---------------) + I cba 0x002438c3, // n0x00b7 c0x0000 (---------------) + I cbn 0x0037dc04, // n0x00b8 c0x0000 (---------------) + I cbre 0x0c61aa82, // n0x00b9 c0x0031 (n0x06d6-n0x06da) + I cc 0x0ca2a082, // n0x00ba c0x0032 (n0x06da-n0x06db) + I cd 0x00215cc3, // n0x00bb c0x0000 (---------------) + I ceb 0x00233a06, // n0x00bc c0x0000 (---------------) + I center 0x002e7743, // n0x00bd c0x0000 (---------------) + I ceo 0x0021d7c4, // n0x00be c0x0000 (---------------) + I cern 0x0cf104c2, // n0x00bf c0x0033 (n0x06db-n0x06dc) + I cf 0x003104c3, // n0x00c0 c0x0000 (---------------) + I cfa 0x00366243, // n0x00c1 c0x0000 (---------------) + I cfd 0x0020ea02, // n0x00c2 c0x0000 (---------------) + I cg 0x0d204a02, // n0x00c3 c0x0034 (n0x06dc-n0x06dd) + I ch 0x002a9f06, // n0x00c4 c0x0000 (---------------) + I chanel 0x00227d87, // n0x00c5 c0x0000 (---------------) + I channel 0x002facc5, // n0x00c6 c0x0000 (---------------) + I chase 0x0023a704, // n0x00c7 c0x0000 (---------------) + I chat 0x0028dec5, // n0x00c8 c0x0000 (---------------) + I cheap 0x00353cc7, // n0x00c9 c0x0000 (---------------) + I chintai 0x00297d05, // n0x00ca c0x0000 (---------------) + I chloe 0x002e5109, // n0x00cb c0x0000 (---------------) + I christmas 0x002e6f86, // n0x00cc c0x0000 (---------------) + I chrome 0x002fabc6, // n0x00cd c0x0000 (---------------) + I church 0x0d6155c2, // n0x00ce c0x0035 (n0x06dd-n0x06ec) + I ci 0x0025f788, // n0x00cf c0x0000 (---------------) + I cipriani 0x00322106, // n0x00d0 c0x0000 (---------------) + I circle 0x00237905, // n0x00d1 c0x0000 (---------------) + I cisco 0x003245c5, // n0x00d2 c0x0000 (---------------) + I citic 0x002735c4, // n0x00d3 c0x0000 (---------------) + I city 0x002735c8, // n0x00d4 c0x0000 (---------------) + I cityeats 0x0da01782, // n0x00d5 c0x0036 (n0x06ec-n0x06ed)* o I ck 0x0de0af42, // n0x00d6 c0x0037 (n0x06ed-n0x06f2) + I cl 0x00357546, // n0x00d7 c0x0000 (---------------) + I claims 0x0032d748, // n0x00d8 c0x0000 (---------------) + I cleaning 0x00367205, // n0x00d9 c0x0000 (---------------) + I click 0x00368f86, // n0x00da c0x0000 (---------------) + I clinic 0x003784c8, // n0x00db c0x0000 (---------------) + I clothing 0x00332205, // n0x00dc c0x0000 (---------------) + I cloud 0x002752c4, // n0x00dd c0x0000 (---------------) + I club 0x002752c7, // n0x00de c0x0000 (---------------) + I clubmed 0x0e249082, // n0x00df c0x0038 (n0x06f2-n0x06f6) + I cm 0x0e6211c2, // n0x00e0 c0x0039 (n0x06f6-n0x0723) + I cn 0x0fe00742, // n0x00e1 c0x003f (n0x0728-n0x0735) + I co 0x0032ca05, // n0x00e2 c0x0000 (---------------) + I coach 0x0028ca05, // n0x00e3 c0x0000 (---------------) + I codes 0x003690c6, // n0x00e4 c0x0000 (---------------) + I coffee 0x0021e787, // n0x00e5 c0x0000 (---------------) + I college 0x002214c7, // n0x00e6 c0x0000 (---------------) + I cologne 0x10622ac3, // n0x00e7 c0x0041 (n0x0736-n0x07ff) + I com 0x002d4148, // n0x00e8 c0x0000 (---------------) + I commbank 0x00222ac9, // n0x00e9 c0x0000 (---------------) + I community 0x002232c7, // n0x00ea c0x0000 (---------------) + I company 0x002236c8, // n0x00eb c0x0000 (---------------) + I computer 0x00223ec6, // n0x00ec c0x0000 (---------------) + I comsec 0x00224306, // n0x00ed c0x0000 (---------------) + I condos 0x00224c0c, // n0x00ee c0x0000 (---------------) + I construction 0x00225a8a, // n0x00ef c0x0000 (---------------) + I consulting 0x00225f47, // n0x00f0 c0x0000 (---------------) + I contact 0x00226e0b, // n0x00f1 c0x0000 (---------------) + I contractors 0x00227bc7, // n0x00f2 c0x0000 (---------------) + I cooking 0x00227bce, // n0x00f3 c0x0000 (---------------) + I cookingchannel 0x00228384, // n0x00f4 c0x0000 (---------------) + I cool 0x00228d44, // n0x00f5 c0x0000 (---------------) + I coop 0x0022b2c7, // n0x00f6 c0x0000 (---------------) + I corsica 0x00362c07, // n0x00f7 c0x0000 (---------------) + I country 0x0022d906, // n0x00f8 c0x0000 (---------------) + I coupon 0x0022d907, // n0x00f9 c0x0000 (---------------) + I coupons 0x0022dc87, // n0x00fa c0x0000 (---------------) + I courses 0x11a0c502, // n0x00fb c0x0046 (n0x081d-n0x0824) + I cr 0x00230646, // n0x00fc c0x0000 (---------------) + I credit 0x0023064a, // n0x00fd c0x0000 (---------------) + I creditcard 0x002308cb, // n0x00fe c0x0000 (---------------) + I creditunion 0x002319c7, // n0x00ff c0x0000 (---------------) + I cricket 0x00232885, // n0x0100 c0x0000 (---------------) + I crown 0x002329c3, // n0x0101 c0x0000 (---------------) + I crs 0x00233147, // n0x0102 c0x0000 (---------------) + I cruises 0x00355d43, // n0x0103 c0x0000 (---------------) + I csc 0x11e24002, // n0x0104 c0x0047 (n0x0824-n0x082a) + I cu 0x002333ca, // n0x0105 c0x0000 (---------------) + I cuisinella 0x1233f802, // n0x0106 c0x0048 (n0x082a-n0x082b) + I cv 0x126b8942, // n0x0107 c0x0049 (n0x082b-n0x082f) + I cw 0x12a35882, // n0x0108 c0x004a (n0x082f-n0x0831) + I cx 0x12e29e42, // n0x0109 c0x004b (n0x0831-n0x083e) o I cy 0x002dcac5, // n0x010a c0x0000 (---------------) + I cymru 0x00235b84, // n0x010b c0x0000 (---------------) + I cyou 0x13614442, // n0x010c c0x004d (n0x083f-n0x0840) + I cz 0x0021bc05, // n0x010d c0x0000 (---------------) + I dabur 0x00264503, // n0x010e c0x0000 (---------------) + I dad 0x0032dec5, // n0x010f c0x0000 (---------------) + I dance 0x00209004, // n0x0110 c0x0000 (---------------) + I date 0x00390f06, // n0x0111 c0x0000 (---------------) + I dating 0x00207286, // n0x0112 c0x0000 (---------------) + I datsun 0x00277d83, // n0x0113 c0x0000 (---------------) + I day 0x00251304, // n0x0114 c0x0000 (---------------) + I dclk 0x002f9383, // n0x0115 c0x0000 (---------------) + I dds 0x13a006c2, // n0x0116 c0x004e (n0x0840-n0x0848) + I de 0x002196c4, // n0x0117 c0x0000 (---------------) + I deal 0x00364186, // n0x0118 c0x0000 (---------------) + I dealer 0x002196c5, // n0x0119 c0x0000 (---------------) + I deals 0x002528c6, // n0x011a c0x0000 (---------------) + I degree 0x00268948, // n0x011b c0x0000 (---------------) + I delivery 0x002297c4, // n0x011c c0x0000 (---------------) + I dell 0x0024f885, // n0x011d c0x0000 (---------------) + I delta 0x0022e548, // n0x011e c0x0000 (---------------) + I democrat 0x00298646, // n0x011f c0x0000 (---------------) + I dental 0x00234ec7, // n0x0120 c0x0000 (---------------) + I dentist 0x00232f44, // n0x0121 c0x0000 (---------------) + I desi 0x00232f46, // n0x0122 c0x0000 (---------------) + I design 0x0030a403, // n0x0123 c0x0000 (---------------) + I dev 0x002b0cc8, // n0x0124 c0x0000 (---------------) + I diamonds 0x002f6384, // n0x0125 c0x0000 (---------------) + I diet 0x002ef0c7, // n0x0126 c0x0000 (---------------) + I digital 0x00352bc6, // n0x0127 c0x0000 (---------------) + I direct 0x00352bc9, // n0x0128 c0x0000 (---------------) + I directory 0x002f87c8, // n0x0129 c0x0000 (---------------) + I discount 0x0020c7c2, // n0x012a c0x0000 (---------------) + I dj 0x13e71742, // n0x012b c0x004f (n0x0848-n0x0849) + I dk 0x142618c2, // n0x012c c0x0050 (n0x0849-n0x084e) + I dm 0x0036cd83, // n0x012d c0x0000 (---------------) + I dnp 0x14604002, // n0x012e c0x0051 (n0x084e-n0x0858) + I do 0x00355cc4, // n0x012f c0x0000 (---------------) + I docs 0x00204003, // n0x0130 c0x0000 (---------------) + I dog 0x0024f044, // n0x0131 c0x0000 (---------------) + I doha 0x002e8307, // n0x0132 c0x0000 (---------------) + I domains 0x0023ba06, // n0x0133 c0x0000 (---------------) + I doosan 0x0031c343, // n0x0134 c0x0000 (---------------) + I dot 0x002ede08, // n0x0135 c0x0000 (---------------) + I download 0x003102c5, // n0x0136 c0x0000 (---------------) + I drive 0x00394cc4, // n0x0137 c0x0000 (---------------) + I dstv 0x002482c3, // n0x0138 c0x0000 (---------------) + I dtv 0x0026a005, // n0x0139 c0x0000 (---------------) + I dubai 0x0031b886, // n0x013a c0x0000 (---------------) + I dunlop 0x0032a4c6, // n0x013b c0x0000 (---------------) + I dupont 0x00383246, // n0x013c c0x0000 (---------------) + I durban 0x00300bc4, // n0x013d c0x0000 (---------------) + I dvag 0x14aa3602, // n0x013e c0x0052 (n0x0858-n0x0860) + I dz 0x00330d85, // n0x013f c0x0000 (---------------) + I earth 0x00242e03, // n0x0140 c0x0000 (---------------) + I eat 0x14e00702, // n0x0141 c0x0053 (n0x0860-n0x086c) + I ec 0x0038d785, // n0x0142 c0x0000 (---------------) + I edeka 0x002d75c3, // n0x0143 c0x0000 (---------------) + I edu 0x00375549, // n0x0144 c0x0000 (---------------) + I education 0x15206042, // n0x0145 c0x0054 (n0x086c-n0x0876) + I ee 0x15a0df82, // n0x0146 c0x0056 (n0x0877-n0x0880) + I eg 0x003435c5, // n0x0147 c0x0000 (---------------) + I email 0x00312206, // n0x0148 c0x0000 (---------------) + I emerck 0x002ba7c6, // n0x0149 c0x0000 (---------------) + I energy 0x002a8a88, // n0x014a c0x0000 (---------------) + I engineer 0x002a8a8b, // n0x014b c0x0000 (---------------) + I engineering 0x0037a7cb, // n0x014c c0x0000 (---------------) + I enterprises 0x00364485, // n0x014d c0x0000 (---------------) + I epson 0x0021f909, // n0x014e c0x0000 (---------------) + I equipment 0x01600ec2, // n0x014f c0x0005 (---------------)* o I er 0x00259904, // n0x0150 c0x0000 (---------------) + I erni 0x162010c2, // n0x0151 c0x0058 (n0x0881-n0x0886) + I es 0x00275b43, // n0x0152 c0x0000 (---------------) + I esq 0x002b1846, // n0x0153 c0x0000 (---------------) + I estate 0x16a0bbc2, // n0x0154 c0x005a (n0x0887-n0x088f) + I et 0x0021d5c2, // n0x0155 c0x0000 (---------------) + I eu 0x002ef88a, // n0x0156 c0x0000 (---------------) + I eurovision 0x002b71c3, // n0x0157 c0x0000 (---------------) + I eus 0x003423c6, // n0x0158 c0x0000 (---------------) + I events 0x00381fc8, // n0x0159 c0x0000 (---------------) + I everbank 0x002f3908, // n0x015a c0x0000 (---------------) + I exchange 0x0030c7c6, // n0x015b c0x0000 (---------------) + I expert 0x00203e87, // n0x015c c0x0000 (---------------) + I exposed 0x0029ab47, // n0x015d c0x0000 (---------------) + I express 0x0021008a, // n0x015e c0x0000 (---------------) + I extraspace 0x00310504, // n0x015f c0x0000 (---------------) + I fage 0x00328344, // n0x0160 c0x0000 (---------------) + I fail 0x0033d609, // n0x0161 c0x0000 (---------------) + I fairwinds 0x00377ec5, // n0x0162 c0x0000 (---------------) + I faith 0x00311c06, // n0x0163 c0x0000 (---------------) + I family 0x0020f1c3, // n0x0164 c0x0000 (---------------) + I fan 0x002c5544, // n0x0165 c0x0000 (---------------) + I fans 0x0021f804, // n0x0166 c0x0000 (---------------) + I farm 0x0025d247, // n0x0167 c0x0000 (---------------) + I fashion 0x00287d44, // n0x0168 c0x0000 (---------------) + I fast 0x00369188, // n0x0169 c0x0000 (---------------) + I feedback 0x003127c7, // n0x016a c0x0000 (---------------) + I ferrero 0x16e099c2, // n0x016b c0x005b (n0x088f-n0x0892) + I fi 0x00356104, // n0x016c c0x0000 (---------------) + I film 0x00356745, // n0x016d c0x0000 (---------------) + I final 0x00368607, // n0x016e c0x0000 (---------------) + I finance 0x00371509, // n0x016f c0x0000 (---------------) + I financial 0x00236744, // n0x0170 c0x0000 (---------------) + I fire 0x00237d49, // n0x0171 c0x0000 (---------------) + I firestone 0x00238548, // n0x0172 c0x0000 (---------------) + I firmdale 0x00238904, // n0x0173 c0x0000 (---------------) + I fish 0x00238907, // n0x0174 c0x0000 (---------------) + I fishing 0x00238f03, // n0x0175 c0x0000 (---------------) + I fit 0x00239087, // n0x0176 c0x0000 (---------------) + I fitness 0x016241c2, // n0x0177 c0x0005 (---------------)* o I fj 0x01697782, // n0x0178 c0x0005 (---------------)* o I fk 0x0023a306, // n0x0179 c0x0000 (---------------) + I flickr 0x0023b147, // n0x017a c0x0000 (---------------) + I flights 0x0023c607, // n0x017b c0x0000 (---------------) + I florist 0x0023ef07, // n0x017c c0x0000 (---------------) + I flowers 0x0023f508, // n0x017d c0x0000 (---------------) + I flsmidth 0x0023ffc3, // n0x017e c0x0000 (---------------) + I fly 0x00358002, // n0x017f c0x0000 (---------------) + I fm 0x00200382, // n0x0180 c0x0000 (---------------) + I fo 0x00241943, // n0x0181 c0x0000 (---------------) + I foo 0x0024194b, // n0x0182 c0x0000 (---------------) + I foodnetwork 0x0030b888, // n0x0183 c0x0000 (---------------) + I football 0x003640c4, // n0x0184 c0x0000 (---------------) + I ford 0x00242f85, // n0x0185 c0x0000 (---------------) + I forex 0x00244a47, // n0x0186 c0x0000 (---------------) + I forsale 0x00246b45, // n0x0187 c0x0000 (---------------) + I forum 0x00303b8a, // n0x0188 c0x0000 (---------------) + I foundation 0x17200d42, // n0x0189 c0x005c (n0x0892-n0x08aa) + I fr 0x0024c6c3, // n0x018a c0x0000 (---------------) + I frl 0x0024c787, // n0x018b c0x0000 (---------------) + I frogans 0x003906c9, // n0x018c c0x0000 (---------------) + I frontdoor 0x00200d48, // n0x018d c0x0000 (---------------) + I frontier 0x0026fc04, // n0x018e c0x0000 (---------------) + I fund 0x00272f09, // n0x018f c0x0000 (---------------) + I furniture 0x002764c6, // n0x0190 c0x0000 (---------------) + I futbol 0x00277503, // n0x0191 c0x0000 (---------------) + I fyi 0x00201602, // n0x0192 c0x0000 (---------------) + I ga 0x00215b83, // n0x0193 c0x0000 (---------------) + I gal 0x00226607, // n0x0194 c0x0000 (---------------) + I gallery 0x00362a05, // n0x0195 c0x0000 (---------------) + I gallo 0x0036bd46, // n0x0196 c0x0000 (---------------) + I gallup 0x00212084, // n0x0197 c0x0000 (---------------) + I game 0x002d2145, // n0x0198 c0x0000 (---------------) + I games 0x0020e506, // n0x0199 c0x0000 (---------------) + I garden 0x00205a42, // n0x019a c0x0000 (---------------) + I gb 0x00378f84, // n0x019b c0x0000 (---------------) + I gbiz 0x0021b342, // n0x019c c0x0000 (---------------) + I gd 0x002d0143, // n0x019d c0x0000 (---------------) + I gdn 0x176012c2, // n0x019e c0x005d (n0x08aa-n0x08b1) + I ge 0x00237543, // n0x019f c0x0000 (---------------) + I gea 0x0020db04, // n0x01a0 c0x0000 (---------------) + I gent 0x0020db07, // n0x01a1 c0x0000 (---------------) + I genting 0x00248e82, // n0x01a2 c0x0000 (---------------) + I gf 0x17a00402, // n0x01a3 c0x005e (n0x08b1-n0x08b4) + I gg 0x00268b44, // n0x01a4 c0x0000 (---------------) + I ggee 0x17e36e42, // n0x01a5 c0x005f (n0x08b4-n0x08b9) + I gh 0x18200442, // n0x01a6 c0x0060 (n0x08b9-n0x08bf) + I gi 0x0030f704, // n0x01a7 c0x0000 (---------------) + I gift 0x0030f705, // n0x01a8 c0x0000 (---------------) + I gifts 0x002b9bc5, // n0x01a9 c0x0000 (---------------) + I gives 0x00213586, // n0x01aa c0x0000 (---------------) + I giving 0x18629902, // n0x01ab c0x0061 (n0x08bf-n0x08c4) + I gl 0x0034da85, // n0x01ac c0x0000 (---------------) + I glass 0x00274303, // n0x01ad c0x0000 (---------------) + I gle 0x00389c06, // n0x01ae c0x0000 (---------------) + I global 0x0038a445, // n0x01af c0x0000 (---------------) + I globo 0x002047c2, // n0x01b0 c0x0000 (---------------) + I gm 0x00323145, // n0x01b1 c0x0000 (---------------) + I gmail 0x00208443, // n0x01b2 c0x0000 (---------------) + I gmo 0x0020a643, // n0x01b3 c0x0000 (---------------) + I gmx 0x18a050c2, // n0x01b4 c0x0062 (n0x08c4-n0x08ca) + I gn 0x00238a84, // n0x01b5 c0x0000 (---------------) + I gold 0x00238a89, // n0x01b6 c0x0000 (---------------) + I goldpoint 0x0025d184, // n0x01b7 c0x0000 (---------------) + I golf 0x0028c883, // n0x01b8 c0x0000 (---------------) + I goo 0x00330c48, // n0x01b9 c0x0000 (---------------) + I goodyear 0x0028c884, // n0x01ba c0x0000 (---------------) + I goog 0x0028c886, // n0x01bb c0x0000 (---------------) + I google 0x0028e783, // n0x01bc c0x0000 (---------------) + I gop 0x0020bec3, // n0x01bd c0x0000 (---------------) + I got 0x0020bec4, // n0x01be c0x0000 (---------------) + I gotv 0x0021e283, // n0x01bf c0x0000 (---------------) + I gov 0x18ece142, // n0x01c0 c0x0063 (n0x08ca-n0x08d0) + I gp 0x0034f382, // n0x01c1 c0x0000 (---------------) + I gq 0x1920dc82, // n0x01c2 c0x0064 (n0x08d0-n0x08d6) + I gr 0x002ff248, // n0x01c3 c0x0000 (---------------) + I grainger 0x00341188, // n0x01c4 c0x0000 (---------------) + I graphics 0x0037d046, // n0x01c5 c0x0000 (---------------) + I gratis 0x0025b105, // n0x01c6 c0x0000 (---------------) + I green 0x0021dd45, // n0x01c7 c0x0000 (---------------) + I gripe 0x002646c5, // n0x01c8 c0x0000 (---------------) + I group 0x0026cd02, // n0x01c9 c0x0000 (---------------) + I gs 0x19651202, // n0x01ca c0x0065 (n0x08d6-n0x08dd) + I gt 0x01629702, // n0x01cb c0x0005 (---------------)* o I gu 0x0025f6c5, // n0x01cc c0x0000 (---------------) + I gucci 0x002ca244, // n0x01cd c0x0000 (---------------) + I guge 0x00229705, // n0x01ce c0x0000 (---------------) + I guide 0x0022d647, // n0x01cf c0x0000 (---------------) + I guitars 0x0025bc44, // n0x01d0 c0x0000 (---------------) + I guru 0x00204b82, // n0x01d1 c0x0000 (---------------) + I gw 0x19a25a02, // n0x01d2 c0x0066 (n0x08dd-n0x08e0) + I gy 0x0038a2c7, // n0x01d3 c0x0000 (---------------) + I hamburg 0x00392287, // n0x01d4 c0x0000 (---------------) + I hangout 0x00329884, // n0x01d5 c0x0000 (---------------) + I haus 0x00235cc8, // n0x01d6 c0x0000 (---------------) + I hdfcbank 0x00205e06, // n0x01d7 c0x0000 (---------------) + I health 0x00205e0a, // n0x01d8 c0x0000 (---------------) + I healthcare 0x00205204, // n0x01d9 c0x0000 (---------------) + I help 0x00209408, // n0x01da c0x0000 (---------------) + I helsinki 0x0023f784, // n0x01db c0x0000 (---------------) + I here 0x00219446, // n0x01dc c0x0000 (---------------) + I hermes 0x00280244, // n0x01dd c0x0000 (---------------) + I hgtv 0x0032cd06, // n0x01de c0x0000 (---------------) + I hiphop 0x0028d547, // n0x01df c0x0000 (---------------) + I hitachi 0x0025f603, // n0x01e0 c0x0000 (---------------) + I hiv 0x19e2ea02, // n0x01e1 c0x0067 (n0x08e0-n0x08f8) + I hk 0x0025ab03, // n0x01e2 c0x0000 (---------------) + I hkt 0x00206182, // n0x01e3 c0x0000 (---------------) + I hm 0x1a217542, // n0x01e4 c0x0068 (n0x08f8-n0x08fe) + I hn 0x002cd886, // n0x01e5 c0x0000 (---------------) + I hockey 0x0034b148, // n0x01e6 c0x0000 (---------------) + I holdings 0x00290807, // n0x01e7 c0x0000 (---------------) + I holiday 0x002b8e89, // n0x01e8 c0x0000 (---------------) + I homedepot 0x00291385, // n0x01e9 c0x0000 (---------------) + I homes 0x00292005, // n0x01ea c0x0000 (---------------) + I honda 0x00293c05, // n0x01eb c0x0000 (---------------) + I horse 0x00202fc4, // n0x01ec c0x0000 (---------------) + I host 0x002836c7, // n0x01ed c0x0000 (---------------) + I hosting 0x00294947, // n0x01ee c0x0000 (---------------) + I hoteles 0x00294fc7, // n0x01ef c0x0000 (---------------) + I hotmail 0x0021da05, // n0x01f0 c0x0000 (---------------) + I house 0x00297383, // n0x01f1 c0x0000 (---------------) + I how 0x1a625842, // n0x01f2 c0x0069 (n0x08fe-n0x0903) + I hr 0x002dbf04, // n0x01f3 c0x0000 (---------------) + I hsbc 0x1aa36e82, // n0x01f4 c0x006a (n0x0903-n0x0914) + I ht 0x00249003, // n0x01f5 c0x0000 (---------------) + I htc 0x1ae17d42, // n0x01f6 c0x006b (n0x0914-n0x0934) + I hu 0x0031b7c3, // n0x01f7 c0x0000 (---------------) + I ibm 0x0028bf44, // n0x01f8 c0x0000 (---------------) + I icbc 0x00200b43, // n0x01f9 c0x0000 (---------------) + I ice 0x0033c383, // n0x01fa c0x0000 (---------------) + I icu 0x1b206202, // n0x01fb c0x006c (n0x0934-n0x093f) + I id 0x1ba00e82, // n0x01fc c0x006e (n0x0940-n0x0942) + I ie 0x00370d03, // n0x01fd c0x0000 (---------------) + I ifm 0x0031cac5, // n0x01fe c0x0000 (---------------) + I iinet 0x1be036c2, // n0x01ff c0x006f (n0x0942-n0x0943)* o I il 0x1c603582, // n0x0200 c0x0071 (n0x0944-n0x094b) + I im 0x002f4284, // n0x0201 c0x0000 (---------------) + I imdb 0x00203584, // n0x0202 c0x0000 (---------------) + I immo 0x0020358a, // n0x0203 c0x0000 (---------------) + I immobilien 0x1ce00242, // n0x0204 c0x0073 (n0x094d-n0x095a) + I in 0x00353eca, // n0x0205 c0x0000 (---------------) + I industries 0x00355408, // n0x0206 c0x0000 (---------------) + I infiniti 0x1d200304, // n0x0207 c0x0074 (n0x095a-n0x0964) + I info 0x0020dc03, // n0x0208 c0x0000 (---------------) + I ing 0x00209503, // n0x0209 c0x0000 (---------------) + I ink 0x002ed209, // n0x020a c0x0000 (---------------) + I institute 0x002806c9, // n0x020b c0x0000 (---------------) + I insurance 0x002e8406, // n0x020c c0x0000 (---------------) + I insure 0x1d638c03, // n0x020d c0x0075 (n0x0964-n0x0965) + I int 0x002dd88d, // n0x020e c0x0000 (---------------) + I international 0x002087cb, // n0x020f c0x0000 (---------------) + I investments 0x1da00042, // n0x0210 c0x0076 (n0x0965-n0x0968) + I io 0x00331048, // n0x0211 c0x0000 (---------------) + I ipiranga 0x1de11142, // n0x0212 c0x0077 (n0x0968-n0x096e) + I iq 0x1e200542, // n0x0213 c0x0078 (n0x096e-n0x0977) + I ir 0x00294c05, // n0x0214 c0x0000 (---------------) + I irish 0x1e602b42, // n0x0215 c0x0079 (n0x0977-n0x097f) + I is 0x00370f07, // n0x0216 c0x0000 (---------------) + I iselect 0x00202b43, // n0x0217 c0x0000 (---------------) + I ist 0x00210c48, // n0x0218 c0x0000 (---------------) + I istanbul 0x1ea06e82, // n0x0219 c0x007a (n0x097f-n0x0af0) + I it 0x00206e84, // n0x021a c0x0000 (---------------) + I itau 0x003664c3, // n0x021b c0x0000 (---------------) + I iwc 0x002a51c6, // n0x021c c0x0000 (---------------) + I jaguar 0x0030ad84, // n0x021d c0x0000 (---------------) + I java 0x00243883, // n0x021e c0x0000 (---------------) + I jcb 0x0025b3c3, // n0x021f c0x0000 (---------------) + I jcp 0x1ee01f82, // n0x0220 c0x007b (n0x0af0-n0x0af3) + I je 0x0033ab85, // n0x0221 c0x0000 (---------------) + I jetzt 0x0034f487, // n0x0222 c0x0000 (---------------) + I jewelry 0x00266583, // n0x0223 c0x0000 (---------------) + I jio 0x00297c83, // n0x0224 c0x0000 (---------------) + I jlc 0x00297e43, // n0x0225 c0x0000 (---------------) + I jll 0x01697f02, // n0x0226 c0x0005 (---------------)* o I jm 0x00297f03, // n0x0227 c0x0000 (---------------) + I jmp 0x002987c3, // n0x0228 c0x0000 (---------------) + I jnj 0x1f202982, // n0x0229 c0x007c (n0x0af3-n0x0afb) + I jo 0x002a5d04, // n0x022a c0x0000 (---------------) + I jobs 0x00389ac6, // n0x022b c0x0000 (---------------) + I joburg 0x00203903, // n0x022c c0x0000 (---------------) + I jot 0x00298c43, // n0x022d c0x0000 (---------------) + I joy 0x1f6990c2, // n0x022e c0x007d (n0x0afb-n0x0b6a) + I jp 0x002990c8, // n0x022f c0x0000 (---------------) + I jpmorgan 0x0029ccc4, // n0x0230 c0x0000 (---------------) + I jprs 0x002faec6, // n0x0231 c0x0000 (---------------) + I juegos 0x002e6846, // n0x0232 c0x0000 (---------------) + I kaufen 0x00233fc4, // n0x0233 c0x0000 (---------------) + I kddi 0x2d201002, // n0x0234 c0x00b4 (n0x11fe-n0x11ff)* o I ke 0x002a6f4b, // n0x0235 c0x0000 (---------------) + I kerryhotels 0x0021268e, // n0x0236 c0x0000 (---------------) + I kerrylogistics 0x0021810f, // n0x0237 c0x0000 (---------------) + I kerryproperties 0x00235e83, // n0x0238 c0x0000 (---------------) + I kfh 0x2daa3fc2, // n0x0239 c0x00b6 (n0x1200-n0x1206) + I kg 0x016176c2, // n0x023a c0x0005 (---------------)* o I kh 0x2de01b02, // n0x023b c0x00b7 (n0x1206-n0x120d) + I ki 0x0027d603, // n0x023c c0x0000 (---------------) + I kim 0x002f33c6, // n0x023d c0x0000 (---------------) + I kinder 0x00227886, // n0x023e c0x0000 (---------------) + I kindle 0x00298f07, // n0x023f c0x0000 (---------------) + I kitchen 0x002d2dc4, // n0x0240 c0x0000 (---------------) + I kiwi 0x2e268d82, // n0x0241 c0x00b8 (n0x120d-n0x121e) + I km 0x2e656942, // n0x0242 c0x00b9 (n0x121e-n0x1222) + I kn 0x0021f385, // n0x0243 c0x0000 (---------------) + I koeln 0x002be447, // n0x0244 c0x0000 (---------------) + I komatsu 0x2ea08382, // n0x0245 c0x00ba (n0x1222-n0x1228) + I kp 0x00208384, // n0x0246 c0x0000 (---------------) + I kpmg 0x00360183, // n0x0247 c0x0000 (---------------) + I kpn 0x2ee034c2, // n0x0248 c0x00bb (n0x1228-n0x1246) + I kr 0x0033a003, // n0x0249 c0x0000 (---------------) + I krd 0x0029d8c4, // n0x024a c0x0000 (---------------) + I kred 0x002a3f09, // n0x024b c0x0000 (---------------) + I kuokgroup 0x016ac642, // n0x024c c0x0005 (---------------)* o I kw 0x2f229082, // n0x024d c0x00bc (n0x1246-n0x124b) + I ky 0x002568c6, // n0x024e c0x0000 (---------------) + I kyknet 0x002acb05, // n0x024f c0x0000 (---------------) + I kyoto 0x2f6f0002, // n0x0250 c0x00bd (n0x124b-n0x1251) + I kz 0x2fa01e42, // n0x0251 c0x00be (n0x1251-n0x125a) + I la 0x003276c7, // n0x0252 c0x0000 (---------------) + I lacaixa 0x0033df4b, // n0x0253 c0x0000 (---------------) + I lamborghini 0x002335c9, // n0x0254 c0x0000 (---------------) + I lancaster 0x002364c4, // n0x0255 c0x0000 (---------------) + I land 0x0036d989, // n0x0256 c0x0000 (---------------) + I landrover 0x002679c7, // n0x0257 c0x0000 (---------------) + I lasalle 0x00222143, // n0x0258 c0x0000 (---------------) + I lat 0x002c18c7, // n0x0259 c0x0000 (---------------) + I latrobe 0x00253883, // n0x025a c0x0000 (---------------) + I law 0x00270406, // n0x025b c0x0000 (---------------) + I lawyer 0x2fe0a542, // n0x025c c0x00bf (n0x125a-n0x125f) + I lb 0x302339c2, // n0x025d c0x00c0 (n0x125f-n0x1265) + I lc 0x0021fbc3, // n0x025e c0x0000 (---------------) + I lds 0x00267b05, // n0x025f c0x0000 (---------------) + I lease 0x0025f307, // n0x0260 c0x0000 (---------------) + I leclerc 0x00362985, // n0x0261 c0x0000 (---------------) + I legal 0x002ad945, // n0x0262 c0x0000 (---------------) + I lexus 0x002ce984, // n0x0263 c0x0000 (---------------) + I lgbt 0x306008c2, // n0x0264 c0x00c1 (n0x1265-n0x1266) + I li 0x002ee607, // n0x0265 c0x0000 (---------------) + I liaison 0x002aadc4, // n0x0266 c0x0000 (---------------) + I lidl 0x00247844, // n0x0267 c0x0000 (---------------) + I life 0x0031c64d, // n0x0268 c0x0000 (---------------) + I lifeinsurance 0x00247849, // n0x0269 c0x0000 (---------------) + I lifestyle 0x00236dc8, // n0x026a c0x0000 (---------------) + I lighting 0x00261684, // n0x026b c0x0000 (---------------) + I like 0x002edc87, // n0x026c c0x0000 (---------------) + I limited 0x002ee1c4, // n0x026d c0x0000 (---------------) + I limo 0x00251e07, // n0x026e c0x0000 (---------------) + I lincoln 0x0031dc05, // n0x026f c0x0000 (---------------) + I linde 0x0031e2c4, // n0x0270 c0x0000 (---------------) + I link 0x002bfc05, // n0x0271 c0x0000 (---------------) + I lipsy 0x0024b384, // n0x0272 c0x0000 (---------------) + I live 0x002d7785, // n0x0273 c0x0000 (---------------) + I lixil 0x30a08342, // n0x0274 c0x00c2 (n0x1266-n0x1275) + I lk 0x0020ab84, // n0x0275 c0x0000 (---------------) + I loan 0x0020ab85, // n0x0276 c0x0000 (---------------) + I loans 0x0020af86, // n0x0277 c0x0000 (---------------) + I locker 0x00362ac5, // n0x0278 c0x0000 (---------------) + I locus 0x002c1ec3, // n0x0279 c0x0000 (---------------) + I lol 0x00340906, // n0x027a c0x0000 (---------------) + I london 0x00364385, // n0x027b c0x0000 (---------------) + I lotte 0x00206505, // n0x027c c0x0000 (---------------) + I lotto 0x002123c4, // n0x027d c0x0000 (---------------) + I love 0x30e76e02, // n0x027e c0x00c3 (n0x1275-n0x127a) + I lr 0x31202d42, // n0x027f c0x00c4 (n0x127a-n0x127c) + I ls 0x31605ec2, // n0x0280 c0x00c5 (n0x127c-n0x127e) + I lt 0x003413c3, // n0x0281 c0x0000 (---------------) + I ltd 0x003413c4, // n0x0282 c0x0000 (---------------) + I ltda 0x31a071c2, // n0x0283 c0x00c6 (n0x127e-n0x127f) + I lu 0x0036be05, // n0x0284 c0x0000 (---------------) + I lupin 0x00222d84, // n0x0285 c0x0000 (---------------) + I luxe 0x00225dc6, // n0x0286 c0x0000 (---------------) + I luxury 0x31e27f02, // n0x0287 c0x00c7 (n0x127f-n0x1288) + I lv 0x32228b42, // n0x0288 c0x00c8 (n0x1288-n0x1291) + I ly 0x32604302, // n0x0289 c0x00c9 (n0x1291-n0x1297) + I ma 0x00300a86, // n0x028a c0x0000 (---------------) + I madrid 0x0032a984, // n0x028b c0x0000 (---------------) + I maif 0x0033c9c6, // n0x028c c0x0000 (---------------) + I maison 0x0026a746, // n0x028d c0x0000 (---------------) + I makeup 0x00206903, // n0x028e c0x0000 (---------------) + I man 0x00351aca, // n0x028f c0x0000 (---------------) + I management 0x0022a685, // n0x0290 c0x0000 (---------------) + I mango 0x0029bcc6, // n0x0291 c0x0000 (---------------) + I market 0x00357049, // n0x0292 c0x0000 (---------------) + I marketing 0x0029bcc7, // n0x0293 c0x0000 (---------------) + I markets 0x0027c808, // n0x0294 c0x0000 (---------------) + I marriott 0x00271143, // n0x0295 c0x0000 (---------------) + I mba 0x32a3a6c2, // n0x0296 c0x00ca (n0x1297-n0x1299) + I mc 0x32e38602, // n0x0297 c0x00cb (n0x1299-n0x129a) + I md 0x33208942, // n0x0298 c0x00cc (n0x129a-n0x12a2) + I me 0x002dc385, // n0x0299 c0x0000 (---------------) + I media 0x00282f44, // n0x029a c0x0000 (---------------) + I meet 0x0020fe89, // n0x029b c0x0000 (---------------) + I melbourne 0x003121c4, // n0x029c c0x0000 (---------------) + I meme 0x002edac8, // n0x029d c0x0000 (---------------) + I memorial 0x00208943, // n0x029e c0x0000 (---------------) + I men 0x0034d804, // n0x029f c0x0000 (---------------) + I menu 0x0023a883, // n0x02a0 c0x0000 (---------------) + I meo 0x0031c587, // n0x02a1 c0x0000 (---------------) + I metlife 0x33608402, // n0x02a2 c0x00cd (n0x12a2-n0x12aa) + I mg 0x00249282, // n0x02a3 c0x0000 (---------------) + I mh 0x002322c5, // n0x02a4 c0x0000 (---------------) + I miami 0x00257ec9, // n0x02a5 c0x0000 (---------------) + I microsoft 0x0023fa03, // n0x02a6 c0x0000 (---------------) + I mil 0x0026b344, // n0x02a7 c0x0000 (---------------) + I mini 0x00246f03, // n0x02a8 c0x0000 (---------------) + I mit 0x33b56d82, // n0x02a9 c0x00ce (n0x12aa-n0x12b2) + I mk 0x33e0ab42, // n0x02aa c0x00cf (n0x12b2-n0x12b9) + I ml 0x002afd83, // n0x02ab c0x0000 (---------------) + I mlb 0x00358b83, // n0x02ac c0x0000 (---------------) + I mls 0x016035c2, // n0x02ad c0x0005 (---------------)* o I mm 0x003679c3, // n0x02ae c0x0000 (---------------) + I mma 0x34217082, // n0x02af c0x00d0 (n0x12b9-n0x12bd) + I mn 0x00217084, // n0x02b0 c0x0000 (---------------) + I mnet 0x34603602, // n0x02b1 c0x00d1 (n0x12bd-n0x12c2) + I mo 0x00203604, // n0x02b2 c0x0000 (---------------) + I mobi 0x002cc406, // n0x02b3 c0x0000 (---------------) + I mobily 0x00208484, // n0x02b4 c0x0000 (---------------) + I moda 0x002fb2c3, // n0x02b5 c0x0000 (---------------) + I moe 0x0038f703, // n0x02b6 c0x0000 (---------------) + I moi 0x0021cfc3, // n0x02b7 c0x0000 (---------------) + I mom 0x00230c46, // n0x02b8 c0x0000 (---------------) + I monash 0x002b6185, // n0x02b9 c0x0000 (---------------) + I money 0x00261909, // n0x02ba c0x0000 (---------------) + I montblanc 0x002b60c6, // n0x02bb c0x0000 (---------------) + I mormon 0x002b66c8, // n0x02bc c0x0000 (---------------) + I mortgage 0x002b68c6, // n0x02bd c0x0000 (---------------) + I moscow 0x0025cb84, // n0x02be c0x0000 (---------------) + I moto 0x0028678b, // n0x02bf c0x0000 (---------------) + I motorcycles 0x002b8403, // n0x02c0 c0x0000 (---------------) + I mov 0x002b8405, // n0x02c1 c0x0000 (---------------) + I movie 0x002b8548, // n0x02c2 c0x0000 (---------------) + I movistar 0x00214902, // n0x02c3 c0x0000 (---------------) + I mp 0x003279c2, // n0x02c4 c0x0000 (---------------) + I mq 0x34adcb42, // n0x02c5 c0x00d2 (n0x12c2-n0x12c4) + I mr 0x34e09282, // n0x02c6 c0x00d3 (n0x12c4-n0x12c9) + I ms 0x35259642, // n0x02c7 c0x00d4 (n0x12c9-n0x12cd) + I mt 0x00259643, // n0x02c8 c0x0000 (---------------) + I mtn 0x002b8844, // n0x02c9 c0x0000 (---------------) + I mtpc 0x002b9703, // n0x02ca c0x0000 (---------------) + I mtr 0x35a000c2, // n0x02cb c0x00d6 (n0x12ce-n0x12d5) + I mu 0x002bae0b, // n0x02cc c0x0000 (---------------) + I multichoice 0x35ebd646, // n0x02cd c0x00d7 (n0x12d5-n0x14f9) + I museum 0x0036d306, // n0x02ce c0x0000 (---------------) + I mutual 0x002bdc88, // n0x02cf c0x0000 (---------------) + I mutuelle 0x3624ffc2, // n0x02d0 c0x00d8 (n0x14f9-n0x1507) + I mv 0x3660a142, // n0x02d1 c0x00d9 (n0x1507-n0x1512) + I mw 0x36a0a682, // n0x02d2 c0x00da (n0x1512-n0x1518) + I mx 0x36e20282, // n0x02d3 c0x00db (n0x1518-n0x1520) + I my 0x372c6c02, // n0x02d4 c0x00dc (n0x1520-n0x1521)* o I mz 0x002c6c0b, // n0x02d5 c0x0000 (---------------) + I mzansimagic 0x37600282, // n0x02d6 c0x00dd (n0x1521-n0x1532) + I na 0x002f3845, // n0x02d7 c0x0000 (---------------) + I nadex 0x0032b206, // n0x02d8 c0x0000 (---------------) + I nagoya 0x37a98944, // n0x02d9 c0x00de (n0x1532-n0x1534) + I name 0x0030cfc7, // n0x02da c0x0000 (---------------) + I naspers 0x00240dc6, // n0x02db c0x0000 (---------------) + I natura 0x0037fe44, // n0x02dc c0x0000 (---------------) + I navy 0x3861c742, // n0x02dd c0x00e1 (n0x1536-n0x1537) + I nc 0x00201082, // n0x02de c0x0000 (---------------) + I ne 0x00305e83, // n0x02df c0x0000 (---------------) + I nec 0x38a170c3, // n0x02e0 c0x00e2 (n0x1537-n0x1568) + I net 0x002efe87, // n0x02e1 c0x0000 (---------------) + I netbank 0x002d7687, // n0x02e2 c0x0000 (---------------) + I netflix 0x00241a47, // n0x02e3 c0x0000 (---------------) + I network 0x00319107, // n0x02e4 c0x0000 (---------------) + I neustar 0x0021a383, // n0x02e5 c0x0000 (---------------) + I new 0x00366d44, // n0x02e6 c0x0000 (---------------) + I news 0x00210044, // n0x02e7 c0x0000 (---------------) + I next 0x00352aca, // n0x02e8 c0x0000 (---------------) + I nextdirect 0x00255985, // n0x02e9 c0x0000 (---------------) + I nexus 0x39e00342, // n0x02ea c0x00e7 (n0x1570-n0x157a) + I nf 0x3a201282, // n0x02eb c0x00e8 (n0x157a-n0x1583) + I ng 0x00202303, // n0x02ec c0x0000 (---------------) + I ngo 0x0025aac3, // n0x02ed c0x0000 (---------------) + I nhk 0x01603d42, // n0x02ee c0x0005 (---------------)* o I ni 0x00369044, // n0x02ef c0x0000 (---------------) + I nico 0x00204c45, // n0x02f0 c0x0000 (---------------) + I nikon 0x002bbfc5, // n0x02f1 c0x0000 (---------------) + I ninja 0x0029c346, // n0x02f2 c0x0000 (---------------) + I nissan 0x3aa36482, // n0x02f3 c0x00ea (n0x1584-n0x1587) + I nl 0x3ae00c02, // n0x02f4 c0x00eb (n0x1587-n0x185d) + I no 0x00201b85, // n0x02f5 c0x0000 (---------------) + I nokia 0x0036d012, // n0x02f6 c0x0000 (---------------) + I northwesternmutual 0x00204546, // n0x02f7 c0x0000 (---------------) + I norton 0x0021c343, // n0x02f8 c0x0000 (---------------) + I now 0x0036a0c6, // n0x02f9 c0x0000 (---------------) + I nowruz 0x0030b645, // n0x02fa c0x0000 (---------------) + I nowtv 0x0160a2c2, // n0x02fb c0x0005 (---------------)* o I np 0x43209e82, // n0x02fc c0x010c (n0x1885-n0x188c) + I nr 0x002cc1c3, // n0x02fd c0x0000 (---------------) + I nra 0x00345903, // n0x02fe c0x0000 (---------------) + I nrw 0x00361083, // n0x02ff c0x0000 (---------------) + I ntt 0x43605bc2, // n0x0300 c0x010d (n0x188c-n0x188f) + I nu 0x00223403, // n0x0301 c0x0000 (---------------) + I nyc 0x43a078c2, // n0x0302 c0x010e (n0x188f-n0x189f) + I nz 0x00203643, // n0x0303 c0x0000 (---------------) + I obi 0x002a5d48, // n0x0304 c0x0000 (---------------) + I observer 0x00219c46, // n0x0305 c0x0000 (---------------) + I office 0x003954c7, // n0x0306 c0x0000 (---------------) + I okinawa 0x002a2686, // n0x0307 c0x0000 (---------------) + I olayan 0x002a268b, // n0x0308 c0x0000 (---------------) + I olayangroup 0x002dbd04, // n0x0309 c0x0000 (---------------) + I ollo 0x44200082, // n0x030a c0x0110 (n0x18a0-n0x18a9) + I om 0x0036bc85, // n0x030b c0x0000 (---------------) + I omega 0x0021a343, // n0x030c c0x0000 (---------------) + I one 0x00292c83, // n0x030d c0x0000 (---------------) + I ong 0x003023c3, // n0x030e c0x0000 (---------------) + I onl 0x003023c6, // n0x030f c0x0000 (---------------) + I online 0x0027b9c3, // n0x0310 c0x0000 (---------------) + I ooo 0x0032d686, // n0x0311 c0x0000 (---------------) + I oracle 0x002a6246, // n0x0312 c0x0000 (---------------) + I orange 0x4461dcc3, // n0x0313 c0x0111 (n0x18a9-n0x18e3) + I org 0x00299187, // n0x0314 c0x0000 (---------------) + I organic 0x0029a9cd, // n0x0315 c0x0000 (---------------) + I orientexpress 0x002864c5, // n0x0316 c0x0000 (---------------) + I osaka 0x00239506, // n0x0317 c0x0000 (---------------) + I otsuka 0x00206543, // n0x0318 c0x0000 (---------------) + I ott 0x00389e43, // n0x0319 c0x0000 (---------------) + I ovh 0x45e052c2, // n0x031a c0x0117 (n0x1920-n0x192b) + I pa 0x00310fc4, // n0x031b c0x0000 (---------------) + I page 0x002fb60c, // n0x031c c0x0000 (---------------) + I pamperedchef 0x0022c007, // n0x031d c0x0000 (---------------) + I panerai 0x0025b445, // n0x031e c0x0000 (---------------) + I paris 0x0028f504, // n0x031f c0x0000 (---------------) + I pars 0x00297f88, // n0x0320 c0x0000 (---------------) + I partners 0x002c2085, // n0x0321 c0x0000 (---------------) + I parts 0x002a2905, // n0x0322 c0x0000 (---------------) + I party 0x002a4109, // n0x0323 c0x0000 (---------------) + I passagens 0x002ab584, // n0x0324 c0x0000 (---------------) + I payu 0x002b88c4, // n0x0325 c0x0000 (---------------) + I pccw 0x46214942, // n0x0326 c0x0118 (n0x192b-n0x1933) + I pe 0x0021ab43, // n0x0327 c0x0000 (---------------) + I pet 0x46764f42, // n0x0328 c0x0119 (n0x1933-n0x1936) + I pf 0x016bf182, // n0x0329 c0x0005 (---------------)* o I pg 0x46a8f0c2, // n0x032a c0x011a (n0x1936-n0x193e) + I ph 0x002dc948, // n0x032b c0x0000 (---------------) + I pharmacy 0x002bfb47, // n0x032c c0x0000 (---------------) + I philips 0x0028f0c5, // n0x032d c0x0000 (---------------) + I photo 0x002c014b, // n0x032e c0x0000 (---------------) + I photography 0x002bea86, // n0x032f c0x0000 (---------------) + I photos 0x002c0346, // n0x0330 c0x0000 (---------------) + I physio 0x002c04c6, // n0x0331 c0x0000 (---------------) + I piaget 0x0021ec04, // n0x0332 c0x0000 (---------------) + I pics 0x002c0a46, // n0x0333 c0x0000 (---------------) + I pictet 0x002c0fc8, // n0x0334 c0x0000 (---------------) + I pictures 0x0022c6c3, // n0x0335 c0x0000 (---------------) + I pid 0x00243743, // n0x0336 c0x0000 (---------------) + I pin 0x00243744, // n0x0337 c0x0000 (---------------) + I ping 0x002c1c84, // n0x0338 c0x0000 (---------------) + I pink 0x002c3cc5, // n0x0339 c0x0000 (---------------) + I pizza 0x46ec3e02, // n0x033a c0x011b (n0x193e-n0x194c) + I pk 0x47201e02, // n0x033b c0x011c (n0x194c-n0x19f1) + I pl 0x00201e05, // n0x033c c0x0000 (---------------) + I place 0x00290d44, // n0x033d c0x0000 (---------------) + I play 0x002c61cb, // n0x033e c0x0000 (---------------) + I playstation 0x002c7948, // n0x033f c0x0000 (---------------) + I plumbing 0x002c7b84, // n0x0340 c0x0000 (---------------) + I plus 0x002083c2, // n0x0341 c0x0000 (---------------) + I pm 0x47a3df82, // n0x0342 c0x011e (n0x1a20-n0x1a25) + I pn 0x0029a743, // n0x0343 c0x0000 (---------------) + I pnc 0x002c7fc4, // n0x0344 c0x0000 (---------------) + I pohl 0x002c80c5, // n0x0345 c0x0000 (---------------) + I poker 0x002c9d84, // n0x0346 c0x0000 (---------------) + I porn 0x002b31c4, // n0x0347 c0x0000 (---------------) + I post 0x47e18242, // n0x0348 c0x011f (n0x1a25-n0x1a32) + I pr 0x0025da85, // n0x0349 c0x0000 (---------------) + I praxi 0x0029abc5, // n0x034a c0x0000 (---------------) + I press 0x002cad45, // n0x034b c0x0000 (---------------) + I prime 0x48218243, // n0x034c c0x0120 (n0x1a32-n0x1a39) + I pro 0x002cbe44, // n0x034d c0x0000 (---------------) + I prod 0x002cbe4b, // n0x034e c0x0000 (---------------) + I productions 0x002cc284, // n0x034f c0x0000 (---------------) + I prof 0x002cca85, // n0x0350 c0x0000 (---------------) + I promo 0x0021824a, // n0x0351 c0x0000 (---------------) + I properties 0x002cce48, // n0x0352 c0x0000 (---------------) + I property 0x002cd04a, // n0x0353 c0x0000 (---------------) + I protection 0x4861dc02, // n0x0354 c0x0121 (n0x1a39-n0x1a40) + I ps 0x48a95982, // n0x0355 c0x0122 (n0x1a40-n0x1a49) + I pt 0x00296543, // n0x0356 c0x0000 (---------------) + I pub 0x48f8ae42, // n0x0357 c0x0123 (n0x1a49-n0x1a4f) + I pw 0x492be202, // n0x0358 c0x0124 (n0x1a4f-n0x1a56) + I py 0x496fd8c2, // n0x0359 c0x0125 (n0x1a56-n0x1a5f) + I qa 0x002ce804, // n0x035a c0x0000 (---------------) + I qpon 0x00211186, // n0x035b c0x0000 (---------------) + I quebec 0x00222685, // n0x035c c0x0000 (---------------) + I quest 0x00301a06, // n0x035d c0x0000 (---------------) + I racing 0x49a030c2, // n0x035e c0x0126 (n0x1a5f-n0x1a63) + I re 0x0033d884, // n0x035f c0x0000 (---------------) + I read 0x0032e0c7, // n0x0360 c0x0000 (---------------) + I realtor 0x0036b3c6, // n0x0361 c0x0000 (---------------) + I realty 0x00307487, // n0x0362 c0x0000 (---------------) + I recipes 0x00230683, // n0x0363 c0x0000 (---------------) + I red 0x0029d908, // n0x0364 c0x0000 (---------------) + I redstone 0x003237cb, // n0x0365 c0x0000 (---------------) + I redumbrella 0x002730c5, // n0x0366 c0x0000 (---------------) + I rehab 0x002e8505, // n0x0367 c0x0000 (---------------) + I reise 0x002e8506, // n0x0368 c0x0000 (---------------) + I reisen 0x002a45c4, // n0x0369 c0x0000 (---------------) + I reit 0x00365b48, // n0x036a c0x0000 (---------------) + I reliance 0x00210403, // n0x036b c0x0000 (---------------) + I ren 0x00210404, // n0x036c c0x0000 (---------------) + I rent 0x00210407, // n0x036d c0x0000 (---------------) + I rentals 0x002117c6, // n0x036e c0x0000 (---------------) + I repair 0x0030ea86, // n0x036f c0x0000 (---------------) + I report 0x002964ca, // n0x0370 c0x0000 (---------------) + I republican 0x00237dc4, // n0x0371 c0x0000 (---------------) + I rest 0x003386ca, // n0x0372 c0x0000 (---------------) + I restaurant 0x0031bd06, // n0x0373 c0x0000 (---------------) + I review 0x0031bd07, // n0x0374 c0x0000 (---------------) + I reviews 0x00243007, // n0x0375 c0x0000 (---------------) + I rexroth 0x002614c4, // n0x0376 c0x0000 (---------------) + I rich 0x002614c9, // n0x0377 c0x0000 (---------------) + I richardli 0x0024ea05, // n0x0378 c0x0000 (---------------) + I ricoh 0x00228f83, // n0x0379 c0x0000 (---------------) + I ril 0x0022ad03, // n0x037a c0x0000 (---------------) + I rio 0x0021dd83, // n0x037b c0x0000 (---------------) + I rip 0x49e00d82, // n0x037c c0x0127 (n0x1a63-n0x1a6f) + I ro 0x0028e886, // n0x037d c0x0000 (---------------) + I rocher 0x00297105, // n0x037e c0x0000 (---------------) + I rocks 0x002c1b45, // n0x037f c0x0000 (---------------) + I rodeo 0x0023a144, // n0x0380 c0x0000 (---------------) + I room 0x4a2060c2, // n0x0381 c0x0128 (n0x1a6f-n0x1a76) + I rs 0x00324a84, // n0x0382 c0x0000 (---------------) + I rsvp 0x4a6044c2, // n0x0383 c0x0129 (n0x1a76-n0x1afa) + I ru 0x0024f144, // n0x0384 c0x0000 (---------------) + I ruhr 0x002044c3, // n0x0385 c0x0000 (---------------) + I run 0x4ab0d882, // n0x0386 c0x012a (n0x1afa-n0x1b03) + I rw 0x0031d103, // n0x0387 c0x0000 (---------------) + I rwe 0x00289606, // n0x0388 c0x0000 (---------------) + I ryukyu 0x4ae01a02, // n0x0389 c0x012b (n0x1b03-n0x1b0b) + I sa 0x00272608, // n0x038a c0x0000 (---------------) + I saarland 0x00234784, // n0x038b c0x0000 (---------------) + I safe 0x00234786, // n0x038c c0x0000 (---------------) + I safety 0x002f4d46, // n0x038d c0x0000 (---------------) + I sakura 0x00244b04, // n0x038e c0x0000 (---------------) + I sale 0x00340885, // n0x038f c0x0000 (---------------) + I salon 0x00395107, // n0x0390 c0x0000 (---------------) + I samsung 0x0029c407, // n0x0391 c0x0000 (---------------) + I sandvik 0x0029c40f, // n0x0392 c0x0000 (---------------) + I sandvikcoromant 0x002098c6, // n0x0393 c0x0000 (---------------) + I sanofi 0x00210583, // n0x0394 c0x0000 (---------------) + I sap 0x00210584, // n0x0395 c0x0000 (---------------) + I sapo 0x0021d684, // n0x0396 c0x0000 (---------------) + I sarl 0x002275c3, // n0x0397 c0x0000 (---------------) + I sas 0x00219584, // n0x0398 c0x0000 (---------------) + I save 0x002332c4, // n0x0399 c0x0000 (---------------) + I saxo 0x4b2046c2, // n0x039a c0x012c (n0x1b0b-n0x1b10) + I sb 0x00277ac3, // n0x039b c0x0000 (---------------) + I sbi 0x002350c3, // n0x039c c0x0000 (---------------) + I sbs 0x4b600982, // n0x039d c0x012d (n0x1b10-n0x1b15) + I sc 0x00229183, // n0x039e c0x0000 (---------------) + I sca 0x00355d83, // n0x039f c0x0000 (---------------) + I scb 0x00206107, // n0x03a0 c0x0000 (---------------) + I schmidt 0x0023514c, // n0x03a1 c0x0000 (---------------) + I scholarships 0x00235406, // n0x03a2 c0x0000 (---------------) + I school 0x002c39c6, // n0x03a3 c0x0000 (---------------) + I schule 0x00370987, // n0x03a4 c0x0000 (---------------) + I schwarz 0x00223b07, // n0x03a5 c0x0000 (---------------) + I science 0x00212fc4, // n0x03a6 c0x0000 (---------------) + I scor 0x00237984, // n0x03a7 c0x0000 (---------------) + I scot 0x4ba4f842, // n0x03a8 c0x012e (n0x1b15-n0x1b1d) + I sd 0x4be02e82, // n0x03a9 c0x012f (n0x1b1d-n0x1b46) + I se 0x003004c4, // n0x03aa c0x0000 (---------------) + I seat 0x00223f88, // n0x03ab c0x0000 (---------------) + I security 0x00267bc4, // n0x03ac c0x0000 (---------------) + I seek 0x002ba785, // n0x03ad c0x0000 (---------------) + I sener 0x00243bc8, // n0x03ae c0x0000 (---------------) + I services 0x002476c3, // n0x03af c0x0000 (---------------) + I sew 0x0029acc3, // n0x03b0 c0x0000 (---------------) + I sex 0x0029acc4, // n0x03b1 c0x0000 (---------------) + I sexy 0x4c262dc2, // n0x03b2 c0x0130 (n0x1b46-n0x1b4d) + I sg 0x4c6001c2, // n0x03b3 c0x0131 (n0x1b4d-n0x1b53) + I sh 0x00255e05, // n0x03b4 c0x0000 (---------------) + I sharp 0x00256344, // n0x03b5 c0x0000 (---------------) + I shaw 0x00208c04, // n0x03b6 c0x0000 (---------------) + I shia 0x002cb1c7, // n0x03b7 c0x0000 (---------------) + I shiksha 0x00369905, // n0x03b8 c0x0000 (---------------) + I shoes 0x002b0e86, // n0x03b9 c0x0000 (---------------) + I shouji 0x002b3884, // n0x03ba c0x0000 (---------------) + I show 0x002b6b87, // n0x03bb c0x0000 (---------------) + I shriram 0x4ca09182, // n0x03bc c0x0132 (n0x1b53-n0x1b54) + I si 0x0036b904, // n0x03bd c0x0000 (---------------) + I silk 0x002914c4, // n0x03be c0x0000 (---------------) + I sina 0x00274247, // n0x03bf c0x0000 (---------------) + I singles 0x00242b84, // n0x03c0 c0x0000 (---------------) + I site 0x0022e942, // n0x03c1 c0x0000 (---------------) + I sj 0x4ce07b42, // n0x03c2 c0x0133 (n0x1b54-n0x1b55) + I sk 0x00207b43, // n0x03c3 c0x0000 (---------------) + I ski 0x002f3384, // n0x03c4 c0x0000 (---------------) + I skin 0x00229043, // n0x03c5 c0x0000 (---------------) + I sky 0x00229045, // n0x03c6 c0x0000 (---------------) + I skype 0x4d212582, // n0x03c7 c0x0134 (n0x1b55-n0x1b5a) + I sl 0x0023f582, // n0x03c8 c0x0000 (---------------) + I sm 0x0034b305, // n0x03c9 c0x0000 (---------------) + I smile 0x4d610b02, // n0x03ca c0x0135 (n0x1b5a-n0x1b62) + I sn 0x00310444, // n0x03cb c0x0000 (---------------) + I sncf 0x4da01102, // n0x03cc c0x0136 (n0x1b62-n0x1b65) + I so 0x00240a06, // n0x03cd c0x0000 (---------------) + I soccer 0x002c27c6, // n0x03ce c0x0000 (---------------) + I social 0x00258008, // n0x03cf c0x0000 (---------------) + I softbank 0x002a6c88, // n0x03d0 c0x0000 (---------------) + I software 0x002de604, // n0x03d1 c0x0000 (---------------) + I sohu 0x002d0205, // n0x03d2 c0x0000 (---------------) + I solar 0x002d9149, // n0x03d3 c0x0000 (---------------) + I solutions 0x00364504, // n0x03d4 c0x0000 (---------------) + I song 0x002bc184, // n0x03d5 c0x0000 (---------------) + I sony 0x00207fc3, // n0x03d6 c0x0000 (---------------) + I soy 0x002101c5, // n0x03d7 c0x0000 (---------------) + I space 0x00379247, // n0x03d8 c0x0000 (---------------) + I spiegel 0x00236a04, // n0x03d9 c0x0000 (---------------) + I spot 0x0033d80d, // n0x03da c0x0000 (---------------) + I spreadbetting 0x002ceec2, // n0x03db c0x0000 (---------------) + I sr 0x002ceec3, // n0x03dc c0x0000 (---------------) + I srl 0x4de023c2, // n0x03dd c0x0137 (n0x1b65-n0x1b71) + I st 0x0035bf05, // n0x03de c0x0000 (---------------) + I stada 0x00232444, // n0x03df c0x0000 (---------------) + I star 0x003191c7, // n0x03e0 c0x0000 (---------------) + I starhub 0x002b1889, // n0x03e1 c0x0000 (---------------) + I statebank 0x0029ca07, // n0x03e2 c0x0000 (---------------) + I statoil 0x00264603, // n0x03e3 c0x0000 (---------------) + I stc 0x00264608, // n0x03e4 c0x0000 (---------------) + I stcgroup 0x00259f09, // n0x03e5 c0x0000 (---------------) + I stockholm 0x002cf147, // n0x03e6 c0x0000 (---------------) + I storage 0x002cf4c5, // n0x03e7 c0x0000 (---------------) + I store 0x002cfc86, // n0x03e8 c0x0000 (---------------) + I studio 0x002cfe05, // n0x03e9 c0x0000 (---------------) + I study 0x00247945, // n0x03ea c0x0000 (---------------) + I style 0x4e203a42, // n0x03eb c0x0138 (n0x1b71-n0x1b91) + I su 0x002f0b45, // n0x03ec c0x0000 (---------------) + I sucks 0x002acd0a, // n0x03ed c0x0000 (---------------) + I supersport 0x002b49c8, // n0x03ee c0x0000 (---------------) + I supplies 0x002cccc6, // n0x03ef c0x0000 (---------------) + I supply 0x00243e87, // n0x03f0 c0x0000 (---------------) + I support 0x00287c84, // n0x03f1 c0x0000 (---------------) + I surf 0x00330647, // n0x03f2 c0x0000 (---------------) + I surgery 0x002d2f46, // n0x03f3 c0x0000 (---------------) + I suzuki 0x4e61d0c2, // n0x03f4 c0x0139 (n0x1b91-n0x1b96) + I sv 0x0020ac86, // n0x03f5 c0x0000 (---------------) + I swatch 0x002d6685, // n0x03f6 c0x0000 (---------------) + I swiss 0x4ead6b42, // n0x03f7 c0x013a (n0x1b96-n0x1b97) + I sx 0x4ee84ec2, // n0x03f8 c0x013b (n0x1b97-n0x1b9d) + I sy 0x00368086, // n0x03f9 c0x0000 (---------------) + I sydney 0x0029d448, // n0x03fa c0x0000 (---------------) + I symantec 0x00392447, // n0x03fb c0x0000 (---------------) + I systems 0x4f207582, // n0x03fc c0x013c (n0x1b9d-n0x1ba0) + I sz 0x0020c083, // n0x03fd c0x0000 (---------------) + I tab 0x00382f46, // n0x03fe c0x0000 (---------------) + I taipei 0x00216944, // n0x03ff c0x0000 (---------------) + I talk 0x003879c6, // n0x0400 c0x0000 (---------------) + I taobao 0x0031cbca, // n0x0401 c0x0000 (---------------) + I tatamotors 0x0031df05, // n0x0402 c0x0000 (---------------) + I tatar 0x0020f886, // n0x0403 c0x0000 (---------------) + I tattoo 0x00217c43, // n0x0404 c0x0000 (---------------) + I tax 0x00217c44, // n0x0405 c0x0000 (---------------) + I taxi 0x0020ad42, // n0x0406 c0x0000 (---------------) + I tc 0x002f4203, // n0x0407 c0x0000 (---------------) + I tci 0x4f600682, // n0x0408 c0x013d (n0x1ba0-n0x1ba1) + I td 0x002c9803, // n0x0409 c0x0000 (---------------) + I tdk 0x00354144, // n0x040a c0x0000 (---------------) + I team 0x0029d584, // n0x040b c0x0000 (---------------) + I tech 0x0029d58a, // n0x040c c0x0000 (---------------) + I technology 0x0022ba83, // n0x040d c0x0000 (---------------) + I tel 0x002734c8, // n0x040e c0x0000 (---------------) + I telecity 0x00250a0a, // n0x040f c0x0000 (---------------) + I telefonica 0x00325507, // n0x0410 c0x0000 (---------------) + I temasek 0x002dab46, // n0x0411 c0x0000 (---------------) + I tennis 0x0033f0c4, // n0x0412 c0x0000 (---------------) + I teva 0x0027e202, // n0x0413 c0x0000 (---------------) + I tf 0x0021e342, // n0x0414 c0x0000 (---------------) + I tg 0x4fa01d82, // n0x0415 c0x013e (n0x1ba1-n0x1ba8) + I th 0x00235c83, // n0x0416 c0x0000 (---------------) + I thd 0x002f9147, // n0x0417 c0x0000 (---------------) + I theater 0x00242d87, // n0x0418 c0x0000 (---------------) + I theatre 0x00377f8b, // n0x0419 c0x0000 (---------------) + I theguardian 0x00340707, // n0x041a c0x0000 (---------------) + I tickets 0x0021bb06, // n0x041b c0x0000 (---------------) + I tienda 0x00375107, // n0x041c c0x0000 (---------------) + I tiffany 0x00354984, // n0x041d c0x0000 (---------------) + I tips 0x00355585, // n0x041e c0x0000 (---------------) + I tires 0x002a4985, // n0x041f c0x0000 (---------------) + I tirol 0x4fe02bc2, // n0x0420 c0x013f (n0x1ba8-n0x1bb7) + I tj 0x0023a7c2, // n0x0421 c0x0000 (---------------) + I tk 0x5020fc42, // n0x0422 c0x0140 (n0x1bb7-n0x1bb8) + I tl 0x50608902, // n0x0423 c0x0141 (n0x1bb8-n0x1bc0) + I tm 0x0026a9c5, // n0x0424 c0x0000 (---------------) + I tmall 0x50a1d1c2, // n0x0425 c0x0142 (n0x1bc0-n0x1bd4) + I tn 0x50e01682, // n0x0426 c0x0143 (n0x1bd4-n0x1bda) + I to 0x00312e85, // n0x0427 c0x0000 (---------------) + I today 0x00316545, // n0x0428 c0x0000 (---------------) + I tokyo 0x0020f945, // n0x0429 c0x0000 (---------------) + I tools 0x002469c3, // n0x042a c0x0000 (---------------) + I top 0x00338cc5, // n0x042b c0x0000 (---------------) + I toray 0x002beb47, // n0x042c c0x0000 (---------------) + I toshiba 0x00339905, // n0x042d c0x0000 (---------------) + I tours 0x0021abc4, // n0x042e c0x0000 (---------------) + I town 0x00338906, // n0x042f c0x0000 (---------------) + I toyota 0x00247b04, // n0x0430 c0x0000 (---------------) + I toys 0x00285142, // n0x0431 c0x0000 (---------------) + I tp 0x51202402, // n0x0432 c0x0144 (n0x1bda-n0x1bef) + I tr 0x00229a45, // n0x0433 c0x0000 (---------------) + I trade 0x0028fe07, // n0x0434 c0x0000 (---------------) + I trading 0x002b9748, // n0x0435 c0x0000 (---------------) + I training 0x0027f186, // n0x0436 c0x0000 (---------------) + I travel 0x0027f18d, // n0x0437 c0x0000 (---------------) + I travelchannel 0x00280489, // n0x0438 c0x0000 (---------------) + I travelers 0x00280492, // n0x0439 c0x0000 (---------------) + I travelersinsurance 0x00313185, // n0x043a c0x0000 (---------------) + I trust 0x0034a4c3, // n0x043b c0x0000 (---------------) + I trv 0x51e06582, // n0x043c c0x0147 (n0x1bf1-n0x1c02) + I tt 0x0035a104, // n0x043d c0x0000 (---------------) + I tube 0x002d71c3, // n0x043e c0x0000 (---------------) + I tui 0x002d83c5, // n0x043f c0x0000 (---------------) + I tunes 0x002d8e45, // n0x0440 c0x0000 (---------------) + I tushu 0x5220bf42, // n0x0441 c0x0148 (n0x1c02-n0x1c06) + I tv 0x0020bf43, // n0x0442 c0x0000 (---------------) + I tvs 0x52641ac2, // n0x0443 c0x0149 (n0x1c06-n0x1c14) + I tw 0x52a17142, // n0x0444 c0x014a (n0x1c14-n0x1c20) + I tz 0x52e17d82, // n0x0445 c0x014b (n0x1c20-n0x1c6e) + I ua 0x0032ba03, // n0x0446 c0x0000 (---------------) + I ubs 0x53205082, // n0x0447 c0x014c (n0x1c6e-n0x1c77) + I ug 0x5360cf02, // n0x0448 c0x014d (n0x1c77-n0x1c82) + I uk 0x0029f04a, // n0x0449 c0x0000 (---------------) + I university 0x00203a83, // n0x044a c0x0000 (---------------) + I uno 0x00245543, // n0x044b c0x0000 (---------------) + I uol 0x002c16c3, // n0x044c c0x0000 (---------------) + I ups 0x54209f42, // n0x044d c0x0150 (n0x1c84-n0x1cc3) + I us 0x62606842, // n0x044e c0x0189 (n0x1d66-n0x1d6c) + I uy 0x62e018c2, // n0x044f c0x018b (n0x1d6d-n0x1d71) + I uz 0x002013c2, // n0x0450 c0x0000 (---------------) + I va 0x00340209, // n0x0451 c0x0000 (---------------) + I vacations 0x002aba84, // n0x0452 c0x0000 (---------------) + I vana 0x6334a542, // n0x0453 c0x018c (n0x1d71-n0x1d77) + I vc 0x636014c2, // n0x0454 c0x018d (n0x1d77-n0x1d88) + I ve 0x0027d4c5, // n0x0455 c0x0000 (---------------) + I vegas 0x00227248, // n0x0456 c0x0000 (---------------) + I ventures 0x002d998c, // n0x0457 c0x0000 (---------------) + I versicherung 0x0022b9c3, // n0x0458 c0x0000 (---------------) + I vet 0x0024ad42, // n0x0459 c0x0000 (---------------) + I vg 0x63a13602, // n0x045a c0x018e (n0x1d88-n0x1d8d) + I vi 0x002b4346, // n0x045b c0x0000 (---------------) + I viajes 0x002db9c5, // n0x045c c0x0000 (---------------) + I video 0x002b1403, // n0x045d c0x0000 (---------------) + I vig 0x002c7686, // n0x045e c0x0000 (---------------) + I viking 0x002dbb06, // n0x045f c0x0000 (---------------) + I villas 0x00213603, // n0x0460 c0x0000 (---------------) + I vin 0x002dc703, // n0x0461 c0x0000 (---------------) + I vip 0x002dd146, // n0x0462 c0x0000 (---------------) + I virgin 0x00248b46, // n0x0463 c0x0000 (---------------) + I vision 0x002b85c5, // n0x0464 c0x0000 (---------------) + I vista 0x002dd6ca, // n0x0465 c0x0000 (---------------) + I vistaprint 0x0022cf04, // n0x0466 c0x0000 (---------------) + I viva 0x00332eca, // n0x0467 c0x0000 (---------------) + I vlaanderen 0x63e08102, // n0x0468 c0x018f (n0x1d8d-n0x1d9a) + I vn 0x002716c5, // n0x0469 c0x0000 (---------------) + I vodka 0x002e0c8a, // n0x046a c0x0000 (---------------) + I volkswagen 0x002e2484, // n0x046b c0x0000 (---------------) + I vote 0x002e2586, // n0x046c c0x0000 (---------------) + I voting 0x002e2704, // n0x046d c0x0000 (---------------) + I voto 0x0030c486, // n0x046e c0x0000 (---------------) + I voyage 0x6421d102, // n0x046f c0x0190 (n0x1d9a-n0x1d9e) + I vu 0x002a4e86, // n0x0470 c0x0000 (---------------) + I vuelos 0x0036cbc5, // n0x0471 c0x0000 (---------------) + I wales 0x0038b0c6, // n0x0472 c0x0000 (---------------) + I walter 0x003578c4, // n0x0473 c0x0000 (---------------) + I wang 0x003578c7, // n0x0474 c0x0000 (---------------) + I wanggou 0x00351a06, // n0x0475 c0x0000 (---------------) + I warman 0x0020acc5, // n0x0476 c0x0000 (---------------) + I watch 0x00293647, // n0x0477 c0x0000 (---------------) + I watches 0x00384107, // n0x0478 c0x0000 (---------------) + I weather 0x0038410e, // n0x0479 c0x0000 (---------------) + I weatherchannel 0x00219fc6, // n0x047a c0x0000 (---------------) + I webcam 0x00251cc5, // n0x047b c0x0000 (---------------) + I weber 0x002af047, // n0x047c c0x0000 (---------------) + I website 0x002d4bc3, // n0x047d c0x0000 (---------------) + I wed 0x0031c007, // n0x047e c0x0000 (---------------) + I wedding 0x003912c5, // n0x047f c0x0000 (---------------) + I weibo 0x0020a184, // n0x0480 c0x0000 (---------------) + I weir 0x0021f7c2, // n0x0481 c0x0000 (---------------) + I wf 0x002c7207, // n0x0482 c0x0000 (---------------) + I whoswho 0x002d2e44, // n0x0483 c0x0000 (---------------) + I wien 0x0025a484, // n0x0484 c0x0000 (---------------) + I wiki 0x0024910b, // n0x0485 c0x0000 (---------------) + I williamhill 0x00213c83, // n0x0486 c0x0000 (---------------) + I win 0x002b6a07, // n0x0487 c0x0000 (---------------) + I windows 0x00213c84, // n0x0488 c0x0000 (---------------) + I wine 0x00231fc3, // n0x0489 c0x0000 (---------------) + I wme 0x00241b04, // n0x048a c0x0000 (---------------) + I work 0x0029b085, // n0x048b c0x0000 (---------------) + I works 0x00314905, // n0x048c c0x0000 (---------------) + I world 0x6460ba82, // n0x048d c0x0191 (n0x1d9e-n0x1da5) + I ws 0x002e34c3, // n0x048e c0x0000 (---------------) + I wtc 0x002e3b03, // n0x048f c0x0000 (---------------) + I wtf 0x0020a6c4, // n0x0490 c0x0000 (---------------) + I xbox 0x0020a785, // n0x0491 c0x0000 (---------------) + I xerox 0x00217cc6, // n0x0492 c0x0000 (---------------) + I xihuan 0x00356e83, // n0x0493 c0x0000 (---------------) + I xin 0x002358cb, // n0x0494 c0x0000 (---------------) + I xn--11b4c3d 0x0023d74b, // n0x0495 c0x0000 (---------------) + I xn--1ck2e1b 0x00291d4b, // n0x0496 c0x0000 (---------------) + I xn--1qqw23a 0x002bfeca, // n0x0497 c0x0000 (---------------) + I xn--30rr7y 0x0033588b, // n0x0498 c0x0000 (---------------) + I xn--3bst00m 0x003942cb, // n0x0499 c0x0000 (---------------) + I xn--3ds443g 0x0039658c, // n0x049a c0x0000 (---------------) + I xn--3e0b707e 0x00397251, // n0x049b c0x0000 (---------------) + I xn--3oq18vl8pn36a 0x002e480a, // n0x049c c0x0000 (---------------) + I xn--3pxu8k 0x002e4bcb, // n0x049d c0x0000 (---------------) + I xn--42c2d9a 0x002e4e8b, // n0x049e c0x0000 (---------------) + I xn--45brj9c 0x002e6d4a, // n0x049f c0x0000 (---------------) + I xn--45q11c 0x002e780a, // n0x04a0 c0x0000 (---------------) + I xn--4gbrim 0x002e8b8e, // n0x04a1 c0x0000 (---------------) + I xn--54b7fta0cc 0x002e9e4b, // n0x04a2 c0x0000 (---------------) + I xn--55qw42g 0x002ea10a, // n0x04a3 c0x0000 (---------------) + I xn--55qx5d 0x002eb14a, // n0x04a4 c0x0000 (---------------) + I xn--5tzm5g 0x002eb64b, // n0x04a5 c0x0000 (---------------) + I xn--6frz82g 0x002ebb8e, // n0x04a6 c0x0000 (---------------) + I xn--6qq986b3xl 0x002ec6cc, // n0x04a7 c0x0000 (---------------) + I xn--80adxhks 0x002ecb4b, // n0x04a8 c0x0000 (---------------) + I xn--80ao21a 0x002ece0c, // n0x04a9 c0x0000 (---------------) + I xn--80asehdb 0x002f108a, // n0x04aa c0x0000 (---------------) + I xn--80aswg 0x002f228c, // n0x04ab c0x0000 (---------------) + I xn--8y0a063a 0x64af258a, // n0x04ac c0x0192 (n0x1da5-n0x1dab) + I xn--90a3ac 0x002f5849, // n0x04ad c0x0000 (---------------) + I xn--90ais 0x002f664a, // n0x04ae c0x0000 (---------------) + I xn--9dbq2a 0x002f68ca, // n0x04af c0x0000 (---------------) + I xn--9et52u 0x002f6b4b, // n0x04b0 c0x0000 (---------------) + I xn--9krt00a 0x002fa44e, // n0x04b1 c0x0000 (---------------) + I xn--b4w605ferd 0x002fa7d1, // n0x04b2 c0x0000 (---------------) + I xn--bck1b9a5dre4c 0x00303289, // n0x04b3 c0x0000 (---------------) + I xn--c1avg 0x003034ca, // n0x04b4 c0x0000 (---------------) + I xn--c2br7g 0x00303e0b, // n0x04b5 c0x0000 (---------------) + I xn--cck2b3b 0x0030618a, // n0x04b6 c0x0000 (---------------) + I xn--cg4bki 0x00306d16, // n0x04b7 c0x0000 (---------------) + I xn--clchc0ea0b2g2a9gcd 0x003091cb, // n0x04b8 c0x0000 (---------------) + I xn--czr694b 0x0030a9ca, // n0x04b9 c0x0000 (---------------) + I xn--czrs0t 0x0030d48a, // n0x04ba c0x0000 (---------------) + I xn--czru2d 0x0030f2cb, // n0x04bb c0x0000 (---------------) + I xn--d1acj3b 0x003125c9, // n0x04bc c0x0000 (---------------) + I xn--d1alf 0x0031508d, // n0x04bd c0x0000 (---------------) + I xn--eckvdtc9d 0x003167cb, // n0x04be c0x0000 (---------------) + I xn--efvy88h 0x003178cb, // n0x04bf c0x0000 (---------------) + I xn--estv75g 0x0031828b, // n0x04c0 c0x0000 (---------------) + I xn--fct429k 0x00319909, // n0x04c1 c0x0000 (---------------) + I xn--fhbei 0x00319f4e, // n0x04c2 c0x0000 (---------------) + I xn--fiq228c5hs 0x0031a48a, // n0x04c3 c0x0000 (---------------) + I xn--fiq64b 0x0031ec0a, // n0x04c4 c0x0000 (---------------) + I xn--fiqs8s 0x0031f0ca, // n0x04c5 c0x0000 (---------------) + I xn--fiqz9s 0x0031fa8b, // n0x04c6 c0x0000 (---------------) + I xn--fjq720a 0x003202cb, // n0x04c7 c0x0000 (---------------) + I xn--flw351e 0x0032058d, // n0x04c8 c0x0000 (---------------) + I xn--fpcrj9c3d 0x00321e0d, // n0x04c9 c0x0000 (---------------) + I xn--fzc2c9e2c 0x00322dd0, // n0x04ca c0x0000 (---------------) + I xn--fzys8d69uvgm 0x0032328b, // n0x04cb c0x0000 (---------------) + I xn--g2xx48c 0x00323ecc, // n0x04cc c0x0000 (---------------) + I xn--gckr3f0f 0x0032434b, // n0x04cd c0x0000 (---------------) + I xn--gecrj9c 0x0032880b, // n0x04ce c0x0000 (---------------) + I xn--h2brj9c 0x0032f14b, // n0x04cf c0x0000 (---------------) + I xn--hxt814e 0x0032fbcf, // n0x04d0 c0x0000 (---------------) + I xn--i1b6b1a6a2e 0x0032ff8b, // n0x04d1 c0x0000 (---------------) + I xn--imr513n 0x0033080a, // n0x04d2 c0x0000 (---------------) + I xn--io0a7i 0x00331249, // n0x04d3 c0x0000 (---------------) + I xn--j1aef 0x003315c9, // n0x04d4 c0x0000 (---------------) + I xn--j1amh 0x0033198b, // n0x04d5 c0x0000 (---------------) + I xn--j6w193g 0x00331c4e, // n0x04d6 c0x0000 (---------------) + I xn--jlq61u9w7b 0x0033354b, // n0x04d7 c0x0000 (---------------) + I xn--jvr189m 0x0033444f, // n0x04d8 c0x0000 (---------------) + I xn--kcrx77d1x4a 0x00337d8b, // n0x04d9 c0x0000 (---------------) + I xn--kprw13d 0x0033804b, // n0x04da c0x0000 (---------------) + I xn--kpry57d 0x0033830b, // n0x04db c0x0000 (---------------) + I xn--kpu716f 0x00338e0a, // n0x04dc c0x0000 (---------------) + I xn--kput3i 0x0033db49, // n0x04dd c0x0000 (---------------) + I xn--l1acc 0x00344dcf, // n0x04de c0x0000 (---------------) + I xn--lgbbat1ad8j 0x0034978c, // n0x04df c0x0000 (---------------) + I xn--mgb2ddes 0x00349c8c, // n0x04e0 c0x0000 (---------------) + I xn--mgb9awbf 0x0034a18e, // n0x04e1 c0x0000 (---------------) + I xn--mgba3a3ejt 0x0034a88f, // n0x04e2 c0x0000 (---------------) + I xn--mgba3a4f16a 0x0034ac4e, // n0x04e3 c0x0000 (---------------) + I xn--mgba3a4fra 0x0034b750, // n0x04e4 c0x0000 (---------------) + I xn--mgba7c0bbn0a 0x0034bb4e, // n0x04e5 c0x0000 (---------------) + I xn--mgbaam7a8h 0x0034c10c, // n0x04e6 c0x0000 (---------------) + I xn--mgbab2bd 0x0034c412, // n0x04e7 c0x0000 (---------------) + I xn--mgbai9a5eva00b 0x0034f091, // n0x04e8 c0x0000 (---------------) + I xn--mgbai9azgqp6j 0x0034f64e, // n0x04e9 c0x0000 (---------------) + I xn--mgbayh7gpa 0x0034fa8e, // n0x04ea c0x0000 (---------------) + I xn--mgbb9fbpob 0x0034ffce, // n0x04eb c0x0000 (---------------) + I xn--mgbbh1a71e 0x0035034f, // n0x04ec c0x0000 (---------------) + I xn--mgbc0a9azcg 0x00350713, // n0x04ed c0x0000 (---------------) + I xn--mgberp4a5d4a87g 0x00350bd1, // n0x04ee c0x0000 (---------------) + I xn--mgberp4a5d4ar 0x0035100c, // n0x04ef c0x0000 (---------------) + I xn--mgbpl2fh 0x00351453, // n0x04f0 c0x0000 (---------------) + I xn--mgbqly7c0a67fbc 0x00352310, // n0x04f1 c0x0000 (---------------) + I xn--mgbqly7cvafr 0x00352e0c, // n0x04f2 c0x0000 (---------------) + I xn--mgbt3dhd 0x0035310c, // n0x04f3 c0x0000 (---------------) + I xn--mgbtf8fl 0x003535cb, // n0x04f4 c0x0000 (---------------) + I xn--mgbtx2b 0x0035588e, // n0x04f5 c0x0000 (---------------) + I xn--mgbx4cd0ab 0x00355e8b, // n0x04f6 c0x0000 (---------------) + I xn--mix082f 0x003564cb, // n0x04f7 c0x0000 (---------------) + I xn--mix891f 0x0035728c, // n0x04f8 c0x0000 (---------------) + I xn--mk1bu44c 0x0035c6ca, // n0x04f9 c0x0000 (---------------) + I xn--mxtq1m 0x0035ca8c, // n0x04fa c0x0000 (---------------) + I xn--ngbc5azd 0x0035cd8c, // n0x04fb c0x0000 (---------------) + I xn--ngbe9e0a 0x0035f64b, // n0x04fc c0x0000 (---------------) + I xn--nnx388a 0x0035f908, // n0x04fd c0x0000 (---------------) + I xn--node 0x00360249, // n0x04fe c0x0000 (---------------) + I xn--nqv7f 0x0036024f, // n0x04ff c0x0000 (---------------) + I xn--nqv7fs00ema 0x00361f8b, // n0x0500 c0x0000 (---------------) + I xn--nyqy26a 0x003633ca, // n0x0501 c0x0000 (---------------) + I xn--o3cw4h 0x00364d8c, // n0x0502 c0x0000 (---------------) + I xn--ogbpf8fl 0x00366089, // n0x0503 c0x0000 (---------------) + I xn--p1acf 0x00366308, // n0x0504 c0x0000 (---------------) + I xn--p1ai 0x00366f8b, // n0x0505 c0x0000 (---------------) + I xn--pbt977c 0x003676cb, // n0x0506 c0x0000 (---------------) + I xn--pgbs0dh 0x00368a8a, // n0x0507 c0x0000 (---------------) + I xn--pssy2u 0x00368d0b, // n0x0508 c0x0000 (---------------) + I xn--q9jyb4c 0x0036944c, // n0x0509 c0x0000 (---------------) + I xn--qcka1pmc 0x0036a988, // n0x050a c0x0000 (---------------) + I xn--qxam 0x0037230b, // n0x050b c0x0000 (---------------) + I xn--rhqv96g 0x00374d8b, // n0x050c c0x0000 (---------------) + I xn--rovu88b 0x0037824b, // n0x050d c0x0000 (---------------) + I xn--s9brj9c 0x00379a8b, // n0x050e c0x0000 (---------------) + I xn--ses554g 0x00383c8b, // n0x050f c0x0000 (---------------) + I xn--t60b56a 0x00383f49, // n0x0510 c0x0000 (---------------) + I xn--tckwe 0x00387fca, // n0x0511 c0x0000 (---------------) + I xn--unup4y 0x00388f17, // n0x0512 c0x0000 (---------------) + I xn--vermgensberater-ctb 0x0038a918, // n0x0513 c0x0000 (---------------) + I xn--vermgensberatung-pwb 0x0038dcc9, // n0x0514 c0x0000 (---------------) + I xn--vhquv 0x0038f00b, // n0x0515 c0x0000 (---------------) + I xn--vuq861b 0x0038fb94, // n0x0516 c0x0000 (---------------) + I xn--w4r85el8fhu5dnra 0x0039034a, // n0x0517 c0x0000 (---------------) + I xn--wgbh1c 0x0039090a, // n0x0518 c0x0000 (---------------) + I xn--wgbl6a 0x00390b8b, // n0x0519 c0x0000 (---------------) + I xn--xhq521b 0x00391a90, // n0x051a c0x0000 (---------------) + I xn--xkc2al3hye2a 0x00391e91, // n0x051b c0x0000 (---------------) + I xn--xkc2dl3a5ee0h 0x0039290a, // n0x051c c0x0000 (---------------) + I xn--y9a3aq 0x003938cd, // n0x051d c0x0000 (---------------) + I xn--yfro4i67o 0x00393fcd, // n0x051e c0x0000 (---------------) + I xn--ygbi2ammx 0x0039688b, // n0x051f c0x0000 (---------------) + I xn--zfr164b 0x00397046, // n0x0520 c0x0000 (---------------) + I xperia 0x003971c3, // n0x0521 c0x0000 (---------------) + I xxx 0x0029ad43, // n0x0522 c0x0000 (---------------) + I xyz 0x00269586, // n0x0523 c0x0000 (---------------) + I yachts 0x0027b905, // n0x0524 c0x0000 (---------------) + I yahoo 0x002151c7, // n0x0525 c0x0000 (---------------) + I yamaxun 0x00326dc6, // n0x0526 c0x0000 (---------------) + I yandex 0x01614d82, // n0x0527 c0x0005 (---------------)* o I ye 0x002e3609, // n0x0528 c0x0000 (---------------) + I yodobashi 0x00301804, // n0x0529 c0x0000 (---------------) + I yoga 0x0032b5c8, // n0x052a c0x0000 (---------------) + I yokohama 0x00235bc3, // n0x052b c0x0000 (---------------) + I you 0x0035a047, // n0x052c c0x0000 (---------------) + I youtube 0x0022f542, // n0x052d c0x0000 (---------------) + I yt 0x00201943, // n0x052e c0x0000 (---------------) + I yun 0x64e043c2, // n0x052f c0x0193 (n0x1dab-n0x1dbc) o I za 0x002b3106, // n0x0530 c0x0000 (---------------) + I zappos 0x002b3c84, // n0x0531 c0x0000 (---------------) + I zara 0x00311384, // n0x0532 c0x0000 (---------------) + I zero 0x0023b443, // n0x0533 c0x0000 (---------------) + I zip 0x0023b445, // n0x0534 c0x0000 (---------------) + I zippo 0x016e4582, // n0x0535 c0x0005 (---------------)* o I zm 0x002c7ec4, // n0x0536 c0x0000 (---------------) + I zone 0x00261407, // n0x0537 c0x0000 (---------------) + I zuerich 0x016a0202, // n0x0538 c0x0005 (---------------)* o I zw 0x00222ac3, // n0x0539 c0x0000 (---------------) + I com 0x002d75c3, // n0x053a c0x0000 (---------------) + I edu 0x0021e283, // n0x053b c0x0000 (---------------) + I gov 0x0023fa03, // n0x053c c0x0000 (---------------) + I mil 0x002170c3, // n0x053d c0x0000 (---------------) + I net 0x0021dcc3, // n0x053e c0x0000 (---------------) + I org 0x00207cc3, // n0x053f c0x0000 (---------------) + I nom 0x00201e82, // n0x0540 c0x0000 (---------------) + I ac 0x000e4188, // n0x0541 c0x0000 (---------------) + blogspot 0x00200742, // n0x0542 c0x0000 (---------------) + I co 0x0021e283, // n0x0543 c0x0000 (---------------) + I gov 0x0023fa03, // n0x0544 c0x0000 (---------------) + I mil 0x002170c3, // n0x0545 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0546 c0x0000 (---------------) + I org 0x00206103, // n0x0547 c0x0000 (---------------) + I sch 0x002ffad6, // n0x0548 c0x0000 (---------------) + I accident-investigation 0x00301f93, // n0x0549 c0x0000 (---------------) + I accident-prevention 0x00340589, // n0x054a c0x0000 (---------------) + I aerobatic 0x002751c8, // n0x054b c0x0000 (---------------) + I aeroclub 0x0036bb09, // n0x054c c0x0000 (---------------) + I aerodrome 0x002e0e06, // n0x054d c0x0000 (---------------) + I agents 0x0032cf10, // n0x054e c0x0000 (---------------) + I air-surveillance 0x00211893, // n0x054f c0x0000 (---------------) + I air-traffic-control 0x002fb3c8, // n0x0550 c0x0000 (---------------) + I aircraft 0x00262307, // n0x0551 c0x0000 (---------------) + I airline 0x00266e47, // n0x0552 c0x0000 (---------------) + I airport 0x0028bd4a, // n0x0553 c0x0000 (---------------) + I airtraffic 0x003541c9, // n0x0554 c0x0000 (---------------) + I ambulance 0x00309f89, // n0x0555 c0x0000 (---------------) + I amusement 0x002bbacb, // n0x0556 c0x0000 (---------------) + I association 0x002f8406, // n0x0557 c0x0000 (---------------) + I author 0x002ed6ca, // n0x0558 c0x0000 (---------------) + I ballooning 0x00218046, // n0x0559 c0x0000 (---------------) + I broker 0x00301403, // n0x055a c0x0000 (---------------) + I caa 0x002dc1c5, // n0x055b c0x0000 (---------------) + I cargo 0x003246c8, // n0x055c c0x0000 (---------------) + I catering 0x00240acd, // n0x055d c0x0000 (---------------) + I certification 0x0032cacc, // n0x055e c0x0000 (---------------) + I championship 0x0036c887, // n0x055f c0x0000 (---------------) + I charter 0x00328a8d, // n0x0560 c0x0000 (---------------) + I civilaviation 0x002752c4, // n0x0561 c0x0000 (---------------) + I club 0x0022498a, // n0x0562 c0x0000 (---------------) + I conference 0x002255ca, // n0x0563 c0x0000 (---------------) + I consultant 0x00225a8a, // n0x0564 c0x0000 (---------------) + I consulting 0x00211b87, // n0x0565 c0x0000 (---------------) + I control 0x0022cd47, // n0x0566 c0x0000 (---------------) + I council 0x00231004, // n0x0567 c0x0000 (---------------) + I crew 0x00232f46, // n0x0568 c0x0000 (---------------) + I design 0x002727c4, // n0x0569 c0x0000 (---------------) + I dgca 0x00336208, // n0x056a c0x0000 (---------------) + I educator 0x00343bc9, // n0x056b c0x0000 (---------------) + I emergency 0x002a8a86, // n0x056c c0x0000 (---------------) + I engine 0x002a8a88, // n0x056d c0x0000 (---------------) + I engineer 0x00233a4d, // n0x056e c0x0000 (---------------) + I entertainment 0x0021f909, // n0x056f c0x0000 (---------------) + I equipment 0x002f3908, // n0x0570 c0x0000 (---------------) + I exchange 0x0029ab47, // n0x0571 c0x0000 (---------------) + I express 0x0026ac0a, // n0x0572 c0x0000 (---------------) + I federation 0x0023b146, // n0x0573 c0x0000 (---------------) + I flight 0x00248ec7, // n0x0574 c0x0000 (---------------) + I freight 0x0024d004, // n0x0575 c0x0000 (---------------) + I fuel 0x00256007, // n0x0576 c0x0000 (---------------) + I gliding 0x00259a0a, // n0x0577 c0x0000 (---------------) + I government 0x0037868e, // n0x0578 c0x0000 (---------------) + I groundhandling 0x002646c5, // n0x0579 c0x0000 (---------------) + I group 0x0038718b, // n0x057a c0x0000 (---------------) + I hanggliding 0x00278ac9, // n0x057b c0x0000 (---------------) + I homebuilt 0x002806c9, // n0x057c c0x0000 (---------------) + I insurance 0x00202987, // n0x057d c0x0000 (---------------) + I journal 0x0020298a, // n0x057e c0x0000 (---------------) + I journalist 0x00274187, // n0x057f c0x0000 (---------------) + I leasing 0x002127c9, // n0x0580 c0x0000 (---------------) + I logistics 0x00395948, // n0x0581 c0x0000 (---------------) + I magazine 0x002a0c8b, // n0x0582 c0x0000 (---------------) + I maintenance 0x003117cb, // n0x0583 c0x0000 (---------------) + I marketplace 0x002dc385, // n0x0584 c0x0000 (---------------) + I media 0x00236c8a, // n0x0585 c0x0000 (---------------) + I microlight 0x002371c9, // n0x0586 c0x0000 (---------------) + I modelling 0x00354cca, // n0x0587 c0x0000 (---------------) + I navigation 0x0022948b, // n0x0588 c0x0000 (---------------) + I parachuting 0x00255f0b, // n0x0589 c0x0000 (---------------) + I paragliding 0x002bb855, // n0x058a c0x0000 (---------------) + I passenger-association 0x002c1505, // n0x058b c0x0000 (---------------) + I pilot 0x0029abc5, // n0x058c c0x0000 (---------------) + I press 0x002cbe4a, // n0x058d c0x0000 (---------------) + I production 0x002e634a, // n0x058e c0x0000 (---------------) + I recreation 0x002e0107, // n0x058f c0x0000 (---------------) + I repbody 0x00215503, // n0x0590 c0x0000 (---------------) + I res 0x00296808, // n0x0591 c0x0000 (---------------) + I research 0x002bc30a, // n0x0592 c0x0000 (---------------) + I rotorcraft 0x00234786, // n0x0593 c0x0000 (---------------) + I safety 0x0023f089, // n0x0594 c0x0000 (---------------) + I scientist 0x00243bc8, // n0x0595 c0x0000 (---------------) + I services 0x002b3884, // n0x0596 c0x0000 (---------------) + I show 0x00253c09, // n0x0597 c0x0000 (---------------) + I skydiving 0x002a6c88, // n0x0598 c0x0000 (---------------) + I software 0x00298587, // n0x0599 c0x0000 (---------------) + I student 0x00217c44, // n0x059a c0x0000 (---------------) + I taxi 0x00229a46, // n0x059b c0x0000 (---------------) + I trader 0x0028fe07, // n0x059c c0x0000 (---------------) + I trading 0x0028aec7, // n0x059d c0x0000 (---------------) + I trainer 0x00230a45, // n0x059e c0x0000 (---------------) + I union 0x002e04cc, // n0x059f c0x0000 (---------------) + I workinggroup 0x0029b085, // n0x05a0 c0x0000 (---------------) + I works 0x00222ac3, // n0x05a1 c0x0000 (---------------) + I com 0x002d75c3, // n0x05a2 c0x0000 (---------------) + I edu 0x0021e283, // n0x05a3 c0x0000 (---------------) + I gov 0x002170c3, // n0x05a4 c0x0000 (---------------) + I net 0x0021dcc3, // n0x05a5 c0x0000 (---------------) + I org 0x00200742, // n0x05a6 c0x0000 (---------------) + I co 0x00222ac3, // n0x05a7 c0x0000 (---------------) + I com 0x002170c3, // n0x05a8 c0x0000 (---------------) + I net 0x00207cc3, // n0x05a9 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x05aa c0x0000 (---------------) + I org 0x00222ac3, // n0x05ab c0x0000 (---------------) + I com 0x002170c3, // n0x05ac c0x0000 (---------------) + I net 0x00219c43, // n0x05ad c0x0000 (---------------) + I off 0x0021dcc3, // n0x05ae c0x0000 (---------------) + I org 0x000e4188, // n0x05af c0x0000 (---------------) + blogspot 0x00222ac3, // n0x05b0 c0x0000 (---------------) + I com 0x002d75c3, // n0x05b1 c0x0000 (---------------) + I edu 0x0021e283, // n0x05b2 c0x0000 (---------------) + I gov 0x0023fa03, // n0x05b3 c0x0000 (---------------) + I mil 0x002170c3, // n0x05b4 c0x0000 (---------------) + I net 0x0021dcc3, // n0x05b5 c0x0000 (---------------) + I org 0x000e4188, // n0x05b6 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x05b7 c0x0000 (---------------) + I com 0x002d75c3, // n0x05b8 c0x0000 (---------------) + I edu 0x002170c3, // n0x05b9 c0x0000 (---------------) + I net 0x0021dcc3, // n0x05ba c0x0000 (---------------) + I org 0x00200742, // n0x05bb c0x0000 (---------------) + I co 0x00203fc2, // n0x05bc c0x0000 (---------------) + I ed 0x00225cc2, // n0x05bd c0x0000 (---------------) + I gv 0x00206e82, // n0x05be c0x0000 (---------------) + I it 0x002003c2, // n0x05bf c0x0000 (---------------) + I og 0x00268e82, // n0x05c0 c0x0000 (---------------) + I pb 0x04a22ac3, // n0x05c1 c0x0012 (n0x05ca-n0x05cb) + I com 0x002d75c3, // n0x05c2 c0x0000 (---------------) + I edu 0x0034eb03, // n0x05c3 c0x0000 (---------------) + I gob 0x0021e283, // n0x05c4 c0x0000 (---------------) + I gov 0x00238c03, // n0x05c5 c0x0000 (---------------) + I int 0x0023fa03, // n0x05c6 c0x0000 (---------------) + I mil 0x002170c3, // n0x05c7 c0x0000 (---------------) + I net 0x0021dcc3, // n0x05c8 c0x0000 (---------------) + I org 0x00227303, // n0x05c9 c0x0000 (---------------) + I tur 0x000e4188, // n0x05ca c0x0000 (---------------) + blogspot 0x002f5744, // n0x05cb c0x0000 (---------------) + I e164 0x0034d5c7, // n0x05cc c0x0000 (---------------) + I in-addr 0x00213a43, // n0x05cd c0x0000 (---------------) + I ip6 0x00234684, // n0x05ce c0x0000 (---------------) + I iris 0x00202803, // n0x05cf c0x0000 (---------------) + I uri 0x00202a03, // n0x05d0 c0x0000 (---------------) + I urn 0x0021e283, // n0x05d1 c0x0000 (---------------) + I gov 0x00201e82, // n0x05d2 c0x0000 (---------------) + I ac 0x00110603, // n0x05d3 c0x0000 (---------------) + biz 0x05a00742, // n0x05d4 c0x0016 (n0x05d9-n0x05da) + I co 0x00225cc2, // n0x05d5 c0x0000 (---------------) + I gv 0x00000304, // n0x05d6 c0x0000 (---------------) + info 0x00200c42, // n0x05d7 c0x0000 (---------------) + I or 0x000cba44, // n0x05d8 c0x0000 (---------------) + priv 0x000e4188, // n0x05d9 c0x0000 (---------------) + blogspot 0x00226043, // n0x05da c0x0000 (---------------) + I act 0x002a00c3, // n0x05db c0x0000 (---------------) + I asn 0x06222ac3, // n0x05dc c0x0018 (n0x05ec-n0x05ed) + I com 0x00224984, // n0x05dd c0x0000 (---------------) + I conf 0x066d75c3, // n0x05de c0x0019 (n0x05ed-n0x05f5) + I edu 0x06a1e283, // n0x05df c0x001a (n0x05f5-n0x05fa) + I gov 0x00206202, // n0x05e0 c0x0000 (---------------) + I id 0x00200304, // n0x05e1 c0x0000 (---------------) + I info 0x002170c3, // n0x05e2 c0x0000 (---------------) + I net 0x0020ac43, // n0x05e3 c0x0000 (---------------) + I nsw 0x00200e02, // n0x05e4 c0x0000 (---------------) + I nt 0x0021dcc3, // n0x05e5 c0x0000 (---------------) + I org 0x00212bc2, // n0x05e6 c0x0000 (---------------) + I oz 0x002ce743, // n0x05e7 c0x0000 (---------------) + I qld 0x00201a02, // n0x05e8 c0x0000 (---------------) + I sa 0x00200143, // n0x05e9 c0x0000 (---------------) + I tas 0x00243c83, // n0x05ea c0x0000 (---------------) + I vic 0x00202542, // n0x05eb c0x0000 (---------------) + I wa 0x000e4188, // n0x05ec c0x0000 (---------------) + blogspot 0x00226043, // n0x05ed c0x0000 (---------------) + I act 0x0020ac43, // n0x05ee c0x0000 (---------------) + I nsw 0x00200e02, // n0x05ef c0x0000 (---------------) + I nt 0x002ce743, // n0x05f0 c0x0000 (---------------) + I qld 0x00201a02, // n0x05f1 c0x0000 (---------------) + I sa 0x00200143, // n0x05f2 c0x0000 (---------------) + I tas 0x00243c83, // n0x05f3 c0x0000 (---------------) + I vic 0x00202542, // n0x05f4 c0x0000 (---------------) + I wa 0x002ce743, // n0x05f5 c0x0000 (---------------) + I qld 0x00201a02, // n0x05f6 c0x0000 (---------------) + I sa 0x00200143, // n0x05f7 c0x0000 (---------------) + I tas 0x00243c83, // n0x05f8 c0x0000 (---------------) + I vic 0x00202542, // n0x05f9 c0x0000 (---------------) + I wa 0x00222ac3, // n0x05fa c0x0000 (---------------) + I com 0x00310603, // n0x05fb c0x0000 (---------------) + I biz 0x00222ac3, // n0x05fc c0x0000 (---------------) + I com 0x002d75c3, // n0x05fd c0x0000 (---------------) + I edu 0x0021e283, // n0x05fe c0x0000 (---------------) + I gov 0x00200304, // n0x05ff c0x0000 (---------------) + I info 0x00238c03, // n0x0600 c0x0000 (---------------) + I int 0x0023fa03, // n0x0601 c0x0000 (---------------) + I mil 0x00298944, // n0x0602 c0x0000 (---------------) + I name 0x002170c3, // n0x0603 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0604 c0x0000 (---------------) + I org 0x00207742, // n0x0605 c0x0000 (---------------) + I pp 0x00218243, // n0x0606 c0x0000 (---------------) + I pro 0x000e4188, // n0x0607 c0x0000 (---------------) + blogspot 0x00200742, // n0x0608 c0x0000 (---------------) + I co 0x00222ac3, // n0x0609 c0x0000 (---------------) + I com 0x002d75c3, // n0x060a c0x0000 (---------------) + I edu 0x0021e283, // n0x060b c0x0000 (---------------) + I gov 0x0023fa03, // n0x060c c0x0000 (---------------) + I mil 0x002170c3, // n0x060d c0x0000 (---------------) + I net 0x0021dcc3, // n0x060e c0x0000 (---------------) + I org 0x002060c2, // n0x060f c0x0000 (---------------) + I rs 0x00262644, // n0x0610 c0x0000 (---------------) + I unbi 0x00201984, // n0x0611 c0x0000 (---------------) + I unsa 0x00310603, // n0x0612 c0x0000 (---------------) + I biz 0x00200742, // n0x0613 c0x0000 (---------------) + I co 0x00222ac3, // n0x0614 c0x0000 (---------------) + I com 0x002d75c3, // n0x0615 c0x0000 (---------------) + I edu 0x0021e283, // n0x0616 c0x0000 (---------------) + I gov 0x00200304, // n0x0617 c0x0000 (---------------) + I info 0x002170c3, // n0x0618 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0619 c0x0000 (---------------) + I org 0x002cf4c5, // n0x061a c0x0000 (---------------) + I store 0x0020bf42, // n0x061b c0x0000 (---------------) + I tv 0x00201e82, // n0x061c c0x0000 (---------------) + I ac 0x000e4188, // n0x061d c0x0000 (---------------) + blogspot 0x0021e283, // n0x061e c0x0000 (---------------) + I gov 0x00225381, // n0x061f c0x0000 (---------------) + I 0 0x00223681, // n0x0620 c0x0000 (---------------) + I 1 0x0023d901, // n0x0621 c0x0000 (---------------) + I 2 0x00235b01, // n0x0622 c0x0000 (---------------) + I 3 0x00235a81, // n0x0623 c0x0000 (---------------) + I 4 0x002b1e01, // n0x0624 c0x0000 (---------------) + I 5 0x00213ac1, // n0x0625 c0x0000 (---------------) + I 6 0x00225481, // n0x0626 c0x0000 (---------------) + I 7 0x002e4a01, // n0x0627 c0x0000 (---------------) + I 8 0x002e4e01, // n0x0628 c0x0000 (---------------) + I 9 0x00200181, // n0x0629 c0x0000 (---------------) + I a 0x00200001, // n0x062a c0x0000 (---------------) + I b 0x000e4188, // n0x062b c0x0000 (---------------) + blogspot 0x00200741, // n0x062c c0x0000 (---------------) + I c 0x002005c1, // n0x062d c0x0000 (---------------) + I d 0x00200701, // n0x062e c0x0000 (---------------) + I e 0x00200381, // n0x062f c0x0000 (---------------) + I f 0x00200401, // n0x0630 c0x0000 (---------------) + I g 0x00200201, // n0x0631 c0x0000 (---------------) + I h 0x00200041, // n0x0632 c0x0000 (---------------) + I i 0x00201f81, // n0x0633 c0x0000 (---------------) + I j 0x00201001, // n0x0634 c0x0000 (---------------) + I k 0x002008c1, // n0x0635 c0x0000 (---------------) + I l 0x002000c1, // n0x0636 c0x0000 (---------------) + I m 0x00200281, // n0x0637 c0x0000 (---------------) + I n 0x00200081, // n0x0638 c0x0000 (---------------) + I o 0x00200b01, // n0x0639 c0x0000 (---------------) + I p 0x00211181, // n0x063a c0x0000 (---------------) + I q 0x00200581, // n0x063b c0x0000 (---------------) + I r 0x002001c1, // n0x063c c0x0000 (---------------) + I s 0x00200141, // n0x063d c0x0000 (---------------) + I t 0x00200101, // n0x063e c0x0000 (---------------) + I u 0x002013c1, // n0x063f c0x0000 (---------------) + I v 0x00202541, // n0x0640 c0x0000 (---------------) + I w 0x00203ec1, // n0x0641 c0x0000 (---------------) + I x 0x00200801, // n0x0642 c0x0000 (---------------) + I y 0x00201901, // n0x0643 c0x0000 (---------------) + I z 0x00222ac3, // n0x0644 c0x0000 (---------------) + I com 0x002d75c3, // n0x0645 c0x0000 (---------------) + I edu 0x0021e283, // n0x0646 c0x0000 (---------------) + I gov 0x002170c3, // n0x0647 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0648 c0x0000 (---------------) + I org 0x00200742, // n0x0649 c0x0000 (---------------) + I co 0x00222ac3, // n0x064a c0x0000 (---------------) + I com 0x002d75c3, // n0x064b c0x0000 (---------------) + I edu 0x00200c42, // n0x064c c0x0000 (---------------) + I or 0x0021dcc3, // n0x064d c0x0000 (---------------) + I org 0x00009ac6, // n0x064e c0x0000 (---------------) + dyndns 0x00041d4a, // n0x064f c0x0000 (---------------) + for-better 0x00076a48, // n0x0650 c0x0000 (---------------) + for-more 0x00042348, // n0x0651 c0x0000 (---------------) + for-some 0x00042c87, // n0x0652 c0x0000 (---------------) + for-the 0x00130f46, // n0x0653 c0x0000 (---------------) + selfip 0x00110e86, // n0x0654 c0x0000 (---------------) + webhop 0x002729c4, // n0x0655 c0x0000 (---------------) + I asso 0x002f4347, // n0x0656 c0x0000 (---------------) + I barreau 0x000e4188, // n0x0657 c0x0000 (---------------) + blogspot 0x003579c4, // n0x0658 c0x0000 (---------------) + I gouv 0x00222ac3, // n0x0659 c0x0000 (---------------) + I com 0x002d75c3, // n0x065a c0x0000 (---------------) + I edu 0x0021e283, // n0x065b c0x0000 (---------------) + I gov 0x002170c3, // n0x065c c0x0000 (---------------) + I net 0x0021dcc3, // n0x065d c0x0000 (---------------) + I org 0x00222ac3, // n0x065e c0x0000 (---------------) + I com 0x002d75c3, // n0x065f c0x0000 (---------------) + I edu 0x0034eb03, // n0x0660 c0x0000 (---------------) + I gob 0x0021e283, // n0x0661 c0x0000 (---------------) + I gov 0x00238c03, // n0x0662 c0x0000 (---------------) + I int 0x0023fa03, // n0x0663 c0x0000 (---------------) + I mil 0x002170c3, // n0x0664 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0665 c0x0000 (---------------) + I org 0x0020bf42, // n0x0666 c0x0000 (---------------) + I tv 0x002b2643, // n0x0667 c0x0000 (---------------) + I adm 0x002db303, // n0x0668 c0x0000 (---------------) + I adv 0x00256e43, // n0x0669 c0x0000 (---------------) + I agr 0x00204942, // n0x066a c0x0000 (---------------) + I am 0x00323d83, // n0x066b c0x0000 (---------------) + I arq 0x00200603, // n0x066c c0x0000 (---------------) + I art 0x00201643, // n0x066d c0x0000 (---------------) + I ato 0x00200001, // n0x066e c0x0000 (---------------) + I b 0x00200003, // n0x066f c0x0000 (---------------) + I bio 0x002d0084, // n0x0670 c0x0000 (---------------) + I blog 0x0031b803, // n0x0671 c0x0000 (---------------) + I bmd 0x002f4243, // n0x0672 c0x0000 (---------------) + I cim 0x002dbfc3, // n0x0673 c0x0000 (---------------) + I cng 0x002211c3, // n0x0674 c0x0000 (---------------) + I cnt 0x0a622ac3, // n0x0675 c0x0029 (n0x06ad-n0x06ae) + I com 0x00228d44, // n0x0676 c0x0000 (---------------) + I coop 0x00305ec3, // n0x0677 c0x0000 (---------------) + I ecn 0x00200703, // n0x0678 c0x0000 (---------------) + I eco 0x002d75c3, // n0x0679 c0x0000 (---------------) + I edu 0x00226343, // n0x067a c0x0000 (---------------) + I emp 0x002674c3, // n0x067b c0x0000 (---------------) + I eng 0x0028cac3, // n0x067c c0x0000 (---------------) + I esp 0x002f41c3, // n0x067d c0x0000 (---------------) + I etc 0x0021bac3, // n0x067e c0x0000 (---------------) + I eti 0x0021f803, // n0x067f c0x0000 (---------------) + I far 0x0023bdc4, // n0x0680 c0x0000 (---------------) + I flog 0x00358002, // n0x0681 c0x0000 (---------------) + I fm 0x002416c3, // n0x0682 c0x0000 (---------------) + I fnd 0x00247a83, // n0x0683 c0x0000 (---------------) + I fot 0x002645c3, // n0x0684 c0x0000 (---------------) + I fst 0x0036f1c3, // n0x0685 c0x0000 (---------------) + I g12 0x00311b83, // n0x0686 c0x0000 (---------------) + I ggf 0x0021e283, // n0x0687 c0x0000 (---------------) + I gov 0x002b7c43, // n0x0688 c0x0000 (---------------) + I imb 0x00215703, // n0x0689 c0x0000 (---------------) + I ind 0x00200303, // n0x068a c0x0000 (---------------) + I inf 0x00202c03, // n0x068b c0x0000 (---------------) + I jor 0x002de8c3, // n0x068c c0x0000 (---------------) + I jus 0x0021e843, // n0x068d c0x0000 (---------------) + I leg 0x002e3403, // n0x068e c0x0000 (---------------) + I lel 0x0020f583, // n0x068f c0x0000 (---------------) + I mat 0x0020b403, // n0x0690 c0x0000 (---------------) + I med 0x0023fa03, // n0x0691 c0x0000 (---------------) + I mil 0x00214902, // n0x0692 c0x0000 (---------------) + I mp 0x002bc903, // n0x0693 c0x0000 (---------------) + I mus 0x002170c3, // n0x0694 c0x0000 (---------------) + I net 0x01607cc3, // n0x0695 c0x0005 (---------------)* o I nom 0x0023fdc3, // n0x0696 c0x0000 (---------------) + I not 0x00211c03, // n0x0697 c0x0000 (---------------) + I ntr 0x0024f003, // n0x0698 c0x0000 (---------------) + I odo 0x0021dcc3, // n0x0699 c0x0000 (---------------) + I org 0x002bf143, // n0x069a c0x0000 (---------------) + I ppg 0x00218243, // n0x069b c0x0000 (---------------) + I pro 0x002353c3, // n0x069c c0x0000 (---------------) + I psc 0x002dc783, // n0x069d c0x0000 (---------------) + I psi 0x002ce903, // n0x069e c0x0000 (---------------) + I qsl 0x00250685, // n0x069f c0x0000 (---------------) + I radio 0x002e6343, // n0x06a0 c0x0000 (---------------) + I rec 0x002ce943, // n0x06a1 c0x0000 (---------------) + I slg 0x002cef83, // n0x06a2 c0x0000 (---------------) + I srv 0x00217c44, // n0x06a3 c0x0000 (---------------) + I taxi 0x00362ec3, // n0x06a4 c0x0000 (---------------) + I teo 0x002fb583, // n0x06a5 c0x0000 (---------------) + I tmp 0x00283003, // n0x06a6 c0x0000 (---------------) + I trd 0x00227303, // n0x06a7 c0x0000 (---------------) + I tur 0x0020bf42, // n0x06a8 c0x0000 (---------------) + I tv 0x0022b9c3, // n0x06a9 c0x0000 (---------------) + I vet 0x002df504, // n0x06aa c0x0000 (---------------) + I vlog 0x0025a484, // n0x06ab c0x0000 (---------------) + I wiki 0x0024dc43, // n0x06ac c0x0000 (---------------) + I zlg 0x000e4188, // n0x06ad c0x0000 (---------------) + blogspot 0x00222ac3, // n0x06ae c0x0000 (---------------) + I com 0x002d75c3, // n0x06af c0x0000 (---------------) + I edu 0x0021e283, // n0x06b0 c0x0000 (---------------) + I gov 0x002170c3, // n0x06b1 c0x0000 (---------------) + I net 0x0021dcc3, // n0x06b2 c0x0000 (---------------) + I org 0x00222ac3, // n0x06b3 c0x0000 (---------------) + I com 0x002d75c3, // n0x06b4 c0x0000 (---------------) + I edu 0x0021e283, // n0x06b5 c0x0000 (---------------) + I gov 0x002170c3, // n0x06b6 c0x0000 (---------------) + I net 0x0021dcc3, // n0x06b7 c0x0000 (---------------) + I org 0x00200742, // n0x06b8 c0x0000 (---------------) + I co 0x0021dcc3, // n0x06b9 c0x0000 (---------------) + I org 0x0ba22ac3, // n0x06ba c0x002e (n0x06be-n0x06bf) + I com 0x0021e283, // n0x06bb c0x0000 (---------------) + I gov 0x0023fa03, // n0x06bc c0x0000 (---------------) + I mil 0x00209982, // n0x06bd c0x0000 (---------------) + I of 0x000e4188, // n0x06be c0x0000 (---------------) + blogspot 0x00222ac3, // n0x06bf c0x0000 (---------------) + I com 0x002d75c3, // n0x06c0 c0x0000 (---------------) + I edu 0x0021e283, // n0x06c1 c0x0000 (---------------) + I gov 0x002170c3, // n0x06c2 c0x0000 (---------------) + I net 0x0021dcc3, // n0x06c3 c0x0000 (---------------) + I org 0x000043c2, // n0x06c4 c0x0000 (---------------) + za 0x002004c2, // n0x06c5 c0x0000 (---------------) + I ab 0x0021a042, // n0x06c6 c0x0000 (---------------) + I bc 0x000e4188, // n0x06c7 c0x0000 (---------------) + blogspot 0x00000742, // n0x06c8 c0x0000 (---------------) + co 0x00227d42, // n0x06c9 c0x0000 (---------------) + I gc 0x00205942, // n0x06ca c0x0000 (---------------) + I mb 0x00210d42, // n0x06cb c0x0000 (---------------) + I nb 0x00200342, // n0x06cc c0x0000 (---------------) + I nf 0x00236482, // n0x06cd c0x0000 (---------------) + I nl 0x002019c2, // n0x06ce c0x0000 (---------------) + I ns 0x00200e02, // n0x06cf c0x0000 (---------------) + I nt 0x00205bc2, // n0x06d0 c0x0000 (---------------) + I nu 0x00200dc2, // n0x06d1 c0x0000 (---------------) + I on 0x00214942, // n0x06d2 c0x0000 (---------------) + I pe 0x00369542, // n0x06d3 c0x0000 (---------------) + I qc 0x00207b42, // n0x06d4 c0x0000 (---------------) + I sk 0x002202c2, // n0x06d5 c0x0000 (---------------) + I yk 0x00085109, // n0x06d6 c0x0000 (---------------) + ftpaccess 0x0001208b, // n0x06d7 c0x0000 (---------------) + game-server 0x000bea08, // n0x06d8 c0x0000 (---------------) + myphotos 0x00043609, // n0x06d9 c0x0000 (---------------) + scrapping 0x0021e283, // n0x06da c0x0000 (---------------) + I gov 0x000e4188, // n0x06db c0x0000 (---------------) + blogspot 0x000e4188, // n0x06dc c0x0000 (---------------) + blogspot 0x00201e82, // n0x06dd c0x0000 (---------------) + I ac 0x002729c4, // n0x06de c0x0000 (---------------) + I asso 0x00200742, // n0x06df c0x0000 (---------------) + I co 0x00222ac3, // n0x06e0 c0x0000 (---------------) + I com 0x00203fc2, // n0x06e1 c0x0000 (---------------) + I ed 0x002d75c3, // n0x06e2 c0x0000 (---------------) + I edu 0x00202342, // n0x06e3 c0x0000 (---------------) + I go 0x003579c4, // n0x06e4 c0x0000 (---------------) + I gouv 0x00238c03, // n0x06e5 c0x0000 (---------------) + I int 0x00238602, // n0x06e6 c0x0000 (---------------) + I md 0x002170c3, // n0x06e7 c0x0000 (---------------) + I net 0x00200c42, // n0x06e8 c0x0000 (---------------) + I or 0x0021dcc3, // n0x06e9 c0x0000 (---------------) + I org 0x0029abc6, // n0x06ea c0x0000 (---------------) + I presse 0x002f710f, // n0x06eb c0x0000 (---------------) + I xn--aroport-bya 0x006e3e83, // n0x06ec c0x0001 (---------------) ! I www 0x000e4188, // n0x06ed c0x0000 (---------------) + blogspot 0x00200742, // n0x06ee c0x0000 (---------------) + I co 0x0034eb03, // n0x06ef c0x0000 (---------------) + I gob 0x0021e283, // n0x06f0 c0x0000 (---------------) + I gov 0x0023fa03, // n0x06f1 c0x0000 (---------------) + I mil 0x00200742, // n0x06f2 c0x0000 (---------------) + I co 0x00222ac3, // n0x06f3 c0x0000 (---------------) + I com 0x0021e283, // n0x06f4 c0x0000 (---------------) + I gov 0x002170c3, // n0x06f5 c0x0000 (---------------) + I net 0x00201e82, // n0x06f6 c0x0000 (---------------) + I ac 0x002076c2, // n0x06f7 c0x0000 (---------------) + I ah 0x0ea72409, // n0x06f8 c0x003a (n0x0723-n0x0724) o I amazonaws 0x00202642, // n0x06f9 c0x0000 (---------------) + I bj 0x0f222ac3, // n0x06fa c0x003c (n0x0725-n0x0726) + I com 0x0022e082, // n0x06fb c0x0000 (---------------) + I cq 0x002d75c3, // n0x06fc c0x0000 (---------------) + I edu 0x002241c2, // n0x06fd c0x0000 (---------------) + I fj 0x0021b342, // n0x06fe c0x0000 (---------------) + I gd 0x0021e283, // n0x06ff c0x0000 (---------------) + I gov 0x0026cd02, // n0x0700 c0x0000 (---------------) + I gs 0x0023d702, // n0x0701 c0x0000 (---------------) + I gx 0x00243802, // n0x0702 c0x0000 (---------------) + I gz 0x00202dc2, // n0x0703 c0x0000 (---------------) + I ha 0x002f6242, // n0x0704 c0x0000 (---------------) + I hb 0x00205202, // n0x0705 c0x0000 (---------------) + I he 0x00200202, // n0x0706 c0x0000 (---------------) + I hi 0x0022ea02, // n0x0707 c0x0000 (---------------) + I hk 0x0020cc02, // n0x0708 c0x0000 (---------------) + I hl 0x00217542, // n0x0709 c0x0000 (---------------) + I hn 0x00297c82, // n0x070a c0x0000 (---------------) + I jl 0x002bdf02, // n0x070b c0x0000 (---------------) + I js 0x002fc642, // n0x070c c0x0000 (---------------) + I jx 0x0021f442, // n0x070d c0x0000 (---------------) + I ln 0x0023fa03, // n0x070e c0x0000 (---------------) + I mil 0x00203602, // n0x070f c0x0000 (---------------) + I mo 0x002170c3, // n0x0710 c0x0000 (---------------) + I net 0x00233c42, // n0x0711 c0x0000 (---------------) + I nm 0x0026d802, // n0x0712 c0x0000 (---------------) + I nx 0x0021dcc3, // n0x0713 c0x0000 (---------------) + I org 0x0022e0c2, // n0x0714 c0x0000 (---------------) + I qh 0x00200982, // n0x0715 c0x0000 (---------------) + I sc 0x0024f842, // n0x0716 c0x0000 (---------------) + I sd 0x002001c2, // n0x0717 c0x0000 (---------------) + I sh 0x00210b02, // n0x0718 c0x0000 (---------------) + I sn 0x002d6b42, // n0x0719 c0x0000 (---------------) + I sx 0x00202bc2, // n0x071a c0x0000 (---------------) + I tj 0x00241ac2, // n0x071b c0x0000 (---------------) + I tw 0x0020a882, // n0x071c c0x0000 (---------------) + I xj 0x002ea10a, // n0x071d c0x0000 (---------------) + I xn--55qx5d 0x0033080a, // n0x071e c0x0000 (---------------) + I xn--io0a7i 0x0036394a, // n0x071f c0x0000 (---------------) + I xn--od0alg 0x00397682, // n0x0720 c0x0000 (---------------) + I xz 0x00200802, // n0x0721 c0x0000 (---------------) + I yn 0x00243842, // n0x0722 c0x0000 (---------------) + I zj 0x0ec23487, // n0x0723 c0x003b (n0x0724-n0x0725) + compute 0x00105f0a, // n0x0724 c0x0000 (---------------) + cn-north-1 0x0f672409, // n0x0725 c0x003d (n0x0726-n0x0727) o I amazonaws 0x0fb05f0a, // n0x0726 c0x003e (n0x0727-n0x0728) o I cn-north-1 0x000413c2, // n0x0727 c0x0000 (---------------) + s3 0x00246584, // n0x0728 c0x0000 (---------------) + I arts 0x10222ac3, // n0x0729 c0x0040 (n0x0735-n0x0736) + I com 0x002d75c3, // n0x072a c0x0000 (---------------) + I edu 0x00238544, // n0x072b c0x0000 (---------------) + I firm 0x0021e283, // n0x072c c0x0000 (---------------) + I gov 0x00200304, // n0x072d c0x0000 (---------------) + I info 0x00238c03, // n0x072e c0x0000 (---------------) + I int 0x0023fa03, // n0x072f c0x0000 (---------------) + I mil 0x002170c3, // n0x0730 c0x0000 (---------------) + I net 0x00207cc3, // n0x0731 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x0732 c0x0000 (---------------) + I org 0x002e6343, // n0x0733 c0x0000 (---------------) + I rec 0x00219fc3, // n0x0734 c0x0000 (---------------) + I web 0x000e4188, // n0x0735 c0x0000 (---------------) + blogspot 0x000f00c5, // n0x0736 c0x0000 (---------------) + 1kapp 0x000f2202, // n0x0737 c0x0000 (---------------) + 4u 0x00167c06, // n0x0738 c0x0000 (---------------) + africa 0x10a72409, // n0x0739 c0x0042 (n0x07ff-n0x0811) o I amazonaws 0x00036947, // n0x073a c0x0000 (---------------) + appspot 0x00000602, // n0x073b c0x0000 (---------------) + ar 0x00163e4a, // n0x073c c0x0000 (---------------) + betainabox 0x000d0087, // n0x073d c0x0000 (---------------) + blogdns 0x000e4188, // n0x073e c0x0000 (---------------) + blogspot 0x00012e82, // n0x073f c0x0000 (---------------) + br 0x0012df87, // n0x0740 c0x0000 (---------------) + cechire 0x0013220f, // n0x0741 c0x0000 (---------------) + cloudcontrolapp 0x0018d44f, // n0x0742 c0x0000 (---------------) + cloudcontrolled 0x000211c2, // n0x0743 c0x0000 (---------------) + cn 0x00000742, // n0x0744 c0x0000 (---------------) + co 0x0008ca08, // n0x0745 c0x0000 (---------------) + codespot 0x000006c2, // n0x0746 c0x0000 (---------------) + de 0x00146fc8, // n0x0747 c0x0000 (---------------) + dnsalias 0x0006a247, // n0x0748 c0x0000 (---------------) + dnsdojo 0x00010a4b, // n0x0749 c0x0000 (---------------) + doesntexist 0x0015fdc9, // n0x074a c0x0000 (---------------) + dontexist 0x00146ec7, // n0x074b c0x0000 (---------------) + doomdns 0x000da58c, // n0x074c c0x0000 (---------------) + dreamhosters 0x0015aeca, // n0x074d c0x0000 (---------------) + dyn-o-saur 0x000007c8, // n0x074e c0x0000 (---------------) + dynalias 0x000b8c0e, // n0x074f c0x0000 (---------------) + dyndns-at-home 0x000e024e, // n0x0750 c0x0000 (---------------) + dyndns-at-work 0x000cfecb, // n0x0751 c0x0000 (---------------) + dyndns-blog 0x00009acb, // n0x0752 c0x0000 (---------------) + dyndns-free 0x0000b1cb, // n0x0753 c0x0000 (---------------) + dyndns-home 0x00013889, // n0x0754 c0x0000 (---------------) + dyndns-ip 0x00018d4b, // n0x0755 c0x0000 (---------------) + dyndns-mail 0x00019a8d, // n0x0756 c0x0000 (---------------) + dyndns-office 0x0001ea4b, // n0x0757 c0x0000 (---------------) + dyndns-pics 0x0001fd0d, // n0x0758 c0x0000 (---------------) + dyndns-remote 0x00020d4d, // n0x0759 c0x0000 (---------------) + dyndns-server 0x00051b0a, // n0x075a c0x0000 (---------------) + dyndns-web 0x0005a2cb, // n0x075b c0x0000 (---------------) + dyndns-wiki 0x0009aecb, // n0x075c c0x0000 (---------------) + dyndns-work 0x00016650, // n0x075d c0x0000 (---------------) + elasticbeanstalk 0x0013c78f, // n0x075e c0x0000 (---------------) + est-a-la-maison 0x0002270f, // n0x075f c0x0000 (---------------) + est-a-la-masion 0x000144cd, // n0x0760 c0x0000 (---------------) + est-le-patron 0x000ef550, // n0x0761 c0x0000 (---------------) + est-mon-blogueur 0x0001d5c2, // n0x0762 c0x0000 (---------------) + eu 0x0003674b, // n0x0763 c0x0000 (---------------) + firebaseapp 0x0003ffc8, // n0x0764 c0x0000 (---------------) + flynnhub 0x0004d407, // n0x0765 c0x0000 (---------------) + from-ak 0x0004d747, // n0x0766 c0x0000 (---------------) + from-al 0x0004d907, // n0x0767 c0x0000 (---------------) + from-ar 0x0004dd07, // n0x0768 c0x0000 (---------------) + from-ca 0x0004f607, // n0x0769 c0x0000 (---------------) + from-ct 0x00050247, // n0x076a c0x0000 (---------------) + from-dc 0x00052787, // n0x076b c0x0000 (---------------) + from-de 0x00052a47, // n0x076c c0x0000 (---------------) + from-fl 0x00054187, // n0x076d c0x0000 (---------------) + from-ga 0x00054487, // n0x076e c0x0000 (---------------) + from-hi 0x00054ec7, // n0x076f c0x0000 (---------------) + from-ia 0x00055087, // n0x0770 c0x0000 (---------------) + from-id 0x00055247, // n0x0771 c0x0000 (---------------) + from-il 0x00055407, // n0x0772 c0x0000 (---------------) + from-in 0x000561c7, // n0x0773 c0x0000 (---------------) + from-ks 0x00056787, // n0x0774 c0x0000 (---------------) + from-ky 0x00057247, // n0x0775 c0x0000 (---------------) + from-ma 0x00057647, // n0x0776 c0x0000 (---------------) + from-md 0x00057d87, // n0x0777 c0x0000 (---------------) + from-mi 0x00058887, // n0x0778 c0x0000 (---------------) + from-mn 0x00058a47, // n0x0779 c0x0000 (---------------) + from-mo 0x00059007, // n0x077a c0x0000 (---------------) + from-ms 0x00059507, // n0x077b c0x0000 (---------------) + from-mt 0x00059707, // n0x077c c0x0000 (---------------) + from-nc 0x0005a607, // n0x077d c0x0000 (---------------) + from-nd 0x0005a7c7, // n0x077e c0x0000 (---------------) + from-ne 0x0005a987, // n0x077f c0x0000 (---------------) + from-nh 0x0005b247, // n0x0780 c0x0000 (---------------) + from-nj 0x0005b747, // n0x0781 c0x0000 (---------------) + from-nm 0x0005c247, // n0x0782 c0x0000 (---------------) + from-nv 0x0005c847, // n0x0783 c0x0000 (---------------) + from-oh 0x0005cf07, // n0x0784 c0x0000 (---------------) + from-ok 0x0005d407, // n0x0785 c0x0000 (---------------) + from-or 0x0005d5c7, // n0x0786 c0x0000 (---------------) + from-pa 0x0005d947, // n0x0787 c0x0000 (---------------) + from-pr 0x0005e307, // n0x0788 c0x0000 (---------------) + from-ri 0x0005e687, // n0x0789 c0x0000 (---------------) + from-sc 0x0005ea87, // n0x078a c0x0000 (---------------) + from-sd 0x000604c7, // n0x078b c0x0000 (---------------) + from-tn 0x00060687, // n0x078c c0x0000 (---------------) + from-tx 0x00061207, // n0x078d c0x0000 (---------------) + from-ut 0x00062947, // n0x078e c0x0000 (---------------) + from-va 0x00062f87, // n0x078f c0x0000 (---------------) + from-vt 0x00063287, // n0x0790 c0x0000 (---------------) + from-wa 0x00063447, // n0x0791 c0x0000 (---------------) + from-wi 0x000637c7, // n0x0792 c0x0000 (---------------) + from-wv 0x00063a07, // n0x0793 c0x0000 (---------------) + from-wy 0x00005a42, // n0x0794 c0x0000 (---------------) + gb 0x000c0587, // n0x0795 c0x0000 (---------------) + getmyip 0x000b53d1, // n0x0796 c0x0000 (---------------) + githubusercontent 0x000cd58a, // n0x0797 c0x0000 (---------------) + googleapis 0x0008c88a, // n0x0798 c0x0000 (---------------) + googlecode 0x00043a86, // n0x0799 c0x0000 (---------------) + gotdns 0x0000dc82, // n0x079a c0x0000 (---------------) + gr 0x0008f309, // n0x079b c0x0000 (---------------) + herokuapp 0x0007fe89, // n0x079c c0x0000 (---------------) + herokussl 0x0002ea02, // n0x079d c0x0000 (---------------) + hk 0x0013eeca, // n0x079e c0x0000 (---------------) + hobby-site 0x00090ec9, // n0x079f c0x0000 (---------------) + homelinux 0x00091b88, // n0x07a0 c0x0000 (---------------) + homeunix 0x00017d42, // n0x07a1 c0x0000 (---------------) + hu 0x001008c9, // n0x07a2 c0x0000 (---------------) + iamallama 0x0005db8e, // n0x07a3 c0x0000 (---------------) + is-a-anarchist 0x000d5d8c, // n0x07a4 c0x0000 (---------------) + is-a-blogger 0x000bf2cf, // n0x07a5 c0x0000 (---------------) + is-a-bookkeeper 0x0017d14e, // n0x07a6 c0x0000 (---------------) + is-a-bulls-fan 0x0000cf8c, // n0x07a7 c0x0000 (---------------) + is-a-caterer 0x00166909, // n0x07a8 c0x0000 (---------------) + is-a-chef 0x00099ad1, // n0x07a9 c0x0000 (---------------) + is-a-conservative 0x0009a088, // n0x07aa c0x0000 (---------------) + is-a-cpa 0x00169b92, // n0x07ab c0x0000 (---------------) + is-a-cubicle-slave 0x0002e40d, // n0x07ac c0x0000 (---------------) + is-a-democrat 0x00032e0d, // n0x07ad c0x0000 (---------------) + is-a-designer 0x00138acb, // n0x07ae c0x0000 (---------------) + is-a-doctor 0x001713d5, // n0x07af c0x0000 (---------------) + is-a-financialadvisor 0x00052e49, // n0x07b0 c0x0000 (---------------) + is-a-geek 0x0005afca, // n0x07b1 c0x0000 (---------------) + is-a-green 0x0005bb09, // n0x07b2 c0x0000 (---------------) + is-a-guru 0x00060e10, // n0x07b3 c0x0000 (---------------) + is-a-hard-worker 0x00065f4b, // n0x07b4 c0x0000 (---------------) + is-a-hunter 0x0006f74f, // n0x07b5 c0x0000 (---------------) + is-a-landscaper 0x000702cb, // n0x07b6 c0x0000 (---------------) + is-a-lawyer 0x00073b0c, // n0x07b7 c0x0000 (---------------) + is-a-liberal 0x00077590, // n0x07b8 c0x0000 (---------------) + is-a-libertarian 0x001370ca, // n0x07b9 c0x0000 (---------------) + is-a-llama 0x00137a4d, // n0x07ba c0x0000 (---------------) + is-a-musician 0x00174a0e, // n0x07bb c0x0000 (---------------) + is-a-nascarfan 0x0007bf4a, // n0x07bc c0x0000 (---------------) + is-a-nurse 0x0007d0cc, // n0x07bd c0x0000 (---------------) + is-a-painter 0x0008ab94, // n0x07be c0x0000 (---------------) + is-a-personaltrainer 0x0008ef91, // n0x07bf c0x0000 (---------------) + is-a-photographer 0x00090c0b, // n0x07c0 c0x0000 (---------------) + is-a-player 0x0009638f, // n0x07c1 c0x0000 (---------------) + is-a-republican 0x00096fcd, // n0x07c2 c0x0000 (---------------) + is-a-rockstar 0x000c268e, // n0x07c3 c0x0000 (---------------) + is-a-socialist 0x0009844c, // n0x07c4 c0x0000 (---------------) + is-a-student 0x0009d08c, // n0x07c5 c0x0000 (---------------) + is-a-teacher 0x000c238b, // n0x07c6 c0x0000 (---------------) + is-a-techie 0x000c3f4e, // n0x07c7 c0x0000 (---------------) + is-a-therapist 0x000d7cd0, // n0x07c8 c0x0000 (---------------) + is-an-accountant 0x0015d44b, // n0x07c9 c0x0000 (---------------) + is-an-actor 0x000a110d, // n0x07ca c0x0000 (---------------) + is-an-actress 0x000a768f, // n0x07cb c0x0000 (---------------) + is-an-anarchist 0x000a814c, // n0x07cc c0x0000 (---------------) + is-an-artist 0x000a890e, // n0x07cd c0x0000 (---------------) + is-an-engineer 0x000a97d1, // n0x07ce c0x0000 (---------------) + is-an-entertainer 0x00135f8c, // n0x07cf c0x0000 (---------------) + is-certified 0x00133a07, // n0x07d0 c0x0000 (---------------) + is-gone 0x000b0fcd, // n0x07d1 c0x0000 (---------------) + is-into-anime 0x000b918c, // n0x07d2 c0x0000 (---------------) + is-into-cars 0x000d1250, // n0x07d3 c0x0000 (---------------) + is-into-cartoons 0x000d1f4d, // n0x07d4 c0x0000 (---------------) + is-into-games 0x000d3087, // n0x07d5 c0x0000 (---------------) + is-leet 0x000d7250, // n0x07d6 c0x0000 (---------------) + is-not-certified 0x000f9e48, // n0x07d7 c0x0000 (---------------) + is-slick 0x001063cb, // n0x07d8 c0x0000 (---------------) + is-uberleet 0x00146b4f, // n0x07d9 c0x0000 (---------------) + is-with-theband 0x00191648, // n0x07da c0x0000 (---------------) + isa-geek 0x000cd78d, // n0x07db c0x0000 (---------------) + isa-hockeynut 0x00159d10, // n0x07dc c0x0000 (---------------) + issmarterthanyou 0x0009a703, // n0x07dd c0x0000 (---------------) + jpn 0x000034c2, // n0x07de c0x0000 (---------------) + kr 0x00061689, // n0x07df c0x0000 (---------------) + likes-pie 0x0007878a, // n0x07e0 c0x0000 (---------------) + likescandy 0x00032003, // n0x07e1 c0x0000 (---------------) + mex 0x001024c8, // n0x07e2 c0x0000 (---------------) + neat-url 0x00002f07, // n0x07e3 c0x0000 (---------------) + nfshost 0x00000c02, // n0x07e4 c0x0000 (---------------) + no 0x0005080a, // n0x07e5 c0x0000 (---------------) + operaunite 0x0019238f, // n0x07e6 c0x0000 (---------------) + outsystemscloud 0x00110fd2, // n0x07e7 c0x0000 (---------------) + pagespeedmobilizer 0x00169542, // n0x07e8 c0x0000 (---------------) + qc 0x00132187, // n0x07e9 c0x0000 (---------------) + rhcloud 0x00000d82, // n0x07ea c0x0000 (---------------) + ro 0x000044c2, // n0x07eb c0x0000 (---------------) + ru 0x00001a02, // n0x07ec c0x0000 (---------------) + sa 0x0002f650, // n0x07ed c0x0000 (---------------) + saves-the-whales 0x00002e82, // n0x07ee c0x0000 (---------------) + se 0x00130f46, // n0x07ef c0x0000 (---------------) + selfip 0x000c368e, // n0x07f0 c0x0000 (---------------) + sells-for-less 0x0007ac8b, // n0x07f1 c0x0000 (---------------) + sells-for-u 0x00079088, // n0x07f2 c0x0000 (---------------) + servebbs 0x000e0a0a, // n0x07f3 c0x0000 (---------------) + simple-url 0x000dc7c7, // n0x07f4 c0x0000 (---------------) + sinaapp 0x000101cd, // n0x07f5 c0x0000 (---------------) + space-to-rent 0x0010160c, // n0x07f6 c0x0000 (---------------) + teaches-yoga 0x0000cf02, // n0x07f7 c0x0000 (---------------) + uk 0x00009f42, // n0x07f8 c0x0000 (---------------) + us 0x00006842, // n0x07f9 c0x0000 (---------------) + uy 0x000dc70a, // n0x07fa c0x0000 (---------------) + vipsinaapp 0x000cd48a, // n0x07fb c0x0000 (---------------) + withgoogle 0x000e3f0e, // n0x07fc c0x0000 (---------------) + writesthisblog 0x000c9948, // n0x07fd c0x0000 (---------------) + yolasite 0x000043c2, // n0x07fe c0x0000 (---------------) + za 0x10c23487, // n0x07ff c0x0043 (n0x0811-n0x081a) + compute 0x11023489, // n0x0800 c0x0044 (n0x081a-n0x081c) + compute-1 0x0000a503, // n0x0801 c0x0000 (---------------) + elb 0x1172bb4c, // n0x0802 c0x0045 (n0x081c-n0x081d) o I eu-central-1 0x000413c2, // n0x0803 c0x0000 (---------------) + s3 0x000f0c51, // n0x0804 c0x0000 (---------------) + s3-ap-northeast-1 0x000f9411, // n0x0805 c0x0000 (---------------) + s3-ap-southeast-1 0x0010a591, // n0x0806 c0x0000 (---------------) + s3-ap-southeast-2 0x0012ba8f, // n0x0807 c0x0000 (---------------) + s3-eu-central-1 0x00072c0c, // n0x0808 c0x0000 (---------------) + s3-eu-west-1 0x0010d14d, // n0x0809 c0x0000 (---------------) + s3-external-1 0x0010ef8d, // n0x080a c0x0000 (---------------) + s3-external-2 0x0011e6d5, // n0x080b c0x0000 (---------------) + s3-fips-us-gov-west-1 0x000413cc, // n0x080c c0x0000 (---------------) + s3-sa-east-1 0x000696d0, // n0x080d c0x0000 (---------------) + s3-us-gov-west-1 0x0011960c, // n0x080e c0x0000 (---------------) + s3-us-west-1 0x000affcc, // n0x080f c0x0000 (---------------) + s3-us-west-2 0x0002b6c9, // n0x0810 c0x0000 (---------------) + us-east-1 0x000f0d0e, // n0x0811 c0x0000 (---------------) + ap-northeast-1 0x000f94ce, // n0x0812 c0x0000 (---------------) + ap-southeast-1 0x0010a64e, // n0x0813 c0x0000 (---------------) + ap-southeast-2 0x0012bb4c, // n0x0814 c0x0000 (---------------) + eu-central-1 0x00072cc9, // n0x0815 c0x0000 (---------------) + eu-west-1 0x00041489, // n0x0816 c0x0000 (---------------) + sa-east-1 0x0006978d, // n0x0817 c0x0000 (---------------) + us-gov-west-1 0x001196c9, // n0x0818 c0x0000 (---------------) + us-west-1 0x000b0089, // n0x0819 c0x0000 (---------------) + us-west-2 0x000f0043, // n0x081a c0x0000 (---------------) + z-1 0x000c8c03, // n0x081b c0x0000 (---------------) + z-2 0x000413c2, // n0x081c c0x0000 (---------------) + s3 0x00201e82, // n0x081d c0x0000 (---------------) + I ac 0x00200742, // n0x081e c0x0000 (---------------) + I co 0x00203fc2, // n0x081f c0x0000 (---------------) + I ed 0x002099c2, // n0x0820 c0x0000 (---------------) + I fi 0x00202342, // n0x0821 c0x0000 (---------------) + I go 0x00200c42, // n0x0822 c0x0000 (---------------) + I or 0x00201a02, // n0x0823 c0x0000 (---------------) + I sa 0x00222ac3, // n0x0824 c0x0000 (---------------) + I com 0x002d75c3, // n0x0825 c0x0000 (---------------) + I edu 0x0021e283, // n0x0826 c0x0000 (---------------) + I gov 0x00200303, // n0x0827 c0x0000 (---------------) + I inf 0x002170c3, // n0x0828 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0829 c0x0000 (---------------) + I org 0x000e4188, // n0x082a c0x0000 (---------------) + blogspot 0x00222ac3, // n0x082b c0x0000 (---------------) + I com 0x002d75c3, // n0x082c c0x0000 (---------------) + I edu 0x002170c3, // n0x082d c0x0000 (---------------) + I net 0x0021dcc3, // n0x082e c0x0000 (---------------) + I org 0x00078a43, // n0x082f c0x0000 (---------------) + ath 0x0021e283, // n0x0830 c0x0000 (---------------) + I gov 0x00201e82, // n0x0831 c0x0000 (---------------) + I ac 0x00310603, // n0x0832 c0x0000 (---------------) + I biz 0x13222ac3, // n0x0833 c0x004c (n0x083e-n0x083f) + I com 0x00267c47, // n0x0834 c0x0000 (---------------) + I ekloges 0x0021e283, // n0x0835 c0x0000 (---------------) + I gov 0x003413c3, // n0x0836 c0x0000 (---------------) + I ltd 0x00298944, // n0x0837 c0x0000 (---------------) + I name 0x002170c3, // n0x0838 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0839 c0x0000 (---------------) + I org 0x002647ca, // n0x083a c0x0000 (---------------) + I parliament 0x0029abc5, // n0x083b c0x0000 (---------------) + I press 0x00218243, // n0x083c c0x0000 (---------------) + I pro 0x00208902, // n0x083d c0x0000 (---------------) + I tm 0x000e4188, // n0x083e c0x0000 (---------------) + blogspot 0x000e4188, // n0x083f c0x0000 (---------------) + blogspot 0x000e4188, // n0x0840 c0x0000 (---------------) + blogspot 0x00022ac3, // n0x0841 c0x0000 (---------------) + com 0x0009fe8f, // n0x0842 c0x0000 (---------------) + fuettertdasnetz 0x0015ff4a, // n0x0843 c0x0000 (---------------) + isteingeek 0x000c2947, // n0x0844 c0x0000 (---------------) + istmein 0x00016f4a, // n0x0845 c0x0000 (---------------) + lebtimnetz 0x0006cb8a, // n0x0846 c0x0000 (---------------) + leitungsen 0x000e8f4d, // n0x0847 c0x0000 (---------------) + traeumtgerade 0x000e4188, // n0x0848 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x0849 c0x0000 (---------------) + I com 0x002d75c3, // n0x084a c0x0000 (---------------) + I edu 0x0021e283, // n0x084b c0x0000 (---------------) + I gov 0x002170c3, // n0x084c c0x0000 (---------------) + I net 0x0021dcc3, // n0x084d c0x0000 (---------------) + I org 0x00200603, // n0x084e c0x0000 (---------------) + I art 0x00222ac3, // n0x084f c0x0000 (---------------) + I com 0x002d75c3, // n0x0850 c0x0000 (---------------) + I edu 0x0034eb03, // n0x0851 c0x0000 (---------------) + I gob 0x0021e283, // n0x0852 c0x0000 (---------------) + I gov 0x0023fa03, // n0x0853 c0x0000 (---------------) + I mil 0x002170c3, // n0x0854 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0855 c0x0000 (---------------) + I org 0x00280043, // n0x0856 c0x0000 (---------------) + I sld 0x00219fc3, // n0x0857 c0x0000 (---------------) + I web 0x00200603, // n0x0858 c0x0000 (---------------) + I art 0x002729c4, // n0x0859 c0x0000 (---------------) + I asso 0x00222ac3, // n0x085a c0x0000 (---------------) + I com 0x002d75c3, // n0x085b c0x0000 (---------------) + I edu 0x0021e283, // n0x085c c0x0000 (---------------) + I gov 0x002170c3, // n0x085d c0x0000 (---------------) + I net 0x0021dcc3, // n0x085e c0x0000 (---------------) + I org 0x00218943, // n0x085f c0x0000 (---------------) + I pol 0x00222ac3, // n0x0860 c0x0000 (---------------) + I com 0x002d75c3, // n0x0861 c0x0000 (---------------) + I edu 0x00236403, // n0x0862 c0x0000 (---------------) + I fin 0x0034eb03, // n0x0863 c0x0000 (---------------) + I gob 0x0021e283, // n0x0864 c0x0000 (---------------) + I gov 0x00200304, // n0x0865 c0x0000 (---------------) + I info 0x00312503, // n0x0866 c0x0000 (---------------) + I k12 0x0020b403, // n0x0867 c0x0000 (---------------) + I med 0x0023fa03, // n0x0868 c0x0000 (---------------) + I mil 0x002170c3, // n0x0869 c0x0000 (---------------) + I net 0x0021dcc3, // n0x086a c0x0000 (---------------) + I org 0x00218243, // n0x086b c0x0000 (---------------) + I pro 0x00382f83, // n0x086c c0x0000 (---------------) + I aip 0x15622ac3, // n0x086d c0x0055 (n0x0876-n0x0877) + I com 0x002d75c3, // n0x086e c0x0000 (---------------) + I edu 0x002099c3, // n0x086f c0x0000 (---------------) + I fie 0x0021e283, // n0x0870 c0x0000 (---------------) + I gov 0x00273c43, // n0x0871 c0x0000 (---------------) + I lib 0x0020b403, // n0x0872 c0x0000 (---------------) + I med 0x0021dcc3, // n0x0873 c0x0000 (---------------) + I org 0x0025f803, // n0x0874 c0x0000 (---------------) + I pri 0x00375bc4, // n0x0875 c0x0000 (---------------) + I riik 0x000e4188, // n0x0876 c0x0000 (---------------) + blogspot 0x15e22ac3, // n0x0877 c0x0057 (n0x0880-n0x0881) + I com 0x002d75c3, // n0x0878 c0x0000 (---------------) + I edu 0x00291c43, // n0x0879 c0x0000 (---------------) + I eun 0x0021e283, // n0x087a c0x0000 (---------------) + I gov 0x0023fa03, // n0x087b c0x0000 (---------------) + I mil 0x00298944, // n0x087c c0x0000 (---------------) + I name 0x002170c3, // n0x087d c0x0000 (---------------) + I net 0x0021dcc3, // n0x087e c0x0000 (---------------) + I org 0x00215583, // n0x087f c0x0000 (---------------) + I sci 0x000e4188, // n0x0880 c0x0000 (---------------) + blogspot 0x16622ac3, // n0x0881 c0x0059 (n0x0886-n0x0887) + I com 0x002d75c3, // n0x0882 c0x0000 (---------------) + I edu 0x0034eb03, // n0x0883 c0x0000 (---------------) + I gob 0x00207cc3, // n0x0884 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x0885 c0x0000 (---------------) + I org 0x000e4188, // n0x0886 c0x0000 (---------------) + blogspot 0x00310603, // n0x0887 c0x0000 (---------------) + I biz 0x00222ac3, // n0x0888 c0x0000 (---------------) + I com 0x002d75c3, // n0x0889 c0x0000 (---------------) + I edu 0x0021e283, // n0x088a c0x0000 (---------------) + I gov 0x00200304, // n0x088b c0x0000 (---------------) + I info 0x00298944, // n0x088c c0x0000 (---------------) + I name 0x002170c3, // n0x088d c0x0000 (---------------) + I net 0x0021dcc3, // n0x088e c0x0000 (---------------) + I org 0x002f85c5, // n0x088f c0x0000 (---------------) + I aland 0x000e4188, // n0x0890 c0x0000 (---------------) + blogspot 0x00006743, // n0x0891 c0x0000 (---------------) + iki 0x0036e608, // n0x0892 c0x0000 (---------------) + I aeroport 0x00383787, // n0x0893 c0x0000 (---------------) + I assedic 0x002729c4, // n0x0894 c0x0000 (---------------) + I asso 0x00310b86, // n0x0895 c0x0000 (---------------) + I avocat 0x0031e586, // n0x0896 c0x0000 (---------------) + I avoues 0x000e4188, // n0x0897 c0x0000 (---------------) + blogspot 0x0025f743, // n0x0898 c0x0000 (---------------) + I cci 0x003011c9, // n0x0899 c0x0000 (---------------) + I chambagri 0x00234bd5, // n0x089a c0x0000 (---------------) + I chirurgiens-dentistes 0x00222ac3, // n0x089b c0x0000 (---------------) + I com 0x0030c7d2, // n0x089c c0x0000 (---------------) + I experts-comptables 0x0030c58f, // n0x089d c0x0000 (---------------) + I geometre-expert 0x003579c4, // n0x089e c0x0000 (---------------) + I gouv 0x0020dc85, // n0x089f c0x0000 (---------------) + I greta 0x002de690, // n0x08a0 c0x0000 (---------------) + I huissier-justice 0x002753c7, // n0x08a1 c0x0000 (---------------) + I medecin 0x00207cc3, // n0x08a2 c0x0000 (---------------) + I nom 0x00265c08, // n0x08a3 c0x0000 (---------------) + I notaires 0x002e078a, // n0x08a4 c0x0000 (---------------) + I pharmacien 0x0021a444, // n0x08a5 c0x0000 (---------------) + I port 0x002ca783, // n0x08a6 c0x0000 (---------------) + I prd 0x0029abc6, // n0x08a7 c0x0000 (---------------) + I presse 0x00208902, // n0x08a8 c0x0000 (---------------) + I tm 0x0036b18b, // n0x08a9 c0x0000 (---------------) + I veterinaire 0x00222ac3, // n0x08aa c0x0000 (---------------) + I com 0x002d75c3, // n0x08ab c0x0000 (---------------) + I edu 0x0021e283, // n0x08ac c0x0000 (---------------) + I gov 0x0023fa03, // n0x08ad c0x0000 (---------------) + I mil 0x002170c3, // n0x08ae c0x0000 (---------------) + I net 0x0021dcc3, // n0x08af c0x0000 (---------------) + I org 0x002ce243, // n0x08b0 c0x0000 (---------------) + I pvt 0x00200742, // n0x08b1 c0x0000 (---------------) + I co 0x002170c3, // n0x08b2 c0x0000 (---------------) + I net 0x0021dcc3, // n0x08b3 c0x0000 (---------------) + I org 0x00222ac3, // n0x08b4 c0x0000 (---------------) + I com 0x002d75c3, // n0x08b5 c0x0000 (---------------) + I edu 0x0021e283, // n0x08b6 c0x0000 (---------------) + I gov 0x0023fa03, // n0x08b7 c0x0000 (---------------) + I mil 0x0021dcc3, // n0x08b8 c0x0000 (---------------) + I org 0x00222ac3, // n0x08b9 c0x0000 (---------------) + I com 0x002d75c3, // n0x08ba c0x0000 (---------------) + I edu 0x0021e283, // n0x08bb c0x0000 (---------------) + I gov 0x003413c3, // n0x08bc c0x0000 (---------------) + I ltd 0x00208483, // n0x08bd c0x0000 (---------------) + I mod 0x0021dcc3, // n0x08be c0x0000 (---------------) + I org 0x00200742, // n0x08bf c0x0000 (---------------) + I co 0x00222ac3, // n0x08c0 c0x0000 (---------------) + I com 0x002d75c3, // n0x08c1 c0x0000 (---------------) + I edu 0x002170c3, // n0x08c2 c0x0000 (---------------) + I net 0x0021dcc3, // n0x08c3 c0x0000 (---------------) + I org 0x00201e82, // n0x08c4 c0x0000 (---------------) + I ac 0x00222ac3, // n0x08c5 c0x0000 (---------------) + I com 0x002d75c3, // n0x08c6 c0x0000 (---------------) + I edu 0x0021e283, // n0x08c7 c0x0000 (---------------) + I gov 0x002170c3, // n0x08c8 c0x0000 (---------------) + I net 0x0021dcc3, // n0x08c9 c0x0000 (---------------) + I org 0x002729c4, // n0x08ca c0x0000 (---------------) + I asso 0x00222ac3, // n0x08cb c0x0000 (---------------) + I com 0x002d75c3, // n0x08cc c0x0000 (---------------) + I edu 0x00203604, // n0x08cd c0x0000 (---------------) + I mobi 0x002170c3, // n0x08ce c0x0000 (---------------) + I net 0x0021dcc3, // n0x08cf c0x0000 (---------------) + I org 0x000e4188, // n0x08d0 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x08d1 c0x0000 (---------------) + I com 0x002d75c3, // n0x08d2 c0x0000 (---------------) + I edu 0x0021e283, // n0x08d3 c0x0000 (---------------) + I gov 0x002170c3, // n0x08d4 c0x0000 (---------------) + I net 0x0021dcc3, // n0x08d5 c0x0000 (---------------) + I org 0x00222ac3, // n0x08d6 c0x0000 (---------------) + I com 0x002d75c3, // n0x08d7 c0x0000 (---------------) + I edu 0x0034eb03, // n0x08d8 c0x0000 (---------------) + I gob 0x00215703, // n0x08d9 c0x0000 (---------------) + I ind 0x0023fa03, // n0x08da c0x0000 (---------------) + I mil 0x002170c3, // n0x08db c0x0000 (---------------) + I net 0x0021dcc3, // n0x08dc c0x0000 (---------------) + I org 0x00200742, // n0x08dd c0x0000 (---------------) + I co 0x00222ac3, // n0x08de c0x0000 (---------------) + I com 0x002170c3, // n0x08df c0x0000 (---------------) + I net 0x000e4188, // n0x08e0 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x08e1 c0x0000 (---------------) + I com 0x002d75c3, // n0x08e2 c0x0000 (---------------) + I edu 0x0021e283, // n0x08e3 c0x0000 (---------------) + I gov 0x00300b83, // n0x08e4 c0x0000 (---------------) + I idv 0x00051e43, // n0x08e5 c0x0000 (---------------) + inc 0x001413c3, // n0x08e6 c0x0000 (---------------) + ltd 0x002170c3, // n0x08e7 c0x0000 (---------------) + I net 0x0021dcc3, // n0x08e8 c0x0000 (---------------) + I org 0x002ea10a, // n0x08e9 c0x0000 (---------------) + I xn--55qx5d 0x00306ac9, // n0x08ea c0x0000 (---------------) + I xn--ciqpn 0x0032788b, // n0x08eb c0x0000 (---------------) + I xn--gmq050i 0x00327f0a, // n0x08ec c0x0000 (---------------) + I xn--gmqw5a 0x0033080a, // n0x08ed c0x0000 (---------------) + I xn--io0a7i 0x0033f6cb, // n0x08ee c0x0000 (---------------) + I xn--lcvr32d 0x00356c8a, // n0x08ef c0x0000 (---------------) + I xn--mk0axi 0x0035c6ca, // n0x08f0 c0x0000 (---------------) + I xn--mxtq1m 0x0036394a, // n0x08f1 c0x0000 (---------------) + I xn--od0alg 0x00363bcb, // n0x08f2 c0x0000 (---------------) + I xn--od0aq3b 0x00384789, // n0x08f3 c0x0000 (---------------) + I xn--tn0ag 0x003867ca, // n0x08f4 c0x0000 (---------------) + I xn--uc0atv 0x00386c4b, // n0x08f5 c0x0000 (---------------) + I xn--uc0ay4a 0x0039008b, // n0x08f6 c0x0000 (---------------) + I xn--wcvs22d 0x0039634a, // n0x08f7 c0x0000 (---------------) + I xn--zf0avx 0x00222ac3, // n0x08f8 c0x0000 (---------------) + I com 0x002d75c3, // n0x08f9 c0x0000 (---------------) + I edu 0x0034eb03, // n0x08fa c0x0000 (---------------) + I gob 0x0023fa03, // n0x08fb c0x0000 (---------------) + I mil 0x002170c3, // n0x08fc c0x0000 (---------------) + I net 0x0021dcc3, // n0x08fd c0x0000 (---------------) + I org 0x000e4188, // n0x08fe c0x0000 (---------------) + blogspot 0x00222ac3, // n0x08ff c0x0000 (---------------) + I com 0x0024d404, // n0x0900 c0x0000 (---------------) + I from 0x00209782, // n0x0901 c0x0000 (---------------) + I iz 0x00298944, // n0x0902 c0x0000 (---------------) + I name 0x0036b745, // n0x0903 c0x0000 (---------------) + I adult 0x00200603, // n0x0904 c0x0000 (---------------) + I art 0x002729c4, // n0x0905 c0x0000 (---------------) + I asso 0x00222ac3, // n0x0906 c0x0000 (---------------) + I com 0x00228d44, // n0x0907 c0x0000 (---------------) + I coop 0x002d75c3, // n0x0908 c0x0000 (---------------) + I edu 0x00238544, // n0x0909 c0x0000 (---------------) + I firm 0x003579c4, // n0x090a c0x0000 (---------------) + I gouv 0x00200304, // n0x090b c0x0000 (---------------) + I info 0x0020b403, // n0x090c c0x0000 (---------------) + I med 0x002170c3, // n0x090d c0x0000 (---------------) + I net 0x0021dcc3, // n0x090e c0x0000 (---------------) + I org 0x0028acc5, // n0x090f c0x0000 (---------------) + I perso 0x00218943, // n0x0910 c0x0000 (---------------) + I pol 0x00218243, // n0x0911 c0x0000 (---------------) + I pro 0x00241283, // n0x0912 c0x0000 (---------------) + I rel 0x0029b184, // n0x0913 c0x0000 (---------------) + I shop 0x0036f244, // n0x0914 c0x0000 (---------------) + I 2000 0x00256e45, // n0x0915 c0x0000 (---------------) + I agrar 0x000e4188, // n0x0916 c0x0000 (---------------) + blogspot 0x002de404, // n0x0917 c0x0000 (---------------) + I bolt 0x002112c6, // n0x0918 c0x0000 (---------------) + I casino 0x002735c4, // n0x0919 c0x0000 (---------------) + I city 0x00200742, // n0x091a c0x0000 (---------------) + I co 0x003128c7, // n0x091b c0x0000 (---------------) + I erotica 0x0023a507, // n0x091c c0x0000 (---------------) + I erotika 0x00356104, // n0x091d c0x0000 (---------------) + I film 0x00246b45, // n0x091e c0x0000 (---------------) + I forum 0x002d2145, // n0x091f c0x0000 (---------------) + I games 0x00294945, // n0x0920 c0x0000 (---------------) + I hotel 0x00200304, // n0x0921 c0x0000 (---------------) + I info 0x0032d888, // n0x0922 c0x0000 (---------------) + I ingatlan 0x00207486, // n0x0923 c0x0000 (---------------) + I jogasz 0x002c1d48, // n0x0924 c0x0000 (---------------) + I konyvelo 0x0023b745, // n0x0925 c0x0000 (---------------) + I lakas 0x002dc385, // n0x0926 c0x0000 (---------------) + I media 0x00366d44, // n0x0927 c0x0000 (---------------) + I news 0x0021dcc3, // n0x0928 c0x0000 (---------------) + I org 0x002cba44, // n0x0929 c0x0000 (---------------) + I priv 0x0033de86, // n0x092a c0x0000 (---------------) + I reklam 0x0029acc3, // n0x092b c0x0000 (---------------) + I sex 0x0029b184, // n0x092c c0x0000 (---------------) + I shop 0x0027cac5, // n0x092d c0x0000 (---------------) + I sport 0x00278704, // n0x092e c0x0000 (---------------) + I suli 0x0020bac4, // n0x092f c0x0000 (---------------) + I szex 0x00208902, // n0x0930 c0x0000 (---------------) + I tm 0x0024f786, // n0x0931 c0x0000 (---------------) + I tozsde 0x0037a486, // n0x0932 c0x0000 (---------------) + I utazas 0x002db9c5, // n0x0933 c0x0000 (---------------) + I video 0x00201e82, // n0x0934 c0x0000 (---------------) + I ac 0x00310603, // n0x0935 c0x0000 (---------------) + I biz 0x1b600742, // n0x0936 c0x006d (n0x093f-n0x0940) + I co 0x00227544, // n0x0937 c0x0000 (---------------) + I desa 0x00202342, // n0x0938 c0x0000 (---------------) + I go 0x0023fa03, // n0x0939 c0x0000 (---------------) + I mil 0x00220282, // n0x093a c0x0000 (---------------) + I my 0x002170c3, // n0x093b c0x0000 (---------------) + I net 0x00200c42, // n0x093c c0x0000 (---------------) + I or 0x00206103, // n0x093d c0x0000 (---------------) + I sch 0x00219fc3, // n0x093e c0x0000 (---------------) + I web 0x000e4188, // n0x093f c0x0000 (---------------) + blogspot 0x000e4188, // n0x0940 c0x0000 (---------------) + blogspot 0x0021e283, // n0x0941 c0x0000 (---------------) + I gov 0x1c200742, // n0x0942 c0x0070 (n0x0943-n0x0944) o I co 0x000e4188, // n0x0943 c0x0000 (---------------) + blogspot 0x00201e82, // n0x0944 c0x0000 (---------------) + I ac 0x1ca00742, // n0x0945 c0x0072 (n0x094b-n0x094d) + I co 0x00222ac3, // n0x0946 c0x0000 (---------------) + I com 0x002170c3, // n0x0947 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0948 c0x0000 (---------------) + I org 0x00206582, // n0x0949 c0x0000 (---------------) + I tt 0x0020bf42, // n0x094a c0x0000 (---------------) + I tv 0x003413c3, // n0x094b c0x0000 (---------------) + I ltd 0x002c65c3, // n0x094c c0x0000 (---------------) + I plc 0x00201e82, // n0x094d c0x0000 (---------------) + I ac 0x000e4188, // n0x094e c0x0000 (---------------) + blogspot 0x00200742, // n0x094f c0x0000 (---------------) + I co 0x002d75c3, // n0x0950 c0x0000 (---------------) + I edu 0x00238544, // n0x0951 c0x0000 (---------------) + I firm 0x002012c3, // n0x0952 c0x0000 (---------------) + I gen 0x0021e283, // n0x0953 c0x0000 (---------------) + I gov 0x00215703, // n0x0954 c0x0000 (---------------) + I ind 0x0023fa03, // n0x0955 c0x0000 (---------------) + I mil 0x002170c3, // n0x0956 c0x0000 (---------------) + I net 0x0020e3c3, // n0x0957 c0x0000 (---------------) + I nic 0x0021dcc3, // n0x0958 c0x0000 (---------------) + I org 0x00215503, // n0x0959 c0x0000 (---------------) + I res 0x000f7e53, // n0x095a c0x0000 (---------------) + barrel-of-knowledge 0x00104094, // n0x095b c0x0000 (---------------) + barrell-of-knowledge 0x00009ac6, // n0x095c c0x0000 (---------------) + dyndns 0x00042187, // n0x095d c0x0000 (---------------) + for-our 0x000f8fc9, // n0x095e c0x0000 (---------------) + groks-the 0x0009b5ca, // n0x095f c0x0000 (---------------) + groks-this 0x0007690d, // n0x0960 c0x0000 (---------------) + here-for-more 0x0009bfca, // n0x0961 c0x0000 (---------------) + knowsitall 0x00130f46, // n0x0962 c0x0000 (---------------) + selfip 0x00110e86, // n0x0963 c0x0000 (---------------) + webhop 0x0021d5c2, // n0x0964 c0x0000 (---------------) + I eu 0x00222ac3, // n0x0965 c0x0000 (---------------) + I com 0x000b53c6, // n0x0966 c0x0000 (---------------) + github 0x000f9303, // n0x0967 c0x0000 (---------------) + nid 0x00222ac3, // n0x0968 c0x0000 (---------------) + I com 0x002d75c3, // n0x0969 c0x0000 (---------------) + I edu 0x0021e283, // n0x096a c0x0000 (---------------) + I gov 0x0023fa03, // n0x096b c0x0000 (---------------) + I mil 0x002170c3, // n0x096c c0x0000 (---------------) + I net 0x0021dcc3, // n0x096d c0x0000 (---------------) + I org 0x00201e82, // n0x096e c0x0000 (---------------) + I ac 0x00200742, // n0x096f c0x0000 (---------------) + I co 0x0021e283, // n0x0970 c0x0000 (---------------) + I gov 0x00206202, // n0x0971 c0x0000 (---------------) + I id 0x002170c3, // n0x0972 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0973 c0x0000 (---------------) + I org 0x00206103, // n0x0974 c0x0000 (---------------) + I sch 0x0034a88f, // n0x0975 c0x0000 (---------------) + I xn--mgba3a4f16a 0x0034ac4e, // n0x0976 c0x0000 (---------------) + I xn--mgba3a4fra 0x000e4188, // n0x0977 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x0978 c0x0000 (---------------) + I com 0x000356c7, // n0x0979 c0x0000 (---------------) + cupcake 0x002d75c3, // n0x097a c0x0000 (---------------) + I edu 0x0021e283, // n0x097b c0x0000 (---------------) + I gov 0x00238c03, // n0x097c c0x0000 (---------------) + I int 0x002170c3, // n0x097d c0x0000 (---------------) + I net 0x0021dcc3, // n0x097e c0x0000 (---------------) + I org 0x00214a43, // n0x097f c0x0000 (---------------) + I abr 0x0038b8c7, // n0x0980 c0x0000 (---------------) + I abruzzo 0x002015c2, // n0x0981 c0x0000 (---------------) + I ag 0x00384949, // n0x0982 c0x0000 (---------------) + I agrigento 0x00200882, // n0x0983 c0x0000 (---------------) + I al 0x0022f94b, // n0x0984 c0x0000 (---------------) + I alessandria 0x002d344a, // n0x0985 c0x0000 (---------------) + I alto-adige 0x002c0d89, // n0x0986 c0x0000 (---------------) + I altoadige 0x00201242, // n0x0987 c0x0000 (---------------) + I an 0x00295b46, // n0x0988 c0x0000 (---------------) + I ancona 0x00264b95, // n0x0989 c0x0000 (---------------) + I andria-barletta-trani 0x0022fa95, // n0x098a c0x0000 (---------------) + I andria-trani-barletta 0x0026bc93, // n0x098b c0x0000 (---------------) + I andriabarlettatrani 0x00230013, // n0x098c c0x0000 (---------------) + I andriatranibarletta 0x0020fd82, // n0x098d c0x0000 (---------------) + I ao 0x00218745, // n0x098e c0x0000 (---------------) + I aosta 0x00341e0c, // n0x098f c0x0000 (---------------) + I aosta-valley 0x0029a44b, // n0x0990 c0x0000 (---------------) + I aostavalley 0x00258685, // n0x0991 c0x0000 (---------------) + I aoste 0x002105c2, // n0x0992 c0x0000 (---------------) + I ap 0x00273fc2, // n0x0993 c0x0000 (---------------) + I aq 0x002d7986, // n0x0994 c0x0000 (---------------) + I aquila 0x00200602, // n0x0995 c0x0000 (---------------) + I ar 0x00363106, // n0x0996 c0x0000 (---------------) + I arezzo 0x0020094d, // n0x0997 c0x0000 (---------------) + I ascoli-piceno 0x0034714c, // n0x0998 c0x0000 (---------------) + I ascolipiceno 0x002166c4, // n0x0999 c0x0000 (---------------) + I asti 0x00201642, // n0x099a c0x0000 (---------------) + I at 0x00201482, // n0x099b c0x0000 (---------------) + I av 0x00369f48, // n0x099c c0x0000 (---------------) + I avellino 0x00205a82, // n0x099d c0x0000 (---------------) + I ba 0x00240186, // n0x099e c0x0000 (---------------) + I balsan 0x0027eb84, // n0x099f c0x0000 (---------------) + I bari 0x00264d55, // n0x09a0 c0x0000 (---------------) + I barletta-trani-andria 0x0026be13, // n0x09a1 c0x0000 (---------------) + I barlettatraniandria 0x0020a443, // n0x09a2 c0x0000 (---------------) + I bas 0x0030d98a, // n0x09a3 c0x0000 (---------------) + I basilicata 0x002c5dc7, // n0x09a4 c0x0000 (---------------) + I belluno 0x0030fa49, // n0x09a5 c0x0000 (---------------) + I benevento 0x0023dc87, // n0x09a6 c0x0000 (---------------) + I bergamo 0x00355e02, // n0x09a7 c0x0000 (---------------) + I bg 0x00200002, // n0x09a8 c0x0000 (---------------) + I bi 0x00381ac6, // n0x09a9 c0x0000 (---------------) + I biella 0x00205842, // n0x09aa c0x0000 (---------------) + I bl 0x000e4188, // n0x09ab c0x0000 (---------------) + blogspot 0x0020a282, // n0x09ac c0x0000 (---------------) + I bn 0x0020a702, // n0x09ad c0x0000 (---------------) + I bo 0x0034c987, // n0x09ae c0x0000 (---------------) + I bologna 0x00391387, // n0x09af c0x0000 (---------------) + I bolzano 0x00212b85, // n0x09b0 c0x0000 (---------------) + I bozen 0x00212e82, // n0x09b1 c0x0000 (---------------) + I br 0x002154c7, // n0x09b2 c0x0000 (---------------) + I brescia 0x00215688, // n0x09b3 c0x0000 (---------------) + I brindisi 0x00235102, // n0x09b4 c0x0000 (---------------) + I bs 0x00216fc2, // n0x09b5 c0x0000 (---------------) + I bt 0x002203c2, // n0x09b6 c0x0000 (---------------) + I bz 0x002055c2, // n0x09b7 c0x0000 (---------------) + I ca 0x00250c08, // n0x09b8 c0x0000 (---------------) + I cagliari 0x0020e443, // n0x09b9 c0x0000 (---------------) + I cal 0x00238348, // n0x09ba c0x0000 (---------------) + I calabria 0x002e718d, // n0x09bb c0x0000 (---------------) + I caltanissetta 0x0021a083, // n0x09bc c0x0000 (---------------) + I cam 0x00300748, // n0x09bd c0x0000 (---------------) + I campania 0x0022c60f, // n0x09be c0x0000 (---------------) + I campidano-medio 0x0022c9ce, // n0x09bf c0x0000 (---------------) + I campidanomedio 0x0027284a, // n0x09c0 c0x0000 (---------------) + I campobasso 0x002d4e91, // n0x09c1 c0x0000 (---------------) + I carbonia-iglesias 0x002d5310, // n0x09c2 c0x0000 (---------------) + I carboniaiglesias 0x0031888d, // n0x09c3 c0x0000 (---------------) + I carrara-massa 0x00318bcc, // n0x09c4 c0x0000 (---------------) + I carraramassa 0x002055c7, // n0x09c5 c0x0000 (---------------) + I caserta 0x0030db07, // n0x09c6 c0x0000 (---------------) + I catania 0x00310c49, // n0x09c7 c0x0000 (---------------) + I catanzaro 0x002167c2, // n0x09c8 c0x0000 (---------------) + I cb 0x00200b82, // n0x09c9 c0x0000 (---------------) + I ce 0x0024434c, // n0x09ca c0x0000 (---------------) + I cesena-forli 0x0024464b, // n0x09cb c0x0000 (---------------) + I cesenaforli 0x00204a02, // n0x09cc c0x0000 (---------------) + I ch 0x002c2546, // n0x09cd c0x0000 (---------------) + I chieti 0x002155c2, // n0x09ce c0x0000 (---------------) + I ci 0x0020af42, // n0x09cf c0x0000 (---------------) + I cl 0x002211c2, // n0x09d0 c0x0000 (---------------) + I cn 0x00200742, // n0x09d1 c0x0000 (---------------) + I co 0x002230c4, // n0x09d2 c0x0000 (---------------) + I como 0x0022bdc7, // n0x09d3 c0x0000 (---------------) + I cosenza 0x0020c502, // n0x09d4 c0x0000 (---------------) + I cr 0x00230b87, // n0x09d5 c0x0000 (---------------) + I cremona 0x00231e07, // n0x09d6 c0x0000 (---------------) + I crotone 0x0020f142, // n0x09d7 c0x0000 (---------------) + I cs 0x00223d82, // n0x09d8 c0x0000 (---------------) + I ct 0x00235585, // n0x09d9 c0x0000 (---------------) + I cuneo 0x00214442, // n0x09da c0x0000 (---------------) + I cz 0x002e990e, // n0x09db c0x0000 (---------------) + I dell-ogliastra 0x002297cd, // n0x09dc c0x0000 (---------------) + I dellogliastra 0x002d75c3, // n0x09dd c0x0000 (---------------) + I edu 0x0023f9ce, // n0x09de c0x0000 (---------------) + I emilia-romagna 0x00261dcd, // n0x09df c0x0000 (---------------) + I emiliaromagna 0x0034efc3, // n0x09e0 c0x0000 (---------------) + I emr 0x00200bc2, // n0x09e1 c0x0000 (---------------) + I en 0x00201504, // n0x09e2 c0x0000 (---------------) + I enna 0x00235d42, // n0x09e3 c0x0000 (---------------) + I fc 0x0020c742, // n0x09e4 c0x0000 (---------------) + I fe 0x002cc345, // n0x09e5 c0x0000 (---------------) + I fermo 0x002e3b87, // n0x09e6 c0x0000 (---------------) + I ferrara 0x00331442, // n0x09e7 c0x0000 (---------------) + I fg 0x002099c2, // n0x09e8 c0x0000 (---------------) + I fi 0x00237b87, // n0x09e9 c0x0000 (---------------) + I firenze 0x0023c248, // n0x09ea c0x0000 (---------------) + I florence 0x00358002, // n0x09eb c0x0000 (---------------) + I fm 0x00200386, // n0x09ec c0x0000 (---------------) + I foggia 0x002441cc, // n0x09ed c0x0000 (---------------) + I forli-cesena 0x0024450b, // n0x09ee c0x0000 (---------------) + I forlicesena 0x00200d42, // n0x09ef c0x0000 (---------------) + I fr 0x002495cf, // n0x09f0 c0x0000 (---------------) + I friuli-v-giulia 0x00249990, // n0x09f1 c0x0000 (---------------) + I friuli-ve-giulia 0x00249d8f, // n0x09f2 c0x0000 (---------------) + I friuli-vegiulia 0x0024a155, // n0x09f3 c0x0000 (---------------) + I friuli-venezia-giulia 0x0024a694, // n0x09f4 c0x0000 (---------------) + I friuli-veneziagiulia 0x0024ab8e, // n0x09f5 c0x0000 (---------------) + I friuli-vgiulia 0x0024af0e, // n0x09f6 c0x0000 (---------------) + I friuliv-giulia 0x0024b28f, // n0x09f7 c0x0000 (---------------) + I friulive-giulia 0x0024b64e, // n0x09f8 c0x0000 (---------------) + I friulivegiulia 0x0024b9d4, // n0x09f9 c0x0000 (---------------) + I friulivenezia-giulia 0x0024bed3, // n0x09fa c0x0000 (---------------) + I friuliveneziagiulia 0x0024c38d, // n0x09fb c0x0000 (---------------) + I friulivgiulia 0x00263bc9, // n0x09fc c0x0000 (---------------) + I frosinone 0x00277443, // n0x09fd c0x0000 (---------------) + I fvg 0x002012c2, // n0x09fe c0x0000 (---------------) + I ge 0x0030bb05, // n0x09ff c0x0000 (---------------) + I genoa 0x002012c6, // n0x0a00 c0x0000 (---------------) + I genova 0x00202342, // n0x0a01 c0x0000 (---------------) + I go 0x002473c7, // n0x0a02 c0x0000 (---------------) + I gorizia 0x0021e283, // n0x0a03 c0x0000 (---------------) + I gov 0x0020dc82, // n0x0a04 c0x0000 (---------------) + I gr 0x002e9508, // n0x0a05 c0x0000 (---------------) + I grosseto 0x002d50d1, // n0x0a06 c0x0000 (---------------) + I iglesias-carbonia 0x002d5510, // n0x0a07 c0x0000 (---------------) + I iglesiascarbonia 0x00203582, // n0x0a08 c0x0000 (---------------) + I im 0x002148c7, // n0x0a09 c0x0000 (---------------) + I imperia 0x00202b42, // n0x0a0a c0x0000 (---------------) + I is 0x002ee307, // n0x0a0b c0x0000 (---------------) + I isernia 0x002034c2, // n0x0a0c c0x0000 (---------------) + I kr 0x0036dc89, // n0x0a0d c0x0000 (---------------) + I la-spezia 0x002d7947, // n0x0a0e c0x0000 (---------------) + I laquila 0x00257b88, // n0x0a0f c0x0000 (---------------) + I laspezia 0x0035dc46, // n0x0a10 c0x0000 (---------------) + I latina 0x002c64c3, // n0x0a11 c0x0000 (---------------) + I laz 0x0035a705, // n0x0a12 c0x0000 (---------------) + I lazio 0x002339c2, // n0x0a13 c0x0000 (---------------) + I lc 0x00203c42, // n0x0a14 c0x0000 (---------------) + I le 0x00381ec5, // n0x0a15 c0x0000 (---------------) + I lecce 0x0021e6c5, // n0x0a16 c0x0000 (---------------) + I lecco 0x002008c2, // n0x0a17 c0x0000 (---------------) + I li 0x0021a583, // n0x0a18 c0x0000 (---------------) + I lig 0x00244887, // n0x0a19 c0x0000 (---------------) + I liguria 0x003436c7, // n0x0a1a c0x0000 (---------------) + I livorno 0x00205882, // n0x0a1b c0x0000 (---------------) + I lo 0x002455c4, // n0x0a1c c0x0000 (---------------) + I lodi 0x00260a43, // n0x0a1d c0x0000 (---------------) + I lom 0x002b0b49, // n0x0a1e c0x0000 (---------------) + I lombardia 0x002b8a88, // n0x0a1f c0x0000 (---------------) + I lombardy 0x00205ec2, // n0x0a20 c0x0000 (---------------) + I lt 0x002071c2, // n0x0a21 c0x0000 (---------------) + I lu 0x00219187, // n0x0a22 c0x0000 (---------------) + I lucania 0x0021aa05, // n0x0a23 c0x0000 (---------------) + I lucca 0x00300248, // n0x0a24 c0x0000 (---------------) + I macerata 0x0029c6c7, // n0x0a25 c0x0000 (---------------) + I mantova 0x00216503, // n0x0a26 c0x0000 (---------------) + I mar 0x0028de06, // n0x0a27 c0x0000 (---------------) + I marche 0x0031870d, // n0x0a28 c0x0000 (---------------) + I massa-carrara 0x00318a8c, // n0x0a29 c0x0000 (---------------) + I massacarrara 0x0029f6c6, // n0x0a2a c0x0000 (---------------) + I matera 0x00205942, // n0x0a2b c0x0000 (---------------) + I mb 0x0023a6c2, // n0x0a2c c0x0000 (---------------) + I mc 0x00208942, // n0x0a2d c0x0000 (---------------) + I me 0x0022c48f, // n0x0a2e c0x0000 (---------------) + I medio-campidano 0x0022c88e, // n0x0a2f c0x0000 (---------------) + I mediocampidano 0x00291407, // n0x0a30 c0x0000 (---------------) + I messina 0x00204802, // n0x0a31 c0x0000 (---------------) + I mi 0x002f1e85, // n0x0a32 c0x0000 (---------------) + I milan 0x002f1e86, // n0x0a33 c0x0000 (---------------) + I milano 0x00217082, // n0x0a34 c0x0000 (---------------) + I mn 0x00203602, // n0x0a35 c0x0000 (---------------) + I mo 0x00278386, // n0x0a36 c0x0000 (---------------) + I modena 0x00285643, // n0x0a37 c0x0000 (---------------) + I mol 0x002ee246, // n0x0a38 c0x0000 (---------------) + I molise 0x002b1e85, // n0x0a39 c0x0000 (---------------) + I monza 0x002b1e8d, // n0x0a3a c0x0000 (---------------) + I monza-brianza 0x002b26d5, // n0x0a3b c0x0000 (---------------) + I monza-e-della-brianza 0x002b2e8c, // n0x0a3c c0x0000 (---------------) + I monzabrianza 0x002b39cd, // n0x0a3d c0x0000 (---------------) + I monzaebrianza 0x002b3d92, // n0x0a3e c0x0000 (---------------) + I monzaedellabrianza 0x00209282, // n0x0a3f c0x0000 (---------------) + I ms 0x00259642, // n0x0a40 c0x0000 (---------------) + I mt 0x00200282, // n0x0a41 c0x0000 (---------------) + I na 0x002b7886, // n0x0a42 c0x0000 (---------------) + I naples 0x002d5c46, // n0x0a43 c0x0000 (---------------) + I napoli 0x00200c02, // n0x0a44 c0x0000 (---------------) + I no 0x00201346, // n0x0a45 c0x0000 (---------------) + I novara 0x00205bc2, // n0x0a46 c0x0000 (---------------) + I nu 0x00205bc5, // n0x0a47 c0x0000 (---------------) + I nuoro 0x002003c2, // n0x0a48 c0x0000 (---------------) + I og 0x002298c9, // n0x0a49 c0x0000 (---------------) + I ogliastra 0x0022840c, // n0x0a4a c0x0000 (---------------) + I olbia-tempio 0x0022874b, // n0x0a4b c0x0000 (---------------) + I olbiatempio 0x00200c42, // n0x0a4c c0x0000 (---------------) + I or 0x0023c688, // n0x0a4d c0x0000 (---------------) + I oristano 0x002031c2, // n0x0a4e c0x0000 (---------------) + I ot 0x002052c2, // n0x0a4f c0x0000 (---------------) + I pa 0x0029a206, // n0x0a50 c0x0000 (---------------) + I padova 0x0034f945, // n0x0a51 c0x0000 (---------------) + I padua 0x0021ce87, // n0x0a52 c0x0000 (---------------) + I palermo 0x003927c5, // n0x0a53 c0x0000 (---------------) + I parma 0x002c0705, // n0x0a54 c0x0000 (---------------) + I pavia 0x00203e02, // n0x0a55 c0x0000 (---------------) + I pc 0x0029b282, // n0x0a56 c0x0000 (---------------) + I pd 0x00214942, // n0x0a57 c0x0000 (---------------) + I pe 0x0026fa47, // n0x0a58 c0x0000 (---------------) + I perugia 0x0030758d, // n0x0a59 c0x0000 (---------------) + I pesaro-urbino 0x0030790c, // n0x0a5a c0x0000 (---------------) + I pesarourbino 0x00229107, // n0x0a5b c0x0000 (---------------) + I pescara 0x002bf182, // n0x0a5c c0x0000 (---------------) + I pg 0x00200b02, // n0x0a5d c0x0000 (---------------) + I pi 0x00207788, // n0x0a5e c0x0000 (---------------) + I piacenza 0x00261808, // n0x0a5f c0x0000 (---------------) + I piedmont 0x002c1308, // n0x0a60 c0x0000 (---------------) + I piemonte 0x002cd744, // n0x0a61 c0x0000 (---------------) + I pisa 0x002c41c7, // n0x0a62 c0x0000 (---------------) + I pistoia 0x002c7d43, // n0x0a63 c0x0000 (---------------) + I pmn 0x0023df82, // n0x0a64 c0x0000 (---------------) + I pn 0x00203f02, // n0x0a65 c0x0000 (---------------) + I po 0x002c9b49, // n0x0a66 c0x0000 (---------------) + I pordenone 0x00236a47, // n0x0a67 c0x0000 (---------------) + I potenza 0x00218242, // n0x0a68 c0x0000 (---------------) + I pr 0x00346185, // n0x0a69 c0x0000 (---------------) + I prato 0x00295982, // n0x0a6a c0x0000 (---------------) + I pt 0x00223542, // n0x0a6b c0x0000 (---------------) + I pu 0x0025cd83, // n0x0a6c c0x0000 (---------------) + I pug 0x0025cd86, // n0x0a6d c0x0000 (---------------) + I puglia 0x002ce242, // n0x0a6e c0x0000 (---------------) + I pv 0x002ce6c2, // n0x0a6f c0x0000 (---------------) + I pz 0x00201442, // n0x0a70 c0x0000 (---------------) + I ra 0x0038c106, // n0x0a71 c0x0000 (---------------) + I ragusa 0x00201447, // n0x0a72 c0x0000 (---------------) + I ravenna 0x00227b82, // n0x0a73 c0x0000 (---------------) + I rc 0x002030c2, // n0x0a74 c0x0000 (---------------) + I re 0x0023818f, // n0x0a75 c0x0000 (---------------) + I reggio-calabria 0x0023f80d, // n0x0a76 c0x0000 (---------------) + I reggio-emilia 0x0025df8e, // n0x0a77 c0x0000 (---------------) + I reggiocalabria 0x00261c4c, // n0x0a78 c0x0000 (---------------) + I reggioemilia 0x00204782, // n0x0a79 c0x0000 (---------------) + I rg 0x00202842, // n0x0a7a c0x0000 (---------------) + I ri 0x0021ba45, // n0x0a7b c0x0000 (---------------) + I rieti 0x002e79c6, // n0x0a7c c0x0000 (---------------) + I rimini 0x002194c2, // n0x0a7d c0x0000 (---------------) + I rm 0x00202182, // n0x0a7e c0x0000 (---------------) + I rn 0x00200d82, // n0x0a7f c0x0000 (---------------) + I ro 0x0023fb84, // n0x0a80 c0x0000 (---------------) + I roma 0x002e7004, // n0x0a81 c0x0000 (---------------) + I rome 0x002b1386, // n0x0a82 c0x0000 (---------------) + I rovigo 0x00201a02, // n0x0a83 c0x0000 (---------------) + I sa 0x002671c7, // n0x0a84 c0x0000 (---------------) + I salerno 0x00218483, // n0x0a85 c0x0000 (---------------) + I sar 0x0021c048, // n0x0a86 c0x0000 (---------------) + I sardegna 0x0021ca08, // n0x0a87 c0x0000 (---------------) + I sardinia 0x00369a07, // n0x0a88 c0x0000 (---------------) + I sassari 0x00232a46, // n0x0a89 c0x0000 (---------------) + I savona 0x00209182, // n0x0a8a c0x0000 (---------------) + I si 0x00215803, // n0x0a8b c0x0000 (---------------) + I sic 0x00215807, // n0x0a8c c0x0000 (---------------) + I sicilia 0x0026b646, // n0x0a8d c0x0000 (---------------) + I sicily 0x002b77c5, // n0x0a8e c0x0000 (---------------) + I siena 0x002d0d88, // n0x0a8f c0x0000 (---------------) + I siracusa 0x00201102, // n0x0a90 c0x0000 (---------------) + I so 0x0033ca87, // n0x0a91 c0x0000 (---------------) + I sondrio 0x002101c2, // n0x0a92 c0x0000 (---------------) + I sp 0x002ceec2, // n0x0a93 c0x0000 (---------------) + I sr 0x00211f02, // n0x0a94 c0x0000 (---------------) + I ss 0x002b5a09, // n0x0a95 c0x0000 (---------------) + I suedtirol 0x0021d0c2, // n0x0a96 c0x0000 (---------------) + I sv 0x00200142, // n0x0a97 c0x0000 (---------------) + I ta 0x00229383, // n0x0a98 c0x0000 (---------------) + I taa 0x0036ec87, // n0x0a99 c0x0000 (---------------) + I taranto 0x00203202, // n0x0a9a c0x0000 (---------------) + I te 0x0022858c, // n0x0a9b c0x0000 (---------------) + I tempio-olbia 0x0022888b, // n0x0a9c c0x0000 (---------------) + I tempioolbia 0x0029f746, // n0x0a9d c0x0000 (---------------) + I teramo 0x002f9245, // n0x0a9e c0x0000 (---------------) + I terni 0x0021d1c2, // n0x0a9f c0x0000 (---------------) + I tn 0x00201682, // n0x0aa0 c0x0000 (---------------) + I to 0x0029f3c6, // n0x0aa1 c0x0000 (---------------) + I torino 0x002520c3, // n0x0aa2 c0x0000 (---------------) + I tos 0x003096c7, // n0x0aa3 c0x0000 (---------------) + I toscana 0x00285142, // n0x0aa4 c0x0000 (---------------) + I tp 0x00202402, // n0x0aa5 c0x0000 (---------------) + I tr 0x00264a15, // n0x0aa6 c0x0000 (---------------) + I trani-andria-barletta 0x0022fc55, // n0x0aa7 c0x0000 (---------------) + I trani-barletta-andria 0x0026bb53, // n0x0aa8 c0x0000 (---------------) + I traniandriabarletta 0x00230193, // n0x0aa9 c0x0000 (---------------) + I tranibarlettaandria 0x0027cbc7, // n0x0aaa c0x0000 (---------------) + I trapani 0x0028cbc8, // n0x0aab c0x0000 (---------------) + I trentino 0x0028cbd0, // n0x0aac c0x0000 (---------------) + I trentino-a-adige 0x0029458f, // n0x0aad c0x0000 (---------------) + I trentino-aadige 0x002d3213, // n0x0aae c0x0000 (---------------) + I trentino-alto-adige 0x00306652, // n0x0aaf c0x0000 (---------------) + I trentino-altoadige 0x0033be90, // n0x0ab0 c0x0000 (---------------) + I trentino-s-tirol 0x0033ac8f, // n0x0ab1 c0x0000 (---------------) + I trentino-stirol 0x0038cd52, // n0x0ab2 c0x0000 (---------------) + I trentino-sud-tirol 0x002a4691, // n0x0ab3 c0x0000 (---------------) + I trentino-sudtirol 0x002acf53, // n0x0ab4 c0x0000 (---------------) + I trentino-sued-tirol 0x002b57d2, // n0x0ab5 c0x0000 (---------------) + I trentino-suedtirol 0x002bc54f, // n0x0ab6 c0x0000 (---------------) + I trentinoa-adige 0x002bd2ce, // n0x0ab7 c0x0000 (---------------) + I trentinoaadige 0x002dccd2, // n0x0ab8 c0x0000 (---------------) + I trentinoalto-adige 0x002c0b91, // n0x0ab9 c0x0000 (---------------) + I trentinoaltoadige 0x002cb48f, // n0x0aba c0x0000 (---------------) + I trentinos-tirol 0x002cc70e, // n0x0abb c0x0000 (---------------) + I trentinostirol 0x002cda91, // n0x0abc c0x0000 (---------------) + I trentinosud-tirol 0x002ce2d0, // n0x0abd c0x0000 (---------------) + I trentinosudtirol 0x002cea52, // n0x0abe c0x0000 (---------------) + I trentinosued-tirol 0x002dde91, // n0x0abf c0x0000 (---------------) + I trentinosuedtirol 0x002d0946, // n0x0ac0 c0x0000 (---------------) + I trento 0x002de4c7, // n0x0ac1 c0x0000 (---------------) + I treviso 0x00354007, // n0x0ac2 c0x0000 (---------------) + I trieste 0x00203a02, // n0x0ac3 c0x0000 (---------------) + I ts 0x002af6c5, // n0x0ac4 c0x0000 (---------------) + I turin 0x002d8c87, // n0x0ac5 c0x0000 (---------------) + I tuscany 0x0020bf42, // n0x0ac6 c0x0000 (---------------) + I tv 0x002070c2, // n0x0ac7 c0x0000 (---------------) + I ud 0x00319045, // n0x0ac8 c0x0000 (---------------) + I udine 0x00215fc3, // n0x0ac9 c0x0000 (---------------) + I umb 0x002570c6, // n0x0aca c0x0000 (---------------) + I umbria 0x0030774d, // n0x0acb c0x0000 (---------------) + I urbino-pesaro 0x00307a8c, // n0x0acc c0x0000 (---------------) + I urbinopesaro 0x002013c2, // n0x0acd c0x0000 (---------------) + I va 0x00341c8b, // n0x0ace c0x0000 (---------------) + I val-d-aosta 0x0029a30a, // n0x0acf c0x0000 (---------------) + I val-daosta 0x0030ae0a, // n0x0ad0 c0x0000 (---------------) + I vald-aosta 0x0029e789, // n0x0ad1 c0x0000 (---------------) + I valdaosta 0x0029c80b, // n0x0ad2 c0x0000 (---------------) + I valle-aosta 0x002c904d, // n0x0ad3 c0x0000 (---------------) + I valle-d-aosta 0x002d958c, // n0x0ad4 c0x0000 (---------------) + I valle-daosta 0x0021860a, // n0x0ad5 c0x0000 (---------------) + I valleaosta 0x00244e8c, // n0x0ad6 c0x0000 (---------------) + I valled-aosta 0x0024cc8b, // n0x0ad7 c0x0000 (---------------) + I valledaosta 0x002584cc, // n0x0ad8 c0x0000 (---------------) + I vallee-aoste 0x0025be8b, // n0x0ad9 c0x0000 (---------------) + I valleeaoste 0x00263943, // n0x0ada c0x0000 (---------------) + I vao 0x00278f86, // n0x0adb c0x0000 (---------------) + I varese 0x0030b742, // n0x0adc c0x0000 (---------------) + I vb 0x0034a542, // n0x0add c0x0000 (---------------) + I vc 0x00211603, // n0x0ade c0x0000 (---------------) + I vda 0x002014c2, // n0x0adf c0x0000 (---------------) + I ve 0x002014c3, // n0x0ae0 c0x0000 (---------------) + I ven 0x003546c6, // n0x0ae1 c0x0000 (---------------) + I veneto 0x0024a307, // n0x0ae2 c0x0000 (---------------) + I venezia 0x0025c506, // n0x0ae3 c0x0000 (---------------) + I venice 0x00220fc8, // n0x0ae4 c0x0000 (---------------) + I verbania 0x002a5e88, // n0x0ae5 c0x0000 (---------------) + I vercelli 0x00248346, // n0x0ae6 c0x0000 (---------------) + I verona 0x00213602, // n0x0ae7 c0x0000 (---------------) + I vi 0x002db38d, // n0x0ae8 c0x0000 (---------------) + I vibo-valentia 0x002db6cc, // n0x0ae9 c0x0000 (---------------) + I vibovalentia 0x00357a87, // n0x0aea c0x0000 (---------------) + I vicenza 0x002de2c7, // n0x0aeb c0x0000 (---------------) + I viterbo 0x00211782, // n0x0aec c0x0000 (---------------) + I vr 0x0020bf82, // n0x0aed c0x0000 (---------------) + I vs 0x0021e302, // n0x0aee c0x0000 (---------------) + I vt 0x0024ebc2, // n0x0aef c0x0000 (---------------) + I vv 0x00200742, // n0x0af0 c0x0000 (---------------) + I co 0x002170c3, // n0x0af1 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0af2 c0x0000 (---------------) + I org 0x00222ac3, // n0x0af3 c0x0000 (---------------) + I com 0x002d75c3, // n0x0af4 c0x0000 (---------------) + I edu 0x0021e283, // n0x0af5 c0x0000 (---------------) + I gov 0x0023fa03, // n0x0af6 c0x0000 (---------------) + I mil 0x00298944, // n0x0af7 c0x0000 (---------------) + I name 0x002170c3, // n0x0af8 c0x0000 (---------------) + I net 0x0021dcc3, // n0x0af9 c0x0000 (---------------) + I org 0x00206103, // n0x0afa c0x0000 (---------------) + I sch 0x00201e82, // n0x0afb c0x0000 (---------------) + I ac 0x00210a02, // n0x0afc c0x0000 (---------------) + I ad 0x1fa34b45, // n0x0afd c0x007e (n0x0b6a-n0x0b9e) + I aichi 0x1fe06e05, // n0x0afe c0x007f (n0x0b9e-n0x0bba) + I akita 0x20387ac6, // n0x0aff c0x0080 (n0x0bba-n0x0bd0) + I aomori 0x000e4188, // n0x0b00 c0x0000 (---------------) + blogspot 0x206a0745, // n0x0b01 c0x0081 (n0x0bd0-n0x0c0a) + I chiba 0x00200742, // n0x0b02 c0x0000 (---------------) + I co 0x00203fc2, // n0x0b03 c0x0000 (---------------) + I ed 0x20b1c945, // n0x0b04 c0x0082 (n0x0c0a-n0x0c20) + I ehime 0x20e6b7c5, // n0x0b05 c0x0083 (n0x0c20-n0x0c2f) + I fukui 0x2126c587, // n0x0b06 c0x0084 (n0x0c2f-n0x0c6e) + I fukuoka 0x2166d5c9, // n0x0b07 c0x0085 (n0x0c6e-n0x0ca1) + I fukushima 0x21a89804, // n0x0b08 c0x0086 (n0x0ca1-n0x0cc7) + I gifu 0x00202342, // n0x0b09 c0x0000 (---------------) + I go 0x0020dc82, // n0x0b0a c0x0000 (---------------) + I gr 0x21e36f85, // n0x0b0b c0x0087 (n0x0cc7-n0x0ceb) + I gunma 0x2227c649, // n0x0b0c c0x0088 (n0x0ceb-n0x0d04) + I hiroshima 0x2275fc48, // n0x0b0d c0x0089 (n0x0d04-n0x0d92) + I hokkaido 0x22a96e45, // n0x0b0e c0x008a (n0x0d92-n0x0dc0) + I hyogo 0x22f16ac7, // n0x0b0f c0x008b (n0x0dc0-n0x0df3) + I ibaraki 0x23214e48, // n0x0b10 c0x008c (n0x0df3-n0x0e06) + I ishikawa 0x236c3b85, // n0x0b11 c0x008d (n0x0e06-n0x0e28) + I iwate 0x23a81f06, // n0x0b12 c0x008e (n0x0e28-n0x0e37) + I kagawa 0x23e71789, // n0x0b13 c0x008f (n0x0e37-n0x0e4b) + I kagoshima 0x24332808, // n0x0b14 c0x0090 (n0x0e4b-n0x0e69) + I kanagawa 0x246a8748, // n0x0b15 c0x0091 (n0x0e69-n0x0e6a)* o I kawasaki 0x24a8294a, // n0x0b16 c0x0092 (n0x0e6a-n0x0e6b)* o I kitakyushu 0x24e43484, // n0x0b17 c0x0093 (n0x0e6b-n0x0e6c)* o I kobe 0x252ba445, // n0x0b18 c0x0094 (n0x0e6c-n0x0e8b) + I kochi 0x256a2d48, // n0x0b19 c0x0095 (n0x0e8b-n0x0ea5) + I kumamoto 0x25aacb05, // n0x0b1a c0x0096 (n0x0ea5-n0x0ec4) + I kyoto 0x0020e4c2, // n0x0b1b c0x0000 (---------------) + I lg 0x25e28143, // n0x0b1c c0x0097 (n0x0ec4-n0x0ee2) + I mie 0x2628d746, // n0x0b1d c0x0098 (n0x0ee2-n0x0f03) + I miyagi 0x26771208, // n0x0b1e c0x0099 (n0x0f03-n0x0f1e) + I miyazaki 0x26b4e4c6, // n0x0b1f c0x009a (n0x0f1e-n0x0f69) + I nagano 0x26f6c108, // n0x0b20 c0x009b (n0x0f69-n0x0f7f) + I nagasaki 0x2732b206, // n0x0b21 c0x009c (n0x0f7f-n0x0f80)* o I nagoya 0x276da0c4, // n0x0b22 c0x009d (n0x0f80-n0x0fa6) + I nara 0x00201082, // n0x0b23 c0x0000 (---------------) + I ne 0x27a5f907, // n0x0b24 c0x009e (n0x0fa6-n0x0fc8) + I niigata 0x27e98d04, // n0x0b25 c0x009f (n0x0fc8-n0x0fdb) + I oita 0x28266607, // n0x0b26 c0x00a0 (n0x0fdb-n0x0ff5) + I okayama 0x287954c7, // n0x0b27 c0x00a1 (n0x0ff5-n0x101f) + I okinawa 0x00200c42, // n0x0b28 c0x0000 (---------------) + I or 0x28a864c5, // n0x0b29 c0x00a2 (n0x101f-n0x1051) + I osaka 0x28e75104, // n0x0b2a c0x00a3 (n0x1051-n0x106b) + I saga 0x292d0f07, // n0x0b2b c0x00a4 (n0x106b-n0x10b0) + I saitama 0x296129c7, // n0x0b2c c0x00a5 (n0x10b0-n0x10b1)* o I sapporo 0x29a6f286, // n0x0b2d c0x00a6 (n0x10b1-n0x10b2)* o I sendai 0x29e525c5, // n0x0b2e c0x00a7 (n0x10b2-n0x10c9) + I shiga 0x2a281087, // n0x0b2f c0x00a8 (n0x10c9-n0x10e0) + I shimane 0x2a6b4b88, // n0x0b30 c0x00a9 (n0x10e0-n0x1104) + I shizuoka 0x2ab0f5c7, // n0x0b31 c0x00aa (n0x1104-n0x1123) + I tochigi 0x2ae8e2c9, // n0x0b32 c0x00ab (n0x1123-n0x1134) + I tokushima 0x2b316545, // n0x0b33 c0x00ac (n0x1134-n0x116d) + I tokyo 0x2b6e2787, // n0x0b34 c0x00ad (n0x116d-n0x117a) + I tottori 0x2ba7c346, // n0x0b35 c0x00ae (n0x117a-n0x1192) + I toyama 0x2bf2dc48, // n0x0b36 c0x00af (n0x1192-n0x11af) + I wakayama 0x0022528d, // n0x0b37 c0x0000 (---------------) + I xn--0trq7p7nn 0x00260809, // n0x0b38 c0x0000 (---------------) + I xn--1ctwo 0x0026d84b, // n0x0b39 c0x0000 (---------------) + I xn--1lqs03n 0x002910cb, // n0x0b3a c0x0000 (---------------) + I xn--1lqs71d 0x002b1bcb, // n0x0b3b c0x0000 (---------------) + I xn--2m4a15e 0x002d6b8b, // n0x0b3c c0x0000 (---------------) + I xn--32vp30h 0x002e7bcb, // n0x0b3d c0x0000 (---------------) + I xn--4it168d 0x002e7e8b, // n0x0b3e c0x0000 (---------------) + I xn--4it797k 0x002e8689, // n0x0b3f c0x0000 (---------------) + I xn--4pvxs 0x002ea38b, // n0x0b40 c0x0000 (---------------) + I xn--5js045d 0x002ea64b, // n0x0b41 c0x0000 (---------------) + I xn--5rtp49c 0x002ead0b, // n0x0b42 c0x0000 (---------------) + I xn--5rtq34k 0x002eb3ca, // n0x0b43 c0x0000 (---------------) + I xn--6btw5a 0x002eb90a, // n0x0b44 c0x0000 (---------------) + I xn--6orx2r 0x002ebf0c, // n0x0b45 c0x0000 (---------------) + I xn--7t0a264c 0x002f16cb, // n0x0b46 c0x0000 (---------------) + I xn--8ltr62k 0x002f200a, // n0x0b47 c0x0000 (---------------) + I xn--8pvr4u 0x0030374a, // n0x0b48 c0x0000 (---------------) + I xn--c3s14m 0x0031334e, // n0x0b49 c0x0000 (---------------) + I xn--d5qv7z876c 0x00313d4e, // n0x0b4a c0x0000 (---------------) + I xn--djrs72d6uy 0x003140ca, // n0x0b4b c0x0000 (---------------) + I xn--djty4k 0x003153ca, // n0x0b4c c0x0000 (---------------) + I xn--efvn9s 0x0031700b, // n0x0b4d c0x0000 (---------------) + I xn--ehqz56n 0x003172cb, // n0x0b4e c0x0000 (---------------) + I xn--elqq16h 0x00317fcb, // n0x0b4f c0x0000 (---------------) + I xn--f6qx53a 0x00333bcb, // n0x0b50 c0x0000 (---------------) + I xn--k7yn95e 0x003341ca, // n0x0b51 c0x0000 (---------------) + I xn--kbrq7o 0x00334e8b, // n0x0b52 c0x0000 (---------------) + I xn--klt787d 0x0033514a, // n0x0b53 c0x0000 (---------------) + I xn--kltp7d 0x003353ca, // n0x0b54 c0x0000 (---------------) + I xn--kltx9a 0x0033564a, // n0x0b55 c0x0000 (---------------) + I xn--klty5x 0x00357c4b, // n0x0b56 c0x0000 (---------------) + I xn--mkru45i 0x0035d08b, // n0x0b57 c0x0000 (---------------) + I xn--nit225k 0x0036094e, // n0x0b58 c0x0000 (---------------) + I xn--ntso0iqx3a 0x00360ccb, // n0x0b59 c0x0000 (---------------) + I xn--ntsq17g 0x003687cb, // n0x0b5a c0x0000 (---------------) + I xn--pssu33l 0x0036a44b, // n0x0b5b c0x0000 (---------------) + I xn--qqqt11m 0x003725ca, // n0x0b5c c0x0000 (---------------) + I xn--rht27z 0x00372849, // n0x0b5d c0x0000 (---------------) + I xn--rht3d 0x00372a8a, // n0x0b5e c0x0000 (---------------) + I xn--rht61e 0x0037410a, // n0x0b5f c0x0000 (---------------) + I xn--rny31h 0x0038548b, // n0x0b60 c0x0000 (---------------) + I xn--tor131o 0x00386f0b, // n0x0b61 c0x0000 (---------------) + I xn--uist22h 0x0038744a, // n0x0b62 c0x0000 (---------------) + I xn--uisz3g 0x0038824b, // n0x0b63 c0x0000 (---------------) + I xn--uuwu58a 0x0038d1cb, // n0x0b64 c0x0000 (---------------) + I xn--vgu402c 0x00395d8b, // n0x0b65 c0x0000 (---------------) + I xn--zbx025d 0x2c26dc08, // n0x0b66 c0x00b0 (n0x11af-n0x11d1) + I yamagata 0x2c676089, // n0x0b67 c0x00b1 (n0x11d1-n0x11e1) + I yamaguchi 0x2ca9b889, // n0x0b68 c0x00b2 (n0x11e1-n0x11fd) + I yamanashi 0x2cf2b5c8, // n0x0b69 c0x00b3 (n0x11fd-n0x11fe)* o I yokohama 0x002a2345, // n0x0b6a c0x0000 (---------------) + I aisai 0x002068c3, // n0x0b6b c0x0000 (---------------) + I ama 0x00203884, // n0x0b6c c0x0000 (---------------) + I anjo 0x0034cb85, // n0x0b6d c0x0000 (---------------) + I asuke 0x00289546, // n0x0b6e c0x0000 (---------------) + I chiryu 0x002932c5, // n0x0b6f c0x0000 (---------------) + I chita 0x00274d84, // n0x0b70 c0x0000 (---------------) + I fuso 0x002472c8, // n0x0b71 c0x0000 (---------------) + I gamagori 0x00242045, // n0x0b72 c0x0000 (---------------) + I handa 0x0027ed44, // n0x0b73 c0x0000 (---------------) + I hazu 0x002b2387, // n0x0b74 c0x0000 (---------------) + I hekinan 0x00288d0a, // n0x0b75 c0x0000 (---------------) + I higashiura 0x002a580a, // n0x0b76 c0x0000 (---------------) + I ichinomiya 0x0031f587, // n0x0b77 c0x0000 (---------------) + I inazawa 0x002067c7, // n0x0b78 c0x0000 (---------------) + I inuyama 0x002d6707, // n0x0b79 c0x0000 (---------------) + I isshiki 0x00248887, // n0x0b7a c0x0000 (---------------) + I iwakura 0x00203cc5, // n0x0b7b c0x0000 (---------------) + I kanie 0x00311ec6, // n0x0b7c c0x0000 (---------------) + I kariya 0x0027cf47, // n0x0b7d c0x0000 (---------------) + I kasugai 0x0025a504, // n0x0b7e c0x0000 (---------------) + I kira 0x002fe646, // n0x0b7f c0x0000 (---------------) + I kiyosu 0x002977c6, // n0x0b80 c0x0000 (---------------) + I komaki 0x00204cc5, // n0x0b81 c0x0000 (---------------) + I konan 0x0024c9c4, // n0x0b82 c0x0000 (---------------) + I kota 0x00292a46, // n0x0b83 c0x0000 (---------------) + I mihama 0x00288107, // n0x0b84 c0x0000 (---------------) + I miyoshi 0x002209c6, // n0x0b85 c0x0000 (---------------) + I nishio 0x002e6987, // n0x0b86 c0x0000 (---------------) + I nisshin 0x0027e743, // n0x0b87 c0x0000 (---------------) + I obu 0x0023be46, // n0x0b88 c0x0000 (---------------) + I oguchi 0x0024f085, // n0x0b89 c0x0000 (---------------) + I oharu 0x0026c687, // n0x0b8a c0x0000 (---------------) + I okazaki 0x002ad48a, // n0x0b8b c0x0000 (---------------) + I owariasahi 0x002e9604, // n0x0b8c c0x0000 (---------------) + I seto 0x00213308, // n0x0b8d c0x0000 (---------------) + I shikatsu 0x0028d309, // n0x0b8e c0x0000 (---------------) + I shinshiro 0x002a4307, // n0x0b8f c0x0000 (---------------) + I shitara 0x0026a586, // n0x0b90 c0x0000 (---------------) + I tahara 0x00248648, // n0x0b91 c0x0000 (---------------) + I takahama 0x0030be89, // n0x0b92 c0x0000 (---------------) + I tobishima 0x00366704, // n0x0b93 c0x0000 (---------------) + I toei 0x0025d104, // n0x0b94 c0x0000 (---------------) + I togo 0x002df1c5, // n0x0b95 c0x0000 (---------------) + I tokai 0x00376b08, // n0x0b96 c0x0000 (---------------) + I tokoname 0x002aeb47, // n0x0b97 c0x0000 (---------------) + I toyoake 0x00286c89, // n0x0b98 c0x0000 (---------------) + I toyohashi 0x00322bc8, // n0x0b99 c0x0000 (---------------) + I toyokawa 0x00221246, // n0x0b9a c0x0000 (---------------) + I toyone 0x00338906, // n0x0b9b c0x0000 (---------------) + I toyota 0x00283308, // n0x0b9c c0x0000 (---------------) + I tsushima 0x00359906, // n0x0b9d c0x0000 (---------------) + I yatomi 0x00206e05, // n0x0b9e c0x0000 (---------------) + I akita 0x0026f346, // n0x0b9f c0x0000 (---------------) + I daisen 0x00266b48, // n0x0ba0 c0x0000 (---------------) + I fujisato 0x002dc286, // n0x0ba1 c0x0000 (---------------) + I gojome 0x0024608b, // n0x0ba2 c0x0000 (---------------) + I hachirogata 0x00279ac6, // n0x0ba3 c0x0000 (---------------) + I happou 0x00284b0d, // n0x0ba4 c0x0000 (---------------) + I higashinaruse 0x002028c5, // n0x0ba5 c0x0000 (---------------) + I honjo 0x00292e46, // n0x0ba6 c0x0000 (---------------) + I honjyo 0x00214f05, // n0x0ba7 c0x0000 (---------------) + I ikawa 0x00281889, // n0x0ba8 c0x0000 (---------------) + I kamikoani 0x0022ea47, // n0x0ba9 c0x0000 (---------------) + I kamioka 0x0033ecc8, // n0x0baa c0x0000 (---------------) + I katagami 0x0022bc46, // n0x0bab c0x0000 (---------------) + I kazuno 0x00283c89, // n0x0bac c0x0000 (---------------) + I kitaakita 0x0036b9c6, // n0x0bad c0x0000 (---------------) + I kosaka 0x002ad405, // n0x0bae c0x0000 (---------------) + I kyowa 0x0028b246, // n0x0baf c0x0000 (---------------) + I misato 0x002bf786, // n0x0bb0 c0x0000 (---------------) + I mitane 0x002b5c49, // n0x0bb1 c0x0000 (---------------) + I moriyoshi 0x00226806, // n0x0bb2 c0x0000 (---------------) + I nikaho 0x0023a007, // n0x0bb3 c0x0000 (---------------) + I noshiro 0x0027bd85, // n0x0bb4 c0x0000 (---------------) + I odate 0x00204043, // n0x0bb5 c0x0000 (---------------) + I oga 0x00246205, // n0x0bb6 c0x0000 (---------------) + I ogata 0x00293cc7, // n0x0bb7 c0x0000 (---------------) + I semboku 0x0023ed06, // n0x0bb8 c0x0000 (---------------) + I yokote 0x002027c9, // n0x0bb9 c0x0000 (---------------) + I yurihonjo 0x00387ac6, // n0x0bba c0x0000 (---------------) + I aomori 0x0026f586, // n0x0bbb c0x0000 (---------------) + I gonohe 0x0022e109, // n0x0bbc c0x0000 (---------------) + I hachinohe 0x0026ed49, // n0x0bbd c0x0000 (---------------) + I hashikami 0x0028bc07, // n0x0bbe c0x0000 (---------------) + I hiranai 0x00305a08, // n0x0bbf c0x0000 (---------------) + I hirosaki 0x00273909, // n0x0bc0 c0x0000 (---------------) + I itayanagi 0x0026ce88, // n0x0bc1 c0x0000 (---------------) + I kuroishi 0x0035c906, // n0x0bc2 c0x0000 (---------------) + I misawa 0x002bda45, // n0x0bc3 c0x0000 (---------------) + I mutsu 0x0021638a, // n0x0bc4 c0x0000 (---------------) + I nakadomari 0x0026f606, // n0x0bc5 c0x0000 (---------------) + I noheji 0x0035e1c6, // n0x0bc6 c0x0000 (---------------) + I oirase 0x0028d905, // n0x0bc7 c0x0000 (---------------) + I owani 0x00205c88, // n0x0bc8 c0x0000 (---------------) + I rokunohe 0x002092c7, // n0x0bc9 c0x0000 (---------------) + I sannohe 0x0029ba0a, // n0x0bca c0x0000 (---------------) + I shichinohe 0x00238986, // n0x0bcb c0x0000 (---------------) + I shingo 0x0024cec5, // n0x0bcc c0x0000 (---------------) + I takko 0x0023e846, // n0x0bcd c0x0000 (---------------) + I towada 0x002e1a47, // n0x0bce c0x0000 (---------------) + I tsugaru 0x0026a447, // n0x0bcf c0x0000 (---------------) + I tsuruta 0x002041c5, // n0x0bd0 c0x0000 (---------------) + I abiko 0x002ad5c5, // n0x0bd1 c0x0000 (---------------) + I asahi 0x002c6646, // n0x0bd2 c0x0000 (---------------) + I chonan 0x002c6e86, // n0x0bd3 c0x0000 (---------------) + I chosei 0x0034a586, // n0x0bd4 c0x0000 (---------------) + I choshi 0x002be904, // n0x0bd5 c0x0000 (---------------) + I chuo 0x0026e2c9, // n0x0bd6 c0x0000 (---------------) + I funabashi 0x00276f46, // n0x0bd7 c0x0000 (---------------) + I futtsu 0x002d6f4a, // n0x0bd8 c0x0000 (---------------) + I hanamigawa 0x0027df48, // n0x0bd9 c0x0000 (---------------) + I ichihara 0x00312b88, // n0x0bda c0x0000 (---------------) + I ichikawa 0x002a580a, // n0x0bdb c0x0000 (---------------) + I ichinomiya 0x00329b05, // n0x0bdc c0x0000 (---------------) + I inzai 0x00288045, // n0x0bdd c0x0000 (---------------) + I isumi 0x00269408, // n0x0bde c0x0000 (---------------) + I kamagaya 0x002ba1c8, // n0x0bdf c0x0000 (---------------) + I kamogawa 0x00375c87, // n0x0be0 c0x0000 (---------------) + I kashiwa 0x00335e46, // n0x0be1 c0x0000 (---------------) + I katori 0x002fd408, // n0x0be2 c0x0000 (---------------) + I katsuura 0x0027d607, // n0x0be3 c0x0000 (---------------) + I kimitsu 0x0026c7c8, // n0x0be4 c0x0000 (---------------) + I kisarazu 0x0035d306, // n0x0be5 c0x0000 (---------------) + I kozaki 0x0026ff48, // n0x0be6 c0x0000 (---------------) + I kujukuri 0x0027e846, // n0x0be7 c0x0000 (---------------) + I kyonan 0x0023b8c7, // n0x0be8 c0x0000 (---------------) + I matsudo 0x002846c6, // n0x0be9 c0x0000 (---------------) + I midori 0x00292a46, // n0x0bea c0x0000 (---------------) + I mihama 0x00213fca, // n0x0beb c0x0000 (---------------) + I minamiboso 0x00223146, // n0x0bec c0x0000 (---------------) + I mobara 0x002bda49, // n0x0bed c0x0000 (---------------) + I mutsuzawa 0x0032a1c6, // n0x0bee c0x0000 (---------------) + I nagara 0x002a0a8a, // n0x0bef c0x0000 (---------------) + I nagareyama 0x002da0c9, // n0x0bf0 c0x0000 (---------------) + I narashino 0x0025ac46, // n0x0bf1 c0x0000 (---------------) + I narita 0x00384f84, // n0x0bf2 c0x0000 (---------------) + I noda 0x0030bbcd, // n0x0bf3 c0x0000 (---------------) + I oamishirasato 0x00276307, // n0x0bf4 c0x0000 (---------------) + I omigawa 0x002fffc6, // n0x0bf5 c0x0000 (---------------) + I onjuku 0x002a8605, // n0x0bf6 c0x0000 (---------------) + I otaki 0x0036ba45, // n0x0bf7 c0x0000 (---------------) + I sakae 0x002f4d46, // n0x0bf8 c0x0000 (---------------) + I sakura 0x002a73c9, // n0x0bf9 c0x0000 (---------------) + I shimofusa 0x002b9447, // n0x0bfa c0x0000 (---------------) + I shirako 0x00268406, // n0x0bfb c0x0000 (---------------) + I shiroi 0x0029fd06, // n0x0bfc c0x0000 (---------------) + I shisui 0x00274e09, // n0x0bfd c0x0000 (---------------) + I sodegaura 0x0022a904, // n0x0bfe c0x0000 (---------------) + I sosa 0x0021f304, // n0x0bff c0x0000 (---------------) + I tako 0x0038a708, // n0x0c00 c0x0000 (---------------) + I tateyama 0x002e5fc6, // n0x0c01 c0x0000 (---------------) + I togane 0x00340e08, // n0x0c02 c0x0000 (---------------) + I tohnosho 0x003163c8, // n0x0c03 c0x0000 (---------------) + I tomisato 0x00206f47, // n0x0c04 c0x0000 (---------------) + I urayasu 0x00382d89, // n0x0c05 c0x0000 (---------------) + I yachimata 0x002e38c7, // n0x0c06 c0x0000 (---------------) + I yachiyo 0x002a060a, // n0x0c07 c0x0000 (---------------) + I yokaichiba 0x00315d8f, // n0x0c08 c0x0000 (---------------) + I yokoshibahikari 0x002394ca, // n0x0c09 c0x0000 (---------------) + I yotsukaido 0x0021b845, // n0x0c0a c0x0000 (---------------) + I ainan 0x00266d85, // n0x0c0b c0x0000 (---------------) + I honai 0x0020f345, // n0x0c0c c0x0000 (---------------) + I ikata 0x0027eac7, // n0x0c0d c0x0000 (---------------) + I imabari 0x00253503, // n0x0c0e c0x0000 (---------------) + I iyo 0x00305c08, // n0x0c0f c0x0000 (---------------) + I kamijima 0x0037aec6, // n0x0c10 c0x0000 (---------------) + I kihoku 0x0037afc9, // n0x0c11 c0x0000 (---------------) + I kumakogen 0x002e5286, // n0x0c12 c0x0000 (---------------) + I masaki 0x00392e07, // n0x0c13 c0x0000 (---------------) + I matsuno 0x00283a49, // n0x0c14 c0x0000 (---------------) + I matsuyama 0x0033ebc8, // n0x0c15 c0x0000 (---------------) + I namikata 0x0028d9c7, // n0x0c16 c0x0000 (---------------) + I niihama 0x002e3dc3, // n0x0c17 c0x0000 (---------------) + I ozu 0x002a23c5, // n0x0c18 c0x0000 (---------------) + I saijo 0x00315cc5, // n0x0c19 c0x0000 (---------------) + I seiyo 0x002be74b, // n0x0c1a c0x0000 (---------------) + I shikokuchuo 0x002acbc4, // n0x0c1b c0x0000 (---------------) + I tobe 0x002d1504, // n0x0c1c c0x0000 (---------------) + I toon 0x00265706, // n0x0c1d c0x0000 (---------------) + I uchiko 0x002e4647, // n0x0c1e c0x0000 (---------------) + I uwajima 0x003804ca, // n0x0c1f c0x0000 (---------------) + I yawatahama 0x002281c7, // n0x0c20 c0x0000 (---------------) + I echizen 0x00366787, // n0x0c21 c0x0000 (---------------) + I eiheiji 0x0026b7c5, // n0x0c22 c0x0000 (---------------) + I fukui 0x00390e45, // n0x0c23 c0x0000 (---------------) + I ikeda 0x00260149, // n0x0c24 c0x0000 (---------------) + I katsuyama 0x00292a46, // n0x0c25 c0x0000 (---------------) + I mihama 0x0022804d, // n0x0c26 c0x0000 (---------------) + I minamiechizen 0x00395885, // n0x0c27 c0x0000 (---------------) + I obama 0x00285a43, // n0x0c28 c0x0000 (---------------) + I ohi 0x00207e83, // n0x0c29 c0x0000 (---------------) + I ono 0x003404c5, // n0x0c2a c0x0000 (---------------) + I sabae 0x003396c5, // n0x0c2b c0x0000 (---------------) + I sakai 0x00248648, // n0x0c2c c0x0000 (---------------) + I takahama 0x00277007, // n0x0c2d c0x0000 (---------------) + I tsuruga 0x0021f086, // n0x0c2e c0x0000 (---------------) + I wakasa 0x00289c86, // n0x0c2f c0x0000 (---------------) + I ashiya 0x0021de85, // n0x0c30 c0x0000 (---------------) + I buzen 0x00375807, // n0x0c31 c0x0000 (---------------) + I chikugo 0x00206a47, // n0x0c32 c0x0000 (---------------) + I chikuho 0x002a5bc7, // n0x0c33 c0x0000 (---------------) + I chikujo 0x002ba4ca, // n0x0c34 c0x0000 (---------------) + I chikushino 0x0023bf08, // n0x0c35 c0x0000 (---------------) + I chikuzen 0x002be904, // n0x0c36 c0x0000 (---------------) + I chuo 0x0024ed47, // n0x0c37 c0x0000 (---------------) + I dazaifu 0x0026ae87, // n0x0c38 c0x0000 (---------------) + I fukuchi 0x00317546, // n0x0c39 c0x0000 (---------------) + I hakata 0x002545c7, // n0x0c3a c0x0000 (---------------) + I higashi 0x002c5b48, // n0x0c3b c0x0000 (---------------) + I hirokawa 0x0029b788, // n0x0c3c c0x0000 (---------------) + I hisayama 0x00246d86, // n0x0c3d c0x0000 (---------------) + I iizuka 0x0023abc8, // n0x0c3e c0x0000 (---------------) + I inatsuki 0x00226884, // n0x0c3f c0x0000 (---------------) + I kaho 0x0027cf46, // n0x0c40 c0x0000 (---------------) + I kasuga 0x0020d3c6, // n0x0c41 c0x0000 (---------------) + I kasuya 0x003824c6, // n0x0c42 c0x0000 (---------------) + I kawara 0x00295dc6, // n0x0c43 c0x0000 (---------------) + I keisen 0x00232c84, // n0x0c44 c0x0000 (---------------) + I koga 0x00248946, // n0x0c45 c0x0000 (---------------) + I kurate 0x002a67c6, // n0x0c46 c0x0000 (---------------) + I kurogi 0x00282e46, // n0x0c47 c0x0000 (---------------) + I kurume 0x00213fc6, // n0x0c48 c0x0000 (---------------) + I minami 0x00207d46, // n0x0c49 c0x0000 (---------------) + I miyako 0x00272346, // n0x0c4a c0x0000 (---------------) + I miyama 0x0021ef88, // n0x0c4b c0x0000 (---------------) + I miyawaka 0x002fe4c8, // n0x0c4c c0x0000 (---------------) + I mizumaki 0x002bb0c8, // n0x0c4d c0x0000 (---------------) + I munakata 0x002934c8, // n0x0c4e c0x0000 (---------------) + I nakagawa 0x00269386, // n0x0c4f c0x0000 (---------------) + I nakama 0x00208b85, // n0x0c50 c0x0000 (---------------) + I nishi 0x0031b486, // n0x0c51 c0x0000 (---------------) + I nogata 0x00296ec5, // n0x0c52 c0x0000 (---------------) + I ogori 0x0035c047, // n0x0c53 c0x0000 (---------------) + I okagaki 0x0022ecc5, // n0x0c54 c0x0000 (---------------) + I okawa 0x00201bc3, // n0x0c55 c0x0000 (---------------) + I oki 0x00200085, // n0x0c56 c0x0000 (---------------) + I omuta 0x002c7844, // n0x0c57 c0x0000 (---------------) + I onga 0x00207e85, // n0x0c58 c0x0000 (---------------) + I onojo 0x0020fdc3, // n0x0c59 c0x0000 (---------------) + I oto 0x002d47c7, // n0x0c5a c0x0000 (---------------) + I saigawa 0x00333848, // n0x0c5b c0x0000 (---------------) + I sasaguri 0x002e6a46, // n0x0c5c c0x0000 (---------------) + I shingu 0x0029230d, // n0x0c5d c0x0000 (---------------) + I shinyoshitomi 0x00266d46, // n0x0c5e c0x0000 (---------------) + I shonai 0x002823c5, // n0x0c5f c0x0000 (---------------) + I soeda 0x002ad183, // n0x0c60 c0x0000 (---------------) + I sue 0x002a2189, // n0x0c61 c0x0000 (---------------) + I tachiarai 0x0020e146, // n0x0c62 c0x0000 (---------------) + I tagawa 0x002344c6, // n0x0c63 c0x0000 (---------------) + I takata 0x00253644, // n0x0c64 c0x0000 (---------------) + I toho 0x00239447, // n0x0c65 c0x0000 (---------------) + I toyotsu 0x00227786, // n0x0c66 c0x0000 (---------------) + I tsuiki 0x00289985, // n0x0c67 c0x0000 (---------------) + I ukiha 0x00209803, // n0x0c68 c0x0000 (---------------) + I umi 0x00211e04, // n0x0c69 c0x0000 (---------------) + I usui 0x0026b046, // n0x0c6a c0x0000 (---------------) + I yamada 0x002d81c4, // n0x0c6b c0x0000 (---------------) + I yame 0x002f7448, // n0x0c6c c0x0000 (---------------) + I yanagawa 0x0038f4c9, // n0x0c6d c0x0000 (---------------) + I yukuhashi 0x0022ef49, // n0x0c6e c0x0000 (---------------) + I aizubange 0x0028b14a, // n0x0c6f c0x0000 (---------------) + I aizumisato 0x0023124d, // n0x0c70 c0x0000 (---------------) + I aizuwakamatsu 0x00240607, // n0x0c71 c0x0000 (---------------) + I asakawa 0x00255706, // n0x0c72 c0x0000 (---------------) + I bandai 0x00209004, // n0x0c73 c0x0000 (---------------) + I date 0x0026d5c9, // n0x0c74 c0x0000 (---------------) + I fukushima 0x00274788, // n0x0c75 c0x0000 (---------------) + I furudono 0x00275f06, // n0x0c76 c0x0000 (---------------) + I futaba 0x002e9cc6, // n0x0c77 c0x0000 (---------------) + I hanawa 0x002545c7, // n0x0c78 c0x0000 (---------------) + I higashi 0x0029cdc6, // n0x0c79 c0x0000 (---------------) + I hirata 0x0021af86, // n0x0c7a c0x0000 (---------------) + I hirono 0x00329c06, // n0x0c7b c0x0000 (---------------) + I iitate 0x0039554a, // n0x0c7c c0x0000 (---------------) + I inawashiro 0x00214e48, // n0x0c7d c0x0000 (---------------) + I ishikawa 0x002999c5, // n0x0c7e c0x0000 (---------------) + I iwaki 0x00254a09, // n0x0c7f c0x0000 (---------------) + I izumizaki 0x002af2ca, // n0x0c80 c0x0000 (---------------) + I kagamiishi 0x002150c8, // n0x0c81 c0x0000 (---------------) + I kaneyama 0x00287448, // n0x0c82 c0x0000 (---------------) + I kawamata 0x002815c8, // n0x0c83 c0x0000 (---------------) + I kitakata 0x00293e8c, // n0x0c84 c0x0000 (---------------) + I kitashiobara 0x002c3e45, // n0x0c85 c0x0000 (---------------) + I koori 0x00289f08, // n0x0c86 c0x0000 (---------------) + I koriyama 0x002f1d86, // n0x0c87 c0x0000 (---------------) + I kunimi 0x002d1906, // n0x0c88 c0x0000 (---------------) + I miharu 0x00392cc7, // n0x0c89 c0x0000 (---------------) + I mishima 0x002280c5, // n0x0c8a c0x0000 (---------------) + I namie 0x0026f4c5, // n0x0c8b c0x0000 (---------------) + I nango 0x0022ee09, // n0x0c8c c0x0000 (---------------) + I nishiaizu 0x0020bd87, // n0x0c8d c0x0000 (---------------) + I nishigo 0x0037af85, // n0x0c8e c0x0000 (---------------) + I okuma 0x0021e147, // n0x0c8f c0x0000 (---------------) + I omotego 0x00207e83, // n0x0c90 c0x0000 (---------------) + I ono 0x002af985, // n0x0c91 c0x0000 (---------------) + I otama 0x00355688, // n0x0c92 c0x0000 (---------------) + I samegawa 0x0026e047, // n0x0c93 c0x0000 (---------------) + I shimogo 0x00287309, // n0x0c94 c0x0000 (---------------) + I shirakawa 0x002b3885, // n0x0c95 c0x0000 (---------------) + I showa 0x0038e104, // n0x0c96 c0x0000 (---------------) + I soma 0x0028c348, // n0x0c97 c0x0000 (---------------) + I sukagawa 0x0025fa47, // n0x0c98 c0x0000 (---------------) + I taishin 0x0028db88, // n0x0c99 c0x0000 (---------------) + I tamakawa 0x003109c8, // n0x0c9a c0x0000 (---------------) + I tanagura 0x0034d1c5, // n0x0c9b c0x0000 (---------------) + I tenei 0x00389946, // n0x0c9c c0x0000 (---------------) + I yabuki 0x0022afc6, // n0x0c9d c0x0000 (---------------) + I yamato 0x00346949, // n0x0c9e c0x0000 (---------------) + I yamatsuri 0x002fdc47, // n0x0c9f c0x0000 (---------------) + I yanaizu 0x00297546, // n0x0ca0 c0x0000 (---------------) + I yugawa 0x00383347, // n0x0ca1 c0x0000 (---------------) + I anpachi 0x00244403, // n0x0ca2 c0x0000 (---------------) + I ena 0x00289804, // n0x0ca3 c0x0000 (---------------) + I gifu 0x003746c5, // n0x0ca4 c0x0000 (---------------) + I ginan 0x0024efc4, // n0x0ca5 c0x0000 (---------------) + I godo 0x00232644, // n0x0ca6 c0x0000 (---------------) + I gujo 0x0023ca07, // n0x0ca7 c0x0000 (---------------) + I hashima 0x002e5907, // n0x0ca8 c0x0000 (---------------) + I hichiso 0x002685c4, // n0x0ca9 c0x0000 (---------------) + I hida 0x00287150, // n0x0caa c0x0000 (---------------) + I higashishirakawa 0x002f4ec7, // n0x0cab c0x0000 (---------------) + I ibigawa 0x00390e45, // n0x0cac c0x0000 (---------------) + I ikeda 0x00271acc, // n0x0cad c0x0000 (---------------) + I kakamigahara 0x00203cc4, // n0x0cae c0x0000 (---------------) + I kani 0x0028f7c8, // n0x0caf c0x0000 (---------------) + I kasahara 0x0023b7c9, // n0x0cb0 c0x0000 (---------------) + I kasamatsu 0x00298ac6, // n0x0cb1 c0x0000 (---------------) + I kawaue 0x0022aa08, // n0x0cb2 c0x0000 (---------------) + I kitagata 0x0022ec04, // n0x0cb3 c0x0000 (---------------) + I mino 0x002fb148, // n0x0cb4 c0x0000 (---------------) + I minokamo 0x002adf86, // n0x0cb5 c0x0000 (---------------) + I mitake 0x00252288, // n0x0cb6 c0x0000 (---------------) + I mizunami 0x00289146, // n0x0cb7 c0x0000 (---------------) + I motosu 0x0021d20b, // n0x0cb8 c0x0000 (---------------) + I nakatsugawa 0x00394b85, // n0x0cb9 c0x0000 (---------------) + I ogaki 0x002b5248, // n0x0cba c0x0000 (---------------) + I sakahogi 0x0020d984, // n0x0cbb c0x0000 (---------------) + I seki 0x0038f90a, // n0x0cbc c0x0000 (---------------) + I sekigahara 0x00287309, // n0x0cbd c0x0000 (---------------) + I shirakawa 0x0024f946, // n0x0cbe c0x0000 (---------------) + I tajimi 0x0020f408, // n0x0cbf c0x0000 (---------------) + I takayama 0x002b9085, // n0x0cc0 c0x0000 (---------------) + I tarui 0x002add84, // n0x0cc1 c0x0000 (---------------) + I toki 0x0028f6c6, // n0x0cc2 c0x0000 (---------------) + I tomika 0x002e55c8, // n0x0cc3 c0x0000 (---------------) + I wanouchi 0x0026dc08, // n0x0cc4 c0x0000 (---------------) + I yamagata 0x00330546, // n0x0cc5 c0x0000 (---------------) + I yaotsu 0x00396e84, // n0x0cc6 c0x0000 (---------------) + I yoro 0x00216306, // n0x0cc7 c0x0000 (---------------) + I annaka 0x002e3947, // n0x0cc8 c0x0000 (---------------) + I chiyoda 0x00266507, // n0x0cc9 c0x0000 (---------------) + I fujioka 0x002545cf, // n0x0cca c0x0000 (---------------) + I higashiagatsuma 0x0037a987, // n0x0ccb c0x0000 (---------------) + I isesaki 0x0025ad07, // n0x0ccc c0x0000 (---------------) + I itakura 0x002d17c5, // n0x0ccd c0x0000 (---------------) + I kanna 0x002cc145, // n0x0cce c0x0000 (---------------) + I kanra 0x0028b8c9, // n0x0ccf c0x0000 (---------------) + I katashina 0x00343106, // n0x0cd0 c0x0000 (---------------) + I kawaba 0x00258d45, // n0x0cd1 c0x0000 (---------------) + I kiryu 0x0026f047, // n0x0cd2 c0x0000 (---------------) + I kusatsu 0x002cb088, // n0x0cd3 c0x0000 (---------------) + I maebashi 0x002cae05, // n0x0cd4 c0x0000 (---------------) + I meiwa 0x002846c6, // n0x0cd5 c0x0000 (---------------) + I midori 0x00204808, // n0x0cd6 c0x0000 (---------------) + I minakami 0x0034e4ca, // n0x0cd7 c0x0000 (---------------) + I naganohara 0x00364808, // n0x0cd8 c0x0000 (---------------) + I nakanojo 0x00278107, // n0x0cd9 c0x0000 (---------------) + I nanmoku 0x003161c6, // n0x0cda c0x0000 (---------------) + I numata 0x002549c6, // n0x0cdb c0x0000 (---------------) + I oizumi 0x0020ca43, // n0x0cdc c0x0000 (---------------) + I ora 0x00203943, // n0x0cdd c0x0000 (---------------) + I ota 0x0034a649, // n0x0cde c0x0000 (---------------) + I shibukawa 0x00273789, // n0x0cdf c0x0000 (---------------) + I shimonita 0x0028e1c6, // n0x0ce0 c0x0000 (---------------) + I shinto 0x002b3885, // n0x0ce1 c0x0000 (---------------) + I showa 0x00298d88, // n0x0ce2 c0x0000 (---------------) + I takasaki 0x0020f408, // n0x0ce3 c0x0000 (---------------) + I takayama 0x003936c8, // n0x0ce4 c0x0000 (---------------) + I tamamura 0x00329c8b, // n0x0ce5 c0x0000 (---------------) + I tatebayashi 0x00292547, // n0x0ce6 c0x0000 (---------------) + I tomioka 0x0030b489, // n0x0ce7 c0x0000 (---------------) + I tsukiyono 0x00254848, // n0x0ce8 c0x0000 (---------------) + I tsumagoi 0x0038dac4, // n0x0ce9 c0x0000 (---------------) + I ueno 0x002b5d48, // n0x0cea c0x0000 (---------------) + I yoshioka 0x0027a909, // n0x0ceb c0x0000 (---------------) + I asaminami 0x002557c5, // n0x0cec c0x0000 (---------------) + I daiwa 0x0020dd07, // n0x0ced c0x0000 (---------------) + I etajima 0x002ab685, // n0x0cee c0x0000 (---------------) + I fuchu 0x0026db08, // n0x0cef c0x0000 (---------------) + I fukuyama 0x0027dd8b, // n0x0cf0 c0x0000 (---------------) + I hatsukaichi 0x00280dd0, // n0x0cf1 c0x0000 (---------------) + I higashihiroshima 0x00292c45, // n0x0cf2 c0x0000 (---------------) + I hongo 0x0020d8cc, // n0x0cf3 c0x0000 (---------------) + I jinsekikogen 0x0021f245, // n0x0cf4 c0x0000 (---------------) + I kaita 0x0026b843, // n0x0cf5 c0x0000 (---------------) + I kui 0x00285906, // n0x0cf6 c0x0000 (---------------) + I kumano 0x002a4544, // n0x0cf7 c0x0000 (---------------) + I kure 0x003637c6, // n0x0cf8 c0x0000 (---------------) + I mihara 0x00288107, // n0x0cf9 c0x0000 (---------------) + I miyoshi 0x00204884, // n0x0cfa c0x0000 (---------------) + I naka 0x002a5708, // n0x0cfb c0x0000 (---------------) + I onomichi 0x00305acd, // n0x0cfc c0x0000 (---------------) + I osakikamijima 0x00335c85, // n0x0cfd c0x0000 (---------------) + I otake 0x00201a04, // n0x0cfe c0x0000 (---------------) + I saka 0x0021b584, // n0x0cff c0x0000 (---------------) + I sera 0x00325cc9, // n0x0d00 c0x0000 (---------------) + I seranishi 0x0027f9c8, // n0x0d01 c0x0000 (---------------) + I shinichi 0x002f5a47, // n0x0d02 c0x0000 (---------------) + I shobara 0x002ae008, // n0x0d03 c0x0000 (---------------) + I takehara 0x0026e388, // n0x0d04 c0x0000 (---------------) + I abashiri 0x00268705, // n0x0d05 c0x0000 (---------------) + I abira 0x0031acc7, // n0x0d06 c0x0000 (---------------) + I aibetsu 0x00268687, // n0x0d07 c0x0000 (---------------) + I akabira 0x00300f87, // n0x0d08 c0x0000 (---------------) + I akkeshi 0x002ad5c9, // n0x0d09 c0x0000 (---------------) + I asahikawa 0x00227609, // n0x0d0a c0x0000 (---------------) + I ashibetsu 0x00230d06, // n0x0d0b c0x0000 (---------------) + I ashoro 0x00318dc6, // n0x0d0c c0x0000 (---------------) + I assabu 0x00254806, // n0x0d0d c0x0000 (---------------) + I atsuma 0x00323c05, // n0x0d0e c0x0000 (---------------) + I bibai 0x002626c4, // n0x0d0f c0x0000 (---------------) + I biei 0x0038aec6, // n0x0d10 c0x0000 (---------------) + I bifuka 0x0038f286, // n0x0d11 c0x0000 (---------------) + I bihoro 0x00268748, // n0x0d12 c0x0000 (---------------) + I biratori 0x002e170b, // n0x0d13 c0x0000 (---------------) + I chippubetsu 0x00366547, // n0x0d14 c0x0000 (---------------) + I chitose 0x00209004, // n0x0d15 c0x0000 (---------------) + I date 0x0032d2c6, // n0x0d16 c0x0000 (---------------) + I ebetsu 0x00337807, // n0x0d17 c0x0000 (---------------) + I embetsu 0x00271f45, // n0x0d18 c0x0000 (---------------) + I eniwa 0x002f35c5, // n0x0d19 c0x0000 (---------------) + I erimo 0x00202244, // n0x0d1a c0x0000 (---------------) + I esan 0x00227586, // n0x0d1b c0x0000 (---------------) + I esashi 0x0038af48, // n0x0d1c c0x0000 (---------------) + I fukagawa 0x0026d5c9, // n0x0d1d c0x0000 (---------------) + I fukushima 0x00239f06, // n0x0d1e c0x0000 (---------------) + I furano 0x00273e08, // n0x0d1f c0x0000 (---------------) + I furubira 0x002e3146, // n0x0d20 c0x0000 (---------------) + I haboro 0x00325388, // n0x0d21 c0x0000 (---------------) + I hakodate 0x002a154c, // n0x0d22 c0x0000 (---------------) + I hamatonbetsu 0x002685c6, // n0x0d23 c0x0000 (---------------) + I hidaka 0x0028208d, // n0x0d24 c0x0000 (---------------) + I higashikagura 0x0028250b, // n0x0d25 c0x0000 (---------------) + I higashikawa 0x0023a0c5, // n0x0d26 c0x0000 (---------------) + I hiroo 0x00206b87, // n0x0d27 c0x0000 (---------------) + I hokuryu 0x00226906, // n0x0d28 c0x0000 (---------------) + I hokuto 0x00305188, // n0x0d29 c0x0000 (---------------) + I honbetsu 0x00230d89, // n0x0d2a c0x0000 (---------------) + I horokanai 0x00346588, // n0x0d2b c0x0000 (---------------) + I horonobe 0x00390e45, // n0x0d2c c0x0000 (---------------) + I ikeda 0x0020de07, // n0x0d2d c0x0000 (---------------) + I imakane 0x002af448, // n0x0d2e c0x0000 (---------------) + I ishikari 0x0023e509, // n0x0d2f c0x0000 (---------------) + I iwamizawa 0x002e74c6, // n0x0d30 c0x0000 (---------------) + I iwanai 0x00239e0a, // n0x0d31 c0x0000 (---------------) + I kamifurano 0x00304f08, // n0x0d32 c0x0000 (---------------) + I kamikawa 0x003463cb, // n0x0d33 c0x0000 (---------------) + I kamishihoro 0x002ae7cc, // n0x0d34 c0x0000 (---------------) + I kamisunagawa 0x002fb248, // n0x0d35 c0x0000 (---------------) + I kamoenai 0x00269e06, // n0x0d36 c0x0000 (---------------) + I kayabe 0x002a5a88, // n0x0d37 c0x0000 (---------------) + I kembuchi 0x0035e007, // n0x0d38 c0x0000 (---------------) + I kikonai 0x002e5389, // n0x0d39 c0x0000 (---------------) + I kimobetsu 0x0027c54d, // n0x0d3a c0x0000 (---------------) + I kitahiroshima 0x002885c6, // n0x0d3b c0x0000 (---------------) + I kitami 0x002534c8, // n0x0d3c c0x0000 (---------------) + I kiyosato 0x002fe389, // n0x0d3d c0x0000 (---------------) + I koshimizu 0x002a3148, // n0x0d3e c0x0000 (---------------) + I kunneppu 0x00270048, // n0x0d3f c0x0000 (---------------) + I kuriyama 0x002a7e8c, // n0x0d40 c0x0000 (---------------) + I kuromatsunai 0x002a9347, // n0x0d41 c0x0000 (---------------) + I kushiro 0x002a9e47, // n0x0d42 c0x0000 (---------------) + I kutchan 0x002ad405, // n0x0d43 c0x0000 (---------------) + I kyowa 0x00260307, // n0x0d44 c0x0000 (---------------) + I mashike 0x002caf48, // n0x0d45 c0x0000 (---------------) + I matsumae 0x0028f746, // n0x0d46 c0x0000 (---------------) + I mikasa 0x003561cc, // n0x0d47 c0x0000 (---------------) + I minamifurano 0x002ccb48, // n0x0d48 c0x0000 (---------------) + I mombetsu 0x002b7108, // n0x0d49 c0x0000 (---------------) + I moseushi 0x0024e806, // n0x0d4a c0x0000 (---------------) + I mukawa 0x002a6187, // n0x0d4b c0x0000 (---------------) + I muroran 0x00230f04, // n0x0d4c c0x0000 (---------------) + I naie 0x002934c8, // n0x0d4d c0x0000 (---------------) + I nakagawa 0x0026208c, // n0x0d4e c0x0000 (---------------) + I nakasatsunai 0x0027848c, // n0x0d4f c0x0000 (---------------) + I nakatombetsu 0x0021b8c5, // n0x0d50 c0x0000 (---------------) + I nanae 0x0037c587, // n0x0d51 c0x0000 (---------------) + I nanporo 0x00396e06, // n0x0d52 c0x0000 (---------------) + I nayoro 0x002a6106, // n0x0d53 c0x0000 (---------------) + I nemuro 0x00281a48, // n0x0d54 c0x0000 (---------------) + I niikappu 0x0037ae44, // n0x0d55 c0x0000 (---------------) + I niki 0x002209cb, // n0x0d56 c0x0000 (---------------) + I nishiokoppe 0x002f090b, // n0x0d57 c0x0000 (---------------) + I noboribetsu 0x003161c6, // n0x0d58 c0x0000 (---------------) + I numata 0x00305947, // n0x0d59 c0x0000 (---------------) + I obihiro 0x00311445, // n0x0d5a c0x0000 (---------------) + I obira 0x0025d045, // n0x0d5b c0x0000 (---------------) + I oketo 0x00220b06, // n0x0d5c c0x0000 (---------------) + I okoppe 0x002b9045, // n0x0d5d c0x0000 (---------------) + I otaru 0x002acb85, // n0x0d5e c0x0000 (---------------) + I otobe 0x002c4a07, // n0x0d5f c0x0000 (---------------) + I otofuke 0x0025cbc9, // n0x0d60 c0x0000 (---------------) + I otoineppu 0x002f3c44, // n0x0d61 c0x0000 (---------------) + I oumu 0x0035f085, // n0x0d62 c0x0000 (---------------) + I ozora 0x002c2c45, // n0x0d63 c0x0000 (---------------) + I pippu 0x0028eb48, // n0x0d64 c0x0000 (---------------) + I rankoshi 0x002a5545, // n0x0d65 c0x0000 (---------------) + I rebun 0x002b4809, // n0x0d66 c0x0000 (---------------) + I rikubetsu 0x00294c47, // n0x0d67 c0x0000 (---------------) + I rishiri 0x00294c4b, // n0x0d68 c0x0000 (---------------) + I rishirifuji 0x00307c86, // n0x0d69 c0x0000 (---------------) + I saroma 0x0021ecc9, // n0x0d6a c0x0000 (---------------) + I sarufutsu 0x0024c908, // n0x0d6b c0x0000 (---------------) + I shakotan 0x00252d45, // n0x0d6c c0x0000 (---------------) + I shari 0x00301088, // n0x0d6d c0x0000 (---------------) + I shibecha 0x00227648, // n0x0d6e c0x0000 (---------------) + I shibetsu 0x00251507, // n0x0d6f c0x0000 (---------------) + I shikabe 0x002d3e87, // n0x0d70 c0x0000 (---------------) + I shikaoi 0x0023ca89, // n0x0d71 c0x0000 (---------------) + I shimamaki 0x002521c7, // n0x0d72 c0x0000 (---------------) + I shimizu 0x00266909, // n0x0d73 c0x0000 (---------------) + I shimokawa 0x00287a0c, // n0x0d74 c0x0000 (---------------) + I shinshinotsu 0x0028e1c8, // n0x0d75 c0x0000 (---------------) + I shintoku 0x002d1609, // n0x0d76 c0x0000 (---------------) + I shiranuka 0x002d2247, // n0x0d77 c0x0000 (---------------) + I shiraoi 0x0026e449, // n0x0d78 c0x0000 (---------------) + I shiriuchi 0x002e5a47, // n0x0d79 c0x0000 (---------------) + I sobetsu 0x002ae8c8, // n0x0d7a c0x0000 (---------------) + I sunagawa 0x0028ee85, // n0x0d7b c0x0000 (---------------) + I taiki 0x0027cec6, // n0x0d7c c0x0000 (---------------) + I takasu 0x002a8648, // n0x0d7d c0x0000 (---------------) + I takikawa 0x00245108, // n0x0d7e c0x0000 (---------------) + I takinoue 0x002af189, // n0x0d7f c0x0000 (---------------) + I teshikaga 0x002acbc7, // n0x0d80 c0x0000 (---------------) + I tobetsu 0x0028b345, // n0x0d81 c0x0000 (---------------) + I tohma 0x002b9dc9, // n0x0d82 c0x0000 (---------------) + I tomakomai 0x0036edc6, // n0x0d83 c0x0000 (---------------) + I tomari 0x0027c344, // n0x0d84 c0x0000 (---------------) + I toya 0x00346246, // n0x0d85 c0x0000 (---------------) + I toyako 0x00371088, // n0x0d86 c0x0000 (---------------) + I toyotomi 0x00244007, // n0x0d87 c0x0000 (---------------) + I toyoura 0x002e1908, // n0x0d88 c0x0000 (---------------) + I tsubetsu 0x0023ac89, // n0x0d89 c0x0000 (---------------) + I tsukigata 0x0024e587, // n0x0d8a c0x0000 (---------------) + I urakawa 0x00288ec6, // n0x0d8b c0x0000 (---------------) + I urausu 0x00206c44, // n0x0d8c c0x0000 (---------------) + I uryu 0x00200109, // n0x0d8d c0x0000 (---------------) + I utashinai 0x00342f08, // n0x0d8e c0x0000 (---------------) + I wakkanai 0x0024e6c7, // n0x0d8f c0x0000 (---------------) + I wassamu 0x00311fc6, // n0x0d90 c0x0000 (---------------) + I yakumo 0x00292f46, // n0x0d91 c0x0000 (---------------) + I yoichi 0x0035e144, // n0x0d92 c0x0000 (---------------) + I aioi 0x00341846, // n0x0d93 c0x0000 (---------------) + I akashi 0x00207e03, // n0x0d94 c0x0000 (---------------) + I ako 0x0038bd09, // n0x0d95 c0x0000 (---------------) + I amagasaki 0x00394b46, // n0x0d96 c0x0000 (---------------) + I aogaki 0x0028c7c5, // n0x0d97 c0x0000 (---------------) + I asago 0x00289c86, // n0x0d98 c0x0000 (---------------) + I ashiya 0x0028dcc5, // n0x0d99 c0x0000 (---------------) + I awaji 0x0026d348, // n0x0d9a c0x0000 (---------------) + I fukusaki 0x002faf87, // n0x0d9b c0x0000 (---------------) + I goshiki 0x002f8c46, // n0x0d9c c0x0000 (---------------) + I harima 0x0031c986, // n0x0d9d c0x0000 (---------------) + I himeji 0x00312b88, // n0x0d9e c0x0000 (---------------) + I ichikawa 0x0028ba47, // n0x0d9f c0x0000 (---------------) + I inagawa 0x00288605, // n0x0da0 c0x0000 (---------------) + I itami 0x0028a188, // n0x0da1 c0x0000 (---------------) + I kakogawa 0x003744c8, // n0x0da2 c0x0000 (---------------) + I kamigori 0x00304f08, // n0x0da3 c0x0000 (---------------) + I kamikawa 0x0021f105, // n0x0da4 c0x0000 (---------------) + I kasai 0x0027cf46, // n0x0da5 c0x0000 (---------------) + I kasuga 0x0022ed09, // n0x0da6 c0x0000 (---------------) + I kawanishi 0x0022ae44, // n0x0da7 c0x0000 (---------------) + I miki 0x00359a0b, // n0x0da8 c0x0000 (---------------) + I minamiawaji 0x0021ac8b, // n0x0da9 c0x0000 (---------------) + I nishinomiya 0x002998c9, // n0x0daa c0x0000 (---------------) + I nishiwaki 0x00207e83, // n0x0dab c0x0000 (---------------) + I ono 0x002453c5, // n0x0dac c0x0000 (---------------) + I sanda 0x00208a46, // n0x0dad c0x0000 (---------------) + I sannan 0x002937c8, // n0x0dae c0x0000 (---------------) + I sasayama 0x002349c4, // n0x0daf c0x0000 (---------------) + I sayo 0x002e6a46, // n0x0db0 c0x0000 (---------------) + I shingu 0x002ba609, // n0x0db1 c0x0000 (---------------) + I shinonsen 0x003081c5, // n0x0db2 c0x0000 (---------------) + I shiso 0x002c4946, // n0x0db3 c0x0000 (---------------) + I sumoto 0x0025fa46, // n0x0db4 c0x0000 (---------------) + I taishi 0x00209604, // n0x0db5 c0x0000 (---------------) + I taka 0x002875ca, // n0x0db6 c0x0000 (---------------) + I takarazuka 0x0028c708, // n0x0db7 c0x0000 (---------------) + I takasago 0x00245106, // n0x0db8 c0x0000 (---------------) + I takino 0x0035ee85, // n0x0db9 c0x0000 (---------------) + I tamba 0x00203987, // n0x0dba c0x0000 (---------------) + I tatsuno 0x0022e707, // n0x0dbb c0x0000 (---------------) + I toyooka 0x00389944, // n0x0dbc c0x0000 (---------------) + I yabu 0x0021aec7, // n0x0dbd c0x0000 (---------------) + I yashiro 0x002a0604, // n0x0dbe c0x0000 (---------------) + I yoka 0x00322c46, // n0x0dbf c0x0000 (---------------) + I yokawa 0x00204943, // n0x0dc0 c0x0000 (---------------) + I ami 0x002ad5c5, // n0x0dc1 c0x0000 (---------------) + I asahi 0x00346e05, // n0x0dc2 c0x0000 (---------------) + I bando 0x002e5708, // n0x0dc3 c0x0000 (---------------) + I chikusei 0x0024ef05, // n0x0dc4 c0x0000 (---------------) + I daigo 0x00268309, // n0x0dc5 c0x0000 (---------------) + I fujishiro 0x0028d547, // n0x0dc6 c0x0000 (---------------) + I hitachi 0x0029330b, // n0x0dc7 c0x0000 (---------------) + I hitachinaka 0x0028d54c, // n0x0dc8 c0x0000 (---------------) + I hitachiomiya 0x0028e50a, // n0x0dc9 c0x0000 (---------------) + I hitachiota 0x00316ac7, // n0x0dca c0x0000 (---------------) + I ibaraki 0x00200243, // n0x0dcb c0x0000 (---------------) + I ina 0x00291508, // n0x0dcc c0x0000 (---------------) + I inashiki 0x0021f2c5, // n0x0dcd c0x0000 (---------------) + I itako 0x002cae85, // n0x0dce c0x0000 (---------------) + I iwama 0x00207f44, // n0x0dcf c0x0000 (---------------) + I joso 0x002ae7c6, // n0x0dd0 c0x0000 (---------------) + I kamisu 0x0023b7c6, // n0x0dd1 c0x0000 (---------------) + I kasama 0x00341887, // n0x0dd2 c0x0000 (---------------) + I kashima 0x0020b60b, // n0x0dd3 c0x0000 (---------------) + I kasumigaura 0x00232c84, // n0x0dd4 c0x0000 (---------------) + I koga 0x0033ee44, // n0x0dd5 c0x0000 (---------------) + I miho 0x00246f04, // n0x0dd6 c0x0000 (---------------) + I mito 0x002b4f86, // n0x0dd7 c0x0000 (---------------) + I moriya 0x00204884, // n0x0dd8 c0x0000 (---------------) + I naka 0x00376c08, // n0x0dd9 c0x0000 (---------------) + I namegata 0x00321385, // n0x0dda c0x0000 (---------------) + I oarai 0x00204045, // n0x0ddb c0x0000 (---------------) + I ogawa 0x00393607, // n0x0ddc c0x0000 (---------------) + I omitama 0x00206c89, // n0x0ddd c0x0000 (---------------) + I ryugasaki 0x003396c5, // n0x0dde c0x0000 (---------------) + I sakai 0x0030cc0a, // n0x0ddf c0x0000 (---------------) + I sakuragawa 0x0027bc89, // n0x0de0 c0x0000 (---------------) + I shimodate 0x0027db0a, // n0x0de1 c0x0000 (---------------) + I shimotsuma 0x00395689, // n0x0de2 c0x0000 (---------------) + I shirosato 0x00339a04, // n0x0de3 c0x0000 (---------------) + I sowa 0x0029fdc5, // n0x0de4 c0x0000 (---------------) + I suifu 0x0029cec8, // n0x0de5 c0x0000 (---------------) + I takahagi 0x002d0fcb, // n0x0de6 c0x0000 (---------------) + I tamatsukuri 0x002df1c5, // n0x0de7 c0x0000 (---------------) + I tokai 0x00352046, // n0x0de8 c0x0000 (---------------) + I tomobe 0x0021a304, // n0x0de9 c0x0000 (---------------) + I tone 0x00268846, // n0x0dea c0x0000 (---------------) + I toride 0x0024e409, // n0x0deb c0x0000 (---------------) + I tsuchiura 0x0032d387, // n0x0dec c0x0000 (---------------) + I tsukuba 0x00387c88, // n0x0ded c0x0000 (---------------) + I uchihara 0x002315c6, // n0x0dee c0x0000 (---------------) + I ushiku 0x002e38c7, // n0x0def c0x0000 (---------------) + I yachiyo 0x0026dc08, // n0x0df0 c0x0000 (---------------) + I yamagata 0x00377b86, // n0x0df1 c0x0000 (---------------) + I yawara 0x00260d44, // n0x0df2 c0x0000 (---------------) + I yuki 0x0034af87, // n0x0df3 c0x0000 (---------------) + I anamizu 0x00336fc5, // n0x0df4 c0x0000 (---------------) + I hakui 0x0034be87, // n0x0df5 c0x0000 (---------------) + I hakusan 0x00281f04, // n0x0df6 c0x0000 (---------------) + I kaga 0x00226886, // n0x0df7 c0x0000 (---------------) + I kahoku 0x0037ffc8, // n0x0df8 c0x0000 (---------------) + I kanazawa 0x002826c8, // n0x0df9 c0x0000 (---------------) + I kawakita 0x002be447, // n0x0dfa c0x0000 (---------------) + I komatsu 0x0023fcc8, // n0x0dfb c0x0000 (---------------) + I nakanoto 0x0027e905, // n0x0dfc c0x0000 (---------------) + I nanao 0x00207cc4, // n0x0dfd c0x0000 (---------------) + I nomi 0x00312a88, // n0x0dfe c0x0000 (---------------) + I nonoichi 0x0023fdc4, // n0x0dff c0x0000 (---------------) + I noto 0x0020f2c5, // n0x0e00 c0x0000 (---------------) + I shika 0x002d2b84, // n0x0e01 c0x0000 (---------------) + I suzu 0x0027d707, // n0x0e02 c0x0000 (---------------) + I tsubata 0x0031c3c7, // n0x0e03 c0x0000 (---------------) + I tsurugi 0x0026e588, // n0x0e04 c0x0000 (---------------) + I uchinada 0x0028dd06, // n0x0e05 c0x0000 (---------------) + I wajima 0x0024ee85, // n0x0e06 c0x0000 (---------------) + I fudai 0x00268108, // n0x0e07 c0x0000 (---------------) + I fujisawa 0x00364a08, // n0x0e08 c0x0000 (---------------) + I hanamaki 0x0028b089, // n0x0e09 c0x0000 (---------------) + I hiraizumi 0x0021af86, // n0x0e0a c0x0000 (---------------) + I hirono 0x0029ba88, // n0x0e0b c0x0000 (---------------) + I ichinohe 0x0038f78a, // n0x0e0c c0x0000 (---------------) + I ichinoseki 0x00271fc8, // n0x0e0d c0x0000 (---------------) + I iwaizumi 0x002c3b85, // n0x0e0e c0x0000 (---------------) + I iwate 0x0031b686, // n0x0e0f c0x0000 (---------------) + I joboji 0x0027bb48, // n0x0e10 c0x0000 (---------------) + I kamaishi 0x0020deca, // n0x0e11 c0x0000 (---------------) + I kanegasaki 0x0032a887, // n0x0e12 c0x0000 (---------------) + I karumai 0x00273345, // n0x0e13 c0x0000 (---------------) + I kawai 0x00209588, // n0x0e14 c0x0000 (---------------) + I kitakami 0x00224704, // n0x0e15 c0x0000 (---------------) + I kuji 0x00205d06, // n0x0e16 c0x0000 (---------------) + I kunohe 0x002aa5c8, // n0x0e17 c0x0000 (---------------) + I kuzumaki 0x00207d46, // n0x0e18 c0x0000 (---------------) + I miyako 0x00304788, // n0x0e19 c0x0000 (---------------) + I mizusawa 0x0022ac87, // n0x0e1a c0x0000 (---------------) + I morioka 0x00205106, // n0x0e1b c0x0000 (---------------) + I ninohe 0x00384f84, // n0x0e1c c0x0000 (---------------) + I noda 0x0029a847, // n0x0e1d c0x0000 (---------------) + I ofunato 0x002e13c4, // n0x0e1e c0x0000 (---------------) + I oshu 0x0024e3c7, // n0x0e1f c0x0000 (---------------) + I otsuchi 0x0023430d, // n0x0e20 c0x0000 (---------------) + I rikuzentakata 0x0026d185, // n0x0e21 c0x0000 (---------------) + I shiwa 0x002a71cb, // n0x0e22 c0x0000 (---------------) + I shizukuishi 0x002fe746, // n0x0e23 c0x0000 (---------------) + I sumita 0x0023c788, // n0x0e24 c0x0000 (---------------) + I tanohata 0x00369804, // n0x0e25 c0x0000 (---------------) + I tono 0x00264306, // n0x0e26 c0x0000 (---------------) + I yahaba 0x0026b046, // n0x0e27 c0x0000 (---------------) + I yamada 0x0036c587, // n0x0e28 c0x0000 (---------------) + I ayagawa 0x00281d4d, // n0x0e29 c0x0000 (---------------) + I higashikagawa 0x002982c7, // n0x0e2a c0x0000 (---------------) + I kanonji 0x002e8108, // n0x0e2b c0x0000 (---------------) + I kotohira 0x00257385, // n0x0e2c c0x0000 (---------------) + I manno 0x00283488, // n0x0e2d c0x0000 (---------------) + I marugame 0x002aeac6, // n0x0e2e c0x0000 (---------------) + I mitoyo 0x0027e988, // n0x0e2f c0x0000 (---------------) + I naoshima 0x0020ce46, // n0x0e30 c0x0000 (---------------) + I sanuki 0x0031c2c7, // n0x0e31 c0x0000 (---------------) + I tadotsu 0x0026e909, // n0x0e32 c0x0000 (---------------) + I takamatsu 0x00369807, // n0x0e33 c0x0000 (---------------) + I tonosho 0x002761c8, // n0x0e34 c0x0000 (---------------) + I uchinomi 0x00261345, // n0x0e35 c0x0000 (---------------) + I utazu 0x00212c08, // n0x0e36 c0x0000 (---------------) + I zentsuji 0x00305dc5, // n0x0e37 c0x0000 (---------------) + I akune 0x00236bc5, // n0x0e38 c0x0000 (---------------) + I amami 0x0030fcc5, // n0x0e39 c0x0000 (---------------) + I hioki 0x00209883, // n0x0e3a c0x0000 (---------------) + I isa 0x0026f3c4, // n0x0e3b c0x0000 (---------------) + I isen 0x00209785, // n0x0e3c c0x0000 (---------------) + I izumi 0x00271789, // n0x0e3d c0x0000 (---------------) + I kagoshima 0x002b4d06, // n0x0e3e c0x0000 (---------------) + I kanoya 0x002c5c48, // n0x0e3f c0x0000 (---------------) + I kawanabe 0x002d3c45, // n0x0e40 c0x0000 (---------------) + I kinko 0x00314307, // n0x0e41 c0x0000 (---------------) + I kouyama 0x002d3a4a, // n0x0e42 c0x0000 (---------------) + I makurazaki 0x002c4889, // n0x0e43 c0x0000 (---------------) + I matsumoto 0x002bf68a, // n0x0e44 c0x0000 (---------------) + I minamitane 0x002bb148, // n0x0e45 c0x0000 (---------------) + I nakatane 0x0021df8c, // n0x0e46 c0x0000 (---------------) + I nishinoomote 0x0026f0cd, // n0x0e47 c0x0000 (---------------) + I satsumasendai 0x002da843, // n0x0e48 c0x0000 (---------------) + I soo 0x00304688, // n0x0e49 c0x0000 (---------------) + I tarumizu 0x00211dc5, // n0x0e4a c0x0000 (---------------) + I yusui 0x00343086, // n0x0e4b c0x0000 (---------------) + I aikawa 0x0033ea46, // n0x0e4c c0x0000 (---------------) + I atsugi 0x002c35c5, // n0x0e4d c0x0000 (---------------) + I ayase 0x00383449, // n0x0e4e c0x0000 (---------------) + I chigasaki 0x00240845, // n0x0e4f c0x0000 (---------------) + I ebina 0x00268108, // n0x0e50 c0x0000 (---------------) + I fujisawa 0x00265b06, // n0x0e51 c0x0000 (---------------) + I hadano 0x00328686, // n0x0e52 c0x0000 (---------------) + I hakone 0x0028c209, // n0x0e53 c0x0000 (---------------) + I hiratsuka 0x00377387, // n0x0e54 c0x0000 (---------------) + I isehara 0x00315c06, // n0x0e55 c0x0000 (---------------) + I kaisei 0x002d39c8, // n0x0e56 c0x0000 (---------------) + I kamakura 0x003823c8, // n0x0e57 c0x0000 (---------------) + I kiyokawa 0x0032b7c7, // n0x0e58 c0x0000 (---------------) + I matsuda 0x0025240e, // n0x0e59 c0x0000 (---------------) + I minamiashigara 0x002aed05, // n0x0e5a c0x0000 (---------------) + I miura 0x0023e405, // n0x0e5b c0x0000 (---------------) + I nakai 0x00207c48, // n0x0e5c c0x0000 (---------------) + I ninomiya 0x00202487, // n0x0e5d c0x0000 (---------------) + I odawara 0x00238bc2, // n0x0e5e c0x0000 (---------------) + I oi 0x002a6c04, // n0x0e5f c0x0000 (---------------) + I oiso 0x003636ca, // n0x0e60 c0x0000 (---------------) + I sagamihara 0x0024e788, // n0x0e61 c0x0000 (---------------) + I samukawa 0x00337906, // n0x0e62 c0x0000 (---------------) + I tsukui 0x00283b88, // n0x0e63 c0x0000 (---------------) + I yamakita 0x0022afc6, // n0x0e64 c0x0000 (---------------) + I yamato 0x00311d48, // n0x0e65 c0x0000 (---------------) + I yokosuka 0x00297548, // n0x0e66 c0x0000 (---------------) + I yugawara 0x00236b84, // n0x0e67 c0x0000 (---------------) + I zama 0x003185c5, // n0x0e68 c0x0000 (---------------) + I zushi 0x006735c4, // n0x0e69 c0x0001 (---------------) ! I city 0x006735c4, // n0x0e6a c0x0001 (---------------) ! I city 0x006735c4, // n0x0e6b c0x0001 (---------------) ! I city 0x00201ac3, // n0x0e6c c0x0000 (---------------) + I aki 0x002f3a86, // n0x0e6d c0x0000 (---------------) + I geisei 0x002685c6, // n0x0e6e c0x0000 (---------------) + I hidaka 0x0028888c, // n0x0e6f c0x0000 (---------------) + I higashitsuno 0x00201b43, // n0x0e70 c0x0000 (---------------) + I ino 0x002ab006, // n0x0e71 c0x0000 (---------------) + I kagami 0x00204904, // n0x0e72 c0x0000 (---------------) + I kami 0x0020e0c8, // n0x0e73 c0x0000 (---------------) + I kitagawa 0x002ba445, // n0x0e74 c0x0000 (---------------) + I kochi 0x003637c6, // n0x0e75 c0x0000 (---------------) + I mihara 0x002a2e48, // n0x0e76 c0x0000 (---------------) + I motoyama 0x002bc286, // n0x0e77 c0x0000 (---------------) + I muroto 0x002f8bc6, // n0x0e78 c0x0000 (---------------) + I nahari 0x00248448, // n0x0e79 c0x0000 (---------------) + I nakamura 0x00374747, // n0x0e7a c0x0000 (---------------) + I nankoku 0x00251f89, // n0x0e7b c0x0000 (---------------) + I nishitosa 0x00328d8a, // n0x0e7c c0x0000 (---------------) + I niyodogawa 0x00240384, // n0x0e7d c0x0000 (---------------) + I ochi 0x0022ecc5, // n0x0e7e c0x0000 (---------------) + I okawa 0x00286c45, // n0x0e7f c0x0000 (---------------) + I otoyo 0x0022a786, // n0x0e80 c0x0000 (---------------) + I otsuki 0x00240646, // n0x0e81 c0x0000 (---------------) + I sakawa 0x00291906, // n0x0e82 c0x0000 (---------------) + I sukumo 0x002d1e06, // n0x0e83 c0x0000 (---------------) + I susaki 0x002520c4, // n0x0e84 c0x0000 (---------------) + I tosa 0x002520cb, // n0x0e85 c0x0000 (---------------) + I tosashimizu 0x00221244, // n0x0e86 c0x0000 (---------------) + I toyo 0x00203a05, // n0x0e87 c0x0000 (---------------) + I tsuno 0x00296285, // n0x0e88 c0x0000 (---------------) + I umaji 0x00207006, // n0x0e89 c0x0000 (---------------) + I yasuda 0x00209f08, // n0x0e8a c0x0000 (---------------) + I yusuhara 0x0026ef87, // n0x0e8b c0x0000 (---------------) + I amakusa 0x0034e684, // n0x0e8c c0x0000 (---------------) + I arao 0x00209dc3, // n0x0e8d c0x0000 (---------------) + I aso 0x002e3545, // n0x0e8e c0x0000 (---------------) + I choyo 0x00351f07, // n0x0e8f c0x0000 (---------------) + I gyokuto 0x0028f9c9, // n0x0e90 c0x0000 (---------------) + I hitoyoshi 0x0026ee8b, // n0x0e91 c0x0000 (---------------) + I kamiamakusa 0x00341887, // n0x0e92 c0x0000 (---------------) + I kashima 0x0036c287, // n0x0e93 c0x0000 (---------------) + I kikuchi 0x002d4744, // n0x0e94 c0x0000 (---------------) + I kosa 0x002a2d48, // n0x0e95 c0x0000 (---------------) + I kumamoto 0x00253387, // n0x0e96 c0x0000 (---------------) + I mashiki 0x0028fc06, // n0x0e97 c0x0000 (---------------) + I mifune 0x00260ac8, // n0x0e98 c0x0000 (---------------) + I minamata 0x0029ee4b, // n0x0e99 c0x0000 (---------------) + I minamioguni 0x0034cac6, // n0x0e9a c0x0000 (---------------) + I nagasu 0x0020e649, // n0x0e9b c0x0000 (---------------) + I nishihara 0x0029efc5, // n0x0e9c c0x0000 (---------------) + I oguni 0x002e3dc3, // n0x0e9d c0x0000 (---------------) + I ozu 0x002c4946, // n0x0e9e c0x0000 (---------------) + I sumoto 0x0022ab88, // n0x0e9f c0x0000 (---------------) + I takamori 0x0020cf03, // n0x0ea0 c0x0000 (---------------) + I uki 0x002269c3, // n0x0ea1 c0x0000 (---------------) + I uto 0x0026dc06, // n0x0ea2 c0x0000 (---------------) + I yamaga 0x0022afc6, // n0x0ea3 c0x0000 (---------------) + I yamato 0x00373e8a, // n0x0ea4 c0x0000 (---------------) + I yatsushiro 0x00269e45, // n0x0ea5 c0x0000 (---------------) + I ayabe 0x0026ae8b, // n0x0ea6 c0x0000 (---------------) + I fukuchiyama 0x00289bcb, // n0x0ea7 c0x0000 (---------------) + I higashiyama 0x00229783, // n0x0ea8 c0x0000 (---------------) + I ide 0x00213cc3, // n0x0ea9 c0x0000 (---------------) + I ine 0x00298c44, // n0x0eaa c0x0000 (---------------) + I joyo 0x0023a807, // n0x0eab c0x0000 (---------------) + I kameoka 0x0022ac04, // n0x0eac c0x0000 (---------------) + I kamo 0x00206e44, // n0x0ead c0x0000 (---------------) + I kita 0x002f1c04, // n0x0eae c0x0000 (---------------) + I kizu 0x002722c8, // n0x0eaf c0x0000 (---------------) + I kumiyama 0x0035edc8, // n0x0eb0 c0x0000 (---------------) + I kyotamba 0x0030f889, // n0x0eb1 c0x0000 (---------------) + I kyotanabe 0x003165c8, // n0x0eb2 c0x0000 (---------------) + I kyotango 0x0030c047, // n0x0eb3 c0x0000 (---------------) + I maizuru 0x00213fc6, // n0x0eb4 c0x0000 (---------------) + I minami 0x002c588f, // n0x0eb5 c0x0000 (---------------) + I minamiyamashiro 0x002aee46, // n0x0eb6 c0x0000 (---------------) + I miyazu 0x002ba3c4, // n0x0eb7 c0x0000 (---------------) + I muko 0x0035ec0a, // n0x0eb8 c0x0000 (---------------) + I nagaokakyo 0x00351e07, // n0x0eb9 c0x0000 (---------------) + I nakagyo 0x00204d46, // n0x0eba c0x0000 (---------------) + I nantan 0x0027c389, // n0x0ebb c0x0000 (---------------) + I oyamazaki 0x0030f805, // n0x0ebc c0x0000 (---------------) + I sakyo 0x002c6f45, // n0x0ebd c0x0000 (---------------) + I seika 0x0030f946, // n0x0ebe c0x0000 (---------------) + I tanabe 0x00212d43, // n0x0ebf c0x0000 (---------------) + I uji 0x00224749, // n0x0ec0 c0x0000 (---------------) + I ujitawara 0x00214fc6, // n0x0ec1 c0x0000 (---------------) + I wazuka 0x0023aa49, // n0x0ec2 c0x0000 (---------------) + I yamashina 0x003804c6, // n0x0ec3 c0x0000 (---------------) + I yawata 0x002ad5c5, // n0x0ec4 c0x0000 (---------------) + I asahi 0x0035dd05, // n0x0ec5 c0x0000 (---------------) + I inabe 0x00233203, // n0x0ec6 c0x0000 (---------------) + I ise 0x0023a948, // n0x0ec7 c0x0000 (---------------) + I kameyama 0x002406c7, // n0x0ec8 c0x0000 (---------------) + I kawagoe 0x0037aec4, // n0x0ec9 c0x0000 (---------------) + I kiho 0x0022a888, // n0x0eca c0x0000 (---------------) + I kisosaki 0x002927c4, // n0x0ecb c0x0000 (---------------) + I kiwa 0x002d4306, // n0x0ecc c0x0000 (---------------) + I komono 0x00285906, // n0x0ecd c0x0000 (---------------) + I kumano 0x0022f386, // n0x0ece c0x0000 (---------------) + I kuwana 0x002b5109, // n0x0ecf c0x0000 (---------------) + I matsusaka 0x002cae05, // n0x0ed0 c0x0000 (---------------) + I meiwa 0x00292a46, // n0x0ed1 c0x0000 (---------------) + I mihama 0x00370d89, // n0x0ed2 c0x0000 (---------------) + I minamiise 0x002adc06, // n0x0ed3 c0x0000 (---------------) + I misugi 0x00272346, // n0x0ed4 c0x0000 (---------------) + I miyama 0x0036fe46, // n0x0ed5 c0x0000 (---------------) + I nabari 0x0021f645, // n0x0ed6 c0x0000 (---------------) + I shima 0x002d2b86, // n0x0ed7 c0x0000 (---------------) + I suzuka 0x0031c2c4, // n0x0ed8 c0x0000 (---------------) + I tado 0x0028ee85, // n0x0ed9 c0x0000 (---------------) + I taiki 0x00245104, // n0x0eda c0x0000 (---------------) + I taki 0x002f1b06, // n0x0edb c0x0000 (---------------) + I tamaki 0x00395844, // n0x0edc c0x0000 (---------------) + I toba 0x00203a03, // n0x0edd c0x0000 (---------------) + I tsu 0x00274845, // n0x0ede c0x0000 (---------------) + I udono 0x00227348, // n0x0edf c0x0000 (---------------) + I ureshino 0x00253ec7, // n0x0ee0 c0x0000 (---------------) + I watarai 0x00234a49, // n0x0ee1 c0x0000 (---------------) + I yokkaichi 0x00274a88, // n0x0ee2 c0x0000 (---------------) + I furukawa 0x002830d1, // n0x0ee3 c0x0000 (---------------) + I higashimatsushima 0x0025faca, // n0x0ee4 c0x0000 (---------------) + I ishinomaki 0x00316107, // n0x0ee5 c0x0000 (---------------) + I iwanuma 0x0038d846, // n0x0ee6 c0x0000 (---------------) + I kakuda 0x00204904, // n0x0ee7 c0x0000 (---------------) + I kami 0x002a8748, // n0x0ee8 c0x0000 (---------------) + I kawasaki 0x0034cc49, // n0x0ee9 c0x0000 (---------------) + I kesennuma 0x0028b408, // n0x0eea c0x0000 (---------------) + I marumori 0x0028328a, // n0x0eeb c0x0000 (---------------) + I matsushima 0x002b45cd, // n0x0eec c0x0000 (---------------) + I minamisanriku 0x0028b246, // n0x0eed c0x0000 (---------------) + I misato 0x00248546, // n0x0eee c0x0000 (---------------) + I murata 0x0029a906, // n0x0eef c0x0000 (---------------) + I natori 0x00204047, // n0x0ef0 c0x0000 (---------------) + I ogawara 0x002e81c5, // n0x0ef1 c0x0000 (---------------) + I ohira 0x00295c07, // n0x0ef2 c0x0000 (---------------) + I onagawa 0x0022a945, // n0x0ef3 c0x0000 (---------------) + I osaki 0x00294d84, // n0x0ef4 c0x0000 (---------------) + I rifu 0x0027c146, // n0x0ef5 c0x0000 (---------------) + I semine 0x003416c7, // n0x0ef6 c0x0000 (---------------) + I shibata 0x0022444d, // n0x0ef7 c0x0000 (---------------) + I shichikashuku 0x0027ba87, // n0x0ef8 c0x0000 (---------------) + I shikama 0x002471c8, // n0x0ef9 c0x0000 (---------------) + I shiogama 0x00268409, // n0x0efa c0x0000 (---------------) + I shiroishi 0x0031b586, // n0x0efb c0x0000 (---------------) + I tagajo 0x002e7445, // n0x0efc c0x0000 (---------------) + I taiwa 0x0020fe04, // n0x0efd c0x0000 (---------------) + I tome 0x00371186, // n0x0efe c0x0000 (---------------) + I tomiya 0x00389846, // n0x0eff c0x0000 (---------------) + I wakuya 0x0024e906, // n0x0f00 c0x0000 (---------------) + I watari 0x00286688, // n0x0f01 c0x0000 (---------------) + I yamamoto 0x00395443, // n0x0f02 c0x0000 (---------------) + I zao 0x00206fc3, // n0x0f03 c0x0000 (---------------) + I aya 0x0036cf45, // n0x0f04 c0x0000 (---------------) + I ebino 0x00375946, // n0x0f05 c0x0000 (---------------) + I gokase 0x00297505, // n0x0f06 c0x0000 (---------------) + I hyuga 0x002317c8, // n0x0f07 c0x0000 (---------------) + I kadogawa 0x002882ca, // n0x0f08 c0x0000 (---------------) + I kawaminami 0x00389a44, // n0x0f09 c0x0000 (---------------) + I kijo 0x0020e0c8, // n0x0f0a c0x0000 (---------------) + I kitagawa 0x002815c8, // n0x0f0b c0x0000 (---------------) + I kitakata 0x00206e47, // n0x0f0c c0x0000 (---------------) + I kitaura 0x002d3d09, // n0x0f0d c0x0000 (---------------) + I kobayashi 0x002a2a48, // n0x0f0e c0x0000 (---------------) + I kunitomi 0x0026d647, // n0x0f0f c0x0000 (---------------) + I kushima 0x0027cdc6, // n0x0f10 c0x0000 (---------------) + I mimata 0x00207d4a, // n0x0f11 c0x0000 (---------------) + I miyakonojo 0x00371208, // n0x0f12 c0x0000 (---------------) + I miyazaki 0x002ae609, // n0x0f13 c0x0000 (---------------) + I morotsuka 0x0027fa88, // n0x0f14 c0x0000 (---------------) + I nichinan 0x00217e09, // n0x0f15 c0x0000 (---------------) + I nishimera 0x00346687, // n0x0f16 c0x0000 (---------------) + I nobeoka 0x00302b45, // n0x0f17 c0x0000 (---------------) + I saito 0x00329e86, // n0x0f18 c0x0000 (---------------) + I shiiba 0x0028f5c8, // n0x0f19 c0x0000 (---------------) + I shintomi 0x0023ae48, // n0x0f1a c0x0000 (---------------) + I takaharu 0x002462c8, // n0x0f1b c0x0000 (---------------) + I takanabe 0x002f9c88, // n0x0f1c c0x0000 (---------------) + I takazaki 0x00203a05, // n0x0f1d c0x0000 (---------------) + I tsuno 0x0022e144, // n0x0f1e c0x0000 (---------------) + I achi 0x0034e008, // n0x0f1f c0x0000 (---------------) + I agematsu 0x00204e44, // n0x0f20 c0x0000 (---------------) + I anan 0x00395484, // n0x0f21 c0x0000 (---------------) + I aoki 0x002ad5c5, // n0x0f22 c0x0000 (---------------) + I asahi 0x0027ed87, // n0x0f23 c0x0000 (---------------) + I azumino 0x00206a49, // n0x0f24 c0x0000 (---------------) + I chikuhoku 0x0036c387, // n0x0f25 c0x0000 (---------------) + I chikuma 0x0022e185, // n0x0f26 c0x0000 (---------------) + I chino 0x00265906, // n0x0f27 c0x0000 (---------------) + I fujimi 0x003317c6, // n0x0f28 c0x0000 (---------------) + I hakuba 0x0020a004, // n0x0f29 c0x0000 (---------------) + I hara 0x0028c546, // n0x0f2a c0x0000 (---------------) + I hiraya 0x0024ecc4, // n0x0f2b c0x0000 (---------------) + I iida 0x00256486, // n0x0f2c c0x0000 (---------------) + I iijima 0x0034d2c6, // n0x0f2d c0x0000 (---------------) + I iiyama 0x0020ec86, // n0x0f2e c0x0000 (---------------) + I iizuna 0x00390e45, // n0x0f2f c0x0000 (---------------) + I ikeda 0x00231687, // n0x0f30 c0x0000 (---------------) + I ikusaka 0x00200243, // n0x0f31 c0x0000 (---------------) + I ina 0x0031e389, // n0x0f32 c0x0000 (---------------) + I karuizawa 0x00315908, // n0x0f33 c0x0000 (---------------) + I kawakami 0x0022a884, // n0x0f34 c0x0000 (---------------) + I kiso 0x0026d4cd, // n0x0f35 c0x0000 (---------------) + I kisofukushima 0x002827c8, // n0x0f36 c0x0000 (---------------) + I kitaaiki 0x002fa008, // n0x0f37 c0x0000 (---------------) + I komagane 0x002ae586, // n0x0f38 c0x0000 (---------------) + I komoro 0x0026ea09, // n0x0f39 c0x0000 (---------------) + I matsukawa 0x002c4889, // n0x0f3a c0x0000 (---------------) + I matsumoto 0x0024e105, // n0x0f3b c0x0000 (---------------) + I miasa 0x002883ca, // n0x0f3c c0x0000 (---------------) + I minamiaiki 0x0025b8ca, // n0x0f3d c0x0000 (---------------) + I minamimaki 0x002b064c, // n0x0f3e c0x0000 (---------------) + I minamiminowa 0x002b07c6, // n0x0f3f c0x0000 (---------------) + I minowa 0x00266386, // n0x0f40 c0x0000 (---------------) + I miyada 0x002af8c6, // n0x0f41 c0x0000 (---------------) + I miyota 0x00258b89, // n0x0f42 c0x0000 (---------------) + I mochizuki 0x0034e4c6, // n0x0f43 c0x0000 (---------------) + I nagano 0x0028ba86, // n0x0f44 c0x0000 (---------------) + I nagawa 0x00240906, // n0x0f45 c0x0000 (---------------) + I nagiso 0x002934c8, // n0x0f46 c0x0000 (---------------) + I nakagawa 0x0023fcc6, // n0x0f47 c0x0000 (---------------) + I nakano 0x002fe9cb, // n0x0f48 c0x0000 (---------------) + I nozawaonsen 0x0027ef05, // n0x0f49 c0x0000 (---------------) + I obuse 0x00204045, // n0x0f4a c0x0000 (---------------) + I ogawa 0x00266605, // n0x0f4b c0x0000 (---------------) + I okaya 0x00353c06, // n0x0f4c c0x0000 (---------------) + I omachi 0x00207d03, // n0x0f4d c0x0000 (---------------) + I omi 0x0022f306, // n0x0f4e c0x0000 (---------------) + I ookuwa 0x0027ba07, // n0x0f4f c0x0000 (---------------) + I ooshika 0x002a8605, // n0x0f50 c0x0000 (---------------) + I otaki 0x003389c5, // n0x0f51 c0x0000 (---------------) + I otari 0x0036ba45, // n0x0f52 c0x0000 (---------------) + I sakae 0x00201a06, // n0x0f53 c0x0000 (---------------) + I sakaki 0x0024e1c4, // n0x0f54 c0x0000 (---------------) + I saku 0x0035fb46, // n0x0f55 c0x0000 (---------------) + I sakuho 0x00325709, // n0x0f56 c0x0000 (---------------) + I shimosuwa 0x00353a8c, // n0x0f57 c0x0000 (---------------) + I shinanomachi 0x00294ac8, // n0x0f58 c0x0000 (---------------) + I shiojiri 0x002e5544, // n0x0f59 c0x0000 (---------------) + I suwa 0x002d2806, // n0x0f5a c0x0000 (---------------) + I suzaka 0x002fe846, // n0x0f5b c0x0000 (---------------) + I takagi 0x0022ab88, // n0x0f5c c0x0000 (---------------) + I takamori 0x0020f408, // n0x0f5d c0x0000 (---------------) + I takayama 0x00353989, // n0x0f5e c0x0000 (---------------) + I tateshina 0x00203987, // n0x0f5f c0x0000 (---------------) + I tatsuno 0x002e5d09, // n0x0f60 c0x0000 (---------------) + I togakushi 0x0025e506, // n0x0f61 c0x0000 (---------------) + I togura 0x002204c4, // n0x0f62 c0x0000 (---------------) + I tomi 0x00207204, // n0x0f63 c0x0000 (---------------) + I ueda 0x0023e8c4, // n0x0f64 c0x0000 (---------------) + I wada 0x0026dc08, // n0x0f65 c0x0000 (---------------) + I yamagata 0x0020688a, // n0x0f66 c0x0000 (---------------) + I yamanouchi 0x00339646, // n0x0f67 c0x0000 (---------------) + I yasaka 0x0033e847, // n0x0f68 c0x0000 (---------------) + I yasuoka 0x002e9747, // n0x0f69 c0x0000 (---------------) + I chijiwa 0x0021edc5, // n0x0f6a c0x0000 (---------------) + I futsu 0x00286c04, // n0x0f6b c0x0000 (---------------) + I goto 0x0027a8c6, // n0x0f6c c0x0000 (---------------) + I hasami 0x002e8206, // n0x0f6d c0x0000 (---------------) + I hirado 0x00206743, // n0x0f6e c0x0000 (---------------) + I iki 0x00315747, // n0x0f6f c0x0000 (---------------) + I isahaya 0x003108c8, // n0x0f70 c0x0000 (---------------) + I kawatana 0x0024e24a, // n0x0f71 c0x0000 (---------------) + I kuchinotsu 0x002bcc48, // n0x0f72 c0x0000 (---------------) + I matsuura 0x0036c108, // n0x0f73 c0x0000 (---------------) + I nagasaki 0x00395885, // n0x0f74 c0x0000 (---------------) + I obama 0x0023a1c5, // n0x0f75 c0x0000 (---------------) + I omura 0x00366645, // n0x0f76 c0x0000 (---------------) + I oseto 0x0021f186, // n0x0f77 c0x0000 (---------------) + I saikai 0x0029be46, // n0x0f78 c0x0000 (---------------) + I sasebo 0x002e5845, // n0x0f79 c0x0000 (---------------) + I seihi 0x0038bf49, // n0x0f7a c0x0000 (---------------) + I shimabara 0x00286a0c, // n0x0f7b c0x0000 (---------------) + I shinkamigoto 0x00226a07, // n0x0f7c c0x0000 (---------------) + I togitsu 0x00283308, // n0x0f7d c0x0000 (---------------) + I tsushima 0x00279c05, // n0x0f7e c0x0000 (---------------) + I unzen 0x006735c4, // n0x0f7f c0x0001 (---------------) ! I city 0x00346e44, // n0x0f80 c0x0000 (---------------) + I ando 0x0026e184, // n0x0f81 c0x0000 (---------------) + I gose 0x0022e2c6, // n0x0f82 c0x0000 (---------------) + I heguri 0x0028a74e, // n0x0f83 c0x0000 (---------------) + I higashiyoshino 0x00344187, // n0x0f84 c0x0000 (---------------) + I ikaruga 0x00204245, // n0x0f85 c0x0000 (---------------) + I ikoma 0x0022adcc, // n0x0f86 c0x0000 (---------------) + I kamikitayama 0x00292687, // n0x0f87 c0x0000 (---------------) + I kanmaki 0x00341647, // n0x0f88 c0x0000 (---------------) + I kashiba 0x00344809, // n0x0f89 c0x0000 (---------------) + I kashihara 0x002133c9, // n0x0f8a c0x0000 (---------------) + I katsuragi 0x00273345, // n0x0f8b c0x0000 (---------------) + I kawai 0x00315908, // n0x0f8c c0x0000 (---------------) + I kawakami 0x0022ed09, // n0x0f8d c0x0000 (---------------) + I kawanishi 0x002c9885, // n0x0f8e c0x0000 (---------------) + I koryo 0x002a8548, // n0x0f8f c0x0000 (---------------) + I kurotaki 0x002b5f46, // n0x0f90 c0x0000 (---------------) + I mitsue 0x002a5986, // n0x0f91 c0x0000 (---------------) + I miyake 0x002da0c4, // n0x0f92 c0x0000 (---------------) + I nara 0x00257448, // n0x0f93 c0x0000 (---------------) + I nosegawa 0x002432c3, // n0x0f94 c0x0000 (---------------) + I oji 0x00392684, // n0x0f95 c0x0000 (---------------) + I ouda 0x002e35c5, // n0x0f96 c0x0000 (---------------) + I oyodo 0x002f4d47, // n0x0f97 c0x0000 (---------------) + I sakurai 0x00202285, // n0x0f98 c0x0000 (---------------) + I sango 0x0038f649, // n0x0f99 c0x0000 (---------------) + I shimoichi 0x00267dcd, // n0x0f9a c0x0000 (---------------) + I shimokitayama 0x00285306, // n0x0f9b c0x0000 (---------------) + I shinjo 0x00220944, // n0x0f9c c0x0000 (---------------) + I soni 0x00335dc8, // n0x0f9d c0x0000 (---------------) + I takatori 0x0025ca0a, // n0x0f9e c0x0000 (---------------) + I tawaramoto 0x00203207, // n0x0f9f c0x0000 (---------------) + I tenkawa 0x0027be45, // n0x0fa0 c0x0000 (---------------) + I tenri 0x002070c3, // n0x0fa1 c0x0000 (---------------) + I uda 0x00289d8e, // n0x0fa2 c0x0000 (---------------) + I yamatokoriyama 0x0022afcc, // n0x0fa3 c0x0000 (---------------) + I yamatotakada 0x0027b147, // n0x0fa4 c0x0000 (---------------) + I yamazoe 0x0028a907, // n0x0fa5 c0x0000 (---------------) + I yoshino 0x002015c3, // n0x0fa6 c0x0000 (---------------) + I aga 0x0034e505, // n0x0fa7 c0x0000 (---------------) + I agano 0x0026e185, // n0x0fa8 c0x0000 (---------------) + I gosen 0x00283f48, // n0x0fa9 c0x0000 (---------------) + I itoigawa 0x00281409, // n0x0faa c0x0000 (---------------) + I izumozaki 0x0026a386, // n0x0fab c0x0000 (---------------) + I joetsu 0x0022ac04, // n0x0fac c0x0000 (---------------) + I kamo 0x00316046, // n0x0fad c0x0000 (---------------) + I kariwa 0x0038218b, // n0x0fae c0x0000 (---------------) + I kashiwazaki 0x002c460c, // n0x0faf c0x0000 (---------------) + I minamiuonuma 0x0026c3c7, // n0x0fb0 c0x0000 (---------------) + I mitsuke 0x002ba105, // n0x0fb1 c0x0000 (---------------) + I muika 0x003743c8, // n0x0fb2 c0x0000 (---------------) + I murakami 0x0032b585, // n0x0fb3 c0x0000 (---------------) + I myoko 0x0035ec07, // n0x0fb4 c0x0000 (---------------) + I nagaoka 0x0025f907, // n0x0fb5 c0x0000 (---------------) + I niigata 0x002432c5, // n0x0fb6 c0x0000 (---------------) + I ojiya 0x00207d03, // n0x0fb7 c0x0000 (---------------) + I omi 0x002109c4, // n0x0fb8 c0x0000 (---------------) + I sado 0x00203845, // n0x0fb9 c0x0000 (---------------) + I sanjo 0x002f3b45, // n0x0fba c0x0000 (---------------) + I seiro 0x002f3b46, // n0x0fbb c0x0000 (---------------) + I seirou 0x00274588, // n0x0fbc c0x0000 (---------------) + I sekikawa 0x003416c7, // n0x0fbd c0x0000 (---------------) + I shibata 0x0033ed46, // n0x0fbe c0x0000 (---------------) + I tagami 0x0031abc6, // n0x0fbf c0x0000 (---------------) + I tainai 0x0030fc06, // n0x0fc0 c0x0000 (---------------) + I tochio 0x002e1589, // n0x0fc1 c0x0000 (---------------) + I tokamachi 0x0031adc7, // n0x0fc2 c0x0000 (---------------) + I tsubame 0x00207306, // n0x0fc3 c0x0000 (---------------) + I tsunan 0x002c4786, // n0x0fc4 c0x0000 (---------------) + I uonuma 0x00243386, // n0x0fc5 c0x0000 (---------------) + I yahiko 0x00298cc5, // n0x0fc6 c0x0000 (---------------) + I yoita 0x00216b86, // n0x0fc7 c0x0000 (---------------) + I yuzawa 0x0034c845, // n0x0fc8 c0x0000 (---------------) + I beppu 0x002a55c8, // n0x0fc9 c0x0000 (---------------) + I bungoono 0x0024facb, // n0x0fca c0x0000 (---------------) + I bungotakada 0x0027a6c6, // n0x0fcb c0x0000 (---------------) + I hasama 0x002e9784, // n0x0fcc c0x0000 (---------------) + I hiji 0x00336449, // n0x0fcd c0x0000 (---------------) + I himeshima 0x0028d544, // n0x0fce c0x0000 (---------------) + I hita 0x002b5ec8, // n0x0fcf c0x0000 (---------------) + I kamitsue 0x0027b5c7, // n0x0fd0 c0x0000 (---------------) + I kokonoe 0x0026ff44, // n0x0fd1 c0x0000 (---------------) + I kuju 0x002a0f48, // n0x0fd2 c0x0000 (---------------) + I kunisaki 0x002a9c04, // n0x0fd3 c0x0000 (---------------) + I kusu 0x00298d04, // n0x0fd4 c0x0000 (---------------) + I oita 0x002a7585, // n0x0fd5 c0x0000 (---------------) + I saiki 0x00335cc6, // n0x0fd6 c0x0000 (---------------) + I taketa 0x00272207, // n0x0fd7 c0x0000 (---------------) + I tsukumi 0x00222503, // n0x0fd8 c0x0000 (---------------) + I usa 0x00288f85, // n0x0fd9 c0x0000 (---------------) + I usuki 0x002ab604, // n0x0fda c0x0000 (---------------) + I yufu 0x0023e446, // n0x0fdb c0x0000 (---------------) + I akaiwa 0x0024e188, // n0x0fdc c0x0000 (---------------) + I asakuchi 0x00310605, // n0x0fdd c0x0000 (---------------) + I bizen 0x0027e449, // n0x0fde c0x0000 (---------------) + I hayashima 0x002b9fc5, // n0x0fdf c0x0000 (---------------) + I ibara 0x002ab008, // n0x0fe0 c0x0000 (---------------) + I kagamino 0x00340b47, // n0x0fe1 c0x0000 (---------------) + I kasaoka 0x0035c188, // n0x0fe2 c0x0000 (---------------) + I kibichuo 0x002a0447, // n0x0fe3 c0x0000 (---------------) + I kumenan 0x0025adc9, // n0x0fe4 c0x0000 (---------------) + I kurashiki 0x002487c6, // n0x0fe5 c0x0000 (---------------) + I maniwa 0x00303986, // n0x0fe6 c0x0000 (---------------) + I misaki 0x00240904, // n0x0fe7 c0x0000 (---------------) + I nagi 0x0027cd05, // n0x0fe8 c0x0000 (---------------) + I niimi 0x002dac0c, // n0x0fe9 c0x0000 (---------------) + I nishiawakura 0x00266607, // n0x0fea c0x0000 (---------------) + I okayama 0x00266c47, // n0x0feb c0x0000 (---------------) + I satosho 0x002e9608, // n0x0fec c0x0000 (---------------) + I setouchi 0x00285306, // n0x0fed c0x0000 (---------------) + I shinjo 0x00340f44, // n0x0fee c0x0000 (---------------) + I shoo 0x0030ad04, // n0x0fef c0x0000 (---------------) + I soja 0x0023c909, // n0x0ff0 c0x0000 (---------------) + I takahashi 0x002af9c6, // n0x0ff1 c0x0000 (---------------) + I tamano 0x002601c7, // n0x0ff2 c0x0000 (---------------) + I tsuyama 0x00295d44, // n0x0ff3 c0x0000 (---------------) + I wake 0x002b4e06, // n0x0ff4 c0x0000 (---------------) + I yakage 0x00342185, // n0x0ff5 c0x0000 (---------------) + I aguni 0x0028d847, // n0x0ff6 c0x0000 (---------------) + I ginowan 0x002fe946, // n0x0ff7 c0x0000 (---------------) + I ginoza 0x00239cc9, // n0x0ff8 c0x0000 (---------------) + I gushikami 0x002b0487, // n0x0ff9 c0x0000 (---------------) + I haebaru 0x002545c7, // n0x0ffa c0x0000 (---------------) + I higashi 0x0028c086, // n0x0ffb c0x0000 (---------------) + I hirara 0x00231145, // n0x0ffc c0x0000 (---------------) + I iheya 0x0026cf88, // n0x0ffd c0x0000 (---------------) + I ishigaki 0x00214e48, // n0x0ffe c0x0000 (---------------) + I ishikawa 0x0022a5c6, // n0x0fff c0x0000 (---------------) + I itoman 0x00310645, // n0x1000 c0x0000 (---------------) + I izena 0x002f0446, // n0x1001 c0x0000 (---------------) + I kadena 0x00201b03, // n0x1002 c0x0000 (---------------) + I kin 0x00283dc9, // n0x1003 c0x0000 (---------------) + I kitadaito 0x0029168e, // n0x1004 c0x0000 (---------------) + I kitanakagusuku 0x0029f548, // n0x1005 c0x0000 (---------------) + I kumejima 0x002928c8, // n0x1006 c0x0000 (---------------) + I kunigami 0x0022a3cb, // n0x1007 c0x0000 (---------------) + I minamidaito 0x0027e686, // n0x1008 c0x0000 (---------------) + I motobu 0x002402c4, // n0x1009 c0x0000 (---------------) + I nago 0x0026ecc4, // n0x100a c0x0000 (---------------) + I naha 0x0029178a, // n0x100b c0x0000 (---------------) + I nakagusuku 0x0020d7c7, // n0x100c c0x0000 (---------------) + I nakijin 0x002073c5, // n0x100d c0x0000 (---------------) + I nanjo 0x0020e649, // n0x100e c0x0000 (---------------) + I nishihara 0x002a6885, // n0x100f c0x0000 (---------------) + I ogimi 0x003954c7, // n0x1010 c0x0000 (---------------) + I okinawa 0x002988c4, // n0x1011 c0x0000 (---------------) + I onna 0x00265dc7, // n0x1012 c0x0000 (---------------) + I shimoji 0x003162c8, // n0x1013 c0x0000 (---------------) + I taketomi 0x002a43c6, // n0x1014 c0x0000 (---------------) + I tarama 0x002065c9, // n0x1015 c0x0000 (---------------) + I tokashiki 0x002a2b4a, // n0x1016 c0x0000 (---------------) + I tomigusuku 0x0020d746, // n0x1017 c0x0000 (---------------) + I tonaki 0x00282306, // n0x1018 c0x0000 (---------------) + I urasoe 0x00296205, // n0x1019 c0x0000 (---------------) + I uruma 0x00361285, // n0x101a c0x0000 (---------------) + I yaese 0x00305787, // n0x101b c0x0000 (---------------) + I yomitan 0x00309c08, // n0x101c c0x0000 (---------------) + I yonabaru 0x003420c8, // n0x101d c0x0000 (---------------) + I yonaguni 0x00236b86, // n0x101e c0x0000 (---------------) + I zamami 0x0031d9c5, // n0x101f c0x0000 (---------------) + I abeno 0x002403ce, // n0x1020 c0x0000 (---------------) + I chihayaakasaka 0x002be904, // n0x1021 c0x0000 (---------------) + I chuo 0x0022a545, // n0x1022 c0x0000 (---------------) + I daito 0x00265289, // n0x1023 c0x0000 (---------------) + I fujiidera 0x00273148, // n0x1024 c0x0000 (---------------) + I habikino 0x00278046, // n0x1025 c0x0000 (---------------) + I hannan 0x0028630c, // n0x1026 c0x0000 (---------------) + I higashiosaka 0x00287ed0, // n0x1027 c0x0000 (---------------) + I higashisumiyoshi 0x0028a38f, // n0x1028 c0x0000 (---------------) + I higashiyodogawa 0x0028b7c8, // n0x1029 c0x0000 (---------------) + I hirakata 0x00316ac7, // n0x102a c0x0000 (---------------) + I ibaraki 0x00390e45, // n0x102b c0x0000 (---------------) + I ikeda 0x00209785, // n0x102c c0x0000 (---------------) + I izumi 0x00272089, // n0x102d c0x0000 (---------------) + I izumiotsu 0x00209789, // n0x102e c0x0000 (---------------) + I izumisano 0x00216406, // n0x102f c0x0000 (---------------) + I kadoma 0x002df247, // n0x1030 c0x0000 (---------------) + I kaizuka 0x0037c505, // n0x1031 c0x0000 (---------------) + I kanan 0x00375c89, // n0x1032 c0x0000 (---------------) + I kashiwara 0x003175c6, // n0x1033 c0x0000 (---------------) + I katano 0x0034e30d, // n0x1034 c0x0000 (---------------) + I kawachinagano 0x0026d109, // n0x1035 c0x0000 (---------------) + I kishiwada 0x00206e44, // n0x1036 c0x0000 (---------------) + I kita 0x0029f2c8, // n0x1037 c0x0000 (---------------) + I kumatori 0x0034e0c9, // n0x1038 c0x0000 (---------------) + I matsubara 0x00339806, // n0x1039 c0x0000 (---------------) + I minato 0x00265a05, // n0x103a c0x0000 (---------------) + I minoh 0x00303986, // n0x103b c0x0000 (---------------) + I misaki 0x00387b49, // n0x103c c0x0000 (---------------) + I moriguchi 0x003896c8, // n0x103d c0x0000 (---------------) + I neyagawa 0x00208b85, // n0x103e c0x0000 (---------------) + I nishi 0x00257444, // n0x103f c0x0000 (---------------) + I nose 0x002864cb, // n0x1040 c0x0000 (---------------) + I osakasayama 0x003396c5, // n0x1041 c0x0000 (---------------) + I sakai 0x00286606, // n0x1042 c0x0000 (---------------) + I sayama 0x0026f406, // n0x1043 c0x0000 (---------------) + I sennan 0x00243d86, // n0x1044 c0x0000 (---------------) + I settsu 0x003260cb, // n0x1045 c0x0000 (---------------) + I shijonawate 0x0027e549, // n0x1046 c0x0000 (---------------) + I shimamoto 0x002e5b85, // n0x1047 c0x0000 (---------------) + I suita 0x0035bf47, // n0x1048 c0x0000 (---------------) + I tadaoka 0x0025fa46, // n0x1049 c0x0000 (---------------) + I taishi 0x002345c6, // n0x104a c0x0000 (---------------) + I tajiri 0x0026df08, // n0x104b c0x0000 (---------------) + I takaishi 0x00376d89, // n0x104c c0x0000 (---------------) + I takatsuki 0x00246f8c, // n0x104d c0x0000 (---------------) + I tondabayashi 0x00351d08, // n0x104e c0x0000 (---------------) + I toyonaka 0x002260c6, // n0x104f c0x0000 (---------------) + I toyono 0x00330543, // n0x1050 c0x0000 (---------------) + I yao 0x0027ebc6, // n0x1051 c0x0000 (---------------) + I ariake 0x0025ac85, // n0x1052 c0x0000 (---------------) + I arita 0x0026b1c8, // n0x1053 c0x0000 (---------------) + I fukudomi 0x0021b746, // n0x1054 c0x0000 (---------------) + I genkai 0x0028da88, // n0x1055 c0x0000 (---------------) + I hamatama 0x00228245, // n0x1056 c0x0000 (---------------) + I hizen 0x00352985, // n0x1057 c0x0000 (---------------) + I imari 0x002877c8, // n0x1058 c0x0000 (---------------) + I kamimine 0x002d2c87, // n0x1059 c0x0000 (---------------) + I kanzaki 0x0033e987, // n0x105a c0x0000 (---------------) + I karatsu 0x00341887, // n0x105b c0x0000 (---------------) + I kashima 0x0022aa08, // n0x105c c0x0000 (---------------) + I kitagata 0x00316c08, // n0x105d c0x0000 (---------------) + I kitahata 0x00253286, // n0x105e c0x0000 (---------------) + I kiyama 0x002f1947, // n0x105f c0x0000 (---------------) + I kouhoku 0x002896c7, // n0x1060 c0x0000 (---------------) + I kyuragi 0x00325dca, // n0x1061 c0x0000 (---------------) + I nishiarita 0x00212803, // n0x1062 c0x0000 (---------------) + I ogi 0x00353c06, // n0x1063 c0x0000 (---------------) + I omachi 0x002069c5, // n0x1064 c0x0000 (---------------) + I ouchi 0x00275104, // n0x1065 c0x0000 (---------------) + I saga 0x00268409, // n0x1066 c0x0000 (---------------) + I shiroishi 0x0025ad44, // n0x1067 c0x0000 (---------------) + I taku 0x00253f44, // n0x1068 c0x0000 (---------------) + I tara 0x002891c4, // n0x1069 c0x0000 (---------------) + I tosu 0x0028a90b, // n0x106a c0x0000 (---------------) + I yoshinogari 0x0034e247, // n0x106b c0x0000 (---------------) + I arakawa 0x00240605, // n0x106c c0x0000 (---------------) + I asaka 0x00280ac8, // n0x106d c0x0000 (---------------) + I chichibu 0x00265906, // n0x106e c0x0000 (---------------) + I fujimi 0x00265908, // n0x106f c0x0000 (---------------) + I fujimino 0x00269d86, // n0x1070 c0x0000 (---------------) + I fukaya 0x00278e45, // n0x1071 c0x0000 (---------------) + I hanno 0x002794c5, // n0x1072 c0x0000 (---------------) + I hanyu 0x0027b306, // n0x1073 c0x0000 (---------------) + I hasuda 0x0027b788, // n0x1074 c0x0000 (---------------) + I hatogaya 0x0027c2c8, // n0x1075 c0x0000 (---------------) + I hatoyama 0x002685c6, // n0x1076 c0x0000 (---------------) + I hidaka 0x0028090f, // n0x1077 c0x0000 (---------------) + I higashichichibu 0x00283890, // n0x1078 c0x0000 (---------------) + I higashimatsuyama 0x002028c5, // n0x1079 c0x0000 (---------------) + I honjo 0x00200243, // n0x107a c0x0000 (---------------) + I ina 0x002797c5, // n0x107b c0x0000 (---------------) + I iruma 0x0030b3c8, // n0x107c c0x0000 (---------------) + I iwatsuki 0x00209689, // n0x107d c0x0000 (---------------) + I kamiizumi 0x00304f08, // n0x107e c0x0000 (---------------) + I kamikawa 0x00340c88, // n0x107f c0x0000 (---------------) + I kamisato 0x00391808, // n0x1080 c0x0000 (---------------) + I kasukabe 0x002406c7, // n0x1081 c0x0000 (---------------) + I kawagoe 0x002655c9, // n0x1082 c0x0000 (---------------) + I kawaguchi 0x0028dc88, // n0x1083 c0x0000 (---------------) + I kawajima 0x00369344, // n0x1084 c0x0000 (---------------) + I kazo 0x00289048, // n0x1085 c0x0000 (---------------) + I kitamoto 0x0028ec09, // n0x1086 c0x0000 (---------------) + I koshigaya 0x00307ec7, // n0x1087 c0x0000 (---------------) + I kounosu 0x00293e04, // n0x1088 c0x0000 (---------------) + I kuki 0x0036c448, // n0x1089 c0x0000 (---------------) + I kumagaya 0x0023144a, // n0x108a c0x0000 (---------------) + I matsubushi 0x0031ef46, // n0x108b c0x0000 (---------------) + I minano 0x0028b246, // n0x108c c0x0000 (---------------) + I misato 0x0021ae49, // n0x108d c0x0000 (---------------) + I miyashiro 0x00288107, // n0x108e c0x0000 (---------------) + I miyoshi 0x002b62c8, // n0x108f c0x0000 (---------------) + I moroyama 0x00201588, // n0x1090 c0x0000 (---------------) + I nagatoro 0x00342d88, // n0x1091 c0x0000 (---------------) + I namegawa 0x003721c5, // n0x1092 c0x0000 (---------------) + I niiza 0x00362605, // n0x1093 c0x0000 (---------------) + I ogano 0x00204045, // n0x1094 c0x0000 (---------------) + I ogawa 0x0026e145, // n0x1095 c0x0000 (---------------) + I ogose 0x00259347, // n0x1096 c0x0000 (---------------) + I okegawa 0x00207d05, // n0x1097 c0x0000 (---------------) + I omiya 0x002a8605, // n0x1098 c0x0000 (---------------) + I otaki 0x00386ac6, // n0x1099 c0x0000 (---------------) + I ranzan 0x00304e47, // n0x109a c0x0000 (---------------) + I ryokami 0x002d0f07, // n0x109b c0x0000 (---------------) + I saitama 0x00231746, // n0x109c c0x0000 (---------------) + I sakado 0x002bb685, // n0x109d c0x0000 (---------------) + I satte 0x00286606, // n0x109e c0x0000 (---------------) + I sayama 0x002066c5, // n0x109f c0x0000 (---------------) + I shiki 0x00298148, // n0x10a0 c0x0000 (---------------) + I shiraoka 0x002cc0c4, // n0x10a1 c0x0000 (---------------) + I soka 0x002adc86, // n0x10a2 c0x0000 (---------------) + I sugito 0x00312e84, // n0x10a3 c0x0000 (---------------) + I toda 0x002add88, // n0x10a4 c0x0000 (---------------) + I tokigawa 0x00302c0a, // n0x10a5 c0x0000 (---------------) + I tokorozawa 0x0027700c, // n0x10a6 c0x0000 (---------------) + I tsurugashima 0x0020b805, // n0x10a7 c0x0000 (---------------) + I urawa 0x00204106, // n0x10a8 c0x0000 (---------------) + I warabi 0x00247146, // n0x10a9 c0x0000 (---------------) + I yashio 0x002f5606, // n0x10aa c0x0000 (---------------) + I yokoze 0x00226144, // n0x10ab c0x0000 (---------------) + I yono 0x00375b45, // n0x10ac c0x0000 (---------------) + I yorii 0x00269bc7, // n0x10ad c0x0000 (---------------) + I yoshida 0x00288189, // n0x10ae c0x0000 (---------------) + I yoshikawa 0x0028fac7, // n0x10af c0x0000 (---------------) + I yoshimi 0x006735c4, // n0x10b0 c0x0001 (---------------) ! I city 0x006735c4, // n0x10b1 c0x0001 (---------------) ! I city 0x002f59c5, // n0x10b2 c0x0000 (---------------) + I aisho 0x0023dd44, // n0x10b3 c0x0000 (---------------) + I gamo 0x00285cca, // n0x10b4 c0x0000 (---------------) + I higashiomi 0x00265786, // n0x10b5 c0x0000 (---------------) + I hikone 0x00346344, // n0x10b6 c0x0000 (---------------) + I koka 0x00204cc5, // n0x10b7 c0x0000 (---------------) + I konan 0x002d7bc5, // n0x10b8 c0x0000 (---------------) + I kosei 0x002e8104, // n0x10b9 c0x0000 (---------------) + I koto 0x0026f047, // n0x10ba c0x0000 (---------------) + I kusatsu 0x002b9f47, // n0x10bb c0x0000 (---------------) + I maibara 0x002b4f88, // n0x10bc c0x0000 (---------------) + I moriyama 0x0036df48, // n0x10bd c0x0000 (---------------) + I nagahama 0x00208b89, // n0x10be c0x0000 (---------------) + I nishiazai 0x003176c8, // n0x10bf c0x0000 (---------------) + I notogawa 0x00285e8b, // n0x10c0 c0x0000 (---------------) + I omihachiman 0x0022a784, // n0x10c1 c0x0000 (---------------) + I otsu 0x0025e445, // n0x10c2 c0x0000 (---------------) + I ritto 0x00258dc5, // n0x10c3 c0x0000 (---------------) + I ryuoh 0x00341809, // n0x10c4 c0x0000 (---------------) + I takashima 0x00376d89, // n0x10c5 c0x0000 (---------------) + I takatsuki 0x00336348, // n0x10c6 c0x0000 (---------------) + I torahime 0x00233d48, // n0x10c7 c0x0000 (---------------) + I toyosato 0x00207004, // n0x10c8 c0x0000 (---------------) + I yasu 0x002fe885, // n0x10c9 c0x0000 (---------------) + I akagi 0x002068c3, // n0x10ca c0x0000 (---------------) + I ama 0x0022a745, // n0x10cb c0x0000 (---------------) + I gotsu 0x00292ac6, // n0x10cc c0x0000 (---------------) + I hamada 0x0028124c, // n0x10cd c0x0000 (---------------) + I higashiizumo 0x00214ec6, // n0x10ce c0x0000 (---------------) + I hikawa 0x002fb046, // n0x10cf c0x0000 (---------------) + I hikimi 0x002782c5, // n0x10d0 c0x0000 (---------------) + I izumo 0x00201a88, // n0x10d1 c0x0000 (---------------) + I kakinoki 0x002a2fc6, // n0x10d2 c0x0000 (---------------) + I masuda 0x0038d9c6, // n0x10d3 c0x0000 (---------------) + I matsue 0x0028b246, // n0x10d4 c0x0000 (---------------) + I misato 0x0021f48c, // n0x10d5 c0x0000 (---------------) + I nishinoshima 0x0024eac4, // n0x10d6 c0x0000 (---------------) + I ohda 0x0030fd4a, // n0x10d7 c0x0000 (---------------) + I okinoshima 0x00278208, // n0x10d8 c0x0000 (---------------) + I okuizumo 0x00281087, // n0x10d9 c0x0000 (---------------) + I shimane 0x00260c46, // n0x10da c0x0000 (---------------) + I tamayu 0x002e5507, // n0x10db c0x0000 (---------------) + I tsuwano 0x002ca4c5, // n0x10dc c0x0000 (---------------) + I unnan 0x00311fc6, // n0x10dd c0x0000 (---------------) + I yakumo 0x0033ba46, // n0x10de c0x0000 (---------------) + I yasugi 0x00365987, // n0x10df c0x0000 (---------------) + I yatsuka 0x00253f84, // n0x10e0 c0x0000 (---------------) + I arai 0x0027d805, // n0x10e1 c0x0000 (---------------) + I atami 0x00265284, // n0x10e2 c0x0000 (---------------) + I fuji 0x00294e07, // n0x10e3 c0x0000 (---------------) + I fujieda 0x002654c8, // n0x10e4 c0x0000 (---------------) + I fujikawa 0x0026620a, // n0x10e5 c0x0000 (---------------) + I fujinomiya 0x0026ce07, // n0x10e6 c0x0000 (---------------) + I fukuroi 0x00271047, // n0x10e7 c0x0000 (---------------) + I gotemba 0x00316a47, // n0x10e8 c0x0000 (---------------) + I haibara 0x0032b6c9, // n0x10e9 c0x0000 (---------------) + I hamamatsu 0x0028124a, // n0x10ea c0x0000 (---------------) + I higashiizu 0x00220483, // n0x10eb c0x0000 (---------------) + I ito 0x00253e85, // n0x10ec c0x0000 (---------------) + I iwata 0x00209783, // n0x10ed c0x0000 (---------------) + I izu 0x002f1c49, // n0x10ee c0x0000 (---------------) + I izunokuni 0x002c7008, // n0x10ef c0x0000 (---------------) + I kakegawa 0x002d17c7, // n0x10f0 c0x0000 (---------------) + I kannami 0x00305009, // n0x10f1 c0x0000 (---------------) + I kawanehon 0x00214f46, // n0x10f2 c0x0000 (---------------) + I kawazu 0x0025fcc8, // n0x10f3 c0x0000 (---------------) + I kikugawa 0x002d4745, // n0x10f4 c0x0000 (---------------) + I kosai 0x00364b0a, // n0x10f5 c0x0000 (---------------) + I makinohara 0x00355209, // n0x10f6 c0x0000 (---------------) + I matsuzaki 0x00246c49, // n0x10f7 c0x0000 (---------------) + I minamiizu 0x00392cc7, // n0x10f8 c0x0000 (---------------) + I mishima 0x0028b509, // n0x10f9 c0x0000 (---------------) + I morimachi 0x0020eb88, // n0x10fa c0x0000 (---------------) + I nishiizu 0x002d2986, // n0x10fb c0x0000 (---------------) + I numazu 0x002042c8, // n0x10fc c0x0000 (---------------) + I omaezaki 0x0034e807, // n0x10fd c0x0000 (---------------) + I shimada 0x002521c7, // n0x10fe c0x0000 (---------------) + I shimizu 0x0027bc87, // n0x10ff c0x0000 (---------------) + I shimoda 0x002b4b88, // n0x1100 c0x0000 (---------------) + I shizuoka 0x002d2686, // n0x1101 c0x0000 (---------------) + I susono 0x00231205, // n0x1102 c0x0000 (---------------) + I yaizu 0x00269bc7, // n0x1103 c0x0000 (---------------) + I yoshida 0x00281e08, // n0x1104 c0x0000 (---------------) + I ashikaga 0x0030f544, // n0x1105 c0x0000 (---------------) + I bato 0x002d6e04, // n0x1106 c0x0000 (---------------) + I haga 0x00315b07, // n0x1107 c0x0000 (---------------) + I ichikai 0x00255847, // n0x1108 c0x0000 (---------------) + I iwafune 0x0022eb8a, // n0x1109 c0x0000 (---------------) + I kaminokawa 0x002d2906, // n0x110a c0x0000 (---------------) + I kanuma 0x0027afca, // n0x110b c0x0000 (---------------) + I karasuyama 0x002a6b47, // n0x110c c0x0000 (---------------) + I kuroiso 0x002be6c7, // n0x110d c0x0000 (---------------) + I mashiko 0x0024fa44, // n0x110e c0x0000 (---------------) + I mibu 0x002669c4, // n0x110f c0x0000 (---------------) + I moka 0x0021ff46, // n0x1110 c0x0000 (---------------) + I motegi 0x002efac4, // n0x1111 c0x0000 (---------------) + I nasu 0x002efacc, // n0x1112 c0x0000 (---------------) + I nasushiobara 0x0033e185, // n0x1113 c0x0000 (---------------) + I nikko 0x0020f249, // n0x1114 c0x0000 (---------------) + I nishikata 0x00267304, // n0x1115 c0x0000 (---------------) + I nogi 0x002e81c5, // n0x1116 c0x0000 (---------------) + I ohira 0x0025c988, // n0x1117 c0x0000 (---------------) + I ohtawara 0x0027c385, // n0x1118 c0x0000 (---------------) + I oyama 0x002f4d46, // n0x1119 c0x0000 (---------------) + I sakura 0x002098c4, // n0x111a c0x0000 (---------------) + I sano 0x0027924a, // n0x111b c0x0000 (---------------) + I shimotsuke 0x002d80c6, // n0x111c c0x0000 (---------------) + I shioya 0x00316d8a, // n0x111d c0x0000 (---------------) + I takanezawa 0x0030f5c7, // n0x111e c0x0000 (---------------) + I tochigi 0x0021d305, // n0x111f c0x0000 (---------------) + I tsuga 0x00212d45, // n0x1120 c0x0000 (---------------) + I ujiie 0x0021ee0a, // n0x1121 c0x0000 (---------------) + I utsunomiya 0x0028c645, // n0x1122 c0x0000 (---------------) + I yaita 0x00272046, // n0x1123 c0x0000 (---------------) + I aizumi 0x00204e44, // n0x1124 c0x0000 (---------------) + I anan 0x002a0706, // n0x1125 c0x0000 (---------------) + I ichiba 0x00305845, // n0x1126 c0x0000 (---------------) + I itano 0x0021b806, // n0x1127 c0x0000 (---------------) + I kainan 0x002be44c, // n0x1128 c0x0000 (---------------) + I komatsushima 0x002b644a, // n0x1129 c0x0000 (---------------) + I matsushige 0x0025b9c4, // n0x112a c0x0000 (---------------) + I mima 0x00213fc6, // n0x112b c0x0000 (---------------) + I minami 0x00288107, // n0x112c c0x0000 (---------------) + I miyoshi 0x002b9b44, // n0x112d c0x0000 (---------------) + I mugi 0x002934c8, // n0x112e c0x0000 (---------------) + I nakagawa 0x00376a06, // n0x112f c0x0000 (---------------) + I naruto 0x00240249, // n0x1130 c0x0000 (---------------) + I sanagochi 0x002c2189, // n0x1131 c0x0000 (---------------) + I shishikui 0x0028e2c9, // n0x1132 c0x0000 (---------------) + I tokushima 0x00359bc6, // n0x1133 c0x0000 (---------------) + I wajiki 0x0034e906, // n0x1134 c0x0000 (---------------) + I adachi 0x00204407, // n0x1135 c0x0000 (---------------) + I akiruno 0x0038be88, // n0x1136 c0x0000 (---------------) + I akishima 0x0034e709, // n0x1137 c0x0000 (---------------) + I aogashima 0x0034e247, // n0x1138 c0x0000 (---------------) + I arakawa 0x0027e786, // n0x1139 c0x0000 (---------------) + I bunkyo 0x002e3947, // n0x113a c0x0000 (---------------) + I chiyoda 0x0029a7c5, // n0x113b c0x0000 (---------------) + I chofu 0x002be904, // n0x113c c0x0000 (---------------) + I chuo 0x00203fc7, // n0x113d c0x0000 (---------------) + I edogawa 0x002ab685, // n0x113e c0x0000 (---------------) + I fuchu 0x00275045, // n0x113f c0x0000 (---------------) + I fussa 0x00389ec7, // n0x1140 c0x0000 (---------------) + I hachijo 0x00243188, // n0x1141 c0x0000 (---------------) + I hachioji 0x00374346, // n0x1142 c0x0000 (---------------) + I hamura 0x00282c8d, // n0x1143 c0x0000 (---------------) + I higashikurume 0x0028414f, // n0x1144 c0x0000 (---------------) + I higashimurayama 0x00289bcd, // n0x1145 c0x0000 (---------------) + I higashiyamato 0x0021ad44, // n0x1146 c0x0000 (---------------) + I hino 0x00227446, // n0x1147 c0x0000 (---------------) + I hinode 0x002bcf88, // n0x1148 c0x0000 (---------------) + I hinohara 0x002408c5, // n0x1149 c0x0000 (---------------) + I inagi 0x00325f88, // n0x114a c0x0000 (---------------) + I itabashi 0x002513ca, // n0x114b c0x0000 (---------------) + I katsushika 0x00206e44, // n0x114c c0x0000 (---------------) + I kita 0x002978c6, // n0x114d c0x0000 (---------------) + I kiyose 0x002a3687, // n0x114e c0x0000 (---------------) + I kodaira 0x00232c87, // n0x114f c0x0000 (---------------) + I koganei 0x00374809, // n0x1150 c0x0000 (---------------) + I kokubunji 0x00204285, // n0x1151 c0x0000 (---------------) + I komae 0x002e8104, // n0x1152 c0x0000 (---------------) + I koto 0x0031850a, // n0x1153 c0x0000 (---------------) + I kouzushima 0x002a2089, // n0x1154 c0x0000 (---------------) + I kunitachi 0x0028b607, // n0x1155 c0x0000 (---------------) + I machida 0x002b1286, // n0x1156 c0x0000 (---------------) + I meguro 0x00339806, // n0x1157 c0x0000 (---------------) + I minato 0x002fe7c6, // n0x1158 c0x0000 (---------------) + I mitaka 0x0034b046, // n0x1159 c0x0000 (---------------) + I mizuho 0x002bc90f, // n0x115a c0x0000 (---------------) + I musashimurayama 0x002bce49, // n0x115b c0x0000 (---------------) + I musashino 0x0023fcc6, // n0x115c c0x0000 (---------------) + I nakano 0x003528c6, // n0x115d c0x0000 (---------------) + I nerima 0x00301849, // n0x115e c0x0000 (---------------) + I ogasawara 0x002f1a47, // n0x115f c0x0000 (---------------) + I okutama 0x0020b3c3, // n0x1160 c0x0000 (---------------) + I ome 0x0021f606, // n0x1161 c0x0000 (---------------) + I oshima 0x00203943, // n0x1162 c0x0000 (---------------) + I ota 0x002c3488, // n0x1163 c0x0000 (---------------) + I setagaya 0x002e3787, // n0x1164 c0x0000 (---------------) + I shibuya 0x0028b9c9, // n0x1165 c0x0000 (---------------) + I shinagawa 0x00285788, // n0x1166 c0x0000 (---------------) + I shinjuku 0x0033eac8, // n0x1167 c0x0000 (---------------) + I suginami 0x00289246, // n0x1168 c0x0000 (---------------) + I sumida 0x0032da89, // n0x1169 c0x0000 (---------------) + I tachikawa 0x002e5c45, // n0x116a c0x0000 (---------------) + I taito 0x00260c44, // n0x116b c0x0000 (---------------) + I tama 0x002d0a47, // n0x116c c0x0000 (---------------) + I toshima 0x00258c05, // n0x116d c0x0000 (---------------) + I chizu 0x0021ad44, // n0x116e c0x0000 (---------------) + I hino 0x00274b88, // n0x116f c0x0000 (---------------) + I kawahara 0x0020da84, // n0x1170 c0x0000 (---------------) + I koge 0x002eaf87, // n0x1171 c0x0000 (---------------) + I kotoura 0x003337c6, // n0x1172 c0x0000 (---------------) + I misasa 0x002c6705, // n0x1173 c0x0000 (---------------) + I nanbu 0x0027fa88, // n0x1174 c0x0000 (---------------) + I nichinan 0x003396cb, // n0x1175 c0x0000 (---------------) + I sakaiminato 0x002e2787, // n0x1176 c0x0000 (---------------) + I tottori 0x0021f086, // n0x1177 c0x0000 (---------------) + I wakasa 0x002aeec4, // n0x1178 c0x0000 (---------------) + I yazu 0x0032b186, // n0x1179 c0x0000 (---------------) + I yonago 0x002ad5c5, // n0x117a c0x0000 (---------------) + I asahi 0x002ab685, // n0x117b c0x0000 (---------------) + I fuchu 0x0026c2c9, // n0x117c c0x0000 (---------------) + I fukumitsu 0x0026ec49, // n0x117d c0x0000 (---------------) + I funahashi 0x00252204, // n0x117e c0x0000 (---------------) + I himi 0x00252245, // n0x117f c0x0000 (---------------) + I imizu 0x00214005, // n0x1180 c0x0000 (---------------) + I inami 0x00364986, // n0x1181 c0x0000 (---------------) + I johana 0x00315a08, // n0x1182 c0x0000 (---------------) + I kamiichi 0x002a4c46, // n0x1183 c0x0000 (---------------) + I kurobe 0x0031070b, // n0x1184 c0x0000 (---------------) + I nakaniikawa 0x0029894a, // n0x1185 c0x0000 (---------------) + I namerikawa 0x002e14c5, // n0x1186 c0x0000 (---------------) + I nanto 0x00279546, // n0x1187 c0x0000 (---------------) + I nyuzen 0x0031d945, // n0x1188 c0x0000 (---------------) + I oyabe 0x00205705, // n0x1189 c0x0000 (---------------) + I taira 0x00281747, // n0x118a c0x0000 (---------------) + I takaoka 0x0038a708, // n0x118b c0x0000 (---------------) + I tateyama 0x0027b804, // n0x118c c0x0000 (---------------) + I toga 0x0024e006, // n0x118d c0x0000 (---------------) + I tonami 0x0027c346, // n0x118e c0x0000 (---------------) + I toyama 0x0020ed47, // n0x118f c0x0000 (---------------) + I unazuki 0x002e3d84, // n0x1190 c0x0000 (---------------) + I uozu 0x0026b046, // n0x1191 c0x0000 (---------------) + I yamada 0x00250d45, // n0x1192 c0x0000 (---------------) + I arida 0x00250d49, // n0x1193 c0x0000 (---------------) + I aridagawa 0x0034eb04, // n0x1194 c0x0000 (---------------) + I gobo 0x00286d89, // n0x1195 c0x0000 (---------------) + I hashimoto 0x002685c6, // n0x1196 c0x0000 (---------------) + I hidaka 0x002a9408, // n0x1197 c0x0000 (---------------) + I hirogawa 0x00214005, // n0x1198 c0x0000 (---------------) + I inami 0x002e9845, // n0x1199 c0x0000 (---------------) + I iwade 0x0021b806, // n0x119a c0x0000 (---------------) + I kainan 0x00246e89, // n0x119b c0x0000 (---------------) + I kamitonda 0x002133c9, // n0x119c c0x0000 (---------------) + I katsuragi 0x002fb0c6, // n0x119d c0x0000 (---------------) + I kimino 0x00273248, // n0x119e c0x0000 (---------------) + I kinokawa 0x0022aec8, // n0x119f c0x0000 (---------------) + I kitayama 0x0031d904, // n0x11a0 c0x0000 (---------------) + I koya 0x0034b544, // n0x11a1 c0x0000 (---------------) + I koza 0x0034b548, // n0x11a2 c0x0000 (---------------) + I kozagawa 0x003000c8, // n0x11a3 c0x0000 (---------------) + I kudoyama 0x002e5e09, // n0x11a4 c0x0000 (---------------) + I kushimoto 0x00292a46, // n0x11a5 c0x0000 (---------------) + I mihama 0x0028b246, // n0x11a6 c0x0000 (---------------) + I misato 0x002fd2cd, // n0x11a7 c0x0000 (---------------) + I nachikatsuura 0x002e6a46, // n0x11a8 c0x0000 (---------------) + I shingu 0x002a1409, // n0x11a9 c0x0000 (---------------) + I shirahama 0x00353dc5, // n0x11aa c0x0000 (---------------) + I taiji 0x0030f946, // n0x11ab c0x0000 (---------------) + I tanabe 0x0032dc48, // n0x11ac c0x0000 (---------------) + I wakayama 0x002f9ac5, // n0x11ad c0x0000 (---------------) + I yuasa 0x00289704, // n0x11ae c0x0000 (---------------) + I yura 0x002ad5c5, // n0x11af c0x0000 (---------------) + I asahi 0x0026e788, // n0x11b0 c0x0000 (---------------) + I funagata 0x00285a89, // n0x11b1 c0x0000 (---------------) + I higashine 0x00265344, // n0x11b2 c0x0000 (---------------) + I iide 0x00226886, // n0x11b3 c0x0000 (---------------) + I kahoku 0x003467ca, // n0x11b4 c0x0000 (---------------) + I kaminoyama 0x002150c8, // n0x11b5 c0x0000 (---------------) + I kaneyama 0x0022ed09, // n0x11b6 c0x0000 (---------------) + I kawanishi 0x002f8d4a, // n0x11b7 c0x0000 (---------------) + I mamurogawa 0x00304f86, // n0x11b8 c0x0000 (---------------) + I mikawa 0x00284308, // n0x11b9 c0x0000 (---------------) + I murayama 0x0035e9c5, // n0x11ba c0x0000 (---------------) + I nagai 0x00355088, // n0x11bb c0x0000 (---------------) + I nakayama 0x002a0545, // n0x11bc c0x0000 (---------------) + I nanyo 0x00214e09, // n0x11bd c0x0000 (---------------) + I nishikawa 0x0034fd89, // n0x11be c0x0000 (---------------) + I obanazawa 0x00210a82, // n0x11bf c0x0000 (---------------) + I oe 0x0029efc5, // n0x11c0 c0x0000 (---------------) + I oguni 0x00258e86, // n0x11c1 c0x0000 (---------------) + I ohkura 0x00268507, // n0x11c2 c0x0000 (---------------) + I oishida 0x00275105, // n0x11c3 c0x0000 (---------------) + I sagae 0x002f9b86, // n0x11c4 c0x0000 (---------------) + I sakata 0x00359408, // n0x11c5 c0x0000 (---------------) + I sakegawa 0x00285306, // n0x11c6 c0x0000 (---------------) + I shinjo 0x0029cd89, // n0x11c7 c0x0000 (---------------) + I shirataka 0x00266d46, // n0x11c8 c0x0000 (---------------) + I shonai 0x0026dd88, // n0x11c9 c0x0000 (---------------) + I takahata 0x00294245, // n0x11ca c0x0000 (---------------) + I tendo 0x00247ec6, // n0x11cb c0x0000 (---------------) + I tozawa 0x003052c8, // n0x11cc c0x0000 (---------------) + I tsuruoka 0x0026dc08, // n0x11cd c0x0000 (---------------) + I yamagata 0x0034d348, // n0x11ce c0x0000 (---------------) + I yamanobe 0x002212c8, // n0x11cf c0x0000 (---------------) + I yonezawa 0x00216b84, // n0x11d0 c0x0000 (---------------) + I yuza 0x0021bc43, // n0x11d1 c0x0000 (---------------) + I abu 0x0029cfc4, // n0x11d2 c0x0000 (---------------) + I hagi 0x002af4c6, // n0x11d3 c0x0000 (---------------) + I hikari 0x0029a804, // n0x11d4 c0x0000 (---------------) + I hofu 0x00292807, // n0x11d5 c0x0000 (---------------) + I iwakuni 0x0038d8c9, // n0x11d6 c0x0000 (---------------) + I kudamatsu 0x002ae205, // n0x11d7 c0x0000 (---------------) + I mitou 0x00201586, // n0x11d8 c0x0000 (---------------) + I nagato 0x0021f606, // n0x11d9 c0x0000 (---------------) + I oshima 0x002743cb, // n0x11da c0x0000 (---------------) + I shimonoseki 0x002e1406, // n0x11db c0x0000 (---------------) + I shunan 0x003003c6, // n0x11dc c0x0000 (---------------) + I tabuse 0x00286f48, // n0x11dd c0x0000 (---------------) + I tokuyama 0x00338906, // n0x11de c0x0000 (---------------) + I toyota 0x002b48c3, // n0x11df c0x0000 (---------------) + I ube 0x00213ec3, // n0x11e0 c0x0000 (---------------) + I yuu 0x002be904, // n0x11e1 c0x0000 (---------------) + I chuo 0x002243c5, // n0x11e2 c0x0000 (---------------) + I doshi 0x00289887, // n0x11e3 c0x0000 (---------------) + I fuefuki 0x002654c8, // n0x11e4 c0x0000 (---------------) + I fujikawa 0x002654cf, // n0x11e5 c0x0000 (---------------) + I fujikawaguchiko 0x00269acb, // n0x11e6 c0x0000 (---------------) + I fujiyoshida 0x00315808, // n0x11e7 c0x0000 (---------------) + I hayakawa 0x00226906, // n0x11e8 c0x0000 (---------------) + I hokuto 0x00312b8e, // n0x11e9 c0x0000 (---------------) + I ichikawamisato 0x0021b803, // n0x11ea c0x0000 (---------------) + I kai 0x0024cf84, // n0x11eb c0x0000 (---------------) + I kofu 0x002e1385, // n0x11ec c0x0000 (---------------) + I koshu 0x002e4a46, // n0x11ed c0x0000 (---------------) + I kosuge 0x0027a9cb, // n0x11ee c0x0000 (---------------) + I minami-alps 0x0027ee46, // n0x11ef c0x0000 (---------------) + I minobu 0x00204889, // n0x11f0 c0x0000 (---------------) + I nakamichi 0x002c6705, // n0x11f1 c0x0000 (---------------) + I nanbu 0x00372f88, // n0x11f2 c0x0000 (---------------) + I narusawa 0x00208608, // n0x11f3 c0x0000 (---------------) + I nirasaki 0x0021328c, // n0x11f4 c0x0000 (---------------) + I nishikatsura 0x0028a946, // n0x11f5 c0x0000 (---------------) + I oshino 0x0022a786, // n0x11f6 c0x0000 (---------------) + I otsuki 0x002b3885, // n0x11f7 c0x0000 (---------------) + I showa 0x00275f88, // n0x11f8 c0x0000 (---------------) + I tabayama 0x0026a445, // n0x11f9 c0x0000 (---------------) + I tsuru 0x0038dac8, // n0x11fa c0x0000 (---------------) + I uenohara 0x0028a00a, // n0x11fb c0x0000 (---------------) + I yamanakako 0x0029b889, // n0x11fc c0x0000 (---------------) + I yamanashi 0x006735c4, // n0x11fd c0x0001 (---------------) ! I city 0x2d600742, // n0x11fe c0x00b5 (n0x11ff-n0x1200) o I co 0x000e4188, // n0x11ff c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1200 c0x0000 (---------------) + I com 0x002d75c3, // n0x1201 c0x0000 (---------------) + I edu 0x0021e283, // n0x1202 c0x0000 (---------------) + I gov 0x0023fa03, // n0x1203 c0x0000 (---------------) + I mil 0x002170c3, // n0x1204 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1205 c0x0000 (---------------) + I org 0x00310603, // n0x1206 c0x0000 (---------------) + I biz 0x00222ac3, // n0x1207 c0x0000 (---------------) + I com 0x002d75c3, // n0x1208 c0x0000 (---------------) + I edu 0x0021e283, // n0x1209 c0x0000 (---------------) + I gov 0x00200304, // n0x120a c0x0000 (---------------) + I info 0x002170c3, // n0x120b c0x0000 (---------------) + I net 0x0021dcc3, // n0x120c c0x0000 (---------------) + I org 0x002362c3, // n0x120d c0x0000 (---------------) + I ass 0x002729c4, // n0x120e c0x0000 (---------------) + I asso 0x00222ac3, // n0x120f c0x0000 (---------------) + I com 0x00228d44, // n0x1210 c0x0000 (---------------) + I coop 0x002d75c3, // n0x1211 c0x0000 (---------------) + I edu 0x003579c4, // n0x1212 c0x0000 (---------------) + I gouv 0x0021e283, // n0x1213 c0x0000 (---------------) + I gov 0x002753c7, // n0x1214 c0x0000 (---------------) + I medecin 0x0023fa03, // n0x1215 c0x0000 (---------------) + I mil 0x00207cc3, // n0x1216 c0x0000 (---------------) + I nom 0x00265c08, // n0x1217 c0x0000 (---------------) + I notaires 0x0021dcc3, // n0x1218 c0x0000 (---------------) + I org 0x002e078b, // n0x1219 c0x0000 (---------------) + I pharmaciens 0x002ca783, // n0x121a c0x0000 (---------------) + I prd 0x0029abc6, // n0x121b c0x0000 (---------------) + I presse 0x00208902, // n0x121c c0x0000 (---------------) + I tm 0x0036b18b, // n0x121d c0x0000 (---------------) + I veterinaire 0x002d75c3, // n0x121e c0x0000 (---------------) + I edu 0x0021e283, // n0x121f c0x0000 (---------------) + I gov 0x002170c3, // n0x1220 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1221 c0x0000 (---------------) + I org 0x00222ac3, // n0x1222 c0x0000 (---------------) + I com 0x002d75c3, // n0x1223 c0x0000 (---------------) + I edu 0x0021e283, // n0x1224 c0x0000 (---------------) + I gov 0x0021dcc3, // n0x1225 c0x0000 (---------------) + I org 0x002117c3, // n0x1226 c0x0000 (---------------) + I rep 0x00210103, // n0x1227 c0x0000 (---------------) + I tra 0x00201e82, // n0x1228 c0x0000 (---------------) + I ac 0x000e4188, // n0x1229 c0x0000 (---------------) + blogspot 0x002224c5, // n0x122a c0x0000 (---------------) + I busan 0x002ea8c8, // n0x122b c0x0000 (---------------) + I chungbuk 0x002ec1c8, // n0x122c c0x0000 (---------------) + I chungnam 0x00200742, // n0x122d c0x0000 (---------------) + I co 0x0032b905, // n0x122e c0x0000 (---------------) + I daegu 0x0023e947, // n0x122f c0x0000 (---------------) + I daejeon 0x002010c2, // n0x1230 c0x0000 (---------------) + I es 0x00204ac7, // n0x1231 c0x0000 (---------------) + I gangwon 0x00202342, // n0x1232 c0x0000 (---------------) + I go 0x00370b47, // n0x1233 c0x0000 (---------------) + I gwangju 0x00384c89, // n0x1234 c0x0000 (---------------) + I gyeongbuk 0x0035e588, // n0x1235 c0x0000 (---------------) + I gyeonggi 0x00342c09, // n0x1236 c0x0000 (---------------) + I gyeongnam 0x00203802, // n0x1237 c0x0000 (---------------) + I hs 0x002c2a87, // n0x1238 c0x0000 (---------------) + I incheon 0x002fae44, // n0x1239 c0x0000 (---------------) + I jeju 0x0023ea07, // n0x123a c0x0000 (---------------) + I jeonbuk 0x00298847, // n0x123b c0x0000 (---------------) + I jeonnam 0x002a3fc2, // n0x123c c0x0000 (---------------) + I kg 0x0023fa03, // n0x123d c0x0000 (---------------) + I mil 0x00209282, // n0x123e c0x0000 (---------------) + I ms 0x00201082, // n0x123f c0x0000 (---------------) + I ne 0x00200c42, // n0x1240 c0x0000 (---------------) + I or 0x00214942, // n0x1241 c0x0000 (---------------) + I pe 0x002030c2, // n0x1242 c0x0000 (---------------) + I re 0x00200982, // n0x1243 c0x0000 (---------------) + I sc 0x002baac5, // n0x1244 c0x0000 (---------------) + I seoul 0x002376c5, // n0x1245 c0x0000 (---------------) + I ulsan 0x00222ac3, // n0x1246 c0x0000 (---------------) + I com 0x002d75c3, // n0x1247 c0x0000 (---------------) + I edu 0x0021e283, // n0x1248 c0x0000 (---------------) + I gov 0x002170c3, // n0x1249 c0x0000 (---------------) + I net 0x0021dcc3, // n0x124a c0x0000 (---------------) + I org 0x00222ac3, // n0x124b c0x0000 (---------------) + I com 0x002d75c3, // n0x124c c0x0000 (---------------) + I edu 0x0021e283, // n0x124d c0x0000 (---------------) + I gov 0x0023fa03, // n0x124e c0x0000 (---------------) + I mil 0x002170c3, // n0x124f c0x0000 (---------------) + I net 0x0021dcc3, // n0x1250 c0x0000 (---------------) + I org 0x00000741, // n0x1251 c0x0000 (---------------) + c 0x00222ac3, // n0x1252 c0x0000 (---------------) + I com 0x002d75c3, // n0x1253 c0x0000 (---------------) + I edu 0x0021e283, // n0x1254 c0x0000 (---------------) + I gov 0x00200304, // n0x1255 c0x0000 (---------------) + I info 0x00238c03, // n0x1256 c0x0000 (---------------) + I int 0x002170c3, // n0x1257 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1258 c0x0000 (---------------) + I org 0x00214943, // n0x1259 c0x0000 (---------------) + I per 0x00222ac3, // n0x125a c0x0000 (---------------) + I com 0x002d75c3, // n0x125b c0x0000 (---------------) + I edu 0x0021e283, // n0x125c c0x0000 (---------------) + I gov 0x002170c3, // n0x125d c0x0000 (---------------) + I net 0x0021dcc3, // n0x125e c0x0000 (---------------) + I org 0x00200742, // n0x125f c0x0000 (---------------) + I co 0x00222ac3, // n0x1260 c0x0000 (---------------) + I com 0x002d75c3, // n0x1261 c0x0000 (---------------) + I edu 0x0021e283, // n0x1262 c0x0000 (---------------) + I gov 0x002170c3, // n0x1263 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1264 c0x0000 (---------------) + I org 0x000e4188, // n0x1265 c0x0000 (---------------) + blogspot 0x00201e82, // n0x1266 c0x0000 (---------------) + I ac 0x002aa2c4, // n0x1267 c0x0000 (---------------) + I assn 0x00222ac3, // n0x1268 c0x0000 (---------------) + I com 0x002d75c3, // n0x1269 c0x0000 (---------------) + I edu 0x0021e283, // n0x126a c0x0000 (---------------) + I gov 0x00221d03, // n0x126b c0x0000 (---------------) + I grp 0x00294945, // n0x126c c0x0000 (---------------) + I hotel 0x00238c03, // n0x126d c0x0000 (---------------) + I int 0x003413c3, // n0x126e c0x0000 (---------------) + I ltd 0x002170c3, // n0x126f c0x0000 (---------------) + I net 0x00202303, // n0x1270 c0x0000 (---------------) + I ngo 0x0021dcc3, // n0x1271 c0x0000 (---------------) + I org 0x00206103, // n0x1272 c0x0000 (---------------) + I sch 0x00240a03, // n0x1273 c0x0000 (---------------) + I soc 0x00219fc3, // n0x1274 c0x0000 (---------------) + I web 0x00222ac3, // n0x1275 c0x0000 (---------------) + I com 0x002d75c3, // n0x1276 c0x0000 (---------------) + I edu 0x0021e283, // n0x1277 c0x0000 (---------------) + I gov 0x002170c3, // n0x1278 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1279 c0x0000 (---------------) + I org 0x00200742, // n0x127a c0x0000 (---------------) + I co 0x0021dcc3, // n0x127b c0x0000 (---------------) + I org 0x000e4188, // n0x127c c0x0000 (---------------) + blogspot 0x0021e283, // n0x127d c0x0000 (---------------) + I gov 0x000e4188, // n0x127e c0x0000 (---------------) + blogspot 0x002a00c3, // n0x127f c0x0000 (---------------) + I asn 0x00222ac3, // n0x1280 c0x0000 (---------------) + I com 0x00224984, // n0x1281 c0x0000 (---------------) + I conf 0x002d75c3, // n0x1282 c0x0000 (---------------) + I edu 0x0021e283, // n0x1283 c0x0000 (---------------) + I gov 0x00206202, // n0x1284 c0x0000 (---------------) + I id 0x0023fa03, // n0x1285 c0x0000 (---------------) + I mil 0x002170c3, // n0x1286 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1287 c0x0000 (---------------) + I org 0x00222ac3, // n0x1288 c0x0000 (---------------) + I com 0x002d75c3, // n0x1289 c0x0000 (---------------) + I edu 0x0021e283, // n0x128a c0x0000 (---------------) + I gov 0x00206202, // n0x128b c0x0000 (---------------) + I id 0x0020b403, // n0x128c c0x0000 (---------------) + I med 0x002170c3, // n0x128d c0x0000 (---------------) + I net 0x0021dcc3, // n0x128e c0x0000 (---------------) + I org 0x002c65c3, // n0x128f c0x0000 (---------------) + I plc 0x00206103, // n0x1290 c0x0000 (---------------) + I sch 0x00201e82, // n0x1291 c0x0000 (---------------) + I ac 0x00200742, // n0x1292 c0x0000 (---------------) + I co 0x0021e283, // n0x1293 c0x0000 (---------------) + I gov 0x002170c3, // n0x1294 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1295 c0x0000 (---------------) + I org 0x0029abc5, // n0x1296 c0x0000 (---------------) + I press 0x002729c4, // n0x1297 c0x0000 (---------------) + I asso 0x00208902, // n0x1298 c0x0000 (---------------) + I tm 0x000e4188, // n0x1299 c0x0000 (---------------) + blogspot 0x00201e82, // n0x129a c0x0000 (---------------) + I ac 0x00200742, // n0x129b c0x0000 (---------------) + I co 0x002d75c3, // n0x129c c0x0000 (---------------) + I edu 0x0021e283, // n0x129d c0x0000 (---------------) + I gov 0x00226ac3, // n0x129e c0x0000 (---------------) + I its 0x002170c3, // n0x129f c0x0000 (---------------) + I net 0x0021dcc3, // n0x12a0 c0x0000 (---------------) + I org 0x002cba44, // n0x12a1 c0x0000 (---------------) + I priv 0x00222ac3, // n0x12a2 c0x0000 (---------------) + I com 0x002d75c3, // n0x12a3 c0x0000 (---------------) + I edu 0x0021e283, // n0x12a4 c0x0000 (---------------) + I gov 0x0023fa03, // n0x12a5 c0x0000 (---------------) + I mil 0x00207cc3, // n0x12a6 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x12a7 c0x0000 (---------------) + I org 0x002ca783, // n0x12a8 c0x0000 (---------------) + I prd 0x00208902, // n0x12a9 c0x0000 (---------------) + I tm 0x000e4188, // n0x12aa c0x0000 (---------------) + blogspot 0x00222ac3, // n0x12ab c0x0000 (---------------) + I com 0x002d75c3, // n0x12ac c0x0000 (---------------) + I edu 0x0021e283, // n0x12ad c0x0000 (---------------) + I gov 0x00200303, // n0x12ae c0x0000 (---------------) + I inf 0x00298944, // n0x12af c0x0000 (---------------) + I name 0x002170c3, // n0x12b0 c0x0000 (---------------) + I net 0x0021dcc3, // n0x12b1 c0x0000 (---------------) + I org 0x00222ac3, // n0x12b2 c0x0000 (---------------) + I com 0x002d75c3, // n0x12b3 c0x0000 (---------------) + I edu 0x003579c4, // n0x12b4 c0x0000 (---------------) + I gouv 0x0021e283, // n0x12b5 c0x0000 (---------------) + I gov 0x002170c3, // n0x12b6 c0x0000 (---------------) + I net 0x0021dcc3, // n0x12b7 c0x0000 (---------------) + I org 0x0029abc6, // n0x12b8 c0x0000 (---------------) + I presse 0x002d75c3, // n0x12b9 c0x0000 (---------------) + I edu 0x0021e283, // n0x12ba c0x0000 (---------------) + I gov 0x00023403, // n0x12bb c0x0000 (---------------) + nyc 0x0021dcc3, // n0x12bc c0x0000 (---------------) + I org 0x00222ac3, // n0x12bd c0x0000 (---------------) + I com 0x002d75c3, // n0x12be c0x0000 (---------------) + I edu 0x0021e283, // n0x12bf c0x0000 (---------------) + I gov 0x002170c3, // n0x12c0 c0x0000 (---------------) + I net 0x0021dcc3, // n0x12c1 c0x0000 (---------------) + I org 0x000e4188, // n0x12c2 c0x0000 (---------------) + blogspot 0x0021e283, // n0x12c3 c0x0000 (---------------) + I gov 0x00222ac3, // n0x12c4 c0x0000 (---------------) + I com 0x002d75c3, // n0x12c5 c0x0000 (---------------) + I edu 0x0021e283, // n0x12c6 c0x0000 (---------------) + I gov 0x002170c3, // n0x12c7 c0x0000 (---------------) + I net 0x0021dcc3, // n0x12c8 c0x0000 (---------------) + I org 0x35622ac3, // n0x12c9 c0x00d5 (n0x12cd-n0x12ce) + I com 0x002d75c3, // n0x12ca c0x0000 (---------------) + I edu 0x002170c3, // n0x12cb c0x0000 (---------------) + I net 0x0021dcc3, // n0x12cc c0x0000 (---------------) + I org 0x000e4188, // n0x12cd c0x0000 (---------------) + blogspot 0x00201e82, // n0x12ce c0x0000 (---------------) + I ac 0x00200742, // n0x12cf c0x0000 (---------------) + I co 0x00222ac3, // n0x12d0 c0x0000 (---------------) + I com 0x0021e283, // n0x12d1 c0x0000 (---------------) + I gov 0x002170c3, // n0x12d2 c0x0000 (---------------) + I net 0x00200c42, // n0x12d3 c0x0000 (---------------) + I or 0x0021dcc3, // n0x12d4 c0x0000 (---------------) + I org 0x002f2787, // n0x12d5 c0x0000 (---------------) + I academy 0x0033c2cb, // n0x12d6 c0x0000 (---------------) + I agriculture 0x00205743, // n0x12d7 c0x0000 (---------------) + I air 0x0022c148, // n0x12d8 c0x0000 (---------------) + I airguard 0x0038bc07, // n0x12d9 c0x0000 (---------------) + I alabama 0x00267646, // n0x12da c0x0000 (---------------) + I alaska 0x002b6e85, // n0x12db c0x0000 (---------------) + I amber 0x003541c9, // n0x12dc c0x0000 (---------------) + I ambulance 0x002757c8, // n0x12dd c0x0000 (---------------) + I american 0x002757c9, // n0x12de c0x0000 (---------------) + I americana 0x002757d0, // n0x12df c0x0000 (---------------) + I americanantiques 0x0031aecb, // n0x12e0 c0x0000 (---------------) + I americanart 0x002b6cc9, // n0x12e1 c0x0000 (---------------) + I amsterdam 0x00208f03, // n0x12e2 c0x0000 (---------------) + I and 0x003228c9, // n0x12e3 c0x0000 (---------------) + I annefrank 0x00225786, // n0x12e4 c0x0000 (---------------) + I anthro 0x0022578c, // n0x12e5 c0x0000 (---------------) + I anthropology 0x00222588, // n0x12e6 c0x0000 (---------------) + I antiques 0x00392b08, // n0x12e7 c0x0000 (---------------) + I aquarium 0x00256f09, // n0x12e8 c0x0000 (---------------) + I arboretum 0x0029690e, // n0x12e9 c0x0000 (---------------) + I archaeological 0x003429cb, // n0x12ea c0x0000 (---------------) + I archaeology 0x002a52cc, // n0x12eb c0x0000 (---------------) + I architecture 0x00200603, // n0x12ec c0x0000 (---------------) + I art 0x0031b0cc, // n0x12ed c0x0000 (---------------) + I artanddesign 0x0037a6c9, // n0x12ee c0x0000 (---------------) + I artcenter 0x00200607, // n0x12ef c0x0000 (---------------) + I artdeco 0x0037548c, // n0x12f0 c0x0000 (---------------) + I arteducation 0x0022654a, // n0x12f1 c0x0000 (---------------) + I artgallery 0x00246584, // n0x12f2 c0x0000 (---------------) + I arts 0x0024658d, // n0x12f3 c0x0000 (---------------) + I artsandcrafts 0x0037a588, // n0x12f4 c0x0000 (---------------) + I asmatart 0x0034db0d, // n0x12f5 c0x0000 (---------------) + I assassination 0x0037ac46, // n0x12f6 c0x0000 (---------------) + I assisi 0x002bbacb, // n0x12f7 c0x0000 (---------------) + I association 0x0032b3c9, // n0x12f8 c0x0000 (---------------) + I astronomy 0x0032d947, // n0x12f9 c0x0000 (---------------) + I atlanta 0x0030ce46, // n0x12fa c0x0000 (---------------) + I austin 0x002ee489, // n0x12fb c0x0000 (---------------) + I australia 0x0030494a, // n0x12fc c0x0000 (---------------) + I automotive 0x00328bc8, // n0x12fd c0x0000 (---------------) + I aviation 0x0025db04, // n0x12fe c0x0000 (---------------) + I axis 0x0035ef47, // n0x12ff c0x0000 (---------------) + I badajoz 0x00264407, // n0x1300 c0x0000 (---------------) + I baghdad 0x00295f44, // n0x1301 c0x0000 (---------------) + I bahn 0x0023d9c4, // n0x1302 c0x0000 (---------------) + I bale 0x002708c9, // n0x1303 c0x0000 (---------------) + I baltimore 0x0036bf49, // n0x1304 c0x0000 (---------------) + I barcelona 0x002ed5c8, // n0x1305 c0x0000 (---------------) + I baseball 0x0020a445, // n0x1306 c0x0000 (---------------) + I basel 0x002dbe45, // n0x1307 c0x0000 (---------------) + I baths 0x00205a86, // n0x1308 c0x0000 (---------------) + I bauern 0x00246449, // n0x1309 c0x0000 (---------------) + I beauxarts 0x0035a18d, // n0x130a c0x0000 (---------------) + I beeldengeluid 0x002a4d48, // n0x130b c0x0000 (---------------) + I bellevue 0x00205987, // n0x130c c0x0000 (---------------) + I bergbau 0x002b6f08, // n0x130d c0x0000 (---------------) + I berkeley 0x00251d46, // n0x130e c0x0000 (---------------) + I berlin 0x00353844, // n0x130f c0x0000 (---------------) + I bern 0x003628c5, // n0x1310 c0x0000 (---------------) + I bible 0x00394a46, // n0x1311 c0x0000 (---------------) + I bilbao 0x00396b04, // n0x1312 c0x0000 (---------------) + I bill 0x00200507, // n0x1313 c0x0000 (---------------) + I birdart 0x00201cca, // n0x1314 c0x0000 (---------------) + I birthplace 0x0020bcc4, // n0x1315 c0x0000 (---------------) + I bonn 0x0020d686, // n0x1316 c0x0000 (---------------) + I boston 0x0020e2c9, // n0x1317 c0x0000 (---------------) + I botanical 0x0020e2cf, // n0x1318 c0x0000 (---------------) + I botanicalgarden 0x0020e88d, // n0x1319 c0x0000 (---------------) + I botanicgarden 0x002107c6, // n0x131a c0x0000 (---------------) + I botany 0x00213b10, // n0x131b c0x0000 (---------------) + I brandywinevalley 0x00214a86, // n0x131c c0x0000 (---------------) + I brasil 0x002159c7, // n0x131d c0x0000 (---------------) + I bristol 0x00215d47, // n0x131e c0x0000 (---------------) + I british 0x00215d4f, // n0x131f c0x0000 (---------------) + I britishcolumbia 0x00216d09, // n0x1320 c0x0000 (---------------) + I broadcast 0x0021b106, // n0x1321 c0x0000 (---------------) + I brunel 0x0021be87, // n0x1322 c0x0000 (---------------) + I brussel 0x0021be88, // n0x1323 c0x0000 (---------------) + I brussels 0x0021c809, // n0x1324 c0x0000 (---------------) + I bruxelles 0x002c67c8, // n0x1325 c0x0000 (---------------) + I building 0x002c2fc7, // n0x1326 c0x0000 (---------------) + I burghof 0x002224c3, // n0x1327 c0x0000 (---------------) + I bus 0x00280c46, // n0x1328 c0x0000 (---------------) + I bushey 0x0027d948, // n0x1329 c0x0000 (---------------) + I cadaques 0x00296bca, // n0x132a c0x0000 (---------------) + I california 0x0021a089, // n0x132b c0x0000 (---------------) + I cambridge 0x00208ec3, // n0x132c c0x0000 (---------------) + I can 0x00309786, // n0x132d c0x0000 (---------------) + I canada 0x0024de4a, // n0x132e c0x0000 (---------------) + I capebreton 0x0031bb87, // n0x132f c0x0000 (---------------) + I carrier 0x003752ca, // n0x1330 c0x0000 (---------------) + I cartoonart 0x0038390e, // n0x1331 c0x0000 (---------------) + I casadelamoneda 0x00216e46, // n0x1332 c0x0000 (---------------) + I castle 0x0021c487, // n0x1333 c0x0000 (---------------) + I castres 0x0020f006, // n0x1334 c0x0000 (---------------) + I celtic 0x00233a06, // n0x1335 c0x0000 (---------------) + I center 0x0036240b, // n0x1336 c0x0000 (---------------) + I chattanooga 0x002503ca, // n0x1337 c0x0000 (---------------) + I cheltenham 0x002eeccd, // n0x1338 c0x0000 (---------------) + I chesapeakebay 0x0034e9c7, // n0x1339 c0x0000 (---------------) + I chicago 0x00262bc8, // n0x133a c0x0000 (---------------) + I children 0x00262bc9, // n0x133b c0x0000 (---------------) + I childrens 0x00262bcf, // n0x133c c0x0000 (---------------) + I childrensgarden 0x0029300c, // n0x133d c0x0000 (---------------) + I chiropractic 0x00299309, // n0x133e c0x0000 (---------------) + I chocolate 0x0022d30e, // n0x133f c0x0000 (---------------) + I christiansburg 0x002754ca, // n0x1340 c0x0000 (---------------) + I cincinnati 0x00343506, // n0x1341 c0x0000 (---------------) + I cinema 0x00323506, // n0x1342 c0x0000 (---------------) + I circus 0x0034564c, // n0x1343 c0x0000 (---------------) + I civilisation 0x0034878c, // n0x1344 c0x0000 (---------------) + I civilization 0x003518c8, // n0x1345 c0x0000 (---------------) + I civilwar 0x00369707, // n0x1346 c0x0000 (---------------) + I clinton 0x0020af45, // n0x1347 c0x0000 (---------------) + I clock 0x00387ec4, // n0x1348 c0x0000 (---------------) + I coal 0x0032ac0e, // n0x1349 c0x0000 (---------------) + I coastaldefence 0x00200744, // n0x134a c0x0000 (---------------) + I cody 0x00232107, // n0x134b c0x0000 (---------------) + I coldwar 0x0024f38a, // n0x134c c0x0000 (---------------) + I collection 0x00221854, // n0x134d c0x0000 (---------------) + I colonialwilliamsburg 0x00221f0f, // n0x134e c0x0000 (---------------) + I coloradoplateau 0x00215f08, // n0x134f c0x0000 (---------------) + I columbia 0x00222388, // n0x1350 c0x0000 (---------------) + I columbus 0x002b354d, // n0x1351 c0x0000 (---------------) + I communication 0x002b354e, // n0x1352 c0x0000 (---------------) + I communications 0x00222ac9, // n0x1353 c0x0000 (---------------) + I community 0x002236c8, // n0x1354 c0x0000 (---------------) + I computer 0x002236cf, // n0x1355 c0x0000 (---------------) + I computerhistory 0x0022624c, // n0x1356 c0x0000 (---------------) + I contemporary 0x0022624f, // n0x1357 c0x0000 (---------------) + I contemporaryart 0x00227187, // n0x1358 c0x0000 (---------------) + I convent 0x00229bca, // n0x1359 c0x0000 (---------------) + I copenhagen 0x0021300b, // n0x135a c0x0000 (---------------) + I corporation 0x0022b908, // n0x135b c0x0000 (---------------) + I corvette 0x0022c347, // n0x135c c0x0000 (---------------) + I costume 0x00362c0d, // n0x135d c0x0000 (---------------) + I countryestate 0x002f8886, // n0x135e c0x0000 (---------------) + I county 0x00246746, // n0x135f c0x0000 (---------------) + I crafts 0x0022f189, // n0x1360 c0x0000 (---------------) + I cranbrook 0x002e63c8, // n0x1361 c0x0000 (---------------) + I creation 0x00233808, // n0x1362 c0x0000 (---------------) + I cultural 0x0023380e, // n0x1363 c0x0000 (---------------) + I culturalcenter 0x00323687, // n0x1364 c0x0000 (---------------) + I culture 0x00343d85, // n0x1365 c0x0000 (---------------) + I cyber 0x002dcac5, // n0x1366 c0x0000 (---------------) + I cymru 0x00270d04, // n0x1367 c0x0000 (---------------) + I dali 0x00267906, // n0x1368 c0x0000 (---------------) + I dallas 0x002ed4c8, // n0x1369 c0x0000 (---------------) + I database 0x0034d6c3, // n0x136a c0x0000 (---------------) + I ddr 0x00255ace, // n0x136b c0x0000 (---------------) + I decorativearts 0x00362fc8, // n0x136c c0x0000 (---------------) + I delaware 0x0029f90b, // n0x136d c0x0000 (---------------) + I delmenhorst 0x00311707, // n0x136e c0x0000 (---------------) + I denmark 0x002b8f85, // n0x136f c0x0000 (---------------) + I depot 0x00232f46, // n0x1370 c0x0000 (---------------) + I design 0x00295507, // n0x1371 c0x0000 (---------------) + I detroit 0x002dff48, // n0x1372 c0x0000 (---------------) + I dinosaur 0x00304c89, // n0x1373 c0x0000 (---------------) + I discovery 0x002250c5, // n0x1374 c0x0000 (---------------) + I dolls 0x00274888, // n0x1375 c0x0000 (---------------) + I donostia 0x0038a206, // n0x1376 c0x0000 (---------------) + I durham 0x00367b0a, // n0x1377 c0x0000 (---------------) + I eastafrica 0x0032ab09, // n0x1378 c0x0000 (---------------) + I eastcoast 0x00375549, // n0x1379 c0x0000 (---------------) + I education 0x0037554b, // n0x137a c0x0000 (---------------) + I educational 0x002958c8, // n0x137b c0x0000 (---------------) + I egyptian 0x00295e09, // n0x137c c0x0000 (---------------) + I eisenbahn 0x0020a506, // n0x137d c0x0000 (---------------) + I elburg 0x0034cf0a, // n0x137e c0x0000 (---------------) + I elvendrell 0x0032af4a, // n0x137f c0x0000 (---------------) + I embroidery 0x00229dcc, // n0x1380 c0x0000 (---------------) + I encyclopedic 0x0037b187, // n0x1381 c0x0000 (---------------) + I england 0x00384a8a, // n0x1382 c0x0000 (---------------) + I entomology 0x0030de4b, // n0x1383 c0x0000 (---------------) + I environment 0x0030de59, // n0x1384 c0x0000 (---------------) + I environmentalconservation 0x003543c8, // n0x1385 c0x0000 (---------------) + I epilepsy 0x0029ac45, // n0x1386 c0x0000 (---------------) + I essex 0x002b1846, // n0x1387 c0x0000 (---------------) + I estate 0x002f6409, // n0x1388 c0x0000 (---------------) + I ethnology 0x0020bb46, // n0x1389 c0x0000 (---------------) + I exeter 0x00326eca, // n0x138a c0x0000 (---------------) + I exhibition 0x00311c06, // n0x138b c0x0000 (---------------) + I family 0x0021f804, // n0x138c c0x0000 (---------------) + I farm 0x0021f80d, // n0x138d c0x0000 (---------------) + I farmequipment 0x00366b07, // n0x138e c0x0000 (---------------) + I farmers 0x002fb8c9, // n0x138f c0x0000 (---------------) + I farmstead 0x002099c5, // n0x1390 c0x0000 (---------------) + I field 0x00338588, // n0x1391 c0x0000 (---------------) + I figueres 0x00349f49, // n0x1392 c0x0000 (---------------) + I filatelia 0x00356104, // n0x1393 c0x0000 (---------------) + I film 0x003707c7, // n0x1394 c0x0000 (---------------) + I fineart 0x003707c8, // n0x1395 c0x0000 (---------------) + I finearts 0x00236407, // n0x1396 c0x0000 (---------------) + I finland 0x00252b88, // n0x1397 c0x0000 (---------------) + I flanders 0x0023c447, // n0x1398 c0x0000 (---------------) + I florida 0x002e7685, // n0x1399 c0x0000 (---------------) + I force 0x002457cc, // n0x139a c0x0000 (---------------) + I fortmissoula 0x00245e89, // n0x139b c0x0000 (---------------) + I fortworth 0x00303b8a, // n0x139c c0x0000 (---------------) + I foundation 0x00377209, // n0x139d c0x0000 (---------------) + I francaise 0x003229c9, // n0x139e c0x0000 (---------------) + I frankfurt 0x0035268c, // n0x139f c0x0000 (---------------) + I franziskaner 0x00209c8b, // n0x13a0 c0x0000 (---------------) + I freemasonry 0x00248cc8, // n0x13a1 c0x0000 (---------------) + I freiburg 0x002493c8, // n0x13a2 c0x0000 (---------------) + I fribourg 0x0024c784, // n0x13a3 c0x0000 (---------------) + I frog 0x0026fc08, // n0x13a4 c0x0000 (---------------) + I fundacio 0x00272f09, // n0x13a5 c0x0000 (---------------) + I furniture 0x00226607, // n0x13a6 c0x0000 (---------------) + I gallery 0x0020e506, // n0x13a7 c0x0000 (---------------) + I garden 0x0021a607, // n0x13a8 c0x0000 (---------------) + I gateway 0x00268b89, // n0x13a9 c0x0000 (---------------) + I geelvinck 0x002a634b, // n0x13aa c0x0000 (---------------) + I gemological 0x00309a87, // n0x13ab c0x0000 (---------------) + I geology 0x002f8287, // n0x13ac c0x0000 (---------------) + I georgia 0x00267387, // n0x13ad c0x0000 (---------------) + I giessen 0x0034da84, // n0x13ae c0x0000 (---------------) + I glas 0x0034da85, // n0x13af c0x0000 (---------------) + I glass 0x00292d05, // n0x13b0 c0x0000 (---------------) + I gorge 0x00320b0b, // n0x13b1 c0x0000 (---------------) + I grandrapids 0x00380d44, // n0x13b2 c0x0000 (---------------) + I graz 0x002e6b48, // n0x13b3 c0x0000 (---------------) + I guernsey 0x002a19ca, // n0x13b4 c0x0000 (---------------) + I halloffame 0x0038a2c7, // n0x13b5 c0x0000 (---------------) + I hamburg 0x00372047, // n0x13b6 c0x0000 (---------------) + I handson 0x0027a252, // n0x13b7 c0x0000 (---------------) + I harvestcelebration 0x00256386, // n0x13b8 c0x0000 (---------------) + I hawaii 0x00205e06, // n0x13b9 c0x0000 (---------------) + I health 0x002f518e, // n0x13ba c0x0000 (---------------) + I heimatunduhren 0x00257ac6, // n0x13bb c0x0000 (---------------) + I hellas 0x00209408, // n0x13bc c0x0000 (---------------) + I helsinki 0x0027f4cf, // n0x13bd c0x0000 (---------------) + I hembygdsforbund 0x0034dec8, // n0x13be c0x0000 (---------------) + I heritage 0x0025de08, // n0x13bf c0x0000 (---------------) + I histoire 0x002a794a, // n0x13c0 c0x0000 (---------------) + I historical 0x002a7951, // n0x13c1 c0x0000 (---------------) + I historicalsociety 0x0028cfce, // n0x13c2 c0x0000 (---------------) + I historichouses 0x0024268a, // n0x13c3 c0x0000 (---------------) + I historisch 0x0024268c, // n0x13c4 c0x0000 (---------------) + I historisches 0x002238c7, // n0x13c5 c0x0000 (---------------) + I history 0x002238d0, // n0x13c6 c0x0000 (---------------) + I historyofscience 0x0038f308, // n0x13c7 c0x0000 (---------------) + I horology 0x0021da05, // n0x13c8 c0x0000 (---------------) + I house 0x002d8f0a, // n0x13c9 c0x0000 (---------------) + I humanities 0x00396b4c, // n0x13ca c0x0000 (---------------) + I illustration 0x003365cd, // n0x13cb c0x0000 (---------------) + I imageandsound 0x002d5b06, // n0x13cc c0x0000 (---------------) + I indian 0x002d5b07, // n0x13cd c0x0000 (---------------) + I indiana 0x002d5b0c, // n0x13ce c0x0000 (---------------) + I indianapolis 0x00356ecc, // n0x13cf c0x0000 (---------------) + I indianmarket 0x00238c0c, // n0x13d0 c0x0000 (---------------) + I intelligence 0x0027d28b, // n0x13d1 c0x0000 (---------------) + I interactive 0x00273f44, // n0x13d2 c0x0000 (---------------) + I iraq 0x0021afc4, // n0x13d3 c0x0000 (---------------) + I iron 0x00357ec9, // n0x13d4 c0x0000 (---------------) + I isleofman 0x002bc087, // n0x13d5 c0x0000 (---------------) + I jamison 0x002207c9, // n0x13d6 c0x0000 (---------------) + I jefferson 0x00337649, // n0x13d7 c0x0000 (---------------) + I jerusalem 0x0034f487, // n0x13d8 c0x0000 (---------------) + I jewelry 0x0038cb46, // n0x13d9 c0x0000 (---------------) + I jewish 0x0038cb49, // n0x13da c0x0000 (---------------) + I jewishart 0x00297743, // n0x13db c0x0000 (---------------) + I jfk 0x0028540a, // n0x13dc c0x0000 (---------------) + I journalism 0x0036e9c7, // n0x13dd c0x0000 (---------------) + I judaica 0x0035f38b, // n0x13de c0x0000 (---------------) + I judygarland 0x002eeb4a, // n0x13df c0x0000 (---------------) + I juedisches 0x00370c84, // n0x13e0 c0x0000 (---------------) + I juif 0x002df386, // n0x13e1 c0x0000 (---------------) + I karate 0x002af549, // n0x13e2 c0x0000 (---------------) + I karikatur 0x00394c44, // n0x13e3 c0x0000 (---------------) + I kids 0x0033e24a, // n0x13e4 c0x0000 (---------------) + I koebenhavn 0x0021f385, // n0x13e5 c0x0000 (---------------) + I koeln 0x002a3845, // n0x13e6 c0x0000 (---------------) + I kunst 0x002a384d, // n0x13e7 c0x0000 (---------------) + I kunstsammlung 0x002a3b8e, // n0x13e8 c0x0000 (---------------) + I kunstunddesign 0x002feec5, // n0x13e9 c0x0000 (---------------) + I labor 0x0037c986, // n0x13ea c0x0000 (---------------) + I labour 0x00323a07, // n0x13eb c0x0000 (---------------) + I lajolla 0x00261a4a, // n0x13ec c0x0000 (---------------) + I lancashire 0x0035b146, // n0x13ed c0x0000 (---------------) + I landes 0x002856c4, // n0x13ee c0x0000 (---------------) + I lans 0x002d0287, // n0x13ef c0x0000 (---------------) + I larsson 0x0029eacb, // n0x13f0 c0x0000 (---------------) + I lewismiller 0x00251e07, // n0x13f1 c0x0000 (---------------) + I lincoln 0x00329ac4, // n0x13f2 c0x0000 (---------------) + I linz 0x002a1d46, // n0x13f3 c0x0000 (---------------) + I living 0x002a1d4d, // n0x13f4 c0x0000 (---------------) + I livinghistory 0x0032254c, // n0x13f5 c0x0000 (---------------) + I localhistory 0x00340906, // n0x13f6 c0x0000 (---------------) + I london 0x002a4f4a, // n0x13f7 c0x0000 (---------------) + I losangeles 0x002116c6, // n0x13f8 c0x0000 (---------------) + I louvre 0x00259d88, // n0x13f9 c0x0000 (---------------) + I loyalist 0x0021d747, // n0x13fa c0x0000 (---------------) + I lucerne 0x00222d8a, // n0x13fb c0x0000 (---------------) + I luxembourg 0x00226c86, // n0x13fc c0x0000 (---------------) + I luzern 0x0026b0c3, // n0x13fd c0x0000 (---------------) + I mad 0x00300a86, // n0x13fe c0x0000 (---------------) + I madrid 0x0026aa08, // n0x13ff c0x0000 (---------------) + I mallorca 0x0028608a, // n0x1400 c0x0000 (---------------) + I manchester 0x00266747, // n0x1401 c0x0000 (---------------) + I mansion 0x00266748, // n0x1402 c0x0000 (---------------) + I mansions 0x0026d784, // n0x1403 c0x0000 (---------------) + I manx 0x00277287, // n0x1404 c0x0000 (---------------) + I marburg 0x0036ee48, // n0x1405 c0x0000 (---------------) + I maritime 0x00237048, // n0x1406 c0x0000 (---------------) + I maritimo 0x00256588, // n0x1407 c0x0000 (---------------) + I maryland 0x003372ca, // n0x1408 c0x0000 (---------------) + I marylhurst 0x002dc385, // n0x1409 c0x0000 (---------------) + I media 0x002e7087, // n0x140a c0x0000 (---------------) + I medical 0x002424d3, // n0x140b c0x0000 (---------------) + I medizinhistorisches 0x00257946, // n0x140c c0x0000 (---------------) + I meeres 0x002edac8, // n0x140d c0x0000 (---------------) + I memorial 0x00219509, // n0x140e c0x0000 (---------------) + I mesaverde 0x00204988, // n0x140f c0x0000 (---------------) + I michigan 0x002892cb, // n0x1410 c0x0000 (---------------) + I midatlantic 0x002a6948, // n0x1411 c0x0000 (---------------) + I military 0x0029ec04, // n0x1412 c0x0000 (---------------) + I mill 0x002878c6, // n0x1413 c0x0000 (---------------) + I miners 0x002e7a46, // n0x1414 c0x0000 (---------------) + I mining 0x00335b09, // n0x1415 c0x0000 (---------------) + I minnesota 0x002ad807, // n0x1416 c0x0000 (---------------) + I missile 0x002458c8, // n0x1417 c0x0000 (---------------) + I missoula 0x00291a06, // n0x1418 c0x0000 (---------------) + I modern 0x0021cfc4, // n0x1419 c0x0000 (---------------) + I moma 0x002b6185, // n0x141a c0x0000 (---------------) + I money 0x002b02c8, // n0x141b c0x0000 (---------------) + I monmouth 0x002b094a, // n0x141c c0x0000 (---------------) + I monticello 0x002b1648, // n0x141d c0x0000 (---------------) + I montreal 0x002b68c6, // n0x141e c0x0000 (---------------) + I moscow 0x0028678a, // n0x141f c0x0000 (---------------) + I motorcycle 0x002f3cc8, // n0x1420 c0x0000 (---------------) + I muenchen 0x002b9948, // n0x1421 c0x0000 (---------------) + I muenster 0x002ba948, // n0x1422 c0x0000 (---------------) + I mulhouse 0x002bb346, // n0x1423 c0x0000 (---------------) + I muncie 0x002bd186, // n0x1424 c0x0000 (---------------) + I museet 0x0030e7cc, // n0x1425 c0x0000 (---------------) + I museumcenter 0x002bd650, // n0x1426 c0x0000 (---------------) + I museumvereniging 0x00337b85, // n0x1427 c0x0000 (---------------) + I music 0x002dd9c8, // n0x1428 c0x0000 (---------------) + I national 0x002dd9d0, // n0x1429 c0x0000 (---------------) + I nationalfirearms 0x0034dcd0, // n0x142a c0x0000 (---------------) + I nationalheritage 0x0027564e, // n0x142b c0x0000 (---------------) + I nativeamerican 0x0030e44e, // n0x142c c0x0000 (---------------) + I naturalhistory 0x0030e454, // n0x142d c0x0000 (---------------) + I naturalhistorymuseum 0x00240dcf, // n0x142e c0x0000 (---------------) + I naturalsciences 0x00241186, // n0x142f c0x0000 (---------------) + I nature 0x002f4951, // n0x1430 c0x0000 (---------------) + I naturhistorisches 0x0031cfd3, // n0x1431 c0x0000 (---------------) + I natuurwetenschappen 0x0031d448, // n0x1432 c0x0000 (---------------) + I naumburg 0x00341c05, // n0x1433 c0x0000 (---------------) + I naval 0x00262448, // n0x1434 c0x0000 (---------------) + I nebraska 0x0021d585, // n0x1435 c0x0000 (---------------) + I neues 0x002e60cc, // n0x1436 c0x0000 (---------------) + I newhampshire 0x00221609, // n0x1437 c0x0000 (---------------) + I newjersey 0x00231f49, // n0x1438 c0x0000 (---------------) + I newmexico 0x0021a387, // n0x1439 c0x0000 (---------------) + I newport 0x00366d49, // n0x143a c0x0000 (---------------) + I newspaper 0x00237f07, // n0x143b c0x0000 (---------------) + I newyork 0x00203d46, // n0x143c c0x0000 (---------------) + I niepce 0x003626c7, // n0x143d c0x0000 (---------------) + I norfolk 0x002f0dc5, // n0x143e c0x0000 (---------------) + I north 0x00345903, // n0x143f c0x0000 (---------------) + I nrw 0x0034d889, // n0x1440 c0x0000 (---------------) + I nuernberg 0x002e9309, // n0x1441 c0x0000 (---------------) + I nuremberg 0x00223403, // n0x1442 c0x0000 (---------------) + I nyc 0x002108c4, // n0x1443 c0x0000 (---------------) + I nyny 0x0034100d, // n0x1444 c0x0000 (---------------) + I oceanographic 0x0034384f, // n0x1445 c0x0000 (---------------) + I oceanographique 0x002e3085, // n0x1446 c0x0000 (---------------) + I omaha 0x003023c6, // n0x1447 c0x0000 (---------------) + I online 0x0032a587, // n0x1448 c0x0000 (---------------) + I ontario 0x0032ce07, // n0x1449 c0x0000 (---------------) + I openair 0x00276b86, // n0x144a c0x0000 (---------------) + I oregon 0x00276b8b, // n0x144b c0x0000 (---------------) + I oregontrail 0x0028e6c5, // n0x144c c0x0000 (---------------) + I otago 0x00364046, // n0x144d c0x0000 (---------------) + I oxford 0x0031ba07, // n0x144e c0x0000 (---------------) + I pacific 0x0025d709, // n0x144f c0x0000 (---------------) + I paderborn 0x0036ce06, // n0x1450 c0x0000 (---------------) + I palace 0x002052c5, // n0x1451 c0x0000 (---------------) + I paleo 0x00324b4b, // n0x1452 c0x0000 (---------------) + I palmsprings 0x00221d86, // n0x1453 c0x0000 (---------------) + I panama 0x0025b445, // n0x1454 c0x0000 (---------------) + I paris 0x002a3348, // n0x1455 c0x0000 (---------------) + I pasadena 0x002dc948, // n0x1456 c0x0000 (---------------) + I pharmacy 0x0036150c, // n0x1457 c0x0000 (---------------) + I philadelphia 0x00361510, // n0x1458 c0x0000 (---------------) + I philadelphiaarea 0x002bf909, // n0x1459 c0x0000 (---------------) + I philately 0x002bfd47, // n0x145a c0x0000 (---------------) + I phoenix 0x002c014b, // n0x145b c0x0000 (---------------) + I photography 0x002c1506, // n0x145c c0x0000 (---------------) + I pilots 0x002c2e8a, // n0x145d c0x0000 (---------------) + I pittsburgh 0x002c438b, // n0x145e c0x0000 (---------------) + I planetarium 0x002c4bca, // n0x145f c0x0000 (---------------) + I plantation 0x002c4e46, // n0x1460 c0x0000 (---------------) + I plants 0x002c6485, // n0x1461 c0x0000 (---------------) + I plaza 0x0036e706, // n0x1462 c0x0000 (---------------) + I portal 0x00266f08, // n0x1463 c0x0000 (---------------) + I portland 0x0021a44a, // n0x1464 c0x0000 (---------------) + I portlligat 0x002b31dc, // n0x1465 c0x0000 (---------------) + I posts-and-telecommunications 0x002ca84c, // n0x1466 c0x0000 (---------------) + I preservation 0x002cab48, // n0x1467 c0x0000 (---------------) + I presidio 0x0029abc5, // n0x1468 c0x0000 (---------------) + I press 0x002cc587, // n0x1469 c0x0000 (---------------) + I project 0x00296546, // n0x146a c0x0000 (---------------) + I public 0x0034c905, // n0x146b c0x0000 (---------------) + I pubol 0x00211186, // n0x146c c0x0000 (---------------) + I quebec 0x00276d48, // n0x146d c0x0000 (---------------) + I railroad 0x00253fc7, // n0x146e c0x0000 (---------------) + I railway 0x00296808, // n0x146f c0x0000 (---------------) + I research 0x0021c58a, // n0x1470 c0x0000 (---------------) + I resistance 0x0033cb8c, // n0x1471 c0x0000 (---------------) + I riodejaneiro 0x0033ce09, // n0x1472 c0x0000 (---------------) + I rochester 0x00201707, // n0x1473 c0x0000 (---------------) + I rockart 0x0023fb84, // n0x1474 c0x0000 (---------------) + I roma 0x0023afc6, // n0x1475 c0x0000 (---------------) + I russia 0x002c508a, // n0x1476 c0x0000 (---------------) + I saintlouis 0x00337745, // n0x1477 c0x0000 (---------------) + I salem 0x0034250c, // n0x1478 c0x0000 (---------------) + I salvadordali 0x0034ec88, // n0x1479 c0x0000 (---------------) + I salzburg 0x00270ec8, // n0x147a c0x0000 (---------------) + I sandiego 0x0023774c, // n0x147b c0x0000 (---------------) + I sanfrancisco 0x0020bfcc, // n0x147c c0x0000 (---------------) + I santabarbara 0x0020c3c9, // n0x147d c0x0000 (---------------) + I santacruz 0x0020c607, // n0x147e c0x0000 (---------------) + I santafe 0x0035768c, // n0x147f c0x0000 (---------------) + I saskatchewan 0x002251c4, // n0x1480 c0x0000 (---------------) + I satx 0x0022de0a, // n0x1481 c0x0000 (---------------) + I savannahga 0x0020cb8c, // n0x1482 c0x0000 (---------------) + I schlesisches 0x00354a4b, // n0x1483 c0x0000 (---------------) + I schoenbrunn 0x0025e7cb, // n0x1484 c0x0000 (---------------) + I schokoladen 0x00235406, // n0x1485 c0x0000 (---------------) + I school 0x0023b2c7, // n0x1486 c0x0000 (---------------) + I schweiz 0x00223b07, // n0x1487 c0x0000 (---------------) + I science 0x00223b0f, // n0x1488 c0x0000 (---------------) + I science-fiction 0x002d6251, // n0x1489 c0x0000 (---------------) + I scienceandhistory 0x0037f9d2, // n0x148a c0x0000 (---------------) + I scienceandindustry 0x0023ce0d, // n0x148b c0x0000 (---------------) + I sciencecenter 0x0023ce0e, // n0x148c c0x0000 (---------------) + I sciencecenters 0x0023d14e, // n0x148d c0x0000 (---------------) + I sciencehistory 0x00240f88, // n0x148e c0x0000 (---------------) + I sciences 0x00240f92, // n0x148f c0x0000 (---------------) + I sciencesnaturelles 0x00237988, // n0x1490 c0x0000 (---------------) + I scotland 0x002dfc87, // n0x1491 c0x0000 (---------------) + I seaport 0x0023920a, // n0x1492 c0x0000 (---------------) + I settlement 0x0020fb88, // n0x1493 c0x0000 (---------------) + I settlers 0x00257a85, // n0x1494 c0x0000 (---------------) + I shell 0x0025918a, // n0x1495 c0x0000 (---------------) + I sherbrooke 0x0037ad47, // n0x1496 c0x0000 (---------------) + I sibenik 0x0036b904, // n0x1497 c0x0000 (---------------) + I silk 0x00207b43, // n0x1498 c0x0000 (---------------) + I ski 0x002e3345, // n0x1499 c0x0000 (---------------) + I skole 0x002a7bc7, // n0x149a c0x0000 (---------------) + I society 0x002d84c7, // n0x149b c0x0000 (---------------) + I sologne 0x003367ce, // n0x149c c0x0000 (---------------) + I soundandvision 0x0031f30d, // n0x149d c0x0000 (---------------) + I southcarolina 0x00320d89, // n0x149e c0x0000 (---------------) + I southwest 0x002101c5, // n0x149f c0x0000 (---------------) + I space 0x00349a43, // n0x14a0 c0x0000 (---------------) + I spy 0x00275b86, // n0x14a1 c0x0000 (---------------) + I square 0x00248205, // n0x14a2 c0x0000 (---------------) + I stadt 0x0029fb48, // n0x14a3 c0x0000 (---------------) + I stalbans 0x00232449, // n0x14a4 c0x0000 (---------------) + I starnberg 0x002b1885, // n0x14a5 c0x0000 (---------------) + I state 0x00362e0f, // n0x14a6 c0x0000 (---------------) + I stateofdelaware 0x002c62c7, // n0x14a7 c0x0000 (---------------) + I station 0x00354105, // n0x14a8 c0x0000 (---------------) + I steam 0x002f2f8a, // n0x14a9 c0x0000 (---------------) + I steiermark 0x002a83c6, // n0x14aa c0x0000 (---------------) + I stjohn 0x00259f09, // n0x14ab c0x0000 (---------------) + I stockholm 0x002cf98c, // n0x14ac c0x0000 (---------------) + I stpetersburg 0x002d0749, // n0x14ad c0x0000 (---------------) + I stuttgart 0x00211e46, // n0x14ae c0x0000 (---------------) + I suisse 0x002a17cc, // n0x14af c0x0000 (---------------) + I surgeonshall 0x002d1c86, // n0x14b0 c0x0000 (---------------) + I surrey 0x002d4988, // n0x14b1 c0x0000 (---------------) + I svizzera 0x002d4b86, // n0x14b2 c0x0000 (---------------) + I sweden 0x00368086, // n0x14b3 c0x0000 (---------------) + I sydney 0x0024ca44, // n0x14b4 c0x0000 (---------------) + I tank 0x00249043, // n0x14b5 c0x0000 (---------------) + I tcm 0x0029d58a, // n0x14b6 c0x0000 (---------------) + I technology 0x002994d1, // n0x14b7 c0x0000 (---------------) + I telekommunikation 0x00248a4a, // n0x14b8 c0x0000 (---------------) + I television 0x00209085, // n0x14b9 c0x0000 (---------------) + I texas 0x00326307, // n0x14ba c0x0000 (---------------) + I textile 0x002f9147, // n0x14bb c0x0000 (---------------) + I theater 0x0036ef44, // n0x14bc c0x0000 (---------------) + I time 0x0036ef4b, // n0x14bd c0x0000 (---------------) + I timekeeping 0x0035e408, // n0x14be c0x0000 (---------------) + I topology 0x0029f3c6, // n0x14bf c0x0000 (---------------) + I torino 0x002e9685, // n0x14c0 c0x0000 (---------------) + I touch 0x0021abc4, // n0x14c1 c0x0000 (---------------) + I town 0x0027c9c9, // n0x14c2 c0x0000 (---------------) + I transport 0x00242e84, // n0x14c3 c0x0000 (---------------) + I tree 0x00211c47, // n0x14c4 c0x0000 (---------------) + I trolley 0x00313185, // n0x14c5 c0x0000 (---------------) + I trust 0x00313187, // n0x14c6 c0x0000 (---------------) + I trustee 0x002f53c5, // n0x14c7 c0x0000 (---------------) + I uhren 0x00213f43, // n0x14c8 c0x0000 (---------------) + I ulm 0x002dfb48, // n0x14c9 c0x0000 (---------------) + I undersea 0x0029f04a, // n0x14ca c0x0000 (---------------) + I university 0x00222503, // n0x14cb c0x0000 (---------------) + I usa 0x0022250a, // n0x14cc c0x0000 (---------------) + I usantiques 0x0038c1c6, // n0x14cd c0x0000 (---------------) + I usarts 0x00362b8f, // n0x14ce c0x0000 (---------------) + I uscountryestate 0x00323609, // n0x14cf c0x0000 (---------------) + I usculture 0x00255a50, // n0x14d0 c0x0000 (---------------) + I usdecorativearts 0x002ada08, // n0x14d1 c0x0000 (---------------) + I usgarden 0x002b7209, // n0x14d2 c0x0000 (---------------) + I ushistory 0x00282ac7, // n0x14d3 c0x0000 (---------------) + I ushuaia 0x002a1ccf, // n0x14d4 c0x0000 (---------------) + I uslivinghistory 0x0026a544, // n0x14d5 c0x0000 (---------------) + I utah 0x00357a44, // n0x14d6 c0x0000 (---------------) + I uvic 0x00213d86, // n0x14d7 c0x0000 (---------------) + I valley 0x002292c6, // n0x14d8 c0x0000 (---------------) + I vantaa 0x0038deca, // n0x14d9 c0x0000 (---------------) + I versailles 0x002c7686, // n0x14da c0x0000 (---------------) + I viking 0x00327d47, // n0x14db c0x0000 (---------------) + I village 0x002dd148, // n0x14dc c0x0000 (---------------) + I virginia 0x002dd347, // n0x14dd c0x0000 (---------------) + I virtual 0x002dd507, // n0x14de c0x0000 (---------------) + I virtuel 0x00332eca, // n0x14df c0x0000 (---------------) + I vlaanderen 0x002df98b, // n0x14e0 c0x0000 (---------------) + I volkenkunde 0x0036cbc5, // n0x14e1 c0x0000 (---------------) + I wales 0x0037f608, // n0x14e2 c0x0000 (---------------) + I wallonie 0x00202543, // n0x14e3 c0x0000 (---------------) + I war 0x0025108c, // n0x14e4 c0x0000 (---------------) + I washingtondc 0x0020accf, // n0x14e5 c0x0000 (---------------) + I watch-and-clock 0x0025fe4d, // n0x14e6 c0x0000 (---------------) + I watchandclock 0x0036d147, // n0x14e7 c0x0000 (---------------) + I western 0x00320ec9, // n0x14e8 c0x0000 (---------------) + I westfalen 0x0029b447, // n0x14e9 c0x0000 (---------------) + I whaling 0x00247748, // n0x14ea c0x0000 (---------------) + I wildlife 0x00221a4c, // n0x14eb c0x0000 (---------------) + I williamsburg 0x002a0248, // n0x14ec c0x0000 (---------------) + I windmill 0x0029b088, // n0x14ed c0x0000 (---------------) + I workshop 0x002f608e, // n0x14ee c0x0000 (---------------) + I xn--9dbhblg6di 0x003083d4, // n0x14ef c0x0000 (---------------) + I xn--comunicaes-v6a2o 0x003088e4, // n0x14f0 c0x0000 (---------------) + I xn--correios-e-telecomunicaes-ghc29a 0x0032844a, // n0x14f1 c0x0000 (---------------) + I xn--h1aegh 0x0034760b, // n0x14f2 c0x0000 (---------------) + I xn--lns-qla 0x00237fc4, // n0x14f3 c0x0000 (---------------) + I york 0x00237fc9, // n0x14f4 c0x0000 (---------------) + I yorkshire 0x00297948, // n0x14f5 c0x0000 (---------------) + I yosemite 0x00235bc5, // n0x14f6 c0x0000 (---------------) + I youth 0x0038ba0a, // n0x14f7 c0x0000 (---------------) + I zoological 0x00363207, // n0x14f8 c0x0000 (---------------) + I zoology 0x002751c4, // n0x14f9 c0x0000 (---------------) + I aero 0x00310603, // n0x14fa c0x0000 (---------------) + I biz 0x00222ac3, // n0x14fb c0x0000 (---------------) + I com 0x00228d44, // n0x14fc c0x0000 (---------------) + I coop 0x002d75c3, // n0x14fd c0x0000 (---------------) + I edu 0x0021e283, // n0x14fe c0x0000 (---------------) + I gov 0x00200304, // n0x14ff c0x0000 (---------------) + I info 0x00238c03, // n0x1500 c0x0000 (---------------) + I int 0x0023fa03, // n0x1501 c0x0000 (---------------) + I mil 0x002bd646, // n0x1502 c0x0000 (---------------) + I museum 0x00298944, // n0x1503 c0x0000 (---------------) + I name 0x002170c3, // n0x1504 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1505 c0x0000 (---------------) + I org 0x00218243, // n0x1506 c0x0000 (---------------) + I pro 0x00201e82, // n0x1507 c0x0000 (---------------) + I ac 0x00310603, // n0x1508 c0x0000 (---------------) + I biz 0x00200742, // n0x1509 c0x0000 (---------------) + I co 0x00222ac3, // n0x150a c0x0000 (---------------) + I com 0x00228d44, // n0x150b c0x0000 (---------------) + I coop 0x002d75c3, // n0x150c c0x0000 (---------------) + I edu 0x0021e283, // n0x150d c0x0000 (---------------) + I gov 0x00238c03, // n0x150e c0x0000 (---------------) + I int 0x002bd646, // n0x150f c0x0000 (---------------) + I museum 0x002170c3, // n0x1510 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1511 c0x0000 (---------------) + I org 0x000e4188, // n0x1512 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1513 c0x0000 (---------------) + I com 0x002d75c3, // n0x1514 c0x0000 (---------------) + I edu 0x0034eb03, // n0x1515 c0x0000 (---------------) + I gob 0x002170c3, // n0x1516 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1517 c0x0000 (---------------) + I org 0x000e4188, // n0x1518 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1519 c0x0000 (---------------) + I com 0x002d75c3, // n0x151a c0x0000 (---------------) + I edu 0x0021e283, // n0x151b c0x0000 (---------------) + I gov 0x0023fa03, // n0x151c c0x0000 (---------------) + I mil 0x00298944, // n0x151d c0x0000 (---------------) + I name 0x002170c3, // n0x151e c0x0000 (---------------) + I net 0x0021dcc3, // n0x151f c0x0000 (---------------) + I org 0x006ed3c8, // n0x1520 c0x0001 (---------------) ! I teledata 0x002055c2, // n0x1521 c0x0000 (---------------) + I ca 0x0021aa82, // n0x1522 c0x0000 (---------------) + I cc 0x00200742, // n0x1523 c0x0000 (---------------) + I co 0x00222ac3, // n0x1524 c0x0000 (---------------) + I com 0x0022fb02, // n0x1525 c0x0000 (---------------) + I dr 0x00200242, // n0x1526 c0x0000 (---------------) + I in 0x00200304, // n0x1527 c0x0000 (---------------) + I info 0x00203604, // n0x1528 c0x0000 (---------------) + I mobi 0x0020a682, // n0x1529 c0x0000 (---------------) + I mx 0x00298944, // n0x152a c0x0000 (---------------) + I name 0x00200c42, // n0x152b c0x0000 (---------------) + I or 0x0021dcc3, // n0x152c c0x0000 (---------------) + I org 0x00218243, // n0x152d c0x0000 (---------------) + I pro 0x00235406, // n0x152e c0x0000 (---------------) + I school 0x0020bf42, // n0x152f c0x0000 (---------------) + I tv 0x00209f42, // n0x1530 c0x0000 (---------------) + I us 0x0020ba82, // n0x1531 c0x0000 (---------------) + I ws 0x37e19443, // n0x1532 c0x00df (n0x1534-n0x1535) o I her 0x382238c3, // n0x1533 c0x00e0 (n0x1535-n0x1536) o I his 0x000439c6, // n0x1534 c0x0000 (---------------) + forgot 0x000439c6, // n0x1535 c0x0000 (---------------) + forgot 0x002729c4, // n0x1536 c0x0000 (---------------) + I asso 0x0010054c, // n0x1537 c0x0000 (---------------) + at-band-camp 0x0006c90c, // n0x1538 c0x0000 (---------------) + azure-mobile 0x000aef0d, // n0x1539 c0x0000 (---------------) + azurewebsites 0x000d0087, // n0x153a c0x0000 (---------------) + blogdns 0x00017a88, // n0x153b c0x0000 (---------------) + broke-it 0x0001d90a, // n0x153c c0x0000 (---------------) + buyshouses 0x38e2a085, // n0x153d c0x00e3 (n0x1568-n0x1569) o I cdn77 0x0002a089, // n0x153e c0x0000 (---------------) + cdn77-ssl 0x00192608, // n0x153f c0x0000 (---------------) + cloudapp 0x0019058a, // n0x1540 c0x0000 (---------------) + cloudfront 0x00146fc8, // n0x1541 c0x0000 (---------------) + dnsalias 0x0006a247, // n0x1542 c0x0000 (---------------) + dnsdojo 0x0018a587, // n0x1543 c0x0000 (---------------) + does-it 0x0015fdc9, // n0x1544 c0x0000 (---------------) + dontexist 0x000007c8, // n0x1545 c0x0000 (---------------) + dynalias 0x00078989, // n0x1546 c0x0000 (---------------) + dynathome 0x0009428d, // n0x1547 c0x0000 (---------------) + endofinternet 0x39287d46, // n0x1548 c0x00e4 (n0x1569-n0x156b) o I fastly 0x0004dac7, // n0x1549 c0x0000 (---------------) + from-az 0x0004f247, // n0x154a c0x0000 (---------------) + from-co 0x00056b87, // n0x154b c0x0000 (---------------) + from-la 0x0005c687, // n0x154c c0x0000 (---------------) + from-ny 0x00005a42, // n0x154d c0x0000 (---------------) + gb 0x00104507, // n0x154e c0x0000 (---------------) + gets-it 0x0005058c, // n0x154f c0x0000 (---------------) + ham-radio-op 0x00085007, // n0x1550 c0x0000 (---------------) + homeftp 0x000909c6, // n0x1551 c0x0000 (---------------) + homeip 0x00090ec9, // n0x1552 c0x0000 (---------------) + homelinux 0x00091b88, // n0x1553 c0x0000 (---------------) + homeunix 0x00017d42, // n0x1554 c0x0000 (---------------) + hu 0x00000242, // n0x1555 c0x0000 (---------------) + in 0x0005554b, // n0x1556 c0x0000 (---------------) + in-the-band 0x00166909, // n0x1557 c0x0000 (---------------) + is-a-chef 0x00052e49, // n0x1558 c0x0000 (---------------) + is-a-geek 0x00191648, // n0x1559 c0x0000 (---------------) + isa-geek 0x000990c2, // n0x155a c0x0000 (---------------) + jp 0x00183609, // n0x155b c0x0000 (---------------) + kicks-ass 0x00019c4d, // n0x155c c0x0000 (---------------) + office-on-the 0x000c7e07, // n0x155d c0x0000 (---------------) + podzone 0x0004294d, // n0x155e c0x0000 (---------------) + scrapper-site 0x00002e82, // n0x155f c0x0000 (---------------) + se 0x00130f46, // n0x1560 c0x0000 (---------------) + selfip 0x0007efc8, // n0x1561 c0x0000 (---------------) + sells-it 0x00079088, // n0x1562 c0x0000 (---------------) + servebbs 0x00161348, // n0x1563 c0x0000 (---------------) + serveftp 0x0003f688, // n0x1564 c0x0000 (---------------) + thruhere 0x0000cf02, // n0x1565 c0x0000 (---------------) + uk 0x00110e86, // n0x1566 c0x0000 (---------------) + webhop 0x000043c2, // n0x1567 c0x0000 (---------------) + za 0x00000581, // n0x1568 c0x0000 (---------------) + r 0x396cbe44, // n0x1569 c0x00e5 (n0x156b-n0x156d) o I prod 0x39a2a203, // n0x156a c0x00e6 (n0x156d-n0x1570) o I ssl 0x00000181, // n0x156b c0x0000 (---------------) + a 0x00189c06, // n0x156c c0x0000 (---------------) + global 0x00000181, // n0x156d c0x0000 (---------------) + a 0x00000001, // n0x156e c0x0000 (---------------) + b 0x00189c06, // n0x156f c0x0000 (---------------) + global 0x00246584, // n0x1570 c0x0000 (---------------) + I arts 0x00222ac3, // n0x1571 c0x0000 (---------------) + I com 0x00238544, // n0x1572 c0x0000 (---------------) + I firm 0x00200304, // n0x1573 c0x0000 (---------------) + I info 0x002170c3, // n0x1574 c0x0000 (---------------) + I net 0x002193c5, // n0x1575 c0x0000 (---------------) + I other 0x00214943, // n0x1576 c0x0000 (---------------) + I per 0x002e6343, // n0x1577 c0x0000 (---------------) + I rec 0x002cf4c5, // n0x1578 c0x0000 (---------------) + I store 0x00219fc3, // n0x1579 c0x0000 (---------------) + I web 0x3a622ac3, // n0x157a c0x00e9 (n0x1583-n0x1584) + I com 0x002d75c3, // n0x157b c0x0000 (---------------) + I edu 0x0021e283, // n0x157c c0x0000 (---------------) + I gov 0x0023fa03, // n0x157d c0x0000 (---------------) + I mil 0x00203604, // n0x157e c0x0000 (---------------) + I mobi 0x00298944, // n0x157f c0x0000 (---------------) + I name 0x002170c3, // n0x1580 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1581 c0x0000 (---------------) + I org 0x00206103, // n0x1582 c0x0000 (---------------) + I sch 0x000e4188, // n0x1583 c0x0000 (---------------) + blogspot 0x000e4188, // n0x1584 c0x0000 (---------------) + blogspot 0x003401c2, // n0x1585 c0x0000 (---------------) + I bv 0x00000742, // n0x1586 c0x0000 (---------------) + co 0x3b21b502, // n0x1587 c0x00ec (n0x185d-n0x185e) + I aa 0x00301488, // n0x1588 c0x0000 (---------------) + I aarborte 0x0021b986, // n0x1589 c0x0000 (---------------) + I aejrie 0x002aa946, // n0x158a c0x0000 (---------------) + I afjord 0x0021b307, // n0x158b c0x0000 (---------------) + I agdenes 0x3b6076c2, // n0x158c c0x00ed (n0x185e-n0x185f) + I ah 0x3ba2b548, // n0x158d c0x00ee (n0x185f-n0x1860) o I akershus 0x0031a9ca, // n0x158e c0x0000 (---------------) + I aknoluokta 0x0024d548, // n0x158f c0x0000 (---------------) + I akrehamn 0x00200882, // n0x1590 c0x0000 (---------------) + I al 0x0036e809, // n0x1591 c0x0000 (---------------) + I alaheadju 0x0036cc07, // n0x1592 c0x0000 (---------------) + I alesund 0x0020e486, // n0x1593 c0x0000 (---------------) + I algard 0x00219749, // n0x1594 c0x0000 (---------------) + I alstahaug 0x0028ee04, // n0x1595 c0x0000 (---------------) + I alta 0x002ab3c6, // n0x1596 c0x0000 (---------------) + I alvdal 0x002aad44, // n0x1597 c0x0000 (---------------) + I amli 0x0025cb44, // n0x1598 c0x0000 (---------------) + I amot 0x00245409, // n0x1599 c0x0000 (---------------) + I andasuolo 0x002ee906, // n0x159a c0x0000 (---------------) + I andebu 0x0034bfc5, // n0x159b c0x0000 (---------------) + I andoy 0x00279985, // n0x159c c0x0000 (---------------) + I ardal 0x002a6dc7, // n0x159d c0x0000 (---------------) + I aremark 0x00275c47, // n0x159e c0x0000 (---------------) + I arendal 0x002798c4, // n0x159f c0x0000 (---------------) + I arna 0x0021b546, // n0x15a0 c0x0000 (---------------) + I aseral 0x00212605, // n0x15a1 c0x0000 (---------------) + I asker 0x0027d585, // n0x15a2 c0x0000 (---------------) + I askim 0x0031d885, // n0x15a3 c0x0000 (---------------) + I askoy 0x002dbc07, // n0x15a4 c0x0000 (---------------) + I askvoll 0x00311545, // n0x15a5 c0x0000 (---------------) + I asnes 0x002f1489, // n0x15a6 c0x0000 (---------------) + I audnedaln 0x00271305, // n0x15a7 c0x0000 (---------------) + I aukra 0x002e0084, // n0x15a8 c0x0000 (---------------) + I aure 0x0035b087, // n0x15a9 c0x0000 (---------------) + I aurland 0x0036d70e, // n0x15aa c0x0000 (---------------) + I aurskog-holand 0x003298c9, // n0x15ab c0x0000 (---------------) + I austevoll 0x002f5049, // n0x15ac c0x0000 (---------------) + I austrheim 0x0030dc86, // n0x15ad c0x0000 (---------------) + I averoy 0x00321688, // n0x15ae c0x0000 (---------------) + I badaddja 0x00329f8b, // n0x15af c0x0000 (---------------) + I bahcavuotna 0x002a080c, // n0x15b0 c0x0000 (---------------) + I bahccavuotna 0x00323c86, // n0x15b1 c0x0000 (---------------) + I baidar 0x00342887, // n0x15b2 c0x0000 (---------------) + I bajddar 0x0035dbc5, // n0x15b3 c0x0000 (---------------) + I balat 0x0023d9ca, // n0x15b4 c0x0000 (---------------) + I balestrand 0x0030b989, // n0x15b5 c0x0000 (---------------) + I ballangen 0x00268ec9, // n0x15b6 c0x0000 (---------------) + I balsfjord 0x002c8706, // n0x15b7 c0x0000 (---------------) + I bamble 0x002d37c5, // n0x15b8 c0x0000 (---------------) + I bardu 0x002b0545, // n0x15b9 c0x0000 (---------------) + I barum 0x0031a6c9, // n0x15ba c0x0000 (---------------) + I batsfjord 0x0035ddcb, // n0x15bb c0x0000 (---------------) + I bearalvahki 0x00269f06, // n0x15bc c0x0000 (---------------) + I beardu 0x00319a86, // n0x15bd c0x0000 (---------------) + I beiarn 0x00204704, // n0x15be c0x0000 (---------------) + I berg 0x00279f06, // n0x15bf c0x0000 (---------------) + I bergen 0x00343e08, // n0x15c0 c0x0000 (---------------) + I berlevag 0x00389486, // n0x15c1 c0x0000 (---------------) + I bievat 0x00219046, // n0x15c2 c0x0000 (---------------) + I bindal 0x00200f48, // n0x15c3 c0x0000 (---------------) + I birkenes 0x00202647, // n0x15c4 c0x0000 (---------------) + I bjarkoy 0x002033c9, // n0x15c5 c0x0000 (---------------) + I bjerkreim 0x00205005, // n0x15c6 c0x0000 (---------------) + I bjugn 0x000e4188, // n0x15c7 c0x0000 (---------------) + blogspot 0x0038a504, // n0x15c8 c0x0000 (---------------) + I bodo 0x0029bf44, // n0x15c9 c0x0000 (---------------) + I bokn 0x0020aac5, // n0x15ca c0x0000 (---------------) + I bomlo 0x0037dc49, // n0x15cb c0x0000 (---------------) + I bremanger 0x00218ac7, // n0x15cc c0x0000 (---------------) + I bronnoy 0x00218acb, // n0x15cd c0x0000 (---------------) + I bronnoysund 0x0021a7ca, // n0x15ce c0x0000 (---------------) + I brumunddal 0x0021d4c5, // n0x15cf c0x0000 (---------------) + I bryne 0x3be0a582, // n0x15d0 c0x00ef (n0x1860-n0x1861) + I bu 0x002eea07, // n0x15d1 c0x0000 (---------------) + I budejju 0x3c318ec8, // n0x15d2 c0x00f0 (n0x1861-n0x1862) o I buskerud 0x00251987, // n0x15d3 c0x0000 (---------------) + I bygland 0x0025f245, // n0x15d4 c0x0000 (---------------) + I bykle 0x0032234a, // n0x15d5 c0x0000 (---------------) + I cahcesuolo 0x00000742, // n0x15d6 c0x0000 (---------------) + co 0x0024fd0b, // n0x15d7 c0x0000 (---------------) + I davvenjarga 0x0024eb4a, // n0x15d8 c0x0000 (---------------) + I davvesiida 0x002e9206, // n0x15d9 c0x0000 (---------------) + I deatnu 0x002b8f83, // n0x15da c0x0000 (---------------) + I dep 0x0023404d, // n0x15db c0x0000 (---------------) + I dielddanuorri 0x0023e18c, // n0x15dc c0x0000 (---------------) + I divtasvuodna 0x002690cd, // n0x15dd c0x0000 (---------------) + I divttasvuotna 0x002f8b05, // n0x15de c0x0000 (---------------) + I donna 0x002396c5, // n0x15df c0x0000 (---------------) + I dovre 0x0034d707, // n0x15e0 c0x0000 (---------------) + I drammen 0x002edfc9, // n0x15e1 c0x0000 (---------------) + I drangedal 0x0031a8c6, // n0x15e2 c0x0000 (---------------) + I drobak 0x002c7505, // n0x15e3 c0x0000 (---------------) + I dyroy 0x0021e888, // n0x15e4 c0x0000 (---------------) + I egersund 0x00262743, // n0x15e5 c0x0000 (---------------) + I eid 0x002ec4c8, // n0x15e6 c0x0000 (---------------) + I eidfjord 0x00279e08, // n0x15e7 c0x0000 (---------------) + I eidsberg 0x002ac2c7, // n0x15e8 c0x0000 (---------------) + I eidskog 0x00262748, // n0x15e9 c0x0000 (---------------) + I eidsvoll 0x00383049, // n0x15ea c0x0000 (---------------) + I eigersund 0x00227ec7, // n0x15eb c0x0000 (---------------) + I elverum 0x00300e87, // n0x15ec c0x0000 (---------------) + I enebakk 0x002674c8, // n0x15ed c0x0000 (---------------) + I engerdal 0x002569c4, // n0x15ee c0x0000 (---------------) + I etne 0x002569c7, // n0x15ef c0x0000 (---------------) + I etnedal 0x0037ab48, // n0x15f0 c0x0000 (---------------) + I evenassi 0x0030a446, // n0x15f1 c0x0000 (---------------) + I evenes 0x00201f0f, // n0x15f2 c0x0000 (---------------) + I evje-og-hornnes 0x00345a07, // n0x15f3 c0x0000 (---------------) + I farsund 0x002c3146, // n0x15f4 c0x0000 (---------------) + I fauske 0x0020c745, // n0x15f5 c0x0000 (---------------) + I fedje 0x00234803, // n0x15f6 c0x0000 (---------------) + I fet 0x00324187, // n0x15f7 c0x0000 (---------------) + I fetsund 0x00235ec3, // n0x15f8 c0x0000 (---------------) + I fhs 0x002365c6, // n0x15f9 c0x0000 (---------------) + I finnoy 0x00238f06, // n0x15fa c0x0000 (---------------) + I fitjar 0x00239986, // n0x15fb c0x0000 (---------------) + I fjaler 0x0027e245, // n0x15fc c0x0000 (---------------) + I fjell 0x00252b83, // n0x15fd c0x0000 (---------------) + I fla 0x0035be08, // n0x15fe c0x0000 (---------------) + I flakstad 0x00353389, // n0x15ff c0x0000 (---------------) + I flatanger 0x0036500b, // n0x1600 c0x0000 (---------------) + I flekkefjord 0x00239b08, // n0x1601 c0x0000 (---------------) + I flesberg 0x0023c105, // n0x1602 c0x0000 (---------------) + I flora 0x0023d4c5, // n0x1603 c0x0000 (---------------) + I floro 0x3c758002, // n0x1604 c0x00f1 (n0x1862-n0x1863) + I fm 0x00362789, // n0x1605 c0x0000 (---------------) + I folkebibl 0x00241787, // n0x1606 c0x0000 (---------------) + I folldal 0x003640c5, // n0x1607 c0x0000 (---------------) + I forde 0x00245307, // n0x1608 c0x0000 (---------------) + I forsand 0x00247586, // n0x1609 c0x0000 (---------------) + I fosnes 0x0034af05, // n0x160a c0x0000 (---------------) + I frana 0x0024804b, // n0x160b c0x0000 (---------------) + I fredrikstad 0x00248cc4, // n0x160c c0x0000 (---------------) + I frei 0x0024d105, // n0x160d c0x0000 (---------------) + I frogn 0x0024d247, // n0x160e c0x0000 (---------------) + I froland 0x00263e06, // n0x160f c0x0000 (---------------) + I frosta 0x00264245, // n0x1610 c0x0000 (---------------) + I froya 0x0026fe07, // n0x1611 c0x0000 (---------------) + I fuoisku 0x00270587, // n0x1612 c0x0000 (---------------) + I fuossko 0x002a7504, // n0x1613 c0x0000 (---------------) + I fusa 0x0027798a, // n0x1614 c0x0000 (---------------) + I fylkesbibl 0x00277e48, // n0x1615 c0x0000 (---------------) + I fyresdal 0x0035ea49, // n0x1616 c0x0000 (---------------) + I gaivuotna 0x00215b85, // n0x1617 c0x0000 (---------------) + I galsa 0x0024ff46, // n0x1618 c0x0000 (---------------) + I gamvik 0x00343fca, // n0x1619 c0x0000 (---------------) + I gangaviika 0x003442c6, // n0x161a c0x0000 (---------------) + I gaular 0x002542c7, // n0x161b c0x0000 (---------------) + I gausdal 0x0035e70d, // n0x161c c0x0000 (---------------) + I giehtavuoatna 0x00220049, // n0x161d c0x0000 (---------------) + I gildeskal 0x00347945, // n0x161e c0x0000 (---------------) + I giske 0x0030ee07, // n0x161f c0x0000 (---------------) + I gjemnes 0x002ed908, // n0x1620 c0x0000 (---------------) + I gjerdrum 0x0031c188, // n0x1621 c0x0000 (---------------) + I gjerstad 0x0031d607, // n0x1622 c0x0000 (---------------) + I gjesdal 0x003446c6, // n0x1623 c0x0000 (---------------) + I gjovik 0x00395287, // n0x1624 c0x0000 (---------------) + I gloppen 0x00238a83, // n0x1625 c0x0000 (---------------) + I gol 0x00320b04, // n0x1626 c0x0000 (---------------) + I gran 0x00348cc5, // n0x1627 c0x0000 (---------------) + I grane 0x00376107, // n0x1628 c0x0000 (---------------) + I granvin 0x00379f89, // n0x1629 c0x0000 (---------------) + I gratangen 0x002136c8, // n0x162a c0x0000 (---------------) + I grimstad 0x002c77c5, // n0x162b c0x0000 (---------------) + I grong 0x00222fc4, // n0x162c c0x0000 (---------------) + I grue 0x00331485, // n0x162d c0x0000 (---------------) + I gulen 0x002373cd, // n0x162e c0x0000 (---------------) + I guovdageaidnu 0x00202dc2, // n0x162f c0x0000 (---------------) + I ha 0x00289a46, // n0x1630 c0x0000 (---------------) + I habmer 0x00330e86, // n0x1631 c0x0000 (---------------) + I hadsel 0x002f5e0a, // n0x1632 c0x0000 (---------------) + I hagebostad 0x0035b7c6, // n0x1633 c0x0000 (---------------) + I halden 0x00363605, // n0x1634 c0x0000 (---------------) + I halsa 0x0036e045, // n0x1635 c0x0000 (---------------) + I hamar 0x0036e047, // n0x1636 c0x0000 (---------------) + I hamaroy 0x0036794c, // n0x1637 c0x0000 (---------------) + I hammarfeasta 0x002ef38a, // n0x1638 c0x0000 (---------------) + I hammerfest 0x002796c6, // n0x1639 c0x0000 (---------------) + I hapmir 0x002ae105, // n0x163a c0x0000 (---------------) + I haram 0x00279d46, // n0x163b c0x0000 (---------------) + I hareid 0x0027a087, // n0x163c c0x0000 (---------------) + I harstad 0x0027b486, // n0x163d c0x0000 (---------------) + I hasvik 0x0027e14c, // n0x163e c0x0000 (---------------) + I hattfjelldal 0x00219889, // n0x163f c0x0000 (---------------) + I haugesund 0x3ca9bc07, // n0x1640 c0x00f2 (n0x1863-n0x1866) o I hedmark 0x0027f885, // n0x1641 c0x0000 (---------------) + I hemne 0x0027f886, // n0x1642 c0x0000 (---------------) + I hemnes 0x0027fc88, // n0x1643 c0x0000 (---------------) + I hemsedal 0x0022db45, // n0x1644 c0x0000 (---------------) + I herad 0x0028fd85, // n0x1645 c0x0000 (---------------) + I hitra 0x0028ffc8, // n0x1646 c0x0000 (---------------) + I hjartdal 0x002901ca, // n0x1647 c0x0000 (---------------) + I hjelmeland 0x3ce0cc02, // n0x1648 c0x00f3 (n0x1866-n0x1867) + I hl 0x3d206182, // n0x1649 c0x00f4 (n0x1867-n0x1868) + I hm 0x002536c5, // n0x164a c0x0000 (---------------) + I hobol 0x0029a803, // n0x164b c0x0000 (---------------) + I hof 0x002c7348, // n0x164c c0x0000 (---------------) + I hokksund 0x002351c3, // n0x164d c0x0000 (---------------) + I hol 0x00290444, // n0x164e c0x0000 (---------------) + I hole 0x0025a04b, // n0x164f c0x0000 (---------------) + I holmestrand 0x00271dc8, // n0x1650 c0x0000 (---------------) + I holtalen 0x00292148, // n0x1651 c0x0000 (---------------) + I honefoss 0x3d6f84c9, // n0x1652 c0x00f5 (n0x1868-n0x1869) o I hordaland 0x002939c9, // n0x1653 c0x0000 (---------------) + I hornindal 0x00294186, // n0x1654 c0x0000 (---------------) + I horten 0x00295188, // n0x1655 c0x0000 (---------------) + I hoyanger 0x00295389, // n0x1656 c0x0000 (---------------) + I hoylandet 0x00296046, // n0x1657 c0x0000 (---------------) + I hurdal 0x002961c5, // n0x1658 c0x0000 (---------------) + I hurum 0x003512c6, // n0x1659 c0x0000 (---------------) + I hvaler 0x0036b589, // n0x165a c0x0000 (---------------) + I hyllestad 0x0030a287, // n0x165b c0x0000 (---------------) + I ibestad 0x00247d86, // n0x165c c0x0000 (---------------) + I idrett 0x002f3407, // n0x165d c0x0000 (---------------) + I inderoy 0x00304b07, // n0x165e c0x0000 (---------------) + I iveland 0x0025f644, // n0x165f c0x0000 (---------------) + I ivgu 0x3da14c09, // n0x1660 c0x00f6 (n0x1869-n0x186a) + I jan-mayen 0x002b4408, // n0x1661 c0x0000 (---------------) + I jessheim 0x00345148, // n0x1662 c0x0000 (---------------) + I jevnaker 0x002326c7, // n0x1663 c0x0000 (---------------) + I jolster 0x002afb86, // n0x1664 c0x0000 (---------------) + I jondal 0x0038a009, // n0x1665 c0x0000 (---------------) + I jorpeland 0x002ab887, // n0x1666 c0x0000 (---------------) + I kafjord 0x0022e84a, // n0x1667 c0x0000 (---------------) + I karasjohka 0x002d8848, // n0x1668 c0x0000 (---------------) + I karasjok 0x0023eb87, // n0x1669 c0x0000 (---------------) + I karlsoy 0x00305646, // n0x166a c0x0000 (---------------) + I karmoy 0x002eaa8a, // n0x166b c0x0000 (---------------) + I kautokeino 0x0023cc48, // n0x166c c0x0000 (---------------) + I kirkenes 0x0025ef45, // n0x166d c0x0000 (---------------) + I klabu 0x0021cd85, // n0x166e c0x0000 (---------------) + I klepp 0x002ac947, // n0x166f c0x0000 (---------------) + I kommune 0x002b7dc9, // n0x1670 c0x0000 (---------------) + I kongsberg 0x002b814b, // n0x1671 c0x0000 (---------------) + I kongsvinger 0x002c83c8, // n0x1672 c0x0000 (---------------) + I kopervik 0x00271389, // n0x1673 c0x0000 (---------------) + I kraanghke 0x0023a407, // n0x1674 c0x0000 (---------------) + I kragero 0x0029db0c, // n0x1675 c0x0000 (---------------) + I kristiansand 0x0029df8c, // n0x1676 c0x0000 (---------------) + I kristiansund 0x0029e28a, // n0x1677 c0x0000 (---------------) + I krodsherad 0x0029e50c, // n0x1678 c0x0000 (---------------) + I krokstadelva 0x002aa8c8, // n0x1679 c0x0000 (---------------) + I kvafjord 0x002aaac8, // n0x167a c0x0000 (---------------) + I kvalsund 0x002aacc4, // n0x167b c0x0000 (---------------) + I kvam 0x002aba49, // n0x167c c0x0000 (---------------) + I kvanangen 0x002abc89, // n0x167d c0x0000 (---------------) + I kvinesdal 0x002abeca, // n0x167e c0x0000 (---------------) + I kvinnherad 0x002ac149, // n0x167f c0x0000 (---------------) + I kviteseid 0x002ac487, // n0x1680 c0x0000 (---------------) + I kvitsoy 0x00381bcc, // n0x1681 c0x0000 (---------------) + I laakesvuemie 0x00207686, // n0x1682 c0x0000 (---------------) + I lahppi 0x00256cc8, // n0x1683 c0x0000 (---------------) + I langevag 0x00344386, // n0x1684 c0x0000 (---------------) + I lardal 0x002d7a86, // n0x1685 c0x0000 (---------------) + I larvik 0x00347847, // n0x1686 c0x0000 (---------------) + I lavagis 0x00358888, // n0x1687 c0x0000 (---------------) + I lavangen 0x002f020b, // n0x1688 c0x0000 (---------------) + I leangaviika 0x00251847, // n0x1689 c0x0000 (---------------) + I lebesby 0x00227989, // n0x168a c0x0000 (---------------) + I leikanger 0x002386c9, // n0x168b c0x0000 (---------------) + I leirfjord 0x00244b87, // n0x168c c0x0000 (---------------) + I leirvik 0x00203c44, // n0x168d c0x0000 (---------------) + I leka 0x0034b3c7, // n0x168e c0x0000 (---------------) + I leksvik 0x00364686, // n0x168f c0x0000 (---------------) + I lenvik 0x00364246, // n0x1690 c0x0000 (---------------) + I lerdal 0x002a5105, // n0x1691 c0x0000 (---------------) + I lesja 0x00326448, // n0x1692 c0x0000 (---------------) + I levanger 0x002a6004, // n0x1693 c0x0000 (---------------) + I lier 0x002a6006, // n0x1694 c0x0000 (---------------) + I lierne 0x002ef24b, // n0x1695 c0x0000 (---------------) + I lillehammer 0x00270d89, // n0x1696 c0x0000 (---------------) + I lillesand 0x0031d786, // n0x1697 c0x0000 (---------------) + I lindas 0x0031dc09, // n0x1698 c0x0000 (---------------) + I lindesnes 0x002dbd86, // n0x1699 c0x0000 (---------------) + I loabat 0x002455c8, // n0x169a c0x0000 (---------------) + I lodingen 0x00260a43, // n0x169b c0x0000 (---------------) + I lom 0x0031b945, // n0x169c c0x0000 (---------------) + I loppa 0x003444c9, // n0x169d c0x0000 (---------------) + I lorenskog 0x0034d145, // n0x169e c0x0000 (---------------) + I loten 0x002d8b84, // n0x169f c0x0000 (---------------) + I lund 0x00263646, // n0x16a0 c0x0000 (---------------) + I lunner 0x0029cb85, // n0x16a1 c0x0000 (---------------) + I luroy 0x002c7bc6, // n0x16a2 c0x0000 (---------------) + I luster 0x002e1c87, // n0x16a3 c0x0000 (---------------) + I lyngdal 0x0029c206, // n0x16a4 c0x0000 (---------------) + I lyngen 0x0028448b, // n0x16a5 c0x0000 (---------------) + I malatvuopmi 0x0034ce07, // n0x16a6 c0x0000 (---------------) + I malselv 0x00307d86, // n0x16a7 c0x0000 (---------------) + I malvik 0x00358046, // n0x16a8 c0x0000 (---------------) + I mandal 0x002a6e86, // n0x16a9 c0x0000 (---------------) + I marker 0x00279889, // n0x16aa c0x0000 (---------------) + I marnardal 0x003419ca, // n0x16ab c0x0000 (---------------) + I masfjorden 0x00314445, // n0x16ac c0x0000 (---------------) + I masoy 0x0020f58d, // n0x16ad c0x0000 (---------------) + I matta-varjjat 0x002902c6, // n0x16ae c0x0000 (---------------) + I meland 0x002d8246, // n0x16af c0x0000 (---------------) + I meldal 0x002a1bc6, // n0x16b0 c0x0000 (---------------) + I melhus 0x00259d05, // n0x16b1 c0x0000 (---------------) + I meloy 0x0022b487, // n0x16b2 c0x0000 (---------------) + I meraker 0x002886c7, // n0x16b3 c0x0000 (---------------) + I midsund 0x002061ce, // n0x16b4 c0x0000 (---------------) + I midtre-gauldal 0x0023fa03, // n0x16b5 c0x0000 (---------------) + I mil 0x002afb49, // n0x16b6 c0x0000 (---------------) + I mjondalen 0x002f3689, // n0x16b7 c0x0000 (---------------) + I mo-i-rana 0x0023ddc7, // n0x16b8 c0x0000 (---------------) + I moareke 0x00208487, // n0x16b9 c0x0000 (---------------) + I modalen 0x003120c5, // n0x16ba c0x0000 (---------------) + I modum 0x0029f845, // n0x16bb c0x0000 (---------------) + I molde 0x3de70a0f, // n0x16bc c0x00f7 (n0x186a-n0x186c) o I more-og-romsdal 0x002b7447, // n0x16bd c0x0000 (---------------) + I mosjoen 0x002b7608, // n0x16be c0x0000 (---------------) + I moskenes 0x002b7b44, // n0x16bf c0x0000 (---------------) + I moss 0x002b8006, // n0x16c0 c0x0000 (---------------) + I mosvik 0x3e2dcb42, // n0x16c1 c0x00f8 (n0x186c-n0x186d) + I mr 0x002bb5c6, // n0x16c2 c0x0000 (---------------) + I muosat 0x002bd646, // n0x16c3 c0x0000 (---------------) + I museum 0x002f054e, // n0x16c4 c0x0000 (---------------) + I naamesjevuemie 0x002ec30a, // n0x16c5 c0x0000 (---------------) + I namdalseid 0x0021c1c6, // n0x16c6 c0x0000 (---------------) + I namsos 0x00232b4a, // n0x16c7 c0x0000 (---------------) + I namsskogan 0x002b2489, // n0x16c8 c0x0000 (---------------) + I nannestad 0x002ff685, // n0x16c9 c0x0000 (---------------) + I naroy 0x0037c388, // n0x16ca c0x0000 (---------------) + I narviika 0x00393206, // n0x16cb c0x0000 (---------------) + I narvik 0x0031e108, // n0x16cc c0x0000 (---------------) + I naustdal 0x00354f08, // n0x16cd c0x0000 (---------------) + I navuotna 0x00395acb, // n0x16ce c0x0000 (---------------) + I nedre-eiker 0x0021b405, // n0x16cf c0x0000 (---------------) + I nesna 0x003115c8, // n0x16d0 c0x0000 (---------------) + I nesodden 0x0020108c, // n0x16d1 c0x0000 (---------------) + I nesoddtangen 0x0025f107, // n0x16d2 c0x0000 (---------------) + I nesseby 0x00239146, // n0x16d3 c0x0000 (---------------) + I nesset 0x002e6588, // n0x16d4 c0x0000 (---------------) + I nissedal 0x002677c8, // n0x16d5 c0x0000 (---------------) + I nittedal 0x3e636482, // n0x16d6 c0x00f9 (n0x186d-n0x186e) + I nl 0x002ab18b, // n0x16d7 c0x0000 (---------------) + I nord-aurdal 0x00200c09, // n0x16d8 c0x0000 (---------------) + I nord-fron 0x003473c9, // n0x16d9 c0x0000 (---------------) + I nord-odal 0x0031da87, // n0x16da c0x0000 (---------------) + I norddal 0x002befc8, // n0x16db c0x0000 (---------------) + I nordkapp 0x3ea3dfc8, // n0x16dc c0x00fa (n0x186e-n0x1872) o I nordland 0x002c5f0b, // n0x16dd c0x0000 (---------------) + I nordre-land 0x003914c9, // n0x16de c0x0000 (---------------) + I nordreisa 0x002113cd, // n0x16df c0x0000 (---------------) + I nore-og-uvdal 0x0023fdc8, // n0x16e0 c0x0000 (---------------) + I notodden 0x00288b08, // n0x16e1 c0x0000 (---------------) + I notteroy 0x3ee00e02, // n0x16e2 c0x00fb (n0x1872-n0x1873) + I nt 0x00396f44, // n0x16e3 c0x0000 (---------------) + I odda 0x3f209982, // n0x16e4 c0x00fc (n0x1873-n0x1874) + I of 0x002d89c6, // n0x16e5 c0x0000 (---------------) + I oksnes 0x3f600a02, // n0x16e6 c0x00fd (n0x1874-n0x1875) + I ol 0x0021d00a, // n0x16e7 c0x0000 (---------------) + I omasvuotna 0x0029b206, // n0x16e8 c0x0000 (---------------) + I oppdal 0x00220b88, // n0x16e9 c0x0000 (---------------) + I oppegard 0x00241b48, // n0x16ea c0x0000 (---------------) + I orkanger 0x00321986, // n0x16eb c0x0000 (---------------) + I orkdal 0x0032e206, // n0x16ec c0x0000 (---------------) + I orland 0x002ce006, // n0x16ed c0x0000 (---------------) + I orskog 0x0029fac5, // n0x16ee c0x0000 (---------------) + I orsta 0x0022be04, // n0x16ef c0x0000 (---------------) + I osen 0x3fab8a04, // n0x16f0 c0x00fe (n0x1875-n0x1876) + I oslo 0x00207f86, // n0x16f1 c0x0000 (---------------) + I osoyro 0x002586c7, // n0x16f2 c0x0000 (---------------) + I osteroy 0x3fed6987, // n0x16f3 c0x00ff (n0x1876-n0x1877) o I ostfold 0x0020300b, // n0x16f4 c0x0000 (---------------) + I ostre-toten 0x0036dac9, // n0x16f5 c0x0000 (---------------) + I overhalla 0x0023970a, // n0x16f6 c0x0000 (---------------) + I ovre-eiker 0x002f3544, // n0x16f7 c0x0000 (---------------) + I oyer 0x00300d08, // n0x16f8 c0x0000 (---------------) + I oygarden 0x00247b4d, // n0x16f9 c0x0000 (---------------) + I oystre-slidre 0x002c9e89, // n0x16fa c0x0000 (---------------) + I porsanger 0x002ca0c8, // n0x16fb c0x0000 (---------------) + I porsangu 0x002ca349, // n0x16fc c0x0000 (---------------) + I porsgrunn 0x002cba44, // n0x16fd c0x0000 (---------------) + I priv 0x00212ec4, // n0x16fe c0x0000 (---------------) + I rade 0x00254d85, // n0x16ff c0x0000 (---------------) + I radoy 0x0035f14b, // n0x1700 c0x0000 (---------------) + I rahkkeravju 0x00271d46, // n0x1701 c0x0000 (---------------) + I raholt 0x002a2305, // n0x1702 c0x0000 (---------------) + I raisa 0x0032a2c9, // n0x1703 c0x0000 (---------------) + I rakkestad 0x0021b608, // n0x1704 c0x0000 (---------------) + I ralingen 0x0025abc4, // n0x1705 c0x0000 (---------------) + I rana 0x0023db49, // n0x1706 c0x0000 (---------------) + I randaberg 0x0026a685, // n0x1707 c0x0000 (---------------) + I rauma 0x00275c88, // n0x1708 c0x0000 (---------------) + I rendalen 0x0033c507, // n0x1709 c0x0000 (---------------) + I rennebu 0x002f5448, // n0x170a c0x0000 (---------------) + I rennesoy 0x002af746, // n0x170b c0x0000 (---------------) + I rindal 0x003247c7, // n0x170c c0x0000 (---------------) + I ringebu 0x002a8c49, // n0x170d c0x0000 (---------------) + I ringerike 0x00324cc9, // n0x170e c0x0000 (---------------) + I ringsaker 0x0025b4c5, // n0x170f c0x0000 (---------------) + I risor 0x002346c5, // n0x1710 c0x0000 (---------------) + I rissa 0x4021d702, // n0x1711 c0x0100 (n0x1877-n0x1878) + I rl 0x002dfe44, // n0x1712 c0x0000 (---------------) + I roan 0x0036a305, // n0x1713 c0x0000 (---------------) + I rodoy 0x0033c1c6, // n0x1714 c0x0000 (---------------) + I rollag 0x00302a85, // n0x1715 c0x0000 (---------------) + I romsa 0x0023d587, // n0x1716 c0x0000 (---------------) + I romskog 0x002e3245, // n0x1717 c0x0000 (---------------) + I roros 0x00263e44, // n0x1718 c0x0000 (---------------) + I rost 0x0030dd46, // n0x1719 c0x0000 (---------------) + I royken 0x002c7587, // n0x171a c0x0000 (---------------) + I royrvik 0x002dcb86, // n0x171b c0x0000 (---------------) + I ruovat 0x00268ac5, // n0x171c c0x0000 (---------------) + I rygge 0x0031ce08, // n0x171d c0x0000 (---------------) + I salangen 0x0031de05, // n0x171e c0x0000 (---------------) + I salat 0x00341347, // n0x171f c0x0000 (---------------) + I saltdal 0x0035b289, // n0x1720 c0x0000 (---------------) + I samnanger 0x0029dd0a, // n0x1721 c0x0000 (---------------) + I sandefjord 0x0023bac7, // n0x1722 c0x0000 (---------------) + I sandnes 0x0023bacc, // n0x1723 c0x0000 (---------------) + I sandnessjoen 0x0034bf86, // n0x1724 c0x0000 (---------------) + I sandoy 0x0021db49, // n0x1725 c0x0000 (---------------) + I sarpsborg 0x0022d7c5, // n0x1726 c0x0000 (---------------) + I sauda 0x0022da88, // n0x1727 c0x0000 (---------------) + I sauherad 0x0020a4c3, // n0x1728 c0x0000 (---------------) + I sel 0x0020a4c5, // n0x1729 c0x0000 (---------------) + I selbu 0x002fad85, // n0x172a c0x0000 (---------------) + I selje 0x00245cc7, // n0x172b c0x0000 (---------------) + I seljord 0x4060f182, // n0x172c c0x0101 (n0x1878-n0x1879) + I sf 0x0023b647, // n0x172d c0x0000 (---------------) + I siellak 0x002b79c6, // n0x172e c0x0000 (---------------) + I sigdal 0x00214b46, // n0x172f c0x0000 (---------------) + I siljan 0x002c1186, // n0x1730 c0x0000 (---------------) + I sirdal 0x00267706, // n0x1731 c0x0000 (---------------) + I skanit 0x00310108, // n0x1732 c0x0000 (---------------) + I skanland 0x00262585, // n0x1733 c0x0000 (---------------) + I skaun 0x002c3207, // n0x1734 c0x0000 (---------------) + I skedsmo 0x002c320d, // n0x1735 c0x0000 (---------------) + I skedsmokorset 0x00207b43, // n0x1736 c0x0000 (---------------) + I ski 0x00207b45, // n0x1737 c0x0000 (---------------) + I skien 0x002f2d47, // n0x1738 c0x0000 (---------------) + I skierva 0x0036b048, // n0x1739 c0x0000 (---------------) + I skiptvet 0x0036ac05, // n0x173a c0x0000 (---------------) + I skjak 0x0030c348, // n0x173b c0x0000 (---------------) + I skjervoy 0x002206c6, // n0x173c c0x0000 (---------------) + I skodje 0x0022a247, // n0x173d c0x0000 (---------------) + I slattum 0x00285605, // n0x173e c0x0000 (---------------) + I smola 0x0021b486, // n0x173f c0x0000 (---------------) + I snaase 0x00340405, // n0x1740 c0x0000 (---------------) + I snasa 0x002aa34a, // n0x1741 c0x0000 (---------------) + I snillfjord 0x002c4f86, // n0x1742 c0x0000 (---------------) + I snoasa 0x002141c7, // n0x1743 c0x0000 (---------------) + I sogndal 0x00308285, // n0x1744 c0x0000 (---------------) + I sogne 0x002d9347, // n0x1745 c0x0000 (---------------) + I sokndal 0x002d0204, // n0x1746 c0x0000 (---------------) + I sola 0x002d8b06, // n0x1747 c0x0000 (---------------) + I solund 0x002da005, // n0x1748 c0x0000 (---------------) + I somna 0x002ee70b, // n0x1749 c0x0000 (---------------) + I sondre-land 0x00364509, // n0x174a c0x0000 (---------------) + I songdalen 0x0037184a, // n0x174b c0x0000 (---------------) + I sor-aurdal 0x0025b548, // n0x174c c0x0000 (---------------) + I sor-fron 0x002e0f48, // n0x174d c0x0000 (---------------) + I sor-odal 0x002e888c, // n0x174e c0x0000 (---------------) + I sor-varanger 0x002ec987, // n0x174f c0x0000 (---------------) + I sorfold 0x00315608, // n0x1750 c0x0000 (---------------) + I sorreisa 0x0031a288, // n0x1751 c0x0000 (---------------) + I sortland 0x0031ee45, // n0x1752 c0x0000 (---------------) + I sorum 0x002ac70a, // n0x1753 c0x0000 (---------------) + I spjelkavik 0x00349a49, // n0x1754 c0x0000 (---------------) + I spydeberg 0x40a023c2, // n0x1755 c0x0102 (n0x1879-n0x187a) + I st 0x00309986, // n0x1756 c0x0000 (---------------) + I stange 0x0029ca04, // n0x1757 c0x0000 (---------------) + I stat 0x0029e909, // n0x1758 c0x0000 (---------------) + I stathelle 0x002c92c9, // n0x1759 c0x0000 (---------------) + I stavanger 0x002d97c7, // n0x175a c0x0000 (---------------) + I stavern 0x0025c087, // n0x175b c0x0000 (---------------) + I steigen 0x003374c9, // n0x175c c0x0000 (---------------) + I steinkjer 0x00202b88, // n0x175d c0x0000 (---------------) + I stjordal 0x00202b8f, // n0x175e c0x0000 (---------------) + I stjordalshalsen 0x00228bc6, // n0x175f c0x0000 (---------------) + I stokke 0x0023f24b, // n0x1760 c0x0000 (---------------) + I stor-elvdal 0x002cf305, // n0x1761 c0x0000 (---------------) + I stord 0x002cf307, // n0x1762 c0x0000 (---------------) + I stordal 0x002cf749, // n0x1763 c0x0000 (---------------) + I storfjord 0x0023dac6, // n0x1764 c0x0000 (---------------) + I strand 0x0023dac7, // n0x1765 c0x0000 (---------------) + I stranda 0x0037fd45, // n0x1766 c0x0000 (---------------) + I stryn 0x00224fc4, // n0x1767 c0x0000 (---------------) + I sula 0x00226b46, // n0x1768 c0x0000 (---------------) + I suldal 0x00218c84, // n0x1769 c0x0000 (---------------) + I sund 0x002a9c87, // n0x176a c0x0000 (---------------) + I sunndal 0x002d1a88, // n0x176b c0x0000 (---------------) + I surnadal 0x40ed36c8, // n0x176c c0x0103 (n0x187a-n0x187b) + I svalbard 0x002d4485, // n0x176d c0x0000 (---------------) + I sveio 0x002d45c7, // n0x176e c0x0000 (---------------) + I svelvik 0x00354549, // n0x176f c0x0000 (---------------) + I sykkylven 0x00204e04, // n0x1770 c0x0000 (---------------) + I tana 0x00204e08, // n0x1771 c0x0000 (---------------) + I tananger 0x4122ba88, // n0x1772 c0x0104 (n0x187b-n0x187d) o I telemark 0x0036ef44, // n0x1773 c0x0000 (---------------) + I time 0x00225c08, // n0x1774 c0x0000 (---------------) + I tingvoll 0x0030cf04, // n0x1775 c0x0000 (---------------) + I tinn 0x0021fb09, // n0x1776 c0x0000 (---------------) + I tjeldsund 0x00259c45, // n0x1777 c0x0000 (---------------) + I tjome 0x41608902, // n0x1778 c0x0105 (n0x187d-n0x187e) + I tm 0x00228c05, // n0x1779 c0x0000 (---------------) + I tokke 0x00215ac5, // n0x177a c0x0000 (---------------) + I tolga 0x00204608, // n0x177b c0x0000 (---------------) + I tonsberg 0x00226fc7, // n0x177c c0x0000 (---------------) + I torsken 0x41a02402, // n0x177d c0x0106 (n0x187e-n0x187f) + I tr 0x0025ab85, // n0x177e c0x0000 (---------------) + I trana 0x00263106, // n0x177f c0x0000 (---------------) + I tranby 0x00278cc6, // n0x1780 c0x0000 (---------------) + I tranoy 0x002dfe08, // n0x1781 c0x0000 (---------------) + I troandin 0x002e4348, // n0x1782 c0x0000 (---------------) + I trogstad 0x00302a46, // n0x1783 c0x0000 (---------------) + I tromsa 0x0030ac06, // n0x1784 c0x0000 (---------------) + I tromso 0x00214709, // n0x1785 c0x0000 (---------------) + I trondheim 0x0036b846, // n0x1786 c0x0000 (---------------) + I trysil 0x00394d4b, // n0x1787 c0x0000 (---------------) + I tvedestrand 0x00222c85, // n0x1788 c0x0000 (---------------) + I tydal 0x0020fac6, // n0x1789 c0x0000 (---------------) + I tynset 0x00224108, // n0x178a c0x0000 (---------------) + I tysfjord 0x00234886, // n0x178b c0x0000 (---------------) + I tysnes 0x002f8986, // n0x178c c0x0000 (---------------) + I tysvar 0x00210dca, // n0x178d c0x0000 (---------------) + I ullensaker 0x002bab8a, // n0x178e c0x0000 (---------------) + I ullensvang 0x0025bd05, // n0x178f c0x0000 (---------------) + I ulvik 0x00215307, // n0x1790 c0x0000 (---------------) + I unjarga 0x002d0d06, // n0x1791 c0x0000 (---------------) + I utsira 0x41e013c2, // n0x1792 c0x0107 (n0x187f-n0x1880) + I va 0x002f2e87, // n0x1793 c0x0000 (---------------) + I vaapste 0x00262a85, // n0x1794 c0x0000 (---------------) + I vadso 0x00343f44, // n0x1795 c0x0000 (---------------) + I vaga 0x00343f45, // n0x1796 c0x0000 (---------------) + I vagan 0x00300c06, // n0x1797 c0x0000 (---------------) + I vagsoy 0x0033f147, // n0x1798 c0x0000 (---------------) + I vaksdal 0x00213d85, // n0x1799 c0x0000 (---------------) + I valle 0x002bad04, // n0x179a c0x0000 (---------------) + I vang 0x0025c3c8, // n0x179b c0x0000 (---------------) + I vanylven 0x002f8a45, // n0x179c c0x0000 (---------------) + I vardo 0x00280307, // n0x179d c0x0000 (---------------) + I varggat 0x002cf005, // n0x179e c0x0000 (---------------) + I varoy 0x00310385, // n0x179f c0x0000 (---------------) + I vefsn 0x00212004, // n0x17a0 c0x0000 (---------------) + I vega 0x00299e89, // n0x17a1 c0x0000 (---------------) + I vegarshei 0x00212448, // n0x17a2 c0x0000 (---------------) + I vennesla 0x00212286, // n0x17a3 c0x0000 (---------------) + I verdal 0x00386a06, // n0x17a4 c0x0000 (---------------) + I verran 0x002b9c46, // n0x17a5 c0x0000 (---------------) + I vestby 0x422d9c88, // n0x17a6 c0x0108 (n0x1880-n0x1881) o I vestfold 0x002d9e87, // n0x17a7 c0x0000 (---------------) + I vestnes 0x002da30d, // n0x17a8 c0x0000 (---------------) + I vestre-slidre 0x002da90c, // n0x17a9 c0x0000 (---------------) + I vestre-toten 0x002daf09, // n0x17aa c0x0000 (---------------) + I vestvagoy 0x002db149, // n0x17ab c0x0000 (---------------) + I vevelstad 0x4273b4c2, // n0x17ac c0x0109 (n0x1881-n0x1882) + I vf 0x0038c903, // n0x17ad c0x0000 (---------------) + I vgs 0x00244c83, // n0x17ae c0x0000 (---------------) + I vik 0x00364745, // n0x17af c0x0000 (---------------) + I vikna 0x0037620a, // n0x17b0 c0x0000 (---------------) + I vindafjord 0x00302906, // n0x17b1 c0x0000 (---------------) + I voagat 0x002df605, // n0x17b2 c0x0000 (---------------) + I volda 0x002e21c4, // n0x17b3 c0x0000 (---------------) + I voss 0x002e21cb, // n0x17b4 c0x0000 (---------------) + I vossevangen 0x002f6e0c, // n0x17b5 c0x0000 (---------------) + I xn--andy-ira 0x002f764c, // n0x17b6 c0x0000 (---------------) + I xn--asky-ira 0x002f7955, // n0x17b7 c0x0000 (---------------) + I xn--aurskog-hland-jnb 0x002f984d, // n0x17b8 c0x0000 (---------------) + I xn--avery-yua 0x002fbb0f, // n0x17b9 c0x0000 (---------------) + I xn--bdddj-mrabd 0x002fbed2, // n0x17ba c0x0000 (---------------) + I xn--bearalvhki-y4a 0x002fc34f, // n0x17bb c0x0000 (---------------) + I xn--berlevg-jxa 0x002fc712, // n0x17bc c0x0000 (---------------) + I xn--bhcavuotna-s4a 0x002fcb93, // n0x17bd c0x0000 (---------------) + I xn--bhccavuotna-k7a 0x002fd04d, // n0x17be c0x0000 (---------------) + I xn--bidr-5nac 0x002fd60d, // n0x17bf c0x0000 (---------------) + I xn--bievt-0qa 0x002fd94e, // n0x17c0 c0x0000 (---------------) + I xn--bjarky-fya 0x002fde0e, // n0x17c1 c0x0000 (---------------) + I xn--bjddar-pta 0x002fec8c, // n0x17c2 c0x0000 (---------------) + I xn--blt-elab 0x002ff00c, // n0x17c3 c0x0000 (---------------) + I xn--bmlo-gra 0x002ff44b, // n0x17c4 c0x0000 (---------------) + I xn--bod-2na 0x002ff7ce, // n0x17c5 c0x0000 (---------------) + I xn--brnny-wuac 0x00301b92, // n0x17c6 c0x0000 (---------------) + I xn--brnnysund-m8ac 0x003026cc, // n0x17c7 c0x0000 (---------------) + I xn--brum-voa 0x00302e90, // n0x17c8 c0x0000 (---------------) + I xn--btsfjord-9za 0x003138d2, // n0x17c9 c0x0000 (---------------) + I xn--davvenjrga-y4a 0x0031458c, // n0x17ca c0x0000 (---------------) + I xn--dnna-gra 0x00314a4d, // n0x17cb c0x0000 (---------------) + I xn--drbak-wua 0x00314d8c, // n0x17cc c0x0000 (---------------) + I xn--dyry-ira 0x00317b91, // n0x17cd c0x0000 (---------------) + I xn--eveni-0qa01ga 0x00319c0d, // n0x17ce c0x0000 (---------------) + I xn--finny-yua 0x0031f74d, // n0x17cf c0x0000 (---------------) + I xn--fjord-lra 0x0031fd4a, // n0x17d0 c0x0000 (---------------) + I xn--fl-zia 0x0031ffcc, // n0x17d1 c0x0000 (---------------) + I xn--flor-jra 0x003208cc, // n0x17d2 c0x0000 (---------------) + I xn--frde-gra 0x0032110c, // n0x17d3 c0x0000 (---------------) + I xn--frna-woa 0x00321b0c, // n0x17d4 c0x0000 (---------------) + I xn--frya-hra 0x00324f13, // n0x17d5 c0x0000 (---------------) + I xn--ggaviika-8ya47h 0x00326650, // n0x17d6 c0x0000 (---------------) + I xn--gildeskl-g0a 0x00326a50, // n0x17d7 c0x0000 (---------------) + I xn--givuotna-8ya 0x0032714d, // n0x17d8 c0x0000 (---------------) + I xn--gjvik-wua 0x0032748c, // n0x17d9 c0x0000 (---------------) + I xn--gls-elac 0x00328189, // n0x17da c0x0000 (---------------) + I xn--h-2fa 0x0032900d, // n0x17db c0x0000 (---------------) + I xn--hbmer-xqa 0x00329353, // n0x17dc c0x0000 (---------------) + I xn--hcesuolo-7ya35b 0x0032c151, // n0x17dd c0x0000 (---------------) + I xn--hgebostad-g3a 0x0032c593, // n0x17de c0x0000 (---------------) + I xn--hmmrfeasta-s4ac 0x0032e38f, // n0x17df c0x0000 (---------------) + I xn--hnefoss-q1a 0x0032e74c, // n0x17e0 c0x0000 (---------------) + I xn--hobl-ira 0x0032ea4f, // n0x17e1 c0x0000 (---------------) + I xn--holtlen-hxa 0x0032ee0d, // n0x17e2 c0x0000 (---------------) + I xn--hpmir-xqa 0x0032f40f, // n0x17e3 c0x0000 (---------------) + I xn--hyanger-q1a 0x0032f7d0, // n0x17e4 c0x0000 (---------------) + I xn--hylandet-54a 0x0033024e, // n0x17e5 c0x0000 (---------------) + I xn--indery-fya 0x00332a0e, // n0x17e6 c0x0000 (---------------) + I xn--jlster-bya 0x00333150, // n0x17e7 c0x0000 (---------------) + I xn--jrpeland-54a 0x00333e8d, // n0x17e8 c0x0000 (---------------) + I xn--karmy-yua 0x0033480e, // n0x17e9 c0x0000 (---------------) + I xn--kfjord-iua 0x00334b8c, // n0x17ea c0x0000 (---------------) + I xn--klbu-woa 0x00336b53, // n0x17eb c0x0000 (---------------) + I xn--koluokta-7ya57h 0x0033934e, // n0x17ec c0x0000 (---------------) + I xn--krager-gya 0x00339b10, // n0x17ed c0x0000 (---------------) + I xn--kranghke-b0a 0x00339f11, // n0x17ee c0x0000 (---------------) + I xn--krdsherad-m8a 0x0033a34f, // n0x17ef c0x0000 (---------------) + I xn--krehamn-dxa 0x0033a713, // n0x17f0 c0x0000 (---------------) + I xn--krjohka-hwab49j 0x0033b04d, // n0x17f1 c0x0000 (---------------) + I xn--ksnes-uua 0x0033b38f, // n0x17f2 c0x0000 (---------------) + I xn--kvfjord-nxa 0x0033b74e, // n0x17f3 c0x0000 (---------------) + I xn--kvitsy-fya 0x0033d050, // n0x17f4 c0x0000 (---------------) + I xn--kvnangen-k0a 0x0033d449, // n0x17f5 c0x0000 (---------------) + I xn--l-1fa 0x0033e4d0, // n0x17f6 c0x0000 (---------------) + I xn--laheadju-7ya 0x0033f30f, // n0x17f7 c0x0000 (---------------) + I xn--langevg-jxa 0x0033f98f, // n0x17f8 c0x0000 (---------------) + I xn--ldingen-q1a 0x0033fd52, // n0x17f9 c0x0000 (---------------) + I xn--leagaviika-52b 0x00344a4e, // n0x17fa c0x0000 (---------------) + I xn--lesund-hua 0x0034534d, // n0x17fb c0x0000 (---------------) + I xn--lgrd-poac 0x00345bcd, // n0x17fc c0x0000 (---------------) + I xn--lhppi-xqa 0x00345f0d, // n0x17fd c0x0000 (---------------) + I xn--linds-pra 0x00347a8d, // n0x17fe c0x0000 (---------------) + I xn--loabt-0qa 0x00347dcd, // n0x17ff c0x0000 (---------------) + I xn--lrdal-sra 0x00348110, // n0x1800 c0x0000 (---------------) + I xn--lrenskog-54a 0x0034850b, // n0x1801 c0x0000 (---------------) + I xn--lt-liac 0x00348a8c, // n0x1802 c0x0000 (---------------) + I xn--lten-gra 0x00348e0c, // n0x1803 c0x0000 (---------------) + I xn--lury-ira 0x0034910c, // n0x1804 c0x0000 (---------------) + I xn--mely-ira 0x0034940e, // n0x1805 c0x0000 (---------------) + I xn--merker-kua 0x00356890, // n0x1806 c0x0000 (---------------) + I xn--mjndalen-64a 0x003581d2, // n0x1807 c0x0000 (---------------) + I xn--mlatvuopmi-s4a 0x0035864b, // n0x1808 c0x0000 (---------------) + I xn--mli-tla 0x00358a8e, // n0x1809 c0x0000 (---------------) + I xn--mlselv-iua 0x00358e0e, // n0x180a c0x0000 (---------------) + I xn--moreke-jua 0x0035960e, // n0x180b c0x0000 (---------------) + I xn--mosjen-eya 0x0035a4cb, // n0x180c c0x0000 (---------------) + I xn--mot-tla 0x42b5a856, // n0x180d c0x010a (n0x1882-n0x1884) o I xn--mre-og-romsdal-qqb 0x0035b4cd, // n0x180e c0x0000 (---------------) + I xn--msy-ula0h 0x0035b954, // n0x180f c0x0000 (---------------) + I xn--mtta-vrjjat-k7af 0x0035c38d, // n0x1810 c0x0000 (---------------) + I xn--muost-0qa 0x0035d715, // n0x1811 c0x0000 (---------------) + I xn--nmesjevuemie-tcba 0x0036060d, // n0x1812 c0x0000 (---------------) + I xn--nry-yla5g 0x00360f8f, // n0x1813 c0x0000 (---------------) + I xn--nttery-byae 0x00361bcf, // n0x1814 c0x0000 (---------------) + I xn--nvuotna-hwa 0x003652cf, // n0x1815 c0x0000 (---------------) + I xn--oppegrd-ixa 0x0036568e, // n0x1816 c0x0000 (---------------) + I xn--ostery-fya 0x00365d4d, // n0x1817 c0x0000 (---------------) + I xn--osyro-wua 0x00368211, // n0x1818 c0x0000 (---------------) + I xn--porsgu-sta26f 0x0036f34c, // n0x1819 c0x0000 (---------------) + I xn--rady-ira 0x0036f64c, // n0x181a c0x0000 (---------------) + I xn--rdal-poa 0x0036f94b, // n0x181b c0x0000 (---------------) + I xn--rde-ula 0x0036fc0c, // n0x181c c0x0000 (---------------) + I xn--rdy-0nab 0x0036ffcf, // n0x181d c0x0000 (---------------) + I xn--rennesy-v1a 0x00370392, // n0x181e c0x0000 (---------------) + I xn--rhkkervju-01af 0x00371acd, // n0x181f c0x0000 (---------------) + I xn--rholt-mra 0x00372d0c, // n0x1820 c0x0000 (---------------) + I xn--risa-5na 0x0037318c, // n0x1821 c0x0000 (---------------) + I xn--risr-ira 0x0037348d, // n0x1822 c0x0000 (---------------) + I xn--rland-uua 0x003737cf, // n0x1823 c0x0000 (---------------) + I xn--rlingen-mxa 0x00373b8e, // n0x1824 c0x0000 (---------------) + I xn--rmskog-bya 0x00375ecc, // n0x1825 c0x0000 (---------------) + I xn--rros-gra 0x0037648d, // n0x1826 c0x0000 (---------------) + I xn--rskog-uua 0x003767cb, // n0x1827 c0x0000 (---------------) + I xn--rst-0na 0x00376fcc, // n0x1828 c0x0000 (---------------) + I xn--rsta-fra 0x0037754d, // n0x1829 c0x0000 (---------------) + I xn--ryken-vua 0x0037788e, // n0x182a c0x0000 (---------------) + I xn--ryrvik-bya 0x00377d09, // n0x182b c0x0000 (---------------) + I xn--s-1fa 0x00378b53, // n0x182c c0x0000 (---------------) + I xn--sandnessjen-ogb 0x0037940d, // n0x182d c0x0000 (---------------) + I xn--sandy-yua 0x0037974d, // n0x182e c0x0000 (---------------) + I xn--seral-lra 0x00379d4c, // n0x182f c0x0000 (---------------) + I xn--sgne-gra 0x0037a1ce, // n0x1830 c0x0000 (---------------) + I xn--skierv-uta 0x0037b34f, // n0x1831 c0x0000 (---------------) + I xn--skjervy-v1a 0x0037b70c, // n0x1832 c0x0000 (---------------) + I xn--skjk-soa 0x0037ba0d, // n0x1833 c0x0000 (---------------) + I xn--sknit-yqa 0x0037bd4f, // n0x1834 c0x0000 (---------------) + I xn--sknland-fxa 0x0037c10c, // n0x1835 c0x0000 (---------------) + I xn--slat-5na 0x0037c74c, // n0x1836 c0x0000 (---------------) + I xn--slt-elab 0x0037cb0c, // n0x1837 c0x0000 (---------------) + I xn--smla-hra 0x0037ce0c, // n0x1838 c0x0000 (---------------) + I xn--smna-gra 0x0037d4cd, // n0x1839 c0x0000 (---------------) + I xn--snase-nra 0x0037d812, // n0x183a c0x0000 (---------------) + I xn--sndre-land-0cb 0x0037de8c, // n0x183b c0x0000 (---------------) + I xn--snes-poa 0x0037e18c, // n0x183c c0x0000 (---------------) + I xn--snsa-roa 0x0037e491, // n0x183d c0x0000 (---------------) + I xn--sr-aurdal-l8a 0x0037e8cf, // n0x183e c0x0000 (---------------) + I xn--sr-fron-q1a 0x0037ec8f, // n0x183f c0x0000 (---------------) + I xn--sr-odal-q1a 0x0037f053, // n0x1840 c0x0000 (---------------) + I xn--sr-varanger-ggb 0x003801ce, // n0x1841 c0x0000 (---------------) + I xn--srfold-bya 0x0038074f, // n0x1842 c0x0000 (---------------) + I xn--srreisa-q1a 0x00380b0c, // n0x1843 c0x0000 (---------------) + I xn--srum-gra 0x42f80e4e, // n0x1844 c0x010b (n0x1884-n0x1885) o I xn--stfold-9xa 0x003811cf, // n0x1845 c0x0000 (---------------) + I xn--stjrdal-s1a 0x00381596, // n0x1846 c0x0000 (---------------) + I xn--stjrdalshalsen-sqb 0x00382652, // n0x1847 c0x0000 (---------------) + I xn--stre-toten-zcb 0x0038448c, // n0x1848 c0x0000 (---------------) + I xn--tjme-hra 0x003850cf, // n0x1849 c0x0000 (---------------) + I xn--tnsberg-q1a 0x0038574d, // n0x184a c0x0000 (---------------) + I xn--trany-yua 0x00385a8f, // n0x184b c0x0000 (---------------) + I xn--trgstad-r1a 0x00385e4c, // n0x184c c0x0000 (---------------) + I xn--trna-woa 0x0038614d, // n0x184d c0x0000 (---------------) + I xn--troms-zua 0x0038648d, // n0x184e c0x0000 (---------------) + I xn--tysvr-vra 0x003876ce, // n0x184f c0x0000 (---------------) + I xn--unjrga-rta 0x0038850c, // n0x1850 c0x0000 (---------------) + I xn--vads-jra 0x0038880c, // n0x1851 c0x0000 (---------------) + I xn--vard-jra 0x00388b10, // n0x1852 c0x0000 (---------------) + I xn--vegrshei-c0a 0x0038b251, // n0x1853 c0x0000 (---------------) + I xn--vestvgy-ixa6o 0x0038b68b, // n0x1854 c0x0000 (---------------) + I xn--vg-yiab 0x0038c50c, // n0x1855 c0x0000 (---------------) + I xn--vgan-qoa 0x0038c80e, // n0x1856 c0x0000 (---------------) + I xn--vgsy-qoa0j 0x0038e511, // n0x1857 c0x0000 (---------------) + I xn--vre-eiker-k8a 0x0038e94e, // n0x1858 c0x0000 (---------------) + I xn--vrggt-xqad 0x0038eccd, // n0x1859 c0x0000 (---------------) + I xn--vry-yla5g 0x00392fcb, // n0x185a c0x0000 (---------------) + I xn--yer-zna 0x00393c0f, // n0x185b c0x0000 (---------------) + I xn--ygarden-p1a 0x00394594, // n0x185c c0x0000 (---------------) + I xn--ystre-slidre-ujb 0x0026cd02, // n0x185d c0x0000 (---------------) + I gs 0x0026cd02, // n0x185e c0x0000 (---------------) + I gs 0x00201083, // n0x185f c0x0000 (---------------) + I nes 0x0026cd02, // n0x1860 c0x0000 (---------------) + I gs 0x00201083, // n0x1861 c0x0000 (---------------) + I nes 0x0026cd02, // n0x1862 c0x0000 (---------------) + I gs 0x00202382, // n0x1863 c0x0000 (---------------) + I os 0x00351305, // n0x1864 c0x0000 (---------------) + I valer 0x0038e20c, // n0x1865 c0x0000 (---------------) + I xn--vler-qoa 0x0026cd02, // n0x1866 c0x0000 (---------------) + I gs 0x0026cd02, // n0x1867 c0x0000 (---------------) + I gs 0x00202382, // n0x1868 c0x0000 (---------------) + I os 0x0026cd02, // n0x1869 c0x0000 (---------------) + I gs 0x00280105, // n0x186a c0x0000 (---------------) + I heroy 0x0029dd05, // n0x186b c0x0000 (---------------) + I sande 0x0026cd02, // n0x186c c0x0000 (---------------) + I gs 0x0026cd02, // n0x186d c0x0000 (---------------) + I gs 0x0020a702, // n0x186e c0x0000 (---------------) + I bo 0x00280105, // n0x186f c0x0000 (---------------) + I heroy 0x002fa209, // n0x1870 c0x0000 (---------------) + I xn--b-5ga 0x0032be4c, // n0x1871 c0x0000 (---------------) + I xn--hery-ira 0x0026cd02, // n0x1872 c0x0000 (---------------) + I gs 0x0026cd02, // n0x1873 c0x0000 (---------------) + I gs 0x0026cd02, // n0x1874 c0x0000 (---------------) + I gs 0x0026cd02, // n0x1875 c0x0000 (---------------) + I gs 0x00351305, // n0x1876 c0x0000 (---------------) + I valer 0x0026cd02, // n0x1877 c0x0000 (---------------) + I gs 0x0026cd02, // n0x1878 c0x0000 (---------------) + I gs 0x0026cd02, // n0x1879 c0x0000 (---------------) + I gs 0x0026cd02, // n0x187a c0x0000 (---------------) + I gs 0x0020a702, // n0x187b c0x0000 (---------------) + I bo 0x002fa209, // n0x187c c0x0000 (---------------) + I xn--b-5ga 0x0026cd02, // n0x187d c0x0000 (---------------) + I gs 0x0026cd02, // n0x187e c0x0000 (---------------) + I gs 0x0026cd02, // n0x187f c0x0000 (---------------) + I gs 0x0029dd05, // n0x1880 c0x0000 (---------------) + I sande 0x0026cd02, // n0x1881 c0x0000 (---------------) + I gs 0x0029dd05, // n0x1882 c0x0000 (---------------) + I sande 0x0032be4c, // n0x1883 c0x0000 (---------------) + I xn--hery-ira 0x0038e20c, // n0x1884 c0x0000 (---------------) + I xn--vler-qoa 0x00310603, // n0x1885 c0x0000 (---------------) + I biz 0x00222ac3, // n0x1886 c0x0000 (---------------) + I com 0x002d75c3, // n0x1887 c0x0000 (---------------) + I edu 0x0021e283, // n0x1888 c0x0000 (---------------) + I gov 0x00200304, // n0x1889 c0x0000 (---------------) + I info 0x002170c3, // n0x188a c0x0000 (---------------) + I net 0x0021dcc3, // n0x188b c0x0000 (---------------) + I org 0x00166bc8, // n0x188c c0x0000 (---------------) + merseine 0x0007c1c4, // n0x188d c0x0000 (---------------) + mine 0x000cb2c8, // n0x188e c0x0000 (---------------) + shacknet 0x00201e82, // n0x188f c0x0000 (---------------) + I ac 0x43e00742, // n0x1890 c0x010f (n0x189f-n0x18a0) + I co 0x002319c3, // n0x1891 c0x0000 (---------------) + I cri 0x00252f84, // n0x1892 c0x0000 (---------------) + I geek 0x002012c3, // n0x1893 c0x0000 (---------------) + I gen 0x0021e284, // n0x1894 c0x0000 (---------------) + I govt 0x00205e06, // n0x1895 c0x0000 (---------------) + I health 0x002d2e03, // n0x1896 c0x0000 (---------------) + I iwi 0x002d2dc4, // n0x1897 c0x0000 (---------------) + I kiwi 0x002701c5, // n0x1898 c0x0000 (---------------) + I maori 0x0023fa03, // n0x1899 c0x0000 (---------------) + I mil 0x002170c3, // n0x189a c0x0000 (---------------) + I net 0x0021dcc3, // n0x189b c0x0000 (---------------) + I org 0x002647ca, // n0x189c c0x0000 (---------------) + I parliament 0x00235406, // n0x189d c0x0000 (---------------) + I school 0x0035918c, // n0x189e c0x0000 (---------------) + I xn--mori-qsa 0x000e4188, // n0x189f c0x0000 (---------------) + blogspot 0x00200742, // n0x18a0 c0x0000 (---------------) + I co 0x00222ac3, // n0x18a1 c0x0000 (---------------) + I com 0x002d75c3, // n0x18a2 c0x0000 (---------------) + I edu 0x0021e283, // n0x18a3 c0x0000 (---------------) + I gov 0x0020b403, // n0x18a4 c0x0000 (---------------) + I med 0x002bd646, // n0x18a5 c0x0000 (---------------) + I museum 0x002170c3, // n0x18a6 c0x0000 (---------------) + I net 0x0021dcc3, // n0x18a7 c0x0000 (---------------) + I org 0x00218243, // n0x18a8 c0x0000 (---------------) + I pro 0x00004342, // n0x18a9 c0x0000 (---------------) + ae 0x000d0087, // n0x18aa c0x0000 (---------------) + blogdns 0x001619c8, // n0x18ab c0x0000 (---------------) + blogsite 0x00076592, // n0x18ac c0x0000 (---------------) + boldlygoingnowhere 0x44a2a085, // n0x18ad c0x0112 (n0x18e3-n0x18e5) o I cdn77 0x44f0720c, // n0x18ae c0x0113 (n0x18e5-n0x18e6) o I cdn77-secure 0x00146fc8, // n0x18af c0x0000 (---------------) + dnsalias 0x0006a247, // n0x18b0 c0x0000 (---------------) + dnsdojo 0x00010a4b, // n0x18b1 c0x0000 (---------------) + doesntexist 0x0015fdc9, // n0x18b2 c0x0000 (---------------) + dontexist 0x00146ec7, // n0x18b3 c0x0000 (---------------) + doomdns 0x0006a147, // n0x18b4 c0x0000 (---------------) + duckdns 0x00194fc6, // n0x18b5 c0x0000 (---------------) + dvrdns 0x000007c8, // n0x18b6 c0x0000 (---------------) + dynalias 0x45409ac6, // n0x18b7 c0x0115 (n0x18e7-n0x18e9) + dyndns 0x0009428d, // n0x18b8 c0x0000 (---------------) + endofinternet 0x000f3e50, // n0x18b9 c0x0000 (---------------) + endoftheinternet 0x4581d5c2, // n0x18ba c0x0116 (n0x18e9-n0x1920) + eu 0x00057807, // n0x18bb c0x0000 (---------------) + from-me 0x00083589, // n0x18bc c0x0000 (---------------) + game-host 0x00043a86, // n0x18bd c0x0000 (---------------) + gotdns 0x0002ea02, // n0x18be c0x0000 (---------------) + hk 0x0013eeca, // n0x18bf c0x0000 (---------------) + hobby-site 0x0000b387, // n0x18c0 c0x0000 (---------------) + homedns 0x00085007, // n0x18c1 c0x0000 (---------------) + homeftp 0x00090ec9, // n0x18c2 c0x0000 (---------------) + homelinux 0x00091b88, // n0x18c3 c0x0000 (---------------) + homeunix 0x000c528e, // n0x18c4 c0x0000 (---------------) + is-a-bruinsfan 0x00008d8e, // n0x18c5 c0x0000 (---------------) + is-a-candidate 0x0000eecf, // n0x18c6 c0x0000 (---------------) + is-a-celticsfan 0x00166909, // n0x18c7 c0x0000 (---------------) + is-a-chef 0x00052e49, // n0x18c8 c0x0000 (---------------) + is-a-geek 0x0006b8cb, // n0x18c9 c0x0000 (---------------) + is-a-knight 0x001259cf, // n0x18ca c0x0000 (---------------) + is-a-linux-user 0x0008480c, // n0x18cb c0x0000 (---------------) + is-a-patsfan 0x000d23cb, // n0x18cc c0x0000 (---------------) + is-a-soxfan 0x00103ac8, // n0x18cd c0x0000 (---------------) + is-found 0x000d6887, // n0x18ce c0x0000 (---------------) + is-lost 0x000e2908, // n0x18cf c0x0000 (---------------) + is-saved 0x0012148b, // n0x18d0 c0x0000 (---------------) + is-very-bad 0x00127b0c, // n0x18d1 c0x0000 (---------------) + is-very-evil 0x00130a4c, // n0x18d2 c0x0000 (---------------) + is-very-good 0x0013904c, // n0x18d3 c0x0000 (---------------) + is-very-nice 0x0013bb8d, // n0x18d4 c0x0000 (---------------) + is-very-sweet 0x00191648, // n0x18d5 c0x0000 (---------------) + isa-geek 0x00183609, // n0x18d6 c0x0000 (---------------) + kicks-ass 0x0016a6cb, // n0x18d7 c0x0000 (---------------) + misconfused 0x000c7e07, // n0x18d8 c0x0000 (---------------) + podzone 0x0016184a, // n0x18d9 c0x0000 (---------------) + readmyblog 0x00130f46, // n0x18da c0x0000 (---------------) + selfip 0x00084dcd, // n0x18db c0x0000 (---------------) + sellsyourhome 0x00079088, // n0x18dc c0x0000 (---------------) + servebbs 0x00161348, // n0x18dd c0x0000 (---------------) + serveftp 0x00011f49, // n0x18de c0x0000 (---------------) + servegame 0x000d044c, // n0x18df c0x0000 (---------------) + stuff-4-sale 0x00009f42, // n0x18e0 c0x0000 (---------------) + us 0x00110e86, // n0x18e1 c0x0000 (---------------) + webhop 0x000043c2, // n0x18e2 c0x0000 (---------------) + za 0x00000741, // n0x18e3 c0x0000 (---------------) + c 0x000060c3, // n0x18e4 c0x0000 (---------------) + rsc 0x45374606, // n0x18e5 c0x0114 (n0x18e6-n0x18e7) o I origin 0x0002a203, // n0x18e6 c0x0000 (---------------) + ssl 0x00002342, // n0x18e7 c0x0000 (---------------) + go 0x0000b384, // n0x18e8 c0x0000 (---------------) + home 0x00000882, // n0x18e9 c0x0000 (---------------) + al 0x000729c4, // n0x18ea c0x0000 (---------------) + asso 0x00001642, // n0x18eb c0x0000 (---------------) + at 0x00005ac2, // n0x18ec c0x0000 (---------------) + au 0x00004702, // n0x18ed c0x0000 (---------------) + be 0x00155e02, // n0x18ee c0x0000 (---------------) + bg 0x000055c2, // n0x18ef c0x0000 (---------------) + ca 0x0002a082, // n0x18f0 c0x0000 (---------------) + cd 0x00004a02, // n0x18f1 c0x0000 (---------------) + ch 0x000211c2, // n0x18f2 c0x0000 (---------------) + cn 0x00029e42, // n0x18f3 c0x0000 (---------------) + cy 0x00014442, // n0x18f4 c0x0000 (---------------) + cz 0x000006c2, // n0x18f5 c0x0000 (---------------) + de 0x00071742, // n0x18f6 c0x0000 (---------------) + dk 0x000d75c3, // n0x18f7 c0x0000 (---------------) + edu 0x00006042, // n0x18f8 c0x0000 (---------------) + ee 0x000010c2, // n0x18f9 c0x0000 (---------------) + es 0x000099c2, // n0x18fa c0x0000 (---------------) + fi 0x00000d42, // n0x18fb c0x0000 (---------------) + fr 0x0000dc82, // n0x18fc c0x0000 (---------------) + gr 0x00025842, // n0x18fd c0x0000 (---------------) + hr 0x00017d42, // n0x18fe c0x0000 (---------------) + hu 0x00000e82, // n0x18ff c0x0000 (---------------) + ie 0x000036c2, // n0x1900 c0x0000 (---------------) + il 0x00000242, // n0x1901 c0x0000 (---------------) + in 0x00038c03, // n0x1902 c0x0000 (---------------) + int 0x00002b42, // n0x1903 c0x0000 (---------------) + is 0x00006e82, // n0x1904 c0x0000 (---------------) + it 0x000990c2, // n0x1905 c0x0000 (---------------) + jp 0x000034c2, // n0x1906 c0x0000 (---------------) + kr 0x00005ec2, // n0x1907 c0x0000 (---------------) + lt 0x000071c2, // n0x1908 c0x0000 (---------------) + lu 0x00027f02, // n0x1909 c0x0000 (---------------) + lv 0x0003a6c2, // n0x190a c0x0000 (---------------) + mc 0x00008942, // n0x190b c0x0000 (---------------) + me 0x00156d82, // n0x190c c0x0000 (---------------) + mk 0x00059642, // n0x190d c0x0000 (---------------) + mt 0x00020282, // n0x190e c0x0000 (---------------) + my 0x000170c3, // n0x190f c0x0000 (---------------) + net 0x00001282, // n0x1910 c0x0000 (---------------) + ng 0x00036482, // n0x1911 c0x0000 (---------------) + nl 0x00000c02, // n0x1912 c0x0000 (---------------) + no 0x000078c2, // n0x1913 c0x0000 (---------------) + nz 0x0005b445, // n0x1914 c0x0000 (---------------) + paris 0x00001e02, // n0x1915 c0x0000 (---------------) + pl 0x00095982, // n0x1916 c0x0000 (---------------) + pt 0x00123e03, // n0x1917 c0x0000 (---------------) + q-a 0x00000d82, // n0x1918 c0x0000 (---------------) + ro 0x000044c2, // n0x1919 c0x0000 (---------------) + ru 0x00002e82, // n0x191a c0x0000 (---------------) + se 0x00009182, // n0x191b c0x0000 (---------------) + si 0x00007b42, // n0x191c c0x0000 (---------------) + sk 0x00002402, // n0x191d c0x0000 (---------------) + tr 0x0000cf02, // n0x191e c0x0000 (---------------) + uk 0x00009f42, // n0x191f c0x0000 (---------------) + us 0x0020c283, // n0x1920 c0x0000 (---------------) + I abo 0x00201e82, // n0x1921 c0x0000 (---------------) + I ac 0x00222ac3, // n0x1922 c0x0000 (---------------) + I com 0x002d75c3, // n0x1923 c0x0000 (---------------) + I edu 0x0034eb03, // n0x1924 c0x0000 (---------------) + I gob 0x0020dc03, // n0x1925 c0x0000 (---------------) + I ing 0x0020b403, // n0x1926 c0x0000 (---------------) + I med 0x002170c3, // n0x1927 c0x0000 (---------------) + I net 0x00207cc3, // n0x1928 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x1929 c0x0000 (---------------) + I org 0x00280043, // n0x192a c0x0000 (---------------) + I sld 0x000e4188, // n0x192b c0x0000 (---------------) + blogspot 0x00222ac3, // n0x192c c0x0000 (---------------) + I com 0x002d75c3, // n0x192d c0x0000 (---------------) + I edu 0x0034eb03, // n0x192e c0x0000 (---------------) + I gob 0x0023fa03, // n0x192f c0x0000 (---------------) + I mil 0x002170c3, // n0x1930 c0x0000 (---------------) + I net 0x00207cc3, // n0x1931 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x1932 c0x0000 (---------------) + I org 0x00222ac3, // n0x1933 c0x0000 (---------------) + I com 0x002d75c3, // n0x1934 c0x0000 (---------------) + I edu 0x0021dcc3, // n0x1935 c0x0000 (---------------) + I org 0x00222ac3, // n0x1936 c0x0000 (---------------) + I com 0x002d75c3, // n0x1937 c0x0000 (---------------) + I edu 0x0021e283, // n0x1938 c0x0000 (---------------) + I gov 0x00200041, // n0x1939 c0x0000 (---------------) + I i 0x0023fa03, // n0x193a c0x0000 (---------------) + I mil 0x002170c3, // n0x193b c0x0000 (---------------) + I net 0x00202303, // n0x193c c0x0000 (---------------) + I ngo 0x0021dcc3, // n0x193d c0x0000 (---------------) + I org 0x00310603, // n0x193e c0x0000 (---------------) + I biz 0x00222ac3, // n0x193f c0x0000 (---------------) + I com 0x002d75c3, // n0x1940 c0x0000 (---------------) + I edu 0x002a1b43, // n0x1941 c0x0000 (---------------) + I fam 0x0034eb03, // n0x1942 c0x0000 (---------------) + I gob 0x00375943, // n0x1943 c0x0000 (---------------) + I gok 0x0026f583, // n0x1944 c0x0000 (---------------) + I gon 0x0028e783, // n0x1945 c0x0000 (---------------) + I gop 0x00202343, // n0x1946 c0x0000 (---------------) + I gos 0x0021e283, // n0x1947 c0x0000 (---------------) + I gov 0x00200304, // n0x1948 c0x0000 (---------------) + I info 0x002170c3, // n0x1949 c0x0000 (---------------) + I net 0x0021dcc3, // n0x194a c0x0000 (---------------) + I org 0x00219fc3, // n0x194b c0x0000 (---------------) + I web 0x002f8f84, // n0x194c c0x0000 (---------------) + I agro 0x002375c3, // n0x194d c0x0000 (---------------) + I aid 0x00000603, // n0x194e c0x0000 (---------------) + art 0x0026a983, // n0x194f c0x0000 (---------------) + I atm 0x0023e708, // n0x1950 c0x0000 (---------------) + I augustow 0x002eaac4, // n0x1951 c0x0000 (---------------) + I auto 0x0032d4ca, // n0x1952 c0x0000 (---------------) + I babia-gora 0x0034d4c6, // n0x1953 c0x0000 (---------------) + I bedzin 0x0035ad87, // n0x1954 c0x0000 (---------------) + I beskidy 0x0021604a, // n0x1955 c0x0000 (---------------) + I bialowieza 0x00228a89, // n0x1956 c0x0000 (---------------) + I bialystok 0x0037f4c7, // n0x1957 c0x0000 (---------------) + I bielawa 0x00382a8a, // n0x1958 c0x0000 (---------------) + I bieszczady 0x00310603, // n0x1959 c0x0000 (---------------) + I biz 0x0025374b, // n0x195a c0x0000 (---------------) + I boleslawiec 0x00343289, // n0x195b c0x0000 (---------------) + I bydgoszcz 0x002b9d45, // n0x195c c0x0000 (---------------) + I bytom 0x002bb407, // n0x195d c0x0000 (---------------) + I cieszyn 0x00000742, // n0x195e c0x0000 (---------------) + co 0x00222ac3, // n0x195f c0x0000 (---------------) + I com 0x002c8a87, // n0x1960 c0x0000 (---------------) + I czeladz 0x00214445, // n0x1961 c0x0000 (---------------) + I czest 0x002aae49, // n0x1962 c0x0000 (---------------) + I dlugoleka 0x002d75c3, // n0x1963 c0x0000 (---------------) + I edu 0x0021b206, // n0x1964 c0x0000 (---------------) + I elblag 0x002aa003, // n0x1965 c0x0000 (---------------) + I elk 0x000b7a43, // n0x1966 c0x0000 (---------------) + gda 0x000e1246, // n0x1967 c0x0000 (---------------) + gdansk 0x0016e4c6, // n0x1968 c0x0000 (---------------) + gdynia 0x0014ee47, // n0x1969 c0x0000 (---------------) + gliwice 0x00391046, // n0x196a c0x0000 (---------------) + I glogow 0x002047c5, // n0x196b c0x0000 (---------------) + I gmina 0x0031b347, // n0x196c c0x0000 (---------------) + I gniezno 0x002b1487, // n0x196d c0x0000 (---------------) + I gorlice 0x4761e283, // n0x196e c0x011d (n0x19f1-n0x1a20) + I gov 0x003147c7, // n0x196f c0x0000 (---------------) + I grajewo 0x0034b2c3, // n0x1970 c0x0000 (---------------) + I gsm 0x0036cb05, // n0x1971 c0x0000 (---------------) + I ilawa 0x00200304, // n0x1972 c0x0000 (---------------) + I info 0x0020a8c8, // n0x1973 c0x0000 (---------------) + I jaworzno 0x0020c80c, // n0x1974 c0x0000 (---------------) + I jelenia-gora 0x00297b45, // n0x1975 c0x0000 (---------------) + I jgora 0x002bed46, // n0x1976 c0x0000 (---------------) + I kalisz 0x002c8947, // n0x1977 c0x0000 (---------------) + I karpacz 0x002017c7, // n0x1978 c0x0000 (---------------) + I kartuzy 0x00216a07, // n0x1979 c0x0000 (---------------) + I kaszuby 0x00217888, // n0x197a c0x0000 (---------------) + I katowice 0x0036730f, // n0x197b c0x0000 (---------------) + I kazimierz-dolny 0x0023df05, // n0x197c c0x0000 (---------------) + I kepno 0x00231ac7, // n0x197d c0x0000 (---------------) + I ketrzyn 0x002a3547, // n0x197e c0x0000 (---------------) + I klodzko 0x0029058a, // n0x197f c0x0000 (---------------) + I kobierzyce 0x00295709, // n0x1980 c0x0000 (---------------) + I kolobrzeg 0x002bbf45, // n0x1981 c0x0000 (---------------) + I konin 0x002bdf8a, // n0x1982 c0x0000 (---------------) + I konskowola 0x0011bec6, // n0x1983 c0x0000 (---------------) + krakow 0x002aa085, // n0x1984 c0x0000 (---------------) + I kutno 0x002be184, // n0x1985 c0x0000 (---------------) + I lapy 0x002c8806, // n0x1986 c0x0000 (---------------) + I lebork 0x00322207, // n0x1987 c0x0000 (---------------) + I legnica 0x002bde07, // n0x1988 c0x0000 (---------------) + I lezajsk 0x0036d448, // n0x1989 c0x0000 (---------------) + I limanowa 0x002c6b85, // n0x198a c0x0000 (---------------) + I lomza 0x00214346, // n0x198b c0x0000 (---------------) + I lowicz 0x00218fc5, // n0x198c c0x0000 (---------------) + I lubin 0x0029b345, // n0x198d c0x0000 (---------------) + I lukow 0x00218f04, // n0x198e c0x0000 (---------------) + I mail 0x00321887, // n0x198f c0x0000 (---------------) + I malbork 0x0030ff4a, // n0x1990 c0x0000 (---------------) + I malopolska 0x0020b988, // n0x1991 c0x0000 (---------------) + I mazowsze 0x002d2a06, // n0x1992 c0x0000 (---------------) + I mazury 0x0000b403, // n0x1993 c0x0000 (---------------) + med 0x002dc385, // n0x1994 c0x0000 (---------------) + I media 0x00232386, // n0x1995 c0x0000 (---------------) + I miasta 0x00381e06, // n0x1996 c0x0000 (---------------) + I mielec 0x002f0806, // n0x1997 c0x0000 (---------------) + I mielno 0x0023fa03, // n0x1998 c0x0000 (---------------) + I mil 0x00371d47, // n0x1999 c0x0000 (---------------) + I mragowo 0x002a34c5, // n0x199a c0x0000 (---------------) + I naklo 0x002170c3, // n0x199b c0x0000 (---------------) + I net 0x0037f74d, // n0x199c c0x0000 (---------------) + I nieruchomosci 0x00207cc3, // n0x199d c0x0000 (---------------) + I nom 0x0036d548, // n0x199e c0x0000 (---------------) + I nowaruda 0x00210944, // n0x199f c0x0000 (---------------) + I nysa 0x00264105, // n0x19a0 c0x0000 (---------------) + I olawa 0x00290486, // n0x19a1 c0x0000 (---------------) + I olecko 0x002c1f06, // n0x19a2 c0x0000 (---------------) + I olkusz 0x0020f9c7, // n0x19a3 c0x0000 (---------------) + I olsztyn 0x00228dc7, // n0x19a4 c0x0000 (---------------) + I opoczno 0x00246a05, // n0x19a5 c0x0000 (---------------) + I opole 0x0021dcc3, // n0x19a6 c0x0000 (---------------) + I org 0x00202387, // n0x19a7 c0x0000 (---------------) + I ostroda 0x00203b09, // n0x19a8 c0x0000 (---------------) + I ostroleka 0x002053c9, // n0x19a9 c0x0000 (---------------) + I ostrowiec 0x0020818a, // n0x19aa c0x0000 (---------------) + I ostrowwlkp 0x00203e02, // n0x19ab c0x0000 (---------------) + I pc 0x0036cac4, // n0x19ac c0x0000 (---------------) + I pila 0x002c2d84, // n0x19ad c0x0000 (---------------) + I pisz 0x00210607, // n0x19ae c0x0000 (---------------) + I podhale 0x0023b508, // n0x19af c0x0000 (---------------) + I podlasie 0x002c8cc9, // n0x19b0 c0x0000 (---------------) + I polkowice 0x00207a09, // n0x19b1 c0x0000 (---------------) + I pomorskie 0x002c9507, // n0x19b2 c0x0000 (---------------) + I pomorze 0x0026a886, // n0x19b3 c0x0000 (---------------) + I powiat 0x000ca606, // n0x19b4 c0x0000 (---------------) + poznan 0x002cba44, // n0x19b5 c0x0000 (---------------) + I priv 0x002cbbca, // n0x19b6 c0x0000 (---------------) + I prochowice 0x002cd2c8, // n0x19b7 c0x0000 (---------------) + I pruszkow 0x002cdec9, // n0x19b8 c0x0000 (---------------) + I przeworsk 0x00281bc6, // n0x19b9 c0x0000 (---------------) + I pulawy 0x002e8285, // n0x19ba c0x0000 (---------------) + I radom 0x0020b848, // n0x19bb c0x0000 (---------------) + I rawa-maz 0x002b174a, // n0x19bc c0x0000 (---------------) + I realestate 0x00241283, // n0x19bd c0x0000 (---------------) + I rel 0x00226746, // n0x19be c0x0000 (---------------) + I rybnik 0x002c9607, // n0x19bf c0x0000 (---------------) + I rzeszow 0x0020b505, // n0x19c0 c0x0000 (---------------) + I sanok 0x00375a45, // n0x19c1 c0x0000 (---------------) + I sejny 0x0029acc3, // n0x19c2 c0x0000 (---------------) + I sex 0x0029b184, // n0x19c3 c0x0000 (---------------) + I shop 0x0021cd45, // n0x19c4 c0x0000 (---------------) + I sklep 0x00270687, // n0x19c5 c0x0000 (---------------) + I skoczow 0x00212585, // n0x19c6 c0x0000 (---------------) + I slask 0x002c1646, // n0x19c7 c0x0000 (---------------) + I slupsk 0x000ddd85, // n0x19c8 c0x0000 (---------------) + sopot 0x0021c283, // n0x19c9 c0x0000 (---------------) + I sos 0x0021c289, // n0x19ca c0x0000 (---------------) + I sosnowiec 0x00263ecc, // n0x19cb c0x0000 (---------------) + I stalowa-wola 0x0029720c, // n0x19cc c0x0000 (---------------) + I starachowice 0x002b8648, // n0x19cd c0x0000 (---------------) + I stargard 0x00325847, // n0x19ce c0x0000 (---------------) + I suwalki 0x002d4d08, // n0x19cf c0x0000 (---------------) + I swidnica 0x002d590a, // n0x19d0 c0x0000 (---------------) + I swiebodzin 0x002d608b, // n0x19d1 c0x0000 (---------------) + I swinoujscie 0x003433c8, // n0x19d2 c0x0000 (---------------) + I szczecin 0x002bee48, // n0x19d3 c0x0000 (---------------) + I szczytno 0x00207586, // n0x19d4 c0x0000 (---------------) + I szkola 0x0030a185, // n0x19d5 c0x0000 (---------------) + I targi 0x0030ebca, // n0x19d6 c0x0000 (---------------) + I tarnobrzeg 0x0021e345, // n0x19d7 c0x0000 (---------------) + I tgory 0x00208902, // n0x19d8 c0x0000 (---------------) + I tm 0x002ae287, // n0x19d9 c0x0000 (---------------) + I tourism 0x0027f186, // n0x19da c0x0000 (---------------) + I travel 0x0033de05, // n0x19db c0x0000 (---------------) + I turek 0x002d8689, // n0x19dc c0x0000 (---------------) + I turystyka 0x0036b4c5, // n0x19dd c0x0000 (---------------) + I tychy 0x0027af05, // n0x19de c0x0000 (---------------) + I ustka 0x0036c6c9, // n0x19df c0x0000 (---------------) + I walbrzych 0x00232206, // n0x19e0 c0x0000 (---------------) + I warmia 0x00250f08, // n0x19e1 c0x0000 (---------------) + I warszawa 0x002c7183, // n0x19e2 c0x0000 (---------------) + I waw 0x00391186, // n0x19e3 c0x0000 (---------------) + I wegrow 0x00263586, // n0x19e4 c0x0000 (---------------) + I wielun 0x002e2d45, // n0x19e5 c0x0000 (---------------) + I wlocl 0x002e2d49, // n0x19e6 c0x0000 (---------------) + I wloclawek 0x0030b189, // n0x19e7 c0x0000 (---------------) + I wodzislaw 0x002609c7, // n0x19e8 c0x0000 (---------------) + I wolomin 0x000e2bc4, // n0x19e9 c0x0000 (---------------) + wroc 0x002e2bc7, // n0x19ea c0x0000 (---------------) + I wroclaw 0x00207909, // n0x19eb c0x0000 (---------------) + I zachpomor 0x00216245, // n0x19ec c0x0000 (---------------) + I zagan 0x0002bf08, // n0x19ed c0x0000 (---------------) + zakopane 0x00310d85, // n0x19ee c0x0000 (---------------) + I zarow 0x00217185, // n0x19ef c0x0000 (---------------) + I zgora 0x0021e549, // n0x19f0 c0x0000 (---------------) + I zgorzelec 0x002105c2, // n0x19f1 c0x0000 (---------------) + I ap 0x00253e04, // n0x19f2 c0x0000 (---------------) + I griw 0x00200b42, // n0x19f3 c0x0000 (---------------) + I ic 0x00202b42, // n0x19f4 c0x0000 (---------------) + I is 0x00268d85, // n0x19f5 c0x0000 (---------------) + I kmpsp 0x002c1788, // n0x19f6 c0x0000 (---------------) + I konsulat 0x00379185, // n0x19f7 c0x0000 (---------------) + I kppsp 0x002ac643, // n0x19f8 c0x0000 (---------------) + I kwp 0x002ac645, // n0x19f9 c0x0000 (---------------) + I kwpsp 0x002bb7c3, // n0x19fa c0x0000 (---------------) + I mup 0x0020a142, // n0x19fb c0x0000 (---------------) + I mw 0x002d3fc4, // n0x19fc c0x0000 (---------------) + I oirm 0x002f3c43, // n0x19fd c0x0000 (---------------) + I oum 0x002052c2, // n0x19fe c0x0000 (---------------) + I pa 0x0036be84, // n0x19ff c0x0000 (---------------) + I pinb 0x002c3b43, // n0x1a00 c0x0000 (---------------) + I piw 0x00203f02, // n0x1a01 c0x0000 (---------------) + I po 0x002369c3, // n0x1a02 c0x0000 (---------------) + I psp 0x0027ac04, // n0x1a03 c0x0000 (---------------) + I psse 0x002a32c3, // n0x1a04 c0x0000 (---------------) + I pup 0x00370ac4, // n0x1a05 c0x0000 (---------------) + I rzgw 0x00201a02, // n0x1a06 c0x0000 (---------------) + I sa 0x0025ebc3, // n0x1a07 c0x0000 (---------------) + I sdn 0x002206c3, // n0x1a08 c0x0000 (---------------) + I sko 0x00201102, // n0x1a09 c0x0000 (---------------) + I so 0x002ceec2, // n0x1a0a c0x0000 (---------------) + I sr 0x0030afc9, // n0x1a0b c0x0000 (---------------) + I starostwo 0x00205082, // n0x1a0c c0x0000 (---------------) + I ug 0x0031c4c4, // n0x1a0d c0x0000 (---------------) + I ugim 0x00209802, // n0x1a0e c0x0000 (---------------) + I um 0x0020b6c4, // n0x1a0f c0x0000 (---------------) + I umig 0x0026a844, // n0x1a10 c0x0000 (---------------) + I upow 0x00243ec4, // n0x1a11 c0x0000 (---------------) + I uppo 0x00209f42, // n0x1a12 c0x0000 (---------------) + I us 0x0022f3c2, // n0x1a13 c0x0000 (---------------) + I uw 0x0020c583, // n0x1a14 c0x0000 (---------------) + I uzs 0x00345983, // n0x1a15 c0x0000 (---------------) + I wif 0x002310c4, // n0x1a16 c0x0000 (---------------) + I wiih 0x00270804, // n0x1a17 c0x0000 (---------------) + I winb 0x002b8984, // n0x1a18 c0x0000 (---------------) + I wios 0x002c9784, // n0x1a19 c0x0000 (---------------) + I witd 0x0030b383, // n0x1a1a c0x0000 (---------------) + I wiw 0x002725c3, // n0x1a1b c0x0000 (---------------) + I wsa 0x0031be44, // n0x1a1c c0x0000 (---------------) + I wskr 0x002e3d44, // n0x1a1d c0x0000 (---------------) + I wuoz 0x002e4546, // n0x1a1e c0x0000 (---------------) + I wzmiuw 0x002c2042, // n0x1a1f c0x0000 (---------------) + I zp 0x00200742, // n0x1a20 c0x0000 (---------------) + I co 0x002d75c3, // n0x1a21 c0x0000 (---------------) + I edu 0x0021e283, // n0x1a22 c0x0000 (---------------) + I gov 0x002170c3, // n0x1a23 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1a24 c0x0000 (---------------) + I org 0x00201e82, // n0x1a25 c0x0000 (---------------) + I ac 0x00310603, // n0x1a26 c0x0000 (---------------) + I biz 0x00222ac3, // n0x1a27 c0x0000 (---------------) + I com 0x002d75c3, // n0x1a28 c0x0000 (---------------) + I edu 0x00208883, // n0x1a29 c0x0000 (---------------) + I est 0x0021e283, // n0x1a2a c0x0000 (---------------) + I gov 0x00200304, // n0x1a2b c0x0000 (---------------) + I info 0x0030b284, // n0x1a2c c0x0000 (---------------) + I isla 0x00298944, // n0x1a2d c0x0000 (---------------) + I name 0x002170c3, // n0x1a2e c0x0000 (---------------) + I net 0x0021dcc3, // n0x1a2f c0x0000 (---------------) + I org 0x00218243, // n0x1a30 c0x0000 (---------------) + I pro 0x002cc284, // n0x1a31 c0x0000 (---------------) + I prof 0x002f2783, // n0x1a32 c0x0000 (---------------) + I aca 0x0020c103, // n0x1a33 c0x0000 (---------------) + I bar 0x0025b403, // n0x1a34 c0x0000 (---------------) + I cpa 0x002674c3, // n0x1a35 c0x0000 (---------------) + I eng 0x0029d803, // n0x1a36 c0x0000 (---------------) + I jur 0x00253883, // n0x1a37 c0x0000 (---------------) + I law 0x0020b403, // n0x1a38 c0x0000 (---------------) + I med 0x00222ac3, // n0x1a39 c0x0000 (---------------) + I com 0x002d75c3, // n0x1a3a c0x0000 (---------------) + I edu 0x0021e283, // n0x1a3b c0x0000 (---------------) + I gov 0x002170c3, // n0x1a3c c0x0000 (---------------) + I net 0x0021dcc3, // n0x1a3d c0x0000 (---------------) + I org 0x002c6b43, // n0x1a3e c0x0000 (---------------) + I plo 0x00223f83, // n0x1a3f c0x0000 (---------------) + I sec 0x000e4188, // n0x1a40 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1a41 c0x0000 (---------------) + I com 0x002d75c3, // n0x1a42 c0x0000 (---------------) + I edu 0x0021e283, // n0x1a43 c0x0000 (---------------) + I gov 0x00238c03, // n0x1a44 c0x0000 (---------------) + I int 0x002170c3, // n0x1a45 c0x0000 (---------------) + I net 0x0022cb84, // n0x1a46 c0x0000 (---------------) + I nome 0x0021dcc3, // n0x1a47 c0x0000 (---------------) + I org 0x00296544, // n0x1a48 c0x0000 (---------------) + I publ 0x00251645, // n0x1a49 c0x0000 (---------------) + I belau 0x00200742, // n0x1a4a c0x0000 (---------------) + I co 0x00203fc2, // n0x1a4b c0x0000 (---------------) + I ed 0x00202342, // n0x1a4c c0x0000 (---------------) + I go 0x00201082, // n0x1a4d c0x0000 (---------------) + I ne 0x00200c42, // n0x1a4e c0x0000 (---------------) + I or 0x00222ac3, // n0x1a4f c0x0000 (---------------) + I com 0x00228d44, // n0x1a50 c0x0000 (---------------) + I coop 0x002d75c3, // n0x1a51 c0x0000 (---------------) + I edu 0x0021e283, // n0x1a52 c0x0000 (---------------) + I gov 0x0023fa03, // n0x1a53 c0x0000 (---------------) + I mil 0x002170c3, // n0x1a54 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1a55 c0x0000 (---------------) + I org 0x000e4188, // n0x1a56 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1a57 c0x0000 (---------------) + I com 0x002d75c3, // n0x1a58 c0x0000 (---------------) + I edu 0x0021e283, // n0x1a59 c0x0000 (---------------) + I gov 0x0023fa03, // n0x1a5a c0x0000 (---------------) + I mil 0x00298944, // n0x1a5b c0x0000 (---------------) + I name 0x002170c3, // n0x1a5c c0x0000 (---------------) + I net 0x0021dcc3, // n0x1a5d c0x0000 (---------------) + I org 0x00206103, // n0x1a5e c0x0000 (---------------) + I sch 0x002729c4, // n0x1a5f c0x0000 (---------------) + I asso 0x000e4188, // n0x1a60 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1a61 c0x0000 (---------------) + I com 0x00207cc3, // n0x1a62 c0x0000 (---------------) + I nom 0x00246584, // n0x1a63 c0x0000 (---------------) + I arts 0x000e4188, // n0x1a64 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1a65 c0x0000 (---------------) + I com 0x00238544, // n0x1a66 c0x0000 (---------------) + I firm 0x00200304, // n0x1a67 c0x0000 (---------------) + I info 0x00207cc3, // n0x1a68 c0x0000 (---------------) + I nom 0x00200e02, // n0x1a69 c0x0000 (---------------) + I nt 0x0021dcc3, // n0x1a6a c0x0000 (---------------) + I org 0x002e6343, // n0x1a6b c0x0000 (---------------) + I rec 0x002cf4c5, // n0x1a6c c0x0000 (---------------) + I store 0x00208902, // n0x1a6d c0x0000 (---------------) + I tm 0x002e3e83, // n0x1a6e c0x0000 (---------------) + I www 0x00201e82, // n0x1a6f c0x0000 (---------------) + I ac 0x000e4188, // n0x1a70 c0x0000 (---------------) + blogspot 0x00200742, // n0x1a71 c0x0000 (---------------) + I co 0x002d75c3, // n0x1a72 c0x0000 (---------------) + I edu 0x0021e283, // n0x1a73 c0x0000 (---------------) + I gov 0x00200242, // n0x1a74 c0x0000 (---------------) + I in 0x0021dcc3, // n0x1a75 c0x0000 (---------------) + I org 0x00201e82, // n0x1a76 c0x0000 (---------------) + I ac 0x00382c47, // n0x1a77 c0x0000 (---------------) + I adygeya 0x0028ee05, // n0x1a78 c0x0000 (---------------) + I altai 0x00248504, // n0x1a79 c0x0000 (---------------) + I amur 0x0036ab06, // n0x1a7a c0x0000 (---------------) + I amursk 0x002f314b, // n0x1a7b c0x0000 (---------------) + I arkhangelsk 0x002e9b49, // n0x1a7c c0x0000 (---------------) + I astrakhan 0x002bec86, // n0x1a7d c0x0000 (---------------) + I baikal 0x00309449, // n0x1a7e c0x0000 (---------------) + I bashkiria 0x002c1a08, // n0x1a7f c0x0000 (---------------) + I belgorod 0x00200503, // n0x1a80 c0x0000 (---------------) + I bir 0x000e4188, // n0x1a81 c0x0000 (---------------) + blogspot 0x0021cc07, // n0x1a82 c0x0000 (---------------) + I bryansk 0x0021bc88, // n0x1a83 c0x0000 (---------------) + I buryatia 0x00355dc3, // n0x1a84 c0x0000 (---------------) + I cbg 0x002503c4, // n0x1a85 c0x0000 (---------------) + I chel 0x002539cb, // n0x1a86 c0x0000 (---------------) + I chelyabinsk 0x002932c5, // n0x1a87 c0x0000 (---------------) + I chita 0x002ab708, // n0x1a88 c0x0000 (---------------) + I chukotka 0x00313689, // n0x1a89 c0x0000 (---------------) + I chuvashia 0x00249083, // n0x1a8a c0x0000 (---------------) + I cmw 0x00222ac3, // n0x1a8b c0x0000 (---------------) + I com 0x00309888, // n0x1a8c c0x0000 (---------------) + I dagestan 0x002d3887, // n0x1a8d c0x0000 (---------------) + I dudinka 0x00311a46, // n0x1a8e c0x0000 (---------------) + I e-burg 0x002d75c3, // n0x1a8f c0x0000 (---------------) + I edu 0x0032aa47, // n0x1a90 c0x0000 (---------------) + I fareast 0x0021e283, // n0x1a91 c0x0000 (---------------) + I gov 0x003789c6, // n0x1a92 c0x0000 (---------------) + I grozny 0x00238c03, // n0x1a93 c0x0000 (---------------) + I int 0x00220587, // n0x1a94 c0x0000 (---------------) + I irkutsk 0x002f2a47, // n0x1a95 c0x0000 (---------------) + I ivanovo 0x00379007, // n0x1a96 c0x0000 (---------------) + I izhevsk 0x00321805, // n0x1a97 c0x0000 (---------------) + I jamal 0x00202683, // n0x1a98 c0x0000 (---------------) + I jar 0x002a248b, // n0x1a99 c0x0000 (---------------) + I joshkar-ola 0x00312348, // n0x1a9a c0x0000 (---------------) + I k-uralsk 0x002201c8, // n0x1a9b c0x0000 (---------------) + I kalmykia 0x00305446, // n0x1a9c c0x0000 (---------------) + I kaluga 0x0023a649, // n0x1a9d c0x0000 (---------------) + I kamchatka 0x00365ac7, // n0x1a9e c0x0000 (---------------) + I karelia 0x002dec85, // n0x1a9f c0x0000 (---------------) + I kazan 0x0022d2c4, // n0x1aa0 c0x0000 (---------------) + I kchr 0x00271548, // n0x1aa1 c0x0000 (---------------) + I kemerovo 0x00235f8a, // n0x1aa2 c0x0000 (---------------) + I khabarovsk 0x002361c9, // n0x1aa3 c0x0000 (---------------) + I khakassia 0x0025be03, // n0x1aa4 c0x0000 (---------------) + I khv 0x00254bc5, // n0x1aa5 c0x0000 (---------------) + I kirov 0x00325683, // n0x1aa6 c0x0000 (---------------) + I kms 0x002b9586, // n0x1aa7 c0x0000 (---------------) + I koenig 0x003935c4, // n0x1aa8 c0x0000 (---------------) + I komi 0x002e2f48, // n0x1aa9 c0x0000 (---------------) + I kostroma 0x0039334b, // n0x1aaa c0x0000 (---------------) + I krasnoyarsk 0x00331845, // n0x1aab c0x0000 (---------------) + I kuban 0x002a4ac6, // n0x1aac c0x0000 (---------------) + I kurgan 0x002a8e85, // n0x1aad c0x0000 (---------------) + I kursk 0x002a9608, // n0x1aae c0x0000 (---------------) + I kustanai 0x002aa1c7, // n0x1aaf c0x0000 (---------------) + I kuzbass 0x003414c7, // n0x1ab0 c0x0000 (---------------) + I lipetsk 0x0032ddc7, // n0x1ab1 c0x0000 (---------------) + I magadan 0x00271948, // n0x1ab2 c0x0000 (---------------) + I magnitka 0x00216504, // n0x1ab3 c0x0000 (---------------) + I mari 0x00216507, // n0x1ab4 c0x0000 (---------------) + I mari-el 0x003529c6, // n0x1ab5 c0x0000 (---------------) + I marine 0x0023fa03, // n0x1ab6 c0x0000 (---------------) + I mil 0x002b4208, // n0x1ab7 c0x0000 (---------------) + I mordovia 0x00233f43, // n0x1ab8 c0x0000 (---------------) + I msk 0x002bbd88, // n0x1ab9 c0x0000 (---------------) + I murmansk 0x002bf205, // n0x1aba c0x0000 (---------------) + I mytis 0x00332688, // n0x1abb c0x0000 (---------------) + I nakhodka 0x00375747, // n0x1abc c0x0000 (---------------) + I nalchik 0x002170c3, // n0x1abd c0x0000 (---------------) + I net 0x002effc3, // n0x1abe c0x0000 (---------------) + I nkz 0x00278ec4, // n0x1abf c0x0000 (---------------) + I nnov 0x00228f07, // n0x1ac0 c0x0000 (---------------) + I norilsk 0x00201343, // n0x1ac1 c0x0000 (---------------) + I nov 0x002f2b0b, // n0x1ac2 c0x0000 (---------------) + I novosibirsk 0x00217803, // n0x1ac3 c0x0000 (---------------) + I nsk 0x00233f04, // n0x1ac4 c0x0000 (---------------) + I omsk 0x002cf548, // n0x1ac5 c0x0000 (---------------) + I orenburg 0x0021dcc3, // n0x1ac6 c0x0000 (---------------) + I org 0x002c98c5, // n0x1ac7 c0x0000 (---------------) + I oryol 0x002e3305, // n0x1ac8 c0x0000 (---------------) + I oskol 0x00332586, // n0x1ac9 c0x0000 (---------------) + I palana 0x00395385, // n0x1aca c0x0000 (---------------) + I penza 0x002bf5c4, // n0x1acb c0x0000 (---------------) + I perm 0x00207742, // n0x1acc c0x0000 (---------------) + I pp 0x002ce183, // n0x1acd c0x0000 (---------------) + I ptz 0x002be20a, // n0x1ace c0x0000 (---------------) + I pyatigorsk 0x002ef043, // n0x1acf c0x0000 (---------------) + I rnd 0x0030c189, // n0x1ad0 c0x0000 (---------------) + I rubtsovsk 0x003227c6, // n0x1ad1 c0x0000 (---------------) + I ryazan 0x00217648, // n0x1ad2 c0x0000 (---------------) + I sakhalin 0x0027a746, // n0x1ad3 c0x0000 (---------------) + I samara 0x00218487, // n0x1ad4 c0x0000 (---------------) + I saratov 0x002b7c08, // n0x1ad5 c0x0000 (---------------) + I simbirsk 0x002ae3c8, // n0x1ad6 c0x0000 (---------------) + I smolensk 0x002c5603, // n0x1ad7 c0x0000 (---------------) + I snz 0x00268e43, // n0x1ad8 c0x0000 (---------------) + I spb 0x002187c9, // n0x1ad9 c0x0000 (---------------) + I stavropol 0x002daf83, // n0x1ada c0x0000 (---------------) + I stv 0x002d0c06, // n0x1adb c0x0000 (---------------) + I surgut 0x0028ea86, // n0x1adc c0x0000 (---------------) + I syzran 0x002fe106, // n0x1add c0x0000 (---------------) + I tambov 0x0031df09, // n0x1ade c0x0000 (---------------) + I tatarstan 0x002e3fc4, // n0x1adf c0x0000 (---------------) + I test 0x0020fe03, // n0x1ae0 c0x0000 (---------------) + I tom 0x00233ec5, // n0x1ae1 c0x0000 (---------------) + I tomsk 0x0038c2c9, // n0x1ae2 c0x0000 (---------------) + I tsaritsyn 0x00220683, // n0x1ae3 c0x0000 (---------------) + I tsk 0x002d78c4, // n0x1ae4 c0x0000 (---------------) + I tula 0x002d9504, // n0x1ae5 c0x0000 (---------------) + I tuva 0x00248304, // n0x1ae6 c0x0000 (---------------) + I tver 0x002a7d06, // n0x1ae7 c0x0000 (---------------) + I tyumen 0x00309dc3, // n0x1ae8 c0x0000 (---------------) + I udm 0x00309dc8, // n0x1ae9 c0x0000 (---------------) + I udmurtia 0x00245a08, // n0x1aea c0x0000 (---------------) + I ulan-ude 0x002fe246, // n0x1aeb c0x0000 (---------------) + I vdonsk 0x002dea8b, // n0x1aec c0x0000 (---------------) + I vladikavkaz 0x002dedc8, // n0x1aed c0x0000 (---------------) + I vladimir 0x002defcb, // n0x1aee c0x0000 (---------------) + I vladivostok 0x002df749, // n0x1aef c0x0000 (---------------) + I volgograd 0x002e1147, // n0x1af0 c0x0000 (---------------) + I vologda 0x002e1e48, // n0x1af1 c0x0000 (---------------) + I voronezh 0x002e2b03, // n0x1af2 c0x0000 (---------------) + I vrn 0x0037fec6, // n0x1af3 c0x0000 (---------------) + I vyatka 0x0020d4c7, // n0x1af4 c0x0000 (---------------) + I yakutia 0x00284405, // n0x1af5 c0x0000 (---------------) + I yamal 0x00332d09, // n0x1af6 c0x0000 (---------------) + I yaroslavl 0x0036e1cd, // n0x1af7 c0x0000 (---------------) + I yekaterinburg 0x00217491, // n0x1af8 c0x0000 (---------------) + I yuzhno-sakhalinsk 0x0029adc5, // n0x1af9 c0x0000 (---------------) + I zgrad 0x00201e82, // n0x1afa c0x0000 (---------------) + I ac 0x00200742, // n0x1afb c0x0000 (---------------) + I co 0x00222ac3, // n0x1afc c0x0000 (---------------) + I com 0x002d75c3, // n0x1afd c0x0000 (---------------) + I edu 0x003579c4, // n0x1afe c0x0000 (---------------) + I gouv 0x0021e283, // n0x1aff c0x0000 (---------------) + I gov 0x00238c03, // n0x1b00 c0x0000 (---------------) + I int 0x0023fa03, // n0x1b01 c0x0000 (---------------) + I mil 0x002170c3, // n0x1b02 c0x0000 (---------------) + I net 0x00222ac3, // n0x1b03 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b04 c0x0000 (---------------) + I edu 0x0021e283, // n0x1b05 c0x0000 (---------------) + I gov 0x0020b403, // n0x1b06 c0x0000 (---------------) + I med 0x002170c3, // n0x1b07 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b08 c0x0000 (---------------) + I org 0x00296543, // n0x1b09 c0x0000 (---------------) + I pub 0x00206103, // n0x1b0a c0x0000 (---------------) + I sch 0x00222ac3, // n0x1b0b c0x0000 (---------------) + I com 0x002d75c3, // n0x1b0c c0x0000 (---------------) + I edu 0x0021e283, // n0x1b0d c0x0000 (---------------) + I gov 0x002170c3, // n0x1b0e c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b0f c0x0000 (---------------) + I org 0x00222ac3, // n0x1b10 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b11 c0x0000 (---------------) + I edu 0x0021e283, // n0x1b12 c0x0000 (---------------) + I gov 0x002170c3, // n0x1b13 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b14 c0x0000 (---------------) + I org 0x00222ac3, // n0x1b15 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b16 c0x0000 (---------------) + I edu 0x0021e283, // n0x1b17 c0x0000 (---------------) + I gov 0x00200304, // n0x1b18 c0x0000 (---------------) + I info 0x0020b403, // n0x1b19 c0x0000 (---------------) + I med 0x002170c3, // n0x1b1a c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b1b c0x0000 (---------------) + I org 0x0020bf42, // n0x1b1c c0x0000 (---------------) + I tv 0x00200181, // n0x1b1d c0x0000 (---------------) + I a 0x00201e82, // n0x1b1e c0x0000 (---------------) + I ac 0x00200001, // n0x1b1f c0x0000 (---------------) + I b 0x002fbc02, // n0x1b20 c0x0000 (---------------) + I bd 0x000e4188, // n0x1b21 c0x0000 (---------------) + blogspot 0x00213b05, // n0x1b22 c0x0000 (---------------) + I brand 0x00200741, // n0x1b23 c0x0000 (---------------) + I c 0x00022ac3, // n0x1b24 c0x0000 (---------------) + com 0x002005c1, // n0x1b25 c0x0000 (---------------) + I d 0x00200701, // n0x1b26 c0x0000 (---------------) + I e 0x00200381, // n0x1b27 c0x0000 (---------------) + I f 0x00235ec2, // n0x1b28 c0x0000 (---------------) + I fh 0x00235ec4, // n0x1b29 c0x0000 (---------------) + I fhsk 0x00351283, // n0x1b2a c0x0000 (---------------) + I fhv 0x00200401, // n0x1b2b c0x0000 (---------------) + I g 0x00200201, // n0x1b2c c0x0000 (---------------) + I h 0x00200041, // n0x1b2d c0x0000 (---------------) + I i 0x00201001, // n0x1b2e c0x0000 (---------------) + I k 0x002c8587, // n0x1b2f c0x0000 (---------------) + I komforb 0x002a8f8f, // n0x1b30 c0x0000 (---------------) + I kommunalforbund 0x002b1a86, // n0x1b31 c0x0000 (---------------) + I komvux 0x002008c1, // n0x1b32 c0x0000 (---------------) + I l 0x00323b46, // n0x1b33 c0x0000 (---------------) + I lanbib 0x002000c1, // n0x1b34 c0x0000 (---------------) + I m 0x00200281, // n0x1b35 c0x0000 (---------------) + I n 0x002f460e, // n0x1b36 c0x0000 (---------------) + I naturbruksgymn 0x00200081, // n0x1b37 c0x0000 (---------------) + I o 0x0021dcc3, // n0x1b38 c0x0000 (---------------) + I org 0x00200b01, // n0x1b39 c0x0000 (---------------) + I p 0x00290b05, // n0x1b3a c0x0000 (---------------) + I parti 0x00207742, // n0x1b3b c0x0000 (---------------) + I pp 0x0029abc5, // n0x1b3c c0x0000 (---------------) + I press 0x00200581, // n0x1b3d c0x0000 (---------------) + I r 0x002001c1, // n0x1b3e c0x0000 (---------------) + I s 0x00200141, // n0x1b3f c0x0000 (---------------) + I t 0x00208902, // n0x1b40 c0x0000 (---------------) + I tm 0x00200101, // n0x1b41 c0x0000 (---------------) + I u 0x00202541, // n0x1b42 c0x0000 (---------------) + I w 0x00203ec1, // n0x1b43 c0x0000 (---------------) + I x 0x00200801, // n0x1b44 c0x0000 (---------------) + I y 0x00201901, // n0x1b45 c0x0000 (---------------) + I z 0x000e4188, // n0x1b46 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1b47 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b48 c0x0000 (---------------) + I edu 0x0021e283, // n0x1b49 c0x0000 (---------------) + I gov 0x002170c3, // n0x1b4a c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b4b c0x0000 (---------------) + I org 0x00214943, // n0x1b4c c0x0000 (---------------) + I per 0x00222ac3, // n0x1b4d c0x0000 (---------------) + I com 0x0021e283, // n0x1b4e c0x0000 (---------------) + I gov 0x0023fa03, // n0x1b4f c0x0000 (---------------) + I mil 0x002170c3, // n0x1b50 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b51 c0x0000 (---------------) + I org 0x014c56c8, // n0x1b52 c0x0005 (---------------)* o platform 0x000e4188, // n0x1b53 c0x0000 (---------------) + blogspot 0x000e4188, // n0x1b54 c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1b55 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b56 c0x0000 (---------------) + I edu 0x0021e283, // n0x1b57 c0x0000 (---------------) + I gov 0x002170c3, // n0x1b58 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b59 c0x0000 (---------------) + I org 0x00200603, // n0x1b5a c0x0000 (---------------) + I art 0x000e4188, // n0x1b5b c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1b5c c0x0000 (---------------) + I com 0x002d75c3, // n0x1b5d c0x0000 (---------------) + I edu 0x003579c4, // n0x1b5e c0x0000 (---------------) + I gouv 0x0021dcc3, // n0x1b5f c0x0000 (---------------) + I org 0x0028acc5, // n0x1b60 c0x0000 (---------------) + I perso 0x0029f044, // n0x1b61 c0x0000 (---------------) + I univ 0x00222ac3, // n0x1b62 c0x0000 (---------------) + I com 0x002170c3, // n0x1b63 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b64 c0x0000 (---------------) + I org 0x00200742, // n0x1b65 c0x0000 (---------------) + I co 0x00222ac3, // n0x1b66 c0x0000 (---------------) + I com 0x00224f09, // n0x1b67 c0x0000 (---------------) + I consulado 0x002d75c3, // n0x1b68 c0x0000 (---------------) + I edu 0x00271109, // n0x1b69 c0x0000 (---------------) + I embaixada 0x0021e283, // n0x1b6a c0x0000 (---------------) + I gov 0x0023fa03, // n0x1b6b c0x0000 (---------------) + I mil 0x002170c3, // n0x1b6c c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b6d c0x0000 (---------------) + I org 0x002cb848, // n0x1b6e c0x0000 (---------------) + I principe 0x0020fd47, // n0x1b6f c0x0000 (---------------) + I saotome 0x002cf4c5, // n0x1b70 c0x0000 (---------------) + I store 0x00382c47, // n0x1b71 c0x0000 (---------------) + I adygeya 0x002f314b, // n0x1b72 c0x0000 (---------------) + I arkhangelsk 0x00389cc8, // n0x1b73 c0x0000 (---------------) + I balashov 0x00309449, // n0x1b74 c0x0000 (---------------) + I bashkiria 0x0021cc07, // n0x1b75 c0x0000 (---------------) + I bryansk 0x00309888, // n0x1b76 c0x0000 (---------------) + I dagestan 0x003789c6, // n0x1b77 c0x0000 (---------------) + I grozny 0x002f2a47, // n0x1b78 c0x0000 (---------------) + I ivanovo 0x002201c8, // n0x1b79 c0x0000 (---------------) + I kalmykia 0x00305446, // n0x1b7a c0x0000 (---------------) + I kaluga 0x00365ac7, // n0x1b7b c0x0000 (---------------) + I karelia 0x002361c9, // n0x1b7c c0x0000 (---------------) + I khakassia 0x00384e89, // n0x1b7d c0x0000 (---------------) + I krasnodar 0x002a4ac6, // n0x1b7e c0x0000 (---------------) + I kurgan 0x00275dc5, // n0x1b7f c0x0000 (---------------) + I lenug 0x002b4208, // n0x1b80 c0x0000 (---------------) + I mordovia 0x00233f43, // n0x1b81 c0x0000 (---------------) + I msk 0x002bbd88, // n0x1b82 c0x0000 (---------------) + I murmansk 0x00375747, // n0x1b83 c0x0000 (---------------) + I nalchik 0x00201343, // n0x1b84 c0x0000 (---------------) + I nov 0x0032a707, // n0x1b85 c0x0000 (---------------) + I obninsk 0x00395385, // n0x1b86 c0x0000 (---------------) + I penza 0x002c8208, // n0x1b87 c0x0000 (---------------) + I pokrovsk 0x00262b45, // n0x1b88 c0x0000 (---------------) + I sochi 0x00268e43, // n0x1b89 c0x0000 (---------------) + I spb 0x003547c9, // n0x1b8a c0x0000 (---------------) + I togliatti 0x00295587, // n0x1b8b c0x0000 (---------------) + I troitsk 0x002d78c4, // n0x1b8c c0x0000 (---------------) + I tula 0x002d9504, // n0x1b8d c0x0000 (---------------) + I tuva 0x002dea8b, // n0x1b8e c0x0000 (---------------) + I vladikavkaz 0x002dedc8, // n0x1b8f c0x0000 (---------------) + I vladimir 0x002e1147, // n0x1b90 c0x0000 (---------------) + I vologda 0x00222ac3, // n0x1b91 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b92 c0x0000 (---------------) + I edu 0x0034eb03, // n0x1b93 c0x0000 (---------------) + I gob 0x0021dcc3, // n0x1b94 c0x0000 (---------------) + I org 0x00230683, // n0x1b95 c0x0000 (---------------) + I red 0x0021e283, // n0x1b96 c0x0000 (---------------) + I gov 0x00222ac3, // n0x1b97 c0x0000 (---------------) + I com 0x002d75c3, // n0x1b98 c0x0000 (---------------) + I edu 0x0021e283, // n0x1b99 c0x0000 (---------------) + I gov 0x0023fa03, // n0x1b9a c0x0000 (---------------) + I mil 0x002170c3, // n0x1b9b c0x0000 (---------------) + I net 0x0021dcc3, // n0x1b9c c0x0000 (---------------) + I org 0x00201e82, // n0x1b9d c0x0000 (---------------) + I ac 0x00200742, // n0x1b9e c0x0000 (---------------) + I co 0x0021dcc3, // n0x1b9f c0x0000 (---------------) + I org 0x000e4188, // n0x1ba0 c0x0000 (---------------) + blogspot 0x00201e82, // n0x1ba1 c0x0000 (---------------) + I ac 0x00200742, // n0x1ba2 c0x0000 (---------------) + I co 0x00202342, // n0x1ba3 c0x0000 (---------------) + I go 0x00200242, // n0x1ba4 c0x0000 (---------------) + I in 0x00204802, // n0x1ba5 c0x0000 (---------------) + I mi 0x002170c3, // n0x1ba6 c0x0000 (---------------) + I net 0x00200c42, // n0x1ba7 c0x0000 (---------------) + I or 0x00201e82, // n0x1ba8 c0x0000 (---------------) + I ac 0x00310603, // n0x1ba9 c0x0000 (---------------) + I biz 0x00200742, // n0x1baa c0x0000 (---------------) + I co 0x00222ac3, // n0x1bab c0x0000 (---------------) + I com 0x002d75c3, // n0x1bac c0x0000 (---------------) + I edu 0x00202342, // n0x1bad c0x0000 (---------------) + I go 0x0021e283, // n0x1bae c0x0000 (---------------) + I gov 0x00238c03, // n0x1baf c0x0000 (---------------) + I int 0x0023fa03, // n0x1bb0 c0x0000 (---------------) + I mil 0x00298944, // n0x1bb1 c0x0000 (---------------) + I name 0x002170c3, // n0x1bb2 c0x0000 (---------------) + I net 0x0020e3c3, // n0x1bb3 c0x0000 (---------------) + I nic 0x0021dcc3, // n0x1bb4 c0x0000 (---------------) + I org 0x002e3fc4, // n0x1bb5 c0x0000 (---------------) + I test 0x00219fc3, // n0x1bb6 c0x0000 (---------------) + I web 0x0021e283, // n0x1bb7 c0x0000 (---------------) + I gov 0x00200742, // n0x1bb8 c0x0000 (---------------) + I co 0x00222ac3, // n0x1bb9 c0x0000 (---------------) + I com 0x002d75c3, // n0x1bba c0x0000 (---------------) + I edu 0x0021e283, // n0x1bbb c0x0000 (---------------) + I gov 0x0023fa03, // n0x1bbc c0x0000 (---------------) + I mil 0x002170c3, // n0x1bbd c0x0000 (---------------) + I net 0x00207cc3, // n0x1bbe c0x0000 (---------------) + I nom 0x0021dcc3, // n0x1bbf c0x0000 (---------------) + I org 0x002efd87, // n0x1bc0 c0x0000 (---------------) + I agrinet 0x00222ac3, // n0x1bc1 c0x0000 (---------------) + I com 0x00245b87, // n0x1bc2 c0x0000 (---------------) + I defense 0x002d75c6, // n0x1bc3 c0x0000 (---------------) + I edunet 0x00210e83, // n0x1bc4 c0x0000 (---------------) + I ens 0x00236403, // n0x1bc5 c0x0000 (---------------) + I fin 0x0021e283, // n0x1bc6 c0x0000 (---------------) + I gov 0x00215703, // n0x1bc7 c0x0000 (---------------) + I ind 0x00200304, // n0x1bc8 c0x0000 (---------------) + I info 0x002c5104, // n0x1bc9 c0x0000 (---------------) + I intl 0x002d4086, // n0x1bca c0x0000 (---------------) + I mincom 0x0023ac03, // n0x1bcb c0x0000 (---------------) + I nat 0x002170c3, // n0x1bcc c0x0000 (---------------) + I net 0x0021dcc3, // n0x1bcd c0x0000 (---------------) + I org 0x0028acc5, // n0x1bce c0x0000 (---------------) + I perso 0x003538c4, // n0x1bcf c0x0000 (---------------) + I rnrt 0x002e6c03, // n0x1bd0 c0x0000 (---------------) + I rns 0x00205b83, // n0x1bd1 c0x0000 (---------------) + I rnu 0x002ae287, // n0x1bd2 c0x0000 (---------------) + I tourism 0x0033c485, // n0x1bd3 c0x0000 (---------------) + I turen 0x00222ac3, // n0x1bd4 c0x0000 (---------------) + I com 0x002d75c3, // n0x1bd5 c0x0000 (---------------) + I edu 0x0021e283, // n0x1bd6 c0x0000 (---------------) + I gov 0x0023fa03, // n0x1bd7 c0x0000 (---------------) + I mil 0x002170c3, // n0x1bd8 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1bd9 c0x0000 (---------------) + I org 0x00201482, // n0x1bda c0x0000 (---------------) + I av 0x002791c3, // n0x1bdb c0x0000 (---------------) + I bbs 0x00251643, // n0x1bdc c0x0000 (---------------) + I bel 0x00310603, // n0x1bdd c0x0000 (---------------) + I biz 0x51622ac3, // n0x1bde c0x0145 (n0x1bef-n0x1bf0) + I com 0x0022fb02, // n0x1bdf c0x0000 (---------------) + I dr 0x002d75c3, // n0x1be0 c0x0000 (---------------) + I edu 0x002012c3, // n0x1be1 c0x0000 (---------------) + I gen 0x0021e283, // n0x1be2 c0x0000 (---------------) + I gov 0x00200304, // n0x1be3 c0x0000 (---------------) + I info 0x00312503, // n0x1be4 c0x0000 (---------------) + I k12 0x0023df03, // n0x1be5 c0x0000 (---------------) + I kep 0x0023fa03, // n0x1be6 c0x0000 (---------------) + I mil 0x00298944, // n0x1be7 c0x0000 (---------------) + I name 0x51a1c742, // n0x1be8 c0x0146 (n0x1bf0-n0x1bf1) + I nc 0x002170c3, // n0x1be9 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1bea c0x0000 (---------------) + I org 0x00218943, // n0x1beb c0x0000 (---------------) + I pol 0x0022ba83, // n0x1bec c0x0000 (---------------) + I tel 0x0020bf42, // n0x1bed c0x0000 (---------------) + I tv 0x00219fc3, // n0x1bee c0x0000 (---------------) + I web 0x000e4188, // n0x1bef c0x0000 (---------------) + blogspot 0x0021e283, // n0x1bf0 c0x0000 (---------------) + I gov 0x002751c4, // n0x1bf1 c0x0000 (---------------) + I aero 0x00310603, // n0x1bf2 c0x0000 (---------------) + I biz 0x00200742, // n0x1bf3 c0x0000 (---------------) + I co 0x00222ac3, // n0x1bf4 c0x0000 (---------------) + I com 0x00228d44, // n0x1bf5 c0x0000 (---------------) + I coop 0x002d75c3, // n0x1bf6 c0x0000 (---------------) + I edu 0x0021e283, // n0x1bf7 c0x0000 (---------------) + I gov 0x00200304, // n0x1bf8 c0x0000 (---------------) + I info 0x00238c03, // n0x1bf9 c0x0000 (---------------) + I int 0x002a5d04, // n0x1bfa c0x0000 (---------------) + I jobs 0x00203604, // n0x1bfb c0x0000 (---------------) + I mobi 0x002bd646, // n0x1bfc c0x0000 (---------------) + I museum 0x00298944, // n0x1bfd c0x0000 (---------------) + I name 0x002170c3, // n0x1bfe c0x0000 (---------------) + I net 0x0021dcc3, // n0x1bff c0x0000 (---------------) + I org 0x00218243, // n0x1c00 c0x0000 (---------------) + I pro 0x0027f186, // n0x1c01 c0x0000 (---------------) + I travel 0x00041e4b, // n0x1c02 c0x0000 (---------------) + better-than 0x00009ac6, // n0x1c03 c0x0000 (---------------) + dyndns 0x00019e0a, // n0x1c04 c0x0000 (---------------) + on-the-web 0x00171e8a, // n0x1c05 c0x0000 (---------------) + worse-than 0x000e4188, // n0x1c06 c0x0000 (---------------) + blogspot 0x002752c4, // n0x1c07 c0x0000 (---------------) + I club 0x00222ac3, // n0x1c08 c0x0000 (---------------) + I com 0x003105c4, // n0x1c09 c0x0000 (---------------) + I ebiz 0x002d75c3, // n0x1c0a c0x0000 (---------------) + I edu 0x00212084, // n0x1c0b c0x0000 (---------------) + I game 0x0021e283, // n0x1c0c c0x0000 (---------------) + I gov 0x00300b83, // n0x1c0d c0x0000 (---------------) + I idv 0x0023fa03, // n0x1c0e c0x0000 (---------------) + I mil 0x002170c3, // n0x1c0f c0x0000 (---------------) + I net 0x0021dcc3, // n0x1c10 c0x0000 (---------------) + I org 0x0030d70b, // n0x1c11 c0x0000 (---------------) + I xn--czrw28b 0x003867ca, // n0x1c12 c0x0000 (---------------) + I xn--uc0atv 0x0039604c, // n0x1c13 c0x0000 (---------------) + I xn--zf0ao64a 0x00201e82, // n0x1c14 c0x0000 (---------------) + I ac 0x00200742, // n0x1c15 c0x0000 (---------------) + I co 0x00202342, // n0x1c16 c0x0000 (---------------) + I go 0x00294945, // n0x1c17 c0x0000 (---------------) + I hotel 0x00200304, // n0x1c18 c0x0000 (---------------) + I info 0x00208942, // n0x1c19 c0x0000 (---------------) + I me 0x0023fa03, // n0x1c1a c0x0000 (---------------) + I mil 0x00203604, // n0x1c1b c0x0000 (---------------) + I mobi 0x00201082, // n0x1c1c c0x0000 (---------------) + I ne 0x00200c42, // n0x1c1d c0x0000 (---------------) + I or 0x00200982, // n0x1c1e c0x0000 (---------------) + I sc 0x0020bf42, // n0x1c1f c0x0000 (---------------) + I tv 0x0029d289, // n0x1c20 c0x0000 (---------------) + I cherkassy 0x0028e908, // n0x1c21 c0x0000 (---------------) + I cherkasy 0x00259889, // n0x1c22 c0x0000 (---------------) + I chernigov 0x0025f489, // n0x1c23 c0x0000 (---------------) + I chernihiv 0x0026b44a, // n0x1c24 c0x0000 (---------------) + I chernivtsi 0x00367e8a, // n0x1c25 c0x0000 (---------------) + I chernovtsy 0x00201782, // n0x1c26 c0x0000 (---------------) + I ck 0x002211c2, // n0x1c27 c0x0000 (---------------) + I cn 0x00200742, // n0x1c28 c0x0000 (---------------) + I co 0x00222ac3, // n0x1c29 c0x0000 (---------------) + I com 0x0020c502, // n0x1c2a c0x0000 (---------------) + I cr 0x00231c86, // n0x1c2b c0x0000 (---------------) + I crimea 0x0033f802, // n0x1c2c c0x0000 (---------------) + I cv 0x00209b82, // n0x1c2d c0x0000 (---------------) + I dn 0x0036ad4e, // n0x1c2e c0x0000 (---------------) + I dnepropetrovsk 0x0025ec0e, // n0x1c2f c0x0000 (---------------) + I dnipropetrovsk 0x0026b2c7, // n0x1c30 c0x0000 (---------------) + I dominic 0x003409c7, // n0x1c31 c0x0000 (---------------) + I donetsk 0x00238b42, // n0x1c32 c0x0000 (---------------) + I dp 0x002d75c3, // n0x1c33 c0x0000 (---------------) + I edu 0x0021e283, // n0x1c34 c0x0000 (---------------) + I gov 0x00239ec2, // n0x1c35 c0x0000 (---------------) + I if 0x00200242, // n0x1c36 c0x0000 (---------------) + I in 0x0022cf4f, // n0x1c37 c0x0000 (---------------) + I ivano-frankivsk 0x002176c2, // n0x1c38 c0x0000 (---------------) + I kh 0x00244d07, // n0x1c39 c0x0000 (---------------) + I kharkiv 0x0024cb07, // n0x1c3a c0x0000 (---------------) + I kharkov 0x00250087, // n0x1c3b c0x0000 (---------------) + I kherson 0x0025304c, // n0x1c3c c0x0000 (---------------) + I khmelnitskiy 0x002581cc, // n0x1c3d c0x0000 (---------------) + I khmelnytskyi 0x0037aac4, // n0x1c3e c0x0000 (---------------) + I kiev 0x00254bca, // n0x1c3f c0x0000 (---------------) + I kirovograd 0x00268d82, // n0x1c40 c0x0000 (---------------) + I km 0x002034c2, // n0x1c41 c0x0000 (---------------) + I kr 0x0029ed84, // n0x1c42 c0x0000 (---------------) + I krym 0x00238082, // n0x1c43 c0x0000 (---------------) + I ks 0x002aa8c2, // n0x1c44 c0x0000 (---------------) + I kv 0x00258404, // n0x1c45 c0x0000 (---------------) + I kyiv 0x0020e4c2, // n0x1c46 c0x0000 (---------------) + I lg 0x00205ec2, // n0x1c47 c0x0000 (---------------) + I lt 0x003054c7, // n0x1c48 c0x0000 (---------------) + I lugansk 0x002e6745, // n0x1c49 c0x0000 (---------------) + I lutsk 0x00227f02, // n0x1c4a c0x0000 (---------------) + I lv 0x0022cec4, // n0x1c4b c0x0000 (---------------) + I lviv 0x00356d82, // n0x1c4c c0x0000 (---------------) + I mk 0x002f28c8, // n0x1c4d c0x0000 (---------------) + I mykolaiv 0x002170c3, // n0x1c4e c0x0000 (---------------) + I net 0x00342248, // n0x1c4f c0x0000 (---------------) + I nikolaev 0x00200782, // n0x1c50 c0x0000 (---------------) + I od 0x00227505, // n0x1c51 c0x0000 (---------------) + I odesa 0x0035fa46, // n0x1c52 c0x0000 (---------------) + I odessa 0x0021dcc3, // n0x1c53 c0x0000 (---------------) + I org 0x00201e02, // n0x1c54 c0x0000 (---------------) + I pl 0x002c8f07, // n0x1c55 c0x0000 (---------------) + I poltava 0x00207742, // n0x1c56 c0x0000 (---------------) + I pp 0x002cba85, // n0x1c57 c0x0000 (---------------) + I rivne 0x00208085, // n0x1c58 c0x0000 (---------------) + I rovno 0x00211fc2, // n0x1c59 c0x0000 (---------------) + I rv 0x002046c2, // n0x1c5a c0x0000 (---------------) + I sb 0x0035e2ca, // n0x1c5b c0x0000 (---------------) + I sebastopol 0x0024688a, // n0x1c5c c0x0000 (---------------) + I sevastopol 0x0023f582, // n0x1c5d c0x0000 (---------------) + I sm 0x00308004, // n0x1c5e c0x0000 (---------------) + I sumy 0x00203202, // n0x1c5f c0x0000 (---------------) + I te 0x0036c988, // n0x1c60 c0x0000 (---------------) + I ternopil 0x002018c2, // n0x1c61 c0x0000 (---------------) + I uz 0x0036a1c8, // n0x1c62 c0x0000 (---------------) + I uzhgorod 0x002dc087, // n0x1c63 c0x0000 (---------------) + I vinnica 0x002dc4c9, // n0x1c64 c0x0000 (---------------) + I vinnytsia 0x00208102, // n0x1c65 c0x0000 (---------------) + I vn 0x002e1c05, // n0x1c66 c0x0000 (---------------) + I volyn 0x0028edc5, // n0x1c67 c0x0000 (---------------) + I yalta 0x002b214b, // n0x1c68 c0x0000 (---------------) + I zaporizhzhe 0x002b2b8c, // n0x1c69 c0x0000 (---------------) + I zaporizhzhia 0x00220408, // n0x1c6a c0x0000 (---------------) + I zhitomir 0x002e1fc8, // n0x1c6b c0x0000 (---------------) + I zhytomyr 0x002c2042, // n0x1c6c c0x0000 (---------------) + I zp 0x0020fa82, // n0x1c6d c0x0000 (---------------) + I zt 0x00201e82, // n0x1c6e c0x0000 (---------------) + I ac 0x000e4188, // n0x1c6f c0x0000 (---------------) + blogspot 0x00200742, // n0x1c70 c0x0000 (---------------) + I co 0x00222ac3, // n0x1c71 c0x0000 (---------------) + I com 0x00202342, // n0x1c72 c0x0000 (---------------) + I go 0x00201082, // n0x1c73 c0x0000 (---------------) + I ne 0x00200c42, // n0x1c74 c0x0000 (---------------) + I or 0x0021dcc3, // n0x1c75 c0x0000 (---------------) + I org 0x00200982, // n0x1c76 c0x0000 (---------------) + I sc 0x00201e82, // n0x1c77 c0x0000 (---------------) + I ac 0x53a00742, // n0x1c78 c0x014e (n0x1c82-n0x1c83) + I co 0x53e1e283, // n0x1c79 c0x014f (n0x1c83-n0x1c84) + I gov 0x003413c3, // n0x1c7a c0x0000 (---------------) + I ltd 0x00208942, // n0x1c7b c0x0000 (---------------) + I me 0x002170c3, // n0x1c7c c0x0000 (---------------) + I net 0x002037c3, // n0x1c7d c0x0000 (---------------) + I nhs 0x0021dcc3, // n0x1c7e c0x0000 (---------------) + I org 0x002c65c3, // n0x1c7f c0x0000 (---------------) + I plc 0x00218946, // n0x1c80 c0x0000 (---------------) + I police 0x01606103, // n0x1c81 c0x0005 (---------------)* o I sch 0x000e4188, // n0x1c82 c0x0000 (---------------) + blogspot 0x00043bc7, // n0x1c83 c0x0000 (---------------) + service 0x54601a42, // n0x1c84 c0x0151 (n0x1cc3-n0x1cc6) + I ak 0x54a00882, // n0x1c85 c0x0152 (n0x1cc6-n0x1cc9) + I al 0x54e00602, // n0x1c86 c0x0153 (n0x1cc9-n0x1ccc) + I ar 0x55200182, // n0x1c87 c0x0154 (n0x1ccc-n0x1ccf) + I as 0x55608cc2, // n0x1c88 c0x0155 (n0x1ccf-n0x1cd2) + I az 0x55a055c2, // n0x1c89 c0x0156 (n0x1cd2-n0x1cd5) + I ca 0x55e00742, // n0x1c8a c0x0157 (n0x1cd5-n0x1cd8) + I co 0x56223d82, // n0x1c8b c0x0158 (n0x1cd8-n0x1cdb) + I ct 0x56616e02, // n0x1c8c c0x0159 (n0x1cdb-n0x1cde) + I dc 0x56a006c2, // n0x1c8d c0x015a (n0x1cde-n0x1ce1) + I de 0x0025ec03, // n0x1c8e c0x0000 (---------------) + I dni 0x0020c743, // n0x1c8f c0x0000 (---------------) + I fed 0x56e39b02, // n0x1c90 c0x015b (n0x1ce1-n0x1ce4) + I fl 0x57201602, // n0x1c91 c0x015c (n0x1ce4-n0x1ce7) + I ga 0x57629702, // n0x1c92 c0x015d (n0x1ce7-n0x1cea) + I gu 0x57a00202, // n0x1c93 c0x015e (n0x1cea-n0x1cec) + I hi 0x57e00482, // n0x1c94 c0x015f (n0x1cec-n0x1cef) + I ia 0x58206202, // n0x1c95 c0x0160 (n0x1cef-n0x1cf2) + I id 0x586036c2, // n0x1c96 c0x0161 (n0x1cf2-n0x1cf5) + I il 0x58a00242, // n0x1c97 c0x0162 (n0x1cf5-n0x1cf8) + I in 0x000aa785, // n0x1c98 c0x0000 (---------------) + is-by 0x00209883, // n0x1c99 c0x0000 (---------------) + I isa 0x00394c44, // n0x1c9a c0x0000 (---------------) + I kids 0x58e38082, // n0x1c9b c0x0163 (n0x1cf8-n0x1cfb) + I ks 0x59229082, // n0x1c9c c0x0164 (n0x1cfb-n0x1cfe) + I ky 0x59601e42, // n0x1c9d c0x0165 (n0x1cfe-n0x1d01) + I la 0x0006700b, // n0x1c9e c0x0000 (---------------) + land-4-sale 0x59a04302, // n0x1c9f c0x0166 (n0x1d01-n0x1d04) + I ma 0x5a238602, // n0x1ca0 c0x0168 (n0x1d07-n0x1d0a) + I md 0x5a608942, // n0x1ca1 c0x0169 (n0x1d0a-n0x1d0d) + I me 0x5aa04802, // n0x1ca2 c0x016a (n0x1d0d-n0x1d10) + I mi 0x5ae17082, // n0x1ca3 c0x016b (n0x1d10-n0x1d13) + I mn 0x5b203602, // n0x1ca4 c0x016c (n0x1d13-n0x1d16) + I mo 0x5b609282, // n0x1ca5 c0x016d (n0x1d16-n0x1d19) + I ms 0x5ba59642, // n0x1ca6 c0x016e (n0x1d19-n0x1d1c) + I mt 0x5be1c742, // n0x1ca7 c0x016f (n0x1d1c-n0x1d1f) + I nc 0x5c208f42, // n0x1ca8 c0x0170 (n0x1d1f-n0x1d21) + I nd 0x5c601082, // n0x1ca9 c0x0171 (n0x1d21-n0x1d24) + I ne 0x5ca037c2, // n0x1caa c0x0172 (n0x1d24-n0x1d27) + I nh 0x5ce02942, // n0x1cab c0x0173 (n0x1d27-n0x1d2a) + I nj 0x5d233c42, // n0x1cac c0x0174 (n0x1d2a-n0x1d2d) + I nm 0x002c55c3, // n0x1cad c0x0000 (---------------) + I nsn 0x5d608802, // n0x1cae c0x0175 (n0x1d2d-n0x1d30) + I nv 0x5da108c2, // n0x1caf c0x0176 (n0x1d30-n0x1d33) + I ny 0x5de051c2, // n0x1cb0 c0x0177 (n0x1d33-n0x1d36) + I oh 0x5e201bc2, // n0x1cb1 c0x0178 (n0x1d36-n0x1d39) + I ok 0x5e600c42, // n0x1cb2 c0x0179 (n0x1d39-n0x1d3c) + I or 0x5ea052c2, // n0x1cb3 c0x017a (n0x1d3c-n0x1d3f) + I pa 0x5ee18242, // n0x1cb4 c0x017b (n0x1d3f-n0x1d42) + I pr 0x5f202842, // n0x1cb5 c0x017c (n0x1d42-n0x1d45) + I ri 0x5f600982, // n0x1cb6 c0x017d (n0x1d45-n0x1d48) + I sc 0x5fa4f842, // n0x1cb7 c0x017e (n0x1d48-n0x1d4a) + I sd 0x000d044c, // n0x1cb8 c0x0000 (---------------) + stuff-4-sale 0x5fe1d1c2, // n0x1cb9 c0x017f (n0x1d4a-n0x1d4d) + I tn 0x60225242, // n0x1cba c0x0180 (n0x1d4d-n0x1d50) + I tx 0x60600102, // n0x1cbb c0x0181 (n0x1d50-n0x1d53) + I ut 0x60a013c2, // n0x1cbc c0x0182 (n0x1d53-n0x1d56) + I va 0x60e13602, // n0x1cbd c0x0183 (n0x1d56-n0x1d59) + I vi 0x6121e302, // n0x1cbe c0x0184 (n0x1d59-n0x1d5c) + I vt 0x61602542, // n0x1cbf c0x0185 (n0x1d5c-n0x1d5f) + I wa 0x61a05502, // n0x1cc0 c0x0186 (n0x1d5f-n0x1d62) + I wi 0x61e63902, // n0x1cc1 c0x0187 (n0x1d62-n0x1d63) + I wv 0x62237f82, // n0x1cc2 c0x0188 (n0x1d63-n0x1d66) + I wy 0x0021aa82, // n0x1cc3 c0x0000 (---------------) + I cc 0x00312503, // n0x1cc4 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cc5 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cc6 c0x0000 (---------------) + I cc 0x00312503, // n0x1cc7 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cc8 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cc9 c0x0000 (---------------) + I cc 0x00312503, // n0x1cca c0x0000 (---------------) + I k12 0x00273c43, // n0x1ccb c0x0000 (---------------) + I lib 0x0021aa82, // n0x1ccc c0x0000 (---------------) + I cc 0x00312503, // n0x1ccd c0x0000 (---------------) + I k12 0x00273c43, // n0x1cce c0x0000 (---------------) + I lib 0x0021aa82, // n0x1ccf c0x0000 (---------------) + I cc 0x00312503, // n0x1cd0 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cd1 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cd2 c0x0000 (---------------) + I cc 0x00312503, // n0x1cd3 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cd4 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cd5 c0x0000 (---------------) + I cc 0x00312503, // n0x1cd6 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cd7 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cd8 c0x0000 (---------------) + I cc 0x00312503, // n0x1cd9 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cda c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cdb c0x0000 (---------------) + I cc 0x00312503, // n0x1cdc c0x0000 (---------------) + I k12 0x00273c43, // n0x1cdd c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cde c0x0000 (---------------) + I cc 0x00312503, // n0x1cdf c0x0000 (---------------) + I k12 0x00273c43, // n0x1ce0 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1ce1 c0x0000 (---------------) + I cc 0x00312503, // n0x1ce2 c0x0000 (---------------) + I k12 0x00273c43, // n0x1ce3 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1ce4 c0x0000 (---------------) + I cc 0x00312503, // n0x1ce5 c0x0000 (---------------) + I k12 0x00273c43, // n0x1ce6 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1ce7 c0x0000 (---------------) + I cc 0x00312503, // n0x1ce8 c0x0000 (---------------) + I k12 0x00273c43, // n0x1ce9 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cea c0x0000 (---------------) + I cc 0x00273c43, // n0x1ceb c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cec c0x0000 (---------------) + I cc 0x00312503, // n0x1ced c0x0000 (---------------) + I k12 0x00273c43, // n0x1cee c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cef c0x0000 (---------------) + I cc 0x00312503, // n0x1cf0 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cf1 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cf2 c0x0000 (---------------) + I cc 0x00312503, // n0x1cf3 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cf4 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cf5 c0x0000 (---------------) + I cc 0x00312503, // n0x1cf6 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cf7 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cf8 c0x0000 (---------------) + I cc 0x00312503, // n0x1cf9 c0x0000 (---------------) + I k12 0x00273c43, // n0x1cfa c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cfb c0x0000 (---------------) + I cc 0x00312503, // n0x1cfc c0x0000 (---------------) + I k12 0x00273c43, // n0x1cfd c0x0000 (---------------) + I lib 0x0021aa82, // n0x1cfe c0x0000 (---------------) + I cc 0x00312503, // n0x1cff c0x0000 (---------------) + I k12 0x00273c43, // n0x1d00 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d01 c0x0000 (---------------) + I cc 0x59f12503, // n0x1d02 c0x0167 (n0x1d04-n0x1d07) + I k12 0x00273c43, // n0x1d03 c0x0000 (---------------) + I lib 0x002e8ec4, // n0x1d04 c0x0000 (---------------) + I chtr 0x0028e806, // n0x1d05 c0x0000 (---------------) + I paroch 0x002ce243, // n0x1d06 c0x0000 (---------------) + I pvt 0x0021aa82, // n0x1d07 c0x0000 (---------------) + I cc 0x00312503, // n0x1d08 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d09 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d0a c0x0000 (---------------) + I cc 0x00312503, // n0x1d0b c0x0000 (---------------) + I k12 0x00273c43, // n0x1d0c c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d0d c0x0000 (---------------) + I cc 0x00312503, // n0x1d0e c0x0000 (---------------) + I k12 0x00273c43, // n0x1d0f c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d10 c0x0000 (---------------) + I cc 0x00312503, // n0x1d11 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d12 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d13 c0x0000 (---------------) + I cc 0x00312503, // n0x1d14 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d15 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d16 c0x0000 (---------------) + I cc 0x00312503, // n0x1d17 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d18 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d19 c0x0000 (---------------) + I cc 0x00312503, // n0x1d1a c0x0000 (---------------) + I k12 0x00273c43, // n0x1d1b c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d1c c0x0000 (---------------) + I cc 0x00312503, // n0x1d1d c0x0000 (---------------) + I k12 0x00273c43, // n0x1d1e c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d1f c0x0000 (---------------) + I cc 0x00273c43, // n0x1d20 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d21 c0x0000 (---------------) + I cc 0x00312503, // n0x1d22 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d23 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d24 c0x0000 (---------------) + I cc 0x00312503, // n0x1d25 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d26 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d27 c0x0000 (---------------) + I cc 0x00312503, // n0x1d28 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d29 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d2a c0x0000 (---------------) + I cc 0x00312503, // n0x1d2b c0x0000 (---------------) + I k12 0x00273c43, // n0x1d2c c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d2d c0x0000 (---------------) + I cc 0x00312503, // n0x1d2e c0x0000 (---------------) + I k12 0x00273c43, // n0x1d2f c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d30 c0x0000 (---------------) + I cc 0x00312503, // n0x1d31 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d32 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d33 c0x0000 (---------------) + I cc 0x00312503, // n0x1d34 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d35 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d36 c0x0000 (---------------) + I cc 0x00312503, // n0x1d37 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d38 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d39 c0x0000 (---------------) + I cc 0x00312503, // n0x1d3a c0x0000 (---------------) + I k12 0x00273c43, // n0x1d3b c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d3c c0x0000 (---------------) + I cc 0x00312503, // n0x1d3d c0x0000 (---------------) + I k12 0x00273c43, // n0x1d3e c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d3f c0x0000 (---------------) + I cc 0x00312503, // n0x1d40 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d41 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d42 c0x0000 (---------------) + I cc 0x00312503, // n0x1d43 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d44 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d45 c0x0000 (---------------) + I cc 0x00312503, // n0x1d46 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d47 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d48 c0x0000 (---------------) + I cc 0x00273c43, // n0x1d49 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d4a c0x0000 (---------------) + I cc 0x00312503, // n0x1d4b c0x0000 (---------------) + I k12 0x00273c43, // n0x1d4c c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d4d c0x0000 (---------------) + I cc 0x00312503, // n0x1d4e c0x0000 (---------------) + I k12 0x00273c43, // n0x1d4f c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d50 c0x0000 (---------------) + I cc 0x00312503, // n0x1d51 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d52 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d53 c0x0000 (---------------) + I cc 0x00312503, // n0x1d54 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d55 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d56 c0x0000 (---------------) + I cc 0x00312503, // n0x1d57 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d58 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d59 c0x0000 (---------------) + I cc 0x00312503, // n0x1d5a c0x0000 (---------------) + I k12 0x00273c43, // n0x1d5b c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d5c c0x0000 (---------------) + I cc 0x00312503, // n0x1d5d c0x0000 (---------------) + I k12 0x00273c43, // n0x1d5e c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d5f c0x0000 (---------------) + I cc 0x00312503, // n0x1d60 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d61 c0x0000 (---------------) + I lib 0x0021aa82, // n0x1d62 c0x0000 (---------------) + I cc 0x0021aa82, // n0x1d63 c0x0000 (---------------) + I cc 0x00312503, // n0x1d64 c0x0000 (---------------) + I k12 0x00273c43, // n0x1d65 c0x0000 (---------------) + I lib 0x62a22ac3, // n0x1d66 c0x018a (n0x1d6c-n0x1d6d) + I com 0x002d75c3, // n0x1d67 c0x0000 (---------------) + I edu 0x0032b9c3, // n0x1d68 c0x0000 (---------------) + I gub 0x0023fa03, // n0x1d69 c0x0000 (---------------) + I mil 0x002170c3, // n0x1d6a c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d6b c0x0000 (---------------) + I org 0x000e4188, // n0x1d6c c0x0000 (---------------) + blogspot 0x00200742, // n0x1d6d c0x0000 (---------------) + I co 0x00222ac3, // n0x1d6e c0x0000 (---------------) + I com 0x002170c3, // n0x1d6f c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d70 c0x0000 (---------------) + I org 0x00222ac3, // n0x1d71 c0x0000 (---------------) + I com 0x002d75c3, // n0x1d72 c0x0000 (---------------) + I edu 0x0021e283, // n0x1d73 c0x0000 (---------------) + I gov 0x0023fa03, // n0x1d74 c0x0000 (---------------) + I mil 0x002170c3, // n0x1d75 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d76 c0x0000 (---------------) + I org 0x00246584, // n0x1d77 c0x0000 (---------------) + I arts 0x00200742, // n0x1d78 c0x0000 (---------------) + I co 0x00222ac3, // n0x1d79 c0x0000 (---------------) + I com 0x0023ee43, // n0x1d7a c0x0000 (---------------) + I e12 0x002d75c3, // n0x1d7b c0x0000 (---------------) + I edu 0x00238544, // n0x1d7c c0x0000 (---------------) + I firm 0x0034eb03, // n0x1d7d c0x0000 (---------------) + I gob 0x0021e283, // n0x1d7e c0x0000 (---------------) + I gov 0x00200304, // n0x1d7f c0x0000 (---------------) + I info 0x00238c03, // n0x1d80 c0x0000 (---------------) + I int 0x0023fa03, // n0x1d81 c0x0000 (---------------) + I mil 0x002170c3, // n0x1d82 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d83 c0x0000 (---------------) + I org 0x002e6343, // n0x1d84 c0x0000 (---------------) + I rec 0x002cf4c5, // n0x1d85 c0x0000 (---------------) + I store 0x0029d583, // n0x1d86 c0x0000 (---------------) + I tec 0x00219fc3, // n0x1d87 c0x0000 (---------------) + I web 0x00200742, // n0x1d88 c0x0000 (---------------) + I co 0x00222ac3, // n0x1d89 c0x0000 (---------------) + I com 0x00312503, // n0x1d8a c0x0000 (---------------) + I k12 0x002170c3, // n0x1d8b c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d8c c0x0000 (---------------) + I org 0x00201e82, // n0x1d8d c0x0000 (---------------) + I ac 0x00310603, // n0x1d8e c0x0000 (---------------) + I biz 0x000e4188, // n0x1d8f c0x0000 (---------------) + blogspot 0x00222ac3, // n0x1d90 c0x0000 (---------------) + I com 0x002d75c3, // n0x1d91 c0x0000 (---------------) + I edu 0x0021e283, // n0x1d92 c0x0000 (---------------) + I gov 0x00205e06, // n0x1d93 c0x0000 (---------------) + I health 0x00200304, // n0x1d94 c0x0000 (---------------) + I info 0x00238c03, // n0x1d95 c0x0000 (---------------) + I int 0x00298944, // n0x1d96 c0x0000 (---------------) + I name 0x002170c3, // n0x1d97 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d98 c0x0000 (---------------) + I org 0x00218243, // n0x1d99 c0x0000 (---------------) + I pro 0x00222ac3, // n0x1d9a c0x0000 (---------------) + I com 0x002d75c3, // n0x1d9b c0x0000 (---------------) + I edu 0x002170c3, // n0x1d9c c0x0000 (---------------) + I net 0x0021dcc3, // n0x1d9d c0x0000 (---------------) + I org 0x00222ac3, // n0x1d9e c0x0000 (---------------) + I com 0x00009ac6, // n0x1d9f c0x0000 (---------------) + dyndns 0x002d75c3, // n0x1da0 c0x0000 (---------------) + I edu 0x0021e283, // n0x1da1 c0x0000 (---------------) + I gov 0x00108086, // n0x1da2 c0x0000 (---------------) + mypets 0x002170c3, // n0x1da3 c0x0000 (---------------) + I net 0x0021dcc3, // n0x1da4 c0x0000 (---------------) + I org 0x002f1308, // n0x1da5 c0x0000 (---------------) + I xn--80au 0x002f5c09, // n0x1da6 c0x0000 (---------------) + I xn--90azh 0x00303289, // n0x1da7 c0x0000 (---------------) + I xn--c1avg 0x00312fc8, // n0x1da8 c0x0000 (---------------) + I xn--d1at 0x00362248, // n0x1da9 c0x0000 (---------------) + I xn--o1ac 0x00362249, // n0x1daa c0x0000 (---------------) + I xn--o1ach 0x00201e82, // n0x1dab c0x0000 (---------------) + I ac 0x00301306, // n0x1dac c0x0000 (---------------) + I agrica 0x00205e83, // n0x1dad c0x0000 (---------------) + I alt 0x65200742, // n0x1dae c0x0194 (n0x1dbc-n0x1dbd) + I co 0x002d75c3, // n0x1daf c0x0000 (---------------) + I edu 0x0021e283, // n0x1db0 c0x0000 (---------------) + I gov 0x002c6987, // n0x1db1 c0x0000 (---------------) + I grondar 0x00253883, // n0x1db2 c0x0000 (---------------) + I law 0x0023fa03, // n0x1db3 c0x0000 (---------------) + I mil 0x002170c3, // n0x1db4 c0x0000 (---------------) + I net 0x00202303, // n0x1db5 c0x0000 (---------------) + I ngo 0x00208b83, // n0x1db6 c0x0000 (---------------) + I nis 0x00207cc3, // n0x1db7 c0x0000 (---------------) + I nom 0x0021dcc3, // n0x1db8 c0x0000 (---------------) + I org 0x00235406, // n0x1db9 c0x0000 (---------------) + I school 0x00208902, // n0x1dba c0x0000 (---------------) + I tm 0x00219fc3, // n0x1dbb c0x0000 (---------------) + I web 0x000e4188, // n0x1dbc c0x0000 (---------------) + blogspot } // children is the list of nodes' children, the parent's wildcard bit and the // parent's node type. If a node has no children then their children index // will be in the range [0, 6), depending on the wildcard bit and node type. // // The layout within the uint32, from MSB to LSB, is: // [ 1 bits] unused // [ 1 bits] wildcard bit // [ 2 bits] node type // [14 bits] high nodes index (exclusive) of children // [14 bits] low nodes index (inclusive) of children var children = [...]uint32{ 0x00000000, // c0x0000 (---------------) + 0x10000000, // c0x0001 (---------------) ! 0x20000000, // c0x0002 (---------------) o 0x40000000, // c0x0003 (---------------)* + 0x50000000, // c0x0004 (---------------)* ! 0x60000000, // c0x0005 (---------------)* o 0x014fc539, // c0x0006 (n0x0539-n0x053f) + 0x0150053f, // c0x0007 (n0x053f-n0x0540) + 0x01520540, // c0x0008 (n0x0540-n0x0548) + 0x01684548, // c0x0009 (n0x0548-n0x05a1) + 0x016985a1, // c0x000a (n0x05a1-n0x05a6) + 0x016ac5a6, // c0x000b (n0x05a6-n0x05ab) + 0x016bc5ab, // c0x000c (n0x05ab-n0x05af) + 0x016d85af, // c0x000d (n0x05af-n0x05b6) + 0x016dc5b6, // c0x000e (n0x05b6-n0x05b7) + 0x016ec5b7, // c0x000f (n0x05b7-n0x05bb) + 0x017045bb, // c0x0010 (n0x05bb-n0x05c1) + 0x017285c1, // c0x0011 (n0x05c1-n0x05ca) + 0x0172c5ca, // c0x0012 (n0x05ca-n0x05cb) + 0x017445cb, // c0x0013 (n0x05cb-n0x05d1) + 0x017485d1, // c0x0014 (n0x05d1-n0x05d2) + 0x017645d2, // c0x0015 (n0x05d2-n0x05d9) + 0x017685d9, // c0x0016 (n0x05d9-n0x05da) + 0x017b05da, // c0x0017 (n0x05da-n0x05ec) + 0x017b45ec, // c0x0018 (n0x05ec-n0x05ed) + 0x017d45ed, // c0x0019 (n0x05ed-n0x05f5) + 0x017e85f5, // c0x001a (n0x05f5-n0x05fa) + 0x017ec5fa, // c0x001b (n0x05fa-n0x05fb) + 0x0181c5fb, // c0x001c (n0x05fb-n0x0607) + 0x01848607, // c0x001d (n0x0607-n0x0612) + 0x01870612, // c0x001e (n0x0612-n0x061c) + 0x0187861c, // c0x001f (n0x061c-n0x061e) + 0x0187c61e, // c0x0020 (n0x061e-n0x061f) + 0x0191061f, // c0x0021 (n0x061f-n0x0644) + 0x01924644, // c0x0022 (n0x0644-n0x0649) + 0x01938649, // c0x0023 (n0x0649-n0x064e) + 0x0195464e, // c0x0024 (n0x064e-n0x0655) + 0x01964655, // c0x0025 (n0x0655-n0x0659) + 0x01978659, // c0x0026 (n0x0659-n0x065e) + 0x0199c65e, // c0x0027 (n0x065e-n0x0667) + 0x01ab4667, // c0x0028 (n0x0667-n0x06ad) + 0x01ab86ad, // c0x0029 (n0x06ad-n0x06ae) + 0x01acc6ae, // c0x002a (n0x06ae-n0x06b3) + 0x01ae06b3, // c0x002b (n0x06b3-n0x06b8) + 0x01ae86b8, // c0x002c (n0x06b8-n0x06ba) + 0x01af86ba, // c0x002d (n0x06ba-n0x06be) + 0x01afc6be, // c0x002e (n0x06be-n0x06bf) + 0x01b146bf, // c0x002f (n0x06bf-n0x06c5) + 0x01b586c5, // c0x0030 (n0x06c5-n0x06d6) + 0x01b686d6, // c0x0031 (n0x06d6-n0x06da) + 0x01b6c6da, // c0x0032 (n0x06da-n0x06db) + 0x01b706db, // c0x0033 (n0x06db-n0x06dc) + 0x01b746dc, // c0x0034 (n0x06dc-n0x06dd) + 0x01bb06dd, // c0x0035 (n0x06dd-n0x06ec) + 0x61bb46ec, // c0x0036 (n0x06ec-n0x06ed)* o 0x01bc86ed, // c0x0037 (n0x06ed-n0x06f2) + 0x01bd86f2, // c0x0038 (n0x06f2-n0x06f6) + 0x01c8c6f6, // c0x0039 (n0x06f6-n0x0723) + 0x21c90723, // c0x003a (n0x0723-n0x0724) o 0x01c94724, // c0x003b (n0x0724-n0x0725) + 0x01c98725, // c0x003c (n0x0725-n0x0726) + 0x21c9c726, // c0x003d (n0x0726-n0x0727) o 0x21ca0727, // c0x003e (n0x0727-n0x0728) o 0x01cd4728, // c0x003f (n0x0728-n0x0735) + 0x01cd8735, // c0x0040 (n0x0735-n0x0736) + 0x01ffc736, // c0x0041 (n0x0736-n0x07ff) + 0x220447ff, // c0x0042 (n0x07ff-n0x0811) o 0x02068811, // c0x0043 (n0x0811-n0x081a) + 0x0207081a, // c0x0044 (n0x081a-n0x081c) + 0x2207481c, // c0x0045 (n0x081c-n0x081d) o 0x0209081d, // c0x0046 (n0x081d-n0x0824) + 0x020a8824, // c0x0047 (n0x0824-n0x082a) + 0x020ac82a, // c0x0048 (n0x082a-n0x082b) + 0x020bc82b, // c0x0049 (n0x082b-n0x082f) + 0x020c482f, // c0x004a (n0x082f-n0x0831) + 0x220f8831, // c0x004b (n0x0831-n0x083e) o 0x020fc83e, // c0x004c (n0x083e-n0x083f) + 0x0210083f, // c0x004d (n0x083f-n0x0840) + 0x02120840, // c0x004e (n0x0840-n0x0848) + 0x02124848, // c0x004f (n0x0848-n0x0849) + 0x02138849, // c0x0050 (n0x0849-n0x084e) + 0x0216084e, // c0x0051 (n0x084e-n0x0858) + 0x02180858, // c0x0052 (n0x0858-n0x0860) + 0x021b0860, // c0x0053 (n0x0860-n0x086c) + 0x021d886c, // c0x0054 (n0x086c-n0x0876) + 0x021dc876, // c0x0055 (n0x0876-n0x0877) + 0x02200877, // c0x0056 (n0x0877-n0x0880) + 0x02204880, // c0x0057 (n0x0880-n0x0881) + 0x02218881, // c0x0058 (n0x0881-n0x0886) + 0x0221c886, // c0x0059 (n0x0886-n0x0887) + 0x0223c887, // c0x005a (n0x0887-n0x088f) + 0x0224888f, // c0x005b (n0x088f-n0x0892) + 0x022a8892, // c0x005c (n0x0892-n0x08aa) + 0x022c48aa, // c0x005d (n0x08aa-n0x08b1) + 0x022d08b1, // c0x005e (n0x08b1-n0x08b4) + 0x022e48b4, // c0x005f (n0x08b4-n0x08b9) + 0x022fc8b9, // c0x0060 (n0x08b9-n0x08bf) + 0x023108bf, // c0x0061 (n0x08bf-n0x08c4) + 0x023288c4, // c0x0062 (n0x08c4-n0x08ca) + 0x023408ca, // c0x0063 (n0x08ca-n0x08d0) + 0x023588d0, // c0x0064 (n0x08d0-n0x08d6) + 0x023748d6, // c0x0065 (n0x08d6-n0x08dd) + 0x023808dd, // c0x0066 (n0x08dd-n0x08e0) + 0x023e08e0, // c0x0067 (n0x08e0-n0x08f8) + 0x023f88f8, // c0x0068 (n0x08f8-n0x08fe) + 0x0240c8fe, // c0x0069 (n0x08fe-n0x0903) + 0x02450903, // c0x006a (n0x0903-n0x0914) + 0x024d0914, // c0x006b (n0x0914-n0x0934) + 0x024fc934, // c0x006c (n0x0934-n0x093f) + 0x0250093f, // c0x006d (n0x093f-n0x0940) + 0x02508940, // c0x006e (n0x0940-n0x0942) + 0x6250c942, // c0x006f (n0x0942-n0x0943)* o 0x22510943, // c0x0070 (n0x0943-n0x0944) o 0x0252c944, // c0x0071 (n0x0944-n0x094b) + 0x0253494b, // c0x0072 (n0x094b-n0x094d) + 0x0256894d, // c0x0073 (n0x094d-n0x095a) + 0x0259095a, // c0x0074 (n0x095a-n0x0964) + 0x02594964, // c0x0075 (n0x0964-n0x0965) + 0x025a0965, // c0x0076 (n0x0965-n0x0968) + 0x025b8968, // c0x0077 (n0x0968-n0x096e) + 0x025dc96e, // c0x0078 (n0x096e-n0x0977) + 0x025fc977, // c0x0079 (n0x0977-n0x097f) + 0x02bc097f, // c0x007a (n0x097f-n0x0af0) + 0x02bccaf0, // c0x007b (n0x0af0-n0x0af3) + 0x02becaf3, // c0x007c (n0x0af3-n0x0afb) + 0x02da8afb, // c0x007d (n0x0afb-n0x0b6a) + 0x02e78b6a, // c0x007e (n0x0b6a-n0x0b9e) + 0x02ee8b9e, // c0x007f (n0x0b9e-n0x0bba) + 0x02f40bba, // c0x0080 (n0x0bba-n0x0bd0) + 0x03028bd0, // c0x0081 (n0x0bd0-n0x0c0a) + 0x03080c0a, // c0x0082 (n0x0c0a-n0x0c20) + 0x030bcc20, // c0x0083 (n0x0c20-n0x0c2f) + 0x031b8c2f, // c0x0084 (n0x0c2f-n0x0c6e) + 0x03284c6e, // c0x0085 (n0x0c6e-n0x0ca1) + 0x0331cca1, // c0x0086 (n0x0ca1-n0x0cc7) + 0x033accc7, // c0x0087 (n0x0cc7-n0x0ceb) + 0x03410ceb, // c0x0088 (n0x0ceb-n0x0d04) + 0x03648d04, // c0x0089 (n0x0d04-n0x0d92) + 0x03700d92, // c0x008a (n0x0d92-n0x0dc0) + 0x037ccdc0, // c0x008b (n0x0dc0-n0x0df3) + 0x03818df3, // c0x008c (n0x0df3-n0x0e06) + 0x038a0e06, // c0x008d (n0x0e06-n0x0e28) + 0x038dce28, // c0x008e (n0x0e28-n0x0e37) + 0x0392ce37, // c0x008f (n0x0e37-n0x0e4b) + 0x039a4e4b, // c0x0090 (n0x0e4b-n0x0e69) + 0x639a8e69, // c0x0091 (n0x0e69-n0x0e6a)* o 0x639ace6a, // c0x0092 (n0x0e6a-n0x0e6b)* o 0x639b0e6b, // c0x0093 (n0x0e6b-n0x0e6c)* o 0x03a2ce6c, // c0x0094 (n0x0e6c-n0x0e8b) + 0x03a94e8b, // c0x0095 (n0x0e8b-n0x0ea5) + 0x03b10ea5, // c0x0096 (n0x0ea5-n0x0ec4) + 0x03b88ec4, // c0x0097 (n0x0ec4-n0x0ee2) + 0x03c0cee2, // c0x0098 (n0x0ee2-n0x0f03) + 0x03c78f03, // c0x0099 (n0x0f03-n0x0f1e) + 0x03da4f1e, // c0x009a (n0x0f1e-n0x0f69) + 0x03dfcf69, // c0x009b (n0x0f69-n0x0f7f) + 0x63e00f7f, // c0x009c (n0x0f7f-n0x0f80)* o 0x03e98f80, // c0x009d (n0x0f80-n0x0fa6) + 0x03f20fa6, // c0x009e (n0x0fa6-n0x0fc8) + 0x03f6cfc8, // c0x009f (n0x0fc8-n0x0fdb) + 0x03fd4fdb, // c0x00a0 (n0x0fdb-n0x0ff5) + 0x0407cff5, // c0x00a1 (n0x0ff5-n0x101f) + 0x0414501f, // c0x00a2 (n0x101f-n0x1051) + 0x041ad051, // c0x00a3 (n0x1051-n0x106b) + 0x042c106b, // c0x00a4 (n0x106b-n0x10b0) + 0x642c50b0, // c0x00a5 (n0x10b0-n0x10b1)* o 0x642c90b1, // c0x00a6 (n0x10b1-n0x10b2)* o 0x043250b2, // c0x00a7 (n0x10b2-n0x10c9) + 0x043810c9, // c0x00a8 (n0x10c9-n0x10e0) + 0x044110e0, // c0x00a9 (n0x10e0-n0x1104) + 0x0448d104, // c0x00aa (n0x1104-n0x1123) + 0x044d1123, // c0x00ab (n0x1123-n0x1134) + 0x045b5134, // c0x00ac (n0x1134-n0x116d) + 0x045e916d, // c0x00ad (n0x116d-n0x117a) + 0x0464917a, // c0x00ae (n0x117a-n0x1192) + 0x046bd192, // c0x00af (n0x1192-n0x11af) + 0x047451af, // c0x00b0 (n0x11af-n0x11d1) + 0x047851d1, // c0x00b1 (n0x11d1-n0x11e1) + 0x047f51e1, // c0x00b2 (n0x11e1-n0x11fd) + 0x647f91fd, // c0x00b3 (n0x11fd-n0x11fe)* o 0x647fd1fe, // c0x00b4 (n0x11fe-n0x11ff)* o 0x248011ff, // c0x00b5 (n0x11ff-n0x1200) o 0x04819200, // c0x00b6 (n0x1200-n0x1206) + 0x04835206, // c0x00b7 (n0x1206-n0x120d) + 0x0487920d, // c0x00b8 (n0x120d-n0x121e) + 0x0488921e, // c0x00b9 (n0x121e-n0x1222) + 0x048a1222, // c0x00ba (n0x1222-n0x1228) + 0x04919228, // c0x00bb (n0x1228-n0x1246) + 0x0492d246, // c0x00bc (n0x1246-n0x124b) + 0x0494524b, // c0x00bd (n0x124b-n0x1251) + 0x04969251, // c0x00be (n0x1251-n0x125a) + 0x0497d25a, // c0x00bf (n0x125a-n0x125f) + 0x0499525f, // c0x00c0 (n0x125f-n0x1265) + 0x04999265, // c0x00c1 (n0x1265-n0x1266) + 0x049d5266, // c0x00c2 (n0x1266-n0x1275) + 0x049e9275, // c0x00c3 (n0x1275-n0x127a) + 0x049f127a, // c0x00c4 (n0x127a-n0x127c) + 0x049f927c, // c0x00c5 (n0x127c-n0x127e) + 0x049fd27e, // c0x00c6 (n0x127e-n0x127f) + 0x04a2127f, // c0x00c7 (n0x127f-n0x1288) + 0x04a45288, // c0x00c8 (n0x1288-n0x1291) + 0x04a5d291, // c0x00c9 (n0x1291-n0x1297) + 0x04a65297, // c0x00ca (n0x1297-n0x1299) + 0x04a69299, // c0x00cb (n0x1299-n0x129a) + 0x04a8929a, // c0x00cc (n0x129a-n0x12a2) + 0x04aa92a2, // c0x00cd (n0x12a2-n0x12aa) + 0x04ac92aa, // c0x00ce (n0x12aa-n0x12b2) + 0x04ae52b2, // c0x00cf (n0x12b2-n0x12b9) + 0x04af52b9, // c0x00d0 (n0x12b9-n0x12bd) + 0x04b092bd, // c0x00d1 (n0x12bd-n0x12c2) + 0x04b112c2, // c0x00d2 (n0x12c2-n0x12c4) + 0x04b252c4, // c0x00d3 (n0x12c4-n0x12c9) + 0x04b352c9, // c0x00d4 (n0x12c9-n0x12cd) + 0x04b392cd, // c0x00d5 (n0x12cd-n0x12ce) + 0x04b552ce, // c0x00d6 (n0x12ce-n0x12d5) + 0x053e52d5, // c0x00d7 (n0x12d5-n0x14f9) + 0x0541d4f9, // c0x00d8 (n0x14f9-n0x1507) + 0x05449507, // c0x00d9 (n0x1507-n0x1512) + 0x05461512, // c0x00da (n0x1512-n0x1518) + 0x05481518, // c0x00db (n0x1518-n0x1520) + 0x65485520, // c0x00dc (n0x1520-n0x1521)* o 0x054c9521, // c0x00dd (n0x1521-n0x1532) + 0x054d1532, // c0x00de (n0x1532-n0x1534) + 0x254d5534, // c0x00df (n0x1534-n0x1535) o 0x254d9535, // c0x00e0 (n0x1535-n0x1536) o 0x054dd536, // c0x00e1 (n0x1536-n0x1537) + 0x055a1537, // c0x00e2 (n0x1537-n0x1568) + 0x255a5568, // c0x00e3 (n0x1568-n0x1569) o 0x255ad569, // c0x00e4 (n0x1569-n0x156b) o 0x255b556b, // c0x00e5 (n0x156b-n0x156d) o 0x255c156d, // c0x00e6 (n0x156d-n0x1570) o 0x055e9570, // c0x00e7 (n0x1570-n0x157a) + 0x0560d57a, // c0x00e8 (n0x157a-n0x1583) + 0x05611583, // c0x00e9 (n0x1583-n0x1584) + 0x0561d584, // c0x00ea (n0x1584-n0x1587) + 0x06175587, // c0x00eb (n0x1587-n0x185d) + 0x0617985d, // c0x00ec (n0x185d-n0x185e) + 0x0617d85e, // c0x00ed (n0x185e-n0x185f) + 0x2618185f, // c0x00ee (n0x185f-n0x1860) o 0x06185860, // c0x00ef (n0x1860-n0x1861) + 0x26189861, // c0x00f0 (n0x1861-n0x1862) o 0x0618d862, // c0x00f1 (n0x1862-n0x1863) + 0x26199863, // c0x00f2 (n0x1863-n0x1866) o 0x0619d866, // c0x00f3 (n0x1866-n0x1867) + 0x061a1867, // c0x00f4 (n0x1867-n0x1868) + 0x261a5868, // c0x00f5 (n0x1868-n0x1869) o 0x061a9869, // c0x00f6 (n0x1869-n0x186a) + 0x261b186a, // c0x00f7 (n0x186a-n0x186c) o 0x061b586c, // c0x00f8 (n0x186c-n0x186d) + 0x061b986d, // c0x00f9 (n0x186d-n0x186e) + 0x261c986e, // c0x00fa (n0x186e-n0x1872) o 0x061cd872, // c0x00fb (n0x1872-n0x1873) + 0x061d1873, // c0x00fc (n0x1873-n0x1874) + 0x061d5874, // c0x00fd (n0x1874-n0x1875) + 0x061d9875, // c0x00fe (n0x1875-n0x1876) + 0x261dd876, // c0x00ff (n0x1876-n0x1877) o 0x061e1877, // c0x0100 (n0x1877-n0x1878) + 0x061e5878, // c0x0101 (n0x1878-n0x1879) + 0x061e9879, // c0x0102 (n0x1879-n0x187a) + 0x061ed87a, // c0x0103 (n0x187a-n0x187b) + 0x261f587b, // c0x0104 (n0x187b-n0x187d) o 0x061f987d, // c0x0105 (n0x187d-n0x187e) + 0x061fd87e, // c0x0106 (n0x187e-n0x187f) + 0x0620187f, // c0x0107 (n0x187f-n0x1880) + 0x26205880, // c0x0108 (n0x1880-n0x1881) o 0x06209881, // c0x0109 (n0x1881-n0x1882) + 0x26211882, // c0x010a (n0x1882-n0x1884) o 0x26215884, // c0x010b (n0x1884-n0x1885) o 0x06231885, // c0x010c (n0x1885-n0x188c) + 0x0623d88c, // c0x010d (n0x188c-n0x188f) + 0x0627d88f, // c0x010e (n0x188f-n0x189f) + 0x0628189f, // c0x010f (n0x189f-n0x18a0) + 0x062a58a0, // c0x0110 (n0x18a0-n0x18a9) + 0x0638d8a9, // c0x0111 (n0x18a9-n0x18e3) + 0x263958e3, // c0x0112 (n0x18e3-n0x18e5) o 0x263998e5, // c0x0113 (n0x18e5-n0x18e6) o 0x2639d8e6, // c0x0114 (n0x18e6-n0x18e7) o 0x063a58e7, // c0x0115 (n0x18e7-n0x18e9) + 0x064818e9, // c0x0116 (n0x18e9-n0x1920) + 0x064ad920, // c0x0117 (n0x1920-n0x192b) + 0x064cd92b, // c0x0118 (n0x192b-n0x1933) + 0x064d9933, // c0x0119 (n0x1933-n0x1936) + 0x064f9936, // c0x011a (n0x1936-n0x193e) + 0x0653193e, // c0x011b (n0x193e-n0x194c) + 0x067c594c, // c0x011c (n0x194c-n0x19f1) + 0x068819f1, // c0x011d (n0x19f1-n0x1a20) + 0x06895a20, // c0x011e (n0x1a20-n0x1a25) + 0x068c9a25, // c0x011f (n0x1a25-n0x1a32) + 0x068e5a32, // c0x0120 (n0x1a32-n0x1a39) + 0x06901a39, // c0x0121 (n0x1a39-n0x1a40) + 0x06925a40, // c0x0122 (n0x1a40-n0x1a49) + 0x0693da49, // c0x0123 (n0x1a49-n0x1a4f) + 0x06959a4f, // c0x0124 (n0x1a4f-n0x1a56) + 0x0697da56, // c0x0125 (n0x1a56-n0x1a5f) + 0x0698da5f, // c0x0126 (n0x1a5f-n0x1a63) + 0x069bda63, // c0x0127 (n0x1a63-n0x1a6f) + 0x069d9a6f, // c0x0128 (n0x1a6f-n0x1a76) + 0x06be9a76, // c0x0129 (n0x1a76-n0x1afa) + 0x06c0dafa, // c0x012a (n0x1afa-n0x1b03) + 0x06c2db03, // c0x012b (n0x1b03-n0x1b0b) + 0x06c41b0b, // c0x012c (n0x1b0b-n0x1b10) + 0x06c55b10, // c0x012d (n0x1b10-n0x1b15) + 0x06c75b15, // c0x012e (n0x1b15-n0x1b1d) + 0x06d19b1d, // c0x012f (n0x1b1d-n0x1b46) + 0x06d35b46, // c0x0130 (n0x1b46-n0x1b4d) + 0x06d4db4d, // c0x0131 (n0x1b4d-n0x1b53) + 0x06d51b53, // c0x0132 (n0x1b53-n0x1b54) + 0x06d55b54, // c0x0133 (n0x1b54-n0x1b55) + 0x06d69b55, // c0x0134 (n0x1b55-n0x1b5a) + 0x06d89b5a, // c0x0135 (n0x1b5a-n0x1b62) + 0x06d95b62, // c0x0136 (n0x1b62-n0x1b65) + 0x06dc5b65, // c0x0137 (n0x1b65-n0x1b71) + 0x06e45b71, // c0x0138 (n0x1b71-n0x1b91) + 0x06e59b91, // c0x0139 (n0x1b91-n0x1b96) + 0x06e5db96, // c0x013a (n0x1b96-n0x1b97) + 0x06e75b97, // c0x013b (n0x1b97-n0x1b9d) + 0x06e81b9d, // c0x013c (n0x1b9d-n0x1ba0) + 0x06e85ba0, // c0x013d (n0x1ba0-n0x1ba1) + 0x06ea1ba1, // c0x013e (n0x1ba1-n0x1ba8) + 0x06eddba8, // c0x013f (n0x1ba8-n0x1bb7) + 0x06ee1bb7, // c0x0140 (n0x1bb7-n0x1bb8) + 0x06f01bb8, // c0x0141 (n0x1bb8-n0x1bc0) + 0x06f51bc0, // c0x0142 (n0x1bc0-n0x1bd4) + 0x06f69bd4, // c0x0143 (n0x1bd4-n0x1bda) + 0x06fbdbda, // c0x0144 (n0x1bda-n0x1bef) + 0x06fc1bef, // c0x0145 (n0x1bef-n0x1bf0) + 0x06fc5bf0, // c0x0146 (n0x1bf0-n0x1bf1) + 0x07009bf1, // c0x0147 (n0x1bf1-n0x1c02) + 0x07019c02, // c0x0148 (n0x1c02-n0x1c06) + 0x07051c06, // c0x0149 (n0x1c06-n0x1c14) + 0x07081c14, // c0x014a (n0x1c14-n0x1c20) + 0x071b9c20, // c0x014b (n0x1c20-n0x1c6e) + 0x071ddc6e, // c0x014c (n0x1c6e-n0x1c77) + 0x07209c77, // c0x014d (n0x1c77-n0x1c82) + 0x0720dc82, // c0x014e (n0x1c82-n0x1c83) + 0x07211c83, // c0x014f (n0x1c83-n0x1c84) + 0x0730dc84, // c0x0150 (n0x1c84-n0x1cc3) + 0x07319cc3, // c0x0151 (n0x1cc3-n0x1cc6) + 0x07325cc6, // c0x0152 (n0x1cc6-n0x1cc9) + 0x07331cc9, // c0x0153 (n0x1cc9-n0x1ccc) + 0x0733dccc, // c0x0154 (n0x1ccc-n0x1ccf) + 0x07349ccf, // c0x0155 (n0x1ccf-n0x1cd2) + 0x07355cd2, // c0x0156 (n0x1cd2-n0x1cd5) + 0x07361cd5, // c0x0157 (n0x1cd5-n0x1cd8) + 0x0736dcd8, // c0x0158 (n0x1cd8-n0x1cdb) + 0x07379cdb, // c0x0159 (n0x1cdb-n0x1cde) + 0x07385cde, // c0x015a (n0x1cde-n0x1ce1) + 0x07391ce1, // c0x015b (n0x1ce1-n0x1ce4) + 0x0739dce4, // c0x015c (n0x1ce4-n0x1ce7) + 0x073a9ce7, // c0x015d (n0x1ce7-n0x1cea) + 0x073b1cea, // c0x015e (n0x1cea-n0x1cec) + 0x073bdcec, // c0x015f (n0x1cec-n0x1cef) + 0x073c9cef, // c0x0160 (n0x1cef-n0x1cf2) + 0x073d5cf2, // c0x0161 (n0x1cf2-n0x1cf5) + 0x073e1cf5, // c0x0162 (n0x1cf5-n0x1cf8) + 0x073edcf8, // c0x0163 (n0x1cf8-n0x1cfb) + 0x073f9cfb, // c0x0164 (n0x1cfb-n0x1cfe) + 0x07405cfe, // c0x0165 (n0x1cfe-n0x1d01) + 0x07411d01, // c0x0166 (n0x1d01-n0x1d04) + 0x0741dd04, // c0x0167 (n0x1d04-n0x1d07) + 0x07429d07, // c0x0168 (n0x1d07-n0x1d0a) + 0x07435d0a, // c0x0169 (n0x1d0a-n0x1d0d) + 0x07441d0d, // c0x016a (n0x1d0d-n0x1d10) + 0x0744dd10, // c0x016b (n0x1d10-n0x1d13) + 0x07459d13, // c0x016c (n0x1d13-n0x1d16) + 0x07465d16, // c0x016d (n0x1d16-n0x1d19) + 0x07471d19, // c0x016e (n0x1d19-n0x1d1c) + 0x0747dd1c, // c0x016f (n0x1d1c-n0x1d1f) + 0x07485d1f, // c0x0170 (n0x1d1f-n0x1d21) + 0x07491d21, // c0x0171 (n0x1d21-n0x1d24) + 0x0749dd24, // c0x0172 (n0x1d24-n0x1d27) + 0x074a9d27, // c0x0173 (n0x1d27-n0x1d2a) + 0x074b5d2a, // c0x0174 (n0x1d2a-n0x1d2d) + 0x074c1d2d, // c0x0175 (n0x1d2d-n0x1d30) + 0x074cdd30, // c0x0176 (n0x1d30-n0x1d33) + 0x074d9d33, // c0x0177 (n0x1d33-n0x1d36) + 0x074e5d36, // c0x0178 (n0x1d36-n0x1d39) + 0x074f1d39, // c0x0179 (n0x1d39-n0x1d3c) + 0x074fdd3c, // c0x017a (n0x1d3c-n0x1d3f) + 0x07509d3f, // c0x017b (n0x1d3f-n0x1d42) + 0x07515d42, // c0x017c (n0x1d42-n0x1d45) + 0x07521d45, // c0x017d (n0x1d45-n0x1d48) + 0x07529d48, // c0x017e (n0x1d48-n0x1d4a) + 0x07535d4a, // c0x017f (n0x1d4a-n0x1d4d) + 0x07541d4d, // c0x0180 (n0x1d4d-n0x1d50) + 0x0754dd50, // c0x0181 (n0x1d50-n0x1d53) + 0x07559d53, // c0x0182 (n0x1d53-n0x1d56) + 0x07565d56, // c0x0183 (n0x1d56-n0x1d59) + 0x07571d59, // c0x0184 (n0x1d59-n0x1d5c) + 0x0757dd5c, // c0x0185 (n0x1d5c-n0x1d5f) + 0x07589d5f, // c0x0186 (n0x1d5f-n0x1d62) + 0x0758dd62, // c0x0187 (n0x1d62-n0x1d63) + 0x07599d63, // c0x0188 (n0x1d63-n0x1d66) + 0x075b1d66, // c0x0189 (n0x1d66-n0x1d6c) + 0x075b5d6c, // c0x018a (n0x1d6c-n0x1d6d) + 0x075c5d6d, // c0x018b (n0x1d6d-n0x1d71) + 0x075ddd71, // c0x018c (n0x1d71-n0x1d77) + 0x07621d77, // c0x018d (n0x1d77-n0x1d88) + 0x07635d88, // c0x018e (n0x1d88-n0x1d8d) + 0x07669d8d, // c0x018f (n0x1d8d-n0x1d9a) + 0x07679d9a, // c0x0190 (n0x1d9a-n0x1d9e) + 0x07695d9e, // c0x0191 (n0x1d9e-n0x1da5) + 0x076adda5, // c0x0192 (n0x1da5-n0x1dab) + 0x276f1dab, // c0x0193 (n0x1dab-n0x1dbc) o 0x076f5dbc, // c0x0194 (n0x1dbc-n0x1dbd) + } // max children 404 (capacity 511) // max text offset 26074 (capacity 32767) // max text length 36 (capacity 63) // max hi 7613 (capacity 16383) // max lo 7612 (capacity 16383) ================================================ FILE: vendor/golang.org/x/net/publicsuffix/table_test.go ================================================ // generated by go run gen.go; DO NOT EDIT package publicsuffix var rules = [...]string{ "ac", "com.ac", "edu.ac", "gov.ac", "net.ac", "mil.ac", "org.ac", "ad", "nom.ad", "ae", "co.ae", "net.ae", "org.ae", "sch.ae", "ac.ae", "gov.ae", "mil.ae", "aero", "accident-investigation.aero", "accident-prevention.aero", "aerobatic.aero", "aeroclub.aero", "aerodrome.aero", "agents.aero", "aircraft.aero", "airline.aero", "airport.aero", "air-surveillance.aero", "airtraffic.aero", "air-traffic-control.aero", "ambulance.aero", "amusement.aero", "association.aero", "author.aero", "ballooning.aero", "broker.aero", "caa.aero", "cargo.aero", "catering.aero", "certification.aero", "championship.aero", "charter.aero", "civilaviation.aero", "club.aero", "conference.aero", "consultant.aero", "consulting.aero", "control.aero", "council.aero", "crew.aero", "design.aero", "dgca.aero", "educator.aero", "emergency.aero", "engine.aero", "engineer.aero", "entertainment.aero", "equipment.aero", "exchange.aero", "express.aero", "federation.aero", "flight.aero", "freight.aero", "fuel.aero", "gliding.aero", "government.aero", "groundhandling.aero", "group.aero", "hanggliding.aero", "homebuilt.aero", "insurance.aero", "journal.aero", "journalist.aero", "leasing.aero", "logistics.aero", "magazine.aero", "maintenance.aero", "marketplace.aero", "media.aero", "microlight.aero", "modelling.aero", "navigation.aero", "parachuting.aero", "paragliding.aero", "passenger-association.aero", "pilot.aero", "press.aero", "production.aero", "recreation.aero", "repbody.aero", "res.aero", "research.aero", "rotorcraft.aero", "safety.aero", "scientist.aero", "services.aero", "show.aero", "skydiving.aero", "software.aero", "student.aero", "taxi.aero", "trader.aero", "trading.aero", "trainer.aero", "union.aero", "workinggroup.aero", "works.aero", "af", "gov.af", "com.af", "org.af", "net.af", "edu.af", "ag", "com.ag", "org.ag", "net.ag", "co.ag", "nom.ag", "ai", "off.ai", "com.ai", "net.ai", "org.ai", "al", "com.al", "edu.al", "gov.al", "mil.al", "net.al", "org.al", "am", "an", "com.an", "net.an", "org.an", "edu.an", "ao", "ed.ao", "gv.ao", "og.ao", "co.ao", "pb.ao", "it.ao", "aq", "ar", "com.ar", "edu.ar", "gob.ar", "gov.ar", "int.ar", "mil.ar", "net.ar", "org.ar", "tur.ar", "arpa", "e164.arpa", "in-addr.arpa", "ip6.arpa", "iris.arpa", "uri.arpa", "urn.arpa", "as", "gov.as", "asia", "at", "ac.at", "co.at", "gv.at", "or.at", "au", "com.au", "net.au", "org.au", "edu.au", "gov.au", "asn.au", "id.au", "info.au", "conf.au", "oz.au", "act.au", "nsw.au", "nt.au", "qld.au", "sa.au", "tas.au", "vic.au", "wa.au", "act.edu.au", "nsw.edu.au", "nt.edu.au", "qld.edu.au", "sa.edu.au", "tas.edu.au", "vic.edu.au", "wa.edu.au", "qld.gov.au", "sa.gov.au", "tas.gov.au", "vic.gov.au", "wa.gov.au", "aw", "com.aw", "ax", "az", "com.az", "net.az", "int.az", "gov.az", "org.az", "edu.az", "info.az", "pp.az", "mil.az", "name.az", "pro.az", "biz.az", "ba", "org.ba", "net.ba", "edu.ba", "gov.ba", "mil.ba", "unsa.ba", "unbi.ba", "co.ba", "com.ba", "rs.ba", "bb", "biz.bb", "co.bb", "com.bb", "edu.bb", "gov.bb", "info.bb", "net.bb", "org.bb", "store.bb", "tv.bb", "*.bd", "be", "ac.be", "bf", "gov.bf", "bg", "a.bg", "b.bg", "c.bg", "d.bg", "e.bg", "f.bg", "g.bg", "h.bg", "i.bg", "j.bg", "k.bg", "l.bg", "m.bg", "n.bg", "o.bg", "p.bg", "q.bg", "r.bg", "s.bg", "t.bg", "u.bg", "v.bg", "w.bg", "x.bg", "y.bg", "z.bg", "0.bg", "1.bg", "2.bg", "3.bg", "4.bg", "5.bg", "6.bg", "7.bg", "8.bg", "9.bg", "bh", "com.bh", "edu.bh", "net.bh", "org.bh", "gov.bh", "bi", "co.bi", "com.bi", "edu.bi", "or.bi", "org.bi", "biz", "bj", "asso.bj", "barreau.bj", "gouv.bj", "bm", "com.bm", "edu.bm", "gov.bm", "net.bm", "org.bm", "*.bn", "bo", "com.bo", "edu.bo", "gov.bo", "gob.bo", "int.bo", "org.bo", "net.bo", "mil.bo", "tv.bo", "br", "adm.br", "adv.br", "agr.br", "am.br", "arq.br", "art.br", "ato.br", "b.br", "bio.br", "blog.br", "bmd.br", "cim.br", "cng.br", "cnt.br", "com.br", "coop.br", "ecn.br", "eco.br", "edu.br", "emp.br", "eng.br", "esp.br", "etc.br", "eti.br", "far.br", "flog.br", "fm.br", "fnd.br", "fot.br", "fst.br", "g12.br", "ggf.br", "gov.br", "imb.br", "ind.br", "inf.br", "jor.br", "jus.br", "leg.br", "lel.br", "mat.br", "med.br", "mil.br", "mp.br", "mus.br", "net.br", "*.nom.br", "not.br", "ntr.br", "odo.br", "org.br", "ppg.br", "pro.br", "psc.br", "psi.br", "qsl.br", "radio.br", "rec.br", "slg.br", "srv.br", "taxi.br", "teo.br", "tmp.br", "trd.br", "tur.br", "tv.br", "vet.br", "vlog.br", "wiki.br", "zlg.br", "bs", "com.bs", "net.bs", "org.bs", "edu.bs", "gov.bs", "bt", "com.bt", "edu.bt", "gov.bt", "net.bt", "org.bt", "bv", "bw", "co.bw", "org.bw", "by", "gov.by", "mil.by", "com.by", "of.by", "bz", "com.bz", "net.bz", "org.bz", "edu.bz", "gov.bz", "ca", "ab.ca", "bc.ca", "mb.ca", "nb.ca", "nf.ca", "nl.ca", "ns.ca", "nt.ca", "nu.ca", "on.ca", "pe.ca", "qc.ca", "sk.ca", "yk.ca", "gc.ca", "cat", "cc", "cd", "gov.cd", "cf", "cg", "ch", "ci", "org.ci", "or.ci", "com.ci", "co.ci", "edu.ci", "ed.ci", "ac.ci", "net.ci", "go.ci", "asso.ci", "xn--aroport-bya.ci", "int.ci", "presse.ci", "md.ci", "gouv.ci", "*.ck", "!www.ck", "cl", "gov.cl", "gob.cl", "co.cl", "mil.cl", "cm", "co.cm", "com.cm", "gov.cm", "net.cm", "cn", "ac.cn", "com.cn", "edu.cn", "gov.cn", "net.cn", "org.cn", "mil.cn", "xn--55qx5d.cn", "xn--io0a7i.cn", "xn--od0alg.cn", "ah.cn", "bj.cn", "cq.cn", "fj.cn", "gd.cn", "gs.cn", "gz.cn", "gx.cn", "ha.cn", "hb.cn", "he.cn", "hi.cn", "hl.cn", "hn.cn", "jl.cn", "js.cn", "jx.cn", "ln.cn", "nm.cn", "nx.cn", "qh.cn", "sc.cn", "sd.cn", "sh.cn", "sn.cn", "sx.cn", "tj.cn", "xj.cn", "xz.cn", "yn.cn", "zj.cn", "hk.cn", "mo.cn", "tw.cn", "co", "arts.co", "com.co", "edu.co", "firm.co", "gov.co", "info.co", "int.co", "mil.co", "net.co", "nom.co", "org.co", "rec.co", "web.co", "com", "coop", "cr", "ac.cr", "co.cr", "ed.cr", "fi.cr", "go.cr", "or.cr", "sa.cr", "cu", "com.cu", "edu.cu", "org.cu", "net.cu", "gov.cu", "inf.cu", "cv", "cw", "com.cw", "edu.cw", "net.cw", "org.cw", "cx", "gov.cx", "ac.cy", "biz.cy", "com.cy", "ekloges.cy", "gov.cy", "ltd.cy", "name.cy", "net.cy", "org.cy", "parliament.cy", "press.cy", "pro.cy", "tm.cy", "cz", "de", "dj", "dk", "dm", "com.dm", "net.dm", "org.dm", "edu.dm", "gov.dm", "do", "art.do", "com.do", "edu.do", "gob.do", "gov.do", "mil.do", "net.do", "org.do", "sld.do", "web.do", "dz", "com.dz", "org.dz", "net.dz", "gov.dz", "edu.dz", "asso.dz", "pol.dz", "art.dz", "ec", "com.ec", "info.ec", "net.ec", "fin.ec", "k12.ec", "med.ec", "pro.ec", "org.ec", "edu.ec", "gov.ec", "gob.ec", "mil.ec", "edu", "ee", "edu.ee", "gov.ee", "riik.ee", "lib.ee", "med.ee", "com.ee", "pri.ee", "aip.ee", "org.ee", "fie.ee", "eg", "com.eg", "edu.eg", "eun.eg", "gov.eg", "mil.eg", "name.eg", "net.eg", "org.eg", "sci.eg", "*.er", "es", "com.es", "nom.es", "org.es", "gob.es", "edu.es", "et", "com.et", "gov.et", "org.et", "edu.et", "biz.et", "name.et", "info.et", "net.et", "eu", "fi", "aland.fi", "*.fj", "*.fk", "fm", "fo", "fr", "com.fr", "asso.fr", "nom.fr", "prd.fr", "presse.fr", "tm.fr", "aeroport.fr", "assedic.fr", "avocat.fr", "avoues.fr", "cci.fr", "chambagri.fr", "chirurgiens-dentistes.fr", "experts-comptables.fr", "geometre-expert.fr", "gouv.fr", "greta.fr", "huissier-justice.fr", "medecin.fr", "notaires.fr", "pharmacien.fr", "port.fr", "veterinaire.fr", "ga", "gb", "gd", "ge", "com.ge", "edu.ge", "gov.ge", "org.ge", "mil.ge", "net.ge", "pvt.ge", "gf", "gg", "co.gg", "net.gg", "org.gg", "gh", "com.gh", "edu.gh", "gov.gh", "org.gh", "mil.gh", "gi", "com.gi", "ltd.gi", "gov.gi", "mod.gi", "edu.gi", "org.gi", "gl", "co.gl", "com.gl", "edu.gl", "net.gl", "org.gl", "gm", "gn", "ac.gn", "com.gn", "edu.gn", "gov.gn", "org.gn", "net.gn", "gov", "gp", "com.gp", "net.gp", "mobi.gp", "edu.gp", "org.gp", "asso.gp", "gq", "gr", "com.gr", "edu.gr", "net.gr", "org.gr", "gov.gr", "gs", "gt", "com.gt", "edu.gt", "gob.gt", "ind.gt", "mil.gt", "net.gt", "org.gt", "*.gu", "gw", "gy", "co.gy", "com.gy", "net.gy", "hk", "com.hk", "edu.hk", "gov.hk", "idv.hk", "net.hk", "org.hk", "xn--55qx5d.hk", "xn--wcvs22d.hk", "xn--lcvr32d.hk", "xn--mxtq1m.hk", "xn--gmqw5a.hk", "xn--ciqpn.hk", "xn--gmq050i.hk", "xn--zf0avx.hk", "xn--io0a7i.hk", "xn--mk0axi.hk", "xn--od0alg.hk", "xn--od0aq3b.hk", "xn--tn0ag.hk", "xn--uc0atv.hk", "xn--uc0ay4a.hk", "hm", "hn", "com.hn", "edu.hn", "org.hn", "net.hn", "mil.hn", "gob.hn", "hr", "iz.hr", "from.hr", "name.hr", "com.hr", "ht", "com.ht", "shop.ht", "firm.ht", "info.ht", "adult.ht", "net.ht", "pro.ht", "org.ht", "med.ht", "art.ht", "coop.ht", "pol.ht", "asso.ht", "edu.ht", "rel.ht", "gouv.ht", "perso.ht", "hu", "co.hu", "info.hu", "org.hu", "priv.hu", "sport.hu", "tm.hu", "2000.hu", "agrar.hu", "bolt.hu", "casino.hu", "city.hu", "erotica.hu", "erotika.hu", "film.hu", "forum.hu", "games.hu", "hotel.hu", "ingatlan.hu", "jogasz.hu", "konyvelo.hu", "lakas.hu", "media.hu", "news.hu", "reklam.hu", "sex.hu", "shop.hu", "suli.hu", "szex.hu", "tozsde.hu", "utazas.hu", "video.hu", "id", "ac.id", "biz.id", "co.id", "desa.id", "go.id", "mil.id", "my.id", "net.id", "or.id", "sch.id", "web.id", "ie", "gov.ie", "*.il", "im", "ac.im", "co.im", "com.im", "ltd.co.im", "net.im", "org.im", "plc.co.im", "tt.im", "tv.im", "in", "co.in", "firm.in", "net.in", "org.in", "gen.in", "ind.in", "nic.in", "ac.in", "edu.in", "res.in", "gov.in", "mil.in", "info", "int", "eu.int", "io", "com.io", "iq", "gov.iq", "edu.iq", "mil.iq", "com.iq", "org.iq", "net.iq", "ir", "ac.ir", "co.ir", "gov.ir", "id.ir", "net.ir", "org.ir", "sch.ir", "xn--mgba3a4f16a.ir", "xn--mgba3a4fra.ir", "is", "net.is", "com.is", "edu.is", "gov.is", "org.is", "int.is", "it", "gov.it", "edu.it", "abr.it", "abruzzo.it", "aosta-valley.it", "aostavalley.it", "bas.it", "basilicata.it", "cal.it", "calabria.it", "cam.it", "campania.it", "emilia-romagna.it", "emiliaromagna.it", "emr.it", "friuli-v-giulia.it", "friuli-ve-giulia.it", "friuli-vegiulia.it", "friuli-venezia-giulia.it", "friuli-veneziagiulia.it", "friuli-vgiulia.it", "friuliv-giulia.it", "friulive-giulia.it", "friulivegiulia.it", "friulivenezia-giulia.it", "friuliveneziagiulia.it", "friulivgiulia.it", "fvg.it", "laz.it", "lazio.it", "lig.it", "liguria.it", "lom.it", "lombardia.it", "lombardy.it", "lucania.it", "mar.it", "marche.it", "mol.it", "molise.it", "piedmont.it", "piemonte.it", "pmn.it", "pug.it", "puglia.it", "sar.it", "sardegna.it", "sardinia.it", "sic.it", "sicilia.it", "sicily.it", "taa.it", "tos.it", "toscana.it", "trentino-a-adige.it", "trentino-aadige.it", "trentino-alto-adige.it", "trentino-altoadige.it", "trentino-s-tirol.it", "trentino-stirol.it", "trentino-sud-tirol.it", "trentino-sudtirol.it", "trentino-sued-tirol.it", "trentino-suedtirol.it", "trentinoa-adige.it", "trentinoaadige.it", "trentinoalto-adige.it", "trentinoaltoadige.it", "trentinos-tirol.it", "trentinostirol.it", "trentinosud-tirol.it", "trentinosudtirol.it", "trentinosued-tirol.it", "trentinosuedtirol.it", "tuscany.it", "umb.it", "umbria.it", "val-d-aosta.it", "val-daosta.it", "vald-aosta.it", "valdaosta.it", "valle-aosta.it", "valle-d-aosta.it", "valle-daosta.it", "valleaosta.it", "valled-aosta.it", "valledaosta.it", "vallee-aoste.it", "valleeaoste.it", "vao.it", "vda.it", "ven.it", "veneto.it", "ag.it", "agrigento.it", "al.it", "alessandria.it", "alto-adige.it", "altoadige.it", "an.it", "ancona.it", "andria-barletta-trani.it", "andria-trani-barletta.it", "andriabarlettatrani.it", "andriatranibarletta.it", "ao.it", "aosta.it", "aoste.it", "ap.it", "aq.it", "aquila.it", "ar.it", "arezzo.it", "ascoli-piceno.it", "ascolipiceno.it", "asti.it", "at.it", "av.it", "avellino.it", "ba.it", "balsan.it", "bari.it", "barletta-trani-andria.it", "barlettatraniandria.it", "belluno.it", "benevento.it", "bergamo.it", "bg.it", "bi.it", "biella.it", "bl.it", "bn.it", "bo.it", "bologna.it", "bolzano.it", "bozen.it", "br.it", "brescia.it", "brindisi.it", "bs.it", "bt.it", "bz.it", "ca.it", "cagliari.it", "caltanissetta.it", "campidano-medio.it", "campidanomedio.it", "campobasso.it", "carbonia-iglesias.it", "carboniaiglesias.it", "carrara-massa.it", "carraramassa.it", "caserta.it", "catania.it", "catanzaro.it", "cb.it", "ce.it", "cesena-forli.it", "cesenaforli.it", "ch.it", "chieti.it", "ci.it", "cl.it", "cn.it", "co.it", "como.it", "cosenza.it", "cr.it", "cremona.it", "crotone.it", "cs.it", "ct.it", "cuneo.it", "cz.it", "dell-ogliastra.it", "dellogliastra.it", "en.it", "enna.it", "fc.it", "fe.it", "fermo.it", "ferrara.it", "fg.it", "fi.it", "firenze.it", "florence.it", "fm.it", "foggia.it", "forli-cesena.it", "forlicesena.it", "fr.it", "frosinone.it", "ge.it", "genoa.it", "genova.it", "go.it", "gorizia.it", "gr.it", "grosseto.it", "iglesias-carbonia.it", "iglesiascarbonia.it", "im.it", "imperia.it", "is.it", "isernia.it", "kr.it", "la-spezia.it", "laquila.it", "laspezia.it", "latina.it", "lc.it", "le.it", "lecce.it", "lecco.it", "li.it", "livorno.it", "lo.it", "lodi.it", "lt.it", "lu.it", "lucca.it", "macerata.it", "mantova.it", "massa-carrara.it", "massacarrara.it", "matera.it", "mb.it", "mc.it", "me.it", "medio-campidano.it", "mediocampidano.it", "messina.it", "mi.it", "milan.it", "milano.it", "mn.it", "mo.it", "modena.it", "monza-brianza.it", "monza-e-della-brianza.it", "monza.it", "monzabrianza.it", "monzaebrianza.it", "monzaedellabrianza.it", "ms.it", "mt.it", "na.it", "naples.it", "napoli.it", "no.it", "novara.it", "nu.it", "nuoro.it", "og.it", "ogliastra.it", "olbia-tempio.it", "olbiatempio.it", "or.it", "oristano.it", "ot.it", "pa.it", "padova.it", "padua.it", "palermo.it", "parma.it", "pavia.it", "pc.it", "pd.it", "pe.it", "perugia.it", "pesaro-urbino.it", "pesarourbino.it", "pescara.it", "pg.it", "pi.it", "piacenza.it", "pisa.it", "pistoia.it", "pn.it", "po.it", "pordenone.it", "potenza.it", "pr.it", "prato.it", "pt.it", "pu.it", "pv.it", "pz.it", "ra.it", "ragusa.it", "ravenna.it", "rc.it", "re.it", "reggio-calabria.it", "reggio-emilia.it", "reggiocalabria.it", "reggioemilia.it", "rg.it", "ri.it", "rieti.it", "rimini.it", "rm.it", "rn.it", "ro.it", "roma.it", "rome.it", "rovigo.it", "sa.it", "salerno.it", "sassari.it", "savona.it", "si.it", "siena.it", "siracusa.it", "so.it", "sondrio.it", "sp.it", "sr.it", "ss.it", "suedtirol.it", "sv.it", "ta.it", "taranto.it", "te.it", "tempio-olbia.it", "tempioolbia.it", "teramo.it", "terni.it", "tn.it", "to.it", "torino.it", "tp.it", "tr.it", "trani-andria-barletta.it", "trani-barletta-andria.it", "traniandriabarletta.it", "tranibarlettaandria.it", "trapani.it", "trentino.it", "trento.it", "treviso.it", "trieste.it", "ts.it", "turin.it", "tv.it", "ud.it", "udine.it", "urbino-pesaro.it", "urbinopesaro.it", "va.it", "varese.it", "vb.it", "vc.it", "ve.it", "venezia.it", "venice.it", "verbania.it", "vercelli.it", "verona.it", "vi.it", "vibo-valentia.it", "vibovalentia.it", "vicenza.it", "viterbo.it", "vr.it", "vs.it", "vt.it", "vv.it", "je", "co.je", "net.je", "org.je", "*.jm", "jo", "com.jo", "org.jo", "net.jo", "edu.jo", "sch.jo", "gov.jo", "mil.jo", "name.jo", "jobs", "jp", "ac.jp", "ad.jp", "co.jp", "ed.jp", "go.jp", "gr.jp", "lg.jp", "ne.jp", "or.jp", "aichi.jp", "akita.jp", "aomori.jp", "chiba.jp", "ehime.jp", "fukui.jp", "fukuoka.jp", "fukushima.jp", "gifu.jp", "gunma.jp", "hiroshima.jp", "hokkaido.jp", "hyogo.jp", "ibaraki.jp", "ishikawa.jp", "iwate.jp", "kagawa.jp", "kagoshima.jp", "kanagawa.jp", "kochi.jp", "kumamoto.jp", "kyoto.jp", "mie.jp", "miyagi.jp", "miyazaki.jp", "nagano.jp", "nagasaki.jp", "nara.jp", "niigata.jp", "oita.jp", "okayama.jp", "okinawa.jp", "osaka.jp", "saga.jp", "saitama.jp", "shiga.jp", "shimane.jp", "shizuoka.jp", "tochigi.jp", "tokushima.jp", "tokyo.jp", "tottori.jp", "toyama.jp", "wakayama.jp", "yamagata.jp", "yamaguchi.jp", "yamanashi.jp", "xn--4pvxs.jp", "xn--vgu402c.jp", "xn--c3s14m.jp", "xn--f6qx53a.jp", "xn--8pvr4u.jp", "xn--uist22h.jp", "xn--djrs72d6uy.jp", "xn--mkru45i.jp", "xn--0trq7p7nn.jp", "xn--8ltr62k.jp", "xn--2m4a15e.jp", "xn--efvn9s.jp", "xn--32vp30h.jp", "xn--4it797k.jp", "xn--1lqs71d.jp", "xn--5rtp49c.jp", "xn--5js045d.jp", "xn--ehqz56n.jp", "xn--1lqs03n.jp", "xn--qqqt11m.jp", "xn--kbrq7o.jp", "xn--pssu33l.jp", "xn--ntsq17g.jp", "xn--uisz3g.jp", "xn--6btw5a.jp", "xn--1ctwo.jp", "xn--6orx2r.jp", "xn--rht61e.jp", "xn--rht27z.jp", "xn--djty4k.jp", "xn--nit225k.jp", "xn--rht3d.jp", "xn--klty5x.jp", "xn--kltx9a.jp", "xn--kltp7d.jp", "xn--uuwu58a.jp", "xn--zbx025d.jp", "xn--ntso0iqx3a.jp", "xn--elqq16h.jp", "xn--4it168d.jp", "xn--klt787d.jp", "xn--rny31h.jp", "xn--7t0a264c.jp", "xn--5rtq34k.jp", "xn--k7yn95e.jp", "xn--tor131o.jp", "xn--d5qv7z876c.jp", "*.kawasaki.jp", "*.kitakyushu.jp", "*.kobe.jp", "*.nagoya.jp", "*.sapporo.jp", "*.sendai.jp", "*.yokohama.jp", "!city.kawasaki.jp", "!city.kitakyushu.jp", "!city.kobe.jp", "!city.nagoya.jp", "!city.sapporo.jp", "!city.sendai.jp", "!city.yokohama.jp", "aisai.aichi.jp", "ama.aichi.jp", "anjo.aichi.jp", "asuke.aichi.jp", "chiryu.aichi.jp", "chita.aichi.jp", "fuso.aichi.jp", "gamagori.aichi.jp", "handa.aichi.jp", "hazu.aichi.jp", "hekinan.aichi.jp", "higashiura.aichi.jp", "ichinomiya.aichi.jp", "inazawa.aichi.jp", "inuyama.aichi.jp", "isshiki.aichi.jp", "iwakura.aichi.jp", "kanie.aichi.jp", "kariya.aichi.jp", "kasugai.aichi.jp", "kira.aichi.jp", "kiyosu.aichi.jp", "komaki.aichi.jp", "konan.aichi.jp", "kota.aichi.jp", "mihama.aichi.jp", "miyoshi.aichi.jp", "nishio.aichi.jp", "nisshin.aichi.jp", "obu.aichi.jp", "oguchi.aichi.jp", "oharu.aichi.jp", "okazaki.aichi.jp", "owariasahi.aichi.jp", "seto.aichi.jp", "shikatsu.aichi.jp", "shinshiro.aichi.jp", "shitara.aichi.jp", "tahara.aichi.jp", "takahama.aichi.jp", "tobishima.aichi.jp", "toei.aichi.jp", "togo.aichi.jp", "tokai.aichi.jp", "tokoname.aichi.jp", "toyoake.aichi.jp", "toyohashi.aichi.jp", "toyokawa.aichi.jp", "toyone.aichi.jp", "toyota.aichi.jp", "tsushima.aichi.jp", "yatomi.aichi.jp", "akita.akita.jp", "daisen.akita.jp", "fujisato.akita.jp", "gojome.akita.jp", "hachirogata.akita.jp", "happou.akita.jp", "higashinaruse.akita.jp", "honjo.akita.jp", "honjyo.akita.jp", "ikawa.akita.jp", "kamikoani.akita.jp", "kamioka.akita.jp", "katagami.akita.jp", "kazuno.akita.jp", "kitaakita.akita.jp", "kosaka.akita.jp", "kyowa.akita.jp", "misato.akita.jp", "mitane.akita.jp", "moriyoshi.akita.jp", "nikaho.akita.jp", "noshiro.akita.jp", "odate.akita.jp", "oga.akita.jp", "ogata.akita.jp", "semboku.akita.jp", "yokote.akita.jp", "yurihonjo.akita.jp", "aomori.aomori.jp", "gonohe.aomori.jp", "hachinohe.aomori.jp", "hashikami.aomori.jp", "hiranai.aomori.jp", "hirosaki.aomori.jp", "itayanagi.aomori.jp", "kuroishi.aomori.jp", "misawa.aomori.jp", "mutsu.aomori.jp", "nakadomari.aomori.jp", "noheji.aomori.jp", "oirase.aomori.jp", "owani.aomori.jp", "rokunohe.aomori.jp", "sannohe.aomori.jp", "shichinohe.aomori.jp", "shingo.aomori.jp", "takko.aomori.jp", "towada.aomori.jp", "tsugaru.aomori.jp", "tsuruta.aomori.jp", "abiko.chiba.jp", "asahi.chiba.jp", "chonan.chiba.jp", "chosei.chiba.jp", "choshi.chiba.jp", "chuo.chiba.jp", "funabashi.chiba.jp", "futtsu.chiba.jp", "hanamigawa.chiba.jp", "ichihara.chiba.jp", "ichikawa.chiba.jp", "ichinomiya.chiba.jp", "inzai.chiba.jp", "isumi.chiba.jp", "kamagaya.chiba.jp", "kamogawa.chiba.jp", "kashiwa.chiba.jp", "katori.chiba.jp", "katsuura.chiba.jp", "kimitsu.chiba.jp", "kisarazu.chiba.jp", "kozaki.chiba.jp", "kujukuri.chiba.jp", "kyonan.chiba.jp", "matsudo.chiba.jp", "midori.chiba.jp", "mihama.chiba.jp", "minamiboso.chiba.jp", "mobara.chiba.jp", "mutsuzawa.chiba.jp", "nagara.chiba.jp", "nagareyama.chiba.jp", "narashino.chiba.jp", "narita.chiba.jp", "noda.chiba.jp", "oamishirasato.chiba.jp", "omigawa.chiba.jp", "onjuku.chiba.jp", "otaki.chiba.jp", "sakae.chiba.jp", "sakura.chiba.jp", "shimofusa.chiba.jp", "shirako.chiba.jp", "shiroi.chiba.jp", "shisui.chiba.jp", "sodegaura.chiba.jp", "sosa.chiba.jp", "tako.chiba.jp", "tateyama.chiba.jp", "togane.chiba.jp", "tohnosho.chiba.jp", "tomisato.chiba.jp", "urayasu.chiba.jp", "yachimata.chiba.jp", "yachiyo.chiba.jp", "yokaichiba.chiba.jp", "yokoshibahikari.chiba.jp", "yotsukaido.chiba.jp", "ainan.ehime.jp", "honai.ehime.jp", "ikata.ehime.jp", "imabari.ehime.jp", "iyo.ehime.jp", "kamijima.ehime.jp", "kihoku.ehime.jp", "kumakogen.ehime.jp", "masaki.ehime.jp", "matsuno.ehime.jp", "matsuyama.ehime.jp", "namikata.ehime.jp", "niihama.ehime.jp", "ozu.ehime.jp", "saijo.ehime.jp", "seiyo.ehime.jp", "shikokuchuo.ehime.jp", "tobe.ehime.jp", "toon.ehime.jp", "uchiko.ehime.jp", "uwajima.ehime.jp", "yawatahama.ehime.jp", "echizen.fukui.jp", "eiheiji.fukui.jp", "fukui.fukui.jp", "ikeda.fukui.jp", "katsuyama.fukui.jp", "mihama.fukui.jp", "minamiechizen.fukui.jp", "obama.fukui.jp", "ohi.fukui.jp", "ono.fukui.jp", "sabae.fukui.jp", "sakai.fukui.jp", "takahama.fukui.jp", "tsuruga.fukui.jp", "wakasa.fukui.jp", "ashiya.fukuoka.jp", "buzen.fukuoka.jp", "chikugo.fukuoka.jp", "chikuho.fukuoka.jp", "chikujo.fukuoka.jp", "chikushino.fukuoka.jp", "chikuzen.fukuoka.jp", "chuo.fukuoka.jp", "dazaifu.fukuoka.jp", "fukuchi.fukuoka.jp", "hakata.fukuoka.jp", "higashi.fukuoka.jp", "hirokawa.fukuoka.jp", "hisayama.fukuoka.jp", "iizuka.fukuoka.jp", "inatsuki.fukuoka.jp", "kaho.fukuoka.jp", "kasuga.fukuoka.jp", "kasuya.fukuoka.jp", "kawara.fukuoka.jp", "keisen.fukuoka.jp", "koga.fukuoka.jp", "kurate.fukuoka.jp", "kurogi.fukuoka.jp", "kurume.fukuoka.jp", "minami.fukuoka.jp", "miyako.fukuoka.jp", "miyama.fukuoka.jp", "miyawaka.fukuoka.jp", "mizumaki.fukuoka.jp", "munakata.fukuoka.jp", "nakagawa.fukuoka.jp", "nakama.fukuoka.jp", "nishi.fukuoka.jp", "nogata.fukuoka.jp", "ogori.fukuoka.jp", "okagaki.fukuoka.jp", "okawa.fukuoka.jp", "oki.fukuoka.jp", "omuta.fukuoka.jp", "onga.fukuoka.jp", "onojo.fukuoka.jp", "oto.fukuoka.jp", "saigawa.fukuoka.jp", "sasaguri.fukuoka.jp", "shingu.fukuoka.jp", "shinyoshitomi.fukuoka.jp", "shonai.fukuoka.jp", "soeda.fukuoka.jp", "sue.fukuoka.jp", "tachiarai.fukuoka.jp", "tagawa.fukuoka.jp", "takata.fukuoka.jp", "toho.fukuoka.jp", "toyotsu.fukuoka.jp", "tsuiki.fukuoka.jp", "ukiha.fukuoka.jp", "umi.fukuoka.jp", "usui.fukuoka.jp", "yamada.fukuoka.jp", "yame.fukuoka.jp", "yanagawa.fukuoka.jp", "yukuhashi.fukuoka.jp", "aizubange.fukushima.jp", "aizumisato.fukushima.jp", "aizuwakamatsu.fukushima.jp", "asakawa.fukushima.jp", "bandai.fukushima.jp", "date.fukushima.jp", "fukushima.fukushima.jp", "furudono.fukushima.jp", "futaba.fukushima.jp", "hanawa.fukushima.jp", "higashi.fukushima.jp", "hirata.fukushima.jp", "hirono.fukushima.jp", "iitate.fukushima.jp", "inawashiro.fukushima.jp", "ishikawa.fukushima.jp", "iwaki.fukushima.jp", "izumizaki.fukushima.jp", "kagamiishi.fukushima.jp", "kaneyama.fukushima.jp", "kawamata.fukushima.jp", "kitakata.fukushima.jp", "kitashiobara.fukushima.jp", "koori.fukushima.jp", "koriyama.fukushima.jp", "kunimi.fukushima.jp", "miharu.fukushima.jp", "mishima.fukushima.jp", "namie.fukushima.jp", "nango.fukushima.jp", "nishiaizu.fukushima.jp", "nishigo.fukushima.jp", "okuma.fukushima.jp", "omotego.fukushima.jp", "ono.fukushima.jp", "otama.fukushima.jp", "samegawa.fukushima.jp", "shimogo.fukushima.jp", "shirakawa.fukushima.jp", "showa.fukushima.jp", "soma.fukushima.jp", "sukagawa.fukushima.jp", "taishin.fukushima.jp", "tamakawa.fukushima.jp", "tanagura.fukushima.jp", "tenei.fukushima.jp", "yabuki.fukushima.jp", "yamato.fukushima.jp", "yamatsuri.fukushima.jp", "yanaizu.fukushima.jp", "yugawa.fukushima.jp", "anpachi.gifu.jp", "ena.gifu.jp", "gifu.gifu.jp", "ginan.gifu.jp", "godo.gifu.jp", "gujo.gifu.jp", "hashima.gifu.jp", "hichiso.gifu.jp", "hida.gifu.jp", "higashishirakawa.gifu.jp", "ibigawa.gifu.jp", "ikeda.gifu.jp", "kakamigahara.gifu.jp", "kani.gifu.jp", "kasahara.gifu.jp", "kasamatsu.gifu.jp", "kawaue.gifu.jp", "kitagata.gifu.jp", "mino.gifu.jp", "minokamo.gifu.jp", "mitake.gifu.jp", "mizunami.gifu.jp", "motosu.gifu.jp", "nakatsugawa.gifu.jp", "ogaki.gifu.jp", "sakahogi.gifu.jp", "seki.gifu.jp", "sekigahara.gifu.jp", "shirakawa.gifu.jp", "tajimi.gifu.jp", "takayama.gifu.jp", "tarui.gifu.jp", "toki.gifu.jp", "tomika.gifu.jp", "wanouchi.gifu.jp", "yamagata.gifu.jp", "yaotsu.gifu.jp", "yoro.gifu.jp", "annaka.gunma.jp", "chiyoda.gunma.jp", "fujioka.gunma.jp", "higashiagatsuma.gunma.jp", "isesaki.gunma.jp", "itakura.gunma.jp", "kanna.gunma.jp", "kanra.gunma.jp", "katashina.gunma.jp", "kawaba.gunma.jp", "kiryu.gunma.jp", "kusatsu.gunma.jp", "maebashi.gunma.jp", "meiwa.gunma.jp", "midori.gunma.jp", "minakami.gunma.jp", "naganohara.gunma.jp", "nakanojo.gunma.jp", "nanmoku.gunma.jp", "numata.gunma.jp", "oizumi.gunma.jp", "ora.gunma.jp", "ota.gunma.jp", "shibukawa.gunma.jp", "shimonita.gunma.jp", "shinto.gunma.jp", "showa.gunma.jp", "takasaki.gunma.jp", "takayama.gunma.jp", "tamamura.gunma.jp", "tatebayashi.gunma.jp", "tomioka.gunma.jp", "tsukiyono.gunma.jp", "tsumagoi.gunma.jp", "ueno.gunma.jp", "yoshioka.gunma.jp", "asaminami.hiroshima.jp", "daiwa.hiroshima.jp", "etajima.hiroshima.jp", "fuchu.hiroshima.jp", "fukuyama.hiroshima.jp", "hatsukaichi.hiroshima.jp", "higashihiroshima.hiroshima.jp", "hongo.hiroshima.jp", "jinsekikogen.hiroshima.jp", "kaita.hiroshima.jp", "kui.hiroshima.jp", "kumano.hiroshima.jp", "kure.hiroshima.jp", "mihara.hiroshima.jp", "miyoshi.hiroshima.jp", "naka.hiroshima.jp", "onomichi.hiroshima.jp", "osakikamijima.hiroshima.jp", "otake.hiroshima.jp", "saka.hiroshima.jp", "sera.hiroshima.jp", "seranishi.hiroshima.jp", "shinichi.hiroshima.jp", "shobara.hiroshima.jp", "takehara.hiroshima.jp", "abashiri.hokkaido.jp", "abira.hokkaido.jp", "aibetsu.hokkaido.jp", "akabira.hokkaido.jp", "akkeshi.hokkaido.jp", "asahikawa.hokkaido.jp", "ashibetsu.hokkaido.jp", "ashoro.hokkaido.jp", "assabu.hokkaido.jp", "atsuma.hokkaido.jp", "bibai.hokkaido.jp", "biei.hokkaido.jp", "bifuka.hokkaido.jp", "bihoro.hokkaido.jp", "biratori.hokkaido.jp", "chippubetsu.hokkaido.jp", "chitose.hokkaido.jp", "date.hokkaido.jp", "ebetsu.hokkaido.jp", "embetsu.hokkaido.jp", "eniwa.hokkaido.jp", "erimo.hokkaido.jp", "esan.hokkaido.jp", "esashi.hokkaido.jp", "fukagawa.hokkaido.jp", "fukushima.hokkaido.jp", "furano.hokkaido.jp", "furubira.hokkaido.jp", "haboro.hokkaido.jp", "hakodate.hokkaido.jp", "hamatonbetsu.hokkaido.jp", "hidaka.hokkaido.jp", "higashikagura.hokkaido.jp", "higashikawa.hokkaido.jp", "hiroo.hokkaido.jp", "hokuryu.hokkaido.jp", "hokuto.hokkaido.jp", "honbetsu.hokkaido.jp", "horokanai.hokkaido.jp", "horonobe.hokkaido.jp", "ikeda.hokkaido.jp", "imakane.hokkaido.jp", "ishikari.hokkaido.jp", "iwamizawa.hokkaido.jp", "iwanai.hokkaido.jp", "kamifurano.hokkaido.jp", "kamikawa.hokkaido.jp", "kamishihoro.hokkaido.jp", "kamisunagawa.hokkaido.jp", "kamoenai.hokkaido.jp", "kayabe.hokkaido.jp", "kembuchi.hokkaido.jp", "kikonai.hokkaido.jp", "kimobetsu.hokkaido.jp", "kitahiroshima.hokkaido.jp", "kitami.hokkaido.jp", "kiyosato.hokkaido.jp", "koshimizu.hokkaido.jp", "kunneppu.hokkaido.jp", "kuriyama.hokkaido.jp", "kuromatsunai.hokkaido.jp", "kushiro.hokkaido.jp", "kutchan.hokkaido.jp", "kyowa.hokkaido.jp", "mashike.hokkaido.jp", "matsumae.hokkaido.jp", "mikasa.hokkaido.jp", "minamifurano.hokkaido.jp", "mombetsu.hokkaido.jp", "moseushi.hokkaido.jp", "mukawa.hokkaido.jp", "muroran.hokkaido.jp", "naie.hokkaido.jp", "nakagawa.hokkaido.jp", "nakasatsunai.hokkaido.jp", "nakatombetsu.hokkaido.jp", "nanae.hokkaido.jp", "nanporo.hokkaido.jp", "nayoro.hokkaido.jp", "nemuro.hokkaido.jp", "niikappu.hokkaido.jp", "niki.hokkaido.jp", "nishiokoppe.hokkaido.jp", "noboribetsu.hokkaido.jp", "numata.hokkaido.jp", "obihiro.hokkaido.jp", "obira.hokkaido.jp", "oketo.hokkaido.jp", "okoppe.hokkaido.jp", "otaru.hokkaido.jp", "otobe.hokkaido.jp", "otofuke.hokkaido.jp", "otoineppu.hokkaido.jp", "oumu.hokkaido.jp", "ozora.hokkaido.jp", "pippu.hokkaido.jp", "rankoshi.hokkaido.jp", "rebun.hokkaido.jp", "rikubetsu.hokkaido.jp", "rishiri.hokkaido.jp", "rishirifuji.hokkaido.jp", "saroma.hokkaido.jp", "sarufutsu.hokkaido.jp", "shakotan.hokkaido.jp", "shari.hokkaido.jp", "shibecha.hokkaido.jp", "shibetsu.hokkaido.jp", "shikabe.hokkaido.jp", "shikaoi.hokkaido.jp", "shimamaki.hokkaido.jp", "shimizu.hokkaido.jp", "shimokawa.hokkaido.jp", "shinshinotsu.hokkaido.jp", "shintoku.hokkaido.jp", "shiranuka.hokkaido.jp", "shiraoi.hokkaido.jp", "shiriuchi.hokkaido.jp", "sobetsu.hokkaido.jp", "sunagawa.hokkaido.jp", "taiki.hokkaido.jp", "takasu.hokkaido.jp", "takikawa.hokkaido.jp", "takinoue.hokkaido.jp", "teshikaga.hokkaido.jp", "tobetsu.hokkaido.jp", "tohma.hokkaido.jp", "tomakomai.hokkaido.jp", "tomari.hokkaido.jp", "toya.hokkaido.jp", "toyako.hokkaido.jp", "toyotomi.hokkaido.jp", "toyoura.hokkaido.jp", "tsubetsu.hokkaido.jp", "tsukigata.hokkaido.jp", "urakawa.hokkaido.jp", "urausu.hokkaido.jp", "uryu.hokkaido.jp", "utashinai.hokkaido.jp", "wakkanai.hokkaido.jp", "wassamu.hokkaido.jp", "yakumo.hokkaido.jp", "yoichi.hokkaido.jp", "aioi.hyogo.jp", "akashi.hyogo.jp", "ako.hyogo.jp", "amagasaki.hyogo.jp", "aogaki.hyogo.jp", "asago.hyogo.jp", "ashiya.hyogo.jp", "awaji.hyogo.jp", "fukusaki.hyogo.jp", "goshiki.hyogo.jp", "harima.hyogo.jp", "himeji.hyogo.jp", "ichikawa.hyogo.jp", "inagawa.hyogo.jp", "itami.hyogo.jp", "kakogawa.hyogo.jp", "kamigori.hyogo.jp", "kamikawa.hyogo.jp", "kasai.hyogo.jp", "kasuga.hyogo.jp", "kawanishi.hyogo.jp", "miki.hyogo.jp", "minamiawaji.hyogo.jp", "nishinomiya.hyogo.jp", "nishiwaki.hyogo.jp", "ono.hyogo.jp", "sanda.hyogo.jp", "sannan.hyogo.jp", "sasayama.hyogo.jp", "sayo.hyogo.jp", "shingu.hyogo.jp", "shinonsen.hyogo.jp", "shiso.hyogo.jp", "sumoto.hyogo.jp", "taishi.hyogo.jp", "taka.hyogo.jp", "takarazuka.hyogo.jp", "takasago.hyogo.jp", "takino.hyogo.jp", "tamba.hyogo.jp", "tatsuno.hyogo.jp", "toyooka.hyogo.jp", "yabu.hyogo.jp", "yashiro.hyogo.jp", "yoka.hyogo.jp", "yokawa.hyogo.jp", "ami.ibaraki.jp", "asahi.ibaraki.jp", "bando.ibaraki.jp", "chikusei.ibaraki.jp", "daigo.ibaraki.jp", "fujishiro.ibaraki.jp", "hitachi.ibaraki.jp", "hitachinaka.ibaraki.jp", "hitachiomiya.ibaraki.jp", "hitachiota.ibaraki.jp", "ibaraki.ibaraki.jp", "ina.ibaraki.jp", "inashiki.ibaraki.jp", "itako.ibaraki.jp", "iwama.ibaraki.jp", "joso.ibaraki.jp", "kamisu.ibaraki.jp", "kasama.ibaraki.jp", "kashima.ibaraki.jp", "kasumigaura.ibaraki.jp", "koga.ibaraki.jp", "miho.ibaraki.jp", "mito.ibaraki.jp", "moriya.ibaraki.jp", "naka.ibaraki.jp", "namegata.ibaraki.jp", "oarai.ibaraki.jp", "ogawa.ibaraki.jp", "omitama.ibaraki.jp", "ryugasaki.ibaraki.jp", "sakai.ibaraki.jp", "sakuragawa.ibaraki.jp", "shimodate.ibaraki.jp", "shimotsuma.ibaraki.jp", "shirosato.ibaraki.jp", "sowa.ibaraki.jp", "suifu.ibaraki.jp", "takahagi.ibaraki.jp", "tamatsukuri.ibaraki.jp", "tokai.ibaraki.jp", "tomobe.ibaraki.jp", "tone.ibaraki.jp", "toride.ibaraki.jp", "tsuchiura.ibaraki.jp", "tsukuba.ibaraki.jp", "uchihara.ibaraki.jp", "ushiku.ibaraki.jp", "yachiyo.ibaraki.jp", "yamagata.ibaraki.jp", "yawara.ibaraki.jp", "yuki.ibaraki.jp", "anamizu.ishikawa.jp", "hakui.ishikawa.jp", "hakusan.ishikawa.jp", "kaga.ishikawa.jp", "kahoku.ishikawa.jp", "kanazawa.ishikawa.jp", "kawakita.ishikawa.jp", "komatsu.ishikawa.jp", "nakanoto.ishikawa.jp", "nanao.ishikawa.jp", "nomi.ishikawa.jp", "nonoichi.ishikawa.jp", "noto.ishikawa.jp", "shika.ishikawa.jp", "suzu.ishikawa.jp", "tsubata.ishikawa.jp", "tsurugi.ishikawa.jp", "uchinada.ishikawa.jp", "wajima.ishikawa.jp", "fudai.iwate.jp", "fujisawa.iwate.jp", "hanamaki.iwate.jp", "hiraizumi.iwate.jp", "hirono.iwate.jp", "ichinohe.iwate.jp", "ichinoseki.iwate.jp", "iwaizumi.iwate.jp", "iwate.iwate.jp", "joboji.iwate.jp", "kamaishi.iwate.jp", "kanegasaki.iwate.jp", "karumai.iwate.jp", "kawai.iwate.jp", "kitakami.iwate.jp", "kuji.iwate.jp", "kunohe.iwate.jp", "kuzumaki.iwate.jp", "miyako.iwate.jp", "mizusawa.iwate.jp", "morioka.iwate.jp", "ninohe.iwate.jp", "noda.iwate.jp", "ofunato.iwate.jp", "oshu.iwate.jp", "otsuchi.iwate.jp", "rikuzentakata.iwate.jp", "shiwa.iwate.jp", "shizukuishi.iwate.jp", "sumita.iwate.jp", "tanohata.iwate.jp", "tono.iwate.jp", "yahaba.iwate.jp", "yamada.iwate.jp", "ayagawa.kagawa.jp", "higashikagawa.kagawa.jp", "kanonji.kagawa.jp", "kotohira.kagawa.jp", "manno.kagawa.jp", "marugame.kagawa.jp", "mitoyo.kagawa.jp", "naoshima.kagawa.jp", "sanuki.kagawa.jp", "tadotsu.kagawa.jp", "takamatsu.kagawa.jp", "tonosho.kagawa.jp", "uchinomi.kagawa.jp", "utazu.kagawa.jp", "zentsuji.kagawa.jp", "akune.kagoshima.jp", "amami.kagoshima.jp", "hioki.kagoshima.jp", "isa.kagoshima.jp", "isen.kagoshima.jp", "izumi.kagoshima.jp", "kagoshima.kagoshima.jp", "kanoya.kagoshima.jp", "kawanabe.kagoshima.jp", "kinko.kagoshima.jp", "kouyama.kagoshima.jp", "makurazaki.kagoshima.jp", "matsumoto.kagoshima.jp", "minamitane.kagoshima.jp", "nakatane.kagoshima.jp", "nishinoomote.kagoshima.jp", "satsumasendai.kagoshima.jp", "soo.kagoshima.jp", "tarumizu.kagoshima.jp", "yusui.kagoshima.jp", "aikawa.kanagawa.jp", "atsugi.kanagawa.jp", "ayase.kanagawa.jp", "chigasaki.kanagawa.jp", "ebina.kanagawa.jp", "fujisawa.kanagawa.jp", "hadano.kanagawa.jp", "hakone.kanagawa.jp", "hiratsuka.kanagawa.jp", "isehara.kanagawa.jp", "kaisei.kanagawa.jp", "kamakura.kanagawa.jp", "kiyokawa.kanagawa.jp", "matsuda.kanagawa.jp", "minamiashigara.kanagawa.jp", "miura.kanagawa.jp", "nakai.kanagawa.jp", "ninomiya.kanagawa.jp", "odawara.kanagawa.jp", "oi.kanagawa.jp", "oiso.kanagawa.jp", "sagamihara.kanagawa.jp", "samukawa.kanagawa.jp", "tsukui.kanagawa.jp", "yamakita.kanagawa.jp", "yamato.kanagawa.jp", "yokosuka.kanagawa.jp", "yugawara.kanagawa.jp", "zama.kanagawa.jp", "zushi.kanagawa.jp", "aki.kochi.jp", "geisei.kochi.jp", "hidaka.kochi.jp", "higashitsuno.kochi.jp", "ino.kochi.jp", "kagami.kochi.jp", "kami.kochi.jp", "kitagawa.kochi.jp", "kochi.kochi.jp", "mihara.kochi.jp", "motoyama.kochi.jp", "muroto.kochi.jp", "nahari.kochi.jp", "nakamura.kochi.jp", "nankoku.kochi.jp", "nishitosa.kochi.jp", "niyodogawa.kochi.jp", "ochi.kochi.jp", "okawa.kochi.jp", "otoyo.kochi.jp", "otsuki.kochi.jp", "sakawa.kochi.jp", "sukumo.kochi.jp", "susaki.kochi.jp", "tosa.kochi.jp", "tosashimizu.kochi.jp", "toyo.kochi.jp", "tsuno.kochi.jp", "umaji.kochi.jp", "yasuda.kochi.jp", "yusuhara.kochi.jp", "amakusa.kumamoto.jp", "arao.kumamoto.jp", "aso.kumamoto.jp", "choyo.kumamoto.jp", "gyokuto.kumamoto.jp", "hitoyoshi.kumamoto.jp", "kamiamakusa.kumamoto.jp", "kashima.kumamoto.jp", "kikuchi.kumamoto.jp", "kosa.kumamoto.jp", "kumamoto.kumamoto.jp", "mashiki.kumamoto.jp", "mifune.kumamoto.jp", "minamata.kumamoto.jp", "minamioguni.kumamoto.jp", "nagasu.kumamoto.jp", "nishihara.kumamoto.jp", "oguni.kumamoto.jp", "ozu.kumamoto.jp", "sumoto.kumamoto.jp", "takamori.kumamoto.jp", "uki.kumamoto.jp", "uto.kumamoto.jp", "yamaga.kumamoto.jp", "yamato.kumamoto.jp", "yatsushiro.kumamoto.jp", "ayabe.kyoto.jp", "fukuchiyama.kyoto.jp", "higashiyama.kyoto.jp", "ide.kyoto.jp", "ine.kyoto.jp", "joyo.kyoto.jp", "kameoka.kyoto.jp", "kamo.kyoto.jp", "kita.kyoto.jp", "kizu.kyoto.jp", "kumiyama.kyoto.jp", "kyotamba.kyoto.jp", "kyotanabe.kyoto.jp", "kyotango.kyoto.jp", "maizuru.kyoto.jp", "minami.kyoto.jp", "minamiyamashiro.kyoto.jp", "miyazu.kyoto.jp", "muko.kyoto.jp", "nagaokakyo.kyoto.jp", "nakagyo.kyoto.jp", "nantan.kyoto.jp", "oyamazaki.kyoto.jp", "sakyo.kyoto.jp", "seika.kyoto.jp", "tanabe.kyoto.jp", "uji.kyoto.jp", "ujitawara.kyoto.jp", "wazuka.kyoto.jp", "yamashina.kyoto.jp", "yawata.kyoto.jp", "asahi.mie.jp", "inabe.mie.jp", "ise.mie.jp", "kameyama.mie.jp", "kawagoe.mie.jp", "kiho.mie.jp", "kisosaki.mie.jp", "kiwa.mie.jp", "komono.mie.jp", "kumano.mie.jp", "kuwana.mie.jp", "matsusaka.mie.jp", "meiwa.mie.jp", "mihama.mie.jp", "minamiise.mie.jp", "misugi.mie.jp", "miyama.mie.jp", "nabari.mie.jp", "shima.mie.jp", "suzuka.mie.jp", "tado.mie.jp", "taiki.mie.jp", "taki.mie.jp", "tamaki.mie.jp", "toba.mie.jp", "tsu.mie.jp", "udono.mie.jp", "ureshino.mie.jp", "watarai.mie.jp", "yokkaichi.mie.jp", "furukawa.miyagi.jp", "higashimatsushima.miyagi.jp", "ishinomaki.miyagi.jp", "iwanuma.miyagi.jp", "kakuda.miyagi.jp", "kami.miyagi.jp", "kawasaki.miyagi.jp", "kesennuma.miyagi.jp", "marumori.miyagi.jp", "matsushima.miyagi.jp", "minamisanriku.miyagi.jp", "misato.miyagi.jp", "murata.miyagi.jp", "natori.miyagi.jp", "ogawara.miyagi.jp", "ohira.miyagi.jp", "onagawa.miyagi.jp", "osaki.miyagi.jp", "rifu.miyagi.jp", "semine.miyagi.jp", "shibata.miyagi.jp", "shichikashuku.miyagi.jp", "shikama.miyagi.jp", "shiogama.miyagi.jp", "shiroishi.miyagi.jp", "tagajo.miyagi.jp", "taiwa.miyagi.jp", "tome.miyagi.jp", "tomiya.miyagi.jp", "wakuya.miyagi.jp", "watari.miyagi.jp", "yamamoto.miyagi.jp", "zao.miyagi.jp", "aya.miyazaki.jp", "ebino.miyazaki.jp", "gokase.miyazaki.jp", "hyuga.miyazaki.jp", "kadogawa.miyazaki.jp", "kawaminami.miyazaki.jp", "kijo.miyazaki.jp", "kitagawa.miyazaki.jp", "kitakata.miyazaki.jp", "kitaura.miyazaki.jp", "kobayashi.miyazaki.jp", "kunitomi.miyazaki.jp", "kushima.miyazaki.jp", "mimata.miyazaki.jp", "miyakonojo.miyazaki.jp", "miyazaki.miyazaki.jp", "morotsuka.miyazaki.jp", "nichinan.miyazaki.jp", "nishimera.miyazaki.jp", "nobeoka.miyazaki.jp", "saito.miyazaki.jp", "shiiba.miyazaki.jp", "shintomi.miyazaki.jp", "takaharu.miyazaki.jp", "takanabe.miyazaki.jp", "takazaki.miyazaki.jp", "tsuno.miyazaki.jp", "achi.nagano.jp", "agematsu.nagano.jp", "anan.nagano.jp", "aoki.nagano.jp", "asahi.nagano.jp", "azumino.nagano.jp", "chikuhoku.nagano.jp", "chikuma.nagano.jp", "chino.nagano.jp", "fujimi.nagano.jp", "hakuba.nagano.jp", "hara.nagano.jp", "hiraya.nagano.jp", "iida.nagano.jp", "iijima.nagano.jp", "iiyama.nagano.jp", "iizuna.nagano.jp", "ikeda.nagano.jp", "ikusaka.nagano.jp", "ina.nagano.jp", "karuizawa.nagano.jp", "kawakami.nagano.jp", "kiso.nagano.jp", "kisofukushima.nagano.jp", "kitaaiki.nagano.jp", "komagane.nagano.jp", "komoro.nagano.jp", "matsukawa.nagano.jp", "matsumoto.nagano.jp", "miasa.nagano.jp", "minamiaiki.nagano.jp", "minamimaki.nagano.jp", "minamiminowa.nagano.jp", "minowa.nagano.jp", "miyada.nagano.jp", "miyota.nagano.jp", "mochizuki.nagano.jp", "nagano.nagano.jp", "nagawa.nagano.jp", "nagiso.nagano.jp", "nakagawa.nagano.jp", "nakano.nagano.jp", "nozawaonsen.nagano.jp", "obuse.nagano.jp", "ogawa.nagano.jp", "okaya.nagano.jp", "omachi.nagano.jp", "omi.nagano.jp", "ookuwa.nagano.jp", "ooshika.nagano.jp", "otaki.nagano.jp", "otari.nagano.jp", "sakae.nagano.jp", "sakaki.nagano.jp", "saku.nagano.jp", "sakuho.nagano.jp", "shimosuwa.nagano.jp", "shinanomachi.nagano.jp", "shiojiri.nagano.jp", "suwa.nagano.jp", "suzaka.nagano.jp", "takagi.nagano.jp", "takamori.nagano.jp", "takayama.nagano.jp", "tateshina.nagano.jp", "tatsuno.nagano.jp", "togakushi.nagano.jp", "togura.nagano.jp", "tomi.nagano.jp", "ueda.nagano.jp", "wada.nagano.jp", "yamagata.nagano.jp", "yamanouchi.nagano.jp", "yasaka.nagano.jp", "yasuoka.nagano.jp", "chijiwa.nagasaki.jp", "futsu.nagasaki.jp", "goto.nagasaki.jp", "hasami.nagasaki.jp", "hirado.nagasaki.jp", "iki.nagasaki.jp", "isahaya.nagasaki.jp", "kawatana.nagasaki.jp", "kuchinotsu.nagasaki.jp", "matsuura.nagasaki.jp", "nagasaki.nagasaki.jp", "obama.nagasaki.jp", "omura.nagasaki.jp", "oseto.nagasaki.jp", "saikai.nagasaki.jp", "sasebo.nagasaki.jp", "seihi.nagasaki.jp", "shimabara.nagasaki.jp", "shinkamigoto.nagasaki.jp", "togitsu.nagasaki.jp", "tsushima.nagasaki.jp", "unzen.nagasaki.jp", "ando.nara.jp", "gose.nara.jp", "heguri.nara.jp", "higashiyoshino.nara.jp", "ikaruga.nara.jp", "ikoma.nara.jp", "kamikitayama.nara.jp", "kanmaki.nara.jp", "kashiba.nara.jp", "kashihara.nara.jp", "katsuragi.nara.jp", "kawai.nara.jp", "kawakami.nara.jp", "kawanishi.nara.jp", "koryo.nara.jp", "kurotaki.nara.jp", "mitsue.nara.jp", "miyake.nara.jp", "nara.nara.jp", "nosegawa.nara.jp", "oji.nara.jp", "ouda.nara.jp", "oyodo.nara.jp", "sakurai.nara.jp", "sango.nara.jp", "shimoichi.nara.jp", "shimokitayama.nara.jp", "shinjo.nara.jp", "soni.nara.jp", "takatori.nara.jp", "tawaramoto.nara.jp", "tenkawa.nara.jp", "tenri.nara.jp", "uda.nara.jp", "yamatokoriyama.nara.jp", "yamatotakada.nara.jp", "yamazoe.nara.jp", "yoshino.nara.jp", "aga.niigata.jp", "agano.niigata.jp", "gosen.niigata.jp", "itoigawa.niigata.jp", "izumozaki.niigata.jp", "joetsu.niigata.jp", "kamo.niigata.jp", "kariwa.niigata.jp", "kashiwazaki.niigata.jp", "minamiuonuma.niigata.jp", "mitsuke.niigata.jp", "muika.niigata.jp", "murakami.niigata.jp", "myoko.niigata.jp", "nagaoka.niigata.jp", "niigata.niigata.jp", "ojiya.niigata.jp", "omi.niigata.jp", "sado.niigata.jp", "sanjo.niigata.jp", "seiro.niigata.jp", "seirou.niigata.jp", "sekikawa.niigata.jp", "shibata.niigata.jp", "tagami.niigata.jp", "tainai.niigata.jp", "tochio.niigata.jp", "tokamachi.niigata.jp", "tsubame.niigata.jp", "tsunan.niigata.jp", "uonuma.niigata.jp", "yahiko.niigata.jp", "yoita.niigata.jp", "yuzawa.niigata.jp", "beppu.oita.jp", "bungoono.oita.jp", "bungotakada.oita.jp", "hasama.oita.jp", "hiji.oita.jp", "himeshima.oita.jp", "hita.oita.jp", "kamitsue.oita.jp", "kokonoe.oita.jp", "kuju.oita.jp", "kunisaki.oita.jp", "kusu.oita.jp", "oita.oita.jp", "saiki.oita.jp", "taketa.oita.jp", "tsukumi.oita.jp", "usa.oita.jp", "usuki.oita.jp", "yufu.oita.jp", "akaiwa.okayama.jp", "asakuchi.okayama.jp", "bizen.okayama.jp", "hayashima.okayama.jp", "ibara.okayama.jp", "kagamino.okayama.jp", "kasaoka.okayama.jp", "kibichuo.okayama.jp", "kumenan.okayama.jp", "kurashiki.okayama.jp", "maniwa.okayama.jp", "misaki.okayama.jp", "nagi.okayama.jp", "niimi.okayama.jp", "nishiawakura.okayama.jp", "okayama.okayama.jp", "satosho.okayama.jp", "setouchi.okayama.jp", "shinjo.okayama.jp", "shoo.okayama.jp", "soja.okayama.jp", "takahashi.okayama.jp", "tamano.okayama.jp", "tsuyama.okayama.jp", "wake.okayama.jp", "yakage.okayama.jp", "aguni.okinawa.jp", "ginowan.okinawa.jp", "ginoza.okinawa.jp", "gushikami.okinawa.jp", "haebaru.okinawa.jp", "higashi.okinawa.jp", "hirara.okinawa.jp", "iheya.okinawa.jp", "ishigaki.okinawa.jp", "ishikawa.okinawa.jp", "itoman.okinawa.jp", "izena.okinawa.jp", "kadena.okinawa.jp", "kin.okinawa.jp", "kitadaito.okinawa.jp", "kitanakagusuku.okinawa.jp", "kumejima.okinawa.jp", "kunigami.okinawa.jp", "minamidaito.okinawa.jp", "motobu.okinawa.jp", "nago.okinawa.jp", "naha.okinawa.jp", "nakagusuku.okinawa.jp", "nakijin.okinawa.jp", "nanjo.okinawa.jp", "nishihara.okinawa.jp", "ogimi.okinawa.jp", "okinawa.okinawa.jp", "onna.okinawa.jp", "shimoji.okinawa.jp", "taketomi.okinawa.jp", "tarama.okinawa.jp", "tokashiki.okinawa.jp", "tomigusuku.okinawa.jp", "tonaki.okinawa.jp", "urasoe.okinawa.jp", "uruma.okinawa.jp", "yaese.okinawa.jp", "yomitan.okinawa.jp", "yonabaru.okinawa.jp", "yonaguni.okinawa.jp", "zamami.okinawa.jp", "abeno.osaka.jp", "chihayaakasaka.osaka.jp", "chuo.osaka.jp", "daito.osaka.jp", "fujiidera.osaka.jp", "habikino.osaka.jp", "hannan.osaka.jp", "higashiosaka.osaka.jp", "higashisumiyoshi.osaka.jp", "higashiyodogawa.osaka.jp", "hirakata.osaka.jp", "ibaraki.osaka.jp", "ikeda.osaka.jp", "izumi.osaka.jp", "izumiotsu.osaka.jp", "izumisano.osaka.jp", "kadoma.osaka.jp", "kaizuka.osaka.jp", "kanan.osaka.jp", "kashiwara.osaka.jp", "katano.osaka.jp", "kawachinagano.osaka.jp", "kishiwada.osaka.jp", "kita.osaka.jp", "kumatori.osaka.jp", "matsubara.osaka.jp", "minato.osaka.jp", "minoh.osaka.jp", "misaki.osaka.jp", "moriguchi.osaka.jp", "neyagawa.osaka.jp", "nishi.osaka.jp", "nose.osaka.jp", "osakasayama.osaka.jp", "sakai.osaka.jp", "sayama.osaka.jp", "sennan.osaka.jp", "settsu.osaka.jp", "shijonawate.osaka.jp", "shimamoto.osaka.jp", "suita.osaka.jp", "tadaoka.osaka.jp", "taishi.osaka.jp", "tajiri.osaka.jp", "takaishi.osaka.jp", "takatsuki.osaka.jp", "tondabayashi.osaka.jp", "toyonaka.osaka.jp", "toyono.osaka.jp", "yao.osaka.jp", "ariake.saga.jp", "arita.saga.jp", "fukudomi.saga.jp", "genkai.saga.jp", "hamatama.saga.jp", "hizen.saga.jp", "imari.saga.jp", "kamimine.saga.jp", "kanzaki.saga.jp", "karatsu.saga.jp", "kashima.saga.jp", "kitagata.saga.jp", "kitahata.saga.jp", "kiyama.saga.jp", "kouhoku.saga.jp", "kyuragi.saga.jp", "nishiarita.saga.jp", "ogi.saga.jp", "omachi.saga.jp", "ouchi.saga.jp", "saga.saga.jp", "shiroishi.saga.jp", "taku.saga.jp", "tara.saga.jp", "tosu.saga.jp", "yoshinogari.saga.jp", "arakawa.saitama.jp", "asaka.saitama.jp", "chichibu.saitama.jp", "fujimi.saitama.jp", "fujimino.saitama.jp", "fukaya.saitama.jp", "hanno.saitama.jp", "hanyu.saitama.jp", "hasuda.saitama.jp", "hatogaya.saitama.jp", "hatoyama.saitama.jp", "hidaka.saitama.jp", "higashichichibu.saitama.jp", "higashimatsuyama.saitama.jp", "honjo.saitama.jp", "ina.saitama.jp", "iruma.saitama.jp", "iwatsuki.saitama.jp", "kamiizumi.saitama.jp", "kamikawa.saitama.jp", "kamisato.saitama.jp", "kasukabe.saitama.jp", "kawagoe.saitama.jp", "kawaguchi.saitama.jp", "kawajima.saitama.jp", "kazo.saitama.jp", "kitamoto.saitama.jp", "koshigaya.saitama.jp", "kounosu.saitama.jp", "kuki.saitama.jp", "kumagaya.saitama.jp", "matsubushi.saitama.jp", "minano.saitama.jp", "misato.saitama.jp", "miyashiro.saitama.jp", "miyoshi.saitama.jp", "moroyama.saitama.jp", "nagatoro.saitama.jp", "namegawa.saitama.jp", "niiza.saitama.jp", "ogano.saitama.jp", "ogawa.saitama.jp", "ogose.saitama.jp", "okegawa.saitama.jp", "omiya.saitama.jp", "otaki.saitama.jp", "ranzan.saitama.jp", "ryokami.saitama.jp", "saitama.saitama.jp", "sakado.saitama.jp", "satte.saitama.jp", "sayama.saitama.jp", "shiki.saitama.jp", "shiraoka.saitama.jp", "soka.saitama.jp", "sugito.saitama.jp", "toda.saitama.jp", "tokigawa.saitama.jp", "tokorozawa.saitama.jp", "tsurugashima.saitama.jp", "urawa.saitama.jp", "warabi.saitama.jp", "yashio.saitama.jp", "yokoze.saitama.jp", "yono.saitama.jp", "yorii.saitama.jp", "yoshida.saitama.jp", "yoshikawa.saitama.jp", "yoshimi.saitama.jp", "aisho.shiga.jp", "gamo.shiga.jp", "higashiomi.shiga.jp", "hikone.shiga.jp", "koka.shiga.jp", "konan.shiga.jp", "kosei.shiga.jp", "koto.shiga.jp", "kusatsu.shiga.jp", "maibara.shiga.jp", "moriyama.shiga.jp", "nagahama.shiga.jp", "nishiazai.shiga.jp", "notogawa.shiga.jp", "omihachiman.shiga.jp", "otsu.shiga.jp", "ritto.shiga.jp", "ryuoh.shiga.jp", "takashima.shiga.jp", "takatsuki.shiga.jp", "torahime.shiga.jp", "toyosato.shiga.jp", "yasu.shiga.jp", "akagi.shimane.jp", "ama.shimane.jp", "gotsu.shimane.jp", "hamada.shimane.jp", "higashiizumo.shimane.jp", "hikawa.shimane.jp", "hikimi.shimane.jp", "izumo.shimane.jp", "kakinoki.shimane.jp", "masuda.shimane.jp", "matsue.shimane.jp", "misato.shimane.jp", "nishinoshima.shimane.jp", "ohda.shimane.jp", "okinoshima.shimane.jp", "okuizumo.shimane.jp", "shimane.shimane.jp", "tamayu.shimane.jp", "tsuwano.shimane.jp", "unnan.shimane.jp", "yakumo.shimane.jp", "yasugi.shimane.jp", "yatsuka.shimane.jp", "arai.shizuoka.jp", "atami.shizuoka.jp", "fuji.shizuoka.jp", "fujieda.shizuoka.jp", "fujikawa.shizuoka.jp", "fujinomiya.shizuoka.jp", "fukuroi.shizuoka.jp", "gotemba.shizuoka.jp", "haibara.shizuoka.jp", "hamamatsu.shizuoka.jp", "higashiizu.shizuoka.jp", "ito.shizuoka.jp", "iwata.shizuoka.jp", "izu.shizuoka.jp", "izunokuni.shizuoka.jp", "kakegawa.shizuoka.jp", "kannami.shizuoka.jp", "kawanehon.shizuoka.jp", "kawazu.shizuoka.jp", "kikugawa.shizuoka.jp", "kosai.shizuoka.jp", "makinohara.shizuoka.jp", "matsuzaki.shizuoka.jp", "minamiizu.shizuoka.jp", "mishima.shizuoka.jp", "morimachi.shizuoka.jp", "nishiizu.shizuoka.jp", "numazu.shizuoka.jp", "omaezaki.shizuoka.jp", "shimada.shizuoka.jp", "shimizu.shizuoka.jp", "shimoda.shizuoka.jp", "shizuoka.shizuoka.jp", "susono.shizuoka.jp", "yaizu.shizuoka.jp", "yoshida.shizuoka.jp", "ashikaga.tochigi.jp", "bato.tochigi.jp", "haga.tochigi.jp", "ichikai.tochigi.jp", "iwafune.tochigi.jp", "kaminokawa.tochigi.jp", "kanuma.tochigi.jp", "karasuyama.tochigi.jp", "kuroiso.tochigi.jp", "mashiko.tochigi.jp", "mibu.tochigi.jp", "moka.tochigi.jp", "motegi.tochigi.jp", "nasu.tochigi.jp", "nasushiobara.tochigi.jp", "nikko.tochigi.jp", "nishikata.tochigi.jp", "nogi.tochigi.jp", "ohira.tochigi.jp", "ohtawara.tochigi.jp", "oyama.tochigi.jp", "sakura.tochigi.jp", "sano.tochigi.jp", "shimotsuke.tochigi.jp", "shioya.tochigi.jp", "takanezawa.tochigi.jp", "tochigi.tochigi.jp", "tsuga.tochigi.jp", "ujiie.tochigi.jp", "utsunomiya.tochigi.jp", "yaita.tochigi.jp", "aizumi.tokushima.jp", "anan.tokushima.jp", "ichiba.tokushima.jp", "itano.tokushima.jp", "kainan.tokushima.jp", "komatsushima.tokushima.jp", "matsushige.tokushima.jp", "mima.tokushima.jp", "minami.tokushima.jp", "miyoshi.tokushima.jp", "mugi.tokushima.jp", "nakagawa.tokushima.jp", "naruto.tokushima.jp", "sanagochi.tokushima.jp", "shishikui.tokushima.jp", "tokushima.tokushima.jp", "wajiki.tokushima.jp", "adachi.tokyo.jp", "akiruno.tokyo.jp", "akishima.tokyo.jp", "aogashima.tokyo.jp", "arakawa.tokyo.jp", "bunkyo.tokyo.jp", "chiyoda.tokyo.jp", "chofu.tokyo.jp", "chuo.tokyo.jp", "edogawa.tokyo.jp", "fuchu.tokyo.jp", "fussa.tokyo.jp", "hachijo.tokyo.jp", "hachioji.tokyo.jp", "hamura.tokyo.jp", "higashikurume.tokyo.jp", "higashimurayama.tokyo.jp", "higashiyamato.tokyo.jp", "hino.tokyo.jp", "hinode.tokyo.jp", "hinohara.tokyo.jp", "inagi.tokyo.jp", "itabashi.tokyo.jp", "katsushika.tokyo.jp", "kita.tokyo.jp", "kiyose.tokyo.jp", "kodaira.tokyo.jp", "koganei.tokyo.jp", "kokubunji.tokyo.jp", "komae.tokyo.jp", "koto.tokyo.jp", "kouzushima.tokyo.jp", "kunitachi.tokyo.jp", "machida.tokyo.jp", "meguro.tokyo.jp", "minato.tokyo.jp", "mitaka.tokyo.jp", "mizuho.tokyo.jp", "musashimurayama.tokyo.jp", "musashino.tokyo.jp", "nakano.tokyo.jp", "nerima.tokyo.jp", "ogasawara.tokyo.jp", "okutama.tokyo.jp", "ome.tokyo.jp", "oshima.tokyo.jp", "ota.tokyo.jp", "setagaya.tokyo.jp", "shibuya.tokyo.jp", "shinagawa.tokyo.jp", "shinjuku.tokyo.jp", "suginami.tokyo.jp", "sumida.tokyo.jp", "tachikawa.tokyo.jp", "taito.tokyo.jp", "tama.tokyo.jp", "toshima.tokyo.jp", "chizu.tottori.jp", "hino.tottori.jp", "kawahara.tottori.jp", "koge.tottori.jp", "kotoura.tottori.jp", "misasa.tottori.jp", "nanbu.tottori.jp", "nichinan.tottori.jp", "sakaiminato.tottori.jp", "tottori.tottori.jp", "wakasa.tottori.jp", "yazu.tottori.jp", "yonago.tottori.jp", "asahi.toyama.jp", "fuchu.toyama.jp", "fukumitsu.toyama.jp", "funahashi.toyama.jp", "himi.toyama.jp", "imizu.toyama.jp", "inami.toyama.jp", "johana.toyama.jp", "kamiichi.toyama.jp", "kurobe.toyama.jp", "nakaniikawa.toyama.jp", "namerikawa.toyama.jp", "nanto.toyama.jp", "nyuzen.toyama.jp", "oyabe.toyama.jp", "taira.toyama.jp", "takaoka.toyama.jp", "tateyama.toyama.jp", "toga.toyama.jp", "tonami.toyama.jp", "toyama.toyama.jp", "unazuki.toyama.jp", "uozu.toyama.jp", "yamada.toyama.jp", "arida.wakayama.jp", "aridagawa.wakayama.jp", "gobo.wakayama.jp", "hashimoto.wakayama.jp", "hidaka.wakayama.jp", "hirogawa.wakayama.jp", "inami.wakayama.jp", "iwade.wakayama.jp", "kainan.wakayama.jp", "kamitonda.wakayama.jp", "katsuragi.wakayama.jp", "kimino.wakayama.jp", "kinokawa.wakayama.jp", "kitayama.wakayama.jp", "koya.wakayama.jp", "koza.wakayama.jp", "kozagawa.wakayama.jp", "kudoyama.wakayama.jp", "kushimoto.wakayama.jp", "mihama.wakayama.jp", "misato.wakayama.jp", "nachikatsuura.wakayama.jp", "shingu.wakayama.jp", "shirahama.wakayama.jp", "taiji.wakayama.jp", "tanabe.wakayama.jp", "wakayama.wakayama.jp", "yuasa.wakayama.jp", "yura.wakayama.jp", "asahi.yamagata.jp", "funagata.yamagata.jp", "higashine.yamagata.jp", "iide.yamagata.jp", "kahoku.yamagata.jp", "kaminoyama.yamagata.jp", "kaneyama.yamagata.jp", "kawanishi.yamagata.jp", "mamurogawa.yamagata.jp", "mikawa.yamagata.jp", "murayama.yamagata.jp", "nagai.yamagata.jp", "nakayama.yamagata.jp", "nanyo.yamagata.jp", "nishikawa.yamagata.jp", "obanazawa.yamagata.jp", "oe.yamagata.jp", "oguni.yamagata.jp", "ohkura.yamagata.jp", "oishida.yamagata.jp", "sagae.yamagata.jp", "sakata.yamagata.jp", "sakegawa.yamagata.jp", "shinjo.yamagata.jp", "shirataka.yamagata.jp", "shonai.yamagata.jp", "takahata.yamagata.jp", "tendo.yamagata.jp", "tozawa.yamagata.jp", "tsuruoka.yamagata.jp", "yamagata.yamagata.jp", "yamanobe.yamagata.jp", "yonezawa.yamagata.jp", "yuza.yamagata.jp", "abu.yamaguchi.jp", "hagi.yamaguchi.jp", "hikari.yamaguchi.jp", "hofu.yamaguchi.jp", "iwakuni.yamaguchi.jp", "kudamatsu.yamaguchi.jp", "mitou.yamaguchi.jp", "nagato.yamaguchi.jp", "oshima.yamaguchi.jp", "shimonoseki.yamaguchi.jp", "shunan.yamaguchi.jp", "tabuse.yamaguchi.jp", "tokuyama.yamaguchi.jp", "toyota.yamaguchi.jp", "ube.yamaguchi.jp", "yuu.yamaguchi.jp", "chuo.yamanashi.jp", "doshi.yamanashi.jp", "fuefuki.yamanashi.jp", "fujikawa.yamanashi.jp", "fujikawaguchiko.yamanashi.jp", "fujiyoshida.yamanashi.jp", "hayakawa.yamanashi.jp", "hokuto.yamanashi.jp", "ichikawamisato.yamanashi.jp", "kai.yamanashi.jp", "kofu.yamanashi.jp", "koshu.yamanashi.jp", "kosuge.yamanashi.jp", "minami-alps.yamanashi.jp", "minobu.yamanashi.jp", "nakamichi.yamanashi.jp", "nanbu.yamanashi.jp", "narusawa.yamanashi.jp", "nirasaki.yamanashi.jp", "nishikatsura.yamanashi.jp", "oshino.yamanashi.jp", "otsuki.yamanashi.jp", "showa.yamanashi.jp", "tabayama.yamanashi.jp", "tsuru.yamanashi.jp", "uenohara.yamanashi.jp", "yamanakako.yamanashi.jp", "yamanashi.yamanashi.jp", "*.ke", "kg", "org.kg", "net.kg", "com.kg", "edu.kg", "gov.kg", "mil.kg", "*.kh", "ki", "edu.ki", "biz.ki", "net.ki", "org.ki", "gov.ki", "info.ki", "com.ki", "km", "org.km", "nom.km", "gov.km", "prd.km", "tm.km", "edu.km", "mil.km", "ass.km", "com.km", "coop.km", "asso.km", "presse.km", "medecin.km", "notaires.km", "pharmaciens.km", "veterinaire.km", "gouv.km", "kn", "net.kn", "org.kn", "edu.kn", "gov.kn", "kp", "com.kp", "edu.kp", "gov.kp", "org.kp", "rep.kp", "tra.kp", "kr", "ac.kr", "co.kr", "es.kr", "go.kr", "hs.kr", "kg.kr", "mil.kr", "ms.kr", "ne.kr", "or.kr", "pe.kr", "re.kr", "sc.kr", "busan.kr", "chungbuk.kr", "chungnam.kr", "daegu.kr", "daejeon.kr", "gangwon.kr", "gwangju.kr", "gyeongbuk.kr", "gyeonggi.kr", "gyeongnam.kr", "incheon.kr", "jeju.kr", "jeonbuk.kr", "jeonnam.kr", "seoul.kr", "ulsan.kr", "*.kw", "ky", "edu.ky", "gov.ky", "com.ky", "org.ky", "net.ky", "kz", "org.kz", "edu.kz", "net.kz", "gov.kz", "mil.kz", "com.kz", "la", "int.la", "net.la", "info.la", "edu.la", "gov.la", "per.la", "com.la", "org.la", "lb", "com.lb", "edu.lb", "gov.lb", "net.lb", "org.lb", "lc", "com.lc", "net.lc", "co.lc", "org.lc", "edu.lc", "gov.lc", "li", "lk", "gov.lk", "sch.lk", "net.lk", "int.lk", "com.lk", "org.lk", "edu.lk", "ngo.lk", "soc.lk", "web.lk", "ltd.lk", "assn.lk", "grp.lk", "hotel.lk", "ac.lk", "lr", "com.lr", "edu.lr", "gov.lr", "org.lr", "net.lr", "ls", "co.ls", "org.ls", "lt", "gov.lt", "lu", "lv", "com.lv", "edu.lv", "gov.lv", "org.lv", "mil.lv", "id.lv", "net.lv", "asn.lv", "conf.lv", "ly", "com.ly", "net.ly", "gov.ly", "plc.ly", "edu.ly", "sch.ly", "med.ly", "org.ly", "id.ly", "ma", "co.ma", "net.ma", "gov.ma", "org.ma", "ac.ma", "press.ma", "mc", "tm.mc", "asso.mc", "md", "me", "co.me", "net.me", "org.me", "edu.me", "ac.me", "gov.me", "its.me", "priv.me", "mg", "org.mg", "nom.mg", "gov.mg", "prd.mg", "tm.mg", "edu.mg", "mil.mg", "com.mg", "mh", "mil", "mk", "com.mk", "org.mk", "net.mk", "edu.mk", "gov.mk", "inf.mk", "name.mk", "ml", "com.ml", "edu.ml", "gouv.ml", "gov.ml", "net.ml", "org.ml", "presse.ml", "*.mm", "mn", "gov.mn", "edu.mn", "org.mn", "mo", "com.mo", "net.mo", "org.mo", "edu.mo", "gov.mo", "mobi", "mp", "mq", "mr", "gov.mr", "ms", "com.ms", "edu.ms", "gov.ms", "net.ms", "org.ms", "mt", "com.mt", "edu.mt", "net.mt", "org.mt", "mu", "com.mu", "net.mu", "org.mu", "gov.mu", "ac.mu", "co.mu", "or.mu", "museum", "academy.museum", "agriculture.museum", "air.museum", "airguard.museum", "alabama.museum", "alaska.museum", "amber.museum", "ambulance.museum", "american.museum", "americana.museum", "americanantiques.museum", "americanart.museum", "amsterdam.museum", "and.museum", "annefrank.museum", "anthro.museum", "anthropology.museum", "antiques.museum", "aquarium.museum", "arboretum.museum", "archaeological.museum", "archaeology.museum", "architecture.museum", "art.museum", "artanddesign.museum", "artcenter.museum", "artdeco.museum", "arteducation.museum", "artgallery.museum", "arts.museum", "artsandcrafts.museum", "asmatart.museum", "assassination.museum", "assisi.museum", "association.museum", "astronomy.museum", "atlanta.museum", "austin.museum", "australia.museum", "automotive.museum", "aviation.museum", "axis.museum", "badajoz.museum", "baghdad.museum", "bahn.museum", "bale.museum", "baltimore.museum", "barcelona.museum", "baseball.museum", "basel.museum", "baths.museum", "bauern.museum", "beauxarts.museum", "beeldengeluid.museum", "bellevue.museum", "bergbau.museum", "berkeley.museum", "berlin.museum", "bern.museum", "bible.museum", "bilbao.museum", "bill.museum", "birdart.museum", "birthplace.museum", "bonn.museum", "boston.museum", "botanical.museum", "botanicalgarden.museum", "botanicgarden.museum", "botany.museum", "brandywinevalley.museum", "brasil.museum", "bristol.museum", "british.museum", "britishcolumbia.museum", "broadcast.museum", "brunel.museum", "brussel.museum", "brussels.museum", "bruxelles.museum", "building.museum", "burghof.museum", "bus.museum", "bushey.museum", "cadaques.museum", "california.museum", "cambridge.museum", "can.museum", "canada.museum", "capebreton.museum", "carrier.museum", "cartoonart.museum", "casadelamoneda.museum", "castle.museum", "castres.museum", "celtic.museum", "center.museum", "chattanooga.museum", "cheltenham.museum", "chesapeakebay.museum", "chicago.museum", "children.museum", "childrens.museum", "childrensgarden.museum", "chiropractic.museum", "chocolate.museum", "christiansburg.museum", "cincinnati.museum", "cinema.museum", "circus.museum", "civilisation.museum", "civilization.museum", "civilwar.museum", "clinton.museum", "clock.museum", "coal.museum", "coastaldefence.museum", "cody.museum", "coldwar.museum", "collection.museum", "colonialwilliamsburg.museum", "coloradoplateau.museum", "columbia.museum", "columbus.museum", "communication.museum", "communications.museum", "community.museum", "computer.museum", "computerhistory.museum", "xn--comunicaes-v6a2o.museum", "contemporary.museum", "contemporaryart.museum", "convent.museum", "copenhagen.museum", "corporation.museum", "xn--correios-e-telecomunicaes-ghc29a.museum", "corvette.museum", "costume.museum", "countryestate.museum", "county.museum", "crafts.museum", "cranbrook.museum", "creation.museum", "cultural.museum", "culturalcenter.museum", "culture.museum", "cyber.museum", "cymru.museum", "dali.museum", "dallas.museum", "database.museum", "ddr.museum", "decorativearts.museum", "delaware.museum", "delmenhorst.museum", "denmark.museum", "depot.museum", "design.museum", "detroit.museum", "dinosaur.museum", "discovery.museum", "dolls.museum", "donostia.museum", "durham.museum", "eastafrica.museum", "eastcoast.museum", "education.museum", "educational.museum", "egyptian.museum", "eisenbahn.museum", "elburg.museum", "elvendrell.museum", "embroidery.museum", "encyclopedic.museum", "england.museum", "entomology.museum", "environment.museum", "environmentalconservation.museum", "epilepsy.museum", "essex.museum", "estate.museum", "ethnology.museum", "exeter.museum", "exhibition.museum", "family.museum", "farm.museum", "farmequipment.museum", "farmers.museum", "farmstead.museum", "field.museum", "figueres.museum", "filatelia.museum", "film.museum", "fineart.museum", "finearts.museum", "finland.museum", "flanders.museum", "florida.museum", "force.museum", "fortmissoula.museum", "fortworth.museum", "foundation.museum", "francaise.museum", "frankfurt.museum", "franziskaner.museum", "freemasonry.museum", "freiburg.museum", "fribourg.museum", "frog.museum", "fundacio.museum", "furniture.museum", "gallery.museum", "garden.museum", "gateway.museum", "geelvinck.museum", "gemological.museum", "geology.museum", "georgia.museum", "giessen.museum", "glas.museum", "glass.museum", "gorge.museum", "grandrapids.museum", "graz.museum", "guernsey.museum", "halloffame.museum", "hamburg.museum", "handson.museum", "harvestcelebration.museum", "hawaii.museum", "health.museum", "heimatunduhren.museum", "hellas.museum", "helsinki.museum", "hembygdsforbund.museum", "heritage.museum", "histoire.museum", "historical.museum", "historicalsociety.museum", "historichouses.museum", "historisch.museum", "historisches.museum", "history.museum", "historyofscience.museum", "horology.museum", "house.museum", "humanities.museum", "illustration.museum", "imageandsound.museum", "indian.museum", "indiana.museum", "indianapolis.museum", "indianmarket.museum", "intelligence.museum", "interactive.museum", "iraq.museum", "iron.museum", "isleofman.museum", "jamison.museum", "jefferson.museum", "jerusalem.museum", "jewelry.museum", "jewish.museum", "jewishart.museum", "jfk.museum", "journalism.museum", "judaica.museum", "judygarland.museum", "juedisches.museum", "juif.museum", "karate.museum", "karikatur.museum", "kids.museum", "koebenhavn.museum", "koeln.museum", "kunst.museum", "kunstsammlung.museum", "kunstunddesign.museum", "labor.museum", "labour.museum", "lajolla.museum", "lancashire.museum", "landes.museum", "lans.museum", "xn--lns-qla.museum", "larsson.museum", "lewismiller.museum", "lincoln.museum", "linz.museum", "living.museum", "livinghistory.museum", "localhistory.museum", "london.museum", "losangeles.museum", "louvre.museum", "loyalist.museum", "lucerne.museum", "luxembourg.museum", "luzern.museum", "mad.museum", "madrid.museum", "mallorca.museum", "manchester.museum", "mansion.museum", "mansions.museum", "manx.museum", "marburg.museum", "maritime.museum", "maritimo.museum", "maryland.museum", "marylhurst.museum", "media.museum", "medical.museum", "medizinhistorisches.museum", "meeres.museum", "memorial.museum", "mesaverde.museum", "michigan.museum", "midatlantic.museum", "military.museum", "mill.museum", "miners.museum", "mining.museum", "minnesota.museum", "missile.museum", "missoula.museum", "modern.museum", "moma.museum", "money.museum", "monmouth.museum", "monticello.museum", "montreal.museum", "moscow.museum", "motorcycle.museum", "muenchen.museum", "muenster.museum", "mulhouse.museum", "muncie.museum", "museet.museum", "museumcenter.museum", "museumvereniging.museum", "music.museum", "national.museum", "nationalfirearms.museum", "nationalheritage.museum", "nativeamerican.museum", "naturalhistory.museum", "naturalhistorymuseum.museum", "naturalsciences.museum", "nature.museum", "naturhistorisches.museum", "natuurwetenschappen.museum", "naumburg.museum", "naval.museum", "nebraska.museum", "neues.museum", "newhampshire.museum", "newjersey.museum", "newmexico.museum", "newport.museum", "newspaper.museum", "newyork.museum", "niepce.museum", "norfolk.museum", "north.museum", "nrw.museum", "nuernberg.museum", "nuremberg.museum", "nyc.museum", "nyny.museum", "oceanographic.museum", "oceanographique.museum", "omaha.museum", "online.museum", "ontario.museum", "openair.museum", "oregon.museum", "oregontrail.museum", "otago.museum", "oxford.museum", "pacific.museum", "paderborn.museum", "palace.museum", "paleo.museum", "palmsprings.museum", "panama.museum", "paris.museum", "pasadena.museum", "pharmacy.museum", "philadelphia.museum", "philadelphiaarea.museum", "philately.museum", "phoenix.museum", "photography.museum", "pilots.museum", "pittsburgh.museum", "planetarium.museum", "plantation.museum", "plants.museum", "plaza.museum", "portal.museum", "portland.museum", "portlligat.museum", "posts-and-telecommunications.museum", "preservation.museum", "presidio.museum", "press.museum", "project.museum", "public.museum", "pubol.museum", "quebec.museum", "railroad.museum", "railway.museum", "research.museum", "resistance.museum", "riodejaneiro.museum", "rochester.museum", "rockart.museum", "roma.museum", "russia.museum", "saintlouis.museum", "salem.museum", "salvadordali.museum", "salzburg.museum", "sandiego.museum", "sanfrancisco.museum", "santabarbara.museum", "santacruz.museum", "santafe.museum", "saskatchewan.museum", "satx.museum", "savannahga.museum", "schlesisches.museum", "schoenbrunn.museum", "schokoladen.museum", "school.museum", "schweiz.museum", "science.museum", "scienceandhistory.museum", "scienceandindustry.museum", "sciencecenter.museum", "sciencecenters.museum", "science-fiction.museum", "sciencehistory.museum", "sciences.museum", "sciencesnaturelles.museum", "scotland.museum", "seaport.museum", "settlement.museum", "settlers.museum", "shell.museum", "sherbrooke.museum", "sibenik.museum", "silk.museum", "ski.museum", "skole.museum", "society.museum", "sologne.museum", "soundandvision.museum", "southcarolina.museum", "southwest.museum", "space.museum", "spy.museum", "square.museum", "stadt.museum", "stalbans.museum", "starnberg.museum", "state.museum", "stateofdelaware.museum", "station.museum", "steam.museum", "steiermark.museum", "stjohn.museum", "stockholm.museum", "stpetersburg.museum", "stuttgart.museum", "suisse.museum", "surgeonshall.museum", "surrey.museum", "svizzera.museum", "sweden.museum", "sydney.museum", "tank.museum", "tcm.museum", "technology.museum", "telekommunikation.museum", "television.museum", "texas.museum", "textile.museum", "theater.museum", "time.museum", "timekeeping.museum", "topology.museum", "torino.museum", "touch.museum", "town.museum", "transport.museum", "tree.museum", "trolley.museum", "trust.museum", "trustee.museum", "uhren.museum", "ulm.museum", "undersea.museum", "university.museum", "usa.museum", "usantiques.museum", "usarts.museum", "uscountryestate.museum", "usculture.museum", "usdecorativearts.museum", "usgarden.museum", "ushistory.museum", "ushuaia.museum", "uslivinghistory.museum", "utah.museum", "uvic.museum", "valley.museum", "vantaa.museum", "versailles.museum", "viking.museum", "village.museum", "virginia.museum", "virtual.museum", "virtuel.museum", "vlaanderen.museum", "volkenkunde.museum", "wales.museum", "wallonie.museum", "war.museum", "washingtondc.museum", "watchandclock.museum", "watch-and-clock.museum", "western.museum", "westfalen.museum", "whaling.museum", "wildlife.museum", "williamsburg.museum", "windmill.museum", "workshop.museum", "york.museum", "yorkshire.museum", "yosemite.museum", "youth.museum", "zoological.museum", "zoology.museum", "xn--9dbhblg6di.museum", "xn--h1aegh.museum", "mv", "aero.mv", "biz.mv", "com.mv", "coop.mv", "edu.mv", "gov.mv", "info.mv", "int.mv", "mil.mv", "museum.mv", "name.mv", "net.mv", "org.mv", "pro.mv", "mw", "ac.mw", "biz.mw", "co.mw", "com.mw", "coop.mw", "edu.mw", "gov.mw", "int.mw", "museum.mw", "net.mw", "org.mw", "mx", "com.mx", "org.mx", "gob.mx", "edu.mx", "net.mx", "my", "com.my", "net.my", "org.my", "gov.my", "edu.my", "mil.my", "name.my", "*.mz", "!teledata.mz", "na", "info.na", "pro.na", "name.na", "school.na", "or.na", "dr.na", "us.na", "mx.na", "ca.na", "in.na", "cc.na", "tv.na", "ws.na", "mobi.na", "co.na", "com.na", "org.na", "name", "nc", "asso.nc", "ne", "net", "nf", "com.nf", "net.nf", "per.nf", "rec.nf", "web.nf", "arts.nf", "firm.nf", "info.nf", "other.nf", "store.nf", "ng", "com.ng", "edu.ng", "name.ng", "net.ng", "org.ng", "sch.ng", "gov.ng", "mil.ng", "mobi.ng", "*.ni", "nl", "bv.nl", "no", "fhs.no", "vgs.no", "fylkesbibl.no", "folkebibl.no", "museum.no", "idrett.no", "priv.no", "mil.no", "stat.no", "dep.no", "kommune.no", "herad.no", "aa.no", "ah.no", "bu.no", "fm.no", "hl.no", "hm.no", "jan-mayen.no", "mr.no", "nl.no", "nt.no", "of.no", "ol.no", "oslo.no", "rl.no", "sf.no", "st.no", "svalbard.no", "tm.no", "tr.no", "va.no", "vf.no", "gs.aa.no", "gs.ah.no", "gs.bu.no", "gs.fm.no", "gs.hl.no", "gs.hm.no", "gs.jan-mayen.no", "gs.mr.no", "gs.nl.no", "gs.nt.no", "gs.of.no", "gs.ol.no", "gs.oslo.no", "gs.rl.no", "gs.sf.no", "gs.st.no", "gs.svalbard.no", "gs.tm.no", "gs.tr.no", "gs.va.no", "gs.vf.no", "akrehamn.no", "xn--krehamn-dxa.no", "algard.no", "xn--lgrd-poac.no", "arna.no", "brumunddal.no", "bryne.no", "bronnoysund.no", "xn--brnnysund-m8ac.no", "drobak.no", "xn--drbak-wua.no", "egersund.no", "fetsund.no", "floro.no", "xn--flor-jra.no", "fredrikstad.no", "hokksund.no", "honefoss.no", "xn--hnefoss-q1a.no", "jessheim.no", "jorpeland.no", "xn--jrpeland-54a.no", "kirkenes.no", "kopervik.no", "krokstadelva.no", "langevag.no", "xn--langevg-jxa.no", "leirvik.no", "mjondalen.no", "xn--mjndalen-64a.no", "mo-i-rana.no", "mosjoen.no", "xn--mosjen-eya.no", "nesoddtangen.no", "orkanger.no", "osoyro.no", "xn--osyro-wua.no", "raholt.no", "xn--rholt-mra.no", "sandnessjoen.no", "xn--sandnessjen-ogb.no", "skedsmokorset.no", "slattum.no", "spjelkavik.no", "stathelle.no", "stavern.no", "stjordalshalsen.no", "xn--stjrdalshalsen-sqb.no", "tananger.no", "tranby.no", "vossevangen.no", "afjord.no", "xn--fjord-lra.no", "agdenes.no", "al.no", "xn--l-1fa.no", "alesund.no", "xn--lesund-hua.no", "alstahaug.no", "alta.no", "xn--lt-liac.no", "alaheadju.no", "xn--laheadju-7ya.no", "alvdal.no", "amli.no", "xn--mli-tla.no", "amot.no", "xn--mot-tla.no", "andebu.no", "andoy.no", "xn--andy-ira.no", "andasuolo.no", "ardal.no", "xn--rdal-poa.no", "aremark.no", "arendal.no", "xn--s-1fa.no", "aseral.no", "xn--seral-lra.no", "asker.no", "askim.no", "askvoll.no", "askoy.no", "xn--asky-ira.no", "asnes.no", "xn--snes-poa.no", "audnedaln.no", "aukra.no", "aure.no", "aurland.no", "aurskog-holand.no", "xn--aurskog-hland-jnb.no", "austevoll.no", "austrheim.no", "averoy.no", "xn--avery-yua.no", "balestrand.no", "ballangen.no", "balat.no", "xn--blt-elab.no", "balsfjord.no", "bahccavuotna.no", "xn--bhccavuotna-k7a.no", "bamble.no", "bardu.no", "beardu.no", "beiarn.no", "bajddar.no", "xn--bjddar-pta.no", "baidar.no", "xn--bidr-5nac.no", "berg.no", "bergen.no", "berlevag.no", "xn--berlevg-jxa.no", "bearalvahki.no", "xn--bearalvhki-y4a.no", "bindal.no", "birkenes.no", "bjarkoy.no", "xn--bjarky-fya.no", "bjerkreim.no", "bjugn.no", "bodo.no", "xn--bod-2na.no", "badaddja.no", "xn--bdddj-mrabd.no", "budejju.no", "bokn.no", "bremanger.no", "bronnoy.no", "xn--brnny-wuac.no", "bygland.no", "bykle.no", "barum.no", "xn--brum-voa.no", "bo.telemark.no", "xn--b-5ga.telemark.no", "bo.nordland.no", "xn--b-5ga.nordland.no", "bievat.no", "xn--bievt-0qa.no", "bomlo.no", "xn--bmlo-gra.no", "batsfjord.no", "xn--btsfjord-9za.no", "bahcavuotna.no", "xn--bhcavuotna-s4a.no", "dovre.no", "drammen.no", "drangedal.no", "dyroy.no", "xn--dyry-ira.no", "donna.no", "xn--dnna-gra.no", "eid.no", "eidfjord.no", "eidsberg.no", "eidskog.no", "eidsvoll.no", "eigersund.no", "elverum.no", "enebakk.no", "engerdal.no", "etne.no", "etnedal.no", "evenes.no", "evenassi.no", "xn--eveni-0qa01ga.no", "evje-og-hornnes.no", "farsund.no", "fauske.no", "fuossko.no", "fuoisku.no", "fedje.no", "fet.no", "finnoy.no", "xn--finny-yua.no", "fitjar.no", "fjaler.no", "fjell.no", "flakstad.no", "flatanger.no", "flekkefjord.no", "flesberg.no", "flora.no", "fla.no", "xn--fl-zia.no", "folldal.no", "forsand.no", "fosnes.no", "frei.no", "frogn.no", "froland.no", "frosta.no", "frana.no", "xn--frna-woa.no", "froya.no", "xn--frya-hra.no", "fusa.no", "fyresdal.no", "forde.no", "xn--frde-gra.no", "gamvik.no", "gangaviika.no", "xn--ggaviika-8ya47h.no", "gaular.no", "gausdal.no", "gildeskal.no", "xn--gildeskl-g0a.no", "giske.no", "gjemnes.no", "gjerdrum.no", "gjerstad.no", "gjesdal.no", "gjovik.no", "xn--gjvik-wua.no", "gloppen.no", "gol.no", "gran.no", "grane.no", "granvin.no", "gratangen.no", "grimstad.no", "grong.no", "kraanghke.no", "xn--kranghke-b0a.no", "grue.no", "gulen.no", "hadsel.no", "halden.no", "halsa.no", "hamar.no", "hamaroy.no", "habmer.no", "xn--hbmer-xqa.no", "hapmir.no", "xn--hpmir-xqa.no", "hammerfest.no", "hammarfeasta.no", "xn--hmmrfeasta-s4ac.no", "haram.no", "hareid.no", "harstad.no", "hasvik.no", "aknoluokta.no", "xn--koluokta-7ya57h.no", "hattfjelldal.no", "aarborte.no", "haugesund.no", "hemne.no", "hemnes.no", "hemsedal.no", "heroy.more-og-romsdal.no", "xn--hery-ira.xn--mre-og-romsdal-qqb.no", "heroy.nordland.no", "xn--hery-ira.nordland.no", "hitra.no", "hjartdal.no", "hjelmeland.no", "hobol.no", "xn--hobl-ira.no", "hof.no", "hol.no", "hole.no", "holmestrand.no", "holtalen.no", "xn--holtlen-hxa.no", "hornindal.no", "horten.no", "hurdal.no", "hurum.no", "hvaler.no", "hyllestad.no", "hagebostad.no", "xn--hgebostad-g3a.no", "hoyanger.no", "xn--hyanger-q1a.no", "hoylandet.no", "xn--hylandet-54a.no", "ha.no", "xn--h-2fa.no", "ibestad.no", "inderoy.no", "xn--indery-fya.no", "iveland.no", "jevnaker.no", "jondal.no", "jolster.no", "xn--jlster-bya.no", "karasjok.no", "karasjohka.no", "xn--krjohka-hwab49j.no", "karlsoy.no", "galsa.no", "xn--gls-elac.no", "karmoy.no", "xn--karmy-yua.no", "kautokeino.no", "guovdageaidnu.no", "klepp.no", "klabu.no", "xn--klbu-woa.no", "kongsberg.no", "kongsvinger.no", "kragero.no", "xn--krager-gya.no", "kristiansand.no", "kristiansund.no", "krodsherad.no", "xn--krdsherad-m8a.no", "kvalsund.no", "rahkkeravju.no", "xn--rhkkervju-01af.no", "kvam.no", "kvinesdal.no", "kvinnherad.no", "kviteseid.no", "kvitsoy.no", "xn--kvitsy-fya.no", "kvafjord.no", "xn--kvfjord-nxa.no", "giehtavuoatna.no", "kvanangen.no", "xn--kvnangen-k0a.no", "navuotna.no", "xn--nvuotna-hwa.no", "kafjord.no", "xn--kfjord-iua.no", "gaivuotna.no", "xn--givuotna-8ya.no", "larvik.no", "lavangen.no", "lavagis.no", "loabat.no", "xn--loabt-0qa.no", "lebesby.no", "davvesiida.no", "leikanger.no", "leirfjord.no", "leka.no", "leksvik.no", "lenvik.no", "leangaviika.no", "xn--leagaviika-52b.no", "lesja.no", "levanger.no", "lier.no", "lierne.no", "lillehammer.no", "lillesand.no", "lindesnes.no", "lindas.no", "xn--linds-pra.no", "lom.no", "loppa.no", "lahppi.no", "xn--lhppi-xqa.no", "lund.no", "lunner.no", "luroy.no", "xn--lury-ira.no", "luster.no", "lyngdal.no", "lyngen.no", "ivgu.no", "lardal.no", "lerdal.no", "xn--lrdal-sra.no", "lodingen.no", "xn--ldingen-q1a.no", "lorenskog.no", "xn--lrenskog-54a.no", "loten.no", "xn--lten-gra.no", "malvik.no", "masoy.no", "xn--msy-ula0h.no", "muosat.no", "xn--muost-0qa.no", "mandal.no", "marker.no", "marnardal.no", "masfjorden.no", "meland.no", "meldal.no", "melhus.no", "meloy.no", "xn--mely-ira.no", "meraker.no", "xn--merker-kua.no", "moareke.no", "xn--moreke-jua.no", "midsund.no", "midtre-gauldal.no", "modalen.no", "modum.no", "molde.no", "moskenes.no", "moss.no", "mosvik.no", "malselv.no", "xn--mlselv-iua.no", "malatvuopmi.no", "xn--mlatvuopmi-s4a.no", "namdalseid.no", "aejrie.no", "namsos.no", "namsskogan.no", "naamesjevuemie.no", "xn--nmesjevuemie-tcba.no", "laakesvuemie.no", "nannestad.no", "narvik.no", "narviika.no", "naustdal.no", "nedre-eiker.no", "nes.akershus.no", "nes.buskerud.no", "nesna.no", "nesodden.no", "nesseby.no", "unjarga.no", "xn--unjrga-rta.no", "nesset.no", "nissedal.no", "nittedal.no", "nord-aurdal.no", "nord-fron.no", "nord-odal.no", "norddal.no", "nordkapp.no", "davvenjarga.no", "xn--davvenjrga-y4a.no", "nordre-land.no", "nordreisa.no", "raisa.no", "xn--risa-5na.no", "nore-og-uvdal.no", "notodden.no", "naroy.no", "xn--nry-yla5g.no", "notteroy.no", "xn--nttery-byae.no", "odda.no", "oksnes.no", "xn--ksnes-uua.no", "oppdal.no", "oppegard.no", "xn--oppegrd-ixa.no", "orkdal.no", "orland.no", "xn--rland-uua.no", "orskog.no", "xn--rskog-uua.no", "orsta.no", "xn--rsta-fra.no", "os.hedmark.no", "os.hordaland.no", "osen.no", "osteroy.no", "xn--ostery-fya.no", "ostre-toten.no", "xn--stre-toten-zcb.no", "overhalla.no", "ovre-eiker.no", "xn--vre-eiker-k8a.no", "oyer.no", "xn--yer-zna.no", "oygarden.no", "xn--ygarden-p1a.no", "oystre-slidre.no", "xn--ystre-slidre-ujb.no", "porsanger.no", "porsangu.no", "xn--porsgu-sta26f.no", "porsgrunn.no", "radoy.no", "xn--rady-ira.no", "rakkestad.no", "rana.no", "ruovat.no", "randaberg.no", "rauma.no", "rendalen.no", "rennebu.no", "rennesoy.no", "xn--rennesy-v1a.no", "rindal.no", "ringebu.no", "ringerike.no", "ringsaker.no", "rissa.no", "risor.no", "xn--risr-ira.no", "roan.no", "rollag.no", "rygge.no", "ralingen.no", "xn--rlingen-mxa.no", "rodoy.no", "xn--rdy-0nab.no", "romskog.no", "xn--rmskog-bya.no", "roros.no", "xn--rros-gra.no", "rost.no", "xn--rst-0na.no", "royken.no", "xn--ryken-vua.no", "royrvik.no", "xn--ryrvik-bya.no", "rade.no", "xn--rde-ula.no", "salangen.no", "siellak.no", "saltdal.no", "salat.no", "xn--slt-elab.no", "xn--slat-5na.no", "samnanger.no", "sande.more-og-romsdal.no", "sande.xn--mre-og-romsdal-qqb.no", "sande.vestfold.no", "sandefjord.no", "sandnes.no", "sandoy.no", "xn--sandy-yua.no", "sarpsborg.no", "sauda.no", "sauherad.no", "sel.no", "selbu.no", "selje.no", "seljord.no", "sigdal.no", "siljan.no", "sirdal.no", "skaun.no", "skedsmo.no", "ski.no", "skien.no", "skiptvet.no", "skjervoy.no", "xn--skjervy-v1a.no", "skierva.no", "xn--skierv-uta.no", "skjak.no", "xn--skjk-soa.no", "skodje.no", "skanland.no", "xn--sknland-fxa.no", "skanit.no", "xn--sknit-yqa.no", "smola.no", "xn--smla-hra.no", "snillfjord.no", "snasa.no", "xn--snsa-roa.no", "snoasa.no", "snaase.no", "xn--snase-nra.no", "sogndal.no", "sokndal.no", "sola.no", "solund.no", "songdalen.no", "sortland.no", "spydeberg.no", "stange.no", "stavanger.no", "steigen.no", "steinkjer.no", "stjordal.no", "xn--stjrdal-s1a.no", "stokke.no", "stor-elvdal.no", "stord.no", "stordal.no", "storfjord.no", "omasvuotna.no", "strand.no", "stranda.no", "stryn.no", "sula.no", "suldal.no", "sund.no", "sunndal.no", "surnadal.no", "sveio.no", "svelvik.no", "sykkylven.no", "sogne.no", "xn--sgne-gra.no", "somna.no", "xn--smna-gra.no", "sondre-land.no", "xn--sndre-land-0cb.no", "sor-aurdal.no", "xn--sr-aurdal-l8a.no", "sor-fron.no", "xn--sr-fron-q1a.no", "sor-odal.no", "xn--sr-odal-q1a.no", "sor-varanger.no", "xn--sr-varanger-ggb.no", "matta-varjjat.no", "xn--mtta-vrjjat-k7af.no", "sorfold.no", "xn--srfold-bya.no", "sorreisa.no", "xn--srreisa-q1a.no", "sorum.no", "xn--srum-gra.no", "tana.no", "deatnu.no", "time.no", "tingvoll.no", "tinn.no", "tjeldsund.no", "dielddanuorri.no", "tjome.no", "xn--tjme-hra.no", "tokke.no", "tolga.no", "torsken.no", "tranoy.no", "xn--trany-yua.no", "tromso.no", "xn--troms-zua.no", "tromsa.no", "romsa.no", "trondheim.no", "troandin.no", "trysil.no", "trana.no", "xn--trna-woa.no", "trogstad.no", "xn--trgstad-r1a.no", "tvedestrand.no", "tydal.no", "tynset.no", "tysfjord.no", "divtasvuodna.no", "divttasvuotna.no", "tysnes.no", "tysvar.no", "xn--tysvr-vra.no", "tonsberg.no", "xn--tnsberg-q1a.no", "ullensaker.no", "ullensvang.no", "ulvik.no", "utsira.no", "vadso.no", "xn--vads-jra.no", "cahcesuolo.no", "xn--hcesuolo-7ya35b.no", "vaksdal.no", "valle.no", "vang.no", "vanylven.no", "vardo.no", "xn--vard-jra.no", "varggat.no", "xn--vrggt-xqad.no", "vefsn.no", "vaapste.no", "vega.no", "vegarshei.no", "xn--vegrshei-c0a.no", "vennesla.no", "verdal.no", "verran.no", "vestby.no", "vestnes.no", "vestre-slidre.no", "vestre-toten.no", "vestvagoy.no", "xn--vestvgy-ixa6o.no", "vevelstad.no", "vik.no", "vikna.no", "vindafjord.no", "volda.no", "voss.no", "varoy.no", "xn--vry-yla5g.no", "vagan.no", "xn--vgan-qoa.no", "voagat.no", "vagsoy.no", "xn--vgsy-qoa0j.no", "vaga.no", "xn--vg-yiab.no", "valer.ostfold.no", "xn--vler-qoa.xn--stfold-9xa.no", "valer.hedmark.no", "xn--vler-qoa.hedmark.no", "*.np", "nr", "biz.nr", "info.nr", "gov.nr", "edu.nr", "org.nr", "net.nr", "com.nr", "nu", "nz", "ac.nz", "co.nz", "cri.nz", "geek.nz", "gen.nz", "govt.nz", "health.nz", "iwi.nz", "kiwi.nz", "maori.nz", "mil.nz", "xn--mori-qsa.nz", "net.nz", "org.nz", "parliament.nz", "school.nz", "om", "co.om", "com.om", "edu.om", "gov.om", "med.om", "museum.om", "net.om", "org.om", "pro.om", "org", "pa", "ac.pa", "gob.pa", "com.pa", "org.pa", "sld.pa", "edu.pa", "net.pa", "ing.pa", "abo.pa", "med.pa", "nom.pa", "pe", "edu.pe", "gob.pe", "nom.pe", "mil.pe", "org.pe", "com.pe", "net.pe", "pf", "com.pf", "org.pf", "edu.pf", "*.pg", "ph", "com.ph", "net.ph", "org.ph", "gov.ph", "edu.ph", "ngo.ph", "mil.ph", "i.ph", "pk", "com.pk", "net.pk", "edu.pk", "org.pk", "fam.pk", "biz.pk", "web.pk", "gov.pk", "gob.pk", "gok.pk", "gon.pk", "gop.pk", "gos.pk", "info.pk", "pl", "com.pl", "net.pl", "org.pl", "aid.pl", "agro.pl", "atm.pl", "auto.pl", "biz.pl", "edu.pl", "gmina.pl", "gsm.pl", "info.pl", "mail.pl", "miasta.pl", "media.pl", "mil.pl", "nieruchomosci.pl", "nom.pl", "pc.pl", "powiat.pl", "priv.pl", "realestate.pl", "rel.pl", "sex.pl", "shop.pl", "sklep.pl", "sos.pl", "szkola.pl", "targi.pl", "tm.pl", "tourism.pl", "travel.pl", "turystyka.pl", "gov.pl", "ap.gov.pl", "ic.gov.pl", "is.gov.pl", "us.gov.pl", "kmpsp.gov.pl", "kppsp.gov.pl", "kwpsp.gov.pl", "psp.gov.pl", "wskr.gov.pl", "kwp.gov.pl", "mw.gov.pl", "ug.gov.pl", "um.gov.pl", "umig.gov.pl", "ugim.gov.pl", "upow.gov.pl", "uw.gov.pl", "starostwo.gov.pl", "pa.gov.pl", "po.gov.pl", "psse.gov.pl", "pup.gov.pl", "rzgw.gov.pl", "sa.gov.pl", "so.gov.pl", "sr.gov.pl", "wsa.gov.pl", "sko.gov.pl", "uzs.gov.pl", "wiih.gov.pl", "winb.gov.pl", "pinb.gov.pl", "wios.gov.pl", "witd.gov.pl", "wzmiuw.gov.pl", "piw.gov.pl", "wiw.gov.pl", "griw.gov.pl", "wif.gov.pl", "oum.gov.pl", "sdn.gov.pl", "zp.gov.pl", "uppo.gov.pl", "mup.gov.pl", "wuoz.gov.pl", "konsulat.gov.pl", "oirm.gov.pl", "augustow.pl", "babia-gora.pl", "bedzin.pl", "beskidy.pl", "bialowieza.pl", "bialystok.pl", "bielawa.pl", "bieszczady.pl", "boleslawiec.pl", "bydgoszcz.pl", "bytom.pl", "cieszyn.pl", "czeladz.pl", "czest.pl", "dlugoleka.pl", "elblag.pl", "elk.pl", "glogow.pl", "gniezno.pl", "gorlice.pl", "grajewo.pl", "ilawa.pl", "jaworzno.pl", "jelenia-gora.pl", "jgora.pl", "kalisz.pl", "kazimierz-dolny.pl", "karpacz.pl", "kartuzy.pl", "kaszuby.pl", "katowice.pl", "kepno.pl", "ketrzyn.pl", "klodzko.pl", "kobierzyce.pl", "kolobrzeg.pl", "konin.pl", "konskowola.pl", "kutno.pl", "lapy.pl", "lebork.pl", "legnica.pl", "lezajsk.pl", "limanowa.pl", "lomza.pl", "lowicz.pl", "lubin.pl", "lukow.pl", "malbork.pl", "malopolska.pl", "mazowsze.pl", "mazury.pl", "mielec.pl", "mielno.pl", "mragowo.pl", "naklo.pl", "nowaruda.pl", "nysa.pl", "olawa.pl", "olecko.pl", "olkusz.pl", "olsztyn.pl", "opoczno.pl", "opole.pl", "ostroda.pl", "ostroleka.pl", "ostrowiec.pl", "ostrowwlkp.pl", "pila.pl", "pisz.pl", "podhale.pl", "podlasie.pl", "polkowice.pl", "pomorze.pl", "pomorskie.pl", "prochowice.pl", "pruszkow.pl", "przeworsk.pl", "pulawy.pl", "radom.pl", "rawa-maz.pl", "rybnik.pl", "rzeszow.pl", "sanok.pl", "sejny.pl", "slask.pl", "slupsk.pl", "sosnowiec.pl", "stalowa-wola.pl", "skoczow.pl", "starachowice.pl", "stargard.pl", "suwalki.pl", "swidnica.pl", "swiebodzin.pl", "swinoujscie.pl", "szczecin.pl", "szczytno.pl", "tarnobrzeg.pl", "tgory.pl", "turek.pl", "tychy.pl", "ustka.pl", "walbrzych.pl", "warmia.pl", "warszawa.pl", "waw.pl", "wegrow.pl", "wielun.pl", "wlocl.pl", "wloclawek.pl", "wodzislaw.pl", "wolomin.pl", "wroclaw.pl", "zachpomor.pl", "zagan.pl", "zarow.pl", "zgora.pl", "zgorzelec.pl", "pm", "pn", "gov.pn", "co.pn", "org.pn", "edu.pn", "net.pn", "post", "pr", "com.pr", "net.pr", "org.pr", "gov.pr", "edu.pr", "isla.pr", "pro.pr", "biz.pr", "info.pr", "name.pr", "est.pr", "prof.pr", "ac.pr", "pro", "aca.pro", "bar.pro", "cpa.pro", "jur.pro", "law.pro", "med.pro", "eng.pro", "ps", "edu.ps", "gov.ps", "sec.ps", "plo.ps", "com.ps", "org.ps", "net.ps", "pt", "net.pt", "gov.pt", "org.pt", "edu.pt", "int.pt", "publ.pt", "com.pt", "nome.pt", "pw", "co.pw", "ne.pw", "or.pw", "ed.pw", "go.pw", "belau.pw", "py", "com.py", "coop.py", "edu.py", "gov.py", "mil.py", "net.py", "org.py", "qa", "com.qa", "edu.qa", "gov.qa", "mil.qa", "name.qa", "net.qa", "org.qa", "sch.qa", "re", "com.re", "asso.re", "nom.re", "ro", "com.ro", "org.ro", "tm.ro", "nt.ro", "nom.ro", "info.ro", "rec.ro", "arts.ro", "firm.ro", "store.ro", "www.ro", "rs", "co.rs", "org.rs", "edu.rs", "ac.rs", "gov.rs", "in.rs", "ru", "ac.ru", "com.ru", "edu.ru", "int.ru", "net.ru", "org.ru", "pp.ru", "adygeya.ru", "altai.ru", "amur.ru", "arkhangelsk.ru", "astrakhan.ru", "bashkiria.ru", "belgorod.ru", "bir.ru", "bryansk.ru", "buryatia.ru", "cbg.ru", "chel.ru", "chelyabinsk.ru", "chita.ru", "chukotka.ru", "chuvashia.ru", "dagestan.ru", "dudinka.ru", "e-burg.ru", "grozny.ru", "irkutsk.ru", "ivanovo.ru", "izhevsk.ru", "jar.ru", "joshkar-ola.ru", "kalmykia.ru", "kaluga.ru", "kamchatka.ru", "karelia.ru", "kazan.ru", "kchr.ru", "kemerovo.ru", "khabarovsk.ru", "khakassia.ru", "khv.ru", "kirov.ru", "koenig.ru", "komi.ru", "kostroma.ru", "krasnoyarsk.ru", "kuban.ru", "kurgan.ru", "kursk.ru", "lipetsk.ru", "magadan.ru", "mari.ru", "mari-el.ru", "marine.ru", "mordovia.ru", "msk.ru", "murmansk.ru", "nalchik.ru", "nnov.ru", "nov.ru", "novosibirsk.ru", "nsk.ru", "omsk.ru", "orenburg.ru", "oryol.ru", "palana.ru", "penza.ru", "perm.ru", "ptz.ru", "rnd.ru", "ryazan.ru", "sakhalin.ru", "samara.ru", "saratov.ru", "simbirsk.ru", "smolensk.ru", "spb.ru", "stavropol.ru", "stv.ru", "surgut.ru", "tambov.ru", "tatarstan.ru", "tom.ru", "tomsk.ru", "tsaritsyn.ru", "tsk.ru", "tula.ru", "tuva.ru", "tver.ru", "tyumen.ru", "udm.ru", "udmurtia.ru", "ulan-ude.ru", "vladikavkaz.ru", "vladimir.ru", "vladivostok.ru", "volgograd.ru", "vologda.ru", "voronezh.ru", "vrn.ru", "vyatka.ru", "yakutia.ru", "yamal.ru", "yaroslavl.ru", "yekaterinburg.ru", "yuzhno-sakhalinsk.ru", "amursk.ru", "baikal.ru", "cmw.ru", "fareast.ru", "jamal.ru", "kms.ru", "k-uralsk.ru", "kustanai.ru", "kuzbass.ru", "magnitka.ru", "mytis.ru", "nakhodka.ru", "nkz.ru", "norilsk.ru", "oskol.ru", "pyatigorsk.ru", "rubtsovsk.ru", "snz.ru", "syzran.ru", "vdonsk.ru", "zgrad.ru", "gov.ru", "mil.ru", "test.ru", "rw", "gov.rw", "net.rw", "edu.rw", "ac.rw", "com.rw", "co.rw", "int.rw", "mil.rw", "gouv.rw", "sa", "com.sa", "net.sa", "org.sa", "gov.sa", "med.sa", "pub.sa", "edu.sa", "sch.sa", "sb", "com.sb", "edu.sb", "gov.sb", "net.sb", "org.sb", "sc", "com.sc", "gov.sc", "net.sc", "org.sc", "edu.sc", "sd", "com.sd", "net.sd", "org.sd", "edu.sd", "med.sd", "tv.sd", "gov.sd", "info.sd", "se", "a.se", "ac.se", "b.se", "bd.se", "brand.se", "c.se", "d.se", "e.se", "f.se", "fh.se", "fhsk.se", "fhv.se", "g.se", "h.se", "i.se", "k.se", "komforb.se", "kommunalforbund.se", "komvux.se", "l.se", "lanbib.se", "m.se", "n.se", "naturbruksgymn.se", "o.se", "org.se", "p.se", "parti.se", "pp.se", "press.se", "r.se", "s.se", "t.se", "tm.se", "u.se", "w.se", "x.se", "y.se", "z.se", "sg", "com.sg", "net.sg", "org.sg", "gov.sg", "edu.sg", "per.sg", "sh", "com.sh", "net.sh", "gov.sh", "org.sh", "mil.sh", "si", "sj", "sk", "sl", "com.sl", "net.sl", "edu.sl", "gov.sl", "org.sl", "sm", "sn", "art.sn", "com.sn", "edu.sn", "gouv.sn", "org.sn", "perso.sn", "univ.sn", "so", "com.so", "net.so", "org.so", "sr", "st", "co.st", "com.st", "consulado.st", "edu.st", "embaixada.st", "gov.st", "mil.st", "net.st", "org.st", "principe.st", "saotome.st", "store.st", "su", "adygeya.su", "arkhangelsk.su", "balashov.su", "bashkiria.su", "bryansk.su", "dagestan.su", "grozny.su", "ivanovo.su", "kalmykia.su", "kaluga.su", "karelia.su", "khakassia.su", "krasnodar.su", "kurgan.su", "lenug.su", "mordovia.su", "msk.su", "murmansk.su", "nalchik.su", "nov.su", "obninsk.su", "penza.su", "pokrovsk.su", "sochi.su", "spb.su", "togliatti.su", "troitsk.su", "tula.su", "tuva.su", "vladikavkaz.su", "vladimir.su", "vologda.su", "sv", "com.sv", "edu.sv", "gob.sv", "org.sv", "red.sv", "sx", "gov.sx", "sy", "edu.sy", "gov.sy", "net.sy", "mil.sy", "com.sy", "org.sy", "sz", "co.sz", "ac.sz", "org.sz", "tc", "td", "tel", "tf", "tg", "th", "ac.th", "co.th", "go.th", "in.th", "mi.th", "net.th", "or.th", "tj", "ac.tj", "biz.tj", "co.tj", "com.tj", "edu.tj", "go.tj", "gov.tj", "int.tj", "mil.tj", "name.tj", "net.tj", "nic.tj", "org.tj", "test.tj", "web.tj", "tk", "tl", "gov.tl", "tm", "com.tm", "co.tm", "org.tm", "net.tm", "nom.tm", "gov.tm", "mil.tm", "edu.tm", "tn", "com.tn", "ens.tn", "fin.tn", "gov.tn", "ind.tn", "intl.tn", "nat.tn", "net.tn", "org.tn", "info.tn", "perso.tn", "tourism.tn", "edunet.tn", "rnrt.tn", "rns.tn", "rnu.tn", "mincom.tn", "agrinet.tn", "defense.tn", "turen.tn", "to", "com.to", "gov.to", "net.to", "org.to", "edu.to", "mil.to", "tp", "tr", "com.tr", "info.tr", "biz.tr", "net.tr", "org.tr", "web.tr", "gen.tr", "tv.tr", "av.tr", "dr.tr", "bbs.tr", "name.tr", "tel.tr", "gov.tr", "bel.tr", "pol.tr", "mil.tr", "k12.tr", "edu.tr", "kep.tr", "nc.tr", "gov.nc.tr", "travel", "tt", "co.tt", "com.tt", "org.tt", "net.tt", "biz.tt", "info.tt", "pro.tt", "int.tt", "coop.tt", "jobs.tt", "mobi.tt", "travel.tt", "museum.tt", "aero.tt", "name.tt", "gov.tt", "edu.tt", "tv", "tw", "edu.tw", "gov.tw", "mil.tw", "com.tw", "net.tw", "org.tw", "idv.tw", "game.tw", "ebiz.tw", "club.tw", "xn--zf0ao64a.tw", "xn--uc0atv.tw", "xn--czrw28b.tw", "tz", "ac.tz", "co.tz", "go.tz", "hotel.tz", "info.tz", "me.tz", "mil.tz", "mobi.tz", "ne.tz", "or.tz", "sc.tz", "tv.tz", "ua", "com.ua", "edu.ua", "gov.ua", "in.ua", "net.ua", "org.ua", "cherkassy.ua", "cherkasy.ua", "chernigov.ua", "chernihiv.ua", "chernivtsi.ua", "chernovtsy.ua", "ck.ua", "cn.ua", "cr.ua", "crimea.ua", "cv.ua", "dn.ua", "dnepropetrovsk.ua", "dnipropetrovsk.ua", "dominic.ua", "donetsk.ua", "dp.ua", "if.ua", "ivano-frankivsk.ua", "kh.ua", "kharkiv.ua", "kharkov.ua", "kherson.ua", "khmelnitskiy.ua", "khmelnytskyi.ua", "kiev.ua", "kirovograd.ua", "km.ua", "kr.ua", "krym.ua", "ks.ua", "kv.ua", "kyiv.ua", "lg.ua", "lt.ua", "lugansk.ua", "lutsk.ua", "lv.ua", "lviv.ua", "mk.ua", "mykolaiv.ua", "nikolaev.ua", "od.ua", "odesa.ua", "odessa.ua", "pl.ua", "poltava.ua", "rivne.ua", "rovno.ua", "rv.ua", "sb.ua", "sebastopol.ua", "sevastopol.ua", "sm.ua", "sumy.ua", "te.ua", "ternopil.ua", "uz.ua", "uzhgorod.ua", "vinnica.ua", "vinnytsia.ua", "vn.ua", "volyn.ua", "yalta.ua", "zaporizhzhe.ua", "zaporizhzhia.ua", "zhitomir.ua", "zhytomyr.ua", "zp.ua", "zt.ua", "co.ua", "pp.ua", "ug", "co.ug", "or.ug", "ac.ug", "sc.ug", "go.ug", "ne.ug", "com.ug", "org.ug", "uk", "ac.uk", "co.uk", "gov.uk", "ltd.uk", "me.uk", "net.uk", "nhs.uk", "org.uk", "plc.uk", "police.uk", "*.sch.uk", "us", "dni.us", "fed.us", "isa.us", "kids.us", "nsn.us", "ak.us", "al.us", "ar.us", "as.us", "az.us", "ca.us", "co.us", "ct.us", "dc.us", "de.us", "fl.us", "ga.us", "gu.us", "hi.us", "ia.us", "id.us", "il.us", "in.us", "ks.us", "ky.us", "la.us", "ma.us", "md.us", "me.us", "mi.us", "mn.us", "mo.us", "ms.us", "mt.us", "nc.us", "nd.us", "ne.us", "nh.us", "nj.us", "nm.us", "nv.us", "ny.us", "oh.us", "ok.us", "or.us", "pa.us", "pr.us", "ri.us", "sc.us", "sd.us", "tn.us", "tx.us", "ut.us", "vi.us", "vt.us", "va.us", "wa.us", "wi.us", "wv.us", "wy.us", "k12.ak.us", "k12.al.us", "k12.ar.us", "k12.as.us", "k12.az.us", "k12.ca.us", "k12.co.us", "k12.ct.us", "k12.dc.us", "k12.de.us", "k12.fl.us", "k12.ga.us", "k12.gu.us", "k12.ia.us", "k12.id.us", "k12.il.us", "k12.in.us", "k12.ks.us", "k12.ky.us", "k12.la.us", "k12.ma.us", "k12.md.us", "k12.me.us", "k12.mi.us", "k12.mn.us", "k12.mo.us", "k12.ms.us", "k12.mt.us", "k12.nc.us", "k12.ne.us", "k12.nh.us", "k12.nj.us", "k12.nm.us", "k12.nv.us", "k12.ny.us", "k12.oh.us", "k12.ok.us", "k12.or.us", "k12.pa.us", "k12.pr.us", "k12.ri.us", "k12.sc.us", "k12.tn.us", "k12.tx.us", "k12.ut.us", "k12.vi.us", "k12.vt.us", "k12.va.us", "k12.wa.us", "k12.wi.us", "k12.wy.us", "cc.ak.us", "cc.al.us", "cc.ar.us", "cc.as.us", "cc.az.us", "cc.ca.us", "cc.co.us", "cc.ct.us", "cc.dc.us", "cc.de.us", "cc.fl.us", "cc.ga.us", "cc.gu.us", "cc.hi.us", "cc.ia.us", "cc.id.us", "cc.il.us", "cc.in.us", "cc.ks.us", "cc.ky.us", "cc.la.us", "cc.ma.us", "cc.md.us", "cc.me.us", "cc.mi.us", "cc.mn.us", "cc.mo.us", "cc.ms.us", "cc.mt.us", "cc.nc.us", "cc.nd.us", "cc.ne.us", "cc.nh.us", "cc.nj.us", "cc.nm.us", "cc.nv.us", "cc.ny.us", "cc.oh.us", "cc.ok.us", "cc.or.us", "cc.pa.us", "cc.pr.us", "cc.ri.us", "cc.sc.us", "cc.sd.us", "cc.tn.us", "cc.tx.us", "cc.ut.us", "cc.vi.us", "cc.vt.us", "cc.va.us", "cc.wa.us", "cc.wi.us", "cc.wv.us", "cc.wy.us", "lib.ak.us", "lib.al.us", "lib.ar.us", "lib.as.us", "lib.az.us", "lib.ca.us", "lib.co.us", "lib.ct.us", "lib.dc.us", "lib.de.us", "lib.fl.us", "lib.ga.us", "lib.gu.us", "lib.hi.us", "lib.ia.us", "lib.id.us", "lib.il.us", "lib.in.us", "lib.ks.us", "lib.ky.us", "lib.la.us", "lib.ma.us", "lib.md.us", "lib.me.us", "lib.mi.us", "lib.mn.us", "lib.mo.us", "lib.ms.us", "lib.mt.us", "lib.nc.us", "lib.nd.us", "lib.ne.us", "lib.nh.us", "lib.nj.us", "lib.nm.us", "lib.nv.us", "lib.ny.us", "lib.oh.us", "lib.ok.us", "lib.or.us", "lib.pa.us", "lib.pr.us", "lib.ri.us", "lib.sc.us", "lib.sd.us", "lib.tn.us", "lib.tx.us", "lib.ut.us", "lib.vi.us", "lib.vt.us", "lib.va.us", "lib.wa.us", "lib.wi.us", "lib.wy.us", "pvt.k12.ma.us", "chtr.k12.ma.us", "paroch.k12.ma.us", "uy", "com.uy", "edu.uy", "gub.uy", "mil.uy", "net.uy", "org.uy", "uz", "co.uz", "com.uz", "net.uz", "org.uz", "va", "vc", "com.vc", "net.vc", "org.vc", "gov.vc", "mil.vc", "edu.vc", "ve", "arts.ve", "co.ve", "com.ve", "e12.ve", "edu.ve", "firm.ve", "gob.ve", "gov.ve", "info.ve", "int.ve", "mil.ve", "net.ve", "org.ve", "rec.ve", "store.ve", "tec.ve", "web.ve", "vg", "vi", "co.vi", "com.vi", "k12.vi", "net.vi", "org.vi", "vn", "com.vn", "net.vn", "org.vn", "edu.vn", "gov.vn", "int.vn", "ac.vn", "biz.vn", "info.vn", "name.vn", "pro.vn", "health.vn", "vu", "com.vu", "edu.vu", "net.vu", "org.vu", "wf", "ws", "com.ws", "net.ws", "org.ws", "gov.ws", "edu.ws", "yt", "xn--mgbaam7a8h", "xn--y9a3aq", "xn--54b7fta0cc", "xn--90ais", "xn--fiqs8s", "xn--fiqz9s", "xn--lgbbat1ad8j", "xn--wgbh1c", "xn--node", "xn--qxam", "xn--j6w193g", "xn--h2brj9c", "xn--mgbbh1a71e", "xn--fpcrj9c3d", "xn--gecrj9c", "xn--s9brj9c", "xn--45brj9c", "xn--xkc2dl3a5ee0h", "xn--mgba3a4f16a", "xn--mgba3a4fra", "xn--mgbtx2b", "xn--mgbayh7gpa", "xn--3e0b707e", "xn--80ao21a", "xn--fzc2c9e2c", "xn--xkc2al3hye2a", "xn--mgbc0a9azcg", "xn--d1alf", "xn--l1acc", "xn--mix891f", "xn--mix082f", "xn--mgbx4cd0ab", "xn--mgb9awbf", "xn--mgbai9azgqp6j", "xn--mgbai9a5eva00b", "xn--ygbi2ammx", "xn--90a3ac", "xn--o1ac.xn--90a3ac", "xn--c1avg.xn--90a3ac", "xn--90azh.xn--90a3ac", "xn--d1at.xn--90a3ac", "xn--o1ach.xn--90a3ac", "xn--80au.xn--90a3ac", "xn--p1ai", "xn--wgbl6a", "xn--mgberp4a5d4ar", "xn--mgberp4a5d4a87g", "xn--mgbqly7c0a67fbc", "xn--mgbqly7cvafr", "xn--mgbpl2fh", "xn--yfro4i67o", "xn--clchc0ea0b2g2a9gcd", "xn--ogbpf8fl", "xn--mgbtf8fl", "xn--o3cw4h", "xn--pgbs0dh", "xn--kpry57d", "xn--kprw13d", "xn--nnx388a", "xn--j1amh", "xn--mgb2ddes", "xxx", "*.ye", "ac.za", "agrica.za", "alt.za", "co.za", "edu.za", "gov.za", "grondar.za", "law.za", "mil.za", "net.za", "ngo.za", "nis.za", "nom.za", "org.za", "school.za", "tm.za", "web.za", "*.zm", "*.zw", "aaa", "aarp", "abb", "abbott", "able", "abogado", "academy", "accenture", "accountant", "accountants", "aco", "active", "actor", "ads", "adult", "aeg", "aetna", "afl", "africa", "africamagic", "agakhan", "agency", "aig", "airforce", "airtel", "akdn", "alibaba", "alipay", "allfinanz", "ally", "alsace", "amica", "amsterdam", "analytics", "android", "anquan", "apartments", "app", "apple", "aquarelle", "aramco", "archi", "army", "arte", "associates", "attorney", "auction", "audi", "audible", "audio", "author", "auto", "autos", "avianca", "aws", "axa", "azure", "baby", "baidu", "band", "bank", "bar", "barcelona", "barclaycard", "barclays", "barefoot", "bargains", "bauhaus", "bayern", "bbc", "bbva", "bcg", "bcn", "beats", "beer", "bentley", "berlin", "best", "bet", "bharti", "bible", "bid", "bike", "bing", "bingo", "bio", "black", "blackfriday", "blog", "bloomberg", "blue", "bms", "bmw", "bnl", "bnpparibas", "boats", "bom", "bond", "boo", "boots", "bosch", "bostik", "bot", "boutique", "bradesco", "bridgestone", "broadway", "broker", "brother", "brussels", "budapest", "build", "builders", "business", "buy", "buzz", "bzh", "cab", "cafe", "cal", "call", "camera", "camp", "cancerresearch", "canon", "capetown", "capital", "car", "caravan", "cards", "care", "career", "careers", "cars", "cartier", "casa", "cash", "casino", "catering", "cba", "cbn", "cbre", "ceb", "center", "ceo", "cern", "cfa", "cfd", "chanel", "channel", "chase", "chat", "cheap", "chintai", "chloe", "christmas", "chrome", "church", "cipriani", "circle", "cisco", "citic", "city", "cityeats", "claims", "cleaning", "click", "clinic", "clothing", "cloud", "club", "clubmed", "coach", "codes", "coffee", "college", "cologne", "commbank", "community", "company", "computer", "comsec", "condos", "construction", "consulting", "contact", "contractors", "cooking", "cookingchannel", "cool", "corsica", "country", "coupon", "coupons", "courses", "credit", "creditcard", "creditunion", "cricket", "crown", "crs", "cruises", "csc", "cuisinella", "cymru", "cyou", "dabur", "dad", "dance", "date", "dating", "datsun", "day", "dclk", "dds", "deal", "dealer", "deals", "degree", "delivery", "dell", "delta", "democrat", "dental", "dentist", "desi", "design", "dev", "diamonds", "diet", "digital", "direct", "directory", "discount", "dnp", "docs", "dog", "doha", "domains", "doosan", "dot", "download", "drive", "dstv", "dtv", "dubai", "dunlop", "dupont", "durban", "dvag", "earth", "eat", "edeka", "education", "email", "emerck", "energy", "engineer", "engineering", "enterprises", "epson", "equipment", "erni", "esq", "estate", "eurovision", "eus", "events", "everbank", "exchange", "expert", "exposed", "express", "extraspace", "fage", "fail", "fairwinds", "faith", "family", "fan", "fans", "farm", "fashion", "fast", "feedback", "ferrero", "film", "final", "finance", "financial", "fire", "firestone", "firmdale", "fish", "fishing", "fit", "fitness", "flickr", "flights", "florist", "flowers", "flsmidth", "fly", "foo", "foodnetwork", "football", "ford", "forex", "forsale", "forum", "foundation", "frl", "frogans", "frontdoor", "frontier", "fund", "furniture", "futbol", "fyi", "gal", "gallery", "gallo", "gallup", "game", "games", "garden", "gbiz", "gdn", "gea", "gent", "genting", "ggee", "gift", "gifts", "gives", "giving", "glass", "gle", "global", "globo", "gmail", "gmo", "gmx", "gold", "goldpoint", "golf", "goo", "goodyear", "goog", "google", "gop", "got", "gotv", "grainger", "graphics", "gratis", "green", "gripe", "group", "gucci", "guge", "guide", "guitars", "guru", "hamburg", "hangout", "haus", "hdfcbank", "health", "healthcare", "help", "helsinki", "here", "hermes", "hgtv", "hiphop", "hitachi", "hiv", "hkt", "hockey", "holdings", "holiday", "homedepot", "homes", "honda", "horse", "host", "hosting", "hoteles", "hotmail", "house", "how", "hsbc", "htc", "ibm", "icbc", "ice", "icu", "ifm", "iinet", "imdb", "immo", "immobilien", "industries", "infiniti", "ing", "ink", "institute", "insurance", "insure", "international", "investments", "ipiranga", "irish", "iselect", "ist", "istanbul", "itau", "iwc", "jaguar", "java", "jcb", "jcp", "jetzt", "jewelry", "jio", "jlc", "jll", "jmp", "jnj", "joburg", "jot", "joy", "jpmorgan", "jprs", "juegos", "kaufen", "kddi", "kerryhotels", "kerrylogistics", "kerryproperties", "kfh", "kim", "kinder", "kindle", "kitchen", "kiwi", "koeln", "komatsu", "kpmg", "kpn", "krd", "kred", "kuokgroup", "kyknet", "kyoto", "lacaixa", "lamborghini", "lancaster", "land", "landrover", "lasalle", "lat", "latrobe", "law", "lawyer", "lds", "lease", "leclerc", "legal", "lexus", "lgbt", "liaison", "lidl", "life", "lifeinsurance", "lifestyle", "lighting", "like", "limited", "limo", "lincoln", "linde", "link", "lipsy", "live", "lixil", "loan", "loans", "locker", "locus", "lol", "london", "lotte", "lotto", "love", "ltd", "ltda", "lupin", "luxe", "luxury", "madrid", "maif", "maison", "makeup", "man", "management", "mango", "market", "marketing", "markets", "marriott", "mba", "media", "meet", "melbourne", "meme", "memorial", "men", "menu", "meo", "metlife", "miami", "microsoft", "mini", "mit", "mlb", "mls", "mma", "mnet", "mobily", "moda", "moe", "moi", "mom", "monash", "money", "montblanc", "mormon", "mortgage", "moscow", "moto", "motorcycles", "mov", "movie", "movistar", "mtn", "mtpc", "mtr", "multichoice", "mutual", "mutuelle", "mzansimagic", "nadex", "nagoya", "naspers", "natura", "navy", "nec", "netbank", "netflix", "network", "neustar", "new", "news", "next", "nextdirect", "nexus", "ngo", "nhk", "nico", "nikon", "ninja", "nissan", "nokia", "northwesternmutual", "norton", "now", "nowruz", "nowtv", "nra", "nrw", "ntt", "nyc", "obi", "observer", "office", "okinawa", "olayan", "olayangroup", "ollo", "omega", "one", "ong", "onl", "online", "ooo", "oracle", "orange", "organic", "orientexpress", "osaka", "otsuka", "ott", "ovh", "page", "pamperedchef", "panerai", "paris", "pars", "partners", "parts", "party", "passagens", "payu", "pccw", "pet", "pharmacy", "philips", "photo", "photography", "photos", "physio", "piaget", "pics", "pictet", "pictures", "pid", "pin", "ping", "pink", "pizza", "place", "play", "playstation", "plumbing", "plus", "pnc", "pohl", "poker", "porn", "praxi", "press", "prime", "prod", "productions", "prof", "promo", "properties", "property", "protection", "pub", "qpon", "quebec", "quest", "racing", "read", "realtor", "realty", "recipes", "red", "redstone", "redumbrella", "rehab", "reise", "reisen", "reit", "reliance", "ren", "rent", "rentals", "repair", "report", "republican", "rest", "restaurant", "review", "reviews", "rexroth", "rich", "richardli", "ricoh", "ril", "rio", "rip", "rocher", "rocks", "rodeo", "room", "rsvp", "ruhr", "run", "rwe", "ryukyu", "saarland", "safe", "safety", "sakura", "sale", "salon", "samsung", "sandvik", "sandvikcoromant", "sanofi", "sap", "sapo", "sarl", "sas", "save", "saxo", "sbi", "sbs", "sca", "scb", "schmidt", "scholarships", "school", "schule", "schwarz", "science", "scor", "scot", "seat", "security", "seek", "sener", "services", "sew", "sex", "sexy", "sharp", "shaw", "shia", "shiksha", "shoes", "shouji", "show", "shriram", "silk", "sina", "singles", "site", "ski", "skin", "sky", "skype", "smile", "sncf", "soccer", "social", "softbank", "software", "sohu", "solar", "solutions", "song", "sony", "soy", "space", "spiegel", "spot", "spreadbetting", "srl", "stada", "star", "starhub", "statebank", "statoil", "stc", "stcgroup", "stockholm", "storage", "store", "studio", "study", "style", "sucks", "supersport", "supplies", "supply", "support", "surf", "surgery", "suzuki", "swatch", "swiss", "sydney", "symantec", "systems", "tab", "taipei", "talk", "taobao", "tatamotors", "tatar", "tattoo", "tax", "taxi", "tci", "tdk", "team", "tech", "technology", "telecity", "telefonica", "temasek", "tennis", "teva", "thd", "theater", "theatre", "theguardian", "tickets", "tienda", "tiffany", "tips", "tires", "tirol", "tmall", "today", "tokyo", "tools", "top", "toray", "toshiba", "tours", "town", "toyota", "toys", "trade", "trading", "training", "travelchannel", "travelers", "travelersinsurance", "trust", "trv", "tube", "tui", "tunes", "tushu", "tvs", "ubs", "university", "uno", "uol", "ups", "vacations", "vana", "vegas", "ventures", "versicherung", "vet", "viajes", "video", "vig", "viking", "villas", "vin", "vip", "virgin", "vision", "vista", "vistaprint", "viva", "vlaanderen", "vodka", "volkswagen", "vote", "voting", "voto", "voyage", "vuelos", "wales", "walter", "wang", "wanggou", "warman", "watch", "watches", "weather", "weatherchannel", "webcam", "weber", "website", "wed", "wedding", "weibo", "weir", "whoswho", "wien", "wiki", "williamhill", "win", "windows", "wine", "wme", "work", "works", "world", "wtc", "wtf", "xbox", "xerox", "xihuan", "xin", "xn--11b4c3d", "xn--1ck2e1b", "xn--1qqw23a", "xn--30rr7y", "xn--3bst00m", "xn--3ds443g", "xn--3oq18vl8pn36a", "xn--3pxu8k", "xn--42c2d9a", "xn--45q11c", "xn--4gbrim", "xn--55qw42g", "xn--55qx5d", "xn--5tzm5g", "xn--6frz82g", "xn--6qq986b3xl", "xn--80adxhks", "xn--80asehdb", "xn--80aswg", "xn--8y0a063a", "xn--9dbq2a", "xn--9et52u", "xn--9krt00a", "xn--b4w605ferd", "xn--bck1b9a5dre4c", "xn--c1avg", "xn--c2br7g", "xn--cck2b3b", "xn--cg4bki", "xn--czr694b", "xn--czrs0t", "xn--czru2d", "xn--d1acj3b", "xn--eckvdtc9d", "xn--efvy88h", "xn--estv75g", "xn--fct429k", "xn--fhbei", "xn--fiq228c5hs", "xn--fiq64b", "xn--fjq720a", "xn--flw351e", "xn--fzys8d69uvgm", "xn--g2xx48c", "xn--gckr3f0f", "xn--hxt814e", "xn--i1b6b1a6a2e", "xn--imr513n", "xn--io0a7i", "xn--j1aef", "xn--jlq61u9w7b", "xn--jvr189m", "xn--kcrx77d1x4a", "xn--kpu716f", "xn--kput3i", "xn--mgba3a3ejt", "xn--mgba7c0bbn0a", "xn--mgbab2bd", "xn--mgbb9fbpob", "xn--mgbt3dhd", "xn--mk1bu44c", "xn--mxtq1m", "xn--ngbc5azd", "xn--ngbe9e0a", "xn--nqv7f", "xn--nqv7fs00ema", "xn--nyqy26a", "xn--p1acf", "xn--pbt977c", "xn--pssy2u", "xn--q9jyb4c", "xn--qcka1pmc", "xn--rhqv96g", "xn--rovu88b", "xn--ses554g", "xn--t60b56a", "xn--tckwe", "xn--unup4y", "xn--vermgensberater-ctb", "xn--vermgensberatung-pwb", "xn--vhquv", "xn--vuq861b", "xn--w4r85el8fhu5dnra", "xn--xhq521b", "xn--zfr164b", "xperia", "xyz", "yachts", "yahoo", "yamaxun", "yandex", "yodobashi", "yoga", "yokohama", "you", "youtube", "yun", "zappos", "zara", "zero", "zip", "zippo", "zone", "zuerich", "cloudfront.net", "ap-northeast-1.compute.amazonaws.com", "ap-southeast-1.compute.amazonaws.com", "ap-southeast-2.compute.amazonaws.com", "cn-north-1.compute.amazonaws.cn", "compute.amazonaws.cn", "compute.amazonaws.com", "compute-1.amazonaws.com", "eu-west-1.compute.amazonaws.com", "eu-central-1.compute.amazonaws.com", "sa-east-1.compute.amazonaws.com", "us-east-1.amazonaws.com", "us-gov-west-1.compute.amazonaws.com", "us-west-1.compute.amazonaws.com", "us-west-2.compute.amazonaws.com", "z-1.compute-1.amazonaws.com", "z-2.compute-1.amazonaws.com", "elasticbeanstalk.com", "elb.amazonaws.com", "s3.amazonaws.com", "s3-ap-northeast-1.amazonaws.com", "s3-ap-southeast-1.amazonaws.com", "s3-ap-southeast-2.amazonaws.com", "s3-external-1.amazonaws.com", "s3-external-2.amazonaws.com", "s3-fips-us-gov-west-1.amazonaws.com", "s3-eu-central-1.amazonaws.com", "s3-eu-west-1.amazonaws.com", "s3-sa-east-1.amazonaws.com", "s3-us-gov-west-1.amazonaws.com", "s3-us-west-1.amazonaws.com", "s3-us-west-2.amazonaws.com", "s3.cn-north-1.amazonaws.com.cn", "s3.eu-central-1.amazonaws.com", "betainabox.com", "ae.org", "ar.com", "br.com", "cn.com", "com.de", "com.se", "de.com", "eu.com", "gb.com", "gb.net", "hu.com", "hu.net", "jp.net", "jpn.com", "kr.com", "mex.com", "no.com", "qc.com", "ru.com", "sa.com", "se.com", "se.net", "uk.com", "uk.net", "us.com", "uy.com", "za.bz", "za.com", "africa.com", "gr.com", "in.net", "us.org", "co.com", "c.la", "cloudcontrolled.com", "cloudcontrolapp.com", "co.ca", "c.cdn77.org", "cdn77-ssl.net", "r.cdn77.net", "rsc.cdn77.org", "ssl.origin.cdn77-secure.org", "co.nl", "co.no", "*.platform.sh", "cupcake.is", "dreamhosters.com", "duckdns.org", "dyndns-at-home.com", "dyndns-at-work.com", "dyndns-blog.com", "dyndns-free.com", "dyndns-home.com", "dyndns-ip.com", "dyndns-mail.com", "dyndns-office.com", "dyndns-pics.com", "dyndns-remote.com", "dyndns-server.com", "dyndns-web.com", "dyndns-wiki.com", "dyndns-work.com", "dyndns.biz", "dyndns.info", "dyndns.org", "dyndns.tv", "at-band-camp.net", "ath.cx", "barrel-of-knowledge.info", "barrell-of-knowledge.info", "better-than.tv", "blogdns.com", "blogdns.net", "blogdns.org", "blogsite.org", "boldlygoingnowhere.org", "broke-it.net", "buyshouses.net", "cechire.com", "dnsalias.com", "dnsalias.net", "dnsalias.org", "dnsdojo.com", "dnsdojo.net", "dnsdojo.org", "does-it.net", "doesntexist.com", "doesntexist.org", "dontexist.com", "dontexist.net", "dontexist.org", "doomdns.com", "doomdns.org", "dvrdns.org", "dyn-o-saur.com", "dynalias.com", "dynalias.net", "dynalias.org", "dynathome.net", "dyndns.ws", "endofinternet.net", "endofinternet.org", "endoftheinternet.org", "est-a-la-maison.com", "est-a-la-masion.com", "est-le-patron.com", "est-mon-blogueur.com", "for-better.biz", "for-more.biz", "for-our.info", "for-some.biz", "for-the.biz", "forgot.her.name", "forgot.his.name", "from-ak.com", "from-al.com", "from-ar.com", "from-az.net", "from-ca.com", "from-co.net", "from-ct.com", "from-dc.com", "from-de.com", "from-fl.com", "from-ga.com", "from-hi.com", "from-ia.com", "from-id.com", "from-il.com", "from-in.com", "from-ks.com", "from-ky.com", "from-la.net", "from-ma.com", "from-md.com", "from-me.org", "from-mi.com", "from-mn.com", "from-mo.com", "from-ms.com", "from-mt.com", "from-nc.com", "from-nd.com", "from-ne.com", "from-nh.com", "from-nj.com", "from-nm.com", "from-nv.com", "from-ny.net", "from-oh.com", "from-ok.com", "from-or.com", "from-pa.com", "from-pr.com", "from-ri.com", "from-sc.com", "from-sd.com", "from-tn.com", "from-tx.com", "from-ut.com", "from-va.com", "from-vt.com", "from-wa.com", "from-wi.com", "from-wv.com", "from-wy.com", "ftpaccess.cc", "fuettertdasnetz.de", "game-host.org", "game-server.cc", "getmyip.com", "gets-it.net", "go.dyndns.org", "gotdns.com", "gotdns.org", "groks-the.info", "groks-this.info", "ham-radio-op.net", "here-for-more.info", "hobby-site.com", "hobby-site.org", "home.dyndns.org", "homedns.org", "homeftp.net", "homeftp.org", "homeip.net", "homelinux.com", "homelinux.net", "homelinux.org", "homeunix.com", "homeunix.net", "homeunix.org", "iamallama.com", "in-the-band.net", "is-a-anarchist.com", "is-a-blogger.com", "is-a-bookkeeper.com", "is-a-bruinsfan.org", "is-a-bulls-fan.com", "is-a-candidate.org", "is-a-caterer.com", "is-a-celticsfan.org", "is-a-chef.com", "is-a-chef.net", "is-a-chef.org", "is-a-conservative.com", "is-a-cpa.com", "is-a-cubicle-slave.com", "is-a-democrat.com", "is-a-designer.com", "is-a-doctor.com", "is-a-financialadvisor.com", "is-a-geek.com", "is-a-geek.net", "is-a-geek.org", "is-a-green.com", "is-a-guru.com", "is-a-hard-worker.com", "is-a-hunter.com", "is-a-knight.org", "is-a-landscaper.com", "is-a-lawyer.com", "is-a-liberal.com", "is-a-libertarian.com", "is-a-linux-user.org", "is-a-llama.com", "is-a-musician.com", "is-a-nascarfan.com", "is-a-nurse.com", "is-a-painter.com", "is-a-patsfan.org", "is-a-personaltrainer.com", "is-a-photographer.com", "is-a-player.com", "is-a-republican.com", "is-a-rockstar.com", "is-a-socialist.com", "is-a-soxfan.org", "is-a-student.com", "is-a-teacher.com", "is-a-techie.com", "is-a-therapist.com", "is-an-accountant.com", "is-an-actor.com", "is-an-actress.com", "is-an-anarchist.com", "is-an-artist.com", "is-an-engineer.com", "is-an-entertainer.com", "is-by.us", "is-certified.com", "is-found.org", "is-gone.com", "is-into-anime.com", "is-into-cars.com", "is-into-cartoons.com", "is-into-games.com", "is-leet.com", "is-lost.org", "is-not-certified.com", "is-saved.org", "is-slick.com", "is-uberleet.com", "is-very-bad.org", "is-very-evil.org", "is-very-good.org", "is-very-nice.org", "is-very-sweet.org", "is-with-theband.com", "isa-geek.com", "isa-geek.net", "isa-geek.org", "isa-hockeynut.com", "issmarterthanyou.com", "isteingeek.de", "istmein.de", "kicks-ass.net", "kicks-ass.org", "knowsitall.info", "land-4-sale.us", "lebtimnetz.de", "leitungsen.de", "likes-pie.com", "likescandy.com", "merseine.nu", "mine.nu", "misconfused.org", "mypets.ws", "myphotos.cc", "neat-url.com", "office-on-the.net", "on-the-web.tv", "podzone.net", "podzone.org", "readmyblog.org", "saves-the-whales.com", "scrapper-site.net", "scrapping.cc", "selfip.biz", "selfip.com", "selfip.info", "selfip.net", "selfip.org", "sells-for-less.com", "sells-for-u.com", "sells-it.net", "sellsyourhome.org", "servebbs.com", "servebbs.net", "servebbs.org", "serveftp.net", "serveftp.org", "servegame.org", "shacknet.nu", "simple-url.com", "space-to-rent.com", "stuff-4-sale.org", "stuff-4-sale.us", "teaches-yoga.com", "thruhere.net", "traeumtgerade.de", "webhop.biz", "webhop.info", "webhop.net", "webhop.org", "worse-than.tv", "writesthisblog.com", "eu.org", "al.eu.org", "asso.eu.org", "at.eu.org", "au.eu.org", "be.eu.org", "bg.eu.org", "ca.eu.org", "cd.eu.org", "ch.eu.org", "cn.eu.org", "cy.eu.org", "cz.eu.org", "de.eu.org", "dk.eu.org", "edu.eu.org", "ee.eu.org", "es.eu.org", "fi.eu.org", "fr.eu.org", "gr.eu.org", "hr.eu.org", "hu.eu.org", "ie.eu.org", "il.eu.org", "in.eu.org", "int.eu.org", "is.eu.org", "it.eu.org", "jp.eu.org", "kr.eu.org", "lt.eu.org", "lu.eu.org", "lv.eu.org", "mc.eu.org", "me.eu.org", "mk.eu.org", "mt.eu.org", "my.eu.org", "net.eu.org", "ng.eu.org", "nl.eu.org", "no.eu.org", "nz.eu.org", "paris.eu.org", "pl.eu.org", "pt.eu.org", "q-a.eu.org", "ro.eu.org", "ru.eu.org", "se.eu.org", "si.eu.org", "sk.eu.org", "tr.eu.org", "uk.eu.org", "us.eu.org", "a.ssl.fastly.net", "b.ssl.fastly.net", "global.ssl.fastly.net", "a.prod.fastly.net", "global.prod.fastly.net", "firebaseapp.com", "flynnhub.com", "service.gov.uk", "github.io", "githubusercontent.com", "ro.com", "appspot.com", "blogspot.ae", "blogspot.al", "blogspot.am", "blogspot.ba", "blogspot.be", "blogspot.bg", "blogspot.bj", "blogspot.ca", "blogspot.cf", "blogspot.ch", "blogspot.cl", "blogspot.co.at", "blogspot.co.id", "blogspot.co.il", "blogspot.co.ke", "blogspot.co.nz", "blogspot.co.uk", "blogspot.co.za", "blogspot.com", "blogspot.com.ar", "blogspot.com.au", "blogspot.com.br", "blogspot.com.by", "blogspot.com.co", "blogspot.com.cy", "blogspot.com.ee", "blogspot.com.eg", "blogspot.com.es", "blogspot.com.mt", "blogspot.com.ng", "blogspot.com.tr", "blogspot.com.uy", "blogspot.cv", "blogspot.cz", "blogspot.de", "blogspot.dk", "blogspot.fi", "blogspot.fr", "blogspot.gr", "blogspot.hk", "blogspot.hr", "blogspot.hu", "blogspot.ie", "blogspot.in", "blogspot.is", "blogspot.it", "blogspot.jp", "blogspot.kr", "blogspot.li", "blogspot.lt", "blogspot.lu", "blogspot.md", "blogspot.mk", "blogspot.mr", "blogspot.mx", "blogspot.my", "blogspot.nl", "blogspot.no", "blogspot.pe", "blogspot.pt", "blogspot.qa", "blogspot.re", "blogspot.ro", "blogspot.rs", "blogspot.ru", "blogspot.se", "blogspot.sg", "blogspot.si", "blogspot.sk", "blogspot.sn", "blogspot.td", "blogspot.tw", "blogspot.ug", "blogspot.vn", "codespot.com", "googleapis.com", "googlecode.com", "pagespeedmobilizer.com", "withgoogle.com", "herokuapp.com", "herokussl.com", "iki.fi", "biz.at", "info.at", "co.pl", "azurewebsites.net", "azure-mobile.net", "cloudapp.net", "4u.com", "nfshost.com", "nyc.mn", "nid.io", "operaunite.com", "outsystemscloud.com", "art.pl", "gliwice.pl", "krakow.pl", "poznan.pl", "wroc.pl", "zakopane.pl", "priv.at", "rhcloud.com", "sinaapp.com", "vipsinaapp.com", "1kapp.com", "gda.pl", "gdansk.pl", "gdynia.pl", "med.pl", "sopot.pl", "hk.com", "hk.org", "ltd.hk", "inc.hk", "yolasite.com", "za.net", "za.org", } var nodeLabels = [...]string{ "aaa", "aarp", "abb", "abbott", "able", "abogado", "ac", "academy", "accenture", "accountant", "accountants", "aco", "active", "actor", "ad", "ads", "adult", "ae", "aeg", "aero", "aetna", "af", "afl", "africa", "africamagic", "ag", "agakhan", "agency", "ai", "aig", "airforce", "airtel", "akdn", "al", "alibaba", "alipay", "allfinanz", "ally", "alsace", "am", "amica", "amsterdam", "an", "analytics", "android", "anquan", "ao", "apartments", "app", "apple", "aq", "aquarelle", "ar", "aramco", "archi", "army", "arpa", "arte", "as", "asia", "associates", "at", "attorney", "au", "auction", "audi", "audible", "audio", "author", "auto", "autos", "avianca", "aw", "aws", "ax", "axa", "az", "azure", "ba", "baby", "baidu", "band", "bank", "bar", "barcelona", "barclaycard", "barclays", "barefoot", "bargains", "bauhaus", "bayern", "bb", "bbc", "bbva", "bcg", "bcn", "bd", "be", "beats", "beer", "bentley", "berlin", "best", "bet", "bf", "bg", "bh", "bharti", "bi", "bible", "bid", "bike", "bing", "bingo", "bio", "biz", "bj", "black", "blackfriday", "blog", "bloomberg", "blue", "bm", "bms", "bmw", "bn", "bnl", "bnpparibas", "bo", "boats", "bom", "bond", "boo", "boots", "bosch", "bostik", "bot", "boutique", "br", "bradesco", "bridgestone", "broadway", "broker", "brother", "brussels", "bs", "bt", "budapest", "build", "builders", "business", "buy", "buzz", "bv", "bw", "by", "bz", "bzh", "ca", "cab", "cafe", "cal", "call", "camera", "camp", "cancerresearch", "canon", "capetown", "capital", "car", "caravan", "cards", "care", "career", "careers", "cars", "cartier", "casa", "cash", "casino", "cat", "catering", "cba", "cbn", "cbre", "cc", "cd", "ceb", "center", "ceo", "cern", "cf", "cfa", "cfd", "cg", "ch", "chanel", "channel", "chase", "chat", "cheap", "chintai", "chloe", "christmas", "chrome", "church", "ci", "cipriani", "circle", "cisco", "citic", "city", "cityeats", "ck", "cl", "claims", "cleaning", "click", "clinic", "clothing", "cloud", "club", "clubmed", "cm", "cn", "co", "coach", "codes", "coffee", "college", "cologne", "com", "commbank", "community", "company", "computer", "comsec", "condos", "construction", "consulting", "contact", "contractors", "cooking", "cookingchannel", "cool", "coop", "corsica", "country", "coupon", "coupons", "courses", "cr", "credit", "creditcard", "creditunion", "cricket", "crown", "crs", "cruises", "csc", "cu", "cuisinella", "cv", "cw", "cx", "cy", "cymru", "cyou", "cz", "dabur", "dad", "dance", "date", "dating", "datsun", "day", "dclk", "dds", "de", "deal", "dealer", "deals", "degree", "delivery", "dell", "delta", "democrat", "dental", "dentist", "desi", "design", "dev", "diamonds", "diet", "digital", "direct", "directory", "discount", "dj", "dk", "dm", "dnp", "do", "docs", "dog", "doha", "domains", "doosan", "dot", "download", "drive", "dstv", "dtv", "dubai", "dunlop", "dupont", "durban", "dvag", "dz", "earth", "eat", "ec", "edeka", "edu", "education", "ee", "eg", "email", "emerck", "energy", "engineer", "engineering", "enterprises", "epson", "equipment", "er", "erni", "es", "esq", "estate", "et", "eu", "eurovision", "eus", "events", "everbank", "exchange", "expert", "exposed", "express", "extraspace", "fage", "fail", "fairwinds", "faith", "family", "fan", "fans", "farm", "fashion", "fast", "feedback", "ferrero", "fi", "film", "final", "finance", "financial", "fire", "firestone", "firmdale", "fish", "fishing", "fit", "fitness", "fj", "fk", "flickr", "flights", "florist", "flowers", "flsmidth", "fly", "fm", "fo", "foo", "foodnetwork", "football", "ford", "forex", "forsale", "forum", "foundation", "fr", "frl", "frogans", "frontdoor", "frontier", "fund", "furniture", "futbol", "fyi", "ga", "gal", "gallery", "gallo", "gallup", "game", "games", "garden", "gb", "gbiz", "gd", "gdn", "ge", "gea", "gent", "genting", "gf", "gg", "ggee", "gh", "gi", "gift", "gifts", "gives", "giving", "gl", "glass", "gle", "global", "globo", "gm", "gmail", "gmo", "gmx", "gn", "gold", "goldpoint", "golf", "goo", "goodyear", "goog", "google", "gop", "got", "gotv", "gov", "gp", "gq", "gr", "grainger", "graphics", "gratis", "green", "gripe", "group", "gs", "gt", "gu", "gucci", "guge", "guide", "guitars", "guru", "gw", "gy", "hamburg", "hangout", "haus", "hdfcbank", "health", "healthcare", "help", "helsinki", "here", "hermes", "hgtv", "hiphop", "hitachi", "hiv", "hk", "hkt", "hm", "hn", "hockey", "holdings", "holiday", "homedepot", "homes", "honda", "horse", "host", "hosting", "hoteles", "hotmail", "house", "how", "hr", "hsbc", "ht", "htc", "hu", "ibm", "icbc", "ice", "icu", "id", "ie", "ifm", "iinet", "il", "im", "imdb", "immo", "immobilien", "in", "industries", "infiniti", "info", "ing", "ink", "institute", "insurance", "insure", "int", "international", "investments", "io", "ipiranga", "iq", "ir", "irish", "is", "iselect", "ist", "istanbul", "it", "itau", "iwc", "jaguar", "java", "jcb", "jcp", "je", "jetzt", "jewelry", "jio", "jlc", "jll", "jm", "jmp", "jnj", "jo", "jobs", "joburg", "jot", "joy", "jp", "jpmorgan", "jprs", "juegos", "kaufen", "kddi", "ke", "kerryhotels", "kerrylogistics", "kerryproperties", "kfh", "kg", "kh", "ki", "kim", "kinder", "kindle", "kitchen", "kiwi", "km", "kn", "koeln", "komatsu", "kp", "kpmg", "kpn", "kr", "krd", "kred", "kuokgroup", "kw", "ky", "kyknet", "kyoto", "kz", "la", "lacaixa", "lamborghini", "lancaster", "land", "landrover", "lasalle", "lat", "latrobe", "law", "lawyer", "lb", "lc", "lds", "lease", "leclerc", "legal", "lexus", "lgbt", "li", "liaison", "lidl", "life", "lifeinsurance", "lifestyle", "lighting", "like", "limited", "limo", "lincoln", "linde", "link", "lipsy", "live", "lixil", "lk", "loan", "loans", "locker", "locus", "lol", "london", "lotte", "lotto", "love", "lr", "ls", "lt", "ltd", "ltda", "lu", "lupin", "luxe", "luxury", "lv", "ly", "ma", "madrid", "maif", "maison", "makeup", "man", "management", "mango", "market", "marketing", "markets", "marriott", "mba", "mc", "md", "me", "media", "meet", "melbourne", "meme", "memorial", "men", "menu", "meo", "metlife", "mg", "mh", "miami", "microsoft", "mil", "mini", "mit", "mk", "ml", "mlb", "mls", "mm", "mma", "mn", "mnet", "mo", "mobi", "mobily", "moda", "moe", "moi", "mom", "monash", "money", "montblanc", "mormon", "mortgage", "moscow", "moto", "motorcycles", "mov", "movie", "movistar", "mp", "mq", "mr", "ms", "mt", "mtn", "mtpc", "mtr", "mu", "multichoice", "museum", "mutual", "mutuelle", "mv", "mw", "mx", "my", "mz", "mzansimagic", "na", "nadex", "nagoya", "name", "naspers", "natura", "navy", "nc", "ne", "nec", "net", "netbank", "netflix", "network", "neustar", "new", "news", "next", "nextdirect", "nexus", "nf", "ng", "ngo", "nhk", "ni", "nico", "nikon", "ninja", "nissan", "nl", "no", "nokia", "northwesternmutual", "norton", "now", "nowruz", "nowtv", "np", "nr", "nra", "nrw", "ntt", "nu", "nyc", "nz", "obi", "observer", "office", "okinawa", "olayan", "olayangroup", "ollo", "om", "omega", "one", "ong", "onl", "online", "ooo", "oracle", "orange", "org", "organic", "orientexpress", "osaka", "otsuka", "ott", "ovh", "pa", "page", "pamperedchef", "panerai", "paris", "pars", "partners", "parts", "party", "passagens", "payu", "pccw", "pe", "pet", "pf", "pg", "ph", "pharmacy", "philips", "photo", "photography", "photos", "physio", "piaget", "pics", "pictet", "pictures", "pid", "pin", "ping", "pink", "pizza", "pk", "pl", "place", "play", "playstation", "plumbing", "plus", "pm", "pn", "pnc", "pohl", "poker", "porn", "post", "pr", "praxi", "press", "prime", "pro", "prod", "productions", "prof", "promo", "properties", "property", "protection", "ps", "pt", "pub", "pw", "py", "qa", "qpon", "quebec", "quest", "racing", "re", "read", "realtor", "realty", "recipes", "red", "redstone", "redumbrella", "rehab", "reise", "reisen", "reit", "reliance", "ren", "rent", "rentals", "repair", "report", "republican", "rest", "restaurant", "review", "reviews", "rexroth", "rich", "richardli", "ricoh", "ril", "rio", "rip", "ro", "rocher", "rocks", "rodeo", "room", "rs", "rsvp", "ru", "ruhr", "run", "rw", "rwe", "ryukyu", "sa", "saarland", "safe", "safety", "sakura", "sale", "salon", "samsung", "sandvik", "sandvikcoromant", "sanofi", "sap", "sapo", "sarl", "sas", "save", "saxo", "sb", "sbi", "sbs", "sc", "sca", "scb", "schmidt", "scholarships", "school", "schule", "schwarz", "science", "scor", "scot", "sd", "se", "seat", "security", "seek", "sener", "services", "sew", "sex", "sexy", "sg", "sh", "sharp", "shaw", "shia", "shiksha", "shoes", "shouji", "show", "shriram", "si", "silk", "sina", "singles", "site", "sj", "sk", "ski", "skin", "sky", "skype", "sl", "sm", "smile", "sn", "sncf", "so", "soccer", "social", "softbank", "software", "sohu", "solar", "solutions", "song", "sony", "soy", "space", "spiegel", "spot", "spreadbetting", "sr", "srl", "st", "stada", "star", "starhub", "statebank", "statoil", "stc", "stcgroup", "stockholm", "storage", "store", "studio", "study", "style", "su", "sucks", "supersport", "supplies", "supply", "support", "surf", "surgery", "suzuki", "sv", "swatch", "swiss", "sx", "sy", "sydney", "symantec", "systems", "sz", "tab", "taipei", "talk", "taobao", "tatamotors", "tatar", "tattoo", "tax", "taxi", "tc", "tci", "td", "tdk", "team", "tech", "technology", "tel", "telecity", "telefonica", "temasek", "tennis", "teva", "tf", "tg", "th", "thd", "theater", "theatre", "theguardian", "tickets", "tienda", "tiffany", "tips", "tires", "tirol", "tj", "tk", "tl", "tm", "tmall", "tn", "to", "today", "tokyo", "tools", "top", "toray", "toshiba", "tours", "town", "toyota", "toys", "tp", "tr", "trade", "trading", "training", "travel", "travelchannel", "travelers", "travelersinsurance", "trust", "trv", "tt", "tube", "tui", "tunes", "tushu", "tv", "tvs", "tw", "tz", "ua", "ubs", "ug", "uk", "university", "uno", "uol", "ups", "us", "uy", "uz", "va", "vacations", "vana", "vc", "ve", "vegas", "ventures", "versicherung", "vet", "vg", "vi", "viajes", "video", "vig", "viking", "villas", "vin", "vip", "virgin", "vision", "vista", "vistaprint", "viva", "vlaanderen", "vn", "vodka", "volkswagen", "vote", "voting", "voto", "voyage", "vu", "vuelos", "wales", "walter", "wang", "wanggou", "warman", "watch", "watches", "weather", "weatherchannel", "webcam", "weber", "website", "wed", "wedding", "weibo", "weir", "wf", "whoswho", "wien", "wiki", "williamhill", "win", "windows", "wine", "wme", "work", "works", "world", "ws", "wtc", "wtf", "xbox", "xerox", "xihuan", "xin", "xn--11b4c3d", "xn--1ck2e1b", "xn--1qqw23a", "xn--30rr7y", "xn--3bst00m", "xn--3ds443g", "xn--3e0b707e", "xn--3oq18vl8pn36a", "xn--3pxu8k", "xn--42c2d9a", "xn--45brj9c", "xn--45q11c", "xn--4gbrim", "xn--54b7fta0cc", "xn--55qw42g", "xn--55qx5d", "xn--5tzm5g", "xn--6frz82g", "xn--6qq986b3xl", "xn--80adxhks", "xn--80ao21a", "xn--80asehdb", "xn--80aswg", "xn--8y0a063a", "xn--90a3ac", "xn--90ais", "xn--9dbq2a", "xn--9et52u", "xn--9krt00a", "xn--b4w605ferd", "xn--bck1b9a5dre4c", "xn--c1avg", "xn--c2br7g", "xn--cck2b3b", "xn--cg4bki", "xn--clchc0ea0b2g2a9gcd", "xn--czr694b", "xn--czrs0t", "xn--czru2d", "xn--d1acj3b", "xn--d1alf", "xn--eckvdtc9d", "xn--efvy88h", "xn--estv75g", "xn--fct429k", "xn--fhbei", "xn--fiq228c5hs", "xn--fiq64b", "xn--fiqs8s", "xn--fiqz9s", "xn--fjq720a", "xn--flw351e", "xn--fpcrj9c3d", "xn--fzc2c9e2c", "xn--fzys8d69uvgm", "xn--g2xx48c", "xn--gckr3f0f", "xn--gecrj9c", "xn--h2brj9c", "xn--hxt814e", "xn--i1b6b1a6a2e", "xn--imr513n", "xn--io0a7i", "xn--j1aef", "xn--j1amh", "xn--j6w193g", "xn--jlq61u9w7b", "xn--jvr189m", "xn--kcrx77d1x4a", "xn--kprw13d", "xn--kpry57d", "xn--kpu716f", "xn--kput3i", "xn--l1acc", "xn--lgbbat1ad8j", "xn--mgb2ddes", "xn--mgb9awbf", "xn--mgba3a3ejt", "xn--mgba3a4f16a", "xn--mgba3a4fra", "xn--mgba7c0bbn0a", "xn--mgbaam7a8h", "xn--mgbab2bd", "xn--mgbai9a5eva00b", "xn--mgbai9azgqp6j", "xn--mgbayh7gpa", "xn--mgbb9fbpob", "xn--mgbbh1a71e", "xn--mgbc0a9azcg", "xn--mgberp4a5d4a87g", "xn--mgberp4a5d4ar", "xn--mgbpl2fh", "xn--mgbqly7c0a67fbc", "xn--mgbqly7cvafr", "xn--mgbt3dhd", "xn--mgbtf8fl", "xn--mgbtx2b", "xn--mgbx4cd0ab", "xn--mix082f", "xn--mix891f", "xn--mk1bu44c", "xn--mxtq1m", "xn--ngbc5azd", "xn--ngbe9e0a", "xn--nnx388a", "xn--node", "xn--nqv7f", "xn--nqv7fs00ema", "xn--nyqy26a", "xn--o3cw4h", "xn--ogbpf8fl", "xn--p1acf", "xn--p1ai", "xn--pbt977c", "xn--pgbs0dh", "xn--pssy2u", "xn--q9jyb4c", "xn--qcka1pmc", "xn--qxam", "xn--rhqv96g", "xn--rovu88b", "xn--s9brj9c", "xn--ses554g", "xn--t60b56a", "xn--tckwe", "xn--unup4y", "xn--vermgensberater-ctb", "xn--vermgensberatung-pwb", "xn--vhquv", "xn--vuq861b", "xn--w4r85el8fhu5dnra", "xn--wgbh1c", "xn--wgbl6a", "xn--xhq521b", "xn--xkc2al3hye2a", "xn--xkc2dl3a5ee0h", "xn--y9a3aq", "xn--yfro4i67o", "xn--ygbi2ammx", "xn--zfr164b", "xperia", "xxx", "xyz", "yachts", "yahoo", "yamaxun", "yandex", "ye", "yodobashi", "yoga", "yokohama", "you", "youtube", "yt", "yun", "za", "zappos", "zara", "zero", "zip", "zippo", "zm", "zone", "zuerich", "zw", "com", "edu", "gov", "mil", "net", "org", "nom", "ac", "blogspot", "co", "gov", "mil", "net", "org", "sch", "accident-investigation", "accident-prevention", "aerobatic", "aeroclub", "aerodrome", "agents", "air-surveillance", "air-traffic-control", "aircraft", "airline", "airport", "airtraffic", "ambulance", "amusement", "association", "author", "ballooning", "broker", "caa", "cargo", "catering", "certification", "championship", "charter", "civilaviation", "club", "conference", "consultant", "consulting", "control", "council", "crew", "design", "dgca", "educator", "emergency", "engine", "engineer", "entertainment", "equipment", "exchange", "express", "federation", "flight", "freight", "fuel", "gliding", "government", "groundhandling", "group", "hanggliding", "homebuilt", "insurance", "journal", "journalist", "leasing", "logistics", "magazine", "maintenance", "marketplace", "media", "microlight", "modelling", "navigation", "parachuting", "paragliding", "passenger-association", "pilot", "press", "production", "recreation", "repbody", "res", "research", "rotorcraft", "safety", "scientist", "services", "show", "skydiving", "software", "student", "taxi", "trader", "trading", "trainer", "union", "workinggroup", "works", "com", "edu", "gov", "net", "org", "co", "com", "net", "nom", "org", "com", "net", "off", "org", "blogspot", "com", "edu", "gov", "mil", "net", "org", "blogspot", "com", "edu", "net", "org", "co", "ed", "gv", "it", "og", "pb", "com", "edu", "gob", "gov", "int", "mil", "net", "org", "tur", "blogspot", "e164", "in-addr", "ip6", "iris", "uri", "urn", "gov", "ac", "biz", "co", "gv", "info", "or", "priv", "blogspot", "act", "asn", "com", "conf", "edu", "gov", "id", "info", "net", "nsw", "nt", "org", "oz", "qld", "sa", "tas", "vic", "wa", "blogspot", "act", "nsw", "nt", "qld", "sa", "tas", "vic", "wa", "qld", "sa", "tas", "vic", "wa", "com", "biz", "com", "edu", "gov", "info", "int", "mil", "name", "net", "org", "pp", "pro", "blogspot", "co", "com", "edu", "gov", "mil", "net", "org", "rs", "unbi", "unsa", "biz", "co", "com", "edu", "gov", "info", "net", "org", "store", "tv", "ac", "blogspot", "gov", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "blogspot", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "com", "edu", "gov", "net", "org", "co", "com", "edu", "or", "org", "dyndns", "for-better", "for-more", "for-some", "for-the", "selfip", "webhop", "asso", "barreau", "blogspot", "gouv", "com", "edu", "gov", "net", "org", "com", "edu", "gob", "gov", "int", "mil", "net", "org", "tv", "adm", "adv", "agr", "am", "arq", "art", "ato", "b", "bio", "blog", "bmd", "cim", "cng", "cnt", "com", "coop", "ecn", "eco", "edu", "emp", "eng", "esp", "etc", "eti", "far", "flog", "fm", "fnd", "fot", "fst", "g12", "ggf", "gov", "imb", "ind", "inf", "jor", "jus", "leg", "lel", "mat", "med", "mil", "mp", "mus", "net", "nom", "not", "ntr", "odo", "org", "ppg", "pro", "psc", "psi", "qsl", "radio", "rec", "slg", "srv", "taxi", "teo", "tmp", "trd", "tur", "tv", "vet", "vlog", "wiki", "zlg", "blogspot", "com", "edu", "gov", "net", "org", "com", "edu", "gov", "net", "org", "co", "org", "com", "gov", "mil", "of", "blogspot", "com", "edu", "gov", "net", "org", "za", "ab", "bc", "blogspot", "co", "gc", "mb", "nb", "nf", "nl", "ns", "nt", "nu", "on", "pe", "qc", "sk", "yk", "ftpaccess", "game-server", "myphotos", "scrapping", "gov", "blogspot", "blogspot", "ac", "asso", "co", "com", "ed", "edu", "go", "gouv", "int", "md", "net", "or", "org", "presse", "xn--aroport-bya", "www", "blogspot", "co", "gob", "gov", "mil", "co", "com", "gov", "net", "ac", "ah", "amazonaws", "bj", "com", "cq", "edu", "fj", "gd", "gov", "gs", "gx", "gz", "ha", "hb", "he", "hi", "hk", "hl", "hn", "jl", "js", "jx", "ln", "mil", "mo", "net", "nm", "nx", "org", "qh", "sc", "sd", "sh", "sn", "sx", "tj", "tw", "xj", "xn--55qx5d", "xn--io0a7i", "xn--od0alg", "xz", "yn", "zj", "compute", "cn-north-1", "amazonaws", "cn-north-1", "s3", "arts", "com", "edu", "firm", "gov", "info", "int", "mil", "net", "nom", "org", "rec", "web", "blogspot", "1kapp", "4u", "africa", "amazonaws", "appspot", "ar", "betainabox", "blogdns", "blogspot", "br", "cechire", "cloudcontrolapp", "cloudcontrolled", "cn", "co", "codespot", "de", "dnsalias", "dnsdojo", "doesntexist", "dontexist", "doomdns", "dreamhosters", "dyn-o-saur", "dynalias", "dyndns-at-home", "dyndns-at-work", "dyndns-blog", "dyndns-free", "dyndns-home", "dyndns-ip", "dyndns-mail", "dyndns-office", "dyndns-pics", "dyndns-remote", "dyndns-server", "dyndns-web", "dyndns-wiki", "dyndns-work", "elasticbeanstalk", "est-a-la-maison", "est-a-la-masion", "est-le-patron", "est-mon-blogueur", "eu", "firebaseapp", "flynnhub", "from-ak", "from-al", "from-ar", "from-ca", "from-ct", "from-dc", "from-de", "from-fl", "from-ga", "from-hi", "from-ia", "from-id", "from-il", "from-in", "from-ks", "from-ky", "from-ma", "from-md", "from-mi", "from-mn", "from-mo", "from-ms", "from-mt", "from-nc", "from-nd", "from-ne", "from-nh", "from-nj", "from-nm", "from-nv", "from-oh", "from-ok", "from-or", "from-pa", "from-pr", "from-ri", "from-sc", "from-sd", "from-tn", "from-tx", "from-ut", "from-va", "from-vt", "from-wa", "from-wi", "from-wv", "from-wy", "gb", "getmyip", "githubusercontent", "googleapis", "googlecode", "gotdns", "gr", "herokuapp", "herokussl", "hk", "hobby-site", "homelinux", "homeunix", "hu", "iamallama", "is-a-anarchist", "is-a-blogger", "is-a-bookkeeper", "is-a-bulls-fan", "is-a-caterer", "is-a-chef", "is-a-conservative", "is-a-cpa", "is-a-cubicle-slave", "is-a-democrat", "is-a-designer", "is-a-doctor", "is-a-financialadvisor", "is-a-geek", "is-a-green", "is-a-guru", "is-a-hard-worker", "is-a-hunter", "is-a-landscaper", "is-a-lawyer", "is-a-liberal", "is-a-libertarian", "is-a-llama", "is-a-musician", "is-a-nascarfan", "is-a-nurse", "is-a-painter", "is-a-personaltrainer", "is-a-photographer", "is-a-player", "is-a-republican", "is-a-rockstar", "is-a-socialist", "is-a-student", "is-a-teacher", "is-a-techie", "is-a-therapist", "is-an-accountant", "is-an-actor", "is-an-actress", "is-an-anarchist", "is-an-artist", "is-an-engineer", "is-an-entertainer", "is-certified", "is-gone", "is-into-anime", "is-into-cars", "is-into-cartoons", "is-into-games", "is-leet", "is-not-certified", "is-slick", "is-uberleet", "is-with-theband", "isa-geek", "isa-hockeynut", "issmarterthanyou", "jpn", "kr", "likes-pie", "likescandy", "mex", "neat-url", "nfshost", "no", "operaunite", "outsystemscloud", "pagespeedmobilizer", "qc", "rhcloud", "ro", "ru", "sa", "saves-the-whales", "se", "selfip", "sells-for-less", "sells-for-u", "servebbs", "simple-url", "sinaapp", "space-to-rent", "teaches-yoga", "uk", "us", "uy", "vipsinaapp", "withgoogle", "writesthisblog", "yolasite", "za", "compute", "compute-1", "elb", "eu-central-1", "s3", "s3-ap-northeast-1", "s3-ap-southeast-1", "s3-ap-southeast-2", "s3-eu-central-1", "s3-eu-west-1", "s3-external-1", "s3-external-2", "s3-fips-us-gov-west-1", "s3-sa-east-1", "s3-us-gov-west-1", "s3-us-west-1", "s3-us-west-2", "us-east-1", "ap-northeast-1", "ap-southeast-1", "ap-southeast-2", "eu-central-1", "eu-west-1", "sa-east-1", "us-gov-west-1", "us-west-1", "us-west-2", "z-1", "z-2", "s3", "ac", "co", "ed", "fi", "go", "or", "sa", "com", "edu", "gov", "inf", "net", "org", "blogspot", "com", "edu", "net", "org", "ath", "gov", "ac", "biz", "com", "ekloges", "gov", "ltd", "name", "net", "org", "parliament", "press", "pro", "tm", "blogspot", "blogspot", "blogspot", "com", "fuettertdasnetz", "isteingeek", "istmein", "lebtimnetz", "leitungsen", "traeumtgerade", "blogspot", "com", "edu", "gov", "net", "org", "art", "com", "edu", "gob", "gov", "mil", "net", "org", "sld", "web", "art", "asso", "com", "edu", "gov", "net", "org", "pol", "com", "edu", "fin", "gob", "gov", "info", "k12", "med", "mil", "net", "org", "pro", "aip", "com", "edu", "fie", "gov", "lib", "med", "org", "pri", "riik", "blogspot", "com", "edu", "eun", "gov", "mil", "name", "net", "org", "sci", "blogspot", "com", "edu", "gob", "nom", "org", "blogspot", "biz", "com", "edu", "gov", "info", "name", "net", "org", "aland", "blogspot", "iki", "aeroport", "assedic", "asso", "avocat", "avoues", "blogspot", "cci", "chambagri", "chirurgiens-dentistes", "com", "experts-comptables", "geometre-expert", "gouv", "greta", "huissier-justice", "medecin", "nom", "notaires", "pharmacien", "port", "prd", "presse", "tm", "veterinaire", "com", "edu", "gov", "mil", "net", "org", "pvt", "co", "net", "org", "com", "edu", "gov", "mil", "org", "com", "edu", "gov", "ltd", "mod", "org", "co", "com", "edu", "net", "org", "ac", "com", "edu", "gov", "net", "org", "asso", "com", "edu", "mobi", "net", "org", "blogspot", "com", "edu", "gov", "net", "org", "com", "edu", "gob", "ind", "mil", "net", "org", "co", "com", "net", "blogspot", "com", "edu", "gov", "idv", "inc", "ltd", "net", "org", "xn--55qx5d", "xn--ciqpn", "xn--gmq050i", "xn--gmqw5a", "xn--io0a7i", "xn--lcvr32d", "xn--mk0axi", "xn--mxtq1m", "xn--od0alg", "xn--od0aq3b", "xn--tn0ag", "xn--uc0atv", "xn--uc0ay4a", "xn--wcvs22d", "xn--zf0avx", "com", "edu", "gob", "mil", "net", "org", "blogspot", "com", "from", "iz", "name", "adult", "art", "asso", "com", "coop", "edu", "firm", "gouv", "info", "med", "net", "org", "perso", "pol", "pro", "rel", "shop", "2000", "agrar", "blogspot", "bolt", "casino", "city", "co", "erotica", "erotika", "film", "forum", "games", "hotel", "info", "ingatlan", "jogasz", "konyvelo", "lakas", "media", "news", "org", "priv", "reklam", "sex", "shop", "sport", "suli", "szex", "tm", "tozsde", "utazas", "video", "ac", "biz", "co", "desa", "go", "mil", "my", "net", "or", "sch", "web", "blogspot", "blogspot", "gov", "co", "blogspot", "ac", "co", "com", "net", "org", "tt", "tv", "ltd", "plc", "ac", "blogspot", "co", "edu", "firm", "gen", "gov", "ind", "mil", "net", "nic", "org", "res", "barrel-of-knowledge", "barrell-of-knowledge", "dyndns", "for-our", "groks-the", "groks-this", "here-for-more", "knowsitall", "selfip", "webhop", "eu", "com", "github", "nid", "com", "edu", "gov", "mil", "net", "org", "ac", "co", "gov", "id", "net", "org", "sch", "xn--mgba3a4f16a", "xn--mgba3a4fra", "blogspot", "com", "cupcake", "edu", "gov", "int", "net", "org", "abr", "abruzzo", "ag", "agrigento", "al", "alessandria", "alto-adige", "altoadige", "an", "ancona", "andria-barletta-trani", "andria-trani-barletta", "andriabarlettatrani", "andriatranibarletta", "ao", "aosta", "aosta-valley", "aostavalley", "aoste", "ap", "aq", "aquila", "ar", "arezzo", "ascoli-piceno", "ascolipiceno", "asti", "at", "av", "avellino", "ba", "balsan", "bari", "barletta-trani-andria", "barlettatraniandria", "bas", "basilicata", "belluno", "benevento", "bergamo", "bg", "bi", "biella", "bl", "blogspot", "bn", "bo", "bologna", "bolzano", "bozen", "br", "brescia", "brindisi", "bs", "bt", "bz", "ca", "cagliari", "cal", "calabria", "caltanissetta", "cam", "campania", "campidano-medio", "campidanomedio", "campobasso", "carbonia-iglesias", "carboniaiglesias", "carrara-massa", "carraramassa", "caserta", "catania", "catanzaro", "cb", "ce", "cesena-forli", "cesenaforli", "ch", "chieti", "ci", "cl", "cn", "co", "como", "cosenza", "cr", "cremona", "crotone", "cs", "ct", "cuneo", "cz", "dell-ogliastra", "dellogliastra", "edu", "emilia-romagna", "emiliaromagna", "emr", "en", "enna", "fc", "fe", "fermo", "ferrara", "fg", "fi", "firenze", "florence", "fm", "foggia", "forli-cesena", "forlicesena", "fr", "friuli-v-giulia", "friuli-ve-giulia", "friuli-vegiulia", "friuli-venezia-giulia", "friuli-veneziagiulia", "friuli-vgiulia", "friuliv-giulia", "friulive-giulia", "friulivegiulia", "friulivenezia-giulia", "friuliveneziagiulia", "friulivgiulia", "frosinone", "fvg", "ge", "genoa", "genova", "go", "gorizia", "gov", "gr", "grosseto", "iglesias-carbonia", "iglesiascarbonia", "im", "imperia", "is", "isernia", "kr", "la-spezia", "laquila", "laspezia", "latina", "laz", "lazio", "lc", "le", "lecce", "lecco", "li", "lig", "liguria", "livorno", "lo", "lodi", "lom", "lombardia", "lombardy", "lt", "lu", "lucania", "lucca", "macerata", "mantova", "mar", "marche", "massa-carrara", "massacarrara", "matera", "mb", "mc", "me", "medio-campidano", "mediocampidano", "messina", "mi", "milan", "milano", "mn", "mo", "modena", "mol", "molise", "monza", "monza-brianza", "monza-e-della-brianza", "monzabrianza", "monzaebrianza", "monzaedellabrianza", "ms", "mt", "na", "naples", "napoli", "no", "novara", "nu", "nuoro", "og", "ogliastra", "olbia-tempio", "olbiatempio", "or", "oristano", "ot", "pa", "padova", "padua", "palermo", "parma", "pavia", "pc", "pd", "pe", "perugia", "pesaro-urbino", "pesarourbino", "pescara", "pg", "pi", "piacenza", "piedmont", "piemonte", "pisa", "pistoia", "pmn", "pn", "po", "pordenone", "potenza", "pr", "prato", "pt", "pu", "pug", "puglia", "pv", "pz", "ra", "ragusa", "ravenna", "rc", "re", "reggio-calabria", "reggio-emilia", "reggiocalabria", "reggioemilia", "rg", "ri", "rieti", "rimini", "rm", "rn", "ro", "roma", "rome", "rovigo", "sa", "salerno", "sar", "sardegna", "sardinia", "sassari", "savona", "si", "sic", "sicilia", "sicily", "siena", "siracusa", "so", "sondrio", "sp", "sr", "ss", "suedtirol", "sv", "ta", "taa", "taranto", "te", "tempio-olbia", "tempioolbia", "teramo", "terni", "tn", "to", "torino", "tos", "toscana", "tp", "tr", "trani-andria-barletta", "trani-barletta-andria", "traniandriabarletta", "tranibarlettaandria", "trapani", "trentino", "trentino-a-adige", "trentino-aadige", "trentino-alto-adige", "trentino-altoadige", "trentino-s-tirol", "trentino-stirol", "trentino-sud-tirol", "trentino-sudtirol", "trentino-sued-tirol", "trentino-suedtirol", "trentinoa-adige", "trentinoaadige", "trentinoalto-adige", "trentinoaltoadige", "trentinos-tirol", "trentinostirol", "trentinosud-tirol", "trentinosudtirol", "trentinosued-tirol", "trentinosuedtirol", "trento", "treviso", "trieste", "ts", "turin", "tuscany", "tv", "ud", "udine", "umb", "umbria", "urbino-pesaro", "urbinopesaro", "va", "val-d-aosta", "val-daosta", "vald-aosta", "valdaosta", "valle-aosta", "valle-d-aosta", "valle-daosta", "valleaosta", "valled-aosta", "valledaosta", "vallee-aoste", "valleeaoste", "vao", "varese", "vb", "vc", "vda", "ve", "ven", "veneto", "venezia", "venice", "verbania", "vercelli", "verona", "vi", "vibo-valentia", "vibovalentia", "vicenza", "viterbo", "vr", "vs", "vt", "vv", "co", "net", "org", "com", "edu", "gov", "mil", "name", "net", "org", "sch", "ac", "ad", "aichi", "akita", "aomori", "blogspot", "chiba", "co", "ed", "ehime", "fukui", "fukuoka", "fukushima", "gifu", "go", "gr", "gunma", "hiroshima", "hokkaido", "hyogo", "ibaraki", "ishikawa", "iwate", "kagawa", "kagoshima", "kanagawa", "kawasaki", "kitakyushu", "kobe", "kochi", "kumamoto", "kyoto", "lg", "mie", "miyagi", "miyazaki", "nagano", "nagasaki", "nagoya", "nara", "ne", "niigata", "oita", "okayama", "okinawa", "or", "osaka", "saga", "saitama", "sapporo", "sendai", "shiga", "shimane", "shizuoka", "tochigi", "tokushima", "tokyo", "tottori", "toyama", "wakayama", "xn--0trq7p7nn", "xn--1ctwo", "xn--1lqs03n", "xn--1lqs71d", "xn--2m4a15e", "xn--32vp30h", "xn--4it168d", "xn--4it797k", "xn--4pvxs", "xn--5js045d", "xn--5rtp49c", "xn--5rtq34k", "xn--6btw5a", "xn--6orx2r", "xn--7t0a264c", "xn--8ltr62k", "xn--8pvr4u", "xn--c3s14m", "xn--d5qv7z876c", "xn--djrs72d6uy", "xn--djty4k", "xn--efvn9s", "xn--ehqz56n", "xn--elqq16h", "xn--f6qx53a", "xn--k7yn95e", "xn--kbrq7o", "xn--klt787d", "xn--kltp7d", "xn--kltx9a", "xn--klty5x", "xn--mkru45i", "xn--nit225k", "xn--ntso0iqx3a", "xn--ntsq17g", "xn--pssu33l", "xn--qqqt11m", "xn--rht27z", "xn--rht3d", "xn--rht61e", "xn--rny31h", "xn--tor131o", "xn--uist22h", "xn--uisz3g", "xn--uuwu58a", "xn--vgu402c", "xn--zbx025d", "yamagata", "yamaguchi", "yamanashi", "yokohama", "aisai", "ama", "anjo", "asuke", "chiryu", "chita", "fuso", "gamagori", "handa", "hazu", "hekinan", "higashiura", "ichinomiya", "inazawa", "inuyama", "isshiki", "iwakura", "kanie", "kariya", "kasugai", "kira", "kiyosu", "komaki", "konan", "kota", "mihama", "miyoshi", "nishio", "nisshin", "obu", "oguchi", "oharu", "okazaki", "owariasahi", "seto", "shikatsu", "shinshiro", "shitara", "tahara", "takahama", "tobishima", "toei", "togo", "tokai", "tokoname", "toyoake", "toyohashi", "toyokawa", "toyone", "toyota", "tsushima", "yatomi", "akita", "daisen", "fujisato", "gojome", "hachirogata", "happou", "higashinaruse", "honjo", "honjyo", "ikawa", "kamikoani", "kamioka", "katagami", "kazuno", "kitaakita", "kosaka", "kyowa", "misato", "mitane", "moriyoshi", "nikaho", "noshiro", "odate", "oga", "ogata", "semboku", "yokote", "yurihonjo", "aomori", "gonohe", "hachinohe", "hashikami", "hiranai", "hirosaki", "itayanagi", "kuroishi", "misawa", "mutsu", "nakadomari", "noheji", "oirase", "owani", "rokunohe", "sannohe", "shichinohe", "shingo", "takko", "towada", "tsugaru", "tsuruta", "abiko", "asahi", "chonan", "chosei", "choshi", "chuo", "funabashi", "futtsu", "hanamigawa", "ichihara", "ichikawa", "ichinomiya", "inzai", "isumi", "kamagaya", "kamogawa", "kashiwa", "katori", "katsuura", "kimitsu", "kisarazu", "kozaki", "kujukuri", "kyonan", "matsudo", "midori", "mihama", "minamiboso", "mobara", "mutsuzawa", "nagara", "nagareyama", "narashino", "narita", "noda", "oamishirasato", "omigawa", "onjuku", "otaki", "sakae", "sakura", "shimofusa", "shirako", "shiroi", "shisui", "sodegaura", "sosa", "tako", "tateyama", "togane", "tohnosho", "tomisato", "urayasu", "yachimata", "yachiyo", "yokaichiba", "yokoshibahikari", "yotsukaido", "ainan", "honai", "ikata", "imabari", "iyo", "kamijima", "kihoku", "kumakogen", "masaki", "matsuno", "matsuyama", "namikata", "niihama", "ozu", "saijo", "seiyo", "shikokuchuo", "tobe", "toon", "uchiko", "uwajima", "yawatahama", "echizen", "eiheiji", "fukui", "ikeda", "katsuyama", "mihama", "minamiechizen", "obama", "ohi", "ono", "sabae", "sakai", "takahama", "tsuruga", "wakasa", "ashiya", "buzen", "chikugo", "chikuho", "chikujo", "chikushino", "chikuzen", "chuo", "dazaifu", "fukuchi", "hakata", "higashi", "hirokawa", "hisayama", "iizuka", "inatsuki", "kaho", "kasuga", "kasuya", "kawara", "keisen", "koga", "kurate", "kurogi", "kurume", "minami", "miyako", "miyama", "miyawaka", "mizumaki", "munakata", "nakagawa", "nakama", "nishi", "nogata", "ogori", "okagaki", "okawa", "oki", "omuta", "onga", "onojo", "oto", "saigawa", "sasaguri", "shingu", "shinyoshitomi", "shonai", "soeda", "sue", "tachiarai", "tagawa", "takata", "toho", "toyotsu", "tsuiki", "ukiha", "umi", "usui", "yamada", "yame", "yanagawa", "yukuhashi", "aizubange", "aizumisato", "aizuwakamatsu", "asakawa", "bandai", "date", "fukushima", "furudono", "futaba", "hanawa", "higashi", "hirata", "hirono", "iitate", "inawashiro", "ishikawa", "iwaki", "izumizaki", "kagamiishi", "kaneyama", "kawamata", "kitakata", "kitashiobara", "koori", "koriyama", "kunimi", "miharu", "mishima", "namie", "nango", "nishiaizu", "nishigo", "okuma", "omotego", "ono", "otama", "samegawa", "shimogo", "shirakawa", "showa", "soma", "sukagawa", "taishin", "tamakawa", "tanagura", "tenei", "yabuki", "yamato", "yamatsuri", "yanaizu", "yugawa", "anpachi", "ena", "gifu", "ginan", "godo", "gujo", "hashima", "hichiso", "hida", "higashishirakawa", "ibigawa", "ikeda", "kakamigahara", "kani", "kasahara", "kasamatsu", "kawaue", "kitagata", "mino", "minokamo", "mitake", "mizunami", "motosu", "nakatsugawa", "ogaki", "sakahogi", "seki", "sekigahara", "shirakawa", "tajimi", "takayama", "tarui", "toki", "tomika", "wanouchi", "yamagata", "yaotsu", "yoro", "annaka", "chiyoda", "fujioka", "higashiagatsuma", "isesaki", "itakura", "kanna", "kanra", "katashina", "kawaba", "kiryu", "kusatsu", "maebashi", "meiwa", "midori", "minakami", "naganohara", "nakanojo", "nanmoku", "numata", "oizumi", "ora", "ota", "shibukawa", "shimonita", "shinto", "showa", "takasaki", "takayama", "tamamura", "tatebayashi", "tomioka", "tsukiyono", "tsumagoi", "ueno", "yoshioka", "asaminami", "daiwa", "etajima", "fuchu", "fukuyama", "hatsukaichi", "higashihiroshima", "hongo", "jinsekikogen", "kaita", "kui", "kumano", "kure", "mihara", "miyoshi", "naka", "onomichi", "osakikamijima", "otake", "saka", "sera", "seranishi", "shinichi", "shobara", "takehara", "abashiri", "abira", "aibetsu", "akabira", "akkeshi", "asahikawa", "ashibetsu", "ashoro", "assabu", "atsuma", "bibai", "biei", "bifuka", "bihoro", "biratori", "chippubetsu", "chitose", "date", "ebetsu", "embetsu", "eniwa", "erimo", "esan", "esashi", "fukagawa", "fukushima", "furano", "furubira", "haboro", "hakodate", "hamatonbetsu", "hidaka", "higashikagura", "higashikawa", "hiroo", "hokuryu", "hokuto", "honbetsu", "horokanai", "horonobe", "ikeda", "imakane", "ishikari", "iwamizawa", "iwanai", "kamifurano", "kamikawa", "kamishihoro", "kamisunagawa", "kamoenai", "kayabe", "kembuchi", "kikonai", "kimobetsu", "kitahiroshima", "kitami", "kiyosato", "koshimizu", "kunneppu", "kuriyama", "kuromatsunai", "kushiro", "kutchan", "kyowa", "mashike", "matsumae", "mikasa", "minamifurano", "mombetsu", "moseushi", "mukawa", "muroran", "naie", "nakagawa", "nakasatsunai", "nakatombetsu", "nanae", "nanporo", "nayoro", "nemuro", "niikappu", "niki", "nishiokoppe", "noboribetsu", "numata", "obihiro", "obira", "oketo", "okoppe", "otaru", "otobe", "otofuke", "otoineppu", "oumu", "ozora", "pippu", "rankoshi", "rebun", "rikubetsu", "rishiri", "rishirifuji", "saroma", "sarufutsu", "shakotan", "shari", "shibecha", "shibetsu", "shikabe", "shikaoi", "shimamaki", "shimizu", "shimokawa", "shinshinotsu", "shintoku", "shiranuka", "shiraoi", "shiriuchi", "sobetsu", "sunagawa", "taiki", "takasu", "takikawa", "takinoue", "teshikaga", "tobetsu", "tohma", "tomakomai", "tomari", "toya", "toyako", "toyotomi", "toyoura", "tsubetsu", "tsukigata", "urakawa", "urausu", "uryu", "utashinai", "wakkanai", "wassamu", "yakumo", "yoichi", "aioi", "akashi", "ako", "amagasaki", "aogaki", "asago", "ashiya", "awaji", "fukusaki", "goshiki", "harima", "himeji", "ichikawa", "inagawa", "itami", "kakogawa", "kamigori", "kamikawa", "kasai", "kasuga", "kawanishi", "miki", "minamiawaji", "nishinomiya", "nishiwaki", "ono", "sanda", "sannan", "sasayama", "sayo", "shingu", "shinonsen", "shiso", "sumoto", "taishi", "taka", "takarazuka", "takasago", "takino", "tamba", "tatsuno", "toyooka", "yabu", "yashiro", "yoka", "yokawa", "ami", "asahi", "bando", "chikusei", "daigo", "fujishiro", "hitachi", "hitachinaka", "hitachiomiya", "hitachiota", "ibaraki", "ina", "inashiki", "itako", "iwama", "joso", "kamisu", "kasama", "kashima", "kasumigaura", "koga", "miho", "mito", "moriya", "naka", "namegata", "oarai", "ogawa", "omitama", "ryugasaki", "sakai", "sakuragawa", "shimodate", "shimotsuma", "shirosato", "sowa", "suifu", "takahagi", "tamatsukuri", "tokai", "tomobe", "tone", "toride", "tsuchiura", "tsukuba", "uchihara", "ushiku", "yachiyo", "yamagata", "yawara", "yuki", "anamizu", "hakui", "hakusan", "kaga", "kahoku", "kanazawa", "kawakita", "komatsu", "nakanoto", "nanao", "nomi", "nonoichi", "noto", "shika", "suzu", "tsubata", "tsurugi", "uchinada", "wajima", "fudai", "fujisawa", "hanamaki", "hiraizumi", "hirono", "ichinohe", "ichinoseki", "iwaizumi", "iwate", "joboji", "kamaishi", "kanegasaki", "karumai", "kawai", "kitakami", "kuji", "kunohe", "kuzumaki", "miyako", "mizusawa", "morioka", "ninohe", "noda", "ofunato", "oshu", "otsuchi", "rikuzentakata", "shiwa", "shizukuishi", "sumita", "tanohata", "tono", "yahaba", "yamada", "ayagawa", "higashikagawa", "kanonji", "kotohira", "manno", "marugame", "mitoyo", "naoshima", "sanuki", "tadotsu", "takamatsu", "tonosho", "uchinomi", "utazu", "zentsuji", "akune", "amami", "hioki", "isa", "isen", "izumi", "kagoshima", "kanoya", "kawanabe", "kinko", "kouyama", "makurazaki", "matsumoto", "minamitane", "nakatane", "nishinoomote", "satsumasendai", "soo", "tarumizu", "yusui", "aikawa", "atsugi", "ayase", "chigasaki", "ebina", "fujisawa", "hadano", "hakone", "hiratsuka", "isehara", "kaisei", "kamakura", "kiyokawa", "matsuda", "minamiashigara", "miura", "nakai", "ninomiya", "odawara", "oi", "oiso", "sagamihara", "samukawa", "tsukui", "yamakita", "yamato", "yokosuka", "yugawara", "zama", "zushi", "city", "city", "city", "aki", "geisei", "hidaka", "higashitsuno", "ino", "kagami", "kami", "kitagawa", "kochi", "mihara", "motoyama", "muroto", "nahari", "nakamura", "nankoku", "nishitosa", "niyodogawa", "ochi", "okawa", "otoyo", "otsuki", "sakawa", "sukumo", "susaki", "tosa", "tosashimizu", "toyo", "tsuno", "umaji", "yasuda", "yusuhara", "amakusa", "arao", "aso", "choyo", "gyokuto", "hitoyoshi", "kamiamakusa", "kashima", "kikuchi", "kosa", "kumamoto", "mashiki", "mifune", "minamata", "minamioguni", "nagasu", "nishihara", "oguni", "ozu", "sumoto", "takamori", "uki", "uto", "yamaga", "yamato", "yatsushiro", "ayabe", "fukuchiyama", "higashiyama", "ide", "ine", "joyo", "kameoka", "kamo", "kita", "kizu", "kumiyama", "kyotamba", "kyotanabe", "kyotango", "maizuru", "minami", "minamiyamashiro", "miyazu", "muko", "nagaokakyo", "nakagyo", "nantan", "oyamazaki", "sakyo", "seika", "tanabe", "uji", "ujitawara", "wazuka", "yamashina", "yawata", "asahi", "inabe", "ise", "kameyama", "kawagoe", "kiho", "kisosaki", "kiwa", "komono", "kumano", "kuwana", "matsusaka", "meiwa", "mihama", "minamiise", "misugi", "miyama", "nabari", "shima", "suzuka", "tado", "taiki", "taki", "tamaki", "toba", "tsu", "udono", "ureshino", "watarai", "yokkaichi", "furukawa", "higashimatsushima", "ishinomaki", "iwanuma", "kakuda", "kami", "kawasaki", "kesennuma", "marumori", "matsushima", "minamisanriku", "misato", "murata", "natori", "ogawara", "ohira", "onagawa", "osaki", "rifu", "semine", "shibata", "shichikashuku", "shikama", "shiogama", "shiroishi", "tagajo", "taiwa", "tome", "tomiya", "wakuya", "watari", "yamamoto", "zao", "aya", "ebino", "gokase", "hyuga", "kadogawa", "kawaminami", "kijo", "kitagawa", "kitakata", "kitaura", "kobayashi", "kunitomi", "kushima", "mimata", "miyakonojo", "miyazaki", "morotsuka", "nichinan", "nishimera", "nobeoka", "saito", "shiiba", "shintomi", "takaharu", "takanabe", "takazaki", "tsuno", "achi", "agematsu", "anan", "aoki", "asahi", "azumino", "chikuhoku", "chikuma", "chino", "fujimi", "hakuba", "hara", "hiraya", "iida", "iijima", "iiyama", "iizuna", "ikeda", "ikusaka", "ina", "karuizawa", "kawakami", "kiso", "kisofukushima", "kitaaiki", "komagane", "komoro", "matsukawa", "matsumoto", "miasa", "minamiaiki", "minamimaki", "minamiminowa", "minowa", "miyada", "miyota", "mochizuki", "nagano", "nagawa", "nagiso", "nakagawa", "nakano", "nozawaonsen", "obuse", "ogawa", "okaya", "omachi", "omi", "ookuwa", "ooshika", "otaki", "otari", "sakae", "sakaki", "saku", "sakuho", "shimosuwa", "shinanomachi", "shiojiri", "suwa", "suzaka", "takagi", "takamori", "takayama", "tateshina", "tatsuno", "togakushi", "togura", "tomi", "ueda", "wada", "yamagata", "yamanouchi", "yasaka", "yasuoka", "chijiwa", "futsu", "goto", "hasami", "hirado", "iki", "isahaya", "kawatana", "kuchinotsu", "matsuura", "nagasaki", "obama", "omura", "oseto", "saikai", "sasebo", "seihi", "shimabara", "shinkamigoto", "togitsu", "tsushima", "unzen", "city", "ando", "gose", "heguri", "higashiyoshino", "ikaruga", "ikoma", "kamikitayama", "kanmaki", "kashiba", "kashihara", "katsuragi", "kawai", "kawakami", "kawanishi", "koryo", "kurotaki", "mitsue", "miyake", "nara", "nosegawa", "oji", "ouda", "oyodo", "sakurai", "sango", "shimoichi", "shimokitayama", "shinjo", "soni", "takatori", "tawaramoto", "tenkawa", "tenri", "uda", "yamatokoriyama", "yamatotakada", "yamazoe", "yoshino", "aga", "agano", "gosen", "itoigawa", "izumozaki", "joetsu", "kamo", "kariwa", "kashiwazaki", "minamiuonuma", "mitsuke", "muika", "murakami", "myoko", "nagaoka", "niigata", "ojiya", "omi", "sado", "sanjo", "seiro", "seirou", "sekikawa", "shibata", "tagami", "tainai", "tochio", "tokamachi", "tsubame", "tsunan", "uonuma", "yahiko", "yoita", "yuzawa", "beppu", "bungoono", "bungotakada", "hasama", "hiji", "himeshima", "hita", "kamitsue", "kokonoe", "kuju", "kunisaki", "kusu", "oita", "saiki", "taketa", "tsukumi", "usa", "usuki", "yufu", "akaiwa", "asakuchi", "bizen", "hayashima", "ibara", "kagamino", "kasaoka", "kibichuo", "kumenan", "kurashiki", "maniwa", "misaki", "nagi", "niimi", "nishiawakura", "okayama", "satosho", "setouchi", "shinjo", "shoo", "soja", "takahashi", "tamano", "tsuyama", "wake", "yakage", "aguni", "ginowan", "ginoza", "gushikami", "haebaru", "higashi", "hirara", "iheya", "ishigaki", "ishikawa", "itoman", "izena", "kadena", "kin", "kitadaito", "kitanakagusuku", "kumejima", "kunigami", "minamidaito", "motobu", "nago", "naha", "nakagusuku", "nakijin", "nanjo", "nishihara", "ogimi", "okinawa", "onna", "shimoji", "taketomi", "tarama", "tokashiki", "tomigusuku", "tonaki", "urasoe", "uruma", "yaese", "yomitan", "yonabaru", "yonaguni", "zamami", "abeno", "chihayaakasaka", "chuo", "daito", "fujiidera", "habikino", "hannan", "higashiosaka", "higashisumiyoshi", "higashiyodogawa", "hirakata", "ibaraki", "ikeda", "izumi", "izumiotsu", "izumisano", "kadoma", "kaizuka", "kanan", "kashiwara", "katano", "kawachinagano", "kishiwada", "kita", "kumatori", "matsubara", "minato", "minoh", "misaki", "moriguchi", "neyagawa", "nishi", "nose", "osakasayama", "sakai", "sayama", "sennan", "settsu", "shijonawate", "shimamoto", "suita", "tadaoka", "taishi", "tajiri", "takaishi", "takatsuki", "tondabayashi", "toyonaka", "toyono", "yao", "ariake", "arita", "fukudomi", "genkai", "hamatama", "hizen", "imari", "kamimine", "kanzaki", "karatsu", "kashima", "kitagata", "kitahata", "kiyama", "kouhoku", "kyuragi", "nishiarita", "ogi", "omachi", "ouchi", "saga", "shiroishi", "taku", "tara", "tosu", "yoshinogari", "arakawa", "asaka", "chichibu", "fujimi", "fujimino", "fukaya", "hanno", "hanyu", "hasuda", "hatogaya", "hatoyama", "hidaka", "higashichichibu", "higashimatsuyama", "honjo", "ina", "iruma", "iwatsuki", "kamiizumi", "kamikawa", "kamisato", "kasukabe", "kawagoe", "kawaguchi", "kawajima", "kazo", "kitamoto", "koshigaya", "kounosu", "kuki", "kumagaya", "matsubushi", "minano", "misato", "miyashiro", "miyoshi", "moroyama", "nagatoro", "namegawa", "niiza", "ogano", "ogawa", "ogose", "okegawa", "omiya", "otaki", "ranzan", "ryokami", "saitama", "sakado", "satte", "sayama", "shiki", "shiraoka", "soka", "sugito", "toda", "tokigawa", "tokorozawa", "tsurugashima", "urawa", "warabi", "yashio", "yokoze", "yono", "yorii", "yoshida", "yoshikawa", "yoshimi", "city", "city", "aisho", "gamo", "higashiomi", "hikone", "koka", "konan", "kosei", "koto", "kusatsu", "maibara", "moriyama", "nagahama", "nishiazai", "notogawa", "omihachiman", "otsu", "ritto", "ryuoh", "takashima", "takatsuki", "torahime", "toyosato", "yasu", "akagi", "ama", "gotsu", "hamada", "higashiizumo", "hikawa", "hikimi", "izumo", "kakinoki", "masuda", "matsue", "misato", "nishinoshima", "ohda", "okinoshima", "okuizumo", "shimane", "tamayu", "tsuwano", "unnan", "yakumo", "yasugi", "yatsuka", "arai", "atami", "fuji", "fujieda", "fujikawa", "fujinomiya", "fukuroi", "gotemba", "haibara", "hamamatsu", "higashiizu", "ito", "iwata", "izu", "izunokuni", "kakegawa", "kannami", "kawanehon", "kawazu", "kikugawa", "kosai", "makinohara", "matsuzaki", "minamiizu", "mishima", "morimachi", "nishiizu", "numazu", "omaezaki", "shimada", "shimizu", "shimoda", "shizuoka", "susono", "yaizu", "yoshida", "ashikaga", "bato", "haga", "ichikai", "iwafune", "kaminokawa", "kanuma", "karasuyama", "kuroiso", "mashiko", "mibu", "moka", "motegi", "nasu", "nasushiobara", "nikko", "nishikata", "nogi", "ohira", "ohtawara", "oyama", "sakura", "sano", "shimotsuke", "shioya", "takanezawa", "tochigi", "tsuga", "ujiie", "utsunomiya", "yaita", "aizumi", "anan", "ichiba", "itano", "kainan", "komatsushima", "matsushige", "mima", "minami", "miyoshi", "mugi", "nakagawa", "naruto", "sanagochi", "shishikui", "tokushima", "wajiki", "adachi", "akiruno", "akishima", "aogashima", "arakawa", "bunkyo", "chiyoda", "chofu", "chuo", "edogawa", "fuchu", "fussa", "hachijo", "hachioji", "hamura", "higashikurume", "higashimurayama", "higashiyamato", "hino", "hinode", "hinohara", "inagi", "itabashi", "katsushika", "kita", "kiyose", "kodaira", "koganei", "kokubunji", "komae", "koto", "kouzushima", "kunitachi", "machida", "meguro", "minato", "mitaka", "mizuho", "musashimurayama", "musashino", "nakano", "nerima", "ogasawara", "okutama", "ome", "oshima", "ota", "setagaya", "shibuya", "shinagawa", "shinjuku", "suginami", "sumida", "tachikawa", "taito", "tama", "toshima", "chizu", "hino", "kawahara", "koge", "kotoura", "misasa", "nanbu", "nichinan", "sakaiminato", "tottori", "wakasa", "yazu", "yonago", "asahi", "fuchu", "fukumitsu", "funahashi", "himi", "imizu", "inami", "johana", "kamiichi", "kurobe", "nakaniikawa", "namerikawa", "nanto", "nyuzen", "oyabe", "taira", "takaoka", "tateyama", "toga", "tonami", "toyama", "unazuki", "uozu", "yamada", "arida", "aridagawa", "gobo", "hashimoto", "hidaka", "hirogawa", "inami", "iwade", "kainan", "kamitonda", "katsuragi", "kimino", "kinokawa", "kitayama", "koya", "koza", "kozagawa", "kudoyama", "kushimoto", "mihama", "misato", "nachikatsuura", "shingu", "shirahama", "taiji", "tanabe", "wakayama", "yuasa", "yura", "asahi", "funagata", "higashine", "iide", "kahoku", "kaminoyama", "kaneyama", "kawanishi", "mamurogawa", "mikawa", "murayama", "nagai", "nakayama", "nanyo", "nishikawa", "obanazawa", "oe", "oguni", "ohkura", "oishida", "sagae", "sakata", "sakegawa", "shinjo", "shirataka", "shonai", "takahata", "tendo", "tozawa", "tsuruoka", "yamagata", "yamanobe", "yonezawa", "yuza", "abu", "hagi", "hikari", "hofu", "iwakuni", "kudamatsu", "mitou", "nagato", "oshima", "shimonoseki", "shunan", "tabuse", "tokuyama", "toyota", "ube", "yuu", "chuo", "doshi", "fuefuki", "fujikawa", "fujikawaguchiko", "fujiyoshida", "hayakawa", "hokuto", "ichikawamisato", "kai", "kofu", "koshu", "kosuge", "minami-alps", "minobu", "nakamichi", "nanbu", "narusawa", "nirasaki", "nishikatsura", "oshino", "otsuki", "showa", "tabayama", "tsuru", "uenohara", "yamanakako", "yamanashi", "city", "co", "blogspot", "com", "edu", "gov", "mil", "net", "org", "biz", "com", "edu", "gov", "info", "net", "org", "ass", "asso", "com", "coop", "edu", "gouv", "gov", "medecin", "mil", "nom", "notaires", "org", "pharmaciens", "prd", "presse", "tm", "veterinaire", "edu", "gov", "net", "org", "com", "edu", "gov", "org", "rep", "tra", "ac", "blogspot", "busan", "chungbuk", "chungnam", "co", "daegu", "daejeon", "es", "gangwon", "go", "gwangju", "gyeongbuk", "gyeonggi", "gyeongnam", "hs", "incheon", "jeju", "jeonbuk", "jeonnam", "kg", "mil", "ms", "ne", "or", "pe", "re", "sc", "seoul", "ulsan", "com", "edu", "gov", "net", "org", "com", "edu", "gov", "mil", "net", "org", "c", "com", "edu", "gov", "info", "int", "net", "org", "per", "com", "edu", "gov", "net", "org", "co", "com", "edu", "gov", "net", "org", "blogspot", "ac", "assn", "com", "edu", "gov", "grp", "hotel", "int", "ltd", "net", "ngo", "org", "sch", "soc", "web", "com", "edu", "gov", "net", "org", "co", "org", "blogspot", "gov", "blogspot", "asn", "com", "conf", "edu", "gov", "id", "mil", "net", "org", "com", "edu", "gov", "id", "med", "net", "org", "plc", "sch", "ac", "co", "gov", "net", "org", "press", "asso", "tm", "blogspot", "ac", "co", "edu", "gov", "its", "net", "org", "priv", "com", "edu", "gov", "mil", "nom", "org", "prd", "tm", "blogspot", "com", "edu", "gov", "inf", "name", "net", "org", "com", "edu", "gouv", "gov", "net", "org", "presse", "edu", "gov", "nyc", "org", "com", "edu", "gov", "net", "org", "blogspot", "gov", "com", "edu", "gov", "net", "org", "com", "edu", "net", "org", "blogspot", "ac", "co", "com", "gov", "net", "or", "org", "academy", "agriculture", "air", "airguard", "alabama", "alaska", "amber", "ambulance", "american", "americana", "americanantiques", "americanart", "amsterdam", "and", "annefrank", "anthro", "anthropology", "antiques", "aquarium", "arboretum", "archaeological", "archaeology", "architecture", "art", "artanddesign", "artcenter", "artdeco", "arteducation", "artgallery", "arts", "artsandcrafts", "asmatart", "assassination", "assisi", "association", "astronomy", "atlanta", "austin", "australia", "automotive", "aviation", "axis", "badajoz", "baghdad", "bahn", "bale", "baltimore", "barcelona", "baseball", "basel", "baths", "bauern", "beauxarts", "beeldengeluid", "bellevue", "bergbau", "berkeley", "berlin", "bern", "bible", "bilbao", "bill", "birdart", "birthplace", "bonn", "boston", "botanical", "botanicalgarden", "botanicgarden", "botany", "brandywinevalley", "brasil", "bristol", "british", "britishcolumbia", "broadcast", "brunel", "brussel", "brussels", "bruxelles", "building", "burghof", "bus", "bushey", "cadaques", "california", "cambridge", "can", "canada", "capebreton", "carrier", "cartoonart", "casadelamoneda", "castle", "castres", "celtic", "center", "chattanooga", "cheltenham", "chesapeakebay", "chicago", "children", "childrens", "childrensgarden", "chiropractic", "chocolate", "christiansburg", "cincinnati", "cinema", "circus", "civilisation", "civilization", "civilwar", "clinton", "clock", "coal", "coastaldefence", "cody", "coldwar", "collection", "colonialwilliamsburg", "coloradoplateau", "columbia", "columbus", "communication", "communications", "community", "computer", "computerhistory", "contemporary", "contemporaryart", "convent", "copenhagen", "corporation", "corvette", "costume", "countryestate", "county", "crafts", "cranbrook", "creation", "cultural", "culturalcenter", "culture", "cyber", "cymru", "dali", "dallas", "database", "ddr", "decorativearts", "delaware", "delmenhorst", "denmark", "depot", "design", "detroit", "dinosaur", "discovery", "dolls", "donostia", "durham", "eastafrica", "eastcoast", "education", "educational", "egyptian", "eisenbahn", "elburg", "elvendrell", "embroidery", "encyclopedic", "england", "entomology", "environment", "environmentalconservation", "epilepsy", "essex", "estate", "ethnology", "exeter", "exhibition", "family", "farm", "farmequipment", "farmers", "farmstead", "field", "figueres", "filatelia", "film", "fineart", "finearts", "finland", "flanders", "florida", "force", "fortmissoula", "fortworth", "foundation", "francaise", "frankfurt", "franziskaner", "freemasonry", "freiburg", "fribourg", "frog", "fundacio", "furniture", "gallery", "garden", "gateway", "geelvinck", "gemological", "geology", "georgia", "giessen", "glas", "glass", "gorge", "grandrapids", "graz", "guernsey", "halloffame", "hamburg", "handson", "harvestcelebration", "hawaii", "health", "heimatunduhren", "hellas", "helsinki", "hembygdsforbund", "heritage", "histoire", "historical", "historicalsociety", "historichouses", "historisch", "historisches", "history", "historyofscience", "horology", "house", "humanities", "illustration", "imageandsound", "indian", "indiana", "indianapolis", "indianmarket", "intelligence", "interactive", "iraq", "iron", "isleofman", "jamison", "jefferson", "jerusalem", "jewelry", "jewish", "jewishart", "jfk", "journalism", "judaica", "judygarland", "juedisches", "juif", "karate", "karikatur", "kids", "koebenhavn", "koeln", "kunst", "kunstsammlung", "kunstunddesign", "labor", "labour", "lajolla", "lancashire", "landes", "lans", "larsson", "lewismiller", "lincoln", "linz", "living", "livinghistory", "localhistory", "london", "losangeles", "louvre", "loyalist", "lucerne", "luxembourg", "luzern", "mad", "madrid", "mallorca", "manchester", "mansion", "mansions", "manx", "marburg", "maritime", "maritimo", "maryland", "marylhurst", "media", "medical", "medizinhistorisches", "meeres", "memorial", "mesaverde", "michigan", "midatlantic", "military", "mill", "miners", "mining", "minnesota", "missile", "missoula", "modern", "moma", "money", "monmouth", "monticello", "montreal", "moscow", "motorcycle", "muenchen", "muenster", "mulhouse", "muncie", "museet", "museumcenter", "museumvereniging", "music", "national", "nationalfirearms", "nationalheritage", "nativeamerican", "naturalhistory", "naturalhistorymuseum", "naturalsciences", "nature", "naturhistorisches", "natuurwetenschappen", "naumburg", "naval", "nebraska", "neues", "newhampshire", "newjersey", "newmexico", "newport", "newspaper", "newyork", "niepce", "norfolk", "north", "nrw", "nuernberg", "nuremberg", "nyc", "nyny", "oceanographic", "oceanographique", "omaha", "online", "ontario", "openair", "oregon", "oregontrail", "otago", "oxford", "pacific", "paderborn", "palace", "paleo", "palmsprings", "panama", "paris", "pasadena", "pharmacy", "philadelphia", "philadelphiaarea", "philately", "phoenix", "photography", "pilots", "pittsburgh", "planetarium", "plantation", "plants", "plaza", "portal", "portland", "portlligat", "posts-and-telecommunications", "preservation", "presidio", "press", "project", "public", "pubol", "quebec", "railroad", "railway", "research", "resistance", "riodejaneiro", "rochester", "rockart", "roma", "russia", "saintlouis", "salem", "salvadordali", "salzburg", "sandiego", "sanfrancisco", "santabarbara", "santacruz", "santafe", "saskatchewan", "satx", "savannahga", "schlesisches", "schoenbrunn", "schokoladen", "school", "schweiz", "science", "science-fiction", "scienceandhistory", "scienceandindustry", "sciencecenter", "sciencecenters", "sciencehistory", "sciences", "sciencesnaturelles", "scotland", "seaport", "settlement", "settlers", "shell", "sherbrooke", "sibenik", "silk", "ski", "skole", "society", "sologne", "soundandvision", "southcarolina", "southwest", "space", "spy", "square", "stadt", "stalbans", "starnberg", "state", "stateofdelaware", "station", "steam", "steiermark", "stjohn", "stockholm", "stpetersburg", "stuttgart", "suisse", "surgeonshall", "surrey", "svizzera", "sweden", "sydney", "tank", "tcm", "technology", "telekommunikation", "television", "texas", "textile", "theater", "time", "timekeeping", "topology", "torino", "touch", "town", "transport", "tree", "trolley", "trust", "trustee", "uhren", "ulm", "undersea", "university", "usa", "usantiques", "usarts", "uscountryestate", "usculture", "usdecorativearts", "usgarden", "ushistory", "ushuaia", "uslivinghistory", "utah", "uvic", "valley", "vantaa", "versailles", "viking", "village", "virginia", "virtual", "virtuel", "vlaanderen", "volkenkunde", "wales", "wallonie", "war", "washingtondc", "watch-and-clock", "watchandclock", "western", "westfalen", "whaling", "wildlife", "williamsburg", "windmill", "workshop", "xn--9dbhblg6di", "xn--comunicaes-v6a2o", "xn--correios-e-telecomunicaes-ghc29a", "xn--h1aegh", "xn--lns-qla", "york", "yorkshire", "yosemite", "youth", "zoological", "zoology", "aero", "biz", "com", "coop", "edu", "gov", "info", "int", "mil", "museum", "name", "net", "org", "pro", "ac", "biz", "co", "com", "coop", "edu", "gov", "int", "museum", "net", "org", "blogspot", "com", "edu", "gob", "net", "org", "blogspot", "com", "edu", "gov", "mil", "name", "net", "org", "teledata", "ca", "cc", "co", "com", "dr", "in", "info", "mobi", "mx", "name", "or", "org", "pro", "school", "tv", "us", "ws", "her", "his", "forgot", "forgot", "asso", "at-band-camp", "azure-mobile", "azurewebsites", "blogdns", "broke-it", "buyshouses", "cdn77", "cdn77-ssl", "cloudapp", "cloudfront", "dnsalias", "dnsdojo", "does-it", "dontexist", "dynalias", "dynathome", "endofinternet", "fastly", "from-az", "from-co", "from-la", "from-ny", "gb", "gets-it", "ham-radio-op", "homeftp", "homeip", "homelinux", "homeunix", "hu", "in", "in-the-band", "is-a-chef", "is-a-geek", "isa-geek", "jp", "kicks-ass", "office-on-the", "podzone", "scrapper-site", "se", "selfip", "sells-it", "servebbs", "serveftp", "thruhere", "uk", "webhop", "za", "r", "prod", "ssl", "a", "global", "a", "b", "global", "arts", "com", "firm", "info", "net", "other", "per", "rec", "store", "web", "com", "edu", "gov", "mil", "mobi", "name", "net", "org", "sch", "blogspot", "blogspot", "bv", "co", "aa", "aarborte", "aejrie", "afjord", "agdenes", "ah", "akershus", "aknoluokta", "akrehamn", "al", "alaheadju", "alesund", "algard", "alstahaug", "alta", "alvdal", "amli", "amot", "andasuolo", "andebu", "andoy", "ardal", "aremark", "arendal", "arna", "aseral", "asker", "askim", "askoy", "askvoll", "asnes", "audnedaln", "aukra", "aure", "aurland", "aurskog-holand", "austevoll", "austrheim", "averoy", "badaddja", "bahcavuotna", "bahccavuotna", "baidar", "bajddar", "balat", "balestrand", "ballangen", "balsfjord", "bamble", "bardu", "barum", "batsfjord", "bearalvahki", "beardu", "beiarn", "berg", "bergen", "berlevag", "bievat", "bindal", "birkenes", "bjarkoy", "bjerkreim", "bjugn", "blogspot", "bodo", "bokn", "bomlo", "bremanger", "bronnoy", "bronnoysund", "brumunddal", "bryne", "bu", "budejju", "buskerud", "bygland", "bykle", "cahcesuolo", "co", "davvenjarga", "davvesiida", "deatnu", "dep", "dielddanuorri", "divtasvuodna", "divttasvuotna", "donna", "dovre", "drammen", "drangedal", "drobak", "dyroy", "egersund", "eid", "eidfjord", "eidsberg", "eidskog", "eidsvoll", "eigersund", "elverum", "enebakk", "engerdal", "etne", "etnedal", "evenassi", "evenes", "evje-og-hornnes", "farsund", "fauske", "fedje", "fet", "fetsund", "fhs", "finnoy", "fitjar", "fjaler", "fjell", "fla", "flakstad", "flatanger", "flekkefjord", "flesberg", "flora", "floro", "fm", "folkebibl", "folldal", "forde", "forsand", "fosnes", "frana", "fredrikstad", "frei", "frogn", "froland", "frosta", "froya", "fuoisku", "fuossko", "fusa", "fylkesbibl", "fyresdal", "gaivuotna", "galsa", "gamvik", "gangaviika", "gaular", "gausdal", "giehtavuoatna", "gildeskal", "giske", "gjemnes", "gjerdrum", "gjerstad", "gjesdal", "gjovik", "gloppen", "gol", "gran", "grane", "granvin", "gratangen", "grimstad", "grong", "grue", "gulen", "guovdageaidnu", "ha", "habmer", "hadsel", "hagebostad", "halden", "halsa", "hamar", "hamaroy", "hammarfeasta", "hammerfest", "hapmir", "haram", "hareid", "harstad", "hasvik", "hattfjelldal", "haugesund", "hedmark", "hemne", "hemnes", "hemsedal", "herad", "hitra", "hjartdal", "hjelmeland", "hl", "hm", "hobol", "hof", "hokksund", "hol", "hole", "holmestrand", "holtalen", "honefoss", "hordaland", "hornindal", "horten", "hoyanger", "hoylandet", "hurdal", "hurum", "hvaler", "hyllestad", "ibestad", "idrett", "inderoy", "iveland", "ivgu", "jan-mayen", "jessheim", "jevnaker", "jolster", "jondal", "jorpeland", "kafjord", "karasjohka", "karasjok", "karlsoy", "karmoy", "kautokeino", "kirkenes", "klabu", "klepp", "kommune", "kongsberg", "kongsvinger", "kopervik", "kraanghke", "kragero", "kristiansand", "kristiansund", "krodsherad", "krokstadelva", "kvafjord", "kvalsund", "kvam", "kvanangen", "kvinesdal", "kvinnherad", "kviteseid", "kvitsoy", "laakesvuemie", "lahppi", "langevag", "lardal", "larvik", "lavagis", "lavangen", "leangaviika", "lebesby", "leikanger", "leirfjord", "leirvik", "leka", "leksvik", "lenvik", "lerdal", "lesja", "levanger", "lier", "lierne", "lillehammer", "lillesand", "lindas", "lindesnes", "loabat", "lodingen", "lom", "loppa", "lorenskog", "loten", "lund", "lunner", "luroy", "luster", "lyngdal", "lyngen", "malatvuopmi", "malselv", "malvik", "mandal", "marker", "marnardal", "masfjorden", "masoy", "matta-varjjat", "meland", "meldal", "melhus", "meloy", "meraker", "midsund", "midtre-gauldal", "mil", "mjondalen", "mo-i-rana", "moareke", "modalen", "modum", "molde", "more-og-romsdal", "mosjoen", "moskenes", "moss", "mosvik", "mr", "muosat", "museum", "naamesjevuemie", "namdalseid", "namsos", "namsskogan", "nannestad", "naroy", "narviika", "narvik", "naustdal", "navuotna", "nedre-eiker", "nesna", "nesodden", "nesoddtangen", "nesseby", "nesset", "nissedal", "nittedal", "nl", "nord-aurdal", "nord-fron", "nord-odal", "norddal", "nordkapp", "nordland", "nordre-land", "nordreisa", "nore-og-uvdal", "notodden", "notteroy", "nt", "odda", "of", "oksnes", "ol", "omasvuotna", "oppdal", "oppegard", "orkanger", "orkdal", "orland", "orskog", "orsta", "osen", "oslo", "osoyro", "osteroy", "ostfold", "ostre-toten", "overhalla", "ovre-eiker", "oyer", "oygarden", "oystre-slidre", "porsanger", "porsangu", "porsgrunn", "priv", "rade", "radoy", "rahkkeravju", "raholt", "raisa", "rakkestad", "ralingen", "rana", "randaberg", "rauma", "rendalen", "rennebu", "rennesoy", "rindal", "ringebu", "ringerike", "ringsaker", "risor", "rissa", "rl", "roan", "rodoy", "rollag", "romsa", "romskog", "roros", "rost", "royken", "royrvik", "ruovat", "rygge", "salangen", "salat", "saltdal", "samnanger", "sandefjord", "sandnes", "sandnessjoen", "sandoy", "sarpsborg", "sauda", "sauherad", "sel", "selbu", "selje", "seljord", "sf", "siellak", "sigdal", "siljan", "sirdal", "skanit", "skanland", "skaun", "skedsmo", "skedsmokorset", "ski", "skien", "skierva", "skiptvet", "skjak", "skjervoy", "skodje", "slattum", "smola", "snaase", "snasa", "snillfjord", "snoasa", "sogndal", "sogne", "sokndal", "sola", "solund", "somna", "sondre-land", "songdalen", "sor-aurdal", "sor-fron", "sor-odal", "sor-varanger", "sorfold", "sorreisa", "sortland", "sorum", "spjelkavik", "spydeberg", "st", "stange", "stat", "stathelle", "stavanger", "stavern", "steigen", "steinkjer", "stjordal", "stjordalshalsen", "stokke", "stor-elvdal", "stord", "stordal", "storfjord", "strand", "stranda", "stryn", "sula", "suldal", "sund", "sunndal", "surnadal", "svalbard", "sveio", "svelvik", "sykkylven", "tana", "tananger", "telemark", "time", "tingvoll", "tinn", "tjeldsund", "tjome", "tm", "tokke", "tolga", "tonsberg", "torsken", "tr", "trana", "tranby", "tranoy", "troandin", "trogstad", "tromsa", "tromso", "trondheim", "trysil", "tvedestrand", "tydal", "tynset", "tysfjord", "tysnes", "tysvar", "ullensaker", "ullensvang", "ulvik", "unjarga", "utsira", "va", "vaapste", "vadso", "vaga", "vagan", "vagsoy", "vaksdal", "valle", "vang", "vanylven", "vardo", "varggat", "varoy", "vefsn", "vega", "vegarshei", "vennesla", "verdal", "verran", "vestby", "vestfold", "vestnes", "vestre-slidre", "vestre-toten", "vestvagoy", "vevelstad", "vf", "vgs", "vik", "vikna", "vindafjord", "voagat", "volda", "voss", "vossevangen", "xn--andy-ira", "xn--asky-ira", "xn--aurskog-hland-jnb", "xn--avery-yua", "xn--bdddj-mrabd", "xn--bearalvhki-y4a", "xn--berlevg-jxa", "xn--bhcavuotna-s4a", "xn--bhccavuotna-k7a", "xn--bidr-5nac", "xn--bievt-0qa", "xn--bjarky-fya", "xn--bjddar-pta", "xn--blt-elab", "xn--bmlo-gra", "xn--bod-2na", "xn--brnny-wuac", "xn--brnnysund-m8ac", "xn--brum-voa", "xn--btsfjord-9za", "xn--davvenjrga-y4a", "xn--dnna-gra", "xn--drbak-wua", "xn--dyry-ira", "xn--eveni-0qa01ga", "xn--finny-yua", "xn--fjord-lra", "xn--fl-zia", "xn--flor-jra", "xn--frde-gra", "xn--frna-woa", "xn--frya-hra", "xn--ggaviika-8ya47h", "xn--gildeskl-g0a", "xn--givuotna-8ya", "xn--gjvik-wua", "xn--gls-elac", "xn--h-2fa", "xn--hbmer-xqa", "xn--hcesuolo-7ya35b", "xn--hgebostad-g3a", "xn--hmmrfeasta-s4ac", "xn--hnefoss-q1a", "xn--hobl-ira", "xn--holtlen-hxa", "xn--hpmir-xqa", "xn--hyanger-q1a", "xn--hylandet-54a", "xn--indery-fya", "xn--jlster-bya", "xn--jrpeland-54a", "xn--karmy-yua", "xn--kfjord-iua", "xn--klbu-woa", "xn--koluokta-7ya57h", "xn--krager-gya", "xn--kranghke-b0a", "xn--krdsherad-m8a", "xn--krehamn-dxa", "xn--krjohka-hwab49j", "xn--ksnes-uua", "xn--kvfjord-nxa", "xn--kvitsy-fya", "xn--kvnangen-k0a", "xn--l-1fa", "xn--laheadju-7ya", "xn--langevg-jxa", "xn--ldingen-q1a", "xn--leagaviika-52b", "xn--lesund-hua", "xn--lgrd-poac", "xn--lhppi-xqa", "xn--linds-pra", "xn--loabt-0qa", "xn--lrdal-sra", "xn--lrenskog-54a", "xn--lt-liac", "xn--lten-gra", "xn--lury-ira", "xn--mely-ira", "xn--merker-kua", "xn--mjndalen-64a", "xn--mlatvuopmi-s4a", "xn--mli-tla", "xn--mlselv-iua", "xn--moreke-jua", "xn--mosjen-eya", "xn--mot-tla", "xn--mre-og-romsdal-qqb", "xn--msy-ula0h", "xn--mtta-vrjjat-k7af", "xn--muost-0qa", "xn--nmesjevuemie-tcba", "xn--nry-yla5g", "xn--nttery-byae", "xn--nvuotna-hwa", "xn--oppegrd-ixa", "xn--ostery-fya", "xn--osyro-wua", "xn--porsgu-sta26f", "xn--rady-ira", "xn--rdal-poa", "xn--rde-ula", "xn--rdy-0nab", "xn--rennesy-v1a", "xn--rhkkervju-01af", "xn--rholt-mra", "xn--risa-5na", "xn--risr-ira", "xn--rland-uua", "xn--rlingen-mxa", "xn--rmskog-bya", "xn--rros-gra", "xn--rskog-uua", "xn--rst-0na", "xn--rsta-fra", "xn--ryken-vua", "xn--ryrvik-bya", "xn--s-1fa", "xn--sandnessjen-ogb", "xn--sandy-yua", "xn--seral-lra", "xn--sgne-gra", "xn--skierv-uta", "xn--skjervy-v1a", "xn--skjk-soa", "xn--sknit-yqa", "xn--sknland-fxa", "xn--slat-5na", "xn--slt-elab", "xn--smla-hra", "xn--smna-gra", "xn--snase-nra", "xn--sndre-land-0cb", "xn--snes-poa", "xn--snsa-roa", "xn--sr-aurdal-l8a", "xn--sr-fron-q1a", "xn--sr-odal-q1a", "xn--sr-varanger-ggb", "xn--srfold-bya", "xn--srreisa-q1a", "xn--srum-gra", "xn--stfold-9xa", "xn--stjrdal-s1a", "xn--stjrdalshalsen-sqb", "xn--stre-toten-zcb", "xn--tjme-hra", "xn--tnsberg-q1a", "xn--trany-yua", "xn--trgstad-r1a", "xn--trna-woa", "xn--troms-zua", "xn--tysvr-vra", "xn--unjrga-rta", "xn--vads-jra", "xn--vard-jra", "xn--vegrshei-c0a", "xn--vestvgy-ixa6o", "xn--vg-yiab", "xn--vgan-qoa", "xn--vgsy-qoa0j", "xn--vre-eiker-k8a", "xn--vrggt-xqad", "xn--vry-yla5g", "xn--yer-zna", "xn--ygarden-p1a", "xn--ystre-slidre-ujb", "gs", "gs", "nes", "gs", "nes", "gs", "os", "valer", "xn--vler-qoa", "gs", "gs", "os", "gs", "heroy", "sande", "gs", "gs", "bo", "heroy", "xn--b-5ga", "xn--hery-ira", "gs", "gs", "gs", "gs", "valer", "gs", "gs", "gs", "gs", "bo", "xn--b-5ga", "gs", "gs", "gs", "sande", "gs", "sande", "xn--hery-ira", "xn--vler-qoa", "biz", "com", "edu", "gov", "info", "net", "org", "merseine", "mine", "shacknet", "ac", "co", "cri", "geek", "gen", "govt", "health", "iwi", "kiwi", "maori", "mil", "net", "org", "parliament", "school", "xn--mori-qsa", "blogspot", "co", "com", "edu", "gov", "med", "museum", "net", "org", "pro", "ae", "blogdns", "blogsite", "boldlygoingnowhere", "cdn77", "cdn77-secure", "dnsalias", "dnsdojo", "doesntexist", "dontexist", "doomdns", "duckdns", "dvrdns", "dynalias", "dyndns", "endofinternet", "endoftheinternet", "eu", "from-me", "game-host", "gotdns", "hk", "hobby-site", "homedns", "homeftp", "homelinux", "homeunix", "is-a-bruinsfan", "is-a-candidate", "is-a-celticsfan", "is-a-chef", "is-a-geek", "is-a-knight", "is-a-linux-user", "is-a-patsfan", "is-a-soxfan", "is-found", "is-lost", "is-saved", "is-very-bad", "is-very-evil", "is-very-good", "is-very-nice", "is-very-sweet", "isa-geek", "kicks-ass", "misconfused", "podzone", "readmyblog", "selfip", "sellsyourhome", "servebbs", "serveftp", "servegame", "stuff-4-sale", "us", "webhop", "za", "c", "rsc", "origin", "ssl", "go", "home", "al", "asso", "at", "au", "be", "bg", "ca", "cd", "ch", "cn", "cy", "cz", "de", "dk", "edu", "ee", "es", "fi", "fr", "gr", "hr", "hu", "ie", "il", "in", "int", "is", "it", "jp", "kr", "lt", "lu", "lv", "mc", "me", "mk", "mt", "my", "net", "ng", "nl", "no", "nz", "paris", "pl", "pt", "q-a", "ro", "ru", "se", "si", "sk", "tr", "uk", "us", "abo", "ac", "com", "edu", "gob", "ing", "med", "net", "nom", "org", "sld", "blogspot", "com", "edu", "gob", "mil", "net", "nom", "org", "com", "edu", "org", "com", "edu", "gov", "i", "mil", "net", "ngo", "org", "biz", "com", "edu", "fam", "gob", "gok", "gon", "gop", "gos", "gov", "info", "net", "org", "web", "agro", "aid", "art", "atm", "augustow", "auto", "babia-gora", "bedzin", "beskidy", "bialowieza", "bialystok", "bielawa", "bieszczady", "biz", "boleslawiec", "bydgoszcz", "bytom", "cieszyn", "co", "com", "czeladz", "czest", "dlugoleka", "edu", "elblag", "elk", "gda", "gdansk", "gdynia", "gliwice", "glogow", "gmina", "gniezno", "gorlice", "gov", "grajewo", "gsm", "ilawa", "info", "jaworzno", "jelenia-gora", "jgora", "kalisz", "karpacz", "kartuzy", "kaszuby", "katowice", "kazimierz-dolny", "kepno", "ketrzyn", "klodzko", "kobierzyce", "kolobrzeg", "konin", "konskowola", "krakow", "kutno", "lapy", "lebork", "legnica", "lezajsk", "limanowa", "lomza", "lowicz", "lubin", "lukow", "mail", "malbork", "malopolska", "mazowsze", "mazury", "med", "media", "miasta", "mielec", "mielno", "mil", "mragowo", "naklo", "net", "nieruchomosci", "nom", "nowaruda", "nysa", "olawa", "olecko", "olkusz", "olsztyn", "opoczno", "opole", "org", "ostroda", "ostroleka", "ostrowiec", "ostrowwlkp", "pc", "pila", "pisz", "podhale", "podlasie", "polkowice", "pomorskie", "pomorze", "powiat", "poznan", "priv", "prochowice", "pruszkow", "przeworsk", "pulawy", "radom", "rawa-maz", "realestate", "rel", "rybnik", "rzeszow", "sanok", "sejny", "sex", "shop", "sklep", "skoczow", "slask", "slupsk", "sopot", "sos", "sosnowiec", "stalowa-wola", "starachowice", "stargard", "suwalki", "swidnica", "swiebodzin", "swinoujscie", "szczecin", "szczytno", "szkola", "targi", "tarnobrzeg", "tgory", "tm", "tourism", "travel", "turek", "turystyka", "tychy", "ustka", "walbrzych", "warmia", "warszawa", "waw", "wegrow", "wielun", "wlocl", "wloclawek", "wodzislaw", "wolomin", "wroc", "wroclaw", "zachpomor", "zagan", "zakopane", "zarow", "zgora", "zgorzelec", "ap", "griw", "ic", "is", "kmpsp", "konsulat", "kppsp", "kwp", "kwpsp", "mup", "mw", "oirm", "oum", "pa", "pinb", "piw", "po", "psp", "psse", "pup", "rzgw", "sa", "sdn", "sko", "so", "sr", "starostwo", "ug", "ugim", "um", "umig", "upow", "uppo", "us", "uw", "uzs", "wif", "wiih", "winb", "wios", "witd", "wiw", "wsa", "wskr", "wuoz", "wzmiuw", "zp", "co", "edu", "gov", "net", "org", "ac", "biz", "com", "edu", "est", "gov", "info", "isla", "name", "net", "org", "pro", "prof", "aca", "bar", "cpa", "eng", "jur", "law", "med", "com", "edu", "gov", "net", "org", "plo", "sec", "blogspot", "com", "edu", "gov", "int", "net", "nome", "org", "publ", "belau", "co", "ed", "go", "ne", "or", "com", "coop", "edu", "gov", "mil", "net", "org", "blogspot", "com", "edu", "gov", "mil", "name", "net", "org", "sch", "asso", "blogspot", "com", "nom", "arts", "blogspot", "com", "firm", "info", "nom", "nt", "org", "rec", "store", "tm", "www", "ac", "blogspot", "co", "edu", "gov", "in", "org", "ac", "adygeya", "altai", "amur", "amursk", "arkhangelsk", "astrakhan", "baikal", "bashkiria", "belgorod", "bir", "blogspot", "bryansk", "buryatia", "cbg", "chel", "chelyabinsk", "chita", "chukotka", "chuvashia", "cmw", "com", "dagestan", "dudinka", "e-burg", "edu", "fareast", "gov", "grozny", "int", "irkutsk", "ivanovo", "izhevsk", "jamal", "jar", "joshkar-ola", "k-uralsk", "kalmykia", "kaluga", "kamchatka", "karelia", "kazan", "kchr", "kemerovo", "khabarovsk", "khakassia", "khv", "kirov", "kms", "koenig", "komi", "kostroma", "krasnoyarsk", "kuban", "kurgan", "kursk", "kustanai", "kuzbass", "lipetsk", "magadan", "magnitka", "mari", "mari-el", "marine", "mil", "mordovia", "msk", "murmansk", "mytis", "nakhodka", "nalchik", "net", "nkz", "nnov", "norilsk", "nov", "novosibirsk", "nsk", "omsk", "orenburg", "org", "oryol", "oskol", "palana", "penza", "perm", "pp", "ptz", "pyatigorsk", "rnd", "rubtsovsk", "ryazan", "sakhalin", "samara", "saratov", "simbirsk", "smolensk", "snz", "spb", "stavropol", "stv", "surgut", "syzran", "tambov", "tatarstan", "test", "tom", "tomsk", "tsaritsyn", "tsk", "tula", "tuva", "tver", "tyumen", "udm", "udmurtia", "ulan-ude", "vdonsk", "vladikavkaz", "vladimir", "vladivostok", "volgograd", "vologda", "voronezh", "vrn", "vyatka", "yakutia", "yamal", "yaroslavl", "yekaterinburg", "yuzhno-sakhalinsk", "zgrad", "ac", "co", "com", "edu", "gouv", "gov", "int", "mil", "net", "com", "edu", "gov", "med", "net", "org", "pub", "sch", "com", "edu", "gov", "net", "org", "com", "edu", "gov", "net", "org", "com", "edu", "gov", "info", "med", "net", "org", "tv", "a", "ac", "b", "bd", "blogspot", "brand", "c", "com", "d", "e", "f", "fh", "fhsk", "fhv", "g", "h", "i", "k", "komforb", "kommunalforbund", "komvux", "l", "lanbib", "m", "n", "naturbruksgymn", "o", "org", "p", "parti", "pp", "press", "r", "s", "t", "tm", "u", "w", "x", "y", "z", "blogspot", "com", "edu", "gov", "net", "org", "per", "com", "gov", "mil", "net", "org", "platform", "blogspot", "blogspot", "com", "edu", "gov", "net", "org", "art", "blogspot", "com", "edu", "gouv", "org", "perso", "univ", "com", "net", "org", "co", "com", "consulado", "edu", "embaixada", "gov", "mil", "net", "org", "principe", "saotome", "store", "adygeya", "arkhangelsk", "balashov", "bashkiria", "bryansk", "dagestan", "grozny", "ivanovo", "kalmykia", "kaluga", "karelia", "khakassia", "krasnodar", "kurgan", "lenug", "mordovia", "msk", "murmansk", "nalchik", "nov", "obninsk", "penza", "pokrovsk", "sochi", "spb", "togliatti", "troitsk", "tula", "tuva", "vladikavkaz", "vladimir", "vologda", "com", "edu", "gob", "org", "red", "gov", "com", "edu", "gov", "mil", "net", "org", "ac", "co", "org", "blogspot", "ac", "co", "go", "in", "mi", "net", "or", "ac", "biz", "co", "com", "edu", "go", "gov", "int", "mil", "name", "net", "nic", "org", "test", "web", "gov", "co", "com", "edu", "gov", "mil", "net", "nom", "org", "agrinet", "com", "defense", "edunet", "ens", "fin", "gov", "ind", "info", "intl", "mincom", "nat", "net", "org", "perso", "rnrt", "rns", "rnu", "tourism", "turen", "com", "edu", "gov", "mil", "net", "org", "av", "bbs", "bel", "biz", "com", "dr", "edu", "gen", "gov", "info", "k12", "kep", "mil", "name", "nc", "net", "org", "pol", "tel", "tv", "web", "blogspot", "gov", "aero", "biz", "co", "com", "coop", "edu", "gov", "info", "int", "jobs", "mobi", "museum", "name", "net", "org", "pro", "travel", "better-than", "dyndns", "on-the-web", "worse-than", "blogspot", "club", "com", "ebiz", "edu", "game", "gov", "idv", "mil", "net", "org", "xn--czrw28b", "xn--uc0atv", "xn--zf0ao64a", "ac", "co", "go", "hotel", "info", "me", "mil", "mobi", "ne", "or", "sc", "tv", "cherkassy", "cherkasy", "chernigov", "chernihiv", "chernivtsi", "chernovtsy", "ck", "cn", "co", "com", "cr", "crimea", "cv", "dn", "dnepropetrovsk", "dnipropetrovsk", "dominic", "donetsk", "dp", "edu", "gov", "if", "in", "ivano-frankivsk", "kh", "kharkiv", "kharkov", "kherson", "khmelnitskiy", "khmelnytskyi", "kiev", "kirovograd", "km", "kr", "krym", "ks", "kv", "kyiv", "lg", "lt", "lugansk", "lutsk", "lv", "lviv", "mk", "mykolaiv", "net", "nikolaev", "od", "odesa", "odessa", "org", "pl", "poltava", "pp", "rivne", "rovno", "rv", "sb", "sebastopol", "sevastopol", "sm", "sumy", "te", "ternopil", "uz", "uzhgorod", "vinnica", "vinnytsia", "vn", "volyn", "yalta", "zaporizhzhe", "zaporizhzhia", "zhitomir", "zhytomyr", "zp", "zt", "ac", "blogspot", "co", "com", "go", "ne", "or", "org", "sc", "ac", "co", "gov", "ltd", "me", "net", "nhs", "org", "plc", "police", "sch", "blogspot", "service", "ak", "al", "ar", "as", "az", "ca", "co", "ct", "dc", "de", "dni", "fed", "fl", "ga", "gu", "hi", "ia", "id", "il", "in", "is-by", "isa", "kids", "ks", "ky", "la", "land-4-sale", "ma", "md", "me", "mi", "mn", "mo", "ms", "mt", "nc", "nd", "ne", "nh", "nj", "nm", "nsn", "nv", "ny", "oh", "ok", "or", "pa", "pr", "ri", "sc", "sd", "stuff-4-sale", "tn", "tx", "ut", "va", "vi", "vt", "wa", "wi", "wv", "wy", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "chtr", "paroch", "pvt", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "k12", "lib", "cc", "cc", "k12", "lib", "com", "edu", "gub", "mil", "net", "org", "blogspot", "co", "com", "net", "org", "com", "edu", "gov", "mil", "net", "org", "arts", "co", "com", "e12", "edu", "firm", "gob", "gov", "info", "int", "mil", "net", "org", "rec", "store", "tec", "web", "co", "com", "k12", "net", "org", "ac", "biz", "blogspot", "com", "edu", "gov", "health", "info", "int", "name", "net", "org", "pro", "com", "edu", "net", "org", "com", "dyndns", "edu", "gov", "mypets", "net", "org", "xn--80au", "xn--90azh", "xn--c1avg", "xn--d1at", "xn--o1ac", "xn--o1ach", "ac", "agrica", "alt", "co", "edu", "gov", "grondar", "law", "mil", "net", "ngo", "nis", "nom", "org", "school", "tm", "web", "blogspot", } ================================================ FILE: vendor/golang.org/x/net/trace/events.go ================================================ // 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" ) var eventsTmpl = template.Must(template.New("events").Funcs(template.FuncMap{ "elapsed": elapsed, "trimSpace": strings.TrimSpace, }).Parse(eventsHTML)) 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: } } const eventsHTML = ` events

/debug/events

{{range $i, $fam := .Families}} {{range $j, $bucket := $.Buckets}} {{$n := index $.Counts $i $j}} {{end}} {{end}}
{{$fam}} {{if $n}}{{end}} [{{$n}} {{$bucket.String}}] {{if $n}}{{end}}
{{if $.EventLogs}}

Family: {{$.Family}}

{{if $.Expanded}}
{{end}} [Summary]{{if $.Expanded}}{{end}} {{if not $.Expanded}}{{end}} [Expanded]{{if not $.Expanded}}{{end}} {{range $el := $.EventLogs}} {{if $.Expanded}} {{range $el.Events}} {{end}} {{end}} {{end}}
WhenElapsed
{{$el.When}} {{$el.ElapsedTime}} {{$el.Title}}
{{$el.Stack|trimSpace}}
{{.WhenString}} {{elapsed .Elapsed}} .{{if .IsErr}}E{{else}}.{{end}}. {{.What}}
{{end}} ` ================================================ FILE: vendor/golang.org/x/net/trace/histogram.go ================================================ // 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" "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()) } // Input: data var distTmpl = template.Must(template.New("distTmpl").Parse(`
Count: {{.Count}} Mean: {{printf "%.0f" .Mean}} StdDev: {{printf "%.0f" .StandardDeviation}} Median: {{.Median}}

{{range $b := .Buckets}} {{if $b}} {{end}} {{end}}
[ {{.Lower}}, {{.Upper}}) {{.N}} {{printf "%#.3f" .Pct}}% {{printf "%#.3f" .CumulativePct}}%
`)) ================================================ FILE: vendor/golang.org/x/net/trace/histogram_test.go ================================================ // 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 ( "math" "testing" ) type sumTest struct { value int64 sum int64 sumOfSquares float64 total int64 } var sumTests = []sumTest{ {100, 100, 10000, 1}, {50, 150, 12500, 2}, {50, 200, 15000, 3}, {50, 250, 17500, 4}, } type bucketingTest struct { in int64 log int bucket int } var bucketingTests = []bucketingTest{ {0, 0, 0}, {1, 1, 0}, {2, 2, 1}, {3, 2, 1}, {4, 3, 2}, {1000, 10, 9}, {1023, 10, 9}, {1024, 11, 10}, {1000000, 20, 19}, } type multiplyTest struct { in int64 ratio float64 expectedSum int64 expectedTotal int64 expectedSumOfSquares float64 } var multiplyTests = []multiplyTest{ {15, 2.5, 37, 2, 562.5}, {128, 4.6, 758, 13, 77953.9}, } type percentileTest struct { fraction float64 expected int64 } var percentileTests = []percentileTest{ {0.25, 48}, {0.5, 96}, {0.6, 109}, {0.75, 128}, {0.90, 205}, {0.95, 230}, {0.99, 256}, } func TestSum(t *testing.T) { var h histogram for _, test := range sumTests { h.addMeasurement(test.value) sum := h.sum if sum != test.sum { t.Errorf("h.Sum = %v WANT: %v", sum, test.sum) } sumOfSquares := h.sumOfSquares if sumOfSquares != test.sumOfSquares { t.Errorf("h.SumOfSquares = %v WANT: %v", sumOfSquares, test.sumOfSquares) } total := h.total() if total != test.total { t.Errorf("h.Total = %v WANT: %v", total, test.total) } } } func TestMultiply(t *testing.T) { var h histogram for i, test := range multiplyTests { h.addMeasurement(test.in) h.Multiply(test.ratio) if h.sum != test.expectedSum { t.Errorf("#%v: h.sum = %v WANT: %v", i, h.sum, test.expectedSum) } if h.total() != test.expectedTotal { t.Errorf("#%v: h.total = %v WANT: %v", i, h.total(), test.expectedTotal) } if h.sumOfSquares != test.expectedSumOfSquares { t.Errorf("#%v: h.SumOfSquares = %v WANT: %v", i, test.expectedSumOfSquares, h.sumOfSquares) } } } func TestBucketingFunctions(t *testing.T) { for _, test := range bucketingTests { log := log2(test.in) if log != test.log { t.Errorf("log2 = %v WANT: %v", log, test.log) } bucket := getBucket(test.in) if bucket != test.bucket { t.Errorf("getBucket = %v WANT: %v", bucket, test.bucket) } } } func TestAverage(t *testing.T) { a := new(histogram) average := a.average() if average != 0 { t.Errorf("Average of empty histogram was %v WANT: 0", average) } a.addMeasurement(1) a.addMeasurement(1) a.addMeasurement(3) const expected = float64(5) / float64(3) average = a.average() if !isApproximate(average, expected) { t.Errorf("Average = %g WANT: %v", average, expected) } } func TestStandardDeviation(t *testing.T) { a := new(histogram) add(a, 10, 1<<4) add(a, 10, 1<<5) add(a, 10, 1<<6) stdDev := a.standardDeviation() const expected = 19.95 if !isApproximate(stdDev, expected) { t.Errorf("StandardDeviation = %v WANT: %v", stdDev, expected) } // No values a = new(histogram) stdDev = a.standardDeviation() if !isApproximate(stdDev, 0) { t.Errorf("StandardDeviation = %v WANT: 0", stdDev) } add(a, 1, 1<<4) if !isApproximate(stdDev, 0) { t.Errorf("StandardDeviation = %v WANT: 0", stdDev) } add(a, 10, 1<<4) if !isApproximate(stdDev, 0) { t.Errorf("StandardDeviation = %v WANT: 0", stdDev) } } func TestPercentileBoundary(t *testing.T) { a := new(histogram) add(a, 5, 1<<4) add(a, 10, 1<<6) add(a, 5, 1<<7) for _, test := range percentileTests { percentile := a.percentileBoundary(test.fraction) if percentile != test.expected { t.Errorf("h.PercentileBoundary (fraction=%v) = %v WANT: %v", test.fraction, percentile, test.expected) } } } func TestCopyFrom(t *testing.T) { a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 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, 37, 38}, 4, -1} b := histogram{6, 36, []int64{2, 3, 4, 5, 6, 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, 37, 38, 39}, 5, -1} a.CopyFrom(&b) if a.String() != b.String() { t.Errorf("a.String = %s WANT: %s", a.String(), b.String()) } } func TestClear(t *testing.T) { a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 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, 37, 38}, 4, -1} a.Clear() expected := "0, 0.000000, 0, 0, []" if a.String() != expected { t.Errorf("a.String = %s WANT %s", a.String(), expected) } } func TestNew(t *testing.T) { a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 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, 37, 38}, 4, -1} b := a.New() expected := "0, 0.000000, 0, 0, []" if b.(*histogram).String() != expected { t.Errorf("b.(*histogram).String = %s WANT: %s", b.(*histogram).String(), expected) } } func TestAdd(t *testing.T) { // The tests here depend on the associativity of addMeasurement and Add. // Add empty observation a := histogram{5, 25, []int64{1, 2, 3, 4, 5, 6, 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, 37, 38}, 4, -1} b := a.New() expected := a.String() a.Add(b) if a.String() != expected { t.Errorf("a.String = %s WANT: %s", a.String(), expected) } // Add same bucketed value, no new buckets c := new(histogram) d := new(histogram) e := new(histogram) c.addMeasurement(12) d.addMeasurement(11) e.addMeasurement(12) e.addMeasurement(11) c.Add(d) if c.String() != e.String() { t.Errorf("c.String = %s WANT: %s", c.String(), e.String()) } // Add bucketed values f := new(histogram) g := new(histogram) h := new(histogram) f.addMeasurement(4) f.addMeasurement(12) f.addMeasurement(100) g.addMeasurement(18) g.addMeasurement(36) g.addMeasurement(255) h.addMeasurement(4) h.addMeasurement(12) h.addMeasurement(100) h.addMeasurement(18) h.addMeasurement(36) h.addMeasurement(255) f.Add(g) if f.String() != h.String() { t.Errorf("f.String = %q WANT: %q", f.String(), h.String()) } // add buckets to no buckets i := new(histogram) j := new(histogram) k := new(histogram) j.addMeasurement(18) j.addMeasurement(36) j.addMeasurement(255) k.addMeasurement(18) k.addMeasurement(36) k.addMeasurement(255) i.Add(j) if i.String() != k.String() { t.Errorf("i.String = %q WANT: %q", i.String(), k.String()) } // add buckets to single value (no overlap) l := new(histogram) m := new(histogram) n := new(histogram) l.addMeasurement(0) m.addMeasurement(18) m.addMeasurement(36) m.addMeasurement(255) n.addMeasurement(0) n.addMeasurement(18) n.addMeasurement(36) n.addMeasurement(255) l.Add(m) if l.String() != n.String() { t.Errorf("l.String = %q WANT: %q", l.String(), n.String()) } // mixed order o := new(histogram) p := new(histogram) o.addMeasurement(0) o.addMeasurement(2) o.addMeasurement(0) p.addMeasurement(0) p.addMeasurement(0) p.addMeasurement(2) if o.String() != p.String() { t.Errorf("o.String = %q WANT: %q", o.String(), p.String()) } } func add(h *histogram, times int, val int64) { for i := 0; i < times; i++ { h.addMeasurement(val) } } func isApproximate(x, y float64) bool { return math.Abs(x-y) < 1e-2 } ================================================ FILE: vendor/golang.org/x/net/trace/trace.go ================================================ // 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/context" "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 customise its authorisation requirements. // // The default AuthRequest function returns (true, true) iff the request comes from localhost/127.0.0.1/[::1]. var AuthRequest = func(req *http.Request) (any, sensitive bool) { host, _, err := net.SplitHostPort(req.RemoteAddr) switch { case err != nil: // Badly formed address; fail closed. return false, false case host == "localhost" || host == "127.0.0.1" || host == "::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 } 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 } 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") // 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 } // 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.events = make([]event, 0, maxEventsPerTrace) 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 What interface{} // string or fmt.Stringer Sensitive bool // whether this event contains sensitive information } // 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 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 } 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.events = nil tr.refs = 0 tr.recycler = nil tr.disc = 0 tr.finishStack = nil } // 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 requestz.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) < cap(tr.events) { tr.events = append(tr.events, e) } else { // Discard the middle events. di := int((cap(tr.events) - 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[cap(tr.events)-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.events = make([]event, 0, 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 pageTmpl = template.Must(template.New("Page").Funcs(template.FuncMap{ "elapsed": elapsed, "add": func(a, b int) int { return a + b }, }).Parse(pageHTML)) const pageHTML = ` {{template "Prolog" .}} {{template "StatusTable" .}} {{template "Epilog" .}} {{define "Prolog"}} /debug/requests

/debug/requests

{{end}} {{/* end of Prolog */}} {{define "StatusTable"}} {{range $fam := .Families}} {{$n := index $.ActiveTraceCount $fam}} {{$f := index $.CompletedTraces $fam}} {{range $i, $b := $f.Buckets}} {{$empty := $b.Empty}} {{end}} {{$nb := len $f.Buckets}} {{end}}
{{$fam}} {{if $n}}{{end}} [{{$n}} active] {{if $n}}{{end}} {{if not $empty}}{{end}} [{{.Cond}}] {{if not $empty}}{{end}} [minute] [hour] [total]
{{end}} {{/* end of StatusTable */}} {{define "Epilog"}} {{if $.Traces}}

Family: {{$.Family}}

{{if or $.Expanded $.Traced}} [Normal/Summary] {{else}} [Normal/Summary] {{end}} {{if or (not $.Expanded) $.Traced}} [Normal/Expanded] {{else}} [Normal/Expanded] {{end}} {{if not $.Active}} {{if or $.Expanded (not $.Traced)}} [Traced/Summary] {{else}} [Traced/Summary] {{end}} {{if or (not $.Expanded) (not $.Traced)}} [Traced/Expanded] {{else}} [Traced/Expanded] {{end}} {{end}} {{if $.Total}}

Showing {{len $.Traces}} of {{$.Total}} traces.

{{end}} {{range $tr := $.Traces}} {{/* TODO: include traceID/spanID */}} {{if $.Expanded}} {{range $tr.Events}} {{end}} {{end}} {{end}}
{{if $.Active}}Active{{else}}Completed{{end}} Requests
WhenElapsed (s)
{{$tr.When}} {{$tr.ElapsedTime}} {{$tr.Title}}
{{.WhenString}} {{elapsed .Elapsed}} {{if or $.ShowSensitive (not .Sensitive)}}... {{.What}}{{else}}[redacted]{{end}}
{{end}} {{/* if $.Traces */}} {{if $.Histogram}}

Latency (µs) of {{$.Family}} over {{$.HistogramWindow}}

{{$.Histogram}} {{end}} {{/* if $.Histogram */}} {{end}} {{/* end of Epilog */}} ` ================================================ FILE: vendor/golang.org/x/net/trace/trace_test.go ================================================ // 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 ( "reflect" "testing" ) type s struct{} func (s) String() string { return "lazy string" } // TestReset checks whether all the fields are zeroed after reset. func TestReset(t *testing.T) { tr := New("foo", "bar") tr.LazyLog(s{}, false) tr.LazyPrintf("%d", 1) tr.SetRecycler(func(_ interface{}) {}) tr.SetTraceInfo(3, 4) tr.SetMaxEvents(100) tr.SetError() tr.Finish() tr.(*trace).reset() if !reflect.DeepEqual(tr, new(trace)) { t.Errorf("reset didn't clear all fields: %+v", tr) } } // TestResetLog checks whether all the fields are zeroed after reset. func TestResetLog(t *testing.T) { el := NewEventLog("foo", "bar") el.Printf("message") el.Errorf("error") el.Finish() el.(*eventLog).reset() if !reflect.DeepEqual(el, new(eventLog)) { t.Errorf("reset didn't clear all fields: %+v", el) } } ================================================ FILE: vendor/golang.org/x/net/webdav/file.go ================================================ // 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 webdav import ( "io" "net/http" "os" "path" "path/filepath" "strings" "sync" "time" "golang.org/x/net/webdav/internal/xml" ) // slashClean is equivalent to but slightly more efficient than // path.Clean("/" + name). func slashClean(name string) string { if name == "" || name[0] != '/' { name = "/" + name } return path.Clean(name) } // A FileSystem implements access to a collection of named files. The elements // in a file path are separated by slash ('/', U+002F) characters, regardless // of host operating system convention. // // Each method has the same semantics as the os package's function of the same // name. // // Note that the os.Rename documentation says that "OS-specific restrictions // might apply". In particular, whether or not renaming a file or directory // overwriting another existing file or directory is an error is OS-dependent. type FileSystem interface { Mkdir(name string, perm os.FileMode) error OpenFile(name string, flag int, perm os.FileMode) (File, error) RemoveAll(name string) error Rename(oldName, newName string) error Stat(name string) (os.FileInfo, error) } // A File is returned by a FileSystem's OpenFile method and can be served by a // Handler. // // A File may optionally implement the DeadPropsHolder interface, if it can // load and save dead properties. type File interface { http.File io.Writer } // A Dir implements FileSystem using the native file system restricted to a // specific directory tree. // // While the FileSystem.OpenFile method takes '/'-separated paths, a Dir's // string value is a filename on the native file system, not a URL, so it is // separated by filepath.Separator, which isn't necessarily '/'. // // An empty Dir is treated as ".". type Dir string func (d Dir) resolve(name string) string { // This implementation is based on Dir.Open's code in the standard net/http package. if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 || strings.Contains(name, "\x00") { return "" } dir := string(d) if dir == "" { dir = "." } return filepath.Join(dir, filepath.FromSlash(slashClean(name))) } func (d Dir) Mkdir(name string, perm os.FileMode) error { if name = d.resolve(name); name == "" { return os.ErrNotExist } return os.Mkdir(name, perm) } func (d Dir) OpenFile(name string, flag int, perm os.FileMode) (File, error) { if name = d.resolve(name); name == "" { return nil, os.ErrNotExist } f, err := os.OpenFile(name, flag, perm) if err != nil { return nil, err } return f, nil } func (d Dir) RemoveAll(name string) error { if name = d.resolve(name); name == "" { return os.ErrNotExist } if name == filepath.Clean(string(d)) { // Prohibit removing the virtual root directory. return os.ErrInvalid } return os.RemoveAll(name) } func (d Dir) Rename(oldName, newName string) error { if oldName = d.resolve(oldName); oldName == "" { return os.ErrNotExist } if newName = d.resolve(newName); newName == "" { return os.ErrNotExist } if root := filepath.Clean(string(d)); root == oldName || root == newName { // Prohibit renaming from or to the virtual root directory. return os.ErrInvalid } return os.Rename(oldName, newName) } func (d Dir) Stat(name string) (os.FileInfo, error) { if name = d.resolve(name); name == "" { return nil, os.ErrNotExist } return os.Stat(name) } // NewMemFS returns a new in-memory FileSystem implementation. func NewMemFS() FileSystem { return &memFS{ root: memFSNode{ children: make(map[string]*memFSNode), mode: 0660 | os.ModeDir, modTime: time.Now(), }, } } // A memFS implements FileSystem, storing all metadata and actual file data // in-memory. No limits on filesystem size are used, so it is not recommended // this be used where the clients are untrusted. // // Concurrent access is permitted. The tree structure is protected by a mutex, // and each node's contents and metadata are protected by a per-node mutex. // // TODO: Enforce file permissions. type memFS struct { mu sync.Mutex root memFSNode } // TODO: clean up and rationalize the walk/find code. // walk walks the directory tree for the fullname, calling f at each step. If f // returns an error, the walk will be aborted and return that same error. // // dir is the directory at that step, frag is the name fragment, and final is // whether it is the final step. For example, walking "/foo/bar/x" will result // in 3 calls to f: // - "/", "foo", false // - "/foo/", "bar", false // - "/foo/bar/", "x", true // The frag argument will be empty only if dir is the root node and the walk // ends at that root node. func (fs *memFS) walk(op, fullname string, f func(dir *memFSNode, frag string, final bool) error) error { original := fullname fullname = slashClean(fullname) // Strip any leading "/"s to make fullname a relative path, as the walk // starts at fs.root. if fullname[0] == '/' { fullname = fullname[1:] } dir := &fs.root for { frag, remaining := fullname, "" i := strings.IndexRune(fullname, '/') final := i < 0 if !final { frag, remaining = fullname[:i], fullname[i+1:] } if frag == "" && dir != &fs.root { panic("webdav: empty path fragment for a clean path") } if err := f(dir, frag, final); err != nil { return &os.PathError{ Op: op, Path: original, Err: err, } } if final { break } child := dir.children[frag] if child == nil { return &os.PathError{ Op: op, Path: original, Err: os.ErrNotExist, } } if !child.mode.IsDir() { return &os.PathError{ Op: op, Path: original, Err: os.ErrInvalid, } } dir, fullname = child, remaining } return nil } // find returns the parent of the named node and the relative name fragment // from the parent to the child. For example, if finding "/foo/bar/baz" then // parent will be the node for "/foo/bar" and frag will be "baz". // // If the fullname names the root node, then parent, frag and err will be zero. // // find returns an error if the parent does not already exist or the parent // isn't a directory, but it will not return an error per se if the child does // not already exist. The error returned is either nil or an *os.PathError // whose Op is op. func (fs *memFS) find(op, fullname string) (parent *memFSNode, frag string, err error) { err = fs.walk(op, fullname, func(parent0 *memFSNode, frag0 string, final bool) error { if !final { return nil } if frag0 != "" { parent, frag = parent0, frag0 } return nil }) return parent, frag, err } func (fs *memFS) Mkdir(name string, perm os.FileMode) error { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("mkdir", name) if err != nil { return err } if dir == nil { // We can't create the root. return os.ErrInvalid } if _, ok := dir.children[frag]; ok { return os.ErrExist } dir.children[frag] = &memFSNode{ children: make(map[string]*memFSNode), mode: perm.Perm() | os.ModeDir, modTime: time.Now(), } return nil } func (fs *memFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("open", name) if err != nil { return nil, err } var n *memFSNode if dir == nil { // We're opening the root. if flag&(os.O_WRONLY|os.O_RDWR) != 0 { return nil, os.ErrPermission } n, frag = &fs.root, "/" } else { n = dir.children[frag] if flag&(os.O_SYNC|os.O_APPEND) != 0 { // memFile doesn't support these flags yet. return nil, os.ErrInvalid } if flag&os.O_CREATE != 0 { if flag&os.O_EXCL != 0 && n != nil { return nil, os.ErrExist } if n == nil { n = &memFSNode{ mode: perm.Perm(), } dir.children[frag] = n } } if n == nil { return nil, os.ErrNotExist } if flag&(os.O_WRONLY|os.O_RDWR) != 0 && flag&os.O_TRUNC != 0 { n.mu.Lock() n.data = nil n.mu.Unlock() } } children := make([]os.FileInfo, 0, len(n.children)) for cName, c := range n.children { children = append(children, c.stat(cName)) } return &memFile{ n: n, nameSnapshot: frag, childrenSnapshot: children, }, nil } func (fs *memFS) RemoveAll(name string) error { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("remove", name) if err != nil { return err } if dir == nil { // We can't remove the root. return os.ErrInvalid } delete(dir.children, frag) return nil } func (fs *memFS) Rename(oldName, newName string) error { fs.mu.Lock() defer fs.mu.Unlock() oldName = slashClean(oldName) newName = slashClean(newName) if oldName == newName { return nil } if strings.HasPrefix(newName, oldName+"/") { // We can't rename oldName to be a sub-directory of itself. return os.ErrInvalid } oDir, oFrag, err := fs.find("rename", oldName) if err != nil { return err } if oDir == nil { // We can't rename from the root. return os.ErrInvalid } nDir, nFrag, err := fs.find("rename", newName) if err != nil { return err } if nDir == nil { // We can't rename to the root. return os.ErrInvalid } oNode, ok := oDir.children[oFrag] if !ok { return os.ErrNotExist } if oNode.children != nil { if nNode, ok := nDir.children[nFrag]; ok { if nNode.children == nil { return errNotADirectory } if len(nNode.children) != 0 { return errDirectoryNotEmpty } } } delete(oDir.children, oFrag) nDir.children[nFrag] = oNode return nil } func (fs *memFS) Stat(name string) (os.FileInfo, error) { fs.mu.Lock() defer fs.mu.Unlock() dir, frag, err := fs.find("stat", name) if err != nil { return nil, err } if dir == nil { // We're stat'ting the root. return fs.root.stat("/"), nil } if n, ok := dir.children[frag]; ok { return n.stat(path.Base(name)), nil } return nil, os.ErrNotExist } // A memFSNode represents a single entry in the in-memory filesystem and also // implements os.FileInfo. type memFSNode struct { // children is protected by memFS.mu. children map[string]*memFSNode mu sync.Mutex data []byte mode os.FileMode modTime time.Time deadProps map[xml.Name]Property } func (n *memFSNode) stat(name string) *memFileInfo { n.mu.Lock() defer n.mu.Unlock() return &memFileInfo{ name: name, size: int64(len(n.data)), mode: n.mode, modTime: n.modTime, } } func (n *memFSNode) DeadProps() (map[xml.Name]Property, error) { n.mu.Lock() defer n.mu.Unlock() if len(n.deadProps) == 0 { return nil, nil } ret := make(map[xml.Name]Property, len(n.deadProps)) for k, v := range n.deadProps { ret[k] = v } return ret, nil } func (n *memFSNode) Patch(patches []Proppatch) ([]Propstat, error) { n.mu.Lock() defer n.mu.Unlock() pstat := Propstat{Status: http.StatusOK} for _, patch := range patches { for _, p := range patch.Props { pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName}) if patch.Remove { delete(n.deadProps, p.XMLName) continue } if n.deadProps == nil { n.deadProps = map[xml.Name]Property{} } n.deadProps[p.XMLName] = p } } return []Propstat{pstat}, nil } type memFileInfo struct { name string size int64 mode os.FileMode modTime time.Time } func (f *memFileInfo) Name() string { return f.name } func (f *memFileInfo) Size() int64 { return f.size } func (f *memFileInfo) Mode() os.FileMode { return f.mode } func (f *memFileInfo) ModTime() time.Time { return f.modTime } func (f *memFileInfo) IsDir() bool { return f.mode.IsDir() } func (f *memFileInfo) Sys() interface{} { return nil } // A memFile is a File implementation for a memFSNode. It is a per-file (not // per-node) read/write position, and a snapshot of the memFS' tree structure // (a node's name and children) for that node. type memFile struct { n *memFSNode nameSnapshot string childrenSnapshot []os.FileInfo // pos is protected by n.mu. pos int } // A *memFile implements the optional DeadPropsHolder interface. var _ DeadPropsHolder = (*memFile)(nil) func (f *memFile) DeadProps() (map[xml.Name]Property, error) { return f.n.DeadProps() } func (f *memFile) Patch(patches []Proppatch) ([]Propstat, error) { return f.n.Patch(patches) } func (f *memFile) Close() error { return nil } func (f *memFile) Read(p []byte) (int, error) { f.n.mu.Lock() defer f.n.mu.Unlock() if f.n.mode.IsDir() { return 0, os.ErrInvalid } if f.pos >= len(f.n.data) { return 0, io.EOF } n := copy(p, f.n.data[f.pos:]) f.pos += n return n, nil } func (f *memFile) Readdir(count int) ([]os.FileInfo, error) { f.n.mu.Lock() defer f.n.mu.Unlock() if !f.n.mode.IsDir() { return nil, os.ErrInvalid } old := f.pos if old >= len(f.childrenSnapshot) { // The os.File Readdir docs say that at the end of a directory, // the error is io.EOF if count > 0 and nil if count <= 0. if count > 0 { return nil, io.EOF } return nil, nil } if count > 0 { f.pos += count if f.pos > len(f.childrenSnapshot) { f.pos = len(f.childrenSnapshot) } } else { f.pos = len(f.childrenSnapshot) old = 0 } return f.childrenSnapshot[old:f.pos], nil } func (f *memFile) Seek(offset int64, whence int) (int64, error) { f.n.mu.Lock() defer f.n.mu.Unlock() npos := f.pos // TODO: How to handle offsets greater than the size of system int? switch whence { case os.SEEK_SET: npos = int(offset) case os.SEEK_CUR: npos += int(offset) case os.SEEK_END: npos = len(f.n.data) + int(offset) default: npos = -1 } if npos < 0 { return 0, os.ErrInvalid } f.pos = npos return int64(f.pos), nil } func (f *memFile) Stat() (os.FileInfo, error) { return f.n.stat(f.nameSnapshot), nil } func (f *memFile) Write(p []byte) (int, error) { lenp := len(p) f.n.mu.Lock() defer f.n.mu.Unlock() if f.n.mode.IsDir() { return 0, os.ErrInvalid } if f.pos < len(f.n.data) { n := copy(f.n.data[f.pos:], p) f.pos += n p = p[n:] } else if f.pos > len(f.n.data) { // Write permits the creation of holes, if we've seek'ed past the // existing end of file. if f.pos <= cap(f.n.data) { oldLen := len(f.n.data) f.n.data = f.n.data[:f.pos] hole := f.n.data[oldLen:] for i := range hole { hole[i] = 0 } } else { d := make([]byte, f.pos, f.pos+len(p)) copy(d, f.n.data) f.n.data = d } } if len(p) > 0 { // We should only get here if f.pos == len(f.n.data). f.n.data = append(f.n.data, p...) f.pos = len(f.n.data) } f.n.modTime = time.Now() return lenp, nil } // moveFiles moves files and/or directories from src to dst. // // See section 9.9.4 for when various HTTP status codes apply. func moveFiles(fs FileSystem, src, dst string, overwrite bool) (status int, err error) { created := false if _, err := fs.Stat(dst); err != nil { if !os.IsNotExist(err) { return http.StatusForbidden, err } created = true } else if overwrite { // Section 9.9.3 says that "If a resource exists at the destination // and the Overwrite header is "T", then prior to performing the move, // the server must perform a DELETE with "Depth: infinity" on the // destination resource. if err := fs.RemoveAll(dst); err != nil { return http.StatusForbidden, err } } else { return http.StatusPreconditionFailed, os.ErrExist } if err := fs.Rename(src, dst); err != nil { return http.StatusForbidden, err } if created { return http.StatusCreated, nil } return http.StatusNoContent, nil } func copyProps(dst, src File) error { d, ok := dst.(DeadPropsHolder) if !ok { return nil } s, ok := src.(DeadPropsHolder) if !ok { return nil } m, err := s.DeadProps() if err != nil { return err } props := make([]Property, 0, len(m)) for _, prop := range m { props = append(props, prop) } _, err = d.Patch([]Proppatch{{Props: props}}) return err } // copyFiles copies files and/or directories from src to dst. // // See section 9.8.5 for when various HTTP status codes apply. func copyFiles(fs FileSystem, src, dst string, overwrite bool, depth int, recursion int) (status int, err error) { if recursion == 1000 { return http.StatusInternalServerError, errRecursionTooDeep } recursion++ // TODO: section 9.8.3 says that "Note that an infinite-depth COPY of /A/ // into /A/B/ could lead to infinite recursion if not handled correctly." srcFile, err := fs.OpenFile(src, os.O_RDONLY, 0) if err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusInternalServerError, err } defer srcFile.Close() srcStat, err := srcFile.Stat() if err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusInternalServerError, err } srcPerm := srcStat.Mode() & os.ModePerm created := false if _, err := fs.Stat(dst); err != nil { if os.IsNotExist(err) { created = true } else { return http.StatusForbidden, err } } else { if !overwrite { return http.StatusPreconditionFailed, os.ErrExist } if err := fs.RemoveAll(dst); err != nil && !os.IsNotExist(err) { return http.StatusForbidden, err } } if srcStat.IsDir() { if err := fs.Mkdir(dst, srcPerm); err != nil { return http.StatusForbidden, err } if depth == infiniteDepth { children, err := srcFile.Readdir(-1) if err != nil { return http.StatusForbidden, err } for _, c := range children { name := c.Name() s := path.Join(src, name) d := path.Join(dst, name) cStatus, cErr := copyFiles(fs, s, d, overwrite, depth, recursion) if cErr != nil { // TODO: MultiStatus. return cStatus, cErr } } } } else { dstFile, err := fs.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, srcPerm) if err != nil { if os.IsNotExist(err) { return http.StatusConflict, err } return http.StatusForbidden, err } _, copyErr := io.Copy(dstFile, srcFile) propsErr := copyProps(dstFile, srcFile) closeErr := dstFile.Close() if copyErr != nil { return http.StatusInternalServerError, copyErr } if propsErr != nil { return http.StatusInternalServerError, propsErr } if closeErr != nil { return http.StatusInternalServerError, closeErr } } if created { return http.StatusCreated, nil } return http.StatusNoContent, nil } // walkFS traverses filesystem fs starting at name up to depth levels. // // Allowed values for depth are 0, 1 or infiniteDepth. For each visited node, // walkFS calls walkFn. If a visited file system node is a directory and // walkFn returns filepath.SkipDir, walkFS will skip traversal of this node. func walkFS(fs FileSystem, depth int, name string, info os.FileInfo, walkFn filepath.WalkFunc) error { // This implementation is based on Walk's code in the standard path/filepath package. err := walkFn(name, info, nil) if err != nil { if info.IsDir() && err == filepath.SkipDir { return nil } return err } if !info.IsDir() || depth == 0 { return nil } if depth == 1 { depth = 0 } // Read directory names. f, err := fs.OpenFile(name, os.O_RDONLY, 0) if err != nil { return walkFn(name, info, err) } fileInfos, err := f.Readdir(0) f.Close() if err != nil { return walkFn(name, info, err) } for _, fileInfo := range fileInfos { filename := path.Join(name, fileInfo.Name()) fileInfo, err := fs.Stat(filename) if err != nil { if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir { return err } } else { err = walkFS(fs, depth, filename, fileInfo, walkFn) if err != nil { if !fileInfo.IsDir() || err != filepath.SkipDir { return err } } } } return nil } ================================================ FILE: vendor/golang.org/x/net/webdav/file_test.go ================================================ // 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 webdav import ( "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "reflect" "runtime" "sort" "strconv" "strings" "testing" "golang.org/x/net/webdav/internal/xml" ) func TestSlashClean(t *testing.T) { testCases := []string{ "", ".", "/", "/./", "//", "//.", "//a", "/a", "/a/b/c", "/a//b/./../c/d/", "a", "a/b/c", } for _, tc := range testCases { got := slashClean(tc) want := path.Clean("/" + tc) if got != want { t.Errorf("tc=%q: got %q, want %q", tc, got, want) } } } func TestDirResolve(t *testing.T) { testCases := []struct { dir, name, want string }{ {"/", "", "/"}, {"/", "/", "/"}, {"/", ".", "/"}, {"/", "./a", "/a"}, {"/", "..", "/"}, {"/", "..", "/"}, {"/", "../", "/"}, {"/", "../.", "/"}, {"/", "../a", "/a"}, {"/", "../..", "/"}, {"/", "../bar/a", "/bar/a"}, {"/", "../baz/a", "/baz/a"}, {"/", "...", "/..."}, {"/", ".../a", "/.../a"}, {"/", ".../..", "/"}, {"/", "a", "/a"}, {"/", "a/./b", "/a/b"}, {"/", "a/../../b", "/b"}, {"/", "a/../b", "/b"}, {"/", "a/b", "/a/b"}, {"/", "a/b/c/../../d", "/a/d"}, {"/", "a/b/c/../../../d", "/d"}, {"/", "a/b/c/../../../../d", "/d"}, {"/", "a/b/c/d", "/a/b/c/d"}, {"/foo/bar", "", "/foo/bar"}, {"/foo/bar", "/", "/foo/bar"}, {"/foo/bar", ".", "/foo/bar"}, {"/foo/bar", "./a", "/foo/bar/a"}, {"/foo/bar", "..", "/foo/bar"}, {"/foo/bar", "../", "/foo/bar"}, {"/foo/bar", "../.", "/foo/bar"}, {"/foo/bar", "../a", "/foo/bar/a"}, {"/foo/bar", "../..", "/foo/bar"}, {"/foo/bar", "../bar/a", "/foo/bar/bar/a"}, {"/foo/bar", "../baz/a", "/foo/bar/baz/a"}, {"/foo/bar", "...", "/foo/bar/..."}, {"/foo/bar", ".../a", "/foo/bar/.../a"}, {"/foo/bar", ".../..", "/foo/bar"}, {"/foo/bar", "a", "/foo/bar/a"}, {"/foo/bar", "a/./b", "/foo/bar/a/b"}, {"/foo/bar", "a/../../b", "/foo/bar/b"}, {"/foo/bar", "a/../b", "/foo/bar/b"}, {"/foo/bar", "a/b", "/foo/bar/a/b"}, {"/foo/bar", "a/b/c/../../d", "/foo/bar/a/d"}, {"/foo/bar", "a/b/c/../../../d", "/foo/bar/d"}, {"/foo/bar", "a/b/c/../../../../d", "/foo/bar/d"}, {"/foo/bar", "a/b/c/d", "/foo/bar/a/b/c/d"}, {"/foo/bar/", "", "/foo/bar"}, {"/foo/bar/", "/", "/foo/bar"}, {"/foo/bar/", ".", "/foo/bar"}, {"/foo/bar/", "./a", "/foo/bar/a"}, {"/foo/bar/", "..", "/foo/bar"}, {"/foo//bar///", "", "/foo/bar"}, {"/foo//bar///", "/", "/foo/bar"}, {"/foo//bar///", ".", "/foo/bar"}, {"/foo//bar///", "./a", "/foo/bar/a"}, {"/foo//bar///", "..", "/foo/bar"}, {"/x/y/z", "ab/c\x00d/ef", ""}, {".", "", "."}, {".", "/", "."}, {".", ".", "."}, {".", "./a", "a"}, {".", "..", "."}, {".", "..", "."}, {".", "../", "."}, {".", "../.", "."}, {".", "../a", "a"}, {".", "../..", "."}, {".", "../bar/a", "bar/a"}, {".", "../baz/a", "baz/a"}, {".", "...", "..."}, {".", ".../a", ".../a"}, {".", ".../..", "."}, {".", "a", "a"}, {".", "a/./b", "a/b"}, {".", "a/../../b", "b"}, {".", "a/../b", "b"}, {".", "a/b", "a/b"}, {".", "a/b/c/../../d", "a/d"}, {".", "a/b/c/../../../d", "d"}, {".", "a/b/c/../../../../d", "d"}, {".", "a/b/c/d", "a/b/c/d"}, {"", "", "."}, {"", "/", "."}, {"", ".", "."}, {"", "./a", "a"}, {"", "..", "."}, } for _, tc := range testCases { d := Dir(filepath.FromSlash(tc.dir)) if got := filepath.ToSlash(d.resolve(tc.name)); got != tc.want { t.Errorf("dir=%q, name=%q: got %q, want %q", tc.dir, tc.name, got, tc.want) } } } func TestWalk(t *testing.T) { type walkStep struct { name, frag string final bool } testCases := []struct { dir string want []walkStep }{ {"", []walkStep{ {"", "", true}, }}, {"/", []walkStep{ {"", "", true}, }}, {"/a", []walkStep{ {"", "a", true}, }}, {"/a/", []walkStep{ {"", "a", true}, }}, {"/a/b", []walkStep{ {"", "a", false}, {"a", "b", true}, }}, {"/a/b/", []walkStep{ {"", "a", false}, {"a", "b", true}, }}, {"/a/b/c", []walkStep{ {"", "a", false}, {"a", "b", false}, {"b", "c", true}, }}, // The following test case is the one mentioned explicitly // in the method description. {"/foo/bar/x", []walkStep{ {"", "foo", false}, {"foo", "bar", false}, {"bar", "x", true}, }}, } for _, tc := range testCases { fs := NewMemFS().(*memFS) parts := strings.Split(tc.dir, "/") for p := 2; p < len(parts); p++ { d := strings.Join(parts[:p], "/") if err := fs.Mkdir(d, 0666); err != nil { t.Errorf("tc.dir=%q: mkdir: %q: %v", tc.dir, d, err) } } i, prevFrag := 0, "" err := fs.walk("test", tc.dir, func(dir *memFSNode, frag string, final bool) error { got := walkStep{ name: prevFrag, frag: frag, final: final, } want := tc.want[i] if got != want { return fmt.Errorf("got %+v, want %+v", got, want) } i, prevFrag = i+1, frag return nil }) if err != nil { t.Errorf("tc.dir=%q: %v", tc.dir, err) } } } // find appends to ss the names of the named file and its children. It is // analogous to the Unix find command. // // The returned strings are not guaranteed to be in any particular order. func find(ss []string, fs FileSystem, name string) ([]string, error) { stat, err := fs.Stat(name) if err != nil { return nil, err } ss = append(ss, name) if stat.IsDir() { f, err := fs.OpenFile(name, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() children, err := f.Readdir(-1) if err != nil { return nil, err } for _, c := range children { ss, err = find(ss, fs, path.Join(name, c.Name())) if err != nil { return nil, err } } } return ss, nil } func testFS(t *testing.T, fs FileSystem) { errStr := func(err error) string { switch { case os.IsExist(err): return "errExist" case os.IsNotExist(err): return "errNotExist" case err != nil: return "err" } return "ok" } // The non-"find" non-"stat" test cases should change the file system state. The // indentation of the "find"s and "stat"s helps distinguish such test cases. testCases := []string{ " stat / want dir", " stat /a want errNotExist", " stat /d want errNotExist", " stat /d/e want errNotExist", "create /a A want ok", " stat /a want 1", "create /d/e EEE want errNotExist", "mk-dir /a want errExist", "mk-dir /d/m want errNotExist", "mk-dir /d want ok", " stat /d want dir", "create /d/e EEE want ok", " stat /d/e want 3", " find / /a /d /d/e", "create /d/f FFFF want ok", "create /d/g GGGGGGG want ok", "mk-dir /d/m want ok", "mk-dir /d/m want errExist", "create /d/m/p PPPPP want ok", " stat /d/e want 3", " stat /d/f want 4", " stat /d/g want 7", " stat /d/h want errNotExist", " stat /d/m want dir", " stat /d/m/p want 5", " find / /a /d /d/e /d/f /d/g /d/m /d/m/p", "rm-all /d want ok", " stat /a want 1", " stat /d want errNotExist", " stat /d/e want errNotExist", " stat /d/f want errNotExist", " stat /d/g want errNotExist", " stat /d/m want errNotExist", " stat /d/m/p want errNotExist", " find / /a", "mk-dir /d/m want errNotExist", "mk-dir /d want ok", "create /d/f FFFF want ok", "rm-all /d/f want ok", "mk-dir /d/m want ok", "rm-all /z want ok", "rm-all / want err", "create /b BB want ok", " stat / want dir", " stat /a want 1", " stat /b want 2", " stat /c want errNotExist", " stat /d want dir", " stat /d/m want dir", " find / /a /b /d /d/m", "move__ o=F /b /c want ok", " stat /b want errNotExist", " stat /c want 2", " stat /d/m want dir", " stat /d/n want errNotExist", " find / /a /c /d /d/m", "move__ o=F /d/m /d/n want ok", "create /d/n/q QQQQ want ok", " stat /d/m want errNotExist", " stat /d/n want dir", " stat /d/n/q want 4", "move__ o=F /d /d/n/z want err", "move__ o=T /c /d/n/q want ok", " stat /c want errNotExist", " stat /d/n/q want 2", " find / /a /d /d/n /d/n/q", "create /d/n/r RRRRR want ok", "mk-dir /u want ok", "mk-dir /u/v want ok", "move__ o=F /d/n /u want errExist", "create /t TTTTTT want ok", "move__ o=F /d/n /t want errExist", "rm-all /t want ok", "move__ o=F /d/n /t want ok", " stat /d want dir", " stat /d/n want errNotExist", " stat /d/n/r want errNotExist", " stat /t want dir", " stat /t/q want 2", " stat /t/r want 5", " find / /a /d /t /t/q /t/r /u /u/v", "move__ o=F /t / want errExist", "move__ o=T /t /u/v want ok", " stat /u/v/r want 5", "move__ o=F / /z want err", " find / /a /d /u /u/v /u/v/q /u/v/r", " stat /a want 1", " stat /b want errNotExist", " stat /c want errNotExist", " stat /u/v/r want 5", "copy__ o=F d=0 /a /b want ok", "copy__ o=T d=0 /a /c want ok", " stat /a want 1", " stat /b want 1", " stat /c want 1", " stat /u/v/r want 5", "copy__ o=F d=0 /u/v/r /b want errExist", " stat /b want 1", "copy__ o=T d=0 /u/v/r /b want ok", " stat /a want 1", " stat /b want 5", " stat /u/v/r want 5", "rm-all /a want ok", "rm-all /b want ok", "mk-dir /u/v/w want ok", "create /u/v/w/s SSSSSSSS want ok", " stat /d want dir", " stat /d/x want errNotExist", " stat /d/y want errNotExist", " stat /u/v/r want 5", " stat /u/v/w/s want 8", " find / /c /d /u /u/v /u/v/q /u/v/r /u/v/w /u/v/w/s", "copy__ o=T d=0 /u/v /d/x want ok", "copy__ o=T d=∞ /u/v /d/y want ok", "rm-all /u want ok", " stat /d/x want dir", " stat /d/x/q want errNotExist", " stat /d/x/r want errNotExist", " stat /d/x/w want errNotExist", " stat /d/x/w/s want errNotExist", " stat /d/y want dir", " stat /d/y/q want 2", " stat /d/y/r want 5", " stat /d/y/w want dir", " stat /d/y/w/s want 8", " stat /u want errNotExist", " find / /c /d /d/x /d/y /d/y/q /d/y/r /d/y/w /d/y/w/s", "copy__ o=F d=∞ /d/y /d/x want errExist", } for i, tc := range testCases { tc = strings.TrimSpace(tc) j := strings.IndexByte(tc, ' ') if j < 0 { t.Fatalf("test case #%d %q: invalid command", i, tc) } op, arg := tc[:j], tc[j+1:] switch op { default: t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) case "create": parts := strings.Split(arg, " ") if len(parts) != 4 || parts[2] != "want" { t.Fatalf("test case #%d %q: invalid write", i, tc) } f, opErr := fs.OpenFile(parts[0], os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if got := errStr(opErr); got != parts[3] { t.Fatalf("test case #%d %q: OpenFile: got %q (%v), want %q", i, tc, got, opErr, parts[3]) } if f != nil { if _, err := f.Write([]byte(parts[1])); err != nil { t.Fatalf("test case #%d %q: Write: %v", i, tc, err) } if err := f.Close(); err != nil { t.Fatalf("test case #%d %q: Close: %v", i, tc, err) } } case "find": got, err := find(nil, fs, "/") if err != nil { t.Fatalf("test case #%d %q: find: %v", i, tc, err) } sort.Strings(got) want := strings.Split(arg, " ") if !reflect.DeepEqual(got, want) { t.Fatalf("test case #%d %q:\ngot %s\nwant %s", i, tc, got, want) } case "copy__", "mk-dir", "move__", "rm-all", "stat": nParts := 3 switch op { case "copy__": nParts = 6 case "move__": nParts = 5 } parts := strings.Split(arg, " ") if len(parts) != nParts { t.Fatalf("test case #%d %q: invalid %s", i, tc, op) } got, opErr := "", error(nil) switch op { case "copy__": depth := 0 if parts[1] == "d=∞" { depth = infiniteDepth } _, opErr = copyFiles(fs, parts[2], parts[3], parts[0] == "o=T", depth, 0) case "mk-dir": opErr = fs.Mkdir(parts[0], 0777) case "move__": _, opErr = moveFiles(fs, parts[1], parts[2], parts[0] == "o=T") case "rm-all": opErr = fs.RemoveAll(parts[0]) case "stat": var stat os.FileInfo fileName := parts[0] if stat, opErr = fs.Stat(fileName); opErr == nil { if stat.IsDir() { got = "dir" } else { got = strconv.Itoa(int(stat.Size())) } if fileName == "/" { // For a Dir FileSystem, the virtual file system root maps to a // real file system name like "/tmp/webdav-test012345", which does // not end with "/". We skip such cases. } else if statName := stat.Name(); path.Base(fileName) != statName { t.Fatalf("test case #%d %q: file name %q inconsistent with stat name %q", i, tc, fileName, statName) } } } if got == "" { got = errStr(opErr) } if parts[len(parts)-2] != "want" { t.Fatalf("test case #%d %q: invalid %s", i, tc, op) } if want := parts[len(parts)-1]; got != want { t.Fatalf("test case #%d %q: got %q (%v), want %q", i, tc, got, opErr, want) } } } } func TestDir(t *testing.T) { switch runtime.GOOS { case "nacl": t.Skip("see golang.org/issue/12004") case "plan9": t.Skip("see golang.org/issue/11453") } td, err := ioutil.TempDir("", "webdav-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(td) testFS(t, Dir(td)) } func TestMemFS(t *testing.T) { testFS(t, NewMemFS()) } func TestMemFSRoot(t *testing.T) { fs := NewMemFS() for i := 0; i < 5; i++ { stat, err := fs.Stat("/") if err != nil { t.Fatalf("i=%d: Stat: %v", i, err) } if !stat.IsDir() { t.Fatalf("i=%d: Stat.IsDir is false, want true", i) } f, err := fs.OpenFile("/", os.O_RDONLY, 0) if err != nil { t.Fatalf("i=%d: OpenFile: %v", i, err) } defer f.Close() children, err := f.Readdir(-1) if err != nil { t.Fatalf("i=%d: Readdir: %v", i, err) } if len(children) != i { t.Fatalf("i=%d: got %d children, want %d", i, len(children), i) } if _, err := f.Write(make([]byte, 1)); err == nil { t.Fatalf("i=%d: Write: got nil error, want non-nil", i) } if err := fs.Mkdir(fmt.Sprintf("/dir%d", i), 0777); err != nil { t.Fatalf("i=%d: Mkdir: %v", i, err) } } } func TestMemFileReaddir(t *testing.T) { fs := NewMemFS() if err := fs.Mkdir("/foo", 0777); err != nil { t.Fatalf("Mkdir: %v", err) } readdir := func(count int) ([]os.FileInfo, error) { f, err := fs.OpenFile("/foo", os.O_RDONLY, 0) if err != nil { t.Fatalf("OpenFile: %v", err) } defer f.Close() return f.Readdir(count) } if got, err := readdir(-1); len(got) != 0 || err != nil { t.Fatalf("readdir(-1): got %d fileInfos with err=%v, want 0, ", len(got), err) } if got, err := readdir(+1); len(got) != 0 || err != io.EOF { t.Fatalf("readdir(+1): got %d fileInfos with err=%v, want 0, EOF", len(got), err) } } func TestMemFile(t *testing.T) { testCases := []string{ "wantData ", "wantSize 0", "write abc", "wantData abc", "write de", "wantData abcde", "wantSize 5", "write 5*x", "write 4*y+2*z", "write 3*st", "wantData abcdexxxxxyyyyzzststst", "wantSize 22", "seek set 4 want 4", "write EFG", "wantData abcdEFGxxxyyyyzzststst", "wantSize 22", "seek set 2 want 2", "read cdEF", "read Gx", "seek cur 0 want 8", "seek cur 2 want 10", "seek cur -1 want 9", "write J", "wantData abcdEFGxxJyyyyzzststst", "wantSize 22", "seek cur -4 want 6", "write ghijk", "wantData abcdEFghijkyyyzzststst", "wantSize 22", "read yyyz", "seek cur 0 want 15", "write ", "seek cur 0 want 15", "read ", "seek cur 0 want 15", "seek end -3 want 19", "write ZZ", "wantData abcdEFghijkyyyzzstsZZt", "wantSize 22", "write 4*A", "wantData abcdEFghijkyyyzzstsZZAAAA", "wantSize 25", "seek end 0 want 25", "seek end -5 want 20", "read Z+4*A", "write 5*B", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB", "wantSize 30", "seek end 10 want 40", "write C", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........C", "wantSize 41", "write D", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........CD", "wantSize 42", "seek set 43 want 43", "write E", "wantData abcdEFghijkyyyzzstsZZAAAABBBBB..........CD.E", "wantSize 44", "seek set 0 want 0", "write 5*123456789_", "wantData 123456789_123456789_123456789_123456789_123456789_", "wantSize 50", "seek cur 0 want 50", "seek cur -99 want err", } const filename = "/foo" fs := NewMemFS() f, err := fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { t.Fatalf("OpenFile: %v", err) } defer f.Close() for i, tc := range testCases { j := strings.IndexByte(tc, ' ') if j < 0 { t.Fatalf("test case #%d %q: invalid command", i, tc) } op, arg := tc[:j], tc[j+1:] // Expand an arg like "3*a+2*b" to "aaabb". parts := strings.Split(arg, "+") for j, part := range parts { if k := strings.IndexByte(part, '*'); k >= 0 { repeatCount, repeatStr := part[:k], part[k+1:] n, err := strconv.Atoi(repeatCount) if err != nil { t.Fatalf("test case #%d %q: invalid repeat count %q", i, tc, repeatCount) } parts[j] = strings.Repeat(repeatStr, n) } } arg = strings.Join(parts, "") switch op { default: t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) case "read": buf := make([]byte, len(arg)) if _, err := io.ReadFull(f, buf); err != nil { t.Fatalf("test case #%d %q: ReadFull: %v", i, tc, err) } if got := string(buf); got != arg { t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, arg) } case "seek": parts := strings.Split(arg, " ") if len(parts) != 4 { t.Fatalf("test case #%d %q: invalid seek", i, tc) } whence := 0 switch parts[0] { default: t.Fatalf("test case #%d %q: invalid seek whence", i, tc) case "set": whence = os.SEEK_SET case "cur": whence = os.SEEK_CUR case "end": whence = os.SEEK_END } offset, err := strconv.Atoi(parts[1]) if err != nil { t.Fatalf("test case #%d %q: invalid offset %q", i, tc, parts[1]) } if parts[2] != "want" { t.Fatalf("test case #%d %q: invalid seek", i, tc) } if parts[3] == "err" { _, err := f.Seek(int64(offset), whence) if err == nil { t.Fatalf("test case #%d %q: Seek returned nil error, want non-nil", i, tc) } } else { got, err := f.Seek(int64(offset), whence) if err != nil { t.Fatalf("test case #%d %q: Seek: %v", i, tc, err) } want, err := strconv.Atoi(parts[3]) if err != nil { t.Fatalf("test case #%d %q: invalid want %q", i, tc, parts[3]) } if got != int64(want) { t.Fatalf("test case #%d %q: got %d, want %d", i, tc, got, want) } } case "write": n, err := f.Write([]byte(arg)) if err != nil { t.Fatalf("test case #%d %q: write: %v", i, tc, err) } if n != len(arg) { t.Fatalf("test case #%d %q: write returned %d bytes, want %d", i, tc, n, len(arg)) } case "wantData": g, err := fs.OpenFile(filename, os.O_RDONLY, 0666) if err != nil { t.Fatalf("test case #%d %q: OpenFile: %v", i, tc, err) } gotBytes, err := ioutil.ReadAll(g) if err != nil { t.Fatalf("test case #%d %q: ReadAll: %v", i, tc, err) } for i, c := range gotBytes { if c == '\x00' { gotBytes[i] = '.' } } got := string(gotBytes) if got != arg { t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, arg) } if err := g.Close(); err != nil { t.Fatalf("test case #%d %q: Close: %v", i, tc, err) } case "wantSize": n, err := strconv.Atoi(arg) if err != nil { t.Fatalf("test case #%d %q: invalid size %q", i, tc, arg) } fi, err := fs.Stat(filename) if err != nil { t.Fatalf("test case #%d %q: Stat: %v", i, tc, err) } if got, want := fi.Size(), int64(n); got != want { t.Fatalf("test case #%d %q: got %d, want %d", i, tc, got, want) } } } } // TestMemFileWriteAllocs tests that writing N consecutive 1KiB chunks to a // memFile doesn't allocate a new buffer for each of those N times. Otherwise, // calling io.Copy(aMemFile, src) is likely to have quadratic complexity. func TestMemFileWriteAllocs(t *testing.T) { fs := NewMemFS() f, err := fs.OpenFile("/xxx", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { t.Fatalf("OpenFile: %v", err) } defer f.Close() xxx := make([]byte, 1024) for i := range xxx { xxx[i] = 'x' } a := testing.AllocsPerRun(100, func() { f.Write(xxx) }) // AllocsPerRun returns an integral value, so we compare the rounded-down // number to zero. if a > 0 { t.Fatalf("%v allocs per run, want 0", a) } } func BenchmarkMemFileWrite(b *testing.B) { fs := NewMemFS() xxx := make([]byte, 1024) for i := range xxx { xxx[i] = 'x' } b.ResetTimer() for i := 0; i < b.N; i++ { f, err := fs.OpenFile("/xxx", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { b.Fatalf("OpenFile: %v", err) } for j := 0; j < 100; j++ { f.Write(xxx) } if err := f.Close(); err != nil { b.Fatalf("Close: %v", err) } if err := fs.RemoveAll("/xxx"); err != nil { b.Fatalf("RemoveAll: %v", err) } } } func TestCopyMoveProps(t *testing.T) { fs := NewMemFS() create := func(name string) error { f, err := fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return err } _, wErr := f.Write([]byte("contents")) cErr := f.Close() if wErr != nil { return wErr } return cErr } patch := func(name string, patches ...Proppatch) error { f, err := fs.OpenFile(name, os.O_RDWR, 0666) if err != nil { return err } _, pErr := f.(DeadPropsHolder).Patch(patches) cErr := f.Close() if pErr != nil { return pErr } return cErr } props := func(name string) (map[xml.Name]Property, error) { f, err := fs.OpenFile(name, os.O_RDWR, 0666) if err != nil { return nil, err } m, pErr := f.(DeadPropsHolder).DeadProps() cErr := f.Close() if pErr != nil { return nil, pErr } if cErr != nil { return nil, cErr } return m, nil } p0 := Property{ XMLName: xml.Name{Space: "x:", Local: "boat"}, InnerXML: []byte("pea-green"), } p1 := Property{ XMLName: xml.Name{Space: "x:", Local: "ring"}, InnerXML: []byte("1 shilling"), } p2 := Property{ XMLName: xml.Name{Space: "x:", Local: "spoon"}, InnerXML: []byte("runcible"), } p3 := Property{ XMLName: xml.Name{Space: "x:", Local: "moon"}, InnerXML: []byte("light"), } if err := create("/src"); err != nil { t.Fatalf("create /src: %v", err) } if err := patch("/src", Proppatch{Props: []Property{p0, p1}}); err != nil { t.Fatalf("patch /src +p0 +p1: %v", err) } if _, err := copyFiles(fs, "/src", "/tmp", true, infiniteDepth, 0); err != nil { t.Fatalf("copyFiles /src /tmp: %v", err) } if _, err := moveFiles(fs, "/tmp", "/dst", true); err != nil { t.Fatalf("moveFiles /tmp /dst: %v", err) } if err := patch("/src", Proppatch{Props: []Property{p0}, Remove: true}); err != nil { t.Fatalf("patch /src -p0: %v", err) } if err := patch("/src", Proppatch{Props: []Property{p2}}); err != nil { t.Fatalf("patch /src +p2: %v", err) } if err := patch("/dst", Proppatch{Props: []Property{p1}, Remove: true}); err != nil { t.Fatalf("patch /dst -p1: %v", err) } if err := patch("/dst", Proppatch{Props: []Property{p3}}); err != nil { t.Fatalf("patch /dst +p3: %v", err) } gotSrc, err := props("/src") if err != nil { t.Fatalf("props /src: %v", err) } wantSrc := map[xml.Name]Property{ p1.XMLName: p1, p2.XMLName: p2, } if !reflect.DeepEqual(gotSrc, wantSrc) { t.Fatalf("props /src:\ngot %v\nwant %v", gotSrc, wantSrc) } gotDst, err := props("/dst") if err != nil { t.Fatalf("props /dst: %v", err) } wantDst := map[xml.Name]Property{ p0.XMLName: p0, p3.XMLName: p3, } if !reflect.DeepEqual(gotDst, wantDst) { t.Fatalf("props /dst:\ngot %v\nwant %v", gotDst, wantDst) } } func TestWalkFS(t *testing.T) { testCases := []struct { desc string buildfs []string startAt string depth int walkFn filepath.WalkFunc want []string }{{ "just root", []string{}, "/", infiniteDepth, nil, []string{ "/", }, }, { "infinite walk from root", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/d", "mkdir /e", "touch /f", }, "/", infiniteDepth, nil, []string{ "/", "/a", "/a/b", "/a/b/c", "/a/d", "/e", "/f", }, }, { "infinite walk from subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/d", "mkdir /e", "touch /f", }, "/a", infiniteDepth, nil, []string{ "/a", "/a/b", "/a/b/c", "/a/d", }, }, { "depth 1 walk from root", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/d", "mkdir /e", "touch /f", }, "/", 1, nil, []string{ "/", "/a", "/e", "/f", }, }, { "depth 1 walk from subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/b/g", "mkdir /a/b/g/h", "touch /a/b/g/i", "touch /a/b/g/h/j", }, "/a/b", 1, nil, []string{ "/a/b", "/a/b/c", "/a/b/g", }, }, { "depth 0 walk from subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/b/g", "mkdir /a/b/g/h", "touch /a/b/g/i", "touch /a/b/g/h/j", }, "/a/b", 0, nil, []string{ "/a/b", }, }, { "infinite walk from file", []string{ "mkdir /a", "touch /a/b", "touch /a/c", }, "/a/b", 0, nil, []string{ "/a/b", }, }, { "infinite walk with skipped subdir", []string{ "mkdir /a", "mkdir /a/b", "touch /a/b/c", "mkdir /a/b/g", "mkdir /a/b/g/h", "touch /a/b/g/i", "touch /a/b/g/h/j", "touch /a/b/z", }, "/", infiniteDepth, func(path string, info os.FileInfo, err error) error { if path == "/a/b/g" { return filepath.SkipDir } return nil }, []string{ "/", "/a", "/a/b", "/a/b/c", "/a/b/z", }, }} for _, tc := range testCases { fs, err := buildTestFS(tc.buildfs) if err != nil { t.Fatalf("%s: cannot create test filesystem: %v", tc.desc, err) } var got []string traceFn := func(path string, info os.FileInfo, err error) error { if tc.walkFn != nil { err = tc.walkFn(path, info, err) if err != nil { return err } } got = append(got, path) return nil } fi, err := fs.Stat(tc.startAt) if err != nil { t.Fatalf("%s: cannot stat: %v", tc.desc, err) } err = walkFS(fs, tc.depth, tc.startAt, fi, traceFn) if err != nil { t.Errorf("%s:\ngot error %v, want nil", tc.desc, err) continue } sort.Strings(got) sort.Strings(tc.want) if !reflect.DeepEqual(got, tc.want) { t.Errorf("%s:\ngot %q\nwant %q", tc.desc, got, tc.want) continue } } } func buildTestFS(buildfs []string) (FileSystem, error) { // TODO: Could this be merged with the build logic in TestFS? fs := NewMemFS() for _, b := range buildfs { op := strings.Split(b, " ") switch op[0] { case "mkdir": err := fs.Mkdir(op[1], os.ModeDir|0777) if err != nil { return nil, err } case "touch": f, err := fs.OpenFile(op[1], os.O_RDWR|os.O_CREATE, 0666) if err != nil { return nil, err } f.Close() case "write": f, err := fs.OpenFile(op[1], os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return nil, err } _, err = f.Write([]byte(op[2])) f.Close() if err != nil { return nil, err } default: return nil, fmt.Errorf("unknown file operation %q", op[0]) } } return fs, nil } ================================================ FILE: vendor/golang.org/x/net/webdav/if.go ================================================ // 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 webdav // The If header is covered by Section 10.4. // http://www.webdav.org/specs/rfc4918.html#HEADER_If import ( "strings" ) // ifHeader is a disjunction (OR) of ifLists. type ifHeader struct { lists []ifList } // ifList is a conjunction (AND) of Conditions, and an optional resource tag. type ifList struct { resourceTag string conditions []Condition } // parseIfHeader parses the "If: foo bar" HTTP header. The httpHeader string // should omit the "If:" prefix and have any "\r\n"s collapsed to a " ", as is // returned by req.Header.Get("If") for a http.Request req. func parseIfHeader(httpHeader string) (h ifHeader, ok bool) { s := strings.TrimSpace(httpHeader) switch tokenType, _, _ := lex(s); tokenType { case '(': return parseNoTagLists(s) case angleTokenType: return parseTaggedLists(s) default: return ifHeader{}, false } } func parseNoTagLists(s string) (h ifHeader, ok bool) { for { l, remaining, ok := parseList(s) if !ok { return ifHeader{}, false } h.lists = append(h.lists, l) if remaining == "" { return h, true } s = remaining } } func parseTaggedLists(s string) (h ifHeader, ok bool) { resourceTag, n := "", 0 for first := true; ; first = false { tokenType, tokenStr, remaining := lex(s) switch tokenType { case angleTokenType: if !first && n == 0 { return ifHeader{}, false } resourceTag, n = tokenStr, 0 s = remaining case '(': n++ l, remaining, ok := parseList(s) if !ok { return ifHeader{}, false } l.resourceTag = resourceTag h.lists = append(h.lists, l) if remaining == "" { return h, true } s = remaining default: return ifHeader{}, false } } } func parseList(s string) (l ifList, remaining string, ok bool) { tokenType, _, s := lex(s) if tokenType != '(' { return ifList{}, "", false } for { tokenType, _, remaining = lex(s) if tokenType == ')' { if len(l.conditions) == 0 { return ifList{}, "", false } return l, remaining, true } c, remaining, ok := parseCondition(s) if !ok { return ifList{}, "", false } l.conditions = append(l.conditions, c) s = remaining } } func parseCondition(s string) (c Condition, remaining string, ok bool) { tokenType, tokenStr, s := lex(s) if tokenType == notTokenType { c.Not = true tokenType, tokenStr, s = lex(s) } switch tokenType { case strTokenType, angleTokenType: c.Token = tokenStr case squareTokenType: c.ETag = tokenStr default: return Condition{}, "", false } return c, s, true } // Single-rune tokens like '(' or ')' have a token type equal to their rune. // All other tokens have a negative token type. const ( errTokenType = rune(-1) eofTokenType = rune(-2) strTokenType = rune(-3) notTokenType = rune(-4) angleTokenType = rune(-5) squareTokenType = rune(-6) ) func lex(s string) (tokenType rune, tokenStr string, remaining string) { // The net/textproto Reader that parses the HTTP header will collapse // Linear White Space that spans multiple "\r\n" lines to a single " ", // so we don't need to look for '\r' or '\n'. for len(s) > 0 && (s[0] == '\t' || s[0] == ' ') { s = s[1:] } if len(s) == 0 { return eofTokenType, "", "" } i := 0 loop: for ; i < len(s); i++ { switch s[i] { case '\t', ' ', '(', ')', '<', '>', '[', ']': break loop } } if i != 0 { tokenStr, remaining = s[:i], s[i:] if tokenStr == "Not" { return notTokenType, "", remaining } return strTokenType, tokenStr, remaining } j := 0 switch s[0] { case '<': j, tokenType = strings.IndexByte(s, '>'), angleTokenType case '[': j, tokenType = strings.IndexByte(s, ']'), squareTokenType default: return rune(s[0]), "", s[1:] } if j < 0 { return errTokenType, "", "" } return tokenType, s[1:j], s[j+1:] } ================================================ FILE: vendor/golang.org/x/net/webdav/if_test.go ================================================ // 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 webdav import ( "reflect" "strings" "testing" ) func TestParseIfHeader(t *testing.T) { // The "section x.y.z" test cases come from section x.y.z of the spec at // http://www.webdav.org/specs/rfc4918.html testCases := []struct { desc string input string want ifHeader }{{ "bad: empty", ``, ifHeader{}, }, { "bad: no parens", `foobar`, ifHeader{}, }, { "bad: empty list #1", `()`, ifHeader{}, }, { "bad: empty list #2", `(a) (b c) () (d)`, ifHeader{}, }, { "bad: no list after resource #1", ``, ifHeader{}, }, { "bad: no list after resource #2", ` (a)`, ifHeader{}, }, { "bad: no list after resource #3", ` (a) (b) `, ifHeader{}, }, { "bad: no-tag-list followed by tagged-list", `(a) (b) (c)`, ifHeader{}, }, { "bad: unfinished list", `(a`, ifHeader{}, }, { "bad: unfinished ETag", `([b`, ifHeader{}, }, { "bad: unfinished Notted list", `(Not a`, ifHeader{}, }, { "bad: double Not", `(Not Not a)`, ifHeader{}, }, { "good: one list with a Token", `(a)`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `a`, }}, }}, }, }, { "good: one list with an ETag", `([a])`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ ETag: `a`, }}, }}, }, }, { "good: one list with three Nots", `(Not a Not b Not [d])`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Not: true, Token: `a`, }, { Not: true, Token: `b`, }, { Not: true, ETag: `d`, }}, }}, }, }, { "good: two lists", `(a) (b)`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `a`, }}, }, { conditions: []Condition{{ Token: `b`, }}, }}, }, }, { "good: two Notted lists", `(Not a) (Not b)`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Not: true, Token: `a`, }}, }, { conditions: []Condition{{ Not: true, Token: `b`, }}, }}, }, }, { "section 7.5.1", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://www.example.com/users/f/fielding/index.html`, conditions: []Condition{{ Token: `urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6`, }}, }}, }, }, { "section 7.5.2 #1", `()`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, }}, }}, }, }, { "section 7.5.2 #2", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://example.com/locked/`, conditions: []Condition{{ Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, }}, }}, }, }, { "section 7.5.2 #3", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://example.com/locked/member`, conditions: []Condition{{ Token: `urn:uuid:150852e2-3847-42d5-8cbe-0f4f296f26cf`, }}, }}, }, }, { "section 9.9.6", `() ()`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:fe184f2e-6eec-41d0-c765-01adc56e6bb4`, }}, }, { conditions: []Condition{{ Token: `urn:uuid:e454f3f3-acdc-452a-56c7-00a5c91e4b77`, }}, }}, }, }, { "section 9.10.8", `()`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:e71d4fae-5dec-22d6-fea5-00a0c91e6be4`, }}, }}, }, }, { "section 10.4.6", `( ["I am an ETag"]) (["I am another ETag"])`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }, { ETag: `"I am an ETag"`, }}, }, { conditions: []Condition{{ ETag: `"I am another ETag"`, }}, }}, }, }, { "section 10.4.7", `(Not )`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Not: true, Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }, { Token: `urn:uuid:58f202ac-22cf-11d1-b12d-002035b29092`, }}, }}, }, }, { "section 10.4.8", `() (Not )`, ifHeader{ lists: []ifList{{ conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }}, }, { conditions: []Condition{{ Not: true, Token: `DAV:no-lock`, }}, }}, }, }, { "section 10.4.9", ` ( [W/"A weak ETag"]) (["strong ETag"])`, ifHeader{ lists: []ifList{{ resourceTag: `/resource1`, conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }, { ETag: `W/"A weak ETag"`, }}, }, { resourceTag: `/resource1`, conditions: []Condition{{ ETag: `"strong ETag"`, }}, }}, }, }, { "section 10.4.10", ` ()`, ifHeader{ lists: []ifList{{ resourceTag: `http://www.example.com/specs/`, conditions: []Condition{{ Token: `urn:uuid:181d4fae-7d8c-11d0-a765-00a0c91e6bf2`, }}, }}, }, }, { "section 10.4.11 #1", ` (["4217"])`, ifHeader{ lists: []ifList{{ resourceTag: `/specs/rfc2518.doc`, conditions: []Condition{{ ETag: `"4217"`, }}, }}, }, }, { "section 10.4.11 #2", ` (Not ["4217"])`, ifHeader{ lists: []ifList{{ resourceTag: `/specs/rfc2518.doc`, conditions: []Condition{{ Not: true, ETag: `"4217"`, }}, }}, }, }} for _, tc := range testCases { got, ok := parseIfHeader(strings.Replace(tc.input, "\n", "", -1)) if gotEmpty := reflect.DeepEqual(got, ifHeader{}); gotEmpty == ok { t.Errorf("%s: should be different: empty header == %t, ok == %t", tc.desc, gotEmpty, ok) continue } if !reflect.DeepEqual(got, tc.want) { t.Errorf("%s:\ngot %v\nwant %v", tc.desc, got, tc.want) continue } } } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/README ================================================ This is a fork of the encoding/xml package at ca1d6c4, the last commit before https://go.googlesource.com/go/+/c0d6d33 "encoding/xml: restore Go 1.4 name space behavior" made late in the lead-up to the Go 1.5 release. The list of encoding/xml changes is at https://go.googlesource.com/go/+log/master/src/encoding/xml This fork is temporary, and I (nigeltao) expect to revert it after Go 1.6 is released. See http://golang.org/issue/11841 ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/atom_test.go ================================================ // 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 xml import "time" var atomValue = &Feed{ XMLName: Name{"http://www.w3.org/2005/Atom", "feed"}, Title: "Example Feed", Link: []Link{{Href: "http://example.org/"}}, Updated: ParseTime("2003-12-13T18:30:02Z"), Author: Person{Name: "John Doe"}, Id: "urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", Entry: []Entry{ { Title: "Atom-Powered Robots Run Amok", Link: []Link{{Href: "http://example.org/2003/12/13/atom03"}}, Id: "urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", Updated: ParseTime("2003-12-13T18:30:02Z"), Summary: NewText("Some text."), }, }, } var atomXml = `` + `` + `Example Feed` + `urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6` + `` + `John Doe` + `` + `Atom-Powered Robots Run Amok` + `urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a` + `` + `2003-12-13T18:30:02Z` + `` + `Some text.` + `` + `` func ParseTime(str string) time.Time { t, err := time.Parse(time.RFC3339, str) if err != nil { panic(err) } return t } func NewText(text string) Text { return Text{ Body: text, } } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/example_test.go ================================================ // 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 xml_test import ( "encoding/xml" "fmt" "os" ) func ExampleMarshalIndent() { type Address struct { City, State string } type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"` } v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} v.Comment = " Need more details. " v.Address = Address{"Hanga Roa", "Easter Island"} output, err := xml.MarshalIndent(v, " ", " ") if err != nil { fmt.Printf("error: %v\n", err) } os.Stdout.Write(output) // Output: // // // John // Doe // // 42 // false // Hanga Roa // Easter Island // // } func ExampleEncoder() { type Address struct { City, State string } type Person struct { XMLName xml.Name `xml:"person"` Id int `xml:"id,attr"` FirstName string `xml:"name>first"` LastName string `xml:"name>last"` Age int `xml:"age"` Height float32 `xml:"height,omitempty"` Married bool Address Comment string `xml:",comment"` } v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42} v.Comment = " Need more details. " v.Address = Address{"Hanga Roa", "Easter Island"} enc := xml.NewEncoder(os.Stdout) enc.Indent(" ", " ") if err := enc.Encode(v); err != nil { fmt.Printf("error: %v\n", err) } // Output: // // // John // Doe // // 42 // false // Hanga Roa // Easter Island // // } // This example demonstrates unmarshaling an XML excerpt into a value with // some preset fields. Note that the Phone field isn't modified and that // the XML element is ignored. Also, the Groups field is assigned // considering the element path provided in its tag. func ExampleUnmarshal() { type Email struct { Where string `xml:"where,attr"` Addr string } type Address struct { City, State string } type Result struct { XMLName xml.Name `xml:"Person"` Name string `xml:"FullName"` Phone string Email []Email Groups []string `xml:"Group>Value"` Address } v := Result{Name: "none", Phone: "none"} data := ` Grace R. Emlin Example Inc. gre@example.com gre@work.com Friends Squash Hanga Roa Easter Island ` err := xml.Unmarshal([]byte(data), &v) if err != nil { fmt.Printf("error: %v", err) return } fmt.Printf("XMLName: %#v\n", v.XMLName) fmt.Printf("Name: %q\n", v.Name) fmt.Printf("Phone: %q\n", v.Phone) fmt.Printf("Email: %v\n", v.Email) fmt.Printf("Groups: %v\n", v.Groups) fmt.Printf("Address: %v\n", v.Address) // Output: // XMLName: xml.Name{Space:"", Local:"Person"} // Name: "Grace R. Emlin" // Phone: "none" // Email: [{home gre@example.com} {work gre@work.com}] // Groups: [Friends Squash] // Address: {Hanga Roa Easter Island} } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/marshal.go ================================================ // 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 xml import ( "bufio" "bytes" "encoding" "fmt" "io" "reflect" "strconv" "strings" ) const ( // A generic XML header suitable for use with the output of Marshal. // This is not automatically added to any output of this package, // it is provided as a convenience. Header = `` + "\n" ) // Marshal returns the XML encoding of v. // // Marshal handles an array or slice by marshalling each of the elements. // Marshal handles a pointer by marshalling the value it points at or, if the // pointer is nil, by writing nothing. Marshal handles an interface value by // marshalling the value it contains or, if the interface value is nil, by // writing nothing. Marshal handles all other data by writing one or more XML // elements containing the data. // // The name for the XML elements is taken from, in order of preference: // - the tag on the XMLName field, if the data is a struct // - the value of the XMLName field of type xml.Name // - the tag of the struct field used to obtain the data // - the name of the struct field used to obtain the data // - the name of the marshalled type // // The XML element for a struct contains marshalled elements for each of the // exported fields of the struct, with these exceptions: // - the XMLName field, described above, is omitted. // - a field with tag "-" is omitted. // - a field with tag "name,attr" becomes an attribute with // the given name in the XML element. // - a field with tag ",attr" becomes an attribute with the // field name in the XML element. // - a field with tag ",chardata" is written as character data, // not as an XML element. // - a field with tag ",innerxml" is written verbatim, not subject // to the usual marshalling procedure. // - a field with tag ",comment" is written as an XML comment, not // subject to the usual marshalling procedure. It must not contain // the "--" string within it. // - a field with a tag including the "omitempty" option is omitted // if the field value is empty. The empty values are false, 0, any // nil pointer or interface value, and any array, slice, map, or // string of length zero. // - an anonymous struct field is handled as if the fields of its // value were part of the outer struct. // // If a field uses a tag "a>b>c", then the element c will be nested inside // parent elements a and b. Fields that appear next to each other that name // the same parent will be enclosed in one XML element. // // See MarshalIndent for an example. // // Marshal will return an error if asked to marshal a channel, function, or map. func Marshal(v interface{}) ([]byte, error) { var b bytes.Buffer if err := NewEncoder(&b).Encode(v); err != nil { return nil, err } return b.Bytes(), nil } // Marshaler is the interface implemented by objects that can marshal // themselves into valid XML elements. // // MarshalXML encodes the receiver as zero or more XML elements. // By convention, arrays or slices are typically encoded as a sequence // of elements, one per entry. // Using start as the element tag is not required, but doing so // will enable Unmarshal to match the XML elements to the correct // struct field. // One common implementation strategy is to construct a separate // value with a layout corresponding to the desired XML and then // to encode it using e.EncodeElement. // Another common strategy is to use repeated calls to e.EncodeToken // to generate the XML output one token at a time. // The sequence of encoded tokens must make up zero or more valid // XML elements. type Marshaler interface { MarshalXML(e *Encoder, start StartElement) error } // MarshalerAttr is the interface implemented by objects that can marshal // themselves into valid XML attributes. // // MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. // Using name as the attribute name is not required, but doing so // will enable Unmarshal to match the attribute to the correct // struct field. // If MarshalXMLAttr returns the zero attribute Attr{}, no attribute // will be generated in the output. // MarshalXMLAttr is used only for struct fields with the // "attr" option in the field tag. type MarshalerAttr interface { MarshalXMLAttr(name Name) (Attr, error) } // MarshalIndent works like Marshal, but each XML element begins on a new // indented line that starts with prefix and is followed by one or more // copies of indent according to the nesting depth. func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { var b bytes.Buffer enc := NewEncoder(&b) enc.Indent(prefix, indent) if err := enc.Encode(v); err != nil { return nil, err } return b.Bytes(), nil } // An Encoder writes XML data to an output stream. type Encoder struct { p printer } // NewEncoder returns a new encoder that writes to w. func NewEncoder(w io.Writer) *Encoder { e := &Encoder{printer{Writer: bufio.NewWriter(w)}} e.p.encoder = e return e } // Indent sets the encoder to generate XML in which each element // begins on a new indented line that starts with prefix and is followed by // one or more copies of indent according to the nesting depth. func (enc *Encoder) Indent(prefix, indent string) { enc.p.prefix = prefix enc.p.indent = indent } // Encode writes the XML encoding of v to the stream. // // See the documentation for Marshal for details about the conversion // of Go values to XML. // // Encode calls Flush before returning. func (enc *Encoder) Encode(v interface{}) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, nil) if err != nil { return err } return enc.p.Flush() } // EncodeElement writes the XML encoding of v to the stream, // using start as the outermost tag in the encoding. // // See the documentation for Marshal for details about the conversion // of Go values to XML. // // EncodeElement calls Flush before returning. func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error { err := enc.p.marshalValue(reflect.ValueOf(v), nil, &start) if err != nil { return err } return enc.p.Flush() } var ( begComment = []byte("") endProcInst = []byte("?>") endDirective = []byte(">") ) // EncodeToken writes the given XML token to the stream. // It returns an error if StartElement and EndElement tokens are not // properly matched. // // EncodeToken does not call Flush, because usually it is part of a // larger operation such as Encode or EncodeElement (or a custom // Marshaler's MarshalXML invoked during those), and those will call // Flush when finished. Callers that create an Encoder and then invoke // EncodeToken directly, without using Encode or EncodeElement, need to // call Flush when finished to ensure that the XML is written to the // underlying writer. // // EncodeToken allows writing a ProcInst with Target set to "xml" only // as the first token in the stream. // // When encoding a StartElement holding an XML namespace prefix // declaration for a prefix that is not already declared, contained // elements (including the StartElement itself) will use the declared // prefix when encoding names with matching namespace URIs. func (enc *Encoder) EncodeToken(t Token) error { p := &enc.p switch t := t.(type) { case StartElement: if err := p.writeStart(&t); err != nil { return err } case EndElement: if err := p.writeEnd(t.Name); err != nil { return err } case CharData: escapeText(p, t, false) case Comment: if bytes.Contains(t, endComment) { return fmt.Errorf("xml: EncodeToken of Comment containing --> marker") } p.WriteString("") return p.cachedWriteError() case ProcInst: // First token to be encoded which is also a ProcInst with target of xml // is the xml declaration. The only ProcInst where target of xml is allowed. if t.Target == "xml" && p.Buffered() != 0 { return fmt.Errorf("xml: EncodeToken of ProcInst xml target only valid for xml declaration, first token encoded") } if !isNameString(t.Target) { return fmt.Errorf("xml: EncodeToken of ProcInst with invalid Target") } if bytes.Contains(t.Inst, endProcInst) { return fmt.Errorf("xml: EncodeToken of ProcInst containing ?> marker") } p.WriteString(" 0 { p.WriteByte(' ') p.Write(t.Inst) } p.WriteString("?>") case Directive: if !isValidDirective(t) { return fmt.Errorf("xml: EncodeToken of Directive containing wrong < or > markers") } p.WriteString("") default: return fmt.Errorf("xml: EncodeToken of invalid token type") } return p.cachedWriteError() } // isValidDirective reports whether dir is a valid directive text, // meaning angle brackets are matched, ignoring comments and strings. func isValidDirective(dir Directive) bool { var ( depth int inquote uint8 incomment bool ) for i, c := range dir { switch { case incomment: if c == '>' { if n := 1 + i - len(endComment); n >= 0 && bytes.Equal(dir[n:i+1], endComment) { incomment = false } } // Just ignore anything in comment case inquote != 0: if c == inquote { inquote = 0 } // Just ignore anything within quotes case c == '\'' || c == '"': inquote = c case c == '<': if i+len(begComment) < len(dir) && bytes.Equal(dir[i:i+len(begComment)], begComment) { incomment = true } else { depth++ } case c == '>': if depth == 0 { return false } depth-- } } return depth == 0 && inquote == 0 && !incomment } // Flush flushes any buffered XML to the underlying writer. // See the EncodeToken documentation for details about when it is necessary. func (enc *Encoder) Flush() error { return enc.p.Flush() } type printer struct { *bufio.Writer encoder *Encoder seq int indent string prefix string depth int indentedIn bool putNewline bool defaultNS string attrNS map[string]string // map prefix -> name space attrPrefix map[string]string // map name space -> prefix prefixes []printerPrefix tags []Name } // printerPrefix holds a namespace undo record. // When an element is popped, the prefix record // is set back to the recorded URL. The empty // prefix records the URL for the default name space. // // The start of an element is recorded with an element // that has mark=true. type printerPrefix struct { prefix string url string mark bool } func (p *printer) prefixForNS(url string, isAttr bool) string { // The "http://www.w3.org/XML/1998/namespace" name space is predefined as "xml" // and must be referred to that way. // (The "http://www.w3.org/2000/xmlns/" name space is also predefined as "xmlns", // but users should not be trying to use that one directly - that's our job.) if url == xmlURL { return "xml" } if !isAttr && url == p.defaultNS { // We can use the default name space. return "" } return p.attrPrefix[url] } // defineNS pushes any namespace definition found in the given attribute. // If ignoreNonEmptyDefault is true, an xmlns="nonempty" // attribute will be ignored. func (p *printer) defineNS(attr Attr, ignoreNonEmptyDefault bool) error { var prefix string if attr.Name.Local == "xmlns" { if attr.Name.Space != "" && attr.Name.Space != "xml" && attr.Name.Space != xmlURL { return fmt.Errorf("xml: cannot redefine xmlns attribute prefix") } } else if attr.Name.Space == "xmlns" && attr.Name.Local != "" { prefix = attr.Name.Local if attr.Value == "" { // Technically, an empty XML namespace is allowed for an attribute. // From http://www.w3.org/TR/xml-names11/#scoping-defaulting: // // The attribute value in a namespace declaration for a prefix may be // empty. This has the effect, within the scope of the declaration, of removing // any association of the prefix with a namespace name. // // However our namespace prefixes here are used only as hints. There's // no need to respect the removal of a namespace prefix, so we ignore it. return nil } } else { // Ignore: it's not a namespace definition return nil } if prefix == "" { if attr.Value == p.defaultNS { // No need for redefinition. return nil } if attr.Value != "" && ignoreNonEmptyDefault { // We have an xmlns="..." value but // it can't define a name space in this context, // probably because the element has an empty // name space. In this case, we just ignore // the name space declaration. return nil } } else if _, ok := p.attrPrefix[attr.Value]; ok { // There's already a prefix for the given name space, // so use that. This prevents us from // having two prefixes for the same name space // so attrNS and attrPrefix can remain bijective. return nil } p.pushPrefix(prefix, attr.Value) return nil } // createNSPrefix creates a name space prefix attribute // to use for the given name space, defining a new prefix // if necessary. // If isAttr is true, the prefix is to be created for an attribute // prefix, which means that the default name space cannot // be used. func (p *printer) createNSPrefix(url string, isAttr bool) { if _, ok := p.attrPrefix[url]; ok { // We already have a prefix for the given URL. return } switch { case !isAttr && url == p.defaultNS: // We can use the default name space. return case url == "": // The only way we can encode names in the empty // name space is by using the default name space, // so we must use that. if p.defaultNS != "" { // The default namespace is non-empty, so we // need to set it to empty. p.pushPrefix("", "") } return case url == xmlURL: return } // TODO If the URL is an existing prefix, we could // use it as is. That would enable the // marshaling of elements that had been unmarshaled // and with a name space prefix that was not found. // although technically it would be incorrect. // Pick a name. We try to use the final element of the path // but fall back to _. prefix := strings.TrimRight(url, "/") if i := strings.LastIndex(prefix, "/"); i >= 0 { prefix = prefix[i+1:] } if prefix == "" || !isName([]byte(prefix)) || strings.Contains(prefix, ":") { prefix = "_" } if strings.HasPrefix(prefix, "xml") { // xmlanything is reserved. prefix = "_" + prefix } if p.attrNS[prefix] != "" { // Name is taken. Find a better one. for p.seq++; ; p.seq++ { if id := prefix + "_" + strconv.Itoa(p.seq); p.attrNS[id] == "" { prefix = id break } } } p.pushPrefix(prefix, url) } // writeNamespaces writes xmlns attributes for all the // namespace prefixes that have been defined in // the current element. func (p *printer) writeNamespaces() { for i := len(p.prefixes) - 1; i >= 0; i-- { prefix := p.prefixes[i] if prefix.mark { return } p.WriteString(" ") if prefix.prefix == "" { // Default name space. p.WriteString(`xmlns="`) } else { p.WriteString("xmlns:") p.WriteString(prefix.prefix) p.WriteString(`="`) } EscapeText(p, []byte(p.nsForPrefix(prefix.prefix))) p.WriteString(`"`) } } // pushPrefix pushes a new prefix on the prefix stack // without checking to see if it is already defined. func (p *printer) pushPrefix(prefix, url string) { p.prefixes = append(p.prefixes, printerPrefix{ prefix: prefix, url: p.nsForPrefix(prefix), }) p.setAttrPrefix(prefix, url) } // nsForPrefix returns the name space for the given // prefix. Note that this is not valid for the // empty attribute prefix, which always has an empty // name space. func (p *printer) nsForPrefix(prefix string) string { if prefix == "" { return p.defaultNS } return p.attrNS[prefix] } // markPrefix marks the start of an element on the prefix // stack. func (p *printer) markPrefix() { p.prefixes = append(p.prefixes, printerPrefix{ mark: true, }) } // popPrefix pops all defined prefixes for the current // element. func (p *printer) popPrefix() { for len(p.prefixes) > 0 { prefix := p.prefixes[len(p.prefixes)-1] p.prefixes = p.prefixes[:len(p.prefixes)-1] if prefix.mark { break } p.setAttrPrefix(prefix.prefix, prefix.url) } } // setAttrPrefix sets an attribute name space prefix. // If url is empty, the attribute is removed. // If prefix is empty, the default name space is set. func (p *printer) setAttrPrefix(prefix, url string) { if prefix == "" { p.defaultNS = url return } if url == "" { delete(p.attrPrefix, p.attrNS[prefix]) delete(p.attrNS, prefix) return } if p.attrPrefix == nil { // Need to define a new name space. p.attrPrefix = make(map[string]string) p.attrNS = make(map[string]string) } // Remove any old prefix value. This is OK because we maintain a // strict one-to-one mapping between prefix and URL (see // defineNS) delete(p.attrPrefix, p.attrNS[prefix]) p.attrPrefix[url] = prefix p.attrNS[prefix] = url } var ( marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() marshalerAttrType = reflect.TypeOf((*MarshalerAttr)(nil)).Elem() textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() ) // marshalValue writes one or more XML elements representing val. // If val was obtained from a struct field, finfo must have its details. func (p *printer) marshalValue(val reflect.Value, finfo *fieldInfo, startTemplate *StartElement) error { if startTemplate != nil && startTemplate.Name.Local == "" { return fmt.Errorf("xml: EncodeElement of StartElement with missing name") } if !val.IsValid() { return nil } if finfo != nil && finfo.flags&fOmitEmpty != 0 && isEmptyValue(val) { return nil } // Drill into interfaces and pointers. // This can turn into an infinite loop given a cyclic chain, // but it matches the Go 1 behavior. for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { if val.IsNil() { return nil } val = val.Elem() } kind := val.Kind() typ := val.Type() // Check for marshaler. if val.CanInterface() && typ.Implements(marshalerType) { return p.marshalInterface(val.Interface().(Marshaler), p.defaultStart(typ, finfo, startTemplate)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(marshalerType) { return p.marshalInterface(pv.Interface().(Marshaler), p.defaultStart(pv.Type(), finfo, startTemplate)) } } // Check for text marshaler. if val.CanInterface() && typ.Implements(textMarshalerType) { return p.marshalTextInterface(val.Interface().(encoding.TextMarshaler), p.defaultStart(typ, finfo, startTemplate)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { return p.marshalTextInterface(pv.Interface().(encoding.TextMarshaler), p.defaultStart(pv.Type(), finfo, startTemplate)) } } // Slices and arrays iterate over the elements. They do not have an enclosing tag. if (kind == reflect.Slice || kind == reflect.Array) && typ.Elem().Kind() != reflect.Uint8 { for i, n := 0, val.Len(); i < n; i++ { if err := p.marshalValue(val.Index(i), finfo, startTemplate); err != nil { return err } } return nil } tinfo, err := getTypeInfo(typ) if err != nil { return err } // Create start element. // Precedence for the XML element name is: // 0. startTemplate // 1. XMLName field in underlying struct; // 2. field name/tag in the struct field; and // 3. type name var start StartElement // explicitNS records whether the element's name space has been // explicitly set (for example an XMLName field). explicitNS := false if startTemplate != nil { start.Name = startTemplate.Name explicitNS = true start.Attr = append(start.Attr, startTemplate.Attr...) } else if tinfo.xmlname != nil { xmlname := tinfo.xmlname if xmlname.name != "" { start.Name.Space, start.Name.Local = xmlname.xmlns, xmlname.name } else if v, ok := xmlname.value(val).Interface().(Name); ok && v.Local != "" { start.Name = v } explicitNS = true } if start.Name.Local == "" && finfo != nil { start.Name.Local = finfo.name if finfo.xmlns != "" { start.Name.Space = finfo.xmlns explicitNS = true } } if start.Name.Local == "" { name := typ.Name() if name == "" { return &UnsupportedTypeError{typ} } start.Name.Local = name } // defaultNS records the default name space as set by a xmlns="..." // attribute. We don't set p.defaultNS because we want to let // the attribute writing code (in p.defineNS) be solely responsible // for maintaining that. defaultNS := p.defaultNS // Attributes for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fAttr == 0 { continue } attr, err := p.fieldAttr(finfo, val) if err != nil { return err } if attr.Name.Local == "" { continue } start.Attr = append(start.Attr, attr) if attr.Name.Space == "" && attr.Name.Local == "xmlns" { defaultNS = attr.Value } } if !explicitNS { // Historic behavior: elements use the default name space // they are contained in by default. start.Name.Space = defaultNS } // Historic behaviour: an element that's in a namespace sets // the default namespace for all elements contained within it. start.setDefaultNamespace() if err := p.writeStart(&start); err != nil { return err } if val.Kind() == reflect.Struct { err = p.marshalStruct(tinfo, val) } else { s, b, err1 := p.marshalSimple(typ, val) if err1 != nil { err = err1 } else if b != nil { EscapeText(p, b) } else { p.EscapeString(s) } } if err != nil { return err } if err := p.writeEnd(start.Name); err != nil { return err } return p.cachedWriteError() } // fieldAttr returns the attribute of the given field. // If the returned attribute has an empty Name.Local, // it should not be used. // The given value holds the value containing the field. func (p *printer) fieldAttr(finfo *fieldInfo, val reflect.Value) (Attr, error) { fv := finfo.value(val) name := Name{Space: finfo.xmlns, Local: finfo.name} if finfo.flags&fOmitEmpty != 0 && isEmptyValue(fv) { return Attr{}, nil } if fv.Kind() == reflect.Interface && fv.IsNil() { return Attr{}, nil } if fv.CanInterface() && fv.Type().Implements(marshalerAttrType) { attr, err := fv.Interface().(MarshalerAttr).MarshalXMLAttr(name) return attr, err } if fv.CanAddr() { pv := fv.Addr() if pv.CanInterface() && pv.Type().Implements(marshalerAttrType) { attr, err := pv.Interface().(MarshalerAttr).MarshalXMLAttr(name) return attr, err } } if fv.CanInterface() && fv.Type().Implements(textMarshalerType) { text, err := fv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return Attr{}, err } return Attr{name, string(text)}, nil } if fv.CanAddr() { pv := fv.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { text, err := pv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return Attr{}, err } return Attr{name, string(text)}, nil } } // Dereference or skip nil pointer, interface values. switch fv.Kind() { case reflect.Ptr, reflect.Interface: if fv.IsNil() { return Attr{}, nil } fv = fv.Elem() } s, b, err := p.marshalSimple(fv.Type(), fv) if err != nil { return Attr{}, err } if b != nil { s = string(b) } return Attr{name, s}, nil } // defaultStart returns the default start element to use, // given the reflect type, field info, and start template. func (p *printer) defaultStart(typ reflect.Type, finfo *fieldInfo, startTemplate *StartElement) StartElement { var start StartElement // Precedence for the XML element name is as above, // except that we do not look inside structs for the first field. if startTemplate != nil { start.Name = startTemplate.Name start.Attr = append(start.Attr, startTemplate.Attr...) } else if finfo != nil && finfo.name != "" { start.Name.Local = finfo.name start.Name.Space = finfo.xmlns } else if typ.Name() != "" { start.Name.Local = typ.Name() } else { // Must be a pointer to a named type, // since it has the Marshaler methods. start.Name.Local = typ.Elem().Name() } // Historic behaviour: elements use the name space of // the element they are contained in by default. if start.Name.Space == "" { start.Name.Space = p.defaultNS } start.setDefaultNamespace() return start } // marshalInterface marshals a Marshaler interface value. func (p *printer) marshalInterface(val Marshaler, start StartElement) error { // Push a marker onto the tag stack so that MarshalXML // cannot close the XML tags that it did not open. p.tags = append(p.tags, Name{}) n := len(p.tags) err := val.MarshalXML(p.encoder, start) if err != nil { return err } // Make sure MarshalXML closed all its tags. p.tags[n-1] is the mark. if len(p.tags) > n { return fmt.Errorf("xml: %s.MarshalXML wrote invalid XML: <%s> not closed", receiverType(val), p.tags[len(p.tags)-1].Local) } p.tags = p.tags[:n-1] return nil } // marshalTextInterface marshals a TextMarshaler interface value. func (p *printer) marshalTextInterface(val encoding.TextMarshaler, start StartElement) error { if err := p.writeStart(&start); err != nil { return err } text, err := val.MarshalText() if err != nil { return err } EscapeText(p, text) return p.writeEnd(start.Name) } // writeStart writes the given start element. func (p *printer) writeStart(start *StartElement) error { if start.Name.Local == "" { return fmt.Errorf("xml: start tag with no name") } p.tags = append(p.tags, start.Name) p.markPrefix() // Define any name spaces explicitly declared in the attributes. // We do this as a separate pass so that explicitly declared prefixes // will take precedence over implicitly declared prefixes // regardless of the order of the attributes. ignoreNonEmptyDefault := start.Name.Space == "" for _, attr := range start.Attr { if err := p.defineNS(attr, ignoreNonEmptyDefault); err != nil { return err } } // Define any new name spaces implied by the attributes. for _, attr := range start.Attr { name := attr.Name // From http://www.w3.org/TR/xml-names11/#defaulting // "Default namespace declarations do not apply directly // to attribute names; the interpretation of unprefixed // attributes is determined by the element on which they // appear." // This means we don't need to create a new namespace // when an attribute name space is empty. if name.Space != "" && !name.isNamespace() { p.createNSPrefix(name.Space, true) } } p.createNSPrefix(start.Name.Space, false) p.writeIndent(1) p.WriteByte('<') p.writeName(start.Name, false) p.writeNamespaces() for _, attr := range start.Attr { name := attr.Name if name.Local == "" || name.isNamespace() { // Namespaces have already been written by writeNamespaces above. continue } p.WriteByte(' ') p.writeName(name, true) p.WriteString(`="`) p.EscapeString(attr.Value) p.WriteByte('"') } p.WriteByte('>') return nil } // writeName writes the given name. It assumes // that p.createNSPrefix(name) has already been called. func (p *printer) writeName(name Name, isAttr bool) { if prefix := p.prefixForNS(name.Space, isAttr); prefix != "" { p.WriteString(prefix) p.WriteByte(':') } p.WriteString(name.Local) } func (p *printer) writeEnd(name Name) error { if name.Local == "" { return fmt.Errorf("xml: end tag with no name") } if len(p.tags) == 0 || p.tags[len(p.tags)-1].Local == "" { return fmt.Errorf("xml: end tag without start tag", name.Local) } if top := p.tags[len(p.tags)-1]; top != name { if top.Local != name.Local { return fmt.Errorf("xml: end tag does not match start tag <%s>", name.Local, top.Local) } return fmt.Errorf("xml: end tag in namespace %s does not match start tag <%s> in namespace %s", name.Local, name.Space, top.Local, top.Space) } p.tags = p.tags[:len(p.tags)-1] p.writeIndent(-1) p.WriteByte('<') p.WriteByte('/') p.writeName(name, false) p.WriteByte('>') p.popPrefix() return nil } func (p *printer) marshalSimple(typ reflect.Type, val reflect.Value) (string, []byte, error) { switch val.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return strconv.FormatInt(val.Int(), 10), nil, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return strconv.FormatUint(val.Uint(), 10), nil, nil case reflect.Float32, reflect.Float64: return strconv.FormatFloat(val.Float(), 'g', -1, val.Type().Bits()), nil, nil case reflect.String: return val.String(), nil, nil case reflect.Bool: return strconv.FormatBool(val.Bool()), nil, nil case reflect.Array: if typ.Elem().Kind() != reflect.Uint8 { break } // [...]byte var bytes []byte if val.CanAddr() { bytes = val.Slice(0, val.Len()).Bytes() } else { bytes = make([]byte, val.Len()) reflect.Copy(reflect.ValueOf(bytes), val) } return "", bytes, nil case reflect.Slice: if typ.Elem().Kind() != reflect.Uint8 { break } // []byte return "", val.Bytes(), nil } return "", nil, &UnsupportedTypeError{typ} } var ddBytes = []byte("--") func (p *printer) marshalStruct(tinfo *typeInfo, val reflect.Value) error { s := parentStack{p: p} for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fAttr != 0 { continue } vf := finfo.value(val) // Dereference or skip nil pointer, interface values. switch vf.Kind() { case reflect.Ptr, reflect.Interface: if !vf.IsNil() { vf = vf.Elem() } } switch finfo.flags & fMode { case fCharData: if err := s.setParents(&noField, reflect.Value{}); err != nil { return err } if vf.CanInterface() && vf.Type().Implements(textMarshalerType) { data, err := vf.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } Escape(p, data) continue } if vf.CanAddr() { pv := vf.Addr() if pv.CanInterface() && pv.Type().Implements(textMarshalerType) { data, err := pv.Interface().(encoding.TextMarshaler).MarshalText() if err != nil { return err } Escape(p, data) continue } } var scratch [64]byte switch vf.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: Escape(p, strconv.AppendInt(scratch[:0], vf.Int(), 10)) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: Escape(p, strconv.AppendUint(scratch[:0], vf.Uint(), 10)) case reflect.Float32, reflect.Float64: Escape(p, strconv.AppendFloat(scratch[:0], vf.Float(), 'g', -1, vf.Type().Bits())) case reflect.Bool: Escape(p, strconv.AppendBool(scratch[:0], vf.Bool())) case reflect.String: if err := EscapeText(p, []byte(vf.String())); err != nil { return err } case reflect.Slice: if elem, ok := vf.Interface().([]byte); ok { if err := EscapeText(p, elem); err != nil { return err } } } continue case fComment: if err := s.setParents(&noField, reflect.Value{}); err != nil { return err } k := vf.Kind() if !(k == reflect.String || k == reflect.Slice && vf.Type().Elem().Kind() == reflect.Uint8) { return fmt.Errorf("xml: bad type for comment field of %s", val.Type()) } if vf.Len() == 0 { continue } p.writeIndent(0) p.WriteString("" is invalid grammar. Make it "- -->" p.WriteByte(' ') } p.WriteString("-->") continue case fInnerXml: iface := vf.Interface() switch raw := iface.(type) { case []byte: p.Write(raw) continue case string: p.WriteString(raw) continue } case fElement, fElement | fAny: if err := s.setParents(finfo, vf); err != nil { return err } } if err := p.marshalValue(vf, finfo, nil); err != nil { return err } } if err := s.setParents(&noField, reflect.Value{}); err != nil { return err } return p.cachedWriteError() } var noField fieldInfo // return the bufio Writer's cached write error func (p *printer) cachedWriteError() error { _, err := p.Write(nil) return err } func (p *printer) writeIndent(depthDelta int) { if len(p.prefix) == 0 && len(p.indent) == 0 { return } if depthDelta < 0 { p.depth-- if p.indentedIn { p.indentedIn = false return } p.indentedIn = false } if p.putNewline { p.WriteByte('\n') } else { p.putNewline = true } if len(p.prefix) > 0 { p.WriteString(p.prefix) } if len(p.indent) > 0 { for i := 0; i < p.depth; i++ { p.WriteString(p.indent) } } if depthDelta > 0 { p.depth++ p.indentedIn = true } } type parentStack struct { p *printer xmlns string parents []string } // setParents sets the stack of current parents to those found in finfo. // It only writes the start elements if vf holds a non-nil value. // If finfo is &noField, it pops all elements. func (s *parentStack) setParents(finfo *fieldInfo, vf reflect.Value) error { xmlns := s.p.defaultNS if finfo.xmlns != "" { xmlns = finfo.xmlns } commonParents := 0 if xmlns == s.xmlns { for ; commonParents < len(finfo.parents) && commonParents < len(s.parents); commonParents++ { if finfo.parents[commonParents] != s.parents[commonParents] { break } } } // Pop off any parents that aren't in common with the previous field. for i := len(s.parents) - 1; i >= commonParents; i-- { if err := s.p.writeEnd(Name{ Space: s.xmlns, Local: s.parents[i], }); err != nil { return err } } s.parents = finfo.parents s.xmlns = xmlns if commonParents >= len(s.parents) { // No new elements to push. return nil } if (vf.Kind() == reflect.Ptr || vf.Kind() == reflect.Interface) && vf.IsNil() { // The element is nil, so no need for the start elements. s.parents = s.parents[:commonParents] return nil } // Push any new parents required. for _, name := range s.parents[commonParents:] { start := &StartElement{ Name: Name{ Space: s.xmlns, Local: name, }, } // Set the default name space for parent elements // to match what we do with other elements. if s.xmlns != s.p.defaultNS { start.setDefaultNamespace() } if err := s.p.writeStart(start); err != nil { return err } } return nil } // A MarshalXMLError is returned when Marshal encounters a type // that cannot be converted into XML. type UnsupportedTypeError struct { Type reflect.Type } func (e *UnsupportedTypeError) Error() string { return "xml: unsupported type: " + e.Type.String() } 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 } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/marshal_test.go ================================================ // 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 xml import ( "bytes" "errors" "fmt" "io" "reflect" "strconv" "strings" "sync" "testing" "time" ) type DriveType int const ( HyperDrive DriveType = iota ImprobabilityDrive ) type Passenger struct { Name []string `xml:"name"` Weight float32 `xml:"weight"` } type Ship struct { XMLName struct{} `xml:"spaceship"` Name string `xml:"name,attr"` Pilot string `xml:"pilot,attr"` Drive DriveType `xml:"drive"` Age uint `xml:"age"` Passenger []*Passenger `xml:"passenger"` secret string } type NamedType string type Port struct { XMLName struct{} `xml:"port"` Type string `xml:"type,attr,omitempty"` Comment string `xml:",comment"` Number string `xml:",chardata"` } type Domain struct { XMLName struct{} `xml:"domain"` Country string `xml:",attr,omitempty"` Name []byte `xml:",chardata"` Comment []byte `xml:",comment"` } type Book struct { XMLName struct{} `xml:"book"` Title string `xml:",chardata"` } type Event struct { XMLName struct{} `xml:"event"` Year int `xml:",chardata"` } type Movie struct { XMLName struct{} `xml:"movie"` Length uint `xml:",chardata"` } type Pi struct { XMLName struct{} `xml:"pi"` Approximation float32 `xml:",chardata"` } type Universe struct { XMLName struct{} `xml:"universe"` Visible float64 `xml:",chardata"` } type Particle struct { XMLName struct{} `xml:"particle"` HasMass bool `xml:",chardata"` } type Departure struct { XMLName struct{} `xml:"departure"` When time.Time `xml:",chardata"` } type SecretAgent struct { XMLName struct{} `xml:"agent"` Handle string `xml:"handle,attr"` Identity string Obfuscate string `xml:",innerxml"` } type NestedItems struct { XMLName struct{} `xml:"result"` Items []string `xml:">item"` Item1 []string `xml:"Items>item1"` } type NestedOrder struct { XMLName struct{} `xml:"result"` Field1 string `xml:"parent>c"` Field2 string `xml:"parent>b"` Field3 string `xml:"parent>a"` } type MixedNested struct { XMLName struct{} `xml:"result"` A string `xml:"parent1>a"` B string `xml:"b"` C string `xml:"parent1>parent2>c"` D string `xml:"parent1>d"` } type NilTest struct { A interface{} `xml:"parent1>parent2>a"` B interface{} `xml:"parent1>b"` C interface{} `xml:"parent1>parent2>c"` } type Service struct { XMLName struct{} `xml:"service"` Domain *Domain `xml:"host>domain"` Port *Port `xml:"host>port"` Extra1 interface{} Extra2 interface{} `xml:"host>extra2"` } var nilStruct *Ship type EmbedA struct { EmbedC EmbedB EmbedB FieldA string } type EmbedB struct { FieldB string *EmbedC } type EmbedC struct { FieldA1 string `xml:"FieldA>A1"` FieldA2 string `xml:"FieldA>A2"` FieldB string FieldC string } type NameCasing struct { XMLName struct{} `xml:"casing"` Xy string XY string XyA string `xml:"Xy,attr"` XYA string `xml:"XY,attr"` } type NamePrecedence struct { XMLName Name `xml:"Parent"` FromTag XMLNameWithoutTag `xml:"InTag"` FromNameVal XMLNameWithoutTag FromNameTag XMLNameWithTag InFieldName string } type XMLNameWithTag struct { XMLName Name `xml:"InXMLNameTag"` Value string `xml:",chardata"` } type XMLNameWithNSTag struct { XMLName Name `xml:"ns InXMLNameWithNSTag"` Value string `xml:",chardata"` } type XMLNameWithoutTag struct { XMLName Name Value string `xml:",chardata"` } type NameInField struct { Foo Name `xml:"ns foo"` } type AttrTest struct { Int int `xml:",attr"` Named int `xml:"int,attr"` Float float64 `xml:",attr"` Uint8 uint8 `xml:",attr"` Bool bool `xml:",attr"` Str string `xml:",attr"` Bytes []byte `xml:",attr"` } type OmitAttrTest struct { Int int `xml:",attr,omitempty"` Named int `xml:"int,attr,omitempty"` Float float64 `xml:",attr,omitempty"` Uint8 uint8 `xml:",attr,omitempty"` Bool bool `xml:",attr,omitempty"` Str string `xml:",attr,omitempty"` Bytes []byte `xml:",attr,omitempty"` } type OmitFieldTest struct { Int int `xml:",omitempty"` Named int `xml:"int,omitempty"` Float float64 `xml:",omitempty"` Uint8 uint8 `xml:",omitempty"` Bool bool `xml:",omitempty"` Str string `xml:",omitempty"` Bytes []byte `xml:",omitempty"` Ptr *PresenceTest `xml:",omitempty"` } type AnyTest struct { XMLName struct{} `xml:"a"` Nested string `xml:"nested>value"` AnyField AnyHolder `xml:",any"` } type AnyOmitTest struct { XMLName struct{} `xml:"a"` Nested string `xml:"nested>value"` AnyField *AnyHolder `xml:",any,omitempty"` } type AnySliceTest struct { XMLName struct{} `xml:"a"` Nested string `xml:"nested>value"` AnyField []AnyHolder `xml:",any"` } type AnyHolder struct { XMLName Name XML string `xml:",innerxml"` } type RecurseA struct { A string B *RecurseB } type RecurseB struct { A *RecurseA B string } type PresenceTest struct { Exists *struct{} } type IgnoreTest struct { PublicSecret string `xml:"-"` } type MyBytes []byte type Data struct { Bytes []byte Attr []byte `xml:",attr"` Custom MyBytes } type Plain struct { V interface{} } type MyInt int type EmbedInt struct { MyInt } type Strings struct { X []string `xml:"A>B,omitempty"` } type PointerFieldsTest struct { XMLName Name `xml:"dummy"` Name *string `xml:"name,attr"` Age *uint `xml:"age,attr"` Empty *string `xml:"empty,attr"` Contents *string `xml:",chardata"` } type ChardataEmptyTest struct { XMLName Name `xml:"test"` Contents *string `xml:",chardata"` } type MyMarshalerTest struct { } var _ Marshaler = (*MyMarshalerTest)(nil) func (m *MyMarshalerTest) MarshalXML(e *Encoder, start StartElement) error { e.EncodeToken(start) e.EncodeToken(CharData([]byte("hello world"))) e.EncodeToken(EndElement{start.Name}) return nil } type MyMarshalerAttrTest struct{} var _ MarshalerAttr = (*MyMarshalerAttrTest)(nil) func (m *MyMarshalerAttrTest) MarshalXMLAttr(name Name) (Attr, error) { return Attr{name, "hello world"}, nil } type MyMarshalerValueAttrTest struct{} var _ MarshalerAttr = MyMarshalerValueAttrTest{} func (m MyMarshalerValueAttrTest) MarshalXMLAttr(name Name) (Attr, error) { return Attr{name, "hello world"}, nil } type MarshalerStruct struct { Foo MyMarshalerAttrTest `xml:",attr"` } type MarshalerValueStruct struct { Foo MyMarshalerValueAttrTest `xml:",attr"` } type InnerStruct struct { XMLName Name `xml:"testns outer"` } type OuterStruct struct { InnerStruct IntAttr int `xml:"int,attr"` } type OuterNamedStruct struct { InnerStruct XMLName Name `xml:"outerns test"` IntAttr int `xml:"int,attr"` } type OuterNamedOrderedStruct struct { XMLName Name `xml:"outerns test"` InnerStruct IntAttr int `xml:"int,attr"` } type OuterOuterStruct struct { OuterStruct } type NestedAndChardata struct { AB []string `xml:"A>B"` Chardata string `xml:",chardata"` } type NestedAndComment struct { AB []string `xml:"A>B"` Comment string `xml:",comment"` } type XMLNSFieldStruct struct { Ns string `xml:"xmlns,attr"` Body string } type NamedXMLNSFieldStruct struct { XMLName struct{} `xml:"testns test"` Ns string `xml:"xmlns,attr"` Body string } type XMLNSFieldStructWithOmitEmpty struct { Ns string `xml:"xmlns,attr,omitempty"` Body string } type NamedXMLNSFieldStructWithEmptyNamespace struct { XMLName struct{} `xml:"test"` Ns string `xml:"xmlns,attr"` Body string } type RecursiveXMLNSFieldStruct struct { Ns string `xml:"xmlns,attr"` Body *RecursiveXMLNSFieldStruct `xml:",omitempty"` Text string `xml:",omitempty"` } func ifaceptr(x interface{}) interface{} { return &x } var ( nameAttr = "Sarah" ageAttr = uint(12) contentsAttr = "lorem ipsum" ) // Unless explicitly stated as such (or *Plain), all of the // tests below are two-way tests. When introducing new tests, // please try to make them two-way as well to ensure that // marshalling and unmarshalling are as symmetrical as feasible. var marshalTests = []struct { Value interface{} ExpectXML string MarshalOnly bool UnmarshalOnly bool }{ // Test nil marshals to nothing {Value: nil, ExpectXML: ``, MarshalOnly: true}, {Value: nilStruct, ExpectXML: ``, MarshalOnly: true}, // Test value types {Value: &Plain{true}, ExpectXML: `true`}, {Value: &Plain{false}, ExpectXML: `false`}, {Value: &Plain{int(42)}, ExpectXML: `42`}, {Value: &Plain{int8(42)}, ExpectXML: `42`}, {Value: &Plain{int16(42)}, ExpectXML: `42`}, {Value: &Plain{int32(42)}, ExpectXML: `42`}, {Value: &Plain{uint(42)}, ExpectXML: `42`}, {Value: &Plain{uint8(42)}, ExpectXML: `42`}, {Value: &Plain{uint16(42)}, ExpectXML: `42`}, {Value: &Plain{uint32(42)}, ExpectXML: `42`}, {Value: &Plain{float32(1.25)}, ExpectXML: `1.25`}, {Value: &Plain{float64(1.25)}, ExpectXML: `1.25`}, {Value: &Plain{uintptr(0xFFDD)}, ExpectXML: `65501`}, {Value: &Plain{"gopher"}, ExpectXML: `gopher`}, {Value: &Plain{[]byte("gopher")}, ExpectXML: `gopher`}, {Value: &Plain{""}, ExpectXML: `</>`}, {Value: &Plain{[]byte("")}, ExpectXML: `</>`}, {Value: &Plain{[3]byte{'<', '/', '>'}}, ExpectXML: `</>`}, {Value: &Plain{NamedType("potato")}, ExpectXML: `potato`}, {Value: &Plain{[]int{1, 2, 3}}, ExpectXML: `123`}, {Value: &Plain{[3]int{1, 2, 3}}, ExpectXML: `123`}, {Value: ifaceptr(true), MarshalOnly: true, ExpectXML: `true`}, // Test time. { Value: &Plain{time.Unix(1e9, 123456789).UTC()}, ExpectXML: `2001-09-09T01:46:40.123456789Z`, }, // A pointer to struct{} may be used to test for an element's presence. { Value: &PresenceTest{new(struct{})}, ExpectXML: ``, }, { Value: &PresenceTest{}, ExpectXML: ``, }, // A pointer to struct{} may be used to test for an element's presence. { Value: &PresenceTest{new(struct{})}, ExpectXML: ``, }, { Value: &PresenceTest{}, ExpectXML: ``, }, // A []byte field is only nil if the element was not found. { Value: &Data{}, ExpectXML: ``, UnmarshalOnly: true, }, { Value: &Data{Bytes: []byte{}, Custom: MyBytes{}, Attr: []byte{}}, ExpectXML: ``, UnmarshalOnly: true, }, // Check that []byte works, including named []byte types. { Value: &Data{Bytes: []byte("ab"), Custom: MyBytes("cd"), Attr: []byte{'v'}}, ExpectXML: `abcd`, }, // Test innerxml { Value: &SecretAgent{ Handle: "007", Identity: "James Bond", Obfuscate: "", }, ExpectXML: `James Bond`, MarshalOnly: true, }, { Value: &SecretAgent{ Handle: "007", Identity: "James Bond", Obfuscate: "James Bond", }, ExpectXML: `James Bond`, UnmarshalOnly: true, }, // Test structs {Value: &Port{Type: "ssl", Number: "443"}, ExpectXML: `443`}, {Value: &Port{Number: "443"}, ExpectXML: `443`}, {Value: &Port{Type: ""}, ExpectXML: ``}, {Value: &Port{Number: "443", Comment: "https"}, ExpectXML: `443`}, {Value: &Port{Number: "443", Comment: "add space-"}, ExpectXML: `443`, MarshalOnly: true}, {Value: &Domain{Name: []byte("google.com&friends")}, ExpectXML: `google.com&friends`}, {Value: &Domain{Name: []byte("google.com"), Comment: []byte(" &friends ")}, ExpectXML: `google.com`}, {Value: &Book{Title: "Pride & Prejudice"}, ExpectXML: `Pride & Prejudice`}, {Value: &Event{Year: -3114}, ExpectXML: `-3114`}, {Value: &Movie{Length: 13440}, ExpectXML: `13440`}, {Value: &Pi{Approximation: 3.14159265}, ExpectXML: `3.1415927`}, {Value: &Universe{Visible: 9.3e13}, ExpectXML: `9.3e+13`}, {Value: &Particle{HasMass: true}, ExpectXML: `true`}, {Value: &Departure{When: ParseTime("2013-01-09T00:15:00-09:00")}, ExpectXML: `2013-01-09T00:15:00-09:00`}, {Value: atomValue, ExpectXML: atomXml}, { Value: &Ship{ Name: "Heart of Gold", Pilot: "Computer", Age: 1, Drive: ImprobabilityDrive, Passenger: []*Passenger{ { Name: []string{"Zaphod", "Beeblebrox"}, Weight: 7.25, }, { Name: []string{"Trisha", "McMillen"}, Weight: 5.5, }, { Name: []string{"Ford", "Prefect"}, Weight: 7, }, { Name: []string{"Arthur", "Dent"}, Weight: 6.75, }, }, }, ExpectXML: `` + `` + strconv.Itoa(int(ImprobabilityDrive)) + `` + `1` + `` + `Zaphod` + `Beeblebrox` + `7.25` + `` + `` + `Trisha` + `McMillen` + `5.5` + `` + `` + `Ford` + `Prefect` + `7` + `` + `` + `Arthur` + `Dent` + `6.75` + `` + ``, }, // Test a>b { Value: &NestedItems{Items: nil, Item1: nil}, ExpectXML: `` + `` + `` + ``, }, { Value: &NestedItems{Items: []string{}, Item1: []string{}}, ExpectXML: `` + `` + `` + ``, MarshalOnly: true, }, { Value: &NestedItems{Items: nil, Item1: []string{"A"}}, ExpectXML: `` + `` + `A` + `` + ``, }, { Value: &NestedItems{Items: []string{"A", "B"}, Item1: nil}, ExpectXML: `` + `` + `A` + `B` + `` + ``, }, { Value: &NestedItems{Items: []string{"A", "B"}, Item1: []string{"C"}}, ExpectXML: `` + `` + `A` + `B` + `C` + `` + ``, }, { Value: &NestedOrder{Field1: "C", Field2: "B", Field3: "A"}, ExpectXML: `` + `` + `C` + `B` + `A` + `` + ``, }, { Value: &NilTest{A: "A", B: nil, C: "C"}, ExpectXML: `` + `` + `A` + `C` + `` + ``, MarshalOnly: true, // Uses interface{} }, { Value: &MixedNested{A: "A", B: "B", C: "C", D: "D"}, ExpectXML: `` + `A` + `B` + `` + `C` + `D` + `` + ``, }, { Value: &Service{Port: &Port{Number: "80"}}, ExpectXML: `80`, }, { Value: &Service{}, ExpectXML: ``, }, { Value: &Service{Port: &Port{Number: "80"}, Extra1: "A", Extra2: "B"}, ExpectXML: `` + `80` + `A` + `B` + ``, MarshalOnly: true, }, { Value: &Service{Port: &Port{Number: "80"}, Extra2: "example"}, ExpectXML: `` + `80` + `example` + ``, MarshalOnly: true, }, { Value: &struct { XMLName struct{} `xml:"space top"` A string `xml:"x>a"` B string `xml:"x>b"` C string `xml:"space x>c"` C1 string `xml:"space1 x>c"` D1 string `xml:"space1 x>d"` E1 string `xml:"x>e"` }{ A: "a", B: "b", C: "c", C1: "c1", D1: "d1", E1: "e1", }, ExpectXML: `` + `abc` + `` + `c1` + `d1` + `` + `` + `e1` + `` + ``, }, { Value: &struct { XMLName Name A string `xml:"x>a"` B string `xml:"x>b"` C string `xml:"space x>c"` C1 string `xml:"space1 x>c"` D1 string `xml:"space1 x>d"` }{ XMLName: Name{ Space: "space0", Local: "top", }, A: "a", B: "b", C: "c", C1: "c1", D1: "d1", }, ExpectXML: `` + `ab` + `c` + `` + `c1` + `d1` + `` + ``, }, { Value: &struct { XMLName struct{} `xml:"top"` B string `xml:"space x>b"` B1 string `xml:"space1 x>b"` }{ B: "b", B1: "b1", }, ExpectXML: `` + `b` + `b1` + ``, }, // Test struct embedding { Value: &EmbedA{ EmbedC: EmbedC{ FieldA1: "", // Shadowed by A.A FieldA2: "", // Shadowed by A.A FieldB: "A.C.B", FieldC: "A.C.C", }, EmbedB: EmbedB{ FieldB: "A.B.B", EmbedC: &EmbedC{ FieldA1: "A.B.C.A1", FieldA2: "A.B.C.A2", FieldB: "", // Shadowed by A.B.B FieldC: "A.B.C.C", }, }, FieldA: "A.A", }, ExpectXML: `` + `A.C.B` + `A.C.C` + `` + `A.B.B` + `` + `A.B.C.A1` + `A.B.C.A2` + `` + `A.B.C.C` + `` + `A.A` + ``, }, // Test that name casing matters { Value: &NameCasing{Xy: "mixed", XY: "upper", XyA: "mixedA", XYA: "upperA"}, ExpectXML: `mixedupper`, }, // Test the order in which the XML element name is chosen { Value: &NamePrecedence{ FromTag: XMLNameWithoutTag{Value: "A"}, FromNameVal: XMLNameWithoutTag{XMLName: Name{Local: "InXMLName"}, Value: "B"}, FromNameTag: XMLNameWithTag{Value: "C"}, InFieldName: "D", }, ExpectXML: `` + `A` + `B` + `C` + `D` + ``, MarshalOnly: true, }, { Value: &NamePrecedence{ XMLName: Name{Local: "Parent"}, FromTag: XMLNameWithoutTag{XMLName: Name{Local: "InTag"}, Value: "A"}, FromNameVal: XMLNameWithoutTag{XMLName: Name{Local: "FromNameVal"}, Value: "B"}, FromNameTag: XMLNameWithTag{XMLName: Name{Local: "InXMLNameTag"}, Value: "C"}, InFieldName: "D", }, ExpectXML: `` + `A` + `B` + `C` + `D` + ``, UnmarshalOnly: true, }, // xml.Name works in a plain field as well. { Value: &NameInField{Name{Space: "ns", Local: "foo"}}, ExpectXML: ``, }, { Value: &NameInField{Name{Space: "ns", Local: "foo"}}, ExpectXML: ``, UnmarshalOnly: true, }, // Marshaling zero xml.Name uses the tag or field name. { Value: &NameInField{}, ExpectXML: ``, MarshalOnly: true, }, // Test attributes { Value: &AttrTest{ Int: 8, Named: 9, Float: 23.5, Uint8: 255, Bool: true, Str: "str", Bytes: []byte("byt"), }, ExpectXML: ``, }, { Value: &AttrTest{Bytes: []byte{}}, ExpectXML: ``, }, { Value: &OmitAttrTest{ Int: 8, Named: 9, Float: 23.5, Uint8: 255, Bool: true, Str: "str", Bytes: []byte("byt"), }, ExpectXML: ``, }, { Value: &OmitAttrTest{}, ExpectXML: ``, }, // pointer fields { Value: &PointerFieldsTest{Name: &nameAttr, Age: &ageAttr, Contents: &contentsAttr}, ExpectXML: `lorem ipsum`, MarshalOnly: true, }, // empty chardata pointer field { Value: &ChardataEmptyTest{}, ExpectXML: ``, MarshalOnly: true, }, // omitempty on fields { Value: &OmitFieldTest{ Int: 8, Named: 9, Float: 23.5, Uint8: 255, Bool: true, Str: "str", Bytes: []byte("byt"), Ptr: &PresenceTest{}, }, ExpectXML: `` + `8` + `9` + `23.5` + `255` + `true` + `str` + `byt` + `` + ``, }, { Value: &OmitFieldTest{}, ExpectXML: ``, }, // Test ",any" { ExpectXML: `knownunknown`, Value: &AnyTest{ Nested: "known", AnyField: AnyHolder{ XMLName: Name{Local: "other"}, XML: "unknown", }, }, }, { Value: &AnyTest{Nested: "known", AnyField: AnyHolder{ XML: "", XMLName: Name{Local: "AnyField"}, }, }, ExpectXML: `known`, }, { ExpectXML: `b`, Value: &AnyOmitTest{ Nested: "b", }, }, { ExpectXML: `bei`, Value: &AnySliceTest{ Nested: "b", AnyField: []AnyHolder{ { XMLName: Name{Local: "c"}, XML: "e", }, { XMLName: Name{Space: "f", Local: "g"}, XML: "i", }, }, }, }, { ExpectXML: `b`, Value: &AnySliceTest{ Nested: "b", }, }, // Test recursive types. { Value: &RecurseA{ A: "a1", B: &RecurseB{ A: &RecurseA{"a2", nil}, B: "b1", }, }, ExpectXML: `a1a2b1`, }, // Test ignoring fields via "-" tag { ExpectXML: ``, Value: &IgnoreTest{}, }, { ExpectXML: ``, Value: &IgnoreTest{PublicSecret: "can't tell"}, MarshalOnly: true, }, { ExpectXML: `ignore me`, Value: &IgnoreTest{}, UnmarshalOnly: true, }, // Test escaping. { ExpectXML: `dquote: "; squote: '; ampersand: &; less: <; greater: >;`, Value: &AnyTest{ Nested: `dquote: "; squote: '; ampersand: &; less: <; greater: >;`, AnyField: AnyHolder{XMLName: Name{Local: "empty"}}, }, }, { ExpectXML: `newline: ; cr: ; tab: ;`, Value: &AnyTest{ Nested: "newline: \n; cr: \r; tab: \t;", AnyField: AnyHolder{XMLName: Name{Local: "AnyField"}}, }, }, { ExpectXML: "1\r2\r\n3\n\r4\n5", Value: &AnyTest{ Nested: "1\n2\n3\n\n4\n5", }, UnmarshalOnly: true, }, { ExpectXML: `42`, Value: &EmbedInt{ MyInt: 42, }, }, // Test omitempty with parent chain; see golang.org/issue/4168. { ExpectXML: ``, Value: &Strings{}, }, // Custom marshalers. { ExpectXML: `hello world`, Value: &MyMarshalerTest{}, }, { ExpectXML: ``, Value: &MarshalerStruct{}, }, { ExpectXML: ``, Value: &MarshalerValueStruct{}, }, { ExpectXML: ``, Value: &OuterStruct{IntAttr: 10}, }, { ExpectXML: ``, Value: &OuterNamedStruct{XMLName: Name{Space: "outerns", Local: "test"}, IntAttr: 10}, }, { ExpectXML: ``, Value: &OuterNamedOrderedStruct{XMLName: Name{Space: "outerns", Local: "test"}, IntAttr: 10}, }, { ExpectXML: ``, Value: &OuterOuterStruct{OuterStruct{IntAttr: 10}}, }, { ExpectXML: `test`, Value: &NestedAndChardata{AB: make([]string, 2), Chardata: "test"}, }, { ExpectXML: ``, Value: &NestedAndComment{AB: make([]string, 2), Comment: "test"}, }, { ExpectXML: `hello world`, Value: &XMLNSFieldStruct{Ns: "http://example.com/ns", Body: "hello world"}, }, { ExpectXML: `hello world`, Value: &NamedXMLNSFieldStruct{Ns: "http://example.com/ns", Body: "hello world"}, }, { ExpectXML: `hello world`, Value: &NamedXMLNSFieldStruct{Ns: "", Body: "hello world"}, }, { ExpectXML: `hello world`, Value: &XMLNSFieldStructWithOmitEmpty{Body: "hello world"}, }, { // The xmlns attribute must be ignored because the // element is in the empty namespace, so it's not possible // to set the default namespace to something non-empty. ExpectXML: `hello world`, Value: &NamedXMLNSFieldStructWithEmptyNamespace{Ns: "foo", Body: "hello world"}, MarshalOnly: true, }, { ExpectXML: `hello world`, Value: &RecursiveXMLNSFieldStruct{ Ns: "foo", Body: &RecursiveXMLNSFieldStruct{ Text: "hello world", }, }, }, } func TestMarshal(t *testing.T) { for idx, test := range marshalTests { if test.UnmarshalOnly { continue } data, err := Marshal(test.Value) if err != nil { t.Errorf("#%d: marshal(%#v): %s", idx, test.Value, err) continue } if got, want := string(data), test.ExpectXML; got != want { if strings.Contains(want, "\n") { t.Errorf("#%d: marshal(%#v):\nHAVE:\n%s\nWANT:\n%s", idx, test.Value, got, want) } else { t.Errorf("#%d: marshal(%#v):\nhave %#q\nwant %#q", idx, test.Value, got, want) } } } } type AttrParent struct { X string `xml:"X>Y,attr"` } type BadAttr struct { Name []string `xml:"name,attr"` } var marshalErrorTests = []struct { Value interface{} Err string Kind reflect.Kind }{ { Value: make(chan bool), Err: "xml: unsupported type: chan bool", Kind: reflect.Chan, }, { Value: map[string]string{ "question": "What do you get when you multiply six by nine?", "answer": "42", }, Err: "xml: unsupported type: map[string]string", Kind: reflect.Map, }, { Value: map[*Ship]bool{nil: false}, Err: "xml: unsupported type: map[*xml.Ship]bool", Kind: reflect.Map, }, { Value: &Domain{Comment: []byte("f--bar")}, Err: `xml: comments must not contain "--"`, }, // Reject parent chain with attr, never worked; see golang.org/issue/5033. { Value: &AttrParent{}, Err: `xml: X>Y chain not valid with attr flag`, }, { Value: BadAttr{[]string{"X", "Y"}}, Err: `xml: unsupported type: []string`, }, } var marshalIndentTests = []struct { Value interface{} Prefix string Indent string ExpectXML string }{ { Value: &SecretAgent{ Handle: "007", Identity: "James Bond", Obfuscate: "", }, Prefix: "", Indent: "\t", ExpectXML: fmt.Sprintf("\n\tJames Bond\n"), }, } func TestMarshalErrors(t *testing.T) { for idx, test := range marshalErrorTests { data, err := Marshal(test.Value) if err == nil { t.Errorf("#%d: marshal(%#v) = [success] %q, want error %v", idx, test.Value, data, test.Err) continue } if err.Error() != test.Err { t.Errorf("#%d: marshal(%#v) = [error] %v, want %v", idx, test.Value, err, test.Err) } if test.Kind != reflect.Invalid { if kind := err.(*UnsupportedTypeError).Type.Kind(); kind != test.Kind { t.Errorf("#%d: marshal(%#v) = [error kind] %s, want %s", idx, test.Value, kind, test.Kind) } } } } // Do invertibility testing on the various structures that we test func TestUnmarshal(t *testing.T) { for i, test := range marshalTests { if test.MarshalOnly { continue } if _, ok := test.Value.(*Plain); ok { continue } vt := reflect.TypeOf(test.Value) dest := reflect.New(vt.Elem()).Interface() err := Unmarshal([]byte(test.ExpectXML), dest) switch fix := dest.(type) { case *Feed: fix.Author.InnerXML = "" for i := range fix.Entry { fix.Entry[i].Author.InnerXML = "" } } if err != nil { t.Errorf("#%d: unexpected error: %#v", i, err) } else if got, want := dest, test.Value; !reflect.DeepEqual(got, want) { t.Errorf("#%d: unmarshal(%q):\nhave %#v\nwant %#v", i, test.ExpectXML, got, want) } } } func TestMarshalIndent(t *testing.T) { for i, test := range marshalIndentTests { data, err := MarshalIndent(test.Value, test.Prefix, test.Indent) if err != nil { t.Errorf("#%d: Error: %s", i, err) continue } if got, want := string(data), test.ExpectXML; got != want { t.Errorf("#%d: MarshalIndent:\nGot:%s\nWant:\n%s", i, got, want) } } } type limitedBytesWriter struct { w io.Writer remain int // until writes fail } func (lw *limitedBytesWriter) Write(p []byte) (n int, err error) { if lw.remain <= 0 { println("error") return 0, errors.New("write limit hit") } if len(p) > lw.remain { p = p[:lw.remain] n, _ = lw.w.Write(p) lw.remain = 0 return n, errors.New("write limit hit") } n, err = lw.w.Write(p) lw.remain -= n return n, err } func TestMarshalWriteErrors(t *testing.T) { var buf bytes.Buffer const writeCap = 1024 w := &limitedBytesWriter{&buf, writeCap} enc := NewEncoder(w) var err error var i int const n = 4000 for i = 1; i <= n; i++ { err = enc.Encode(&Passenger{ Name: []string{"Alice", "Bob"}, Weight: 5, }) if err != nil { break } } if err == nil { t.Error("expected an error") } if i == n { t.Errorf("expected to fail before the end") } if buf.Len() != writeCap { t.Errorf("buf.Len() = %d; want %d", buf.Len(), writeCap) } } func TestMarshalWriteIOErrors(t *testing.T) { enc := NewEncoder(errWriter{}) expectErr := "unwritable" err := enc.Encode(&Passenger{}) if err == nil || err.Error() != expectErr { t.Errorf("EscapeTest = [error] %v, want %v", err, expectErr) } } func TestMarshalFlush(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) if err := enc.EncodeToken(CharData("hello world")); err != nil { t.Fatalf("enc.EncodeToken: %v", err) } if buf.Len() > 0 { t.Fatalf("enc.EncodeToken caused actual write: %q", buf.Bytes()) } if err := enc.Flush(); err != nil { t.Fatalf("enc.Flush: %v", err) } if buf.String() != "hello world" { t.Fatalf("after enc.Flush, buf.String() = %q, want %q", buf.String(), "hello world") } } var encodeElementTests = []struct { desc string value interface{} start StartElement expectXML string }{{ desc: "simple string", value: "hello", start: StartElement{ Name: Name{Local: "a"}, }, expectXML: `hello`, }, { desc: "string with added attributes", value: "hello", start: StartElement{ Name: Name{Local: "a"}, Attr: []Attr{{ Name: Name{Local: "x"}, Value: "y", }, { Name: Name{Local: "foo"}, Value: "bar", }}, }, expectXML: `hello`, }, { desc: "start element with default name space", value: struct { Foo XMLNameWithNSTag }{ Foo: XMLNameWithNSTag{ Value: "hello", }, }, start: StartElement{ Name: Name{Space: "ns", Local: "a"}, Attr: []Attr{{ Name: Name{Local: "xmlns"}, // "ns" is the name space defined in XMLNameWithNSTag Value: "ns", }}, }, expectXML: `hello`, }, { desc: "start element in name space with different default name space", value: struct { Foo XMLNameWithNSTag }{ Foo: XMLNameWithNSTag{ Value: "hello", }, }, start: StartElement{ Name: Name{Space: "ns2", Local: "a"}, Attr: []Attr{{ Name: Name{Local: "xmlns"}, // "ns" is the name space defined in XMLNameWithNSTag Value: "ns", }}, }, expectXML: `hello`, }, { desc: "XMLMarshaler with start element with default name space", value: &MyMarshalerTest{}, start: StartElement{ Name: Name{Space: "ns2", Local: "a"}, Attr: []Attr{{ Name: Name{Local: "xmlns"}, // "ns" is the name space defined in XMLNameWithNSTag Value: "ns", }}, }, expectXML: `hello world`, }} func TestEncodeElement(t *testing.T) { for idx, test := range encodeElementTests { var buf bytes.Buffer enc := NewEncoder(&buf) err := enc.EncodeElement(test.value, test.start) if err != nil { t.Fatalf("enc.EncodeElement: %v", err) } err = enc.Flush() if err != nil { t.Fatalf("enc.Flush: %v", err) } if got, want := buf.String(), test.expectXML; got != want { t.Errorf("#%d(%s): EncodeElement(%#v, %#v):\nhave %#q\nwant %#q", idx, test.desc, test.value, test.start, got, want) } } } func BenchmarkMarshal(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { Marshal(atomValue) } } func BenchmarkUnmarshal(b *testing.B) { b.ReportAllocs() xml := []byte(atomXml) for i := 0; i < b.N; i++ { Unmarshal(xml, &Feed{}) } } // golang.org/issue/6556 func TestStructPointerMarshal(t *testing.T) { type A struct { XMLName string `xml:"a"` B []interface{} } type C struct { XMLName Name Value string `xml:"value"` } a := new(A) a.B = append(a.B, &C{ XMLName: Name{Local: "c"}, Value: "x", }) b, err := Marshal(a) if err != nil { t.Fatal(err) } if x := string(b); x != "x" { t.Fatal(x) } var v A err = Unmarshal(b, &v) if err != nil { t.Fatal(err) } } var encodeTokenTests = []struct { desc string toks []Token want string err string }{{ desc: "start element with name space", toks: []Token{ StartElement{Name{"space", "local"}, nil}, }, want: ``, }, { desc: "start element with no name", toks: []Token{ StartElement{Name{"space", ""}, nil}, }, err: "xml: start tag with no name", }, { desc: "end element with no name", toks: []Token{ EndElement{Name{"space", ""}}, }, err: "xml: end tag with no name", }, { desc: "char data", toks: []Token{ CharData("foo"), }, want: `foo`, }, { desc: "char data with escaped chars", toks: []Token{ CharData(" \t\n"), }, want: " \n", }, { desc: "comment", toks: []Token{ Comment("foo"), }, want: ``, }, { desc: "comment with invalid content", toks: []Token{ Comment("foo-->"), }, err: "xml: EncodeToken of Comment containing --> marker", }, { desc: "proc instruction", toks: []Token{ ProcInst{"Target", []byte("Instruction")}, }, want: ``, }, { desc: "proc instruction with empty target", toks: []Token{ ProcInst{"", []byte("Instruction")}, }, err: "xml: EncodeToken of ProcInst with invalid Target", }, { desc: "proc instruction with bad content", toks: []Token{ ProcInst{"", []byte("Instruction?>")}, }, err: "xml: EncodeToken of ProcInst with invalid Target", }, { desc: "directive", toks: []Token{ Directive("foo"), }, want: ``, }, { desc: "more complex directive", toks: []Token{ Directive("DOCTYPE doc [ '> ]"), }, want: `'> ]>`, }, { desc: "directive instruction with bad name", toks: []Token{ Directive("foo>"), }, err: "xml: EncodeToken of Directive containing wrong < or > markers", }, { desc: "end tag without start tag", toks: []Token{ EndElement{Name{"foo", "bar"}}, }, err: "xml: end tag without start tag", }, { desc: "mismatching end tag local name", toks: []Token{ StartElement{Name{"", "foo"}, nil}, EndElement{Name{"", "bar"}}, }, err: "xml: end tag does not match start tag ", want: ``, }, { desc: "mismatching end tag namespace", toks: []Token{ StartElement{Name{"space", "foo"}, nil}, EndElement{Name{"another", "foo"}}, }, err: "xml: end tag in namespace another does not match start tag in namespace space", want: ``, }, { desc: "start element with explicit namespace", toks: []Token{ StartElement{Name{"space", "local"}, []Attr{ {Name{"xmlns", "x"}, "space"}, {Name{"space", "foo"}, "value"}, }}, }, want: ``, }, { desc: "start element with explicit namespace and colliding prefix", toks: []Token{ StartElement{Name{"space", "local"}, []Attr{ {Name{"xmlns", "x"}, "space"}, {Name{"space", "foo"}, "value"}, {Name{"x", "bar"}, "other"}, }}, }, want: ``, }, { desc: "start element using previously defined namespace", toks: []Token{ StartElement{Name{"", "local"}, []Attr{ {Name{"xmlns", "x"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"space", "x"}, "y"}, }}, }, want: ``, }, { desc: "nested name space with same prefix", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space1"}, }}, StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space2"}, }}, StartElement{Name{"", "foo"}, []Attr{ {Name{"space1", "a"}, "space1 value"}, {Name{"space2", "b"}, "space2 value"}, }}, EndElement{Name{"", "foo"}}, EndElement{Name{"", "foo"}}, StartElement{Name{"", "foo"}, []Attr{ {Name{"space1", "a"}, "space1 value"}, {Name{"space2", "b"}, "space2 value"}, }}, }, want: ``, }, { desc: "start element defining several prefixes for the same name space", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"xmlns", "a"}, "space"}, {Name{"xmlns", "b"}, "space"}, {Name{"space", "x"}, "value"}, }}, }, want: ``, }, { desc: "nested element redefines name space", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"xmlns", "y"}, "space"}, {Name{"space", "a"}, "value"}, }}, }, want: ``, }, { desc: "nested element creates alias for default name space", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"xmlns", "y"}, "space"}, {Name{"space", "a"}, "value"}, }}, }, want: ``, }, { desc: "nested element defines default name space with existing prefix", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "x"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, {Name{"space", "a"}, "value"}, }}, }, want: ``, }, { desc: "nested element uses empty attribute name space when default ns defined", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "attr"}, "value"}, }}, }, want: ``, }, { desc: "redefine xmlns", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"foo", "xmlns"}, "space"}, }}, }, err: `xml: cannot redefine xmlns attribute prefix`, }, { desc: "xmlns with explicit name space #1", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"xml", "xmlns"}, "space"}, }}, }, want: ``, }, { desc: "xmlns with explicit name space #2", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{xmlURL, "xmlns"}, "space"}, }}, }, want: ``, }, { desc: "empty name space declaration is ignored", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"xmlns", "foo"}, ""}, }}, }, want: ``, }, { desc: "attribute with no name is ignored", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"", ""}, "value"}, }}, }, want: ``, }, { desc: "namespace URL with non-valid name", toks: []Token{ StartElement{Name{"/34", "foo"}, []Attr{ {Name{"/34", "x"}, "value"}, }}, }, want: `<_:foo xmlns:_="/34" _:x="value">`, }, { desc: "nested element resets default namespace to empty", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"", "foo"}, []Attr{ {Name{"", "xmlns"}, ""}, {Name{"", "x"}, "value"}, {Name{"space", "x"}, "value"}, }}, }, want: ``, }, { desc: "nested element requires empty default name space", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"", "foo"}, nil}, }, want: ``, }, { desc: "attribute uses name space from xmlns", toks: []Token{ StartElement{Name{"some/space", "foo"}, []Attr{ {Name{"", "attr"}, "value"}, {Name{"some/space", "other"}, "other value"}, }}, }, want: ``, }, { desc: "default name space should not be used by attributes", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, {Name{"xmlns", "bar"}, "space"}, {Name{"space", "baz"}, "foo"}, }}, StartElement{Name{"space", "baz"}, nil}, EndElement{Name{"space", "baz"}}, EndElement{Name{"space", "foo"}}, }, want: ``, }, { desc: "default name space not used by attributes, not explicitly defined", toks: []Token{ StartElement{Name{"space", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, {Name{"space", "baz"}, "foo"}, }}, StartElement{Name{"space", "baz"}, nil}, EndElement{Name{"space", "baz"}}, EndElement{Name{"space", "foo"}}, }, want: ``, }, { desc: "impossible xmlns declaration", toks: []Token{ StartElement{Name{"", "foo"}, []Attr{ {Name{"", "xmlns"}, "space"}, }}, StartElement{Name{"space", "bar"}, []Attr{ {Name{"space", "attr"}, "value"}, }}, }, want: ``, }} func TestEncodeToken(t *testing.T) { loop: for i, tt := range encodeTokenTests { var buf bytes.Buffer enc := NewEncoder(&buf) var err error for j, tok := range tt.toks { err = enc.EncodeToken(tok) if err != nil && j < len(tt.toks)-1 { t.Errorf("#%d %s token #%d: %v", i, tt.desc, j, err) continue loop } } errorf := func(f string, a ...interface{}) { t.Errorf("#%d %s token #%d:%s", i, tt.desc, len(tt.toks)-1, fmt.Sprintf(f, a...)) } switch { case tt.err != "" && err == nil: errorf(" expected error; got none") continue case tt.err == "" && err != nil: errorf(" got error: %v", err) continue case tt.err != "" && err != nil && tt.err != err.Error(): errorf(" error mismatch; got %v, want %v", err, tt.err) continue } if err := enc.Flush(); err != nil { errorf(" %v", err) continue } if got := buf.String(); got != tt.want { errorf("\ngot %v\nwant %v", got, tt.want) continue } } } func TestProcInstEncodeToken(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) if err := enc.EncodeToken(ProcInst{"xml", []byte("Instruction")}); err != nil { t.Fatalf("enc.EncodeToken: expected to be able to encode xml target ProcInst as first token, %s", err) } if err := enc.EncodeToken(ProcInst{"Target", []byte("Instruction")}); err != nil { t.Fatalf("enc.EncodeToken: expected to be able to add non-xml target ProcInst") } if err := enc.EncodeToken(ProcInst{"xml", []byte("Instruction")}); err == nil { t.Fatalf("enc.EncodeToken: expected to not be allowed to encode xml target ProcInst when not first token") } } func TestDecodeEncode(t *testing.T) { var in, out bytes.Buffer in.WriteString(` `) dec := NewDecoder(&in) enc := NewEncoder(&out) for tok, err := dec.Token(); err == nil; tok, err = dec.Token() { err = enc.EncodeToken(tok) if err != nil { t.Fatalf("enc.EncodeToken: Unable to encode token (%#v), %v", tok, err) } } } // Issue 9796. Used to fail with GORACE="halt_on_error=1" -race. func TestRace9796(t *testing.T) { type A struct{} type B struct { C []A `xml:"X>Y"` } var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { Marshal(B{[]A{A{}}}) wg.Done() }() } wg.Wait() } func TestIsValidDirective(t *testing.T) { testOK := []string{ "<>", "< < > >", "' '>' >", " ]>", " '<' ' doc ANY> ]>", ">>> a < comment --> [ ] >", } testKO := []string{ "<", ">", "", "< > > < < >", " -->", "", "'", "", } for _, s := range testOK { if !isValidDirective(Directive(s)) { t.Errorf("Directive %q is expected to be valid", s) } } for _, s := range testKO { if isValidDirective(Directive(s)) { t.Errorf("Directive %q is expected to be invalid", s) } } } // Issue 11719. EncodeToken used to silently eat tokens with an invalid type. func TestSimpleUseOfEncodeToken(t *testing.T) { var buf bytes.Buffer enc := NewEncoder(&buf) if err := enc.EncodeToken(&StartElement{Name: Name{"", "object1"}}); err == nil { t.Errorf("enc.EncodeToken: pointer type should be rejected") } if err := enc.EncodeToken(&EndElement{Name: Name{"", "object1"}}); err == nil { t.Errorf("enc.EncodeToken: pointer type should be rejected") } if err := enc.EncodeToken(StartElement{Name: Name{"", "object2"}}); err != nil { t.Errorf("enc.EncodeToken: StartElement %s", err) } if err := enc.EncodeToken(EndElement{Name: Name{"", "object2"}}); err != nil { t.Errorf("enc.EncodeToken: EndElement %s", err) } if err := enc.EncodeToken(Universe{}); err == nil { t.Errorf("enc.EncodeToken: invalid type not caught") } if err := enc.Flush(); err != nil { t.Errorf("enc.Flush: %s", err) } if buf.Len() == 0 { t.Errorf("enc.EncodeToken: empty buffer") } want := "" if buf.String() != want { t.Errorf("enc.EncodeToken: expected %q; got %q", want, buf.String()) } } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/read.go ================================================ // 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 xml import ( "bytes" "encoding" "errors" "fmt" "reflect" "strconv" "strings" ) // BUG(rsc): Mapping between XML elements and data structures is inherently flawed: // an XML element is an order-dependent collection of anonymous // values, while a data structure is an order-independent collection // of named values. // See package json for a textual representation more suitable // to data structures. // Unmarshal parses the XML-encoded data and stores the result in // the value pointed to by v, which must be an arbitrary struct, // slice, or string. Well-formed data that does not fit into v is // discarded. // // Because Unmarshal uses the reflect package, it can only assign // to exported (upper case) fields. Unmarshal uses a case-sensitive // comparison to match XML element names to tag values and struct // field names. // // Unmarshal maps an XML element to a struct using the following rules. // In the rules, the tag of a field refers to the value associated with the // key 'xml' in the struct field's tag (see the example above). // // * If the struct has a field of type []byte or string with tag // ",innerxml", Unmarshal accumulates the raw XML nested inside the // element in that field. The rest of the rules still apply. // // * If the struct has a field named XMLName of type xml.Name, // Unmarshal records the element name in that field. // // * If the XMLName field has an associated tag of the form // "name" or "namespace-URL name", the XML element must have // the given name (and, optionally, name space) or else Unmarshal // returns an error. // // * If the XML element has an attribute whose name matches a // struct field name with an associated tag containing ",attr" or // the explicit name in a struct field tag of the form "name,attr", // Unmarshal records the attribute value in that field. // // * If the XML element contains character data, that data is // accumulated in the first struct field that has tag ",chardata". // The struct field may have type []byte or string. // If there is no such field, the character data is discarded. // // * If the XML element contains comments, they are accumulated in // the first struct field that has tag ",comment". The struct // field may have type []byte or string. If there is no such // field, the comments are discarded. // // * If the XML element contains a sub-element whose name matches // the prefix of a tag formatted as "a" or "a>b>c", unmarshal // will descend into the XML structure looking for elements with the // given names, and will map the innermost elements to that struct // field. A tag starting with ">" is equivalent to one starting // with the field name followed by ">". // // * If the XML element contains a sub-element whose name matches // a struct field's XMLName tag and the struct field has no // explicit name tag as per the previous rule, unmarshal maps // the sub-element to that struct field. // // * If the XML element contains a sub-element whose name matches a // field without any mode flags (",attr", ",chardata", etc), Unmarshal // maps the sub-element to that struct field. // // * If the XML element contains a sub-element that hasn't matched any // of the above rules and the struct has a field with tag ",any", // unmarshal maps the sub-element to that struct field. // // * An anonymous struct field is handled as if the fields of its // value were part of the outer struct. // // * A struct field with tag "-" is never unmarshalled into. // // Unmarshal maps an XML element to a string or []byte by saving the // concatenation of that element's character data in the string or // []byte. The saved []byte is never nil. // // Unmarshal maps an attribute value to a string or []byte by saving // the value in the string or slice. // // Unmarshal maps an XML element to a slice by extending the length of // the slice and mapping the element to the newly created value. // // Unmarshal maps an XML element or attribute value to a bool by // setting it to the boolean value represented by the string. // // Unmarshal maps an XML element or attribute value to an integer or // floating-point field by setting the field to the result of // interpreting the string value in decimal. There is no check for // overflow. // // Unmarshal maps an XML element to an xml.Name by recording the // element name. // // Unmarshal maps an XML element to a pointer by setting the pointer // to a freshly allocated value and then mapping the element to that value. // func Unmarshal(data []byte, v interface{}) error { return NewDecoder(bytes.NewReader(data)).Decode(v) } // Decode works like xml.Unmarshal, except it reads the decoder // stream to find the start element. func (d *Decoder) Decode(v interface{}) error { return d.DecodeElement(v, nil) } // DecodeElement works like xml.Unmarshal except that it takes // a pointer to the start XML element to decode into v. // It is useful when a client reads some raw XML tokens itself // but also wants to defer to Unmarshal for some elements. func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error { val := reflect.ValueOf(v) if val.Kind() != reflect.Ptr { return errors.New("non-pointer passed to Unmarshal") } return d.unmarshal(val.Elem(), start) } // An UnmarshalError represents an error in the unmarshalling process. type UnmarshalError string func (e UnmarshalError) Error() string { return string(e) } // Unmarshaler is the interface implemented by objects that can unmarshal // an XML element description of themselves. // // UnmarshalXML decodes a single XML element // beginning with the given start element. // If it returns an error, the outer call to Unmarshal stops and // returns that error. // UnmarshalXML must consume exactly one XML element. // One common implementation strategy is to unmarshal into // a separate value with a layout matching the expected XML // using d.DecodeElement, and then to copy the data from // that value into the receiver. // Another common strategy is to use d.Token to process the // XML object one token at a time. // UnmarshalXML may not use d.RawToken. type Unmarshaler interface { UnmarshalXML(d *Decoder, start StartElement) error } // UnmarshalerAttr is the interface implemented by objects that can unmarshal // an XML attribute description of themselves. // // UnmarshalXMLAttr decodes a single XML attribute. // If it returns an error, the outer call to Unmarshal stops and // returns that error. // UnmarshalXMLAttr is used only for struct fields with the // "attr" option in the field tag. type UnmarshalerAttr interface { UnmarshalXMLAttr(attr Attr) error } // receiverType returns the receiver type to use in an expression like "%s.MethodName". func receiverType(val interface{}) string { t := reflect.TypeOf(val) if t.Name() != "" { return t.String() } return "(" + t.String() + ")" } // unmarshalInterface unmarshals a single XML element into val. // start is the opening tag of the element. func (p *Decoder) unmarshalInterface(val Unmarshaler, start *StartElement) error { // Record that decoder must stop at end tag corresponding to start. p.pushEOF() p.unmarshalDepth++ err := val.UnmarshalXML(p, *start) p.unmarshalDepth-- if err != nil { p.popEOF() return err } if !p.popEOF() { return fmt.Errorf("xml: %s.UnmarshalXML did not consume entire <%s> element", receiverType(val), start.Name.Local) } return nil } // unmarshalTextInterface unmarshals a single XML element into val. // The chardata contained in the element (but not its children) // is passed to the text unmarshaler. func (p *Decoder) unmarshalTextInterface(val encoding.TextUnmarshaler, start *StartElement) error { var buf []byte depth := 1 for depth > 0 { t, err := p.Token() if err != nil { return err } switch t := t.(type) { case CharData: if depth == 1 { buf = append(buf, t...) } case StartElement: depth++ case EndElement: depth-- } } return val.UnmarshalText(buf) } // unmarshalAttr unmarshals a single XML attribute into val. func (p *Decoder) unmarshalAttr(val reflect.Value, attr Attr) error { if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } if val.CanInterface() && val.Type().Implements(unmarshalerAttrType) { // This is an unmarshaler with a non-pointer receiver, // so it's likely to be incorrect, but we do what we're told. return val.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(unmarshalerAttrType) { return pv.Interface().(UnmarshalerAttr).UnmarshalXMLAttr(attr) } } // Not an UnmarshalerAttr; try encoding.TextUnmarshaler. if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { // This is an unmarshaler with a non-pointer receiver, // so it's likely to be incorrect, but we do what we're told. return val.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value)) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { return pv.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(attr.Value)) } } copyValue(val, []byte(attr.Value)) return nil } var ( unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() unmarshalerAttrType = reflect.TypeOf((*UnmarshalerAttr)(nil)).Elem() textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() ) // Unmarshal a single XML element into val. func (p *Decoder) unmarshal(val reflect.Value, start *StartElement) error { // Find start element if we need it. if start == nil { for { tok, err := p.Token() if err != nil { return err } if t, ok := tok.(StartElement); ok { start = &t break } } } // Load value from interface, but only if the result will be // usefully addressable. if val.Kind() == reflect.Interface && !val.IsNil() { e := val.Elem() if e.Kind() == reflect.Ptr && !e.IsNil() { val = e } } if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } if val.CanInterface() && val.Type().Implements(unmarshalerType) { // This is an unmarshaler with a non-pointer receiver, // so it's likely to be incorrect, but we do what we're told. return p.unmarshalInterface(val.Interface().(Unmarshaler), start) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(unmarshalerType) { return p.unmarshalInterface(pv.Interface().(Unmarshaler), start) } } if val.CanInterface() && val.Type().Implements(textUnmarshalerType) { return p.unmarshalTextInterface(val.Interface().(encoding.TextUnmarshaler), start) } if val.CanAddr() { pv := val.Addr() if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { return p.unmarshalTextInterface(pv.Interface().(encoding.TextUnmarshaler), start) } } var ( data []byte saveData reflect.Value comment []byte saveComment reflect.Value saveXML reflect.Value saveXMLIndex int saveXMLData []byte saveAny reflect.Value sv reflect.Value tinfo *typeInfo err error ) switch v := val; v.Kind() { default: return errors.New("unknown type " + v.Type().String()) case reflect.Interface: // TODO: For now, simply ignore the field. In the near // future we may choose to unmarshal the start // element on it, if not nil. return p.Skip() case reflect.Slice: typ := v.Type() if typ.Elem().Kind() == reflect.Uint8 { // []byte saveData = v break } // Slice of element values. // Grow slice. n := v.Len() if n >= v.Cap() { ncap := 2 * n if ncap < 4 { ncap = 4 } new := reflect.MakeSlice(typ, n, ncap) reflect.Copy(new, v) v.Set(new) } v.SetLen(n + 1) // Recur to read element into slice. if err := p.unmarshal(v.Index(n), start); err != nil { v.SetLen(n) return err } return nil case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.String: saveData = v case reflect.Struct: typ := v.Type() if typ == nameType { v.Set(reflect.ValueOf(start.Name)) break } sv = v tinfo, err = getTypeInfo(typ) if err != nil { return err } // Validate and assign element name. if tinfo.xmlname != nil { finfo := tinfo.xmlname if finfo.name != "" && finfo.name != start.Name.Local { return UnmarshalError("expected element type <" + finfo.name + "> but have <" + start.Name.Local + ">") } if finfo.xmlns != "" && finfo.xmlns != start.Name.Space { e := "expected element <" + finfo.name + "> in name space " + finfo.xmlns + " but have " if start.Name.Space == "" { e += "no name space" } else { e += start.Name.Space } return UnmarshalError(e) } fv := finfo.value(sv) if _, ok := fv.Interface().(Name); ok { fv.Set(reflect.ValueOf(start.Name)) } } // Assign attributes. // Also, determine whether we need to save character data or comments. for i := range tinfo.fields { finfo := &tinfo.fields[i] switch finfo.flags & fMode { case fAttr: strv := finfo.value(sv) // Look for attribute. for _, a := range start.Attr { if a.Name.Local == finfo.name && (finfo.xmlns == "" || finfo.xmlns == a.Name.Space) { if err := p.unmarshalAttr(strv, a); err != nil { return err } break } } case fCharData: if !saveData.IsValid() { saveData = finfo.value(sv) } case fComment: if !saveComment.IsValid() { saveComment = finfo.value(sv) } case fAny, fAny | fElement: if !saveAny.IsValid() { saveAny = finfo.value(sv) } case fInnerXml: if !saveXML.IsValid() { saveXML = finfo.value(sv) if p.saved == nil { saveXMLIndex = 0 p.saved = new(bytes.Buffer) } else { saveXMLIndex = p.savedOffset() } } } } } // Find end element. // Process sub-elements along the way. Loop: for { var savedOffset int if saveXML.IsValid() { savedOffset = p.savedOffset() } tok, err := p.Token() if err != nil { return err } switch t := tok.(type) { case StartElement: consumed := false if sv.IsValid() { consumed, err = p.unmarshalPath(tinfo, sv, nil, &t) if err != nil { return err } if !consumed && saveAny.IsValid() { consumed = true if err := p.unmarshal(saveAny, &t); err != nil { return err } } } if !consumed { if err := p.Skip(); err != nil { return err } } case EndElement: if saveXML.IsValid() { saveXMLData = p.saved.Bytes()[saveXMLIndex:savedOffset] if saveXMLIndex == 0 { p.saved = nil } } break Loop case CharData: if saveData.IsValid() { data = append(data, t...) } case Comment: if saveComment.IsValid() { comment = append(comment, t...) } } } if saveData.IsValid() && saveData.CanInterface() && saveData.Type().Implements(textUnmarshalerType) { if err := saveData.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { return err } saveData = reflect.Value{} } if saveData.IsValid() && saveData.CanAddr() { pv := saveData.Addr() if pv.CanInterface() && pv.Type().Implements(textUnmarshalerType) { if err := pv.Interface().(encoding.TextUnmarshaler).UnmarshalText(data); err != nil { return err } saveData = reflect.Value{} } } if err := copyValue(saveData, data); err != nil { return err } switch t := saveComment; t.Kind() { case reflect.String: t.SetString(string(comment)) case reflect.Slice: t.Set(reflect.ValueOf(comment)) } switch t := saveXML; t.Kind() { case reflect.String: t.SetString(string(saveXMLData)) case reflect.Slice: t.Set(reflect.ValueOf(saveXMLData)) } return nil } func copyValue(dst reflect.Value, src []byte) (err error) { dst0 := dst if dst.Kind() == reflect.Ptr { if dst.IsNil() { dst.Set(reflect.New(dst.Type().Elem())) } dst = dst.Elem() } // Save accumulated data. switch dst.Kind() { case reflect.Invalid: // Probably a comment. default: return errors.New("cannot unmarshal into " + dst0.Type().String()) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: itmp, err := strconv.ParseInt(string(src), 10, dst.Type().Bits()) if err != nil { return err } dst.SetInt(itmp) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: utmp, err := strconv.ParseUint(string(src), 10, dst.Type().Bits()) if err != nil { return err } dst.SetUint(utmp) case reflect.Float32, reflect.Float64: ftmp, err := strconv.ParseFloat(string(src), dst.Type().Bits()) if err != nil { return err } dst.SetFloat(ftmp) case reflect.Bool: value, err := strconv.ParseBool(strings.TrimSpace(string(src))) if err != nil { return err } dst.SetBool(value) case reflect.String: dst.SetString(string(src)) case reflect.Slice: if len(src) == 0 { // non-nil to flag presence src = []byte{} } dst.SetBytes(src) } return nil } // unmarshalPath walks down an XML structure looking for wanted // paths, and calls unmarshal on them. // The consumed result tells whether XML elements have been consumed // from the Decoder until start's matching end element, or if it's // still untouched because start is uninteresting for sv's fields. func (p *Decoder) unmarshalPath(tinfo *typeInfo, sv reflect.Value, parents []string, start *StartElement) (consumed bool, err error) { recurse := false Loop: for i := range tinfo.fields { finfo := &tinfo.fields[i] if finfo.flags&fElement == 0 || len(finfo.parents) < len(parents) || finfo.xmlns != "" && finfo.xmlns != start.Name.Space { continue } for j := range parents { if parents[j] != finfo.parents[j] { continue Loop } } if len(finfo.parents) == len(parents) && finfo.name == start.Name.Local { // It's a perfect match, unmarshal the field. return true, p.unmarshal(finfo.value(sv), start) } if len(finfo.parents) > len(parents) && finfo.parents[len(parents)] == start.Name.Local { // It's a prefix for the field. Break and recurse // since it's not ok for one field path to be itself // the prefix for another field path. recurse = true // We can reuse the same slice as long as we // don't try to append to it. parents = finfo.parents[:len(parents)+1] break } } if !recurse { // We have no business with this element. return false, nil } // The element is not a perfect match for any field, but one // or more fields have the path to this element as a parent // prefix. Recurse and attempt to match these. for { var tok Token tok, err = p.Token() if err != nil { return true, err } switch t := tok.(type) { case StartElement: consumed2, err := p.unmarshalPath(tinfo, sv, parents, &t) if err != nil { return true, err } if !consumed2 { if err := p.Skip(); err != nil { return true, err } } case EndElement: return true, nil } } } // Skip reads tokens until it has consumed the end element // matching the most recent start element already consumed. // It recurs if it encounters a start element, so it can be used to // skip nested structures. // It returns nil if it finds an end element matching the start // element; otherwise it returns an error describing the problem. func (d *Decoder) Skip() error { for { tok, err := d.Token() if err != nil { return err } switch tok.(type) { case StartElement: if err := d.Skip(); err != nil { return err } case EndElement: return nil } } } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/read_test.go ================================================ // 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 xml import ( "bytes" "fmt" "io" "reflect" "strings" "testing" "time" ) // Stripped down Atom feed data structures. func TestUnmarshalFeed(t *testing.T) { var f Feed if err := Unmarshal([]byte(atomFeedString), &f); err != nil { t.Fatalf("Unmarshal: %s", err) } if !reflect.DeepEqual(f, atomFeed) { t.Fatalf("have %#v\nwant %#v", f, atomFeed) } } // hget http://codereview.appspot.com/rss/mine/rsc const atomFeedString = ` Code Review - My issueshttp://codereview.appspot.com/rietveld<>rietveld: an attempt at pubsubhubbub 2009-10-04T01:35:58+00:00email-address-removedurn:md5:134d9179c41f806be79b3a5f7877d19a An attempt at adding pubsubhubbub support to Rietveld. http://code.google.com/p/pubsubhubbub http://code.google.com/p/rietveld/issues/detail?id=155 The server side of the protocol is trivial: 1. add a &lt;link rel=&quot;hub&quot; href=&quot;hub-server&quot;&gt; tag to all feeds that will be pubsubhubbubbed. 2. every time one of those feeds changes, tell the hub with a simple POST request. I have tested this by adding debug prints to a local hub server and checking that the server got the right publish requests. I can&#39;t quite get the server to work, but I think the bug is not in my code. I think that the server expects to be able to grab the feed and see the feed&#39;s actual URL in the link rel=&quot;self&quot;, but the default value for that drops the :port from the URL, and I cannot for the life of me figure out how to get the Atom generator deep inside django not to do that, or even where it is doing that, or even what code is running to generate the Atom feed. (I thought I knew but I added some assert False statements and it kept running!) Ignoring that particular problem, I would appreciate feedback on the right way to get the two values at the top of feeds.py marked NOTE(rsc). rietveld: correct tab handling 2009-10-03T23:02:17+00:00email-address-removedurn:md5:0a2a4f19bb815101f0ba2904aed7c35a This fixes the buggy tab rendering that can be seen at http://codereview.appspot.com/116075/diff/1/2 The fundamental problem was that the tab code was not being told what column the text began in, so it didn&#39;t know where to put the tab stops. Another problem was that some of the code assumed that string byte offsets were the same as column offsets, which is only true if there are no tabs. In the process of fixing this, I cleaned up the arguments to Fold and ExpandTabs and renamed them Break and _ExpandTabs so that I could be sure that I found all the call sites. I also wanted to verify that ExpandTabs was not being used from outside intra_region_diff.py. ` type Feed struct { XMLName Name `xml:"http://www.w3.org/2005/Atom feed"` Title string `xml:"title"` Id string `xml:"id"` Link []Link `xml:"link"` Updated time.Time `xml:"updated,attr"` Author Person `xml:"author"` Entry []Entry `xml:"entry"` } type Entry struct { Title string `xml:"title"` Id string `xml:"id"` Link []Link `xml:"link"` Updated time.Time `xml:"updated"` Author Person `xml:"author"` Summary Text `xml:"summary"` } type Link struct { Rel string `xml:"rel,attr,omitempty"` Href string `xml:"href,attr"` } type Person struct { Name string `xml:"name"` URI string `xml:"uri"` Email string `xml:"email"` InnerXML string `xml:",innerxml"` } type Text struct { Type string `xml:"type,attr,omitempty"` Body string `xml:",chardata"` } var atomFeed = Feed{ XMLName: Name{"http://www.w3.org/2005/Atom", "feed"}, Title: "Code Review - My issues", Link: []Link{ {Rel: "alternate", Href: "http://codereview.appspot.com/"}, {Rel: "self", Href: "http://codereview.appspot.com/rss/mine/rsc"}, }, Id: "http://codereview.appspot.com/", Updated: ParseTime("2009-10-04T01:35:58+00:00"), Author: Person{ Name: "rietveld<>", InnerXML: "rietveld<>", }, Entry: []Entry{ { Title: "rietveld: an attempt at pubsubhubbub\n", Link: []Link{ {Rel: "alternate", Href: "http://codereview.appspot.com/126085"}, }, Updated: ParseTime("2009-10-04T01:35:58+00:00"), Author: Person{ Name: "email-address-removed", InnerXML: "email-address-removed", }, Id: "urn:md5:134d9179c41f806be79b3a5f7877d19a", Summary: Text{ Type: "html", Body: ` An attempt at adding pubsubhubbub support to Rietveld. http://code.google.com/p/pubsubhubbub http://code.google.com/p/rietveld/issues/detail?id=155 The server side of the protocol is trivial: 1. add a <link rel="hub" href="hub-server"> tag to all feeds that will be pubsubhubbubbed. 2. every time one of those feeds changes, tell the hub with a simple POST request. I have tested this by adding debug prints to a local hub server and checking that the server got the right publish requests. I can't quite get the server to work, but I think the bug is not in my code. I think that the server expects to be able to grab the feed and see the feed's actual URL in the link rel="self", but the default value for that drops the :port from the URL, and I cannot for the life of me figure out how to get the Atom generator deep inside django not to do that, or even where it is doing that, or even what code is running to generate the Atom feed. (I thought I knew but I added some assert False statements and it kept running!) Ignoring that particular problem, I would appreciate feedback on the right way to get the two values at the top of feeds.py marked NOTE(rsc). `, }, }, { Title: "rietveld: correct tab handling\n", Link: []Link{ {Rel: "alternate", Href: "http://codereview.appspot.com/124106"}, }, Updated: ParseTime("2009-10-03T23:02:17+00:00"), Author: Person{ Name: "email-address-removed", InnerXML: "email-address-removed", }, Id: "urn:md5:0a2a4f19bb815101f0ba2904aed7c35a", Summary: Text{ Type: "html", Body: ` This fixes the buggy tab rendering that can be seen at http://codereview.appspot.com/116075/diff/1/2 The fundamental problem was that the tab code was not being told what column the text began in, so it didn't know where to put the tab stops. Another problem was that some of the code assumed that string byte offsets were the same as column offsets, which is only true if there are no tabs. In the process of fixing this, I cleaned up the arguments to Fold and ExpandTabs and renamed them Break and _ExpandTabs so that I could be sure that I found all the call sites. I also wanted to verify that ExpandTabs was not being used from outside intra_region_diff.py. `, }, }, }, } const pathTestString = ` 1 A B C D <_> E 2 ` type PathTestItem struct { Value string } type PathTestA struct { Items []PathTestItem `xml:">Item1"` Before, After string } type PathTestB struct { Other []PathTestItem `xml:"Items>Item1"` Before, After string } type PathTestC struct { Values1 []string `xml:"Items>Item1>Value"` Values2 []string `xml:"Items>Item2>Value"` Before, After string } type PathTestSet struct { Item1 []PathTestItem } type PathTestD struct { Other PathTestSet `xml:"Items"` Before, After string } type PathTestE struct { Underline string `xml:"Items>_>Value"` Before, After string } var pathTests = []interface{}{ &PathTestA{Items: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"}, &PathTestB{Other: []PathTestItem{{"A"}, {"D"}}, Before: "1", After: "2"}, &PathTestC{Values1: []string{"A", "C", "D"}, Values2: []string{"B"}, Before: "1", After: "2"}, &PathTestD{Other: PathTestSet{Item1: []PathTestItem{{"A"}, {"D"}}}, Before: "1", After: "2"}, &PathTestE{Underline: "E", Before: "1", After: "2"}, } func TestUnmarshalPaths(t *testing.T) { for _, pt := range pathTests { v := reflect.New(reflect.TypeOf(pt).Elem()).Interface() if err := Unmarshal([]byte(pathTestString), v); err != nil { t.Fatalf("Unmarshal: %s", err) } if !reflect.DeepEqual(v, pt) { t.Fatalf("have %#v\nwant %#v", v, pt) } } } type BadPathTestA struct { First string `xml:"items>item1"` Other string `xml:"items>item2"` Second string `xml:"items"` } type BadPathTestB struct { Other string `xml:"items>item2>value"` First string `xml:"items>item1"` Second string `xml:"items>item1>value"` } type BadPathTestC struct { First string Second string `xml:"First"` } type BadPathTestD struct { BadPathEmbeddedA BadPathEmbeddedB } type BadPathEmbeddedA struct { First string } type BadPathEmbeddedB struct { Second string `xml:"First"` } var badPathTests = []struct { v, e interface{} }{ {&BadPathTestA{}, &TagPathError{reflect.TypeOf(BadPathTestA{}), "First", "items>item1", "Second", "items"}}, {&BadPathTestB{}, &TagPathError{reflect.TypeOf(BadPathTestB{}), "First", "items>item1", "Second", "items>item1>value"}}, {&BadPathTestC{}, &TagPathError{reflect.TypeOf(BadPathTestC{}), "First", "", "Second", "First"}}, {&BadPathTestD{}, &TagPathError{reflect.TypeOf(BadPathTestD{}), "First", "", "Second", "First"}}, } func TestUnmarshalBadPaths(t *testing.T) { for _, tt := range badPathTests { err := Unmarshal([]byte(pathTestString), tt.v) if !reflect.DeepEqual(err, tt.e) { t.Fatalf("Unmarshal with %#v didn't fail properly:\nhave %#v,\nwant %#v", tt.v, err, tt.e) } } } const OK = "OK" const withoutNameTypeData = ` ` type TestThree struct { XMLName Name `xml:"Test3"` Attr string `xml:",attr"` } func TestUnmarshalWithoutNameType(t *testing.T) { var x TestThree if err := Unmarshal([]byte(withoutNameTypeData), &x); err != nil { t.Fatalf("Unmarshal: %s", err) } if x.Attr != OK { t.Fatalf("have %v\nwant %v", x.Attr, OK) } } func TestUnmarshalAttr(t *testing.T) { type ParamVal struct { Int int `xml:"int,attr"` } type ParamPtr struct { Int *int `xml:"int,attr"` } type ParamStringPtr struct { Int *string `xml:"int,attr"` } x := []byte(``) p1 := &ParamPtr{} if err := Unmarshal(x, p1); err != nil { t.Fatalf("Unmarshal: %s", err) } if p1.Int == nil { t.Fatalf("Unmarshal failed in to *int field") } else if *p1.Int != 1 { t.Fatalf("Unmarshal with %s failed:\nhave %#v,\n want %#v", x, p1.Int, 1) } p2 := &ParamVal{} if err := Unmarshal(x, p2); err != nil { t.Fatalf("Unmarshal: %s", err) } if p2.Int != 1 { t.Fatalf("Unmarshal with %s failed:\nhave %#v,\n want %#v", x, p2.Int, 1) } p3 := &ParamStringPtr{} if err := Unmarshal(x, p3); err != nil { t.Fatalf("Unmarshal: %s", err) } if p3.Int == nil { t.Fatalf("Unmarshal failed in to *string field") } else if *p3.Int != "1" { t.Fatalf("Unmarshal with %s failed:\nhave %#v,\n want %#v", x, p3.Int, 1) } } type Tables struct { HTable string `xml:"http://www.w3.org/TR/html4/ table"` FTable string `xml:"http://www.w3schools.com/furniture table"` } var tables = []struct { xml string tab Tables ns string }{ { xml: `` + `hello
` + `world
` + `
`, tab: Tables{"hello", "world"}, }, { xml: `` + `world
` + `hello
` + `
`, tab: Tables{"hello", "world"}, }, { xml: `` + `world` + `hello` + ``, tab: Tables{"hello", "world"}, }, { xml: `` + `bogus
` + `
`, tab: Tables{}, }, { xml: `` + `only
` + `
`, tab: Tables{HTable: "only"}, ns: "http://www.w3.org/TR/html4/", }, { xml: `` + `only
` + `
`, tab: Tables{FTable: "only"}, ns: "http://www.w3schools.com/furniture", }, { xml: `` + `only
` + `
`, tab: Tables{}, ns: "something else entirely", }, } func TestUnmarshalNS(t *testing.T) { for i, tt := range tables { var dst Tables var err error if tt.ns != "" { d := NewDecoder(strings.NewReader(tt.xml)) d.DefaultSpace = tt.ns err = d.Decode(&dst) } else { err = Unmarshal([]byte(tt.xml), &dst) } if err != nil { t.Errorf("#%d: Unmarshal: %v", i, err) continue } want := tt.tab if dst != want { t.Errorf("#%d: dst=%+v, want %+v", i, dst, want) } } } func TestRoundTrip(t *testing.T) { // From issue 7535 const s = `` in := bytes.NewBufferString(s) for i := 0; i < 10; i++ { out := &bytes.Buffer{} d := NewDecoder(in) e := NewEncoder(out) for { t, err := d.Token() if err == io.EOF { break } if err != nil { fmt.Println("failed:", err) return } e.EncodeToken(t) } e.Flush() in = out } if got := in.String(); got != s { t.Errorf("have: %q\nwant: %q\n", got, s) } } func TestMarshalNS(t *testing.T) { dst := Tables{"hello", "world"} data, err := Marshal(&dst) if err != nil { t.Fatalf("Marshal: %v", err) } want := `hello
world
` str := string(data) if str != want { t.Errorf("have: %q\nwant: %q\n", str, want) } } type TableAttrs struct { TAttr TAttr } type TAttr struct { HTable string `xml:"http://www.w3.org/TR/html4/ table,attr"` FTable string `xml:"http://www.w3schools.com/furniture table,attr"` Lang string `xml:"http://www.w3.org/XML/1998/namespace lang,attr,omitempty"` Other1 string `xml:"http://golang.org/xml/ other,attr,omitempty"` Other2 string `xml:"http://golang.org/xmlfoo/ other,attr,omitempty"` Other3 string `xml:"http://golang.org/json/ other,attr,omitempty"` Other4 string `xml:"http://golang.org/2/json/ other,attr,omitempty"` } var tableAttrs = []struct { xml string tab TableAttrs ns string }{ { xml: ``, tab: TableAttrs{TAttr{HTable: "hello", FTable: "world"}}, }, { xml: ``, tab: TableAttrs{TAttr{HTable: "hello", FTable: "world"}}, }, { xml: ``, tab: TableAttrs{TAttr{HTable: "hello", FTable: "world"}}, }, { // Default space does not apply to attribute names. xml: ``, tab: TableAttrs{TAttr{HTable: "hello", FTable: ""}}, }, { // Default space does not apply to attribute names. xml: ``, tab: TableAttrs{TAttr{HTable: "", FTable: "world"}}, }, { xml: ``, tab: TableAttrs{}, }, { // Default space does not apply to attribute names. xml: ``, tab: TableAttrs{TAttr{HTable: "hello", FTable: ""}}, ns: "http://www.w3schools.com/furniture", }, { // Default space does not apply to attribute names. xml: ``, tab: TableAttrs{TAttr{HTable: "", FTable: "world"}}, ns: "http://www.w3.org/TR/html4/", }, { xml: ``, tab: TableAttrs{}, ns: "something else entirely", }, } func TestUnmarshalNSAttr(t *testing.T) { for i, tt := range tableAttrs { var dst TableAttrs var err error if tt.ns != "" { d := NewDecoder(strings.NewReader(tt.xml)) d.DefaultSpace = tt.ns err = d.Decode(&dst) } else { err = Unmarshal([]byte(tt.xml), &dst) } if err != nil { t.Errorf("#%d: Unmarshal: %v", i, err) continue } want := tt.tab if dst != want { t.Errorf("#%d: dst=%+v, want %+v", i, dst, want) } } } func TestMarshalNSAttr(t *testing.T) { src := TableAttrs{TAttr{"hello", "world", "en_US", "other1", "other2", "other3", "other4"}} data, err := Marshal(&src) if err != nil { t.Fatalf("Marshal: %v", err) } want := `` str := string(data) if str != want { t.Errorf("Marshal:\nhave: %#q\nwant: %#q\n", str, want) } var dst TableAttrs if err := Unmarshal(data, &dst); err != nil { t.Errorf("Unmarshal: %v", err) } if dst != src { t.Errorf("Unmarshal = %q, want %q", dst, src) } } type MyCharData struct { body string } func (m *MyCharData) UnmarshalXML(d *Decoder, start StartElement) error { for { t, err := d.Token() if err == io.EOF { // found end of element break } if err != nil { return err } if char, ok := t.(CharData); ok { m.body += string(char) } } return nil } var _ Unmarshaler = (*MyCharData)(nil) func (m *MyCharData) UnmarshalXMLAttr(attr Attr) error { panic("must not call") } type MyAttr struct { attr string } func (m *MyAttr) UnmarshalXMLAttr(attr Attr) error { m.attr = attr.Value return nil } var _ UnmarshalerAttr = (*MyAttr)(nil) type MyStruct struct { Data *MyCharData Attr *MyAttr `xml:",attr"` Data2 MyCharData Attr2 MyAttr `xml:",attr"` } func TestUnmarshaler(t *testing.T) { xml := ` hello world howdy world ` var m MyStruct if err := Unmarshal([]byte(xml), &m); err != nil { t.Fatal(err) } if m.Data == nil || m.Attr == nil || m.Data.body != "hello world" || m.Attr.attr != "attr1" || m.Data2.body != "howdy world" || m.Attr2.attr != "attr2" { t.Errorf("m=%#+v\n", m) } } type Pea struct { Cotelydon string } type Pod struct { Pea interface{} `xml:"Pea"` } // https://golang.org/issue/6836 func TestUnmarshalIntoInterface(t *testing.T) { pod := new(Pod) pod.Pea = new(Pea) xml := `Green stuff` err := Unmarshal([]byte(xml), pod) if err != nil { t.Fatalf("failed to unmarshal %q: %v", xml, err) } pea, ok := pod.Pea.(*Pea) if !ok { t.Fatalf("unmarshalled into wrong type: have %T want *Pea", pod.Pea) } have, want := pea.Cotelydon, "Green stuff" if have != want { t.Errorf("failed to unmarshal into interface, have %q want %q", have, want) } } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/typeinfo.go ================================================ // 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 xml import ( "fmt" "reflect" "strings" "sync" ) // typeInfo holds details for the xml representation of a type. type typeInfo struct { xmlname *fieldInfo fields []fieldInfo } // fieldInfo holds details for the xml representation of a single field. type fieldInfo struct { idx []int name string xmlns string flags fieldFlags parents []string } type fieldFlags int const ( fElement fieldFlags = 1 << iota fAttr fCharData fInnerXml fComment fAny fOmitEmpty fMode = fElement | fAttr | fCharData | fInnerXml | fComment | fAny ) var tinfoMap = make(map[reflect.Type]*typeInfo) var tinfoLock sync.RWMutex var nameType = reflect.TypeOf(Name{}) // getTypeInfo returns the typeInfo structure with details necessary // for marshalling and unmarshalling typ. func getTypeInfo(typ reflect.Type) (*typeInfo, error) { tinfoLock.RLock() tinfo, ok := tinfoMap[typ] tinfoLock.RUnlock() if ok { return tinfo, nil } tinfo = &typeInfo{} if typ.Kind() == reflect.Struct && typ != nameType { n := typ.NumField() for i := 0; i < n; i++ { f := typ.Field(i) if f.PkgPath != "" || f.Tag.Get("xml") == "-" { continue // Private field } // For embedded structs, embed its fields. if f.Anonymous { t := f.Type if t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() == reflect.Struct { inner, err := getTypeInfo(t) if err != nil { return nil, err } if tinfo.xmlname == nil { tinfo.xmlname = inner.xmlname } for _, finfo := range inner.fields { finfo.idx = append([]int{i}, finfo.idx...) if err := addFieldInfo(typ, tinfo, &finfo); err != nil { return nil, err } } continue } } finfo, err := structFieldInfo(typ, &f) if err != nil { return nil, err } if f.Name == "XMLName" { tinfo.xmlname = finfo continue } // Add the field if it doesn't conflict with other fields. if err := addFieldInfo(typ, tinfo, finfo); err != nil { return nil, err } } } tinfoLock.Lock() tinfoMap[typ] = tinfo tinfoLock.Unlock() return tinfo, nil } // structFieldInfo builds and returns a fieldInfo for f. func structFieldInfo(typ reflect.Type, f *reflect.StructField) (*fieldInfo, error) { finfo := &fieldInfo{idx: f.Index} // Split the tag from the xml namespace if necessary. tag := f.Tag.Get("xml") if i := strings.Index(tag, " "); i >= 0 { finfo.xmlns, tag = tag[:i], tag[i+1:] } // Parse flags. tokens := strings.Split(tag, ",") if len(tokens) == 1 { finfo.flags = fElement } else { tag = tokens[0] for _, flag := range tokens[1:] { switch flag { case "attr": finfo.flags |= fAttr case "chardata": finfo.flags |= fCharData case "innerxml": finfo.flags |= fInnerXml case "comment": finfo.flags |= fComment case "any": finfo.flags |= fAny case "omitempty": finfo.flags |= fOmitEmpty } } // Validate the flags used. valid := true switch mode := finfo.flags & fMode; mode { case 0: finfo.flags |= fElement case fAttr, fCharData, fInnerXml, fComment, fAny: if f.Name == "XMLName" || tag != "" && mode != fAttr { valid = false } default: // This will also catch multiple modes in a single field. valid = false } if finfo.flags&fMode == fAny { finfo.flags |= fElement } if finfo.flags&fOmitEmpty != 0 && finfo.flags&(fElement|fAttr) == 0 { valid = false } if !valid { return nil, fmt.Errorf("xml: invalid tag in field %s of type %s: %q", f.Name, typ, f.Tag.Get("xml")) } } // Use of xmlns without a name is not allowed. if finfo.xmlns != "" && tag == "" { return nil, fmt.Errorf("xml: namespace without name in field %s of type %s: %q", f.Name, typ, f.Tag.Get("xml")) } if f.Name == "XMLName" { // The XMLName field records the XML element name. Don't // process it as usual because its name should default to // empty rather than to the field name. finfo.name = tag return finfo, nil } if tag == "" { // If the name part of the tag is completely empty, get // default from XMLName of underlying struct if feasible, // or field name otherwise. if xmlname := lookupXMLName(f.Type); xmlname != nil { finfo.xmlns, finfo.name = xmlname.xmlns, xmlname.name } else { finfo.name = f.Name } return finfo, nil } if finfo.xmlns == "" && finfo.flags&fAttr == 0 { // If it's an element no namespace specified, get the default // from the XMLName of enclosing struct if possible. if xmlname := lookupXMLName(typ); xmlname != nil { finfo.xmlns = xmlname.xmlns } } // Prepare field name and parents. parents := strings.Split(tag, ">") if parents[0] == "" { parents[0] = f.Name } if parents[len(parents)-1] == "" { return nil, fmt.Errorf("xml: trailing '>' in field %s of type %s", f.Name, typ) } finfo.name = parents[len(parents)-1] if len(parents) > 1 { if (finfo.flags & fElement) == 0 { return nil, fmt.Errorf("xml: %s chain not valid with %s flag", tag, strings.Join(tokens[1:], ",")) } finfo.parents = parents[:len(parents)-1] } // If the field type has an XMLName field, the names must match // so that the behavior of both marshalling and unmarshalling // is straightforward and unambiguous. if finfo.flags&fElement != 0 { ftyp := f.Type xmlname := lookupXMLName(ftyp) if xmlname != nil && xmlname.name != finfo.name { return nil, fmt.Errorf("xml: name %q in tag of %s.%s conflicts with name %q in %s.XMLName", finfo.name, typ, f.Name, xmlname.name, ftyp) } } return finfo, nil } // lookupXMLName returns the fieldInfo for typ's XMLName field // in case it exists and has a valid xml field tag, otherwise // it returns nil. func lookupXMLName(typ reflect.Type) (xmlname *fieldInfo) { for typ.Kind() == reflect.Ptr { typ = typ.Elem() } if typ.Kind() != reflect.Struct { return nil } for i, n := 0, typ.NumField(); i < n; i++ { f := typ.Field(i) if f.Name != "XMLName" { continue } finfo, err := structFieldInfo(typ, &f) if finfo.name != "" && err == nil { return finfo } // Also consider errors as a non-existent field tag // and let getTypeInfo itself report the error. break } return nil } func min(a, b int) int { if a <= b { return a } return b } // addFieldInfo adds finfo to tinfo.fields if there are no // conflicts, or if conflicts arise from previous fields that were // obtained from deeper embedded structures than finfo. In the latter // case, the conflicting entries are dropped. // A conflict occurs when the path (parent + name) to a field is // itself a prefix of another path, or when two paths match exactly. // It is okay for field paths to share a common, shorter prefix. func addFieldInfo(typ reflect.Type, tinfo *typeInfo, newf *fieldInfo) error { var conflicts []int Loop: // First, figure all conflicts. Most working code will have none. for i := range tinfo.fields { oldf := &tinfo.fields[i] if oldf.flags&fMode != newf.flags&fMode { continue } if oldf.xmlns != "" && newf.xmlns != "" && oldf.xmlns != newf.xmlns { continue } minl := min(len(newf.parents), len(oldf.parents)) for p := 0; p < minl; p++ { if oldf.parents[p] != newf.parents[p] { continue Loop } } if len(oldf.parents) > len(newf.parents) { if oldf.parents[len(newf.parents)] == newf.name { conflicts = append(conflicts, i) } } else if len(oldf.parents) < len(newf.parents) { if newf.parents[len(oldf.parents)] == oldf.name { conflicts = append(conflicts, i) } } else { if newf.name == oldf.name { conflicts = append(conflicts, i) } } } // Without conflicts, add the new field and return. if conflicts == nil { tinfo.fields = append(tinfo.fields, *newf) return nil } // If any conflict is shallower, ignore the new field. // This matches the Go field resolution on embedding. for _, i := range conflicts { if len(tinfo.fields[i].idx) < len(newf.idx) { return nil } } // Otherwise, if any of them is at the same depth level, it's an error. for _, i := range conflicts { oldf := &tinfo.fields[i] if len(oldf.idx) == len(newf.idx) { f1 := typ.FieldByIndex(oldf.idx) f2 := typ.FieldByIndex(newf.idx) return &TagPathError{typ, f1.Name, f1.Tag.Get("xml"), f2.Name, f2.Tag.Get("xml")} } } // Otherwise, the new field is shallower, and thus takes precedence, // so drop the conflicting fields from tinfo and append the new one. for c := len(conflicts) - 1; c >= 0; c-- { i := conflicts[c] copy(tinfo.fields[i:], tinfo.fields[i+1:]) tinfo.fields = tinfo.fields[:len(tinfo.fields)-1] } tinfo.fields = append(tinfo.fields, *newf) return nil } // A TagPathError represents an error in the unmarshalling process // caused by the use of field tags with conflicting paths. type TagPathError struct { Struct reflect.Type Field1, Tag1 string Field2, Tag2 string } func (e *TagPathError) Error() string { return fmt.Sprintf("%s field %q with tag %q conflicts with field %q with tag %q", e.Struct, e.Field1, e.Tag1, e.Field2, e.Tag2) } // value returns v's field value corresponding to finfo. // It's equivalent to v.FieldByIndex(finfo.idx), but initializes // and dereferences pointers as necessary. func (finfo *fieldInfo) value(v reflect.Value) reflect.Value { for i, x := range finfo.idx { if i > 0 { t := v.Type() if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct { if v.IsNil() { v.Set(reflect.New(v.Type().Elem())) } v = v.Elem() } } v = v.Field(x) } return v } ================================================ FILE: vendor/golang.org/x/net/webdav/internal/xml/xml.go ================================================ // 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 xml implements a simple XML 1.0 parser that // understands XML name spaces. package xml // References: // Annotated XML spec: http://www.xml.com/axml/testaxml.htm // XML name spaces: http://www.w3.org/TR/REC-xml-names/ // TODO(rsc): // Test error handling. import ( "bufio" "bytes" "errors" "fmt" "io" "strconv" "strings" "unicode" "unicode/utf8" ) // A SyntaxError represents a syntax error in the XML input stream. type SyntaxError struct { Msg string Line int } func (e *SyntaxError) Error() string { return "XML syntax error on line " + strconv.Itoa(e.Line) + ": " + e.Msg } // A Name represents an XML name (Local) annotated with a name space // identifier (Space). In tokens returned by Decoder.Token, the Space // identifier is given as a canonical URL, not the short prefix used in // the document being parsed. // // As a special case, XML namespace declarations will use the literal // string "xmlns" for the Space field instead of the fully resolved URL. // See Encoder.EncodeToken for more information on namespace encoding // behaviour. type Name struct { Space, Local string } // isNamespace reports whether the name is a namespace-defining name. func (name Name) isNamespace() bool { return name.Local == "xmlns" || name.Space == "xmlns" } // An Attr represents an attribute in an XML element (Name=Value). type Attr struct { Name Name Value string } // A Token is an interface holding one of the token types: // StartElement, EndElement, CharData, Comment, ProcInst, or Directive. type Token interface{} // A StartElement represents an XML start element. type StartElement struct { Name Name Attr []Attr } func (e StartElement) Copy() StartElement { attrs := make([]Attr, len(e.Attr)) copy(attrs, e.Attr) e.Attr = attrs return e } // End returns the corresponding XML end element. func (e StartElement) End() EndElement { return EndElement{e.Name} } // setDefaultNamespace sets the namespace of the element // as the default for all elements contained within it. func (e *StartElement) setDefaultNamespace() { if e.Name.Space == "" { // If there's no namespace on the element, don't // set the default. Strictly speaking this might be wrong, as // we can't tell if the element had no namespace set // or was just using the default namespace. return } // Don't add a default name space if there's already one set. for _, attr := range e.Attr { if attr.Name.Space == "" && attr.Name.Local == "xmlns" { return } } e.Attr = append(e.Attr, Attr{ Name: Name{ Local: "xmlns", }, Value: e.Name.Space, }) } // An EndElement represents an XML end element. type EndElement struct { Name Name } // A CharData represents XML character data (raw text), // in which XML escape sequences have been replaced by // the characters they represent. type CharData []byte func makeCopy(b []byte) []byte { b1 := make([]byte, len(b)) copy(b1, b) return b1 } func (c CharData) Copy() CharData { return CharData(makeCopy(c)) } // A Comment represents an XML comment of the form . // The bytes do not include the comment markers. type Comment []byte func (c Comment) Copy() Comment { return Comment(makeCopy(c)) } // A ProcInst represents an XML processing instruction of the form type ProcInst struct { Target string Inst []byte } func (p ProcInst) Copy() ProcInst { p.Inst = makeCopy(p.Inst) return p } // A Directive represents an XML directive of the form . // The bytes do not include the markers. type Directive []byte func (d Directive) Copy() Directive { return Directive(makeCopy(d)) } // CopyToken returns a copy of a Token. func CopyToken(t Token) Token { switch v := t.(type) { case CharData: return v.Copy() case Comment: return v.Copy() case Directive: return v.Copy() case ProcInst: return v.Copy() case StartElement: return v.Copy() } return t } // A Decoder represents an XML parser reading a particular input stream. // The parser assumes that its input is encoded in UTF-8. type Decoder struct { // Strict defaults to true, enforcing the requirements // of the XML specification. // If set to false, the parser allows input containing common // mistakes: // * If an element is missing an end tag, the parser invents // end tags as necessary to keep the return values from Token // properly balanced. // * In attribute values and character data, unknown or malformed // character entities (sequences beginning with &) are left alone. // // Setting: // // d.Strict = false; // d.AutoClose = HTMLAutoClose; // d.Entity = HTMLEntity // // creates a parser that can handle typical HTML. // // Strict mode does not enforce the requirements of the XML name spaces TR. // In particular it does not reject name space tags using undefined prefixes. // Such tags are recorded with the unknown prefix as the name space URL. Strict bool // When Strict == false, AutoClose indicates a set of elements to // consider closed immediately after they are opened, regardless // of whether an end element is present. AutoClose []string // Entity can be used to map non-standard entity names to string replacements. // The parser behaves as if these standard mappings are present in the map, // regardless of the actual map content: // // "lt": "<", // "gt": ">", // "amp": "&", // "apos": "'", // "quot": `"`, Entity map[string]string // CharsetReader, if non-nil, defines a function to generate // charset-conversion readers, converting from the provided // non-UTF-8 charset into UTF-8. If CharsetReader is nil or // returns an error, parsing stops with an error. One of the // the CharsetReader's result values must be non-nil. CharsetReader func(charset string, input io.Reader) (io.Reader, error) // DefaultSpace sets the default name space used for unadorned tags, // as if the entire XML stream were wrapped in an element containing // the attribute xmlns="DefaultSpace". DefaultSpace string r io.ByteReader buf bytes.Buffer saved *bytes.Buffer stk *stack free *stack needClose bool toClose Name nextToken Token nextByte int ns map[string]string err error line int offset int64 unmarshalDepth int } // NewDecoder creates a new XML parser reading from r. // If r does not implement io.ByteReader, NewDecoder will // do its own buffering. func NewDecoder(r io.Reader) *Decoder { d := &Decoder{ ns: make(map[string]string), nextByte: -1, line: 1, Strict: true, } d.switchToReader(r) return d } // Token returns the next XML token in the input stream. // At the end of the input stream, Token returns nil, io.EOF. // // Slices of bytes in the returned token data refer to the // parser's internal buffer and remain valid only until the next // call to Token. To acquire a copy of the bytes, call CopyToken // or the token's Copy method. // // Token expands self-closing elements such as
// into separate start and end elements returned by successive calls. // // Token guarantees that the StartElement and EndElement // tokens it returns are properly nested and matched: // if Token encounters an unexpected end element, // it will return an error. // // Token implements XML name spaces as described by // http://www.w3.org/TR/REC-xml-names/. Each of the // Name structures contained in the Token has the Space // set to the URL identifying its name space when known. // If Token encounters an unrecognized name space prefix, // it uses the prefix as the Space rather than report an error. func (d *Decoder) Token() (t Token, err error) { if d.stk != nil && d.stk.kind == stkEOF { err = io.EOF return } if d.nextToken != nil { t = d.nextToken d.nextToken = nil } else if t, err = d.rawToken(); err != nil { return } if !d.Strict { if t1, ok := d.autoClose(t); ok { d.nextToken = t t = t1 } } switch t1 := t.(type) { case StartElement: // In XML name spaces, the translations listed in the // attributes apply to the element name and // to the other attribute names, so process // the translations first. for _, a := range t1.Attr { if a.Name.Space == "xmlns" { v, ok := d.ns[a.Name.Local] d.pushNs(a.Name.Local, v, ok) d.ns[a.Name.Local] = a.Value } if a.Name.Space == "" && a.Name.Local == "xmlns" { // Default space for untagged names v, ok := d.ns[""] d.pushNs("", v, ok) d.ns[""] = a.Value } } d.translate(&t1.Name, true) for i := range t1.Attr { d.translate(&t1.Attr[i].Name, false) } d.pushElement(t1.Name) t = t1 case EndElement: d.translate(&t1.Name, true) if !d.popElement(&t1) { return nil, d.err } t = t1 } return } const xmlURL = "http://www.w3.org/XML/1998/namespace" // Apply name space translation to name n. // The default name space (for Space=="") // applies only to element names, not to attribute names. func (d *Decoder) translate(n *Name, isElementName bool) { switch { case n.Space == "xmlns": return case n.Space == "" && !isElementName: return case n.Space == "xml": n.Space = xmlURL case n.Space == "" && n.Local == "xmlns": return } if v, ok := d.ns[n.Space]; ok { n.Space = v } else if n.Space == "" { n.Space = d.DefaultSpace } } func (d *Decoder) switchToReader(r io.Reader) { // Get efficient byte at a time reader. // Assume that if reader has its own // ReadByte, it's efficient enough. // Otherwise, use bufio. if rb, ok := r.(io.ByteReader); ok { d.r = rb } else { d.r = bufio.NewReader(r) } } // Parsing state - stack holds old name space translations // and the current set of open elements. The translations to pop when // ending a given tag are *below* it on the stack, which is // more work but forced on us by XML. type stack struct { next *stack kind int name Name ok bool } const ( stkStart = iota stkNs stkEOF ) func (d *Decoder) push(kind int) *stack { s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.next = d.stk s.kind = kind d.stk = s return s } func (d *Decoder) pop() *stack { s := d.stk if s != nil { d.stk = s.next s.next = d.free d.free = s } return s } // Record that after the current element is finished // (that element is already pushed on the stack) // Token should return EOF until popEOF is called. func (d *Decoder) pushEOF() { // Walk down stack to find Start. // It might not be the top, because there might be stkNs // entries above it. start := d.stk for start.kind != stkStart { start = start.next } // The stkNs entries below a start are associated with that // element too; skip over them. for start.next != nil && start.next.kind == stkNs { start = start.next } s := d.free if s != nil { d.free = s.next } else { s = new(stack) } s.kind = stkEOF s.next = start.next start.next = s } // Undo a pushEOF. // The element must have been finished, so the EOF should be at the top of the stack. func (d *Decoder) popEOF() bool { if d.stk == nil || d.stk.kind != stkEOF { return false } d.pop() return true } // Record that we are starting an element with the given name. func (d *Decoder) pushElement(name Name) { s := d.push(stkStart) s.name = name } // Record that we are changing the value of ns[local]. // The old value is url, ok. func (d *Decoder) pushNs(local string, url string, ok bool) { s := d.push(stkNs) s.name.Local = local s.name.Space = url s.ok = ok } // Creates a SyntaxError with the current line number. func (d *Decoder) syntaxError(msg string) error { return &SyntaxError{Msg: msg, Line: d.line} } // Record that we are ending an element with the given name. // The name must match the record at the top of the stack, // which must be a pushElement record. // After popping the element, apply any undo records from // the stack to restore the name translations that existed // before we saw this element. func (d *Decoder) popElement(t *EndElement) bool { s := d.pop() name := t.Name switch { case s == nil || s.kind != stkStart: d.err = d.syntaxError("unexpected end element ") return false case s.name.Local != name.Local: if !d.Strict { d.needClose = true d.toClose = t.Name t.Name = s.name return true } d.err = d.syntaxError("element <" + s.name.Local + "> closed by ") return false case s.name.Space != name.Space: d.err = d.syntaxError("element <" + s.name.Local + "> in space " + s.name.Space + "closed by in space " + name.Space) return false } // Pop stack until a Start or EOF is on the top, undoing the // translations that were associated with the element we just closed. for d.stk != nil && d.stk.kind != stkStart && d.stk.kind != stkEOF { s := d.pop() if s.ok { d.ns[s.name.Local] = s.name.Space } else { delete(d.ns, s.name.Local) } } return true } // If the top element on the stack is autoclosing and // t is not the end tag, invent the end tag. func (d *Decoder) autoClose(t Token) (Token, bool) { if d.stk == nil || d.stk.kind != stkStart { return nil, false } name := strings.ToLower(d.stk.name.Local) for _, s := range d.AutoClose { if strings.ToLower(s) == name { // This one should be auto closed if t doesn't close it. et, ok := t.(EndElement) if !ok || et.Name.Local != name { return EndElement{d.stk.name}, true } break } } return nil, false } var errRawToken = errors.New("xml: cannot use RawToken from UnmarshalXML method") // RawToken is like Token but does not verify that // start and end elements match and does not translate // name space prefixes to their corresponding URLs. func (d *Decoder) RawToken() (Token, error) { if d.unmarshalDepth > 0 { return nil, errRawToken } return d.rawToken() } func (d *Decoder) rawToken() (Token, error) { if d.err != nil { return nil, d.err } if d.needClose { // The last element we read was self-closing and // we returned just the StartElement half. // Return the EndElement half now. d.needClose = false return EndElement{d.toClose}, nil } b, ok := d.getc() if !ok { return nil, d.err } if b != '<' { // Text section. d.ungetc(b) data := d.text(-1, false) if data == nil { return nil, d.err } return CharData(data), nil } if b, ok = d.mustgetc(); !ok { return nil, d.err } switch b { case '/': // ' { d.err = d.syntaxError("invalid characters between ") return nil, d.err } return EndElement{name}, nil case '?': // ' { break } b0 = b } data := d.buf.Bytes() data = data[0 : len(data)-2] // chop ?> if target == "xml" { content := string(data) ver := procInst("version", content) if ver != "" && ver != "1.0" { d.err = fmt.Errorf("xml: unsupported version %q; only version 1.0 is supported", ver) return nil, d.err } enc := procInst("encoding", content) if enc != "" && enc != "utf-8" && enc != "UTF-8" { if d.CharsetReader == nil { d.err = fmt.Errorf("xml: encoding %q declared but Decoder.CharsetReader is nil", enc) return nil, d.err } newr, err := d.CharsetReader(enc, d.r.(io.Reader)) if err != nil { d.err = fmt.Errorf("xml: opening charset %q: %v", enc, err) return nil, d.err } if newr == nil { panic("CharsetReader returned a nil Reader for charset " + enc) } d.switchToReader(newr) } } return ProcInst{target, data}, nil case '!': // ' { break } b0, b1 = b1, b } data := d.buf.Bytes() data = data[0 : len(data)-3] // chop --> return Comment(data), nil case '[': // . data := d.text(-1, true) if data == nil { return nil, d.err } return CharData(data), nil } // Probably a directive: , , etc. // We don't care, but accumulate for caller. Quoted angle // brackets do not count for nesting. d.buf.Reset() d.buf.WriteByte(b) inquote := uint8(0) depth := 0 for { if b, ok = d.mustgetc(); !ok { return nil, d.err } if inquote == 0 && b == '>' && depth == 0 { break } HandleB: d.buf.WriteByte(b) switch { case b == inquote: inquote = 0 case inquote != 0: // in quotes, no special action case b == '\'' || b == '"': inquote = b case b == '>' && inquote == 0: depth-- case b == '<' && inquote == 0: // Look for ` var testEntity = map[string]string{"何": "What", "is-it": "is it?"} var rawTokens = []Token{ CharData("\n"), ProcInst{"xml", []byte(`version="1.0" encoding="UTF-8"`)}, CharData("\n"), Directive(`DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"`), CharData("\n"), StartElement{Name{"", "body"}, []Attr{{Name{"xmlns", "foo"}, "ns1"}, {Name{"", "xmlns"}, "ns2"}, {Name{"xmlns", "tag"}, "ns3"}}}, CharData("\n "), StartElement{Name{"", "hello"}, []Attr{{Name{"", "lang"}, "en"}}}, CharData("World <>'\" 白鵬翔"), EndElement{Name{"", "hello"}}, CharData("\n "), StartElement{Name{"", "query"}, []Attr{}}, CharData("What is it?"), EndElement{Name{"", "query"}}, CharData("\n "), StartElement{Name{"", "goodbye"}, []Attr{}}, EndElement{Name{"", "goodbye"}}, CharData("\n "), StartElement{Name{"", "outer"}, []Attr{{Name{"foo", "attr"}, "value"}, {Name{"xmlns", "tag"}, "ns4"}}}, CharData("\n "), StartElement{Name{"", "inner"}, []Attr{}}, EndElement{Name{"", "inner"}}, CharData("\n "), EndElement{Name{"", "outer"}}, CharData("\n "), StartElement{Name{"tag", "name"}, []Attr{}}, CharData("\n "), CharData("Some text here."), CharData("\n "), EndElement{Name{"tag", "name"}}, CharData("\n"), EndElement{Name{"", "body"}}, Comment(" missing final newline "), } var cookedTokens = []Token{ CharData("\n"), ProcInst{"xml", []byte(`version="1.0" encoding="UTF-8"`)}, CharData("\n"), Directive(`DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"`), CharData("\n"), StartElement{Name{"ns2", "body"}, []Attr{{Name{"xmlns", "foo"}, "ns1"}, {Name{"", "xmlns"}, "ns2"}, {Name{"xmlns", "tag"}, "ns3"}}}, CharData("\n "), StartElement{Name{"ns2", "hello"}, []Attr{{Name{"", "lang"}, "en"}}}, CharData("World <>'\" 白鵬翔"), EndElement{Name{"ns2", "hello"}}, CharData("\n "), StartElement{Name{"ns2", "query"}, []Attr{}}, CharData("What is it?"), EndElement{Name{"ns2", "query"}}, CharData("\n "), StartElement{Name{"ns2", "goodbye"}, []Attr{}}, EndElement{Name{"ns2", "goodbye"}}, CharData("\n "), StartElement{Name{"ns2", "outer"}, []Attr{{Name{"ns1", "attr"}, "value"}, {Name{"xmlns", "tag"}, "ns4"}}}, CharData("\n "), StartElement{Name{"ns2", "inner"}, []Attr{}}, EndElement{Name{"ns2", "inner"}}, CharData("\n "), EndElement{Name{"ns2", "outer"}}, CharData("\n "), StartElement{Name{"ns3", "name"}, []Attr{}}, CharData("\n "), CharData("Some text here."), CharData("\n "), EndElement{Name{"ns3", "name"}}, CharData("\n"), EndElement{Name{"ns2", "body"}}, Comment(" missing final newline "), } const testInputAltEncoding = ` VALUE` var rawTokensAltEncoding = []Token{ CharData("\n"), ProcInst{"xml", []byte(`version="1.0" encoding="x-testing-uppercase"`)}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("value"), EndElement{Name{"", "tag"}}, } var xmlInput = []string{ // unexpected EOF cases "<", "", "", "", // "", // let the Token() caller handle "", "", "", "", " c;", "", "", "", // "", // let the Token() caller handle "", "", "cdata]]>", } func TestRawToken(t *testing.T) { d := NewDecoder(strings.NewReader(testInput)) d.Entity = testEntity testRawToken(t, d, testInput, rawTokens) } const nonStrictInput = ` non&entity &unknown;entity { &#zzz; &なまえ3; <-gt; &; &0a; ` var nonStringEntity = map[string]string{"": "oops!", "0a": "oops!"} var nonStrictTokens = []Token{ CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("non&entity"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&unknown;entity"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("{"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&#zzz;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&なまえ3;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("<-gt;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&;"), EndElement{Name{"", "tag"}}, CharData("\n"), StartElement{Name{"", "tag"}, []Attr{}}, CharData("&0a;"), EndElement{Name{"", "tag"}}, CharData("\n"), } func TestNonStrictRawToken(t *testing.T) { d := NewDecoder(strings.NewReader(nonStrictInput)) d.Strict = false testRawToken(t, d, nonStrictInput, nonStrictTokens) } type downCaser struct { t *testing.T r io.ByteReader } func (d *downCaser) ReadByte() (c byte, err error) { c, err = d.r.ReadByte() if c >= 'A' && c <= 'Z' { c += 'a' - 'A' } return } func (d *downCaser) Read(p []byte) (int, error) { d.t.Fatalf("unexpected Read call on downCaser reader") panic("unreachable") } func TestRawTokenAltEncoding(t *testing.T) { d := NewDecoder(strings.NewReader(testInputAltEncoding)) d.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) { if charset != "x-testing-uppercase" { t.Fatalf("unexpected charset %q", charset) } return &downCaser{t, input.(io.ByteReader)}, nil } testRawToken(t, d, testInputAltEncoding, rawTokensAltEncoding) } func TestRawTokenAltEncodingNoConverter(t *testing.T) { d := NewDecoder(strings.NewReader(testInputAltEncoding)) token, err := d.RawToken() if token == nil { t.Fatalf("expected a token on first RawToken call") } if err != nil { t.Fatal(err) } token, err = d.RawToken() if token != nil { t.Errorf("expected a nil token; got %#v", token) } if err == nil { t.Fatalf("expected an error on second RawToken call") } const encoding = "x-testing-uppercase" if !strings.Contains(err.Error(), encoding) { t.Errorf("expected error to contain %q; got error: %v", encoding, err) } } func testRawToken(t *testing.T, d *Decoder, raw string, rawTokens []Token) { lastEnd := int64(0) for i, want := range rawTokens { start := d.InputOffset() have, err := d.RawToken() end := d.InputOffset() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { var shave, swant string if _, ok := have.(CharData); ok { shave = fmt.Sprintf("CharData(%q)", have) } else { shave = fmt.Sprintf("%#v", have) } if _, ok := want.(CharData); ok { swant = fmt.Sprintf("CharData(%q)", want) } else { swant = fmt.Sprintf("%#v", want) } t.Errorf("token %d = %s, want %s", i, shave, swant) } // Check that InputOffset returned actual token. switch { case start < lastEnd: t.Errorf("token %d: position [%d,%d) for %T is before previous token", i, start, end, have) case start >= end: // Special case: EndElement can be synthesized. if start == end && end == lastEnd { break } t.Errorf("token %d: position [%d,%d) for %T is empty", i, start, end, have) case end > int64(len(raw)): t.Errorf("token %d: position [%d,%d) for %T extends beyond input", i, start, end, have) default: text := raw[start:end] if strings.ContainsAny(text, "<>") && (!strings.HasPrefix(text, "<") || !strings.HasSuffix(text, ">")) { t.Errorf("token %d: misaligned raw token %#q for %T", i, text, have) } } lastEnd = end } } // Ensure that directives (specifically !DOCTYPE) include the complete // text of any nested directives, noting that < and > do not change // nesting depth if they are in single or double quotes. var nestedDirectivesInput = ` ]> ">]> ]> '>]> ]> '>]> ]> ` var nestedDirectivesTokens = []Token{ CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE [">]`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE ['>]`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE ['>]`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), } func TestNestedDirectives(t *testing.T) { d := NewDecoder(strings.NewReader(nestedDirectivesInput)) for i, want := range nestedDirectivesTokens { have, err := d.Token() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { t.Errorf("token %d = %#v want %#v", i, have, want) } } } func TestToken(t *testing.T) { d := NewDecoder(strings.NewReader(testInput)) d.Entity = testEntity for i, want := range cookedTokens { have, err := d.Token() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { t.Errorf("token %d = %#v want %#v", i, have, want) } } } func TestSyntax(t *testing.T) { for i := range xmlInput { d := NewDecoder(strings.NewReader(xmlInput[i])) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } if _, ok := err.(*SyntaxError); !ok { t.Fatalf(`xmlInput "%s": expected SyntaxError not received`, xmlInput[i]) } } } type allScalars struct { True1 bool True2 bool False1 bool False2 bool Int int Int8 int8 Int16 int16 Int32 int32 Int64 int64 Uint int Uint8 uint8 Uint16 uint16 Uint32 uint32 Uint64 uint64 Uintptr uintptr Float32 float32 Float64 float64 String string PtrString *string } var all = allScalars{ True1: true, True2: true, False1: false, False2: false, Int: 1, Int8: -2, Int16: 3, Int32: -4, Int64: 5, Uint: 6, Uint8: 7, Uint16: 8, Uint32: 9, Uint64: 10, Uintptr: 11, Float32: 13.0, Float64: 14.0, String: "15", PtrString: &sixteen, } var sixteen = "16" const testScalarsInput = ` true 1 false 0 1 -2 3 -4 5 6 7 8 9 10 11 12.0 13.0 14.0 15 16 ` func TestAllScalars(t *testing.T) { var a allScalars err := Unmarshal([]byte(testScalarsInput), &a) if err != nil { t.Fatal(err) } if !reflect.DeepEqual(a, all) { t.Errorf("have %+v want %+v", a, all) } } type item struct { Field_a string } func TestIssue569(t *testing.T) { data := `abcd` var i item err := Unmarshal([]byte(data), &i) if err != nil || i.Field_a != "abcd" { t.Fatal("Expecting abcd") } } func TestUnquotedAttrs(t *testing.T) { data := "" d := NewDecoder(strings.NewReader(data)) d.Strict = false token, err := d.Token() if _, ok := err.(*SyntaxError); ok { t.Errorf("Unexpected error: %v", err) } if token.(StartElement).Name.Local != "tag" { t.Errorf("Unexpected tag name: %v", token.(StartElement).Name.Local) } attr := token.(StartElement).Attr[0] if attr.Value != "azAZ09:-_" { t.Errorf("Unexpected attribute value: %v", attr.Value) } if attr.Name.Local != "attr" { t.Errorf("Unexpected attribute name: %v", attr.Name.Local) } } func TestValuelessAttrs(t *testing.T) { tests := [][3]string{ {"

", "p", "nowrap"}, {"

", "p", "nowrap"}, {"", "input", "checked"}, {"", "input", "checked"}, } for _, test := range tests { d := NewDecoder(strings.NewReader(test[0])) d.Strict = false token, err := d.Token() if _, ok := err.(*SyntaxError); ok { t.Errorf("Unexpected error: %v", err) } if token.(StartElement).Name.Local != test[1] { t.Errorf("Unexpected tag name: %v", token.(StartElement).Name.Local) } attr := token.(StartElement).Attr[0] if attr.Value != test[2] { t.Errorf("Unexpected attribute value: %v", attr.Value) } if attr.Name.Local != test[2] { t.Errorf("Unexpected attribute name: %v", attr.Name.Local) } } } func TestCopyTokenCharData(t *testing.T) { data := []byte("same data") var tok1 Token = CharData(data) tok2 := CopyToken(tok1) if !reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(CharData) != CharData") } data[1] = 'o' if reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(CharData) uses same buffer.") } } func TestCopyTokenStartElement(t *testing.T) { elt := StartElement{Name{"", "hello"}, []Attr{{Name{"", "lang"}, "en"}}} var tok1 Token = elt tok2 := CopyToken(tok1) if tok1.(StartElement).Attr[0].Value != "en" { t.Error("CopyToken overwrote Attr[0]") } if !reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(StartElement) != StartElement") } tok1.(StartElement).Attr[0] = Attr{Name{"", "lang"}, "de"} if reflect.DeepEqual(tok1, tok2) { t.Error("CopyToken(CharData) uses same buffer.") } } func TestSyntaxErrorLineNum(t *testing.T) { testInput := "

Foo

\n\n

Bar\n" d := NewDecoder(strings.NewReader(testInput)) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } synerr, ok := err.(*SyntaxError) if !ok { t.Error("Expected SyntaxError.") } if synerr.Line != 3 { t.Error("SyntaxError didn't have correct line number.") } } func TestTrailingRawToken(t *testing.T) { input := ` ` d := NewDecoder(strings.NewReader(input)) var err error for _, err = d.RawToken(); err == nil; _, err = d.RawToken() { } if err != io.EOF { t.Fatalf("d.RawToken() = _, %v, want _, io.EOF", err) } } func TestTrailingToken(t *testing.T) { input := ` ` d := NewDecoder(strings.NewReader(input)) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } if err != io.EOF { t.Fatalf("d.Token() = _, %v, want _, io.EOF", err) } } func TestEntityInsideCDATA(t *testing.T) { input := `` d := NewDecoder(strings.NewReader(input)) var err error for _, err = d.Token(); err == nil; _, err = d.Token() { } if err != io.EOF { t.Fatalf("d.Token() = _, %v, want _, io.EOF", err) } } var characterTests = []struct { in string err string }{ {"\x12", "illegal character code U+0012"}, {"\x0b", "illegal character code U+000B"}, {"\xef\xbf\xbe", "illegal character code U+FFFE"}, {"\r\n\x07", "illegal character code U+0007"}, {"what's up", "expected attribute name in element"}, {"&abc\x01;", "invalid character entity &abc (no semicolon)"}, {"&\x01;", "invalid character entity & (no semicolon)"}, {"&\xef\xbf\xbe;", "invalid character entity &\uFFFE;"}, {"&hello;", "invalid character entity &hello;"}, } func TestDisallowedCharacters(t *testing.T) { for i, tt := range characterTests { d := NewDecoder(strings.NewReader(tt.in)) var err error for err == nil { _, err = d.Token() } synerr, ok := err.(*SyntaxError) if !ok { t.Fatalf("input %d d.Token() = _, %v, want _, *SyntaxError", i, err) } if synerr.Msg != tt.err { t.Fatalf("input %d synerr.Msg wrong: want %q, got %q", i, tt.err, synerr.Msg) } } } type procInstEncodingTest struct { expect, got string } var procInstTests = []struct { input string expect [2]string }{ {`version="1.0" encoding="utf-8"`, [2]string{"1.0", "utf-8"}}, {`version="1.0" encoding='utf-8'`, [2]string{"1.0", "utf-8"}}, {`version="1.0" encoding='utf-8' `, [2]string{"1.0", "utf-8"}}, {`version="1.0" encoding=utf-8`, [2]string{"1.0", ""}}, {`encoding="FOO" `, [2]string{"", "FOO"}}, } func TestProcInstEncoding(t *testing.T) { for _, test := range procInstTests { if got := procInst("version", test.input); got != test.expect[0] { t.Errorf("procInst(version, %q) = %q; want %q", test.input, got, test.expect[0]) } if got := procInst("encoding", test.input); got != test.expect[1] { t.Errorf("procInst(encoding, %q) = %q; want %q", test.input, got, test.expect[1]) } } } // Ensure that directives with comments include the complete // text of any nested directives. var directivesWithCommentsInput = ` ]> ]> --> --> []> ` var directivesWithCommentsTokens = []Token{ CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), Directive(`DOCTYPE []`), CharData("\n"), } func TestDirectivesWithComments(t *testing.T) { d := NewDecoder(strings.NewReader(directivesWithCommentsInput)) for i, want := range directivesWithCommentsTokens { have, err := d.Token() if err != nil { t.Fatalf("token %d: unexpected error: %s", i, err) } if !reflect.DeepEqual(have, want) { t.Errorf("token %d = %#v want %#v", i, have, want) } } } // Writer whose Write method always returns an error. type errWriter struct{} func (errWriter) Write(p []byte) (n int, err error) { return 0, fmt.Errorf("unwritable") } func TestEscapeTextIOErrors(t *testing.T) { expectErr := "unwritable" err := EscapeText(errWriter{}, []byte{'A'}) if err == nil || err.Error() != expectErr { t.Errorf("have %v, want %v", err, expectErr) } } func TestEscapeTextInvalidChar(t *testing.T) { input := []byte("A \x00 terminated string.") expected := "A \uFFFD terminated string." buff := new(bytes.Buffer) if err := EscapeText(buff, input); err != nil { t.Fatalf("have %v, want nil", err) } text := buff.String() if text != expected { t.Errorf("have %v, want %v", text, expected) } } func TestIssue5880(t *testing.T) { type T []byte data, err := Marshal(T{192, 168, 0, 1}) if err != nil { t.Errorf("Marshal error: %v", err) } if !utf8.Valid(data) { t.Errorf("Marshal generated invalid UTF-8: %x", data) } } ================================================ FILE: vendor/golang.org/x/net/webdav/litmus_test_server.go ================================================ // 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 ignore /* This program is a server for the WebDAV 'litmus' compliance test at http://www.webdav.org/neon/litmus/ To run the test: go run litmus_test_server.go and separately, from the downloaded litmus-xxx directory: make URL=http://localhost:9999/ check */ package main import ( "flag" "fmt" "log" "net/http" "net/url" "golang.org/x/net/webdav" ) var port = flag.Int("port", 9999, "server port") func main() { flag.Parse() log.SetFlags(0) h := &webdav.Handler{ FileSystem: webdav.NewMemFS(), LockSystem: webdav.NewMemLS(), Logger: func(r *http.Request, err error) { litmus := r.Header.Get("X-Litmus") if len(litmus) > 19 { litmus = litmus[:16] + "..." } switch r.Method { case "COPY", "MOVE": dst := "" if u, err := url.Parse(r.Header.Get("Destination")); err == nil { dst = u.Path } o := r.Header.Get("Overwrite") log.Printf("%-20s%-10s%-30s%-30so=%-2s%v", litmus, r.Method, r.URL.Path, dst, o, err) default: log.Printf("%-20s%-10s%-30s%v", litmus, r.Method, r.URL.Path, err) } }, } // The next line would normally be: // http.Handle("/", h) // but we wrap that HTTP handler h to cater for a special case. // // The propfind_invalid2 litmus test case expects an empty namespace prefix // declaration to be an error. The FAQ in the webdav litmus test says: // // "What does the "propfind_invalid2" test check for?... // // If a request was sent with an XML body which included an empty namespace // prefix declaration (xmlns:ns1=""), then the server must reject that with // a "400 Bad Request" response, as it is invalid according to the XML // Namespace specification." // // On the other hand, the Go standard library's encoding/xml package // accepts an empty xmlns namespace, as per the discussion at // https://github.com/golang/go/issues/8068 // // Empty namespaces seem disallowed in the second (2006) edition of the XML // standard, but allowed in a later edition. The grammar differs between // http://www.w3.org/TR/2006/REC-xml-names-20060816/#ns-decl and // http://www.w3.org/TR/REC-xml-names/#dt-prefix // // Thus, we assume that the propfind_invalid2 test is obsolete, and // hard-code the 400 Bad Request response that the test expects. http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("X-Litmus") == "props: 3 (propfind_invalid2)" { http.Error(w, "400 Bad Request", http.StatusBadRequest) return } h.ServeHTTP(w, r) })) addr := fmt.Sprintf(":%d", *port) log.Printf("Serving %v", addr) log.Fatal(http.ListenAndServe(addr, nil)) } ================================================ FILE: vendor/golang.org/x/net/webdav/lock.go ================================================ // 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 webdav import ( "container/heap" "errors" "strconv" "strings" "sync" "time" ) var ( // ErrConfirmationFailed is returned by a LockSystem's Confirm method. ErrConfirmationFailed = errors.New("webdav: confirmation failed") // ErrForbidden is returned by a LockSystem's Unlock method. ErrForbidden = errors.New("webdav: forbidden") // ErrLocked is returned by a LockSystem's Create, Refresh and Unlock methods. ErrLocked = errors.New("webdav: locked") // ErrNoSuchLock is returned by a LockSystem's Refresh and Unlock methods. ErrNoSuchLock = errors.New("webdav: no such lock") ) // Condition can match a WebDAV resource, based on a token or ETag. // Exactly one of Token and ETag should be non-empty. type Condition struct { Not bool Token string ETag string } // LockSystem manages access to a collection of named resources. The elements // in a lock name are separated by slash ('/', U+002F) characters, regardless // of host operating system convention. type LockSystem interface { // Confirm confirms that the caller can claim all of the locks specified by // the given conditions, and that holding the union of all of those locks // gives exclusive access to all of the named resources. Up to two resources // can be named. Empty names are ignored. // // Exactly one of release and err will be non-nil. If release is non-nil, // all of the requested locks are held until release is called. Calling // release does not unlock the lock, in the WebDAV UNLOCK sense, but once // Confirm has confirmed that a lock claim is valid, that lock cannot be // Confirmed again until it has been released. // // If Confirm returns ErrConfirmationFailed then the Handler will continue // to try any other set of locks presented (a WebDAV HTTP request can // present more than one set of locks). If it returns any other non-nil // error, the Handler will write a "500 Internal Server Error" HTTP status. Confirm(now time.Time, name0, name1 string, conditions ...Condition) (release func(), err error) // Create creates a lock with the given depth, duration, owner and root // (name). The depth will either be negative (meaning infinite) or zero. // // If Create returns ErrLocked then the Handler will write a "423 Locked" // HTTP status. If it returns any other non-nil error, the Handler will // write a "500 Internal Server Error" HTTP status. // // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.10.6 for // when to use each error. // // The token returned identifies the created lock. It should be an absolute // URI as defined by RFC 3986, Section 4.3. In particular, it should not // contain whitespace. Create(now time.Time, details LockDetails) (token string, err error) // Refresh refreshes the lock with the given token. // // If Refresh returns ErrLocked then the Handler will write a "423 Locked" // HTTP Status. If Refresh returns ErrNoSuchLock then the Handler will write // a "412 Precondition Failed" HTTP Status. If it returns any other non-nil // error, the Handler will write a "500 Internal Server Error" HTTP status. // // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.10.6 for // when to use each error. Refresh(now time.Time, token string, duration time.Duration) (LockDetails, error) // Unlock unlocks the lock with the given token. // // If Unlock returns ErrForbidden then the Handler will write a "403 // Forbidden" HTTP Status. If Unlock returns ErrLocked then the Handler // will write a "423 Locked" HTTP status. If Unlock returns ErrNoSuchLock // then the Handler will write a "409 Conflict" HTTP Status. If it returns // any other non-nil error, the Handler will write a "500 Internal Server // Error" HTTP status. // // See http://www.webdav.org/specs/rfc4918.html#rfc.section.9.11.1 for // when to use each error. Unlock(now time.Time, token string) error } // LockDetails are a lock's metadata. type LockDetails struct { // Root is the root resource name being locked. For a zero-depth lock, the // root is the only resource being locked. Root string // Duration is the lock timeout. A negative duration means infinite. Duration time.Duration // OwnerXML is the verbatim XML given in a LOCK HTTP request. // // TODO: does the "verbatim" nature play well with XML namespaces? // Does the OwnerXML field need to have more structure? See // https://codereview.appspot.com/175140043/#msg2 OwnerXML string // ZeroDepth is whether the lock has zero depth. If it does not have zero // depth, it has infinite depth. ZeroDepth bool } // NewMemLS returns a new in-memory LockSystem. func NewMemLS() LockSystem { return &memLS{ byName: make(map[string]*memLSNode), byToken: make(map[string]*memLSNode), gen: uint64(time.Now().Unix()), } } type memLS struct { mu sync.Mutex byName map[string]*memLSNode byToken map[string]*memLSNode gen uint64 // byExpiry only contains those nodes whose LockDetails have a finite // Duration and are yet to expire. byExpiry byExpiry } func (m *memLS) nextToken() string { m.gen++ return strconv.FormatUint(m.gen, 10) } func (m *memLS) collectExpiredNodes(now time.Time) { for len(m.byExpiry) > 0 { if now.Before(m.byExpiry[0].expiry) { break } m.remove(m.byExpiry[0]) } } func (m *memLS) Confirm(now time.Time, name0, name1 string, conditions ...Condition) (func(), error) { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) var n0, n1 *memLSNode if name0 != "" { if n0 = m.lookup(slashClean(name0), conditions...); n0 == nil { return nil, ErrConfirmationFailed } } if name1 != "" { if n1 = m.lookup(slashClean(name1), conditions...); n1 == nil { return nil, ErrConfirmationFailed } } // Don't hold the same node twice. if n1 == n0 { n1 = nil } if n0 != nil { m.hold(n0) } if n1 != nil { m.hold(n1) } return func() { m.mu.Lock() defer m.mu.Unlock() if n1 != nil { m.unhold(n1) } if n0 != nil { m.unhold(n0) } }, nil } // lookup returns the node n that locks the named resource, provided that n // matches at least one of the given conditions and that lock isn't held by // another party. Otherwise, it returns nil. // // n may be a parent of the named resource, if n is an infinite depth lock. func (m *memLS) lookup(name string, conditions ...Condition) (n *memLSNode) { // TODO: support Condition.Not and Condition.ETag. for _, c := range conditions { n = m.byToken[c.Token] if n == nil || n.held { continue } if name == n.details.Root { return n } if n.details.ZeroDepth { continue } if n.details.Root == "/" || strings.HasPrefix(name, n.details.Root+"/") { return n } } return nil } func (m *memLS) hold(n *memLSNode) { if n.held { panic("webdav: memLS inconsistent held state") } n.held = true if n.details.Duration >= 0 && n.byExpiryIndex >= 0 { heap.Remove(&m.byExpiry, n.byExpiryIndex) } } func (m *memLS) unhold(n *memLSNode) { if !n.held { panic("webdav: memLS inconsistent held state") } n.held = false if n.details.Duration >= 0 { heap.Push(&m.byExpiry, n) } } func (m *memLS) Create(now time.Time, details LockDetails) (string, error) { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) details.Root = slashClean(details.Root) if !m.canCreate(details.Root, details.ZeroDepth) { return "", ErrLocked } n := m.create(details.Root) n.token = m.nextToken() m.byToken[n.token] = n n.details = details if n.details.Duration >= 0 { n.expiry = now.Add(n.details.Duration) heap.Push(&m.byExpiry, n) } return n.token, nil } func (m *memLS) Refresh(now time.Time, token string, duration time.Duration) (LockDetails, error) { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) n := m.byToken[token] if n == nil { return LockDetails{}, ErrNoSuchLock } if n.held { return LockDetails{}, ErrLocked } if n.byExpiryIndex >= 0 { heap.Remove(&m.byExpiry, n.byExpiryIndex) } n.details.Duration = duration if n.details.Duration >= 0 { n.expiry = now.Add(n.details.Duration) heap.Push(&m.byExpiry, n) } return n.details, nil } func (m *memLS) Unlock(now time.Time, token string) error { m.mu.Lock() defer m.mu.Unlock() m.collectExpiredNodes(now) n := m.byToken[token] if n == nil { return ErrNoSuchLock } if n.held { return ErrLocked } m.remove(n) return nil } func (m *memLS) canCreate(name string, zeroDepth bool) bool { return walkToRoot(name, func(name0 string, first bool) bool { n := m.byName[name0] if n == nil { return true } if first { if n.token != "" { // The target node is already locked. return false } if !zeroDepth { // The requested lock depth is infinite, and the fact that n exists // (n != nil) means that a descendent of the target node is locked. return false } } else if n.token != "" && !n.details.ZeroDepth { // An ancestor of the target node is locked with infinite depth. return false } return true }) } func (m *memLS) create(name string) (ret *memLSNode) { walkToRoot(name, func(name0 string, first bool) bool { n := m.byName[name0] if n == nil { n = &memLSNode{ details: LockDetails{ Root: name0, }, byExpiryIndex: -1, } m.byName[name0] = n } n.refCount++ if first { ret = n } return true }) return ret } func (m *memLS) remove(n *memLSNode) { delete(m.byToken, n.token) n.token = "" walkToRoot(n.details.Root, func(name0 string, first bool) bool { x := m.byName[name0] x.refCount-- if x.refCount == 0 { delete(m.byName, name0) } return true }) if n.byExpiryIndex >= 0 { heap.Remove(&m.byExpiry, n.byExpiryIndex) } } func walkToRoot(name string, f func(name0 string, first bool) bool) bool { for first := true; ; first = false { if !f(name, first) { return false } if name == "/" { break } name = name[:strings.LastIndex(name, "/")] if name == "" { name = "/" } } return true } type memLSNode struct { // details are the lock metadata. Even if this node's name is not explicitly locked, // details.Root will still equal the node's name. details LockDetails // token is the unique identifier for this node's lock. An empty token means that // this node is not explicitly locked. token string // refCount is the number of self-or-descendent nodes that are explicitly locked. refCount int // expiry is when this node's lock expires. expiry time.Time // byExpiryIndex is the index of this node in memLS.byExpiry. It is -1 // if this node does not expire, or has expired. byExpiryIndex int // held is whether this node's lock is actively held by a Confirm call. held bool } type byExpiry []*memLSNode func (b *byExpiry) Len() int { return len(*b) } func (b *byExpiry) Less(i, j int) bool { return (*b)[i].expiry.Before((*b)[j].expiry) } func (b *byExpiry) Swap(i, j int) { (*b)[i], (*b)[j] = (*b)[j], (*b)[i] (*b)[i].byExpiryIndex = i (*b)[j].byExpiryIndex = j } func (b *byExpiry) Push(x interface{}) { n := x.(*memLSNode) n.byExpiryIndex = len(*b) *b = append(*b, n) } func (b *byExpiry) Pop() interface{} { i := len(*b) - 1 n := (*b)[i] (*b)[i] = nil n.byExpiryIndex = -1 *b = (*b)[:i] return n } const infiniteTimeout = -1 // parseTimeout parses the Timeout HTTP header, as per section 10.7. If s is // empty, an infiniteTimeout is returned. func parseTimeout(s string) (time.Duration, error) { if s == "" { return infiniteTimeout, nil } if i := strings.IndexByte(s, ','); i >= 0 { s = s[:i] } s = strings.TrimSpace(s) if s == "Infinite" { return infiniteTimeout, nil } const pre = "Second-" if !strings.HasPrefix(s, pre) { return 0, errInvalidTimeout } s = s[len(pre):] if s == "" || s[0] < '0' || '9' < s[0] { return 0, errInvalidTimeout } n, err := strconv.ParseInt(s, 10, 64) if err != nil || 1<<32-1 < n { return 0, errInvalidTimeout } return time.Duration(n) * time.Second, nil } ================================================ FILE: vendor/golang.org/x/net/webdav/lock_test.go ================================================ // 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 webdav import ( "fmt" "math/rand" "path" "reflect" "sort" "strconv" "strings" "testing" "time" ) func TestWalkToRoot(t *testing.T) { testCases := []struct { name string want []string }{{ "/a/b/c/d", []string{ "/a/b/c/d", "/a/b/c", "/a/b", "/a", "/", }, }, { "/a", []string{ "/a", "/", }, }, { "/", []string{ "/", }, }} for _, tc := range testCases { var got []string if !walkToRoot(tc.name, func(name0 string, first bool) bool { if first != (len(got) == 0) { t.Errorf("name=%q: first=%t but len(got)==%d", tc.name, first, len(got)) return false } got = append(got, name0) return true }) { continue } if !reflect.DeepEqual(got, tc.want) { t.Errorf("name=%q:\ngot %q\nwant %q", tc.name, got, tc.want) } } } var lockTestDurations = []time.Duration{ infiniteTimeout, // infiniteTimeout means to never expire. 0, // A zero duration means to expire immediately. 100 * time.Hour, // A very large duration will not expire in these tests. } // lockTestNames are the names of a set of mutually compatible locks. For each // name fragment: // - _ means no explicit lock. // - i means a infinite-depth lock, // - z means a zero-depth lock, var lockTestNames = []string{ "/_/_/_/_/z", "/_/_/i", "/_/z", "/_/z/i", "/_/z/z", "/_/z/_/i", "/_/z/_/z", "/i", "/z", "/z/_/i", "/z/_/z", } func lockTestZeroDepth(name string) bool { switch name[len(name)-1] { case 'i': return false case 'z': return true } panic(fmt.Sprintf("lock name %q did not end with 'i' or 'z'", name)) } func TestMemLSCanCreate(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) for _, name := range lockTestNames { _, err := m.Create(now, LockDetails{ Root: name, Duration: infiniteTimeout, ZeroDepth: lockTestZeroDepth(name), }) if err != nil { t.Fatalf("creating lock for %q: %v", name, err) } } wantCanCreate := func(name string, zeroDepth bool) bool { for _, n := range lockTestNames { switch { case n == name: // An existing lock has the same name as the proposed lock. return false case strings.HasPrefix(n, name): // An existing lock would be a child of the proposed lock, // which conflicts if the proposed lock has infinite depth. if !zeroDepth { return false } case strings.HasPrefix(name, n): // An existing lock would be an ancestor of the proposed lock, // which conflicts if the ancestor has infinite depth. if n[len(n)-1] == 'i' { return false } } } return true } var check func(int, string) check = func(recursion int, name string) { for _, zeroDepth := range []bool{false, true} { got := m.canCreate(name, zeroDepth) want := wantCanCreate(name, zeroDepth) if got != want { t.Errorf("canCreate name=%q zeroDepth=%t: got %t, want %t", name, zeroDepth, got, want) } } if recursion == 6 { return } if name != "/" { name += "/" } for _, c := range "_iz" { check(recursion+1, name+string(c)) } } check(0, "/") } func TestMemLSLookup(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) badToken := m.nextToken() t.Logf("badToken=%q", badToken) for _, name := range lockTestNames { token, err := m.Create(now, LockDetails{ Root: name, Duration: infiniteTimeout, ZeroDepth: lockTestZeroDepth(name), }) if err != nil { t.Fatalf("creating lock for %q: %v", name, err) } t.Logf("%-15q -> node=%p token=%q", name, m.byName[name], token) } baseNames := append([]string{"/a", "/b/c"}, lockTestNames...) for _, baseName := range baseNames { for _, suffix := range []string{"", "/0", "/1/2/3"} { name := baseName + suffix goodToken := "" base := m.byName[baseName] if base != nil && (suffix == "" || !lockTestZeroDepth(baseName)) { goodToken = base.token } for _, token := range []string{badToken, goodToken} { if token == "" { continue } got := m.lookup(name, Condition{Token: token}) want := base if token == badToken { want = nil } if got != want { t.Errorf("name=%-20qtoken=%q (bad=%t): got %p, want %p", name, token, token == badToken, got, want) } } } } } func TestMemLSConfirm(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) alice, err := m.Create(now, LockDetails{ Root: "/alice", Duration: infiniteTimeout, ZeroDepth: false, }) tweedle, err := m.Create(now, LockDetails{ Root: "/tweedle", Duration: infiniteTimeout, ZeroDepth: false, }) if err != nil { t.Fatalf("Create: %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Create: inconsistent state: %v", err) } // Test a mismatch between name and condition. _, err = m.Confirm(now, "/tweedle/dee", "", Condition{Token: alice}) if err != ErrConfirmationFailed { t.Fatalf("Confirm (mismatch): got %v, want ErrConfirmationFailed", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (mismatch): inconsistent state: %v", err) } // Test two names (that fall under the same lock) in the one Confirm call. release, err := m.Confirm(now, "/tweedle/dee", "/tweedle/dum", Condition{Token: tweedle}) if err != nil { t.Fatalf("Confirm (twins): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (twins): inconsistent state: %v", err) } release() if err := m.consistent(); err != nil { t.Fatalf("release (twins): inconsistent state: %v", err) } // Test the same two names in overlapping Confirm / release calls. releaseDee, err := m.Confirm(now, "/tweedle/dee", "", Condition{Token: tweedle}) if err != nil { t.Fatalf("Confirm (sequence #0): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (sequence #0): inconsistent state: %v", err) } _, err = m.Confirm(now, "/tweedle/dum", "", Condition{Token: tweedle}) if err != ErrConfirmationFailed { t.Fatalf("Confirm (sequence #1): got %v, want ErrConfirmationFailed", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (sequence #1): inconsistent state: %v", err) } releaseDee() if err := m.consistent(); err != nil { t.Fatalf("release (sequence #2): inconsistent state: %v", err) } releaseDum, err := m.Confirm(now, "/tweedle/dum", "", Condition{Token: tweedle}) if err != nil { t.Fatalf("Confirm (sequence #3): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Confirm (sequence #3): inconsistent state: %v", err) } // Test that you can't unlock a held lock. err = m.Unlock(now, tweedle) if err != ErrLocked { t.Fatalf("Unlock (sequence #4): got %v, want ErrLocked", err) } releaseDum() if err := m.consistent(); err != nil { t.Fatalf("release (sequence #5): inconsistent state: %v", err) } err = m.Unlock(now, tweedle) if err != nil { t.Fatalf("Unlock (sequence #6): %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Unlock (sequence #6): inconsistent state: %v", err) } } func TestMemLSNonCanonicalRoot(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) token, err := m.Create(now, LockDetails{ Root: "/foo/./bar//", Duration: 1 * time.Second, }) if err != nil { t.Fatalf("Create: %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Create: inconsistent state: %v", err) } if err := m.Unlock(now, token); err != nil { t.Fatalf("Unlock: %v", err) } if err := m.consistent(); err != nil { t.Fatalf("Unlock: inconsistent state: %v", err) } } func TestMemLSExpiry(t *testing.T) { m := NewMemLS().(*memLS) testCases := []string{ "setNow 0", "create /a.5", "want /a.5", "create /c.6", "want /a.5 /c.6", "create /a/b.7", "want /a.5 /a/b.7 /c.6", "setNow 4", "want /a.5 /a/b.7 /c.6", "setNow 5", "want /a/b.7 /c.6", "setNow 6", "want /a/b.7", "setNow 7", "want ", "setNow 8", "want ", "create /a.12", "create /b.13", "create /c.15", "create /a/d.16", "want /a.12 /a/d.16 /b.13 /c.15", "refresh /a.14", "want /a.14 /a/d.16 /b.13 /c.15", "setNow 12", "want /a.14 /a/d.16 /b.13 /c.15", "setNow 13", "want /a.14 /a/d.16 /c.15", "setNow 14", "want /a/d.16 /c.15", "refresh /a/d.20", "refresh /c.20", "want /a/d.20 /c.20", "setNow 20", "want ", } tokens := map[string]string{} zTime := time.Unix(0, 0) now := zTime for i, tc := range testCases { j := strings.IndexByte(tc, ' ') if j < 0 { t.Fatalf("test case #%d %q: invalid command", i, tc) } op, arg := tc[:j], tc[j+1:] switch op { default: t.Fatalf("test case #%d %q: invalid operation %q", i, tc, op) case "create", "refresh": parts := strings.Split(arg, ".") if len(parts) != 2 { t.Fatalf("test case #%d %q: invalid create", i, tc) } root := parts[0] d, err := strconv.Atoi(parts[1]) if err != nil { t.Fatalf("test case #%d %q: invalid duration", i, tc) } dur := time.Unix(0, 0).Add(time.Duration(d) * time.Second).Sub(now) switch op { case "create": token, err := m.Create(now, LockDetails{ Root: root, Duration: dur, ZeroDepth: true, }) if err != nil { t.Fatalf("test case #%d %q: Create: %v", i, tc, err) } tokens[root] = token case "refresh": token := tokens[root] if token == "" { t.Fatalf("test case #%d %q: no token for %q", i, tc, root) } got, err := m.Refresh(now, token, dur) if err != nil { t.Fatalf("test case #%d %q: Refresh: %v", i, tc, err) } want := LockDetails{ Root: root, Duration: dur, ZeroDepth: true, } if got != want { t.Fatalf("test case #%d %q:\ngot %v\nwant %v", i, tc, got, want) } } case "setNow": d, err := strconv.Atoi(arg) if err != nil { t.Fatalf("test case #%d %q: invalid duration", i, tc) } now = time.Unix(0, 0).Add(time.Duration(d) * time.Second) case "want": m.mu.Lock() m.collectExpiredNodes(now) got := make([]string, 0, len(m.byToken)) for _, n := range m.byToken { got = append(got, fmt.Sprintf("%s.%d", n.details.Root, n.expiry.Sub(zTime)/time.Second)) } m.mu.Unlock() sort.Strings(got) want := []string{} if arg != "" { want = strings.Split(arg, " ") } if !reflect.DeepEqual(got, want) { t.Fatalf("test case #%d %q:\ngot %q\nwant %q", i, tc, got, want) } } if err := m.consistent(); err != nil { t.Fatalf("test case #%d %q: inconsistent state: %v", i, tc, err) } } } func TestMemLS(t *testing.T) { now := time.Unix(0, 0) m := NewMemLS().(*memLS) rng := rand.New(rand.NewSource(0)) tokens := map[string]string{} nConfirm, nCreate, nRefresh, nUnlock := 0, 0, 0, 0 const N = 2000 for i := 0; i < N; i++ { name := lockTestNames[rng.Intn(len(lockTestNames))] duration := lockTestDurations[rng.Intn(len(lockTestDurations))] confirmed, unlocked := false, false // If the name was already locked, we randomly confirm/release, refresh // or unlock it. Otherwise, we create a lock. token := tokens[name] if token != "" { switch rng.Intn(3) { case 0: confirmed = true nConfirm++ release, err := m.Confirm(now, name, "", Condition{Token: token}) if err != nil { t.Fatalf("iteration #%d: Confirm %q: %v", i, name, err) } if err := m.consistent(); err != nil { t.Fatalf("iteration #%d: inconsistent state: %v", i, err) } release() case 1: nRefresh++ if _, err := m.Refresh(now, token, duration); err != nil { t.Fatalf("iteration #%d: Refresh %q: %v", i, name, err) } case 2: unlocked = true nUnlock++ if err := m.Unlock(now, token); err != nil { t.Fatalf("iteration #%d: Unlock %q: %v", i, name, err) } } } else { nCreate++ var err error token, err = m.Create(now, LockDetails{ Root: name, Duration: duration, ZeroDepth: lockTestZeroDepth(name), }) if err != nil { t.Fatalf("iteration #%d: Create %q: %v", i, name, err) } } if !confirmed { if duration == 0 || unlocked { // A zero-duration lock should expire immediately and is // effectively equivalent to being unlocked. tokens[name] = "" } else { tokens[name] = token } } if err := m.consistent(); err != nil { t.Fatalf("iteration #%d: inconsistent state: %v", i, err) } } if nConfirm < N/10 { t.Fatalf("too few Confirm calls: got %d, want >= %d", nConfirm, N/10) } if nCreate < N/10 { t.Fatalf("too few Create calls: got %d, want >= %d", nCreate, N/10) } if nRefresh < N/10 { t.Fatalf("too few Refresh calls: got %d, want >= %d", nRefresh, N/10) } if nUnlock < N/10 { t.Fatalf("too few Unlock calls: got %d, want >= %d", nUnlock, N/10) } } func (m *memLS) consistent() error { m.mu.Lock() defer m.mu.Unlock() // If m.byName is non-empty, then it must contain an entry for the root "/", // and its refCount should equal the number of locked nodes. if len(m.byName) > 0 { n := m.byName["/"] if n == nil { return fmt.Errorf(`non-empty m.byName does not contain the root "/"`) } if n.refCount != len(m.byToken) { return fmt.Errorf("root node refCount=%d, differs from len(m.byToken)=%d", n.refCount, len(m.byToken)) } } for name, n := range m.byName { // The map keys should be consistent with the node's copy of the key. if n.details.Root != name { return fmt.Errorf("node name %q != byName map key %q", n.details.Root, name) } // A name must be clean, and start with a "/". if len(name) == 0 || name[0] != '/' { return fmt.Errorf(`node name %q does not start with "/"`, name) } if name != path.Clean(name) { return fmt.Errorf(`node name %q is not clean`, name) } // A node's refCount should be positive. if n.refCount <= 0 { return fmt.Errorf("non-positive refCount for node at name %q", name) } // A node's refCount should be the number of self-or-descendents that // are locked (i.e. have a non-empty token). var list []string for name0, n0 := range m.byName { // All of lockTestNames' name fragments are one byte long: '_', 'i' or 'z', // so strings.HasPrefix is equivalent to self-or-descendent name match. // We don't have to worry about "/foo/bar" being a false positive match // for "/foo/b". if strings.HasPrefix(name0, name) && n0.token != "" { list = append(list, name0) } } if n.refCount != len(list) { sort.Strings(list) return fmt.Errorf("node at name %q has refCount %d but locked self-or-descendents are %q (len=%d)", name, n.refCount, list, len(list)) } // A node n is in m.byToken if it has a non-empty token. if n.token != "" { if _, ok := m.byToken[n.token]; !ok { return fmt.Errorf("node at name %q has token %q but not in m.byToken", name, n.token) } } // A node n is in m.byExpiry if it has a non-negative byExpiryIndex. if n.byExpiryIndex >= 0 { if n.byExpiryIndex >= len(m.byExpiry) { return fmt.Errorf("node at name %q has byExpiryIndex %d but m.byExpiry has length %d", name, n.byExpiryIndex, len(m.byExpiry)) } if n != m.byExpiry[n.byExpiryIndex] { return fmt.Errorf("node at name %q has byExpiryIndex %d but that indexes a different node", name, n.byExpiryIndex) } } } for token, n := range m.byToken { // The map keys should be consistent with the node's copy of the key. if n.token != token { return fmt.Errorf("node token %q != byToken map key %q", n.token, token) } // Every node in m.byToken is in m.byName. if _, ok := m.byName[n.details.Root]; !ok { return fmt.Errorf("node at name %q in m.byToken but not in m.byName", n.details.Root) } } for i, n := range m.byExpiry { // The slice indices should be consistent with the node's copy of the index. if n.byExpiryIndex != i { return fmt.Errorf("node byExpiryIndex %d != byExpiry slice index %d", n.byExpiryIndex, i) } // Every node in m.byExpiry is in m.byName. if _, ok := m.byName[n.details.Root]; !ok { return fmt.Errorf("node at name %q in m.byExpiry but not in m.byName", n.details.Root) } // No node in m.byExpiry should be held. if n.held { return fmt.Errorf("node at name %q in m.byExpiry is held", n.details.Root) } } return nil } func TestParseTimeout(t *testing.T) { testCases := []struct { s string want time.Duration wantErr error }{{ "", infiniteTimeout, nil, }, { "Infinite", infiniteTimeout, nil, }, { "Infinitesimal", 0, errInvalidTimeout, }, { "infinite", 0, errInvalidTimeout, }, { "Second-0", 0 * time.Second, nil, }, { "Second-123", 123 * time.Second, nil, }, { " Second-456 ", 456 * time.Second, nil, }, { "Second-4100000000", 4100000000 * time.Second, nil, }, { "junk", 0, errInvalidTimeout, }, { "Second-", 0, errInvalidTimeout, }, { "Second--1", 0, errInvalidTimeout, }, { "Second--123", 0, errInvalidTimeout, }, { "Second-+123", 0, errInvalidTimeout, }, { "Second-0x123", 0, errInvalidTimeout, }, { "second-123", 0, errInvalidTimeout, }, { "Second-4294967295", 4294967295 * time.Second, nil, }, { // Section 10.7 says that "The timeout value for TimeType "Second" // must not be greater than 2^32-1." "Second-4294967296", 0, errInvalidTimeout, }, { // This test case comes from section 9.10.9 of the spec. It says, // // "In this request, the client has specified that it desires an // infinite-length lock, if available, otherwise a timeout of 4.1 // billion seconds, if available." // // The Go WebDAV package always supports infinite length locks, // and ignores the fallback after the comma. "Infinite, Second-4100000000", infiniteTimeout, nil, }} for _, tc := range testCases { got, gotErr := parseTimeout(tc.s) if got != tc.want || gotErr != tc.wantErr { t.Errorf("parsing %q:\ngot %v, %v\nwant %v, %v", tc.s, got, gotErr, tc.want, tc.wantErr) } } } ================================================ FILE: vendor/golang.org/x/net/webdav/prop.go ================================================ // 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 webdav import ( "fmt" "io" "mime" "net/http" "os" "path/filepath" "strconv" "golang.org/x/net/webdav/internal/xml" ) // Proppatch describes a property update instruction as defined in RFC 4918. // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPPATCH type Proppatch struct { // Remove specifies whether this patch removes properties. If it does not // remove them, it sets them. Remove bool // Props contains the properties to be set or removed. Props []Property } // Propstat describes a XML propstat element as defined in RFC 4918. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat type Propstat struct { // Props contains the properties for which Status applies. Props []Property // Status defines the HTTP status code of the properties in Prop. // Allowed values include, but are not limited to the WebDAV status // code extensions for HTTP/1.1. // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11 Status int // XMLError contains the XML representation of the optional error element. // XML content within this field must not rely on any predefined // namespace declarations or prefixes. If empty, the XML error element // is omitted. XMLError string // ResponseDescription contains the contents of the optional // responsedescription field. If empty, the XML element is omitted. ResponseDescription string } // makePropstats returns a slice containing those of x and y whose Props slice // is non-empty. If both are empty, it returns a slice containing an otherwise // zero Propstat whose HTTP status code is 200 OK. func makePropstats(x, y Propstat) []Propstat { pstats := make([]Propstat, 0, 2) if len(x.Props) != 0 { pstats = append(pstats, x) } if len(y.Props) != 0 { pstats = append(pstats, y) } if len(pstats) == 0 { pstats = append(pstats, Propstat{ Status: http.StatusOK, }) } return pstats } // DeadPropsHolder holds the dead properties of a resource. // // Dead properties are those properties that are explicitly defined. In // comparison, live properties, such as DAV:getcontentlength, are implicitly // defined by the underlying resource, and cannot be explicitly overridden or // removed. See the Terminology section of // http://www.webdav.org/specs/rfc4918.html#rfc.section.3 // // There is a whitelist of the names of live properties. This package handles // all live properties, and will only pass non-whitelisted names to the Patch // method of DeadPropsHolder implementations. type DeadPropsHolder interface { // DeadProps returns a copy of the dead properties held. DeadProps() (map[xml.Name]Property, error) // Patch patches the dead properties held. // // Patching is atomic; either all or no patches succeed. It returns (nil, // non-nil) if an internal server error occurred, otherwise the Propstats // collectively contain one Property for each proposed patch Property. If // all patches succeed, Patch returns a slice of length one and a Propstat // element with a 200 OK HTTP status code. If none succeed, for reasons // other than an internal server error, no Propstat has status 200 OK. // // For more details on when various HTTP status codes apply, see // http://www.webdav.org/specs/rfc4918.html#PROPPATCH-status Patch([]Proppatch) ([]Propstat, error) } // liveProps contains all supported, protected DAV: properties. var liveProps = map[xml.Name]struct { // findFn implements the propfind function of this property. If nil, // it indicates a hidden property. findFn func(FileSystem, LockSystem, string, os.FileInfo) (string, error) // dir is true if the property applies to directories. dir bool }{ xml.Name{Space: "DAV:", Local: "resourcetype"}: { findFn: findResourceType, dir: true, }, xml.Name{Space: "DAV:", Local: "displayname"}: { findFn: findDisplayName, dir: true, }, xml.Name{Space: "DAV:", Local: "getcontentlength"}: { findFn: findContentLength, dir: true, }, xml.Name{Space: "DAV:", Local: "getlastmodified"}: { findFn: findLastModified, dir: true, }, xml.Name{Space: "DAV:", Local: "creationdate"}: { findFn: nil, dir: true, }, xml.Name{Space: "DAV:", Local: "getcontentlanguage"}: { findFn: nil, dir: true, }, xml.Name{Space: "DAV:", Local: "getcontenttype"}: { findFn: findContentType, dir: true, }, xml.Name{Space: "DAV:", Local: "getetag"}: { findFn: findETag, // findETag implements ETag as the concatenated hex values of a file's // modification time and size. This is not a reliable synchronization // mechanism for directories, so we do not advertise getetag for DAV // collections. dir: false, }, // TODO: The lockdiscovery property requires LockSystem to list the // active locks on a resource. xml.Name{Space: "DAV:", Local: "lockdiscovery"}: {}, xml.Name{Space: "DAV:", Local: "supportedlock"}: { findFn: findSupportedLock, dir: true, }, } // TODO(nigeltao) merge props and allprop? // Props returns the status of the properties named pnames for resource name. // // Each Propstat has a unique status and each property name will only be part // of one Propstat element. func props(fs FileSystem, ls LockSystem, name string, pnames []xml.Name) ([]Propstat, error) { f, err := fs.OpenFile(name, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } isDir := fi.IsDir() var deadProps map[xml.Name]Property if dph, ok := f.(DeadPropsHolder); ok { deadProps, err = dph.DeadProps() if err != nil { return nil, err } } pstatOK := Propstat{Status: http.StatusOK} pstatNotFound := Propstat{Status: http.StatusNotFound} for _, pn := range pnames { // If this file has dead properties, check if they contain pn. if dp, ok := deadProps[pn]; ok { pstatOK.Props = append(pstatOK.Props, dp) continue } // Otherwise, it must either be a live property or we don't know it. if prop := liveProps[pn]; prop.findFn != nil && (prop.dir || !isDir) { innerXML, err := prop.findFn(fs, ls, name, fi) if err != nil { return nil, err } pstatOK.Props = append(pstatOK.Props, Property{ XMLName: pn, InnerXML: []byte(innerXML), }) } else { pstatNotFound.Props = append(pstatNotFound.Props, Property{ XMLName: pn, }) } } return makePropstats(pstatOK, pstatNotFound), nil } // Propnames returns the property names defined for resource name. func propnames(fs FileSystem, ls LockSystem, name string) ([]xml.Name, error) { f, err := fs.OpenFile(name, os.O_RDONLY, 0) if err != nil { return nil, err } defer f.Close() fi, err := f.Stat() if err != nil { return nil, err } isDir := fi.IsDir() var deadProps map[xml.Name]Property if dph, ok := f.(DeadPropsHolder); ok { deadProps, err = dph.DeadProps() if err != nil { return nil, err } } pnames := make([]xml.Name, 0, len(liveProps)+len(deadProps)) for pn, prop := range liveProps { if prop.findFn != nil && (prop.dir || !isDir) { pnames = append(pnames, pn) } } for pn := range deadProps { pnames = append(pnames, pn) } return pnames, nil } // Allprop returns the properties defined for resource name and the properties // named in include. // // Note that RFC 4918 defines 'allprop' to return the DAV: properties defined // within the RFC plus dead properties. Other live properties should only be // returned if they are named in 'include'. // // See http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND func allprop(fs FileSystem, ls LockSystem, name string, include []xml.Name) ([]Propstat, error) { pnames, err := propnames(fs, ls, name) if err != nil { return nil, err } // Add names from include if they are not already covered in pnames. nameset := make(map[xml.Name]bool) for _, pn := range pnames { nameset[pn] = true } for _, pn := range include { if !nameset[pn] { pnames = append(pnames, pn) } } return props(fs, ls, name, pnames) } // Patch patches the properties of resource name. The return values are // constrained in the same manner as DeadPropsHolder.Patch. func patch(fs FileSystem, ls LockSystem, name string, patches []Proppatch) ([]Propstat, error) { conflict := false loop: for _, patch := range patches { for _, p := range patch.Props { if _, ok := liveProps[p.XMLName]; ok { conflict = true break loop } } } if conflict { pstatForbidden := Propstat{ Status: http.StatusForbidden, XMLError: ``, } pstatFailedDep := Propstat{ Status: StatusFailedDependency, } for _, patch := range patches { for _, p := range patch.Props { if _, ok := liveProps[p.XMLName]; ok { pstatForbidden.Props = append(pstatForbidden.Props, Property{XMLName: p.XMLName}) } else { pstatFailedDep.Props = append(pstatFailedDep.Props, Property{XMLName: p.XMLName}) } } } return makePropstats(pstatForbidden, pstatFailedDep), nil } f, err := fs.OpenFile(name, os.O_RDWR, 0) if err != nil { return nil, err } defer f.Close() if dph, ok := f.(DeadPropsHolder); ok { ret, err := dph.Patch(patches) if err != nil { return nil, err } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat says that // "The contents of the prop XML element must only list the names of // properties to which the result in the status element applies." for _, pstat := range ret { for i, p := range pstat.Props { pstat.Props[i] = Property{XMLName: p.XMLName} } } return ret, nil } // The file doesn't implement the optional DeadPropsHolder interface, so // all patches are forbidden. pstat := Propstat{Status: http.StatusForbidden} for _, patch := range patches { for _, p := range patch.Props { pstat.Props = append(pstat.Props, Property{XMLName: p.XMLName}) } } return []Propstat{pstat}, nil } func findResourceType(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { if fi.IsDir() { return ``, nil } return "", nil } func findDisplayName(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { if slashClean(name) == "/" { // Hide the real name of a possibly prefixed root directory. return "", nil } return fi.Name(), nil } func findContentLength(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { return strconv.FormatInt(fi.Size(), 10), nil } func findLastModified(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { return fi.ModTime().Format(http.TimeFormat), nil } func findContentType(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { f, err := fs.OpenFile(name, os.O_RDONLY, 0) if err != nil { return "", err } defer f.Close() // This implementation is based on serveContent's code in the standard net/http package. ctype := mime.TypeByExtension(filepath.Ext(name)) if ctype == "" { // Read a chunk to decide between utf-8 text and binary. var buf [512]byte n, _ := io.ReadFull(f, buf[:]) ctype = http.DetectContentType(buf[:n]) // Rewind file. _, err = f.Seek(0, os.SEEK_SET) } return ctype, err } func findETag(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { // The Apache http 2.4 web server by default concatenates the // modification time and size of a file. We replicate the heuristic // with nanosecond granularity. return fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size()), nil } func findSupportedLock(fs FileSystem, ls LockSystem, name string, fi os.FileInfo) (string, error) { return `` + `` + `` + `` + ``, nil } ================================================ FILE: vendor/golang.org/x/net/webdav/prop_test.go ================================================ // 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 webdav import ( "fmt" "net/http" "os" "reflect" "sort" "testing" "golang.org/x/net/webdav/internal/xml" ) func TestMemPS(t *testing.T) { // calcProps calculates the getlastmodified and getetag DAV: property // values in pstats for resource name in file-system fs. calcProps := func(name string, fs FileSystem, ls LockSystem, pstats []Propstat) error { fi, err := fs.Stat(name) if err != nil { return err } for _, pst := range pstats { for i, p := range pst.Props { switch p.XMLName { case xml.Name{Space: "DAV:", Local: "getlastmodified"}: p.InnerXML = []byte(fi.ModTime().Format(http.TimeFormat)) pst.Props[i] = p case xml.Name{Space: "DAV:", Local: "getetag"}: if fi.IsDir() { continue } etag, err := findETag(fs, ls, name, fi) if err != nil { return err } p.InnerXML = []byte(etag) pst.Props[i] = p } } } return nil } const ( lockEntry = `` + `` + `` + `` + `` statForbiddenError = `` ) type propOp struct { op string name string pnames []xml.Name patches []Proppatch wantPnames []xml.Name wantPropstats []Propstat } testCases := []struct { desc string noDeadProps bool buildfs []string propOp []propOp }{{ desc: "propname", buildfs: []string{"mkdir /dir", "touch /file"}, propOp: []propOp{{ op: "propname", name: "/dir", wantPnames: []xml.Name{ xml.Name{Space: "DAV:", Local: "resourcetype"}, xml.Name{Space: "DAV:", Local: "displayname"}, xml.Name{Space: "DAV:", Local: "getcontentlength"}, xml.Name{Space: "DAV:", Local: "getlastmodified"}, xml.Name{Space: "DAV:", Local: "getcontenttype"}, xml.Name{Space: "DAV:", Local: "supportedlock"}, }, }, { op: "propname", name: "/file", wantPnames: []xml.Name{ xml.Name{Space: "DAV:", Local: "resourcetype"}, xml.Name{Space: "DAV:", Local: "displayname"}, xml.Name{Space: "DAV:", Local: "getcontentlength"}, xml.Name{Space: "DAV:", Local: "getlastmodified"}, xml.Name{Space: "DAV:", Local: "getcontenttype"}, xml.Name{Space: "DAV:", Local: "getetag"}, xml.Name{Space: "DAV:", Local: "supportedlock"}, }, }}, }, { desc: "allprop dir and file", buildfs: []string{"mkdir /dir", "write /file foobarbaz"}, propOp: []propOp{{ op: "allprop", name: "/dir", wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(``), }, { XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("dir"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, InnerXML: []byte("0"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, InnerXML: []byte("text/plain; charset=utf-8"), }, { XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, InnerXML: []byte(lockEntry), }}, }}, }, { op: "allprop", name: "/file", wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(""), }, { XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("file"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, InnerXML: []byte("9"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, InnerXML: []byte("text/plain; charset=utf-8"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, InnerXML: []byte(lockEntry), }}, }}, }, { op: "allprop", name: "/file", pnames: []xml.Name{ {"DAV:", "resourcetype"}, {"foo", "bar"}, }, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(""), }, { XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("file"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontentlength"}, InnerXML: []byte("9"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getlastmodified"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "getcontenttype"}, InnerXML: []byte("text/plain; charset=utf-8"), }, { XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, InnerXML: nil, // Calculated during test. }, { XMLName: xml.Name{Space: "DAV:", Local: "supportedlock"}, InnerXML: []byte(lockEntry), }}}, { Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}}, }, }}, }, { desc: "propfind DAV:resourcetype", buildfs: []string{"mkdir /dir", "touch /file"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "resourcetype"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(``), }}, }}, }, { op: "propfind", name: "/file", pnames: []xml.Name{{"DAV:", "resourcetype"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "resourcetype"}, InnerXML: []byte(""), }}, }}, }}, }, { desc: "propfind unsupported DAV properties", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "getcontentlanguage"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getcontentlanguage"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "creationdate"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "creationdate"}, }}, }}, }}, }, { desc: "propfind getetag for files but not for directories", buildfs: []string{"mkdir /dir", "touch /file"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"DAV:", "getetag"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, }}, }}, }, { op: "propfind", name: "/file", pnames: []xml.Name{{"DAV:", "getetag"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, InnerXML: nil, // Calculated during test. }}, }}, }}, }, { desc: "proppatch property on no-dead-properties file system", buildfs: []string{"mkdir /dir"}, noDeadProps: true, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusForbidden, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusForbidden, XMLError: statForbiddenError, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "getetag"}, }}, }}, }}, }, { desc: "proppatch dead property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{{Space: "foo", Local: "bar"}}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }}, }}, }, { desc: "proppatch dead property with failed dependency", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }, { Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, InnerXML: []byte("xxx"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusForbidden, XMLError: statForbiddenError, Props: []Property{{ XMLName: xml.Name{Space: "DAV:", Local: "displayname"}, }}, }, { Status: StatusFailedDependency, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{{Space: "foo", Local: "bar"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }}, }, { desc: "proppatch remove dead property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }, { XMLName: xml.Name{Space: "spam", Local: "ham"}, InnerXML: []byte("eggs"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }, { XMLName: xml.Name{Space: "spam", Local: "ham"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{ {Space: "foo", Local: "bar"}, {Space: "spam", Local: "ham"}, }, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }, { XMLName: xml.Name{Space: "spam", Local: "ham"}, InnerXML: []byte("eggs"), }}, }}, }, { op: "proppatch", name: "/dir", patches: []Proppatch{{ Remove: true, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propfind", name: "/dir", pnames: []xml.Name{ {Space: "foo", Local: "bar"}, {Space: "spam", Local: "ham"}, }, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }, { Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "spam", Local: "ham"}, InnerXML: []byte("eggs"), }}, }}, }}, }, { desc: "propname with dead property", buildfs: []string{"touch /file"}, propOp: []propOp{{ op: "proppatch", name: "/file", patches: []Proppatch{{ Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, InnerXML: []byte("baz"), }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }, { op: "propname", name: "/file", wantPnames: []xml.Name{ xml.Name{Space: "DAV:", Local: "resourcetype"}, xml.Name{Space: "DAV:", Local: "displayname"}, xml.Name{Space: "DAV:", Local: "getcontentlength"}, xml.Name{Space: "DAV:", Local: "getlastmodified"}, xml.Name{Space: "DAV:", Local: "getcontenttype"}, xml.Name{Space: "DAV:", Local: "getetag"}, xml.Name{Space: "DAV:", Local: "supportedlock"}, xml.Name{Space: "foo", Local: "bar"}, }, }}, }, { desc: "proppatch remove unknown dead property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "proppatch", name: "/dir", patches: []Proppatch{{ Remove: true, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, wantPropstats: []Propstat{{ Status: http.StatusOK, Props: []Property{{ XMLName: xml.Name{Space: "foo", Local: "bar"}, }}, }}, }}, }, { desc: "bad: propfind unknown property", buildfs: []string{"mkdir /dir"}, propOp: []propOp{{ op: "propfind", name: "/dir", pnames: []xml.Name{{"foo:", "bar"}}, wantPropstats: []Propstat{{ Status: http.StatusNotFound, Props: []Property{{ XMLName: xml.Name{Space: "foo:", Local: "bar"}, }}, }}, }}, }} for _, tc := range testCases { fs, err := buildTestFS(tc.buildfs) if err != nil { t.Fatalf("%s: cannot create test filesystem: %v", tc.desc, err) } if tc.noDeadProps { fs = noDeadPropsFS{fs} } ls := NewMemLS() for _, op := range tc.propOp { desc := fmt.Sprintf("%s: %s %s", tc.desc, op.op, op.name) if err = calcProps(op.name, fs, ls, op.wantPropstats); err != nil { t.Fatalf("%s: calcProps: %v", desc, err) } // Call property system. var propstats []Propstat switch op.op { case "propname": pnames, err := propnames(fs, ls, op.name) if err != nil { t.Errorf("%s: got error %v, want nil", desc, err) continue } sort.Sort(byXMLName(pnames)) sort.Sort(byXMLName(op.wantPnames)) if !reflect.DeepEqual(pnames, op.wantPnames) { t.Errorf("%s: pnames\ngot %q\nwant %q", desc, pnames, op.wantPnames) } continue case "allprop": propstats, err = allprop(fs, ls, op.name, op.pnames) case "propfind": propstats, err = props(fs, ls, op.name, op.pnames) case "proppatch": propstats, err = patch(fs, ls, op.name, op.patches) default: t.Fatalf("%s: %s not implemented", desc, op.op) } if err != nil { t.Errorf("%s: got error %v, want nil", desc, err) continue } // Compare return values from allprop, propfind or proppatch. for _, pst := range propstats { sort.Sort(byPropname(pst.Props)) } for _, pst := range op.wantPropstats { sort.Sort(byPropname(pst.Props)) } sort.Sort(byStatus(propstats)) sort.Sort(byStatus(op.wantPropstats)) if !reflect.DeepEqual(propstats, op.wantPropstats) { t.Errorf("%s: propstat\ngot %q\nwant %q", desc, propstats, op.wantPropstats) } } } } func cmpXMLName(a, b xml.Name) bool { if a.Space != b.Space { return a.Space < b.Space } return a.Local < b.Local } type byXMLName []xml.Name func (b byXMLName) Len() int { return len(b) } func (b byXMLName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byXMLName) Less(i, j int) bool { return cmpXMLName(b[i], b[j]) } type byPropname []Property func (b byPropname) Len() int { return len(b) } func (b byPropname) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byPropname) Less(i, j int) bool { return cmpXMLName(b[i].XMLName, b[j].XMLName) } type byStatus []Propstat func (b byStatus) Len() int { return len(b) } func (b byStatus) Swap(i, j int) { b[i], b[j] = b[j], b[i] } func (b byStatus) Less(i, j int) bool { return b[i].Status < b[j].Status } type noDeadPropsFS struct { FileSystem } func (fs noDeadPropsFS) OpenFile(name string, flag int, perm os.FileMode) (File, error) { f, err := fs.FileSystem.OpenFile(name, flag, perm) if err != nil { return nil, err } return noDeadPropsFile{f}, nil } // noDeadPropsFile wraps a File but strips any optional DeadPropsHolder methods // provided by the underlying File implementation. type noDeadPropsFile struct { f File } func (f noDeadPropsFile) Close() error { return f.f.Close() } func (f noDeadPropsFile) Read(p []byte) (int, error) { return f.f.Read(p) } func (f noDeadPropsFile) Readdir(count int) ([]os.FileInfo, error) { return f.f.Readdir(count) } func (f noDeadPropsFile) Seek(off int64, whence int) (int64, error) { return f.f.Seek(off, whence) } func (f noDeadPropsFile) Stat() (os.FileInfo, error) { return f.f.Stat() } func (f noDeadPropsFile) Write(p []byte) (int, error) { return f.f.Write(p) } ================================================ FILE: vendor/golang.org/x/net/webdav/webdav.go ================================================ // 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 webdav etc etc TODO. package webdav // import "golang.org/x/net/webdav" import ( "errors" "fmt" "io" "log" "net/http" "net/url" "os" "path" "runtime" "strings" "time" ) // Package webdav's XML output requires the standard library's encoding/xml // package version 1.5 or greater. Otherwise, it will produce malformed XML. // // As of May 2015, the Go stable release is version 1.4, so we print a message // to let users know that this golang.org/x/etc package won't work yet. // // This package also won't work with Go 1.3 and earlier, but making this // runtime version check catch all the earlier versions too, and not just // "1.4.x", isn't worth the complexity. // // TODO: delete this check at some point after Go 1.5 is released. var go1Dot4 = strings.HasPrefix(runtime.Version(), "go1.4.") func init() { if go1Dot4 { log.Println("package webdav requires Go version 1.5 or greater") } } type Handler struct { // Prefix is the URL path prefix to strip from WebDAV resource paths. Prefix string // FileSystem is the virtual file system. FileSystem FileSystem // LockSystem is the lock management system. LockSystem LockSystem // Logger is an optional error logger. If non-nil, it will be called // for all HTTP requests. Logger func(*http.Request, error) } func (h *Handler) stripPrefix(p string) (string, int, error) { if h.Prefix == "" { return p, http.StatusOK, nil } if r := strings.TrimPrefix(p, h.Prefix); len(r) < len(p) { return r, http.StatusOK, nil } return p, http.StatusNotFound, errPrefixMismatch } func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { status, err := http.StatusBadRequest, errUnsupportedMethod if h.FileSystem == nil { status, err = http.StatusInternalServerError, errNoFileSystem } else if h.LockSystem == nil { status, err = http.StatusInternalServerError, errNoLockSystem } else { switch r.Method { case "OPTIONS": status, err = h.handleOptions(w, r) case "GET", "HEAD", "POST": status, err = h.handleGetHeadPost(w, r) case "DELETE": status, err = h.handleDelete(w, r) case "PUT": status, err = h.handlePut(w, r) case "MKCOL": status, err = h.handleMkcol(w, r) case "COPY", "MOVE": status, err = h.handleCopyMove(w, r) case "LOCK": status, err = h.handleLock(w, r) case "UNLOCK": status, err = h.handleUnlock(w, r) case "PROPFIND": status, err = h.handlePropfind(w, r) case "PROPPATCH": status, err = h.handleProppatch(w, r) } } if status != 0 { w.WriteHeader(status) if status != http.StatusNoContent { w.Write([]byte(StatusText(status))) } } if h.Logger != nil { h.Logger(r, err) } } func (h *Handler) lock(now time.Time, root string) (token string, status int, err error) { token, err = h.LockSystem.Create(now, LockDetails{ Root: root, Duration: infiniteTimeout, ZeroDepth: true, }) if err != nil { if err == ErrLocked { return "", StatusLocked, err } return "", http.StatusInternalServerError, err } return token, 0, nil } func (h *Handler) confirmLocks(r *http.Request, src, dst string) (release func(), status int, err error) { hdr := r.Header.Get("If") if hdr == "" { // An empty If header means that the client hasn't previously created locks. // Even if this client doesn't care about locks, we still need to check that // the resources aren't locked by another client, so we create temporary // locks that would conflict with another client's locks. These temporary // locks are unlocked at the end of the HTTP request. now, srcToken, dstToken := time.Now(), "", "" if src != "" { srcToken, status, err = h.lock(now, src) if err != nil { return nil, status, err } } if dst != "" { dstToken, status, err = h.lock(now, dst) if err != nil { if srcToken != "" { h.LockSystem.Unlock(now, srcToken) } return nil, status, err } } return func() { if dstToken != "" { h.LockSystem.Unlock(now, dstToken) } if srcToken != "" { h.LockSystem.Unlock(now, srcToken) } }, 0, nil } ih, ok := parseIfHeader(hdr) if !ok { return nil, http.StatusBadRequest, errInvalidIfHeader } // ih is a disjunction (OR) of ifLists, so any ifList will do. for _, l := range ih.lists { lsrc := l.resourceTag if lsrc == "" { lsrc = src } else { u, err := url.Parse(lsrc) if err != nil { continue } if u.Host != r.Host { continue } lsrc = u.Path } release, err = h.LockSystem.Confirm(time.Now(), lsrc, dst, l.conditions...) if err == ErrConfirmationFailed { continue } if err != nil { return nil, http.StatusInternalServerError, err } return release, 0, nil } // Section 10.4.1 says that "If this header is evaluated and all state lists // fail, then the request must fail with a 412 (Precondition Failed) status." // We follow the spec even though the cond_put_corrupt_token test case from // the litmus test warns on seeing a 412 instead of a 423 (Locked). return nil, http.StatusPreconditionFailed, ErrLocked } func (h *Handler) handleOptions(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } allow := "OPTIONS, LOCK, PUT, MKCOL" if fi, err := h.FileSystem.Stat(reqPath); err == nil { if fi.IsDir() { allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND" } else { allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND, PUT" } } w.Header().Set("Allow", allow) // http://www.webdav.org/specs/rfc4918.html#dav.compliance.classes w.Header().Set("DAV", "1, 2") // http://msdn.microsoft.com/en-au/library/cc250217.aspx w.Header().Set("MS-Author-Via", "DAV") return 0, nil } func (h *Handler) handleGetHeadPost(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } // TODO: check locks for read-only access?? f, err := h.FileSystem.OpenFile(reqPath, os.O_RDONLY, 0) if err != nil { return http.StatusNotFound, err } defer f.Close() fi, err := f.Stat() if err != nil { return http.StatusNotFound, err } if !fi.IsDir() { etag, err := findETag(h.FileSystem, h.LockSystem, reqPath, fi) if err != nil { return http.StatusInternalServerError, err } w.Header().Set("ETag", etag) } // Let ServeContent determine the Content-Type header. http.ServeContent(w, r, reqPath, fi.ModTime(), f) return 0, nil } func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } release, status, err := h.confirmLocks(r, reqPath, "") if err != nil { return status, err } defer release() // TODO: return MultiStatus where appropriate. // "godoc os RemoveAll" says that "If the path does not exist, RemoveAll // returns nil (no error)." WebDAV semantics are that it should return a // "404 Not Found". We therefore have to Stat before we RemoveAll. if _, err := h.FileSystem.Stat(reqPath); err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusMethodNotAllowed, err } if err := h.FileSystem.RemoveAll(reqPath); err != nil { return http.StatusMethodNotAllowed, err } return http.StatusNoContent, nil } func (h *Handler) handlePut(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } release, status, err := h.confirmLocks(r, reqPath, "") if err != nil { return status, err } defer release() // TODO(rost): Support the If-Match, If-None-Match headers? See bradfitz' // comments in http.checkEtag. f, err := h.FileSystem.OpenFile(reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { return http.StatusNotFound, err } _, copyErr := io.Copy(f, r.Body) fi, statErr := f.Stat() closeErr := f.Close() // TODO(rost): Returning 405 Method Not Allowed might not be appropriate. if copyErr != nil { return http.StatusMethodNotAllowed, copyErr } if statErr != nil { return http.StatusMethodNotAllowed, statErr } if closeErr != nil { return http.StatusMethodNotAllowed, closeErr } etag, err := findETag(h.FileSystem, h.LockSystem, reqPath, fi) if err != nil { return http.StatusInternalServerError, err } w.Header().Set("ETag", etag) return http.StatusCreated, nil } func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } release, status, err := h.confirmLocks(r, reqPath, "") if err != nil { return status, err } defer release() if r.ContentLength > 0 { return http.StatusUnsupportedMediaType, nil } if err := h.FileSystem.Mkdir(reqPath, 0777); err != nil { if os.IsNotExist(err) { return http.StatusConflict, err } return http.StatusMethodNotAllowed, err } return http.StatusCreated, nil } func (h *Handler) handleCopyMove(w http.ResponseWriter, r *http.Request) (status int, err error) { hdr := r.Header.Get("Destination") if hdr == "" { return http.StatusBadRequest, errInvalidDestination } u, err := url.Parse(hdr) if err != nil { return http.StatusBadRequest, errInvalidDestination } if u.Host != r.Host { return http.StatusBadGateway, errInvalidDestination } src, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } dst, status, err := h.stripPrefix(u.Path) if err != nil { return status, err } if dst == "" { return http.StatusBadGateway, errInvalidDestination } if dst == src { return http.StatusForbidden, errDestinationEqualsSource } if r.Method == "COPY" { // Section 7.5.1 says that a COPY only needs to lock the destination, // not both destination and source. Strictly speaking, this is racy, // even though a COPY doesn't modify the source, if a concurrent // operation modifies the source. However, the litmus test explicitly // checks that COPYing a locked-by-another source is OK. release, status, err := h.confirmLocks(r, "", dst) if err != nil { return status, err } defer release() // Section 9.8.3 says that "The COPY method on a collection without a Depth // header must act as if a Depth header with value "infinity" was included". depth := infiniteDepth if hdr := r.Header.Get("Depth"); hdr != "" { depth = parseDepth(hdr) if depth != 0 && depth != infiniteDepth { // Section 9.8.3 says that "A client may submit a Depth header on a // COPY on a collection with a value of "0" or "infinity"." return http.StatusBadRequest, errInvalidDepth } } return copyFiles(h.FileSystem, src, dst, r.Header.Get("Overwrite") != "F", depth, 0) } release, status, err := h.confirmLocks(r, src, dst) if err != nil { return status, err } defer release() // Section 9.9.2 says that "The MOVE method on a collection must act as if // a "Depth: infinity" header was used on it. A client must not submit a // Depth header on a MOVE on a collection with any value but "infinity"." if hdr := r.Header.Get("Depth"); hdr != "" { if parseDepth(hdr) != infiniteDepth { return http.StatusBadRequest, errInvalidDepth } } return moveFiles(h.FileSystem, src, dst, r.Header.Get("Overwrite") == "T") } func (h *Handler) handleLock(w http.ResponseWriter, r *http.Request) (retStatus int, retErr error) { duration, err := parseTimeout(r.Header.Get("Timeout")) if err != nil { return http.StatusBadRequest, err } li, status, err := readLockInfo(r.Body) if err != nil { return status, err } token, ld, now, created := "", LockDetails{}, time.Now(), false if li == (lockInfo{}) { // An empty lockInfo means to refresh the lock. ih, ok := parseIfHeader(r.Header.Get("If")) if !ok { return http.StatusBadRequest, errInvalidIfHeader } if len(ih.lists) == 1 && len(ih.lists[0].conditions) == 1 { token = ih.lists[0].conditions[0].Token } if token == "" { return http.StatusBadRequest, errInvalidLockToken } ld, err = h.LockSystem.Refresh(now, token, duration) if err != nil { if err == ErrNoSuchLock { return http.StatusPreconditionFailed, err } return http.StatusInternalServerError, err } } else { // Section 9.10.3 says that "If no Depth header is submitted on a LOCK request, // then the request MUST act as if a "Depth:infinity" had been submitted." depth := infiniteDepth if hdr := r.Header.Get("Depth"); hdr != "" { depth = parseDepth(hdr) if depth != 0 && depth != infiniteDepth { // Section 9.10.3 says that "Values other than 0 or infinity must not be // used with the Depth header on a LOCK method". return http.StatusBadRequest, errInvalidDepth } } reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } ld = LockDetails{ Root: reqPath, Duration: duration, OwnerXML: li.Owner.InnerXML, ZeroDepth: depth == 0, } token, err = h.LockSystem.Create(now, ld) if err != nil { if err == ErrLocked { return StatusLocked, err } return http.StatusInternalServerError, err } defer func() { if retErr != nil { h.LockSystem.Unlock(now, token) } }() // Create the resource if it didn't previously exist. if _, err := h.FileSystem.Stat(reqPath); err != nil { f, err := h.FileSystem.OpenFile(reqPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { // TODO: detect missing intermediate dirs and return http.StatusConflict? return http.StatusInternalServerError, err } f.Close() created = true } // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the // Lock-Token value is a Coded-URL. We add angle brackets. w.Header().Set("Lock-Token", "<"+token+">") } w.Header().Set("Content-Type", "application/xml; charset=utf-8") if created { // This is "w.WriteHeader(http.StatusCreated)" and not "return // http.StatusCreated, nil" because we write our own (XML) response to w // and Handler.ServeHTTP would otherwise write "Created". w.WriteHeader(http.StatusCreated) } writeLockInfo(w, token, ld) return 0, nil } func (h *Handler) handleUnlock(w http.ResponseWriter, r *http.Request) (status int, err error) { // http://www.webdav.org/specs/rfc4918.html#HEADER_Lock-Token says that the // Lock-Token value is a Coded-URL. We strip its angle brackets. t := r.Header.Get("Lock-Token") if len(t) < 2 || t[0] != '<' || t[len(t)-1] != '>' { return http.StatusBadRequest, errInvalidLockToken } t = t[1 : len(t)-1] switch err = h.LockSystem.Unlock(time.Now(), t); err { case nil: return http.StatusNoContent, err case ErrForbidden: return http.StatusForbidden, err case ErrLocked: return StatusLocked, err case ErrNoSuchLock: return http.StatusConflict, err default: return http.StatusInternalServerError, err } } func (h *Handler) handlePropfind(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } fi, err := h.FileSystem.Stat(reqPath) if err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusMethodNotAllowed, err } depth := infiniteDepth if hdr := r.Header.Get("Depth"); hdr != "" { depth = parseDepth(hdr) if depth == invalidDepth { return http.StatusBadRequest, errInvalidDepth } } pf, status, err := readPropfind(r.Body) if err != nil { return status, err } mw := multistatusWriter{w: w} walkFn := func(reqPath string, info os.FileInfo, err error) error { if err != nil { return err } var pstats []Propstat if pf.Propname != nil { pnames, err := propnames(h.FileSystem, h.LockSystem, reqPath) if err != nil { return err } pstat := Propstat{Status: http.StatusOK} for _, xmlname := range pnames { pstat.Props = append(pstat.Props, Property{XMLName: xmlname}) } pstats = append(pstats, pstat) } else if pf.Allprop != nil { pstats, err = allprop(h.FileSystem, h.LockSystem, reqPath, pf.Prop) } else { pstats, err = props(h.FileSystem, h.LockSystem, reqPath, pf.Prop) } if err != nil { return err } return mw.write(makePropstatResponse(path.Join(h.Prefix, reqPath), pstats)) } walkErr := walkFS(h.FileSystem, depth, reqPath, fi, walkFn) closeErr := mw.close() if walkErr != nil { return http.StatusInternalServerError, walkErr } if closeErr != nil { return http.StatusInternalServerError, closeErr } return 0, nil } func (h *Handler) handleProppatch(w http.ResponseWriter, r *http.Request) (status int, err error) { reqPath, status, err := h.stripPrefix(r.URL.Path) if err != nil { return status, err } release, status, err := h.confirmLocks(r, reqPath, "") if err != nil { return status, err } defer release() if _, err := h.FileSystem.Stat(reqPath); err != nil { if os.IsNotExist(err) { return http.StatusNotFound, err } return http.StatusMethodNotAllowed, err } patches, status, err := readProppatch(r.Body) if err != nil { return status, err } pstats, err := patch(h.FileSystem, h.LockSystem, reqPath, patches) if err != nil { return http.StatusInternalServerError, err } mw := multistatusWriter{w: w} writeErr := mw.write(makePropstatResponse(r.URL.Path, pstats)) closeErr := mw.close() if writeErr != nil { return http.StatusInternalServerError, writeErr } if closeErr != nil { return http.StatusInternalServerError, closeErr } return 0, nil } func makePropstatResponse(href string, pstats []Propstat) *response { resp := response{ Href: []string{href}, Propstat: make([]propstat, 0, len(pstats)), } for _, p := range pstats { var xmlErr *xmlError if p.XMLError != "" { xmlErr = &xmlError{InnerXML: []byte(p.XMLError)} } resp.Propstat = append(resp.Propstat, propstat{ Status: fmt.Sprintf("HTTP/1.1 %d %s", p.Status, StatusText(p.Status)), Prop: p.Props, ResponseDescription: p.ResponseDescription, Error: xmlErr, }) } return &resp } const ( infiniteDepth = -1 invalidDepth = -2 ) // parseDepth maps the strings "0", "1" and "infinity" to 0, 1 and // infiniteDepth. Parsing any other string returns invalidDepth. // // Different WebDAV methods have further constraints on valid depths: // - PROPFIND has no further restrictions, as per section 9.1. // - COPY accepts only "0" or "infinity", as per section 9.8.3. // - MOVE accepts only "infinity", as per section 9.9.2. // - LOCK accepts only "0" or "infinity", as per section 9.10.3. // These constraints are enforced by the handleXxx methods. func parseDepth(s string) int { switch s { case "0": return 0 case "1": return 1 case "infinity": return infiniteDepth } return invalidDepth } // http://www.webdav.org/specs/rfc4918.html#status.code.extensions.to.http11 const ( StatusMulti = 207 StatusUnprocessableEntity = 422 StatusLocked = 423 StatusFailedDependency = 424 StatusInsufficientStorage = 507 ) func StatusText(code int) string { switch code { case StatusMulti: return "Multi-Status" case StatusUnprocessableEntity: return "Unprocessable Entity" case StatusLocked: return "Locked" case StatusFailedDependency: return "Failed Dependency" case StatusInsufficientStorage: return "Insufficient Storage" } return http.StatusText(code) } var ( errDestinationEqualsSource = errors.New("webdav: destination equals source") errDirectoryNotEmpty = errors.New("webdav: directory not empty") errInvalidDepth = errors.New("webdav: invalid depth") errInvalidDestination = errors.New("webdav: invalid destination") errInvalidIfHeader = errors.New("webdav: invalid If header") errInvalidLockInfo = errors.New("webdav: invalid lock info") errInvalidLockToken = errors.New("webdav: invalid lock token") errInvalidPropfind = errors.New("webdav: invalid propfind") errInvalidProppatch = errors.New("webdav: invalid proppatch") errInvalidResponse = errors.New("webdav: invalid response") errInvalidTimeout = errors.New("webdav: invalid timeout") errNoFileSystem = errors.New("webdav: no file system") errNoLockSystem = errors.New("webdav: no lock system") errNotADirectory = errors.New("webdav: not a directory") errPrefixMismatch = errors.New("webdav: prefix mismatch") errRecursionTooDeep = errors.New("webdav: recursion too deep") errUnsupportedLockInfo = errors.New("webdav: unsupported lock info") errUnsupportedMethod = errors.New("webdav: unsupported method") ) ================================================ FILE: vendor/golang.org/x/net/webdav/webdav_test.go ================================================ // 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 webdav import ( "fmt" "io" "net/http" "net/http/httptest" "reflect" "sort" "strings" "testing" ) // TODO: add tests to check XML responses with the expected prefix path func TestPrefix(t *testing.T) { const dst, blah = "Destination", "blah blah blah" do := func(method, urlStr string, body io.Reader, wantStatusCode int, headers ...string) error { req, err := http.NewRequest(method, urlStr, body) if err != nil { return err } for len(headers) >= 2 { req.Header.Add(headers[0], headers[1]) headers = headers[2:] } res, err := http.DefaultClient.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode != wantStatusCode { return fmt.Errorf("got status code %d, want %d", res.StatusCode, wantStatusCode) } return nil } prefixes := []string{ "/", "/a/", "/a/b/", "/a/b/c/", } for _, prefix := range prefixes { fs := NewMemFS() h := &Handler{ FileSystem: fs, LockSystem: NewMemLS(), } mux := http.NewServeMux() if prefix != "/" { h.Prefix = prefix } mux.Handle(prefix, h) srv := httptest.NewServer(mux) defer srv.Close() // The script is: // MKCOL /a // MKCOL /a/b // PUT /a/b/c // COPY /a/b/c /a/b/d // MKCOL /a/b/e // MOVE /a/b/d /a/b/e/f // which should yield the (possibly stripped) filenames /a/b/c and // /a/b/e/f, plus their parent directories. wantA := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusMovedPermanently, "/a/b/": http.StatusNotFound, "/a/b/c/": http.StatusNotFound, }[prefix] if err := do("MKCOL", srv.URL+"/a", nil, wantA); err != nil { t.Errorf("prefix=%-9q MKCOL /a: %v", prefix, err) continue } wantB := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusMovedPermanently, "/a/b/c/": http.StatusNotFound, }[prefix] if err := do("MKCOL", srv.URL+"/a/b", nil, wantB); err != nil { t.Errorf("prefix=%-9q MKCOL /a/b: %v", prefix, err) continue } wantC := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusMovedPermanently, }[prefix] if err := do("PUT", srv.URL+"/a/b/c", strings.NewReader(blah), wantC); err != nil { t.Errorf("prefix=%-9q PUT /a/b/c: %v", prefix, err) continue } wantD := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusMovedPermanently, }[prefix] if err := do("COPY", srv.URL+"/a/b/c", nil, wantD, dst, srv.URL+"/a/b/d"); err != nil { t.Errorf("prefix=%-9q COPY /a/b/c /a/b/d: %v", prefix, err) continue } wantE := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusNotFound, }[prefix] if err := do("MKCOL", srv.URL+"/a/b/e", nil, wantE); err != nil { t.Errorf("prefix=%-9q MKCOL /a/b/e: %v", prefix, err) continue } wantF := map[string]int{ "/": http.StatusCreated, "/a/": http.StatusCreated, "/a/b/": http.StatusCreated, "/a/b/c/": http.StatusNotFound, }[prefix] if err := do("MOVE", srv.URL+"/a/b/d", nil, wantF, dst, srv.URL+"/a/b/e/f"); err != nil { t.Errorf("prefix=%-9q MOVE /a/b/d /a/b/e/f: %v", prefix, err) continue } got, err := find(nil, fs, "/") if err != nil { t.Errorf("prefix=%-9q find: %v", prefix, err) continue } sort.Strings(got) want := map[string][]string{ "/": []string{"/", "/a", "/a/b", "/a/b/c", "/a/b/e", "/a/b/e/f"}, "/a/": []string{"/", "/b", "/b/c", "/b/e", "/b/e/f"}, "/a/b/": []string{"/", "/c", "/e", "/e/f"}, "/a/b/c/": []string{"/"}, }[prefix] if !reflect.DeepEqual(got, want) { t.Errorf("prefix=%-9q find:\ngot %v\nwant %v", prefix, got, want) continue } } } ================================================ FILE: vendor/golang.org/x/net/webdav/xml.go ================================================ // 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 webdav // The XML encoding is covered by Section 14. // http://www.webdav.org/specs/rfc4918.html#xml.element.definitions import ( "bytes" "fmt" "io" "net/http" "time" "golang.org/x/net/webdav/internal/xml" ) // http://www.webdav.org/specs/rfc4918.html#ELEMENT_lockinfo type lockInfo struct { XMLName xml.Name `xml:"lockinfo"` Exclusive *struct{} `xml:"lockscope>exclusive"` Shared *struct{} `xml:"lockscope>shared"` Write *struct{} `xml:"locktype>write"` Owner owner `xml:"owner"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_owner type owner struct { InnerXML string `xml:",innerxml"` } func readLockInfo(r io.Reader) (li lockInfo, status int, err error) { c := &countingReader{r: r} if err = xml.NewDecoder(c).Decode(&li); err != nil { if err == io.EOF { if c.n == 0 { // An empty body means to refresh the lock. // http://www.webdav.org/specs/rfc4918.html#refreshing-locks return lockInfo{}, 0, nil } err = errInvalidLockInfo } return lockInfo{}, http.StatusBadRequest, err } // We only support exclusive (non-shared) write locks. In practice, these are // the only types of locks that seem to matter. if li.Exclusive == nil || li.Shared != nil || li.Write == nil { return lockInfo{}, http.StatusNotImplemented, errUnsupportedLockInfo } return li, 0, nil } type countingReader struct { n int r io.Reader } func (c *countingReader) Read(p []byte) (int, error) { n, err := c.r.Read(p) c.n += n return n, err } func writeLockInfo(w io.Writer, token string, ld LockDetails) (int, error) { depth := "infinity" if ld.ZeroDepth { depth = "0" } timeout := ld.Duration / time.Second return fmt.Fprintf(w, "\n"+ "\n"+ " \n"+ " \n"+ " %s\n"+ " %s\n"+ " Second-%d\n"+ " %s\n"+ " %s\n"+ "", depth, ld.OwnerXML, timeout, escape(token), escape(ld.Root), ) } func escape(s string) string { for i := 0; i < len(s); i++ { switch s[i] { case '"', '&', '\'', '<', '>': b := bytes.NewBuffer(nil) xml.EscapeText(b, []byte(s)) return b.String() } } return s } // Next returns the next token, if any, in the XML stream of d. // RFC 4918 requires to ignore comments, processing instructions // and directives. // http://www.webdav.org/specs/rfc4918.html#property_values // http://www.webdav.org/specs/rfc4918.html#xml-extensibility func next(d *xml.Decoder) (xml.Token, error) { for { t, err := d.Token() if err != nil { return t, err } switch t.(type) { case xml.Comment, xml.Directive, xml.ProcInst: continue default: return t, nil } } } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for propfind) type propfindProps []xml.Name // UnmarshalXML appends the property names enclosed within start to pn. // // It returns an error if start does not contain any properties or if // properties contain values. Character data between properties is ignored. func (pn *propfindProps) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { for { t, err := next(d) if err != nil { return err } switch t.(type) { case xml.EndElement: if len(*pn) == 0 { return fmt.Errorf("%s must not be empty", start.Name.Local) } return nil case xml.StartElement: name := t.(xml.StartElement).Name t, err = next(d) if err != nil { return err } if _, ok := t.(xml.EndElement); !ok { return fmt.Errorf("unexpected token %T", t) } *pn = append(*pn, name) } } } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propfind type propfind struct { XMLName xml.Name `xml:"DAV: propfind"` Allprop *struct{} `xml:"DAV: allprop"` Propname *struct{} `xml:"DAV: propname"` Prop propfindProps `xml:"DAV: prop"` Include propfindProps `xml:"DAV: include"` } func readPropfind(r io.Reader) (pf propfind, status int, err error) { c := countingReader{r: r} if err = xml.NewDecoder(&c).Decode(&pf); err != nil { if err == io.EOF { if c.n == 0 { // An empty body means to propfind allprop. // http://www.webdav.org/specs/rfc4918.html#METHOD_PROPFIND return propfind{Allprop: new(struct{})}, 0, nil } err = errInvalidPropfind } return propfind{}, http.StatusBadRequest, err } if pf.Allprop == nil && pf.Include != nil { return propfind{}, http.StatusBadRequest, errInvalidPropfind } if pf.Allprop != nil && (pf.Prop != nil || pf.Propname != nil) { return propfind{}, http.StatusBadRequest, errInvalidPropfind } if pf.Prop != nil && pf.Propname != nil { return propfind{}, http.StatusBadRequest, errInvalidPropfind } if pf.Propname == nil && pf.Allprop == nil && pf.Prop == nil { return propfind{}, http.StatusBadRequest, errInvalidPropfind } return pf, 0, nil } // Property represents a single DAV resource property as defined in RFC 4918. // See http://www.webdav.org/specs/rfc4918.html#data.model.for.resource.properties type Property struct { // XMLName is the fully qualified name that identifies this property. XMLName xml.Name // Lang is an optional xml:lang attribute. Lang string `xml:"xml:lang,attr,omitempty"` // InnerXML contains the XML representation of the property value. // See http://www.webdav.org/specs/rfc4918.html#property_values // // Property values of complex type or mixed-content must have fully // expanded XML namespaces or be self-contained with according // XML namespace declarations. They must not rely on any XML // namespace declarations within the scope of the XML document, // even including the DAV: namespace. InnerXML []byte `xml:",innerxml"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_error // See multistatusWriter for the "D:" namespace prefix. type xmlError struct { XMLName xml.Name `xml:"D:error"` InnerXML []byte `xml:",innerxml"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propstat // See multistatusWriter for the "D:" namespace prefix. type propstat struct { Prop []Property `xml:"D:prop>_ignored_"` Status string `xml:"D:status"` Error *xmlError `xml:"D:error"` ResponseDescription string `xml:"D:responsedescription,omitempty"` } // MarshalXML prepends the "D:" namespace prefix on properties in the DAV: namespace // before encoding. See multistatusWriter. func (ps propstat) MarshalXML(e *xml.Encoder, start xml.StartElement) error { for k, prop := range ps.Prop { if prop.XMLName.Space == "DAV:" { prop.XMLName = xml.Name{Space: "", Local: "D:" + prop.XMLName.Local} ps.Prop[k] = prop } } // Distinct type to avoid infinite recursion of MarshalXML. type newpropstat propstat return e.EncodeElement(newpropstat(ps), start) } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_response // See multistatusWriter for the "D:" namespace prefix. type response struct { XMLName xml.Name `xml:"D:response"` Href []string `xml:"D:href"` Propstat []propstat `xml:"D:propstat"` Status string `xml:"D:status,omitempty"` Error *xmlError `xml:"D:error"` ResponseDescription string `xml:"D:responsedescription,omitempty"` } // MultistatusWriter marshals one or more Responses into a XML // multistatus response. // See http://www.webdav.org/specs/rfc4918.html#ELEMENT_multistatus // TODO(rsto, mpl): As a workaround, the "D:" namespace prefix, defined as // "DAV:" on this element, is prepended on the nested response, as well as on all // its nested elements. All property names in the DAV: namespace are prefixed as // well. This is because some versions of Mini-Redirector (on windows 7) ignore // elements with a default namespace (no prefixed namespace). A less intrusive fix // should be possible after golang.org/cl/11074. See https://golang.org/issue/11177 type multistatusWriter struct { // ResponseDescription contains the optional responsedescription // of the multistatus XML element. Only the latest content before // close will be emitted. Empty response descriptions are not // written. responseDescription string w http.ResponseWriter enc *xml.Encoder } // Write validates and emits a DAV response as part of a multistatus response // element. // // It sets the HTTP status code of its underlying http.ResponseWriter to 207 // (Multi-Status) and populates the Content-Type header. If r is the // first, valid response to be written, Write prepends the XML representation // of r with a multistatus tag. Callers must call close after the last response // has been written. func (w *multistatusWriter) write(r *response) error { switch len(r.Href) { case 0: return errInvalidResponse case 1: if len(r.Propstat) > 0 != (r.Status == "") { return errInvalidResponse } default: if len(r.Propstat) > 0 || r.Status == "" { return errInvalidResponse } } err := w.writeHeader() if err != nil { return err } return w.enc.Encode(r) } // writeHeader writes a XML multistatus start element on w's underlying // http.ResponseWriter and returns the result of the write operation. // After the first write attempt, writeHeader becomes a no-op. func (w *multistatusWriter) writeHeader() error { if w.enc != nil { return nil } w.w.Header().Add("Content-Type", "text/xml; charset=utf-8") w.w.WriteHeader(StatusMulti) _, err := fmt.Fprintf(w.w, ``) if err != nil { return err } w.enc = xml.NewEncoder(w.w) return w.enc.EncodeToken(xml.StartElement{ Name: xml.Name{ Space: "DAV:", Local: "multistatus", }, Attr: []xml.Attr{{ Name: xml.Name{Space: "xmlns", Local: "D"}, Value: "DAV:", }}, }) } // Close completes the marshalling of the multistatus response. It returns // an error if the multistatus response could not be completed. If both the // return value and field enc of w are nil, then no multistatus response has // been written. func (w *multistatusWriter) close() error { if w.enc == nil { return nil } var end []xml.Token if w.responseDescription != "" { name := xml.Name{Space: "DAV:", Local: "responsedescription"} end = append(end, xml.StartElement{Name: name}, xml.CharData(w.responseDescription), xml.EndElement{Name: name}, ) } end = append(end, xml.EndElement{ Name: xml.Name{Space: "DAV:", Local: "multistatus"}, }) for _, t := range end { err := w.enc.EncodeToken(t) if err != nil { return err } } return w.enc.Flush() } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_prop (for proppatch) type proppatchProps []Property var xmlLangName = xml.Name{Space: "http://www.w3.org/XML/1998/namespace", Local: "lang"} func xmlLang(s xml.StartElement, d string) string { for _, attr := range s.Attr { if attr.Name == xmlLangName { return attr.Value } } return d } type xmlValue []byte func (v *xmlValue) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { // The XML value of a property can be arbitrary, mixed-content XML. // To make sure that the unmarshalled value contains all required // namespaces, we encode all the property value XML tokens into a // buffer. This forces the encoder to redeclare any used namespaces. var b bytes.Buffer e := xml.NewEncoder(&b) for { t, err := next(d) if err != nil { return err } if e, ok := t.(xml.EndElement); ok && e.Name == start.Name { break } if err = e.EncodeToken(t); err != nil { return err } } err := e.Flush() if err != nil { return err } *v = b.Bytes() return nil } // UnmarshalXML appends the property names and values enclosed within start // to ps. // // An xml:lang attribute that is defined either on the DAV:prop or property // name XML element is propagated to the property's Lang field. // // UnmarshalXML returns an error if start does not contain any properties or if // property values contain syntactically incorrect XML. func (ps *proppatchProps) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { lang := xmlLang(start, "") for { t, err := next(d) if err != nil { return err } switch elem := t.(type) { case xml.EndElement: if len(*ps) == 0 { return fmt.Errorf("%s must not be empty", start.Name.Local) } return nil case xml.StartElement: p := Property{ XMLName: t.(xml.StartElement).Name, Lang: xmlLang(t.(xml.StartElement), lang), } err = d.DecodeElement(((*xmlValue)(&p.InnerXML)), &elem) if err != nil { return err } *ps = append(*ps, p) } } } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_set // http://www.webdav.org/specs/rfc4918.html#ELEMENT_remove type setRemove struct { XMLName xml.Name Lang string `xml:"xml:lang,attr,omitempty"` Prop proppatchProps `xml:"DAV: prop"` } // http://www.webdav.org/specs/rfc4918.html#ELEMENT_propertyupdate type propertyupdate struct { XMLName xml.Name `xml:"DAV: propertyupdate"` Lang string `xml:"xml:lang,attr,omitempty"` SetRemove []setRemove `xml:",any"` } func readProppatch(r io.Reader) (patches []Proppatch, status int, err error) { var pu propertyupdate if err = xml.NewDecoder(r).Decode(&pu); err != nil { return nil, http.StatusBadRequest, err } for _, op := range pu.SetRemove { remove := false switch op.XMLName { case xml.Name{Space: "DAV:", Local: "set"}: // No-op. case xml.Name{Space: "DAV:", Local: "remove"}: for _, p := range op.Prop { if len(p.InnerXML) > 0 { return nil, http.StatusBadRequest, errInvalidProppatch } } remove = true default: return nil, http.StatusBadRequest, errInvalidProppatch } patches = append(patches, Proppatch{Remove: remove, Props: op.Prop}) } return patches, 0, nil } ================================================ FILE: vendor/golang.org/x/net/webdav/xml_test.go ================================================ // 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 webdav import ( "bytes" "fmt" "io" "net/http" "net/http/httptest" "reflect" "sort" "strings" "testing" "golang.org/x/net/webdav/internal/xml" ) func TestReadLockInfo(t *testing.T) { // The "section x.y.z" test cases come from section x.y.z of the spec at // http://www.webdav.org/specs/rfc4918.html testCases := []struct { desc string input string wantLI lockInfo wantStatus int }{{ "bad: junk", "xxx", lockInfo{}, http.StatusBadRequest, }, { "bad: invalid owner XML", "" + "\n" + " \n" + " \n" + " \n" + " no end tag \n" + " \n" + "", lockInfo{}, http.StatusBadRequest, }, { "bad: invalid UTF-8", "" + "\n" + " \n" + " \n" + " \n" + " \xff \n" + " \n" + "", lockInfo{}, http.StatusBadRequest, }, { "bad: unfinished XML #1", "" + "\n" + " \n" + " \n", lockInfo{}, http.StatusBadRequest, }, { "bad: unfinished XML #2", "" + "\n" + " \n" + " \n" + " \n", lockInfo{}, http.StatusBadRequest, }, { "good: empty", "", lockInfo{}, 0, }, { "good: plain-text owner", "" + "\n" + " \n" + " \n" + " gopher\n" + "", lockInfo{ XMLName: xml.Name{Space: "DAV:", Local: "lockinfo"}, Exclusive: new(struct{}), Write: new(struct{}), Owner: owner{ InnerXML: "gopher", }, }, 0, }, { "section 9.10.7", "" + "\n" + " \n" + " \n" + " \n" + " http://example.org/~ejw/contact.html\n" + " \n" + "", lockInfo{ XMLName: xml.Name{Space: "DAV:", Local: "lockinfo"}, Exclusive: new(struct{}), Write: new(struct{}), Owner: owner{ InnerXML: "\n http://example.org/~ejw/contact.html\n ", }, }, 0, }} for _, tc := range testCases { li, status, err := readLockInfo(strings.NewReader(tc.input)) if tc.wantStatus != 0 { if err == nil { t.Errorf("%s: got nil error, want non-nil", tc.desc) continue } } else if err != nil { t.Errorf("%s: %v", tc.desc, err) continue } if !reflect.DeepEqual(li, tc.wantLI) || status != tc.wantStatus { t.Errorf("%s:\ngot lockInfo=%v, status=%v\nwant lockInfo=%v, status=%v", tc.desc, li, status, tc.wantLI, tc.wantStatus) continue } } } func TestReadPropfind(t *testing.T) { testCases := []struct { desc string input string wantPF propfind wantStatus int }{{ desc: "propfind: propname", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Propname: new(struct{}), }, }, { desc: "propfind: empty body means allprop", input: "", wantPF: propfind{ Allprop: new(struct{}), }, }, { desc: "propfind: allprop", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Allprop: new(struct{}), }, }, { desc: "propfind: allprop followed by include", input: "" + "\n" + " \n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Allprop: new(struct{}), Include: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: include followed by allprop", input: "" + "\n" + " \n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Allprop: new(struct{}), Include: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propfind", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: prop with ignored comments", input: "" + "\n" + " \n" + " \n" + " \n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propfind with ignored whitespace", input: "" + "\n" + " \n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propfind with ignored mixed-content", input: "" + "\n" + " foobar\n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Prop: propfindProps{xml.Name{Space: "DAV:", Local: "displayname"}}, }, }, { desc: "propfind: propname with ignored element (section A.4)", input: "" + "\n" + " \n" + " *boss*\n" + "", wantPF: propfind{ XMLName: xml.Name{Space: "DAV:", Local: "propfind"}, Propname: new(struct{}), }, }, { desc: "propfind: bad: junk", input: "xxx", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: propname and allprop (section A.3)", input: "" + "\n" + " " + " " + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: propname and prop", input: "" + "\n" + " \n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: allprop and prop", input: "" + "\n" + " \n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: empty propfind with ignored element (section A.4)", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: empty prop", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: prop with just chardata", input: "" + "\n" + " foo\n" + "", wantStatus: http.StatusBadRequest, }, { desc: "bad: interrupted prop", input: "" + "\n" + " \n", wantStatus: http.StatusBadRequest, }, { desc: "bad: malformed end element prop", input: "" + "\n" + " \n", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: property with chardata value", input: "" + "\n" + " bar\n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: property with whitespace value", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }, { desc: "propfind: bad: include without allprop", input: "" + "\n" + " \n" + "", wantStatus: http.StatusBadRequest, }} for _, tc := range testCases { pf, status, err := readPropfind(strings.NewReader(tc.input)) if tc.wantStatus != 0 { if err == nil { t.Errorf("%s: got nil error, want non-nil", tc.desc) continue } } else if err != nil { t.Errorf("%s: %v", tc.desc, err) continue } if !reflect.DeepEqual(pf, tc.wantPF) || status != tc.wantStatus { t.Errorf("%s:\ngot propfind=%v, status=%v\nwant propfind=%v, status=%v", tc.desc, pf, status, tc.wantPF, tc.wantStatus) continue } } } func TestMultistatusWriter(t *testing.T) { if go1Dot4 { t.Skip("TestMultistatusWriter requires Go version 1.5 or greater") } ///The "section x.y.z" test cases come from section x.y.z of the spec at // http://www.webdav.org/specs/rfc4918.html testCases := []struct { desc string responses []response respdesc string writeHeader bool wantXML string wantCode int wantErr error }{{ desc: "section 9.2.2 (failed dependency)", responses: []response{{ Href: []string{"http://example.com/foo"}, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://ns.example.com/", Local: "Authors", }, }}, Status: "HTTP/1.1 424 Failed Dependency", }, { Prop: []Property{{ XMLName: xml.Name{ Space: "http://ns.example.com/", Local: "Copyright-Owner", }, }}, Status: "HTTP/1.1 409 Conflict", }}, ResponseDescription: "Copyright Owner cannot be deleted or altered.", }}, wantXML: `` + `` + `` + ` ` + ` http://example.com/foo` + ` ` + ` ` + ` ` + ` ` + ` HTTP/1.1 424 Failed Dependency` + ` ` + ` ` + ` ` + ` ` + ` ` + ` HTTP/1.1 409 Conflict` + ` ` + ` Copyright Owner cannot be deleted or altered.` + `` + ``, wantCode: StatusMulti, }, { desc: "section 9.6.2 (lock-token-submitted)", responses: []response{{ Href: []string{"http://example.com/foo"}, Status: "HTTP/1.1 423 Locked", Error: &xmlError{ InnerXML: []byte(``), }, }}, wantXML: `` + `` + `` + ` ` + ` http://example.com/foo` + ` HTTP/1.1 423 Locked` + ` ` + ` ` + ``, wantCode: StatusMulti, }, { desc: "section 9.1.3", responses: []response{{ Href: []string{"http://example.com/foo"}, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "bigbox"}, InnerXML: []byte(`` + `` + `Box type A` + ``), }, { XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "author"}, InnerXML: []byte(`` + `` + `J.J. Johnson` + ``), }}, Status: "HTTP/1.1 200 OK", }, { Prop: []Property{{ XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "DingALing"}, }, { XMLName: xml.Name{Space: "http://ns.example.com/boxschema/", Local: "Random"}, }}, Status: "HTTP/1.1 403 Forbidden", ResponseDescription: "The user does not have access to the DingALing property.", }}, }}, respdesc: "There has been an access violation error.", wantXML: `` + `` + `` + ` ` + ` http://example.com/foo` + ` ` + ` ` + ` Box type A` + ` J.J. Johnson` + ` ` + ` HTTP/1.1 200 OK` + ` ` + ` ` + ` ` + ` ` + ` ` + ` ` + ` HTTP/1.1 403 Forbidden` + ` The user does not have access to the DingALing property.` + ` ` + ` ` + ` There has been an access violation error.` + ``, wantCode: StatusMulti, }, { desc: "no response written", // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "no response written (with description)", respdesc: "too bad", // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "empty multistatus with header", writeHeader: true, wantXML: ``, wantCode: StatusMulti, }, { desc: "bad: no href", responses: []response{{ Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://example.com/", Local: "foo", }, }}, Status: "HTTP/1.1 200 OK", }}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: multiple hrefs and no status", responses: []response{{ Href: []string{"http://example.com/foo", "http://example.com/bar"}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: one href and no propstat", responses: []response{{ Href: []string{"http://example.com/foo"}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: status with one href and propstat", responses: []response{{ Href: []string{"http://example.com/foo"}, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://example.com/", Local: "foo", }, }}, Status: "HTTP/1.1 200 OK", }}, Status: "HTTP/1.1 200 OK", }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }, { desc: "bad: multiple hrefs and propstat", responses: []response{{ Href: []string{ "http://example.com/foo", "http://example.com/bar", }, Propstat: []propstat{{ Prop: []Property{{ XMLName: xml.Name{ Space: "http://example.com/", Local: "foo", }, }}, Status: "HTTP/1.1 200 OK", }}, }}, wantErr: errInvalidResponse, // default of http.responseWriter wantCode: http.StatusOK, }} n := xmlNormalizer{omitWhitespace: true} loop: for _, tc := range testCases { rec := httptest.NewRecorder() w := multistatusWriter{w: rec, responseDescription: tc.respdesc} if tc.writeHeader { if err := w.writeHeader(); err != nil { t.Errorf("%s: got writeHeader error %v, want nil", tc.desc, err) continue } } for _, r := range tc.responses { if err := w.write(&r); err != nil { if err != tc.wantErr { t.Errorf("%s: got write error %v, want %v", tc.desc, err, tc.wantErr) } continue loop } } if err := w.close(); err != tc.wantErr { t.Errorf("%s: got close error %v, want %v", tc.desc, err, tc.wantErr) continue } if rec.Code != tc.wantCode { t.Errorf("%s: got HTTP status code %d, want %d\n", tc.desc, rec.Code, tc.wantCode) continue } gotXML := rec.Body.String() eq, err := n.equalXML(strings.NewReader(gotXML), strings.NewReader(tc.wantXML)) if err != nil { t.Errorf("%s: equalXML: %v", tc.desc, err) continue } if !eq { t.Errorf("%s: XML body\ngot %s\nwant %s", tc.desc, gotXML, tc.wantXML) } } } func TestReadProppatch(t *testing.T) { ppStr := func(pps []Proppatch) string { var outer []string for _, pp := range pps { var inner []string for _, p := range pp.Props { inner = append(inner, fmt.Sprintf("{XMLName: %q, Lang: %q, InnerXML: %q}", p.XMLName, p.Lang, p.InnerXML)) } outer = append(outer, fmt.Sprintf("{Remove: %t, Props: [%s]}", pp.Remove, strings.Join(inner, ", "))) } return "[" + strings.Join(outer, ", ") + "]" } testCases := []struct { desc string input string wantPP []Proppatch wantStatus int }{{ desc: "proppatch: section 9.2 (with simple property value)", input: `` + `` + `` + ` ` + ` somevalue` + ` ` + ` ` + ` ` + ` ` + ``, wantPP: []Proppatch{{ Props: []Property{{ xml.Name{Space: "http://ns.example.com/z/", Local: "Authors"}, "", []byte(`somevalue`), }}, }, { Remove: true, Props: []Property{{ xml.Name{Space: "http://ns.example.com/z/", Local: "Copyright-Owner"}, "", nil, }}, }}, }, { desc: "proppatch: lang attribute on prop", input: `` + `` + `` + ` ` + ` ` + ` ` + ` ` + ` ` + ``, wantPP: []Proppatch{{ Props: []Property{{ xml.Name{Space: "http://example.com/ns", Local: "foo"}, "en", nil, }}, }}, }, { desc: "bad: remove with value", input: `` + `` + `` + ` ` + ` ` + ` ` + ` Jim Whitehead` + ` ` + ` ` + ` ` + ``, wantStatus: http.StatusBadRequest, }, { desc: "bad: empty propertyupdate", input: `` + `` + ``, wantStatus: http.StatusBadRequest, }, { desc: "bad: empty prop", input: `` + `` + `` + ` ` + ` ` + ` ` + ``, wantStatus: http.StatusBadRequest, }} for _, tc := range testCases { pp, status, err := readProppatch(strings.NewReader(tc.input)) if tc.wantStatus != 0 { if err == nil { t.Errorf("%s: got nil error, want non-nil", tc.desc) continue } } else if err != nil { t.Errorf("%s: %v", tc.desc, err) continue } if status != tc.wantStatus { t.Errorf("%s: got status %d, want %d", tc.desc, status, tc.wantStatus) continue } if !reflect.DeepEqual(pp, tc.wantPP) || status != tc.wantStatus { t.Errorf("%s: proppatch\ngot %v\nwant %v", tc.desc, ppStr(pp), ppStr(tc.wantPP)) } } } func TestUnmarshalXMLValue(t *testing.T) { testCases := []struct { desc string input string wantVal string }{{ desc: "simple char data", input: "foo", wantVal: "foo", }, { desc: "empty element", input: "", wantVal: "", }, { desc: "preserve namespace", input: ``, wantVal: ``, }, { desc: "preserve root element namespace", input: ``, wantVal: ``, }, { desc: "preserve whitespace", input: " \t ", wantVal: " \t ", }, { desc: "preserve mixed content", input: ` a `, wantVal: ` a `, }, { desc: "section 9.2", input: `` + `` + ` Jim Whitehead` + ` Roy Fielding` + ``, wantVal: `` + ` Jim Whitehead` + ` Roy Fielding`, }, { desc: "section 4.3.1 (mixed content)", input: `` + `` + ` Jane Doe` + ` ` + ` mailto:jane.doe@example.com` + ` http://www.example.com` + ` ` + ` Jane has been working way too long on the` + ` long-awaited revision of ]]>.` + ` ` + ``, wantVal: `` + ` Jane Doe` + ` ` + ` mailto:jane.doe@example.com` + ` http://www.example.com` + ` ` + ` Jane has been working way too long on the` + ` long-awaited revision of <RFC2518>.` + ` `, }} var n xmlNormalizer for _, tc := range testCases { d := xml.NewDecoder(strings.NewReader(tc.input)) var v xmlValue if err := d.Decode(&v); err != nil { t.Errorf("%s: got error %v, want nil", tc.desc, err) continue } eq, err := n.equalXML(bytes.NewReader(v), strings.NewReader(tc.wantVal)) if err != nil { t.Errorf("%s: equalXML: %v", tc.desc, err) continue } if !eq { t.Errorf("%s:\ngot %s\nwant %s", tc.desc, string(v), tc.wantVal) } } } // xmlNormalizer normalizes XML. type xmlNormalizer struct { // omitWhitespace instructs to ignore whitespace between element tags. omitWhitespace bool // omitComments instructs to ignore XML comments. omitComments bool } // normalize writes the normalized XML content of r to w. It applies the // following rules // // * Rename namespace prefixes according to an internal heuristic. // * Remove unnecessary namespace declarations. // * Sort attributes in XML start elements in lexical order of their // fully qualified name. // * Remove XML directives and processing instructions. // * Remove CDATA between XML tags that only contains whitespace, if // instructed to do so. // * Remove comments, if instructed to do so. // func (n *xmlNormalizer) normalize(w io.Writer, r io.Reader) error { d := xml.NewDecoder(r) e := xml.NewEncoder(w) for { t, err := d.Token() if err != nil { if t == nil && err == io.EOF { break } return err } switch val := t.(type) { case xml.Directive, xml.ProcInst: continue case xml.Comment: if n.omitComments { continue } case xml.CharData: if n.omitWhitespace && len(bytes.TrimSpace(val)) == 0 { continue } case xml.StartElement: start, _ := xml.CopyToken(val).(xml.StartElement) attr := start.Attr[:0] for _, a := range start.Attr { if a.Name.Space == "xmlns" || a.Name.Local == "xmlns" { continue } attr = append(attr, a) } sort.Sort(byName(attr)) start.Attr = attr t = start } err = e.EncodeToken(t) if err != nil { return err } } return e.Flush() } // equalXML tests for equality of the normalized XML contents of a and b. func (n *xmlNormalizer) equalXML(a, b io.Reader) (bool, error) { var buf bytes.Buffer if err := n.normalize(&buf, a); err != nil { return false, err } normA := buf.String() buf.Reset() if err := n.normalize(&buf, b); err != nil { return false, err } normB := buf.String() return normA == normB, nil } type byName []xml.Attr func (a byName) Len() int { return len(a) } func (a byName) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byName) Less(i, j int) bool { if a[i].Name.Space != a[j].Name.Space { return a[i].Name.Space < a[j].Name.Space } return a[i].Name.Local < a[j].Name.Local } ================================================ FILE: vendor/golang.org/x/net/websocket/client.go ================================================ // 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" "crypto/tls" "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} } switch config.Location.Scheme { case "ws": client, err = net.Dial("tcp", parseAuthority(config.Location)) case "wss": client, err = tls.Dial("tcp", parseAuthority(config.Location), config.TlsConfig) default: err = ErrBadScheme } if err != nil { goto Error } ws, err = NewClient(config, client) if err != nil { client.Close() goto Error } return Error: return nil, &DialError{config, err} } ================================================ FILE: vendor/golang.org/x/net/websocket/exampledial_test.go ================================================ // 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 websocket_test import ( "fmt" "log" "golang.org/x/net/websocket" ) // This example demonstrates a trivial client. func ExampleDial() { origin := "http://localhost/" url := "ws://localhost:12345/ws" ws, err := websocket.Dial(url, "", origin) if err != nil { log.Fatal(err) } if _, err := ws.Write([]byte("hello, world!\n")); err != nil { log.Fatal(err) } var msg = make([]byte, 512) var n int if n, err = ws.Read(msg); err != nil { log.Fatal(err) } fmt.Printf("Received: %s.\n", msg[:n]) } ================================================ FILE: vendor/golang.org/x/net/websocket/examplehandler_test.go ================================================ // 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 websocket_test import ( "io" "net/http" "golang.org/x/net/websocket" ) // Echo the data received on the WebSocket. func EchoServer(ws *websocket.Conn) { io.Copy(ws, ws) } // This example demonstrates a trivial echo server. func ExampleHandler() { http.Handle("/echo", websocket.Handler(EchoServer)) err := http.ListenAndServe(":12345", nil) if err != nil { panic("ListenAndServe: " + err.Error()) } } ================================================ FILE: vendor/golang.org/x/net/websocket/hybi.go ================================================ // 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 err != nil { return 0, err } 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) } ================================================ FILE: vendor/golang.org/x/net/websocket/hybi_test.go ================================================ // 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 import ( "bufio" "bytes" "fmt" "io" "net/http" "net/url" "strings" "testing" ) // Test the getNonceAccept function with values in // http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17 func TestSecWebSocketAccept(t *testing.T) { nonce := []byte("dGhlIHNhbXBsZSBub25jZQ==") expected := []byte("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") accept, err := getNonceAccept(nonce) if err != nil { t.Errorf("getNonceAccept: returned error %v", err) return } if !bytes.Equal(expected, accept) { t.Errorf("getNonceAccept: expected %q got %q", expected, accept) } } func TestHybiClientHandshake(t *testing.T) { type test struct { url, host string } tests := []test{ {"ws://server.example.com/chat", "server.example.com"}, {"ws://127.0.0.1/chat", "127.0.0.1"}, } if _, err := url.ParseRequestURI("http://[fe80::1%25lo0]"); err == nil { tests = append(tests, test{"ws://[fe80::1%25lo0]/chat", "[fe80::1]"}) } for _, tt := range tests { var b bytes.Buffer bw := bufio.NewWriter(&b) br := bufio.NewReader(strings.NewReader(`HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat `)) var err error var config Config config.Location, err = url.ParseRequestURI(tt.url) if err != nil { t.Fatal("location url", err) } config.Origin, err = url.ParseRequestURI("http://example.com") if err != nil { t.Fatal("origin url", err) } config.Protocol = append(config.Protocol, "chat") config.Protocol = append(config.Protocol, "superchat") config.Version = ProtocolVersionHybi13 config.handshakeData = map[string]string{ "key": "dGhlIHNhbXBsZSBub25jZQ==", } if err := hybiClientHandshake(&config, br, bw); err != nil { t.Fatal("handshake", err) } req, err := http.ReadRequest(bufio.NewReader(&b)) if err != nil { t.Fatal("read request", err) } if req.Method != "GET" { t.Errorf("request method expected GET, but got %s", req.Method) } if req.URL.Path != "/chat" { t.Errorf("request path expected /chat, but got %s", req.URL.Path) } if req.Proto != "HTTP/1.1" { t.Errorf("request proto expected HTTP/1.1, but got %s", req.Proto) } if req.Host != tt.host { t.Errorf("request host expected %s, but got %s", tt.host, req.Host) } var expectedHeader = map[string]string{ "Connection": "Upgrade", "Upgrade": "websocket", "Sec-Websocket-Key": config.handshakeData["key"], "Origin": config.Origin.String(), "Sec-Websocket-Protocol": "chat, superchat", "Sec-Websocket-Version": fmt.Sprintf("%d", ProtocolVersionHybi13), } for k, v := range expectedHeader { if req.Header.Get(k) != v { t.Errorf("%s expected %s, but got %v", k, v, req.Header.Get(k)) } } } } func TestHybiClientHandshakeWithHeader(t *testing.T) { b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) br := bufio.NewReader(strings.NewReader(`HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat `)) var err error config := new(Config) config.Location, err = url.ParseRequestURI("ws://server.example.com/chat") if err != nil { t.Fatal("location url", err) } config.Origin, err = url.ParseRequestURI("http://example.com") if err != nil { t.Fatal("origin url", err) } config.Protocol = append(config.Protocol, "chat") config.Protocol = append(config.Protocol, "superchat") config.Version = ProtocolVersionHybi13 config.Header = http.Header(make(map[string][]string)) config.Header.Add("User-Agent", "test") config.handshakeData = map[string]string{ "key": "dGhlIHNhbXBsZSBub25jZQ==", } err = hybiClientHandshake(config, br, bw) if err != nil { t.Errorf("handshake failed: %v", err) } req, err := http.ReadRequest(bufio.NewReader(b)) if err != nil { t.Fatalf("read request: %v", err) } if req.Method != "GET" { t.Errorf("request method expected GET, but got %q", req.Method) } if req.URL.Path != "/chat" { t.Errorf("request path expected /chat, but got %q", req.URL.Path) } if req.Proto != "HTTP/1.1" { t.Errorf("request proto expected HTTP/1.1, but got %q", req.Proto) } if req.Host != "server.example.com" { t.Errorf("request Host expected server.example.com, but got %v", req.Host) } var expectedHeader = map[string]string{ "Connection": "Upgrade", "Upgrade": "websocket", "Sec-Websocket-Key": config.handshakeData["key"], "Origin": config.Origin.String(), "Sec-Websocket-Protocol": "chat, superchat", "Sec-Websocket-Version": fmt.Sprintf("%d", ProtocolVersionHybi13), "User-Agent": "test", } for k, v := range expectedHeader { if req.Header.Get(k) != v { t.Errorf(fmt.Sprintf("%s expected %q but got %q", k, v, req.Header.Get(k))) } } } func TestHybiServerHandshake(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != nil { t.Errorf("handshake failed: %v", err) } if code != http.StatusSwitchingProtocols { t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) } expectedProtocols := []string{"chat", "superchat"} if fmt.Sprintf("%v", config.Protocol) != fmt.Sprintf("%v", expectedProtocols) { t.Errorf("protocol expected %q but got %q", expectedProtocols, config.Protocol) } b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) config.Protocol = config.Protocol[:1] err = handshaker.AcceptHandshake(bw) if err != nil { t.Errorf("handshake response failed: %v", err) } expectedResponse := strings.Join([]string{ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", "Sec-WebSocket-Protocol: chat", "", ""}, "\r\n") if b.String() != expectedResponse { t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) } } func TestHybiServerHandshakeNoSubProtocol(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Version: 13 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != nil { t.Errorf("handshake failed: %v", err) } if code != http.StatusSwitchingProtocols { t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) } if len(config.Protocol) != 0 { t.Errorf("len(config.Protocol) expected 0, but got %q", len(config.Protocol)) } b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) err = handshaker.AcceptHandshake(bw) if err != nil { t.Errorf("handshake response failed: %v", err) } expectedResponse := strings.Join([]string{ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", "", ""}, "\r\n") if b.String() != expectedResponse { t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) } } func TestHybiServerHandshakeHybiBadVersion(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Sec-WebSocket-Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 9 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != ErrBadWebSocketVersion { t.Errorf("handshake expected err %q but got %q", ErrBadWebSocketVersion, err) } if code != http.StatusBadRequest { t.Errorf("status expected %q but got %q", http.StatusBadRequest, code) } } func testHybiFrame(t *testing.T, testHeader, testPayload, testMaskedPayload []byte, frameHeader *hybiFrameHeader) { b := bytes.NewBuffer([]byte{}) frameWriterFactory := &hybiFrameWriterFactory{bufio.NewWriter(b), false} w, _ := frameWriterFactory.NewFrameWriter(TextFrame) w.(*hybiFrameWriter).header = frameHeader _, err := w.Write(testPayload) w.Close() if err != nil { t.Errorf("Write error %q", err) } var expectedFrame []byte expectedFrame = append(expectedFrame, testHeader...) expectedFrame = append(expectedFrame, testMaskedPayload...) if !bytes.Equal(expectedFrame, b.Bytes()) { t.Errorf("frame expected %q got %q", expectedFrame, b.Bytes()) } frameReaderFactory := &hybiFrameReaderFactory{bufio.NewReader(b)} r, err := frameReaderFactory.NewFrameReader() if err != nil { t.Errorf("Read error %q", err) } if header := r.HeaderReader(); header == nil { t.Errorf("no header") } else { actualHeader := make([]byte, r.Len()) n, err := header.Read(actualHeader) if err != nil { t.Errorf("Read header error %q", err) } else { if n < len(testHeader) { t.Errorf("header too short %q got %q", testHeader, actualHeader[:n]) } if !bytes.Equal(testHeader, actualHeader[:n]) { t.Errorf("header expected %q got %q", testHeader, actualHeader[:n]) } } } if trailer := r.TrailerReader(); trailer != nil { t.Errorf("unexpected trailer %q", trailer) } frame := r.(*hybiFrameReader) if frameHeader.Fin != frame.header.Fin || frameHeader.OpCode != frame.header.OpCode || len(testPayload) != int(frame.header.Length) { t.Errorf("mismatch %v (%d) vs %v", frameHeader, len(testPayload), frame) } payload := make([]byte, len(testPayload)) _, err = r.Read(payload) if err != nil && err != io.EOF { t.Errorf("read %v", err) } if !bytes.Equal(testPayload, payload) { t.Errorf("payload %q vs %q", testPayload, payload) } } func TestHybiShortTextFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame} payload := []byte("hello") testHybiFrame(t, []byte{0x81, 0x05}, payload, payload, frameHeader) payload = make([]byte, 125) testHybiFrame(t, []byte{0x81, 125}, payload, payload, frameHeader) } func TestHybiShortMaskedTextFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame, MaskingKey: []byte{0xcc, 0x55, 0x80, 0x20}} payload := []byte("hello") maskedPayload := []byte{0xa4, 0x30, 0xec, 0x4c, 0xa3} header := []byte{0x81, 0x85} header = append(header, frameHeader.MaskingKey...) testHybiFrame(t, header, payload, maskedPayload, frameHeader) } func TestHybiShortBinaryFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: BinaryFrame} payload := []byte("hello") testHybiFrame(t, []byte{0x82, 0x05}, payload, payload, frameHeader) payload = make([]byte, 125) testHybiFrame(t, []byte{0x82, 125}, payload, payload, frameHeader) } func TestHybiControlFrame(t *testing.T) { payload := []byte("hello") frameHeader := &hybiFrameHeader{Fin: true, OpCode: PingFrame} testHybiFrame(t, []byte{0x89, 0x05}, payload, payload, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: PingFrame} testHybiFrame(t, []byte{0x89, 0x00}, nil, nil, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: PongFrame} testHybiFrame(t, []byte{0x8A, 0x05}, payload, payload, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: PongFrame} testHybiFrame(t, []byte{0x8A, 0x00}, nil, nil, frameHeader) frameHeader = &hybiFrameHeader{Fin: true, OpCode: CloseFrame} payload = []byte{0x03, 0xe8} // 1000 testHybiFrame(t, []byte{0x88, 0x02}, payload, payload, frameHeader) } func TestHybiLongFrame(t *testing.T) { frameHeader := &hybiFrameHeader{Fin: true, OpCode: TextFrame} payload := make([]byte, 126) testHybiFrame(t, []byte{0x81, 126, 0x00, 126}, payload, payload, frameHeader) payload = make([]byte, 65535) testHybiFrame(t, []byte{0x81, 126, 0xff, 0xff}, payload, payload, frameHeader) payload = make([]byte, 65536) testHybiFrame(t, []byte{0x81, 127, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}, payload, payload, frameHeader) } func TestHybiClientRead(t *testing.T) { wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o', 0x89, 0x05, 'h', 'e', 'l', 'l', 'o', // ping 0x81, 0x05, 'w', 'o', 'r', 'l', 'd'} br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) msg := make([]byte, 512) n, err := conn.Read(msg) if err != nil { t.Errorf("read 1st frame, error %q", err) } if n != 5 { t.Errorf("read 1st frame, expect 5, got %d", n) } if !bytes.Equal(wireData[2:7], msg[:n]) { t.Errorf("read 1st frame %v, got %v", wireData[2:7], msg[:n]) } n, err = conn.Read(msg) if err != nil { t.Errorf("read 2nd frame, error %q", err) } if n != 5 { t.Errorf("read 2nd frame, expect 5, got %d", n) } if !bytes.Equal(wireData[16:21], msg[:n]) { t.Errorf("read 2nd frame %v, got %v", wireData[16:21], msg[:n]) } n, err = conn.Read(msg) if err == nil { t.Errorf("read not EOF") } if n != 0 { t.Errorf("expect read 0, got %d", n) } } func TestHybiShortRead(t *testing.T) { wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o', 0x89, 0x05, 'h', 'e', 'l', 'l', 'o', // ping 0x81, 0x05, 'w', 'o', 'r', 'l', 'd'} br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) step := 0 pos := 0 expectedPos := []int{2, 5, 16, 19} expectedLen := []int{3, 2, 3, 2} for { msg := make([]byte, 3) n, err := conn.Read(msg) if step >= len(expectedPos) { if err == nil { t.Errorf("read not EOF") } if n != 0 { t.Errorf("expect read 0, got %d", n) } return } pos = expectedPos[step] endPos := pos + expectedLen[step] if err != nil { t.Errorf("read from %d, got error %q", pos, err) return } if n != endPos-pos { t.Errorf("read from %d, expect %d, got %d", pos, endPos-pos, n) } if !bytes.Equal(wireData[pos:endPos], msg[:n]) { t.Errorf("read from %d, frame %v, got %v", pos, wireData[pos:endPos], msg[:n]) } step++ } } func TestHybiServerRead(t *testing.T) { wireData := []byte{0x81, 0x85, 0xcc, 0x55, 0x80, 0x20, 0xa4, 0x30, 0xec, 0x4c, 0xa3, // hello 0x89, 0x85, 0xcc, 0x55, 0x80, 0x20, 0xa4, 0x30, 0xec, 0x4c, 0xa3, // ping: hello 0x81, 0x85, 0xed, 0x83, 0xb4, 0x24, 0x9a, 0xec, 0xc6, 0x48, 0x89, // world } br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, new(http.Request)) expected := [][]byte{[]byte("hello"), []byte("world")} msg := make([]byte, 512) n, err := conn.Read(msg) if err != nil { t.Errorf("read 1st frame, error %q", err) } if n != 5 { t.Errorf("read 1st frame, expect 5, got %d", n) } if !bytes.Equal(expected[0], msg[:n]) { t.Errorf("read 1st frame %q, got %q", expected[0], msg[:n]) } n, err = conn.Read(msg) if err != nil { t.Errorf("read 2nd frame, error %q", err) } if n != 5 { t.Errorf("read 2nd frame, expect 5, got %d", n) } if !bytes.Equal(expected[1], msg[:n]) { t.Errorf("read 2nd frame %q, got %q", expected[1], msg[:n]) } n, err = conn.Read(msg) if err == nil { t.Errorf("read not EOF") } if n != 0 { t.Errorf("expect read 0, got %d", n) } } func TestHybiServerReadWithoutMasking(t *testing.T) { wireData := []byte{0x81, 0x05, 'h', 'e', 'l', 'l', 'o'} br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, new(http.Request)) // server MUST close the connection upon receiving a non-masked frame. msg := make([]byte, 512) _, err := conn.Read(msg) if err != io.EOF { t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) } } func TestHybiClientReadWithMasking(t *testing.T) { wireData := []byte{0x81, 0x85, 0xcc, 0x55, 0x80, 0x20, 0xa4, 0x30, 0xec, 0x4c, 0xa3, // hello } br := bufio.NewReader(bytes.NewBuffer(wireData)) bw := bufio.NewWriter(bytes.NewBuffer([]byte{})) conn := newHybiConn(newConfig(t, "/"), bufio.NewReadWriter(br, bw), nil, nil) // client MUST close the connection upon receiving a masked frame. msg := make([]byte, 512) _, err := conn.Read(msg) if err != io.EOF { t.Errorf("read 1st frame, expect %q, but got %q", io.EOF, err) } } // Test the hybiServerHandshaker supports firefox implementation and // checks Connection request header include (but it's not necessary // equal to) "upgrade" func TestHybiServerFirefoxHandshake(t *testing.T) { config := new(Config) handshaker := &hybiServerHandshaker{Config: config} br := bufio.NewReader(strings.NewReader(`GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: keep-alive, upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 `)) req, err := http.ReadRequest(br) if err != nil { t.Fatal("request", err) } code, err := handshaker.ReadHandshake(br, req) if err != nil { t.Errorf("handshake failed: %v", err) } if code != http.StatusSwitchingProtocols { t.Errorf("status expected %q but got %q", http.StatusSwitchingProtocols, code) } b := bytes.NewBuffer([]byte{}) bw := bufio.NewWriter(b) config.Protocol = []string{"chat"} err = handshaker.AcceptHandshake(bw) if err != nil { t.Errorf("handshake response failed: %v", err) } expectedResponse := strings.Join([]string{ "HTTP/1.1 101 Switching Protocols", "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", "Sec-WebSocket-Protocol: chat", "", ""}, "\r\n") if b.String() != expectedResponse { t.Errorf("handshake expected %q but got %q", expectedResponse, b.String()) } } ================================================ FILE: vendor/golang.org/x/net/websocket/server.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/net/websocket/websocket.go ================================================ // 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. 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 ) // 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"} ) // 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 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. 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 } // 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() if err != nil { return n, err } 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. 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 } 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} ================================================ FILE: vendor/golang.org/x/net/websocket/websocket_test.go ================================================ // 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 ( "bytes" "fmt" "io" "log" "net" "net/http" "net/http/httptest" "net/url" "reflect" "runtime" "strings" "sync" "testing" "time" ) var serverAddr string var once sync.Once func echoServer(ws *Conn) { defer ws.Close() io.Copy(ws, ws) } type Count struct { S string N int } func countServer(ws *Conn) { defer ws.Close() for { var count Count err := JSON.Receive(ws, &count) if err != nil { return } count.N++ count.S = strings.Repeat(count.S, count.N) err = JSON.Send(ws, count) if err != nil { return } } } type testCtrlAndDataHandler struct { hybiFrameHandler } func (h *testCtrlAndDataHandler) WritePing(b []byte) (int, error) { h.hybiFrameHandler.conn.wio.Lock() defer h.hybiFrameHandler.conn.wio.Unlock() w, err := h.hybiFrameHandler.conn.frameWriterFactory.NewFrameWriter(PingFrame) if err != nil { return 0, err } n, err := w.Write(b) w.Close() return n, err } func ctrlAndDataServer(ws *Conn) { defer ws.Close() h := &testCtrlAndDataHandler{hybiFrameHandler: hybiFrameHandler{conn: ws}} ws.frameHandler = h go func() { for i := 0; ; i++ { var b []byte if i%2 != 0 { // with or without payload b = []byte(fmt.Sprintf("#%d-CONTROL-FRAME-FROM-SERVER", i)) } if _, err := h.WritePing(b); err != nil { break } if _, err := h.WritePong(b); err != nil { // unsolicited pong break } time.Sleep(10 * time.Millisecond) } }() b := make([]byte, 128) for { n, err := ws.Read(b) if err != nil { break } if _, err := ws.Write(b[:n]); err != nil { break } } } func subProtocolHandshake(config *Config, req *http.Request) error { for _, proto := range config.Protocol { if proto == "chat" { config.Protocol = []string{proto} return nil } } return ErrBadWebSocketProtocol } func subProtoServer(ws *Conn) { for _, proto := range ws.Config().Protocol { io.WriteString(ws, proto) } } func startServer() { http.Handle("/echo", Handler(echoServer)) http.Handle("/count", Handler(countServer)) http.Handle("/ctrldata", Handler(ctrlAndDataServer)) subproto := Server{ Handshake: subProtocolHandshake, Handler: Handler(subProtoServer), } http.Handle("/subproto", subproto) server := httptest.NewServer(nil) serverAddr = server.Listener.Addr().String() log.Print("Test WebSocket server listening on ", serverAddr) } func newConfig(t *testing.T, path string) *Config { config, _ := NewConfig(fmt.Sprintf("ws://%s%s", serverAddr, path), "http://localhost") return config } func TestEcho(t *testing.T) { once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/echo"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } msg := []byte("hello, world\n") if _, err := conn.Write(msg); err != nil { t.Errorf("Write: %v", err) } var actual_msg = make([]byte, 512) n, err := conn.Read(actual_msg) if err != nil { t.Errorf("Read: %v", err) } actual_msg = actual_msg[0:n] if !bytes.Equal(msg, actual_msg) { t.Errorf("Echo: expected %q got %q", msg, actual_msg) } conn.Close() } func TestAddr(t *testing.T) { once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/echo"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } ra := conn.RemoteAddr().String() if !strings.HasPrefix(ra, "ws://") || !strings.HasSuffix(ra, "/echo") { t.Errorf("Bad remote addr: %v", ra) } la := conn.LocalAddr().String() if !strings.HasPrefix(la, "http://") { t.Errorf("Bad local addr: %v", la) } conn.Close() } func TestCount(t *testing.T) { once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/count"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } var count Count count.S = "hello" if err := JSON.Send(conn, count); err != nil { t.Errorf("Write: %v", err) } if err := JSON.Receive(conn, &count); err != nil { t.Errorf("Read: %v", err) } if count.N != 1 { t.Errorf("count: expected %d got %d", 1, count.N) } if count.S != "hello" { t.Errorf("count: expected %q got %q", "hello", count.S) } if err := JSON.Send(conn, count); err != nil { t.Errorf("Write: %v", err) } if err := JSON.Receive(conn, &count); err != nil { t.Errorf("Read: %v", err) } if count.N != 2 { t.Errorf("count: expected %d got %d", 2, count.N) } if count.S != "hellohello" { t.Errorf("count: expected %q got %q", "hellohello", count.S) } conn.Close() } func TestWithQuery(t *testing.T) { once.Do(startServer) client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } config := newConfig(t, "/echo") config.Location, err = url.ParseRequestURI(fmt.Sprintf("ws://%s/echo?q=v", serverAddr)) if err != nil { t.Fatal("location url", err) } ws, err := NewClient(config, client) if err != nil { t.Errorf("WebSocket handshake: %v", err) return } ws.Close() } func testWithProtocol(t *testing.T, subproto []string) (string, error) { once.Do(startServer) client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } config := newConfig(t, "/subproto") config.Protocol = subproto ws, err := NewClient(config, client) if err != nil { return "", err } msg := make([]byte, 16) n, err := ws.Read(msg) if err != nil { return "", err } ws.Close() return string(msg[:n]), nil } func TestWithProtocol(t *testing.T) { proto, err := testWithProtocol(t, []string{"chat"}) if err != nil { t.Errorf("SubProto: unexpected error: %v", err) } if proto != "chat" { t.Errorf("SubProto: expected %q, got %q", "chat", proto) } } func TestWithTwoProtocol(t *testing.T) { proto, err := testWithProtocol(t, []string{"test", "chat"}) if err != nil { t.Errorf("SubProto: unexpected error: %v", err) } if proto != "chat" { t.Errorf("SubProto: expected %q, got %q", "chat", proto) } } func TestWithBadProtocol(t *testing.T) { _, err := testWithProtocol(t, []string{"test"}) if err != ErrBadStatus { t.Errorf("SubProto: expected %v, got %v", ErrBadStatus, err) } } func TestHTTP(t *testing.T) { once.Do(startServer) // If the client did not send a handshake that matches the protocol // specification, the server MUST return an HTTP response with an // appropriate error code (such as 400 Bad Request) resp, err := http.Get(fmt.Sprintf("http://%s/echo", serverAddr)) if err != nil { t.Errorf("Get: error %#v", err) return } if resp == nil { t.Error("Get: resp is null") return } if resp.StatusCode != http.StatusBadRequest { t.Errorf("Get: expected %q got %q", http.StatusBadRequest, resp.StatusCode) } } func TestTrailingSpaces(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=955 // The last runs of this create keys with trailing spaces that should not be // generated by the client. once.Do(startServer) config := newConfig(t, "/echo") for i := 0; i < 30; i++ { // body ws, err := DialConfig(config) if err != nil { t.Errorf("Dial #%d failed: %v", i, err) break } ws.Close() } } func TestDialConfigBadVersion(t *testing.T) { once.Do(startServer) config := newConfig(t, "/echo") config.Version = 1234 _, err := DialConfig(config) if dialerr, ok := err.(*DialError); ok { if dialerr.Err != ErrBadProtocolVersion { t.Errorf("dial expected err %q but got %q", ErrBadProtocolVersion, dialerr.Err) } } } func TestSmallBuffer(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=1145 // Read should be able to handle reading a fragment of a frame. once.Do(startServer) // websocket.Dial() client, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } conn, err := NewClient(newConfig(t, "/echo"), client) if err != nil { t.Errorf("WebSocket handshake error: %v", err) return } msg := []byte("hello, world\n") if _, err := conn.Write(msg); err != nil { t.Errorf("Write: %v", err) } var small_msg = make([]byte, 8) n, err := conn.Read(small_msg) if err != nil { t.Errorf("Read: %v", err) } if !bytes.Equal(msg[:len(small_msg)], small_msg) { t.Errorf("Echo: expected %q got %q", msg[:len(small_msg)], small_msg) } var second_msg = make([]byte, len(msg)) n, err = conn.Read(second_msg) if err != nil { t.Errorf("Read: %v", err) } second_msg = second_msg[0:n] if !bytes.Equal(msg[len(small_msg):], second_msg) { t.Errorf("Echo: expected %q got %q", msg[len(small_msg):], second_msg) } conn.Close() } var parseAuthorityTests = []struct { in *url.URL out string }{ { &url.URL{ Scheme: "ws", Host: "www.google.com", }, "www.google.com:80", }, { &url.URL{ Scheme: "wss", Host: "www.google.com", }, "www.google.com:443", }, { &url.URL{ Scheme: "ws", Host: "www.google.com:80", }, "www.google.com:80", }, { &url.URL{ Scheme: "wss", Host: "www.google.com:443", }, "www.google.com:443", }, // some invalid ones for parseAuthority. parseAuthority doesn't // concern itself with the scheme unless it actually knows about it { &url.URL{ Scheme: "http", Host: "www.google.com", }, "www.google.com", }, { &url.URL{ Scheme: "http", Host: "www.google.com:80", }, "www.google.com:80", }, { &url.URL{ Scheme: "asdf", Host: "127.0.0.1", }, "127.0.0.1", }, { &url.URL{ Scheme: "asdf", Host: "www.google.com", }, "www.google.com", }, } func TestParseAuthority(t *testing.T) { for _, tt := range parseAuthorityTests { out := parseAuthority(tt.in) if out != tt.out { t.Errorf("got %v; want %v", out, tt.out) } } } type closerConn struct { net.Conn closed int // count of the number of times Close was called } func (c *closerConn) Close() error { c.closed++ return c.Conn.Close() } func TestClose(t *testing.T) { if runtime.GOOS == "plan9" { t.Skip("see golang.org/issue/11454") } once.Do(startServer) conn, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal("dialing", err) } cc := closerConn{Conn: conn} client, err := NewClient(newConfig(t, "/echo"), &cc) if err != nil { t.Fatalf("WebSocket handshake: %v", err) } // set the deadline to ten minutes ago, which will have expired by the time // client.Close sends the close status frame. conn.SetDeadline(time.Now().Add(-10 * time.Minute)) if err := client.Close(); err == nil { t.Errorf("ws.Close(): expected error, got %v", err) } if cc.closed < 1 { t.Fatalf("ws.Close(): expected underlying ws.rwc.Close to be called > 0 times, got: %v", cc.closed) } } var originTests = []struct { req *http.Request origin *url.URL }{ { req: &http.Request{ Header: http.Header{ "Origin": []string{"http://www.example.com"}, }, }, origin: &url.URL{ Scheme: "http", Host: "www.example.com", }, }, { req: &http.Request{}, }, } func TestOrigin(t *testing.T) { conf := newConfig(t, "/echo") conf.Version = ProtocolVersionHybi13 for i, tt := range originTests { origin, err := Origin(conf, tt.req) if err != nil { t.Error(err) continue } if !reflect.DeepEqual(origin, tt.origin) { t.Errorf("#%d: got origin %v; want %v", i, origin, tt.origin) continue } } } func TestCtrlAndData(t *testing.T) { once.Do(startServer) c, err := net.Dial("tcp", serverAddr) if err != nil { t.Fatal(err) } ws, err := NewClient(newConfig(t, "/ctrldata"), c) if err != nil { t.Fatal(err) } defer ws.Close() h := &testCtrlAndDataHandler{hybiFrameHandler: hybiFrameHandler{conn: ws}} ws.frameHandler = h b := make([]byte, 128) for i := 0; i < 2; i++ { data := []byte(fmt.Sprintf("#%d-DATA-FRAME-FROM-CLIENT", i)) if _, err := ws.Write(data); err != nil { t.Fatalf("#%d: %v", i, err) } var ctrl []byte if i%2 != 0 { // with or without payload ctrl = []byte(fmt.Sprintf("#%d-CONTROL-FRAME-FROM-CLIENT", i)) } if _, err := h.WritePing(ctrl); err != nil { t.Fatalf("#%d: %v", i, err) } n, err := ws.Read(b) if err != nil { t.Fatalf("#%d: %v", i, err) } if !bytes.Equal(b[:n], data) { t.Fatalf("#%d: got %v; want %v", i, b[:n], data) } } } ================================================ FILE: vendor/golang.org/x/sys/.gitattributes ================================================ # Treat all files in this repo as binary, with no git magic updating # line endings. Windows users contributing to Go will need to use a # modern version of git and editors capable of LF line endings. # # We'll prevent accidental CRLF line endings from entering the repo # via the git-review gofmt checks. # # See golang.org/issue/9281 * -text ================================================ FILE: vendor/golang.org/x/sys/.gitignore ================================================ # Add no patterns to .hgignore except for files generated by the build. last-change ================================================ FILE: vendor/golang.org/x/sys/AUTHORS ================================================ # This source code refers to The Go Authors for copyright purposes. # The master list of authors is in the main Go distribution, # visible at http://tip.golang.org/AUTHORS. ================================================ FILE: vendor/golang.org/x/sys/CONTRIBUTING.md ================================================ # Contributing to Go Go is an open source project. It is the work of hundreds of contributors. We appreciate your help! ## Filing issues When [filing an issue](https://golang.org/issue/new), make sure to answer these five questions: 1. What version of Go are you using (`go version`)? 2. What operating system and processor architecture are you using? 3. What did you do? 4. What did you expect to see? 5. What did you see instead? General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. The gophers there will answer or ask you to file an issue if you've tripped over a bug. ## Contributing code Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) before sending patches. **We do not accept GitHub pull requests** (we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). Unless otherwise noted, the Go source files are distributed under the BSD-style license found in the LICENSE file. ================================================ FILE: vendor/golang.org/x/sys/CONTRIBUTORS ================================================ # This source code was written by the Go contributors. # The master list of contributors is in the main Go distribution, # visible at http://tip.golang.org/CONTRIBUTORS. ================================================ FILE: vendor/golang.org/x/sys/LICENSE ================================================ 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. ================================================ FILE: vendor/golang.org/x/sys/PATENTS ================================================ 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. ================================================ FILE: vendor/golang.org/x/sys/README ================================================ 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. ================================================ FILE: vendor/golang.org/x/sys/codereview.cfg ================================================ issuerepo: golang/go ================================================ FILE: vendor/golang.org/x/sys/plan9/asm.s ================================================ // 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. #include "textflag.h" TEXT ·use(SB),NOSPLIT,$0 RET ================================================ FILE: vendor/golang.org/x/sys/plan9/asm_plan9_386.s ================================================ // 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. #include "textflag.h" // // System call support for 386, Plan 9 // // Just jump to package syscall's implementation for all these functions. // The runtime may know about them. TEXT ·Syscall(SB),NOSPLIT,$0-32 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-44 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 ·seek(SB),NOSPLIT,$0-36 JMP syscall·seek(SB) TEXT ·exit(SB),NOSPLIT,$4-4 JMP syscall·exit(SB) ================================================ FILE: vendor/golang.org/x/sys/plan9/asm_plan9_amd64.s ================================================ // 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. #include "textflag.h" // // System call support for amd64, Plan 9 // // 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 ·RawSyscall(SB),NOSPLIT,$0-56 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-80 JMP syscall·RawSyscall6(SB) TEXT ·seek(SB),NOSPLIT,$0-56 JMP syscall·seek(SB) TEXT ·exit(SB),NOSPLIT,$8-8 JMP syscall·exit(SB) ================================================ FILE: vendor/golang.org/x/sys/plan9/const_plan9.go ================================================ package plan9 // Plan 9 Constants // Open modes const ( O_RDONLY = 0 O_WRONLY = 1 O_RDWR = 2 O_TRUNC = 16 O_CLOEXEC = 32 O_EXCL = 0x1000 ) // Rfork flags const ( RFNAMEG = 1 << 0 RFENVG = 1 << 1 RFFDG = 1 << 2 RFNOTEG = 1 << 3 RFPROC = 1 << 4 RFMEM = 1 << 5 RFNOWAIT = 1 << 6 RFCNAMEG = 1 << 10 RFCENVG = 1 << 11 RFCFDG = 1 << 12 RFREND = 1 << 13 RFNOMNT = 1 << 14 ) // Qid.Type bits const ( QTDIR = 0x80 QTAPPEND = 0x40 QTEXCL = 0x20 QTMOUNT = 0x10 QTAUTH = 0x08 QTTMP = 0x04 QTFILE = 0x00 ) // Dir.Mode bits const ( DMDIR = 0x80000000 DMAPPEND = 0x40000000 DMEXCL = 0x20000000 DMMOUNT = 0x10000000 DMAUTH = 0x08000000 DMTMP = 0x04000000 DMREAD = 0x4 DMWRITE = 0x2 DMEXEC = 0x1 ) const ( STATMAX = 65535 ERRMAX = 128 STATFIXLEN = 49 ) ================================================ FILE: vendor/golang.org/x/sys/plan9/dir_plan9.go ================================================ // 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. // Plan 9 directory marshalling. See intro(5). package plan9 import "errors" var ( ErrShortStat = errors.New("stat buffer too short") ErrBadStat = errors.New("malformed stat buffer") ErrBadName = errors.New("bad character in file name") ) // A Qid represents a 9P server's unique identification for a file. type Qid struct { Path uint64 // the file server's unique identification for the file Vers uint32 // version number for given Path Type uint8 // the type of the file (plan9.QTDIR for example) } // A Dir contains the metadata for a file. type Dir struct { // system-modified data Type uint16 // server type Dev uint32 // server subtype // file data Qid Qid // unique id from server Mode uint32 // permissions Atime uint32 // last read time Mtime uint32 // last write time Length int64 // file length Name string // last element of path Uid string // owner name Gid string // group name Muid string // last modifier name } var nullDir = Dir{ Type: ^uint16(0), Dev: ^uint32(0), Qid: Qid{ Path: ^uint64(0), Vers: ^uint32(0), Type: ^uint8(0), }, Mode: ^uint32(0), Atime: ^uint32(0), Mtime: ^uint32(0), Length: ^int64(0), } // Null assigns special "don't touch" values to members of d to // avoid modifying them during plan9.Wstat. func (d *Dir) Null() { *d = nullDir } // Marshal encodes a 9P stat message corresponding to d into b // // If there isn't enough space in b for a stat message, ErrShortStat is returned. func (d *Dir) Marshal(b []byte) (n int, err error) { n = STATFIXLEN + len(d.Name) + len(d.Uid) + len(d.Gid) + len(d.Muid) if n > len(b) { return n, ErrShortStat } for _, c := range d.Name { if c == '/' { return n, ErrBadName } } b = pbit16(b, uint16(n)-2) b = pbit16(b, d.Type) b = pbit32(b, d.Dev) b = pbit8(b, d.Qid.Type) b = pbit32(b, d.Qid.Vers) b = pbit64(b, d.Qid.Path) b = pbit32(b, d.Mode) b = pbit32(b, d.Atime) b = pbit32(b, d.Mtime) b = pbit64(b, uint64(d.Length)) b = pstring(b, d.Name) b = pstring(b, d.Uid) b = pstring(b, d.Gid) b = pstring(b, d.Muid) return n, nil } // UnmarshalDir decodes a single 9P stat message from b and returns the resulting Dir. // // If b is too small to hold a valid stat message, ErrShortStat is returned. // // If the stat message itself is invalid, ErrBadStat is returned. func UnmarshalDir(b []byte) (*Dir, error) { if len(b) < STATFIXLEN { return nil, ErrShortStat } size, buf := gbit16(b) if len(b) != int(size)+2 { return nil, ErrBadStat } b = buf var d Dir d.Type, b = gbit16(b) d.Dev, b = gbit32(b) d.Qid.Type, b = gbit8(b) d.Qid.Vers, b = gbit32(b) d.Qid.Path, b = gbit64(b) d.Mode, b = gbit32(b) d.Atime, b = gbit32(b) d.Mtime, b = gbit32(b) n, b := gbit64(b) d.Length = int64(n) var ok bool if d.Name, b, ok = gstring(b); !ok { return nil, ErrBadStat } if d.Uid, b, ok = gstring(b); !ok { return nil, ErrBadStat } if d.Gid, b, ok = gstring(b); !ok { return nil, ErrBadStat } if d.Muid, b, ok = gstring(b); !ok { return nil, ErrBadStat } return &d, nil } // pbit8 copies the 8-bit number v to b and returns the remaining slice of b. func pbit8(b []byte, v uint8) []byte { b[0] = byte(v) return b[1:] } // pbit16 copies the 16-bit number v to b in little-endian order and returns the remaining slice of b. func pbit16(b []byte, v uint16) []byte { b[0] = byte(v) b[1] = byte(v >> 8) return b[2:] } // pbit32 copies the 32-bit number v to b in little-endian order and returns the remaining slice of b. func pbit32(b []byte, v uint32) []byte { b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) return b[4:] } // pbit64 copies the 64-bit number v to b in little-endian order and returns the remaining slice of b. func pbit64(b []byte, v uint64) []byte { b[0] = byte(v) b[1] = byte(v >> 8) b[2] = byte(v >> 16) b[3] = byte(v >> 24) b[4] = byte(v >> 32) b[5] = byte(v >> 40) b[6] = byte(v >> 48) b[7] = byte(v >> 56) return b[8:] } // pstring copies the string s to b, prepending it with a 16-bit length in little-endian order, and // returning the remaining slice of b.. func pstring(b []byte, s string) []byte { b = pbit16(b, uint16(len(s))) n := copy(b, s) return b[n:] } // gbit8 reads an 8-bit number from b and returns it with the remaining slice of b. func gbit8(b []byte) (uint8, []byte) { return uint8(b[0]), b[1:] } // gbit16 reads a 16-bit number in little-endian order from b and returns it with the remaining slice of b. func gbit16(b []byte) (uint16, []byte) { return uint16(b[0]) | uint16(b[1])<<8, b[2:] } // gbit32 reads a 32-bit number in little-endian order from b and returns it with the remaining slice of b. func gbit32(b []byte) (uint32, []byte) { return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24, b[4:] } // gbit64 reads a 64-bit number in little-endian order from b and returns it with the remaining slice of b. func gbit64(b []byte) (uint64, []byte) { lo := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 hi := uint32(b[4]) | uint32(b[5])<<8 | uint32(b[6])<<16 | uint32(b[7])<<24 return uint64(lo) | uint64(hi)<<32, b[8:] } // gstring reads a string from b, prefixed with a 16-bit length in little-endian order. // It returns the string with the remaining slice of b and a boolean. If the length is // greater than the number of bytes in b, the boolean will be false. func gstring(b []byte) (string, []byte, bool) { n, b := gbit16(b) if int(n) > len(b) { return "", b, false } return string(b[:n]), b[n:], true } ================================================ FILE: vendor/golang.org/x/sys/plan9/env_plan9.go ================================================ // 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. // Plan 9 environment variables. package plan9 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() } ================================================ FILE: vendor/golang.org/x/sys/plan9/env_unset.go ================================================ // 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 plan9 import "syscall" func Unsetenv(key string) error { // This was added in Go 1.4. return syscall.Unsetenv(key) } ================================================ FILE: vendor/golang.org/x/sys/plan9/errors_plan9.go ================================================ // 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 plan9 import "syscall" // Constants const ( // Invented values to support what package os expects. O_CREAT = 0x02000 O_APPEND = 0x00400 O_NOCTTY = 0x00000 O_NONBLOCK = 0x00000 O_SYNC = 0x00000 O_ASYNC = 0x00000 S_IFMT = 0x1f000 S_IFIFO = 0x1000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFBLK = 0x6000 S_IFREG = 0x8000 S_IFLNK = 0xa000 S_IFSOCK = 0xc000 ) // Errors var ( EINVAL = syscall.NewError("bad arg in system call") ENOTDIR = syscall.NewError("not a directory") EISDIR = syscall.NewError("file is a directory") ENOENT = syscall.NewError("file does not exist") EEXIST = syscall.NewError("file already exists") EMFILE = syscall.NewError("no free file descriptors") EIO = syscall.NewError("i/o error") ENAMETOOLONG = syscall.NewError("file name too long") EINTR = syscall.NewError("interrupted") EPERM = syscall.NewError("permission denied") EBUSY = syscall.NewError("no free devices") ETIMEDOUT = syscall.NewError("connection timed out") EPLAN9 = syscall.NewError("not supported by plan 9") // The following errors do not correspond to any // Plan 9 system messages. Invented to support // what package os and others expect. EACCES = syscall.NewError("access permission denied") EAFNOSUPPORT = syscall.NewError("address family not supported by protocol") ) ================================================ FILE: vendor/golang.org/x/sys/plan9/mkall.sh ================================================ #!/usr/bin/env bash # 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. # The plan9 package provides access to the raw system call # interface of the underlying operating system. Porting Go to # a new architecture/operating system combination requires # some manual effort, though there are tools that automate # much of the process. The auto-generated files have names # beginning with z. # # This script runs or (given -n) prints suggested commands to generate z files # for the current system. Running those commands is not automatic. # This script is documentation more than anything else. # # * asm_${GOOS}_${GOARCH}.s # # This hand-written assembly file 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. # # * syscall_${GOOS}.go # # This hand-written Go file implements system calls that need # special handling and lists "//sys" comments giving prototypes # for ones that can be auto-generated. Mksyscall reads those # comments to generate the stubs. # # * syscall_${GOOS}_${GOARCH}.go # # Same as syscall_${GOOS}.go except that it contains code specific # to ${GOOS} on one particular architecture. # # * types_${GOOS}.c # # This hand-written C file includes standard C headers and then # creates typedef or enum names beginning with a dollar sign # (use of $ in variable names is a gcc extension). The hardest # part about preparing this file is figuring out which headers to # include and which symbols need to be #defined to get the # actual data structures that pass through to the kernel system calls. # Some C libraries present 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.c and types_linux.c for examples. # # * zerror_${GOOS}_${GOARCH}.go # # This machine-generated file defines the system's error numbers, # error strings, and signal numbers. The generator is "mkerrors.sh". # Usually no arguments are needed, but mkerrors.sh will pass its # arguments on to godefs. # # * zsyscall_${GOOS}_${GOARCH}.go # # Generated by mksyscall.pl; see syscall_${GOOS}.go above. # # * zsysnum_${GOOS}_${GOARCH}.go # # Generated by mksysnum_${GOOS}. # # * ztypes_${GOOS}_${GOARCH}.go # # Generated by godefs; see types_${GOOS}.c above. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="./mksyscall.pl" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= run="sh" case "$1" in -syscalls) for i in zsyscall*go do sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; plan9_386) mkerrors= mksyscall="./mksyscall.pl -l32 -plan9" mksysnum="./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h" mktypes="XXX" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in plan9) syscall_goos="syscall_$GOOS.go" if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos syscall_$GOOSARCH.go |gofmt >zsyscall_$GOOSARCH.go"; fi ;; esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go"; fi ) | $run ================================================ FILE: vendor/golang.org/x/sys/plan9/mkerrors.sh ================================================ #!/usr/bin/env bash # 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. # Generate Go code listing errors and other #defined constant # values (ENAMETOOLONG etc.), by asking the preprocessor # about the definitions. unset LANG export LC_ALL=C export LC_CTYPE=C CC=${CC:-gcc} uname=$(uname) includes=' #include #include #include #include #include #include #include #include #include #include #include #include #include ' ccflags="$@" # Write go tool cgo -godefs input. ( echo package plan9 echo echo '/*' indirect="includes_$(uname)" echo "${!indirect} $includes" echo '*/' echo 'import "C"' echo echo 'const (' # The gcc command line prints all the #defines # it encounters while processing the input echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | awk ' $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} $2 ~ /^(SCM_SRCRT)$/ {next} $2 ~ /^(MAP_FAILED)$/ {next} $2 !~ /^ETH_/ && $2 !~ /^EPROC_/ && $2 !~ /^EQUIV_/ && $2 !~ /^EXPR_/ && $2 ~ /^E[A-Z0-9_]+$/ || $2 ~ /^B[0-9_]+$/ || $2 ~ /^V[A-Z0-9]+$/ || $2 ~ /^CS[A-Z0-9]/ || $2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ || $2 ~ /^IGN/ || $2 ~ /^IX(ON|ANY|OFF)$/ || $2 ~ /^IN(LCR|PCK)$/ || $2 ~ /(^FLU?SH)|(FLU?SH$)/ || $2 ~ /^C(LOCAL|READ)$/ || $2 == "BRKINT" || $2 == "HUPCL" || $2 == "PENDIN" || $2 == "TOSTOP" || $2 ~ /^PAR/ || $2 ~ /^SIG[^_]/ || $2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ || $2 ~ /^IN_/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || $2 == "ICMPV6_FILTER" || $2 == "SOMAXCONN" || $2 == "NAME_MAX" || $2 == "IFNAMSIZ" || $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || $2 ~ /^SYSCTL_VERS/ || $2 ~ /^(MS|MNT)_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || $2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ || $2 ~ /^LINUX_REBOOT_CMD_/ || $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 !~ "NLA_TYPE_MASK" && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL)$/ && $2 ~ /^(BPF|DLT)_/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} {next} ' | sort echo ')' ) >_const.go # Pull out the error names for later. errors=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | sort ) # Pull out the signal names for later. signals=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort ) # Again, writing regexps to a file. echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT' echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep echo echo '// Errors' echo 'const (' cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= Errno(\1)/' echo ')' echo echo '// Signals' echo 'const (' cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= Signal(\1)/' echo ')' # Run C program to print error and syscall strings. ( echo -E " #include #include #include #include #include #include #define nelem(x) (sizeof(x)/sizeof((x)[0])) enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below int errors[] = { " for i in $errors do echo -E ' '$i, done echo -E " }; int signals[] = { " for i in $signals do echo -E ' '$i, done # Use -E because on some systems bash builtin interprets \n itself. echo -E ' }; static int intcmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main(void) { int i, j, e; char buf[1024], *p; printf("\n\n// Error table\n"); printf("var errors = [...]string {\n"); qsort(errors, nelem(errors), sizeof errors[0], intcmp); for(i=0; i 0 && errors[i-1] == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); printf("var signals = [...]string {\n"); qsort(signals, nelem(signals), sizeof signals[0], intcmp); for(i=0; i 0 && signals[i-1] == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; // cut trailing : number. p = strrchr(buf, ":"[0]); if(p) *p = '\0'; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); return 0; } ' ) >_errors.c $CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out ================================================ FILE: vendor/golang.org/x/sys/plan9/mksyscall.pl ================================================ #!/usr/bin/env perl # 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. # This program reads a file containing function prototypes # (like syscall_plan9.go) and generates system call bodies. # The prototypes are marked by lines beginning with "//sys" # and read like func declarations if //sys is replaced by func, but: # * The parameter lists must give a name for each argument. # This includes return parameters. # * The parameter lists must give a type for each argument: # the (x, y, z int) shorthand is not allowed. # * If the return parameter is an error number, it must be named errno. # A line beginning with //sysnb is like //sys, except that the # goroutine will not be suspended during the execution of the system # call. This must only be used for system calls which can never # block, as otherwise the system call could cause all goroutines to # hang. use strict; my $cmdline = "mksyscall.pl " . join(' ', @ARGV); my $errors = 0; my $_32bit = ""; my $plan9 = 0; my $openbsd = 0; my $netbsd = 0; my $dragonfly = 0; my $nacl = 0; my $arm = 0; # 64-bit value should use (even, odd)-pair if($ARGV[0] eq "-b32") { $_32bit = "big-endian"; shift; } elsif($ARGV[0] eq "-l32") { $_32bit = "little-endian"; shift; } if($ARGV[0] eq "-plan9") { $plan9 = 1; shift; } if($ARGV[0] eq "-openbsd") { $openbsd = 1; shift; } if($ARGV[0] eq "-netbsd") { $netbsd = 1; shift; } if($ARGV[0] eq "-dragonfly") { $dragonfly = 1; shift; } if($ARGV[0] eq "-nacl") { $nacl = 1; shift; } if($ARGV[0] eq "-arm") { $arm = 1; shift; } if($ARGV[0] =~ /^-/) { print STDERR "usage: mksyscall.pl [-b32 | -l32] [file ...]\n"; exit 1; } sub parseparamlist($) { my ($list) = @_; $list =~ s/^\s*//; $list =~ s/\s*$//; if($list eq "") { return (); } return split(/\s*,\s*/, $list); } sub parseparam($) { my ($p) = @_; if($p !~ /^(\S*) (\S*)$/) { print STDERR "$ARGV:$.: malformed parameter: $p\n"; $errors = 1; return ("xx", "int"); } return ($1, $2); } my $text = ""; while(<>) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, errno error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # Try in vain to keep people from editing this file. # The theory is that they jump into the middle of the file # without reading the header. $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; # Go function header. my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass dummy pointer in that case. # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). $text .= "\tvar _p$n unsafe.Pointer\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; $text .= "\n"; push @args, "uintptr(_p$n)", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && ($openbsd || $netbsd)) { push @args, "0"; if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $dragonfly) { if ($func !~ /^extp(read|write)/i) { push @args, "0"; } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $_32bit ne "") { if(@args % 2 && $arm) { # arm abi specifies 64-bit argument uses # (even, odd) pair push @args, "0" } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name>>32)"; } } else { push @args, "uintptr($name)"; } } # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { $asm = "RawSyscall"; } if(@args <= 3) { while(@args < 3) { push @args, "0"; } } elsif(@args <= 6) { $asm .= "6"; while(@args < 6) { push @args, "0"; } } elsif(@args <= 9) { $asm .= "9"; while(@args < 9) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # System call number. if($sysname eq "") { $sysname = "SYS_$func"; $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar $sysname =~ y/a-z/A-Z/; if($nacl) { $sysname =~ y/A-Z/a-z/; } } # Actual call. my $args = join(', ', @args); my $call = "$asm($sysname, $args)"; # Assign return values. my $body = ""; my @ret = ("_", "_", "_"); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err" && !$plan9) { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } elsif($name eq "err" && $plan9) { $ret[0] = "r0"; $ret[2] = "e1"; next; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1" || $plan9) { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($plan9 && $ret[2] eq "e1") { $text .= "\tif int32(r0) == -1 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } elsif ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n\n"; } chomp $text; chomp $text; if($errors) { exit 1; } print <= 10 { buf[i] = byte(val%10 + '0') i-- val /= 10 } buf[i] = byte(val + '0') return string(buf[i:]) } ================================================ FILE: vendor/golang.org/x/sys/plan9/syscall.go ================================================ // 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 plan9 // Package plan9 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 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.ErrorString. package plan9 // import "golang.org/x/sys/plan9" import "unsafe" // 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 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 } // 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) ================================================ FILE: vendor/golang.org/x/sys/plan9/syscall_plan9.go ================================================ // 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. // Plan 9 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 plan9 import ( "syscall" "unsafe" ) // A Note is a string describing a process note. // It implements the os.Signal interface. type Note string func (n Note) Signal() {} func (n Note) String() string { return string(n) } var ( Stdin = 0 Stdout = 1 Stderr = 2 ) // For testing: clients can set this flag to force // creation of IPv6 sockets to return EAFNOSUPPORT. var SocketDisableIPv6 bool func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.ErrorString) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.ErrorString) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr) func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr) func atoi(b []byte) (n uint) { n = 0 for i := 0; i < len(b); i++ { n = n*10 + uint(b[i]-'0') } return } func cstring(s []byte) string { for i := range s { if s[i] == 0 { return string(s[0:i]) } } return string(s) } func errstr() string { var buf [ERRMAX]byte RawSyscall(SYS_ERRSTR, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), 0) buf[len(buf)-1] = 0 return cstring(buf[:]) } // Implemented in assembly to import from runtime. func exit(code int) func Exit(code int) { exit(code) } func readnum(path string) (uint, error) { var b [12]byte fd, e := Open(path, O_RDONLY) if e != nil { return 0, e } defer Close(fd) n, e := Pread(fd, b[:], 0) if e != nil { return 0, e } m := 0 for ; m < n && b[m] == ' '; m++ { } return atoi(b[m : n-1]), nil } func Getpid() (pid int) { n, _ := readnum("#c/pid") return int(n) } func Getppid() (ppid int) { n, _ := readnum("#c/ppid") return int(n) } func Read(fd int, p []byte) (n int, err error) { return Pread(fd, p, -1) } func Write(fd int, p []byte) (n int, err error) { return Pwrite(fd, p, -1) } var ioSync int64 //sys fd2path(fd int, buf []byte) (err error) func Fd2path(fd int) (path string, err error) { var buf [512]byte e := fd2path(fd, buf[:]) if e != nil { return "", e } return cstring(buf[:]), nil } //sys pipe(p *[2]int32) (err error) func Pipe(p []int) (err error) { if len(p) != 2 { return syscall.ErrorString("bad arg in system call") } var pp [2]int32 err = pipe(&pp) 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(placeholder uintptr, fd int, offset int64, whence int) (newoffset int64, err string) func Seek(fd int, offset int64, whence int) (newoffset int64, err error) { newoffset, e := seek(0, fd, offset, whence) if newoffset == -1 { err = syscall.ErrorString(e) } return } func Mkdir(path string, mode uint32) (err error) { fd, err := Create(path, O_RDONLY, DMDIR|mode) if fd != -1 { Close(fd) } return } type Waitmsg struct { Pid int Time [3]uint32 Msg string } func (w Waitmsg) Exited() bool { return true } func (w Waitmsg) Signaled() bool { return false } func (w Waitmsg) ExitStatus() int { if len(w.Msg) == 0 { // a normal exit returns no message return 0 } return 1 } //sys await(s []byte) (n int, err error) func Await(w *Waitmsg) (err error) { var buf [512]byte var f [5][]byte n, err := await(buf[:]) if err != nil || w == nil { return } nf := 0 p := 0 for i := 0; i < n && nf < len(f)-1; i++ { if buf[i] == ' ' { f[nf] = buf[p:i] p = i + 1 nf++ } } f[nf] = buf[p:] nf++ if nf != len(f) { return syscall.ErrorString("invalid wait message") } w.Pid = int(atoi(f[0])) w.Time[0] = uint32(atoi(f[1])) w.Time[1] = uint32(atoi(f[2])) w.Time[2] = uint32(atoi(f[3])) w.Msg = cstring(f[4]) if w.Msg == "''" { // await() returns '' for no error w.Msg = "" } return } func Unmount(name, old string) (err error) { fixwd() oldp, err := BytePtrFromString(old) if err != nil { return err } oldptr := uintptr(unsafe.Pointer(oldp)) var r0 uintptr var e syscall.ErrorString // bind(2) man page: If name is zero, everything bound or mounted upon old is unbound or unmounted. if name == "" { r0, _, e = Syscall(SYS_UNMOUNT, _zero, oldptr, 0) } else { namep, err := BytePtrFromString(name) if err != nil { return err } r0, _, e = Syscall(SYS_UNMOUNT, uintptr(unsafe.Pointer(namep)), oldptr, 0) } if int32(r0) == -1 { err = e } return } func Fchdir(fd int) (err error) { path, err := Fd2path(fd) if err != nil { return } return Chdir(path) } type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } 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 nsec() int64 { var scratch int64 r0, _, _ := Syscall(SYS_NSEC, uintptr(unsafe.Pointer(&scratch)), 0, 0) // TODO(aram): remove hack after I fix _nsec in the pc64 kernel. if r0 == 0 { return scratch } return int64(r0) } func Gettimeofday(tv *Timeval) error { nsec := nsec() *tv = NsecToTimeval(nsec) return nil } func Getpagesize() int { return 0x1000 } func Getegid() (egid int) { return -1 } func Geteuid() (euid int) { return -1 } func Getgid() (gid int) { return -1 } func Getuid() (uid int) { return -1 } func Getgroups() (gids []int, err error) { return make([]int, 0), nil } //sys open(path string, mode int) (fd int, err error) func Open(path string, mode int) (fd int, err error) { fixwd() return open(path, mode) } //sys create(path string, mode int, perm uint32) (fd int, err error) func Create(path string, mode int, perm uint32) (fd int, err error) { fixwd() return create(path, mode, perm) } //sys remove(path string) (err error) func Remove(path string) error { fixwd() return remove(path) } //sys stat(path string, edir []byte) (n int, err error) func Stat(path string, edir []byte) (n int, err error) { fixwd() return stat(path, edir) } //sys bind(name string, old string, flag int) (err error) func Bind(name string, old string, flag int) (err error) { fixwd() return bind(name, old, flag) } //sys mount(fd int, afd int, old string, flag int, aname string) (err error) func Mount(fd int, afd int, old string, flag int, aname string) (err error) { fixwd() return mount(fd, afd, old, flag, aname) } //sys wstat(path string, edir []byte) (err error) func Wstat(path string, edir []byte) (err error) { fixwd() return wstat(path, edir) } //sys chdir(path string) (err error) //sys Dup(oldfd int, newfd int) (fd 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 Close(fd int) (err error) //sys Fstat(fd int, edir []byte) (n int, err error) //sys Fwstat(fd int, edir []byte) (err error) ================================================ FILE: vendor/golang.org/x/sys/plan9/syscall_test.go ================================================ // 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 plan9 package plan9_test import ( "testing" "golang.org/x/sys/plan9" ) func testSetGetenv(t *testing.T, key, value string) { err := plan9.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := plan9.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } ================================================ FILE: vendor/golang.org/x/sys/plan9/zsyscall_plan9_386.go ================================================ // mksyscall.pl -l32 -plan9 syscall_plan9.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package plan9 import "unsafe" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fd2path(fd int, buf []byte) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FD2PATH, uintptr(fd), uintptr(_p0), uintptr(len(buf))) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]int32) (err error) { r0, _, e1 := Syscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func await(s []byte) (n int, err error) { var _p0 unsafe.Pointer if len(s) > 0 { _p0 = unsafe.Pointer(&s[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_AWAIT, uintptr(_p0), uintptr(len(s)), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func open(path string, mode int) (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), 0) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func create(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_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func remove(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, edir []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(name string, old string, flag int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(old) if err != nil { return } r0, _, e1 := Syscall(SYS_BIND, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(fd int, afd int, old string, flag int, aname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(old) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(aname) if err != nil { return } r0, _, e1 := Syscall6(SYS_MOUNT, uintptr(fd), uintptr(afd), uintptr(unsafe.Pointer(_p0)), uintptr(flag), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wstat(path string, edir []byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = 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 } r0, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int, newfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), uintptr(newfd), 0) fd = int(r0) if int32(r0) == -1 { err = 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 int32(r0) == -1 { err = 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 int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { r0, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, edir []byte) (n int, err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fwstat(fd int, edir []byte) (err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FWSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) if int32(r0) == -1 { err = e1 } return } ================================================ FILE: vendor/golang.org/x/sys/plan9/zsyscall_plan9_amd64.go ================================================ // mksyscall.pl -l32 -plan9 syscall_plan9.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT package plan9 import "unsafe" // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fd2path(fd int, buf []byte) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FD2PATH, uintptr(fd), uintptr(_p0), uintptr(len(buf))) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func pipe(p *[2]int32) (err error) { r0, _, e1 := Syscall(SYS_PIPE, uintptr(unsafe.Pointer(p)), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func await(s []byte) (n int, err error) { var _p0 unsafe.Pointer if len(s) > 0 { _p0 = unsafe.Pointer(&s[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_AWAIT, uintptr(_p0), uintptr(len(s)), 0) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func open(path string, mode int) (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), 0) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func create(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_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(perm)) use(unsafe.Pointer(_p0)) fd = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func remove(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall(SYS_REMOVE, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func stat(path string, edir []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_STAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(name string, old string, flag int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(name) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(old) if err != nil { return } r0, _, e1 := Syscall(SYS_BIND, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(flag)) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(fd int, afd int, old string, flag int, aname string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(old) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(aname) if err != nil { return } r0, _, e1 := Syscall6(SYS_MOUNT, uintptr(fd), uintptr(afd), uintptr(unsafe.Pointer(_p0)), uintptr(flag), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wstat(path string, edir []byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(edir) > 0 { _p1 = unsafe.Pointer(&edir[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WSTAT, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(edir))) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = 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 } r0, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int, newfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), uintptr(newfd), 0) fd = int(r0) if int32(r0) == -1 { err = 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 int32(r0) == -1 { err = 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 int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { r0, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fstat(fd int, edir []byte) (n int, err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) n = int(r0) if int32(r0) == -1 { err = e1 } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fwstat(fd int, edir []byte) (err error) { var _p0 unsafe.Pointer if len(edir) > 0 { _p0 = unsafe.Pointer(&edir[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_FWSTAT, uintptr(fd), uintptr(_p0), uintptr(len(edir))) if int32(r0) == -1 { err = e1 } return } ================================================ FILE: vendor/golang.org/x/sys/plan9/zsysnum_plan9.go ================================================ // mksysnum_plan9.sh /opt/plan9/sys/src/libc/9syscall/sys.h // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT package plan9 const ( SYS_SYSR1 = 0 SYS_BIND = 2 SYS_CHDIR = 3 SYS_CLOSE = 4 SYS_DUP = 5 SYS_ALARM = 6 SYS_EXEC = 7 SYS_EXITS = 8 SYS_FAUTH = 10 SYS_SEGBRK = 12 SYS_OPEN = 14 SYS_OSEEK = 16 SYS_SLEEP = 17 SYS_RFORK = 19 SYS_PIPE = 21 SYS_CREATE = 22 SYS_FD2PATH = 23 SYS_BRK_ = 24 SYS_REMOVE = 25 SYS_NOTIFY = 28 SYS_NOTED = 29 SYS_SEGATTACH = 30 SYS_SEGDETACH = 31 SYS_SEGFREE = 32 SYS_SEGFLUSH = 33 SYS_RENDEZVOUS = 34 SYS_UNMOUNT = 35 SYS_SEMACQUIRE = 37 SYS_SEMRELEASE = 38 SYS_SEEK = 39 SYS_FVERSION = 40 SYS_ERRSTR = 41 SYS_STAT = 42 SYS_FSTAT = 43 SYS_WSTAT = 44 SYS_FWSTAT = 45 SYS_MOUNT = 46 SYS_AWAIT = 47 SYS_PREAD = 50 SYS_PWRITE = 51 SYS_TSEMACQUIRE = 52 SYS_NSEC = 53 ) ================================================ FILE: vendor/golang.org/x/sys/unix/.gitignore ================================================ _obj/ ================================================ FILE: vendor/golang.org/x/sys/unix/asm.s ================================================ // 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 ================================================ FILE: vendor/golang.org/x/sys/unix/asm_darwin_386.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_darwin_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_darwin_arm.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_darwin_arm64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_dragonfly_386.s ================================================ // 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-32 JMP syscall·Syscall(SB) TEXT ·Syscall6(SB),NOSPLIT,$0-44 JMP syscall·Syscall6(SB) TEXT ·Syscall9(SB),NOSPLIT,$0-56 JMP syscall·Syscall9(SB) TEXT ·RawSyscall(SB),NOSPLIT,$0-32 JMP syscall·RawSyscall(SB) TEXT ·RawSyscall6(SB),NOSPLIT,$0-44 JMP syscall·RawSyscall6(SB) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_dragonfly_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_freebsd_386.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_freebsd_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_freebsd_arm.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_linux_386.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_linux_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_linux_arm.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_linux_arm64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_linux_ppc64x.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_netbsd_386.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_netbsd_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_netbsd_arm.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_openbsd_386.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_openbsd_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/asm_solaris_amd64.s ================================================ // 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-64 JMP syscall·sysvicall6(SB) TEXT ·rawSysvicall6(SB),NOSPLIT,$0-64 JMP syscall·rawSysvicall6(SB) ================================================ FILE: vendor/golang.org/x/sys/unix/constants.go ================================================ // 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/creds_test.go ================================================ // 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 package unix_test import ( "bytes" "net" "os" "syscall" "testing" "golang.org/x/sys/unix" ) // TestSCMCredentials tests the sending and receiving of credentials // (PID, UID, GID) in an ancillary message between two UNIX // sockets. The SO_PASSCRED socket option is enabled on the sending // socket for this to work. func TestSCMCredentials(t *testing.T) { fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer unix.Close(fds[0]) defer unix.Close(fds[1]) err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1) if err != nil { t.Fatalf("SetsockoptInt: %v", err) } srvFile := os.NewFile(uintptr(fds[0]), "server") defer srvFile.Close() srv, err := net.FileConn(srvFile) if err != nil { t.Errorf("FileConn: %v", err) return } defer srv.Close() cliFile := os.NewFile(uintptr(fds[1]), "client") defer cliFile.Close() cli, err := net.FileConn(cliFile) if err != nil { t.Errorf("FileConn: %v", err) return } defer cli.Close() var ucred unix.Ucred if os.Getuid() != 0 { ucred.Pid = int32(os.Getpid()) ucred.Uid = 0 ucred.Gid = 0 oob := unix.UnixCredentials(&ucred) _, _, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) if op, ok := err.(*net.OpError); ok { err = op.Err } if sys, ok := err.(*os.SyscallError); ok { err = sys.Err } if err != syscall.EPERM { t.Fatalf("WriteMsgUnix failed with %v, want EPERM", err) } } ucred.Pid = int32(os.Getpid()) ucred.Uid = uint32(os.Getuid()) ucred.Gid = uint32(os.Getgid()) oob := unix.UnixCredentials(&ucred) // this is going to send a dummy byte n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil) if err != nil { t.Fatalf("WriteMsgUnix: %v", err) } if n != 0 { t.Fatalf("WriteMsgUnix n = %d, want 0", n) } if oobn != len(oob) { t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob)) } oob2 := make([]byte, 10*len(oob)) n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2) if err != nil { t.Fatalf("ReadMsgUnix: %v", err) } if flags != 0 { t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags) } if n != 1 { t.Fatalf("ReadMsgUnix n = %d, want 1 (dummy byte)", n) } if oobn2 != oobn { // without SO_PASSCRED set on the socket, ReadMsgUnix will // return zero oob bytes t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn) } oob2 = oob2[:oobn2] if !bytes.Equal(oob, oob2) { t.Fatal("ReadMsgUnix oob bytes don't match") } scm, err := unix.ParseSocketControlMessage(oob2) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } newUcred, err := unix.ParseUnixCredentials(&scm[0]) if err != nil { t.Fatalf("ParseUnixCredentials: %v", err) } if *newUcred != ucred { t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred) } } ================================================ FILE: vendor/golang.org/x/sys/unix/env_unix.go ================================================ // 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() } ================================================ FILE: vendor/golang.org/x/sys/unix/env_unset.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/export_test.go ================================================ // 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 var Itoa = itoa ================================================ FILE: vendor/golang.org/x/sys/unix/flock.go ================================================ // +build linux darwin freebsd openbsd netbsd dragonfly // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/flock_linux_32bit.go ================================================ // +build linux,386 linux,arm // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/gccgo.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/gccgo_c.c ================================================ // 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 #include #include #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))) { } ================================================ FILE: vendor/golang.org/x/sys/unix/gccgo_linux_amd64.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/mkall.sh ================================================ #!/usr/bin/env bash # 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. # The unix package provides access to the raw system call # interface of the underlying operating system. Porting Go to # a new architecture/operating system combination requires # some manual effort, though there are tools that automate # much of the process. The auto-generated files have names # beginning with z. # # This script runs or (given -n) prints suggested commands to generate z files # for the current system. Running those commands is not automatic. # This script is documentation more than anything else. # # * asm_${GOOS}_${GOARCH}.s # # This hand-written assembly file 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. # # * syscall_${GOOS}.go # # This hand-written Go file implements system calls that need # special handling and lists "//sys" comments giving prototypes # for ones that can be auto-generated. Mksyscall reads those # comments to generate the stubs. # # * syscall_${GOOS}_${GOARCH}.go # # Same as syscall_${GOOS}.go except that it contains code specific # to ${GOOS} on one particular architecture. # # * types_${GOOS}.c # # This hand-written C file includes standard C headers and then # creates typedef or enum names beginning with a dollar sign # (use of $ in variable names is a gcc extension). The hardest # part about preparing this file is figuring out which headers to # include and which symbols need to be #defined to get the # actual data structures that pass through to the kernel system calls. # Some C libraries present 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.c and types_linux.c for examples. # # * zerror_${GOOS}_${GOARCH}.go # # This machine-generated file defines the system's error numbers, # error strings, and signal numbers. The generator is "mkerrors.sh". # Usually no arguments are needed, but mkerrors.sh will pass its # arguments on to godefs. # # * zsyscall_${GOOS}_${GOARCH}.go # # Generated by mksyscall.pl; see syscall_${GOOS}.go above. # # * zsysnum_${GOOS}_${GOARCH}.go # # Generated by mksysnum_${GOOS}. # # * ztypes_${GOOS}_${GOARCH}.go # # Generated by godefs; see types_${GOOS}.c above. GOOSARCH="${GOOS}_${GOARCH}" # defaults mksyscall="./mksyscall.pl" mkerrors="./mkerrors.sh" zerrors="zerrors_$GOOSARCH.go" mksysctl="" zsysctl="zsysctl_$GOOSARCH.go" mksysnum= mktypes= run="sh" case "$1" in -syscalls) for i in zsyscall*go do sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i rm _$i done exit 0 ;; -n) run="cat" shift esac case "$#" in 0) ;; *) echo 'usage: mkall.sh [-n]' 1>&2 exit 2 esac GOOSARCH_in=syscall_$GOOSARCH.go case "$GOOSARCH" in _* | *_ | _) echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2 exit 1 ;; darwin_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_amd64) mkerrors="$mkerrors -m64" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_arm) mkerrors="$mkerrors" mksysnum="./mksysnum_darwin.pl /usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; darwin_arm64) mkerrors="$mkerrors -m64" mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; dragonfly_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -dragonfly" mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; dragonfly_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -dragonfly" mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_amd64) mkerrors="$mkerrors -m64" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; freebsd_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -arm" mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl" # Let the type of C char be singed for making the bare syscall # API consistent across over platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; linux_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32" mksysnum="./mksysnum_linux.pl /usr/include/asm/unistd_32.h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_amd64) unistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1) if [ "$unistd_h" = "" ]; then echo >&2 cannot find unistd_64.h exit 1 fi mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_arm) mkerrors="$mkerrors" mksyscall="./mksyscall.pl -l32 -arm" mksysnum="curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_arm64) unistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1) if [ "$unistd_h" = "" ]; then echo >&2 cannot find unistd_64.h exit 1 fi mksysnum="./mksysnum_linux.pl $unistd_h" # Let the type of C char be singed for making the bare syscall # API consistent across over platforms. mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char" ;; linux_ppc64) GOOSARCH_in=syscall_linux_ppc64x.go unistd_h=/usr/include/asm/unistd.h mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; linux_ppc64le) GOOSARCH_in=syscall_linux_ppc64x.go unistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h mkerrors="$mkerrors -m64" mksysnum="./mksysnum_linux.pl $unistd_h" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -netbsd" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; netbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -netbsd" mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_386) mkerrors="$mkerrors -m32" mksyscall="./mksyscall.pl -l32 -openbsd" mksysctl="./mksysctl_openbsd.pl" zsysctl="zsysctl_openbsd.go" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; openbsd_amd64) mkerrors="$mkerrors -m64" mksyscall="./mksyscall.pl -openbsd" mksysctl="./mksysctl_openbsd.pl" zsysctl="zsysctl_openbsd.go" mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl" mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; solaris_amd64) mksyscall="./mksyscall_solaris.pl" mkerrors="$mkerrors -m64" mksysnum= mktypes="GOARCH=$GOARCH go tool cgo -godefs" ;; *) echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2 exit 1 ;; esac ( if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi case "$GOOS" in *) syscall_goos="syscall_$GOOS.go" case "$GOOS" in darwin | dragonfly | freebsd | netbsd | openbsd) syscall_goos="syscall_bsd.go $syscall_goos" ;; esac if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi ;; esac if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi if [ -n "$mktypes" ]; then echo "echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go"; echo "$mktypes types_$GOOS.go | gofmt >>ztypes_$GOOSARCH.go"; fi ) | $run ================================================ FILE: vendor/golang.org/x/sys/unix/mkerrors.sh ================================================ #!/usr/bin/env bash # 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. # Generate Go code listing errors and other #defined constant # values (ENAMETOOLONG etc.), by asking the preprocessor # about the definitions. unset LANG export LC_ALL=C export LC_CTYPE=C if test -z "$GOARCH" -o -z "$GOOS"; then echo 1>&2 "GOARCH or GOOS not defined in environment" exit 1 fi CC=${CC:-cc} if [[ "$GOOS" -eq "solaris" ]]; then # Assumes GNU versions of utilities in PATH. export PATH=/usr/gnu/bin:$PATH fi uname=$(uname) includes_Darwin=' #define _DARWIN_C_SOURCE #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes_DragonFly=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes_FreeBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if __FreeBSD__ >= 10 #define IFT_CARP 0xf8 // IFT_CARP is deprecated in FreeBSD 10 #undef SIOCAIFADDR #define SIOCAIFADDR _IOW(105, 26, struct oifaliasreq) // ifaliasreq contains if_data #undef SIOCSIFPHYADDR #define SIOCSIFPHYADDR _IOW(105, 70, struct oifaliasreq) // ifaliasreq contains if_data #endif ' includes_Linux=' #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #ifndef __LP64__ #define _FILE_OFFSET_BITS 64 #endif #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef MSG_FASTOPEN #define MSG_FASTOPEN 0x20000000 #endif #ifndef PTRACE_GETREGS #define PTRACE_GETREGS 0xc #endif #ifndef PTRACE_SETREGS #define PTRACE_SETREGS 0xd #endif ' includes_NetBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Needed since refers to it... #define schedppq 1 ' includes_OpenBSD=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // We keep some constants not supported in OpenBSD 5.5 and beyond for // the promise of compatibility. #define EMUL_ENABLED 0x1 #define EMUL_NATIVE 0x2 #define IPV6_FAITH 0x1d #define IPV6_OPTIONS 0x1 #define IPV6_RTHDR_STRICT 0x1 #define IPV6_SOCKOPT_RESERVED1 0x3 #define SIOCGIFGENERIC 0xc020693a #define SIOCSIFGENERIC 0x80206939 #define WALTSIG 0x4 ' includes_SunOS=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' includes=' #include #include #include #include #include #include #include #include #include #include #include #include #include #include ' ccflags="$@" # Write go tool cgo -godefs input. ( echo package unix echo echo '/*' indirect="includes_$(uname)" echo "${!indirect} $includes" echo '*/' echo 'import "C"' echo 'import "syscall"' echo echo 'const (' # The gcc command line prints all the #defines # it encounters while processing the input echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags | awk ' $1 != "#define" || $2 ~ /\(/ || $3 == "" {next} $2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next} # 386 registers $2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next} $2 ~ /^(SCM_SRCRT)$/ {next} $2 ~ /^(MAP_FAILED)$/ {next} $2 ~ /^ELF_.*$/ {next}# contains ELF_ARCH, etc. $2 ~ /^EXTATTR_NAMESPACE_NAMES/ || $2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next} $2 !~ /^ETH_/ && $2 !~ /^EPROC_/ && $2 !~ /^EQUIV_/ && $2 !~ /^EXPR_/ && $2 ~ /^E[A-Z0-9_]+$/ || $2 ~ /^B[0-9_]+$/ || $2 == "BOTHER" || $2 ~ /^CI?BAUD(EX)?$/ || $2 == "IBSHIFT" || $2 ~ /^V[A-Z0-9]+$/ || $2 ~ /^CS[A-Z0-9]/ || $2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ || $2 ~ /^IGN/ || $2 ~ /^IX(ON|ANY|OFF)$/ || $2 ~ /^IN(LCR|PCK)$/ || $2 ~ /(^FLU?SH)|(FLU?SH$)/ || $2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ || $2 == "BRKINT" || $2 == "HUPCL" || $2 == "PENDIN" || $2 == "TOSTOP" || $2 == "XCASE" || $2 == "ALTWERASE" || $2 == "NOKERNINFO" || $2 ~ /^PAR/ || $2 ~ /^SIG[^_]/ || $2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ || $2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ || $2 ~ /^O?XTABS$/ || $2 ~ /^TC[IO](ON|OFF)$/ || $2 ~ /^IN_/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || $2 == "ICMPV6_FILTER" || $2 == "SOMAXCONN" || $2 == "NAME_MAX" || $2 == "IFNAMSIZ" || $2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ || $2 ~ /^SYSCTL_VERS/ || $2 ~ /^(MS|MNT)_/ || $2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ || $2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ || $2 ~ /^LINUX_REBOOT_CMD_/ || $2 ~ /^LINUX_REBOOT_MAGIC[12]$/ || $2 !~ "NLA_TYPE_MASK" && $2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ || $2 ~ /^SIOC/ || $2 ~ /^TIOC/ || $2 ~ /^TCGET/ || $2 ~ /^TCSET/ || $2 ~ /^TC(FLSH|SBRKP?|XONC)$/ || $2 !~ "RTF_BITS" && $2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ || $2 ~ /^BIOC/ || $2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ || $2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ || $2 ~ /^PRIO_(PROCESS|PGRP|USER)/ || $2 ~ /^CLONE_[A-Z_]+/ || $2 !~ /^(BPF_TIMEVAL)$/ && $2 ~ /^(BPF|DLT)_/ || $2 ~ /^CLOCK_/ || $2 !~ "WMESGLEN" && $2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)} $2 ~ /^__WCOREFLAG$/ {next} $2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)} {next} ' | sort echo ')' ) >_const.go # Pull out the error names for later. errors=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' | sort ) # Pull out the signal names for later. signals=$( echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort ) # Again, writing regexps to a file. echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' | sort >_error.grep echo '#include ' | $CC -x c - -E -dM $ccflags | awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' | egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' | sort >_signal.grep echo '// mkerrors.sh' "$@" echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT' echo echo "// +build ${GOARCH},${GOOS}" echo go tool cgo -godefs -- "$@" _const.go >_error.out cat _error.out | grep -vf _error.grep | grep -vf _signal.grep echo echo '// Errors' echo 'const (' cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/' echo ')' echo echo '// Signals' echo 'const (' cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/' echo ')' # Run C program to print error and syscall strings. ( echo -E " #include #include #include #include #include #include #define nelem(x) (sizeof(x)/sizeof((x)[0])) enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below int errors[] = { " for i in $errors do echo -E ' '$i, done echo -E " }; int signals[] = { " for i in $signals do echo -E ' '$i, done # Use -E because on some systems bash builtin interprets \n itself. echo -E ' }; static int intcmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int main(void) { int i, j, e; char buf[1024], *p; printf("\n\n// Error table\n"); printf("var errors = [...]string {\n"); qsort(errors, nelem(errors), sizeof errors[0], intcmp); for(i=0; i 0 && errors[i-1] == e) continue; strcpy(buf, strerror(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); printf("\n\n// Signal table\n"); printf("var signals = [...]string {\n"); qsort(signals, nelem(signals), sizeof signals[0], intcmp); for(i=0; i 0 && signals[i-1] == e) continue; strcpy(buf, strsignal(e)); // lowercase first letter: Bad -> bad, but STREAM -> STREAM. if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z) buf[0] += a - A; // cut trailing : number. p = strrchr(buf, ":"[0]); if(p) *p = '\0'; printf("\t%d: \"%s\",\n", e, buf); } printf("}\n\n"); return 0; } ' ) >_errors.c $CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out ================================================ FILE: vendor/golang.org/x/sys/unix/mksyscall.pl ================================================ #!/usr/bin/env perl # 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. # This program reads a file containing function prototypes # (like syscall_darwin.go) and generates system call bodies. # The prototypes are marked by lines beginning with "//sys" # and read like func declarations if //sys is replaced by func, but: # * The parameter lists must give a name for each argument. # This includes return parameters. # * The parameter lists must give a type for each argument: # the (x, y, z int) shorthand is not allowed. # * If the return parameter is an error number, it must be named errno. # A line beginning with //sysnb is like //sys, except that the # goroutine will not be suspended during the execution of the system # call. This must only be used for system calls which can never # block, as otherwise the system call could cause all goroutines to # hang. use strict; my $cmdline = "mksyscall.pl " . join(' ', @ARGV); my $errors = 0; my $_32bit = ""; my $plan9 = 0; my $openbsd = 0; my $netbsd = 0; my $dragonfly = 0; my $arm = 0; # 64-bit value should use (even, odd)-pair if($ARGV[0] eq "-b32") { $_32bit = "big-endian"; shift; } elsif($ARGV[0] eq "-l32") { $_32bit = "little-endian"; shift; } if($ARGV[0] eq "-plan9") { $plan9 = 1; shift; } if($ARGV[0] eq "-openbsd") { $openbsd = 1; shift; } if($ARGV[0] eq "-netbsd") { $netbsd = 1; shift; } if($ARGV[0] eq "-dragonfly") { $dragonfly = 1; shift; } if($ARGV[0] eq "-arm") { $arm = 1; shift; } if($ARGV[0] =~ /^-/) { print STDERR "usage: mksyscall.pl [-b32 | -l32] [file ...]\n"; exit 1; } if($ENV{'GOARCH'} eq "" || $ENV{'GOOS'} eq "") { print STDERR "GOARCH or GOOS not defined in environment\n"; exit 1; } sub parseparamlist($) { my ($list) = @_; $list =~ s/^\s*//; $list =~ s/\s*$//; if($list eq "") { return (); } return split(/\s*,\s*/, $list); } sub parseparam($) { my ($p) = @_; if($p !~ /^(\S*) (\S*)$/) { print STDERR "$ARGV:$.: malformed parameter: $p\n"; $errors = 1; return ("xx", "int"); } return ($1, $2); } my $text = ""; while(<>) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, errno error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($func, $in, $out, $sysname) = ($2, $3, $4, $5); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # Try in vain to keep people from editing this file. # The theory is that they jump into the middle of the file # without reading the header. $text .= "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"; # Go function header. my $out_decl = @out ? sprintf(" (%s)", join(', ', @out)) : ""; $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out_decl; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, $errvar = BytePtrFromString($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n *byte\n"; $text .= "\t_p$n, _ = BytePtrFromString($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass dummy pointer in that case. # Used to pass nil, but some OSes or simulators reject write(fd, nil, 0). $text .= "\tvar _p$n unsafe.Pointer\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = unsafe.Pointer(\&${name}[0])\n\t}"; $text .= " else {\n\t\t_p$n = unsafe.Pointer(&_zero)\n\t}"; $text .= "\n"; push @args, "uintptr(_p$n)", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && ($openbsd || $netbsd)) { push @args, "0"; if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $dragonfly) { if ($func !~ /^extp(read|write)/i) { push @args, "0"; } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } elsif($_32bit eq "little-endian") { push @args, "uintptr($name)", "uintptr($name>>32)"; } else { push @args, "uintptr($name)"; } } elsif($type eq "int64" && $_32bit ne "") { if(@args % 2 && $arm) { # arm abi specifies 64-bit argument uses # (even, odd) pair push @args, "0" } if($_32bit eq "big-endian") { push @args, "uintptr($name>>32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name>>32)"; } } else { push @args, "uintptr($name)"; } } # Determine which form to use; pad args with zeros. my $asm = "Syscall"; if ($nonblock) { $asm = "RawSyscall"; } if(@args <= 3) { while(@args < 3) { push @args, "0"; } } elsif(@args <= 6) { $asm .= "6"; while(@args < 6) { push @args, "0"; } } elsif(@args <= 9) { $asm .= "9"; while(@args < 9) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # System call number. if($sysname eq "") { $sysname = "SYS_$func"; $sysname =~ s/([a-z])([A-Z])/${1}_$2/g; # turn FooBar into Foo_Bar $sysname =~ y/a-z/A-Z/; } # Actual call. my $args = join(', ', @args); my $call = "$asm($sysname, $args)"; # Assign return values. my $body = ""; my @ret = ("_", "_", "_"); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err" && !$plan9) { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } elsif($name eq "err" && $plan9) { $ret[0] = "r0"; $ret[2] = "e1"; next; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1" || $plan9) { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($plan9 && $ret[2] eq "e1") { $text .= "\tif int32(r0) == -1 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } elsif ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = errnoErr(e1)\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n\n"; } chomp $text; chomp $text; if($errors) { exit 1; } print <) { chomp; s/\s+/ /g; s/^\s+//; s/\s+$//; $package = $1 if !$package && /^package (\S+)$/; my $nonblock = /^\/\/sysnb /; next if !/^\/\/sys / && !$nonblock; # Line must be of the form # func Open(path string, mode int, perm int) (fd int, err error) # Split into name, in params, out params. if(!/^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$/) { print STDERR "$ARGV:$.: malformed //sys declaration\n"; $errors = 1; next; } my ($nb, $func, $in, $out, $modname, $sysname) = ($1, $2, $3, $4, $5, $6); # Split argument lists on comma. my @in = parseparamlist($in); my @out = parseparamlist($out); # So file name. if($modname eq "") { $modname = "libc"; } # System call name. if($sysname eq "") { $sysname = "$func"; } # System call pointer variable name. my $sysvarname = "proc$sysname"; my $strconvfunc = "BytePtrFromString"; my $strconvtype = "*byte"; $sysname =~ y/A-Z/a-z/; # All libc functions are lowercase. # Runtime import of function to allow cross-platform builds. $dynimports .= "//go:cgo_import_dynamic libc_${sysname} ${sysname} \"$modname.so\"\n"; # Link symbol to proc address variable. $linknames .= "//go:linkname ${sysvarname} libc_${sysname}\n"; # Library proc address variable. push @vars, $sysvarname; # Go function header. $out = join(', ', @out); if($out ne "") { $out = " ($out)"; } if($text ne "") { $text .= "\n" } $text .= sprintf "func %s(%s)%s {\n", $func, join(', ', @in), $out; # Check if err return available my $errvar = ""; foreach my $p (@out) { my ($name, $type) = parseparam($p); if($type eq "error") { $errvar = $name; last; } } # Prepare arguments to Syscall. my @args = (); my @uses = (); my $n = 0; foreach my $p (@in) { my ($name, $type) = parseparam($p); if($type =~ /^\*/) { push @args, "uintptr(unsafe.Pointer($name))"; } elsif($type eq "string" && $errvar ne "") { $text .= "\tvar _p$n $strconvtype\n"; $text .= "\t_p$n, $errvar = $strconvfunc($name)\n"; $text .= "\tif $errvar != nil {\n\t\treturn\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type eq "string") { print STDERR "$ARGV:$.: $func uses string arguments, but has no error return\n"; $text .= "\tvar _p$n $strconvtype\n"; $text .= "\t_p$n, _ = $strconvfunc($name)\n"; push @args, "uintptr(unsafe.Pointer(_p$n))"; push @uses, "use(unsafe.Pointer(_p$n))"; $n++; } elsif($type =~ /^\[\](.*)/) { # Convert slice into pointer, length. # Have to be careful not to take address of &a[0] if len == 0: # pass nil in that case. $text .= "\tvar _p$n *$1\n"; $text .= "\tif len($name) > 0 {\n\t\t_p$n = \&$name\[0]\n\t}\n"; push @args, "uintptr(unsafe.Pointer(_p$n))", "uintptr(len($name))"; $n++; } elsif($type eq "int64" && $_32bit ne "") { if($_32bit eq "big-endian") { push @args, "uintptr($name >> 32)", "uintptr($name)"; } else { push @args, "uintptr($name)", "uintptr($name >> 32)"; } } elsif($type eq "bool") { $text .= "\tvar _p$n uint32\n"; $text .= "\tif $name {\n\t\t_p$n = 1\n\t} else {\n\t\t_p$n = 0\n\t}\n"; push @args, "uintptr(_p$n)"; $n++; } else { push @args, "uintptr($name)"; } } my $nargs = @args; # Determine which form to use; pad args with zeros. my $asm = "sysvicall6"; if ($nonblock) { $asm = "rawSysvicall6"; } if(@args <= 6) { while(@args < 6) { push @args, "0"; } } else { print STDERR "$ARGV:$.: too many arguments to system call\n"; } # Actual call. my $args = join(', ', @args); my $call = "$asm(uintptr(unsafe.Pointer(&$sysvarname)), $nargs, $args)"; # Assign return values. my $body = ""; my $failexpr = ""; my @ret = ("_", "_", "_"); my @pout= (); my $do_errno = 0; for(my $i=0; $i<@out; $i++) { my $p = $out[$i]; my ($name, $type) = parseparam($p); my $reg = ""; if($name eq "err") { $reg = "e1"; $ret[2] = $reg; $do_errno = 1; } else { $reg = sprintf("r%d", $i); $ret[$i] = $reg; } if($type eq "bool") { $reg = "$reg != 0"; } if($type eq "int64" && $_32bit ne "") { # 64-bit number in r1:r0 or r0:r1. if($i+2 > @out) { print STDERR "$ARGV:$.: not enough registers for int64 return\n"; } if($_32bit eq "big-endian") { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i, $i+1); } else { $reg = sprintf("int64(r%d)<<32 | int64(r%d)", $i+1, $i); } $ret[$i] = sprintf("r%d", $i); $ret[$i+1] = sprintf("r%d", $i+1); } if($reg ne "e1") { $body .= "\t$name = $type($reg)\n"; } } if ($ret[0] eq "_" && $ret[1] eq "_" && $ret[2] eq "_") { $text .= "\t$call\n"; } else { $text .= "\t$ret[0], $ret[1], $ret[2] := $call\n"; } foreach my $use (@uses) { $text .= "\t$use\n"; } $text .= $body; if ($do_errno) { $text .= "\tif e1 != 0 {\n"; $text .= "\t\terr = e1\n"; $text .= "\t}\n"; } $text .= "\treturn\n"; $text .= "}\n"; } if($errors) { exit 1; } print < "net.inet", "net.inet.ipproto" => "net.inet", "net.inet6.ipv6proto" => "net.inet6", "net.inet6.ipv6" => "net.inet6.ip6", "net.inet.icmpv6" => "net.inet6.icmp6", "net.inet6.divert6" => "net.inet6.divert", "net.inet6.tcp6" => "net.inet.tcp", "net.inet6.udp6" => "net.inet.udp", "mpls" => "net.mpls", "swpenc" => "vm.swapencrypt" ); # Node mappings my %node_map = ( "net.inet.ip.ifq" => "net.ifq", "net.inet.pfsync" => "net.pfsync", "net.mpls.ifq" => "net.ifq" ); my $ctlname; my %mib = (); my %sysctl = (); my $node; sub debug() { print STDERR "$_[0]\n" if $debug; } # Walk the MIB and build a sysctl name to OID mapping. sub build_sysctl() { my ($node, $name, $oid) = @_; my %node = %{$node}; my @oid = @{$oid}; foreach my $key (sort keys %node) { my @node = @{$node{$key}}; my $nodename = $name.($name ne '' ? '.' : '').$key; my @nodeoid = (@oid, $node[0]); if ($node[1] eq 'CTLTYPE_NODE') { if (exists $node_map{$nodename}) { $node = \%mib; $ctlname = $node_map{$nodename}; foreach my $part (split /\./, $ctlname) { $node = \%{@{$$node{$part}}[2]}; } } else { $node = $node[2]; } &build_sysctl($node, $nodename, \@nodeoid); } elsif ($node[1] ne '') { $sysctl{$nodename} = \@nodeoid; } } } foreach my $ctl (@ctls) { $ctls{$ctl} = $ctl; } # Build MIB foreach my $header (@headers) { &debug("Processing $header..."); open HEADER, "/usr/include/$header" || print STDERR "Failed to open $header\n"; while (

) { if ($_ =~ /^#define\s+(CTL_NAMES)\s+{/ || $_ =~ /^#define\s+(CTL_(.*)_NAMES)\s+{/ || $_ =~ /^#define\s+((.*)CTL_NAMES)\s+{/) { if ($1 eq 'CTL_NAMES') { # Top level. $node = \%mib; } else { # Node. my $nodename = lc($2); if ($header =~ /^netinet\//) { $ctlname = "net.inet.$nodename"; } elsif ($header =~ /^netinet6\//) { $ctlname = "net.inet6.$nodename"; } elsif ($header =~ /^net\//) { $ctlname = "net.$nodename"; } else { $ctlname = "$nodename"; $ctlname =~ s/^(fs|net|kern)_/$1\./; } if (exists $ctl_map{$ctlname}) { $ctlname = $ctl_map{$ctlname}; } if (not exists $ctls{$ctlname}) { &debug("Ignoring $ctlname..."); next; } # Walk down from the top of the MIB. $node = \%mib; foreach my $part (split /\./, $ctlname) { if (not exists $$node{$part}) { &debug("Missing node $part"); $$node{$part} = [ 0, '', {} ]; } $node = \%{@{$$node{$part}}[2]}; } } # Populate current node with entries. my $i = -1; while (defined($_) && $_ !~ /^}/) { $_ =
; $i++ if $_ =~ /{.*}/; next if $_ !~ /{\s+"(\w+)",\s+(CTLTYPE_[A-Z]+)\s+}/; $$node{$1} = [ $i, $2, {} ]; } } } close HEADER; } &build_sysctl(\%mib, "", []); print <){ if(/^#define\s+SYS_(\w+)\s+([0-9]+)/){ my $name = $1; my $num = $2; $name =~ y/a-z/A-Z/; print " SYS_$name = $num;" } } print <){ if(/^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$/){ my $num = $1; my $proto = $2; my $name = "SYS_$3"; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print <){ if(/^([0-9]+)\s+\S+\s+STD\s+({ \S+\s+(\w+).*)$/){ my $num = $1; my $proto = $2; my $name = "SYS_$3"; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } if($name =~ /^SYS_CAP_+/ || $name =~ /^SYS___CAP_+/){ next } print " $name = $num; // $proto\n"; # We keep Capsicum syscall numbers for FreeBSD # 9-STABLE here because we are not sure whether they # are mature and stable. if($num == 513){ print " SYS_CAP_NEW = 514 // { int cap_new(int fd, uint64_t rights); }\n"; print " SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \\\n"; print " SYS_CAP_ENTER = 516 // { int cap_enter(void); }\n"; print " SYS_CAP_GETMODE = 517 // { int cap_getmode(u_int *modep); }\n"; } } } print < 999){ # ignore deprecated syscalls that are no longer implemented # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/include/uapi/asm-generic/unistd.h?id=refs/heads/master#n716 return; } $name =~ y/a-z/A-Z/; print " SYS_$name = $num;\n"; } my $prev; open(GCC, "gcc -E -dD $ARGV[0] |") || die "can't run gcc"; while(){ if(/^#define __NR_syscalls\s+/) { # ignore redefinitions of __NR_syscalls } elsif(/^#define __NR_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR3264_(\w+)\s+([0-9]+)/){ $prev = $2; fmt($1, $2); } elsif(/^#define __NR_(\w+)\s+\(\w+\+\s*([0-9]+)\)/){ fmt($1, $prev+$2) } } print <){ if($line =~ /^(.*)\\$/) { # Handle continuation $line = $1; $_ =~ s/^\s+//; $line .= $_; } else { # New line $line = $_; } next if $line =~ /\\$/; if($line =~ /^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$/) { my $num = $1; my $proto = $6; my $compat = $8; my $name = "$7_$9"; $name = "$7_$11" if $11 ne ''; $name =~ y/a-z/A-Z/; if($compat eq '' || $compat eq '30' || $compat eq '50') { print " $name = $num; // $proto\n"; } } } print <){ if(/^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$/){ my $num = $1; my $proto = $3; my $name = $4; $name =~ y/a-z/A-Z/; # There are multiple entries for enosys and nosys, so comment them out. if($name =~ /^SYS_E?NOSYS$/){ $name = "// $name"; } if($name eq 'SYS_SYS_EXIT'){ $name = 'SYS_EXIT'; } print " $name = $num; // $proto\n"; } } print < 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/str.go ================================================ // 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:]) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall.go ================================================ // 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" import "unsafe" // 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 } // 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) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_bsd.go ================================================ // 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) { mib, err := sysctlmib(name, args...) if err != nil { return "", err } // Find size. n := uintptr(0) if err := sysctl(mib, nil, &n, nil, 0); err != nil { return "", err } if n == 0 { return "", nil } // Read into buffer of that size. buf := make([]byte, n) if err := sysctl(mib, &buf[0], &n, nil, 0); err != nil { return "", err } // 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 { return utimes(path, nil) } // TODO: The BSDs can do utimensat with SYS_UTIMENSAT but it // isn't supported by darwin so this uses utimes instead if len(ts) != 2 { return EINVAL } // 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]))) } //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) // Madvise(addr *byte, len int, behav int) (err error) // Mprotect(addr *byte, len int, prot int) (err error) // Msync(addr *byte, len int, flags int) (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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_bsd_test.go ================================================ // 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 openbsd package unix_test import ( "testing" "golang.org/x/sys/unix" ) const MNT_WAIT = 1 func TestGetfsstat(t *testing.T) { n, err := unix.Getfsstat(nil, MNT_WAIT) if err != nil { t.Fatal(err) } data := make([]unix.Statfs_t, n) n, err = unix.Getfsstat(data, MNT_WAIT) if err != nil { t.Fatal(err) } empty := unix.Statfs_t{} for _, stat := range data { if stat == empty { t.Fatal("an empty Statfs_t struct was returned") } } } func TestSysctlRaw(t *testing.T) { _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid()) if err != nil { t.Fatal(err) } } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_darwin.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 } /* * 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) } /* * 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 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_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 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 Mkfifo(path string, mode uint32) (err error) //sys Mknod(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 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) //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 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 /* * 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 // Mmap // Mlock // Munlock // 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 // Mlockall // Munlockall // __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 // Msync_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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_darwin_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_darwin_amd64.go ================================================ // 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" ) //sys Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_darwin_arm.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_darwin_arm64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_dragonfly.go ================================================ // 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 [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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) reclen := int(16+dirent.Namlen+1+7) & ^7 buf = buf[reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 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 /* * 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 // Mmap // 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 // Msync_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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_dragonfly_386.go ================================================ // 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,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 = int32(nsec / 1e9) ts.Nsec = int32(nsec % 1e9) return } func TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_dragonfly_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_freebsd.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 } /* * 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 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 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 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 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 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) /* * 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 // Mmap // Mlock // Munlock // 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 // Mlockall // Munlockall // __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 // Msync_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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_freebsd_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_freebsd_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_freebsd_arm.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return tv.Sec*1e9 + int64(tv.Usec)*1e3 } 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) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_freebsd_test.go ================================================ // 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 freebsd package unix_test import ( "testing" "golang.org/x/sys/unix" ) func TestSysctUint64(t *testing.T) { _, err := unix.SysctlUint64("vm.max_kernel_address") if err != nil { t.Fatal(err) } } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_linux.go ================================================ // 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 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 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) func Unlinkat(dirfd int, path string) error { return unlinkat(dirfd, path, 0) } //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(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].Sec = ts[i].Sec tv[i].Usec = ts[i].Nsec / 1000 } 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) (err error) { return Mknod(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 } 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 } 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 SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error) { return setsockopt(fd, level, opt, unsafe.Pointer(mreq), unsafe.Sizeof(*mreq)) } 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 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 clen(n []byte) int { for i := 0; i < len(n); i++ { if n[i] == 0 { return i } } return len(n) } func ReadDirent(fd int, buf []byte) (n int, err error) { return Getdents(fd, buf) } 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 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) //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 Fchmodat(dirfd int, path string, mode uint32, flags int) (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) //sysnb Getrusage(who int, rusage *Rusage) (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 Listxattr(path string, dest []byte) (sz 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 Pause() (err error) //sys PivotRoot(newroot string, putold string) (err error) = SYS_PIVOT_ROOT //sysnb prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) = SYS_PRLIMIT64 //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 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) // 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() //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 Utime(path string, buf *Utimbuf) (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 Munlock(b []byte) (err error) //sys Mlockall(flags int) (err error) //sys Munlockall() (err error) /* * Unimplemented */ // AddKey // AfsSyscall // Alarm // ArchPrctl // Brk // Capget // Capset // ClockGetres // ClockNanosleep // ClockSettime // Clone // CreateModule // DeleteModule // EpollCtlOld // EpollPwait // EpollWaitOld // Eventfd // Execve // Fgetxattr // Flistxattr // Fork // Fremovexattr // Fsetxattr // Futex // GetKernelSyms // GetMempolicy // GetRobustList // GetThreadArea // Getitimer // Getpmsg // IoCancel // IoDestroy // IoGetevents // IoSetup // IoSubmit // Ioctl // IoprioGet // IoprioSet // KexecLoad // Keyctl // Lgetxattr // Llistxattr // LookupDcookie // Lremovexattr // Lsetxattr // Mbind // MigratePages // Mincore // ModifyLdt // Mount // MovePages // Mprotect // MqGetsetattr // MqNotify // MqOpen // MqTimedreceive // MqTimedsend // MqUnlink // Mremap // Msgctl // Msgget // Msgrcv // Msgsnd // Msync // Newfstatat // Nfsservctl // Personality // Poll // Ppoll // Pselect6 // Ptrace // Putpmsg // QueryModule // Quotactl // Readahead // Readv // RemapFilePages // RequestKey // 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 // Vmsplice // Vserver // Waitid // _Sysctl ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_linux_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) 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) // 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_linux_amd64.go ================================================ // 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 import "syscall" //sys Dup2(oldfd int, newfd 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 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) //go:noescape func gettimeofday(tv *Timeval) (err syscall.Errno) 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 } 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_linux_arm.go ================================================ // 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) //sysnb Time(t *Time_t) (tt Time_t, 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 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_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) } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_linux_arm64.go ================================================ // 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 const _SYS_dup = SYS_DUP3 //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) //sysnb Time(t *Time_t) (tt Time_t, 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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 (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) } // 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_linux_ppc64x.go ================================================ // 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 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) //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 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) 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_netbsd.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 /* * 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 ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_netbsd_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_netbsd_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_netbsd_arm.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_no_getwd.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_openbsd.go ================================================ // 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 } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Fileno == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:dirent.Namlen]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } //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 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 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 /* * 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 // utimensat // vfork // writev ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_openbsd_386.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_openbsd_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_solaris.go ================================================ // 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) } // ParseDirent parses up to max directory entries in buf, // appending the names to names. It returns the number // 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) for max != 0 && len(buf) > 0 { dirent := (*Dirent)(unsafe.Pointer(&buf[0])) if dirent.Reclen == 0 { buf = nil break } buf = buf[dirent.Reclen:] if dirent.Ino == 0 { // File absent in directory. continue } bytes := (*[10000]byte)(unsafe.Pointer(&dirent.Name[0])) var name = string(bytes[0:clen(bytes[:])]) if name == "." || name == ".." { // Useless names continue } max-- count++ names = append(names, name) } return origlen - len(buf), count, names } func pipe() (r uintptr, w uintptr, err uintptr) func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } r0, w0, e1 := pipe() if e1 != 0 { err = syscall.Errno(e1) } p[0], p[1] = int(r0), int(w0) return } 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 } func wait4(pid uintptr, wstatus *WaitStatus, options uintptr, rusage *Rusage) (wpid uintptr, err uintptr) func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error) { r0, e1 := wait4(uintptr(pid), wstatus, uintptr(options), rusage) if e1 != 0 { err = syscall.Errno(e1) } return int(r0), err } func gethostname() (name string, err uintptr) func Gethostname() (name string, err error) { name, e1 := gethostname() if e1 != 0 { err = syscall.Errno(e1) } return name, err } //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.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.Accrights = (*int8)(unsafe.Pointer(&oob[0])) } 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.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.Accrights = (*int8)(unsafe.Pointer(&oob[0])) } 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 int, arg uintptr) (err error) func IoctlSetInt(fd int, req int, value int) (err error) { return ioctl(fd, req, uintptr(value)) } func IoctlSetWinsize(fd int, req int, value *Winsize) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermios(fd int, req int, value *Termios) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlSetTermio(fd int, req int, value *Termio) (err error) { return ioctl(fd, req, uintptr(unsafe.Pointer(value))) } func IoctlGetInt(fd int, req int) (int, error) { var value int err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return value, err } func IoctlGetWinsize(fd int, req int) (*Winsize, error) { var value Winsize err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermios(fd int, req int) (*Termios, error) { var value Termios err := ioctl(fd, req, uintptr(unsafe.Pointer(&value))) return &value, err } func IoctlGetTermio(fd int, req int) (*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 Fpathconf(fd int, name int) (val int, err error) //sys Fstat(fd int, stat *Stat_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.listen //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 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) (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.bind //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) = libsocket.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.sendto //sys socket(domain int, typ int, proto int) (fd int, err error) = libsocket.socket //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) = libsocket.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.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) } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_solaris_amd64.go ================================================ // 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 TimevalToNsec(tv Timeval) int64 { return int64(tv.Sec)*1e9 + int64(tv.Usec)*1e3 } 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") } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_test.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "fmt" "testing" "golang.org/x/sys/unix" ) func testSetGetenv(t *testing.T, key, value string) { err := unix.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := unix.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } func TestItoa(t *testing.T) { // Make most negative integer: 0x8000... i := 1 for i<<1 != 0 { i <<= 1 } if i >= 0 { t.Fatal("bad math") } s := unix.Itoa(i) f := fmt.Sprint(i) if s != f { t.Fatalf("itoa(%d) = %s, want %s", i, s, f) } } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_unix.go ================================================ // 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 ) // 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 } func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err syscall.Errno) func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err syscall.Errno) // Mmap manager, for use by operating system-specific implementations. type mmapper struct { 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/syscall_unix_test.go ================================================ // 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 dragonfly freebsd linux netbsd openbsd solaris package unix_test import ( "flag" "fmt" "io/ioutil" "net" "os" "os/exec" "path/filepath" "runtime" "testing" "time" "golang.org/x/sys/unix" ) // Tests that below functions, structures and constants are consistent // on all Unix-like systems. func _() { // program scheduling priority functions and constants var ( _ func(int, int, int) error = unix.Setpriority _ func(int, int) (int, error) = unix.Getpriority ) const ( _ int = unix.PRIO_USER _ int = unix.PRIO_PROCESS _ int = unix.PRIO_PGRP ) // termios constants const ( _ int = unix.TCIFLUSH _ int = unix.TCIOFLUSH _ int = unix.TCOFLUSH ) // fcntl file locking structure and constants var ( _ = unix.Flock_t{ Type: int16(0), Whence: int16(0), Start: int64(0), Len: int64(0), Pid: int32(0), } ) const ( _ = unix.F_GETLK _ = unix.F_SETLK _ = unix.F_SETLKW ) } // TestFcntlFlock tests whether the file locking structure matches // the calling convention of each kernel. func TestFcntlFlock(t *testing.T) { name := filepath.Join(os.TempDir(), "TestFcntlFlock") fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0) if err != nil { t.Fatalf("Open failed: %v", err) } defer unix.Unlink(name) defer unix.Close(fd) flock := unix.Flock_t{ Type: unix.F_RDLCK, Start: 0, Len: 0, Whence: 1, } if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil { t.Fatalf("FcntlFlock failed: %v", err) } } // TestPassFD tests passing a file descriptor over a Unix socket. // // This test involved both a parent and child process. The parent // process is invoked as a normal test, with "go test", which then // runs the child process by running the current test binary with args // "-test.run=^TestPassFD$" and an environment variable used to signal // that the test should become the child process instead. func TestPassFD(t *testing.T) { switch runtime.GOOS { case "dragonfly": // TODO(jsing): Figure out why sendmsg is returning EINVAL. t.Skip("skipping test on dragonfly") case "solaris": // TODO(aram): Figure out why ReadMsgUnix is returning empty message. t.Skip("skipping test on solaris, see issue 7402") } if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" { passFDChild() return } tempDir, err := ioutil.TempDir("", "TestPassFD") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0) if err != nil { t.Fatalf("Socketpair: %v", err) } defer unix.Close(fds[0]) defer unix.Close(fds[1]) writeFile := os.NewFile(uintptr(fds[0]), "child-writes") readFile := os.NewFile(uintptr(fds[1]), "parent-reads") defer writeFile.Close() defer readFile.Close() cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir) cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" { cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp) } cmd.ExtraFiles = []*os.File{writeFile} out, err := cmd.CombinedOutput() if len(out) > 0 || err != nil { t.Fatalf("child process: %q, %v", out, err) } c, err := net.FileConn(readFile) if err != nil { t.Fatalf("FileConn: %v", err) } defer c.Close() uc, ok := c.(*net.UnixConn) if !ok { t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c) } buf := make([]byte, 32) // expect 1 byte oob := make([]byte, 32) // expect 24 bytes closeUnix := time.AfterFunc(5*time.Second, func() { t.Logf("timeout reading from unix socket") uc.Close() }) _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob) closeUnix.Stop() scms, err := unix.ParseSocketControlMessage(oob[:oobn]) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != 1 { t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms) } scm := scms[0] gotFds, err := unix.ParseUnixRights(&scm) if err != nil { t.Fatalf("unix.ParseUnixRights: %v", err) } if len(gotFds) != 1 { t.Fatalf("wanted 1 fd; got %#v", gotFds) } f := os.NewFile(uintptr(gotFds[0]), "fd-from-child") defer f.Close() got, err := ioutil.ReadAll(f) want := "Hello from child process!\n" if string(got) != want { t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want) } } // passFDChild is the child process used by TestPassFD. func passFDChild() { defer os.Exit(0) // Look for our fd. It should be fd 3, but we work around an fd leak // bug here (http://golang.org/issue/2603) to let it be elsewhere. var uc *net.UnixConn for fd := uintptr(3); fd <= 10; fd++ { f := os.NewFile(fd, "unix-conn") var ok bool netc, _ := net.FileConn(f) uc, ok = netc.(*net.UnixConn) if ok { break } } if uc == nil { fmt.Println("failed to find unix fd") return } // Make a file f to send to our parent process on uc. // We make it in tempDir, which our parent will clean up. flag.Parse() tempDir := flag.Arg(0) f, err := ioutil.TempFile(tempDir, "") if err != nil { fmt.Printf("TempFile: %v", err) return } f.Write([]byte("Hello from child process!\n")) f.Seek(0, 0) rights := unix.UnixRights(int(f.Fd())) dummyByte := []byte("x") n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil) if err != nil { fmt.Printf("WriteMsgUnix: %v", err) return } if n != 1 || oobn != len(rights) { fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights)) return } } // TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage, // and ParseUnixRights are able to successfully round-trip lists of file descriptors. func TestUnixRightsRoundtrip(t *testing.T) { testCases := [...][][]int{ {{42}}, {{1, 2}}, {{3, 4, 5}}, {{}}, {{1, 2}, {3, 4, 5}, {}, {7}}, } for _, testCase := range testCases { b := []byte{} var n int for _, fds := range testCase { // Last assignment to n wins n = len(b) + unix.CmsgLen(4*len(fds)) b = append(b, unix.UnixRights(fds...)...) } // Truncate b b = b[:n] scms, err := unix.ParseSocketControlMessage(b) if err != nil { t.Fatalf("ParseSocketControlMessage: %v", err) } if len(scms) != len(testCase) { t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms) } for i, scm := range scms { gotFds, err := unix.ParseUnixRights(&scm) if err != nil { t.Fatalf("ParseUnixRights: %v", err) } wantFds := testCase[i] if len(gotFds) != len(wantFds) { t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds) } for j, fd := range gotFds { if fd != wantFds[j] { t.Fatalf("expected fd %v, got %v", wantFds[j], fd) } } } } } func TestRlimit(t *testing.T) { var rlimit, zero unix.Rlimit err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Getrlimit: save failed: %v", err) } if zero == rlimit { t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit) } set := rlimit set.Cur = set.Max - 1 err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set) if err != nil { t.Fatalf("Setrlimit: set failed: %#v %v", set, err) } var get unix.Rlimit err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get) if err != nil { t.Fatalf("Getrlimit: get failed: %v", err) } set = rlimit set.Cur = set.Max - 1 if set != get { // Seems like Darwin requires some privilege to // increase the soft limit of rlimit sandbox, though // Setrlimit never reports an error. switch runtime.GOOS { case "darwin": default: t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get) } } err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit) if err != nil { t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err) } } func TestSeekFailure(t *testing.T) { _, err := unix.Seek(-1, 0, 0) if err == nil { t.Fatalf("Seek(-1, 0, 0) did not fail") } str := err.Error() // used to crash on Linux t.Logf("Seek: %v", str) if str == "" { t.Fatalf("Seek(-1, 0, 0) return error with empty message") } } ================================================ FILE: vendor/golang.org/x/sys/unix/types_darwin.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define __DARWIN_UNIX03 0 #define KERNEL #define _DARWIN_USE_64_BIT_INODE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat64 type Statfs_t C.struct_statfs64 type Flock_t C.struct_flock type Fstore_t C.struct_fstore type Radvisory_t C.struct_radvisory type Fbootstraptransfer_t C.struct_fbootstraptransfer type Log2phys_t C.struct_log2phys type Fsid C.struct_fsid type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2 SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfmaMsghdr2 C.struct_ifma_msghdr2 type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios // fchmodat-like syscalls. const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) ================================================ FILE: vendor/golang.org/x/sys/unix/types_dragonfly.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.struct_fsid // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr // Terminal handling type Termios C.struct_termios ================================================ FILE: vendor/golang.org/x/sys/unix/types_freebsd.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; // This structure is a duplicate of stat on FreeBSD 8-STABLE. // See /usr/include/sys/stat.h. struct stat8 { #undef st_atimespec st_atim #undef st_mtimespec st_mtim #undef st_ctimespec st_ctim #undef st_birthtimespec st_birthtim __dev_t st_dev; ino_t st_ino; mode_t st_mode; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; __dev_t st_rdev; #if __BSD_VISIBLE struct timespec st_atimespec; struct timespec st_mtimespec; struct timespec st_ctimespec; #else time_t st_atime; long __st_atimensec; time_t st_mtime; long __st_mtimensec; time_t st_ctime; long __st_ctimensec; #endif off_t st_size; blkcnt_t st_blocks; blksize_t st_blksize; fflags_t st_flags; __uint32_t st_gen; __int32_t st_lspare; #if __BSD_VISIBLE struct timespec st_birthtimespec; unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); unsigned int :(8 / 2) * (16 - (int)sizeof(struct timespec)); #else time_t st_birthtime; long st_birthtimensec; unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); unsigned int :(8 / 2) * (16 - (int)sizeof(struct __timespec)); #endif }; // This structure is a duplicate of if_data on FreeBSD 8-STABLE. // See /usr/include/net/if.h. struct if_data8 { u_char ifi_type; u_char ifi_physical; u_char ifi_addrlen; u_char ifi_hdrlen; u_char ifi_link_state; u_char ifi_spare_char1; u_char ifi_spare_char2; u_char ifi_datalen; u_long ifi_mtu; u_long ifi_metric; u_long ifi_baudrate; u_long ifi_ipackets; u_long ifi_ierrors; u_long ifi_opackets; u_long ifi_oerrors; u_long ifi_collisions; u_long ifi_ibytes; u_long ifi_obytes; u_long ifi_imcasts; u_long ifi_omcasts; u_long ifi_iqdrops; u_long ifi_noproto; u_long ifi_hwassist; time_t ifi_epoch; struct timeval ifi_lastchange; }; // This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE. // See /usr/include/net/if.h. struct if_msghdr8 { u_short ifm_msglen; u_char ifm_version; u_char ifm_type; int ifm_addrs; int ifm_flags; u_short ifm_index; struct if_data8 ifm_data; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat8 type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.struct_fsid // Advice to Fadvise const ( FADV_NORMAL = C.POSIX_FADV_NORMAL FADV_RANDOM = C.POSIX_FADV_RANDOM FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL FADV_WILLNEED = C.POSIX_FADV_WILLNEED FADV_DONTNEED = C.POSIX_FADV_DONTNEED FADV_NOREUSE = C.POSIX_FADV_NOREUSE ) // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPMreqn C.struct_ip_mreqn type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( sizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfMsghdr = C.sizeof_struct_if_msghdr8 sizeofIfData = C.sizeof_struct_if_data SizeofIfData = C.sizeof_struct_if_data8 SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type ifMsghdr C.struct_if_msghdr type IfMsghdr C.struct_if_msghdr8 type ifData C.struct_if_data type IfData C.struct_if_data8 type IfaMsghdr C.struct_ifa_msghdr type IfmaMsghdr C.struct_ifma_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfZbuf C.struct_bpf_zbuf type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfZbufHeader C.struct_bpf_zbuf_header // Terminal handling type Termios C.struct_termios ================================================ FILE: vendor/golang.org/x/sys/unix/types_linux.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define _LARGEFILE_SOURCE #define _LARGEFILE64_SOURCE #define _FILE_OFFSET_BITS 64 #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef TCSETS2 // On systems that have "struct termios2" use this as type Termios. typedef struct termios2 termios_t; #else typedef struct termios termios_t; #endif enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_ll s5; struct sockaddr_nl s6; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; // copied from /usr/include/linux/un.h struct my_sockaddr_un { sa_family_t sun_family; #if defined(__ARM_EABI__) || defined(__powerpc64__) // on ARM char is by default unsigned signed char sun_path[108]; #else char sun_path[108]; #endif }; #ifdef __ARM_EABI__ typedef struct user_regs PtraceRegs; #elif defined(__aarch64__) typedef struct user_pt_regs PtraceRegs; #elif defined(__powerpc64__) typedef struct pt_regs PtraceRegs; #else typedef struct user_regs_struct PtraceRegs; #endif // The real epoll_event is a union, and godefs doesn't handle it well. struct my_epoll_event { uint32_t events; #ifdef __ARM_EABI__ // padding is not specified in linux/eventpoll.h but added to conform to the // alignment requirements of EABI int32_t padFd; #endif int32_t fd; int32_t pad; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timex C.struct_timex type Time_t C.time_t type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Dirent C.struct_dirent type Fsid C.fsid_t type Flock_t C.struct_flock // Advice to Fadvise const ( FADV_NORMAL = C.POSIX_FADV_NORMAL FADV_RANDOM = C.POSIX_FADV_RANDOM FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL FADV_WILLNEED = C.POSIX_FADV_WILLNEED FADV_DONTNEED = C.POSIX_FADV_DONTNEED FADV_NOREUSE = C.POSIX_FADV_NOREUSE ) // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_my_sockaddr_un type RawSockaddrLinklayer C.struct_sockaddr_ll type RawSockaddrNetlink C.struct_sockaddr_nl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPMreqn C.struct_ip_mreqn type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet4Pktinfo C.struct_in_pktinfo type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter type Ucred C.struct_ucred type TCPInfo C.struct_tcp_info const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrLinklayer = C.sizeof_struct_sockaddr_ll SizeofSockaddrNetlink = C.sizeof_struct_sockaddr_nl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPMreqn = C.sizeof_struct_ip_mreqn SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter SizeofUcred = C.sizeof_struct_ucred SizeofTCPInfo = C.sizeof_struct_tcp_info ) // Netlink routing and interface messages const ( IFA_UNSPEC = C.IFA_UNSPEC IFA_ADDRESS = C.IFA_ADDRESS IFA_LOCAL = C.IFA_LOCAL IFA_LABEL = C.IFA_LABEL IFA_BROADCAST = C.IFA_BROADCAST IFA_ANYCAST = C.IFA_ANYCAST IFA_CACHEINFO = C.IFA_CACHEINFO IFA_MULTICAST = C.IFA_MULTICAST IFLA_UNSPEC = C.IFLA_UNSPEC IFLA_ADDRESS = C.IFLA_ADDRESS IFLA_BROADCAST = C.IFLA_BROADCAST IFLA_IFNAME = C.IFLA_IFNAME IFLA_MTU = C.IFLA_MTU IFLA_LINK = C.IFLA_LINK IFLA_QDISC = C.IFLA_QDISC IFLA_STATS = C.IFLA_STATS IFLA_COST = C.IFLA_COST IFLA_PRIORITY = C.IFLA_PRIORITY IFLA_MASTER = C.IFLA_MASTER IFLA_WIRELESS = C.IFLA_WIRELESS IFLA_PROTINFO = C.IFLA_PROTINFO IFLA_TXQLEN = C.IFLA_TXQLEN IFLA_MAP = C.IFLA_MAP IFLA_WEIGHT = C.IFLA_WEIGHT IFLA_OPERSTATE = C.IFLA_OPERSTATE IFLA_LINKMODE = C.IFLA_LINKMODE IFLA_LINKINFO = C.IFLA_LINKINFO IFLA_NET_NS_PID = C.IFLA_NET_NS_PID IFLA_IFALIAS = C.IFLA_IFALIAS IFLA_MAX = C.IFLA_MAX RT_SCOPE_UNIVERSE = C.RT_SCOPE_UNIVERSE RT_SCOPE_SITE = C.RT_SCOPE_SITE RT_SCOPE_LINK = C.RT_SCOPE_LINK RT_SCOPE_HOST = C.RT_SCOPE_HOST RT_SCOPE_NOWHERE = C.RT_SCOPE_NOWHERE RT_TABLE_UNSPEC = C.RT_TABLE_UNSPEC RT_TABLE_COMPAT = C.RT_TABLE_COMPAT RT_TABLE_DEFAULT = C.RT_TABLE_DEFAULT RT_TABLE_MAIN = C.RT_TABLE_MAIN RT_TABLE_LOCAL = C.RT_TABLE_LOCAL RT_TABLE_MAX = C.RT_TABLE_MAX RTA_UNSPEC = C.RTA_UNSPEC RTA_DST = C.RTA_DST RTA_SRC = C.RTA_SRC RTA_IIF = C.RTA_IIF RTA_OIF = C.RTA_OIF RTA_GATEWAY = C.RTA_GATEWAY RTA_PRIORITY = C.RTA_PRIORITY RTA_PREFSRC = C.RTA_PREFSRC RTA_METRICS = C.RTA_METRICS RTA_MULTIPATH = C.RTA_MULTIPATH RTA_FLOW = C.RTA_FLOW RTA_CACHEINFO = C.RTA_CACHEINFO RTA_TABLE = C.RTA_TABLE RTN_UNSPEC = C.RTN_UNSPEC RTN_UNICAST = C.RTN_UNICAST RTN_LOCAL = C.RTN_LOCAL RTN_BROADCAST = C.RTN_BROADCAST RTN_ANYCAST = C.RTN_ANYCAST RTN_MULTICAST = C.RTN_MULTICAST RTN_BLACKHOLE = C.RTN_BLACKHOLE RTN_UNREACHABLE = C.RTN_UNREACHABLE RTN_PROHIBIT = C.RTN_PROHIBIT RTN_THROW = C.RTN_THROW RTN_NAT = C.RTN_NAT RTN_XRESOLVE = C.RTN_XRESOLVE RTNLGRP_NONE = C.RTNLGRP_NONE RTNLGRP_LINK = C.RTNLGRP_LINK RTNLGRP_NOTIFY = C.RTNLGRP_NOTIFY RTNLGRP_NEIGH = C.RTNLGRP_NEIGH RTNLGRP_TC = C.RTNLGRP_TC RTNLGRP_IPV4_IFADDR = C.RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_MROUTE = C.RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_ROUTE = C.RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_RULE = C.RTNLGRP_IPV4_RULE RTNLGRP_IPV6_IFADDR = C.RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_MROUTE = C.RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_ROUTE = C.RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_IFINFO = C.RTNLGRP_IPV6_IFINFO RTNLGRP_IPV6_PREFIX = C.RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_RULE = C.RTNLGRP_IPV6_RULE RTNLGRP_ND_USEROPT = C.RTNLGRP_ND_USEROPT SizeofNlMsghdr = C.sizeof_struct_nlmsghdr SizeofNlMsgerr = C.sizeof_struct_nlmsgerr SizeofRtGenmsg = C.sizeof_struct_rtgenmsg SizeofNlAttr = C.sizeof_struct_nlattr SizeofRtAttr = C.sizeof_struct_rtattr SizeofIfInfomsg = C.sizeof_struct_ifinfomsg SizeofIfAddrmsg = C.sizeof_struct_ifaddrmsg SizeofRtMsg = C.sizeof_struct_rtmsg SizeofRtNexthop = C.sizeof_struct_rtnexthop ) type NlMsghdr C.struct_nlmsghdr type NlMsgerr C.struct_nlmsgerr type RtGenmsg C.struct_rtgenmsg type NlAttr C.struct_nlattr type RtAttr C.struct_rtattr type IfInfomsg C.struct_ifinfomsg type IfAddrmsg C.struct_ifaddrmsg type RtMsg C.struct_rtmsg type RtNexthop C.struct_rtnexthop // Linux socket filter const ( SizeofSockFilter = C.sizeof_struct_sock_filter SizeofSockFprog = C.sizeof_struct_sock_fprog ) type SockFilter C.struct_sock_filter type SockFprog C.struct_sock_fprog // Inotify type InotifyEvent C.struct_inotify_event const SizeofInotifyEvent = C.sizeof_struct_inotify_event // Ptrace // Register structures type PtraceRegs C.PtraceRegs // Misc type FdSet C.fd_set type Sysinfo_t C.struct_sysinfo type Utsname C.struct_utsname type Ustat_t C.struct_ustat type EpollEvent C.struct_my_epoll_event const ( AT_FDCWD = C.AT_FDCWD AT_REMOVEDIR = C.AT_REMOVEDIR AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW ) // Terminal handling type Termios C.termios_t ================================================ FILE: vendor/golang.org/x/sys/unix/types_netbsd.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.fsid_t // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics type Mclpool C.struct_mclpool // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfTimeval C.struct_bpf_timeval // Terminal handling type Termios C.struct_termios // Sysctl type Sysctlnode C.struct_sysctlnode ================================================ FILE: vendor/golang.org/x/sys/unix/types_openbsd.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Statfs_t C.struct_statfs type Flock_t C.struct_flock type Dirent C.struct_dirent type Fsid C.fsid_t // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Ptrace requests const ( PTRACE_TRACEME = C.PT_TRACE_ME PTRACE_CONT = C.PT_CONTINUE PTRACE_KILL = C.PT_KILL ) // Events (kqueue, kevent) type Kevent_t C.struct_kevent // Select type FdSet C.fd_set // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type IfAnnounceMsghdr C.struct_if_announcemsghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics type Mclpool C.struct_mclpool // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfHdr C.struct_bpf_hdr type BpfTimeval C.struct_bpf_timeval // Terminal handling type Termios C.struct_termios ================================================ FILE: vendor/golang.org/x/sys/unix/types_solaris.go ================================================ // 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 ignore /* Input to cgo -godefs. See also mkerrors.sh and mkall.sh */ // +godefs map struct_in_addr [4]byte /* in_addr */ // +godefs map struct_in6_addr [16]byte /* in6_addr */ package unix /* #define KERNEL // These defines ensure that builds done on newer versions of Solaris are // backwards-compatible with older versions of Solaris and // OpenSolaris-based derivatives. #define __USE_SUNOS_SOCKETS__ // msghdr #define __USE_LEGACY_PROTOTYPES__ // iovec #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include enum { sizeofPtr = sizeof(void*), }; union sockaddr_all { struct sockaddr s1; // this one gets used for fields struct sockaddr_in s2; // these pad it out struct sockaddr_in6 s3; struct sockaddr_un s4; struct sockaddr_dl s5; }; struct sockaddr_any { struct sockaddr addr; char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)]; }; */ import "C" // Machine characteristics; for internal use. const ( sizeofPtr = C.sizeofPtr sizeofShort = C.sizeof_short sizeofInt = C.sizeof_int sizeofLong = C.sizeof_long sizeofLongLong = C.sizeof_longlong PathMax = C.PATH_MAX ) // Basic types type ( _C_short C.short _C_int C.int _C_long C.long _C_long_long C.longlong ) // Time type Timespec C.struct_timespec type Timeval C.struct_timeval type Timeval32 C.struct_timeval32 type Tms C.struct_tms type Utimbuf C.struct_utimbuf // Processes type Rusage C.struct_rusage type Rlimit C.struct_rlimit type _Gid_t C.gid_t // Files const ( // Directory mode bits S_IFMT = C.S_IFMT S_IFIFO = C.S_IFIFO S_IFCHR = C.S_IFCHR S_IFDIR = C.S_IFDIR S_IFBLK = C.S_IFBLK S_IFREG = C.S_IFREG S_IFLNK = C.S_IFLNK S_IFSOCK = C.S_IFSOCK S_ISUID = C.S_ISUID S_ISGID = C.S_ISGID S_ISVTX = C.S_ISVTX S_IRUSR = C.S_IRUSR S_IWUSR = C.S_IWUSR S_IXUSR = C.S_IXUSR ) type Stat_t C.struct_stat type Flock_t C.struct_flock type Dirent C.struct_dirent // Sockets type RawSockaddrInet4 C.struct_sockaddr_in type RawSockaddrInet6 C.struct_sockaddr_in6 type RawSockaddrUnix C.struct_sockaddr_un type RawSockaddrDatalink C.struct_sockaddr_dl type RawSockaddr C.struct_sockaddr type RawSockaddrAny C.struct_sockaddr_any type _Socklen C.socklen_t type Linger C.struct_linger type Iovec C.struct_iovec type IPMreq C.struct_ip_mreq type IPv6Mreq C.struct_ipv6_mreq type Msghdr C.struct_msghdr type Cmsghdr C.struct_cmsghdr type Inet6Pktinfo C.struct_in6_pktinfo type IPv6MTUInfo C.struct_ip6_mtuinfo type ICMPv6Filter C.struct_icmp6_filter const ( SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6 SizeofSockaddrAny = C.sizeof_struct_sockaddr_any SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl SizeofLinger = C.sizeof_struct_linger SizeofIPMreq = C.sizeof_struct_ip_mreq SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq SizeofMsghdr = C.sizeof_struct_msghdr SizeofCmsghdr = C.sizeof_struct_cmsghdr SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter ) // Select type FdSet C.fd_set // Misc type Utsname C.struct_utsname type Ustat_t C.struct_ustat const ( AT_FDCWD = C.AT_FDCWD AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW AT_REMOVEDIR = C.AT_REMOVEDIR AT_EACCESS = C.AT_EACCESS ) // Routing and interface messages const ( SizeofIfMsghdr = C.sizeof_struct_if_msghdr SizeofIfData = C.sizeof_struct_if_data SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr SizeofRtMsghdr = C.sizeof_struct_rt_msghdr SizeofRtMetrics = C.sizeof_struct_rt_metrics ) type IfMsghdr C.struct_if_msghdr type IfData C.struct_if_data type IfaMsghdr C.struct_ifa_msghdr type RtMsghdr C.struct_rt_msghdr type RtMetrics C.struct_rt_metrics // Berkeley packet filter const ( SizeofBpfVersion = C.sizeof_struct_bpf_version SizeofBpfStat = C.sizeof_struct_bpf_stat SizeofBpfProgram = C.sizeof_struct_bpf_program SizeofBpfInsn = C.sizeof_struct_bpf_insn SizeofBpfHdr = C.sizeof_struct_bpf_hdr ) type BpfVersion C.struct_bpf_version type BpfStat C.struct_bpf_stat type BpfProgram C.struct_bpf_program type BpfInsn C.struct_bpf_insn type BpfTimeval C.struct_bpf_timeval type BpfHdr C.struct_bpf_hdr // sysconf information const _SC_PAGESIZE = C._SC_PAGESIZE // Terminal handling type Termios C.struct_termios type Termio C.struct_termio type Winsize C.struct_winsize ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_darwin_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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 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 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_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_darwin_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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 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 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_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go // +build arm,darwin 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 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 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 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 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xc 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 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_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 = 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_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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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) ) ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_darwin_arm64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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 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 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_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe 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_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 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 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_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 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_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 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 NOFLSH = 0x80000000 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_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 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 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_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_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 = 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_dragonfly_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,dragonfly // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -m32 _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_NETGRAPH = 0x20 AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 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 = 0xc0084279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4008426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCLOCK = 0x2000427a BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80084267 BIOCSETIF = 0x8020426c BIOCSETWF = 0x8008427b 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_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 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 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_MARKER = 0xf EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x8 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_NODATA = 0x1000 EV_ONESHOT = 0x10 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_SCTP = 0x84 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_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_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_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_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_NOTIFICATION = 0x200 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_SYNC = 0x800 MSG_TRUNC = 0x10 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 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_OOB = 0x2 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 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_FBUFFERED = 0x2000000 O_FMASK = 0x7fc0000 O_FNONBLOCKING = 0x80000 O_FOFFSET = 0x200000 O_FSYNC = 0x80 O_FSYNCWRITE = 0x400000 O_FUNBUFFERED = 0x1000000 O_MAPONREAD = 0x4000000 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 = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020691f SIOCGIFCONF = 0xc0086924 SIOCGIFDATA = 0xc0206926 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFGMEMB = 0xc024698a SIOCGIFINDEX = 0xc0206920 SIOCGIFMEDIA = 0xc0286938 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 = 0xc00c6978 SIOCSDRVSPEC = 0x801c697b 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_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_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 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 TCIOFLUSH = 0x3 TCOFLUSH = 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 = 0x40087458 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 = 0x40087459 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_dragonfly_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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_NETGRAPH = 0x20 AF_NS = 0x6 AF_OSI = 0x7 AF_PUP = 0x4 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_UNIX = 0x1 AF_UNSPEC = 0x0 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 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 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_MARKER = 0xf EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0x8 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_NODATA = 0x1000 EV_ONESHOT = 0x10 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_SCTP = 0x84 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_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_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_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_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_NOTIFICATION = 0x200 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_SYNC = 0x800 MSG_TRUNC = 0x10 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 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_OOB = 0x2 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_WRITE = 0x2 OCRNL = 0x10 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 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_FBUFFERED = 0x2000000 O_FMASK = 0x7fc0000 O_FNONBLOCKING = 0x80000 O_FOFFSET = 0x200000 O_FSYNC = 0x80 O_FSYNCWRITE = 0x400000 O_FUNBUFFERED = 0x1000000 O_MAPONREAD = 0x4000000 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_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_ACCEPTFILTER = 0x1000 SO_BROADCAST = 0x20 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 TCIOFLUSH = 0x3 TCOFLUSH = 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_freebsd_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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_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 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 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_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 = 0xf6 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 = 0x79 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_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xb 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_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 = 0x218f72 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_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_INFINIBAND = 0xc7 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_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 = 0xf6 IFT_PFSYNC = 0xf7 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 = 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 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_MAXID = 0x34 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_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_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_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_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 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_FAITH = 0x16 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_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTOS = 0x44 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_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_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 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 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 NET_RT_MAXID = 0x6 NOFLSH = 0x80000000 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_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 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_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 = 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_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_PRCLONING = 0x10000 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_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 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_NORTREF = 0x2 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 SIOCADDRT = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 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 SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 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 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CONGESTION = 0x40 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_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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_freebsd_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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_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 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 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_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 = 0xf6 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 = 0x79 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_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xb 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_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 = 0x218f72 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_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_INFINIBAND = 0xc7 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_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 = 0xf6 IFT_PFSYNC = 0xf7 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 = 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 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_MAXID = 0x34 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_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_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_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_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 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_FAITH = 0x16 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_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTOS = 0x44 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_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_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 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 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 NET_RT_MAXID = 0x6 NOFLSH = 0x80000000 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_MSECONDS = 0x2 NOTE_NSECONDS = 0x8 NOTE_PCTRLMASK = 0xf0000000 NOTE_PDATAMASK = 0xfffff 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 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_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 = 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_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_PRCLONING = 0x10000 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_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 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_NORTREF = 0x2 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 SIOCADDRT = 0x8040720a SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80286987 SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8040720b SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80286989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc028697b SIOCGETSGCNT = 0xc0207210 SIOCGETVIFCNT = 0xc028720f SIOCGHIWAT = 0x40047301 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 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 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 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CONGESTION = 0x40 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_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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_freebsd_arm.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; 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 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_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 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 = 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_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 = 0xf6 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 = 0x79 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_FS = -0x9 EVFILT_LIO = -0xa EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xb 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_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 = 0x218f72 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_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_INFINIBAND = 0xc7 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_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 = 0xf6 IFT_PFSYNC = 0xf7 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 = 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 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_MAXID = 0x34 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_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_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_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_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BINDANY = 0x18 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_FAITH = 0x16 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_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVRETOPTS = 0x6 IP_RECVTOS = 0x44 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_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_NORESERVE = 0x40 MAP_NOSYNC = 0x800 MAP_PREFAULT_READ = 0x40000 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 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 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 NET_RT_MAXID = 0x6 NOFLSH = 0x80000000 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_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 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_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 = 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_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_PRCLONING = 0x10000 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_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 RTV_WEIGHT = 0x100 RT_ALL_FIBS = -0x1 RT_CACHING_CONTEXT = 0x1 RT_DEFAULT_FIB = 0x0 RT_NORTREF = 0x2 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 SIOCADDRT = 0x8030720a SIOCAIFADDR = 0x8040691a SIOCAIFGROUP = 0x80246987 SIOCALIFADDR = 0x8118691b SIOCATMARK = 0x40047307 SIOCDELMULTI = 0x80206932 SIOCDELRT = 0x8030720b SIOCDIFADDR = 0x80206919 SIOCDIFGROUP = 0x80246989 SIOCDIFPHYADDR = 0x80206949 SIOCDLIFADDR = 0x8118691d SIOCGDRVSPEC = 0xc01c697b SIOCGETSGCNT = 0xc0147210 SIOCGETVIFCNT = 0xc014720f SIOCGHIWAT = 0x40047301 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 SIOCGLIFADDR = 0xc118691c SIOCGLIFPHYADDR = 0xc118694b SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCGPRIVATE_0 = 0xc0206950 SIOCGPRIVATE_1 = 0xc0206951 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 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_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 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CA_NAME_MAX = 0x10 TCP_CONGESTION = 0x40 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_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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_linux_386.go ================================================ // mkerrors.sh -m32 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x28 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_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 EPOLL_NONBLOCK = 0x800 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 IFF_MULTICAST = 0x1000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_OVS_DATAPATH = 0x8000 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DOFORK = 0xb MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 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_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 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_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_GET_THREAD_AREA = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_MASK = 0xff 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_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SEIZE = 0x4206 PTRACE_SEIZE_DEVEL = 0x80000000 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xe RTAX_MTU = 0x2 RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x10 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELNEIGH = 0x1d RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x4f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x10 RTM_NR_MSGTYPES = 0x40 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_MARK = 0x24 SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 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_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 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 = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CONGESTION = 0xd TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_QUICKACK = 0xc TCP_SYNCNT = 0x7 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 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 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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 NFS 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: "unknown error 133", } // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_linux_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x28 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_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 EPOLL_NONBLOCK = 0x800 ETH_P_1588 = 0x88f7 ETH_P_8021AD = 0x88a8 ETH_P_8021AH = 0x88e7 ETH_P_8021Q = 0x8100 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_AARP = 0x80f3 ETH_P_AF_IUCV = 0xfbfb ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_QINQ1 = 0x9100 ETH_P_QINQ2 = 0x9200 ETH_P_QINQ3 = 0x9300 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TDLS = 0x890d ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 IFF_MULTICAST = 0x1000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 IFF_OVS_DATAPATH = 0x8000 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_TAP = 0x2 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 0x800 IN_ONESHOT = 0x80000000 IN_ONLYDIR = 0x1000000 IN_OPEN = 0x20 IN_Q_OVERFLOW = 0x4000 IN_UNMOUNT = 0x2000 IPPROTO_AH = 0x33 IPPROTO_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DOFORK = 0xb MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_DUMP_INTR = 0x10 NLM_F_ECHO = 0x8 NLM_F_EXCL = 0x200 NLM_F_MATCH = 0x200 NLM_F_MULTI = 0x2 NLM_F_REPLACE = 0x100 NLM_F_REQUEST = 0x1 NLM_F_ROOT = 0x100 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 OLCUC = 0x2 ONLCR = 0x4 ONLRET = 0x20 ONOCR = 0x10 OPOST = 0x1 O_ACCMODE = 0x3 O_APPEND = 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_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_AUXDATA = 0x8 PACKET_BROADCAST = 0x1 PACKET_COPY_THRESH = 0x7 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FANOUT = 0x12 PACKET_FANOUT_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_KEEPCAPS = 0x8 PR_SET_MM = 0x23 PR_SET_MM_BRK = 0x7 PR_SET_MM_END_CODE = 0x2 PR_SET_MM_END_DATA = 0x4 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_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_GET_THREAD_AREA = 0x19 PTRACE_INTERRUPT = 0x4207 PTRACE_KILL = 0x8 PTRACE_LISTEN = 0x4208 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_MASK = 0xff 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_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SEIZE = 0x4206 PTRACE_SEIZE_DEVEL = 0x80000000 PTRACE_SETFPREGS = 0xf PTRACE_SETFPXREGS = 0x13 PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xe RTAX_MTU = 0x2 RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x10 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELNEIGH = 0x1d RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x4f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x10 RTM_NR_MSGTYPES = 0x40 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_MARK = 0x24 SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 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_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 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 = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CONGESTION = 0xd TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_QUICKACK = 0xc TCP_SYNCNT = 0x7 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 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 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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 NFS 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: "unknown error 133", } // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_linux_arm.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x27 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_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_PHY = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXINSNS = 0x1000 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 BS0 = 0x0 BS1 = 0x2000 BSDLY = 0x2000 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ELF_NGREG = 0x12 ELF_PRARGSZ = 0x50 ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 EPOLLERR = 0x8 EPOLLET = -0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 EPOLLWRBAND = 0x200 EPOLLWRNORM = 0x100 EPOLL_CLOEXEC = 0x80000 EPOLL_CTL_ADD = 0x1 EPOLL_CTL_DEL = 0x2 EPOLL_CTL_MOD = 0x3 EPOLL_NONBLOCK = 0x800 ETH_P_1588 = 0x88f7 ETH_P_8021Q = 0x8100 ETH_P_802_2 = 0x4 ETH_P_802_3 = 0x1 ETH_P_AARP = 0x80f3 ETH_P_ALL = 0x3 ETH_P_AOE = 0x88a2 ETH_P_ARCNET = 0x1a ETH_P_ARP = 0x806 ETH_P_ATALK = 0x809b ETH_P_ATMFATE = 0x8884 ETH_P_ATMMPOA = 0x884c ETH_P_AX25 = 0x2 ETH_P_BPQ = 0x8ff ETH_P_CAIF = 0xf7 ETH_P_CAN = 0xc ETH_P_CONTROL = 0x16 ETH_P_CUST = 0x6006 ETH_P_DDCMP = 0x6 ETH_P_DEC = 0x6000 ETH_P_DIAG = 0x6005 ETH_P_DNA_DL = 0x6001 ETH_P_DNA_RC = 0x6002 ETH_P_DNA_RT = 0x6003 ETH_P_DSA = 0x1b ETH_P_ECONET = 0x18 ETH_P_EDSA = 0xdada ETH_P_FCOE = 0x8906 ETH_P_FIP = 0x8914 ETH_P_HDLC = 0x19 ETH_P_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_PAE = 0x888e ETH_P_PAUSE = 0x8808 ETH_P_PHONET = 0xf5 ETH_P_PPPTALK = 0x10 ETH_P_PPP_DISC = 0x8863 ETH_P_PPP_MP = 0x8 ETH_P_PPP_SES = 0x8864 ETH_P_PUP = 0x200 ETH_P_PUPAT = 0x201 ETH_P_RARP = 0x8035 ETH_P_SCA = 0x6007 ETH_P_SLOW = 0x8809 ETH_P_SNAP = 0x5 ETH_P_TEB = 0x6558 ETH_P_TIPC = 0x88ca ETH_P_TRAILER = 0x1c ETH_P_TR_802_2 = 0x11 ETH_P_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_ALLMULTI = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DYNAMIC = 0x8000 IFF_LOOPBACK = 0x8 IFF_MASTER = 0x400 IFF_MULTICAST = 0x1000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_NO_PI = 0x1000 IFF_ONE_QUEUE = 0x2000 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 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_COMP = 0x6c IPPROTO_DCCP = 0x21 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_ENCAP = 0x62 IPPROTO_ESP = 0x32 IPPROTO_FRAGMENT = 0x2c IPPROTO_GRE = 0x2f IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IGMP = 0x2 IPPROTO_IP = 0x0 IPPROTO_IPIP = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_XFRM_POLICY = 0x11 ISIG = 0x1 ISTRIP = 0x20 IUCLC = 0x200 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 LINUX_REBOOT_CMD_CAD_OFF = 0x0 LINUX_REBOOT_CMD_CAD_ON = 0x89abcdef LINUX_REBOOT_CMD_HALT = 0xcdef0123 LINUX_REBOOT_CMD_KEXEC = 0x45584543 LINUX_REBOOT_CMD_POWER_OFF = 0x4321fedc LINUX_REBOOT_CMD_RESTART = 0x1234567 LINUX_REBOOT_CMD_RESTART2 = 0xa1b2c3d4 LINUX_REBOOT_CMD_SW_SUSPEND = 0xd000fce2 LINUX_REBOOT_MAGIC1 = 0xfee1dead LINUX_REBOOT_MAGIC2 = 0x28121969 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_DOFORK = 0xb MADV_DONTFORK = 0xa MADV_DONTNEED = 0x4 MADV_HUGEPAGE = 0xe MADV_HWPOISON = 0x64 MADV_MERGEABLE = 0xc MADV_NOHUGEPAGE = 0xf MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_REMOVE = 0x9 MADV_SEQUENTIAL = 0x2 MADV_UNMERGEABLE = 0xd MADV_WILLNEED = 0x3 MAP_ANON = 0x20 MAP_ANONYMOUS = 0x20 MAP_DENYWRITE = 0x800 MAP_EXECUTABLE = 0x1000 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_GROWSDOWN = 0x100 MAP_LOCKED = 0x2000 MAP_NONBLOCK = 0x10000 MAP_NORESERVE = 0x4000 MAP_POPULATE = 0x8000 MAP_PRIVATE = 0x2 MAP_SHARED = 0x1 MAP_TYPE = 0xf MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_SCSITRANSPORT = 0x12 NETLINK_SELINUX = 0x7 NETLINK_UNUSED = 0x1 NETLINK_USERSOCK = 0x2 NETLINK_XFRM = 0x6 NL0 = 0x0 NL1 = 0x100 NLA_ALIGNTO = 0x4 NLA_F_NESTED = 0x8000 NLA_F_NET_BYTEORDER = 0x4000 NLA_HDRLEN = 0x4 NLDLY = 0x100 NLMSG_ALIGNTO = 0x4 NLMSG_DONE = 0x3 NLMSG_ERROR = 0x2 NLMSG_HDRLEN = 0x10 NLMSG_MIN_TYPE = 0x10 NLMSG_NOOP = 0x1 NLMSG_OVERRUN = 0x4 NLM_F_ACK = 0x4 NLM_F_APPEND = 0x800 NLM_F_ATOMIC = 0x400 NLM_F_CREATE = 0x400 NLM_F_DUMP = 0x300 NLM_F_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 = 0x1000 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 = 0x1000 O_SYNC = 0x1000 O_TRUNC = 0x200 O_WRONLY = 0x1 PACKET_ADD_MEMBERSHIP = 0x1 PACKET_BROADCAST = 0x1 PACKET_DROP_MEMBERSHIP = 0x2 PACKET_FASTROUTE = 0x6 PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MULTICAST = 0x2 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PARENB = 0x100 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_CLEAR_SECCOMP_FILTER = 0x25 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECCOMP_FILTER = 0x23 PR_GET_SECUREBITS = 0x1b PR_GET_TIMERSLACK = 0x1e PR_GET_TIMING = 0xd PR_GET_TSC = 0x19 PR_GET_UNALIGN = 0x5 PR_MCE_KILL = 0x21 PR_MCE_KILL_CLEAR = 0x0 PR_MCE_KILL_DEFAULT = 0x2 PR_MCE_KILL_EARLY = 0x1 PR_MCE_KILL_GET = 0x22 PR_MCE_KILL_LATE = 0x0 PR_MCE_KILL_SET = 0x1 PR_SECCOMP_FILTER_EVENT = 0x1 PR_SECCOMP_FILTER_SYSCALL = 0x0 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc PR_SET_KEEPCAPS = 0x8 PR_SET_NAME = 0xf PR_SET_PDEATHSIG = 0x1 PR_SET_PTRACER = 0x59616d61 PR_SET_SECCOMP = 0x16 PR_SET_SECCOMP_FILTER = 0x24 PR_SET_SECUREBITS = 0x1c PR_SET_TIMERSLACK = 0x1d PR_SET_TIMING = 0xe PR_SET_TSC = 0x1a PR_SET_UNALIGN = 0x6 PR_TASK_PERF_EVENTS_DISABLE = 0x1f PR_TASK_PERF_EVENTS_ENABLE = 0x20 PR_TIMING_STATISTICAL = 0x0 PR_TIMING_TIMESTAMP = 0x1 PR_TSC_ENABLE = 0x1 PR_TSC_SIGSEGV = 0x2 PR_UNALIGN_NOPRINT = 0x1 PR_UNALIGN_SIGBUS = 0x2 PTRACE_ATTACH = 0x10 PTRACE_CONT = 0x7 PTRACE_DETACH = 0x11 PTRACE_EVENT_CLONE = 0x3 PTRACE_EVENT_EXEC = 0x4 PTRACE_EVENT_EXIT = 0x6 PTRACE_EVENT_FORK = 0x1 PTRACE_EVENT_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_GETVFPREGS = 0x1b PTRACE_GETWMMXREGS = 0x12 PTRACE_GET_THREAD_AREA = 0x16 PTRACE_KILL = 0x8 PTRACE_OLDSETOPTIONS = 0x15 PTRACE_O_MASK = 0x7f PTRACE_O_TRACECLONE = 0x8 PTRACE_O_TRACEEXEC = 0x10 PTRACE_O_TRACEEXIT = 0x40 PTRACE_O_TRACEFORK = 0x2 PTRACE_O_TRACESYSGOOD = 0x1 PTRACE_O_TRACEVFORK = 0x4 PTRACE_O_TRACEVFORKDONE = 0x20 PTRACE_PEEKDATA = 0x2 PTRACE_PEEKTEXT = 0x1 PTRACE_PEEKUSR = 0x3 PTRACE_POKEDATA = 0x5 PTRACE_POKETEXT = 0x4 PTRACE_POKEUSR = 0x6 PTRACE_SETCRUNCHREGS = 0x1a PTRACE_SETFPREGS = 0xf PTRACE_SETHBPREGS = 0x1e PTRACE_SETOPTIONS = 0x4200 PTRACE_SETREGS = 0xd PTRACE_SETREGSET = 0x4205 PTRACE_SETSIGINFO = 0x4203 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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xe RTAX_MTU = 0x2 RTAX_REORDERING = 0x9 RTAX_RTO_MIN = 0xd RTAX_RTT = 0x4 RTAX_RTTVAR = 0x5 RTAX_SSTHRESH = 0x6 RTAX_UNSPEC = 0x0 RTAX_WINDOW = 0x3 RTA_ALIGNTO = 0x4 RTA_MAX = 0x10 RTCF_DIRECTSRC = 0x4000000 RTCF_DOREDIRECT = 0x1000000 RTCF_LOG = 0x2000000 RTCF_MASQ = 0x400000 RTCF_NAT = 0x800000 RTCF_VALVE = 0x200000 RTF_ADDRCLASSMASK = 0xf8000000 RTF_ADDRCONF = 0x40000 RTF_ALLONLINK = 0x20000 RTF_BROADCAST = 0x10000000 RTF_CACHE = 0x1000000 RTF_DEFAULT = 0x10000 RTF_DYNAMIC = 0x10 RTF_FLOW = 0x2000000 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_INTERFACE = 0x40000000 RTF_IRTT = 0x100 RTF_LINKRT = 0x100000 RTF_LOCAL = 0x80000000 RTF_MODIFIED = 0x20 RTF_MSS = 0x40 RTF_MTU = 0x40 RTF_MULTICAST = 0x20000000 RTF_NAT = 0x8000000 RTF_NOFORWARD = 0x1000 RTF_NONEXTHOP = 0x200000 RTF_NOPMTUDISC = 0x4000 RTF_POLICY = 0x4000000 RTF_REINSTATE = 0x8 RTF_REJECT = 0x200 RTF_STATIC = 0x400 RTF_THROW = 0x2000 RTF_UP = 0x1 RTF_WINDOW = 0x80 RTF_XRESOLVE = 0x800 RTM_BASE = 0x10 RTM_DELACTION = 0x31 RTM_DELADDR = 0x15 RTM_DELADDRLABEL = 0x49 RTM_DELLINK = 0x11 RTM_DELNEIGH = 0x1d RTM_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x4f RTM_NEWACTION = 0x30 RTM_NEWADDR = 0x14 RTM_NEWADDRLABEL = 0x48 RTM_NEWLINK = 0x10 RTM_NEWNDUSEROPT = 0x44 RTM_NEWNEIGH = 0x1c RTM_NEWNEIGHTBL = 0x40 RTM_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x10 RTM_NR_MSGTYPES = 0x40 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_KEEPALIVE = 0x9 SO_LINGER = 0xd SO_MARK = 0x24 SO_NO_CHECK = 0xb SO_OOBINLINE = 0xa SO_PASSCRED = 0x10 SO_PASSSEC = 0x22 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_RXQ_OVFL = 0x28 SO_SECURITY_AUTHENTICATION = 0x16 SO_SECURITY_ENCRYPTION_NETWORK = 0x18 SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17 SO_SNDBUF = 0x7 SO_SNDBUFFORCE = 0x20 SO_SNDLOWAT = 0x13 SO_SNDTIMEO = 0x15 SO_TIMESTAMP = 0x1d SO_TIMESTAMPING = 0x25 SO_TIMESTAMPNS = 0x23 SO_TYPE = 0x3 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 = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 TCP_CONGESTION = 0xd TCP_CORK = 0x3 TCP_DEFER_ACCEPT = 0x9 TCP_INFO = 0xb TCP_KEEPCNT = 0x6 TCP_KEEPIDLE = 0x4 TCP_KEEPINTVL = 0x5 TCP_LINGER2 = 0x8 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_WINSHIFT = 0xe TCP_MD5SIG = 0xe TCP_MD5SIG_MAXKEYLEN = 0x50 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_QUICKACK = 0xc TCP_SYNCNT = 0x7 TCP_WINDOW_CLAMP = 0xa TCSAFLUSH = 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 TUNATTACHFILTER = 0x400854d5 TUNDETACHFILTER = 0x400854d6 TUNGETFEATURES = 0x800454cf TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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 NFS 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: "unknown error 133", } // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_linux_arm64.go ================================================ // mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go package unix import "syscall" const ( AF_ALG = 0x26 AF_APPLETALK = 0x5 AF_ASH = 0x12 AF_ATMPVC = 0x8 AF_ATMSVC = 0x14 AF_AX25 = 0x3 AF_BLUETOOTH = 0x1f AF_BRIDGE = 0x7 AF_CAIF = 0x25 AF_CAN = 0x1d AF_DECnet = 0xc AF_ECONET = 0x13 AF_FILE = 0x1 AF_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x29 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 0x1008 B110 = 0x3 B115200 = 0x1002 B1152000 = 0x1009 B1200 = 0x9 B134 = 0x4 B150 = 0x5 B1500000 = 0x100a B1800 = 0xa B19200 = 0xe B200 = 0x6 B2000000 = 0x100b B230400 = 0x1003 B2400 = 0xb B2500000 = 0x100c B300 = 0x7 B3000000 = 0x100d B3500000 = 0x100e B38400 = 0xf B4000000 = 0x100f B460800 = 0x1004 B4800 = 0xc B50 = 0x1 B500000 = 0x1005 B57600 = 0x1001 B576000 = 0x1006 B600 = 0x8 B75 = 0x2 B921600 = 0x1007 B9600 = 0xd BOTHER = 0x1000 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_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_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 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 0x200 CR2 = 0x400 CR3 = 0x600 CRDLY = 0x600 CREAD = 0x80 CRTSCTS = 0x80000000 CS5 = 0x0 CS6 = 0x10 CS7 = 0x20 CS8 = 0x30 CSIGNAL = 0xff CSIZE = 0x30 CSTART = 0x11 CSTATUS = 0x0 CSTOP = 0x13 CSTOPB = 0x40 CSUSP = 0x1a DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x200 ECHOE = 0x10 ECHOK = 0x20 ECHOKE = 0x800 ECHONL = 0x40 ECHOPRT = 0x400 ELF_NGREG = 0x22 ELF_PRARGSZ = 0x50 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 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_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_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_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_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x8000 FFDLY = 0x8000 FLUSHO = 0x1000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LIVE_ADDR_CHANGE = 0x100000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN = 0x200000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 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_OVS_DATAPATH = 0x8000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_SUPP_NOFCS = 0x80000 IFF_TAP = 0x2 IFF_TEAM_PORT = 0x40000 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 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_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_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_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 = 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_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 PACKET_VERSION = 0xa PACKET_VNET_HDR = 0xf PARENB = 0x100 PARITY_CRC16_PR0 = 0x2 PARITY_CRC16_PR0_CCITT = 0x4 PARITY_CRC16_PR1 = 0x3 PARITY_CRC16_PR1_CCITT = 0x5 PARITY_CRC32_PR0_CCITT = 0x6 PARITY_CRC32_PR1_CCITT = 0x7 PARITY_DEFAULT = 0x0 PARITY_NONE = 0x1 PARMRK = 0x8 PARODD = 0x200 PENDIN = 0x4000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x1000000 PROT_GROWSUP = 0x2000000 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PR_CAPBSET_DROP = 0x18 PR_CAPBSET_READ = 0x17 PR_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b 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_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc 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_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_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 = 0x1000ff 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_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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xf 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 = 0x11 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_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x57 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_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x12 RTM_NR_MSGTYPES = 0x48 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a 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_WIFI_STATUS = 0x29 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x800 TAB2 = 0x1000 TAB3 = 0x1800 TABDLY = 0x1800 TCFLSH = 0x540b TCGETA = 0x5405 TCGETS = 0x5401 TCGETS2 = 0x802c542a TCGETX = 0x5432 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 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_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 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 TUNATTACHFILTER = 0x401054d5 TUNDETACHFILTER = 0x401054d6 TUNGETFEATURES = 0x800454cf TUNGETFILTER = 0x801054db TUNGETIFF = 0x800454d2 TUNGETSNDBUF = 0x800454d3 TUNGETVNETHDRSZ = 0x800454d7 TUNSETDEBUG = 0x400454c9 TUNSETGROUP = 0x400454ce TUNSETIFF = 0x400454ca TUNSETIFINDEX = 0x400454da TUNSETLINK = 0x400454cd TUNSETNOCSUM = 0x400454c8 TUNSETOFFLOAD = 0x400454d0 TUNSETOWNER = 0x400454cc TUNSETPERSIST = 0x400454cb TUNSETQUEUE = 0x400454d9 TUNSETSNDBUF = 0x400454d4 TUNSETTXFILTER = 0x400454d1 TUNSETVNETHDRSZ = 0x400454d8 VDISCARD = 0xd VEOF = 0x4 VEOL = 0xb VEOL2 = 0x10 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x6 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_linux_ppc64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64,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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x29 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_6LOWPAN = 0x339 ARPHRD_ADAPT = 0x108 ARPHRD_APPLETLK = 0x8 ARPHRD_ARCNET = 0x7 ARPHRD_ASH = 0x30d ARPHRD_ATM = 0x13 ARPHRD_AX25 = 0x3 ARPHRD_BIF = 0x307 ARPHRD_CAIF = 0x336 ARPHRD_CAN = 0x118 ARPHRD_CHAOS = 0x5 ARPHRD_CISCO = 0x201 ARPHRD_CSLIP = 0x101 ARPHRD_CSLIP6 = 0x103 ARPHRD_DDCMP = 0x205 ARPHRD_DLCI = 0xf ARPHRD_ECONET = 0x30e ARPHRD_EETHER = 0x2 ARPHRD_ETHER = 0x1 ARPHRD_EUI64 = 0x1b ARPHRD_FCAL = 0x311 ARPHRD_FCFABRIC = 0x313 ARPHRD_FCPL = 0x312 ARPHRD_FCPP = 0x310 ARPHRD_FDDI = 0x306 ARPHRD_FRAD = 0x302 ARPHRD_HDLC = 0x201 ARPHRD_HIPPI = 0x30c ARPHRD_HWX25 = 0x110 ARPHRD_IEEE1394 = 0x18 ARPHRD_IEEE802 = 0x6 ARPHRD_IEEE80211 = 0x321 ARPHRD_IEEE80211_PRISM = 0x322 ARPHRD_IEEE80211_RADIOTAP = 0x323 ARPHRD_IEEE802154 = 0x324 ARPHRD_IEEE802154_MONITOR = 0x325 ARPHRD_IEEE802_TR = 0x320 ARPHRD_INFINIBAND = 0x20 ARPHRD_IP6GRE = 0x337 ARPHRD_IPDDP = 0x309 ARPHRD_IPGRE = 0x30a ARPHRD_IRDA = 0x30f ARPHRD_LAPB = 0x204 ARPHRD_LOCALTLK = 0x305 ARPHRD_LOOPBACK = 0x304 ARPHRD_METRICOM = 0x17 ARPHRD_NETLINK = 0x338 ARPHRD_NETROM = 0x0 ARPHRD_NONE = 0xfffe ARPHRD_PHONET = 0x334 ARPHRD_PHONET_PIPE = 0x335 ARPHRD_PIMREG = 0x30b ARPHRD_PPP = 0x200 ARPHRD_PRONET = 0x4 ARPHRD_RAWHDLC = 0x206 ARPHRD_ROSE = 0x10e ARPHRD_RSRVD = 0x104 ARPHRD_SIT = 0x308 ARPHRD_SKIP = 0x303 ARPHRD_SLIP = 0x100 ARPHRD_SLIP6 = 0x102 ARPHRD_TUNNEL = 0x300 ARPHRD_TUNNEL6 = 0x301 ARPHRD_VOID = 0xffff ARPHRD_X25 = 0x10f B0 = 0x0 B1000000 = 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 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_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_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 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 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 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 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_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_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_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 ETH_P_XDSA = 0xf8 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 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 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_NODAD = 0x2 IFA_F_NOPREFIXROUTE = 0x200 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 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_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_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_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_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 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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_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_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 = 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_CPU = 0x2 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_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 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_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_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_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc 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 = 0x1000ff 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_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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xf 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 = 0x11 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_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x57 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_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x12 RTM_NR_MSGTYPES = 0x48 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BPF_EXTENSIONS = 0x30 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a 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_WIFI_STATUS = 0x29 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 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_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 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 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETHDRSZ = 0x400454d7 TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETHDRSZ = 0x800454d8 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 VEOL2 = 0x8 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x5 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_linux_ppc64le.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64le,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_IEEE802154 = 0x24 AF_INET = 0x2 AF_INET6 = 0xa AF_IPX = 0x4 AF_IRDA = 0x17 AF_ISDN = 0x22 AF_IUCV = 0x20 AF_KEY = 0xf AF_LLC = 0x1a AF_LOCAL = 0x1 AF_MAX = 0x29 AF_NETBEUI = 0xd AF_NETLINK = 0x10 AF_NETROM = 0x6 AF_NFC = 0x27 AF_PACKET = 0x11 AF_PHONET = 0x23 AF_PPPOX = 0x18 AF_RDS = 0x15 AF_ROSE = 0xb AF_ROUTE = 0x10 AF_RXRPC = 0x21 AF_SECURITY = 0xe AF_SNA = 0x16 AF_TIPC = 0x1e AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_VSOCK = 0x28 AF_WANPIPE = 0x19 AF_X25 = 0x9 ARPHRD_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 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_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_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 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_THREAD_CPUTIME_ID = 0x3 CLOCK_TXFROMRX = 0x4 CLOCK_TXINT = 0x3 CLONE_CHILD_CLEARTID = 0x200000 CLONE_CHILD_SETTID = 0x1000000 CLONE_DETACHED = 0x400000 CLONE_FILES = 0x400 CLONE_FS = 0x200 CLONE_IO = 0x80000000 CLONE_NEWIPC = 0x8000000 CLONE_NEWNET = 0x40000000 CLONE_NEWNS = 0x20000 CLONE_NEWPID = 0x20000000 CLONE_NEWUSER = 0x10000000 CLONE_NEWUTS = 0x4000000 CLONE_PARENT = 0x8000 CLONE_PARENT_SETTID = 0x100000 CLONE_PTRACE = 0x2000 CLONE_SETTLS = 0x80000 CLONE_SIGHAND = 0x800 CLONE_SYSVSEM = 0x40000 CLONE_THREAD = 0x10000 CLONE_UNTRACED = 0x800000 CLONE_VFORK = 0x4000 CLONE_VM = 0x100 CMSPAR = 0x40000000 CR0 = 0x0 CR1 = 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 ENCODING_DEFAULT = 0x0 ENCODING_FM_MARK = 0x3 ENCODING_FM_SPACE = 0x4 ENCODING_MANCHESTER = 0x5 ENCODING_NRZ = 0x1 ENCODING_NRZI = 0x2 EPOLLERR = 0x8 EPOLLET = 0x80000000 EPOLLHUP = 0x10 EPOLLIN = 0x1 EPOLLMSG = 0x400 EPOLLONESHOT = 0x40000000 EPOLLOUT = 0x4 EPOLLPRI = 0x2 EPOLLRDBAND = 0x80 EPOLLRDHUP = 0x2000 EPOLLRDNORM = 0x40 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_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_IEEE802154 = 0xf6 ETH_P_IEEEPUP = 0xa00 ETH_P_IEEEPUPAT = 0xa01 ETH_P_IP = 0x800 ETH_P_IPV6 = 0x86dd ETH_P_IPX = 0x8137 ETH_P_IRDA = 0x17 ETH_P_LAT = 0x6004 ETH_P_LINK_CTL = 0x886c ETH_P_LOCALTALK = 0x9 ETH_P_LOOP = 0x60 ETH_P_MOBITEX = 0x15 ETH_P_MPLS_MC = 0x8848 ETH_P_MPLS_UC = 0x8847 ETH_P_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_WAN_PPP = 0x7 ETH_P_WCCP = 0x883e ETH_P_X25 = 0x805 EXTA = 0xe EXTB = 0xf EXTPROC = 0x10000000 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FF0 = 0x0 FF1 = 0x4000 FFDLY = 0x4000 FLUSHO = 0x800000 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_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 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_NODAD = 0x2 IFA_F_OPTIMISTIC = 0x4 IFA_F_PERMANENT = 0x80 IFA_F_SECONDARY = 0x1 IFA_F_TEMPORARY = 0x1 IFA_F_TENTATIVE = 0x40 IFA_MAX = 0x7 IFF_802_1Q_VLAN = 0x1 IFF_ALLMULTI = 0x200 IFF_ATTACH_QUEUE = 0x200 IFF_AUTOMEDIA = 0x4000 IFF_BONDING = 0x20 IFF_BRIDGE_PORT = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_DETACH_QUEUE = 0x400 IFF_DISABLE_NETPOLL = 0x1000 IFF_DONT_BRIDGE = 0x800 IFF_DORMANT = 0x20000 IFF_DYNAMIC = 0x8000 IFF_EBRIDGE = 0x2 IFF_ECHO = 0x40000 IFF_ISATAP = 0x80 IFF_LIVE_ADDR_CHANGE = 0x100000 IFF_LOOPBACK = 0x8 IFF_LOWER_UP = 0x10000 IFF_MACVLAN = 0x200000 IFF_MACVLAN_PORT = 0x2000 IFF_MASTER = 0x400 IFF_MASTER_8023AD = 0x8 IFF_MASTER_ALB = 0x10 IFF_MASTER_ARPMON = 0x100 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_OVS_DATAPATH = 0x8000 IFF_PERSIST = 0x800 IFF_POINTOPOINT = 0x10 IFF_PORTSEL = 0x2000 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SLAVE = 0x800 IFF_SLAVE_INACTIVE = 0x4 IFF_SLAVE_NEEDARP = 0x40 IFF_SUPP_NOFCS = 0x80000 IFF_TAP = 0x2 IFF_TEAM_PORT = 0x40000 IFF_TUN = 0x1 IFF_TUN_EXCL = 0x8000 IFF_TX_SKB_SHARING = 0x10000 IFF_UNICAST_FLT = 0x20000 IFF_UP = 0x1 IFF_VNET_HDR = 0x4000 IFF_VOLATILE = 0x70c5a IFF_WAN_HDLC = 0x200 IFF_XMIT_DST_RELEASE = 0x400 IFNAMSIZ = 0x10 IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_ACCESS = 0x1 IN_ALL_EVENTS = 0xfff IN_ATTRIB = 0x4 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLOEXEC = 0x80000 IN_CLOSE = 0x18 IN_CLOSE_NOWRITE = 0x10 IN_CLOSE_WRITE = 0x8 IN_CREATE = 0x100 IN_DELETE = 0x200 IN_DELETE_SELF = 0x400 IN_DONT_FOLLOW = 0x2000000 IN_EXCL_UNLINK = 0x4000000 IN_IGNORED = 0x8000 IN_ISDIR = 0x40000000 IN_LOOPBACKNET = 0x7f IN_MASK_ADD = 0x20000000 IN_MODIFY = 0x2 IN_MOVE = 0xc0 IN_MOVED_FROM = 0x40 IN_MOVED_TO = 0x80 IN_MOVE_SELF = 0x800 IN_NONBLOCK = 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_MTP = 0x5c IPPROTO_NONE = 0x3b IPPROTO_PIM = 0x67 IPPROTO_PUP = 0xc IPPROTO_RAW = 0xff IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_SCTP = 0x84 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_UDP = 0x11 IPPROTO_UDPLITE = 0x88 IPV6_2292DSTOPTS = 0x4 IPV6_2292HOPLIMIT = 0x8 IPV6_2292HOPOPTS = 0x3 IPV6_2292PKTINFO = 0x2 IPV6_2292PKTOPTIONS = 0x6 IPV6_2292RTHDR = 0x5 IPV6_ADDRFORM = 0x1 IPV6_ADD_MEMBERSHIP = 0x14 IPV6_AUTHHDR = 0xa IPV6_CHECKSUM = 0x7 IPV6_DROP_MEMBERSHIP = 0x15 IPV6_DSTOPTS = 0x3b IPV6_HOPLIMIT = 0x34 IPV6_HOPOPTS = 0x36 IPV6_IPSEC_POLICY = 0x22 IPV6_JOIN_ANYCAST = 0x1b IPV6_JOIN_GROUP = 0x14 IPV6_LEAVE_ANYCAST = 0x1c IPV6_LEAVE_GROUP = 0x15 IPV6_MTU = 0x18 IPV6_MTU_DISCOVER = 0x17 IPV6_MULTICAST_HOPS = 0x12 IPV6_MULTICAST_IF = 0x11 IPV6_MULTICAST_LOOP = 0x13 IPV6_NEXTHOP = 0x9 IPV6_PKTINFO = 0x32 IPV6_PMTUDISC_DO = 0x2 IPV6_PMTUDISC_DONT = 0x0 IPV6_PMTUDISC_PROBE = 0x3 IPV6_PMTUDISC_WANT = 0x1 IPV6_RECVDSTOPTS = 0x3a IPV6_RECVERR = 0x19 IPV6_RECVHOPLIMIT = 0x33 IPV6_RECVHOPOPTS = 0x35 IPV6_RECVPKTINFO = 0x31 IPV6_RECVRTHDR = 0x38 IPV6_RECVTCLASS = 0x42 IPV6_ROUTER_ALERT = 0x16 IPV6_RTHDR = 0x39 IPV6_RTHDRDSTOPTS = 0x37 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_RXDSTOPTS = 0x3b IPV6_RXHOPOPTS = 0x36 IPV6_TCLASS = 0x43 IPV6_UNICAST_HOPS = 0x10 IPV6_V6ONLY = 0x1a IPV6_XFRM_POLICY = 0x23 IP_ADD_MEMBERSHIP = 0x23 IP_ADD_SOURCE_MEMBERSHIP = 0x27 IP_BLOCK_SOURCE = 0x26 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0x24 IP_DROP_SOURCE_MEMBERSHIP = 0x28 IP_FREEBIND = 0xf IP_HDRINCL = 0x3 IP_IPSEC_POLICY = 0x10 IP_MAXPACKET = 0xffff IP_MAX_MEMBERSHIPS = 0x14 IP_MF = 0x2000 IP_MINTTL = 0x15 IP_MSFILTER = 0x29 IP_MSS = 0x240 IP_MTU = 0xe IP_MTU_DISCOVER = 0xa IP_MULTICAST_ALL = 0x31 IP_MULTICAST_IF = 0x20 IP_MULTICAST_LOOP = 0x22 IP_MULTICAST_TTL = 0x21 IP_OFFMASK = 0x1fff IP_OPTIONS = 0x4 IP_ORIGDSTADDR = 0x14 IP_PASSSEC = 0x12 IP_PKTINFO = 0x8 IP_PKTOPTIONS = 0x9 IP_PMTUDISC = 0xa IP_PMTUDISC_DO = 0x2 IP_PMTUDISC_DONT = 0x0 IP_PMTUDISC_PROBE = 0x3 IP_PMTUDISC_WANT = 0x1 IP_RECVERR = 0xb IP_RECVOPTS = 0x6 IP_RECVORIGDSTADDR = 0x14 IP_RECVRETOPTS = 0x7 IP_RECVTOS = 0xd IP_RECVTTL = 0xc IP_RETOPTS = 0x7 IP_RF = 0x8000 IP_ROUTER_ALERT = 0x5 IP_TOS = 0x1 IP_TRANSPARENT = 0x13 IP_TTL = 0x2 IP_UNBLOCK_SOURCE = 0x25 IP_UNICAST_IF = 0x32 IP_XFRM_POLICY = 0x11 ISIG = 0x80 ISTRIP = 0x20 IUCLC = 0x1000 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 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_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 MNT_DETACH = 0x2 MNT_EXPIRE = 0x4 MNT_FORCE = 0x1 MSG_CMSG_CLOEXEC = 0x40000000 MSG_CONFIRM = 0x800 MSG_CTRUNC = 0x8 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x40 MSG_EOR = 0x80 MSG_ERRQUEUE = 0x2000 MSG_FASTOPEN = 0x20000000 MSG_FIN = 0x200 MSG_MORE = 0x8000 MSG_NOSIGNAL = 0x4000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_PROXY = 0x10 MSG_RST = 0x1000 MSG_SYN = 0x400 MSG_TRUNC = 0x20 MSG_TRYHARD = 0x4 MSG_WAITALL = 0x100 MSG_WAITFORONE = 0x10000 MS_ACTIVE = 0x40000000 MS_ASYNC = 0x1 MS_BIND = 0x1000 MS_DIRSYNC = 0x80 MS_INVALIDATE = 0x2 MS_I_VERSION = 0x800000 MS_KERNMOUNT = 0x400000 MS_MANDLOCK = 0x40 MS_MGC_MSK = 0xffff0000 MS_MGC_VAL = 0xc0ed0000 MS_MOVE = 0x2000 MS_NOATIME = 0x400 MS_NODEV = 0x4 MS_NODIRATIME = 0x800 MS_NOEXEC = 0x8 MS_NOSUID = 0x2 MS_NOUSER = -0x80000000 MS_POSIXACL = 0x10000 MS_PRIVATE = 0x40000 MS_RDONLY = 0x1 MS_REC = 0x4000 MS_RELATIME = 0x200000 MS_REMOUNT = 0x20 MS_RMT_MASK = 0x800051 MS_SHARED = 0x100000 MS_SILENT = 0x8000 MS_SLAVE = 0x80000 MS_STRICTATIME = 0x1000000 MS_SYNC = 0x4 MS_SYNCHRONOUS = 0x10 MS_UNBINDABLE = 0x20000 NAME_MAX = 0xff NETLINK_ADD_MEMBERSHIP = 0x1 NETLINK_AUDIT = 0x9 NETLINK_BROADCAST_ERROR = 0x4 NETLINK_CONNECTOR = 0xb NETLINK_CRYPTO = 0x15 NETLINK_DNRTMSG = 0xe NETLINK_DROP_MEMBERSHIP = 0x2 NETLINK_ECRYPTFS = 0x13 NETLINK_FIB_LOOKUP = 0xa NETLINK_FIREWALL = 0x3 NETLINK_GENERIC = 0x10 NETLINK_INET_DIAG = 0x4 NETLINK_IP6_FW = 0xd NETLINK_ISCSI = 0x8 NETLINK_KOBJECT_UEVENT = 0xf NETLINK_NETFILTER = 0xc NETLINK_NFLOG = 0x5 NETLINK_NO_ENOBUFS = 0x5 NETLINK_PKTINFO = 0x3 NETLINK_RDMA = 0x14 NETLINK_ROUTE = 0x0 NETLINK_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_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 = 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_CPU = 0x2 PACKET_FANOUT_FLAG_DEFRAG = 0x8000 PACKET_FANOUT_FLAG_ROLLOVER = 0x1000 PACKET_FANOUT_HASH = 0x0 PACKET_FANOUT_LB = 0x1 PACKET_FANOUT_RND = 0x4 PACKET_FANOUT_ROLLOVER = 0x3 PACKET_FASTROUTE = 0x6 PACKET_HDRLEN = 0xb PACKET_HOST = 0x0 PACKET_LOOPBACK = 0x5 PACKET_LOSS = 0xe PACKET_MR_ALLMULTI = 0x2 PACKET_MR_MULTICAST = 0x0 PACKET_MR_PROMISC = 0x1 PACKET_MR_UNICAST = 0x3 PACKET_MULTICAST = 0x2 PACKET_ORIGDEV = 0x9 PACKET_OTHERHOST = 0x3 PACKET_OUTGOING = 0x4 PACKET_RECV_OUTPUT = 0x3 PACKET_RESERVE = 0xc PACKET_RX_RING = 0x5 PACKET_STATISTICS = 0x6 PACKET_TIMESTAMP = 0x11 PACKET_TX_HAS_OFF = 0x13 PACKET_TX_RING = 0xd PACKET_TX_TIMESTAMP = 0x10 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 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_ENDIAN_BIG = 0x0 PR_ENDIAN_LITTLE = 0x1 PR_ENDIAN_PPC_LITTLE = 0x2 PR_FPEMU_NOPRINT = 0x1 PR_FPEMU_SIGFPE = 0x2 PR_FP_EXC_ASYNC = 0x2 PR_FP_EXC_DISABLED = 0x0 PR_FP_EXC_DIV = 0x10000 PR_FP_EXC_INV = 0x100000 PR_FP_EXC_NONRECOV = 0x1 PR_FP_EXC_OVF = 0x20000 PR_FP_EXC_PRECISE = 0x3 PR_FP_EXC_RES = 0x80000 PR_FP_EXC_SW_ENABLE = 0x80 PR_FP_EXC_UND = 0x40000 PR_GET_CHILD_SUBREAPER = 0x25 PR_GET_DUMPABLE = 0x3 PR_GET_ENDIAN = 0x13 PR_GET_FPEMU = 0x9 PR_GET_FPEXC = 0xb PR_GET_KEEPCAPS = 0x7 PR_GET_NAME = 0x10 PR_GET_NO_NEW_PRIVS = 0x27 PR_GET_PDEATHSIG = 0x2 PR_GET_SECCOMP = 0x15 PR_GET_SECUREBITS = 0x1b 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_SET_CHILD_SUBREAPER = 0x24 PR_SET_DUMPABLE = 0x4 PR_SET_ENDIAN = 0x14 PR_SET_FPEMU = 0xa PR_SET_FPEXC = 0xc 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_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_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 = 0x1000ff 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_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_NOFILE = 0x7 RLIMIT_STACK = 0x3 RLIM_INFINITY = -0x1 RTAX_ADVMSS = 0x8 RTAX_CWND = 0x7 RTAX_FEATURES = 0xc RTAX_FEATURE_ALLFRAG = 0x8 RTAX_FEATURE_ECN = 0x1 RTAX_FEATURE_SACK = 0x2 RTAX_FEATURE_TIMESTAMP = 0x4 RTAX_HOPLIMIT = 0xa RTAX_INITCWND = 0xb RTAX_INITRWND = 0xe RTAX_LOCK = 0x1 RTAX_MAX = 0xf 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 = 0x11 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_DELQDISC = 0x25 RTM_DELROUTE = 0x19 RTM_DELRULE = 0x21 RTM_DELTCLASS = 0x29 RTM_DELTFILTER = 0x2d RTM_F_CLONED = 0x200 RTM_F_EQUALIZE = 0x400 RTM_F_NOTIFY = 0x100 RTM_F_PREFIX = 0x800 RTM_GETACTION = 0x32 RTM_GETADDR = 0x16 RTM_GETADDRLABEL = 0x4a RTM_GETANYCAST = 0x3e RTM_GETDCB = 0x4e RTM_GETLINK = 0x12 RTM_GETMDB = 0x56 RTM_GETMULTICAST = 0x3a RTM_GETNEIGH = 0x1e RTM_GETNEIGHTBL = 0x42 RTM_GETNETCONF = 0x52 RTM_GETQDISC = 0x26 RTM_GETROUTE = 0x1a RTM_GETRULE = 0x22 RTM_GETTCLASS = 0x2a RTM_GETTFILTER = 0x2e RTM_MAX = 0x57 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_NEWPREFIX = 0x34 RTM_NEWQDISC = 0x24 RTM_NEWROUTE = 0x18 RTM_NEWRULE = 0x20 RTM_NEWTCLASS = 0x28 RTM_NEWTFILTER = 0x2c RTM_NR_FAMILIES = 0x12 RTM_NR_MSGTYPES = 0x48 RTM_SETDCB = 0x4f RTM_SETLINK = 0x13 RTM_SETNEIGHTBL = 0x43 RTNH_ALIGNTO = 0x4 RTNH_F_DEAD = 0x1 RTNH_F_ONLINK = 0x4 RTNH_F_PERVASIVE = 0x2 RTN_MAX = 0xb RTPROT_BIRD = 0xc RTPROT_BOOT = 0x3 RTPROT_DHCP = 0x10 RTPROT_DNROUTED = 0xd RTPROT_GATED = 0x8 RTPROT_KERNEL = 0x2 RTPROT_MROUTED = 0x11 RTPROT_MRT = 0xa RTPROT_NTK = 0xf RTPROT_RA = 0x9 RTPROT_REDIRECT = 0x1 RTPROT_STATIC = 0x4 RTPROT_UNSPEC = 0x0 RTPROT_XORP = 0xe RTPROT_ZEBRA = 0xb RT_CLASS_DEFAULT = 0xfd RT_CLASS_LOCAL = 0xff RT_CLASS_MAIN = 0xfe RT_CLASS_MAX = 0xff RT_CLASS_UNSPEC = 0x0 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 RUSAGE_THREAD = 0x1 SCM_CREDENTIALS = 0x2 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x1d SCM_TIMESTAMPING = 0x25 SCM_TIMESTAMPNS = 0x23 SCM_WIFI_STATUS = 0x29 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDDLCI = 0x8980 SIOCADDMULTI = 0x8931 SIOCADDRT = 0x890b SIOCATMARK = 0x8905 SIOCDARP = 0x8953 SIOCDELDLCI = 0x8981 SIOCDELMULTI = 0x8932 SIOCDELRT = 0x890c SIOCDEVPRIVATE = 0x89f0 SIOCDIFADDR = 0x8936 SIOCDRARP = 0x8960 SIOCGARP = 0x8954 SIOCGIFADDR = 0x8915 SIOCGIFBR = 0x8940 SIOCGIFBRDADDR = 0x8919 SIOCGIFCONF = 0x8912 SIOCGIFCOUNT = 0x8938 SIOCGIFDSTADDR = 0x8917 SIOCGIFENCAP = 0x8925 SIOCGIFFLAGS = 0x8913 SIOCGIFHWADDR = 0x8927 SIOCGIFINDEX = 0x8933 SIOCGIFMAP = 0x8970 SIOCGIFMEM = 0x891f SIOCGIFMETRIC = 0x891d SIOCGIFMTU = 0x8921 SIOCGIFNAME = 0x8910 SIOCGIFNETMASK = 0x891b SIOCGIFPFLAGS = 0x8935 SIOCGIFSLAVE = 0x8929 SIOCGIFTXQLEN = 0x8942 SIOCGPGRP = 0x8904 SIOCGRARP = 0x8961 SIOCGSTAMP = 0x8906 SIOCGSTAMPNS = 0x8907 SIOCPROTOPRIVATE = 0x89e0 SIOCRTMSG = 0x890d SIOCSARP = 0x8955 SIOCSIFADDR = 0x8916 SIOCSIFBR = 0x8941 SIOCSIFBRDADDR = 0x891a SIOCSIFDSTADDR = 0x8918 SIOCSIFENCAP = 0x8926 SIOCSIFFLAGS = 0x8914 SIOCSIFHWADDR = 0x8924 SIOCSIFHWBROADCAST = 0x8937 SIOCSIFLINK = 0x8911 SIOCSIFMAP = 0x8971 SIOCSIFMEM = 0x8920 SIOCSIFMETRIC = 0x891e SIOCSIFMTU = 0x8922 SIOCSIFNAME = 0x8923 SIOCSIFNETMASK = 0x891c SIOCSIFPFLAGS = 0x8934 SIOCSIFSLAVE = 0x8930 SIOCSIFTXQLEN = 0x8943 SIOCSPGRP = 0x8902 SIOCSRARP = 0x8962 SOCK_CLOEXEC = 0x80000 SOCK_DCCP = 0x6 SOCK_DGRAM = 0x2 SOCK_NONBLOCK = 0x800 SOCK_PACKET = 0xa SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_AAL = 0x109 SOL_ATM = 0x108 SOL_DECNET = 0x105 SOL_ICMPV6 = 0x3a SOL_IP = 0x0 SOL_IPV6 = 0x29 SOL_IRDA = 0x10a SOL_PACKET = 0x107 SOL_RAW = 0xff SOL_SOCKET = 0x1 SOL_TCP = 0x6 SOL_X25 = 0x106 SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x1e SO_ATTACH_FILTER = 0x1a SO_BINDTODEVICE = 0x19 SO_BROADCAST = 0x6 SO_BSDCOMPAT = 0xe SO_BUSY_POLL = 0x2e SO_DEBUG = 0x1 SO_DETACH_FILTER = 0x1b SO_DOMAIN = 0x27 SO_DONTROUTE = 0x5 SO_ERROR = 0x4 SO_GET_FILTER = 0x1a 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_WIFI_STATUS = 0x29 S_BLKSIZE = 0x200 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TAB0 = 0x0 TAB1 = 0x400 TAB2 = 0x800 TAB3 = 0xc00 TABDLY = 0xc00 TCFLSH = 0x2000741f TCGETA = 0x40147417 TCGETS = 0x402c7413 TCIFLUSH = 0x0 TCIOFF = 0x2 TCIOFLUSH = 0x2 TCION = 0x3 TCOFLUSH = 0x1 TCOOFF = 0x0 TCOON = 0x1 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_QUEUE_SEQ = 0x15 TCP_QUICKACK = 0xc TCP_REPAIR = 0x13 TCP_REPAIR_OPTIONS = 0x16 TCP_REPAIR_QUEUE = 0x14 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 TUNATTACHFILTER = 0x801054d5 TUNDETACHFILTER = 0x801054d6 TUNGETFEATURES = 0x400454cf TUNGETFILTER = 0x401054db TUNGETIFF = 0x400454d2 TUNGETSNDBUF = 0x400454d3 TUNGETVNETHDRSZ = 0x400454d7 TUNSETDEBUG = 0x800454c9 TUNSETGROUP = 0x800454ce TUNSETIFF = 0x800454ca TUNSETIFINDEX = 0x800454da TUNSETLINK = 0x800454cd TUNSETNOCSUM = 0x800454c8 TUNSETOFFLOAD = 0x800454d0 TUNSETOWNER = 0x800454cc TUNSETPERSIST = 0x800454cb TUNSETQUEUE = 0x800454d9 TUNSETSNDBUF = 0x800454d4 TUNSETTXFILTER = 0x800454d1 TUNSETVNETHDRSZ = 0x800454d8 VDISCARD = 0x10 VEOF = 0x4 VEOL = 0x6 VEOL2 = 0x8 VERASE = 0x2 VINTR = 0x0 VKILL = 0x3 VLNEXT = 0xf VMIN = 0x5 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_netbsd_386.go ================================================ // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_netbsd_amd64.go ================================================ // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_netbsd_arm.go ================================================ // 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 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_openbsd_386.go ================================================ // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_openbsd_amd64.go ================================================ // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zerrors_solaris_amd64.go ================================================ // mkerrors.sh -m64 // MACHINE GENERATED BY THE COMMAND ABOVE; 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 CFLUSH = 0xf 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 CREAD = 0x80 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 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_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_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 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 IXANY = 0x800 IXOFF = 0x1000 IXON = 0x400 MADV_ACCESS_DEFAULT = 0x6 MADV_ACCESS_LWP = 0x7 MADV_ACCESS_MANY = 0x8 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MAP_32BIT = 0x80 MAP_ALIGN = 0x200 MAP_ANON = 0x100 MAP_ANONYMOUS = 0x100 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 NOFLSH = 0x80 OCRNL = 0x8 OFDEL = 0x80 OFILL = 0x40 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 TCFLSH = 0x5407 TCGETA = 0x5401 TCGETS = 0x540d TCIFLUSH = 0x0 TCIOFLUSH = 0x2 TCOFLUSH = 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 ) // 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", } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_darwin_386.go ================================================ // mksyscall.pl -l32 syscall_bsd.go syscall_darwin.go syscall_darwin_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_darwin_amd64.go ================================================ // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_darwin_arm.go ================================================ // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_darwin_arm64.go ================================================ // mksyscall.pl syscall_bsd.go syscall_darwin.go syscall_darwin_arm64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm64,darwin 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) 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 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_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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_dragonfly_386.go ================================================ // mksyscall.pl -l32 -dragonfly syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,dragonfly 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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), 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 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), 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_dragonfly_amd64.go ================================================ // mksyscall.pl -dragonfly syscall_bsd.go syscall_dragonfly.go syscall_dragonfly_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,dragonfly 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_freebsd_386.go ================================================ // mksyscall.pl -l32 syscall_bsd.go syscall_freebsd.go syscall_freebsd_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,freebsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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 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), 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_freebsd_amd64.go ================================================ // mksyscall.pl syscall_bsd.go syscall_freebsd.go syscall_freebsd_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,freebsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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 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), 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_freebsd_arm.go ================================================ // mksyscall.pl -l32 -arm syscall_bsd.go syscall_freebsd.go syscall_freebsd_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,freebsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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))) 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 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) use(unsafe.Pointer(_p0)) 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 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_linux_386.go ================================================ // mksyscall.pl -l32 syscall_linux.go syscall_linux_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_linux_amd64.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func write(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func exitThread(code int) (err error) { _, _, e1 := Syscall(SYS_EXIT, uintptr(code), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func writelen(fd int, p *byte, np int) (n int, err error) { r0, _, e1 := Syscall(SYS_WRITE, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(np)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func munmap(addr uintptr, length uintptr) (err error) { _, _, e1 := Syscall(SYS_MUNMAP, uintptr(addr), uintptr(length), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Madvise(b []byte, advice int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MADVISE, uintptr(_p0), uintptr(len(b)), uintptr(advice)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mprotect(b []byte, prot int) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MPROTECT, uintptr(_p0), uintptr(len(b)), uintptr(prot)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlock(b []byte) (err error) { var _p0 unsafe.Pointer if len(b) > 0 { _p0 = unsafe.Pointer(&b[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_MUNLOCK, uintptr(_p0), uintptr(len(b)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mlockall(flags int) (err error) { _, _, e1 := Syscall(SYS_MLOCKALL, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Munlockall() (err error) { _, _, e1 := Syscall(SYS_MUNLOCKALL, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup2(oldfd int, newfd int) (err error) { _, _, e1 := Syscall(SYS_DUP2, uintptr(oldfd), uintptr(newfd), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_linux_arm.go ================================================ // mksyscall.pl -l32 -arm syscall_linux.go syscall_linux_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(off>>32), uintptr(len), uintptr(len>>32)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchdir(fd int) (err error) { _, _, e1 := Syscall(SYS_FCHDIR, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmod(fd int, mode uint32) (err error) { _, _, e1 := Syscall(SYS_FCHMOD, uintptr(fd), uintptr(mode), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHMODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, r1, e1 := Syscall6(SYS_TEE, uintptr(rfd), uintptr(wfd), uintptr(len), uintptr(flags), 0, 0) n = int64(int64(r1)<<32 | int64(r0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tgkill(tgid int, tid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_TGKILL, uintptr(tgid), uintptr(tid), uintptr(sig)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Times(tms *Tms) (ticks uintptr, err error) { r0, _, e1 := RawSyscall(SYS_TIMES, uintptr(unsafe.Pointer(tms)), 0, 0) ticks = uintptr(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Umask(mask int) (oldmask int) { r0, _, _ := RawSyscall(SYS_UMASK, uintptr(mask), 0, 0) oldmask = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Uname(buf *Utsname) (err error) { _, _, e1 := RawSyscall(SYS_UNAME, uintptr(unsafe.Pointer(buf)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unmount(target string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(target) if err != nil { return } _, _, e1 := Syscall(SYS_UMOUNT2, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Lstat(path string, stat *Stat_t) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_LSTAT64, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(stat)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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_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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_linux_arm64.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_arm64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm64,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_ppc64x.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_linux_ppc64le.go ================================================ // mksyscall.pl syscall_linux.go syscall_linux_ppc64x.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build ppc64le,linux package unix import ( "syscall" "unsafe" ) var _ syscall.Errno // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func linkat(olddirfd int, oldpath string, newdirfd int, newpath string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_LINKAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func openat(dirfd int, path string, flags int, mode uint32) (fd int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } r0, _, e1 := Syscall6(SYS_OPENAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags), uintptr(mode), 0, 0) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func readlinkat(dirfd int, path string, buf []byte) (n int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(buf) > 0 { _p1 = unsafe.Pointer(&buf[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_READLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(buf)), 0, 0) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func symlinkat(oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall(SYS_SYMLINKAT, uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1))) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func unlinkat(dirfd int, path string, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UNLINKAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(flags)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimes(path string, times *[2]Timeval) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIMES, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func utimensat(dirfd int, path string, times *[2]Timespec, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func futimesat(dirfd int, path *byte, times *[2]Timeval) (err error) { _, _, e1 := Syscall(SYS_FUTIMESAT, uintptr(dirfd), uintptr(unsafe.Pointer(path)), uintptr(unsafe.Pointer(times))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getcwd(buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETCWD, uintptr(_p0), uintptr(len(buf)), 0) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, err error) { r0, _, e1 := Syscall6(SYS_WAIT4, uintptr(pid), uintptr(unsafe.Pointer(wstatus)), uintptr(options), uintptr(unsafe.Pointer(rusage)), 0, 0) wpid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ptrace(request int, pid int, addr uintptr, data uintptr) (err error) { _, _, e1 := Syscall6(SYS_PTRACE, uintptr(request), uintptr(pid), uintptr(addr), uintptr(data), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func reboot(magic1 uint, magic2 uint, cmd int, arg string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(arg) if err != nil { return } _, _, e1 := Syscall6(SYS_REBOOT, uintptr(magic1), uintptr(magic2), uintptr(cmd), uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func mount(source string, target string, fstype string, flags uintptr, data *byte) (err error) { var _p0 *byte _p0, err = BytePtrFromString(source) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(target) if err != nil { return } var _p2 *byte _p2, err = BytePtrFromString(fstype) if err != nil { return } _, _, e1 := Syscall6(SYS_MOUNT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(unsafe.Pointer(_p2)), uintptr(flags), uintptr(unsafe.Pointer(data)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) use(unsafe.Pointer(_p2)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Acct(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_ACCT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Adjtimex(buf *Timex) (state int, err error) { r0, _, e1 := Syscall(SYS_ADJTIMEX, uintptr(unsafe.Pointer(buf)), 0, 0) state = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chdir(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHDIR, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func ClockGettime(clockid int32, time *Timespec) (err error) { _, _, e1 := Syscall(SYS_CLOCK_GETTIME, uintptr(clockid), uintptr(unsafe.Pointer(time)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Close(fd int) (err error) { _, _, e1 := Syscall(SYS_CLOSE, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup(oldfd int) (fd int, err error) { r0, _, e1 := Syscall(SYS_DUP, uintptr(oldfd), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Dup3(oldfd int, newfd int, flags int) (err error) { _, _, e1 := Syscall(SYS_DUP3, uintptr(oldfd), uintptr(newfd), uintptr(flags)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate(size int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE, uintptr(size), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCreate1(flag int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_EPOLL_CREATE1, uintptr(flag), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error) { _, _, e1 := RawSyscall6(SYS_EPOLL_CTL, uintptr(epfd), uintptr(op), uintptr(fd), uintptr(unsafe.Pointer(event)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 Exit(code int) { Syscall(SYS_EXIT_GROUP, uintptr(code), 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Faccessat(dirfd int, path string, mode uint32, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FACCESSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(flags), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fallocate(fd int, mode uint32, off int64, len int64) (err error) { _, _, e1 := Syscall6(SYS_FALLOCATE, uintptr(fd), uintptr(mode), uintptr(off), uintptr(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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_FCHOWNAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(uid), uintptr(gid), uintptr(flags), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func fcntl(fd int, cmd int, arg int) (val int, err error) { r0, _, e1 := Syscall(SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg)) val = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fdatasync(fd int) (err error) { _, _, e1 := Syscall(SYS_FDATASYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Flock(fd int, how int) (err error) { _, _, e1 := Syscall(SYS_FLOCK, uintptr(fd), uintptr(how), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Fsync(fd int) (err error) { _, _, e1 := Syscall(SYS_FSYNC, uintptr(fd), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getdents(fd int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_GETDENTS64, uintptr(fd), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpgid(pid int) (pgid int, err error) { r0, _, e1 := RawSyscall(SYS_GETPGID, uintptr(pid), 0, 0) pgid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpid() (pid int) { r0, _, _ := RawSyscall(SYS_GETPID, 0, 0, 0) pid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getppid() (ppid int) { r0, _, _ := RawSyscall(SYS_GETPPID, 0, 0, 0) ppid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getpriority(which int, who int) (prio int, err error) { r0, _, e1 := Syscall(SYS_GETPRIORITY, uintptr(which), uintptr(who), 0) prio = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getrusage(who int, rusage *Rusage) (err error) { _, _, e1 := RawSyscall(SYS_GETRUSAGE, uintptr(who), uintptr(unsafe.Pointer(rusage)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Gettid() (tid int) { r0, _, _ := RawSyscall(SYS_GETTID, 0, 0, 0) tid = int(r0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Getxattr(path string, attr string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(dest) > 0 { _p2 = unsafe.Pointer(&dest[0]) } else { _p2 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(dest)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error) { var _p0 *byte _p0, err = BytePtrFromString(pathname) if err != nil { return } r0, _, e1 := Syscall(SYS_INOTIFY_ADD_WATCH, uintptr(fd), uintptr(unsafe.Pointer(_p0)), uintptr(mask)) use(unsafe.Pointer(_p0)) watchdesc = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyInit1(flags int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_INIT1, uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error) { r0, _, e1 := RawSyscall(SYS_INOTIFY_RM_WATCH, uintptr(fd), uintptr(watchdesc), 0) success = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Kill(pid int, sig syscall.Signal) (err error) { _, _, e1 := RawSyscall(SYS_KILL, uintptr(pid), uintptr(sig), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Klogctl(typ int, buf []byte) (n int, err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_SYSLOG, uintptr(typ), uintptr(_p0), uintptr(len(buf))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listxattr(path string, dest []byte) (sz int, err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 unsafe.Pointer if len(dest) > 0 { _p1 = unsafe.Pointer(&dest[0]) } else { _p1 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_LISTXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(_p1), uintptr(len(dest))) use(unsafe.Pointer(_p0)) sz = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mkdirat(dirfd int, path string, mode uint32) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_MKDIRAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall6(SYS_MKNODAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(mode), uintptr(dev), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Nanosleep(time *Timespec, leftover *Timespec) (err error) { _, _, e1 := Syscall(SYS_NANOSLEEP, uintptr(unsafe.Pointer(time)), uintptr(unsafe.Pointer(leftover)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 PivotRoot(newroot string, putold string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(newroot) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(putold) if err != nil { return } _, _, e1 := Syscall(SYS_PIVOT_ROOT, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func prlimit(pid int, resource int, old *Rlimit, newlimit *Rlimit) (err error) { _, _, e1 := RawSyscall6(SYS_PRLIMIT64, uintptr(pid), uintptr(resource), uintptr(unsafe.Pointer(old)), uintptr(unsafe.Pointer(newlimit)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (err error) { _, _, e1 := Syscall6(SYS_PRCTL, uintptr(option), uintptr(arg2), uintptr(arg3), uintptr(arg4), uintptr(arg5), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func read(fd int, p []byte) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall(SYS_READ, uintptr(fd), uintptr(_p0), uintptr(len(p))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Removexattr(path string, attr string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } _, _, e1 := Syscall(SYS_REMOVEXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(oldpath) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(newpath) if err != nil { return } _, _, e1 := Syscall6(SYS_RENAMEAT, uintptr(olddirfd), uintptr(unsafe.Pointer(_p0)), uintptr(newdirfd), uintptr(unsafe.Pointer(_p1)), 0, 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setdomainname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETDOMAINNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sethostname(p []byte) (err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall(SYS_SETHOSTNAME, uintptr(_p0), uintptr(len(p)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpgid(pid int, pgid int) (err error) { _, _, e1 := RawSyscall(SYS_SETPGID, uintptr(pid), uintptr(pgid), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setsid() (pid int, err error) { r0, _, e1 := RawSyscall(SYS_SETSID, 0, 0, 0) pid = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Settimeofday(tv *Timeval) (err error) { _, _, e1 := RawSyscall(SYS_SETTIMEOFDAY, uintptr(unsafe.Pointer(tv)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setpriority(which int, who int, prio int) (err error) { _, _, e1 := Syscall(SYS_SETPRIORITY, uintptr(which), uintptr(who), uintptr(prio)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Setxattr(path string, attr string, data []byte, flags int) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } var _p1 *byte _p1, err = BytePtrFromString(attr) if err != nil { return } var _p2 unsafe.Pointer if len(data) > 0 { _p2 = unsafe.Pointer(&data[0]) } else { _p2 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_p1)), uintptr(_p2), uintptr(len(data)), uintptr(flags), 0) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() { Syscall(SYS_SYNC, 0, 0, 0) return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sysinfo(info *Sysinfo_t) (err error) { _, _, e1 := RawSyscall(SYS_SYSINFO, uintptr(unsafe.Pointer(info)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Tee(rfd int, wfd int, len int, flags int) (n int64, err error) { r0, _, 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Unshare(flags int) (err error) { _, _, e1 := Syscall(SYS_UNSHARE, uintptr(flags), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Ustat(dev int, ubuf *Ustat_t) (err error) { _, _, e1 := Syscall(SYS_USTAT, uintptr(dev), uintptr(unsafe.Pointer(ubuf)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Utime(path string, buf *Utimbuf) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_UTIME, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(buf)), 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Listen(s int, n int) (err error) { _, _, e1 := Syscall(SYS_LISTEN, uintptr(s), uintptr(n), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) { r0, _, e1 := Syscall(SYS_ACCEPT, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) { r0, _, e1 := Syscall6(SYS_ACCEPT4, uintptr(s), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen)), uintptr(flags), 0, 0) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := Syscall(SYS_CONNECT, uintptr(s), uintptr(addr), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getgroups(n int, list *_Gid_t) (nn int, err error) { r0, _, e1 := RawSyscall(SYS_GETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) nn = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setgroups(n int, list *_Gid_t) (err error) { _, _, e1 := RawSyscall(SYS_SETGROUPS, uintptr(n), uintptr(unsafe.Pointer(list)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) { _, _, e1 := Syscall6(SYS_GETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(unsafe.Pointer(vallen)), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) { _, _, e1 := Syscall6(SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socket(domain int, typ int, proto int) (fd int, err error) { r0, _, e1 := RawSyscall(SYS_SOCKET, uintptr(domain), uintptr(typ), uintptr(proto)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) { _, _, e1 := RawSyscall6(SYS_SOCKETPAIR, uintptr(domain), uintptr(typ), uintptr(proto), uintptr(unsafe.Pointer(fd)), 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETPEERNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) { _, _, e1 := RawSyscall(SYS_GETSOCKNAME, uintptr(fd), uintptr(unsafe.Pointer(rsa)), uintptr(unsafe.Pointer(addrlen))) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) { var _p0 unsafe.Pointer if len(p) > 0 { _p0 = unsafe.Pointer(&p[0]) } else { _p0 = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(SYS_RECVFROM, uintptr(fd), uintptr(_p0), uintptr(len(p)), uintptr(flags), uintptr(unsafe.Pointer(from)), uintptr(unsafe.Pointer(fromlen))) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) { var _p0 unsafe.Pointer if len(buf) > 0 { _p0 = unsafe.Pointer(&buf[0]) } else { _p0 = unsafe.Pointer(&_zero) } _, _, e1 := Syscall6(SYS_SENDTO, uintptr(s), uintptr(_p0), uintptr(len(buf)), uintptr(flags), uintptr(to), uintptr(addrlen)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func recvmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_RECVMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func sendmsg(s int, msg *Msghdr, flags int) (n int, err error) { r0, _, e1 := Syscall(SYS_SENDMSG, uintptr(s), uintptr(unsafe.Pointer(msg)), uintptr(flags)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_netbsd_386.go ================================================ // mksyscall.pl -l32 -netbsd syscall_bsd.go syscall_netbsd.go syscall_netbsd_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,netbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_netbsd_amd64.go ================================================ // mksyscall.pl -netbsd syscall_bsd.go syscall_netbsd.go syscall_netbsd_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,netbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_netbsd_arm.go ================================================ // mksyscall.pl -l32 -arm syscall_bsd.go syscall_netbsd.go syscall_netbsd_arm.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build arm,netbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_openbsd_386.go ================================================ // mksyscall.pl -l32 -openbsd syscall_bsd.go syscall_openbsd.go syscall_openbsd_386.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build 386,openbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_openbsd_amd64.go ================================================ // mksyscall.pl -openbsd syscall_bsd.go syscall_openbsd.go syscall_openbsd_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,openbsd 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Chroot(path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := Syscall(SYS_CHROOT, uintptr(unsafe.Pointer(_p0)), 0, 0) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 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 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)) use(unsafe.Pointer(_p0)) fd = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) 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))) use(unsafe.Pointer(_p0)) n = int(r0) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) 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 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func Sync() (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)) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = errnoErr(e1) } return } // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT func 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsyscall_solaris_amd64.go ================================================ // mksyscall_solaris.pl syscall_solaris.go syscall_solaris_amd64.go // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // +build amd64,solaris package unix import ( "syscall" "unsafe" ) //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_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_recvmsg recvmsg "libsocket.so" //go:cgo_import_dynamic libc_sendmsg 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_fpathconf fpathconf "libc.so" //go:cgo_import_dynamic libc_fstat fstat "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_listen listen "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_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_bind bind "libsocket.so" //go:cgo_import_dynamic libc_connect 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_sendto sendto "libsocket.so" //go:cgo_import_dynamic libc_socket socket "libsocket.so" //go:cgo_import_dynamic libc_socketpair socketpair "libsocket.so" //go:cgo_import_dynamic libc_write write "libc.so" //go:cgo_import_dynamic libc_getsockopt 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 procgetsockname libc_getsockname //go:linkname procGetcwd libc_getcwd //go:linkname procgetgroups libc_getgroups //go:linkname procsetgroups libc_setgroups //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 procrecvmsg libc_recvmsg //go:linkname procsendmsg libc_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 procFpathconf libc_fpathconf //go:linkname procFstat libc_fstat //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 proclisten libc_listen //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 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 procbind libc_bind //go:linkname procconnect libc_connect //go:linkname procmmap libc_mmap //go:linkname procmunmap libc_munmap //go:linkname procsendto libc_sendto //go:linkname procsocket libc_socket //go:linkname procsocketpair libc_socketpair //go:linkname procwrite libc_write //go:linkname procgetsockopt libc_getsockopt //go:linkname procgetpeername libc_getpeername //go:linkname procsetsockopt libc_setsockopt //go:linkname procrecvfrom libc_recvfrom //go:linkname procsysconf libc_sysconf var ( procgetsockname, procGetcwd, procgetgroups, procsetgroups, procutimes, procutimensat, procfcntl, procfutimesat, procaccept, procrecvmsg, procsendmsg, procacct, procioctl, procAccess, procAdjtime, procChdir, procChmod, procChown, procChroot, procClose, procCreat, procDup, procDup2, procExit, procFchdir, procFchmod, procFchmodat, procFchown, procFchownat, procFdatasync, procFpathconf, procFstat, procGetdents, procGetgid, procGetpid, procGetpgid, procGetpgrp, procGeteuid, procGetegid, procGetppid, procGetpriority, procGetrlimit, procGetrusage, procGettimeofday, procGetuid, procKill, procLchown, procLink, proclisten, 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, procSymlink, procSync, procTimes, procTruncate, procFsync, procFtruncate, procUmask, procUname, procumount, procUnlink, procUnlinkat, procUstat, procUtime, procbind, procconnect, procmmap, procmunmap, procsendto, procsocket, procsocketpair, procwrite, procgetsockopt, procgetpeername, procsetsockopt, procrecvfrom, procsysconf syscallFunc ) 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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(&procrecvmsg)), 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(&procsendmsg)), 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 int, 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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 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 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) if e1 != 0 { err = e1 } return } func Listen(s int, backlog int) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&proclisten)), 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) use(unsafe.Pointer(_p1)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = e1 } return } func Unlinkat(dirfd int, path string) (err error) { var _p0 *byte _p0, err = BytePtrFromString(path) if err != nil { return } _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procUnlinkat)), 2, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), 0, 0, 0, 0) use(unsafe.Pointer(_p0)) 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) use(unsafe.Pointer(_p0)) if e1 != 0 { err = e1 } return } func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) { _, _, e1 := sysvicall6(uintptr(unsafe.Pointer(&procbind)), 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(&procconnect)), 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(&procsendto)), 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(&procsocket)), 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(&procsocketpair)), 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(&procgetsockopt)), 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/zsysctl_openbsd.go ================================================ // 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}}, } ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_darwin_386.go ================================================ // 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_darwin_amd64.go ================================================ // 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_darwin_arm.go ================================================ // mksysnum_darwin.pl /usr/include/sys/syscall.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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_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_ATSOCKET = 206 SYS_ATGETMSG = 207 SYS_ATPUTMSG = 208 SYS_ATPSNDREQ = 209 SYS_ATPSNDRSP = 210 SYS_ATPGETREQ = 211 SYS_ATPGETRSP = 212 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_SEM_GETVALUE = 274 SYS_SEM_INIT = 275 SYS_SEM_DESTROY = 276 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_MAXSYSCALL = 440 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_darwin_arm64.go ================================================ // mksysnum_darwin.pl /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.4.sdk/usr/include/sys/syscall.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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_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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_dragonfly_386.go ================================================ // mksysnum_dragonfly.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build 386,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(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, 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(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, 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, 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_SCTP_PEELOFF = 364 // { int sctp_peeloff(int sd, caddr_t name ); } 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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_dragonfly_amd64.go ================================================ // mksysnum_dragonfly.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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(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, 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(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, 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, 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_SCTP_PEELOFF = 364 // { int sctp_peeloff(int sd, caddr_t name ); } 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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_freebsd_386.go ================================================ // mksysnum_freebsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ 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_NEW = 514 // { int cap_new(int fd, uint64_t rights); } SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ 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_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, \ ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_freebsd_amd64.go ================================================ // mksysnum_freebsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ 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_NEW = 514 // { int cap_new(int fd, uint64_t rights); } SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ 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_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, \ ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_freebsd_arm.go ================================================ // mksysnum_freebsd.pl // MACHINE GENERATED BY THE ABOVE COMMAND; 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_SCTP_PEELOFF = 471 // { int sctp_peeloff(int sd, uint32_t name); } SYS_SCTP_GENERIC_SENDMSG = 472 // { int sctp_generic_sendmsg(int sd, caddr_t msg, int mlen, \ SYS_SCTP_GENERIC_SENDMSG_IOV = 473 // { int sctp_generic_sendmsg_iov(int sd, struct iovec *iov, int iovlen, \ SYS_SCTP_GENERIC_RECVMSG = 474 // { int sctp_generic_recvmsg(int sd, struct iovec *iov, int iovlen, \ 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_NEW = 514 // { int cap_new(int fd, uint64_t rights); } SYS_CAP_GETRIGHTS = 515 // { int cap_getrights(int fd, \ 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_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, \ ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_linux_386.go ================================================ // mksysnum_linux.pl /usr/include/asm/unistd_32.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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_MADVISE1 = 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_linux_amd64.go ================================================ // mksysnum_linux.pl /usr/include/asm/unistd_64.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_linux_arm.go ================================================ // mksysnum_linux.pl // MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT // +build arm,linux package unix const ( SYS_OABI_SYSCALL_BASE = 0 SYS_SYSCALL_BASE = 0 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_TIME = 13 SYS_MKNOD = 14 SYS_CHMOD = 15 SYS_LCHOWN = 16 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_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_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_GETRLIMIT = 76 SYS_GETRUSAGE = 77 SYS_GETTIMEOFDAY = 78 SYS_SETTIMEOFDAY = 79 SYS_GETGROUPS = 80 SYS_SETGROUPS = 81 SYS_SELECT = 82 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_FCHOWN = 95 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_VHANGUP = 111 SYS_SYSCALL = 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_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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_linux_arm64.go ================================================ // mksysnum_linux.pl /usr/include/asm-generic/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64.go ================================================ // mksysnum_linux.pl /usr/include/asm/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_linux_ppc64le.go ================================================ // mksysnum_linux.pl /usr/include/powerpc64le-linux-gnu/asm/unistd.h // MACHINE GENERATED BY THE ABOVE COMMAND; 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_netbsd_386.go ================================================ // 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___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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_netbsd_amd64.go ================================================ // 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___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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_netbsd_arm.go ================================================ // 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___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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_openbsd_386.go ================================================ // 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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_openbsd_amd64.go ================================================ // 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); } ) ================================================ FILE: vendor/golang.org/x/sys/unix/zsysnum_solaris_amd64.go ================================================ // 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 ) ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_darwin_386.go ================================================ // +build 386,darwin // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_darwin.go 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_darwin_amd64.go ================================================ // +build amd64,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 } const ( AT_FDCWD = -0x2 AT_SYMLINK_NOFOLLOW = 0x20 ) ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_darwin_arm.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_darwin_arm64.go ================================================ // +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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_dragonfly_386.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_dragonfly.go // +build 386,dragonfly 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 { 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 int32 Bsize int32 Iosize int32 Blocks int32 Bfree int32 Bavail int32 Files int32 Ffree int32 Fsid Fsid Owner uint32 Type int32 Flags int32 Syncwrites int32 Asyncwrites int32 Fstypename [16]int8 Mntonname [80]int8 Syncreads int32 Asyncreads int32 Spares1 int16 Mntfromname [80]int8 Spares2 int16 Spare [2]int32 } 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 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 = 0x36 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 int32 Udata *byte } type FdSet struct { Bits [32]uint32 } const ( SizeofIfMsghdr = 0x68 SizeofIfData = 0x58 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 IfData struct { Type uint8 Physical uint8 Addrlen uint8 Hdrlen uint8 Recvquota uint8 Xmitquota uint8 Pad_cgo_0 [2]byte Mtu uint32 Metric uint32 Link_state uint32 Baudrate uint64 Ipackets uint32 Ierrors uint32 Opackets uint32 Oerrors uint32 Collisions uint32 Ibytes uint32 Obytes uint32 Imcasts uint32 Omcasts uint32 Iqdrops uint32 Noproto uint32 Hwassist uint32 Unused uint32 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 uint32 Rmx RtMetrics } type RtMetrics struct { Locks uint32 Mtu uint32 Pksent uint32 Expire uint32 Sendpipe uint32 Ssthresh uint32 Rtt uint32 Rttvar uint32 Recvpipe uint32 Hopcount uint32 Mssopt uint16 Pad uint16 Msl uint32 Iwmaxsegs uint32 Iwcapsegs 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_dragonfly_amd64.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_dragonfly.go // +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 Unused 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_freebsd_386.go ================================================ // +build 386,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.go 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 uint32 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 = 0x64 SizeofIfMsghdr = 0x60 sizeofIfData = 0x54 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 Baudrate_pf 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 uint64 Epoch int32 Lastchange Timeval } 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_freebsd_amd64.go ================================================ // +build amd64,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.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 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 uint32 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 Baudrate_pf 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 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_freebsd_arm.go ================================================ // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -fsigned-char types_freebsd.go // +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 uint32 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 } 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 = 0x70 SizeofIfMsghdr = 0x70 sizeofIfData = 0x60 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 Baudrate_pf 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 uint64 Epoch int64 Lastchange Timeval } 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_linux_386.go ================================================ // +build 386,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev 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 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 RawSockaddr struct { Family uint16 Data [14]int8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [96]int8 } type _Socklen uint32 type Linger struct { Onoff int32 Linger int32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPMreqn struct { Multiaddr [4]byte /* in_addr */ Address [4]byte /* in_addr */ Ifindex int32 } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen uint32 Control *byte Controllen uint32 Flags int32 } type Cmsghdr struct { Len uint32 Level int32 Type int32 X__cmsg_data [0]uint8 } 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 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x1d RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 Name [0]int8 } 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_SYMLINK_NOFOLLOW = 0x100 AT_REMOVEDIR = 0x200 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_linux_amd64.go ================================================ // +build amd64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.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 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 X__unused [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 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x1d RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 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 Name [0]int8 } 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_SYMLINK_NOFOLLOW = 0x100 AT_REMOVEDIR = 0x200 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_linux_arm.go ================================================ // +build arm,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.go package unix const ( sizeofPtr = 0x4 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x4 sizeofLongLong = 0x8 PathMax = 0x1000 ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Tai int32 Pad_cgo_0 [44]byte } type Time_t int32 type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 } type Utimbuf struct { Actime int32 Modtime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type _Gid_t uint32 type Stat_t struct { Dev 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 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 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 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 X__cmsg_data [0]uint8 } 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 SizeofLinger = 0x8 SizeofIPMreq = 0x8 SizeofIPMreqn = 0xc SizeofIPv6Mreq = 0x14 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofInet4Pktinfo = 0xc SizeofInet6Pktinfo = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofICMPv6Filter = 0x20 SizeofUcred = 0xc SizeofTCPInfo = 0x68 ) const ( IFA_UNSPEC = 0x0 IFA_ADDRESS = 0x1 IFA_LOCAL = 0x2 IFA_LABEL = 0x3 IFA_BROADCAST = 0x4 IFA_ANYCAST = 0x5 IFA_CACHEINFO = 0x6 IFA_MULTICAST = 0x7 IFLA_UNSPEC = 0x0 IFLA_ADDRESS = 0x1 IFLA_BROADCAST = 0x2 IFLA_IFNAME = 0x3 IFLA_MTU = 0x4 IFLA_LINK = 0x5 IFLA_QDISC = 0x6 IFLA_STATS = 0x7 IFLA_COST = 0x8 IFLA_PRIORITY = 0x9 IFLA_MASTER = 0xa IFLA_WIRELESS = 0xb IFLA_PROTINFO = 0xc IFLA_TXQLEN = 0xd IFLA_MAP = 0xe IFLA_WEIGHT = 0xf IFLA_OPERSTATE = 0x10 IFLA_LINKMODE = 0x11 IFLA_LINKINFO = 0x12 IFLA_NET_NS_PID = 0x13 IFLA_IFALIAS = 0x14 IFLA_MAX = 0x1d RT_SCOPE_UNIVERSE = 0x0 RT_SCOPE_SITE = 0xc8 RT_SCOPE_LINK = 0xfd RT_SCOPE_HOST = 0xfe RT_SCOPE_NOWHERE = 0xff RT_TABLE_UNSPEC = 0x0 RT_TABLE_COMPAT = 0xfc RT_TABLE_DEFAULT = 0xfd RT_TABLE_MAIN = 0xfe RT_TABLE_LOCAL = 0xff RT_TABLE_MAX = 0xffffffff RTA_UNSPEC = 0x0 RTA_DST = 0x1 RTA_SRC = 0x2 RTA_IIF = 0x3 RTA_OIF = 0x4 RTA_GATEWAY = 0x5 RTA_PRIORITY = 0x6 RTA_PREFSRC = 0x7 RTA_METRICS = 0x8 RTA_MULTIPATH = 0x9 RTA_FLOW = 0xb RTA_CACHEINFO = 0xc RTA_TABLE = 0xf RTN_UNSPEC = 0x0 RTN_UNICAST = 0x1 RTN_LOCAL = 0x2 RTN_BROADCAST = 0x3 RTN_ANYCAST = 0x4 RTN_MULTICAST = 0x5 RTN_BLACKHOLE = 0x6 RTN_UNREACHABLE = 0x7 RTN_PROHIBIT = 0x8 RTN_THROW = 0x9 RTN_NAT = 0xa RTN_XRESOLVE = 0xb RTNLGRP_NONE = 0x0 RTNLGRP_LINK = 0x1 RTNLGRP_NOTIFY = 0x2 RTNLGRP_NEIGH = 0x3 RTNLGRP_TC = 0x4 RTNLGRP_IPV4_IFADDR = 0x5 RTNLGRP_IPV4_MROUTE = 0x6 RTNLGRP_IPV4_ROUTE = 0x7 RTNLGRP_IPV4_RULE = 0x8 RTNLGRP_IPV6_IFADDR = 0x9 RTNLGRP_IPV6_MROUTE = 0xa RTNLGRP_IPV6_ROUTE = 0xb RTNLGRP_IPV6_IFINFO = 0xc RTNLGRP_IPV6_PREFIX = 0x12 RTNLGRP_IPV6_RULE = 0x13 RTNLGRP_ND_USEROPT = 0x14 SizeofNlMsghdr = 0x10 SizeofNlMsgerr = 0x14 SizeofRtGenmsg = 0x1 SizeofNlAttr = 0x4 SizeofRtAttr = 0x4 SizeofIfInfomsg = 0x10 SizeofIfAddrmsg = 0x8 SizeofRtMsg = 0xc SizeofRtNexthop = 0x8 ) type NlMsghdr struct { Len uint32 Type uint16 Flags uint16 Seq uint32 Pid uint32 } type NlMsgerr struct { Error int32 Msg NlMsghdr } type RtGenmsg struct { Family uint8 } type NlAttr struct { Len uint16 Type uint16 } type RtAttr struct { Len uint16 Type uint16 } type IfInfomsg struct { Family uint8 X__ifi_pad uint8 Type uint16 Index int32 Flags uint32 Change uint32 } type IfAddrmsg struct { Family uint8 Prefixlen uint8 Flags uint8 Scope uint8 Index uint32 } type RtMsg struct { Family uint8 Dst_len uint8 Src_len uint8 Tos uint8 Table uint8 Protocol uint8 Scope uint8 Type uint8 Flags uint32 } type RtNexthop struct { Len uint16 Flags uint8 Hops uint8 Ifindex int32 } const ( SizeofSockFilter = 0x8 SizeofSockFprog = 0x8 ) type SockFilter struct { Code uint16 Jt uint8 Jf uint8 K uint32 } type SockFprog struct { Len uint16 Pad_cgo_0 [2]byte Filter *SockFilter } type InotifyEvent struct { Wd int32 Mask uint32 Cookie uint32 Len uint32 Name [0]uint8 } 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_SYMLINK_NOFOLLOW = 0x100 AT_REMOVEDIR = 0x200 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_linux_arm64.go ================================================ // +build arm64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- -fsigned-char types_linux.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 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 X__glibc_reserved [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 } 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x22 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 Name [0]int8 } 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 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_NOFOLLOW = 0x100 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Line uint8 Cc [19]uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_linux_ppc64.go ================================================ // +build ppc64,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.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 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 X__glibc_reserved4 uint64 X__glibc_reserved5 uint64 X__glibc_reserved6 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 } 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 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x23 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 Name [0]uint8 } 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 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_NOFOLLOW = 0x100 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Line uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_linux_ppc64le.go ================================================ // +build ppc64le,linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_linux.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 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 X__glibc_reserved4 uint64 X__glibc_reserved5 uint64 X__glibc_reserved6 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 } 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 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 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 X__cmsg_data [0]uint8 } 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 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 = 0x22 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 Name [0]uint8 } 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 Fd int32 Pad int32 } const ( AT_FDCWD = -0x64 AT_REMOVEDIR = 0x200 AT_SYMLINK_NOFOLLOW = 0x100 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [19]uint8 Line uint8 Ispeed uint32 Ospeed uint32 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_netbsd_386.go ================================================ // 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 } 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_netbsd_amd64.go ================================================ // 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 } 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_netbsd_arm.go ================================================ // 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 } 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_openbsd_386.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_openbsd_amd64.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/unix/ztypes_solaris_amd64.go ================================================ // +build amd64,solaris // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_solaris.go package unix const ( sizeofPtr = 0x8 sizeofShort = 0x2 sizeofInt = 0x4 sizeofLong = 0x8 sizeofLongLong = 0x8 PathMax = 0x400 ) 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 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/asm.s ================================================ // 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. #include "textflag.h" TEXT ·use(SB),NOSPLIT,$0 RET ================================================ FILE: vendor/golang.org/x/sys/windows/asm_windows_386.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/windows/asm_windows_amd64.s ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/windows/dll_windows.go ================================================ // 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. 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 } // 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)) + ".") } return } // 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 { mu sync.Mutex dll *DLL // non nil once DLL is loaded Name string } // 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 { d.mu.Lock() defer d.mu.Unlock() if d.dll == nil { dll, e := LoadDLL(d.Name) if e != nil { return e } // 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} } // A LazyProc implements access to a procedure inside a LazyDLL. // It delays the lookup until the Addr method is called. type LazyProc struct { mu sync.Mutex Name string 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() } // 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...) } ================================================ FILE: vendor/golang.org/x/sys/windows/env_unset.go ================================================ // 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 windows import "syscall" func Unsetenv(key string) error { // This was added in Go 1.4. return syscall.Unsetenv(key) } ================================================ FILE: vendor/golang.org/x/sys/windows/env_windows.go ================================================ // 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() } ================================================ FILE: vendor/golang.org/x/sys/windows/eventlog.go ================================================ // 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 ================================================ FILE: vendor/golang.org/x/sys/windows/exec_windows.go ================================================ // 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 } } } ================================================ FILE: vendor/golang.org/x/sys/windows/race.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/windows/race0.go ================================================ // 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) { } ================================================ FILE: vendor/golang.org/x/sys/windows/registry/export_test.go ================================================ // 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 func (k Key) SetValue(name string, valtype uint32, data []byte) error { return k.setValue(name, valtype, data) } ================================================ FILE: vendor/golang.org/x/sys/windows/registry/key.go ================================================ // 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) ) // 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 } // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/registry/registry_test.go ================================================ // 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_test import ( "bytes" "crypto/rand" "os" "syscall" "testing" "time" "unsafe" "golang.org/x/sys/windows/registry" ) func randKeyName(prefix string) string { const numbers = "0123456789" buf := make([]byte, 10) rand.Read(buf) for i, b := range buf { buf[i] = numbers[b%byte(len(numbers))] } return prefix + string(buf) } func TestReadSubKeyNames(t *testing.T) { k, err := registry.OpenKey(registry.CLASSES_ROOT, "TypeLib", registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer k.Close() names, err := k.ReadSubKeyNames(-1) if err != nil { t.Fatal(err) } var foundStdOle bool for _, name := range names { // Every PC has "stdole 2.0 OLE Automation" library installed. if name == "{00020430-0000-0000-C000-000000000046}" { foundStdOle = true } } if !foundStdOle { t.Fatal("could not find stdole 2.0 OLE Automation") } } func TestCreateOpenDeleteKey(t *testing.T) { k, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer k.Close() testKName := randKeyName("TestCreateOpenDeleteKey_") testK, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY) if err != nil { t.Fatal(err) } defer testK.Close() if exist { t.Fatalf("key %q already exists", testKName) } testKAgain, exist, err := registry.CreateKey(k, testKName, registry.CREATE_SUB_KEY) if err != nil { t.Fatal(err) } defer testKAgain.Close() if !exist { t.Fatalf("key %q should already exist", testKName) } testKOpened, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS) if err != nil { t.Fatal(err) } defer testKOpened.Close() err = registry.DeleteKey(k, testKName) if err != nil { t.Fatal(err) } testKOpenedAgain, err := registry.OpenKey(k, testKName, registry.ENUMERATE_SUB_KEYS) if err == nil { defer testKOpenedAgain.Close() t.Fatalf("key %q should already been deleted", testKName) } if err != registry.ErrNotExist { t.Fatalf(`unexpected error ("not exist" expected): %v`, err) } } func equalStringSlice(a, b []string) bool { if len(a) != len(b) { return false } if a == nil { return true } for i := range a { if a[i] != b[i] { return false } } return true } type ValueTest struct { Type uint32 Name string Value interface{} WillFail bool } var ValueTests = []ValueTest{ {Type: registry.SZ, Name: "String1", Value: ""}, {Type: registry.SZ, Name: "String2", Value: "\000", WillFail: true}, {Type: registry.SZ, Name: "String3", Value: "Hello World"}, {Type: registry.SZ, Name: "String4", Value: "Hello World\000", WillFail: true}, {Type: registry.EXPAND_SZ, Name: "ExpString1", Value: ""}, {Type: registry.EXPAND_SZ, Name: "ExpString2", Value: "\000", WillFail: true}, {Type: registry.EXPAND_SZ, Name: "ExpString3", Value: "Hello World"}, {Type: registry.EXPAND_SZ, Name: "ExpString4", Value: "Hello\000World", WillFail: true}, {Type: registry.EXPAND_SZ, Name: "ExpString5", Value: "%PATH%"}, {Type: registry.EXPAND_SZ, Name: "ExpString6", Value: "%NO_SUCH_VARIABLE%"}, {Type: registry.EXPAND_SZ, Name: "ExpString7", Value: "%PATH%;."}, {Type: registry.BINARY, Name: "Binary1", Value: []byte{}}, {Type: registry.BINARY, Name: "Binary2", Value: []byte{1, 2, 3}}, {Type: registry.BINARY, Name: "Binary3", Value: []byte{3, 2, 1, 0, 1, 2, 3}}, {Type: registry.DWORD, Name: "Dword1", Value: uint64(0)}, {Type: registry.DWORD, Name: "Dword2", Value: uint64(1)}, {Type: registry.DWORD, Name: "Dword3", Value: uint64(0xff)}, {Type: registry.DWORD, Name: "Dword4", Value: uint64(0xffff)}, {Type: registry.QWORD, Name: "Qword1", Value: uint64(0)}, {Type: registry.QWORD, Name: "Qword2", Value: uint64(1)}, {Type: registry.QWORD, Name: "Qword3", Value: uint64(0xff)}, {Type: registry.QWORD, Name: "Qword4", Value: uint64(0xffff)}, {Type: registry.QWORD, Name: "Qword5", Value: uint64(0xffffff)}, {Type: registry.QWORD, Name: "Qword6", Value: uint64(0xffffffff)}, {Type: registry.MULTI_SZ, Name: "MultiString1", Value: []string{"a", "b", "c"}}, {Type: registry.MULTI_SZ, Name: "MultiString2", Value: []string{"abc", "", "cba"}}, {Type: registry.MULTI_SZ, Name: "MultiString3", Value: []string{""}}, {Type: registry.MULTI_SZ, Name: "MultiString4", Value: []string{"abcdef"}}, {Type: registry.MULTI_SZ, Name: "MultiString5", Value: []string{"\000"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString6", Value: []string{"a\000b"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString7", Value: []string{"ab", "\000", "cd"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString8", Value: []string{"\000", "cd"}, WillFail: true}, {Type: registry.MULTI_SZ, Name: "MultiString9", Value: []string{"ab", "\000"}, WillFail: true}, } func setValues(t *testing.T, k registry.Key) { for _, test := range ValueTests { var err error switch test.Type { case registry.SZ: err = k.SetStringValue(test.Name, test.Value.(string)) case registry.EXPAND_SZ: err = k.SetExpandStringValue(test.Name, test.Value.(string)) case registry.MULTI_SZ: err = k.SetStringsValue(test.Name, test.Value.([]string)) case registry.BINARY: err = k.SetBinaryValue(test.Name, test.Value.([]byte)) case registry.DWORD: err = k.SetDWordValue(test.Name, uint32(test.Value.(uint64))) case registry.QWORD: err = k.SetQWordValue(test.Name, test.Value.(uint64)) default: t.Fatalf("unsupported type %d for %s value", test.Type, test.Name) } if test.WillFail { if err == nil { t.Fatalf("setting %s value %q should fail, but succeeded", test.Name, test.Value) } } else { if err != nil { t.Fatal(err) } } } } func enumerateValues(t *testing.T, k registry.Key) { names, err := k.ReadValueNames(-1) if err != nil { t.Error(err) return } haveNames := make(map[string]bool) for _, n := range names { haveNames[n] = false } for _, test := range ValueTests { wantFound := !test.WillFail _, haveFound := haveNames[test.Name] if wantFound && !haveFound { t.Errorf("value %s is not found while enumerating", test.Name) } if haveFound && !wantFound { t.Errorf("value %s is found while enumerating, but expected to fail", test.Name) } if haveFound { delete(haveNames, test.Name) } } for n, v := range haveNames { t.Errorf("value %s (%v) is found while enumerating, but has not been cretaed", n, v) } } func testErrNotExist(t *testing.T, name string, err error) { if err == nil { t.Errorf("%s value should not exist", name) return } if err != registry.ErrNotExist { t.Errorf("reading %s value should return 'not exist' error, but got: %s", name, err) return } } func testErrUnexpectedType(t *testing.T, test ValueTest, gottype uint32, err error) { if err == nil { t.Errorf("GetXValue(%q) should not succeed", test.Name) return } if err != registry.ErrUnexpectedType { t.Errorf("reading %s value should return 'unexpected key value type' error, but got: %s", test.Name, err) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetStringValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetStringValue(test.Name) if err != nil { t.Errorf("GetStringValue(%s) failed: %v", test.Name, err) return } if got != test.Value { t.Errorf("want %s value %q, got %q", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } if gottype == registry.EXPAND_SZ { _, err = registry.ExpandString(got) if err != nil { t.Errorf("ExpandString(%s) failed: %v", got, err) return } } } func testGetIntegerValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetIntegerValue(test.Name) if err != nil { t.Errorf("GetIntegerValue(%s) failed: %v", test.Name, err) return } if got != test.Value.(uint64) { t.Errorf("want %s value %v, got %v", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetBinaryValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetBinaryValue(test.Name) if err != nil { t.Errorf("GetBinaryValue(%s) failed: %v", test.Name, err) return } if !bytes.Equal(got, test.Value.([]byte)) { t.Errorf("want %s value %v, got %v", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetStringsValue(t *testing.T, k registry.Key, test ValueTest) { got, gottype, err := k.GetStringsValue(test.Name) if err != nil { t.Errorf("GetStringsValue(%s) failed: %v", test.Name, err) return } if !equalStringSlice(got, test.Value.([]string)) { t.Errorf("want %s value %#v, got %#v", test.Name, test.Value, got) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } } func testGetValue(t *testing.T, k registry.Key, test ValueTest, size int) { if size <= 0 { return } // read data with no buffer gotsize, gottype, err := k.GetValue(test.Name, nil) if err != nil { t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err) return } if gotsize != size { t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } // read data with short buffer gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size-1)) if err == nil { t.Errorf("GetValue(%s, [%d]byte) should fail, but suceeded", test.Name, size-1) return } if err != registry.ErrShortBuffer { t.Errorf("reading %s value should return 'short buffer' error, but got: %s", test.Name, err) return } if gotsize != size { t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } // read full data gotsize, gottype, err = k.GetValue(test.Name, make([]byte, size)) if err != nil { t.Errorf("GetValue(%s, [%d]byte) failed: %v", test.Name, size, err) return } if gotsize != size { t.Errorf("want %s value size of %d, got %v", test.Name, size, gotsize) return } if gottype != test.Type { t.Errorf("want %s value type %v, got %v", test.Name, test.Type, gottype) return } // check GetValue returns ErrNotExist as required _, _, err = k.GetValue(test.Name+"_not_there", make([]byte, size)) if err == nil { t.Errorf("GetValue(%q) should not succeed", test.Name) return } if err != registry.ErrNotExist { t.Errorf("GetValue(%q) should return 'not exist' error, but got: %s", test.Name, err) return } } func testValues(t *testing.T, k registry.Key) { for _, test := range ValueTests { switch test.Type { case registry.SZ, registry.EXPAND_SZ: if test.WillFail { _, _, err := k.GetStringValue(test.Name) testErrNotExist(t, test.Name, err) } else { testGetStringValue(t, k, test) _, gottype, err := k.GetIntegerValue(test.Name) testErrUnexpectedType(t, test, gottype, err) // Size of utf16 string in bytes is not perfect, // but correct for current test values. // Size also includes terminating 0. testGetValue(t, k, test, (len(test.Value.(string))+1)*2) } _, _, err := k.GetStringValue(test.Name + "_string_not_created") testErrNotExist(t, test.Name+"_string_not_created", err) case registry.DWORD, registry.QWORD: testGetIntegerValue(t, k, test) _, gottype, err := k.GetBinaryValue(test.Name) testErrUnexpectedType(t, test, gottype, err) _, _, err = k.GetIntegerValue(test.Name + "_int_not_created") testErrNotExist(t, test.Name+"_int_not_created", err) size := 8 if test.Type == registry.DWORD { size = 4 } testGetValue(t, k, test, size) case registry.BINARY: testGetBinaryValue(t, k, test) _, gottype, err := k.GetStringsValue(test.Name) testErrUnexpectedType(t, test, gottype, err) _, _, err = k.GetBinaryValue(test.Name + "_byte_not_created") testErrNotExist(t, test.Name+"_byte_not_created", err) testGetValue(t, k, test, len(test.Value.([]byte))) case registry.MULTI_SZ: if test.WillFail { _, _, err := k.GetStringsValue(test.Name) testErrNotExist(t, test.Name, err) } else { testGetStringsValue(t, k, test) _, gottype, err := k.GetStringValue(test.Name) testErrUnexpectedType(t, test, gottype, err) size := 0 for _, s := range test.Value.([]string) { size += len(s) + 1 // nil terminated } size += 1 // extra nil at the end size *= 2 // count bytes, not uint16 testGetValue(t, k, test, size) } _, _, err := k.GetStringsValue(test.Name + "_strings_not_created") testErrNotExist(t, test.Name+"_strings_not_created", err) default: t.Errorf("unsupported type %d for %s value", test.Type, test.Name) continue } } } func testStat(t *testing.T, k registry.Key) { subk, _, err := registry.CreateKey(k, "subkey", registry.CREATE_SUB_KEY) if err != nil { t.Error(err) return } defer subk.Close() defer registry.DeleteKey(k, "subkey") ki, err := k.Stat() if err != nil { t.Error(err) return } if ki.SubKeyCount != 1 { t.Error("key must have 1 subkey") } if ki.MaxSubKeyLen != 6 { t.Error("key max subkey name length must be 6") } if ki.ValueCount != 24 { t.Errorf("key must have 24 values, but is %d", ki.ValueCount) } if ki.MaxValueNameLen != 12 { t.Errorf("key max value name length must be 10, but is %d", ki.MaxValueNameLen) } if ki.MaxValueLen != 38 { t.Errorf("key max value length must be 38, but is %d", ki.MaxValueLen) } if mt, ct := ki.ModTime(), time.Now(); ct.Sub(mt) > 100*time.Millisecond { t.Errorf("key mod time is not close to current time: mtime=%v current=%v delta=%v", mt, ct, ct.Sub(mt)) } } func deleteValues(t *testing.T, k registry.Key) { for _, test := range ValueTests { if test.WillFail { continue } err := k.DeleteValue(test.Name) if err != nil { t.Error(err) continue } } names, err := k.ReadValueNames(-1) if err != nil { t.Error(err) return } if len(names) != 0 { t.Errorf("some values remain after deletion: %v", names) } } func TestValues(t *testing.T) { softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer softwareK.Close() testKName := randKeyName("TestValues_") k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE) if err != nil { t.Fatal(err) } defer k.Close() if exist { t.Fatalf("key %q already exists", testKName) } defer registry.DeleteKey(softwareK, testKName) setValues(t, k) enumerateValues(t, k) testValues(t, k) testStat(t, k) deleteValues(t, k) } func walkKey(t *testing.T, k registry.Key, kname string) { names, err := k.ReadValueNames(-1) if err != nil { t.Fatalf("reading value names of %s failed: %v", kname, err) } for _, name := range names { _, valtype, err := k.GetValue(name, nil) if err != nil { t.Fatalf("reading value type of %s of %s failed: %v", name, kname, err) } switch valtype { case registry.NONE: case registry.SZ: _, _, err := k.GetStringValue(name) if err != nil { t.Error(err) } case registry.EXPAND_SZ: s, _, err := k.GetStringValue(name) if err != nil { t.Error(err) } _, err = registry.ExpandString(s) if err != nil { t.Error(err) } case registry.DWORD, registry.QWORD: _, _, err := k.GetIntegerValue(name) if err != nil { t.Error(err) } case registry.BINARY: _, _, err := k.GetBinaryValue(name) if err != nil { t.Error(err) } case registry.MULTI_SZ: _, _, err := k.GetStringsValue(name) if err != nil { t.Error(err) } case registry.FULL_RESOURCE_DESCRIPTOR, registry.RESOURCE_LIST, registry.RESOURCE_REQUIREMENTS_LIST: // TODO: not implemented default: t.Fatalf("value type %d of %s of %s failed: %v", valtype, name, kname, err) } } names, err = k.ReadSubKeyNames(-1) if err != nil { t.Fatalf("reading sub-keys of %s failed: %v", kname, err) } for _, name := range names { func() { subk, err := registry.OpenKey(k, name, registry.ENUMERATE_SUB_KEYS|registry.QUERY_VALUE) if err != nil { if err == syscall.ERROR_ACCESS_DENIED { // ignore error, if we are not allowed to access this key return } t.Fatalf("opening sub-keys %s of %s failed: %v", name, kname, err) } defer subk.Close() walkKey(t, subk, kname+`\`+name) }() } } func TestWalkFullRegistry(t *testing.T) { if testing.Short() { t.Skip("skipping long running test in short mode") } walkKey(t, registry.CLASSES_ROOT, "CLASSES_ROOT") walkKey(t, registry.CURRENT_USER, "CURRENT_USER") walkKey(t, registry.LOCAL_MACHINE, "LOCAL_MACHINE") walkKey(t, registry.USERS, "USERS") walkKey(t, registry.CURRENT_CONFIG, "CURRENT_CONFIG") } func TestExpandString(t *testing.T) { got, err := registry.ExpandString("%PATH%") if err != nil { t.Fatal(err) } want := os.Getenv("PATH") if got != want { t.Errorf("want %q string expanded, got %q", want, got) } } func TestInvalidValues(t *testing.T) { softwareK, err := registry.OpenKey(registry.CURRENT_USER, "Software", registry.QUERY_VALUE) if err != nil { t.Fatal(err) } defer softwareK.Close() testKName := randKeyName("TestInvalidValues_") k, exist, err := registry.CreateKey(softwareK, testKName, registry.CREATE_SUB_KEY|registry.QUERY_VALUE|registry.SET_VALUE) if err != nil { t.Fatal(err) } defer k.Close() if exist { t.Fatalf("key %q already exists", testKName) } defer registry.DeleteKey(softwareK, testKName) var tests = []struct { Type uint32 Name string Data []byte }{ {registry.DWORD, "Dword1", nil}, {registry.DWORD, "Dword2", []byte{1, 2, 3}}, {registry.QWORD, "Qword1", nil}, {registry.QWORD, "Qword2", []byte{1, 2, 3}}, {registry.QWORD, "Qword3", []byte{1, 2, 3, 4, 5, 6, 7}}, {registry.MULTI_SZ, "MultiString1", nil}, {registry.MULTI_SZ, "MultiString2", []byte{0}}, {registry.MULTI_SZ, "MultiString3", []byte{'a', 'b', 0}}, {registry.MULTI_SZ, "MultiString4", []byte{'a', 0, 0, 'b', 0}}, {registry.MULTI_SZ, "MultiString5", []byte{'a', 0, 0}}, } for _, test := range tests { err := k.SetValue(test.Name, test.Type, test.Data) if err != nil { t.Fatalf("SetValue for %q failed: %v", test.Name, err) } } for _, test := range tests { switch test.Type { case registry.DWORD, registry.QWORD: value, valType, err := k.GetIntegerValue(test.Name) if err == nil { t.Errorf("GetIntegerValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value) } case registry.MULTI_SZ: value, valType, err := k.GetStringsValue(test.Name) if err == nil { if len(value) != 0 { t.Errorf("GetStringsValue(%q) succeeded. Returns type=%d value=%v", test.Name, valType, value) } } default: t.Errorf("unsupported type %d for %s value", test.Type, test.Name) } } } func TestGetMUIStringValue(t *testing.T) { if err := registry.LoadRegLoadMUIString(); err != nil { t.Skip("regLoadMUIString not supported; skipping") } if err := procGetDynamicTimeZoneInformation.Find(); err != nil { t.Skipf("%s not supported; skipping", procGetDynamicTimeZoneInformation.Name) } var dtzi DynamicTimezoneinformation if _, err := GetDynamicTimeZoneInformation(&dtzi); err != nil { t.Fatal(err) } tzKeyName := syscall.UTF16ToString(dtzi.TimeZoneKeyName[:]) timezoneK, err := registry.OpenKey(registry.LOCAL_MACHINE, `SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\`+tzKeyName, registry.READ) if err != nil { t.Fatal(err) } defer timezoneK.Close() var tests = []struct { key registry.Key name string want string }{ {timezoneK, "MUI_Std", syscall.UTF16ToString(dtzi.StandardName[:])}, {timezoneK, "MUI_Dlt", syscall.UTF16ToString(dtzi.DaylightName[:])}, } for _, test := range tests { got, err := test.key.GetMUIStringValue(test.name) if err != nil { t.Error("GetMUIStringValue:", err) } if got != test.want { t.Errorf("GetMUIStringValue: %s: Got %q, want %q", test.name, got, test.want) } } } type DynamicTimezoneinformation struct { Bias int32 StandardName [32]uint16 StandardDate syscall.Systemtime StandardBias int32 DaylightName [32]uint16 DaylightDate syscall.Systemtime DaylightBias int32 TimeZoneKeyName [128]uint16 DynamicDaylightTimeDisabled uint8 } var ( kernel32DLL = syscall.NewLazyDLL("kernel32") procGetDynamicTimeZoneInformation = kernel32DLL.NewProc("GetDynamicTimeZoneInformation") ) func GetDynamicTimeZoneInformation(dtzi *DynamicTimezoneinformation) (rc uint32, err error) { r0, _, e1 := syscall.Syscall(procGetDynamicTimeZoneInformation.Addr(), 1, uintptr(unsafe.Pointer(dtzi)), 0, 0) rc = uint32(r0) if rc == 0xffffffff { if e1 != 0 { err = error(e1) } else { err = syscall.EINVAL } } return } ================================================ FILE: vendor/golang.org/x/sys/windows/registry/syscall.go ================================================ // 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" //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go syscall.go 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 expandEnvironmentStrings(src *uint16, dst *uint16, size uint32) (n uint32, err error) = kernel32.ExpandEnvironmentStringsW ================================================ FILE: vendor/golang.org/x/sys/windows/registry/value.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/registry/zsyscall_windows.go ================================================ // MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT package registry import "unsafe" import "syscall" var _ unsafe.Pointer var ( modadvapi32 = syscall.NewLazyDLL("advapi32.dll") modkernel32 = syscall.NewLazyDLL("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") 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 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 = error(e1) } else { err = syscall.EINVAL } } return } ================================================ FILE: vendor/golang.org/x/sys/windows/security_windows.go ================================================ // 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 } } } ================================================ FILE: vendor/golang.org/x/sys/windows/service.go ================================================ // 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 ) 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 } //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 ================================================ FILE: vendor/golang.org/x/sys/windows/str.go ================================================ // 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:]) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/debug/log.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/debug/service.go ================================================ // 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, status} case status = <-changes: } } }() _, errno := handler.Execute([]string{name}, cmds, changes) if errno != 0 { return syscall.Errno(errno) } return nil } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/event.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/eventlog/install.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/eventlog/log.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/eventlog/log_test.go ================================================ // 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_test import ( "testing" "golang.org/x/sys/windows/svc/eventlog" ) func TestLog(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode - it modifies system logs") } const name = "mylog" const supports = eventlog.Error | eventlog.Warning | eventlog.Info err := eventlog.InstallAsEventCreate(name, supports) if err != nil { t.Fatalf("Install failed: %s", err) } defer func() { err = eventlog.Remove(name) if err != nil { t.Fatalf("Remove failed: %s", err) } }() l, err := eventlog.Open(name) if err != nil { t.Fatalf("Open failed: %s", err) } defer l.Close() err = l.Info(1, "info") if err != nil { t.Fatalf("Info failed: %s", err) } err = l.Warning(2, "warning") if err != nil { t.Fatalf("Warning failed: %s", err) } err = l.Error(3, "error") if err != nil { t.Fatalf("Error failed: %s", err) } } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/example/beep.go ================================================ // 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 main import ( "syscall" ) // BUG(brainman): MessageBeep Windows api is broken on Windows 7, // so this example does not beep when runs as service on Windows 7. var ( beepFunc = syscall.MustLoadDLL("user32.dll").MustFindProc("MessageBeep") ) func beep() { beepFunc.Call(0xffffffff) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/example/install.go ================================================ // 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 main import ( "fmt" "os" "path/filepath" "golang.org/x/sys/windows/svc/eventlog" "golang.org/x/sys/windows/svc/mgr" ) func exePath() (string, error) { prog := os.Args[0] p, err := filepath.Abs(prog) if err != nil { return "", err } fi, err := os.Stat(p) if err == nil { if !fi.Mode().IsDir() { return p, nil } err = fmt.Errorf("%s is directory", p) } if filepath.Ext(p) == "" { p += ".exe" fi, err := os.Stat(p) if err == nil { if !fi.Mode().IsDir() { return p, nil } err = fmt.Errorf("%s is directory", p) } } return "", err } func installService(name, desc string) error { exepath, err := exePath() if err != nil { return err } m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err == nil { s.Close() return fmt.Errorf("service %s already exists", name) } s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: desc}, "is", "auto-started") if err != nil { return err } defer s.Close() err = eventlog.InstallAsEventCreate(name, eventlog.Error|eventlog.Warning|eventlog.Info) if err != nil { s.Delete() return fmt.Errorf("SetupEventLogSource() failed: %s", err) } return nil } func removeService(name string) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("service %s is not installed", name) } defer s.Close() err = s.Delete() if err != nil { return err } err = eventlog.Remove(name) if err != nil { return fmt.Errorf("RemoveEventLogSource() failed: %s", err) } return nil } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/example/main.go ================================================ // 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 // Example service program that beeps. // // The program demonstrates how to create Windows service and // install / remove it on a computer. It also shows how to // stop / start / pause / continue any service, and how to // write to event log. It also shows how to use debug // facilities available in debug package. // package main import ( "fmt" "log" "os" "strings" "golang.org/x/sys/windows/svc" ) func usage(errmsg string) { fmt.Fprintf(os.Stderr, "%s\n\n"+ "usage: %s \n"+ " where is one of\n"+ " install, remove, debug, start, stop, pause or continue.\n", errmsg, os.Args[0]) os.Exit(2) } func main() { const svcName = "myservice" isIntSess, err := svc.IsAnInteractiveSession() if err != nil { log.Fatalf("failed to determine if we are running in an interactive session: %v", err) } if !isIntSess { runService(svcName, false) return } if len(os.Args) < 2 { usage("no command specified") } cmd := strings.ToLower(os.Args[1]) switch cmd { case "debug": runService(svcName, true) return case "install": err = installService(svcName, "my service") case "remove": err = removeService(svcName) case "start": err = startService(svcName) case "stop": err = controlService(svcName, svc.Stop, svc.Stopped) case "pause": err = controlService(svcName, svc.Pause, svc.Paused) case "continue": err = controlService(svcName, svc.Continue, svc.Running) default: usage(fmt.Sprintf("invalid command %s", cmd)) } if err != nil { log.Fatalf("failed to %s %s: %v", cmd, svcName, err) } return } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/example/manage.go ================================================ // 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 main import ( "fmt" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/mgr" ) func startService(name string) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() err = s.Start("is", "manual-started") if err != nil { return fmt.Errorf("could not start service: %v", err) } return nil } func controlService(name string, c svc.Cmd, to svc.State) error { m, err := mgr.Connect() if err != nil { return err } defer m.Disconnect() s, err := m.OpenService(name) if err != nil { return fmt.Errorf("could not access service: %v", err) } defer s.Close() status, err := s.Control(c) if err != nil { return fmt.Errorf("could not send control=%d: %v", c, err) } timeout := time.Now().Add(10 * time.Second) for status.State != to { if timeout.Before(time.Now()) { return fmt.Errorf("timeout waiting for service to go to state=%d", to) } time.Sleep(300 * time.Millisecond) status, err = s.Query() if err != nil { return fmt.Errorf("could not retrieve service status: %v", err) } } return nil } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/example/service.go ================================================ // 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 main import ( "fmt" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/debug" "golang.org/x/sys/windows/svc/eventlog" ) var elog debug.Log type myservice struct{} func (m *myservice) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) { const cmdsAccepted = svc.AcceptStop | svc.AcceptShutdown | svc.AcceptPauseAndContinue changes <- svc.Status{State: svc.StartPending} fasttick := time.Tick(500 * time.Millisecond) slowtick := time.Tick(2 * time.Second) tick := fasttick changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} loop: for { select { case <-tick: beep() elog.Info(1, "beep") case c := <-r: switch c.Cmd { case svc.Interrogate: changes <- c.CurrentStatus // Testing deadlock from https://code.google.com/p/winsvc/issues/detail?id=4 time.Sleep(100 * time.Millisecond) changes <- c.CurrentStatus case svc.Stop, svc.Shutdown: break loop case svc.Pause: changes <- svc.Status{State: svc.Paused, Accepts: cmdsAccepted} tick = slowtick case svc.Continue: changes <- svc.Status{State: svc.Running, Accepts: cmdsAccepted} tick = fasttick default: elog.Error(1, fmt.Sprintf("unexpected control request #%d", c)) } } } changes <- svc.Status{State: svc.StopPending} return } func runService(name string, isDebug bool) { var err error if isDebug { elog = debug.New(name) } else { elog, err = eventlog.Open(name) if err != nil { return } } defer elog.Close() elog.Info(1, fmt.Sprintf("starting %s service", name)) run := svc.Run if isDebug { run = debug.Run } err = run(name, &myservice{}) if err != nil { elog.Error(1, fmt.Sprintf("%s service failed: %v", name, err)) return } elog.Info(1, fmt.Sprintf("%s service stopped", name)) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/go12.c ================================================ // 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; } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/go12.go ================================================ // 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) ================================================ FILE: vendor/golang.org/x/sys/windows/svc/go13.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/mgr/config.go ================================================ // 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) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/mgr/mgr.go ================================================ // 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" "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. // If service StartType is set to StartAutomatic, // args will be passed to svc.Handle.Execute. 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 } 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, windows.SERVICE_WIN32_OWN_PROCESS, 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/mgr/mgr_test.go ================================================ // 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_test import ( "os" "path/filepath" "sort" "strings" "syscall" "testing" "time" "golang.org/x/sys/windows/svc/mgr" ) func TestOpenLanManServer(t *testing.T) { m, err := mgr.Connect() if err != nil { if errno, ok := err.(syscall.Errno); ok && errno == syscall.ERROR_ACCESS_DENIED { t.Skip("Skipping test: we don't have rights to manage services.") } t.Fatalf("SCM connection failed: %s", err) } defer m.Disconnect() s, err := m.OpenService("LanmanServer") if err != nil { t.Fatalf("OpenService(lanmanserver) failed: %s", err) } defer s.Close() _, err = s.Config() if err != nil { t.Fatalf("Config failed: %s", err) } } func install(t *testing.T, m *mgr.Mgr, name, exepath string, c mgr.Config) { // Sometimes it takes a while for the service to get // removed after previous test run. for i := 0; ; i++ { s, err := m.OpenService(name) if err != nil { break } s.Close() if i > 10 { t.Fatalf("service %s already exists", name) } time.Sleep(300 * time.Millisecond) } s, err := m.CreateService(name, exepath, c) if err != nil { t.Fatalf("CreateService(%s) failed: %v", name, err) } defer s.Close() } func depString(d []string) string { if len(d) == 0 { return "" } for i := range d { d[i] = strings.ToLower(d[i]) } ss := sort.StringSlice(d) ss.Sort() return strings.Join([]string(ss), " ") } func testConfig(t *testing.T, s *mgr.Service, should mgr.Config) mgr.Config { is, err := s.Config() if err != nil { t.Fatalf("Config failed: %s", err) } if should.DisplayName != is.DisplayName { t.Fatalf("config mismatch: DisplayName is %q, but should have %q", is.DisplayName, should.DisplayName) } if should.StartType != is.StartType { t.Fatalf("config mismatch: StartType is %v, but should have %v", is.StartType, should.StartType) } if should.Description != is.Description { t.Fatalf("config mismatch: Description is %q, but should have %q", is.Description, should.Description) } if depString(should.Dependencies) != depString(is.Dependencies) { t.Fatalf("config mismatch: Dependencies is %v, but should have %v", is.Dependencies, should.Dependencies) } return is } func remove(t *testing.T, s *mgr.Service) { err := s.Delete() if err != nil { t.Fatalf("Delete failed: %s", err) } } func TestMyService(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode - it modifies system services") } const name = "myservice" m, err := mgr.Connect() if err != nil { if errno, ok := err.(syscall.Errno); ok && errno == syscall.ERROR_ACCESS_DENIED { t.Skip("Skipping test: we don't have rights to manage services.") } t.Fatalf("SCM connection failed: %s", err) } defer m.Disconnect() c := mgr.Config{ StartType: mgr.StartDisabled, DisplayName: "my service", Description: "my service is just a test", Dependencies: []string{"LanmanServer", "W32Time"}, } exename := os.Args[0] exepath, err := filepath.Abs(exename) if err != nil { t.Fatalf("filepath.Abs(%s) failed: %s", exename, err) } install(t, m, name, exepath, c) s, err := m.OpenService(name) if err != nil { t.Fatalf("service %s is not installed", name) } defer s.Close() c.BinaryPathName = exepath c = testConfig(t, s, c) c.StartType = mgr.StartManual err = s.UpdateConfig(c) if err != nil { t.Fatalf("UpdateConfig failed: %v", err) } testConfig(t, s, c) remove(t, s) } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/mgr/service.go ================================================ // 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. // TODO(brainman): Use EnumServicesStatus to enumerate services in the specified service control manager database. // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/security.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/service.go ================================================ // 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) ) // 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) ) // 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 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 ctlHandlerProc uintptr cSetEvent uintptr cWaitForSingleObject uintptr cRegisterServiceCtrlHandlerW uintptr ) func init() { k := syscall.MustLoadDLL("kernel32.dll") cSetEvent = k.MustFindProc("SetEvent").Addr() cWaitForSingleObject = k.MustFindProc("WaitForSingleObject").Addr() a := syscall.MustLoadDLL("advapi32.dll") cRegisterServiceCtrlHandlerW = a.MustFindProc("RegisterServiceCtrlHandlerW").Addr() } type ctlEvent struct { cmd Cmd 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 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 loop: for { select { case r := <-inch: if r.errno != 0 { ec.errno = r.errno break loop } inch = nil outch = cmdsToHandler cmd = r.cmd case outch <- ChangeRequest{cmd, 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) uintptr { e := ctlEvent{cmd: Cmd(ctl)} // 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 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 ctlHandlerProc, err = newCallback(ctlHandler) if err != nil { return err } go s.run() err = windows.StartServiceCtrlDispatcher(&t[0]) if err != nil { return err } return nil } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/svc_test.go ================================================ // 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_test import ( "io/ioutil" "os" "os/exec" "path/filepath" "testing" "time" "golang.org/x/sys/windows/svc" "golang.org/x/sys/windows/svc/mgr" ) func getState(t *testing.T, s *mgr.Service) svc.State { status, err := s.Query() if err != nil { t.Fatalf("Query(%s) failed: %s", s.Name, err) } return status.State } func testState(t *testing.T, s *mgr.Service, want svc.State) { have := getState(t, s) if have != want { t.Fatalf("%s state is=%d want=%d", s.Name, have, want) } } func waitState(t *testing.T, s *mgr.Service, want svc.State) { for i := 0; ; i++ { have := getState(t, s) if have == want { return } if i > 10 { t.Fatalf("%s state is=%d, waiting timeout", s.Name, have) } time.Sleep(300 * time.Millisecond) } } func TestExample(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode - it modifies system services") } const name = "myservice" m, err := mgr.Connect() if err != nil { t.Fatalf("SCM connection failed: %s", err) } defer m.Disconnect() dir, err := ioutil.TempDir("", "svc") if err != nil { t.Fatalf("failed to create temp directory: %v", err) } defer os.RemoveAll(dir) exepath := filepath.Join(dir, "a.exe") o, err := exec.Command("go", "build", "-o", exepath, "golang.org/x/sys/windows/svc/example").CombinedOutput() if err != nil { t.Fatalf("failed to build service program: %v\n%v", err, string(o)) } s, err := m.OpenService(name) if err == nil { err = s.Delete() if err != nil { s.Close() t.Fatalf("Delete failed: %s", err) } s.Close() } s, err = m.CreateService(name, exepath, mgr.Config{DisplayName: "my service"}, "is", "auto-started") if err != nil { t.Fatalf("CreateService(%s) failed: %v", name, err) } defer s.Close() testState(t, s, svc.Stopped) err = s.Start("is", "manual-started") if err != nil { t.Fatalf("Start(%s) failed: %s", s.Name, err) } waitState(t, s, svc.Running) time.Sleep(1 * time.Second) // testing deadlock from issues 4. _, err = s.Control(svc.Interrogate) if err != nil { t.Fatalf("Control(%s) failed: %s", s.Name, err) } _, err = s.Control(svc.Interrogate) if err != nil { t.Fatalf("Control(%s) failed: %s", s.Name, err) } time.Sleep(1 * time.Second) _, err = s.Control(svc.Stop) if err != nil { t.Fatalf("Control(%s) failed: %s", s.Name, err) } waitState(t, s, svc.Stopped) err = s.Delete() if err != nil { t.Fatalf("Delete failed: %s", err) } } ================================================ FILE: vendor/golang.org/x/sys/windows/svc/sys_386.s ================================================ // 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 ·cRegisterServiceCtrlHandlerW(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) uintptr TEXT ·servicectlhandler(SB),7,$0 MOVL ·ctlHandlerProc(SB), CX JMP CX ================================================ FILE: vendor/golang.org/x/sys/windows/svc/sys_amd64.s ================================================ // 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 MOVQ ·cRegisterServiceCtrlHandlerW(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) uintptr TEXT ·servicectlhandler(SB),7,$0 MOVQ ·ctlHandlerProc(SB), AX JMP AX ================================================ FILE: vendor/golang.org/x/sys/windows/syscall.go ================================================ // 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" "unsafe" ) // 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 } // 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) ================================================ FILE: vendor/golang.org/x/sys/windows/syscall_test.go ================================================ // 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 windows package windows_test import ( "testing" "golang.org/x/sys/windows" ) func testSetGetenv(t *testing.T, key, value string) { err := windows.Setenv(key, value) if err != nil { t.Fatalf("Setenv failed to set %q: %v", value, err) } newvalue, found := windows.Getenv(key) if !found { t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value) } if newvalue != value { t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value) } } func TestEnv(t *testing.T) { testSetGetenv(t, "TESTENV", "AVALUE") // make sure TESTENV gets set to "", not deleted testSetGetenv(t, "TESTENV", "") } ================================================ FILE: vendor/golang.org/x/sys/windows/syscall_windows.go ================================================ // 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" ) //go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go eventlog.go service.go syscall_windows.go security_windows.go 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 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 int) (handle Handle, err error) [failretval==InvalidHandle] //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 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 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 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 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 *syscall.SecurityAttributes, manualReset uint32, initialState uint32, name *uint16) (handle Handle, err error) = kernel32.CreateEventW //sys SetEvent(event Handle) (err error) = kernel32.SetEvent // 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(h int) (fd Handle) { r, _ := GetStdHandle(h) 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 MoveFile(from, to) } 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 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 // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/syscall_windows_test.go ================================================ // 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_test import ( "io/ioutil" "os" "path/filepath" "syscall" "testing" "unsafe" "golang.org/x/sys/windows" ) func TestWin32finddata(t *testing.T) { dir, err := ioutil.TempDir("", "go-build") if err != nil { t.Fatalf("failed to create temp directory: %v", err) } defer os.RemoveAll(dir) path := filepath.Join(dir, "long_name.and_extension") f, err := os.Create(path) if err != nil { t.Fatalf("failed to create %v: %v", path, err) } f.Close() type X struct { fd windows.Win32finddata got byte pad [10]byte // to protect ourselves } var want byte = 2 // it is unlikely to have this character in the filename x := X{got: want} pathp, _ := windows.UTF16PtrFromString(path) h, err := windows.FindFirstFile(pathp, &(x.fd)) if err != nil { t.Fatalf("FindFirstFile failed: %v", err) } err = windows.FindClose(h) if err != nil { t.Fatalf("FindClose failed: %v", err) } if x.got != want { t.Fatalf("memory corruption: want=%d got=%d", want, x.got) } } func TestFormatMessage(t *testing.T) { dll := windows.MustLoadDLL("pdh.dll") pdhOpenQuery := func(datasrc *uint16, userdata uint32, query *windows.Handle) (errno uintptr) { r0, _, _ := syscall.Syscall(dll.MustFindProc("PdhOpenQueryW").Addr(), 3, uintptr(unsafe.Pointer(datasrc)), uintptr(userdata), uintptr(unsafe.Pointer(query))) return r0 } pdhCloseQuery := func(query windows.Handle) (errno uintptr) { r0, _, _ := syscall.Syscall(dll.MustFindProc("PdhCloseQuery").Addr(), 1, uintptr(query), 0, 0) return r0 } var q windows.Handle name, err := windows.UTF16PtrFromString("no_such_source") if err != nil { t.Fatal(err) } errno := pdhOpenQuery(name, 0, &q) if errno == 0 { pdhCloseQuery(q) t.Fatal("PdhOpenQuery succeeded, but expected to fail.") } const flags uint32 = syscall.FORMAT_MESSAGE_FROM_HMODULE | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS buf := make([]uint16, 300) _, err = windows.FormatMessage(flags, uintptr(dll.Handle), uint32(errno), 0, buf, nil) if err != nil { t.Fatal("FormatMessage for handle=%x and errno=%x failed: %v", dll.Handle, errno, err) } } func abort(funcname string, err error) { panic(funcname + " failed: " + err.Error()) } func ExampleLoadLibrary() { h, err := windows.LoadLibrary("kernel32.dll") if err != nil { abort("LoadLibrary", err) } defer windows.FreeLibrary(h) proc, err := windows.GetProcAddress(h, "GetVersion") if err != nil { abort("GetProcAddress", err) } r, _, _ := syscall.Syscall(uintptr(proc), 0, 0, 0, 0) major := byte(r) minor := uint8(r >> 8) build := uint16(r >> 16) print("windows version ", major, ".", minor, " (Build ", build, ")\n") } ================================================ FILE: vendor/golang.org/x/sys/windows/zsyscall_windows.go ================================================ // MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT package windows import "unsafe" import "syscall" var _ unsafe.Pointer var ( modadvapi32 = syscall.NewLazyDLL("advapi32.dll") modkernel32 = syscall.NewLazyDLL("kernel32.dll") modshell32 = syscall.NewLazyDLL("shell32.dll") modmswsock = syscall.NewLazyDLL("mswsock.dll") modcrypt32 = syscall.NewLazyDLL("crypt32.dll") modws2_32 = syscall.NewLazyDLL("ws2_32.dll") moddnsapi = syscall.NewLazyDLL("dnsapi.dll") modiphlpapi = syscall.NewLazyDLL("iphlpapi.dll") modsecur32 = syscall.NewLazyDLL("secur32.dll") modnetapi32 = syscall.NewLazyDLL("netapi32.dll") moduserenv = syscall.NewLazyDLL("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") procGetLastError = modkernel32.NewProc("GetLastError") procLoadLibraryW = modkernel32.NewProc("LoadLibraryW") 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") 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") procGetComputerNameW = modkernel32.NewProc("GetComputerNameW") procGetComputerNameExW = modkernel32.NewProc("GetComputerNameExW") procSetEndOfFile = modkernel32.NewProc("SetEndOfFile") procGetSystemTimeAsFileTime = modkernel32.NewProc("GetSystemTimeAsFileTime") 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") 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") 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") procSetEvent = modkernel32.NewProc("SetEvent") 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") 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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(e1) } else { err = syscall.EINVAL } } return } func GetStdHandle(stdhandle int) (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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(e1) } else { err = syscall.EINVAL } } return } func GetSystemTimeAsFileTime(time *Filetime) { syscall.Syscall(procGetSystemTimeAsFileTime.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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 *syscall.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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(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 = error(e1) } else { err = syscall.EINVAL } } return } ================================================ FILE: vendor/golang.org/x/sys/windows/ztypes_windows.go ================================================ // 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 STD_OUTPUT_HANDLE = -11 STD_ERROR_HANDLE = -12 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 PAGE_READONLY = 0x02 PAGE_READWRITE = 0x04 PAGE_WRITECOPY = 0x08 PAGE_EXECUTE_READ = 0x20 PAGE_EXECUTE_READWRITE = 0x40 PAGE_EXECUTE_WRITECOPY = 0x80 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 ) ================================================ FILE: vendor/golang.org/x/sys/windows/ztypes_windows_386.go ================================================ // 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 } ================================================ FILE: vendor/golang.org/x/sys/windows/ztypes_windows_amd64.go ================================================ // 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/.travis.yml ================================================ language: go go: - 1.4 - 1.5 - 1.6 - tip go_import_path: gopkg.in/yaml.v2 ================================================ FILE: vendor/gopkg.in/yaml.v2/LICENSE ================================================ Copyright (c) 2011-2014 - Canonical Inc. This software is licensed under the LGPLv3, included below. As a special exception to the GNU Lesser General Public License version 3 ("LGPL3"), the copyright holders of this Library give you permission to convey to a third party a Combined Work that links statically or dynamically to this Library without providing any Minimal Corresponding Source or Minimal Application Code as set out in 4d or providing the installation information set out in section 4e, provided that you comply with the other provisions of LGPL3 and provided that you meet, for the Application the terms and conditions of the license(s) which apply to the Application. Except as stated in this special exception, the provisions of LGPL3 will continue to comply in full to this Library. If you modify this Library, you may apply this exception to your version of this Library, but you are not obliged to do so. If you do not wish to do so, delete this exception statement from your version. This exception does not (and cannot) modify any license terms which apply to the Application, with which you must still comply. GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. ================================================ FILE: vendor/gopkg.in/yaml.v2/LICENSE.libyaml ================================================ 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. ================================================ FILE: vendor/gopkg.in/yaml.v2/README.md ================================================ # 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 LGPL with an exception that allows it to be linked statically. 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 ``` ================================================ FILE: vendor/gopkg.in/yaml.v2/apic.go ================================================ 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 //} // // ================================================ FILE: vendor/gopkg.in/yaml.v2/decode.go ================================================ 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 == "") { 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) } ================================================ FILE: vendor/gopkg.in/yaml.v2/decode_test.go ================================================ package yaml_test import ( "errors" . "gopkg.in/check.v1" "gopkg.in/yaml.v2" "math" "net" "reflect" "strings" "time" ) var unmarshalIntTest = 123 var unmarshalTests = []struct { data string value interface{} }{ { "", &struct{}{}, }, { "{}", &struct{}{}, }, { "v: hi", map[string]string{"v": "hi"}, }, { "v: hi", map[string]interface{}{"v": "hi"}, }, { "v: true", map[string]string{"v": "true"}, }, { "v: true", map[string]interface{}{"v": true}, }, { "v: 10", map[string]interface{}{"v": 10}, }, { "v: 0b10", map[string]interface{}{"v": 2}, }, { "v: 0xA", map[string]interface{}{"v": 10}, }, { "v: 4294967296", map[string]int64{"v": 4294967296}, }, { "v: 0.1", map[string]interface{}{"v": 0.1}, }, { "v: .1", map[string]interface{}{"v": 0.1}, }, { "v: .Inf", map[string]interface{}{"v": math.Inf(+1)}, }, { "v: -.Inf", map[string]interface{}{"v": math.Inf(-1)}, }, { "v: -10", map[string]interface{}{"v": -10}, }, { "v: -.1", map[string]interface{}{"v": -0.1}, }, // Simple values. { "123", &unmarshalIntTest, }, // Floats from spec { "canonical: 6.8523e+5", map[string]interface{}{"canonical": 6.8523e+5}, }, { "expo: 685.230_15e+03", map[string]interface{}{"expo": 685.23015e+03}, }, { "fixed: 685_230.15", map[string]interface{}{"fixed": 685230.15}, }, { "neginf: -.inf", map[string]interface{}{"neginf": math.Inf(-1)}, }, { "fixed: 685_230.15", map[string]float64{"fixed": 685230.15}, }, //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails. // Bools from spec { "canonical: y", map[string]interface{}{"canonical": true}, }, { "answer: NO", map[string]interface{}{"answer": false}, }, { "logical: True", map[string]interface{}{"logical": true}, }, { "option: on", map[string]interface{}{"option": true}, }, { "option: on", map[string]bool{"option": true}, }, // Ints from spec { "canonical: 685230", map[string]interface{}{"canonical": 685230}, }, { "decimal: +685_230", map[string]interface{}{"decimal": 685230}, }, { "octal: 02472256", map[string]interface{}{"octal": 685230}, }, { "hexa: 0x_0A_74_AE", map[string]interface{}{"hexa": 685230}, }, { "bin: 0b1010_0111_0100_1010_1110", map[string]interface{}{"bin": 685230}, }, { "bin: -0b101010", map[string]interface{}{"bin": -42}, }, { "decimal: +685_230", map[string]int{"decimal": 685230}, }, //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported // Nulls from spec { "empty:", map[string]interface{}{"empty": nil}, }, { "canonical: ~", map[string]interface{}{"canonical": nil}, }, { "english: null", map[string]interface{}{"english": nil}, }, { "~: null key", map[interface{}]string{nil: "null key"}, }, { "empty:", map[string]*bool{"empty": nil}, }, // Flow sequence { "seq: [A,B]", map[string]interface{}{"seq": []interface{}{"A", "B"}}, }, { "seq: [A,B,C,]", map[string][]string{"seq": []string{"A", "B", "C"}}, }, { "seq: [A,1,C]", map[string][]string{"seq": []string{"A", "1", "C"}}, }, { "seq: [A,1,C]", map[string][]int{"seq": []int{1}}, }, { "seq: [A,1,C]", map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, }, // Block sequence { "seq:\n - A\n - B", map[string]interface{}{"seq": []interface{}{"A", "B"}}, }, { "seq:\n - A\n - B\n - C", map[string][]string{"seq": []string{"A", "B", "C"}}, }, { "seq:\n - A\n - 1\n - C", map[string][]string{"seq": []string{"A", "1", "C"}}, }, { "seq:\n - A\n - 1\n - C", map[string][]int{"seq": []int{1}}, }, { "seq:\n - A\n - 1\n - C", map[string]interface{}{"seq": []interface{}{"A", 1, "C"}}, }, // Literal block scalar { "scalar: | # Comment\n\n literal\n\n \ttext\n\n", map[string]string{"scalar": "\nliteral\n\n\ttext\n"}, }, // Folded block scalar { "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n", map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"}, }, // Map inside interface with no type hints. { "a: {b: c}", map[interface{}]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, }, // Structs and type conversions. { "hello: world", &struct{ Hello string }{"world"}, }, { "a: {b: c}", &struct{ A struct{ B string } }{struct{ B string }{"c"}}, }, { "a: {b: c}", &struct{ A *struct{ B string } }{&struct{ B string }{"c"}}, }, { "a: {b: c}", &struct{ A map[string]string }{map[string]string{"b": "c"}}, }, { "a: {b: c}", &struct{ A *map[string]string }{&map[string]string{"b": "c"}}, }, { "a:", &struct{ A map[string]string }{}, }, { "a: 1", &struct{ A int }{1}, }, { "a: 1", &struct{ A float64 }{1}, }, { "a: 1.0", &struct{ A int }{1}, }, { "a: 1.0", &struct{ A uint }{1}, }, { "a: [1, 2]", &struct{ A []int }{[]int{1, 2}}, }, { "a: 1", &struct{ B int }{0}, }, { "a: 1", &struct { B int "a" }{1}, }, { "a: y", &struct{ A bool }{true}, }, // Some cross type conversions { "v: 42", map[string]uint{"v": 42}, }, { "v: -42", map[string]uint{}, }, { "v: 4294967296", map[string]uint64{"v": 4294967296}, }, { "v: -4294967296", map[string]uint64{}, }, // int { "int_max: 2147483647", map[string]int{"int_max": math.MaxInt32}, }, { "int_min: -2147483648", map[string]int{"int_min": math.MinInt32}, }, { "int_overflow: 9223372036854775808", // math.MaxInt64 + 1 map[string]int{}, }, // int64 { "int64_max: 9223372036854775807", map[string]int64{"int64_max": math.MaxInt64}, }, { "int64_max_base2: 0b111111111111111111111111111111111111111111111111111111111111111", map[string]int64{"int64_max_base2": math.MaxInt64}, }, { "int64_min: -9223372036854775808", map[string]int64{"int64_min": math.MinInt64}, }, { "int64_neg_base2: -0b111111111111111111111111111111111111111111111111111111111111111", map[string]int64{"int64_neg_base2": -math.MaxInt64}, }, { "int64_overflow: 9223372036854775808", // math.MaxInt64 + 1 map[string]int64{}, }, // uint { "uint_min: 0", map[string]uint{"uint_min": 0}, }, { "uint_max: 4294967295", map[string]uint{"uint_max": math.MaxUint32}, }, { "uint_underflow: -1", map[string]uint{}, }, // uint64 { "uint64_min: 0", map[string]uint{"uint64_min": 0}, }, { "uint64_max: 18446744073709551615", map[string]uint64{"uint64_max": math.MaxUint64}, }, { "uint64_max_base2: 0b1111111111111111111111111111111111111111111111111111111111111111", map[string]uint64{"uint64_max_base2": math.MaxUint64}, }, { "uint64_maxint64: 9223372036854775807", map[string]uint64{"uint64_maxint64": math.MaxInt64}, }, { "uint64_underflow: -1", map[string]uint64{}, }, // float32 { "float32_max: 3.40282346638528859811704183484516925440e+38", map[string]float32{"float32_max": math.MaxFloat32}, }, { "float32_nonzero: 1.401298464324817070923729583289916131280e-45", map[string]float32{"float32_nonzero": math.SmallestNonzeroFloat32}, }, { "float32_maxuint64: 18446744073709551615", map[string]float32{"float32_maxuint64": float32(math.MaxUint64)}, }, { "float32_maxuint64+1: 18446744073709551616", map[string]float32{"float32_maxuint64+1": float32(math.MaxUint64 + 1)}, }, // float64 { "float64_max: 1.797693134862315708145274237317043567981e+308", map[string]float64{"float64_max": math.MaxFloat64}, }, { "float64_nonzero: 4.940656458412465441765687928682213723651e-324", map[string]float64{"float64_nonzero": math.SmallestNonzeroFloat64}, }, { "float64_maxuint64: 18446744073709551615", map[string]float64{"float64_maxuint64": float64(math.MaxUint64)}, }, { "float64_maxuint64+1: 18446744073709551616", map[string]float64{"float64_maxuint64+1": float64(math.MaxUint64 + 1)}, }, // Overflow cases. { "v: 4294967297", map[string]int32{}, }, { "v: 128", map[string]int8{}, }, // Quoted values. { "'1': '\"2\"'", map[interface{}]interface{}{"1": "\"2\""}, }, { "v:\n- A\n- 'B\n\n C'\n", map[string][]string{"v": []string{"A", "B\nC"}}, }, // Explicit tags. { "v: !!float '1.1'", map[string]interface{}{"v": 1.1}, }, { "v: !!null ''", map[string]interface{}{"v": nil}, }, { "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'", map[string]interface{}{"v": 1}, }, // Anchors and aliases. { "a: &x 1\nb: &y 2\nc: *x\nd: *y\n", &struct{ A, B, C, D int }{1, 2, 1, 2}, }, { "a: &a {c: 1}\nb: *a", &struct { A, B struct { C int } }{struct{ C int }{1}, struct{ C int }{1}}, }, { "a: &a [1, 2]\nb: *a", &struct{ B []int }{[]int{1, 2}}, }, { "b: *a\na: &a {c: 1}", &struct { A, B struct { C int } }{struct{ C int }{1}, struct{ C int }{1}}, }, // Bug #1133337 { "foo: ''", map[string]*string{"foo": new(string)}, }, { "foo: null", map[string]string{"foo": ""}, }, { "foo: null", map[string]interface{}{"foo": nil}, }, // Ignored field { "a: 1\nb: 2\n", &struct { A int B int "-" }{1, 0}, }, // Bug #1191981 { "" + "%YAML 1.1\n" + "--- !!str\n" + `"Generic line break (no glyph)\n\` + "\n" + ` Generic line break (glyphed)\n\` + "\n" + ` Line separator\u2028\` + "\n" + ` Paragraph separator\u2029"` + "\n", "" + "Generic line break (no glyph)\n" + "Generic line break (glyphed)\n" + "Line separator\u2028Paragraph separator\u2029", }, // Struct inlining { "a: 1\nb: 2\nc: 3\n", &struct { A int C inlineB `yaml:",inline"` }{1, inlineB{2, inlineC{3}}}, }, // Map inlining { "a: 1\nb: 2\nc: 3\n", &struct { A int C map[string]int `yaml:",inline"` }{1, map[string]int{"b": 2, "c": 3}}, }, // bug 1243827 { "a: -b_c", map[string]interface{}{"a": "-b_c"}, }, { "a: +b_c", map[string]interface{}{"a": "+b_c"}, }, { "a: 50cent_of_dollar", map[string]interface{}{"a": "50cent_of_dollar"}, }, // Duration { "a: 3s", map[string]time.Duration{"a": 3 * time.Second}, }, // Issue #24. { "a: ", map[string]string{"a": ""}, }, // Base 60 floats are obsolete and unsupported. { "a: 1:1\n", map[string]string{"a": "1:1"}, }, // Binary data. { "a: !!binary gIGC\n", map[string]string{"a": "\x80\x81\x82"}, }, { "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", map[string]string{"a": strings.Repeat("\x90", 54)}, }, { "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n", map[string]string{"a": strings.Repeat("\x00", 52)}, }, // Ordered maps. { "{b: 2, a: 1, d: 4, c: 3, sub: {e: 5}}", &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, }, // Issue #39. { "a:\n b:\n c: d\n", map[string]struct{ B interface{} }{"a": {map[interface{}]interface{}{"c": "d"}}}, }, // Custom map type. { "a: {b: c}", M{"a": M{"b": "c"}}, }, // Support encoding.TextUnmarshaler. { "a: 1.2.3.4\n", map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, }, { "a: 2015-02-24T18:19:39Z\n", map[string]time.Time{"a": time.Unix(1424801979, 0)}, }, // Encode empty lists as zero-length slices. { "a: []", &struct{ A []int }{[]int{}}, }, // UTF-16-LE { "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00", M{"ñoño": "very yes"}, }, // UTF-16-LE with surrogate. { "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00", M{"ñoño": "very yes 🟔"}, }, // UTF-16-BE { "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n", M{"ñoño": "very yes"}, }, // UTF-16-BE with surrogate. { "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n", M{"ñoño": "very yes 🟔"}, }, } type M map[interface{}]interface{} type inlineB struct { B int inlineC `yaml:",inline"` } type inlineC struct { C int } func (s *S) TestUnmarshal(c *C) { for _, item := range unmarshalTests { t := reflect.ValueOf(item.value).Type() var value interface{} switch t.Kind() { case reflect.Map: value = reflect.MakeMap(t).Interface() case reflect.String: value = reflect.New(t).Interface() case reflect.Ptr: value = reflect.New(t.Elem()).Interface() default: c.Fatalf("missing case for %s", t) } err := yaml.Unmarshal([]byte(item.data), value) if _, ok := err.(*yaml.TypeError); !ok { c.Assert(err, IsNil) } if t.Kind() == reflect.String { c.Assert(*value.(*string), Equals, item.value) } else { c.Assert(value, DeepEquals, item.value) } } } func (s *S) TestUnmarshalNaN(c *C) { value := map[string]interface{}{} err := yaml.Unmarshal([]byte("notanum: .NaN"), &value) c.Assert(err, IsNil) c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true) } var unmarshalErrorTests = []struct { data, error string }{ {"v: !!float 'error'", "yaml: cannot decode !!str `error` as a !!float"}, {"v: [A,", "yaml: line 1: did not find expected node content"}, {"v:\n- [A,", "yaml: line 2: did not find expected node content"}, {"a: *b\n", "yaml: unknown anchor 'b' referenced"}, {"a: &a\n b: *a\n", "yaml: anchor 'a' value contains itself"}, {"value: -", "yaml: block sequence entries are not allowed in this context"}, {"a: !!binary ==", "yaml: !!binary value contains invalid base64 data"}, {"{[.]}", `yaml: invalid map key: \[\]interface \{\}\{"\."\}`}, {"{{.}}", `yaml: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`}, } func (s *S) TestUnmarshalErrors(c *C) { for _, item := range unmarshalErrorTests { var value interface{} err := yaml.Unmarshal([]byte(item.data), &value) c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value)) } } var unmarshalerTests = []struct { data, tag string value interface{} }{ {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}}, {"_: [1,A]", "!!seq", []interface{}{1, "A"}}, {"_: 10", "!!int", 10}, {"_: null", "!!null", nil}, {`_: BAR!`, "!!str", "BAR!"}, {`_: "BAR!"`, "!!str", "BAR!"}, {"_: !!foo 'BAR!'", "!!foo", "BAR!"}, } var unmarshalerResult = map[int]error{} type unmarshalerType struct { value interface{} } func (o *unmarshalerType) UnmarshalYAML(unmarshal func(v interface{}) error) error { if err := unmarshal(&o.value); err != nil { return err } if i, ok := o.value.(int); ok { if result, ok := unmarshalerResult[i]; ok { return result } } return nil } type unmarshalerPointer struct { Field *unmarshalerType "_" } type unmarshalerValue struct { Field unmarshalerType "_" } func (s *S) TestUnmarshalerPointerField(c *C) { for _, item := range unmarshalerTests { obj := &unmarshalerPointer{} err := yaml.Unmarshal([]byte(item.data), obj) c.Assert(err, IsNil) if item.value == nil { c.Assert(obj.Field, IsNil) } else { c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) c.Assert(obj.Field.value, DeepEquals, item.value) } } } func (s *S) TestUnmarshalerValueField(c *C) { for _, item := range unmarshalerTests { obj := &unmarshalerValue{} err := yaml.Unmarshal([]byte(item.data), obj) c.Assert(err, IsNil) c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value)) c.Assert(obj.Field.value, DeepEquals, item.value) } } func (s *S) TestUnmarshalerWholeDocument(c *C) { obj := &unmarshalerType{} err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj) c.Assert(err, IsNil) value, ok := obj.value.(map[interface{}]interface{}) c.Assert(ok, Equals, true, Commentf("value: %#v", obj.value)) c.Assert(value["_"], DeepEquals, unmarshalerTests[0].value) } func (s *S) TestUnmarshalerTypeError(c *C) { unmarshalerResult[2] = &yaml.TypeError{[]string{"foo"}} unmarshalerResult[4] = &yaml.TypeError{[]string{"bar"}} defer func() { delete(unmarshalerResult, 2) delete(unmarshalerResult, 4) }() type T struct { Before int After int M map[string]*unmarshalerType } var v T data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}` err := yaml.Unmarshal([]byte(data), &v) c.Assert(err, ErrorMatches, ""+ "yaml: unmarshal errors:\n"+ " line 1: cannot unmarshal !!str `A` into int\n"+ " foo\n"+ " bar\n"+ " line 1: cannot unmarshal !!str `B` into int") c.Assert(v.M["abc"], NotNil) c.Assert(v.M["def"], IsNil) c.Assert(v.M["ghi"], NotNil) c.Assert(v.M["jkl"], IsNil) c.Assert(v.M["abc"].value, Equals, 1) c.Assert(v.M["ghi"].value, Equals, 3) } type proxyTypeError struct{} func (v *proxyTypeError) UnmarshalYAML(unmarshal func(interface{}) error) error { var s string var a int32 var b int64 if err := unmarshal(&s); err != nil { panic(err) } if s == "a" { if err := unmarshal(&b); err == nil { panic("should have failed") } return unmarshal(&a) } if err := unmarshal(&a); err == nil { panic("should have failed") } return unmarshal(&b) } func (s *S) TestUnmarshalerTypeErrorProxying(c *C) { type T struct { Before int After int M map[string]*proxyTypeError } var v T data := `{before: A, m: {abc: a, def: b}, after: B}` err := yaml.Unmarshal([]byte(data), &v) c.Assert(err, ErrorMatches, ""+ "yaml: unmarshal errors:\n"+ " line 1: cannot unmarshal !!str `A` into int\n"+ " line 1: cannot unmarshal !!str `a` into int32\n"+ " line 1: cannot unmarshal !!str `b` into int64\n"+ " line 1: cannot unmarshal !!str `B` into int") } type failingUnmarshaler struct{} var failingErr = errors.New("failingErr") func (ft *failingUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { return failingErr } func (s *S) TestUnmarshalerError(c *C) { err := yaml.Unmarshal([]byte("a: b"), &failingUnmarshaler{}) c.Assert(err, Equals, failingErr) } type sliceUnmarshaler []int func (su *sliceUnmarshaler) UnmarshalYAML(unmarshal func(interface{}) error) error { var slice []int err := unmarshal(&slice) if err == nil { *su = slice return nil } var intVal int err = unmarshal(&intVal) if err == nil { *su = []int{intVal} return nil } return err } func (s *S) TestUnmarshalerRetry(c *C) { var su sliceUnmarshaler err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su) c.Assert(err, IsNil) c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1, 2, 3})) err = yaml.Unmarshal([]byte("1"), &su) c.Assert(err, IsNil) c.Assert(su, DeepEquals, sliceUnmarshaler([]int{1})) } // From http://yaml.org/type/merge.html var mergeTests = ` anchors: list: - &CENTER { "x": 1, "y": 2 } - &LEFT { "x": 0, "y": 2 } - &BIG { "r": 10 } - &SMALL { "r": 1 } # All the following maps are equal: plain: # Explicit keys "x": 1 "y": 2 "r": 10 label: center/big mergeOne: # Merge one map << : *CENTER "r": 10 label: center/big mergeMultiple: # Merge multiple maps << : [ *CENTER, *BIG ] label: center/big override: # Override << : [ *BIG, *LEFT, *SMALL ] "x": 1 label: center/big shortTag: # Explicit short merge tag !!merge "<<" : [ *CENTER, *BIG ] label: center/big longTag: # Explicit merge long tag ! "<<" : [ *CENTER, *BIG ] label: center/big inlineMap: # Inlined map << : {"x": 1, "y": 2, "r": 10} label: center/big inlineSequenceMap: # Inlined map in sequence << : [ *CENTER, {"r": 10} ] label: center/big ` func (s *S) TestMerge(c *C) { var want = map[interface{}]interface{}{ "x": 1, "y": 2, "r": 10, "label": "center/big", } var m map[interface{}]interface{} err := yaml.Unmarshal([]byte(mergeTests), &m) c.Assert(err, IsNil) for name, test := range m { if name == "anchors" { continue } c.Assert(test, DeepEquals, want, Commentf("test %q failed", name)) } } func (s *S) TestMergeStruct(c *C) { type Data struct { X, Y, R int Label string } want := Data{1, 2, 10, "center/big"} var m map[string]Data err := yaml.Unmarshal([]byte(mergeTests), &m) c.Assert(err, IsNil) for name, test := range m { if name == "anchors" { continue } c.Assert(test, Equals, want, Commentf("test %q failed", name)) } } var unmarshalNullTests = []func() interface{}{ func() interface{} { var v interface{}; v = "v"; return &v }, func() interface{} { var s = "s"; return &s }, func() interface{} { var s = "s"; sptr := &s; return &sptr }, func() interface{} { var i = 1; return &i }, func() interface{} { var i = 1; iptr := &i; return &iptr }, func() interface{} { m := map[string]int{"s": 1}; return &m }, func() interface{} { m := map[string]int{"s": 1}; return m }, } func (s *S) TestUnmarshalNull(c *C) { for _, test := range unmarshalNullTests { item := test() zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface() err := yaml.Unmarshal([]byte("null"), item) c.Assert(err, IsNil) if reflect.TypeOf(item).Kind() == reflect.Map { c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface()) } else { c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero) } } } func (s *S) TestUnmarshalSliceOnPreset(c *C) { // Issue #48. v := struct{ A []int }{[]int{1}} yaml.Unmarshal([]byte("a: [2]"), &v) c.Assert(v.A, DeepEquals, []int{2}) } //var data []byte //func init() { // var err error // data, err = ioutil.ReadFile("/tmp/file.yaml") // if err != nil { // panic(err) // } //} // //func (s *S) BenchmarkUnmarshal(c *C) { // var err error // for i := 0; i < c.N; i++ { // var v map[string]interface{} // err = yaml.Unmarshal(data, &v) // } // if err != nil { // panic(err) // } //} // //func (s *S) BenchmarkMarshal(c *C) { // var v map[string]interface{} // yaml.Unmarshal(data, &v) // c.ResetTimer() // for i := 0; i < c.N; i++ { // yaml.Marshal(&v) // } //} ================================================ FILE: vendor/gopkg.in/yaml.v2/emitterc.go ================================================ 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/encode.go ================================================ 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() } ================================================ FILE: vendor/gopkg.in/yaml.v2/encode_test.go ================================================ package yaml_test import ( "fmt" "math" "strconv" "strings" "time" . "gopkg.in/check.v1" "gopkg.in/yaml.v2" "net" "os" ) var marshalIntTest = 123 var marshalTests = []struct { value interface{} data string }{ { nil, "null\n", }, { &struct{}{}, "{}\n", }, { map[string]string{"v": "hi"}, "v: hi\n", }, { map[string]interface{}{"v": "hi"}, "v: hi\n", }, { map[string]string{"v": "true"}, "v: \"true\"\n", }, { map[string]string{"v": "false"}, "v: \"false\"\n", }, { map[string]interface{}{"v": true}, "v: true\n", }, { map[string]interface{}{"v": false}, "v: false\n", }, { map[string]interface{}{"v": 10}, "v: 10\n", }, { map[string]interface{}{"v": -10}, "v: -10\n", }, { map[string]uint{"v": 42}, "v: 42\n", }, { map[string]interface{}{"v": int64(4294967296)}, "v: 4294967296\n", }, { map[string]int64{"v": int64(4294967296)}, "v: 4294967296\n", }, { map[string]uint64{"v": 4294967296}, "v: 4294967296\n", }, { map[string]interface{}{"v": "10"}, "v: \"10\"\n", }, { map[string]interface{}{"v": 0.1}, "v: 0.1\n", }, { map[string]interface{}{"v": float64(0.1)}, "v: 0.1\n", }, { map[string]interface{}{"v": -0.1}, "v: -0.1\n", }, { map[string]interface{}{"v": math.Inf(+1)}, "v: .inf\n", }, { map[string]interface{}{"v": math.Inf(-1)}, "v: -.inf\n", }, { map[string]interface{}{"v": math.NaN()}, "v: .nan\n", }, { map[string]interface{}{"v": nil}, "v: null\n", }, { map[string]interface{}{"v": ""}, "v: \"\"\n", }, { map[string][]string{"v": []string{"A", "B"}}, "v:\n- A\n- B\n", }, { map[string][]string{"v": []string{"A", "B\nC"}}, "v:\n- A\n- |-\n B\n C\n", }, { map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}}, "v:\n- A\n- 1\n- B:\n - 2\n - 3\n", }, { map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}}, "a:\n b: c\n", }, { map[string]interface{}{"a": "-"}, "a: '-'\n", }, // Simple values. { &marshalIntTest, "123\n", }, // Structures { &struct{ Hello string }{"world"}, "hello: world\n", }, { &struct { A struct { B string } }{struct{ B string }{"c"}}, "a:\n b: c\n", }, { &struct { A *struct { B string } }{&struct{ B string }{"c"}}, "a:\n b: c\n", }, { &struct { A *struct { B string } }{}, "a: null\n", }, { &struct{ A int }{1}, "a: 1\n", }, { &struct{ A []int }{[]int{1, 2}}, "a:\n- 1\n- 2\n", }, { &struct { B int "a" }{1}, "a: 1\n", }, { &struct{ A bool }{true}, "a: true\n", }, // Conditional flag { &struct { A int "a,omitempty" B int "b,omitempty" }{1, 0}, "a: 1\n", }, { &struct { A int "a,omitempty" B int "b,omitempty" }{0, 0}, "{}\n", }, { &struct { A *struct{ X, y int } "a,omitempty,flow" }{&struct{ X, y int }{1, 2}}, "a: {x: 1}\n", }, { &struct { A *struct{ X, y int } "a,omitempty,flow" }{nil}, "{}\n", }, { &struct { A *struct{ X, y int } "a,omitempty,flow" }{&struct{ X, y int }{}}, "a: {x: 0}\n", }, { &struct { A struct{ X, y int } "a,omitempty,flow" }{struct{ X, y int }{1, 2}}, "a: {x: 1}\n", }, { &struct { A struct{ X, y int } "a,omitempty,flow" }{struct{ X, y int }{0, 1}}, "{}\n", }, { &struct { A float64 "a,omitempty" B float64 "b,omitempty" }{1, 0}, "a: 1\n", }, // Flow flag { &struct { A []int "a,flow" }{[]int{1, 2}}, "a: [1, 2]\n", }, { &struct { A map[string]string "a,flow" }{map[string]string{"b": "c", "d": "e"}}, "a: {b: c, d: e}\n", }, { &struct { A struct { B, D string } "a,flow" }{struct{ B, D string }{"c", "e"}}, "a: {b: c, d: e}\n", }, // Unexported field { &struct { u int A int }{0, 1}, "a: 1\n", }, // Ignored field { &struct { A int B int "-" }{1, 2}, "a: 1\n", }, // Struct inlining { &struct { A int C inlineB `yaml:",inline"` }{1, inlineB{2, inlineC{3}}}, "a: 1\nb: 2\nc: 3\n", }, // Map inlining { &struct { A int C map[string]int `yaml:",inline"` }{1, map[string]int{"b": 2, "c": 3}}, "a: 1\nb: 2\nc: 3\n", }, // Duration { map[string]time.Duration{"a": 3 * time.Second}, "a: 3s\n", }, // Issue #24: bug in map merging logic. { map[string]string{"a": ""}, "a: \n", }, // Issue #34: marshal unsupported base 60 floats quoted for compatibility // with old YAML 1.1 parsers. { map[string]string{"a": "1:1"}, "a: \"1:1\"\n", }, // Binary data. { map[string]string{"a": "\x00"}, "a: \"\\0\"\n", }, { map[string]string{"a": "\x80\x81\x82"}, "a: !!binary gIGC\n", }, { map[string]string{"a": strings.Repeat("\x90", 54)}, "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n", }, // Ordered maps. { &yaml.MapSlice{{"b", 2}, {"a", 1}, {"d", 4}, {"c", 3}, {"sub", yaml.MapSlice{{"e", 5}}}}, "b: 2\na: 1\nd: 4\nc: 3\nsub:\n e: 5\n", }, // Encode unicode as utf-8 rather than in escaped form. { map[string]string{"a": "你好"}, "a: 你好\n", }, // Support encoding.TextMarshaler. { map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)}, "a: 1.2.3.4\n", }, { map[string]time.Time{"a": time.Unix(1424801979, 0)}, "a: 2015-02-24T18:19:39Z\n", }, // Ensure strings containing ": " are quoted (reported as PR #43, but not reproducible). { map[string]string{"a": "b: c"}, "a: 'b: c'\n", }, // Containing hash mark ('#') in string should be quoted { map[string]string{"a": "Hello #comment"}, "a: 'Hello #comment'\n", }, { map[string]string{"a": "你好 #comment"}, "a: '你好 #comment'\n", }, } func (s *S) TestMarshal(c *C) { defer os.Setenv("TZ", os.Getenv("TZ")) os.Setenv("TZ", "UTC") for _, item := range marshalTests { data, err := yaml.Marshal(item.value) c.Assert(err, IsNil) c.Assert(string(data), Equals, item.data) } } var marshalErrorTests = []struct { value interface{} error string panic string }{{ value: &struct { B int inlineB ",inline" }{1, inlineB{2, inlineC{3}}}, panic: `Duplicated key 'b' in struct struct \{ B int; .*`, }, { value: &struct { A int B map[string]int ",inline" }{1, map[string]int{"a": 2}}, panic: `Can't have key "a" in inlined map; conflicts with struct field`, }} func (s *S) TestMarshalErrors(c *C) { for _, item := range marshalErrorTests { if item.panic != "" { c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic) } else { _, err := yaml.Marshal(item.value) c.Assert(err, ErrorMatches, item.error) } } } func (s *S) TestMarshalTypeCache(c *C) { var data []byte var err error func() { type T struct{ A int } data, err = yaml.Marshal(&T{}) c.Assert(err, IsNil) }() func() { type T struct{ B int } data, err = yaml.Marshal(&T{}) c.Assert(err, IsNil) }() c.Assert(string(data), Equals, "b: 0\n") } var marshalerTests = []struct { data string value interface{} }{ {"_:\n hi: there\n", map[interface{}]interface{}{"hi": "there"}}, {"_:\n- 1\n- A\n", []interface{}{1, "A"}}, {"_: 10\n", 10}, {"_: null\n", nil}, {"_: BAR!\n", "BAR!"}, } type marshalerType struct { value interface{} } func (o marshalerType) MarshalText() ([]byte, error) { panic("MarshalText called on type with MarshalYAML") } func (o marshalerType) MarshalYAML() (interface{}, error) { return o.value, nil } type marshalerValue struct { Field marshalerType "_" } func (s *S) TestMarshaler(c *C) { for _, item := range marshalerTests { obj := &marshalerValue{} obj.Field.value = item.value data, err := yaml.Marshal(obj) c.Assert(err, IsNil) c.Assert(string(data), Equals, string(item.data)) } } func (s *S) TestMarshalerWholeDocument(c *C) { obj := &marshalerType{} obj.value = map[string]string{"hello": "world!"} data, err := yaml.Marshal(obj) c.Assert(err, IsNil) c.Assert(string(data), Equals, "hello: world!\n") } type failingMarshaler struct{} func (ft *failingMarshaler) MarshalYAML() (interface{}, error) { return nil, failingErr } func (s *S) TestMarshalerError(c *C) { _, err := yaml.Marshal(&failingMarshaler{}) c.Assert(err, Equals, failingErr) } func (s *S) TestSortedOutput(c *C) { order := []interface{}{ false, true, 1, uint(1), 1.0, 1.1, 1.2, 2, uint(2), 2.0, 2.1, "", ".1", ".2", ".a", "1", "2", "a!10", "a/2", "a/10", "a~10", "ab/1", "b/1", "b/01", "b/2", "b/02", "b/3", "b/03", "b1", "b01", "b3", "c2.10", "c10.2", "d1", "d12", "d12a", } m := make(map[interface{}]int) for _, k := range order { m[k] = 1 } data, err := yaml.Marshal(m) c.Assert(err, IsNil) out := "\n" + string(data) last := 0 for i, k := range order { repr := fmt.Sprint(k) if s, ok := k.(string); ok { if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil { repr = `"` + repr + `"` } } index := strings.Index(out, "\n"+repr+":") if index == -1 { c.Fatalf("%#v is not in the output: %#v", k, out) } if index < last { c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out) } last = index } } ================================================ FILE: vendor/gopkg.in/yaml.v2/parserc.go ================================================ 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 ", 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 ", 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/readerc.go ================================================ 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/resolve.go ================================================ package yaml import ( "encoding/base64" "math" "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 } 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 } 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]) } ================================================ FILE: vendor/gopkg.in/yaml.v2/scannerc.go ================================================ 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/sorter.go ================================================ 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") } ================================================ FILE: vendor/gopkg.in/yaml.v2/suite_test.go ================================================ package yaml_test import ( . "gopkg.in/check.v1" "testing" ) func Test(t *testing.T) { TestingT(t) } type S struct{} var _ = Suite(&S{}) ================================================ FILE: vendor/gopkg.in/yaml.v2/writerc.go ================================================ 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/yaml.go ================================================ // 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:"[][,[,]]" (...)` // // 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 } ================================================ FILE: vendor/gopkg.in/yaml.v2/yamlh.go ================================================ 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 "" } // 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 "" } // 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. } ================================================ FILE: vendor/gopkg.in/yaml.v2/yamlprivateh.go ================================================ 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 } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/LICENSE ================================================ Copyright (c) 2012 Péter Surányi. 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 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. ---------------------------------------------------------------------- Portions of inf.Dec's source code have been derived from Go and are covered by the following license: ---------------------------------------------------------------------- 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. ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/benchmark_test.go ================================================ package inf import ( "fmt" "math/big" "math/rand" "sync" "testing" ) const maxcap = 1024 * 1024 const bits = 256 const maxscale = 32 var once sync.Once var decInput [][2]Dec var intInput [][2]big.Int var initBench = func() { decInput = make([][2]Dec, maxcap) intInput = make([][2]big.Int, maxcap) max := new(big.Int).Lsh(big.NewInt(1), bits) r := rand.New(rand.NewSource(0)) for i := 0; i < cap(decInput); i++ { decInput[i][0].SetUnscaledBig(new(big.Int).Rand(r, max)). SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale))) decInput[i][1].SetUnscaledBig(new(big.Int).Rand(r, max)). SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale))) } for i := 0; i < cap(intInput); i++ { intInput[i][0].Rand(r, max) intInput[i][1].Rand(r, max) } } func doBenchmarkDec1(b *testing.B, f func(z *Dec)) { once.Do(initBench) b.ResetTimer() b.StartTimer() for i := 0; i < b.N; i++ { f(&decInput[i%maxcap][0]) } } func doBenchmarkDec2(b *testing.B, f func(x, y *Dec)) { once.Do(initBench) b.ResetTimer() b.StartTimer() for i := 0; i < b.N; i++ { f(&decInput[i%maxcap][0], &decInput[i%maxcap][1]) } } func doBenchmarkInt1(b *testing.B, f func(z *big.Int)) { once.Do(initBench) b.ResetTimer() b.StartTimer() for i := 0; i < b.N; i++ { f(&intInput[i%maxcap][0]) } } func doBenchmarkInt2(b *testing.B, f func(x, y *big.Int)) { once.Do(initBench) b.ResetTimer() b.StartTimer() for i := 0; i < b.N; i++ { f(&intInput[i%maxcap][0], &intInput[i%maxcap][1]) } } func Benchmark_Dec_String(b *testing.B) { doBenchmarkDec1(b, func(x *Dec) { x.String() }) } func Benchmark_Dec_StringScan(b *testing.B) { doBenchmarkDec1(b, func(x *Dec) { s := x.String() d := new(Dec) fmt.Sscan(s, d) }) } func Benchmark_Dec_GobEncode(b *testing.B) { doBenchmarkDec1(b, func(x *Dec) { x.GobEncode() }) } func Benchmark_Dec_GobEnDecode(b *testing.B) { doBenchmarkDec1(b, func(x *Dec) { g, _ := x.GobEncode() new(Dec).GobDecode(g) }) } func Benchmark_Dec_Add(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { ys := y.Scale() y.SetScale(x.Scale()) _ = new(Dec).Add(x, y) y.SetScale(ys) }) } func Benchmark_Dec_AddMixed(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { _ = new(Dec).Add(x, y) }) } func Benchmark_Dec_Sub(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { ys := y.Scale() y.SetScale(x.Scale()) _ = new(Dec).Sub(x, y) y.SetScale(ys) }) } func Benchmark_Dec_SubMixed(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { _ = new(Dec).Sub(x, y) }) } func Benchmark_Dec_Mul(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { _ = new(Dec).Mul(x, y) }) } func Benchmark_Dec_Mul_QuoExact(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { v := new(Dec).Mul(x, y) _ = new(Dec).QuoExact(v, y) }) } func Benchmark_Dec_QuoRound_Fixed_Down(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { _ = new(Dec).QuoRound(x, y, 0, RoundDown) }) } func Benchmark_Dec_QuoRound_Fixed_HalfUp(b *testing.B) { doBenchmarkDec2(b, func(x, y *Dec) { _ = new(Dec).QuoRound(x, y, 0, RoundHalfUp) }) } func Benchmark_Int_String(b *testing.B) { doBenchmarkInt1(b, func(x *big.Int) { x.String() }) } func Benchmark_Int_StringScan(b *testing.B) { doBenchmarkInt1(b, func(x *big.Int) { s := x.String() d := new(big.Int) fmt.Sscan(s, d) }) } func Benchmark_Int_GobEncode(b *testing.B) { doBenchmarkInt1(b, func(x *big.Int) { x.GobEncode() }) } func Benchmark_Int_GobEnDecode(b *testing.B) { doBenchmarkInt1(b, func(x *big.Int) { g, _ := x.GobEncode() new(big.Int).GobDecode(g) }) } func Benchmark_Int_Add(b *testing.B) { doBenchmarkInt2(b, func(x, y *big.Int) { _ = new(big.Int).Add(x, y) }) } func Benchmark_Int_Sub(b *testing.B) { doBenchmarkInt2(b, func(x, y *big.Int) { _ = new(big.Int).Sub(x, y) }) } func Benchmark_Int_Mul(b *testing.B) { doBenchmarkInt2(b, func(x, y *big.Int) { _ = new(big.Int).Mul(x, y) }) } func Benchmark_Int_Quo(b *testing.B) { doBenchmarkInt2(b, func(x, y *big.Int) { _ = new(big.Int).Quo(x, y) }) } func Benchmark_Int_QuoRem(b *testing.B) { doBenchmarkInt2(b, func(x, y *big.Int) { _, _ = new(big.Int).QuoRem(x, y, new(big.Int)) }) } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/dec.go ================================================ // Package inf (type inf.Dec) implements "infinite-precision" decimal // arithmetic. // "Infinite precision" describes two characteristics: practically unlimited // precision for decimal number representation and no support for calculating // with any specific fixed precision. // (Although there is no practical limit on precision, inf.Dec can only // represent finite decimals.) // // This package is currently in experimental stage and the API may change. // // This package does NOT support: // - rounding to specific precisions (as opposed to specific decimal positions) // - the notion of context (each rounding must be explicit) // - NaN and Inf values, and distinguishing between positive and negative zero // - conversions to and from float32/64 types // // Features considered for possible addition: // + formatting options // + Exp method // + combined operations such as AddRound/MulAdd etc // + exchanging data in decimal32/64/128 formats // package inf // TODO: // - avoid excessive deep copying (quo and rounders) import ( "fmt" "io" "math/big" "strings" ) // A Dec represents a signed arbitrary-precision decimal. // It is a combination of a sign, an arbitrary-precision integer coefficient // value, and a signed fixed-precision exponent value. // The sign and the coefficient value are handled together as a signed value // and referred to as the unscaled value. // (Positive and negative zero values are not distinguished.) // Since the exponent is most commonly non-positive, it is handled in negated // form and referred to as scale. // // The mathematical value of a Dec equals: // // unscaled * 10**(-scale) // // Note that different Dec representations may have equal mathematical values. // // unscaled scale String() // ------------------------- // 0 0 "0" // 0 2 "0.00" // 0 -2 "0" // 1 0 "1" // 100 2 "1.00" // 10 0 "10" // 1 -1 "10" // // The zero value for a Dec represents the value 0 with scale 0. // // Operations are typically performed through the *Dec type. // The semantics of the assignment operation "=" for "bare" Dec values is // undefined and should not be relied on. // // Methods are typically of the form: // // func (z *Dec) Op(x, y *Dec) *Dec // // and implement operations z = x Op y with the result as receiver; if it // is one of the operands it may be overwritten (and its memory reused). // To enable chaining of operations, the result is also returned. Methods // returning a result other than *Dec take one of the operands as the receiver. // // A "bare" Quo method (quotient / division operation) is not provided, as the // result is not always a finite decimal and thus in general cannot be // represented as a Dec. // Instead, in the common case when rounding is (potentially) necessary, // QuoRound should be used with a Scale and a Rounder. // QuoExact or QuoRound with RoundExact can be used in the special cases when it // is known that the result is always a finite decimal. // type Dec struct { unscaled big.Int scale Scale } // Scale represents the type used for the scale of a Dec. type Scale int32 const scaleSize = 4 // bytes in a Scale value // Scaler represents a method for obtaining the scale to use for the result of // an operation on x and y. type scaler interface { Scale(x *Dec, y *Dec) Scale } var bigInt = [...]*big.Int{ big.NewInt(0), big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4), big.NewInt(5), big.NewInt(6), big.NewInt(7), big.NewInt(8), big.NewInt(9), big.NewInt(10), } var exp10cache [64]big.Int = func() [64]big.Int { e10, e10i := [64]big.Int{}, bigInt[1] for i, _ := range e10 { e10[i].Set(e10i) e10i = new(big.Int).Mul(e10i, bigInt[10]) } return e10 }() // NewDec allocates and returns a new Dec set to the given int64 unscaled value // and scale. func NewDec(unscaled int64, scale Scale) *Dec { return new(Dec).SetUnscaled(unscaled).SetScale(scale) } // NewDecBig allocates and returns a new Dec set to the given *big.Int unscaled // value and scale. func NewDecBig(unscaled *big.Int, scale Scale) *Dec { return new(Dec).SetUnscaledBig(unscaled).SetScale(scale) } // Scale returns the scale of x. func (x *Dec) Scale() Scale { return x.scale } // Unscaled returns the unscaled value of x for u and true for ok when the // unscaled value can be represented as int64; otherwise it returns an undefined // int64 value for u and false for ok. Use x.UnscaledBig().Int64() to avoid // checking the validity of the value when the check is known to be redundant. func (x *Dec) Unscaled() (u int64, ok bool) { u = x.unscaled.Int64() var i big.Int ok = i.SetInt64(u).Cmp(&x.unscaled) == 0 return } // UnscaledBig returns the unscaled value of x as *big.Int. func (x *Dec) UnscaledBig() *big.Int { return &x.unscaled } // SetScale sets the scale of z, with the unscaled value unchanged, and returns // z. // The mathematical value of the Dec changes as if it was multiplied by // 10**(oldscale-scale). func (z *Dec) SetScale(scale Scale) *Dec { z.scale = scale return z } // SetUnscaled sets the unscaled value of z, with the scale unchanged, and // returns z. func (z *Dec) SetUnscaled(unscaled int64) *Dec { z.unscaled.SetInt64(unscaled) return z } // SetUnscaledBig sets the unscaled value of z, with the scale unchanged, and // returns z. func (z *Dec) SetUnscaledBig(unscaled *big.Int) *Dec { z.unscaled.Set(unscaled) return z } // Set sets z to the value of x and returns z. // It does nothing if z == x. func (z *Dec) Set(x *Dec) *Dec { if z != x { z.SetUnscaledBig(x.UnscaledBig()) z.SetScale(x.Scale()) } return z } // Sign returns: // // -1 if x < 0 // 0 if x == 0 // +1 if x > 0 // func (x *Dec) Sign() int { return x.UnscaledBig().Sign() } // Neg sets z to -x and returns z. func (z *Dec) Neg(x *Dec) *Dec { z.SetScale(x.Scale()) z.UnscaledBig().Neg(x.UnscaledBig()) return z } // Cmp compares x and y and returns: // // -1 if x < y // 0 if x == y // +1 if x > y // func (x *Dec) Cmp(y *Dec) int { xx, yy := upscale(x, y) return xx.UnscaledBig().Cmp(yy.UnscaledBig()) } // Abs sets z to |x| (the absolute value of x) and returns z. func (z *Dec) Abs(x *Dec) *Dec { z.SetScale(x.Scale()) z.UnscaledBig().Abs(x.UnscaledBig()) return z } // Add sets z to the sum x+y and returns z. // The scale of z is the greater of the scales of x and y. func (z *Dec) Add(x, y *Dec) *Dec { xx, yy := upscale(x, y) z.SetScale(xx.Scale()) z.UnscaledBig().Add(xx.UnscaledBig(), yy.UnscaledBig()) return z } // Sub sets z to the difference x-y and returns z. // The scale of z is the greater of the scales of x and y. func (z *Dec) Sub(x, y *Dec) *Dec { xx, yy := upscale(x, y) z.SetScale(xx.Scale()) z.UnscaledBig().Sub(xx.UnscaledBig(), yy.UnscaledBig()) return z } // Mul sets z to the product x*y and returns z. // The scale of z is the sum of the scales of x and y. func (z *Dec) Mul(x, y *Dec) *Dec { z.SetScale(x.Scale() + y.Scale()) z.UnscaledBig().Mul(x.UnscaledBig(), y.UnscaledBig()) return z } // Round sets z to the value of x rounded to Scale s using Rounder r, and // returns z. func (z *Dec) Round(x *Dec, s Scale, r Rounder) *Dec { return z.QuoRound(x, NewDec(1, 0), s, r) } // QuoRound sets z to the quotient x/y, rounded using the given Rounder to the // specified scale. // // If the rounder is RoundExact but the result can not be expressed exactly at // the specified scale, QuoRound returns nil, and the value of z is undefined. // // There is no corresponding Div method; the equivalent can be achieved through // the choice of Rounder used. // func (z *Dec) QuoRound(x, y *Dec, s Scale, r Rounder) *Dec { return z.quo(x, y, sclr{s}, r) } func (z *Dec) quo(x, y *Dec, s scaler, r Rounder) *Dec { scl := s.Scale(x, y) var zzz *Dec if r.UseRemainder() { zz, rA, rB := new(Dec).quoRem(x, y, scl, true, new(big.Int), new(big.Int)) zzz = r.Round(new(Dec), zz, rA, rB) } else { zz, _, _ := new(Dec).quoRem(x, y, scl, false, nil, nil) zzz = r.Round(new(Dec), zz, nil, nil) } if zzz == nil { return nil } return z.Set(zzz) } // QuoExact sets z to the quotient x/y and returns z when x/y is a finite // decimal. Otherwise it returns nil and the value of z is undefined. // // The scale of a non-nil result is "x.Scale() - y.Scale()" or greater; it is // calculated so that the remainder will be zero whenever x/y is a finite // decimal. func (z *Dec) QuoExact(x, y *Dec) *Dec { return z.quo(x, y, scaleQuoExact{}, RoundExact) } // quoRem sets z to the quotient x/y with the scale s, and if useRem is true, // it sets remNum and remDen to the numerator and denominator of the remainder. // It returns z, remNum and remDen. // // The remainder is normalized to the range -1 < r < 1 to simplify rounding; // that is, the results satisfy the following equation: // // x / y = z + (remNum/remDen) * 10**(-z.Scale()) // // See Rounder for more details about rounding. // func (z *Dec) quoRem(x, y *Dec, s Scale, useRem bool, remNum, remDen *big.Int) (*Dec, *big.Int, *big.Int) { // difference (required adjustment) compared to "canonical" result scale shift := s - (x.Scale() - y.Scale()) // pointers to adjusted unscaled dividend and divisor var ix, iy *big.Int switch { case shift > 0: // increased scale: decimal-shift dividend left ix = new(big.Int).Mul(x.UnscaledBig(), exp10(shift)) iy = y.UnscaledBig() case shift < 0: // decreased scale: decimal-shift divisor left ix = x.UnscaledBig() iy = new(big.Int).Mul(y.UnscaledBig(), exp10(-shift)) default: ix = x.UnscaledBig() iy = y.UnscaledBig() } // save a copy of iy in case it to be overwritten with the result iy2 := iy if iy == z.UnscaledBig() { iy2 = new(big.Int).Set(iy) } // set scale z.SetScale(s) // set unscaled if useRem { // Int division _, intr := z.UnscaledBig().QuoRem(ix, iy, new(big.Int)) // set remainder remNum.Set(intr) remDen.Set(iy2) } else { z.UnscaledBig().Quo(ix, iy) } return z, remNum, remDen } type sclr struct{ s Scale } func (s sclr) Scale(x, y *Dec) Scale { return s.s } type scaleQuoExact struct{} func (sqe scaleQuoExact) Scale(x, y *Dec) Scale { rem := new(big.Rat).SetFrac(x.UnscaledBig(), y.UnscaledBig()) f2, f5 := factor2(rem.Denom()), factor(rem.Denom(), bigInt[5]) var f10 Scale if f2 > f5 { f10 = Scale(f2) } else { f10 = Scale(f5) } return x.Scale() - y.Scale() + f10 } func factor(n *big.Int, p *big.Int) int { // could be improved for large factors d, f := n, 0 for { dd, dm := new(big.Int).DivMod(d, p, new(big.Int)) if dm.Sign() == 0 { f++ d = dd } else { break } } return f } func factor2(n *big.Int) int { // could be improved for large factors f := 0 for ; n.Bit(f) == 0; f++ { } return f } func upscale(a, b *Dec) (*Dec, *Dec) { if a.Scale() == b.Scale() { return a, b } if a.Scale() > b.Scale() { bb := b.rescale(a.Scale()) return a, bb } aa := a.rescale(b.Scale()) return aa, b } func exp10(x Scale) *big.Int { if int(x) < len(exp10cache) { return &exp10cache[int(x)] } return new(big.Int).Exp(bigInt[10], big.NewInt(int64(x)), nil) } func (x *Dec) rescale(newScale Scale) *Dec { shift := newScale - x.Scale() switch { case shift < 0: e := exp10(-shift) return NewDecBig(new(big.Int).Quo(x.UnscaledBig(), e), newScale) case shift > 0: e := exp10(shift) return NewDecBig(new(big.Int).Mul(x.UnscaledBig(), e), newScale) } return x } var zeros = []byte("00000000000000000000000000000000" + "00000000000000000000000000000000") var lzeros = Scale(len(zeros)) func appendZeros(s []byte, n Scale) []byte { for i := Scale(0); i < n; i += lzeros { if n > i+lzeros { s = append(s, zeros...) } else { s = append(s, zeros[0:n-i]...) } } return s } func (x *Dec) String() string { if x == nil { return "" } scale := x.Scale() s := []byte(x.UnscaledBig().String()) if scale <= 0 { if scale != 0 && x.unscaled.Sign() != 0 { s = appendZeros(s, -scale) } return string(s) } negbit := Scale(-((x.Sign() - 1) / 2)) // scale > 0 lens := Scale(len(s)) if lens-negbit <= scale { ss := make([]byte, 0, scale+2) if negbit == 1 { ss = append(ss, '-') } ss = append(ss, '0', '.') ss = appendZeros(ss, scale-lens+negbit) ss = append(ss, s[negbit:]...) return string(ss) } // lens > scale ss := make([]byte, 0, lens+1) ss = append(ss, s[:lens-scale]...) ss = append(ss, '.') ss = append(ss, s[lens-scale:]...) return string(ss) } // Format is a support routine for fmt.Formatter. It accepts the decimal // formats 'd' and 'f', and handles both equivalently. // Width, precision, flags and bases 2, 8, 16 are not supported. func (x *Dec) Format(s fmt.State, ch rune) { if ch != 'd' && ch != 'f' && ch != 'v' && ch != 's' { fmt.Fprintf(s, "%%!%c(dec.Dec=%s)", ch, x.String()) return } fmt.Fprintf(s, x.String()) } func (z *Dec) scan(r io.RuneScanner) (*Dec, error) { unscaled := make([]byte, 0, 256) // collects chars of unscaled as bytes dp, dg := -1, -1 // indexes of decimal point, first digit loop: for { ch, _, err := r.ReadRune() if err == io.EOF { break loop } if err != nil { return nil, err } switch { case ch == '+' || ch == '-': if len(unscaled) > 0 || dp >= 0 { // must be first character r.UnreadRune() break loop } case ch == '.': if dp >= 0 { r.UnreadRune() break loop } dp = len(unscaled) continue // don't add to unscaled case ch >= '0' && ch <= '9': if dg == -1 { dg = len(unscaled) } default: r.UnreadRune() break loop } unscaled = append(unscaled, byte(ch)) } if dg == -1 { return nil, fmt.Errorf("no digits read") } if dp >= 0 { z.SetScale(Scale(len(unscaled) - dp)) } else { z.SetScale(0) } _, ok := z.UnscaledBig().SetString(string(unscaled), 10) if !ok { return nil, fmt.Errorf("invalid decimal: %s", string(unscaled)) } return z, nil } // SetString sets z to the value of s, interpreted as a decimal (base 10), // and returns z and a boolean indicating success. The scale of z is the // number of digits after the decimal point (including any trailing 0s), // or 0 if there is no decimal point. If SetString fails, the value of z // is undefined but the returned value is nil. func (z *Dec) SetString(s string) (*Dec, bool) { r := strings.NewReader(s) _, err := z.scan(r) if err != nil { return nil, false } _, _, err = r.ReadRune() if err != io.EOF { return nil, false } // err == io.EOF => scan consumed all of s return z, true } // Scan is a support routine for fmt.Scanner; it sets z to the value of // the scanned number. It accepts the decimal formats 'd' and 'f', and // handles both equivalently. Bases 2, 8, 16 are not supported. // The scale of z is the number of digits after the decimal point // (including any trailing 0s), or 0 if there is no decimal point. func (z *Dec) Scan(s fmt.ScanState, ch rune) error { if ch != 'd' && ch != 'f' && ch != 's' && ch != 'v' { return fmt.Errorf("Dec.Scan: invalid verb '%c'", ch) } s.SkipSpace() _, err := z.scan(s) return err } // Gob encoding version const decGobVersion byte = 1 func scaleBytes(s Scale) []byte { buf := make([]byte, scaleSize) i := scaleSize for j := 0; j < scaleSize; j++ { i-- buf[i] = byte(s) s >>= 8 } return buf } func scale(b []byte) (s Scale) { for j := 0; j < scaleSize; j++ { s <<= 8 s |= Scale(b[j]) } return } // GobEncode implements the gob.GobEncoder interface. func (x *Dec) GobEncode() ([]byte, error) { buf, err := x.UnscaledBig().GobEncode() if err != nil { return nil, err } buf = append(append(buf, scaleBytes(x.Scale())...), decGobVersion) return buf, nil } // GobDecode implements the gob.GobDecoder interface. func (z *Dec) GobDecode(buf []byte) error { if len(buf) == 0 { return fmt.Errorf("Dec.GobDecode: no data") } b := buf[len(buf)-1] if b != decGobVersion { return fmt.Errorf("Dec.GobDecode: encoding version %d not supported", b) } l := len(buf) - scaleSize - 1 err := z.UnscaledBig().GobDecode(buf[:l]) if err != nil { return err } z.SetScale(scale(buf[l : l+scaleSize])) return nil } // MarshalText implements the encoding.TextMarshaler interface. func (x *Dec) MarshalText() ([]byte, error) { return []byte(x.String()), nil } // UnmarshalText implements the encoding.TextUnmarshaler interface. func (z *Dec) UnmarshalText(data []byte) error { _, ok := z.SetString(string(data)) if !ok { return fmt.Errorf("invalid inf.Dec") } return nil } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/dec_go1_2_test.go ================================================ // +build go1.2 package inf import ( "encoding" "encoding/json" "testing" ) var _ encoding.TextMarshaler = new(Dec) var _ encoding.TextUnmarshaler = new(Dec) type Obj struct { Val *Dec } func TestDecJsonMarshalUnmarshal(t *testing.T) { o := Obj{Val: NewDec(123, 2)} js, err := json.Marshal(o) if err != nil { t.Fatalf("json.Marshal(%v): got %v, want ok", o, err) } o2 := &Obj{} err = json.Unmarshal(js, o2) if err != nil { t.Fatalf("json.Unmarshal(%#q): got %v, want ok", js, err) } if o.Val.Scale() != o2.Val.Scale() || o.Val.UnscaledBig().Cmp(o2.Val.UnscaledBig()) != 0 { t.Fatalf("json.Unmarshal(json.Marshal(%v)): want %v, got %v", o, o, o2) } } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/dec_internal_test.go ================================================ package inf import ( "math/big" "testing" ) var decQuoRemZZZ = []struct { z, x, y *Dec r *big.Rat srA, srB int }{ // basic examples {NewDec(1, 0), NewDec(2, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1}, {NewDec(15, 1), NewDec(3, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1}, {NewDec(1, 1), NewDec(1, 0), NewDec(10, 0), big.NewRat(0, 1), 0, 1}, {NewDec(0, 0), NewDec(2, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1}, {NewDec(0, 0), NewDec(2, 0), NewDec(6, 0), big.NewRat(1, 3), 1, 1}, {NewDec(1, 1), NewDec(2, 0), NewDec(12, 0), big.NewRat(2, 3), 1, 1}, // examples from the Go Language Specification {NewDec(1, 0), NewDec(5, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1}, {NewDec(-1, 0), NewDec(-5, 0), NewDec(3, 0), big.NewRat(-2, 3), -1, 1}, {NewDec(-1, 0), NewDec(5, 0), NewDec(-3, 0), big.NewRat(-2, 3), 1, -1}, {NewDec(1, 0), NewDec(-5, 0), NewDec(-3, 0), big.NewRat(2, 3), -1, -1}, } func TestDecQuoRem(t *testing.T) { for i, a := range decQuoRemZZZ { z, rA, rB := new(Dec), new(big.Int), new(big.Int) s := scaleQuoExact{}.Scale(a.x, a.y) z.quoRem(a.x, a.y, s, true, rA, rB) if a.z.Cmp(z) != 0 || a.r.Cmp(new(big.Rat).SetFrac(rA, rB)) != 0 { t.Errorf("#%d QuoRemZZZ got %v, %v, %v; expected %v, %v", i, z, rA, rB, a.z, a.r) } if a.srA != rA.Sign() || a.srB != rB.Sign() { t.Errorf("#%d QuoRemZZZ wrong signs, got %v, %v; expected %v, %v", i, rA.Sign(), rB.Sign(), a.srA, a.srB) } } } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/dec_test.go ================================================ package inf_test import ( "bytes" "encoding/gob" "fmt" "math/big" "strings" "testing" "speter.net/go/exp/math/dec/inf" ) type decFunZZ func(z, x, y *inf.Dec) *inf.Dec type decArgZZ struct { z, x, y *inf.Dec } var decSumZZ = []decArgZZ{ {inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)}, {inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)}, {inf.NewDec(1111111110, 0), inf.NewDec(123456789, 0), inf.NewDec(987654321, 0)}, {inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(0, 0)}, {inf.NewDec(864197532, 0), inf.NewDec(-123456789, 0), inf.NewDec(987654321, 0)}, {inf.NewDec(-1111111110, 0), inf.NewDec(-123456789, 0), inf.NewDec(-987654321, 0)}, {inf.NewDec(12, 2), inf.NewDec(1, 1), inf.NewDec(2, 2)}, } var decProdZZ = []decArgZZ{ {inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)}, {inf.NewDec(0, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)}, {inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(1, 0)}, {inf.NewDec(-991*991, 0), inf.NewDec(991, 0), inf.NewDec(-991, 0)}, {inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)}, {inf.NewDec(2, -3), inf.NewDec(1, -1), inf.NewDec(2, -2)}, {inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)}, } func TestDecSignZ(t *testing.T) { var zero inf.Dec for _, a := range decSumZZ { s := a.z.Sign() e := a.z.Cmp(&zero) if s != e { t.Errorf("got %d; want %d for z = %v", s, e, a.z) } } } func TestDecAbsZ(t *testing.T) { var zero inf.Dec for _, a := range decSumZZ { var z inf.Dec z.Abs(a.z) var e inf.Dec e.Set(a.z) if e.Cmp(&zero) < 0 { e.Sub(&zero, &e) } if z.Cmp(&e) != 0 { t.Errorf("got z = %v; want %v", z, e) } } } func testDecFunZZ(t *testing.T, msg string, f decFunZZ, a decArgZZ) { var z inf.Dec f(&z, a.x, a.y) if (&z).Cmp(a.z) != 0 { t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z) } } func TestDecSumZZ(t *testing.T) { AddZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Add(x, y) } SubZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Sub(x, y) } for _, a := range decSumZZ { arg := a testDecFunZZ(t, "AddZZ", AddZZ, arg) arg = decArgZZ{a.z, a.y, a.x} testDecFunZZ(t, "AddZZ symmetric", AddZZ, arg) arg = decArgZZ{a.x, a.z, a.y} testDecFunZZ(t, "SubZZ", SubZZ, arg) arg = decArgZZ{a.y, a.z, a.x} testDecFunZZ(t, "SubZZ symmetric", SubZZ, arg) } } func TestDecProdZZ(t *testing.T) { MulZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Mul(x, y) } for _, a := range decProdZZ { arg := a testDecFunZZ(t, "MulZZ", MulZZ, arg) arg = decArgZZ{a.z, a.y, a.x} testDecFunZZ(t, "MulZZ symmetric", MulZZ, arg) } } var decUnscaledTests = []struct { d *inf.Dec u int64 // ignored when ok == false ok bool }{ {new(inf.Dec), 0, true}, {inf.NewDec(-1<<63, 0), -1 << 63, true}, {inf.NewDec(-(-1<<63 + 1), 0), -(-1<<63 + 1), true}, {new(inf.Dec).Neg(inf.NewDec(-1<<63, 0)), 0, false}, {new(inf.Dec).Sub(inf.NewDec(-1<<63, 0), inf.NewDec(1, 0)), 0, false}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), 0, false}, } func TestDecUnscaled(t *testing.T) { for i, tt := range decUnscaledTests { u, ok := tt.d.Unscaled() if ok != tt.ok { t.Errorf("#%d Unscaled: got %v, expected %v", i, ok, tt.ok) } else if ok && u != tt.u { t.Errorf("#%d Unscaled: got %v, expected %v", i, u, tt.u) } } } var decRoundTests = [...]struct { in *inf.Dec s inf.Scale r inf.Rounder exp *inf.Dec }{ {inf.NewDec(123424999999999993, 15), 2, inf.RoundHalfUp, inf.NewDec(12342, 2)}, {inf.NewDec(123425000000000001, 15), 2, inf.RoundHalfUp, inf.NewDec(12343, 2)}, {inf.NewDec(123424999999999993, 15), 15, inf.RoundHalfUp, inf.NewDec(123424999999999993, 15)}, {inf.NewDec(123424999999999993, 15), 16, inf.RoundHalfUp, inf.NewDec(1234249999999999930, 16)}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -1, inf.RoundHalfUp, inf.NewDec(1844674407370955162, -1)}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -2, inf.RoundHalfUp, inf.NewDec(184467440737095516, -2)}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -3, inf.RoundHalfUp, inf.NewDec(18446744073709552, -3)}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -4, inf.RoundHalfUp, inf.NewDec(1844674407370955, -4)}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -5, inf.RoundHalfUp, inf.NewDec(184467440737096, -5)}, {inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -6, inf.RoundHalfUp, inf.NewDec(18446744073710, -6)}, } func TestDecRound(t *testing.T) { for i, tt := range decRoundTests { z := new(inf.Dec).Round(tt.in, tt.s, tt.r) if tt.exp.Cmp(z) != 0 { t.Errorf("#%d Round got %v; expected %v", i, z, tt.exp) } } } var decStringTests = []struct { in string out string val int64 scale inf.Scale // skip SetString if negative ok bool scanOk bool }{ {in: "", ok: false, scanOk: false}, {in: "a", ok: false, scanOk: false}, {in: "z", ok: false, scanOk: false}, {in: "+", ok: false, scanOk: false}, {in: "-", ok: false, scanOk: false}, {in: "g", ok: false, scanOk: false}, {in: ".", ok: false, scanOk: false}, {in: ".-0", ok: false, scanOk: false}, {in: ".+0", ok: false, scanOk: false}, // Scannable but not SetStringable {"0b", "ignored", 0, 0, false, true}, {"0x", "ignored", 0, 0, false, true}, {"0xg", "ignored", 0, 0, false, true}, {"0.0g", "ignored", 0, 1, false, true}, // examples from godoc for Dec {"0", "0", 0, 0, true, true}, {"0.00", "0.00", 0, 2, true, true}, {"ignored", "0", 0, -2, true, false}, {"1", "1", 1, 0, true, true}, {"1.00", "1.00", 100, 2, true, true}, {"10", "10", 10, 0, true, true}, {"ignored", "10", 1, -1, true, false}, // other tests {"+0", "0", 0, 0, true, true}, {"-0", "0", 0, 0, true, true}, {"0.0", "0.0", 0, 1, true, true}, {"0.1", "0.1", 1, 1, true, true}, {"0.", "0", 0, 0, true, true}, {"-10", "-10", -1, -1, true, true}, {"-1", "-1", -1, 0, true, true}, {"-0.1", "-0.1", -1, 1, true, true}, {"-0.01", "-0.01", -1, 2, true, true}, {"+0.", "0", 0, 0, true, true}, {"-0.", "0", 0, 0, true, true}, {".0", "0.0", 0, 1, true, true}, {"+.0", "0.0", 0, 1, true, true}, {"-.0", "0.0", 0, 1, true, true}, {"0.0000000000", "0.0000000000", 0, 10, true, true}, {"0.0000000001", "0.0000000001", 1, 10, true, true}, {"-0.0000000000", "0.0000000000", 0, 10, true, true}, {"-0.0000000001", "-0.0000000001", -1, 10, true, true}, {"-10", "-10", -10, 0, true, true}, {"+10", "10", 10, 0, true, true}, {"00", "0", 0, 0, true, true}, {"023", "23", 23, 0, true, true}, // decimal, not octal {"-02.3", "-2.3", -23, 1, true, true}, // decimal, not octal } func TestDecGetString(t *testing.T) { z := new(inf.Dec) for i, test := range decStringTests { if !test.ok { continue } z.SetUnscaled(test.val) z.SetScale(test.scale) s := z.String() if s != test.out { t.Errorf("#%da got %s; want %s", i, s, test.out) } s = fmt.Sprintf("%d", z) if s != test.out { t.Errorf("#%db got %s; want %s", i, s, test.out) } } } func TestDecSetString(t *testing.T) { tmp := new(inf.Dec) for i, test := range decStringTests { if test.scale < 0 { // SetString only supports scale >= 0 continue } // initialize to a non-zero value so that issues with parsing // 0 are detected tmp.Set(inf.NewDec(1234567890, 123)) n1, ok1 := new(inf.Dec).SetString(test.in) n2, ok2 := tmp.SetString(test.in) expected := inf.NewDec(test.val, test.scale) if ok1 != test.ok || ok2 != test.ok { t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok) continue } if !ok1 { if n1 != nil { t.Errorf("#%d (input '%s') n1 != nil", i, test.in) } continue } if !ok2 { if n2 != nil { t.Errorf("#%d (input '%s') n2 != nil", i, test.in) } continue } if n1.Cmp(expected) != 0 { t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val) } if n2.Cmp(expected) != 0 { t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val) } } } func TestDecScan(t *testing.T) { tmp := new(inf.Dec) for i, test := range decStringTests { if test.scale < 0 { // SetString only supports scale >= 0 continue } // initialize to a non-zero value so that issues with parsing // 0 are detected tmp.Set(inf.NewDec(1234567890, 123)) n1, n2 := new(inf.Dec), tmp nn1, err1 := fmt.Sscan(test.in, n1) nn2, err2 := fmt.Sscan(test.in, n2) if !test.scanOk { if err1 == nil || err2 == nil { t.Errorf("#%d (input '%s') ok incorrect, should be %t", i, test.in, test.scanOk) } continue } expected := inf.NewDec(test.val, test.scale) if nn1 != 1 || err1 != nil || nn2 != 1 || err2 != nil { t.Errorf("#%d (input '%s') error %d %v, %d %v", i, test.in, nn1, err1, nn2, err2) continue } if n1.Cmp(expected) != 0 { t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val) } if n2.Cmp(expected) != 0 { t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val) } } } var decScanNextTests = []struct { in string ok bool next rune }{ {"", false, 0}, {"a", false, 'a'}, {"z", false, 'z'}, {"+", false, 0}, {"-", false, 0}, {"g", false, 'g'}, {".", false, 0}, {".-0", false, '-'}, {".+0", false, '+'}, {"0b", true, 'b'}, {"0x", true, 'x'}, {"0xg", true, 'x'}, {"0.0g", true, 'g'}, } func TestDecScanNext(t *testing.T) { for i, test := range decScanNextTests { rdr := strings.NewReader(test.in) n1 := new(inf.Dec) nn1, _ := fmt.Fscan(rdr, n1) if (test.ok && nn1 == 0) || (!test.ok && nn1 > 0) { t.Errorf("#%d (input '%s') ok incorrect should be %t", i, test.in, test.ok) continue } r := rune(0) nn2, err := fmt.Fscanf(rdr, "%c", &r) if test.next != r { t.Errorf("#%d (input '%s') next incorrect, got %c should be %c, %d, %v", i, test.in, r, test.next, nn2, err) } } } var decGobEncodingTests = []string{ "0", "1", "2", "10", "42", "1234567890", "298472983472983471903246121093472394872319615612417471234712061", } func TestDecGobEncoding(t *testing.T) { var medium bytes.Buffer enc := gob.NewEncoder(&medium) dec := gob.NewDecoder(&medium) for i, test := range decGobEncodingTests { for j := 0; j < 2; j++ { for k := inf.Scale(-5); k <= 5; k++ { medium.Reset() // empty buffer for each test case (in case of failures) stest := test if j != 0 { // negative numbers stest = "-" + test } var tx inf.Dec tx.SetString(stest) tx.SetScale(k) // test with positive, negative, and zero scale if err := enc.Encode(&tx); err != nil { t.Errorf("#%d%c: encoding failed: %s", i, 'a'+j, err) } var rx inf.Dec if err := dec.Decode(&rx); err != nil { t.Errorf("#%d%c: decoding failed: %s", i, 'a'+j, err) } if rx.Cmp(&tx) != 0 { t.Errorf("#%d%c: transmission failed: got %s want %s", i, 'a'+j, &rx, &tx) } } } } } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/example_test.go ================================================ package inf_test import ( "fmt" "log" ) import "speter.net/go/exp/math/dec/inf" func ExampleDec_SetString() { d := new(inf.Dec) d.SetString("012345.67890") // decimal; leading 0 ignored; trailing 0 kept fmt.Println(d) // Output: 12345.67890 } func ExampleDec_Scan() { // The Scan function is rarely used directly; // the fmt package recognizes it as an implementation of fmt.Scanner. d := new(inf.Dec) _, err := fmt.Sscan("184467440.73709551617", d) if err != nil { log.Println("error scanning value:", err) } else { fmt.Println(d) } // Output: 184467440.73709551617 } func ExampleDec_QuoRound_scale2RoundDown() { // 10 / 3 is an infinite decimal; it has no exact Dec representation x, y := inf.NewDec(10, 0), inf.NewDec(3, 0) // use 2 digits beyond the decimal point, round towards 0 z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown) fmt.Println(z) // Output: 3.33 } func ExampleDec_QuoRound_scale2RoundCeil() { // -42 / 400 is an finite decimal with 3 digits beyond the decimal point x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0) // use 2 digits beyond decimal point, round towards positive infinity z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil) fmt.Println(z) // Output: -0.10 } func ExampleDec_QuoExact_ok() { // 1 / 25 is a finite decimal; it has exact Dec representation x, y := inf.NewDec(1, 0), inf.NewDec(25, 0) z := new(inf.Dec).QuoExact(x, y) fmt.Println(z) // Output: 0.04 } func ExampleDec_QuoExact_fail() { // 1 / 3 is an infinite decimal; it has no exact Dec representation x, y := inf.NewDec(1, 0), inf.NewDec(3, 0) z := new(inf.Dec).QuoExact(x, y) fmt.Println(z) // Output: } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/rounder.go ================================================ package inf import ( "math/big" ) // Rounder represents a method for rounding the (possibly infinite decimal) // result of a division to a finite Dec. It is used by Dec.Round() and // Dec.Quo(). // // See the Example for results of using each Rounder with some sample values. // type Rounder rounder // See http://speleotrove.com/decimal/damodel.html#refround for more detailed // definitions of these rounding modes. var ( RoundDown Rounder // towards 0 RoundUp Rounder // away from 0 RoundFloor Rounder // towards -infinity RoundCeil Rounder // towards +infinity RoundHalfDown Rounder // to nearest; towards 0 if same distance RoundHalfUp Rounder // to nearest; away from 0 if same distance RoundHalfEven Rounder // to nearest; even last digit if same distance ) // RoundExact is to be used in the case when rounding is not necessary. // When used with Quo or Round, it returns the result verbatim when it can be // expressed exactly with the given precision, and it returns nil otherwise. // QuoExact is a shorthand for using Quo with RoundExact. var RoundExact Rounder type rounder interface { // When UseRemainder() returns true, the Round() method is passed the // remainder of the division, expressed as the numerator and denominator of // a rational. UseRemainder() bool // Round sets the rounded value of a quotient to z, and returns z. // quo is rounded down (truncated towards zero) to the scale obtained from // the Scaler in Quo(). // // When the remainder is not used, remNum and remDen are nil. // When used, the remainder is normalized between -1 and 1; that is: // // -|remDen| < remNum < |remDen| // // remDen has the same sign as y, and remNum is zero or has the same sign // as x. Round(z, quo *Dec, remNum, remDen *big.Int) *Dec } type rndr struct { useRem bool round func(z, quo *Dec, remNum, remDen *big.Int) *Dec } func (r rndr) UseRemainder() bool { return r.useRem } func (r rndr) Round(z, quo *Dec, remNum, remDen *big.Int) *Dec { return r.round(z, quo, remNum, remDen) } var intSign = []*big.Int{big.NewInt(-1), big.NewInt(0), big.NewInt(1)} func roundHalf(f func(c int, odd uint) (roundUp bool)) func(z, q *Dec, rA, rB *big.Int) *Dec { return func(z, q *Dec, rA, rB *big.Int) *Dec { z.Set(q) brA, brB := rA.BitLen(), rB.BitLen() if brA < brB-1 { // brA < brB-1 => |rA| < |rB/2| return z } roundUp := false srA, srB := rA.Sign(), rB.Sign() s := srA * srB if brA == brB-1 { rA2 := new(big.Int).Lsh(rA, 1) if s < 0 { rA2.Neg(rA2) } roundUp = f(rA2.Cmp(rB)*srB, z.UnscaledBig().Bit(0)) } else { // brA > brB-1 => |rA| > |rB/2| roundUp = true } if roundUp { z.UnscaledBig().Add(z.UnscaledBig(), intSign[s+1]) } return z } } func init() { RoundExact = rndr{true, func(z, q *Dec, rA, rB *big.Int) *Dec { if rA.Sign() != 0 { return nil } return z.Set(q) }} RoundDown = rndr{false, func(z, q *Dec, rA, rB *big.Int) *Dec { return z.Set(q) }} RoundUp = rndr{true, func(z, q *Dec, rA, rB *big.Int) *Dec { z.Set(q) if rA.Sign() != 0 { z.UnscaledBig().Add(z.UnscaledBig(), intSign[rA.Sign()*rB.Sign()+1]) } return z }} RoundFloor = rndr{true, func(z, q *Dec, rA, rB *big.Int) *Dec { z.Set(q) if rA.Sign()*rB.Sign() < 0 { z.UnscaledBig().Add(z.UnscaledBig(), intSign[0]) } return z }} RoundCeil = rndr{true, func(z, q *Dec, rA, rB *big.Int) *Dec { z.Set(q) if rA.Sign()*rB.Sign() > 0 { z.UnscaledBig().Add(z.UnscaledBig(), intSign[2]) } return z }} RoundHalfDown = rndr{true, roundHalf( func(c int, odd uint) bool { return c > 0 })} RoundHalfUp = rndr{true, roundHalf( func(c int, odd uint) bool { return c >= 0 })} RoundHalfEven = rndr{true, roundHalf( func(c int, odd uint) bool { return c > 0 || c == 0 && odd == 1 })} } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/rounder_example_test.go ================================================ package inf_test import ( "fmt" "os" "text/tabwriter" "speter.net/go/exp/math/dec/inf" ) // This example displays the results of Dec.Round with each of the Rounders. // func ExampleRounder() { var vals = []struct { x string s inf.Scale }{ {"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1}, {"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1}, {"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1}, {"0.12", 1}, {"0.15", 1}, {"0.18", 1}, } var rounders = []struct { name string rounder inf.Rounder }{ {"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp}, {"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor}, {"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp}, {"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact}, } fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):\n") w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight) fmt.Fprint(w, "x\ts\t|\t") for _, r := range rounders { fmt.Fprintf(w, "%s\t", r.name[5:]) } fmt.Fprintln(w) for _, v := range vals { fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s) for _, r := range rounders { x, _ := new(inf.Dec).SetString(v.x) z := new(inf.Dec).Round(x, v.s, r.rounder) fmt.Fprintf(w, "%d\t", z) } fmt.Fprintln(w) } w.Flush() // Output: // The results of new(inf.Dec).Round(x, s, inf.RoundXXX): // // x s | Down Up Ceil Floor HalfDown HalfUp HalfEven Exact // -0.18 1 | -0.1 -0.2 -0.1 -0.2 -0.2 -0.2 -0.2 // -0.15 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.2 -0.2 // -0.12 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.1 -0.1 // -0.10 1 | -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 // -0.08 1 | 0.0 -0.1 0.0 -0.1 -0.1 -0.1 -0.1 // -0.05 1 | 0.0 -0.1 0.0 -0.1 0.0 -0.1 0.0 // -0.02 1 | 0.0 -0.1 0.0 -0.1 0.0 0.0 0.0 // 0.00 1 | 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 // 0.02 1 | 0.0 0.1 0.1 0.0 0.0 0.0 0.0 // 0.05 1 | 0.0 0.1 0.1 0.0 0.0 0.1 0.0 // 0.08 1 | 0.0 0.1 0.1 0.0 0.1 0.1 0.1 // 0.10 1 | 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 // 0.12 1 | 0.1 0.2 0.2 0.1 0.1 0.1 0.1 // 0.15 1 | 0.1 0.2 0.2 0.1 0.1 0.2 0.2 // 0.18 1 | 0.1 0.2 0.2 0.1 0.2 0.2 0.2 } ================================================ FILE: vendor/speter.net/go/exp/math/dec/inf/rounder_test.go ================================================ package inf_test import ( "math/big" "testing" "speter.net/go/exp/math/dec/inf" ) var decRounderInputs = [...]struct { quo *inf.Dec rA, rB *big.Int }{ // examples from go language spec {inf.NewDec(1, 0), big.NewInt(2), big.NewInt(3)}, // 5 / 3 {inf.NewDec(-1, 0), big.NewInt(-2), big.NewInt(3)}, // -5 / 3 {inf.NewDec(-1, 0), big.NewInt(2), big.NewInt(-3)}, // 5 / -3 {inf.NewDec(1, 0), big.NewInt(-2), big.NewInt(-3)}, // -5 / -3 // examples from godoc {inf.NewDec(-1, 1), big.NewInt(-8), big.NewInt(10)}, {inf.NewDec(-1, 1), big.NewInt(-5), big.NewInt(10)}, {inf.NewDec(-1, 1), big.NewInt(-2), big.NewInt(10)}, {inf.NewDec(0, 1), big.NewInt(-8), big.NewInt(10)}, {inf.NewDec(0, 1), big.NewInt(-5), big.NewInt(10)}, {inf.NewDec(0, 1), big.NewInt(-2), big.NewInt(10)}, {inf.NewDec(0, 1), big.NewInt(0), big.NewInt(1)}, {inf.NewDec(0, 1), big.NewInt(2), big.NewInt(10)}, {inf.NewDec(0, 1), big.NewInt(5), big.NewInt(10)}, {inf.NewDec(0, 1), big.NewInt(8), big.NewInt(10)}, {inf.NewDec(1, 1), big.NewInt(2), big.NewInt(10)}, {inf.NewDec(1, 1), big.NewInt(5), big.NewInt(10)}, {inf.NewDec(1, 1), big.NewInt(8), big.NewInt(10)}, } var decRounderResults = [...]struct { rounder inf.Rounder results [len(decRounderInputs)]*inf.Dec }{ {inf.RoundExact, [...]*inf.Dec{nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, inf.NewDec(0, 1), nil, nil, nil, nil, nil, nil}}, {inf.RoundDown, [...]*inf.Dec{ inf.NewDec(1, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(1, 0), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}}, {inf.RoundUp, [...]*inf.Dec{ inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, {inf.RoundHalfDown, [...]*inf.Dec{ inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1)}}, {inf.RoundHalfUp, [...]*inf.Dec{ inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, {inf.RoundHalfEven, [...]*inf.Dec{ inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0), inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, {inf.RoundFloor, [...]*inf.Dec{ inf.NewDec(1, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(1, 0), inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}}, {inf.RoundCeil, [...]*inf.Dec{ inf.NewDec(2, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(2, 0), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}}, } func TestDecRounders(t *testing.T) { for i, a := range decRounderResults { for j, input := range decRounderInputs { q := new(inf.Dec).Set(input.quo) rA, rB := new(big.Int).Set(input.rA), new(big.Int).Set(input.rB) res := a.rounder.Round(new(inf.Dec), q, rA, rB) if a.results[j] == nil && res == nil { continue } if (a.results[j] == nil && res != nil) || (a.results[j] != nil && res == nil) || a.results[j].Cmp(res) != 0 { t.Errorf("#%d,%d Rounder got %v; expected %v", i, j, res, a.results[j]) } } } } ================================================ FILE: version/VERSION ================================================ 0.3.1 ================================================ FILE: version/info.go ================================================ /* * Copyright 2016 Red Hat * * 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 version // Build information. Populated at build-time. var ( Version string Revision string Branch string BuildUser string BuildDate string GoVersion string ) // Map provides the iterable version information. var Map = map[string]string{ "version": Version, "revision": Revision, "branch": Branch, "buildUser": BuildUser, "buildDate": BuildDate, "goVersion": GoVersion, } ================================================ FILE: winrm/winrm.go ================================================ /* * Copyright 2016 Red Hat * * 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 winrm import ( "fmt" "io" "os" "strconv" "strings" "github.com/masterzen/winrm/winrm" "k8s.io/kubernetes/pkg/api" client "k8s.io/kubernetes/pkg/client/unversioned" "github.com/fabric8io/kansible/ansible" "github.com/fabric8io/kansible/log" ) // RemoteWinRmCommand runs the remote command on a windows machine func RemoteWinRmCommand(user string, password string, host string, port string, commandText string, c *client.Client, rc *api.ReplicationController, hostName string) error { portNumber, err := parsePortNumber(port) if err != nil { return err } log.Info("Connecting to windows host over WinRM on host %s and port %d with user %s with command `%s`", host, portNumber, user, commandText) client, err := winrm.NewClient(&winrm.Endpoint{Host: host, Port: portNumber, HTTPS: false, Insecure: false}, user, password) if err != nil { return fmt.Errorf("Could not create WinRM client: %s", err) } isBash := false isBashShellText := os.Getenv(ansible.EnvIsBashShell) if len(isBashShellText) > 0 && strings.ToLower(isBashShellText) == "true" { isBash = true } if rc.ObjectMeta.Annotations != nil && !isBash { oldShellID := rc.ObjectMeta.Annotations[ansible.WinRMShellAnnotationPrefix+hostName] if len(oldShellID) > 0 { // lets close the previously running shell on this machine log.Info("Closing the old WinRM Shell %s", oldShellID) shell := client.NewShell(oldShellID) err = shell.Close() if err != nil { log.Warn("Failed to close shell %s. Error: %s", oldShellID, err) } } } shell, err := client.CreateShell() if err != nil { return fmt.Errorf("Impossible to create WinRM shell: %s", err) } defer shell.Close() shellID := shell.ShellId log.Info("Created WinRM Shell %s", shellID) if rc != nil && c != nil && !isBash { rc.ObjectMeta.Annotations[ansible.WinRMShellAnnotationPrefix+hostName] = shellID _, err = c.ReplicationControllers(rc.ObjectMeta.Namespace).UpdateStatus(rc) if err != nil { return err } } var cmd *winrm.Command cmd, err = shell.Execute(commandText) if err != nil { return fmt.Errorf("Impossible to create Command %s\n", err) } go io.Copy(cmd.Stdin, os.Stdin) go io.Copy(os.Stdout, cmd.Stdout) go io.Copy(os.Stderr, cmd.Stderr) cmd.Wait() exitCode := cmd.ExitCode() if exitCode > 0 { return fmt.Errorf("Failed to run command '%s' got exit code %d", commandText, exitCode) } // TODO // return cmd.Error() return nil } // CloseShell closes the given WinRM Shell terminating any processes created within it func CloseShell(user string, password string, host string, port string, shellID string) error { portNumber, err := parsePortNumber(port) if err != nil { return err } client, err := winrm.NewClient(&winrm.Endpoint{Host: host, Port: portNumber, HTTPS: false, Insecure: false}, user, password) if err != nil { return fmt.Errorf("Could not create WinRM client: %s", err) } log.Info("Closing shell %s", shellID) shell := client.NewShell(shellID) return shell.Close() } func parsePortNumber(port string) (int, error) { portNumber, err := strconv.Atoi(port) if err != nil { return 0, fmt.Errorf("Failed to convert port number text `%s` to a number: %s", port, err) } return portNumber, nil }